diff --git a/webtorrent.chromeapp.js b/webtorrent.chromeapp.js index 910e5e389a..550e62b7f8 100644 --- a/webtorrent.chromeapp.js +++ b/webtorrent.chromeapp.js @@ -20,23 +20,23 @@ `).join("
"),html=getPageHTML(`${escapeHtml(torrent.name)} - WebTorrent`,`

${escapeHtml(torrent.name)}

    ${listHtml}
- `);res.end(html)}function serve404Page(){res.statusCode=404,res.setHeader("Content-Type","text/html");const html=getPageHTML("404 - Not Found","

404 - Not Found

");res.end(html)}function serveFile(file){res.statusCode=200,res.setHeader("Content-Type",mime.getType(file.name)||"application/octet-stream"),res.setHeader("Accept-Ranges","bytes"),res.setHeader("Content-Disposition",`inline; filename*=UTF-8''${encodeRFC5987(file.name)}`),res.setHeader("transferMode.dlna.org","Streaming"),res.setHeader("contentFeatures.dlna.org","DLNA.ORG_OP=01;DLNA.ORG_CI=0;DLNA.ORG_FLAGS=01700000000000000000000000000000");let range=rangeParser(file.length,req.headers.range||"");return Array.isArray(range)?(res.statusCode=206,range=range[0],res.setHeader("Content-Range",`bytes ${range.start}-${range.end}/${file.length}`),res.setHeader("Content-Length",range.end-range.start+1)):(range=null,res.setHeader("Content-Length",file.length)),"HEAD"===req.method?res.end():void pump(file.createReadStream(range),res)}function serveMethodNotAllowed(){res.statusCode=405,res.setHeader("Content-Type","text/html");const html=getPageHTML("405 - Method Not Allowed","

405 - Method Not Allowed

");res.end(html)}if(opts.hostname&&`${opts.hostname}:${server.address().port}`!==req.headers.host)return req.destroy();const pathname=new URL(req.url,"http://example.com").pathname;return isOriginAllowed(req)&&res.setHeader("Access-Control-Allow-Origin",req.headers.origin),res.setHeader("X-Content-Type-Options","nosniff"),res.setHeader("Content-Security-Policy","base-uri 'none'; default-src 'none'; frame-ancestors 'none'; form-action 'none';"),"/favicon.ico"===pathname?serve404Page():"OPTIONS"===req.method?isOriginAllowed(req)?function(){res.statusCode=204,res.setHeader("Access-Control-Max-Age","600"),res.setHeader("Access-Control-Allow-Methods","GET,HEAD"),req.headers["access-control-request-headers"]&&res.setHeader("Access-Control-Allow-Headers",req.headers["access-control-request-headers"]),res.end()}():serveMethodNotAllowed():"GET"===req.method||"HEAD"===req.method?void(torrent.ready?handleRequest():(pendingReady.push(onReady),torrent.once("ready",onReady))):serveMethodNotAllowed()}const server=http.createServer();opts.origin||(opts.origin="*");const sockets=[],pendingReady=[];let closed=!1;const _listen=server.listen,_close=server.close;return server.listen=(...args)=>(closed=!1,server.on("connection",onConnection),server.on("request",onRequest),_listen.apply(server,args)),server.close=cb=>{for(closed=!0,server.removeListener("connection",onConnection),server.removeListener("request",onRequest);pendingReady.length;){const onReady=pendingReady.pop();torrent.removeListener("ready",onReady)}_close.call(server,cb)},server.destroy=cb=>{sockets.forEach(socket=>{socket.destroy()}),cb||(cb=()=>{}),closed?process.nextTick(cb):server.close(cb),torrent=null},server}}).call(this)}).call(this,require("_process"))},{_process:132,"escape-html":77,http:92,mime:116,pump:133,"range-parser":141,"unordered-array-remove":191}],7:[function(require,module){(function(process,global){(function(){function getBlockPipelineLength(wire,duration){return 2+_Mathceil(duration*wire.downloadSpeed()/Piece.BLOCK_LENGTH)}function getPiecePipelineLength(wire,duration,pieceLength){return 1+_Mathceil(duration*wire.downloadSpeed()/pieceLength)}function randomInt(high){return 0|Math.random()*high}function noop(){}const addrToIPPort=require("addr-to-ip-port"),BitField=require("bitfield").default,ChunkStoreWriteStream=require("chunk-store-stream/write"),debug=require("debug")("webtorrent:torrent"),Discovery=require("torrent-discovery"),EventEmitter=require("events").EventEmitter,fs=require("fs"),FSChunkStore=require("fs-chunk-store"),get=require("simple-get"),ImmediateChunkStore=require("immediate-chunk-store"),MultiStream=require("multistream"),net=require("net"),os=require("os"),parallel=require("run-parallel"),parallelLimit=require("run-parallel-limit"),parseTorrent=require("parse-torrent"),path=require("path"),Piece=require("torrent-piece"),pump=require("pump"),randomIterate=require("random-iterate"),sha1=require("simple-sha1"),speedometer=require("speedometer"),utMetadata=require("ut_metadata"),utPex=require("ut_pex"),utp=require("utp-native"),File=require("./file"),Peer=require("./peer"),RarityMap=require("./rarity-map"),Server=require("./server"),CHOKE_TIMEOUT=5e3,SPEED_THRESHOLD=3*Piece.BLOCK_LENGTH,PIPELINE_MAX_DURATION=1,FILESYSTEM_CONCURRENCY=process.browser?1/0:2,RECONNECT_WAIT=[1e3,5e3,15e3],VERSION=require("../package.json").version,USER_AGENT=`WebTorrent/${VERSION} (https://webtorrent.io)`;let TMP;try{TMP=path.join(fs.statSync("/tmp")&&"/tmp","webtorrent")}catch(err){TMP=path.join("function"==typeof os.tmpdir?os.tmpdir():"/","webtorrent")}class Torrent extends EventEmitter{constructor(torrentId,client,opts){super(),this._debugId="unknown infohash",this.client=client,this.announce=opts.announce,this.urlList=opts.urlList,this.path=opts.path,this.skipVerify=!!opts.skipVerify,this._store=opts.store||FSChunkStore,this._getAnnounceOpts=opts.getAnnounceOpts,"boolean"==typeof opts.private&&(this.private=opts.private),this.strategy=opts.strategy||"sequential",this.maxWebConns=opts.maxWebConns||4,this._rechokeNumSlots=!1===opts.uploads||0===opts.uploads?0:+opts.uploads||10,this._rechokeOptimisticWire=null,this._rechokeOptimisticTime=0,this._rechokeIntervalId=null,this.ready=!1,this.destroyed=!1,this.paused=!1,this.done=!1,this.metadata=null,this.store=null,this.files=[],this.pieces=[],this._amInterested=!1,this._selections=[],this._critical=[],this.wires=[],this._queue=[],this._peers={},this._peersLength=0,this.received=0,this.uploaded=0,this._downloadSpeed=speedometer(),this._uploadSpeed=speedometer(),this._servers=[],this._xsRequests=[],this._fileModtimes=opts.fileModtimes,null!==torrentId&&this._onTorrentId(torrentId),this._debug("new torrent")}get timeRemaining(){return this.done?0:0===this.downloadSpeed?1/0:1e3*((this.length-this.downloaded)/this.downloadSpeed)}get downloaded(){if(!this.bitfield)return 0;let downloaded=0;for(let index=0,len=this.pieces.length;index{this.destroyed||this._onParsedTorrent(parsedTorrent)})):parseTorrent.remote(torrentId,(err,parsedTorrent)=>this.destroyed?void 0:err?this._destroy(err):void this._onParsedTorrent(parsedTorrent))}_onParsedTorrent(parsedTorrent){if(!this.destroyed){if(this._processParsedTorrent(parsedTorrent),!this.infoHash)return this._destroy(new Error("Malformed torrent data: No info hash"));(this.path||(this.path=path.join(TMP,this.infoHash)),this._rechokeIntervalId=setInterval(()=>{this._rechoke()},1e4),this._rechokeIntervalId.unref&&this._rechokeIntervalId.unref(),this.emit("_infoHash",this.infoHash),!this.destroyed)&&(this.emit("infoHash",this.infoHash),this.destroyed||(this.client.listening?this._onListening():this.client.once("listening",()=>{this._onListening()})))}}_processParsedTorrent(parsedTorrent){this._debugId=parsedTorrent.infoHash.toString("hex").substring(0,7),"undefined"!=typeof this.private&&(parsedTorrent.private=this.private),this.announce&&(parsedTorrent.announce=parsedTorrent.announce.concat(this.announce)),this.client.tracker&&global.WEBTORRENT_ANNOUNCE&&!parsedTorrent.private&&(parsedTorrent.announce=parsedTorrent.announce.concat(global.WEBTORRENT_ANNOUNCE)),this.urlList&&(parsedTorrent.urlList=parsedTorrent.urlList.concat(this.urlList)),parsedTorrent.announce=Array.from(new Set(parsedTorrent.announce)),parsedTorrent.urlList=Array.from(new Set(parsedTorrent.urlList)),Object.assign(this,parsedTorrent),this.magnetURI=parseTorrent.toMagnetURI(parsedTorrent),this.torrentFile=parseTorrent.toTorrentFile(parsedTorrent)}_onListening(){this.destroyed||(this.info?this._onMetadata(this):(this.xs&&this._getMetadataFromServer(),this._startDiscovery()))}_startDiscovery(){if(this.discovery||this.destroyed)return;let trackerOpts=this.client.tracker;trackerOpts&&(trackerOpts=Object.assign({},this.client.tracker,{getAnnounceOpts:()=>{const opts={uploaded:this.uploaded,downloaded:this.downloaded,left:_Mathmax(this.length-this.downloaded,0)};return this.client.tracker.getAnnounceOpts&&Object.assign(opts,this.client.tracker.getAnnounceOpts()),this._getAnnounceOpts&&Object.assign(opts,this._getAnnounceOpts()),opts}})),this.peerAddresses&&this.peerAddresses.forEach(peer=>this.addPeer(peer)),this.discovery=new Discovery({infoHash:this.infoHash,announce:this.announce,peerId:this.client.peerId,dht:!this.private&&this.client.dht,tracker:trackerOpts,port:this.client.torrentPort,userAgent:USER_AGENT,lsd:this.client.lsd}),this.discovery.on("error",err=>{this._destroy(err)}),this.discovery.on("peer",(peer,source)=>{this._debug("peer %s discovered via %s",peer,source);"string"==typeof peer&&this.done||this.addPeer(peer)}),this.discovery.on("trackerAnnounce",()=>{this.emit("trackerAnnounce"),0===this.numPeers&&this.emit("noPeers","tracker")}),this.discovery.on("dhtAnnounce",()=>{this.emit("dhtAnnounce"),0===this.numPeers&&this.emit("noPeers","dht")}),this.discovery.on("warning",err=>{this.emit("warning",err)})}_getMetadataFromServer(){function getMetadataFromURL(url,cb){function onResponse(err,res,torrent){if(self.destroyed)return cb(null);if(self.metadata)return cb(null);if(err)return self.emit("warning",new Error(`http error from xs param: ${url}`)),cb(null);if(200!==res.statusCode)return self.emit("warning",new Error(`non-200 status code ${res.statusCode} from xs param: ${url}`)),cb(null);let parsedTorrent;try{parsedTorrent=parseTorrent(torrent)}catch(err){}return parsedTorrent?parsedTorrent.infoHash===self.infoHash?void(self._onMetadata(parsedTorrent),cb(null)):(self.emit("warning",new Error(`got torrent file with incorrect info hash from xs param: ${url}`)),cb(null)):(self.emit("warning",new Error(`got invalid torrent file from xs param: ${url}`)),cb(null))}if(0!==url.indexOf("http://")&&0!==url.indexOf("https://"))return self.emit("warning",new Error(`skipping non-http xs param: ${url}`)),cb(null);let req;try{req=get.concat({url,method:"GET",headers:{"user-agent":USER_AGENT}},onResponse)}catch(err){return self.emit("warning",new Error(`skipping invalid url xs param: ${url}`)),cb(null)}self._xsRequests.push(req)}const self=this,urls=Array.isArray(this.xs)?this.xs:[this.xs],tasks=urls.map(url=>cb=>{getMetadataFromURL(url,cb)});parallel(tasks)}_onMetadata(metadata){if(this.metadata||this.destroyed)return;this._debug("got metadata"),this._xsRequests.forEach(req=>{req.abort()}),this._xsRequests=[];let parsedTorrent;if(metadata&&metadata.infoHash)parsedTorrent=metadata;else try{parsedTorrent=parseTorrent(metadata)}catch(err){return this._destroy(err)}if(this._processParsedTorrent(parsedTorrent),this.metadata=this.torrentFile,this.client.enableWebSeeds&&this.urlList.forEach(url=>{this.addWebSeed(url)}),this._rarityMap=new RarityMap(this),this.store=new ImmediateChunkStore(new this._store(this.pieceLength,{torrent:{infoHash:this.infoHash},files:this.files.map(file=>({path:path.join(this.path,file.path),length:file.length,offset:file.offset})),length:this.length,name:this.infoHash})),this.files=this.files.map(file=>new File(this,file)),this.so?this.files.forEach((v,i)=>{this.so.includes(i)?this.files[i].select():this.files[i].deselect()}):0!==this.pieces.length&&this.select(0,this.pieces.length-1,!1),this._hashes=this.pieces,this.pieces=this.pieces.map((hash,i)=>{const pieceLength=i===this.pieces.length-1?this.lastPieceLength:this.pieceLength;return new Piece(pieceLength)}),this._reservations=this.pieces.map(()=>[]),this.bitfield=new BitField(this.pieces.length),this.wires.forEach(wire=>{wire.ut_metadata&&wire.ut_metadata.setMetadata(this.metadata),this._onWireWithMetadata(wire)}),this.emit("metadata"),!this.destroyed)if(this.skipVerify)this._markAllVerified(),this._onStore();else{const onPiecesVerified=err=>err?this._destroy(err):void(this._debug("done verifying"),this._onStore());this._debug("verifying existing torrent data"),this._fileModtimes&&this._store===FSChunkStore?this.getFileModtimes((err,fileModtimes)=>{if(err)return this._destroy(err);const unchanged=this.files.map((_,index)=>fileModtimes[index]===this._fileModtimes[index]).every(x=>x);unchanged?(this._markAllVerified(),this._onStore()):this._verifyPieces(onPiecesVerified)}):this._verifyPieces(onPiecesVerified)}}getFileModtimes(cb){const ret=[];parallelLimit(this.files.map((file,index)=>cb=>{fs.stat(path.join(this.path,file.path),(err,stat)=>err&&"ENOENT"!==err.code?cb(err):void(ret[index]=stat&&stat.mtime.getTime(),cb(null)))}),FILESYSTEM_CONCURRENCY,err=>{this._debug("done getting file modtimes"),cb(err,ret)})}_verifyPieces(cb){parallelLimit(this.pieces.map((piece,index)=>cb=>this.destroyed?cb(new Error("torrent is destroyed")):void this.store.get(index,(err,buf)=>this.destroyed?cb(new Error("torrent is destroyed")):err?process.nextTick(cb,null):void sha1(buf,hash=>{if(this.destroyed)return cb(new Error("torrent is destroyed"));if(hash===this._hashes[index]){if(!this.pieces[index])return cb(null);this._debug("piece verified %s",index),this._markVerified(index)}else this._debug("piece invalid %s",index);cb(null)}))),FILESYSTEM_CONCURRENCY,cb)}rescanFiles(cb){if(this.destroyed)throw new Error("torrent is destroyed");cb||(cb=noop),this._verifyPieces(err=>err?(this._destroy(err),cb(err)):void(this._checkDone(),cb(null)))}_markAllVerified(){for(let index=0;index{req.abort()}),this._rarityMap&&this._rarityMap.destroy(),this._peers)this.removePeer(id);this.files.forEach(file=>{file instanceof File&&file._destroy()});const tasks=this._servers.map(server=>cb=>{server.destroy(cb)});this.discovery&&tasks.push(cb=>{this.discovery.destroy(cb)}),this.store&&tasks.push(cb=>{opts&&opts.destroyStore?this.store.destroy(cb):this.store.close(cb)}),parallel(tasks,cb),err&&(0===this.listenerCount("error")?this.client.emit("error",err):this.emit("error",err)),this.emit("close"),this.client=null,this.files=[],this.discovery=null,this.store=null,this._rarityMap=null,this._peers=null,this._servers=null,this._xsRequests=null}}addPeer(peer){if(this.destroyed)throw new Error("torrent is destroyed");if(!this.infoHash)throw new Error("addPeer() must not be called before the `infoHash` event");if(this.client.blocked){let host;if("string"==typeof peer){let parts;try{parts=addrToIPPort(peer)}catch(e){return this._debug("ignoring peer: invalid %s",peer),this.emit("invalidPeer",peer),!1}host=parts[0]}else"string"==typeof peer.remoteAddress&&(host=peer.remoteAddress);if(host&&this.client.blocked.contains(host))return this._debug("ignoring peer: blocked %s",peer),"string"!=typeof peer&&peer.destroy(),this.emit("blockedPeer",peer),!1}const wasAdded=!!this._addPeer(peer,this.client.utp?"utp":"tcp");return wasAdded?this.emit("peer",peer):this.emit("invalidPeer",peer),wasAdded}_addPeer(peer,type){if(this.destroyed)return"string"!=typeof peer&&peer.destroy(),null;if("string"==typeof peer&&!this._validAddr(peer))return this._debug("ignoring peer: invalid %s",peer),null;const id=peer&&peer.id||peer;if(this._peers[id])return this._debug("ignoring peer: duplicate (%s)",id),"string"!=typeof peer&&peer.destroy(),null;if(this.paused)return this._debug("ignoring peer: torrent is paused"),"string"!=typeof peer&&peer.destroy(),null;this._debug("add peer %s",id);let newPeer;return newPeer="string"==typeof peer?"utp"===type?Peer.createUTPOutgoingPeer(peer,this):Peer.createTCPOutgoingPeer(peer,this):Peer.createWebRTCPeer(peer,this),this._peers[newPeer.id]=newPeer,this._peersLength+=1,"string"==typeof peer&&(this._queue.push(newPeer),this._drain()),newPeer}addWebSeed(url){if(this.destroyed)throw new Error("torrent is destroyed");if(!/^https?:\/\/.+/.test(url))return this.emit("warning",new Error(`ignoring invalid web seed: ${url}`)),void this.emit("invalidPeer",url);if(this._peers[url])return this.emit("warning",new Error(`ignoring duplicate web seed: ${url}`)),void this.emit("invalidPeer",url);this._debug("add web seed %s",url);const newPeer=Peer.createWebSeedPeer(url,this);this._peers[newPeer.id]=newPeer,this._peersLength+=1,this.emit("peer",url)}_addIncomingPeer(peer){return this.destroyed?peer.destroy(new Error("torrent is destroyed")):this.paused?peer.destroy(new Error("torrent is paused")):void(this._debug("add incoming peer %s",peer.id),this._peers[peer.id]=peer,this._peersLength+=1)}removePeer(peer){const id=peer&&peer.id||peer;peer=this._peers[id];peer&&(this._debug("removePeer %s",id),delete this._peers[id],this._peersLength-=1,peer.destroy(),this._drain())}select(start,end,priority,notify){if(this.destroyed)throw new Error("torrent is destroyed");if(0>start||endb.priority-a.priority),this._updateSelections()}deselect(start,end,priority){if(this.destroyed)throw new Error("torrent is destroyed");priority=+priority||0,this._debug("deselect %s-%s (priority %s)",start,end,priority);for(let i=0;i{this.destroyed||(this.received+=downloaded,this._downloadSpeed(downloaded),this.client._downloadSpeed(downloaded),this.emit("download",downloaded),this.destroyed||this.client.emit("download",downloaded))}),wire.on("upload",uploaded=>{this.destroyed||(this.uploaded+=uploaded,this._uploadSpeed(uploaded),this.client._uploadSpeed(uploaded),this.emit("upload",uploaded),this.destroyed||this.client.emit("upload",uploaded))}),this.wires.push(wire),addr){const parts=addrToIPPort(addr);wire.remoteAddress=parts[0],wire.remotePort=parts[1]}this.client.dht&&this.client.dht.listening&&wire.on("port",port=>this.destroyed||this.client.dht.destroyed?void 0:wire.remoteAddress?0===port||65536{this._debug("wire timeout (%s)",addr),wire.destroy()}),wire.setTimeout(3e4,!0),wire.setKeepAlive(!0),wire.use(utMetadata(this.metadata)),wire.ut_metadata.on("warning",err=>{this._debug("ut_metadata warning: %s",err.message)}),this.metadata||(wire.ut_metadata.on("metadata",metadata=>{this._debug("got metadata via ut_metadata"),this._onMetadata(metadata)}),wire.ut_metadata.fetch()),"function"!=typeof utPex||this.private||(wire.use(utPex()),wire.ut_pex.on("peer",peer=>{this.done||(this._debug("ut_pex: got peer: %s (from %s)",peer,addr),this.addPeer(peer))}),wire.ut_pex.on("dropped",peer=>{const peerObj=this._peers[peer];peerObj&&!peerObj.connected&&(this._debug("ut_pex: dropped peer: %s (from %s)",peer,addr),this.removePeer(peer))}),wire.once("close",()=>{wire.ut_pex.reset()})),this.emit("wire",wire,addr),this.metadata&&process.nextTick(()=>{this._onWireWithMetadata(wire)})}_onWireWithMetadata(wire){let timeoutId=null;const onChokeTimeout=()=>{this.destroyed||wire.destroyed||(this._numQueued>2*(this._numConns-this.numPeers)&&wire.amInterested?wire.destroy():(timeoutId=setTimeout(onChokeTimeout,CHOKE_TIMEOUT),timeoutId.unref&&timeoutId.unref()))};let i;const updateSeedStatus=()=>{if(wire.peerPieces.buffer.length===this.bitfield.buffer.length){for(i=0;i{updateSeedStatus(),this._update(),this._updateWireInterest(wire)}),wire.on("have",()=>{updateSeedStatus(),this._update(),this._updateWireInterest(wire)}),wire.once("interested",()=>{wire.unchoke()}),wire.once("close",()=>{clearTimeout(timeoutId)}),wire.on("choke",()=>{clearTimeout(timeoutId),timeoutId=setTimeout(onChokeTimeout,CHOKE_TIMEOUT),timeoutId.unref&&timeoutId.unref()}),wire.on("unchoke",()=>{clearTimeout(timeoutId),this._update()}),wire.on("request",(index,offset,length,cb)=>length>131072?wire.destroy():void(this.pieces[index]||this.store.get(index,{offset,length},cb))),wire.bitfield(this.bitfield),this._updateWireInterest(wire),wire.peerExtensions.dht&&this.client.dht&&this.client.dht.listening&&wire.port(this.client.dht.address().port),"webSeed"!==wire.type&&(timeoutId=setTimeout(onChokeTimeout,CHOKE_TIMEOUT),timeoutId.unref&&timeoutId.unref()),wire.isSeeder=!1,updateSeedStatus()}_updateSelections(){!this.ready||this.destroyed||(process.nextTick(()=>{this._gcSelections()}),this._updateInterest(),this._update())}_gcSelections(){for(let i=0;ithis._updateWireInterest(wire));prev===this._amInterested||(this._amInterested?this.emit("interested"):this.emit("uninterested"))}_updateWireInterest(wire){let interested=!1;for(let index=0;indexi>=start&&i<=end&&!(i in tried)&&wire.peerPieces.get(i)&&(!rank||rank(i))}function speedRanker(){const speed=wire.downloadSpeed()||1;if(speed>SPEED_THRESHOLD)return()=>!0;const secs=_Mathmax(1,wire.requests.length)*Piece.BLOCK_LENGTH/speed;let tries=10,ptr=0;return index=>{if(!tries||self.bitfield.get(index))return!0;for(let missing=self.pieces[index].missing;ptr=maxOutstandingRequests)return!0;const rank=speedRanker();for(let i=0;ipiece));){for(;self._request(wire,piece,self._critical[piece]||hotswap););if(wire.requests.lengthpiece));){if(self._request(wire,piece,!1))return;tried[piece]=!0,tries+=1}}else for(piece=next.to;piece>=next.from+next.offset;--piece)if(wire.peerPieces.get(piece)&&self._request(wire,piece,!1))return}}();const minOutstandingRequests=getBlockPipelineLength(wire,.5);if(wire.requests.length>=minOutstandingRequests)return;const maxOutstandingRequests=getBlockPipelineLength(wire,PIPELINE_MAX_DURATION);trySelectWire(!1)||trySelectWire(!0)}_rechoke(){if(this.ready){const wireStack=this.wires.map(wire=>({wire,random:Math.random()})).sort((objA,objB)=>{const wireA=objA.wire,wireB=objB.wire;return wireA.downloadSpeed()===wireB.downloadSpeed()?wireA.uploadSpeed()===wireB.uploadSpeed()?wireA.amChoking===wireB.amChoking?objA.random-objB.random:wireA.amChoking?-1:1:wireA.uploadSpeed()-wireB.uploadSpeed():wireA.downloadSpeed()-wireB.downloadSpeed()}).map(obj=>obj.wire);0>=this._rechokeOptimisticTime?this._rechokeOptimisticWire=null:this._rechokeOptimisticTime-=1;for(let numInterestedUnchoked=0;0wire.peerInterested);if(0wire!==this._rechokeOptimisticWire).forEach(wire=>wire.choke())}}_hotswap(wire,index){const speed=wire.downloadSpeed();if(speed=SPEED_THRESHOLD||2*otherSpeed>speed||otherSpeed>minSpeed||(minWire=otherWire,minSpeed=otherSpeed)}if(!minWire)return!1;for(i=0;i{self._update()})}const self=this,numRequests=wire.requests.length,isWebSeed="webSeed"===wire.type;if(self.bitfield.get(index))return!1;const maxOutstandingRequests=isWebSeed?_Mathmin(getPiecePipelineLength(wire,PIPELINE_MAX_DURATION,self.pieceLength),self.maxWebConns):getBlockPipelineLength(wire,PIPELINE_MAX_DURATION);if(numRequests>=maxOutstandingRequests)return!1;const piece=self.pieces[index];let reservation=isWebSeed?piece.reserveRemaining():piece.reserve();if(-1===reservation&&hotswap&&self._hotswap(wire,index)&&(reservation=isWebSeed?piece.reserveRemaining():piece.reserve()),-1===reservation)return!1;let r=self._reservations[index];r||(r=self._reservations[index]=[]);let i=r.indexOf(null);-1===i&&(i=r.length),r[i]=wire;const chunkOffset=piece.chunkOffset(reservation),chunkLength=isWebSeed?piece.chunkLengthRemaining(reservation):piece.chunkLength(reservation);return wire.request(index,chunkOffset,chunkLength,function onChunk(err,chunk){if(self.destroyed)return;if(!self.ready)return self.once("ready",()=>{onChunk(err,chunk)});if(r[i]===wire&&(r[i]=null),piece!==self.pieces[index])return onUpdateTick();if(err)return self._debug("error getting piece %s (offset: %s length: %s) from %s: %s",index,chunkOffset,chunkLength,`${wire.remoteAddress}:${wire.remotePort}`,err.message),isWebSeed?piece.cancelRemaining(reservation):piece.cancel(reservation),void onUpdateTick();if(self._debug("got piece %s (offset: %s length: %s) from %s",index,chunkOffset,chunkLength,`${wire.remoteAddress}:${wire.remotePort}`),!piece.set(reservation,chunk,wire))return onUpdateTick();const buf=piece.flush();sha1(buf,hash=>{if(!self.destroyed){if(hash===self._hashes[index]){if(!self.pieces[index])return;self._debug("piece verified %s",index),self.pieces[index]=null,self._reservations[index]=null,self.bitfield.set(index,!0),self.store.put(index,buf),self.wires.forEach(wire=>{wire.have(index)}),self._checkDone()&&!self.destroyed&&self.discovery.complete()}else self.pieces[index]=new Piece(piece.length),self.emit("warning",new Error(`Piece ${index} failed verification`));onUpdateTick()}})}),!0}_checkDone(){if(this.destroyed)return;this.files.forEach(file=>{if(!file.done){for(let i=file._startPiece;i<=file._endPiece;++i)if(!this.bitfield.get(i))return;file.done=!0,file.emit("done"),this._debug(`file done: ${file.name}`)}});let done=!0;for(let i=0;i{this.load(streams,cb)});Array.isArray(streams)||(streams=[streams]),cb||(cb=noop);const readable=new MultiStream(streams),writable=new ChunkStoreWriteStream(this.store,this.pieceLength);pump(readable,writable,err=>err?cb(err):void(this._markAllVerified(),this._checkDone(),cb(null)))}createServer(requestListener){if("function"!=typeof Server)throw new Error("node.js-only method");if(this.destroyed)throw new Error("torrent is destroyed");const server=new Server(this,requestListener);return this._servers.push(server),server}pause(){this.destroyed||(this._debug("pause"),this.paused=!0)}resume(){this.destroyed||(this._debug("resume"),this.paused=!1,this._drain())}_debug(){const args=[].slice.call(arguments);args[0]=`[${this.client?this.client._debugId:"No Client"}] [${this._debugId}] ${args[0]}`,debug(...args)}_drain(){if(this._debug("_drain numConns %s maxConns %s",this._numConns,this.client.maxConns),"function"!=typeof net.connect||this.destroyed||this.paused||this._numConns>=this.client.maxConns)return;this._debug("drain (%s queued, %s/%s peers)",this._numQueued,this.numPeers,this.client.maxConns);const peer=this._queue.shift();if(!peer)return;this._debug("%s connect attempt to %s",peer.type,peer.addr);const parts=addrToIPPort(peer.addr),opts={host:parts[0],port:parts[1]};peer.conn="utpOutgoing"===peer.type?utp.connect(opts.port,opts.host):net.connect(opts);const conn=peer.conn;conn.once("connect",()=>{peer.onConnect()}),conn.once("error",err=>{peer.destroy(err)}),peer.startConnectTimeout(),conn.on("close",()=>{if(!this.destroyed){if(peer.retries>=RECONNECT_WAIT.length){if(this.client.utp){const newPeer=this._addPeer(peer.addr,"tcp");newPeer&&(newPeer.retries=0)}else this._debug("conn %s closed: will not re-add (max %s attempts)",peer.addr,RECONNECT_WAIT.length);return}const ms=RECONNECT_WAIT[peer.retries];this._debug("conn %s closed: will re-add to queue in %sms (attempt %s)",peer.addr,ms,peer.retries+1);const reconnectTimeout=setTimeout(()=>{if(!this.destroyed){const newPeer=this._addPeer(peer.addr,this.client.utp?"utp":"tcp");newPeer&&(newPeer.retries=peer.retries+1)}},ms);reconnectTimeout.unref&&reconnectTimeout.unref()}})}_validAddr(addr){let parts;try{parts=addrToIPPort(addr)}catch(e){return!1}const host=parts[0],port=parts[1];return 0port&&("127.0.0.1"!==host||port!==this.client.torrentPort)}}module.exports=Torrent}).call(this)}).call(this,require("_process"),"undefined"==typeof global?"undefined"==typeof self?"undefined"==typeof window?{}:window:self:global)},{"../package.json":202,"./file":3,"./peer":4,"./rarity-map":5,"./server":6,_process:132,"addr-to-ip-port":9,bitfield:22,"chunk-store-stream/write":66,debug:69,events:39,fs:37,"fs-chunk-store":114,"immediate-chunk-store":96,multistream:126,net:65,os:36,"parse-torrent":130,path:40,pump:133,"random-iterate":139,"run-parallel":162,"run-parallel-limit":161,"simple-get":167,"simple-sha1":169,speedometer:172,"torrent-discovery":187,"torrent-piece":188,ut_metadata:194,ut_pex:195,"utp-native":36}],8:[function(require,module){(function(Buffer){(function(){const BitField=require("bitfield").default,debug=require("debug")("webtorrent:webconn"),get=require("simple-get"),sha1=require("simple-sha1"),Wire=require("bittorrent-protocol"),VERSION=require("../package.json").version;module.exports=class WebConn extends Wire{constructor(url,torrent){super(),this.url=url,this.webPeerId=sha1.sync(url),this._torrent=torrent,this._init()}_init(){this.setKeepAlive(!0),this.once("handshake",infoHash=>{if(this.destroyed)return;this.handshake(infoHash,this.webPeerId);const numPieces=this._torrent.pieces.length,bitfield=new BitField(numPieces);for(let i=0;i<=numPieces;i++)bitfield.set(i,!0);this.bitfield(bitfield)}),this.once("interested",()=>{debug("interested"),this.unchoke()}),this.on("uninterested",()=>{debug("uninterested")}),this.on("choke",()=>{debug("choke")}),this.on("unchoke",()=>{debug("unchoke")}),this.on("bitfield",()=>{debug("bitfield")}),this.on("request",(pieceIndex,offset,length,callback)=>{debug("request pieceIndex=%d offset=%d length=%d",pieceIndex,offset,length),this.httpRequest(pieceIndex,offset,length,callback)})}httpRequest(pieceIndex,offset,length,cb){const pieceOffset=pieceIndex*this._torrent.pieceLength,rangeStart=pieceOffset+offset,rangeEnd=rangeStart+length-1,files=this._torrent.files;let requests;if(1>=files.length)requests=[{url:this.url,start:rangeStart,end:rangeEnd}];else{const requestedFiles=files.filter(file=>file.offset<=rangeEnd&&file.offset+file.length>rangeStart);if(1>requestedFiles.length)return cb(new Error("Could not find file corresponnding to web seed range request"));requests=requestedFiles.map(requestedFile=>{const fileEnd=requestedFile.offset+requestedFile.length-1,url=this.url+("/"===this.url[this.url.length-1]?"":"/")+requestedFile.path;return{url,fileOffsetInRange:_Mathmax(requestedFile.offset-rangeStart,0),start:_Mathmax(rangeStart-requestedFile.offset,0),end:_Mathmin(fileEnd,rangeEnd-requestedFile.offset)}})}let numRequestsSucceeded=0,hasError=!1,ret;1{function onResponse(res,data){return 200>res.statusCode||300<=res.statusCode?(hasError=!0,cb(new Error(`Unexpected HTTP status code ${res.statusCode}`))):void(debug("Got data of length %d",data.length),1===requests.length?cb(null,data):(data.copy(ret,request.fileOffsetInRange),++numRequestsSucceeded===requests.length&&cb(null,ret)))}const url=request.url,start=request.start,end=request.end;debug("Requesting url=%s pieceIndex=%d offset=%d length=%d start=%d end=%d",url,pieceIndex,offset,length,start,end);const opts={url,method:"GET",headers:{"user-agent":`WebTorrent/${VERSION} (https://webtorrent.io)`,range:`bytes=${start}-${end}`}};get.concat(opts,(err,res,data)=>hasError?void 0:err?"undefined"==typeof window||url.startsWith(`${window.location.origin}/`)?(hasError=!0,cb(err)):get.head(url,(errHead,res)=>hasError?void 0:errHead?(hasError=!0,cb(errHead)):200>res.statusCode||300<=res.statusCode?(hasError=!0,cb(new Error(`Unexpected HTTP status code ${res.statusCode}`))):res.url===url?(hasError=!0,cb(err)):void(opts.url=res.url,get.concat(opts,(err,res,data)=>hasError?void 0:err?(hasError=!0,cb(err)):void onResponse(res,data)))):void onResponse(res,data))})}destroy(){super.destroy(),this._torrent=null}}}).call(this)}).call(this,require("buffer").Buffer)},{"../package.json":202,bitfield:22,"bittorrent-protocol":25,buffer:38,debug:69,"simple-get":167,"simple-sha1":169}],9:[function(require,module){let cache={},size=0;module.exports=function(addr){if(1e5===size&&module.exports.reset(),!cache[addr]){const m=/^\[?([^\]]+)\]?:(\d+)$/.exec(addr);if(!m)throw new Error(`invalid addr: ${addr}`);cache[addr]=[m[1],+m[2]],size+=1}return cache[addr]},module.exports.reset=function(){cache={},size=0}},{}],10:[function(require,module){module.exports=function(arr,fn,self){if(arr.filter)return arr.filter(fn,self);if(void 0===arr||null===arr)throw new TypeError;if("function"!=typeof fn)throw new TypeError;for(var ret=[],i=0;i404 - Not Found");res.end(html)}function serveFile(file){res.setHeader("Content-Type",mime.getType(file.name)||"application/octet-stream"),res.setHeader("Accept-Ranges","bytes"),res.setHeader("Content-Disposition",`inline; filename*=UTF-8''${encodeRFC5987(file.name)}`),res.setHeader("transferMode.dlna.org","Streaming"),res.setHeader("contentFeatures.dlna.org","DLNA.ORG_OP=01;DLNA.ORG_CI=0;DLNA.ORG_FLAGS=01700000000000000000000000000000");let range=rangeParser(file.length,req.headers.range||"");return Array.isArray(range)?(res.statusCode=206,range=range[0],res.setHeader("Content-Range",`bytes ${range.start}-${range.end}/${file.length}`),res.setHeader("Content-Length",range.end-range.start+1)):(res.statusCode=200,range=null,res.setHeader("Content-Length",file.length)),"HEAD"===req.method?res.end():void pump(file.createReadStream(range),res)}function serveMethodNotAllowed(){res.statusCode=405,res.setHeader("Content-Type","text/html");const html=getPageHTML("405 - Method Not Allowed","

405 - Method Not Allowed

");res.end(html)}if(opts.hostname&&`${opts.hostname}:${server.address().port}`!==req.headers.host)return req.destroy();const pathname=new URL(req.url,"http://example.com").pathname;return isOriginAllowed(req)&&res.setHeader("Access-Control-Allow-Origin",req.headers.origin),res.setHeader("X-Content-Type-Options","nosniff"),res.setHeader("Content-Security-Policy","base-uri 'none'; default-src 'none'; frame-ancestors 'none'; form-action 'none';"),"/favicon.ico"===pathname?serve404Page():"OPTIONS"===req.method?isOriginAllowed(req)?function(){res.statusCode=204,res.setHeader("Access-Control-Max-Age","600"),res.setHeader("Access-Control-Allow-Methods","GET,HEAD"),req.headers["access-control-request-headers"]&&res.setHeader("Access-Control-Allow-Headers",req.headers["access-control-request-headers"]),res.end()}():serveMethodNotAllowed():"GET"===req.method||"HEAD"===req.method?torrent.ready?handleRequest():(pendingReady.push(onReady),void torrent.once("ready",onReady)):serveMethodNotAllowed()}const server=http.createServer();opts.origin||(opts.origin="*");const sockets=[],pendingReady=[];let closed=!1;const _listen=server.listen,_close=server.close;return server.listen=(...args)=>(closed=!1,server.on("connection",onConnection),server.on("request",onRequest),_listen.apply(server,args)),server.close=cb=>{for(closed=!0,server.removeListener("connection",onConnection),server.removeListener("request",onRequest);0{sockets.forEach(socket=>{socket.destroy()}),cb||(cb=()=>{}),closed?process.nextTick(cb):server.close(cb),torrent=null},server}}).call(this)}).call(this,require("_process"))},{_process:132,"escape-html":77,http:92,mime:116,pump:133,"range-parser":141,"unordered-array-remove":191}],7:[function(require,module){(function(process,global){(function(){function getBlockPipelineLength(wire,duration){return 2+_Mathceil(duration*wire.downloadSpeed()/Piece.BLOCK_LENGTH)}function getPiecePipelineLength(wire,duration,pieceLength){return 1+_Mathceil(duration*wire.downloadSpeed()/pieceLength)}function randomInt(high){return 0|Math.random()*high}function noop(){}const addrToIPPort=require("addr-to-ip-port"),BitField=require("bitfield").default,ChunkStoreWriteStream=require("chunk-store-stream/write"),debug=require("debug")("webtorrent:torrent"),Discovery=require("torrent-discovery"),EventEmitter=require("events").EventEmitter,fs=require("fs"),FSChunkStore=require("fs-chunk-store"),get=require("simple-get"),ImmediateChunkStore=require("immediate-chunk-store"),MultiStream=require("multistream"),net=require("net"),os=require("os"),parallel=require("run-parallel"),parallelLimit=require("run-parallel-limit"),parseTorrent=require("parse-torrent"),path=require("path"),Piece=require("torrent-piece"),pump=require("pump"),randomIterate=require("random-iterate"),sha1=require("simple-sha1"),speedometer=require("speedometer"),utMetadata=require("ut_metadata"),utPex=require("ut_pex"),utp=require("utp-native"),File=require("./file"),Peer=require("./peer"),RarityMap=require("./rarity-map"),Server=require("./server"),CHOKE_TIMEOUT=5e3,SPEED_THRESHOLD=3*Piece.BLOCK_LENGTH,PIPELINE_MAX_DURATION=1,FILESYSTEM_CONCURRENCY=process.browser?1/0:2,RECONNECT_WAIT=[1e3,5e3,15e3],VERSION=require("../package.json").version,USER_AGENT=`WebTorrent/${VERSION} (https://webtorrent.io)`;let TMP;try{TMP=path.join(fs.statSync("/tmp")&&"/tmp","webtorrent")}catch(err){TMP=path.join("function"==typeof os.tmpdir?os.tmpdir():"/","webtorrent")}class Torrent extends EventEmitter{constructor(torrentId,client,opts){super(),this._debugId="unknown infohash",this.client=client,this.announce=opts.announce,this.urlList=opts.urlList,this.path=opts.path,this.skipVerify=!!opts.skipVerify,this._store=opts.store||FSChunkStore,this._getAnnounceOpts=opts.getAnnounceOpts,"boolean"==typeof opts.private&&(this.private=opts.private),this.strategy=opts.strategy||"sequential",this.maxWebConns=opts.maxWebConns||4,this._rechokeNumSlots=!1===opts.uploads||0===opts.uploads?0:+opts.uploads||10,this._rechokeOptimisticWire=null,this._rechokeOptimisticTime=0,this._rechokeIntervalId=null,this.ready=!1,this.destroyed=!1,this.paused=!1,this.done=!1,this.metadata=null,this.store=null,this.files=[],this.pieces=[],this._amInterested=!1,this._selections=[],this._critical=[],this.wires=[],this._queue=[],this._peers={},this._peersLength=0,this.received=0,this.uploaded=0,this._downloadSpeed=speedometer(),this._uploadSpeed=speedometer(),this._servers=[],this._xsRequests=[],this._fileModtimes=opts.fileModtimes,null!==torrentId&&this._onTorrentId(torrentId),this._debug("new torrent")}get timeRemaining(){return this.done?0:0===this.downloadSpeed?1/0:1e3*((this.length-this.downloaded)/this.downloadSpeed)}get downloaded(){if(!this.bitfield)return 0;let downloaded=0;for(let index=0,len=this.pieces.length;index{this.destroyed||this._onParsedTorrent(parsedTorrent)})):parseTorrent.remote(torrentId,(err,parsedTorrent)=>this.destroyed?void 0:err?this._destroy(err):void this._onParsedTorrent(parsedTorrent))}_onParsedTorrent(parsedTorrent){if(!this.destroyed){if(this._processParsedTorrent(parsedTorrent),!this.infoHash)return this._destroy(new Error("Malformed torrent data: No info hash"));(this.path||(this.path=path.join(TMP,this.infoHash)),this._rechokeIntervalId=setInterval(()=>{this._rechoke()},1e4),this._rechokeIntervalId.unref&&this._rechokeIntervalId.unref(),this.emit("_infoHash",this.infoHash),!this.destroyed)&&(this.emit("infoHash",this.infoHash),this.destroyed||(this.client.listening?this._onListening():this.client.once("listening",()=>{this._onListening()})))}}_processParsedTorrent(parsedTorrent){this._debugId=parsedTorrent.infoHash.toString("hex").substring(0,7),"undefined"!=typeof this.private&&(parsedTorrent.private=this.private),this.announce&&(parsedTorrent.announce=parsedTorrent.announce.concat(this.announce)),this.client.tracker&&global.WEBTORRENT_ANNOUNCE&&!parsedTorrent.private&&(parsedTorrent.announce=parsedTorrent.announce.concat(global.WEBTORRENT_ANNOUNCE)),this.urlList&&(parsedTorrent.urlList=parsedTorrent.urlList.concat(this.urlList)),parsedTorrent.announce=Array.from(new Set(parsedTorrent.announce)),parsedTorrent.urlList=Array.from(new Set(parsedTorrent.urlList)),Object.assign(this,parsedTorrent),this.magnetURI=parseTorrent.toMagnetURI(parsedTorrent),this.torrentFile=parseTorrent.toTorrentFile(parsedTorrent)}_onListening(){this.destroyed||(this.info?this._onMetadata(this):(this.xs&&this._getMetadataFromServer(),this._startDiscovery()))}_startDiscovery(){if(this.discovery||this.destroyed)return;let trackerOpts=this.client.tracker;trackerOpts&&(trackerOpts=Object.assign({},this.client.tracker,{getAnnounceOpts:()=>{const opts={uploaded:this.uploaded,downloaded:this.downloaded,left:_Mathmax(this.length-this.downloaded,0)};return this.client.tracker.getAnnounceOpts&&Object.assign(opts,this.client.tracker.getAnnounceOpts()),this._getAnnounceOpts&&Object.assign(opts,this._getAnnounceOpts()),opts}})),this.peerAddresses&&this.peerAddresses.forEach(peer=>this.addPeer(peer)),this.discovery=new Discovery({infoHash:this.infoHash,announce:this.announce,peerId:this.client.peerId,dht:!this.private&&this.client.dht,tracker:trackerOpts,port:this.client.torrentPort,userAgent:USER_AGENT,lsd:this.client.lsd}),this.discovery.on("error",err=>{this._destroy(err)}),this.discovery.on("peer",(peer,source)=>{this._debug("peer %s discovered via %s",peer,source);"string"==typeof peer&&this.done||this.addPeer(peer)}),this.discovery.on("trackerAnnounce",()=>{this.emit("trackerAnnounce"),0===this.numPeers&&this.emit("noPeers","tracker")}),this.discovery.on("dhtAnnounce",()=>{this.emit("dhtAnnounce"),0===this.numPeers&&this.emit("noPeers","dht")}),this.discovery.on("warning",err=>{this.emit("warning",err)})}_getMetadataFromServer(){function getMetadataFromURL(url,cb){function onResponse(err,res,torrent){if(self.destroyed)return cb(null);if(self.metadata)return cb(null);if(err)return self.emit("warning",new Error(`http error from xs param: ${url}`)),cb(null);if(200!==res.statusCode)return self.emit("warning",new Error(`non-200 status code ${res.statusCode} from xs param: ${url}`)),cb(null);let parsedTorrent;try{parsedTorrent=parseTorrent(torrent)}catch(err){}return parsedTorrent?parsedTorrent.infoHash===self.infoHash?void(self._onMetadata(parsedTorrent),cb(null)):(self.emit("warning",new Error(`got torrent file with incorrect info hash from xs param: ${url}`)),cb(null)):(self.emit("warning",new Error(`got invalid torrent file from xs param: ${url}`)),cb(null))}if(0!==url.indexOf("http://")&&0!==url.indexOf("https://"))return self.emit("warning",new Error(`skipping non-http xs param: ${url}`)),cb(null);let req;try{req=get.concat({url,method:"GET",headers:{"user-agent":USER_AGENT}},onResponse)}catch(err){return self.emit("warning",new Error(`skipping invalid url xs param: ${url}`)),cb(null)}self._xsRequests.push(req)}const self=this,urls=Array.isArray(this.xs)?this.xs:[this.xs],tasks=urls.map(url=>cb=>{getMetadataFromURL(url,cb)});parallel(tasks)}_onMetadata(metadata){if(this.metadata||this.destroyed)return;this._debug("got metadata"),this._xsRequests.forEach(req=>{req.abort()}),this._xsRequests=[];let parsedTorrent;if(metadata&&metadata.infoHash)parsedTorrent=metadata;else try{parsedTorrent=parseTorrent(metadata)}catch(err){return this._destroy(err)}if(this._processParsedTorrent(parsedTorrent),this.metadata=this.torrentFile,this.client.enableWebSeeds&&this.urlList.forEach(url=>{this.addWebSeed(url)}),this._rarityMap=new RarityMap(this),this.store=new ImmediateChunkStore(new this._store(this.pieceLength,{torrent:{infoHash:this.infoHash},files:this.files.map(file=>({path:path.join(this.path,file.path),length:file.length,offset:file.offset})),length:this.length,name:this.infoHash})),this.files=this.files.map(file=>new File(this,file)),this.so?this.files.forEach((v,i)=>{this.so.includes(i)?this.files[i].select():this.files[i].deselect()}):0!==this.pieces.length&&this.select(0,this.pieces.length-1,!1),this._hashes=this.pieces,this.pieces=this.pieces.map((hash,i)=>{const pieceLength=i===this.pieces.length-1?this.lastPieceLength:this.pieceLength;return new Piece(pieceLength)}),this._reservations=this.pieces.map(()=>[]),this.bitfield=new BitField(this.pieces.length),this.wires.forEach(wire=>{wire.ut_metadata&&wire.ut_metadata.setMetadata(this.metadata),this._onWireWithMetadata(wire)}),this.emit("metadata"),!this.destroyed)if(this.skipVerify)this._markAllVerified(),this._onStore();else{const onPiecesVerified=err=>err?this._destroy(err):void(this._debug("done verifying"),this._onStore());this._debug("verifying existing torrent data"),this._fileModtimes&&this._store===FSChunkStore?this.getFileModtimes((err,fileModtimes)=>{if(err)return this._destroy(err);const unchanged=this.files.map((_,index)=>fileModtimes[index]===this._fileModtimes[index]).every(x=>x);unchanged?(this._markAllVerified(),this._onStore()):this._verifyPieces(onPiecesVerified)}):this._verifyPieces(onPiecesVerified)}}getFileModtimes(cb){const ret=[];parallelLimit(this.files.map((file,index)=>cb=>{fs.stat(path.join(this.path,file.path),(err,stat)=>err&&"ENOENT"!==err.code?cb(err):void(ret[index]=stat&&stat.mtime.getTime(),cb(null)))}),FILESYSTEM_CONCURRENCY,err=>{this._debug("done getting file modtimes"),cb(err,ret)})}_verifyPieces(cb){parallelLimit(this.pieces.map((piece,index)=>cb=>this.destroyed?cb(new Error("torrent is destroyed")):void this.store.get(index,(err,buf)=>this.destroyed?cb(new Error("torrent is destroyed")):err?process.nextTick(cb,null):void sha1(buf,hash=>{if(this.destroyed)return cb(new Error("torrent is destroyed"));if(hash===this._hashes[index]){if(!this.pieces[index])return cb(null);this._debug("piece verified %s",index),this._markVerified(index)}else this._debug("piece invalid %s",index);cb(null)}))),FILESYSTEM_CONCURRENCY,cb)}rescanFiles(cb){if(this.destroyed)throw new Error("torrent is destroyed");cb||(cb=noop),this._verifyPieces(err=>err?(this._destroy(err),cb(err)):void(this._checkDone(),cb(null)))}_markAllVerified(){for(let index=0;index{req.abort()}),this._rarityMap&&this._rarityMap.destroy(),this._peers)this.removePeer(id);this.files.forEach(file=>{file instanceof File&&file._destroy()});const tasks=this._servers.map(server=>cb=>{server.destroy(cb)});this.discovery&&tasks.push(cb=>{this.discovery.destroy(cb)}),this.store&&tasks.push(cb=>{opts&&opts.destroyStore?this.store.destroy(cb):this.store.close(cb)}),parallel(tasks,cb),err&&(0===this.listenerCount("error")?this.client.emit("error",err):this.emit("error",err)),this.emit("close"),this.client=null,this.files=[],this.discovery=null,this.store=null,this._rarityMap=null,this._peers=null,this._servers=null,this._xsRequests=null}}addPeer(peer){if(this.destroyed)throw new Error("torrent is destroyed");if(!this.infoHash)throw new Error("addPeer() must not be called before the `infoHash` event");if(this.client.blocked){let host;if("string"==typeof peer){let parts;try{parts=addrToIPPort(peer)}catch(e){return this._debug("ignoring peer: invalid %s",peer),this.emit("invalidPeer",peer),!1}host=parts[0]}else"string"==typeof peer.remoteAddress&&(host=peer.remoteAddress);if(host&&this.client.blocked.contains(host))return this._debug("ignoring peer: blocked %s",peer),"string"!=typeof peer&&peer.destroy(),this.emit("blockedPeer",peer),!1}const wasAdded=!!this._addPeer(peer,this.client.utp?"utp":"tcp");return wasAdded?this.emit("peer",peer):this.emit("invalidPeer",peer),wasAdded}_addPeer(peer,type){if(this.destroyed)return"string"!=typeof peer&&peer.destroy(),null;if("string"==typeof peer&&!this._validAddr(peer))return this._debug("ignoring peer: invalid %s",peer),null;const id=peer&&peer.id||peer;if(this._peers[id])return this._debug("ignoring peer: duplicate (%s)",id),"string"!=typeof peer&&peer.destroy(),null;if(this.paused)return this._debug("ignoring peer: torrent is paused"),"string"!=typeof peer&&peer.destroy(),null;this._debug("add peer %s",id);let newPeer;return newPeer="string"==typeof peer?"utp"===type?Peer.createUTPOutgoingPeer(peer,this):Peer.createTCPOutgoingPeer(peer,this):Peer.createWebRTCPeer(peer,this),this._peers[newPeer.id]=newPeer,this._peersLength+=1,"string"==typeof peer&&(this._queue.push(newPeer),this._drain()),newPeer}addWebSeed(url){if(this.destroyed)throw new Error("torrent is destroyed");if(!/^https?:\/\/.+/.test(url))return this.emit("warning",new Error(`ignoring invalid web seed: ${url}`)),void this.emit("invalidPeer",url);if(this._peers[url])return this.emit("warning",new Error(`ignoring duplicate web seed: ${url}`)),void this.emit("invalidPeer",url);this._debug("add web seed %s",url);const newPeer=Peer.createWebSeedPeer(url,this);this._peers[newPeer.id]=newPeer,this._peersLength+=1,this.emit("peer",url)}_addIncomingPeer(peer){return this.destroyed?peer.destroy(new Error("torrent is destroyed")):this.paused?peer.destroy(new Error("torrent is paused")):void(this._debug("add incoming peer %s",peer.id),this._peers[peer.id]=peer,this._peersLength+=1)}removePeer(peer){const id=peer&&peer.id||peer;peer=this._peers[id];peer&&(this._debug("removePeer %s",id),delete this._peers[id],this._peersLength-=1,peer.destroy(),this._drain())}select(start,end,priority,notify){if(this.destroyed)throw new Error("torrent is destroyed");if(0>start||endb.priority-a.priority),this._updateSelections()}deselect(start,end,priority){if(this.destroyed)throw new Error("torrent is destroyed");priority=+priority||0,this._debug("deselect %s-%s (priority %s)",start,end,priority);for(let i=0;i{this.destroyed||(this.received+=downloaded,this._downloadSpeed(downloaded),this.client._downloadSpeed(downloaded),this.emit("download",downloaded),this.destroyed||this.client.emit("download",downloaded))}),wire.on("upload",uploaded=>{this.destroyed||(this.uploaded+=uploaded,this._uploadSpeed(uploaded),this.client._uploadSpeed(uploaded),this.emit("upload",uploaded),this.destroyed||this.client.emit("upload",uploaded))}),this.wires.push(wire),addr){const parts=addrToIPPort(addr);wire.remoteAddress=parts[0],wire.remotePort=parts[1]}this.client.dht&&this.client.dht.listening&&wire.on("port",port=>this.destroyed||this.client.dht.destroyed?void 0:wire.remoteAddress?0===port||65536{this._debug("wire timeout (%s)",addr),wire.destroy()}),wire.setTimeout(3e4,!0),wire.setKeepAlive(!0),wire.use(utMetadata(this.metadata)),wire.ut_metadata.on("warning",err=>{this._debug("ut_metadata warning: %s",err.message)}),this.metadata||(wire.ut_metadata.on("metadata",metadata=>{this._debug("got metadata via ut_metadata"),this._onMetadata(metadata)}),wire.ut_metadata.fetch()),"function"!=typeof utPex||this.private||(wire.use(utPex()),wire.ut_pex.on("peer",peer=>{this.done||(this._debug("ut_pex: got peer: %s (from %s)",peer,addr),this.addPeer(peer))}),wire.ut_pex.on("dropped",peer=>{const peerObj=this._peers[peer];peerObj&&!peerObj.connected&&(this._debug("ut_pex: dropped peer: %s (from %s)",peer,addr),this.removePeer(peer))}),wire.once("close",()=>{wire.ut_pex.reset()})),this.emit("wire",wire,addr),this.metadata&&process.nextTick(()=>{this._onWireWithMetadata(wire)})}_onWireWithMetadata(wire){let timeoutId=null;const onChokeTimeout=()=>{this.destroyed||wire.destroyed||(this._numQueued>2*(this._numConns-this.numPeers)&&wire.amInterested?wire.destroy():(timeoutId=setTimeout(onChokeTimeout,CHOKE_TIMEOUT),timeoutId.unref&&timeoutId.unref()))};let i;const updateSeedStatus=()=>{if(wire.peerPieces.buffer.length===this.bitfield.buffer.length){for(i=0;i{updateSeedStatus(),this._update(),this._updateWireInterest(wire)}),wire.on("have",()=>{updateSeedStatus(),this._update(),this._updateWireInterest(wire)}),wire.once("interested",()=>{wire.unchoke()}),wire.once("close",()=>{clearTimeout(timeoutId)}),wire.on("choke",()=>{clearTimeout(timeoutId),timeoutId=setTimeout(onChokeTimeout,CHOKE_TIMEOUT),timeoutId.unref&&timeoutId.unref()}),wire.on("unchoke",()=>{clearTimeout(timeoutId),this._update()}),wire.on("request",(index,offset,length,cb)=>length>131072?wire.destroy():void(this.pieces[index]||this.store.get(index,{offset,length},cb))),wire.bitfield(this.bitfield),this._updateWireInterest(wire),wire.peerExtensions.dht&&this.client.dht&&this.client.dht.listening&&wire.port(this.client.dht.address().port),"webSeed"!==wire.type&&(timeoutId=setTimeout(onChokeTimeout,CHOKE_TIMEOUT),timeoutId.unref&&timeoutId.unref()),wire.isSeeder=!1,updateSeedStatus()}_updateSelections(){!this.ready||this.destroyed||(process.nextTick(()=>{this._gcSelections()}),this._updateInterest(),this._update())}_gcSelections(){for(let i=0;ithis._updateWireInterest(wire));prev===this._amInterested||(this._amInterested?this.emit("interested"):this.emit("uninterested"))}_updateWireInterest(wire){let interested=!1;for(let index=0;indexi>=start&&i<=end&&!(i in tried)&&wire.peerPieces.get(i)&&(!rank||rank(i))}function speedRanker(){const speed=wire.downloadSpeed()||1;if(speed>SPEED_THRESHOLD)return()=>!0;const secs=_Mathmax(1,wire.requests.length)*Piece.BLOCK_LENGTH/speed;let tries=10,ptr=0;return index=>{if(!tries||self.bitfield.get(index))return!0;for(let missing=self.pieces[index].missing;ptr=maxOutstandingRequests)return!0;const rank=speedRanker();for(let i=0;ipiece));){for(;self._request(wire,piece,self._critical[piece]||hotswap););if(wire.requests.lengthpiece));){if(self._request(wire,piece,!1))return;tried[piece]=!0,tries+=1}}else for(piece=next.to;piece>=next.from+next.offset;--piece)if(wire.peerPieces.get(piece)&&self._request(wire,piece,!1))return}}();const minOutstandingRequests=getBlockPipelineLength(wire,.5);if(wire.requests.length>=minOutstandingRequests)return;const maxOutstandingRequests=getBlockPipelineLength(wire,PIPELINE_MAX_DURATION);trySelectWire(!1)||trySelectWire(!0)}_rechoke(){if(this.ready){const wireStack=this.wires.map(wire=>({wire,random:Math.random()})).sort((objA,objB)=>{const wireA=objA.wire,wireB=objB.wire;return wireA.downloadSpeed()===wireB.downloadSpeed()?wireA.uploadSpeed()===wireB.uploadSpeed()?wireA.amChoking===wireB.amChoking?objA.random-objB.random:wireA.amChoking?-1:1:wireA.uploadSpeed()-wireB.uploadSpeed():wireA.downloadSpeed()-wireB.downloadSpeed()}).map(obj=>obj.wire);0>=this._rechokeOptimisticTime?this._rechokeOptimisticWire=null:this._rechokeOptimisticTime-=1;for(let numInterestedUnchoked=0;0wire.peerInterested);if(0wire!==this._rechokeOptimisticWire).forEach(wire=>wire.choke())}}_hotswap(wire,index){const speed=wire.downloadSpeed();if(speed=SPEED_THRESHOLD||2*otherSpeed>speed||otherSpeed>minSpeed||(minWire=otherWire,minSpeed=otherSpeed)}if(!minWire)return!1;for(i=0;i{self._update()})}const self=this,numRequests=wire.requests.length,isWebSeed="webSeed"===wire.type;if(self.bitfield.get(index))return!1;const maxOutstandingRequests=isWebSeed?_Mathmin(getPiecePipelineLength(wire,PIPELINE_MAX_DURATION,self.pieceLength),self.maxWebConns):getBlockPipelineLength(wire,PIPELINE_MAX_DURATION);if(numRequests>=maxOutstandingRequests)return!1;const piece=self.pieces[index];let reservation=isWebSeed?piece.reserveRemaining():piece.reserve();if(-1===reservation&&hotswap&&self._hotswap(wire,index)&&(reservation=isWebSeed?piece.reserveRemaining():piece.reserve()),-1===reservation)return!1;let r=self._reservations[index];r||(r=self._reservations[index]=[]);let i=r.indexOf(null);-1===i&&(i=r.length),r[i]=wire;const chunkOffset=piece.chunkOffset(reservation),chunkLength=isWebSeed?piece.chunkLengthRemaining(reservation):piece.chunkLength(reservation);return wire.request(index,chunkOffset,chunkLength,function onChunk(err,chunk){if(self.destroyed)return;if(!self.ready)return self.once("ready",()=>{onChunk(err,chunk)});if(r[i]===wire&&(r[i]=null),piece!==self.pieces[index])return onUpdateTick();if(err)return self._debug("error getting piece %s (offset: %s length: %s) from %s: %s",index,chunkOffset,chunkLength,`${wire.remoteAddress}:${wire.remotePort}`,err.message),isWebSeed?piece.cancelRemaining(reservation):piece.cancel(reservation),void onUpdateTick();if(self._debug("got piece %s (offset: %s length: %s) from %s",index,chunkOffset,chunkLength,`${wire.remoteAddress}:${wire.remotePort}`),!piece.set(reservation,chunk,wire))return onUpdateTick();const buf=piece.flush();sha1(buf,hash=>{if(!self.destroyed){if(hash===self._hashes[index]){if(!self.pieces[index])return;self._debug("piece verified %s",index),self.pieces[index]=null,self._reservations[index]=null,self.bitfield.set(index,!0),self.store.put(index,buf),self.wires.forEach(wire=>{wire.have(index)}),self._checkDone()&&!self.destroyed&&self.discovery.complete()}else self.pieces[index]=new Piece(piece.length),self.emit("warning",new Error(`Piece ${index} failed verification`));onUpdateTick()}})}),!0}_checkDone(){if(this.destroyed)return;this.files.forEach(file=>{if(!file.done){for(let i=file._startPiece;i<=file._endPiece;++i)if(!this.bitfield.get(i))return;file.done=!0,file.emit("done"),this._debug(`file done: ${file.name}`)}});let done=!0;for(let i=0;i{this.load(streams,cb)});Array.isArray(streams)||(streams=[streams]),cb||(cb=noop);const readable=new MultiStream(streams),writable=new ChunkStoreWriteStream(this.store,this.pieceLength);pump(readable,writable,err=>err?cb(err):void(this._markAllVerified(),this._checkDone(),cb(null)))}createServer(requestListener){if("function"!=typeof Server)throw new Error("node.js-only method");if(this.destroyed)throw new Error("torrent is destroyed");const server=new Server(this,requestListener);return this._servers.push(server),server}pause(){this.destroyed||(this._debug("pause"),this.paused=!0)}resume(){this.destroyed||(this._debug("resume"),this.paused=!1,this._drain())}_debug(){const args=[].slice.call(arguments);args[0]=`[${this.client?this.client._debugId:"No Client"}] [${this._debugId}] ${args[0]}`,debug(...args)}_drain(){if(this._debug("_drain numConns %s maxConns %s",this._numConns,this.client.maxConns),"function"!=typeof net.connect||this.destroyed||this.paused||this._numConns>=this.client.maxConns)return;this._debug("drain (%s queued, %s/%s peers)",this._numQueued,this.numPeers,this.client.maxConns);const peer=this._queue.shift();if(!peer)return;this._debug("%s connect attempt to %s",peer.type,peer.addr);const parts=addrToIPPort(peer.addr),opts={host:parts[0],port:parts[1]};peer.conn="utpOutgoing"===peer.type?utp.connect(opts.port,opts.host):net.connect(opts);const conn=peer.conn;conn.once("connect",()=>{peer.onConnect()}),conn.once("error",err=>{peer.destroy(err)}),peer.startConnectTimeout(),conn.on("close",()=>{if(!this.destroyed){if(peer.retries>=RECONNECT_WAIT.length){if(this.client.utp){const newPeer=this._addPeer(peer.addr,"tcp");newPeer&&(newPeer.retries=0)}else this._debug("conn %s closed: will not re-add (max %s attempts)",peer.addr,RECONNECT_WAIT.length);return}const ms=RECONNECT_WAIT[peer.retries];this._debug("conn %s closed: will re-add to queue in %sms (attempt %s)",peer.addr,ms,peer.retries+1);const reconnectTimeout=setTimeout(()=>{if(!this.destroyed){const newPeer=this._addPeer(peer.addr,this.client.utp?"utp":"tcp");newPeer&&(newPeer.retries=peer.retries+1)}},ms);reconnectTimeout.unref&&reconnectTimeout.unref()}})}_validAddr(addr){let parts;try{parts=addrToIPPort(addr)}catch(e){return!1}const host=parts[0],port=parts[1];return 0port&&("127.0.0.1"!==host||port!==this.client.torrentPort)}}module.exports=Torrent}).call(this)}).call(this,require("_process"),"undefined"==typeof global?"undefined"==typeof self?"undefined"==typeof window?{}:window:self:global)},{"../package.json":202,"./file":3,"./peer":4,"./rarity-map":5,"./server":6,_process:132,"addr-to-ip-port":9,bitfield:22,"chunk-store-stream/write":66,debug:69,events:39,fs:37,"fs-chunk-store":114,"immediate-chunk-store":96,multistream:126,net:65,os:36,"parse-torrent":130,path:40,pump:133,"random-iterate":139,"run-parallel":162,"run-parallel-limit":161,"simple-get":167,"simple-sha1":169,speedometer:172,"torrent-discovery":187,"torrent-piece":188,ut_metadata:194,ut_pex:195,"utp-native":36}],8:[function(require,module){(function(Buffer){(function(){const BitField=require("bitfield").default,debug=require("debug")("webtorrent:webconn"),get=require("simple-get"),sha1=require("simple-sha1"),Wire=require("bittorrent-protocol"),VERSION=require("../package.json").version;module.exports=class WebConn extends Wire{constructor(url,torrent){super(),this.url=url,this.webPeerId=sha1.sync(url),this._torrent=torrent,this._init()}_init(){this.setKeepAlive(!0),this.once("handshake",infoHash=>{if(this.destroyed)return;this.handshake(infoHash,this.webPeerId);const numPieces=this._torrent.pieces.length,bitfield=new BitField(numPieces);for(let i=0;i<=numPieces;i++)bitfield.set(i,!0);this.bitfield(bitfield)}),this.once("interested",()=>{debug("interested"),this.unchoke()}),this.on("uninterested",()=>{debug("uninterested")}),this.on("choke",()=>{debug("choke")}),this.on("unchoke",()=>{debug("unchoke")}),this.on("bitfield",()=>{debug("bitfield")}),this.on("request",(pieceIndex,offset,length,callback)=>{debug("request pieceIndex=%d offset=%d length=%d",pieceIndex,offset,length),this.httpRequest(pieceIndex,offset,length,callback)})}httpRequest(pieceIndex,offset,length,cb){const pieceOffset=pieceIndex*this._torrent.pieceLength,rangeStart=pieceOffset+offset,rangeEnd=rangeStart+length-1,files=this._torrent.files;let requests;if(1>=files.length)requests=[{url:this.url,start:rangeStart,end:rangeEnd}];else{const requestedFiles=files.filter(file=>file.offset<=rangeEnd&&file.offset+file.length>rangeStart);if(1>requestedFiles.length)return cb(new Error("Could not find file corresponnding to web seed range request"));requests=requestedFiles.map(requestedFile=>{const fileEnd=requestedFile.offset+requestedFile.length-1,url=this.url+("/"===this.url[this.url.length-1]?"":"/")+requestedFile.path;return{url,fileOffsetInRange:_Mathmax(requestedFile.offset-rangeStart,0),start:_Mathmax(rangeStart-requestedFile.offset,0),end:_Mathmin(fileEnd,rangeEnd-requestedFile.offset)}})}let numRequestsSucceeded=0,hasError=!1,ret;1{function onResponse(res,data){return 200>res.statusCode||300<=res.statusCode?(hasError=!0,cb(new Error(`Unexpected HTTP status code ${res.statusCode}`))):void(debug("Got data of length %d",data.length),1===requests.length?cb(null,data):(data.copy(ret,request.fileOffsetInRange),++numRequestsSucceeded===requests.length&&cb(null,ret)))}const url=request.url,start=request.start,end=request.end;debug("Requesting url=%s pieceIndex=%d offset=%d length=%d start=%d end=%d",url,pieceIndex,offset,length,start,end);const opts={url,method:"GET",headers:{"user-agent":`WebTorrent/${VERSION} (https://webtorrent.io)`,range:`bytes=${start}-${end}`}};get.concat(opts,(err,res,data)=>hasError?void 0:err?"undefined"==typeof window||url.startsWith(`${window.location.origin}/`)?(hasError=!0,cb(err)):get.head(url,(errHead,res)=>hasError?void 0:errHead?(hasError=!0,cb(errHead)):200>res.statusCode||300<=res.statusCode?(hasError=!0,cb(new Error(`Unexpected HTTP status code ${res.statusCode}`))):res.url===url?(hasError=!0,cb(err)):void(opts.url=res.url,get.concat(opts,(err,res,data)=>hasError?void 0:err?(hasError=!0,cb(err)):void onResponse(res,data)))):void onResponse(res,data))})}destroy(){super.destroy(),this._torrent=null}}}).call(this)}).call(this,require("buffer").Buffer)},{"../package.json":202,bitfield:22,"bittorrent-protocol":25,buffer:38,debug:69,"simple-get":167,"simple-sha1":169}],9:[function(require,module){let cache={},size=0;module.exports=function(addr){if(1e5===size&&module.exports.reset(),!cache[addr]){const m=/^\[?([^\]]+)\]?:(\d+)$/.exec(addr);if(!m)throw new Error(`invalid addr: ${addr}`);cache[addr]=[m[1],+m[2]],size+=1}return cache[addr]},module.exports.reset=function(){cache={},size=0}},{}],10:[function(require,module){module.exports=function(arr,fn,self){if(arr.filter)return arr.filter(fn,self);if(void 0===arr||null===arr)throw new TypeError;if("function"!=typeof fn)throw new TypeError;for(var ret=[],i=0;i * @license MIT - */function compare(a,b){if(a===b)return 0;for(var x=a.length,y=b.length,i=0,len=_Mathmin(x,y);irecurseTimes)return isRegExp(value)?ctx.stylize(RegExp.prototype.toString.call(value),"regexp"):ctx.stylize("[Object]","special");ctx.seen.push(value);var output;return output=array?formatArray(ctx,value,recurseTimes,visibleKeys,keys):keys.map(function(key){return formatProperty(ctx,value,recurseTimes,visibleKeys,key,array)}),ctx.seen.pop(),reduceToSingleString(output,base,braces)}function formatPrimitive(ctx,value){if(isUndefined(value))return ctx.stylize("undefined","undefined");if(isString(value)){var simple="'"+JSON.stringify(value).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,"\"")+"'";return ctx.stylize(simple,"string")}return isNumber(value)?ctx.stylize(""+value,"number"):isBoolean(value)?ctx.stylize(""+value,"boolean"):isNull(value)?ctx.stylize("null","null"):void 0}function formatError(value){return"["+Error.prototype.toString.call(value)+"]"}function formatArray(ctx,value,recurseTimes,visibleKeys,keys){for(var output=[],i=0,l=value.length;ictx.seen.indexOf(desc.value)?(str=isNull(recurseTimes)?formatValue(ctx,desc.value,null):formatValue(ctx,desc.value,recurseTimes-1),-1n?"0"+n.toString(10):n.toString(10)}function timestamp(){var d=new Date,time=[pad(d.getHours()),pad(d.getMinutes()),pad(d.getSeconds())].join(":");return[d.getDate(),months[d.getMonth()],time].join(" ")}function hasOwnProperty(obj,prop){return Object.prototype.hasOwnProperty.call(obj,prop)}exports.format=function(f){if(!isString(f)){for(var objects=[],i=0;i=len)return x;switch(x){case"%s":return args[i++]+"";case"%d":return+args[i++];case"%j":try{return JSON.stringify(args[i++])}catch(_){return"[Circular]"}default:return x;}}),x=args[i];i>16,arr[curByte++]=255&tmp>>8,arr[curByte++]=255&tmp;return 2===placeHoldersLen&&(tmp=revLookup[b64.charCodeAt(i)]<<2|revLookup[b64.charCodeAt(i+1)]>>4,arr[curByte++]=255&tmp),1===placeHoldersLen&&(tmp=revLookup[b64.charCodeAt(i)]<<10|revLookup[b64.charCodeAt(i+1)]<<4|revLookup[b64.charCodeAt(i+2)]>>2,arr[curByte++]=255&tmp>>8,arr[curByte++]=255&tmp),arr}function tripletToBase64(num){return lookup[63&num>>18]+lookup[63&num>>12]+lookup[63&num>>6]+lookup[63&num]}function encodeChunk(uint8,start,end){for(var output=[],i=start,tmp;ilen2?len2:i+maxChunkLength));return 1===extraBytes?(tmp=uint8[len-1],parts.push(lookup[tmp>>2]+lookup[63&tmp<<4]+"==")):2===extraBytes&&(tmp=(uint8[len-2]<<8)+uint8[len-1],parts.push(lookup[tmp>>10]+lookup[63&tmp>>4]+lookup[63&tmp<<2]+"=")),parts.join("")}exports.byteLength=function(b64){var lens=getLens(b64),validLen=lens[0],placeHoldersLen=lens[1];return 3*(validLen+placeHoldersLen)/4-placeHoldersLen},exports.toByteArray=toByteArray,exports.fromByteArray=fromByteArray;for(var lookup=[],revLookup=[],Arr="undefined"==typeof Uint8Array?Array:Uint8Array,code="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",i=0,len=code.length;inum&&48<=num){sum=10*sum+(num-48);continue}if(i!==start||43!==num){if(i===start&&45===num){sign=-1;continue}if(46===num)break;throw new Error("not a number: buffer["+i+"] = "+num)}}return sum*sign}function decode(data,start,end,encoding){return null==data||0===data.length?null:("number"!=typeof start&&null==encoding&&(encoding=start,start=void 0),"number"!=typeof end&&null==encoding&&(encoding=end,end=void 0),decode.position=0,decode.encoding=encoding||null,decode.data=Buffer.isBuffer(data)?data.slice(start,end):Buffer.from(data),decode.bytes=decode.data.length,decode.next())}var Buffer=require("safe-buffer").Buffer;const END_OF_TYPE=101;decode.bytes=0,decode.position=0,decode.data=null,decode.encoding=null,decode.next=function(){switch(decode.data[decode.position]){case 100:return decode.dictionary();case 108:return decode.list();case 105:return decode.integer();default:return decode.buffer();}},decode.find=function(chr){for(var i=decode.position,c=decode.data.length,d=decode.data;iArray.from({length:end-start+1},(cur,idx)=>idx+start);return range.reduce((acc,cur)=>{const r=cur.split("-").map(cur=>parseInt(cur));return acc.concat(generateRange(...r))},[])}module.exports=parseRange,module.exports.parse=parseRange,module.exports.compose=function(range){return range.reduce((acc,cur,idx,arr)=>((0===idx||cur!==arr[idx-1]+1)&&acc.push([]),acc[acc.length-1].push(cur),acc),[]).map(cur=>1low||low>=haystack.length)throw new RangeError("invalid lower bound");if(void 0===high)high=haystack.length-1;else if(high|=0,high=haystack.length)throw new RangeError("invalid upper bound");for(;low<=high;)if(mid=low+(high-low>>>1),cmp=+comparator(haystack[mid],needle,mid,haystack),0>cmp)low=mid+1;else if(0>3;return 0!=num%8&&out++,out}Object.defineProperty(exports,"__esModule",{value:!0});var BitField=function(){function BitField(data,opts){void 0===data&&(data=0);var grow=null===opts||void 0===opts?void 0:opts.grow;this.grow=grow&&isFinite(grow)&&getByteSize(grow)||grow||0,this.buffer="number"==typeof data?new Uint8Array(getByteSize(data)):data}return BitField.prototype.get=function(i){var j=i>>3;return j>i%8)},BitField.prototype.set=function(i,value){void 0===value&&(value=!0);var j=i>>3;if(value){if(this.buffer.length>i%8}else j>i%8))},BitField.prototype.forEach=function(fn,start,end){void 0===start&&(start=0),void 0===end&&(end=8*this.buffer.length);for(var i=start,j=i>>3,y=128>>i%8,byte=this.buffer[j];i>1},BitField}();exports.default=BitField},{}],23:[function(require,module){(function(process,Buffer){(function(){function noop(){}function sha1(buf){return Buffer.from(simpleSha1.sync(buf),"hex")}function createGetResponse(id,token,value){const r={id,token,v:value.v};return value.sig&&(r.sig=value.sig,r.k=value.k,"number"==typeof value.seq&&(r.seq=value.seq)),r}function encodePeer(host,port){const buf=Buffer.allocUnsafe(6),ip=host.split(".");for(let i=0;4>i;i++)buf[i]=parseInt(ip[i]||0,10);return buf.writeUInt16BE(port,4),buf}function decodePeers(buf){const peers=[];try{for(let i=0;ideadNode?(self._debug("swaping dead node with newer",deadNode),swap(deadNode),cb()):void(self._debug("no node added, all other nodes ok"),cb()))});this._rpc.on("ping",(older,swap)=>{onping({older,swap})}),process.nextTick(function(){self.destroyed||self._bootstrap(!1!==opts.bootstrap)}),this._debug("new DHT %s",this.nodeId);const self=this}_setBucketCheckInterval(){function checkBucket(){const diff=Date.now()-self._rpc.nodes.metadata.lastChange;return diff{self.destroyed||(1>self.nodes.toArray().length&&self._bootstrap(!0),queueNext())})}function queueNext(){if(self._runningBucketCheck&&!self.destroyed){const nextTimeout=_Mathfloor(Math.random()*interval+30000);self._bucketCheckTimeout=setTimeout(checkBucket,nextTimeout)}}const self=this,interval=60000;this._runningBucketCheck=!0,queueNext()}_pingAll(cb){this._checkAndRemoveNodes(this.nodes.toArray(),cb)}removeBucketCheckInterval(){this._runningBucketCheck=!1,clearTimeout(this._bucketCheckTimeout)}updateBucketTimestamp(){this._rpc.nodes.metadata.lastChange=Date.now()}_checkAndRemoveNodes(nodes,cb){const self=this;this._checkNodes(nodes,!0,(_,node)=>{node&&self.removeNode(node.id),cb(null,node)})}_checkNodes(nodes,force,cb){function test(acc){let current=null;for(;acc.length&&(current=acc.pop(),current.id&&!force)&&!(1e4err?void cb(null,current):(self.updateBucketTimestamp(),test(acc))):cb(null)}const self=this;test(nodes)}addNode(node){const self=this;if(node.id){node.id=toBuffer(node.id);const old=!!this._rpc.nodes.get(node.id);return this._rpc.nodes.add(node),void(old||(this.emit("node",node),this.updateBucketTimestamp()))}this._sendPing(node,(_,node)=>{node&&self.addNode(node)})}removeNode(id){this._rpc.nodes.remove(toBuffer(id))}_sendPing(node,cb){const self=this,expectedId=node.id;this._rpc.query(node,{q:"ping"},(err,pong,node)=>err?cb(err):pong.r&&pong.r.id&&Buffer.isBuffer(pong.r.id)&&pong.r.id.length===self._hashLength?Buffer.isBuffer(expectedId)&&!expectedId.equals(pong.r.id)?cb(new Error("Unexpected node id")):void(self.updateBucketTimestamp(),cb(null,{id:pong.r.id,host:node.host||node.address,port:node.port})):cb(new Error("Bad reply")))}toJSON(){const self=this,values={};return Object.keys(this._values.cache).forEach(key=>{const value=self._values.cache[key].value;values[key]={v:value.v.toString("hex"),id:value.id.toString("hex")},null!=value.seq&&(values[key].seq=value.seq),null!=value.sig&&(values[key].sig=value.sig.toString("hex")),null!=value.k&&(values[key].k=value.k.toString("hex"))}),{nodes:this._rpc.nodes.toArray().map(toNode),values}}put(opts,cb){(Buffer.isBuffer(opts)||"string"==typeof opts)&&(opts={v:opts});const isMutable=!!opts.k;if(opts.v===void 0)throw new Error("opts.v not given");if(1e3<=opts.v.length)throw new Error("v must be less than 1000 bytes in put()");if(isMutable&&void 0!==opts.cas&&"number"!=typeof opts.cas)throw new Error("opts.cas must be an integer if provided");if(isMutable&&32!==opts.k.length)throw new Error("opts.k ed25519 public key must be 32 bytes");if(isMutable&&"function"!=typeof opts.sign&&!Buffer.isBuffer(opts.sig))throw new Error("opts.sign function or options.sig signature is required for mutable put");if(isMutable&&opts.salt&&64 64 bytes long");if(isMutable&&void 0===opts.seq)throw new Error("opts.seq not provided for a mutable update");if(isMutable&&"number"!=typeof opts.seq)throw new Error("opts.seq not an integer");return this._put(opts,cb)}_put(opts,cb){cb||(cb=noop);const isMutable=!!opts.k,v="string"==typeof opts.v?Buffer.from(opts.v):opts.v,key=isMutable?this._hash(opts.salt?Buffer.concat([opts.k,opts.salt]):opts.k):this._hash(bencode.encode(v)),table=this._tables.get(key.toString("hex"));if(!table)return this._preput(key,opts,cb);const message={q:"put",a:{id:this._rpc.id,token:null,v}};return isMutable?("number"==typeof opts.cas&&(message.a.cas=opts.cas),opts.salt&&(message.a.salt=opts.salt),message.a.k=opts.k,message.a.seq=opts.seq,"function"==typeof opts.sign?message.a.sig=opts.sign(encodeSigData(message.a)):Buffer.isBuffer(opts.sig)&&(message.a.sig=opts.sig)):this._values.set(key.toString("hex"),message.a),this._rpc.queryAll(table.closest(key),message,null,(err,n)=>err?cb(err,key,n):void cb(null,key,n)),key}_preput(key,opts,cb){const self=this;return this._closest(key,{q:"get",a:{id:this._rpc.id,target:key}},null,err=>err?cb(err):void self.put(opts,cb)),key}get(key,opts,cb){function done(err){return err?cb(err):void cb(null,value)}function onreply(message){const r=message.r;if(!r||!r.v)return!0;const isMutable=r.k||r.sig;if(opts.salt&&(r.salt=Buffer.from(opts.salt)),isMutable){if(!verify||!r.sig||!r.k)return!0;if(!verify(r.sig,encodeSigData(r),r.k))return!0;hash(r.salt?Buffer.concat([r.k,r.salt]):r.k).equals(key)&&(!value||r.seq>value.seq)&&(value=r)}else if(hash(bencode.encode(r.v)).equals(key))return value=r,!1;return!0}key=toBuffer(key),"function"==typeof opts&&(cb=opts,opts=null),opts||(opts={});const verify=opts.verify||this._verify,hash=this._hash;let value=this._values.get(key.toString("hex"))||null;return value&&!1!==opts.cache?(value=createGetResponse(this._rpc.id,null,value),process.nextTick(done)):void this._closest(key,{q:"get",a:{id:this._rpc.id,target:key}},onreply,done)}announce(infoHash,port,cb){if("function"==typeof port)return this.announce(infoHash,0,port);infoHash=toBuffer(infoHash),cb||(cb=noop);const table=this._tables.get(infoHash.toString("hex"));if(!table)return this._preannounce(infoHash,port,cb);if(this._host){const dhtPort=this.listening?this.address().port:0;this._addPeer({host:this._host,port:port||dhtPort},infoHash,{host:this._host,port:dhtPort})}const message={q:"announce_peer",a:{id:this._rpc.id,token:null,info_hash:infoHash,port,implied_port:port?0:1}};this._debug("announce %s %d",infoHash,port),this._rpc.queryAll(table.closest(infoHash),message,null,cb)}_preannounce(infoHash,port,cb){const self=this;this.lookup(infoHash,err=>self.destroyed?cb(new Error("dht is destroyed")):err?cb(err):void self.announce(infoHash,port,cb))}lookup(infoHash,cb){function emit(values,from){values||(values=self._peers.get(infoHash.toString("hex"),100));const peers=decodePeers(values);for(let i=0;i{self.emit("close"),cb&&cb()})}_onquery(query,peer){const q=query.q.toString();if(this._debug("received %s query from %s:%d",q,peer.address,peer.port),!!query.a)return"ping"===q?this._rpc.response(peer,query,{id:this._rpc.id}):"find_node"===q?this._onfindnode(query,peer):"get_peers"===q?this._ongetpeers(query,peer):"announce_peer"===q?this._onannouncepeer(query,peer):"get"===q?this._onget(query,peer):"put"===q?this._onput(query,peer):void 0}_onfindnode(query,peer){const target=query.a.target;if(!target)return this._rpc.error(peer,query,[203,"`find_node` missing required `a.target` field"]);this.emit("find_node",target);const nodes=this._rpc.nodes.closest(target);this._rpc.response(peer,query,{id:this._rpc.id},nodes)}_ongetpeers(query,peer){const host=peer.address||peer.host,infoHash=query.a.info_hash;if(!infoHash)return this._rpc.error(peer,query,[203,"`get_peers` missing required `a.info_hash` field"]);this.emit("get_peers",infoHash);const r={id:this._rpc.id,token:this._generateToken(host)},peers=this._peers.get(infoHash.toString("hex"));peers.length?(r.values=peers,this._rpc.response(peer,query,r)):this._rpc.response(peer,query,r,this._rpc.nodes.closest(infoHash))}_onannouncepeer(query,peer){const host=peer.address||peer.host,port=query.a.implied_port?peer.port:query.a.port;if(!port||"number"!=typeof port||0>=port||65535prev.seq))return this._rpc.error(peer,query,[302,"sequence number less than current"]);this._values.set(keyHex,{v,k:a.k,salt:a.salt,sig:a.sig,seq:a.seq,id})}else this._values.set(keyHex,{v,id});this._rpc.response(peer,query,{id:this._rpc.id})}_bootstrap(populate){function ready(){self.ready||(self._debug("emit ready"),self.ready=!0,self.emit("ready"))}const self=this;return populate?void this._rpc.populate(self._rpc.id,{q:"find_node",a:{id:self._rpc.id,target:self._rpc.id}},ready):process.nextTick(ready)}_closest(target,message,onmessage,cb){const self=this,table=new KBucket({localNodeId:target,numberOfNodesPerKBucket:this._rpc.k});this._rpc.closest(target,message,function(message,node){return!message.r||(message.r.token&&message.r.id&&Buffer.isBuffer(message.r.id)&&message.r.id.length===self._hashLength&&(self._debug("found node %s (target: %s)",message.r.id,target),table.add({id:message.r.id,host:node.host||node.address,port:node.port,token:message.r.token})),!onmessage||onmessage(message,node))},function(err,n){return err?cb(err):void(self._tables.set(target.toString("hex"),table),self._debug("visited %d nodes",n),cb(null,n))})}_debug(){if(debug.enabled){const args=[].slice.call(arguments);args[0]=`[${this.nodeId.toString("hex").substring(0,7)}] ${args[0]}`;for(let i=1;i */const dgram=require("dgram"),EventEmitter=require("events").EventEmitter,debug=require("debug")("bittorrent-lsd"),LSD_HOST="239.192.152.143",LSD_PORT=6771;module.exports=class LSD extends EventEmitter{constructor(opts={}){if(super(),!opts.peerId)throw new Error("Option `peerId` is required");if(!opts.infoHash)throw new Error("Option `infoHash` is required");if(!opts.port)throw new Error("Option `port` is required");this.peerId="string"==typeof opts.peerId?opts.peerId:opts.peerId.toString("hex"),this.infoHash="string"==typeof opts.infoHash?opts.infoHash.toLowerCase():opts.infoHash.toString("hex"),this.port="string"==typeof opts.port?opts.port:opts.port.toString(),this.cookie=`bittorrent-lsd-${this.peerId}`,this.destroyed=!1,this.annouceIntervalId=null,this.server=dgram.createSocket({type:"udp4",reuseAddr:!0});this.server.on("listening",()=>{debug("listening");try{this.server.addMembership(LSD_HOST)}catch(err){this.emit("warning",err)}}),this.server.on("message",(msg,rinfo)=>{debug("message",msg.toString(),`${rinfo.address}:${rinfo.port}`);const parsedAnnounce=this._parseAnnounce(msg.toString());null==parsedAnnounce||parsedAnnounce.cookie===this.cookie||parsedAnnounce.infoHash.forEach(infoHash=>{this.emit("peer",`${rinfo.address}:${parsedAnnounce.port}`,infoHash)})}),this.server.on("error",err=>{this.emit("error",err)})}_parseAnnounce(announce){const checkInfoHash=infoHash=>/^[0-9a-fA-F]{40}$/.test(infoHash);debug("parse announce",announce);const sections=announce.split("\r\n");if("BT-SEARCH * HTTP/1.1"!==sections[0])return this.emit("warning","Invalid LSD announce (header)"),null;const host=sections[1].split("Host: ")[1];if(!(host=>/^(239.192.152.143|\[ff15::efc0:988f\]):6771$/.test(host))(host))return this.emit("warning","Invalid LSD announce (host)"),null;const port=sections[2].split("Port: ")[1];if(!(port=>/^\d+$/.test(port))(port))return this.emit("warning","Invalid LSD announce (port)"),null;const infoHash=sections.filter(section=>section.includes("Infohash: ")).map(section=>section.split("Infohash: ")[1]).filter(infoHash=>checkInfoHash(infoHash));if(0===infoHash.length)return this.emit("warning","Invalid LSD announce (infoHash)"),null;const cookie=sections.filter(section=>section.includes("cookie: ")).map(section=>section.split("cookie: ")[1]).reduce((acc,cur)=>cur,null);return{host:host,port:port,infoHash:infoHash,cookie:cookie}}destroy(cb){this.destroyed||(this.destroyed=!0,debug("destroy"),clearInterval(this.annouceIntervalId),this.server.close(cb))}start(){debug("start"),this.server.bind(LSD_PORT),this._announce(),this.annouceIntervalId=setInterval(()=>{this._announce()},3e5)}_announce(){debug("send announce");const announce=`BT-SEARCH * HTTP/1.1\r\nHost: ${`${LSD_HOST}:${LSD_PORT}`}\r\nPort: ${this.port}\r\nInfohash: ${this.infoHash}\r\ncookie: ${this.cookie}\r\n\r\n\r\n`;this.server.send(announce,LSD_PORT,LSD_HOST)}}},{debug:69,dgram:63,events:39}],25:[function(require,module){(function(Buffer){(function(){/*! bittorrent-protocol. MIT License. WebTorrent LLC */const arrayRemove=require("unordered-array-remove"),bencode=require("bencode"),BitField=require("bitfield").default,debug=require("debug")("bittorrent-protocol"),randombytes=require("randombytes"),speedometer=require("speedometer"),stream=require("readable-stream"),MESSAGE_PROTOCOL=Buffer.from("\x13BitTorrent protocol"),MESSAGE_KEEP_ALIVE=Buffer.from([0,0,0,0]),MESSAGE_CHOKE=Buffer.from([0,0,0,1,0]),MESSAGE_UNCHOKE=Buffer.from([0,0,0,1,1]),MESSAGE_INTERESTED=Buffer.from([0,0,0,1,2]),MESSAGE_UNINTERESTED=Buffer.from([0,0,0,1,3]),MESSAGE_RESERVED=[0,0,0,0,0,0,0,0],MESSAGE_PORT=[0,0,0,3,9,0,0];class Request{constructor(piece,offset,length,callback){this.piece=piece,this.offset=offset,this.length=length,this.callback=callback}}class Wire extends stream.Duplex{constructor(){super(),this._debugId=randombytes(4).toString("hex"),this._debug("new wire"),this.peerId=null,this.peerIdBuffer=null,this.type=null,this.amChoking=!0,this.amInterested=!1,this.peerChoking=!0,this.peerInterested=!1,this.peerPieces=new BitField(0,{grow:4e5}),this.peerExtensions={},this.requests=[],this.peerRequests=[],this.extendedMapping={},this.peerExtendedMapping={},this.extendedHandshake={},this.peerExtendedHandshake={},this._ext={},this._nextExt=1,this.uploaded=0,this.downloaded=0,this.uploadSpeed=speedometer(),this.downloadSpeed=speedometer(),this._keepAliveInterval=null,this._timeout=null,this._timeoutMs=0,this.destroyed=!1,this._finished=!1,this._parserSize=0,this._parser=null,this._buffer=[],this._bufferSize=0,this.once("finish",()=>this._onFinish()),this._parseHandshake()}setKeepAlive(enable){this._debug("setKeepAlive %s",enable),clearInterval(this._keepAliveInterval);!1===enable||(this._keepAliveInterval=setInterval(()=>{this.keepAlive()},55e3))}setTimeout(ms,unref){this._debug("setTimeout ms=%d unref=%s",ms,unref),this._clearTimeout(),this._timeoutMs=ms,this._timeoutUnref=!!unref,this._updateTimeout()}destroy(){this.destroyed||(this.destroyed=!0,this._debug("destroy"),this.emit("close"),this.end())}end(...args){this._debug("end"),this._onUninterested(),this._onChoke(),super.end(...args)}use(Extension){function noop(){}const name=Extension.prototype.name;if(!name)throw new Error("Extension class requires a \"name\" property on the prototype");this._debug("use extension.name=%s",name);const ext=this._nextExt,handler=new Extension(this);"function"!=typeof handler.onHandshake&&(handler.onHandshake=noop),"function"!=typeof handler.onExtendedHandshake&&(handler.onExtendedHandshake=noop),"function"!=typeof handler.onMessage&&(handler.onMessage=noop),this.extendedMapping[ext]=name,this._ext[name]=handler,this[name]=handler,this._nextExt+=1}keepAlive(){this._debug("keep-alive"),this._push(MESSAGE_KEEP_ALIVE)}handshake(infoHash,peerId,extensions){let infoHashBuffer,peerIdBuffer;if("string"==typeof infoHash?(infoHash=infoHash.toLowerCase(),infoHashBuffer=Buffer.from(infoHash,"hex")):(infoHashBuffer=infoHash,infoHash=infoHashBuffer.toString("hex")),"string"==typeof peerId?peerIdBuffer=Buffer.from(peerId,"hex"):(peerIdBuffer=peerId,peerId=peerIdBuffer.toString("hex")),20!==infoHashBuffer.length||20!==peerIdBuffer.length)throw new Error("infoHash and peerId MUST have length 20");this._debug("handshake i=%s p=%s exts=%o",infoHash,peerId,extensions);const reserved=Buffer.from(MESSAGE_RESERVED);reserved[5]|=16,extensions&&extensions.dht&&(reserved[7]|=1),this._push(Buffer.concat([MESSAGE_PROTOCOL,reserved,infoHashBuffer,peerIdBuffer])),this._handshakeSent=!0,this.peerExtensions.extended&&!this._extendedHandshakeSent&&this._sendExtendedHandshake()}_sendExtendedHandshake(){const msg=Object.assign({},this.extendedHandshake);for(const ext in msg.m={},this.extendedMapping){const name=this.extendedMapping[ext];msg.m[name]=+ext}this.extended(0,bencode.encode(msg)),this._extendedHandshakeSent=!0}choke(){if(!this.amChoking){for(this.amChoking=!0,this._debug("choke");this.peerRequests.length;)this.peerRequests.pop();this._push(MESSAGE_CHOKE)}}unchoke(){this.amChoking&&(this.amChoking=!1,this._debug("unchoke"),this._push(MESSAGE_UNCHOKE))}interested(){this.amInterested||(this.amInterested=!0,this._debug("interested"),this._push(MESSAGE_INTERESTED))}uninterested(){this.amInterested&&(this.amInterested=!1,this._debug("uninterested"),this._push(MESSAGE_UNINTERESTED))}have(index){this._debug("have %d",index),this._message(4,[index],null)}bitfield(bitfield){this._debug("bitfield"),Buffer.isBuffer(bitfield)||(bitfield=bitfield.buffer),this._message(5,[],bitfield)}request(index,offset,length,cb){return cb||(cb=()=>{}),this._finished?cb(new Error("wire is closed")):this.peerChoking?cb(new Error("peer is choking")):void(this._debug("request index=%d offset=%d length=%d",index,offset,length),this.requests.push(new Request(index,offset,length,cb)),this._updateTimeout(),this._message(6,[index,offset,length],null))}piece(index,offset,buffer){this._debug("piece index=%d offset=%d",index,offset),this.uploaded+=buffer.length,this.uploadSpeed(buffer.length),this.emit("upload",buffer.length),this._message(7,[index,offset],buffer)}cancel(index,offset,length){this._debug("cancel index=%d offset=%d length=%d",index,offset,length),this._callback(this._pull(this.requests,index,offset,length),new Error("request was cancelled"),null),this._message(8,[index,offset,length],null)}port(port){this._debug("port %d",port);const message=Buffer.from(MESSAGE_PORT);message.writeUInt16BE(port,5),this._push(message)}extended(ext,obj){if(this._debug("extended ext=%s",ext),"string"==typeof ext&&this.peerExtendedMapping[ext]&&(ext=this.peerExtendedMapping[ext]),"number"==typeof ext){const extId=Buffer.from([ext]),buf=Buffer.isBuffer(obj)?obj:bencode.encode(obj);this._message(20,[],Buffer.concat([extId,buf]))}else throw new Error(`Unrecognized extension: ${ext}`)}_read(){}_message(id,numbers,data){const dataLength=data?data.length:0,buffer=Buffer.allocUnsafe(5+4*numbers.length);buffer.writeUInt32BE(buffer.length+dataLength-4,0),buffer[4]=id;for(let i=0;irequest===this._pull(this.peerRequests,index,offset,length)?err?this._debug("error satisfying request index=%d offset=%d length=%d (%s)",index,offset,length,err.message):void this.piece(index,offset,buffer):void 0,request=new Request(index,offset,length,respond);this.peerRequests.push(request),this.emit("request",index,offset,length,respond)}_onPiece(index,offset,buffer){this._debug("got piece index=%d offset=%d",index,offset),this._callback(this._pull(this.requests,index,offset,buffer.length),null,buffer),this.downloaded+=buffer.length,this.downloadSpeed(buffer.length),this.emit("download",buffer.length),this.emit("piece",index,offset,buffer)}_onCancel(index,offset,length){this._debug("got cancel index=%d offset=%d length=%d",index,offset,length),this._pull(this.peerRequests,index,offset,length),this.emit("cancel",index,offset,length)}_onPort(port){this._debug("got port %d",port),this.emit("port",port)}_onExtended(ext,buf){if(0===ext){let info;try{info=bencode.decode(buf)}catch(err){this._debug("ignoring invalid extended handshake: %s",err.message||err)}if(!info)return;this.peerExtendedHandshake=info;if("object"==typeof info.m)for(var name in info.m)this.peerExtendedMapping[name]=+info.m[name].toString();for(name in this._ext)this.peerExtendedMapping[name]&&this._ext[name].onExtendedHandshake(this.peerExtendedHandshake);this._debug("got extended handshake"),this.emit("extended","handshake",this.peerExtendedHandshake)}else this.extendedMapping[ext]&&(ext=this.extendedMapping[ext],this._ext[ext]&&this._ext[ext].onMessage(buf)),this._debug("got extended message ext=%s",ext),this.emit("extended",ext,buf)}_onTimeout(){this._debug("request timed out"),this._callback(this.requests.shift(),new Error("request has timed out"),null),this.emit("timeout")}_write(data,encoding,cb){for(this._bufferSize+=data.length,this._buffer.push(data);this._bufferSize>=this._parserSize;){const buffer=1===this._buffer.length?this._buffer[0]:Buffer.concat(this._buffer);this._bufferSize-=this._parserSize,this._buffer=this._bufferSize?[buffer.slice(this._parserSize)]:[],this._parser(buffer.slice(0,this._parserSize))}cb(null)}_callback(request,err,buffer){request&&(this._clearTimeout(),!this.peerChoking&&!this._finished&&this._updateTimeout(),request.callback(err,buffer))}_clearTimeout(){this._timeout&&(clearTimeout(this._timeout),this._timeout=null)}_updateTimeout(){this._timeoutMs&&this.requests.length&&!this._timeout&&(this._timeout=setTimeout(()=>this._onTimeout(),this._timeoutMs),this._timeoutUnref&&this._timeout.unref&&this._timeout.unref())}_parse(size,parser){this._parserSize=size,this._parser=parser}_onMessageLength(buffer){const length=buffer.readUInt32BE(0);0{const pstrlen=buffer.readUInt8(0);this._parse(pstrlen+48,handshake=>{const protocol=handshake.slice(0,pstrlen);return"BitTorrent protocol"===protocol.toString()?void(handshake=handshake.slice(pstrlen),this._onHandshake(handshake.slice(8,28),handshake.slice(28,48),{dht:!!(1&handshake[7]),extended:!!(16&handshake[5])}),this._parse(4,this._onMessageLength)):(this._debug("Error: wire not speaking BitTorrent protocol (%s)",protocol.toString()),void this.end())})})}_onFinish(){for(this._finished=!0,this.push(null);this.read(););for(clearInterval(this._keepAliveInterval),this._parse(Number.MAX_VALUE,()=>{});this.peerRequests.length;)this.peerRequests.pop();for(;this.requests.length;)this._callback(this.requests.pop(),new Error("wire was closed"),null)}_debug(...args){args[0]=`[${this._debugId}] ${args[0]}`,debug(...args)}_pull(requests,piece,offset,length){for(let i=0;i(announceUrl=announceUrl.toString(),"/"===announceUrl[announceUrl.length-1]&&(announceUrl=announceUrl.substring(0,announceUrl.length-1)),announceUrl)),announce=Array.from(new Set(announce));const webrtcSupport=!1!==this._wrtc&&(!!this._wrtc||Peer.WEBRTC_SUPPORT),nextTickWarn=err=>{process.nextTick(()=>{this.emit("warning",err)})};this._trackers=announce.map(announceUrl=>{let parsedUrl;try{parsedUrl=new URL(announceUrl)}catch(err){return nextTickWarn(new Error(`Invalid tracker URL: ${announceUrl}`)),null}const port=parsedUrl.port;if(0>port||65535{tracker.setInterval()})}stop(opts){opts=this._defaultAnnounceOpts(opts),opts.event="stopped",debug("send `stop` %o",opts),this._announce(opts)}complete(opts){opts||(opts={}),opts=this._defaultAnnounceOpts(opts),opts.event="completed",debug("send `complete` %o",opts),this._announce(opts)}update(opts){opts=this._defaultAnnounceOpts(opts),opts.event&&delete opts.event,debug("send `update` %o",opts),this._announce(opts)}_announce(opts){this._trackers.forEach(tracker=>{tracker.announce(opts)})}scrape(opts){debug("send `scrape`"),opts||(opts={}),this._trackers.forEach(tracker=>{tracker.scrape(opts)})}setInterval(intervalMs){debug("setInterval %d",intervalMs),this._trackers.forEach(tracker=>{tracker.setInterval(intervalMs)})}destroy(cb){if(!this.destroyed){this.destroyed=!0,debug("destroy");const tasks=this._trackers.map(tracker=>cb=>{tracker.destroy(cb)});parallel(tasks,cb),this._trackers=[],this._getAnnounceOpts=null}}_defaultAnnounceOpts(opts={}){return null==opts.numwant&&(opts.numwant=common.DEFAULT_ANNOUNCE_PEERS),null==opts.uploaded&&(opts.uploaded=0),null==opts.downloaded&&(opts.downloaded=0),this._getAnnounceOpts&&(opts=Object.assign({},opts,this._getAnnounceOpts())),opts}}Client.scrape=(opts,cb)=>{if(cb=once(cb),!opts.infoHash)throw new Error("Option `infoHash` is required");if(!opts.announce)throw new Error("Option `announce` is required");const clientOpts=Object.assign({},opts,{infoHash:Array.isArray(opts.infoHash)?opts.infoHash[0]:opts.infoHash,peerId:Buffer.from("01234567890123456789"),port:6881}),client=new Client(clientOpts);client.once("error",cb),client.once("warning",cb);let len=Array.isArray(opts.infoHash)?opts.infoHash.length:1;const results={};return client.on("scrape",data=>{if(len-=1,results[data.infoHash]=data,0===len){client.destroy();const keys=Object.keys(results);1===keys.length?cb(null,results[keys[0]]):cb(null,results)}}),opts.infoHash=Array.isArray(opts.infoHash)?opts.infoHash.map(infoHash=>Buffer.from(infoHash,"hex")):Buffer.from(opts.infoHash,"hex"),client.scrape({infoHash:opts.infoHash}),client},module.exports=Client}).call(this)}).call(this,require("_process"),require("buffer").Buffer)},{"./lib/client/http-tracker":27,"./lib/client/udp-tracker":29,"./lib/client/websocket-tracker":30,"./lib/common":32,_process:132,buffer:38,debug:69,events:39,once:129,"run-parallel":162,"simple-peer":168}],27:[function(require,module){(function(Buffer){(function(){const arrayRemove=require("unordered-array-remove"),bencode=require("bencode"),compact2string=require("compact2string"),debug=require("debug")("bittorrent-tracker:http-tracker"),get=require("simple-get"),common=require("../common"),Tracker=require("./tracker");class HTTPTracker extends Tracker{constructor(client,announceUrl){super(client,announceUrl),debug("new http tracker %s",announceUrl),this.scrapeUrl=null;const match=this.announceUrl.match(/\/(announce)[^/]*$/);if(match){const pre=this.announceUrl.slice(0,match.index),post=this.announceUrl.slice(match.index+9);this.scrapeUrl=`${pre}/scrape${post}`}this.cleanupFns=[],this.maybeDestroyCleanup=null}announce(opts){if(!this.destroyed){const params=Object.assign({},opts,{compact:null==opts.compact?1:opts.compact,info_hash:this.client._infoHashBinary,peer_id:this.client._peerIdBinary,port:this.client._port});this._trackerId&&(params.trackerid=this._trackerId),this._request(this.announceUrl,params,(err,data)=>err?this.client.emit("warning",err):void this._onAnnounceResponse(data))}}scrape(opts){if(this.destroyed)return;if(!this.scrapeUrl)return void this.client.emit("error",new Error(`scrape not supported ${this.announceUrl}`));const infoHashes=Array.isArray(opts.infoHash)&&0infoHash.toString("binary")):opts.infoHash&&opts.infoHash.toString("binary")||this.client._infoHashBinary;this._request(this.scrapeUrl,{info_hash:infoHashes},(err,data)=>err?this.client.emit("warning",err):void this._onScrapeResponse(data))}destroy(cb){function destroyCleanup(){timeout&&(clearTimeout(timeout),timeout=null),self.maybeDestroyCleanup=null,self.cleanupFns.slice(0).forEach(cleanup=>{cleanup()}),self.cleanupFns=[],cb(null)}const self=this;if(this.destroyed)return cb(null);if(this.destroyed=!0,clearInterval(this.interval),0===this.cleanupFns.length)return destroyCleanup();var timeout=setTimeout(destroyCleanup,common.DESTROY_TIMEOUT);this.maybeDestroyCleanup=()=>{0===this.cleanupFns.length&&destroyCleanup()}}_request(requestUrl,params,cb){function cleanup(){request&&(arrayRemove(self.cleanupFns,self.cleanupFns.indexOf(cleanup)),request.abort(),request=null),self.maybeDestroyCleanup&&self.maybeDestroyCleanup()}const self=this,u=requestUrl+(requestUrl.includes("?")?"&":"?")+common.querystringStringify(params);this.cleanupFns.push(cleanup);let request=get.concat({url:u,timeout:common.REQUEST_TIMEOUT,headers:{"user-agent":this.client._userAgent||""}},function(err,res,data){if(cleanup(),!self.destroyed){if(err)return cb(err);if(200!==res.statusCode)return cb(new Error(`Non-200 response code ${res.statusCode} from ${self.announceUrl}`));if(!data||0===data.length)return cb(new Error(`Invalid tracker response from${self.announceUrl}`));try{data=bencode.decode(data)}catch(err){return cb(new Error(`Error decoding tracker response: ${err.message}`))}const failure=data["failure reason"];if(failure)return debug(`failure from ${requestUrl} (${failure})`),cb(new Error(failure));const warning=data["warning message"];warning&&(debug(`warning from ${requestUrl} (${warning})`),self.client.emit("warning",new Error(warning))),debug(`response from ${requestUrl}`),cb(null,data)}})}_onAnnounceResponse(data){const interval=data.interval||data["min interval"];interval&&this.setInterval(1e3*interval);const trackerId=data["tracker id"];trackerId&&(this._trackerId=trackerId);const response=Object.assign({},data,{announce:this.announceUrl,infoHash:common.binaryToHex(data.info_hash)});this.client.emit("update",response);let addrs;if(Buffer.isBuffer(data.peers)){try{addrs=compact2string.multi(data.peers)}catch(err){return this.client.emit("warning",err)}addrs.forEach(addr=>{this.client.emit("peer",addr)})}else Array.isArray(data.peers)&&data.peers.forEach(peer=>{this.client.emit("peer",`${peer.ip}:${peer.port}`)});if(Buffer.isBuffer(data.peers6)){try{addrs=compact2string.multi6(data.peers6)}catch(err){return this.client.emit("warning",err)}addrs.forEach(addr=>{this.client.emit("peer",addr)})}else Array.isArray(data.peers6)&&data.peers6.forEach(peer=>{const ip=/^\[/.test(peer.ip)||!/:/.test(peer.ip)?peer.ip:`[${peer.ip}]`;this.client.emit("peer",`${ip}:${peer.port}`)})}_onScrapeResponse(data){data=data.files||data.host||{};const keys=Object.keys(data);return 0===keys.length?void this.client.emit("warning",new Error("invalid scrape response")):void keys.forEach(infoHash=>{const response=Object.assign(data[infoHash],{announce:this.announceUrl,infoHash:common.binaryToHex(infoHash)});this.client.emit("scrape",response)})}}HTTPTracker.prototype.DEFAULT_ANNOUNCE_INTERVAL=1800000,module.exports=HTTPTracker}).call(this)}).call(this,{isBuffer:require("../../../is-buffer/index.js")})},{"../../../is-buffer/index.js":101,"../common":32,"./tracker":28,bencode:19,compact2string:67,debug:69,"simple-get":167,"unordered-array-remove":191}],28:[function(require,module){const EventEmitter=require("events");module.exports=class Tracker extends EventEmitter{constructor(client,announceUrl){super(),this.client=client,this.announceUrl=announceUrl,this.interval=null,this.destroyed=!1}setInterval(intervalMs){null==intervalMs&&(intervalMs=this.DEFAULT_ANNOUNCE_INTERVAL),clearInterval(this.interval),intervalMs&&(this.interval=setInterval(()=>{this.announce(this.client._defaultAnnounceOpts())},intervalMs),this.interval.unref&&this.interval.unref())}}},{events:39}],29:[function(require,module){(function(Buffer){(function(){function genTransactionId(){return randombytes(4)}function toUInt16(n){const buf=Buffer.allocUnsafe(2);return buf.writeUInt16BE(n,0),buf}function toUInt64(n){if(n>MAX_UINT||"string"==typeof n){const bytes=new BN(n).toArray();for(;8>bytes.length;)bytes.unshift(0);return Buffer.from(bytes)}return Buffer.concat([common.toUInt32(0),common.toUInt32(n)])}function noop(){}const arrayRemove=require("unordered-array-remove"),BN=require("bn.js"),compact2string=require("compact2string"),debug=require("debug")("bittorrent-tracker:udp-tracker"),dgram=require("dgram"),randombytes=require("randombytes"),common=require("../common"),Tracker=require("./tracker");class UDPTracker extends Tracker{constructor(client,announceUrl){super(client,announceUrl),debug("new udp tracker %s",announceUrl),this.cleanupFns=[],this.maybeDestroyCleanup=null}announce(opts){this.destroyed||this._request(opts)}scrape(opts){this.destroyed||(opts._scrape=!0,this._request(opts))}destroy(cb){function destroyCleanup(){timeout&&(clearTimeout(timeout),timeout=null),self.maybeDestroyCleanup=null,self.cleanupFns.slice(0).forEach(cleanup=>{cleanup()}),self.cleanupFns=[],cb(null)}const self=this;if(this.destroyed)return cb(null);if(this.destroyed=!0,clearInterval(this.interval),0===this.cleanupFns.length)return destroyCleanup();var timeout=setTimeout(destroyCleanup,common.DESTROY_TIMEOUT);this.maybeDestroyCleanup=()=>{0===this.cleanupFns.length&&destroyCleanup()}}_request(opts){function cleanup(){if(timeout&&(clearTimeout(timeout),timeout=null),socket){arrayRemove(self.cleanupFns,self.cleanupFns.indexOf(cleanup)),socket.removeListener("error",onError),socket.removeListener("message",onSocketMessage),socket.on("error",noop);try{socket.close()}catch(err){}socket=null}self.maybeDestroyCleanup&&self.maybeDestroyCleanup()}function onError(err){if(cleanup(),!self.destroyed){try{err.message&&(err.message+=` (${self.announceUrl})`)}catch(ignoredErr){}self.client.emit("warning",err)}}function onSocketMessage(msg){if(8>msg.length||msg.readUInt32BE(4)!==transactionId.readUInt32BE(0))return onError(new Error("tracker sent invalid transaction id"));const action=msg.readUInt32BE(0);switch(debug("UDP response %s, action %s",self.announceUrl,action),action){case 0:{if(16>msg.length)return onError(new Error("invalid udp handshake"));opts._scrape?scrape(msg.slice(8,16)):announce(msg.slice(8,16),opts);break}case 1:{if(cleanup(),self.destroyed)return;if(20>msg.length)return onError(new Error("invalid announce message"));const interval=msg.readUInt32BE(8);interval&&self.setInterval(1e3*interval),self.client.emit("update",{announce:self.announceUrl,complete:msg.readUInt32BE(16),incomplete:msg.readUInt32BE(12)});let addrs;try{addrs=compact2string.multi(msg.slice(20))}catch(err){return self.client.emit("warning",err)}addrs.forEach(addr=>{self.client.emit("peer",addr)});break}case 2:{if(cleanup(),self.destroyed)return;if(20>msg.length||0!=(msg.length-8)%12)return onError(new Error("invalid scrape message"));const infoHashes=Array.isArray(opts.infoHash)&&0infoHash.toString("hex")):[opts.infoHash&&opts.infoHash.toString("hex")||self.client.infoHash];for(let i=0,len=(msg.length-8)/12;imsg.length)return onError(new Error("invalid error message"));self.client.emit("warning",new Error(msg.slice(8).toString()));break}default:onError(new Error("tracker sent invalid action"));}}function send(message){socket.send(message,0,message.length,port,hostname)}function announce(connectionId,opts){transactionId=genTransactionId(),send(Buffer.concat([connectionId,common.toUInt32(common.ACTIONS.ANNOUNCE),transactionId,self.client._infoHashBuffer,self.client._peerIdBuffer,toUInt64(opts.downloaded),null==opts.left?Buffer.from("FFFFFFFFFFFFFFFF","hex"):toUInt64(opts.left),toUInt64(opts.uploaded),common.toUInt32(common.EVENTS[opts.event]||0),common.toUInt32(0),common.toUInt32(0),common.toUInt32(opts.numwant),toUInt16(self.client._port)]))}function scrape(connectionId){transactionId=genTransactionId();const infoHash=Array.isArray(opts.infoHash)&&0{"stopped"===opts.event?cleanup():onError(new Error(`tracker request timed out (${opts.event})`)),timeout=null},common.REQUEST_TIMEOUT);timeout.unref&&timeout.unref(),this.cleanupFns.push(cleanup),send(Buffer.concat([common.CONNECTION_ID,common.toUInt32(common.ACTIONS.CONNECT),transactionId])),socket.once("error",onError),socket.on("message",onSocketMessage)}}UDPTracker.prototype.DEFAULT_ANNOUNCE_INTERVAL=1800000;const MAX_UINT=4294967295;module.exports=UDPTracker}).call(this)}).call(this,require("buffer").Buffer)},{"../common":32,"./tracker":28,"bn.js":35,buffer:38,compact2string:67,debug:69,dgram:63,randombytes:140,"unordered-array-remove":191}],30:[function(require,module){function noop(){}const debug=require("debug")("bittorrent-tracker:websocket-tracker"),Peer=require("simple-peer"),randombytes=require("randombytes"),Socket=require("simple-websocket"),common=require("../common"),Tracker=require("./tracker"),socketPool={};class WebSocketTracker extends Tracker{constructor(client,announceUrl){super(client,announceUrl),debug("new websocket tracker %s",announceUrl),this.peers={},this.socket=null,this.reconnecting=!1,this.retries=0,this.reconnectTimer=null,this.expectingResponse=!1,this._openSocket()}announce(opts){if(this.destroyed||this.reconnecting)return;if(!this.socket.connected)return void this.socket.once("connect",()=>{this.announce(opts)});const params=Object.assign({},opts,{action:"announce",info_hash:this.client._infoHashBinary,peer_id:this.client._peerIdBinary});if(this._trackerId&&(params.trackerid=this._trackerId),"stopped"===opts.event||"completed"===opts.event)this._send(params);else{const numwant=_Mathmin(opts.numwant,10);this._generateOffers(numwant,offers=>{params.numwant=numwant,params.offers=offers,this._send(params)})}}scrape(opts){if(this.destroyed||this.reconnecting)return;if(!this.socket.connected)return void this.socket.once("connect",()=>{this.scrape(opts)});const infoHashes=Array.isArray(opts.infoHash)&&0infoHash.toString("binary")):opts.infoHash&&opts.infoHash.toString("binary")||this.client._infoHashBinary;this._send({action:"scrape",info_hash:infoHashes})}destroy(cb=noop){function destroyCleanup(){timeout&&(clearTimeout(timeout),timeout=null),socket.removeListener("data",destroyCleanup),socket.destroy(),socket=null}if(this.destroyed)return cb(null);for(const peerId in this.destroyed=!0,clearInterval(this.interval),clearTimeout(this.reconnectTimer),this.peers){const peer=this.peers[peerId];clearTimeout(peer.trackerTimeout),peer.destroy()}if(this.peers=null,this.socket&&(this.socket.removeListener("connect",this._onSocketConnectBound),this.socket.removeListener("data",this._onSocketDataBound),this.socket.removeListener("close",this._onSocketCloseBound),this.socket.removeListener("error",this._onSocketErrorBound),this.socket=null),this._onSocketConnectBound=null,this._onSocketErrorBound=null,this._onSocketDataBound=null,this._onSocketCloseBound=null,socketPool[this.announceUrl]&&(socketPool[this.announceUrl].consumers-=1),0{this._onSocketConnect()},this._onSocketErrorBound=err=>{this._onSocketError(err)},this._onSocketDataBound=data=>{this._onSocketData(data)},this._onSocketCloseBound=()=>{this._onSocketClose()},this.socket=socketPool[this.announceUrl],this.socket?(socketPool[this.announceUrl].consumers+=1,this.socket.connected&&this._onSocketConnectBound()):(this.socket=socketPool[this.announceUrl]=new Socket(this.announceUrl),this.socket.consumers=1,this.socket.once("connect",this._onSocketConnectBound)),this.socket.on("data",this._onSocketDataBound),this.socket.once("close",this._onSocketCloseBound),this.socket.once("error",this._onSocketErrorBound)}_onSocketConnect(){this.destroyed||this.reconnecting&&(this.reconnecting=!1,this.retries=0,this.announce(this.client._defaultAnnounceOpts()))}_onSocketData(data){if(!this.destroyed){this.expectingResponse=!1;try{data=JSON.parse(data)}catch(err){return void this.client.emit("warning",new Error("Invalid tracker response"))}"announce"===data.action?this._onAnnounceResponse(data):"scrape"===data.action?this._onScrapeResponse(data):this._onSocketError(new Error(`invalid action in WS response: ${data.action}`))}}_onAnnounceResponse(data){if(data.info_hash!==this.client._infoHashBinary)return void debug("ignoring websocket data from %s for %s (looking for %s: reused socket)",this.announceUrl,common.binaryToHex(data.info_hash),this.client.infoHash);if(data.peer_id&&data.peer_id===this.client._peerIdBinary)return;debug("received %s from %s for %s",JSON.stringify(data),this.announceUrl,this.client.infoHash);const failure=data["failure reason"];if(failure)return this.client.emit("warning",new Error(failure));const warning=data["warning message"];warning&&this.client.emit("warning",new Error(warning));const interval=data.interval||data["min interval"];interval&&this.setInterval(1e3*interval);const trackerId=data["tracker id"];if(trackerId&&(this._trackerId=trackerId),null!=data.complete){const response=Object.assign({},data,{announce:this.announceUrl,infoHash:common.binaryToHex(data.info_hash)});this.client.emit("update",response)}let peer;if(data.offer&&data.peer_id&&(debug("creating peer (from remote offer)"),peer=this._createPeer(),peer.id=common.binaryToHex(data.peer_id),peer.once("signal",answer=>{const params={action:"announce",info_hash:this.client._infoHashBinary,peer_id:this.client._peerIdBinary,to_peer_id:data.peer_id,answer,offer_id:data.offer_id};this._trackerId&&(params.trackerid=this._trackerId),this._send(params)}),peer.signal(data.offer),this.client.emit("peer",peer)),data.answer&&data.peer_id){const offerId=common.binaryToHex(data.offer_id);peer=this.peers[offerId],peer?(peer.id=common.binaryToHex(data.peer_id),peer.signal(data.answer),this.client.emit("peer",peer),clearTimeout(peer.trackerTimeout),peer.trackerTimeout=null,delete this.peers[offerId]):debug(`got unexpected answer: ${JSON.stringify(data.answer)}`)}}_onScrapeResponse(data){data=data.files||{};const keys=Object.keys(data);return 0===keys.length?void this.client.emit("warning",new Error("invalid scrape response")):void keys.forEach(infoHash=>{const response=Object.assign(data[infoHash],{announce:this.announceUrl,infoHash:common.binaryToHex(infoHash)});this.client.emit("scrape",response)})}_onSocketClose(){this.destroyed||(this.destroy(),this._startReconnectTimer())}_onSocketError(err){this.destroyed||(this.destroy(),this.client.emit("warning",err),this._startReconnectTimer())}_startReconnectTimer(){const ms=_Mathfloor(Math.random()*300000)+_Mathmin(_Mathpow(2,this.retries)*10000,3600000);this.reconnecting=!0,clearTimeout(this.reconnectTimer),this.reconnectTimer=setTimeout(()=>{this.retries++,this._openSocket()},ms),this.reconnectTimer.unref&&this.reconnectTimer.unref(),debug("reconnecting socket in %s ms",ms)}_send(params){if(!this.destroyed){this.expectingResponse=!0;const message=JSON.stringify(params);debug("send %s",message),this.socket.send(message)}}_generateOffers(numwant,cb){function generateOffer(){const offerId=randombytes(20).toString("hex");debug("creating peer (from _generateOffers)");const peer=self.peers[offerId]=self._createPeer({initiator:!0});peer.once("signal",offer=>{offers.push({offer,offer_id:common.hexToBinary(offerId)}),checkDone()}),peer.trackerTimeout=setTimeout(()=>{debug("tracker timeout: destroying peer"),peer.trackerTimeout=null,delete self.peers[offerId],peer.destroy()},50000),peer.trackerTimeout.unref&&peer.trackerTimeout.unref()}function checkDone(){offers.length===numwant&&(debug("generated %s offers",numwant),cb(offers))}const self=this,offers=[];debug("generating %s offers",numwant);for(let i=0;i */module.exports=function(blob,cb){function onLoadEnd(e){reader.removeEventListener("loadend",onLoadEnd,!1),e.error?cb(e.error):cb(null,Buffer.from(reader.result))}if("undefined"==typeof Blob||!(blob instanceof Blob))throw new Error("first argument must be a Blob");if("function"!=typeof cb)throw new Error("second argument must be a function");const reader=new FileReader;reader.addEventListener("loadend",onLoadEnd,!1),reader.readAsArrayBuffer(blob)}}).call(this)}).call(this,require("buffer").Buffer)},{buffer:38}],34:[function(require,module){(function(Buffer){(function(){const{Transform}=require("readable-stream");module.exports=class Block extends Transform{constructor(size,opts={}){super(opts),"object"==typeof size&&(opts=size,size=opts.size),this.size=size||512;const{nopad,zeroPadding=!0}=opts;this._zeroPadding=!nopad&&!!zeroPadding,this._buffered=[],this._bufferedBytes=0}_transform(buf,enc,next){for(this._bufferedBytes+=buf.length,this._buffered.push(buf);this._bufferedBytes>=this.size;){const b=Buffer.concat(this._buffered);this._bufferedBytes-=this.size,this.push(b.slice(0,this.size)),this._buffered=[b.slice(this.size,b.length)]}next()}_flush(){if(this._bufferedBytes&&this._zeroPadding){const zeroes=Buffer.alloc(this.size-this._bufferedBytes);this._buffered.push(zeroes),this.push(Buffer.concat(this._buffered)),this._buffered=null}else this._bufferedBytes&&(this.push(Buffer.concat(this._buffered)),this._buffered=null);this.push(null)}}}).call(this)}).call(this,require("buffer").Buffer)},{buffer:38,"readable-stream":157}],35:[function(require,module){(function(module,exports){'use strict';var _Mathimul=Math.imul,_Mathclz=Math.clz32;function assert(val,msg){if(!val)throw new Error(msg||"Assertion failed")}function inherits(ctor,superCtor){ctor.super_=superCtor;var TempCtor=function(){};TempCtor.prototype=superCtor.prototype,ctor.prototype=new TempCtor,ctor.prototype.constructor=ctor}function BN(number,base,endian){return BN.isBN(number)?number:void(this.negative=0,this.words=null,this.length=0,this.red=null,null!==number&&(("le"===base||"be"===base)&&(endian=base,base=10),this._init(number||0,base||10,endian||"be")))}function parseHex(str,start,end){for(var r=0,len=_Mathmin(str.length,end),z=0,i=start,c;i=c?c-49+10:17<=c&&22>=c?c-17+10:c,r|=b,z|=b}return assert(!(240&z),"Invalid character in "+str),r}function parseBase(str,start,end,mul){for(var r=0,b=0,len=_Mathmin(str.length,end),i=start,c;i"}function toBitArray(num){for(var w=Array(num.bitLength()),bit=0;bit>>wbit}return w}function smallMulTo(self,num,out){out.negative=num.negative^self.negative;var len=0|self.length+num.length;out.length=len,len=0|len-1;var a=0|self.words[0],b=0|num.words[0],r=a*b,lo=67108863&r,carry=0|r/67108864;out.words[0]=lo;for(var k=1;k>>26,rword=67108863&carry,maxJ=_Mathmin(k,num.length-1),j=_Mathmax(0,k-self.length+1),i;j<=maxJ;j++)i=0|k-j,a=0|self.words[i],b=0|num.words[j],r=a*b+rword,ncarry+=0|r/67108864,rword=67108863&r;out.words[k]=0|rword,carry=0|ncarry}return 0===carry?out.length--:out.words[k]=0|carry,out._strip()}function bigMulTo(self,num,out){out.negative=num.negative^self.negative,out.length=self.length+num.length;for(var carry=0,hncarry=0,k=0,ncarry;k>>26),hncarry+=ncarry>>>26,ncarry&=67108863}out.words[k]=rword,carry=ncarry,ncarry=hncarry}return 0===carry?out.length--:out.words[k]=carry,out._strip()}function jumboMulTo(self,num,out){return bigMulTo(self,num,out)}function FFTM(x,y){this.x=x,this.y=y}function MPrime(name,p){this.name=name,this.p=new BN(p,16),this.n=this.p.bitLength(),this.k=new BN(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}function K256(){MPrime.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function P224(){MPrime.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function P192(){MPrime.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function P25519(){MPrime.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function Red(m){if("string"==typeof m){var prime=BN._prime(m);this.m=prime.p,this.prime=prime}else assert(m.gtn(1),"modulus must be greater than 1"),this.m=m,this.prime=null}function Mont(m){Red.call(this,m),this.shift=this.m.bitLength(),0!=this.shift%26&&(this.shift+=26-this.shift%26),this.r=new BN(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}"object"==typeof module?module.exports=BN:exports.BN=BN,BN.BN=BN,BN.wordSize=26;var Buffer;try{Buffer=require("buffer").Buffer}catch(e){}if(BN.isBN=function(num){return!!(num instanceof BN)||null!==num&&"object"==typeof num&&num.constructor.wordSize===BN.wordSize&&Array.isArray(num.words)},BN.max=function(left,right){return 0left.cmp(right)?left:right},BN.prototype._init=function(number,base,endian){if("number"==typeof number)return this._initNumber(number,base,endian);if("object"==typeof number)return this._initArray(number,base,endian);"hex"===base&&(base=16),assert(base===(0|base)&&2<=base&&36>=base),number=number.toString().replace(/\s+/g,"");var start=0;"-"===number[0]&&start++,16===base?this._parseHex(number,start):this._parseBase(number,base,start),"-"===number[0]&&(this.negative=1),this._strip(),"le"!==endian||this._initArray(this.toArray(),base,endian)},BN.prototype._initNumber=function(number,base,endian){0>number&&(this.negative=1,number=-number),67108864>number?(this.words=[67108863&number],this.length=1):4503599627370496>number?(this.words=[67108863&number,67108863&number/67108864],this.length=2):(assert(9007199254740992>number),this.words=[67108863&number,67108863&number/67108864,1],this.length=3),"le"!==endian||this._initArray(this.toArray(),base,endian)},BN.prototype._initArray=function(number,base,endian){if(assert("number"==typeof number.length),0>=number.length)return this.words=[0],this.length=1,this;this.length=_Mathceil(number.length/3),this.words=Array(this.length);for(var i=0;i>>26-off,off+=24,26<=off&&(off-=26,j++);else if("le"===endian)for(i=0,j=0;i>>26-off,off+=24,26<=off&&(off-=26,j++);return this._strip()},BN.prototype._parseHex=function(number,start){this.length=_Mathceil((number.length-start)/6),this.words=Array(this.length);for(var i=0;i=start;i-=6)w=parseHex(number,i,i+6),this.words[j]|=67108863&w<>>26-off,off+=24,26<=off&&(off-=26,j++);i+6!==start&&(w=parseHex(number,start,i+6),this.words[j]|=67108863&w<>>26-off),this._strip()},BN.prototype._parseBase=function(number,base,start){this.words=[0],this.length=1;for(var limbLen=0,limbPow=1;67108863>=limbPow;limbPow*=base)limbLen++;limbLen--,limbPow=0|limbPow/base;for(var total=number.length-start,mod=total%limbLen,end=_Mathmin(total,total-mod)+start,word=0,i=start;ithis.words[0]+word?this.words[0]+=word:this._iaddn(word);if(0!==mod){var pow=1;for(word=parseBase(number,i,number.length,base),i=0;ithis.words[0]+word?this.words[0]+=word:this._iaddn(word)}},BN.prototype.copy=function(dest){dest.words=Array(this.length);for(var i=0;i>>24-off,out=0!==carry||i!==this.length-1?zeros[6-word.length]+word+out:word+out,off+=2,26<=off&&(off-=26,i--)}for(0!==carry&&(out=carry.toString(16)+out);0!=out.length%padding;)out="0"+out;return 0!==this.negative&&(out="-"+out),out}if(base===(0|base)&&2<=base&&36>=base){var groupSize=groupSizes[base],groupBase=groupBases[base];out="";var c=this.clone();for(c.negative=0;!c.isZero();){var r=c.modrn(groupBase).toString(base);c=c.idivn(groupBase),out=c.isZero()?r+out:zeros[groupSize-r.length]+r+out}for(this.isZero()&&(out="0"+out);0!=out.length%padding;)out="0"+out;return 0!==this.negative&&(out="-"+out),out}assert(!1,"Base should be between 2 and 36")},BN.prototype.toNumber=function(){var ret=this.words[0];return 2===this.length?ret+=67108864*this.words[1]:3===this.length&&1===this.words[2]?ret+=4503599627370496+67108864*this.words[1]:2>8),position>16),6==shift?(position>24),carry=0,shift=0):(carry=word>>>24,shift+=2);if(position>8),0<=position&&(res[position--]=255&word>>16),6==shift?(0<=position&&(res[position--]=255&word>>24),carry=0,shift=0):(carry=word>>>24,shift+=2);if(0<=position)for(res[position--]=carry;0<=position;)res[position--]=0},BN.prototype._countBits=_Mathclz?function(w){return 32-_Mathclz(w)}:function(w){var t=w,r=0;return 4096<=t&&(r+=13,t>>>=13),64<=t&&(r+=7,t>>>=7),8<=t&&(r+=4,t>>>=4),2<=t&&(r+=2,t>>>=2),r+t},BN.prototype._zeroBits=function(w){if(0===w)return 26;var t=w,r=0;return 0==(8191&t)&&(r+=13,t>>>=13),0==(127&t)&&(r+=7,t>>>=7),0==(15&t)&&(r+=4,t>>>=4),0==(3&t)&&(r+=2,t>>>=2),0==(1&t)&&r++,r},BN.prototype.bitLength=function(){var w=this.words[this.length-1],hi=this._countBits(w);return 26*(this.length-1)+hi},BN.prototype.zeroBits=function(){if(this.isZero())return 0;for(var r=0,i=0,b;inum.length?this.clone().ior(num):num.clone().ior(this)},BN.prototype.uor=function(num){return this.length>num.length?this.clone().iuor(num):num.clone().iuor(this)},BN.prototype.iuand=function(num){var b=this.length>num.length?num:this;for(var i=0;inum.length?this.clone().iand(num):num.clone().iand(this)},BN.prototype.uand=function(num){return this.length>num.length?this.clone().iuand(num):num.clone().iuand(this)},BN.prototype.iuxor=function(num){var a,b;this.length>num.length?(a=this,b=num):(a=num,b=this);for(var i=0;inum.length?this.clone().ixor(num):num.clone().ixor(this)},BN.prototype.uxor=function(num){return this.length>num.length?this.clone().iuxor(num):num.clone().iuxor(this)},BN.prototype.inotn=function(width){assert("number"==typeof width&&0<=width);var bytesNeeded=0|_Mathceil(width/26),bitsLeft=width%26;this._expand(bytesNeeded),0>26-bitsLeft),this._strip()},BN.prototype.notn=function(width){return this.clone().inotn(width)},BN.prototype.setn=function(bit,val){assert("number"==typeof bit&&0<=bit);var off=0|bit/26,wbit=bit%26;return this._expand(off+1),val?this.words[off]|=1<num.length?(a=this,b=num):(a=num,b=this);for(var carry=0,i=0;i>>26;for(;0!==carry&&i>>26;if(this.length=a.length,0!==carry)this.words[this.length]=carry,this.length++;else if(a!==this)for(;inum.length?this.clone().iadd(num):num.clone().iadd(this)},BN.prototype.isub=function(num){if(0!==num.negative){num.negative=0;var r=this.iadd(num);return num.negative=1,r._normSign()}if(0!==this.negative)return this.negative=0,this.iadd(num),this.negative=1,this._normSign();var cmp=this.cmp(num);if(0===cmp)return this.negative=0,this.length=1,this.words[0]=0,this;var a,b;0>26,this.words[i]=67108863&r;for(;0!==carry&&i>26,this.words[i]=67108863&r;if(0===carry&&i>>13,a1=0|a[1],al1=8191&a1,ah1=a1>>>13,a2=0|a[2],al2=8191&a2,ah2=a2>>>13,a3=0|a[3],al3=8191&a3,ah3=a3>>>13,a4=0|a[4],al4=8191&a4,ah4=a4>>>13,a5=0|a[5],al5=8191&a5,ah5=a5>>>13,a6=0|a[6],al6=8191&a6,ah6=a6>>>13,a7=0|a[7],al7=8191&a7,ah7=a7>>>13,a8=0|a[8],al8=8191&a8,ah8=a8>>>13,a9=0|a[9],al9=8191&a9,ah9=a9>>>13,b0=0|b[0],bl0=8191&b0,bh0=b0>>>13,b1=0|b[1],bl1=8191&b1,bh1=b1>>>13,b2=0|b[2],bl2=8191&b2,bh2=b2>>>13,b3=0|b[3],bl3=8191&b3,bh3=b3>>>13,b4=0|b[4],bl4=8191&b4,bh4=b4>>>13,b5=0|b[5],bl5=8191&b5,bh5=b5>>>13,b6=0|b[6],bl6=8191&b6,bh6=b6>>>13,b7=0|b[7],bl7=8191&b7,bh7=b7>>>13,b8=0|b[8],bl8=8191&b8,bh8=b8>>>13,b9=0|b[9],bl9=8191&b9,bh9=b9>>>13,lo,mid,hi;out.negative=self.negative^num.negative,out.length=19,lo=_Mathimul(al0,bl0),mid=_Mathimul(al0,bh0),mid=0|mid+_Mathimul(ah0,bl0),hi=_Mathimul(ah0,bh0);var w0=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w0>>>26),w0&=67108863,lo=_Mathimul(al1,bl0),mid=_Mathimul(al1,bh0),mid=0|mid+_Mathimul(ah1,bl0),hi=_Mathimul(ah1,bh0),lo=0|lo+_Mathimul(al0,bl1),mid=0|mid+_Mathimul(al0,bh1),mid=0|mid+_Mathimul(ah0,bl1),hi=0|hi+_Mathimul(ah0,bh1);var w1=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w1>>>26),w1&=67108863,lo=_Mathimul(al2,bl0),mid=_Mathimul(al2,bh0),mid=0|mid+_Mathimul(ah2,bl0),hi=_Mathimul(ah2,bh0),lo=0|lo+_Mathimul(al1,bl1),mid=0|mid+_Mathimul(al1,bh1),mid=0|mid+_Mathimul(ah1,bl1),hi=0|hi+_Mathimul(ah1,bh1),lo=0|lo+_Mathimul(al0,bl2),mid=0|mid+_Mathimul(al0,bh2),mid=0|mid+_Mathimul(ah0,bl2),hi=0|hi+_Mathimul(ah0,bh2);var w2=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w2>>>26),w2&=67108863,lo=_Mathimul(al3,bl0),mid=_Mathimul(al3,bh0),mid=0|mid+_Mathimul(ah3,bl0),hi=_Mathimul(ah3,bh0),lo=0|lo+_Mathimul(al2,bl1),mid=0|mid+_Mathimul(al2,bh1),mid=0|mid+_Mathimul(ah2,bl1),hi=0|hi+_Mathimul(ah2,bh1),lo=0|lo+_Mathimul(al1,bl2),mid=0|mid+_Mathimul(al1,bh2),mid=0|mid+_Mathimul(ah1,bl2),hi=0|hi+_Mathimul(ah1,bh2),lo=0|lo+_Mathimul(al0,bl3),mid=0|mid+_Mathimul(al0,bh3),mid=0|mid+_Mathimul(ah0,bl3),hi=0|hi+_Mathimul(ah0,bh3);var w3=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w3>>>26),w3&=67108863,lo=_Mathimul(al4,bl0),mid=_Mathimul(al4,bh0),mid=0|mid+_Mathimul(ah4,bl0),hi=_Mathimul(ah4,bh0),lo=0|lo+_Mathimul(al3,bl1),mid=0|mid+_Mathimul(al3,bh1),mid=0|mid+_Mathimul(ah3,bl1),hi=0|hi+_Mathimul(ah3,bh1),lo=0|lo+_Mathimul(al2,bl2),mid=0|mid+_Mathimul(al2,bh2),mid=0|mid+_Mathimul(ah2,bl2),hi=0|hi+_Mathimul(ah2,bh2),lo=0|lo+_Mathimul(al1,bl3),mid=0|mid+_Mathimul(al1,bh3),mid=0|mid+_Mathimul(ah1,bl3),hi=0|hi+_Mathimul(ah1,bh3),lo=0|lo+_Mathimul(al0,bl4),mid=0|mid+_Mathimul(al0,bh4),mid=0|mid+_Mathimul(ah0,bl4),hi=0|hi+_Mathimul(ah0,bh4);var w4=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w4>>>26),w4&=67108863,lo=_Mathimul(al5,bl0),mid=_Mathimul(al5,bh0),mid=0|mid+_Mathimul(ah5,bl0),hi=_Mathimul(ah5,bh0),lo=0|lo+_Mathimul(al4,bl1),mid=0|mid+_Mathimul(al4,bh1),mid=0|mid+_Mathimul(ah4,bl1),hi=0|hi+_Mathimul(ah4,bh1),lo=0|lo+_Mathimul(al3,bl2),mid=0|mid+_Mathimul(al3,bh2),mid=0|mid+_Mathimul(ah3,bl2),hi=0|hi+_Mathimul(ah3,bh2),lo=0|lo+_Mathimul(al2,bl3),mid=0|mid+_Mathimul(al2,bh3),mid=0|mid+_Mathimul(ah2,bl3),hi=0|hi+_Mathimul(ah2,bh3),lo=0|lo+_Mathimul(al1,bl4),mid=0|mid+_Mathimul(al1,bh4),mid=0|mid+_Mathimul(ah1,bl4),hi=0|hi+_Mathimul(ah1,bh4),lo=0|lo+_Mathimul(al0,bl5),mid=0|mid+_Mathimul(al0,bh5),mid=0|mid+_Mathimul(ah0,bl5),hi=0|hi+_Mathimul(ah0,bh5);var w5=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w5>>>26),w5&=67108863,lo=_Mathimul(al6,bl0),mid=_Mathimul(al6,bh0),mid=0|mid+_Mathimul(ah6,bl0),hi=_Mathimul(ah6,bh0),lo=0|lo+_Mathimul(al5,bl1),mid=0|mid+_Mathimul(al5,bh1),mid=0|mid+_Mathimul(ah5,bl1),hi=0|hi+_Mathimul(ah5,bh1),lo=0|lo+_Mathimul(al4,bl2),mid=0|mid+_Mathimul(al4,bh2),mid=0|mid+_Mathimul(ah4,bl2),hi=0|hi+_Mathimul(ah4,bh2),lo=0|lo+_Mathimul(al3,bl3),mid=0|mid+_Mathimul(al3,bh3),mid=0|mid+_Mathimul(ah3,bl3),hi=0|hi+_Mathimul(ah3,bh3),lo=0|lo+_Mathimul(al2,bl4),mid=0|mid+_Mathimul(al2,bh4),mid=0|mid+_Mathimul(ah2,bl4),hi=0|hi+_Mathimul(ah2,bh4),lo=0|lo+_Mathimul(al1,bl5),mid=0|mid+_Mathimul(al1,bh5),mid=0|mid+_Mathimul(ah1,bl5),hi=0|hi+_Mathimul(ah1,bh5),lo=0|lo+_Mathimul(al0,bl6),mid=0|mid+_Mathimul(al0,bh6),mid=0|mid+_Mathimul(ah0,bl6),hi=0|hi+_Mathimul(ah0,bh6);var w6=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w6>>>26),w6&=67108863,lo=_Mathimul(al7,bl0),mid=_Mathimul(al7,bh0),mid=0|mid+_Mathimul(ah7,bl0),hi=_Mathimul(ah7,bh0),lo=0|lo+_Mathimul(al6,bl1),mid=0|mid+_Mathimul(al6,bh1),mid=0|mid+_Mathimul(ah6,bl1),hi=0|hi+_Mathimul(ah6,bh1),lo=0|lo+_Mathimul(al5,bl2),mid=0|mid+_Mathimul(al5,bh2),mid=0|mid+_Mathimul(ah5,bl2),hi=0|hi+_Mathimul(ah5,bh2),lo=0|lo+_Mathimul(al4,bl3),mid=0|mid+_Mathimul(al4,bh3),mid=0|mid+_Mathimul(ah4,bl3),hi=0|hi+_Mathimul(ah4,bh3),lo=0|lo+_Mathimul(al3,bl4),mid=0|mid+_Mathimul(al3,bh4),mid=0|mid+_Mathimul(ah3,bl4),hi=0|hi+_Mathimul(ah3,bh4),lo=0|lo+_Mathimul(al2,bl5),mid=0|mid+_Mathimul(al2,bh5),mid=0|mid+_Mathimul(ah2,bl5),hi=0|hi+_Mathimul(ah2,bh5),lo=0|lo+_Mathimul(al1,bl6),mid=0|mid+_Mathimul(al1,bh6),mid=0|mid+_Mathimul(ah1,bl6),hi=0|hi+_Mathimul(ah1,bh6),lo=0|lo+_Mathimul(al0,bl7),mid=0|mid+_Mathimul(al0,bh7),mid=0|mid+_Mathimul(ah0,bl7),hi=0|hi+_Mathimul(ah0,bh7);var w7=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w7>>>26),w7&=67108863,lo=_Mathimul(al8,bl0),mid=_Mathimul(al8,bh0),mid=0|mid+_Mathimul(ah8,bl0),hi=_Mathimul(ah8,bh0),lo=0|lo+_Mathimul(al7,bl1),mid=0|mid+_Mathimul(al7,bh1),mid=0|mid+_Mathimul(ah7,bl1),hi=0|hi+_Mathimul(ah7,bh1),lo=0|lo+_Mathimul(al6,bl2),mid=0|mid+_Mathimul(al6,bh2),mid=0|mid+_Mathimul(ah6,bl2),hi=0|hi+_Mathimul(ah6,bh2),lo=0|lo+_Mathimul(al5,bl3),mid=0|mid+_Mathimul(al5,bh3),mid=0|mid+_Mathimul(ah5,bl3),hi=0|hi+_Mathimul(ah5,bh3),lo=0|lo+_Mathimul(al4,bl4),mid=0|mid+_Mathimul(al4,bh4),mid=0|mid+_Mathimul(ah4,bl4),hi=0|hi+_Mathimul(ah4,bh4),lo=0|lo+_Mathimul(al3,bl5),mid=0|mid+_Mathimul(al3,bh5),mid=0|mid+_Mathimul(ah3,bl5),hi=0|hi+_Mathimul(ah3,bh5),lo=0|lo+_Mathimul(al2,bl6),mid=0|mid+_Mathimul(al2,bh6),mid=0|mid+_Mathimul(ah2,bl6),hi=0|hi+_Mathimul(ah2,bh6),lo=0|lo+_Mathimul(al1,bl7),mid=0|mid+_Mathimul(al1,bh7),mid=0|mid+_Mathimul(ah1,bl7),hi=0|hi+_Mathimul(ah1,bh7),lo=0|lo+_Mathimul(al0,bl8),mid=0|mid+_Mathimul(al0,bh8),mid=0|mid+_Mathimul(ah0,bl8),hi=0|hi+_Mathimul(ah0,bh8);var w8=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w8>>>26),w8&=67108863,lo=_Mathimul(al9,bl0),mid=_Mathimul(al9,bh0),mid=0|mid+_Mathimul(ah9,bl0),hi=_Mathimul(ah9,bh0),lo=0|lo+_Mathimul(al8,bl1),mid=0|mid+_Mathimul(al8,bh1),mid=0|mid+_Mathimul(ah8,bl1),hi=0|hi+_Mathimul(ah8,bh1),lo=0|lo+_Mathimul(al7,bl2),mid=0|mid+_Mathimul(al7,bh2),mid=0|mid+_Mathimul(ah7,bl2),hi=0|hi+_Mathimul(ah7,bh2),lo=0|lo+_Mathimul(al6,bl3),mid=0|mid+_Mathimul(al6,bh3),mid=0|mid+_Mathimul(ah6,bl3),hi=0|hi+_Mathimul(ah6,bh3),lo=0|lo+_Mathimul(al5,bl4),mid=0|mid+_Mathimul(al5,bh4),mid=0|mid+_Mathimul(ah5,bl4),hi=0|hi+_Mathimul(ah5,bh4),lo=0|lo+_Mathimul(al4,bl5),mid=0|mid+_Mathimul(al4,bh5),mid=0|mid+_Mathimul(ah4,bl5),hi=0|hi+_Mathimul(ah4,bh5),lo=0|lo+_Mathimul(al3,bl6),mid=0|mid+_Mathimul(al3,bh6),mid=0|mid+_Mathimul(ah3,bl6),hi=0|hi+_Mathimul(ah3,bh6),lo=0|lo+_Mathimul(al2,bl7),mid=0|mid+_Mathimul(al2,bh7),mid=0|mid+_Mathimul(ah2,bl7),hi=0|hi+_Mathimul(ah2,bh7),lo=0|lo+_Mathimul(al1,bl8),mid=0|mid+_Mathimul(al1,bh8),mid=0|mid+_Mathimul(ah1,bl8),hi=0|hi+_Mathimul(ah1,bh8),lo=0|lo+_Mathimul(al0,bl9),mid=0|mid+_Mathimul(al0,bh9),mid=0|mid+_Mathimul(ah0,bl9),hi=0|hi+_Mathimul(ah0,bh9);var w9=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w9>>>26),w9&=67108863,lo=_Mathimul(al9,bl1),mid=_Mathimul(al9,bh1),mid=0|mid+_Mathimul(ah9,bl1),hi=_Mathimul(ah9,bh1),lo=0|lo+_Mathimul(al8,bl2),mid=0|mid+_Mathimul(al8,bh2),mid=0|mid+_Mathimul(ah8,bl2),hi=0|hi+_Mathimul(ah8,bh2),lo=0|lo+_Mathimul(al7,bl3),mid=0|mid+_Mathimul(al7,bh3),mid=0|mid+_Mathimul(ah7,bl3),hi=0|hi+_Mathimul(ah7,bh3),lo=0|lo+_Mathimul(al6,bl4),mid=0|mid+_Mathimul(al6,bh4),mid=0|mid+_Mathimul(ah6,bl4),hi=0|hi+_Mathimul(ah6,bh4),lo=0|lo+_Mathimul(al5,bl5),mid=0|mid+_Mathimul(al5,bh5),mid=0|mid+_Mathimul(ah5,bl5),hi=0|hi+_Mathimul(ah5,bh5),lo=0|lo+_Mathimul(al4,bl6),mid=0|mid+_Mathimul(al4,bh6),mid=0|mid+_Mathimul(ah4,bl6),hi=0|hi+_Mathimul(ah4,bh6),lo=0|lo+_Mathimul(al3,bl7),mid=0|mid+_Mathimul(al3,bh7),mid=0|mid+_Mathimul(ah3,bl7),hi=0|hi+_Mathimul(ah3,bh7),lo=0|lo+_Mathimul(al2,bl8),mid=0|mid+_Mathimul(al2,bh8),mid=0|mid+_Mathimul(ah2,bl8),hi=0|hi+_Mathimul(ah2,bh8),lo=0|lo+_Mathimul(al1,bl9),mid=0|mid+_Mathimul(al1,bh9),mid=0|mid+_Mathimul(ah1,bl9),hi=0|hi+_Mathimul(ah1,bh9);var w10=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w10>>>26),w10&=67108863,lo=_Mathimul(al9,bl2),mid=_Mathimul(al9,bh2),mid=0|mid+_Mathimul(ah9,bl2),hi=_Mathimul(ah9,bh2),lo=0|lo+_Mathimul(al8,bl3),mid=0|mid+_Mathimul(al8,bh3),mid=0|mid+_Mathimul(ah8,bl3),hi=0|hi+_Mathimul(ah8,bh3),lo=0|lo+_Mathimul(al7,bl4),mid=0|mid+_Mathimul(al7,bh4),mid=0|mid+_Mathimul(ah7,bl4),hi=0|hi+_Mathimul(ah7,bh4),lo=0|lo+_Mathimul(al6,bl5),mid=0|mid+_Mathimul(al6,bh5),mid=0|mid+_Mathimul(ah6,bl5),hi=0|hi+_Mathimul(ah6,bh5),lo=0|lo+_Mathimul(al5,bl6),mid=0|mid+_Mathimul(al5,bh6),mid=0|mid+_Mathimul(ah5,bl6),hi=0|hi+_Mathimul(ah5,bh6),lo=0|lo+_Mathimul(al4,bl7),mid=0|mid+_Mathimul(al4,bh7),mid=0|mid+_Mathimul(ah4,bl7),hi=0|hi+_Mathimul(ah4,bh7),lo=0|lo+_Mathimul(al3,bl8),mid=0|mid+_Mathimul(al3,bh8),mid=0|mid+_Mathimul(ah3,bl8),hi=0|hi+_Mathimul(ah3,bh8),lo=0|lo+_Mathimul(al2,bl9),mid=0|mid+_Mathimul(al2,bh9),mid=0|mid+_Mathimul(ah2,bl9),hi=0|hi+_Mathimul(ah2,bh9);var w11=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w11>>>26),w11&=67108863,lo=_Mathimul(al9,bl3),mid=_Mathimul(al9,bh3),mid=0|mid+_Mathimul(ah9,bl3),hi=_Mathimul(ah9,bh3),lo=0|lo+_Mathimul(al8,bl4),mid=0|mid+_Mathimul(al8,bh4),mid=0|mid+_Mathimul(ah8,bl4),hi=0|hi+_Mathimul(ah8,bh4),lo=0|lo+_Mathimul(al7,bl5),mid=0|mid+_Mathimul(al7,bh5),mid=0|mid+_Mathimul(ah7,bl5),hi=0|hi+_Mathimul(ah7,bh5),lo=0|lo+_Mathimul(al6,bl6),mid=0|mid+_Mathimul(al6,bh6),mid=0|mid+_Mathimul(ah6,bl6),hi=0|hi+_Mathimul(ah6,bh6),lo=0|lo+_Mathimul(al5,bl7),mid=0|mid+_Mathimul(al5,bh7),mid=0|mid+_Mathimul(ah5,bl7),hi=0|hi+_Mathimul(ah5,bh7),lo=0|lo+_Mathimul(al4,bl8),mid=0|mid+_Mathimul(al4,bh8),mid=0|mid+_Mathimul(ah4,bl8),hi=0|hi+_Mathimul(ah4,bh8),lo=0|lo+_Mathimul(al3,bl9),mid=0|mid+_Mathimul(al3,bh9),mid=0|mid+_Mathimul(ah3,bl9),hi=0|hi+_Mathimul(ah3,bh9);var w12=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w12>>>26),w12&=67108863,lo=_Mathimul(al9,bl4),mid=_Mathimul(al9,bh4),mid=0|mid+_Mathimul(ah9,bl4),hi=_Mathimul(ah9,bh4),lo=0|lo+_Mathimul(al8,bl5),mid=0|mid+_Mathimul(al8,bh5),mid=0|mid+_Mathimul(ah8,bl5),hi=0|hi+_Mathimul(ah8,bh5),lo=0|lo+_Mathimul(al7,bl6),mid=0|mid+_Mathimul(al7,bh6),mid=0|mid+_Mathimul(ah7,bl6),hi=0|hi+_Mathimul(ah7,bh6),lo=0|lo+_Mathimul(al6,bl7),mid=0|mid+_Mathimul(al6,bh7),mid=0|mid+_Mathimul(ah6,bl7),hi=0|hi+_Mathimul(ah6,bh7),lo=0|lo+_Mathimul(al5,bl8),mid=0|mid+_Mathimul(al5,bh8),mid=0|mid+_Mathimul(ah5,bl8),hi=0|hi+_Mathimul(ah5,bh8),lo=0|lo+_Mathimul(al4,bl9),mid=0|mid+_Mathimul(al4,bh9),mid=0|mid+_Mathimul(ah4,bl9),hi=0|hi+_Mathimul(ah4,bh9);var w13=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w13>>>26),w13&=67108863,lo=_Mathimul(al9,bl5),mid=_Mathimul(al9,bh5),mid=0|mid+_Mathimul(ah9,bl5),hi=_Mathimul(ah9,bh5),lo=0|lo+_Mathimul(al8,bl6),mid=0|mid+_Mathimul(al8,bh6),mid=0|mid+_Mathimul(ah8,bl6),hi=0|hi+_Mathimul(ah8,bh6),lo=0|lo+_Mathimul(al7,bl7),mid=0|mid+_Mathimul(al7,bh7),mid=0|mid+_Mathimul(ah7,bl7),hi=0|hi+_Mathimul(ah7,bh7),lo=0|lo+_Mathimul(al6,bl8),mid=0|mid+_Mathimul(al6,bh8),mid=0|mid+_Mathimul(ah6,bl8),hi=0|hi+_Mathimul(ah6,bh8),lo=0|lo+_Mathimul(al5,bl9),mid=0|mid+_Mathimul(al5,bh9),mid=0|mid+_Mathimul(ah5,bl9),hi=0|hi+_Mathimul(ah5,bh9);var w14=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w14>>>26),w14&=67108863,lo=_Mathimul(al9,bl6),mid=_Mathimul(al9,bh6),mid=0|mid+_Mathimul(ah9,bl6),hi=_Mathimul(ah9,bh6),lo=0|lo+_Mathimul(al8,bl7),mid=0|mid+_Mathimul(al8,bh7),mid=0|mid+_Mathimul(ah8,bl7),hi=0|hi+_Mathimul(ah8,bh7),lo=0|lo+_Mathimul(al7,bl8),mid=0|mid+_Mathimul(al7,bh8),mid=0|mid+_Mathimul(ah7,bl8),hi=0|hi+_Mathimul(ah7,bh8),lo=0|lo+_Mathimul(al6,bl9),mid=0|mid+_Mathimul(al6,bh9),mid=0|mid+_Mathimul(ah6,bl9),hi=0|hi+_Mathimul(ah6,bh9);var w15=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w15>>>26),w15&=67108863,lo=_Mathimul(al9,bl7),mid=_Mathimul(al9,bh7),mid=0|mid+_Mathimul(ah9,bl7),hi=_Mathimul(ah9,bh7),lo=0|lo+_Mathimul(al8,bl8),mid=0|mid+_Mathimul(al8,bh8),mid=0|mid+_Mathimul(ah8,bl8),hi=0|hi+_Mathimul(ah8,bh8),lo=0|lo+_Mathimul(al7,bl9),mid=0|mid+_Mathimul(al7,bh9),mid=0|mid+_Mathimul(ah7,bl9),hi=0|hi+_Mathimul(ah7,bh9);var w16=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w16>>>26),w16&=67108863,lo=_Mathimul(al9,bl8),mid=_Mathimul(al9,bh8),mid=0|mid+_Mathimul(ah9,bl8),hi=_Mathimul(ah9,bh8),lo=0|lo+_Mathimul(al8,bl9),mid=0|mid+_Mathimul(al8,bh9),mid=0|mid+_Mathimul(ah8,bl9),hi=0|hi+_Mathimul(ah8,bh9);var w17=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w17>>>26),w17&=67108863,lo=_Mathimul(al9,bl9),mid=_Mathimul(al9,bh9),mid=0|mid+_Mathimul(ah9,bl9),hi=_Mathimul(ah9,bh9);var w18=0|(0|c+lo)+((8191&mid)<<13);return c=0|(0|hi+(mid>>>13))+(w18>>>26),w18&=67108863,o[0]=w0,o[1]=w1,o[2]=w2,o[3]=w3,o[4]=w4,o[5]=w5,o[6]=w6,o[7]=w7,o[8]=w8,o[9]=w9,o[10]=w10,o[11]=w11,o[12]=w12,o[13]=w13,o[14]=w14,o[15]=w15,o[16]=w16,o[17]=w17,o[18]=w18,0!==c&&(o[19]=c,out.length++),out};_Mathimul||(comb10MulTo=smallMulTo),BN.prototype.mulTo=function(num,out){var len=this.length+num.length,res;return res=10===this.length&&10===num.length?comb10MulTo(this,num,out):63>len?smallMulTo(this,num,out):1024>len?bigMulTo(this,num,out):jumboMulTo(this,num,out),res},FFTM.prototype.makeRBT=function(N){for(var t=Array(N),l=BN.prototype._countBits(N)-1,i=0;i>=1;return rb},FFTM.prototype.permute=function(rbt,rws,iws,rtws,itws,N){for(var i=0;i>>=1)i++;return 1<=N))for(var i=0,t;iw?0:0|w/67108864;return ws},FFTM.prototype.convert13b=function(ws,len,rws,N){for(var carry=0,i=0;i>>=13,rws[2*i+1]=8191&carry,carry>>>=13;for(i=2*len;inum;isNegNum&&(num=-num),assert("number"==typeof num),assert(67108864>num);for(var carry=0,i=0;i>=26,carry+=0|w/67108864,carry+=lo>>>26,this.words[i]=67108863&lo}return 0!==carry&&(this.words[i]=carry,this.length++),isNegNum?this.ineg():this},BN.prototype.muln=function(num){return this.clone().imuln(num)},BN.prototype.sqr=function(){return this.mul(this)},BN.prototype.isqr=function(){return this.imul(this.clone())},BN.prototype.pow=function(num){var w=toBitArray(num);if(0===w.length)return new BN(1);for(var res=this,i=0;i>>26-r<<26-r,c=(0|this.words[i])-newCarry<>>26-r}carry&&(this.words[i]=carry,this.length++)}if(0!==s){for(i=this.length-1;0<=i;i--)this.words[i+s]=this.words[i];for(i=0;is)for(this.length-=s,i=0;i=h);i--){var word=0|this.words[i];this.words[i]=carry<<26-r|word>>>r,carry=word&(67108863^67108863>>>r<>>r<num),0>num?this.isubn(-num):0===this.negative?this._iaddn(num):1===this.length&&(0|this.words[0])<=num?(this.words[0]=num-(0|this.words[0]),this.negative=0,this):(this.negative=0,this.isubn(num),this.negative=1,this)},BN.prototype._iaddn=function(num){this.words[0]+=num;for(var i=0;inum),0>num)return this.iaddn(-num);if(0!==this.negative)return this.negative=0,this.iaddn(num),this.negative=1,this;if(this.words[0]-=num,1===this.length&&0>this.words[0])this.words[0]=-this.words[0],this.negative=1;else for(var i=0;ithis.words[i];i++)this.words[i]+=67108864,this.words[i+1]-=1;return this._strip()},BN.prototype.addn=function(num){return this.clone().iaddn(num)},BN.prototype.subn=function(num){return this.clone().isubn(num)},BN.prototype.iabs=function(){return this.negative=0,this},BN.prototype.abs=function(){return this.clone().iabs()},BN.prototype._ishlnsubmul=function(num,mul,shift){var len=num.length+shift,i;this._expand(len);var carry=0,w;for(i=0;i>26)-(0|right/67108864),this.words[i+shift]=67108863&w}for(;i>26,this.words[i+shift]=67108863&w;if(0===carry)return this._strip();for(assert(-1===carry),carry=0,i=0;i>26,this.words[i]=67108863&w;return this.negative=1,this._strip()},BN.prototype._wordDiv=function(num,mode){var shift=this.length-num.length,a=this.clone(),b=num,bhi=0|b.words[b.length-1],bhiBits=this._countBits(bhi);shift=26-bhiBits,0!=shift&&(b=b.ushln(shift),a.iushln(shift),bhi=0|b.words[b.length-1]);var m=a.length-b.length,q;if("mod"!==mode){q=new BN(null),q.length=m+1,q.words=Array(q.length);for(var i=0;ithis.length||0>this.cmp(num)?{div:new BN(0),mod:this}:1===num.length?"div"===mode?{div:this.divn(num.words[0]),mod:null}:"mod"===mode?{div:null,mod:new BN(this.modrn(num.words[0]))}:{div:this.divn(num.words[0]),mod:new BN(this.modrn(num.words[0]))}:this._wordDiv(num,mode):(res=this.neg().divmod(num.neg(),mode),"div"!==mode&&(mod=res.mod.neg(),positive&&0!==mod.negative&&mod.isub(num)),{div:res.div,mod:mod})},BN.prototype.div=function(num){return this.divmod(num,"div",!1).div},BN.prototype.mod=function(num){return this.divmod(num,"mod",!1).mod},BN.prototype.umod=function(num){return this.divmod(num,"mod",!0).mod},BN.prototype.divRound=function(num){var dm=this.divmod(num);if(dm.mod.isZero())return dm.div;var mod=0===dm.div.negative?dm.mod:dm.mod.isub(num),half=num.ushrn(1),r2=num.andln(1),cmp=mod.cmp(half);return 0>cmp||1===r2&&0===cmp?dm.div:0===dm.div.negative?dm.div.iaddn(1):dm.div.isubn(1)},BN.prototype.modrn=function(num){var isNegNum=0>num;isNegNum&&(num=-num),assert(67108863>=num);for(var p=67108864%num,acc=0,i=this.length-1;0<=i;i--)acc=(p*acc+(0|this.words[i]))%num;return isNegNum?-acc:acc},BN.prototype.modn=function(num){return this.modrn(num)},BN.prototype.idivn=function(num){var isNegNum=0>num;isNegNum&&(num=-num),assert(67108863>=num);for(var carry=0,i=this.length-1,w;0<=i;i--)w=(0|this.words[i])+67108864*carry,this.words[i]=0|w/num,carry=w%num;return this._strip(),isNegNum?this.ineg():this},BN.prototype.divn=function(num){return this.clone().idivn(num)},BN.prototype.egcd=function(p){assert(0===p.negative),assert(!p.isZero());var x=this,y=p.clone();x=0===x.negative?x.clone():x.umod(p);for(var A=new BN(1),B=new BN(0),C=new BN(0),D=new BN(1),g=0;x.isEven()&&y.isEven();)x.iushrn(1),y.iushrn(1),++g;for(var yp=y.clone(),xp=x.clone();!x.isZero();){for(var i=0,im=1;0==(x.words[0]&im)&&26>i;++i,im<<=1);if(0j;++j,jm<<=1);if(0i;++i,im<<=1);if(0j;++j,jm<<=1);if(0res.cmpn(0)&&res.iadd(p),res},BN.prototype.gcd=function(num){if(this.isZero())return num.abs();if(num.isZero())return this.abs();var a=this.clone(),b=num.clone();a.negative=0,b.negative=0;for(var shift=0;a.isEven()&&b.isEven();shift++)a.iushrn(1),b.iushrn(1);do{for(;a.isEven();)a.iushrn(1);for(;b.isEven();)b.iushrn(1);var r=a.cmp(b);if(0>r){var t=a;a=b,b=t}else if(0===r||0===b.cmpn(1))break;a.isub(b)}while(!0);return b.iushln(shift)},BN.prototype.invm=function(num){return this.egcd(num).a.umod(num)},BN.prototype.isEven=function(){return 0==(1&this.words[0])},BN.prototype.isOdd=function(){return 1==(1&this.words[0])},BN.prototype.andln=function(num){return this.words[0]&num},BN.prototype.bincn=function(bit){assert("number"==typeof bit);var r=bit%26,s=(bit-r)/26,q=1<>>26,w&=67108863,this.words[i]=w;return 0!==carry&&(this.words[i]=carry,this.length++),this},BN.prototype.isZero=function(){return 1===this.length&&0===this.words[0]},BN.prototype.cmpn=function(num){var negative=0>num;if(0!==this.negative&&!negative)return-1;if(0===this.negative&&negative)return 1;this._strip();var res;if(1=num,"Number is too big");var w=0|this.words[0];res=w===num?0:wnum.length)return 1;if(this.lengthb&&(res=1);break}}return res},BN.prototype.gtn=function(num){return 1===this.cmpn(num)},BN.prototype.gt=function(num){return 1===this.cmp(num)},BN.prototype.gten=function(num){return 0<=this.cmpn(num)},BN.prototype.gte=function(num){return 0<=this.cmp(num)},BN.prototype.ltn=function(num){return-1===this.cmpn(num)},BN.prototype.lt=function(num){return-1===this.cmp(num)},BN.prototype.lten=function(num){return 0>=this.cmpn(num)},BN.prototype.lte=function(num){return 0>=this.cmp(num)},BN.prototype.eqn=function(num){return 0===this.cmpn(num)},BN.prototype.eq=function(num){return 0===this.cmp(num)},BN.red=function(num){return new Red(num)},BN.prototype.toRed=function(ctx){return assert(!this.red,"Already a number in reduction context"),assert(0===this.negative,"red works only with positives"),ctx.convertTo(this)._forceRed(ctx)},BN.prototype.fromRed=function(){return assert(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},BN.prototype._forceRed=function(ctx){return this.red=ctx,this},BN.prototype.forceRed=function(ctx){return assert(!this.red,"Already a number in reduction context"),this._forceRed(ctx)},BN.prototype.redAdd=function(num){return assert(this.red,"redAdd works only with red numbers"),this.red.add(this,num)},BN.prototype.redIAdd=function(num){return assert(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,num)},BN.prototype.redSub=function(num){return assert(this.red,"redSub works only with red numbers"),this.red.sub(this,num)},BN.prototype.redISub=function(num){return assert(this.red,"redISub works only with red numbers"),this.red.isub(this,num)},BN.prototype.redShl=function(num){return assert(this.red,"redShl works only with red numbers"),this.red.shl(this,num)},BN.prototype.redMul=function(num){return assert(this.red,"redMul works only with red numbers"),this.red._verify2(this,num),this.red.mul(this,num)},BN.prototype.redIMul=function(num){return assert(this.red,"redMul works only with red numbers"),this.red._verify2(this,num),this.red.imul(this,num)},BN.prototype.redSqr=function(){return assert(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},BN.prototype.redISqr=function(){return assert(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},BN.prototype.redSqrt=function(){return assert(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},BN.prototype.redInvm=function(){return assert(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},BN.prototype.redNeg=function(){return assert(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},BN.prototype.redPow=function(num){return assert(this.red&&!num.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,num)};var primes={k256:null,p224:null,p192:null,p25519:null};MPrime.prototype._tmp=function(){var tmp=new BN(null);return tmp.words=Array(_Mathceil(this.n/13)),tmp},MPrime.prototype.ireduce=function(num){var r=num,rlen;do this.split(r,this.tmp),r=this.imulK(r),r=r.iadd(this.tmp),rlen=r.bitLength();while(rlen>this.n);var cmp=rlen=input.length)return input.words[0]=0,void(input.length=1);var prev=input.words[9];for(output.words[output.length++]=prev&mask,i=10;i>>22,prev=next}prev>>>=22,input.words[i-10]=prev,input.length-=0===prev&&10>>=26,num.words[i]=lo,carry=hi}return 0!==carry&&(num.words[num.length++]=carry),num},BN._prime=function prime(name){if(primes[name])return primes[name];var prime;if("k256"===name)prime=new K256;else if("p224"===name)prime=new P224;else if("p192"===name)prime=new P192;else if("p25519"===name)prime=new P25519;else throw new Error("Unknown prime "+name);return primes[name]=prime,prime},Red.prototype._verify1=function(a){assert(0===a.negative,"red works only with positives"),assert(a.red,"red works only with red numbers")},Red.prototype._verify2=function(a,b){assert(0==(a.negative|b.negative),"red works only with positives"),assert(a.red&&a.red===b.red,"red works only with red numbers")},Red.prototype.imod=function(a){return this.prime?this.prime.ireduce(a)._forceRed(this):(move(a,a.umod(this.m)._forceRed(this)),a)},Red.prototype.neg=function(a){return a.isZero()?a.clone():this.m.sub(a)._forceRed(this)},Red.prototype.add=function(a,b){this._verify2(a,b);var res=a.add(b);return 0<=res.cmp(this.m)&&res.isub(this.m),res._forceRed(this)},Red.prototype.iadd=function(a,b){this._verify2(a,b);var res=a.iadd(b);return 0<=res.cmp(this.m)&&res.isub(this.m),res},Red.prototype.sub=function(a,b){this._verify2(a,b);var res=a.sub(b);return 0>res.cmpn(0)&&res.iadd(this.m),res._forceRed(this)},Red.prototype.isub=function(a,b){this._verify2(a,b);var res=a.isub(b);return 0>res.cmpn(0)&&res.iadd(this.m),res},Red.prototype.shl=function(a,num){return this._verify1(a),this.imod(a.ushln(num))},Red.prototype.imul=function(a,b){return this._verify2(a,b),this.imod(a.imul(b))},Red.prototype.mul=function(a,b){return this._verify2(a,b),this.imod(a.mul(b))},Red.prototype.isqr=function(a){return this.imul(a,a.clone())},Red.prototype.sqr=function(a){return this.mul(a,a)},Red.prototype.sqrt=function(a){if(a.isZero())return a.clone();var mod3=this.m.andln(3);if(assert(1==mod3%2),3===mod3){var pow=this.m.add(new BN(1)).iushrn(2);return this.pow(a,pow)}for(var q=this.m.subn(1),s=0;!q.isZero()&&0===q.andln(1);)s++,q.iushrn(1);assert(!q.isZero());var one=new BN(1).toRed(this),nOne=one.redNeg(),lpow=this.m.subn(1).iushrn(1),z=this.m.bitLength();for(z=new BN(2*z*z).toRed(this);0!==this.pow(z,lpow).cmp(nOne);)z.redIAdd(nOne);for(var c=this.pow(z,q),r=this.pow(a,q.addn(1).iushrn(1)),t=this.pow(a,q),m=s;0!==t.cmp(one);){for(var tmp=t,i=0;0!==tmp.cmp(one);i++)tmp=tmp.redSqr();assert(i>j,res!==wnd[0]&&(res=this.sqr(res)),0===bit&&0===current){currentLen=0;continue}current<<=1,current|=bit,currentLen++,4!==currentLen&&(0!==i||0!==j)||(res=this.mul(res,wnd[current]),currentLen=0,current=0)}start=26}return res},Red.prototype.convertTo=function(num){var r=num.umod(this.m);return r===num?r.clone():r},Red.prototype.convertFrom=function(num){var res=num.clone();return res.red=null,res},BN.mont=function(num){return new Mont(num)},inherits(Mont,Red),Mont.prototype.convertTo=function(num){return this.imod(num.ushln(this.shift))},Mont.prototype.convertFrom=function(num){var r=this.imod(num.mul(this.rinv));return r.red=null,r},Mont.prototype.imul=function(a,b){if(a.isZero()||b.isZero())return a.words[0]=0,a.length=1,a;var t=a.imul(b),c=t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),u=t.isub(c).iushrn(this.shift),res=u;return 0<=u.cmp(this.m)?res=u.isub(this.m):0>u.cmpn(0)&&(res=u.iadd(this.m)),res._forceRed(this)},Mont.prototype.mul=function(a,b){if(a.isZero()||b.isZero())return new BN(0)._forceRed(this);var t=a.mul(b),c=t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),u=t.isub(c).iushrn(this.shift),res=u;return 0<=u.cmp(this.m)?res=u.isub(this.m):0>u.cmpn(0)&&(res=u.iadd(this.m)),res._forceRed(this)},Mont.prototype.invm=function(a){var res=this.imod(a._invmp(this.m).mul(this.r2));return res._forceRed(this)}})("undefined"==typeof module||module,this)},{buffer:36}],36:[function(){},{}],37:[function(require,module,exports){arguments[4][36][0].apply(exports,arguments)},{dup:36}],38:[function(require,module,exports){(function(){(function(){/*! + */function compare(a,b){if(a===b)return 0;for(var x=a.length,y=b.length,i=0,len=_Mathmin(x,y);irecurseTimes)return isRegExp(value)?ctx.stylize(RegExp.prototype.toString.call(value),"regexp"):ctx.stylize("[Object]","special");ctx.seen.push(value);var output;return output=array?formatArray(ctx,value,recurseTimes,visibleKeys,keys):keys.map(function(key){return formatProperty(ctx,value,recurseTimes,visibleKeys,key,array)}),ctx.seen.pop(),reduceToSingleString(output,base,braces)}function formatPrimitive(ctx,value){if(isUndefined(value))return ctx.stylize("undefined","undefined");if(isString(value)){var simple="'"+JSON.stringify(value).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,"\"")+"'";return ctx.stylize(simple,"string")}return isNumber(value)?ctx.stylize(""+value,"number"):isBoolean(value)?ctx.stylize(""+value,"boolean"):isNull(value)?ctx.stylize("null","null"):void 0}function formatError(value){return"["+Error.prototype.toString.call(value)+"]"}function formatArray(ctx,value,recurseTimes,visibleKeys,keys){for(var output=[],i=0,l=value.length;ictx.seen.indexOf(desc.value)?(str=isNull(recurseTimes)?formatValue(ctx,desc.value,null):formatValue(ctx,desc.value,recurseTimes-1),-1n?"0"+n.toString(10):n.toString(10)}function timestamp(){var d=new Date,time=[pad(d.getHours()),pad(d.getMinutes()),pad(d.getSeconds())].join(":");return[d.getDate(),months[d.getMonth()],time].join(" ")}function hasOwnProperty(obj,prop){return Object.prototype.hasOwnProperty.call(obj,prop)}exports.format=function(f){if(!isString(f)){for(var objects=[],i=0;i=len)return x;switch(x){case"%s":return args[i++]+"";case"%d":return+args[i++];case"%j":try{return JSON.stringify(args[i++])}catch(_){return"[Circular]"}default:return x;}}),x=args[i];i>16,arr[curByte++]=255&tmp>>8,arr[curByte++]=255&tmp;return 2===placeHoldersLen&&(tmp=revLookup[b64.charCodeAt(i)]<<2|revLookup[b64.charCodeAt(i+1)]>>4,arr[curByte++]=255&tmp),1===placeHoldersLen&&(tmp=revLookup[b64.charCodeAt(i)]<<10|revLookup[b64.charCodeAt(i+1)]<<4|revLookup[b64.charCodeAt(i+2)]>>2,arr[curByte++]=255&tmp>>8,arr[curByte++]=255&tmp),arr}function tripletToBase64(num){return lookup[63&num>>18]+lookup[63&num>>12]+lookup[63&num>>6]+lookup[63&num]}function encodeChunk(uint8,start,end){for(var output=[],i=start,tmp;ilen2?len2:i+maxChunkLength));return 1===extraBytes?(tmp=uint8[len-1],parts.push(lookup[tmp>>2]+lookup[63&tmp<<4]+"==")):2===extraBytes&&(tmp=(uint8[len-2]<<8)+uint8[len-1],parts.push(lookup[tmp>>10]+lookup[63&tmp>>4]+lookup[63&tmp<<2]+"=")),parts.join("")}exports.byteLength=function(b64){var lens=getLens(b64),validLen=lens[0],placeHoldersLen=lens[1];return 3*(validLen+placeHoldersLen)/4-placeHoldersLen},exports.toByteArray=toByteArray,exports.fromByteArray=fromByteArray;for(var lookup=[],revLookup=[],Arr="undefined"==typeof Uint8Array?Array:Uint8Array,code="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",i=0,len=code.length;inum&&48<=num){sum=10*sum+(num-48);continue}if(i!==start||43!==num){if(i===start&&45===num){sign=-1;continue}if(46===num)break;throw new Error("not a number: buffer["+i+"] = "+num)}}return sum*sign}function decode(data,start,end,encoding){return null==data||0===data.length?null:("number"!=typeof start&&null==encoding&&(encoding=start,start=void 0),"number"!=typeof end&&null==encoding&&(encoding=end,end=void 0),decode.position=0,decode.encoding=encoding||null,decode.data=Buffer.isBuffer(data)?data.slice(start,end):Buffer.from(data),decode.bytes=decode.data.length,decode.next())}var Buffer=require("safe-buffer").Buffer;const END_OF_TYPE=101;decode.bytes=0,decode.position=0,decode.data=null,decode.encoding=null,decode.next=function(){switch(decode.data[decode.position]){case 100:return decode.dictionary();case 108:return decode.list();case 105:return decode.integer();default:return decode.buffer();}},decode.find=function(chr){for(var i=decode.position,c=decode.data.length,d=decode.data;iArray.from({length:end-start+1},(cur,idx)=>idx+start);return range.reduce((acc,cur)=>{const r=cur.split("-").map(cur=>parseInt(cur));return acc.concat(generateRange(...r))},[])}module.exports=parseRange,module.exports.parse=parseRange,module.exports.compose=function(range){return range.reduce((acc,cur,idx,arr)=>((0===idx||cur!==arr[idx-1]+1)&&acc.push([]),acc[acc.length-1].push(cur),acc),[]).map(cur=>1low||low>=haystack.length)throw new RangeError("invalid lower bound");if(void 0===high)high=haystack.length-1;else if(high|=0,high=haystack.length)throw new RangeError("invalid upper bound");for(;low<=high;)if(mid=low+(high-low>>>1),cmp=+comparator(haystack[mid],needle,mid,haystack),0>cmp)low=mid+1;else if(0>3;return 0!=num%8&&out++,out}Object.defineProperty(exports,"__esModule",{value:!0});var BitField=function(){function BitField(data,opts){void 0===data&&(data=0);var grow=null===opts||void 0===opts?void 0:opts.grow;this.grow=grow&&isFinite(grow)&&getByteSize(grow)||grow||0,this.buffer="number"==typeof data?new Uint8Array(getByteSize(data)):data}return BitField.prototype.get=function(i){var j=i>>3;return j>i%8)},BitField.prototype.set=function(i,value){void 0===value&&(value=!0);var j=i>>3;if(value){if(this.buffer.length>i%8}else j>i%8))},BitField.prototype.forEach=function(fn,start,end){void 0===start&&(start=0),void 0===end&&(end=8*this.buffer.length);for(var i=start,j=i>>3,y=128>>i%8,byte=this.buffer[j];i>1},BitField}();exports.default=BitField},{}],23:[function(require,module){(function(process,Buffer){(function(){function noop(){}function sha1(buf){return Buffer.from(simpleSha1.sync(buf),"hex")}function createGetResponse(id,token,value){const r={id,token,v:value.v};return value.sig&&(r.sig=value.sig,r.k=value.k,"number"==typeof value.seq&&(r.seq=value.seq)),r}function encodePeer(host,port){const buf=Buffer.allocUnsafe(6),ip=host.split(".");for(let i=0;4>i;i++)buf[i]=parseInt(ip[i]||0,10);return buf.writeUInt16BE(port,4),buf}function decodePeers(buf){const peers=[];try{for(let i=0;ideadNode?(self._debug("swaping dead node with newer",deadNode),swap(deadNode),cb()):void(self._debug("no node added, all other nodes ok"),cb()))});this._rpc.on("ping",(older,swap)=>{onping({older,swap})}),process.nextTick(function(){self.destroyed||self._bootstrap(!1!==opts.bootstrap)}),this._debug("new DHT %s",this.nodeId);const self=this}_setBucketCheckInterval(){function checkBucket(){const diff=Date.now()-self._rpc.nodes.metadata.lastChange;return diff{self.destroyed||(1>self.nodes.toArray().length&&self._bootstrap(!0),queueNext())})}function queueNext(){if(self._runningBucketCheck&&!self.destroyed){const nextTimeout=_Mathfloor(Math.random()*interval+30000);self._bucketCheckTimeout=setTimeout(checkBucket,nextTimeout)}}const self=this,interval=60000;this._runningBucketCheck=!0,queueNext()}_pingAll(cb){this._checkAndRemoveNodes(this.nodes.toArray(),cb)}removeBucketCheckInterval(){this._runningBucketCheck=!1,clearTimeout(this._bucketCheckTimeout)}updateBucketTimestamp(){this._rpc.nodes.metadata.lastChange=Date.now()}_checkAndRemoveNodes(nodes,cb){const self=this;this._checkNodes(nodes,!0,(_,node)=>{node&&self.removeNode(node.id),cb(null,node)})}_checkNodes(nodes,force,cb){function test(acc){let current=null;for(;acc.length&&(current=acc.pop(),current.id&&!force)&&!(1e4err?void cb(null,current):(self.updateBucketTimestamp(),test(acc))):cb(null)}const self=this;test(nodes)}addNode(node){const self=this;if(node.id){node.id=toBuffer(node.id);const old=!!this._rpc.nodes.get(node.id);return this._rpc.nodes.add(node),void(old||(this.emit("node",node),this.updateBucketTimestamp()))}this._sendPing(node,(_,node)=>{node&&self.addNode(node)})}removeNode(id){this._rpc.nodes.remove(toBuffer(id))}_sendPing(node,cb){const self=this,expectedId=node.id;this._rpc.query(node,{q:"ping"},(err,pong,node)=>err?cb(err):pong.r&&pong.r.id&&Buffer.isBuffer(pong.r.id)&&pong.r.id.length===self._hashLength?Buffer.isBuffer(expectedId)&&!expectedId.equals(pong.r.id)?cb(new Error("Unexpected node id")):void(self.updateBucketTimestamp(),cb(null,{id:pong.r.id,host:node.host||node.address,port:node.port})):cb(new Error("Bad reply")))}toJSON(){const self=this,values={};return Object.keys(this._values.cache).forEach(key=>{const value=self._values.cache[key].value;values[key]={v:value.v.toString("hex"),id:value.id.toString("hex")},null!=value.seq&&(values[key].seq=value.seq),null!=value.sig&&(values[key].sig=value.sig.toString("hex")),null!=value.k&&(values[key].k=value.k.toString("hex"))}),{nodes:this._rpc.nodes.toArray().map(toNode),values}}put(opts,cb){(Buffer.isBuffer(opts)||"string"==typeof opts)&&(opts={v:opts});const isMutable=!!opts.k;if(opts.v===void 0)throw new Error("opts.v not given");if(1e3<=opts.v.length)throw new Error("v must be less than 1000 bytes in put()");if(isMutable&&void 0!==opts.cas&&"number"!=typeof opts.cas)throw new Error("opts.cas must be an integer if provided");if(isMutable&&32!==opts.k.length)throw new Error("opts.k ed25519 public key must be 32 bytes");if(isMutable&&"function"!=typeof opts.sign&&!Buffer.isBuffer(opts.sig))throw new Error("opts.sign function or options.sig signature is required for mutable put");if(isMutable&&opts.salt&&64 64 bytes long");if(isMutable&&void 0===opts.seq)throw new Error("opts.seq not provided for a mutable update");if(isMutable&&"number"!=typeof opts.seq)throw new Error("opts.seq not an integer");return this._put(opts,cb)}_put(opts,cb){cb||(cb=noop);const isMutable=!!opts.k,v="string"==typeof opts.v?Buffer.from(opts.v):opts.v,key=isMutable?this._hash(opts.salt?Buffer.concat([opts.k,opts.salt]):opts.k):this._hash(bencode.encode(v)),table=this._tables.get(key.toString("hex"));if(!table)return this._preput(key,opts,cb);const message={q:"put",a:{id:this._rpc.id,token:null,v}};return isMutable?("number"==typeof opts.cas&&(message.a.cas=opts.cas),opts.salt&&(message.a.salt=opts.salt),message.a.k=opts.k,message.a.seq=opts.seq,"function"==typeof opts.sign?message.a.sig=opts.sign(encodeSigData(message.a)):Buffer.isBuffer(opts.sig)&&(message.a.sig=opts.sig)):this._values.set(key.toString("hex"),message.a),this._rpc.queryAll(table.closest(key),message,null,(err,n)=>err?cb(err,key,n):void cb(null,key,n)),key}_preput(key,opts,cb){const self=this;return this._closest(key,{q:"get",a:{id:this._rpc.id,target:key}},null,err=>err?cb(err):void self.put(opts,cb)),key}get(key,opts,cb){function done(err){return err?cb(err):void cb(null,value)}function onreply(message){const r=message.r;if(!r||!r.v)return!0;const isMutable=r.k||r.sig;if(opts.salt&&(r.salt=Buffer.from(opts.salt)),isMutable){if(!verify||!r.sig||!r.k)return!0;if(!verify(r.sig,encodeSigData(r),r.k))return!0;hash(r.salt?Buffer.concat([r.k,r.salt]):r.k).equals(key)&&(!value||r.seq>value.seq)&&(value=r)}else if(hash(bencode.encode(r.v)).equals(key))return value=r,!1;return!0}key=toBuffer(key),"function"==typeof opts&&(cb=opts,opts=null),opts||(opts={});const verify=opts.verify||this._verify,hash=this._hash;let value=this._values.get(key.toString("hex"))||null;return value&&!1!==opts.cache?(value=createGetResponse(this._rpc.id,null,value),process.nextTick(done)):void this._closest(key,{q:"get",a:{id:this._rpc.id,target:key}},onreply,done)}announce(infoHash,port,cb){if("function"==typeof port)return this.announce(infoHash,0,port);infoHash=toBuffer(infoHash),cb||(cb=noop);const table=this._tables.get(infoHash.toString("hex"));if(!table)return this._preannounce(infoHash,port,cb);if(this._host){const dhtPort=this.listening?this.address().port:0;this._addPeer({host:this._host,port:port||dhtPort},infoHash,{host:this._host,port:dhtPort})}const message={q:"announce_peer",a:{id:this._rpc.id,token:null,info_hash:infoHash,port,implied_port:port?0:1}};this._debug("announce %s %d",infoHash,port),this._rpc.queryAll(table.closest(infoHash),message,null,cb)}_preannounce(infoHash,port,cb){const self=this;this.lookup(infoHash,err=>self.destroyed?cb(new Error("dht is destroyed")):err?cb(err):void self.announce(infoHash,port,cb))}lookup(infoHash,cb){function emit(values,from){values||(values=self._peers.get(infoHash.toString("hex"),100));const peers=decodePeers(values);for(let i=0;i{self.emit("close"),cb&&cb()})}_onquery(query,peer){const q=query.q.toString();if(this._debug("received %s query from %s:%d",q,peer.address,peer.port),!!query.a)return"ping"===q?this._rpc.response(peer,query,{id:this._rpc.id}):"find_node"===q?this._onfindnode(query,peer):"get_peers"===q?this._ongetpeers(query,peer):"announce_peer"===q?this._onannouncepeer(query,peer):"get"===q?this._onget(query,peer):"put"===q?this._onput(query,peer):void 0}_onfindnode(query,peer){const target=query.a.target;if(!target)return this._rpc.error(peer,query,[203,"`find_node` missing required `a.target` field"]);this.emit("find_node",target);const nodes=this._rpc.nodes.closest(target);this._rpc.response(peer,query,{id:this._rpc.id},nodes)}_ongetpeers(query,peer){const host=peer.address||peer.host,infoHash=query.a.info_hash;if(!infoHash)return this._rpc.error(peer,query,[203,"`get_peers` missing required `a.info_hash` field"]);this.emit("get_peers",infoHash);const r={id:this._rpc.id,token:this._generateToken(host)},peers=this._peers.get(infoHash.toString("hex"));peers.length?(r.values=peers,this._rpc.response(peer,query,r)):this._rpc.response(peer,query,r,this._rpc.nodes.closest(infoHash))}_onannouncepeer(query,peer){const host=peer.address||peer.host,port=query.a.implied_port?peer.port:query.a.port;if(!port||"number"!=typeof port||0>=port||65535prev.seq))return this._rpc.error(peer,query,[302,"sequence number less than current"]);this._values.set(keyHex,{v,k:a.k,salt:a.salt,sig:a.sig,seq:a.seq,id})}else this._values.set(keyHex,{v,id});this._rpc.response(peer,query,{id:this._rpc.id})}_bootstrap(populate){function ready(){self.ready||(self._debug("emit ready"),self.ready=!0,self.emit("ready"))}const self=this;return populate?void this._rpc.populate(self._rpc.id,{q:"find_node",a:{id:self._rpc.id,target:self._rpc.id}},ready):process.nextTick(ready)}_closest(target,message,onmessage,cb){const self=this,table=new KBucket({localNodeId:target,numberOfNodesPerKBucket:this._rpc.k});this._rpc.closest(target,message,function(message,node){return!message.r||(message.r.token&&message.r.id&&Buffer.isBuffer(message.r.id)&&message.r.id.length===self._hashLength&&(self._debug("found node %s (target: %s)",message.r.id,target),table.add({id:message.r.id,host:node.host||node.address,port:node.port,token:message.r.token})),!onmessage||onmessage(message,node))},function(err,n){return err?cb(err):void(self._tables.set(target.toString("hex"),table),self._debug("visited %d nodes",n),cb(null,n))})}_debug(){if(debug.enabled){const args=[].slice.call(arguments);args[0]=`[${this.nodeId.toString("hex").substring(0,7)}] ${args[0]}`;for(let i=1;i */const dgram=require("dgram"),EventEmitter=require("events").EventEmitter,debug=require("debug")("bittorrent-lsd"),LSD_HOST="239.192.152.143",LSD_PORT=6771;module.exports=class LSD extends EventEmitter{constructor(opts={}){if(super(),!opts.peerId)throw new Error("Option `peerId` is required");if(!opts.infoHash)throw new Error("Option `infoHash` is required");if(!opts.port)throw new Error("Option `port` is required");this.peerId="string"==typeof opts.peerId?opts.peerId:opts.peerId.toString("hex"),this.infoHash="string"==typeof opts.infoHash?opts.infoHash.toLowerCase():opts.infoHash.toString("hex"),this.port="string"==typeof opts.port?opts.port:opts.port.toString(),this.cookie=`bittorrent-lsd-${this.peerId}`,this.destroyed=!1,this.annouceIntervalId=null,this.server=dgram.createSocket({type:"udp4",reuseAddr:!0});this.server.on("listening",()=>{debug("listening");try{this.server.addMembership(LSD_HOST)}catch(err){this.emit("warning",err)}}),this.server.on("message",(msg,rinfo)=>{debug("message",msg.toString(),`${rinfo.address}:${rinfo.port}`);const parsedAnnounce=this._parseAnnounce(msg.toString());null==parsedAnnounce||parsedAnnounce.cookie===this.cookie||parsedAnnounce.infoHash.forEach(infoHash=>{this.emit("peer",`${rinfo.address}:${parsedAnnounce.port}`,infoHash)})}),this.server.on("error",err=>{this.emit("error",err)})}_parseAnnounce(announce){const checkInfoHash=infoHash=>/^[0-9a-fA-F]{40}$/.test(infoHash);debug("parse announce",announce);const sections=announce.split("\r\n");if("BT-SEARCH * HTTP/1.1"!==sections[0])return this.emit("warning","Invalid LSD announce (header)"),null;const host=sections[1].split("Host: ")[1];if(!(host=>/^(239.192.152.143|\[ff15::efc0:988f\]):6771$/.test(host))(host))return this.emit("warning","Invalid LSD announce (host)"),null;const port=sections[2].split("Port: ")[1];if(!(port=>/^\d+$/.test(port))(port))return this.emit("warning","Invalid LSD announce (port)"),null;const infoHash=sections.filter(section=>section.includes("Infohash: ")).map(section=>section.split("Infohash: ")[1]).filter(infoHash=>checkInfoHash(infoHash));if(0===infoHash.length)return this.emit("warning","Invalid LSD announce (infoHash)"),null;const cookie=sections.filter(section=>section.includes("cookie: ")).map(section=>section.split("cookie: ")[1]).reduce((acc,cur)=>cur,null);return{host:host,port:port,infoHash:infoHash,cookie:cookie}}destroy(cb){this.destroyed||(this.destroyed=!0,debug("destroy"),clearInterval(this.annouceIntervalId),this.server.close(cb))}start(){debug("start"),this.server.bind(LSD_PORT),this._announce(),this.annouceIntervalId=setInterval(()=>{this._announce()},3e5)}_announce(){debug("send announce");const announce=`BT-SEARCH * HTTP/1.1\r\nHost: ${`${LSD_HOST}:${LSD_PORT}`}\r\nPort: ${this.port}\r\nInfohash: ${this.infoHash}\r\ncookie: ${this.cookie}\r\n\r\n\r\n`;this.server.send(announce,LSD_PORT,LSD_HOST)}}},{debug:69,dgram:63,events:39}],25:[function(require,module){(function(Buffer){(function(){/*! bittorrent-protocol. MIT License. WebTorrent LLC */const arrayRemove=require("unordered-array-remove"),bencode=require("bencode"),BitField=require("bitfield").default,debug=require("debug")("bittorrent-protocol"),randombytes=require("randombytes"),speedometer=require("speedometer"),stream=require("readable-stream"),MESSAGE_PROTOCOL=Buffer.from("\x13BitTorrent protocol"),MESSAGE_KEEP_ALIVE=Buffer.from([0,0,0,0]),MESSAGE_CHOKE=Buffer.from([0,0,0,1,0]),MESSAGE_UNCHOKE=Buffer.from([0,0,0,1,1]),MESSAGE_INTERESTED=Buffer.from([0,0,0,1,2]),MESSAGE_UNINTERESTED=Buffer.from([0,0,0,1,3]),MESSAGE_RESERVED=[0,0,0,0,0,0,0,0],MESSAGE_PORT=[0,0,0,3,9,0,0];class Request{constructor(piece,offset,length,callback){this.piece=piece,this.offset=offset,this.length=length,this.callback=callback}}class Wire extends stream.Duplex{constructor(){super(),this._debugId=randombytes(4).toString("hex"),this._debug("new wire"),this.peerId=null,this.peerIdBuffer=null,this.type=null,this.amChoking=!0,this.amInterested=!1,this.peerChoking=!0,this.peerInterested=!1,this.peerPieces=new BitField(0,{grow:4e5}),this.peerExtensions={},this.requests=[],this.peerRequests=[],this.extendedMapping={},this.peerExtendedMapping={},this.extendedHandshake={},this.peerExtendedHandshake={},this._ext={},this._nextExt=1,this.uploaded=0,this.downloaded=0,this.uploadSpeed=speedometer(),this.downloadSpeed=speedometer(),this._keepAliveInterval=null,this._timeout=null,this._timeoutMs=0,this.destroyed=!1,this._finished=!1,this._parserSize=0,this._parser=null,this._buffer=[],this._bufferSize=0,this.once("finish",()=>this._onFinish()),this._parseHandshake()}setKeepAlive(enable){this._debug("setKeepAlive %s",enable),clearInterval(this._keepAliveInterval);!1===enable||(this._keepAliveInterval=setInterval(()=>{this.keepAlive()},55e3))}setTimeout(ms,unref){this._debug("setTimeout ms=%d unref=%s",ms,unref),this._clearTimeout(),this._timeoutMs=ms,this._timeoutUnref=!!unref,this._updateTimeout()}destroy(){this.destroyed||(this.destroyed=!0,this._debug("destroy"),this.emit("close"),this.end())}end(...args){this._debug("end"),this._onUninterested(),this._onChoke(),super.end(...args)}use(Extension){function noop(){}const name=Extension.prototype.name;if(!name)throw new Error("Extension class requires a \"name\" property on the prototype");this._debug("use extension.name=%s",name);const ext=this._nextExt,handler=new Extension(this);"function"!=typeof handler.onHandshake&&(handler.onHandshake=noop),"function"!=typeof handler.onExtendedHandshake&&(handler.onExtendedHandshake=noop),"function"!=typeof handler.onMessage&&(handler.onMessage=noop),this.extendedMapping[ext]=name,this._ext[name]=handler,this[name]=handler,this._nextExt+=1}keepAlive(){this._debug("keep-alive"),this._push(MESSAGE_KEEP_ALIVE)}handshake(infoHash,peerId,extensions){let infoHashBuffer,peerIdBuffer;if("string"==typeof infoHash?(infoHash=infoHash.toLowerCase(),infoHashBuffer=Buffer.from(infoHash,"hex")):(infoHashBuffer=infoHash,infoHash=infoHashBuffer.toString("hex")),"string"==typeof peerId?peerIdBuffer=Buffer.from(peerId,"hex"):(peerIdBuffer=peerId,peerId=peerIdBuffer.toString("hex")),20!==infoHashBuffer.length||20!==peerIdBuffer.length)throw new Error("infoHash and peerId MUST have length 20");this._debug("handshake i=%s p=%s exts=%o",infoHash,peerId,extensions);const reserved=Buffer.from(MESSAGE_RESERVED);reserved[5]|=16,extensions&&extensions.dht&&(reserved[7]|=1),this._push(Buffer.concat([MESSAGE_PROTOCOL,reserved,infoHashBuffer,peerIdBuffer])),this._handshakeSent=!0,this.peerExtensions.extended&&!this._extendedHandshakeSent&&this._sendExtendedHandshake()}_sendExtendedHandshake(){const msg=Object.assign({},this.extendedHandshake);for(const ext in msg.m={},this.extendedMapping){const name=this.extendedMapping[ext];msg.m[name]=+ext}this.extended(0,bencode.encode(msg)),this._extendedHandshakeSent=!0}choke(){if(!this.amChoking){for(this.amChoking=!0,this._debug("choke");this.peerRequests.length;)this.peerRequests.pop();this._push(MESSAGE_CHOKE)}}unchoke(){this.amChoking&&(this.amChoking=!1,this._debug("unchoke"),this._push(MESSAGE_UNCHOKE))}interested(){this.amInterested||(this.amInterested=!0,this._debug("interested"),this._push(MESSAGE_INTERESTED))}uninterested(){this.amInterested&&(this.amInterested=!1,this._debug("uninterested"),this._push(MESSAGE_UNINTERESTED))}have(index){this._debug("have %d",index),this._message(4,[index],null)}bitfield(bitfield){this._debug("bitfield"),Buffer.isBuffer(bitfield)||(bitfield=bitfield.buffer),this._message(5,[],bitfield)}request(index,offset,length,cb){return cb||(cb=()=>{}),this._finished?cb(new Error("wire is closed")):this.peerChoking?cb(new Error("peer is choking")):void(this._debug("request index=%d offset=%d length=%d",index,offset,length),this.requests.push(new Request(index,offset,length,cb)),this._updateTimeout(),this._message(6,[index,offset,length],null))}piece(index,offset,buffer){this._debug("piece index=%d offset=%d",index,offset),this.uploaded+=buffer.length,this.uploadSpeed(buffer.length),this.emit("upload",buffer.length),this._message(7,[index,offset],buffer)}cancel(index,offset,length){this._debug("cancel index=%d offset=%d length=%d",index,offset,length),this._callback(this._pull(this.requests,index,offset,length),new Error("request was cancelled"),null),this._message(8,[index,offset,length],null)}port(port){this._debug("port %d",port);const message=Buffer.from(MESSAGE_PORT);message.writeUInt16BE(port,5),this._push(message)}extended(ext,obj){if(this._debug("extended ext=%s",ext),"string"==typeof ext&&this.peerExtendedMapping[ext]&&(ext=this.peerExtendedMapping[ext]),"number"==typeof ext){const extId=Buffer.from([ext]),buf=Buffer.isBuffer(obj)?obj:bencode.encode(obj);this._message(20,[],Buffer.concat([extId,buf]))}else throw new Error(`Unrecognized extension: ${ext}`)}_read(){}_message(id,numbers,data){const dataLength=data?data.length:0,buffer=Buffer.allocUnsafe(5+4*numbers.length);buffer.writeUInt32BE(buffer.length+dataLength-4,0),buffer[4]=id;for(let i=0;irequest===this._pull(this.peerRequests,index,offset,length)?err?this._debug("error satisfying request index=%d offset=%d length=%d (%s)",index,offset,length,err.message):void this.piece(index,offset,buffer):void 0,request=new Request(index,offset,length,respond);this.peerRequests.push(request),this.emit("request",index,offset,length,respond)}_onPiece(index,offset,buffer){this._debug("got piece index=%d offset=%d",index,offset),this._callback(this._pull(this.requests,index,offset,buffer.length),null,buffer),this.downloaded+=buffer.length,this.downloadSpeed(buffer.length),this.emit("download",buffer.length),this.emit("piece",index,offset,buffer)}_onCancel(index,offset,length){this._debug("got cancel index=%d offset=%d length=%d",index,offset,length),this._pull(this.peerRequests,index,offset,length),this.emit("cancel",index,offset,length)}_onPort(port){this._debug("got port %d",port),this.emit("port",port)}_onExtended(ext,buf){if(0===ext){let info;try{info=bencode.decode(buf)}catch(err){this._debug("ignoring invalid extended handshake: %s",err.message||err)}if(!info)return;this.peerExtendedHandshake=info;if("object"==typeof info.m)for(var name in info.m)this.peerExtendedMapping[name]=+info.m[name].toString();for(name in this._ext)this.peerExtendedMapping[name]&&this._ext[name].onExtendedHandshake(this.peerExtendedHandshake);this._debug("got extended handshake"),this.emit("extended","handshake",this.peerExtendedHandshake)}else this.extendedMapping[ext]&&(ext=this.extendedMapping[ext],this._ext[ext]&&this._ext[ext].onMessage(buf)),this._debug("got extended message ext=%s",ext),this.emit("extended",ext,buf)}_onTimeout(){this._debug("request timed out"),this._callback(this.requests.shift(),new Error("request has timed out"),null),this.emit("timeout")}_write(data,encoding,cb){for(this._bufferSize+=data.length,this._buffer.push(data);this._bufferSize>=this._parserSize;){const buffer=1===this._buffer.length?this._buffer[0]:Buffer.concat(this._buffer);this._bufferSize-=this._parserSize,this._buffer=this._bufferSize?[buffer.slice(this._parserSize)]:[],this._parser(buffer.slice(0,this._parserSize))}cb(null)}_callback(request,err,buffer){request&&(this._clearTimeout(),!this.peerChoking&&!this._finished&&this._updateTimeout(),request.callback(err,buffer))}_clearTimeout(){this._timeout&&(clearTimeout(this._timeout),this._timeout=null)}_updateTimeout(){this._timeoutMs&&this.requests.length&&!this._timeout&&(this._timeout=setTimeout(()=>this._onTimeout(),this._timeoutMs),this._timeoutUnref&&this._timeout.unref&&this._timeout.unref())}_parse(size,parser){this._parserSize=size,this._parser=parser}_onMessageLength(buffer){const length=buffer.readUInt32BE(0);0{const pstrlen=buffer.readUInt8(0);this._parse(pstrlen+48,handshake=>{const protocol=handshake.slice(0,pstrlen);return"BitTorrent protocol"===protocol.toString()?void(handshake=handshake.slice(pstrlen),this._onHandshake(handshake.slice(8,28),handshake.slice(28,48),{dht:!!(1&handshake[7]),extended:!!(16&handshake[5])}),this._parse(4,this._onMessageLength)):(this._debug("Error: wire not speaking BitTorrent protocol (%s)",protocol.toString()),void this.end())})})}_onFinish(){for(this._finished=!0,this.push(null);this.read(););for(clearInterval(this._keepAliveInterval),this._parse(Number.MAX_VALUE,()=>{});this.peerRequests.length;)this.peerRequests.pop();for(;this.requests.length;)this._callback(this.requests.pop(),new Error("wire was closed"),null)}_debug(...args){args[0]=`[${this._debugId}] ${args[0]}`,debug(...args)}_pull(requests,piece,offset,length){for(let i=0;i(announceUrl=announceUrl.toString(),"/"===announceUrl[announceUrl.length-1]&&(announceUrl=announceUrl.substring(0,announceUrl.length-1)),announceUrl)),announce=Array.from(new Set(announce));const webrtcSupport=!1!==this._wrtc&&(!!this._wrtc||Peer.WEBRTC_SUPPORT),nextTickWarn=err=>{process.nextTick(()=>{this.emit("warning",err)})};this._trackers=announce.map(announceUrl=>{let parsedUrl;try{parsedUrl=new URL(announceUrl)}catch(err){return nextTickWarn(new Error(`Invalid tracker URL: ${announceUrl}`)),null}const port=parsedUrl.port;if(0>port||65535{tracker.setInterval()})}stop(opts){opts=this._defaultAnnounceOpts(opts),opts.event="stopped",debug("send `stop` %o",opts),this._announce(opts)}complete(opts){opts||(opts={}),opts=this._defaultAnnounceOpts(opts),opts.event="completed",debug("send `complete` %o",opts),this._announce(opts)}update(opts){opts=this._defaultAnnounceOpts(opts),opts.event&&delete opts.event,debug("send `update` %o",opts),this._announce(opts)}_announce(opts){this._trackers.forEach(tracker=>{tracker.announce(opts)})}scrape(opts){debug("send `scrape`"),opts||(opts={}),this._trackers.forEach(tracker=>{tracker.scrape(opts)})}setInterval(intervalMs){debug("setInterval %d",intervalMs),this._trackers.forEach(tracker=>{tracker.setInterval(intervalMs)})}destroy(cb){if(!this.destroyed){this.destroyed=!0,debug("destroy");const tasks=this._trackers.map(tracker=>cb=>{tracker.destroy(cb)});parallel(tasks,cb),this._trackers=[],this._getAnnounceOpts=null}}_defaultAnnounceOpts(opts={}){return null==opts.numwant&&(opts.numwant=common.DEFAULT_ANNOUNCE_PEERS),null==opts.uploaded&&(opts.uploaded=0),null==opts.downloaded&&(opts.downloaded=0),this._getAnnounceOpts&&(opts=Object.assign({},opts,this._getAnnounceOpts())),opts}}Client.scrape=(opts,cb)=>{if(cb=once(cb),!opts.infoHash)throw new Error("Option `infoHash` is required");if(!opts.announce)throw new Error("Option `announce` is required");const clientOpts=Object.assign({},opts,{infoHash:Array.isArray(opts.infoHash)?opts.infoHash[0]:opts.infoHash,peerId:Buffer.from("01234567890123456789"),port:6881}),client=new Client(clientOpts);client.once("error",cb),client.once("warning",cb);let len=Array.isArray(opts.infoHash)?opts.infoHash.length:1;const results={};return client.on("scrape",data=>{if(len-=1,results[data.infoHash]=data,0===len){client.destroy();const keys=Object.keys(results);1===keys.length?cb(null,results[keys[0]]):cb(null,results)}}),opts.infoHash=Array.isArray(opts.infoHash)?opts.infoHash.map(infoHash=>Buffer.from(infoHash,"hex")):Buffer.from(opts.infoHash,"hex"),client.scrape({infoHash:opts.infoHash}),client},module.exports=Client}).call(this)}).call(this,require("_process"),require("buffer").Buffer)},{"./lib/client/http-tracker":27,"./lib/client/udp-tracker":29,"./lib/client/websocket-tracker":30,"./lib/common":32,_process:132,buffer:38,debug:69,events:39,once:129,"run-parallel":162,"simple-peer":168}],27:[function(require,module){(function(Buffer){(function(){const arrayRemove=require("unordered-array-remove"),bencode=require("bencode"),compact2string=require("compact2string"),debug=require("debug")("bittorrent-tracker:http-tracker"),get=require("simple-get"),common=require("../common"),Tracker=require("./tracker");class HTTPTracker extends Tracker{constructor(client,announceUrl){super(client,announceUrl),debug("new http tracker %s",announceUrl),this.scrapeUrl=null;const match=this.announceUrl.match(/\/(announce)[^/]*$/);if(match){const pre=this.announceUrl.slice(0,match.index),post=this.announceUrl.slice(match.index+9);this.scrapeUrl=`${pre}/scrape${post}`}this.cleanupFns=[],this.maybeDestroyCleanup=null}announce(opts){if(!this.destroyed){const params=Object.assign({},opts,{compact:null==opts.compact?1:opts.compact,info_hash:this.client._infoHashBinary,peer_id:this.client._peerIdBinary,port:this.client._port});this._trackerId&&(params.trackerid=this._trackerId),this._request(this.announceUrl,params,(err,data)=>err?this.client.emit("warning",err):void this._onAnnounceResponse(data))}}scrape(opts){if(this.destroyed)return;if(!this.scrapeUrl)return void this.client.emit("error",new Error(`scrape not supported ${this.announceUrl}`));const infoHashes=Array.isArray(opts.infoHash)&&0infoHash.toString("binary")):opts.infoHash&&opts.infoHash.toString("binary")||this.client._infoHashBinary;this._request(this.scrapeUrl,{info_hash:infoHashes},(err,data)=>err?this.client.emit("warning",err):void this._onScrapeResponse(data))}destroy(cb){function destroyCleanup(){timeout&&(clearTimeout(timeout),timeout=null),self.maybeDestroyCleanup=null,self.cleanupFns.slice(0).forEach(cleanup=>{cleanup()}),self.cleanupFns=[],cb(null)}const self=this;if(this.destroyed)return cb(null);if(this.destroyed=!0,clearInterval(this.interval),0===this.cleanupFns.length)return destroyCleanup();var timeout=setTimeout(destroyCleanup,common.DESTROY_TIMEOUT);this.maybeDestroyCleanup=()=>{0===this.cleanupFns.length&&destroyCleanup()}}_request(requestUrl,params,cb){function cleanup(){request&&(arrayRemove(self.cleanupFns,self.cleanupFns.indexOf(cleanup)),request.abort(),request=null),self.maybeDestroyCleanup&&self.maybeDestroyCleanup()}const self=this,u=requestUrl+(requestUrl.includes("?")?"&":"?")+common.querystringStringify(params);this.cleanupFns.push(cleanup);let request=get.concat({url:u,timeout:common.REQUEST_TIMEOUT,headers:{"user-agent":this.client._userAgent||""}},function(err,res,data){if(cleanup(),!self.destroyed){if(err)return cb(err);if(200!==res.statusCode)return cb(new Error(`Non-200 response code ${res.statusCode} from ${self.announceUrl}`));if(!data||0===data.length)return cb(new Error(`Invalid tracker response from${self.announceUrl}`));try{data=bencode.decode(data)}catch(err){return cb(new Error(`Error decoding tracker response: ${err.message}`))}const failure=data["failure reason"];if(failure)return debug(`failure from ${requestUrl} (${failure})`),cb(new Error(failure));const warning=data["warning message"];warning&&(debug(`warning from ${requestUrl} (${warning})`),self.client.emit("warning",new Error(warning))),debug(`response from ${requestUrl}`),cb(null,data)}})}_onAnnounceResponse(data){const interval=data.interval||data["min interval"];interval&&this.setInterval(1e3*interval);const trackerId=data["tracker id"];trackerId&&(this._trackerId=trackerId);const response=Object.assign({},data,{announce:this.announceUrl,infoHash:common.binaryToHex(data.info_hash)});this.client.emit("update",response);let addrs;if(Buffer.isBuffer(data.peers)){try{addrs=compact2string.multi(data.peers)}catch(err){return this.client.emit("warning",err)}addrs.forEach(addr=>{this.client.emit("peer",addr)})}else Array.isArray(data.peers)&&data.peers.forEach(peer=>{this.client.emit("peer",`${peer.ip}:${peer.port}`)});if(Buffer.isBuffer(data.peers6)){try{addrs=compact2string.multi6(data.peers6)}catch(err){return this.client.emit("warning",err)}addrs.forEach(addr=>{this.client.emit("peer",addr)})}else Array.isArray(data.peers6)&&data.peers6.forEach(peer=>{const ip=/^\[/.test(peer.ip)||!/:/.test(peer.ip)?peer.ip:`[${peer.ip}]`;this.client.emit("peer",`${ip}:${peer.port}`)})}_onScrapeResponse(data){data=data.files||data.host||{};const keys=Object.keys(data);return 0===keys.length?void this.client.emit("warning",new Error("invalid scrape response")):void keys.forEach(infoHash=>{const response=Object.assign(data[infoHash],{announce:this.announceUrl,infoHash:common.binaryToHex(infoHash)});this.client.emit("scrape",response)})}}HTTPTracker.prototype.DEFAULT_ANNOUNCE_INTERVAL=1800000,module.exports=HTTPTracker}).call(this)}).call(this,{isBuffer:require("../../../is-buffer/index.js")})},{"../../../is-buffer/index.js":101,"../common":32,"./tracker":28,bencode:19,compact2string:67,debug:69,"simple-get":167,"unordered-array-remove":191}],28:[function(require,module){const EventEmitter=require("events");module.exports=class Tracker extends EventEmitter{constructor(client,announceUrl){super(),this.client=client,this.announceUrl=announceUrl,this.interval=null,this.destroyed=!1}setInterval(intervalMs){null==intervalMs&&(intervalMs=this.DEFAULT_ANNOUNCE_INTERVAL),clearInterval(this.interval),intervalMs&&(this.interval=setInterval(()=>{this.announce(this.client._defaultAnnounceOpts())},intervalMs),this.interval.unref&&this.interval.unref())}}},{events:39}],29:[function(require,module){(function(Buffer){(function(){function genTransactionId(){return randombytes(4)}function toUInt16(n){const buf=Buffer.allocUnsafe(2);return buf.writeUInt16BE(n,0),buf}function toUInt64(n){if(n>MAX_UINT||"string"==typeof n){const bytes=new BN(n).toArray();for(;8>bytes.length;)bytes.unshift(0);return Buffer.from(bytes)}return Buffer.concat([common.toUInt32(0),common.toUInt32(n)])}function noop(){}const arrayRemove=require("unordered-array-remove"),BN=require("bn.js"),compact2string=require("compact2string"),debug=require("debug")("bittorrent-tracker:udp-tracker"),dgram=require("dgram"),randombytes=require("randombytes"),common=require("../common"),Tracker=require("./tracker");class UDPTracker extends Tracker{constructor(client,announceUrl){super(client,announceUrl),debug("new udp tracker %s",announceUrl),this.cleanupFns=[],this.maybeDestroyCleanup=null}announce(opts){this.destroyed||this._request(opts)}scrape(opts){this.destroyed||(opts._scrape=!0,this._request(opts))}destroy(cb){function destroyCleanup(){timeout&&(clearTimeout(timeout),timeout=null),self.maybeDestroyCleanup=null,self.cleanupFns.slice(0).forEach(cleanup=>{cleanup()}),self.cleanupFns=[],cb(null)}const self=this;if(this.destroyed)return cb(null);if(this.destroyed=!0,clearInterval(this.interval),0===this.cleanupFns.length)return destroyCleanup();var timeout=setTimeout(destroyCleanup,common.DESTROY_TIMEOUT);this.maybeDestroyCleanup=()=>{0===this.cleanupFns.length&&destroyCleanup()}}_request(opts){function cleanup(){if(timeout&&(clearTimeout(timeout),timeout=null),socket){arrayRemove(self.cleanupFns,self.cleanupFns.indexOf(cleanup)),socket.removeListener("error",onError),socket.removeListener("message",onSocketMessage),socket.on("error",noop);try{socket.close()}catch(err){}socket=null}self.maybeDestroyCleanup&&self.maybeDestroyCleanup()}function onError(err){if(cleanup(),!self.destroyed){try{err.message&&(err.message+=` (${self.announceUrl})`)}catch(ignoredErr){}self.client.emit("warning",err)}}function onSocketMessage(msg){if(8>msg.length||msg.readUInt32BE(4)!==transactionId.readUInt32BE(0))return onError(new Error("tracker sent invalid transaction id"));const action=msg.readUInt32BE(0);switch(debug("UDP response %s, action %s",self.announceUrl,action),action){case 0:{if(16>msg.length)return onError(new Error("invalid udp handshake"));opts._scrape?scrape(msg.slice(8,16)):announce(msg.slice(8,16),opts);break}case 1:{if(cleanup(),self.destroyed)return;if(20>msg.length)return onError(new Error("invalid announce message"));const interval=msg.readUInt32BE(8);interval&&self.setInterval(1e3*interval),self.client.emit("update",{announce:self.announceUrl,complete:msg.readUInt32BE(16),incomplete:msg.readUInt32BE(12)});let addrs;try{addrs=compact2string.multi(msg.slice(20))}catch(err){return self.client.emit("warning",err)}addrs.forEach(addr=>{self.client.emit("peer",addr)});break}case 2:{if(cleanup(),self.destroyed)return;if(20>msg.length||0!=(msg.length-8)%12)return onError(new Error("invalid scrape message"));const infoHashes=Array.isArray(opts.infoHash)&&0infoHash.toString("hex")):[opts.infoHash&&opts.infoHash.toString("hex")||self.client.infoHash];for(let i=0,len=(msg.length-8)/12;imsg.length)return onError(new Error("invalid error message"));self.client.emit("warning",new Error(msg.slice(8).toString()));break}default:onError(new Error("tracker sent invalid action"));}}function send(message){socket.send(message,0,message.length,port,hostname)}function announce(connectionId,opts){transactionId=genTransactionId(),send(Buffer.concat([connectionId,common.toUInt32(common.ACTIONS.ANNOUNCE),transactionId,self.client._infoHashBuffer,self.client._peerIdBuffer,toUInt64(opts.downloaded),null==opts.left?Buffer.from("FFFFFFFFFFFFFFFF","hex"):toUInt64(opts.left),toUInt64(opts.uploaded),common.toUInt32(common.EVENTS[opts.event]||0),common.toUInt32(0),common.toUInt32(0),common.toUInt32(opts.numwant),toUInt16(self.client._port)]))}function scrape(connectionId){transactionId=genTransactionId();const infoHash=Array.isArray(opts.infoHash)&&0{"stopped"===opts.event?cleanup():onError(new Error(`tracker request timed out (${opts.event})`)),timeout=null},common.REQUEST_TIMEOUT);timeout.unref&&timeout.unref(),this.cleanupFns.push(cleanup),send(Buffer.concat([common.CONNECTION_ID,common.toUInt32(common.ACTIONS.CONNECT),transactionId])),socket.once("error",onError),socket.on("message",onSocketMessage)}}UDPTracker.prototype.DEFAULT_ANNOUNCE_INTERVAL=1800000;const MAX_UINT=4294967295;module.exports=UDPTracker}).call(this)}).call(this,require("buffer").Buffer)},{"../common":32,"./tracker":28,"bn.js":35,buffer:38,compact2string:67,debug:69,dgram:63,randombytes:140,"unordered-array-remove":191}],30:[function(require,module){function noop(){}const debug=require("debug")("bittorrent-tracker:websocket-tracker"),Peer=require("simple-peer"),randombytes=require("randombytes"),Socket=require("simple-websocket"),common=require("../common"),Tracker=require("./tracker"),socketPool={};class WebSocketTracker extends Tracker{constructor(client,announceUrl){super(client,announceUrl),debug("new websocket tracker %s",announceUrl),this.peers={},this.socket=null,this.reconnecting=!1,this.retries=0,this.reconnectTimer=null,this.expectingResponse=!1,this._openSocket()}announce(opts){if(this.destroyed||this.reconnecting)return;if(!this.socket.connected)return void this.socket.once("connect",()=>{this.announce(opts)});const params=Object.assign({},opts,{action:"announce",info_hash:this.client._infoHashBinary,peer_id:this.client._peerIdBinary});if(this._trackerId&&(params.trackerid=this._trackerId),"stopped"===opts.event||"completed"===opts.event)this._send(params);else{const numwant=_Mathmin(opts.numwant,10);this._generateOffers(numwant,offers=>{params.numwant=numwant,params.offers=offers,this._send(params)})}}scrape(opts){if(this.destroyed||this.reconnecting)return;if(!this.socket.connected)return void this.socket.once("connect",()=>{this.scrape(opts)});const infoHashes=Array.isArray(opts.infoHash)&&0infoHash.toString("binary")):opts.infoHash&&opts.infoHash.toString("binary")||this.client._infoHashBinary;this._send({action:"scrape",info_hash:infoHashes})}destroy(cb=noop){function destroyCleanup(){timeout&&(clearTimeout(timeout),timeout=null),socket.removeListener("data",destroyCleanup),socket.destroy(),socket=null}if(this.destroyed)return cb(null);for(const peerId in this.destroyed=!0,clearInterval(this.interval),clearTimeout(this.reconnectTimer),this.peers){const peer=this.peers[peerId];clearTimeout(peer.trackerTimeout),peer.destroy()}if(this.peers=null,this.socket&&(this.socket.removeListener("connect",this._onSocketConnectBound),this.socket.removeListener("data",this._onSocketDataBound),this.socket.removeListener("close",this._onSocketCloseBound),this.socket.removeListener("error",this._onSocketErrorBound),this.socket=null),this._onSocketConnectBound=null,this._onSocketErrorBound=null,this._onSocketDataBound=null,this._onSocketCloseBound=null,socketPool[this.announceUrl]&&(socketPool[this.announceUrl].consumers-=1),0{this._onSocketConnect()},this._onSocketErrorBound=err=>{this._onSocketError(err)},this._onSocketDataBound=data=>{this._onSocketData(data)},this._onSocketCloseBound=()=>{this._onSocketClose()},this.socket=socketPool[this.announceUrl],this.socket?(socketPool[this.announceUrl].consumers+=1,this.socket.connected&&this._onSocketConnectBound()):(this.socket=socketPool[this.announceUrl]=new Socket(this.announceUrl),this.socket.consumers=1,this.socket.once("connect",this._onSocketConnectBound)),this.socket.on("data",this._onSocketDataBound),this.socket.once("close",this._onSocketCloseBound),this.socket.once("error",this._onSocketErrorBound)}_onSocketConnect(){this.destroyed||this.reconnecting&&(this.reconnecting=!1,this.retries=0,this.announce(this.client._defaultAnnounceOpts()))}_onSocketData(data){if(!this.destroyed){this.expectingResponse=!1;try{data=JSON.parse(data)}catch(err){return void this.client.emit("warning",new Error("Invalid tracker response"))}"announce"===data.action?this._onAnnounceResponse(data):"scrape"===data.action?this._onScrapeResponse(data):this._onSocketError(new Error(`invalid action in WS response: ${data.action}`))}}_onAnnounceResponse(data){if(data.info_hash!==this.client._infoHashBinary)return void debug("ignoring websocket data from %s for %s (looking for %s: reused socket)",this.announceUrl,common.binaryToHex(data.info_hash),this.client.infoHash);if(data.peer_id&&data.peer_id===this.client._peerIdBinary)return;debug("received %s from %s for %s",JSON.stringify(data),this.announceUrl,this.client.infoHash);const failure=data["failure reason"];if(failure)return this.client.emit("warning",new Error(failure));const warning=data["warning message"];warning&&this.client.emit("warning",new Error(warning));const interval=data.interval||data["min interval"];interval&&this.setInterval(1e3*interval);const trackerId=data["tracker id"];if(trackerId&&(this._trackerId=trackerId),null!=data.complete){const response=Object.assign({},data,{announce:this.announceUrl,infoHash:common.binaryToHex(data.info_hash)});this.client.emit("update",response)}let peer;if(data.offer&&data.peer_id&&(debug("creating peer (from remote offer)"),peer=this._createPeer(),peer.id=common.binaryToHex(data.peer_id),peer.once("signal",answer=>{const params={action:"announce",info_hash:this.client._infoHashBinary,peer_id:this.client._peerIdBinary,to_peer_id:data.peer_id,answer,offer_id:data.offer_id};this._trackerId&&(params.trackerid=this._trackerId),this._send(params)}),peer.signal(data.offer),this.client.emit("peer",peer)),data.answer&&data.peer_id){const offerId=common.binaryToHex(data.offer_id);peer=this.peers[offerId],peer?(peer.id=common.binaryToHex(data.peer_id),peer.signal(data.answer),this.client.emit("peer",peer),clearTimeout(peer.trackerTimeout),peer.trackerTimeout=null,delete this.peers[offerId]):debug(`got unexpected answer: ${JSON.stringify(data.answer)}`)}}_onScrapeResponse(data){data=data.files||{};const keys=Object.keys(data);return 0===keys.length?void this.client.emit("warning",new Error("invalid scrape response")):void keys.forEach(infoHash=>{const response=Object.assign(data[infoHash],{announce:this.announceUrl,infoHash:common.binaryToHex(infoHash)});this.client.emit("scrape",response)})}_onSocketClose(){this.destroyed||(this.destroy(),this._startReconnectTimer())}_onSocketError(err){this.destroyed||(this.destroy(),this.client.emit("warning",err),this._startReconnectTimer())}_startReconnectTimer(){const ms=_Mathfloor(Math.random()*300000)+_Mathmin(_Mathpow(2,this.retries)*10000,3600000);this.reconnecting=!0,clearTimeout(this.reconnectTimer),this.reconnectTimer=setTimeout(()=>{this.retries++,this._openSocket()},ms),this.reconnectTimer.unref&&this.reconnectTimer.unref(),debug("reconnecting socket in %s ms",ms)}_send(params){if(!this.destroyed){this.expectingResponse=!0;const message=JSON.stringify(params);debug("send %s",message),this.socket.send(message)}}_generateOffers(numwant,cb){function generateOffer(){const offerId=randombytes(20).toString("hex");debug("creating peer (from _generateOffers)");const peer=self.peers[offerId]=self._createPeer({initiator:!0});peer.once("signal",offer=>{offers.push({offer,offer_id:common.hexToBinary(offerId)}),checkDone()}),peer.trackerTimeout=setTimeout(()=>{debug("tracker timeout: destroying peer"),peer.trackerTimeout=null,delete self.peers[offerId],peer.destroy()},50000),peer.trackerTimeout.unref&&peer.trackerTimeout.unref()}function checkDone(){offers.length===numwant&&(debug("generated %s offers",numwant),cb(offers))}const self=this,offers=[];debug("generating %s offers",numwant);for(let i=0;i */module.exports=function(blob,cb){function onLoadEnd(e){reader.removeEventListener("loadend",onLoadEnd,!1),e.error?cb(e.error):cb(null,Buffer.from(reader.result))}if("undefined"==typeof Blob||!(blob instanceof Blob))throw new Error("first argument must be a Blob");if("function"!=typeof cb)throw new Error("second argument must be a function");const reader=new FileReader;reader.addEventListener("loadend",onLoadEnd,!1),reader.readAsArrayBuffer(blob)}}).call(this)}).call(this,require("buffer").Buffer)},{buffer:38}],34:[function(require,module){(function(Buffer){(function(){const{Transform}=require("readable-stream");module.exports=class Block extends Transform{constructor(size,opts={}){super(opts),"object"==typeof size&&(opts=size,size=opts.size),this.size=size||512;const{nopad,zeroPadding=!0}=opts;this._zeroPadding=!nopad&&!!zeroPadding,this._buffered=[],this._bufferedBytes=0}_transform(buf,enc,next){for(this._bufferedBytes+=buf.length,this._buffered.push(buf);this._bufferedBytes>=this.size;){const b=Buffer.concat(this._buffered);this._bufferedBytes-=this.size,this.push(b.slice(0,this.size)),this._buffered=[b.slice(this.size,b.length)]}next()}_flush(){if(this._bufferedBytes&&this._zeroPadding){const zeroes=Buffer.alloc(this.size-this._bufferedBytes);this._buffered.push(zeroes),this.push(Buffer.concat(this._buffered)),this._buffered=null}else this._bufferedBytes&&(this.push(Buffer.concat(this._buffered)),this._buffered=null);this.push(null)}}}).call(this)}).call(this,require("buffer").Buffer)},{buffer:38,"readable-stream":157}],35:[function(require,module){(function(module,exports){'use strict';var _Mathimul=Math.imul,_Mathclz=Math.clz32;function assert(val,msg){if(!val)throw new Error(msg||"Assertion failed")}function inherits(ctor,superCtor){ctor.super_=superCtor;var TempCtor=function(){};TempCtor.prototype=superCtor.prototype,ctor.prototype=new TempCtor,ctor.prototype.constructor=ctor}function BN(number,base,endian){return BN.isBN(number)?number:void(this.negative=0,this.words=null,this.length=0,this.red=null,null!==number&&(("le"===base||"be"===base)&&(endian=base,base=10),this._init(number||0,base||10,endian||"be")))}function parseHex(str,start,end){for(var r=0,len=_Mathmin(str.length,end),z=0,i=start,c;i=c?c-49+10:17<=c&&22>=c?c-17+10:c,r|=b,z|=b}return assert(!(240&z),"Invalid character in "+str),r}function parseBase(str,start,end,mul){for(var r=0,b=0,len=_Mathmin(str.length,end),i=start,c;i"}function toBitArray(num){for(var w=Array(num.bitLength()),bit=0;bit>>wbit}return w}function smallMulTo(self,num,out){out.negative=num.negative^self.negative;var len=0|self.length+num.length;out.length=len,len=0|len-1;var a=0|self.words[0],b=0|num.words[0],r=a*b,lo=67108863&r,carry=0|r/67108864;out.words[0]=lo;for(var k=1;k>>26,rword=67108863&carry,maxJ=_Mathmin(k,num.length-1),j=_Mathmax(0,k-self.length+1),i;j<=maxJ;j++)i=0|k-j,a=0|self.words[i],b=0|num.words[j],r=a*b+rword,ncarry+=0|r/67108864,rword=67108863&r;out.words[k]=0|rword,carry=0|ncarry}return 0===carry?out.length--:out.words[k]=0|carry,out._strip()}function bigMulTo(self,num,out){out.negative=num.negative^self.negative,out.length=self.length+num.length;for(var carry=0,hncarry=0,k=0,ncarry;k>>26),hncarry+=ncarry>>>26,ncarry&=67108863}out.words[k]=rword,carry=ncarry,ncarry=hncarry}return 0===carry?out.length--:out.words[k]=carry,out._strip()}function jumboMulTo(self,num,out){return bigMulTo(self,num,out)}function FFTM(x,y){this.x=x,this.y=y}function MPrime(name,p){this.name=name,this.p=new BN(p,16),this.n=this.p.bitLength(),this.k=new BN(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}function K256(){MPrime.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function P224(){MPrime.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function P192(){MPrime.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function P25519(){MPrime.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function Red(m){if("string"==typeof m){var prime=BN._prime(m);this.m=prime.p,this.prime=prime}else assert(m.gtn(1),"modulus must be greater than 1"),this.m=m,this.prime=null}function Mont(m){Red.call(this,m),this.shift=this.m.bitLength(),0!=this.shift%26&&(this.shift+=26-this.shift%26),this.r=new BN(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}"object"==typeof module?module.exports=BN:exports.BN=BN,BN.BN=BN,BN.wordSize=26;var Buffer;try{Buffer=require("buffer").Buffer}catch(e){}if(BN.isBN=function(num){return!!(num instanceof BN)||null!==num&&"object"==typeof num&&num.constructor.wordSize===BN.wordSize&&Array.isArray(num.words)},BN.max=function(left,right){return 0left.cmp(right)?left:right},BN.prototype._init=function(number,base,endian){if("number"==typeof number)return this._initNumber(number,base,endian);if("object"==typeof number)return this._initArray(number,base,endian);"hex"===base&&(base=16),assert(base===(0|base)&&2<=base&&36>=base),number=number.toString().replace(/\s+/g,"");var start=0;"-"===number[0]&&start++,16===base?this._parseHex(number,start):this._parseBase(number,base,start),"-"===number[0]&&(this.negative=1),this._strip(),"le"!==endian||this._initArray(this.toArray(),base,endian)},BN.prototype._initNumber=function(number,base,endian){0>number&&(this.negative=1,number=-number),67108864>number?(this.words=[67108863&number],this.length=1):4503599627370496>number?(this.words=[67108863&number,67108863&number/67108864],this.length=2):(assert(9007199254740992>number),this.words=[67108863&number,67108863&number/67108864,1],this.length=3),"le"!==endian||this._initArray(this.toArray(),base,endian)},BN.prototype._initArray=function(number,base,endian){if(assert("number"==typeof number.length),0>=number.length)return this.words=[0],this.length=1,this;this.length=_Mathceil(number.length/3),this.words=Array(this.length);for(var i=0;i>>26-off,off+=24,26<=off&&(off-=26,j++);else if("le"===endian)for(i=0,j=0;i>>26-off,off+=24,26<=off&&(off-=26,j++);return this._strip()},BN.prototype._parseHex=function(number,start){this.length=_Mathceil((number.length-start)/6),this.words=Array(this.length);for(var i=0;i=start;i-=6)w=parseHex(number,i,i+6),this.words[j]|=67108863&w<>>26-off,off+=24,26<=off&&(off-=26,j++);i+6!==start&&(w=parseHex(number,start,i+6),this.words[j]|=67108863&w<>>26-off),this._strip()},BN.prototype._parseBase=function(number,base,start){this.words=[0],this.length=1;for(var limbLen=0,limbPow=1;67108863>=limbPow;limbPow*=base)limbLen++;limbLen--,limbPow=0|limbPow/base;for(var total=number.length-start,mod=total%limbLen,end=_Mathmin(total,total-mod)+start,word=0,i=start;ithis.words[0]+word?this.words[0]+=word:this._iaddn(word);if(0!==mod){var pow=1;for(word=parseBase(number,i,number.length,base),i=0;ithis.words[0]+word?this.words[0]+=word:this._iaddn(word)}},BN.prototype.copy=function(dest){dest.words=Array(this.length);for(var i=0;i>>24-off,out=0!==carry||i!==this.length-1?zeros[6-word.length]+word+out:word+out,off+=2,26<=off&&(off-=26,i--)}for(0!==carry&&(out=carry.toString(16)+out);0!=out.length%padding;)out="0"+out;return 0!==this.negative&&(out="-"+out),out}if(base===(0|base)&&2<=base&&36>=base){var groupSize=groupSizes[base],groupBase=groupBases[base];out="";var c=this.clone();for(c.negative=0;!c.isZero();){var r=c.modrn(groupBase).toString(base);c=c.idivn(groupBase),out=c.isZero()?r+out:zeros[groupSize-r.length]+r+out}for(this.isZero()&&(out="0"+out);0!=out.length%padding;)out="0"+out;return 0!==this.negative&&(out="-"+out),out}assert(!1,"Base should be between 2 and 36")},BN.prototype.toNumber=function(){var ret=this.words[0];return 2===this.length?ret+=67108864*this.words[1]:3===this.length&&1===this.words[2]?ret+=4503599627370496+67108864*this.words[1]:2>8),position>16),6==shift?(position>24),carry=0,shift=0):(carry=word>>>24,shift+=2);if(position>8),0<=position&&(res[position--]=255&word>>16),6==shift?(0<=position&&(res[position--]=255&word>>24),carry=0,shift=0):(carry=word>>>24,shift+=2);if(0<=position)for(res[position--]=carry;0<=position;)res[position--]=0},BN.prototype._countBits=_Mathclz?function(w){return 32-_Mathclz(w)}:function(w){var t=w,r=0;return 4096<=t&&(r+=13,t>>>=13),64<=t&&(r+=7,t>>>=7),8<=t&&(r+=4,t>>>=4),2<=t&&(r+=2,t>>>=2),r+t},BN.prototype._zeroBits=function(w){if(0===w)return 26;var t=w,r=0;return 0==(8191&t)&&(r+=13,t>>>=13),0==(127&t)&&(r+=7,t>>>=7),0==(15&t)&&(r+=4,t>>>=4),0==(3&t)&&(r+=2,t>>>=2),0==(1&t)&&r++,r},BN.prototype.bitLength=function(){var w=this.words[this.length-1],hi=this._countBits(w);return 26*(this.length-1)+hi},BN.prototype.zeroBits=function(){if(this.isZero())return 0;for(var r=0,i=0,b;inum.length?this.clone().ior(num):num.clone().ior(this)},BN.prototype.uor=function(num){return this.length>num.length?this.clone().iuor(num):num.clone().iuor(this)},BN.prototype.iuand=function(num){var b=this.length>num.length?num:this;for(var i=0;inum.length?this.clone().iand(num):num.clone().iand(this)},BN.prototype.uand=function(num){return this.length>num.length?this.clone().iuand(num):num.clone().iuand(this)},BN.prototype.iuxor=function(num){var a,b;this.length>num.length?(a=this,b=num):(a=num,b=this);for(var i=0;inum.length?this.clone().ixor(num):num.clone().ixor(this)},BN.prototype.uxor=function(num){return this.length>num.length?this.clone().iuxor(num):num.clone().iuxor(this)},BN.prototype.inotn=function(width){assert("number"==typeof width&&0<=width);var bytesNeeded=0|_Mathceil(width/26),bitsLeft=width%26;this._expand(bytesNeeded),0>26-bitsLeft),this._strip()},BN.prototype.notn=function(width){return this.clone().inotn(width)},BN.prototype.setn=function(bit,val){assert("number"==typeof bit&&0<=bit);var off=0|bit/26,wbit=bit%26;return this._expand(off+1),val?this.words[off]|=1<num.length?(a=this,b=num):(a=num,b=this);for(var carry=0,i=0;i>>26;for(;0!==carry&&i>>26;if(this.length=a.length,0!==carry)this.words[this.length]=carry,this.length++;else if(a!==this)for(;inum.length?this.clone().iadd(num):num.clone().iadd(this)},BN.prototype.isub=function(num){if(0!==num.negative){num.negative=0;var r=this.iadd(num);return num.negative=1,r._normSign()}if(0!==this.negative)return this.negative=0,this.iadd(num),this.negative=1,this._normSign();var cmp=this.cmp(num);if(0===cmp)return this.negative=0,this.length=1,this.words[0]=0,this;var a,b;0>26,this.words[i]=67108863&r;for(;0!==carry&&i>26,this.words[i]=67108863&r;if(0===carry&&i>>13,a1=0|a[1],al1=8191&a1,ah1=a1>>>13,a2=0|a[2],al2=8191&a2,ah2=a2>>>13,a3=0|a[3],al3=8191&a3,ah3=a3>>>13,a4=0|a[4],al4=8191&a4,ah4=a4>>>13,a5=0|a[5],al5=8191&a5,ah5=a5>>>13,a6=0|a[6],al6=8191&a6,ah6=a6>>>13,a7=0|a[7],al7=8191&a7,ah7=a7>>>13,a8=0|a[8],al8=8191&a8,ah8=a8>>>13,a9=0|a[9],al9=8191&a9,ah9=a9>>>13,b0=0|b[0],bl0=8191&b0,bh0=b0>>>13,b1=0|b[1],bl1=8191&b1,bh1=b1>>>13,b2=0|b[2],bl2=8191&b2,bh2=b2>>>13,b3=0|b[3],bl3=8191&b3,bh3=b3>>>13,b4=0|b[4],bl4=8191&b4,bh4=b4>>>13,b5=0|b[5],bl5=8191&b5,bh5=b5>>>13,b6=0|b[6],bl6=8191&b6,bh6=b6>>>13,b7=0|b[7],bl7=8191&b7,bh7=b7>>>13,b8=0|b[8],bl8=8191&b8,bh8=b8>>>13,b9=0|b[9],bl9=8191&b9,bh9=b9>>>13,lo,mid,hi;out.negative=self.negative^num.negative,out.length=19,lo=_Mathimul(al0,bl0),mid=_Mathimul(al0,bh0),mid=0|mid+_Mathimul(ah0,bl0),hi=_Mathimul(ah0,bh0);var w0=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w0>>>26),w0&=67108863,lo=_Mathimul(al1,bl0),mid=_Mathimul(al1,bh0),mid=0|mid+_Mathimul(ah1,bl0),hi=_Mathimul(ah1,bh0),lo=0|lo+_Mathimul(al0,bl1),mid=0|mid+_Mathimul(al0,bh1),mid=0|mid+_Mathimul(ah0,bl1),hi=0|hi+_Mathimul(ah0,bh1);var w1=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w1>>>26),w1&=67108863,lo=_Mathimul(al2,bl0),mid=_Mathimul(al2,bh0),mid=0|mid+_Mathimul(ah2,bl0),hi=_Mathimul(ah2,bh0),lo=0|lo+_Mathimul(al1,bl1),mid=0|mid+_Mathimul(al1,bh1),mid=0|mid+_Mathimul(ah1,bl1),hi=0|hi+_Mathimul(ah1,bh1),lo=0|lo+_Mathimul(al0,bl2),mid=0|mid+_Mathimul(al0,bh2),mid=0|mid+_Mathimul(ah0,bl2),hi=0|hi+_Mathimul(ah0,bh2);var w2=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w2>>>26),w2&=67108863,lo=_Mathimul(al3,bl0),mid=_Mathimul(al3,bh0),mid=0|mid+_Mathimul(ah3,bl0),hi=_Mathimul(ah3,bh0),lo=0|lo+_Mathimul(al2,bl1),mid=0|mid+_Mathimul(al2,bh1),mid=0|mid+_Mathimul(ah2,bl1),hi=0|hi+_Mathimul(ah2,bh1),lo=0|lo+_Mathimul(al1,bl2),mid=0|mid+_Mathimul(al1,bh2),mid=0|mid+_Mathimul(ah1,bl2),hi=0|hi+_Mathimul(ah1,bh2),lo=0|lo+_Mathimul(al0,bl3),mid=0|mid+_Mathimul(al0,bh3),mid=0|mid+_Mathimul(ah0,bl3),hi=0|hi+_Mathimul(ah0,bh3);var w3=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w3>>>26),w3&=67108863,lo=_Mathimul(al4,bl0),mid=_Mathimul(al4,bh0),mid=0|mid+_Mathimul(ah4,bl0),hi=_Mathimul(ah4,bh0),lo=0|lo+_Mathimul(al3,bl1),mid=0|mid+_Mathimul(al3,bh1),mid=0|mid+_Mathimul(ah3,bl1),hi=0|hi+_Mathimul(ah3,bh1),lo=0|lo+_Mathimul(al2,bl2),mid=0|mid+_Mathimul(al2,bh2),mid=0|mid+_Mathimul(ah2,bl2),hi=0|hi+_Mathimul(ah2,bh2),lo=0|lo+_Mathimul(al1,bl3),mid=0|mid+_Mathimul(al1,bh3),mid=0|mid+_Mathimul(ah1,bl3),hi=0|hi+_Mathimul(ah1,bh3),lo=0|lo+_Mathimul(al0,bl4),mid=0|mid+_Mathimul(al0,bh4),mid=0|mid+_Mathimul(ah0,bl4),hi=0|hi+_Mathimul(ah0,bh4);var w4=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w4>>>26),w4&=67108863,lo=_Mathimul(al5,bl0),mid=_Mathimul(al5,bh0),mid=0|mid+_Mathimul(ah5,bl0),hi=_Mathimul(ah5,bh0),lo=0|lo+_Mathimul(al4,bl1),mid=0|mid+_Mathimul(al4,bh1),mid=0|mid+_Mathimul(ah4,bl1),hi=0|hi+_Mathimul(ah4,bh1),lo=0|lo+_Mathimul(al3,bl2),mid=0|mid+_Mathimul(al3,bh2),mid=0|mid+_Mathimul(ah3,bl2),hi=0|hi+_Mathimul(ah3,bh2),lo=0|lo+_Mathimul(al2,bl3),mid=0|mid+_Mathimul(al2,bh3),mid=0|mid+_Mathimul(ah2,bl3),hi=0|hi+_Mathimul(ah2,bh3),lo=0|lo+_Mathimul(al1,bl4),mid=0|mid+_Mathimul(al1,bh4),mid=0|mid+_Mathimul(ah1,bl4),hi=0|hi+_Mathimul(ah1,bh4),lo=0|lo+_Mathimul(al0,bl5),mid=0|mid+_Mathimul(al0,bh5),mid=0|mid+_Mathimul(ah0,bl5),hi=0|hi+_Mathimul(ah0,bh5);var w5=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w5>>>26),w5&=67108863,lo=_Mathimul(al6,bl0),mid=_Mathimul(al6,bh0),mid=0|mid+_Mathimul(ah6,bl0),hi=_Mathimul(ah6,bh0),lo=0|lo+_Mathimul(al5,bl1),mid=0|mid+_Mathimul(al5,bh1),mid=0|mid+_Mathimul(ah5,bl1),hi=0|hi+_Mathimul(ah5,bh1),lo=0|lo+_Mathimul(al4,bl2),mid=0|mid+_Mathimul(al4,bh2),mid=0|mid+_Mathimul(ah4,bl2),hi=0|hi+_Mathimul(ah4,bh2),lo=0|lo+_Mathimul(al3,bl3),mid=0|mid+_Mathimul(al3,bh3),mid=0|mid+_Mathimul(ah3,bl3),hi=0|hi+_Mathimul(ah3,bh3),lo=0|lo+_Mathimul(al2,bl4),mid=0|mid+_Mathimul(al2,bh4),mid=0|mid+_Mathimul(ah2,bl4),hi=0|hi+_Mathimul(ah2,bh4),lo=0|lo+_Mathimul(al1,bl5),mid=0|mid+_Mathimul(al1,bh5),mid=0|mid+_Mathimul(ah1,bl5),hi=0|hi+_Mathimul(ah1,bh5),lo=0|lo+_Mathimul(al0,bl6),mid=0|mid+_Mathimul(al0,bh6),mid=0|mid+_Mathimul(ah0,bl6),hi=0|hi+_Mathimul(ah0,bh6);var w6=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w6>>>26),w6&=67108863,lo=_Mathimul(al7,bl0),mid=_Mathimul(al7,bh0),mid=0|mid+_Mathimul(ah7,bl0),hi=_Mathimul(ah7,bh0),lo=0|lo+_Mathimul(al6,bl1),mid=0|mid+_Mathimul(al6,bh1),mid=0|mid+_Mathimul(ah6,bl1),hi=0|hi+_Mathimul(ah6,bh1),lo=0|lo+_Mathimul(al5,bl2),mid=0|mid+_Mathimul(al5,bh2),mid=0|mid+_Mathimul(ah5,bl2),hi=0|hi+_Mathimul(ah5,bh2),lo=0|lo+_Mathimul(al4,bl3),mid=0|mid+_Mathimul(al4,bh3),mid=0|mid+_Mathimul(ah4,bl3),hi=0|hi+_Mathimul(ah4,bh3),lo=0|lo+_Mathimul(al3,bl4),mid=0|mid+_Mathimul(al3,bh4),mid=0|mid+_Mathimul(ah3,bl4),hi=0|hi+_Mathimul(ah3,bh4),lo=0|lo+_Mathimul(al2,bl5),mid=0|mid+_Mathimul(al2,bh5),mid=0|mid+_Mathimul(ah2,bl5),hi=0|hi+_Mathimul(ah2,bh5),lo=0|lo+_Mathimul(al1,bl6),mid=0|mid+_Mathimul(al1,bh6),mid=0|mid+_Mathimul(ah1,bl6),hi=0|hi+_Mathimul(ah1,bh6),lo=0|lo+_Mathimul(al0,bl7),mid=0|mid+_Mathimul(al0,bh7),mid=0|mid+_Mathimul(ah0,bl7),hi=0|hi+_Mathimul(ah0,bh7);var w7=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w7>>>26),w7&=67108863,lo=_Mathimul(al8,bl0),mid=_Mathimul(al8,bh0),mid=0|mid+_Mathimul(ah8,bl0),hi=_Mathimul(ah8,bh0),lo=0|lo+_Mathimul(al7,bl1),mid=0|mid+_Mathimul(al7,bh1),mid=0|mid+_Mathimul(ah7,bl1),hi=0|hi+_Mathimul(ah7,bh1),lo=0|lo+_Mathimul(al6,bl2),mid=0|mid+_Mathimul(al6,bh2),mid=0|mid+_Mathimul(ah6,bl2),hi=0|hi+_Mathimul(ah6,bh2),lo=0|lo+_Mathimul(al5,bl3),mid=0|mid+_Mathimul(al5,bh3),mid=0|mid+_Mathimul(ah5,bl3),hi=0|hi+_Mathimul(ah5,bh3),lo=0|lo+_Mathimul(al4,bl4),mid=0|mid+_Mathimul(al4,bh4),mid=0|mid+_Mathimul(ah4,bl4),hi=0|hi+_Mathimul(ah4,bh4),lo=0|lo+_Mathimul(al3,bl5),mid=0|mid+_Mathimul(al3,bh5),mid=0|mid+_Mathimul(ah3,bl5),hi=0|hi+_Mathimul(ah3,bh5),lo=0|lo+_Mathimul(al2,bl6),mid=0|mid+_Mathimul(al2,bh6),mid=0|mid+_Mathimul(ah2,bl6),hi=0|hi+_Mathimul(ah2,bh6),lo=0|lo+_Mathimul(al1,bl7),mid=0|mid+_Mathimul(al1,bh7),mid=0|mid+_Mathimul(ah1,bl7),hi=0|hi+_Mathimul(ah1,bh7),lo=0|lo+_Mathimul(al0,bl8),mid=0|mid+_Mathimul(al0,bh8),mid=0|mid+_Mathimul(ah0,bl8),hi=0|hi+_Mathimul(ah0,bh8);var w8=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w8>>>26),w8&=67108863,lo=_Mathimul(al9,bl0),mid=_Mathimul(al9,bh0),mid=0|mid+_Mathimul(ah9,bl0),hi=_Mathimul(ah9,bh0),lo=0|lo+_Mathimul(al8,bl1),mid=0|mid+_Mathimul(al8,bh1),mid=0|mid+_Mathimul(ah8,bl1),hi=0|hi+_Mathimul(ah8,bh1),lo=0|lo+_Mathimul(al7,bl2),mid=0|mid+_Mathimul(al7,bh2),mid=0|mid+_Mathimul(ah7,bl2),hi=0|hi+_Mathimul(ah7,bh2),lo=0|lo+_Mathimul(al6,bl3),mid=0|mid+_Mathimul(al6,bh3),mid=0|mid+_Mathimul(ah6,bl3),hi=0|hi+_Mathimul(ah6,bh3),lo=0|lo+_Mathimul(al5,bl4),mid=0|mid+_Mathimul(al5,bh4),mid=0|mid+_Mathimul(ah5,bl4),hi=0|hi+_Mathimul(ah5,bh4),lo=0|lo+_Mathimul(al4,bl5),mid=0|mid+_Mathimul(al4,bh5),mid=0|mid+_Mathimul(ah4,bl5),hi=0|hi+_Mathimul(ah4,bh5),lo=0|lo+_Mathimul(al3,bl6),mid=0|mid+_Mathimul(al3,bh6),mid=0|mid+_Mathimul(ah3,bl6),hi=0|hi+_Mathimul(ah3,bh6),lo=0|lo+_Mathimul(al2,bl7),mid=0|mid+_Mathimul(al2,bh7),mid=0|mid+_Mathimul(ah2,bl7),hi=0|hi+_Mathimul(ah2,bh7),lo=0|lo+_Mathimul(al1,bl8),mid=0|mid+_Mathimul(al1,bh8),mid=0|mid+_Mathimul(ah1,bl8),hi=0|hi+_Mathimul(ah1,bh8),lo=0|lo+_Mathimul(al0,bl9),mid=0|mid+_Mathimul(al0,bh9),mid=0|mid+_Mathimul(ah0,bl9),hi=0|hi+_Mathimul(ah0,bh9);var w9=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w9>>>26),w9&=67108863,lo=_Mathimul(al9,bl1),mid=_Mathimul(al9,bh1),mid=0|mid+_Mathimul(ah9,bl1),hi=_Mathimul(ah9,bh1),lo=0|lo+_Mathimul(al8,bl2),mid=0|mid+_Mathimul(al8,bh2),mid=0|mid+_Mathimul(ah8,bl2),hi=0|hi+_Mathimul(ah8,bh2),lo=0|lo+_Mathimul(al7,bl3),mid=0|mid+_Mathimul(al7,bh3),mid=0|mid+_Mathimul(ah7,bl3),hi=0|hi+_Mathimul(ah7,bh3),lo=0|lo+_Mathimul(al6,bl4),mid=0|mid+_Mathimul(al6,bh4),mid=0|mid+_Mathimul(ah6,bl4),hi=0|hi+_Mathimul(ah6,bh4),lo=0|lo+_Mathimul(al5,bl5),mid=0|mid+_Mathimul(al5,bh5),mid=0|mid+_Mathimul(ah5,bl5),hi=0|hi+_Mathimul(ah5,bh5),lo=0|lo+_Mathimul(al4,bl6),mid=0|mid+_Mathimul(al4,bh6),mid=0|mid+_Mathimul(ah4,bl6),hi=0|hi+_Mathimul(ah4,bh6),lo=0|lo+_Mathimul(al3,bl7),mid=0|mid+_Mathimul(al3,bh7),mid=0|mid+_Mathimul(ah3,bl7),hi=0|hi+_Mathimul(ah3,bh7),lo=0|lo+_Mathimul(al2,bl8),mid=0|mid+_Mathimul(al2,bh8),mid=0|mid+_Mathimul(ah2,bl8),hi=0|hi+_Mathimul(ah2,bh8),lo=0|lo+_Mathimul(al1,bl9),mid=0|mid+_Mathimul(al1,bh9),mid=0|mid+_Mathimul(ah1,bl9),hi=0|hi+_Mathimul(ah1,bh9);var w10=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w10>>>26),w10&=67108863,lo=_Mathimul(al9,bl2),mid=_Mathimul(al9,bh2),mid=0|mid+_Mathimul(ah9,bl2),hi=_Mathimul(ah9,bh2),lo=0|lo+_Mathimul(al8,bl3),mid=0|mid+_Mathimul(al8,bh3),mid=0|mid+_Mathimul(ah8,bl3),hi=0|hi+_Mathimul(ah8,bh3),lo=0|lo+_Mathimul(al7,bl4),mid=0|mid+_Mathimul(al7,bh4),mid=0|mid+_Mathimul(ah7,bl4),hi=0|hi+_Mathimul(ah7,bh4),lo=0|lo+_Mathimul(al6,bl5),mid=0|mid+_Mathimul(al6,bh5),mid=0|mid+_Mathimul(ah6,bl5),hi=0|hi+_Mathimul(ah6,bh5),lo=0|lo+_Mathimul(al5,bl6),mid=0|mid+_Mathimul(al5,bh6),mid=0|mid+_Mathimul(ah5,bl6),hi=0|hi+_Mathimul(ah5,bh6),lo=0|lo+_Mathimul(al4,bl7),mid=0|mid+_Mathimul(al4,bh7),mid=0|mid+_Mathimul(ah4,bl7),hi=0|hi+_Mathimul(ah4,bh7),lo=0|lo+_Mathimul(al3,bl8),mid=0|mid+_Mathimul(al3,bh8),mid=0|mid+_Mathimul(ah3,bl8),hi=0|hi+_Mathimul(ah3,bh8),lo=0|lo+_Mathimul(al2,bl9),mid=0|mid+_Mathimul(al2,bh9),mid=0|mid+_Mathimul(ah2,bl9),hi=0|hi+_Mathimul(ah2,bh9);var w11=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w11>>>26),w11&=67108863,lo=_Mathimul(al9,bl3),mid=_Mathimul(al9,bh3),mid=0|mid+_Mathimul(ah9,bl3),hi=_Mathimul(ah9,bh3),lo=0|lo+_Mathimul(al8,bl4),mid=0|mid+_Mathimul(al8,bh4),mid=0|mid+_Mathimul(ah8,bl4),hi=0|hi+_Mathimul(ah8,bh4),lo=0|lo+_Mathimul(al7,bl5),mid=0|mid+_Mathimul(al7,bh5),mid=0|mid+_Mathimul(ah7,bl5),hi=0|hi+_Mathimul(ah7,bh5),lo=0|lo+_Mathimul(al6,bl6),mid=0|mid+_Mathimul(al6,bh6),mid=0|mid+_Mathimul(ah6,bl6),hi=0|hi+_Mathimul(ah6,bh6),lo=0|lo+_Mathimul(al5,bl7),mid=0|mid+_Mathimul(al5,bh7),mid=0|mid+_Mathimul(ah5,bl7),hi=0|hi+_Mathimul(ah5,bh7),lo=0|lo+_Mathimul(al4,bl8),mid=0|mid+_Mathimul(al4,bh8),mid=0|mid+_Mathimul(ah4,bl8),hi=0|hi+_Mathimul(ah4,bh8),lo=0|lo+_Mathimul(al3,bl9),mid=0|mid+_Mathimul(al3,bh9),mid=0|mid+_Mathimul(ah3,bl9),hi=0|hi+_Mathimul(ah3,bh9);var w12=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w12>>>26),w12&=67108863,lo=_Mathimul(al9,bl4),mid=_Mathimul(al9,bh4),mid=0|mid+_Mathimul(ah9,bl4),hi=_Mathimul(ah9,bh4),lo=0|lo+_Mathimul(al8,bl5),mid=0|mid+_Mathimul(al8,bh5),mid=0|mid+_Mathimul(ah8,bl5),hi=0|hi+_Mathimul(ah8,bh5),lo=0|lo+_Mathimul(al7,bl6),mid=0|mid+_Mathimul(al7,bh6),mid=0|mid+_Mathimul(ah7,bl6),hi=0|hi+_Mathimul(ah7,bh6),lo=0|lo+_Mathimul(al6,bl7),mid=0|mid+_Mathimul(al6,bh7),mid=0|mid+_Mathimul(ah6,bl7),hi=0|hi+_Mathimul(ah6,bh7),lo=0|lo+_Mathimul(al5,bl8),mid=0|mid+_Mathimul(al5,bh8),mid=0|mid+_Mathimul(ah5,bl8),hi=0|hi+_Mathimul(ah5,bh8),lo=0|lo+_Mathimul(al4,bl9),mid=0|mid+_Mathimul(al4,bh9),mid=0|mid+_Mathimul(ah4,bl9),hi=0|hi+_Mathimul(ah4,bh9);var w13=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w13>>>26),w13&=67108863,lo=_Mathimul(al9,bl5),mid=_Mathimul(al9,bh5),mid=0|mid+_Mathimul(ah9,bl5),hi=_Mathimul(ah9,bh5),lo=0|lo+_Mathimul(al8,bl6),mid=0|mid+_Mathimul(al8,bh6),mid=0|mid+_Mathimul(ah8,bl6),hi=0|hi+_Mathimul(ah8,bh6),lo=0|lo+_Mathimul(al7,bl7),mid=0|mid+_Mathimul(al7,bh7),mid=0|mid+_Mathimul(ah7,bl7),hi=0|hi+_Mathimul(ah7,bh7),lo=0|lo+_Mathimul(al6,bl8),mid=0|mid+_Mathimul(al6,bh8),mid=0|mid+_Mathimul(ah6,bl8),hi=0|hi+_Mathimul(ah6,bh8),lo=0|lo+_Mathimul(al5,bl9),mid=0|mid+_Mathimul(al5,bh9),mid=0|mid+_Mathimul(ah5,bl9),hi=0|hi+_Mathimul(ah5,bh9);var w14=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w14>>>26),w14&=67108863,lo=_Mathimul(al9,bl6),mid=_Mathimul(al9,bh6),mid=0|mid+_Mathimul(ah9,bl6),hi=_Mathimul(ah9,bh6),lo=0|lo+_Mathimul(al8,bl7),mid=0|mid+_Mathimul(al8,bh7),mid=0|mid+_Mathimul(ah8,bl7),hi=0|hi+_Mathimul(ah8,bh7),lo=0|lo+_Mathimul(al7,bl8),mid=0|mid+_Mathimul(al7,bh8),mid=0|mid+_Mathimul(ah7,bl8),hi=0|hi+_Mathimul(ah7,bh8),lo=0|lo+_Mathimul(al6,bl9),mid=0|mid+_Mathimul(al6,bh9),mid=0|mid+_Mathimul(ah6,bl9),hi=0|hi+_Mathimul(ah6,bh9);var w15=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w15>>>26),w15&=67108863,lo=_Mathimul(al9,bl7),mid=_Mathimul(al9,bh7),mid=0|mid+_Mathimul(ah9,bl7),hi=_Mathimul(ah9,bh7),lo=0|lo+_Mathimul(al8,bl8),mid=0|mid+_Mathimul(al8,bh8),mid=0|mid+_Mathimul(ah8,bl8),hi=0|hi+_Mathimul(ah8,bh8),lo=0|lo+_Mathimul(al7,bl9),mid=0|mid+_Mathimul(al7,bh9),mid=0|mid+_Mathimul(ah7,bl9),hi=0|hi+_Mathimul(ah7,bh9);var w16=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w16>>>26),w16&=67108863,lo=_Mathimul(al9,bl8),mid=_Mathimul(al9,bh8),mid=0|mid+_Mathimul(ah9,bl8),hi=_Mathimul(ah9,bh8),lo=0|lo+_Mathimul(al8,bl9),mid=0|mid+_Mathimul(al8,bh9),mid=0|mid+_Mathimul(ah8,bl9),hi=0|hi+_Mathimul(ah8,bh9);var w17=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w17>>>26),w17&=67108863,lo=_Mathimul(al9,bl9),mid=_Mathimul(al9,bh9),mid=0|mid+_Mathimul(ah9,bl9),hi=_Mathimul(ah9,bh9);var w18=0|(0|c+lo)+((8191&mid)<<13);return c=0|(0|hi+(mid>>>13))+(w18>>>26),w18&=67108863,o[0]=w0,o[1]=w1,o[2]=w2,o[3]=w3,o[4]=w4,o[5]=w5,o[6]=w6,o[7]=w7,o[8]=w8,o[9]=w9,o[10]=w10,o[11]=w11,o[12]=w12,o[13]=w13,o[14]=w14,o[15]=w15,o[16]=w16,o[17]=w17,o[18]=w18,0!==c&&(o[19]=c,out.length++),out};_Mathimul||(comb10MulTo=smallMulTo),BN.prototype.mulTo=function(num,out){var len=this.length+num.length,res;return res=10===this.length&&10===num.length?comb10MulTo(this,num,out):63>len?smallMulTo(this,num,out):1024>len?bigMulTo(this,num,out):jumboMulTo(this,num,out),res},FFTM.prototype.makeRBT=function(N){for(var t=Array(N),l=BN.prototype._countBits(N)-1,i=0;i>=1;return rb},FFTM.prototype.permute=function(rbt,rws,iws,rtws,itws,N){for(var i=0;i>>=1)i++;return 1<=N))for(var i=0,t;iw?0:0|w/67108864;return ws},FFTM.prototype.convert13b=function(ws,len,rws,N){for(var carry=0,i=0;i>>=13,rws[2*i+1]=8191&carry,carry>>>=13;for(i=2*len;inum;isNegNum&&(num=-num),assert("number"==typeof num),assert(67108864>num);for(var carry=0,i=0;i>=26,carry+=0|w/67108864,carry+=lo>>>26,this.words[i]=67108863&lo}return 0!==carry&&(this.words[i]=carry,this.length++),isNegNum?this.ineg():this},BN.prototype.muln=function(num){return this.clone().imuln(num)},BN.prototype.sqr=function(){return this.mul(this)},BN.prototype.isqr=function(){return this.imul(this.clone())},BN.prototype.pow=function(num){var w=toBitArray(num);if(0===w.length)return new BN(1);for(var res=this,i=0;i>>26-r<<26-r,c=(0|this.words[i])-newCarry<>>26-r}carry&&(this.words[i]=carry,this.length++)}if(0!==s){for(i=this.length-1;0<=i;i--)this.words[i+s]=this.words[i];for(i=0;is)for(this.length-=s,i=0;i=h);i--){var word=0|this.words[i];this.words[i]=carry<<26-r|word>>>r,carry=word&(67108863^67108863>>>r<>>r<num),0>num?this.isubn(-num):0===this.negative?this._iaddn(num):1===this.length&&(0|this.words[0])<=num?(this.words[0]=num-(0|this.words[0]),this.negative=0,this):(this.negative=0,this.isubn(num),this.negative=1,this)},BN.prototype._iaddn=function(num){this.words[0]+=num;for(var i=0;inum),0>num)return this.iaddn(-num);if(0!==this.negative)return this.negative=0,this.iaddn(num),this.negative=1,this;if(this.words[0]-=num,1===this.length&&0>this.words[0])this.words[0]=-this.words[0],this.negative=1;else for(var i=0;ithis.words[i];i++)this.words[i]+=67108864,this.words[i+1]-=1;return this._strip()},BN.prototype.addn=function(num){return this.clone().iaddn(num)},BN.prototype.subn=function(num){return this.clone().isubn(num)},BN.prototype.iabs=function(){return this.negative=0,this},BN.prototype.abs=function(){return this.clone().iabs()},BN.prototype._ishlnsubmul=function(num,mul,shift){var len=num.length+shift,i;this._expand(len);var carry=0,w;for(i=0;i>26)-(0|right/67108864),this.words[i+shift]=67108863&w}for(;i>26,this.words[i+shift]=67108863&w;if(0===carry)return this._strip();for(assert(-1===carry),carry=0,i=0;i>26,this.words[i]=67108863&w;return this.negative=1,this._strip()},BN.prototype._wordDiv=function(num,mode){var shift=this.length-num.length,a=this.clone(),b=num,bhi=0|b.words[b.length-1],bhiBits=this._countBits(bhi);shift=26-bhiBits,0!=shift&&(b=b.ushln(shift),a.iushln(shift),bhi=0|b.words[b.length-1]);var m=a.length-b.length,q;if("mod"!==mode){q=new BN(null),q.length=m+1,q.words=Array(q.length);for(var i=0;ithis.length||0>this.cmp(num)?{div:new BN(0),mod:this}:1===num.length?"div"===mode?{div:this.divn(num.words[0]),mod:null}:"mod"===mode?{div:null,mod:new BN(this.modrn(num.words[0]))}:{div:this.divn(num.words[0]),mod:new BN(this.modrn(num.words[0]))}:this._wordDiv(num,mode):(res=this.neg().divmod(num.neg(),mode),"div"!==mode&&(mod=res.mod.neg(),positive&&0!==mod.negative&&mod.isub(num)),{div:res.div,mod:mod})},BN.prototype.div=function(num){return this.divmod(num,"div",!1).div},BN.prototype.mod=function(num){return this.divmod(num,"mod",!1).mod},BN.prototype.umod=function(num){return this.divmod(num,"mod",!0).mod},BN.prototype.divRound=function(num){var dm=this.divmod(num);if(dm.mod.isZero())return dm.div;var mod=0===dm.div.negative?dm.mod:dm.mod.isub(num),half=num.ushrn(1),r2=num.andln(1),cmp=mod.cmp(half);return 0>cmp||1===r2&&0===cmp?dm.div:0===dm.div.negative?dm.div.iaddn(1):dm.div.isubn(1)},BN.prototype.modrn=function(num){var isNegNum=0>num;isNegNum&&(num=-num),assert(67108863>=num);for(var p=67108864%num,acc=0,i=this.length-1;0<=i;i--)acc=(p*acc+(0|this.words[i]))%num;return isNegNum?-acc:acc},BN.prototype.modn=function(num){return this.modrn(num)},BN.prototype.idivn=function(num){var isNegNum=0>num;isNegNum&&(num=-num),assert(67108863>=num);for(var carry=0,i=this.length-1,w;0<=i;i--)w=(0|this.words[i])+67108864*carry,this.words[i]=0|w/num,carry=w%num;return this._strip(),isNegNum?this.ineg():this},BN.prototype.divn=function(num){return this.clone().idivn(num)},BN.prototype.egcd=function(p){assert(0===p.negative),assert(!p.isZero());var x=this,y=p.clone();x=0===x.negative?x.clone():x.umod(p);for(var A=new BN(1),B=new BN(0),C=new BN(0),D=new BN(1),g=0;x.isEven()&&y.isEven();)x.iushrn(1),y.iushrn(1),++g;for(var yp=y.clone(),xp=x.clone();!x.isZero();){for(var i=0,im=1;0==(x.words[0]&im)&&26>i;++i,im<<=1);if(0j;++j,jm<<=1);if(0i;++i,im<<=1);if(0j;++j,jm<<=1);if(0res.cmpn(0)&&res.iadd(p),res},BN.prototype.gcd=function(num){if(this.isZero())return num.abs();if(num.isZero())return this.abs();var a=this.clone(),b=num.clone();a.negative=0,b.negative=0;for(var shift=0;a.isEven()&&b.isEven();shift++)a.iushrn(1),b.iushrn(1);do{for(;a.isEven();)a.iushrn(1);for(;b.isEven();)b.iushrn(1);var r=a.cmp(b);if(0>r){var t=a;a=b,b=t}else if(0===r||0===b.cmpn(1))break;a.isub(b)}while(!0);return b.iushln(shift)},BN.prototype.invm=function(num){return this.egcd(num).a.umod(num)},BN.prototype.isEven=function(){return 0==(1&this.words[0])},BN.prototype.isOdd=function(){return 1==(1&this.words[0])},BN.prototype.andln=function(num){return this.words[0]&num},BN.prototype.bincn=function(bit){assert("number"==typeof bit);var r=bit%26,s=(bit-r)/26,q=1<>>26,w&=67108863,this.words[i]=w;return 0!==carry&&(this.words[i]=carry,this.length++),this},BN.prototype.isZero=function(){return 1===this.length&&0===this.words[0]},BN.prototype.cmpn=function(num){var negative=0>num;if(0!==this.negative&&!negative)return-1;if(0===this.negative&&negative)return 1;this._strip();var res;if(1=num,"Number is too big");var w=0|this.words[0];res=w===num?0:wnum.length)return 1;if(this.lengthb&&(res=1);break}}return res},BN.prototype.gtn=function(num){return 1===this.cmpn(num)},BN.prototype.gt=function(num){return 1===this.cmp(num)},BN.prototype.gten=function(num){return 0<=this.cmpn(num)},BN.prototype.gte=function(num){return 0<=this.cmp(num)},BN.prototype.ltn=function(num){return-1===this.cmpn(num)},BN.prototype.lt=function(num){return-1===this.cmp(num)},BN.prototype.lten=function(num){return 0>=this.cmpn(num)},BN.prototype.lte=function(num){return 0>=this.cmp(num)},BN.prototype.eqn=function(num){return 0===this.cmpn(num)},BN.prototype.eq=function(num){return 0===this.cmp(num)},BN.red=function(num){return new Red(num)},BN.prototype.toRed=function(ctx){return assert(!this.red,"Already a number in reduction context"),assert(0===this.negative,"red works only with positives"),ctx.convertTo(this)._forceRed(ctx)},BN.prototype.fromRed=function(){return assert(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},BN.prototype._forceRed=function(ctx){return this.red=ctx,this},BN.prototype.forceRed=function(ctx){return assert(!this.red,"Already a number in reduction context"),this._forceRed(ctx)},BN.prototype.redAdd=function(num){return assert(this.red,"redAdd works only with red numbers"),this.red.add(this,num)},BN.prototype.redIAdd=function(num){return assert(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,num)},BN.prototype.redSub=function(num){return assert(this.red,"redSub works only with red numbers"),this.red.sub(this,num)},BN.prototype.redISub=function(num){return assert(this.red,"redISub works only with red numbers"),this.red.isub(this,num)},BN.prototype.redShl=function(num){return assert(this.red,"redShl works only with red numbers"),this.red.shl(this,num)},BN.prototype.redMul=function(num){return assert(this.red,"redMul works only with red numbers"),this.red._verify2(this,num),this.red.mul(this,num)},BN.prototype.redIMul=function(num){return assert(this.red,"redMul works only with red numbers"),this.red._verify2(this,num),this.red.imul(this,num)},BN.prototype.redSqr=function(){return assert(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},BN.prototype.redISqr=function(){return assert(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},BN.prototype.redSqrt=function(){return assert(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},BN.prototype.redInvm=function(){return assert(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},BN.prototype.redNeg=function(){return assert(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},BN.prototype.redPow=function(num){return assert(this.red&&!num.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,num)};var primes={k256:null,p224:null,p192:null,p25519:null};MPrime.prototype._tmp=function(){var tmp=new BN(null);return tmp.words=Array(_Mathceil(this.n/13)),tmp},MPrime.prototype.ireduce=function(num){var r=num,rlen;do this.split(r,this.tmp),r=this.imulK(r),r=r.iadd(this.tmp),rlen=r.bitLength();while(rlen>this.n);var cmp=rlen=input.length)return input.words[0]=0,void(input.length=1);var prev=input.words[9];for(output.words[output.length++]=prev&mask,i=10;i>>22,prev=next}prev>>>=22,input.words[i-10]=prev,input.length-=0===prev&&10>>=26,num.words[i]=lo,carry=hi}return 0!==carry&&(num.words[num.length++]=carry),num},BN._prime=function prime(name){if(primes[name])return primes[name];var prime;if("k256"===name)prime=new K256;else if("p224"===name)prime=new P224;else if("p192"===name)prime=new P192;else if("p25519"===name)prime=new P25519;else throw new Error("Unknown prime "+name);return primes[name]=prime,prime},Red.prototype._verify1=function(a){assert(0===a.negative,"red works only with positives"),assert(a.red,"red works only with red numbers")},Red.prototype._verify2=function(a,b){assert(0==(a.negative|b.negative),"red works only with positives"),assert(a.red&&a.red===b.red,"red works only with red numbers")},Red.prototype.imod=function(a){return this.prime?this.prime.ireduce(a)._forceRed(this):(move(a,a.umod(this.m)._forceRed(this)),a)},Red.prototype.neg=function(a){return a.isZero()?a.clone():this.m.sub(a)._forceRed(this)},Red.prototype.add=function(a,b){this._verify2(a,b);var res=a.add(b);return 0<=res.cmp(this.m)&&res.isub(this.m),res._forceRed(this)},Red.prototype.iadd=function(a,b){this._verify2(a,b);var res=a.iadd(b);return 0<=res.cmp(this.m)&&res.isub(this.m),res},Red.prototype.sub=function(a,b){this._verify2(a,b);var res=a.sub(b);return 0>res.cmpn(0)&&res.iadd(this.m),res._forceRed(this)},Red.prototype.isub=function(a,b){this._verify2(a,b);var res=a.isub(b);return 0>res.cmpn(0)&&res.iadd(this.m),res},Red.prototype.shl=function(a,num){return this._verify1(a),this.imod(a.ushln(num))},Red.prototype.imul=function(a,b){return this._verify2(a,b),this.imod(a.imul(b))},Red.prototype.mul=function(a,b){return this._verify2(a,b),this.imod(a.mul(b))},Red.prototype.isqr=function(a){return this.imul(a,a.clone())},Red.prototype.sqr=function(a){return this.mul(a,a)},Red.prototype.sqrt=function(a){if(a.isZero())return a.clone();var mod3=this.m.andln(3);if(assert(1==mod3%2),3===mod3){var pow=this.m.add(new BN(1)).iushrn(2);return this.pow(a,pow)}for(var q=this.m.subn(1),s=0;!q.isZero()&&0===q.andln(1);)s++,q.iushrn(1);assert(!q.isZero());var one=new BN(1).toRed(this),nOne=one.redNeg(),lpow=this.m.subn(1).iushrn(1),z=this.m.bitLength();for(z=new BN(2*z*z).toRed(this);0!==this.pow(z,lpow).cmp(nOne);)z.redIAdd(nOne);for(var c=this.pow(z,q),r=this.pow(a,q.addn(1).iushrn(1)),t=this.pow(a,q),m=s;0!==t.cmp(one);){for(var tmp=t,i=0;0!==tmp.cmp(one);i++)tmp=tmp.redSqr();assert(i>j,res!==wnd[0]&&(res=this.sqr(res)),0===bit&&0===current){currentLen=0;continue}current<<=1,current|=bit,currentLen++,(4===currentLen||0===i&&0===j)&&(res=this.mul(res,wnd[current]),currentLen=0,current=0)}start=26}return res},Red.prototype.convertTo=function(num){var r=num.umod(this.m);return r===num?r.clone():r},Red.prototype.convertFrom=function(num){var res=num.clone();return res.red=null,res},BN.mont=function(num){return new Mont(num)},inherits(Mont,Red),Mont.prototype.convertTo=function(num){return this.imod(num.ushln(this.shift))},Mont.prototype.convertFrom=function(num){var r=this.imod(num.mul(this.rinv));return r.red=null,r},Mont.prototype.imul=function(a,b){if(a.isZero()||b.isZero())return a.words[0]=0,a.length=1,a;var t=a.imul(b),c=t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),u=t.isub(c).iushrn(this.shift),res=u;return 0<=u.cmp(this.m)?res=u.isub(this.m):0>u.cmpn(0)&&(res=u.iadd(this.m)),res._forceRed(this)},Mont.prototype.mul=function(a,b){if(a.isZero()||b.isZero())return new BN(0)._forceRed(this);var t=a.mul(b),c=t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),u=t.isub(c).iushrn(this.shift),res=u;return 0<=u.cmp(this.m)?res=u.isub(this.m):0>u.cmpn(0)&&(res=u.iadd(this.m)),res._forceRed(this)},Mont.prototype.invm=function(a){var res=this.imod(a._invmp(this.m).mul(this.r2));return res._forceRed(this)}})("undefined"==typeof module||module,this)},{buffer:36}],36:[function(){},{}],37:[function(require,module,exports){arguments[4][36][0].apply(exports,arguments)},{dup:36}],38:[function(require,module,exports){(function(){(function(){/*! * The buffer module from node.js, for the browser. * * @author Feross Aboukhadijeh * @license MIT - */'use strict';function createBuffer(length){if(2147483647size)throw new RangeError("The value \""+size+"\" is invalid for option \"size\"")}function alloc(size,fill,encoding){return assertSize(size),0>=size?createBuffer(size):void 0===fill?createBuffer(size):"string"==typeof encoding?createBuffer(size).fill(fill,encoding):createBuffer(size).fill(fill)}function allocUnsafe(size){return assertSize(size),createBuffer(0>size?0:0|checked(size))}function fromString(string,encoding){if(("string"!=typeof encoding||""===encoding)&&(encoding="utf8"),!Buffer.isEncoding(encoding))throw new TypeError("Unknown encoding: "+encoding);var length=0|byteLength(string,encoding),buf=createBuffer(length),actual=buf.write(string,encoding);return actual!==length&&(buf=buf.slice(0,actual)),buf}function fromArrayLike(array){for(var length=0>array.length?0:0|checked(array.length),buf=createBuffer(length),i=0;ibyteOffset||array.byteLength=2147483647)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+2147483647 .toString(16)+" bytes");return 0|length}function byteLength(string,encoding){if(Buffer.isBuffer(string))return string.length;if(ArrayBuffer.isView(string)||isInstance(string,ArrayBuffer))return string.byteLength;if("string"!=typeof string)throw new TypeError("The \"string\" argument must be one of type string, Buffer, or ArrayBuffer. Received type "+typeof string);var len=string.length,mustMatch=2>>1;case"base64":return base64ToBytes(string).length;default:if(loweredCase)return mustMatch?-1:utf8ToBytes(string).length;encoding=(""+encoding).toLowerCase(),loweredCase=!0;}}function slowToString(encoding,start,end){var loweredCase=!1;if((void 0===start||0>start)&&(start=0),start>this.length)return"";if((void 0===end||end>this.length)&&(end=this.length),0>=end)return"";if(end>>>=0,start>>>=0,end<=start)return"";for(encoding||(encoding="utf8");;)switch(encoding){case"hex":return hexSlice(this,start,end);case"utf8":case"utf-8":return utf8Slice(this,start,end);case"ascii":return asciiSlice(this,start,end);case"latin1":case"binary":return latin1Slice(this,start,end);case"base64":return base64Slice(this,start,end);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return utf16leSlice(this,start,end);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(encoding+"").toLowerCase(),loweredCase=!0;}}function swap(b,n,m){var i=b[n];b[n]=b[m],b[m]=i}function bidirectionalIndexOf(buffer,val,byteOffset,encoding,dir){if(0===buffer.length)return-1;if("string"==typeof byteOffset?(encoding=byteOffset,byteOffset=0):2147483647byteOffset&&(byteOffset=-2147483648),byteOffset=+byteOffset,numberIsNaN(byteOffset)&&(byteOffset=dir?0:buffer.length-1),0>byteOffset&&(byteOffset=buffer.length+byteOffset),byteOffset>=buffer.length){if(dir)return-1;byteOffset=buffer.length-1}else if(0>byteOffset)if(dir)byteOffset=0;else return-1;if("string"==typeof val&&(val=Buffer.from(val,encoding)),Buffer.isBuffer(val))return 0===val.length?-1:arrayIndexOf(buffer,val,byteOffset,encoding,dir);if("number"==typeof val)return val&=255,"function"==typeof Uint8Array.prototype.indexOf?dir?Uint8Array.prototype.indexOf.call(buffer,val,byteOffset):Uint8Array.prototype.lastIndexOf.call(buffer,val,byteOffset):arrayIndexOf(buffer,[val],byteOffset,encoding,dir);throw new TypeError("val must be string, number or Buffer")}function arrayIndexOf(arr,val,byteOffset,encoding,dir){function read(buf,i){return 1===indexSize?buf[i]:buf.readUInt16BE(i*indexSize)}var indexSize=1,arrLength=arr.length,valLength=val.length;if(void 0!==encoding&&(encoding=(encoding+"").toLowerCase(),"ucs2"===encoding||"ucs-2"===encoding||"utf16le"===encoding||"utf-16le"===encoding)){if(2>arr.length||2>val.length)return-1;indexSize=2,arrLength/=2,valLength/=2,byteOffset/=2}var i;if(dir){var foundIndex=-1;for(i=byteOffset;iarrLength&&(byteOffset=arrLength-valLength),i=byteOffset;0<=i;i--){for(var found=!0,j=0;jremaining&&(length=remaining)):length=remaining;var strLen=string.length;length>strLen/2&&(length=strLen/2);for(var i=0,parsed;ifirstByte&&(codePoint=firstByte):2===bytesPerSequence?(secondByte=buf[i+1],128==(192&secondByte)&&(tempCodePoint=(31&firstByte)<<6|63&secondByte,127tempCodePoint||57343tempCodePoint&&(codePoint=tempCodePoint))):void 0}null===codePoint?(codePoint=65533,bytesPerSequence=1):65535>>10),codePoint=56320|1023&codePoint),res.push(codePoint),i+=bytesPerSequence}return decodeCodePointsArray(res)}function decodeCodePointsArray(codePoints){var len=codePoints.length;if(len<=4096)return _StringfromCharCode.apply(String,codePoints);for(var res="",i=0;istart)&&(start=0),(!end||0>end||end>len)&&(end=len);for(var out="",i=start;ioffset)throw new RangeError("offset is not uint");if(offset+ext>length)throw new RangeError("Trying to access beyond buffer length")}function checkInt(buf,value,offset,ext,max,min){if(!Buffer.isBuffer(buf))throw new TypeError("\"buffer\" argument must be a Buffer instance");if(value>max||valuebuf.length)throw new RangeError("Index out of range")}function checkIEEE754(buf,value,offset,ext){if(offset+ext>buf.length)throw new RangeError("Index out of range");if(0>offset)throw new RangeError("Index out of range")}function writeFloat(buf,value,offset,littleEndian,noAssert){return value=+value,offset>>>=0,noAssert||checkIEEE754(buf,value,offset,4,34028234663852886e22,-34028234663852886e22),ieee754.write(buf,value,offset,littleEndian,23,4),offset+4}function writeDouble(buf,value,offset,littleEndian,noAssert){return value=+value,offset>>>=0,noAssert||checkIEEE754(buf,value,offset,8,17976931348623157e292,-17976931348623157e292),ieee754.write(buf,value,offset,littleEndian,52,8),offset+8}function base64clean(str){if(str=str.split("=")[0],str=str.trim().replace(INVALID_BASE64_RE,""),2>str.length)return"";for(;0!=str.length%4;)str+="=";return str}function toHex(n){return 16>n?"0"+n.toString(16):n.toString(16)}function utf8ToBytes(string,units){units=units||1/0;for(var length=string.length,leadSurrogate=null,bytes=[],i=0,codePoint;icodePoint){if(!leadSurrogate){if(56319codePoint){-1<(units-=3)&&bytes.push(239,191,189),leadSurrogate=codePoint;continue}codePoint=(leadSurrogate-55296<<10|codePoint-56320)+65536}else leadSurrogate&&-1<(units-=3)&&bytes.push(239,191,189);if(leadSurrogate=null,128>codePoint){if(0>(units-=1))break;bytes.push(codePoint)}else if(2048>codePoint){if(0>(units-=2))break;bytes.push(192|codePoint>>6,128|63&codePoint)}else if(65536>codePoint){if(0>(units-=3))break;bytes.push(224|codePoint>>12,128|63&codePoint>>6,128|63&codePoint)}else if(1114112>codePoint){if(0>(units-=4))break;bytes.push(240|codePoint>>18,128|63&codePoint>>12,128|63&codePoint>>6,128|63&codePoint)}else throw new Error("Invalid code point")}return bytes}function asciiToBytes(str){for(var byteArray=[],i=0;i(units-=2));++i)c=str.charCodeAt(i),hi=c>>8,lo=c%256,byteArray.push(lo),byteArray.push(hi);return byteArray}function base64ToBytes(str){return base64.toByteArray(base64clean(str))}function blitBuffer(src,dst,offset,length){for(var i=0;i=dst.length||i>=src.length);++i)dst[i+offset]=src[i];return i}function isInstance(obj,type){return obj instanceof type||null!=obj&&null!=obj.constructor&&null!=obj.constructor.name&&obj.constructor.name===type.name}function numberIsNaN(obj){return obj!==obj}var base64=require("base64-js"),ieee754=require("ieee754");exports.Buffer=Buffer,exports.SlowBuffer=function(length){return+length!=length&&(length=0),Buffer.alloc(+length)},exports.INSPECT_MAX_BYTES=50;exports.kMaxLength=2147483647,Buffer.TYPED_ARRAY_SUPPORT=function(){try{var arr=new Uint8Array(1);return arr.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===arr.foo()}catch(e){return!1}}(),Buffer.TYPED_ARRAY_SUPPORT||"undefined"==typeof console||"function"!=typeof console.error||console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."),Object.defineProperty(Buffer.prototype,"parent",{enumerable:!0,get:function(){return Buffer.isBuffer(this)?this.buffer:void 0}}),Object.defineProperty(Buffer.prototype,"offset",{enumerable:!0,get:function(){return Buffer.isBuffer(this)?this.byteOffset:void 0}}),"undefined"!=typeof Symbol&&null!=Symbol.species&&Buffer[Symbol.species]===Buffer&&Object.defineProperty(Buffer,Symbol.species,{value:null,configurable:!0,enumerable:!1,writable:!1}),Buffer.poolSize=8192,Buffer.from=function(value,encodingOrOffset,length){return from(value,encodingOrOffset,length)},Buffer.prototype.__proto__=Uint8Array.prototype,Buffer.__proto__=Uint8Array,Buffer.alloc=function(size,fill,encoding){return alloc(size,fill,encoding)},Buffer.allocUnsafe=function(size){return allocUnsafe(size)},Buffer.allocUnsafeSlow=function(size){return allocUnsafe(size)},Buffer.isBuffer=function(b){return null!=b&&!0===b._isBuffer&&b!==Buffer.prototype},Buffer.compare=function(a,b){if(isInstance(a,Uint8Array)&&(a=Buffer.from(a,a.offset,a.byteLength)),isInstance(b,Uint8Array)&&(b=Buffer.from(b,b.offset,b.byteLength)),!Buffer.isBuffer(a)||!Buffer.isBuffer(b))throw new TypeError("The \"buf1\", \"buf2\" arguments must be one of type Buffer or Uint8Array");if(a===b)return 0;for(var x=a.length,y=b.length,i=0,len=_Mathmin(x,y);imax&&(str+=" ... "),""},Buffer.prototype.compare=function(target,start,end,thisStart,thisEnd){if(isInstance(target,Uint8Array)&&(target=Buffer.from(target,target.offset,target.byteLength)),!Buffer.isBuffer(target))throw new TypeError("The \"target\" argument must be one of type Buffer or Uint8Array. Received type "+typeof target);if(void 0===start&&(start=0),void 0===end&&(end=target?target.length:0),void 0===thisStart&&(thisStart=0),void 0===thisEnd&&(thisEnd=this.length),0>start||end>target.length||0>thisStart||thisEnd>this.length)throw new RangeError("out of range index");if(thisStart>=thisEnd&&start>=end)return 0;if(thisStart>=thisEnd)return-1;if(start>=end)return 1;if(start>>>=0,end>>>=0,thisStart>>>=0,thisEnd>>>=0,this===target)return 0;for(var x=thisEnd-thisStart,y=end-start,len=_Mathmin(x,y),thisCopy=this.slice(thisStart,thisEnd),targetCopy=target.slice(start,end),i=0;i>>=0,isFinite(length)?(length>>>=0,void 0===encoding&&(encoding="utf8")):(encoding=length,length=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");var remaining=this.length-offset;if((void 0===length||length>remaining)&&(length=remaining),0length||0>offset)||offset>this.length)throw new RangeError("Attempt to write outside buffer bounds");encoding||(encoding="utf8");for(var loweredCase=!1;;)switch(encoding){case"hex":return hexWrite(this,string,offset,length);case"utf8":case"utf-8":return utf8Write(this,string,offset,length);case"ascii":return asciiWrite(this,string,offset,length);case"latin1":case"binary":return latin1Write(this,string,offset,length);case"base64":return base64Write(this,string,offset,length);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ucs2Write(this,string,offset,length);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(""+encoding).toLowerCase(),loweredCase=!0;}},Buffer.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};Buffer.prototype.slice=function(start,end){var len=this.length;start=~~start,end=void 0===end?len:~~end,0>start?(start+=len,0>start&&(start=0)):start>len&&(start=len),0>end?(end+=len,0>end&&(end=0)):end>len&&(end=len),end>>=0,byteLength>>>=0,noAssert||checkOffset(offset,byteLength,this.length);for(var val=this[offset],mul=1,i=0;++i>>=0,byteLength>>>=0,noAssert||checkOffset(offset,byteLength,this.length);for(var val=this[offset+--byteLength],mul=1;0>>=0,noAssert||checkOffset(offset,1,this.length),this[offset]},Buffer.prototype.readUInt16LE=function(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,2,this.length),this[offset]|this[offset+1]<<8},Buffer.prototype.readUInt16BE=function(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,2,this.length),this[offset]<<8|this[offset+1]},Buffer.prototype.readUInt32LE=function(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,4,this.length),(this[offset]|this[offset+1]<<8|this[offset+2]<<16)+16777216*this[offset+3]},Buffer.prototype.readUInt32BE=function(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,4,this.length),16777216*this[offset]+(this[offset+1]<<16|this[offset+2]<<8|this[offset+3])},Buffer.prototype.readIntLE=function(offset,byteLength,noAssert){offset>>>=0,byteLength>>>=0,noAssert||checkOffset(offset,byteLength,this.length);for(var val=this[offset],mul=1,i=0;++i=mul&&(val-=_Mathpow(2,8*byteLength)),val},Buffer.prototype.readIntBE=function(offset,byteLength,noAssert){offset>>>=0,byteLength>>>=0,noAssert||checkOffset(offset,byteLength,this.length);for(var i=byteLength,mul=1,val=this[offset+--i];0=mul&&(val-=_Mathpow(2,8*byteLength)),val},Buffer.prototype.readInt8=function(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,1,this.length),128&this[offset]?-1*(255-this[offset]+1):this[offset]},Buffer.prototype.readInt16LE=function(offset,noAssert){offset>>>=0,noAssert||checkOffset(offset,2,this.length);var val=this[offset]|this[offset+1]<<8;return 32768&val?4294901760|val:val},Buffer.prototype.readInt16BE=function(offset,noAssert){offset>>>=0,noAssert||checkOffset(offset,2,this.length);var val=this[offset+1]|this[offset]<<8;return 32768&val?4294901760|val:val},Buffer.prototype.readInt32LE=function(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,4,this.length),this[offset]|this[offset+1]<<8|this[offset+2]<<16|this[offset+3]<<24},Buffer.prototype.readInt32BE=function(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,4,this.length),this[offset]<<24|this[offset+1]<<16|this[offset+2]<<8|this[offset+3]},Buffer.prototype.readFloatLE=function(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,4,this.length),ieee754.read(this,offset,!0,23,4)},Buffer.prototype.readFloatBE=function(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,4,this.length),ieee754.read(this,offset,!1,23,4)},Buffer.prototype.readDoubleLE=function(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,8,this.length),ieee754.read(this,offset,!0,52,8)},Buffer.prototype.readDoubleBE=function(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,8,this.length),ieee754.read(this,offset,!1,52,8)},Buffer.prototype.writeUIntLE=function(value,offset,byteLength,noAssert){if(value=+value,offset>>>=0,byteLength>>>=0,!noAssert){var maxBytes=_Mathpow(2,8*byteLength)-1;checkInt(this,value,offset,byteLength,maxBytes,0)}var mul=1,i=0;for(this[offset]=255&value;++i>>=0,byteLength>>>=0,!noAssert){var maxBytes=_Mathpow(2,8*byteLength)-1;checkInt(this,value,offset,byteLength,maxBytes,0)}var i=byteLength-1,mul=1;for(this[offset+i]=255&value;0<=--i&&(mul*=256);)this[offset+i]=255&value/mul;return offset+byteLength},Buffer.prototype.writeUInt8=function(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,1,255,0),this[offset]=255&value,offset+1},Buffer.prototype.writeUInt16LE=function(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,2,65535,0),this[offset]=255&value,this[offset+1]=value>>>8,offset+2},Buffer.prototype.writeUInt16BE=function(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,2,65535,0),this[offset]=value>>>8,this[offset+1]=255&value,offset+2},Buffer.prototype.writeUInt32LE=function(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,4,4294967295,0),this[offset+3]=value>>>24,this[offset+2]=value>>>16,this[offset+1]=value>>>8,this[offset]=255&value,offset+4},Buffer.prototype.writeUInt32BE=function(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,4,4294967295,0),this[offset]=value>>>24,this[offset+1]=value>>>16,this[offset+2]=value>>>8,this[offset+3]=255&value,offset+4},Buffer.prototype.writeIntLE=function(value,offset,byteLength,noAssert){if(value=+value,offset>>>=0,!noAssert){var limit=_Mathpow(2,8*byteLength-1);checkInt(this,value,offset,byteLength,limit-1,-limit)}var i=0,mul=1,sub=0;for(this[offset]=255&value;++ivalue&&0===sub&&0!==this[offset+i-1]&&(sub=1),this[offset+i]=255&(value/mul>>0)-sub;return offset+byteLength},Buffer.prototype.writeIntBE=function(value,offset,byteLength,noAssert){if(value=+value,offset>>>=0,!noAssert){var limit=_Mathpow(2,8*byteLength-1);checkInt(this,value,offset,byteLength,limit-1,-limit)}var i=byteLength-1,mul=1,sub=0;for(this[offset+i]=255&value;0<=--i&&(mul*=256);)0>value&&0===sub&&0!==this[offset+i+1]&&(sub=1),this[offset+i]=255&(value/mul>>0)-sub;return offset+byteLength},Buffer.prototype.writeInt8=function(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,1,127,-128),0>value&&(value=255+value+1),this[offset]=255&value,offset+1},Buffer.prototype.writeInt16LE=function(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,2,32767,-32768),this[offset]=255&value,this[offset+1]=value>>>8,offset+2},Buffer.prototype.writeInt16BE=function(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,2,32767,-32768),this[offset]=value>>>8,this[offset+1]=255&value,offset+2},Buffer.prototype.writeInt32LE=function(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,4,2147483647,-2147483648),this[offset]=255&value,this[offset+1]=value>>>8,this[offset+2]=value>>>16,this[offset+3]=value>>>24,offset+4},Buffer.prototype.writeInt32BE=function(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,4,2147483647,-2147483648),0>value&&(value=4294967295+value+1),this[offset]=value>>>24,this[offset+1]=value>>>16,this[offset+2]=value>>>8,this[offset+3]=255&value,offset+4},Buffer.prototype.writeFloatLE=function(value,offset,noAssert){return writeFloat(this,value,offset,!0,noAssert)},Buffer.prototype.writeFloatBE=function(value,offset,noAssert){return writeFloat(this,value,offset,!1,noAssert)},Buffer.prototype.writeDoubleLE=function(value,offset,noAssert){return writeDouble(this,value,offset,!0,noAssert)},Buffer.prototype.writeDoubleBE=function(value,offset,noAssert){return writeDouble(this,value,offset,!1,noAssert)},Buffer.prototype.copy=function(target,targetStart,start,end){if(!Buffer.isBuffer(target))throw new TypeError("argument should be a Buffer");if(start||(start=0),end||0===end||(end=this.length),targetStart>=target.length&&(targetStart=target.length),targetStart||(targetStart=0),0targetStart)throw new RangeError("targetStart out of bounds");if(0>start||start>=this.length)throw new RangeError("Index out of range");if(0>end)throw new RangeError("sourceEnd out of bounds");end>this.length&&(end=this.length),target.length-targetStartcode||"latin1"===encoding)&&(val=code)}}else"number"==typeof val&&(val&=255);if(0>start||this.length>>=0,end=end===void 0?this.length:end>>>0,val||(val=0);var i;if("number"==typeof val)for(i=start;im&&!existing.warned){existing.warned=!0;var w=new Error("Possible EventEmitter memory leak detected. "+existing.length+" "+(type+" listeners added. Use emitter.setMaxListeners() to increase limit"));w.name="MaxListenersExceededWarning",w.emitter=target,w.type=type,w.count=existing.length,ProcessEmitWarning(w)}return target}function onceWrapper(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function _onceWrap(target,type,listener){var state={fired:!1,wrapFn:void 0,target:target,type:type,listener:listener},wrapped=onceWrapper.bind(state);return wrapped.listener=listener,state.wrapFn=wrapped,wrapped}function _listeners(target,type,unwrap){var events=target._events;if(events===void 0)return[];var evlistener=events[type];return void 0===evlistener?[]:"function"==typeof evlistener?unwrap?[evlistener.listener||evlistener]:[evlistener]:unwrap?unwrapListeners(evlistener):arrayClone(evlistener,evlistener.length)}function listenerCount(type){var events=this._events;if(events!==void 0){var evlistener=events[type];if("function"==typeof evlistener)return 1;if(void 0!==evlistener)return evlistener.length}return 0}function arrayClone(arr,n){for(var copy=Array(n),i=0;iarg||NumberIsNaN(arg))throw new RangeError("The value of \"defaultMaxListeners\" is out of range. It must be a non-negative number. Received "+arg+".");defaultMaxListeners=arg}}),EventEmitter.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},EventEmitter.prototype.setMaxListeners=function(n){if("number"!=typeof n||0>n||NumberIsNaN(n))throw new RangeError("The value of \"n\" is out of range. It must be a non-negative number. Received "+n+".");return this._maxListeners=n,this},EventEmitter.prototype.getMaxListeners=function(){return _getMaxListeners(this)},EventEmitter.prototype.emit=function(type){for(var args=[],i=1;iposition)return this;0===position?list.shift():spliceOne(list,position),1===list.length&&(events[type]=list[0]),void 0!==events.removeListener&&this.emit("removeListener",type,originalListener||listener)}return this},EventEmitter.prototype.off=EventEmitter.prototype.removeListener,EventEmitter.prototype.removeAllListeners=function(type){var listeners,events,i;if(events=this._events,void 0===events)return this;if(void 0===events.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==events[type]&&(0==--this._eventsCount?this._events=Object.create(null):delete events[type]),this;if(0===arguments.length){var keys=Object.keys(events),key;for(i=0;ires.length||2!==lastSegmentLength||46!==res.charCodeAt(res.length-1)||46!==res.charCodeAt(res.length-2))if(2length){if(47===to.charCodeAt(toStart+i))return to.slice(toStart+i+1);if(0===i)return to.slice(toStart+i)}else fromLen>length&&(47===from.charCodeAt(fromStart+i)?lastCommonSep=i:0===i&&(lastCommonSep=0));break}var fromCode=from.charCodeAt(fromStart+i),toCode=to.charCodeAt(toStart+i);if(fromCode!==toCode)break;else 47===fromCode&&(lastCommonSep=i)}var out="";for(i=fromStart+lastCommonSep+1;i<=fromEnd;++i)(i===fromEnd||47===from.charCodeAt(i))&&(out+=0===out.length?"..":"/..");return 0=start;--i){if(code=path.charCodeAt(i),47===code){if(!matchedSlash){startPart=i+1;break}continue}-1===end&&(matchedSlash=!1,end=i+1),46===code?-1===startDot?startDot=i:1!==preDotState&&(preDotState=1):-1!==startDot&&(preDotState=-1)}return-1===startDot||-1===end||0===preDotState||1===preDotState&&startDot===end-1&&startDot===startPart+1?-1!==end&&(0===startPart&&isAbsolute?ret.base=ret.name=path.slice(1,end):ret.base=ret.name=path.slice(startPart,end)):(0===startPart&&isAbsolute?(ret.name=path.slice(1,startDot),ret.base=path.slice(1,end)):(ret.name=path.slice(startPart,startDot),ret.base=path.slice(startPart,end)),ret.ext=path.slice(startDot,end)),0pos?0:+pos,search.length)===search}function endsWith(str,search,this_len){return(void 0===this_len||this_len>str.length)&&(this_len=str.length),str.substring(this_len-search.length,this_len)===search}function includes(str,search,start){return"number"!=typeof start&&(start=0),!(start+search.length>str.length)&&-1!==str.indexOf(search,start)}var codes={};createErrorType("ERR_INVALID_OPT_VALUE",function(name,value){return"The value \""+value+"\" is invalid for option \""+name+"\""},TypeError),createErrorType("ERR_INVALID_ARG_TYPE",function(name,expected,actual){var determiner;"string"==typeof expected&&startsWith(expected,"not ")?(determiner="must not be",expected=expected.replace(/^not /,"")):determiner="must be";var msg;if(endsWith(name," argument"))msg="The ".concat(name," ").concat(determiner," ").concat(oneOf(expected,"type"));else{var type=includes(name,".")?"property":"argument";msg="The \"".concat(name,"\" ").concat(type," ").concat(determiner," ").concat(oneOf(expected,"type"))}return msg+=". Received type ".concat(typeof actual),msg},TypeError),createErrorType("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF"),createErrorType("ERR_METHOD_NOT_IMPLEMENTED",function(name){return"The "+name+" method is not implemented"}),createErrorType("ERR_STREAM_PREMATURE_CLOSE","Premature close"),createErrorType("ERR_STREAM_DESTROYED",function(name){return"Cannot call "+name+" after a stream was destroyed"}),createErrorType("ERR_MULTIPLE_CALLBACK","Callback called multiple times"),createErrorType("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable"),createErrorType("ERR_STREAM_WRITE_AFTER_END","write after end"),createErrorType("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),createErrorType("ERR_UNKNOWN_ENCODING",function(arg){return"Unknown encoding: "+arg},TypeError),createErrorType("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event"),module.exports.codes=codes},{}],43:[function(require,module){(function(process){(function(){'use strict';function Duplex(options){return this instanceof Duplex?void(Readable.call(this,options),Writable.call(this,options),this.allowHalfOpen=!0,options&&(!1===options.readable&&(this.readable=!1),!1===options.writable&&(this.writable=!1),!1===options.allowHalfOpen&&(this.allowHalfOpen=!1,this.once("end",onend)))):new Duplex(options)}function onend(){this._writableState.ended||process.nextTick(onEndNT,this)}function onEndNT(self){self.end()}var objectKeys=Object.keys||function(obj){var keys=[];for(var key in obj)keys.push(key);return keys};module.exports=Duplex;var Readable=require("./_stream_readable"),Writable=require("./_stream_writable");require("inherits")(Duplex,Readable);for(var keys=objectKeys(Writable.prototype),v=0,method;v>>1,n|=n>>>2,n|=n>>>4,n|=n>>>8,n|=n>>>16,n++),n}function howMuchToRead(n,state){return 0>=n||0===state.length&&state.ended?0:state.objectMode?1:n===n?(n>state.highWaterMark&&(state.highWaterMark=computeNewHighWaterMark(n)),n<=state.length?n:state.ended?state.length:(state.needReadable=!0,0)):state.flowing&&state.length?state.buffer.head.data.length:state.length}function onEofChunk(stream,state){if(debug("onEofChunk"),!state.ended){if(state.decoder){var chunk=state.decoder.end();chunk&&chunk.length&&(state.buffer.push(chunk),state.length+=state.objectMode?1:chunk.length)}state.ended=!0,state.sync?emitReadable(stream):(state.needReadable=!1,!state.emittedReadable&&(state.emittedReadable=!0,emitReadable_(stream)))}}function emitReadable(stream){var state=stream._readableState;debug("emitReadable",state.needReadable,state.emittedReadable),state.needReadable=!1,state.emittedReadable||(debug("emitReadable",state.flowing),state.emittedReadable=!0,process.nextTick(emitReadable_,stream))}function emitReadable_(stream){var state=stream._readableState;debug("emitReadable_",state.destroyed,state.length,state.ended),!state.destroyed&&(state.length||state.ended)&&(stream.emit("readable"),state.emittedReadable=!1),state.needReadable=!state.flowing&&!state.ended&&state.length<=state.highWaterMark,flow(stream)}function maybeReadMore(stream,state){state.readingMore||(state.readingMore=!0,process.nextTick(maybeReadMore_,stream,state))}function maybeReadMore_(stream,state){for(;!state.reading&&!state.ended&&(state.length=state.length?(ret=state.decoder?state.buffer.join(""):1===state.buffer.length?state.buffer.first():state.buffer.concat(state.length),state.buffer.clear()):ret=state.buffer.consume(n,state.decoder),ret}function endReadable(stream){var state=stream._readableState;debug("endReadable",state.endEmitted),state.endEmitted||(state.ended=!0,process.nextTick(endReadableNT,state,stream))}function endReadableNT(state,stream){if(debug("endReadableNT",state.endEmitted,state.length),!state.endEmitted&&0===state.length&&(state.endEmitted=!0,stream.readable=!1,stream.emit("end"),state.autoDestroy)){var wState=stream._writableState;(!wState||wState.autoDestroy&&wState.finished)&&stream.destroy()}}function indexOf(xs,x){for(var i=0,l=xs.length;i=state.highWaterMark)||state.ended))return debug("read: emitReadable",state.length,state.ended),0===state.length&&state.ended?endReadable(this):emitReadable(this),null;if(n=howMuchToRead(n,state),0===n&&state.ended)return 0===state.length&&endReadable(this),null;var doRead=state.needReadable;debug("need readable",doRead),(0===state.length||state.length-n>>0),p=this.head,i=0;p;)copyBuffer(p.data,ret,i),i+=p.data.length,p=p.next;return ret}},{key:"consume",value:function(n,hasStrings){var ret;return nstr.length?str.length:n;if(ret+=nb===str.length?str:str.slice(0,n),n-=nb,0===n){nb===str.length?(++c,this.head=p.next?p.next:this.tail=null):(this.head=p,p.data=str.slice(nb));break}++c}return this.length-=c,ret}},{key:"_getBuffer",value:function(n){var ret=Buffer.allocUnsafe(n),p=this.head,c=1;for(p.data.copy(ret),n-=p.data.length;p=p.next;){var buf=p.data,nb=n>buf.length?buf.length:n;if(buf.copy(ret,ret.length-n,0,nb),n-=nb,0===n){nb===buf.length?(++c,this.head=p.next?p.next:this.tail=null):(this.head=p,p.data=buf.slice(nb));break}++c}return this.length-=c,ret}},{key:custom,value:function(_,options){return inspect(this,_objectSpread({},options,{depth:0,customInspect:!1}))}}]),BufferList}()},{buffer:38,util:36}],50:[function(require,module){(function(process){(function(){'use strict';function emitErrorAndCloseNT(self,err){emitErrorNT(self,err),emitCloseNT(self)}function emitCloseNT(self){self._writableState&&!self._writableState.emitClose||self._readableState&&!self._readableState.emitClose||self.emit("close")}function emitErrorNT(self,err){self.emit("error",err)}module.exports={destroy:function(err,cb){var _this=this,readableDestroyed=this._readableState&&this._readableState.destroyed,writableDestroyed=this._writableState&&this._writableState.destroyed;return readableDestroyed||writableDestroyed?(cb?cb(err):err&&(this._writableState?!this._writableState.errorEmitted&&(this._writableState.errorEmitted=!0,process.nextTick(emitErrorNT,this,err)):process.nextTick(emitErrorNT,this,err)),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(err||null,function(err){!cb&&err?_this._writableState?_this._writableState.errorEmitted?process.nextTick(emitCloseNT,_this):(_this._writableState.errorEmitted=!0,process.nextTick(emitErrorAndCloseNT,_this,err)):process.nextTick(emitErrorAndCloseNT,_this,err):cb?(process.nextTick(emitCloseNT,_this),cb(err)):process.nextTick(emitCloseNT,_this)}),this)},undestroy:function(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finalCalled=!1,this._writableState.prefinished=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)},errorOrDestroy:function(stream,err){var rState=stream._readableState,wState=stream._writableState;rState&&rState.autoDestroy||wState&&wState.autoDestroy?stream.destroy(err):stream.emit("error",err)}}}).call(this)}).call(this,require("_process"))},{_process:132}],51:[function(require,module){'use strict';function once(callback){var called=!1;return function(){if(!called){called=!0;for(var _len=arguments.length,args=Array(_len),_key=0;_key<_len;_key++)args[_key]=arguments[_key];callback.apply(this,args)}}}function noop(){}function isRequest(stream){return stream.setHeader&&"function"==typeof stream.abort}function eos(stream,opts,callback){if("function"==typeof opts)return eos(stream,null,opts);opts||(opts={}),callback=once(callback||noop);var readable=opts.readable||!1!==opts.readable&&stream.readable,writable=opts.writable||!1!==opts.writable&&stream.writable,onlegacyfinish=function(){stream.writable||onfinish()},writableEnded=stream._writableState&&stream._writableState.finished,onfinish=function(){writable=!1,writableEnded=!0,readable||callback.call(stream)},readableEnded=stream._readableState&&stream._readableState.endEmitted,onend=function(){readable=!1,readableEnded=!0,writable||callback.call(stream)},onerror=function(err){callback.call(stream,err)},onclose=function(){var err;return readable&&!readableEnded?(stream._readableState&&stream._readableState.ended||(err=new ERR_STREAM_PREMATURE_CLOSE),callback.call(stream,err)):writable&&!writableEnded?(stream._writableState&&stream._writableState.ended||(err=new ERR_STREAM_PREMATURE_CLOSE),callback.call(stream,err)):void 0},onrequest=function(){stream.req.on("finish",onfinish)};return isRequest(stream)?(stream.on("complete",onfinish),stream.on("abort",onclose),stream.req?onrequest():stream.on("request",onrequest)):writable&&!stream._writableState&&(stream.on("end",onlegacyfinish),stream.on("close",onlegacyfinish)),stream.on("end",onend),stream.on("finish",onfinish),!1!==opts.error&&stream.on("error",onerror),stream.on("close",onclose),function(){stream.removeListener("complete",onfinish),stream.removeListener("abort",onclose),stream.removeListener("request",onrequest),stream.req&&stream.req.removeListener("finish",onfinish),stream.removeListener("end",onlegacyfinish),stream.removeListener("close",onlegacyfinish),stream.removeListener("finish",onfinish),stream.removeListener("end",onend),stream.removeListener("error",onerror),stream.removeListener("close",onclose)}}var ERR_STREAM_PREMATURE_CLOSE=require("../../../errors").codes.ERR_STREAM_PREMATURE_CLOSE;module.exports=eos},{"../../../errors":42}],52:[function(require,module){module.exports=function(){throw new Error("Readable.from is not available in the browser")}},{}],53:[function(require,module){'use strict';function once(callback){var called=!1;return function(){called||(called=!0,callback.apply(void 0,arguments))}}function noop(err){if(err)throw err}function isRequest(stream){return stream.setHeader&&"function"==typeof stream.abort}function destroyer(stream,reading,writing,callback){callback=once(callback);var closed=!1;stream.on("close",function(){closed=!0}),eos===void 0&&(eos=require("./end-of-stream")),eos(stream,{readable:reading,writable:writing},function(err){return err?callback(err):void(closed=!0,callback())});var destroyed=!1;return function(err){if(!closed)return destroyed?void 0:(destroyed=!0,isRequest(stream)?stream.abort():"function"==typeof stream.destroy?stream.destroy():void callback(err||new ERR_STREAM_DESTROYED("pipe")))}}function call(fn){fn()}function pipe(from,to){return from.pipe(to)}function popCallback(streams){return streams.length?"function"==typeof streams[streams.length-1]?streams.pop():noop:noop}var _require$codes=require("../../../errors").codes,ERR_MISSING_ARGS=_require$codes.ERR_MISSING_ARGS,ERR_STREAM_DESTROYED=_require$codes.ERR_STREAM_DESTROYED,eos;module.exports=function(){for(var _len=arguments.length,streams=Array(_len),_key=0;_key<_len;_key++)streams[_key]=arguments[_key];var callback=popCallback(streams);if(Array.isArray(streams[0])&&(streams=streams[0]),2>streams.length)throw new ERR_MISSING_ARGS("streams");var destroys=streams.map(function(stream,i){var reading=ihwm){var name=isDuplex?duplexKey:"highWaterMark";throw new ERR_INVALID_OPT_VALUE(name,hwm)}return _Mathfloor(hwm)}return state.objectMode?16:16384}}},{"../../../errors":42}],55:[function(require,module){module.exports=require("events").EventEmitter},{events:39}],56:[function(require,module,exports){arguments[4][13][0].apply(exports,arguments)},{dup:13}],57:[function(require,module,exports){'use strict';function uncurryThis(f){return f.call.bind(f)}function checkBoxedPrimitive(value,prototypeValueOf){if("object"!=typeof value)return!1;try{return prototypeValueOf(value),!0}catch(e){return!1}}function isMapToString(value){return"[object Map]"===ObjectToString(value)}function isSetToString(value){return"[object Set]"===ObjectToString(value)}function isWeakMapToString(value){return"[object WeakMap]"===ObjectToString(value)}function isWeakSetToString(value){return"[object WeakSet]"===ObjectToString(value)}function isArrayBufferToString(value){return"[object ArrayBuffer]"===ObjectToString(value)}function isArrayBuffer(value){return"undefined"!=typeof ArrayBuffer&&(isArrayBufferToString.working?isArrayBufferToString(value):value instanceof ArrayBuffer)}function isDataViewToString(value){return"[object DataView]"===ObjectToString(value)}function isDataView(value){return"undefined"!=typeof DataView&&(isDataViewToString.working?isDataViewToString(value):value instanceof DataView)}function isSharedArrayBufferToString(value){return"[object SharedArrayBuffer]"===ObjectToString(value)}function isSharedArrayBuffer(value){return"undefined"!=typeof SharedArrayBuffer&&(isSharedArrayBufferToString.working?isSharedArrayBufferToString(value):value instanceof SharedArrayBuffer)}function isNumberObject(value){return checkBoxedPrimitive(value,numberValue)}function isStringObject(value){return checkBoxedPrimitive(value,stringValue)}function isBooleanObject(value){return checkBoxedPrimitive(value,booleanValue)}function isBigIntObject(value){return BigIntSupported&&checkBoxedPrimitive(value,bigIntValue)}function isSymbolObject(value){return SymbolSupported&&checkBoxedPrimitive(value,symbolValue)}var isArgumentsObject=require("is-arguments"),isGeneratorFunction=require("is-generator-function"),whichTypedArray=require("which-typed-array"),isTypedArray=require("is-typed-array"),BigIntSupported="undefined"!=typeof BigInt,SymbolSupported="undefined"!=typeof Symbol,ObjectToString=uncurryThis(Object.prototype.toString),numberValue=uncurryThis(_Numberprototype.valueOf),stringValue=uncurryThis(_Stringprototype.valueOf),booleanValue=uncurryThis(Boolean.prototype.valueOf);if(BigIntSupported)var bigIntValue=uncurryThis(BigInt.prototype.valueOf);if(SymbolSupported)var symbolValue=uncurryThis(Symbol.prototype.valueOf);exports.isArgumentsObject=isArgumentsObject,exports.isGeneratorFunction=isGeneratorFunction,exports.isTypedArray=isTypedArray,exports.isPromise=function(input){return"undefined"!=typeof Promise&&input instanceof Promise||null!==input&&"object"==typeof input&&"function"==typeof input.then&&"function"==typeof input.catch},exports.isArrayBufferView=function(value){return"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(value):isTypedArray(value)||isDataView(value)},exports.isUint8Array=function(value){return"Uint8Array"===whichTypedArray(value)},exports.isUint8ClampedArray=function(value){return"Uint8ClampedArray"===whichTypedArray(value)},exports.isUint16Array=function(value){return"Uint16Array"===whichTypedArray(value)},exports.isUint32Array=function(value){return"Uint32Array"===whichTypedArray(value)},exports.isInt8Array=function(value){return"Int8Array"===whichTypedArray(value)},exports.isInt16Array=function(value){return"Int16Array"===whichTypedArray(value)},exports.isInt32Array=function(value){return"Int32Array"===whichTypedArray(value)},exports.isFloat32Array=function(value){return"Float32Array"===whichTypedArray(value)},exports.isFloat64Array=function(value){return"Float64Array"===whichTypedArray(value)},exports.isBigInt64Array=function(value){return"BigInt64Array"===whichTypedArray(value)},exports.isBigUint64Array=function(value){return"BigUint64Array"===whichTypedArray(value)},isMapToString.working="undefined"!=typeof Map&&isMapToString(new Map),exports.isMap=function(value){return"undefined"!=typeof Map&&(isMapToString.working?isMapToString(value):value instanceof Map)},isSetToString.working="undefined"!=typeof Set&&isSetToString(new Set),exports.isSet=function(value){return"undefined"!=typeof Set&&(isSetToString.working?isSetToString(value):value instanceof Set)},isWeakMapToString.working="undefined"!=typeof WeakMap&&isWeakMapToString(new WeakMap),exports.isWeakMap=function(value){return"undefined"!=typeof WeakMap&&(isWeakMapToString.working?isWeakMapToString(value):value instanceof WeakMap)},isWeakSetToString.working="undefined"!=typeof WeakSet&&isWeakSetToString(new WeakSet),exports.isWeakSet=function(value){return isWeakSetToString(value)},isArrayBufferToString.working="undefined"!=typeof ArrayBuffer&&isArrayBufferToString(new ArrayBuffer),exports.isArrayBuffer=isArrayBuffer,isDataViewToString.working="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof DataView&&isDataViewToString(new DataView(new ArrayBuffer(1),0,1)),exports.isDataView=isDataView,isSharedArrayBufferToString.working="undefined"!=typeof SharedArrayBuffer&&isSharedArrayBufferToString(new SharedArrayBuffer),exports.isSharedArrayBuffer=isSharedArrayBuffer,exports.isAsyncFunction=function(value){return"[object AsyncFunction]"===ObjectToString(value)},exports.isMapIterator=function(value){return"[object Map Iterator]"===ObjectToString(value)},exports.isSetIterator=function(value){return"[object Set Iterator]"===ObjectToString(value)},exports.isGeneratorObject=function(value){return"[object Generator]"===ObjectToString(value)},exports.isWebAssemblyCompiledModule=function(value){return"[object WebAssembly.Module]"===ObjectToString(value)},exports.isNumberObject=isNumberObject,exports.isStringObject=isStringObject,exports.isBooleanObject=isBooleanObject,exports.isBigIntObject=isBigIntObject,exports.isSymbolObject=isSymbolObject,exports.isBoxedPrimitive=function(value){return isNumberObject(value)||isStringObject(value)||isBooleanObject(value)||isBigIntObject(value)||isSymbolObject(value)},exports.isAnyArrayBuffer=function(value){return"undefined"!=typeof Uint8Array&&(isArrayBuffer(value)||isSharedArrayBuffer(value))},["isProxy","isExternal","isModuleNamespaceObject"].forEach(function(method){Object.defineProperty(exports,method,{enumerable:!1,value:function(){throw new Error(method+" is not supported in userland")}})})},{"is-arguments":99,"is-generator-function":103,"is-typed-array":104,"which-typed-array":199}],58:[function(require,module,exports){(function(process){(function(){function inspect(obj,opts){var ctx={seen:[],stylize:stylizeNoColor};return 3<=arguments.length&&(ctx.depth=arguments[2]),4<=arguments.length&&(ctx.colors=arguments[3]),isBoolean(opts)?ctx.showHidden=opts:opts&&exports._extend(ctx,opts),isUndefined(ctx.showHidden)&&(ctx.showHidden=!1),isUndefined(ctx.depth)&&(ctx.depth=2),isUndefined(ctx.colors)&&(ctx.colors=!1),isUndefined(ctx.customInspect)&&(ctx.customInspect=!0),ctx.colors&&(ctx.stylize=stylizeWithColor),formatValue(ctx,obj,ctx.depth)}function stylizeWithColor(str,styleType){var style=inspect.styles[styleType];return style?"\x1B["+inspect.colors[style][0]+"m"+str+"\x1B["+inspect.colors[style][1]+"m":str}function stylizeNoColor(str){return str}function arrayToHash(array){var hash={};return array.forEach(function(val){hash[val]=!0}),hash}function formatValue(ctx,value,recurseTimes){if(ctx.customInspect&&value&&isFunction(value.inspect)&&value.inspect!==exports.inspect&&!(value.constructor&&value.constructor.prototype===value)){var ret=value.inspect(recurseTimes,ctx);return isString(ret)||(ret=formatValue(ctx,ret,recurseTimes)),ret}var primitive=formatPrimitive(ctx,value);if(primitive)return primitive;var keys=Object.keys(value),visibleKeys=arrayToHash(keys);if(ctx.showHidden&&(keys=Object.getOwnPropertyNames(value)),isError(value)&&(0<=keys.indexOf("message")||0<=keys.indexOf("description")))return formatError(value);if(0===keys.length){if(isFunction(value)){var name=value.name?": "+value.name:"";return ctx.stylize("[Function"+name+"]","special")}if(isRegExp(value))return ctx.stylize(RegExp.prototype.toString.call(value),"regexp");if(isDate(value))return ctx.stylize(Date.prototype.toString.call(value),"date");if(isError(value))return formatError(value)}var base="",array=!1,braces=["{","}"];if(isArray(value)&&(array=!0,braces=["[","]"]),isFunction(value)){var n=value.name?": "+value.name:"";base=" [Function"+n+"]"}if(isRegExp(value)&&(base=" "+RegExp.prototype.toString.call(value)),isDate(value)&&(base=" "+Date.prototype.toUTCString.call(value)),isError(value)&&(base=" "+formatError(value)),0===keys.length&&(!array||0==value.length))return braces[0]+base+braces[1];if(0>recurseTimes)return isRegExp(value)?ctx.stylize(RegExp.prototype.toString.call(value),"regexp"):ctx.stylize("[Object]","special");ctx.seen.push(value);var output;return output=array?formatArray(ctx,value,recurseTimes,visibleKeys,keys):keys.map(function(key){return formatProperty(ctx,value,recurseTimes,visibleKeys,key,array)}),ctx.seen.pop(),reduceToSingleString(output,base,braces)}function formatPrimitive(ctx,value){if(isUndefined(value))return ctx.stylize("undefined","undefined");if(isString(value)){var simple="'"+JSON.stringify(value).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,"\"")+"'";return ctx.stylize(simple,"string")}return isNumber(value)?ctx.stylize(""+value,"number"):isBoolean(value)?ctx.stylize(""+value,"boolean"):isNull(value)?ctx.stylize("null","null"):void 0}function formatError(value){return"["+Error.prototype.toString.call(value)+"]"}function formatArray(ctx,value,recurseTimes,visibleKeys,keys){for(var output=[],i=0,l=value.length;ictx.seen.indexOf(desc.value)?(str=isNull(recurseTimes)?formatValue(ctx,desc.value,null):formatValue(ctx,desc.value,recurseTimes-1),-1n?"0"+n.toString(10):n.toString(10)}function timestamp(){var d=new Date,time=[pad(d.getHours()),pad(d.getMinutes()),pad(d.getSeconds())].join(":");return[d.getDate(),months[d.getMonth()],time].join(" ")}function hasOwnProperty(obj,prop){return Object.prototype.hasOwnProperty.call(obj,prop)}function callbackifyOnRejected(reason,cb){if(!reason){var newReason=new Error("Promise was rejected with a falsy value");newReason.reason=reason,reason=newReason}return cb(reason)}var getOwnPropertyDescriptors=Object.getOwnPropertyDescriptors||function(obj){for(var keys=Object.keys(obj),descriptors={},i=0;i=len)return x;switch(x){case"%s":return args[i++]+"";case"%d":return+args[i++];case"%j":try{return JSON.stringify(args[i++])}catch(_){return"[Circular]"}default:return x;}}),x=args[i];isize)throw new RangeError("\"size\" argument must not be negative");return Buffer.allocUnsafe?Buffer.allocUnsafe(size):new Buffer(size)}}).call(this)}).call(this,require("buffer").Buffer)},{buffer:38}],60:[function(require,module){(function(Buffer){(function(){var bufferFill=require("buffer-fill"),allocUnsafe=require("buffer-alloc-unsafe");module.exports=function(size,fill,encoding){if("number"!=typeof size)throw new TypeError("\"size\" argument must be a number");if(0>size)throw new RangeError("\"size\" argument must not be negative");if(Buffer.alloc)return Buffer.alloc(size,fill,encoding);var buffer=allocUnsafe(size);return 0===size?buffer:void 0===fill?bufferFill(buffer,0):("string"!=typeof encoding&&(encoding=void 0),bufferFill(buffer,fill,encoding))}}).call(this)}).call(this,require("buffer").Buffer)},{buffer:38,"buffer-alloc-unsafe":59,"buffer-fill":61}],61:[function(require,module){(function(Buffer){(function(){function isSingleByte(val){return 1===val.length&&256>val.charCodeAt(0)}function fillWithNumber(buffer,val,start,end){if(0>start||end>buffer.length)throw new RangeError("Out of range index");return start>>>=0,end=void 0===end?buffer.length:end>>>0,end>start&&buffer.fill(val,start,end),buffer}function fillWithBuffer(buffer,val,start,end){if(0>start||end>buffer.length)throw new RangeError("Out of range index");if(end<=start)return buffer;start>>>=0,end=void 0===end?buffer.length:end>>>0;for(var pos=start,len=val.length;pos<=end-len;)val.copy(buffer,pos),pos+=len;return pos!==end&&val.copy(buffer,pos,0,end-pos),buffer}var hasFullSupport=function(){try{if(!Buffer.isEncoding("latin1"))return!1;var buf=Buffer.alloc?Buffer.alloc(4):new Buffer(4);return buf.fill("ab","ucs2"),"61006200"===buf.toString("hex")}catch(_){return!1}}();module.exports=function(buffer,val,start,end,encoding){if(hasFullSupport)return buffer.fill(val,start,end,encoding);if("number"==typeof val)return fillWithNumber(buffer,val,start,end);if("string"==typeof val){if("string"==typeof start?(encoding=start,start=0,end=buffer.length):"string"==typeof end&&(encoding=end,end=buffer.length),void 0!==encoding&&"string"!=typeof encoding)throw new TypeError("encoding must be a string");if("latin1"===encoding&&(encoding="binary"),"string"==typeof encoding&&!Buffer.isEncoding(encoding))throw new TypeError("Unknown encoding: "+encoding);if(""===val)return fillWithNumber(buffer,0,start,end);if(isSingleByte(val))return fillWithNumber(buffer,val.charCodeAt(0),start,end);val=new Buffer(val,encoding)}return Buffer.isBuffer(val)?fillWithBuffer(buffer,val,start,end):fillWithNumber(buffer,0,start,end)}}).call(this)}).call(this,require("buffer").Buffer)},{buffer:38}],62:[function(require,module){module.exports={100:"Continue",101:"Switching Protocols",102:"Processing",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Unordered Collection",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",509:"Bandwidth Limit Exceeded",510:"Not Extended",511:"Network Authentication Required"}},{}],63:[function(require,module,exports){(function(Buffer){(function(){function onReceive(info){info.socketId in sockets?sockets[info.socketId]._onReceive(info):console.error("Unknown socket id: "+info.socketId)}function onReceiveError(info){info.socketId in sockets?sockets[info.socketId]._onReceiveError(info.resultCode):console.error("Unknown socket id: "+info.socketId)}function Socket(options,listener){var self=this;if(EventEmitter.call(self),"string"==typeof options&&(options={type:options}),"udp4"!==options.type)throw new Error("Bad socket type specified. Valid types are: udp4");"function"==typeof listener&&self.on("message",listener),self._destroyed=!1,self._bindState=0,self._bindTasks=[]}function sliceBuffer(buffer,offset,length){if("string"==typeof buffer)buffer=Buffer.from(buffer);else if(!(buffer instanceof Buffer))throw new TypeError("First argument must be a buffer or string");offset>>>=0,length>>>=0;var buf=buffer.buffer;return(buffer.byteOffset||buffer.byteLength!==buf.byteLength)&&(buf=buf.slice(buffer.byteOffset,buffer.byteOffset+buffer.byteLength)),(offset||length!==buffer.length)&&(buf=buf.slice(offset,length)),Buffer.from(buf)}function fixBufferList(list){for(var newlist=Array(list.length),i=0,l=list.length,buf;iresult?void self.emit("error",new Error("Socket "+self.id+" failed to bind. "+chrome.runtime.lastError.message)):void chrome.sockets.udp.getInfo(self.id,function(socketInfo){return socketInfo.localPort&&socketInfo.localAddress?void(self._port=socketInfo.localPort,self._address=socketInfo.localAddress,self._bindState=BIND_STATE_BOUND,self.emit("listening"),self._bindTasks.map(function(t){t.callback()})):void self.emit("error",new Error("Cannot get local port/address for Socket "+self.id))})})})})},Socket.prototype._onReceive=function(info){var self=this,buf=Buffer.from(new Uint8Array(info.data)),rinfo={address:info.remoteAddress,family:"IPv4",port:info.remotePort,size:buf.length};self.emit("message",buf,rinfo)},Socket.prototype._onReceiveError=function(resultCode){var self=this;self.emit("error",new Error("Socket "+self.id+" receive error "+resultCode))},Socket.prototype.send=function(buffer,offset,length,port,address,callback){var self=this,list;if(address||port&&"function"!=typeof port?buffer=sliceBuffer(buffer,offset,length):(callback=port,port=offset,address=length),!Array.isArray(buffer)){if("string"==typeof buffer)list=[Buffer.from(buffer)];else if(!(buffer instanceof Buffer))throw new TypeError("First argument must be a buffer or a string");else list=[buffer];}else if(!(list=fixBufferList(buffer)))throw new TypeError("Buffer list arguments must be buffers or strings");if(port>>>=0,0===port||65535 0 and < 65536");if("function"!=typeof callback&&(callback=function(){}),self._bindState===BIND_STATE_UNBOUND&&self.bind(0),self._bindState!==BIND_STATE_BOUND)return self._sendQueue||(self._sendQueue=[],self.once("listening",function(){for(var i=0;isendInfo.resultCode){var err=new Error("Socket "+self.id+" send error "+sendInfo.resultCode);callback(err),self.emit("error",err)}else callback(null)})},Socket.prototype.close=function(){var self=this;self._destroyed||(delete sockets[self.id],chrome.sockets.udp.close(self.id),self._destroyed=!0,self.emit("close"))},Socket.prototype.address=function(){var self=this;return{address:self._address,port:self._port,family:"IPv4"}},Socket.prototype.setBroadcast=function(){},Socket.prototype.setTTL=function(){},Socket.prototype.setMulticastTTL=function(ttl,callback){function setMulticastTTL(callback){chrome.sockets.udp.setMulticastTimeToLive(self.id,ttl,callback)}var self=this;callback||(callback=function(){}),self._bindState===BIND_STATE_BOUND?setMulticastTTL(callback):self._bindTasks.push({fn:setMulticastTTL,callback})},Socket.prototype.setMulticastLoopback=function(flag,callback){function setMulticastLoopback(callback){chrome.sockets.udp.setMulticastLoopbackMode(self.id,flag,callback)}var self=this;callback||(callback=function(){}),self._bindState===BIND_STATE_BOUND?setMulticastLoopback(callback):self._bindTasks.push({fn:setMulticastLoopback,callback})},Socket.prototype.addMembership=function(multicastAddress,multicastInterface,callback){var self=this;callback||(callback=function(){}),chrome.sockets.udp.joinGroup(self.id,multicastAddress,callback)},Socket.prototype.dropMembership=function(multicastAddress,multicastInterface,callback){var self=this;callback||(callback=function(){}),chrome.sockets.udp.leaveGroup(self.id,multicastAddress,callback)},Socket.prototype.unref=function(){},Socket.prototype.ref=function(){}}).call(this)}).call(this,require("buffer").Buffer)},{buffer:38,events:39,inherits:97,"run-series":163}],64:[function(require,module,exports){function lookup(hostname,opts,cb){return"function"==typeof opts?lookup(hostname,null,opts):void chrome.dns.resolve(hostname,resolveInfo=>{if(0!==resolveInfo.resultCode)return cb(new Error("DNS lookup error: "+chrome.runtime.lastError.message));const address=resolveInfo.address,ipVersion=isIPv4(address)?4:isIPv6(address)?6:0;cb(null,address,ipVersion)})}const{isIPv4,isIPv6}=require("chrome-net");exports.lookup=lookup},{"chrome-net":65}],65:[function(require,module,exports){(function(process){(function(){/*! chrome-net. MIT License. Feross Aboukhadijeh */'use strict';function onAccept(info){info.socketId in servers?servers[info.socketId]._onAccept(info.clientSocketId):console.error("Unknown server socket id: "+info.socketId)}function onAcceptError(info){info.socketId in servers?servers[info.socketId]._onAcceptError(info.resultCode):console.error("Unknown server socket id: "+info.socketId)}function onReceive(info){info.socketId in sockets?sockets[info.socketId]._onReceive(info.data):console.error("Unknown socket id: "+info.socketId)}function onReceiveError(info){if(info.socketId in sockets)sockets[info.socketId]._onReceiveError(info.resultCode);else{if(-100===info.resultCode)return;console.error("Unknown socket id: "+info.socketId)}}function Server(options,connectionListener){if(!(this instanceof Server))return new Server(options,connectionListener);if(EventEmitter.call(this),"function"==typeof options)connectionListener=options,options={},this.on("connection",connectionListener);else if(null==options||"object"==typeof options)options=options||{},"function"==typeof connectionListener&&this.on("connection",connectionListener);else throw new TypeError("options must be an object");this._connections=0,Object.defineProperty(this,"connections",{get:deprecate(()=>this._connections,"Server.connections property is deprecated. Use Server.getConnections method instead."),set:deprecate(val=>this._connections=val,"Server.connections property is deprecated."),configurable:!0,enumerable:!1}),this.id=null,this.connecting=!1,this.allowHalfOpen=options.allowHalfOpen||!1,this.pauseOnConnect=!!options.pauseOnConnect,this._address=null,this._host=null,this._port=null,this._backlog=null}function emitCloseNT(self){self.id||self.connecting||self._connections||self.emit("close")}function Socket(options){if(!(this instanceof Socket))return new Socket(options);if("number"==typeof options?options={fd:options}:void 0===options&&(options={}),options.handle)throw new Error("handle is not supported in Chrome Apps.");else if(void 0!==options.fd)throw new Error("fd is not supported in Chrome Apps.");options.decodeStrings=!0,options.objectMode=!1,stream.Duplex.call(this,options),this.destroyed=!1,this._hadError=!1,this.id=null,this._parent=null,this._host=null,this._port=null,this._pendingData=null,this.ondata=null,this.onend=null,this._init(),this._reset(),this.allowHalfOpen=options.allowHalfOpen||!1,this.on("finish",this.destroy),options.server&&(this.server=this._server=options.server,this.id=options.id,sockets[this.id]=this,options.pauseOnCreate&&(this._readableState.flowing=!1),this.connecting=!0,this.writable=!0,this._onConnect())}function normalizeConnectArgs(args){var options={};if(null!==args[0]&&"object"==typeof args[0])options=args[0];else if(isPipeName(args[0]))throw new Error("Pipes are not supported in Chrome Apps.");else options.port=args[0],"string"==typeof args[1]&&(options.host=args[1]);var cb=args[args.length-1];return"function"==typeof cb?[options,cb]:[options]}function toNumber(x){return!!(0<=(x=+x))&&x}function isPipeName(s){return"string"==typeof s&&!1===toNumber(s)}function isLegalPort(port){return("number"==typeof port||"string"==typeof port)&&("string"!=typeof port||0!==port.trim().length)&&+port==+port>>>0&&65535>=port}function assertPort(port){if("undefined"!=typeof port&&!isLegalPort(port))throw new RangeError("\"port\" argument must be >= 0 and < 65536")}function ignoreLastError(){void chrome.runtime.lastError}function chromeCallbackWrap(callback){return()=>{var error;chrome.runtime.lastError&&(console.error(chrome.runtime.lastError.message),error=new Error(chrome.runtime.lastError.message)),callback&&callback(error)}}function emitErrorNT(self,err){self.emit("error",err)}function errnoException(err,syscall,details){var uvCode=errorChromeToUv[err]||"UNKNOWN",message=syscall+" "+err+" "+details;chrome.runtime.lastError&&(message+=" "+chrome.runtime.lastError.message),message+=" (mapped uv code: "+uvCode+")";var e=new Error(message);return e.code=e.errno=uvCode,e.syscall=syscall,e}function exceptionWithHostPort(err,syscall,address,port,additional){var details;details=port&&0{if(!this.connecting||this.id)return ignoreLastError(),void chrome.sockets.tcpServer.close(createInfo.socketId);if(chrome.runtime.lastError)return void this.emit("error",new Error(chrome.runtime.lastError.message));var socketId=this.id=createInfo.socketId;servers[this.id]=this;var listen=()=>chrome.sockets.tcpServer.listen(this.id,this._host,this._port,this._backlog,result=>this.id===socketId?0!==result&&isAny6?(ignoreLastError(),this._host="0.0.0.0",isAny6=!1,listen()):void this._onListen(result):void ignoreLastError());listen()}),this},Server.prototype._onListen=function(result){if(this.connecting=!1,0===result){var idBefore=this.id;chrome.sockets.tcpServer.getInfo(this.id,info=>this.id===idBefore?chrome.runtime.lastError?void this._onListen(-2):void(this._address={port:info.localPort,family:info.localAddress&&-1!==info.localAddress.indexOf(":")?"IPv6":"IPv4",address:info.localAddress},this.emit("listening")):void ignoreLastError())}else this.emit("error",exceptionWithHostPort(result,"listen",this._host,this._port)),this.id&&(chrome.sockets.tcpServer.close(this.id),delete servers[this.id],this.id=null)},Server.prototype._onAccept=function(clientSocketId){if(this.maxConnections&&this._connections>=this.maxConnections)return chrome.sockets.tcp.close(clientSocketId),void console.warn("Rejected connection - hit `maxConnections` limit");this._connections+=1;var acceptedSocket=new Socket({server:this,id:clientSocketId,allowHalfOpen:this.allowHalfOpen,pauseOnCreate:this.pauseOnConnect});acceptedSocket.on("connect",()=>this.emit("connection",acceptedSocket))},Server.prototype._onAcceptError=function(resultCode){this.emit("error",errnoException(resultCode,"accept")),this.close()},Server.prototype.close=function(callback){return"function"==typeof callback&&(this.id?this.once("close",callback):this.once("close",()=>callback(new Error("Not running")))),this.id&&(chrome.sockets.tcpServer.close(this.id),delete servers[this.id],this.id=null),this._address=null,this.connecting=!1,this._emitCloseIfDrained(),this},Server.prototype._emitCloseIfDrained=function(){this.id||this.connecting||this._connections||process.nextTick(emitCloseNT,this)},Object.defineProperty(Server.prototype,"listening",{get:function(){return!!this._address},configurable:!0,enumerable:!0}),Server.prototype.address=function(){return this._address},Server.prototype.unref=Server.prototype.ref=function(){return this},Server.prototype.getConnections=function(callback){process.nextTick(callback,null,this._connections)},inherits(Socket,stream.Duplex),exports.Socket=Socket,Socket.prototype._init=function(){this.bytesRead=0,this._bytesDispatched=0,this.server=null,this._server=null},Socket.prototype._reset=function(){this.remoteAddress=this.remotePort=this.localAddress=this.localPort=null,this.remoteFamily="IPv4",this.readable=this.writable=!1,this.connecting=!1},Socket.prototype.connect=function(){const argsLen=arguments.length;for(var args=Array(argsLen),i=0;i= 0 and < 65536: "+this._port)}return this._port|=0,this._init(),this._unrefTimer(),"function"==typeof cb&&this.once("connect",cb),chrome.sockets.tcp.create(createInfo=>!this.connecting||this.id?(ignoreLastError(),void chrome.sockets.tcp.close(createInfo.socketId)):chrome.runtime.lastError?void this.destroy(new Error(chrome.runtime.lastError.message)):void(this.id=createInfo.socketId,sockets[this.id]=this,chrome.sockets.tcp.setPaused(this.id,!0),chrome.sockets.tcp.connect(this.id,this._host,this._port,result=>this.id===createInfo.socketId?0===result?void(this._unrefTimer(),this._onConnect()):void this.destroy(exceptionWithHostPort(result,"connect",this._host,this._port)):void ignoreLastError()))),this},Socket.prototype._onConnect=function(){var idBefore=this.id;chrome.sockets.tcp.getInfo(this.id,result=>this.id===idBefore?chrome.runtime.lastError?void this.destroy(new Error(chrome.runtime.lastError.message)):void(this.remoteAddress=result.peerAddress,this.remoteFamily=result.peerAddress&&-1!==result.peerAddress.indexOf(":")?"IPv6":"IPv4",this.remotePort=result.peerPort,this.localAddress=result.localAddress,this.localPort=result.localPort,this.connecting=!1,this.readable=!0,this.emit("connect"),!this.isPaused()&&this.read(0)):void ignoreLastError())},Object.defineProperty(Socket.prototype,"bufferSize",{get:function(){if(this.id){var bytes=this._writableState.length;return this._pendingData&&(bytes+=this._pendingData.length),bytes}}}),Socket.prototype.end=function(data,encoding){stream.Duplex.prototype.end.call(this,data,encoding),this.writable=!1},Socket.prototype._write=function(chunk,encoding,callback){if(callback||(callback=()=>{}),this.connecting)return this._pendingData=chunk,void this.once("connect",()=>this._write(chunk,encoding,callback));if(this._pendingData=null,!this.id)return void callback(new Error("This socket is closed"));var buffer=chunk.buffer;chunk.byteLength!==buffer.byteLength&&(buffer=buffer.slice(chunk.byteOffset,chunk.byteOffset+chunk.byteLength));var idBefore=this.id;chrome.sockets.tcp.send(this.id,buffer,sendInfo=>this.id===idBefore?void(0>sendInfo.resultCode?this._destroy(exceptionWithHostPort(sendInfo.resultCode,"write",this.remoteAddress,this.remotePort),callback):(this._unrefTimer(),callback(null))):void ignoreLastError()),this._bytesDispatched+=chunk.length},Socket.prototype._read=function(bufferSize){if(this.connecting||!this.id)return void this.once("connect",()=>this._read(bufferSize));chrome.sockets.tcp.setPaused(this.id,!1);var idBefore=this.id;chrome.sockets.tcp.getInfo(this.id,result=>this.id===idBefore?void((chrome.runtime.lastError||!result.connected)&&this._onReceiveError(-15)):void ignoreLastError())},Socket.prototype._onReceive=function(data){var buffer=Buffer.from(data),offset=this.bytesRead;this.bytesRead+=buffer.length,this._unrefTimer(),this.ondata&&(console.error("socket.ondata = func is non-standard, use socket.on('data', func)"),this.ondata(buffer,offset,this.bytesRead)),this.push(buffer)||chrome.sockets.tcp.setPaused(this.id,!0)},Socket.prototype._onReceiveError=function(resultCode){-100===resultCode?(this.onend&&(console.error("socket.onend = func is non-standard, use socket.on('end', func)"),this.once("end",this.onend)),this.push(null),this.destroy()):0>resultCode&&this.destroy(errnoException(resultCode,"read"))},function(name,callback){Object.defineProperty(Socket.prototype,name,{configurable:!1,enumerable:!0,get:callback})}("bytesWritten",function(){if(this.id)return this._bytesDispatched+this.bufferSize}),Socket.prototype.destroy=function(exception){this._destroy(exception)},Socket.prototype._destroy=function(exception,cb){var fireErrorCallbacks=()=>{cb&&cb(exception),exception&&!this._writableState.errorEmitted&&(process.nextTick(emitErrorNT,this,exception),this._writableState.errorEmitted=!0)};if(this.destroyed)return void fireErrorCallbacks();this._server&&(this._server._connections-=1,this._server._emitCloseIfDrained&&this._server._emitCloseIfDrained()),this._reset();for(var s=this;null!==s;s=s._parent)timers.unenroll(s);this.destroyed=!0,this.id&&(delete sockets[this.id],chrome.sockets.tcp.close(this.id,()=>{this.destroyed&&this.emit("close",!!exception)}),this.id=null),fireErrorCallbacks()},Socket.prototype.destroySoon=function(){this.writable&&this.end(),this._writableState.finished&&this.destroy()},Socket.prototype.setTimeout=function(timeout,callback){return 0===timeout?(timers.unenroll(this),callback&&this.removeListener("timeout",callback)):(timers.enroll(this,timeout),timers._unrefActive(this),callback&&this.once("timeout",callback)),this},Socket.prototype._onTimeout=function(){this.emit("timeout")},Socket.prototype._unrefTimer=function(){for(var s=this;null!==s;s=s._parent)timers._unrefActive(s)},Socket.prototype.setNoDelay=function(noDelay,callback){return this.id?(noDelay=void 0===noDelay||!!noDelay,chrome.sockets.tcp.setNoDelay(this.id,noDelay,chromeCallbackWrap(callback)),this):(this.once("connect",()=>this.setNoDelay(noDelay,callback)),this)},Socket.prototype.setKeepAlive=function(enable,initialDelay,callback){return this.id?(chrome.sockets.tcp.setKeepAlive(this.id,!!enable,~~(initialDelay/1e3),chromeCallbackWrap(callback)),this):(this.once("connect",()=>this.setKeepAlive(enable,initialDelay,callback)),this)},Socket.prototype.address=function(){return{address:this.localAddress,port:this.localPort,family:this.localAddress&&-1!==this.localAddress.indexOf(":")?"IPv6":"IPv4"}},Object.defineProperty(Socket.prototype,"_connecting",{get:function(){return this.connecting}}),Object.defineProperty(Socket.prototype,"readyState",{get:function(){return this.connecting?"opening":this.readable&&this.writable?"open":"closed"}}),Socket.prototype.unref=Socket.prototype.ref=function(){return this};var IPv4Regex=/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/,IPv6Regex=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]).){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]).){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/;exports.isIPv4=IPv4Regex.test.bind(IPv4Regex),exports.isIPv6=IPv6Regex.test.bind(IPv6Regex),exports.isIP=function(ip){return exports.isIPv4(ip)?4:exports.isIPv6(ip)?6:0};var errorChromeToUv={"-10":"EACCES","-22":"EACCES","-138":"EACCES","-147":"EADDRINUSE","-108":"EADDRNOTAVAIL","-103":"ECONNABORTED","-102":"ECONNREFUSED","-101":"ECONNRESET","-16":"EEXIST","-8":"EFBIG","-109":"EHOSTUNREACH","-4":"EINVAL","-23":"EISCONN","-6":"ENOENT","-13":"ENOMEM","-106":"ENONET","-18":"ENOSPC","-11":"ENOSYS","-15":"ENOTCONN","-105":"ENOTFOUND","-118":"ETIMEDOUT","-100":"EOF"}}).call(this)}).call(this,require("_process"))},{_process:132,buffer:38,events:39,inherits:97,stream:41,timers:185,util:58}],66:[function(require,module){const BlockStream=require("block-stream2"),stream=require("readable-stream");class ChunkStoreWriteStream extends stream.Writable{constructor(store,chunkLength,opts={}){if(super(opts),!store||!store.put||!store.get)throw new Error("First argument must be an abstract-chunk-store compliant store");if(chunkLength=+chunkLength,!chunkLength)throw new Error("Second argument must be a chunk length");this._blockstream=new BlockStream(chunkLength,{zeroPadding:!1}),this._outstandingPuts=0;let index=0;const onData=chunk=>{this.destroyed||(this._outstandingPuts+=1,store.put(index,chunk,()=>{this._outstandingPuts-=1,0===this._outstandingPuts&&"function"==typeof this._finalCb&&(this._finalCb(null),this._finalCb=null)}),index+=1)};this._blockstream.on("data",onData).on("error",err=>{this.destroy(err)})}_write(chunk,encoding,callback){this._blockstream.write(chunk,encoding,callback)}_final(cb){this._blockstream.end(),this._blockstream.once("end",()=>{0===this._outstandingPuts?cb(null):this._finalCb=cb})}destroy(err){this.destroyed||(this.destroyed=!0,err&&this.emit("error",err),this.emit("close"))}}module.exports=ChunkStoreWriteStream},{"block-stream2":34,"readable-stream":157}],67:[function(require,module){var ipaddr=require("ipaddr.js"),compact2string=function(buf){switch(buf.length){case 6:return buf[0]+"."+buf[1]+"."+buf[2]+"."+buf[3]+":"+buf.readUInt16BE(4);break;case 18:for(var hexGroups=[],i=0;8>i;i++)hexGroups.push(buf.readUInt16BE(2*i).toString(16));var host=ipaddr.parse(hexGroups.join(":")).toString();return"["+host+"]:"+buf.readUInt16BE(16);default:throw new Error("Invalid Compact IP/PORT, It should contain 6 or 18 bytes");}};compact2string.multi=function(buf){if(0!=buf.length%6)throw new Error("buf length isn't multiple of compact IP/PORTs (6 bytes)");for(var output=[],i=0;i<=buf.length-1;i+=6)output.push(compact2string(buf.slice(i,i+6)));return output},compact2string.multi6=function(buf){if(0!=buf.length%18)throw new Error("buf length isn't multiple of compact IP6/PORTs (18 bytes)");for(var output=[],i=0;i<=buf.length-1;i+=18)output.push(compact2string(buf.slice(i,i+18)));return output},module.exports=compact2string},{"ipaddr.js":98}],68:[function(require,module){(function(process,global,Buffer){(function(){function flat(arr1){return arr1.reduce((acc,val)=>Array.isArray(val)?acc.concat(flat(val)):acc.concat(val),[])}function _parseInput(input,opts,cb){function processInput(){parallel(input.map(item=>cb=>{const file={};if(isBlob(item))file.getStream=getBlobStream(item),file.length=item.size;else if(Buffer.isBuffer(item))file.getStream=getBufferStream(item),file.length=item.length;else if(isReadable(item))file.getStream=getStreamStream(item,file),file.length=0;else{if("string"==typeof item){if("function"!=typeof getFiles)throw new Error("filesystem paths do not work in the browser");const keepRoot=1err?cb(err):void(files=flat(files),cb(null,files,isSingleFileTorrent)))}if(isFileList(input)&&(input=Array.from(input)),Array.isArray(input)||(input=[input]),0===input.length)throw new Error("invalid input type");input.forEach(item=>{if(null==item)throw new Error(`invalid input type: ${item}`)}),input=input.map(item=>isBlob(item)&&"string"==typeof item.path&&"function"==typeof getFiles?item.path:item),1!==input.length||"string"==typeof input[0]||input[0].name||(input[0].name=opts.name);let commonPrefix=null;input.forEach((item,i)=>{if("string"==typeof item)return;let path=item.fullPath||item.name;path||(path=`Unknown File ${i+1}`,item.unknownName=!0),item.path=path.split("/"),item.path[0]||item.path.shift(),2>item.path.length?commonPrefix=null:0===i&&1{if("string"==typeof item)return!0;const filename=item.path[item.path.length-1];return notHidden(filename)&&junk.not(filename)}),commonPrefix&&input.forEach(item=>{const pathless=(Buffer.isBuffer(item)||isReadable(item))&&!item.path;"string"==typeof item||pathless||item.path.shift()}),!opts.name&&commonPrefix&&(opts.name=commonPrefix),opts.name||input.some(item=>"string"==typeof item?(opts.name=corePath.basename(item),!0):item.unknownName?void 0:(opts.name=item.path[item.path.length-1],!0)),opts.name||(opts.name=`Unnamed Torrent ${Date.now()}`);const numPaths=input.reduce((sum,item)=>sum+ +("string"==typeof item),0);let isSingleFileTorrent=1===input.length;if(1===input.length&&"string"==typeof input[0]){if("function"!=typeof getFiles)throw new Error("filesystem paths do not work in the browser");isFile(input[0],(err,pathIsFile)=>err?cb(err):void(isSingleFileTorrent=pathIsFile,processInput()))}else process.nextTick(()=>{processInput()})}function notHidden(file){return"."!==file[0]}function getPieceList(files,pieceLength,cb){function onData(chunk){length+=chunk.length;const i=pieceNum;sha1(chunk,hash=>{pieces[i]=hash,remainingHashes-=1,maybeDone()}),remainingHashes+=1,pieceNum+=1}function onEnd(){ended=!0,maybeDone()}function onError(err){cleanup(),cb(err)}function cleanup(){multistream.removeListener("error",onError),blockstream.removeListener("data",onData),blockstream.removeListener("end",onEnd),blockstream.removeListener("error",onError)}function maybeDone(){ended&&0===remainingHashes&&(cleanup(),cb(null,Buffer.from(pieces.join(""),"hex"),length))}cb=once(cb);const pieces=[];let length=0;const streams=files.map(file=>file.getStream);let remainingHashes=0,pieceNum=0,ended=!1;const multistream=new MultiStream(streams),blockstream=new BlockStream(pieceLength,{zeroPadding:!1});multistream.on("error",onError),multistream.pipe(blockstream).on("data",onData).on("end",onEnd).on("error",onError)}function onFiles(files,opts,cb){let announceList=opts.announceList;announceList||("string"==typeof opts.announce?announceList=[[opts.announce]]:Array.isArray(opts.announce)&&(announceList=opts.announce.map(u=>[u]))),announceList||(announceList=[]),global.WEBTORRENT_ANNOUNCE&&("string"==typeof global.WEBTORRENT_ANNOUNCE?announceList.push([[global.WEBTORRENT_ANNOUNCE]]):Array.isArray(global.WEBTORRENT_ANNOUNCE)&&(announceList=announceList.concat(global.WEBTORRENT_ANNOUNCE.map(u=>[u])))),opts.announce===void 0&&opts.announceList===void 0&&(announceList=announceList.concat(module.exports.announceList)),"string"==typeof opts.urlList&&(opts.urlList=[opts.urlList]);const torrent={info:{name:opts.name},"creation date":_Mathceil((+opts.creationDate||Date.now())/1e3),encoding:"UTF-8"};0!==announceList.length&&(torrent.announce=announceList[0][0],torrent["announce-list"]=announceList),opts.comment!==void 0&&(torrent.comment=opts.comment),opts.createdBy!==void 0&&(torrent["created by"]=opts.createdBy),opts.private!==void 0&&(torrent.info.private=+opts.private),opts.info!==void 0&&Object.assign(torrent.info,opts.info),opts.sslCert!==void 0&&(torrent.info["ssl-cert"]=opts.sslCert),opts.urlList!==void 0&&(torrent["url-list"]=opts.urlList);const pieceLength=opts.pieceLength||calcPieceLength(files.reduce(sumLength,0));torrent.info["piece length"]=pieceLength,getPieceList(files,pieceLength,(err,pieces,torrentLength)=>err?cb(err):void(torrent.info.pieces=pieces,files.forEach(file=>{delete file.getStream}),opts.singleFileTorrent?torrent.info.length=torrentLength:torrent.info.files=files,cb(null,bencode.encode(torrent))))}function sumLength(sum,file){return sum+file.length}function isBlob(obj){return"undefined"!=typeof Blob&&obj instanceof Blob}function isFileList(obj){return"undefined"!=typeof FileList&&obj instanceof FileList}function isReadable(obj){return"object"==typeof obj&&null!=obj&&"function"==typeof obj.pipe}function getBlobStream(file){return()=>new FileReadStream(file)}function getBufferStream(buffer){return()=>{const s=new stream.PassThrough;return s.end(buffer),s}}function getStreamStream(readable,file){return()=>{const counter=new stream.Transform;return counter._transform=function(buf,enc,done){file.length+=buf.length,this.push(buf),done()},readable.pipe(counter),counter}}/*! create-torrent. MIT License. WebTorrent LLC */const bencode=require("bencode"),BlockStream=require("block-stream2"),calcPieceLength=require("piece-length"),corePath=require("path"),FileReadStream=require("filestream/read"),isFile=require("is-file"),junk=require("junk"),MultiStream=require("multistream"),once=require("once"),parallel=require("run-parallel"),sha1=require("simple-sha1"),stream=require("readable-stream"),getFiles=require("./get-files");module.exports=function(input,opts,cb){"function"==typeof opts&&([opts,cb]=[cb,opts]),opts=opts?Object.assign({},opts):{},_parseInput(input,opts,(err,files,singleFileTorrent)=>err?cb(err):void(opts.singleFileTorrent=singleFileTorrent,onFiles(files,opts,cb)))},module.exports.parseInput=function(input,opts,cb){"function"==typeof opts&&([opts,cb]=[cb,opts]),opts=opts?Object.assign({},opts):{},_parseInput(input,opts,cb)},module.exports.announceList=[["udp://tracker.leechers-paradise.org:6969"],["udp://tracker.coppersurfer.tk:6969"],["udp://tracker.opentrackr.org:1337"],["udp://explodie.org:6969"],["udp://tracker.empire-js.us:1337"],["wss://tracker.btorrent.xyz"],["wss://tracker.openwebtorrent.com"]]}).call(this)}).call(this,require("_process"),"undefined"==typeof global?"undefined"==typeof self?"undefined"==typeof window?{}:window:self:global,require("buffer").Buffer)},{"./get-files":36,_process:132,bencode:19,"block-stream2":34,buffer:38,"filestream/read":78,"is-file":102,junk:106,multistream:126,once:129,path:40,"piece-length":131,"readable-stream":157,"run-parallel":162,"simple-sha1":169}],69:[function(require,module,exports){(function(process){(function(){function load(){let r;try{r=exports.storage.getItem("debug")}catch(error){}return!r&&"undefined"!=typeof process&&"env"in process&&(r=process.env.DEBUG),r}exports.formatArgs=function(args){if(args[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+args[0]+(this.useColors?"%c ":" ")+"+"+module.exports.humanize(this.diff),!this.useColors)return;const c="color: "+this.color;args.splice(1,0,c,"color: inherit");let index=0,lastC=0;args[0].replace(/%[a-zA-Z%]/g,match=>{"%%"===match||(index++,"%c"===match&&(lastC=index))}),args.splice(lastC,0,c)},exports.save=function(namespaces){try{namespaces?exports.storage.setItem("debug",namespaces):exports.storage.removeItem("debug")}catch(error){}},exports.load=load,exports.useColors=function(){return!!("undefined"!=typeof window&&window.process&&("renderer"===window.process.type||window.process.__nwjs))||!("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))&&("undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&31<=parseInt(RegExp.$1,10)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/))},exports.storage=function(){try{return localStorage}catch(error){}}(),exports.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],exports.log=console.debug||console.log||(()=>{}),module.exports=require("./common")(exports);const{formatters}=module.exports;formatters.j=function(v){try{return JSON.stringify(v)}catch(error){return"[UnexpectedJSONParseError]: "+error.message}}}).call(this)}).call(this,require("_process"))},{"./common":70,_process:132}],70:[function(require,module){module.exports=function(env){function createDebug(namespace){function debug(...args){if(!debug.enabled)return;const self=debug,curr=+new Date,ms=curr-(prevTime||curr);self.diff=ms,self.prev=prevTime,self.curr=curr,prevTime=curr,args[0]=createDebug.coerce(args[0]),"string"!=typeof args[0]&&args.unshift("%O");let index=0;args[0]=args[0].replace(/%([a-zA-Z%])/g,(match,format)=>{if("%%"===match)return match;index++;const formatter=createDebug.formatters[format];if("function"==typeof formatter){const val=args[index];match=formatter.call(self,val),args.splice(index,1),index--}return match}),createDebug.formatArgs.call(self,args);const logFn=self.log||createDebug.log;logFn.apply(self,args)}let prevTime;return debug.namespace=namespace,debug.enabled=createDebug.enabled(namespace),debug.useColors=createDebug.useColors(),debug.color=createDebug.selectColor(namespace),debug.destroy=destroy,debug.extend=extend,"function"==typeof createDebug.init&&createDebug.init(debug),createDebug.instances.push(debug),debug}function destroy(){const index=createDebug.instances.indexOf(this);return-1!==index&&(createDebug.instances.splice(index,1),!0)}function extend(namespace,delimiter){const newDebug=createDebug(this.namespace+("undefined"==typeof delimiter?":":delimiter)+namespace);return newDebug.log=this.log,newDebug}function toNamespace(regexp){return regexp.toString().substring(2,regexp.toString().length-2).replace(/\.\*\?$/,"*")}return createDebug.debug=createDebug,createDebug.default=createDebug,createDebug.coerce=function(val){return val instanceof Error?val.stack||val.message:val},createDebug.disable=function(){const namespaces=[...createDebug.names.map(toNamespace),...createDebug.skips.map(toNamespace).map(namespace=>"-"+namespace)].join(",");return createDebug.enable(""),namespaces},createDebug.enable=function(namespaces){createDebug.save(namespaces),createDebug.names=[],createDebug.skips=[];let i;const split=("string"==typeof namespaces?namespaces:"").split(/[\s,]+/),len=split.length;for(i=0;i{createDebug[key]=env[key]}),createDebug.instances=[],createDebug.names=[],createDebug.skips=[],createDebug.formatters={},createDebug.selectColor=function(namespace){let hash=0;for(let i=0;i=parts.length){var desc=$gOPD(value,parts[i]);if(!allowMissing&&!(parts[i]in value))throw new $TypeError("base intrinsic for "+name+" exists, but the property is not available.");value=desc&&"get"in desc&&!("originalValue"in desc.get)?desc.get:value[parts[i]]}else value=value[parts[i]];return value}},{"function-bind":82,"has-symbols":84}],74:[function(require,module){'use strict';var bind=require("function-bind"),GetIntrinsic=require("../GetIntrinsic"),$apply=GetIntrinsic("%Function.prototype.apply%"),$call=GetIntrinsic("%Function.prototype.call%"),$reflectApply=GetIntrinsic("%Reflect.apply%",!0)||bind.call($call,$apply),$defineProperty=GetIntrinsic("%Object.defineProperty%",!0);if($defineProperty)try{$defineProperty({},"a",{value:1})}catch(e){$defineProperty=null}module.exports=function(){return $reflectApply(bind,$call,arguments)};var applyBind=function(){return $reflectApply(bind,$apply,arguments)};$defineProperty?$defineProperty(module.exports,"apply",{value:applyBind}):module.exports.apply=applyBind},{"../GetIntrinsic":73,"function-bind":82}],75:[function(require,module){'use strict';var GetIntrinsic=require("../GetIntrinsic"),callBind=require("./callBind"),$indexOf=callBind(GetIntrinsic("String.prototype.indexOf"));module.exports=function(name,allowMissing){var intrinsic=GetIntrinsic(name,!!allowMissing);return"function"==typeof intrinsic&&$indexOf(name,".prototype.")?callBind(intrinsic):intrinsic}},{"../GetIntrinsic":73,"./callBind":74}],76:[function(require,module){'use strict';var GetIntrinsic=require("../GetIntrinsic"),$gOPD=GetIntrinsic("%Object.getOwnPropertyDescriptor%");if($gOPD)try{$gOPD([],"length")}catch(e){$gOPD=null}module.exports=$gOPD},{"../GetIntrinsic":73}],77:[function(require,module){/*! + */'use strict';function createBuffer(length){if(2147483647size)throw new RangeError("The value \""+size+"\" is invalid for option \"size\"")}function alloc(size,fill,encoding){return assertSize(size),0>=size?createBuffer(size):void 0===fill?createBuffer(size):"string"==typeof encoding?createBuffer(size).fill(fill,encoding):createBuffer(size).fill(fill)}function allocUnsafe(size){return assertSize(size),createBuffer(0>size?0:0|checked(size))}function fromString(string,encoding){if(("string"!=typeof encoding||""===encoding)&&(encoding="utf8"),!Buffer.isEncoding(encoding))throw new TypeError("Unknown encoding: "+encoding);var length=0|byteLength(string,encoding),buf=createBuffer(length),actual=buf.write(string,encoding);return actual!==length&&(buf=buf.slice(0,actual)),buf}function fromArrayLike(array){for(var length=0>array.length?0:0|checked(array.length),buf=createBuffer(length),i=0;ibyteOffset||array.byteLength=2147483647)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+2147483647 .toString(16)+" bytes");return 0|length}function byteLength(string,encoding){if(Buffer.isBuffer(string))return string.length;if(ArrayBuffer.isView(string)||isInstance(string,ArrayBuffer))return string.byteLength;if("string"!=typeof string)throw new TypeError("The \"string\" argument must be one of type string, Buffer, or ArrayBuffer. Received type "+typeof string);var len=string.length,mustMatch=2>>1;case"base64":return base64ToBytes(string).length;default:if(loweredCase)return mustMatch?-1:utf8ToBytes(string).length;encoding=(""+encoding).toLowerCase(),loweredCase=!0;}}function slowToString(encoding,start,end){var loweredCase=!1;if((void 0===start||0>start)&&(start=0),start>this.length)return"";if((void 0===end||end>this.length)&&(end=this.length),0>=end)return"";if(end>>>=0,start>>>=0,end<=start)return"";for(encoding||(encoding="utf8");;)switch(encoding){case"hex":return hexSlice(this,start,end);case"utf8":case"utf-8":return utf8Slice(this,start,end);case"ascii":return asciiSlice(this,start,end);case"latin1":case"binary":return latin1Slice(this,start,end);case"base64":return base64Slice(this,start,end);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return utf16leSlice(this,start,end);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(encoding+"").toLowerCase(),loweredCase=!0;}}function swap(b,n,m){var i=b[n];b[n]=b[m],b[m]=i}function bidirectionalIndexOf(buffer,val,byteOffset,encoding,dir){if(0===buffer.length)return-1;if("string"==typeof byteOffset?(encoding=byteOffset,byteOffset=0):2147483647byteOffset&&(byteOffset=-2147483648),byteOffset=+byteOffset,numberIsNaN(byteOffset)&&(byteOffset=dir?0:buffer.length-1),0>byteOffset&&(byteOffset=buffer.length+byteOffset),byteOffset>=buffer.length){if(dir)return-1;byteOffset=buffer.length-1}else if(0>byteOffset)if(dir)byteOffset=0;else return-1;if("string"==typeof val&&(val=Buffer.from(val,encoding)),Buffer.isBuffer(val))return 0===val.length?-1:arrayIndexOf(buffer,val,byteOffset,encoding,dir);if("number"==typeof val)return val&=255,"function"==typeof Uint8Array.prototype.indexOf?dir?Uint8Array.prototype.indexOf.call(buffer,val,byteOffset):Uint8Array.prototype.lastIndexOf.call(buffer,val,byteOffset):arrayIndexOf(buffer,[val],byteOffset,encoding,dir);throw new TypeError("val must be string, number or Buffer")}function arrayIndexOf(arr,val,byteOffset,encoding,dir){function read(buf,i){return 1===indexSize?buf[i]:buf.readUInt16BE(i*indexSize)}var indexSize=1,arrLength=arr.length,valLength=val.length;if(void 0!==encoding&&(encoding=(encoding+"").toLowerCase(),"ucs2"===encoding||"ucs-2"===encoding||"utf16le"===encoding||"utf-16le"===encoding)){if(2>arr.length||2>val.length)return-1;indexSize=2,arrLength/=2,valLength/=2,byteOffset/=2}var i;if(dir){var foundIndex=-1;for(i=byteOffset;iarrLength&&(byteOffset=arrLength-valLength),i=byteOffset;0<=i;i--){for(var found=!0,j=0;jremaining&&(length=remaining)):length=remaining;var strLen=string.length;length>strLen/2&&(length=strLen/2);for(var i=0,parsed;ifirstByte&&(codePoint=firstByte):2===bytesPerSequence?(secondByte=buf[i+1],128==(192&secondByte)&&(tempCodePoint=(31&firstByte)<<6|63&secondByte,127tempCodePoint||57343tempCodePoint&&(codePoint=tempCodePoint))):void 0}null===codePoint?(codePoint=65533,bytesPerSequence=1):65535>>10),codePoint=56320|1023&codePoint),res.push(codePoint),i+=bytesPerSequence}return decodeCodePointsArray(res)}function decodeCodePointsArray(codePoints){var len=codePoints.length;if(len<=4096)return _StringfromCharCode.apply(String,codePoints);for(var res="",i=0;istart)&&(start=0),(!end||0>end||end>len)&&(end=len);for(var out="",i=start;ioffset)throw new RangeError("offset is not uint");if(offset+ext>length)throw new RangeError("Trying to access beyond buffer length")}function checkInt(buf,value,offset,ext,max,min){if(!Buffer.isBuffer(buf))throw new TypeError("\"buffer\" argument must be a Buffer instance");if(value>max||valuebuf.length)throw new RangeError("Index out of range")}function checkIEEE754(buf,value,offset,ext){if(offset+ext>buf.length)throw new RangeError("Index out of range");if(0>offset)throw new RangeError("Index out of range")}function writeFloat(buf,value,offset,littleEndian,noAssert){return value=+value,offset>>>=0,noAssert||checkIEEE754(buf,value,offset,4,34028234663852886e22,-34028234663852886e22),ieee754.write(buf,value,offset,littleEndian,23,4),offset+4}function writeDouble(buf,value,offset,littleEndian,noAssert){return value=+value,offset>>>=0,noAssert||checkIEEE754(buf,value,offset,8,17976931348623157e292,-17976931348623157e292),ieee754.write(buf,value,offset,littleEndian,52,8),offset+8}function base64clean(str){if(str=str.split("=")[0],str=str.trim().replace(INVALID_BASE64_RE,""),2>str.length)return"";for(;0!=str.length%4;)str+="=";return str}function toHex(n){return 16>n?"0"+n.toString(16):n.toString(16)}function utf8ToBytes(string,units){units=units||1/0;for(var length=string.length,leadSurrogate=null,bytes=[],i=0,codePoint;icodePoint){if(!leadSurrogate){if(56319codePoint){-1<(units-=3)&&bytes.push(239,191,189),leadSurrogate=codePoint;continue}codePoint=(leadSurrogate-55296<<10|codePoint-56320)+65536}else leadSurrogate&&-1<(units-=3)&&bytes.push(239,191,189);if(leadSurrogate=null,128>codePoint){if(0>(units-=1))break;bytes.push(codePoint)}else if(2048>codePoint){if(0>(units-=2))break;bytes.push(192|codePoint>>6,128|63&codePoint)}else if(65536>codePoint){if(0>(units-=3))break;bytes.push(224|codePoint>>12,128|63&codePoint>>6,128|63&codePoint)}else if(1114112>codePoint){if(0>(units-=4))break;bytes.push(240|codePoint>>18,128|63&codePoint>>12,128|63&codePoint>>6,128|63&codePoint)}else throw new Error("Invalid code point")}return bytes}function asciiToBytes(str){for(var byteArray=[],i=0;i(units-=2));++i)c=str.charCodeAt(i),hi=c>>8,lo=c%256,byteArray.push(lo),byteArray.push(hi);return byteArray}function base64ToBytes(str){return base64.toByteArray(base64clean(str))}function blitBuffer(src,dst,offset,length){for(var i=0;i=dst.length||i>=src.length);++i)dst[i+offset]=src[i];return i}function isInstance(obj,type){return obj instanceof type||null!=obj&&null!=obj.constructor&&null!=obj.constructor.name&&obj.constructor.name===type.name}function numberIsNaN(obj){return obj!==obj}var base64=require("base64-js"),ieee754=require("ieee754");exports.Buffer=Buffer,exports.SlowBuffer=function(length){return+length!=length&&(length=0),Buffer.alloc(+length)},exports.INSPECT_MAX_BYTES=50;exports.kMaxLength=2147483647,Buffer.TYPED_ARRAY_SUPPORT=function(){try{var arr=new Uint8Array(1);return arr.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===arr.foo()}catch(e){return!1}}(),Buffer.TYPED_ARRAY_SUPPORT||"undefined"==typeof console||"function"!=typeof console.error||console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."),Object.defineProperty(Buffer.prototype,"parent",{enumerable:!0,get:function(){return Buffer.isBuffer(this)?this.buffer:void 0}}),Object.defineProperty(Buffer.prototype,"offset",{enumerable:!0,get:function(){return Buffer.isBuffer(this)?this.byteOffset:void 0}}),"undefined"!=typeof Symbol&&null!=Symbol.species&&Buffer[Symbol.species]===Buffer&&Object.defineProperty(Buffer,Symbol.species,{value:null,configurable:!0,enumerable:!1,writable:!1}),Buffer.poolSize=8192,Buffer.from=function(value,encodingOrOffset,length){return from(value,encodingOrOffset,length)},Buffer.prototype.__proto__=Uint8Array.prototype,Buffer.__proto__=Uint8Array,Buffer.alloc=function(size,fill,encoding){return alloc(size,fill,encoding)},Buffer.allocUnsafe=function(size){return allocUnsafe(size)},Buffer.allocUnsafeSlow=function(size){return allocUnsafe(size)},Buffer.isBuffer=function(b){return null!=b&&!0===b._isBuffer&&b!==Buffer.prototype},Buffer.compare=function(a,b){if(isInstance(a,Uint8Array)&&(a=Buffer.from(a,a.offset,a.byteLength)),isInstance(b,Uint8Array)&&(b=Buffer.from(b,b.offset,b.byteLength)),!Buffer.isBuffer(a)||!Buffer.isBuffer(b))throw new TypeError("The \"buf1\", \"buf2\" arguments must be one of type Buffer or Uint8Array");if(a===b)return 0;for(var x=a.length,y=b.length,i=0,len=_Mathmin(x,y);imax&&(str+=" ... "),""},Buffer.prototype.compare=function(target,start,end,thisStart,thisEnd){if(isInstance(target,Uint8Array)&&(target=Buffer.from(target,target.offset,target.byteLength)),!Buffer.isBuffer(target))throw new TypeError("The \"target\" argument must be one of type Buffer or Uint8Array. Received type "+typeof target);if(void 0===start&&(start=0),void 0===end&&(end=target?target.length:0),void 0===thisStart&&(thisStart=0),void 0===thisEnd&&(thisEnd=this.length),0>start||end>target.length||0>thisStart||thisEnd>this.length)throw new RangeError("out of range index");if(thisStart>=thisEnd&&start>=end)return 0;if(thisStart>=thisEnd)return-1;if(start>=end)return 1;if(start>>>=0,end>>>=0,thisStart>>>=0,thisEnd>>>=0,this===target)return 0;for(var x=thisEnd-thisStart,y=end-start,len=_Mathmin(x,y),thisCopy=this.slice(thisStart,thisEnd),targetCopy=target.slice(start,end),i=0;i>>=0,isFinite(length)?(length>>>=0,void 0===encoding&&(encoding="utf8")):(encoding=length,length=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");var remaining=this.length-offset;if((void 0===length||length>remaining)&&(length=remaining),0length||0>offset)||offset>this.length)throw new RangeError("Attempt to write outside buffer bounds");encoding||(encoding="utf8");for(var loweredCase=!1;;)switch(encoding){case"hex":return hexWrite(this,string,offset,length);case"utf8":case"utf-8":return utf8Write(this,string,offset,length);case"ascii":return asciiWrite(this,string,offset,length);case"latin1":case"binary":return latin1Write(this,string,offset,length);case"base64":return base64Write(this,string,offset,length);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ucs2Write(this,string,offset,length);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(""+encoding).toLowerCase(),loweredCase=!0;}},Buffer.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};Buffer.prototype.slice=function(start,end){var len=this.length;start=~~start,end=end===void 0?len:~~end,0>start?(start+=len,0>start&&(start=0)):start>len&&(start=len),0>end?(end+=len,0>end&&(end=0)):end>len&&(end=len),end>>=0,byteLength>>>=0,noAssert||checkOffset(offset,byteLength,this.length);for(var val=this[offset],mul=1,i=0;++i>>=0,byteLength>>>=0,noAssert||checkOffset(offset,byteLength,this.length);for(var val=this[offset+--byteLength],mul=1;0>>=0,noAssert||checkOffset(offset,1,this.length),this[offset]},Buffer.prototype.readUInt16LE=function(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,2,this.length),this[offset]|this[offset+1]<<8},Buffer.prototype.readUInt16BE=function(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,2,this.length),this[offset]<<8|this[offset+1]},Buffer.prototype.readUInt32LE=function(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,4,this.length),(this[offset]|this[offset+1]<<8|this[offset+2]<<16)+16777216*this[offset+3]},Buffer.prototype.readUInt32BE=function(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,4,this.length),16777216*this[offset]+(this[offset+1]<<16|this[offset+2]<<8|this[offset+3])},Buffer.prototype.readIntLE=function(offset,byteLength,noAssert){offset>>>=0,byteLength>>>=0,noAssert||checkOffset(offset,byteLength,this.length);for(var val=this[offset],mul=1,i=0;++i=mul&&(val-=_Mathpow(2,8*byteLength)),val},Buffer.prototype.readIntBE=function(offset,byteLength,noAssert){offset>>>=0,byteLength>>>=0,noAssert||checkOffset(offset,byteLength,this.length);for(var i=byteLength,mul=1,val=this[offset+--i];0=mul&&(val-=_Mathpow(2,8*byteLength)),val},Buffer.prototype.readInt8=function(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,1,this.length),128&this[offset]?-1*(255-this[offset]+1):this[offset]},Buffer.prototype.readInt16LE=function(offset,noAssert){offset>>>=0,noAssert||checkOffset(offset,2,this.length);var val=this[offset]|this[offset+1]<<8;return 32768&val?4294901760|val:val},Buffer.prototype.readInt16BE=function(offset,noAssert){offset>>>=0,noAssert||checkOffset(offset,2,this.length);var val=this[offset+1]|this[offset]<<8;return 32768&val?4294901760|val:val},Buffer.prototype.readInt32LE=function(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,4,this.length),this[offset]|this[offset+1]<<8|this[offset+2]<<16|this[offset+3]<<24},Buffer.prototype.readInt32BE=function(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,4,this.length),this[offset]<<24|this[offset+1]<<16|this[offset+2]<<8|this[offset+3]},Buffer.prototype.readFloatLE=function(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,4,this.length),ieee754.read(this,offset,!0,23,4)},Buffer.prototype.readFloatBE=function(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,4,this.length),ieee754.read(this,offset,!1,23,4)},Buffer.prototype.readDoubleLE=function(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,8,this.length),ieee754.read(this,offset,!0,52,8)},Buffer.prototype.readDoubleBE=function(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,8,this.length),ieee754.read(this,offset,!1,52,8)},Buffer.prototype.writeUIntLE=function(value,offset,byteLength,noAssert){if(value=+value,offset>>>=0,byteLength>>>=0,!noAssert){var maxBytes=_Mathpow(2,8*byteLength)-1;checkInt(this,value,offset,byteLength,maxBytes,0)}var mul=1,i=0;for(this[offset]=255&value;++i>>=0,byteLength>>>=0,!noAssert){var maxBytes=_Mathpow(2,8*byteLength)-1;checkInt(this,value,offset,byteLength,maxBytes,0)}var i=byteLength-1,mul=1;for(this[offset+i]=255&value;0<=--i&&(mul*=256);)this[offset+i]=255&value/mul;return offset+byteLength},Buffer.prototype.writeUInt8=function(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,1,255,0),this[offset]=255&value,offset+1},Buffer.prototype.writeUInt16LE=function(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,2,65535,0),this[offset]=255&value,this[offset+1]=value>>>8,offset+2},Buffer.prototype.writeUInt16BE=function(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,2,65535,0),this[offset]=value>>>8,this[offset+1]=255&value,offset+2},Buffer.prototype.writeUInt32LE=function(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,4,4294967295,0),this[offset+3]=value>>>24,this[offset+2]=value>>>16,this[offset+1]=value>>>8,this[offset]=255&value,offset+4},Buffer.prototype.writeUInt32BE=function(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,4,4294967295,0),this[offset]=value>>>24,this[offset+1]=value>>>16,this[offset+2]=value>>>8,this[offset+3]=255&value,offset+4},Buffer.prototype.writeIntLE=function(value,offset,byteLength,noAssert){if(value=+value,offset>>>=0,!noAssert){var limit=_Mathpow(2,8*byteLength-1);checkInt(this,value,offset,byteLength,limit-1,-limit)}var i=0,mul=1,sub=0;for(this[offset]=255&value;++ivalue&&0===sub&&0!==this[offset+i-1]&&(sub=1),this[offset+i]=255&(value/mul>>0)-sub;return offset+byteLength},Buffer.prototype.writeIntBE=function(value,offset,byteLength,noAssert){if(value=+value,offset>>>=0,!noAssert){var limit=_Mathpow(2,8*byteLength-1);checkInt(this,value,offset,byteLength,limit-1,-limit)}var i=byteLength-1,mul=1,sub=0;for(this[offset+i]=255&value;0<=--i&&(mul*=256);)0>value&&0===sub&&0!==this[offset+i+1]&&(sub=1),this[offset+i]=255&(value/mul>>0)-sub;return offset+byteLength},Buffer.prototype.writeInt8=function(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,1,127,-128),0>value&&(value=255+value+1),this[offset]=255&value,offset+1},Buffer.prototype.writeInt16LE=function(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,2,32767,-32768),this[offset]=255&value,this[offset+1]=value>>>8,offset+2},Buffer.prototype.writeInt16BE=function(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,2,32767,-32768),this[offset]=value>>>8,this[offset+1]=255&value,offset+2},Buffer.prototype.writeInt32LE=function(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,4,2147483647,-2147483648),this[offset]=255&value,this[offset+1]=value>>>8,this[offset+2]=value>>>16,this[offset+3]=value>>>24,offset+4},Buffer.prototype.writeInt32BE=function(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,4,2147483647,-2147483648),0>value&&(value=4294967295+value+1),this[offset]=value>>>24,this[offset+1]=value>>>16,this[offset+2]=value>>>8,this[offset+3]=255&value,offset+4},Buffer.prototype.writeFloatLE=function(value,offset,noAssert){return writeFloat(this,value,offset,!0,noAssert)},Buffer.prototype.writeFloatBE=function(value,offset,noAssert){return writeFloat(this,value,offset,!1,noAssert)},Buffer.prototype.writeDoubleLE=function(value,offset,noAssert){return writeDouble(this,value,offset,!0,noAssert)},Buffer.prototype.writeDoubleBE=function(value,offset,noAssert){return writeDouble(this,value,offset,!1,noAssert)},Buffer.prototype.copy=function(target,targetStart,start,end){if(!Buffer.isBuffer(target))throw new TypeError("argument should be a Buffer");if(start||(start=0),end||0===end||(end=this.length),targetStart>=target.length&&(targetStart=target.length),targetStart||(targetStart=0),0targetStart)throw new RangeError("targetStart out of bounds");if(0>start||start>=this.length)throw new RangeError("Index out of range");if(0>end)throw new RangeError("sourceEnd out of bounds");end>this.length&&(end=this.length),target.length-targetStartcode||"latin1"===encoding)&&(val=code)}}else"number"==typeof val&&(val&=255);if(0>start||this.length>>=0,end=end===void 0?this.length:end>>>0,val||(val=0);var i;if("number"==typeof val)for(i=start;im&&!existing.warned){existing.warned=!0;var w=new Error("Possible EventEmitter memory leak detected. "+existing.length+" "+(type+" listeners added. Use emitter.setMaxListeners() to increase limit"));w.name="MaxListenersExceededWarning",w.emitter=target,w.type=type,w.count=existing.length,ProcessEmitWarning(w)}return target}function onceWrapper(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function _onceWrap(target,type,listener){var state={fired:!1,wrapFn:void 0,target:target,type:type,listener:listener},wrapped=onceWrapper.bind(state);return wrapped.listener=listener,state.wrapFn=wrapped,wrapped}function _listeners(target,type,unwrap){var events=target._events;if(events===void 0)return[];var evlistener=events[type];return void 0===evlistener?[]:"function"==typeof evlistener?unwrap?[evlistener.listener||evlistener]:[evlistener]:unwrap?unwrapListeners(evlistener):arrayClone(evlistener,evlistener.length)}function listenerCount(type){var events=this._events;if(events!==void 0){var evlistener=events[type];if("function"==typeof evlistener)return 1;if(void 0!==evlistener)return evlistener.length}return 0}function arrayClone(arr,n){for(var copy=Array(n),i=0;iarg||NumberIsNaN(arg))throw new RangeError("The value of \"defaultMaxListeners\" is out of range. It must be a non-negative number. Received "+arg+".");defaultMaxListeners=arg}}),EventEmitter.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},EventEmitter.prototype.setMaxListeners=function(n){if("number"!=typeof n||0>n||NumberIsNaN(n))throw new RangeError("The value of \"n\" is out of range. It must be a non-negative number. Received "+n+".");return this._maxListeners=n,this},EventEmitter.prototype.getMaxListeners=function(){return _getMaxListeners(this)},EventEmitter.prototype.emit=function(type){for(var args=[],i=1;iposition)return this;0===position?list.shift():spliceOne(list,position),1===list.length&&(events[type]=list[0]),void 0!==events.removeListener&&this.emit("removeListener",type,originalListener||listener)}return this},EventEmitter.prototype.off=EventEmitter.prototype.removeListener,EventEmitter.prototype.removeAllListeners=function(type){var listeners,events,i;if(events=this._events,void 0===events)return this;if(void 0===events.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==events[type]&&(0==--this._eventsCount?this._events=Object.create(null):delete events[type]),this;if(0===arguments.length){var keys=Object.keys(events),key;for(i=0;ires.length||2!==lastSegmentLength||46!==res.charCodeAt(res.length-1)||46!==res.charCodeAt(res.length-2))if(2length){if(47===to.charCodeAt(toStart+i))return to.slice(toStart+i+1);if(0===i)return to.slice(toStart+i)}else fromLen>length&&(47===from.charCodeAt(fromStart+i)?lastCommonSep=i:0===i&&(lastCommonSep=0));break}var fromCode=from.charCodeAt(fromStart+i),toCode=to.charCodeAt(toStart+i);if(fromCode!==toCode)break;else 47===fromCode&&(lastCommonSep=i)}var out="";for(i=fromStart+lastCommonSep+1;i<=fromEnd;++i)(i===fromEnd||47===from.charCodeAt(i))&&(out+=0===out.length?"..":"/..");return 0=start;--i){if(code=path.charCodeAt(i),47===code){if(!matchedSlash){startPart=i+1;break}continue}-1===end&&(matchedSlash=!1,end=i+1),46===code?-1===startDot?startDot=i:1!==preDotState&&(preDotState=1):-1!==startDot&&(preDotState=-1)}return-1===startDot||-1===end||0===preDotState||1===preDotState&&startDot===end-1&&startDot===startPart+1?-1!==end&&(0===startPart&&isAbsolute?ret.base=ret.name=path.slice(1,end):ret.base=ret.name=path.slice(startPart,end)):(0===startPart&&isAbsolute?(ret.name=path.slice(1,startDot),ret.base=path.slice(1,end)):(ret.name=path.slice(startPart,startDot),ret.base=path.slice(startPart,end)),ret.ext=path.slice(startDot,end)),0pos?0:+pos,search.length)===search}function endsWith(str,search,this_len){return(void 0===this_len||this_len>str.length)&&(this_len=str.length),str.substring(this_len-search.length,this_len)===search}function includes(str,search,start){return"number"!=typeof start&&(start=0),!(start+search.length>str.length)&&-1!==str.indexOf(search,start)}var codes={};createErrorType("ERR_INVALID_OPT_VALUE",function(name,value){return"The value \""+value+"\" is invalid for option \""+name+"\""},TypeError),createErrorType("ERR_INVALID_ARG_TYPE",function(name,expected,actual){var determiner;"string"==typeof expected&&startsWith(expected,"not ")?(determiner="must not be",expected=expected.replace(/^not /,"")):determiner="must be";var msg;if(endsWith(name," argument"))msg="The ".concat(name," ").concat(determiner," ").concat(oneOf(expected,"type"));else{var type=includes(name,".")?"property":"argument";msg="The \"".concat(name,"\" ").concat(type," ").concat(determiner," ").concat(oneOf(expected,"type"))}return msg+=". Received type ".concat(typeof actual),msg},TypeError),createErrorType("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF"),createErrorType("ERR_METHOD_NOT_IMPLEMENTED",function(name){return"The "+name+" method is not implemented"}),createErrorType("ERR_STREAM_PREMATURE_CLOSE","Premature close"),createErrorType("ERR_STREAM_DESTROYED",function(name){return"Cannot call "+name+" after a stream was destroyed"}),createErrorType("ERR_MULTIPLE_CALLBACK","Callback called multiple times"),createErrorType("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable"),createErrorType("ERR_STREAM_WRITE_AFTER_END","write after end"),createErrorType("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),createErrorType("ERR_UNKNOWN_ENCODING",function(arg){return"Unknown encoding: "+arg},TypeError),createErrorType("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event"),module.exports.codes=codes},{}],43:[function(require,module){(function(process){(function(){'use strict';function Duplex(options){return this instanceof Duplex?void(Readable.call(this,options),Writable.call(this,options),this.allowHalfOpen=!0,options&&(!1===options.readable&&(this.readable=!1),!1===options.writable&&(this.writable=!1),!1===options.allowHalfOpen&&(this.allowHalfOpen=!1,this.once("end",onend)))):new Duplex(options)}function onend(){this._writableState.ended||process.nextTick(onEndNT,this)}function onEndNT(self){self.end()}var objectKeys=Object.keys||function(obj){var keys=[];for(var key in obj)keys.push(key);return keys};module.exports=Duplex;var Readable=require("./_stream_readable"),Writable=require("./_stream_writable");require("inherits")(Duplex,Readable);for(var keys=objectKeys(Writable.prototype),v=0,method;v>>1,n|=n>>>2,n|=n>>>4,n|=n>>>8,n|=n>>>16,n++),n}function howMuchToRead(n,state){return 0>=n||0===state.length&&state.ended?0:state.objectMode?1:n===n?(n>state.highWaterMark&&(state.highWaterMark=computeNewHighWaterMark(n)),n<=state.length?n:state.ended?state.length:(state.needReadable=!0,0)):state.flowing&&state.length?state.buffer.head.data.length:state.length}function onEofChunk(stream,state){if(debug("onEofChunk"),!state.ended){if(state.decoder){var chunk=state.decoder.end();chunk&&chunk.length&&(state.buffer.push(chunk),state.length+=state.objectMode?1:chunk.length)}state.ended=!0,state.sync?emitReadable(stream):(state.needReadable=!1,!state.emittedReadable&&(state.emittedReadable=!0,emitReadable_(stream)))}}function emitReadable(stream){var state=stream._readableState;debug("emitReadable",state.needReadable,state.emittedReadable),state.needReadable=!1,state.emittedReadable||(debug("emitReadable",state.flowing),state.emittedReadable=!0,process.nextTick(emitReadable_,stream))}function emitReadable_(stream){var state=stream._readableState;debug("emitReadable_",state.destroyed,state.length,state.ended),!state.destroyed&&(state.length||state.ended)&&(stream.emit("readable"),state.emittedReadable=!1),state.needReadable=!state.flowing&&!state.ended&&state.length<=state.highWaterMark,flow(stream)}function maybeReadMore(stream,state){state.readingMore||(state.readingMore=!0,process.nextTick(maybeReadMore_,stream,state))}function maybeReadMore_(stream,state){for(;!state.reading&&!state.ended&&(state.length=state.length?(ret=state.decoder?state.buffer.join(""):1===state.buffer.length?state.buffer.first():state.buffer.concat(state.length),state.buffer.clear()):ret=state.buffer.consume(n,state.decoder),ret}function endReadable(stream){var state=stream._readableState;debug("endReadable",state.endEmitted),state.endEmitted||(state.ended=!0,process.nextTick(endReadableNT,state,stream))}function endReadableNT(state,stream){if(debug("endReadableNT",state.endEmitted,state.length),!state.endEmitted&&0===state.length&&(state.endEmitted=!0,stream.readable=!1,stream.emit("end"),state.autoDestroy)){var wState=stream._writableState;(!wState||wState.autoDestroy&&wState.finished)&&stream.destroy()}}function indexOf(xs,x){for(var i=0,l=xs.length;i=state.highWaterMark)||state.ended))return debug("read: emitReadable",state.length,state.ended),0===state.length&&state.ended?endReadable(this):emitReadable(this),null;if(n=howMuchToRead(n,state),0===n&&state.ended)return 0===state.length&&endReadable(this),null;var doRead=state.needReadable;debug("need readable",doRead),(0===state.length||state.length-n>>0),p=this.head,i=0;p;)copyBuffer(p.data,ret,i),i+=p.data.length,p=p.next;return ret}},{key:"consume",value:function(n,hasStrings){var ret;return nstr.length?str.length:n;if(ret+=nb===str.length?str:str.slice(0,n),n-=nb,0===n){nb===str.length?(++c,this.head=p.next?p.next:this.tail=null):(this.head=p,p.data=str.slice(nb));break}++c}return this.length-=c,ret}},{key:"_getBuffer",value:function(n){var ret=Buffer.allocUnsafe(n),p=this.head,c=1;for(p.data.copy(ret),n-=p.data.length;p=p.next;){var buf=p.data,nb=n>buf.length?buf.length:n;if(buf.copy(ret,ret.length-n,0,nb),n-=nb,0===n){nb===buf.length?(++c,this.head=p.next?p.next:this.tail=null):(this.head=p,p.data=buf.slice(nb));break}++c}return this.length-=c,ret}},{key:custom,value:function(_,options){return inspect(this,_objectSpread({},options,{depth:0,customInspect:!1}))}}]),BufferList}()},{buffer:38,util:36}],50:[function(require,module){(function(process){(function(){'use strict';function emitErrorAndCloseNT(self,err){emitErrorNT(self,err),emitCloseNT(self)}function emitCloseNT(self){self._writableState&&!self._writableState.emitClose||self._readableState&&!self._readableState.emitClose||self.emit("close")}function emitErrorNT(self,err){self.emit("error",err)}module.exports={destroy:function(err,cb){var _this=this,readableDestroyed=this._readableState&&this._readableState.destroyed,writableDestroyed=this._writableState&&this._writableState.destroyed;return readableDestroyed||writableDestroyed?(cb?cb(err):err&&(this._writableState?!this._writableState.errorEmitted&&(this._writableState.errorEmitted=!0,process.nextTick(emitErrorNT,this,err)):process.nextTick(emitErrorNT,this,err)),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(err||null,function(err){!cb&&err?_this._writableState?_this._writableState.errorEmitted?process.nextTick(emitCloseNT,_this):(_this._writableState.errorEmitted=!0,process.nextTick(emitErrorAndCloseNT,_this,err)):process.nextTick(emitErrorAndCloseNT,_this,err):cb?(process.nextTick(emitCloseNT,_this),cb(err)):process.nextTick(emitCloseNT,_this)}),this)},undestroy:function(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finalCalled=!1,this._writableState.prefinished=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)},errorOrDestroy:function(stream,err){var rState=stream._readableState,wState=stream._writableState;rState&&rState.autoDestroy||wState&&wState.autoDestroy?stream.destroy(err):stream.emit("error",err)}}}).call(this)}).call(this,require("_process"))},{_process:132}],51:[function(require,module){'use strict';function once(callback){var called=!1;return function(){if(!called){called=!0;for(var _len=arguments.length,args=Array(_len),_key=0;_key<_len;_key++)args[_key]=arguments[_key];callback.apply(this,args)}}}function noop(){}function isRequest(stream){return stream.setHeader&&"function"==typeof stream.abort}function eos(stream,opts,callback){if("function"==typeof opts)return eos(stream,null,opts);opts||(opts={}),callback=once(callback||noop);var readable=opts.readable||!1!==opts.readable&&stream.readable,writable=opts.writable||!1!==opts.writable&&stream.writable,onlegacyfinish=function(){stream.writable||onfinish()},writableEnded=stream._writableState&&stream._writableState.finished,onfinish=function(){writable=!1,writableEnded=!0,readable||callback.call(stream)},readableEnded=stream._readableState&&stream._readableState.endEmitted,onend=function(){readable=!1,readableEnded=!0,writable||callback.call(stream)},onerror=function(err){callback.call(stream,err)},onclose=function(){var err;return readable&&!readableEnded?(stream._readableState&&stream._readableState.ended||(err=new ERR_STREAM_PREMATURE_CLOSE),callback.call(stream,err)):writable&&!writableEnded?(stream._writableState&&stream._writableState.ended||(err=new ERR_STREAM_PREMATURE_CLOSE),callback.call(stream,err)):void 0},onrequest=function(){stream.req.on("finish",onfinish)};return isRequest(stream)?(stream.on("complete",onfinish),stream.on("abort",onclose),stream.req?onrequest():stream.on("request",onrequest)):writable&&!stream._writableState&&(stream.on("end",onlegacyfinish),stream.on("close",onlegacyfinish)),stream.on("end",onend),stream.on("finish",onfinish),!1!==opts.error&&stream.on("error",onerror),stream.on("close",onclose),function(){stream.removeListener("complete",onfinish),stream.removeListener("abort",onclose),stream.removeListener("request",onrequest),stream.req&&stream.req.removeListener("finish",onfinish),stream.removeListener("end",onlegacyfinish),stream.removeListener("close",onlegacyfinish),stream.removeListener("finish",onfinish),stream.removeListener("end",onend),stream.removeListener("error",onerror),stream.removeListener("close",onclose)}}var ERR_STREAM_PREMATURE_CLOSE=require("../../../errors").codes.ERR_STREAM_PREMATURE_CLOSE;module.exports=eos},{"../../../errors":42}],52:[function(require,module){module.exports=function(){throw new Error("Readable.from is not available in the browser")}},{}],53:[function(require,module){'use strict';function once(callback){var called=!1;return function(){called||(called=!0,callback.apply(void 0,arguments))}}function noop(err){if(err)throw err}function isRequest(stream){return stream.setHeader&&"function"==typeof stream.abort}function destroyer(stream,reading,writing,callback){callback=once(callback);var closed=!1;stream.on("close",function(){closed=!0}),eos===void 0&&(eos=require("./end-of-stream")),eos(stream,{readable:reading,writable:writing},function(err){return err?callback(err):void(closed=!0,callback())});var destroyed=!1;return function(err){if(!closed)return destroyed?void 0:(destroyed=!0,isRequest(stream)?stream.abort():"function"==typeof stream.destroy?stream.destroy():void callback(err||new ERR_STREAM_DESTROYED("pipe")))}}function call(fn){fn()}function pipe(from,to){return from.pipe(to)}function popCallback(streams){return streams.length?"function"==typeof streams[streams.length-1]?streams.pop():noop:noop}var _require$codes=require("../../../errors").codes,ERR_MISSING_ARGS=_require$codes.ERR_MISSING_ARGS,ERR_STREAM_DESTROYED=_require$codes.ERR_STREAM_DESTROYED,eos;module.exports=function(){for(var _len=arguments.length,streams=Array(_len),_key=0;_key<_len;_key++)streams[_key]=arguments[_key];var callback=popCallback(streams);if(Array.isArray(streams[0])&&(streams=streams[0]),2>streams.length)throw new ERR_MISSING_ARGS("streams");var destroys=streams.map(function(stream,i){var reading=ihwm){var name=isDuplex?duplexKey:"highWaterMark";throw new ERR_INVALID_OPT_VALUE(name,hwm)}return _Mathfloor(hwm)}return state.objectMode?16:16384}}},{"../../../errors":42}],55:[function(require,module){module.exports=require("events").EventEmitter},{events:39}],56:[function(require,module,exports){arguments[4][13][0].apply(exports,arguments)},{dup:13}],57:[function(require,module,exports){'use strict';function uncurryThis(f){return f.call.bind(f)}function checkBoxedPrimitive(value,prototypeValueOf){if("object"!=typeof value)return!1;try{return prototypeValueOf(value),!0}catch(e){return!1}}function isMapToString(value){return"[object Map]"===ObjectToString(value)}function isSetToString(value){return"[object Set]"===ObjectToString(value)}function isWeakMapToString(value){return"[object WeakMap]"===ObjectToString(value)}function isWeakSetToString(value){return"[object WeakSet]"===ObjectToString(value)}function isArrayBufferToString(value){return"[object ArrayBuffer]"===ObjectToString(value)}function isArrayBuffer(value){return"undefined"!=typeof ArrayBuffer&&(isArrayBufferToString.working?isArrayBufferToString(value):value instanceof ArrayBuffer)}function isDataViewToString(value){return"[object DataView]"===ObjectToString(value)}function isDataView(value){return"undefined"!=typeof DataView&&(isDataViewToString.working?isDataViewToString(value):value instanceof DataView)}function isSharedArrayBufferToString(value){return"[object SharedArrayBuffer]"===ObjectToString(value)}function isSharedArrayBuffer(value){return"undefined"!=typeof SharedArrayBuffer&&(isSharedArrayBufferToString.working?isSharedArrayBufferToString(value):value instanceof SharedArrayBuffer)}function isNumberObject(value){return checkBoxedPrimitive(value,numberValue)}function isStringObject(value){return checkBoxedPrimitive(value,stringValue)}function isBooleanObject(value){return checkBoxedPrimitive(value,booleanValue)}function isBigIntObject(value){return BigIntSupported&&checkBoxedPrimitive(value,bigIntValue)}function isSymbolObject(value){return SymbolSupported&&checkBoxedPrimitive(value,symbolValue)}var isArgumentsObject=require("is-arguments"),isGeneratorFunction=require("is-generator-function"),whichTypedArray=require("which-typed-array"),isTypedArray=require("is-typed-array"),BigIntSupported="undefined"!=typeof BigInt,SymbolSupported="undefined"!=typeof Symbol,ObjectToString=uncurryThis(Object.prototype.toString),numberValue=uncurryThis(_Numberprototype.valueOf),stringValue=uncurryThis(_Stringprototype.valueOf),booleanValue=uncurryThis(Boolean.prototype.valueOf);if(BigIntSupported)var bigIntValue=uncurryThis(BigInt.prototype.valueOf);if(SymbolSupported)var symbolValue=uncurryThis(Symbol.prototype.valueOf);exports.isArgumentsObject=isArgumentsObject,exports.isGeneratorFunction=isGeneratorFunction,exports.isTypedArray=isTypedArray,exports.isPromise=function(input){return"undefined"!=typeof Promise&&input instanceof Promise||null!==input&&"object"==typeof input&&"function"==typeof input.then&&"function"==typeof input.catch},exports.isArrayBufferView=function(value){return"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(value):isTypedArray(value)||isDataView(value)},exports.isUint8Array=function(value){return"Uint8Array"===whichTypedArray(value)},exports.isUint8ClampedArray=function(value){return"Uint8ClampedArray"===whichTypedArray(value)},exports.isUint16Array=function(value){return"Uint16Array"===whichTypedArray(value)},exports.isUint32Array=function(value){return"Uint32Array"===whichTypedArray(value)},exports.isInt8Array=function(value){return"Int8Array"===whichTypedArray(value)},exports.isInt16Array=function(value){return"Int16Array"===whichTypedArray(value)},exports.isInt32Array=function(value){return"Int32Array"===whichTypedArray(value)},exports.isFloat32Array=function(value){return"Float32Array"===whichTypedArray(value)},exports.isFloat64Array=function(value){return"Float64Array"===whichTypedArray(value)},exports.isBigInt64Array=function(value){return"BigInt64Array"===whichTypedArray(value)},exports.isBigUint64Array=function(value){return"BigUint64Array"===whichTypedArray(value)},isMapToString.working="undefined"!=typeof Map&&isMapToString(new Map),exports.isMap=function(value){return"undefined"!=typeof Map&&(isMapToString.working?isMapToString(value):value instanceof Map)},isSetToString.working="undefined"!=typeof Set&&isSetToString(new Set),exports.isSet=function(value){return"undefined"!=typeof Set&&(isSetToString.working?isSetToString(value):value instanceof Set)},isWeakMapToString.working="undefined"!=typeof WeakMap&&isWeakMapToString(new WeakMap),exports.isWeakMap=function(value){return"undefined"!=typeof WeakMap&&(isWeakMapToString.working?isWeakMapToString(value):value instanceof WeakMap)},isWeakSetToString.working="undefined"!=typeof WeakSet&&isWeakSetToString(new WeakSet),exports.isWeakSet=function(value){return isWeakSetToString(value)},isArrayBufferToString.working="undefined"!=typeof ArrayBuffer&&isArrayBufferToString(new ArrayBuffer),exports.isArrayBuffer=isArrayBuffer,isDataViewToString.working="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof DataView&&isDataViewToString(new DataView(new ArrayBuffer(1),0,1)),exports.isDataView=isDataView,isSharedArrayBufferToString.working="undefined"!=typeof SharedArrayBuffer&&isSharedArrayBufferToString(new SharedArrayBuffer),exports.isSharedArrayBuffer=isSharedArrayBuffer,exports.isAsyncFunction=function(value){return"[object AsyncFunction]"===ObjectToString(value)},exports.isMapIterator=function(value){return"[object Map Iterator]"===ObjectToString(value)},exports.isSetIterator=function(value){return"[object Set Iterator]"===ObjectToString(value)},exports.isGeneratorObject=function(value){return"[object Generator]"===ObjectToString(value)},exports.isWebAssemblyCompiledModule=function(value){return"[object WebAssembly.Module]"===ObjectToString(value)},exports.isNumberObject=isNumberObject,exports.isStringObject=isStringObject,exports.isBooleanObject=isBooleanObject,exports.isBigIntObject=isBigIntObject,exports.isSymbolObject=isSymbolObject,exports.isBoxedPrimitive=function(value){return isNumberObject(value)||isStringObject(value)||isBooleanObject(value)||isBigIntObject(value)||isSymbolObject(value)},exports.isAnyArrayBuffer=function(value){return"undefined"!=typeof Uint8Array&&(isArrayBuffer(value)||isSharedArrayBuffer(value))},["isProxy","isExternal","isModuleNamespaceObject"].forEach(function(method){Object.defineProperty(exports,method,{enumerable:!1,value:function(){throw new Error(method+" is not supported in userland")}})})},{"is-arguments":99,"is-generator-function":103,"is-typed-array":104,"which-typed-array":199}],58:[function(require,module,exports){(function(process){(function(){function inspect(obj,opts){var ctx={seen:[],stylize:stylizeNoColor};return 3<=arguments.length&&(ctx.depth=arguments[2]),4<=arguments.length&&(ctx.colors=arguments[3]),isBoolean(opts)?ctx.showHidden=opts:opts&&exports._extend(ctx,opts),isUndefined(ctx.showHidden)&&(ctx.showHidden=!1),isUndefined(ctx.depth)&&(ctx.depth=2),isUndefined(ctx.colors)&&(ctx.colors=!1),isUndefined(ctx.customInspect)&&(ctx.customInspect=!0),ctx.colors&&(ctx.stylize=stylizeWithColor),formatValue(ctx,obj,ctx.depth)}function stylizeWithColor(str,styleType){var style=inspect.styles[styleType];return style?"\x1B["+inspect.colors[style][0]+"m"+str+"\x1B["+inspect.colors[style][1]+"m":str}function stylizeNoColor(str){return str}function arrayToHash(array){var hash={};return array.forEach(function(val){hash[val]=!0}),hash}function formatValue(ctx,value,recurseTimes){if(ctx.customInspect&&value&&isFunction(value.inspect)&&value.inspect!==exports.inspect&&!(value.constructor&&value.constructor.prototype===value)){var ret=value.inspect(recurseTimes,ctx);return isString(ret)||(ret=formatValue(ctx,ret,recurseTimes)),ret}var primitive=formatPrimitive(ctx,value);if(primitive)return primitive;var keys=Object.keys(value),visibleKeys=arrayToHash(keys);if(ctx.showHidden&&(keys=Object.getOwnPropertyNames(value)),isError(value)&&(0<=keys.indexOf("message")||0<=keys.indexOf("description")))return formatError(value);if(0===keys.length){if(isFunction(value)){var name=value.name?": "+value.name:"";return ctx.stylize("[Function"+name+"]","special")}if(isRegExp(value))return ctx.stylize(RegExp.prototype.toString.call(value),"regexp");if(isDate(value))return ctx.stylize(Date.prototype.toString.call(value),"date");if(isError(value))return formatError(value)}var base="",array=!1,braces=["{","}"];if(isArray(value)&&(array=!0,braces=["[","]"]),isFunction(value)){var n=value.name?": "+value.name:"";base=" [Function"+n+"]"}if(isRegExp(value)&&(base=" "+RegExp.prototype.toString.call(value)),isDate(value)&&(base=" "+Date.prototype.toUTCString.call(value)),isError(value)&&(base=" "+formatError(value)),0===keys.length&&(!array||0==value.length))return braces[0]+base+braces[1];if(0>recurseTimes)return isRegExp(value)?ctx.stylize(RegExp.prototype.toString.call(value),"regexp"):ctx.stylize("[Object]","special");ctx.seen.push(value);var output;return output=array?formatArray(ctx,value,recurseTimes,visibleKeys,keys):keys.map(function(key){return formatProperty(ctx,value,recurseTimes,visibleKeys,key,array)}),ctx.seen.pop(),reduceToSingleString(output,base,braces)}function formatPrimitive(ctx,value){if(isUndefined(value))return ctx.stylize("undefined","undefined");if(isString(value)){var simple="'"+JSON.stringify(value).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,"\"")+"'";return ctx.stylize(simple,"string")}return isNumber(value)?ctx.stylize(""+value,"number"):isBoolean(value)?ctx.stylize(""+value,"boolean"):isNull(value)?ctx.stylize("null","null"):void 0}function formatError(value){return"["+Error.prototype.toString.call(value)+"]"}function formatArray(ctx,value,recurseTimes,visibleKeys,keys){for(var output=[],i=0,l=value.length;ictx.seen.indexOf(desc.value)?(str=isNull(recurseTimes)?formatValue(ctx,desc.value,null):formatValue(ctx,desc.value,recurseTimes-1),-1n?"0"+n.toString(10):n.toString(10)}function timestamp(){var d=new Date,time=[pad(d.getHours()),pad(d.getMinutes()),pad(d.getSeconds())].join(":");return[d.getDate(),months[d.getMonth()],time].join(" ")}function hasOwnProperty(obj,prop){return Object.prototype.hasOwnProperty.call(obj,prop)}function callbackifyOnRejected(reason,cb){if(!reason){var newReason=new Error("Promise was rejected with a falsy value");newReason.reason=reason,reason=newReason}return cb(reason)}var getOwnPropertyDescriptors=Object.getOwnPropertyDescriptors||function(obj){for(var keys=Object.keys(obj),descriptors={},i=0;i=len)return x;switch(x){case"%s":return args[i++]+"";case"%d":return+args[i++];case"%j":try{return JSON.stringify(args[i++])}catch(_){return"[Circular]"}default:return x;}}),x=args[i];isize)throw new RangeError("\"size\" argument must not be negative");return Buffer.allocUnsafe?Buffer.allocUnsafe(size):new Buffer(size)}}).call(this)}).call(this,require("buffer").Buffer)},{buffer:38}],60:[function(require,module){(function(Buffer){(function(){var bufferFill=require("buffer-fill"),allocUnsafe=require("buffer-alloc-unsafe");module.exports=function(size,fill,encoding){if("number"!=typeof size)throw new TypeError("\"size\" argument must be a number");if(0>size)throw new RangeError("\"size\" argument must not be negative");if(Buffer.alloc)return Buffer.alloc(size,fill,encoding);var buffer=allocUnsafe(size);return 0===size?buffer:void 0===fill?bufferFill(buffer,0):("string"!=typeof encoding&&(encoding=void 0),bufferFill(buffer,fill,encoding))}}).call(this)}).call(this,require("buffer").Buffer)},{buffer:38,"buffer-alloc-unsafe":59,"buffer-fill":61}],61:[function(require,module){(function(Buffer){(function(){function isSingleByte(val){return 1===val.length&&256>val.charCodeAt(0)}function fillWithNumber(buffer,val,start,end){if(0>start||end>buffer.length)throw new RangeError("Out of range index");return start>>>=0,end=void 0===end?buffer.length:end>>>0,end>start&&buffer.fill(val,start,end),buffer}function fillWithBuffer(buffer,val,start,end){if(0>start||end>buffer.length)throw new RangeError("Out of range index");if(end<=start)return buffer;start>>>=0,end=void 0===end?buffer.length:end>>>0;for(var pos=start,len=val.length;pos<=end-len;)val.copy(buffer,pos),pos+=len;return pos!==end&&val.copy(buffer,pos,0,end-pos),buffer}var hasFullSupport=function(){try{if(!Buffer.isEncoding("latin1"))return!1;var buf=Buffer.alloc?Buffer.alloc(4):new Buffer(4);return buf.fill("ab","ucs2"),"61006200"===buf.toString("hex")}catch(_){return!1}}();module.exports=function(buffer,val,start,end,encoding){if(hasFullSupport)return buffer.fill(val,start,end,encoding);if("number"==typeof val)return fillWithNumber(buffer,val,start,end);if("string"==typeof val){if("string"==typeof start?(encoding=start,start=0,end=buffer.length):"string"==typeof end&&(encoding=end,end=buffer.length),void 0!==encoding&&"string"!=typeof encoding)throw new TypeError("encoding must be a string");if("latin1"===encoding&&(encoding="binary"),"string"==typeof encoding&&!Buffer.isEncoding(encoding))throw new TypeError("Unknown encoding: "+encoding);if(""===val)return fillWithNumber(buffer,0,start,end);if(isSingleByte(val))return fillWithNumber(buffer,val.charCodeAt(0),start,end);val=new Buffer(val,encoding)}return Buffer.isBuffer(val)?fillWithBuffer(buffer,val,start,end):fillWithNumber(buffer,0,start,end)}}).call(this)}).call(this,require("buffer").Buffer)},{buffer:38}],62:[function(require,module){module.exports={100:"Continue",101:"Switching Protocols",102:"Processing",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Unordered Collection",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",509:"Bandwidth Limit Exceeded",510:"Not Extended",511:"Network Authentication Required"}},{}],63:[function(require,module,exports){(function(Buffer){(function(){function onReceive(info){info.socketId in sockets?sockets[info.socketId]._onReceive(info):console.error("Unknown socket id: "+info.socketId)}function onReceiveError(info){info.socketId in sockets?sockets[info.socketId]._onReceiveError(info.resultCode):console.error("Unknown socket id: "+info.socketId)}function Socket(options,listener){var self=this;if(EventEmitter.call(self),"string"==typeof options&&(options={type:options}),"udp4"!==options.type)throw new Error("Bad socket type specified. Valid types are: udp4");"function"==typeof listener&&self.on("message",listener),self._destroyed=!1,self._bindState=0,self._bindTasks=[]}function sliceBuffer(buffer,offset,length){if("string"==typeof buffer)buffer=Buffer.from(buffer);else if(!(buffer instanceof Buffer))throw new TypeError("First argument must be a buffer or string");offset>>>=0,length>>>=0;var buf=buffer.buffer;return(buffer.byteOffset||buffer.byteLength!==buf.byteLength)&&(buf=buf.slice(buffer.byteOffset,buffer.byteOffset+buffer.byteLength)),(offset||length!==buffer.length)&&(buf=buf.slice(offset,length)),Buffer.from(buf)}function fixBufferList(list){for(var newlist=Array(list.length),i=0,l=list.length,buf;iresult?void self.emit("error",new Error("Socket "+self.id+" failed to bind. "+chrome.runtime.lastError.message)):void chrome.sockets.udp.getInfo(self.id,function(socketInfo){return socketInfo.localPort&&socketInfo.localAddress?void(self._port=socketInfo.localPort,self._address=socketInfo.localAddress,self._bindState=BIND_STATE_BOUND,self.emit("listening"),self._bindTasks.map(function(t){t.callback()})):void self.emit("error",new Error("Cannot get local port/address for Socket "+self.id))})})})})},Socket.prototype._onReceive=function(info){var self=this,buf=Buffer.from(new Uint8Array(info.data)),rinfo={address:info.remoteAddress,family:"IPv4",port:info.remotePort,size:buf.length};self.emit("message",buf,rinfo)},Socket.prototype._onReceiveError=function(resultCode){var self=this;self.emit("error",new Error("Socket "+self.id+" receive error "+resultCode))},Socket.prototype.send=function(buffer,offset,length,port,address,callback){var self=this,list;if(address||port&&"function"!=typeof port?buffer=sliceBuffer(buffer,offset,length):(callback=port,port=offset,address=length),!Array.isArray(buffer)){if("string"==typeof buffer)list=[Buffer.from(buffer)];else if(!(buffer instanceof Buffer))throw new TypeError("First argument must be a buffer or a string");else list=[buffer];}else if(!(list=fixBufferList(buffer)))throw new TypeError("Buffer list arguments must be buffers or strings");if(port>>>=0,0===port||65535 0 and < 65536");if("function"!=typeof callback&&(callback=function(){}),self._bindState===BIND_STATE_UNBOUND&&self.bind(0),self._bindState!==BIND_STATE_BOUND)return self._sendQueue||(self._sendQueue=[],self.once("listening",function(){for(var i=0;isendInfo.resultCode){var err=new Error("Socket "+self.id+" send error "+sendInfo.resultCode);callback(err),self.emit("error",err)}else callback(null)})},Socket.prototype.close=function(){var self=this;self._destroyed||(delete sockets[self.id],chrome.sockets.udp.close(self.id),self._destroyed=!0,self.emit("close"))},Socket.prototype.address=function(){var self=this;return{address:self._address,port:self._port,family:"IPv4"}},Socket.prototype.setBroadcast=function(){},Socket.prototype.setTTL=function(){},Socket.prototype.setMulticastTTL=function(ttl,callback){function setMulticastTTL(callback){chrome.sockets.udp.setMulticastTimeToLive(self.id,ttl,callback)}var self=this;callback||(callback=function(){}),self._bindState===BIND_STATE_BOUND?setMulticastTTL(callback):self._bindTasks.push({fn:setMulticastTTL,callback})},Socket.prototype.setMulticastLoopback=function(flag,callback){function setMulticastLoopback(callback){chrome.sockets.udp.setMulticastLoopbackMode(self.id,flag,callback)}var self=this;callback||(callback=function(){}),self._bindState===BIND_STATE_BOUND?setMulticastLoopback(callback):self._bindTasks.push({fn:setMulticastLoopback,callback})},Socket.prototype.addMembership=function(multicastAddress,multicastInterface,callback){var self=this;callback||(callback=function(){}),chrome.sockets.udp.joinGroup(self.id,multicastAddress,callback)},Socket.prototype.dropMembership=function(multicastAddress,multicastInterface,callback){var self=this;callback||(callback=function(){}),chrome.sockets.udp.leaveGroup(self.id,multicastAddress,callback)},Socket.prototype.unref=function(){},Socket.prototype.ref=function(){}}).call(this)}).call(this,require("buffer").Buffer)},{buffer:38,events:39,inherits:97,"run-series":163}],64:[function(require,module,exports){function lookup(hostname,opts,cb){return"function"==typeof opts?lookup(hostname,null,opts):void chrome.dns.resolve(hostname,resolveInfo=>{if(0!==resolveInfo.resultCode)return cb(new Error("DNS lookup error: "+chrome.runtime.lastError.message));const address=resolveInfo.address,ipVersion=isIPv4(address)?4:isIPv6(address)?6:0;cb(null,address,ipVersion)})}const{isIPv4,isIPv6}=require("chrome-net");exports.lookup=lookup},{"chrome-net":65}],65:[function(require,module,exports){(function(process){(function(){/*! chrome-net. MIT License. Feross Aboukhadijeh */'use strict';function onAccept(info){info.socketId in servers?servers[info.socketId]._onAccept(info.clientSocketId):console.error("Unknown server socket id: "+info.socketId)}function onAcceptError(info){info.socketId in servers?servers[info.socketId]._onAcceptError(info.resultCode):console.error("Unknown server socket id: "+info.socketId)}function onReceive(info){info.socketId in sockets?sockets[info.socketId]._onReceive(info.data):console.error("Unknown socket id: "+info.socketId)}function onReceiveError(info){if(info.socketId in sockets)sockets[info.socketId]._onReceiveError(info.resultCode);else{if(-100===info.resultCode)return;console.error("Unknown socket id: "+info.socketId)}}function Server(options,connectionListener){if(!(this instanceof Server))return new Server(options,connectionListener);if(EventEmitter.call(this),"function"==typeof options)connectionListener=options,options={},this.on("connection",connectionListener);else if(null==options||"object"==typeof options)options=options||{},"function"==typeof connectionListener&&this.on("connection",connectionListener);else throw new TypeError("options must be an object");this._connections=0,Object.defineProperty(this,"connections",{get:deprecate(()=>this._connections,"Server.connections property is deprecated. Use Server.getConnections method instead."),set:deprecate(val=>this._connections=val,"Server.connections property is deprecated."),configurable:!0,enumerable:!1}),this.id=null,this.connecting=!1,this.allowHalfOpen=options.allowHalfOpen||!1,this.pauseOnConnect=!!options.pauseOnConnect,this._address=null,this._host=null,this._port=null,this._backlog=null}function emitCloseNT(self){self.id||self.connecting||self._connections||self.emit("close")}function Socket(options){if(!(this instanceof Socket))return new Socket(options);if("number"==typeof options?options={fd:options}:void 0===options&&(options={}),options.handle)throw new Error("handle is not supported in Chrome Apps.");else if(void 0!==options.fd)throw new Error("fd is not supported in Chrome Apps.");options.decodeStrings=!0,options.objectMode=!1,stream.Duplex.call(this,options),this.destroyed=!1,this._hadError=!1,this.id=null,this._parent=null,this._host=null,this._port=null,this._pendingData=null,this.ondata=null,this.onend=null,this._init(),this._reset(),this.allowHalfOpen=options.allowHalfOpen||!1,this.on("finish",this.destroy),options.server&&(this.server=this._server=options.server,this.id=options.id,sockets[this.id]=this,options.pauseOnCreate&&(this._readableState.flowing=!1),this.connecting=!0,this.writable=!0,this._onConnect())}function normalizeConnectArgs(args){var options={};if(null!==args[0]&&"object"==typeof args[0])options=args[0];else if(isPipeName(args[0]))throw new Error("Pipes are not supported in Chrome Apps.");else options.port=args[0],"string"==typeof args[1]&&(options.host=args[1]);var cb=args[args.length-1];return"function"==typeof cb?[options,cb]:[options]}function toNumber(x){return!!(0<=(x=+x))&&x}function isPipeName(s){return"string"==typeof s&&!1===toNumber(s)}function isLegalPort(port){return("number"==typeof port||"string"==typeof port)&&("string"!=typeof port||0!==port.trim().length)&&+port==+port>>>0&&65535>=port}function assertPort(port){if("undefined"!=typeof port&&!isLegalPort(port))throw new RangeError("\"port\" argument must be >= 0 and < 65536")}function ignoreLastError(){void chrome.runtime.lastError}function chromeCallbackWrap(callback){return()=>{var error;chrome.runtime.lastError&&(console.error(chrome.runtime.lastError.message),error=new Error(chrome.runtime.lastError.message)),callback&&callback(error)}}function emitErrorNT(self,err){self.emit("error",err)}function errnoException(err,syscall,details){var uvCode=errorChromeToUv[err]||"UNKNOWN",message=syscall+" "+err+" "+details;chrome.runtime.lastError&&(message+=" "+chrome.runtime.lastError.message),message+=" (mapped uv code: "+uvCode+")";var e=new Error(message);return e.code=e.errno=uvCode,e.syscall=syscall,e}function exceptionWithHostPort(err,syscall,address,port,additional){var details;details=port&&0{if(!this.connecting||this.id)return ignoreLastError(),void chrome.sockets.tcpServer.close(createInfo.socketId);if(chrome.runtime.lastError)return void this.emit("error",new Error(chrome.runtime.lastError.message));var socketId=this.id=createInfo.socketId;servers[this.id]=this;var listen=()=>chrome.sockets.tcpServer.listen(this.id,this._host,this._port,this._backlog,result=>this.id===socketId?0!==result&&isAny6?(ignoreLastError(),this._host="0.0.0.0",isAny6=!1,listen()):void this._onListen(result):void ignoreLastError());listen()}),this},Server.prototype._onListen=function(result){if(this.connecting=!1,0===result){var idBefore=this.id;chrome.sockets.tcpServer.getInfo(this.id,info=>this.id===idBefore?chrome.runtime.lastError?void this._onListen(-2):void(this._address={port:info.localPort,family:info.localAddress&&-1!==info.localAddress.indexOf(":")?"IPv6":"IPv4",address:info.localAddress},this.emit("listening")):void ignoreLastError())}else this.emit("error",exceptionWithHostPort(result,"listen",this._host,this._port)),this.id&&(chrome.sockets.tcpServer.close(this.id),delete servers[this.id],this.id=null)},Server.prototype._onAccept=function(clientSocketId){if(this.maxConnections&&this._connections>=this.maxConnections)return chrome.sockets.tcp.close(clientSocketId),void console.warn("Rejected connection - hit `maxConnections` limit");this._connections+=1;var acceptedSocket=new Socket({server:this,id:clientSocketId,allowHalfOpen:this.allowHalfOpen,pauseOnCreate:this.pauseOnConnect});acceptedSocket.on("connect",()=>this.emit("connection",acceptedSocket))},Server.prototype._onAcceptError=function(resultCode){this.emit("error",errnoException(resultCode,"accept")),this.close()},Server.prototype.close=function(callback){return"function"==typeof callback&&(this.id?this.once("close",callback):this.once("close",()=>callback(new Error("Not running")))),this.id&&(chrome.sockets.tcpServer.close(this.id),delete servers[this.id],this.id=null),this._address=null,this.connecting=!1,this._emitCloseIfDrained(),this},Server.prototype._emitCloseIfDrained=function(){this.id||this.connecting||this._connections||process.nextTick(emitCloseNT,this)},Object.defineProperty(Server.prototype,"listening",{get:function(){return!!this._address},configurable:!0,enumerable:!0}),Server.prototype.address=function(){return this._address},Server.prototype.unref=Server.prototype.ref=function(){return this},Server.prototype.getConnections=function(callback){process.nextTick(callback,null,this._connections)},inherits(Socket,stream.Duplex),exports.Socket=Socket,Socket.prototype._init=function(){this.bytesRead=0,this._bytesDispatched=0,this.server=null,this._server=null},Socket.prototype._reset=function(){this.remoteAddress=this.remotePort=this.localAddress=this.localPort=null,this.remoteFamily="IPv4",this.readable=this.writable=!1,this.connecting=!1},Socket.prototype.connect=function(){const argsLen=arguments.length;for(var args=Array(argsLen),i=0;i= 0 and < 65536: "+this._port)}return this._port|=0,this._init(),this._unrefTimer(),"function"==typeof cb&&this.once("connect",cb),chrome.sockets.tcp.create(createInfo=>!this.connecting||this.id?(ignoreLastError(),void chrome.sockets.tcp.close(createInfo.socketId)):chrome.runtime.lastError?void this.destroy(new Error(chrome.runtime.lastError.message)):void(this.id=createInfo.socketId,sockets[this.id]=this,chrome.sockets.tcp.setPaused(this.id,!0),chrome.sockets.tcp.connect(this.id,this._host,this._port,result=>this.id===createInfo.socketId?0===result?void(this._unrefTimer(),this._onConnect()):void this.destroy(exceptionWithHostPort(result,"connect",this._host,this._port)):void ignoreLastError()))),this},Socket.prototype._onConnect=function(){var idBefore=this.id;chrome.sockets.tcp.getInfo(this.id,result=>this.id===idBefore?chrome.runtime.lastError?void this.destroy(new Error(chrome.runtime.lastError.message)):void(this.remoteAddress=result.peerAddress,this.remoteFamily=result.peerAddress&&-1!==result.peerAddress.indexOf(":")?"IPv6":"IPv4",this.remotePort=result.peerPort,this.localAddress=result.localAddress,this.localPort=result.localPort,this.connecting=!1,this.readable=!0,this.emit("connect"),!this.isPaused()&&this.read(0)):void ignoreLastError())},Object.defineProperty(Socket.prototype,"bufferSize",{get:function(){if(this.id){var bytes=this._writableState.length;return this._pendingData&&(bytes+=this._pendingData.length),bytes}}}),Socket.prototype.end=function(data,encoding){stream.Duplex.prototype.end.call(this,data,encoding),this.writable=!1},Socket.prototype._write=function(chunk,encoding,callback){if(callback||(callback=()=>{}),this.connecting)return this._pendingData=chunk,void this.once("connect",()=>this._write(chunk,encoding,callback));if(this._pendingData=null,!this.id)return void callback(new Error("This socket is closed"));var buffer=chunk.buffer;chunk.byteLength!==buffer.byteLength&&(buffer=buffer.slice(chunk.byteOffset,chunk.byteOffset+chunk.byteLength));var idBefore=this.id;chrome.sockets.tcp.send(this.id,buffer,sendInfo=>this.id===idBefore?void(0>sendInfo.resultCode?this._destroy(exceptionWithHostPort(sendInfo.resultCode,"write",this.remoteAddress,this.remotePort),callback):(this._unrefTimer(),callback(null))):void ignoreLastError()),this._bytesDispatched+=chunk.length},Socket.prototype._read=function(bufferSize){if(this.connecting||!this.id)return void this.once("connect",()=>this._read(bufferSize));chrome.sockets.tcp.setPaused(this.id,!1);var idBefore=this.id;chrome.sockets.tcp.getInfo(this.id,result=>this.id===idBefore?void((chrome.runtime.lastError||!result.connected)&&this._onReceiveError(-15)):void ignoreLastError())},Socket.prototype._onReceive=function(data){var buffer=Buffer.from(data),offset=this.bytesRead;this.bytesRead+=buffer.length,this._unrefTimer(),this.ondata&&(console.error("socket.ondata = func is non-standard, use socket.on('data', func)"),this.ondata(buffer,offset,this.bytesRead)),this.push(buffer)||chrome.sockets.tcp.setPaused(this.id,!0)},Socket.prototype._onReceiveError=function(resultCode){-100===resultCode?(this.onend&&(console.error("socket.onend = func is non-standard, use socket.on('end', func)"),this.once("end",this.onend)),this.push(null),this.destroy()):0>resultCode&&this.destroy(errnoException(resultCode,"read"))},function(name,callback){Object.defineProperty(Socket.prototype,name,{configurable:!1,enumerable:!0,get:callback})}("bytesWritten",function(){if(this.id)return this._bytesDispatched+this.bufferSize}),Socket.prototype.destroy=function(exception){this._destroy(exception)},Socket.prototype._destroy=function(exception,cb){var fireErrorCallbacks=()=>{cb&&cb(exception),exception&&!this._writableState.errorEmitted&&(process.nextTick(emitErrorNT,this,exception),this._writableState.errorEmitted=!0)};if(this.destroyed)return void fireErrorCallbacks();this._server&&(this._server._connections-=1,this._server._emitCloseIfDrained&&this._server._emitCloseIfDrained()),this._reset();for(var s=this;null!==s;s=s._parent)timers.unenroll(s);this.destroyed=!0,this.id&&(delete sockets[this.id],chrome.sockets.tcp.close(this.id,()=>{this.destroyed&&this.emit("close",!!exception)}),this.id=null),fireErrorCallbacks()},Socket.prototype.destroySoon=function(){this.writable&&this.end(),this._writableState.finished&&this.destroy()},Socket.prototype.setTimeout=function(timeout,callback){return 0===timeout?(timers.unenroll(this),callback&&this.removeListener("timeout",callback)):(timers.enroll(this,timeout),timers._unrefActive(this),callback&&this.once("timeout",callback)),this},Socket.prototype._onTimeout=function(){this.emit("timeout")},Socket.prototype._unrefTimer=function(){for(var s=this;null!==s;s=s._parent)timers._unrefActive(s)},Socket.prototype.setNoDelay=function(noDelay,callback){return this.id?(noDelay=void 0===noDelay||!!noDelay,chrome.sockets.tcp.setNoDelay(this.id,noDelay,chromeCallbackWrap(callback)),this):(this.once("connect",()=>this.setNoDelay(noDelay,callback)),this)},Socket.prototype.setKeepAlive=function(enable,initialDelay,callback){return this.id?(chrome.sockets.tcp.setKeepAlive(this.id,!!enable,~~(initialDelay/1e3),chromeCallbackWrap(callback)),this):(this.once("connect",()=>this.setKeepAlive(enable,initialDelay,callback)),this)},Socket.prototype.address=function(){return{address:this.localAddress,port:this.localPort,family:this.localAddress&&-1!==this.localAddress.indexOf(":")?"IPv6":"IPv4"}},Object.defineProperty(Socket.prototype,"_connecting",{get:function(){return this.connecting}}),Object.defineProperty(Socket.prototype,"readyState",{get:function(){return this.connecting?"opening":this.readable&&this.writable?"open":"closed"}}),Socket.prototype.unref=Socket.prototype.ref=function(){return this};var IPv4Regex=/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/,IPv6Regex=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]).){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]).){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/;exports.isIPv4=IPv4Regex.test.bind(IPv4Regex),exports.isIPv6=IPv6Regex.test.bind(IPv6Regex),exports.isIP=function(ip){return exports.isIPv4(ip)?4:exports.isIPv6(ip)?6:0};var errorChromeToUv={"-10":"EACCES","-22":"EACCES","-138":"EACCES","-147":"EADDRINUSE","-108":"EADDRNOTAVAIL","-103":"ECONNABORTED","-102":"ECONNREFUSED","-101":"ECONNRESET","-16":"EEXIST","-8":"EFBIG","-109":"EHOSTUNREACH","-4":"EINVAL","-23":"EISCONN","-6":"ENOENT","-13":"ENOMEM","-106":"ENONET","-18":"ENOSPC","-11":"ENOSYS","-15":"ENOTCONN","-105":"ENOTFOUND","-118":"ETIMEDOUT","-100":"EOF"}}).call(this)}).call(this,require("_process"))},{_process:132,buffer:38,events:39,inherits:97,stream:41,timers:185,util:58}],66:[function(require,module){const BlockStream=require("block-stream2"),stream=require("readable-stream");class ChunkStoreWriteStream extends stream.Writable{constructor(store,chunkLength,opts={}){if(super(opts),!store||!store.put||!store.get)throw new Error("First argument must be an abstract-chunk-store compliant store");if(chunkLength=+chunkLength,!chunkLength)throw new Error("Second argument must be a chunk length");this._blockstream=new BlockStream(chunkLength,{zeroPadding:!1}),this._outstandingPuts=0;let index=0;const onData=chunk=>{this.destroyed||(this._outstandingPuts+=1,store.put(index,chunk,()=>{this._outstandingPuts-=1,0===this._outstandingPuts&&"function"==typeof this._finalCb&&(this._finalCb(null),this._finalCb=null)}),index+=1)};this._blockstream.on("data",onData).on("error",err=>{this.destroy(err)})}_write(chunk,encoding,callback){this._blockstream.write(chunk,encoding,callback)}_final(cb){this._blockstream.end(),this._blockstream.once("end",()=>{0===this._outstandingPuts?cb(null):this._finalCb=cb})}destroy(err){this.destroyed||(this.destroyed=!0,err&&this.emit("error",err),this.emit("close"))}}module.exports=ChunkStoreWriteStream},{"block-stream2":34,"readable-stream":157}],67:[function(require,module){var ipaddr=require("ipaddr.js"),compact2string=function(buf){switch(buf.length){case 6:return buf[0]+"."+buf[1]+"."+buf[2]+"."+buf[3]+":"+buf.readUInt16BE(4);break;case 18:for(var hexGroups=[],i=0;8>i;i++)hexGroups.push(buf.readUInt16BE(2*i).toString(16));var host=ipaddr.parse(hexGroups.join(":")).toString();return"["+host+"]:"+buf.readUInt16BE(16);default:throw new Error("Invalid Compact IP/PORT, It should contain 6 or 18 bytes");}};compact2string.multi=function(buf){if(0!=buf.length%6)throw new Error("buf length isn't multiple of compact IP/PORTs (6 bytes)");for(var output=[],i=0;i<=buf.length-1;i+=6)output.push(compact2string(buf.slice(i,i+6)));return output},compact2string.multi6=function(buf){if(0!=buf.length%18)throw new Error("buf length isn't multiple of compact IP6/PORTs (18 bytes)");for(var output=[],i=0;i<=buf.length-1;i+=18)output.push(compact2string(buf.slice(i,i+18)));return output},module.exports=compact2string},{"ipaddr.js":98}],68:[function(require,module){(function(process,global,Buffer){(function(){function flat(arr1){return arr1.reduce((acc,val)=>Array.isArray(val)?acc.concat(flat(val)):acc.concat(val),[])}function _parseInput(input,opts,cb){function processInput(){parallel(input.map(item=>cb=>{const file={};if(isBlob(item))file.getStream=getBlobStream(item),file.length=item.size;else if(Buffer.isBuffer(item))file.getStream=getBufferStream(item),file.length=item.length;else if(isReadable(item))file.getStream=getStreamStream(item,file),file.length=0;else{if("string"==typeof item){if("function"!=typeof getFiles)throw new Error("filesystem paths do not work in the browser");const keepRoot=1err?cb(err):void(files=flat(files),cb(null,files,isSingleFileTorrent)))}if(isFileList(input)&&(input=Array.from(input)),Array.isArray(input)||(input=[input]),0===input.length)throw new Error("invalid input type");input.forEach(item=>{if(null==item)throw new Error(`invalid input type: ${item}`)}),input=input.map(item=>isBlob(item)&&"string"==typeof item.path&&"function"==typeof getFiles?item.path:item),1!==input.length||"string"==typeof input[0]||input[0].name||(input[0].name=opts.name);let commonPrefix=null;input.forEach((item,i)=>{if("string"==typeof item)return;let path=item.fullPath||item.name;path||(path=`Unknown File ${i+1}`,item.unknownName=!0),item.path=path.split("/"),item.path[0]||item.path.shift(),2>item.path.length?commonPrefix=null:0===i&&1{if("string"==typeof item)return!0;const filename=item.path[item.path.length-1];return notHidden(filename)&&junk.not(filename)}),commonPrefix&&input.forEach(item=>{const pathless=(Buffer.isBuffer(item)||isReadable(item))&&!item.path;"string"==typeof item||pathless||item.path.shift()}),!opts.name&&commonPrefix&&(opts.name=commonPrefix),opts.name||input.some(item=>"string"==typeof item?(opts.name=corePath.basename(item),!0):item.unknownName?void 0:(opts.name=item.path[item.path.length-1],!0)),opts.name||(opts.name=`Unnamed Torrent ${Date.now()}`);const numPaths=input.reduce((sum,item)=>sum+ +("string"==typeof item),0);let isSingleFileTorrent=1===input.length;if(1===input.length&&"string"==typeof input[0]){if("function"!=typeof getFiles)throw new Error("filesystem paths do not work in the browser");isFile(input[0],(err,pathIsFile)=>err?cb(err):void(isSingleFileTorrent=pathIsFile,processInput()))}else process.nextTick(()=>{processInput()})}function notHidden(file){return"."!==file[0]}function getPieceList(files,pieceLength,cb){function onData(chunk){length+=chunk.length;const i=pieceNum;sha1(chunk,hash=>{pieces[i]=hash,remainingHashes-=1,maybeDone()}),remainingHashes+=1,pieceNum+=1}function onEnd(){ended=!0,maybeDone()}function onError(err){cleanup(),cb(err)}function cleanup(){multistream.removeListener("error",onError),blockstream.removeListener("data",onData),blockstream.removeListener("end",onEnd),blockstream.removeListener("error",onError)}function maybeDone(){ended&&0===remainingHashes&&(cleanup(),cb(null,Buffer.from(pieces.join(""),"hex"),length))}cb=once(cb);const pieces=[];let length=0;const streams=files.map(file=>file.getStream);let remainingHashes=0,pieceNum=0,ended=!1;const multistream=new MultiStream(streams),blockstream=new BlockStream(pieceLength,{zeroPadding:!1});multistream.on("error",onError),multistream.pipe(blockstream).on("data",onData).on("end",onEnd).on("error",onError)}function onFiles(files,opts,cb){let announceList=opts.announceList;announceList||("string"==typeof opts.announce?announceList=[[opts.announce]]:Array.isArray(opts.announce)&&(announceList=opts.announce.map(u=>[u]))),announceList||(announceList=[]),global.WEBTORRENT_ANNOUNCE&&("string"==typeof global.WEBTORRENT_ANNOUNCE?announceList.push([[global.WEBTORRENT_ANNOUNCE]]):Array.isArray(global.WEBTORRENT_ANNOUNCE)&&(announceList=announceList.concat(global.WEBTORRENT_ANNOUNCE.map(u=>[u])))),opts.announce===void 0&&opts.announceList===void 0&&(announceList=announceList.concat(module.exports.announceList)),"string"==typeof opts.urlList&&(opts.urlList=[opts.urlList]);const torrent={info:{name:opts.name},"creation date":_Mathceil((+opts.creationDate||Date.now())/1e3),encoding:"UTF-8"};0!==announceList.length&&(torrent.announce=announceList[0][0],torrent["announce-list"]=announceList),opts.comment!==void 0&&(torrent.comment=opts.comment),opts.createdBy!==void 0&&(torrent["created by"]=opts.createdBy),opts.private!==void 0&&(torrent.info.private=+opts.private),opts.info!==void 0&&Object.assign(torrent.info,opts.info),opts.sslCert!==void 0&&(torrent.info["ssl-cert"]=opts.sslCert),opts.urlList!==void 0&&(torrent["url-list"]=opts.urlList);const pieceLength=opts.pieceLength||calcPieceLength(files.reduce(sumLength,0));torrent.info["piece length"]=pieceLength,getPieceList(files,pieceLength,(err,pieces,torrentLength)=>err?cb(err):void(torrent.info.pieces=pieces,files.forEach(file=>{delete file.getStream}),opts.singleFileTorrent?torrent.info.length=torrentLength:torrent.info.files=files,cb(null,bencode.encode(torrent))))}function sumLength(sum,file){return sum+file.length}function isBlob(obj){return"undefined"!=typeof Blob&&obj instanceof Blob}function isFileList(obj){return"undefined"!=typeof FileList&&obj instanceof FileList}function isReadable(obj){return"object"==typeof obj&&null!=obj&&"function"==typeof obj.pipe}function getBlobStream(file){return()=>new FileReadStream(file)}function getBufferStream(buffer){return()=>{const s=new stream.PassThrough;return s.end(buffer),s}}function getStreamStream(readable,file){return()=>{const counter=new stream.Transform;return counter._transform=function(buf,enc,done){file.length+=buf.length,this.push(buf),done()},readable.pipe(counter),counter}}/*! create-torrent. MIT License. WebTorrent LLC */const bencode=require("bencode"),BlockStream=require("block-stream2"),calcPieceLength=require("piece-length"),corePath=require("path"),FileReadStream=require("filestream/read"),isFile=require("is-file"),junk=require("junk"),MultiStream=require("multistream"),once=require("once"),parallel=require("run-parallel"),sha1=require("simple-sha1"),stream=require("readable-stream"),getFiles=require("./get-files");module.exports=function(input,opts,cb){"function"==typeof opts&&([opts,cb]=[cb,opts]),opts=opts?Object.assign({},opts):{},_parseInput(input,opts,(err,files,singleFileTorrent)=>err?cb(err):void(opts.singleFileTorrent=singleFileTorrent,onFiles(files,opts,cb)))},module.exports.parseInput=function(input,opts,cb){"function"==typeof opts&&([opts,cb]=[cb,opts]),opts=opts?Object.assign({},opts):{},_parseInput(input,opts,cb)},module.exports.announceList=[["udp://tracker.leechers-paradise.org:6969"],["udp://tracker.coppersurfer.tk:6969"],["udp://tracker.opentrackr.org:1337"],["udp://explodie.org:6969"],["udp://tracker.empire-js.us:1337"],["wss://tracker.btorrent.xyz"],["wss://tracker.openwebtorrent.com"]]}).call(this)}).call(this,require("_process"),"undefined"==typeof global?"undefined"==typeof self?"undefined"==typeof window?{}:window:self:global,require("buffer").Buffer)},{"./get-files":36,_process:132,bencode:19,"block-stream2":34,buffer:38,"filestream/read":78,"is-file":102,junk:106,multistream:126,once:129,path:40,"piece-length":131,"readable-stream":157,"run-parallel":162,"simple-sha1":169}],69:[function(require,module,exports){(function(process){(function(){function load(){let r;try{r=exports.storage.getItem("debug")}catch(error){}return!r&&"undefined"!=typeof process&&"env"in process&&(r=process.env.DEBUG),r}exports.formatArgs=function(args){if(args[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+args[0]+(this.useColors?"%c ":" ")+"+"+module.exports.humanize(this.diff),!this.useColors)return;const c="color: "+this.color;args.splice(1,0,c,"color: inherit");let index=0,lastC=0;args[0].replace(/%[a-zA-Z%]/g,match=>{"%%"===match||(index++,"%c"===match&&(lastC=index))}),args.splice(lastC,0,c)},exports.save=function(namespaces){try{namespaces?exports.storage.setItem("debug",namespaces):exports.storage.removeItem("debug")}catch(error){}},exports.load=load,exports.useColors=function(){return!!("undefined"!=typeof window&&window.process&&("renderer"===window.process.type||window.process.__nwjs))||!("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))&&("undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&31<=parseInt(RegExp.$1,10)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/))},exports.storage=function(){try{return localStorage}catch(error){}}(),exports.destroy=(()=>{let warned=!1;return()=>{warned||(warned=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),exports.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],exports.log=console.debug||console.log||(()=>{}),module.exports=require("./common")(exports);const{formatters}=module.exports;formatters.j=function(v){try{return JSON.stringify(v)}catch(error){return"[UnexpectedJSONParseError]: "+error.message}}}).call(this)}).call(this,require("_process"))},{"./common":70,_process:132}],70:[function(require,module){module.exports=function(env){function createDebug(namespace){function debug(...args){if(!debug.enabled)return;const self=debug,curr=+new Date,ms=curr-(prevTime||curr);self.diff=ms,self.prev=prevTime,self.curr=curr,prevTime=curr,args[0]=createDebug.coerce(args[0]),"string"!=typeof args[0]&&args.unshift("%O");let index=0;args[0]=args[0].replace(/%([a-zA-Z%])/g,(match,format)=>{if("%%"===match)return"%";index++;const formatter=createDebug.formatters[format];if("function"==typeof formatter){const val=args[index];match=formatter.call(self,val),args.splice(index,1),index--}return match}),createDebug.formatArgs.call(self,args);const logFn=self.log||createDebug.log;logFn.apply(self,args)}let enableOverride=null,prevTime;return debug.namespace=namespace,debug.useColors=createDebug.useColors(),debug.color=createDebug.selectColor(namespace),debug.extend=extend,debug.destroy=createDebug.destroy,Object.defineProperty(debug,"enabled",{enumerable:!0,configurable:!1,get:()=>null===enableOverride?createDebug.enabled(namespace):enableOverride,set:v=>{enableOverride=v}}),"function"==typeof createDebug.init&&createDebug.init(debug),debug}function extend(namespace,delimiter){const newDebug=createDebug(this.namespace+("undefined"==typeof delimiter?":":delimiter)+namespace);return newDebug.log=this.log,newDebug}function toNamespace(regexp){return regexp.toString().substring(2,regexp.toString().length-2).replace(/\.\*\?$/,"*")}return createDebug.debug=createDebug,createDebug.default=createDebug,createDebug.coerce=function(val){return val instanceof Error?val.stack||val.message:val},createDebug.disable=function(){const namespaces=[...createDebug.names.map(toNamespace),...createDebug.skips.map(toNamespace).map(namespace=>"-"+namespace)].join(",");return createDebug.enable(""),namespaces},createDebug.enable=function(namespaces){createDebug.save(namespaces),createDebug.names=[],createDebug.skips=[];let i;const split=("string"==typeof namespaces?namespaces:"").split(/[\s,]+/),len=split.length;for(i=0;i{createDebug[key]=env[key]}),createDebug.names=[],createDebug.skips=[],createDebug.formatters={},createDebug.selectColor=function(namespace){let hash=0;for(let i=0;i=parts.length){var desc=$gOPD(value,parts[i]);if(!allowMissing&&!(parts[i]in value))throw new $TypeError("base intrinsic for "+name+" exists, but the property is not available.");value=desc&&"get"in desc&&!("originalValue"in desc.get)?desc.get:value[parts[i]]}else value=value[parts[i]];return value}},{"function-bind":82,"has-symbols":84}],74:[function(require,module){'use strict';var bind=require("function-bind"),GetIntrinsic=require("../GetIntrinsic"),$apply=GetIntrinsic("%Function.prototype.apply%"),$call=GetIntrinsic("%Function.prototype.call%"),$reflectApply=GetIntrinsic("%Reflect.apply%",!0)||bind.call($call,$apply),$defineProperty=GetIntrinsic("%Object.defineProperty%",!0);if($defineProperty)try{$defineProperty({},"a",{value:1})}catch(e){$defineProperty=null}module.exports=function(){return $reflectApply(bind,$call,arguments)};var applyBind=function(){return $reflectApply(bind,$apply,arguments)};$defineProperty?$defineProperty(module.exports,"apply",{value:applyBind}):module.exports.apply=applyBind},{"../GetIntrinsic":73,"function-bind":82}],75:[function(require,module){'use strict';var GetIntrinsic=require("../GetIntrinsic"),callBind=require("./callBind"),$indexOf=callBind(GetIntrinsic("String.prototype.indexOf"));module.exports=function(name,allowMissing){var intrinsic=GetIntrinsic(name,!!allowMissing);return"function"==typeof intrinsic&&$indexOf(name,".prototype.")?callBind(intrinsic):intrinsic}},{"../GetIntrinsic":73,"./callBind":74}],76:[function(require,module){'use strict';var GetIntrinsic=require("../GetIntrinsic"),$gOPD=GetIntrinsic("%Object.getOwnPropertyDescriptor%");if($gOPD)try{$gOPD([],"length")}catch(e){$gOPD=null}module.exports=$gOPD},{"../GetIntrinsic":73}],77:[function(require,module){/*! * escape-html * Copyright(c) 2012-2013 TJ Holowaychuk * Copyright(c) 2015 Andreas Lubbe * Copyright(c) 2015 Tiancheng "Timothy" Gu * MIT Licensed - */'use strict';module.exports=function(string){var str=""+string,match=/["'&<>]/.exec(str);if(!match)return str;var html="",index=0,lastIndex=0,escape;for(index=match.index;index{this.push(toBuffer(reader.result))},reader.onerror=()=>{this.emit("error",reader.error)},this.reader=reader,this._generateHeaderBlocks(file,opts,(err,blocks)=>err?this.emit("error",err):void(Array.isArray(blocks)&&blocks.forEach(block=>this.push(block)),this._ready=!0,this.emit("_ready")))}_generateHeaderBlocks(file,opts,callback){callback(null,[])}_read(){if(!this._ready)return void this.once("_ready",this._read.bind(this));const startOffset=this._offset;let endOffset=this._offset+this._chunkSize;return endOffset>this._size&&(endOffset=this._size),startOffset===this._size?(this.destroy(),void this.push(null)):void(this.reader.readAsArrayBuffer(this._file.slice(startOffset,endOffset)),this._offset=endOffset)}destroy(){if(this._file=null,this.reader){this.reader.onload=null,this.reader.onerror=null;try{this.reader.abort()}catch(e){}}this.reader=null}}},{"readable-stream":157,"typedarray-to-buffer":189}],79:[function(require,module){var hasOwn=Object.prototype.hasOwnProperty,toString=Object.prototype.toString;module.exports=function(obj,fn,ctx){if("[object Function]"!==toString.call(fn))throw new TypeError("iterator must be a function");var l=obj.length;if(l===+l)for(var i=0;iself.maxSockets||freeLen>=self.maxFreeSockets?socket.destroy():(freeSockets=freeSockets||[],self.freeSockets[name]=freeSockets,socket.setKeepAlive(!0,self.keepAliveMsecs),socket.unref(),socket._httpMessage=null,self.removeSocket(socket,options),freeSockets.push(socket))}else socket.destroy()}})}const net=require("net"),util=require("util"),EventEmitter=require("events"),debug=util.debuglog("http");util.inherits(Agent,EventEmitter),exports.Agent=Agent,Agent.defaultMaxSockets=1/0,Agent.prototype.createConnection=net.createConnection,Agent.prototype.getName=function(options){var name=options.host||"localhost";return name+=":",options.port&&(name+=options.port),name+=":",options.localAddress&&(name+=options.localAddress),(4===options.family||6===options.family)&&(name+=":"+options.family),name},Agent.prototype.addRequest=function(req,options){"string"==typeof options&&(options={host:options,port:arguments[2],localAddress:arguments[3]}),options=util._extend({},options),options=util._extend(options,this.options);var name=this.getName(options);this.sockets[name]||(this.sockets[name]=[]);var freeLen=this.freeSockets[name]?this.freeSockets[name].length:0,sockLen=freeLen+this.sockets[name].length;if(freeLen){var socket=this.freeSockets[name].shift();debug("have free socket"),this.freeSockets[name].length||delete this.freeSockets[name],socket.ref(),req.onSocket(socket),this.sockets[name].push(socket)}else sockLen=this.maxHeaderPairs||this._headers.length=ch)||!!(65<=ch&&90>=ch)||!(45!==ch)||!!(48<=ch&&57>=ch)||34!==ch&&40!==ch&&41!==ch&&44!==ch&&(!!(33<=ch&&46>=ch)||!(124!==ch&&126!==ch))}const binding=require("http-parser-js"),methods=binding.methods,HTTPParser=binding.HTTPParser,FreeList=require("freelist").FreeList,incoming=require("./_http_incoming"),IncomingMessage=incoming.IncomingMessage,readStart=incoming.readStart,readStop=incoming.readStop,debug=require("util").debuglog("http");exports.debug=debug,exports.CRLF="\r\n",exports.chunkExpression=/chunk/i,exports.continueExpression=/100-continue/i,exports.methods=methods;const kOnHeaders=0|HTTPParser.kOnHeaders,kOnHeadersComplete=0|HTTPParser.kOnHeadersComplete,kOnBody=0|HTTPParser.kOnBody,kOnMessageComplete=0|HTTPParser.kOnMessageComplete,kOnExecute=0|HTTPParser.kOnExecute;var parsers=new FreeList("parsers",1e3,function(){var parser=new HTTPParser(HTTPParser.REQUEST);return parser._headers=[],parser._url="",parser._consumed=!1,parser.socket=null,parser.incoming=null,parser.outgoing=null,parser[kOnHeaders]=parserOnHeaders,parser[kOnHeadersComplete]=parserOnHeadersComplete,parser[kOnBody]=parserOnBody,parser[kOnMessageComplete]=parserOnMessageComplete,parser[kOnExecute]=null,parser});exports.parsers=parsers,exports.freeParser=function(parser,req,socket){parser&&(parser._headers=[],parser.onIncoming=null,parser._consumed&&parser.unconsume(),parser._consumed=!1,parser.socket&&(parser.socket.parser=null),parser.socket=null,parser.incoming=null,parser.outgoing=null,parser[kOnExecute]=null,!1===parsers.free(parser)&&parser.close(),parser=null),req&&(req.parser=null),socket&&(socket.parser=null)},exports.httpSocketSetup=function(socket){socket.removeListener("drain",ondrain),socket.on("drain",ondrain)},exports._checkIsHttpToken=function(val){if("string"!=typeof val||0===val.length)return!1;if(!isValidTokenChar(val.charCodeAt(0)))return!1;const len=val.length;if(1val.length)return!1;var c=val.charCodeAt(0);if(31>=c&&9!==c||255val.length)return!1;if(c=val.charCodeAt(1),31>=c&&9!==c||255val.length)return!1;if(c=val.charCodeAt(2),31>=c&&9!==c||255=c&&9!==c||255arguments.length)throw new Error("\"name\" argument is required for getHeader(name)");if(this._headers){var key=name.toLowerCase();return this._headers[key]}},OutgoingMessage.prototype.removeHeader=function(name){if(1>arguments.length)throw new Error("\"name\" argument is required for removeHeader(name)");if(this._header)throw new Error("Can't remove headers after they are sent");var key=name.toLowerCase();"date"===key?this.sendDate=!1:automaticHeaders[key]&&(this._removedHeader[key]=!0),this._headers&&(delete this._headers[key],delete this._headerNames[key])},OutgoingMessage.prototype._renderHeaders=function(){if(this._header)throw new Error("Can't render headers after they are sent to the client");var headersMap=this._headers;if(!headersMap)return{};for(var headers={},keys=Object.keys(headersMap),headerNames=this._headerNames,i=0,l=keys.length,key;i{this.emit("finish")};return ret=this._hasBody&&this.chunkedEncoding?this._send("0\r\n"+this._trailer+"\r\n","binary",finish):this._send("","binary",finish),this.connection&&data&&this.connection.uncork(),this.finished=!0,debug("outgoing message end."),0===this.output.length&&this.connection&&this.connection._httpMessage===this&&this._finish(),ret},OutgoingMessage.prototype._finish=function(){assert(this.connection),this.emit("prefinish")},OutgoingMessage.prototype._flush=function(){var socket=this.socket,ret;socket&&socket.writable&&(ret=this._flushOutput(socket),this.finished?this._finish():ret&&this.emit("drain"))},OutgoingMessage.prototype._flushOutput=function(socket){var outputLength=this.output.length,ret;if(0>=outputLength)return ret;var output=this.output,outputEncodings=this.outputEncodings,outputCallbacks=this.outputCallbacks;socket.cork();for(var i=0;ireq.httpVersionMajor||1>req.httpVersionMinor)&&(this.useChunkedEncodingByDefault=chunkExpression.test(req.headers.te),this.shouldKeepAlive=!1)}function onServerResponseClose(){this._httpMessage&&this._httpMessage.emit("close")}function Server(requestListener){return this instanceof Server?void(net.Server.call(this,{allowHalfOpen:!0}),requestListener&&this.addListener("request",requestListener),this.httpAllowHalfOpen=!1,this.addListener("connection",connectionListener),this.timeout=120000,this._pendingResponseData=0):new Server(requestListener)}function connectionListener(socket){function updateOutgoingData(delta){if(outgoingData+=delta,socket._paused&&outgoingData{}),self.emit("clientError",e,this)||this.destroy(e)}function socketOnData(d){assert(!socket._paused),debug("SERVER socketOnData %d",d.length);var ret=parser.execute(d);onParserExecuteCommon(ret,d)}function onParserExecuteCommon(ret,d){if(ret instanceof Error)debug("parse error"),socketOnError.call(socket,ret);else if(parser.incoming&&parser.incoming.upgrade){var req=parser.incoming;debug("SERVER upgrade or connect",req.method),d||(d=parser.getCurrentBuffer()),socket.removeListener("data",socketOnData),socket.removeListener("end",socketOnEnd),socket.removeListener("close",serverSocketCloseListener),unconsume(parser,socket),parser.finish(),freeParser(parser,req,null),parser=null;var eventName="CONNECT"===req.method?"connect":"upgrade";if(0socket._writableState.highWaterMark;socket._paused&&!needPause&&(socket._paused=!1,socket.parser&&socket.parser.resume(),socket.resume())}function parserOnIncoming(req,shouldKeepAlive){if(incoming.push(req),!socket._paused){var needPause=socket._writableState.needDrain||outgoingData>=socket._writableState.highWaterMark;needPause&&(socket._paused=!0,socket.pause())}var res=new ServerResponse(req);return res._onPendingData=updateOutgoingData,res.shouldKeepAlive=shouldKeepAlive,socket._httpMessage?outgoing.push(res):res.assignSocket(socket),res.on("finish",function(){if(assert(0===incoming.length||incoming[0]===req),incoming.shift(),req._consuming||req._readableState.resumeScheduled||req._dump(),res.detachSocket(socket),res._last)socket.destroySoon();else{var m=outgoing.shift();m&&m.assignSocket(socket)}}),void 0!==req.headers.expect&&1==req.httpVersionMajor&&1==req.httpVersionMinor?continueExpression.test(req.headers.expect)?(res._expect_continue=!0,0statusCode||999=statusCode)&&(this._hasBody=!1),this._expect_continue&&!this._sent100&&(this.shouldKeepAlive=!1),this._storeHeader(statusLine,headers)},ServerResponse.prototype.writeHeader=function(){this.writeHead.apply(this,arguments)},util.inherits(Server,net.Server),Server.prototype.setTimeout=function(msecs,callback){return this.timeout=msecs,callback&&this.on("timeout",callback),this},exports.Server=Server,exports._connectionListener=connectionListener},{"./_http_common":88,"./_http_outgoing":90,assert:11,"http-parser-js":93,net:65,util:58}],92:[function(require,module,exports){'use strict';function Client(port,host){return this instanceof Client?void(EventEmitter.call(this),host=host||"localhost",port=port||80,this.host=host,this.port=port,this.agent=new Agent({host:host,port:port,maxSockets:1})):new Client(port,host)}const util=require("util"),internalUtil=util,EventEmitter=require("events");exports.IncomingMessage=require("./_http_incoming").IncomingMessage;const common=require("./_http_common");exports.METHODS=common.methods.slice().sort(),exports.OutgoingMessage=require("./_http_outgoing").OutgoingMessage;const server=require("./_http_server");exports.ServerResponse=server.ServerResponse,exports.STATUS_CODES=server.STATUS_CODES;const agent=require("./_http_agent"),Agent=exports.Agent=agent.Agent;exports.globalAgent=agent.globalAgent;const client=require("./_http_client"),ClientRequest=exports.ClientRequest=client.ClientRequest;exports.request=function(options,cb){return new ClientRequest(options,cb)},exports.get=function(options,cb){var req=exports.request(options,cb);return req.end(),req},exports._connectionListener=server._connectionListener;const Server=exports.Server=server.Server;exports.createServer=function(requestListener){return new Server(requestListener)},util.inherits(Client,EventEmitter),Client.prototype.request=function(method,path,headers){var self=this,options={};options.host=self.host,options.port=self.port,"/"===method[0]&&(headers=path,path=method,method="GET"),options.method=method,options.path=path,options.headers=headers,options.agent=self.agent;var c=new ClientRequest(options);return c.on("error",function(e){self.emit("error",e)}),c.on("socket",function(s){s.on("end",function(){if(self._decoder){var ret=self._decoder.end();ret&&self.emit("data",ret)}self.emit("end")})}),c},exports.Client=internalUtil.deprecate(Client,"http.Client is deprecated."),exports.createClient=internalUtil.deprecate(function(port,host){return new Client(port,host)},"http.createClient is deprecated. Use http.request instead.")},{"./_http_agent":86,"./_http_client":87,"./_http_common":88,"./_http_incoming":89,"./_http_outgoing":90,"./_http_server":91,events:39,util:58}],93:[function(require,module,exports){function HTTPParser(type){assert.ok(type===HTTPParser.REQUEST||type===HTTPParser.RESPONSE),this.type=type,this.state=type+"_LINE",this.info={headers:[],upgrade:!1},this.trailers=[],this.line="",this.isChunked=!1,this.connection="",this.headerSize=0,this.body_bytes=null,this.isUserCall=!1,this.hadError=!1}function parseErrorCode(code){var err=new Error("Parse Error");return err.code=code,err}var assert=require("assert");exports.HTTPParser=HTTPParser,HTTPParser.encoding="ascii",HTTPParser.maxHeaderSize=81920,HTTPParser.REQUEST="REQUEST",HTTPParser.RESPONSE="RESPONSE";var kOnHeaders=HTTPParser.kOnHeaders=0,kOnHeadersComplete=HTTPParser.kOnHeadersComplete=1,kOnBody=HTTPParser.kOnBody=2,kOnMessageComplete=HTTPParser.kOnMessageComplete=3;HTTPParser.prototype[kOnHeaders]=HTTPParser.prototype[kOnHeadersComplete]=HTTPParser.prototype[kOnBody]=HTTPParser.prototype[kOnMessageComplete]=function(){};var compatMode0_12=!0;Object.defineProperty(HTTPParser,"kOnExecute",{get:function(){return compatMode0_12=!1,4}});var methods=exports.methods=HTTPParser.methods=["DELETE","GET","HEAD","POST","PUT","CONNECT","OPTIONS","TRACE","COPY","LOCK","MKCOL","MOVE","PROPFIND","PROPPATCH","SEARCH","UNLOCK","BIND","REBIND","UNBIND","ACL","REPORT","MKACTIVITY","CHECKOUT","MERGE","M-SEARCH","NOTIFY","SUBSCRIBE","UNSUBSCRIBE","PATCH","PURGE","MKCALENDAR","LINK","UNLINK"],method_connect=methods.indexOf("CONNECT");HTTPParser.prototype.reinitialize=HTTPParser,HTTPParser.prototype.close=HTTPParser.prototype.pause=HTTPParser.prototype.resume=HTTPParser.prototype.free=function(){},HTTPParser.prototype._compatMode0_11=!1,HTTPParser.prototype.getAsyncId=function(){return 0};var headerState={REQUEST_LINE:!0,RESPONSE_LINE:!0,HEADER:!0};HTTPParser.prototype.execute=function(chunk,start,length){if(!(this instanceof HTTPParser))throw new TypeError("not a HTTPParser");start=start||0,length="number"==typeof length?length:chunk.length,this.chunk=chunk,this.offset=start;var end=this.end=start+length;try{for(;this.offsetHTTPParser.maxHeaderSize)?new Error("max header size exceeded"):length};var stateFinishAllowed={REQUEST_LINE:!0,RESPONSE_LINE:!0,BODY_RAW:!0};HTTPParser.prototype.finish=function(){return this.hadError?void 0:stateFinishAllowed[this.state]?void("BODY_RAW"===this.state&&this.userCall()(this[kOnMessageComplete]())):new Error("invalid state for EOF")},HTTPParser.prototype.consume=HTTPParser.prototype.unconsume=HTTPParser.prototype.getCurrentBuffer=function(){},HTTPParser.prototype.userCall=function(){this.isUserCall=!0;var self=this;return function(ret){return self.isUserCall=!1,ret}},HTTPParser.prototype.nextRequest=function(){this.userCall()(this[kOnMessageComplete]()),this.reinitialize(this.type)},HTTPParser.prototype.consumeLine=function(){for(var end=this.end,chunk=this.chunk,i=this.offset;i */exports.read=function(buffer,offset,isLE,mLen,nBytes){var eLen=8*nBytes-mLen-1,eMax=(1<>1,nBits=-7,i=isLE?nBytes-1:0,d=isLE?-1:1,s=buffer[offset+i],e,m;for(i+=d,e=s&(1<<-nBits)-1,s>>=-nBits,nBits+=eLen;0>=-nBits,nBits+=mLen;0>1,rt=23===mLen?_Mathpow(2,-24)-_Mathpow(2,-77):0,i=isLE?0:nBytes-1,d=isLE?1:-1,s=0>value||0===value&&0>1/value?1:0,e,m,c;for(value=_Mathabs(value),isNaN(value)||value===1/0?(m=isNaN(value)?1:0,e=eMax):(e=_Mathfloor(_Mathlog(value)/_MathLN),1>value*(c=_Mathpow(2,-e))&&(e--,c*=2),value+=1<=e+eBias?rt/c:rt*_Mathpow(2,1-eBias),2<=value*c&&(e++,c/=2),e+eBias>=eMax?(m=0,e=eMax):1<=e+eBias?(m=(value*c-1)*_Mathpow(2,mLen),e+=eBias):(m=value*_Mathpow(2,eBias-1)*_Mathpow(2,mLen),e=0));8<=mLen;buffer[offset+i]=255&m,i+=d,m/=256,mLen-=8);for(e=e< */const queueMicrotask=require("queue-microtask");module.exports=class ImmediateStore{constructor(store){if(this.store=store,this.chunkLength=store.chunkLength,!this.store||!this.store.get||!this.store.put)throw new Error("First argument must be abstract-chunk-store compliant");this.mem=[]}put(index,buf,cb){this.mem[index]=buf,this.store.put(index,buf,err=>{this.mem[index]=null,cb&&cb(err)})}get(index,opts,cb){if("function"==typeof opts)return this.get(index,null,opts);let memoryBuffer=this.mem[index];if(!memoryBuffer)return this.store.get(index,opts,cb);if(opts){const start=opts.offset||0,end=opts.length?start+opts.length:memoryBuffer.length;memoryBuffer=memoryBuffer.slice(start,end)}queueMicrotask(()=>{cb&&cb(null,memoryBuffer)})}close(cb){this.store.close(cb)}destroy(cb){this.store.destroy(cb)}}},{"queue-microtask":138}],97:[function(require,module){module.exports="function"==typeof Object.create?function(ctor,superCtor){superCtor&&(ctor.super_=superCtor,ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:!1,writable:!0,configurable:!0}}))}:function(ctor,superCtor){if(superCtor){ctor.super_=superCtor;var TempCtor=function(){};TempCtor.prototype=superCtor.prototype,ctor.prototype=new TempCtor,ctor.prototype.constructor=ctor}}},{}],98:[function(require,module){(function(root){'use strict';function expandIPv6(string,parts){if(string.indexOf("::")!==string.lastIndexOf("::"))return null;let colonCount=0,lastColon=-1,zoneId=(string.match(ipv6Regexes.zoneIndex)||[])[0],replacement,replacementCount;for(zoneId&&(zoneId=zoneId.substring(1),string=string.replace(/%.+$/,""));0<=(lastColon=string.indexOf(":",lastColon+1));)colonCount++;if("::"===string.substr(0,2)&&colonCount--,"::"===string.substr(-2,2)&&colonCount--,colonCount>parts)return null;for(replacementCount=parts-colonCount,replacement=":";replacementCount--;)replacement+="0:";return string=string.replace("::",replacement),":"===string[0]&&(string=string.slice(1)),":"===string[string.length-1]&&(string=string.slice(0,-1)),parts=function(){const ref=string.split(":"),results=[];for(let i=0;ishift&&(shift=0),first[part]>>shift!=second[part]>>shift)return!1;cidrBits-=partSize,part+=1}return!0}function parseIntAuto(string){if(hexRegex.test(string))return parseInt(string,16);if("0"===string[0]&&!isNaN(parseInt(string[1],10))){if(octalRegex.test(string))return parseInt(string,8);throw new Error(`ipaddr: cannot parse ${string} as octal`)}return parseInt(string,10)}function padPart(part,length){for(;part.length=octet))throw new Error("ipaddr: ipv4 octet should fit in 8 bits");this.octets=octets}return IPv4.prototype.SpecialRanges={unspecified:[[new IPv4([0,0,0,0]),8]],broadcast:[[new IPv4([255,255,255,255]),32]],multicast:[[new IPv4([224,0,0,0]),4]],linkLocal:[[new IPv4([169,254,0,0]),16]],loopback:[[new IPv4([127,0,0,0]),8]],carrierGradeNat:[[new IPv4([100,64,0,0]),10]],private:[[new IPv4([10,0,0,0]),8],[new IPv4([172,16,0,0]),12],[new IPv4([192,168,0,0]),16]],reserved:[[new IPv4([192,0,0,0]),24],[new IPv4([192,0,2,0]),24],[new IPv4([192,88,99,0]),24],[new IPv4([198,51,100,0]),24],[new IPv4([203,0,113,0]),24],[new IPv4([240,0,0,0]),4]]},IPv4.prototype.kind=function(){return"ipv4"},IPv4.prototype.match=function(other,cidrRange){let ref;if(void 0===cidrRange&&(ref=other,other=ref[0],cidrRange=ref[1]),"ipv4"!==other.kind())throw new Error("ipaddr: cannot match ipv4 address with non-ipv4 one");return matchCIDR(this.octets,other.octets,8,cidrRange)},IPv4.prototype.prefixLengthFromSubnetMask=function(){let cidr=0,stop=!1;const zerotable={0:8,128:7,192:6,224:5,240:4,248:3,252:2,254:1,255:0};let i,octet,zeros;for(i=3;0<=i;i-=1)if(octet=this.octets[i],octet in zerotable){if(zeros=zerotable[octet],stop&&0!==zeros)return null;8!==zeros&&(stop=!0),cidr+=zeros}else return null;return 32-cidr},IPv4.prototype.range=function(){return ipaddr.subnetMatch(this,this.SpecialRanges)},IPv4.prototype.toByteArray=function(){return this.octets.slice(0)},IPv4.prototype.toIPv4MappedAddress=function(){return ipaddr.IPv6.parse(`::ffff:${this.toString()}`)},IPv4.prototype.toNormalizedString=function(){return this.toString()},IPv4.prototype.toString=function(){return this.octets.join(".")},IPv4}(),ipaddr.IPv4.broadcastAddressFromCIDR=function(string){try{const cidr=this.parseCIDR(string),ipInterfaceOctets=cidr[0].toByteArray(),subnetMaskOctets=this.subnetMaskFromPrefixLength(cidr[1]).toByteArray(),octets=[];for(let i=0;4>i;)octets.push(parseInt(ipInterfaceOctets[i],10)|255^parseInt(subnetMaskOctets[i],10)),i++;return new this(octets)}catch(e){throw new Error("ipaddr: the address does not have IPv4 CIDR format")}},ipaddr.IPv4.isIPv4=function(string){return null!==this.parser(string)},ipaddr.IPv4.isValid=function(string){try{return new this(this.parser(string)),!0}catch(e){return!1}},ipaddr.IPv4.isValidFourPartDecimal=function(string){return!!(ipaddr.IPv4.isValid(string)&&string.match(/^(0|[1-9]\d*)(\.(0|[1-9]\d*)){3}$/))},ipaddr.IPv4.networkAddressFromCIDR=function(string){let cidr,i,ipInterfaceOctets,octets,subnetMaskOctets;try{for(cidr=this.parseCIDR(string),ipInterfaceOctets=cidr[0].toByteArray(),subnetMaskOctets=this.subnetMaskFromPrefixLength(cidr[1]).toByteArray(),octets=[],i=0;4>i;)octets.push(parseInt(ipInterfaceOctets[i],10)&parseInt(subnetMaskOctets[i],10)),i++;return new this(octets)}catch(e){throw new Error("ipaddr: the address does not have IPv4 CIDR format")}},ipaddr.IPv4.parse=function(string){const parts=this.parser(string);if(null===parts)throw new Error("ipaddr: string is not formatted like an IPv4 Address");return new this(parts)},ipaddr.IPv4.parseCIDR=function(string){let match;if(match=string.match(/^(.+)\/(\d+)$/)){const maskLength=parseInt(match[2]);if(0<=maskLength&&32>=maskLength){const parsed=[this.parse(match[1]),maskLength];return Object.defineProperty(parsed,"toString",{value:function(){return this.join("/")}}),parsed}}throw new Error("ipaddr: string is not formatted like an IPv4 CIDR range")},ipaddr.IPv4.parser=function(string){let match,part,value;if(match=string.match(ipv4Regexes.fourOctet))return function(){const ref=match.slice(1,6),results=[];for(let i=0;ivalue)throw new Error("ipaddr: address outside defined range");return function(){const results=[];let shift;for(shift=0;24>=shift;shift+=8)results.push(255&value>>shift);return results}().reverse()}return(match=string.match(ipv4Regexes.twoOctet))?function(){const ref=match.slice(1,4),results=[];if(value=parseIntAuto(ref[1]),16777215value)throw new Error("ipaddr: address outside defined range");return results.push(parseIntAuto(ref[0])),results.push(255&value>>16),results.push(255&value>>8),results.push(255&value),results}():(match=string.match(ipv4Regexes.threeOctet))?function(){const ref=match.slice(1,5),results=[];if(value=parseIntAuto(ref[2]),65535value)throw new Error("ipaddr: address outside defined range");return results.push(parseIntAuto(ref[0])),results.push(parseIntAuto(ref[1])),results.push(255&value>>8),results.push(255&value),results}():null},ipaddr.IPv4.subnetMaskFromPrefixLength=function(prefix){if(prefix=parseInt(prefix),0>prefix||32filledOctetCount&&(octets[filledOctetCount]=_Mathpow(2,prefix%8)-1<<8-prefix%8),new this(octets)},ipaddr.IPv6=function(){function IPv6(parts,zoneId){let i,part;if(16===parts.length)for(this.parts=[],i=0;14>=i;i+=2)this.parts.push(parts[i]<<8|parts[i+1]);else if(8===parts.length)this.parts=parts;else throw new Error("ipaddr: ipv6 part count should be 8 or 16");for(i=0;i=part))throw new Error("ipaddr: ipv6 part should fit in 16 bits");zoneId&&(this.zoneId=zoneId)}return IPv6.prototype.SpecialRanges={unspecified:[new IPv6([0,0,0,0,0,0,0,0]),128],linkLocal:[new IPv6([65152,0,0,0,0,0,0,0]),10],multicast:[new IPv6([65280,0,0,0,0,0,0,0]),8],loopback:[new IPv6([0,0,0,0,0,0,0,1]),128],uniqueLocal:[new IPv6([64512,0,0,0,0,0,0,0]),7],ipv4Mapped:[new IPv6([0,0,0,0,0,65535,0,0]),96],rfc6145:[new IPv6([0,0,0,0,65535,0,0,0]),96],rfc6052:[new IPv6([100,65435,0,0,0,0,0,0]),96],"6to4":[new IPv6([8194,0,0,0,0,0,0,0]),16],teredo:[new IPv6([8193,0,0,0,0,0,0,0]),32],reserved:[[new IPv6([8193,3512,0,0,0,0,0,0]),32]]},IPv6.prototype.isIPv4MappedAddress=function(){return"ipv4Mapped"===this.range()},IPv6.prototype.kind=function(){return"ipv6"},IPv6.prototype.match=function(other,cidrRange){let ref;if(void 0===cidrRange&&(ref=other,other=ref[0],cidrRange=ref[1]),"ipv6"!==other.kind())throw new Error("ipaddr: cannot match ipv6 address with non-ipv6 one");return matchCIDR(this.parts,other.parts,16,cidrRange)},IPv6.prototype.prefixLengthFromSubnetMask=function(){let cidr=0,stop=!1;const zerotable={0:16,32768:15,49152:14,57344:13,61440:12,63488:11,64512:10,65024:9,65280:8,65408:7,65472:6,65504:5,65520:4,65528:3,65532:2,65534:1,65535:0};let part,zeros;for(let i=7;0<=i;i-=1)if(part=this.parts[i],part in zerotable){if(zeros=zerotable[part],stop&&0!==zeros)return null;16!==zeros&&(stop=!0),cidr+=zeros}else return null;return 128-cidr},IPv6.prototype.range=function(){return ipaddr.subnetMatch(this,this.SpecialRanges)},IPv6.prototype.toByteArray=function(){let part;const bytes=[],ref=this.parts;for(let i=0;i>8),bytes.push(255&part);return bytes},IPv6.prototype.toFixedLengthString=function(){const addr=function(){const results=[];for(let i=0;i>8,255&high,low>>8,255&low])},IPv6.prototype.toNormalizedString=function(){const addr=function(){const results=[];for(let i=0;ibestMatchLength&&(bestMatchIndex=match.index,bestMatchLength=match[0].length);return 0>bestMatchLength?string:`${string.substring(0,bestMatchIndex)}::${string.substring(bestMatchIndex+bestMatchLength)}`},IPv6.prototype.toString=function(){return this.toNormalizedString().replace(/((^|:)(0(:|$))+)/,"::")},IPv6}(),ipaddr.IPv6.isIPv6=function(string){return null!==this.parser(string)},ipaddr.IPv6.isValid=function(string){if("string"==typeof string&&-1===string.indexOf(":"))return!1;try{const addr=this.parser(string);return new this(addr.parts,addr.zoneId),!0}catch(e){return!1}},ipaddr.IPv6.parse=function(string){const addr=this.parser(string);if(null===addr.parts)throw new Error("ipaddr: string is not formatted like an IPv6 Address");return new this(addr.parts,addr.zoneId)},ipaddr.IPv6.parseCIDR=function(string){let maskLength,match,parsed;if((match=string.match(/^(.+)\/(\d+)$/))&&(maskLength=parseInt(match[2]),0<=maskLength&&128>=maskLength))return parsed=[this.parse(match[1]),maskLength],Object.defineProperty(parsed,"toString",{value:function(){return this.join("/")}}),parsed;throw new Error("ipaddr: string is not formatted like an IPv6 CIDR range")},ipaddr.IPv6.parser=function(string){let addr,i,match,octet,octets,zoneId;if(match=string.match(ipv6Regexes.deprecatedTransitional))return this.parser(`::ffff:${match[1]}`);if(ipv6Regexes.native.test(string))return expandIPv6(string,8);if((match=string.match(ipv6Regexes.transitional))&&(zoneId=match[6]||"",addr=expandIPv6(match[1].slice(0,-1)+zoneId,6),addr.parts)){for(octets=[parseInt(match[2]),parseInt(match[3]),parseInt(match[4]),parseInt(match[5])],i=0;i=octet))return null;return addr.parts.push(octets[0]<<8|octets[1]),addr.parts.push(octets[2]<<8|octets[3]),{parts:addr.parts,zoneId:addr.zoneId}}return null},ipaddr.fromByteArray=function(bytes){const length=bytes.length;if(4===length)return new ipaddr.IPv4(bytes);if(16===length)return new ipaddr.IPv6(bytes);throw new Error("ipaddr: the binary input is neither an IPv6 nor IPv4 address")},ipaddr.isValid=function(string){return ipaddr.IPv6.isValid(string)||ipaddr.IPv4.isValid(string)},ipaddr.parse=function(string){if(ipaddr.IPv6.isValid(string))return ipaddr.IPv6.parse(string);if(ipaddr.IPv4.isValid(string))return ipaddr.IPv4.parse(string);throw new Error("ipaddr: the address has neither IPv6 nor IPv4 format")},ipaddr.parseCIDR=function(string){try{return ipaddr.IPv6.parseCIDR(string)}catch(e){try{return ipaddr.IPv4.parseCIDR(string)}catch(e2){throw new Error("ipaddr: the address has neither IPv6 nor IPv4 CIDR format")}}},ipaddr.process=function(string){const addr=this.parse(string);return"ipv6"===addr.kind()&&addr.isIPv4MappedAddress()?addr.toIPv4Address():addr},ipaddr.subnetMatch=function(address,rangeList,defaultName){let i,rangeName,rangeSubnets,subnet;for(rangeName in(void 0===defaultName||null===defaultName)&&(defaultName="unicast"),rangeList)if(Object.prototype.hasOwnProperty.call(rangeList,rangeName))for(rangeSubnets=rangeList[rangeName],rangeSubnets[0]&&!(rangeSubnets[0]instanceof Array)&&(rangeSubnets=[rangeSubnets]),i=0;i127)return!1;return!0}},{}],101:[function(require,module){function isBuffer(obj){return!!obj.constructor&&"function"==typeof obj.constructor.isBuffer&&obj.constructor.isBuffer(obj)}function isSlowBuffer(obj){return"function"==typeof obj.readFloatLE&&"function"==typeof obj.slice&&isBuffer(obj.slice(0,0))}/*! + */'use strict';module.exports=function(string){var str=""+string,match=/["'&<>]/.exec(str);if(!match)return str;var html="",index=0,lastIndex=0,escape;for(index=match.index;index{this.push(toBuffer(reader.result))},reader.onerror=()=>{this.emit("error",reader.error)},this.reader=reader,this._generateHeaderBlocks(file,opts,(err,blocks)=>err?this.emit("error",err):void(Array.isArray(blocks)&&blocks.forEach(block=>this.push(block)),this._ready=!0,this.emit("_ready")))}_generateHeaderBlocks(file,opts,callback){callback(null,[])}_read(){if(!this._ready)return void this.once("_ready",this._read.bind(this));const startOffset=this._offset;let endOffset=this._offset+this._chunkSize;return endOffset>this._size&&(endOffset=this._size),startOffset===this._size?(this.destroy(),void this.push(null)):void(this.reader.readAsArrayBuffer(this._file.slice(startOffset,endOffset)),this._offset=endOffset)}destroy(){if(this._file=null,this.reader){this.reader.onload=null,this.reader.onerror=null;try{this.reader.abort()}catch(e){}}this.reader=null}}},{"readable-stream":157,"typedarray-to-buffer":189}],79:[function(require,module){var hasOwn=Object.prototype.hasOwnProperty,toString=Object.prototype.toString;module.exports=function(obj,fn,ctx){if("[object Function]"!==toString.call(fn))throw new TypeError("iterator must be a function");var l=obj.length;if(l===+l)for(var i=0;iself.maxSockets||freeLen>=self.maxFreeSockets?socket.destroy():(freeSockets=freeSockets||[],self.freeSockets[name]=freeSockets,socket.setKeepAlive(!0,self.keepAliveMsecs),socket.unref(),socket._httpMessage=null,self.removeSocket(socket,options),freeSockets.push(socket))}else socket.destroy()}})}const net=require("net"),util=require("util"),EventEmitter=require("events"),debug=util.debuglog("http");util.inherits(Agent,EventEmitter),exports.Agent=Agent,Agent.defaultMaxSockets=1/0,Agent.prototype.createConnection=net.createConnection,Agent.prototype.getName=function(options){var name=options.host||"localhost";return name+=":",options.port&&(name+=options.port),name+=":",options.localAddress&&(name+=options.localAddress),(4===options.family||6===options.family)&&(name+=":"+options.family),name},Agent.prototype.addRequest=function(req,options){"string"==typeof options&&(options={host:options,port:arguments[2],localAddress:arguments[3]}),options=util._extend({},options),options=util._extend(options,this.options);var name=this.getName(options);this.sockets[name]||(this.sockets[name]=[]);var freeLen=this.freeSockets[name]?this.freeSockets[name].length:0,sockLen=freeLen+this.sockets[name].length;if(freeLen){var socket=this.freeSockets[name].shift();debug("have free socket"),this.freeSockets[name].length||delete this.freeSockets[name],socket.ref(),req.onSocket(socket),this.sockets[name].push(socket)}else sockLen=this.maxHeaderPairs||this._headers.length=ch)||!!(65<=ch&&90>=ch)||!(45!==ch)||!!(48<=ch&&57>=ch)||34!==ch&&40!==ch&&41!==ch&&44!==ch&&(!!(33<=ch&&46>=ch)||!(124!==ch&&126!==ch))}const binding=require("http-parser-js"),methods=binding.methods,HTTPParser=binding.HTTPParser,FreeList=require("freelist").FreeList,incoming=require("./_http_incoming"),IncomingMessage=incoming.IncomingMessage,readStart=incoming.readStart,readStop=incoming.readStop,debug=require("util").debuglog("http");exports.debug=debug,exports.CRLF="\r\n",exports.chunkExpression=/chunk/i,exports.continueExpression=/100-continue/i,exports.methods=methods;const kOnHeaders=0|HTTPParser.kOnHeaders,kOnHeadersComplete=0|HTTPParser.kOnHeadersComplete,kOnBody=0|HTTPParser.kOnBody,kOnMessageComplete=0|HTTPParser.kOnMessageComplete,kOnExecute=0|HTTPParser.kOnExecute;var parsers=new FreeList("parsers",1e3,function(){var parser=new HTTPParser(HTTPParser.REQUEST);return parser._headers=[],parser._url="",parser._consumed=!1,parser.socket=null,parser.incoming=null,parser.outgoing=null,parser[kOnHeaders]=parserOnHeaders,parser[kOnHeadersComplete]=parserOnHeadersComplete,parser[kOnBody]=parserOnBody,parser[kOnMessageComplete]=parserOnMessageComplete,parser[kOnExecute]=null,parser});exports.parsers=parsers,exports.freeParser=function(parser,req,socket){parser&&(parser._headers=[],parser.onIncoming=null,parser._consumed&&parser.unconsume(),parser._consumed=!1,parser.socket&&(parser.socket.parser=null),parser.socket=null,parser.incoming=null,parser.outgoing=null,parser[kOnExecute]=null,!1===parsers.free(parser)&&parser.close(),parser=null),req&&(req.parser=null),socket&&(socket.parser=null)},exports.httpSocketSetup=function(socket){socket.removeListener("drain",ondrain),socket.on("drain",ondrain)},exports._checkIsHttpToken=function(val){if("string"!=typeof val||0===val.length)return!1;if(!isValidTokenChar(val.charCodeAt(0)))return!1;const len=val.length;if(1val.length)return!1;var c=val.charCodeAt(0);if(31>=c&&9!==c||255val.length)return!1;if(c=val.charCodeAt(1),31>=c&&9!==c||255val.length)return!1;if(c=val.charCodeAt(2),31>=c&&9!==c||255=c&&9!==c||255arguments.length)throw new Error("\"name\" argument is required for getHeader(name)");if(this._headers){var key=name.toLowerCase();return this._headers[key]}},OutgoingMessage.prototype.removeHeader=function(name){if(1>arguments.length)throw new Error("\"name\" argument is required for removeHeader(name)");if(this._header)throw new Error("Can't remove headers after they are sent");var key=name.toLowerCase();"date"===key?this.sendDate=!1:automaticHeaders[key]&&(this._removedHeader[key]=!0),this._headers&&(delete this._headers[key],delete this._headerNames[key])},OutgoingMessage.prototype._renderHeaders=function(){if(this._header)throw new Error("Can't render headers after they are sent to the client");var headersMap=this._headers;if(!headersMap)return{};for(var headers={},keys=Object.keys(headersMap),headerNames=this._headerNames,i=0,l=keys.length,key;i{this.emit("finish")};return ret=this._hasBody&&this.chunkedEncoding?this._send("0\r\n"+this._trailer+"\r\n","binary",finish):this._send("","binary",finish),this.connection&&data&&this.connection.uncork(),this.finished=!0,debug("outgoing message end."),0===this.output.length&&this.connection&&this.connection._httpMessage===this&&this._finish(),ret},OutgoingMessage.prototype._finish=function(){assert(this.connection),this.emit("prefinish")},OutgoingMessage.prototype._flush=function(){var socket=this.socket,ret;socket&&socket.writable&&(ret=this._flushOutput(socket),this.finished?this._finish():ret&&this.emit("drain"))},OutgoingMessage.prototype._flushOutput=function(socket){var outputLength=this.output.length,ret;if(0>=outputLength)return ret;var output=this.output,outputEncodings=this.outputEncodings,outputCallbacks=this.outputCallbacks;socket.cork();for(var i=0;ireq.httpVersionMajor||1>req.httpVersionMinor)&&(this.useChunkedEncodingByDefault=chunkExpression.test(req.headers.te),this.shouldKeepAlive=!1)}function onServerResponseClose(){this._httpMessage&&this._httpMessage.emit("close")}function Server(requestListener){return this instanceof Server?void(net.Server.call(this,{allowHalfOpen:!0}),requestListener&&this.addListener("request",requestListener),this.httpAllowHalfOpen=!1,this.addListener("connection",connectionListener),this.timeout=120000,this._pendingResponseData=0):new Server(requestListener)}function connectionListener(socket){function updateOutgoingData(delta){if(outgoingData+=delta,socket._paused&&outgoingData{}),self.emit("clientError",e,this)||this.destroy(e)}function socketOnData(d){assert(!socket._paused),debug("SERVER socketOnData %d",d.length);var ret=parser.execute(d);onParserExecuteCommon(ret,d)}function onParserExecuteCommon(ret,d){if(ret instanceof Error)debug("parse error"),socketOnError.call(socket,ret);else if(parser.incoming&&parser.incoming.upgrade){var req=parser.incoming;debug("SERVER upgrade or connect",req.method),d||(d=parser.getCurrentBuffer()),socket.removeListener("data",socketOnData),socket.removeListener("end",socketOnEnd),socket.removeListener("close",serverSocketCloseListener),unconsume(parser,socket),parser.finish(),freeParser(parser,req,null),parser=null;var eventName="CONNECT"===req.method?"connect":"upgrade";if(0socket._writableState.highWaterMark;socket._paused&&!needPause&&(socket._paused=!1,socket.parser&&socket.parser.resume(),socket.resume())}function parserOnIncoming(req,shouldKeepAlive){if(incoming.push(req),!socket._paused){var needPause=socket._writableState.needDrain||outgoingData>=socket._writableState.highWaterMark;needPause&&(socket._paused=!0,socket.pause())}var res=new ServerResponse(req);return res._onPendingData=updateOutgoingData,res.shouldKeepAlive=shouldKeepAlive,socket._httpMessage?outgoing.push(res):res.assignSocket(socket),res.on("finish",function(){if(assert(0===incoming.length||incoming[0]===req),incoming.shift(),req._consuming||req._readableState.resumeScheduled||req._dump(),res.detachSocket(socket),res._last)socket.destroySoon();else{var m=outgoing.shift();m&&m.assignSocket(socket)}}),void 0!==req.headers.expect&&1==req.httpVersionMajor&&1==req.httpVersionMinor?continueExpression.test(req.headers.expect)?(res._expect_continue=!0,0statusCode||999=statusCode)&&(this._hasBody=!1),this._expect_continue&&!this._sent100&&(this.shouldKeepAlive=!1),this._storeHeader(statusLine,headers)},ServerResponse.prototype.writeHeader=function(){this.writeHead.apply(this,arguments)},util.inherits(Server,net.Server),Server.prototype.setTimeout=function(msecs,callback){return this.timeout=msecs,callback&&this.on("timeout",callback),this},exports.Server=Server,exports._connectionListener=connectionListener},{"./_http_common":88,"./_http_outgoing":90,assert:11,"http-parser-js":93,net:65,util:58}],92:[function(require,module,exports){'use strict';function Client(port,host){return this instanceof Client?void(EventEmitter.call(this),host=host||"localhost",port=port||80,this.host=host,this.port=port,this.agent=new Agent({host:host,port:port,maxSockets:1})):new Client(port,host)}const util=require("util"),internalUtil=util,EventEmitter=require("events");exports.IncomingMessage=require("./_http_incoming").IncomingMessage;const common=require("./_http_common");exports.METHODS=common.methods.slice().sort(),exports.OutgoingMessage=require("./_http_outgoing").OutgoingMessage;const server=require("./_http_server");exports.ServerResponse=server.ServerResponse,exports.STATUS_CODES=server.STATUS_CODES;const agent=require("./_http_agent"),Agent=exports.Agent=agent.Agent;exports.globalAgent=agent.globalAgent;const client=require("./_http_client"),ClientRequest=exports.ClientRequest=client.ClientRequest;exports.request=function(options,cb){return new ClientRequest(options,cb)},exports.get=function(options,cb){var req=exports.request(options,cb);return req.end(),req},exports._connectionListener=server._connectionListener;const Server=exports.Server=server.Server;exports.createServer=function(requestListener){return new Server(requestListener)},util.inherits(Client,EventEmitter),Client.prototype.request=function(method,path,headers){var self=this,options={};options.host=self.host,options.port=self.port,"/"===method[0]&&(headers=path,path=method,method="GET"),options.method=method,options.path=path,options.headers=headers,options.agent=self.agent;var c=new ClientRequest(options);return c.on("error",function(e){self.emit("error",e)}),c.on("socket",function(s){s.on("end",function(){if(self._decoder){var ret=self._decoder.end();ret&&self.emit("data",ret)}self.emit("end")})}),c},exports.Client=internalUtil.deprecate(Client,"http.Client is deprecated."),exports.createClient=internalUtil.deprecate(function(port,host){return new Client(port,host)},"http.createClient is deprecated. Use http.request instead.")},{"./_http_agent":86,"./_http_client":87,"./_http_common":88,"./_http_incoming":89,"./_http_outgoing":90,"./_http_server":91,events:39,util:58}],93:[function(require,module,exports){function HTTPParser(type){assert.ok(type===HTTPParser.REQUEST||type===HTTPParser.RESPONSE),this.type=type,this.state=type+"_LINE",this.info={headers:[],upgrade:!1},this.trailers=[],this.line="",this.isChunked=!1,this.connection="",this.headerSize=0,this.body_bytes=null,this.isUserCall=!1,this.hadError=!1}function parseErrorCode(code){var err=new Error("Parse Error");return err.code=code,err}var assert=require("assert");exports.HTTPParser=HTTPParser,HTTPParser.encoding="ascii",HTTPParser.maxHeaderSize=81920,HTTPParser.REQUEST="REQUEST",HTTPParser.RESPONSE="RESPONSE";var kOnHeaders=HTTPParser.kOnHeaders=0,kOnHeadersComplete=HTTPParser.kOnHeadersComplete=1,kOnBody=HTTPParser.kOnBody=2,kOnMessageComplete=HTTPParser.kOnMessageComplete=3;HTTPParser.prototype[kOnHeaders]=HTTPParser.prototype[kOnHeadersComplete]=HTTPParser.prototype[kOnBody]=HTTPParser.prototype[kOnMessageComplete]=function(){};var compatMode0_12=!0;Object.defineProperty(HTTPParser,"kOnExecute",{get:function(){return compatMode0_12=!1,4}});var methods=exports.methods=HTTPParser.methods=["DELETE","GET","HEAD","POST","PUT","CONNECT","OPTIONS","TRACE","COPY","LOCK","MKCOL","MOVE","PROPFIND","PROPPATCH","SEARCH","UNLOCK","BIND","REBIND","UNBIND","ACL","REPORT","MKACTIVITY","CHECKOUT","MERGE","M-SEARCH","NOTIFY","SUBSCRIBE","UNSUBSCRIBE","PATCH","PURGE","MKCALENDAR","LINK","UNLINK"],method_connect=methods.indexOf("CONNECT");HTTPParser.prototype.reinitialize=HTTPParser,HTTPParser.prototype.close=HTTPParser.prototype.pause=HTTPParser.prototype.resume=HTTPParser.prototype.free=function(){},HTTPParser.prototype._compatMode0_11=!1,HTTPParser.prototype.getAsyncId=function(){return 0};var headerState={REQUEST_LINE:!0,RESPONSE_LINE:!0,HEADER:!0};HTTPParser.prototype.execute=function(chunk,start,length){if(!(this instanceof HTTPParser))throw new TypeError("not a HTTPParser");start=start||0,length="number"==typeof length?length:chunk.length,this.chunk=chunk,this.offset=start;var end=this.end=start+length;try{for(;this.offsetHTTPParser.maxHeaderSize)?new Error("max header size exceeded"):length};var stateFinishAllowed={REQUEST_LINE:!0,RESPONSE_LINE:!0,BODY_RAW:!0};HTTPParser.prototype.finish=function(){return this.hadError?void 0:stateFinishAllowed[this.state]?void("BODY_RAW"===this.state&&this.userCall()(this[kOnMessageComplete]())):new Error("invalid state for EOF")},HTTPParser.prototype.consume=HTTPParser.prototype.unconsume=HTTPParser.prototype.getCurrentBuffer=function(){},HTTPParser.prototype.userCall=function(){this.isUserCall=!0;var self=this;return function(ret){return self.isUserCall=!1,ret}},HTTPParser.prototype.nextRequest=function(){this.userCall()(this[kOnMessageComplete]()),this.reinitialize(this.type)},HTTPParser.prototype.consumeLine=function(){for(var end=this.end,chunk=this.chunk,i=this.offset;i */exports.read=function(buffer,offset,isLE,mLen,nBytes){var eLen=8*nBytes-mLen-1,eMax=(1<>1,nBits=-7,i=isLE?nBytes-1:0,d=isLE?-1:1,s=buffer[offset+i],e,m;for(i+=d,e=s&(1<<-nBits)-1,s>>=-nBits,nBits+=eLen;0>=-nBits,nBits+=mLen;0>1,rt=23===mLen?_Mathpow(2,-24)-_Mathpow(2,-77):0,i=isLE?0:nBytes-1,d=isLE?1:-1,s=0>value||0===value&&0>1/value?1:0,e,m,c;for(value=_Mathabs(value),isNaN(value)||value===1/0?(m=isNaN(value)?1:0,e=eMax):(e=_Mathfloor(_Mathlog(value)/_MathLN),1>value*(c=_Mathpow(2,-e))&&(e--,c*=2),value+=1<=e+eBias?rt/c:rt*_Mathpow(2,1-eBias),2<=value*c&&(e++,c/=2),e+eBias>=eMax?(m=0,e=eMax):1<=e+eBias?(m=(value*c-1)*_Mathpow(2,mLen),e+=eBias):(m=value*_Mathpow(2,eBias-1)*_Mathpow(2,mLen),e=0));8<=mLen;buffer[offset+i]=255&m,i+=d,m/=256,mLen-=8);for(e=e< */const queueMicrotask=require("queue-microtask");module.exports=class ImmediateStore{constructor(store){if(this.store=store,this.chunkLength=store.chunkLength,!this.store||!this.store.get||!this.store.put)throw new Error("First argument must be abstract-chunk-store compliant");this.mem=[]}put(index,buf,cb){this.mem[index]=buf,this.store.put(index,buf,err=>{this.mem[index]=null,cb&&cb(err)})}get(index,opts,cb){if("function"==typeof opts)return this.get(index,null,opts);let memoryBuffer=this.mem[index];if(!memoryBuffer)return this.store.get(index,opts,cb);if(opts){const start=opts.offset||0,end=opts.length?start+opts.length:memoryBuffer.length;memoryBuffer=memoryBuffer.slice(start,end)}queueMicrotask(()=>{cb&&cb(null,memoryBuffer)})}close(cb){this.store.close(cb)}destroy(cb){this.store.destroy(cb)}}},{"queue-microtask":138}],97:[function(require,module){module.exports="function"==typeof Object.create?function(ctor,superCtor){superCtor&&(ctor.super_=superCtor,ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:!1,writable:!0,configurable:!0}}))}:function(ctor,superCtor){if(superCtor){ctor.super_=superCtor;var TempCtor=function(){};TempCtor.prototype=superCtor.prototype,ctor.prototype=new TempCtor,ctor.prototype.constructor=ctor}}},{}],98:[function(require,module){(function(root){'use strict';function expandIPv6(string,parts){if(string.indexOf("::")!==string.lastIndexOf("::"))return null;let colonCount=0,lastColon=-1,zoneId=(string.match(ipv6Regexes.zoneIndex)||[])[0],replacement,replacementCount;for(zoneId&&(zoneId=zoneId.substring(1),string=string.replace(/%.+$/,""));0<=(lastColon=string.indexOf(":",lastColon+1));)colonCount++;if("::"===string.substr(0,2)&&colonCount--,"::"===string.substr(-2,2)&&colonCount--,colonCount>parts)return null;for(replacementCount=parts-colonCount,replacement=":";replacementCount--;)replacement+="0:";return string=string.replace("::",replacement),":"===string[0]&&(string=string.slice(1)),":"===string[string.length-1]&&(string=string.slice(0,-1)),parts=function(){const ref=string.split(":"),results=[];for(let i=0;ishift&&(shift=0),first[part]>>shift!=second[part]>>shift)return!1;cidrBits-=partSize,part+=1}return!0}function parseIntAuto(string){if(hexRegex.test(string))return parseInt(string,16);if("0"===string[0]&&!isNaN(parseInt(string[1],10))){if(octalRegex.test(string))return parseInt(string,8);throw new Error(`ipaddr: cannot parse ${string} as octal`)}return parseInt(string,10)}function padPart(part,length){for(;part.length=octet))throw new Error("ipaddr: ipv4 octet should fit in 8 bits");this.octets=octets}return IPv4.prototype.SpecialRanges={unspecified:[[new IPv4([0,0,0,0]),8]],broadcast:[[new IPv4([255,255,255,255]),32]],multicast:[[new IPv4([224,0,0,0]),4]],linkLocal:[[new IPv4([169,254,0,0]),16]],loopback:[[new IPv4([127,0,0,0]),8]],carrierGradeNat:[[new IPv4([100,64,0,0]),10]],private:[[new IPv4([10,0,0,0]),8],[new IPv4([172,16,0,0]),12],[new IPv4([192,168,0,0]),16]],reserved:[[new IPv4([192,0,0,0]),24],[new IPv4([192,0,2,0]),24],[new IPv4([192,88,99,0]),24],[new IPv4([198,51,100,0]),24],[new IPv4([203,0,113,0]),24],[new IPv4([240,0,0,0]),4]]},IPv4.prototype.kind=function(){return"ipv4"},IPv4.prototype.match=function(other,cidrRange){let ref;if(void 0===cidrRange&&(ref=other,other=ref[0],cidrRange=ref[1]),"ipv4"!==other.kind())throw new Error("ipaddr: cannot match ipv4 address with non-ipv4 one");return matchCIDR(this.octets,other.octets,8,cidrRange)},IPv4.prototype.prefixLengthFromSubnetMask=function(){let cidr=0,stop=!1;const zerotable={0:8,128:7,192:6,224:5,240:4,248:3,252:2,254:1,255:0};let i,octet,zeros;for(i=3;0<=i;i-=1)if(octet=this.octets[i],octet in zerotable){if(zeros=zerotable[octet],stop&&0!==zeros)return null;8!==zeros&&(stop=!0),cidr+=zeros}else return null;return 32-cidr},IPv4.prototype.range=function(){return ipaddr.subnetMatch(this,this.SpecialRanges)},IPv4.prototype.toByteArray=function(){return this.octets.slice(0)},IPv4.prototype.toIPv4MappedAddress=function(){return ipaddr.IPv6.parse(`::ffff:${this.toString()}`)},IPv4.prototype.toNormalizedString=function(){return this.toString()},IPv4.prototype.toString=function(){return this.octets.join(".")},IPv4}(),ipaddr.IPv4.broadcastAddressFromCIDR=function(string){try{const cidr=this.parseCIDR(string),ipInterfaceOctets=cidr[0].toByteArray(),subnetMaskOctets=this.subnetMaskFromPrefixLength(cidr[1]).toByteArray(),octets=[];for(let i=0;4>i;)octets.push(parseInt(ipInterfaceOctets[i],10)|255^parseInt(subnetMaskOctets[i],10)),i++;return new this(octets)}catch(e){throw new Error("ipaddr: the address does not have IPv4 CIDR format")}},ipaddr.IPv4.isIPv4=function(string){return null!==this.parser(string)},ipaddr.IPv4.isValid=function(string){try{return new this(this.parser(string)),!0}catch(e){return!1}},ipaddr.IPv4.isValidFourPartDecimal=function(string){return!!(ipaddr.IPv4.isValid(string)&&string.match(/^(0|[1-9]\d*)(\.(0|[1-9]\d*)){3}$/))},ipaddr.IPv4.networkAddressFromCIDR=function(string){let cidr,i,ipInterfaceOctets,octets,subnetMaskOctets;try{for(cidr=this.parseCIDR(string),ipInterfaceOctets=cidr[0].toByteArray(),subnetMaskOctets=this.subnetMaskFromPrefixLength(cidr[1]).toByteArray(),octets=[],i=0;4>i;)octets.push(parseInt(ipInterfaceOctets[i],10)&parseInt(subnetMaskOctets[i],10)),i++;return new this(octets)}catch(e){throw new Error("ipaddr: the address does not have IPv4 CIDR format")}},ipaddr.IPv4.parse=function(string){const parts=this.parser(string);if(null===parts)throw new Error("ipaddr: string is not formatted like an IPv4 Address");return new this(parts)},ipaddr.IPv4.parseCIDR=function(string){let match;if(match=string.match(/^(.+)\/(\d+)$/)){const maskLength=parseInt(match[2]);if(0<=maskLength&&32>=maskLength){const parsed=[this.parse(match[1]),maskLength];return Object.defineProperty(parsed,"toString",{value:function(){return this.join("/")}}),parsed}}throw new Error("ipaddr: string is not formatted like an IPv4 CIDR range")},ipaddr.IPv4.parser=function(string){let match,part,value;if(match=string.match(ipv4Regexes.fourOctet))return function(){const ref=match.slice(1,6),results=[];for(let i=0;ivalue)throw new Error("ipaddr: address outside defined range");return function(){const results=[];let shift;for(shift=0;24>=shift;shift+=8)results.push(255&value>>shift);return results}().reverse()}return(match=string.match(ipv4Regexes.twoOctet))?function(){const ref=match.slice(1,4),results=[];if(value=parseIntAuto(ref[1]),16777215value)throw new Error("ipaddr: address outside defined range");return results.push(parseIntAuto(ref[0])),results.push(255&value>>16),results.push(255&value>>8),results.push(255&value),results}():(match=string.match(ipv4Regexes.threeOctet))?function(){const ref=match.slice(1,5),results=[];if(value=parseIntAuto(ref[2]),65535value)throw new Error("ipaddr: address outside defined range");return results.push(parseIntAuto(ref[0])),results.push(parseIntAuto(ref[1])),results.push(255&value>>8),results.push(255&value),results}():null},ipaddr.IPv4.subnetMaskFromPrefixLength=function(prefix){if(prefix=parseInt(prefix),0>prefix||32filledOctetCount&&(octets[filledOctetCount]=_Mathpow(2,prefix%8)-1<<8-prefix%8),new this(octets)},ipaddr.IPv6=function(){function IPv6(parts,zoneId){let i,part;if(16===parts.length)for(this.parts=[],i=0;14>=i;i+=2)this.parts.push(parts[i]<<8|parts[i+1]);else if(8===parts.length)this.parts=parts;else throw new Error("ipaddr: ipv6 part count should be 8 or 16");for(i=0;i=part))throw new Error("ipaddr: ipv6 part should fit in 16 bits");zoneId&&(this.zoneId=zoneId)}return IPv6.prototype.SpecialRanges={unspecified:[new IPv6([0,0,0,0,0,0,0,0]),128],linkLocal:[new IPv6([65152,0,0,0,0,0,0,0]),10],multicast:[new IPv6([65280,0,0,0,0,0,0,0]),8],loopback:[new IPv6([0,0,0,0,0,0,0,1]),128],uniqueLocal:[new IPv6([64512,0,0,0,0,0,0,0]),7],ipv4Mapped:[new IPv6([0,0,0,0,0,65535,0,0]),96],rfc6145:[new IPv6([0,0,0,0,65535,0,0,0]),96],rfc6052:[new IPv6([100,65435,0,0,0,0,0,0]),96],"6to4":[new IPv6([8194,0,0,0,0,0,0,0]),16],teredo:[new IPv6([8193,0,0,0,0,0,0,0]),32],reserved:[[new IPv6([8193,3512,0,0,0,0,0,0]),32]]},IPv6.prototype.isIPv4MappedAddress=function(){return"ipv4Mapped"===this.range()},IPv6.prototype.kind=function(){return"ipv6"},IPv6.prototype.match=function(other,cidrRange){let ref;if(void 0===cidrRange&&(ref=other,other=ref[0],cidrRange=ref[1]),"ipv6"!==other.kind())throw new Error("ipaddr: cannot match ipv6 address with non-ipv6 one");return matchCIDR(this.parts,other.parts,16,cidrRange)},IPv6.prototype.prefixLengthFromSubnetMask=function(){let cidr=0,stop=!1;const zerotable={0:16,32768:15,49152:14,57344:13,61440:12,63488:11,64512:10,65024:9,65280:8,65408:7,65472:6,65504:5,65520:4,65528:3,65532:2,65534:1,65535:0};let part,zeros;for(let i=7;0<=i;i-=1)if(part=this.parts[i],part in zerotable){if(zeros=zerotable[part],stop&&0!==zeros)return null;16!==zeros&&(stop=!0),cidr+=zeros}else return null;return 128-cidr},IPv6.prototype.range=function(){return ipaddr.subnetMatch(this,this.SpecialRanges)},IPv6.prototype.toByteArray=function(){let part;const bytes=[],ref=this.parts;for(let i=0;i>8),bytes.push(255&part);return bytes},IPv6.prototype.toFixedLengthString=function(){const addr=function(){const results=[];for(let i=0;i>8,255&high,low>>8,255&low])},IPv6.prototype.toNormalizedString=function(){const addr=function(){const results=[];for(let i=0;ibestMatchLength&&(bestMatchIndex=match.index,bestMatchLength=match[0].length);return 0>bestMatchLength?string:`${string.substring(0,bestMatchIndex)}::${string.substring(bestMatchIndex+bestMatchLength)}`},IPv6.prototype.toString=function(){return this.toNormalizedString().replace(/((^|:)(0(:|$))+)/,"::")},IPv6}(),ipaddr.IPv6.isIPv6=function(string){return null!==this.parser(string)},ipaddr.IPv6.isValid=function(string){if("string"==typeof string&&-1===string.indexOf(":"))return!1;try{const addr=this.parser(string);return new this(addr.parts,addr.zoneId),!0}catch(e){return!1}},ipaddr.IPv6.parse=function(string){const addr=this.parser(string);if(null===addr.parts)throw new Error("ipaddr: string is not formatted like an IPv6 Address");return new this(addr.parts,addr.zoneId)},ipaddr.IPv6.parseCIDR=function(string){let maskLength,match,parsed;if((match=string.match(/^(.+)\/(\d+)$/))&&(maskLength=parseInt(match[2]),0<=maskLength&&128>=maskLength))return parsed=[this.parse(match[1]),maskLength],Object.defineProperty(parsed,"toString",{value:function(){return this.join("/")}}),parsed;throw new Error("ipaddr: string is not formatted like an IPv6 CIDR range")},ipaddr.IPv6.parser=function(string){let addr,i,match,octet,octets,zoneId;if(match=string.match(ipv6Regexes.deprecatedTransitional))return this.parser(`::ffff:${match[1]}`);if(ipv6Regexes.native.test(string))return expandIPv6(string,8);if((match=string.match(ipv6Regexes.transitional))&&(zoneId=match[6]||"",addr=expandIPv6(match[1].slice(0,-1)+zoneId,6),addr.parts)){for(octets=[parseInt(match[2]),parseInt(match[3]),parseInt(match[4]),parseInt(match[5])],i=0;i=octet))return null;return addr.parts.push(octets[0]<<8|octets[1]),addr.parts.push(octets[2]<<8|octets[3]),{parts:addr.parts,zoneId:addr.zoneId}}return null},ipaddr.fromByteArray=function(bytes){const length=bytes.length;if(4===length)return new ipaddr.IPv4(bytes);if(16===length)return new ipaddr.IPv6(bytes);throw new Error("ipaddr: the binary input is neither an IPv6 nor IPv4 address")},ipaddr.isValid=function(string){return ipaddr.IPv6.isValid(string)||ipaddr.IPv4.isValid(string)},ipaddr.parse=function(string){if(ipaddr.IPv6.isValid(string))return ipaddr.IPv6.parse(string);if(ipaddr.IPv4.isValid(string))return ipaddr.IPv4.parse(string);throw new Error("ipaddr: the address has neither IPv6 nor IPv4 format")},ipaddr.parseCIDR=function(string){try{return ipaddr.IPv6.parseCIDR(string)}catch(e){try{return ipaddr.IPv4.parseCIDR(string)}catch(e2){throw new Error("ipaddr: the address has neither IPv6 nor IPv4 CIDR format")}}},ipaddr.process=function(string){const addr=this.parse(string);return"ipv6"===addr.kind()&&addr.isIPv4MappedAddress()?addr.toIPv4Address():addr},ipaddr.subnetMatch=function(address,rangeList,defaultName){let i,rangeName,rangeSubnets,subnet;for(rangeName in(void 0===defaultName||null===defaultName)&&(defaultName="unicast"),rangeList)if(Object.prototype.hasOwnProperty.call(rangeList,rangeName))for(rangeSubnets=rangeList[rangeName],rangeSubnets[0]&&!(rangeSubnets[0]instanceof Array)&&(rangeSubnets=[rangeSubnets]),i=0;i127)return!1;return!0}},{}],101:[function(require,module){function isBuffer(obj){return!!obj.constructor&&"function"==typeof obj.constructor.isBuffer&&obj.constructor.isBuffer(obj)}function isSlowBuffer(obj){return"function"==typeof obj.readFloatLE&&"function"==typeof obj.slice&&isBuffer(obj.slice(0,0))}/*! * Determine if an object is a Buffer * * @author Feross Aboukhadijeh @@ -50,4 +50,4 @@ object-assign * Copyright(c) 2012-2014 TJ Holowaychuk * Copyright(c) 2015-2016 Douglas Christopher Wilson * MIT Licensed - */'use strict';function combineRanges(ranges){for(var ordered=ranges.map(mapWithIndex).sort(sortByRangeStart),j=0,i=1;icurrent.end+1?ordered[++j]=range:range.end>current.end&&(current.end=range.end,current.index=_Mathmin(current.index,range.index))}ordered.length=j+1;var combined=ordered.sort(sortByRangeIndex).map(mapWithoutIndex);return combined.type=ranges.type,combined}function mapWithIndex(range,index){return{start:range.start,end:range.end,index:index}}function mapWithoutIndex(range){return{start:range.start,end:range.end}}function sortByRangeIndex(a,b){return a.index-b.index}function sortByRangeStart(a,b){return a.start-b.start}module.exports=function(size,str,options){if("string"!=typeof str)throw new TypeError("argument str must be a string");var index=str.indexOf("=");if(-1===index)return-2;var arr=str.slice(index+1).split(","),ranges=[];ranges.type=str.slice(0,index);for(var i=0;isize-1&&(end=size-1),!(isNaN(start)||isNaN(end)||start>end||0>start))&&ranges.push({start:start,end:end})}return 1>ranges.length?-1:options&&options.combine?combineRanges(ranges):ranges}},{}],142:[function(require,module){const{Writable,PassThrough}=require("readable-stream");module.exports=class RangeSliceStream extends Writable{constructor(offset,opts={}){super(opts),this.destroyed=!1,this._queue=[],this._position=offset||0,this._cb=null,this._buffer=null,this._out=null}_write(chunk,encoding,cb){let drained=!0;for(;;){if(this.destroyed)return;if(0===this._queue.length)return this._buffer=chunk,void(this._cb=cb);this._buffer=null;var currRange=this._queue[0];const writeStart=_Mathmax(currRange.start-this._position,0),writeEnd=currRange.end-this._position;if(writeStart>=chunk.length)return this._position+=chunk.length,cb(null);let toWrite;if(writeEnd>chunk.length){this._position+=chunk.length,toWrite=0===writeStart?chunk:chunk.slice(writeStart),drained=currRange.stream.write(toWrite)&&drained;break}this._position+=writeEnd,toWrite=0===writeStart&&writeEnd===chunk.length?chunk:chunk.slice(writeStart,writeEnd),drained=currRange.stream.write(toWrite)&&drained,currRange.last&&currRange.stream.end(),chunk=chunk.slice(writeEnd),this._queue.shift()}drained?cb(null):currRange.stream.once("drain",cb.bind(null,null))}slice(ranges){if(this.destroyed)return null;Array.isArray(ranges)||(ranges=[ranges]);const str=new PassThrough;return ranges.forEach((range,i)=>{this._queue.push({start:range.start,end:range.end,stream:str,last:i===ranges.length-1})}),this._buffer&&this._write(this._buffer,null,this._cb),str}destroy(err){this.destroyed||(this.destroyed=!0,err&&this.emit("error",err))}}},{"readable-stream":157}],143:[function(require,module,exports){arguments[4][42][0].apply(exports,arguments)},{dup:42}],144:[function(require,module,exports){arguments[4][43][0].apply(exports,arguments)},{"./_stream_readable":146,"./_stream_writable":148,_process:132,dup:43,inherits:97}],145:[function(require,module,exports){arguments[4][44][0].apply(exports,arguments)},{"./_stream_transform":147,dup:44,inherits:97}],146:[function(require,module,exports){arguments[4][45][0].apply(exports,arguments)},{"../errors":143,"./_stream_duplex":144,"./internal/streams/async_iterator":149,"./internal/streams/buffer_list":150,"./internal/streams/destroy":151,"./internal/streams/from":153,"./internal/streams/state":155,"./internal/streams/stream":156,_process:132,buffer:38,dup:45,events:39,inherits:97,"string_decoder/":182,util:36}],147:[function(require,module,exports){arguments[4][46][0].apply(exports,arguments)},{"../errors":143,"./_stream_duplex":144,dup:46,inherits:97}],148:[function(require,module,exports){arguments[4][47][0].apply(exports,arguments)},{"../errors":143,"./_stream_duplex":144,"./internal/streams/destroy":151,"./internal/streams/state":155,"./internal/streams/stream":156,_process:132,buffer:38,dup:47,inherits:97,"util-deprecate":196}],149:[function(require,module,exports){arguments[4][48][0].apply(exports,arguments)},{"./end-of-stream":152,_process:132,dup:48}],150:[function(require,module,exports){arguments[4][49][0].apply(exports,arguments)},{buffer:38,dup:49,util:36}],151:[function(require,module,exports){arguments[4][50][0].apply(exports,arguments)},{_process:132,dup:50}],152:[function(require,module,exports){arguments[4][51][0].apply(exports,arguments)},{"../../../errors":143,dup:51}],153:[function(require,module,exports){arguments[4][52][0].apply(exports,arguments)},{dup:52}],154:[function(require,module,exports){arguments[4][53][0].apply(exports,arguments)},{"../../../errors":143,"./end-of-stream":152,dup:53}],155:[function(require,module,exports){arguments[4][54][0].apply(exports,arguments)},{"../../../errors":143,dup:54}],156:[function(require,module,exports){arguments[4][55][0].apply(exports,arguments)},{dup:55,events:39}],157:[function(require,module,exports){exports=module.exports=require("./lib/_stream_readable.js"),exports.Stream=exports,exports.Readable=exports,exports.Writable=require("./lib/_stream_writable.js"),exports.Duplex=require("./lib/_stream_duplex.js"),exports.Transform=require("./lib/_stream_transform.js"),exports.PassThrough=require("./lib/_stream_passthrough.js"),exports.finished=require("./lib/internal/streams/end-of-stream.js"),exports.pipeline=require("./lib/internal/streams/pipeline.js")},{"./lib/_stream_duplex.js":144,"./lib/_stream_passthrough.js":145,"./lib/_stream_readable.js":146,"./lib/_stream_transform.js":147,"./lib/_stream_writable.js":148,"./lib/internal/streams/end-of-stream.js":152,"./lib/internal/streams/pipeline.js":154}],158:[function(require,module){(function(Buffer){(function(){function RecordSet(){this.list=[],this.map=new Map}function RecordStore(){this.records=new Map,this.size=0}function RecordCache(opts){if(!(this instanceof RecordCache))return new RecordCache(opts);if(opts||(opts={}),this.maxSize=opts.maxSize||1/0,this.maxAge=opts.maxAge||0,this._onstale=opts.onStale||opts.onstale||null,this._fresh=new RecordStore,this._stale=new RecordStore,this._interval=null,this.maxAge&&this.maxAge<1/0){var tick=_Mathceil(2/3*this.maxAge);this._interval=setInterval(this._gc.bind(this),tick),this._interval.unref&&this._interval.unref()}}function toString(record){return Buffer.isBuffer(record)?record.toString("hex"):record}function swap(list,a,b){var tmp=list[a];tmp.index=b,list[b].index=a,list[a]=list[b],list[b]=tmp}var EMPTY=[];module.exports=RecordCache,RecordSet.prototype.add=function(record,value){var k=toString(record),r=this.map.get(k);return!r&&(r={index:this.list.length,record:value||record},this.list.push(r),this.map.set(k,r),!0)},RecordSet.prototype.remove=function(record){var k=toString(record),r=this.map.get(k);return!!r&&(swap(this.list,r.index,this.list.length-1),this.list.pop(),this.map.delete(k),!0)},RecordStore.prototype.add=function(name,record,value){var r=this.records.get(name);return r||(r=new RecordSet,this.records.set(name,r)),!!r.add(record,value)&&(this.size++,!0)},RecordStore.prototype.remove=function(name,record,value){var r=this.records.get(name);return!!r&&!!r.remove(record,value)&&(this.size--,r.map.size||this.records.delete(name),!0)},RecordStore.prototype.get=function(name){var r=this.records.get(name);return r?r.list:EMPTY},Object.defineProperty(RecordCache.prototype,"size",{get:function(){return this._fresh.size+this._stale.size}}),RecordCache.prototype.add=function(name,record,value){this._stale.remove(name,record,value),this._fresh.add(name,record,value)&&this._fresh.size>this.maxSize&&this._gc()},RecordCache.prototype.remove=function(name,record,value){this._fresh.remove(name,record,value),this._stale.remove(name,record,value)},RecordCache.prototype.get=function(name,n){var a=this._fresh.get(name),b=this._stale.get(name),aLen=a.length,bLen=b.length,len=aLen+bLen;(n>len||!n)&&(n=len);for(var result=Array(n),i=0,j;iopts.maxBlobLength)||(debug("File length too large for Blob URL approach: %d (max: %d)",file.length,opts.maxBlobLength),fatalError(new Error(`File length too large for Blob URL approach: ${file.length} (max: ${opts.maxBlobLength})`)),!1)}function renderMediaElement(type){checkBlobLength()&&(elem=getElem(type),getBlobURL(file,(err,url)=>err?fatalError(err):void(elem.addEventListener("error",fatalError),elem.addEventListener("loadstart",onLoadStart),elem.addEventListener("canplay",onCanPlay),elem.src=url)))}function onLoadStart(){elem.removeEventListener("loadstart",onLoadStart),opts.autoplay&&elem.play()}function onCanPlay(){elem.removeEventListener("canplay",onCanPlay),cb(null,elem)}function renderIframe(){getBlobURL(file,(err,url)=>err?fatalError(err):void(".pdf"===extname?(elem=getElem("object"),elem.setAttribute("typemustmatch",!0),elem.setAttribute("type","application/pdf"),elem.setAttribute("data",url)):(elem=getElem("iframe"),elem.sandbox="allow-forms allow-scripts",elem.src=url),cb(null,elem)))}function fatalError(err){err.message=`Error rendering file "${file.name}": ${err.message}`,debug(err.message),cb(err)}const extname=path.extname(file.name).toLowerCase();let currentTime=0,elem;MEDIASOURCE_EXTS.includes(extname)?function(){function useVideostream(){debug(`Use \`videostream\` package for ${file.name}`),prepareElem(),elem.addEventListener("error",fallbackToMediaSource),elem.addEventListener("loadstart",onLoadStart),elem.addEventListener("canplay",onCanPlay),new VideoStream(file,elem)}function useMediaSource(){debug(`Use MediaSource API for ${file.name}`),prepareElem(),elem.addEventListener("error",fallbackToBlobURL),elem.addEventListener("loadstart",onLoadStart),elem.addEventListener("canplay",onCanPlay);const wrapper=new MediaElementWrapper(elem),writable=wrapper.createWriteStream(getCodec(file.name));file.createReadStream().pipe(writable),currentTime&&(elem.currentTime=currentTime)}function useBlobURL(){debug(`Use Blob URL for ${file.name}`),prepareElem(),elem.addEventListener("error",fatalError),elem.addEventListener("loadstart",onLoadStart),elem.addEventListener("canplay",onCanPlay),getBlobURL(file,(err,url)=>err?fatalError(err):void(elem.src=url,currentTime&&(elem.currentTime=currentTime)))}function fallbackToMediaSource(err){debug("videostream error: fallback to MediaSource API: %o",err.message||err),elem.removeEventListener("error",fallbackToMediaSource),elem.removeEventListener("canplay",onCanPlay),useMediaSource()}function fallbackToBlobURL(err){debug("MediaSource API error: fallback to Blob URL: %o",err.message||err);checkBlobLength()&&(elem.removeEventListener("error",fallbackToBlobURL),elem.removeEventListener("canplay",onCanPlay),useBlobURL())}function prepareElem(){elem||(elem=getElem(tagName),elem.addEventListener("progress",()=>{currentTime=elem.currentTime}))}const tagName=MEDIASOURCE_VIDEO_EXTS.includes(extname)?"video":"audio";MediaSource?VIDEOSTREAM_EXTS.includes(extname)?useVideostream():useMediaSource():useBlobURL()}():VIDEO_EXTS.includes(extname)?renderMediaElement("video"):AUDIO_EXTS.includes(extname)?renderMediaElement("audio"):IMAGE_EXTS.includes(extname)?function(){elem=getElem("img"),getBlobURL(file,(err,url)=>err?fatalError(err):void(elem.src=url,elem.alt=file.name,cb(null,elem)))}():IFRAME_EXTS.includes(extname)?renderIframe():function(){function done(){isAscii(str)?(debug("File extension \"%s\" appears ascii, so will render.",extname),renderIframe()):(debug("File extension \"%s\" appears non-ascii, will not render.",extname),cb(new Error(`Unsupported file type "${extname}": Cannot append to DOM`)))}debug("Unknown file extension \"%s\" - will attempt to render into iframe",extname);let str="";file.createReadStream({start:0,end:1e3}).setEncoding("utf8").on("data",chunk=>{str+=chunk}).on("end",done).on("error",cb)}()}function getBlobURL(file,cb){const extname=path.extname(file.name).toLowerCase();streamToBlobURL(file.createReadStream(),exports.mime[extname]).then(blobUrl=>cb(null,blobUrl),err=>cb(err))}function validateFile(file){if(null==file)throw new Error("file cannot be null or undefined");if("string"!=typeof file.name)throw new Error("missing or invalid file.name property");if("function"!=typeof file.createReadStream)throw new Error("missing or invalid file.createReadStream property")}function getCodec(name){const extname=path.extname(name).toLowerCase();return{".m4a":"audio/mp4; codecs=\"mp4a.40.5\"",".m4b":"audio/mp4; codecs=\"mp4a.40.5\"",".m4p":"audio/mp4; codecs=\"mp4a.40.5\"",".m4v":"video/mp4; codecs=\"avc1.640029, mp4a.40.5\"",".mkv":"video/webm; codecs=\"avc1.640029, mp4a.40.5\"",".mp3":"audio/mpeg",".mp4":"video/mp4; codecs=\"avc1.640029, mp4a.40.5\"",".webm":"video/webm; codecs=\"vorbis, vp8\""}[extname]}function parseOpts(opts){null==opts.autoplay&&(opts.autoplay=!1),null==opts.muted&&(opts.muted=!1),null==opts.controls&&(opts.controls=!0),null==opts.maxBlobLength&&(opts.maxBlobLength=MAX_BLOB_LENGTH)}function setMediaOpts(elem,opts){elem.autoplay=!!opts.autoplay,elem.muted=!!opts.muted,elem.controls=!!opts.controls}exports.render=function(file,elem,opts,cb){"function"==typeof opts&&(cb=opts,opts={}),opts||(opts={}),cb||(cb=()=>{}),validateFile(file),parseOpts(opts),"string"==typeof elem&&(elem=document.querySelector(elem)),renderMedia(file,tagName=>{if(elem.nodeName!==tagName.toUpperCase()){const extname=path.extname(file.name).toLowerCase();throw new Error(`Cannot render "${extname}" inside a "${elem.nodeName.toLowerCase()}" element, expected "${tagName}"`)}return("video"===tagName||"audio"===tagName)&&setMediaOpts(elem,opts),elem},opts,cb)},exports.append=function(file,rootElem,opts,cb){function createMedia(tagName){const elem=createElem(tagName);return setMediaOpts(elem,opts),rootElem.appendChild(elem),elem}function createElem(tagName){const elem=document.createElement(tagName);return rootElem.appendChild(elem),elem}function done(err,elem){err&&elem&&elem.remove(),cb(err,elem)}if("function"==typeof opts&&(cb=opts,opts={}),opts||(opts={}),cb||(cb=()=>{}),validateFile(file),parseOpts(opts),"string"==typeof rootElem&&(rootElem=document.querySelector(rootElem)),rootElem&&("VIDEO"===rootElem.nodeName||"AUDIO"===rootElem.nodeName))throw new Error("Invalid video/audio node argument. Argument must be root element that video/audio tag will be appended to.");renderMedia(file,function(tagName){return"video"===tagName||"audio"===tagName?createMedia(tagName):createElem(tagName)},opts,done)},exports.mime=require("./lib/mime.json");const debug=require("debug")("render-media"),isAscii=require("is-ascii"),MediaElementWrapper=require("mediasource"),path=require("path"),streamToBlobURL=require("stream-to-blob-url"),VideoStream=require("videostream"),VIDEOSTREAM_EXTS=[".m4a",".m4b",".m4p",".m4v",".mp4"],MEDIASOURCE_VIDEO_EXTS=[".m4v",".mkv",".mp4",".webm"],MEDIASOURCE_EXTS=[].concat(MEDIASOURCE_VIDEO_EXTS,[".m4a",".m4b",".m4p",".mp3"]),VIDEO_EXTS=[".mov",".ogv"],AUDIO_EXTS=[".aac",".oga",".ogg",".wav",".flac"],IMAGE_EXTS=[".bmp",".gif",".jpeg",".jpg",".png",".svg"],IFRAME_EXTS=[".css",".html",".js",".md",".pdf",".srt",".txt"],MAX_BLOB_LENGTH=200000000,MediaSource="undefined"!=typeof window&&window.MediaSource},{"./lib/mime.json":160,debug:69,"is-ascii":100,mediasource:113,path:40,"stream-to-blob-url":177,videostream:198}],160:[function(require,module){module.exports={".3gp":"video/3gpp",".aac":"audio/aac",".aif":"audio/x-aiff",".aiff":"audio/x-aiff",".atom":"application/atom+xml",".avi":"video/x-msvideo",".bmp":"image/bmp",".bz2":"application/x-bzip2",".conf":"text/plain",".css":"text/css",".csv":"text/plain",".diff":"text/x-diff",".doc":"application/msword",".flv":"video/x-flv",".gif":"image/gif",".gz":"application/x-gzip",".htm":"text/html",".html":"text/html",".ico":"image/vnd.microsoft.icon",".ics":"text/calendar",".iso":"application/octet-stream",".jar":"application/java-archive",".jpeg":"image/jpeg",".jpg":"image/jpeg",".js":"application/javascript",".json":"application/json",".less":"text/css",".log":"text/plain",".m3u":"audio/x-mpegurl",".m4a":"audio/x-m4a",".m4b":"audio/mp4",".m4p":"audio/mp4",".m4v":"video/x-m4v",".manifest":"text/cache-manifest",".markdown":"text/x-markdown",".mathml":"application/mathml+xml",".md":"text/x-markdown",".mid":"audio/midi",".midi":"audio/midi",".mov":"video/quicktime",".mp3":"audio/mpeg",".mp4":"video/mp4",".mp4v":"video/mp4",".mpeg":"video/mpeg",".mpg":"video/mpeg",".odp":"application/vnd.oasis.opendocument.presentation",".ods":"application/vnd.oasis.opendocument.spreadsheet",".odt":"application/vnd.oasis.opendocument.text",".oga":"audio/ogg",".ogg":"application/ogg",".pdf":"application/pdf",".png":"image/png",".pps":"application/vnd.ms-powerpoint",".ppt":"application/vnd.ms-powerpoint",".ps":"application/postscript",".psd":"image/vnd.adobe.photoshop",".qt":"video/quicktime",".rar":"application/x-rar-compressed",".rdf":"application/rdf+xml",".rss":"application/rss+xml",".rtf":"application/rtf",".svg":"image/svg+xml",".svgz":"image/svg+xml",".swf":"application/x-shockwave-flash",".tar":"application/x-tar",".tbz":"application/x-bzip-compressed-tar",".text":"text/plain",".tif":"image/tiff",".tiff":"image/tiff",".torrent":"application/x-bittorrent",".ttf":"application/x-font-ttf",".txt":"text/plain",".wav":"audio/wav",".webm":"video/webm",".wma":"audio/x-ms-wma",".wmv":"video/x-ms-wmv",".xls":"application/vnd.ms-excel",".xml":"application/xml",".yaml":"text/yaml",".yml":"text/yaml",".zip":"application/zip"}},{}],161:[function(require,module){(function(process){(function(){/*! run-parallel-limit. MIT License. Feross Aboukhadijeh */module.exports=function(tasks,limit,cb){function done(err){function end(){cb&&cb(err,results),cb=null}isSync?process.nextTick(end):end()}function each(i,err,result){if(results[i]=result,err&&(isErrored=!0),0==--pending||err)done(err);else if(!isErrored&&next */module.exports=function(tasks,cb){function done(err){function end(){cb&&cb(err,results),cb=null}isSync?process.nextTick(end):end()}function each(i,err,result){results[i]=result,(0==--pending||err)&&done(err)}var isSync=!0,results,pending,keys;Array.isArray(tasks)?(results=[],pending=tasks.length):(keys=Object.keys(tasks),results={},pending=keys.length),pending?keys?keys.forEach(function(key){tasks[key](function(err,result){each(key,err,result)})}):tasks.forEach(function(task,i){task(function(err,result){each(i,err,result)})}):done(null),isSync=!1}}).call(this)}).call(this,require("_process"))},{_process:132}],163:[function(require,module){(function(process){(function(){/*! run-series. MIT License. Feross Aboukhadijeh */module.exports=function(tasks,cb){function done(err){function end(){cb&&cb(err,results)}isSync?process.nextTick(end):end()}function each(err,result){results.push(result),++current>=tasks.length||err?done(err):tasks[current](each)}var current=0,results=[],isSync=!0;0>2)+1;i>2]|=128<<24-(chunkLen%4<<3),bin[(-16&(chunkLen>>2)+2)+14]=0|msgLen/536870912,bin[(-16&(chunkLen>>2)+2)+15]=msgLen<<3},getRawDigest=function(heap,padMaxChunkLen){var io=new Int32Array(heap,padMaxChunkLen+320,5),out=new Int32Array(5),arr=new DataView(out.buffer);return arr.setInt32(0,io[0],!1),arr.setInt32(4,io[1],!1),arr.setInt32(8,io[2],!1),arr.setInt32(12,io[3],!1),arr.setInt32(16,io[4],!1),out},Rusha=function(){function Rusha(chunkSize){if(_classCallCheck(this,Rusha),chunkSize=chunkSize||65536,0>2);return padZeroes(view,chunkLen),padData(view,chunkLen,msgLen),padChunkLen},Rusha.prototype._write=function(data,chunkOffset,chunkLen,off){conv(data,this._h8,this._h32,chunkOffset,chunkLen,off||0)},Rusha.prototype._coreCall=function(data,chunkOffset,chunkLen,msgLen,finalize){var padChunkLen=chunkLen;this._write(data,chunkOffset,chunkLen),finalize&&(padChunkLen=this._padChunk(chunkLen,msgLen)),this._core.hash(padChunkLen,this._padMaxChunkLen)},Rusha.prototype.rawDigest=function(str){var msgLen=str.byteLength||str.length||str.size||0;this._initState(this._heap,this._padMaxChunkLen);var chunkOffset=0,chunkLen=this._maxChunkLen;for(chunkOffset=0;msgLen>chunkOffset+chunkLen;chunkOffset+=chunkLen)this._coreCall(str,chunkOffset,chunkLen,msgLen,!1);return this._coreCall(str,chunkOffset,msgLen-chunkOffset,msgLen,!0),getRawDigest(this._heap,this._padMaxChunkLen)},Rusha.prototype.digest=function(str){return toHex(this.rawDigest(str).buffer)},Rusha.prototype.digestFromString=function(str){return this.digest(str)},Rusha.prototype.digestFromBuffer=function(str){return this.digest(str)},Rusha.prototype.digestFromArrayBuffer=function(str){return this.digest(str)},Rusha.prototype.resetState=function(){return this._initState(this._heap,this._padMaxChunkLen),this},Rusha.prototype.append=function(chunk){var chunkOffset=0,chunkLen=chunk.byteLength||chunk.length||chunk.size||0,turnOffset=this._offset%this._maxChunkLen,inputLen=void 0;for(this._offset+=chunkLen;chunkOffseti;i++)precomputedHex[i]=(16>i?"0":"")+i.toString(16);module.exports.toHex=function(arrayBuffer){for(var binarray=new Uint8Array(arrayBuffer),res=Array(arrayBuffer.byteLength),_i=0;_i=v)return 65536;if(16777216>v)for(p=1;p>2],y1$857=0|H$849[x$852+324>>2],y2$859=0|H$849[x$852+328>>2],y3$861=0|H$849[x$852+332>>2],y4$863=0|H$849[x$852+336>>2],i$853=0;(0|i$853)<(0|k$851);i$853=0|i$853+64){for(z0$856=y0$855,z1$858=y1$857,z2$860=y2$859,z3$862=y3$861,z4$864=y4$863,j$854=0;64>(0|j$854);j$854=0|j$854+4)t1$866=0|H$849[i$853+j$854>>2],t0$865=0|(0|(y0$855<<5|y0$855>>>27)+(y1$857&y2$859|~y1$857&y3$861))+(0|(0|t1$866+y4$863)+1518500249),y4$863=y3$861,y3$861=y2$859,y2$859=y1$857<<30|y1$857>>>2,y1$857=y0$855,y0$855=t0$865,H$849[k$851+j$854>>2]=t1$866;for(j$854=0|k$851+64;(0|j$854)<(0|k$851+80);j$854=0|j$854+4)t1$866=(H$849[j$854-12>>2]^H$849[j$854-32>>2]^H$849[j$854-56>>2]^H$849[j$854-64>>2])<<1|(H$849[j$854-12>>2]^H$849[j$854-32>>2]^H$849[j$854-56>>2]^H$849[j$854-64>>2])>>>31,t0$865=0|(0|(y0$855<<5|y0$855>>>27)+(y1$857&y2$859|~y1$857&y3$861))+(0|(0|t1$866+y4$863)+1518500249),y4$863=y3$861,y3$861=y2$859,y2$859=y1$857<<30|y1$857>>>2,y1$857=y0$855,y0$855=t0$865,H$849[j$854>>2]=t1$866;for(j$854=0|k$851+80;(0|j$854)<(0|k$851+160);j$854=0|j$854+4)t1$866=(H$849[j$854-12>>2]^H$849[j$854-32>>2]^H$849[j$854-56>>2]^H$849[j$854-64>>2])<<1|(H$849[j$854-12>>2]^H$849[j$854-32>>2]^H$849[j$854-56>>2]^H$849[j$854-64>>2])>>>31,t0$865=0|(0|(y0$855<<5|y0$855>>>27)+(y1$857^y2$859^y3$861))+(0|(0|t1$866+y4$863)+1859775393),y4$863=y3$861,y3$861=y2$859,y2$859=y1$857<<30|y1$857>>>2,y1$857=y0$855,y0$855=t0$865,H$849[j$854>>2]=t1$866;for(j$854=0|k$851+160;(0|j$854)<(0|k$851+240);j$854=0|j$854+4)t1$866=(H$849[j$854-12>>2]^H$849[j$854-32>>2]^H$849[j$854-56>>2]^H$849[j$854-64>>2])<<1|(H$849[j$854-12>>2]^H$849[j$854-32>>2]^H$849[j$854-56>>2]^H$849[j$854-64>>2])>>>31,t0$865=0|(0|(y0$855<<5|y0$855>>>27)+(y1$857&y2$859|y1$857&y3$861|y2$859&y3$861))+(0|(0|t1$866+y4$863)-1894007588),y4$863=y3$861,y3$861=y2$859,y2$859=y1$857<<30|y1$857>>>2,y1$857=y0$855,y0$855=t0$865,H$849[j$854>>2]=t1$866;for(j$854=0|k$851+240;(0|j$854)<(0|k$851+320);j$854=0|j$854+4)t1$866=(H$849[j$854-12>>2]^H$849[j$854-32>>2]^H$849[j$854-56>>2]^H$849[j$854-64>>2])<<1|(H$849[j$854-12>>2]^H$849[j$854-32>>2]^H$849[j$854-56>>2]^H$849[j$854-64>>2])>>>31,t0$865=0|(0|(y0$855<<5|y0$855>>>27)+(y1$857^y2$859^y3$861))+(0|(0|t1$866+y4$863)-899497514),y4$863=y3$861,y3$861=y2$859,y2$859=y1$857<<30|y1$857>>>2,y1$857=y0$855,y0$855=t0$865,H$849[j$854>>2]=t1$866;y0$855=0|y0$855+z0$856,y1$857=0|y1$857+z1$858,y2$859=0|y2$859+z2$860,y3$861=0|y3$861+z3$862,y4$863=0|y4$863+z4$864}H$849[x$852+320>>2]=y0$855,H$849[x$852+324>>2]=y1$857,H$849[x$852+328>>2]=y2$859,H$849[x$852+332>>2]=y3$861,H$849[x$852+336>>2]=y4$863}}}},function(module){var _this=this,reader=void 0;"undefined"!=typeof self&&"undefined"!=typeof self.FileReaderSync&&(reader=new self.FileReaderSync);var convStr=function(str,H8,H32,start,len,off){var om=off%4,lm=(len+om)%4,j=len-lm,i;switch(om){case 0:H8[off]=str.charCodeAt(start+3);case 1:H8[0|off+1-(om<<1)]=str.charCodeAt(start+2);case 2:H8[0|off+2-(om<<1)]=str.charCodeAt(start+1);case 3:H8[0|off+3-(om<<1)]=str.charCodeAt(start);}if(!(len>2]=str.charCodeAt(start+i)<<24|str.charCodeAt(start+i+1)<<16|str.charCodeAt(start+i+2)<<8|str.charCodeAt(start+i+3);switch(lm){case 3:H8[0|off+j+1]=str.charCodeAt(start+j+2);case 2:H8[0|off+j+2]=str.charCodeAt(start+j+1);case 1:H8[0|off+j+3]=str.charCodeAt(start+j);}}},convBuf=function(buf,H8,H32,start,len,off){var om=off%4,lm=(len+om)%4,j=len-lm,i;switch(om){case 0:H8[off]=buf[start+3];case 1:H8[0|off+1-(om<<1)]=buf[start+2];case 2:H8[0|off+2-(om<<1)]=buf[start+1];case 3:H8[0|off+3-(om<<1)]=buf[start];}if(!(len>2]=buf[start+i]<<24|buf[start+i+1]<<16|buf[start+i+2]<<8|buf[start+i+3];switch(lm){case 3:H8[0|off+j+1]=buf[start+j+2];case 2:H8[0|off+j+2]=buf[start+j+1];case 1:H8[0|off+j+3]=buf[start+j];}}},convBlob=function(blob,H8,H32,start,len,off){var i=void 0,om=off%4,lm=(len+om)%4,j=len-lm,buf=new Uint8Array(reader.readAsArrayBuffer(blob.slice(start,start+len)));switch(om){case 0:H8[off]=buf[3];case 1:H8[0|off+1-(om<<1)]=buf[2];case 2:H8[0|off+2-(om<<1)]=buf[1];case 3:H8[0|off+3-(om<<1)]=buf[0];}if(!(len>2]=buf[i]<<24|buf[i+1]<<16|buf[i+2]<<8|buf[i+3];switch(lm){case 3:H8[0|off+j+1]=buf[j+2];case 2:H8[0|off+j+2]=buf[j+1];case 1:H8[0|off+j+3]=buf[j];}}};module.exports=function(data,H8,H32,start,len,off){if("string"==typeof data)return convStr(data,H8,H32,start,len,off);if(data instanceof Array)return convBuf(data,H8,H32,start,len,off);if(_this&&_this.Buffer&&_this.Buffer.isBuffer(data))return convBuf(data,H8,H32,start,len,off);if(data instanceof ArrayBuffer)return convBuf(new Uint8Array(data),H8,H32,start,len,off);if(data.buffer instanceof ArrayBuffer)return convBuf(new Uint8Array(data.buffer,data.byteOffset,data.byteLength),H8,H32,start,len,off);if(data instanceof Blob)return convBlob(data,H8,H32,start,len,off);throw new Error("Unsupported data type.")}},function(module,exports,__webpack_require__){function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}var Rusha=__webpack_require__(0),_require=__webpack_require__(1),toHex=_require.toHex,Hash=function(){function Hash(){_classCallCheck(this,Hash),this._rusha=new Rusha,this._rusha.resetState()}return Hash.prototype.update=function(data){return this._rusha.append(data),this},Hash.prototype.digest=function digest(encoding){var digest=this._rusha.rawEnd().buffer;if(!encoding)return digest;if("hex"===encoding)return toHex(digest);throw new Error("unsupported digest encoding")},Hash}();module.exports=function(){return new Hash}}])})},{}],165:[function(require,module,exports){function copyProps(src,dst){for(var key in src)dst[key]=src[key]}function SafeBuffer(arg,encodingOrOffset,length){return Buffer(arg,encodingOrOffset,length)}/*! safe-buffer. MIT License. Feross Aboukhadijeh */var buffer=require("buffer"),Buffer=buffer.Buffer;Buffer.from&&Buffer.alloc&&Buffer.allocUnsafe&&Buffer.allocUnsafeSlow?module.exports=buffer:(copyProps(buffer,exports),exports.Buffer=SafeBuffer),SafeBuffer.prototype=Object.create(Buffer.prototype),copyProps(Buffer,SafeBuffer),SafeBuffer.from=function(arg,encodingOrOffset,length){if("number"==typeof arg)throw new TypeError("Argument must not be a number");return Buffer(arg,encodingOrOffset,length)},SafeBuffer.alloc=function(size,fill,encoding){if("number"!=typeof size)throw new TypeError("Argument must be a number");var buf=Buffer(size);return void 0===fill?buf.fill(0):"string"==typeof encoding?buf.fill(fill,encoding):buf.fill(fill),buf},SafeBuffer.allocUnsafe=function(size){if("number"!=typeof size)throw new TypeError("Argument must be a number");return Buffer(size)},SafeBuffer.allocUnsafeSlow=function(size){if("number"!=typeof size)throw new TypeError("Argument must be a number");return buffer.SlowBuffer(size)}},{buffer:38}],166:[function(require,module){(function(Buffer){(function(){/*! simple-concat. MIT License. Feross Aboukhadijeh */module.exports=function(stream,cb){var chunks=[];stream.on("data",function(chunk){chunks.push(chunk)}),stream.once("end",function(){cb&&cb(null,Buffer.concat(chunks)),cb=null}),stream.once("error",function(err){cb&&cb(err),cb=null})}}).call(this)}).call(this,require("buffer").Buffer)},{buffer:38}],167:[function(require,module){(function(Buffer){(function(){function simpleGet(opts,cb){if(opts=Object.assign({maxRedirects:10},"string"==typeof opts?{url:opts}:opts),cb=once(cb),opts.url){const{hostname,port,protocol,auth,path}=url.parse(opts.url);delete opts.url,hostname||port||protocol||auth?Object.assign(opts,{hostname,port,protocol,auth,path}):opts.path=path}const headers={"accept-encoding":"gzip, deflate"};opts.headers&&Object.keys(opts.headers).forEach(k=>headers[k.toLowerCase()]=opts.headers[k]),opts.headers=headers;let body;opts.body?body=opts.json&&!isStream(opts.body)?JSON.stringify(opts.body):opts.body:opts.form&&(body="string"==typeof opts.form?opts.form:querystring.stringify(opts.form),opts.headers["content-type"]="application/x-www-form-urlencoded"),body&&(!opts.method&&(opts.method="POST"),!isStream(body)&&(opts.headers["content-length"]=Buffer.byteLength(body)),opts.json&&!opts.form&&(opts.headers["content-type"]="application/json")),delete opts.body,delete opts.form,opts.json&&(opts.headers.accept="application/json"),opts.method&&(opts.method=opts.method.toUpperCase());const protocol="https:"===opts.protocol?https:http,req=protocol.request(opts,res=>{if(!1!==opts.followRedirects&&300<=res.statusCode&&400>res.statusCode&&res.headers.location)return opts.url=res.headers.location,delete opts.headers.host,res.resume(),"POST"===opts.method&&[301,302].includes(res.statusCode)&&(opts.method="GET",delete opts.headers["content-length"],delete opts.headers["content-type"]),0==opts.maxRedirects--?cb(new Error("too many redirects")):simpleGet(opts,cb);const tryUnzip="function"==typeof decompressResponse&&"HEAD"!==opts.method;cb(null,tryUnzip?decompressResponse(res):res)});return req.on("timeout",()=>{req.abort(),cb(new Error("Request timed out"))}),req.on("error",cb),isStream(body)?body.on("error",cb).pipe(req):req.end(body),req}module.exports=simpleGet;const concat=require("simple-concat"),decompressResponse=require("decompress-response"),http=require("http"),https=require("https"),once=require("once"),querystring=require("querystring"),url=require("url"),isStream=o=>null!==o&&"object"==typeof o&&"function"==typeof o.pipe;simpleGet.concat=(opts,cb)=>simpleGet(opts,(err,res)=>err?cb(err):void concat(res,(err,data)=>{if(err)return cb(err);if(opts.json)try{data=JSON.parse(data.toString())}catch(err){return cb(err,res,data)}cb(null,res,data)})),["get","post","put","patch","head","delete"].forEach(method=>{simpleGet[method]=(opts,cb)=>("string"==typeof opts&&(opts={url:opts}),simpleGet(Object.assign({method:method.toUpperCase()},opts),cb))})}).call(this)}).call(this,require("buffer").Buffer)},{buffer:38,"decompress-response":36,http:173,https:94,once:129,querystring:137,"simple-concat":166,url:192}],168:[function(require,module){function filterTrickle(sdp){return sdp.replace(/a=ice-options:trickle\s\n/g,"")}function warn(message){console.warn(message)}/*! simple-peer. MIT License. Feross Aboukhadijeh */const debug=require("debug")("simple-peer"),getBrowserRTC=require("get-browser-rtc"),randombytes=require("randombytes"),stream=require("readable-stream"),queueMicrotask=require("queue-microtask"),errCode=require("err-code"),{Buffer}=require("buffer"),MAX_BUFFERED_AMOUNT=65536;class Peer extends stream.Duplex{constructor(opts){if(opts=Object.assign({allowHalfOpen:!1},opts),super(opts),this._id=randombytes(4).toString("hex").slice(0,7),this._debug("new peer %o",opts),this.channelName=opts.initiator?opts.channelName||randombytes(20).toString("hex"):null,this.initiator=opts.initiator||!1,this.channelConfig=opts.channelConfig||Peer.channelConfig,this.channelNegotiated=this.channelConfig.negotiated,this.config=Object.assign({},Peer.config,opts.config),this.offerOptions=opts.offerOptions||{},this.answerOptions=opts.answerOptions||{},this.sdpTransform=opts.sdpTransform||(sdp=>sdp),this.streams=opts.streams||(opts.stream?[opts.stream]:[]),this.trickle=void 0===opts.trickle||opts.trickle,this.allowHalfTrickle=void 0!==opts.allowHalfTrickle&&opts.allowHalfTrickle,this.iceCompleteTimeout=opts.iceCompleteTimeout||5000,this.destroyed=!1,this.destroying=!1,this._connected=!1,this.remoteAddress=void 0,this.remoteFamily=void 0,this.remotePort=void 0,this.localAddress=void 0,this.localFamily=void 0,this.localPort=void 0,this._wrtc=opts.wrtc&&"object"==typeof opts.wrtc?opts.wrtc:getBrowserRTC(),!this._wrtc)if("undefined"==typeof window)throw errCode(new Error("No WebRTC support: Specify `opts.wrtc` option in this environment"),"ERR_WEBRTC_SUPPORT");else throw errCode(new Error("No WebRTC support: Not a supported browser"),"ERR_WEBRTC_SUPPORT");this._pcReady=!1,this._channelReady=!1,this._iceComplete=!1,this._iceCompleteTimer=null,this._channel=null,this._pendingCandidates=[],this._isNegotiating=!1,this._firstNegotiation=!0,this._batchedNegotiation=!1,this._queuedNegotiation=!1,this._sendersAwaitingStable=[],this._senderMap=new Map,this._closingInterval=null,this._remoteTracks=[],this._remoteStreams=[],this._chunk=null,this._cb=null,this._interval=null;try{this._pc=new this._wrtc.RTCPeerConnection(this.config)}catch(err){return void queueMicrotask(()=>this.destroy(errCode(err,"ERR_PC_CONSTRUCTOR")))}this._isReactNativeWebrtc="number"==typeof this._pc._peerConnectionId,this._pc.oniceconnectionstatechange=()=>{this._onIceStateChange()},this._pc.onicegatheringstatechange=()=>{this._onIceStateChange()},this._pc.onconnectionstatechange=()=>{this._onConnectionStateChange()},this._pc.onsignalingstatechange=()=>{this._onSignalingStateChange()},this._pc.onicecandidate=event=>{this._onIceCandidate(event)},this.initiator||this.channelNegotiated?this._setupData({channel:this._pc.createDataChannel(this.channelName,this.channelConfig)}):this._pc.ondatachannel=event=>{this._setupData(event)},this.streams&&this.streams.forEach(stream=>{this.addStream(stream)}),this._pc.ontrack=event=>{this._onTrack(event)},this._debug("initial negotiation"),this._needsNegotiation(),this._onFinishBound=()=>{this._onFinish()},this.once("finish",this._onFinishBound)}get bufferSize(){return this._channel&&this._channel.bufferedAmount||0}get connected(){return this._connected&&"open"===this._channel.readyState}address(){return{port:this.localPort,family:this.localFamily,address:this.localAddress}}signal(data){if(this.destroyed)throw errCode(new Error("cannot signal after peer is destroyed"),"ERR_SIGNALING");if("string"==typeof data)try{data=JSON.parse(data)}catch(err){data={}}this._debug("signal()"),data.renegotiate&&this.initiator&&(this._debug("got request to renegotiate"),this._needsNegotiation()),data.transceiverRequest&&this.initiator&&(this._debug("got request for transceiver"),this.addTransceiver(data.transceiverRequest.kind,data.transceiverRequest.init)),data.candidate&&(this._pc.remoteDescription&&this._pc.remoteDescription.type?this._addIceCandidate(data.candidate):this._pendingCandidates.push(data.candidate)),data.sdp&&this._pc.setRemoteDescription(new this._wrtc.RTCSessionDescription(data)).then(()=>{this.destroyed||(this._pendingCandidates.forEach(candidate=>{this._addIceCandidate(candidate)}),this._pendingCandidates=[],"offer"===this._pc.remoteDescription.type&&this._createAnswer())}).catch(err=>{this.destroy(errCode(err,"ERR_SET_REMOTE_DESCRIPTION"))}),data.sdp||data.candidate||data.renegotiate||data.transceiverRequest||this.destroy(errCode(new Error("signal() called with invalid signal data"),"ERR_SIGNALING"))}_addIceCandidate(candidate){const iceCandidateObj=new this._wrtc.RTCIceCandidate(candidate);this._pc.addIceCandidate(iceCandidateObj).catch(err=>{!iceCandidateObj.address||iceCandidateObj.address.endsWith(".local")?warn("Ignoring unsupported ICE candidate."):this.destroy(errCode(err,"ERR_ADD_ICE_CANDIDATE"))})}send(chunk){this._channel.send(chunk)}addTransceiver(kind,init){if(this._debug("addTransceiver()"),this.initiator)try{this._pc.addTransceiver(kind,init),this._needsNegotiation()}catch(err){this.destroy(errCode(err,"ERR_ADD_TRANSCEIVER"))}else this.emit("signal",{type:"transceiverRequest",transceiverRequest:{kind,init}})}addStream(stream){this._debug("addStream()"),stream.getTracks().forEach(track=>{this.addTrack(track,stream)})}addTrack(track,stream){this._debug("addTrack()");const submap=this._senderMap.get(track)||new Map;let sender=submap.get(stream);if(!sender)sender=this._pc.addTrack(track,stream),submap.set(stream,sender),this._senderMap.set(track,submap),this._needsNegotiation();else if(sender.removed)throw errCode(new Error("Track has been removed. You should enable/disable tracks that you want to re-add."),"ERR_SENDER_REMOVED");else throw errCode(new Error("Track has already been added to that stream."),"ERR_SENDER_ALREADY_ADDED")}replaceTrack(oldTrack,newTrack,stream){this._debug("replaceTrack()");const submap=this._senderMap.get(oldTrack),sender=submap?submap.get(stream):null;if(!sender)throw errCode(new Error("Cannot replace track that was never added."),"ERR_TRACK_NOT_ADDED");newTrack&&this._senderMap.set(newTrack,submap),null==sender.replaceTrack?this.destroy(errCode(new Error("replaceTrack is not supported in this browser"),"ERR_UNSUPPORTED_REPLACETRACK")):sender.replaceTrack(newTrack)}removeTrack(track,stream){this._debug("removeSender()");const submap=this._senderMap.get(track),sender=submap?submap.get(stream):null;if(!sender)throw errCode(new Error("Cannot remove track that was never added."),"ERR_TRACK_NOT_ADDED");try{sender.removed=!0,this._pc.removeTrack(sender)}catch(err){"NS_ERROR_UNEXPECTED"===err.name?this._sendersAwaitingStable.push(sender):this.destroy(errCode(err,"ERR_REMOVE_TRACK"))}this._needsNegotiation()}removeStream(stream){this._debug("removeSenders()"),stream.getTracks().forEach(track=>{this.removeTrack(track,stream)})}_needsNegotiation(){this._debug("_needsNegotiation");this._batchedNegotiation||(this._batchedNegotiation=!0,queueMicrotask(()=>{this._batchedNegotiation=!1,this.initiator||!this._firstNegotiation?(this._debug("starting batched negotiation"),this.negotiate()):this._debug("non-initiator initial negotiation request discarded"),this._firstNegotiation=!1}))}negotiate(){this.initiator?this._isNegotiating?(this._queuedNegotiation=!0,this._debug("already negotiating, queueing")):(this._debug("start negotiation"),setTimeout(()=>{this._createOffer()},0)):this._isNegotiating?(this._queuedNegotiation=!0,this._debug("already negotiating, queueing")):(this._debug("requesting negotiation from initiator"),this.emit("signal",{type:"renegotiate",renegotiate:!0})),this._isNegotiating=!0}destroy(err){this._destroy(err,()=>{})}_destroy(err,cb){this.destroyed||this.destroying||(this.destroying=!0,this._debug("destroying (error: %s)",err&&(err.message||err)),queueMicrotask(()=>{if(this.destroyed=!0,this.destroying=!1,this._debug("destroy (error: %s)",err&&(err.message||err)),this.readable=this.writable=!1,this._readableState.ended||this.push(null),this._writableState.finished||this.end(),this._connected=!1,this._pcReady=!1,this._channelReady=!1,this._remoteTracks=null,this._remoteStreams=null,this._senderMap=null,clearInterval(this._closingInterval),this._closingInterval=null,clearInterval(this._interval),this._interval=null,this._chunk=null,this._cb=null,this._onFinishBound&&this.removeListener("finish",this._onFinishBound),this._onFinishBound=null,this._channel){try{this._channel.close()}catch(err){}this._channel.onmessage=null,this._channel.onopen=null,this._channel.onclose=null,this._channel.onerror=null}if(this._pc){try{this._pc.close()}catch(err){}this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ontrack=null,this._pc.ondatachannel=null}this._pc=null,this._channel=null,err&&this.emit("error",err),this.emit("close"),cb()}))}_setupData(event){if(!event.channel)return this.destroy(errCode(new Error("Data channel event is missing `channel` property"),"ERR_DATA_CHANNEL"));this._channel=event.channel,this._channel.binaryType="arraybuffer","number"==typeof this._channel.bufferedAmountLowThreshold&&(this._channel.bufferedAmountLowThreshold=MAX_BUFFERED_AMOUNT),this.channelName=this._channel.label,this._channel.onmessage=event=>{this._onChannelMessage(event)},this._channel.onbufferedamountlow=()=>{this._onChannelBufferedAmountLow()},this._channel.onopen=()=>{this._onChannelOpen()},this._channel.onclose=()=>{this._onChannelClose()},this._channel.onerror=err=>{this.destroy(errCode(err,"ERR_DATA_CHANNEL"))};let isClosing=!1;this._closingInterval=setInterval(()=>{this._channel&&"closing"===this._channel.readyState?(isClosing&&this._onChannelClose(),isClosing=!0):isClosing=!1},5000)}_read(){}_write(chunk,encoding,cb){if(this.destroyed)return cb(errCode(new Error("cannot write after peer is destroyed"),"ERR_DATA_CHANNEL"));if(this._connected){try{this.send(chunk)}catch(err){return this.destroy(errCode(err,"ERR_DATA_CHANNEL"))}this._channel.bufferedAmount>MAX_BUFFERED_AMOUNT?(this._debug("start backpressure: bufferedAmount %d",this._channel.bufferedAmount),this._cb=cb):cb(null)}else this._debug("write before connect"),this._chunk=chunk,this._cb=cb}_onFinish(){if(!this.destroyed){const destroySoon=()=>{setTimeout(()=>this.destroy(),1e3)};this._connected?destroySoon():this.once("connect",destroySoon)}}_startIceCompleteTimeout(){this.destroyed||this._iceCompleteTimer||(this._debug("started iceComplete timeout"),this._iceCompleteTimer=setTimeout(()=>{this._iceComplete||(this._iceComplete=!0,this._debug("iceComplete timeout completed"),this.emit("iceTimeout"),this.emit("_iceComplete"))},this.iceCompleteTimeout))}_createOffer(){this.destroyed||this._pc.createOffer(this.offerOptions).then(offer=>{if(this.destroyed)return;this.trickle||this.allowHalfTrickle||(offer.sdp=filterTrickle(offer.sdp)),offer.sdp=this.sdpTransform(offer.sdp);const sendOffer=()=>{if(!this.destroyed){const signal=this._pc.localDescription||offer;this._debug("signal"),this.emit("signal",{type:signal.type,sdp:signal.sdp})}};this._pc.setLocalDescription(offer).then(()=>{this._debug("createOffer success");this.destroyed||(this.trickle||this._iceComplete?sendOffer():this.once("_iceComplete",sendOffer))}).catch(err=>{this.destroy(errCode(err,"ERR_SET_LOCAL_DESCRIPTION"))})}).catch(err=>{this.destroy(errCode(err,"ERR_CREATE_OFFER"))})}_requestMissingTransceivers(){this._pc.getTransceivers&&this._pc.getTransceivers().forEach(transceiver=>{transceiver.mid||!transceiver.sender.track||transceiver.requested||(transceiver.requested=!0,this.addTransceiver(transceiver.sender.track.kind))})}_createAnswer(){this.destroyed||this._pc.createAnswer(this.answerOptions).then(answer=>{if(this.destroyed)return;this.trickle||this.allowHalfTrickle||(answer.sdp=filterTrickle(answer.sdp)),answer.sdp=this.sdpTransform(answer.sdp);const sendAnswer=()=>{if(!this.destroyed){const signal=this._pc.localDescription||answer;this._debug("signal"),this.emit("signal",{type:signal.type,sdp:signal.sdp}),this.initiator||this._requestMissingTransceivers()}};this._pc.setLocalDescription(answer).then(()=>{this.destroyed||(this.trickle||this._iceComplete?sendAnswer():this.once("_iceComplete",sendAnswer))}).catch(err=>{this.destroy(errCode(err,"ERR_SET_LOCAL_DESCRIPTION"))})}).catch(err=>{this.destroy(errCode(err,"ERR_CREATE_ANSWER"))})}_onConnectionStateChange(){this.destroyed||"failed"===this._pc.connectionState&&this.destroy(errCode(new Error("Connection failed."),"ERR_CONNECTION_FAILURE"))}_onIceStateChange(){if(this.destroyed)return;const iceConnectionState=this._pc.iceConnectionState,iceGatheringState=this._pc.iceGatheringState;this._debug("iceStateChange (connection: %s) (gathering: %s)",iceConnectionState,iceGatheringState),this.emit("iceStateChange",iceConnectionState,iceGatheringState),("connected"===iceConnectionState||"completed"===iceConnectionState)&&(this._pcReady=!0,this._maybeReady()),"failed"===iceConnectionState&&this.destroy(errCode(new Error("Ice connection failed."),"ERR_ICE_CONNECTION_FAILURE")),"closed"===iceConnectionState&&this.destroy(errCode(new Error("Ice connection closed."),"ERR_ICE_CONNECTION_CLOSED"))}getStats(cb){const flattenValues=report=>("[object Array]"===Object.prototype.toString.call(report.values)&&report.values.forEach(value=>{Object.assign(report,value)}),report);0===this._pc.getStats.length||this._isReactNativeWebrtc?this._pc.getStats().then(res=>{const reports=[];res.forEach(report=>{reports.push(flattenValues(report))}),cb(null,reports)},err=>cb(err)):0{if(this.destroyed)return;const reports=[];res.result().forEach(result=>{const report={};result.names().forEach(name=>{report[name]=result.stat(name)}),report.id=result.id,report.type=result.type,report.timestamp=result.timestamp,reports.push(flattenValues(report))}),cb(null,reports)},err=>cb(err)):cb(null,[])}_maybeReady(){if(this._debug("maybeReady pc %s channel %s",this._pcReady,this._channelReady),this._connected||this._connecting||!this._pcReady||!this._channelReady)return;this._connecting=!0;const findCandidatePair=()=>{this.destroyed||this.getStats((err,items)=>{if(this.destroyed)return;err&&(items=[]);const remoteCandidates={},localCandidates={},candidatePairs={};let foundSelectedCandidatePair=!1;items.forEach(item=>{("remotecandidate"===item.type||"remote-candidate"===item.type)&&(remoteCandidates[item.id]=item),("localcandidate"===item.type||"local-candidate"===item.type)&&(localCandidates[item.id]=item),("candidatepair"===item.type||"candidate-pair"===item.type)&&(candidatePairs[item.id]=item)});const setSelectedCandidatePair=selectedCandidatePair=>{foundSelectedCandidatePair=!0;let local=localCandidates[selectedCandidatePair.localCandidateId];local&&(local.ip||local.address)?(this.localAddress=local.ip||local.address,this.localPort=+local.port):local&&local.ipAddress?(this.localAddress=local.ipAddress,this.localPort=+local.portNumber):"string"==typeof selectedCandidatePair.googLocalAddress&&(local=selectedCandidatePair.googLocalAddress.split(":"),this.localAddress=local[0],this.localPort=+local[1]),this.localAddress&&(this.localFamily=this.localAddress.includes(":")?"IPv6":"IPv4");let remote=remoteCandidates[selectedCandidatePair.remoteCandidateId];remote&&(remote.ip||remote.address)?(this.remoteAddress=remote.ip||remote.address,this.remotePort=+remote.port):remote&&remote.ipAddress?(this.remoteAddress=remote.ipAddress,this.remotePort=+remote.portNumber):"string"==typeof selectedCandidatePair.googRemoteAddress&&(remote=selectedCandidatePair.googRemoteAddress.split(":"),this.remoteAddress=remote[0],this.remotePort=+remote[1]),this.remoteAddress&&(this.remoteFamily=this.remoteAddress.includes(":")?"IPv6":"IPv4"),this._debug("connect local: %s:%s remote: %s:%s",this.localAddress,this.localPort,this.remoteAddress,this.remotePort)};if(items.forEach(item=>{"transport"===item.type&&item.selectedCandidatePairId&&setSelectedCandidatePair(candidatePairs[item.selectedCandidatePairId]),("googCandidatePair"===item.type&&"true"===item.googActiveConnection||("candidatepair"===item.type||"candidate-pair"===item.type)&&item.selected)&&setSelectedCandidatePair(item)}),!foundSelectedCandidatePair&&(!Object.keys(candidatePairs).length||Object.keys(localCandidates).length))return void setTimeout(findCandidatePair,100);if(this._connecting=!1,this._connected=!0,this._chunk){try{this.send(this._chunk)}catch(err){return this.destroy(errCode(err,"ERR_DATA_CHANNEL"))}this._chunk=null,this._debug("sent chunk from \"write before connect\"");const cb=this._cb;this._cb=null,cb(null)}"number"!=typeof this._channel.bufferedAmountLowThreshold&&(this._interval=setInterval(()=>this._onInterval(),150),this._interval.unref&&this._interval.unref()),this._debug("connect"),this.emit("connect")})};findCandidatePair()}_onInterval(){this._cb&&this._channel&&!(this._channel.bufferedAmount>MAX_BUFFERED_AMOUNT)&&this._onChannelBufferedAmountLow()}_onSignalingStateChange(){this.destroyed||("stable"===this._pc.signalingState&&(this._isNegotiating=!1,this._debug("flushing sender queue",this._sendersAwaitingStable),this._sendersAwaitingStable.forEach(sender=>{this._pc.removeTrack(sender),this._queuedNegotiation=!0}),this._sendersAwaitingStable=[],this._queuedNegotiation?(this._debug("flushing negotiation queue"),this._queuedNegotiation=!1,this._needsNegotiation()):(this._debug("negotiated"),this.emit("negotiated"))),this._debug("signalingStateChange %s",this._pc.signalingState),this.emit("signalingStateChange",this._pc.signalingState))}_onIceCandidate(event){this.destroyed||(event.candidate&&this.trickle?this.emit("signal",{type:"candidate",candidate:{candidate:event.candidate.candidate,sdpMLineIndex:event.candidate.sdpMLineIndex,sdpMid:event.candidate.sdpMid}}):!event.candidate&&!this._iceComplete&&(this._iceComplete=!0,this.emit("_iceComplete")),event.candidate&&this._startIceCompleteTimeout())}_onChannelMessage(event){if(this.destroyed)return;let data=event.data;data instanceof ArrayBuffer&&(data=Buffer.from(data)),this.push(data)}_onChannelBufferedAmountLow(){if(!this.destroyed&&this._cb){this._debug("ending backpressure: bufferedAmount %d",this._channel.bufferedAmount);const cb=this._cb;this._cb=null,cb(null)}}_onChannelOpen(){this._connected||this.destroyed||(this._debug("on channel open"),this._channelReady=!0,this._maybeReady())}_onChannelClose(){this.destroyed||(this._debug("on channel close"),this.destroy())}_onTrack(event){this.destroyed||event.streams.forEach(eventStream=>{this._debug("on track"),this.emit("track",event.track,eventStream),this._remoteTracks.push({track:event.track,stream:eventStream});this._remoteStreams.some(remoteStream=>remoteStream.id===eventStream.id)||(this._remoteStreams.push(eventStream),queueMicrotask(()=>{this._debug("on stream"),this.emit("stream",eventStream)}))})}_debug(){const args=[].slice.call(arguments);args[0]="["+this._id+"] "+args[0],debug.apply(null,args)}}Peer.WEBRTC_SUPPORT=!!getBrowserRTC(),Peer.config={iceServers:[{urls:["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478"]}],sdpSemantics:"unified-plan"},Peer.channelConfig={},module.exports=Peer},{buffer:38,debug:69,"err-code":72,"get-browser-rtc":83,"queue-microtask":138,randombytes:140,"readable-stream":157}],169:[function(require,module){function sha1sync(buf){return rusha.digest(buf)}function sha1(buf,cb){return subtle?void("string"==typeof buf&&(buf=uint8array(buf)),subtle.digest({name:"sha-1"},buf).then(function(result){cb(hex(new Uint8Array(result)))},function(){cb(sha1sync(buf))})):void("undefined"==typeof window?queueMicrotask(()=>cb(sha1sync(buf))):rushaWorkerSha1(buf,function(err,hash){return err?void cb(sha1sync(buf)):void cb(hash)}))}function uint8array(s){for(var l=s.length,array=new Uint8Array(l),i=0;i>>4).toString(16)),chars.push((15&bite).toString(16));return chars.join("")}var Rusha=require("rusha"),rushaWorkerSha1=require("./rusha-worker-sha1"),rusha=new Rusha,scope="undefined"==typeof window?self:window,crypto=scope.crypto||scope.msCrypto||{},subtle=crypto.subtle||crypto.webkitSubtle;try{subtle.digest({name:"sha-1"},new Uint8Array).catch(function(){subtle=!1})}catch(err){subtle=!1}module.exports=sha1,module.exports.sync=sha1sync},{"./rusha-worker-sha1":170,rusha:164}],170:[function(require,module){function init(){worker=Rusha.createWorker(),nextTaskId=1,cbs={},worker.onmessage=function(e){var taskId=e.data.id,cb=cbs[taskId];delete cbs[taskId],null==e.data.error?cb(null,e.data.hash):cb(new Error("Rusha worker error: "+e.data.error))}}function sha1(buf,cb){worker||init(),cbs[nextTaskId]=cb,worker.postMessage({id:nextTaskId,data:buf}),nextTaskId+=1}var Rusha=require("rusha"),worker,nextTaskId,cbs;module.exports=sha1},{rusha:164}],171:[function(require,module){(function(Buffer){(function(){const debug=require("debug")("simple-websocket"),randombytes=require("randombytes"),stream=require("readable-stream"),queueMicrotask=require("queue-microtask"),ws=require("ws"),_WebSocket="function"==typeof ws?ws:WebSocket,MAX_BUFFERED_AMOUNT=65536;class Socket extends stream.Duplex{constructor(opts={}){if("string"==typeof opts&&(opts={url:opts}),opts=Object.assign({allowHalfOpen:!1},opts),super(opts),null==opts.url&&null==opts.socket)throw new Error("Missing required `url` or `socket` option");if(null!=opts.url&&null!=opts.socket)throw new Error("Must specify either `url` or `socket` option, not both");if(this._id=randombytes(4).toString("hex").slice(0,7),this._debug("new websocket: %o",opts),this.connected=!1,this.destroyed=!1,this._chunk=null,this._cb=null,this._interval=null,opts.socket)this.url=opts.socket.url,this._ws=opts.socket,this.connected=opts.socket.readyState===_WebSocket.OPEN;else{this.url=opts.url;try{this._ws="function"==typeof ws?new _WebSocket(opts.url,opts):new _WebSocket(opts.url)}catch(err){return void queueMicrotask(()=>this.destroy(err))}}this._ws.binaryType="arraybuffer",this._ws.onopen=()=>{this._onOpen()},this._ws.onmessage=event=>{this._onMessage(event)},this._ws.onclose=()=>{this._onClose()},this._ws.onerror=()=>{this.destroy(new Error("connection error to "+this.url))},this._onFinishBound=()=>{this._onFinish()},this.once("finish",this._onFinishBound)}send(chunk){this._ws.send(chunk)}destroy(err){this._destroy(err,()=>{})}_destroy(err,cb){if(!this.destroyed){if(this._debug("destroy (error: %s)",err&&(err.message||err)),this.readable=this.writable=!1,this._readableState.ended||this.push(null),this._writableState.finished||this.end(),this.connected=!1,this.destroyed=!0,clearInterval(this._interval),this._interval=null,this._chunk=null,this._cb=null,this._onFinishBound&&this.removeListener("finish",this._onFinishBound),this._onFinishBound=null,this._ws){const ws=this._ws,onClose=()=>{ws.onclose=null};if(ws.readyState===_WebSocket.CLOSED)onClose();else try{ws.onclose=onClose,ws.close()}catch(err){onClose()}ws.onopen=null,ws.onmessage=null,ws.onerror=()=>{}}if(this._ws=null,err){if("undefined"!=typeof DOMException&&err instanceof DOMException){const code=err.code;err=new Error(err.message),err.code=code}this.emit("error",err)}this.emit("close"),cb()}}_read(){}_write(chunk,encoding,cb){if(this.destroyed)return cb(new Error("cannot write after socket is destroyed"));if(this.connected){try{this.send(chunk)}catch(err){return this.destroy(err)}"function"!=typeof ws&&this._ws.bufferedAmount>MAX_BUFFERED_AMOUNT?(this._debug("start backpressure: bufferedAmount %d",this._ws.bufferedAmount),this._cb=cb):cb(null)}else this._debug("write before connect"),this._chunk=chunk,this._cb=cb}_onFinish(){if(!this.destroyed){const destroySoon=()=>{setTimeout(()=>this.destroy(),1e3)};this.connected?destroySoon():this.once("connect",destroySoon)}}_onMessage(event){if(this.destroyed)return;let data=event.data;data instanceof ArrayBuffer&&(data=Buffer.from(data)),this.push(data)}_onOpen(){if(!(this.connected||this.destroyed)){if(this.connected=!0,this._chunk){try{this.send(this._chunk)}catch(err){return this.destroy(err)}this._chunk=null,this._debug("sent chunk from \"write before connect\"");const cb=this._cb;this._cb=null,cb(null)}"function"!=typeof ws&&(this._interval=setInterval(()=>this._onInterval(),150),this._interval.unref&&this._interval.unref()),this._debug("connect"),this.emit("connect")}}_onInterval(){if(this._cb&&this._ws&&!(this._ws.bufferedAmount>MAX_BUFFERED_AMOUNT)){this._debug("ending backpressure: bufferedAmount %d",this._ws.bufferedAmount);const cb=this._cb;this._cb=null,cb(null)}}_onClose(){this.destroyed||(this._debug("on close"),this.destroy())}_debug(){const args=[].slice.call(arguments);args[0]="["+this._id+"] "+args[0],debug.apply(null,args)}}Socket.WEBSOCKET_SUPPORT=!!_WebSocket,module.exports=Socket}).call(this)}).call(this,require("buffer").Buffer)},{buffer:38,debug:69,"queue-microtask":138,randombytes:140,"readable-stream":157,ws:36}],172:[function(require,module){var tick=1,maxTick=65535,resolution=4,inc=function(){tick=tick+1&maxTick},timer;module.exports=function(seconds){timer||(timer=setInterval(inc,0|1e3/resolution),timer.unref&&timer.unref());var size=resolution*(seconds||5),buffer=[0],pointer=1,last=tick-1&maxTick;return function(delta){var dist=tick-last&maxTick;for(dist>size&&(dist=size),last=tick;dist--;)pointer===size&&(pointer=0),buffer[pointer]=buffer[0===pointer?size-1:pointer-1],pointer++;delta&&(buffer[pointer-1]+=delta);var top=buffer[pointer-1],btm=buffer.lengthself._pos){var newData=response.substr(self._pos);if("x-user-defined"===self._charset){for(var buffer=Buffer.alloc(newData.length),i=0;iself._pos&&(self.push(Buffer.from(new Uint8Array(reader.result.slice(self._pos)))),self._pos=reader.result.byteLength)},reader.onload=function(){self.push(null)},reader.readAsArrayBuffer(response);}self._xhr.readyState===rStates.DONE&&"ms-stream"!==self._mode&&self.push(null)}}).call(this)}).call(this,require("_process"),"undefined"==typeof global?"undefined"==typeof self?"undefined"==typeof window?{}:window:self:global,require("buffer").Buffer)},{"./capability":174,_process:132,buffer:38,inherits:97,"readable-stream":157}],177:[function(require,module){module.exports=async function(stream,mimeType){const blob=await getBlob(stream,mimeType),url=URL.createObjectURL(blob);return url};const getBlob=require("stream-to-blob")},{"stream-to-blob":178}],178:[function(require,module){/*! stream-to-blob. MIT License. Feross Aboukhadijeh */module.exports=function(stream,mimeType){if(null!=mimeType&&"string"!=typeof mimeType)throw new Error("Invalid mimetype, expected string.");return new Promise((resolve,reject)=>{const chunks=[];stream.on("data",chunk=>chunks.push(chunk)).once("end",()=>{const blob=null==mimeType?new Blob(chunks):new Blob(chunks,{type:mimeType});resolve(blob)}).once("error",reject)})}},{}],179:[function(require,module){(function(Buffer){(function(){/*! stream-with-known-length-to-buffer. MIT License. Feross Aboukhadijeh */var once=require("once");module.exports=function(stream,length,cb){cb=once(cb);var buf=Buffer.alloc(length),offset=0;stream.on("data",function(chunk){chunk.copy(buf,offset),offset+=chunk.length}).on("end",function(){cb(null,buf)}).on("error",cb)}}).call(this)}).call(this,require("buffer").Buffer)},{buffer:38,once:129}],180:[function(require,module){(function(Buffer){(function(){const addrToIPPort=require("addr-to-ip-port"),ipaddr=require("ipaddr.js");module.exports=addrs=>("string"==typeof addrs&&(addrs=[addrs]),Buffer.concat(addrs.map(addr=>{const s=addrToIPPort(addr);if(2!==s.length)throw new Error("invalid address format, expecting: 10.10.10.5:128");const ip=ipaddr.parse(s[0]),ipBuf=Buffer.from(ip.toByteArray()),port=s[1],portBuf=Buffer.allocUnsafe(2);return portBuf.writeUInt16BE(port,0),Buffer.concat([ipBuf,portBuf])}))),module.exports.multi=module.exports,module.exports.multi6=module.exports}).call(this)}).call(this,require("buffer").Buffer)},{"addr-to-ip-port":9,buffer:38,"ipaddr.js":181}],181:[function(require,module){(function(){var expandIPv6,ipaddr,ipv4Part,ipv4Regexes,ipv6Part,ipv6Regexes,matchCIDR,root,zoneIndex;ipaddr={},root=this,"undefined"!=typeof module&&null!==module&&module.exports?module.exports=ipaddr:root.ipaddr=ipaddr,matchCIDR=function(first,second,partSize,cidrBits){var part,shift;if(first.length!==second.length)throw new Error("ipaddr: cannot match CIDR for objects with different lengths");for(part=0;0shift&&(shift=0),first[part]>>shift!=second[part]>>shift)return!1;cidrBits-=partSize,part+=1}return!0},ipaddr.subnetMatch=function(address,rangeList,defaultName){var k,len,rangeName,rangeSubnets,subnet;for(rangeName in null==defaultName&&(defaultName="unicast"),rangeList)for(rangeSubnets=rangeList[rangeName],rangeSubnets[0]&&!(rangeSubnets[0]instanceof Array)&&(rangeSubnets=[rangeSubnets]),(k=0,len=rangeSubnets.length);k=octet))throw new Error("ipaddr: ipv4 octet should fit in 8 bits");this.octets=octets}return IPv4.prototype.kind=function(){return"ipv4"},IPv4.prototype.toString=function(){return this.octets.join(".")},IPv4.prototype.toNormalizedString=function(){return this.toString()},IPv4.prototype.toByteArray=function(){return this.octets.slice(0)},IPv4.prototype.match=function(other,cidrRange){var ref;if(void 0===cidrRange&&(ref=other,other=ref[0],cidrRange=ref[1]),"ipv4"!==other.kind())throw new Error("ipaddr: cannot match ipv4 address with non-ipv4 one");return matchCIDR(this.octets,other.octets,8,cidrRange)},IPv4.prototype.SpecialRanges={unspecified:[[new IPv4([0,0,0,0]),8]],broadcast:[[new IPv4([255,255,255,255]),32]],multicast:[[new IPv4([224,0,0,0]),4]],linkLocal:[[new IPv4([169,254,0,0]),16]],loopback:[[new IPv4([127,0,0,0]),8]],carrierGradeNat:[[new IPv4([100,64,0,0]),10]],private:[[new IPv4([10,0,0,0]),8],[new IPv4([172,16,0,0]),12],[new IPv4([192,168,0,0]),16]],reserved:[[new IPv4([192,0,0,0]),24],[new IPv4([192,0,2,0]),24],[new IPv4([192,88,99,0]),24],[new IPv4([198,51,100,0]),24],[new IPv4([203,0,113,0]),24],[new IPv4([240,0,0,0]),4]]},IPv4.prototype.range=function(){return ipaddr.subnetMatch(this,this.SpecialRanges)},IPv4.prototype.toIPv4MappedAddress=function(){return ipaddr.IPv6.parse("::ffff:"+this.toString())},IPv4.prototype.prefixLengthFromSubnetMask=function(){var cidr,i,k,octet,stop,zeros,zerotable;for(zerotable={0:8,128:7,192:6,224:5,240:4,248:3,252:2,254:1,255:0},cidr=0,stop=!1,i=k=3;0<=k;i=k+=-1)if(octet=this.octets[i],octet in zerotable){if(zeros=zerotable[octet],stop&&0!==zeros)return null;8!==zeros&&(stop=!0),cidr+=zeros}else return null;return 32-cidr},IPv4}(),ipv4Part="(0?\\d+|0x[a-f0-9]+)",ipv4Regexes={fourOctet:new RegExp("^"+ipv4Part+"\\."+ipv4Part+"\\."+ipv4Part+"\\."+ipv4Part+"$","i"),longValue:new RegExp("^"+ipv4Part+"$","i")},ipaddr.IPv4.parser=function(string){var match,parseIntAuto,part,shift,value;if(parseIntAuto=function(string){return"0"===string[0]&&"x"!==string[1]?parseInt(string,8):parseInt(string)},match=string.match(ipv4Regexes.fourOctet))return function(){var k,len,ref,results;for(ref=match.slice(1,6),results=[],(k=0,len=ref.length);kvalue)throw new Error("ipaddr: address outside defined range");return function(){var k,results;for(results=[],shift=k=0;24>=k;shift=k+=8)results.push(255&value>>shift);return results}().reverse()}return null},ipaddr.IPv6=function(){function IPv6(parts,zoneId){var i,k,l,len,part,ref;if(16===parts.length)for(this.parts=[],i=k=0;14>=k;i=k+=2)this.parts.push(parts[i]<<8|parts[i+1]);else if(8===parts.length)this.parts=parts;else throw new Error("ipaddr: ipv6 part count should be 8 or 16");for(ref=this.parts,l=0,len=ref.length;l=part))throw new Error("ipaddr: ipv6 part should fit in 16 bits");zoneId&&(this.zoneId=zoneId)}return IPv6.prototype.kind=function(){return"ipv6"},IPv6.prototype.toString=function(){return this.toNormalizedString().replace(/((^|:)(0(:|$))+)/,"::")},IPv6.prototype.toRFC5952String=function(){var bestMatchIndex,bestMatchLength,match,regex,string;for(regex=/((^|:)(0(:|$)){2,})/g,string=this.toNormalizedString(),bestMatchIndex=0,bestMatchLength=-1;match=regex.exec(string);)match[0].length>bestMatchLength&&(bestMatchIndex=match.index,bestMatchLength=match[0].length);return 0>bestMatchLength?string:string.substring(0,bestMatchIndex)+"::"+string.substring(bestMatchIndex+bestMatchLength)},IPv6.prototype.toByteArray=function(){var bytes,k,len,part,ref;for(bytes=[],ref=this.parts,(k=0,len=ref.length);k>8),bytes.push(255&part);return bytes},IPv6.prototype.toNormalizedString=function(){var addr,part,suffix;return addr=function(){var k,len,ref,results;for(ref=this.parts,results=[],(k=0,len=ref.length);k>8,255&high,low>>8,255&low])},IPv6.prototype.prefixLengthFromSubnetMask=function(){var cidr,i,k,part,stop,zeros,zerotable;for(zerotable={0:16,32768:15,49152:14,57344:13,61440:12,63488:11,64512:10,65024:9,65280:8,65408:7,65472:6,65504:5,65520:4,65528:3,65532:2,65534:1,65535:0},cidr=0,stop=!1,i=k=7;0<=k;i=k+=-1)if(part=this.parts[i],part in zerotable){if(zeros=zerotable[part],stop&&0!==zeros)return null;16!==zeros&&(stop=!0),cidr+=zeros}else return null;return 128-cidr},IPv6}(),ipv6Part="(?:[0-9a-f]+::?)+",zoneIndex="%[0-9a-z]{1,}",ipv6Regexes={zoneIndex:new RegExp(zoneIndex,"i"),native:new RegExp("^(::)?("+ipv6Part+")?([0-9a-f]+)?(::)?("+zoneIndex+")?$","i"),transitional:new RegExp("^((?:"+ipv6Part+")|(?:::)(?:"+ipv6Part+")?)"+(ipv4Part+"\\."+ipv4Part+"\\."+ipv4Part+"\\."+ipv4Part)+("("+zoneIndex+")?$"),"i")},expandIPv6=function(string,parts){var colonCount,lastColon,part,replacement,replacementCount,zoneId;if(string.indexOf("::")!==string.lastIndexOf("::"))return null;for(zoneId=(string.match(ipv6Regexes.zoneIndex)||[])[0],zoneId&&(zoneId=zoneId.substring(1),string=string.replace(/%.+$/,"")),colonCount=0,lastColon=-1;0<=(lastColon=string.indexOf(":",lastColon+1));)colonCount++;if("::"===string.substr(0,2)&&colonCount--,"::"===string.substr(-2,2)&&colonCount--,colonCount>parts)return null;for(replacementCount=parts-colonCount,replacement=":";replacementCount--;)replacement+="0:";return string=string.replace("::",replacement),":"===string[0]&&(string=string.slice(1)),":"===string[string.length-1]&&(string=string.slice(0,-1)),parts=function(){var k,len,ref,results;for(ref=string.split(":"),results=[],(k=0,len=ref.length);k=octet))return null;return addr.parts.push(octets[0]<<8|octets[1]),addr.parts.push(octets[2]<<8|octets[3]),{parts:addr.parts,zoneId:addr.zoneId}}return null},ipaddr.IPv4.isIPv4=ipaddr.IPv6.isIPv6=function(string){return null!==this.parser(string)},ipaddr.IPv4.isValid=function(string){var e;try{return new this(this.parser(string)),!0}catch(error1){return e=error1,!1}},ipaddr.IPv4.isValidFourPartDecimal=function(string){return!!(ipaddr.IPv4.isValid(string)&&string.match(/^(0|[1-9]\d*)(\.(0|[1-9]\d*)){3}$/))},ipaddr.IPv6.isValid=function(string){var addr,e;if("string"==typeof string&&-1===string.indexOf(":"))return!1;try{return addr=this.parser(string),new this(addr.parts,addr.zoneId),!0}catch(error1){return e=error1,!1}},ipaddr.IPv4.parse=function(string){var parts;if(parts=this.parser(string),null===parts)throw new Error("ipaddr: string is not formatted like ip address");return new this(parts)},ipaddr.IPv6.parse=function(string){var addr;if(addr=this.parser(string),null===addr.parts)throw new Error("ipaddr: string is not formatted like ip address");return new this(addr.parts,addr.zoneId)},ipaddr.IPv4.parseCIDR=function(string){var maskLength,match,parsed;if((match=string.match(/^(.+)\/(\d+)$/))&&(maskLength=parseInt(match[2]),0<=maskLength&&32>=maskLength))return parsed=[this.parse(match[1]),maskLength],Object.defineProperty(parsed,"toString",{value:function(){return this.join("/")}}),parsed;throw new Error("ipaddr: string is not formatted like an IPv4 CIDR range")},ipaddr.IPv4.subnetMaskFromPrefixLength=function(prefix){var filledOctetCount,j,octets;if(prefix=parseInt(prefix),0>prefix||32filledOctetCount&&(octets[filledOctetCount]=_Mathpow(2,prefix%8)-1<<8-prefix%8),new this(octets)},ipaddr.IPv4.broadcastAddressFromCIDR=function(string){var cidr,error,i,ipInterfaceOctets,octets,subnetMaskOctets;try{for(cidr=this.parseCIDR(string),ipInterfaceOctets=cidr[0].toByteArray(),subnetMaskOctets=this.subnetMaskFromPrefixLength(cidr[1]).toByteArray(),octets=[],i=0;4>i;)octets.push(parseInt(ipInterfaceOctets[i],10)|255^parseInt(subnetMaskOctets[i],10)),i++;return new this(octets)}catch(error1){throw error=error1,new Error("ipaddr: the address does not have IPv4 CIDR format")}},ipaddr.IPv4.networkAddressFromCIDR=function(string){var cidr,error,i,ipInterfaceOctets,octets,subnetMaskOctets;try{for(cidr=this.parseCIDR(string),ipInterfaceOctets=cidr[0].toByteArray(),subnetMaskOctets=this.subnetMaskFromPrefixLength(cidr[1]).toByteArray(),octets=[],i=0;4>i;)octets.push(parseInt(ipInterfaceOctets[i],10)&parseInt(subnetMaskOctets[i],10)),i++;return new this(octets)}catch(error1){throw error=error1,new Error("ipaddr: the address does not have IPv4 CIDR format")}},ipaddr.IPv6.parseCIDR=function(string){var maskLength,match,parsed;if((match=string.match(/^(.+)\/(\d+)$/))&&(maskLength=parseInt(match[2]),0<=maskLength&&128>=maskLength))return parsed=[this.parse(match[1]),maskLength],Object.defineProperty(parsed,"toString",{value:function(){return this.join("/")}}),parsed;throw new Error("ipaddr: string is not formatted like an IPv6 CIDR range")},ipaddr.isValid=function(string){return ipaddr.IPv6.isValid(string)||ipaddr.IPv4.isValid(string)},ipaddr.parse=function(string){if(ipaddr.IPv6.isValid(string))return ipaddr.IPv6.parse(string);if(ipaddr.IPv4.isValid(string))return ipaddr.IPv4.parse(string);throw new Error("ipaddr: the address has neither IPv6 nor IPv4 format")},ipaddr.parseCIDR=function(string){var e;try{return ipaddr.IPv6.parseCIDR(string)}catch(error1){e=error1;try{return ipaddr.IPv4.parseCIDR(string)}catch(error1){throw e=error1,new Error("ipaddr: the address has neither IPv6 nor IPv4 CIDR format")}}},ipaddr.fromByteArray=function(bytes){var length;if(length=bytes.length,4===length)return new ipaddr.IPv4(bytes);if(16===length)return new ipaddr.IPv6(bytes);throw new Error("ipaddr: the binary input is neither an IPv6 nor IPv4 address")},ipaddr.process=function(string){var addr;return addr=this.parse(string),"ipv6"===addr.kind()&&addr.isIPv4MappedAddress()?addr.toIPv4Address():addr}}).call(this)},{}],182:[function(require,module,exports){'use strict';function _normalizeEncoding(enc){if(!enc)return"utf8";for(var retried;;)switch(enc){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return enc;default:if(retried)return;enc=(""+enc).toLowerCase(),retried=!0;}}function normalizeEncoding(enc){var nenc=_normalizeEncoding(enc);if("string"!=typeof nenc&&(Buffer.isEncoding===isEncoding||!isEncoding(enc)))throw new Error("Unknown encoding: "+enc);return nenc||enc}function StringDecoder(encoding){this.encoding=normalizeEncoding(encoding);var nb;switch(this.encoding){case"utf16le":this.text=utf16Text,this.end=utf16End,nb=4;break;case"utf8":this.fillLast=utf8FillLast,nb=4;break;case"base64":this.text=base64Text,this.end=base64End,nb=3;break;default:return this.write=simpleWrite,void(this.end=simpleEnd);}this.lastNeed=0,this.lastTotal=0,this.lastChar=Buffer.allocUnsafe(nb)}function utf8CheckByte(byte){if(127>=byte)return 0;return 6==byte>>5?2:14==byte>>4?3:30==byte>>3?4:2==byte>>6?-1:-2}function utf8CheckIncomplete(self,buf,i){var j=buf.length-1;if(j=c)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=buf[buf.length-2],this.lastChar[1]=buf[buf.length-1],r.slice(0,-1)}return r}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=buf[buf.length-1],buf.toString("utf16le",i,buf.length-1)}function utf16End(buf){var r=buf&&buf.length?this.write(buf):"";if(this.lastNeed){var end=this.lastTotal-this.lastNeed;return r+this.lastChar.toString("utf16le",0,end)}return r}function base64Text(buf,i){var n=(buf.length-i)%3;return 0==n?buf.toString("base64",i):(this.lastNeed=3-n,this.lastTotal=3,1==n?this.lastChar[0]=buf[buf.length-1]:(this.lastChar[0]=buf[buf.length-2],this.lastChar[1]=buf[buf.length-1]),buf.toString("base64",i,buf.length-n))}function base64End(buf){var r=buf&&buf.length?this.write(buf):"";return this.lastNeed?r+this.lastChar.toString("base64",0,3-this.lastNeed):r}function simpleWrite(buf){return buf.toString(this.encoding)}function simpleEnd(buf){return buf&&buf.length?this.write(buf):""}var Buffer=require("safe-buffer").Buffer,isEncoding=Buffer.isEncoding||function(encoding){switch(encoding=""+encoding,encoding&&encoding.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1;}};exports.StringDecoder=StringDecoder,StringDecoder.prototype.write=function(buf){if(0===buf.length)return"";var r,i;if(this.lastNeed){if(r=this.fillLast(buf),void 0===r)return"";i=this.lastNeed,this.lastNeed=0}else i=0;return i>shiftIndex,shiftIndex=(shiftIndex+5)%8,digit=digit<>8-shiftIndex,i++):(digit=31¤t>>8-(shiftIndex+5),shiftIndex=(shiftIndex+5)%8,0===shiftIndex&&i++),encoded[j]="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567".charCodeAt(digit),j++}for(i=j;i=shiftIndex?(shiftIndex=(shiftIndex+5)%8,0===shiftIndex?(plainChar|=plainDigit,decoded[plainPos]=plainChar,plainPos++,plainChar=0):plainChar|=255&plainDigit<<8-shiftIndex):(shiftIndex=(shiftIndex+5)%8,plainChar|=255&plainDigit>>>shiftIndex,decoded[plainPos]=plainChar,plainPos++,plainChar=255&plainDigit<<8-shiftIndex);else throw new Error("Invalid input - it is not base32 encoded string")}return decoded.slice(0,plainPos)}}).call(this)}).call(this,require("buffer").Buffer)},{buffer:38}],185:[function(require,module,exports){(function(setImmediate,clearImmediate){(function(){function Timeout(id,clearFn){this._id=id,this._clearFn=clearFn}var nextTick=require("process/browser.js").nextTick,apply=Function.prototype.apply,slice=Array.prototype.slice,immediateIds={},nextImmediateId=0;exports.setTimeout=function(){return new Timeout(apply.call(setTimeout,window,arguments),clearTimeout)},exports.setInterval=function(){return new Timeout(apply.call(setInterval,window,arguments),clearInterval)},exports.clearTimeout=exports.clearInterval=function(timeout){timeout.close()},Timeout.prototype.unref=Timeout.prototype.ref=function(){},Timeout.prototype.close=function(){this._clearFn.call(window,this._id)},exports.enroll=function(item,msecs){clearTimeout(item._idleTimeoutId),item._idleTimeout=msecs},exports.unenroll=function(item){clearTimeout(item._idleTimeoutId),item._idleTimeout=-1},exports._unrefActive=exports.active=function(item){clearTimeout(item._idleTimeoutId);var msecs=item._idleTimeout;0<=msecs&&(item._idleTimeoutId=setTimeout(function(){item._onTimeout&&item._onTimeout()},msecs))},exports.setImmediate="function"==typeof setImmediate?setImmediate:function(fn){var id=nextImmediateId++,args=!(2>arguments.length)&&slice.call(arguments,1);return immediateIds[id]=!0,nextTick(function(){immediateIds[id]&&(args?fn.apply(null,args):fn.call(null),exports.clearImmediate(id))}),id},exports.clearImmediate="function"==typeof clearImmediate?clearImmediate:function(id){delete immediateIds[id]}}).call(this)}).call(this,require("timers").setImmediate,require("timers").clearImmediate)},{"process/browser.js":132,timers:185}],186:[function(require,module){var Buffer=require("buffer").Buffer;module.exports=function(buf){if(buf instanceof Uint8Array){if(0===buf.byteOffset&&buf.byteLength===buf.buffer.byteLength)return buf.buffer;if("function"==typeof buf.buffer.slice)return buf.buffer.slice(buf.byteOffset,buf.byteOffset+buf.byteLength)}if(Buffer.isBuffer(buf)){for(var arrayCopy=new Uint8Array(buf.length),len=buf.length,i=0;i */const debug=require("debug")("torrent-discovery"),DHT=require("bittorrent-dht/client"),EventEmitter=require("events").EventEmitter,parallel=require("run-parallel"),Tracker=require("bittorrent-tracker/client"),LSD=require("bittorrent-lsd");module.exports=class Discovery extends EventEmitter{constructor(opts){if(super(),!opts.peerId)throw new Error("Option `peerId` is required");if(!opts.infoHash)throw new Error("Option `infoHash` is required");if(!process.browser&&!opts.port)throw new Error("Option `port` is required");this.peerId="string"==typeof opts.peerId?opts.peerId:opts.peerId.toString("hex"),this.infoHash="string"==typeof opts.infoHash?opts.infoHash.toLowerCase():opts.infoHash.toString("hex"),this._port=opts.port,this._userAgent=opts.userAgent,this.destroyed=!1,this._announce=opts.announce||[],this._intervalMs=opts.intervalMs||900000,this._trackerOpts=null,this._dhtAnnouncing=!1,this._dhtTimeout=!1,this._internalDHT=!1,this._onWarning=err=>{this.emit("warning",err)},this._onError=err=>{this.emit("error",err)},this._onDHTPeer=(peer,infoHash)=>{infoHash.toString("hex")!==this.infoHash||this.emit("peer",`${peer.host}:${peer.port}`,"dht")},this._onTrackerPeer=peer=>{this.emit("peer",peer,"tracker")},this._onTrackerAnnounce=()=>{this.emit("trackerAnnounce")},this._onLSDPeer=peer=>{this.emit("peer",peer,"lsd")};const createDHT=(port,opts)=>{const dht=new DHT(opts);return dht.on("warning",this._onWarning),dht.on("error",this._onError),dht.listen(port),this._internalDHT=!0,dht};!1===opts.tracker?this.tracker=null:opts.tracker&&"object"==typeof opts.tracker?(this._trackerOpts=Object.assign({},opts.tracker),this.tracker=this._createTracker()):this.tracker=this._createTracker(),this.dht=!1===opts.dht||"function"!=typeof DHT?null:opts.dht&&"function"==typeof opts.dht.addNode?opts.dht:opts.dht&&"object"==typeof opts.dht?createDHT(opts.dhtPort,opts.dht):createDHT(opts.dhtPort),this.dht&&(this.dht.on("peer",this._onDHTPeer),this._dhtAnnounce()),this.lsd=!1===opts.lsd||"function"!=typeof LSD?null:this._createLSD()}updatePort(port){port===this._port||(this._port=port,this.dht&&this._dhtAnnounce(),this.tracker&&(this.tracker.stop(),this.tracker.destroy(()=>{this.tracker=this._createTracker()})))}complete(opts){this.tracker&&this.tracker.complete(opts)}destroy(cb){if(!this.destroyed){this.destroyed=!0,clearTimeout(this._dhtTimeout);const tasks=[];this.tracker&&(this.tracker.stop(),this.tracker.removeListener("warning",this._onWarning),this.tracker.removeListener("error",this._onError),this.tracker.removeListener("peer",this._onTrackerPeer),this.tracker.removeListener("update",this._onTrackerAnnounce),tasks.push(cb=>{this.tracker.destroy(cb)})),this.dht&&this.dht.removeListener("peer",this._onDHTPeer),this._internalDHT&&(this.dht.removeListener("warning",this._onWarning),this.dht.removeListener("error",this._onError),tasks.push(cb=>{this.dht.destroy(cb)})),this.lsd&&(this.lsd.removeListener("warning",this._onWarning),this.lsd.removeListener("error",this._onError),this.lsd.removeListener("peer",this._onLSDPeer),tasks.push(cb=>{this.lsd.destroy(cb)})),parallel(tasks,cb),this.dht=null,this.tracker=null,this.lsd=null,this._announce=null}}_createTracker(){const opts=Object.assign({},this._trackerOpts,{infoHash:this.infoHash,announce:this._announce,peerId:this.peerId,port:this._port,userAgent:this._userAgent}),tracker=new Tracker(opts);return tracker.on("warning",this._onWarning),tracker.on("error",this._onError),tracker.on("peer",this._onTrackerPeer),tracker.on("update",this._onTrackerAnnounce),tracker.setInterval(this._intervalMs),tracker.start(),tracker}_dhtAnnounce(){this._dhtAnnouncing||(debug("dht announce"),this._dhtAnnouncing=!0,clearTimeout(this._dhtTimeout),this.dht.announce(this.infoHash,this._port,err=>{this._dhtAnnouncing=!1,debug("dht announce complete"),err&&this.emit("warning",err),this.emit("dhtAnnounce"),this.destroyed||(this._dhtTimeout=setTimeout(()=>{this._dhtAnnounce()},this._intervalMs+_Mathfloor(Math.random()*this._intervalMs/5)),this._dhtTimeout.unref&&this._dhtTimeout.unref())}))}_createLSD(){const opts=Object.assign({},{infoHash:this.infoHash,peerId:this.peerId,port:this._port}),lsd=new LSD(opts);return lsd.on("warning",this._onWarning),lsd.on("error",this._onError),lsd.on("peer",this._onLSDPeer),lsd.start(),lsd}}}).call(this)}).call(this,require("_process"))},{_process:132,"bittorrent-dht/client":23,"bittorrent-lsd":24,"bittorrent-tracker/client":26,debug:69,events:39,"run-parallel":162}],188:[function(require,module){(function(Buffer){(function(){const BLOCK_LENGTH=16384;class Piece{constructor(length){this.length=length,this.missing=length,this.sources=null,this._chunks=_Mathceil(length/BLOCK_LENGTH),this._remainder=length%BLOCK_LENGTH||BLOCK_LENGTH,this._buffered=0,this._buffer=null,this._cancellations=null,this._reservations=0,this._flushed=!1}chunkLength(i){return i===this._chunks-1?this._remainder:BLOCK_LENGTH}chunkLengthRemaining(i){return this.length-i*BLOCK_LENGTH}chunkOffset(i){return i*BLOCK_LENGTH}reserve(){return this.init()?this._cancellations.length?this._cancellations.pop():this._reservations=arr.length||0>i)){var last=arr.pop();if(i","\"","`"," ","\r","\n","\t"]),autoEscape=["'"].concat(unwise),nonHostChars=["%","/","?",";","#"].concat(autoEscape),hostEndingChars=["/","?","#"],hostnamePartPattern=/^[+a-z0-9A-Z_-]{0,63}$/,unsafeProtocol={javascript:!0,"javascript:":!0},hostlessProtocol={javascript:!0,"javascript:":!0},slashedProtocol={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},querystring=require("querystring");Url.prototype.parse=function(url,parseQueryString,slashesDenoteHost){if(!util.isString(url))throw new TypeError("Parameter 'url' must be a string, not "+typeof url);var queryIndex=url.indexOf("?"),splitter=-1!==queryIndex&&queryIndexrelPath.length&&relPath.unshift(""),result.pathname=relPath.join("/")}else result.pathname=relative.pathname;if(result.search=relative.search,result.query=relative.query,result.host=relative.host||"",result.auth=relative.auth,result.hostname=relative.hostname||relative.host,result.port=relative.port,result.pathname||result.search){var p=result.pathname||"",s=result.search||"";result.path=p+s}return result.slashes=result.slashes||relative.slashes,result.href=result.format(),result}var isSourceAbs=result.pathname&&"/"===result.pathname.charAt(0),isRelAbs=relative.host||relative.pathname&&"/"===relative.pathname.charAt(0),mustEndAbs=isRelAbs||isSourceAbs||result.host&&relative.pathname,removeAllDots=mustEndAbs,srcPath=result.pathname&&result.pathname.split("/")||[],relPath=relative.pathname&&relative.pathname.split("/")||[],psychotic=result.protocol&&!slashedProtocol[result.protocol];if(psychotic&&(result.hostname="",result.port=null,result.host&&(""===srcPath[0]?srcPath[0]=result.host:srcPath.unshift(result.host)),result.host="",relative.protocol&&(relative.hostname=null,relative.port=null,relative.host&&(""===relPath[0]?relPath[0]=relative.host:relPath.unshift(relative.host)),relative.host=null),mustEndAbs=mustEndAbs&&(""===relPath[0]||""===srcPath[0])),isRelAbs)result.host=relative.host||""===relative.host?relative.host:result.host,result.hostname=relative.hostname||""===relative.hostname?relative.hostname:result.hostname,result.search=relative.search,result.query=relative.query,srcPath=relPath;else if(relPath.length)srcPath||(srcPath=[]),srcPath.pop(),srcPath=srcPath.concat(relPath),result.search=relative.search,result.query=relative.query;else if(!util.isNullOrUndefined(relative.search)){if(psychotic){result.hostname=result.host=srcPath.shift();var authInHost=!!(result.host&&0 */const{EventEmitter}=require("events"),bencode=require("bencode"),BitField=require("bitfield").default,debug=require("debug")("ut_metadata"),sha1=require("simple-sha1"),BITFIELD_GROW=1E3,PIECE_LENGTH=16384;module.exports=metadata=>{class utMetadata extends EventEmitter{constructor(wire){super(),this._wire=wire,this._fetching=!1,this._metadataComplete=!1,this._metadataSize=null,this._remainingRejects=null,this._bitfield=new BitField(0,{grow:BITFIELD_GROW}),Buffer.isBuffer(metadata)&&this.setMetadata(metadata)}onHandshake(infoHash){this._infoHash=infoHash}onExtendedHandshake(handshake){return handshake.m&&handshake.m.ut_metadata?handshake.metadata_size?"number"!=typeof handshake.metadata_size||1E7=handshake.metadata_size?this.emit("warning",new Error("Peer gave invalid metadata size")):void(this._metadataSize=handshake.metadata_size,this._numPieces=_Mathceil(this._metadataSize/PIECE_LENGTH),this._remainingRejects=2*this._numPieces,this._requestPieces()):this.emit("warning",new Error("Peer does not have metadata")):this.emit("warning",new Error("Peer does not support ut_metadata"))}onMessage(buf){let dict,trailer;try{const str=buf.toString(),trailerIndex=str.indexOf("ee")+2;dict=bencode.decode(str.substring(0,trailerIndex)),trailer=buf.slice(trailerIndex)}catch(err){return}switch(dict.msg_type){case 0:this._onRequest(dict.piece);break;case 1:this._onData(dict.piece,trailer,dict.total_size);break;case 2:this._onReject(dict.piece);}}fetch(){this._metadataComplete||(this._fetching=!0,this._metadataSize&&this._requestPieces())}cancel(){this._fetching=!1}setMetadata(metadata){if(this._metadataComplete)return!0;debug("set metadata");try{const info=bencode.decode(metadata).info;info&&(metadata=bencode.encode(info))}catch(err){}return!(this._infoHash&&this._infoHash!==sha1.sync(metadata))&&(this.cancel(),this.metadata=metadata,this._metadataComplete=!0,this._metadataSize=this.metadata.length,this._wire.extendedHandshake.metadata_size=this._metadataSize,this.emit("metadata",bencode.encode({info:bencode.decode(this.metadata)})),!0)}_send(dict,trailer){let buf=bencode.encode(dict);Buffer.isBuffer(trailer)&&(buf=Buffer.concat([buf,trailer])),this._wire.extended("ut_metadata",buf)}_request(piece){this._send({msg_type:0,piece})}_data(piece,buf,totalSize){const msg={msg_type:1,piece};"number"==typeof totalSize&&(msg.total_size=totalSize),this._send(msg,buf)}_reject(piece){this._send({msg_type:2,piece})}_onRequest(piece){if(!this._metadataComplete)return void this._reject(piece);const start=piece*PIECE_LENGTH;let end=start+PIECE_LENGTH;end>this._metadataSize&&(end=this._metadataSize);const buf=this.metadata.slice(start,end);this._data(piece,buf,this._metadataSize)}_onData(piece,buf){buf.length>PIECE_LENGTH||!this._fetching||(buf.copy(this.metadata,piece*PIECE_LENGTH),this._bitfield.set(piece),this._checkDone())}_onReject(piece){0 */var EventEmitter=require("events").EventEmitter,compact2string=require("compact2string"),string2compact=require("string2compact"),bencode=require("bencode"),PEX_MAX_PEERS=50;module.exports=()=>{class utPex extends EventEmitter{constructor(wire){super(),this._wire=wire,this._intervalId=null,this.reset()}start(){clearInterval(this._intervalId),this._intervalId=setInterval(()=>this._sendMessage(),65e3),this._intervalId.unref&&this._intervalId.unref()}stop(){clearInterval(this._intervalId),this._intervalId=null}reset(){this._remoteAddedPeers={},this._remoteDroppedPeers={},this._localAddedPeers={},this._localDroppedPeers={},this.stop()}addPeer(peer){0>peer.indexOf(":")||peer in this._remoteAddedPeers||(peer in this._localDroppedPeers&&delete this._localDroppedPeers[peer],this._localAddedPeers[peer]=!0)}dropPeer(peer){0>peer.indexOf(":")||peer in this._remoteDroppedPeers||(peer in this._localAddedPeers&&delete this._localAddedPeers[peer],this._localDroppedPeers[peer]=!0)}onExtendedHandshake(handshake){if(!handshake.m||!handshake.m.ut_pex)return this.emit("warning",new Error("Peer does not support ut_pex"))}onMessage(buf){var message;try{message=bencode.decode(buf)}catch(err){return}if(message.added)try{compact2string.multi(message.added).forEach(peer=>{delete this._remoteDroppedPeers[peer],peer in this._remoteAddedPeers||(this._remoteAddedPeers[peer]=!0,this.emit("peer",peer))})}catch(err){return}if(message.dropped)try{compact2string.multi(message.dropped).forEach(peer=>{delete this._remoteAddedPeers[peer],peer in this._remoteDroppedPeers||(this._remoteDroppedPeers[peer]=!0,this.emit("dropped",peer))})}catch(err){}}_sendMessage(){var localAdded=Object.keys(this._localAddedPeers).slice(0,PEX_MAX_PEERS),localDropped=Object.keys(this._localDroppedPeers).slice(0,PEX_MAX_PEERS),added=Buffer.concat(localAdded.map(string2compact)),dropped=Buffer.concat(localDropped.map(string2compact)),addedFlags=Buffer.concat(localAdded.map(()=>Buffer.from([0])));localAdded.forEach(peer=>delete this._localAddedPeers[peer]),localDropped.forEach(peer=>delete this._localDroppedPeers[peer]),this._wire.extended("ut_pex",{added:added,"added.f":addedFlags,dropped:dropped,added6:Buffer.alloc(0),"added6.f":Buffer.alloc(0),dropped6:Buffer.alloc(0)})}}return utPex.prototype.name="ut_pex",utPex}}).call(this)}).call(this,require("buffer").Buffer)},{bencode:19,buffer:38,compact2string:67,events:39,string2compact:180}],196:[function(require,module){(function(global){(function(){function config(name){try{if(!global.localStorage)return!1}catch(_){return!1}var val=global.localStorage[name];return null!=val&&"true"===(val+"").toLowerCase()}module.exports=function(fn,msg){function deprecated(){if(!warned){if(config("throwDeprecation"))throw new Error(msg);else config("traceDeprecation")?console.trace(msg):console.warn(msg);warned=!0}return fn.apply(this,arguments)}if(config("noDeprecation"))return fn;var warned=!1;return deprecated}}).call(this)}).call(this,"undefined"==typeof global?"undefined"==typeof self?"undefined"==typeof window?{}:window:self:global)},{}],197:[function(require,module){(function(Buffer){(function(){function empty(){return{version:0,flags:0,entries:[]}}const bs=require("binary-search"),EventEmitter=require("events"),mp4=require("mp4-stream"),Box=require("mp4-box-encoding"),RangeSliceStream=require("range-slice-stream");class RunLengthIndex{constructor(entries,countName){this._entries=entries,this._countName=countName||"count",this._index=0,this._offset=0,this.value=this._entries[0]}inc(){this._offset++,this._offset>=this._entries[this._index][this._countName]&&(this._index++,this._offset=0),this.value=this._entries[this._index]}}module.exports=class MP4Remuxer extends EventEmitter{constructor(file){super(),this._tracks=[],this._file=file,this._decoder=null,this._findMoov(0)}_findMoov(offset){this._decoder&&this._decoder.destroy();let toSkip=0;this._decoder=mp4.decode();const fileStream=this._file.createReadStream({start:offset});fileStream.pipe(this._decoder);const boxHandler=headers=>{"moov"===headers.type?(this._decoder.removeListener("box",boxHandler),this._decoder.decode(moov=>{fileStream.destroy();try{this._processMoov(moov)}catch(err){err.message=`Cannot parse mp4 file: ${err.message}`,this.emit("error",err)}})):headers.length<4096?(toSkip+=headers.length,this._decoder.ignore()):(this._decoder.removeListener("box",boxHandler),toSkip+=headers.length,fileStream.destroy(),this._decoder.destroy(),this._findMoov(offset+toSkip))};this._decoder.on("box",boxHandler)}_processMoov(moov){const traks=moov.traks;this._tracks=[],this._hasVideo=!1,this._hasAudio=!1;for(let i=0;i=stbl.stsz.entries.length)break;if(sampleInChunk++,offsetInChunk+=size,sampleInChunk>=currChunkEntry.samplesPerChunk){sampleInChunk=0,offsetInChunk=0,chunk++;const nextChunkEntry=stbl.stsc.entries[sampleToChunkIndex+1];nextChunkEntry&&chunk+1>=nextChunkEntry.firstChunk&&sampleToChunkIndex++}dts+=duration,decodingTimeEntry.inc(),presentationOffsetEntry&&presentationOffsetEntry.inc(),sync&&syncSampleIndex++}trak.mdia.mdhd.duration=0,trak.tkhd.duration=0;const defaultSampleDescriptionIndex=currChunkEntry.sampleDescriptionId,trackMoov={type:"moov",mvhd:moov.mvhd,traks:[{tkhd:trak.tkhd,mdia:{mdhd:trak.mdia.mdhd,hdlr:trak.mdia.hdlr,elng:trak.mdia.elng,minf:{vmhd:trak.mdia.minf.vmhd,smhd:trak.mdia.minf.smhd,dinf:trak.mdia.minf.dinf,stbl:{stsd:stbl.stsd,stts:empty(),ctts:empty(),stsc:empty(),stsz:empty(),stco:empty(),stss:empty()}}}}],mvex:{mehd:{fragmentDuration:moov.mvhd.duration},trexs:[{trackId:trak.tkhd.trackId,defaultSampleDescriptionIndex,defaultSampleDuration:0,defaultSampleSize:0,defaultSampleFlags:0}]}};this._tracks.push({fragmentSequence:1,trackId:trak.tkhd.trackId,timeScale:trak.mdia.mdhd.timeScale,samples,currSample:null,currTime:null,moov:trackMoov,mime})}if(0===this._tracks.length)return void this.emit("error",new Error("no playable tracks"));moov.mvhd.duration=0,this._ftyp={type:"ftyp",brand:"iso5",brandVersion:0,compatibleBrands:["iso5"]};const ftypBuf=Box.encode(this._ftyp),data=this._tracks.map(track=>{const moovBuf=Box.encode(track.moov);return{mime:track.mime,init:Buffer.concat([ftypBuf,moovBuf])}});this.emit("ready",data)}seek(time){if(!this._tracks)throw new Error("Not ready yet; wait for 'ready' event");this._fileStream&&(this._fileStream.destroy(),this._fileStream=null);let startOffset=-1;if(this._tracks.map((track,i)=>{track.outStream&&track.outStream.destroy(),track.inStream&&(track.inStream.destroy(),track.inStream=null);const outStream=track.outStream=mp4.encode(),fragment=this._generateFragment(i,time);if(!fragment)return outStream.finalize();(-1===startOffset||fragment.ranges[0].start{outStream.destroyed||outStream.box(frag.moof,err=>{if(err)return this.emit("error",err);if(!outStream.destroyed){const slicedStream=track.inStream.slice(frag.ranges);slicedStream.pipe(outStream.mediaData(frag.length,err=>{if(err)return this.emit("error",err);if(!outStream.destroyed){const nextFrag=this._generateFragment(i);return nextFrag?void writeFragment(nextFrag):outStream.finalize()}}))}})};writeFragment(fragment)}),0<=startOffset){const fileStream=this._fileStream=this._file.createReadStream({start:startOffset});this._tracks.forEach(track=>{track.inStream=new RangeSliceStream(startOffset,{highWaterMark:1e7}),fileStream.pipe(track.inStream)})}return this._tracks.map(track=>track.outStream)}_findSampleBefore(trackInd,time){const track=this._tracks[trackInd],scaledTime=_Mathfloor(track.timeScale*time);let sample=bs(track.samples,scaledTime,(sample,t)=>{const pts=sample.dts+sample.presentationOffset;return pts-t});for(-1===sample?sample=0:0>sample&&(sample=-sample-2);!track.samples[sample].sync;)sample--;return sample}_generateFragment(track,time){const currTrack=this._tracks[track];let firstSample;if(firstSample=void 0===time?currTrack.currSample:this._findSampleBefore(track,time),firstSample>=currTrack.samples.length)return null;const startDts=currTrack.samples[firstSample].dts;let totalLen=0;const ranges=[];for(var currSample=firstSample;currSample=currTrack.timeScale*1)break;totalLen+=sample.size;const currRange=ranges.length-1;0>currRange||ranges[currRange].end!==sample.offset?ranges.push({start:sample.offset,end:sample.offset+sample.size}):ranges[currRange].end+=sample.size}return currTrack.currSample=currSample,{moof:this._generateMoof(track,firstSample,currSample),ranges,length:totalLen}}_generateMoof(track,firstSample,lastSample){const currTrack=this._tracks[track],entries=[];let trunVersion=0;for(let j=firstSample;jcurrSample.presentationOffset&&(trunVersion=1),entries.push({sampleDuration:currSample.duration,sampleSize:currSample.size,sampleFlags:currSample.sync?33554432:16842752,sampleCompositionTimeOffset:currSample.presentationOffset})}const moof={type:"moof",mfhd:{sequenceNumber:currTrack.fragmentSequence++},trafs:[{tfhd:{flags:131072,trackId:currTrack.trackId},tfdt:{baseMediaDecodeTime:currTrack.samples[firstSample].dts},trun:{flags:3841,dataOffset:8,entries,version:trunVersion}}]};return moof.trafs[0].trun.dataOffset+=Box.encodingLength(moof),moof}}}).call(this)}).call(this,require("buffer").Buffer)},{"binary-search":21,buffer:38,events:39,"mp4-box-encoding":121,"mp4-stream":124,"range-slice-stream":142}],198:[function(require,module){function VideoStream(file,mediaElem,opts={}){return this instanceof VideoStream?void(this.detailedError=null,this._elem=mediaElem,this._elemWrapper=new MediaElementWrapper(mediaElem),this._waitingFired=!1,this._trackMeta=null,this._file=file,this._tracks=null,"none"!==this._elem.preload&&this._createMuxer(),this._onError=()=>{this.detailedError=this._elemWrapper.detailedError,this.destroy()},this._onWaiting=()=>{this._waitingFired=!0,this._muxer?this._tracks&&this._pump():this._createMuxer()},mediaElem.autoplay&&(mediaElem.preload="auto"),mediaElem.addEventListener("waiting",this._onWaiting),mediaElem.addEventListener("error",this._onError)):(console.warn("Don't invoke VideoStream without the 'new' keyword."),new VideoStream(file,mediaElem,opts))}const MediaElementWrapper=require("mediasource"),pump=require("pump"),MP4Remuxer=require("./mp4-remuxer");VideoStream.prototype={_createMuxer(){this._muxer=new MP4Remuxer(this._file),this._muxer.on("ready",data=>{this._tracks=data.map(trackData=>{const mediaSource=this._elemWrapper.createWriteStream(trackData.mime);mediaSource.on("error",err=>{this._elemWrapper.error(err)});const track={muxed:null,mediaSource,initFlushed:!1,onInitFlushed:null};return mediaSource.write(trackData.init,err=>{track.initFlushed=!0,track.onInitFlushed&&track.onInitFlushed(err)}),track}),(this._waitingFired||"auto"===this._elem.preload)&&this._pump()}),this._muxer.on("error",err=>{this._elemWrapper.error(err)})},_pump(){const muxed=this._muxer.seek(this._elem.currentTime,!this._tracks);this._tracks.forEach((track,i)=>{const pumpTrack=()=>{track.muxed&&(track.muxed.destroy(),track.mediaSource=this._elemWrapper.createWriteStream(track.mediaSource),track.mediaSource.on("error",err=>{this._elemWrapper.error(err)})),track.muxed=muxed[i],pump(track.muxed,track.mediaSource)};track.initFlushed?pumpTrack():track.onInitFlushed=err=>err?void this._elemWrapper.error(err):void pumpTrack()})},destroy(){this.destroyed||(this.destroyed=!0,this._elem.removeEventListener("waiting",this._onWaiting),this._elem.removeEventListener("error",this._onError),this._tracks&&this._tracks.forEach(track=>{track.muxed&&track.muxed.destroy()}),this._elem.src="")}},module.exports=VideoStream},{"./mp4-remuxer":197,mediasource:113,pump:133}],199:[function(require,module){(function(global){(function(){'use strict';var forEach=require("foreach"),availableTypedArrays=require("available-typed-arrays"),callBound=require("es-abstract/helpers/callBound"),$toString=callBound("Object.prototype.toString"),hasSymbols=require("has-symbols")(),hasToStringTag=hasSymbols&&"symbol"==typeof Symbol.toStringTag,typedArrays=availableTypedArrays(),$slice=callBound("String.prototype.slice"),toStrTags={},gOPD=require("es-abstract/helpers/getOwnPropertyDescriptor"),getPrototypeOf=Object.getPrototypeOf;hasToStringTag&&gOPD&&getPrototypeOf&&forEach(typedArrays,function(typedArray){if("function"==typeof global[typedArray]){var arr=new global[typedArray];if(!(Symbol.toStringTag in arr))throw new EvalError("this engine has support for Symbol.toStringTag, but "+typedArray+" does not have the property! Please report this.");var proto=getPrototypeOf(arr),descriptor=gOPD(proto,Symbol.toStringTag);if(!descriptor){var superProto=getPrototypeOf(proto);descriptor=gOPD(superProto,Symbol.toStringTag)}toStrTags[typedArray]=descriptor.get}});var tryTypedArrays=function(value){var foundName=!1;return forEach(toStrTags,function(getter,typedArray){if(!foundName)try{var name=getter.call(value);name===typedArray&&(foundName=name)}catch(e){}}),foundName},isTypedArray=require("is-typed-array");module.exports=function(value){return!!isTypedArray(value)&&(hasToStringTag?tryTypedArrays(value):$slice($toString(value),8,-1))}}).call(this)}).call(this,"undefined"==typeof global?"undefined"==typeof self?"undefined"==typeof window?{}:window:self:global)},{"available-typed-arrays":15,"es-abstract/helpers/callBound":75,"es-abstract/helpers/getOwnPropertyDescriptor":76,foreach:79,"has-symbols":84,"is-typed-array":104}],200:[function(require,module){function wrappy(fn,cb){function wrapper(){for(var args=Array(arguments.length),i=0;i */const{EventEmitter}=require("events"),concat=require("simple-concat"),createTorrent=require("create-torrent"),debug=require("debug")("webtorrent"),DHT=require("bittorrent-dht/client"),loadIPSet=require("load-ip-set"),parallel=require("run-parallel"),parseTorrent=require("parse-torrent"),path=require("path"),Peer=require("simple-peer"),randombytes=require("randombytes"),speedometer=require("speedometer"),ConnPool=require("./lib/conn-pool"),Torrent=require("./lib/torrent"),VERSION=require("./package.json").version,VERSION_STR=VERSION.replace(/\d*./g,v=>`0${v%100}`.slice(-2)).slice(0,4);class WebTorrent extends EventEmitter{constructor(opts={}){super(),this.peerId="string"==typeof opts.peerId?opts.peerId:Buffer.isBuffer(opts.peerId)?opts.peerId.toString("hex"):Buffer.from(`-WW${VERSION_STR}-`+randombytes(9).toString("base64")).toString("hex"),this.peerIdBuffer=Buffer.from(this.peerId,"hex"),this.nodeId="string"==typeof opts.nodeId?opts.nodeId:Buffer.isBuffer(opts.nodeId)?opts.nodeId.toString("hex"):randombytes(20).toString("hex"),this.nodeIdBuffer=Buffer.from(this.nodeId,"hex"),this._debugId=this.peerId.toString("hex").substring(0,7),this.destroyed=!1,this.listening=!1,this.torrentPort=opts.torrentPort||0,this.dhtPort=opts.dhtPort||0,this.tracker=opts.tracker===void 0?{}:opts.tracker,this.lsd=!1!==opts.lsd,this.torrents=[],this.maxConns=+opts.maxConns||55,this.utp=!0===opts.utp,this._debug("new webtorrent (peerId %s, nodeId %s, port %s)",this.peerId,this.nodeId,this.torrentPort),this.tracker&&("object"!=typeof this.tracker&&(this.tracker={}),opts.rtcConfig&&(console.warn("WebTorrent: opts.rtcConfig is deprecated. Use opts.tracker.rtcConfig instead"),this.tracker.rtcConfig=opts.rtcConfig),opts.wrtc&&(console.warn("WebTorrent: opts.wrtc is deprecated. Use opts.tracker.wrtc instead"),this.tracker.wrtc=opts.wrtc),global.WRTC&&!this.tracker.wrtc&&(this.tracker.wrtc=global.WRTC)),"function"==typeof ConnPool?this._connPool=new ConnPool(this):process.nextTick(()=>{this._onListening()}),this._downloadSpeed=speedometer(),this._uploadSpeed=speedometer(),!1!==opts.dht&&"function"==typeof DHT?(this.dht=new DHT(Object.assign({},{nodeId:this.nodeId},opts.dht)),this.dht.once("error",err=>{this._destroy(err)}),this.dht.once("listening",()=>{const address=this.dht.address();address&&(this.dhtPort=address.port)}),this.dht.setMaxListeners(0),this.dht.listen(this.dhtPort)):this.dht=!1,this.enableWebSeeds=!1!==opts.webSeeds;const ready=()=>{this.destroyed||(this.ready=!0,this.emit("ready"))};"function"==typeof loadIPSet&&null!=opts.blocklist?loadIPSet(opts.blocklist,{headers:{"user-agent":`WebTorrent/${VERSION} (https://webtorrent.io)`}},(err,ipSet)=>err?this.error(`Failed to load blocklist: ${err.message}`):void(this.blocked=ipSet,ready())):process.nextTick(ready)}get downloadSpeed(){return this._downloadSpeed()}get uploadSpeed(){return this._uploadSpeed()}get progress(){const torrents=this.torrents.filter(torrent=>1!==torrent.progress),downloaded=torrents.reduce((total,torrent)=>total+torrent.downloaded,0),length=torrents.reduce((total,torrent)=>total+(torrent.length||0),0)||1;return downloaded/length}get ratio(){const uploaded=this.torrents.reduce((total,torrent)=>total+torrent.uploaded,0),received=this.torrents.reduce((total,torrent)=>total+torrent.received,0)||1;return uploaded/received}get(torrentId){if(!(torrentId instanceof Torrent)){let parsed;try{parsed=parseTorrent(torrentId)}catch(err){}if(!parsed)return null;if(!parsed.infoHash)throw new Error("Invalid torrent identifier");for(const torrent of this.torrents)if(torrent.infoHash===parsed.infoHash)return torrent}else if(this.torrents.includes(torrentId))return torrentId;return null}download(torrentId,opts,ontorrent){return console.warn("WebTorrent: client.download() is deprecated. Use client.add() instead"),this.add(torrentId,opts,ontorrent)}add(torrentId,opts={},ontorrent=()=>{}){function onClose(){torrent.removeListener("_infoHash",onInfoHash),torrent.removeListener("ready",onReady),torrent.removeListener("close",onClose)}if(this.destroyed)throw new Error("client is destroyed");"function"==typeof opts&&([opts,ontorrent]=[{},opts]);const onInfoHash=()=>{if(!this.destroyed)for(const t of this.torrents)if(t.infoHash===torrent.infoHash&&t!==torrent)return void torrent._destroy(new Error(`Cannot add duplicate torrent ${torrent.infoHash}`))},onReady=()=>{this.destroyed||(ontorrent(torrent),this.emit("torrent",torrent))};this._debug("add"),opts=opts?Object.assign({},opts):{};const torrent=new Torrent(torrentId,this,opts);return this.torrents.push(torrent),torrent.once("_infoHash",onInfoHash),torrent.once("ready",onReady),torrent.once("close",onClose),torrent}seed(input,opts,onseed){if(this.destroyed)throw new Error("client is destroyed");"function"==typeof opts&&([opts,onseed]=[{},opts]),this._debug("seed"),opts=opts?Object.assign({},opts):{},opts.skipVerify=!0;const isFilePath="string"==typeof input;isFilePath&&(opts.path=path.dirname(input)),opts.createdBy||(opts.createdBy=`WebTorrent/${VERSION_STR}`);const _onseed=torrent=>{this._debug("on seed"),"function"==typeof onseed&&onseed(torrent),torrent.emit("seed"),this.emit("seed",torrent)},torrent=this.add(null,opts,torrent=>{const tasks=[cb=>isFilePath?cb():void torrent.load(streams,cb)];this.dht&&tasks.push(cb=>{torrent.once("dhtAnnounce",cb)}),parallel(tasks,err=>this.destroyed?void 0:err?torrent._destroy(err):void _onseed(torrent))});let streams;return isFileList(input)?input=Array.from(input):!Array.isArray(input)&&(input=[input]),parallel(input.map(item=>cb=>{isReadable(item)?concat(item,cb):cb(null,item)}),(err,input)=>this.destroyed?void 0:err?torrent._destroy(err):void createTorrent.parseInput(input,opts,(err,files)=>this.destroyed?void 0:err?torrent._destroy(err):void(streams=files.map(file=>file.getStream),createTorrent(input,opts,(err,torrentBuf)=>{if(!this.destroyed){if(err)return torrent._destroy(err);const existingTorrent=this.get(torrentBuf);existingTorrent?torrent._destroy(new Error(`Cannot add duplicate torrent ${existingTorrent.infoHash}`)):torrent._onTorrentId(torrentBuf)}})))),torrent}remove(torrentId,opts,cb){if("function"==typeof opts)return this.remove(torrentId,null,opts);this._debug("remove");const torrent=this.get(torrentId);if(!torrent)throw new Error(`No torrent with id ${torrentId}`);this._remove(torrentId,opts,cb)}_remove(torrentId,opts,cb){if("function"==typeof opts)return this._remove(torrentId,null,opts);const torrent=this.get(torrentId);torrent&&(this.torrents.splice(this.torrents.indexOf(torrent),1),torrent.destroy(opts,cb))}address(){return this.listening?this._connPool?this._connPool.tcpServer.address():{address:"0.0.0.0",family:"IPv4",port:0}:null}destroy(cb){if(this.destroyed)throw new Error("client already destroyed");this._destroy(null,cb)}_destroy(err,cb){this._debug("client destroy"),this.destroyed=!0;const tasks=this.torrents.map(torrent=>cb=>{torrent.destroy(cb)});this._connPool&&tasks.push(cb=>{this._connPool.destroy(cb)}),this.dht&&tasks.push(cb=>{this.dht.destroy(cb)}),parallel(tasks,cb),err&&this.emit("error",err),this.torrents=[],this._connPool=null,this.dht=null}_onListening(){if(this._debug("listening"),this.listening=!0,this._connPool){const address=this._connPool.tcpServer.address();address&&(this.torrentPort=address.port)}this.emit("listening")}_debug(){const args=[].slice.call(arguments);args[0]=`[${this._debugId}] ${args[0]}`,debug(...args)}}WebTorrent.WEBRTC_SUPPORT=Peer.WEBRTC_SUPPORT,WebTorrent.VERSION=VERSION,module.exports=WebTorrent}).call(this)}).call(this,require("_process"),"undefined"==typeof global?"undefined"==typeof self?"undefined"==typeof window?{}:window:self:global,require("buffer").Buffer)},{"./lib/conn-pool":1,"./lib/torrent":7,"./package.json":202,_process:132,"bittorrent-dht/client":23,buffer:38,"create-torrent":68,debug:69,events:39,"load-ip-set":36,"parse-torrent":130,path:40,randombytes:140,"run-parallel":162,"simple-concat":166,"simple-peer":168,speedometer:172}]},{},[203])(203)}); \ No newline at end of file + */'use strict';function combineRanges(ranges){for(var ordered=ranges.map(mapWithIndex).sort(sortByRangeStart),j=0,i=1;icurrent.end+1?ordered[++j]=range:range.end>current.end&&(current.end=range.end,current.index=_Mathmin(current.index,range.index))}ordered.length=j+1;var combined=ordered.sort(sortByRangeIndex).map(mapWithoutIndex);return combined.type=ranges.type,combined}function mapWithIndex(range,index){return{start:range.start,end:range.end,index:index}}function mapWithoutIndex(range){return{start:range.start,end:range.end}}function sortByRangeIndex(a,b){return a.index-b.index}function sortByRangeStart(a,b){return a.start-b.start}module.exports=function(size,str,options){if("string"!=typeof str)throw new TypeError("argument str must be a string");var index=str.indexOf("=");if(-1===index)return-2;var arr=str.slice(index+1).split(","),ranges=[];ranges.type=str.slice(0,index);for(var i=0;isize-1&&(end=size-1),!(isNaN(start)||isNaN(end)||start>end||0>start))&&ranges.push({start:start,end:end})}return 1>ranges.length?-1:options&&options.combine?combineRanges(ranges):ranges}},{}],142:[function(require,module){const{Writable,PassThrough}=require("readable-stream");module.exports=class RangeSliceStream extends Writable{constructor(offset,opts={}){super(opts),this.destroyed=!1,this._queue=[],this._position=offset||0,this._cb=null,this._buffer=null,this._out=null}_write(chunk,encoding,cb){let drained=!0;for(;;){if(this.destroyed)return;if(0===this._queue.length)return this._buffer=chunk,void(this._cb=cb);this._buffer=null;var currRange=this._queue[0];const writeStart=_Mathmax(currRange.start-this._position,0),writeEnd=currRange.end-this._position;if(writeStart>=chunk.length)return this._position+=chunk.length,cb(null);let toWrite;if(writeEnd>chunk.length){this._position+=chunk.length,toWrite=0===writeStart?chunk:chunk.slice(writeStart),drained=currRange.stream.write(toWrite)&&drained;break}this._position+=writeEnd,toWrite=0===writeStart&&writeEnd===chunk.length?chunk:chunk.slice(writeStart,writeEnd),drained=currRange.stream.write(toWrite)&&drained,currRange.last&&currRange.stream.end(),chunk=chunk.slice(writeEnd),this._queue.shift()}drained?cb(null):currRange.stream.once("drain",cb.bind(null,null))}slice(ranges){if(this.destroyed)return null;Array.isArray(ranges)||(ranges=[ranges]);const str=new PassThrough;return ranges.forEach((range,i)=>{this._queue.push({start:range.start,end:range.end,stream:str,last:i===ranges.length-1})}),this._buffer&&this._write(this._buffer,null,this._cb),str}destroy(err){this.destroyed||(this.destroyed=!0,err&&this.emit("error",err))}}},{"readable-stream":157}],143:[function(require,module,exports){arguments[4][42][0].apply(exports,arguments)},{dup:42}],144:[function(require,module,exports){arguments[4][43][0].apply(exports,arguments)},{"./_stream_readable":146,"./_stream_writable":148,_process:132,dup:43,inherits:97}],145:[function(require,module,exports){arguments[4][44][0].apply(exports,arguments)},{"./_stream_transform":147,dup:44,inherits:97}],146:[function(require,module,exports){arguments[4][45][0].apply(exports,arguments)},{"../errors":143,"./_stream_duplex":144,"./internal/streams/async_iterator":149,"./internal/streams/buffer_list":150,"./internal/streams/destroy":151,"./internal/streams/from":153,"./internal/streams/state":155,"./internal/streams/stream":156,_process:132,buffer:38,dup:45,events:39,inherits:97,"string_decoder/":182,util:36}],147:[function(require,module,exports){arguments[4][46][0].apply(exports,arguments)},{"../errors":143,"./_stream_duplex":144,dup:46,inherits:97}],148:[function(require,module,exports){arguments[4][47][0].apply(exports,arguments)},{"../errors":143,"./_stream_duplex":144,"./internal/streams/destroy":151,"./internal/streams/state":155,"./internal/streams/stream":156,_process:132,buffer:38,dup:47,inherits:97,"util-deprecate":196}],149:[function(require,module,exports){arguments[4][48][0].apply(exports,arguments)},{"./end-of-stream":152,_process:132,dup:48}],150:[function(require,module,exports){arguments[4][49][0].apply(exports,arguments)},{buffer:38,dup:49,util:36}],151:[function(require,module,exports){arguments[4][50][0].apply(exports,arguments)},{_process:132,dup:50}],152:[function(require,module,exports){arguments[4][51][0].apply(exports,arguments)},{"../../../errors":143,dup:51}],153:[function(require,module,exports){arguments[4][52][0].apply(exports,arguments)},{dup:52}],154:[function(require,module,exports){arguments[4][53][0].apply(exports,arguments)},{"../../../errors":143,"./end-of-stream":152,dup:53}],155:[function(require,module,exports){arguments[4][54][0].apply(exports,arguments)},{"../../../errors":143,dup:54}],156:[function(require,module,exports){arguments[4][55][0].apply(exports,arguments)},{dup:55,events:39}],157:[function(require,module,exports){exports=module.exports=require("./lib/_stream_readable.js"),exports.Stream=exports,exports.Readable=exports,exports.Writable=require("./lib/_stream_writable.js"),exports.Duplex=require("./lib/_stream_duplex.js"),exports.Transform=require("./lib/_stream_transform.js"),exports.PassThrough=require("./lib/_stream_passthrough.js"),exports.finished=require("./lib/internal/streams/end-of-stream.js"),exports.pipeline=require("./lib/internal/streams/pipeline.js")},{"./lib/_stream_duplex.js":144,"./lib/_stream_passthrough.js":145,"./lib/_stream_readable.js":146,"./lib/_stream_transform.js":147,"./lib/_stream_writable.js":148,"./lib/internal/streams/end-of-stream.js":152,"./lib/internal/streams/pipeline.js":154}],158:[function(require,module){(function(Buffer){(function(){function RecordSet(){this.list=[],this.map=new Map}function RecordStore(){this.records=new Map,this.size=0}function RecordCache(opts){if(!(this instanceof RecordCache))return new RecordCache(opts);if(opts||(opts={}),this.maxSize=opts.maxSize||1/0,this.maxAge=opts.maxAge||0,this._onstale=opts.onStale||opts.onstale||null,this._fresh=new RecordStore,this._stale=new RecordStore,this._interval=null,this.maxAge&&this.maxAge<1/0){var tick=_Mathceil(2/3*this.maxAge);this._interval=setInterval(this._gc.bind(this),tick),this._interval.unref&&this._interval.unref()}}function toString(record){return Buffer.isBuffer(record)?record.toString("hex"):record}function swap(list,a,b){var tmp=list[a];tmp.index=b,list[b].index=a,list[a]=list[b],list[b]=tmp}var EMPTY=[];module.exports=RecordCache,RecordSet.prototype.add=function(record,value){var k=toString(record),r=this.map.get(k);return!r&&(r={index:this.list.length,record:value||record},this.list.push(r),this.map.set(k,r),!0)},RecordSet.prototype.remove=function(record){var k=toString(record),r=this.map.get(k);return!!r&&(swap(this.list,r.index,this.list.length-1),this.list.pop(),this.map.delete(k),!0)},RecordStore.prototype.add=function(name,record,value){var r=this.records.get(name);return r||(r=new RecordSet,this.records.set(name,r)),!!r.add(record,value)&&(this.size++,!0)},RecordStore.prototype.remove=function(name,record,value){var r=this.records.get(name);return!!r&&!!r.remove(record,value)&&(this.size--,r.map.size||this.records.delete(name),!0)},RecordStore.prototype.get=function(name){var r=this.records.get(name);return r?r.list:EMPTY},Object.defineProperty(RecordCache.prototype,"size",{get:function(){return this._fresh.size+this._stale.size}}),RecordCache.prototype.add=function(name,record,value){this._stale.remove(name,record,value),this._fresh.add(name,record,value)&&this._fresh.size>this.maxSize&&this._gc()},RecordCache.prototype.remove=function(name,record,value){this._fresh.remove(name,record,value),this._stale.remove(name,record,value)},RecordCache.prototype.get=function(name,n){var a=this._fresh.get(name),b=this._stale.get(name),aLen=a.length,bLen=b.length,len=aLen+bLen;(n>len||!n)&&(n=len);for(var result=Array(n),i=0,j;iopts.maxBlobLength)||(debug("File length too large for Blob URL approach: %d (max: %d)",file.length,opts.maxBlobLength),fatalError(new Error(`File length too large for Blob URL approach: ${file.length} (max: ${opts.maxBlobLength})`)),!1)}function renderMediaElement(type){checkBlobLength()&&(elem=getElem(type),getBlobURL(file,(err,url)=>err?fatalError(err):void(elem.addEventListener("error",fatalError),elem.addEventListener("loadstart",onLoadStart),elem.addEventListener("loadedmetadata",onLoadedMetadata),elem.src=url)))}function onLoadStart(){if(elem.removeEventListener("loadstart",onLoadStart),opts.autoplay){const playPromise=elem.play();"undefined"!=typeof playPromise&&playPromise.catch(fatalError)}}function onLoadedMetadata(){elem.removeEventListener("loadedmetadata",onLoadedMetadata),cb(null,elem)}function renderIframe(){getBlobURL(file,(err,url)=>err?fatalError(err):void(".pdf"===extname?(elem=getElem("object"),elem.setAttribute("typemustmatch",!0),elem.setAttribute("type","application/pdf"),elem.setAttribute("data",url)):(elem=getElem("iframe"),elem.sandbox="allow-forms allow-scripts",elem.src=url),cb(null,elem)))}function fatalError(err){err.message=`Error rendering file "${file.name}": ${err.message}`,debug(err.message),cb(err)}const extname=path.extname(file.name).toLowerCase();let currentTime=0,elem;MEDIASOURCE_EXTS.includes(extname)?function(){function useVideostream(){debug(`Use \`videostream\` package for ${file.name}`),prepareElem(),elem.addEventListener("error",fallbackToMediaSource),elem.addEventListener("loadstart",onLoadStart),elem.addEventListener("loadedmetadata",onLoadedMetadata),new VideoStream(file,elem)}function useMediaSource(){debug(`Use MediaSource API for ${file.name}`),prepareElem(),elem.addEventListener("error",fallbackToBlobURL),elem.addEventListener("loadstart",onLoadStart),elem.addEventListener("loadedmetadata",onLoadedMetadata);const wrapper=new MediaElementWrapper(elem),writable=wrapper.createWriteStream(getCodec(file.name));file.createReadStream().pipe(writable),currentTime&&(elem.currentTime=currentTime)}function useBlobURL(){debug(`Use Blob URL for ${file.name}`),prepareElem(),elem.addEventListener("error",fatalError),elem.addEventListener("loadstart",onLoadStart),elem.addEventListener("loadedmetadata",onLoadedMetadata),getBlobURL(file,(err,url)=>err?fatalError(err):void(elem.src=url,currentTime&&(elem.currentTime=currentTime)))}function fallbackToMediaSource(err){debug("videostream error: fallback to MediaSource API: %o",err.message||err),elem.removeEventListener("error",fallbackToMediaSource),elem.removeEventListener("loadedmetadata",onLoadedMetadata),useMediaSource()}function fallbackToBlobURL(err){debug("MediaSource API error: fallback to Blob URL: %o",err.message||err);checkBlobLength()&&(elem.removeEventListener("error",fallbackToBlobURL),elem.removeEventListener("loadedmetadata",onLoadedMetadata),useBlobURL())}function prepareElem(){elem||(elem=getElem(tagName),elem.addEventListener("progress",()=>{currentTime=elem.currentTime}))}const tagName=MEDIASOURCE_VIDEO_EXTS.includes(extname)?"video":"audio";MediaSource?VIDEOSTREAM_EXTS.includes(extname)?useVideostream():useMediaSource():useBlobURL()}():VIDEO_EXTS.includes(extname)?renderMediaElement("video"):AUDIO_EXTS.includes(extname)?renderMediaElement("audio"):IMAGE_EXTS.includes(extname)?function(){elem=getElem("img"),getBlobURL(file,(err,url)=>err?fatalError(err):void(elem.src=url,elem.alt=file.name,cb(null,elem)))}():IFRAME_EXTS.includes(extname)?renderIframe():function(){function done(){isAscii(str)?(debug("File extension \"%s\" appears ascii, so will render.",extname),renderIframe()):(debug("File extension \"%s\" appears non-ascii, will not render.",extname),cb(new Error(`Unsupported file type "${extname}": Cannot append to DOM`)))}debug("Unknown file extension \"%s\" - will attempt to render into iframe",extname);let str="";file.createReadStream({start:0,end:1e3}).setEncoding("utf8").on("data",chunk=>{str+=chunk}).on("end",done).on("error",cb)}()}function getBlobURL(file,cb){const extname=path.extname(file.name).toLowerCase();streamToBlobURL(file.createReadStream(),exports.mime[extname]).then(blobUrl=>cb(null,blobUrl),err=>cb(err))}function validateFile(file){if(null==file)throw new Error("file cannot be null or undefined");if("string"!=typeof file.name)throw new Error("missing or invalid file.name property");if("function"!=typeof file.createReadStream)throw new Error("missing or invalid file.createReadStream property")}function getCodec(name){const extname=path.extname(name).toLowerCase();return{".m4a":"audio/mp4; codecs=\"mp4a.40.5\"",".m4b":"audio/mp4; codecs=\"mp4a.40.5\"",".m4p":"audio/mp4; codecs=\"mp4a.40.5\"",".m4v":"video/mp4; codecs=\"avc1.640029, mp4a.40.5\"",".mkv":"video/webm; codecs=\"avc1.640029, mp4a.40.5\"",".mp3":"audio/mpeg",".mp4":"video/mp4; codecs=\"avc1.640029, mp4a.40.5\"",".webm":"video/webm; codecs=\"vorbis, vp8\""}[extname]}function parseOpts(opts){null==opts.autoplay&&(opts.autoplay=!1),null==opts.muted&&(opts.muted=!1),null==opts.controls&&(opts.controls=!0),null==opts.maxBlobLength&&(opts.maxBlobLength=MAX_BLOB_LENGTH)}function setMediaOpts(elem,opts){elem.autoplay=!!opts.autoplay,elem.muted=!!opts.muted,elem.controls=!!opts.controls}exports.render=function(file,elem,opts,cb){"function"==typeof opts&&(cb=opts,opts={}),opts||(opts={}),cb||(cb=()=>{}),validateFile(file),parseOpts(opts),"string"==typeof elem&&(elem=document.querySelector(elem)),renderMedia(file,tagName=>{if(elem.nodeName!==tagName.toUpperCase()){const extname=path.extname(file.name).toLowerCase();throw new Error(`Cannot render "${extname}" inside a "${elem.nodeName.toLowerCase()}" element, expected "${tagName}"`)}return("video"===tagName||"audio"===tagName)&&setMediaOpts(elem,opts),elem},opts,cb)},exports.append=function(file,rootElem,opts,cb){function createMedia(tagName){const elem=createElem(tagName);return setMediaOpts(elem,opts),rootElem.appendChild(elem),elem}function createElem(tagName){const elem=document.createElement(tagName);return rootElem.appendChild(elem),elem}function done(err,elem){err&&elem&&elem.remove(),cb(err,elem)}if("function"==typeof opts&&(cb=opts,opts={}),opts||(opts={}),cb||(cb=()=>{}),validateFile(file),parseOpts(opts),"string"==typeof rootElem&&(rootElem=document.querySelector(rootElem)),rootElem&&("VIDEO"===rootElem.nodeName||"AUDIO"===rootElem.nodeName))throw new Error("Invalid video/audio node argument. Argument must be root element that video/audio tag will be appended to.");renderMedia(file,function(tagName){return"video"===tagName||"audio"===tagName?createMedia(tagName):createElem(tagName)},opts,done)},exports.mime=require("./lib/mime.json");const debug=require("debug")("render-media"),isAscii=require("is-ascii"),MediaElementWrapper=require("mediasource"),path=require("path"),streamToBlobURL=require("stream-to-blob-url"),VideoStream=require("videostream"),VIDEOSTREAM_EXTS=[".m4a",".m4b",".m4p",".m4v",".mp4"],MEDIASOURCE_VIDEO_EXTS=[".m4v",".mkv",".mp4",".webm"],MEDIASOURCE_EXTS=[].concat(MEDIASOURCE_VIDEO_EXTS,[".m4a",".m4b",".m4p",".mp3"]),VIDEO_EXTS=[".mov",".ogv"],AUDIO_EXTS=[".aac",".oga",".ogg",".wav",".flac"],IMAGE_EXTS=[".bmp",".gif",".jpeg",".jpg",".png",".svg"],IFRAME_EXTS=[".css",".html",".js",".md",".pdf",".srt",".txt"],MAX_BLOB_LENGTH=200000000,MediaSource="undefined"!=typeof window&&window.MediaSource},{"./lib/mime.json":160,debug:69,"is-ascii":100,mediasource:113,path:40,"stream-to-blob-url":177,videostream:198}],160:[function(require,module){module.exports={".3gp":"video/3gpp",".aac":"audio/aac",".aif":"audio/x-aiff",".aiff":"audio/x-aiff",".atom":"application/atom+xml",".avi":"video/x-msvideo",".bmp":"image/bmp",".bz2":"application/x-bzip2",".conf":"text/plain",".css":"text/css",".csv":"text/plain",".diff":"text/x-diff",".doc":"application/msword",".flv":"video/x-flv",".gif":"image/gif",".gz":"application/x-gzip",".htm":"text/html",".html":"text/html",".ico":"image/vnd.microsoft.icon",".ics":"text/calendar",".iso":"application/octet-stream",".jar":"application/java-archive",".jpeg":"image/jpeg",".jpg":"image/jpeg",".js":"application/javascript",".json":"application/json",".less":"text/css",".log":"text/plain",".m3u":"audio/x-mpegurl",".m4a":"audio/x-m4a",".m4b":"audio/mp4",".m4p":"audio/mp4",".m4v":"video/x-m4v",".manifest":"text/cache-manifest",".markdown":"text/x-markdown",".mathml":"application/mathml+xml",".md":"text/x-markdown",".mid":"audio/midi",".midi":"audio/midi",".mov":"video/quicktime",".mp3":"audio/mpeg",".mp4":"video/mp4",".mp4v":"video/mp4",".mpeg":"video/mpeg",".mpg":"video/mpeg",".odp":"application/vnd.oasis.opendocument.presentation",".ods":"application/vnd.oasis.opendocument.spreadsheet",".odt":"application/vnd.oasis.opendocument.text",".oga":"audio/ogg",".ogg":"application/ogg",".pdf":"application/pdf",".png":"image/png",".pps":"application/vnd.ms-powerpoint",".ppt":"application/vnd.ms-powerpoint",".ps":"application/postscript",".psd":"image/vnd.adobe.photoshop",".qt":"video/quicktime",".rar":"application/x-rar-compressed",".rdf":"application/rdf+xml",".rss":"application/rss+xml",".rtf":"application/rtf",".svg":"image/svg+xml",".svgz":"image/svg+xml",".swf":"application/x-shockwave-flash",".tar":"application/x-tar",".tbz":"application/x-bzip-compressed-tar",".text":"text/plain",".tif":"image/tiff",".tiff":"image/tiff",".torrent":"application/x-bittorrent",".ttf":"application/x-font-ttf",".txt":"text/plain",".wav":"audio/wav",".webm":"video/webm",".wma":"audio/x-ms-wma",".wmv":"video/x-ms-wmv",".xls":"application/vnd.ms-excel",".xml":"application/xml",".yaml":"text/yaml",".yml":"text/yaml",".zip":"application/zip"}},{}],161:[function(require,module){(function(process){(function(){/*! run-parallel-limit. MIT License. Feross Aboukhadijeh */module.exports=function(tasks,limit,cb){function done(err){function end(){cb&&cb(err,results),cb=null}isSync?process.nextTick(end):end()}function each(i,err,result){if(results[i]=result,err&&(isErrored=!0),0==--pending||err)done(err);else if(!isErrored&&next */module.exports=function(tasks,cb){function done(err){function end(){cb&&cb(err,results),cb=null}isSync?process.nextTick(end):end()}function each(i,err,result){results[i]=result,(0==--pending||err)&&done(err)}var isSync=!0,results,pending,keys;Array.isArray(tasks)?(results=[],pending=tasks.length):(keys=Object.keys(tasks),results={},pending=keys.length),pending?keys?keys.forEach(function(key){tasks[key](function(err,result){each(key,err,result)})}):tasks.forEach(function(task,i){task(function(err,result){each(i,err,result)})}):done(null),isSync=!1}}).call(this)}).call(this,require("_process"))},{_process:132}],163:[function(require,module){(function(process){(function(){/*! run-series. MIT License. Feross Aboukhadijeh */module.exports=function(tasks,cb){function done(err){function end(){cb&&cb(err,results)}isSync?process.nextTick(end):end()}function each(err,result){results.push(result),++current>=tasks.length||err?done(err):tasks[current](each)}var current=0,results=[],isSync=!0;0>2)+1;i>2]|=128<<24-(chunkLen%4<<3),bin[(-16&(chunkLen>>2)+2)+14]=0|msgLen/536870912,bin[(-16&(chunkLen>>2)+2)+15]=msgLen<<3},getRawDigest=function(heap,padMaxChunkLen){var io=new Int32Array(heap,padMaxChunkLen+320,5),out=new Int32Array(5),arr=new DataView(out.buffer);return arr.setInt32(0,io[0],!1),arr.setInt32(4,io[1],!1),arr.setInt32(8,io[2],!1),arr.setInt32(12,io[3],!1),arr.setInt32(16,io[4],!1),out},Rusha=function(){function Rusha(chunkSize){if(_classCallCheck(this,Rusha),chunkSize=chunkSize||65536,0>2);return padZeroes(view,chunkLen),padData(view,chunkLen,msgLen),padChunkLen},Rusha.prototype._write=function(data,chunkOffset,chunkLen,off){conv(data,this._h8,this._h32,chunkOffset,chunkLen,off||0)},Rusha.prototype._coreCall=function(data,chunkOffset,chunkLen,msgLen,finalize){var padChunkLen=chunkLen;this._write(data,chunkOffset,chunkLen),finalize&&(padChunkLen=this._padChunk(chunkLen,msgLen)),this._core.hash(padChunkLen,this._padMaxChunkLen)},Rusha.prototype.rawDigest=function(str){var msgLen=str.byteLength||str.length||str.size||0;this._initState(this._heap,this._padMaxChunkLen);var chunkOffset=0,chunkLen=this._maxChunkLen;for(chunkOffset=0;msgLen>chunkOffset+chunkLen;chunkOffset+=chunkLen)this._coreCall(str,chunkOffset,chunkLen,msgLen,!1);return this._coreCall(str,chunkOffset,msgLen-chunkOffset,msgLen,!0),getRawDigest(this._heap,this._padMaxChunkLen)},Rusha.prototype.digest=function(str){return toHex(this.rawDigest(str).buffer)},Rusha.prototype.digestFromString=function(str){return this.digest(str)},Rusha.prototype.digestFromBuffer=function(str){return this.digest(str)},Rusha.prototype.digestFromArrayBuffer=function(str){return this.digest(str)},Rusha.prototype.resetState=function(){return this._initState(this._heap,this._padMaxChunkLen),this},Rusha.prototype.append=function(chunk){var chunkOffset=0,chunkLen=chunk.byteLength||chunk.length||chunk.size||0,turnOffset=this._offset%this._maxChunkLen,inputLen=void 0;for(this._offset+=chunkLen;chunkOffseti;i++)precomputedHex[i]=(16>i?"0":"")+i.toString(16);module.exports.toHex=function(arrayBuffer){for(var binarray=new Uint8Array(arrayBuffer),res=Array(arrayBuffer.byteLength),_i=0;_i=v)return 65536;if(16777216>v)for(p=1;p>2],y1$857=0|H$849[x$852+324>>2],y2$859=0|H$849[x$852+328>>2],y3$861=0|H$849[x$852+332>>2],y4$863=0|H$849[x$852+336>>2],i$853=0;(0|i$853)<(0|k$851);i$853=0|i$853+64){for(z0$856=y0$855,z1$858=y1$857,z2$860=y2$859,z3$862=y3$861,z4$864=y4$863,j$854=0;64>(0|j$854);j$854=0|j$854+4)t1$866=0|H$849[i$853+j$854>>2],t0$865=0|(0|(y0$855<<5|y0$855>>>27)+(y1$857&y2$859|~y1$857&y3$861))+(0|(0|t1$866+y4$863)+1518500249),y4$863=y3$861,y3$861=y2$859,y2$859=y1$857<<30|y1$857>>>2,y1$857=y0$855,y0$855=t0$865,H$849[k$851+j$854>>2]=t1$866;for(j$854=0|k$851+64;(0|j$854)<(0|k$851+80);j$854=0|j$854+4)t1$866=(H$849[j$854-12>>2]^H$849[j$854-32>>2]^H$849[j$854-56>>2]^H$849[j$854-64>>2])<<1|(H$849[j$854-12>>2]^H$849[j$854-32>>2]^H$849[j$854-56>>2]^H$849[j$854-64>>2])>>>31,t0$865=0|(0|(y0$855<<5|y0$855>>>27)+(y1$857&y2$859|~y1$857&y3$861))+(0|(0|t1$866+y4$863)+1518500249),y4$863=y3$861,y3$861=y2$859,y2$859=y1$857<<30|y1$857>>>2,y1$857=y0$855,y0$855=t0$865,H$849[j$854>>2]=t1$866;for(j$854=0|k$851+80;(0|j$854)<(0|k$851+160);j$854=0|j$854+4)t1$866=(H$849[j$854-12>>2]^H$849[j$854-32>>2]^H$849[j$854-56>>2]^H$849[j$854-64>>2])<<1|(H$849[j$854-12>>2]^H$849[j$854-32>>2]^H$849[j$854-56>>2]^H$849[j$854-64>>2])>>>31,t0$865=0|(0|(y0$855<<5|y0$855>>>27)+(y1$857^y2$859^y3$861))+(0|(0|t1$866+y4$863)+1859775393),y4$863=y3$861,y3$861=y2$859,y2$859=y1$857<<30|y1$857>>>2,y1$857=y0$855,y0$855=t0$865,H$849[j$854>>2]=t1$866;for(j$854=0|k$851+160;(0|j$854)<(0|k$851+240);j$854=0|j$854+4)t1$866=(H$849[j$854-12>>2]^H$849[j$854-32>>2]^H$849[j$854-56>>2]^H$849[j$854-64>>2])<<1|(H$849[j$854-12>>2]^H$849[j$854-32>>2]^H$849[j$854-56>>2]^H$849[j$854-64>>2])>>>31,t0$865=0|(0|(y0$855<<5|y0$855>>>27)+(y1$857&y2$859|y1$857&y3$861|y2$859&y3$861))+(0|(0|t1$866+y4$863)-1894007588),y4$863=y3$861,y3$861=y2$859,y2$859=y1$857<<30|y1$857>>>2,y1$857=y0$855,y0$855=t0$865,H$849[j$854>>2]=t1$866;for(j$854=0|k$851+240;(0|j$854)<(0|k$851+320);j$854=0|j$854+4)t1$866=(H$849[j$854-12>>2]^H$849[j$854-32>>2]^H$849[j$854-56>>2]^H$849[j$854-64>>2])<<1|(H$849[j$854-12>>2]^H$849[j$854-32>>2]^H$849[j$854-56>>2]^H$849[j$854-64>>2])>>>31,t0$865=0|(0|(y0$855<<5|y0$855>>>27)+(y1$857^y2$859^y3$861))+(0|(0|t1$866+y4$863)-899497514),y4$863=y3$861,y3$861=y2$859,y2$859=y1$857<<30|y1$857>>>2,y1$857=y0$855,y0$855=t0$865,H$849[j$854>>2]=t1$866;y0$855=0|y0$855+z0$856,y1$857=0|y1$857+z1$858,y2$859=0|y2$859+z2$860,y3$861=0|y3$861+z3$862,y4$863=0|y4$863+z4$864}H$849[x$852+320>>2]=y0$855,H$849[x$852+324>>2]=y1$857,H$849[x$852+328>>2]=y2$859,H$849[x$852+332>>2]=y3$861,H$849[x$852+336>>2]=y4$863}}}},function(module){var _this=this,reader=void 0;"undefined"!=typeof self&&"undefined"!=typeof self.FileReaderSync&&(reader=new self.FileReaderSync);var convStr=function(str,H8,H32,start,len,off){var om=off%4,lm=(len+om)%4,j=len-lm,i;switch(om){case 0:H8[off]=str.charCodeAt(start+3);case 1:H8[0|off+1-(om<<1)]=str.charCodeAt(start+2);case 2:H8[0|off+2-(om<<1)]=str.charCodeAt(start+1);case 3:H8[0|off+3-(om<<1)]=str.charCodeAt(start);}if(!(len>2]=str.charCodeAt(start+i)<<24|str.charCodeAt(start+i+1)<<16|str.charCodeAt(start+i+2)<<8|str.charCodeAt(start+i+3);switch(lm){case 3:H8[0|off+j+1]=str.charCodeAt(start+j+2);case 2:H8[0|off+j+2]=str.charCodeAt(start+j+1);case 1:H8[0|off+j+3]=str.charCodeAt(start+j);}}},convBuf=function(buf,H8,H32,start,len,off){var om=off%4,lm=(len+om)%4,j=len-lm,i;switch(om){case 0:H8[off]=buf[start+3];case 1:H8[0|off+1-(om<<1)]=buf[start+2];case 2:H8[0|off+2-(om<<1)]=buf[start+1];case 3:H8[0|off+3-(om<<1)]=buf[start];}if(!(len>2]=buf[start+i]<<24|buf[start+i+1]<<16|buf[start+i+2]<<8|buf[start+i+3];switch(lm){case 3:H8[0|off+j+1]=buf[start+j+2];case 2:H8[0|off+j+2]=buf[start+j+1];case 1:H8[0|off+j+3]=buf[start+j];}}},convBlob=function(blob,H8,H32,start,len,off){var i=void 0,om=off%4,lm=(len+om)%4,j=len-lm,buf=new Uint8Array(reader.readAsArrayBuffer(blob.slice(start,start+len)));switch(om){case 0:H8[off]=buf[3];case 1:H8[0|off+1-(om<<1)]=buf[2];case 2:H8[0|off+2-(om<<1)]=buf[1];case 3:H8[0|off+3-(om<<1)]=buf[0];}if(!(len>2]=buf[i]<<24|buf[i+1]<<16|buf[i+2]<<8|buf[i+3];switch(lm){case 3:H8[0|off+j+1]=buf[j+2];case 2:H8[0|off+j+2]=buf[j+1];case 1:H8[0|off+j+3]=buf[j];}}};module.exports=function(data,H8,H32,start,len,off){if("string"==typeof data)return convStr(data,H8,H32,start,len,off);if(data instanceof Array)return convBuf(data,H8,H32,start,len,off);if(_this&&_this.Buffer&&_this.Buffer.isBuffer(data))return convBuf(data,H8,H32,start,len,off);if(data instanceof ArrayBuffer)return convBuf(new Uint8Array(data),H8,H32,start,len,off);if(data.buffer instanceof ArrayBuffer)return convBuf(new Uint8Array(data.buffer,data.byteOffset,data.byteLength),H8,H32,start,len,off);if(data instanceof Blob)return convBlob(data,H8,H32,start,len,off);throw new Error("Unsupported data type.")}},function(module,exports,__webpack_require__){function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}var Rusha=__webpack_require__(0),_require=__webpack_require__(1),toHex=_require.toHex,Hash=function(){function Hash(){_classCallCheck(this,Hash),this._rusha=new Rusha,this._rusha.resetState()}return Hash.prototype.update=function(data){return this._rusha.append(data),this},Hash.prototype.digest=function digest(encoding){var digest=this._rusha.rawEnd().buffer;if(!encoding)return digest;if("hex"===encoding)return toHex(digest);throw new Error("unsupported digest encoding")},Hash}();module.exports=function(){return new Hash}}])})},{}],165:[function(require,module,exports){function copyProps(src,dst){for(var key in src)dst[key]=src[key]}function SafeBuffer(arg,encodingOrOffset,length){return Buffer(arg,encodingOrOffset,length)}/*! safe-buffer. MIT License. Feross Aboukhadijeh */var buffer=require("buffer"),Buffer=buffer.Buffer;Buffer.from&&Buffer.alloc&&Buffer.allocUnsafe&&Buffer.allocUnsafeSlow?module.exports=buffer:(copyProps(buffer,exports),exports.Buffer=SafeBuffer),SafeBuffer.prototype=Object.create(Buffer.prototype),copyProps(Buffer,SafeBuffer),SafeBuffer.from=function(arg,encodingOrOffset,length){if("number"==typeof arg)throw new TypeError("Argument must not be a number");return Buffer(arg,encodingOrOffset,length)},SafeBuffer.alloc=function(size,fill,encoding){if("number"!=typeof size)throw new TypeError("Argument must be a number");var buf=Buffer(size);return void 0===fill?buf.fill(0):"string"==typeof encoding?buf.fill(fill,encoding):buf.fill(fill),buf},SafeBuffer.allocUnsafe=function(size){if("number"!=typeof size)throw new TypeError("Argument must be a number");return Buffer(size)},SafeBuffer.allocUnsafeSlow=function(size){if("number"!=typeof size)throw new TypeError("Argument must be a number");return buffer.SlowBuffer(size)}},{buffer:38}],166:[function(require,module){(function(Buffer){(function(){/*! simple-concat. MIT License. Feross Aboukhadijeh */module.exports=function(stream,cb){var chunks=[];stream.on("data",function(chunk){chunks.push(chunk)}),stream.once("end",function(){cb&&cb(null,Buffer.concat(chunks)),cb=null}),stream.once("error",function(err){cb&&cb(err),cb=null})}}).call(this)}).call(this,require("buffer").Buffer)},{buffer:38}],167:[function(require,module){(function(Buffer){(function(){function simpleGet(opts,cb){if(opts=Object.assign({maxRedirects:10},"string"==typeof opts?{url:opts}:opts),cb=once(cb),opts.url){const{hostname,port,protocol,auth,path}=url.parse(opts.url);delete opts.url,hostname||port||protocol||auth?Object.assign(opts,{hostname,port,protocol,auth,path}):opts.path=path}const headers={"accept-encoding":"gzip, deflate"};opts.headers&&Object.keys(opts.headers).forEach(k=>headers[k.toLowerCase()]=opts.headers[k]),opts.headers=headers;let body;opts.body?body=opts.json&&!isStream(opts.body)?JSON.stringify(opts.body):opts.body:opts.form&&(body="string"==typeof opts.form?opts.form:querystring.stringify(opts.form),opts.headers["content-type"]="application/x-www-form-urlencoded"),body&&(!opts.method&&(opts.method="POST"),!isStream(body)&&(opts.headers["content-length"]=Buffer.byteLength(body)),opts.json&&!opts.form&&(opts.headers["content-type"]="application/json")),delete opts.body,delete opts.form,opts.json&&(opts.headers.accept="application/json"),opts.method&&(opts.method=opts.method.toUpperCase());const protocol="https:"===opts.protocol?https:http,req=protocol.request(opts,res=>{if(!1!==opts.followRedirects&&300<=res.statusCode&&400>res.statusCode&&res.headers.location)return opts.url=res.headers.location,delete opts.headers.host,res.resume(),"POST"===opts.method&&[301,302].includes(res.statusCode)&&(opts.method="GET",delete opts.headers["content-length"],delete opts.headers["content-type"]),0==opts.maxRedirects--?cb(new Error("too many redirects")):simpleGet(opts,cb);const tryUnzip="function"==typeof decompressResponse&&"HEAD"!==opts.method;cb(null,tryUnzip?decompressResponse(res):res)});return req.on("timeout",()=>{req.abort(),cb(new Error("Request timed out"))}),req.on("error",cb),isStream(body)?body.on("error",cb).pipe(req):req.end(body),req}module.exports=simpleGet;const concat=require("simple-concat"),decompressResponse=require("decompress-response"),http=require("http"),https=require("https"),once=require("once"),querystring=require("querystring"),url=require("url"),isStream=o=>null!==o&&"object"==typeof o&&"function"==typeof o.pipe;simpleGet.concat=(opts,cb)=>simpleGet(opts,(err,res)=>err?cb(err):void concat(res,(err,data)=>{if(err)return cb(err);if(opts.json)try{data=JSON.parse(data.toString())}catch(err){return cb(err,res,data)}cb(null,res,data)})),["get","post","put","patch","head","delete"].forEach(method=>{simpleGet[method]=(opts,cb)=>("string"==typeof opts&&(opts={url:opts}),simpleGet(Object.assign({method:method.toUpperCase()},opts),cb))})}).call(this)}).call(this,require("buffer").Buffer)},{buffer:38,"decompress-response":36,http:173,https:94,once:129,querystring:137,"simple-concat":166,url:192}],168:[function(require,module){function filterTrickle(sdp){return sdp.replace(/a=ice-options:trickle\s\n/g,"")}function warn(message){console.warn(message)}/*! simple-peer. MIT License. Feross Aboukhadijeh */const debug=require("debug")("simple-peer"),getBrowserRTC=require("get-browser-rtc"),randombytes=require("randombytes"),stream=require("readable-stream"),queueMicrotask=require("queue-microtask"),errCode=require("err-code"),{Buffer}=require("buffer"),MAX_BUFFERED_AMOUNT=65536;class Peer extends stream.Duplex{constructor(opts){if(opts=Object.assign({allowHalfOpen:!1},opts),super(opts),this._id=randombytes(4).toString("hex").slice(0,7),this._debug("new peer %o",opts),this.channelName=opts.initiator?opts.channelName||randombytes(20).toString("hex"):null,this.initiator=opts.initiator||!1,this.channelConfig=opts.channelConfig||Peer.channelConfig,this.channelNegotiated=this.channelConfig.negotiated,this.config=Object.assign({},Peer.config,opts.config),this.offerOptions=opts.offerOptions||{},this.answerOptions=opts.answerOptions||{},this.sdpTransform=opts.sdpTransform||(sdp=>sdp),this.streams=opts.streams||(opts.stream?[opts.stream]:[]),this.trickle=void 0===opts.trickle||opts.trickle,this.allowHalfTrickle=void 0!==opts.allowHalfTrickle&&opts.allowHalfTrickle,this.iceCompleteTimeout=opts.iceCompleteTimeout||5000,this.destroyed=!1,this.destroying=!1,this._connected=!1,this.remoteAddress=void 0,this.remoteFamily=void 0,this.remotePort=void 0,this.localAddress=void 0,this.localFamily=void 0,this.localPort=void 0,this._wrtc=opts.wrtc&&"object"==typeof opts.wrtc?opts.wrtc:getBrowserRTC(),!this._wrtc)if("undefined"==typeof window)throw errCode(new Error("No WebRTC support: Specify `opts.wrtc` option in this environment"),"ERR_WEBRTC_SUPPORT");else throw errCode(new Error("No WebRTC support: Not a supported browser"),"ERR_WEBRTC_SUPPORT");this._pcReady=!1,this._channelReady=!1,this._iceComplete=!1,this._iceCompleteTimer=null,this._channel=null,this._pendingCandidates=[],this._isNegotiating=!1,this._firstNegotiation=!0,this._batchedNegotiation=!1,this._queuedNegotiation=!1,this._sendersAwaitingStable=[],this._senderMap=new Map,this._closingInterval=null,this._remoteTracks=[],this._remoteStreams=[],this._chunk=null,this._cb=null,this._interval=null;try{this._pc=new this._wrtc.RTCPeerConnection(this.config)}catch(err){return void queueMicrotask(()=>this.destroy(errCode(err,"ERR_PC_CONSTRUCTOR")))}this._isReactNativeWebrtc="number"==typeof this._pc._peerConnectionId,this._pc.oniceconnectionstatechange=()=>{this._onIceStateChange()},this._pc.onicegatheringstatechange=()=>{this._onIceStateChange()},this._pc.onconnectionstatechange=()=>{this._onConnectionStateChange()},this._pc.onsignalingstatechange=()=>{this._onSignalingStateChange()},this._pc.onicecandidate=event=>{this._onIceCandidate(event)},this.initiator||this.channelNegotiated?this._setupData({channel:this._pc.createDataChannel(this.channelName,this.channelConfig)}):this._pc.ondatachannel=event=>{this._setupData(event)},this.streams&&this.streams.forEach(stream=>{this.addStream(stream)}),this._pc.ontrack=event=>{this._onTrack(event)},this._debug("initial negotiation"),this._needsNegotiation(),this._onFinishBound=()=>{this._onFinish()},this.once("finish",this._onFinishBound)}get bufferSize(){return this._channel&&this._channel.bufferedAmount||0}get connected(){return this._connected&&"open"===this._channel.readyState}address(){return{port:this.localPort,family:this.localFamily,address:this.localAddress}}signal(data){if(this.destroyed)throw errCode(new Error("cannot signal after peer is destroyed"),"ERR_SIGNALING");if("string"==typeof data)try{data=JSON.parse(data)}catch(err){data={}}this._debug("signal()"),data.renegotiate&&this.initiator&&(this._debug("got request to renegotiate"),this._needsNegotiation()),data.transceiverRequest&&this.initiator&&(this._debug("got request for transceiver"),this.addTransceiver(data.transceiverRequest.kind,data.transceiverRequest.init)),data.candidate&&(this._pc.remoteDescription&&this._pc.remoteDescription.type?this._addIceCandidate(data.candidate):this._pendingCandidates.push(data.candidate)),data.sdp&&this._pc.setRemoteDescription(new this._wrtc.RTCSessionDescription(data)).then(()=>{this.destroyed||(this._pendingCandidates.forEach(candidate=>{this._addIceCandidate(candidate)}),this._pendingCandidates=[],"offer"===this._pc.remoteDescription.type&&this._createAnswer())}).catch(err=>{this.destroy(errCode(err,"ERR_SET_REMOTE_DESCRIPTION"))}),data.sdp||data.candidate||data.renegotiate||data.transceiverRequest||this.destroy(errCode(new Error("signal() called with invalid signal data"),"ERR_SIGNALING"))}_addIceCandidate(candidate){const iceCandidateObj=new this._wrtc.RTCIceCandidate(candidate);this._pc.addIceCandidate(iceCandidateObj).catch(err=>{!iceCandidateObj.address||iceCandidateObj.address.endsWith(".local")?warn("Ignoring unsupported ICE candidate."):this.destroy(errCode(err,"ERR_ADD_ICE_CANDIDATE"))})}send(chunk){this._channel.send(chunk)}addTransceiver(kind,init){if(this._debug("addTransceiver()"),this.initiator)try{this._pc.addTransceiver(kind,init),this._needsNegotiation()}catch(err){this.destroy(errCode(err,"ERR_ADD_TRANSCEIVER"))}else this.emit("signal",{type:"transceiverRequest",transceiverRequest:{kind,init}})}addStream(stream){this._debug("addStream()"),stream.getTracks().forEach(track=>{this.addTrack(track,stream)})}addTrack(track,stream){this._debug("addTrack()");const submap=this._senderMap.get(track)||new Map;let sender=submap.get(stream);if(!sender)sender=this._pc.addTrack(track,stream),submap.set(stream,sender),this._senderMap.set(track,submap),this._needsNegotiation();else if(sender.removed)throw errCode(new Error("Track has been removed. You should enable/disable tracks that you want to re-add."),"ERR_SENDER_REMOVED");else throw errCode(new Error("Track has already been added to that stream."),"ERR_SENDER_ALREADY_ADDED")}replaceTrack(oldTrack,newTrack,stream){this._debug("replaceTrack()");const submap=this._senderMap.get(oldTrack),sender=submap?submap.get(stream):null;if(!sender)throw errCode(new Error("Cannot replace track that was never added."),"ERR_TRACK_NOT_ADDED");newTrack&&this._senderMap.set(newTrack,submap),null==sender.replaceTrack?this.destroy(errCode(new Error("replaceTrack is not supported in this browser"),"ERR_UNSUPPORTED_REPLACETRACK")):sender.replaceTrack(newTrack)}removeTrack(track,stream){this._debug("removeSender()");const submap=this._senderMap.get(track),sender=submap?submap.get(stream):null;if(!sender)throw errCode(new Error("Cannot remove track that was never added."),"ERR_TRACK_NOT_ADDED");try{sender.removed=!0,this._pc.removeTrack(sender)}catch(err){"NS_ERROR_UNEXPECTED"===err.name?this._sendersAwaitingStable.push(sender):this.destroy(errCode(err,"ERR_REMOVE_TRACK"))}this._needsNegotiation()}removeStream(stream){this._debug("removeSenders()"),stream.getTracks().forEach(track=>{this.removeTrack(track,stream)})}_needsNegotiation(){this._debug("_needsNegotiation");this._batchedNegotiation||(this._batchedNegotiation=!0,queueMicrotask(()=>{this._batchedNegotiation=!1,this.initiator||!this._firstNegotiation?(this._debug("starting batched negotiation"),this.negotiate()):this._debug("non-initiator initial negotiation request discarded"),this._firstNegotiation=!1}))}negotiate(){this.initiator?this._isNegotiating?(this._queuedNegotiation=!0,this._debug("already negotiating, queueing")):(this._debug("start negotiation"),setTimeout(()=>{this._createOffer()},0)):this._isNegotiating?(this._queuedNegotiation=!0,this._debug("already negotiating, queueing")):(this._debug("requesting negotiation from initiator"),this.emit("signal",{type:"renegotiate",renegotiate:!0})),this._isNegotiating=!0}destroy(err){this._destroy(err,()=>{})}_destroy(err,cb){this.destroyed||this.destroying||(this.destroying=!0,this._debug("destroying (error: %s)",err&&(err.message||err)),queueMicrotask(()=>{if(this.destroyed=!0,this.destroying=!1,this._debug("destroy (error: %s)",err&&(err.message||err)),this.readable=this.writable=!1,this._readableState.ended||this.push(null),this._writableState.finished||this.end(),this._connected=!1,this._pcReady=!1,this._channelReady=!1,this._remoteTracks=null,this._remoteStreams=null,this._senderMap=null,clearInterval(this._closingInterval),this._closingInterval=null,clearInterval(this._interval),this._interval=null,this._chunk=null,this._cb=null,this._onFinishBound&&this.removeListener("finish",this._onFinishBound),this._onFinishBound=null,this._channel){try{this._channel.close()}catch(err){}this._channel.onmessage=null,this._channel.onopen=null,this._channel.onclose=null,this._channel.onerror=null}if(this._pc){try{this._pc.close()}catch(err){}this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ontrack=null,this._pc.ondatachannel=null}this._pc=null,this._channel=null,err&&this.emit("error",err),this.emit("close"),cb()}))}_setupData(event){if(!event.channel)return this.destroy(errCode(new Error("Data channel event is missing `channel` property"),"ERR_DATA_CHANNEL"));this._channel=event.channel,this._channel.binaryType="arraybuffer","number"==typeof this._channel.bufferedAmountLowThreshold&&(this._channel.bufferedAmountLowThreshold=MAX_BUFFERED_AMOUNT),this.channelName=this._channel.label,this._channel.onmessage=event=>{this._onChannelMessage(event)},this._channel.onbufferedamountlow=()=>{this._onChannelBufferedAmountLow()},this._channel.onopen=()=>{this._onChannelOpen()},this._channel.onclose=()=>{this._onChannelClose()},this._channel.onerror=err=>{this.destroy(errCode(err,"ERR_DATA_CHANNEL"))};let isClosing=!1;this._closingInterval=setInterval(()=>{this._channel&&"closing"===this._channel.readyState?(isClosing&&this._onChannelClose(),isClosing=!0):isClosing=!1},5000)}_read(){}_write(chunk,encoding,cb){if(this.destroyed)return cb(errCode(new Error("cannot write after peer is destroyed"),"ERR_DATA_CHANNEL"));if(this._connected){try{this.send(chunk)}catch(err){return this.destroy(errCode(err,"ERR_DATA_CHANNEL"))}this._channel.bufferedAmount>MAX_BUFFERED_AMOUNT?(this._debug("start backpressure: bufferedAmount %d",this._channel.bufferedAmount),this._cb=cb):cb(null)}else this._debug("write before connect"),this._chunk=chunk,this._cb=cb}_onFinish(){if(!this.destroyed){const destroySoon=()=>{setTimeout(()=>this.destroy(),1e3)};this._connected?destroySoon():this.once("connect",destroySoon)}}_startIceCompleteTimeout(){this.destroyed||this._iceCompleteTimer||(this._debug("started iceComplete timeout"),this._iceCompleteTimer=setTimeout(()=>{this._iceComplete||(this._iceComplete=!0,this._debug("iceComplete timeout completed"),this.emit("iceTimeout"),this.emit("_iceComplete"))},this.iceCompleteTimeout))}_createOffer(){this.destroyed||this._pc.createOffer(this.offerOptions).then(offer=>{if(this.destroyed)return;this.trickle||this.allowHalfTrickle||(offer.sdp=filterTrickle(offer.sdp)),offer.sdp=this.sdpTransform(offer.sdp);const sendOffer=()=>{if(!this.destroyed){const signal=this._pc.localDescription||offer;this._debug("signal"),this.emit("signal",{type:signal.type,sdp:signal.sdp})}};this._pc.setLocalDescription(offer).then(()=>{this._debug("createOffer success");this.destroyed||(this.trickle||this._iceComplete?sendOffer():this.once("_iceComplete",sendOffer))}).catch(err=>{this.destroy(errCode(err,"ERR_SET_LOCAL_DESCRIPTION"))})}).catch(err=>{this.destroy(errCode(err,"ERR_CREATE_OFFER"))})}_requestMissingTransceivers(){this._pc.getTransceivers&&this._pc.getTransceivers().forEach(transceiver=>{transceiver.mid||!transceiver.sender.track||transceiver.requested||(transceiver.requested=!0,this.addTransceiver(transceiver.sender.track.kind))})}_createAnswer(){this.destroyed||this._pc.createAnswer(this.answerOptions).then(answer=>{if(this.destroyed)return;this.trickle||this.allowHalfTrickle||(answer.sdp=filterTrickle(answer.sdp)),answer.sdp=this.sdpTransform(answer.sdp);const sendAnswer=()=>{if(!this.destroyed){const signal=this._pc.localDescription||answer;this._debug("signal"),this.emit("signal",{type:signal.type,sdp:signal.sdp}),this.initiator||this._requestMissingTransceivers()}};this._pc.setLocalDescription(answer).then(()=>{this.destroyed||(this.trickle||this._iceComplete?sendAnswer():this.once("_iceComplete",sendAnswer))}).catch(err=>{this.destroy(errCode(err,"ERR_SET_LOCAL_DESCRIPTION"))})}).catch(err=>{this.destroy(errCode(err,"ERR_CREATE_ANSWER"))})}_onConnectionStateChange(){this.destroyed||"failed"===this._pc.connectionState&&this.destroy(errCode(new Error("Connection failed."),"ERR_CONNECTION_FAILURE"))}_onIceStateChange(){if(this.destroyed)return;const iceConnectionState=this._pc.iceConnectionState,iceGatheringState=this._pc.iceGatheringState;this._debug("iceStateChange (connection: %s) (gathering: %s)",iceConnectionState,iceGatheringState),this.emit("iceStateChange",iceConnectionState,iceGatheringState),("connected"===iceConnectionState||"completed"===iceConnectionState)&&(this._pcReady=!0,this._maybeReady()),"failed"===iceConnectionState&&this.destroy(errCode(new Error("Ice connection failed."),"ERR_ICE_CONNECTION_FAILURE")),"closed"===iceConnectionState&&this.destroy(errCode(new Error("Ice connection closed."),"ERR_ICE_CONNECTION_CLOSED"))}getStats(cb){const flattenValues=report=>("[object Array]"===Object.prototype.toString.call(report.values)&&report.values.forEach(value=>{Object.assign(report,value)}),report);0===this._pc.getStats.length||this._isReactNativeWebrtc?this._pc.getStats().then(res=>{const reports=[];res.forEach(report=>{reports.push(flattenValues(report))}),cb(null,reports)},err=>cb(err)):0{if(this.destroyed)return;const reports=[];res.result().forEach(result=>{const report={};result.names().forEach(name=>{report[name]=result.stat(name)}),report.id=result.id,report.type=result.type,report.timestamp=result.timestamp,reports.push(flattenValues(report))}),cb(null,reports)},err=>cb(err)):cb(null,[])}_maybeReady(){if(this._debug("maybeReady pc %s channel %s",this._pcReady,this._channelReady),this._connected||this._connecting||!this._pcReady||!this._channelReady)return;this._connecting=!0;const findCandidatePair=()=>{this.destroyed||this.getStats((err,items)=>{if(this.destroyed)return;err&&(items=[]);const remoteCandidates={},localCandidates={},candidatePairs={};let foundSelectedCandidatePair=!1;items.forEach(item=>{("remotecandidate"===item.type||"remote-candidate"===item.type)&&(remoteCandidates[item.id]=item),("localcandidate"===item.type||"local-candidate"===item.type)&&(localCandidates[item.id]=item),("candidatepair"===item.type||"candidate-pair"===item.type)&&(candidatePairs[item.id]=item)});const setSelectedCandidatePair=selectedCandidatePair=>{foundSelectedCandidatePair=!0;let local=localCandidates[selectedCandidatePair.localCandidateId];local&&(local.ip||local.address)?(this.localAddress=local.ip||local.address,this.localPort=+local.port):local&&local.ipAddress?(this.localAddress=local.ipAddress,this.localPort=+local.portNumber):"string"==typeof selectedCandidatePair.googLocalAddress&&(local=selectedCandidatePair.googLocalAddress.split(":"),this.localAddress=local[0],this.localPort=+local[1]),this.localAddress&&(this.localFamily=this.localAddress.includes(":")?"IPv6":"IPv4");let remote=remoteCandidates[selectedCandidatePair.remoteCandidateId];remote&&(remote.ip||remote.address)?(this.remoteAddress=remote.ip||remote.address,this.remotePort=+remote.port):remote&&remote.ipAddress?(this.remoteAddress=remote.ipAddress,this.remotePort=+remote.portNumber):"string"==typeof selectedCandidatePair.googRemoteAddress&&(remote=selectedCandidatePair.googRemoteAddress.split(":"),this.remoteAddress=remote[0],this.remotePort=+remote[1]),this.remoteAddress&&(this.remoteFamily=this.remoteAddress.includes(":")?"IPv6":"IPv4"),this._debug("connect local: %s:%s remote: %s:%s",this.localAddress,this.localPort,this.remoteAddress,this.remotePort)};if(items.forEach(item=>{"transport"===item.type&&item.selectedCandidatePairId&&setSelectedCandidatePair(candidatePairs[item.selectedCandidatePairId]),("googCandidatePair"===item.type&&"true"===item.googActiveConnection||("candidatepair"===item.type||"candidate-pair"===item.type)&&item.selected)&&setSelectedCandidatePair(item)}),!foundSelectedCandidatePair&&(!Object.keys(candidatePairs).length||Object.keys(localCandidates).length))return void setTimeout(findCandidatePair,100);if(this._connecting=!1,this._connected=!0,this._chunk){try{this.send(this._chunk)}catch(err){return this.destroy(errCode(err,"ERR_DATA_CHANNEL"))}this._chunk=null,this._debug("sent chunk from \"write before connect\"");const cb=this._cb;this._cb=null,cb(null)}"number"!=typeof this._channel.bufferedAmountLowThreshold&&(this._interval=setInterval(()=>this._onInterval(),150),this._interval.unref&&this._interval.unref()),this._debug("connect"),this.emit("connect")})};findCandidatePair()}_onInterval(){this._cb&&this._channel&&!(this._channel.bufferedAmount>MAX_BUFFERED_AMOUNT)&&this._onChannelBufferedAmountLow()}_onSignalingStateChange(){this.destroyed||("stable"===this._pc.signalingState&&(this._isNegotiating=!1,this._debug("flushing sender queue",this._sendersAwaitingStable),this._sendersAwaitingStable.forEach(sender=>{this._pc.removeTrack(sender),this._queuedNegotiation=!0}),this._sendersAwaitingStable=[],this._queuedNegotiation?(this._debug("flushing negotiation queue"),this._queuedNegotiation=!1,this._needsNegotiation()):(this._debug("negotiated"),this.emit("negotiated"))),this._debug("signalingStateChange %s",this._pc.signalingState),this.emit("signalingStateChange",this._pc.signalingState))}_onIceCandidate(event){this.destroyed||(event.candidate&&this.trickle?this.emit("signal",{type:"candidate",candidate:{candidate:event.candidate.candidate,sdpMLineIndex:event.candidate.sdpMLineIndex,sdpMid:event.candidate.sdpMid}}):!event.candidate&&!this._iceComplete&&(this._iceComplete=!0,this.emit("_iceComplete")),event.candidate&&this._startIceCompleteTimeout())}_onChannelMessage(event){if(this.destroyed)return;let data=event.data;data instanceof ArrayBuffer&&(data=Buffer.from(data)),this.push(data)}_onChannelBufferedAmountLow(){if(!this.destroyed&&this._cb){this._debug("ending backpressure: bufferedAmount %d",this._channel.bufferedAmount);const cb=this._cb;this._cb=null,cb(null)}}_onChannelOpen(){this._connected||this.destroyed||(this._debug("on channel open"),this._channelReady=!0,this._maybeReady())}_onChannelClose(){this.destroyed||(this._debug("on channel close"),this.destroy())}_onTrack(event){this.destroyed||event.streams.forEach(eventStream=>{this._debug("on track"),this.emit("track",event.track,eventStream),this._remoteTracks.push({track:event.track,stream:eventStream});this._remoteStreams.some(remoteStream=>remoteStream.id===eventStream.id)||(this._remoteStreams.push(eventStream),queueMicrotask(()=>{this._debug("on stream"),this.emit("stream",eventStream)}))})}_debug(){const args=[].slice.call(arguments);args[0]="["+this._id+"] "+args[0],debug.apply(null,args)}}Peer.WEBRTC_SUPPORT=!!getBrowserRTC(),Peer.config={iceServers:[{urls:["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478"]}],sdpSemantics:"unified-plan"},Peer.channelConfig={},module.exports=Peer},{buffer:38,debug:69,"err-code":72,"get-browser-rtc":83,"queue-microtask":138,randombytes:140,"readable-stream":157}],169:[function(require,module){function sha1sync(buf){return rusha.digest(buf)}function sha1(buf,cb){return subtle?void("string"==typeof buf&&(buf=uint8array(buf)),subtle.digest({name:"sha-1"},buf).then(function(result){cb(hex(new Uint8Array(result)))},function(){cb(sha1sync(buf))})):void("undefined"==typeof window?queueMicrotask(()=>cb(sha1sync(buf))):rushaWorkerSha1(buf,function(err,hash){return err?void cb(sha1sync(buf)):void cb(hash)}))}function uint8array(s){for(var l=s.length,array=new Uint8Array(l),i=0;i>>4).toString(16)),chars.push((15&bite).toString(16));return chars.join("")}var Rusha=require("rusha"),rushaWorkerSha1=require("./rusha-worker-sha1"),rusha=new Rusha,scope="undefined"==typeof window?self:window,crypto=scope.crypto||scope.msCrypto||{},subtle=crypto.subtle||crypto.webkitSubtle;try{subtle.digest({name:"sha-1"},new Uint8Array).catch(function(){subtle=!1})}catch(err){subtle=!1}module.exports=sha1,module.exports.sync=sha1sync},{"./rusha-worker-sha1":170,rusha:164}],170:[function(require,module){function init(){worker=Rusha.createWorker(),nextTaskId=1,cbs={},worker.onmessage=function(e){var taskId=e.data.id,cb=cbs[taskId];delete cbs[taskId],null==e.data.error?cb(null,e.data.hash):cb(new Error("Rusha worker error: "+e.data.error))}}function sha1(buf,cb){worker||init(),cbs[nextTaskId]=cb,worker.postMessage({id:nextTaskId,data:buf}),nextTaskId+=1}var Rusha=require("rusha"),worker,nextTaskId,cbs;module.exports=sha1},{rusha:164}],171:[function(require,module){(function(Buffer){(function(){const debug=require("debug")("simple-websocket"),randombytes=require("randombytes"),stream=require("readable-stream"),queueMicrotask=require("queue-microtask"),ws=require("ws"),_WebSocket="function"==typeof ws?ws:WebSocket,MAX_BUFFERED_AMOUNT=65536;class Socket extends stream.Duplex{constructor(opts={}){if("string"==typeof opts&&(opts={url:opts}),opts=Object.assign({allowHalfOpen:!1},opts),super(opts),null==opts.url&&null==opts.socket)throw new Error("Missing required `url` or `socket` option");if(null!=opts.url&&null!=opts.socket)throw new Error("Must specify either `url` or `socket` option, not both");if(this._id=randombytes(4).toString("hex").slice(0,7),this._debug("new websocket: %o",opts),this.connected=!1,this.destroyed=!1,this._chunk=null,this._cb=null,this._interval=null,opts.socket)this.url=opts.socket.url,this._ws=opts.socket,this.connected=opts.socket.readyState===_WebSocket.OPEN;else{this.url=opts.url;try{this._ws="function"==typeof ws?new _WebSocket(opts.url,opts):new _WebSocket(opts.url)}catch(err){return void queueMicrotask(()=>this.destroy(err))}}this._ws.binaryType="arraybuffer",this._ws.onopen=()=>{this._onOpen()},this._ws.onmessage=event=>{this._onMessage(event)},this._ws.onclose=()=>{this._onClose()},this._ws.onerror=()=>{this.destroy(new Error("connection error to "+this.url))},this._onFinishBound=()=>{this._onFinish()},this.once("finish",this._onFinishBound)}send(chunk){this._ws.send(chunk)}destroy(err){this._destroy(err,()=>{})}_destroy(err,cb){if(!this.destroyed){if(this._debug("destroy (error: %s)",err&&(err.message||err)),this.readable=this.writable=!1,this._readableState.ended||this.push(null),this._writableState.finished||this.end(),this.connected=!1,this.destroyed=!0,clearInterval(this._interval),this._interval=null,this._chunk=null,this._cb=null,this._onFinishBound&&this.removeListener("finish",this._onFinishBound),this._onFinishBound=null,this._ws){const ws=this._ws,onClose=()=>{ws.onclose=null};if(ws.readyState===_WebSocket.CLOSED)onClose();else try{ws.onclose=onClose,ws.close()}catch(err){onClose()}ws.onopen=null,ws.onmessage=null,ws.onerror=()=>{}}if(this._ws=null,err){if("undefined"!=typeof DOMException&&err instanceof DOMException){const code=err.code;err=new Error(err.message),err.code=code}this.emit("error",err)}this.emit("close"),cb()}}_read(){}_write(chunk,encoding,cb){if(this.destroyed)return cb(new Error("cannot write after socket is destroyed"));if(this.connected){try{this.send(chunk)}catch(err){return this.destroy(err)}"function"!=typeof ws&&this._ws.bufferedAmount>MAX_BUFFERED_AMOUNT?(this._debug("start backpressure: bufferedAmount %d",this._ws.bufferedAmount),this._cb=cb):cb(null)}else this._debug("write before connect"),this._chunk=chunk,this._cb=cb}_onFinish(){if(!this.destroyed){const destroySoon=()=>{setTimeout(()=>this.destroy(),1e3)};this.connected?destroySoon():this.once("connect",destroySoon)}}_onMessage(event){if(this.destroyed)return;let data=event.data;data instanceof ArrayBuffer&&(data=Buffer.from(data)),this.push(data)}_onOpen(){if(!(this.connected||this.destroyed)){if(this.connected=!0,this._chunk){try{this.send(this._chunk)}catch(err){return this.destroy(err)}this._chunk=null,this._debug("sent chunk from \"write before connect\"");const cb=this._cb;this._cb=null,cb(null)}"function"!=typeof ws&&(this._interval=setInterval(()=>this._onInterval(),150),this._interval.unref&&this._interval.unref()),this._debug("connect"),this.emit("connect")}}_onInterval(){if(this._cb&&this._ws&&!(this._ws.bufferedAmount>MAX_BUFFERED_AMOUNT)){this._debug("ending backpressure: bufferedAmount %d",this._ws.bufferedAmount);const cb=this._cb;this._cb=null,cb(null)}}_onClose(){this.destroyed||(this._debug("on close"),this.destroy())}_debug(){const args=[].slice.call(arguments);args[0]="["+this._id+"] "+args[0],debug.apply(null,args)}}Socket.WEBSOCKET_SUPPORT=!!_WebSocket,module.exports=Socket}).call(this)}).call(this,require("buffer").Buffer)},{buffer:38,debug:69,"queue-microtask":138,randombytes:140,"readable-stream":157,ws:36}],172:[function(require,module){var tick=1,maxTick=65535,resolution=4,inc=function(){tick=tick+1&maxTick},timer;module.exports=function(seconds){timer||(timer=setInterval(inc,0|1e3/resolution),timer.unref&&timer.unref());var size=resolution*(seconds||5),buffer=[0],pointer=1,last=tick-1&maxTick;return function(delta){var dist=tick-last&maxTick;for(dist>size&&(dist=size),last=tick;dist--;)pointer===size&&(pointer=0),buffer[pointer]=buffer[0===pointer?size-1:pointer-1],pointer++;delta&&(buffer[pointer-1]+=delta);var top=buffer[pointer-1],btm=buffer.lengthself._pos){var newData=response.substr(self._pos);if("x-user-defined"===self._charset){for(var buffer=Buffer.alloc(newData.length),i=0;iself._pos&&(self.push(Buffer.from(new Uint8Array(reader.result.slice(self._pos)))),self._pos=reader.result.byteLength)},reader.onload=function(){self.push(null)},reader.readAsArrayBuffer(response);}self._xhr.readyState===rStates.DONE&&"ms-stream"!==self._mode&&self.push(null)}}).call(this)}).call(this,require("_process"),"undefined"==typeof global?"undefined"==typeof self?"undefined"==typeof window?{}:window:self:global,require("buffer").Buffer)},{"./capability":174,_process:132,buffer:38,inherits:97,"readable-stream":157}],177:[function(require,module){module.exports=async function(stream,mimeType){const blob=await getBlob(stream,mimeType),url=URL.createObjectURL(blob);return url};const getBlob=require("stream-to-blob")},{"stream-to-blob":178}],178:[function(require,module){/*! stream-to-blob. MIT License. Feross Aboukhadijeh */module.exports=function(stream,mimeType){if(null!=mimeType&&"string"!=typeof mimeType)throw new Error("Invalid mimetype, expected string.");return new Promise((resolve,reject)=>{const chunks=[];stream.on("data",chunk=>chunks.push(chunk)).once("end",()=>{const blob=null==mimeType?new Blob(chunks):new Blob(chunks,{type:mimeType});resolve(blob)}).once("error",reject)})}},{}],179:[function(require,module){(function(Buffer){(function(){/*! stream-with-known-length-to-buffer. MIT License. Feross Aboukhadijeh */var once=require("once");module.exports=function(stream,length,cb){cb=once(cb);var buf=Buffer.alloc(length),offset=0;stream.on("data",function(chunk){chunk.copy(buf,offset),offset+=chunk.length}).on("end",function(){cb(null,buf)}).on("error",cb)}}).call(this)}).call(this,require("buffer").Buffer)},{buffer:38,once:129}],180:[function(require,module){(function(Buffer){(function(){const addrToIPPort=require("addr-to-ip-port"),ipaddr=require("ipaddr.js");module.exports=addrs=>("string"==typeof addrs&&(addrs=[addrs]),Buffer.concat(addrs.map(addr=>{const s=addrToIPPort(addr);if(2!==s.length)throw new Error("invalid address format, expecting: 10.10.10.5:128");const ip=ipaddr.parse(s[0]),ipBuf=Buffer.from(ip.toByteArray()),port=s[1],portBuf=Buffer.allocUnsafe(2);return portBuf.writeUInt16BE(port,0),Buffer.concat([ipBuf,portBuf])}))),module.exports.multi=module.exports,module.exports.multi6=module.exports}).call(this)}).call(this,require("buffer").Buffer)},{"addr-to-ip-port":9,buffer:38,"ipaddr.js":181}],181:[function(require,module){(function(){var expandIPv6,ipaddr,ipv4Part,ipv4Regexes,ipv6Part,ipv6Regexes,matchCIDR,root,zoneIndex;ipaddr={},root=this,"undefined"!=typeof module&&null!==module&&module.exports?module.exports=ipaddr:root.ipaddr=ipaddr,matchCIDR=function(first,second,partSize,cidrBits){var part,shift;if(first.length!==second.length)throw new Error("ipaddr: cannot match CIDR for objects with different lengths");for(part=0;0shift&&(shift=0),first[part]>>shift!=second[part]>>shift)return!1;cidrBits-=partSize,part+=1}return!0},ipaddr.subnetMatch=function(address,rangeList,defaultName){var k,len,rangeName,rangeSubnets,subnet;for(rangeName in null==defaultName&&(defaultName="unicast"),rangeList)for(rangeSubnets=rangeList[rangeName],rangeSubnets[0]&&!(rangeSubnets[0]instanceof Array)&&(rangeSubnets=[rangeSubnets]),(k=0,len=rangeSubnets.length);k=octet))throw new Error("ipaddr: ipv4 octet should fit in 8 bits");this.octets=octets}return IPv4.prototype.kind=function(){return"ipv4"},IPv4.prototype.toString=function(){return this.octets.join(".")},IPv4.prototype.toNormalizedString=function(){return this.toString()},IPv4.prototype.toByteArray=function(){return this.octets.slice(0)},IPv4.prototype.match=function(other,cidrRange){var ref;if(void 0===cidrRange&&(ref=other,other=ref[0],cidrRange=ref[1]),"ipv4"!==other.kind())throw new Error("ipaddr: cannot match ipv4 address with non-ipv4 one");return matchCIDR(this.octets,other.octets,8,cidrRange)},IPv4.prototype.SpecialRanges={unspecified:[[new IPv4([0,0,0,0]),8]],broadcast:[[new IPv4([255,255,255,255]),32]],multicast:[[new IPv4([224,0,0,0]),4]],linkLocal:[[new IPv4([169,254,0,0]),16]],loopback:[[new IPv4([127,0,0,0]),8]],carrierGradeNat:[[new IPv4([100,64,0,0]),10]],private:[[new IPv4([10,0,0,0]),8],[new IPv4([172,16,0,0]),12],[new IPv4([192,168,0,0]),16]],reserved:[[new IPv4([192,0,0,0]),24],[new IPv4([192,0,2,0]),24],[new IPv4([192,88,99,0]),24],[new IPv4([198,51,100,0]),24],[new IPv4([203,0,113,0]),24],[new IPv4([240,0,0,0]),4]]},IPv4.prototype.range=function(){return ipaddr.subnetMatch(this,this.SpecialRanges)},IPv4.prototype.toIPv4MappedAddress=function(){return ipaddr.IPv6.parse("::ffff:"+this.toString())},IPv4.prototype.prefixLengthFromSubnetMask=function(){var cidr,i,k,octet,stop,zeros,zerotable;for(zerotable={0:8,128:7,192:6,224:5,240:4,248:3,252:2,254:1,255:0},cidr=0,stop=!1,i=k=3;0<=k;i=k+=-1)if(octet=this.octets[i],octet in zerotable){if(zeros=zerotable[octet],stop&&0!==zeros)return null;8!==zeros&&(stop=!0),cidr+=zeros}else return null;return 32-cidr},IPv4}(),ipv4Part="(0?\\d+|0x[a-f0-9]+)",ipv4Regexes={fourOctet:new RegExp("^"+ipv4Part+"\\."+ipv4Part+"\\."+ipv4Part+"\\."+ipv4Part+"$","i"),longValue:new RegExp("^"+ipv4Part+"$","i")},ipaddr.IPv4.parser=function(string){var match,parseIntAuto,part,shift,value;if(parseIntAuto=function(string){return"0"===string[0]&&"x"!==string[1]?parseInt(string,8):parseInt(string)},match=string.match(ipv4Regexes.fourOctet))return function(){var k,len,ref,results;for(ref=match.slice(1,6),results=[],(k=0,len=ref.length);kvalue)throw new Error("ipaddr: address outside defined range");return function(){var k,results;for(results=[],shift=k=0;24>=k;shift=k+=8)results.push(255&value>>shift);return results}().reverse()}return null},ipaddr.IPv6=function(){function IPv6(parts,zoneId){var i,k,l,len,part,ref;if(16===parts.length)for(this.parts=[],i=k=0;14>=k;i=k+=2)this.parts.push(parts[i]<<8|parts[i+1]);else if(8===parts.length)this.parts=parts;else throw new Error("ipaddr: ipv6 part count should be 8 or 16");for(ref=this.parts,l=0,len=ref.length;l=part))throw new Error("ipaddr: ipv6 part should fit in 16 bits");zoneId&&(this.zoneId=zoneId)}return IPv6.prototype.kind=function(){return"ipv6"},IPv6.prototype.toString=function(){return this.toNormalizedString().replace(/((^|:)(0(:|$))+)/,"::")},IPv6.prototype.toRFC5952String=function(){var bestMatchIndex,bestMatchLength,match,regex,string;for(regex=/((^|:)(0(:|$)){2,})/g,string=this.toNormalizedString(),bestMatchIndex=0,bestMatchLength=-1;match=regex.exec(string);)match[0].length>bestMatchLength&&(bestMatchIndex=match.index,bestMatchLength=match[0].length);return 0>bestMatchLength?string:string.substring(0,bestMatchIndex)+"::"+string.substring(bestMatchIndex+bestMatchLength)},IPv6.prototype.toByteArray=function(){var bytes,k,len,part,ref;for(bytes=[],ref=this.parts,(k=0,len=ref.length);k>8),bytes.push(255&part);return bytes},IPv6.prototype.toNormalizedString=function(){var addr,part,suffix;return addr=function(){var k,len,ref,results;for(ref=this.parts,results=[],(k=0,len=ref.length);k>8,255&high,low>>8,255&low])},IPv6.prototype.prefixLengthFromSubnetMask=function(){var cidr,i,k,part,stop,zeros,zerotable;for(zerotable={0:16,32768:15,49152:14,57344:13,61440:12,63488:11,64512:10,65024:9,65280:8,65408:7,65472:6,65504:5,65520:4,65528:3,65532:2,65534:1,65535:0},cidr=0,stop=!1,i=k=7;0<=k;i=k+=-1)if(part=this.parts[i],part in zerotable){if(zeros=zerotable[part],stop&&0!==zeros)return null;16!==zeros&&(stop=!0),cidr+=zeros}else return null;return 128-cidr},IPv6}(),ipv6Part="(?:[0-9a-f]+::?)+",zoneIndex="%[0-9a-z]{1,}",ipv6Regexes={zoneIndex:new RegExp(zoneIndex,"i"),native:new RegExp("^(::)?("+ipv6Part+")?([0-9a-f]+)?(::)?("+zoneIndex+")?$","i"),transitional:new RegExp("^((?:"+ipv6Part+")|(?:::)(?:"+ipv6Part+")?)"+(ipv4Part+"\\."+ipv4Part+"\\."+ipv4Part+"\\."+ipv4Part)+("("+zoneIndex+")?$"),"i")},expandIPv6=function(string,parts){var colonCount,lastColon,part,replacement,replacementCount,zoneId;if(string.indexOf("::")!==string.lastIndexOf("::"))return null;for(zoneId=(string.match(ipv6Regexes.zoneIndex)||[])[0],zoneId&&(zoneId=zoneId.substring(1),string=string.replace(/%.+$/,"")),colonCount=0,lastColon=-1;0<=(lastColon=string.indexOf(":",lastColon+1));)colonCount++;if("::"===string.substr(0,2)&&colonCount--,"::"===string.substr(-2,2)&&colonCount--,colonCount>parts)return null;for(replacementCount=parts-colonCount,replacement=":";replacementCount--;)replacement+="0:";return string=string.replace("::",replacement),":"===string[0]&&(string=string.slice(1)),":"===string[string.length-1]&&(string=string.slice(0,-1)),parts=function(){var k,len,ref,results;for(ref=string.split(":"),results=[],(k=0,len=ref.length);k=octet))return null;return addr.parts.push(octets[0]<<8|octets[1]),addr.parts.push(octets[2]<<8|octets[3]),{parts:addr.parts,zoneId:addr.zoneId}}return null},ipaddr.IPv4.isIPv4=ipaddr.IPv6.isIPv6=function(string){return null!==this.parser(string)},ipaddr.IPv4.isValid=function(string){var e;try{return new this(this.parser(string)),!0}catch(error1){return e=error1,!1}},ipaddr.IPv4.isValidFourPartDecimal=function(string){return!!(ipaddr.IPv4.isValid(string)&&string.match(/^(0|[1-9]\d*)(\.(0|[1-9]\d*)){3}$/))},ipaddr.IPv6.isValid=function(string){var addr,e;if("string"==typeof string&&-1===string.indexOf(":"))return!1;try{return addr=this.parser(string),new this(addr.parts,addr.zoneId),!0}catch(error1){return e=error1,!1}},ipaddr.IPv4.parse=function(string){var parts;if(parts=this.parser(string),null===parts)throw new Error("ipaddr: string is not formatted like ip address");return new this(parts)},ipaddr.IPv6.parse=function(string){var addr;if(addr=this.parser(string),null===addr.parts)throw new Error("ipaddr: string is not formatted like ip address");return new this(addr.parts,addr.zoneId)},ipaddr.IPv4.parseCIDR=function(string){var maskLength,match,parsed;if((match=string.match(/^(.+)\/(\d+)$/))&&(maskLength=parseInt(match[2]),0<=maskLength&&32>=maskLength))return parsed=[this.parse(match[1]),maskLength],Object.defineProperty(parsed,"toString",{value:function(){return this.join("/")}}),parsed;throw new Error("ipaddr: string is not formatted like an IPv4 CIDR range")},ipaddr.IPv4.subnetMaskFromPrefixLength=function(prefix){var filledOctetCount,j,octets;if(prefix=parseInt(prefix),0>prefix||32filledOctetCount&&(octets[filledOctetCount]=_Mathpow(2,prefix%8)-1<<8-prefix%8),new this(octets)},ipaddr.IPv4.broadcastAddressFromCIDR=function(string){var cidr,error,i,ipInterfaceOctets,octets,subnetMaskOctets;try{for(cidr=this.parseCIDR(string),ipInterfaceOctets=cidr[0].toByteArray(),subnetMaskOctets=this.subnetMaskFromPrefixLength(cidr[1]).toByteArray(),octets=[],i=0;4>i;)octets.push(parseInt(ipInterfaceOctets[i],10)|255^parseInt(subnetMaskOctets[i],10)),i++;return new this(octets)}catch(error1){throw error=error1,new Error("ipaddr: the address does not have IPv4 CIDR format")}},ipaddr.IPv4.networkAddressFromCIDR=function(string){var cidr,error,i,ipInterfaceOctets,octets,subnetMaskOctets;try{for(cidr=this.parseCIDR(string),ipInterfaceOctets=cidr[0].toByteArray(),subnetMaskOctets=this.subnetMaskFromPrefixLength(cidr[1]).toByteArray(),octets=[],i=0;4>i;)octets.push(parseInt(ipInterfaceOctets[i],10)&parseInt(subnetMaskOctets[i],10)),i++;return new this(octets)}catch(error1){throw error=error1,new Error("ipaddr: the address does not have IPv4 CIDR format")}},ipaddr.IPv6.parseCIDR=function(string){var maskLength,match,parsed;if((match=string.match(/^(.+)\/(\d+)$/))&&(maskLength=parseInt(match[2]),0<=maskLength&&128>=maskLength))return parsed=[this.parse(match[1]),maskLength],Object.defineProperty(parsed,"toString",{value:function(){return this.join("/")}}),parsed;throw new Error("ipaddr: string is not formatted like an IPv6 CIDR range")},ipaddr.isValid=function(string){return ipaddr.IPv6.isValid(string)||ipaddr.IPv4.isValid(string)},ipaddr.parse=function(string){if(ipaddr.IPv6.isValid(string))return ipaddr.IPv6.parse(string);if(ipaddr.IPv4.isValid(string))return ipaddr.IPv4.parse(string);throw new Error("ipaddr: the address has neither IPv6 nor IPv4 format")},ipaddr.parseCIDR=function(string){var e;try{return ipaddr.IPv6.parseCIDR(string)}catch(error1){e=error1;try{return ipaddr.IPv4.parseCIDR(string)}catch(error1){throw e=error1,new Error("ipaddr: the address has neither IPv6 nor IPv4 CIDR format")}}},ipaddr.fromByteArray=function(bytes){var length;if(length=bytes.length,4===length)return new ipaddr.IPv4(bytes);if(16===length)return new ipaddr.IPv6(bytes);throw new Error("ipaddr: the binary input is neither an IPv6 nor IPv4 address")},ipaddr.process=function(string){var addr;return addr=this.parse(string),"ipv6"===addr.kind()&&addr.isIPv4MappedAddress()?addr.toIPv4Address():addr}}).call(this)},{}],182:[function(require,module,exports){'use strict';function _normalizeEncoding(enc){if(!enc)return"utf8";for(var retried;;)switch(enc){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return enc;default:if(retried)return;enc=(""+enc).toLowerCase(),retried=!0;}}function normalizeEncoding(enc){var nenc=_normalizeEncoding(enc);if("string"!=typeof nenc&&(Buffer.isEncoding===isEncoding||!isEncoding(enc)))throw new Error("Unknown encoding: "+enc);return nenc||enc}function StringDecoder(encoding){this.encoding=normalizeEncoding(encoding);var nb;switch(this.encoding){case"utf16le":this.text=utf16Text,this.end=utf16End,nb=4;break;case"utf8":this.fillLast=utf8FillLast,nb=4;break;case"base64":this.text=base64Text,this.end=base64End,nb=3;break;default:return this.write=simpleWrite,void(this.end=simpleEnd);}this.lastNeed=0,this.lastTotal=0,this.lastChar=Buffer.allocUnsafe(nb)}function utf8CheckByte(byte){if(127>=byte)return 0;return 6==byte>>5?2:14==byte>>4?3:30==byte>>3?4:2==byte>>6?-1:-2}function utf8CheckIncomplete(self,buf,i){var j=buf.length-1;if(j=c)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=buf[buf.length-2],this.lastChar[1]=buf[buf.length-1],r.slice(0,-1)}return r}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=buf[buf.length-1],buf.toString("utf16le",i,buf.length-1)}function utf16End(buf){var r=buf&&buf.length?this.write(buf):"";if(this.lastNeed){var end=this.lastTotal-this.lastNeed;return r+this.lastChar.toString("utf16le",0,end)}return r}function base64Text(buf,i){var n=(buf.length-i)%3;return 0==n?buf.toString("base64",i):(this.lastNeed=3-n,this.lastTotal=3,1==n?this.lastChar[0]=buf[buf.length-1]:(this.lastChar[0]=buf[buf.length-2],this.lastChar[1]=buf[buf.length-1]),buf.toString("base64",i,buf.length-n))}function base64End(buf){var r=buf&&buf.length?this.write(buf):"";return this.lastNeed?r+this.lastChar.toString("base64",0,3-this.lastNeed):r}function simpleWrite(buf){return buf.toString(this.encoding)}function simpleEnd(buf){return buf&&buf.length?this.write(buf):""}var Buffer=require("safe-buffer").Buffer,isEncoding=Buffer.isEncoding||function(encoding){switch(encoding=""+encoding,encoding&&encoding.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1;}};exports.StringDecoder=StringDecoder,StringDecoder.prototype.write=function(buf){if(0===buf.length)return"";var r,i;if(this.lastNeed){if(r=this.fillLast(buf),void 0===r)return"";i=this.lastNeed,this.lastNeed=0}else i=0;return i>shiftIndex,shiftIndex=(shiftIndex+5)%8,digit=digit<>8-shiftIndex,i++):(digit=31¤t>>8-(shiftIndex+5),shiftIndex=(shiftIndex+5)%8,0===shiftIndex&&i++),encoded[j]="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567".charCodeAt(digit),j++}for(i=j;i=shiftIndex?(shiftIndex=(shiftIndex+5)%8,0===shiftIndex?(plainChar|=plainDigit,decoded[plainPos]=plainChar,plainPos++,plainChar=0):plainChar|=255&plainDigit<<8-shiftIndex):(shiftIndex=(shiftIndex+5)%8,plainChar|=255&plainDigit>>>shiftIndex,decoded[plainPos]=plainChar,plainPos++,plainChar=255&plainDigit<<8-shiftIndex);else throw new Error("Invalid input - it is not base32 encoded string")}return decoded.slice(0,plainPos)}}).call(this)}).call(this,require("buffer").Buffer)},{buffer:38}],185:[function(require,module,exports){(function(setImmediate,clearImmediate){(function(){function Timeout(id,clearFn){this._id=id,this._clearFn=clearFn}var nextTick=require("process/browser.js").nextTick,apply=Function.prototype.apply,slice=Array.prototype.slice,immediateIds={},nextImmediateId=0;exports.setTimeout=function(){return new Timeout(apply.call(setTimeout,window,arguments),clearTimeout)},exports.setInterval=function(){return new Timeout(apply.call(setInterval,window,arguments),clearInterval)},exports.clearTimeout=exports.clearInterval=function(timeout){timeout.close()},Timeout.prototype.unref=Timeout.prototype.ref=function(){},Timeout.prototype.close=function(){this._clearFn.call(window,this._id)},exports.enroll=function(item,msecs){clearTimeout(item._idleTimeoutId),item._idleTimeout=msecs},exports.unenroll=function(item){clearTimeout(item._idleTimeoutId),item._idleTimeout=-1},exports._unrefActive=exports.active=function(item){clearTimeout(item._idleTimeoutId);var msecs=item._idleTimeout;0<=msecs&&(item._idleTimeoutId=setTimeout(function(){item._onTimeout&&item._onTimeout()},msecs))},exports.setImmediate="function"==typeof setImmediate?setImmediate:function(fn){var id=nextImmediateId++,args=!(2>arguments.length)&&slice.call(arguments,1);return immediateIds[id]=!0,nextTick(function(){immediateIds[id]&&(args?fn.apply(null,args):fn.call(null),exports.clearImmediate(id))}),id},exports.clearImmediate="function"==typeof clearImmediate?clearImmediate:function(id){delete immediateIds[id]}}).call(this)}).call(this,require("timers").setImmediate,require("timers").clearImmediate)},{"process/browser.js":132,timers:185}],186:[function(require,module){var Buffer=require("buffer").Buffer;module.exports=function(buf){if(buf instanceof Uint8Array){if(0===buf.byteOffset&&buf.byteLength===buf.buffer.byteLength)return buf.buffer;if("function"==typeof buf.buffer.slice)return buf.buffer.slice(buf.byteOffset,buf.byteOffset+buf.byteLength)}if(Buffer.isBuffer(buf)){for(var arrayCopy=new Uint8Array(buf.length),len=buf.length,i=0;i */const debug=require("debug")("torrent-discovery"),DHT=require("bittorrent-dht/client"),EventEmitter=require("events").EventEmitter,parallel=require("run-parallel"),Tracker=require("bittorrent-tracker/client"),LSD=require("bittorrent-lsd");module.exports=class Discovery extends EventEmitter{constructor(opts){if(super(),!opts.peerId)throw new Error("Option `peerId` is required");if(!opts.infoHash)throw new Error("Option `infoHash` is required");if(!process.browser&&!opts.port)throw new Error("Option `port` is required");this.peerId="string"==typeof opts.peerId?opts.peerId:opts.peerId.toString("hex"),this.infoHash="string"==typeof opts.infoHash?opts.infoHash.toLowerCase():opts.infoHash.toString("hex"),this._port=opts.port,this._userAgent=opts.userAgent,this.destroyed=!1,this._announce=opts.announce||[],this._intervalMs=opts.intervalMs||900000,this._trackerOpts=null,this._dhtAnnouncing=!1,this._dhtTimeout=!1,this._internalDHT=!1,this._onWarning=err=>{this.emit("warning",err)},this._onError=err=>{this.emit("error",err)},this._onDHTPeer=(peer,infoHash)=>{infoHash.toString("hex")!==this.infoHash||this.emit("peer",`${peer.host}:${peer.port}`,"dht")},this._onTrackerPeer=peer=>{this.emit("peer",peer,"tracker")},this._onTrackerAnnounce=()=>{this.emit("trackerAnnounce")},this._onLSDPeer=peer=>{this.emit("peer",peer,"lsd")};const createDHT=(port,opts)=>{const dht=new DHT(opts);return dht.on("warning",this._onWarning),dht.on("error",this._onError),dht.listen(port),this._internalDHT=!0,dht};!1===opts.tracker?this.tracker=null:opts.tracker&&"object"==typeof opts.tracker?(this._trackerOpts=Object.assign({},opts.tracker),this.tracker=this._createTracker()):this.tracker=this._createTracker(),this.dht=!1===opts.dht||"function"!=typeof DHT?null:opts.dht&&"function"==typeof opts.dht.addNode?opts.dht:opts.dht&&"object"==typeof opts.dht?createDHT(opts.dhtPort,opts.dht):createDHT(opts.dhtPort),this.dht&&(this.dht.on("peer",this._onDHTPeer),this._dhtAnnounce()),this.lsd=!1===opts.lsd||"function"!=typeof LSD?null:this._createLSD()}updatePort(port){port===this._port||(this._port=port,this.dht&&this._dhtAnnounce(),this.tracker&&(this.tracker.stop(),this.tracker.destroy(()=>{this.tracker=this._createTracker()})))}complete(opts){this.tracker&&this.tracker.complete(opts)}destroy(cb){if(!this.destroyed){this.destroyed=!0,clearTimeout(this._dhtTimeout);const tasks=[];this.tracker&&(this.tracker.stop(),this.tracker.removeListener("warning",this._onWarning),this.tracker.removeListener("error",this._onError),this.tracker.removeListener("peer",this._onTrackerPeer),this.tracker.removeListener("update",this._onTrackerAnnounce),tasks.push(cb=>{this.tracker.destroy(cb)})),this.dht&&this.dht.removeListener("peer",this._onDHTPeer),this._internalDHT&&(this.dht.removeListener("warning",this._onWarning),this.dht.removeListener("error",this._onError),tasks.push(cb=>{this.dht.destroy(cb)})),this.lsd&&(this.lsd.removeListener("warning",this._onWarning),this.lsd.removeListener("error",this._onError),this.lsd.removeListener("peer",this._onLSDPeer),tasks.push(cb=>{this.lsd.destroy(cb)})),parallel(tasks,cb),this.dht=null,this.tracker=null,this.lsd=null,this._announce=null}}_createTracker(){const opts=Object.assign({},this._trackerOpts,{infoHash:this.infoHash,announce:this._announce,peerId:this.peerId,port:this._port,userAgent:this._userAgent}),tracker=new Tracker(opts);return tracker.on("warning",this._onWarning),tracker.on("error",this._onError),tracker.on("peer",this._onTrackerPeer),tracker.on("update",this._onTrackerAnnounce),tracker.setInterval(this._intervalMs),tracker.start(),tracker}_dhtAnnounce(){this._dhtAnnouncing||(debug("dht announce"),this._dhtAnnouncing=!0,clearTimeout(this._dhtTimeout),this.dht.announce(this.infoHash,this._port,err=>{this._dhtAnnouncing=!1,debug("dht announce complete"),err&&this.emit("warning",err),this.emit("dhtAnnounce"),this.destroyed||(this._dhtTimeout=setTimeout(()=>{this._dhtAnnounce()},this._intervalMs+_Mathfloor(Math.random()*this._intervalMs/5)),this._dhtTimeout.unref&&this._dhtTimeout.unref())}))}_createLSD(){const opts=Object.assign({},{infoHash:this.infoHash,peerId:this.peerId,port:this._port}),lsd=new LSD(opts);return lsd.on("warning",this._onWarning),lsd.on("error",this._onError),lsd.on("peer",this._onLSDPeer),lsd.start(),lsd}}}).call(this)}).call(this,require("_process"))},{_process:132,"bittorrent-dht/client":23,"bittorrent-lsd":24,"bittorrent-tracker/client":26,debug:69,events:39,"run-parallel":162}],188:[function(require,module){(function(Buffer){(function(){const BLOCK_LENGTH=16384;class Piece{constructor(length){this.length=length,this.missing=length,this.sources=null,this._chunks=_Mathceil(length/BLOCK_LENGTH),this._remainder=length%BLOCK_LENGTH||BLOCK_LENGTH,this._buffered=0,this._buffer=null,this._cancellations=null,this._reservations=0,this._flushed=!1}chunkLength(i){return i===this._chunks-1?this._remainder:BLOCK_LENGTH}chunkLengthRemaining(i){return this.length-i*BLOCK_LENGTH}chunkOffset(i){return i*BLOCK_LENGTH}reserve(){return this.init()?this._cancellations.length?this._cancellations.pop():this._reservations=arr.length||0>i)){var last=arr.pop();if(i","\"","`"," ","\r","\n","\t"]),autoEscape=["'"].concat(unwise),nonHostChars=["%","/","?",";","#"].concat(autoEscape),hostEndingChars=["/","?","#"],hostnamePartPattern=/^[+a-z0-9A-Z_-]{0,63}$/,unsafeProtocol={javascript:!0,"javascript:":!0},hostlessProtocol={javascript:!0,"javascript:":!0},slashedProtocol={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},querystring=require("querystring");Url.prototype.parse=function(url,parseQueryString,slashesDenoteHost){if(!util.isString(url))throw new TypeError("Parameter 'url' must be a string, not "+typeof url);var queryIndex=url.indexOf("?"),splitter=-1!==queryIndex&&queryIndexrelPath.length&&relPath.unshift(""),result.pathname=relPath.join("/")}else result.pathname=relative.pathname;if(result.search=relative.search,result.query=relative.query,result.host=relative.host||"",result.auth=relative.auth,result.hostname=relative.hostname||relative.host,result.port=relative.port,result.pathname||result.search){var p=result.pathname||"",s=result.search||"";result.path=p+s}return result.slashes=result.slashes||relative.slashes,result.href=result.format(),result}var isSourceAbs=result.pathname&&"/"===result.pathname.charAt(0),isRelAbs=relative.host||relative.pathname&&"/"===relative.pathname.charAt(0),mustEndAbs=isRelAbs||isSourceAbs||result.host&&relative.pathname,removeAllDots=mustEndAbs,srcPath=result.pathname&&result.pathname.split("/")||[],relPath=relative.pathname&&relative.pathname.split("/")||[],psychotic=result.protocol&&!slashedProtocol[result.protocol];if(psychotic&&(result.hostname="",result.port=null,result.host&&(""===srcPath[0]?srcPath[0]=result.host:srcPath.unshift(result.host)),result.host="",relative.protocol&&(relative.hostname=null,relative.port=null,relative.host&&(""===relPath[0]?relPath[0]=relative.host:relPath.unshift(relative.host)),relative.host=null),mustEndAbs=mustEndAbs&&(""===relPath[0]||""===srcPath[0])),isRelAbs)result.host=relative.host||""===relative.host?relative.host:result.host,result.hostname=relative.hostname||""===relative.hostname?relative.hostname:result.hostname,result.search=relative.search,result.query=relative.query,srcPath=relPath;else if(relPath.length)srcPath||(srcPath=[]),srcPath.pop(),srcPath=srcPath.concat(relPath),result.search=relative.search,result.query=relative.query;else if(!util.isNullOrUndefined(relative.search)){if(psychotic){result.hostname=result.host=srcPath.shift();var authInHost=!!(result.host&&0 */const{EventEmitter}=require("events"),bencode=require("bencode"),BitField=require("bitfield").default,debug=require("debug")("ut_metadata"),sha1=require("simple-sha1"),BITFIELD_GROW=1E3,PIECE_LENGTH=16384;module.exports=metadata=>{class utMetadata extends EventEmitter{constructor(wire){super(),this._wire=wire,this._fetching=!1,this._metadataComplete=!1,this._metadataSize=null,this._remainingRejects=null,this._bitfield=new BitField(0,{grow:BITFIELD_GROW}),Buffer.isBuffer(metadata)&&this.setMetadata(metadata)}onHandshake(infoHash){this._infoHash=infoHash}onExtendedHandshake(handshake){return handshake.m&&handshake.m.ut_metadata?handshake.metadata_size?"number"!=typeof handshake.metadata_size||1E7=handshake.metadata_size?this.emit("warning",new Error("Peer gave invalid metadata size")):void(this._metadataSize=handshake.metadata_size,this._numPieces=_Mathceil(this._metadataSize/PIECE_LENGTH),this._remainingRejects=2*this._numPieces,this._requestPieces()):this.emit("warning",new Error("Peer does not have metadata")):this.emit("warning",new Error("Peer does not support ut_metadata"))}onMessage(buf){let dict,trailer;try{const str=buf.toString(),trailerIndex=str.indexOf("ee")+2;dict=bencode.decode(str.substring(0,trailerIndex)),trailer=buf.slice(trailerIndex)}catch(err){return}switch(dict.msg_type){case 0:this._onRequest(dict.piece);break;case 1:this._onData(dict.piece,trailer,dict.total_size);break;case 2:this._onReject(dict.piece);}}fetch(){this._metadataComplete||(this._fetching=!0,this._metadataSize&&this._requestPieces())}cancel(){this._fetching=!1}setMetadata(metadata){if(this._metadataComplete)return!0;debug("set metadata");try{const info=bencode.decode(metadata).info;info&&(metadata=bencode.encode(info))}catch(err){}return!(this._infoHash&&this._infoHash!==sha1.sync(metadata))&&(this.cancel(),this.metadata=metadata,this._metadataComplete=!0,this._metadataSize=this.metadata.length,this._wire.extendedHandshake.metadata_size=this._metadataSize,this.emit("metadata",bencode.encode({info:bencode.decode(this.metadata)})),!0)}_send(dict,trailer){let buf=bencode.encode(dict);Buffer.isBuffer(trailer)&&(buf=Buffer.concat([buf,trailer])),this._wire.extended("ut_metadata",buf)}_request(piece){this._send({msg_type:0,piece})}_data(piece,buf,totalSize){const msg={msg_type:1,piece};"number"==typeof totalSize&&(msg.total_size=totalSize),this._send(msg,buf)}_reject(piece){this._send({msg_type:2,piece})}_onRequest(piece){if(!this._metadataComplete)return void this._reject(piece);const start=piece*PIECE_LENGTH;let end=start+PIECE_LENGTH;end>this._metadataSize&&(end=this._metadataSize);const buf=this.metadata.slice(start,end);this._data(piece,buf,this._metadataSize)}_onData(piece,buf){buf.length>PIECE_LENGTH||!this._fetching||(buf.copy(this.metadata,piece*PIECE_LENGTH),this._bitfield.set(piece),this._checkDone())}_onReject(piece){0 */var EventEmitter=require("events").EventEmitter,compact2string=require("compact2string"),string2compact=require("string2compact"),bencode=require("bencode"),PEX_MAX_PEERS=50;module.exports=()=>{class utPex extends EventEmitter{constructor(wire){super(),this._wire=wire,this._intervalId=null,this.reset()}start(){clearInterval(this._intervalId),this._intervalId=setInterval(()=>this._sendMessage(),65e3),this._intervalId.unref&&this._intervalId.unref()}stop(){clearInterval(this._intervalId),this._intervalId=null}reset(){this._remoteAddedPeers={},this._remoteDroppedPeers={},this._localAddedPeers={},this._localDroppedPeers={},this.stop()}addPeer(peer){0>peer.indexOf(":")||peer in this._remoteAddedPeers||(peer in this._localDroppedPeers&&delete this._localDroppedPeers[peer],this._localAddedPeers[peer]=!0)}dropPeer(peer){0>peer.indexOf(":")||peer in this._remoteDroppedPeers||(peer in this._localAddedPeers&&delete this._localAddedPeers[peer],this._localDroppedPeers[peer]=!0)}onExtendedHandshake(handshake){if(!handshake.m||!handshake.m.ut_pex)return this.emit("warning",new Error("Peer does not support ut_pex"))}onMessage(buf){var message;try{message=bencode.decode(buf)}catch(err){return}if(message.added)try{compact2string.multi(message.added).forEach(peer=>{delete this._remoteDroppedPeers[peer],peer in this._remoteAddedPeers||(this._remoteAddedPeers[peer]=!0,this.emit("peer",peer))})}catch(err){return}if(message.dropped)try{compact2string.multi(message.dropped).forEach(peer=>{delete this._remoteAddedPeers[peer],peer in this._remoteDroppedPeers||(this._remoteDroppedPeers[peer]=!0,this.emit("dropped",peer))})}catch(err){}}_sendMessage(){var localAdded=Object.keys(this._localAddedPeers).slice(0,PEX_MAX_PEERS),localDropped=Object.keys(this._localDroppedPeers).slice(0,PEX_MAX_PEERS),added=Buffer.concat(localAdded.map(string2compact)),dropped=Buffer.concat(localDropped.map(string2compact)),addedFlags=Buffer.concat(localAdded.map(()=>Buffer.from([0])));localAdded.forEach(peer=>delete this._localAddedPeers[peer]),localDropped.forEach(peer=>delete this._localDroppedPeers[peer]),this._wire.extended("ut_pex",{added:added,"added.f":addedFlags,dropped:dropped,added6:Buffer.alloc(0),"added6.f":Buffer.alloc(0),dropped6:Buffer.alloc(0)})}}return utPex.prototype.name="ut_pex",utPex}}).call(this)}).call(this,require("buffer").Buffer)},{bencode:19,buffer:38,compact2string:67,events:39,string2compact:180}],196:[function(require,module){(function(global){(function(){function config(name){try{if(!global.localStorage)return!1}catch(_){return!1}var val=global.localStorage[name];return null!=val&&"true"===(val+"").toLowerCase()}module.exports=function(fn,msg){function deprecated(){if(!warned){if(config("throwDeprecation"))throw new Error(msg);else config("traceDeprecation")?console.trace(msg):console.warn(msg);warned=!0}return fn.apply(this,arguments)}if(config("noDeprecation"))return fn;var warned=!1;return deprecated}}).call(this)}).call(this,"undefined"==typeof global?"undefined"==typeof self?"undefined"==typeof window?{}:window:self:global)},{}],197:[function(require,module){(function(Buffer){(function(){function empty(){return{version:0,flags:0,entries:[]}}const bs=require("binary-search"),EventEmitter=require("events"),mp4=require("mp4-stream"),Box=require("mp4-box-encoding"),RangeSliceStream=require("range-slice-stream");class RunLengthIndex{constructor(entries,countName){this._entries=entries,this._countName=countName||"count",this._index=0,this._offset=0,this.value=this._entries[0]}inc(){this._offset++,this._offset>=this._entries[this._index][this._countName]&&(this._index++,this._offset=0),this.value=this._entries[this._index]}}module.exports=class MP4Remuxer extends EventEmitter{constructor(file){super(),this._tracks=[],this._file=file,this._decoder=null,this._findMoov(0)}_findMoov(offset){this._decoder&&this._decoder.destroy();let toSkip=0;this._decoder=mp4.decode();const fileStream=this._file.createReadStream({start:offset});fileStream.pipe(this._decoder);const boxHandler=headers=>{"moov"===headers.type?(this._decoder.removeListener("box",boxHandler),this._decoder.decode(moov=>{fileStream.destroy();try{this._processMoov(moov)}catch(err){err.message=`Cannot parse mp4 file: ${err.message}`,this.emit("error",err)}})):headers.length<4096?(toSkip+=headers.length,this._decoder.ignore()):(this._decoder.removeListener("box",boxHandler),toSkip+=headers.length,fileStream.destroy(),this._decoder.destroy(),this._findMoov(offset+toSkip))};this._decoder.on("box",boxHandler)}_processMoov(moov){const traks=moov.traks;this._tracks=[],this._hasVideo=!1,this._hasAudio=!1;for(let i=0;i=stbl.stsz.entries.length)break;if(sampleInChunk++,offsetInChunk+=size,sampleInChunk>=currChunkEntry.samplesPerChunk){sampleInChunk=0,offsetInChunk=0,chunk++;const nextChunkEntry=stbl.stsc.entries[sampleToChunkIndex+1];nextChunkEntry&&chunk+1>=nextChunkEntry.firstChunk&&sampleToChunkIndex++}dts+=duration,decodingTimeEntry.inc(),presentationOffsetEntry&&presentationOffsetEntry.inc(),sync&&syncSampleIndex++}trak.mdia.mdhd.duration=0,trak.tkhd.duration=0;const defaultSampleDescriptionIndex=currChunkEntry.sampleDescriptionId,trackMoov={type:"moov",mvhd:moov.mvhd,traks:[{tkhd:trak.tkhd,mdia:{mdhd:trak.mdia.mdhd,hdlr:trak.mdia.hdlr,elng:trak.mdia.elng,minf:{vmhd:trak.mdia.minf.vmhd,smhd:trak.mdia.minf.smhd,dinf:trak.mdia.minf.dinf,stbl:{stsd:stbl.stsd,stts:empty(),ctts:empty(),stsc:empty(),stsz:empty(),stco:empty(),stss:empty()}}}}],mvex:{mehd:{fragmentDuration:moov.mvhd.duration},trexs:[{trackId:trak.tkhd.trackId,defaultSampleDescriptionIndex,defaultSampleDuration:0,defaultSampleSize:0,defaultSampleFlags:0}]}};this._tracks.push({fragmentSequence:1,trackId:trak.tkhd.trackId,timeScale:trak.mdia.mdhd.timeScale,samples,currSample:null,currTime:null,moov:trackMoov,mime})}if(0===this._tracks.length)return void this.emit("error",new Error("no playable tracks"));moov.mvhd.duration=0,this._ftyp={type:"ftyp",brand:"iso5",brandVersion:0,compatibleBrands:["iso5"]};const ftypBuf=Box.encode(this._ftyp),data=this._tracks.map(track=>{const moovBuf=Box.encode(track.moov);return{mime:track.mime,init:Buffer.concat([ftypBuf,moovBuf])}});this.emit("ready",data)}seek(time){if(!this._tracks)throw new Error("Not ready yet; wait for 'ready' event");this._fileStream&&(this._fileStream.destroy(),this._fileStream=null);let startOffset=-1;if(this._tracks.map((track,i)=>{track.outStream&&track.outStream.destroy(),track.inStream&&(track.inStream.destroy(),track.inStream=null);const outStream=track.outStream=mp4.encode(),fragment=this._generateFragment(i,time);if(!fragment)return outStream.finalize();(-1===startOffset||fragment.ranges[0].start{outStream.destroyed||outStream.box(frag.moof,err=>{if(err)return this.emit("error",err);if(!outStream.destroyed){const slicedStream=track.inStream.slice(frag.ranges);slicedStream.pipe(outStream.mediaData(frag.length,err=>{if(err)return this.emit("error",err);if(!outStream.destroyed){const nextFrag=this._generateFragment(i);return nextFrag?void writeFragment(nextFrag):outStream.finalize()}}))}})};writeFragment(fragment)}),0<=startOffset){const fileStream=this._fileStream=this._file.createReadStream({start:startOffset});this._tracks.forEach(track=>{track.inStream=new RangeSliceStream(startOffset,{highWaterMark:1e7}),fileStream.pipe(track.inStream)})}return this._tracks.map(track=>track.outStream)}_findSampleBefore(trackInd,time){const track=this._tracks[trackInd],scaledTime=_Mathfloor(track.timeScale*time);let sample=bs(track.samples,scaledTime,(sample,t)=>{const pts=sample.dts+sample.presentationOffset;return pts-t});for(-1===sample?sample=0:0>sample&&(sample=-sample-2);!track.samples[sample].sync;)sample--;return sample}_generateFragment(track,time){const currTrack=this._tracks[track];let firstSample;if(firstSample=void 0===time?currTrack.currSample:this._findSampleBefore(track,time),firstSample>=currTrack.samples.length)return null;const startDts=currTrack.samples[firstSample].dts;let totalLen=0;const ranges=[];for(var currSample=firstSample;currSample=currTrack.timeScale*1)break;totalLen+=sample.size;const currRange=ranges.length-1;0>currRange||ranges[currRange].end!==sample.offset?ranges.push({start:sample.offset,end:sample.offset+sample.size}):ranges[currRange].end+=sample.size}return currTrack.currSample=currSample,{moof:this._generateMoof(track,firstSample,currSample),ranges,length:totalLen}}_generateMoof(track,firstSample,lastSample){const currTrack=this._tracks[track],entries=[];let trunVersion=0;for(let j=firstSample;jcurrSample.presentationOffset&&(trunVersion=1),entries.push({sampleDuration:currSample.duration,sampleSize:currSample.size,sampleFlags:currSample.sync?33554432:16842752,sampleCompositionTimeOffset:currSample.presentationOffset})}const moof={type:"moof",mfhd:{sequenceNumber:currTrack.fragmentSequence++},trafs:[{tfhd:{flags:131072,trackId:currTrack.trackId},tfdt:{baseMediaDecodeTime:currTrack.samples[firstSample].dts},trun:{flags:3841,dataOffset:8,entries,version:trunVersion}}]};return moof.trafs[0].trun.dataOffset+=Box.encodingLength(moof),moof}}}).call(this)}).call(this,require("buffer").Buffer)},{"binary-search":21,buffer:38,events:39,"mp4-box-encoding":121,"mp4-stream":124,"range-slice-stream":142}],198:[function(require,module){function VideoStream(file,mediaElem,opts={}){return this instanceof VideoStream?void(this.detailedError=null,this._elem=mediaElem,this._elemWrapper=new MediaElementWrapper(mediaElem),this._waitingFired=!1,this._trackMeta=null,this._file=file,this._tracks=null,"none"!==this._elem.preload&&this._createMuxer(),this._onError=()=>{this.detailedError=this._elemWrapper.detailedError,this.destroy()},this._onWaiting=()=>{this._waitingFired=!0,this._muxer?this._tracks&&this._pump():this._createMuxer()},mediaElem.autoplay&&(mediaElem.preload="auto"),mediaElem.addEventListener("waiting",this._onWaiting),mediaElem.addEventListener("error",this._onError)):(console.warn("Don't invoke VideoStream without the 'new' keyword."),new VideoStream(file,mediaElem,opts))}const MediaElementWrapper=require("mediasource"),pump=require("pump"),MP4Remuxer=require("./mp4-remuxer");VideoStream.prototype={_createMuxer(){this._muxer=new MP4Remuxer(this._file),this._muxer.on("ready",data=>{this._tracks=data.map(trackData=>{const mediaSource=this._elemWrapper.createWriteStream(trackData.mime);mediaSource.on("error",err=>{this._elemWrapper.error(err)});const track={muxed:null,mediaSource,initFlushed:!1,onInitFlushed:null};return mediaSource.write(trackData.init,err=>{track.initFlushed=!0,track.onInitFlushed&&track.onInitFlushed(err)}),track}),(this._waitingFired||"auto"===this._elem.preload)&&this._pump()}),this._muxer.on("error",err=>{this._elemWrapper.error(err)})},_pump(){const muxed=this._muxer.seek(this._elem.currentTime,!this._tracks);this._tracks.forEach((track,i)=>{const pumpTrack=()=>{track.muxed&&(track.muxed.destroy(),track.mediaSource=this._elemWrapper.createWriteStream(track.mediaSource),track.mediaSource.on("error",err=>{this._elemWrapper.error(err)})),track.muxed=muxed[i],pump(track.muxed,track.mediaSource)};track.initFlushed?pumpTrack():track.onInitFlushed=err=>err?void this._elemWrapper.error(err):void pumpTrack()})},destroy(){this.destroyed||(this.destroyed=!0,this._elem.removeEventListener("waiting",this._onWaiting),this._elem.removeEventListener("error",this._onError),this._tracks&&this._tracks.forEach(track=>{track.muxed&&track.muxed.destroy()}),this._elem.src="")}},module.exports=VideoStream},{"./mp4-remuxer":197,mediasource:113,pump:133}],199:[function(require,module){(function(global){(function(){'use strict';var forEach=require("foreach"),availableTypedArrays=require("available-typed-arrays"),callBound=require("es-abstract/helpers/callBound"),$toString=callBound("Object.prototype.toString"),hasSymbols=require("has-symbols")(),hasToStringTag=hasSymbols&&"symbol"==typeof Symbol.toStringTag,typedArrays=availableTypedArrays(),$slice=callBound("String.prototype.slice"),toStrTags={},gOPD=require("es-abstract/helpers/getOwnPropertyDescriptor"),getPrototypeOf=Object.getPrototypeOf;hasToStringTag&&gOPD&&getPrototypeOf&&forEach(typedArrays,function(typedArray){if("function"==typeof global[typedArray]){var arr=new global[typedArray];if(!(Symbol.toStringTag in arr))throw new EvalError("this engine has support for Symbol.toStringTag, but "+typedArray+" does not have the property! Please report this.");var proto=getPrototypeOf(arr),descriptor=gOPD(proto,Symbol.toStringTag);if(!descriptor){var superProto=getPrototypeOf(proto);descriptor=gOPD(superProto,Symbol.toStringTag)}toStrTags[typedArray]=descriptor.get}});var tryTypedArrays=function(value){var foundName=!1;return forEach(toStrTags,function(getter,typedArray){if(!foundName)try{var name=getter.call(value);name===typedArray&&(foundName=name)}catch(e){}}),foundName},isTypedArray=require("is-typed-array");module.exports=function(value){return!!isTypedArray(value)&&(hasToStringTag?tryTypedArrays(value):$slice($toString(value),8,-1))}}).call(this)}).call(this,"undefined"==typeof global?"undefined"==typeof self?"undefined"==typeof window?{}:window:self:global)},{"available-typed-arrays":15,"es-abstract/helpers/callBound":75,"es-abstract/helpers/getOwnPropertyDescriptor":76,foreach:79,"has-symbols":84,"is-typed-array":104}],200:[function(require,module){function wrappy(fn,cb){function wrapper(){for(var args=Array(arguments.length),i=0;i */const{EventEmitter}=require("events"),concat=require("simple-concat"),createTorrent=require("create-torrent"),debug=require("debug")("webtorrent"),DHT=require("bittorrent-dht/client"),loadIPSet=require("load-ip-set"),parallel=require("run-parallel"),parseTorrent=require("parse-torrent"),path=require("path"),Peer=require("simple-peer"),randombytes=require("randombytes"),speedometer=require("speedometer"),ConnPool=require("./lib/conn-pool"),Torrent=require("./lib/torrent"),VERSION=require("./package.json").version,VERSION_STR=VERSION.replace(/\d*./g,v=>`0${v%100}`.slice(-2)).slice(0,4);class WebTorrent extends EventEmitter{constructor(opts={}){super(),this.peerId="string"==typeof opts.peerId?opts.peerId:Buffer.isBuffer(opts.peerId)?opts.peerId.toString("hex"):Buffer.from(`-WW${VERSION_STR}-`+randombytes(9).toString("base64")).toString("hex"),this.peerIdBuffer=Buffer.from(this.peerId,"hex"),this.nodeId="string"==typeof opts.nodeId?opts.nodeId:Buffer.isBuffer(opts.nodeId)?opts.nodeId.toString("hex"):randombytes(20).toString("hex"),this.nodeIdBuffer=Buffer.from(this.nodeId,"hex"),this._debugId=this.peerId.toString("hex").substring(0,7),this.destroyed=!1,this.listening=!1,this.torrentPort=opts.torrentPort||0,this.dhtPort=opts.dhtPort||0,this.tracker=opts.tracker===void 0?{}:opts.tracker,this.lsd=!1!==opts.lsd,this.torrents=[],this.maxConns=+opts.maxConns||55,this.utp=!0===opts.utp,this._debug("new webtorrent (peerId %s, nodeId %s, port %s)",this.peerId,this.nodeId,this.torrentPort),this.tracker&&("object"!=typeof this.tracker&&(this.tracker={}),opts.rtcConfig&&(console.warn("WebTorrent: opts.rtcConfig is deprecated. Use opts.tracker.rtcConfig instead"),this.tracker.rtcConfig=opts.rtcConfig),opts.wrtc&&(console.warn("WebTorrent: opts.wrtc is deprecated. Use opts.tracker.wrtc instead"),this.tracker.wrtc=opts.wrtc),global.WRTC&&!this.tracker.wrtc&&(this.tracker.wrtc=global.WRTC)),"function"==typeof ConnPool?this._connPool=new ConnPool(this):process.nextTick(()=>{this._onListening()}),this._downloadSpeed=speedometer(),this._uploadSpeed=speedometer(),!1!==opts.dht&&"function"==typeof DHT?(this.dht=new DHT(Object.assign({},{nodeId:this.nodeId},opts.dht)),this.dht.once("error",err=>{this._destroy(err)}),this.dht.once("listening",()=>{const address=this.dht.address();address&&(this.dhtPort=address.port)}),this.dht.setMaxListeners(0),this.dht.listen(this.dhtPort)):this.dht=!1,this.enableWebSeeds=!1!==opts.webSeeds;const ready=()=>{this.destroyed||(this.ready=!0,this.emit("ready"))};"function"==typeof loadIPSet&&null!=opts.blocklist?loadIPSet(opts.blocklist,{headers:{"user-agent":`WebTorrent/${VERSION} (https://webtorrent.io)`}},(err,ipSet)=>err?this.error(`Failed to load blocklist: ${err.message}`):void(this.blocked=ipSet,ready())):process.nextTick(ready)}get downloadSpeed(){return this._downloadSpeed()}get uploadSpeed(){return this._uploadSpeed()}get progress(){const torrents=this.torrents.filter(torrent=>1!==torrent.progress),downloaded=torrents.reduce((total,torrent)=>total+torrent.downloaded,0),length=torrents.reduce((total,torrent)=>total+(torrent.length||0),0)||1;return downloaded/length}get ratio(){const uploaded=this.torrents.reduce((total,torrent)=>total+torrent.uploaded,0),received=this.torrents.reduce((total,torrent)=>total+torrent.received,0)||1;return uploaded/received}get(torrentId){if(!(torrentId instanceof Torrent)){let parsed;try{parsed=parseTorrent(torrentId)}catch(err){}if(!parsed)return null;if(!parsed.infoHash)throw new Error("Invalid torrent identifier");for(const torrent of this.torrents)if(torrent.infoHash===parsed.infoHash)return torrent}else if(this.torrents.includes(torrentId))return torrentId;return null}download(torrentId,opts,ontorrent){return console.warn("WebTorrent: client.download() is deprecated. Use client.add() instead"),this.add(torrentId,opts,ontorrent)}add(torrentId,opts={},ontorrent=()=>{}){function onClose(){torrent.removeListener("_infoHash",onInfoHash),torrent.removeListener("ready",onReady),torrent.removeListener("close",onClose)}if(this.destroyed)throw new Error("client is destroyed");"function"==typeof opts&&([opts,ontorrent]=[{},opts]);const onInfoHash=()=>{if(!this.destroyed)for(const t of this.torrents)if(t.infoHash===torrent.infoHash&&t!==torrent)return void torrent._destroy(new Error(`Cannot add duplicate torrent ${torrent.infoHash}`))},onReady=()=>{this.destroyed||(ontorrent(torrent),this.emit("torrent",torrent))};this._debug("add"),opts=opts?Object.assign({},opts):{};const torrent=new Torrent(torrentId,this,opts);return this.torrents.push(torrent),torrent.once("_infoHash",onInfoHash),torrent.once("ready",onReady),torrent.once("close",onClose),torrent}seed(input,opts,onseed){if(this.destroyed)throw new Error("client is destroyed");"function"==typeof opts&&([opts,onseed]=[{},opts]),this._debug("seed"),opts=opts?Object.assign({},opts):{},opts.skipVerify=!0;const isFilePath="string"==typeof input;isFilePath&&(opts.path=path.dirname(input)),opts.createdBy||(opts.createdBy=`WebTorrent/${VERSION_STR}`);const _onseed=torrent=>{this._debug("on seed"),"function"==typeof onseed&&onseed(torrent),torrent.emit("seed"),this.emit("seed",torrent)},torrent=this.add(null,opts,torrent=>{const tasks=[cb=>isFilePath?cb():void torrent.load(streams,cb)];this.dht&&tasks.push(cb=>{torrent.once("dhtAnnounce",cb)}),parallel(tasks,err=>this.destroyed?void 0:err?torrent._destroy(err):void _onseed(torrent))});let streams;return isFileList(input)?input=Array.from(input):!Array.isArray(input)&&(input=[input]),parallel(input.map(item=>cb=>{isReadable(item)?concat(item,cb):cb(null,item)}),(err,input)=>this.destroyed?void 0:err?torrent._destroy(err):void createTorrent.parseInput(input,opts,(err,files)=>this.destroyed?void 0:err?torrent._destroy(err):void(streams=files.map(file=>file.getStream),createTorrent(input,opts,(err,torrentBuf)=>{if(!this.destroyed){if(err)return torrent._destroy(err);const existingTorrent=this.get(torrentBuf);existingTorrent?torrent._destroy(new Error(`Cannot add duplicate torrent ${existingTorrent.infoHash}`)):torrent._onTorrentId(torrentBuf)}})))),torrent}remove(torrentId,opts,cb){if("function"==typeof opts)return this.remove(torrentId,null,opts);this._debug("remove");const torrent=this.get(torrentId);if(!torrent)throw new Error(`No torrent with id ${torrentId}`);this._remove(torrentId,opts,cb)}_remove(torrentId,opts,cb){if("function"==typeof opts)return this._remove(torrentId,null,opts);const torrent=this.get(torrentId);torrent&&(this.torrents.splice(this.torrents.indexOf(torrent),1),torrent.destroy(opts,cb))}address(){return this.listening?this._connPool?this._connPool.tcpServer.address():{address:"0.0.0.0",family:"IPv4",port:0}:null}destroy(cb){if(this.destroyed)throw new Error("client already destroyed");this._destroy(null,cb)}_destroy(err,cb){this._debug("client destroy"),this.destroyed=!0;const tasks=this.torrents.map(torrent=>cb=>{torrent.destroy(cb)});this._connPool&&tasks.push(cb=>{this._connPool.destroy(cb)}),this.dht&&tasks.push(cb=>{this.dht.destroy(cb)}),parallel(tasks,cb),err&&this.emit("error",err),this.torrents=[],this._connPool=null,this.dht=null}_onListening(){if(this._debug("listening"),this.listening=!0,this._connPool){const address=this._connPool.tcpServer.address();address&&(this.torrentPort=address.port)}this.emit("listening")}_debug(){const args=[].slice.call(arguments);args[0]=`[${this._debugId}] ${args[0]}`,debug(...args)}}WebTorrent.WEBRTC_SUPPORT=Peer.WEBRTC_SUPPORT,WebTorrent.VERSION=VERSION,module.exports=WebTorrent}).call(this)}).call(this,require("_process"),"undefined"==typeof global?"undefined"==typeof self?"undefined"==typeof window?{}:window:self:global,require("buffer").Buffer)},{"./lib/conn-pool":1,"./lib/torrent":7,"./package.json":202,_process:132,"bittorrent-dht/client":23,buffer:38,"create-torrent":68,debug:69,events:39,"load-ip-set":36,"parse-torrent":130,path:40,randombytes:140,"run-parallel":162,"simple-concat":166,"simple-peer":168,speedometer:172}]},{},[203])(203)}); \ No newline at end of file diff --git a/webtorrent.min.js b/webtorrent.min.js index 14f447d482..1c335f6a61 100644 --- a/webtorrent.min.js +++ b/webtorrent.min.js @@ -1,6 +1,6 @@ -(function(f){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=f();else if("function"==typeof define&&define.amd)define([],f);else{var g;g="undefined"==typeof window?"undefined"==typeof global?"undefined"==typeof self?this:self:global:window,g.WebTorrent=f()}})(function(){var _Mathabs=Math.abs,_Mathpow=Math.pow,_Mathfloor=Math.floor,_StringfromCharCode=String.fromCharCode,_Mathceil=Math.ceil,_Mathmax=Math.max,_Mathmin=Math.min,define;return function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i{if(this._notifying=!1,!this.destroyed)return debug("read %s (length %s) (err %s)",p,buffer.length,err&&err.message),err?this._destroy(err):void(this._offset&&(buffer=buffer.slice(this._offset),this._offset=0),this._missing{empty.end()}),empty}const fileStream=new FileStream(this,opts);return this._torrent.select(fileStream._startPiece,fileStream._endPiece,!0,()=>{fileStream._notify()}),eos(fileStream,()=>{this._destroyed||!this._torrent.destroyed&&this._torrent.deselect(fileStream._startPiece,fileStream._endPiece,!0)}),fileStream}getBuffer(cb){streamToBuffer(this.createReadStream(),this.length,cb)}getBlob(cb){if("undefined"==typeof window)throw new Error("browser-only method");streamToBlob(this.createReadStream(),this._getMimeType()).then(blob=>cb(null,blob),err=>cb(err))}getBlobURL(cb){if("undefined"==typeof window)throw new Error("browser-only method");streamToBlobURL(this.createReadStream(),this._getMimeType()).then(blobUrl=>cb(null,blobUrl),err=>cb(err))}appendTo(elem,opts,cb){if("undefined"==typeof window)throw new Error("browser-only method");render.append(this,elem,opts,cb)}renderTo(elem,opts,cb){if("undefined"==typeof window)throw new Error("browser-only method");render.render(this,elem,opts,cb)}_getMimeType(){return render.mime[path.extname(this.name).toLowerCase()]}_destroy(){this._destroyed=!0,this._torrent=null}}module.exports=File}).call(this)}).call(this,require("_process"))},{"./file-stream":1,_process:62,"end-of-stream":35,events:25,path:26,"readable-stream":86,"render-media":87,"stream-to-blob":105,"stream-to-blob-url":104,"stream-with-known-length-to-buffer":106}],3:[function(require,module,exports){const arrayRemove=require("unordered-array-remove"),debug=require("debug")("webtorrent:peer"),Wire=require("bittorrent-protocol"),WebConn=require("./webconn");exports.createWebRTCPeer=(conn,swarm)=>{const peer=new Peer(conn.id,"webrtc");return peer.conn=conn,peer.swarm=swarm,peer.conn.connected?peer.onConnect():(peer.conn.once("connect",()=>{peer.onConnect()}),peer.conn.once("error",err=>{peer.destroy(err)}),peer.startConnectTimeout()),peer},exports.createTCPIncomingPeer=conn=>_createIncomingPeer(conn,"tcpIncoming"),exports.createUTPIncomingPeer=conn=>_createIncomingPeer(conn,"utpIncoming"),exports.createTCPOutgoingPeer=(addr,swarm)=>_createOutgoingPeer(addr,swarm,"tcpOutgoing"),exports.createUTPOutgoingPeer=(addr,swarm)=>_createOutgoingPeer(addr,swarm,"utpOutgoing");const _createIncomingPeer=(conn,type)=>{const addr=`${conn.remoteAddress}:${conn.remotePort}`,peer=new Peer(addr,type);return peer.conn=conn,peer.addr=addr,peer.onConnect(),peer},_createOutgoingPeer=(addr,swarm,type)=>{const peer=new Peer(addr,type);return peer.addr=addr,peer.swarm=swarm,peer};exports.createWebSeedPeer=(url,swarm)=>{const peer=new Peer(url,"webSeed");return peer.swarm=swarm,peer.conn=new WebConn(url,swarm),peer.onConnect(),peer};class Peer{constructor(id,type){this.id=id,this.type=type,debug("new %s Peer %s",type,id),this.addr=null,this.conn=null,this.swarm=null,this.wire=null,this.connected=!1,this.destroyed=!1,this.timeout=null,this.retries=0,this.sentHandshake=!1}onConnect(){if(!this.destroyed){this.connected=!0,debug("Peer %s connected",this.id),clearTimeout(this.connectTimeout);const conn=this.conn;conn.once("end",()=>{this.destroy()}),conn.once("close",()=>{this.destroy()}),conn.once("finish",()=>{this.destroy()}),conn.once("error",err=>{this.destroy(err)});const wire=this.wire=new Wire;wire.type=this.type,wire.once("end",()=>{this.destroy()}),wire.once("close",()=>{this.destroy()}),wire.once("finish",()=>{this.destroy()}),wire.once("error",err=>{this.destroy(err)}),wire.once("handshake",(infoHash,peerId)=>{this.onHandshake(infoHash,peerId)}),this.startHandshakeTimeout(),conn.pipe(wire).pipe(conn),this.swarm&&!this.sentHandshake&&this.handshake()}}onHandshake(infoHash,peerId){if(!this.swarm)return;if(this.destroyed)return;if(this.swarm.destroyed)return this.destroy(new Error("swarm already destroyed"));if(infoHash!==this.swarm.infoHash)return this.destroy(new Error("unexpected handshake info hash for this swarm"));if(peerId===this.swarm.peerId)return this.destroy(new Error("refusing to connect to ourselves"));debug("Peer %s got handshake %s",this.id,infoHash),clearTimeout(this.handshakeTimeout),this.retries=0;let addr=this.addr;!addr&&this.conn.remoteAddress&&this.conn.remotePort&&(addr=`${this.conn.remoteAddress}:${this.conn.remotePort}`),this.swarm._onWire(this.wire,addr);this.swarm&&!this.swarm.destroyed&&(this.sentHandshake||this.handshake())}handshake(){const opts={dht:!this.swarm.private&&!!this.swarm.client.dht};this.wire.handshake(this.swarm.infoHash,this.swarm.client.peerId,opts),this.sentHandshake=!0}startConnectTimeout(){clearTimeout(this.connectTimeout);this.connectTimeout=setTimeout(()=>{this.destroy(new Error("connect timeout"))},{webrtc:25e3,tcpOutgoing:5e3,utpOutgoing:5e3}[this.type]),this.connectTimeout.unref&&this.connectTimeout.unref()}startHandshakeTimeout(){clearTimeout(this.handshakeTimeout),this.handshakeTimeout=setTimeout(()=>{this.destroy(new Error("handshake timeout"))},25e3),this.handshakeTimeout.unref&&this.handshakeTimeout.unref()}destroy(err){if(this.destroyed)return;this.destroyed=!0,this.connected=!1,debug("destroy %s %s (error: %s)",this.type,this.id,err&&(err.message||err)),clearTimeout(this.connectTimeout),clearTimeout(this.handshakeTimeout);const swarm=this.swarm,conn=this.conn,wire=this.wire;this.swarm=null,this.conn=null,this.wire=null,swarm&&wire&&arrayRemove(swarm.wires,swarm.wires.indexOf(wire)),conn&&(conn.on("error",()=>{}),conn.destroy()),wire&&wire.destroy(),swarm&&swarm.removePeer(this.id)}}},{"./webconn":6,"bittorrent-protocol":15,debug:33,"unordered-array-remove":115}],4:[function(require,module){module.exports=class RarityMap{constructor(torrent){this._torrent=torrent,this._numPieces=torrent.pieces.length,this._pieces=Array(this._numPieces),this._onWire=wire=>{this.recalculate(),this._initWire(wire)},this._onWireHave=index=>{this._pieces[index]+=1},this._onWireBitfield=()=>{this.recalculate()},this._torrent.wires.forEach(wire=>{this._initWire(wire)}),this._torrent.on("wire",this._onWire),this.recalculate()}getRarestPiece(pieceFilterFunc){let candidates=[],min=1/0;for(let i=0;i{this._cleanupWireEvents(wire)}),this._torrent=null,this._pieces=null,this._onWire=null,this._onWireHave=null,this._onWireBitfield=null}_initWire(wire){wire._onClose=()=>{this._cleanupWireEvents(wire);for(let i=0;i{this.destroyed||this._onParsedTorrent(parsedTorrent)})):parseTorrent.remote(torrentId,(err,parsedTorrent)=>this.destroyed?void 0:err?this._destroy(err):void this._onParsedTorrent(parsedTorrent))}_onParsedTorrent(parsedTorrent){if(!this.destroyed){if(this._processParsedTorrent(parsedTorrent),!this.infoHash)return this._destroy(new Error("Malformed torrent data: No info hash"));(this.path||(this.path=path.join(TMP,this.infoHash)),this._rechokeIntervalId=setInterval(()=>{this._rechoke()},1e4),this._rechokeIntervalId.unref&&this._rechokeIntervalId.unref(),this.emit("_infoHash",this.infoHash),!this.destroyed)&&(this.emit("infoHash",this.infoHash),this.destroyed||(this.client.listening?this._onListening():this.client.once("listening",()=>{this._onListening()})))}}_processParsedTorrent(parsedTorrent){this._debugId=parsedTorrent.infoHash.toString("hex").substring(0,7),"undefined"!=typeof this.private&&(parsedTorrent.private=this.private),this.announce&&(parsedTorrent.announce=parsedTorrent.announce.concat(this.announce)),this.client.tracker&&global.WEBTORRENT_ANNOUNCE&&!parsedTorrent.private&&(parsedTorrent.announce=parsedTorrent.announce.concat(global.WEBTORRENT_ANNOUNCE)),this.urlList&&(parsedTorrent.urlList=parsedTorrent.urlList.concat(this.urlList)),parsedTorrent.announce=Array.from(new Set(parsedTorrent.announce)),parsedTorrent.urlList=Array.from(new Set(parsedTorrent.urlList)),Object.assign(this,parsedTorrent),this.magnetURI=parseTorrent.toMagnetURI(parsedTorrent),this.torrentFile=parseTorrent.toTorrentFile(parsedTorrent)}_onListening(){this.destroyed||(this.info?this._onMetadata(this):(this.xs&&this._getMetadataFromServer(),this._startDiscovery()))}_startDiscovery(){if(this.discovery||this.destroyed)return;let trackerOpts=this.client.tracker;trackerOpts&&(trackerOpts=Object.assign({},this.client.tracker,{getAnnounceOpts:()=>{const opts={uploaded:this.uploaded,downloaded:this.downloaded,left:_Mathmax(this.length-this.downloaded,0)};return this.client.tracker.getAnnounceOpts&&Object.assign(opts,this.client.tracker.getAnnounceOpts()),this._getAnnounceOpts&&Object.assign(opts,this._getAnnounceOpts()),opts}})),this.peerAddresses&&this.peerAddresses.forEach(peer=>this.addPeer(peer)),this.discovery=new Discovery({infoHash:this.infoHash,announce:this.announce,peerId:this.client.peerId,dht:!this.private&&this.client.dht,tracker:trackerOpts,port:this.client.torrentPort,userAgent:USER_AGENT,lsd:this.client.lsd}),this.discovery.on("error",err=>{this._destroy(err)}),this.discovery.on("peer",(peer,source)=>{this._debug("peer %s discovered via %s",peer,source);"string"==typeof peer&&this.done||this.addPeer(peer)}),this.discovery.on("trackerAnnounce",()=>{this.emit("trackerAnnounce"),0===this.numPeers&&this.emit("noPeers","tracker")}),this.discovery.on("dhtAnnounce",()=>{this.emit("dhtAnnounce"),0===this.numPeers&&this.emit("noPeers","dht")}),this.discovery.on("warning",err=>{this.emit("warning",err)})}_getMetadataFromServer(){function getMetadataFromURL(url,cb){function onResponse(err,res,torrent){if(self.destroyed)return cb(null);if(self.metadata)return cb(null);if(err)return self.emit("warning",new Error(`http error from xs param: ${url}`)),cb(null);if(200!==res.statusCode)return self.emit("warning",new Error(`non-200 status code ${res.statusCode} from xs param: ${url}`)),cb(null);let parsedTorrent;try{parsedTorrent=parseTorrent(torrent)}catch(err){}return parsedTorrent?parsedTorrent.infoHash===self.infoHash?void(self._onMetadata(parsedTorrent),cb(null)):(self.emit("warning",new Error(`got torrent file with incorrect info hash from xs param: ${url}`)),cb(null)):(self.emit("warning",new Error(`got invalid torrent file from xs param: ${url}`)),cb(null))}if(0!==url.indexOf("http://")&&0!==url.indexOf("https://"))return self.emit("warning",new Error(`skipping non-http xs param: ${url}`)),cb(null);let req;try{req=get.concat({url,method:"GET",headers:{"user-agent":USER_AGENT}},onResponse)}catch(err){return self.emit("warning",new Error(`skipping invalid url xs param: ${url}`)),cb(null)}self._xsRequests.push(req)}const self=this,urls=Array.isArray(this.xs)?this.xs:[this.xs],tasks=urls.map(url=>cb=>{getMetadataFromURL(url,cb)});parallel(tasks)}_onMetadata(metadata){if(this.metadata||this.destroyed)return;this._debug("got metadata"),this._xsRequests.forEach(req=>{req.abort()}),this._xsRequests=[];let parsedTorrent;if(metadata&&metadata.infoHash)parsedTorrent=metadata;else try{parsedTorrent=parseTorrent(metadata)}catch(err){return this._destroy(err)}if(this._processParsedTorrent(parsedTorrent),this.metadata=this.torrentFile,this.client.enableWebSeeds&&this.urlList.forEach(url=>{this.addWebSeed(url)}),this._rarityMap=new RarityMap(this),this.store=new ImmediateChunkStore(new this._store(this.pieceLength,{torrent:{infoHash:this.infoHash},files:this.files.map(file=>({path:path.join(this.path,file.path),length:file.length,offset:file.offset})),length:this.length,name:this.infoHash})),this.files=this.files.map(file=>new File(this,file)),this.so?this.files.forEach((v,i)=>{this.so.includes(i)?this.files[i].select():this.files[i].deselect()}):0!==this.pieces.length&&this.select(0,this.pieces.length-1,!1),this._hashes=this.pieces,this.pieces=this.pieces.map((hash,i)=>{const pieceLength=i===this.pieces.length-1?this.lastPieceLength:this.pieceLength;return new Piece(pieceLength)}),this._reservations=this.pieces.map(()=>[]),this.bitfield=new BitField(this.pieces.length),this.wires.forEach(wire=>{wire.ut_metadata&&wire.ut_metadata.setMetadata(this.metadata),this._onWireWithMetadata(wire)}),this.emit("metadata"),!this.destroyed)if(this.skipVerify)this._markAllVerified(),this._onStore();else{const onPiecesVerified=err=>err?this._destroy(err):void(this._debug("done verifying"),this._onStore());this._debug("verifying existing torrent data"),this._fileModtimes&&this._store===FSChunkStore?this.getFileModtimes((err,fileModtimes)=>{if(err)return this._destroy(err);const unchanged=this.files.map((_,index)=>fileModtimes[index]===this._fileModtimes[index]).every(x=>x);unchanged?(this._markAllVerified(),this._onStore()):this._verifyPieces(onPiecesVerified)}):this._verifyPieces(onPiecesVerified)}}getFileModtimes(cb){const ret=[];parallelLimit(this.files.map((file,index)=>cb=>{fs.stat(path.join(this.path,file.path),(err,stat)=>err&&"ENOENT"!==err.code?cb(err):void(ret[index]=stat&&stat.mtime.getTime(),cb(null)))}),FILESYSTEM_CONCURRENCY,err=>{this._debug("done getting file modtimes"),cb(err,ret)})}_verifyPieces(cb){parallelLimit(this.pieces.map((piece,index)=>cb=>this.destroyed?cb(new Error("torrent is destroyed")):void this.store.get(index,(err,buf)=>this.destroyed?cb(new Error("torrent is destroyed")):err?process.nextTick(cb,null):void sha1(buf,hash=>{if(this.destroyed)return cb(new Error("torrent is destroyed"));if(hash===this._hashes[index]){if(!this.pieces[index])return cb(null);this._debug("piece verified %s",index),this._markVerified(index)}else this._debug("piece invalid %s",index);cb(null)}))),FILESYSTEM_CONCURRENCY,cb)}rescanFiles(cb){if(this.destroyed)throw new Error("torrent is destroyed");cb||(cb=noop),this._verifyPieces(err=>err?(this._destroy(err),cb(err)):void(this._checkDone(),cb(null)))}_markAllVerified(){for(let index=0;index{req.abort()}),this._rarityMap&&this._rarityMap.destroy(),this._peers)this.removePeer(id);this.files.forEach(file=>{file instanceof File&&file._destroy()});const tasks=this._servers.map(server=>cb=>{server.destroy(cb)});this.discovery&&tasks.push(cb=>{this.discovery.destroy(cb)}),this.store&&tasks.push(cb=>{opts&&opts.destroyStore?this.store.destroy(cb):this.store.close(cb)}),parallel(tasks,cb),err&&(0===this.listenerCount("error")?this.client.emit("error",err):this.emit("error",err)),this.emit("close"),this.client=null,this.files=[],this.discovery=null,this.store=null,this._rarityMap=null,this._peers=null,this._servers=null,this._xsRequests=null}}addPeer(peer){if(this.destroyed)throw new Error("torrent is destroyed");if(!this.infoHash)throw new Error("addPeer() must not be called before the `infoHash` event");if(this.client.blocked){let host;if("string"==typeof peer){let parts;try{parts=addrToIPPort(peer)}catch(e){return this._debug("ignoring peer: invalid %s",peer),this.emit("invalidPeer",peer),!1}host=parts[0]}else"string"==typeof peer.remoteAddress&&(host=peer.remoteAddress);if(host&&this.client.blocked.contains(host))return this._debug("ignoring peer: blocked %s",peer),"string"!=typeof peer&&peer.destroy(),this.emit("blockedPeer",peer),!1}const wasAdded=!!this._addPeer(peer,this.client.utp?"utp":"tcp");return wasAdded?this.emit("peer",peer):this.emit("invalidPeer",peer),wasAdded}_addPeer(peer,type){if(this.destroyed)return"string"!=typeof peer&&peer.destroy(),null;if("string"==typeof peer&&!this._validAddr(peer))return this._debug("ignoring peer: invalid %s",peer),null;const id=peer&&peer.id||peer;if(this._peers[id])return this._debug("ignoring peer: duplicate (%s)",id),"string"!=typeof peer&&peer.destroy(),null;if(this.paused)return this._debug("ignoring peer: torrent is paused"),"string"!=typeof peer&&peer.destroy(),null;this._debug("add peer %s",id);let newPeer;return newPeer="string"==typeof peer?"utp"===type?Peer.createUTPOutgoingPeer(peer,this):Peer.createTCPOutgoingPeer(peer,this):Peer.createWebRTCPeer(peer,this),this._peers[newPeer.id]=newPeer,this._peersLength+=1,"string"==typeof peer&&(this._queue.push(newPeer),this._drain()),newPeer}addWebSeed(url){if(this.destroyed)throw new Error("torrent is destroyed");if(!/^https?:\/\/.+/.test(url))return this.emit("warning",new Error(`ignoring invalid web seed: ${url}`)),void this.emit("invalidPeer",url);if(this._peers[url])return this.emit("warning",new Error(`ignoring duplicate web seed: ${url}`)),void this.emit("invalidPeer",url);this._debug("add web seed %s",url);const newPeer=Peer.createWebSeedPeer(url,this);this._peers[newPeer.id]=newPeer,this._peersLength+=1,this.emit("peer",url)}_addIncomingPeer(peer){return this.destroyed?peer.destroy(new Error("torrent is destroyed")):this.paused?peer.destroy(new Error("torrent is paused")):void(this._debug("add incoming peer %s",peer.id),this._peers[peer.id]=peer,this._peersLength+=1)}removePeer(peer){const id=peer&&peer.id||peer;peer=this._peers[id];peer&&(this._debug("removePeer %s",id),delete this._peers[id],this._peersLength-=1,peer.destroy(),this._drain())}select(start,end,priority,notify){if(this.destroyed)throw new Error("torrent is destroyed");if(0>start||endb.priority-a.priority),this._updateSelections()}deselect(start,end,priority){if(this.destroyed)throw new Error("torrent is destroyed");priority=+priority||0,this._debug("deselect %s-%s (priority %s)",start,end,priority);for(let i=0;i{this.destroyed||(this.received+=downloaded,this._downloadSpeed(downloaded),this.client._downloadSpeed(downloaded),this.emit("download",downloaded),this.destroyed||this.client.emit("download",downloaded))}),wire.on("upload",uploaded=>{this.destroyed||(this.uploaded+=uploaded,this._uploadSpeed(uploaded),this.client._uploadSpeed(uploaded),this.emit("upload",uploaded),this.destroyed||this.client.emit("upload",uploaded))}),this.wires.push(wire),addr){const parts=addrToIPPort(addr);wire.remoteAddress=parts[0],wire.remotePort=parts[1]}this.client.dht&&this.client.dht.listening&&wire.on("port",port=>this.destroyed||this.client.dht.destroyed?void 0:wire.remoteAddress?0===port||65536{this._debug("wire timeout (%s)",addr),wire.destroy()}),wire.setTimeout(3e4,!0),wire.setKeepAlive(!0),wire.use(utMetadata(this.metadata)),wire.ut_metadata.on("warning",err=>{this._debug("ut_metadata warning: %s",err.message)}),this.metadata||(wire.ut_metadata.on("metadata",metadata=>{this._debug("got metadata via ut_metadata"),this._onMetadata(metadata)}),wire.ut_metadata.fetch()),"function"!=typeof utPex||this.private||(wire.use(utPex()),wire.ut_pex.on("peer",peer=>{this.done||(this._debug("ut_pex: got peer: %s (from %s)",peer,addr),this.addPeer(peer))}),wire.ut_pex.on("dropped",peer=>{const peerObj=this._peers[peer];peerObj&&!peerObj.connected&&(this._debug("ut_pex: dropped peer: %s (from %s)",peer,addr),this.removePeer(peer))}),wire.once("close",()=>{wire.ut_pex.reset()})),this.emit("wire",wire,addr),this.metadata&&process.nextTick(()=>{this._onWireWithMetadata(wire)})}_onWireWithMetadata(wire){let timeoutId=null;const onChokeTimeout=()=>{this.destroyed||wire.destroyed||(this._numQueued>2*(this._numConns-this.numPeers)&&wire.amInterested?wire.destroy():(timeoutId=setTimeout(onChokeTimeout,CHOKE_TIMEOUT),timeoutId.unref&&timeoutId.unref()))};let i;const updateSeedStatus=()=>{if(wire.peerPieces.buffer.length===this.bitfield.buffer.length){for(i=0;i{updateSeedStatus(),this._update(),this._updateWireInterest(wire)}),wire.on("have",()=>{updateSeedStatus(),this._update(),this._updateWireInterest(wire)}),wire.once("interested",()=>{wire.unchoke()}),wire.once("close",()=>{clearTimeout(timeoutId)}),wire.on("choke",()=>{clearTimeout(timeoutId),timeoutId=setTimeout(onChokeTimeout,CHOKE_TIMEOUT),timeoutId.unref&&timeoutId.unref()}),wire.on("unchoke",()=>{clearTimeout(timeoutId),this._update()}),wire.on("request",(index,offset,length,cb)=>length>131072?wire.destroy():void(this.pieces[index]||this.store.get(index,{offset,length},cb))),wire.bitfield(this.bitfield),this._updateWireInterest(wire),wire.peerExtensions.dht&&this.client.dht&&this.client.dht.listening&&wire.port(this.client.dht.address().port),"webSeed"!==wire.type&&(timeoutId=setTimeout(onChokeTimeout,CHOKE_TIMEOUT),timeoutId.unref&&timeoutId.unref()),wire.isSeeder=!1,updateSeedStatus()}_updateSelections(){!this.ready||this.destroyed||(process.nextTick(()=>{this._gcSelections()}),this._updateInterest(),this._update())}_gcSelections(){for(let i=0;ithis._updateWireInterest(wire));prev===this._amInterested||(this._amInterested?this.emit("interested"):this.emit("uninterested"))}_updateWireInterest(wire){let interested=!1;for(let index=0;indexi>=start&&i<=end&&!(i in tried)&&wire.peerPieces.get(i)&&(!rank||rank(i))}function speedRanker(){const speed=wire.downloadSpeed()||1;if(speed>SPEED_THRESHOLD)return()=>!0;const secs=_Mathmax(1,wire.requests.length)*Piece.BLOCK_LENGTH/speed;let tries=10,ptr=0;return index=>{if(!tries||self.bitfield.get(index))return!0;for(let missing=self.pieces[index].missing;ptr=maxOutstandingRequests)return!0;const rank=speedRanker();for(let i=0;ipiece));){for(;self._request(wire,piece,self._critical[piece]||hotswap););if(wire.requests.lengthpiece));){if(self._request(wire,piece,!1))return;tried[piece]=!0,tries+=1}}else for(piece=next.to;piece>=next.from+next.offset;--piece)if(wire.peerPieces.get(piece)&&self._request(wire,piece,!1))return}}();const minOutstandingRequests=getBlockPipelineLength(wire,.5);if(wire.requests.length>=minOutstandingRequests)return;const maxOutstandingRequests=getBlockPipelineLength(wire,PIPELINE_MAX_DURATION);trySelectWire(!1)||trySelectWire(!0)}_rechoke(){if(this.ready){const wireStack=this.wires.map(wire=>({wire,random:Math.random()})).sort((objA,objB)=>{const wireA=objA.wire,wireB=objB.wire;return wireA.downloadSpeed()===wireB.downloadSpeed()?wireA.uploadSpeed()===wireB.uploadSpeed()?wireA.amChoking===wireB.amChoking?objA.random-objB.random:wireA.amChoking?-1:1:wireA.uploadSpeed()-wireB.uploadSpeed():wireA.downloadSpeed()-wireB.downloadSpeed()}).map(obj=>obj.wire);0>=this._rechokeOptimisticTime?this._rechokeOptimisticWire=null:this._rechokeOptimisticTime-=1;for(let numInterestedUnchoked=0;0wire.peerInterested);if(0wire!==this._rechokeOptimisticWire).forEach(wire=>wire.choke())}}_hotswap(wire,index){const speed=wire.downloadSpeed();if(speed=SPEED_THRESHOLD||2*otherSpeed>speed||otherSpeed>minSpeed||(minWire=otherWire,minSpeed=otherSpeed)}if(!minWire)return!1;for(i=0;i{self._update()})}const self=this,numRequests=wire.requests.length,isWebSeed="webSeed"===wire.type;if(self.bitfield.get(index))return!1;const maxOutstandingRequests=isWebSeed?_Mathmin(getPiecePipelineLength(wire,PIPELINE_MAX_DURATION,self.pieceLength),self.maxWebConns):getBlockPipelineLength(wire,PIPELINE_MAX_DURATION);if(numRequests>=maxOutstandingRequests)return!1;const piece=self.pieces[index];let reservation=isWebSeed?piece.reserveRemaining():piece.reserve();if(-1===reservation&&hotswap&&self._hotswap(wire,index)&&(reservation=isWebSeed?piece.reserveRemaining():piece.reserve()),-1===reservation)return!1;let r=self._reservations[index];r||(r=self._reservations[index]=[]);let i=r.indexOf(null);-1===i&&(i=r.length),r[i]=wire;const chunkOffset=piece.chunkOffset(reservation),chunkLength=isWebSeed?piece.chunkLengthRemaining(reservation):piece.chunkLength(reservation);return wire.request(index,chunkOffset,chunkLength,function onChunk(err,chunk){if(self.destroyed)return;if(!self.ready)return self.once("ready",()=>{onChunk(err,chunk)});if(r[i]===wire&&(r[i]=null),piece!==self.pieces[index])return onUpdateTick();if(err)return self._debug("error getting piece %s (offset: %s length: %s) from %s: %s",index,chunkOffset,chunkLength,`${wire.remoteAddress}:${wire.remotePort}`,err.message),isWebSeed?piece.cancelRemaining(reservation):piece.cancel(reservation),void onUpdateTick();if(self._debug("got piece %s (offset: %s length: %s) from %s",index,chunkOffset,chunkLength,`${wire.remoteAddress}:${wire.remotePort}`),!piece.set(reservation,chunk,wire))return onUpdateTick();const buf=piece.flush();sha1(buf,hash=>{if(!self.destroyed){if(hash===self._hashes[index]){if(!self.pieces[index])return;self._debug("piece verified %s",index),self.pieces[index]=null,self._reservations[index]=null,self.bitfield.set(index,!0),self.store.put(index,buf),self.wires.forEach(wire=>{wire.have(index)}),self._checkDone()&&!self.destroyed&&self.discovery.complete()}else self.pieces[index]=new Piece(piece.length),self.emit("warning",new Error(`Piece ${index} failed verification`));onUpdateTick()}})}),!0}_checkDone(){if(this.destroyed)return;this.files.forEach(file=>{if(!file.done){for(let i=file._startPiece;i<=file._endPiece;++i)if(!this.bitfield.get(i))return;file.done=!0,file.emit("done"),this._debug(`file done: ${file.name}`)}});let done=!0;for(let i=0;i{this.load(streams,cb)});Array.isArray(streams)||(streams=[streams]),cb||(cb=noop);const readable=new MultiStream(streams),writable=new ChunkStoreWriteStream(this.store,this.pieceLength);pump(readable,writable,err=>err?cb(err):void(this._markAllVerified(),this._checkDone(),cb(null)))}createServer(requestListener){if("function"!=typeof Server)throw new Error("node.js-only method");if(this.destroyed)throw new Error("torrent is destroyed");const server=new Server(this,requestListener);return this._servers.push(server),server}pause(){this.destroyed||(this._debug("pause"),this.paused=!0)}resume(){this.destroyed||(this._debug("resume"),this.paused=!1,this._drain())}_debug(){const args=[].slice.call(arguments);args[0]=`[${this.client?this.client._debugId:"No Client"}] [${this._debugId}] ${args[0]}`,debug(...args)}_drain(){if(this._debug("_drain numConns %s maxConns %s",this._numConns,this.client.maxConns),"function"!=typeof net.connect||this.destroyed||this.paused||this._numConns>=this.client.maxConns)return;this._debug("drain (%s queued, %s/%s peers)",this._numQueued,this.numPeers,this.client.maxConns);const peer=this._queue.shift();if(!peer)return;this._debug("%s connect attempt to %s",peer.type,peer.addr);const parts=addrToIPPort(peer.addr),opts={host:parts[0],port:parts[1]};peer.conn="utpOutgoing"===peer.type?utp.connect(opts.port,opts.host):net.connect(opts);const conn=peer.conn;conn.once("connect",()=>{peer.onConnect()}),conn.once("error",err=>{peer.destroy(err)}),peer.startConnectTimeout(),conn.on("close",()=>{if(!this.destroyed){if(peer.retries>=RECONNECT_WAIT.length){if(this.client.utp){const newPeer=this._addPeer(peer.addr,"tcp");newPeer&&(newPeer.retries=0)}else this._debug("conn %s closed: will not re-add (max %s attempts)",peer.addr,RECONNECT_WAIT.length);return}const ms=RECONNECT_WAIT[peer.retries];this._debug("conn %s closed: will re-add to queue in %sms (attempt %s)",peer.addr,ms,peer.retries+1);const reconnectTimeout=setTimeout(()=>{if(!this.destroyed){const newPeer=this._addPeer(peer.addr,this.client.utp?"utp":"tcp");newPeer&&(newPeer.retries=peer.retries+1)}},ms);reconnectTimeout.unref&&reconnectTimeout.unref()}})}_validAddr(addr){let parts;try{parts=addrToIPPort(addr)}catch(e){return!1}const host=parts[0],port=parts[1];return 0port&&("127.0.0.1"!==host||port!==this.client.torrentPort)}}module.exports=Torrent}).call(this)}).call(this,require("_process"),"undefined"==typeof global?"undefined"==typeof self?"undefined"==typeof window?{}:window:self:global)},{"../package.json":124,"./file":2,"./peer":3,"./rarity-map":4,"./server":22,_process:62,"addr-to-ip-port":7,bitfield:14,"chunk-store-stream/write":31,debug:33,events:25,fs:23,"fs-chunk-store":49,"immediate-chunk-store":41,multistream:57,net:22,os:22,"parse-torrent":60,path:26,pump:63,"random-iterate":69,"run-parallel":90,"run-parallel-limit":89,"simple-get":94,"simple-sha1":96,speedometer:99,"torrent-discovery":111,"torrent-piece":112,ut_metadata:118,ut_pex:22,"utp-native":22}],6:[function(require,module){(function(Buffer){(function(){const BitField=require("bitfield").default,debug=require("debug")("webtorrent:webconn"),get=require("simple-get"),sha1=require("simple-sha1"),Wire=require("bittorrent-protocol"),VERSION=require("../package.json").version;module.exports=class WebConn extends Wire{constructor(url,torrent){super(),this.url=url,this.webPeerId=sha1.sync(url),this._torrent=torrent,this._init()}_init(){this.setKeepAlive(!0),this.once("handshake",infoHash=>{if(this.destroyed)return;this.handshake(infoHash,this.webPeerId);const numPieces=this._torrent.pieces.length,bitfield=new BitField(numPieces);for(let i=0;i<=numPieces;i++)bitfield.set(i,!0);this.bitfield(bitfield)}),this.once("interested",()=>{debug("interested"),this.unchoke()}),this.on("uninterested",()=>{debug("uninterested")}),this.on("choke",()=>{debug("choke")}),this.on("unchoke",()=>{debug("unchoke")}),this.on("bitfield",()=>{debug("bitfield")}),this.on("request",(pieceIndex,offset,length,callback)=>{debug("request pieceIndex=%d offset=%d length=%d",pieceIndex,offset,length),this.httpRequest(pieceIndex,offset,length,callback)})}httpRequest(pieceIndex,offset,length,cb){const pieceOffset=pieceIndex*this._torrent.pieceLength,rangeStart=pieceOffset+offset,rangeEnd=rangeStart+length-1,files=this._torrent.files;let requests;if(1>=files.length)requests=[{url:this.url,start:rangeStart,end:rangeEnd}];else{const requestedFiles=files.filter(file=>file.offset<=rangeEnd&&file.offset+file.length>rangeStart);if(1>requestedFiles.length)return cb(new Error("Could not find file corresponnding to web seed range request"));requests=requestedFiles.map(requestedFile=>{const fileEnd=requestedFile.offset+requestedFile.length-1,url=this.url+("/"===this.url[this.url.length-1]?"":"/")+requestedFile.path;return{url,fileOffsetInRange:_Mathmax(requestedFile.offset-rangeStart,0),start:_Mathmax(rangeStart-requestedFile.offset,0),end:_Mathmin(fileEnd,rangeEnd-requestedFile.offset)}})}let numRequestsSucceeded=0,hasError=!1,ret;1{function onResponse(res,data){return 200>res.statusCode||300<=res.statusCode?(hasError=!0,cb(new Error(`Unexpected HTTP status code ${res.statusCode}`))):void(debug("Got data of length %d",data.length),1===requests.length?cb(null,data):(data.copy(ret,request.fileOffsetInRange),++numRequestsSucceeded===requests.length&&cb(null,ret)))}const url=request.url,start=request.start,end=request.end;debug("Requesting url=%s pieceIndex=%d offset=%d length=%d start=%d end=%d",url,pieceIndex,offset,length,start,end);const opts={url,method:"GET",headers:{"user-agent":`WebTorrent/${VERSION} (https://webtorrent.io)`,range:`bytes=${start}-${end}`}};get.concat(opts,(err,res,data)=>hasError?void 0:err?"undefined"==typeof window||url.startsWith(`${window.location.origin}/`)?(hasError=!0,cb(err)):get.head(url,(errHead,res)=>hasError?void 0:errHead?(hasError=!0,cb(errHead)):200>res.statusCode||300<=res.statusCode?(hasError=!0,cb(new Error(`Unexpected HTTP status code ${res.statusCode}`))):res.url===url?(hasError=!0,cb(err)):void(opts.url=res.url,get.concat(opts,(err,res,data)=>hasError?void 0:err?(hasError=!0,cb(err)):void onResponse(res,data)))):void onResponse(res,data))})}destroy(){super.destroy(),this._torrent=null}}}).call(this)}).call(this,require("buffer").Buffer)},{"../package.json":124,bitfield:14,"bittorrent-protocol":15,buffer:24,debug:33,"simple-get":94,"simple-sha1":96}],7:[function(require,module){let cache={},size=0;module.exports=function(addr){if(1e5===size&&module.exports.reset(),!cache[addr]){const m=/^\[?([^\]]+)\]?:(\d+)$/.exec(addr);if(!m)throw new Error(`invalid addr: ${addr}`);cache[addr]=[m[1],+m[2]],size+=1}return cache[addr]},module.exports.reset=function(){cache={},size=0}},{}],8:[function(require,module,exports){'use strict';function getLens(b64){var len=b64.length;if(0>16,arr[curByte++]=255&tmp>>8,arr[curByte++]=255&tmp;return 2===placeHoldersLen&&(tmp=revLookup[b64.charCodeAt(i)]<<2|revLookup[b64.charCodeAt(i+1)]>>4,arr[curByte++]=255&tmp),1===placeHoldersLen&&(tmp=revLookup[b64.charCodeAt(i)]<<10|revLookup[b64.charCodeAt(i+1)]<<4|revLookup[b64.charCodeAt(i+2)]>>2,arr[curByte++]=255&tmp>>8,arr[curByte++]=255&tmp),arr}function tripletToBase64(num){return lookup[63&num>>18]+lookup[63&num>>12]+lookup[63&num>>6]+lookup[63&num]}function encodeChunk(uint8,start,end){for(var output=[],i=start,tmp;ilen2?len2:i+maxChunkLength));return 1===extraBytes?(tmp=uint8[len-1],parts.push(lookup[tmp>>2]+lookup[63&tmp<<4]+"==")):2===extraBytes&&(tmp=(uint8[len-2]<<8)+uint8[len-1],parts.push(lookup[tmp>>10]+lookup[63&tmp>>4]+lookup[63&tmp<<2]+"=")),parts.join("")}exports.byteLength=function(b64){var lens=getLens(b64),validLen=lens[0],placeHoldersLen=lens[1];return 3*(validLen+placeHoldersLen)/4-placeHoldersLen},exports.toByteArray=toByteArray,exports.fromByteArray=fromByteArray;for(var lookup=[],revLookup=[],Arr="undefined"==typeof Uint8Array?Array:Uint8Array,code="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",i=0,len=code.length;inum&&48<=num){sum=10*sum+(num-48);continue}if(i!==start||43!==num){if(i===start&&45===num){sign=-1;continue}if(46===num)break;throw new Error("not a number: buffer["+i+"] = "+num)}}return sum*sign}function decode(data,start,end,encoding){return null==data||0===data.length?null:("number"!=typeof start&&null==encoding&&(encoding=start,start=void 0),"number"!=typeof end&&null==encoding&&(encoding=end,end=void 0),decode.position=0,decode.encoding=encoding||null,decode.data=Buffer.isBuffer(data)?data.slice(start,end):Buffer.from(data),decode.bytes=decode.data.length,decode.next())}var Buffer=require("safe-buffer").Buffer;const END_OF_TYPE=101;decode.bytes=0,decode.position=0,decode.data=null,decode.encoding=null,decode.next=function(){switch(decode.data[decode.position]){case 100:return decode.dictionary();case 108:return decode.list();case 105:return decode.integer();default:return decode.buffer();}},decode.find=function(chr){for(var i=decode.position,c=decode.data.length,d=decode.data;iArray.from({length:end-start+1},(cur,idx)=>idx+start);return range.reduce((acc,cur)=>{const r=cur.split("-").map(cur=>parseInt(cur));return acc.concat(generateRange(...r))},[])}module.exports=parseRange,module.exports.parse=parseRange,module.exports.compose=function(range){return range.reduce((acc,cur,idx,arr)=>((0===idx||cur!==arr[idx-1]+1)&&acc.push([]),acc[acc.length-1].push(cur),acc),[]).map(cur=>1low||low>=haystack.length)throw new RangeError("invalid lower bound");if(void 0===high)high=haystack.length-1;else if(high|=0,high=haystack.length)throw new RangeError("invalid upper bound");for(;low<=high;)if(mid=low+(high-low>>>1),cmp=+comparator(haystack[mid],needle,mid,haystack),0>cmp)low=mid+1;else if(0>3;return 0!=num%8&&out++,out}Object.defineProperty(exports,"__esModule",{value:!0});var BitField=function(){function BitField(data,opts){void 0===data&&(data=0);var grow=null===opts||void 0===opts?void 0:opts.grow;this.grow=grow&&isFinite(grow)&&getByteSize(grow)||grow||0,this.buffer="number"==typeof data?new Uint8Array(getByteSize(data)):data}return BitField.prototype.get=function(i){var j=i>>3;return j>i%8)},BitField.prototype.set=function(i,value){void 0===value&&(value=!0);var j=i>>3;if(value){if(this.buffer.length>i%8}else j>i%8))},BitField.prototype.forEach=function(fn,start,end){void 0===start&&(start=0),void 0===end&&(end=8*this.buffer.length);for(var i=start,j=i>>3,y=128>>i%8,byte=this.buffer[j];i>1},BitField}();exports.default=BitField},{}],15:[function(require,module){(function(Buffer){(function(){/*! bittorrent-protocol. MIT License. WebTorrent LLC */const arrayRemove=require("unordered-array-remove"),bencode=require("bencode"),BitField=require("bitfield").default,debug=require("debug")("bittorrent-protocol"),randombytes=require("randombytes"),speedometer=require("speedometer"),stream=require("readable-stream"),MESSAGE_PROTOCOL=Buffer.from("\x13BitTorrent protocol"),MESSAGE_KEEP_ALIVE=Buffer.from([0,0,0,0]),MESSAGE_CHOKE=Buffer.from([0,0,0,1,0]),MESSAGE_UNCHOKE=Buffer.from([0,0,0,1,1]),MESSAGE_INTERESTED=Buffer.from([0,0,0,1,2]),MESSAGE_UNINTERESTED=Buffer.from([0,0,0,1,3]),MESSAGE_RESERVED=[0,0,0,0,0,0,0,0],MESSAGE_PORT=[0,0,0,3,9,0,0];class Request{constructor(piece,offset,length,callback){this.piece=piece,this.offset=offset,this.length=length,this.callback=callback}}class Wire extends stream.Duplex{constructor(){super(),this._debugId=randombytes(4).toString("hex"),this._debug("new wire"),this.peerId=null,this.peerIdBuffer=null,this.type=null,this.amChoking=!0,this.amInterested=!1,this.peerChoking=!0,this.peerInterested=!1,this.peerPieces=new BitField(0,{grow:4e5}),this.peerExtensions={},this.requests=[],this.peerRequests=[],this.extendedMapping={},this.peerExtendedMapping={},this.extendedHandshake={},this.peerExtendedHandshake={},this._ext={},this._nextExt=1,this.uploaded=0,this.downloaded=0,this.uploadSpeed=speedometer(),this.downloadSpeed=speedometer(),this._keepAliveInterval=null,this._timeout=null,this._timeoutMs=0,this.destroyed=!1,this._finished=!1,this._parserSize=0,this._parser=null,this._buffer=[],this._bufferSize=0,this.once("finish",()=>this._onFinish()),this._parseHandshake()}setKeepAlive(enable){this._debug("setKeepAlive %s",enable),clearInterval(this._keepAliveInterval);!1===enable||(this._keepAliveInterval=setInterval(()=>{this.keepAlive()},55e3))}setTimeout(ms,unref){this._debug("setTimeout ms=%d unref=%s",ms,unref),this._clearTimeout(),this._timeoutMs=ms,this._timeoutUnref=!!unref,this._updateTimeout()}destroy(){this.destroyed||(this.destroyed=!0,this._debug("destroy"),this.emit("close"),this.end())}end(...args){this._debug("end"),this._onUninterested(),this._onChoke(),super.end(...args)}use(Extension){function noop(){}const name=Extension.prototype.name;if(!name)throw new Error("Extension class requires a \"name\" property on the prototype");this._debug("use extension.name=%s",name);const ext=this._nextExt,handler=new Extension(this);"function"!=typeof handler.onHandshake&&(handler.onHandshake=noop),"function"!=typeof handler.onExtendedHandshake&&(handler.onExtendedHandshake=noop),"function"!=typeof handler.onMessage&&(handler.onMessage=noop),this.extendedMapping[ext]=name,this._ext[name]=handler,this[name]=handler,this._nextExt+=1}keepAlive(){this._debug("keep-alive"),this._push(MESSAGE_KEEP_ALIVE)}handshake(infoHash,peerId,extensions){let infoHashBuffer,peerIdBuffer;if("string"==typeof infoHash?(infoHash=infoHash.toLowerCase(),infoHashBuffer=Buffer.from(infoHash,"hex")):(infoHashBuffer=infoHash,infoHash=infoHashBuffer.toString("hex")),"string"==typeof peerId?peerIdBuffer=Buffer.from(peerId,"hex"):(peerIdBuffer=peerId,peerId=peerIdBuffer.toString("hex")),20!==infoHashBuffer.length||20!==peerIdBuffer.length)throw new Error("infoHash and peerId MUST have length 20");this._debug("handshake i=%s p=%s exts=%o",infoHash,peerId,extensions);const reserved=Buffer.from(MESSAGE_RESERVED);reserved[5]|=16,extensions&&extensions.dht&&(reserved[7]|=1),this._push(Buffer.concat([MESSAGE_PROTOCOL,reserved,infoHashBuffer,peerIdBuffer])),this._handshakeSent=!0,this.peerExtensions.extended&&!this._extendedHandshakeSent&&this._sendExtendedHandshake()}_sendExtendedHandshake(){const msg=Object.assign({},this.extendedHandshake);for(const ext in msg.m={},this.extendedMapping){const name=this.extendedMapping[ext];msg.m[name]=+ext}this.extended(0,bencode.encode(msg)),this._extendedHandshakeSent=!0}choke(){if(!this.amChoking){for(this.amChoking=!0,this._debug("choke");this.peerRequests.length;)this.peerRequests.pop();this._push(MESSAGE_CHOKE)}}unchoke(){this.amChoking&&(this.amChoking=!1,this._debug("unchoke"),this._push(MESSAGE_UNCHOKE))}interested(){this.amInterested||(this.amInterested=!0,this._debug("interested"),this._push(MESSAGE_INTERESTED))}uninterested(){this.amInterested&&(this.amInterested=!1,this._debug("uninterested"),this._push(MESSAGE_UNINTERESTED))}have(index){this._debug("have %d",index),this._message(4,[index],null)}bitfield(bitfield){this._debug("bitfield"),Buffer.isBuffer(bitfield)||(bitfield=bitfield.buffer),this._message(5,[],bitfield)}request(index,offset,length,cb){return cb||(cb=()=>{}),this._finished?cb(new Error("wire is closed")):this.peerChoking?cb(new Error("peer is choking")):void(this._debug("request index=%d offset=%d length=%d",index,offset,length),this.requests.push(new Request(index,offset,length,cb)),this._updateTimeout(),this._message(6,[index,offset,length],null))}piece(index,offset,buffer){this._debug("piece index=%d offset=%d",index,offset),this.uploaded+=buffer.length,this.uploadSpeed(buffer.length),this.emit("upload",buffer.length),this._message(7,[index,offset],buffer)}cancel(index,offset,length){this._debug("cancel index=%d offset=%d length=%d",index,offset,length),this._callback(this._pull(this.requests,index,offset,length),new Error("request was cancelled"),null),this._message(8,[index,offset,length],null)}port(port){this._debug("port %d",port);const message=Buffer.from(MESSAGE_PORT);message.writeUInt16BE(port,5),this._push(message)}extended(ext,obj){if(this._debug("extended ext=%s",ext),"string"==typeof ext&&this.peerExtendedMapping[ext]&&(ext=this.peerExtendedMapping[ext]),"number"==typeof ext){const extId=Buffer.from([ext]),buf=Buffer.isBuffer(obj)?obj:bencode.encode(obj);this._message(20,[],Buffer.concat([extId,buf]))}else throw new Error(`Unrecognized extension: ${ext}`)}_read(){}_message(id,numbers,data){const dataLength=data?data.length:0,buffer=Buffer.allocUnsafe(5+4*numbers.length);buffer.writeUInt32BE(buffer.length+dataLength-4,0),buffer[4]=id;for(let i=0;irequest===this._pull(this.peerRequests,index,offset,length)?err?this._debug("error satisfying request index=%d offset=%d length=%d (%s)",index,offset,length,err.message):void this.piece(index,offset,buffer):void 0,request=new Request(index,offset,length,respond);this.peerRequests.push(request),this.emit("request",index,offset,length,respond)}_onPiece(index,offset,buffer){this._debug("got piece index=%d offset=%d",index,offset),this._callback(this._pull(this.requests,index,offset,buffer.length),null,buffer),this.downloaded+=buffer.length,this.downloadSpeed(buffer.length),this.emit("download",buffer.length),this.emit("piece",index,offset,buffer)}_onCancel(index,offset,length){this._debug("got cancel index=%d offset=%d length=%d",index,offset,length),this._pull(this.peerRequests,index,offset,length),this.emit("cancel",index,offset,length)}_onPort(port){this._debug("got port %d",port),this.emit("port",port)}_onExtended(ext,buf){if(0===ext){let info;try{info=bencode.decode(buf)}catch(err){this._debug("ignoring invalid extended handshake: %s",err.message||err)}if(!info)return;this.peerExtendedHandshake=info;if("object"==typeof info.m)for(var name in info.m)this.peerExtendedMapping[name]=+info.m[name].toString();for(name in this._ext)this.peerExtendedMapping[name]&&this._ext[name].onExtendedHandshake(this.peerExtendedHandshake);this._debug("got extended handshake"),this.emit("extended","handshake",this.peerExtendedHandshake)}else this.extendedMapping[ext]&&(ext=this.extendedMapping[ext],this._ext[ext]&&this._ext[ext].onMessage(buf)),this._debug("got extended message ext=%s",ext),this.emit("extended",ext,buf)}_onTimeout(){this._debug("request timed out"),this._callback(this.requests.shift(),new Error("request has timed out"),null),this.emit("timeout")}_write(data,encoding,cb){for(this._bufferSize+=data.length,this._buffer.push(data);this._bufferSize>=this._parserSize;){const buffer=1===this._buffer.length?this._buffer[0]:Buffer.concat(this._buffer);this._bufferSize-=this._parserSize,this._buffer=this._bufferSize?[buffer.slice(this._parserSize)]:[],this._parser(buffer.slice(0,this._parserSize))}cb(null)}_callback(request,err,buffer){request&&(this._clearTimeout(),!this.peerChoking&&!this._finished&&this._updateTimeout(),request.callback(err,buffer))}_clearTimeout(){this._timeout&&(clearTimeout(this._timeout),this._timeout=null)}_updateTimeout(){this._timeoutMs&&this.requests.length&&!this._timeout&&(this._timeout=setTimeout(()=>this._onTimeout(),this._timeoutMs),this._timeoutUnref&&this._timeout.unref&&this._timeout.unref())}_parse(size,parser){this._parserSize=size,this._parser=parser}_onMessageLength(buffer){const length=buffer.readUInt32BE(0);0{const pstrlen=buffer.readUInt8(0);this._parse(pstrlen+48,handshake=>{const protocol=handshake.slice(0,pstrlen);return"BitTorrent protocol"===protocol.toString()?void(handshake=handshake.slice(pstrlen),this._onHandshake(handshake.slice(8,28),handshake.slice(28,48),{dht:!!(1&handshake[7]),extended:!!(16&handshake[5])}),this._parse(4,this._onMessageLength)):(this._debug("Error: wire not speaking BitTorrent protocol (%s)",protocol.toString()),void this.end())})})}_onFinish(){for(this._finished=!0,this.push(null);this.read(););for(clearInterval(this._keepAliveInterval),this._parse(Number.MAX_VALUE,()=>{});this.peerRequests.length;)this.peerRequests.pop();for(;this.requests.length;)this._callback(this.requests.pop(),new Error("wire was closed"),null)}_debug(...args){args[0]=`[${this._debugId}] ${args[0]}`,debug(...args)}_pull(requests,piece,offset,length){for(let i=0;i(announceUrl=announceUrl.toString(),"/"===announceUrl[announceUrl.length-1]&&(announceUrl=announceUrl.substring(0,announceUrl.length-1)),announceUrl)),announce=Array.from(new Set(announce));const webrtcSupport=!1!==this._wrtc&&(!!this._wrtc||Peer.WEBRTC_SUPPORT),nextTickWarn=err=>{process.nextTick(()=>{this.emit("warning",err)})};this._trackers=announce.map(announceUrl=>{let parsedUrl;try{parsedUrl=new URL(announceUrl)}catch(err){return nextTickWarn(new Error(`Invalid tracker URL: ${announceUrl}`)),null}const port=parsedUrl.port;if(0>port||65535{tracker.setInterval()})}stop(opts){opts=this._defaultAnnounceOpts(opts),opts.event="stopped",debug("send `stop` %o",opts),this._announce(opts)}complete(opts){opts||(opts={}),opts=this._defaultAnnounceOpts(opts),opts.event="completed",debug("send `complete` %o",opts),this._announce(opts)}update(opts){opts=this._defaultAnnounceOpts(opts),opts.event&&delete opts.event,debug("send `update` %o",opts),this._announce(opts)}_announce(opts){this._trackers.forEach(tracker=>{tracker.announce(opts)})}scrape(opts){debug("send `scrape`"),opts||(opts={}),this._trackers.forEach(tracker=>{tracker.scrape(opts)})}setInterval(intervalMs){debug("setInterval %d",intervalMs),this._trackers.forEach(tracker=>{tracker.setInterval(intervalMs)})}destroy(cb){if(!this.destroyed){this.destroyed=!0,debug("destroy");const tasks=this._trackers.map(tracker=>cb=>{tracker.destroy(cb)});parallel(tasks,cb),this._trackers=[],this._getAnnounceOpts=null}}_defaultAnnounceOpts(opts={}){return null==opts.numwant&&(opts.numwant=common.DEFAULT_ANNOUNCE_PEERS),null==opts.uploaded&&(opts.uploaded=0),null==opts.downloaded&&(opts.downloaded=0),this._getAnnounceOpts&&(opts=Object.assign({},opts,this._getAnnounceOpts())),opts}}Client.scrape=(opts,cb)=>{if(cb=once(cb),!opts.infoHash)throw new Error("Option `infoHash` is required");if(!opts.announce)throw new Error("Option `announce` is required");const clientOpts=Object.assign({},opts,{infoHash:Array.isArray(opts.infoHash)?opts.infoHash[0]:opts.infoHash,peerId:Buffer.from("01234567890123456789"),port:6881}),client=new Client(clientOpts);client.once("error",cb),client.once("warning",cb);let len=Array.isArray(opts.infoHash)?opts.infoHash.length:1;const results={};return client.on("scrape",data=>{if(len-=1,results[data.infoHash]=data,0===len){client.destroy();const keys=Object.keys(results);1===keys.length?cb(null,results[keys[0]]):cb(null,results)}}),opts.infoHash=Array.isArray(opts.infoHash)?opts.infoHash.map(infoHash=>Buffer.from(infoHash,"hex")):Buffer.from(opts.infoHash,"hex"),client.scrape({infoHash:opts.infoHash}),client},module.exports=Client}).call(this)}).call(this,require("_process"),require("buffer").Buffer)},{"./lib/client/http-tracker":22,"./lib/client/udp-tracker":22,"./lib/client/websocket-tracker":18,"./lib/common":19,_process:62,buffer:24,debug:33,events:25,once:59,"run-parallel":90,"simple-peer":95}],17:[function(require,module){const EventEmitter=require("events");module.exports=class Tracker extends EventEmitter{constructor(client,announceUrl){super(),this.client=client,this.announceUrl=announceUrl,this.interval=null,this.destroyed=!1}setInterval(intervalMs){null==intervalMs&&(intervalMs=this.DEFAULT_ANNOUNCE_INTERVAL),clearInterval(this.interval),intervalMs&&(this.interval=setInterval(()=>{this.announce(this.client._defaultAnnounceOpts())},intervalMs),this.interval.unref&&this.interval.unref())}}},{events:25}],18:[function(require,module){function noop(){}const debug=require("debug")("bittorrent-tracker:websocket-tracker"),Peer=require("simple-peer"),randombytes=require("randombytes"),Socket=require("simple-websocket"),common=require("../common"),Tracker=require("./tracker"),socketPool={};class WebSocketTracker extends Tracker{constructor(client,announceUrl){super(client,announceUrl),debug("new websocket tracker %s",announceUrl),this.peers={},this.socket=null,this.reconnecting=!1,this.retries=0,this.reconnectTimer=null,this.expectingResponse=!1,this._openSocket()}announce(opts){if(this.destroyed||this.reconnecting)return;if(!this.socket.connected)return void this.socket.once("connect",()=>{this.announce(opts)});const params=Object.assign({},opts,{action:"announce",info_hash:this.client._infoHashBinary,peer_id:this.client._peerIdBinary});if(this._trackerId&&(params.trackerid=this._trackerId),"stopped"===opts.event||"completed"===opts.event)this._send(params);else{const numwant=_Mathmin(opts.numwant,10);this._generateOffers(numwant,offers=>{params.numwant=numwant,params.offers=offers,this._send(params)})}}scrape(opts){if(this.destroyed||this.reconnecting)return;if(!this.socket.connected)return void this.socket.once("connect",()=>{this.scrape(opts)});const infoHashes=Array.isArray(opts.infoHash)&&0infoHash.toString("binary")):opts.infoHash&&opts.infoHash.toString("binary")||this.client._infoHashBinary;this._send({action:"scrape",info_hash:infoHashes})}destroy(cb=noop){function destroyCleanup(){timeout&&(clearTimeout(timeout),timeout=null),socket.removeListener("data",destroyCleanup),socket.destroy(),socket=null}if(this.destroyed)return cb(null);for(const peerId in this.destroyed=!0,clearInterval(this.interval),clearTimeout(this.reconnectTimer),this.peers){const peer=this.peers[peerId];clearTimeout(peer.trackerTimeout),peer.destroy()}if(this.peers=null,this.socket&&(this.socket.removeListener("connect",this._onSocketConnectBound),this.socket.removeListener("data",this._onSocketDataBound),this.socket.removeListener("close",this._onSocketCloseBound),this.socket.removeListener("error",this._onSocketErrorBound),this.socket=null),this._onSocketConnectBound=null,this._onSocketErrorBound=null,this._onSocketDataBound=null,this._onSocketCloseBound=null,socketPool[this.announceUrl]&&(socketPool[this.announceUrl].consumers-=1),0{this._onSocketConnect()},this._onSocketErrorBound=err=>{this._onSocketError(err)},this._onSocketDataBound=data=>{this._onSocketData(data)},this._onSocketCloseBound=()=>{this._onSocketClose()},this.socket=socketPool[this.announceUrl],this.socket?(socketPool[this.announceUrl].consumers+=1,this.socket.connected&&this._onSocketConnectBound()):(this.socket=socketPool[this.announceUrl]=new Socket(this.announceUrl),this.socket.consumers=1,this.socket.once("connect",this._onSocketConnectBound)),this.socket.on("data",this._onSocketDataBound),this.socket.once("close",this._onSocketCloseBound),this.socket.once("error",this._onSocketErrorBound)}_onSocketConnect(){this.destroyed||this.reconnecting&&(this.reconnecting=!1,this.retries=0,this.announce(this.client._defaultAnnounceOpts()))}_onSocketData(data){if(!this.destroyed){this.expectingResponse=!1;try{data=JSON.parse(data)}catch(err){return void this.client.emit("warning",new Error("Invalid tracker response"))}"announce"===data.action?this._onAnnounceResponse(data):"scrape"===data.action?this._onScrapeResponse(data):this._onSocketError(new Error(`invalid action in WS response: ${data.action}`))}}_onAnnounceResponse(data){if(data.info_hash!==this.client._infoHashBinary)return void debug("ignoring websocket data from %s for %s (looking for %s: reused socket)",this.announceUrl,common.binaryToHex(data.info_hash),this.client.infoHash);if(data.peer_id&&data.peer_id===this.client._peerIdBinary)return;debug("received %s from %s for %s",JSON.stringify(data),this.announceUrl,this.client.infoHash);const failure=data["failure reason"];if(failure)return this.client.emit("warning",new Error(failure));const warning=data["warning message"];warning&&this.client.emit("warning",new Error(warning));const interval=data.interval||data["min interval"];interval&&this.setInterval(1e3*interval);const trackerId=data["tracker id"];if(trackerId&&(this._trackerId=trackerId),null!=data.complete){const response=Object.assign({},data,{announce:this.announceUrl,infoHash:common.binaryToHex(data.info_hash)});this.client.emit("update",response)}let peer;if(data.offer&&data.peer_id&&(debug("creating peer (from remote offer)"),peer=this._createPeer(),peer.id=common.binaryToHex(data.peer_id),peer.once("signal",answer=>{const params={action:"announce",info_hash:this.client._infoHashBinary,peer_id:this.client._peerIdBinary,to_peer_id:data.peer_id,answer,offer_id:data.offer_id};this._trackerId&&(params.trackerid=this._trackerId),this._send(params)}),peer.signal(data.offer),this.client.emit("peer",peer)),data.answer&&data.peer_id){const offerId=common.binaryToHex(data.offer_id);peer=this.peers[offerId],peer?(peer.id=common.binaryToHex(data.peer_id),peer.signal(data.answer),this.client.emit("peer",peer),clearTimeout(peer.trackerTimeout),peer.trackerTimeout=null,delete this.peers[offerId]):debug(`got unexpected answer: ${JSON.stringify(data.answer)}`)}}_onScrapeResponse(data){data=data.files||{};const keys=Object.keys(data);return 0===keys.length?void this.client.emit("warning",new Error("invalid scrape response")):void keys.forEach(infoHash=>{const response=Object.assign(data[infoHash],{announce:this.announceUrl,infoHash:common.binaryToHex(infoHash)});this.client.emit("scrape",response)})}_onSocketClose(){this.destroyed||(this.destroy(),this._startReconnectTimer())}_onSocketError(err){this.destroyed||(this.destroy(),this.client.emit("warning",err),this._startReconnectTimer())}_startReconnectTimer(){const ms=_Mathfloor(Math.random()*300000)+_Mathmin(_Mathpow(2,this.retries)*10000,3600000);this.reconnecting=!0,clearTimeout(this.reconnectTimer),this.reconnectTimer=setTimeout(()=>{this.retries++,this._openSocket()},ms),this.reconnectTimer.unref&&this.reconnectTimer.unref(),debug("reconnecting socket in %s ms",ms)}_send(params){if(!this.destroyed){this.expectingResponse=!0;const message=JSON.stringify(params);debug("send %s",message),this.socket.send(message)}}_generateOffers(numwant,cb){function generateOffer(){const offerId=randombytes(20).toString("hex");debug("creating peer (from _generateOffers)");const peer=self.peers[offerId]=self._createPeer({initiator:!0});peer.once("signal",offer=>{offers.push({offer,offer_id:common.hexToBinary(offerId)}),checkDone()}),peer.trackerTimeout=setTimeout(()=>{debug("tracker timeout: destroying peer"),peer.trackerTimeout=null,delete self.peers[offerId],peer.destroy()},50000),peer.trackerTimeout.unref&&peer.trackerTimeout.unref()}function checkDone(){offers.length===numwant&&(debug("generated %s offers",numwant),cb(offers))}const self=this,offers=[];debug("generating %s offers",numwant);for(let i=0;i */module.exports=function(blob,cb){function onLoadEnd(e){reader.removeEventListener("loadend",onLoadEnd,!1),e.error?cb(e.error):cb(null,Buffer.from(reader.result))}if("undefined"==typeof Blob||!(blob instanceof Blob))throw new Error("first argument must be a Blob");if("function"!=typeof cb)throw new Error("second argument must be a function");const reader=new FileReader;reader.addEventListener("loadend",onLoadEnd,!1),reader.readAsArrayBuffer(blob)}}).call(this)}).call(this,require("buffer").Buffer)},{buffer:24}],21:[function(require,module){(function(Buffer){(function(){const{Transform}=require("readable-stream");module.exports=class Block extends Transform{constructor(size,opts={}){super(opts),"object"==typeof size&&(opts=size,size=opts.size),this.size=size||512;const{nopad,zeroPadding=!0}=opts;this._zeroPadding=!nopad&&!!zeroPadding,this._buffered=[],this._bufferedBytes=0}_transform(buf,enc,next){for(this._bufferedBytes+=buf.length,this._buffered.push(buf);this._bufferedBytes>=this.size;){const b=Buffer.concat(this._buffered);this._bufferedBytes-=this.size,this.push(b.slice(0,this.size)),this._buffered=[b.slice(this.size,b.length)]}next()}_flush(){if(this._bufferedBytes&&this._zeroPadding){const zeroes=Buffer.alloc(this.size-this._bufferedBytes);this._buffered.push(zeroes),this.push(Buffer.concat(this._buffered)),this._buffered=null}else this._bufferedBytes&&(this.push(Buffer.concat(this._buffered)),this._buffered=null);this.push(null)}}}).call(this)}).call(this,require("buffer").Buffer)},{buffer:24,"readable-stream":86}],22:[function(){},{}],23:[function(require,module,exports){arguments[4][22][0].apply(exports,arguments)},{dup:22}],24:[function(require,module,exports){(function(){(function(){/*! +(function(f){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=f();else if("function"==typeof define&&define.amd)define([],f);else{var g;g="undefined"==typeof window?"undefined"==typeof global?"undefined"==typeof self?this:self:global:window,g.WebTorrent=f()}})(function(){var _Mathabs=Math.abs,_Mathpow=Math.pow,_Mathfloor=Math.floor,_StringfromCharCode=String.fromCharCode,_Mathceil=Math.ceil,_Mathmax=Math.max,_Mathmin=Math.min,define;return function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i{if(this._notifying=!1,!this.destroyed)return debug("read %s (length %s) (err %s)",p,buffer.length,err&&err.message),err?this._destroy(err):void(this._offset&&(buffer=buffer.slice(this._offset),this._offset=0),this._missing{empty.end()}),empty}const fileStream=new FileStream(this,opts);return this._torrent.select(fileStream._startPiece,fileStream._endPiece,!0,()=>{fileStream._notify()}),eos(fileStream,()=>{this._destroyed||!this._torrent.destroyed&&this._torrent.deselect(fileStream._startPiece,fileStream._endPiece,!0)}),fileStream}getBuffer(cb){streamToBuffer(this.createReadStream(),this.length,cb)}getBlob(cb){if("undefined"==typeof window)throw new Error("browser-only method");streamToBlob(this.createReadStream(),this._getMimeType()).then(blob=>cb(null,blob),err=>cb(err))}getBlobURL(cb){if("undefined"==typeof window)throw new Error("browser-only method");streamToBlobURL(this.createReadStream(),this._getMimeType()).then(blobUrl=>cb(null,blobUrl),err=>cb(err))}appendTo(elem,opts,cb){if("undefined"==typeof window)throw new Error("browser-only method");render.append(this,elem,opts,cb)}renderTo(elem,opts,cb){if("undefined"==typeof window)throw new Error("browser-only method");render.render(this,elem,opts,cb)}_getMimeType(){return render.mime[path.extname(this.name).toLowerCase()]}_destroy(){this._destroyed=!0,this._torrent=null}}module.exports=File}).call(this)}).call(this,require("_process"))},{"./file-stream":1,_process:62,"end-of-stream":35,events:25,path:26,"readable-stream":86,"render-media":87,"stream-to-blob":105,"stream-to-blob-url":104,"stream-with-known-length-to-buffer":106}],3:[function(require,module,exports){const arrayRemove=require("unordered-array-remove"),debug=require("debug")("webtorrent:peer"),Wire=require("bittorrent-protocol"),WebConn=require("./webconn");exports.createWebRTCPeer=(conn,swarm)=>{const peer=new Peer(conn.id,"webrtc");return peer.conn=conn,peer.swarm=swarm,peer.conn.connected?peer.onConnect():(peer.conn.once("connect",()=>{peer.onConnect()}),peer.conn.once("error",err=>{peer.destroy(err)}),peer.startConnectTimeout()),peer},exports.createTCPIncomingPeer=conn=>_createIncomingPeer(conn,"tcpIncoming"),exports.createUTPIncomingPeer=conn=>_createIncomingPeer(conn,"utpIncoming"),exports.createTCPOutgoingPeer=(addr,swarm)=>_createOutgoingPeer(addr,swarm,"tcpOutgoing"),exports.createUTPOutgoingPeer=(addr,swarm)=>_createOutgoingPeer(addr,swarm,"utpOutgoing");const _createIncomingPeer=(conn,type)=>{const addr=`${conn.remoteAddress}:${conn.remotePort}`,peer=new Peer(addr,type);return peer.conn=conn,peer.addr=addr,peer.onConnect(),peer},_createOutgoingPeer=(addr,swarm,type)=>{const peer=new Peer(addr,type);return peer.addr=addr,peer.swarm=swarm,peer};exports.createWebSeedPeer=(url,swarm)=>{const peer=new Peer(url,"webSeed");return peer.swarm=swarm,peer.conn=new WebConn(url,swarm),peer.onConnect(),peer};class Peer{constructor(id,type){this.id=id,this.type=type,debug("new %s Peer %s",type,id),this.addr=null,this.conn=null,this.swarm=null,this.wire=null,this.connected=!1,this.destroyed=!1,this.timeout=null,this.retries=0,this.sentHandshake=!1}onConnect(){if(!this.destroyed){this.connected=!0,debug("Peer %s connected",this.id),clearTimeout(this.connectTimeout);const conn=this.conn;conn.once("end",()=>{this.destroy()}),conn.once("close",()=>{this.destroy()}),conn.once("finish",()=>{this.destroy()}),conn.once("error",err=>{this.destroy(err)});const wire=this.wire=new Wire;wire.type=this.type,wire.once("end",()=>{this.destroy()}),wire.once("close",()=>{this.destroy()}),wire.once("finish",()=>{this.destroy()}),wire.once("error",err=>{this.destroy(err)}),wire.once("handshake",(infoHash,peerId)=>{this.onHandshake(infoHash,peerId)}),this.startHandshakeTimeout(),conn.pipe(wire).pipe(conn),this.swarm&&!this.sentHandshake&&this.handshake()}}onHandshake(infoHash,peerId){if(!this.swarm)return;if(this.destroyed)return;if(this.swarm.destroyed)return this.destroy(new Error("swarm already destroyed"));if(infoHash!==this.swarm.infoHash)return this.destroy(new Error("unexpected handshake info hash for this swarm"));if(peerId===this.swarm.peerId)return this.destroy(new Error("refusing to connect to ourselves"));debug("Peer %s got handshake %s",this.id,infoHash),clearTimeout(this.handshakeTimeout),this.retries=0;let addr=this.addr;!addr&&this.conn.remoteAddress&&this.conn.remotePort&&(addr=`${this.conn.remoteAddress}:${this.conn.remotePort}`),this.swarm._onWire(this.wire,addr);this.swarm&&!this.swarm.destroyed&&(this.sentHandshake||this.handshake())}handshake(){const opts={dht:!this.swarm.private&&!!this.swarm.client.dht};this.wire.handshake(this.swarm.infoHash,this.swarm.client.peerId,opts),this.sentHandshake=!0}startConnectTimeout(){clearTimeout(this.connectTimeout);this.connectTimeout=setTimeout(()=>{this.destroy(new Error("connect timeout"))},{webrtc:25e3,tcpOutgoing:5e3,utpOutgoing:5e3}[this.type]),this.connectTimeout.unref&&this.connectTimeout.unref()}startHandshakeTimeout(){clearTimeout(this.handshakeTimeout),this.handshakeTimeout=setTimeout(()=>{this.destroy(new Error("handshake timeout"))},25e3),this.handshakeTimeout.unref&&this.handshakeTimeout.unref()}destroy(err){if(this.destroyed)return;this.destroyed=!0,this.connected=!1,debug("destroy %s %s (error: %s)",this.type,this.id,err&&(err.message||err)),clearTimeout(this.connectTimeout),clearTimeout(this.handshakeTimeout);const swarm=this.swarm,conn=this.conn,wire=this.wire;this.swarm=null,this.conn=null,this.wire=null,swarm&&wire&&arrayRemove(swarm.wires,swarm.wires.indexOf(wire)),conn&&(conn.on("error",()=>{}),conn.destroy()),wire&&wire.destroy(),swarm&&swarm.removePeer(this.id)}}},{"./webconn":6,"bittorrent-protocol":15,debug:33,"unordered-array-remove":115}],4:[function(require,module){module.exports=class RarityMap{constructor(torrent){this._torrent=torrent,this._numPieces=torrent.pieces.length,this._pieces=Array(this._numPieces),this._onWire=wire=>{this.recalculate(),this._initWire(wire)},this._onWireHave=index=>{this._pieces[index]+=1},this._onWireBitfield=()=>{this.recalculate()},this._torrent.wires.forEach(wire=>{this._initWire(wire)}),this._torrent.on("wire",this._onWire),this.recalculate()}getRarestPiece(pieceFilterFunc){let candidates=[],min=1/0;for(let i=0;i{this._cleanupWireEvents(wire)}),this._torrent=null,this._pieces=null,this._onWire=null,this._onWireHave=null,this._onWireBitfield=null}_initWire(wire){wire._onClose=()=>{this._cleanupWireEvents(wire);for(let i=0;i{this.destroyed||this._onParsedTorrent(parsedTorrent)})):parseTorrent.remote(torrentId,(err,parsedTorrent)=>this.destroyed?void 0:err?this._destroy(err):void this._onParsedTorrent(parsedTorrent))}_onParsedTorrent(parsedTorrent){if(!this.destroyed){if(this._processParsedTorrent(parsedTorrent),!this.infoHash)return this._destroy(new Error("Malformed torrent data: No info hash"));(this.path||(this.path=path.join(TMP,this.infoHash)),this._rechokeIntervalId=setInterval(()=>{this._rechoke()},1e4),this._rechokeIntervalId.unref&&this._rechokeIntervalId.unref(),this.emit("_infoHash",this.infoHash),!this.destroyed)&&(this.emit("infoHash",this.infoHash),this.destroyed||(this.client.listening?this._onListening():this.client.once("listening",()=>{this._onListening()})))}}_processParsedTorrent(parsedTorrent){this._debugId=parsedTorrent.infoHash.toString("hex").substring(0,7),"undefined"!=typeof this.private&&(parsedTorrent.private=this.private),this.announce&&(parsedTorrent.announce=parsedTorrent.announce.concat(this.announce)),this.client.tracker&&global.WEBTORRENT_ANNOUNCE&&!parsedTorrent.private&&(parsedTorrent.announce=parsedTorrent.announce.concat(global.WEBTORRENT_ANNOUNCE)),this.urlList&&(parsedTorrent.urlList=parsedTorrent.urlList.concat(this.urlList)),parsedTorrent.announce=Array.from(new Set(parsedTorrent.announce)),parsedTorrent.urlList=Array.from(new Set(parsedTorrent.urlList)),Object.assign(this,parsedTorrent),this.magnetURI=parseTorrent.toMagnetURI(parsedTorrent),this.torrentFile=parseTorrent.toTorrentFile(parsedTorrent)}_onListening(){this.destroyed||(this.info?this._onMetadata(this):(this.xs&&this._getMetadataFromServer(),this._startDiscovery()))}_startDiscovery(){if(this.discovery||this.destroyed)return;let trackerOpts=this.client.tracker;trackerOpts&&(trackerOpts=Object.assign({},this.client.tracker,{getAnnounceOpts:()=>{const opts={uploaded:this.uploaded,downloaded:this.downloaded,left:_Mathmax(this.length-this.downloaded,0)};return this.client.tracker.getAnnounceOpts&&Object.assign(opts,this.client.tracker.getAnnounceOpts()),this._getAnnounceOpts&&Object.assign(opts,this._getAnnounceOpts()),opts}})),this.peerAddresses&&this.peerAddresses.forEach(peer=>this.addPeer(peer)),this.discovery=new Discovery({infoHash:this.infoHash,announce:this.announce,peerId:this.client.peerId,dht:!this.private&&this.client.dht,tracker:trackerOpts,port:this.client.torrentPort,userAgent:USER_AGENT,lsd:this.client.lsd}),this.discovery.on("error",err=>{this._destroy(err)}),this.discovery.on("peer",(peer,source)=>{this._debug("peer %s discovered via %s",peer,source);"string"==typeof peer&&this.done||this.addPeer(peer)}),this.discovery.on("trackerAnnounce",()=>{this.emit("trackerAnnounce"),0===this.numPeers&&this.emit("noPeers","tracker")}),this.discovery.on("dhtAnnounce",()=>{this.emit("dhtAnnounce"),0===this.numPeers&&this.emit("noPeers","dht")}),this.discovery.on("warning",err=>{this.emit("warning",err)})}_getMetadataFromServer(){function getMetadataFromURL(url,cb){function onResponse(err,res,torrent){if(self.destroyed)return cb(null);if(self.metadata)return cb(null);if(err)return self.emit("warning",new Error(`http error from xs param: ${url}`)),cb(null);if(200!==res.statusCode)return self.emit("warning",new Error(`non-200 status code ${res.statusCode} from xs param: ${url}`)),cb(null);let parsedTorrent;try{parsedTorrent=parseTorrent(torrent)}catch(err){}return parsedTorrent?parsedTorrent.infoHash===self.infoHash?void(self._onMetadata(parsedTorrent),cb(null)):(self.emit("warning",new Error(`got torrent file with incorrect info hash from xs param: ${url}`)),cb(null)):(self.emit("warning",new Error(`got invalid torrent file from xs param: ${url}`)),cb(null))}if(0!==url.indexOf("http://")&&0!==url.indexOf("https://"))return self.emit("warning",new Error(`skipping non-http xs param: ${url}`)),cb(null);let req;try{req=get.concat({url,method:"GET",headers:{"user-agent":USER_AGENT}},onResponse)}catch(err){return self.emit("warning",new Error(`skipping invalid url xs param: ${url}`)),cb(null)}self._xsRequests.push(req)}const self=this,urls=Array.isArray(this.xs)?this.xs:[this.xs],tasks=urls.map(url=>cb=>{getMetadataFromURL(url,cb)});parallel(tasks)}_onMetadata(metadata){if(this.metadata||this.destroyed)return;this._debug("got metadata"),this._xsRequests.forEach(req=>{req.abort()}),this._xsRequests=[];let parsedTorrent;if(metadata&&metadata.infoHash)parsedTorrent=metadata;else try{parsedTorrent=parseTorrent(metadata)}catch(err){return this._destroy(err)}if(this._processParsedTorrent(parsedTorrent),this.metadata=this.torrentFile,this.client.enableWebSeeds&&this.urlList.forEach(url=>{this.addWebSeed(url)}),this._rarityMap=new RarityMap(this),this.store=new ImmediateChunkStore(new this._store(this.pieceLength,{torrent:{infoHash:this.infoHash},files:this.files.map(file=>({path:path.join(this.path,file.path),length:file.length,offset:file.offset})),length:this.length,name:this.infoHash})),this.files=this.files.map(file=>new File(this,file)),this.so?this.files.forEach((v,i)=>{this.so.includes(i)?this.files[i].select():this.files[i].deselect()}):0!==this.pieces.length&&this.select(0,this.pieces.length-1,!1),this._hashes=this.pieces,this.pieces=this.pieces.map((hash,i)=>{const pieceLength=i===this.pieces.length-1?this.lastPieceLength:this.pieceLength;return new Piece(pieceLength)}),this._reservations=this.pieces.map(()=>[]),this.bitfield=new BitField(this.pieces.length),this.wires.forEach(wire=>{wire.ut_metadata&&wire.ut_metadata.setMetadata(this.metadata),this._onWireWithMetadata(wire)}),this.emit("metadata"),!this.destroyed)if(this.skipVerify)this._markAllVerified(),this._onStore();else{const onPiecesVerified=err=>err?this._destroy(err):void(this._debug("done verifying"),this._onStore());this._debug("verifying existing torrent data"),this._fileModtimes&&this._store===FSChunkStore?this.getFileModtimes((err,fileModtimes)=>{if(err)return this._destroy(err);const unchanged=this.files.map((_,index)=>fileModtimes[index]===this._fileModtimes[index]).every(x=>x);unchanged?(this._markAllVerified(),this._onStore()):this._verifyPieces(onPiecesVerified)}):this._verifyPieces(onPiecesVerified)}}getFileModtimes(cb){const ret=[];parallelLimit(this.files.map((file,index)=>cb=>{fs.stat(path.join(this.path,file.path),(err,stat)=>err&&"ENOENT"!==err.code?cb(err):void(ret[index]=stat&&stat.mtime.getTime(),cb(null)))}),FILESYSTEM_CONCURRENCY,err=>{this._debug("done getting file modtimes"),cb(err,ret)})}_verifyPieces(cb){parallelLimit(this.pieces.map((piece,index)=>cb=>this.destroyed?cb(new Error("torrent is destroyed")):void this.store.get(index,(err,buf)=>this.destroyed?cb(new Error("torrent is destroyed")):err?process.nextTick(cb,null):void sha1(buf,hash=>{if(this.destroyed)return cb(new Error("torrent is destroyed"));if(hash===this._hashes[index]){if(!this.pieces[index])return cb(null);this._debug("piece verified %s",index),this._markVerified(index)}else this._debug("piece invalid %s",index);cb(null)}))),FILESYSTEM_CONCURRENCY,cb)}rescanFiles(cb){if(this.destroyed)throw new Error("torrent is destroyed");cb||(cb=noop),this._verifyPieces(err=>err?(this._destroy(err),cb(err)):void(this._checkDone(),cb(null)))}_markAllVerified(){for(let index=0;index{req.abort()}),this._rarityMap&&this._rarityMap.destroy(),this._peers)this.removePeer(id);this.files.forEach(file=>{file instanceof File&&file._destroy()});const tasks=this._servers.map(server=>cb=>{server.destroy(cb)});this.discovery&&tasks.push(cb=>{this.discovery.destroy(cb)}),this.store&&tasks.push(cb=>{opts&&opts.destroyStore?this.store.destroy(cb):this.store.close(cb)}),parallel(tasks,cb),err&&(0===this.listenerCount("error")?this.client.emit("error",err):this.emit("error",err)),this.emit("close"),this.client=null,this.files=[],this.discovery=null,this.store=null,this._rarityMap=null,this._peers=null,this._servers=null,this._xsRequests=null}}addPeer(peer){if(this.destroyed)throw new Error("torrent is destroyed");if(!this.infoHash)throw new Error("addPeer() must not be called before the `infoHash` event");if(this.client.blocked){let host;if("string"==typeof peer){let parts;try{parts=addrToIPPort(peer)}catch(e){return this._debug("ignoring peer: invalid %s",peer),this.emit("invalidPeer",peer),!1}host=parts[0]}else"string"==typeof peer.remoteAddress&&(host=peer.remoteAddress);if(host&&this.client.blocked.contains(host))return this._debug("ignoring peer: blocked %s",peer),"string"!=typeof peer&&peer.destroy(),this.emit("blockedPeer",peer),!1}const wasAdded=!!this._addPeer(peer,this.client.utp?"utp":"tcp");return wasAdded?this.emit("peer",peer):this.emit("invalidPeer",peer),wasAdded}_addPeer(peer,type){if(this.destroyed)return"string"!=typeof peer&&peer.destroy(),null;if("string"==typeof peer&&!this._validAddr(peer))return this._debug("ignoring peer: invalid %s",peer),null;const id=peer&&peer.id||peer;if(this._peers[id])return this._debug("ignoring peer: duplicate (%s)",id),"string"!=typeof peer&&peer.destroy(),null;if(this.paused)return this._debug("ignoring peer: torrent is paused"),"string"!=typeof peer&&peer.destroy(),null;this._debug("add peer %s",id);let newPeer;return newPeer="string"==typeof peer?"utp"===type?Peer.createUTPOutgoingPeer(peer,this):Peer.createTCPOutgoingPeer(peer,this):Peer.createWebRTCPeer(peer,this),this._peers[newPeer.id]=newPeer,this._peersLength+=1,"string"==typeof peer&&(this._queue.push(newPeer),this._drain()),newPeer}addWebSeed(url){if(this.destroyed)throw new Error("torrent is destroyed");if(!/^https?:\/\/.+/.test(url))return this.emit("warning",new Error(`ignoring invalid web seed: ${url}`)),void this.emit("invalidPeer",url);if(this._peers[url])return this.emit("warning",new Error(`ignoring duplicate web seed: ${url}`)),void this.emit("invalidPeer",url);this._debug("add web seed %s",url);const newPeer=Peer.createWebSeedPeer(url,this);this._peers[newPeer.id]=newPeer,this._peersLength+=1,this.emit("peer",url)}_addIncomingPeer(peer){return this.destroyed?peer.destroy(new Error("torrent is destroyed")):this.paused?peer.destroy(new Error("torrent is paused")):void(this._debug("add incoming peer %s",peer.id),this._peers[peer.id]=peer,this._peersLength+=1)}removePeer(peer){const id=peer&&peer.id||peer;peer=this._peers[id];peer&&(this._debug("removePeer %s",id),delete this._peers[id],this._peersLength-=1,peer.destroy(),this._drain())}select(start,end,priority,notify){if(this.destroyed)throw new Error("torrent is destroyed");if(0>start||endb.priority-a.priority),this._updateSelections()}deselect(start,end,priority){if(this.destroyed)throw new Error("torrent is destroyed");priority=+priority||0,this._debug("deselect %s-%s (priority %s)",start,end,priority);for(let i=0;i{this.destroyed||(this.received+=downloaded,this._downloadSpeed(downloaded),this.client._downloadSpeed(downloaded),this.emit("download",downloaded),this.destroyed||this.client.emit("download",downloaded))}),wire.on("upload",uploaded=>{this.destroyed||(this.uploaded+=uploaded,this._uploadSpeed(uploaded),this.client._uploadSpeed(uploaded),this.emit("upload",uploaded),this.destroyed||this.client.emit("upload",uploaded))}),this.wires.push(wire),addr){const parts=addrToIPPort(addr);wire.remoteAddress=parts[0],wire.remotePort=parts[1]}this.client.dht&&this.client.dht.listening&&wire.on("port",port=>this.destroyed||this.client.dht.destroyed?void 0:wire.remoteAddress?0===port||65536{this._debug("wire timeout (%s)",addr),wire.destroy()}),wire.setTimeout(3e4,!0),wire.setKeepAlive(!0),wire.use(utMetadata(this.metadata)),wire.ut_metadata.on("warning",err=>{this._debug("ut_metadata warning: %s",err.message)}),this.metadata||(wire.ut_metadata.on("metadata",metadata=>{this._debug("got metadata via ut_metadata"),this._onMetadata(metadata)}),wire.ut_metadata.fetch()),"function"!=typeof utPex||this.private||(wire.use(utPex()),wire.ut_pex.on("peer",peer=>{this.done||(this._debug("ut_pex: got peer: %s (from %s)",peer,addr),this.addPeer(peer))}),wire.ut_pex.on("dropped",peer=>{const peerObj=this._peers[peer];peerObj&&!peerObj.connected&&(this._debug("ut_pex: dropped peer: %s (from %s)",peer,addr),this.removePeer(peer))}),wire.once("close",()=>{wire.ut_pex.reset()})),this.emit("wire",wire,addr),this.metadata&&process.nextTick(()=>{this._onWireWithMetadata(wire)})}_onWireWithMetadata(wire){let timeoutId=null;const onChokeTimeout=()=>{this.destroyed||wire.destroyed||(this._numQueued>2*(this._numConns-this.numPeers)&&wire.amInterested?wire.destroy():(timeoutId=setTimeout(onChokeTimeout,CHOKE_TIMEOUT),timeoutId.unref&&timeoutId.unref()))};let i;const updateSeedStatus=()=>{if(wire.peerPieces.buffer.length===this.bitfield.buffer.length){for(i=0;i{updateSeedStatus(),this._update(),this._updateWireInterest(wire)}),wire.on("have",()=>{updateSeedStatus(),this._update(),this._updateWireInterest(wire)}),wire.once("interested",()=>{wire.unchoke()}),wire.once("close",()=>{clearTimeout(timeoutId)}),wire.on("choke",()=>{clearTimeout(timeoutId),timeoutId=setTimeout(onChokeTimeout,CHOKE_TIMEOUT),timeoutId.unref&&timeoutId.unref()}),wire.on("unchoke",()=>{clearTimeout(timeoutId),this._update()}),wire.on("request",(index,offset,length,cb)=>length>131072?wire.destroy():void(this.pieces[index]||this.store.get(index,{offset,length},cb))),wire.bitfield(this.bitfield),this._updateWireInterest(wire),wire.peerExtensions.dht&&this.client.dht&&this.client.dht.listening&&wire.port(this.client.dht.address().port),"webSeed"!==wire.type&&(timeoutId=setTimeout(onChokeTimeout,CHOKE_TIMEOUT),timeoutId.unref&&timeoutId.unref()),wire.isSeeder=!1,updateSeedStatus()}_updateSelections(){!this.ready||this.destroyed||(process.nextTick(()=>{this._gcSelections()}),this._updateInterest(),this._update())}_gcSelections(){for(let i=0;ithis._updateWireInterest(wire));prev===this._amInterested||(this._amInterested?this.emit("interested"):this.emit("uninterested"))}_updateWireInterest(wire){let interested=!1;for(let index=0;indexi>=start&&i<=end&&!(i in tried)&&wire.peerPieces.get(i)&&(!rank||rank(i))}function speedRanker(){const speed=wire.downloadSpeed()||1;if(speed>SPEED_THRESHOLD)return()=>!0;const secs=_Mathmax(1,wire.requests.length)*Piece.BLOCK_LENGTH/speed;let tries=10,ptr=0;return index=>{if(!tries||self.bitfield.get(index))return!0;for(let missing=self.pieces[index].missing;ptr=maxOutstandingRequests)return!0;const rank=speedRanker();for(let i=0;ipiece));){for(;self._request(wire,piece,self._critical[piece]||hotswap););if(wire.requests.lengthpiece));){if(self._request(wire,piece,!1))return;tried[piece]=!0,tries+=1}}else for(piece=next.to;piece>=next.from+next.offset;--piece)if(wire.peerPieces.get(piece)&&self._request(wire,piece,!1))return}}();const minOutstandingRequests=getBlockPipelineLength(wire,.5);if(wire.requests.length>=minOutstandingRequests)return;const maxOutstandingRequests=getBlockPipelineLength(wire,PIPELINE_MAX_DURATION);trySelectWire(!1)||trySelectWire(!0)}_rechoke(){if(this.ready){const wireStack=this.wires.map(wire=>({wire,random:Math.random()})).sort((objA,objB)=>{const wireA=objA.wire,wireB=objB.wire;return wireA.downloadSpeed()===wireB.downloadSpeed()?wireA.uploadSpeed()===wireB.uploadSpeed()?wireA.amChoking===wireB.amChoking?objA.random-objB.random:wireA.amChoking?-1:1:wireA.uploadSpeed()-wireB.uploadSpeed():wireA.downloadSpeed()-wireB.downloadSpeed()}).map(obj=>obj.wire);0>=this._rechokeOptimisticTime?this._rechokeOptimisticWire=null:this._rechokeOptimisticTime-=1;for(let numInterestedUnchoked=0;0wire.peerInterested);if(0wire!==this._rechokeOptimisticWire).forEach(wire=>wire.choke())}}_hotswap(wire,index){const speed=wire.downloadSpeed();if(speed=SPEED_THRESHOLD||2*otherSpeed>speed||otherSpeed>minSpeed||(minWire=otherWire,minSpeed=otherSpeed)}if(!minWire)return!1;for(i=0;i{self._update()})}const self=this,numRequests=wire.requests.length,isWebSeed="webSeed"===wire.type;if(self.bitfield.get(index))return!1;const maxOutstandingRequests=isWebSeed?_Mathmin(getPiecePipelineLength(wire,PIPELINE_MAX_DURATION,self.pieceLength),self.maxWebConns):getBlockPipelineLength(wire,PIPELINE_MAX_DURATION);if(numRequests>=maxOutstandingRequests)return!1;const piece=self.pieces[index];let reservation=isWebSeed?piece.reserveRemaining():piece.reserve();if(-1===reservation&&hotswap&&self._hotswap(wire,index)&&(reservation=isWebSeed?piece.reserveRemaining():piece.reserve()),-1===reservation)return!1;let r=self._reservations[index];r||(r=self._reservations[index]=[]);let i=r.indexOf(null);-1===i&&(i=r.length),r[i]=wire;const chunkOffset=piece.chunkOffset(reservation),chunkLength=isWebSeed?piece.chunkLengthRemaining(reservation):piece.chunkLength(reservation);return wire.request(index,chunkOffset,chunkLength,function onChunk(err,chunk){if(self.destroyed)return;if(!self.ready)return self.once("ready",()=>{onChunk(err,chunk)});if(r[i]===wire&&(r[i]=null),piece!==self.pieces[index])return onUpdateTick();if(err)return self._debug("error getting piece %s (offset: %s length: %s) from %s: %s",index,chunkOffset,chunkLength,`${wire.remoteAddress}:${wire.remotePort}`,err.message),isWebSeed?piece.cancelRemaining(reservation):piece.cancel(reservation),void onUpdateTick();if(self._debug("got piece %s (offset: %s length: %s) from %s",index,chunkOffset,chunkLength,`${wire.remoteAddress}:${wire.remotePort}`),!piece.set(reservation,chunk,wire))return onUpdateTick();const buf=piece.flush();sha1(buf,hash=>{if(!self.destroyed){if(hash===self._hashes[index]){if(!self.pieces[index])return;self._debug("piece verified %s",index),self.pieces[index]=null,self._reservations[index]=null,self.bitfield.set(index,!0),self.store.put(index,buf),self.wires.forEach(wire=>{wire.have(index)}),self._checkDone()&&!self.destroyed&&self.discovery.complete()}else self.pieces[index]=new Piece(piece.length),self.emit("warning",new Error(`Piece ${index} failed verification`));onUpdateTick()}})}),!0}_checkDone(){if(this.destroyed)return;this.files.forEach(file=>{if(!file.done){for(let i=file._startPiece;i<=file._endPiece;++i)if(!this.bitfield.get(i))return;file.done=!0,file.emit("done"),this._debug(`file done: ${file.name}`)}});let done=!0;for(let i=0;i{this.load(streams,cb)});Array.isArray(streams)||(streams=[streams]),cb||(cb=noop);const readable=new MultiStream(streams),writable=new ChunkStoreWriteStream(this.store,this.pieceLength);pump(readable,writable,err=>err?cb(err):void(this._markAllVerified(),this._checkDone(),cb(null)))}createServer(requestListener){if("function"!=typeof Server)throw new Error("node.js-only method");if(this.destroyed)throw new Error("torrent is destroyed");const server=new Server(this,requestListener);return this._servers.push(server),server}pause(){this.destroyed||(this._debug("pause"),this.paused=!0)}resume(){this.destroyed||(this._debug("resume"),this.paused=!1,this._drain())}_debug(){const args=[].slice.call(arguments);args[0]=`[${this.client?this.client._debugId:"No Client"}] [${this._debugId}] ${args[0]}`,debug(...args)}_drain(){if(this._debug("_drain numConns %s maxConns %s",this._numConns,this.client.maxConns),"function"!=typeof net.connect||this.destroyed||this.paused||this._numConns>=this.client.maxConns)return;this._debug("drain (%s queued, %s/%s peers)",this._numQueued,this.numPeers,this.client.maxConns);const peer=this._queue.shift();if(!peer)return;this._debug("%s connect attempt to %s",peer.type,peer.addr);const parts=addrToIPPort(peer.addr),opts={host:parts[0],port:parts[1]};peer.conn="utpOutgoing"===peer.type?utp.connect(opts.port,opts.host):net.connect(opts);const conn=peer.conn;conn.once("connect",()=>{peer.onConnect()}),conn.once("error",err=>{peer.destroy(err)}),peer.startConnectTimeout(),conn.on("close",()=>{if(!this.destroyed){if(peer.retries>=RECONNECT_WAIT.length){if(this.client.utp){const newPeer=this._addPeer(peer.addr,"tcp");newPeer&&(newPeer.retries=0)}else this._debug("conn %s closed: will not re-add (max %s attempts)",peer.addr,RECONNECT_WAIT.length);return}const ms=RECONNECT_WAIT[peer.retries];this._debug("conn %s closed: will re-add to queue in %sms (attempt %s)",peer.addr,ms,peer.retries+1);const reconnectTimeout=setTimeout(()=>{if(!this.destroyed){const newPeer=this._addPeer(peer.addr,this.client.utp?"utp":"tcp");newPeer&&(newPeer.retries=peer.retries+1)}},ms);reconnectTimeout.unref&&reconnectTimeout.unref()}})}_validAddr(addr){let parts;try{parts=addrToIPPort(addr)}catch(e){return!1}const host=parts[0],port=parts[1];return 0port&&("127.0.0.1"!==host||port!==this.client.torrentPort)}}module.exports=Torrent}).call(this)}).call(this,require("_process"),"undefined"==typeof global?"undefined"==typeof self?"undefined"==typeof window?{}:window:self:global)},{"../package.json":124,"./file":2,"./peer":3,"./rarity-map":4,"./server":22,_process:62,"addr-to-ip-port":7,bitfield:14,"chunk-store-stream/write":31,debug:33,events:25,fs:23,"fs-chunk-store":49,"immediate-chunk-store":41,multistream:57,net:22,os:22,"parse-torrent":60,path:26,pump:63,"random-iterate":69,"run-parallel":90,"run-parallel-limit":89,"simple-get":94,"simple-sha1":96,speedometer:99,"torrent-discovery":111,"torrent-piece":112,ut_metadata:118,ut_pex:22,"utp-native":22}],6:[function(require,module){(function(Buffer){(function(){const BitField=require("bitfield").default,debug=require("debug")("webtorrent:webconn"),get=require("simple-get"),sha1=require("simple-sha1"),Wire=require("bittorrent-protocol"),VERSION=require("../package.json").version;module.exports=class WebConn extends Wire{constructor(url,torrent){super(),this.url=url,this.webPeerId=sha1.sync(url),this._torrent=torrent,this._init()}_init(){this.setKeepAlive(!0),this.once("handshake",infoHash=>{if(this.destroyed)return;this.handshake(infoHash,this.webPeerId);const numPieces=this._torrent.pieces.length,bitfield=new BitField(numPieces);for(let i=0;i<=numPieces;i++)bitfield.set(i,!0);this.bitfield(bitfield)}),this.once("interested",()=>{debug("interested"),this.unchoke()}),this.on("uninterested",()=>{debug("uninterested")}),this.on("choke",()=>{debug("choke")}),this.on("unchoke",()=>{debug("unchoke")}),this.on("bitfield",()=>{debug("bitfield")}),this.on("request",(pieceIndex,offset,length,callback)=>{debug("request pieceIndex=%d offset=%d length=%d",pieceIndex,offset,length),this.httpRequest(pieceIndex,offset,length,callback)})}httpRequest(pieceIndex,offset,length,cb){const pieceOffset=pieceIndex*this._torrent.pieceLength,rangeStart=pieceOffset+offset,rangeEnd=rangeStart+length-1,files=this._torrent.files;let requests;if(1>=files.length)requests=[{url:this.url,start:rangeStart,end:rangeEnd}];else{const requestedFiles=files.filter(file=>file.offset<=rangeEnd&&file.offset+file.length>rangeStart);if(1>requestedFiles.length)return cb(new Error("Could not find file corresponnding to web seed range request"));requests=requestedFiles.map(requestedFile=>{const fileEnd=requestedFile.offset+requestedFile.length-1,url=this.url+("/"===this.url[this.url.length-1]?"":"/")+requestedFile.path;return{url,fileOffsetInRange:_Mathmax(requestedFile.offset-rangeStart,0),start:_Mathmax(rangeStart-requestedFile.offset,0),end:_Mathmin(fileEnd,rangeEnd-requestedFile.offset)}})}let numRequestsSucceeded=0,hasError=!1,ret;1{function onResponse(res,data){return 200>res.statusCode||300<=res.statusCode?(hasError=!0,cb(new Error(`Unexpected HTTP status code ${res.statusCode}`))):void(debug("Got data of length %d",data.length),1===requests.length?cb(null,data):(data.copy(ret,request.fileOffsetInRange),++numRequestsSucceeded===requests.length&&cb(null,ret)))}const url=request.url,start=request.start,end=request.end;debug("Requesting url=%s pieceIndex=%d offset=%d length=%d start=%d end=%d",url,pieceIndex,offset,length,start,end);const opts={url,method:"GET",headers:{"user-agent":`WebTorrent/${VERSION} (https://webtorrent.io)`,range:`bytes=${start}-${end}`}};get.concat(opts,(err,res,data)=>hasError?void 0:err?"undefined"==typeof window||url.startsWith(`${window.location.origin}/`)?(hasError=!0,cb(err)):get.head(url,(errHead,res)=>hasError?void 0:errHead?(hasError=!0,cb(errHead)):200>res.statusCode||300<=res.statusCode?(hasError=!0,cb(new Error(`Unexpected HTTP status code ${res.statusCode}`))):res.url===url?(hasError=!0,cb(err)):void(opts.url=res.url,get.concat(opts,(err,res,data)=>hasError?void 0:err?(hasError=!0,cb(err)):void onResponse(res,data)))):void onResponse(res,data))})}destroy(){super.destroy(),this._torrent=null}}}).call(this)}).call(this,require("buffer").Buffer)},{"../package.json":124,bitfield:14,"bittorrent-protocol":15,buffer:24,debug:33,"simple-get":94,"simple-sha1":96}],7:[function(require,module){let cache={},size=0;module.exports=function(addr){if(1e5===size&&module.exports.reset(),!cache[addr]){const m=/^\[?([^\]]+)\]?:(\d+)$/.exec(addr);if(!m)throw new Error(`invalid addr: ${addr}`);cache[addr]=[m[1],+m[2]],size+=1}return cache[addr]},module.exports.reset=function(){cache={},size=0}},{}],8:[function(require,module,exports){'use strict';function getLens(b64){var len=b64.length;if(0>16,arr[curByte++]=255&tmp>>8,arr[curByte++]=255&tmp;return 2===placeHoldersLen&&(tmp=revLookup[b64.charCodeAt(i)]<<2|revLookup[b64.charCodeAt(i+1)]>>4,arr[curByte++]=255&tmp),1===placeHoldersLen&&(tmp=revLookup[b64.charCodeAt(i)]<<10|revLookup[b64.charCodeAt(i+1)]<<4|revLookup[b64.charCodeAt(i+2)]>>2,arr[curByte++]=255&tmp>>8,arr[curByte++]=255&tmp),arr}function tripletToBase64(num){return lookup[63&num>>18]+lookup[63&num>>12]+lookup[63&num>>6]+lookup[63&num]}function encodeChunk(uint8,start,end){for(var output=[],i=start,tmp;ilen2?len2:i+maxChunkLength));return 1===extraBytes?(tmp=uint8[len-1],parts.push(lookup[tmp>>2]+lookup[63&tmp<<4]+"==")):2===extraBytes&&(tmp=(uint8[len-2]<<8)+uint8[len-1],parts.push(lookup[tmp>>10]+lookup[63&tmp>>4]+lookup[63&tmp<<2]+"=")),parts.join("")}exports.byteLength=function(b64){var lens=getLens(b64),validLen=lens[0],placeHoldersLen=lens[1];return 3*(validLen+placeHoldersLen)/4-placeHoldersLen},exports.toByteArray=toByteArray,exports.fromByteArray=fromByteArray;for(var lookup=[],revLookup=[],Arr="undefined"==typeof Uint8Array?Array:Uint8Array,code="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",i=0,len=code.length;inum&&48<=num){sum=10*sum+(num-48);continue}if(i!==start||43!==num){if(i===start&&45===num){sign=-1;continue}if(46===num)break;throw new Error("not a number: buffer["+i+"] = "+num)}}return sum*sign}function decode(data,start,end,encoding){return null==data||0===data.length?null:("number"!=typeof start&&null==encoding&&(encoding=start,start=void 0),"number"!=typeof end&&null==encoding&&(encoding=end,end=void 0),decode.position=0,decode.encoding=encoding||null,decode.data=Buffer.isBuffer(data)?data.slice(start,end):Buffer.from(data),decode.bytes=decode.data.length,decode.next())}var Buffer=require("safe-buffer").Buffer;const END_OF_TYPE=101;decode.bytes=0,decode.position=0,decode.data=null,decode.encoding=null,decode.next=function(){switch(decode.data[decode.position]){case 100:return decode.dictionary();case 108:return decode.list();case 105:return decode.integer();default:return decode.buffer();}},decode.find=function(chr){for(var i=decode.position,c=decode.data.length,d=decode.data;iArray.from({length:end-start+1},(cur,idx)=>idx+start);return range.reduce((acc,cur)=>{const r=cur.split("-").map(cur=>parseInt(cur));return acc.concat(generateRange(...r))},[])}module.exports=parseRange,module.exports.parse=parseRange,module.exports.compose=function(range){return range.reduce((acc,cur,idx,arr)=>((0===idx||cur!==arr[idx-1]+1)&&acc.push([]),acc[acc.length-1].push(cur),acc),[]).map(cur=>1low||low>=haystack.length)throw new RangeError("invalid lower bound");if(void 0===high)high=haystack.length-1;else if(high|=0,high=haystack.length)throw new RangeError("invalid upper bound");for(;low<=high;)if(mid=low+(high-low>>>1),cmp=+comparator(haystack[mid],needle,mid,haystack),0>cmp)low=mid+1;else if(0>3;return 0!=num%8&&out++,out}Object.defineProperty(exports,"__esModule",{value:!0});var BitField=function(){function BitField(data,opts){void 0===data&&(data=0);var grow=null===opts||void 0===opts?void 0:opts.grow;this.grow=grow&&isFinite(grow)&&getByteSize(grow)||grow||0,this.buffer="number"==typeof data?new Uint8Array(getByteSize(data)):data}return BitField.prototype.get=function(i){var j=i>>3;return j>i%8)},BitField.prototype.set=function(i,value){void 0===value&&(value=!0);var j=i>>3;if(value){if(this.buffer.length>i%8}else j>i%8))},BitField.prototype.forEach=function(fn,start,end){void 0===start&&(start=0),void 0===end&&(end=8*this.buffer.length);for(var i=start,j=i>>3,y=128>>i%8,byte=this.buffer[j];i>1},BitField}();exports.default=BitField},{}],15:[function(require,module){(function(Buffer){(function(){/*! bittorrent-protocol. MIT License. WebTorrent LLC */const arrayRemove=require("unordered-array-remove"),bencode=require("bencode"),BitField=require("bitfield").default,debug=require("debug")("bittorrent-protocol"),randombytes=require("randombytes"),speedometer=require("speedometer"),stream=require("readable-stream"),MESSAGE_PROTOCOL=Buffer.from("\x13BitTorrent protocol"),MESSAGE_KEEP_ALIVE=Buffer.from([0,0,0,0]),MESSAGE_CHOKE=Buffer.from([0,0,0,1,0]),MESSAGE_UNCHOKE=Buffer.from([0,0,0,1,1]),MESSAGE_INTERESTED=Buffer.from([0,0,0,1,2]),MESSAGE_UNINTERESTED=Buffer.from([0,0,0,1,3]),MESSAGE_RESERVED=[0,0,0,0,0,0,0,0],MESSAGE_PORT=[0,0,0,3,9,0,0];class Request{constructor(piece,offset,length,callback){this.piece=piece,this.offset=offset,this.length=length,this.callback=callback}}class Wire extends stream.Duplex{constructor(){super(),this._debugId=randombytes(4).toString("hex"),this._debug("new wire"),this.peerId=null,this.peerIdBuffer=null,this.type=null,this.amChoking=!0,this.amInterested=!1,this.peerChoking=!0,this.peerInterested=!1,this.peerPieces=new BitField(0,{grow:4e5}),this.peerExtensions={},this.requests=[],this.peerRequests=[],this.extendedMapping={},this.peerExtendedMapping={},this.extendedHandshake={},this.peerExtendedHandshake={},this._ext={},this._nextExt=1,this.uploaded=0,this.downloaded=0,this.uploadSpeed=speedometer(),this.downloadSpeed=speedometer(),this._keepAliveInterval=null,this._timeout=null,this._timeoutMs=0,this.destroyed=!1,this._finished=!1,this._parserSize=0,this._parser=null,this._buffer=[],this._bufferSize=0,this.once("finish",()=>this._onFinish()),this._parseHandshake()}setKeepAlive(enable){this._debug("setKeepAlive %s",enable),clearInterval(this._keepAliveInterval);!1===enable||(this._keepAliveInterval=setInterval(()=>{this.keepAlive()},55e3))}setTimeout(ms,unref){this._debug("setTimeout ms=%d unref=%s",ms,unref),this._clearTimeout(),this._timeoutMs=ms,this._timeoutUnref=!!unref,this._updateTimeout()}destroy(){this.destroyed||(this.destroyed=!0,this._debug("destroy"),this.emit("close"),this.end())}end(...args){this._debug("end"),this._onUninterested(),this._onChoke(),super.end(...args)}use(Extension){function noop(){}const name=Extension.prototype.name;if(!name)throw new Error("Extension class requires a \"name\" property on the prototype");this._debug("use extension.name=%s",name);const ext=this._nextExt,handler=new Extension(this);"function"!=typeof handler.onHandshake&&(handler.onHandshake=noop),"function"!=typeof handler.onExtendedHandshake&&(handler.onExtendedHandshake=noop),"function"!=typeof handler.onMessage&&(handler.onMessage=noop),this.extendedMapping[ext]=name,this._ext[name]=handler,this[name]=handler,this._nextExt+=1}keepAlive(){this._debug("keep-alive"),this._push(MESSAGE_KEEP_ALIVE)}handshake(infoHash,peerId,extensions){let infoHashBuffer,peerIdBuffer;if("string"==typeof infoHash?(infoHash=infoHash.toLowerCase(),infoHashBuffer=Buffer.from(infoHash,"hex")):(infoHashBuffer=infoHash,infoHash=infoHashBuffer.toString("hex")),"string"==typeof peerId?peerIdBuffer=Buffer.from(peerId,"hex"):(peerIdBuffer=peerId,peerId=peerIdBuffer.toString("hex")),20!==infoHashBuffer.length||20!==peerIdBuffer.length)throw new Error("infoHash and peerId MUST have length 20");this._debug("handshake i=%s p=%s exts=%o",infoHash,peerId,extensions);const reserved=Buffer.from(MESSAGE_RESERVED);reserved[5]|=16,extensions&&extensions.dht&&(reserved[7]|=1),this._push(Buffer.concat([MESSAGE_PROTOCOL,reserved,infoHashBuffer,peerIdBuffer])),this._handshakeSent=!0,this.peerExtensions.extended&&!this._extendedHandshakeSent&&this._sendExtendedHandshake()}_sendExtendedHandshake(){const msg=Object.assign({},this.extendedHandshake);for(const ext in msg.m={},this.extendedMapping){const name=this.extendedMapping[ext];msg.m[name]=+ext}this.extended(0,bencode.encode(msg)),this._extendedHandshakeSent=!0}choke(){if(!this.amChoking){for(this.amChoking=!0,this._debug("choke");this.peerRequests.length;)this.peerRequests.pop();this._push(MESSAGE_CHOKE)}}unchoke(){this.amChoking&&(this.amChoking=!1,this._debug("unchoke"),this._push(MESSAGE_UNCHOKE))}interested(){this.amInterested||(this.amInterested=!0,this._debug("interested"),this._push(MESSAGE_INTERESTED))}uninterested(){this.amInterested&&(this.amInterested=!1,this._debug("uninterested"),this._push(MESSAGE_UNINTERESTED))}have(index){this._debug("have %d",index),this._message(4,[index],null)}bitfield(bitfield){this._debug("bitfield"),Buffer.isBuffer(bitfield)||(bitfield=bitfield.buffer),this._message(5,[],bitfield)}request(index,offset,length,cb){return cb||(cb=()=>{}),this._finished?cb(new Error("wire is closed")):this.peerChoking?cb(new Error("peer is choking")):void(this._debug("request index=%d offset=%d length=%d",index,offset,length),this.requests.push(new Request(index,offset,length,cb)),this._updateTimeout(),this._message(6,[index,offset,length],null))}piece(index,offset,buffer){this._debug("piece index=%d offset=%d",index,offset),this.uploaded+=buffer.length,this.uploadSpeed(buffer.length),this.emit("upload",buffer.length),this._message(7,[index,offset],buffer)}cancel(index,offset,length){this._debug("cancel index=%d offset=%d length=%d",index,offset,length),this._callback(this._pull(this.requests,index,offset,length),new Error("request was cancelled"),null),this._message(8,[index,offset,length],null)}port(port){this._debug("port %d",port);const message=Buffer.from(MESSAGE_PORT);message.writeUInt16BE(port,5),this._push(message)}extended(ext,obj){if(this._debug("extended ext=%s",ext),"string"==typeof ext&&this.peerExtendedMapping[ext]&&(ext=this.peerExtendedMapping[ext]),"number"==typeof ext){const extId=Buffer.from([ext]),buf=Buffer.isBuffer(obj)?obj:bencode.encode(obj);this._message(20,[],Buffer.concat([extId,buf]))}else throw new Error(`Unrecognized extension: ${ext}`)}_read(){}_message(id,numbers,data){const dataLength=data?data.length:0,buffer=Buffer.allocUnsafe(5+4*numbers.length);buffer.writeUInt32BE(buffer.length+dataLength-4,0),buffer[4]=id;for(let i=0;irequest===this._pull(this.peerRequests,index,offset,length)?err?this._debug("error satisfying request index=%d offset=%d length=%d (%s)",index,offset,length,err.message):void this.piece(index,offset,buffer):void 0,request=new Request(index,offset,length,respond);this.peerRequests.push(request),this.emit("request",index,offset,length,respond)}_onPiece(index,offset,buffer){this._debug("got piece index=%d offset=%d",index,offset),this._callback(this._pull(this.requests,index,offset,buffer.length),null,buffer),this.downloaded+=buffer.length,this.downloadSpeed(buffer.length),this.emit("download",buffer.length),this.emit("piece",index,offset,buffer)}_onCancel(index,offset,length){this._debug("got cancel index=%d offset=%d length=%d",index,offset,length),this._pull(this.peerRequests,index,offset,length),this.emit("cancel",index,offset,length)}_onPort(port){this._debug("got port %d",port),this.emit("port",port)}_onExtended(ext,buf){if(0===ext){let info;try{info=bencode.decode(buf)}catch(err){this._debug("ignoring invalid extended handshake: %s",err.message||err)}if(!info)return;this.peerExtendedHandshake=info;if("object"==typeof info.m)for(var name in info.m)this.peerExtendedMapping[name]=+info.m[name].toString();for(name in this._ext)this.peerExtendedMapping[name]&&this._ext[name].onExtendedHandshake(this.peerExtendedHandshake);this._debug("got extended handshake"),this.emit("extended","handshake",this.peerExtendedHandshake)}else this.extendedMapping[ext]&&(ext=this.extendedMapping[ext],this._ext[ext]&&this._ext[ext].onMessage(buf)),this._debug("got extended message ext=%s",ext),this.emit("extended",ext,buf)}_onTimeout(){this._debug("request timed out"),this._callback(this.requests.shift(),new Error("request has timed out"),null),this.emit("timeout")}_write(data,encoding,cb){for(this._bufferSize+=data.length,this._buffer.push(data);this._bufferSize>=this._parserSize;){const buffer=1===this._buffer.length?this._buffer[0]:Buffer.concat(this._buffer);this._bufferSize-=this._parserSize,this._buffer=this._bufferSize?[buffer.slice(this._parserSize)]:[],this._parser(buffer.slice(0,this._parserSize))}cb(null)}_callback(request,err,buffer){request&&(this._clearTimeout(),!this.peerChoking&&!this._finished&&this._updateTimeout(),request.callback(err,buffer))}_clearTimeout(){this._timeout&&(clearTimeout(this._timeout),this._timeout=null)}_updateTimeout(){this._timeoutMs&&this.requests.length&&!this._timeout&&(this._timeout=setTimeout(()=>this._onTimeout(),this._timeoutMs),this._timeoutUnref&&this._timeout.unref&&this._timeout.unref())}_parse(size,parser){this._parserSize=size,this._parser=parser}_onMessageLength(buffer){const length=buffer.readUInt32BE(0);0{const pstrlen=buffer.readUInt8(0);this._parse(pstrlen+48,handshake=>{const protocol=handshake.slice(0,pstrlen);return"BitTorrent protocol"===protocol.toString()?void(handshake=handshake.slice(pstrlen),this._onHandshake(handshake.slice(8,28),handshake.slice(28,48),{dht:!!(1&handshake[7]),extended:!!(16&handshake[5])}),this._parse(4,this._onMessageLength)):(this._debug("Error: wire not speaking BitTorrent protocol (%s)",protocol.toString()),void this.end())})})}_onFinish(){for(this._finished=!0,this.push(null);this.read(););for(clearInterval(this._keepAliveInterval),this._parse(Number.MAX_VALUE,()=>{});this.peerRequests.length;)this.peerRequests.pop();for(;this.requests.length;)this._callback(this.requests.pop(),new Error("wire was closed"),null)}_debug(...args){args[0]=`[${this._debugId}] ${args[0]}`,debug(...args)}_pull(requests,piece,offset,length){for(let i=0;i(announceUrl=announceUrl.toString(),"/"===announceUrl[announceUrl.length-1]&&(announceUrl=announceUrl.substring(0,announceUrl.length-1)),announceUrl)),announce=Array.from(new Set(announce));const webrtcSupport=!1!==this._wrtc&&(!!this._wrtc||Peer.WEBRTC_SUPPORT),nextTickWarn=err=>{process.nextTick(()=>{this.emit("warning",err)})};this._trackers=announce.map(announceUrl=>{let parsedUrl;try{parsedUrl=new URL(announceUrl)}catch(err){return nextTickWarn(new Error(`Invalid tracker URL: ${announceUrl}`)),null}const port=parsedUrl.port;if(0>port||65535{tracker.setInterval()})}stop(opts){opts=this._defaultAnnounceOpts(opts),opts.event="stopped",debug("send `stop` %o",opts),this._announce(opts)}complete(opts){opts||(opts={}),opts=this._defaultAnnounceOpts(opts),opts.event="completed",debug("send `complete` %o",opts),this._announce(opts)}update(opts){opts=this._defaultAnnounceOpts(opts),opts.event&&delete opts.event,debug("send `update` %o",opts),this._announce(opts)}_announce(opts){this._trackers.forEach(tracker=>{tracker.announce(opts)})}scrape(opts){debug("send `scrape`"),opts||(opts={}),this._trackers.forEach(tracker=>{tracker.scrape(opts)})}setInterval(intervalMs){debug("setInterval %d",intervalMs),this._trackers.forEach(tracker=>{tracker.setInterval(intervalMs)})}destroy(cb){if(!this.destroyed){this.destroyed=!0,debug("destroy");const tasks=this._trackers.map(tracker=>cb=>{tracker.destroy(cb)});parallel(tasks,cb),this._trackers=[],this._getAnnounceOpts=null}}_defaultAnnounceOpts(opts={}){return null==opts.numwant&&(opts.numwant=common.DEFAULT_ANNOUNCE_PEERS),null==opts.uploaded&&(opts.uploaded=0),null==opts.downloaded&&(opts.downloaded=0),this._getAnnounceOpts&&(opts=Object.assign({},opts,this._getAnnounceOpts())),opts}}Client.scrape=(opts,cb)=>{if(cb=once(cb),!opts.infoHash)throw new Error("Option `infoHash` is required");if(!opts.announce)throw new Error("Option `announce` is required");const clientOpts=Object.assign({},opts,{infoHash:Array.isArray(opts.infoHash)?opts.infoHash[0]:opts.infoHash,peerId:Buffer.from("01234567890123456789"),port:6881}),client=new Client(clientOpts);client.once("error",cb),client.once("warning",cb);let len=Array.isArray(opts.infoHash)?opts.infoHash.length:1;const results={};return client.on("scrape",data=>{if(len-=1,results[data.infoHash]=data,0===len){client.destroy();const keys=Object.keys(results);1===keys.length?cb(null,results[keys[0]]):cb(null,results)}}),opts.infoHash=Array.isArray(opts.infoHash)?opts.infoHash.map(infoHash=>Buffer.from(infoHash,"hex")):Buffer.from(opts.infoHash,"hex"),client.scrape({infoHash:opts.infoHash}),client},module.exports=Client}).call(this)}).call(this,require("_process"),require("buffer").Buffer)},{"./lib/client/http-tracker":22,"./lib/client/udp-tracker":22,"./lib/client/websocket-tracker":18,"./lib/common":19,_process:62,buffer:24,debug:33,events:25,once:59,"run-parallel":90,"simple-peer":95}],17:[function(require,module){const EventEmitter=require("events");module.exports=class Tracker extends EventEmitter{constructor(client,announceUrl){super(),this.client=client,this.announceUrl=announceUrl,this.interval=null,this.destroyed=!1}setInterval(intervalMs){null==intervalMs&&(intervalMs=this.DEFAULT_ANNOUNCE_INTERVAL),clearInterval(this.interval),intervalMs&&(this.interval=setInterval(()=>{this.announce(this.client._defaultAnnounceOpts())},intervalMs),this.interval.unref&&this.interval.unref())}}},{events:25}],18:[function(require,module){function noop(){}const debug=require("debug")("bittorrent-tracker:websocket-tracker"),Peer=require("simple-peer"),randombytes=require("randombytes"),Socket=require("simple-websocket"),common=require("../common"),Tracker=require("./tracker"),socketPool={};class WebSocketTracker extends Tracker{constructor(client,announceUrl){super(client,announceUrl),debug("new websocket tracker %s",announceUrl),this.peers={},this.socket=null,this.reconnecting=!1,this.retries=0,this.reconnectTimer=null,this.expectingResponse=!1,this._openSocket()}announce(opts){if(this.destroyed||this.reconnecting)return;if(!this.socket.connected)return void this.socket.once("connect",()=>{this.announce(opts)});const params=Object.assign({},opts,{action:"announce",info_hash:this.client._infoHashBinary,peer_id:this.client._peerIdBinary});if(this._trackerId&&(params.trackerid=this._trackerId),"stopped"===opts.event||"completed"===opts.event)this._send(params);else{const numwant=_Mathmin(opts.numwant,10);this._generateOffers(numwant,offers=>{params.numwant=numwant,params.offers=offers,this._send(params)})}}scrape(opts){if(this.destroyed||this.reconnecting)return;if(!this.socket.connected)return void this.socket.once("connect",()=>{this.scrape(opts)});const infoHashes=Array.isArray(opts.infoHash)&&0infoHash.toString("binary")):opts.infoHash&&opts.infoHash.toString("binary")||this.client._infoHashBinary;this._send({action:"scrape",info_hash:infoHashes})}destroy(cb=noop){function destroyCleanup(){timeout&&(clearTimeout(timeout),timeout=null),socket.removeListener("data",destroyCleanup),socket.destroy(),socket=null}if(this.destroyed)return cb(null);for(const peerId in this.destroyed=!0,clearInterval(this.interval),clearTimeout(this.reconnectTimer),this.peers){const peer=this.peers[peerId];clearTimeout(peer.trackerTimeout),peer.destroy()}if(this.peers=null,this.socket&&(this.socket.removeListener("connect",this._onSocketConnectBound),this.socket.removeListener("data",this._onSocketDataBound),this.socket.removeListener("close",this._onSocketCloseBound),this.socket.removeListener("error",this._onSocketErrorBound),this.socket=null),this._onSocketConnectBound=null,this._onSocketErrorBound=null,this._onSocketDataBound=null,this._onSocketCloseBound=null,socketPool[this.announceUrl]&&(socketPool[this.announceUrl].consumers-=1),0{this._onSocketConnect()},this._onSocketErrorBound=err=>{this._onSocketError(err)},this._onSocketDataBound=data=>{this._onSocketData(data)},this._onSocketCloseBound=()=>{this._onSocketClose()},this.socket=socketPool[this.announceUrl],this.socket?(socketPool[this.announceUrl].consumers+=1,this.socket.connected&&this._onSocketConnectBound()):(this.socket=socketPool[this.announceUrl]=new Socket(this.announceUrl),this.socket.consumers=1,this.socket.once("connect",this._onSocketConnectBound)),this.socket.on("data",this._onSocketDataBound),this.socket.once("close",this._onSocketCloseBound),this.socket.once("error",this._onSocketErrorBound)}_onSocketConnect(){this.destroyed||this.reconnecting&&(this.reconnecting=!1,this.retries=0,this.announce(this.client._defaultAnnounceOpts()))}_onSocketData(data){if(!this.destroyed){this.expectingResponse=!1;try{data=JSON.parse(data)}catch(err){return void this.client.emit("warning",new Error("Invalid tracker response"))}"announce"===data.action?this._onAnnounceResponse(data):"scrape"===data.action?this._onScrapeResponse(data):this._onSocketError(new Error(`invalid action in WS response: ${data.action}`))}}_onAnnounceResponse(data){if(data.info_hash!==this.client._infoHashBinary)return void debug("ignoring websocket data from %s for %s (looking for %s: reused socket)",this.announceUrl,common.binaryToHex(data.info_hash),this.client.infoHash);if(data.peer_id&&data.peer_id===this.client._peerIdBinary)return;debug("received %s from %s for %s",JSON.stringify(data),this.announceUrl,this.client.infoHash);const failure=data["failure reason"];if(failure)return this.client.emit("warning",new Error(failure));const warning=data["warning message"];warning&&this.client.emit("warning",new Error(warning));const interval=data.interval||data["min interval"];interval&&this.setInterval(1e3*interval);const trackerId=data["tracker id"];if(trackerId&&(this._trackerId=trackerId),null!=data.complete){const response=Object.assign({},data,{announce:this.announceUrl,infoHash:common.binaryToHex(data.info_hash)});this.client.emit("update",response)}let peer;if(data.offer&&data.peer_id&&(debug("creating peer (from remote offer)"),peer=this._createPeer(),peer.id=common.binaryToHex(data.peer_id),peer.once("signal",answer=>{const params={action:"announce",info_hash:this.client._infoHashBinary,peer_id:this.client._peerIdBinary,to_peer_id:data.peer_id,answer,offer_id:data.offer_id};this._trackerId&&(params.trackerid=this._trackerId),this._send(params)}),peer.signal(data.offer),this.client.emit("peer",peer)),data.answer&&data.peer_id){const offerId=common.binaryToHex(data.offer_id);peer=this.peers[offerId],peer?(peer.id=common.binaryToHex(data.peer_id),peer.signal(data.answer),this.client.emit("peer",peer),clearTimeout(peer.trackerTimeout),peer.trackerTimeout=null,delete this.peers[offerId]):debug(`got unexpected answer: ${JSON.stringify(data.answer)}`)}}_onScrapeResponse(data){data=data.files||{};const keys=Object.keys(data);return 0===keys.length?void this.client.emit("warning",new Error("invalid scrape response")):void keys.forEach(infoHash=>{const response=Object.assign(data[infoHash],{announce:this.announceUrl,infoHash:common.binaryToHex(infoHash)});this.client.emit("scrape",response)})}_onSocketClose(){this.destroyed||(this.destroy(),this._startReconnectTimer())}_onSocketError(err){this.destroyed||(this.destroy(),this.client.emit("warning",err),this._startReconnectTimer())}_startReconnectTimer(){const ms=_Mathfloor(Math.random()*300000)+_Mathmin(_Mathpow(2,this.retries)*10000,3600000);this.reconnecting=!0,clearTimeout(this.reconnectTimer),this.reconnectTimer=setTimeout(()=>{this.retries++,this._openSocket()},ms),this.reconnectTimer.unref&&this.reconnectTimer.unref(),debug("reconnecting socket in %s ms",ms)}_send(params){if(!this.destroyed){this.expectingResponse=!0;const message=JSON.stringify(params);debug("send %s",message),this.socket.send(message)}}_generateOffers(numwant,cb){function generateOffer(){const offerId=randombytes(20).toString("hex");debug("creating peer (from _generateOffers)");const peer=self.peers[offerId]=self._createPeer({initiator:!0});peer.once("signal",offer=>{offers.push({offer,offer_id:common.hexToBinary(offerId)}),checkDone()}),peer.trackerTimeout=setTimeout(()=>{debug("tracker timeout: destroying peer"),peer.trackerTimeout=null,delete self.peers[offerId],peer.destroy()},50000),peer.trackerTimeout.unref&&peer.trackerTimeout.unref()}function checkDone(){offers.length===numwant&&(debug("generated %s offers",numwant),cb(offers))}const self=this,offers=[];debug("generating %s offers",numwant);for(let i=0;i */module.exports=function(blob,cb){function onLoadEnd(e){reader.removeEventListener("loadend",onLoadEnd,!1),e.error?cb(e.error):cb(null,Buffer.from(reader.result))}if("undefined"==typeof Blob||!(blob instanceof Blob))throw new Error("first argument must be a Blob");if("function"!=typeof cb)throw new Error("second argument must be a function");const reader=new FileReader;reader.addEventListener("loadend",onLoadEnd,!1),reader.readAsArrayBuffer(blob)}}).call(this)}).call(this,require("buffer").Buffer)},{buffer:24}],21:[function(require,module){(function(Buffer){(function(){const{Transform}=require("readable-stream");module.exports=class Block extends Transform{constructor(size,opts={}){super(opts),"object"==typeof size&&(opts=size,size=opts.size),this.size=size||512;const{nopad,zeroPadding=!0}=opts;this._zeroPadding=!nopad&&!!zeroPadding,this._buffered=[],this._bufferedBytes=0}_transform(buf,enc,next){for(this._bufferedBytes+=buf.length,this._buffered.push(buf);this._bufferedBytes>=this.size;){const b=Buffer.concat(this._buffered);this._bufferedBytes-=this.size,this.push(b.slice(0,this.size)),this._buffered=[b.slice(this.size,b.length)]}next()}_flush(){if(this._bufferedBytes&&this._zeroPadding){const zeroes=Buffer.alloc(this.size-this._bufferedBytes);this._buffered.push(zeroes),this.push(Buffer.concat(this._buffered)),this._buffered=null}else this._bufferedBytes&&(this.push(Buffer.concat(this._buffered)),this._buffered=null);this.push(null)}}}).call(this)}).call(this,require("buffer").Buffer)},{buffer:24,"readable-stream":86}],22:[function(){},{}],23:[function(require,module,exports){arguments[4][22][0].apply(exports,arguments)},{dup:22}],24:[function(require,module,exports){(function(){(function(){/*! * The buffer module from node.js, for the browser. * * @author Feross Aboukhadijeh * @license MIT - */'use strict';function createBuffer(length){if(2147483647size)throw new RangeError("The value \""+size+"\" is invalid for option \"size\"")}function alloc(size,fill,encoding){return assertSize(size),0>=size?createBuffer(size):void 0===fill?createBuffer(size):"string"==typeof encoding?createBuffer(size).fill(fill,encoding):createBuffer(size).fill(fill)}function allocUnsafe(size){return assertSize(size),createBuffer(0>size?0:0|checked(size))}function fromString(string,encoding){if(("string"!=typeof encoding||""===encoding)&&(encoding="utf8"),!Buffer.isEncoding(encoding))throw new TypeError("Unknown encoding: "+encoding);var length=0|byteLength(string,encoding),buf=createBuffer(length),actual=buf.write(string,encoding);return actual!==length&&(buf=buf.slice(0,actual)),buf}function fromArrayLike(array){for(var length=0>array.length?0:0|checked(array.length),buf=createBuffer(length),i=0;ibyteOffset||array.byteLength=2147483647)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+2147483647 .toString(16)+" bytes");return 0|length}function byteLength(string,encoding){if(Buffer.isBuffer(string))return string.length;if(ArrayBuffer.isView(string)||isInstance(string,ArrayBuffer))return string.byteLength;if("string"!=typeof string)throw new TypeError("The \"string\" argument must be one of type string, Buffer, or ArrayBuffer. Received type "+typeof string);var len=string.length,mustMatch=2>>1;case"base64":return base64ToBytes(string).length;default:if(loweredCase)return mustMatch?-1:utf8ToBytes(string).length;encoding=(""+encoding).toLowerCase(),loweredCase=!0;}}function slowToString(encoding,start,end){var loweredCase=!1;if((void 0===start||0>start)&&(start=0),start>this.length)return"";if((void 0===end||end>this.length)&&(end=this.length),0>=end)return"";if(end>>>=0,start>>>=0,end<=start)return"";for(encoding||(encoding="utf8");;)switch(encoding){case"hex":return hexSlice(this,start,end);case"utf8":case"utf-8":return utf8Slice(this,start,end);case"ascii":return asciiSlice(this,start,end);case"latin1":case"binary":return latin1Slice(this,start,end);case"base64":return base64Slice(this,start,end);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return utf16leSlice(this,start,end);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(encoding+"").toLowerCase(),loweredCase=!0;}}function swap(b,n,m){var i=b[n];b[n]=b[m],b[m]=i}function bidirectionalIndexOf(buffer,val,byteOffset,encoding,dir){if(0===buffer.length)return-1;if("string"==typeof byteOffset?(encoding=byteOffset,byteOffset=0):2147483647byteOffset&&(byteOffset=-2147483648),byteOffset=+byteOffset,numberIsNaN(byteOffset)&&(byteOffset=dir?0:buffer.length-1),0>byteOffset&&(byteOffset=buffer.length+byteOffset),byteOffset>=buffer.length){if(dir)return-1;byteOffset=buffer.length-1}else if(0>byteOffset)if(dir)byteOffset=0;else return-1;if("string"==typeof val&&(val=Buffer.from(val,encoding)),Buffer.isBuffer(val))return 0===val.length?-1:arrayIndexOf(buffer,val,byteOffset,encoding,dir);if("number"==typeof val)return val&=255,"function"==typeof Uint8Array.prototype.indexOf?dir?Uint8Array.prototype.indexOf.call(buffer,val,byteOffset):Uint8Array.prototype.lastIndexOf.call(buffer,val,byteOffset):arrayIndexOf(buffer,[val],byteOffset,encoding,dir);throw new TypeError("val must be string, number or Buffer")}function arrayIndexOf(arr,val,byteOffset,encoding,dir){function read(buf,i){return 1===indexSize?buf[i]:buf.readUInt16BE(i*indexSize)}var indexSize=1,arrLength=arr.length,valLength=val.length;if(void 0!==encoding&&(encoding=(encoding+"").toLowerCase(),"ucs2"===encoding||"ucs-2"===encoding||"utf16le"===encoding||"utf-16le"===encoding)){if(2>arr.length||2>val.length)return-1;indexSize=2,arrLength/=2,valLength/=2,byteOffset/=2}var i;if(dir){var foundIndex=-1;for(i=byteOffset;iarrLength&&(byteOffset=arrLength-valLength),i=byteOffset;0<=i;i--){for(var found=!0,j=0;jremaining&&(length=remaining)):length=remaining;var strLen=string.length;length>strLen/2&&(length=strLen/2);for(var i=0,parsed;ifirstByte&&(codePoint=firstByte):2===bytesPerSequence?(secondByte=buf[i+1],128==(192&secondByte)&&(tempCodePoint=(31&firstByte)<<6|63&secondByte,127tempCodePoint||57343tempCodePoint&&(codePoint=tempCodePoint))):void 0}null===codePoint?(codePoint=65533,bytesPerSequence=1):65535>>10),codePoint=56320|1023&codePoint),res.push(codePoint),i+=bytesPerSequence}return decodeCodePointsArray(res)}function decodeCodePointsArray(codePoints){var len=codePoints.length;if(len<=4096)return _StringfromCharCode.apply(String,codePoints);for(var res="",i=0;istart)&&(start=0),(!end||0>end||end>len)&&(end=len);for(var out="",i=start;ioffset)throw new RangeError("offset is not uint");if(offset+ext>length)throw new RangeError("Trying to access beyond buffer length")}function checkInt(buf,value,offset,ext,max,min){if(!Buffer.isBuffer(buf))throw new TypeError("\"buffer\" argument must be a Buffer instance");if(value>max||valuebuf.length)throw new RangeError("Index out of range")}function checkIEEE754(buf,value,offset,ext){if(offset+ext>buf.length)throw new RangeError("Index out of range");if(0>offset)throw new RangeError("Index out of range")}function writeFloat(buf,value,offset,littleEndian,noAssert){return value=+value,offset>>>=0,noAssert||checkIEEE754(buf,value,offset,4,34028234663852886e22,-34028234663852886e22),ieee754.write(buf,value,offset,littleEndian,23,4),offset+4}function writeDouble(buf,value,offset,littleEndian,noAssert){return value=+value,offset>>>=0,noAssert||checkIEEE754(buf,value,offset,8,17976931348623157e292,-17976931348623157e292),ieee754.write(buf,value,offset,littleEndian,52,8),offset+8}function base64clean(str){if(str=str.split("=")[0],str=str.trim().replace(INVALID_BASE64_RE,""),2>str.length)return"";for(;0!=str.length%4;)str+="=";return str}function toHex(n){return 16>n?"0"+n.toString(16):n.toString(16)}function utf8ToBytes(string,units){units=units||1/0;for(var length=string.length,leadSurrogate=null,bytes=[],i=0,codePoint;icodePoint){if(!leadSurrogate){if(56319codePoint){-1<(units-=3)&&bytes.push(239,191,189),leadSurrogate=codePoint;continue}codePoint=(leadSurrogate-55296<<10|codePoint-56320)+65536}else leadSurrogate&&-1<(units-=3)&&bytes.push(239,191,189);if(leadSurrogate=null,128>codePoint){if(0>(units-=1))break;bytes.push(codePoint)}else if(2048>codePoint){if(0>(units-=2))break;bytes.push(192|codePoint>>6,128|63&codePoint)}else if(65536>codePoint){if(0>(units-=3))break;bytes.push(224|codePoint>>12,128|63&codePoint>>6,128|63&codePoint)}else if(1114112>codePoint){if(0>(units-=4))break;bytes.push(240|codePoint>>18,128|63&codePoint>>12,128|63&codePoint>>6,128|63&codePoint)}else throw new Error("Invalid code point")}return bytes}function asciiToBytes(str){for(var byteArray=[],i=0;i(units-=2));++i)c=str.charCodeAt(i),hi=c>>8,lo=c%256,byteArray.push(lo),byteArray.push(hi);return byteArray}function base64ToBytes(str){return base64.toByteArray(base64clean(str))}function blitBuffer(src,dst,offset,length){for(var i=0;i=dst.length||i>=src.length);++i)dst[i+offset]=src[i];return i}function isInstance(obj,type){return obj instanceof type||null!=obj&&null!=obj.constructor&&null!=obj.constructor.name&&obj.constructor.name===type.name}function numberIsNaN(obj){return obj!==obj}var base64=require("base64-js"),ieee754=require("ieee754");exports.Buffer=Buffer,exports.SlowBuffer=function(length){return+length!=length&&(length=0),Buffer.alloc(+length)},exports.INSPECT_MAX_BYTES=50;exports.kMaxLength=2147483647,Buffer.TYPED_ARRAY_SUPPORT=function(){try{var arr=new Uint8Array(1);return arr.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===arr.foo()}catch(e){return!1}}(),Buffer.TYPED_ARRAY_SUPPORT||"undefined"==typeof console||"function"!=typeof console.error||console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."),Object.defineProperty(Buffer.prototype,"parent",{enumerable:!0,get:function(){return Buffer.isBuffer(this)?this.buffer:void 0}}),Object.defineProperty(Buffer.prototype,"offset",{enumerable:!0,get:function(){return Buffer.isBuffer(this)?this.byteOffset:void 0}}),"undefined"!=typeof Symbol&&null!=Symbol.species&&Buffer[Symbol.species]===Buffer&&Object.defineProperty(Buffer,Symbol.species,{value:null,configurable:!0,enumerable:!1,writable:!1}),Buffer.poolSize=8192,Buffer.from=function(value,encodingOrOffset,length){return from(value,encodingOrOffset,length)},Buffer.prototype.__proto__=Uint8Array.prototype,Buffer.__proto__=Uint8Array,Buffer.alloc=function(size,fill,encoding){return alloc(size,fill,encoding)},Buffer.allocUnsafe=function(size){return allocUnsafe(size)},Buffer.allocUnsafeSlow=function(size){return allocUnsafe(size)},Buffer.isBuffer=function(b){return null!=b&&!0===b._isBuffer&&b!==Buffer.prototype},Buffer.compare=function(a,b){if(isInstance(a,Uint8Array)&&(a=Buffer.from(a,a.offset,a.byteLength)),isInstance(b,Uint8Array)&&(b=Buffer.from(b,b.offset,b.byteLength)),!Buffer.isBuffer(a)||!Buffer.isBuffer(b))throw new TypeError("The \"buf1\", \"buf2\" arguments must be one of type Buffer or Uint8Array");if(a===b)return 0;for(var x=a.length,y=b.length,i=0,len=_Mathmin(x,y);imax&&(str+=" ... "),""},Buffer.prototype.compare=function(target,start,end,thisStart,thisEnd){if(isInstance(target,Uint8Array)&&(target=Buffer.from(target,target.offset,target.byteLength)),!Buffer.isBuffer(target))throw new TypeError("The \"target\" argument must be one of type Buffer or Uint8Array. Received type "+typeof target);if(void 0===start&&(start=0),void 0===end&&(end=target?target.length:0),void 0===thisStart&&(thisStart=0),void 0===thisEnd&&(thisEnd=this.length),0>start||end>target.length||0>thisStart||thisEnd>this.length)throw new RangeError("out of range index");if(thisStart>=thisEnd&&start>=end)return 0;if(thisStart>=thisEnd)return-1;if(start>=end)return 1;if(start>>>=0,end>>>=0,thisStart>>>=0,thisEnd>>>=0,this===target)return 0;for(var x=thisEnd-thisStart,y=end-start,len=_Mathmin(x,y),thisCopy=this.slice(thisStart,thisEnd),targetCopy=target.slice(start,end),i=0;i>>=0,isFinite(length)?(length>>>=0,void 0===encoding&&(encoding="utf8")):(encoding=length,length=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");var remaining=this.length-offset;if((void 0===length||length>remaining)&&(length=remaining),0length||0>offset)||offset>this.length)throw new RangeError("Attempt to write outside buffer bounds");encoding||(encoding="utf8");for(var loweredCase=!1;;)switch(encoding){case"hex":return hexWrite(this,string,offset,length);case"utf8":case"utf-8":return utf8Write(this,string,offset,length);case"ascii":return asciiWrite(this,string,offset,length);case"latin1":case"binary":return latin1Write(this,string,offset,length);case"base64":return base64Write(this,string,offset,length);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ucs2Write(this,string,offset,length);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(""+encoding).toLowerCase(),loweredCase=!0;}},Buffer.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};Buffer.prototype.slice=function(start,end){var len=this.length;start=~~start,end=void 0===end?len:~~end,0>start?(start+=len,0>start&&(start=0)):start>len&&(start=len),0>end?(end+=len,0>end&&(end=0)):end>len&&(end=len),end>>=0,byteLength>>>=0,noAssert||checkOffset(offset,byteLength,this.length);for(var val=this[offset],mul=1,i=0;++i>>=0,byteLength>>>=0,noAssert||checkOffset(offset,byteLength,this.length);for(var val=this[offset+--byteLength],mul=1;0>>=0,noAssert||checkOffset(offset,1,this.length),this[offset]},Buffer.prototype.readUInt16LE=function(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,2,this.length),this[offset]|this[offset+1]<<8},Buffer.prototype.readUInt16BE=function(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,2,this.length),this[offset]<<8|this[offset+1]},Buffer.prototype.readUInt32LE=function(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,4,this.length),(this[offset]|this[offset+1]<<8|this[offset+2]<<16)+16777216*this[offset+3]},Buffer.prototype.readUInt32BE=function(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,4,this.length),16777216*this[offset]+(this[offset+1]<<16|this[offset+2]<<8|this[offset+3])},Buffer.prototype.readIntLE=function(offset,byteLength,noAssert){offset>>>=0,byteLength>>>=0,noAssert||checkOffset(offset,byteLength,this.length);for(var val=this[offset],mul=1,i=0;++i=mul&&(val-=_Mathpow(2,8*byteLength)),val},Buffer.prototype.readIntBE=function(offset,byteLength,noAssert){offset>>>=0,byteLength>>>=0,noAssert||checkOffset(offset,byteLength,this.length);for(var i=byteLength,mul=1,val=this[offset+--i];0=mul&&(val-=_Mathpow(2,8*byteLength)),val},Buffer.prototype.readInt8=function(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,1,this.length),128&this[offset]?-1*(255-this[offset]+1):this[offset]},Buffer.prototype.readInt16LE=function(offset,noAssert){offset>>>=0,noAssert||checkOffset(offset,2,this.length);var val=this[offset]|this[offset+1]<<8;return 32768&val?4294901760|val:val},Buffer.prototype.readInt16BE=function(offset,noAssert){offset>>>=0,noAssert||checkOffset(offset,2,this.length);var val=this[offset+1]|this[offset]<<8;return 32768&val?4294901760|val:val},Buffer.prototype.readInt32LE=function(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,4,this.length),this[offset]|this[offset+1]<<8|this[offset+2]<<16|this[offset+3]<<24},Buffer.prototype.readInt32BE=function(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,4,this.length),this[offset]<<24|this[offset+1]<<16|this[offset+2]<<8|this[offset+3]},Buffer.prototype.readFloatLE=function(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,4,this.length),ieee754.read(this,offset,!0,23,4)},Buffer.prototype.readFloatBE=function(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,4,this.length),ieee754.read(this,offset,!1,23,4)},Buffer.prototype.readDoubleLE=function(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,8,this.length),ieee754.read(this,offset,!0,52,8)},Buffer.prototype.readDoubleBE=function(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,8,this.length),ieee754.read(this,offset,!1,52,8)},Buffer.prototype.writeUIntLE=function(value,offset,byteLength,noAssert){if(value=+value,offset>>>=0,byteLength>>>=0,!noAssert){var maxBytes=_Mathpow(2,8*byteLength)-1;checkInt(this,value,offset,byteLength,maxBytes,0)}var mul=1,i=0;for(this[offset]=255&value;++i>>=0,byteLength>>>=0,!noAssert){var maxBytes=_Mathpow(2,8*byteLength)-1;checkInt(this,value,offset,byteLength,maxBytes,0)}var i=byteLength-1,mul=1;for(this[offset+i]=255&value;0<=--i&&(mul*=256);)this[offset+i]=255&value/mul;return offset+byteLength},Buffer.prototype.writeUInt8=function(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,1,255,0),this[offset]=255&value,offset+1},Buffer.prototype.writeUInt16LE=function(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,2,65535,0),this[offset]=255&value,this[offset+1]=value>>>8,offset+2},Buffer.prototype.writeUInt16BE=function(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,2,65535,0),this[offset]=value>>>8,this[offset+1]=255&value,offset+2},Buffer.prototype.writeUInt32LE=function(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,4,4294967295,0),this[offset+3]=value>>>24,this[offset+2]=value>>>16,this[offset+1]=value>>>8,this[offset]=255&value,offset+4},Buffer.prototype.writeUInt32BE=function(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,4,4294967295,0),this[offset]=value>>>24,this[offset+1]=value>>>16,this[offset+2]=value>>>8,this[offset+3]=255&value,offset+4},Buffer.prototype.writeIntLE=function(value,offset,byteLength,noAssert){if(value=+value,offset>>>=0,!noAssert){var limit=_Mathpow(2,8*byteLength-1);checkInt(this,value,offset,byteLength,limit-1,-limit)}var i=0,mul=1,sub=0;for(this[offset]=255&value;++ivalue&&0===sub&&0!==this[offset+i-1]&&(sub=1),this[offset+i]=255&(value/mul>>0)-sub;return offset+byteLength},Buffer.prototype.writeIntBE=function(value,offset,byteLength,noAssert){if(value=+value,offset>>>=0,!noAssert){var limit=_Mathpow(2,8*byteLength-1);checkInt(this,value,offset,byteLength,limit-1,-limit)}var i=byteLength-1,mul=1,sub=0;for(this[offset+i]=255&value;0<=--i&&(mul*=256);)0>value&&0===sub&&0!==this[offset+i+1]&&(sub=1),this[offset+i]=255&(value/mul>>0)-sub;return offset+byteLength},Buffer.prototype.writeInt8=function(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,1,127,-128),0>value&&(value=255+value+1),this[offset]=255&value,offset+1},Buffer.prototype.writeInt16LE=function(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,2,32767,-32768),this[offset]=255&value,this[offset+1]=value>>>8,offset+2},Buffer.prototype.writeInt16BE=function(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,2,32767,-32768),this[offset]=value>>>8,this[offset+1]=255&value,offset+2},Buffer.prototype.writeInt32LE=function(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,4,2147483647,-2147483648),this[offset]=255&value,this[offset+1]=value>>>8,this[offset+2]=value>>>16,this[offset+3]=value>>>24,offset+4},Buffer.prototype.writeInt32BE=function(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,4,2147483647,-2147483648),0>value&&(value=4294967295+value+1),this[offset]=value>>>24,this[offset+1]=value>>>16,this[offset+2]=value>>>8,this[offset+3]=255&value,offset+4},Buffer.prototype.writeFloatLE=function(value,offset,noAssert){return writeFloat(this,value,offset,!0,noAssert)},Buffer.prototype.writeFloatBE=function(value,offset,noAssert){return writeFloat(this,value,offset,!1,noAssert)},Buffer.prototype.writeDoubleLE=function(value,offset,noAssert){return writeDouble(this,value,offset,!0,noAssert)},Buffer.prototype.writeDoubleBE=function(value,offset,noAssert){return writeDouble(this,value,offset,!1,noAssert)},Buffer.prototype.copy=function(target,targetStart,start,end){if(!Buffer.isBuffer(target))throw new TypeError("argument should be a Buffer");if(start||(start=0),end||0===end||(end=this.length),targetStart>=target.length&&(targetStart=target.length),targetStart||(targetStart=0),0targetStart)throw new RangeError("targetStart out of bounds");if(0>start||start>=this.length)throw new RangeError("Index out of range");if(0>end)throw new RangeError("sourceEnd out of bounds");end>this.length&&(end=this.length),target.length-targetStartcode||"latin1"===encoding)&&(val=code)}}else"number"==typeof val&&(val&=255);if(0>start||this.length>>=0,end=end===void 0?this.length:end>>>0,val||(val=0);var i;if("number"==typeof val)for(i=start;im&&!existing.warned){existing.warned=!0;var w=new Error("Possible EventEmitter memory leak detected. "+existing.length+" "+(type+" listeners added. Use emitter.setMaxListeners() to increase limit"));w.name="MaxListenersExceededWarning",w.emitter=target,w.type=type,w.count=existing.length,ProcessEmitWarning(w)}return target}function onceWrapper(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function _onceWrap(target,type,listener){var state={fired:!1,wrapFn:void 0,target:target,type:type,listener:listener},wrapped=onceWrapper.bind(state);return wrapped.listener=listener,state.wrapFn=wrapped,wrapped}function _listeners(target,type,unwrap){var events=target._events;if(events===void 0)return[];var evlistener=events[type];return void 0===evlistener?[]:"function"==typeof evlistener?unwrap?[evlistener.listener||evlistener]:[evlistener]:unwrap?unwrapListeners(evlistener):arrayClone(evlistener,evlistener.length)}function listenerCount(type){var events=this._events;if(events!==void 0){var evlistener=events[type];if("function"==typeof evlistener)return 1;if(void 0!==evlistener)return evlistener.length}return 0}function arrayClone(arr,n){for(var copy=Array(n),i=0;iarg||NumberIsNaN(arg))throw new RangeError("The value of \"defaultMaxListeners\" is out of range. It must be a non-negative number. Received "+arg+".");defaultMaxListeners=arg}}),EventEmitter.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},EventEmitter.prototype.setMaxListeners=function(n){if("number"!=typeof n||0>n||NumberIsNaN(n))throw new RangeError("The value of \"n\" is out of range. It must be a non-negative number. Received "+n+".");return this._maxListeners=n,this},EventEmitter.prototype.getMaxListeners=function(){return _getMaxListeners(this)},EventEmitter.prototype.emit=function(type){for(var args=[],i=1;iposition)return this;0===position?list.shift():spliceOne(list,position),1===list.length&&(events[type]=list[0]),void 0!==events.removeListener&&this.emit("removeListener",type,originalListener||listener)}return this},EventEmitter.prototype.off=EventEmitter.prototype.removeListener,EventEmitter.prototype.removeAllListeners=function(type){var listeners,events,i;if(events=this._events,void 0===events)return this;if(void 0===events.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==events[type]&&(0==--this._eventsCount?this._events=Object.create(null):delete events[type]),this;if(0===arguments.length){var keys=Object.keys(events),key;for(i=0;ires.length||2!==lastSegmentLength||46!==res.charCodeAt(res.length-1)||46!==res.charCodeAt(res.length-2))if(2length){if(47===to.charCodeAt(toStart+i))return to.slice(toStart+i+1);if(0===i)return to.slice(toStart+i)}else fromLen>length&&(47===from.charCodeAt(fromStart+i)?lastCommonSep=i:0===i&&(lastCommonSep=0));break}var fromCode=from.charCodeAt(fromStart+i),toCode=to.charCodeAt(toStart+i);if(fromCode!==toCode)break;else 47===fromCode&&(lastCommonSep=i)}var out="";for(i=fromStart+lastCommonSep+1;i<=fromEnd;++i)(i===fromEnd||47===from.charCodeAt(i))&&(out+=0===out.length?"..":"/..");return 0=start;--i){if(code=path.charCodeAt(i),47===code){if(!matchedSlash){startPart=i+1;break}continue}-1===end&&(matchedSlash=!1,end=i+1),46===code?-1===startDot?startDot=i:1!==preDotState&&(preDotState=1):-1!==startDot&&(preDotState=-1)}return-1===startDot||-1===end||0===preDotState||1===preDotState&&startDot===end-1&&startDot===startPart+1?-1!==end&&(0===startPart&&isAbsolute?ret.base=ret.name=path.slice(1,end):ret.base=ret.name=path.slice(startPart,end)):(0===startPart&&isAbsolute?(ret.name=path.slice(1,startDot),ret.base=path.slice(1,end)):(ret.name=path.slice(startPart,startDot),ret.base=path.slice(startPart,end)),ret.ext=path.slice(startDot,end)),0size)throw new RangeError("\"size\" argument must not be negative");return Buffer.allocUnsafe?Buffer.allocUnsafe(size):new Buffer(size)}}).call(this)}).call(this,require("buffer").Buffer)},{buffer:24}],28:[function(require,module){(function(Buffer){(function(){var bufferFill=require("buffer-fill"),allocUnsafe=require("buffer-alloc-unsafe");module.exports=function(size,fill,encoding){if("number"!=typeof size)throw new TypeError("\"size\" argument must be a number");if(0>size)throw new RangeError("\"size\" argument must not be negative");if(Buffer.alloc)return Buffer.alloc(size,fill,encoding);var buffer=allocUnsafe(size);return 0===size?buffer:void 0===fill?bufferFill(buffer,0):("string"!=typeof encoding&&(encoding=void 0),bufferFill(buffer,fill,encoding))}}).call(this)}).call(this,require("buffer").Buffer)},{buffer:24,"buffer-alloc-unsafe":27,"buffer-fill":29}],29:[function(require,module){(function(Buffer){(function(){function isSingleByte(val){return 1===val.length&&256>val.charCodeAt(0)}function fillWithNumber(buffer,val,start,end){if(0>start||end>buffer.length)throw new RangeError("Out of range index");return start>>>=0,end=void 0===end?buffer.length:end>>>0,end>start&&buffer.fill(val,start,end),buffer}function fillWithBuffer(buffer,val,start,end){if(0>start||end>buffer.length)throw new RangeError("Out of range index");if(end<=start)return buffer;start>>>=0,end=void 0===end?buffer.length:end>>>0;for(var pos=start,len=val.length;pos<=end-len;)val.copy(buffer,pos),pos+=len;return pos!==end&&val.copy(buffer,pos,0,end-pos),buffer}var hasFullSupport=function(){try{if(!Buffer.isEncoding("latin1"))return!1;var buf=Buffer.alloc?Buffer.alloc(4):new Buffer(4);return buf.fill("ab","ucs2"),"61006200"===buf.toString("hex")}catch(_){return!1}}();module.exports=function(buffer,val,start,end,encoding){if(hasFullSupport)return buffer.fill(val,start,end,encoding);if("number"==typeof val)return fillWithNumber(buffer,val,start,end);if("string"==typeof val){if("string"==typeof start?(encoding=start,start=0,end=buffer.length):"string"==typeof end&&(encoding=end,end=buffer.length),void 0!==encoding&&"string"!=typeof encoding)throw new TypeError("encoding must be a string");if("latin1"===encoding&&(encoding="binary"),"string"==typeof encoding&&!Buffer.isEncoding(encoding))throw new TypeError("Unknown encoding: "+encoding);if(""===val)return fillWithNumber(buffer,0,start,end);if(isSingleByte(val))return fillWithNumber(buffer,val.charCodeAt(0),start,end);val=new Buffer(val,encoding)}return Buffer.isBuffer(val)?fillWithBuffer(buffer,val,start,end):fillWithNumber(buffer,0,start,end)}}).call(this)}).call(this,require("buffer").Buffer)},{buffer:24}],30:[function(require,module){module.exports={100:"Continue",101:"Switching Protocols",102:"Processing",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Unordered Collection",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",509:"Bandwidth Limit Exceeded",510:"Not Extended",511:"Network Authentication Required"}},{}],31:[function(require,module){const BlockStream=require("block-stream2"),stream=require("readable-stream");class ChunkStoreWriteStream extends stream.Writable{constructor(store,chunkLength,opts={}){if(super(opts),!store||!store.put||!store.get)throw new Error("First argument must be an abstract-chunk-store compliant store");if(chunkLength=+chunkLength,!chunkLength)throw new Error("Second argument must be a chunk length");this._blockstream=new BlockStream(chunkLength,{zeroPadding:!1}),this._outstandingPuts=0;let index=0;const onData=chunk=>{this.destroyed||(this._outstandingPuts+=1,store.put(index,chunk,()=>{this._outstandingPuts-=1,0===this._outstandingPuts&&"function"==typeof this._finalCb&&(this._finalCb(null),this._finalCb=null)}),index+=1)};this._blockstream.on("data",onData).on("error",err=>{this.destroy(err)})}_write(chunk,encoding,callback){this._blockstream.write(chunk,encoding,callback)}_final(cb){this._blockstream.end(),this._blockstream.once("end",()=>{0===this._outstandingPuts?cb(null):this._finalCb=cb})}destroy(err){this.destroyed||(this.destroyed=!0,err&&this.emit("error",err),this.emit("close"))}}module.exports=ChunkStoreWriteStream},{"block-stream2":21,"readable-stream":86}],32:[function(require,module){(function(process,global,Buffer){(function(){function flat(arr1){return arr1.reduce((acc,val)=>Array.isArray(val)?acc.concat(flat(val)):acc.concat(val),[])}function _parseInput(input,opts,cb){function processInput(){parallel(input.map(item=>cb=>{const file={};if(isBlob(item))file.getStream=getBlobStream(item),file.length=item.size;else if(Buffer.isBuffer(item))file.getStream=getBufferStream(item),file.length=item.length;else if(isReadable(item))file.getStream=getStreamStream(item,file),file.length=0;else{if("string"==typeof item){if("function"!=typeof getFiles)throw new Error("filesystem paths do not work in the browser");const keepRoot=1err?cb(err):void(files=flat(files),cb(null,files,isSingleFileTorrent)))}if(isFileList(input)&&(input=Array.from(input)),Array.isArray(input)||(input=[input]),0===input.length)throw new Error("invalid input type");input.forEach(item=>{if(null==item)throw new Error(`invalid input type: ${item}`)}),input=input.map(item=>isBlob(item)&&"string"==typeof item.path&&"function"==typeof getFiles?item.path:item),1!==input.length||"string"==typeof input[0]||input[0].name||(input[0].name=opts.name);let commonPrefix=null;input.forEach((item,i)=>{if("string"==typeof item)return;let path=item.fullPath||item.name;path||(path=`Unknown File ${i+1}`,item.unknownName=!0),item.path=path.split("/"),item.path[0]||item.path.shift(),2>item.path.length?commonPrefix=null:0===i&&1{if("string"==typeof item)return!0;const filename=item.path[item.path.length-1];return notHidden(filename)&&junk.not(filename)}),commonPrefix&&input.forEach(item=>{const pathless=(Buffer.isBuffer(item)||isReadable(item))&&!item.path;"string"==typeof item||pathless||item.path.shift()}),!opts.name&&commonPrefix&&(opts.name=commonPrefix),opts.name||input.some(item=>"string"==typeof item?(opts.name=corePath.basename(item),!0):item.unknownName?void 0:(opts.name=item.path[item.path.length-1],!0)),opts.name||(opts.name=`Unnamed Torrent ${Date.now()}`);const numPaths=input.reduce((sum,item)=>sum+ +("string"==typeof item),0);let isSingleFileTorrent=1===input.length;if(1===input.length&&"string"==typeof input[0]){if("function"!=typeof getFiles)throw new Error("filesystem paths do not work in the browser");isFile(input[0],(err,pathIsFile)=>err?cb(err):void(isSingleFileTorrent=pathIsFile,processInput()))}else process.nextTick(()=>{processInput()})}function notHidden(file){return"."!==file[0]}function getPieceList(files,pieceLength,cb){function onData(chunk){length+=chunk.length;const i=pieceNum;sha1(chunk,hash=>{pieces[i]=hash,remainingHashes-=1,maybeDone()}),remainingHashes+=1,pieceNum+=1}function onEnd(){ended=!0,maybeDone()}function onError(err){cleanup(),cb(err)}function cleanup(){multistream.removeListener("error",onError),blockstream.removeListener("data",onData),blockstream.removeListener("end",onEnd),blockstream.removeListener("error",onError)}function maybeDone(){ended&&0===remainingHashes&&(cleanup(),cb(null,Buffer.from(pieces.join(""),"hex"),length))}cb=once(cb);const pieces=[];let length=0;const streams=files.map(file=>file.getStream);let remainingHashes=0,pieceNum=0,ended=!1;const multistream=new MultiStream(streams),blockstream=new BlockStream(pieceLength,{zeroPadding:!1});multistream.on("error",onError),multistream.pipe(blockstream).on("data",onData).on("end",onEnd).on("error",onError)}function onFiles(files,opts,cb){let announceList=opts.announceList;announceList||("string"==typeof opts.announce?announceList=[[opts.announce]]:Array.isArray(opts.announce)&&(announceList=opts.announce.map(u=>[u]))),announceList||(announceList=[]),global.WEBTORRENT_ANNOUNCE&&("string"==typeof global.WEBTORRENT_ANNOUNCE?announceList.push([[global.WEBTORRENT_ANNOUNCE]]):Array.isArray(global.WEBTORRENT_ANNOUNCE)&&(announceList=announceList.concat(global.WEBTORRENT_ANNOUNCE.map(u=>[u])))),opts.announce===void 0&&opts.announceList===void 0&&(announceList=announceList.concat(module.exports.announceList)),"string"==typeof opts.urlList&&(opts.urlList=[opts.urlList]);const torrent={info:{name:opts.name},"creation date":_Mathceil((+opts.creationDate||Date.now())/1e3),encoding:"UTF-8"};0!==announceList.length&&(torrent.announce=announceList[0][0],torrent["announce-list"]=announceList),opts.comment!==void 0&&(torrent.comment=opts.comment),opts.createdBy!==void 0&&(torrent["created by"]=opts.createdBy),opts.private!==void 0&&(torrent.info.private=+opts.private),opts.info!==void 0&&Object.assign(torrent.info,opts.info),opts.sslCert!==void 0&&(torrent.info["ssl-cert"]=opts.sslCert),opts.urlList!==void 0&&(torrent["url-list"]=opts.urlList);const pieceLength=opts.pieceLength||calcPieceLength(files.reduce(sumLength,0));torrent.info["piece length"]=pieceLength,getPieceList(files,pieceLength,(err,pieces,torrentLength)=>err?cb(err):void(torrent.info.pieces=pieces,files.forEach(file=>{delete file.getStream}),opts.singleFileTorrent?torrent.info.length=torrentLength:torrent.info.files=files,cb(null,bencode.encode(torrent))))}function sumLength(sum,file){return sum+file.length}function isBlob(obj){return"undefined"!=typeof Blob&&obj instanceof Blob}function isFileList(obj){return"undefined"!=typeof FileList&&obj instanceof FileList}function isReadable(obj){return"object"==typeof obj&&null!=obj&&"function"==typeof obj.pipe}function getBlobStream(file){return()=>new FileReadStream(file)}function getBufferStream(buffer){return()=>{const s=new stream.PassThrough;return s.end(buffer),s}}function getStreamStream(readable,file){return()=>{const counter=new stream.Transform;return counter._transform=function(buf,enc,done){file.length+=buf.length,this.push(buf),done()},readable.pipe(counter),counter}}/*! create-torrent. MIT License. WebTorrent LLC */const bencode=require("bencode"),BlockStream=require("block-stream2"),calcPieceLength=require("piece-length"),corePath=require("path"),FileReadStream=require("filestream/read"),isFile=require("is-file"),junk=require("junk"),MultiStream=require("multistream"),once=require("once"),parallel=require("run-parallel"),sha1=require("simple-sha1"),stream=require("readable-stream"),getFiles=require("./get-files");module.exports=function(input,opts,cb){"function"==typeof opts&&([opts,cb]=[cb,opts]),opts=opts?Object.assign({},opts):{},_parseInput(input,opts,(err,files,singleFileTorrent)=>err?cb(err):void(opts.singleFileTorrent=singleFileTorrent,onFiles(files,opts,cb)))},module.exports.parseInput=function(input,opts,cb){"function"==typeof opts&&([opts,cb]=[cb,opts]),opts=opts?Object.assign({},opts):{},_parseInput(input,opts,cb)},module.exports.announceList=[["udp://tracker.leechers-paradise.org:6969"],["udp://tracker.coppersurfer.tk:6969"],["udp://tracker.opentrackr.org:1337"],["udp://explodie.org:6969"],["udp://tracker.empire-js.us:1337"],["wss://tracker.btorrent.xyz"],["wss://tracker.openwebtorrent.com"]]}).call(this)}).call(this,require("_process"),"undefined"==typeof global?"undefined"==typeof self?"undefined"==typeof window?{}:window:self:global,require("buffer").Buffer)},{"./get-files":22,_process:62,bencode:11,"block-stream2":21,buffer:24,"filestream/read":37,"is-file":44,junk:46,multistream:57,once:59,path:26,"piece-length":61,"readable-stream":86,"run-parallel":90,"simple-sha1":96}],33:[function(require,module,exports){(function(process){(function(){function load(){let r;try{r=exports.storage.getItem("debug")}catch(error){}return!r&&"undefined"!=typeof process&&"env"in process&&(r=process.env.DEBUG),r}exports.formatArgs=function(args){if(args[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+args[0]+(this.useColors?"%c ":" ")+"+"+module.exports.humanize(this.diff),!this.useColors)return;const c="color: "+this.color;args.splice(1,0,c,"color: inherit");let index=0,lastC=0;args[0].replace(/%[a-zA-Z%]/g,match=>{"%%"===match||(index++,"%c"===match&&(lastC=index))}),args.splice(lastC,0,c)},exports.save=function(namespaces){try{namespaces?exports.storage.setItem("debug",namespaces):exports.storage.removeItem("debug")}catch(error){}},exports.load=load,exports.useColors=function(){return!!("undefined"!=typeof window&&window.process&&("renderer"===window.process.type||window.process.__nwjs))||!("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))&&("undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&31<=parseInt(RegExp.$1,10)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/))},exports.storage=function(){try{return localStorage}catch(error){}}(),exports.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],exports.log=console.debug||console.log||(()=>{}),module.exports=require("./common")(exports);const{formatters}=module.exports;formatters.j=function(v){try{return JSON.stringify(v)}catch(error){return"[UnexpectedJSONParseError]: "+error.message}}}).call(this)}).call(this,require("_process"))},{"./common":34,_process:62}],34:[function(require,module){module.exports=function(env){function createDebug(namespace){function debug(...args){if(!debug.enabled)return;const self=debug,curr=+new Date,ms=curr-(prevTime||curr);self.diff=ms,self.prev=prevTime,self.curr=curr,prevTime=curr,args[0]=createDebug.coerce(args[0]),"string"!=typeof args[0]&&args.unshift("%O");let index=0;args[0]=args[0].replace(/%([a-zA-Z%])/g,(match,format)=>{if("%%"===match)return match;index++;const formatter=createDebug.formatters[format];if("function"==typeof formatter){const val=args[index];match=formatter.call(self,val),args.splice(index,1),index--}return match}),createDebug.formatArgs.call(self,args);const logFn=self.log||createDebug.log;logFn.apply(self,args)}let prevTime;return debug.namespace=namespace,debug.enabled=createDebug.enabled(namespace),debug.useColors=createDebug.useColors(),debug.color=createDebug.selectColor(namespace),debug.destroy=destroy,debug.extend=extend,"function"==typeof createDebug.init&&createDebug.init(debug),createDebug.instances.push(debug),debug}function destroy(){const index=createDebug.instances.indexOf(this);return-1!==index&&(createDebug.instances.splice(index,1),!0)}function extend(namespace,delimiter){const newDebug=createDebug(this.namespace+("undefined"==typeof delimiter?":":delimiter)+namespace);return newDebug.log=this.log,newDebug}function toNamespace(regexp){return regexp.toString().substring(2,regexp.toString().length-2).replace(/\.\*\?$/,"*")}return createDebug.debug=createDebug,createDebug.default=createDebug,createDebug.coerce=function(val){return val instanceof Error?val.stack||val.message:val},createDebug.disable=function(){const namespaces=[...createDebug.names.map(toNamespace),...createDebug.skips.map(toNamespace).map(namespace=>"-"+namespace)].join(",");return createDebug.enable(""),namespaces},createDebug.enable=function(namespaces){createDebug.save(namespaces),createDebug.names=[],createDebug.skips=[];let i;const split=("string"==typeof namespaces?namespaces:"").split(/[\s,]+/),len=split.length;for(i=0;i{createDebug[key]=env[key]}),createDebug.instances=[],createDebug.names=[],createDebug.skips=[],createDebug.formatters={},createDebug.selectColor=function(namespace){let hash=0;for(let i=0;i{this.push(toBuffer(reader.result))},reader.onerror=()=>{this.emit("error",reader.error)},this.reader=reader,this._generateHeaderBlocks(file,opts,(err,blocks)=>err?this.emit("error",err):void(Array.isArray(blocks)&&blocks.forEach(block=>this.push(block)),this._ready=!0,this.emit("_ready")))}_generateHeaderBlocks(file,opts,callback){callback(null,[])}_read(){if(!this._ready)return void this.once("_ready",this._read.bind(this));const startOffset=this._offset;let endOffset=this._offset+this._chunkSize;return endOffset>this._size&&(endOffset=this._size),startOffset===this._size?(this.destroy(),void this.push(null)):void(this.reader.readAsArrayBuffer(this._file.slice(startOffset,endOffset)),this._offset=endOffset)}destroy(){if(this._file=null,this.reader){this.reader.onload=null,this.reader.onerror=null;try{this.reader.abort()}catch(e){}}this.reader=null}}},{"readable-stream":86,"typedarray-to-buffer":113}],38:[function(require,module){module.exports=function(){if("undefined"==typeof window)return null;var wrtc={RTCPeerConnection:window.RTCPeerConnection||window.mozRTCPeerConnection||window.webkitRTCPeerConnection,RTCSessionDescription:window.RTCSessionDescription||window.mozRTCSessionDescription||window.webkitRTCSessionDescription,RTCIceCandidate:window.RTCIceCandidate||window.mozRTCIceCandidate||window.webkitRTCIceCandidate};return wrtc.RTCPeerConnection?wrtc:null}},{}],39:[function(require,module){function validateParams(params){if("string"==typeof params&&(params=url.parse(params)),params.protocol||(params.protocol="https:"),"https:"!==params.protocol)throw new Error("Protocol \""+params.protocol+"\" not supported. Expected \"https:\"");return params}var http=require("http"),url=require("url"),https=module.exports;for(var key in http)http.hasOwnProperty(key)&&(https[key]=http[key]);https.request=function(params,cb){return params=validateParams(params),http.request.call(this,params,cb)},https.get=function(params,cb){return params=validateParams(params),http.get.call(this,params,cb)}},{http:100,url:116}],40:[function(require,module,exports){/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */exports.read=function(buffer,offset,isLE,mLen,nBytes){var eLen=8*nBytes-mLen-1,eMax=(1<>1,nBits=-7,i=isLE?nBytes-1:0,d=isLE?-1:1,s=buffer[offset+i],e,m;for(i+=d,e=s&(1<<-nBits)-1,s>>=-nBits,nBits+=eLen;0>=-nBits,nBits+=mLen;0>1,rt=23===mLen?_Mathpow(2,-24)-_Mathpow(2,-77):0,i=isLE?0:nBytes-1,d=isLE?1:-1,s=0>value||0===value&&0>1/value?1:0,e,m,c;for(value=_Mathabs(value),isNaN(value)||value===1/0?(m=isNaN(value)?1:0,e=eMax):(e=_Mathfloor(_Mathlog(value)/_MathLN),1>value*(c=_Mathpow(2,-e))&&(e--,c*=2),value+=1<=e+eBias?rt/c:rt*_Mathpow(2,1-eBias),2<=value*c&&(e++,c/=2),e+eBias>=eMax?(m=0,e=eMax):1<=e+eBias?(m=(value*c-1)*_Mathpow(2,mLen),e+=eBias):(m=value*_Mathpow(2,eBias-1)*_Mathpow(2,mLen),e=0));8<=mLen;buffer[offset+i]=255&m,i+=d,m/=256,mLen-=8);for(e=e< */const queueMicrotask=require("queue-microtask");module.exports=class ImmediateStore{constructor(store){if(this.store=store,this.chunkLength=store.chunkLength,!this.store||!this.store.get||!this.store.put)throw new Error("First argument must be abstract-chunk-store compliant");this.mem=[]}put(index,buf,cb){this.mem[index]=buf,this.store.put(index,buf,err=>{this.mem[index]=null,cb&&cb(err)})}get(index,opts,cb){if("function"==typeof opts)return this.get(index,null,opts);let memoryBuffer=this.mem[index];if(!memoryBuffer)return this.store.get(index,opts,cb);if(opts){const start=opts.offset||0,end=opts.length?start+opts.length:memoryBuffer.length;memoryBuffer=memoryBuffer.slice(start,end)}queueMicrotask(()=>{cb&&cb(null,memoryBuffer)})}close(cb){this.store.close(cb)}destroy(cb){this.store.destroy(cb)}}},{"queue-microtask":68}],42:[function(require,module){module.exports="function"==typeof Object.create?function(ctor,superCtor){superCtor&&(ctor.super_=superCtor,ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:!1,writable:!0,configurable:!0}}))}:function(ctor,superCtor){if(superCtor){ctor.super_=superCtor;var TempCtor=function(){};TempCtor.prototype=superCtor.prototype,ctor.prototype=new TempCtor,ctor.prototype.constructor=ctor}}},{}],43:[function(require,module){module.exports=function(str){for(var i=0,strLen=str.length;i127)return!1;return!0}},{}],44:[function(require,module){'use strict';function isFileSync(path){return fs.existsSync(path)&&fs.statSync(path).isFile()}var fs=require("fs");module.exports=function(path,cb){return cb?void fs.stat(path,function(err,stats){return err?cb(err):cb(null,stats.isFile())}):isFileSync(path)},module.exports.sync=isFileSync},{fs:23}],45:[function(require,module){function isTypedArray(arr){return isStrictTypedArray(arr)||isLooseTypedArray(arr)}function isStrictTypedArray(arr){return arr instanceof Int8Array||arr instanceof Int16Array||arr instanceof Int32Array||arr instanceof Uint8Array||arr instanceof Uint8ClampedArray||arr instanceof Uint16Array||arr instanceof Uint32Array||arr instanceof Float32Array||arr instanceof Float64Array}function isLooseTypedArray(arr){return names[toString.call(arr)]}module.exports=isTypedArray,isTypedArray.strict=isStrictTypedArray,isTypedArray.loose=isLooseTypedArray;var toString=Object.prototype.toString,names={"[object Int8Array]":!0,"[object Int16Array]":!0,"[object Int32Array]":!0,"[object Uint8Array]":!0,"[object Uint8ClampedArray]":!0,"[object Uint16Array]":!0,"[object Uint32Array]":!0,"[object Float32Array]":!0,"[object Float64Array]":!0}},{}],46:[function(require,module,exports){'use strict';exports.re=()=>{throw new Error("`junk.re` was renamed to `junk.regex`")},exports.regex=new RegExp(["^npm-debug\\.log$","^\\..*\\.swp$","^\\.DS_Store$","^\\.AppleDouble$","^\\.LSOverride$","^Icon\\r$","^\\._.*","^\\.Spotlight-V100(?:$|\\/)","\\.Trashes","^__MACOSX$","~$","^Thumbs\\.db$","^ehthumbs\\.db$","^Desktop\\.ini$","@eaDir$"].join("|")),exports.is=filename=>exports.regex.test(filename),exports.not=filename=>!exports.is(filename),exports.default=module.exports},{}],47:[function(require,module){(function(Buffer){(function(){function magnetURIDecode(uri){const result={},data=uri.split("magnet:?")[1],params=data&&0<=data.length?data.split("&"):[];params.forEach(param=>{const keyval=param.split("=");if(2!==keyval.length)return;const key=keyval[0];let val=keyval[1];"dn"===key&&(val=decodeURIComponent(val).replace(/\+/g," ")),("tr"===key||"xs"===key||"as"===key||"ws"===key)&&(val=decodeURIComponent(val)),"kt"===key&&(val=decodeURIComponent(val).split("+")),"ix"===key&&(val=+val),"so"===key&&(val=bep53Range.parse(decodeURIComponent(val).split(","))),result[key]?(!Array.isArray(result[key])&&(result[key]=[result[key]]),result[key].push(val)):result[key]=val});let m;if(result.xt){const xts=Array.isArray(result.xt)?result.xt:[result.xt];xts.forEach(xt=>{if(m=xt.match(/^urn:btih:(.{40})/))result.infoHash=m[1].toLowerCase();else if(m=xt.match(/^urn:btih:(.{32})/)){const decodedStr=base32.decode(m[1]);result.infoHash=Buffer.from(decodedStr,"binary").toString("hex")}})}if(result.xs){const xss=Array.isArray(result.xs)?result.xs:[result.xs];xss.forEach(xs=>{(m=xs.match(/^urn:btpk:(.{64})/))&&(result.publicKey=m[1].toLowerCase())})}return result.infoHash&&(result.infoHashBuffer=Buffer.from(result.infoHash,"hex")),result.publicKey&&(result.publicKeyBuffer=Buffer.from(result.publicKey,"hex")),result.dn&&(result.name=result.dn),result.kt&&(result.keywords=result.kt),result.announce=[],("string"==typeof result.tr||Array.isArray(result.tr))&&(result.announce=result.announce.concat(result.tr)),result.urlList=[],("string"==typeof result.as||Array.isArray(result.as))&&(result.urlList=result.urlList.concat(result.as)),("string"==typeof result.ws||Array.isArray(result.ws))&&(result.urlList=result.urlList.concat(result.ws)),result.peerAddresses=[],("string"==typeof result["x.pe"]||Array.isArray(result["x.pe"]))&&(result.peerAddresses=result.peerAddresses.concat(result["x.pe"])),result.announce=Array.from(new Set(result.announce)),result.urlList=Array.from(new Set(result.urlList)),result.peerAddresses=Array.from(new Set(result.peerAddresses)),result}module.exports=magnetURIDecode,module.exports.decode=magnetURIDecode,module.exports.encode=function(obj){obj=Object.assign({},obj),obj.infoHashBuffer&&(obj.xt=`urn:btih:${obj.infoHashBuffer.toString("hex")}`),obj.infoHash&&(obj.xt=`urn:btih:${obj.infoHash}`),obj.publicKeyBuffer&&(obj.xs=`urn:btpk:${obj.publicKeyBuffer.toString("hex")}`),obj.publicKey&&(obj.xs=`urn:btpk:${obj.publicKey}`),obj.name&&(obj.dn=obj.name),obj.keywords&&(obj.kt=obj.keywords),obj.announce&&(obj.tr=obj.announce),obj.urlList&&(obj.ws=obj.urlList,delete obj.as),obj.peerAddresses&&(obj["x.pe"]=obj.peerAddresses);let result="magnet:?";return Object.keys(obj).filter(key=>2===key.length||"x.pe"===key).forEach((key,i)=>{const values=Array.isArray(obj[key])?obj[key]:[obj[key]];values.forEach((val,j)=>{(0self._bufferDuration)&&self._cb){var cb=self._cb;self._cb=null,cb()}};MediaSourceStream.prototype._getBufferDuration=function(){for(var self=this,buffered=self._sourceBuffer.buffered,currentTime=self._elem.currentTime,bufferEnd=-1,i=0;icurrentTime)break;else(0<=bufferEnd||currentTime<=end)&&(bufferEnd=end)}var bufferedTime=bufferEnd-currentTime;return 0>bufferedTime&&(bufferedTime=0),bufferedTime}},{inherits:42,"readable-stream":86,"to-arraybuffer":110}],49:[function(require,module){(function(process){(function(){function Storage(chunkLength,opts){if(!(this instanceof Storage))return new Storage(chunkLength,opts);if(opts||(opts={}),this.chunkLength=+chunkLength,!this.chunkLength)throw new Error("First argument must be a chunk length");this.chunks=[],this.closed=!1,this.length=+opts.length||1/0,this.length!==1/0&&(this.lastChunkLength=this.length%this.chunkLength||this.chunkLength,this.lastChunkIndex=_Mathceil(this.length/this.chunkLength)-1)}function nextTick(cb,err,val){process.nextTick(function(){cb&&cb(err,val)})}module.exports=Storage,Storage.prototype.put=function(index,buf,cb){if(this.closed)return nextTick(cb,new Error("Storage is closed"));var isLastChunk=index===this.lastChunkIndex;return isLastChunk&&buf.length!==this.lastChunkLength?nextTick(cb,new Error("Last chunk length must be "+this.lastChunkLength)):isLastChunk||buf.length===this.chunkLength?void(this.chunks[index]=buf,nextTick(cb,null)):nextTick(cb,new Error("Chunk length must be "+this.chunkLength))},Storage.prototype.get=function(index,opts,cb){if("function"==typeof opts)return this.get(index,null,opts);if(this.closed)return nextTick(cb,new Error("Storage is closed"));var buf=this.chunks[index];if(!buf){var err=new Error("Chunk not found");return err.notFound=!0,nextTick(cb,err)}if(!opts)return nextTick(cb,null,buf);var offset=opts.offset||0,len=opts.length||buf.length-offset;nextTick(cb,null,buf.slice(offset,len+offset))},Storage.prototype.close=Storage.prototype.destroy=function(cb){return this.closed?nextTick(cb,new Error("Storage is closed")):void(this.closed=!0,this.chunks=null,nextTick(cb,null))}}).call(this)}).call(this,require("_process"))},{_process:62}],50:[function(require,module,exports){(function(Buffer){(function(){function writeReserved(buf,offset,end){for(var i=offset;i>3:0,mimeCodec=null;return oti&&(mimeCodec=oti.toString(16),audioConfig&&(mimeCodec+="."+audioConfig)),{mimeCodec:mimeCodec,buffer:Buffer.from(buf.slice(0))}},exports.esds.encodingLength=function(box){return box.buffer.length},exports.stsz={},exports.stsz.encode=function(box,buf,offset){var entries=box.entries||[];buf=buf?buf.slice(offset):Buffer.alloc(exports.stsz.encodingLength(box)),buf.writeUInt32BE(0,0),buf.writeUInt32BE(entries.length,4);for(var i=0;iUINT32_MAX&&(len=1),buffer.writeUInt32BE(len,offset),buffer.write(obj.type,offset+4,4,"ascii");var ptr=offset+8;if(1===len&&(uint64be.encode(obj.length,buffer,ptr),ptr+=8),boxes.fullBoxes[type]&&(buffer.writeUInt32BE(obj.flags||0,ptr),buffer.writeUInt8(obj.version||0,ptr),ptr+=4),containers[type]){var contents=containers[type];contents.forEach(function(childType){if(5===childType.length){var entry=obj[childType]||[];childType=childType.substr(0,4),entry.forEach(function(child){Box._encode(child,buffer,ptr),ptr+=Box.encode.bytes})}else obj[childType]&&(Box._encode(obj[childType],buffer,ptr),ptr+=Box.encode.bytes)}),obj.otherBoxes&&obj.otherBoxes.forEach(function(child){Box._encode(child,buffer,ptr),ptr+=Box.encode.bytes})}else if(boxes[type]){var encode=boxes[type].encode;encode(obj,buffer,ptr),ptr+=encode.bytes}else if(obj.buffer){var buf=obj.buffer;buf.copy(buffer,ptr),ptr+=obj.buffer.length}else throw new Error("Either `type` must be set to a known type (not'"+type+"') or `buffer` must be set");return Box.encode.bytes=ptr-offset,buffer},Box.readHeaders=function(buffer,start,end){if(start=start||0,end=end||buffer.length,8>end-start)return 8;var len=buffer.readUInt32BE(start),type=buffer.toString("ascii",start+4,start+8),ptr=start+8;if(1===len){if(16>end-start)return 16;len=uint64be.decode(buffer,ptr),ptr+=8}var version,flags;return boxes.fullBoxes[type]&&(version=buffer.readUInt8(ptr),flags=16777215&buffer.readUInt32BE(ptr),ptr+=4),{length:len,headersLen:ptr-start,contentLen:len-(ptr-start),type:type,version:version,flags:flags}},Box.decode=function(buffer,start,end){start=start||0,end=end||buffer.length;var headers=Box.readHeaders(buffer,start,end);if(!headers||headers.length>end-start)throw new Error("Data too short");return Box.decodeWithoutHeaders(headers,buffer,start+headers.headersLen,start+headers.length)},Box.decodeWithoutHeaders=function(headers,buffer,start,end){start=start||0,end=end||buffer.length;var type=headers.type,obj={};if(containers[type]){obj.otherBoxes=[];for(var contents=containers[type],ptr=start,child;8<=end-ptr;)if(child=Box.decode(buffer,ptr,end),ptr+=child.length,0<=contents.indexOf(child.type))obj[child.type]=child;else if(0<=contents.indexOf(child.type+"s")){var childType=child.type+"s",entry=obj[childType]=obj[childType]||[];entry.push(child)}else obj.otherBoxes.push(child)}else if(boxes[type]){var decode=boxes[type].decode;obj=decode(buffer,start,end)}else obj.buffer=Buffer.from(buffer.slice(start,end));return obj.length=headers.length,obj.contentLen=headers.contentLen,obj.type=headers.type,obj.version=headers.version,obj.flags=headers.flags,obj},Box.encodingLength=function(obj){var type=obj.type,len=8;if(boxes.fullBoxes[type]&&(len+=4),containers[type]){var contents=containers[type];contents.forEach(function(childType){if(5===childType.length){var entry=obj[childType]||[];childType=childType.substr(0,4),entry.forEach(function(child){child.type=childType,len+=Box.encodingLength(child)})}else if(obj[childType]){var child=obj[childType];child.type=childType,len+=Box.encodingLength(child)}}),obj.otherBoxes&&obj.otherBoxes.forEach(function(child){len+=Box.encodingLength(child)})}else if(boxes[type])len+=boxes[type].encodingLength(obj);else if(obj.buffer)len+=obj.buffer.length;else throw new Error("Either `type` must be set to a known type (not'"+type+"') or `buffer` must be set");return len>UINT32_MAX&&(len+=8),obj.length=len,len}}).call(this)}).call(this,require("buffer").Buffer)},{"./boxes":50,buffer:24,uint64be:114}],53:[function(require,module){(function(Buffer){(function(){var stream=require("readable-stream"),nextEvent=require("next-event"),Box=require("mp4-box-encoding"),EMPTY=Buffer.alloc(0);class Decoder extends stream.Writable{constructor(opts){super(opts),this.destroyed=!1,this._pending=0,this._missing=0,this._ignoreEmpty=!1,this._buf=null,this._str=null,this._cb=null,this._ondrain=null,this._writeBuffer=null,this._writeCb=null,this._ondrain=null,this._kick()}destroy(err){this.destroyed||(this.destroyed=!0,err&&this.emit("error",err),this.emit("close"))}_write(data,enc,next){if(!this.destroyed){for(var drained=!this._str||!this._str._writableState.needDrain;data.length&&!this.destroyed;){if(!this._missing&&!this._ignoreEmpty)return this._writeBuffer=data,void(this._writeCb=next);var consumed=data.length{this._pending--,this._kick()}),this._cb=cb,this._str}_readBox(){const bufferHeaders=(len,buf)=>{this._buffer(len,additionalBuf=>{buf=buf?Buffer.concat([buf,additionalBuf]):additionalBuf;var headers=Box.readHeaders(buf);"number"==typeof headers?bufferHeaders(headers-buf.length,buf):(this._pending++,this._headers=headers,this.emit("box",headers))})};bufferHeaders(8)}stream(){if(!this._headers)throw new Error("this function can only be called once after 'box' is emitted");var headers=this._headers;return this._headers=null,this._stream(headers.contentLen,null)}decode(cb){if(!this._headers)throw new Error("this function can only be called once after 'box' is emitted");var headers=this._headers;this._headers=null,this._buffer(headers.contentLen,buf=>{var box=Box.decodeWithoutHeaders(headers,buf);cb(box),this._pending--,this._kick()})}ignore(){if(!this._headers)throw new Error("this function can only be called once after 'box' is emitted");var headers=this._headers;this._headers=null,this._missing=headers.contentLen,0===this._missing&&(this._ignoreEmpty=!0),this._cb=()=>{this._pending--,this._kick()}}_kick(){if(!this._pending&&(this._buf||this._str||this._readBox(),this._writeBuffer)){var next=this._writeCb,buffer=this._writeBuffer;this._writeBuffer=null,this._writeCb=null,this._write(buffer,null,next)}}}class MediaData extends stream.PassThrough{constructor(parent){super(),this._parent=parent,this.destroyed=!1}destroy(err){this.destroyed||(this.destroyed=!0,this._parent.destroy(err),err&&this.emit("error",err),this.emit("close"))}}module.exports=Decoder}).call(this)}).call(this,require("buffer").Buffer)},{buffer:24,"mp4-box-encoding":52,"next-event":58,"readable-stream":86}],54:[function(require,module){(function(process,Buffer){(function(){function noop(){}var stream=require("readable-stream"),Box=require("mp4-box-encoding");class Encoder extends stream.Readable{constructor(opts){super(opts),this.destroyed=!1,this._finalized=!1,this._reading=!1,this._stream=null,this._drain=null,this._want=!1,this._onreadable=()=>{this._want&&(this._want=!1,this._read())},this._onend=()=>{this._stream=null}}mdat(size,cb){this.mediaData(size,cb)}mediaData(size,cb){var stream=new MediaData(this);return this.box({type:"mdat",contentLength:size,encodeBufferLen:8,stream:stream},cb),stream}box(box,cb){if(cb||(cb=noop),this.destroyed)return cb(new Error("Encoder is destroyed"));var buf;if(box.encodeBufferLen&&(buf=Buffer.alloc(box.encodeBufferLen)),box.stream)box.buffer=null,buf=Box.encode(box,buf),this.push(buf),this._stream=box.stream,this._stream.on("readable",this._onreadable),this._stream.on("end",this._onend),this._stream.on("end",cb),this._forward();else{buf=Box.encode(box,buf);var drained=this.push(buf);if(drained)return process.nextTick(cb);this._drain=cb}}destroy(err){if(!this.destroyed){if(this.destroyed=!0,this._stream&&this._stream.destroy&&this._stream.destroy(),this._stream=null,this._drain){var cb=this._drain;this._drain=null,cb(err)}err&&this.emit("error",err),this.emit("close")}}finalize(){this._finalized=!0,this._stream||this._drain||this.push(null)}_forward(){if(this._stream)for(;!this.destroyed;){var buf=this._stream.read();if(!buf)return void(this._want=!!this._stream);if(!this.push(buf))return}}_read(){if(!(this._reading||this.destroyed)){if(this._reading=!0,this._stream&&this._forward(),this._drain){var drain=this._drain;this._drain=null,drain()}this._reading=!1,this._finalized&&this.push(null)}}}class MediaData extends stream.PassThrough{constructor(parent){super(),this._parent=parent,this.destroyed=!1}destroy(err){this.destroyed||(this.destroyed=!0,this._parent.destroy(err),err&&this.emit("error",err),this.emit("close"))}}module.exports=Encoder}).call(this)}).call(this,require("_process"),require("buffer").Buffer)},{_process:62,buffer:24,"mp4-box-encoding":52,"readable-stream":86}],55:[function(require,module,exports){const Decoder=require("./decode"),Encoder=require("./encode");exports.decode=opts=>new Decoder(opts),exports.encode=opts=>new Encoder(opts)},{"./decode":53,"./encode":54}],56:[function(require,module){var _Mathround=Math.round;function parse(str){if(str+="",!(100=1.5*n?"s":"")}var d=24*(60*60000);module.exports=function(val,options){options=options||{};var type=typeof val;if("string"==type&&0 */var stream=require("readable-stream");class MultiStream extends stream.Readable{constructor(streams,opts){super(opts),this.destroyed=!1,this._drained=!1,this._forwarding=!1,this._current=null,this._toStreams2=opts&&opts.objectMode?toStreams2Obj:toStreams2Buf,"function"==typeof streams?this._queue=streams:(this._queue=streams.map(this._toStreams2),this._queue.forEach(stream=>{"function"!=typeof stream&&this._attachErrorListener(stream)})),this._next()}_read(){this._drained=!0,this._forward()}_forward(){if(!this._forwarding&&this._drained&&this._current){this._forwarding=!0;for(var chunk;this._drained&&null!==(chunk=this._current.read());)this._drained=this.push(chunk);this._forwarding=!1}}destroy(err){this.destroyed||(this.destroyed=!0,this._current&&this._current.destroy&&this._current.destroy(),"function"!=typeof this._queue&&this._queue.forEach(stream=>{stream.destroy&&stream.destroy()}),err&&this.emit("error",err),this.emit("close"))}_next(){if(this._current=null,"function"==typeof this._queue)this._queue((err,stream)=>err?this.destroy(err):void(stream=this._toStreams2(stream),this._attachErrorListener(stream),this._gotNextStream(stream)));else{var stream=this._queue.shift();"function"==typeof stream&&(stream=this._toStreams2(stream()),this._attachErrorListener(stream)),this._gotNextStream(stream)}}_gotNextStream(stream){if(!stream)return this.push(null),void this.destroy();this._current=stream,this._forward();const onReadable=()=>{this._forward()},onClose=()=>{stream._readableState.ended||this.destroy()},onEnd=()=>{this._current=null,stream.removeListener("readable",onReadable),stream.removeListener("end",onEnd),stream.removeListener("close",onClose),this._next()};stream.on("readable",onReadable),stream.once("end",onEnd),stream.once("close",onClose)}_attachErrorListener(stream){if(!stream)return;const onError=err=>{stream.removeListener("error",onError),this.destroy(err)};stream.once("error",onError)}}MultiStream.obj=streams=>new MultiStream(streams,{objectMode:!0,highWaterMark:16}),module.exports=MultiStream},{"readable-stream":86}],58:[function(require,module){module.exports=function(emitter,name){var next=null;return emitter.on(name,function(data){if(next){var fn=next;next=null,fn(data)}}),function(once){next=once}}},{}],59:[function(require,module){function once(fn){var f=function(){return f.called?f.value:(f.called=!0,f.value=fn.apply(this,arguments))};return f.called=!1,f}function onceStrict(fn){var f=function(){if(f.called)throw new Error(f.onceError);return f.called=!0,f.value=fn.apply(this,arguments)},name=fn.name||"Function wrapped with `once`";return f.onceError=name+" shouldn't be called more than once",f.called=!1,f}var wrappy=require("wrappy");module.exports=wrappy(once),module.exports.strict=wrappy(onceStrict),once.proto=once(function(){Object.defineProperty(Function.prototype,"once",{value:function(){return once(this)},configurable:!0}),Object.defineProperty(Function.prototype,"onceStrict",{value:function(){return onceStrict(this)},configurable:!0})})},{wrappy:122}],60:[function(require,module){(function(process,Buffer){(function(){function parseTorrent(torrentId){if("string"==typeof torrentId&&/^(stream-)?magnet:/.test(torrentId)){const torrentObj=magnet(torrentId);if(!torrentObj.infoHash)throw new Error("Invalid torrent identifier");return torrentObj}if("string"==typeof torrentId&&(/^[a-f0-9]{40}$/i.test(torrentId)||/^[a-z2-7]{32}$/i.test(torrentId)))return magnet(`magnet:?xt=urn:btih:${torrentId}`);if(Buffer.isBuffer(torrentId)&&20===torrentId.length)return magnet(`magnet:?xt=urn:btih:${torrentId.toString("hex")}`);if(Buffer.isBuffer(torrentId))return decodeTorrentFile(torrentId);if(torrentId&&torrentId.infoHash)return torrentId.infoHash=torrentId.infoHash.toLowerCase(),torrentId.announce||(torrentId.announce=[]),"string"==typeof torrentId.announce&&(torrentId.announce=[torrentId.announce]),torrentId.urlList||(torrentId.urlList=[]),torrentId;throw new Error("Invalid torrent identifier")}function parseTorrentRemote(torrentId,opts,cb){function parseOrThrow(torrentBuf){try{parsedTorrent=parseTorrent(torrentBuf)}catch(err){return cb(err)}parsedTorrent&&parsedTorrent.infoHash?cb(null,parsedTorrent):cb(new Error("Invalid torrent identifier"))}if("function"==typeof opts)return parseTorrentRemote(torrentId,{},opts);if("function"!=typeof cb)throw new Error("second argument must be a Function");let parsedTorrent;try{parsedTorrent=parseTorrent(torrentId)}catch(err){}parsedTorrent&&parsedTorrent.infoHash?process.nextTick(()=>{cb(null,parsedTorrent)}):isBlob(torrentId)?blobToBuffer(torrentId,(err,torrentBuf)=>err?cb(new Error(`Error converting Blob: ${err.message}`)):void parseOrThrow(torrentBuf)):"function"==typeof get&&/^https?:/.test(torrentId)?(opts=Object.assign({url:torrentId,timeout:30000,headers:{"user-agent":"WebTorrent (https://webtorrent.io)"}},opts),get.concat(opts,(err,res,torrentBuf)=>err?cb(new Error(`Error downloading torrent: ${err.message}`)):void parseOrThrow(torrentBuf))):"function"==typeof fs.readFile&&"string"==typeof torrentId?fs.readFile(torrentId,(err,torrentBuf)=>err?cb(new Error("Invalid torrent identifier")):void parseOrThrow(torrentBuf)):process.nextTick(()=>{cb(new Error("Invalid torrent identifier"))})}function decodeTorrentFile(torrent){Buffer.isBuffer(torrent)&&(torrent=bencode.decode(torrent)),ensure(torrent.info,"info"),ensure(torrent.info["name.utf-8"]||torrent.info.name,"info.name"),ensure(torrent.info["piece length"],"info['piece length']"),ensure(torrent.info.pieces,"info.pieces"),torrent.info.files?torrent.info.files.forEach(file=>{ensure("number"==typeof file.length,"info.files[0].length"),ensure(file["path.utf-8"]||file.path,"info.files[0].path")}):ensure("number"==typeof torrent.info.length,"info.length");const result={info:torrent.info,infoBuffer:bencode.encode(torrent.info),name:(torrent.info["name.utf-8"]||torrent.info.name).toString(),announce:[]};result.infoHash=sha1.sync(result.infoBuffer),result.infoHashBuffer=Buffer.from(result.infoHash,"hex"),void 0!==torrent.info.private&&(result.private=!!torrent.info.private),torrent["creation date"]&&(result.created=new Date(1e3*torrent["creation date"])),torrent["created by"]&&(result.createdBy=torrent["created by"].toString()),Buffer.isBuffer(torrent.comment)&&(result.comment=torrent.comment.toString()),Array.isArray(torrent["announce-list"])&&0{urls.forEach(url=>{result.announce.push(url.toString())})}):torrent.announce&&result.announce.push(torrent.announce.toString()),Buffer.isBuffer(torrent["url-list"])&&(torrent["url-list"]=0url.toString()),result.announce=Array.from(new Set(result.announce)),result.urlList=Array.from(new Set(result.urlList));const files=torrent.info.files||[torrent.info];result.files=files.map((file,i)=>{const parts=[].concat(result.name,file["path.utf-8"]||file.path||[]).map(p=>p.toString());return{path:path.join.apply(null,[path.sep].concat(parts)).slice(1),name:parts[parts.length-1],length:file.length,offset:files.slice(0,i).reduce(sumLength,0)}}),result.length=files.reduce(sumLength,0);const lastFile=result.files[result.files.length-1];return result.pieceLength=torrent.info["piece length"],result.lastPieceLength=(lastFile.offset+lastFile.length)%result.pieceLength||result.pieceLength,result.pieces=splitPieces(torrent.info.pieces),result}function isBlob(obj){return"undefined"!=typeof Blob&&obj instanceof Blob}function sumLength(sum,file){return sum+file.length}function splitPieces(buf){const pieces=[];for(let i=0;i */const bencode=require("bencode"),blobToBuffer=require("blob-to-buffer"),fs=require("fs"),get=require("simple-get"),magnet=require("magnet-uri"),path=require("path"),sha1=require("simple-sha1");module.exports=parseTorrent,module.exports.remote=parseTorrentRemote,module.exports.toMagnetURI=magnet.encode,module.exports.toTorrentFile=function(parsed){const torrent={info:parsed.info};return torrent["announce-list"]=(parsed.announce||[]).map(url=>(torrent.announce||(torrent.announce=url),url=Buffer.from(url,"utf8"),[url])),torrent["url-list"]=parsed.urlList||[],void 0!==parsed.private&&(torrent.private=+parsed.private),parsed.created&&(torrent["creation date"]=0|parsed.created.getTime()/1e3),parsed.createdBy&&(torrent["created by"]=parsed.createdBy),parsed.comment&&(torrent.comment=parsed.comment),bencode.encode(torrent)};(()=>{Buffer.alloc(0)})()}).call(this)}).call(this,require("_process"),require("buffer").Buffer)},{_process:62,bencode:11,"blob-to-buffer":20,buffer:24,fs:23,"magnet-uri":47,path:26,"simple-get":94,"simple-sha1":96}],61:[function(require,module){module.exports=function(bytes){return _Mathmax(16384,0|1<bytes?1:bytes/1024)+.5)}},{}],62:[function(require,module){function defaultSetTimout(){throw new Error("setTimeout has not been defined")}function defaultClearTimeout(){throw new Error("clearTimeout has not been defined")}function runTimeout(fun){if(cachedSetTimeout===setTimeout)return setTimeout(fun,0);if((cachedSetTimeout===defaultSetTimout||!cachedSetTimeout)&&setTimeout)return cachedSetTimeout=setTimeout,setTimeout(fun,0);try{return cachedSetTimeout(fun,0)}catch(e){try{return cachedSetTimeout.call(null,fun,0)}catch(e){return cachedSetTimeout.call(this,fun,0)}}}function runClearTimeout(marker){if(cachedClearTimeout===clearTimeout)return clearTimeout(marker);if((cachedClearTimeout===defaultClearTimeout||!cachedClearTimeout)&&clearTimeout)return cachedClearTimeout=clearTimeout,clearTimeout(marker);try{return cachedClearTimeout(marker)}catch(e){try{return cachedClearTimeout.call(null,marker)}catch(e){return cachedClearTimeout.call(this,marker)}}}function cleanUpNextTick(){draining&¤tQueue&&(draining=!1,currentQueue.length?queue=currentQueue.concat(queue):queueIndex=-1,queue.length&&drainQueue())}function drainQueue(){if(!draining){var timeout=runTimeout(cleanUpNextTick);draining=!0;for(var len=queue.length;len;){for(currentQueue=queue,queue=[];++queueIndexstreams.length)throw new Error("pump requires two streams per minimum");var destroys=streams.map(function(stream,i){var reading=i=value&&counter>>10),value=56320|1023&value),output+=stringFromCharCode(value),output}).join("")}function basicToDigit(codePoint){return 10>codePoint-48?codePoint-22:26>codePoint-65?codePoint-65:26>codePoint-97?codePoint-97:36}function digitToBasic(digit,flag){return digit+22+75*(26>digit)-((0!=flag)<<5)}function adapt(delta,numPoints,firstTime){var k=0;for(delta=firstTime?floor(delta/700):delta>>1,delta+=floor(delta/numPoints);455basic&&(basic=0),j=0;j=inputLength&&error("invalid-input"),digit=basicToDigit(input.charCodeAt(index++)),(36<=digit||digit>floor((2147483647-i)/w))&&error("overflow"),i+=digit*w,t=k<=bias?1:k>=bias+26?26:k-bias,digitfloor(2147483647/baseMinusT)&&error("overflow"),w*=baseMinusT}out=output.length+1,bias=adapt(i-oldi,out,0==oldi),floor(i/out)>2147483647-n&&error("overflow"),n+=floor(i/out),i%=out,output.splice(i++,0,n)}return ucs2encode(output)}function encode(input){var output=[],n,delta,handledCPCount,basicLength,bias,j,m,q,k,t,currentValue,inputLength,handledCPCountPlusOne,baseMinusT,qMinusT;for(input=ucs2decode(input),inputLength=input.length,n=128,delta=0,bias=72,j=0;jcurrentValue&&output.push(stringFromCharCode(currentValue));for(handledCPCount=basicLength=output.length,basicLength&&output.push("-");handledCPCount=n&¤tValuefloor((2147483647-delta)/handledCPCountPlusOne)&&error("overflow"),delta+=(m-n)*handledCPCountPlusOne,n=m,j=0;j=bias+26?26:k-bias,q= 0x80 (not a basic code point)","invalid-input":"Invalid input"},floor=_Mathfloor,stringFromCharCode=_StringfromCharCode,punycode,key;if(punycode={version:"1.4.1",ucs2:{decode:ucs2decode,encode:ucs2encode},decode:decode,encode:encode,toASCII:function(input){return mapDomain(input,function(string){return /[^\x20-\x7E]/.test(string)?"xn--"+encode(string):string})},toUnicode:function(input){return mapDomain(input,function(string){return /^xn--/.test(string)?decode(string.slice(4).toLowerCase()):string})}},"function"==typeof define&&"object"==typeof define.amd&&define.amd)define("punycode",function(){return punycode});else if(!(freeExports&&freeModule))root.punycode=punycode;else if(module.exports==freeExports)freeModule.exports=punycode;else for(key in punycode)punycode.hasOwnProperty(key)&&(freeExports[key]=punycode[key])})(this)}).call(this)}).call(this,"undefined"==typeof global?"undefined"==typeof self?"undefined"==typeof window?{}:window:self:global)},{}],65:[function(require,module){'use strict';function hasOwnProperty(obj,prop){return Object.prototype.hasOwnProperty.call(obj,prop)}module.exports=function(qs,sep,eq,options){sep=sep||"&",eq=eq||"=";var obj={};if("string"!=typeof qs||0===qs.length)return obj;qs=qs.split(sep);var maxKeys=1e3;options&&"number"==typeof options.maxKeys&&(maxKeys=options.maxKeys);var len=qs.length;0maxKeys&&(len=maxKeys);for(var i=0;i */let promise;module.exports="function"==typeof queueMicrotask?queueMicrotask.bind(globalThis):cb=>(promise||(promise=Promise.resolve())).then(cb).catch(err=>setTimeout(()=>{throw err},0))},{}],69:[function(require,module){module.exports=function(list){var offset=0;return function(){if(offset===list.length)return null;var len=list.length-offset,i=0|Math.random()*len,el=list[offset+i],tmp=list[offset];return list[offset]=el,list[offset+i]=tmp,offset++,el}}},{}],70:[function(require,module){(function(process,global){(function(){'use strict';var Buffer=require("safe-buffer").Buffer,crypto=global.crypto||global.msCrypto;module.exports=crypto&&crypto.getRandomValues?function(size,cb){if(size>4294967295)throw new RangeError("requested too many random bytes");var bytes=Buffer.allocUnsafe(size);if(0=chunk.length)return this._position+=chunk.length,cb(null);let toWrite;if(writeEnd>chunk.length){this._position+=chunk.length,toWrite=0===writeStart?chunk:chunk.slice(writeStart),drained=currRange.stream.write(toWrite)&&drained;break}this._position+=writeEnd,toWrite=0===writeStart&&writeEnd===chunk.length?chunk:chunk.slice(writeStart,writeEnd),drained=currRange.stream.write(toWrite)&&drained,currRange.last&&currRange.stream.end(),chunk=chunk.slice(writeEnd),this._queue.shift()}drained?cb(null):currRange.stream.once("drain",cb.bind(null,null))}slice(ranges){if(this.destroyed)return null;Array.isArray(ranges)||(ranges=[ranges]);const str=new PassThrough;return ranges.forEach((range,i)=>{this._queue.push({start:range.start,end:range.end,stream:str,last:i===ranges.length-1})}),this._buffer&&this._write(this._buffer,null,this._cb),str}destroy(err){this.destroyed||(this.destroyed=!0,err&&this.emit("error",err))}}},{"readable-stream":86}],72:[function(require,module){'use strict';function _inheritsLoose(subClass,superClass){subClass.prototype=Object.create(superClass.prototype),subClass.prototype.constructor=subClass,subClass.__proto__=superClass}function createErrorType(code,message,Base){function getMessage(arg1,arg2,arg3){return"string"==typeof message?message:message(arg1,arg2,arg3)}Base||(Base=Error);var NodeError=function(_Base){function NodeError(arg1,arg2,arg3){return _Base.call(this,getMessage(arg1,arg2,arg3))||this}return _inheritsLoose(NodeError,_Base),NodeError}(Base);NodeError.prototype.name=Base.name,NodeError.prototype.code=code,codes[code]=NodeError}function oneOf(expected,thing){if(Array.isArray(expected)){var len=expected.length;return expected=expected.map(function(i){return i+""}),2pos?0:+pos,search.length)===search}function endsWith(str,search,this_len){return(void 0===this_len||this_len>str.length)&&(this_len=str.length),str.substring(this_len-search.length,this_len)===search}function includes(str,search,start){return"number"!=typeof start&&(start=0),!(start+search.length>str.length)&&-1!==str.indexOf(search,start)}var codes={};createErrorType("ERR_INVALID_OPT_VALUE",function(name,value){return"The value \""+value+"\" is invalid for option \""+name+"\""},TypeError),createErrorType("ERR_INVALID_ARG_TYPE",function(name,expected,actual){var determiner;"string"==typeof expected&&startsWith(expected,"not ")?(determiner="must not be",expected=expected.replace(/^not /,"")):determiner="must be";var msg;if(endsWith(name," argument"))msg="The ".concat(name," ").concat(determiner," ").concat(oneOf(expected,"type"));else{var type=includes(name,".")?"property":"argument";msg="The \"".concat(name,"\" ").concat(type," ").concat(determiner," ").concat(oneOf(expected,"type"))}return msg+=". Received type ".concat(typeof actual),msg},TypeError),createErrorType("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF"),createErrorType("ERR_METHOD_NOT_IMPLEMENTED",function(name){return"The "+name+" method is not implemented"}),createErrorType("ERR_STREAM_PREMATURE_CLOSE","Premature close"),createErrorType("ERR_STREAM_DESTROYED",function(name){return"Cannot call "+name+" after a stream was destroyed"}),createErrorType("ERR_MULTIPLE_CALLBACK","Callback called multiple times"),createErrorType("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable"),createErrorType("ERR_STREAM_WRITE_AFTER_END","write after end"),createErrorType("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),createErrorType("ERR_UNKNOWN_ENCODING",function(arg){return"Unknown encoding: "+arg},TypeError),createErrorType("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event"),module.exports.codes=codes},{}],73:[function(require,module){(function(process){(function(){'use strict';function Duplex(options){return this instanceof Duplex?void(Readable.call(this,options),Writable.call(this,options),this.allowHalfOpen=!0,options&&(!1===options.readable&&(this.readable=!1),!1===options.writable&&(this.writable=!1),!1===options.allowHalfOpen&&(this.allowHalfOpen=!1,this.once("end",onend)))):new Duplex(options)}function onend(){this._writableState.ended||process.nextTick(onEndNT,this)}function onEndNT(self){self.end()}var objectKeys=Object.keys||function(obj){var keys=[];for(var key in obj)keys.push(key);return keys};module.exports=Duplex;var Readable=require("./_stream_readable"),Writable=require("./_stream_writable");require("inherits")(Duplex,Readable);for(var keys=objectKeys(Writable.prototype),v=0,method;v>>1,n|=n>>>2,n|=n>>>4,n|=n>>>8,n|=n>>>16,n++),n}function howMuchToRead(n,state){return 0>=n||0===state.length&&state.ended?0:state.objectMode?1:n===n?(n>state.highWaterMark&&(state.highWaterMark=computeNewHighWaterMark(n)),n<=state.length?n:state.ended?state.length:(state.needReadable=!0,0)):state.flowing&&state.length?state.buffer.head.data.length:state.length}function onEofChunk(stream,state){if(debug("onEofChunk"),!state.ended){if(state.decoder){var chunk=state.decoder.end();chunk&&chunk.length&&(state.buffer.push(chunk),state.length+=state.objectMode?1:chunk.length)}state.ended=!0,state.sync?emitReadable(stream):(state.needReadable=!1,!state.emittedReadable&&(state.emittedReadable=!0,emitReadable_(stream)))}}function emitReadable(stream){var state=stream._readableState;debug("emitReadable",state.needReadable,state.emittedReadable),state.needReadable=!1,state.emittedReadable||(debug("emitReadable",state.flowing),state.emittedReadable=!0,process.nextTick(emitReadable_,stream))}function emitReadable_(stream){var state=stream._readableState;debug("emitReadable_",state.destroyed,state.length,state.ended),!state.destroyed&&(state.length||state.ended)&&(stream.emit("readable"),state.emittedReadable=!1),state.needReadable=!state.flowing&&!state.ended&&state.length<=state.highWaterMark,flow(stream)}function maybeReadMore(stream,state){state.readingMore||(state.readingMore=!0,process.nextTick(maybeReadMore_,stream,state))}function maybeReadMore_(stream,state){for(;!state.reading&&!state.ended&&(state.length=state.length?(ret=state.decoder?state.buffer.join(""):1===state.buffer.length?state.buffer.first():state.buffer.concat(state.length),state.buffer.clear()):ret=state.buffer.consume(n,state.decoder),ret}function endReadable(stream){var state=stream._readableState;debug("endReadable",state.endEmitted),state.endEmitted||(state.ended=!0,process.nextTick(endReadableNT,state,stream))}function endReadableNT(state,stream){if(debug("endReadableNT",state.endEmitted,state.length),!state.endEmitted&&0===state.length&&(state.endEmitted=!0,stream.readable=!1,stream.emit("end"),state.autoDestroy)){var wState=stream._writableState;(!wState||wState.autoDestroy&&wState.finished)&&stream.destroy()}}function indexOf(xs,x){for(var i=0,l=xs.length;i=state.highWaterMark)||state.ended))return debug("read: emitReadable",state.length,state.ended),0===state.length&&state.ended?endReadable(this):emitReadable(this),null;if(n=howMuchToRead(n,state),0===n&&state.ended)return 0===state.length&&endReadable(this),null;var doRead=state.needReadable;debug("need readable",doRead),(0===state.length||state.length-n>>0),p=this.head,i=0;p;)copyBuffer(p.data,ret,i),i+=p.data.length,p=p.next;return ret}},{key:"consume",value:function(n,hasStrings){var ret;return nstr.length?str.length:n;if(ret+=nb===str.length?str:str.slice(0,n),n-=nb,0===n){nb===str.length?(++c,this.head=p.next?p.next:this.tail=null):(this.head=p,p.data=str.slice(nb));break}++c}return this.length-=c,ret}},{key:"_getBuffer",value:function(n){var ret=Buffer.allocUnsafe(n),p=this.head,c=1;for(p.data.copy(ret),n-=p.data.length;p=p.next;){var buf=p.data,nb=n>buf.length?buf.length:n;if(buf.copy(ret,ret.length-n,0,nb),n-=nb,0===n){nb===buf.length?(++c,this.head=p.next?p.next:this.tail=null):(this.head=p,p.data=buf.slice(nb));break}++c}return this.length-=c,ret}},{key:custom,value:function(_,options){return inspect(this,_objectSpread({},options,{depth:0,customInspect:!1}))}}]),BufferList}()},{buffer:24,util:22}],80:[function(require,module){(function(process){(function(){'use strict';function emitErrorAndCloseNT(self,err){emitErrorNT(self,err),emitCloseNT(self)}function emitCloseNT(self){self._writableState&&!self._writableState.emitClose||self._readableState&&!self._readableState.emitClose||self.emit("close")}function emitErrorNT(self,err){self.emit("error",err)}module.exports={destroy:function(err,cb){var _this=this,readableDestroyed=this._readableState&&this._readableState.destroyed,writableDestroyed=this._writableState&&this._writableState.destroyed;return readableDestroyed||writableDestroyed?(cb?cb(err):err&&(this._writableState?!this._writableState.errorEmitted&&(this._writableState.errorEmitted=!0,process.nextTick(emitErrorNT,this,err)):process.nextTick(emitErrorNT,this,err)),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(err||null,function(err){!cb&&err?_this._writableState?_this._writableState.errorEmitted?process.nextTick(emitCloseNT,_this):(_this._writableState.errorEmitted=!0,process.nextTick(emitErrorAndCloseNT,_this,err)):process.nextTick(emitErrorAndCloseNT,_this,err):cb?(process.nextTick(emitCloseNT,_this),cb(err)):process.nextTick(emitCloseNT,_this)}),this)},undestroy:function(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finalCalled=!1,this._writableState.prefinished=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)},errorOrDestroy:function(stream,err){var rState=stream._readableState,wState=stream._writableState;rState&&rState.autoDestroy||wState&&wState.autoDestroy?stream.destroy(err):stream.emit("error",err)}}}).call(this)}).call(this,require("_process"))},{_process:62}],81:[function(require,module){'use strict';function once(callback){var called=!1;return function(){if(!called){called=!0;for(var _len=arguments.length,args=Array(_len),_key=0;_key<_len;_key++)args[_key]=arguments[_key];callback.apply(this,args)}}}function noop(){}function isRequest(stream){return stream.setHeader&&"function"==typeof stream.abort}function eos(stream,opts,callback){if("function"==typeof opts)return eos(stream,null,opts);opts||(opts={}),callback=once(callback||noop);var readable=opts.readable||!1!==opts.readable&&stream.readable,writable=opts.writable||!1!==opts.writable&&stream.writable,onlegacyfinish=function(){stream.writable||onfinish()},writableEnded=stream._writableState&&stream._writableState.finished,onfinish=function(){writable=!1,writableEnded=!0,readable||callback.call(stream)},readableEnded=stream._readableState&&stream._readableState.endEmitted,onend=function(){readable=!1,readableEnded=!0,writable||callback.call(stream)},onerror=function(err){callback.call(stream,err)},onclose=function(){var err;return readable&&!readableEnded?(stream._readableState&&stream._readableState.ended||(err=new ERR_STREAM_PREMATURE_CLOSE),callback.call(stream,err)):writable&&!writableEnded?(stream._writableState&&stream._writableState.ended||(err=new ERR_STREAM_PREMATURE_CLOSE),callback.call(stream,err)):void 0},onrequest=function(){stream.req.on("finish",onfinish)};return isRequest(stream)?(stream.on("complete",onfinish),stream.on("abort",onclose),stream.req?onrequest():stream.on("request",onrequest)):writable&&!stream._writableState&&(stream.on("end",onlegacyfinish),stream.on("close",onlegacyfinish)),stream.on("end",onend),stream.on("finish",onfinish),!1!==opts.error&&stream.on("error",onerror),stream.on("close",onclose),function(){stream.removeListener("complete",onfinish),stream.removeListener("abort",onclose),stream.removeListener("request",onrequest),stream.req&&stream.req.removeListener("finish",onfinish),stream.removeListener("end",onlegacyfinish),stream.removeListener("close",onlegacyfinish),stream.removeListener("finish",onfinish),stream.removeListener("end",onend),stream.removeListener("error",onerror),stream.removeListener("close",onclose)}}var ERR_STREAM_PREMATURE_CLOSE=require("../../../errors").codes.ERR_STREAM_PREMATURE_CLOSE;module.exports=eos},{"../../../errors":72}],82:[function(require,module){module.exports=function(){throw new Error("Readable.from is not available in the browser")}},{}],83:[function(require,module){'use strict';function once(callback){var called=!1;return function(){called||(called=!0,callback.apply(void 0,arguments))}}function noop(err){if(err)throw err}function isRequest(stream){return stream.setHeader&&"function"==typeof stream.abort}function destroyer(stream,reading,writing,callback){callback=once(callback);var closed=!1;stream.on("close",function(){closed=!0}),eos===void 0&&(eos=require("./end-of-stream")),eos(stream,{readable:reading,writable:writing},function(err){return err?callback(err):void(closed=!0,callback())});var destroyed=!1;return function(err){if(!closed)return destroyed?void 0:(destroyed=!0,isRequest(stream)?stream.abort():"function"==typeof stream.destroy?stream.destroy():void callback(err||new ERR_STREAM_DESTROYED("pipe")))}}function call(fn){fn()}function pipe(from,to){return from.pipe(to)}function popCallback(streams){return streams.length?"function"==typeof streams[streams.length-1]?streams.pop():noop:noop}var _require$codes=require("../../../errors").codes,ERR_MISSING_ARGS=_require$codes.ERR_MISSING_ARGS,ERR_STREAM_DESTROYED=_require$codes.ERR_STREAM_DESTROYED,eos;module.exports=function(){for(var _len=arguments.length,streams=Array(_len),_key=0;_key<_len;_key++)streams[_key]=arguments[_key];var callback=popCallback(streams);if(Array.isArray(streams[0])&&(streams=streams[0]),2>streams.length)throw new ERR_MISSING_ARGS("streams");var destroys=streams.map(function(stream,i){var reading=ihwm){var name=isDuplex?duplexKey:"highWaterMark";throw new ERR_INVALID_OPT_VALUE(name,hwm)}return _Mathfloor(hwm)}return state.objectMode?16:16384}}},{"../../../errors":72}],85:[function(require,module){module.exports=require("events").EventEmitter},{events:25}],86:[function(require,module,exports){exports=module.exports=require("./lib/_stream_readable.js"),exports.Stream=exports,exports.Readable=exports,exports.Writable=require("./lib/_stream_writable.js"),exports.Duplex=require("./lib/_stream_duplex.js"),exports.Transform=require("./lib/_stream_transform.js"),exports.PassThrough=require("./lib/_stream_passthrough.js"),exports.finished=require("./lib/internal/streams/end-of-stream.js"),exports.pipeline=require("./lib/internal/streams/pipeline.js")},{"./lib/_stream_duplex.js":73,"./lib/_stream_passthrough.js":74,"./lib/_stream_readable.js":75,"./lib/_stream_transform.js":76,"./lib/_stream_writable.js":77,"./lib/internal/streams/end-of-stream.js":81,"./lib/internal/streams/pipeline.js":83}],87:[function(require,module,exports){function renderMedia(file,getElem,opts,cb){function checkBlobLength(){return!("number"==typeof file.length&&file.length>opts.maxBlobLength)||(debug("File length too large for Blob URL approach: %d (max: %d)",file.length,opts.maxBlobLength),fatalError(new Error(`File length too large for Blob URL approach: ${file.length} (max: ${opts.maxBlobLength})`)),!1)}function renderMediaElement(type){checkBlobLength()&&(elem=getElem(type),getBlobURL(file,(err,url)=>err?fatalError(err):void(elem.addEventListener("error",fatalError),elem.addEventListener("loadstart",onLoadStart),elem.addEventListener("canplay",onCanPlay),elem.src=url)))}function onLoadStart(){elem.removeEventListener("loadstart",onLoadStart),opts.autoplay&&elem.play()}function onCanPlay(){elem.removeEventListener("canplay",onCanPlay),cb(null,elem)}function renderIframe(){getBlobURL(file,(err,url)=>err?fatalError(err):void(".pdf"===extname?(elem=getElem("object"),elem.setAttribute("typemustmatch",!0),elem.setAttribute("type","application/pdf"),elem.setAttribute("data",url)):(elem=getElem("iframe"),elem.sandbox="allow-forms allow-scripts",elem.src=url),cb(null,elem)))}function fatalError(err){err.message=`Error rendering file "${file.name}": ${err.message}`,debug(err.message),cb(err)}const extname=path.extname(file.name).toLowerCase();let currentTime=0,elem;MEDIASOURCE_EXTS.includes(extname)?function(){function useVideostream(){debug(`Use \`videostream\` package for ${file.name}`),prepareElem(),elem.addEventListener("error",fallbackToMediaSource),elem.addEventListener("loadstart",onLoadStart),elem.addEventListener("canplay",onCanPlay),new VideoStream(file,elem)}function useMediaSource(){debug(`Use MediaSource API for ${file.name}`),prepareElem(),elem.addEventListener("error",fallbackToBlobURL),elem.addEventListener("loadstart",onLoadStart),elem.addEventListener("canplay",onCanPlay);const wrapper=new MediaElementWrapper(elem),writable=wrapper.createWriteStream(getCodec(file.name));file.createReadStream().pipe(writable),currentTime&&(elem.currentTime=currentTime)}function useBlobURL(){debug(`Use Blob URL for ${file.name}`),prepareElem(),elem.addEventListener("error",fatalError),elem.addEventListener("loadstart",onLoadStart),elem.addEventListener("canplay",onCanPlay),getBlobURL(file,(err,url)=>err?fatalError(err):void(elem.src=url,currentTime&&(elem.currentTime=currentTime)))}function fallbackToMediaSource(err){debug("videostream error: fallback to MediaSource API: %o",err.message||err),elem.removeEventListener("error",fallbackToMediaSource),elem.removeEventListener("canplay",onCanPlay),useMediaSource()}function fallbackToBlobURL(err){debug("MediaSource API error: fallback to Blob URL: %o",err.message||err);checkBlobLength()&&(elem.removeEventListener("error",fallbackToBlobURL),elem.removeEventListener("canplay",onCanPlay),useBlobURL())}function prepareElem(){elem||(elem=getElem(tagName),elem.addEventListener("progress",()=>{currentTime=elem.currentTime}))}const tagName=MEDIASOURCE_VIDEO_EXTS.includes(extname)?"video":"audio";MediaSource?VIDEOSTREAM_EXTS.includes(extname)?useVideostream():useMediaSource():useBlobURL()}():VIDEO_EXTS.includes(extname)?renderMediaElement("video"):AUDIO_EXTS.includes(extname)?renderMediaElement("audio"):IMAGE_EXTS.includes(extname)?function(){elem=getElem("img"),getBlobURL(file,(err,url)=>err?fatalError(err):void(elem.src=url,elem.alt=file.name,cb(null,elem)))}():IFRAME_EXTS.includes(extname)?renderIframe():function(){function done(){isAscii(str)?(debug("File extension \"%s\" appears ascii, so will render.",extname),renderIframe()):(debug("File extension \"%s\" appears non-ascii, will not render.",extname),cb(new Error(`Unsupported file type "${extname}": Cannot append to DOM`)))}debug("Unknown file extension \"%s\" - will attempt to render into iframe",extname);let str="";file.createReadStream({start:0,end:1e3}).setEncoding("utf8").on("data",chunk=>{str+=chunk}).on("end",done).on("error",cb)}()}function getBlobURL(file,cb){const extname=path.extname(file.name).toLowerCase();streamToBlobURL(file.createReadStream(),exports.mime[extname]).then(blobUrl=>cb(null,blobUrl),err=>cb(err))}function validateFile(file){if(null==file)throw new Error("file cannot be null or undefined");if("string"!=typeof file.name)throw new Error("missing or invalid file.name property");if("function"!=typeof file.createReadStream)throw new Error("missing or invalid file.createReadStream property")}function getCodec(name){const extname=path.extname(name).toLowerCase();return{".m4a":"audio/mp4; codecs=\"mp4a.40.5\"",".m4b":"audio/mp4; codecs=\"mp4a.40.5\"",".m4p":"audio/mp4; codecs=\"mp4a.40.5\"",".m4v":"video/mp4; codecs=\"avc1.640029, mp4a.40.5\"",".mkv":"video/webm; codecs=\"avc1.640029, mp4a.40.5\"",".mp3":"audio/mpeg",".mp4":"video/mp4; codecs=\"avc1.640029, mp4a.40.5\"",".webm":"video/webm; codecs=\"vorbis, vp8\""}[extname]}function parseOpts(opts){null==opts.autoplay&&(opts.autoplay=!1),null==opts.muted&&(opts.muted=!1),null==opts.controls&&(opts.controls=!0),null==opts.maxBlobLength&&(opts.maxBlobLength=MAX_BLOB_LENGTH)}function setMediaOpts(elem,opts){elem.autoplay=!!opts.autoplay,elem.muted=!!opts.muted,elem.controls=!!opts.controls}exports.render=function(file,elem,opts,cb){"function"==typeof opts&&(cb=opts,opts={}),opts||(opts={}),cb||(cb=()=>{}),validateFile(file),parseOpts(opts),"string"==typeof elem&&(elem=document.querySelector(elem)),renderMedia(file,tagName=>{if(elem.nodeName!==tagName.toUpperCase()){const extname=path.extname(file.name).toLowerCase();throw new Error(`Cannot render "${extname}" inside a "${elem.nodeName.toLowerCase()}" element, expected "${tagName}"`)}return("video"===tagName||"audio"===tagName)&&setMediaOpts(elem,opts),elem},opts,cb)},exports.append=function(file,rootElem,opts,cb){function createMedia(tagName){const elem=createElem(tagName);return setMediaOpts(elem,opts),rootElem.appendChild(elem),elem}function createElem(tagName){const elem=document.createElement(tagName);return rootElem.appendChild(elem),elem}function done(err,elem){err&&elem&&elem.remove(),cb(err,elem)}if("function"==typeof opts&&(cb=opts,opts={}),opts||(opts={}),cb||(cb=()=>{}),validateFile(file),parseOpts(opts),"string"==typeof rootElem&&(rootElem=document.querySelector(rootElem)),rootElem&&("VIDEO"===rootElem.nodeName||"AUDIO"===rootElem.nodeName))throw new Error("Invalid video/audio node argument. Argument must be root element that video/audio tag will be appended to.");renderMedia(file,function(tagName){return"video"===tagName||"audio"===tagName?createMedia(tagName):createElem(tagName)},opts,done)},exports.mime=require("./lib/mime.json");const debug=require("debug")("render-media"),isAscii=require("is-ascii"),MediaElementWrapper=require("mediasource"),path=require("path"),streamToBlobURL=require("stream-to-blob-url"),VideoStream=require("videostream"),VIDEOSTREAM_EXTS=[".m4a",".m4b",".m4p",".m4v",".mp4"],MEDIASOURCE_VIDEO_EXTS=[".m4v",".mkv",".mp4",".webm"],MEDIASOURCE_EXTS=[].concat(MEDIASOURCE_VIDEO_EXTS,[".m4a",".m4b",".m4p",".mp3"]),VIDEO_EXTS=[".mov",".ogv"],AUDIO_EXTS=[".aac",".oga",".ogg",".wav",".flac"],IMAGE_EXTS=[".bmp",".gif",".jpeg",".jpg",".png",".svg"],IFRAME_EXTS=[".css",".html",".js",".md",".pdf",".srt",".txt"],MAX_BLOB_LENGTH=200000000,MediaSource="undefined"!=typeof window&&window.MediaSource},{"./lib/mime.json":88,debug:33,"is-ascii":43,mediasource:48,path:26,"stream-to-blob-url":104,videostream:121}],88:[function(require,module){module.exports={".3gp":"video/3gpp",".aac":"audio/aac",".aif":"audio/x-aiff",".aiff":"audio/x-aiff",".atom":"application/atom+xml",".avi":"video/x-msvideo",".bmp":"image/bmp",".bz2":"application/x-bzip2",".conf":"text/plain",".css":"text/css",".csv":"text/plain",".diff":"text/x-diff",".doc":"application/msword",".flv":"video/x-flv",".gif":"image/gif",".gz":"application/x-gzip",".htm":"text/html",".html":"text/html",".ico":"image/vnd.microsoft.icon",".ics":"text/calendar",".iso":"application/octet-stream",".jar":"application/java-archive",".jpeg":"image/jpeg",".jpg":"image/jpeg",".js":"application/javascript",".json":"application/json",".less":"text/css",".log":"text/plain",".m3u":"audio/x-mpegurl",".m4a":"audio/x-m4a",".m4b":"audio/mp4",".m4p":"audio/mp4",".m4v":"video/x-m4v",".manifest":"text/cache-manifest",".markdown":"text/x-markdown",".mathml":"application/mathml+xml",".md":"text/x-markdown",".mid":"audio/midi",".midi":"audio/midi",".mov":"video/quicktime",".mp3":"audio/mpeg",".mp4":"video/mp4",".mp4v":"video/mp4",".mpeg":"video/mpeg",".mpg":"video/mpeg",".odp":"application/vnd.oasis.opendocument.presentation",".ods":"application/vnd.oasis.opendocument.spreadsheet",".odt":"application/vnd.oasis.opendocument.text",".oga":"audio/ogg",".ogg":"application/ogg",".pdf":"application/pdf",".png":"image/png",".pps":"application/vnd.ms-powerpoint",".ppt":"application/vnd.ms-powerpoint",".ps":"application/postscript",".psd":"image/vnd.adobe.photoshop",".qt":"video/quicktime",".rar":"application/x-rar-compressed",".rdf":"application/rdf+xml",".rss":"application/rss+xml",".rtf":"application/rtf",".svg":"image/svg+xml",".svgz":"image/svg+xml",".swf":"application/x-shockwave-flash",".tar":"application/x-tar",".tbz":"application/x-bzip-compressed-tar",".text":"text/plain",".tif":"image/tiff",".tiff":"image/tiff",".torrent":"application/x-bittorrent",".ttf":"application/x-font-ttf",".txt":"text/plain",".wav":"audio/wav",".webm":"video/webm",".wma":"audio/x-ms-wma",".wmv":"video/x-ms-wmv",".xls":"application/vnd.ms-excel",".xml":"application/xml",".yaml":"text/yaml",".yml":"text/yaml",".zip":"application/zip"}},{}],89:[function(require,module){(function(process){(function(){/*! run-parallel-limit. MIT License. Feross Aboukhadijeh */module.exports=function(tasks,limit,cb){function done(err){function end(){cb&&cb(err,results),cb=null}isSync?process.nextTick(end):end()}function each(i,err,result){if(results[i]=result,err&&(isErrored=!0),0==--pending||err)done(err);else if(!isErrored&&next */module.exports=function(tasks,cb){function done(err){function end(){cb&&cb(err,results),cb=null}isSync?process.nextTick(end):end()}function each(i,err,result){results[i]=result,(0==--pending||err)&&done(err)}var isSync=!0,results,pending,keys;Array.isArray(tasks)?(results=[],pending=tasks.length):(keys=Object.keys(tasks),results={},pending=keys.length),pending?keys?keys.forEach(function(key){tasks[key](function(err,result){each(key,err,result)})}):tasks.forEach(function(task,i){task(function(err,result){each(i,err,result)})}):done(null),isSync=!1}}).call(this)}).call(this,require("_process"))},{_process:62}],91:[function(require,module,exports){(function(root,factory){"object"==typeof exports&&"object"==typeof module?module.exports=factory():"function"==typeof define&&define.amd?define([],factory):"object"==typeof exports?exports.Rusha=factory():root.Rusha=factory()})("undefined"==typeof self?this:self,function(){return function(modules){function __webpack_require__(moduleId){if(installedModules[moduleId])return installedModules[moduleId].exports;var module=installedModules[moduleId]={i:moduleId,l:!1,exports:{}};return modules[moduleId].call(module.exports,module,module.exports,__webpack_require__),module.l=!0,module.exports}var installedModules={};return __webpack_require__.m=modules,__webpack_require__.c=installedModules,__webpack_require__.d=function(exports,name,getter){__webpack_require__.o(exports,name)||Object.defineProperty(exports,name,{configurable:!1,enumerable:!0,get:getter})},__webpack_require__.n=function(module){var getter=module&&module.__esModule?function(){return module["default"]}:function(){return module};return __webpack_require__.d(getter,"a",getter),getter},__webpack_require__.o=function(object,property){return Object.prototype.hasOwnProperty.call(object,property)},__webpack_require__.p="",__webpack_require__(__webpack_require__.s=3)}([function(module,exports,__webpack_require__){function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}var RushaCore=__webpack_require__(5),_require=__webpack_require__(1),toHex=_require.toHex,ceilHeapSize=_require.ceilHeapSize,conv=__webpack_require__(6),padlen=function(len){for(len+=9;0>2)+1;i>2]|=128<<24-(chunkLen%4<<3),bin[(-16&(chunkLen>>2)+2)+14]=0|msgLen/536870912,bin[(-16&(chunkLen>>2)+2)+15]=msgLen<<3},getRawDigest=function(heap,padMaxChunkLen){var io=new Int32Array(heap,padMaxChunkLen+320,5),out=new Int32Array(5),arr=new DataView(out.buffer);return arr.setInt32(0,io[0],!1),arr.setInt32(4,io[1],!1),arr.setInt32(8,io[2],!1),arr.setInt32(12,io[3],!1),arr.setInt32(16,io[4],!1),out},Rusha=function(){function Rusha(chunkSize){if(_classCallCheck(this,Rusha),chunkSize=chunkSize||65536,0>2);return padZeroes(view,chunkLen),padData(view,chunkLen,msgLen),padChunkLen},Rusha.prototype._write=function(data,chunkOffset,chunkLen,off){conv(data,this._h8,this._h32,chunkOffset,chunkLen,off||0)},Rusha.prototype._coreCall=function(data,chunkOffset,chunkLen,msgLen,finalize){var padChunkLen=chunkLen;this._write(data,chunkOffset,chunkLen),finalize&&(padChunkLen=this._padChunk(chunkLen,msgLen)),this._core.hash(padChunkLen,this._padMaxChunkLen)},Rusha.prototype.rawDigest=function(str){var msgLen=str.byteLength||str.length||str.size||0;this._initState(this._heap,this._padMaxChunkLen);var chunkOffset=0,chunkLen=this._maxChunkLen;for(chunkOffset=0;msgLen>chunkOffset+chunkLen;chunkOffset+=chunkLen)this._coreCall(str,chunkOffset,chunkLen,msgLen,!1);return this._coreCall(str,chunkOffset,msgLen-chunkOffset,msgLen,!0),getRawDigest(this._heap,this._padMaxChunkLen)},Rusha.prototype.digest=function(str){return toHex(this.rawDigest(str).buffer)},Rusha.prototype.digestFromString=function(str){return this.digest(str)},Rusha.prototype.digestFromBuffer=function(str){return this.digest(str)},Rusha.prototype.digestFromArrayBuffer=function(str){return this.digest(str)},Rusha.prototype.resetState=function(){return this._initState(this._heap,this._padMaxChunkLen),this},Rusha.prototype.append=function(chunk){var chunkOffset=0,chunkLen=chunk.byteLength||chunk.length||chunk.size||0,turnOffset=this._offset%this._maxChunkLen,inputLen=void 0;for(this._offset+=chunkLen;chunkOffseti;i++)precomputedHex[i]=(16>i?"0":"")+i.toString(16);module.exports.toHex=function(arrayBuffer){for(var binarray=new Uint8Array(arrayBuffer),res=Array(arrayBuffer.byteLength),_i=0;_i=v)return 65536;if(16777216>v)for(p=1;p>2],y1$857=0|H$849[x$852+324>>2],y2$859=0|H$849[x$852+328>>2],y3$861=0|H$849[x$852+332>>2],y4$863=0|H$849[x$852+336>>2],i$853=0;(0|i$853)<(0|k$851);i$853=0|i$853+64){for(z0$856=y0$855,z1$858=y1$857,z2$860=y2$859,z3$862=y3$861,z4$864=y4$863,j$854=0;64>(0|j$854);j$854=0|j$854+4)t1$866=0|H$849[i$853+j$854>>2],t0$865=0|(0|(y0$855<<5|y0$855>>>27)+(y1$857&y2$859|~y1$857&y3$861))+(0|(0|t1$866+y4$863)+1518500249),y4$863=y3$861,y3$861=y2$859,y2$859=y1$857<<30|y1$857>>>2,y1$857=y0$855,y0$855=t0$865,H$849[k$851+j$854>>2]=t1$866;for(j$854=0|k$851+64;(0|j$854)<(0|k$851+80);j$854=0|j$854+4)t1$866=(H$849[j$854-12>>2]^H$849[j$854-32>>2]^H$849[j$854-56>>2]^H$849[j$854-64>>2])<<1|(H$849[j$854-12>>2]^H$849[j$854-32>>2]^H$849[j$854-56>>2]^H$849[j$854-64>>2])>>>31,t0$865=0|(0|(y0$855<<5|y0$855>>>27)+(y1$857&y2$859|~y1$857&y3$861))+(0|(0|t1$866+y4$863)+1518500249),y4$863=y3$861,y3$861=y2$859,y2$859=y1$857<<30|y1$857>>>2,y1$857=y0$855,y0$855=t0$865,H$849[j$854>>2]=t1$866;for(j$854=0|k$851+80;(0|j$854)<(0|k$851+160);j$854=0|j$854+4)t1$866=(H$849[j$854-12>>2]^H$849[j$854-32>>2]^H$849[j$854-56>>2]^H$849[j$854-64>>2])<<1|(H$849[j$854-12>>2]^H$849[j$854-32>>2]^H$849[j$854-56>>2]^H$849[j$854-64>>2])>>>31,t0$865=0|(0|(y0$855<<5|y0$855>>>27)+(y1$857^y2$859^y3$861))+(0|(0|t1$866+y4$863)+1859775393),y4$863=y3$861,y3$861=y2$859,y2$859=y1$857<<30|y1$857>>>2,y1$857=y0$855,y0$855=t0$865,H$849[j$854>>2]=t1$866;for(j$854=0|k$851+160;(0|j$854)<(0|k$851+240);j$854=0|j$854+4)t1$866=(H$849[j$854-12>>2]^H$849[j$854-32>>2]^H$849[j$854-56>>2]^H$849[j$854-64>>2])<<1|(H$849[j$854-12>>2]^H$849[j$854-32>>2]^H$849[j$854-56>>2]^H$849[j$854-64>>2])>>>31,t0$865=0|(0|(y0$855<<5|y0$855>>>27)+(y1$857&y2$859|y1$857&y3$861|y2$859&y3$861))+(0|(0|t1$866+y4$863)-1894007588),y4$863=y3$861,y3$861=y2$859,y2$859=y1$857<<30|y1$857>>>2,y1$857=y0$855,y0$855=t0$865,H$849[j$854>>2]=t1$866;for(j$854=0|k$851+240;(0|j$854)<(0|k$851+320);j$854=0|j$854+4)t1$866=(H$849[j$854-12>>2]^H$849[j$854-32>>2]^H$849[j$854-56>>2]^H$849[j$854-64>>2])<<1|(H$849[j$854-12>>2]^H$849[j$854-32>>2]^H$849[j$854-56>>2]^H$849[j$854-64>>2])>>>31,t0$865=0|(0|(y0$855<<5|y0$855>>>27)+(y1$857^y2$859^y3$861))+(0|(0|t1$866+y4$863)-899497514),y4$863=y3$861,y3$861=y2$859,y2$859=y1$857<<30|y1$857>>>2,y1$857=y0$855,y0$855=t0$865,H$849[j$854>>2]=t1$866;y0$855=0|y0$855+z0$856,y1$857=0|y1$857+z1$858,y2$859=0|y2$859+z2$860,y3$861=0|y3$861+z3$862,y4$863=0|y4$863+z4$864}H$849[x$852+320>>2]=y0$855,H$849[x$852+324>>2]=y1$857,H$849[x$852+328>>2]=y2$859,H$849[x$852+332>>2]=y3$861,H$849[x$852+336>>2]=y4$863}}}},function(module){var _this=this,reader=void 0;"undefined"!=typeof self&&"undefined"!=typeof self.FileReaderSync&&(reader=new self.FileReaderSync);var convStr=function(str,H8,H32,start,len,off){var om=off%4,lm=(len+om)%4,j=len-lm,i;switch(om){case 0:H8[off]=str.charCodeAt(start+3);case 1:H8[0|off+1-(om<<1)]=str.charCodeAt(start+2);case 2:H8[0|off+2-(om<<1)]=str.charCodeAt(start+1);case 3:H8[0|off+3-(om<<1)]=str.charCodeAt(start);}if(!(len>2]=str.charCodeAt(start+i)<<24|str.charCodeAt(start+i+1)<<16|str.charCodeAt(start+i+2)<<8|str.charCodeAt(start+i+3);switch(lm){case 3:H8[0|off+j+1]=str.charCodeAt(start+j+2);case 2:H8[0|off+j+2]=str.charCodeAt(start+j+1);case 1:H8[0|off+j+3]=str.charCodeAt(start+j);}}},convBuf=function(buf,H8,H32,start,len,off){var om=off%4,lm=(len+om)%4,j=len-lm,i;switch(om){case 0:H8[off]=buf[start+3];case 1:H8[0|off+1-(om<<1)]=buf[start+2];case 2:H8[0|off+2-(om<<1)]=buf[start+1];case 3:H8[0|off+3-(om<<1)]=buf[start];}if(!(len>2]=buf[start+i]<<24|buf[start+i+1]<<16|buf[start+i+2]<<8|buf[start+i+3];switch(lm){case 3:H8[0|off+j+1]=buf[start+j+2];case 2:H8[0|off+j+2]=buf[start+j+1];case 1:H8[0|off+j+3]=buf[start+j];}}},convBlob=function(blob,H8,H32,start,len,off){var i=void 0,om=off%4,lm=(len+om)%4,j=len-lm,buf=new Uint8Array(reader.readAsArrayBuffer(blob.slice(start,start+len)));switch(om){case 0:H8[off]=buf[3];case 1:H8[0|off+1-(om<<1)]=buf[2];case 2:H8[0|off+2-(om<<1)]=buf[1];case 3:H8[0|off+3-(om<<1)]=buf[0];}if(!(len>2]=buf[i]<<24|buf[i+1]<<16|buf[i+2]<<8|buf[i+3];switch(lm){case 3:H8[0|off+j+1]=buf[j+2];case 2:H8[0|off+j+2]=buf[j+1];case 1:H8[0|off+j+3]=buf[j];}}};module.exports=function(data,H8,H32,start,len,off){if("string"==typeof data)return convStr(data,H8,H32,start,len,off);if(data instanceof Array)return convBuf(data,H8,H32,start,len,off);if(_this&&_this.Buffer&&_this.Buffer.isBuffer(data))return convBuf(data,H8,H32,start,len,off);if(data instanceof ArrayBuffer)return convBuf(new Uint8Array(data),H8,H32,start,len,off);if(data.buffer instanceof ArrayBuffer)return convBuf(new Uint8Array(data.buffer,data.byteOffset,data.byteLength),H8,H32,start,len,off);if(data instanceof Blob)return convBlob(data,H8,H32,start,len,off);throw new Error("Unsupported data type.")}},function(module,exports,__webpack_require__){function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}var Rusha=__webpack_require__(0),_require=__webpack_require__(1),toHex=_require.toHex,Hash=function(){function Hash(){_classCallCheck(this,Hash),this._rusha=new Rusha,this._rusha.resetState()}return Hash.prototype.update=function(data){return this._rusha.append(data),this},Hash.prototype.digest=function digest(encoding){var digest=this._rusha.rawEnd().buffer;if(!encoding)return digest;if("hex"===encoding)return toHex(digest);throw new Error("unsupported digest encoding")},Hash}();module.exports=function(){return new Hash}}])})},{}],92:[function(require,module,exports){function copyProps(src,dst){for(var key in src)dst[key]=src[key]}function SafeBuffer(arg,encodingOrOffset,length){return Buffer(arg,encodingOrOffset,length)}/*! safe-buffer. MIT License. Feross Aboukhadijeh */var buffer=require("buffer"),Buffer=buffer.Buffer;Buffer.from&&Buffer.alloc&&Buffer.allocUnsafe&&Buffer.allocUnsafeSlow?module.exports=buffer:(copyProps(buffer,exports),exports.Buffer=SafeBuffer),SafeBuffer.prototype=Object.create(Buffer.prototype),copyProps(Buffer,SafeBuffer),SafeBuffer.from=function(arg,encodingOrOffset,length){if("number"==typeof arg)throw new TypeError("Argument must not be a number");return Buffer(arg,encodingOrOffset,length)},SafeBuffer.alloc=function(size,fill,encoding){if("number"!=typeof size)throw new TypeError("Argument must be a number");var buf=Buffer(size);return void 0===fill?buf.fill(0):"string"==typeof encoding?buf.fill(fill,encoding):buf.fill(fill),buf},SafeBuffer.allocUnsafe=function(size){if("number"!=typeof size)throw new TypeError("Argument must be a number");return Buffer(size)},SafeBuffer.allocUnsafeSlow=function(size){if("number"!=typeof size)throw new TypeError("Argument must be a number");return buffer.SlowBuffer(size)}},{buffer:24}],93:[function(require,module){(function(Buffer){(function(){/*! simple-concat. MIT License. Feross Aboukhadijeh */module.exports=function(stream,cb){var chunks=[];stream.on("data",function(chunk){chunks.push(chunk)}),stream.once("end",function(){cb&&cb(null,Buffer.concat(chunks)),cb=null}),stream.once("error",function(err){cb&&cb(err),cb=null})}}).call(this)}).call(this,require("buffer").Buffer)},{buffer:24}],94:[function(require,module){(function(Buffer){(function(){function simpleGet(opts,cb){if(opts=Object.assign({maxRedirects:10},"string"==typeof opts?{url:opts}:opts),cb=once(cb),opts.url){const{hostname,port,protocol,auth,path}=url.parse(opts.url);delete opts.url,hostname||port||protocol||auth?Object.assign(opts,{hostname,port,protocol,auth,path}):opts.path=path}const headers={"accept-encoding":"gzip, deflate"};opts.headers&&Object.keys(opts.headers).forEach(k=>headers[k.toLowerCase()]=opts.headers[k]),opts.headers=headers;let body;opts.body?body=opts.json&&!isStream(opts.body)?JSON.stringify(opts.body):opts.body:opts.form&&(body="string"==typeof opts.form?opts.form:querystring.stringify(opts.form),opts.headers["content-type"]="application/x-www-form-urlencoded"),body&&(!opts.method&&(opts.method="POST"),!isStream(body)&&(opts.headers["content-length"]=Buffer.byteLength(body)),opts.json&&!opts.form&&(opts.headers["content-type"]="application/json")),delete opts.body,delete opts.form,opts.json&&(opts.headers.accept="application/json"),opts.method&&(opts.method=opts.method.toUpperCase());const protocol="https:"===opts.protocol?https:http,req=protocol.request(opts,res=>{if(!1!==opts.followRedirects&&300<=res.statusCode&&400>res.statusCode&&res.headers.location)return opts.url=res.headers.location,delete opts.headers.host,res.resume(),"POST"===opts.method&&[301,302].includes(res.statusCode)&&(opts.method="GET",delete opts.headers["content-length"],delete opts.headers["content-type"]),0==opts.maxRedirects--?cb(new Error("too many redirects")):simpleGet(opts,cb);const tryUnzip="function"==typeof decompressResponse&&"HEAD"!==opts.method;cb(null,tryUnzip?decompressResponse(res):res)});return req.on("timeout",()=>{req.abort(),cb(new Error("Request timed out"))}),req.on("error",cb),isStream(body)?body.on("error",cb).pipe(req):req.end(body),req}module.exports=simpleGet;const concat=require("simple-concat"),decompressResponse=require("decompress-response"),http=require("http"),https=require("https"),once=require("once"),querystring=require("querystring"),url=require("url"),isStream=o=>null!==o&&"object"==typeof o&&"function"==typeof o.pipe;simpleGet.concat=(opts,cb)=>simpleGet(opts,(err,res)=>err?cb(err):void concat(res,(err,data)=>{if(err)return cb(err);if(opts.json)try{data=JSON.parse(data.toString())}catch(err){return cb(err,res,data)}cb(null,res,data)})),["get","post","put","patch","head","delete"].forEach(method=>{simpleGet[method]=(opts,cb)=>("string"==typeof opts&&(opts={url:opts}),simpleGet(Object.assign({method:method.toUpperCase()},opts),cb))})}).call(this)}).call(this,require("buffer").Buffer)},{buffer:24,"decompress-response":22,http:100,https:39,once:59,querystring:67,"simple-concat":93,url:116}],95:[function(require,module){function filterTrickle(sdp){return sdp.replace(/a=ice-options:trickle\s\n/g,"")}function warn(message){console.warn(message)}/*! simple-peer. MIT License. Feross Aboukhadijeh */const debug=require("debug")("simple-peer"),getBrowserRTC=require("get-browser-rtc"),randombytes=require("randombytes"),stream=require("readable-stream"),queueMicrotask=require("queue-microtask"),errCode=require("err-code"),{Buffer}=require("buffer"),MAX_BUFFERED_AMOUNT=65536;class Peer extends stream.Duplex{constructor(opts){if(opts=Object.assign({allowHalfOpen:!1},opts),super(opts),this._id=randombytes(4).toString("hex").slice(0,7),this._debug("new peer %o",opts),this.channelName=opts.initiator?opts.channelName||randombytes(20).toString("hex"):null,this.initiator=opts.initiator||!1,this.channelConfig=opts.channelConfig||Peer.channelConfig,this.channelNegotiated=this.channelConfig.negotiated,this.config=Object.assign({},Peer.config,opts.config),this.offerOptions=opts.offerOptions||{},this.answerOptions=opts.answerOptions||{},this.sdpTransform=opts.sdpTransform||(sdp=>sdp),this.streams=opts.streams||(opts.stream?[opts.stream]:[]),this.trickle=void 0===opts.trickle||opts.trickle,this.allowHalfTrickle=void 0!==opts.allowHalfTrickle&&opts.allowHalfTrickle,this.iceCompleteTimeout=opts.iceCompleteTimeout||5000,this.destroyed=!1,this.destroying=!1,this._connected=!1,this.remoteAddress=void 0,this.remoteFamily=void 0,this.remotePort=void 0,this.localAddress=void 0,this.localFamily=void 0,this.localPort=void 0,this._wrtc=opts.wrtc&&"object"==typeof opts.wrtc?opts.wrtc:getBrowserRTC(),!this._wrtc)if("undefined"==typeof window)throw errCode(new Error("No WebRTC support: Specify `opts.wrtc` option in this environment"),"ERR_WEBRTC_SUPPORT");else throw errCode(new Error("No WebRTC support: Not a supported browser"),"ERR_WEBRTC_SUPPORT");this._pcReady=!1,this._channelReady=!1,this._iceComplete=!1,this._iceCompleteTimer=null,this._channel=null,this._pendingCandidates=[],this._isNegotiating=!1,this._firstNegotiation=!0,this._batchedNegotiation=!1,this._queuedNegotiation=!1,this._sendersAwaitingStable=[],this._senderMap=new Map,this._closingInterval=null,this._remoteTracks=[],this._remoteStreams=[],this._chunk=null,this._cb=null,this._interval=null;try{this._pc=new this._wrtc.RTCPeerConnection(this.config)}catch(err){return void queueMicrotask(()=>this.destroy(errCode(err,"ERR_PC_CONSTRUCTOR")))}this._isReactNativeWebrtc="number"==typeof this._pc._peerConnectionId,this._pc.oniceconnectionstatechange=()=>{this._onIceStateChange()},this._pc.onicegatheringstatechange=()=>{this._onIceStateChange()},this._pc.onconnectionstatechange=()=>{this._onConnectionStateChange()},this._pc.onsignalingstatechange=()=>{this._onSignalingStateChange()},this._pc.onicecandidate=event=>{this._onIceCandidate(event)},this.initiator||this.channelNegotiated?this._setupData({channel:this._pc.createDataChannel(this.channelName,this.channelConfig)}):this._pc.ondatachannel=event=>{this._setupData(event)},this.streams&&this.streams.forEach(stream=>{this.addStream(stream)}),this._pc.ontrack=event=>{this._onTrack(event)},this._debug("initial negotiation"),this._needsNegotiation(),this._onFinishBound=()=>{this._onFinish()},this.once("finish",this._onFinishBound)}get bufferSize(){return this._channel&&this._channel.bufferedAmount||0}get connected(){return this._connected&&"open"===this._channel.readyState}address(){return{port:this.localPort,family:this.localFamily,address:this.localAddress}}signal(data){if(this.destroyed)throw errCode(new Error("cannot signal after peer is destroyed"),"ERR_SIGNALING");if("string"==typeof data)try{data=JSON.parse(data)}catch(err){data={}}this._debug("signal()"),data.renegotiate&&this.initiator&&(this._debug("got request to renegotiate"),this._needsNegotiation()),data.transceiverRequest&&this.initiator&&(this._debug("got request for transceiver"),this.addTransceiver(data.transceiverRequest.kind,data.transceiverRequest.init)),data.candidate&&(this._pc.remoteDescription&&this._pc.remoteDescription.type?this._addIceCandidate(data.candidate):this._pendingCandidates.push(data.candidate)),data.sdp&&this._pc.setRemoteDescription(new this._wrtc.RTCSessionDescription(data)).then(()=>{this.destroyed||(this._pendingCandidates.forEach(candidate=>{this._addIceCandidate(candidate)}),this._pendingCandidates=[],"offer"===this._pc.remoteDescription.type&&this._createAnswer())}).catch(err=>{this.destroy(errCode(err,"ERR_SET_REMOTE_DESCRIPTION"))}),data.sdp||data.candidate||data.renegotiate||data.transceiverRequest||this.destroy(errCode(new Error("signal() called with invalid signal data"),"ERR_SIGNALING"))}_addIceCandidate(candidate){const iceCandidateObj=new this._wrtc.RTCIceCandidate(candidate);this._pc.addIceCandidate(iceCandidateObj).catch(err=>{!iceCandidateObj.address||iceCandidateObj.address.endsWith(".local")?warn("Ignoring unsupported ICE candidate."):this.destroy(errCode(err,"ERR_ADD_ICE_CANDIDATE"))})}send(chunk){this._channel.send(chunk)}addTransceiver(kind,init){if(this._debug("addTransceiver()"),this.initiator)try{this._pc.addTransceiver(kind,init),this._needsNegotiation()}catch(err){this.destroy(errCode(err,"ERR_ADD_TRANSCEIVER"))}else this.emit("signal",{type:"transceiverRequest",transceiverRequest:{kind,init}})}addStream(stream){this._debug("addStream()"),stream.getTracks().forEach(track=>{this.addTrack(track,stream)})}addTrack(track,stream){this._debug("addTrack()");const submap=this._senderMap.get(track)||new Map;let sender=submap.get(stream);if(!sender)sender=this._pc.addTrack(track,stream),submap.set(stream,sender),this._senderMap.set(track,submap),this._needsNegotiation();else if(sender.removed)throw errCode(new Error("Track has been removed. You should enable/disable tracks that you want to re-add."),"ERR_SENDER_REMOVED");else throw errCode(new Error("Track has already been added to that stream."),"ERR_SENDER_ALREADY_ADDED")}replaceTrack(oldTrack,newTrack,stream){this._debug("replaceTrack()");const submap=this._senderMap.get(oldTrack),sender=submap?submap.get(stream):null;if(!sender)throw errCode(new Error("Cannot replace track that was never added."),"ERR_TRACK_NOT_ADDED");newTrack&&this._senderMap.set(newTrack,submap),null==sender.replaceTrack?this.destroy(errCode(new Error("replaceTrack is not supported in this browser"),"ERR_UNSUPPORTED_REPLACETRACK")):sender.replaceTrack(newTrack)}removeTrack(track,stream){this._debug("removeSender()");const submap=this._senderMap.get(track),sender=submap?submap.get(stream):null;if(!sender)throw errCode(new Error("Cannot remove track that was never added."),"ERR_TRACK_NOT_ADDED");try{sender.removed=!0,this._pc.removeTrack(sender)}catch(err){"NS_ERROR_UNEXPECTED"===err.name?this._sendersAwaitingStable.push(sender):this.destroy(errCode(err,"ERR_REMOVE_TRACK"))}this._needsNegotiation()}removeStream(stream){this._debug("removeSenders()"),stream.getTracks().forEach(track=>{this.removeTrack(track,stream)})}_needsNegotiation(){this._debug("_needsNegotiation");this._batchedNegotiation||(this._batchedNegotiation=!0,queueMicrotask(()=>{this._batchedNegotiation=!1,this.initiator||!this._firstNegotiation?(this._debug("starting batched negotiation"),this.negotiate()):this._debug("non-initiator initial negotiation request discarded"),this._firstNegotiation=!1}))}negotiate(){this.initiator?this._isNegotiating?(this._queuedNegotiation=!0,this._debug("already negotiating, queueing")):(this._debug("start negotiation"),setTimeout(()=>{this._createOffer()},0)):this._isNegotiating?(this._queuedNegotiation=!0,this._debug("already negotiating, queueing")):(this._debug("requesting negotiation from initiator"),this.emit("signal",{type:"renegotiate",renegotiate:!0})),this._isNegotiating=!0}destroy(err){this._destroy(err,()=>{})}_destroy(err,cb){this.destroyed||this.destroying||(this.destroying=!0,this._debug("destroying (error: %s)",err&&(err.message||err)),queueMicrotask(()=>{if(this.destroyed=!0,this.destroying=!1,this._debug("destroy (error: %s)",err&&(err.message||err)),this.readable=this.writable=!1,this._readableState.ended||this.push(null),this._writableState.finished||this.end(),this._connected=!1,this._pcReady=!1,this._channelReady=!1,this._remoteTracks=null,this._remoteStreams=null,this._senderMap=null,clearInterval(this._closingInterval),this._closingInterval=null,clearInterval(this._interval),this._interval=null,this._chunk=null,this._cb=null,this._onFinishBound&&this.removeListener("finish",this._onFinishBound),this._onFinishBound=null,this._channel){try{this._channel.close()}catch(err){}this._channel.onmessage=null,this._channel.onopen=null,this._channel.onclose=null,this._channel.onerror=null}if(this._pc){try{this._pc.close()}catch(err){}this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ontrack=null,this._pc.ondatachannel=null}this._pc=null,this._channel=null,err&&this.emit("error",err),this.emit("close"),cb()}))}_setupData(event){if(!event.channel)return this.destroy(errCode(new Error("Data channel event is missing `channel` property"),"ERR_DATA_CHANNEL"));this._channel=event.channel,this._channel.binaryType="arraybuffer","number"==typeof this._channel.bufferedAmountLowThreshold&&(this._channel.bufferedAmountLowThreshold=MAX_BUFFERED_AMOUNT),this.channelName=this._channel.label,this._channel.onmessage=event=>{this._onChannelMessage(event)},this._channel.onbufferedamountlow=()=>{this._onChannelBufferedAmountLow()},this._channel.onopen=()=>{this._onChannelOpen()},this._channel.onclose=()=>{this._onChannelClose()},this._channel.onerror=err=>{this.destroy(errCode(err,"ERR_DATA_CHANNEL"))};let isClosing=!1;this._closingInterval=setInterval(()=>{this._channel&&"closing"===this._channel.readyState?(isClosing&&this._onChannelClose(),isClosing=!0):isClosing=!1},5000)}_read(){}_write(chunk,encoding,cb){if(this.destroyed)return cb(errCode(new Error("cannot write after peer is destroyed"),"ERR_DATA_CHANNEL"));if(this._connected){try{this.send(chunk)}catch(err){return this.destroy(errCode(err,"ERR_DATA_CHANNEL"))}this._channel.bufferedAmount>MAX_BUFFERED_AMOUNT?(this._debug("start backpressure: bufferedAmount %d",this._channel.bufferedAmount),this._cb=cb):cb(null)}else this._debug("write before connect"),this._chunk=chunk,this._cb=cb}_onFinish(){if(!this.destroyed){const destroySoon=()=>{setTimeout(()=>this.destroy(),1e3)};this._connected?destroySoon():this.once("connect",destroySoon)}}_startIceCompleteTimeout(){this.destroyed||this._iceCompleteTimer||(this._debug("started iceComplete timeout"),this._iceCompleteTimer=setTimeout(()=>{this._iceComplete||(this._iceComplete=!0,this._debug("iceComplete timeout completed"),this.emit("iceTimeout"),this.emit("_iceComplete"))},this.iceCompleteTimeout))}_createOffer(){this.destroyed||this._pc.createOffer(this.offerOptions).then(offer=>{if(this.destroyed)return;this.trickle||this.allowHalfTrickle||(offer.sdp=filterTrickle(offer.sdp)),offer.sdp=this.sdpTransform(offer.sdp);const sendOffer=()=>{if(!this.destroyed){const signal=this._pc.localDescription||offer;this._debug("signal"),this.emit("signal",{type:signal.type,sdp:signal.sdp})}};this._pc.setLocalDescription(offer).then(()=>{this._debug("createOffer success");this.destroyed||(this.trickle||this._iceComplete?sendOffer():this.once("_iceComplete",sendOffer))}).catch(err=>{this.destroy(errCode(err,"ERR_SET_LOCAL_DESCRIPTION"))})}).catch(err=>{this.destroy(errCode(err,"ERR_CREATE_OFFER"))})}_requestMissingTransceivers(){this._pc.getTransceivers&&this._pc.getTransceivers().forEach(transceiver=>{transceiver.mid||!transceiver.sender.track||transceiver.requested||(transceiver.requested=!0,this.addTransceiver(transceiver.sender.track.kind))})}_createAnswer(){this.destroyed||this._pc.createAnswer(this.answerOptions).then(answer=>{if(this.destroyed)return;this.trickle||this.allowHalfTrickle||(answer.sdp=filterTrickle(answer.sdp)),answer.sdp=this.sdpTransform(answer.sdp);const sendAnswer=()=>{if(!this.destroyed){const signal=this._pc.localDescription||answer;this._debug("signal"),this.emit("signal",{type:signal.type,sdp:signal.sdp}),this.initiator||this._requestMissingTransceivers()}};this._pc.setLocalDescription(answer).then(()=>{this.destroyed||(this.trickle||this._iceComplete?sendAnswer():this.once("_iceComplete",sendAnswer))}).catch(err=>{this.destroy(errCode(err,"ERR_SET_LOCAL_DESCRIPTION"))})}).catch(err=>{this.destroy(errCode(err,"ERR_CREATE_ANSWER"))})}_onConnectionStateChange(){this.destroyed||"failed"===this._pc.connectionState&&this.destroy(errCode(new Error("Connection failed."),"ERR_CONNECTION_FAILURE"))}_onIceStateChange(){if(this.destroyed)return;const iceConnectionState=this._pc.iceConnectionState,iceGatheringState=this._pc.iceGatheringState;this._debug("iceStateChange (connection: %s) (gathering: %s)",iceConnectionState,iceGatheringState),this.emit("iceStateChange",iceConnectionState,iceGatheringState),("connected"===iceConnectionState||"completed"===iceConnectionState)&&(this._pcReady=!0,this._maybeReady()),"failed"===iceConnectionState&&this.destroy(errCode(new Error("Ice connection failed."),"ERR_ICE_CONNECTION_FAILURE")),"closed"===iceConnectionState&&this.destroy(errCode(new Error("Ice connection closed."),"ERR_ICE_CONNECTION_CLOSED"))}getStats(cb){const flattenValues=report=>("[object Array]"===Object.prototype.toString.call(report.values)&&report.values.forEach(value=>{Object.assign(report,value)}),report);0===this._pc.getStats.length||this._isReactNativeWebrtc?this._pc.getStats().then(res=>{const reports=[];res.forEach(report=>{reports.push(flattenValues(report))}),cb(null,reports)},err=>cb(err)):0{if(this.destroyed)return;const reports=[];res.result().forEach(result=>{const report={};result.names().forEach(name=>{report[name]=result.stat(name)}),report.id=result.id,report.type=result.type,report.timestamp=result.timestamp,reports.push(flattenValues(report))}),cb(null,reports)},err=>cb(err)):cb(null,[])}_maybeReady(){if(this._debug("maybeReady pc %s channel %s",this._pcReady,this._channelReady),this._connected||this._connecting||!this._pcReady||!this._channelReady)return;this._connecting=!0;const findCandidatePair=()=>{this.destroyed||this.getStats((err,items)=>{if(this.destroyed)return;err&&(items=[]);const remoteCandidates={},localCandidates={},candidatePairs={};let foundSelectedCandidatePair=!1;items.forEach(item=>{("remotecandidate"===item.type||"remote-candidate"===item.type)&&(remoteCandidates[item.id]=item),("localcandidate"===item.type||"local-candidate"===item.type)&&(localCandidates[item.id]=item),("candidatepair"===item.type||"candidate-pair"===item.type)&&(candidatePairs[item.id]=item)});const setSelectedCandidatePair=selectedCandidatePair=>{foundSelectedCandidatePair=!0;let local=localCandidates[selectedCandidatePair.localCandidateId];local&&(local.ip||local.address)?(this.localAddress=local.ip||local.address,this.localPort=+local.port):local&&local.ipAddress?(this.localAddress=local.ipAddress,this.localPort=+local.portNumber):"string"==typeof selectedCandidatePair.googLocalAddress&&(local=selectedCandidatePair.googLocalAddress.split(":"),this.localAddress=local[0],this.localPort=+local[1]),this.localAddress&&(this.localFamily=this.localAddress.includes(":")?"IPv6":"IPv4");let remote=remoteCandidates[selectedCandidatePair.remoteCandidateId];remote&&(remote.ip||remote.address)?(this.remoteAddress=remote.ip||remote.address,this.remotePort=+remote.port):remote&&remote.ipAddress?(this.remoteAddress=remote.ipAddress,this.remotePort=+remote.portNumber):"string"==typeof selectedCandidatePair.googRemoteAddress&&(remote=selectedCandidatePair.googRemoteAddress.split(":"),this.remoteAddress=remote[0],this.remotePort=+remote[1]),this.remoteAddress&&(this.remoteFamily=this.remoteAddress.includes(":")?"IPv6":"IPv4"),this._debug("connect local: %s:%s remote: %s:%s",this.localAddress,this.localPort,this.remoteAddress,this.remotePort)};if(items.forEach(item=>{"transport"===item.type&&item.selectedCandidatePairId&&setSelectedCandidatePair(candidatePairs[item.selectedCandidatePairId]),("googCandidatePair"===item.type&&"true"===item.googActiveConnection||("candidatepair"===item.type||"candidate-pair"===item.type)&&item.selected)&&setSelectedCandidatePair(item)}),!foundSelectedCandidatePair&&(!Object.keys(candidatePairs).length||Object.keys(localCandidates).length))return void setTimeout(findCandidatePair,100);if(this._connecting=!1,this._connected=!0,this._chunk){try{this.send(this._chunk)}catch(err){return this.destroy(errCode(err,"ERR_DATA_CHANNEL"))}this._chunk=null,this._debug("sent chunk from \"write before connect\"");const cb=this._cb;this._cb=null,cb(null)}"number"!=typeof this._channel.bufferedAmountLowThreshold&&(this._interval=setInterval(()=>this._onInterval(),150),this._interval.unref&&this._interval.unref()),this._debug("connect"),this.emit("connect")})};findCandidatePair()}_onInterval(){this._cb&&this._channel&&!(this._channel.bufferedAmount>MAX_BUFFERED_AMOUNT)&&this._onChannelBufferedAmountLow()}_onSignalingStateChange(){this.destroyed||("stable"===this._pc.signalingState&&(this._isNegotiating=!1,this._debug("flushing sender queue",this._sendersAwaitingStable),this._sendersAwaitingStable.forEach(sender=>{this._pc.removeTrack(sender),this._queuedNegotiation=!0}),this._sendersAwaitingStable=[],this._queuedNegotiation?(this._debug("flushing negotiation queue"),this._queuedNegotiation=!1,this._needsNegotiation()):(this._debug("negotiated"),this.emit("negotiated"))),this._debug("signalingStateChange %s",this._pc.signalingState),this.emit("signalingStateChange",this._pc.signalingState))}_onIceCandidate(event){this.destroyed||(event.candidate&&this.trickle?this.emit("signal",{type:"candidate",candidate:{candidate:event.candidate.candidate,sdpMLineIndex:event.candidate.sdpMLineIndex,sdpMid:event.candidate.sdpMid}}):!event.candidate&&!this._iceComplete&&(this._iceComplete=!0,this.emit("_iceComplete")),event.candidate&&this._startIceCompleteTimeout())}_onChannelMessage(event){if(this.destroyed)return;let data=event.data;data instanceof ArrayBuffer&&(data=Buffer.from(data)),this.push(data)}_onChannelBufferedAmountLow(){if(!this.destroyed&&this._cb){this._debug("ending backpressure: bufferedAmount %d",this._channel.bufferedAmount);const cb=this._cb;this._cb=null,cb(null)}}_onChannelOpen(){this._connected||this.destroyed||(this._debug("on channel open"),this._channelReady=!0,this._maybeReady())}_onChannelClose(){this.destroyed||(this._debug("on channel close"),this.destroy())}_onTrack(event){this.destroyed||event.streams.forEach(eventStream=>{this._debug("on track"),this.emit("track",event.track,eventStream),this._remoteTracks.push({track:event.track,stream:eventStream});this._remoteStreams.some(remoteStream=>remoteStream.id===eventStream.id)||(this._remoteStreams.push(eventStream),queueMicrotask(()=>{this._debug("on stream"),this.emit("stream",eventStream)}))})}_debug(){const args=[].slice.call(arguments);args[0]="["+this._id+"] "+args[0],debug.apply(null,args)}}Peer.WEBRTC_SUPPORT=!!getBrowserRTC(),Peer.config={iceServers:[{urls:["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478"]}],sdpSemantics:"unified-plan"},Peer.channelConfig={},module.exports=Peer},{buffer:24,debug:33,"err-code":36,"get-browser-rtc":38,"queue-microtask":68,randombytes:70,"readable-stream":86}],96:[function(require,module){function sha1sync(buf){return rusha.digest(buf)}function sha1(buf,cb){return subtle?void("string"==typeof buf&&(buf=uint8array(buf)),subtle.digest({name:"sha-1"},buf).then(function(result){cb(hex(new Uint8Array(result)))},function(){cb(sha1sync(buf))})):void("undefined"==typeof window?queueMicrotask(()=>cb(sha1sync(buf))):rushaWorkerSha1(buf,function(err,hash){return err?void cb(sha1sync(buf)):void cb(hash)}))}function uint8array(s){for(var l=s.length,array=new Uint8Array(l),i=0;i>>4).toString(16)),chars.push((15&bite).toString(16));return chars.join("")}var Rusha=require("rusha"),rushaWorkerSha1=require("./rusha-worker-sha1"),rusha=new Rusha,scope="undefined"==typeof window?self:window,crypto=scope.crypto||scope.msCrypto||{},subtle=crypto.subtle||crypto.webkitSubtle;try{subtle.digest({name:"sha-1"},new Uint8Array).catch(function(){subtle=!1})}catch(err){subtle=!1}module.exports=sha1,module.exports.sync=sha1sync},{"./rusha-worker-sha1":97,rusha:91}],97:[function(require,module){function init(){worker=Rusha.createWorker(),nextTaskId=1,cbs={},worker.onmessage=function(e){var taskId=e.data.id,cb=cbs[taskId];delete cbs[taskId],null==e.data.error?cb(null,e.data.hash):cb(new Error("Rusha worker error: "+e.data.error))}}function sha1(buf,cb){worker||init(),cbs[nextTaskId]=cb,worker.postMessage({id:nextTaskId,data:buf}),nextTaskId+=1}var Rusha=require("rusha"),worker,nextTaskId,cbs;module.exports=sha1},{rusha:91}],98:[function(require,module){(function(Buffer){(function(){const debug=require("debug")("simple-websocket"),randombytes=require("randombytes"),stream=require("readable-stream"),queueMicrotask=require("queue-microtask"),ws=require("ws"),_WebSocket="function"==typeof ws?ws:WebSocket,MAX_BUFFERED_AMOUNT=65536;class Socket extends stream.Duplex{constructor(opts={}){if("string"==typeof opts&&(opts={url:opts}),opts=Object.assign({allowHalfOpen:!1},opts),super(opts),null==opts.url&&null==opts.socket)throw new Error("Missing required `url` or `socket` option");if(null!=opts.url&&null!=opts.socket)throw new Error("Must specify either `url` or `socket` option, not both");if(this._id=randombytes(4).toString("hex").slice(0,7),this._debug("new websocket: %o",opts),this.connected=!1,this.destroyed=!1,this._chunk=null,this._cb=null,this._interval=null,opts.socket)this.url=opts.socket.url,this._ws=opts.socket,this.connected=opts.socket.readyState===_WebSocket.OPEN;else{this.url=opts.url;try{this._ws="function"==typeof ws?new _WebSocket(opts.url,opts):new _WebSocket(opts.url)}catch(err){return void queueMicrotask(()=>this.destroy(err))}}this._ws.binaryType="arraybuffer",this._ws.onopen=()=>{this._onOpen()},this._ws.onmessage=event=>{this._onMessage(event)},this._ws.onclose=()=>{this._onClose()},this._ws.onerror=()=>{this.destroy(new Error("connection error to "+this.url))},this._onFinishBound=()=>{this._onFinish()},this.once("finish",this._onFinishBound)}send(chunk){this._ws.send(chunk)}destroy(err){this._destroy(err,()=>{})}_destroy(err,cb){if(!this.destroyed){if(this._debug("destroy (error: %s)",err&&(err.message||err)),this.readable=this.writable=!1,this._readableState.ended||this.push(null),this._writableState.finished||this.end(),this.connected=!1,this.destroyed=!0,clearInterval(this._interval),this._interval=null,this._chunk=null,this._cb=null,this._onFinishBound&&this.removeListener("finish",this._onFinishBound),this._onFinishBound=null,this._ws){const ws=this._ws,onClose=()=>{ws.onclose=null};if(ws.readyState===_WebSocket.CLOSED)onClose();else try{ws.onclose=onClose,ws.close()}catch(err){onClose()}ws.onopen=null,ws.onmessage=null,ws.onerror=()=>{}}if(this._ws=null,err){if("undefined"!=typeof DOMException&&err instanceof DOMException){const code=err.code;err=new Error(err.message),err.code=code}this.emit("error",err)}this.emit("close"),cb()}}_read(){}_write(chunk,encoding,cb){if(this.destroyed)return cb(new Error("cannot write after socket is destroyed"));if(this.connected){try{this.send(chunk)}catch(err){return this.destroy(err)}"function"!=typeof ws&&this._ws.bufferedAmount>MAX_BUFFERED_AMOUNT?(this._debug("start backpressure: bufferedAmount %d",this._ws.bufferedAmount),this._cb=cb):cb(null)}else this._debug("write before connect"),this._chunk=chunk,this._cb=cb}_onFinish(){if(!this.destroyed){const destroySoon=()=>{setTimeout(()=>this.destroy(),1e3)};this.connected?destroySoon():this.once("connect",destroySoon)}}_onMessage(event){if(this.destroyed)return;let data=event.data;data instanceof ArrayBuffer&&(data=Buffer.from(data)),this.push(data)}_onOpen(){if(!(this.connected||this.destroyed)){if(this.connected=!0,this._chunk){try{this.send(this._chunk)}catch(err){return this.destroy(err)}this._chunk=null,this._debug("sent chunk from \"write before connect\"");const cb=this._cb;this._cb=null,cb(null)}"function"!=typeof ws&&(this._interval=setInterval(()=>this._onInterval(),150),this._interval.unref&&this._interval.unref()),this._debug("connect"),this.emit("connect")}}_onInterval(){if(this._cb&&this._ws&&!(this._ws.bufferedAmount>MAX_BUFFERED_AMOUNT)){this._debug("ending backpressure: bufferedAmount %d",this._ws.bufferedAmount);const cb=this._cb;this._cb=null,cb(null)}}_onClose(){this.destroyed||(this._debug("on close"),this.destroy())}_debug(){const args=[].slice.call(arguments);args[0]="["+this._id+"] "+args[0],debug.apply(null,args)}}Socket.WEBSOCKET_SUPPORT=!!_WebSocket,module.exports=Socket}).call(this)}).call(this,require("buffer").Buffer)},{buffer:24,debug:33,"queue-microtask":68,randombytes:70,"readable-stream":86,ws:22}],99:[function(require,module){var tick=1,maxTick=65535,resolution=4,inc=function(){tick=tick+1&maxTick},timer;module.exports=function(seconds){timer||(timer=setInterval(inc,0|1e3/resolution),timer.unref&&timer.unref());var size=resolution*(seconds||5),buffer=[0],pointer=1,last=tick-1&maxTick;return function(delta){var dist=tick-last&maxTick;for(dist>size&&(dist=size),last=tick;dist--;)pointer===size&&(pointer=0),buffer[pointer]=buffer[0===pointer?size-1:pointer-1],pointer++;delta&&(buffer[pointer-1]+=delta);var top=buffer[pointer-1],btm=buffer.lengthself._pos){var newData=response.substr(self._pos);if("x-user-defined"===self._charset){for(var buffer=Buffer.alloc(newData.length),i=0;iself._pos&&(self.push(Buffer.from(new Uint8Array(reader.result.slice(self._pos)))),self._pos=reader.result.byteLength)},reader.onload=function(){self.push(null)},reader.readAsArrayBuffer(response);}self._xhr.readyState===rStates.DONE&&"ms-stream"!==self._mode&&self.push(null)}}).call(this)}).call(this,require("_process"),"undefined"==typeof global?"undefined"==typeof self?"undefined"==typeof window?{}:window:self:global,require("buffer").Buffer)},{"./capability":101,_process:62,buffer:24,inherits:42,"readable-stream":86}],104:[function(require,module){module.exports=async function(stream,mimeType){const blob=await getBlob(stream,mimeType),url=URL.createObjectURL(blob);return url};const getBlob=require("stream-to-blob")},{"stream-to-blob":105}],105:[function(require,module){/*! stream-to-blob. MIT License. Feross Aboukhadijeh */module.exports=function(stream,mimeType){if(null!=mimeType&&"string"!=typeof mimeType)throw new Error("Invalid mimetype, expected string.");return new Promise((resolve,reject)=>{const chunks=[];stream.on("data",chunk=>chunks.push(chunk)).once("end",()=>{const blob=null==mimeType?new Blob(chunks):new Blob(chunks,{type:mimeType});resolve(blob)}).once("error",reject)})}},{}],106:[function(require,module){(function(Buffer){(function(){/*! stream-with-known-length-to-buffer. MIT License. Feross Aboukhadijeh */var once=require("once");module.exports=function(stream,length,cb){cb=once(cb);var buf=Buffer.alloc(length),offset=0;stream.on("data",function(chunk){chunk.copy(buf,offset),offset+=chunk.length}).on("end",function(){cb(null,buf)}).on("error",cb)}}).call(this)}).call(this,require("buffer").Buffer)},{buffer:24,once:59}],107:[function(require,module,exports){'use strict';function _normalizeEncoding(enc){if(!enc)return"utf8";for(var retried;;)switch(enc){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return enc;default:if(retried)return;enc=(""+enc).toLowerCase(),retried=!0;}}function normalizeEncoding(enc){var nenc=_normalizeEncoding(enc);if("string"!=typeof nenc&&(Buffer.isEncoding===isEncoding||!isEncoding(enc)))throw new Error("Unknown encoding: "+enc);return nenc||enc}function StringDecoder(encoding){this.encoding=normalizeEncoding(encoding);var nb;switch(this.encoding){case"utf16le":this.text=utf16Text,this.end=utf16End,nb=4;break;case"utf8":this.fillLast=utf8FillLast,nb=4;break;case"base64":this.text=base64Text,this.end=base64End,nb=3;break;default:return this.write=simpleWrite,void(this.end=simpleEnd);}this.lastNeed=0,this.lastTotal=0,this.lastChar=Buffer.allocUnsafe(nb)}function utf8CheckByte(byte){if(127>=byte)return 0;return 6==byte>>5?2:14==byte>>4?3:30==byte>>3?4:2==byte>>6?-1:-2}function utf8CheckIncomplete(self,buf,i){var j=buf.length-1;if(j=c)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=buf[buf.length-2],this.lastChar[1]=buf[buf.length-1],r.slice(0,-1)}return r}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=buf[buf.length-1],buf.toString("utf16le",i,buf.length-1)}function utf16End(buf){var r=buf&&buf.length?this.write(buf):"";if(this.lastNeed){var end=this.lastTotal-this.lastNeed;return r+this.lastChar.toString("utf16le",0,end)}return r}function base64Text(buf,i){var n=(buf.length-i)%3;return 0==n?buf.toString("base64",i):(this.lastNeed=3-n,this.lastTotal=3,1==n?this.lastChar[0]=buf[buf.length-1]:(this.lastChar[0]=buf[buf.length-2],this.lastChar[1]=buf[buf.length-1]),buf.toString("base64",i,buf.length-n))}function base64End(buf){var r=buf&&buf.length?this.write(buf):"";return this.lastNeed?r+this.lastChar.toString("base64",0,3-this.lastNeed):r}function simpleWrite(buf){return buf.toString(this.encoding)}function simpleEnd(buf){return buf&&buf.length?this.write(buf):""}var Buffer=require("safe-buffer").Buffer,isEncoding=Buffer.isEncoding||function(encoding){switch(encoding=""+encoding,encoding&&encoding.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1;}};exports.StringDecoder=StringDecoder,StringDecoder.prototype.write=function(buf){if(0===buf.length)return"";var r,i;if(this.lastNeed){if(r=this.fillLast(buf),void 0===r)return"";i=this.lastNeed,this.lastNeed=0}else i=0;return i>shiftIndex,shiftIndex=(shiftIndex+5)%8,digit=digit<>8-shiftIndex,i++):(digit=31¤t>>8-(shiftIndex+5),shiftIndex=(shiftIndex+5)%8,0===shiftIndex&&i++),encoded[j]="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567".charCodeAt(digit),j++}for(i=j;i=shiftIndex?(shiftIndex=(shiftIndex+5)%8,0===shiftIndex?(plainChar|=plainDigit,decoded[plainPos]=plainChar,plainPos++,plainChar=0):plainChar|=255&plainDigit<<8-shiftIndex):(shiftIndex=(shiftIndex+5)%8,plainChar|=255&plainDigit>>>shiftIndex,decoded[plainPos]=plainChar,plainPos++,plainChar=255&plainDigit<<8-shiftIndex);else throw new Error("Invalid input - it is not base32 encoded string")}return decoded.slice(0,plainPos)}}).call(this)}).call(this,require("buffer").Buffer)},{buffer:24}],110:[function(require,module){var Buffer=require("buffer").Buffer;module.exports=function(buf){if(buf instanceof Uint8Array){if(0===buf.byteOffset&&buf.byteLength===buf.buffer.byteLength)return buf.buffer;if("function"==typeof buf.buffer.slice)return buf.buffer.slice(buf.byteOffset,buf.byteOffset+buf.byteLength)}if(Buffer.isBuffer(buf)){for(var arrayCopy=new Uint8Array(buf.length),len=buf.length,i=0;i */const debug=require("debug")("torrent-discovery"),DHT=require("bittorrent-dht/client"),EventEmitter=require("events").EventEmitter,parallel=require("run-parallel"),Tracker=require("bittorrent-tracker/client"),LSD=require("bittorrent-lsd");module.exports=class Discovery extends EventEmitter{constructor(opts){if(super(),!opts.peerId)throw new Error("Option `peerId` is required");if(!opts.infoHash)throw new Error("Option `infoHash` is required");if(!process.browser&&!opts.port)throw new Error("Option `port` is required");this.peerId="string"==typeof opts.peerId?opts.peerId:opts.peerId.toString("hex"),this.infoHash="string"==typeof opts.infoHash?opts.infoHash.toLowerCase():opts.infoHash.toString("hex"),this._port=opts.port,this._userAgent=opts.userAgent,this.destroyed=!1,this._announce=opts.announce||[],this._intervalMs=opts.intervalMs||900000,this._trackerOpts=null,this._dhtAnnouncing=!1,this._dhtTimeout=!1,this._internalDHT=!1,this._onWarning=err=>{this.emit("warning",err)},this._onError=err=>{this.emit("error",err)},this._onDHTPeer=(peer,infoHash)=>{infoHash.toString("hex")!==this.infoHash||this.emit("peer",`${peer.host}:${peer.port}`,"dht")},this._onTrackerPeer=peer=>{this.emit("peer",peer,"tracker")},this._onTrackerAnnounce=()=>{this.emit("trackerAnnounce")},this._onLSDPeer=peer=>{this.emit("peer",peer,"lsd")};const createDHT=(port,opts)=>{const dht=new DHT(opts);return dht.on("warning",this._onWarning),dht.on("error",this._onError),dht.listen(port),this._internalDHT=!0,dht};!1===opts.tracker?this.tracker=null:opts.tracker&&"object"==typeof opts.tracker?(this._trackerOpts=Object.assign({},opts.tracker),this.tracker=this._createTracker()):this.tracker=this._createTracker(),this.dht=!1===opts.dht||"function"!=typeof DHT?null:opts.dht&&"function"==typeof opts.dht.addNode?opts.dht:opts.dht&&"object"==typeof opts.dht?createDHT(opts.dhtPort,opts.dht):createDHT(opts.dhtPort),this.dht&&(this.dht.on("peer",this._onDHTPeer),this._dhtAnnounce()),this.lsd=!1===opts.lsd||"function"!=typeof LSD?null:this._createLSD()}updatePort(port){port===this._port||(this._port=port,this.dht&&this._dhtAnnounce(),this.tracker&&(this.tracker.stop(),this.tracker.destroy(()=>{this.tracker=this._createTracker()})))}complete(opts){this.tracker&&this.tracker.complete(opts)}destroy(cb){if(!this.destroyed){this.destroyed=!0,clearTimeout(this._dhtTimeout);const tasks=[];this.tracker&&(this.tracker.stop(),this.tracker.removeListener("warning",this._onWarning),this.tracker.removeListener("error",this._onError),this.tracker.removeListener("peer",this._onTrackerPeer),this.tracker.removeListener("update",this._onTrackerAnnounce),tasks.push(cb=>{this.tracker.destroy(cb)})),this.dht&&this.dht.removeListener("peer",this._onDHTPeer),this._internalDHT&&(this.dht.removeListener("warning",this._onWarning),this.dht.removeListener("error",this._onError),tasks.push(cb=>{this.dht.destroy(cb)})),this.lsd&&(this.lsd.removeListener("warning",this._onWarning),this.lsd.removeListener("error",this._onError),this.lsd.removeListener("peer",this._onLSDPeer),tasks.push(cb=>{this.lsd.destroy(cb)})),parallel(tasks,cb),this.dht=null,this.tracker=null,this.lsd=null,this._announce=null}}_createTracker(){const opts=Object.assign({},this._trackerOpts,{infoHash:this.infoHash,announce:this._announce,peerId:this.peerId,port:this._port,userAgent:this._userAgent}),tracker=new Tracker(opts);return tracker.on("warning",this._onWarning),tracker.on("error",this._onError),tracker.on("peer",this._onTrackerPeer),tracker.on("update",this._onTrackerAnnounce),tracker.setInterval(this._intervalMs),tracker.start(),tracker}_dhtAnnounce(){this._dhtAnnouncing||(debug("dht announce"),this._dhtAnnouncing=!0,clearTimeout(this._dhtTimeout),this.dht.announce(this.infoHash,this._port,err=>{this._dhtAnnouncing=!1,debug("dht announce complete"),err&&this.emit("warning",err),this.emit("dhtAnnounce"),this.destroyed||(this._dhtTimeout=setTimeout(()=>{this._dhtAnnounce()},this._intervalMs+_Mathfloor(Math.random()*this._intervalMs/5)),this._dhtTimeout.unref&&this._dhtTimeout.unref())}))}_createLSD(){const opts=Object.assign({},{infoHash:this.infoHash,peerId:this.peerId,port:this._port}),lsd=new LSD(opts);return lsd.on("warning",this._onWarning),lsd.on("error",this._onError),lsd.on("peer",this._onLSDPeer),lsd.start(),lsd}}}).call(this)}).call(this,require("_process"))},{_process:62,"bittorrent-dht/client":22,"bittorrent-lsd":22,"bittorrent-tracker/client":16,debug:33,events:25,"run-parallel":90}],112:[function(require,module){(function(Buffer){(function(){const BLOCK_LENGTH=16384;class Piece{constructor(length){this.length=length,this.missing=length,this.sources=null,this._chunks=_Mathceil(length/BLOCK_LENGTH),this._remainder=length%BLOCK_LENGTH||BLOCK_LENGTH,this._buffered=0,this._buffer=null,this._cancellations=null,this._reservations=0,this._flushed=!1}chunkLength(i){return i===this._chunks-1?this._remainder:BLOCK_LENGTH}chunkLengthRemaining(i){return this.length-i*BLOCK_LENGTH}chunkOffset(i){return i*BLOCK_LENGTH}reserve(){return this.init()?this._cancellations.length?this._cancellations.pop():this._reservations=arr.length||0>i)){var last=arr.pop();if(i","\"","`"," ","\r","\n","\t"]),autoEscape=["'"].concat(unwise),nonHostChars=["%","/","?",";","#"].concat(autoEscape),hostEndingChars=["/","?","#"],hostnamePartPattern=/^[+a-z0-9A-Z_-]{0,63}$/,unsafeProtocol={javascript:!0,"javascript:":!0},hostlessProtocol={javascript:!0,"javascript:":!0},slashedProtocol={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},querystring=require("querystring");Url.prototype.parse=function(url,parseQueryString,slashesDenoteHost){if(!util.isString(url))throw new TypeError("Parameter 'url' must be a string, not "+typeof url);var queryIndex=url.indexOf("?"),splitter=-1!==queryIndex&&queryIndexrelPath.length&&relPath.unshift(""),result.pathname=relPath.join("/")}else result.pathname=relative.pathname;if(result.search=relative.search,result.query=relative.query,result.host=relative.host||"",result.auth=relative.auth,result.hostname=relative.hostname||relative.host,result.port=relative.port,result.pathname||result.search){var p=result.pathname||"",s=result.search||"";result.path=p+s}return result.slashes=result.slashes||relative.slashes,result.href=result.format(),result}var isSourceAbs=result.pathname&&"/"===result.pathname.charAt(0),isRelAbs=relative.host||relative.pathname&&"/"===relative.pathname.charAt(0),mustEndAbs=isRelAbs||isSourceAbs||result.host&&relative.pathname,removeAllDots=mustEndAbs,srcPath=result.pathname&&result.pathname.split("/")||[],relPath=relative.pathname&&relative.pathname.split("/")||[],psychotic=result.protocol&&!slashedProtocol[result.protocol];if(psychotic&&(result.hostname="",result.port=null,result.host&&(""===srcPath[0]?srcPath[0]=result.host:srcPath.unshift(result.host)),result.host="",relative.protocol&&(relative.hostname=null,relative.port=null,relative.host&&(""===relPath[0]?relPath[0]=relative.host:relPath.unshift(relative.host)),relative.host=null),mustEndAbs=mustEndAbs&&(""===relPath[0]||""===srcPath[0])),isRelAbs)result.host=relative.host||""===relative.host?relative.host:result.host,result.hostname=relative.hostname||""===relative.hostname?relative.hostname:result.hostname,result.search=relative.search,result.query=relative.query,srcPath=relPath;else if(relPath.length)srcPath||(srcPath=[]),srcPath.pop(),srcPath=srcPath.concat(relPath),result.search=relative.search,result.query=relative.query;else if(!util.isNullOrUndefined(relative.search)){if(psychotic){result.hostname=result.host=srcPath.shift();var authInHost=!!(result.host&&0 */const{EventEmitter}=require("events"),bencode=require("bencode"),BitField=require("bitfield").default,debug=require("debug")("ut_metadata"),sha1=require("simple-sha1"),BITFIELD_GROW=1E3,PIECE_LENGTH=16384;module.exports=metadata=>{class utMetadata extends EventEmitter{constructor(wire){super(),this._wire=wire,this._fetching=!1,this._metadataComplete=!1,this._metadataSize=null,this._remainingRejects=null,this._bitfield=new BitField(0,{grow:BITFIELD_GROW}),Buffer.isBuffer(metadata)&&this.setMetadata(metadata)}onHandshake(infoHash){this._infoHash=infoHash}onExtendedHandshake(handshake){return handshake.m&&handshake.m.ut_metadata?handshake.metadata_size?"number"!=typeof handshake.metadata_size||1E7=handshake.metadata_size?this.emit("warning",new Error("Peer gave invalid metadata size")):void(this._metadataSize=handshake.metadata_size,this._numPieces=_Mathceil(this._metadataSize/PIECE_LENGTH),this._remainingRejects=2*this._numPieces,this._requestPieces()):this.emit("warning",new Error("Peer does not have metadata")):this.emit("warning",new Error("Peer does not support ut_metadata"))}onMessage(buf){let dict,trailer;try{const str=buf.toString(),trailerIndex=str.indexOf("ee")+2;dict=bencode.decode(str.substring(0,trailerIndex)),trailer=buf.slice(trailerIndex)}catch(err){return}switch(dict.msg_type){case 0:this._onRequest(dict.piece);break;case 1:this._onData(dict.piece,trailer,dict.total_size);break;case 2:this._onReject(dict.piece);}}fetch(){this._metadataComplete||(this._fetching=!0,this._metadataSize&&this._requestPieces())}cancel(){this._fetching=!1}setMetadata(metadata){if(this._metadataComplete)return!0;debug("set metadata");try{const info=bencode.decode(metadata).info;info&&(metadata=bencode.encode(info))}catch(err){}return!(this._infoHash&&this._infoHash!==sha1.sync(metadata))&&(this.cancel(),this.metadata=metadata,this._metadataComplete=!0,this._metadataSize=this.metadata.length,this._wire.extendedHandshake.metadata_size=this._metadataSize,this.emit("metadata",bencode.encode({info:bencode.decode(this.metadata)})),!0)}_send(dict,trailer){let buf=bencode.encode(dict);Buffer.isBuffer(trailer)&&(buf=Buffer.concat([buf,trailer])),this._wire.extended("ut_metadata",buf)}_request(piece){this._send({msg_type:0,piece})}_data(piece,buf,totalSize){const msg={msg_type:1,piece};"number"==typeof totalSize&&(msg.total_size=totalSize),this._send(msg,buf)}_reject(piece){this._send({msg_type:2,piece})}_onRequest(piece){if(!this._metadataComplete)return void this._reject(piece);const start=piece*PIECE_LENGTH;let end=start+PIECE_LENGTH;end>this._metadataSize&&(end=this._metadataSize);const buf=this.metadata.slice(start,end);this._data(piece,buf,this._metadataSize)}_onData(piece,buf){buf.length>PIECE_LENGTH||!this._fetching||(buf.copy(this.metadata,piece*PIECE_LENGTH),this._bitfield.set(piece),this._checkDone())}_onReject(piece){0=this._entries[this._index][this._countName]&&(this._index++,this._offset=0),this.value=this._entries[this._index]}}module.exports=class MP4Remuxer extends EventEmitter{constructor(file){super(),this._tracks=[],this._file=file,this._decoder=null,this._findMoov(0)}_findMoov(offset){this._decoder&&this._decoder.destroy();let toSkip=0;this._decoder=mp4.decode();const fileStream=this._file.createReadStream({start:offset});fileStream.pipe(this._decoder);const boxHandler=headers=>{"moov"===headers.type?(this._decoder.removeListener("box",boxHandler),this._decoder.decode(moov=>{fileStream.destroy();try{this._processMoov(moov)}catch(err){err.message=`Cannot parse mp4 file: ${err.message}`,this.emit("error",err)}})):headers.length<4096?(toSkip+=headers.length,this._decoder.ignore()):(this._decoder.removeListener("box",boxHandler),toSkip+=headers.length,fileStream.destroy(),this._decoder.destroy(),this._findMoov(offset+toSkip))};this._decoder.on("box",boxHandler)}_processMoov(moov){const traks=moov.traks;this._tracks=[],this._hasVideo=!1,this._hasAudio=!1;for(let i=0;i=stbl.stsz.entries.length)break;if(sampleInChunk++,offsetInChunk+=size,sampleInChunk>=currChunkEntry.samplesPerChunk){sampleInChunk=0,offsetInChunk=0,chunk++;const nextChunkEntry=stbl.stsc.entries[sampleToChunkIndex+1];nextChunkEntry&&chunk+1>=nextChunkEntry.firstChunk&&sampleToChunkIndex++}dts+=duration,decodingTimeEntry.inc(),presentationOffsetEntry&&presentationOffsetEntry.inc(),sync&&syncSampleIndex++}trak.mdia.mdhd.duration=0,trak.tkhd.duration=0;const defaultSampleDescriptionIndex=currChunkEntry.sampleDescriptionId,trackMoov={type:"moov",mvhd:moov.mvhd,traks:[{tkhd:trak.tkhd,mdia:{mdhd:trak.mdia.mdhd,hdlr:trak.mdia.hdlr,elng:trak.mdia.elng,minf:{vmhd:trak.mdia.minf.vmhd,smhd:trak.mdia.minf.smhd,dinf:trak.mdia.minf.dinf,stbl:{stsd:stbl.stsd,stts:empty(),ctts:empty(),stsc:empty(),stsz:empty(),stco:empty(),stss:empty()}}}}],mvex:{mehd:{fragmentDuration:moov.mvhd.duration},trexs:[{trackId:trak.tkhd.trackId,defaultSampleDescriptionIndex,defaultSampleDuration:0,defaultSampleSize:0,defaultSampleFlags:0}]}};this._tracks.push({fragmentSequence:1,trackId:trak.tkhd.trackId,timeScale:trak.mdia.mdhd.timeScale,samples,currSample:null,currTime:null,moov:trackMoov,mime})}if(0===this._tracks.length)return void this.emit("error",new Error("no playable tracks"));moov.mvhd.duration=0,this._ftyp={type:"ftyp",brand:"iso5",brandVersion:0,compatibleBrands:["iso5"]};const ftypBuf=Box.encode(this._ftyp),data=this._tracks.map(track=>{const moovBuf=Box.encode(track.moov);return{mime:track.mime,init:Buffer.concat([ftypBuf,moovBuf])}});this.emit("ready",data)}seek(time){if(!this._tracks)throw new Error("Not ready yet; wait for 'ready' event");this._fileStream&&(this._fileStream.destroy(),this._fileStream=null);let startOffset=-1;if(this._tracks.map((track,i)=>{track.outStream&&track.outStream.destroy(),track.inStream&&(track.inStream.destroy(),track.inStream=null);const outStream=track.outStream=mp4.encode(),fragment=this._generateFragment(i,time);if(!fragment)return outStream.finalize();(-1===startOffset||fragment.ranges[0].start{outStream.destroyed||outStream.box(frag.moof,err=>{if(err)return this.emit("error",err);if(!outStream.destroyed){const slicedStream=track.inStream.slice(frag.ranges);slicedStream.pipe(outStream.mediaData(frag.length,err=>{if(err)return this.emit("error",err);if(!outStream.destroyed){const nextFrag=this._generateFragment(i);return nextFrag?void writeFragment(nextFrag):outStream.finalize()}}))}})};writeFragment(fragment)}),0<=startOffset){const fileStream=this._fileStream=this._file.createReadStream({start:startOffset});this._tracks.forEach(track=>{track.inStream=new RangeSliceStream(startOffset,{highWaterMark:1e7}),fileStream.pipe(track.inStream)})}return this._tracks.map(track=>track.outStream)}_findSampleBefore(trackInd,time){const track=this._tracks[trackInd],scaledTime=_Mathfloor(track.timeScale*time);let sample=bs(track.samples,scaledTime,(sample,t)=>{const pts=sample.dts+sample.presentationOffset;return pts-t});for(-1===sample?sample=0:0>sample&&(sample=-sample-2);!track.samples[sample].sync;)sample--;return sample}_generateFragment(track,time){const currTrack=this._tracks[track];let firstSample;if(firstSample=void 0===time?currTrack.currSample:this._findSampleBefore(track,time),firstSample>=currTrack.samples.length)return null;const startDts=currTrack.samples[firstSample].dts;let totalLen=0;const ranges=[];for(var currSample=firstSample;currSample=currTrack.timeScale*1)break;totalLen+=sample.size;const currRange=ranges.length-1;0>currRange||ranges[currRange].end!==sample.offset?ranges.push({start:sample.offset,end:sample.offset+sample.size}):ranges[currRange].end+=sample.size}return currTrack.currSample=currSample,{moof:this._generateMoof(track,firstSample,currSample),ranges,length:totalLen}}_generateMoof(track,firstSample,lastSample){const currTrack=this._tracks[track],entries=[];let trunVersion=0;for(let j=firstSample;jcurrSample.presentationOffset&&(trunVersion=1),entries.push({sampleDuration:currSample.duration,sampleSize:currSample.size,sampleFlags:currSample.sync?33554432:16842752,sampleCompositionTimeOffset:currSample.presentationOffset})}const moof={type:"moof",mfhd:{sequenceNumber:currTrack.fragmentSequence++},trafs:[{tfhd:{flags:131072,trackId:currTrack.trackId},tfdt:{baseMediaDecodeTime:currTrack.samples[firstSample].dts},trun:{flags:3841,dataOffset:8,entries,version:trunVersion}}]};return moof.trafs[0].trun.dataOffset+=Box.encodingLength(moof),moof}}}).call(this)}).call(this,require("buffer").Buffer)},{"binary-search":13,buffer:24,events:25,"mp4-box-encoding":52,"mp4-stream":55,"range-slice-stream":71}],121:[function(require,module){function VideoStream(file,mediaElem,opts={}){return this instanceof VideoStream?void(this.detailedError=null,this._elem=mediaElem,this._elemWrapper=new MediaElementWrapper(mediaElem),this._waitingFired=!1,this._trackMeta=null,this._file=file,this._tracks=null,"none"!==this._elem.preload&&this._createMuxer(),this._onError=()=>{this.detailedError=this._elemWrapper.detailedError,this.destroy()},this._onWaiting=()=>{this._waitingFired=!0,this._muxer?this._tracks&&this._pump():this._createMuxer()},mediaElem.autoplay&&(mediaElem.preload="auto"),mediaElem.addEventListener("waiting",this._onWaiting),mediaElem.addEventListener("error",this._onError)):(console.warn("Don't invoke VideoStream without the 'new' keyword."),new VideoStream(file,mediaElem,opts))}const MediaElementWrapper=require("mediasource"),pump=require("pump"),MP4Remuxer=require("./mp4-remuxer");VideoStream.prototype={_createMuxer(){this._muxer=new MP4Remuxer(this._file),this._muxer.on("ready",data=>{this._tracks=data.map(trackData=>{const mediaSource=this._elemWrapper.createWriteStream(trackData.mime);mediaSource.on("error",err=>{this._elemWrapper.error(err)});const track={muxed:null,mediaSource,initFlushed:!1,onInitFlushed:null};return mediaSource.write(trackData.init,err=>{track.initFlushed=!0,track.onInitFlushed&&track.onInitFlushed(err)}),track}),(this._waitingFired||"auto"===this._elem.preload)&&this._pump()}),this._muxer.on("error",err=>{this._elemWrapper.error(err)})},_pump(){const muxed=this._muxer.seek(this._elem.currentTime,!this._tracks);this._tracks.forEach((track,i)=>{const pumpTrack=()=>{track.muxed&&(track.muxed.destroy(),track.mediaSource=this._elemWrapper.createWriteStream(track.mediaSource),track.mediaSource.on("error",err=>{this._elemWrapper.error(err)})),track.muxed=muxed[i],pump(track.muxed,track.mediaSource)};track.initFlushed?pumpTrack():track.onInitFlushed=err=>err?void this._elemWrapper.error(err):void pumpTrack()})},destroy(){this.destroyed||(this.destroyed=!0,this._elem.removeEventListener("waiting",this._onWaiting),this._elem.removeEventListener("error",this._onError),this._tracks&&this._tracks.forEach(track=>{track.muxed&&track.muxed.destroy()}),this._elem.src="")}},module.exports=VideoStream},{"./mp4-remuxer":120,mediasource:48,pump:63}],122:[function(require,module){function wrappy(fn,cb){function wrapper(){for(var args=Array(arguments.length),i=0;i */const{EventEmitter}=require("events"),concat=require("simple-concat"),createTorrent=require("create-torrent"),debug=require("debug")("webtorrent"),DHT=require("bittorrent-dht/client"),loadIPSet=require("load-ip-set"),parallel=require("run-parallel"),parseTorrent=require("parse-torrent"),path=require("path"),Peer=require("simple-peer"),randombytes=require("randombytes"),speedometer=require("speedometer"),ConnPool=require("./lib/conn-pool"),Torrent=require("./lib/torrent"),VERSION=require("./package.json").version,VERSION_STR=VERSION.replace(/\d*./g,v=>`0${v%100}`.slice(-2)).slice(0,4);class WebTorrent extends EventEmitter{constructor(opts={}){super(),this.peerId="string"==typeof opts.peerId?opts.peerId:Buffer.isBuffer(opts.peerId)?opts.peerId.toString("hex"):Buffer.from(`-WW${VERSION_STR}-`+randombytes(9).toString("base64")).toString("hex"),this.peerIdBuffer=Buffer.from(this.peerId,"hex"),this.nodeId="string"==typeof opts.nodeId?opts.nodeId:Buffer.isBuffer(opts.nodeId)?opts.nodeId.toString("hex"):randombytes(20).toString("hex"),this.nodeIdBuffer=Buffer.from(this.nodeId,"hex"),this._debugId=this.peerId.toString("hex").substring(0,7),this.destroyed=!1,this.listening=!1,this.torrentPort=opts.torrentPort||0,this.dhtPort=opts.dhtPort||0,this.tracker=opts.tracker===void 0?{}:opts.tracker,this.lsd=!1!==opts.lsd,this.torrents=[],this.maxConns=+opts.maxConns||55,this.utp=!0===opts.utp,this._debug("new webtorrent (peerId %s, nodeId %s, port %s)",this.peerId,this.nodeId,this.torrentPort),this.tracker&&("object"!=typeof this.tracker&&(this.tracker={}),opts.rtcConfig&&(console.warn("WebTorrent: opts.rtcConfig is deprecated. Use opts.tracker.rtcConfig instead"),this.tracker.rtcConfig=opts.rtcConfig),opts.wrtc&&(console.warn("WebTorrent: opts.wrtc is deprecated. Use opts.tracker.wrtc instead"),this.tracker.wrtc=opts.wrtc),global.WRTC&&!this.tracker.wrtc&&(this.tracker.wrtc=global.WRTC)),"function"==typeof ConnPool?this._connPool=new ConnPool(this):process.nextTick(()=>{this._onListening()}),this._downloadSpeed=speedometer(),this._uploadSpeed=speedometer(),!1!==opts.dht&&"function"==typeof DHT?(this.dht=new DHT(Object.assign({},{nodeId:this.nodeId},opts.dht)),this.dht.once("error",err=>{this._destroy(err)}),this.dht.once("listening",()=>{const address=this.dht.address();address&&(this.dhtPort=address.port)}),this.dht.setMaxListeners(0),this.dht.listen(this.dhtPort)):this.dht=!1,this.enableWebSeeds=!1!==opts.webSeeds;const ready=()=>{this.destroyed||(this.ready=!0,this.emit("ready"))};"function"==typeof loadIPSet&&null!=opts.blocklist?loadIPSet(opts.blocklist,{headers:{"user-agent":`WebTorrent/${VERSION} (https://webtorrent.io)`}},(err,ipSet)=>err?this.error(`Failed to load blocklist: ${err.message}`):void(this.blocked=ipSet,ready())):process.nextTick(ready)}get downloadSpeed(){return this._downloadSpeed()}get uploadSpeed(){return this._uploadSpeed()}get progress(){const torrents=this.torrents.filter(torrent=>1!==torrent.progress),downloaded=torrents.reduce((total,torrent)=>total+torrent.downloaded,0),length=torrents.reduce((total,torrent)=>total+(torrent.length||0),0)||1;return downloaded/length}get ratio(){const uploaded=this.torrents.reduce((total,torrent)=>total+torrent.uploaded,0),received=this.torrents.reduce((total,torrent)=>total+torrent.received,0)||1;return uploaded/received}get(torrentId){if(!(torrentId instanceof Torrent)){let parsed;try{parsed=parseTorrent(torrentId)}catch(err){}if(!parsed)return null;if(!parsed.infoHash)throw new Error("Invalid torrent identifier");for(const torrent of this.torrents)if(torrent.infoHash===parsed.infoHash)return torrent}else if(this.torrents.includes(torrentId))return torrentId;return null}download(torrentId,opts,ontorrent){return console.warn("WebTorrent: client.download() is deprecated. Use client.add() instead"),this.add(torrentId,opts,ontorrent)}add(torrentId,opts={},ontorrent=()=>{}){function onClose(){torrent.removeListener("_infoHash",onInfoHash),torrent.removeListener("ready",onReady),torrent.removeListener("close",onClose)}if(this.destroyed)throw new Error("client is destroyed");"function"==typeof opts&&([opts,ontorrent]=[{},opts]);const onInfoHash=()=>{if(!this.destroyed)for(const t of this.torrents)if(t.infoHash===torrent.infoHash&&t!==torrent)return void torrent._destroy(new Error(`Cannot add duplicate torrent ${torrent.infoHash}`))},onReady=()=>{this.destroyed||(ontorrent(torrent),this.emit("torrent",torrent))};this._debug("add"),opts=opts?Object.assign({},opts):{};const torrent=new Torrent(torrentId,this,opts);return this.torrents.push(torrent),torrent.once("_infoHash",onInfoHash),torrent.once("ready",onReady),torrent.once("close",onClose),torrent}seed(input,opts,onseed){if(this.destroyed)throw new Error("client is destroyed");"function"==typeof opts&&([opts,onseed]=[{},opts]),this._debug("seed"),opts=opts?Object.assign({},opts):{},opts.skipVerify=!0;const isFilePath="string"==typeof input;isFilePath&&(opts.path=path.dirname(input)),opts.createdBy||(opts.createdBy=`WebTorrent/${VERSION_STR}`);const _onseed=torrent=>{this._debug("on seed"),"function"==typeof onseed&&onseed(torrent),torrent.emit("seed"),this.emit("seed",torrent)},torrent=this.add(null,opts,torrent=>{const tasks=[cb=>isFilePath?cb():void torrent.load(streams,cb)];this.dht&&tasks.push(cb=>{torrent.once("dhtAnnounce",cb)}),parallel(tasks,err=>this.destroyed?void 0:err?torrent._destroy(err):void _onseed(torrent))});let streams;return isFileList(input)?input=Array.from(input):!Array.isArray(input)&&(input=[input]),parallel(input.map(item=>cb=>{isReadable(item)?concat(item,cb):cb(null,item)}),(err,input)=>this.destroyed?void 0:err?torrent._destroy(err):void createTorrent.parseInput(input,opts,(err,files)=>this.destroyed?void 0:err?torrent._destroy(err):void(streams=files.map(file=>file.getStream),createTorrent(input,opts,(err,torrentBuf)=>{if(!this.destroyed){if(err)return torrent._destroy(err);const existingTorrent=this.get(torrentBuf);existingTorrent?torrent._destroy(new Error(`Cannot add duplicate torrent ${existingTorrent.infoHash}`)):torrent._onTorrentId(torrentBuf)}})))),torrent}remove(torrentId,opts,cb){if("function"==typeof opts)return this.remove(torrentId,null,opts);this._debug("remove");const torrent=this.get(torrentId);if(!torrent)throw new Error(`No torrent with id ${torrentId}`);this._remove(torrentId,opts,cb)}_remove(torrentId,opts,cb){if("function"==typeof opts)return this._remove(torrentId,null,opts);const torrent=this.get(torrentId);torrent&&(this.torrents.splice(this.torrents.indexOf(torrent),1),torrent.destroy(opts,cb))}address(){return this.listening?this._connPool?this._connPool.tcpServer.address():{address:"0.0.0.0",family:"IPv4",port:0}:null}destroy(cb){if(this.destroyed)throw new Error("client already destroyed");this._destroy(null,cb)}_destroy(err,cb){this._debug("client destroy"),this.destroyed=!0;const tasks=this.torrents.map(torrent=>cb=>{torrent.destroy(cb)});this._connPool&&tasks.push(cb=>{this._connPool.destroy(cb)}),this.dht&&tasks.push(cb=>{this.dht.destroy(cb)}),parallel(tasks,cb),err&&this.emit("error",err),this.torrents=[],this._connPool=null,this.dht=null}_onListening(){if(this._debug("listening"),this.listening=!0,this._connPool){const address=this._connPool.tcpServer.address();address&&(this.torrentPort=address.port)}this.emit("listening")}_debug(){const args=[].slice.call(arguments);args[0]=`[${this._debugId}] ${args[0]}`,debug(...args)}}WebTorrent.WEBRTC_SUPPORT=Peer.WEBRTC_SUPPORT,WebTorrent.VERSION=VERSION,module.exports=WebTorrent}).call(this)}).call(this,require("_process"),"undefined"==typeof global?"undefined"==typeof self?"undefined"==typeof window?{}:window:self:global,require("buffer").Buffer)},{"./lib/conn-pool":22,"./lib/torrent":5,"./package.json":124,_process:62,"bittorrent-dht/client":22,buffer:24,"create-torrent":32,debug:33,events:25,"load-ip-set":22,"parse-torrent":60,path:26,randombytes:70,"run-parallel":90,"simple-concat":93,"simple-peer":95,speedometer:99}]},{},[125])(125)}); \ No newline at end of file + */'use strict';function createBuffer(length){if(2147483647size)throw new RangeError("The value \""+size+"\" is invalid for option \"size\"")}function alloc(size,fill,encoding){return assertSize(size),0>=size?createBuffer(size):void 0===fill?createBuffer(size):"string"==typeof encoding?createBuffer(size).fill(fill,encoding):createBuffer(size).fill(fill)}function allocUnsafe(size){return assertSize(size),createBuffer(0>size?0:0|checked(size))}function fromString(string,encoding){if(("string"!=typeof encoding||""===encoding)&&(encoding="utf8"),!Buffer.isEncoding(encoding))throw new TypeError("Unknown encoding: "+encoding);var length=0|byteLength(string,encoding),buf=createBuffer(length),actual=buf.write(string,encoding);return actual!==length&&(buf=buf.slice(0,actual)),buf}function fromArrayLike(array){for(var length=0>array.length?0:0|checked(array.length),buf=createBuffer(length),i=0;ibyteOffset||array.byteLength=2147483647)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+2147483647 .toString(16)+" bytes");return 0|length}function byteLength(string,encoding){if(Buffer.isBuffer(string))return string.length;if(ArrayBuffer.isView(string)||isInstance(string,ArrayBuffer))return string.byteLength;if("string"!=typeof string)throw new TypeError("The \"string\" argument must be one of type string, Buffer, or ArrayBuffer. Received type "+typeof string);var len=string.length,mustMatch=2>>1;case"base64":return base64ToBytes(string).length;default:if(loweredCase)return mustMatch?-1:utf8ToBytes(string).length;encoding=(""+encoding).toLowerCase(),loweredCase=!0;}}function slowToString(encoding,start,end){var loweredCase=!1;if((void 0===start||0>start)&&(start=0),start>this.length)return"";if((void 0===end||end>this.length)&&(end=this.length),0>=end)return"";if(end>>>=0,start>>>=0,end<=start)return"";for(encoding||(encoding="utf8");;)switch(encoding){case"hex":return hexSlice(this,start,end);case"utf8":case"utf-8":return utf8Slice(this,start,end);case"ascii":return asciiSlice(this,start,end);case"latin1":case"binary":return latin1Slice(this,start,end);case"base64":return base64Slice(this,start,end);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return utf16leSlice(this,start,end);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(encoding+"").toLowerCase(),loweredCase=!0;}}function swap(b,n,m){var i=b[n];b[n]=b[m],b[m]=i}function bidirectionalIndexOf(buffer,val,byteOffset,encoding,dir){if(0===buffer.length)return-1;if("string"==typeof byteOffset?(encoding=byteOffset,byteOffset=0):2147483647byteOffset&&(byteOffset=-2147483648),byteOffset=+byteOffset,numberIsNaN(byteOffset)&&(byteOffset=dir?0:buffer.length-1),0>byteOffset&&(byteOffset=buffer.length+byteOffset),byteOffset>=buffer.length){if(dir)return-1;byteOffset=buffer.length-1}else if(0>byteOffset)if(dir)byteOffset=0;else return-1;if("string"==typeof val&&(val=Buffer.from(val,encoding)),Buffer.isBuffer(val))return 0===val.length?-1:arrayIndexOf(buffer,val,byteOffset,encoding,dir);if("number"==typeof val)return val&=255,"function"==typeof Uint8Array.prototype.indexOf?dir?Uint8Array.prototype.indexOf.call(buffer,val,byteOffset):Uint8Array.prototype.lastIndexOf.call(buffer,val,byteOffset):arrayIndexOf(buffer,[val],byteOffset,encoding,dir);throw new TypeError("val must be string, number or Buffer")}function arrayIndexOf(arr,val,byteOffset,encoding,dir){function read(buf,i){return 1===indexSize?buf[i]:buf.readUInt16BE(i*indexSize)}var indexSize=1,arrLength=arr.length,valLength=val.length;if(void 0!==encoding&&(encoding=(encoding+"").toLowerCase(),"ucs2"===encoding||"ucs-2"===encoding||"utf16le"===encoding||"utf-16le"===encoding)){if(2>arr.length||2>val.length)return-1;indexSize=2,arrLength/=2,valLength/=2,byteOffset/=2}var i;if(dir){var foundIndex=-1;for(i=byteOffset;iarrLength&&(byteOffset=arrLength-valLength),i=byteOffset;0<=i;i--){for(var found=!0,j=0;jremaining&&(length=remaining)):length=remaining;var strLen=string.length;length>strLen/2&&(length=strLen/2);for(var i=0,parsed;ifirstByte&&(codePoint=firstByte):2===bytesPerSequence?(secondByte=buf[i+1],128==(192&secondByte)&&(tempCodePoint=(31&firstByte)<<6|63&secondByte,127tempCodePoint||57343tempCodePoint&&(codePoint=tempCodePoint))):void 0}null===codePoint?(codePoint=65533,bytesPerSequence=1):65535>>10),codePoint=56320|1023&codePoint),res.push(codePoint),i+=bytesPerSequence}return decodeCodePointsArray(res)}function decodeCodePointsArray(codePoints){var len=codePoints.length;if(len<=4096)return _StringfromCharCode.apply(String,codePoints);for(var res="",i=0;istart)&&(start=0),(!end||0>end||end>len)&&(end=len);for(var out="",i=start;ioffset)throw new RangeError("offset is not uint");if(offset+ext>length)throw new RangeError("Trying to access beyond buffer length")}function checkInt(buf,value,offset,ext,max,min){if(!Buffer.isBuffer(buf))throw new TypeError("\"buffer\" argument must be a Buffer instance");if(value>max||valuebuf.length)throw new RangeError("Index out of range")}function checkIEEE754(buf,value,offset,ext){if(offset+ext>buf.length)throw new RangeError("Index out of range");if(0>offset)throw new RangeError("Index out of range")}function writeFloat(buf,value,offset,littleEndian,noAssert){return value=+value,offset>>>=0,noAssert||checkIEEE754(buf,value,offset,4,34028234663852886e22,-34028234663852886e22),ieee754.write(buf,value,offset,littleEndian,23,4),offset+4}function writeDouble(buf,value,offset,littleEndian,noAssert){return value=+value,offset>>>=0,noAssert||checkIEEE754(buf,value,offset,8,17976931348623157e292,-17976931348623157e292),ieee754.write(buf,value,offset,littleEndian,52,8),offset+8}function base64clean(str){if(str=str.split("=")[0],str=str.trim().replace(INVALID_BASE64_RE,""),2>str.length)return"";for(;0!=str.length%4;)str+="=";return str}function toHex(n){return 16>n?"0"+n.toString(16):n.toString(16)}function utf8ToBytes(string,units){units=units||1/0;for(var length=string.length,leadSurrogate=null,bytes=[],i=0,codePoint;icodePoint){if(!leadSurrogate){if(56319codePoint){-1<(units-=3)&&bytes.push(239,191,189),leadSurrogate=codePoint;continue}codePoint=(leadSurrogate-55296<<10|codePoint-56320)+65536}else leadSurrogate&&-1<(units-=3)&&bytes.push(239,191,189);if(leadSurrogate=null,128>codePoint){if(0>(units-=1))break;bytes.push(codePoint)}else if(2048>codePoint){if(0>(units-=2))break;bytes.push(192|codePoint>>6,128|63&codePoint)}else if(65536>codePoint){if(0>(units-=3))break;bytes.push(224|codePoint>>12,128|63&codePoint>>6,128|63&codePoint)}else if(1114112>codePoint){if(0>(units-=4))break;bytes.push(240|codePoint>>18,128|63&codePoint>>12,128|63&codePoint>>6,128|63&codePoint)}else throw new Error("Invalid code point")}return bytes}function asciiToBytes(str){for(var byteArray=[],i=0;i(units-=2));++i)c=str.charCodeAt(i),hi=c>>8,lo=c%256,byteArray.push(lo),byteArray.push(hi);return byteArray}function base64ToBytes(str){return base64.toByteArray(base64clean(str))}function blitBuffer(src,dst,offset,length){for(var i=0;i=dst.length||i>=src.length);++i)dst[i+offset]=src[i];return i}function isInstance(obj,type){return obj instanceof type||null!=obj&&null!=obj.constructor&&null!=obj.constructor.name&&obj.constructor.name===type.name}function numberIsNaN(obj){return obj!==obj}var base64=require("base64-js"),ieee754=require("ieee754");exports.Buffer=Buffer,exports.SlowBuffer=function(length){return+length!=length&&(length=0),Buffer.alloc(+length)},exports.INSPECT_MAX_BYTES=50;exports.kMaxLength=2147483647,Buffer.TYPED_ARRAY_SUPPORT=function(){try{var arr=new Uint8Array(1);return arr.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===arr.foo()}catch(e){return!1}}(),Buffer.TYPED_ARRAY_SUPPORT||"undefined"==typeof console||"function"!=typeof console.error||console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."),Object.defineProperty(Buffer.prototype,"parent",{enumerable:!0,get:function(){return Buffer.isBuffer(this)?this.buffer:void 0}}),Object.defineProperty(Buffer.prototype,"offset",{enumerable:!0,get:function(){return Buffer.isBuffer(this)?this.byteOffset:void 0}}),"undefined"!=typeof Symbol&&null!=Symbol.species&&Buffer[Symbol.species]===Buffer&&Object.defineProperty(Buffer,Symbol.species,{value:null,configurable:!0,enumerable:!1,writable:!1}),Buffer.poolSize=8192,Buffer.from=function(value,encodingOrOffset,length){return from(value,encodingOrOffset,length)},Buffer.prototype.__proto__=Uint8Array.prototype,Buffer.__proto__=Uint8Array,Buffer.alloc=function(size,fill,encoding){return alloc(size,fill,encoding)},Buffer.allocUnsafe=function(size){return allocUnsafe(size)},Buffer.allocUnsafeSlow=function(size){return allocUnsafe(size)},Buffer.isBuffer=function(b){return null!=b&&!0===b._isBuffer&&b!==Buffer.prototype},Buffer.compare=function(a,b){if(isInstance(a,Uint8Array)&&(a=Buffer.from(a,a.offset,a.byteLength)),isInstance(b,Uint8Array)&&(b=Buffer.from(b,b.offset,b.byteLength)),!Buffer.isBuffer(a)||!Buffer.isBuffer(b))throw new TypeError("The \"buf1\", \"buf2\" arguments must be one of type Buffer or Uint8Array");if(a===b)return 0;for(var x=a.length,y=b.length,i=0,len=_Mathmin(x,y);imax&&(str+=" ... "),""},Buffer.prototype.compare=function(target,start,end,thisStart,thisEnd){if(isInstance(target,Uint8Array)&&(target=Buffer.from(target,target.offset,target.byteLength)),!Buffer.isBuffer(target))throw new TypeError("The \"target\" argument must be one of type Buffer or Uint8Array. Received type "+typeof target);if(void 0===start&&(start=0),void 0===end&&(end=target?target.length:0),void 0===thisStart&&(thisStart=0),void 0===thisEnd&&(thisEnd=this.length),0>start||end>target.length||0>thisStart||thisEnd>this.length)throw new RangeError("out of range index");if(thisStart>=thisEnd&&start>=end)return 0;if(thisStart>=thisEnd)return-1;if(start>=end)return 1;if(start>>>=0,end>>>=0,thisStart>>>=0,thisEnd>>>=0,this===target)return 0;for(var x=thisEnd-thisStart,y=end-start,len=_Mathmin(x,y),thisCopy=this.slice(thisStart,thisEnd),targetCopy=target.slice(start,end),i=0;i>>=0,isFinite(length)?(length>>>=0,void 0===encoding&&(encoding="utf8")):(encoding=length,length=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");var remaining=this.length-offset;if((void 0===length||length>remaining)&&(length=remaining),0length||0>offset)||offset>this.length)throw new RangeError("Attempt to write outside buffer bounds");encoding||(encoding="utf8");for(var loweredCase=!1;;)switch(encoding){case"hex":return hexWrite(this,string,offset,length);case"utf8":case"utf-8":return utf8Write(this,string,offset,length);case"ascii":return asciiWrite(this,string,offset,length);case"latin1":case"binary":return latin1Write(this,string,offset,length);case"base64":return base64Write(this,string,offset,length);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ucs2Write(this,string,offset,length);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(""+encoding).toLowerCase(),loweredCase=!0;}},Buffer.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};Buffer.prototype.slice=function(start,end){var len=this.length;start=~~start,end=end===void 0?len:~~end,0>start?(start+=len,0>start&&(start=0)):start>len&&(start=len),0>end?(end+=len,0>end&&(end=0)):end>len&&(end=len),end>>=0,byteLength>>>=0,noAssert||checkOffset(offset,byteLength,this.length);for(var val=this[offset],mul=1,i=0;++i>>=0,byteLength>>>=0,noAssert||checkOffset(offset,byteLength,this.length);for(var val=this[offset+--byteLength],mul=1;0>>=0,noAssert||checkOffset(offset,1,this.length),this[offset]},Buffer.prototype.readUInt16LE=function(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,2,this.length),this[offset]|this[offset+1]<<8},Buffer.prototype.readUInt16BE=function(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,2,this.length),this[offset]<<8|this[offset+1]},Buffer.prototype.readUInt32LE=function(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,4,this.length),(this[offset]|this[offset+1]<<8|this[offset+2]<<16)+16777216*this[offset+3]},Buffer.prototype.readUInt32BE=function(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,4,this.length),16777216*this[offset]+(this[offset+1]<<16|this[offset+2]<<8|this[offset+3])},Buffer.prototype.readIntLE=function(offset,byteLength,noAssert){offset>>>=0,byteLength>>>=0,noAssert||checkOffset(offset,byteLength,this.length);for(var val=this[offset],mul=1,i=0;++i=mul&&(val-=_Mathpow(2,8*byteLength)),val},Buffer.prototype.readIntBE=function(offset,byteLength,noAssert){offset>>>=0,byteLength>>>=0,noAssert||checkOffset(offset,byteLength,this.length);for(var i=byteLength,mul=1,val=this[offset+--i];0=mul&&(val-=_Mathpow(2,8*byteLength)),val},Buffer.prototype.readInt8=function(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,1,this.length),128&this[offset]?-1*(255-this[offset]+1):this[offset]},Buffer.prototype.readInt16LE=function(offset,noAssert){offset>>>=0,noAssert||checkOffset(offset,2,this.length);var val=this[offset]|this[offset+1]<<8;return 32768&val?4294901760|val:val},Buffer.prototype.readInt16BE=function(offset,noAssert){offset>>>=0,noAssert||checkOffset(offset,2,this.length);var val=this[offset+1]|this[offset]<<8;return 32768&val?4294901760|val:val},Buffer.prototype.readInt32LE=function(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,4,this.length),this[offset]|this[offset+1]<<8|this[offset+2]<<16|this[offset+3]<<24},Buffer.prototype.readInt32BE=function(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,4,this.length),this[offset]<<24|this[offset+1]<<16|this[offset+2]<<8|this[offset+3]},Buffer.prototype.readFloatLE=function(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,4,this.length),ieee754.read(this,offset,!0,23,4)},Buffer.prototype.readFloatBE=function(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,4,this.length),ieee754.read(this,offset,!1,23,4)},Buffer.prototype.readDoubleLE=function(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,8,this.length),ieee754.read(this,offset,!0,52,8)},Buffer.prototype.readDoubleBE=function(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,8,this.length),ieee754.read(this,offset,!1,52,8)},Buffer.prototype.writeUIntLE=function(value,offset,byteLength,noAssert){if(value=+value,offset>>>=0,byteLength>>>=0,!noAssert){var maxBytes=_Mathpow(2,8*byteLength)-1;checkInt(this,value,offset,byteLength,maxBytes,0)}var mul=1,i=0;for(this[offset]=255&value;++i>>=0,byteLength>>>=0,!noAssert){var maxBytes=_Mathpow(2,8*byteLength)-1;checkInt(this,value,offset,byteLength,maxBytes,0)}var i=byteLength-1,mul=1;for(this[offset+i]=255&value;0<=--i&&(mul*=256);)this[offset+i]=255&value/mul;return offset+byteLength},Buffer.prototype.writeUInt8=function(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,1,255,0),this[offset]=255&value,offset+1},Buffer.prototype.writeUInt16LE=function(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,2,65535,0),this[offset]=255&value,this[offset+1]=value>>>8,offset+2},Buffer.prototype.writeUInt16BE=function(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,2,65535,0),this[offset]=value>>>8,this[offset+1]=255&value,offset+2},Buffer.prototype.writeUInt32LE=function(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,4,4294967295,0),this[offset+3]=value>>>24,this[offset+2]=value>>>16,this[offset+1]=value>>>8,this[offset]=255&value,offset+4},Buffer.prototype.writeUInt32BE=function(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,4,4294967295,0),this[offset]=value>>>24,this[offset+1]=value>>>16,this[offset+2]=value>>>8,this[offset+3]=255&value,offset+4},Buffer.prototype.writeIntLE=function(value,offset,byteLength,noAssert){if(value=+value,offset>>>=0,!noAssert){var limit=_Mathpow(2,8*byteLength-1);checkInt(this,value,offset,byteLength,limit-1,-limit)}var i=0,mul=1,sub=0;for(this[offset]=255&value;++ivalue&&0===sub&&0!==this[offset+i-1]&&(sub=1),this[offset+i]=255&(value/mul>>0)-sub;return offset+byteLength},Buffer.prototype.writeIntBE=function(value,offset,byteLength,noAssert){if(value=+value,offset>>>=0,!noAssert){var limit=_Mathpow(2,8*byteLength-1);checkInt(this,value,offset,byteLength,limit-1,-limit)}var i=byteLength-1,mul=1,sub=0;for(this[offset+i]=255&value;0<=--i&&(mul*=256);)0>value&&0===sub&&0!==this[offset+i+1]&&(sub=1),this[offset+i]=255&(value/mul>>0)-sub;return offset+byteLength},Buffer.prototype.writeInt8=function(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,1,127,-128),0>value&&(value=255+value+1),this[offset]=255&value,offset+1},Buffer.prototype.writeInt16LE=function(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,2,32767,-32768),this[offset]=255&value,this[offset+1]=value>>>8,offset+2},Buffer.prototype.writeInt16BE=function(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,2,32767,-32768),this[offset]=value>>>8,this[offset+1]=255&value,offset+2},Buffer.prototype.writeInt32LE=function(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,4,2147483647,-2147483648),this[offset]=255&value,this[offset+1]=value>>>8,this[offset+2]=value>>>16,this[offset+3]=value>>>24,offset+4},Buffer.prototype.writeInt32BE=function(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,4,2147483647,-2147483648),0>value&&(value=4294967295+value+1),this[offset]=value>>>24,this[offset+1]=value>>>16,this[offset+2]=value>>>8,this[offset+3]=255&value,offset+4},Buffer.prototype.writeFloatLE=function(value,offset,noAssert){return writeFloat(this,value,offset,!0,noAssert)},Buffer.prototype.writeFloatBE=function(value,offset,noAssert){return writeFloat(this,value,offset,!1,noAssert)},Buffer.prototype.writeDoubleLE=function(value,offset,noAssert){return writeDouble(this,value,offset,!0,noAssert)},Buffer.prototype.writeDoubleBE=function(value,offset,noAssert){return writeDouble(this,value,offset,!1,noAssert)},Buffer.prototype.copy=function(target,targetStart,start,end){if(!Buffer.isBuffer(target))throw new TypeError("argument should be a Buffer");if(start||(start=0),end||0===end||(end=this.length),targetStart>=target.length&&(targetStart=target.length),targetStart||(targetStart=0),0targetStart)throw new RangeError("targetStart out of bounds");if(0>start||start>=this.length)throw new RangeError("Index out of range");if(0>end)throw new RangeError("sourceEnd out of bounds");end>this.length&&(end=this.length),target.length-targetStartcode||"latin1"===encoding)&&(val=code)}}else"number"==typeof val&&(val&=255);if(0>start||this.length>>=0,end=end===void 0?this.length:end>>>0,val||(val=0);var i;if("number"==typeof val)for(i=start;im&&!existing.warned){existing.warned=!0;var w=new Error("Possible EventEmitter memory leak detected. "+existing.length+" "+(type+" listeners added. Use emitter.setMaxListeners() to increase limit"));w.name="MaxListenersExceededWarning",w.emitter=target,w.type=type,w.count=existing.length,ProcessEmitWarning(w)}return target}function onceWrapper(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function _onceWrap(target,type,listener){var state={fired:!1,wrapFn:void 0,target:target,type:type,listener:listener},wrapped=onceWrapper.bind(state);return wrapped.listener=listener,state.wrapFn=wrapped,wrapped}function _listeners(target,type,unwrap){var events=target._events;if(events===void 0)return[];var evlistener=events[type];return void 0===evlistener?[]:"function"==typeof evlistener?unwrap?[evlistener.listener||evlistener]:[evlistener]:unwrap?unwrapListeners(evlistener):arrayClone(evlistener,evlistener.length)}function listenerCount(type){var events=this._events;if(events!==void 0){var evlistener=events[type];if("function"==typeof evlistener)return 1;if(void 0!==evlistener)return evlistener.length}return 0}function arrayClone(arr,n){for(var copy=Array(n),i=0;iarg||NumberIsNaN(arg))throw new RangeError("The value of \"defaultMaxListeners\" is out of range. It must be a non-negative number. Received "+arg+".");defaultMaxListeners=arg}}),EventEmitter.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},EventEmitter.prototype.setMaxListeners=function(n){if("number"!=typeof n||0>n||NumberIsNaN(n))throw new RangeError("The value of \"n\" is out of range. It must be a non-negative number. Received "+n+".");return this._maxListeners=n,this},EventEmitter.prototype.getMaxListeners=function(){return _getMaxListeners(this)},EventEmitter.prototype.emit=function(type){for(var args=[],i=1;iposition)return this;0===position?list.shift():spliceOne(list,position),1===list.length&&(events[type]=list[0]),void 0!==events.removeListener&&this.emit("removeListener",type,originalListener||listener)}return this},EventEmitter.prototype.off=EventEmitter.prototype.removeListener,EventEmitter.prototype.removeAllListeners=function(type){var listeners,events,i;if(events=this._events,void 0===events)return this;if(void 0===events.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==events[type]&&(0==--this._eventsCount?this._events=Object.create(null):delete events[type]),this;if(0===arguments.length){var keys=Object.keys(events),key;for(i=0;ires.length||2!==lastSegmentLength||46!==res.charCodeAt(res.length-1)||46!==res.charCodeAt(res.length-2))if(2length){if(47===to.charCodeAt(toStart+i))return to.slice(toStart+i+1);if(0===i)return to.slice(toStart+i)}else fromLen>length&&(47===from.charCodeAt(fromStart+i)?lastCommonSep=i:0===i&&(lastCommonSep=0));break}var fromCode=from.charCodeAt(fromStart+i),toCode=to.charCodeAt(toStart+i);if(fromCode!==toCode)break;else 47===fromCode&&(lastCommonSep=i)}var out="";for(i=fromStart+lastCommonSep+1;i<=fromEnd;++i)(i===fromEnd||47===from.charCodeAt(i))&&(out+=0===out.length?"..":"/..");return 0=start;--i){if(code=path.charCodeAt(i),47===code){if(!matchedSlash){startPart=i+1;break}continue}-1===end&&(matchedSlash=!1,end=i+1),46===code?-1===startDot?startDot=i:1!==preDotState&&(preDotState=1):-1!==startDot&&(preDotState=-1)}return-1===startDot||-1===end||0===preDotState||1===preDotState&&startDot===end-1&&startDot===startPart+1?-1!==end&&(0===startPart&&isAbsolute?ret.base=ret.name=path.slice(1,end):ret.base=ret.name=path.slice(startPart,end)):(0===startPart&&isAbsolute?(ret.name=path.slice(1,startDot),ret.base=path.slice(1,end)):(ret.name=path.slice(startPart,startDot),ret.base=path.slice(startPart,end)),ret.ext=path.slice(startDot,end)),0size)throw new RangeError("\"size\" argument must not be negative");return Buffer.allocUnsafe?Buffer.allocUnsafe(size):new Buffer(size)}}).call(this)}).call(this,require("buffer").Buffer)},{buffer:24}],28:[function(require,module){(function(Buffer){(function(){var bufferFill=require("buffer-fill"),allocUnsafe=require("buffer-alloc-unsafe");module.exports=function(size,fill,encoding){if("number"!=typeof size)throw new TypeError("\"size\" argument must be a number");if(0>size)throw new RangeError("\"size\" argument must not be negative");if(Buffer.alloc)return Buffer.alloc(size,fill,encoding);var buffer=allocUnsafe(size);return 0===size?buffer:void 0===fill?bufferFill(buffer,0):("string"!=typeof encoding&&(encoding=void 0),bufferFill(buffer,fill,encoding))}}).call(this)}).call(this,require("buffer").Buffer)},{buffer:24,"buffer-alloc-unsafe":27,"buffer-fill":29}],29:[function(require,module){(function(Buffer){(function(){function isSingleByte(val){return 1===val.length&&256>val.charCodeAt(0)}function fillWithNumber(buffer,val,start,end){if(0>start||end>buffer.length)throw new RangeError("Out of range index");return start>>>=0,end=void 0===end?buffer.length:end>>>0,end>start&&buffer.fill(val,start,end),buffer}function fillWithBuffer(buffer,val,start,end){if(0>start||end>buffer.length)throw new RangeError("Out of range index");if(end<=start)return buffer;start>>>=0,end=void 0===end?buffer.length:end>>>0;for(var pos=start,len=val.length;pos<=end-len;)val.copy(buffer,pos),pos+=len;return pos!==end&&val.copy(buffer,pos,0,end-pos),buffer}var hasFullSupport=function(){try{if(!Buffer.isEncoding("latin1"))return!1;var buf=Buffer.alloc?Buffer.alloc(4):new Buffer(4);return buf.fill("ab","ucs2"),"61006200"===buf.toString("hex")}catch(_){return!1}}();module.exports=function(buffer,val,start,end,encoding){if(hasFullSupport)return buffer.fill(val,start,end,encoding);if("number"==typeof val)return fillWithNumber(buffer,val,start,end);if("string"==typeof val){if("string"==typeof start?(encoding=start,start=0,end=buffer.length):"string"==typeof end&&(encoding=end,end=buffer.length),void 0!==encoding&&"string"!=typeof encoding)throw new TypeError("encoding must be a string");if("latin1"===encoding&&(encoding="binary"),"string"==typeof encoding&&!Buffer.isEncoding(encoding))throw new TypeError("Unknown encoding: "+encoding);if(""===val)return fillWithNumber(buffer,0,start,end);if(isSingleByte(val))return fillWithNumber(buffer,val.charCodeAt(0),start,end);val=new Buffer(val,encoding)}return Buffer.isBuffer(val)?fillWithBuffer(buffer,val,start,end):fillWithNumber(buffer,0,start,end)}}).call(this)}).call(this,require("buffer").Buffer)},{buffer:24}],30:[function(require,module){module.exports={100:"Continue",101:"Switching Protocols",102:"Processing",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Unordered Collection",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",509:"Bandwidth Limit Exceeded",510:"Not Extended",511:"Network Authentication Required"}},{}],31:[function(require,module){const BlockStream=require("block-stream2"),stream=require("readable-stream");class ChunkStoreWriteStream extends stream.Writable{constructor(store,chunkLength,opts={}){if(super(opts),!store||!store.put||!store.get)throw new Error("First argument must be an abstract-chunk-store compliant store");if(chunkLength=+chunkLength,!chunkLength)throw new Error("Second argument must be a chunk length");this._blockstream=new BlockStream(chunkLength,{zeroPadding:!1}),this._outstandingPuts=0;let index=0;const onData=chunk=>{this.destroyed||(this._outstandingPuts+=1,store.put(index,chunk,()=>{this._outstandingPuts-=1,0===this._outstandingPuts&&"function"==typeof this._finalCb&&(this._finalCb(null),this._finalCb=null)}),index+=1)};this._blockstream.on("data",onData).on("error",err=>{this.destroy(err)})}_write(chunk,encoding,callback){this._blockstream.write(chunk,encoding,callback)}_final(cb){this._blockstream.end(),this._blockstream.once("end",()=>{0===this._outstandingPuts?cb(null):this._finalCb=cb})}destroy(err){this.destroyed||(this.destroyed=!0,err&&this.emit("error",err),this.emit("close"))}}module.exports=ChunkStoreWriteStream},{"block-stream2":21,"readable-stream":86}],32:[function(require,module){(function(process,global,Buffer){(function(){function flat(arr1){return arr1.reduce((acc,val)=>Array.isArray(val)?acc.concat(flat(val)):acc.concat(val),[])}function _parseInput(input,opts,cb){function processInput(){parallel(input.map(item=>cb=>{const file={};if(isBlob(item))file.getStream=getBlobStream(item),file.length=item.size;else if(Buffer.isBuffer(item))file.getStream=getBufferStream(item),file.length=item.length;else if(isReadable(item))file.getStream=getStreamStream(item,file),file.length=0;else{if("string"==typeof item){if("function"!=typeof getFiles)throw new Error("filesystem paths do not work in the browser");const keepRoot=1err?cb(err):void(files=flat(files),cb(null,files,isSingleFileTorrent)))}if(isFileList(input)&&(input=Array.from(input)),Array.isArray(input)||(input=[input]),0===input.length)throw new Error("invalid input type");input.forEach(item=>{if(null==item)throw new Error(`invalid input type: ${item}`)}),input=input.map(item=>isBlob(item)&&"string"==typeof item.path&&"function"==typeof getFiles?item.path:item),1!==input.length||"string"==typeof input[0]||input[0].name||(input[0].name=opts.name);let commonPrefix=null;input.forEach((item,i)=>{if("string"==typeof item)return;let path=item.fullPath||item.name;path||(path=`Unknown File ${i+1}`,item.unknownName=!0),item.path=path.split("/"),item.path[0]||item.path.shift(),2>item.path.length?commonPrefix=null:0===i&&1{if("string"==typeof item)return!0;const filename=item.path[item.path.length-1];return notHidden(filename)&&junk.not(filename)}),commonPrefix&&input.forEach(item=>{const pathless=(Buffer.isBuffer(item)||isReadable(item))&&!item.path;"string"==typeof item||pathless||item.path.shift()}),!opts.name&&commonPrefix&&(opts.name=commonPrefix),opts.name||input.some(item=>"string"==typeof item?(opts.name=corePath.basename(item),!0):item.unknownName?void 0:(opts.name=item.path[item.path.length-1],!0)),opts.name||(opts.name=`Unnamed Torrent ${Date.now()}`);const numPaths=input.reduce((sum,item)=>sum+ +("string"==typeof item),0);let isSingleFileTorrent=1===input.length;if(1===input.length&&"string"==typeof input[0]){if("function"!=typeof getFiles)throw new Error("filesystem paths do not work in the browser");isFile(input[0],(err,pathIsFile)=>err?cb(err):void(isSingleFileTorrent=pathIsFile,processInput()))}else process.nextTick(()=>{processInput()})}function notHidden(file){return"."!==file[0]}function getPieceList(files,pieceLength,cb){function onData(chunk){length+=chunk.length;const i=pieceNum;sha1(chunk,hash=>{pieces[i]=hash,remainingHashes-=1,maybeDone()}),remainingHashes+=1,pieceNum+=1}function onEnd(){ended=!0,maybeDone()}function onError(err){cleanup(),cb(err)}function cleanup(){multistream.removeListener("error",onError),blockstream.removeListener("data",onData),blockstream.removeListener("end",onEnd),blockstream.removeListener("error",onError)}function maybeDone(){ended&&0===remainingHashes&&(cleanup(),cb(null,Buffer.from(pieces.join(""),"hex"),length))}cb=once(cb);const pieces=[];let length=0;const streams=files.map(file=>file.getStream);let remainingHashes=0,pieceNum=0,ended=!1;const multistream=new MultiStream(streams),blockstream=new BlockStream(pieceLength,{zeroPadding:!1});multistream.on("error",onError),multistream.pipe(blockstream).on("data",onData).on("end",onEnd).on("error",onError)}function onFiles(files,opts,cb){let announceList=opts.announceList;announceList||("string"==typeof opts.announce?announceList=[[opts.announce]]:Array.isArray(opts.announce)&&(announceList=opts.announce.map(u=>[u]))),announceList||(announceList=[]),global.WEBTORRENT_ANNOUNCE&&("string"==typeof global.WEBTORRENT_ANNOUNCE?announceList.push([[global.WEBTORRENT_ANNOUNCE]]):Array.isArray(global.WEBTORRENT_ANNOUNCE)&&(announceList=announceList.concat(global.WEBTORRENT_ANNOUNCE.map(u=>[u])))),opts.announce===void 0&&opts.announceList===void 0&&(announceList=announceList.concat(module.exports.announceList)),"string"==typeof opts.urlList&&(opts.urlList=[opts.urlList]);const torrent={info:{name:opts.name},"creation date":_Mathceil((+opts.creationDate||Date.now())/1e3),encoding:"UTF-8"};0!==announceList.length&&(torrent.announce=announceList[0][0],torrent["announce-list"]=announceList),opts.comment!==void 0&&(torrent.comment=opts.comment),opts.createdBy!==void 0&&(torrent["created by"]=opts.createdBy),opts.private!==void 0&&(torrent.info.private=+opts.private),opts.info!==void 0&&Object.assign(torrent.info,opts.info),opts.sslCert!==void 0&&(torrent.info["ssl-cert"]=opts.sslCert),opts.urlList!==void 0&&(torrent["url-list"]=opts.urlList);const pieceLength=opts.pieceLength||calcPieceLength(files.reduce(sumLength,0));torrent.info["piece length"]=pieceLength,getPieceList(files,pieceLength,(err,pieces,torrentLength)=>err?cb(err):void(torrent.info.pieces=pieces,files.forEach(file=>{delete file.getStream}),opts.singleFileTorrent?torrent.info.length=torrentLength:torrent.info.files=files,cb(null,bencode.encode(torrent))))}function sumLength(sum,file){return sum+file.length}function isBlob(obj){return"undefined"!=typeof Blob&&obj instanceof Blob}function isFileList(obj){return"undefined"!=typeof FileList&&obj instanceof FileList}function isReadable(obj){return"object"==typeof obj&&null!=obj&&"function"==typeof obj.pipe}function getBlobStream(file){return()=>new FileReadStream(file)}function getBufferStream(buffer){return()=>{const s=new stream.PassThrough;return s.end(buffer),s}}function getStreamStream(readable,file){return()=>{const counter=new stream.Transform;return counter._transform=function(buf,enc,done){file.length+=buf.length,this.push(buf),done()},readable.pipe(counter),counter}}/*! create-torrent. MIT License. WebTorrent LLC */const bencode=require("bencode"),BlockStream=require("block-stream2"),calcPieceLength=require("piece-length"),corePath=require("path"),FileReadStream=require("filestream/read"),isFile=require("is-file"),junk=require("junk"),MultiStream=require("multistream"),once=require("once"),parallel=require("run-parallel"),sha1=require("simple-sha1"),stream=require("readable-stream"),getFiles=require("./get-files");module.exports=function(input,opts,cb){"function"==typeof opts&&([opts,cb]=[cb,opts]),opts=opts?Object.assign({},opts):{},_parseInput(input,opts,(err,files,singleFileTorrent)=>err?cb(err):void(opts.singleFileTorrent=singleFileTorrent,onFiles(files,opts,cb)))},module.exports.parseInput=function(input,opts,cb){"function"==typeof opts&&([opts,cb]=[cb,opts]),opts=opts?Object.assign({},opts):{},_parseInput(input,opts,cb)},module.exports.announceList=[["udp://tracker.leechers-paradise.org:6969"],["udp://tracker.coppersurfer.tk:6969"],["udp://tracker.opentrackr.org:1337"],["udp://explodie.org:6969"],["udp://tracker.empire-js.us:1337"],["wss://tracker.btorrent.xyz"],["wss://tracker.openwebtorrent.com"]]}).call(this)}).call(this,require("_process"),"undefined"==typeof global?"undefined"==typeof self?"undefined"==typeof window?{}:window:self:global,require("buffer").Buffer)},{"./get-files":22,_process:62,bencode:11,"block-stream2":21,buffer:24,"filestream/read":37,"is-file":44,junk:46,multistream:57,once:59,path:26,"piece-length":61,"readable-stream":86,"run-parallel":90,"simple-sha1":96}],33:[function(require,module,exports){(function(process){(function(){function load(){let r;try{r=exports.storage.getItem("debug")}catch(error){}return!r&&"undefined"!=typeof process&&"env"in process&&(r=process.env.DEBUG),r}exports.formatArgs=function(args){if(args[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+args[0]+(this.useColors?"%c ":" ")+"+"+module.exports.humanize(this.diff),!this.useColors)return;const c="color: "+this.color;args.splice(1,0,c,"color: inherit");let index=0,lastC=0;args[0].replace(/%[a-zA-Z%]/g,match=>{"%%"===match||(index++,"%c"===match&&(lastC=index))}),args.splice(lastC,0,c)},exports.save=function(namespaces){try{namespaces?exports.storage.setItem("debug",namespaces):exports.storage.removeItem("debug")}catch(error){}},exports.load=load,exports.useColors=function(){return!!("undefined"!=typeof window&&window.process&&("renderer"===window.process.type||window.process.__nwjs))||!("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))&&("undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&31<=parseInt(RegExp.$1,10)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/))},exports.storage=function(){try{return localStorage}catch(error){}}(),exports.destroy=(()=>{let warned=!1;return()=>{warned||(warned=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),exports.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],exports.log=console.debug||console.log||(()=>{}),module.exports=require("./common")(exports);const{formatters}=module.exports;formatters.j=function(v){try{return JSON.stringify(v)}catch(error){return"[UnexpectedJSONParseError]: "+error.message}}}).call(this)}).call(this,require("_process"))},{"./common":34,_process:62}],34:[function(require,module){module.exports=function(env){function createDebug(namespace){function debug(...args){if(!debug.enabled)return;const self=debug,curr=+new Date,ms=curr-(prevTime||curr);self.diff=ms,self.prev=prevTime,self.curr=curr,prevTime=curr,args[0]=createDebug.coerce(args[0]),"string"!=typeof args[0]&&args.unshift("%O");let index=0;args[0]=args[0].replace(/%([a-zA-Z%])/g,(match,format)=>{if("%%"===match)return"%";index++;const formatter=createDebug.formatters[format];if("function"==typeof formatter){const val=args[index];match=formatter.call(self,val),args.splice(index,1),index--}return match}),createDebug.formatArgs.call(self,args);const logFn=self.log||createDebug.log;logFn.apply(self,args)}let enableOverride=null,prevTime;return debug.namespace=namespace,debug.useColors=createDebug.useColors(),debug.color=createDebug.selectColor(namespace),debug.extend=extend,debug.destroy=createDebug.destroy,Object.defineProperty(debug,"enabled",{enumerable:!0,configurable:!1,get:()=>null===enableOverride?createDebug.enabled(namespace):enableOverride,set:v=>{enableOverride=v}}),"function"==typeof createDebug.init&&createDebug.init(debug),debug}function extend(namespace,delimiter){const newDebug=createDebug(this.namespace+("undefined"==typeof delimiter?":":delimiter)+namespace);return newDebug.log=this.log,newDebug}function toNamespace(regexp){return regexp.toString().substring(2,regexp.toString().length-2).replace(/\.\*\?$/,"*")}return createDebug.debug=createDebug,createDebug.default=createDebug,createDebug.coerce=function(val){return val instanceof Error?val.stack||val.message:val},createDebug.disable=function(){const namespaces=[...createDebug.names.map(toNamespace),...createDebug.skips.map(toNamespace).map(namespace=>"-"+namespace)].join(",");return createDebug.enable(""),namespaces},createDebug.enable=function(namespaces){createDebug.save(namespaces),createDebug.names=[],createDebug.skips=[];let i;const split=("string"==typeof namespaces?namespaces:"").split(/[\s,]+/),len=split.length;for(i=0;i{createDebug[key]=env[key]}),createDebug.names=[],createDebug.skips=[],createDebug.formatters={},createDebug.selectColor=function(namespace){let hash=0;for(let i=0;i{this.push(toBuffer(reader.result))},reader.onerror=()=>{this.emit("error",reader.error)},this.reader=reader,this._generateHeaderBlocks(file,opts,(err,blocks)=>err?this.emit("error",err):void(Array.isArray(blocks)&&blocks.forEach(block=>this.push(block)),this._ready=!0,this.emit("_ready")))}_generateHeaderBlocks(file,opts,callback){callback(null,[])}_read(){if(!this._ready)return void this.once("_ready",this._read.bind(this));const startOffset=this._offset;let endOffset=this._offset+this._chunkSize;return endOffset>this._size&&(endOffset=this._size),startOffset===this._size?(this.destroy(),void this.push(null)):void(this.reader.readAsArrayBuffer(this._file.slice(startOffset,endOffset)),this._offset=endOffset)}destroy(){if(this._file=null,this.reader){this.reader.onload=null,this.reader.onerror=null;try{this.reader.abort()}catch(e){}}this.reader=null}}},{"readable-stream":86,"typedarray-to-buffer":113}],38:[function(require,module){module.exports=function(){if("undefined"==typeof globalThis)return null;var wrtc={RTCPeerConnection:globalThis.RTCPeerConnection||globalThis.mozRTCPeerConnection||globalThis.webkitRTCPeerConnection,RTCSessionDescription:globalThis.RTCSessionDescription||globalThis.mozRTCSessionDescription||globalThis.webkitRTCSessionDescription,RTCIceCandidate:globalThis.RTCIceCandidate||globalThis.mozRTCIceCandidate||globalThis.webkitRTCIceCandidate};return wrtc.RTCPeerConnection?wrtc:null}},{}],39:[function(require,module){function validateParams(params){if("string"==typeof params&&(params=url.parse(params)),params.protocol||(params.protocol="https:"),"https:"!==params.protocol)throw new Error("Protocol \""+params.protocol+"\" not supported. Expected \"https:\"");return params}var http=require("http"),url=require("url"),https=module.exports;for(var key in http)http.hasOwnProperty(key)&&(https[key]=http[key]);https.request=function(params,cb){return params=validateParams(params),http.request.call(this,params,cb)},https.get=function(params,cb){return params=validateParams(params),http.get.call(this,params,cb)}},{http:100,url:116}],40:[function(require,module,exports){/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */exports.read=function(buffer,offset,isLE,mLen,nBytes){var eLen=8*nBytes-mLen-1,eMax=(1<>1,nBits=-7,i=isLE?nBytes-1:0,d=isLE?-1:1,s=buffer[offset+i],e,m;for(i+=d,e=s&(1<<-nBits)-1,s>>=-nBits,nBits+=eLen;0>=-nBits,nBits+=mLen;0>1,rt=23===mLen?_Mathpow(2,-24)-_Mathpow(2,-77):0,i=isLE?0:nBytes-1,d=isLE?1:-1,s=0>value||0===value&&0>1/value?1:0,e,m,c;for(value=_Mathabs(value),isNaN(value)||value===1/0?(m=isNaN(value)?1:0,e=eMax):(e=_Mathfloor(_Mathlog(value)/_MathLN),1>value*(c=_Mathpow(2,-e))&&(e--,c*=2),value+=1<=e+eBias?rt/c:rt*_Mathpow(2,1-eBias),2<=value*c&&(e++,c/=2),e+eBias>=eMax?(m=0,e=eMax):1<=e+eBias?(m=(value*c-1)*_Mathpow(2,mLen),e+=eBias):(m=value*_Mathpow(2,eBias-1)*_Mathpow(2,mLen),e=0));8<=mLen;buffer[offset+i]=255&m,i+=d,m/=256,mLen-=8);for(e=e< */const queueMicrotask=require("queue-microtask");module.exports=class ImmediateStore{constructor(store){if(this.store=store,this.chunkLength=store.chunkLength,!this.store||!this.store.get||!this.store.put)throw new Error("First argument must be abstract-chunk-store compliant");this.mem=[]}put(index,buf,cb){this.mem[index]=buf,this.store.put(index,buf,err=>{this.mem[index]=null,cb&&cb(err)})}get(index,opts,cb){if("function"==typeof opts)return this.get(index,null,opts);let memoryBuffer=this.mem[index];if(!memoryBuffer)return this.store.get(index,opts,cb);if(opts){const start=opts.offset||0,end=opts.length?start+opts.length:memoryBuffer.length;memoryBuffer=memoryBuffer.slice(start,end)}queueMicrotask(()=>{cb&&cb(null,memoryBuffer)})}close(cb){this.store.close(cb)}destroy(cb){this.store.destroy(cb)}}},{"queue-microtask":68}],42:[function(require,module){module.exports="function"==typeof Object.create?function(ctor,superCtor){superCtor&&(ctor.super_=superCtor,ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:!1,writable:!0,configurable:!0}}))}:function(ctor,superCtor){if(superCtor){ctor.super_=superCtor;var TempCtor=function(){};TempCtor.prototype=superCtor.prototype,ctor.prototype=new TempCtor,ctor.prototype.constructor=ctor}}},{}],43:[function(require,module){module.exports=function(str){for(var i=0,strLen=str.length;i127)return!1;return!0}},{}],44:[function(require,module){'use strict';function isFileSync(path){return fs.existsSync(path)&&fs.statSync(path).isFile()}var fs=require("fs");module.exports=function(path,cb){return cb?void fs.stat(path,function(err,stats){return err?cb(err):cb(null,stats.isFile())}):isFileSync(path)},module.exports.sync=isFileSync},{fs:23}],45:[function(require,module){function isTypedArray(arr){return isStrictTypedArray(arr)||isLooseTypedArray(arr)}function isStrictTypedArray(arr){return arr instanceof Int8Array||arr instanceof Int16Array||arr instanceof Int32Array||arr instanceof Uint8Array||arr instanceof Uint8ClampedArray||arr instanceof Uint16Array||arr instanceof Uint32Array||arr instanceof Float32Array||arr instanceof Float64Array}function isLooseTypedArray(arr){return names[toString.call(arr)]}module.exports=isTypedArray,isTypedArray.strict=isStrictTypedArray,isTypedArray.loose=isLooseTypedArray;var toString=Object.prototype.toString,names={"[object Int8Array]":!0,"[object Int16Array]":!0,"[object Int32Array]":!0,"[object Uint8Array]":!0,"[object Uint8ClampedArray]":!0,"[object Uint16Array]":!0,"[object Uint32Array]":!0,"[object Float32Array]":!0,"[object Float64Array]":!0}},{}],46:[function(require,module,exports){'use strict';exports.re=()=>{throw new Error("`junk.re` was renamed to `junk.regex`")},exports.regex=new RegExp(["^npm-debug\\.log$","^\\..*\\.swp$","^\\.DS_Store$","^\\.AppleDouble$","^\\.LSOverride$","^Icon\\r$","^\\._.*","^\\.Spotlight-V100(?:$|\\/)","\\.Trashes","^__MACOSX$","~$","^Thumbs\\.db$","^ehthumbs\\.db$","^Desktop\\.ini$","@eaDir$"].join("|")),exports.is=filename=>exports.regex.test(filename),exports.not=filename=>!exports.is(filename),exports.default=module.exports},{}],47:[function(require,module){(function(Buffer){(function(){function magnetURIDecode(uri){const result={},data=uri.split("magnet:?")[1],params=data&&0<=data.length?data.split("&"):[];params.forEach(param=>{const keyval=param.split("=");if(2!==keyval.length)return;const key=keyval[0];let val=keyval[1];"dn"===key&&(val=decodeURIComponent(val).replace(/\+/g," ")),("tr"===key||"xs"===key||"as"===key||"ws"===key)&&(val=decodeURIComponent(val)),"kt"===key&&(val=decodeURIComponent(val).split("+")),"ix"===key&&(val=+val),"so"===key&&(val=bep53Range.parse(decodeURIComponent(val).split(","))),result[key]?(!Array.isArray(result[key])&&(result[key]=[result[key]]),result[key].push(val)):result[key]=val});let m;if(result.xt){const xts=Array.isArray(result.xt)?result.xt:[result.xt];xts.forEach(xt=>{if(m=xt.match(/^urn:btih:(.{40})/))result.infoHash=m[1].toLowerCase();else if(m=xt.match(/^urn:btih:(.{32})/)){const decodedStr=base32.decode(m[1]);result.infoHash=Buffer.from(decodedStr,"binary").toString("hex")}})}if(result.xs){const xss=Array.isArray(result.xs)?result.xs:[result.xs];xss.forEach(xs=>{(m=xs.match(/^urn:btpk:(.{64})/))&&(result.publicKey=m[1].toLowerCase())})}return result.infoHash&&(result.infoHashBuffer=Buffer.from(result.infoHash,"hex")),result.publicKey&&(result.publicKeyBuffer=Buffer.from(result.publicKey,"hex")),result.dn&&(result.name=result.dn),result.kt&&(result.keywords=result.kt),result.announce=[],("string"==typeof result.tr||Array.isArray(result.tr))&&(result.announce=result.announce.concat(result.tr)),result.urlList=[],("string"==typeof result.as||Array.isArray(result.as))&&(result.urlList=result.urlList.concat(result.as)),("string"==typeof result.ws||Array.isArray(result.ws))&&(result.urlList=result.urlList.concat(result.ws)),result.peerAddresses=[],("string"==typeof result["x.pe"]||Array.isArray(result["x.pe"]))&&(result.peerAddresses=result.peerAddresses.concat(result["x.pe"])),result.announce=Array.from(new Set(result.announce)),result.urlList=Array.from(new Set(result.urlList)),result.peerAddresses=Array.from(new Set(result.peerAddresses)),result}module.exports=magnetURIDecode,module.exports.decode=magnetURIDecode,module.exports.encode=function(obj){obj=Object.assign({},obj),obj.infoHashBuffer&&(obj.xt=`urn:btih:${obj.infoHashBuffer.toString("hex")}`),obj.infoHash&&(obj.xt=`urn:btih:${obj.infoHash}`),obj.publicKeyBuffer&&(obj.xs=`urn:btpk:${obj.publicKeyBuffer.toString("hex")}`),obj.publicKey&&(obj.xs=`urn:btpk:${obj.publicKey}`),obj.name&&(obj.dn=obj.name),obj.keywords&&(obj.kt=obj.keywords),obj.announce&&(obj.tr=obj.announce),obj.urlList&&(obj.ws=obj.urlList,delete obj.as),obj.peerAddresses&&(obj["x.pe"]=obj.peerAddresses);let result="magnet:?";return Object.keys(obj).filter(key=>2===key.length||"x.pe"===key).forEach((key,i)=>{const values=Array.isArray(obj[key])?obj[key]:[obj[key]];values.forEach((val,j)=>{(0self._bufferDuration)&&self._cb){var cb=self._cb;self._cb=null,cb()}};MediaSourceStream.prototype._getBufferDuration=function(){for(var self=this,buffered=self._sourceBuffer.buffered,currentTime=self._elem.currentTime,bufferEnd=-1,i=0;icurrentTime)break;else(0<=bufferEnd||currentTime<=end)&&(bufferEnd=end)}var bufferedTime=bufferEnd-currentTime;return 0>bufferedTime&&(bufferedTime=0),bufferedTime}},{inherits:42,"readable-stream":86,"to-arraybuffer":110}],49:[function(require,module){(function(process){(function(){function Storage(chunkLength,opts){if(!(this instanceof Storage))return new Storage(chunkLength,opts);if(opts||(opts={}),this.chunkLength=+chunkLength,!this.chunkLength)throw new Error("First argument must be a chunk length");this.chunks=[],this.closed=!1,this.length=+opts.length||1/0,this.length!==1/0&&(this.lastChunkLength=this.length%this.chunkLength||this.chunkLength,this.lastChunkIndex=_Mathceil(this.length/this.chunkLength)-1)}function nextTick(cb,err,val){process.nextTick(function(){cb&&cb(err,val)})}module.exports=Storage,Storage.prototype.put=function(index,buf,cb){if(this.closed)return nextTick(cb,new Error("Storage is closed"));var isLastChunk=index===this.lastChunkIndex;return isLastChunk&&buf.length!==this.lastChunkLength?nextTick(cb,new Error("Last chunk length must be "+this.lastChunkLength)):isLastChunk||buf.length===this.chunkLength?void(this.chunks[index]=buf,nextTick(cb,null)):nextTick(cb,new Error("Chunk length must be "+this.chunkLength))},Storage.prototype.get=function(index,opts,cb){if("function"==typeof opts)return this.get(index,null,opts);if(this.closed)return nextTick(cb,new Error("Storage is closed"));var buf=this.chunks[index];if(!buf){var err=new Error("Chunk not found");return err.notFound=!0,nextTick(cb,err)}if(!opts)return nextTick(cb,null,buf);var offset=opts.offset||0,len=opts.length||buf.length-offset;nextTick(cb,null,buf.slice(offset,len+offset))},Storage.prototype.close=Storage.prototype.destroy=function(cb){return this.closed?nextTick(cb,new Error("Storage is closed")):void(this.closed=!0,this.chunks=null,nextTick(cb,null))}}).call(this)}).call(this,require("_process"))},{_process:62}],50:[function(require,module,exports){(function(Buffer){(function(){function writeReserved(buf,offset,end){for(var i=offset;i>3:0,mimeCodec=null;return oti&&(mimeCodec=oti.toString(16),audioConfig&&(mimeCodec+="."+audioConfig)),{mimeCodec:mimeCodec,buffer:Buffer.from(buf.slice(0))}},exports.esds.encodingLength=function(box){return box.buffer.length},exports.stsz={},exports.stsz.encode=function(box,buf,offset){var entries=box.entries||[];buf=buf?buf.slice(offset):Buffer.alloc(exports.stsz.encodingLength(box)),buf.writeUInt32BE(0,0),buf.writeUInt32BE(entries.length,4);for(var i=0;iUINT32_MAX&&(len=1),buffer.writeUInt32BE(len,offset),buffer.write(obj.type,offset+4,4,"ascii");var ptr=offset+8;if(1===len&&(uint64be.encode(obj.length,buffer,ptr),ptr+=8),boxes.fullBoxes[type]&&(buffer.writeUInt32BE(obj.flags||0,ptr),buffer.writeUInt8(obj.version||0,ptr),ptr+=4),containers[type]){var contents=containers[type];contents.forEach(function(childType){if(5===childType.length){var entry=obj[childType]||[];childType=childType.substr(0,4),entry.forEach(function(child){Box._encode(child,buffer,ptr),ptr+=Box.encode.bytes})}else obj[childType]&&(Box._encode(obj[childType],buffer,ptr),ptr+=Box.encode.bytes)}),obj.otherBoxes&&obj.otherBoxes.forEach(function(child){Box._encode(child,buffer,ptr),ptr+=Box.encode.bytes})}else if(boxes[type]){var encode=boxes[type].encode;encode(obj,buffer,ptr),ptr+=encode.bytes}else if(obj.buffer){var buf=obj.buffer;buf.copy(buffer,ptr),ptr+=obj.buffer.length}else throw new Error("Either `type` must be set to a known type (not'"+type+"') or `buffer` must be set");return Box.encode.bytes=ptr-offset,buffer},Box.readHeaders=function(buffer,start,end){if(start=start||0,end=end||buffer.length,8>end-start)return 8;var len=buffer.readUInt32BE(start),type=buffer.toString("ascii",start+4,start+8),ptr=start+8;if(1===len){if(16>end-start)return 16;len=uint64be.decode(buffer,ptr),ptr+=8}var version,flags;return boxes.fullBoxes[type]&&(version=buffer.readUInt8(ptr),flags=16777215&buffer.readUInt32BE(ptr),ptr+=4),{length:len,headersLen:ptr-start,contentLen:len-(ptr-start),type:type,version:version,flags:flags}},Box.decode=function(buffer,start,end){start=start||0,end=end||buffer.length;var headers=Box.readHeaders(buffer,start,end);if(!headers||headers.length>end-start)throw new Error("Data too short");return Box.decodeWithoutHeaders(headers,buffer,start+headers.headersLen,start+headers.length)},Box.decodeWithoutHeaders=function(headers,buffer,start,end){start=start||0,end=end||buffer.length;var type=headers.type,obj={};if(containers[type]){obj.otherBoxes=[];for(var contents=containers[type],ptr=start,child;8<=end-ptr;)if(child=Box.decode(buffer,ptr,end),ptr+=child.length,0<=contents.indexOf(child.type))obj[child.type]=child;else if(0<=contents.indexOf(child.type+"s")){var childType=child.type+"s",entry=obj[childType]=obj[childType]||[];entry.push(child)}else obj.otherBoxes.push(child)}else if(boxes[type]){var decode=boxes[type].decode;obj=decode(buffer,start,end)}else obj.buffer=Buffer.from(buffer.slice(start,end));return obj.length=headers.length,obj.contentLen=headers.contentLen,obj.type=headers.type,obj.version=headers.version,obj.flags=headers.flags,obj},Box.encodingLength=function(obj){var type=obj.type,len=8;if(boxes.fullBoxes[type]&&(len+=4),containers[type]){var contents=containers[type];contents.forEach(function(childType){if(5===childType.length){var entry=obj[childType]||[];childType=childType.substr(0,4),entry.forEach(function(child){child.type=childType,len+=Box.encodingLength(child)})}else if(obj[childType]){var child=obj[childType];child.type=childType,len+=Box.encodingLength(child)}}),obj.otherBoxes&&obj.otherBoxes.forEach(function(child){len+=Box.encodingLength(child)})}else if(boxes[type])len+=boxes[type].encodingLength(obj);else if(obj.buffer)len+=obj.buffer.length;else throw new Error("Either `type` must be set to a known type (not'"+type+"') or `buffer` must be set");return len>UINT32_MAX&&(len+=8),obj.length=len,len}}).call(this)}).call(this,require("buffer").Buffer)},{"./boxes":50,buffer:24,uint64be:114}],53:[function(require,module){(function(Buffer){(function(){var stream=require("readable-stream"),nextEvent=require("next-event"),Box=require("mp4-box-encoding"),EMPTY=Buffer.alloc(0);class Decoder extends stream.Writable{constructor(opts){super(opts),this.destroyed=!1,this._pending=0,this._missing=0,this._ignoreEmpty=!1,this._buf=null,this._str=null,this._cb=null,this._ondrain=null,this._writeBuffer=null,this._writeCb=null,this._ondrain=null,this._kick()}destroy(err){this.destroyed||(this.destroyed=!0,err&&this.emit("error",err),this.emit("close"))}_write(data,enc,next){if(!this.destroyed){for(var drained=!this._str||!this._str._writableState.needDrain;data.length&&!this.destroyed;){if(!this._missing&&!this._ignoreEmpty)return this._writeBuffer=data,void(this._writeCb=next);var consumed=data.length{this._pending--,this._kick()}),this._cb=cb,this._str}_readBox(){const bufferHeaders=(len,buf)=>{this._buffer(len,additionalBuf=>{buf=buf?Buffer.concat([buf,additionalBuf]):additionalBuf;var headers=Box.readHeaders(buf);"number"==typeof headers?bufferHeaders(headers-buf.length,buf):(this._pending++,this._headers=headers,this.emit("box",headers))})};bufferHeaders(8)}stream(){if(!this._headers)throw new Error("this function can only be called once after 'box' is emitted");var headers=this._headers;return this._headers=null,this._stream(headers.contentLen,null)}decode(cb){if(!this._headers)throw new Error("this function can only be called once after 'box' is emitted");var headers=this._headers;this._headers=null,this._buffer(headers.contentLen,buf=>{var box=Box.decodeWithoutHeaders(headers,buf);cb(box),this._pending--,this._kick()})}ignore(){if(!this._headers)throw new Error("this function can only be called once after 'box' is emitted");var headers=this._headers;this._headers=null,this._missing=headers.contentLen,0===this._missing&&(this._ignoreEmpty=!0),this._cb=()=>{this._pending--,this._kick()}}_kick(){if(!this._pending&&(this._buf||this._str||this._readBox(),this._writeBuffer)){var next=this._writeCb,buffer=this._writeBuffer;this._writeBuffer=null,this._writeCb=null,this._write(buffer,null,next)}}}class MediaData extends stream.PassThrough{constructor(parent){super(),this._parent=parent,this.destroyed=!1}destroy(err){this.destroyed||(this.destroyed=!0,this._parent.destroy(err),err&&this.emit("error",err),this.emit("close"))}}module.exports=Decoder}).call(this)}).call(this,require("buffer").Buffer)},{buffer:24,"mp4-box-encoding":52,"next-event":58,"readable-stream":86}],54:[function(require,module){(function(process,Buffer){(function(){function noop(){}var stream=require("readable-stream"),Box=require("mp4-box-encoding");class Encoder extends stream.Readable{constructor(opts){super(opts),this.destroyed=!1,this._finalized=!1,this._reading=!1,this._stream=null,this._drain=null,this._want=!1,this._onreadable=()=>{this._want&&(this._want=!1,this._read())},this._onend=()=>{this._stream=null}}mdat(size,cb){this.mediaData(size,cb)}mediaData(size,cb){var stream=new MediaData(this);return this.box({type:"mdat",contentLength:size,encodeBufferLen:8,stream:stream},cb),stream}box(box,cb){if(cb||(cb=noop),this.destroyed)return cb(new Error("Encoder is destroyed"));var buf;if(box.encodeBufferLen&&(buf=Buffer.alloc(box.encodeBufferLen)),box.stream)box.buffer=null,buf=Box.encode(box,buf),this.push(buf),this._stream=box.stream,this._stream.on("readable",this._onreadable),this._stream.on("end",this._onend),this._stream.on("end",cb),this._forward();else{buf=Box.encode(box,buf);var drained=this.push(buf);if(drained)return process.nextTick(cb);this._drain=cb}}destroy(err){if(!this.destroyed){if(this.destroyed=!0,this._stream&&this._stream.destroy&&this._stream.destroy(),this._stream=null,this._drain){var cb=this._drain;this._drain=null,cb(err)}err&&this.emit("error",err),this.emit("close")}}finalize(){this._finalized=!0,this._stream||this._drain||this.push(null)}_forward(){if(this._stream)for(;!this.destroyed;){var buf=this._stream.read();if(!buf)return void(this._want=!!this._stream);if(!this.push(buf))return}}_read(){if(!(this._reading||this.destroyed)){if(this._reading=!0,this._stream&&this._forward(),this._drain){var drain=this._drain;this._drain=null,drain()}this._reading=!1,this._finalized&&this.push(null)}}}class MediaData extends stream.PassThrough{constructor(parent){super(),this._parent=parent,this.destroyed=!1}destroy(err){this.destroyed||(this.destroyed=!0,this._parent.destroy(err),err&&this.emit("error",err),this.emit("close"))}}module.exports=Encoder}).call(this)}).call(this,require("_process"),require("buffer").Buffer)},{_process:62,buffer:24,"mp4-box-encoding":52,"readable-stream":86}],55:[function(require,module,exports){const Decoder=require("./decode"),Encoder=require("./encode");exports.decode=opts=>new Decoder(opts),exports.encode=opts=>new Encoder(opts)},{"./decode":53,"./encode":54}],56:[function(require,module){var _Mathround=Math.round;function parse(str){if(str+="",!(100=1.5*n?"s":"")}var d=24*(60*60000);module.exports=function(val,options){options=options||{};var type=typeof val;if("string"==type&&0 */var stream=require("readable-stream");class MultiStream extends stream.Readable{constructor(streams,opts){super(opts),this.destroyed=!1,this._drained=!1,this._forwarding=!1,this._current=null,this._toStreams2=opts&&opts.objectMode?toStreams2Obj:toStreams2Buf,"function"==typeof streams?this._queue=streams:(this._queue=streams.map(this._toStreams2),this._queue.forEach(stream=>{"function"!=typeof stream&&this._attachErrorListener(stream)})),this._next()}_read(){this._drained=!0,this._forward()}_forward(){if(!this._forwarding&&this._drained&&this._current){this._forwarding=!0;for(var chunk;this._drained&&null!==(chunk=this._current.read());)this._drained=this.push(chunk);this._forwarding=!1}}destroy(err){this.destroyed||(this.destroyed=!0,this._current&&this._current.destroy&&this._current.destroy(),"function"!=typeof this._queue&&this._queue.forEach(stream=>{stream.destroy&&stream.destroy()}),err&&this.emit("error",err),this.emit("close"))}_next(){if(this._current=null,"function"==typeof this._queue)this._queue((err,stream)=>err?this.destroy(err):void(stream=this._toStreams2(stream),this._attachErrorListener(stream),this._gotNextStream(stream)));else{var stream=this._queue.shift();"function"==typeof stream&&(stream=this._toStreams2(stream()),this._attachErrorListener(stream)),this._gotNextStream(stream)}}_gotNextStream(stream){if(!stream)return this.push(null),void this.destroy();this._current=stream,this._forward();const onReadable=()=>{this._forward()},onClose=()=>{stream._readableState.ended||this.destroy()},onEnd=()=>{this._current=null,stream.removeListener("readable",onReadable),stream.removeListener("end",onEnd),stream.removeListener("close",onClose),this._next()};stream.on("readable",onReadable),stream.once("end",onEnd),stream.once("close",onClose)}_attachErrorListener(stream){if(!stream)return;const onError=err=>{stream.removeListener("error",onError),this.destroy(err)};stream.once("error",onError)}}MultiStream.obj=streams=>new MultiStream(streams,{objectMode:!0,highWaterMark:16}),module.exports=MultiStream},{"readable-stream":86}],58:[function(require,module){module.exports=function(emitter,name){var next=null;return emitter.on(name,function(data){if(next){var fn=next;next=null,fn(data)}}),function(once){next=once}}},{}],59:[function(require,module){function once(fn){var f=function(){return f.called?f.value:(f.called=!0,f.value=fn.apply(this,arguments))};return f.called=!1,f}function onceStrict(fn){var f=function(){if(f.called)throw new Error(f.onceError);return f.called=!0,f.value=fn.apply(this,arguments)},name=fn.name||"Function wrapped with `once`";return f.onceError=name+" shouldn't be called more than once",f.called=!1,f}var wrappy=require("wrappy");module.exports=wrappy(once),module.exports.strict=wrappy(onceStrict),once.proto=once(function(){Object.defineProperty(Function.prototype,"once",{value:function(){return once(this)},configurable:!0}),Object.defineProperty(Function.prototype,"onceStrict",{value:function(){return onceStrict(this)},configurable:!0})})},{wrappy:122}],60:[function(require,module){(function(process,Buffer){(function(){function parseTorrent(torrentId){if("string"==typeof torrentId&&/^(stream-)?magnet:/.test(torrentId)){const torrentObj=magnet(torrentId);if(!torrentObj.infoHash)throw new Error("Invalid torrent identifier");return torrentObj}if("string"==typeof torrentId&&(/^[a-f0-9]{40}$/i.test(torrentId)||/^[a-z2-7]{32}$/i.test(torrentId)))return magnet(`magnet:?xt=urn:btih:${torrentId}`);if(Buffer.isBuffer(torrentId)&&20===torrentId.length)return magnet(`magnet:?xt=urn:btih:${torrentId.toString("hex")}`);if(Buffer.isBuffer(torrentId))return decodeTorrentFile(torrentId);if(torrentId&&torrentId.infoHash)return torrentId.infoHash=torrentId.infoHash.toLowerCase(),torrentId.announce||(torrentId.announce=[]),"string"==typeof torrentId.announce&&(torrentId.announce=[torrentId.announce]),torrentId.urlList||(torrentId.urlList=[]),torrentId;throw new Error("Invalid torrent identifier")}function parseTorrentRemote(torrentId,opts,cb){function parseOrThrow(torrentBuf){try{parsedTorrent=parseTorrent(torrentBuf)}catch(err){return cb(err)}parsedTorrent&&parsedTorrent.infoHash?cb(null,parsedTorrent):cb(new Error("Invalid torrent identifier"))}if("function"==typeof opts)return parseTorrentRemote(torrentId,{},opts);if("function"!=typeof cb)throw new Error("second argument must be a Function");let parsedTorrent;try{parsedTorrent=parseTorrent(torrentId)}catch(err){}parsedTorrent&&parsedTorrent.infoHash?process.nextTick(()=>{cb(null,parsedTorrent)}):isBlob(torrentId)?blobToBuffer(torrentId,(err,torrentBuf)=>err?cb(new Error(`Error converting Blob: ${err.message}`)):void parseOrThrow(torrentBuf)):"function"==typeof get&&/^https?:/.test(torrentId)?(opts=Object.assign({url:torrentId,timeout:30000,headers:{"user-agent":"WebTorrent (https://webtorrent.io)"}},opts),get.concat(opts,(err,res,torrentBuf)=>err?cb(new Error(`Error downloading torrent: ${err.message}`)):void parseOrThrow(torrentBuf))):"function"==typeof fs.readFile&&"string"==typeof torrentId?fs.readFile(torrentId,(err,torrentBuf)=>err?cb(new Error("Invalid torrent identifier")):void parseOrThrow(torrentBuf)):process.nextTick(()=>{cb(new Error("Invalid torrent identifier"))})}function decodeTorrentFile(torrent){Buffer.isBuffer(torrent)&&(torrent=bencode.decode(torrent)),ensure(torrent.info,"info"),ensure(torrent.info["name.utf-8"]||torrent.info.name,"info.name"),ensure(torrent.info["piece length"],"info['piece length']"),ensure(torrent.info.pieces,"info.pieces"),torrent.info.files?torrent.info.files.forEach(file=>{ensure("number"==typeof file.length,"info.files[0].length"),ensure(file["path.utf-8"]||file.path,"info.files[0].path")}):ensure("number"==typeof torrent.info.length,"info.length");const result={info:torrent.info,infoBuffer:bencode.encode(torrent.info),name:(torrent.info["name.utf-8"]||torrent.info.name).toString(),announce:[]};result.infoHash=sha1.sync(result.infoBuffer),result.infoHashBuffer=Buffer.from(result.infoHash,"hex"),void 0!==torrent.info.private&&(result.private=!!torrent.info.private),torrent["creation date"]&&(result.created=new Date(1e3*torrent["creation date"])),torrent["created by"]&&(result.createdBy=torrent["created by"].toString()),Buffer.isBuffer(torrent.comment)&&(result.comment=torrent.comment.toString()),Array.isArray(torrent["announce-list"])&&0{urls.forEach(url=>{result.announce.push(url.toString())})}):torrent.announce&&result.announce.push(torrent.announce.toString()),Buffer.isBuffer(torrent["url-list"])&&(torrent["url-list"]=0url.toString()),result.announce=Array.from(new Set(result.announce)),result.urlList=Array.from(new Set(result.urlList));const files=torrent.info.files||[torrent.info];result.files=files.map((file,i)=>{const parts=[].concat(result.name,file["path.utf-8"]||file.path||[]).map(p=>p.toString());return{path:path.join.apply(null,[path.sep].concat(parts)).slice(1),name:parts[parts.length-1],length:file.length,offset:files.slice(0,i).reduce(sumLength,0)}}),result.length=files.reduce(sumLength,0);const lastFile=result.files[result.files.length-1];return result.pieceLength=torrent.info["piece length"],result.lastPieceLength=(lastFile.offset+lastFile.length)%result.pieceLength||result.pieceLength,result.pieces=splitPieces(torrent.info.pieces),result}function isBlob(obj){return"undefined"!=typeof Blob&&obj instanceof Blob}function sumLength(sum,file){return sum+file.length}function splitPieces(buf){const pieces=[];for(let i=0;i */const bencode=require("bencode"),blobToBuffer=require("blob-to-buffer"),fs=require("fs"),get=require("simple-get"),magnet=require("magnet-uri"),path=require("path"),sha1=require("simple-sha1");module.exports=parseTorrent,module.exports.remote=parseTorrentRemote,module.exports.toMagnetURI=magnet.encode,module.exports.toTorrentFile=function(parsed){const torrent={info:parsed.info};return torrent["announce-list"]=(parsed.announce||[]).map(url=>(torrent.announce||(torrent.announce=url),url=Buffer.from(url,"utf8"),[url])),torrent["url-list"]=parsed.urlList||[],void 0!==parsed.private&&(torrent.private=+parsed.private),parsed.created&&(torrent["creation date"]=0|parsed.created.getTime()/1e3),parsed.createdBy&&(torrent["created by"]=parsed.createdBy),parsed.comment&&(torrent.comment=parsed.comment),bencode.encode(torrent)};(()=>{Buffer.alloc(0)})()}).call(this)}).call(this,require("_process"),require("buffer").Buffer)},{_process:62,bencode:11,"blob-to-buffer":20,buffer:24,fs:23,"magnet-uri":47,path:26,"simple-get":94,"simple-sha1":96}],61:[function(require,module){module.exports=function(bytes){return _Mathmax(16384,0|1<bytes?1:bytes/1024)+.5)}},{}],62:[function(require,module){function defaultSetTimout(){throw new Error("setTimeout has not been defined")}function defaultClearTimeout(){throw new Error("clearTimeout has not been defined")}function runTimeout(fun){if(cachedSetTimeout===setTimeout)return setTimeout(fun,0);if((cachedSetTimeout===defaultSetTimout||!cachedSetTimeout)&&setTimeout)return cachedSetTimeout=setTimeout,setTimeout(fun,0);try{return cachedSetTimeout(fun,0)}catch(e){try{return cachedSetTimeout.call(null,fun,0)}catch(e){return cachedSetTimeout.call(this,fun,0)}}}function runClearTimeout(marker){if(cachedClearTimeout===clearTimeout)return clearTimeout(marker);if((cachedClearTimeout===defaultClearTimeout||!cachedClearTimeout)&&clearTimeout)return cachedClearTimeout=clearTimeout,clearTimeout(marker);try{return cachedClearTimeout(marker)}catch(e){try{return cachedClearTimeout.call(null,marker)}catch(e){return cachedClearTimeout.call(this,marker)}}}function cleanUpNextTick(){draining&¤tQueue&&(draining=!1,currentQueue.length?queue=currentQueue.concat(queue):queueIndex=-1,queue.length&&drainQueue())}function drainQueue(){if(!draining){var timeout=runTimeout(cleanUpNextTick);draining=!0;for(var len=queue.length;len;){for(currentQueue=queue,queue=[];++queueIndexstreams.length)throw new Error("pump requires two streams per minimum");var destroys=streams.map(function(stream,i){var reading=i=value&&counter>>10),value=56320|1023&value),output+=stringFromCharCode(value),output}).join("")}function basicToDigit(codePoint){return 10>codePoint-48?codePoint-22:26>codePoint-65?codePoint-65:26>codePoint-97?codePoint-97:36}function digitToBasic(digit,flag){return digit+22+75*(26>digit)-((0!=flag)<<5)}function adapt(delta,numPoints,firstTime){var k=0;for(delta=firstTime?floor(delta/700):delta>>1,delta+=floor(delta/numPoints);455basic&&(basic=0),j=0;j=inputLength&&error("invalid-input"),digit=basicToDigit(input.charCodeAt(index++)),(36<=digit||digit>floor((2147483647-i)/w))&&error("overflow"),i+=digit*w,t=k<=bias?1:k>=bias+26?26:k-bias,digitfloor(2147483647/baseMinusT)&&error("overflow"),w*=baseMinusT}out=output.length+1,bias=adapt(i-oldi,out,0==oldi),floor(i/out)>2147483647-n&&error("overflow"),n+=floor(i/out),i%=out,output.splice(i++,0,n)}return ucs2encode(output)}function encode(input){var output=[],n,delta,handledCPCount,basicLength,bias,j,m,q,k,t,currentValue,inputLength,handledCPCountPlusOne,baseMinusT,qMinusT;for(input=ucs2decode(input),inputLength=input.length,n=128,delta=0,bias=72,j=0;jcurrentValue&&output.push(stringFromCharCode(currentValue));for(handledCPCount=basicLength=output.length,basicLength&&output.push("-");handledCPCount=n&¤tValuefloor((2147483647-delta)/handledCPCountPlusOne)&&error("overflow"),delta+=(m-n)*handledCPCountPlusOne,n=m,j=0;j=bias+26?26:k-bias,q= 0x80 (not a basic code point)","invalid-input":"Invalid input"},floor=_Mathfloor,stringFromCharCode=_StringfromCharCode,punycode,key;if(punycode={version:"1.4.1",ucs2:{decode:ucs2decode,encode:ucs2encode},decode:decode,encode:encode,toASCII:function(input){return mapDomain(input,function(string){return /[^\x20-\x7E]/.test(string)?"xn--"+encode(string):string})},toUnicode:function(input){return mapDomain(input,function(string){return /^xn--/.test(string)?decode(string.slice(4).toLowerCase()):string})}},"function"==typeof define&&"object"==typeof define.amd&&define.amd)define("punycode",function(){return punycode});else if(!(freeExports&&freeModule))root.punycode=punycode;else if(module.exports==freeExports)freeModule.exports=punycode;else for(key in punycode)punycode.hasOwnProperty(key)&&(freeExports[key]=punycode[key])})(this)}).call(this)}).call(this,"undefined"==typeof global?"undefined"==typeof self?"undefined"==typeof window?{}:window:self:global)},{}],65:[function(require,module){'use strict';function hasOwnProperty(obj,prop){return Object.prototype.hasOwnProperty.call(obj,prop)}module.exports=function(qs,sep,eq,options){sep=sep||"&",eq=eq||"=";var obj={};if("string"!=typeof qs||0===qs.length)return obj;qs=qs.split(sep);var maxKeys=1e3;options&&"number"==typeof options.maxKeys&&(maxKeys=options.maxKeys);var len=qs.length;0maxKeys&&(len=maxKeys);for(var i=0;i */let promise;module.exports="function"==typeof queueMicrotask?queueMicrotask.bind(globalThis):cb=>(promise||(promise=Promise.resolve())).then(cb).catch(err=>setTimeout(()=>{throw err},0))},{}],69:[function(require,module){module.exports=function(list){var offset=0;return function(){if(offset===list.length)return null;var len=list.length-offset,i=0|Math.random()*len,el=list[offset+i],tmp=list[offset];return list[offset]=el,list[offset+i]=tmp,offset++,el}}},{}],70:[function(require,module){(function(process,global){(function(){'use strict';var Buffer=require("safe-buffer").Buffer,crypto=global.crypto||global.msCrypto;module.exports=crypto&&crypto.getRandomValues?function(size,cb){if(size>4294967295)throw new RangeError("requested too many random bytes");var bytes=Buffer.allocUnsafe(size);if(0=chunk.length)return this._position+=chunk.length,cb(null);let toWrite;if(writeEnd>chunk.length){this._position+=chunk.length,toWrite=0===writeStart?chunk:chunk.slice(writeStart),drained=currRange.stream.write(toWrite)&&drained;break}this._position+=writeEnd,toWrite=0===writeStart&&writeEnd===chunk.length?chunk:chunk.slice(writeStart,writeEnd),drained=currRange.stream.write(toWrite)&&drained,currRange.last&&currRange.stream.end(),chunk=chunk.slice(writeEnd),this._queue.shift()}drained?cb(null):currRange.stream.once("drain",cb.bind(null,null))}slice(ranges){if(this.destroyed)return null;Array.isArray(ranges)||(ranges=[ranges]);const str=new PassThrough;return ranges.forEach((range,i)=>{this._queue.push({start:range.start,end:range.end,stream:str,last:i===ranges.length-1})}),this._buffer&&this._write(this._buffer,null,this._cb),str}destroy(err){this.destroyed||(this.destroyed=!0,err&&this.emit("error",err))}}},{"readable-stream":86}],72:[function(require,module){'use strict';function _inheritsLoose(subClass,superClass){subClass.prototype=Object.create(superClass.prototype),subClass.prototype.constructor=subClass,subClass.__proto__=superClass}function createErrorType(code,message,Base){function getMessage(arg1,arg2,arg3){return"string"==typeof message?message:message(arg1,arg2,arg3)}Base||(Base=Error);var NodeError=function(_Base){function NodeError(arg1,arg2,arg3){return _Base.call(this,getMessage(arg1,arg2,arg3))||this}return _inheritsLoose(NodeError,_Base),NodeError}(Base);NodeError.prototype.name=Base.name,NodeError.prototype.code=code,codes[code]=NodeError}function oneOf(expected,thing){if(Array.isArray(expected)){var len=expected.length;return expected=expected.map(function(i){return i+""}),2pos?0:+pos,search.length)===search}function endsWith(str,search,this_len){return(void 0===this_len||this_len>str.length)&&(this_len=str.length),str.substring(this_len-search.length,this_len)===search}function includes(str,search,start){return"number"!=typeof start&&(start=0),!(start+search.length>str.length)&&-1!==str.indexOf(search,start)}var codes={};createErrorType("ERR_INVALID_OPT_VALUE",function(name,value){return"The value \""+value+"\" is invalid for option \""+name+"\""},TypeError),createErrorType("ERR_INVALID_ARG_TYPE",function(name,expected,actual){var determiner;"string"==typeof expected&&startsWith(expected,"not ")?(determiner="must not be",expected=expected.replace(/^not /,"")):determiner="must be";var msg;if(endsWith(name," argument"))msg="The ".concat(name," ").concat(determiner," ").concat(oneOf(expected,"type"));else{var type=includes(name,".")?"property":"argument";msg="The \"".concat(name,"\" ").concat(type," ").concat(determiner," ").concat(oneOf(expected,"type"))}return msg+=". Received type ".concat(typeof actual),msg},TypeError),createErrorType("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF"),createErrorType("ERR_METHOD_NOT_IMPLEMENTED",function(name){return"The "+name+" method is not implemented"}),createErrorType("ERR_STREAM_PREMATURE_CLOSE","Premature close"),createErrorType("ERR_STREAM_DESTROYED",function(name){return"Cannot call "+name+" after a stream was destroyed"}),createErrorType("ERR_MULTIPLE_CALLBACK","Callback called multiple times"),createErrorType("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable"),createErrorType("ERR_STREAM_WRITE_AFTER_END","write after end"),createErrorType("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),createErrorType("ERR_UNKNOWN_ENCODING",function(arg){return"Unknown encoding: "+arg},TypeError),createErrorType("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event"),module.exports.codes=codes},{}],73:[function(require,module){(function(process){(function(){'use strict';function Duplex(options){return this instanceof Duplex?void(Readable.call(this,options),Writable.call(this,options),this.allowHalfOpen=!0,options&&(!1===options.readable&&(this.readable=!1),!1===options.writable&&(this.writable=!1),!1===options.allowHalfOpen&&(this.allowHalfOpen=!1,this.once("end",onend)))):new Duplex(options)}function onend(){this._writableState.ended||process.nextTick(onEndNT,this)}function onEndNT(self){self.end()}var objectKeys=Object.keys||function(obj){var keys=[];for(var key in obj)keys.push(key);return keys};module.exports=Duplex;var Readable=require("./_stream_readable"),Writable=require("./_stream_writable");require("inherits")(Duplex,Readable);for(var keys=objectKeys(Writable.prototype),v=0,method;v>>1,n|=n>>>2,n|=n>>>4,n|=n>>>8,n|=n>>>16,n++),n}function howMuchToRead(n,state){return 0>=n||0===state.length&&state.ended?0:state.objectMode?1:n===n?(n>state.highWaterMark&&(state.highWaterMark=computeNewHighWaterMark(n)),n<=state.length?n:state.ended?state.length:(state.needReadable=!0,0)):state.flowing&&state.length?state.buffer.head.data.length:state.length}function onEofChunk(stream,state){if(debug("onEofChunk"),!state.ended){if(state.decoder){var chunk=state.decoder.end();chunk&&chunk.length&&(state.buffer.push(chunk),state.length+=state.objectMode?1:chunk.length)}state.ended=!0,state.sync?emitReadable(stream):(state.needReadable=!1,!state.emittedReadable&&(state.emittedReadable=!0,emitReadable_(stream)))}}function emitReadable(stream){var state=stream._readableState;debug("emitReadable",state.needReadable,state.emittedReadable),state.needReadable=!1,state.emittedReadable||(debug("emitReadable",state.flowing),state.emittedReadable=!0,process.nextTick(emitReadable_,stream))}function emitReadable_(stream){var state=stream._readableState;debug("emitReadable_",state.destroyed,state.length,state.ended),!state.destroyed&&(state.length||state.ended)&&(stream.emit("readable"),state.emittedReadable=!1),state.needReadable=!state.flowing&&!state.ended&&state.length<=state.highWaterMark,flow(stream)}function maybeReadMore(stream,state){state.readingMore||(state.readingMore=!0,process.nextTick(maybeReadMore_,stream,state))}function maybeReadMore_(stream,state){for(;!state.reading&&!state.ended&&(state.length=state.length?(ret=state.decoder?state.buffer.join(""):1===state.buffer.length?state.buffer.first():state.buffer.concat(state.length),state.buffer.clear()):ret=state.buffer.consume(n,state.decoder),ret}function endReadable(stream){var state=stream._readableState;debug("endReadable",state.endEmitted),state.endEmitted||(state.ended=!0,process.nextTick(endReadableNT,state,stream))}function endReadableNT(state,stream){if(debug("endReadableNT",state.endEmitted,state.length),!state.endEmitted&&0===state.length&&(state.endEmitted=!0,stream.readable=!1,stream.emit("end"),state.autoDestroy)){var wState=stream._writableState;(!wState||wState.autoDestroy&&wState.finished)&&stream.destroy()}}function indexOf(xs,x){for(var i=0,l=xs.length;i=state.highWaterMark)||state.ended))return debug("read: emitReadable",state.length,state.ended),0===state.length&&state.ended?endReadable(this):emitReadable(this),null;if(n=howMuchToRead(n,state),0===n&&state.ended)return 0===state.length&&endReadable(this),null;var doRead=state.needReadable;debug("need readable",doRead),(0===state.length||state.length-n>>0),p=this.head,i=0;p;)copyBuffer(p.data,ret,i),i+=p.data.length,p=p.next;return ret}},{key:"consume",value:function(n,hasStrings){var ret;return nstr.length?str.length:n;if(ret+=nb===str.length?str:str.slice(0,n),n-=nb,0===n){nb===str.length?(++c,this.head=p.next?p.next:this.tail=null):(this.head=p,p.data=str.slice(nb));break}++c}return this.length-=c,ret}},{key:"_getBuffer",value:function(n){var ret=Buffer.allocUnsafe(n),p=this.head,c=1;for(p.data.copy(ret),n-=p.data.length;p=p.next;){var buf=p.data,nb=n>buf.length?buf.length:n;if(buf.copy(ret,ret.length-n,0,nb),n-=nb,0===n){nb===buf.length?(++c,this.head=p.next?p.next:this.tail=null):(this.head=p,p.data=buf.slice(nb));break}++c}return this.length-=c,ret}},{key:custom,value:function(_,options){return inspect(this,_objectSpread({},options,{depth:0,customInspect:!1}))}}]),BufferList}()},{buffer:24,util:22}],80:[function(require,module){(function(process){(function(){'use strict';function emitErrorAndCloseNT(self,err){emitErrorNT(self,err),emitCloseNT(self)}function emitCloseNT(self){self._writableState&&!self._writableState.emitClose||self._readableState&&!self._readableState.emitClose||self.emit("close")}function emitErrorNT(self,err){self.emit("error",err)}module.exports={destroy:function(err,cb){var _this=this,readableDestroyed=this._readableState&&this._readableState.destroyed,writableDestroyed=this._writableState&&this._writableState.destroyed;return readableDestroyed||writableDestroyed?(cb?cb(err):err&&(this._writableState?!this._writableState.errorEmitted&&(this._writableState.errorEmitted=!0,process.nextTick(emitErrorNT,this,err)):process.nextTick(emitErrorNT,this,err)),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(err||null,function(err){!cb&&err?_this._writableState?_this._writableState.errorEmitted?process.nextTick(emitCloseNT,_this):(_this._writableState.errorEmitted=!0,process.nextTick(emitErrorAndCloseNT,_this,err)):process.nextTick(emitErrorAndCloseNT,_this,err):cb?(process.nextTick(emitCloseNT,_this),cb(err)):process.nextTick(emitCloseNT,_this)}),this)},undestroy:function(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finalCalled=!1,this._writableState.prefinished=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)},errorOrDestroy:function(stream,err){var rState=stream._readableState,wState=stream._writableState;rState&&rState.autoDestroy||wState&&wState.autoDestroy?stream.destroy(err):stream.emit("error",err)}}}).call(this)}).call(this,require("_process"))},{_process:62}],81:[function(require,module){'use strict';function once(callback){var called=!1;return function(){if(!called){called=!0;for(var _len=arguments.length,args=Array(_len),_key=0;_key<_len;_key++)args[_key]=arguments[_key];callback.apply(this,args)}}}function noop(){}function isRequest(stream){return stream.setHeader&&"function"==typeof stream.abort}function eos(stream,opts,callback){if("function"==typeof opts)return eos(stream,null,opts);opts||(opts={}),callback=once(callback||noop);var readable=opts.readable||!1!==opts.readable&&stream.readable,writable=opts.writable||!1!==opts.writable&&stream.writable,onlegacyfinish=function(){stream.writable||onfinish()},writableEnded=stream._writableState&&stream._writableState.finished,onfinish=function(){writable=!1,writableEnded=!0,readable||callback.call(stream)},readableEnded=stream._readableState&&stream._readableState.endEmitted,onend=function(){readable=!1,readableEnded=!0,writable||callback.call(stream)},onerror=function(err){callback.call(stream,err)},onclose=function(){var err;return readable&&!readableEnded?(stream._readableState&&stream._readableState.ended||(err=new ERR_STREAM_PREMATURE_CLOSE),callback.call(stream,err)):writable&&!writableEnded?(stream._writableState&&stream._writableState.ended||(err=new ERR_STREAM_PREMATURE_CLOSE),callback.call(stream,err)):void 0},onrequest=function(){stream.req.on("finish",onfinish)};return isRequest(stream)?(stream.on("complete",onfinish),stream.on("abort",onclose),stream.req?onrequest():stream.on("request",onrequest)):writable&&!stream._writableState&&(stream.on("end",onlegacyfinish),stream.on("close",onlegacyfinish)),stream.on("end",onend),stream.on("finish",onfinish),!1!==opts.error&&stream.on("error",onerror),stream.on("close",onclose),function(){stream.removeListener("complete",onfinish),stream.removeListener("abort",onclose),stream.removeListener("request",onrequest),stream.req&&stream.req.removeListener("finish",onfinish),stream.removeListener("end",onlegacyfinish),stream.removeListener("close",onlegacyfinish),stream.removeListener("finish",onfinish),stream.removeListener("end",onend),stream.removeListener("error",onerror),stream.removeListener("close",onclose)}}var ERR_STREAM_PREMATURE_CLOSE=require("../../../errors").codes.ERR_STREAM_PREMATURE_CLOSE;module.exports=eos},{"../../../errors":72}],82:[function(require,module){module.exports=function(){throw new Error("Readable.from is not available in the browser")}},{}],83:[function(require,module){'use strict';function once(callback){var called=!1;return function(){called||(called=!0,callback.apply(void 0,arguments))}}function noop(err){if(err)throw err}function isRequest(stream){return stream.setHeader&&"function"==typeof stream.abort}function destroyer(stream,reading,writing,callback){callback=once(callback);var closed=!1;stream.on("close",function(){closed=!0}),eos===void 0&&(eos=require("./end-of-stream")),eos(stream,{readable:reading,writable:writing},function(err){return err?callback(err):void(closed=!0,callback())});var destroyed=!1;return function(err){if(!closed)return destroyed?void 0:(destroyed=!0,isRequest(stream)?stream.abort():"function"==typeof stream.destroy?stream.destroy():void callback(err||new ERR_STREAM_DESTROYED("pipe")))}}function call(fn){fn()}function pipe(from,to){return from.pipe(to)}function popCallback(streams){return streams.length?"function"==typeof streams[streams.length-1]?streams.pop():noop:noop}var _require$codes=require("../../../errors").codes,ERR_MISSING_ARGS=_require$codes.ERR_MISSING_ARGS,ERR_STREAM_DESTROYED=_require$codes.ERR_STREAM_DESTROYED,eos;module.exports=function(){for(var _len=arguments.length,streams=Array(_len),_key=0;_key<_len;_key++)streams[_key]=arguments[_key];var callback=popCallback(streams);if(Array.isArray(streams[0])&&(streams=streams[0]),2>streams.length)throw new ERR_MISSING_ARGS("streams");var destroys=streams.map(function(stream,i){var reading=ihwm){var name=isDuplex?duplexKey:"highWaterMark";throw new ERR_INVALID_OPT_VALUE(name,hwm)}return _Mathfloor(hwm)}return state.objectMode?16:16384}}},{"../../../errors":72}],85:[function(require,module){module.exports=require("events").EventEmitter},{events:25}],86:[function(require,module,exports){exports=module.exports=require("./lib/_stream_readable.js"),exports.Stream=exports,exports.Readable=exports,exports.Writable=require("./lib/_stream_writable.js"),exports.Duplex=require("./lib/_stream_duplex.js"),exports.Transform=require("./lib/_stream_transform.js"),exports.PassThrough=require("./lib/_stream_passthrough.js"),exports.finished=require("./lib/internal/streams/end-of-stream.js"),exports.pipeline=require("./lib/internal/streams/pipeline.js")},{"./lib/_stream_duplex.js":73,"./lib/_stream_passthrough.js":74,"./lib/_stream_readable.js":75,"./lib/_stream_transform.js":76,"./lib/_stream_writable.js":77,"./lib/internal/streams/end-of-stream.js":81,"./lib/internal/streams/pipeline.js":83}],87:[function(require,module,exports){function renderMedia(file,getElem,opts,cb){function checkBlobLength(){return!("number"==typeof file.length&&file.length>opts.maxBlobLength)||(debug("File length too large for Blob URL approach: %d (max: %d)",file.length,opts.maxBlobLength),fatalError(new Error(`File length too large for Blob URL approach: ${file.length} (max: ${opts.maxBlobLength})`)),!1)}function renderMediaElement(type){checkBlobLength()&&(elem=getElem(type),getBlobURL(file,(err,url)=>err?fatalError(err):void(elem.addEventListener("error",fatalError),elem.addEventListener("loadstart",onLoadStart),elem.addEventListener("loadedmetadata",onLoadedMetadata),elem.src=url)))}function onLoadStart(){if(elem.removeEventListener("loadstart",onLoadStart),opts.autoplay){const playPromise=elem.play();"undefined"!=typeof playPromise&&playPromise.catch(fatalError)}}function onLoadedMetadata(){elem.removeEventListener("loadedmetadata",onLoadedMetadata),cb(null,elem)}function renderIframe(){getBlobURL(file,(err,url)=>err?fatalError(err):void(".pdf"===extname?(elem=getElem("object"),elem.setAttribute("typemustmatch",!0),elem.setAttribute("type","application/pdf"),elem.setAttribute("data",url)):(elem=getElem("iframe"),elem.sandbox="allow-forms allow-scripts",elem.src=url),cb(null,elem)))}function fatalError(err){err.message=`Error rendering file "${file.name}": ${err.message}`,debug(err.message),cb(err)}const extname=path.extname(file.name).toLowerCase();let currentTime=0,elem;MEDIASOURCE_EXTS.includes(extname)?function(){function useVideostream(){debug(`Use \`videostream\` package for ${file.name}`),prepareElem(),elem.addEventListener("error",fallbackToMediaSource),elem.addEventListener("loadstart",onLoadStart),elem.addEventListener("loadedmetadata",onLoadedMetadata),new VideoStream(file,elem)}function useMediaSource(){debug(`Use MediaSource API for ${file.name}`),prepareElem(),elem.addEventListener("error",fallbackToBlobURL),elem.addEventListener("loadstart",onLoadStart),elem.addEventListener("loadedmetadata",onLoadedMetadata);const wrapper=new MediaElementWrapper(elem),writable=wrapper.createWriteStream(getCodec(file.name));file.createReadStream().pipe(writable),currentTime&&(elem.currentTime=currentTime)}function useBlobURL(){debug(`Use Blob URL for ${file.name}`),prepareElem(),elem.addEventListener("error",fatalError),elem.addEventListener("loadstart",onLoadStart),elem.addEventListener("loadedmetadata",onLoadedMetadata),getBlobURL(file,(err,url)=>err?fatalError(err):void(elem.src=url,currentTime&&(elem.currentTime=currentTime)))}function fallbackToMediaSource(err){debug("videostream error: fallback to MediaSource API: %o",err.message||err),elem.removeEventListener("error",fallbackToMediaSource),elem.removeEventListener("loadedmetadata",onLoadedMetadata),useMediaSource()}function fallbackToBlobURL(err){debug("MediaSource API error: fallback to Blob URL: %o",err.message||err);checkBlobLength()&&(elem.removeEventListener("error",fallbackToBlobURL),elem.removeEventListener("loadedmetadata",onLoadedMetadata),useBlobURL())}function prepareElem(){elem||(elem=getElem(tagName),elem.addEventListener("progress",()=>{currentTime=elem.currentTime}))}const tagName=MEDIASOURCE_VIDEO_EXTS.includes(extname)?"video":"audio";MediaSource?VIDEOSTREAM_EXTS.includes(extname)?useVideostream():useMediaSource():useBlobURL()}():VIDEO_EXTS.includes(extname)?renderMediaElement("video"):AUDIO_EXTS.includes(extname)?renderMediaElement("audio"):IMAGE_EXTS.includes(extname)?function(){elem=getElem("img"),getBlobURL(file,(err,url)=>err?fatalError(err):void(elem.src=url,elem.alt=file.name,cb(null,elem)))}():IFRAME_EXTS.includes(extname)?renderIframe():function(){function done(){isAscii(str)?(debug("File extension \"%s\" appears ascii, so will render.",extname),renderIframe()):(debug("File extension \"%s\" appears non-ascii, will not render.",extname),cb(new Error(`Unsupported file type "${extname}": Cannot append to DOM`)))}debug("Unknown file extension \"%s\" - will attempt to render into iframe",extname);let str="";file.createReadStream({start:0,end:1e3}).setEncoding("utf8").on("data",chunk=>{str+=chunk}).on("end",done).on("error",cb)}()}function getBlobURL(file,cb){const extname=path.extname(file.name).toLowerCase();streamToBlobURL(file.createReadStream(),exports.mime[extname]).then(blobUrl=>cb(null,blobUrl),err=>cb(err))}function validateFile(file){if(null==file)throw new Error("file cannot be null or undefined");if("string"!=typeof file.name)throw new Error("missing or invalid file.name property");if("function"!=typeof file.createReadStream)throw new Error("missing or invalid file.createReadStream property")}function getCodec(name){const extname=path.extname(name).toLowerCase();return{".m4a":"audio/mp4; codecs=\"mp4a.40.5\"",".m4b":"audio/mp4; codecs=\"mp4a.40.5\"",".m4p":"audio/mp4; codecs=\"mp4a.40.5\"",".m4v":"video/mp4; codecs=\"avc1.640029, mp4a.40.5\"",".mkv":"video/webm; codecs=\"avc1.640029, mp4a.40.5\"",".mp3":"audio/mpeg",".mp4":"video/mp4; codecs=\"avc1.640029, mp4a.40.5\"",".webm":"video/webm; codecs=\"vorbis, vp8\""}[extname]}function parseOpts(opts){null==opts.autoplay&&(opts.autoplay=!1),null==opts.muted&&(opts.muted=!1),null==opts.controls&&(opts.controls=!0),null==opts.maxBlobLength&&(opts.maxBlobLength=MAX_BLOB_LENGTH)}function setMediaOpts(elem,opts){elem.autoplay=!!opts.autoplay,elem.muted=!!opts.muted,elem.controls=!!opts.controls}exports.render=function(file,elem,opts,cb){"function"==typeof opts&&(cb=opts,opts={}),opts||(opts={}),cb||(cb=()=>{}),validateFile(file),parseOpts(opts),"string"==typeof elem&&(elem=document.querySelector(elem)),renderMedia(file,tagName=>{if(elem.nodeName!==tagName.toUpperCase()){const extname=path.extname(file.name).toLowerCase();throw new Error(`Cannot render "${extname}" inside a "${elem.nodeName.toLowerCase()}" element, expected "${tagName}"`)}return("video"===tagName||"audio"===tagName)&&setMediaOpts(elem,opts),elem},opts,cb)},exports.append=function(file,rootElem,opts,cb){function createMedia(tagName){const elem=createElem(tagName);return setMediaOpts(elem,opts),rootElem.appendChild(elem),elem}function createElem(tagName){const elem=document.createElement(tagName);return rootElem.appendChild(elem),elem}function done(err,elem){err&&elem&&elem.remove(),cb(err,elem)}if("function"==typeof opts&&(cb=opts,opts={}),opts||(opts={}),cb||(cb=()=>{}),validateFile(file),parseOpts(opts),"string"==typeof rootElem&&(rootElem=document.querySelector(rootElem)),rootElem&&("VIDEO"===rootElem.nodeName||"AUDIO"===rootElem.nodeName))throw new Error("Invalid video/audio node argument. Argument must be root element that video/audio tag will be appended to.");renderMedia(file,function(tagName){return"video"===tagName||"audio"===tagName?createMedia(tagName):createElem(tagName)},opts,done)},exports.mime=require("./lib/mime.json");const debug=require("debug")("render-media"),isAscii=require("is-ascii"),MediaElementWrapper=require("mediasource"),path=require("path"),streamToBlobURL=require("stream-to-blob-url"),VideoStream=require("videostream"),VIDEOSTREAM_EXTS=[".m4a",".m4b",".m4p",".m4v",".mp4"],MEDIASOURCE_VIDEO_EXTS=[".m4v",".mkv",".mp4",".webm"],MEDIASOURCE_EXTS=[].concat(MEDIASOURCE_VIDEO_EXTS,[".m4a",".m4b",".m4p",".mp3"]),VIDEO_EXTS=[".mov",".ogv"],AUDIO_EXTS=[".aac",".oga",".ogg",".wav",".flac"],IMAGE_EXTS=[".bmp",".gif",".jpeg",".jpg",".png",".svg"],IFRAME_EXTS=[".css",".html",".js",".md",".pdf",".srt",".txt"],MAX_BLOB_LENGTH=200000000,MediaSource="undefined"!=typeof window&&window.MediaSource},{"./lib/mime.json":88,debug:33,"is-ascii":43,mediasource:48,path:26,"stream-to-blob-url":104,videostream:121}],88:[function(require,module){module.exports={".3gp":"video/3gpp",".aac":"audio/aac",".aif":"audio/x-aiff",".aiff":"audio/x-aiff",".atom":"application/atom+xml",".avi":"video/x-msvideo",".bmp":"image/bmp",".bz2":"application/x-bzip2",".conf":"text/plain",".css":"text/css",".csv":"text/plain",".diff":"text/x-diff",".doc":"application/msword",".flv":"video/x-flv",".gif":"image/gif",".gz":"application/x-gzip",".htm":"text/html",".html":"text/html",".ico":"image/vnd.microsoft.icon",".ics":"text/calendar",".iso":"application/octet-stream",".jar":"application/java-archive",".jpeg":"image/jpeg",".jpg":"image/jpeg",".js":"application/javascript",".json":"application/json",".less":"text/css",".log":"text/plain",".m3u":"audio/x-mpegurl",".m4a":"audio/x-m4a",".m4b":"audio/mp4",".m4p":"audio/mp4",".m4v":"video/x-m4v",".manifest":"text/cache-manifest",".markdown":"text/x-markdown",".mathml":"application/mathml+xml",".md":"text/x-markdown",".mid":"audio/midi",".midi":"audio/midi",".mov":"video/quicktime",".mp3":"audio/mpeg",".mp4":"video/mp4",".mp4v":"video/mp4",".mpeg":"video/mpeg",".mpg":"video/mpeg",".odp":"application/vnd.oasis.opendocument.presentation",".ods":"application/vnd.oasis.opendocument.spreadsheet",".odt":"application/vnd.oasis.opendocument.text",".oga":"audio/ogg",".ogg":"application/ogg",".pdf":"application/pdf",".png":"image/png",".pps":"application/vnd.ms-powerpoint",".ppt":"application/vnd.ms-powerpoint",".ps":"application/postscript",".psd":"image/vnd.adobe.photoshop",".qt":"video/quicktime",".rar":"application/x-rar-compressed",".rdf":"application/rdf+xml",".rss":"application/rss+xml",".rtf":"application/rtf",".svg":"image/svg+xml",".svgz":"image/svg+xml",".swf":"application/x-shockwave-flash",".tar":"application/x-tar",".tbz":"application/x-bzip-compressed-tar",".text":"text/plain",".tif":"image/tiff",".tiff":"image/tiff",".torrent":"application/x-bittorrent",".ttf":"application/x-font-ttf",".txt":"text/plain",".wav":"audio/wav",".webm":"video/webm",".wma":"audio/x-ms-wma",".wmv":"video/x-ms-wmv",".xls":"application/vnd.ms-excel",".xml":"application/xml",".yaml":"text/yaml",".yml":"text/yaml",".zip":"application/zip"}},{}],89:[function(require,module){(function(process){(function(){/*! run-parallel-limit. MIT License. Feross Aboukhadijeh */module.exports=function(tasks,limit,cb){function done(err){function end(){cb&&cb(err,results),cb=null}isSync?process.nextTick(end):end()}function each(i,err,result){if(results[i]=result,err&&(isErrored=!0),0==--pending||err)done(err);else if(!isErrored&&next */module.exports=function(tasks,cb){function done(err){function end(){cb&&cb(err,results),cb=null}isSync?process.nextTick(end):end()}function each(i,err,result){results[i]=result,(0==--pending||err)&&done(err)}var isSync=!0,results,pending,keys;Array.isArray(tasks)?(results=[],pending=tasks.length):(keys=Object.keys(tasks),results={},pending=keys.length),pending?keys?keys.forEach(function(key){tasks[key](function(err,result){each(key,err,result)})}):tasks.forEach(function(task,i){task(function(err,result){each(i,err,result)})}):done(null),isSync=!1}}).call(this)}).call(this,require("_process"))},{_process:62}],91:[function(require,module,exports){(function(root,factory){"object"==typeof exports&&"object"==typeof module?module.exports=factory():"function"==typeof define&&define.amd?define([],factory):"object"==typeof exports?exports.Rusha=factory():root.Rusha=factory()})("undefined"==typeof self?this:self,function(){return function(modules){function __webpack_require__(moduleId){if(installedModules[moduleId])return installedModules[moduleId].exports;var module=installedModules[moduleId]={i:moduleId,l:!1,exports:{}};return modules[moduleId].call(module.exports,module,module.exports,__webpack_require__),module.l=!0,module.exports}var installedModules={};return __webpack_require__.m=modules,__webpack_require__.c=installedModules,__webpack_require__.d=function(exports,name,getter){__webpack_require__.o(exports,name)||Object.defineProperty(exports,name,{configurable:!1,enumerable:!0,get:getter})},__webpack_require__.n=function(module){var getter=module&&module.__esModule?function(){return module["default"]}:function(){return module};return __webpack_require__.d(getter,"a",getter),getter},__webpack_require__.o=function(object,property){return Object.prototype.hasOwnProperty.call(object,property)},__webpack_require__.p="",__webpack_require__(__webpack_require__.s=3)}([function(module,exports,__webpack_require__){function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}var RushaCore=__webpack_require__(5),_require=__webpack_require__(1),toHex=_require.toHex,ceilHeapSize=_require.ceilHeapSize,conv=__webpack_require__(6),padlen=function(len){for(len+=9;0>2)+1;i>2]|=128<<24-(chunkLen%4<<3),bin[(-16&(chunkLen>>2)+2)+14]=0|msgLen/536870912,bin[(-16&(chunkLen>>2)+2)+15]=msgLen<<3},getRawDigest=function(heap,padMaxChunkLen){var io=new Int32Array(heap,padMaxChunkLen+320,5),out=new Int32Array(5),arr=new DataView(out.buffer);return arr.setInt32(0,io[0],!1),arr.setInt32(4,io[1],!1),arr.setInt32(8,io[2],!1),arr.setInt32(12,io[3],!1),arr.setInt32(16,io[4],!1),out},Rusha=function(){function Rusha(chunkSize){if(_classCallCheck(this,Rusha),chunkSize=chunkSize||65536,0>2);return padZeroes(view,chunkLen),padData(view,chunkLen,msgLen),padChunkLen},Rusha.prototype._write=function(data,chunkOffset,chunkLen,off){conv(data,this._h8,this._h32,chunkOffset,chunkLen,off||0)},Rusha.prototype._coreCall=function(data,chunkOffset,chunkLen,msgLen,finalize){var padChunkLen=chunkLen;this._write(data,chunkOffset,chunkLen),finalize&&(padChunkLen=this._padChunk(chunkLen,msgLen)),this._core.hash(padChunkLen,this._padMaxChunkLen)},Rusha.prototype.rawDigest=function(str){var msgLen=str.byteLength||str.length||str.size||0;this._initState(this._heap,this._padMaxChunkLen);var chunkOffset=0,chunkLen=this._maxChunkLen;for(chunkOffset=0;msgLen>chunkOffset+chunkLen;chunkOffset+=chunkLen)this._coreCall(str,chunkOffset,chunkLen,msgLen,!1);return this._coreCall(str,chunkOffset,msgLen-chunkOffset,msgLen,!0),getRawDigest(this._heap,this._padMaxChunkLen)},Rusha.prototype.digest=function(str){return toHex(this.rawDigest(str).buffer)},Rusha.prototype.digestFromString=function(str){return this.digest(str)},Rusha.prototype.digestFromBuffer=function(str){return this.digest(str)},Rusha.prototype.digestFromArrayBuffer=function(str){return this.digest(str)},Rusha.prototype.resetState=function(){return this._initState(this._heap,this._padMaxChunkLen),this},Rusha.prototype.append=function(chunk){var chunkOffset=0,chunkLen=chunk.byteLength||chunk.length||chunk.size||0,turnOffset=this._offset%this._maxChunkLen,inputLen=void 0;for(this._offset+=chunkLen;chunkOffseti;i++)precomputedHex[i]=(16>i?"0":"")+i.toString(16);module.exports.toHex=function(arrayBuffer){for(var binarray=new Uint8Array(arrayBuffer),res=Array(arrayBuffer.byteLength),_i=0;_i=v)return 65536;if(16777216>v)for(p=1;p>2],y1$857=0|H$849[x$852+324>>2],y2$859=0|H$849[x$852+328>>2],y3$861=0|H$849[x$852+332>>2],y4$863=0|H$849[x$852+336>>2],i$853=0;(0|i$853)<(0|k$851);i$853=0|i$853+64){for(z0$856=y0$855,z1$858=y1$857,z2$860=y2$859,z3$862=y3$861,z4$864=y4$863,j$854=0;64>(0|j$854);j$854=0|j$854+4)t1$866=0|H$849[i$853+j$854>>2],t0$865=0|(0|(y0$855<<5|y0$855>>>27)+(y1$857&y2$859|~y1$857&y3$861))+(0|(0|t1$866+y4$863)+1518500249),y4$863=y3$861,y3$861=y2$859,y2$859=y1$857<<30|y1$857>>>2,y1$857=y0$855,y0$855=t0$865,H$849[k$851+j$854>>2]=t1$866;for(j$854=0|k$851+64;(0|j$854)<(0|k$851+80);j$854=0|j$854+4)t1$866=(H$849[j$854-12>>2]^H$849[j$854-32>>2]^H$849[j$854-56>>2]^H$849[j$854-64>>2])<<1|(H$849[j$854-12>>2]^H$849[j$854-32>>2]^H$849[j$854-56>>2]^H$849[j$854-64>>2])>>>31,t0$865=0|(0|(y0$855<<5|y0$855>>>27)+(y1$857&y2$859|~y1$857&y3$861))+(0|(0|t1$866+y4$863)+1518500249),y4$863=y3$861,y3$861=y2$859,y2$859=y1$857<<30|y1$857>>>2,y1$857=y0$855,y0$855=t0$865,H$849[j$854>>2]=t1$866;for(j$854=0|k$851+80;(0|j$854)<(0|k$851+160);j$854=0|j$854+4)t1$866=(H$849[j$854-12>>2]^H$849[j$854-32>>2]^H$849[j$854-56>>2]^H$849[j$854-64>>2])<<1|(H$849[j$854-12>>2]^H$849[j$854-32>>2]^H$849[j$854-56>>2]^H$849[j$854-64>>2])>>>31,t0$865=0|(0|(y0$855<<5|y0$855>>>27)+(y1$857^y2$859^y3$861))+(0|(0|t1$866+y4$863)+1859775393),y4$863=y3$861,y3$861=y2$859,y2$859=y1$857<<30|y1$857>>>2,y1$857=y0$855,y0$855=t0$865,H$849[j$854>>2]=t1$866;for(j$854=0|k$851+160;(0|j$854)<(0|k$851+240);j$854=0|j$854+4)t1$866=(H$849[j$854-12>>2]^H$849[j$854-32>>2]^H$849[j$854-56>>2]^H$849[j$854-64>>2])<<1|(H$849[j$854-12>>2]^H$849[j$854-32>>2]^H$849[j$854-56>>2]^H$849[j$854-64>>2])>>>31,t0$865=0|(0|(y0$855<<5|y0$855>>>27)+(y1$857&y2$859|y1$857&y3$861|y2$859&y3$861))+(0|(0|t1$866+y4$863)-1894007588),y4$863=y3$861,y3$861=y2$859,y2$859=y1$857<<30|y1$857>>>2,y1$857=y0$855,y0$855=t0$865,H$849[j$854>>2]=t1$866;for(j$854=0|k$851+240;(0|j$854)<(0|k$851+320);j$854=0|j$854+4)t1$866=(H$849[j$854-12>>2]^H$849[j$854-32>>2]^H$849[j$854-56>>2]^H$849[j$854-64>>2])<<1|(H$849[j$854-12>>2]^H$849[j$854-32>>2]^H$849[j$854-56>>2]^H$849[j$854-64>>2])>>>31,t0$865=0|(0|(y0$855<<5|y0$855>>>27)+(y1$857^y2$859^y3$861))+(0|(0|t1$866+y4$863)-899497514),y4$863=y3$861,y3$861=y2$859,y2$859=y1$857<<30|y1$857>>>2,y1$857=y0$855,y0$855=t0$865,H$849[j$854>>2]=t1$866;y0$855=0|y0$855+z0$856,y1$857=0|y1$857+z1$858,y2$859=0|y2$859+z2$860,y3$861=0|y3$861+z3$862,y4$863=0|y4$863+z4$864}H$849[x$852+320>>2]=y0$855,H$849[x$852+324>>2]=y1$857,H$849[x$852+328>>2]=y2$859,H$849[x$852+332>>2]=y3$861,H$849[x$852+336>>2]=y4$863}}}},function(module){var _this=this,reader=void 0;"undefined"!=typeof self&&"undefined"!=typeof self.FileReaderSync&&(reader=new self.FileReaderSync);var convStr=function(str,H8,H32,start,len,off){var om=off%4,lm=(len+om)%4,j=len-lm,i;switch(om){case 0:H8[off]=str.charCodeAt(start+3);case 1:H8[0|off+1-(om<<1)]=str.charCodeAt(start+2);case 2:H8[0|off+2-(om<<1)]=str.charCodeAt(start+1);case 3:H8[0|off+3-(om<<1)]=str.charCodeAt(start);}if(!(len>2]=str.charCodeAt(start+i)<<24|str.charCodeAt(start+i+1)<<16|str.charCodeAt(start+i+2)<<8|str.charCodeAt(start+i+3);switch(lm){case 3:H8[0|off+j+1]=str.charCodeAt(start+j+2);case 2:H8[0|off+j+2]=str.charCodeAt(start+j+1);case 1:H8[0|off+j+3]=str.charCodeAt(start+j);}}},convBuf=function(buf,H8,H32,start,len,off){var om=off%4,lm=(len+om)%4,j=len-lm,i;switch(om){case 0:H8[off]=buf[start+3];case 1:H8[0|off+1-(om<<1)]=buf[start+2];case 2:H8[0|off+2-(om<<1)]=buf[start+1];case 3:H8[0|off+3-(om<<1)]=buf[start];}if(!(len>2]=buf[start+i]<<24|buf[start+i+1]<<16|buf[start+i+2]<<8|buf[start+i+3];switch(lm){case 3:H8[0|off+j+1]=buf[start+j+2];case 2:H8[0|off+j+2]=buf[start+j+1];case 1:H8[0|off+j+3]=buf[start+j];}}},convBlob=function(blob,H8,H32,start,len,off){var i=void 0,om=off%4,lm=(len+om)%4,j=len-lm,buf=new Uint8Array(reader.readAsArrayBuffer(blob.slice(start,start+len)));switch(om){case 0:H8[off]=buf[3];case 1:H8[0|off+1-(om<<1)]=buf[2];case 2:H8[0|off+2-(om<<1)]=buf[1];case 3:H8[0|off+3-(om<<1)]=buf[0];}if(!(len>2]=buf[i]<<24|buf[i+1]<<16|buf[i+2]<<8|buf[i+3];switch(lm){case 3:H8[0|off+j+1]=buf[j+2];case 2:H8[0|off+j+2]=buf[j+1];case 1:H8[0|off+j+3]=buf[j];}}};module.exports=function(data,H8,H32,start,len,off){if("string"==typeof data)return convStr(data,H8,H32,start,len,off);if(data instanceof Array)return convBuf(data,H8,H32,start,len,off);if(_this&&_this.Buffer&&_this.Buffer.isBuffer(data))return convBuf(data,H8,H32,start,len,off);if(data instanceof ArrayBuffer)return convBuf(new Uint8Array(data),H8,H32,start,len,off);if(data.buffer instanceof ArrayBuffer)return convBuf(new Uint8Array(data.buffer,data.byteOffset,data.byteLength),H8,H32,start,len,off);if(data instanceof Blob)return convBlob(data,H8,H32,start,len,off);throw new Error("Unsupported data type.")}},function(module,exports,__webpack_require__){function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}var Rusha=__webpack_require__(0),_require=__webpack_require__(1),toHex=_require.toHex,Hash=function(){function Hash(){_classCallCheck(this,Hash),this._rusha=new Rusha,this._rusha.resetState()}return Hash.prototype.update=function(data){return this._rusha.append(data),this},Hash.prototype.digest=function digest(encoding){var digest=this._rusha.rawEnd().buffer;if(!encoding)return digest;if("hex"===encoding)return toHex(digest);throw new Error("unsupported digest encoding")},Hash}();module.exports=function(){return new Hash}}])})},{}],92:[function(require,module,exports){function copyProps(src,dst){for(var key in src)dst[key]=src[key]}function SafeBuffer(arg,encodingOrOffset,length){return Buffer(arg,encodingOrOffset,length)}/*! safe-buffer. MIT License. Feross Aboukhadijeh */var buffer=require("buffer"),Buffer=buffer.Buffer;Buffer.from&&Buffer.alloc&&Buffer.allocUnsafe&&Buffer.allocUnsafeSlow?module.exports=buffer:(copyProps(buffer,exports),exports.Buffer=SafeBuffer),SafeBuffer.prototype=Object.create(Buffer.prototype),copyProps(Buffer,SafeBuffer),SafeBuffer.from=function(arg,encodingOrOffset,length){if("number"==typeof arg)throw new TypeError("Argument must not be a number");return Buffer(arg,encodingOrOffset,length)},SafeBuffer.alloc=function(size,fill,encoding){if("number"!=typeof size)throw new TypeError("Argument must be a number");var buf=Buffer(size);return void 0===fill?buf.fill(0):"string"==typeof encoding?buf.fill(fill,encoding):buf.fill(fill),buf},SafeBuffer.allocUnsafe=function(size){if("number"!=typeof size)throw new TypeError("Argument must be a number");return Buffer(size)},SafeBuffer.allocUnsafeSlow=function(size){if("number"!=typeof size)throw new TypeError("Argument must be a number");return buffer.SlowBuffer(size)}},{buffer:24}],93:[function(require,module){(function(Buffer){(function(){/*! simple-concat. MIT License. Feross Aboukhadijeh */module.exports=function(stream,cb){var chunks=[];stream.on("data",function(chunk){chunks.push(chunk)}),stream.once("end",function(){cb&&cb(null,Buffer.concat(chunks)),cb=null}),stream.once("error",function(err){cb&&cb(err),cb=null})}}).call(this)}).call(this,require("buffer").Buffer)},{buffer:24}],94:[function(require,module){(function(Buffer){(function(){function simpleGet(opts,cb){if(opts=Object.assign({maxRedirects:10},"string"==typeof opts?{url:opts}:opts),cb=once(cb),opts.url){const{hostname,port,protocol,auth,path}=url.parse(opts.url);delete opts.url,hostname||port||protocol||auth?Object.assign(opts,{hostname,port,protocol,auth,path}):opts.path=path}const headers={"accept-encoding":"gzip, deflate"};opts.headers&&Object.keys(opts.headers).forEach(k=>headers[k.toLowerCase()]=opts.headers[k]),opts.headers=headers;let body;opts.body?body=opts.json&&!isStream(opts.body)?JSON.stringify(opts.body):opts.body:opts.form&&(body="string"==typeof opts.form?opts.form:querystring.stringify(opts.form),opts.headers["content-type"]="application/x-www-form-urlencoded"),body&&(!opts.method&&(opts.method="POST"),!isStream(body)&&(opts.headers["content-length"]=Buffer.byteLength(body)),opts.json&&!opts.form&&(opts.headers["content-type"]="application/json")),delete opts.body,delete opts.form,opts.json&&(opts.headers.accept="application/json"),opts.method&&(opts.method=opts.method.toUpperCase());const protocol="https:"===opts.protocol?https:http,req=protocol.request(opts,res=>{if(!1!==opts.followRedirects&&300<=res.statusCode&&400>res.statusCode&&res.headers.location)return opts.url=res.headers.location,delete opts.headers.host,res.resume(),"POST"===opts.method&&[301,302].includes(res.statusCode)&&(opts.method="GET",delete opts.headers["content-length"],delete opts.headers["content-type"]),0==opts.maxRedirects--?cb(new Error("too many redirects")):simpleGet(opts,cb);const tryUnzip="function"==typeof decompressResponse&&"HEAD"!==opts.method;cb(null,tryUnzip?decompressResponse(res):res)});return req.on("timeout",()=>{req.abort(),cb(new Error("Request timed out"))}),req.on("error",cb),isStream(body)?body.on("error",cb).pipe(req):req.end(body),req}module.exports=simpleGet;const concat=require("simple-concat"),decompressResponse=require("decompress-response"),http=require("http"),https=require("https"),once=require("once"),querystring=require("querystring"),url=require("url"),isStream=o=>null!==o&&"object"==typeof o&&"function"==typeof o.pipe;simpleGet.concat=(opts,cb)=>simpleGet(opts,(err,res)=>err?cb(err):void concat(res,(err,data)=>{if(err)return cb(err);if(opts.json)try{data=JSON.parse(data.toString())}catch(err){return cb(err,res,data)}cb(null,res,data)})),["get","post","put","patch","head","delete"].forEach(method=>{simpleGet[method]=(opts,cb)=>("string"==typeof opts&&(opts={url:opts}),simpleGet(Object.assign({method:method.toUpperCase()},opts),cb))})}).call(this)}).call(this,require("buffer").Buffer)},{buffer:24,"decompress-response":22,http:100,https:39,once:59,querystring:67,"simple-concat":93,url:116}],95:[function(require,module){function filterTrickle(sdp){return sdp.replace(/a=ice-options:trickle\s\n/g,"")}function warn(message){console.warn(message)}/*! simple-peer. MIT License. Feross Aboukhadijeh */const debug=require("debug")("simple-peer"),getBrowserRTC=require("get-browser-rtc"),randombytes=require("randombytes"),stream=require("readable-stream"),queueMicrotask=require("queue-microtask"),errCode=require("err-code"),{Buffer}=require("buffer"),MAX_BUFFERED_AMOUNT=65536;class Peer extends stream.Duplex{constructor(opts){if(opts=Object.assign({allowHalfOpen:!1},opts),super(opts),this._id=randombytes(4).toString("hex").slice(0,7),this._debug("new peer %o",opts),this.channelName=opts.initiator?opts.channelName||randombytes(20).toString("hex"):null,this.initiator=opts.initiator||!1,this.channelConfig=opts.channelConfig||Peer.channelConfig,this.channelNegotiated=this.channelConfig.negotiated,this.config=Object.assign({},Peer.config,opts.config),this.offerOptions=opts.offerOptions||{},this.answerOptions=opts.answerOptions||{},this.sdpTransform=opts.sdpTransform||(sdp=>sdp),this.streams=opts.streams||(opts.stream?[opts.stream]:[]),this.trickle=void 0===opts.trickle||opts.trickle,this.allowHalfTrickle=void 0!==opts.allowHalfTrickle&&opts.allowHalfTrickle,this.iceCompleteTimeout=opts.iceCompleteTimeout||5000,this.destroyed=!1,this.destroying=!1,this._connected=!1,this.remoteAddress=void 0,this.remoteFamily=void 0,this.remotePort=void 0,this.localAddress=void 0,this.localFamily=void 0,this.localPort=void 0,this._wrtc=opts.wrtc&&"object"==typeof opts.wrtc?opts.wrtc:getBrowserRTC(),!this._wrtc)if("undefined"==typeof window)throw errCode(new Error("No WebRTC support: Specify `opts.wrtc` option in this environment"),"ERR_WEBRTC_SUPPORT");else throw errCode(new Error("No WebRTC support: Not a supported browser"),"ERR_WEBRTC_SUPPORT");this._pcReady=!1,this._channelReady=!1,this._iceComplete=!1,this._iceCompleteTimer=null,this._channel=null,this._pendingCandidates=[],this._isNegotiating=!1,this._firstNegotiation=!0,this._batchedNegotiation=!1,this._queuedNegotiation=!1,this._sendersAwaitingStable=[],this._senderMap=new Map,this._closingInterval=null,this._remoteTracks=[],this._remoteStreams=[],this._chunk=null,this._cb=null,this._interval=null;try{this._pc=new this._wrtc.RTCPeerConnection(this.config)}catch(err){return void queueMicrotask(()=>this.destroy(errCode(err,"ERR_PC_CONSTRUCTOR")))}this._isReactNativeWebrtc="number"==typeof this._pc._peerConnectionId,this._pc.oniceconnectionstatechange=()=>{this._onIceStateChange()},this._pc.onicegatheringstatechange=()=>{this._onIceStateChange()},this._pc.onconnectionstatechange=()=>{this._onConnectionStateChange()},this._pc.onsignalingstatechange=()=>{this._onSignalingStateChange()},this._pc.onicecandidate=event=>{this._onIceCandidate(event)},this.initiator||this.channelNegotiated?this._setupData({channel:this._pc.createDataChannel(this.channelName,this.channelConfig)}):this._pc.ondatachannel=event=>{this._setupData(event)},this.streams&&this.streams.forEach(stream=>{this.addStream(stream)}),this._pc.ontrack=event=>{this._onTrack(event)},this._debug("initial negotiation"),this._needsNegotiation(),this._onFinishBound=()=>{this._onFinish()},this.once("finish",this._onFinishBound)}get bufferSize(){return this._channel&&this._channel.bufferedAmount||0}get connected(){return this._connected&&"open"===this._channel.readyState}address(){return{port:this.localPort,family:this.localFamily,address:this.localAddress}}signal(data){if(this.destroyed)throw errCode(new Error("cannot signal after peer is destroyed"),"ERR_SIGNALING");if("string"==typeof data)try{data=JSON.parse(data)}catch(err){data={}}this._debug("signal()"),data.renegotiate&&this.initiator&&(this._debug("got request to renegotiate"),this._needsNegotiation()),data.transceiverRequest&&this.initiator&&(this._debug("got request for transceiver"),this.addTransceiver(data.transceiverRequest.kind,data.transceiverRequest.init)),data.candidate&&(this._pc.remoteDescription&&this._pc.remoteDescription.type?this._addIceCandidate(data.candidate):this._pendingCandidates.push(data.candidate)),data.sdp&&this._pc.setRemoteDescription(new this._wrtc.RTCSessionDescription(data)).then(()=>{this.destroyed||(this._pendingCandidates.forEach(candidate=>{this._addIceCandidate(candidate)}),this._pendingCandidates=[],"offer"===this._pc.remoteDescription.type&&this._createAnswer())}).catch(err=>{this.destroy(errCode(err,"ERR_SET_REMOTE_DESCRIPTION"))}),data.sdp||data.candidate||data.renegotiate||data.transceiverRequest||this.destroy(errCode(new Error("signal() called with invalid signal data"),"ERR_SIGNALING"))}_addIceCandidate(candidate){const iceCandidateObj=new this._wrtc.RTCIceCandidate(candidate);this._pc.addIceCandidate(iceCandidateObj).catch(err=>{!iceCandidateObj.address||iceCandidateObj.address.endsWith(".local")?warn("Ignoring unsupported ICE candidate."):this.destroy(errCode(err,"ERR_ADD_ICE_CANDIDATE"))})}send(chunk){this._channel.send(chunk)}addTransceiver(kind,init){if(this._debug("addTransceiver()"),this.initiator)try{this._pc.addTransceiver(kind,init),this._needsNegotiation()}catch(err){this.destroy(errCode(err,"ERR_ADD_TRANSCEIVER"))}else this.emit("signal",{type:"transceiverRequest",transceiverRequest:{kind,init}})}addStream(stream){this._debug("addStream()"),stream.getTracks().forEach(track=>{this.addTrack(track,stream)})}addTrack(track,stream){this._debug("addTrack()");const submap=this._senderMap.get(track)||new Map;let sender=submap.get(stream);if(!sender)sender=this._pc.addTrack(track,stream),submap.set(stream,sender),this._senderMap.set(track,submap),this._needsNegotiation();else if(sender.removed)throw errCode(new Error("Track has been removed. You should enable/disable tracks that you want to re-add."),"ERR_SENDER_REMOVED");else throw errCode(new Error("Track has already been added to that stream."),"ERR_SENDER_ALREADY_ADDED")}replaceTrack(oldTrack,newTrack,stream){this._debug("replaceTrack()");const submap=this._senderMap.get(oldTrack),sender=submap?submap.get(stream):null;if(!sender)throw errCode(new Error("Cannot replace track that was never added."),"ERR_TRACK_NOT_ADDED");newTrack&&this._senderMap.set(newTrack,submap),null==sender.replaceTrack?this.destroy(errCode(new Error("replaceTrack is not supported in this browser"),"ERR_UNSUPPORTED_REPLACETRACK")):sender.replaceTrack(newTrack)}removeTrack(track,stream){this._debug("removeSender()");const submap=this._senderMap.get(track),sender=submap?submap.get(stream):null;if(!sender)throw errCode(new Error("Cannot remove track that was never added."),"ERR_TRACK_NOT_ADDED");try{sender.removed=!0,this._pc.removeTrack(sender)}catch(err){"NS_ERROR_UNEXPECTED"===err.name?this._sendersAwaitingStable.push(sender):this.destroy(errCode(err,"ERR_REMOVE_TRACK"))}this._needsNegotiation()}removeStream(stream){this._debug("removeSenders()"),stream.getTracks().forEach(track=>{this.removeTrack(track,stream)})}_needsNegotiation(){this._debug("_needsNegotiation");this._batchedNegotiation||(this._batchedNegotiation=!0,queueMicrotask(()=>{this._batchedNegotiation=!1,this.initiator||!this._firstNegotiation?(this._debug("starting batched negotiation"),this.negotiate()):this._debug("non-initiator initial negotiation request discarded"),this._firstNegotiation=!1}))}negotiate(){this.initiator?this._isNegotiating?(this._queuedNegotiation=!0,this._debug("already negotiating, queueing")):(this._debug("start negotiation"),setTimeout(()=>{this._createOffer()},0)):this._isNegotiating?(this._queuedNegotiation=!0,this._debug("already negotiating, queueing")):(this._debug("requesting negotiation from initiator"),this.emit("signal",{type:"renegotiate",renegotiate:!0})),this._isNegotiating=!0}destroy(err){this._destroy(err,()=>{})}_destroy(err,cb){this.destroyed||this.destroying||(this.destroying=!0,this._debug("destroying (error: %s)",err&&(err.message||err)),queueMicrotask(()=>{if(this.destroyed=!0,this.destroying=!1,this._debug("destroy (error: %s)",err&&(err.message||err)),this.readable=this.writable=!1,this._readableState.ended||this.push(null),this._writableState.finished||this.end(),this._connected=!1,this._pcReady=!1,this._channelReady=!1,this._remoteTracks=null,this._remoteStreams=null,this._senderMap=null,clearInterval(this._closingInterval),this._closingInterval=null,clearInterval(this._interval),this._interval=null,this._chunk=null,this._cb=null,this._onFinishBound&&this.removeListener("finish",this._onFinishBound),this._onFinishBound=null,this._channel){try{this._channel.close()}catch(err){}this._channel.onmessage=null,this._channel.onopen=null,this._channel.onclose=null,this._channel.onerror=null}if(this._pc){try{this._pc.close()}catch(err){}this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ontrack=null,this._pc.ondatachannel=null}this._pc=null,this._channel=null,err&&this.emit("error",err),this.emit("close"),cb()}))}_setupData(event){if(!event.channel)return this.destroy(errCode(new Error("Data channel event is missing `channel` property"),"ERR_DATA_CHANNEL"));this._channel=event.channel,this._channel.binaryType="arraybuffer","number"==typeof this._channel.bufferedAmountLowThreshold&&(this._channel.bufferedAmountLowThreshold=MAX_BUFFERED_AMOUNT),this.channelName=this._channel.label,this._channel.onmessage=event=>{this._onChannelMessage(event)},this._channel.onbufferedamountlow=()=>{this._onChannelBufferedAmountLow()},this._channel.onopen=()=>{this._onChannelOpen()},this._channel.onclose=()=>{this._onChannelClose()},this._channel.onerror=err=>{this.destroy(errCode(err,"ERR_DATA_CHANNEL"))};let isClosing=!1;this._closingInterval=setInterval(()=>{this._channel&&"closing"===this._channel.readyState?(isClosing&&this._onChannelClose(),isClosing=!0):isClosing=!1},5000)}_read(){}_write(chunk,encoding,cb){if(this.destroyed)return cb(errCode(new Error("cannot write after peer is destroyed"),"ERR_DATA_CHANNEL"));if(this._connected){try{this.send(chunk)}catch(err){return this.destroy(errCode(err,"ERR_DATA_CHANNEL"))}this._channel.bufferedAmount>MAX_BUFFERED_AMOUNT?(this._debug("start backpressure: bufferedAmount %d",this._channel.bufferedAmount),this._cb=cb):cb(null)}else this._debug("write before connect"),this._chunk=chunk,this._cb=cb}_onFinish(){if(!this.destroyed){const destroySoon=()=>{setTimeout(()=>this.destroy(),1e3)};this._connected?destroySoon():this.once("connect",destroySoon)}}_startIceCompleteTimeout(){this.destroyed||this._iceCompleteTimer||(this._debug("started iceComplete timeout"),this._iceCompleteTimer=setTimeout(()=>{this._iceComplete||(this._iceComplete=!0,this._debug("iceComplete timeout completed"),this.emit("iceTimeout"),this.emit("_iceComplete"))},this.iceCompleteTimeout))}_createOffer(){this.destroyed||this._pc.createOffer(this.offerOptions).then(offer=>{if(this.destroyed)return;this.trickle||this.allowHalfTrickle||(offer.sdp=filterTrickle(offer.sdp)),offer.sdp=this.sdpTransform(offer.sdp);const sendOffer=()=>{if(!this.destroyed){const signal=this._pc.localDescription||offer;this._debug("signal"),this.emit("signal",{type:signal.type,sdp:signal.sdp})}};this._pc.setLocalDescription(offer).then(()=>{this._debug("createOffer success");this.destroyed||(this.trickle||this._iceComplete?sendOffer():this.once("_iceComplete",sendOffer))}).catch(err=>{this.destroy(errCode(err,"ERR_SET_LOCAL_DESCRIPTION"))})}).catch(err=>{this.destroy(errCode(err,"ERR_CREATE_OFFER"))})}_requestMissingTransceivers(){this._pc.getTransceivers&&this._pc.getTransceivers().forEach(transceiver=>{transceiver.mid||!transceiver.sender.track||transceiver.requested||(transceiver.requested=!0,this.addTransceiver(transceiver.sender.track.kind))})}_createAnswer(){this.destroyed||this._pc.createAnswer(this.answerOptions).then(answer=>{if(this.destroyed)return;this.trickle||this.allowHalfTrickle||(answer.sdp=filterTrickle(answer.sdp)),answer.sdp=this.sdpTransform(answer.sdp);const sendAnswer=()=>{if(!this.destroyed){const signal=this._pc.localDescription||answer;this._debug("signal"),this.emit("signal",{type:signal.type,sdp:signal.sdp}),this.initiator||this._requestMissingTransceivers()}};this._pc.setLocalDescription(answer).then(()=>{this.destroyed||(this.trickle||this._iceComplete?sendAnswer():this.once("_iceComplete",sendAnswer))}).catch(err=>{this.destroy(errCode(err,"ERR_SET_LOCAL_DESCRIPTION"))})}).catch(err=>{this.destroy(errCode(err,"ERR_CREATE_ANSWER"))})}_onConnectionStateChange(){this.destroyed||"failed"===this._pc.connectionState&&this.destroy(errCode(new Error("Connection failed."),"ERR_CONNECTION_FAILURE"))}_onIceStateChange(){if(this.destroyed)return;const iceConnectionState=this._pc.iceConnectionState,iceGatheringState=this._pc.iceGatheringState;this._debug("iceStateChange (connection: %s) (gathering: %s)",iceConnectionState,iceGatheringState),this.emit("iceStateChange",iceConnectionState,iceGatheringState),("connected"===iceConnectionState||"completed"===iceConnectionState)&&(this._pcReady=!0,this._maybeReady()),"failed"===iceConnectionState&&this.destroy(errCode(new Error("Ice connection failed."),"ERR_ICE_CONNECTION_FAILURE")),"closed"===iceConnectionState&&this.destroy(errCode(new Error("Ice connection closed."),"ERR_ICE_CONNECTION_CLOSED"))}getStats(cb){const flattenValues=report=>("[object Array]"===Object.prototype.toString.call(report.values)&&report.values.forEach(value=>{Object.assign(report,value)}),report);0===this._pc.getStats.length||this._isReactNativeWebrtc?this._pc.getStats().then(res=>{const reports=[];res.forEach(report=>{reports.push(flattenValues(report))}),cb(null,reports)},err=>cb(err)):0{if(this.destroyed)return;const reports=[];res.result().forEach(result=>{const report={};result.names().forEach(name=>{report[name]=result.stat(name)}),report.id=result.id,report.type=result.type,report.timestamp=result.timestamp,reports.push(flattenValues(report))}),cb(null,reports)},err=>cb(err)):cb(null,[])}_maybeReady(){if(this._debug("maybeReady pc %s channel %s",this._pcReady,this._channelReady),this._connected||this._connecting||!this._pcReady||!this._channelReady)return;this._connecting=!0;const findCandidatePair=()=>{this.destroyed||this.getStats((err,items)=>{if(this.destroyed)return;err&&(items=[]);const remoteCandidates={},localCandidates={},candidatePairs={};let foundSelectedCandidatePair=!1;items.forEach(item=>{("remotecandidate"===item.type||"remote-candidate"===item.type)&&(remoteCandidates[item.id]=item),("localcandidate"===item.type||"local-candidate"===item.type)&&(localCandidates[item.id]=item),("candidatepair"===item.type||"candidate-pair"===item.type)&&(candidatePairs[item.id]=item)});const setSelectedCandidatePair=selectedCandidatePair=>{foundSelectedCandidatePair=!0;let local=localCandidates[selectedCandidatePair.localCandidateId];local&&(local.ip||local.address)?(this.localAddress=local.ip||local.address,this.localPort=+local.port):local&&local.ipAddress?(this.localAddress=local.ipAddress,this.localPort=+local.portNumber):"string"==typeof selectedCandidatePair.googLocalAddress&&(local=selectedCandidatePair.googLocalAddress.split(":"),this.localAddress=local[0],this.localPort=+local[1]),this.localAddress&&(this.localFamily=this.localAddress.includes(":")?"IPv6":"IPv4");let remote=remoteCandidates[selectedCandidatePair.remoteCandidateId];remote&&(remote.ip||remote.address)?(this.remoteAddress=remote.ip||remote.address,this.remotePort=+remote.port):remote&&remote.ipAddress?(this.remoteAddress=remote.ipAddress,this.remotePort=+remote.portNumber):"string"==typeof selectedCandidatePair.googRemoteAddress&&(remote=selectedCandidatePair.googRemoteAddress.split(":"),this.remoteAddress=remote[0],this.remotePort=+remote[1]),this.remoteAddress&&(this.remoteFamily=this.remoteAddress.includes(":")?"IPv6":"IPv4"),this._debug("connect local: %s:%s remote: %s:%s",this.localAddress,this.localPort,this.remoteAddress,this.remotePort)};if(items.forEach(item=>{"transport"===item.type&&item.selectedCandidatePairId&&setSelectedCandidatePair(candidatePairs[item.selectedCandidatePairId]),("googCandidatePair"===item.type&&"true"===item.googActiveConnection||("candidatepair"===item.type||"candidate-pair"===item.type)&&item.selected)&&setSelectedCandidatePair(item)}),!foundSelectedCandidatePair&&(!Object.keys(candidatePairs).length||Object.keys(localCandidates).length))return void setTimeout(findCandidatePair,100);if(this._connecting=!1,this._connected=!0,this._chunk){try{this.send(this._chunk)}catch(err){return this.destroy(errCode(err,"ERR_DATA_CHANNEL"))}this._chunk=null,this._debug("sent chunk from \"write before connect\"");const cb=this._cb;this._cb=null,cb(null)}"number"!=typeof this._channel.bufferedAmountLowThreshold&&(this._interval=setInterval(()=>this._onInterval(),150),this._interval.unref&&this._interval.unref()),this._debug("connect"),this.emit("connect")})};findCandidatePair()}_onInterval(){this._cb&&this._channel&&!(this._channel.bufferedAmount>MAX_BUFFERED_AMOUNT)&&this._onChannelBufferedAmountLow()}_onSignalingStateChange(){this.destroyed||("stable"===this._pc.signalingState&&(this._isNegotiating=!1,this._debug("flushing sender queue",this._sendersAwaitingStable),this._sendersAwaitingStable.forEach(sender=>{this._pc.removeTrack(sender),this._queuedNegotiation=!0}),this._sendersAwaitingStable=[],this._queuedNegotiation?(this._debug("flushing negotiation queue"),this._queuedNegotiation=!1,this._needsNegotiation()):(this._debug("negotiated"),this.emit("negotiated"))),this._debug("signalingStateChange %s",this._pc.signalingState),this.emit("signalingStateChange",this._pc.signalingState))}_onIceCandidate(event){this.destroyed||(event.candidate&&this.trickle?this.emit("signal",{type:"candidate",candidate:{candidate:event.candidate.candidate,sdpMLineIndex:event.candidate.sdpMLineIndex,sdpMid:event.candidate.sdpMid}}):!event.candidate&&!this._iceComplete&&(this._iceComplete=!0,this.emit("_iceComplete")),event.candidate&&this._startIceCompleteTimeout())}_onChannelMessage(event){if(this.destroyed)return;let data=event.data;data instanceof ArrayBuffer&&(data=Buffer.from(data)),this.push(data)}_onChannelBufferedAmountLow(){if(!this.destroyed&&this._cb){this._debug("ending backpressure: bufferedAmount %d",this._channel.bufferedAmount);const cb=this._cb;this._cb=null,cb(null)}}_onChannelOpen(){this._connected||this.destroyed||(this._debug("on channel open"),this._channelReady=!0,this._maybeReady())}_onChannelClose(){this.destroyed||(this._debug("on channel close"),this.destroy())}_onTrack(event){this.destroyed||event.streams.forEach(eventStream=>{this._debug("on track"),this.emit("track",event.track,eventStream),this._remoteTracks.push({track:event.track,stream:eventStream});this._remoteStreams.some(remoteStream=>remoteStream.id===eventStream.id)||(this._remoteStreams.push(eventStream),queueMicrotask(()=>{this._debug("on stream"),this.emit("stream",eventStream)}))})}_debug(){const args=[].slice.call(arguments);args[0]="["+this._id+"] "+args[0],debug.apply(null,args)}}Peer.WEBRTC_SUPPORT=!!getBrowserRTC(),Peer.config={iceServers:[{urls:["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478"]}],sdpSemantics:"unified-plan"},Peer.channelConfig={},module.exports=Peer},{buffer:24,debug:33,"err-code":36,"get-browser-rtc":38,"queue-microtask":68,randombytes:70,"readable-stream":86}],96:[function(require,module){function sha1sync(buf){return rusha.digest(buf)}function sha1(buf,cb){return subtle?void("string"==typeof buf&&(buf=uint8array(buf)),subtle.digest({name:"sha-1"},buf).then(function(result){cb(hex(new Uint8Array(result)))},function(){cb(sha1sync(buf))})):void("undefined"==typeof window?queueMicrotask(()=>cb(sha1sync(buf))):rushaWorkerSha1(buf,function(err,hash){return err?void cb(sha1sync(buf)):void cb(hash)}))}function uint8array(s){for(var l=s.length,array=new Uint8Array(l),i=0;i>>4).toString(16)),chars.push((15&bite).toString(16));return chars.join("")}var Rusha=require("rusha"),rushaWorkerSha1=require("./rusha-worker-sha1"),rusha=new Rusha,scope="undefined"==typeof window?self:window,crypto=scope.crypto||scope.msCrypto||{},subtle=crypto.subtle||crypto.webkitSubtle;try{subtle.digest({name:"sha-1"},new Uint8Array).catch(function(){subtle=!1})}catch(err){subtle=!1}module.exports=sha1,module.exports.sync=sha1sync},{"./rusha-worker-sha1":97,rusha:91}],97:[function(require,module){function init(){worker=Rusha.createWorker(),nextTaskId=1,cbs={},worker.onmessage=function(e){var taskId=e.data.id,cb=cbs[taskId];delete cbs[taskId],null==e.data.error?cb(null,e.data.hash):cb(new Error("Rusha worker error: "+e.data.error))}}function sha1(buf,cb){worker||init(),cbs[nextTaskId]=cb,worker.postMessage({id:nextTaskId,data:buf}),nextTaskId+=1}var Rusha=require("rusha"),worker,nextTaskId,cbs;module.exports=sha1},{rusha:91}],98:[function(require,module){(function(Buffer){(function(){const debug=require("debug")("simple-websocket"),randombytes=require("randombytes"),stream=require("readable-stream"),queueMicrotask=require("queue-microtask"),ws=require("ws"),_WebSocket="function"==typeof ws?ws:WebSocket,MAX_BUFFERED_AMOUNT=65536;class Socket extends stream.Duplex{constructor(opts={}){if("string"==typeof opts&&(opts={url:opts}),opts=Object.assign({allowHalfOpen:!1},opts),super(opts),null==opts.url&&null==opts.socket)throw new Error("Missing required `url` or `socket` option");if(null!=opts.url&&null!=opts.socket)throw new Error("Must specify either `url` or `socket` option, not both");if(this._id=randombytes(4).toString("hex").slice(0,7),this._debug("new websocket: %o",opts),this.connected=!1,this.destroyed=!1,this._chunk=null,this._cb=null,this._interval=null,opts.socket)this.url=opts.socket.url,this._ws=opts.socket,this.connected=opts.socket.readyState===_WebSocket.OPEN;else{this.url=opts.url;try{this._ws="function"==typeof ws?new _WebSocket(opts.url,opts):new _WebSocket(opts.url)}catch(err){return void queueMicrotask(()=>this.destroy(err))}}this._ws.binaryType="arraybuffer",this._ws.onopen=()=>{this._onOpen()},this._ws.onmessage=event=>{this._onMessage(event)},this._ws.onclose=()=>{this._onClose()},this._ws.onerror=()=>{this.destroy(new Error("connection error to "+this.url))},this._onFinishBound=()=>{this._onFinish()},this.once("finish",this._onFinishBound)}send(chunk){this._ws.send(chunk)}destroy(err){this._destroy(err,()=>{})}_destroy(err,cb){if(!this.destroyed){if(this._debug("destroy (error: %s)",err&&(err.message||err)),this.readable=this.writable=!1,this._readableState.ended||this.push(null),this._writableState.finished||this.end(),this.connected=!1,this.destroyed=!0,clearInterval(this._interval),this._interval=null,this._chunk=null,this._cb=null,this._onFinishBound&&this.removeListener("finish",this._onFinishBound),this._onFinishBound=null,this._ws){const ws=this._ws,onClose=()=>{ws.onclose=null};if(ws.readyState===_WebSocket.CLOSED)onClose();else try{ws.onclose=onClose,ws.close()}catch(err){onClose()}ws.onopen=null,ws.onmessage=null,ws.onerror=()=>{}}if(this._ws=null,err){if("undefined"!=typeof DOMException&&err instanceof DOMException){const code=err.code;err=new Error(err.message),err.code=code}this.emit("error",err)}this.emit("close"),cb()}}_read(){}_write(chunk,encoding,cb){if(this.destroyed)return cb(new Error("cannot write after socket is destroyed"));if(this.connected){try{this.send(chunk)}catch(err){return this.destroy(err)}"function"!=typeof ws&&this._ws.bufferedAmount>MAX_BUFFERED_AMOUNT?(this._debug("start backpressure: bufferedAmount %d",this._ws.bufferedAmount),this._cb=cb):cb(null)}else this._debug("write before connect"),this._chunk=chunk,this._cb=cb}_onFinish(){if(!this.destroyed){const destroySoon=()=>{setTimeout(()=>this.destroy(),1e3)};this.connected?destroySoon():this.once("connect",destroySoon)}}_onMessage(event){if(this.destroyed)return;let data=event.data;data instanceof ArrayBuffer&&(data=Buffer.from(data)),this.push(data)}_onOpen(){if(!(this.connected||this.destroyed)){if(this.connected=!0,this._chunk){try{this.send(this._chunk)}catch(err){return this.destroy(err)}this._chunk=null,this._debug("sent chunk from \"write before connect\"");const cb=this._cb;this._cb=null,cb(null)}"function"!=typeof ws&&(this._interval=setInterval(()=>this._onInterval(),150),this._interval.unref&&this._interval.unref()),this._debug("connect"),this.emit("connect")}}_onInterval(){if(this._cb&&this._ws&&!(this._ws.bufferedAmount>MAX_BUFFERED_AMOUNT)){this._debug("ending backpressure: bufferedAmount %d",this._ws.bufferedAmount);const cb=this._cb;this._cb=null,cb(null)}}_onClose(){this.destroyed||(this._debug("on close"),this.destroy())}_debug(){const args=[].slice.call(arguments);args[0]="["+this._id+"] "+args[0],debug.apply(null,args)}}Socket.WEBSOCKET_SUPPORT=!!_WebSocket,module.exports=Socket}).call(this)}).call(this,require("buffer").Buffer)},{buffer:24,debug:33,"queue-microtask":68,randombytes:70,"readable-stream":86,ws:22}],99:[function(require,module){var tick=1,maxTick=65535,resolution=4,inc=function(){tick=tick+1&maxTick},timer;module.exports=function(seconds){timer||(timer=setInterval(inc,0|1e3/resolution),timer.unref&&timer.unref());var size=resolution*(seconds||5),buffer=[0],pointer=1,last=tick-1&maxTick;return function(delta){var dist=tick-last&maxTick;for(dist>size&&(dist=size),last=tick;dist--;)pointer===size&&(pointer=0),buffer[pointer]=buffer[0===pointer?size-1:pointer-1],pointer++;delta&&(buffer[pointer-1]+=delta);var top=buffer[pointer-1],btm=buffer.lengthself._pos){var newData=response.substr(self._pos);if("x-user-defined"===self._charset){for(var buffer=Buffer.alloc(newData.length),i=0;iself._pos&&(self.push(Buffer.from(new Uint8Array(reader.result.slice(self._pos)))),self._pos=reader.result.byteLength)},reader.onload=function(){self.push(null)},reader.readAsArrayBuffer(response);}self._xhr.readyState===rStates.DONE&&"ms-stream"!==self._mode&&self.push(null)}}).call(this)}).call(this,require("_process"),"undefined"==typeof global?"undefined"==typeof self?"undefined"==typeof window?{}:window:self:global,require("buffer").Buffer)},{"./capability":101,_process:62,buffer:24,inherits:42,"readable-stream":86}],104:[function(require,module){module.exports=async function(stream,mimeType){const blob=await getBlob(stream,mimeType),url=URL.createObjectURL(blob);return url};const getBlob=require("stream-to-blob")},{"stream-to-blob":105}],105:[function(require,module){/*! stream-to-blob. MIT License. Feross Aboukhadijeh */module.exports=function(stream,mimeType){if(null!=mimeType&&"string"!=typeof mimeType)throw new Error("Invalid mimetype, expected string.");return new Promise((resolve,reject)=>{const chunks=[];stream.on("data",chunk=>chunks.push(chunk)).once("end",()=>{const blob=null==mimeType?new Blob(chunks):new Blob(chunks,{type:mimeType});resolve(blob)}).once("error",reject)})}},{}],106:[function(require,module){(function(Buffer){(function(){/*! stream-with-known-length-to-buffer. MIT License. Feross Aboukhadijeh */var once=require("once");module.exports=function(stream,length,cb){cb=once(cb);var buf=Buffer.alloc(length),offset=0;stream.on("data",function(chunk){chunk.copy(buf,offset),offset+=chunk.length}).on("end",function(){cb(null,buf)}).on("error",cb)}}).call(this)}).call(this,require("buffer").Buffer)},{buffer:24,once:59}],107:[function(require,module,exports){'use strict';function _normalizeEncoding(enc){if(!enc)return"utf8";for(var retried;;)switch(enc){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return enc;default:if(retried)return;enc=(""+enc).toLowerCase(),retried=!0;}}function normalizeEncoding(enc){var nenc=_normalizeEncoding(enc);if("string"!=typeof nenc&&(Buffer.isEncoding===isEncoding||!isEncoding(enc)))throw new Error("Unknown encoding: "+enc);return nenc||enc}function StringDecoder(encoding){this.encoding=normalizeEncoding(encoding);var nb;switch(this.encoding){case"utf16le":this.text=utf16Text,this.end=utf16End,nb=4;break;case"utf8":this.fillLast=utf8FillLast,nb=4;break;case"base64":this.text=base64Text,this.end=base64End,nb=3;break;default:return this.write=simpleWrite,void(this.end=simpleEnd);}this.lastNeed=0,this.lastTotal=0,this.lastChar=Buffer.allocUnsafe(nb)}function utf8CheckByte(byte){if(127>=byte)return 0;return 6==byte>>5?2:14==byte>>4?3:30==byte>>3?4:2==byte>>6?-1:-2}function utf8CheckIncomplete(self,buf,i){var j=buf.length-1;if(j=c)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=buf[buf.length-2],this.lastChar[1]=buf[buf.length-1],r.slice(0,-1)}return r}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=buf[buf.length-1],buf.toString("utf16le",i,buf.length-1)}function utf16End(buf){var r=buf&&buf.length?this.write(buf):"";if(this.lastNeed){var end=this.lastTotal-this.lastNeed;return r+this.lastChar.toString("utf16le",0,end)}return r}function base64Text(buf,i){var n=(buf.length-i)%3;return 0==n?buf.toString("base64",i):(this.lastNeed=3-n,this.lastTotal=3,1==n?this.lastChar[0]=buf[buf.length-1]:(this.lastChar[0]=buf[buf.length-2],this.lastChar[1]=buf[buf.length-1]),buf.toString("base64",i,buf.length-n))}function base64End(buf){var r=buf&&buf.length?this.write(buf):"";return this.lastNeed?r+this.lastChar.toString("base64",0,3-this.lastNeed):r}function simpleWrite(buf){return buf.toString(this.encoding)}function simpleEnd(buf){return buf&&buf.length?this.write(buf):""}var Buffer=require("safe-buffer").Buffer,isEncoding=Buffer.isEncoding||function(encoding){switch(encoding=""+encoding,encoding&&encoding.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1;}};exports.StringDecoder=StringDecoder,StringDecoder.prototype.write=function(buf){if(0===buf.length)return"";var r,i;if(this.lastNeed){if(r=this.fillLast(buf),void 0===r)return"";i=this.lastNeed,this.lastNeed=0}else i=0;return i>shiftIndex,shiftIndex=(shiftIndex+5)%8,digit=digit<>8-shiftIndex,i++):(digit=31¤t>>8-(shiftIndex+5),shiftIndex=(shiftIndex+5)%8,0===shiftIndex&&i++),encoded[j]="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567".charCodeAt(digit),j++}for(i=j;i=shiftIndex?(shiftIndex=(shiftIndex+5)%8,0===shiftIndex?(plainChar|=plainDigit,decoded[plainPos]=plainChar,plainPos++,plainChar=0):plainChar|=255&plainDigit<<8-shiftIndex):(shiftIndex=(shiftIndex+5)%8,plainChar|=255&plainDigit>>>shiftIndex,decoded[plainPos]=plainChar,plainPos++,plainChar=255&plainDigit<<8-shiftIndex);else throw new Error("Invalid input - it is not base32 encoded string")}return decoded.slice(0,plainPos)}}).call(this)}).call(this,require("buffer").Buffer)},{buffer:24}],110:[function(require,module){var Buffer=require("buffer").Buffer;module.exports=function(buf){if(buf instanceof Uint8Array){if(0===buf.byteOffset&&buf.byteLength===buf.buffer.byteLength)return buf.buffer;if("function"==typeof buf.buffer.slice)return buf.buffer.slice(buf.byteOffset,buf.byteOffset+buf.byteLength)}if(Buffer.isBuffer(buf)){for(var arrayCopy=new Uint8Array(buf.length),len=buf.length,i=0;i */const debug=require("debug")("torrent-discovery"),DHT=require("bittorrent-dht/client"),EventEmitter=require("events").EventEmitter,parallel=require("run-parallel"),Tracker=require("bittorrent-tracker/client"),LSD=require("bittorrent-lsd");module.exports=class Discovery extends EventEmitter{constructor(opts){if(super(),!opts.peerId)throw new Error("Option `peerId` is required");if(!opts.infoHash)throw new Error("Option `infoHash` is required");if(!process.browser&&!opts.port)throw new Error("Option `port` is required");this.peerId="string"==typeof opts.peerId?opts.peerId:opts.peerId.toString("hex"),this.infoHash="string"==typeof opts.infoHash?opts.infoHash.toLowerCase():opts.infoHash.toString("hex"),this._port=opts.port,this._userAgent=opts.userAgent,this.destroyed=!1,this._announce=opts.announce||[],this._intervalMs=opts.intervalMs||900000,this._trackerOpts=null,this._dhtAnnouncing=!1,this._dhtTimeout=!1,this._internalDHT=!1,this._onWarning=err=>{this.emit("warning",err)},this._onError=err=>{this.emit("error",err)},this._onDHTPeer=(peer,infoHash)=>{infoHash.toString("hex")!==this.infoHash||this.emit("peer",`${peer.host}:${peer.port}`,"dht")},this._onTrackerPeer=peer=>{this.emit("peer",peer,"tracker")},this._onTrackerAnnounce=()=>{this.emit("trackerAnnounce")},this._onLSDPeer=peer=>{this.emit("peer",peer,"lsd")};const createDHT=(port,opts)=>{const dht=new DHT(opts);return dht.on("warning",this._onWarning),dht.on("error",this._onError),dht.listen(port),this._internalDHT=!0,dht};!1===opts.tracker?this.tracker=null:opts.tracker&&"object"==typeof opts.tracker?(this._trackerOpts=Object.assign({},opts.tracker),this.tracker=this._createTracker()):this.tracker=this._createTracker(),this.dht=!1===opts.dht||"function"!=typeof DHT?null:opts.dht&&"function"==typeof opts.dht.addNode?opts.dht:opts.dht&&"object"==typeof opts.dht?createDHT(opts.dhtPort,opts.dht):createDHT(opts.dhtPort),this.dht&&(this.dht.on("peer",this._onDHTPeer),this._dhtAnnounce()),this.lsd=!1===opts.lsd||"function"!=typeof LSD?null:this._createLSD()}updatePort(port){port===this._port||(this._port=port,this.dht&&this._dhtAnnounce(),this.tracker&&(this.tracker.stop(),this.tracker.destroy(()=>{this.tracker=this._createTracker()})))}complete(opts){this.tracker&&this.tracker.complete(opts)}destroy(cb){if(!this.destroyed){this.destroyed=!0,clearTimeout(this._dhtTimeout);const tasks=[];this.tracker&&(this.tracker.stop(),this.tracker.removeListener("warning",this._onWarning),this.tracker.removeListener("error",this._onError),this.tracker.removeListener("peer",this._onTrackerPeer),this.tracker.removeListener("update",this._onTrackerAnnounce),tasks.push(cb=>{this.tracker.destroy(cb)})),this.dht&&this.dht.removeListener("peer",this._onDHTPeer),this._internalDHT&&(this.dht.removeListener("warning",this._onWarning),this.dht.removeListener("error",this._onError),tasks.push(cb=>{this.dht.destroy(cb)})),this.lsd&&(this.lsd.removeListener("warning",this._onWarning),this.lsd.removeListener("error",this._onError),this.lsd.removeListener("peer",this._onLSDPeer),tasks.push(cb=>{this.lsd.destroy(cb)})),parallel(tasks,cb),this.dht=null,this.tracker=null,this.lsd=null,this._announce=null}}_createTracker(){const opts=Object.assign({},this._trackerOpts,{infoHash:this.infoHash,announce:this._announce,peerId:this.peerId,port:this._port,userAgent:this._userAgent}),tracker=new Tracker(opts);return tracker.on("warning",this._onWarning),tracker.on("error",this._onError),tracker.on("peer",this._onTrackerPeer),tracker.on("update",this._onTrackerAnnounce),tracker.setInterval(this._intervalMs),tracker.start(),tracker}_dhtAnnounce(){this._dhtAnnouncing||(debug("dht announce"),this._dhtAnnouncing=!0,clearTimeout(this._dhtTimeout),this.dht.announce(this.infoHash,this._port,err=>{this._dhtAnnouncing=!1,debug("dht announce complete"),err&&this.emit("warning",err),this.emit("dhtAnnounce"),this.destroyed||(this._dhtTimeout=setTimeout(()=>{this._dhtAnnounce()},this._intervalMs+_Mathfloor(Math.random()*this._intervalMs/5)),this._dhtTimeout.unref&&this._dhtTimeout.unref())}))}_createLSD(){const opts=Object.assign({},{infoHash:this.infoHash,peerId:this.peerId,port:this._port}),lsd=new LSD(opts);return lsd.on("warning",this._onWarning),lsd.on("error",this._onError),lsd.on("peer",this._onLSDPeer),lsd.start(),lsd}}}).call(this)}).call(this,require("_process"))},{_process:62,"bittorrent-dht/client":22,"bittorrent-lsd":22,"bittorrent-tracker/client":16,debug:33,events:25,"run-parallel":90}],112:[function(require,module){(function(Buffer){(function(){const BLOCK_LENGTH=16384;class Piece{constructor(length){this.length=length,this.missing=length,this.sources=null,this._chunks=_Mathceil(length/BLOCK_LENGTH),this._remainder=length%BLOCK_LENGTH||BLOCK_LENGTH,this._buffered=0,this._buffer=null,this._cancellations=null,this._reservations=0,this._flushed=!1}chunkLength(i){return i===this._chunks-1?this._remainder:BLOCK_LENGTH}chunkLengthRemaining(i){return this.length-i*BLOCK_LENGTH}chunkOffset(i){return i*BLOCK_LENGTH}reserve(){return this.init()?this._cancellations.length?this._cancellations.pop():this._reservations=arr.length||0>i)){var last=arr.pop();if(i","\"","`"," ","\r","\n","\t"]),autoEscape=["'"].concat(unwise),nonHostChars=["%","/","?",";","#"].concat(autoEscape),hostEndingChars=["/","?","#"],hostnamePartPattern=/^[+a-z0-9A-Z_-]{0,63}$/,unsafeProtocol={javascript:!0,"javascript:":!0},hostlessProtocol={javascript:!0,"javascript:":!0},slashedProtocol={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},querystring=require("querystring");Url.prototype.parse=function(url,parseQueryString,slashesDenoteHost){if(!util.isString(url))throw new TypeError("Parameter 'url' must be a string, not "+typeof url);var queryIndex=url.indexOf("?"),splitter=-1!==queryIndex&&queryIndexrelPath.length&&relPath.unshift(""),result.pathname=relPath.join("/")}else result.pathname=relative.pathname;if(result.search=relative.search,result.query=relative.query,result.host=relative.host||"",result.auth=relative.auth,result.hostname=relative.hostname||relative.host,result.port=relative.port,result.pathname||result.search){var p=result.pathname||"",s=result.search||"";result.path=p+s}return result.slashes=result.slashes||relative.slashes,result.href=result.format(),result}var isSourceAbs=result.pathname&&"/"===result.pathname.charAt(0),isRelAbs=relative.host||relative.pathname&&"/"===relative.pathname.charAt(0),mustEndAbs=isRelAbs||isSourceAbs||result.host&&relative.pathname,removeAllDots=mustEndAbs,srcPath=result.pathname&&result.pathname.split("/")||[],relPath=relative.pathname&&relative.pathname.split("/")||[],psychotic=result.protocol&&!slashedProtocol[result.protocol];if(psychotic&&(result.hostname="",result.port=null,result.host&&(""===srcPath[0]?srcPath[0]=result.host:srcPath.unshift(result.host)),result.host="",relative.protocol&&(relative.hostname=null,relative.port=null,relative.host&&(""===relPath[0]?relPath[0]=relative.host:relPath.unshift(relative.host)),relative.host=null),mustEndAbs=mustEndAbs&&(""===relPath[0]||""===srcPath[0])),isRelAbs)result.host=relative.host||""===relative.host?relative.host:result.host,result.hostname=relative.hostname||""===relative.hostname?relative.hostname:result.hostname,result.search=relative.search,result.query=relative.query,srcPath=relPath;else if(relPath.length)srcPath||(srcPath=[]),srcPath.pop(),srcPath=srcPath.concat(relPath),result.search=relative.search,result.query=relative.query;else if(!util.isNullOrUndefined(relative.search)){if(psychotic){result.hostname=result.host=srcPath.shift();var authInHost=!!(result.host&&0 */const{EventEmitter}=require("events"),bencode=require("bencode"),BitField=require("bitfield").default,debug=require("debug")("ut_metadata"),sha1=require("simple-sha1"),BITFIELD_GROW=1E3,PIECE_LENGTH=16384;module.exports=metadata=>{class utMetadata extends EventEmitter{constructor(wire){super(),this._wire=wire,this._fetching=!1,this._metadataComplete=!1,this._metadataSize=null,this._remainingRejects=null,this._bitfield=new BitField(0,{grow:BITFIELD_GROW}),Buffer.isBuffer(metadata)&&this.setMetadata(metadata)}onHandshake(infoHash){this._infoHash=infoHash}onExtendedHandshake(handshake){return handshake.m&&handshake.m.ut_metadata?handshake.metadata_size?"number"!=typeof handshake.metadata_size||1E7=handshake.metadata_size?this.emit("warning",new Error("Peer gave invalid metadata size")):void(this._metadataSize=handshake.metadata_size,this._numPieces=_Mathceil(this._metadataSize/PIECE_LENGTH),this._remainingRejects=2*this._numPieces,this._requestPieces()):this.emit("warning",new Error("Peer does not have metadata")):this.emit("warning",new Error("Peer does not support ut_metadata"))}onMessage(buf){let dict,trailer;try{const str=buf.toString(),trailerIndex=str.indexOf("ee")+2;dict=bencode.decode(str.substring(0,trailerIndex)),trailer=buf.slice(trailerIndex)}catch(err){return}switch(dict.msg_type){case 0:this._onRequest(dict.piece);break;case 1:this._onData(dict.piece,trailer,dict.total_size);break;case 2:this._onReject(dict.piece);}}fetch(){this._metadataComplete||(this._fetching=!0,this._metadataSize&&this._requestPieces())}cancel(){this._fetching=!1}setMetadata(metadata){if(this._metadataComplete)return!0;debug("set metadata");try{const info=bencode.decode(metadata).info;info&&(metadata=bencode.encode(info))}catch(err){}return!(this._infoHash&&this._infoHash!==sha1.sync(metadata))&&(this.cancel(),this.metadata=metadata,this._metadataComplete=!0,this._metadataSize=this.metadata.length,this._wire.extendedHandshake.metadata_size=this._metadataSize,this.emit("metadata",bencode.encode({info:bencode.decode(this.metadata)})),!0)}_send(dict,trailer){let buf=bencode.encode(dict);Buffer.isBuffer(trailer)&&(buf=Buffer.concat([buf,trailer])),this._wire.extended("ut_metadata",buf)}_request(piece){this._send({msg_type:0,piece})}_data(piece,buf,totalSize){const msg={msg_type:1,piece};"number"==typeof totalSize&&(msg.total_size=totalSize),this._send(msg,buf)}_reject(piece){this._send({msg_type:2,piece})}_onRequest(piece){if(!this._metadataComplete)return void this._reject(piece);const start=piece*PIECE_LENGTH;let end=start+PIECE_LENGTH;end>this._metadataSize&&(end=this._metadataSize);const buf=this.metadata.slice(start,end);this._data(piece,buf,this._metadataSize)}_onData(piece,buf){buf.length>PIECE_LENGTH||!this._fetching||(buf.copy(this.metadata,piece*PIECE_LENGTH),this._bitfield.set(piece),this._checkDone())}_onReject(piece){0=this._entries[this._index][this._countName]&&(this._index++,this._offset=0),this.value=this._entries[this._index]}}module.exports=class MP4Remuxer extends EventEmitter{constructor(file){super(),this._tracks=[],this._file=file,this._decoder=null,this._findMoov(0)}_findMoov(offset){this._decoder&&this._decoder.destroy();let toSkip=0;this._decoder=mp4.decode();const fileStream=this._file.createReadStream({start:offset});fileStream.pipe(this._decoder);const boxHandler=headers=>{"moov"===headers.type?(this._decoder.removeListener("box",boxHandler),this._decoder.decode(moov=>{fileStream.destroy();try{this._processMoov(moov)}catch(err){err.message=`Cannot parse mp4 file: ${err.message}`,this.emit("error",err)}})):headers.length<4096?(toSkip+=headers.length,this._decoder.ignore()):(this._decoder.removeListener("box",boxHandler),toSkip+=headers.length,fileStream.destroy(),this._decoder.destroy(),this._findMoov(offset+toSkip))};this._decoder.on("box",boxHandler)}_processMoov(moov){const traks=moov.traks;this._tracks=[],this._hasVideo=!1,this._hasAudio=!1;for(let i=0;i=stbl.stsz.entries.length)break;if(sampleInChunk++,offsetInChunk+=size,sampleInChunk>=currChunkEntry.samplesPerChunk){sampleInChunk=0,offsetInChunk=0,chunk++;const nextChunkEntry=stbl.stsc.entries[sampleToChunkIndex+1];nextChunkEntry&&chunk+1>=nextChunkEntry.firstChunk&&sampleToChunkIndex++}dts+=duration,decodingTimeEntry.inc(),presentationOffsetEntry&&presentationOffsetEntry.inc(),sync&&syncSampleIndex++}trak.mdia.mdhd.duration=0,trak.tkhd.duration=0;const defaultSampleDescriptionIndex=currChunkEntry.sampleDescriptionId,trackMoov={type:"moov",mvhd:moov.mvhd,traks:[{tkhd:trak.tkhd,mdia:{mdhd:trak.mdia.mdhd,hdlr:trak.mdia.hdlr,elng:trak.mdia.elng,minf:{vmhd:trak.mdia.minf.vmhd,smhd:trak.mdia.minf.smhd,dinf:trak.mdia.minf.dinf,stbl:{stsd:stbl.stsd,stts:empty(),ctts:empty(),stsc:empty(),stsz:empty(),stco:empty(),stss:empty()}}}}],mvex:{mehd:{fragmentDuration:moov.mvhd.duration},trexs:[{trackId:trak.tkhd.trackId,defaultSampleDescriptionIndex,defaultSampleDuration:0,defaultSampleSize:0,defaultSampleFlags:0}]}};this._tracks.push({fragmentSequence:1,trackId:trak.tkhd.trackId,timeScale:trak.mdia.mdhd.timeScale,samples,currSample:null,currTime:null,moov:trackMoov,mime})}if(0===this._tracks.length)return void this.emit("error",new Error("no playable tracks"));moov.mvhd.duration=0,this._ftyp={type:"ftyp",brand:"iso5",brandVersion:0,compatibleBrands:["iso5"]};const ftypBuf=Box.encode(this._ftyp),data=this._tracks.map(track=>{const moovBuf=Box.encode(track.moov);return{mime:track.mime,init:Buffer.concat([ftypBuf,moovBuf])}});this.emit("ready",data)}seek(time){if(!this._tracks)throw new Error("Not ready yet; wait for 'ready' event");this._fileStream&&(this._fileStream.destroy(),this._fileStream=null);let startOffset=-1;if(this._tracks.map((track,i)=>{track.outStream&&track.outStream.destroy(),track.inStream&&(track.inStream.destroy(),track.inStream=null);const outStream=track.outStream=mp4.encode(),fragment=this._generateFragment(i,time);if(!fragment)return outStream.finalize();(-1===startOffset||fragment.ranges[0].start{outStream.destroyed||outStream.box(frag.moof,err=>{if(err)return this.emit("error",err);if(!outStream.destroyed){const slicedStream=track.inStream.slice(frag.ranges);slicedStream.pipe(outStream.mediaData(frag.length,err=>{if(err)return this.emit("error",err);if(!outStream.destroyed){const nextFrag=this._generateFragment(i);return nextFrag?void writeFragment(nextFrag):outStream.finalize()}}))}})};writeFragment(fragment)}),0<=startOffset){const fileStream=this._fileStream=this._file.createReadStream({start:startOffset});this._tracks.forEach(track=>{track.inStream=new RangeSliceStream(startOffset,{highWaterMark:1e7}),fileStream.pipe(track.inStream)})}return this._tracks.map(track=>track.outStream)}_findSampleBefore(trackInd,time){const track=this._tracks[trackInd],scaledTime=_Mathfloor(track.timeScale*time);let sample=bs(track.samples,scaledTime,(sample,t)=>{const pts=sample.dts+sample.presentationOffset;return pts-t});for(-1===sample?sample=0:0>sample&&(sample=-sample-2);!track.samples[sample].sync;)sample--;return sample}_generateFragment(track,time){const currTrack=this._tracks[track];let firstSample;if(firstSample=void 0===time?currTrack.currSample:this._findSampleBefore(track,time),firstSample>=currTrack.samples.length)return null;const startDts=currTrack.samples[firstSample].dts;let totalLen=0;const ranges=[];for(var currSample=firstSample;currSample=currTrack.timeScale*1)break;totalLen+=sample.size;const currRange=ranges.length-1;0>currRange||ranges[currRange].end!==sample.offset?ranges.push({start:sample.offset,end:sample.offset+sample.size}):ranges[currRange].end+=sample.size}return currTrack.currSample=currSample,{moof:this._generateMoof(track,firstSample,currSample),ranges,length:totalLen}}_generateMoof(track,firstSample,lastSample){const currTrack=this._tracks[track],entries=[];let trunVersion=0;for(let j=firstSample;jcurrSample.presentationOffset&&(trunVersion=1),entries.push({sampleDuration:currSample.duration,sampleSize:currSample.size,sampleFlags:currSample.sync?33554432:16842752,sampleCompositionTimeOffset:currSample.presentationOffset})}const moof={type:"moof",mfhd:{sequenceNumber:currTrack.fragmentSequence++},trafs:[{tfhd:{flags:131072,trackId:currTrack.trackId},tfdt:{baseMediaDecodeTime:currTrack.samples[firstSample].dts},trun:{flags:3841,dataOffset:8,entries,version:trunVersion}}]};return moof.trafs[0].trun.dataOffset+=Box.encodingLength(moof),moof}}}).call(this)}).call(this,require("buffer").Buffer)},{"binary-search":13,buffer:24,events:25,"mp4-box-encoding":52,"mp4-stream":55,"range-slice-stream":71}],121:[function(require,module){function VideoStream(file,mediaElem,opts={}){return this instanceof VideoStream?void(this.detailedError=null,this._elem=mediaElem,this._elemWrapper=new MediaElementWrapper(mediaElem),this._waitingFired=!1,this._trackMeta=null,this._file=file,this._tracks=null,"none"!==this._elem.preload&&this._createMuxer(),this._onError=()=>{this.detailedError=this._elemWrapper.detailedError,this.destroy()},this._onWaiting=()=>{this._waitingFired=!0,this._muxer?this._tracks&&this._pump():this._createMuxer()},mediaElem.autoplay&&(mediaElem.preload="auto"),mediaElem.addEventListener("waiting",this._onWaiting),mediaElem.addEventListener("error",this._onError)):(console.warn("Don't invoke VideoStream without the 'new' keyword."),new VideoStream(file,mediaElem,opts))}const MediaElementWrapper=require("mediasource"),pump=require("pump"),MP4Remuxer=require("./mp4-remuxer");VideoStream.prototype={_createMuxer(){this._muxer=new MP4Remuxer(this._file),this._muxer.on("ready",data=>{this._tracks=data.map(trackData=>{const mediaSource=this._elemWrapper.createWriteStream(trackData.mime);mediaSource.on("error",err=>{this._elemWrapper.error(err)});const track={muxed:null,mediaSource,initFlushed:!1,onInitFlushed:null};return mediaSource.write(trackData.init,err=>{track.initFlushed=!0,track.onInitFlushed&&track.onInitFlushed(err)}),track}),(this._waitingFired||"auto"===this._elem.preload)&&this._pump()}),this._muxer.on("error",err=>{this._elemWrapper.error(err)})},_pump(){const muxed=this._muxer.seek(this._elem.currentTime,!this._tracks);this._tracks.forEach((track,i)=>{const pumpTrack=()=>{track.muxed&&(track.muxed.destroy(),track.mediaSource=this._elemWrapper.createWriteStream(track.mediaSource),track.mediaSource.on("error",err=>{this._elemWrapper.error(err)})),track.muxed=muxed[i],pump(track.muxed,track.mediaSource)};track.initFlushed?pumpTrack():track.onInitFlushed=err=>err?void this._elemWrapper.error(err):void pumpTrack()})},destroy(){this.destroyed||(this.destroyed=!0,this._elem.removeEventListener("waiting",this._onWaiting),this._elem.removeEventListener("error",this._onError),this._tracks&&this._tracks.forEach(track=>{track.muxed&&track.muxed.destroy()}),this._elem.src="")}},module.exports=VideoStream},{"./mp4-remuxer":120,mediasource:48,pump:63}],122:[function(require,module){function wrappy(fn,cb){function wrapper(){for(var args=Array(arguments.length),i=0;i */const{EventEmitter}=require("events"),concat=require("simple-concat"),createTorrent=require("create-torrent"),debug=require("debug")("webtorrent"),DHT=require("bittorrent-dht/client"),loadIPSet=require("load-ip-set"),parallel=require("run-parallel"),parseTorrent=require("parse-torrent"),path=require("path"),Peer=require("simple-peer"),randombytes=require("randombytes"),speedometer=require("speedometer"),ConnPool=require("./lib/conn-pool"),Torrent=require("./lib/torrent"),VERSION=require("./package.json").version,VERSION_STR=VERSION.replace(/\d*./g,v=>`0${v%100}`.slice(-2)).slice(0,4);class WebTorrent extends EventEmitter{constructor(opts={}){super(),this.peerId="string"==typeof opts.peerId?opts.peerId:Buffer.isBuffer(opts.peerId)?opts.peerId.toString("hex"):Buffer.from(`-WW${VERSION_STR}-`+randombytes(9).toString("base64")).toString("hex"),this.peerIdBuffer=Buffer.from(this.peerId,"hex"),this.nodeId="string"==typeof opts.nodeId?opts.nodeId:Buffer.isBuffer(opts.nodeId)?opts.nodeId.toString("hex"):randombytes(20).toString("hex"),this.nodeIdBuffer=Buffer.from(this.nodeId,"hex"),this._debugId=this.peerId.toString("hex").substring(0,7),this.destroyed=!1,this.listening=!1,this.torrentPort=opts.torrentPort||0,this.dhtPort=opts.dhtPort||0,this.tracker=opts.tracker===void 0?{}:opts.tracker,this.lsd=!1!==opts.lsd,this.torrents=[],this.maxConns=+opts.maxConns||55,this.utp=!0===opts.utp,this._debug("new webtorrent (peerId %s, nodeId %s, port %s)",this.peerId,this.nodeId,this.torrentPort),this.tracker&&("object"!=typeof this.tracker&&(this.tracker={}),opts.rtcConfig&&(console.warn("WebTorrent: opts.rtcConfig is deprecated. Use opts.tracker.rtcConfig instead"),this.tracker.rtcConfig=opts.rtcConfig),opts.wrtc&&(console.warn("WebTorrent: opts.wrtc is deprecated. Use opts.tracker.wrtc instead"),this.tracker.wrtc=opts.wrtc),global.WRTC&&!this.tracker.wrtc&&(this.tracker.wrtc=global.WRTC)),"function"==typeof ConnPool?this._connPool=new ConnPool(this):process.nextTick(()=>{this._onListening()}),this._downloadSpeed=speedometer(),this._uploadSpeed=speedometer(),!1!==opts.dht&&"function"==typeof DHT?(this.dht=new DHT(Object.assign({},{nodeId:this.nodeId},opts.dht)),this.dht.once("error",err=>{this._destroy(err)}),this.dht.once("listening",()=>{const address=this.dht.address();address&&(this.dhtPort=address.port)}),this.dht.setMaxListeners(0),this.dht.listen(this.dhtPort)):this.dht=!1,this.enableWebSeeds=!1!==opts.webSeeds;const ready=()=>{this.destroyed||(this.ready=!0,this.emit("ready"))};"function"==typeof loadIPSet&&null!=opts.blocklist?loadIPSet(opts.blocklist,{headers:{"user-agent":`WebTorrent/${VERSION} (https://webtorrent.io)`}},(err,ipSet)=>err?this.error(`Failed to load blocklist: ${err.message}`):void(this.blocked=ipSet,ready())):process.nextTick(ready)}get downloadSpeed(){return this._downloadSpeed()}get uploadSpeed(){return this._uploadSpeed()}get progress(){const torrents=this.torrents.filter(torrent=>1!==torrent.progress),downloaded=torrents.reduce((total,torrent)=>total+torrent.downloaded,0),length=torrents.reduce((total,torrent)=>total+(torrent.length||0),0)||1;return downloaded/length}get ratio(){const uploaded=this.torrents.reduce((total,torrent)=>total+torrent.uploaded,0),received=this.torrents.reduce((total,torrent)=>total+torrent.received,0)||1;return uploaded/received}get(torrentId){if(!(torrentId instanceof Torrent)){let parsed;try{parsed=parseTorrent(torrentId)}catch(err){}if(!parsed)return null;if(!parsed.infoHash)throw new Error("Invalid torrent identifier");for(const torrent of this.torrents)if(torrent.infoHash===parsed.infoHash)return torrent}else if(this.torrents.includes(torrentId))return torrentId;return null}download(torrentId,opts,ontorrent){return console.warn("WebTorrent: client.download() is deprecated. Use client.add() instead"),this.add(torrentId,opts,ontorrent)}add(torrentId,opts={},ontorrent=()=>{}){function onClose(){torrent.removeListener("_infoHash",onInfoHash),torrent.removeListener("ready",onReady),torrent.removeListener("close",onClose)}if(this.destroyed)throw new Error("client is destroyed");"function"==typeof opts&&([opts,ontorrent]=[{},opts]);const onInfoHash=()=>{if(!this.destroyed)for(const t of this.torrents)if(t.infoHash===torrent.infoHash&&t!==torrent)return void torrent._destroy(new Error(`Cannot add duplicate torrent ${torrent.infoHash}`))},onReady=()=>{this.destroyed||(ontorrent(torrent),this.emit("torrent",torrent))};this._debug("add"),opts=opts?Object.assign({},opts):{};const torrent=new Torrent(torrentId,this,opts);return this.torrents.push(torrent),torrent.once("_infoHash",onInfoHash),torrent.once("ready",onReady),torrent.once("close",onClose),torrent}seed(input,opts,onseed){if(this.destroyed)throw new Error("client is destroyed");"function"==typeof opts&&([opts,onseed]=[{},opts]),this._debug("seed"),opts=opts?Object.assign({},opts):{},opts.skipVerify=!0;const isFilePath="string"==typeof input;isFilePath&&(opts.path=path.dirname(input)),opts.createdBy||(opts.createdBy=`WebTorrent/${VERSION_STR}`);const _onseed=torrent=>{this._debug("on seed"),"function"==typeof onseed&&onseed(torrent),torrent.emit("seed"),this.emit("seed",torrent)},torrent=this.add(null,opts,torrent=>{const tasks=[cb=>isFilePath?cb():void torrent.load(streams,cb)];this.dht&&tasks.push(cb=>{torrent.once("dhtAnnounce",cb)}),parallel(tasks,err=>this.destroyed?void 0:err?torrent._destroy(err):void _onseed(torrent))});let streams;return isFileList(input)?input=Array.from(input):!Array.isArray(input)&&(input=[input]),parallel(input.map(item=>cb=>{isReadable(item)?concat(item,cb):cb(null,item)}),(err,input)=>this.destroyed?void 0:err?torrent._destroy(err):void createTorrent.parseInput(input,opts,(err,files)=>this.destroyed?void 0:err?torrent._destroy(err):void(streams=files.map(file=>file.getStream),createTorrent(input,opts,(err,torrentBuf)=>{if(!this.destroyed){if(err)return torrent._destroy(err);const existingTorrent=this.get(torrentBuf);existingTorrent?torrent._destroy(new Error(`Cannot add duplicate torrent ${existingTorrent.infoHash}`)):torrent._onTorrentId(torrentBuf)}})))),torrent}remove(torrentId,opts,cb){if("function"==typeof opts)return this.remove(torrentId,null,opts);this._debug("remove");const torrent=this.get(torrentId);if(!torrent)throw new Error(`No torrent with id ${torrentId}`);this._remove(torrentId,opts,cb)}_remove(torrentId,opts,cb){if("function"==typeof opts)return this._remove(torrentId,null,opts);const torrent=this.get(torrentId);torrent&&(this.torrents.splice(this.torrents.indexOf(torrent),1),torrent.destroy(opts,cb))}address(){return this.listening?this._connPool?this._connPool.tcpServer.address():{address:"0.0.0.0",family:"IPv4",port:0}:null}destroy(cb){if(this.destroyed)throw new Error("client already destroyed");this._destroy(null,cb)}_destroy(err,cb){this._debug("client destroy"),this.destroyed=!0;const tasks=this.torrents.map(torrent=>cb=>{torrent.destroy(cb)});this._connPool&&tasks.push(cb=>{this._connPool.destroy(cb)}),this.dht&&tasks.push(cb=>{this.dht.destroy(cb)}),parallel(tasks,cb),err&&this.emit("error",err),this.torrents=[],this._connPool=null,this.dht=null}_onListening(){if(this._debug("listening"),this.listening=!0,this._connPool){const address=this._connPool.tcpServer.address();address&&(this.torrentPort=address.port)}this.emit("listening")}_debug(){const args=[].slice.call(arguments);args[0]=`[${this._debugId}] ${args[0]}`,debug(...args)}}WebTorrent.WEBRTC_SUPPORT=Peer.WEBRTC_SUPPORT,WebTorrent.VERSION=VERSION,module.exports=WebTorrent}).call(this)}).call(this,require("_process"),"undefined"==typeof global?"undefined"==typeof self?"undefined"==typeof window?{}:window:self:global,require("buffer").Buffer)},{"./lib/conn-pool":22,"./lib/torrent":5,"./package.json":124,_process:62,"bittorrent-dht/client":22,buffer:24,"create-torrent":32,debug:33,events:25,"load-ip-set":22,"parse-torrent":60,path:26,randombytes:70,"run-parallel":90,"simple-concat":93,"simple-peer":95,speedometer:99}]},{},[125])(125)}); \ No newline at end of file