(function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var t;t="undefined"==typeof window?"undefined"==typeof global?"undefined"==typeof self?this:self:global:window,t.WebTorrent=e()}})(function(){var t=Math.abs,n=Math.pow,r=Math.floor,o=String.fromCharCode,a=Math.ceil,s=Math.max,d=Math.min,l;return function(){function s(d,e,n){function t(o,i){if(!e[o]){if(!d[o]){var l="function"==typeof require&&require;if(!i&&l)return l(o,!0);if(r)return r(o,!0);var c=new Error("Cannot find module '"+o+"'");throw c.code="MODULE_NOT_FOUND",c}var a=e[o]={exports:{}};d[o][0].call(a.exports,function(e){var r=d[o][1][e];return t(r||e)},a,a.exports,s,d,e,n)}return e[o].exports}for(var r="function"==typeof require&&require,o=0;o(this._notifying=!1,this.destroyed?void 0:t?this._destroy(t):void(n("read %s (length %s) (err %s)",e,r.length,t&&t.message),this._offset&&(r=r.slice(this._offset),this._offset=0),this._missing{e.end()}),e}const t=new f(this,e);return this._torrent.select(t._startPiece,t._endPiece,!0,()=>{t._notify()}),a(t,()=>{this._destroyed||!this._torrent.destroyed&&this._torrent.deselect(t._startPiece,t._endPiece,!0)}),t}getBuffer(e){p(this.createReadStream(),this.length,e)}getBlob(e){if("undefined"==typeof window)throw new Error("browser-only method");c(this.createReadStream(),this._getMimeType(),e)}getBlobURL(e){if("undefined"==typeof window)throw new Error("browser-only method");u(this.createReadStream(),this._getMimeType(),e)}appendTo(e,t,n){if("undefined"==typeof window)throw new Error("browser-only method");l.append(this,e,t,n)}renderTo(e,t,n){if("undefined"==typeof window)throw new Error("browser-only method");l.render(this,e,t,n)}_getMimeType(){return l.mime[i.extname(this.name).toLowerCase()]}_destroy(){this._destroyed=!0,this._torrent=null}}t.exports=h}).call(this,e("_process"))},{"./file-stream":1,_process:92,"end-of-stream":48,events:49,path:89,"readable-stream":115,"render-media":116,"stream-to-blob":168,"stream-to-blob-url":167,"stream-with-known-length-to-buffer":169}],3:[function(e,t,n){const r=e("unordered-array-remove"),o=e("debug")("webtorrent:peer"),a=e("bittorrent-protocol"),i=e("./webconn");n.createWebRTCPeer=(e,t)=>{const n=new s(e.id,"webrtc");return n.conn=e,n.swarm=t,n.conn.connected?n.onConnect():(n.conn.once("connect",()=>{n.onConnect()}),n.conn.once("error",e=>{n.destroy(e)}),n.startConnectTimeout()),n},n.createTCPIncomingPeer=e=>{const t=`${e.remoteAddress}:${e.remotePort}`,n=new s(t,"tcpIncoming");return n.conn=e,n.addr=t,n.onConnect(),n},n.createTCPOutgoingPeer=(e,t)=>{const n=new s(e,"tcpOutgoing");return n.addr=e,n.swarm=t,n},n.createWebSeedPeer=(e,t)=>{const n=new s(e,"webSeed");return n.swarm=t,n.conn=new i(e,t),n.onConnect(),n};class s{constructor(e,t){this.id=e,this.type=t,o("new %s Peer %s",t,e),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,o("Peer %s connected",this.id),clearTimeout(this.connectTimeout);const e=this.conn;e.once("end",()=>{this.destroy()}),e.once("close",()=>{this.destroy()}),e.once("finish",()=>{this.destroy()}),e.once("error",e=>{this.destroy(e)});const t=this.wire=new a;t.type=this.type,t.once("end",()=>{this.destroy()}),t.once("close",()=>{this.destroy()}),t.once("finish",()=>{this.destroy()}),t.once("error",e=>{this.destroy(e)}),t.once("handshake",(e,t)=>{this.onHandshake(e,t)}),this.startHandshakeTimeout(),e.pipe(t).pipe(e),this.swarm&&!this.sentHandshake&&this.handshake()}}onHandshake(e,t){if(!this.swarm)return;if(this.destroyed)return;if(this.swarm.destroyed)return this.destroy(new Error("swarm already destroyed"));if(e!==this.swarm.infoHash)return this.destroy(new Error("unexpected handshake info hash for this swarm"));if(t===this.swarm.peerId)return this.destroy(new Error("refusing to connect to ourselves"));o("Peer %s got handshake %s",this.id,e),clearTimeout(this.handshakeTimeout),this.retries=0;let n=this.addr;!n&&this.conn.remoteAddress&&this.conn.remotePort&&(n=`${this.conn.remoteAddress}:${this.conn.remotePort}`),this.swarm._onWire(this.wire,n);this.swarm&&!this.swarm.destroyed&&(this.sentHandshake||this.handshake())}handshake(){const e={dht:!this.swarm.private&&!!this.swarm.client.dht};this.wire.handshake(this.swarm.infoHash,this.swarm.client.peerId,e),this.sentHandshake=!0}startConnectTimeout(){clearTimeout(this.connectTimeout),this.connectTimeout=setTimeout(()=>{this.destroy(new Error("connect timeout"))},"webrtc"===this.type?25e3:5e3),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(e){if(this.destroyed)return;this.destroyed=!0,this.connected=!1,o("destroy %s (error: %s)",this.id,e&&(e.message||e)),clearTimeout(this.connectTimeout),clearTimeout(this.handshakeTimeout);const t=this.swarm,n=this.conn,a=this.wire;this.swarm=null,this.conn=null,this.wire=null,t&&a&&r(t.wires,t.wires.indexOf(a)),n&&(n.on("error",()=>{}),n.destroy()),a&&a.destroy(),t&&t.removePeer(this.id)}}},{"./webconn":6,"bittorrent-protocol":14,debug:45,"unordered-array-remove":183}],4:[function(e,t){t.exports=class{constructor(e){this._torrent=e,this._numPieces=e.pieces.length,this._pieces=Array(this._numPieces),this._onWire=e=>{this.recalculate(),this._initWire(e)},this._onWireHave=e=>{this._pieces[e]+=1},this._onWireBitfield=()=>{this.recalculate()},this._torrent.wires.forEach(e=>{this._initWire(e)}),this._torrent.on("wire",this._onWire),this.recalculate()}getRarestPiece(e){let t=[],n=1/0;for(let r=0;r{this._cleanupWireEvents(e)}),this._torrent=null,this._pieces=null,this._onWire=null,this._onWireHave=null,this._onWireBitfield=null}_initWire(e){e._onClose=()=>{this._cleanupWireEvents(e);for(let t=0;t{this.destroyed||this._onParsedTorrent(t)})):v.remote(e,(e,t)=>this.destroyed?void 0:e?this._destroy(e):void this._onParsedTorrent(t))}_onParsedTorrent(e){if(!this.destroyed){if(this._processParsedTorrent(e),!this.infoHash)return this._destroy(new Error("Malformed torrent data: No info hash"));(this.path||(this.path=L.join(Y,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(e){this._debugId=e.infoHash.toString("hex").substring(0,7),this.announce&&(e.announce=e.announce.concat(this.announce)),this.client.tracker&&r.WEBTORRENT_ANNOUNCE&&!this.private&&(e.announce=e.announce.concat(r.WEBTORRENT_ANNOUNCE)),this.urlList&&(e.urlList=e.urlList.concat(this.urlList)),U(e.announce),U(e.urlList),Object.assign(this,e),this.magnetURI=v.toMagnetURI(e),this.torrentFile=v.toTorrentFile(e)}_onListening(){if(this.discovery||this.destroyed)return;let e=this.client.tracker;e&&(e=Object.assign({},this.client.tracker,{getAnnounceOpts:()=>{const e={uploaded:this.uploaded,downloaded:this.downloaded,left:s(this.length-this.downloaded,0)};return this.client.tracker.getAnnounceOpts&&Object.assign(e,this.client.tracker.getAnnounceOpts()),this._getAnnounceOpts&&Object.assign(e,this._getAnnounceOpts()),e}})),this.discovery=new g({infoHash:this.infoHash,announce:this.announce,peerId:this.client.peerId,dht:!this.private&&this.client.dht,tracker:e,port:this.client.torrentPort,userAgent:K}),this.discovery.on("error",e=>{this._destroy(e)}),this.discovery.on("peer",e=>{"string"==typeof e&&this.done||this.addPeer(e)}),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",e=>{this.emit("warning",e)}),this.info?this._onMetadata(this):this.xs&&this._getMetadataFromServer()}_getMetadataFromServer(){function e(e,n){function r(r,o,a){if(t.destroyed)return n(null);if(t.metadata)return n(null);if(r)return t.emit("warning",new Error(`http error from xs param: ${e}`)),n(null);if(200!==o.statusCode)return t.emit("warning",new Error(`non-200 status code ${o.statusCode} from xs param: ${e}`)),n(null);let i;try{i=v(a)}catch(e){}return i?i.infoHash===t.infoHash?void(t._onMetadata(i),n(null)):(t.emit("warning",new Error(`got torrent file with incorrect info hash from xs param: ${e}`)),n(null)):(t.emit("warning",new Error(`got invalid torrent file from xs param: ${e}`)),n(null))}if(0!==e.indexOf("http://")&&0!==e.indexOf("https://"))return t.emit("warning",new Error(`skipping non-http xs param: ${e}`)),n(null);let o;try{o=y.concat({url:e,method:"GET",headers:{"user-agent":K}},r)}catch(r){return t.emit("warning",new Error(`skipping invalid url xs param: ${e}`)),n(null)}t._xsRequests.push(o)}const t=this,n=Array.isArray(this.xs)?this.xs:[this.xs],r=n.map(t=>n=>{e(t,n)});E(r)}_onMetadata(e){if(this.metadata||this.destroyed)return;this._debug("got metadata"),this._xsRequests.forEach(e=>{e.abort()}),this._xsRequests=[];let t;if(e&&e.infoHash)t=e;else try{t=v(e)}catch(e){return this._destroy(e)}if(this._processParsedTorrent(t),this.metadata=this.torrentFile,this.client.enableWebSeeds&&this.urlList.forEach(e=>{this.addWebSeed(e)}),this._rarityMap=new F(this),this.store=new w(new this._store(this.pieceLength,{torrent:{infoHash:this.infoHash},files:this.files.map(e=>({path:L.join(this.path,e.path),length:e.length,offset:e.offset})),length:this.length,name:this.infoHash})),this.files=this.files.map(e=>new j(this,e)),this.so){const e=O.parse(this.so);this.files.forEach((t,n)=>{e.includes(n)&&this.files[n].select(!0)})}else 0!==this.pieces.length&&this.select(0,this.pieces.length-1,!1);if(this._hashes=this.pieces,this.pieces=this.pieces.map((e,t)=>{const n=t===this.pieces.length-1?this.lastPieceLength:this.pieceLength;return new I(n)}),this._reservations=this.pieces.map(()=>[]),this.bitfield=new f(this.pieces.length),this.wires.forEach(e=>{e.ut_metadata&&e.ut_metadata.setMetadata(this.metadata),this._onWireWithMetadata(e)}),this.skipVerify)this._markAllVerified(),this._onStore();else{const e=e=>e?this._destroy(e):void(this._debug("done verifying"),this._onStore());this._debug("verifying existing torrent data"),this._fileModtimes&&this._store===i?this.getFileModtimes((t,n)=>{if(t)return this._destroy(t);const r=this.files.map((e,t)=>n[t]===this._fileModtimes[t]).every(e=>e);r?(this._markAllVerified(),this._onStore()):this._verifyPieces(e)}):this._verifyPieces(e)}this.emit("metadata")}getFileModtimes(e){const t=[];C(this.files.map((e,n)=>r=>{b.stat(L.join(this.path,e.path),(e,o)=>e&&"ENOENT"!==e.code?r(e):void(t[n]=o&&o.mtime.getTime(),r(null)))}),z,n=>{this._debug("done getting file modtimes"),e(n,t)})}_verifyPieces(e){C(this.pieces.map((e,t)=>e=>this.destroyed?e(new Error("torrent is destroyed")):void this.store.get(t,(r,o)=>this.destroyed?e(new Error("torrent is destroyed")):r?n.nextTick(e,null):void R(o,n=>{if(this.destroyed)return e(new Error("torrent is destroyed"));if(n===this._hashes[t]){if(!this.pieces[t])return;this._debug("piece verified %s",t),this._markVerified(t)}else this._debug("piece invalid %s",t);e(null)}))),z,e)}rescanFiles(e){if(this.destroyed)throw new Error("torrent is destroyed");e||(e=u),this._verifyPieces(t=>t?(this._destroy(t),e(t)):void(this._checkDone(),e(null)))}_markAllVerified(){for(let e=0;e{e.abort()}),this._rarityMap&&this._rarityMap.destroy(),this._peers)this.removePeer(e);this.files.forEach(e=>{e instanceof j&&e._destroy()});const n=this._servers.map(e=>t=>{e.destroy(t)});this.discovery&&n.push(e=>{this.discovery.destroy(e)}),this.store&&n.push(e=>{this.store.close(e)}),E(n,t),e&&(0===this.listenerCount("error")?this.client.emit("error",e):this.emit("error",e)),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(t){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 e;if("string"==typeof t){let n;try{n=p(t)}catch(n){return this._debug("ignoring peer: invalid %s",t),this.emit("invalidPeer",t),!1}e=n[0]}else"string"==typeof t.remoteAddress&&(e=t.remoteAddress);if(e&&this.client.blocked.contains(e))return this._debug("ignoring peer: blocked %s",t),"string"!=typeof t&&t.destroy(),this.emit("blockedPeer",t),!1}const n=!!this._addPeer(t);return n?this.emit("peer",t):this.emit("invalidPeer",t),n}_addPeer(e){if(this.destroyed)return"string"!=typeof e&&e.destroy(),null;if("string"==typeof e&&!this._validAddr(e))return this._debug("ignoring peer: invalid %s",e),null;const t=e&&e.id||e;if(this._peers[t])return this._debug("ignoring peer: duplicate (%s)",t),"string"!=typeof e&&e.destroy(),null;if(this.paused)return this._debug("ignoring peer: torrent is paused"),"string"!=typeof e&&e.destroy(),null;this._debug("add peer %s",t);let n;return n="string"==typeof e?N.createTCPOutgoingPeer(e,this):N.createWebRTCPeer(e,this),this._peers[n.id]=n,this._peersLength+=1,"string"==typeof e&&(this._queue.push(n),this._drain()),n}addWebSeed(e){if(this.destroyed)throw new Error("torrent is destroyed");if(!/^https?:\/\/.+/.test(e))return this.emit("warning",new Error(`ignoring invalid web seed: ${e}`)),void this.emit("invalidPeer",e);if(this._peers[e])return this.emit("warning",new Error(`ignoring duplicate web seed: ${e}`)),void this.emit("invalidPeer",e);this._debug("add web seed %s",e);const t=N.createWebSeedPeer(e,this);this._peers[t.id]=t,this._peersLength+=1,this.emit("peer",e)}_addIncomingPeer(e){return this.destroyed?e.destroy(new Error("torrent is destroyed")):this.paused?e.destroy(new Error("torrent is paused")):void(this._debug("add incoming peer %s",e.id),this._peers[e.id]=e,this._peersLength+=1)}removePeer(e){const t=e&&e.id||e;e=this._peers[t];e&&(this._debug("removePeer %s",t),delete this._peers[t],this._peersLength-=1,e.destroy(),this._drain())}select(e,t,n,r){if(this.destroyed)throw new Error("torrent is destroyed");if(0>e||tt.priority-e.priority),this._updateSelections()}deselect(e,t,n){if(this.destroyed)throw new Error("torrent is destroyed");n=+n||0,this._debug("deselect %s-%s (priority %s)",e,t,n);for(let r=0;r{this.destroyed||(this.received+=e,this._downloadSpeed(e),this.client._downloadSpeed(e),this.emit("download",e),this.client.emit("download",e))}),e.on("upload",e=>{this.destroyed||(this.uploaded+=e,this._uploadSpeed(e),this.client._uploadSpeed(e),this.emit("upload",e),this.client.emit("upload",e))}),this.wires.push(e),t){const n=p(t);e.remoteAddress=n[0],e.remotePort=n[1]}this.client.dht&&this.client.dht.listening&&e.on("port",n=>this.destroyed||this.client.dht.destroyed?void 0:e.remoteAddress?0===n||65536{this._debug("wire timeout (%s)",t),e.destroy()}),e.setTimeout(3e4,!0),e.setKeepAlive(!0),e.use(P(this.metadata)),e.ut_metadata.on("warning",e=>{this._debug("ut_metadata warning: %s",e.message)}),this.metadata||(e.ut_metadata.on("metadata",e=>{this._debug("got metadata via ut_metadata"),this._onMetadata(e)}),e.ut_metadata.fetch()),"function"!=typeof M||this.private||(e.use(M()),e.ut_pex.on("peer",e=>{this.done||(this._debug("ut_pex: got peer: %s (from %s)",e,t),this.addPeer(e))}),e.ut_pex.on("dropped",e=>{const n=this._peers[e];n&&!n.connected&&(this._debug("ut_pex: dropped peer: %s (from %s)",e,t),this.removePeer(e))}),e.once("close",()=>{e.ut_pex.reset()})),this.emit("wire",e,t),this.metadata&&n.nextTick(()=>{this._onWireWithMetadata(e)})}_onWireWithMetadata(e){let t=null;const n=()=>{this.destroyed||e.destroyed||(this._numQueued>2*(this._numConns-this.numPeers)&&e.amInterested?e.destroy():(t=setTimeout(n,H),t.unref&&t.unref()))};let r;const o=()=>{if(e.peerPieces.buffer.length===this.bitfield.buffer.length){for(r=0;r{o(),this._update()}),e.on("have",()=>{o(),this._update()}),e.once("interested",()=>{e.unchoke()}),e.once("close",()=>{clearTimeout(t)}),e.on("choke",()=>{clearTimeout(t),t=setTimeout(n,H),t.unref&&t.unref()}),e.on("unchoke",()=>{clearTimeout(t),this._update()}),e.on("request",(t,n,r,o)=>r>131072?e.destroy():void(this.pieces[t]||this.store.get(t,{offset:n,length:r},o))),e.bitfield(this.bitfield),e.uninterested(),e.peerExtensions.dht&&this.client.dht&&this.client.dht.listening&&e.port(this.client.dht.address().port),"webSeed"!==e.type&&(t=setTimeout(n,H),t.unref&&t.unref()),e.isSeeder=!1,o()}_updateSelections(){!this.ready||this.destroyed||(n.nextTick(()=>{this._gcSelections()}),this._updateInterest(),this._update())}_gcSelections(){for(let e=0;e{let t=!1;for(let n=0;na>=t&&a<=n&&!(a in r)&&e.peerPieces.get(a)&&(!o||o(a))}function n(){const t=e.downloadSpeed()||1;if(t>D)return()=>!0;const n=s(1,e.requests.length)*I.BLOCK_LENGTH/t;let r=10,o=0;return e=>{if(!r||d.bitfield.get(e))return!0;for(let a=d.pieces[e].missing;o=c)return!0;const a=n();for(let n=0;ns));){for(;d._request(e,s,d._critical[s]||o););if(e.requests.lengtho));){if(d._request(e,o,!1))return;i[o]=!0,s+=1}}else for(o=r.to;o>=r.from+r.offset;--o)if(e.peerPieces.get(o)&&d._request(e,o,!1))return}}();const l=o(e,.5);if(e.requests.length>=l)return;const c=o(e,W);a(!1)||a(!0)}_rechoke(){if(!this.ready)return;0{t.isSeeder||t===this._rechokeOptimisticWire||e.push({wire:t,downloadSpeed:t.downloadSpeed(),uploadSpeed:t.uploadSpeed(),salt:Math.random(),isChoked:!0})}),e.sort(function(e,t){return e.downloadSpeed===t.downloadSpeed?e.uploadSpeed===t.uploadSpeed?e.wire.amChoking===t.wire.amChoking?e.salt-t.salt:e.wire.amChoking?1:-1:t.uploadSpeed-e.uploadSpeed:t.downloadSpeed-e.downloadSpeed});let t=0,n=0;for(;ne.wire.peerInterested),r=t[c(t.length)];r&&(r.isChoked=!1,this._rechokeOptimisticWire=r.wire,this._rechokeOptimisticTime=2)}e.forEach(e=>{e.wire.amChoking!==e.isChoked&&(e.isChoked?e.wire.choke():e.wire.unchoke())})}_hotswap(e,t){const n=e.downloadSpeed();if(n=D||2*i>n||i>r||(a=t,r=i)}if(!a)return!1;for(s=0;s{c._update()})}const c=this,u=e.requests.length,p="webSeed"===e.type;if(c.bitfield.get(t))return!1;const f=p?d(l(e,W,c.pieceLength),c.maxWebConns):o(e,W);if(u>=f)return!1;const h=c.pieces[t];let m=p?h.reserveRemaining():h.reserve();if(-1===m&&a&&c._hotswap(e,t)&&(m=p?h.reserveRemaining():h.reserve()),-1===m)return!1;let g=c._reservations[t];g||(g=c._reservations[t]=[]);let _=g.indexOf(null);-1===_&&(_=g.length),g[_]=e;const b=h.chunkOffset(m),y=p?h.chunkLengthRemaining(m):h.chunkLength(m);return e.request(t,b,y,function n(r,o){if(c.destroyed)return;if(!c.ready)return c.once("ready",()=>{n(r,o)});if(g[_]===e&&(g[_]=null),h!==c.pieces[t])return s();if(r)return c._debug("error getting piece %s (offset: %s length: %s) from %s: %s",t,b,y,`${e.remoteAddress}:${e.remotePort}`,r.message),p?h.cancelRemaining(m):h.cancel(m),void s();if(c._debug("got piece %s (offset: %s length: %s) from %s",t,b,y,`${e.remoteAddress}:${e.remotePort}`),!h.set(m,o,e))return s();const a=h.flush();R(a,e=>{if(!c.destroyed){if(e===c._hashes[t]){if(!c.pieces[t])return;c._debug("piece verified %s",t),c.pieces[t]=null,c._reservations[t]=null,c.bitfield.set(t,!0),c.store.put(t,a),c.wires.forEach(e=>{e.have(t)}),c._checkDone()&&!c.destroyed&&c.discovery.complete()}else c.pieces[t]=new I(h.length),c.emit("warning",new Error(`Piece ${t} failed verification`));s()}})}),!0}_checkDone(){if(this.destroyed)return;this.files.forEach(e=>{if(!e.done){for(let t=e._startPiece;t<=e._endPiece;++t)if(!this.bitfield.get(t))return;e.done=!0,e.emit("done"),this._debug(`file done: ${e.name}`)}});let e=!0;for(let t=0;t{this.load(e,t)});Array.isArray(e)||(e=[e]),t||(t=u);const n=new k(e),r=new h(this.store,this.pieceLength);T(n,r,e=>e?t(e):void(this._markAllVerified(),this._checkDone(),t(null)))}createServer(e){if("function"!=typeof q)throw new Error("node.js-only method");if(this.destroyed)throw new Error("torrent is destroyed");const t=new q(this,e);return this._servers.push(t),t}pause(){this.destroyed||(this._debug("pause"),this.paused=!0)}resume(){this.destroyed||(this._debug("resume"),this.paused=!1,this._drain())}_debug(){const e=[].slice.call(arguments);e[0]=`[${this.client._debugId}] [${this._debugId}] ${e[0]}`,m(...e)}_drain(){if(this._debug("_drain numConns %s maxConns %s",this._numConns,this.client.maxConns),"function"!=typeof x.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 e=this._queue.shift();if(!e)return;this._debug("tcp connect attempt to %s",e.addr);const t=p(e.addr),n={host:t[0],port:t[1]},r=e.conn=x.connect(n);r.once("connect",()=>{e.onConnect()}),r.once("error",t=>{e.destroy(t)}),e.startConnectTimeout(),r.on("close",()=>{if(!this.destroyed){if(e.retries>=V.length)return void this._debug("conn %s closed: will not re-add (max %s attempts)",e.addr,V.length);const t=V[e.retries];this._debug("conn %s closed: will re-add to queue in %sms (attempt %s)",e.addr,t,e.retries+1);const n=setTimeout(()=>{const t=this._addPeer(e.addr);t&&(t.retries=e.retries+1)},t);n.unref&&n.unref()}})}_validAddr(e){let t;try{t=p(e)}catch(t){return!1}const n=t[0],r=t[1];return 0r&&("127.0.0.1"!==n||r!==this.client.torrentPort)}}t.exports=$}).call(this,e("_process"),"undefined"==typeof global?"undefined"==typeof self?"undefined"==typeof window?{}:window:self:global)},{"../package.json":193,"./file":2,"./peer":3,"./rarity-map":4,"./server":33,_process:92,"addr-to-ip-port":7,bitfield:13,"chunk-store-stream/write":41,debug:45,events:49,fs:34,"fs-chunk-store":76,"immediate-chunk-store":66,multistream:84,net:33,os:33,"parse-numeric-range":87,"parse-torrent":88,path:89,pump:93,"random-iterate":98,"run-parallel":119,"run-parallel-limit":118,"simple-get":123,"simple-sha1":136,speedometer:151,"torrent-discovery":176,"torrent-piece":179,uniq:182,ut_metadata:186,ut_pex:33}],6:[function(e,t){const n=e("bitfield"),r=e("safe-buffer").Buffer,o=e("debug")("webtorrent:webconn"),a=e("simple-get"),i=e("simple-sha1"),l=e("bittorrent-protocol"),c=e("../package.json").version;t.exports=class extends l{constructor(e,t){super(),this.url=e,this.webPeerId=i.sync(e),this._torrent=t,this._init()}_init(){this.setKeepAlive(!0),this.once("handshake",e=>{if(this.destroyed)return;this.handshake(e,this.webPeerId);const t=this._torrent.pieces.length,r=new n(t);for(let n=0;n<=t;n++)r.set(n,!0);this.bitfield(r)}),this.once("interested",()=>{o("interested"),this.unchoke()}),this.on("uninterested",()=>{o("uninterested")}),this.on("choke",()=>{o("choke")}),this.on("unchoke",()=>{o("unchoke")}),this.on("bitfield",()=>{o("bitfield")}),this.on("request",(e,t,n,r)=>{o("request pieceIndex=%d offset=%d length=%d",e,t,n),this.httpRequest(e,t,n,r)})}httpRequest(e,t,n,i){const l=e*this._torrent.pieceLength,u=l+t,p=u+n-1,f=this._torrent.files;let h;if(1>=f.length)h=[{url:this.url,start:u,end:p}];else{const e=f.filter(e=>e.offset<=p&&e.offset+e.length>u);if(1>e.length)return i(new Error("Could not find file corresponnding to web seed range request"));h=e.map(e=>{const t=e.offset+e.length-1,n=this.url+("/"===this.url[this.url.length-1]?"":"/")+e.path;return{url:n,fileOffsetInRange:s(e.offset-u,0),start:s(u-e.offset,0),end:d(t,p-e.offset)}})}let m=0,g=!1,_;1{function s(e,t){return 200>e.statusCode||300<=e.statusCode?(g=!0,i(new Error(`Unexpected HTTP status code ${e.statusCode}`))):void(o("Got data of length %d",t.length),1===h.length?i(null,t):(t.copy(_,r.fileOffsetInRange),++m===h.length&&i(null,_)))}const d=r.url,l=r.start,u=r.end;o("Requesting url=%s pieceIndex=%d offset=%d length=%d start=%d end=%d",d,e,t,n,l,u);const p={url:d,method:"GET",headers:{"user-agent":`WebTorrent/${c} (https://webtorrent.io)`,range:`bytes=${l}-${u}`}};a.concat(p,(e,t,n)=>g?void 0:e?"undefined"==typeof window||d.startsWith(`${window.location.origin}/`)?(g=!0,i(e)):a.head(d,(t,n)=>g?void 0:t?(g=!0,i(t)):200>n.statusCode||300<=n.statusCode?(g=!0,i(new Error(`Unexpected HTTP status code ${n.statusCode}`))):n.url===d?(g=!0,i(e)):void(p.url=n.url,a.concat(p,(e,t,n)=>g?void 0:e?(g=!0,i(e)):void s(t,n)))):void s(t,n))})}destroy(){super.destroy(),this._torrent=null}}},{"../package.json":193,bitfield:13,"bittorrent-protocol":14,debug:45,"safe-buffer":121,"simple-get":123,"simple-sha1":136}],7:[function(e,t){const n=/^\[?([^\]]+)\]?:(\d+)$/;let r={},o=0;t.exports=function(e){if(1e5===o&&t.exports.reset(),!r[e]){const t=n.exec(e);if(!t)throw new Error(`invalid addr: ${e}`);r[e]=[t[1],+t[2]],o+=1}return r[e]},t.exports.reset=function(){r={},o=0}},{}],8:[function(e,t,n){'use strict';function r(e){var t=e.length;if(0>16,s[d++]=255&f>>8,s[d++]=255&f;return 2===a&&(f=u[e.charCodeAt(c)]<<2|u[e.charCodeAt(c+1)]>>4,s[d++]=255&f),1===a&&(f=u[e.charCodeAt(c)]<<10|u[e.charCodeAt(c+1)]<<4|u[e.charCodeAt(c+2)]>>2,s[d++]=255&f>>8,s[d++]=255&f),s}function s(e){return c[63&e>>18]+c[63&e>>12]+c[63&e>>6]+c[63&e]}function d(e,t,n){for(var r=[],o=t,a;os?s:a+o));return 1===n?(l=e[t-1],r.push(c[l>>2]+c[63&l<<4]+"==")):2===n&&(l=(e[t-2]<<8)+e[t-1],r.push(c[l>>10]+c[63&l>>4]+c[63&l<<2]+"=")),r.join("")}n.byteLength=function(e){var t=r(e),n=t[0],o=t[1];return 3*(n+o)/4-o},n.toByteArray=a,n.fromByteArray=l;for(var c=[],u=[],p="undefined"==typeof Uint8Array?Array:Uint8Array,f="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",h=0,m=f.length;hs&&48<=s){r=10*r+(s-48);continue}if(a!==t||43!==s){if(a===t&&45===s){o=-1;continue}if(46===s)break;throw new Error("not a number: buffer["+a+"] = "+s)}}return r*o}function r(e,t,n,o){return null==e||0===e.length?null:("number"!=typeof t&&null==o&&(o=t,t=void 0),"number"!=typeof n&&null==o&&(o=n,n=void 0),r.position=0,r.encoding=o||null,r.data=a.isBuffer(e)?e.slice(t,n):a.from(e),r.bytes=r.data.length,r.next())}var a=e("safe-buffer").Buffer;const i=101;r.bytes=0,r.position=0,r.data=null,r.encoding=null,r.next=function(){switch(r.data[r.position]){case 100:return r.dictionary();case 108:return r.list();case 105:return r.integer();default:return r.buffer();}},r.find=function(e){for(var t=r.position,n=r.data.length,a=r.data;tr||r>=e.length)throw new RangeError("invalid lower bound");if(void 0===o)o=e.length-1;else if(o|=0,o=e.length)throw new RangeError("invalid upper bound");for(;r<=o;)if(a=r+(o-r>>1),i=+n(e[a],t,a,e),0>i)r=a+1;else if(0>3;return 0!=e%8&&t++,t}var o="undefined"==typeof e?Uint8Array:e;n.prototype.get=function(e){var t=e>>3;return t>e%8)},n.prototype.set=function(e,t){var n=e>>3;t||1===arguments.length?(this.buffer.length>e%8):n>e%8))},n.prototype._grow=function(e){if(this.buffer.length{this.keepAlive()},55e3))}setTimeout(e,t){this._debug("setTimeout ms=%d unref=%s",e,t),this._clearTimeout(),this._timeoutMs=e,this._timeoutUnref=!!t,this._updateTimeout()}destroy(){this.destroyed||(this.destroyed=!0,this._debug("destroy"),this.emit("close"),this.end())}end(...e){this._debug("end"),this._onUninterested(),this._onChoke(),super.end(...e)}use(e){function t(){}const n=e.prototype.name;if(!n)throw new Error("Extension class requires a \"name\" property on the prototype");this._debug("use extension.name=%s",n);const r=this._nextExt,o=new e(this);"function"!=typeof o.onHandshake&&(o.onHandshake=t),"function"!=typeof o.onExtendedHandshake&&(o.onExtendedHandshake=t),"function"!=typeof o.onMessage&&(o.onMessage=t),this.extendedMapping[r]=n,this._ext[n]=o,this[n]=o,this._nextExt+=1}keepAlive(){this._debug("keep-alive"),this._push(u)}handshake(e,t,r){let o,a;if("string"==typeof e?(e=e.toLowerCase(),o=n.from(e,"hex")):(o=e,e=o.toString("hex")),"string"==typeof t?a=n.from(t,"hex"):(a=t,t=a.toString("hex")),20!==o.length||20!==a.length)throw new Error("infoHash and peerId MUST have length 20");this._debug("handshake i=%s p=%s exts=%o",e,t,r);const i=n.from(g);i[5]|=16,r&&r.dht&&(i[7]|=1),this._push(n.concat([c,i,o,a])),this._handshakeSent=!0,this.peerExtensions.extended&&!this._extendedHandshakeSent&&this._sendExtendedHandshake()}_sendExtendedHandshake(){const e=Object.assign({},this.extendedHandshake);for(const t in e.m={},this.extendedMapping){const n=this.extendedMapping[t];e.m[n]=+t}this.extended(0,o.encode(e)),this._extendedHandshakeSent=!0}choke(){if(!this.amChoking){for(this.amChoking=!0,this._debug("choke");this.peerRequests.length;)this.peerRequests.pop();this._push(p)}}unchoke(){this.amChoking&&(this.amChoking=!1,this._debug("unchoke"),this._push(f))}interested(){this.amInterested||(this.amInterested=!0,this._debug("interested"),this._push(h))}uninterested(){this.amInterested&&(this.amInterested=!1,this._debug("uninterested"),this._push(m))}have(e){this._debug("have %d",e),this._message(4,[e],null)}bitfield(e){this._debug("bitfield"),n.isBuffer(e)||(e=e.buffer),this._message(5,[],e)}request(e,t,n,r){return r||(r=()=>{}),this._finished?r(new Error("wire is closed")):this.peerChoking?r(new Error("peer is choking")):void(this._debug("request index=%d offset=%d length=%d",e,t,n),this.requests.push(new b(e,t,n,r)),this._updateTimeout(),this._message(6,[e,t,n],null))}piece(e,t,n){this._debug("piece index=%d offset=%d",e,t),this.uploaded+=n.length,this.uploadSpeed(n.length),this.emit("upload",n.length),this._message(7,[e,t],n)}cancel(e,t,n){this._debug("cancel index=%d offset=%d length=%d",e,t,n),this._callback(this._pull(this.requests,e,t,n),new Error("request was cancelled"),null),this._message(8,[e,t,n],null)}port(e){this._debug("port %d",e);const t=n.from(_);t.writeUInt16BE(e,5),this._push(t)}extended(e,t){if(this._debug("extended ext=%s",e),"string"==typeof e&&this.peerExtendedMapping[e]&&(e=this.peerExtendedMapping[e]),"number"==typeof e){const r=n.from([e]),a=n.isBuffer(t)?t:o.encode(t);this._message(20,[],n.concat([r,a]))}else throw new Error(`Unrecognized extension: ${e}`)}_read(){}_message(e,t,r){const o=r?r.length:0,a=n.allocUnsafe(5+4*t.length);a.writeUInt32BE(a.length+o-4,0),a[4]=e;for(let n=0;nr===this._pull(this.peerRequests,e,t,n)?o?this._debug("error satisfying request index=%d offset=%d length=%d (%s)",e,t,n,o.message):void this.piece(e,t,a):void 0;var r=new b(e,t,n,o);this.peerRequests.push(r),this.emit("request",e,t,n,o)}}_onPiece(e,t,n){this._debug("got piece index=%d offset=%d",e,t),this._callback(this._pull(this.requests,e,t,n.length),null,n),this.downloaded+=n.length,this.downloadSpeed(n.length),this.emit("download",n.length),this.emit("piece",e,t,n)}_onCancel(e,t,n){this._debug("got cancel index=%d offset=%d length=%d",e,t,n),this._pull(this.peerRequests,e,t,n),this.emit("cancel",e,t,n)}_onPort(e){this._debug("got port %d",e),this.emit("port",e)}_onExtended(e,t){if(0===e){let e;try{e=o.decode(t)}catch(e){this._debug("ignoring invalid extended handshake: %s",e.message||e)}if(!e)return;this.peerExtendedHandshake=e;if("object"==typeof e.m)for(var n in e.m)this.peerExtendedMapping[n]=+e.m[n].toString();for(n in this._ext)this.peerExtendedMapping[n]&&this._ext[n].onExtendedHandshake(this.peerExtendedHandshake);this._debug("got extended handshake"),this.emit("extended","handshake",this.peerExtendedHandshake)}else this.extendedMapping[e]&&(e=this.extendedMapping[e],this._ext[e]&&this._ext[e].onMessage(t)),this._debug("got extended message ext=%s",e),this.emit("extended",e,t)}_onTimeout(){this._debug("request timed out"),this._callback(this.requests.shift(),new Error("request has timed out"),null),this.emit("timeout")}_write(e,t,r){for(this._bufferSize+=e.length,this._buffer.push(e);this._bufferSize>=this._parserSize;){const e=1===this._buffer.length?this._buffer[0]:n.concat(this._buffer);this._bufferSize-=this._parserSize,this._buffer=this._bufferSize?[e.slice(this._parserSize)]:[],this._parser(e.slice(0,this._parserSize))}r(null)}_callback(e,t,n){e&&(this._clearTimeout(),!this.peerChoking&&!this._finished&&this._updateTimeout(),e.callback(t,n))}_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(e,t){this._parserSize=e,this._parser=t}_onMessageLength(e){const t=e.readUInt32BE(0);0{const t=e.readUInt8(0);this._parse(t+48,e=>{const n=e.slice(0,t);return"BitTorrent protocol"===n.toString()?void(e=e.slice(t),this._onHandshake(e.slice(8,28),e.slice(28,48),{dht:!!(1&e[7]),extended:!!(16&e[5])}),this._parse(4,this._onMessageLength)):(this._debug("Error: wire not speaking BitTorrent protocol (%s)",n.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(...e){e[0]=`[${this._debugId}] ${e[0]}`,i(...e)}_pull(e,t,n,o){for(let a=0;a>3;return 0!=e%8&&t++,t}"undefined"!=typeof t&&(t.exports=class{constructor(e=0,t){const r=null!=t&&t.grow;this.grow=r&&isFinite(r)&&n(r)||r||0,this.buffer="number"==typeof e?new Uint8Array(n(e)):e}get(e){const t=e>>3;return t>e%8)}set(e,t=!0){const n=e>>3;if(t){if(this.buffer.length>e%8}else n>e%8))}})},{}],16:[function(e,t){(function(n){const{Buffer:r}=e("safe-buffer"),o=e("debug")("bittorrent-tracker:client"),a=e("events"),i=e("once"),s=e("run-parallel"),d=e("simple-peer"),l=e("uniq"),c=e("url"),u=e("./lib/common"),p=e("./lib/client/http-tracker"),f=e("./lib/client/udp-tracker"),h=e("./lib/client/websocket-tracker");class m extends a{constructor(e={}){if(super(),!e.peerId)throw new Error("Option `peerId` is required");if(!e.infoHash)throw new Error("Option `infoHash` is required");if(!e.announce)throw new Error("Option `announce` is required");if(!n.browser&&!e.port)throw new Error("Option `port` is required");this.peerId="string"==typeof e.peerId?e.peerId:e.peerId.toString("hex"),this._peerIdBuffer=r.from(this.peerId,"hex"),this._peerIdBinary=this._peerIdBuffer.toString("binary"),this.infoHash="string"==typeof e.infoHash?e.infoHash.toLowerCase():e.infoHash.toString("hex"),this._infoHashBuffer=r.from(this.infoHash,"hex"),this._infoHashBinary=this._infoHashBuffer.toString("binary"),o("new client %s",this.infoHash),this.destroyed=!1,this._port=e.port,this._getAnnounceOpts=e.getAnnounceOpts,this._rtcConfig=e.rtcConfig,this._userAgent=e.userAgent,this._wrtc="function"==typeof e.wrtc?e.wrtc():e.wrtc;let t="string"==typeof e.announce?[e.announce]:null==e.announce?[]:e.announce;t=t.map(e=>(e=e.toString(),"/"===e[e.length-1]&&(e=e.substring(0,e.length-1)),e)),t=l(t);const a=!1!==this._wrtc&&(!!this._wrtc||d.WEBRTC_SUPPORT),i=e=>{n.nextTick(()=>{this.emit("warning",e)})};this._trackers=t.map(e=>{const t=c.parse(e),n=t.port;if(0>n||65535{e.setInterval()})}stop(e){o("send `stop`"),e=this._defaultAnnounceOpts(e),e.event="stopped",this._announce(e)}complete(e){o("send `complete`"),e||(e={}),e=this._defaultAnnounceOpts(e),e.event="completed",this._announce(e)}update(e){o("send `update`"),e=this._defaultAnnounceOpts(e),e.event&&delete e.event,this._announce(e)}_announce(e){this._trackers.forEach(t=>{t.announce(e)})}scrape(e){o("send `scrape`"),e||(e={}),this._trackers.forEach(t=>{t.scrape(e)})}setInterval(e){o("setInterval %d",e),this._trackers.forEach(t=>{t.setInterval(e)})}destroy(e){if(!this.destroyed){this.destroyed=!0,o("destroy");const t=this._trackers.map(e=>t=>{e.destroy(t)});s(t,e),this._trackers=[],this._getAnnounceOpts=null}}_defaultAnnounceOpts(e={}){return null==e.numwant&&(e.numwant=u.DEFAULT_ANNOUNCE_PEERS),null==e.uploaded&&(e.uploaded=0),null==e.downloaded&&(e.downloaded=0),this._getAnnounceOpts&&(e=Object.assign({},e,this._getAnnounceOpts())),e}}m.scrape=(e,t)=>{if(t=i(t),!e.infoHash)throw new Error("Option `infoHash` is required");if(!e.announce)throw new Error("Option `announce` is required");const n=Object.assign({},e,{infoHash:Array.isArray(e.infoHash)?e.infoHash[0]:e.infoHash,peerId:r.from("01234567890123456789"),port:6881}),o=new m(n);o.once("error",t),o.once("warning",t);let a=Array.isArray(e.infoHash)?e.infoHash.length:1;const s={};return o.on("scrape",e=>{if(a-=1,s[e.infoHash]=e,0===a){o.destroy();const e=Object.keys(s);1===e.length?t(null,s[e[0]]):t(null,s)}}),e.infoHash=Array.isArray(e.infoHash)?e.infoHash.map(e=>r.from(e,"hex")):r.from(e.infoHash,"hex"),o.scrape({infoHash:e.infoHash}),o},t.exports=m}).call(this,e("_process"))},{"./lib/client/http-tracker":33,"./lib/client/udp-tracker":33,"./lib/client/websocket-tracker":18,"./lib/common":19,_process:92,debug:45,events:49,once:86,"run-parallel":119,"safe-buffer":121,"simple-peer":124,uniq:182,url:184}],17:[function(e,t){const n=e("events");t.exports=class extends n{constructor(e,t){super(),this.client=e,this.announceUrl=t,this.interval=null,this.destroyed=!1}setInterval(e){null==e&&(e=this.DEFAULT_ANNOUNCE_INTERVAL),clearInterval(this.interval),e&&(this.interval=setInterval(()=>{this.announce(this.client._defaultAnnounceOpts())},e),this.interval.unref&&this.interval.unref())}}},{events:49}],18:[function(e,t){function o(){}const a=e("debug")("bittorrent-tracker:websocket-tracker"),i=e("simple-peer"),s=e("randombytes"),l=e("simple-websocket"),c=e("../common"),u=e("./tracker"),p={};class f extends u{constructor(e,t,n){super(e,t),a("new websocket tracker %s",t),this.peers={},this.socket=null,this.reconnecting=!1,this.retries=0,this.reconnectTimer=null,this.expectingResponse=!1,this._openSocket()}announce(e){if(this.destroyed||this.reconnecting)return;if(!this.socket.connected)return void this.socket.once("connect",()=>{this.announce(e)});const t=Object.assign({},e,{action:"announce",info_hash:this.client._infoHashBinary,peer_id:this.client._peerIdBinary});if(this._trackerId&&(t.trackerid=this._trackerId),"stopped"===e.event||"completed"===e.event)this._send(t);else{const n=d(e.numwant,10);this._generateOffers(n,e=>{t.numwant=n,t.offers=e,this._send(t)})}}scrape(e){if(this.destroyed||this.reconnecting)return;if(!this.socket.connected)return void this.socket.once("connect",()=>{this.scrape(e)});const t=Array.isArray(e.infoHash)&&0e.toString("binary")):e.infoHash&&e.infoHash.toString("binary")||this.client._infoHashBinary;this._send({action:"scrape",info_hash:t})}destroy(e=o){function t(){r&&(clearTimeout(r),r=null),n.removeListener("data",t),n.destroy(),n=null}if(this.destroyed)return e(null);for(const t in this.destroyed=!0,clearInterval(this.interval),clearTimeout(this.reconnectTimer),this.peers){const e=this.peers[t];clearTimeout(e.trackerTimeout),e.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,p[this.announceUrl]&&(p[this.announceUrl].consumers-=1),0{this._onSocketConnect()},this._onSocketErrorBound=e=>{this._onSocketError(e)},this._onSocketDataBound=e=>{this._onSocketData(e)},this._onSocketCloseBound=()=>{this._onSocketClose()},this.socket=p[this.announceUrl],this.socket?p[this.announceUrl].consumers+=1:(this.socket=p[this.announceUrl]=new l(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(e){if(!this.destroyed){this.expectingResponse=!1;try{e=JSON.parse(e)}catch(e){return void this.client.emit("warning",new Error("Invalid tracker response"))}"announce"===e.action?this._onAnnounceResponse(e):"scrape"===e.action?this._onScrapeResponse(e):this._onSocketError(new Error(`invalid action in WS response: ${e.action}`))}}_onAnnounceResponse(e){if(e.info_hash!==this.client._infoHashBinary)return void a("ignoring websocket data from %s for %s (looking for %s: reused socket)",this.announceUrl,c.binaryToHex(e.info_hash),this.client.infoHash);if(e.peer_id&&e.peer_id===this.client._peerIdBinary)return;a("received %s from %s for %s",JSON.stringify(e),this.announceUrl,this.client.infoHash);const t=e["failure reason"];if(t)return this.client.emit("warning",new Error(t));const n=e["warning message"];n&&this.client.emit("warning",new Error(n));const r=e.interval||e["min interval"];r&&this.setInterval(1e3*r);const o=e["tracker id"];if(o&&(this._trackerId=o),null!=e.complete){const t=Object.assign({},e,{announce:this.announceUrl,infoHash:c.binaryToHex(e.info_hash)});this.client.emit("update",t)}let i;if(e.offer&&e.peer_id&&(a("creating peer (from remote offer)"),i=this._createPeer(),i.id=c.binaryToHex(e.peer_id),i.once("signal",t=>{const n={action:"announce",info_hash:this.client._infoHashBinary,peer_id:this.client._peerIdBinary,to_peer_id:e.peer_id,answer:t,offer_id:e.offer_id};this._trackerId&&(n.trackerid=this._trackerId),this._send(n)}),i.signal(e.offer),this.client.emit("peer",i)),e.answer&&e.peer_id){const t=c.binaryToHex(e.offer_id);i=this.peers[t],i?(i.id=c.binaryToHex(e.peer_id),i.signal(e.answer),this.client.emit("peer",i),clearTimeout(i.trackerTimeout),i.trackerTimeout=null,delete this.peers[t]):a(`got unexpected answer: ${JSON.stringify(e.answer)}`)}}_onScrapeResponse(e){e=e.files||{};const t=Object.keys(e);return 0===t.length?void this.client.emit("warning",new Error("invalid scrape response")):void t.forEach(t=>{const n=Object.assign(e[t],{announce:this.announceUrl,infoHash:c.binaryToHex(t)});this.client.emit("scrape",n)})}_onSocketClose(){this.destroyed||(this.destroy(),this._startReconnectTimer())}_onSocketError(e){this.destroyed||(this.destroy(),this.client.emit("warning",e),this._startReconnectTimer())}_startReconnectTimer(){const e=r(Math.random()*120000)+d(n(2,this.retries)*10000,1800000);this.reconnecting=!0,clearTimeout(this.reconnectTimer),this.reconnectTimer=setTimeout(()=>{this.retries++,this._openSocket()},e),this.reconnectTimer.unref&&this.reconnectTimer.unref(),a("reconnecting socket in %s ms",e)}_send(e){if(!this.destroyed){this.expectingResponse=!0;const t=JSON.stringify(e);a("send %s",t),this.socket.send(t)}}_generateOffers(e,t){function n(){const e=s(20).toString("hex");a("creating peer (from _generateOffers)");const t=o.peers[e]=o._createPeer({initiator:!0});t.once("signal",t=>{i.push({offer:t,offer_id:c.hexToBinary(e)}),r()}),t.trackerTimeout=setTimeout(()=>{a("tracker timeout: destroying peer"),t.trackerTimeout=null,delete o.peers[e],t.destroy()},50000),t.trackerTimeout.unref&&t.trackerTimeout.unref()}function r(){i.length===e&&(a("generated %s offers",e),t(i))}const o=this,i=[];a("generating %s offers",e);for(let r=0;r=this.size;){var o=n.concat(this._buffered);this._bufferedBytes-=this.size,this.push(o.slice(0,this.size)),this._buffered=[o.slice(this.size,o.length)]}r()},r.prototype._flush=function(){if(this._bufferedBytes&&this._zeroPadding){var e=new n(this.size-this._bufferedBytes);e.fill(0),this._buffered.push(e),this.push(n.concat(this._buffered)),this._buffered=null}else this._bufferedBytes&&(this.push(n.concat(this._buffered)),this._buffered=null);this.push(null)}}).call(this,e("buffer").Buffer)},{buffer:39,defined:47,inherits:67,"readable-stream":30}],22:[function(e,t){'use strict';function n(e){return this instanceof n?void(d.call(this,e),l.call(this,e),e&&!1===e.readable&&(this.readable=!1),e&&!1===e.writable&&(this.writable=!1),this.allowHalfOpen=!0,e&&!1===e.allowHalfOpen&&(this.allowHalfOpen=!1),this.once("end",r)):new n(e)}function r(){this.allowHalfOpen||this._writableState.ended||a.nextTick(o,this)}function o(e){e.end()}var a=e("process-nextick-args"),i=Object.keys||function(e){var t=[];for(var n in e)t.push(n);return t};t.exports=n;var s=e("core-util-is");s.inherits=e("inherits");var d=e("./_stream_readable"),l=e("./_stream_writable");s.inherits(n,d);for(var c=i(l.prototype),u=0,p;u>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}function m(e,t){return 0>=e||0===t.length&&t.ended?0:t.objectMode?1:e===e?(e>t.highWaterMark&&(t.highWaterMark=h(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0)):t.flowing&&t.length?t.buffer.head.data.length:t.length}function g(e,t){if(!t.ended){if(t.decoder){var n=t.decoder.end();n&&n.length&&(t.buffer.push(n),t.length+=t.objectMode?1:n.length)}t.ended=!0,_(e)}}function _(e){var t=e._readableState;t.needReadable=!1,t.emittedReadable||(W("emitReadable",t.flowing),t.emittedReadable=!0,t.sync?U.nextTick(b,e):b(e))}function b(e){W("emit readable"),e.emit("readable"),C(e)}function y(e,t){t.readingMore||(t.readingMore=!0,U.nextTick(w,e,t))}function w(e,t){for(var n=t.length;!t.reading&&!t.flowing&&!t.ended&&t.length=t.length?(n=t.decoder?t.buffer.join(""):1===t.buffer.length?t.buffer.head.data:t.buffer.concat(t.length),t.buffer.clear()):n=L(e,t.buffer,t.decoder),n}function L(e,t,n){var r;return ei.length?i.length:e;if(a+=s===i.length?i:i.slice(0,e),e-=s,0===e){s===i.length?(++o,t.head=r.next?r.next:t.tail=null):(t.head=r,r.data=i.slice(s));break}++o}return t.length-=o,a}function T(e,t){var r=F.allocUnsafe(e),o=t.head,a=1;for(o.data.copy(r),e-=o.data.length;o=o.next;){var i=o.data,s=e>i.length?i.length:e;if(i.copy(r,r.length-e,0,s),e-=s,0===e){s===i.length?(++a,t.head=o.next?o.next:t.tail=null):(t.head=o,o.data=i.slice(s));break}++a}return t.length-=a,r}function B(e){var t=e._readableState;if(0=t.highWaterMark||t.ended))return W("read: emitReadable",t.length,t.ended),0===t.length&&t.ended?B(this):_(this),null;if(e=m(e,t),0===e&&t.ended)return 0===t.length&&B(this),null;var o=t.needReadable;W("need readable",o),(0===t.length||t.length-e>>0),n=this.head,a=0;n;)r(n.data,t,a),a+=n.data.length,n=n.next;return t},e}(),a&&a.inspect&&a.inspect.custom&&(t.exports.prototype[a.inspect.custom]=function(){var e=a.inspect({length:this.length});return this.constructor.name+" "+e})},{"safe-buffer":31,util:33}],28:[function(e,t){'use strict';function n(e,t){e.emit("error",t)}var r=e("process-nextick-args");t.exports={destroy:function(e,t){var o=this,a=this._readableState&&this._readableState.destroyed,i=this._writableState&&this._writableState.destroyed;return a||i?(t?t(e):e&&(!this._writableState||!this._writableState.errorEmitted)&&r.nextTick(n,this,e),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(e||null,function(e){!t&&e?(r.nextTick(n,o,e),o._writableState&&(o._writableState.errorEmitted=!0)):t&&t(e)}),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.finished=!1,this._writableState.errorEmitted=!1)}}},{"process-nextick-args":91}],29:[function(e,t){t.exports=e("events").EventEmitter},{events:49}],30:[function(e,t,n){n=t.exports=e("./lib/_stream_readable.js"),n.Stream=n,n.Readable=n,n.Writable=e("./lib/_stream_writable.js"),n.Duplex=e("./lib/_stream_duplex.js"),n.Transform=e("./lib/_stream_transform.js"),n.PassThrough=e("./lib/_stream_passthrough.js")},{"./lib/_stream_duplex.js":22,"./lib/_stream_passthrough.js":23,"./lib/_stream_readable.js":24,"./lib/_stream_transform.js":25,"./lib/_stream_writable.js":26}],31:[function(e,t,n){function r(e,t){for(var n in e)t[n]=e[n]}function o(e,t,n){return i(e,t,n)}var a=e("buffer"),i=a.Buffer;i.from&&i.alloc&&i.allocUnsafe&&i.allocUnsafeSlow?t.exports=a:(r(a,n),n.Buffer=o),r(i,o),o.from=function(e,t,n){if("number"==typeof e)throw new TypeError("Argument must not be a number");return i(e,t,n)},o.alloc=function(e,t,n){if("number"!=typeof e)throw new TypeError("Argument must be a number");var r=i(e);return void 0===t?r.fill(0):"string"==typeof n?r.fill(t,n):r.fill(t),r},o.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return i(e)},o.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return a.SlowBuffer(e)}},{buffer:39}],32:[function(e,t,n){'use strict';function r(e){if(!e)return"utf8";for(var t;;)switch(e){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 e;default:if(t)return;e=(""+e).toLowerCase(),t=!0;}}function o(e){var t=r(e);if("string"!=typeof t&&(_.isEncoding===b||!b(e)))throw new Error("Unknown encoding: "+e);return t||e}function a(e){this.encoding=o(e);var t;switch(this.encoding){case"utf16le":this.text=u,this.end=p,t=4;break;case"utf8":this.fillLast=c,t=4;break;case"base64":this.text=f,this.end=h,t=3;break;default:return this.write=m,void(this.end=g);}this.lastNeed=0,this.lastTotal=0,this.lastChar=_.allocUnsafe(t)}function s(e){if(127>=e)return 0;return 6==e>>5?2:14==e>>4?3:30==e>>3?4:2==e>>6?-1:-2}function d(e,t,n){var r=t.length-1;if(r=r)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1],n.slice(0,-1)}return n}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=e[e.length-1],e.toString("utf16le",t,e.length-1)}function p(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed){var n=this.lastTotal-this.lastNeed;return t+this.lastChar.toString("utf16le",0,n)}return t}function f(e,t){var r=(e.length-t)%3;return 0==r?e.toString("base64",t):(this.lastNeed=3-r,this.lastTotal=3,1==r?this.lastChar[0]=e[e.length-1]:(this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1]),e.toString("base64",t,e.length-r))}function h(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+this.lastChar.toString("base64",0,3-this.lastNeed):t}function m(e){return e.toString(this.encoding)}function g(e){return e&&e.length?this.write(e):""}var _=e("safe-buffer").Buffer,b=_.isEncoding||function(e){switch(e=""+e,e&&e.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;}};n.StringDecoder=a,a.prototype.write=function(e){if(0===e.length)return"";var t,n;if(this.lastNeed){if(t=this.fillLast(e),void 0===t)return"";n=this.lastNeed,this.lastNeed=0}else n=0;return nt)throw new RangeError("\"size\" argument must not be negative");return e.allocUnsafe?e.allocUnsafe(t):new e(t)}}).call(this,e("buffer").Buffer)},{buffer:39}],36:[function(e,t){(function(n){var r=e("buffer-fill"),o=e("buffer-alloc-unsafe");t.exports=function(e,t,a){if("number"!=typeof e)throw new TypeError("\"size\" argument must be a number");if(0>e)throw new RangeError("\"size\" argument must not be negative");if(n.alloc)return n.alloc(e,t,a);var i=o(e);return 0===e?i:void 0===t?r(i,0):("string"!=typeof a&&(a=void 0),r(i,t,a))}}).call(this,e("buffer").Buffer)},{buffer:39,"buffer-alloc-unsafe":35,"buffer-fill":37}],37:[function(e,t){(function(e){function n(e){return 1===e.length&&256>e.charCodeAt(0)}function r(e,t,n,r){if(0>n||r>e.length)throw new RangeError("Out of range index");return n>>>=0,r=void 0===r?e.length:r>>>0,r>n&&e.fill(t,n,r),e}function o(e,t,n,r){if(0>n||r>e.length)throw new RangeError("Out of range index");if(r<=n)return e;n>>>=0,r=void 0===r?e.length:r>>>0;for(var o=n,a=t.length;o<=r-a;)t.copy(e,o),o+=a;return o!==r&&t.copy(e,o,0,r-o),e}var a=function(){try{if(!e.isEncoding("latin1"))return!1;var t=e.alloc?e.alloc(4):new e(4);return t.fill("ab","ucs2"),"61006200"===t.toString("hex")}catch(e){return!1}}();t.exports=function(t,i,s,d,l){if(a)return t.fill(i,s,d,l);if("number"==typeof i)return r(t,i,s,d);if("string"==typeof i){if("string"==typeof s?(l=s,s=0,d=t.length):"string"==typeof d&&(l=d,d=t.length),void 0!==l&&"string"!=typeof l)throw new TypeError("encoding must be a string");if("latin1"===l&&(l="binary"),"string"==typeof l&&!e.isEncoding(l))throw new TypeError("Unknown encoding: "+l);if(""===i)return r(t,0,s,d);if(n(i))return r(t,i.charCodeAt(0),s,d);i=new e(i,l)}return e.isBuffer(i)?o(t,i,s,d):r(t,0,s,d)}}).call(this,e("buffer").Buffer)},{buffer:39}],38:[function(e,t){(function(e){function n(e){return"ArrayBuffer"===a.call(e).slice(8,-1)}function r(t,n,r){n>>>=0;var o=t.byteLength-n;if(0>o)throw new RangeError("'offset' is out of bounds");if(void 0===r)r=o;else if(r>>>=0,r>o)throw new RangeError("'length' is out of bounds");return i?e.from(t.slice(n,n+r)):new e(new Uint8Array(t.slice(n,n+r)))}function o(t,n){if(("string"!=typeof n||""===n)&&(n="utf8"),!e.isEncoding(n))throw new TypeError("\"encoding\" must be a valid string encoding");return i?e.from(t,n):new e(t,n)}var a=Object.prototype.toString,i="function"==typeof e.alloc&&"function"==typeof e.allocUnsafe&&"function"==typeof e.from;t.exports=function(t,a,s){if("number"==typeof t)throw new TypeError("\"value\" argument must not be a number");return n(t)?r(t,a,s):"string"==typeof t?o(t,a):i?e.from(t):new e(t)}}).call(this,e("buffer").Buffer)},{buffer:39}],39:[function(e,t,r){(function(t){/*! * The buffer module from node.js, for the browser. * * @author Feross Aboukhadijeh * @license MIT */'use strict';function a(e){if(2147483647e)throw new RangeError("The value \""+e+"\" is invalid for option \"size\"")}function l(e,t,n){return s(e),0>=e?a(e):void 0===t?a(e):"string"==typeof n?a(e).fill(t,n):a(e).fill(t)}function c(e){return s(e),a(0>e?0:0|m(e))}function u(e,n){if(("string"!=typeof n||""===n)&&(n="utf8"),!t.isEncoding(n))throw new TypeError("Unknown encoding: "+n);var r=0|_(e,n),o=a(r),i=o.write(e,n);return i!==r&&(o=o.slice(0,i)),o}function p(e){for(var t=0>e.length?0:0|m(e.length),n=a(t),r=0;rn||e.byteLength=2147483647)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+2147483647 .toString(16)+" bytes");return 0|e}function g(e){return+e!=e&&(e=0),t.alloc(+e)}function _(e,n){if(t.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||K(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw new TypeError("The \"string\" argument must be one of type string, Buffer, or ArrayBuffer. Received type "+typeof e);var r=e.length,o=2>>1;case"base64":return V(e).length;default:if(a)return o?-1:D(e).length;n=(""+n).toLowerCase(),a=!0;}}function b(e,t,n){var r=!1;if((void 0===t||0>t)&&(t=0),t>this.length)return"";if((void 0===n||n>this.length)&&(n=this.length),0>=n)return"";if(n>>>=0,t>>>=0,n<=t)return"";for(e||(e="utf8");;)switch(e){case"hex":return U(this,t,n);case"utf8":case"utf-8":return T(this,t,n);case"ascii":return R(this,t,n);case"latin1":case"binary":return A(this,t,n);case"base64":return I(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return P(this,t,n);default:if(r)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),r=!0;}}function y(e,t,n){var r=e[t];e[t]=e[n],e[n]=r}function w(e,n,r,o,a){if(0===e.length)return-1;if("string"==typeof r?(o=r,r=0):2147483647r&&(r=-2147483648),r=+r,Y(r)&&(r=a?0:e.length-1),0>r&&(r=e.length+r),r>=e.length){if(a)return-1;r=e.length-1}else if(0>r)if(a)r=0;else return-1;if("string"==typeof n&&(n=t.from(n,o)),t.isBuffer(n))return 0===n.length?-1:k(e,n,r,o,a);if("number"==typeof n)return n&=255,"function"==typeof Uint8Array.prototype.indexOf?a?Uint8Array.prototype.indexOf.call(e,n,r):Uint8Array.prototype.lastIndexOf.call(e,n,r):k(e,[n],r,o,a);throw new TypeError("val must be string, number or Buffer")}function k(e,t,n,r,o){function a(e,t){return 1===s?e[t]:e.readUInt16BE(t*s)}var s=1,d=e.length,l=t.length;if(void 0!==r&&(r=(r+"").toLowerCase(),"ucs2"===r||"ucs-2"===r||"utf16le"===r||"utf-16le"===r)){if(2>e.length||2>t.length)return-1;s=2,d/=2,l/=2,n/=2}var c;if(o){var u=-1;for(c=n;cd&&(n=d-l),c=n;0<=c;c--){for(var p=!0,f=0;fo&&(r=o)):r=o;var a=t.length;r>a/2&&(r=a/2);for(var s=0,d;sa&&(s=a):2===l?(c=e[o+1],128==(192&c)&&(f=(31&a)<<6|63&c,127f||57343f&&(s=f))):void 0}null===s?(s=65533,l=1):65535>>10),s=56320|1023&s),r.push(s),o+=l}return B(r)}function B(e){var t=e.length;if(t<=4096)return o.apply(String,e);for(var n="",r=0;rt)&&(t=0),(!n||0>n||n>r)&&(n=r);for(var o="",a=t;ae)throw new RangeError("offset is not uint");if(e+t>n)throw new RangeError("Trying to access beyond buffer length")}function O(e,n,r,o,a,i){if(!t.isBuffer(e))throw new TypeError("\"buffer\" argument must be a Buffer instance");if(n>a||ne.length)throw new RangeError("Index out of range")}function j(e,t,n,r){if(n+r>e.length)throw new RangeError("Index out of range");if(0>n)throw new RangeError("Index out of range")}function N(e,t,n,r,o){return t=+t,n>>>=0,o||j(e,t,n,4,34028234663852886e22,-34028234663852886e22),X.write(e,t,n,r,23,4),n+4}function F(e,t,n,r,o){return t=+t,n>>>=0,o||j(e,t,n,8,17976931348623157e292,-17976931348623157e292),X.write(e,t,n,r,52,8),n+8}function q(e){if(e=e.split("=")[0],e=e.trim().replace(J,""),2>e.length)return"";for(;0!=e.length%4;)e+="=";return e}function H(e){return 16>e?"0"+e.toString(16):e.toString(16)}function D(e,t){t=t||1/0;for(var n=e.length,r=null,o=[],a=0,s;as){if(!r){if(56319s){-1<(t-=3)&&o.push(239,191,189),r=s;continue}s=(r-55296<<10|s-56320)+65536}else r&&-1<(t-=3)&&o.push(239,191,189);if(r=null,128>s){if(0>(t-=1))break;o.push(s)}else if(2048>s){if(0>(t-=2))break;o.push(192|s>>6,128|63&s)}else if(65536>s){if(0>(t-=3))break;o.push(224|s>>12,128|63&s>>6,128|63&s)}else if(1114112>s){if(0>(t-=4))break;o.push(240|s>>18,128|63&s>>12,128|63&s>>6,128|63&s)}else throw new Error("Invalid code point")}return o}function W(e){for(var t=[],n=0;n(t-=2));++r)o=e.charCodeAt(r),a=o>>8,s=o%256,n.push(s),n.push(a);return n}function V(e){return $.toByteArray(q(e))}function G(e,t,n,r){for(var o=0;o=t.length||o>=e.length);++o)t[o+n]=e[o];return o}function K(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function Y(e){return e!==e}var $=e("base64-js"),X=e("ieee754");r.Buffer=t,r.SlowBuffer=g,r.INSPECT_MAX_BYTES=50;r.kMaxLength=2147483647,t.TYPED_ARRAY_SUPPORT=function(){try{var e=new Uint8Array(1);return e.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===e.foo()}catch(t){return!1}}(),t.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(t.prototype,"parent",{enumerable:!0,get:function(){return t.isBuffer(this)?this.buffer:void 0}}),Object.defineProperty(t.prototype,"offset",{enumerable:!0,get:function(){return t.isBuffer(this)?this.byteOffset:void 0}}),"undefined"!=typeof Symbol&&null!=Symbol.species&&t[Symbol.species]===t&&Object.defineProperty(t,Symbol.species,{value:null,configurable:!0,enumerable:!1,writable:!1}),t.poolSize=8192,t.from=function(e,t,n){return i(e,t,n)},t.prototype.__proto__=Uint8Array.prototype,t.__proto__=Uint8Array,t.alloc=function(e,t,n){return l(e,t,n)},t.allocUnsafe=function(e){return c(e)},t.allocUnsafeSlow=function(e){return c(e)},t.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==t.prototype},t.compare=function(e,n){if(K(e,Uint8Array)&&(e=t.from(e,e.offset,e.byteLength)),K(n,Uint8Array)&&(n=t.from(n,n.offset,n.byteLength)),!t.isBuffer(e)||!t.isBuffer(n))throw new TypeError("The \"buf1\", \"buf2\" arguments must be one of type Buffer or Uint8Array");if(e===n)return 0;for(var r=e.length,o=n.length,s=0,l=d(r,o);st&&(e+=" ... "),""},t.prototype.compare=function(e,n,r,o,a){if(K(e,Uint8Array)&&(e=t.from(e,e.offset,e.byteLength)),!t.isBuffer(e))throw new TypeError("The \"target\" argument must be one of type Buffer or Uint8Array. Received type "+typeof e);if(void 0===n&&(n=0),void 0===r&&(r=e?e.length:0),void 0===o&&(o=0),void 0===a&&(a=this.length),0>n||r>e.length||0>o||a>this.length)throw new RangeError("out of range index");if(o>=a&&n>=r)return 0;if(o>=a)return-1;if(n>=r)return 1;if(n>>>=0,r>>>=0,o>>>=0,a>>>=0,this===e)return 0;for(var s=a-o,l=r-n,c=d(s,l),u=this.slice(o,a),p=e.slice(n,r),f=0;f>>=0,isFinite(n)?(n>>>=0,void 0===r&&(r="utf8")):(r=n,n=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");var o=this.length-t;if((void 0===n||n>o)&&(n=o),0n||0>t)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");r||(r="utf8");for(var a=!1;;)switch(r){case"hex":return x(this,e,t,n);case"utf8":case"utf-8":return S(this,e,t,n);case"ascii":return E(this,e,t,n);case"latin1":case"binary":return C(this,e,t,n);case"base64":return v(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return L(this,e,t,n);default:if(a)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),a=!0;}},t.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};t.prototype.slice=function(e,n){var r=this.length;e=~~e,n=void 0===n?r:~~n,0>e?(e+=r,0>e&&(e=0)):e>r&&(e=r),0>n?(n+=r,0>n&&(n=0)):n>r&&(n=r),n>>=0,t>>>=0,n||M(e,t,this.length);for(var r=this[e],o=1,a=0;++a>>=0,t>>>=0,n||M(e,t,this.length);for(var r=this[e+--t],o=1;0>>=0,t||M(e,1,this.length),this[e]},t.prototype.readUInt16LE=function(e,t){return e>>>=0,t||M(e,2,this.length),this[e]|this[e+1]<<8},t.prototype.readUInt16BE=function(e,t){return e>>>=0,t||M(e,2,this.length),this[e]<<8|this[e+1]},t.prototype.readUInt32LE=function(e,t){return e>>>=0,t||M(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},t.prototype.readUInt32BE=function(e,t){return e>>>=0,t||M(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},t.prototype.readIntLE=function(e,t,r){e>>>=0,t>>>=0,r||M(e,t,this.length);for(var o=this[e],a=1,s=0;++s=a&&(o-=n(2,8*t)),o},t.prototype.readIntBE=function(e,t,r){e>>>=0,t>>>=0,r||M(e,t,this.length);for(var o=t,a=1,s=this[e+--o];0=a&&(s-=n(2,8*t)),s},t.prototype.readInt8=function(e,t){return e>>>=0,t||M(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},t.prototype.readInt16LE=function(e,t){e>>>=0,t||M(e,2,this.length);var n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},t.prototype.readInt16BE=function(e,t){e>>>=0,t||M(e,2,this.length);var n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},t.prototype.readInt32LE=function(e,t){return e>>>=0,t||M(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},t.prototype.readInt32BE=function(e,t){return e>>>=0,t||M(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},t.prototype.readFloatLE=function(e,t){return e>>>=0,t||M(e,4,this.length),X.read(this,e,!0,23,4)},t.prototype.readFloatBE=function(e,t){return e>>>=0,t||M(e,4,this.length),X.read(this,e,!1,23,4)},t.prototype.readDoubleLE=function(e,t){return e>>>=0,t||M(e,8,this.length),X.read(this,e,!0,52,8)},t.prototype.readDoubleBE=function(e,t){return e>>>=0,t||M(e,8,this.length),X.read(this,e,!1,52,8)},t.prototype.writeUIntLE=function(e,t,r,o){if(e=+e,t>>>=0,r>>>=0,!o){var a=n(2,8*r)-1;O(this,e,t,r,a,0)}var s=1,d=0;for(this[t]=255&e;++d>>=0,r>>>=0,!o){var a=n(2,8*r)-1;O(this,e,t,r,a,0)}var s=r-1,d=1;for(this[t+s]=255&e;0<=--s&&(d*=256);)this[t+s]=255&e/d;return t+r},t.prototype.writeUInt8=function(e,t,n){return e=+e,t>>>=0,n||O(this,e,t,1,255,0),this[t]=255&e,t+1},t.prototype.writeUInt16LE=function(e,t,n){return e=+e,t>>>=0,n||O(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},t.prototype.writeUInt16BE=function(e,t,n){return e=+e,t>>>=0,n||O(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},t.prototype.writeUInt32LE=function(e,t,n){return e=+e,t>>>=0,n||O(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},t.prototype.writeUInt32BE=function(e,t,n){return e=+e,t>>>=0,n||O(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},t.prototype.writeIntLE=function(e,t,r,o){if(e=+e,t>>>=0,!o){var a=n(2,8*r-1);O(this,e,t,r,a-1,-a)}var s=0,d=1,l=0;for(this[t]=255&e;++se&&0===l&&0!==this[t+s-1]&&(l=1),this[t+s]=255&(e/d>>0)-l;return t+r},t.prototype.writeIntBE=function(e,t,r,o){if(e=+e,t>>>=0,!o){var a=n(2,8*r-1);O(this,e,t,r,a-1,-a)}var s=r-1,d=1,l=0;for(this[t+s]=255&e;0<=--s&&(d*=256);)0>e&&0===l&&0!==this[t+s+1]&&(l=1),this[t+s]=255&(e/d>>0)-l;return t+r},t.prototype.writeInt8=function(e,t,n){return e=+e,t>>>=0,n||O(this,e,t,1,127,-128),0>e&&(e=255+e+1),this[t]=255&e,t+1},t.prototype.writeInt16LE=function(e,t,n){return e=+e,t>>>=0,n||O(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},t.prototype.writeInt16BE=function(e,t,n){return e=+e,t>>>=0,n||O(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},t.prototype.writeInt32LE=function(e,t,n){return e=+e,t>>>=0,n||O(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},t.prototype.writeInt32BE=function(e,t,n){return e=+e,t>>>=0,n||O(this,e,t,4,2147483647,-2147483648),0>e&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},t.prototype.writeFloatLE=function(e,t,n){return N(this,e,t,!0,n)},t.prototype.writeFloatBE=function(e,t,n){return N(this,e,t,!1,n)},t.prototype.writeDoubleLE=function(e,t,n){return F(this,e,t,!0,n)},t.prototype.writeDoubleBE=function(e,t,n){return F(this,e,t,!1,n)},t.prototype.copy=function(e,n,r,o){if(!t.isBuffer(e))throw new TypeError("argument should be a Buffer");if(r||(r=0),o||0===o||(o=this.length),n>=e.length&&(n=e.length),n||(n=0),0n)throw new RangeError("targetStart out of bounds");if(0>r||r>=this.length)throw new RangeError("Index out of range");if(0>o)throw new RangeError("sourceEnd out of bounds");o>this.length&&(o=this.length),e.length-na||"latin1"===o)&&(e=a)}}else"number"==typeof e&&(e&=255);if(0>n||this.length>>=0,r=r===void 0?this.length:r>>>0,e||(e=0);var s;if("number"==typeof e)for(s=n;s{this.destroyed||(this._outstandingPuts+=1,e.put(o,t,()=>{this._outstandingPuts-=1,0===this._outstandingPuts&&"function"==typeof this._finalCb&&(this._finalCb(null),this._finalCb=null)}),o+=1)};this._blockstream.on("data",a).on("error",e=>{this.destroy(e)})}_write(e,t,n){this._blockstream.write(e,t,n)}_final(e){this._blockstream.end(),this._blockstream.once("end",()=>{0===this._outstandingPuts?e(null):this._finalCb=e})}destroy(e){this.destroyed||(this.destroyed=!0,e&&this.emit("error",e),this.emit("close"))}}t.exports=o},{"block-stream2":21,"readable-stream":115}],42:[function(e,n){n.exports=function(e,n,r){for(var o=1/0,a=0,s=n.length-1,d,l,c;a<=s&&(d=a+(s-a>>1),c=n[d]-e,0>c?a=d+1:0t=>{const n={};if(h(e))n.getStream=_(e),n.length=e.size;else if(o.isBuffer(e))n.getStream=b(e),n.length=e.length;else if(g(e))n.getStream=w(e,n),n.length=0;else{if("string"==typeof e){if("function"!=typeof L.stat)throw new Error("filesystem paths do not work in the browser");const n=1e?r(e):void(t=v(t),r(null,t,u)))}if(m(e)&&(e=Array.from(e)),Array.isArray(e)||(e=[e]),0===e.length)throw new Error("invalid input type");e.forEach(e=>{if(null==e)throw new Error(`invalid input type: ${e}`)}),e=e.map(e=>h(e)&&"string"==typeof e.path&&"function"==typeof L.stat?e.path:e),1!==e.length||"string"==typeof e[0]||e[0].name||(e[0].name=t.name);let d=null;e.forEach((t,n)=>{if("string"==typeof t)return;let r=t.fullPath||t.name;r||(r=`Unknown File ${n+1}`,t.unknownName=!0),t.path=r.split("/"),t.path[0]||t.path.shift(),2>t.path.length?d=null:0===n&&1{if("string"==typeof e)return!0;const t=e.path[e.path.length-1];return c(t)&&T.not(t)}),d&&e.forEach(e=>{const t=(o.isBuffer(e)||g(e))&&!e.path;"string"==typeof e||t||e.path.shift()}),!t.name&&d&&(t.name=d),t.name||e.some(e=>"string"==typeof e?(t.name=E.basename(e),!0):e.unknownName?void 0:(t.name=e.path[e.path.length-1],!0)),t.name||(t.name=`Unnamed Torrent ${Date.now()}`);const l=e.reduce((e,t)=>e+ +("string"==typeof t),0);let u=1===e.length;if(1===e.length&&"string"==typeof e[0]){if("function"!=typeof L.stat)throw new Error("filesystem paths do not work in the browser");I(e[0],(e,t)=>e?r(e):void(u=t,a()))}else n.nextTick(()=>{a()})}function s(e,t,n){l(e,d,(r,o)=>r?n(r):void(o=Array.isArray(o)?v(o):[o],e=E.normalize(e),t&&(e=e.slice(0,e.lastIndexOf(E.sep)+1)),e[e.length-1]!==E.sep&&(e+=E.sep),o.forEach(t=>{t.getStream=y(t.path),t.path=t.path.replace(e,"").split(E.sep)}),n(null,o)))}function d(e,t){t=R(t),L.stat(e,(n,r)=>{if(n)return t(n);const o={length:r.size,path:e};t(null,o)})}function l(e,t,n){L.stat(e,(r,o)=>r?n(r):void(o.isDirectory()?L.readdir(e,(r,o)=>r?n(r):void A(o.filter(c).filter(T.not).map(n=>r=>{l(E.join(e,n),t,r)}),n)):o.isFile()&&t(e,n)))}function c(e){return"."!==e[0]}function u(e,t,n){function r(e){c+=e.length;const t=f;U(e,e=>{l[t]=e,p-=1,d()}),p+=1,f+=1}function a(){h=!0,d()}function i(e){s(),n(e)}function s(){m.removeListener("error",i),g.removeListener("data",r),g.removeListener("end",a),g.removeListener("error",i)}function d(){h&&0==p&&(s(),n(null,o.from(l.join(""),"hex"),c))}n=R(n);const l=[];let c=0;const u=e.map(e=>e.getStream);let p=0,f=0,h=!1;const m=new B(u),g=new x(t,{zeroPadding:!1});m.on("error",i),m.pipe(g).on("data",r).on("end",a).on("error",i)}function p(e,n,o){let i=n.announceList;i||("string"==typeof n.announce?i=[[n.announce]]:Array.isArray(n.announce)&&(i=n.announce.map(e=>[e]))),i||(i=[]),r.WEBTORRENT_ANNOUNCE&&("string"==typeof r.WEBTORRENT_ANNOUNCE?i.push([[r.WEBTORRENT_ANNOUNCE]]):Array.isArray(r.WEBTORRENT_ANNOUNCE)&&(i=i.concat(r.WEBTORRENT_ANNOUNCE.map(e=>[e])))),n.announce===void 0&&n.announceList===void 0&&(i=i.concat(t.exports.announceList)),"string"==typeof n.urlList&&(n.urlList=[n.urlList]);const s={info:{name:n.name},"creation date":a((+n.creationDate||Date.now())/1e3),encoding:"UTF-8"};0!==i.length&&(s.announce=i[0][0],s["announce-list"]=i),n.comment!==void 0&&(s.comment=n.comment),n.createdBy!==void 0&&(s["created by"]=n.createdBy),n.private!==void 0&&(s.info.private=+n.private),n.sslCert!==void 0&&(s.info["ssl-cert"]=n.sslCert),n.urlList!==void 0&&(s["url-list"]=n.urlList);const d=n.pieceLength||S(e.reduce(f,0));s.info["piece length"]=d,u(e,d,(t,r,a)=>t?o(t):void(s.info.pieces=r,e.forEach(e=>{delete e.getStream}),n.singleFileTorrent?s.info.length=a:s.info.files=e,o(null,k.encode(s))))}function f(e,t){return e+t.length}function h(e){return"undefined"!=typeof Blob&&e instanceof Blob}function m(e){return"undefined"!=typeof FileList&&e instanceof FileList}function g(e){return"object"==typeof e&&null!=e&&"function"==typeof e.pipe}function _(e){return()=>new C(e)}function b(e){return()=>{const t=new P.PassThrough;return t.end(e),t}}function y(e){return()=>L.createReadStream(e)}function w(e,t){return()=>{const n=new P.Transform;return n._transform=function(e,n,r){t.length+=e.length,this.push(e),r()},e.pipe(n),n}}const k=e("bencode"),x=e("block-stream2"),S=e("piece-length"),E=e("path"),C=e("filestream/read"),v=e("flatten"),L=e("fs"),I=e("is-file"),T=e("junk"),B=e("multistream"),R=e("once"),A=e("run-parallel"),U=e("simple-sha1"),P=e("readable-stream");t.exports=function(e,t,n){"function"==typeof t&&([t,n]=[n,t]),t=t?Object.assign({},t):{},i(e,t,(e,r,o)=>e?n(e):void(t.singleFileTorrent=o,p(r,t,n)))},t.exports.parseInput=function(e,t,n){"function"==typeof t&&([t,n]=[n,t]),t=t?Object.assign({},t):{},i(e,t,n)},t.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"],["wss://tracker.fastcast.nz"]]}).call(this,e("_process"),"undefined"==typeof global?"undefined"==typeof self?"undefined"==typeof window?{}:window:self:global,e("buffer").Buffer)},{_process:92,bencode:11,"block-stream2":21,buffer:39,"filestream/read":61,flatten:62,fs:34,"is-file":70,junk:73,multistream:84,once:86,path:89,"piece-length":90,"readable-stream":115,"run-parallel":119,"simple-sha1":136}],45:[function(e,t,n){(function(o){function a(){let e;try{e=n.storage.getItem("debug")}catch(e){}return!e&&"undefined"!=typeof o&&"env"in o&&(e=o.env.DEBUG),e}n.log=function(...e){return"object"==typeof console&&console.log&&console.log(...e)},n.formatArgs=function(e){if(e[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+e[0]+(this.useColors?"%c ":" ")+"+"+t.exports.humanize(this.diff),!this.useColors)return;const n="color: "+this.color;e.splice(1,0,n,"color: inherit");let r=0,o=0;e[0].replace(/%[a-zA-Z%]/g,e=>{"%%"===e||(r++,"%c"===e&&(o=r))}),e.splice(o,0,n)},n.save=function(e){try{e?n.storage.setItem("debug",e):n.storage.removeItem("debug")}catch(e){}},n.load=a,n.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+)/))},n.storage=function(){try{return localStorage}catch(e){}}(),n.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"],t.exports=e("./common")(n);const{formatters:i}=t.exports;i.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}).call(this,e("_process"))},{"./common":46,_process:92}],46:[function(e,n){n.exports=function(n){function r(e){let n=0;for(let t=0;t{if("%%"===t)return t;s++;const a=o.formatters[n];if("function"==typeof a){const n=e[s];t=a.call(r,n),e.splice(s,1),s--}return t}),o.formatArgs.call(r,e);const d=r.log||o.log;d.apply(r,e)}let n;return t.namespace=e,t.enabled=o.enabled(e),t.useColors=o.useColors(),t.color=r(e),t.destroy=a,t.extend=i,"function"==typeof o.init&&o.init(t),o.instances.push(t),t}function a(){const e=o.instances.indexOf(this);return-1!==e&&(o.instances.splice(e,1),!0)}function i(e,t){const n=o(this.namespace+("undefined"==typeof t?":":t)+e);return n.log=this.log,n}function s(e){return e.toString().substring(2,e.toString().length-2).replace(/\.\*\?$/,"*")}return o.debug=o,o.default=o,o.coerce=function(e){return e instanceof Error?e.stack||e.message:e},o.disable=function(){const e=[...o.names.map(s),...o.skips.map(s).map(e=>"-"+e)].join(",");return o.enable(""),e},o.enable=function(e){o.save(e),o.names=[],o.skips=[];let t;const n=("string"==typeof e?e:"").split(/[\s,]+/),r=n.length;for(t=0;t{o[e]=n[e]}),o.instances=[],o.names=[],o.skips=[],o.formatters={},o.selectColor=r,o.enable(o.load()),o}},{ms:83}],47:[function(e,t){t.exports=function(){for(var e=0;ea)){s.warned=!0;var d=new Error("Possible EventEmitter memory leak detected. "+s.length+" \""+(t+"\" listeners added. Use emitter.setMaxListeners() to increase limit."));d.name="MaxListenersExceededWarning",d.emitter=e,d.type=t,d.count=s.length,"object"==typeof console&&console.warn&&console.warn("%s: %s",d.name,d.message)}return e}function p(){if(!this.fired)switch(this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length){case 0:return this.listener.call(this.target);case 1:return this.listener.call(this.target,arguments[0]);case 2:return this.listener.call(this.target,arguments[0],arguments[1]);case 3:return this.listener.call(this.target,arguments[0],arguments[1],arguments[2]);default:for(var e=Array(arguments.length),t=0;te||e!==e)throw new TypeError("\"defaultMaxListeners\" must be a positive number");x=e}}):n.defaultMaxListeners=x,n.prototype.setMaxListeners=function(e){if("number"!=typeof e||0>e||isNaN(e))throw new TypeError("\"n\" argument must be a positive number");return this._maxListeners=e,this},n.prototype.getMaxListeners=function(){return r(this)},n.prototype.emit=function(e){var t="error"===e,n,r,o,u,p,f;if(f=this._events,f)t=t&&null==f.error;else if(!t)return!1;if(t){if(1o)return this;0===o?n.shift():g(n,o),1===n.length&&(r[e]=n[0]),r.removeListener&&this.emit("removeListener",e,s||t)}return this},n.prototype.removeAllListeners=function(e){var t,n,r;if(n=this._events,!n)return this;if(!n.removeListener)return 0===arguments.length?(this._events=y(null),this._eventsCount=0):n[e]&&(0==--this._eventsCount?this._events=y(null):delete n[e]),this;if(0===arguments.length){var o=w(n),a;for(r=0;rthis._size&&(r=this._size),n===this._size?(this.destroy(),void this.push(null)):void(t.onload=function(){e._offset=r,e.push(i(t.result))},t.onerror=function(){e.emit("error",t.error)},t.readAsArrayBuffer(this._file.slice(n,r)))},n.prototype.destroy=function(){if(this._file=null,this.reader){this.reader.onload=null,this.reader.onerror=null;try{this.reader.abort()}catch(t){}}this.reader=null}},{inherits:67,"readable-stream":58,"typedarray-to-buffer":180}],62:[function(e,t){t.exports=function(e,t){function n(e,r){return e.reduce(function(e,o){return Array.isArray(o)&&r>1,f=-7,h=o?l-1:0,g=o?-1:1,d=t[r+h],_,b;for(h+=g,_=d&(1<<-f)-1,d>>=-f,f+=c;0>=-f,f+=a;0>1,w=23===p?n(2,-24)-n(2,-77):0,k=u?0:f-1,x=u?1:-1,d=0>a||0===a&&0>1/a?1:0,s,S,E;for(a=t(a),isNaN(a)||a===1/0?(S=isNaN(a)?1:0,s=b):(s=r(g(a)/h),1>a*(E=n(2,-s))&&(s--,E*=2),a+=1<=s+y?w/E:w*n(2,1-y),2<=a*E&&(s++,E/=2),s+y>=b?(S=0,s=b):1<=s+y?(S=(a*E-1)*n(2,p),s+=y):(S=a*n(2,y-1)*n(2,p),s=0));8<=p;o[l+k]=255&S,k+=x,S/=256,p-=8);for(s=s<{t&&t(n,r)})}t.exports=class{constructor(e){if(this.store=e,this.chunkLength=e.chunkLength,!this.store||!this.store.get||!this.store.put)throw new Error("First argument must be abstract-chunk-store compliant");this.mem=[]}put(e,t,n){this.mem[e]=t,this.store.put(e,t,t=>{this.mem[e]=null,n&&n(t)})}get(e,t,r){if("function"==typeof t)return this.get(e,null,t);const o=t&&t.offset||0,a=t&&t.length&&o+t.length,i=this.mem[e];return i?n(r,null,t?i.slice(o,a):i):void this.store.get(e,t,r)}close(e){this.store.close(e)}destroy(e){this.store.destroy(e)}}}).call(this,e("_process"))},{_process:92}],67:[function(e,t){t.exports="function"==typeof Object.create?function(e,t){t&&(e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:function(e,t){if(t){e.super_=t;var n=function(){};n.prototype=t.prototype,e.prototype=new n,e.prototype.constructor=e}}},{}],68:[function(e,t){t.exports=function(e){for(var t=0,n=e.length;t127)return!1;return!0}},{}],69:[function(e,t){function n(e){return!!e.constructor&&"function"==typeof e.constructor.isBuffer&&e.constructor.isBuffer(e)}function r(e){return"function"==typeof e.readFloatLE&&"function"==typeof e.slice&&n(e.slice(0,0))}/*! * Determine if an object is a Buffer * * @author Feross Aboukhadijeh * @license MIT */t.exports=function(e){return null!=e&&(n(e)||r(e)||!!e._isBuffer)}},{}],70:[function(e,t){'use strict';function n(e){return r.existsSync(e)&&r.statSync(e).isFile()}var r=e("fs");t.exports=function(e,t){return t?void r.stat(e,function(e,n){return e?t(e):t(null,n.isFile())}):n(e)},t.exports.sync=n},{fs:34}],71:[function(e,t){function n(e){return r(e)||o(e)}function r(e){return e instanceof Int8Array||e instanceof Int16Array||e instanceof Int32Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray||e instanceof Uint16Array||e instanceof Uint32Array||e instanceof Float32Array||e instanceof Float64Array}function o(e){return i[a.call(e)]}t.exports=n,n.strict=r,n.loose=o;var a=Object.prototype.toString,i={"[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}},{}],72:[function(e,t){var n={}.toString;t.exports=Array.isArray||function(e){return"[object Array]"==n.call(e)}},{}],73:[function(e,t,n){'use strict';n.re=()=>{throw new Error("`junk.re` was renamed to `junk.regex`")},n.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("|")),n.is=e=>n.regex.test(e),n.not=e=>!n.is(e),n.default=t.exports},{}],74:[function(e,t){(function(n){function r(e){const t={},r=e.split("magnet:?")[1],i=r&&0<=r.length?r.split("&"):[];i.forEach(e=>{const n=e.split("=");if(2!==n.length)return;const r=n[0];let o=n[1];if("dn"===r&&(o=decodeURIComponent(o).replace(/\+/g," ")),("tr"===r||"xs"===r||"as"===r||"ws"===r)&&(o=decodeURIComponent(o)),"kt"===r&&(o=decodeURIComponent(o).split("+")),"ix"===r&&(o=+o),!t[r])t[r]=o;else if(Array.isArray(t[r]))t[r].push(o);else{const e=t[r];t[r]=[e,o]}});let s;if(t.xt){const e=Array.isArray(t.xt)?t.xt:[t.xt];e.forEach(e=>{if(s=e.match(/^urn:btih:(.{40})/))t.infoHash=s[1].toLowerCase();else if(s=e.match(/^urn:btih:(.{32})/)){const e=o.decode(s[1]);t.infoHash=n.from(e,"binary").toString("hex")}})}return t.infoHash&&(t.infoHashBuffer=n.from(t.infoHash,"hex")),t.dn&&(t.name=t.dn),t.kt&&(t.keywords=t.kt),t.announce="string"==typeof t.tr?[t.tr]:Array.isArray(t.tr)?t.tr:[],t.urlList=[],("string"==typeof t.as||Array.isArray(t.as))&&(t.urlList=t.urlList.concat(t.as)),("string"==typeof t.ws||Array.isArray(t.ws))&&(t.urlList=t.urlList.concat(t.ws)),a(t.announce),a(t.urlList),t}t.exports=r,t.exports.decode=r,t.exports.encode=function(e){e=Object.assign({},e),e.infoHashBuffer&&(e.xt=`urn:btih:${e.infoHashBuffer.toString("hex")}`),e.infoHash&&(e.xt=`urn:btih:${e.infoHash}`),e.name&&(e.dn=e.name),e.keywords&&(e.kt=e.keywords),e.announce&&(e.tr=e.announce),e.urlList&&(e.ws=e.urlList,delete e.as);let t="magnet:?";return Object.keys(e).filter(e=>2===e.length).forEach((n,r)=>{const o=Array.isArray(e[n])?e[n]:[e[n]];o.forEach((e,o)=>{(0e._bufferDuration)&&e._cb){var t=e._cb;e._cb=null,t()}};r.prototype._getBufferDuration=function(){for(var e=this,t=e._sourceBuffer.buffered,n=e._elem.currentTime,r=-1,o=0;on)break;else(0<=r||n<=s)&&(r=s)}var d=r-n;return 0>d&&(d=0),d}},{inherits:67,"readable-stream":115,"to-arraybuffer":175}],76:[function(e,t){(function(e){function n(e,t){if(!(this instanceof n))return new n(e,t);if(t||(t={}),this.chunkLength=+e,!this.chunkLength)throw new Error("First argument must be a chunk length");this.chunks=[],this.closed=!1,this.length=+t.length||1/0,this.length!==1/0&&(this.lastChunkLength=this.length%this.chunkLength||this.chunkLength,this.lastChunkIndex=a(this.length/this.chunkLength)-1)}function r(t,n,r){e.nextTick(function(){t&&t(n,r)})}t.exports=n,n.prototype.put=function(e,t,n){if(this.closed)return r(n,new Error("Storage is closed"));var o=e===this.lastChunkIndex;return o&&t.length!==this.lastChunkLength?r(n,new Error("Last chunk length must be "+this.lastChunkLength)):o||t.length===this.chunkLength?void(this.chunks[e]=t,r(n,null)):r(n,new Error("Chunk length must be "+this.chunkLength))},n.prototype.get=function(e,t,n){if("function"==typeof t)return this.get(e,null,t);if(this.closed)return r(n,new Error("Storage is closed"));var o=this.chunks[e];if(!o){var a=new Error("Chunk not found");return a.notFound=!0,r(n,a)}if(!t)return r(n,null,o);var i=t.offset||0,s=t.length||o.length-i;r(n,null,o.slice(i,s+i))},n.prototype.close=n.prototype.destroy=function(e){return this.closed?r(e,new Error("Storage is closed")):void(this.closed=!0,this.chunks=null,r(e,null))}}).call(this,e("_process"))},{_process:92}],77:[function(e,t,n){function o(e,t,n){for(var r=t;r>3:0,l=null;return i&&(l=i.toString(16),d&&(l+="."+d)),{mimeCodec:l,buffer:k(e.slice(0))}},n.esds.encodingLength=function(e){return e.buffer.length},n.stsz={},n.stsz.encode=function(e,t,r){var o=e.entries||[];t=t?t.slice(r):w(n.stsz.encodingLength(e)),t.writeUInt32BE(0,0),t.writeUInt32BE(o.length,4);for(var a=0;as&&(a=1),t.writeUInt32BE(a,n),t.write(e.type,n+4,4,"ascii");var c=n+8;if(1===a&&(r.encode(e.length,t,c),c+=8),i.fullBoxes[o]&&(t.writeUInt32BE(e.flags||0,c),t.writeUInt8(e.version||0,c),c+=4),l[o]){var u=l[o];u.forEach(function(n){if(5===n.length){var r=e[n]||[];n=n.substr(0,4),r.forEach(function(e){d._encode(e,t,c),c+=d.encode.bytes})}else e[n]&&(d._encode(e[n],t,c),c+=d.encode.bytes)}),e.otherBoxes&&e.otherBoxes.forEach(function(e){d._encode(e,t,c),c+=d.encode.bytes})}else if(i[o]){var p=i[o].encode;p(e,t,c),c+=p.bytes}else if(e.buffer){var f=e.buffer;f.copy(t,c),c+=e.buffer.length}else throw new Error("Either `type` must be set to a known type (not'"+o+"') or `buffer` must be set");return d.encode.bytes=c-n,t},d.readHeaders=function(e,t,n){if(t=t||0,n=n||e.length,8>n-t)return 8;var o=e.readUInt32BE(t),a=e.toString("ascii",t+4,t+8),s=t+8;if(1===o){if(16>n-t)return 16;o=r.decode(e,s),s+=8}var d,l;return i.fullBoxes[a]&&(d=e.readUInt8(s),l=16777215&e.readUInt32BE(s),s+=4),{length:o,headersLen:s-t,contentLen:o-(s-t),type:a,version:d,flags:l}},d.decode=function(e,t,n){t=t||0,n=n||e.length;var r=d.readHeaders(e,t,n);if(!r||r.length>n-t)throw new Error("Data too short");return d.decodeWithoutHeaders(r,e,t+r.headersLen,t+r.length)},d.decodeWithoutHeaders=function(e,t,n,r){n=n||0,r=r||t.length;var o=e.type,s={};if(l[o]){s.otherBoxes=[];for(var c=l[o],u=n,p;8<=r-u;)if(p=d.decode(t,u,r),u+=p.length,0<=c.indexOf(p.type))s[p.type]=p;else if(0<=c.indexOf(p.type+"s")){var f=p.type+"s",h=s[f]=s[f]||[];h.push(p)}else s.otherBoxes.push(p)}else if(i[o]){var m=i[o].decode;s=m(t,n,r)}else s.buffer=a(t.slice(n,r));return s.length=e.length,s.contentLen=e.contentLen,s.type=e.type,s.version=e.version,s.flags=e.flags,s},d.encodingLength=function(e){var t=e.type,n=8;if(i.fullBoxes[t]&&(n+=4),l[t]){var r=l[t];r.forEach(function(t){if(5===t.length){var r=e[t]||[];t=t.substr(0,4),r.forEach(function(e){e.type=t,n+=d.encodingLength(e)})}else if(e[t]){var o=e[t];o.type=t,n+=d.encodingLength(o)}}),e.otherBoxes&&e.otherBoxes.forEach(function(e){n+=d.encodingLength(e)})}else if(i[t])n+=i[t].encodingLength(e);else if(e.buffer)n+=e.buffer.length;else throw new Error("Either `type` must be set to a known type (not'"+t+"') or `buffer` must be set");return n>s&&(n+=8),e.length=n,n}},{"./boxes":77,"buffer-alloc":36,"buffer-from":38,uint64be:181}],80:[function(e,t){(function(n){function r(){return this instanceof r?void(a.Writable.call(this),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()):new r}function o(e){this._parent=e,this.destroyed=!1,a.PassThrough.call(this)}var a=e("readable-stream"),i=e("inherits"),s=e("next-event"),d=e("mp4-box-encoding"),l=e("buffer-alloc"),c=l(0);t.exports=r,i(r,a.Writable),r.prototype.destroy=function(e){this.destroyed||(this.destroyed=!0,e&&this.emit("error",e),this.emit("close"))},r.prototype._write=function(e,t,n){if(!this.destroyed){for(var r=!this._str||!this._str._writableState.needDrain;e.length&&!this.destroyed;){if(!this._missing&&!this._ignoreEmpty)return this._writeBuffer=e,void(this._writeCb=n);var o=e.length=1.5*r?"s":"")}var l=24*(60*60000);n.exports=function(e,t){t=t||{};var n=typeof e;if("string"==n&&0{l("number"==typeof e.length,"info.files[0].length"),l(e["path.utf-8"]||e.path,"info.files[0].path")}):l("number"==typeof e.info.length,"info.length");const t={info:e.info,infoBuffer:c.encode(e.info),name:(e.info["name.utf-8"]||e.info.name).toString(),announce:[]};t.infoHash=g.sync(t.infoBuffer),t.infoHashBuffer=r.from(t.infoHash,"hex"),void 0!==e.info.private&&(t.private=!!e.info.private),e["creation date"]&&(t.created=new Date(1e3*e["creation date"])),e["created by"]&&(t.createdBy=e["created by"].toString()),r.isBuffer(e.comment)&&(t.comment=e.comment.toString()),Array.isArray(e["announce-list"])&&0{e.forEach(e=>{t.announce.push(e.toString())})}):e.announce&&t.announce.push(e.announce.toString()),r.isBuffer(e["url-list"])&&(e["url-list"]=0e.toString()),_(t.announce),_(t.urlList);const n=e.info.files||[e.info];t.files=n.map((e,r)=>{const o=[].concat(t.name,e["path.utf-8"]||e.path||[]).map(e=>e.toString());return{path:m.join.apply(null,[m.sep].concat(o)).slice(1),name:o[o.length-1],length:e.length,offset:n.slice(0,r).reduce(s,0)}}),t.length=n.reduce(s,0);const o=t.files[t.files.length-1];return t.pieceLength=e.info["piece length"],t.lastPieceLength=(o.offset+o.length)%t.pieceLength||t.pieceLength,t.pieces=d(e.info.pieces),t}function i(e){return"undefined"!=typeof Blob&&e instanceof Blob}function s(e,t){return e+t.length}function d(e){const t=[];for(let n=0;n{t(null,a)}):i(e)?u(e,(e,n)=>e?t(new Error(`Error converting Blob: ${e.message}`)):void r(n)):"function"==typeof f&&/^https?:/.test(e)?f.concat({url:e,timeout:30000,headers:{"user-agent":"WebTorrent (https://webtorrent.io)"}},(e,n,o)=>e?t(new Error(`Error downloading torrent: ${e.message}`)):void r(o)):"function"==typeof p.readFile&&"string"==typeof e?p.readFile(e,(e,n)=>e?t(new Error("Invalid torrent identifier")):void r(n)):n.nextTick(()=>{t(new Error("Invalid torrent identifier"))})},t.exports.toMagnetURI=h.encode,t.exports.toTorrentFile=function(e){const t={info:e.info};return t["announce-list"]=(e.announce||[]).map(e=>(t.announce||(t.announce=e),e=r.from(e,"utf8"),[e])),t["url-list"]=e.urlList||[],void 0!==e.private&&(t["private"]=+e.private),e.created&&(t["creation date"]=0|e.created.getTime()/1e3),e.createdBy&&(t["created by"]=e.createdBy),e.comment&&(t.comment=e.comment),c.encode(t)};(()=>{r.alloc(0)})()}).call(this,e("_process"),e("buffer").Buffer)},{_process:92,bencode:11,"blob-to-buffer":20,buffer:39,fs:34,"magnet-uri":74,path:89,"simple-get":123,"simple-sha1":136,uniq:182}],89:[function(e,t,n){(function(e){function t(e,t){for(var n=0,r=e.length-1,o;0<=r;r--)o=e[r],"."===o?e.splice(r,1):".."===o?(e.splice(r,1),n++):n&&(e.splice(r,1),n--);if(t)for(;n--;n)e.unshift("..");return e}function r(e){"string"!=typeof e&&(e+="");var t=0,n=-1,r=!0,o;for(o=e.length-1;0<=o;--o)if(!(47===e.charCodeAt(o)))-1===n&&(r=!1,n=o+1);else if(!r){t=o+1;break}return-1===n?"":e.slice(t,n)}function o(e,t){if(e.filter)return e.filter(t);for(var n=[],r=0;rn?[]:e.slice(t,n-t+1)}e=n.resolve(e).substr(1),t=n.resolve(t).substr(1);for(var o=r(e.split("/")),a=r(t.split("/")),s=d(o.length,a.length),l=s,c=0;ca++;)i.push(n(2,a));t.exports=function(e){return r(e/o,i)}},{"closest-to":42}],91:[function(e,t){(function(e){'use strict';t.exports="undefined"!=typeof e&&e.version&&0!==e.version.indexOf("v0.")&&(0!==e.version.indexOf("v1.")||0===e.version.indexOf("v1.8."))?e:{nextTick:function(t,n,r,o){if("function"!=typeof t)throw new TypeError("\"callback\" argument must be a function");var a=arguments.length,s,d;switch(a){case 0:case 1:return e.nextTick(t);case 2:return e.nextTick(function(){t.call(null,n)});case 3:return e.nextTick(function(){t.call(null,n,r)});case 4:return e.nextTick(function(){t.call(null,n,r,o)});default:for(s=Array(a-1),d=0;de.length)throw new Error("pump requires two streams per minimum");var n=e.map(function(o,a){var i=a=o&&n>>10),e=56320|1023&e),t+=v(e),t}).join("")}function f(e){return 10>e-48?e-22:26>e-65?e-65:26>e-97?e-97:36}function h(e,t){return e+22+75*(26>e)-((0!=t)<<5)}function m(e,t,n){var r=0;for(e=n?C(e/700):e>>1,e+=C(e/t);455u&&(u=0),h=0;h=o&&s("invalid-input"),x=f(e.charCodeAt(g++)),(36<=x||x>C((2147483647-a)/b))&&s("overflow"),a+=x*b,S=y<=l?1:y>=l+26?26:y-l,xC(2147483647/E)&&s("overflow"),b*=E}c=r.length+1,l=m(a-_,c,0==_),C(a/c)>2147483647-d&&s("overflow"),d+=C(a/c),a%=c,r.splice(a++,0,d)}return p(r)}function _(e){var r=[],o,a,i,d,l,c,p,f,g,_,b,y,w,x,S;for(e=u(e),y=e.length,o=128,a=0,l=72,c=0;cb&&r.push(v(b));for(i=d=r.length,d&&r.push("-");i=o&&bC((2147483647-a)/w)&&s("overflow"),a+=(p-o)*w,o=p,c=0;c=l+26?26:g-l,f<_)break;S=f-_,x=36-_,r.push(v(h(_+S%x,0))),f=C(S/x)}r.push(v(h(f,0))),l=m(a,w,i==d),a=0,++i}++a,++o}return r.join("")}var b="object"==typeof n&&n&&!n.nodeType&&n,y="object"==typeof t&&t&&!t.nodeType&&t,w="object"==typeof e&&e;(w.global===w||w.window===w||w.self===w)&&(a=w);var k=/^xn--/,x=/[^\x20-\x7E]/,S=/[\x2E\u3002\uFF0E\uFF61]/g,E={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},C=r,v=o,L,I;if(L={version:"1.4.1",ucs2:{decode:u,encode:p},decode:g,encode:_,toASCII:function(e){return c(e,function(e){return x.test(e)?"xn--"+_(e):e})},toUnicode:function(e){return c(e,function(e){return k.test(e)?g(e.slice(4).toLowerCase()):e})}},"function"==typeof l&&"object"==typeof l.amd&&l.amd)l("punycode",function(){return L});else if(!(b&&y))a.punycode=L;else if(t.exports==b)y.exports=L;else for(I in L)L.hasOwnProperty(I)&&(b[I]=L[I])})(this)}).call(this,"undefined"==typeof global?"undefined"==typeof self?"undefined"==typeof window?{}:window:self:global)},{}],95:[function(e,t){'use strict';function n(e,t){return Object.prototype.hasOwnProperty.call(e,t)}t.exports=function(e,t,o,a){t=t||"&",o=o||"=";var s={};if("string"!=typeof e||0===e.length)return s;var d=/\+/g;e=e.split(t);var l=1e3;a&&"number"==typeof a.maxKeys&&(l=a.maxKeys);var c=e.length;0l&&(c=l);for(var u=0;u4294967295)throw new RangeError("requested too many random bytes");var r=o.allocUnsafe(e);if(0=e.length)return this._position+=e.length,n(null);let i;if(a>e.length){this._position+=e.length,i=0===t?e:e.slice(t),r=o.stream.write(i)&&r;break}this._position+=a,i=0===t&&a===e.length?e:e.slice(t,a),r=o.stream.write(i)&&r,o.last&&o.stream.end(),e=e.slice(a),this._queue.shift()}r?n(null):o.stream.once("drain",n.bind(null,null))}slice(e){if(this.destroyed)return null;Array.isArray(e)||(e=[e]);const t=new r;return e.forEach((n,r)=>{this._queue.push({start:n.start,end:n.end,stream:t,last:r===e.length-1})}),this._buffer&&this._write(this._buffer,null,this._cb),t}destroy(e){this.destroyed||(this.destroyed=!0,e&&this.emit("error",e))}}},{"readable-stream":115}],101:[function(e,t){'use strict';function n(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,e.__proto__=t}function r(e,t,r){function o(e,n,r){return"string"==typeof t?t:t(e,n,r)}r||(r=Error);var a=function(e){function t(t,n,r){return e.call(this,o(t,n,r))||this}return n(t,e),t}(r);a.prototype.name=r.name,a.prototype.code=e,d[e]=a}function o(e,t){if(Array.isArray(e)){var n=e.length;return e=e.map(function(e){return e+""}),2n?0:+n,t.length)===t}function i(e,t,n){return(void 0===n||n>e.length)&&(n=e.length),e.substring(n-t.length,n)===t}function s(e,t,n){return"number"!=typeof n&&(n=0),!(n+t.length>e.length)&&-1!==e.indexOf(t,n)}var d={};r("ERR_INVALID_OPT_VALUE",function(e,t){return"The value \""+t+"\" is invalid for option \""+e+"\""},TypeError),r("ERR_INVALID_ARG_TYPE",function(e,t,n){var r;"string"==typeof t&&a(t,"not ")?(r="must not be",t=t.replace(/^not /,"")):r="must be";var d;if(i(e," argument"))d="The ".concat(e," ").concat(r," ").concat(o(t,"type"));else{var l=s(e,".")?"property":"argument";d="The \"".concat(e,"\" ").concat(l," ").concat(r," ").concat(o(t,"type"))}return d+=". Received type ".concat(typeof n),d},TypeError),r("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF"),r("ERR_METHOD_NOT_IMPLEMENTED",function(e){return"The "+e+" method is not implemented"}),r("ERR_STREAM_PREMATURE_CLOSE","Premature close"),r("ERR_STREAM_DESTROYED",function(e){return"Cannot call "+e+" after a stream was destroyed"}),r("ERR_MULTIPLE_CALLBACK","Callback called multiple times"),r("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable"),r("ERR_STREAM_WRITE_AFTER_END","write after end"),r("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),r("ERR_UNKNOWN_ENCODING",function(e){return"Unknown encoding: "+e},TypeError),r("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event"),t.exports.codes=d},{}],102:[function(e,t){(function(e){'use strict';var n=new Set;t.exports.emitExperimentalWarning=e.emitWarning?function(t){if(!n.has(t)){n.add(t),e.emitWarning(t+" is an experimental feature. This feature could change at any time","ExperimentalWarning")}}:function(){}}).call(this,e("_process"))},{_process:92}],103:[function(e,t){(function(n){'use strict';function r(e){return this instanceof r?void(s.call(this,e),d.call(this,e),this.allowHalfOpen=!0,e&&(!1===e.readable&&(this.readable=!1),!1===e.writable&&(this.writable=!1),!1===e.allowHalfOpen&&(this.allowHalfOpen=!1,this.once("end",o)))):new r(e)}function o(){this._writableState.ended||n.nextTick(a,this)}function a(e){e.end()}var i=Object.keys||function(e){var t=[];for(var n in e)t.push(n);return t};t.exports=r;var s=e("./_stream_readable"),d=e("./_stream_writable");e("inherits")(r,s);for(var l=i(d.prototype),c=0,u;c>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}function f(e,t){return 0>=e||0===t.length&&t.ended?0:t.objectMode?1:e===e?(e>t.highWaterMark&&(t.highWaterMark=p(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0)):t.flowing&&t.length?t.buffer.head.data.length:t.length}function h(e,t){if(!t.ended){if(t.decoder){var n=t.decoder.end();n&&n.length&&(t.buffer.push(n),t.length+=t.objectMode?1:n.length)}t.ended=!0,t.sync?m(e):(t.needReadable=!1,!t.emittedReadable&&(t.emittedReadable=!0,g(e)))}}function m(e){var t=e._readableState;t.needReadable=!1,t.emittedReadable||(O("emitReadable",t.flowing),t.emittedReadable=!0,n.nextTick(g,e))}function g(e){var t=e._readableState;O("emitReadable_",t.destroyed,t.length,t.ended),!t.destroyed&&(t.length||t.ended)&&e.emit("readable"),t.needReadable=!t.flowing&&!t.ended&&t.length<=t.highWaterMark,E(e)}function _(e,t){t.readingMore||(t.readingMore=!0,n.nextTick(b,e,t))}function b(e,t){for(;!t.reading&&!t.ended&&(t.length=t.length?(n=t.decoder?t.buffer.join(""):1===t.buffer.length?t.buffer.first():t.buffer.concat(t.length),t.buffer.clear()):n=t.buffer.consume(e,t.decoder),n}function v(e){var t=e._readableState;O("endReadable",t.endEmitted),t.endEmitted||(t.ended=!0,n.nextTick(L,t,e))}function L(e,t){O("endReadableNT",e.endEmitted,e.length),e.endEmitted||0!==e.length||(e.endEmitted=!0,t.readable=!1,t.emit("end"))}function I(e,t){for(var n=0,r=e.length;n=t.highWaterMark)||t.ended))return O("read: emitReadable",t.length,t.ended),0===t.length&&t.ended?v(this):m(this),null;if(e=f(e,t),0===e&&t.ended)return 0===t.length&&v(this),null;var o=t.needReadable;O("need readable",o),(0===t.length||t.length-e>>0),n=this.head,r=0;n;)o(n.data,t,r),r+=n.data.length,n=n.next;return t},t.consume=function(e,t){var n;return ea.length?a.length:e;if(o+=i===a.length?a:a.slice(0,e),e-=i,0===e){i===a.length?(++r,this.head=t.next?t.next:this.tail=null):(this.head=t,t.data=a.slice(i));break}++r}return this.length-=r,o},t._getBuffer=function(e){var t=s.allocUnsafe(e),r=this.head,o=1;for(r.data.copy(t),e-=r.data.length;r=r.next;){var a=r.data,i=e>a.length?a.length:e;if(a.copy(t,t.length-e,0,i),e-=i,0===e){i===a.length?(++o,this.head=r.next?r.next:this.tail=null):(this.head=r,r.data=a.slice(i));break}++o}return this.length-=o,t},t[c]=function(e,t){return l(this,n({},t,{depth:0,customInspect:!1}))},e}()},{buffer:39,util:33}],110:[function(e,t){(function(e){'use strict';function n(e,t){o(e,t),r(e)}function r(e){e._writableState&&!e._writableState.emitClose||e._readableState&&!e._readableState.emitClose||e.emit("close")}function o(e,t){e.emit("error",t)}t.exports={destroy:function(t,a){var i=this,s=this._readableState&&this._readableState.destroyed,d=this._writableState&&this._writableState.destroyed;return s||d?(a?a(t):t&&(!this._writableState||!this._writableState.errorEmitted)&&e.nextTick(o,this,t),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(t||null,function(t){!a&&t?(e.nextTick(n,i,t),i._writableState&&(i._writableState.errorEmitted=!0)):a?(e.nextTick(r,i),a(t)):e.nextTick(r,i)}),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)}}}).call(this,e("_process"))},{_process:92}],111:[function(e,t){'use strict';function n(e){var t=!1;return function(){if(!t){t=!0;for(var n=arguments.length,r=Array(n),o=0;ot.length)throw new c("streams");var o=t.map(function(e,n){var s=ns){var d=i?a:"highWaterMark";throw new o(d,s)}return r(s)}return e.objectMode?16:16384}}},{"../../../errors":101}],114:[function(e,t,n){arguments[4][29][0].apply(n,arguments)},{dup:29,events:49}],115:[function(e,t,n){n=t.exports=e("./lib/_stream_readable.js"),n.Stream=n,n.Readable=n,n.Writable=e("./lib/_stream_writable.js"),n.Duplex=e("./lib/_stream_duplex.js"),n.Transform=e("./lib/_stream_transform.js"),n.PassThrough=e("./lib/_stream_passthrough.js"),n.finished=e("./lib/internal/streams/end-of-stream.js"),n.pipeline=e("./lib/internal/streams/pipeline.js")},{"./lib/_stream_duplex.js":103,"./lib/_stream_passthrough.js":104,"./lib/_stream_readable.js":105,"./lib/_stream_transform.js":106,"./lib/_stream_writable.js":107,"./lib/internal/streams/end-of-stream.js":111,"./lib/internal/streams/pipeline.js":112}],116:[function(e,t,n){function r(e,t,n,r){function a(){return!("number"==typeof e.length&&e.length>n.maxBlobLength)||(d("File length too large for Blob URL approach: %d (max: %d)",e.length,n.maxBlobLength),E(new Error("File length too large for Blob URL approach: "+e.length+" (max: "+n.maxBlobLength+")")),!1)}function s(n){a()&&(L=t(n),o(e,function(e,t){return e?E(e):void(L.addEventListener("error",E),L.addEventListener("loadstart",p),L.addEventListener("canplay",x),L.src=t)}))}function p(){L.removeEventListener("loadstart",p),n.autoplay&&L.play()}function x(){L.removeEventListener("canplay",x),r(null,L)}function S(){o(e,function(e,n){return e?E(e):void(".pdf"===C?(L=t("object"),L.setAttribute("typemustmatch",!0),L.setAttribute("type","application/pdf"),L.setAttribute("data",n)):(L=t("iframe"),L.sandbox="allow-forms allow-scripts",L.src=n),r(null,L))})}function E(t){t.message="Error rendering file \""+e.name+"\": "+t.message,d(t.message),r(t)}var C=u.extname(e.name).toLowerCase(),v=0,L;0<=g.indexOf(C)?function(){function n(){d("Use `videostream` package for "+e.name),g(),L.addEventListener("error",l),L.addEventListener("loadstart",p),L.addEventListener("canplay",x),f(e,L)}function r(){d("Use MediaSource API for "+e.name),g(),L.addEventListener("error",u),L.addEventListener("loadstart",p),L.addEventListener("canplay",x);var t=new c(L),n=t.createWriteStream(i(e.name));e.createReadStream().pipe(n),v&&(L.currentTime=v)}function s(){d("Use Blob URL for "+e.name),g(),L.addEventListener("error",E),L.addEventListener("loadstart",p),L.addEventListener("canplay",x),o(e,function(e,t){return e?E(e):void(L.src=t,v&&(L.currentTime=v))})}function l(e){d("videostream error: fallback to MediaSource API: %o",e.message||e),L.removeEventListener("error",l),L.removeEventListener("canplay",x),r()}function u(e){d("MediaSource API error: fallback to Blob URL: %o",e.message||e);a()&&(L.removeEventListener("error",u),L.removeEventListener("canplay",x),s())}function g(){L||(L=t(_),L.addEventListener("progress",function(){v=L.currentTime}))}var _=0<=m.indexOf(C)?"video":"audio";k?0<=h.indexOf(C)?n():r():s()}():0<=_.indexOf(C)?s("video"):0<=b.indexOf(C)?s("audio"):0<=y.indexOf(C)?function(){L=t("img"),o(e,function(t,n){return t?E(t):void(L.src=n,L.alt=e.name,r(null,L))})}():0<=w.indexOf(C)?S():function(){function t(){l(n)?(d("File extension \"%s\" appears ascii, so will render.",C),S()):(d("File extension \"%s\" appears non-ascii, will not render.",C),r(new Error("Unsupported file type \""+C+"\": Cannot append to DOM")))}d("Unknown file extension \"%s\" - will attempt to render into iframe",C);var n="";e.createReadStream({start:0,end:1e3}).setEncoding("utf8").on("data",function(e){n+=e}).on("end",t).on("error",r)}()}function o(e,t){var r=u.extname(e.name).toLowerCase();p(e.createReadStream(),n.mime[r],t)}function a(e){if(null==e)throw new Error("file cannot be null or undefined");if("string"!=typeof e.name)throw new Error("missing or invalid file.name property");if("function"!=typeof e.createReadStream)throw new Error("missing or invalid file.createReadStream property")}function i(e){var t=u.extname(e).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\""}[t]}function s(e){null==e.autoplay&&(e.autoplay=!1),null==e.muted&&(e.muted=!1),null==e.controls&&(e.controls=!0),null==e.maxBlobLength&&(e.maxBlobLength=200000000)}n.render=function(e,t,n,o){"function"==typeof n&&(o=n,n={}),n||(n={}),o||(o=function(){}),a(e),s(n),"string"==typeof t&&(t=document.querySelector(t)),r(e,function(n){if(t.nodeName!==n.toUpperCase()){var r=u.extname(e.name).toLowerCase();throw new Error("Cannot render \""+r+"\" inside a \""+t.nodeName.toLowerCase()+"\" element, expected \""+n+"\"")}return t},n,o)},n.append=function(e,t,n,o){function i(e){var r=d(e);return n.autoplay&&(r.autoplay=!0),n.muted&&(r.muted=!0),n.controls&&(r.controls=!0),t.appendChild(r),r}function d(e){var n=document.createElement(e);return t.appendChild(n),n}function l(e,t){e&&t&&t.remove(),o(e,t)}if("function"==typeof n&&(o=n,n={}),n||(n={}),o||(o=function(){}),a(e),s(n),"string"==typeof t&&(t=document.querySelector(t)),t&&("VIDEO"===t.nodeName||"AUDIO"===t.nodeName))throw new Error("Invalid video/audio node argument. Argument must be root element that video/audio tag will be appended to.");r(e,function(e){return"video"===e||"audio"===e?i(e):d(e)},n,l)},n.mime=e("./lib/mime.json");var d=e("debug")("render-media"),l=e("is-ascii"),c=e("mediasource"),u=e("path"),p=e("stream-to-blob-url"),f=e("videostream"),h=[".m4a",".m4b",".m4p",".m4v",".mp4"],m=[".m4v",".mkv",".mp4",".webm"],g=[].concat(m,[".m4a",".m4b",".m4p",".mp3"]),_=[".mov",".ogv"],b=[".aac",".oga",".ogg",".wav",".flac"],y=[".bmp",".gif",".jpeg",".jpg",".png",".svg"],w=[".css",".html",".js",".md",".pdf",".txt"],k="undefined"!=typeof window&&window.MediaSource},{"./lib/mime.json":117,debug:45,"is-ascii":68,mediasource:75,path:89,"stream-to-blob-url":167,videostream:190}],117:[function(e,t){t.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"}},{}],118:[function(e,t){(function(e){t.exports=function(t,n,r){function o(t){function n(){r&&r(t,s),r=null}i?e.nextTick(n):n()}function a(e,n,r){if(s[e]=r,n&&(u=!0),0==--l||n)o(n);else if(!u&&p>2)+1;a>2]|=128<<24-(t%4<<3),e[(-16&(t>>2)+2)+14]=0|n/536870912,e[(-16&(t>>2)+2)+15]=n<<3},f=function(e,t){var n=new Int32Array(e,t+320,5),r=new Int32Array(5),o=new DataView(r.buffer);return o.setInt32(0,n[0],!1),o.setInt32(4,n[1],!1),o.setInt32(8,n[2],!1),o.setInt32(12,n[3],!1),o.setInt32(16,n[4],!1),r},h=function(){function e(t){if(r(this,e),t=t||65536,0>2);return u(r,e),p(r,e,t),n},e.prototype._write=function(e,t,n,r){l(e,this._h8,this._h32,t,n,r||0)},e.prototype._coreCall=function(e,t,n,r,o){var a=n;this._write(e,t,n),o&&(a=this._padChunk(n,r)),this._core.hash(a,this._padMaxChunkLen)},e.prototype.rawDigest=function(e){var t=e.byteLength||e.length||e.size||0;this._initState(this._heap,this._padMaxChunkLen);var n=0,r=this._maxChunkLen;for(n=0;t>n+r;n+=r)this._coreCall(e,n,r,t,!1);return this._coreCall(e,n,t-n,t,!0),f(this._heap,this._padMaxChunkLen)},e.prototype.digest=function(e){return i(this.rawDigest(e).buffer)},e.prototype.digestFromString=function(e){return this.digest(e)},e.prototype.digestFromBuffer=function(e){return this.digest(e)},e.prototype.digestFromArrayBuffer=function(e){return this.digest(e)},e.prototype.resetState=function(){return this._initState(this._heap,this._padMaxChunkLen),this},e.prototype.append=function(e){var t=0,n=e.byteLength||e.length||e.size||0,r=this._offset%this._maxChunkLen,o=void 0;for(this._offset+=n;tn;n++)t[n]=(16>n?"0":"")+n.toString(16);e.exports.toHex=function(e){for(var n=new Uint8Array(e),r=Array(e.byteLength),o=0;o=e)return 65536;if(16777216>e)for(t=1;t>2],s=0|r[t+324>>2],l=0|r[t+328>>2],u=0|r[t+332>>2],f=0|r[t+336>>2],n=0;(0|n)<(0|e);n=0|n+64){for(i=a,d=s,c=l,p=u,h=f,o=0;64>(0|o);o=0|o+4)g=0|r[n+o>>2],m=0|(0|(a<<5|a>>>27)+(s&l|~s&u))+(0|(0|g+f)+1518500249),f=u,u=l,l=s<<30|s>>>2,s=a,a=m,r[e+o>>2]=g;for(o=0|e+64;(0|o)<(0|e+80);o=0|o+4)g=(r[o-12>>2]^r[o-32>>2]^r[o-56>>2]^r[o-64>>2])<<1|(r[o-12>>2]^r[o-32>>2]^r[o-56>>2]^r[o-64>>2])>>>31,m=0|(0|(a<<5|a>>>27)+(s&l|~s&u))+(0|(0|g+f)+1518500249),f=u,u=l,l=s<<30|s>>>2,s=a,a=m,r[o>>2]=g;for(o=0|e+80;(0|o)<(0|e+160);o=0|o+4)g=(r[o-12>>2]^r[o-32>>2]^r[o-56>>2]^r[o-64>>2])<<1|(r[o-12>>2]^r[o-32>>2]^r[o-56>>2]^r[o-64>>2])>>>31,m=0|(0|(a<<5|a>>>27)+(s^l^u))+(0|(0|g+f)+1859775393),f=u,u=l,l=s<<30|s>>>2,s=a,a=m,r[o>>2]=g;for(o=0|e+160;(0|o)<(0|e+240);o=0|o+4)g=(r[o-12>>2]^r[o-32>>2]^r[o-56>>2]^r[o-64>>2])<<1|(r[o-12>>2]^r[o-32>>2]^r[o-56>>2]^r[o-64>>2])>>>31,m=0|(0|(a<<5|a>>>27)+(s&l|s&u|l&u))+(0|(0|g+f)-1894007588),f=u,u=l,l=s<<30|s>>>2,s=a,a=m,r[o>>2]=g;for(o=0|e+240;(0|o)<(0|e+320);o=0|o+4)g=(r[o-12>>2]^r[o-32>>2]^r[o-56>>2]^r[o-64>>2])<<1|(r[o-12>>2]^r[o-32>>2]^r[o-56>>2]^r[o-64>>2])>>>31,m=0|(0|(a<<5|a>>>27)+(s^l^u))+(0|(0|g+f)-899497514),f=u,u=l,l=s<<30|s>>>2,s=a,a=m,r[o>>2]=g;a=0|a+i,s=0|s+d,l=0|l+c,u=0|u+p,f=0|f+h}r[t+320>>2]=a,r[t+324>>2]=s,r[t+328>>2]=l,r[t+332>>2]=u,r[t+336>>2]=f}}}},function(e){var t=this,n=void 0;"undefined"!=typeof self&&"undefined"!=typeof self.FileReaderSync&&(n=new self.FileReaderSync);var r=function(e,t,n,r,o,a){var s=a%4,d=(o+s)%4,l=o-d,c;switch(s){case 0:t[a]=e.charCodeAt(r+3);case 1:t[0|a+1-(s<<1)]=e.charCodeAt(r+2);case 2:t[0|a+2-(s<<1)]=e.charCodeAt(r+1);case 3:t[0|a+3-(s<<1)]=e.charCodeAt(r);}if(!(o>2]=e.charCodeAt(r+c)<<24|e.charCodeAt(r+c+1)<<16|e.charCodeAt(r+c+2)<<8|e.charCodeAt(r+c+3);switch(d){case 3:t[0|a+l+1]=e.charCodeAt(r+l+2);case 2:t[0|a+l+2]=e.charCodeAt(r+l+1);case 1:t[0|a+l+3]=e.charCodeAt(r+l);}}},o=function(e,t,n,r,o,a){var s=a%4,d=(o+s)%4,l=o-d,c;switch(s){case 0:t[a]=e[r+3];case 1:t[0|a+1-(s<<1)]=e[r+2];case 2:t[0|a+2-(s<<1)]=e[r+1];case 3:t[0|a+3-(s<<1)]=e[r];}if(!(o>2]=e[r+c]<<24|e[r+c+1]<<16|e[r+c+2]<<8|e[r+c+3];switch(d){case 3:t[0|a+l+1]=e[r+l+2];case 2:t[0|a+l+2]=e[r+l+1];case 1:t[0|a+l+3]=e[r+l];}}},a=function(e,t,r,o,a,s){var d=void 0,l=s%4,c=(a+l)%4,u=a-c,p=new Uint8Array(n.readAsArrayBuffer(e.slice(o,o+a)));switch(l){case 0:t[s]=p[3];case 1:t[0|s+1-(l<<1)]=p[2];case 2:t[0|s+2-(l<<1)]=p[1];case 3:t[0|s+3-(l<<1)]=p[0];}if(!(a>2]=p[d]<<24|p[d+1]<<16|p[d+2]<<8|p[d+3];switch(c){case 3:t[0|s+u+1]=p[u+2];case 2:t[0|s+u+2]=p[u+1];case 1:t[0|s+u+3]=p[u];}}};e.exports=function(e,n,i,s,d,l){if("string"==typeof e)return r(e,n,i,s,d,l);if(e instanceof Array)return o(e,n,i,s,d,l);if(t&&t.Buffer&&t.Buffer.isBuffer(e))return o(e,n,i,s,d,l);if(e instanceof ArrayBuffer)return o(new Uint8Array(e),n,i,s,d,l);if(e.buffer instanceof ArrayBuffer)return o(new Uint8Array(e.buffer,e.byteOffset,e.byteLength),n,i,s,d,l);if(e instanceof Blob)return a(e,n,i,s,d,l);throw new Error("Unsupported data type.")}},function(e,t,n){function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}var o=n(0),a=n(1),i=a.toHex,s=function(){function e(){r(this,e),this._rusha=new o,this._rusha.resetState()}return e.prototype.update=function(e){return this._rusha.append(e),this},e.prototype.digest=function e(t){var e=this._rusha.rawEnd().buffer;if(!t)return e;if("hex"===t)return i(e);throw new Error("unsupported digest encoding")},e}();e.exports=function(){return new s}}])})},{}],121:[function(e,t,n){function r(e,t){for(var n in e)t[n]=e[n]}function o(e,t,n){return i(e,t,n)}var a=e("buffer"),i=a.Buffer;i.from&&i.alloc&&i.allocUnsafe&&i.allocUnsafeSlow?t.exports=a:(r(a,n),n.Buffer=o),o.prototype=Object.create(i.prototype),r(i,o),o.from=function(e,t,n){if("number"==typeof e)throw new TypeError("Argument must not be a number");return i(e,t,n)},o.alloc=function(e,t,n){if("number"!=typeof e)throw new TypeError("Argument must be a number");var r=i(e);return void 0===t?r.fill(0):"string"==typeof n?r.fill(t,n):r.fill(t),r},o.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return i(e)},o.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return a.SlowBuffer(e)}},{buffer:39}],122:[function(e,t){(function(e){t.exports=function(t,n){var r=[];t.on("data",function(e){r.push(e)}),t.once("end",function(){n&&n(null,e.concat(r)),n=null}),t.once("error",function(e){n&&n(e),n=null})}}).call(this,e("buffer").Buffer)},{buffer:39}],123:[function(e,t){(function(n){function r(e,t){if(e=Object.assign({maxRedirects:10},"string"==typeof e?{url:e}:e),t=d(t),e.url){const{hostname:t,port:n,protocol:r,auth:o,path:a}=c.parse(e.url);delete e.url,t||n||r||o?Object.assign(e,{hostname:t,port:n,protocol:r,auth:o,path:a}):e.path=a}const o={"accept-encoding":"gzip, deflate"};e.headers&&Object.keys(e.headers).forEach(t=>o[t.toLowerCase()]=e.headers[t]),e.headers=o;let p;e.body?p=e.json&&!u(e.body)?JSON.stringify(e.body):e.body:e.form&&(p="string"==typeof e.form?e.form:l.stringify(e.form),e.headers["content-type"]="application/x-www-form-urlencoded"),p&&(!e.method&&(e.method="POST"),!u(p)&&(e.headers["content-length"]=n.byteLength(p)),e.json&&!e.form&&(e.headers["content-type"]="application/json")),delete e.body,delete e.form,e.json&&(e.headers.accept="application/json"),e.method&&(e.method=e.method.toUpperCase());const f="https:"===e.protocol?s:i,h=f.request(e,n=>{if(300<=n.statusCode&&400>n.statusCode&&n.headers.location)return e.url=n.headers.location,delete e.headers.host,n.resume(),"POST"===e.method&&[301,302].includes(n.statusCode)&&(e.method="GET",delete e.headers["content-length"],delete e.headers["content-type"]),0==e.maxRedirects--?t(new Error("too many redirects")):r(e,t);const o="function"==typeof a&&"HEAD"!==e.method;t(null,o?a(n):n)});return h.on("timeout",()=>{h.abort(),t(new Error("Request timed out"))}),h.on("error",t),u(p)?p.on("error",t).pipe(h):h.end(p),h}t.exports=r;const o=e("simple-concat"),a=e("decompress-response"),i=e("http"),s=e("https"),d=e("once"),l=e("querystring"),c=e("url"),u=e=>null!==e&&"object"==typeof e&&"function"==typeof e.pipe;r.concat=(e,t)=>r(e,(n,r)=>n?t(n):void o(r,(n,o)=>{if(n)return t(n);if(e.json)try{o=JSON.parse(o.toString())}catch(e){return t(e,r,o)}t(null,r,o)})),["get","post","put","patch","head","delete"].forEach(e=>{r[e]=(t,n)=>("string"==typeof t&&(t={url:t}),r(Object.assign({method:e.toUpperCase()},t),n))})}).call(this,e("buffer").Buffer)},{buffer:39,"decompress-response":33,http:152,https:64,once:86,querystring:97,"simple-concat":122,url:184}],124:[function(e,t){(function(n){function r(e){var t=this;if(!(t instanceof r))return new r(e);if(t._id=l(4).toString("hex").slice(0,7),t._debug("new peer %o",e),e=Object.assign({allowHalfOpen:!1},e),c.Duplex.call(t,e),t.channelName=e.initiator?e.channelName||l(20).toString("hex"):null,t.initiator=e.initiator||!1,t.channelConfig=e.channelConfig||r.channelConfig,t.config=Object.assign({},r.config,e.config),t.offerOptions=e.offerOptions||{},t.answerOptions=e.answerOptions||{},t.sdpTransform=e.sdpTransform||function(e){return e},t.streams=e.streams||(e.stream?[e.stream]:[]),t.trickle=void 0===e.trickle||e.trickle,t.allowHalfTrickle=void 0!==e.allowHalfTrickle&&e.allowHalfTrickle,t.iceCompleteTimeout=e.iceCompleteTimeout||5000,t.destroyed=!1,t.connected=!1,t.remoteAddress=void 0,t.remoteFamily=void 0,t.remotePort=void 0,t.localAddress=void 0,t.localFamily=void 0,t.localPort=void 0,t._wrtc=e.wrtc&&"object"==typeof e.wrtc?e.wrtc:s(),!t._wrtc)if("undefined"==typeof window)throw a("No WebRTC support: Specify `opts.wrtc` option in this environment","ERR_WEBRTC_SUPPORT");else throw a("No WebRTC support: Not a supported browser","ERR_WEBRTC_SUPPORT");t._pcReady=!1,t._channelReady=!1,t._iceComplete=!1,t._iceCompleteTimer=null,t._channel=null,t._pendingCandidates=[],t._isNegotiating=!t.initiator,t._batchedNegotiation=!1,t._queuedNegotiation=!1,t._sendersAwaitingStable=[],t._senderMap=new Map,t._firstStable=!0,t._closingInterval=null,t._remoteTracks=[],t._remoteStreams=[],t._chunk=null,t._cb=null,t._interval=null;try{t._pc=new t._wrtc.RTCPeerConnection(t.config)}catch(e){t.destroy(e)}t._isReactNativeWebrtc="number"==typeof t._pc._peerConnectionId,t._pc.oniceconnectionstatechange=function(){t._onIceStateChange()},t._pc.onicegatheringstatechange=function(){t._onIceStateChange()},t._pc.onsignalingstatechange=function(){t._onSignalingStateChange()},t._pc.onicecandidate=function(e){t._onIceCandidate(e)},t.initiator?t._setupData({channel:t._pc.createDataChannel(t.channelName,t.channelConfig)}):t._pc.ondatachannel=function(e){t._setupData(e)},t.streams&&t.streams.forEach(function(e){t.addStream(e)}),t._pc.ontrack=function(e){t._onTrack(e)},t.initiator&&t._needsNegotiation(),t._onFinishBound=function(){t._onFinish()},t.once("finish",t._onFinishBound)}function o(e){return e.replace(/a=ice-options:trickle\s\n/g,"")}function a(e,t){var n=new Error(e);return n.code=t,n}t.exports=r;var i=e("debug")("simple-peer"),s=e("get-browser-rtc"),d=e("inherits"),l=e("randombytes"),c=e("readable-stream"),u=65536;d(r,c.Duplex),r.WEBRTC_SUPPORT=!!s(),r.config={iceServers:[{urls:"stun:stun.l.google.com:19302"},{urls:"stun:global.stun.twilio.com:3478?transport=udp"}],sdpSemantics:"unified-plan"},r.channelConfig={},Object.defineProperty(r.prototype,"bufferSize",{get:function(){var e=this;return e._channel&&e._channel.bufferedAmount||0}}),r.prototype.address=function(){var e=this;return{port:e.localPort,family:e.localFamily,address:e.localAddress}},r.prototype.signal=function(e){var t=this;if(t.destroyed)throw a("cannot signal after peer is destroyed","ERR_SIGNALING");if("string"==typeof e)try{e=JSON.parse(e)}catch(t){e={}}t._debug("signal()"),e.renegotiate&&t.initiator&&(t._debug("got request to renegotiate"),t._needsNegotiation()),e.transceiverRequest&&t.initiator&&(t._debug("got request for transceiver"),t.addTransceiver(e.transceiverRequest.kind,e.transceiverRequest.init)),e.candidate&&(t._pc.localDescription&&t._pc.localDescription.type&&t._pc.remoteDescription&&t._pc.remoteDescription.type?t._addIceCandidate(e.candidate):t._pendingCandidates.push(e.candidate)),e.sdp&&t._pc.setRemoteDescription(new t._wrtc.RTCSessionDescription(e)).then(function(){t.destroyed||(t._pendingCandidates.forEach(function(e){t._addIceCandidate(e)}),t._pendingCandidates=[],"offer"===t._pc.remoteDescription.type&&t._createAnswer())}).catch(function(e){t.destroy(a(e,"ERR_SET_REMOTE_DESCRIPTION"))}),e.sdp||e.candidate||e.renegotiate||e.transceiverRequest||t.destroy(a("signal() called with invalid signal data","ERR_SIGNALING"))},r.prototype._addIceCandidate=function(e){var t=this;t._pc.addIceCandidate(new t._wrtc.RTCIceCandidate(e)).catch(function(e){t.destroy(a(e,"ERR_ADD_ICE_CANDIDATE"))})},r.prototype.send=function(e){var t=this;t._channel.send(e)},r.prototype.addTransceiver=function(e,t){var n=this;if(n._debug("addTransceiver()"),n.initiator)try{n._pc.addTransceiver(e,t),n._needsNegotiation()}catch(e){n.destroy(e)}else n.emit("signal",{transceiverRequest:{kind:e,init:t}})},r.prototype.addStream=function(e){var t=this;t._debug("addStream()"),e.getTracks().forEach(function(n){t.addTrack(n,e)})},r.prototype.addTrack=function(e,t){var n=this;n._debug("addTrack()");var r=n._senderMap.get(e)||new Map,o=r.get(t);o?o.removed?n.destroy(a("Track has been removed. You should enable/disable tracks that you want to re-add."),"ERR_SENDER_REMOVED"):n.destroy(a("Track has already been added to that stream."),"ERR_SENDER_ALREADY_ADDED"):(o=n._pc.addTrack(e,t),r.set(t,o),n._senderMap.set(e,r),n._needsNegotiation())},r.prototype.replaceTrack=function(e,t,n){var r=this;r._debug("replaceTrack()");var o=r._senderMap.get(e),i=o?o.get(n):null;i||r.destroy(a("Cannot replace track that was never added."),"ERR_TRACK_NOT_ADDED"),t&&r._senderMap.set(t,o),null==i.replaceTrack?r.destroy(a("replaceTrack is not supported in this browser","ERR_UNSUPPORTED_REPLACETRACK")):i.replaceTrack(t)},r.prototype.removeTrack=function(e,t){var n=this;n._debug("removeSender()");var r=n._senderMap.get(e),o=r?r.get(t):null;o||n.destroy(a("Cannot remove track that was never added.","ERR_TRACK_NOT_ADDED"));try{o.removed=!0,n._pc.removeTrack(o)}catch(e){"NS_ERROR_UNEXPECTED"===e.name?n._sendersAwaitingStable.push(o):n.destroy(e)}n._needsNegotiation()},r.prototype.removeStream=function(e){var t=this;t._debug("removeSenders()"),e.getTracks().forEach(function(n){t.removeTrack(n,e)})},r.prototype._needsNegotiation=function(){var e=this;e._debug("_needsNegotiation");e._batchedNegotiation||(e._batchedNegotiation=!0,setTimeout(function(){e._batchedNegotiation=!1,e._debug("starting batched negotiation"),e.negotiate()},0))},r.prototype.negotiate=function(){var e=this;e.initiator?e._isNegotiating?(e._queuedNegotiation=!0,e._debug("already negotiating, queueing")):(e._debug("start negotiation"),setTimeout(()=>{e._createOffer()},0)):!e._isNegotiating&&(e._debug("requesting negotiation from initiator"),e.emit("signal",{renegotiate:!0})),e._isNegotiating=!0},r.prototype.destroy=function(e){var t=this;t._destroy(e,function(){})},r.prototype._destroy=function(e,t){var n=this;if(!n.destroyed){if(n._debug("destroy (error: %s)",e&&(e.message||e)),n.readable=n.writable=!1,n._readableState.ended||n.push(null),n._writableState.finished||n.end(),n.destroyed=!0,n.connected=!1,n._pcReady=!1,n._channelReady=!1,n._remoteTracks=null,n._remoteStreams=null,n._senderMap=null,clearInterval(n._closingInterval),n._closingInterval=null,clearInterval(n._interval),n._interval=null,n._chunk=null,n._cb=null,n._onFinishBound&&n.removeListener("finish",n._onFinishBound),n._onFinishBound=null,n._channel){try{n._channel.close()}catch(e){}n._channel.onmessage=null,n._channel.onopen=null,n._channel.onclose=null,n._channel.onerror=null}if(n._pc){try{n._pc.close()}catch(e){}n._pc.oniceconnectionstatechange=null,n._pc.onicegatheringstatechange=null,n._pc.onsignalingstatechange=null,n._pc.onicecandidate=null,n._pc.ontrack=null,n._pc.ondatachannel=null}n._pc=null,n._channel=null,e&&n.emit("error",e),n.emit("close"),t()}},r.prototype._setupData=function(e){var t=this;if(!e.channel)return t.destroy(a("Data channel event is missing `channel` property","ERR_DATA_CHANNEL"));t._channel=e.channel,t._channel.binaryType="arraybuffer","number"==typeof t._channel.bufferedAmountLowThreshold&&(t._channel.bufferedAmountLowThreshold=u),t.channelName=t._channel.label,t._channel.onmessage=function(e){t._onChannelMessage(e)},t._channel.onbufferedamountlow=function(){t._onChannelBufferedAmountLow()},t._channel.onopen=function(){t._onChannelOpen()},t._channel.onclose=function(){t._onChannelClose()},t._channel.onerror=function(e){t.destroy(a(e,"ERR_DATA_CHANNEL"))};var n=!1;t._closingInterval=setInterval(function(){t._channel&&"closing"===t._channel.readyState?(n&&t._onChannelClose(),n=!0):n=!1},5000)},r.prototype._read=function(){},r.prototype._write=function(e,t,n){var r=this;if(r.destroyed)return n(a("cannot write after peer is destroyed","ERR_DATA_CHANNEL"));if(r.connected){try{r.send(e)}catch(e){return r.destroy(a(e,"ERR_DATA_CHANNEL"))}r._channel.bufferedAmount>u?(r._debug("start backpressure: bufferedAmount %d",r._channel.bufferedAmount),r._cb=n):n(null)}else r._debug("write before connect"),r._chunk=e,r._cb=n},r.prototype._onFinish=function(){function e(){setTimeout(function(){t.destroy()},1e3)}var t=this;t.destroyed||(t.connected?e():t.once("connect",e))},r.prototype._startIceCompleteTimeout=function(){var e=this;e.destroyed||e._iceCompleteTimer||(e._debug("started iceComplete timeout"),e._iceCompleteTimer=setTimeout(function(){e._iceComplete||(e._iceComplete=!0,e._debug("iceComplete timeout completed"),e.emit("iceTimeout"),e.emit("_iceComplete"))},e.iceCompleteTimeout))},r.prototype._createOffer=function(){var e=this;e.destroyed||e._pc.createOffer(e.offerOptions).then(function(t){function n(){if(!e.destroyed){var n=e._pc.localDescription||t;e._debug("signal"),e.emit("signal",{type:n.type,sdp:n.sdp})}}e.destroyed||(!e.trickle&&!e.allowHalfTrickle&&(t.sdp=o(t.sdp)),t.sdp=e.sdpTransform(t.sdp),e._pc.setLocalDescription(t).then(function(){e._debug("createOffer success");e.destroyed||(e.trickle||e._iceComplete?n():e.once("_iceComplete",n))}).catch(function(t){e.destroy(a(t,"ERR_SET_LOCAL_DESCRIPTION"))}))}).catch(function(t){e.destroy(a(t,"ERR_CREATE_OFFER"))})},r.prototype._requestMissingTransceivers=function(){var e=this;e._pc.getTransceivers&&e._pc.getTransceivers().forEach(t=>{t.mid||!t.sender.track||t.requested||(t.requested=!0,e.addTransceiver(t.sender.track.kind))})},r.prototype._createAnswer=function(){var e=this;e.destroyed||e._pc.createAnswer(e.answerOptions).then(function(t){function n(){if(!e.destroyed){var n=e._pc.localDescription||t;e._debug("signal"),e.emit("signal",{type:n.type,sdp:n.sdp}),e.initiator||e._requestMissingTransceivers()}}e.destroyed||(!e.trickle&&!e.allowHalfTrickle&&(t.sdp=o(t.sdp)),t.sdp=e.sdpTransform(t.sdp),e._pc.setLocalDescription(t).then(function(){e.destroyed||(e.trickle||e._iceComplete?n():e.once("_iceComplete",n))}).catch(function(t){e.destroy(a(t,"ERR_SET_LOCAL_DESCRIPTION"))}))}).catch(function(t){e.destroy(a(t,"ERR_CREATE_ANSWER"))})},r.prototype._onIceStateChange=function(){var e=this;if(!e.destroyed){var t=e._pc.iceConnectionState,n=e._pc.iceGatheringState;e._debug("iceStateChange (connection: %s) (gathering: %s)",t,n),e.emit("iceStateChange",t,n),("connected"===t||"completed"===t)&&(e._pcReady=!0,e._maybeReady()),"failed"===t&&e.destroy(a("Ice connection failed.","ERR_ICE_CONNECTION_FAILURE")),"closed"===t&&e.destroy(a("Ice connection closed.","ERR_ICE_CONNECTION_CLOSED"))}},r.prototype.getStats=function(e){function t(e){return"[object Array]"===Object.prototype.toString.call(e.values)&&e.values.forEach(function(t){Object.assign(e,t)}),e}var n=this;0===n._pc.getStats.length?n._pc.getStats().then(function(n){var r=[];n.forEach(function(e){r.push(t(e))}),e(null,r)},function(t){e(t)}):n._isReactNativeWebrtc?n._pc.getStats(null,function(n){var r=[];n.forEach(function(e){r.push(t(e))}),e(null,r)},function(t){e(t)}):0u)&&e._onChannelBufferedAmountLow()},r.prototype._onSignalingStateChange=function(){var e=this;e.destroyed||("stable"===e._pc.signalingState&&!e._firstStable&&(e._isNegotiating=!1,e._debug("flushing sender queue",e._sendersAwaitingStable),e._sendersAwaitingStable.forEach(function(t){e._pc.removeTrack(t),e._queuedNegotiation=!0}),e._sendersAwaitingStable=[],e._queuedNegotiation&&(e._debug("flushing negotiation queue"),e._queuedNegotiation=!1,e._needsNegotiation()),e._debug("negotiate"),e.emit("negotiate")),e._firstStable=!1,e._debug("signalingStateChange %s",e._pc.signalingState),e.emit("signalingStateChange",e._pc.signalingState))},r.prototype._onIceCandidate=function(e){var t=this;t.destroyed||(e.candidate&&t.trickle?t.emit("signal",{candidate:{candidate:e.candidate.candidate,sdpMLineIndex:e.candidate.sdpMLineIndex,sdpMid:e.candidate.sdpMid}}):!e.candidate&&!t._iceComplete&&(t._iceComplete=!0,t.emit("_iceComplete")),e.candidate&&t._startIceCompleteTimeout())},r.prototype._onChannelMessage=function(e){var t=this;if(!t.destroyed){var r=e.data;r instanceof ArrayBuffer&&(r=n.from(r)),t.push(r)}},r.prototype._onChannelBufferedAmountLow=function(){var e=this;if(!e.destroyed&&e._cb){e._debug("ending backpressure: bufferedAmount %d",e._channel.bufferedAmount);var t=e._cb;e._cb=null,t(null)}},r.prototype._onChannelOpen=function(){var e=this;e.connected||e.destroyed||(e._debug("on channel open"),e._channelReady=!0,e._maybeReady())},r.prototype._onChannelClose=function(){var e=this;e.destroyed||(e._debug("on channel close"),e.destroy())},r.prototype._onTrack=function(e){var t=this;t.destroyed||e.streams.forEach(function(n){t._debug("on track"),t.emit("track",e.track,n),t._remoteTracks.push({track:e.track,stream:n});t._remoteStreams.some(function(e){return e.id===n.id})||(t._remoteStreams.push(n),setTimeout(function(){t.emit("stream",n)},0))})},r.prototype._debug=function(){var e=this,t=[].slice.call(arguments);t[0]="["+e._id+"] "+t[0],i.apply(null,t)}}).call(this,e("buffer").Buffer)},{buffer:39,debug:45,"get-browser-rtc":63,inherits:67,randombytes:99,"readable-stream":133}],125:[function(e,t,n){arguments[4][22][0].apply(n,arguments)},{"./_stream_readable":127,"./_stream_writable":129,"core-util-is":43,dup:22,inherits:67,"process-nextick-args":91}],126:[function(e,t,n){arguments[4][23][0].apply(n,arguments)},{"./_stream_transform":128,"core-util-is":43,dup:23,inherits:67}],127:[function(e,t,n){arguments[4][24][0].apply(n,arguments)},{"./_stream_duplex":125,"./internal/streams/BufferList":130,"./internal/streams/destroy":131,"./internal/streams/stream":132,_process:92,"core-util-is":43,dup:24,events:49,inherits:67,isarray:72,"process-nextick-args":91,"safe-buffer":134,"string_decoder/":135,util:33}],128:[function(e,t,n){arguments[4][25][0].apply(n,arguments)},{"./_stream_duplex":125,"core-util-is":43,dup:25,inherits:67}],129:[function(e,t,n){arguments[4][26][0].apply(n,arguments)},{"./_stream_duplex":125,"./internal/streams/destroy":131,"./internal/streams/stream":132,_process:92,"core-util-is":43,dup:26,inherits:67,"process-nextick-args":91,"safe-buffer":134,timers:174,"util-deprecate":188}],130:[function(e,t,n){arguments[4][27][0].apply(n,arguments)},{dup:27,"safe-buffer":134,util:33}],131:[function(e,t,n){arguments[4][28][0].apply(n,arguments)},{dup:28,"process-nextick-args":91}],132:[function(e,t,n){arguments[4][29][0].apply(n,arguments)},{dup:29,events:49}],133:[function(e,t,n){arguments[4][30][0].apply(n,arguments)},{"./lib/_stream_duplex.js":125,"./lib/_stream_passthrough.js":126,"./lib/_stream_readable.js":127,"./lib/_stream_transform.js":128,"./lib/_stream_writable.js":129,dup:30}],134:[function(e,t,n){arguments[4][31][0].apply(n,arguments)},{buffer:39,dup:31}],135:[function(e,t,n){arguments[4][32][0].apply(n,arguments)},{dup:32,"safe-buffer":134}],136:[function(e,t){function n(e){return s.digest(e)}function r(e,t){return c?void("string"==typeof e&&(e=o(e)),c.digest({name:"sha-1"},e).then(function(e){t(a(new Uint8Array(e)))},function(){t(n(e))})):void setTimeout(t,0,n(e))}function o(e){for(var t=e.length,n=new Uint8Array(t),r=0;r>>4).toString(16)),n.push((15&o).toString(16));return n.join("")}var i=e("rusha"),s=new i,d="undefined"==typeof window?self:window,l=d.crypto||d.msCrypto||{},c=l.subtle||l.webkitSubtle;try{c.digest({name:"sha-1"},new Uint8Array).catch(function(){c=!1})}catch(e){c=!1}t.exports=r,t.exports.sync=n},{rusha:120}],137:[function(e,t){(function(n,r){function o(e){var t=this;if(!(t instanceof o))return new o(e);if(e||(e={}),"string"==typeof e&&(e={url:e}),null==e.url&&null==e.socket)throw new Error("Missing required `url` or `socket` option");if(null!=e.url&&null!=e.socket)throw new Error("Must specify either `url` or `socket` option, not both");if(t._id=s(4).toString("hex").slice(0,7),t._debug("new websocket: %o",e),e=Object.assign({allowHalfOpen:!1},e),d.Duplex.call(t,e),t.connected=!1,t.destroyed=!1,t._chunk=null,t._cb=null,t._interval=null,e.socket)t.url=e.socket.url,t._ws=e.socket;else{t.url=e.url;try{t._ws="function"==typeof l?new c(e.url,e):new c(e.url)}catch(e){return void n.nextTick(function(){t.destroy(e)})}}t._ws.binaryType="arraybuffer",t._ws.onopen=function(){t._onOpen()},t._ws.onmessage=function(e){t._onMessage(e)},t._ws.onclose=function(){t._onClose()},t._ws.onerror=function(){t.destroy(new Error("connection error to "+t.url))},t._onFinishBound=function(){t._onFinish()},t.once("finish",t._onFinishBound)}t.exports=o;var a=e("debug")("simple-websocket"),i=e("inherits"),s=e("randombytes"),d=e("readable-stream"),l=e("ws"),c="function"==typeof l?l:WebSocket,u=65536;i(o,d.Duplex),o.WEBSOCKET_SUPPORT=!!c,o.prototype.send=function(e){this._ws.send(e)},o.prototype.destroy=function(e){this._destroy(e,function(){})},o.prototype._destroy=function(e,t){var n=this;if(!n.destroyed){if(n._debug("destroy (error: %s)",e&&(e.message||e)),n.readable=n.writable=!1,n._readableState.ended||n.push(null),n._writableState.finished||n.end(),n.connected=!1,n.destroyed=!0,clearInterval(n._interval),n._interval=null,n._chunk=null,n._cb=null,n._onFinishBound&&n.removeListener("finish",n._onFinishBound),n._onFinishBound=null,n._ws){var r=n._ws,o=function(){r.onclose=null};if(r.readyState===c.CLOSED)o();else try{r.onclose=o,r.close()}catch(e){o()}r.onopen=null,r.onmessage=null,r.onerror=function(){}}if(n._ws=null,e){if("undefined"!=typeof DOMException&&e instanceof DOMException){var a=e.code;e=new Error(e.message),e.code=a}n.emit("error",e)}n.emit("close"),t()}},o.prototype._read=function(){},o.prototype._write=function(e,t,n){if(this.destroyed)return n(new Error("cannot write after socket is destroyed"));if(this.connected){try{this.send(e)}catch(e){return this.destroy(e)}"function"!=typeof l&&this._ws.bufferedAmount>u?(this._debug("start backpressure: bufferedAmount %d",this._ws.bufferedAmount),this._cb=n):n(null)}else this._debug("write before connect"),this._chunk=e,this._cb=n},o.prototype._onFinish=function(){function e(){setTimeout(function(){t.destroy()},1e3)}var t=this;t.destroyed||(t.connected?e():t.once("connect",e))},o.prototype._onMessage=function(e){if(!this.destroyed){var t=e.data;t instanceof ArrayBuffer&&(t=r.from(t)),this.push(t)}},o.prototype._onOpen=function(){var e=this;if(!(e.connected||e.destroyed)){if(e.connected=!0,e._chunk){try{e.send(e._chunk)}catch(t){return e.destroy(t)}e._chunk=null,e._debug("sent chunk from \"write before connect\"");var t=e._cb;e._cb=null,t(null)}"function"!=typeof l&&(e._interval=setInterval(function(){e._onInterval()},150),e._interval.unref&&e._interval.unref()),e._debug("connect"),e.emit("connect")}},o.prototype._onInterval=function(){if(this._cb&&this._ws&&!(this._ws.bufferedAmount>u)){this._debug("ending backpressure: bufferedAmount %d",this._ws.bufferedAmount);var e=this._cb;this._cb=null,e(null)}},o.prototype._onClose=function(){this.destroyed||(this._debug("on close"),this.destroy())},o.prototype._debug=function(){var e=[].slice.call(arguments);e[0]="["+this._id+"] "+e[0],a.apply(null,e)}}).call(this,e("_process"),e("buffer").Buffer)},{_process:92,buffer:39,debug:138,inherits:67,randombytes:99,"readable-stream":148,ws:33}],138:[function(e,t,n){(function(o){"use strict";function a(e){return a="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},a(e)}function i(){var e;return"object"===("undefined"==typeof console?"undefined":a(console))&&console.log&&(e=console).log.apply(e,arguments)}function s(){var e;try{e=n.storage.getItem("debug")}catch(e){}return!e&&"undefined"!=typeof o&&"env"in o&&(e=o.env.DEBUG),e}n.log=i,n.formatArgs=function(e){if(e[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+e[0]+(this.useColors?"%c ":" ")+"+"+t.exports.humanize(this.diff),!!this.useColors){var n="color: "+this.color;e.splice(1,0,n,"color: inherit");var r=0,o=0;e[0].replace(/%[a-zA-Z%]/g,function(e){"%%"===e||(r++,"%c"===e&&(o=r))}),e.splice(o,0,n)}},n.save=function(e){try{e?n.storage.setItem("debug",e):n.storage.removeItem("debug")}catch(e){}},n.load=s,n.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+)/))},n.storage=function(){try{return localStorage}catch(e){}}(),n.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"],t.exports=e("./common")(n);var d=t.exports.formatters;d.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}).call(this,e("_process"))},{"./common":139,_process:92}],139:[function(e,n){"use strict";n.exports=function(n){function r(e){for(var n=0,r=0;rt&&(a=t),l=n;a--;)d===t&&(d=0),s[d]=s[0===d?t-1:d-1],d++;e&&(s[d-1]+=e);var i=s[d-1],c=s.lengtht._pos){var s=a.substr(t._pos);if("x-user-defined"===t._charset){for(var l=new o(s.length),c=0;ct._pos&&(t.push(new o(new Uint8Array(e.result.slice(t._pos)))),t._pos=e.result.byteLength)},e.onload=function(){t.push(null)},e.readAsArrayBuffer(a);}t._xhr.readyState===d.DONE&&"ms-stream"!==t._mode&&t.push(null)}}).call(this,e("_process"),"undefined"==typeof global?"undefined"==typeof self?"undefined"==typeof window?{}:window:self:global,e("buffer").Buffer)},{"./capability":153,_process:92,buffer:39,inherits:67,"readable-stream":164}],156:[function(e,t,n){arguments[4][22][0].apply(n,arguments)},{"./_stream_readable":158,"./_stream_writable":160,"core-util-is":43,dup:22,inherits:67,"process-nextick-args":91}],157:[function(e,t,n){arguments[4][23][0].apply(n,arguments)},{"./_stream_transform":159,"core-util-is":43,dup:23,inherits:67}],158:[function(e,t,n){arguments[4][24][0].apply(n,arguments)},{"./_stream_duplex":156,"./internal/streams/BufferList":161,"./internal/streams/destroy":162,"./internal/streams/stream":163,_process:92,"core-util-is":43,dup:24,events:49,inherits:67,isarray:72,"process-nextick-args":91,"safe-buffer":165,"string_decoder/":166,util:33}],159:[function(e,t,n){arguments[4][25][0].apply(n,arguments)},{"./_stream_duplex":156,"core-util-is":43,dup:25,inherits:67}],160:[function(e,t,n){arguments[4][26][0].apply(n,arguments)},{"./_stream_duplex":156,"./internal/streams/destroy":162,"./internal/streams/stream":163,_process:92,"core-util-is":43,dup:26,inherits:67,"process-nextick-args":91,"safe-buffer":165,timers:174,"util-deprecate":188}],161:[function(e,t,n){arguments[4][27][0].apply(n,arguments)},{dup:27,"safe-buffer":165,util:33}],162:[function(e,t,n){arguments[4][28][0].apply(n,arguments)},{dup:28,"process-nextick-args":91}],163:[function(e,t,n){arguments[4][29][0].apply(n,arguments)},{dup:29,events:49}],164:[function(e,t,n){arguments[4][30][0].apply(n,arguments)},{"./lib/_stream_duplex.js":156,"./lib/_stream_passthrough.js":157,"./lib/_stream_readable.js":158,"./lib/_stream_transform.js":159,"./lib/_stream_writable.js":160,dup:30}],165:[function(e,t,n){arguments[4][31][0].apply(n,arguments)},{buffer:39,dup:31}],166:[function(e,t,n){arguments[4][32][0].apply(n,arguments)},{dup:32,"safe-buffer":165}],167:[function(e,t){var n=e("stream-to-blob");t.exports=function e(t,r,o){return"function"==typeof r?e(t,null,r):void n(t,r,function(e,t){if(e)return o(e);var n=URL.createObjectURL(t);o(null,n)})}},{"stream-to-blob":168}],168:[function(e,t){var n=e("once");t.exports=function e(t,r,o){if("function"==typeof r)return e(t,null,r);o=n(o);var a=[];t.on("data",function(e){a.push(e)}).on("end",function(){var e=r?new Blob(a,{type:r}):new Blob(a);o(null,e)}).on("error",o)}},{once:86}],169:[function(e,t){(function(n){var r=e("once");t.exports=function(e,t,o){o=r(o);var a=n.alloc(t),i=0;e.on("data",function(e){e.copy(a,i),i+=e.length}).on("end",function(){o(null,a)}).on("error",o)}}).call(this,e("buffer").Buffer)},{buffer:39,once:86}],170:[function(e,t,n){arguments[4][32][0].apply(n,arguments)},{dup:32,"safe-buffer":171}],171:[function(e,t,n){arguments[4][31][0].apply(n,arguments)},{buffer:39,dup:31}],172:[function(e,t,n){var r=e("./thirty-two");n.encode=r.encode,n.decode=r.decode},{"./thirty-two":173}],173:[function(e,t,n){(function(e){'use strict';function t(e){var t=r(e.length/5);return 0==e.length%5?t:t+1}var o=[255,255,26,27,28,29,30,31,255,255,255,255,255,255,255,255,255,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,255,255,255,255,255,255,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,255,255,255,255,255];n.encode=function(n){e.isBuffer(n)||(n=new e(n));for(var r=0,o=0,a=0,s=0,d=new e(8*t(n));r>a,a=(a+5)%8,s=s<>8-a,r++):(s=31&l>>8-(a+5),a=(a+5)%8,0===a&&r++),d[o]="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567".charCodeAt(s),o++}for(r=o;r=n?(n=(n+5)%8,0==n?(d|=r,l[s]=d,s++,d=0):d|=255&r<<8-n):(n=(n+5)%8,d|=255&r>>>n,l[s]=d,s++,d=255&r<<8-n);else throw new Error("Invalid input - it is not base32 encoded string")}return l.slice(0,s)}}).call(this,e("buffer").Buffer)},{buffer:39}],174:[function(e,t,n){(function(t,r){function o(e,t){this._id=e,this._clearFn=t}var a=e("process/browser.js").nextTick,i=Function.prototype.apply,s=Array.prototype.slice,d={},l=0;n.setTimeout=function(){return new o(i.call(setTimeout,window,arguments),clearTimeout)},n.setInterval=function(){return new o(i.call(setInterval,window,arguments),clearInterval)},n.clearTimeout=n.clearInterval=function(e){e.close()},o.prototype.unref=o.prototype.ref=function(){},o.prototype.close=function(){this._clearFn.call(window,this._id)},n.enroll=function(e,t){clearTimeout(e._idleTimeoutId),e._idleTimeout=t},n.unenroll=function(e){clearTimeout(e._idleTimeoutId),e._idleTimeout=-1},n._unrefActive=n.active=function(e){clearTimeout(e._idleTimeoutId);var t=e._idleTimeout;0<=t&&(e._idleTimeoutId=setTimeout(function(){e._onTimeout&&e._onTimeout()},t))},n.setImmediate="function"==typeof t?t:function(e){var t=l++,r=!(2>arguments.length)&&s.call(arguments,1);return d[t]=!0,a(function(){d[t]&&(r?e.apply(null,r):e.call(null),n.clearImmediate(t))}),t},n.clearImmediate="function"==typeof r?r:function(e){delete d[e]}}).call(this,e("timers").setImmediate,e("timers").clearImmediate)},{"process/browser.js":92,timers:174}],175:[function(e,t){var n=e("buffer").Buffer;t.exports=function(e){if(e instanceof Uint8Array){if(0===e.byteOffset&&e.byteLength===e.buffer.byteLength)return e.buffer;if("function"==typeof e.buffer.slice)return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)}if(n.isBuffer(e)){for(var t=new Uint8Array(e.length),r=e.length,o=0;o{this.emit("warning",e)},this._onError=e=>{this.emit("error",e)},this._onDHTPeer=(e,t)=>{t.toString("hex")!==this.infoHash||this.emit("peer",`${e.host}:${e.port}`,"dht")},this._onTrackerPeer=e=>{this.emit("peer",e,"tracker")},this._onTrackerAnnounce=()=>{this.emit("trackerAnnounce")};const t=(e,t)=>{const n=new a(t);return n.on("warning",this._onWarning),n.on("error",this._onError),n.listen(e),this._internalDHT=!0,n};!1===e.tracker?this.tracker=null:e.tracker&&"object"==typeof e.tracker?(this._trackerOpts=Object.assign({},e.tracker),this.tracker=this._createTracker()):this.tracker=this._createTracker(),this.dht=!1===e.dht||"function"!=typeof a?null:e.dht&&"function"==typeof e.dht.addNode?e.dht:e.dht&&"object"==typeof e.dht?t(e.dhtPort,e.dht):t(e.dhtPort),this.dht&&(this.dht.on("peer",this._onDHTPeer),this._dhtAnnounce())}updatePort(e){e===this._port||(this._port=e,this.dht&&this._dhtAnnounce(),this.tracker&&(this.tracker.stop(),this.tracker.destroy(()=>{this.tracker=this._createTracker()})))}complete(e){this.tracker&&this.tracker.complete(e)}destroy(e){if(!this.destroyed){this.destroyed=!0,clearTimeout(this._dhtTimeout);const t=[];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),t.push(e=>{this.tracker.destroy(e)})),this.dht&&this.dht.removeListener("peer",this._onDHTPeer),this._internalDHT&&(this.dht.removeListener("warning",this._onWarning),this.dht.removeListener("error",this._onError),t.push(e=>{this.dht.destroy(e)})),s(t,e),this.dht=null,this.tracker=null,this._announce=null}}_createTracker(){const e=Object.assign({},this._trackerOpts,{infoHash:this.infoHash,announce:this._announce,peerId:this.peerId,port:this._port,userAgent:this._userAgent}),t=new d(e);return t.on("warning",this._onWarning),t.on("error",this._onError),t.on("peer",this._onTrackerPeer),t.on("update",this._onTrackerAnnounce),t.setInterval(this._intervalMs),t.start(),t}_dhtAnnounce(){this._dhtAnnouncing||(o("dht announce"),this._dhtAnnouncing=!0,clearTimeout(this._dhtTimeout),this.dht.announce(this.infoHash,this._port,e=>{this._dhtAnnouncing=!1,o("dht announce complete"),e&&this.emit("warning",e),this.emit("dhtAnnounce"),this.destroyed||(this._dhtTimeout=setTimeout(()=>{this._dhtAnnounce()},this._intervalMs+r(Math.random()*this._intervalMs/5)),this._dhtTimeout.unref&&this._dhtTimeout.unref())}))}}}).call(this,e("_process"))},{_process:92,"bittorrent-dht/client":33,"bittorrent-tracker/client":16,debug:177,events:49,"run-parallel":119}],177:[function(e,t,n){arguments[4][138][0].apply(n,arguments)},{"./common":178,_process:92,dup:138}],178:[function(e,t,n){arguments[4][139][0].apply(n,arguments)},{dup:139,ms:83}],179:[function(e,t){(function(e){const n=16384;class r{constructor(e){this.length=e,this.missing=e,this.sources=null,this._chunks=a(e/n),this._remainder=e%n||n,this._buffered=0,this._buffer=null,this._cancellations=null,this._reservations=0,this._flushed=!1}chunkLength(e){return e===this._chunks-1?this._remainder:n}chunkLengthRemaining(e){return this.length-e*n}chunkOffset(e){return e*n}reserve(){return this.init()?this._cancellations.length?this._cancellations.pop():this._reservations=e.length||0>t)){var n=e.pop();if(t","\"","`"," ","\r","\n","\t"]),h=["'"].concat(f),m=["%","/","?",";","#"].concat(h),g=["/","?","#"],_=/^[+a-z0-9A-Z_-]{0,63}$/,b=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,y={javascript:!0,"javascript:":!0},w={javascript:!0,"javascript:":!0},x={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},S=e("querystring");r.prototype.parse=function(e,t,n){if(!d.isString(e))throw new TypeError("Parameter 'url' must be a string, not "+typeof e);var r=e.indexOf("?"),o=-1!==r&&r_.length&&_.unshift(""),n.pathname=_.join("/")}else n.pathname=e.pathname;if(n.search=e.search,n.query=e.query,n.host=e.host||"",n.auth=e.auth,n.hostname=e.hostname||e.host,n.port=e.port,n.pathname||n.search){var b=n.pathname||"",p=n.search||"";n.path=b+p}return n.slashes=n.slashes||e.slashes,n.href=n.format(),n}var s=n.pathname&&"/"===n.pathname.charAt(0),y=e.host||e.pathname&&"/"===e.pathname.charAt(0),S=y||s||n.host&&e.pathname,E=S,C=n.pathname&&n.pathname.split("/")||[],_=e.pathname&&e.pathname.split("/")||[],L=n.protocol&&!x[n.protocol];if(L&&(n.hostname="",n.port=null,n.host&&(""===C[0]?C[0]=n.host:C.unshift(n.host)),n.host="",e.protocol&&(e.hostname=null,e.port=null,e.host&&(""===_[0]?_[0]=e.host:_.unshift(e.host)),e.host=null),S=S&&(""===_[0]||""===C[0])),y)n.host=e.host||""===e.host?e.host:n.host,n.hostname=e.hostname||""===e.hostname?e.hostname:n.hostname,n.search=e.search,n.query=e.query,C=_;else if(_.length)C||(C=[]),C.pop(),C=C.concat(_),n.search=e.search,n.query=e.query;else if(!d.isNullOrUndefined(e.search)){if(L){n.hostname=n.host=C.shift();var I=!!(n.host&&0{class t extends r{constructor(t){super(),this._wire=t,this._fetching=!1,this._metadataComplete=!1,this._metadataSize=null,this._remainingRejects=null,this._bitfield=new i(0,{grow:l}),n.isBuffer(e)&&this.setMetadata(e)}onHandshake(e,t,n){this._infoHash=e}onExtendedHandshake(e){return e.m&&e.m.ut_metadata?e.metadata_size?"number"!=typeof e.metadata_size||1E7=e.metadata_size?this.emit("warning",new Error("Peer gave invalid metadata size")):void(this._metadataSize=e.metadata_size,this._numPieces=a(this._metadataSize/c),this._remainingRejects=2*this._numPieces,this._fetching&&this._requestPieces()):this.emit("warning",new Error("Peer does not have metadata")):this.emit("warning",new Error("Peer does not support ut_metadata"))}onMessage(e){let t,n;try{const r=e.toString(),a=r.indexOf("ee")+2;t=o.decode(r.substring(0,a)),n=e.slice(a)}catch(e){return}switch(t.msg_type){case 0:this._onRequest(t.piece);break;case 1:this._onData(t.piece,n,t.total_size);break;case 2:this._onReject(t.piece);}}fetch(){this._metadataComplete||(this._fetching=!0,this._metadataSize&&this._requestPieces())}cancel(){this._fetching=!1}setMetadata(e){if(this._metadataComplete)return!0;s("set metadata");try{const t=o.decode(e).info;t&&(e=o.encode(t))}catch(e){}return!(this._infoHash&&this._infoHash!==d.sync(e))&&(this.cancel(),this.metadata=e,this._metadataComplete=!0,this._metadataSize=this.metadata.length,this._wire.extendedHandshake.metadata_size=this._metadataSize,this.emit("metadata",o.encode({info:o.decode(this.metadata)})),!0)}_send(e,t){let r=o.encode(e);n.isBuffer(t)&&(r=n.concat([r,t])),this._wire.extended("ut_metadata",r)}_request(e){this._send({msg_type:0,piece:e})}_data(e,t,n){const r={msg_type:1,piece:e};"number"==typeof n&&(r.total_size=n),this._send(r,t)}_reject(e){this._send({msg_type:2,piece:e})}_onRequest(e){if(!this._metadataComplete)return void this._reject(e);const t=e*c;let n=t+c;n>this._metadataSize&&(n=this._metadataSize);const r=this.metadata.slice(t,n);this._data(e,r,this._metadataSize)}_onData(e,t,n){t.length>c||(t.copy(this.metadata,e*c),this._bitfield.set(e),this._checkDone())}_onReject(e){0=this._entries[this._index][this._countName]&&(this._index++,this._offset=0),this.value=this._entries[this._index]}}t.exports=class extends i{constructor(e){super(),this._tracks=[],this._file=e,this._decoder=null,this._findMoov(0)}_findMoov(e){this._decoder&&this._decoder.destroy();let t=0;this._decoder=s.decode();const n=this._file.createReadStream({start:e});n.pipe(this._decoder),this._decoder.on("box",r=>{"moov"===r.type?this._decoder.decode(e=>{n.destroy();try{this._processMoov(e)}catch(e){e.message=`Cannot parse mp4 file: ${e.message}`,this.emit("error",e)}}):r.length<4096?(t+=r.length,this._decoder.ignore()):(t+=r.length,n.destroy(),this._decoder.destroy(),this._findMoov(e+t))})}_processMoov(e){const t=e.traks;this._tracks=[],this._hasVideo=!1,this._hasAudio=!1;for(let n=0;n=i.stsz.entries.length)break;if(h++,g+=t,h>=r.samplesPerChunk){h=0,g=0,m++;const e=i.stsc.entries[_+1];e&&m+1>=e.firstChunk&&_++}b+=n,y.inc(),w&&w.inc(),a&&e++}a.mdia.mdhd.duration=0,a.tkhd.duration=0;const k=r.sampleDescriptionId,x={type:"moov",mvhd:e.mvhd,traks:[{tkhd:a.tkhd,mdia:{mdhd:a.mdia.mdhd,hdlr:a.mdia.hdlr,elng:a.mdia.elng,minf:{vmhd:a.mdia.minf.vmhd,smhd:a.mdia.minf.smhd,dinf:a.mdia.minf.dinf,stbl:{stsd:i.stsd,stts:o(),ctts:o(),stsc:o(),stsz:o(),stco:o(),stss:o()}}}}],mvex:{mehd:{fragmentDuration:e.mvhd.duration},trexs:[{trackId:a.tkhd.trackId,defaultSampleDescriptionIndex:k,defaultSampleDuration:0,defaultSampleSize:0,defaultSampleFlags:0}]}};this._tracks.push({fragmentSequence:1,trackId:a.tkhd.trackId,timeScale:a.mdia.mdhd.timeScale,samples:p,currSample:null,currTime:null,moov:x,mime:u})}if(0===this._tracks.length)return void this.emit("error",new Error("no playable tracks"));e.mvhd.duration=0,this._ftyp={type:"ftyp",brand:"iso5",brandVersion:0,compatibleBrands:["iso5"]};const a=d.encode(this._ftyp),i=this._tracks.map(e=>{const t=d.encode(e.moov);return{mime:e.mime,init:n.concat([a,t])}});this.emit("ready",i)}seek(e){if(!this._tracks)throw new Error("Not ready yet; wait for 'ready' event");this._fileStream&&(this._fileStream.destroy(),this._fileStream=null);let t=-1;if(this._tracks.map((n,r)=>{n.outStream&&n.outStream.destroy(),n.inStream&&(n.inStream.destroy(),n.inStream=null);const o=n.outStream=s.encode(),a=this._generateFragment(r,e);if(!a)return o.finalize();(-1===t||a.ranges[0].start{o.destroyed||o.box(e.moof,t=>{if(t)return this.emit("error",t);if(!o.destroyed){const t=n.inStream.slice(e.ranges);t.pipe(o.mediaData(e.length,e=>{if(e)return this.emit("error",e);if(!o.destroyed){const e=this._generateFragment(r);return e?void i(e):o.finalize()}}))}})};i(a)}),0<=t){const e=this._fileStream=this._file.createReadStream({start:t});this._tracks.forEach(n=>{n.inStream=new l(t,{highWaterMark:1e7}),e.pipe(n.inStream)})}return this._tracks.map(e=>e.outStream)}_findSampleBefore(e,t){const n=this._tracks[e],o=r(n.timeScale*t);let i=a(n.samples,o,(e,n)=>{const t=e.dts+e.presentationOffset;return t-n});for(-1===i?i=0:0>i&&(i=-i-2);!n.samples[i].sync;)i--;return i}_generateFragment(e,t){const n=this._tracks[e];let r;if(r=void 0===t?n.currSample:this._findSampleBefore(e,t),r>=n.samples.length)return null;const o=n.samples[r].dts;let a=0;const i=[];for(var s=r;s=n.timeScale*1)break;a+=e.size;const t=i.length-1;0>t||i[t].end!==e.offset?i.push({start:e.offset,end:e.offset+e.size}):i[t].end+=e.size}return n.currSample=s,{moof:this._generateMoof(e,r,s),ranges:i,length:a}}_generateMoof(e,t,n){const r=this._tracks[e],o=[];let a=0;for(let i=t;ie.presentationOffset&&(a=1),o.push({sampleDuration:e.duration,sampleSize:e.size,sampleFlags:e.sync?33554432:16842752,sampleCompositionTimeOffset:e.presentationOffset})}const i={type:"moof",mfhd:{sequenceNumber:r.fragmentSequence++},trafs:[{tfhd:{flags:131072,trackId:r.trackId},tfdt:{baseMediaDecodeTime:r.samples[t].dts},trun:{flags:3841,dataOffset:8,entries:o,version:a}}]};return i.trafs[0].trun.dataOffset+=d.encodingLength(i),i}}}).call(this,e("buffer").Buffer)},{"binary-search":12,buffer:39,events:49,"mp4-box-encoding":79,"mp4-stream":82,"range-slice-stream":100}],190:[function(e,t){function n(e,t,o={}){return this instanceof n?void(this.detailedError=null,this._elem=t,this._elemWrapper=new r(t),this._waitingFired=!1,this._trackMeta=null,this._file=e,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()},t.autoplay&&(t.preload="auto"),t.addEventListener("waiting",this._onWaiting),t.addEventListener("error",this._onError)):(console.warn("don't invoked VideoStream without 'new'"),new n(e,t,o))}const r=e("mediasource"),o=e("pump"),a=e("./mp4-remuxer");n.prototype={_createMuxer(){this._muxer=new a(this._file),this._muxer.on("ready",e=>{this._tracks=e.map(e=>{const t=this._elemWrapper.createWriteStream(e.mime);t.on("error",e=>{this._elemWrapper.error(e)});const n={muxed:null,mediaSource:t,initFlushed:!1,onInitFlushed:null};return t.write(e.init,e=>{n.initFlushed=!0,n.onInitFlushed&&n.onInitFlushed(e)}),n}),(this._waitingFired||"auto"===this._elem.preload)&&this._pump()}),this._muxer.on("error",e=>{this._elemWrapper.error(e)})},_pump(){const e=this._muxer.seek(this._elem.currentTime,!this._tracks);this._tracks.forEach((t,n)=>{const r=()=>{t.muxed&&(t.muxed.destroy(),t.mediaSource=this._elemWrapper.createWriteStream(t.mediaSource),t.mediaSource.on("error",e=>{this._elemWrapper.error(e)})),t.muxed=e[n],o(t.muxed,t.mediaSource)};t.initFlushed?r():t.onInitFlushed=e=>e?void this._elemWrapper.error(e):void r()})},destroy(){this.destroyed||(this.destroyed=!0,this._elem.removeEventListener("waiting",this._onWaiting),this._elem.removeEventListener("error",this._onError),this._tracks&&this._tracks.forEach(e=>{e.muxed&&e.muxed.destroy()}),this._elem.src="")}},t.exports=n},{"./mp4-remuxer":189,mediasource:75,pump:93}],191:[function(e,t){function n(e,t){function r(){for(var t=Array(arguments.length),n=0;n`0${e%100}`.slice(-2)).slice(0,4);class S extends s{constructor(e={}){super(),this.peerId="string"==typeof e.peerId?e.peerId:i.isBuffer(e.peerId)?e.peerId.toString("hex"):i.from(`-WW${x}-`+_(9).toString("base64")).toString("hex"),this.peerIdBuffer=i.from(this.peerId,"hex"),this.nodeId="string"==typeof e.nodeId?e.nodeId:i.isBuffer(e.nodeId)?e.nodeId.toString("hex"):_(20).toString("hex"),this.nodeIdBuffer=i.from(this.nodeId,"hex"),this._debugId=this.peerId.toString("hex").substring(0,7),this.destroyed=!1,this.listening=!1,this.torrentPort=e.torrentPort||0,this.dhtPort=e.dhtPort||0,this.tracker=e.tracker===void 0?{}:e.tracker,this.torrents=[],this.maxConns=+e.maxConns||55,this._debug("new webtorrent (peerId %s, nodeId %s, port %s)",this.peerId,this.nodeId,this.torrentPort),this.tracker&&("object"!=typeof this.tracker&&(this.tracker={}),e.rtcConfig&&(console.warn("WebTorrent: opts.rtcConfig is deprecated. Use opts.tracker.rtcConfig instead"),this.tracker.rtcConfig=e.rtcConfig),e.wrtc&&(console.warn("WebTorrent: opts.wrtc is deprecated. Use opts.tracker.wrtc instead"),this.tracker.wrtc=e.wrtc),r.WRTC&&!this.tracker.wrtc&&(this.tracker.wrtc=r.WRTC)),"function"==typeof y?this._tcpPool=new y(this):n.nextTick(()=>{this._onListening()}),this._downloadSpeed=b(),this._uploadSpeed=b(),!1!==e.dht&&"function"==typeof u?(this.dht=new u(Object.assign({},{nodeId:this.nodeId},e.dht)),this.dht.once("error",e=>{this._destroy(e)}),this.dht.once("listening",()=>{const e=this.dht.address();e&&(this.dhtPort=e.port)}),this.dht.setMaxListeners(0),this.dht.listen(this.dhtPort)):this.dht=!1,this.enableWebSeeds=!1!==e.webSeeds;const t=()=>{this.destroyed||(this.ready=!0,this.emit("ready"))};"function"==typeof p&&null!=e.blocklist?p(e.blocklist,{headers:{"user-agent":`WebTorrent/${k} (https://webtorrent.io)`}},(e,n)=>e?this.error(`Failed to load blocklist: ${e.message}`):void(this.blocked=n,t())):n.nextTick(t)}get downloadSpeed(){return this._downloadSpeed()}get uploadSpeed(){return this._uploadSpeed()}get progress(){const e=this.torrents.filter(e=>1!==e.progress),t=e.reduce((e,t)=>e+t.downloaded,0),n=e.reduce((e,t)=>e+(t.length||0),0)||1;return t/n}get ratio(){const e=this.torrents.reduce((e,t)=>e+t.uploaded,0),t=this.torrents.reduce((e,t)=>e+t.received,0)||1;return e/t}get(e){if(!(e instanceof w)){let t;try{t=h(e)}catch(e){}if(!t)return null;if(!t.infoHash)throw new Error("Invalid torrent identifier");for(const e of this.torrents)if(e.infoHash===t.infoHash)return e}else if(this.torrents.includes(e))return e;return null}download(e,t,n){return console.warn("WebTorrent: client.download() is deprecated. Use client.add() instead"),this.add(e,t,n)}add(e,t={},n){function r(){i.removeListener("_infoHash",o),i.removeListener("ready",a),i.removeListener("close",r)}if(this.destroyed)throw new Error("client is destroyed");"function"==typeof t&&([t,n]=[{},t]);const o=()=>{if(!this.destroyed)for(const e of this.torrents)if(e.infoHash===i.infoHash&&e!==i)return void i._destroy(new Error(`Cannot add duplicate torrent ${i.infoHash}`))},a=()=>{this.destroyed||("function"==typeof n&&n(i),this.emit("torrent",i))};this._debug("add"),t=t?Object.assign({},t):{};const i=new w(e,this,t);return this.torrents.push(i),i.once("_infoHash",o),i.once("ready",a),i.once("close",r),i}seed(e,t,n){if(this.destroyed)throw new Error("client is destroyed");"function"==typeof t&&([t,n]=[{},t]),this._debug("seed"),t=t?Object.assign({},t):{},t.skipVerify=!0;const r="string"==typeof e;r&&(t.path=m.dirname(e)),t.createdBy||(t.createdBy=`WebTorrent/${x}`);const i=e=>{this._debug("on seed"),"function"==typeof n&&n(e),e.emit("seed"),this.emit("seed",e)},s=this.add(null,t,e=>{const t=[t=>r?t():void e.load(c,t)];this.dht&&t.push(t=>{e.once("dhtAnnounce",t)}),f(t,t=>this.destroyed?void 0:t?e._destroy(t):void i(e))});let c;return a(e)?e=Array.from(e):!Array.isArray(e)&&(e=[e]),f(e.map(e=>t=>{o(e)?d(e,t):t(null,e)}),(e,n)=>this.destroyed?void 0:e?s._destroy(e):void l.parseInput(n,t,(e,r)=>this.destroyed?void 0:e?s._destroy(e):void(c=r.map(e=>e.getStream),l(n,t,(e,t)=>{if(!this.destroyed){if(e)return s._destroy(e);const n=this.get(t);n?s._destroy(new Error(`Cannot add duplicate torrent ${n.infoHash}`)):s._onTorrentId(t)}})))),s}remove(e,t){this._debug("remove");const n=this.get(e);if(!n)throw new Error(`No torrent with id ${e}`);this._remove(e,t)}_remove(e,t){const n=this.get(e);n&&(this.torrents.splice(this.torrents.indexOf(n),1),n.destroy(t))}address(){return this.listening?this._tcpPool?this._tcpPool.server.address():{address:"0.0.0.0",family:"IPv4",port:0}:null}destroy(e){if(this.destroyed)throw new Error("client already destroyed");this._destroy(null,e)}_destroy(e,t){this._debug("client destroy"),this.destroyed=!0;const n=this.torrents.map(e=>t=>{e.destroy(t)});this._tcpPool&&n.push(e=>{this._tcpPool.destroy(e)}),this.dht&&n.push(e=>{this.dht.destroy(e)}),f(n,t),e&&this.emit("error",e),this.torrents=[],this._tcpPool=null,this.dht=null}_onListening(){if(this._debug("listening"),this.listening=!0,this._tcpPool){const e=this._tcpPool.server.address();e&&(this.torrentPort=e.port)}this.emit("listening")}_debug(){const e=[].slice.call(arguments);e[0]=`[${this._debugId}] ${e[0]}`,c(...e)}}S.WEBRTC_SUPPORT=g.WEBRTC_SUPPORT,S.VERSION=k,t.exports=S}).call(this,e("_process"),"undefined"==typeof global?"undefined"==typeof self?"undefined"==typeof window?{}:window:self:global)},{"./lib/tcp-pool":33,"./lib/torrent":5,"./package.json":193,_process:92,"bittorrent-dht/client":33,"create-torrent":44,debug:45,events:49,"load-ip-set":33,"parse-torrent":88,path:89,randombytes:99,"run-parallel":119,"safe-buffer":121,"simple-concat":122,"simple-peer":124,speedometer:151}]},{},[194])(194)});