From 93ef3186f278bd0b48ec0121842a5038fe35a7d7 Mon Sep 17 00:00:00 2001 From: Leo <5376265+leoherzog@users.noreply.github.com> Date: Sat, 18 Jun 2022 02:24:36 +0000 Subject: [PATCH] Update Dependencies --- bin/bundle.js | 12 ++++++------ bin/bundle.min.js | 4 ++-- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/bin/bundle.js b/bin/bundle.js index 8565050..73e55b0 100644 --- a/bin/bundle.js +++ b/bin/bundle.js @@ -13915,16 +13915,16 @@ arguments[4][42][0].apply(exports,arguments) var w = this.words[i]; var word = (((w << off) | carry) & 0xffffff).toString(16); carry = (w >>> (24 - off)) & 0xffffff; - if (carry !== 0 || i !== this.length - 1) { - out = zeros[6 - word.length] + word + out; - } else { - out = word + out; - } off += 2; if (off >= 26) { off -= 26; i--; } + if (carry !== 0 || i !== this.length - 1) { + out = zeros[6 - word.length] + word + out; + } else { + out = word + out; + } } if (carry !== 0) { out = carry.toString(16) + out; @@ -62804,7 +62804,7 @@ module.exports = WebConn }).call(this)}).call(this,require("buffer").Buffer) },{"../package.json":495,"bitfield":26,"bittorrent-protocol":27,"buffer":109,"debug":160,"lt_donthave":255,"simple-get":393,"simple-sha1":410}],495:[function(require,module,exports){ module.exports={ - "version": "1.8.20" + "version": "1.8.22" } },{}],496:[function(require,module,exports){ // Returns a wrapper function that returns a wrapped callback diff --git a/bin/bundle.min.js b/bin/bundle.min.js index cc61ca1..96db892 100644 --- a/bin/bundle.min.js +++ b/bin/bundle.min.js @@ -2,7 +2,7 @@ /*! bittorrent-protocol. MIT License. WebTorrent LLC */ const n=e("unordered-array-remove"),r=e("bencode"),s=e("bitfield").default,a=e("crypto"),o=e("debug")("bittorrent-protocol"),c=e("randombytes"),l=e("simple-sha1"),u=e("speedometer"),p=e("readable-stream"),d=e("rc4"),f=i.from("BitTorrent protocol"),h=i.from([0,0,0,0]),m=i.from([0,0,0,1,0]),b=i.from([0,0,0,1,1]),v=i.from([0,0,0,1,2]),g=i.from([0,0,0,1,3]),y=[0,0,0,0,0,0,0,0],_=[0,0,0,3,9,0,0],x=i.from([0,0,0,1,14]),w=i.from([0,0,0,1,15]),k=i.from([0,0,0,0,0,0,0,0]),E=i.from([0,0,1,2]),S=i.from([0,0,0,2]);function M(e,t){for(let i=e.length;i--;)e[i]^=t[i];return e}class A{constructor(e,t,i,n){this.piece=e,this.offset=t,this.length=i,this.callback=n}}class j{constructor(){this.buffer=new Uint8Array}get(e){return!0}set(e){}}class I extends p.Duplex{constructor(e=null,t=0,i=!1){super(),this._debugId=c(4).toString("hex"),this._debug("new wire"),this.peerId=null,this.peerIdBuffer=null,this.type=e,this.amChoking=!0,this.amInterested=!1,this.peerChoking=!0,this.peerInterested=!1,this.peerPieces=new s(0,{grow:4e5}),this.extensions={},this.peerExtensions={},this.requests=[],this.peerRequests=[],this.extendedMapping={},this.peerExtendedMapping={},this.extendedHandshake={},this.peerExtendedHandshake={},this.hasFast=!1,this.allowedFastSet=[],this.peerAllowedFastSet=[],this._ext={},this._nextExt=1,this.uploaded=0,this.downloaded=0,this.uploadSpeed=u(),this.downloadSpeed=u(),this._keepAliveInterval=null,this._timeout=null,this._timeoutMs=0,this._timeoutExpiresAt=null,this.destroyed=!1,this._finished=!1,this._parserSize=0,this._parser=null,this._buffer=[],this._bufferSize=0,this._peEnabled=i,i?(this._dh=a.createDiffieHellman("ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a63a36210000000000090563","hex",2),this._myPubKey=this._dh.generateKeys("hex")):this._myPubKey=null,this._peerPubKey=null,this._sharedSecret=null,this._peerCryptoProvide=[],this._cryptoHandshakeDone=!1,this._cryptoSyncPattern=null,this._waitMaxBytes=null,this._encryptionMethod=null,this._encryptGenerator=null,this._decryptGenerator=null,this._setGenerators=!1,this.once("finish",(()=>this._onFinish())),this.on("finish",this._onFinish),this._debug("type:",this.type),"tcpIncoming"===this.type&&this._peEnabled?this._determineHandshakeType():"tcpOutgoing"===this.type&&this._peEnabled&&0===t?this._parsePe2():this._parseHandshake(null)}setKeepAlive(e){this._debug("setKeepAlive %s",e),clearInterval(this._keepAliveInterval),!1!==e&&(this._keepAliveInterval=setInterval((()=>{this.keepAlive()}),55e3))}setTimeout(e,t){this._debug("setTimeout ms=%d unref=%s",e,t),this._timeoutMs=e,this._timeoutUnref=!!t,this._resetTimeout(!0)}destroy(){if(!this.destroyed)return this.destroyed=!0,this._debug("destroy"),this.emit("close"),this.end(),this}end(...e){return this._debug("end"),this._onUninterested(),this._onChoke(),super.end(...e)}use(e){const t=e.prototype.name;if(!t)throw new Error('Extension class requires a "name" property on the prototype');this._debug("use extension.name=%s",t);const i=this._nextExt,n=new e(this);function r(){}"function"!=typeof n.onHandshake&&(n.onHandshake=r),"function"!=typeof n.onExtendedHandshake&&(n.onExtendedHandshake=r),"function"!=typeof n.onMessage&&(n.onMessage=r),this.extendedMapping[i]=t,this._ext[t]=n,this[t]=n,this._nextExt+=1}keepAlive(){this._debug("keep-alive"),this._push(h)}sendPe1(){if(this._peEnabled){const e=Math.floor(513*Math.random()),t=c(e);this._push(i.concat([i.from(this._myPubKey,"hex"),t]))}}sendPe2(){const e=Math.floor(513*Math.random()),t=c(e);this._push(i.concat([i.from(this._myPubKey,"hex"),t]))}sendPe3(e){this.setEncrypt(this._sharedSecret,e);const t=i.from(l.sync(i.from(this._utfToHex("req1")+this._sharedSecret,"hex")),"hex"),n=M(i.from(l.sync(i.from(this._utfToHex("req2")+e,"hex")),"hex"),i.from(l.sync(i.from(this._utfToHex("req3")+this._sharedSecret,"hex")),"hex")),r=c(2).readUInt16BE(0)%512,s=c(r);let a=i.alloc(14+r+2);k.copy(a),E.copy(a,8),a.writeInt16BE(r,12),s.copy(a,14),a.writeInt16BE(0,14+r),a=this._encryptHandshake(a),this._push(i.concat([t,n,a]))}sendPe4(e){this.setEncrypt(this._sharedSecret,e);const t=c(2).readUInt16BE(0)%512,n=c(t);let r=i.alloc(14+t);k.copy(r),S.copy(r,8),r.writeInt16BE(t,12),n.copy(r,14),r=this._encryptHandshake(r),this._push(r),this._cryptoHandshakeDone=!0,this._debug("completed crypto handshake")}handshake(e,t,n){let r,s;if("string"==typeof e?(e=e.toLowerCase(),r=i.from(e,"hex")):(r=e,e=r.toString("hex")),"string"==typeof t?s=i.from(t,"hex"):(s=t,t=s.toString("hex")),this._infoHash=r,20!==r.length||20!==s.length)throw new Error("infoHash and peerId MUST have length 20");this._debug("handshake i=%s p=%s exts=%o",e,t,n);const a=i.from(y);this.extensions={extended:!0,dht:!(!n||!n.dht),fast:!(!n||!n.fast)},a[5]|=16,this.extensions.dht&&(a[7]|=1),this.extensions.fast&&(a[7]|=4),this.extensions.fast&&this.peerExtensions.fast&&(this._debug("fast extension is enabled"),this.hasFast=!0),this._push(i.concat([f,a,r,s])),this._handshakeSent=!0,this.peerExtensions.extended&&!this._extendedHandshakeSent&&this._sendExtendedHandshake()}_sendExtendedHandshake(){const e=Object.assign({},this.extendedHandshake);e.m={};for(const t in this.extendedMapping){const i=this.extendedMapping[t];e.m[i]=Number(t)}this.extended(0,r.encode(e)),this._extendedHandshakeSent=!0}choke(){if(!this.amChoking)if(this.amChoking=!0,this._debug("choke"),this._push(m),this.hasFast){let e=0;for(;this.peerRequests.length>e;){const t=this.peerRequests[e];this.allowedFastSet.includes(t.piece)?++e:this.reject(t.piece,t.offset,t.length)}}else for(;this.peerRequests.length;)this.peerRequests.pop()}unchoke(){this.amChoking&&(this.amChoking=!1,this._debug("unchoke"),this._push(b))}interested(){this.amInterested||(this.amInterested=!0,this._debug("interested"),this._push(v))}uninterested(){this.amInterested&&(this.amInterested=!1,this._debug("uninterested"),this._push(g))}have(e){this._debug("have %d",e),this._message(4,[e],null)}bitfield(e){this._debug("bitfield"),i.isBuffer(e)||(e=e.buffer),this._message(5,[],e)}request(e,t,i,n){return n||(n=()=>{}),this._finished?n(new Error("wire is closed")):!this.peerChoking||this.hasFast&&this.peerAllowedFastSet.includes(e)?(this._debug("request index=%d offset=%d length=%d",e,t,i),this.requests.push(new A(e,t,i,n)),this._timeout||this._resetTimeout(!0),void this._message(6,[e,t,i],null)):n(new Error("peer is choking"))}piece(e,t,i){this._debug("piece index=%d offset=%d",e,t),this._message(7,[e,t],i),this.uploaded+=i.length,this.uploadSpeed(i.length),this.emit("upload",i.length)}cancel(e,t,i){this._debug("cancel index=%d offset=%d length=%d",e,t,i),this._callback(this._pull(this.requests,e,t,i),new Error("request was cancelled"),null),this._message(8,[e,t,i],null)}port(e){this._debug("port %d",e);const t=i.from(_);t.writeUInt16BE(e,5),this._push(t)}suggest(e){if(!this.hasFast)throw Error("fast extension is disabled");this._debug("suggest %d",e),this._message(13,[e],null)}haveAll(){if(!this.hasFast)throw Error("fast extension is disabled");this._debug("have-all"),this._push(x)}haveNone(){if(!this.hasFast)throw Error("fast extension is disabled");this._debug("have-none"),this._push(w)}reject(e,t,i){if(!this.hasFast)throw Error("fast extension is disabled");this._debug("reject index=%d offset=%d length=%d",e,t,i),this._pull(this.peerRequests,e,t,i),this._message(16,[e,t,i],null)}allowedFast(e){if(!this.hasFast)throw Error("fast extension is disabled");this._debug("allowed-fast %d",e),this.allowedFastSet.includes(e)||this.allowedFastSet.push(e),this._message(17,[e],null)}extended(e,t){if(this._debug("extended ext=%s",e),"string"==typeof e&&this.peerExtendedMapping[e]&&(e=this.peerExtendedMapping[e]),"number"!=typeof e)throw new Error(`Unrecognized extension: ${e}`);{const n=i.from([e]),s=i.isBuffer(t)?t:r.encode(t);this._message(20,[],i.concat([n,s]))}}setEncrypt(e,t){let n,r,s,a,o,c;switch(this.type){case"tcpIncoming":n=l.sync(i.from(this._utfToHex("keyB")+e+t,"hex")),r=l.sync(i.from(this._utfToHex("keyA")+e+t,"hex")),s=i.from(n,"hex"),a=[];for(const e of s.values())a.push(e);o=i.from(r,"hex"),c=[];for(const e of o.values())c.push(e);this._encryptGenerator=new d(a),this._decryptGenerator=new d(c);break;case"tcpOutgoing":n=l.sync(i.from(this._utfToHex("keyA")+e+t,"hex")),r=l.sync(i.from(this._utfToHex("keyB")+e+t,"hex")),s=i.from(n,"hex"),a=[];for(const e of s.values())a.push(e);o=i.from(r,"hex"),c=[];for(const e of o.values())c.push(e);this._encryptGenerator=new d(a),this._decryptGenerator=new d(c);break;default:return!1}for(let e=0;e<1024;e++)this._encryptGenerator.randomByte(),this._decryptGenerator.randomByte();return this._setGenerators=!0,!0}_read(){}_message(e,t,n){const r=n?n.length:0,s=i.allocUnsafe(5+4*t.length);s.writeUInt32BE(s.length+r-4,0),s[4]=e;for(let e=0;e{if(r===this._pull(this.peerRequests,e,t,i))return n?(this._debug("error satisfying request index=%d offset=%d length=%d (%s)",e,t,i,n.message),void(this.hasFast&&this.reject(e,t,i))):void this.piece(e,t,s)},r=new A(e,t,i,n);this.peerRequests.push(r),this.emit("request",e,t,i,n)}_onPiece(e,t,i){this._debug("got piece index=%d offset=%d",e,t),this._callback(this._pull(this.requests,e,t,i.length),null,i),this.downloaded+=i.length,this.downloadSpeed(i.length),this.emit("download",i.length),this.emit("piece",e,t,i)}_onCancel(e,t,i){this._debug("got cancel index=%d offset=%d length=%d",e,t,i),this._pull(this.peerRequests,e,t,i),this.emit("cancel",e,t,i)}_onPort(e){this._debug("got port %d",e),this.emit("port",e)}_onSuggest(e){if(!this.hasFast)return this._debug("Error: got suggest whereas fast extension is disabled"),void this.destroy();this._debug("got suggest %d",e),this.emit("suggest",e)}_onHaveAll(){if(!this.hasFast)return this._debug("Error: got have-all whereas fast extension is disabled"),void this.destroy();this._debug("got have-all"),this.peerPieces=new j,this.emit("have-all")}_onHaveNone(){if(!this.hasFast)return this._debug("Error: got have-none whereas fast extension is disabled"),void this.destroy();this._debug("got have-none"),this.emit("have-none")}_onReject(e,t,i){if(!this.hasFast)return this._debug("Error: got reject whereas fast extension is disabled"),void this.destroy();this._debug("got reject index=%d offset=%d length=%d",e,t,i),this._callback(this._pull(this.requests,e,t,i),new Error("request was rejected"),null),this.emit("reject",e,t,i)}_onAllowedFast(e){if(!this.hasFast)return this._debug("Error: got allowed-fast whereas fast extension is disabled"),void this.destroy();this._debug("got allowed-fast %d",e),this.peerAllowedFastSet.includes(e)||this.peerAllowedFastSet.push(e),this.peerAllowedFastSet.length>100&&this.peerAllowedFastSet.shift(),this.emit("allowed-fast",e)}_onExtended(e,t){if(0===e){let e;try{e=r.decode(t)}catch(e){this._debug("ignoring invalid extended handshake: %s",e.message||e)}if(!e)return;if(this.peerExtendedHandshake=e,"object"==typeof e.m)for(const t in e.m)this.peerExtendedMapping[t]=Number(e.m[t].toString());for(const e in this._ext)this.peerExtendedMapping[e]&&this._ext[e].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,n){if(2===this._encryptionMethod&&this._cryptoHandshakeDone&&(e=this._decrypt(e)),this._bufferSize+=e.length,this._buffer.push(e),this._buffer.length>1&&(this._buffer=[i.concat(this._buffer,this._bufferSize)]),this._cryptoSyncPattern){const t=this._buffer[0].indexOf(this._cryptoSyncPattern);if(-1!==t)this._buffer[0]=this._buffer[0].slice(t+this._cryptoSyncPattern.length),this._bufferSize-=t+this._cryptoSyncPattern.length,this._cryptoSyncPattern=null;else if(this._bufferSize+e.length>this._waitMaxBytes+this._cryptoSyncPattern.length)return this._debug("Error: could not resynchronize"),void this.destroy()}for(;this._bufferSize>=this._parserSize&&!this._cryptoSyncPattern;)if(0===this._parserSize)this._parser(i.from([]));else{const e=this._buffer[0];this._bufferSize-=this._parserSize,this._buffer=this._bufferSize?[e.slice(this._parserSize)]:[],this._parser(e.slice(0,this._parserSize))}n(null)}_callback(e,t,i){e&&(this._resetTimeout(!this.peerChoking&&!this._finished),e.callback(t,i))}_resetTimeout(e){if(!e||!this._timeoutMs||!this.requests.length)return clearTimeout(this._timeout),this._timeout=null,void(this._timeoutExpiresAt=null);const t=Date.now()+this._timeoutMs;if(this._timeout){if(t-this._timeoutExpiresAt<.05*this._timeoutMs)return;clearTimeout(this._timeout)}this._timeoutExpiresAt=t,this._timeout=setTimeout((()=>this._onTimeout()),this._timeoutMs),this._timeoutUnref&&this._timeout.unref&&this._timeout.unref()}_parse(e,t){this._parserSize=e,this._parser=t}_parseUntil(e,t){this._cryptoSyncPattern=e,this._waitMaxBytes=t}_onMessageLength(e){const t=e.readUInt32BE(0);t>0?this._parse(t,this._onMessage):(this._onKeepAlive(),this._parse(4,this._onMessageLength))}_onMessage(e){switch(this._parse(4,this._onMessageLength),e[0]){case 0:return this._onChoke();case 1:return this._onUnchoke();case 2:return this._onInterested();case 3:return this._onUninterested();case 4:return this._onHave(e.readUInt32BE(1));case 5:return this._onBitField(e.slice(1));case 6:return this._onRequest(e.readUInt32BE(1),e.readUInt32BE(5),e.readUInt32BE(9));case 7:return this._onPiece(e.readUInt32BE(1),e.readUInt32BE(5),e.slice(9));case 8:return this._onCancel(e.readUInt32BE(1),e.readUInt32BE(5),e.readUInt32BE(9));case 9:return this._onPort(e.readUInt16BE(1));case 13:return this._onSuggest(e.readUInt32BE(1));case 14:return this._onHaveAll();case 15:return this._onHaveNone();case 16:return this._onReject(e.readUInt32BE(1),e.readUInt32BE(5),e.readUInt32BE(9));case 17:return this._onAllowedFast(e.readUInt32BE(1));case 20:return this._onExtended(e.readUInt8(1),e.slice(2));default:return this._debug("got unknown message"),this.emit("unknownmessage",e)}}_determineHandshakeType(){this._parse(1,(e=>{const t=e.readUInt8(0);19===t?this._parse(t+48,this._onHandshakeBuffer):this._parsePe1(e)}))}_parsePe1(e){this._parse(95,(t=>{this._onPe1(i.concat([e,t])),this._parsePe3()}))}_parsePe2(){this._parse(96,(e=>{for(this._onPe2(e);!this._setGenerators;);this._parsePe4()}))}_parsePe3(){const e=i.from(l.sync(i.from(this._utfToHex("req1")+this._sharedSecret,"hex")),"hex");this._parseUntil(e,512),this._parse(20,(e=>{for(this._onPe3(e);!this._setGenerators;);this._parsePe3Encrypted()}))}_parsePe3Encrypted(){this._parse(14,(e=>{const t=this._decryptHandshake(e.slice(0,8)),i=this._decryptHandshake(e.slice(8,12)),n=this._decryptHandshake(e.slice(12,14)).readUInt16BE(0);this._parse(n,(e=>{e=this._decryptHandshake(e),this._parse(2,(n=>{const r=this._decryptHandshake(n).readUInt16BE(0);this._parse(r,(n=>{n=this._decryptHandshake(n),this._onPe3Encrypted(t,i,e,n);const s=r?n.readUInt8(0):null,a=r?n.slice(1,20):null;19===s&&"BitTorrent protocol"===a.toString()?this._onHandshakeBuffer(n.slice(1)):this._parseHandshake()}))}))}))}))}_parsePe4(){const e=this._decryptHandshake(k);this._parseUntil(e,512),this._parse(6,(e=>{const t=this._decryptHandshake(e.slice(0,4)),i=this._decryptHandshake(e.slice(4,6)).readUInt16BE(0);this._parse(i,(e=>{this._decryptHandshake(e),this._onPe4(t),this._parseHandshake(null)}))}))}_parseHandshake(){this._parse(1,(e=>{const t=e.readUInt8(0);if(19!==t)return this._debug("Error: wire not speaking BitTorrent protocol (%s)",t.toString()),void this.end();this._parse(t+48,this._onHandshakeBuffer)}))}_onHandshakeBuffer(e){const t=e.slice(0,19);if("BitTorrent protocol"!==t.toString())return this._debug("Error: wire not speaking BitTorrent protocol (%s)",t.toString()),void this.end();e=e.slice(19),this._onHandshake(e.slice(8,28),e.slice(28,48),{dht:!!(1&e[7]),fast:!!(4&e[7]),extended:!!(16&e[5])}),this._parse(4,this._onMessageLength)}_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]}`,o(...e)}_pull(e,t,i,r){for(let s=0;s2?"one of ".concat(t," ").concat(e.slice(0,i-1).join(", "),", or ")+e[i-1]:2===i?"one of ".concat(t," ").concat(e[0]," or ").concat(e[1]):"of ".concat(t," ").concat(e[0])}return"of ".concat(t," ").concat(String(e))}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,i){var n,r,a,o;if("string"==typeof t&&(r="not ",t.substr(!a||a<0?0:+a,r.length)===r)?(n="must not be",t=t.replace(/^not /,"")):n="must be",function(e,t,i){return(void 0===i||i>e.length)&&(i=e.length),e.substring(i-t.length,i)===t}(e," argument"))o="The ".concat(e," ").concat(n," ").concat(s(t,"type"));else{var c=function(e,t,i){return"number"!=typeof i&&(i=0),!(i+t.length>e.length)&&-1!==e.indexOf(t,i)}(e,".")?"property":"argument";o='The "'.concat(e,'" ').concat(c," ").concat(n," ").concat(s(t,"type"))}return o+=". Received type ".concat(typeof i)}),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=n},{}],29:[function(e,t,i){(function(i){(function(){"use strict";var n=Object.keys||function(e){var t=[];for(var i in e)t.push(i);return t};t.exports=l;var r=e("./_stream_readable"),s=e("./_stream_writable");e("inherits")(l,r);for(var a=n(s.prototype),o=0;o0)if("string"==typeof t||a.objectMode||Object.getPrototypeOf(t)===o.prototype||(t=function(e){return o.from(e)}(t)),n)a.endEmitted?w(e,new x):A(e,a,t,!0);else if(a.ended)w(e,new y);else{if(a.destroyed)return!1;a.reading=!1,a.decoder&&!i?(t=a.decoder.write(t),a.objectMode||0!==t.length?A(e,a,t,!1):B(e,a)):A(e,a,t,!1)}else n||(a.reading=!1,B(e,a));return!a.ended&&(a.lengtht.highWaterMark&&(t.highWaterMark=function(e){return e>=j?e=j:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0))}function T(e){var t=e._readableState;l("emitReadable",t.needReadable,t.emittedReadable),t.needReadable=!1,t.emittedReadable||(l("emitReadable",t.flowing),t.emittedReadable=!0,i.nextTick(C,e))}function C(e){var t=e._readableState;l("emitReadable_",t.destroyed,t.length,t.ended),t.destroyed||!t.length&&!t.ended||(e.emit("readable"),t.emittedReadable=!1),t.needReadable=!t.flowing&&!t.ended&&t.length<=t.highWaterMark,U(e)}function B(e,t){t.readingMore||(t.readingMore=!0,i.nextTick(R,e,t))}function R(e,t){for(;!t.reading&&!t.ended&&(t.length0,t.resumeScheduled&&!t.paused?t.flowing=!0:e.listenerCount("data")>0&&e.resume()}function O(e){l("readable nexttick read 0"),e.read(0)}function P(e,t){l("resume",t.reading),t.reading||e.read(0),t.resumeScheduled=!1,e.emit("resume"),U(e),t.flowing&&!t.reading&&e.read(0)}function U(e){var t=e._readableState;for(l("flow",t.flowing);t.flowing&&null!==e.read(););}function q(e,t){return 0===t.length?null:(t.objectMode?i=t.buffer.shift():!e||e>=t.length?(i=t.decoder?t.buffer.join(""):1===t.buffer.length?t.buffer.first():t.buffer.concat(t.length),t.buffer.clear()):i=t.buffer.consume(e,t.decoder),i);var i}function N(e){var t=e._readableState;l("endReadable",t.endEmitted),t.endEmitted||(t.ended=!0,i.nextTick(D,t,e))}function D(e,t){if(l("endReadableNT",e.endEmitted,e.length),!e.endEmitted&&0===e.length&&(e.endEmitted=!0,t.readable=!1,t.emit("end"),e.autoDestroy)){var i=t._writableState;(!i||i.autoDestroy&&i.finished)&&t.destroy()}}function z(e,t){for(var i=0,n=e.length;i=t.highWaterMark:t.length>0)||t.ended))return l("read: emitReadable",t.length,t.ended),0===t.length&&t.ended?N(this):T(this),null;if(0===(e=I(e,t))&&t.ended)return 0===t.length&&N(this),null;var n,r=t.needReadable;return l("need readable",r),(0===t.length||t.length-e0?q(e,t):null)?(t.needReadable=t.length<=t.highWaterMark,e=0):(t.length-=e,t.awaitDrain=0),0===t.length&&(t.ended||(t.needReadable=!0),i!==e&&t.ended&&N(this)),null!==n&&this.emit("data",n),n},S.prototype._read=function(e){w(this,new _("_read()"))},S.prototype.pipe=function(e,t){var n=this,r=this._readableState;switch(r.pipesCount){case 0:r.pipes=e;break;case 1:r.pipes=[r.pipes,e];break;default:r.pipes.push(e)}r.pipesCount+=1,l("pipe count=%d opts=%j",r.pipesCount,t);var a=(!t||!1!==t.end)&&e!==i.stdout&&e!==i.stderr?c:b;function o(t,i){l("onunpipe"),t===n&&i&&!1===i.hasUnpiped&&(i.hasUnpiped=!0,l("cleanup"),e.removeListener("close",h),e.removeListener("finish",m),e.removeListener("drain",u),e.removeListener("error",f),e.removeListener("unpipe",o),n.removeListener("end",c),n.removeListener("end",b),n.removeListener("data",d),p=!0,!r.awaitDrain||e._writableState&&!e._writableState.needDrain||u())}function c(){l("onend"),e.end()}r.endEmitted?i.nextTick(a):n.once("end",a),e.on("unpipe",o);var u=function(e){return function(){var t=e._readableState;l("pipeOnDrain",t.awaitDrain),t.awaitDrain&&t.awaitDrain--,0===t.awaitDrain&&s(e,"data")&&(t.flowing=!0,U(e))}}(n);e.on("drain",u);var p=!1;function d(t){l("ondata");var i=e.write(t);l("dest.write",i),!1===i&&((1===r.pipesCount&&r.pipes===e||r.pipesCount>1&&-1!==z(r.pipes,e))&&!p&&(l("false write response, pause",r.awaitDrain),r.awaitDrain++),n.pause())}function f(t){l("onerror",t),b(),e.removeListener("error",f),0===s(e,"error")&&w(e,t)}function h(){e.removeListener("finish",m),b()}function m(){l("onfinish"),e.removeListener("close",h),b()}function b(){l("unpipe"),n.unpipe(e)}return n.on("data",d),function(e,t,i){if("function"==typeof e.prependListener)return e.prependListener(t,i);e._events&&e._events[t]?Array.isArray(e._events[t])?e._events[t].unshift(i):e._events[t]=[i,e._events[t]]:e.on(t,i)}(e,"error",f),e.once("close",h),e.once("finish",m),e.emit("pipe",n),r.flowing||(l("pipe resume"),n.resume()),e},S.prototype.unpipe=function(e){var t=this._readableState,i={hasUnpiped:!1};if(0===t.pipesCount)return this;if(1===t.pipesCount)return e&&e!==t.pipes||(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit("unpipe",this,i)),this;if(!e){var n=t.pipes,r=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var s=0;s0,!1!==r.flowing&&this.resume()):"readable"===e&&(r.endEmitted||r.readableListening||(r.readableListening=r.needReadable=!0,r.flowing=!1,r.emittedReadable=!1,l("on readable",r.length,r.reading),r.length?T(this):r.reading||i.nextTick(O,this))),n},S.prototype.addListener=S.prototype.on,S.prototype.removeListener=function(e,t){var n=a.prototype.removeListener.call(this,e,t);return"readable"===e&&i.nextTick(L,this),n},S.prototype.removeAllListeners=function(e){var t=a.prototype.removeAllListeners.apply(this,arguments);return"readable"!==e&&void 0!==e||i.nextTick(L,this),t},S.prototype.resume=function(){var e=this._readableState;return e.flowing||(l("resume"),e.flowing=!e.readableListening,function(e,t){t.resumeScheduled||(t.resumeScheduled=!0,i.nextTick(P,e,t))}(this,e)),e.paused=!1,this},S.prototype.pause=function(){return l("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(l("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState.paused=!0,this},S.prototype.wrap=function(e){var t=this,i=this._readableState,n=!1;for(var r in e.on("end",(function(){if(l("wrapped end"),i.decoder&&!i.ended){var e=i.decoder.end();e&&e.length&&t.push(e)}t.push(null)})),e.on("data",(function(r){(l("wrapped data"),i.decoder&&(r=i.decoder.write(r)),i.objectMode&&null==r)||(i.objectMode||r&&r.length)&&(t.push(r)||(n=!0,e.pause()))})),e)void 0===this[r]&&"function"==typeof e[r]&&(this[r]=function(t){return function(){return e[t].apply(e,arguments)}}(r));for(var s=0;s-1))throw new x(e);return this._writableState.defaultEncoding=e,this},Object.defineProperty(S.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(S.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),S.prototype._write=function(e,t,i){i(new m("_write()"))},S.prototype._writev=null,S.prototype.end=function(e,t,n){var r=this._writableState;return"function"==typeof e?(n=e,e=null,t=null):"function"==typeof t&&(n=t,t=null),null!=e&&this.write(e,t),r.corked&&(r.corked=1,this.uncork()),r.ending||function(e,t,n){t.ending=!0,C(e,t),n&&(t.finished?i.nextTick(n):e.once("finish",n));t.ended=!0,e.writable=!1}(this,r,n),this},Object.defineProperty(S.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(S.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._writableState&&this._writableState.destroyed},set:function(e){this._writableState&&(this._writableState.destroyed=e)}}),S.prototype.destroy=p.destroy,S.prototype._undestroy=p.undestroy,S.prototype._destroy=function(e,t){t(e)}}).call(this)}).call(this,e("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../errors":28,"./_stream_duplex":29,"./internal/streams/destroy":36,"./internal/streams/state":40,"./internal/streams/stream":41,_process:340,buffer:109,inherits:245,"util-deprecate":485}],34:[function(e,t,i){(function(i){(function(){"use strict";var n;function r(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}var s=e("./end-of-stream"),a=Symbol("lastResolve"),o=Symbol("lastReject"),c=Symbol("error"),l=Symbol("ended"),u=Symbol("lastPromise"),p=Symbol("handlePromise"),d=Symbol("stream");function f(e,t){return{value:e,done:t}}function h(e){var t=e[a];if(null!==t){var i=e[d].read();null!==i&&(e[u]=null,e[a]=null,e[o]=null,t(f(i,!1)))}}function m(e){i.nextTick(h,e)}var b=Object.getPrototypeOf((function(){})),v=Object.setPrototypeOf((r(n={get stream(){return this[d]},next:function(){var e=this,t=this[c];if(null!==t)return Promise.reject(t);if(this[l])return Promise.resolve(f(void 0,!0));if(this[d].destroyed)return new Promise((function(t,n){i.nextTick((function(){e[c]?n(e[c]):t(f(void 0,!0))}))}));var n,r=this[u];if(r)n=new Promise(function(e,t){return function(i,n){e.then((function(){t[l]?i(f(void 0,!0)):t[p](i,n)}),n)}}(r,this));else{var s=this[d].read();if(null!==s)return Promise.resolve(f(s,!1));n=new Promise(this[p])}return this[u]=n,n}},Symbol.asyncIterator,(function(){return this})),r(n,"return",(function(){var e=this;return new Promise((function(t,i){e[d].destroy(null,(function(e){e?i(e):t(f(void 0,!0))}))}))})),n),b);t.exports=function(e){var t,i=Object.create(v,(r(t={},d,{value:e,writable:!0}),r(t,a,{value:null,writable:!0}),r(t,o,{value:null,writable:!0}),r(t,c,{value:null,writable:!0}),r(t,l,{value:e._readableState.endEmitted,writable:!0}),r(t,p,{value:function(e,t){var n=i[d].read();n?(i[u]=null,i[a]=null,i[o]=null,e(f(n,!1))):(i[a]=e,i[o]=t)},writable:!0}),t));return i[u]=null,s(e,(function(e){if(e&&"ERR_STREAM_PREMATURE_CLOSE"!==e.code){var t=i[o];return null!==t&&(i[u]=null,i[a]=null,i[o]=null,t(e)),void(i[c]=e)}var n=i[a];null!==n&&(i[u]=null,i[a]=null,i[o]=null,n(f(void 0,!0))),i[l]=!0})),e.on("readable",m.bind(null,i)),i}}).call(this)}).call(this,e("_process"))},{"./end-of-stream":37,_process:340}],35:[function(e,t,i){"use strict";function n(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function r(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}function s(e,t){for(var i=0;i0?this.tail.next=t:this.head=t,this.tail=t,++this.length}},{key:"unshift",value:function(e){var t={data:e,next:this.head};0===this.length&&(this.tail=t),this.head=t,++this.length}},{key:"shift",value:function(){if(0!==this.length){var e=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,e}}},{key:"clear",value:function(){this.head=this.tail=null,this.length=0}},{key:"join",value:function(e){if(0===this.length)return"";for(var t=this.head,i=""+t.data;t=t.next;)i+=e+t.data;return i}},{key:"concat",value:function(e){if(0===this.length)return a.alloc(0);for(var t,i,n,r=a.allocUnsafe(e>>>0),s=this.head,o=0;s;)t=s.data,i=r,n=o,a.prototype.copy.call(t,i,n),o+=s.data.length,s=s.next;return r}},{key:"consume",value:function(e,t){var i;return er.length?r.length:e;if(s===r.length?n+=r:n+=r.slice(0,e),0==(e-=s)){s===r.length?(++i,t.next?this.head=t.next:this.head=this.tail=null):(this.head=t,t.data=r.slice(s));break}++i}return this.length-=i,n}},{key:"_getBuffer",value:function(e){var t=a.allocUnsafe(e),i=this.head,n=1;for(i.data.copy(t),e-=i.data.length;i=i.next;){var r=i.data,s=e>r.length?r.length:e;if(r.copy(t,t.length-e,0,s),0==(e-=s)){s===r.length?(++n,i.next?this.head=i.next:this.head=this.tail=null):(this.head=i,i.data=r.slice(s));break}++n}return this.length-=n,t}},{key:c,value:function(e,t){return o(this,function(e){for(var t=1;t0,(function(e){n||(n=e),e&&a.forEach(l),s||(a.forEach(l),r(n))}))}));return t.reduce(u)}},{"../../../errors":28,"./end-of-stream":37}],40:[function(e,t,i){"use strict";var n=e("../../../errors").codes.ERR_INVALID_OPT_VALUE;t.exports={getHighWaterMark:function(e,t,i,r){var s=function(e,t,i){return null!=e.highWaterMark?e.highWaterMark:t?e[i]:null}(t,r,i);if(null!=s){if(!isFinite(s)||Math.floor(s)!==s||s<0)throw new n(r?i:"highWaterMark",s);return Math.floor(s)}return e.objectMode?16:16384}}},{"../../../errors":28}],41:[function(e,t,i){t.exports=e("events").EventEmitter},{events:192}],42:[function(e,t,i){(i=t.exports=e("./lib/_stream_readable.js")).Stream=i,i.Readable=i,i.Writable=e("./lib/_stream_writable.js"),i.Duplex=e("./lib/_stream_duplex.js"),i.Transform=e("./lib/_stream_transform.js"),i.PassThrough=e("./lib/_stream_passthrough.js"),i.finished=e("./lib/internal/streams/end-of-stream.js"),i.pipeline=e("./lib/internal/streams/pipeline.js")},{"./lib/_stream_duplex.js":29,"./lib/_stream_passthrough.js":30,"./lib/_stream_readable.js":31,"./lib/_stream_transform.js":32,"./lib/_stream_writable.js":33,"./lib/internal/streams/end-of-stream.js":37,"./lib/internal/streams/pipeline.js":39}],43:[function(e,t,i){(function(i,n){(function(){const r=e("debug")("bittorrent-tracker:client"),s=e("events"),a=e("once"),o=e("run-parallel"),c=e("simple-peer"),l=e("queue-microtask"),u=e("./lib/common"),p=e("./lib/client/http-tracker"),d=e("./lib/client/udp-tracker"),f=e("./lib/client/websocket-tracker");class h extends s{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(!i.browser&&!e.port)throw new Error("Option `port` is required");this.peerId="string"==typeof e.peerId?e.peerId:e.peerId.toString("hex"),this._peerIdBuffer=n.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=n.from(this.infoHash,"hex"),this._infoHashBinary=this._infoHashBuffer.toString("binary"),r("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._proxyOpts=e.proxyOpts,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.length-1]&&(e=e.substring(0,e.length-1)),e))),t=Array.from(new Set(t));const s=!1!==this._wrtc&&(!!this._wrtc||c.WEBRTC_SUPPORT),a=e=>{l((()=>{this.emit("warning",e)}))};this._trackers=t.map((e=>{let t;try{t=u.parseUrl(e)}catch(t){return a(new Error(`Invalid tracker URL: ${e}`)),null}const i=t.port;if(i<0||i>65535)return a(new Error(`Invalid tracker port: ${e}`)),null;const n=t.protocol;return"http:"!==n&&"https:"!==n||"function"!=typeof p?"udp:"===n&&"function"==typeof d?new d(this,e):"ws:"!==n&&"wss:"!==n||!s||"ws:"===n&&"undefined"!=typeof window&&"https:"===window.location.protocol?(a(new Error(`Unsupported tracker protocol: ${e}`)),null):new f(this,e):new p(this,e)})).filter(Boolean)}start(e){(e=this._defaultAnnounceOpts(e)).event="started",r("send `start` %o",e),this._announce(e),this._trackers.forEach((e=>{e.setInterval()}))}stop(e){(e=this._defaultAnnounceOpts(e)).event="stopped",r("send `stop` %o",e),this._announce(e)}complete(e){e||(e={}),(e=this._defaultAnnounceOpts(e)).event="completed",r("send `complete` %o",e),this._announce(e)}update(e){(e=this._defaultAnnounceOpts(e)).event&&delete e.event,r("send `update` %o",e),this._announce(e)}_announce(e){this._trackers.forEach((t=>{t.announce(e)}))}scrape(e){r("send `scrape`"),e||(e={}),this._trackers.forEach((t=>{t.scrape(e)}))}setInterval(e){r("setInterval %d",e),this._trackers.forEach((t=>{t.setInterval(e)}))}destroy(e){if(this.destroyed)return;this.destroyed=!0,r("destroy");const t=this._trackers.map((e=>t=>{e.destroy(t)}));o(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}}h.scrape=(e,t)=>{if(t=a(t),!e.infoHash)throw new Error("Option `infoHash` is required");if(!e.announce)throw new Error("Option `announce` is required");const i=Object.assign({},e,{infoHash:Array.isArray(e.infoHash)?e.infoHash[0]:e.infoHash,peerId:n.from("01234567890123456789"),port:6881}),r=new h(i);r.once("error",t),r.once("warning",t);let s=Array.isArray(e.infoHash)?e.infoHash.length:1;const o={};return r.on("scrape",(e=>{if(s-=1,o[e.infoHash]=e,0===s){r.destroy();const e=Object.keys(o);1===e.length?t(null,o[e[0]]):t(null,o)}})),e.infoHash=Array.isArray(e.infoHash)?e.infoHash.map((e=>n.from(e,"hex"))):n.from(e.infoHash,"hex"),r.scrape({infoHash:e.infoHash}),r},t.exports=h}).call(this)}).call(this,e("_process"),e("buffer").Buffer)},{"./lib/client/http-tracker":66,"./lib/client/udp-tracker":66,"./lib/client/websocket-tracker":45,"./lib/common":46,_process:340,buffer:109,debug:160,events:192,once:325,"queue-microtask":353,"run-parallel":380,"simple-peer":394}],44:[function(e,t,i){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:192}],45:[function(e,t,i){const n=e("clone"),r=e("debug")("bittorrent-tracker:websocket-tracker"),s=e("simple-peer"),a=e("randombytes"),o=e("simple-websocket"),c=e("socks"),l=e("../common"),u=e("./tracker"),p={};class d extends u{constructor(e,t){super(e,t),r("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 i=Math.min(e.numwant,5);this._generateOffers(i,(e=>{t.numwant=i,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={action:"scrape",info_hash:Array.isArray(e.infoHash)&&e.infoHash.length>0?e.infoHash.map((e=>e.toString("binary"))):e.infoHash&&e.infoHash.toString("binary")||this.client._infoHashBinary};this._send(t)}destroy(e=f){if(this.destroyed)return e(null);this.destroyed=!0,clearInterval(this.interval),clearTimeout(this.reconnectTimer);for(const e in this.peers){const t=this.peers[e];clearTimeout(t.trackerTimeout),t.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),p[this.announceUrl].consumers>0)return e();let t,i=p[this.announceUrl];if(delete p[this.announceUrl],i.on("error",f),i.once("close",e),!this.expectingResponse)return n();function n(){t&&(clearTimeout(t),t=null),i.removeListener("data",n),i.destroy(),i=null}t=setTimeout(n,l.DESTROY_TIMEOUT),i.once("data",n)}_openSocket(){if(this.destroyed=!1,this.peers||(this.peers={}),this._onSocketConnectBound=()=>{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.connected&&this._onSocketConnectBound();else{const e=new URL(this.announceUrl);let t;this.client._proxyOpts&&(t="wss:"===e.protocol?this.client._proxyOpts.httpsAgent:this.client._proxyOpts.httpAgent,!t&&this.client._proxyOpts.socksProxy&&(t=new c.Agent(n(this.client._proxyOpts.socksProxy),"wss:"===e.protocol))),this.socket=p[this.announceUrl]=new o({url:this.announceUrl,agent:t}),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 r("ignoring websocket data from %s for %s (looking for %s: reused socket)",this.announceUrl,l.binaryToHex(e.info_hash),this.client.infoHash);if(e.peer_id&&e.peer_id===this.client._peerIdBinary)return;r("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 i=e["warning message"];i&&this.client.emit("warning",new Error(i));const n=e.interval||e["min interval"];n&&this.setInterval(1e3*n);const s=e["tracker id"];if(s&&(this._trackerId=s),null!=e.complete){const t=Object.assign({},e,{announce:this.announceUrl,infoHash:l.binaryToHex(e.info_hash)});this.client.emit("update",t)}let a;if(e.offer&&e.peer_id&&(r("creating peer (from remote offer)"),a=this._createPeer(),a.id=l.binaryToHex(e.peer_id),a.once("signal",(t=>{const i={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&&(i.trackerid=this._trackerId),this._send(i)})),this.client.emit("peer",a),a.signal(e.offer)),e.answer&&e.peer_id){const t=l.binaryToHex(e.offer_id);a=this.peers[t],a?(a.id=l.binaryToHex(e.peer_id),this.client.emit("peer",a),a.signal(e.answer),clearTimeout(a.trackerTimeout),a.trackerTimeout=null,delete this.peers[t]):r(`got unexpected answer: ${JSON.stringify(e.answer)}`)}}_onScrapeResponse(e){e=e.files||{};const t=Object.keys(e);0!==t.length?t.forEach((t=>{const i=Object.assign(e[t],{announce:this.announceUrl,infoHash:l.binaryToHex(t)});this.client.emit("scrape",i)})):this.client.emit("warning",new Error("invalid scrape response"))}_onSocketClose(){this.destroyed||(this.destroy(),this._startReconnectTimer())}_onSocketError(e){this.destroyed||(this.destroy(),this.client.emit("warning",e),this._startReconnectTimer())}_startReconnectTimer(){const e=Math.floor(3e5*Math.random())+Math.min(1e4*Math.pow(2,this.retries),36e5);this.reconnecting=!0,clearTimeout(this.reconnectTimer),this.reconnectTimer=setTimeout((()=>{this.retries++,this._openSocket()}),e),this.reconnectTimer.unref&&this.reconnectTimer.unref(),r("reconnecting socket in %s ms",e)}_send(e){if(this.destroyed)return;this.expectingResponse=!0;const t=JSON.stringify(e);r("send %s",t),this.socket.send(t)}_generateOffers(e,t){const i=this,n=[];r("generating %s offers",e);for(let t=0;t{n.push({offer:t,offer_id:l.hexToBinary(e)}),o()})),t.trackerTimeout=setTimeout((()=>{r("tracker timeout: destroying peer"),t.trackerTimeout=null,delete i.peers[e],t.destroy()}),5e4),t.trackerTimeout.unref&&t.trackerTimeout.unref()}function o(){n.length===e&&(r("generated %s offers",e),t(n))}o()}_createPeer(e){const t=this;e=Object.assign({trickle:!1,config:t.client._rtcConfig,wrtc:t.client._wrtc},e);const i=new s(e);return i.once("error",n),i.once("connect",(function e(){i.removeListener("error",n),i.removeListener("connect",e)})),i;function n(e){t.client.emit("warning",new Error(`Connection error: ${e.message}`)),i.destroy()}}}function f(){}d.prototype.DEFAULT_ANNOUNCE_INTERVAL=3e4,d._socketPool=p,t.exports=d},{"../common":46,"./tracker":44,clone:135,debug:160,randombytes:356,"simple-peer":394,"simple-websocket":412,socks:66}],46:[function(e,t,i){(function(t){(function(){i.DEFAULT_ANNOUNCE_PEERS=50,i.MAX_ANNOUNCE_PEERS=82,i.binaryToHex=e=>("string"!=typeof e&&(e=String(e)),t.from(e,"binary").toString("hex")),i.hexToBinary=e=>("string"!=typeof e&&(e=String(e)),t.from(e,"hex").toString("binary")),i.parseUrl=e=>{const t=new URL(e.replace(/^udp:/,"http:"));return e.match(/^udp:/)&&Object.defineProperties(t,{href:{value:t.href.replace(/^http/,"udp")},protocol:{value:t.protocol.replace(/^http/,"udp")},origin:{value:t.origin.replace(/^http/,"udp")}}),t};const n=e("./common-node");Object.assign(i,n)}).call(this)}).call(this,e("buffer").Buffer)},{"./common-node":66,buffer:109}],47:[function(e,t,i){(function(e){(function(){ /*! blob-to-buffer. MIT License. Feross Aboukhadijeh */ -t.exports=function(t,i){if("undefined"==typeof Blob||!(t instanceof Blob))throw new Error("first argument must be a Blob");if("function"!=typeof i)throw new Error("second argument must be a function");const n=new FileReader;n.addEventListener("loadend",(function t(r){n.removeEventListener("loadend",t,!1),r.error?i(r.error):i(null,e.from(n.result))}),!1),n.readAsArrayBuffer(t)}}).call(this)}).call(this,e("buffer").Buffer)},{buffer:109}],48:[function(e,t,i){(function(i){(function(){const{Transform:n}=e("readable-stream");t.exports=class extends n{constructor(e,t={}){super(t),"object"==typeof e&&(e=(t=e).size),this.size=e||512;const{nopad:i,zeroPadding:n=!0}=t;this._zeroPadding=!i&&!!n,this._buffered=[],this._bufferedBytes=0}_transform(e,t,n){for(this._bufferedBytes+=e.length,this._buffered.push(e);this._bufferedBytes>=this.size;){this._bufferedBytes-=this.size;const e=[];let t=0;for(;t=48&&i<=57?i-48:i>=65&&i<=70?i-55:i>=97&&i<=102?i-87:void n(!1,"Invalid character in "+e)}function c(e,t,i){var n=o(e,i);return i-1>=t&&(n|=o(e,i-1)<<4),n}function l(e,t,i,r){for(var s=0,a=0,o=Math.min(e.length,i),c=t;c=49?l-49+10:l>=17?l-17+10:l,n(l>=0&&a0?e:t},s.min=function(e,t){return e.cmp(t)<0?e:t},s.prototype._init=function(e,t,i){if("number"==typeof e)return this._initNumber(e,t,i);if("object"==typeof e)return this._initArray(e,t,i);"hex"===t&&(t=16),n(t===(0|t)&&t>=2&&t<=36);var r=0;"-"===(e=e.toString().replace(/\s+/g,""))[0]&&(r++,this.negative=1),r=0;r-=3)a=e[r]|e[r-1]<<8|e[r-2]<<16,this.words[s]|=a<>>26-o&67108863,(o+=24)>=26&&(o-=26,s++);else if("le"===i)for(r=0,s=0;r>>26-o&67108863,(o+=24)>=26&&(o-=26,s++);return this._strip()},s.prototype._parseHex=function(e,t,i){this.length=Math.ceil((e.length-t)/6),this.words=new Array(this.length);for(var n=0;n=t;n-=2)r=c(e,t,n)<=18?(s-=18,a+=1,this.words[a]|=r>>>26):s+=8;else for(n=(e.length-t)%2==0?t+1:t;n=18?(s-=18,a+=1,this.words[a]|=r>>>26):s+=8;this._strip()},s.prototype._parseBase=function(e,t,i){this.words=[0],this.length=1;for(var n=0,r=1;r<=67108863;r*=t)n++;n--,r=r/t|0;for(var s=e.length-i,a=s%n,o=Math.min(s,s-a)+i,c=0,u=i;u1&&0===this.words[this.length-1];)this.length--;return this._normSign()},s.prototype._normSign=function(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this},"undefined"!=typeof Symbol&&"function"==typeof Symbol.for)try{s.prototype[Symbol.for("nodejs.util.inspect.custom")]=p}catch(e){s.prototype.inspect=p}else s.prototype.inspect=p;function p(){return(this.red?""}var d=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],f=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],h=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];s.prototype.toString=function(e,t){var i;if(t=0|t||1,16===(e=e||10)||"hex"===e){i="";for(var r=0,s=0,a=0;a>>24-r&16777215)||a!==this.length-1?d[6-c.length]+c+i:c+i,(r+=2)>=26&&(r-=26,a--)}for(0!==s&&(i=s.toString(16)+i);i.length%t!=0;)i="0"+i;return 0!==this.negative&&(i="-"+i),i}if(e===(0|e)&&e>=2&&e<=36){var l=f[e],u=h[e];i="";var p=this.clone();for(p.negative=0;!p.isZero();){var m=p.modrn(u).toString(e);i=(p=p.idivn(u)).isZero()?m+i:d[l-m.length]+m+i}for(this.isZero()&&(i="0"+i);i.length%t!=0;)i="0"+i;return 0!==this.negative&&(i="-"+i),i}n(!1,"Base should be between 2 and 36")},s.prototype.toNumber=function(){var e=this.words[0];return 2===this.length?e+=67108864*this.words[1]:3===this.length&&1===this.words[2]?e+=4503599627370496+67108864*this.words[1]:this.length>2&&n(!1,"Number can only safely store up to 53 bits"),0!==this.negative?-e:e},s.prototype.toJSON=function(){return this.toString(16,2)},a&&(s.prototype.toBuffer=function(e,t){return this.toArrayLike(a,e,t)}),s.prototype.toArray=function(e,t){return this.toArrayLike(Array,e,t)};function m(e,t,i){i.negative=t.negative^e.negative;var n=e.length+t.length|0;i.length=n,n=n-1|0;var r=0|e.words[0],s=0|t.words[0],a=r*s,o=67108863&a,c=a/67108864|0;i.words[0]=o;for(var l=1;l>>26,p=67108863&c,d=Math.min(l,t.length-1),f=Math.max(0,l-e.length+1);f<=d;f++){var h=l-f|0;u+=(a=(r=0|e.words[h])*(s=0|t.words[f])+p)/67108864|0,p=67108863&a}i.words[l]=0|p,c=0|u}return 0!==c?i.words[l]=0|c:i.length--,i._strip()}s.prototype.toArrayLike=function(e,t,i){this._strip();var r=this.byteLength(),s=i||Math.max(1,r);n(r<=s,"byte array longer than desired length"),n(s>0,"Requested array length <= 0");var a=function(e,t){return e.allocUnsafe?e.allocUnsafe(t):new e(t)}(e,s);return this["_toArrayLike"+("le"===t?"LE":"BE")](a,r),a},s.prototype._toArrayLikeLE=function(e,t){for(var i=0,n=0,r=0,s=0;r>8&255),i>16&255),6===s?(i>24&255),n=0,s=0):(n=a>>>24,s+=2)}if(i=0&&(e[i--]=a>>8&255),i>=0&&(e[i--]=a>>16&255),6===s?(i>=0&&(e[i--]=a>>24&255),n=0,s=0):(n=a>>>24,s+=2)}if(i>=0)for(e[i--]=n;i>=0;)e[i--]=0},Math.clz32?s.prototype._countBits=function(e){return 32-Math.clz32(e)}:s.prototype._countBits=function(e){var t=e,i=0;return t>=4096&&(i+=13,t>>>=13),t>=64&&(i+=7,t>>>=7),t>=8&&(i+=4,t>>>=4),t>=2&&(i+=2,t>>>=2),i+t},s.prototype._zeroBits=function(e){if(0===e)return 26;var t=e,i=0;return 0==(8191&t)&&(i+=13,t>>>=13),0==(127&t)&&(i+=7,t>>>=7),0==(15&t)&&(i+=4,t>>>=4),0==(3&t)&&(i+=2,t>>>=2),0==(1&t)&&i++,i},s.prototype.bitLength=function(){var e=this.words[this.length-1],t=this._countBits(e);return 26*(this.length-1)+t},s.prototype.zeroBits=function(){if(this.isZero())return 0;for(var e=0,t=0;te.length?this.clone().ior(e):e.clone().ior(this)},s.prototype.uor=function(e){return this.length>e.length?this.clone().iuor(e):e.clone().iuor(this)},s.prototype.iuand=function(e){var t;t=this.length>e.length?e:this;for(var i=0;ie.length?this.clone().iand(e):e.clone().iand(this)},s.prototype.uand=function(e){return this.length>e.length?this.clone().iuand(e):e.clone().iuand(this)},s.prototype.iuxor=function(e){var t,i;this.length>e.length?(t=this,i=e):(t=e,i=this);for(var n=0;ne.length?this.clone().ixor(e):e.clone().ixor(this)},s.prototype.uxor=function(e){return this.length>e.length?this.clone().iuxor(e):e.clone().iuxor(this)},s.prototype.inotn=function(e){n("number"==typeof e&&e>=0);var t=0|Math.ceil(e/26),i=e%26;this._expand(t),i>0&&t--;for(var r=0;r0&&(this.words[r]=~this.words[r]&67108863>>26-i),this._strip()},s.prototype.notn=function(e){return this.clone().inotn(e)},s.prototype.setn=function(e,t){n("number"==typeof e&&e>=0);var i=e/26|0,r=e%26;return this._expand(i+1),this.words[i]=t?this.words[i]|1<e.length?(i=this,n=e):(i=e,n=this);for(var r=0,s=0;s>>26;for(;0!==r&&s>>26;if(this.length=i.length,0!==r)this.words[this.length]=r,this.length++;else if(i!==this)for(;se.length?this.clone().iadd(e):e.clone().iadd(this)},s.prototype.isub=function(e){if(0!==e.negative){e.negative=0;var t=this.iadd(e);return e.negative=1,t._normSign()}if(0!==this.negative)return this.negative=0,this.iadd(e),this.negative=1,this._normSign();var i,n,r=this.cmp(e);if(0===r)return this.negative=0,this.length=1,this.words[0]=0,this;r>0?(i=this,n=e):(i=e,n=this);for(var s=0,a=0;a>26,this.words[a]=67108863&t;for(;0!==s&&a>26,this.words[a]=67108863&t;if(0===s&&a>>13,f=0|a[1],h=8191&f,m=f>>>13,b=0|a[2],v=8191&b,g=b>>>13,y=0|a[3],_=8191&y,x=y>>>13,w=0|a[4],k=8191&w,E=w>>>13,S=0|a[5],M=8191&S,A=S>>>13,j=0|a[6],I=8191&j,T=j>>>13,C=0|a[7],B=8191&C,R=C>>>13,L=0|a[8],O=8191&L,P=L>>>13,U=0|a[9],q=8191&U,N=U>>>13,D=0|o[0],z=8191&D,H=D>>>13,F=0|o[1],W=8191&F,V=F>>>13,K=0|o[2],$=8191&K,G=K>>>13,X=0|o[3],Y=8191&X,Z=X>>>13,J=0|o[4],Q=8191&J,ee=J>>>13,te=0|o[5],ie=8191&te,ne=te>>>13,re=0|o[6],se=8191&re,ae=re>>>13,oe=0|o[7],ce=8191&oe,le=oe>>>13,ue=0|o[8],pe=8191&ue,de=ue>>>13,fe=0|o[9],he=8191&fe,me=fe>>>13;i.negative=e.negative^t.negative,i.length=19;var be=(l+(n=Math.imul(p,z))|0)+((8191&(r=(r=Math.imul(p,H))+Math.imul(d,z)|0))<<13)|0;l=((s=Math.imul(d,H))+(r>>>13)|0)+(be>>>26)|0,be&=67108863,n=Math.imul(h,z),r=(r=Math.imul(h,H))+Math.imul(m,z)|0,s=Math.imul(m,H);var ve=(l+(n=n+Math.imul(p,W)|0)|0)+((8191&(r=(r=r+Math.imul(p,V)|0)+Math.imul(d,W)|0))<<13)|0;l=((s=s+Math.imul(d,V)|0)+(r>>>13)|0)+(ve>>>26)|0,ve&=67108863,n=Math.imul(v,z),r=(r=Math.imul(v,H))+Math.imul(g,z)|0,s=Math.imul(g,H),n=n+Math.imul(h,W)|0,r=(r=r+Math.imul(h,V)|0)+Math.imul(m,W)|0,s=s+Math.imul(m,V)|0;var ge=(l+(n=n+Math.imul(p,$)|0)|0)+((8191&(r=(r=r+Math.imul(p,G)|0)+Math.imul(d,$)|0))<<13)|0;l=((s=s+Math.imul(d,G)|0)+(r>>>13)|0)+(ge>>>26)|0,ge&=67108863,n=Math.imul(_,z),r=(r=Math.imul(_,H))+Math.imul(x,z)|0,s=Math.imul(x,H),n=n+Math.imul(v,W)|0,r=(r=r+Math.imul(v,V)|0)+Math.imul(g,W)|0,s=s+Math.imul(g,V)|0,n=n+Math.imul(h,$)|0,r=(r=r+Math.imul(h,G)|0)+Math.imul(m,$)|0,s=s+Math.imul(m,G)|0;var ye=(l+(n=n+Math.imul(p,Y)|0)|0)+((8191&(r=(r=r+Math.imul(p,Z)|0)+Math.imul(d,Y)|0))<<13)|0;l=((s=s+Math.imul(d,Z)|0)+(r>>>13)|0)+(ye>>>26)|0,ye&=67108863,n=Math.imul(k,z),r=(r=Math.imul(k,H))+Math.imul(E,z)|0,s=Math.imul(E,H),n=n+Math.imul(_,W)|0,r=(r=r+Math.imul(_,V)|0)+Math.imul(x,W)|0,s=s+Math.imul(x,V)|0,n=n+Math.imul(v,$)|0,r=(r=r+Math.imul(v,G)|0)+Math.imul(g,$)|0,s=s+Math.imul(g,G)|0,n=n+Math.imul(h,Y)|0,r=(r=r+Math.imul(h,Z)|0)+Math.imul(m,Y)|0,s=s+Math.imul(m,Z)|0;var _e=(l+(n=n+Math.imul(p,Q)|0)|0)+((8191&(r=(r=r+Math.imul(p,ee)|0)+Math.imul(d,Q)|0))<<13)|0;l=((s=s+Math.imul(d,ee)|0)+(r>>>13)|0)+(_e>>>26)|0,_e&=67108863,n=Math.imul(M,z),r=(r=Math.imul(M,H))+Math.imul(A,z)|0,s=Math.imul(A,H),n=n+Math.imul(k,W)|0,r=(r=r+Math.imul(k,V)|0)+Math.imul(E,W)|0,s=s+Math.imul(E,V)|0,n=n+Math.imul(_,$)|0,r=(r=r+Math.imul(_,G)|0)+Math.imul(x,$)|0,s=s+Math.imul(x,G)|0,n=n+Math.imul(v,Y)|0,r=(r=r+Math.imul(v,Z)|0)+Math.imul(g,Y)|0,s=s+Math.imul(g,Z)|0,n=n+Math.imul(h,Q)|0,r=(r=r+Math.imul(h,ee)|0)+Math.imul(m,Q)|0,s=s+Math.imul(m,ee)|0;var xe=(l+(n=n+Math.imul(p,ie)|0)|0)+((8191&(r=(r=r+Math.imul(p,ne)|0)+Math.imul(d,ie)|0))<<13)|0;l=((s=s+Math.imul(d,ne)|0)+(r>>>13)|0)+(xe>>>26)|0,xe&=67108863,n=Math.imul(I,z),r=(r=Math.imul(I,H))+Math.imul(T,z)|0,s=Math.imul(T,H),n=n+Math.imul(M,W)|0,r=(r=r+Math.imul(M,V)|0)+Math.imul(A,W)|0,s=s+Math.imul(A,V)|0,n=n+Math.imul(k,$)|0,r=(r=r+Math.imul(k,G)|0)+Math.imul(E,$)|0,s=s+Math.imul(E,G)|0,n=n+Math.imul(_,Y)|0,r=(r=r+Math.imul(_,Z)|0)+Math.imul(x,Y)|0,s=s+Math.imul(x,Z)|0,n=n+Math.imul(v,Q)|0,r=(r=r+Math.imul(v,ee)|0)+Math.imul(g,Q)|0,s=s+Math.imul(g,ee)|0,n=n+Math.imul(h,ie)|0,r=(r=r+Math.imul(h,ne)|0)+Math.imul(m,ie)|0,s=s+Math.imul(m,ne)|0;var we=(l+(n=n+Math.imul(p,se)|0)|0)+((8191&(r=(r=r+Math.imul(p,ae)|0)+Math.imul(d,se)|0))<<13)|0;l=((s=s+Math.imul(d,ae)|0)+(r>>>13)|0)+(we>>>26)|0,we&=67108863,n=Math.imul(B,z),r=(r=Math.imul(B,H))+Math.imul(R,z)|0,s=Math.imul(R,H),n=n+Math.imul(I,W)|0,r=(r=r+Math.imul(I,V)|0)+Math.imul(T,W)|0,s=s+Math.imul(T,V)|0,n=n+Math.imul(M,$)|0,r=(r=r+Math.imul(M,G)|0)+Math.imul(A,$)|0,s=s+Math.imul(A,G)|0,n=n+Math.imul(k,Y)|0,r=(r=r+Math.imul(k,Z)|0)+Math.imul(E,Y)|0,s=s+Math.imul(E,Z)|0,n=n+Math.imul(_,Q)|0,r=(r=r+Math.imul(_,ee)|0)+Math.imul(x,Q)|0,s=s+Math.imul(x,ee)|0,n=n+Math.imul(v,ie)|0,r=(r=r+Math.imul(v,ne)|0)+Math.imul(g,ie)|0,s=s+Math.imul(g,ne)|0,n=n+Math.imul(h,se)|0,r=(r=r+Math.imul(h,ae)|0)+Math.imul(m,se)|0,s=s+Math.imul(m,ae)|0;var ke=(l+(n=n+Math.imul(p,ce)|0)|0)+((8191&(r=(r=r+Math.imul(p,le)|0)+Math.imul(d,ce)|0))<<13)|0;l=((s=s+Math.imul(d,le)|0)+(r>>>13)|0)+(ke>>>26)|0,ke&=67108863,n=Math.imul(O,z),r=(r=Math.imul(O,H))+Math.imul(P,z)|0,s=Math.imul(P,H),n=n+Math.imul(B,W)|0,r=(r=r+Math.imul(B,V)|0)+Math.imul(R,W)|0,s=s+Math.imul(R,V)|0,n=n+Math.imul(I,$)|0,r=(r=r+Math.imul(I,G)|0)+Math.imul(T,$)|0,s=s+Math.imul(T,G)|0,n=n+Math.imul(M,Y)|0,r=(r=r+Math.imul(M,Z)|0)+Math.imul(A,Y)|0,s=s+Math.imul(A,Z)|0,n=n+Math.imul(k,Q)|0,r=(r=r+Math.imul(k,ee)|0)+Math.imul(E,Q)|0,s=s+Math.imul(E,ee)|0,n=n+Math.imul(_,ie)|0,r=(r=r+Math.imul(_,ne)|0)+Math.imul(x,ie)|0,s=s+Math.imul(x,ne)|0,n=n+Math.imul(v,se)|0,r=(r=r+Math.imul(v,ae)|0)+Math.imul(g,se)|0,s=s+Math.imul(g,ae)|0,n=n+Math.imul(h,ce)|0,r=(r=r+Math.imul(h,le)|0)+Math.imul(m,ce)|0,s=s+Math.imul(m,le)|0;var Ee=(l+(n=n+Math.imul(p,pe)|0)|0)+((8191&(r=(r=r+Math.imul(p,de)|0)+Math.imul(d,pe)|0))<<13)|0;l=((s=s+Math.imul(d,de)|0)+(r>>>13)|0)+(Ee>>>26)|0,Ee&=67108863,n=Math.imul(q,z),r=(r=Math.imul(q,H))+Math.imul(N,z)|0,s=Math.imul(N,H),n=n+Math.imul(O,W)|0,r=(r=r+Math.imul(O,V)|0)+Math.imul(P,W)|0,s=s+Math.imul(P,V)|0,n=n+Math.imul(B,$)|0,r=(r=r+Math.imul(B,G)|0)+Math.imul(R,$)|0,s=s+Math.imul(R,G)|0,n=n+Math.imul(I,Y)|0,r=(r=r+Math.imul(I,Z)|0)+Math.imul(T,Y)|0,s=s+Math.imul(T,Z)|0,n=n+Math.imul(M,Q)|0,r=(r=r+Math.imul(M,ee)|0)+Math.imul(A,Q)|0,s=s+Math.imul(A,ee)|0,n=n+Math.imul(k,ie)|0,r=(r=r+Math.imul(k,ne)|0)+Math.imul(E,ie)|0,s=s+Math.imul(E,ne)|0,n=n+Math.imul(_,se)|0,r=(r=r+Math.imul(_,ae)|0)+Math.imul(x,se)|0,s=s+Math.imul(x,ae)|0,n=n+Math.imul(v,ce)|0,r=(r=r+Math.imul(v,le)|0)+Math.imul(g,ce)|0,s=s+Math.imul(g,le)|0,n=n+Math.imul(h,pe)|0,r=(r=r+Math.imul(h,de)|0)+Math.imul(m,pe)|0,s=s+Math.imul(m,de)|0;var Se=(l+(n=n+Math.imul(p,he)|0)|0)+((8191&(r=(r=r+Math.imul(p,me)|0)+Math.imul(d,he)|0))<<13)|0;l=((s=s+Math.imul(d,me)|0)+(r>>>13)|0)+(Se>>>26)|0,Se&=67108863,n=Math.imul(q,W),r=(r=Math.imul(q,V))+Math.imul(N,W)|0,s=Math.imul(N,V),n=n+Math.imul(O,$)|0,r=(r=r+Math.imul(O,G)|0)+Math.imul(P,$)|0,s=s+Math.imul(P,G)|0,n=n+Math.imul(B,Y)|0,r=(r=r+Math.imul(B,Z)|0)+Math.imul(R,Y)|0,s=s+Math.imul(R,Z)|0,n=n+Math.imul(I,Q)|0,r=(r=r+Math.imul(I,ee)|0)+Math.imul(T,Q)|0,s=s+Math.imul(T,ee)|0,n=n+Math.imul(M,ie)|0,r=(r=r+Math.imul(M,ne)|0)+Math.imul(A,ie)|0,s=s+Math.imul(A,ne)|0,n=n+Math.imul(k,se)|0,r=(r=r+Math.imul(k,ae)|0)+Math.imul(E,se)|0,s=s+Math.imul(E,ae)|0,n=n+Math.imul(_,ce)|0,r=(r=r+Math.imul(_,le)|0)+Math.imul(x,ce)|0,s=s+Math.imul(x,le)|0,n=n+Math.imul(v,pe)|0,r=(r=r+Math.imul(v,de)|0)+Math.imul(g,pe)|0,s=s+Math.imul(g,de)|0;var Me=(l+(n=n+Math.imul(h,he)|0)|0)+((8191&(r=(r=r+Math.imul(h,me)|0)+Math.imul(m,he)|0))<<13)|0;l=((s=s+Math.imul(m,me)|0)+(r>>>13)|0)+(Me>>>26)|0,Me&=67108863,n=Math.imul(q,$),r=(r=Math.imul(q,G))+Math.imul(N,$)|0,s=Math.imul(N,G),n=n+Math.imul(O,Y)|0,r=(r=r+Math.imul(O,Z)|0)+Math.imul(P,Y)|0,s=s+Math.imul(P,Z)|0,n=n+Math.imul(B,Q)|0,r=(r=r+Math.imul(B,ee)|0)+Math.imul(R,Q)|0,s=s+Math.imul(R,ee)|0,n=n+Math.imul(I,ie)|0,r=(r=r+Math.imul(I,ne)|0)+Math.imul(T,ie)|0,s=s+Math.imul(T,ne)|0,n=n+Math.imul(M,se)|0,r=(r=r+Math.imul(M,ae)|0)+Math.imul(A,se)|0,s=s+Math.imul(A,ae)|0,n=n+Math.imul(k,ce)|0,r=(r=r+Math.imul(k,le)|0)+Math.imul(E,ce)|0,s=s+Math.imul(E,le)|0,n=n+Math.imul(_,pe)|0,r=(r=r+Math.imul(_,de)|0)+Math.imul(x,pe)|0,s=s+Math.imul(x,de)|0;var Ae=(l+(n=n+Math.imul(v,he)|0)|0)+((8191&(r=(r=r+Math.imul(v,me)|0)+Math.imul(g,he)|0))<<13)|0;l=((s=s+Math.imul(g,me)|0)+(r>>>13)|0)+(Ae>>>26)|0,Ae&=67108863,n=Math.imul(q,Y),r=(r=Math.imul(q,Z))+Math.imul(N,Y)|0,s=Math.imul(N,Z),n=n+Math.imul(O,Q)|0,r=(r=r+Math.imul(O,ee)|0)+Math.imul(P,Q)|0,s=s+Math.imul(P,ee)|0,n=n+Math.imul(B,ie)|0,r=(r=r+Math.imul(B,ne)|0)+Math.imul(R,ie)|0,s=s+Math.imul(R,ne)|0,n=n+Math.imul(I,se)|0,r=(r=r+Math.imul(I,ae)|0)+Math.imul(T,se)|0,s=s+Math.imul(T,ae)|0,n=n+Math.imul(M,ce)|0,r=(r=r+Math.imul(M,le)|0)+Math.imul(A,ce)|0,s=s+Math.imul(A,le)|0,n=n+Math.imul(k,pe)|0,r=(r=r+Math.imul(k,de)|0)+Math.imul(E,pe)|0,s=s+Math.imul(E,de)|0;var je=(l+(n=n+Math.imul(_,he)|0)|0)+((8191&(r=(r=r+Math.imul(_,me)|0)+Math.imul(x,he)|0))<<13)|0;l=((s=s+Math.imul(x,me)|0)+(r>>>13)|0)+(je>>>26)|0,je&=67108863,n=Math.imul(q,Q),r=(r=Math.imul(q,ee))+Math.imul(N,Q)|0,s=Math.imul(N,ee),n=n+Math.imul(O,ie)|0,r=(r=r+Math.imul(O,ne)|0)+Math.imul(P,ie)|0,s=s+Math.imul(P,ne)|0,n=n+Math.imul(B,se)|0,r=(r=r+Math.imul(B,ae)|0)+Math.imul(R,se)|0,s=s+Math.imul(R,ae)|0,n=n+Math.imul(I,ce)|0,r=(r=r+Math.imul(I,le)|0)+Math.imul(T,ce)|0,s=s+Math.imul(T,le)|0,n=n+Math.imul(M,pe)|0,r=(r=r+Math.imul(M,de)|0)+Math.imul(A,pe)|0,s=s+Math.imul(A,de)|0;var Ie=(l+(n=n+Math.imul(k,he)|0)|0)+((8191&(r=(r=r+Math.imul(k,me)|0)+Math.imul(E,he)|0))<<13)|0;l=((s=s+Math.imul(E,me)|0)+(r>>>13)|0)+(Ie>>>26)|0,Ie&=67108863,n=Math.imul(q,ie),r=(r=Math.imul(q,ne))+Math.imul(N,ie)|0,s=Math.imul(N,ne),n=n+Math.imul(O,se)|0,r=(r=r+Math.imul(O,ae)|0)+Math.imul(P,se)|0,s=s+Math.imul(P,ae)|0,n=n+Math.imul(B,ce)|0,r=(r=r+Math.imul(B,le)|0)+Math.imul(R,ce)|0,s=s+Math.imul(R,le)|0,n=n+Math.imul(I,pe)|0,r=(r=r+Math.imul(I,de)|0)+Math.imul(T,pe)|0,s=s+Math.imul(T,de)|0;var Te=(l+(n=n+Math.imul(M,he)|0)|0)+((8191&(r=(r=r+Math.imul(M,me)|0)+Math.imul(A,he)|0))<<13)|0;l=((s=s+Math.imul(A,me)|0)+(r>>>13)|0)+(Te>>>26)|0,Te&=67108863,n=Math.imul(q,se),r=(r=Math.imul(q,ae))+Math.imul(N,se)|0,s=Math.imul(N,ae),n=n+Math.imul(O,ce)|0,r=(r=r+Math.imul(O,le)|0)+Math.imul(P,ce)|0,s=s+Math.imul(P,le)|0,n=n+Math.imul(B,pe)|0,r=(r=r+Math.imul(B,de)|0)+Math.imul(R,pe)|0,s=s+Math.imul(R,de)|0;var Ce=(l+(n=n+Math.imul(I,he)|0)|0)+((8191&(r=(r=r+Math.imul(I,me)|0)+Math.imul(T,he)|0))<<13)|0;l=((s=s+Math.imul(T,me)|0)+(r>>>13)|0)+(Ce>>>26)|0,Ce&=67108863,n=Math.imul(q,ce),r=(r=Math.imul(q,le))+Math.imul(N,ce)|0,s=Math.imul(N,le),n=n+Math.imul(O,pe)|0,r=(r=r+Math.imul(O,de)|0)+Math.imul(P,pe)|0,s=s+Math.imul(P,de)|0;var Be=(l+(n=n+Math.imul(B,he)|0)|0)+((8191&(r=(r=r+Math.imul(B,me)|0)+Math.imul(R,he)|0))<<13)|0;l=((s=s+Math.imul(R,me)|0)+(r>>>13)|0)+(Be>>>26)|0,Be&=67108863,n=Math.imul(q,pe),r=(r=Math.imul(q,de))+Math.imul(N,pe)|0,s=Math.imul(N,de);var Re=(l+(n=n+Math.imul(O,he)|0)|0)+((8191&(r=(r=r+Math.imul(O,me)|0)+Math.imul(P,he)|0))<<13)|0;l=((s=s+Math.imul(P,me)|0)+(r>>>13)|0)+(Re>>>26)|0,Re&=67108863;var Le=(l+(n=Math.imul(q,he))|0)+((8191&(r=(r=Math.imul(q,me))+Math.imul(N,he)|0))<<13)|0;return l=((s=Math.imul(N,me))+(r>>>13)|0)+(Le>>>26)|0,Le&=67108863,c[0]=be,c[1]=ve,c[2]=ge,c[3]=ye,c[4]=_e,c[5]=xe,c[6]=we,c[7]=ke,c[8]=Ee,c[9]=Se,c[10]=Me,c[11]=Ae,c[12]=je,c[13]=Ie,c[14]=Te,c[15]=Ce,c[16]=Be,c[17]=Re,c[18]=Le,0!==l&&(c[19]=l,i.length++),i};function v(e,t,i){i.negative=t.negative^e.negative,i.length=e.length+t.length;for(var n=0,r=0,s=0;s>>26)|0)>>>26,a&=67108863}i.words[s]=o,n=a,a=r}return 0!==n?i.words[s]=n:i.length--,i._strip()}function g(e,t,i){return v(e,t,i)}function y(e,t){this.x=e,this.y=t}Math.imul||(b=m),s.prototype.mulTo=function(e,t){var i=this.length+e.length;return 10===this.length&&10===e.length?b(this,e,t):i<63?m(this,e,t):i<1024?v(this,e,t):g(this,e,t)},y.prototype.makeRBT=function(e){for(var t=new Array(e),i=s.prototype._countBits(e)-1,n=0;n>=1;return n},y.prototype.permute=function(e,t,i,n,r,s){for(var a=0;a>>=1)r++;return 1<>>=13,i[2*a+1]=8191&s,s>>>=13;for(a=2*t;a>=26,i+=s/67108864|0,i+=a>>>26,this.words[r]=67108863&a}return 0!==i&&(this.words[r]=i,this.length++),t?this.ineg():this},s.prototype.muln=function(e){return this.clone().imuln(e)},s.prototype.sqr=function(){return this.mul(this)},s.prototype.isqr=function(){return this.imul(this.clone())},s.prototype.pow=function(e){var t=function(e){for(var t=new Array(e.bitLength()),i=0;i>>r&1}return t}(e);if(0===t.length)return new s(1);for(var i=this,n=0;n=0);var t,i=e%26,r=(e-i)/26,s=67108863>>>26-i<<26-i;if(0!==i){var a=0;for(t=0;t>>26-i}a&&(this.words[t]=a,this.length++)}if(0!==r){for(t=this.length-1;t>=0;t--)this.words[t+r]=this.words[t];for(t=0;t=0),r=t?(t-t%26)/26:0;var s=e%26,a=Math.min((e-s)/26,this.length),o=67108863^67108863>>>s<a)for(this.length-=a,l=0;l=0&&(0!==u||l>=r);l--){var p=0|this.words[l];this.words[l]=u<<26-s|p>>>s,u=p&o}return c&&0!==u&&(c.words[c.length++]=u),0===this.length&&(this.words[0]=0,this.length=1),this._strip()},s.prototype.ishrn=function(e,t,i){return n(0===this.negative),this.iushrn(e,t,i)},s.prototype.shln=function(e){return this.clone().ishln(e)},s.prototype.ushln=function(e){return this.clone().iushln(e)},s.prototype.shrn=function(e){return this.clone().ishrn(e)},s.prototype.ushrn=function(e){return this.clone().iushrn(e)},s.prototype.testn=function(e){n("number"==typeof e&&e>=0);var t=e%26,i=(e-t)/26,r=1<=0);var t=e%26,i=(e-t)/26;if(n(0===this.negative,"imaskn works only with positive numbers"),this.length<=i)return this;if(0!==t&&i++,this.length=Math.min(i,this.length),0!==t){var r=67108863^67108863>>>t<=67108864;t++)this.words[t]-=67108864,t===this.length-1?this.words[t+1]=1:this.words[t+1]++;return this.length=Math.max(this.length,t+1),this},s.prototype.isubn=function(e){if(n("number"==typeof e),n(e<67108864),e<0)return this.iaddn(-e);if(0!==this.negative)return this.negative=0,this.iaddn(e),this.negative=1,this;if(this.words[0]-=e,1===this.length&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var t=0;t>26)-(c/67108864|0),this.words[r+i]=67108863&s}for(;r>26,this.words[r+i]=67108863&s;if(0===o)return this._strip();for(n(-1===o),o=0,r=0;r>26,this.words[r]=67108863&s;return this.negative=1,this._strip()},s.prototype._wordDiv=function(e,t){var i=(this.length,e.length),n=this.clone(),r=e,a=0|r.words[r.length-1];0!==(i=26-this._countBits(a))&&(r=r.ushln(i),n.iushln(i),a=0|r.words[r.length-1]);var o,c=n.length-r.length;if("mod"!==t){(o=new s(null)).length=c+1,o.words=new Array(o.length);for(var l=0;l=0;p--){var d=67108864*(0|n.words[r.length+p])+(0|n.words[r.length+p-1]);for(d=Math.min(d/a|0,67108863),n._ishlnsubmul(r,d,p);0!==n.negative;)d--,n.negative=0,n._ishlnsubmul(r,1,p),n.isZero()||(n.negative^=1);o&&(o.words[p]=d)}return o&&o._strip(),n._strip(),"div"!==t&&0!==i&&n.iushrn(i),{div:o||null,mod:n}},s.prototype.divmod=function(e,t,i){return n(!e.isZero()),this.isZero()?{div:new s(0),mod:new s(0)}:0!==this.negative&&0===e.negative?(o=this.neg().divmod(e,t),"mod"!==t&&(r=o.div.neg()),"div"!==t&&(a=o.mod.neg(),i&&0!==a.negative&&a.iadd(e)),{div:r,mod:a}):0===this.negative&&0!==e.negative?(o=this.divmod(e.neg(),t),"mod"!==t&&(r=o.div.neg()),{div:r,mod:o.mod}):0!=(this.negative&e.negative)?(o=this.neg().divmod(e.neg(),t),"div"!==t&&(a=o.mod.neg(),i&&0!==a.negative&&a.isub(e)),{div:o.div,mod:a}):e.length>this.length||this.cmp(e)<0?{div:new s(0),mod:this}:1===e.length?"div"===t?{div:this.divn(e.words[0]),mod:null}:"mod"===t?{div:null,mod:new s(this.modrn(e.words[0]))}:{div:this.divn(e.words[0]),mod:new s(this.modrn(e.words[0]))}:this._wordDiv(e,t);var r,a,o},s.prototype.div=function(e){return this.divmod(e,"div",!1).div},s.prototype.mod=function(e){return this.divmod(e,"mod",!1).mod},s.prototype.umod=function(e){return this.divmod(e,"mod",!0).mod},s.prototype.divRound=function(e){var t=this.divmod(e);if(t.mod.isZero())return t.div;var i=0!==t.div.negative?t.mod.isub(e):t.mod,n=e.ushrn(1),r=e.andln(1),s=i.cmp(n);return s<0||1===r&&0===s?t.div:0!==t.div.negative?t.div.isubn(1):t.div.iaddn(1)},s.prototype.modrn=function(e){var t=e<0;t&&(e=-e),n(e<=67108863);for(var i=(1<<26)%e,r=0,s=this.length-1;s>=0;s--)r=(i*r+(0|this.words[s]))%e;return t?-r:r},s.prototype.modn=function(e){return this.modrn(e)},s.prototype.idivn=function(e){var t=e<0;t&&(e=-e),n(e<=67108863);for(var i=0,r=this.length-1;r>=0;r--){var s=(0|this.words[r])+67108864*i;this.words[r]=s/e|0,i=s%e}return this._strip(),t?this.ineg():this},s.prototype.divn=function(e){return this.clone().idivn(e)},s.prototype.egcd=function(e){n(0===e.negative),n(!e.isZero());var t=this,i=e.clone();t=0!==t.negative?t.umod(e):t.clone();for(var r=new s(1),a=new s(0),o=new s(0),c=new s(1),l=0;t.isEven()&&i.isEven();)t.iushrn(1),i.iushrn(1),++l;for(var u=i.clone(),p=t.clone();!t.isZero();){for(var d=0,f=1;0==(t.words[0]&f)&&d<26;++d,f<<=1);if(d>0)for(t.iushrn(d);d-- >0;)(r.isOdd()||a.isOdd())&&(r.iadd(u),a.isub(p)),r.iushrn(1),a.iushrn(1);for(var h=0,m=1;0==(i.words[0]&m)&&h<26;++h,m<<=1);if(h>0)for(i.iushrn(h);h-- >0;)(o.isOdd()||c.isOdd())&&(o.iadd(u),c.isub(p)),o.iushrn(1),c.iushrn(1);t.cmp(i)>=0?(t.isub(i),r.isub(o),a.isub(c)):(i.isub(t),o.isub(r),c.isub(a))}return{a:o,b:c,gcd:i.iushln(l)}},s.prototype._invmp=function(e){n(0===e.negative),n(!e.isZero());var t=this,i=e.clone();t=0!==t.negative?t.umod(e):t.clone();for(var r,a=new s(1),o=new s(0),c=i.clone();t.cmpn(1)>0&&i.cmpn(1)>0;){for(var l=0,u=1;0==(t.words[0]&u)&&l<26;++l,u<<=1);if(l>0)for(t.iushrn(l);l-- >0;)a.isOdd()&&a.iadd(c),a.iushrn(1);for(var p=0,d=1;0==(i.words[0]&d)&&p<26;++p,d<<=1);if(p>0)for(i.iushrn(p);p-- >0;)o.isOdd()&&o.iadd(c),o.iushrn(1);t.cmp(i)>=0?(t.isub(i),a.isub(o)):(i.isub(t),o.isub(a))}return(r=0===t.cmpn(1)?a:o).cmpn(0)<0&&r.iadd(e),r},s.prototype.gcd=function(e){if(this.isZero())return e.abs();if(e.isZero())return this.abs();var t=this.clone(),i=e.clone();t.negative=0,i.negative=0;for(var n=0;t.isEven()&&i.isEven();n++)t.iushrn(1),i.iushrn(1);for(;;){for(;t.isEven();)t.iushrn(1);for(;i.isEven();)i.iushrn(1);var r=t.cmp(i);if(r<0){var s=t;t=i,i=s}else if(0===r||0===i.cmpn(1))break;t.isub(i)}return i.iushln(n)},s.prototype.invm=function(e){return this.egcd(e).a.umod(e)},s.prototype.isEven=function(){return 0==(1&this.words[0])},s.prototype.isOdd=function(){return 1==(1&this.words[0])},s.prototype.andln=function(e){return this.words[0]&e},s.prototype.bincn=function(e){n("number"==typeof e);var t=e%26,i=(e-t)/26,r=1<>>26,o&=67108863,this.words[a]=o}return 0!==s&&(this.words[a]=s,this.length++),this},s.prototype.isZero=function(){return 1===this.length&&0===this.words[0]},s.prototype.cmpn=function(e){var t,i=e<0;if(0!==this.negative&&!i)return-1;if(0===this.negative&&i)return 1;if(this._strip(),this.length>1)t=1;else{i&&(e=-e),n(e<=67108863,"Number is too big");var r=0|this.words[0];t=r===e?0:re.length)return 1;if(this.length=0;i--){var n=0|this.words[i],r=0|e.words[i];if(n!==r){nr&&(t=1);break}}return t},s.prototype.gtn=function(e){return 1===this.cmpn(e)},s.prototype.gt=function(e){return 1===this.cmp(e)},s.prototype.gten=function(e){return this.cmpn(e)>=0},s.prototype.gte=function(e){return this.cmp(e)>=0},s.prototype.ltn=function(e){return-1===this.cmpn(e)},s.prototype.lt=function(e){return-1===this.cmp(e)},s.prototype.lten=function(e){return this.cmpn(e)<=0},s.prototype.lte=function(e){return this.cmp(e)<=0},s.prototype.eqn=function(e){return 0===this.cmpn(e)},s.prototype.eq=function(e){return 0===this.cmp(e)},s.red=function(e){return new M(e)},s.prototype.toRed=function(e){return n(!this.red,"Already a number in reduction context"),n(0===this.negative,"red works only with positives"),e.convertTo(this)._forceRed(e)},s.prototype.fromRed=function(){return n(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},s.prototype._forceRed=function(e){return this.red=e,this},s.prototype.forceRed=function(e){return n(!this.red,"Already a number in reduction context"),this._forceRed(e)},s.prototype.redAdd=function(e){return n(this.red,"redAdd works only with red numbers"),this.red.add(this,e)},s.prototype.redIAdd=function(e){return n(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,e)},s.prototype.redSub=function(e){return n(this.red,"redSub works only with red numbers"),this.red.sub(this,e)},s.prototype.redISub=function(e){return n(this.red,"redISub works only with red numbers"),this.red.isub(this,e)},s.prototype.redShl=function(e){return n(this.red,"redShl works only with red numbers"),this.red.shl(this,e)},s.prototype.redMul=function(e){return n(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.mul(this,e)},s.prototype.redIMul=function(e){return n(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.imul(this,e)},s.prototype.redSqr=function(){return n(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},s.prototype.redISqr=function(){return n(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},s.prototype.redSqrt=function(){return n(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},s.prototype.redInvm=function(){return n(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},s.prototype.redNeg=function(){return n(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},s.prototype.redPow=function(e){return n(this.red&&!e.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,e)};var _={k256:null,p224:null,p192:null,p25519:null};function x(e,t){this.name=e,this.p=new s(t,16),this.n=this.p.bitLength(),this.k=new s(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}function w(){x.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function k(){x.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function E(){x.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function S(){x.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function M(e){if("string"==typeof e){var t=s._prime(e);this.m=t.p,this.prime=t}else n(e.gtn(1),"modulus must be greater than 1"),this.m=e,this.prime=null}function A(e){M.call(this,e),this.shift=this.m.bitLength(),this.shift%26!=0&&(this.shift+=26-this.shift%26),this.r=new s(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}x.prototype._tmp=function(){var e=new s(null);return e.words=new Array(Math.ceil(this.n/13)),e},x.prototype.ireduce=function(e){var t,i=e;do{this.split(i,this.tmp),t=(i=(i=this.imulK(i)).iadd(this.tmp)).bitLength()}while(t>this.n);var n=t0?i.isub(this.p):void 0!==i.strip?i.strip():i._strip(),i},x.prototype.split=function(e,t){e.iushrn(this.n,0,t)},x.prototype.imulK=function(e){return e.imul(this.k)},r(w,x),w.prototype.split=function(e,t){for(var i=4194303,n=Math.min(e.length,9),r=0;r>>22,s=a}s>>>=22,e.words[r-10]=s,0===s&&e.length>10?e.length-=10:e.length-=9},w.prototype.imulK=function(e){e.words[e.length]=0,e.words[e.length+1]=0,e.length+=2;for(var t=0,i=0;i>>=26,e.words[i]=r,t=n}return 0!==t&&(e.words[e.length++]=t),e},s._prime=function(e){if(_[e])return _[e];var t;if("k256"===e)t=new w;else if("p224"===e)t=new k;else if("p192"===e)t=new E;else{if("p25519"!==e)throw new Error("Unknown prime "+e);t=new S}return _[e]=t,t},M.prototype._verify1=function(e){n(0===e.negative,"red works only with positives"),n(e.red,"red works only with red numbers")},M.prototype._verify2=function(e,t){n(0==(e.negative|t.negative),"red works only with positives"),n(e.red&&e.red===t.red,"red works only with red numbers")},M.prototype.imod=function(e){return this.prime?this.prime.ireduce(e)._forceRed(this):(u(e,e.umod(this.m)._forceRed(this)),e)},M.prototype.neg=function(e){return e.isZero()?e.clone():this.m.sub(e)._forceRed(this)},M.prototype.add=function(e,t){this._verify2(e,t);var i=e.add(t);return i.cmp(this.m)>=0&&i.isub(this.m),i._forceRed(this)},M.prototype.iadd=function(e,t){this._verify2(e,t);var i=e.iadd(t);return i.cmp(this.m)>=0&&i.isub(this.m),i},M.prototype.sub=function(e,t){this._verify2(e,t);var i=e.sub(t);return i.cmpn(0)<0&&i.iadd(this.m),i._forceRed(this)},M.prototype.isub=function(e,t){this._verify2(e,t);var i=e.isub(t);return i.cmpn(0)<0&&i.iadd(this.m),i},M.prototype.shl=function(e,t){return this._verify1(e),this.imod(e.ushln(t))},M.prototype.imul=function(e,t){return this._verify2(e,t),this.imod(e.imul(t))},M.prototype.mul=function(e,t){return this._verify2(e,t),this.imod(e.mul(t))},M.prototype.isqr=function(e){return this.imul(e,e.clone())},M.prototype.sqr=function(e){return this.mul(e,e)},M.prototype.sqrt=function(e){if(e.isZero())return e.clone();var t=this.m.andln(3);if(n(t%2==1),3===t){var i=this.m.add(new s(1)).iushrn(2);return this.pow(e,i)}for(var r=this.m.subn(1),a=0;!r.isZero()&&0===r.andln(1);)a++,r.iushrn(1);n(!r.isZero());var o=new s(1).toRed(this),c=o.redNeg(),l=this.m.subn(1).iushrn(1),u=this.m.bitLength();for(u=new s(2*u*u).toRed(this);0!==this.pow(u,l).cmp(c);)u.redIAdd(c);for(var p=this.pow(u,r),d=this.pow(e,r.addn(1).iushrn(1)),f=this.pow(e,r),h=a;0!==f.cmp(o);){for(var m=f,b=0;0!==m.cmp(o);b++)m=m.redSqr();n(b=0;n--){for(var l=t.words[n],u=c-1;u>=0;u--){var p=l>>u&1;r!==i[0]&&(r=this.sqr(r)),0!==p||0!==a?(a<<=1,a|=p,(4===++o||0===n&&0===u)&&(r=this.mul(r,i[a]),o=0,a=0)):o=0}c=26}return r},M.prototype.convertTo=function(e){var t=e.umod(this.m);return t===e?t.clone():t},M.prototype.convertFrom=function(e){var t=e.clone();return t.red=null,t},s.mont=function(e){return new A(e)},r(A,M),A.prototype.convertTo=function(e){return this.imod(e.ushln(this.shift))},A.prototype.convertFrom=function(e){var t=this.imod(e.mul(this.rinv));return t.red=null,t},A.prototype.imul=function(e,t){if(e.isZero()||t.isZero())return e.words[0]=0,e.length=1,e;var i=e.imul(t),n=i.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),r=i.isub(n).iushrn(this.shift),s=r;return r.cmp(this.m)>=0?s=r.isub(this.m):r.cmpn(0)<0&&(s=r.iadd(this.m)),s._forceRed(this)},A.prototype.mul=function(e,t){if(e.isZero()||t.isZero())return new s(0)._forceRed(this);var i=e.mul(t),n=i.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),r=i.isub(n).iushrn(this.shift),a=r;return r.cmp(this.m)>=0?a=r.isub(this.m):r.cmpn(0)<0&&(a=r.iadd(this.m)),a._forceRed(this)},A.prototype.invm=function(e){return this.imod(e._invmp(this.m).mul(this.r2))._forceRed(this)}}(void 0===t||t,this)},{buffer:66}],65:[function(e,t,i){var n;function r(e){this.rand=e}if(t.exports=function(e){return n||(n=new r(null)),n.generate(e)},t.exports.Rand=r,r.prototype.generate=function(e){return this._rand(e)},r.prototype._rand=function(e){if(this.rand.getBytes)return this.rand.getBytes(e);for(var t=new Uint8Array(e),i=0;i>>24]^u[h>>>16&255]^p[m>>>8&255]^d[255&b]^t[v++],a=l[h>>>24]^u[m>>>16&255]^p[b>>>8&255]^d[255&f]^t[v++],o=l[m>>>24]^u[b>>>16&255]^p[f>>>8&255]^d[255&h]^t[v++],c=l[b>>>24]^u[f>>>16&255]^p[h>>>8&255]^d[255&m]^t[v++],f=s,h=a,m=o,b=c;return s=(n[f>>>24]<<24|n[h>>>16&255]<<16|n[m>>>8&255]<<8|n[255&b])^t[v++],a=(n[h>>>24]<<24|n[m>>>16&255]<<16|n[b>>>8&255]<<8|n[255&f])^t[v++],o=(n[m>>>24]<<24|n[b>>>16&255]<<16|n[f>>>8&255]<<8|n[255&h])^t[v++],c=(n[b>>>24]<<24|n[f>>>16&255]<<16|n[h>>>8&255]<<8|n[255&m])^t[v++],[s>>>=0,a>>>=0,o>>>=0,c>>>=0]}var o=[0,1,2,4,8,16,32,64,128,27,54],c=function(){for(var e=new Array(256),t=0;t<256;t++)e[t]=t<128?t<<1:t<<1^283;for(var i=[],n=[],r=[[],[],[],[]],s=[[],[],[],[]],a=0,o=0,c=0;c<256;++c){var l=o^o<<1^o<<2^o<<3^o<<4;l=l>>>8^255&l^99,i[a]=l,n[l]=a;var u=e[a],p=e[u],d=e[p],f=257*e[l]^16843008*l;r[0][a]=f<<24|f>>>8,r[1][a]=f<<16|f>>>16,r[2][a]=f<<8|f>>>24,r[3][a]=f,f=16843009*d^65537*p^257*u^16843008*a,s[0][l]=f<<24|f>>>8,s[1][l]=f<<16|f>>>16,s[2][l]=f<<8|f>>>24,s[3][l]=f,0===a?a=o=1:(a=u^e[e[e[d^u]]],o^=e[e[o]])}return{SBOX:i,INV_SBOX:n,SUB_MIX:r,INV_SUB_MIX:s}}();function l(e){this._key=r(e),this._reset()}l.blockSize=16,l.keySize=32,l.prototype.blockSize=l.blockSize,l.prototype.keySize=l.keySize,l.prototype._reset=function(){for(var e=this._key,t=e.length,i=t+6,n=4*(i+1),r=[],s=0;s>>24,a=c.SBOX[a>>>24]<<24|c.SBOX[a>>>16&255]<<16|c.SBOX[a>>>8&255]<<8|c.SBOX[255&a],a^=o[s/t|0]<<24):t>6&&s%t==4&&(a=c.SBOX[a>>>24]<<24|c.SBOX[a>>>16&255]<<16|c.SBOX[a>>>8&255]<<8|c.SBOX[255&a]),r[s]=r[s-t]^a}for(var l=[],u=0;u>>24]]^c.INV_SUB_MIX[1][c.SBOX[d>>>16&255]]^c.INV_SUB_MIX[2][c.SBOX[d>>>8&255]]^c.INV_SUB_MIX[3][c.SBOX[255&d]]}this._nRounds=i,this._keySchedule=r,this._invKeySchedule=l},l.prototype.encryptBlockRaw=function(e){return a(e=r(e),this._keySchedule,c.SUB_MIX,c.SBOX,this._nRounds)},l.prototype.encryptBlock=function(e){var t=this.encryptBlockRaw(e),i=n.allocUnsafe(16);return i.writeUInt32BE(t[0],0),i.writeUInt32BE(t[1],4),i.writeUInt32BE(t[2],8),i.writeUInt32BE(t[3],12),i},l.prototype.decryptBlock=function(e){var t=(e=r(e))[1];e[1]=e[3],e[3]=t;var i=a(e,this._invKeySchedule,c.INV_SUB_MIX,c.INV_SBOX,this._nRounds),s=n.allocUnsafe(16);return s.writeUInt32BE(i[0],0),s.writeUInt32BE(i[3],4),s.writeUInt32BE(i[2],8),s.writeUInt32BE(i[1],12),s},l.prototype.scrub=function(){s(this._keySchedule),s(this._invKeySchedule),s(this._key)},t.exports.AES=l},{"safe-buffer":382}],68:[function(e,t,i){var n=e("./aes"),r=e("safe-buffer").Buffer,s=e("cipher-base"),a=e("inherits"),o=e("./ghash"),c=e("buffer-xor"),l=e("./incr32");function u(e,t,i,a){s.call(this);var c=r.alloc(4,0);this._cipher=new n.AES(t);var u=this._cipher.encryptBlock(c);this._ghash=new o(u),i=function(e,t,i){if(12===t.length)return e._finID=r.concat([t,r.from([0,0,0,1])]),r.concat([t,r.from([0,0,0,2])]);var n=new o(i),s=t.length,a=s%16;n.update(t),a&&(a=16-a,n.update(r.alloc(a,0))),n.update(r.alloc(8,0));var c=8*s,u=r.alloc(8);u.writeUIntBE(c,0,8),n.update(u),e._finID=n.state;var p=r.from(e._finID);return l(p),p}(this,i,u),this._prev=r.from(i),this._cache=r.allocUnsafe(0),this._secCache=r.allocUnsafe(0),this._decrypt=a,this._alen=0,this._len=0,this._mode=e,this._authTag=null,this._called=!1}a(u,s),u.prototype._update=function(e){if(!this._called&&this._alen){var t=16-this._alen%16;t<16&&(t=r.alloc(t,0),this._ghash.update(t))}this._called=!0;var i=this._mode.encrypt(this,e);return this._decrypt?this._ghash.update(e):this._ghash.update(i),this._len+=e.length,i},u.prototype._final=function(){if(this._decrypt&&!this._authTag)throw new Error("Unsupported state or unable to authenticate data");var e=c(this._ghash.final(8*this._alen,8*this._len),this._cipher.encryptBlock(this._finID));if(this._decrypt&&function(e,t){var i=0;e.length!==t.length&&i++;for(var n=Math.min(e.length,t.length),r=0;r16)throw new Error("unable to decrypt data");var i=-1;for(;++i16)return t=this.cache.slice(0,16),this.cache=this.cache.slice(16),t}else if(this.cache.length>=16)return t=this.cache.slice(0,16),this.cache=this.cache.slice(16),t;return null},p.prototype.flush=function(){if(this.cache.length)return this.cache},i.createDecipher=function(e,t){var i=s[e.toLowerCase()];if(!i)throw new TypeError("invalid suite type");var n=l(t,!1,i.key,i.iv);return d(e,n.key,n.iv)},i.createDecipheriv=d},{"./aes":67,"./authCipher":68,"./modes":80,"./streamCipher":83,"cipher-base":133,evp_bytestokey:193,inherits:245,"safe-buffer":382}],71:[function(e,t,i){var n=e("./modes"),r=e("./authCipher"),s=e("safe-buffer").Buffer,a=e("./streamCipher"),o=e("cipher-base"),c=e("./aes"),l=e("evp_bytestokey");function u(e,t,i){o.call(this),this._cache=new d,this._cipher=new c.AES(t),this._prev=s.from(i),this._mode=e,this._autopadding=!0}e("inherits")(u,o),u.prototype._update=function(e){var t,i;this._cache.add(e);for(var n=[];t=this._cache.get();)i=this._mode.encrypt(this,t),n.push(i);return s.concat(n)};var p=s.alloc(16,16);function d(){this.cache=s.allocUnsafe(0)}function f(e,t,i){var o=n[e.toLowerCase()];if(!o)throw new TypeError("invalid suite type");if("string"==typeof t&&(t=s.from(t)),t.length!==o.key/8)throw new TypeError("invalid key length "+t.length);if("string"==typeof i&&(i=s.from(i)),"GCM"!==o.mode&&i.length!==o.iv)throw new TypeError("invalid iv length "+i.length);return"stream"===o.type?new a(o.module,t,i):"auth"===o.type?new r(o.module,t,i):new u(o.module,t,i)}u.prototype._final=function(){var e=this._cache.flush();if(this._autopadding)return e=this._mode.encrypt(this,e),this._cipher.scrub(),e;if(!e.equals(p))throw this._cipher.scrub(),new Error("data not multiple of block length")},u.prototype.setAutoPadding=function(e){return this._autopadding=!!e,this},d.prototype.add=function(e){this.cache=s.concat([this.cache,e])},d.prototype.get=function(){if(this.cache.length>15){var e=this.cache.slice(0,16);return this.cache=this.cache.slice(16),e}return null},d.prototype.flush=function(){for(var e=16-this.cache.length,t=s.allocUnsafe(e),i=-1;++i>>0,0),t.writeUInt32BE(e[1]>>>0,4),t.writeUInt32BE(e[2]>>>0,8),t.writeUInt32BE(e[3]>>>0,12),t}function a(e){this.h=e,this.state=n.alloc(16,0),this.cache=n.allocUnsafe(0)}a.prototype.ghash=function(e){for(var t=-1;++t0;t--)n[t]=n[t]>>>1|(1&n[t-1])<<31;n[0]=n[0]>>>1,i&&(n[0]=n[0]^225<<24)}this.state=s(r)},a.prototype.update=function(e){var t;for(this.cache=n.concat([this.cache,e]);this.cache.length>=16;)t=this.cache.slice(0,16),this.cache=this.cache.slice(16),this.ghash(t)},a.prototype.final=function(e,t){return this.cache.length&&this.ghash(n.concat([this.cache,r],16)),this.ghash(s([0,e,0,t])),this.state},t.exports=a},{"safe-buffer":382}],73:[function(e,t,i){t.exports=function(e){for(var t,i=e.length;i--;){if(255!==(t=e.readUInt8(i))){t++,e.writeUInt8(t,i);break}e.writeUInt8(0,i)}}},{}],74:[function(e,t,i){var n=e("buffer-xor");i.encrypt=function(e,t){var i=n(t,e._prev);return e._prev=e._cipher.encryptBlock(i),e._prev},i.decrypt=function(e,t){var i=e._prev;e._prev=t;var r=e._cipher.decryptBlock(t);return n(r,i)}},{"buffer-xor":113}],75:[function(e,t,i){var n=e("safe-buffer").Buffer,r=e("buffer-xor");function s(e,t,i){var s=t.length,a=r(t,e._cache);return e._cache=e._cache.slice(s),e._prev=n.concat([e._prev,i?t:a]),a}i.encrypt=function(e,t,i){for(var r,a=n.allocUnsafe(0);t.length;){if(0===e._cache.length&&(e._cache=e._cipher.encryptBlock(e._prev),e._prev=n.allocUnsafe(0)),!(e._cache.length<=t.length)){a=n.concat([a,s(e,t,i)]);break}r=e._cache.length,a=n.concat([a,s(e,t.slice(0,r),i)]),t=t.slice(r)}return a}},{"buffer-xor":113,"safe-buffer":382}],76:[function(e,t,i){var n=e("safe-buffer").Buffer;function r(e,t,i){for(var n,r,a=-1,o=0;++a<8;)n=t&1<<7-a?128:0,o+=(128&(r=e._cipher.encryptBlock(e._prev)[0]^n))>>a%8,e._prev=s(e._prev,i?n:r);return o}function s(e,t){var i=e.length,r=-1,s=n.allocUnsafe(e.length);for(e=n.concat([e,n.from([t])]);++r>7;return s}i.encrypt=function(e,t,i){for(var s=t.length,a=n.allocUnsafe(s),o=-1;++o=0||!t.umod(e.prime1)||!t.umod(e.prime2));return t}function a(e,t){var r=function(e){var t=s(e);return{blinder:t.toRed(n.mont(e.modulus)).redPow(new n(e.publicExponent)).fromRed(),unblinder:t.invm(e.modulus)}}(t),a=t.modulus.byteLength(),o=new n(e).mul(r.blinder).umod(t.modulus),c=o.toRed(n.mont(t.prime1)),l=o.toRed(n.mont(t.prime2)),u=t.coefficient,p=t.prime1,d=t.prime2,f=c.redPow(t.exponent1).fromRed(),h=l.redPow(t.exponent2).fromRed(),m=f.isub(h).imul(u).umod(p).imul(d);return h.iadd(m).imul(r.unblinder).umod(t.modulus).toArrayLike(i,"be",a)}a.getr=s,t.exports=a}).call(this)}).call(this,e("buffer").Buffer)},{"bn.js":64,buffer:109,randombytes:356}],88:[function(e,t,i){t.exports=e("./browser/algorithms.json")},{"./browser/algorithms.json":89}],89:[function(e,t,i){t.exports={sha224WithRSAEncryption:{sign:"rsa",hash:"sha224",id:"302d300d06096086480165030402040500041c"},"RSA-SHA224":{sign:"ecdsa/rsa",hash:"sha224",id:"302d300d06096086480165030402040500041c"},sha256WithRSAEncryption:{sign:"rsa",hash:"sha256",id:"3031300d060960864801650304020105000420"},"RSA-SHA256":{sign:"ecdsa/rsa",hash:"sha256",id:"3031300d060960864801650304020105000420"},sha384WithRSAEncryption:{sign:"rsa",hash:"sha384",id:"3041300d060960864801650304020205000430"},"RSA-SHA384":{sign:"ecdsa/rsa",hash:"sha384",id:"3041300d060960864801650304020205000430"},sha512WithRSAEncryption:{sign:"rsa",hash:"sha512",id:"3051300d060960864801650304020305000440"},"RSA-SHA512":{sign:"ecdsa/rsa",hash:"sha512",id:"3051300d060960864801650304020305000440"},"RSA-SHA1":{sign:"rsa",hash:"sha1",id:"3021300906052b0e03021a05000414"},"ecdsa-with-SHA1":{sign:"ecdsa",hash:"sha1",id:""},sha256:{sign:"ecdsa",hash:"sha256",id:""},sha224:{sign:"ecdsa",hash:"sha224",id:""},sha384:{sign:"ecdsa",hash:"sha384",id:""},sha512:{sign:"ecdsa",hash:"sha512",id:""},"DSA-SHA":{sign:"dsa",hash:"sha1",id:""},"DSA-SHA1":{sign:"dsa",hash:"sha1",id:""},DSA:{sign:"dsa",hash:"sha1",id:""},"DSA-WITH-SHA224":{sign:"dsa",hash:"sha224",id:""},"DSA-SHA224":{sign:"dsa",hash:"sha224",id:""},"DSA-WITH-SHA256":{sign:"dsa",hash:"sha256",id:""},"DSA-SHA256":{sign:"dsa",hash:"sha256",id:""},"DSA-WITH-SHA384":{sign:"dsa",hash:"sha384",id:""},"DSA-SHA384":{sign:"dsa",hash:"sha384",id:""},"DSA-WITH-SHA512":{sign:"dsa",hash:"sha512",id:""},"DSA-SHA512":{sign:"dsa",hash:"sha512",id:""},"DSA-RIPEMD160":{sign:"dsa",hash:"rmd160",id:""},ripemd160WithRSA:{sign:"rsa",hash:"rmd160",id:"3021300906052b2403020105000414"},"RSA-RIPEMD160":{sign:"rsa",hash:"rmd160",id:"3021300906052b2403020105000414"},md5WithRSAEncryption:{sign:"rsa",hash:"md5",id:"3020300c06082a864886f70d020505000410"},"RSA-MD5":{sign:"rsa",hash:"md5",id:"3020300c06082a864886f70d020505000410"}}},{}],90:[function(e,t,i){t.exports={"1.3.132.0.10":"secp256k1","1.3.132.0.33":"p224","1.2.840.10045.3.1.1":"p192","1.2.840.10045.3.1.7":"p256","1.3.132.0.34":"p384","1.3.132.0.35":"p521"}},{}],91:[function(e,t,i){var n=e("safe-buffer").Buffer,r=e("create-hash"),s=e("readable-stream"),a=e("inherits"),o=e("./sign"),c=e("./verify"),l=e("./algorithms.json");function u(e){s.Writable.call(this);var t=l[e];if(!t)throw new Error("Unknown message digest");this._hashType=t.hash,this._hash=r(t.hash),this._tag=t.id,this._signType=t.sign}function p(e){s.Writable.call(this);var t=l[e];if(!t)throw new Error("Unknown message digest");this._hash=r(t.hash),this._tag=t.id,this._signType=t.sign}function d(e){return new u(e)}function f(e){return new p(e)}Object.keys(l).forEach((function(e){l[e].id=n.from(l[e].id,"hex"),l[e.toLowerCase()]=l[e]})),a(u,s.Writable),u.prototype._write=function(e,t,i){this._hash.update(e),i()},u.prototype.update=function(e,t){return"string"==typeof e&&(e=n.from(e,t)),this._hash.update(e),this},u.prototype.sign=function(e,t){this.end();var i=this._hash.digest(),n=o(i,e,this._hashType,this._signType,this._tag);return t?n.toString(t):n},a(p,s.Writable),p.prototype._write=function(e,t,i){this._hash.update(e),i()},p.prototype.update=function(e,t){return"string"==typeof e&&(e=n.from(e,t)),this._hash.update(e),this},p.prototype.verify=function(e,t,i){"string"==typeof t&&(t=n.from(t,i)),this.end();var r=this._hash.digest();return c(t,r,e,this._signType,this._tag)},t.exports={Sign:d,Verify:f,createSign:d,createVerify:f}},{"./algorithms.json":89,"./sign":92,"./verify":93,"create-hash":139,inherits:245,"readable-stream":108,"safe-buffer":382}],92:[function(e,t,i){var n=e("safe-buffer").Buffer,r=e("create-hmac"),s=e("browserify-rsa"),a=e("elliptic").ec,o=e("bn.js"),c=e("parse-asn1"),l=e("./curves.json");function u(e,t,i,s){if((e=n.from(e.toArray())).length0&&i.ishrn(n),i}function d(e,t,i){var s,a;do{for(s=n.alloc(0);8*s.length=t)throw new Error("invalid sig")}t.exports=function(e,t,i,l,u){var p=a(i);if("ec"===p.type){if("ecdsa"!==l&&"ecdsa/rsa"!==l)throw new Error("wrong public key type");return function(e,t,i){var n=o[i.data.algorithm.curve.join(".")];if(!n)throw new Error("unknown curve "+i.data.algorithm.curve.join("."));var r=new s(n),a=i.data.subjectPrivateKey.data;return r.verify(t,e,a)}(e,t,p)}if("dsa"===p.type){if("dsa"!==l)throw new Error("wrong public key type");return function(e,t,i){var n=i.data.p,s=i.data.q,o=i.data.g,l=i.data.pub_key,u=a.signature.decode(e,"der"),p=u.s,d=u.r;c(p,s),c(d,s);var f=r.mont(n),h=p.invm(s);return 0===o.toRed(f).redPow(new r(t).mul(h).mod(s)).fromRed().mul(l.toRed(f).redPow(d.mul(h).mod(s)).fromRed()).mod(n).mod(s).cmp(d)}(e,t,p)}if("rsa"!==l&&"ecdsa/rsa"!==l)throw new Error("wrong public key type");t=n.concat([u,t]);for(var d=p.modulus.byteLength(),f=[1],h=0;t.length+f.length+2=this.size;){this._bufferedBytes-=this.size;const e=[];let t=0;for(;t=48&&i<=57?i-48:i>=65&&i<=70?i-55:i>=97&&i<=102?i-87:void n(!1,"Invalid character in "+e)}function c(e,t,i){var n=o(e,i);return i-1>=t&&(n|=o(e,i-1)<<4),n}function l(e,t,i,r){for(var s=0,a=0,o=Math.min(e.length,i),c=t;c=49?l-49+10:l>=17?l-17+10:l,n(l>=0&&a0?e:t},s.min=function(e,t){return e.cmp(t)<0?e:t},s.prototype._init=function(e,t,i){if("number"==typeof e)return this._initNumber(e,t,i);if("object"==typeof e)return this._initArray(e,t,i);"hex"===t&&(t=16),n(t===(0|t)&&t>=2&&t<=36);var r=0;"-"===(e=e.toString().replace(/\s+/g,""))[0]&&(r++,this.negative=1),r=0;r-=3)a=e[r]|e[r-1]<<8|e[r-2]<<16,this.words[s]|=a<>>26-o&67108863,(o+=24)>=26&&(o-=26,s++);else if("le"===i)for(r=0,s=0;r>>26-o&67108863,(o+=24)>=26&&(o-=26,s++);return this._strip()},s.prototype._parseHex=function(e,t,i){this.length=Math.ceil((e.length-t)/6),this.words=new Array(this.length);for(var n=0;n=t;n-=2)r=c(e,t,n)<=18?(s-=18,a+=1,this.words[a]|=r>>>26):s+=8;else for(n=(e.length-t)%2==0?t+1:t;n=18?(s-=18,a+=1,this.words[a]|=r>>>26):s+=8;this._strip()},s.prototype._parseBase=function(e,t,i){this.words=[0],this.length=1;for(var n=0,r=1;r<=67108863;r*=t)n++;n--,r=r/t|0;for(var s=e.length-i,a=s%n,o=Math.min(s,s-a)+i,c=0,u=i;u1&&0===this.words[this.length-1];)this.length--;return this._normSign()},s.prototype._normSign=function(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this},"undefined"!=typeof Symbol&&"function"==typeof Symbol.for)try{s.prototype[Symbol.for("nodejs.util.inspect.custom")]=p}catch(e){s.prototype.inspect=p}else s.prototype.inspect=p;function p(){return(this.red?""}var d=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],f=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],h=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];s.prototype.toString=function(e,t){var i;if(t=0|t||1,16===(e=e||10)||"hex"===e){i="";for(var r=0,s=0,a=0;a>>24-r&16777215,(r+=2)>=26&&(r-=26,a--),i=0!==s||a!==this.length-1?d[6-c.length]+c+i:c+i}for(0!==s&&(i=s.toString(16)+i);i.length%t!=0;)i="0"+i;return 0!==this.negative&&(i="-"+i),i}if(e===(0|e)&&e>=2&&e<=36){var l=f[e],u=h[e];i="";var p=this.clone();for(p.negative=0;!p.isZero();){var m=p.modrn(u).toString(e);i=(p=p.idivn(u)).isZero()?m+i:d[l-m.length]+m+i}for(this.isZero()&&(i="0"+i);i.length%t!=0;)i="0"+i;return 0!==this.negative&&(i="-"+i),i}n(!1,"Base should be between 2 and 36")},s.prototype.toNumber=function(){var e=this.words[0];return 2===this.length?e+=67108864*this.words[1]:3===this.length&&1===this.words[2]?e+=4503599627370496+67108864*this.words[1]:this.length>2&&n(!1,"Number can only safely store up to 53 bits"),0!==this.negative?-e:e},s.prototype.toJSON=function(){return this.toString(16,2)},a&&(s.prototype.toBuffer=function(e,t){return this.toArrayLike(a,e,t)}),s.prototype.toArray=function(e,t){return this.toArrayLike(Array,e,t)};function m(e,t,i){i.negative=t.negative^e.negative;var n=e.length+t.length|0;i.length=n,n=n-1|0;var r=0|e.words[0],s=0|t.words[0],a=r*s,o=67108863&a,c=a/67108864|0;i.words[0]=o;for(var l=1;l>>26,p=67108863&c,d=Math.min(l,t.length-1),f=Math.max(0,l-e.length+1);f<=d;f++){var h=l-f|0;u+=(a=(r=0|e.words[h])*(s=0|t.words[f])+p)/67108864|0,p=67108863&a}i.words[l]=0|p,c=0|u}return 0!==c?i.words[l]=0|c:i.length--,i._strip()}s.prototype.toArrayLike=function(e,t,i){this._strip();var r=this.byteLength(),s=i||Math.max(1,r);n(r<=s,"byte array longer than desired length"),n(s>0,"Requested array length <= 0");var a=function(e,t){return e.allocUnsafe?e.allocUnsafe(t):new e(t)}(e,s);return this["_toArrayLike"+("le"===t?"LE":"BE")](a,r),a},s.prototype._toArrayLikeLE=function(e,t){for(var i=0,n=0,r=0,s=0;r>8&255),i>16&255),6===s?(i>24&255),n=0,s=0):(n=a>>>24,s+=2)}if(i=0&&(e[i--]=a>>8&255),i>=0&&(e[i--]=a>>16&255),6===s?(i>=0&&(e[i--]=a>>24&255),n=0,s=0):(n=a>>>24,s+=2)}if(i>=0)for(e[i--]=n;i>=0;)e[i--]=0},Math.clz32?s.prototype._countBits=function(e){return 32-Math.clz32(e)}:s.prototype._countBits=function(e){var t=e,i=0;return t>=4096&&(i+=13,t>>>=13),t>=64&&(i+=7,t>>>=7),t>=8&&(i+=4,t>>>=4),t>=2&&(i+=2,t>>>=2),i+t},s.prototype._zeroBits=function(e){if(0===e)return 26;var t=e,i=0;return 0==(8191&t)&&(i+=13,t>>>=13),0==(127&t)&&(i+=7,t>>>=7),0==(15&t)&&(i+=4,t>>>=4),0==(3&t)&&(i+=2,t>>>=2),0==(1&t)&&i++,i},s.prototype.bitLength=function(){var e=this.words[this.length-1],t=this._countBits(e);return 26*(this.length-1)+t},s.prototype.zeroBits=function(){if(this.isZero())return 0;for(var e=0,t=0;te.length?this.clone().ior(e):e.clone().ior(this)},s.prototype.uor=function(e){return this.length>e.length?this.clone().iuor(e):e.clone().iuor(this)},s.prototype.iuand=function(e){var t;t=this.length>e.length?e:this;for(var i=0;ie.length?this.clone().iand(e):e.clone().iand(this)},s.prototype.uand=function(e){return this.length>e.length?this.clone().iuand(e):e.clone().iuand(this)},s.prototype.iuxor=function(e){var t,i;this.length>e.length?(t=this,i=e):(t=e,i=this);for(var n=0;ne.length?this.clone().ixor(e):e.clone().ixor(this)},s.prototype.uxor=function(e){return this.length>e.length?this.clone().iuxor(e):e.clone().iuxor(this)},s.prototype.inotn=function(e){n("number"==typeof e&&e>=0);var t=0|Math.ceil(e/26),i=e%26;this._expand(t),i>0&&t--;for(var r=0;r0&&(this.words[r]=~this.words[r]&67108863>>26-i),this._strip()},s.prototype.notn=function(e){return this.clone().inotn(e)},s.prototype.setn=function(e,t){n("number"==typeof e&&e>=0);var i=e/26|0,r=e%26;return this._expand(i+1),this.words[i]=t?this.words[i]|1<e.length?(i=this,n=e):(i=e,n=this);for(var r=0,s=0;s>>26;for(;0!==r&&s>>26;if(this.length=i.length,0!==r)this.words[this.length]=r,this.length++;else if(i!==this)for(;se.length?this.clone().iadd(e):e.clone().iadd(this)},s.prototype.isub=function(e){if(0!==e.negative){e.negative=0;var t=this.iadd(e);return e.negative=1,t._normSign()}if(0!==this.negative)return this.negative=0,this.iadd(e),this.negative=1,this._normSign();var i,n,r=this.cmp(e);if(0===r)return this.negative=0,this.length=1,this.words[0]=0,this;r>0?(i=this,n=e):(i=e,n=this);for(var s=0,a=0;a>26,this.words[a]=67108863&t;for(;0!==s&&a>26,this.words[a]=67108863&t;if(0===s&&a>>13,f=0|a[1],h=8191&f,m=f>>>13,b=0|a[2],v=8191&b,g=b>>>13,y=0|a[3],_=8191&y,x=y>>>13,w=0|a[4],k=8191&w,E=w>>>13,S=0|a[5],M=8191&S,A=S>>>13,j=0|a[6],I=8191&j,T=j>>>13,C=0|a[7],B=8191&C,R=C>>>13,L=0|a[8],O=8191&L,P=L>>>13,U=0|a[9],q=8191&U,N=U>>>13,D=0|o[0],z=8191&D,H=D>>>13,F=0|o[1],W=8191&F,V=F>>>13,K=0|o[2],$=8191&K,G=K>>>13,X=0|o[3],Y=8191&X,Z=X>>>13,J=0|o[4],Q=8191&J,ee=J>>>13,te=0|o[5],ie=8191&te,ne=te>>>13,re=0|o[6],se=8191&re,ae=re>>>13,oe=0|o[7],ce=8191&oe,le=oe>>>13,ue=0|o[8],pe=8191&ue,de=ue>>>13,fe=0|o[9],he=8191&fe,me=fe>>>13;i.negative=e.negative^t.negative,i.length=19;var be=(l+(n=Math.imul(p,z))|0)+((8191&(r=(r=Math.imul(p,H))+Math.imul(d,z)|0))<<13)|0;l=((s=Math.imul(d,H))+(r>>>13)|0)+(be>>>26)|0,be&=67108863,n=Math.imul(h,z),r=(r=Math.imul(h,H))+Math.imul(m,z)|0,s=Math.imul(m,H);var ve=(l+(n=n+Math.imul(p,W)|0)|0)+((8191&(r=(r=r+Math.imul(p,V)|0)+Math.imul(d,W)|0))<<13)|0;l=((s=s+Math.imul(d,V)|0)+(r>>>13)|0)+(ve>>>26)|0,ve&=67108863,n=Math.imul(v,z),r=(r=Math.imul(v,H))+Math.imul(g,z)|0,s=Math.imul(g,H),n=n+Math.imul(h,W)|0,r=(r=r+Math.imul(h,V)|0)+Math.imul(m,W)|0,s=s+Math.imul(m,V)|0;var ge=(l+(n=n+Math.imul(p,$)|0)|0)+((8191&(r=(r=r+Math.imul(p,G)|0)+Math.imul(d,$)|0))<<13)|0;l=((s=s+Math.imul(d,G)|0)+(r>>>13)|0)+(ge>>>26)|0,ge&=67108863,n=Math.imul(_,z),r=(r=Math.imul(_,H))+Math.imul(x,z)|0,s=Math.imul(x,H),n=n+Math.imul(v,W)|0,r=(r=r+Math.imul(v,V)|0)+Math.imul(g,W)|0,s=s+Math.imul(g,V)|0,n=n+Math.imul(h,$)|0,r=(r=r+Math.imul(h,G)|0)+Math.imul(m,$)|0,s=s+Math.imul(m,G)|0;var ye=(l+(n=n+Math.imul(p,Y)|0)|0)+((8191&(r=(r=r+Math.imul(p,Z)|0)+Math.imul(d,Y)|0))<<13)|0;l=((s=s+Math.imul(d,Z)|0)+(r>>>13)|0)+(ye>>>26)|0,ye&=67108863,n=Math.imul(k,z),r=(r=Math.imul(k,H))+Math.imul(E,z)|0,s=Math.imul(E,H),n=n+Math.imul(_,W)|0,r=(r=r+Math.imul(_,V)|0)+Math.imul(x,W)|0,s=s+Math.imul(x,V)|0,n=n+Math.imul(v,$)|0,r=(r=r+Math.imul(v,G)|0)+Math.imul(g,$)|0,s=s+Math.imul(g,G)|0,n=n+Math.imul(h,Y)|0,r=(r=r+Math.imul(h,Z)|0)+Math.imul(m,Y)|0,s=s+Math.imul(m,Z)|0;var _e=(l+(n=n+Math.imul(p,Q)|0)|0)+((8191&(r=(r=r+Math.imul(p,ee)|0)+Math.imul(d,Q)|0))<<13)|0;l=((s=s+Math.imul(d,ee)|0)+(r>>>13)|0)+(_e>>>26)|0,_e&=67108863,n=Math.imul(M,z),r=(r=Math.imul(M,H))+Math.imul(A,z)|0,s=Math.imul(A,H),n=n+Math.imul(k,W)|0,r=(r=r+Math.imul(k,V)|0)+Math.imul(E,W)|0,s=s+Math.imul(E,V)|0,n=n+Math.imul(_,$)|0,r=(r=r+Math.imul(_,G)|0)+Math.imul(x,$)|0,s=s+Math.imul(x,G)|0,n=n+Math.imul(v,Y)|0,r=(r=r+Math.imul(v,Z)|0)+Math.imul(g,Y)|0,s=s+Math.imul(g,Z)|0,n=n+Math.imul(h,Q)|0,r=(r=r+Math.imul(h,ee)|0)+Math.imul(m,Q)|0,s=s+Math.imul(m,ee)|0;var xe=(l+(n=n+Math.imul(p,ie)|0)|0)+((8191&(r=(r=r+Math.imul(p,ne)|0)+Math.imul(d,ie)|0))<<13)|0;l=((s=s+Math.imul(d,ne)|0)+(r>>>13)|0)+(xe>>>26)|0,xe&=67108863,n=Math.imul(I,z),r=(r=Math.imul(I,H))+Math.imul(T,z)|0,s=Math.imul(T,H),n=n+Math.imul(M,W)|0,r=(r=r+Math.imul(M,V)|0)+Math.imul(A,W)|0,s=s+Math.imul(A,V)|0,n=n+Math.imul(k,$)|0,r=(r=r+Math.imul(k,G)|0)+Math.imul(E,$)|0,s=s+Math.imul(E,G)|0,n=n+Math.imul(_,Y)|0,r=(r=r+Math.imul(_,Z)|0)+Math.imul(x,Y)|0,s=s+Math.imul(x,Z)|0,n=n+Math.imul(v,Q)|0,r=(r=r+Math.imul(v,ee)|0)+Math.imul(g,Q)|0,s=s+Math.imul(g,ee)|0,n=n+Math.imul(h,ie)|0,r=(r=r+Math.imul(h,ne)|0)+Math.imul(m,ie)|0,s=s+Math.imul(m,ne)|0;var we=(l+(n=n+Math.imul(p,se)|0)|0)+((8191&(r=(r=r+Math.imul(p,ae)|0)+Math.imul(d,se)|0))<<13)|0;l=((s=s+Math.imul(d,ae)|0)+(r>>>13)|0)+(we>>>26)|0,we&=67108863,n=Math.imul(B,z),r=(r=Math.imul(B,H))+Math.imul(R,z)|0,s=Math.imul(R,H),n=n+Math.imul(I,W)|0,r=(r=r+Math.imul(I,V)|0)+Math.imul(T,W)|0,s=s+Math.imul(T,V)|0,n=n+Math.imul(M,$)|0,r=(r=r+Math.imul(M,G)|0)+Math.imul(A,$)|0,s=s+Math.imul(A,G)|0,n=n+Math.imul(k,Y)|0,r=(r=r+Math.imul(k,Z)|0)+Math.imul(E,Y)|0,s=s+Math.imul(E,Z)|0,n=n+Math.imul(_,Q)|0,r=(r=r+Math.imul(_,ee)|0)+Math.imul(x,Q)|0,s=s+Math.imul(x,ee)|0,n=n+Math.imul(v,ie)|0,r=(r=r+Math.imul(v,ne)|0)+Math.imul(g,ie)|0,s=s+Math.imul(g,ne)|0,n=n+Math.imul(h,se)|0,r=(r=r+Math.imul(h,ae)|0)+Math.imul(m,se)|0,s=s+Math.imul(m,ae)|0;var ke=(l+(n=n+Math.imul(p,ce)|0)|0)+((8191&(r=(r=r+Math.imul(p,le)|0)+Math.imul(d,ce)|0))<<13)|0;l=((s=s+Math.imul(d,le)|0)+(r>>>13)|0)+(ke>>>26)|0,ke&=67108863,n=Math.imul(O,z),r=(r=Math.imul(O,H))+Math.imul(P,z)|0,s=Math.imul(P,H),n=n+Math.imul(B,W)|0,r=(r=r+Math.imul(B,V)|0)+Math.imul(R,W)|0,s=s+Math.imul(R,V)|0,n=n+Math.imul(I,$)|0,r=(r=r+Math.imul(I,G)|0)+Math.imul(T,$)|0,s=s+Math.imul(T,G)|0,n=n+Math.imul(M,Y)|0,r=(r=r+Math.imul(M,Z)|0)+Math.imul(A,Y)|0,s=s+Math.imul(A,Z)|0,n=n+Math.imul(k,Q)|0,r=(r=r+Math.imul(k,ee)|0)+Math.imul(E,Q)|0,s=s+Math.imul(E,ee)|0,n=n+Math.imul(_,ie)|0,r=(r=r+Math.imul(_,ne)|0)+Math.imul(x,ie)|0,s=s+Math.imul(x,ne)|0,n=n+Math.imul(v,se)|0,r=(r=r+Math.imul(v,ae)|0)+Math.imul(g,se)|0,s=s+Math.imul(g,ae)|0,n=n+Math.imul(h,ce)|0,r=(r=r+Math.imul(h,le)|0)+Math.imul(m,ce)|0,s=s+Math.imul(m,le)|0;var Ee=(l+(n=n+Math.imul(p,pe)|0)|0)+((8191&(r=(r=r+Math.imul(p,de)|0)+Math.imul(d,pe)|0))<<13)|0;l=((s=s+Math.imul(d,de)|0)+(r>>>13)|0)+(Ee>>>26)|0,Ee&=67108863,n=Math.imul(q,z),r=(r=Math.imul(q,H))+Math.imul(N,z)|0,s=Math.imul(N,H),n=n+Math.imul(O,W)|0,r=(r=r+Math.imul(O,V)|0)+Math.imul(P,W)|0,s=s+Math.imul(P,V)|0,n=n+Math.imul(B,$)|0,r=(r=r+Math.imul(B,G)|0)+Math.imul(R,$)|0,s=s+Math.imul(R,G)|0,n=n+Math.imul(I,Y)|0,r=(r=r+Math.imul(I,Z)|0)+Math.imul(T,Y)|0,s=s+Math.imul(T,Z)|0,n=n+Math.imul(M,Q)|0,r=(r=r+Math.imul(M,ee)|0)+Math.imul(A,Q)|0,s=s+Math.imul(A,ee)|0,n=n+Math.imul(k,ie)|0,r=(r=r+Math.imul(k,ne)|0)+Math.imul(E,ie)|0,s=s+Math.imul(E,ne)|0,n=n+Math.imul(_,se)|0,r=(r=r+Math.imul(_,ae)|0)+Math.imul(x,se)|0,s=s+Math.imul(x,ae)|0,n=n+Math.imul(v,ce)|0,r=(r=r+Math.imul(v,le)|0)+Math.imul(g,ce)|0,s=s+Math.imul(g,le)|0,n=n+Math.imul(h,pe)|0,r=(r=r+Math.imul(h,de)|0)+Math.imul(m,pe)|0,s=s+Math.imul(m,de)|0;var Se=(l+(n=n+Math.imul(p,he)|0)|0)+((8191&(r=(r=r+Math.imul(p,me)|0)+Math.imul(d,he)|0))<<13)|0;l=((s=s+Math.imul(d,me)|0)+(r>>>13)|0)+(Se>>>26)|0,Se&=67108863,n=Math.imul(q,W),r=(r=Math.imul(q,V))+Math.imul(N,W)|0,s=Math.imul(N,V),n=n+Math.imul(O,$)|0,r=(r=r+Math.imul(O,G)|0)+Math.imul(P,$)|0,s=s+Math.imul(P,G)|0,n=n+Math.imul(B,Y)|0,r=(r=r+Math.imul(B,Z)|0)+Math.imul(R,Y)|0,s=s+Math.imul(R,Z)|0,n=n+Math.imul(I,Q)|0,r=(r=r+Math.imul(I,ee)|0)+Math.imul(T,Q)|0,s=s+Math.imul(T,ee)|0,n=n+Math.imul(M,ie)|0,r=(r=r+Math.imul(M,ne)|0)+Math.imul(A,ie)|0,s=s+Math.imul(A,ne)|0,n=n+Math.imul(k,se)|0,r=(r=r+Math.imul(k,ae)|0)+Math.imul(E,se)|0,s=s+Math.imul(E,ae)|0,n=n+Math.imul(_,ce)|0,r=(r=r+Math.imul(_,le)|0)+Math.imul(x,ce)|0,s=s+Math.imul(x,le)|0,n=n+Math.imul(v,pe)|0,r=(r=r+Math.imul(v,de)|0)+Math.imul(g,pe)|0,s=s+Math.imul(g,de)|0;var Me=(l+(n=n+Math.imul(h,he)|0)|0)+((8191&(r=(r=r+Math.imul(h,me)|0)+Math.imul(m,he)|0))<<13)|0;l=((s=s+Math.imul(m,me)|0)+(r>>>13)|0)+(Me>>>26)|0,Me&=67108863,n=Math.imul(q,$),r=(r=Math.imul(q,G))+Math.imul(N,$)|0,s=Math.imul(N,G),n=n+Math.imul(O,Y)|0,r=(r=r+Math.imul(O,Z)|0)+Math.imul(P,Y)|0,s=s+Math.imul(P,Z)|0,n=n+Math.imul(B,Q)|0,r=(r=r+Math.imul(B,ee)|0)+Math.imul(R,Q)|0,s=s+Math.imul(R,ee)|0,n=n+Math.imul(I,ie)|0,r=(r=r+Math.imul(I,ne)|0)+Math.imul(T,ie)|0,s=s+Math.imul(T,ne)|0,n=n+Math.imul(M,se)|0,r=(r=r+Math.imul(M,ae)|0)+Math.imul(A,se)|0,s=s+Math.imul(A,ae)|0,n=n+Math.imul(k,ce)|0,r=(r=r+Math.imul(k,le)|0)+Math.imul(E,ce)|0,s=s+Math.imul(E,le)|0,n=n+Math.imul(_,pe)|0,r=(r=r+Math.imul(_,de)|0)+Math.imul(x,pe)|0,s=s+Math.imul(x,de)|0;var Ae=(l+(n=n+Math.imul(v,he)|0)|0)+((8191&(r=(r=r+Math.imul(v,me)|0)+Math.imul(g,he)|0))<<13)|0;l=((s=s+Math.imul(g,me)|0)+(r>>>13)|0)+(Ae>>>26)|0,Ae&=67108863,n=Math.imul(q,Y),r=(r=Math.imul(q,Z))+Math.imul(N,Y)|0,s=Math.imul(N,Z),n=n+Math.imul(O,Q)|0,r=(r=r+Math.imul(O,ee)|0)+Math.imul(P,Q)|0,s=s+Math.imul(P,ee)|0,n=n+Math.imul(B,ie)|0,r=(r=r+Math.imul(B,ne)|0)+Math.imul(R,ie)|0,s=s+Math.imul(R,ne)|0,n=n+Math.imul(I,se)|0,r=(r=r+Math.imul(I,ae)|0)+Math.imul(T,se)|0,s=s+Math.imul(T,ae)|0,n=n+Math.imul(M,ce)|0,r=(r=r+Math.imul(M,le)|0)+Math.imul(A,ce)|0,s=s+Math.imul(A,le)|0,n=n+Math.imul(k,pe)|0,r=(r=r+Math.imul(k,de)|0)+Math.imul(E,pe)|0,s=s+Math.imul(E,de)|0;var je=(l+(n=n+Math.imul(_,he)|0)|0)+((8191&(r=(r=r+Math.imul(_,me)|0)+Math.imul(x,he)|0))<<13)|0;l=((s=s+Math.imul(x,me)|0)+(r>>>13)|0)+(je>>>26)|0,je&=67108863,n=Math.imul(q,Q),r=(r=Math.imul(q,ee))+Math.imul(N,Q)|0,s=Math.imul(N,ee),n=n+Math.imul(O,ie)|0,r=(r=r+Math.imul(O,ne)|0)+Math.imul(P,ie)|0,s=s+Math.imul(P,ne)|0,n=n+Math.imul(B,se)|0,r=(r=r+Math.imul(B,ae)|0)+Math.imul(R,se)|0,s=s+Math.imul(R,ae)|0,n=n+Math.imul(I,ce)|0,r=(r=r+Math.imul(I,le)|0)+Math.imul(T,ce)|0,s=s+Math.imul(T,le)|0,n=n+Math.imul(M,pe)|0,r=(r=r+Math.imul(M,de)|0)+Math.imul(A,pe)|0,s=s+Math.imul(A,de)|0;var Ie=(l+(n=n+Math.imul(k,he)|0)|0)+((8191&(r=(r=r+Math.imul(k,me)|0)+Math.imul(E,he)|0))<<13)|0;l=((s=s+Math.imul(E,me)|0)+(r>>>13)|0)+(Ie>>>26)|0,Ie&=67108863,n=Math.imul(q,ie),r=(r=Math.imul(q,ne))+Math.imul(N,ie)|0,s=Math.imul(N,ne),n=n+Math.imul(O,se)|0,r=(r=r+Math.imul(O,ae)|0)+Math.imul(P,se)|0,s=s+Math.imul(P,ae)|0,n=n+Math.imul(B,ce)|0,r=(r=r+Math.imul(B,le)|0)+Math.imul(R,ce)|0,s=s+Math.imul(R,le)|0,n=n+Math.imul(I,pe)|0,r=(r=r+Math.imul(I,de)|0)+Math.imul(T,pe)|0,s=s+Math.imul(T,de)|0;var Te=(l+(n=n+Math.imul(M,he)|0)|0)+((8191&(r=(r=r+Math.imul(M,me)|0)+Math.imul(A,he)|0))<<13)|0;l=((s=s+Math.imul(A,me)|0)+(r>>>13)|0)+(Te>>>26)|0,Te&=67108863,n=Math.imul(q,se),r=(r=Math.imul(q,ae))+Math.imul(N,se)|0,s=Math.imul(N,ae),n=n+Math.imul(O,ce)|0,r=(r=r+Math.imul(O,le)|0)+Math.imul(P,ce)|0,s=s+Math.imul(P,le)|0,n=n+Math.imul(B,pe)|0,r=(r=r+Math.imul(B,de)|0)+Math.imul(R,pe)|0,s=s+Math.imul(R,de)|0;var Ce=(l+(n=n+Math.imul(I,he)|0)|0)+((8191&(r=(r=r+Math.imul(I,me)|0)+Math.imul(T,he)|0))<<13)|0;l=((s=s+Math.imul(T,me)|0)+(r>>>13)|0)+(Ce>>>26)|0,Ce&=67108863,n=Math.imul(q,ce),r=(r=Math.imul(q,le))+Math.imul(N,ce)|0,s=Math.imul(N,le),n=n+Math.imul(O,pe)|0,r=(r=r+Math.imul(O,de)|0)+Math.imul(P,pe)|0,s=s+Math.imul(P,de)|0;var Be=(l+(n=n+Math.imul(B,he)|0)|0)+((8191&(r=(r=r+Math.imul(B,me)|0)+Math.imul(R,he)|0))<<13)|0;l=((s=s+Math.imul(R,me)|0)+(r>>>13)|0)+(Be>>>26)|0,Be&=67108863,n=Math.imul(q,pe),r=(r=Math.imul(q,de))+Math.imul(N,pe)|0,s=Math.imul(N,de);var Re=(l+(n=n+Math.imul(O,he)|0)|0)+((8191&(r=(r=r+Math.imul(O,me)|0)+Math.imul(P,he)|0))<<13)|0;l=((s=s+Math.imul(P,me)|0)+(r>>>13)|0)+(Re>>>26)|0,Re&=67108863;var Le=(l+(n=Math.imul(q,he))|0)+((8191&(r=(r=Math.imul(q,me))+Math.imul(N,he)|0))<<13)|0;return l=((s=Math.imul(N,me))+(r>>>13)|0)+(Le>>>26)|0,Le&=67108863,c[0]=be,c[1]=ve,c[2]=ge,c[3]=ye,c[4]=_e,c[5]=xe,c[6]=we,c[7]=ke,c[8]=Ee,c[9]=Se,c[10]=Me,c[11]=Ae,c[12]=je,c[13]=Ie,c[14]=Te,c[15]=Ce,c[16]=Be,c[17]=Re,c[18]=Le,0!==l&&(c[19]=l,i.length++),i};function v(e,t,i){i.negative=t.negative^e.negative,i.length=e.length+t.length;for(var n=0,r=0,s=0;s>>26)|0)>>>26,a&=67108863}i.words[s]=o,n=a,a=r}return 0!==n?i.words[s]=n:i.length--,i._strip()}function g(e,t,i){return v(e,t,i)}function y(e,t){this.x=e,this.y=t}Math.imul||(b=m),s.prototype.mulTo=function(e,t){var i=this.length+e.length;return 10===this.length&&10===e.length?b(this,e,t):i<63?m(this,e,t):i<1024?v(this,e,t):g(this,e,t)},y.prototype.makeRBT=function(e){for(var t=new Array(e),i=s.prototype._countBits(e)-1,n=0;n>=1;return n},y.prototype.permute=function(e,t,i,n,r,s){for(var a=0;a>>=1)r++;return 1<>>=13,i[2*a+1]=8191&s,s>>>=13;for(a=2*t;a>=26,i+=s/67108864|0,i+=a>>>26,this.words[r]=67108863&a}return 0!==i&&(this.words[r]=i,this.length++),t?this.ineg():this},s.prototype.muln=function(e){return this.clone().imuln(e)},s.prototype.sqr=function(){return this.mul(this)},s.prototype.isqr=function(){return this.imul(this.clone())},s.prototype.pow=function(e){var t=function(e){for(var t=new Array(e.bitLength()),i=0;i>>r&1}return t}(e);if(0===t.length)return new s(1);for(var i=this,n=0;n=0);var t,i=e%26,r=(e-i)/26,s=67108863>>>26-i<<26-i;if(0!==i){var a=0;for(t=0;t>>26-i}a&&(this.words[t]=a,this.length++)}if(0!==r){for(t=this.length-1;t>=0;t--)this.words[t+r]=this.words[t];for(t=0;t=0),r=t?(t-t%26)/26:0;var s=e%26,a=Math.min((e-s)/26,this.length),o=67108863^67108863>>>s<a)for(this.length-=a,l=0;l=0&&(0!==u||l>=r);l--){var p=0|this.words[l];this.words[l]=u<<26-s|p>>>s,u=p&o}return c&&0!==u&&(c.words[c.length++]=u),0===this.length&&(this.words[0]=0,this.length=1),this._strip()},s.prototype.ishrn=function(e,t,i){return n(0===this.negative),this.iushrn(e,t,i)},s.prototype.shln=function(e){return this.clone().ishln(e)},s.prototype.ushln=function(e){return this.clone().iushln(e)},s.prototype.shrn=function(e){return this.clone().ishrn(e)},s.prototype.ushrn=function(e){return this.clone().iushrn(e)},s.prototype.testn=function(e){n("number"==typeof e&&e>=0);var t=e%26,i=(e-t)/26,r=1<=0);var t=e%26,i=(e-t)/26;if(n(0===this.negative,"imaskn works only with positive numbers"),this.length<=i)return this;if(0!==t&&i++,this.length=Math.min(i,this.length),0!==t){var r=67108863^67108863>>>t<=67108864;t++)this.words[t]-=67108864,t===this.length-1?this.words[t+1]=1:this.words[t+1]++;return this.length=Math.max(this.length,t+1),this},s.prototype.isubn=function(e){if(n("number"==typeof e),n(e<67108864),e<0)return this.iaddn(-e);if(0!==this.negative)return this.negative=0,this.iaddn(e),this.negative=1,this;if(this.words[0]-=e,1===this.length&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var t=0;t>26)-(c/67108864|0),this.words[r+i]=67108863&s}for(;r>26,this.words[r+i]=67108863&s;if(0===o)return this._strip();for(n(-1===o),o=0,r=0;r>26,this.words[r]=67108863&s;return this.negative=1,this._strip()},s.prototype._wordDiv=function(e,t){var i=(this.length,e.length),n=this.clone(),r=e,a=0|r.words[r.length-1];0!==(i=26-this._countBits(a))&&(r=r.ushln(i),n.iushln(i),a=0|r.words[r.length-1]);var o,c=n.length-r.length;if("mod"!==t){(o=new s(null)).length=c+1,o.words=new Array(o.length);for(var l=0;l=0;p--){var d=67108864*(0|n.words[r.length+p])+(0|n.words[r.length+p-1]);for(d=Math.min(d/a|0,67108863),n._ishlnsubmul(r,d,p);0!==n.negative;)d--,n.negative=0,n._ishlnsubmul(r,1,p),n.isZero()||(n.negative^=1);o&&(o.words[p]=d)}return o&&o._strip(),n._strip(),"div"!==t&&0!==i&&n.iushrn(i),{div:o||null,mod:n}},s.prototype.divmod=function(e,t,i){return n(!e.isZero()),this.isZero()?{div:new s(0),mod:new s(0)}:0!==this.negative&&0===e.negative?(o=this.neg().divmod(e,t),"mod"!==t&&(r=o.div.neg()),"div"!==t&&(a=o.mod.neg(),i&&0!==a.negative&&a.iadd(e)),{div:r,mod:a}):0===this.negative&&0!==e.negative?(o=this.divmod(e.neg(),t),"mod"!==t&&(r=o.div.neg()),{div:r,mod:o.mod}):0!=(this.negative&e.negative)?(o=this.neg().divmod(e.neg(),t),"div"!==t&&(a=o.mod.neg(),i&&0!==a.negative&&a.isub(e)),{div:o.div,mod:a}):e.length>this.length||this.cmp(e)<0?{div:new s(0),mod:this}:1===e.length?"div"===t?{div:this.divn(e.words[0]),mod:null}:"mod"===t?{div:null,mod:new s(this.modrn(e.words[0]))}:{div:this.divn(e.words[0]),mod:new s(this.modrn(e.words[0]))}:this._wordDiv(e,t);var r,a,o},s.prototype.div=function(e){return this.divmod(e,"div",!1).div},s.prototype.mod=function(e){return this.divmod(e,"mod",!1).mod},s.prototype.umod=function(e){return this.divmod(e,"mod",!0).mod},s.prototype.divRound=function(e){var t=this.divmod(e);if(t.mod.isZero())return t.div;var i=0!==t.div.negative?t.mod.isub(e):t.mod,n=e.ushrn(1),r=e.andln(1),s=i.cmp(n);return s<0||1===r&&0===s?t.div:0!==t.div.negative?t.div.isubn(1):t.div.iaddn(1)},s.prototype.modrn=function(e){var t=e<0;t&&(e=-e),n(e<=67108863);for(var i=(1<<26)%e,r=0,s=this.length-1;s>=0;s--)r=(i*r+(0|this.words[s]))%e;return t?-r:r},s.prototype.modn=function(e){return this.modrn(e)},s.prototype.idivn=function(e){var t=e<0;t&&(e=-e),n(e<=67108863);for(var i=0,r=this.length-1;r>=0;r--){var s=(0|this.words[r])+67108864*i;this.words[r]=s/e|0,i=s%e}return this._strip(),t?this.ineg():this},s.prototype.divn=function(e){return this.clone().idivn(e)},s.prototype.egcd=function(e){n(0===e.negative),n(!e.isZero());var t=this,i=e.clone();t=0!==t.negative?t.umod(e):t.clone();for(var r=new s(1),a=new s(0),o=new s(0),c=new s(1),l=0;t.isEven()&&i.isEven();)t.iushrn(1),i.iushrn(1),++l;for(var u=i.clone(),p=t.clone();!t.isZero();){for(var d=0,f=1;0==(t.words[0]&f)&&d<26;++d,f<<=1);if(d>0)for(t.iushrn(d);d-- >0;)(r.isOdd()||a.isOdd())&&(r.iadd(u),a.isub(p)),r.iushrn(1),a.iushrn(1);for(var h=0,m=1;0==(i.words[0]&m)&&h<26;++h,m<<=1);if(h>0)for(i.iushrn(h);h-- >0;)(o.isOdd()||c.isOdd())&&(o.iadd(u),c.isub(p)),o.iushrn(1),c.iushrn(1);t.cmp(i)>=0?(t.isub(i),r.isub(o),a.isub(c)):(i.isub(t),o.isub(r),c.isub(a))}return{a:o,b:c,gcd:i.iushln(l)}},s.prototype._invmp=function(e){n(0===e.negative),n(!e.isZero());var t=this,i=e.clone();t=0!==t.negative?t.umod(e):t.clone();for(var r,a=new s(1),o=new s(0),c=i.clone();t.cmpn(1)>0&&i.cmpn(1)>0;){for(var l=0,u=1;0==(t.words[0]&u)&&l<26;++l,u<<=1);if(l>0)for(t.iushrn(l);l-- >0;)a.isOdd()&&a.iadd(c),a.iushrn(1);for(var p=0,d=1;0==(i.words[0]&d)&&p<26;++p,d<<=1);if(p>0)for(i.iushrn(p);p-- >0;)o.isOdd()&&o.iadd(c),o.iushrn(1);t.cmp(i)>=0?(t.isub(i),a.isub(o)):(i.isub(t),o.isub(a))}return(r=0===t.cmpn(1)?a:o).cmpn(0)<0&&r.iadd(e),r},s.prototype.gcd=function(e){if(this.isZero())return e.abs();if(e.isZero())return this.abs();var t=this.clone(),i=e.clone();t.negative=0,i.negative=0;for(var n=0;t.isEven()&&i.isEven();n++)t.iushrn(1),i.iushrn(1);for(;;){for(;t.isEven();)t.iushrn(1);for(;i.isEven();)i.iushrn(1);var r=t.cmp(i);if(r<0){var s=t;t=i,i=s}else if(0===r||0===i.cmpn(1))break;t.isub(i)}return i.iushln(n)},s.prototype.invm=function(e){return this.egcd(e).a.umod(e)},s.prototype.isEven=function(){return 0==(1&this.words[0])},s.prototype.isOdd=function(){return 1==(1&this.words[0])},s.prototype.andln=function(e){return this.words[0]&e},s.prototype.bincn=function(e){n("number"==typeof e);var t=e%26,i=(e-t)/26,r=1<>>26,o&=67108863,this.words[a]=o}return 0!==s&&(this.words[a]=s,this.length++),this},s.prototype.isZero=function(){return 1===this.length&&0===this.words[0]},s.prototype.cmpn=function(e){var t,i=e<0;if(0!==this.negative&&!i)return-1;if(0===this.negative&&i)return 1;if(this._strip(),this.length>1)t=1;else{i&&(e=-e),n(e<=67108863,"Number is too big");var r=0|this.words[0];t=r===e?0:re.length)return 1;if(this.length=0;i--){var n=0|this.words[i],r=0|e.words[i];if(n!==r){nr&&(t=1);break}}return t},s.prototype.gtn=function(e){return 1===this.cmpn(e)},s.prototype.gt=function(e){return 1===this.cmp(e)},s.prototype.gten=function(e){return this.cmpn(e)>=0},s.prototype.gte=function(e){return this.cmp(e)>=0},s.prototype.ltn=function(e){return-1===this.cmpn(e)},s.prototype.lt=function(e){return-1===this.cmp(e)},s.prototype.lten=function(e){return this.cmpn(e)<=0},s.prototype.lte=function(e){return this.cmp(e)<=0},s.prototype.eqn=function(e){return 0===this.cmpn(e)},s.prototype.eq=function(e){return 0===this.cmp(e)},s.red=function(e){return new M(e)},s.prototype.toRed=function(e){return n(!this.red,"Already a number in reduction context"),n(0===this.negative,"red works only with positives"),e.convertTo(this)._forceRed(e)},s.prototype.fromRed=function(){return n(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},s.prototype._forceRed=function(e){return this.red=e,this},s.prototype.forceRed=function(e){return n(!this.red,"Already a number in reduction context"),this._forceRed(e)},s.prototype.redAdd=function(e){return n(this.red,"redAdd works only with red numbers"),this.red.add(this,e)},s.prototype.redIAdd=function(e){return n(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,e)},s.prototype.redSub=function(e){return n(this.red,"redSub works only with red numbers"),this.red.sub(this,e)},s.prototype.redISub=function(e){return n(this.red,"redISub works only with red numbers"),this.red.isub(this,e)},s.prototype.redShl=function(e){return n(this.red,"redShl works only with red numbers"),this.red.shl(this,e)},s.prototype.redMul=function(e){return n(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.mul(this,e)},s.prototype.redIMul=function(e){return n(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.imul(this,e)},s.prototype.redSqr=function(){return n(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},s.prototype.redISqr=function(){return n(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},s.prototype.redSqrt=function(){return n(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},s.prototype.redInvm=function(){return n(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},s.prototype.redNeg=function(){return n(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},s.prototype.redPow=function(e){return n(this.red&&!e.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,e)};var _={k256:null,p224:null,p192:null,p25519:null};function x(e,t){this.name=e,this.p=new s(t,16),this.n=this.p.bitLength(),this.k=new s(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}function w(){x.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function k(){x.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function E(){x.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function S(){x.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function M(e){if("string"==typeof e){var t=s._prime(e);this.m=t.p,this.prime=t}else n(e.gtn(1),"modulus must be greater than 1"),this.m=e,this.prime=null}function A(e){M.call(this,e),this.shift=this.m.bitLength(),this.shift%26!=0&&(this.shift+=26-this.shift%26),this.r=new s(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}x.prototype._tmp=function(){var e=new s(null);return e.words=new Array(Math.ceil(this.n/13)),e},x.prototype.ireduce=function(e){var t,i=e;do{this.split(i,this.tmp),t=(i=(i=this.imulK(i)).iadd(this.tmp)).bitLength()}while(t>this.n);var n=t0?i.isub(this.p):void 0!==i.strip?i.strip():i._strip(),i},x.prototype.split=function(e,t){e.iushrn(this.n,0,t)},x.prototype.imulK=function(e){return e.imul(this.k)},r(w,x),w.prototype.split=function(e,t){for(var i=4194303,n=Math.min(e.length,9),r=0;r>>22,s=a}s>>>=22,e.words[r-10]=s,0===s&&e.length>10?e.length-=10:e.length-=9},w.prototype.imulK=function(e){e.words[e.length]=0,e.words[e.length+1]=0,e.length+=2;for(var t=0,i=0;i>>=26,e.words[i]=r,t=n}return 0!==t&&(e.words[e.length++]=t),e},s._prime=function(e){if(_[e])return _[e];var t;if("k256"===e)t=new w;else if("p224"===e)t=new k;else if("p192"===e)t=new E;else{if("p25519"!==e)throw new Error("Unknown prime "+e);t=new S}return _[e]=t,t},M.prototype._verify1=function(e){n(0===e.negative,"red works only with positives"),n(e.red,"red works only with red numbers")},M.prototype._verify2=function(e,t){n(0==(e.negative|t.negative),"red works only with positives"),n(e.red&&e.red===t.red,"red works only with red numbers")},M.prototype.imod=function(e){return this.prime?this.prime.ireduce(e)._forceRed(this):(u(e,e.umod(this.m)._forceRed(this)),e)},M.prototype.neg=function(e){return e.isZero()?e.clone():this.m.sub(e)._forceRed(this)},M.prototype.add=function(e,t){this._verify2(e,t);var i=e.add(t);return i.cmp(this.m)>=0&&i.isub(this.m),i._forceRed(this)},M.prototype.iadd=function(e,t){this._verify2(e,t);var i=e.iadd(t);return i.cmp(this.m)>=0&&i.isub(this.m),i},M.prototype.sub=function(e,t){this._verify2(e,t);var i=e.sub(t);return i.cmpn(0)<0&&i.iadd(this.m),i._forceRed(this)},M.prototype.isub=function(e,t){this._verify2(e,t);var i=e.isub(t);return i.cmpn(0)<0&&i.iadd(this.m),i},M.prototype.shl=function(e,t){return this._verify1(e),this.imod(e.ushln(t))},M.prototype.imul=function(e,t){return this._verify2(e,t),this.imod(e.imul(t))},M.prototype.mul=function(e,t){return this._verify2(e,t),this.imod(e.mul(t))},M.prototype.isqr=function(e){return this.imul(e,e.clone())},M.prototype.sqr=function(e){return this.mul(e,e)},M.prototype.sqrt=function(e){if(e.isZero())return e.clone();var t=this.m.andln(3);if(n(t%2==1),3===t){var i=this.m.add(new s(1)).iushrn(2);return this.pow(e,i)}for(var r=this.m.subn(1),a=0;!r.isZero()&&0===r.andln(1);)a++,r.iushrn(1);n(!r.isZero());var o=new s(1).toRed(this),c=o.redNeg(),l=this.m.subn(1).iushrn(1),u=this.m.bitLength();for(u=new s(2*u*u).toRed(this);0!==this.pow(u,l).cmp(c);)u.redIAdd(c);for(var p=this.pow(u,r),d=this.pow(e,r.addn(1).iushrn(1)),f=this.pow(e,r),h=a;0!==f.cmp(o);){for(var m=f,b=0;0!==m.cmp(o);b++)m=m.redSqr();n(b=0;n--){for(var l=t.words[n],u=c-1;u>=0;u--){var p=l>>u&1;r!==i[0]&&(r=this.sqr(r)),0!==p||0!==a?(a<<=1,a|=p,(4===++o||0===n&&0===u)&&(r=this.mul(r,i[a]),o=0,a=0)):o=0}c=26}return r},M.prototype.convertTo=function(e){var t=e.umod(this.m);return t===e?t.clone():t},M.prototype.convertFrom=function(e){var t=e.clone();return t.red=null,t},s.mont=function(e){return new A(e)},r(A,M),A.prototype.convertTo=function(e){return this.imod(e.ushln(this.shift))},A.prototype.convertFrom=function(e){var t=this.imod(e.mul(this.rinv));return t.red=null,t},A.prototype.imul=function(e,t){if(e.isZero()||t.isZero())return e.words[0]=0,e.length=1,e;var i=e.imul(t),n=i.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),r=i.isub(n).iushrn(this.shift),s=r;return r.cmp(this.m)>=0?s=r.isub(this.m):r.cmpn(0)<0&&(s=r.iadd(this.m)),s._forceRed(this)},A.prototype.mul=function(e,t){if(e.isZero()||t.isZero())return new s(0)._forceRed(this);var i=e.mul(t),n=i.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),r=i.isub(n).iushrn(this.shift),a=r;return r.cmp(this.m)>=0?a=r.isub(this.m):r.cmpn(0)<0&&(a=r.iadd(this.m)),a._forceRed(this)},A.prototype.invm=function(e){return this.imod(e._invmp(this.m).mul(this.r2))._forceRed(this)}}(void 0===t||t,this)},{buffer:66}],65:[function(e,t,i){var n;function r(e){this.rand=e}if(t.exports=function(e){return n||(n=new r(null)),n.generate(e)},t.exports.Rand=r,r.prototype.generate=function(e){return this._rand(e)},r.prototype._rand=function(e){if(this.rand.getBytes)return this.rand.getBytes(e);for(var t=new Uint8Array(e),i=0;i>>24]^u[h>>>16&255]^p[m>>>8&255]^d[255&b]^t[v++],a=l[h>>>24]^u[m>>>16&255]^p[b>>>8&255]^d[255&f]^t[v++],o=l[m>>>24]^u[b>>>16&255]^p[f>>>8&255]^d[255&h]^t[v++],c=l[b>>>24]^u[f>>>16&255]^p[h>>>8&255]^d[255&m]^t[v++],f=s,h=a,m=o,b=c;return s=(n[f>>>24]<<24|n[h>>>16&255]<<16|n[m>>>8&255]<<8|n[255&b])^t[v++],a=(n[h>>>24]<<24|n[m>>>16&255]<<16|n[b>>>8&255]<<8|n[255&f])^t[v++],o=(n[m>>>24]<<24|n[b>>>16&255]<<16|n[f>>>8&255]<<8|n[255&h])^t[v++],c=(n[b>>>24]<<24|n[f>>>16&255]<<16|n[h>>>8&255]<<8|n[255&m])^t[v++],[s>>>=0,a>>>=0,o>>>=0,c>>>=0]}var o=[0,1,2,4,8,16,32,64,128,27,54],c=function(){for(var e=new Array(256),t=0;t<256;t++)e[t]=t<128?t<<1:t<<1^283;for(var i=[],n=[],r=[[],[],[],[]],s=[[],[],[],[]],a=0,o=0,c=0;c<256;++c){var l=o^o<<1^o<<2^o<<3^o<<4;l=l>>>8^255&l^99,i[a]=l,n[l]=a;var u=e[a],p=e[u],d=e[p],f=257*e[l]^16843008*l;r[0][a]=f<<24|f>>>8,r[1][a]=f<<16|f>>>16,r[2][a]=f<<8|f>>>24,r[3][a]=f,f=16843009*d^65537*p^257*u^16843008*a,s[0][l]=f<<24|f>>>8,s[1][l]=f<<16|f>>>16,s[2][l]=f<<8|f>>>24,s[3][l]=f,0===a?a=o=1:(a=u^e[e[e[d^u]]],o^=e[e[o]])}return{SBOX:i,INV_SBOX:n,SUB_MIX:r,INV_SUB_MIX:s}}();function l(e){this._key=r(e),this._reset()}l.blockSize=16,l.keySize=32,l.prototype.blockSize=l.blockSize,l.prototype.keySize=l.keySize,l.prototype._reset=function(){for(var e=this._key,t=e.length,i=t+6,n=4*(i+1),r=[],s=0;s>>24,a=c.SBOX[a>>>24]<<24|c.SBOX[a>>>16&255]<<16|c.SBOX[a>>>8&255]<<8|c.SBOX[255&a],a^=o[s/t|0]<<24):t>6&&s%t==4&&(a=c.SBOX[a>>>24]<<24|c.SBOX[a>>>16&255]<<16|c.SBOX[a>>>8&255]<<8|c.SBOX[255&a]),r[s]=r[s-t]^a}for(var l=[],u=0;u>>24]]^c.INV_SUB_MIX[1][c.SBOX[d>>>16&255]]^c.INV_SUB_MIX[2][c.SBOX[d>>>8&255]]^c.INV_SUB_MIX[3][c.SBOX[255&d]]}this._nRounds=i,this._keySchedule=r,this._invKeySchedule=l},l.prototype.encryptBlockRaw=function(e){return a(e=r(e),this._keySchedule,c.SUB_MIX,c.SBOX,this._nRounds)},l.prototype.encryptBlock=function(e){var t=this.encryptBlockRaw(e),i=n.allocUnsafe(16);return i.writeUInt32BE(t[0],0),i.writeUInt32BE(t[1],4),i.writeUInt32BE(t[2],8),i.writeUInt32BE(t[3],12),i},l.prototype.decryptBlock=function(e){var t=(e=r(e))[1];e[1]=e[3],e[3]=t;var i=a(e,this._invKeySchedule,c.INV_SUB_MIX,c.INV_SBOX,this._nRounds),s=n.allocUnsafe(16);return s.writeUInt32BE(i[0],0),s.writeUInt32BE(i[3],4),s.writeUInt32BE(i[2],8),s.writeUInt32BE(i[1],12),s},l.prototype.scrub=function(){s(this._keySchedule),s(this._invKeySchedule),s(this._key)},t.exports.AES=l},{"safe-buffer":382}],68:[function(e,t,i){var n=e("./aes"),r=e("safe-buffer").Buffer,s=e("cipher-base"),a=e("inherits"),o=e("./ghash"),c=e("buffer-xor"),l=e("./incr32");function u(e,t,i,a){s.call(this);var c=r.alloc(4,0);this._cipher=new n.AES(t);var u=this._cipher.encryptBlock(c);this._ghash=new o(u),i=function(e,t,i){if(12===t.length)return e._finID=r.concat([t,r.from([0,0,0,1])]),r.concat([t,r.from([0,0,0,2])]);var n=new o(i),s=t.length,a=s%16;n.update(t),a&&(a=16-a,n.update(r.alloc(a,0))),n.update(r.alloc(8,0));var c=8*s,u=r.alloc(8);u.writeUIntBE(c,0,8),n.update(u),e._finID=n.state;var p=r.from(e._finID);return l(p),p}(this,i,u),this._prev=r.from(i),this._cache=r.allocUnsafe(0),this._secCache=r.allocUnsafe(0),this._decrypt=a,this._alen=0,this._len=0,this._mode=e,this._authTag=null,this._called=!1}a(u,s),u.prototype._update=function(e){if(!this._called&&this._alen){var t=16-this._alen%16;t<16&&(t=r.alloc(t,0),this._ghash.update(t))}this._called=!0;var i=this._mode.encrypt(this,e);return this._decrypt?this._ghash.update(e):this._ghash.update(i),this._len+=e.length,i},u.prototype._final=function(){if(this._decrypt&&!this._authTag)throw new Error("Unsupported state or unable to authenticate data");var e=c(this._ghash.final(8*this._alen,8*this._len),this._cipher.encryptBlock(this._finID));if(this._decrypt&&function(e,t){var i=0;e.length!==t.length&&i++;for(var n=Math.min(e.length,t.length),r=0;r16)throw new Error("unable to decrypt data");var i=-1;for(;++i16)return t=this.cache.slice(0,16),this.cache=this.cache.slice(16),t}else if(this.cache.length>=16)return t=this.cache.slice(0,16),this.cache=this.cache.slice(16),t;return null},p.prototype.flush=function(){if(this.cache.length)return this.cache},i.createDecipher=function(e,t){var i=s[e.toLowerCase()];if(!i)throw new TypeError("invalid suite type");var n=l(t,!1,i.key,i.iv);return d(e,n.key,n.iv)},i.createDecipheriv=d},{"./aes":67,"./authCipher":68,"./modes":80,"./streamCipher":83,"cipher-base":133,evp_bytestokey:193,inherits:245,"safe-buffer":382}],71:[function(e,t,i){var n=e("./modes"),r=e("./authCipher"),s=e("safe-buffer").Buffer,a=e("./streamCipher"),o=e("cipher-base"),c=e("./aes"),l=e("evp_bytestokey");function u(e,t,i){o.call(this),this._cache=new d,this._cipher=new c.AES(t),this._prev=s.from(i),this._mode=e,this._autopadding=!0}e("inherits")(u,o),u.prototype._update=function(e){var t,i;this._cache.add(e);for(var n=[];t=this._cache.get();)i=this._mode.encrypt(this,t),n.push(i);return s.concat(n)};var p=s.alloc(16,16);function d(){this.cache=s.allocUnsafe(0)}function f(e,t,i){var o=n[e.toLowerCase()];if(!o)throw new TypeError("invalid suite type");if("string"==typeof t&&(t=s.from(t)),t.length!==o.key/8)throw new TypeError("invalid key length "+t.length);if("string"==typeof i&&(i=s.from(i)),"GCM"!==o.mode&&i.length!==o.iv)throw new TypeError("invalid iv length "+i.length);return"stream"===o.type?new a(o.module,t,i):"auth"===o.type?new r(o.module,t,i):new u(o.module,t,i)}u.prototype._final=function(){var e=this._cache.flush();if(this._autopadding)return e=this._mode.encrypt(this,e),this._cipher.scrub(),e;if(!e.equals(p))throw this._cipher.scrub(),new Error("data not multiple of block length")},u.prototype.setAutoPadding=function(e){return this._autopadding=!!e,this},d.prototype.add=function(e){this.cache=s.concat([this.cache,e])},d.prototype.get=function(){if(this.cache.length>15){var e=this.cache.slice(0,16);return this.cache=this.cache.slice(16),e}return null},d.prototype.flush=function(){for(var e=16-this.cache.length,t=s.allocUnsafe(e),i=-1;++i>>0,0),t.writeUInt32BE(e[1]>>>0,4),t.writeUInt32BE(e[2]>>>0,8),t.writeUInt32BE(e[3]>>>0,12),t}function a(e){this.h=e,this.state=n.alloc(16,0),this.cache=n.allocUnsafe(0)}a.prototype.ghash=function(e){for(var t=-1;++t0;t--)n[t]=n[t]>>>1|(1&n[t-1])<<31;n[0]=n[0]>>>1,i&&(n[0]=n[0]^225<<24)}this.state=s(r)},a.prototype.update=function(e){var t;for(this.cache=n.concat([this.cache,e]);this.cache.length>=16;)t=this.cache.slice(0,16),this.cache=this.cache.slice(16),this.ghash(t)},a.prototype.final=function(e,t){return this.cache.length&&this.ghash(n.concat([this.cache,r],16)),this.ghash(s([0,e,0,t])),this.state},t.exports=a},{"safe-buffer":382}],73:[function(e,t,i){t.exports=function(e){for(var t,i=e.length;i--;){if(255!==(t=e.readUInt8(i))){t++,e.writeUInt8(t,i);break}e.writeUInt8(0,i)}}},{}],74:[function(e,t,i){var n=e("buffer-xor");i.encrypt=function(e,t){var i=n(t,e._prev);return e._prev=e._cipher.encryptBlock(i),e._prev},i.decrypt=function(e,t){var i=e._prev;e._prev=t;var r=e._cipher.decryptBlock(t);return n(r,i)}},{"buffer-xor":113}],75:[function(e,t,i){var n=e("safe-buffer").Buffer,r=e("buffer-xor");function s(e,t,i){var s=t.length,a=r(t,e._cache);return e._cache=e._cache.slice(s),e._prev=n.concat([e._prev,i?t:a]),a}i.encrypt=function(e,t,i){for(var r,a=n.allocUnsafe(0);t.length;){if(0===e._cache.length&&(e._cache=e._cipher.encryptBlock(e._prev),e._prev=n.allocUnsafe(0)),!(e._cache.length<=t.length)){a=n.concat([a,s(e,t,i)]);break}r=e._cache.length,a=n.concat([a,s(e,t.slice(0,r),i)]),t=t.slice(r)}return a}},{"buffer-xor":113,"safe-buffer":382}],76:[function(e,t,i){var n=e("safe-buffer").Buffer;function r(e,t,i){for(var n,r,a=-1,o=0;++a<8;)n=t&1<<7-a?128:0,o+=(128&(r=e._cipher.encryptBlock(e._prev)[0]^n))>>a%8,e._prev=s(e._prev,i?n:r);return o}function s(e,t){var i=e.length,r=-1,s=n.allocUnsafe(e.length);for(e=n.concat([e,n.from([t])]);++r>7;return s}i.encrypt=function(e,t,i){for(var s=t.length,a=n.allocUnsafe(s),o=-1;++o=0||!t.umod(e.prime1)||!t.umod(e.prime2));return t}function a(e,t){var r=function(e){var t=s(e);return{blinder:t.toRed(n.mont(e.modulus)).redPow(new n(e.publicExponent)).fromRed(),unblinder:t.invm(e.modulus)}}(t),a=t.modulus.byteLength(),o=new n(e).mul(r.blinder).umod(t.modulus),c=o.toRed(n.mont(t.prime1)),l=o.toRed(n.mont(t.prime2)),u=t.coefficient,p=t.prime1,d=t.prime2,f=c.redPow(t.exponent1).fromRed(),h=l.redPow(t.exponent2).fromRed(),m=f.isub(h).imul(u).umod(p).imul(d);return h.iadd(m).imul(r.unblinder).umod(t.modulus).toArrayLike(i,"be",a)}a.getr=s,t.exports=a}).call(this)}).call(this,e("buffer").Buffer)},{"bn.js":64,buffer:109,randombytes:356}],88:[function(e,t,i){t.exports=e("./browser/algorithms.json")},{"./browser/algorithms.json":89}],89:[function(e,t,i){t.exports={sha224WithRSAEncryption:{sign:"rsa",hash:"sha224",id:"302d300d06096086480165030402040500041c"},"RSA-SHA224":{sign:"ecdsa/rsa",hash:"sha224",id:"302d300d06096086480165030402040500041c"},sha256WithRSAEncryption:{sign:"rsa",hash:"sha256",id:"3031300d060960864801650304020105000420"},"RSA-SHA256":{sign:"ecdsa/rsa",hash:"sha256",id:"3031300d060960864801650304020105000420"},sha384WithRSAEncryption:{sign:"rsa",hash:"sha384",id:"3041300d060960864801650304020205000430"},"RSA-SHA384":{sign:"ecdsa/rsa",hash:"sha384",id:"3041300d060960864801650304020205000430"},sha512WithRSAEncryption:{sign:"rsa",hash:"sha512",id:"3051300d060960864801650304020305000440"},"RSA-SHA512":{sign:"ecdsa/rsa",hash:"sha512",id:"3051300d060960864801650304020305000440"},"RSA-SHA1":{sign:"rsa",hash:"sha1",id:"3021300906052b0e03021a05000414"},"ecdsa-with-SHA1":{sign:"ecdsa",hash:"sha1",id:""},sha256:{sign:"ecdsa",hash:"sha256",id:""},sha224:{sign:"ecdsa",hash:"sha224",id:""},sha384:{sign:"ecdsa",hash:"sha384",id:""},sha512:{sign:"ecdsa",hash:"sha512",id:""},"DSA-SHA":{sign:"dsa",hash:"sha1",id:""},"DSA-SHA1":{sign:"dsa",hash:"sha1",id:""},DSA:{sign:"dsa",hash:"sha1",id:""},"DSA-WITH-SHA224":{sign:"dsa",hash:"sha224",id:""},"DSA-SHA224":{sign:"dsa",hash:"sha224",id:""},"DSA-WITH-SHA256":{sign:"dsa",hash:"sha256",id:""},"DSA-SHA256":{sign:"dsa",hash:"sha256",id:""},"DSA-WITH-SHA384":{sign:"dsa",hash:"sha384",id:""},"DSA-SHA384":{sign:"dsa",hash:"sha384",id:""},"DSA-WITH-SHA512":{sign:"dsa",hash:"sha512",id:""},"DSA-SHA512":{sign:"dsa",hash:"sha512",id:""},"DSA-RIPEMD160":{sign:"dsa",hash:"rmd160",id:""},ripemd160WithRSA:{sign:"rsa",hash:"rmd160",id:"3021300906052b2403020105000414"},"RSA-RIPEMD160":{sign:"rsa",hash:"rmd160",id:"3021300906052b2403020105000414"},md5WithRSAEncryption:{sign:"rsa",hash:"md5",id:"3020300c06082a864886f70d020505000410"},"RSA-MD5":{sign:"rsa",hash:"md5",id:"3020300c06082a864886f70d020505000410"}}},{}],90:[function(e,t,i){t.exports={"1.3.132.0.10":"secp256k1","1.3.132.0.33":"p224","1.2.840.10045.3.1.1":"p192","1.2.840.10045.3.1.7":"p256","1.3.132.0.34":"p384","1.3.132.0.35":"p521"}},{}],91:[function(e,t,i){var n=e("safe-buffer").Buffer,r=e("create-hash"),s=e("readable-stream"),a=e("inherits"),o=e("./sign"),c=e("./verify"),l=e("./algorithms.json");function u(e){s.Writable.call(this);var t=l[e];if(!t)throw new Error("Unknown message digest");this._hashType=t.hash,this._hash=r(t.hash),this._tag=t.id,this._signType=t.sign}function p(e){s.Writable.call(this);var t=l[e];if(!t)throw new Error("Unknown message digest");this._hash=r(t.hash),this._tag=t.id,this._signType=t.sign}function d(e){return new u(e)}function f(e){return new p(e)}Object.keys(l).forEach((function(e){l[e].id=n.from(l[e].id,"hex"),l[e.toLowerCase()]=l[e]})),a(u,s.Writable),u.prototype._write=function(e,t,i){this._hash.update(e),i()},u.prototype.update=function(e,t){return"string"==typeof e&&(e=n.from(e,t)),this._hash.update(e),this},u.prototype.sign=function(e,t){this.end();var i=this._hash.digest(),n=o(i,e,this._hashType,this._signType,this._tag);return t?n.toString(t):n},a(p,s.Writable),p.prototype._write=function(e,t,i){this._hash.update(e),i()},p.prototype.update=function(e,t){return"string"==typeof e&&(e=n.from(e,t)),this._hash.update(e),this},p.prototype.verify=function(e,t,i){"string"==typeof t&&(t=n.from(t,i)),this.end();var r=this._hash.digest();return c(t,r,e,this._signType,this._tag)},t.exports={Sign:d,Verify:f,createSign:d,createVerify:f}},{"./algorithms.json":89,"./sign":92,"./verify":93,"create-hash":139,inherits:245,"readable-stream":108,"safe-buffer":382}],92:[function(e,t,i){var n=e("safe-buffer").Buffer,r=e("create-hmac"),s=e("browserify-rsa"),a=e("elliptic").ec,o=e("bn.js"),c=e("parse-asn1"),l=e("./curves.json");function u(e,t,i,s){if((e=n.from(e.toArray())).length0&&i.ishrn(n),i}function d(e,t,i){var s,a;do{for(s=n.alloc(0);8*s.length=t)throw new Error("invalid sig")}t.exports=function(e,t,i,l,u){var p=a(i);if("ec"===p.type){if("ecdsa"!==l&&"ecdsa/rsa"!==l)throw new Error("wrong public key type");return function(e,t,i){var n=o[i.data.algorithm.curve.join(".")];if(!n)throw new Error("unknown curve "+i.data.algorithm.curve.join("."));var r=new s(n),a=i.data.subjectPrivateKey.data;return r.verify(t,e,a)}(e,t,p)}if("dsa"===p.type){if("dsa"!==l)throw new Error("wrong public key type");return function(e,t,i){var n=i.data.p,s=i.data.q,o=i.data.g,l=i.data.pub_key,u=a.signature.decode(e,"der"),p=u.s,d=u.r;c(p,s),c(d,s);var f=r.mont(n),h=p.invm(s);return 0===o.toRed(f).redPow(new r(t).mul(h).mod(s)).fromRed().mul(l.toRed(f).redPow(d.mul(h).mod(s)).fromRed()).mod(n).mod(s).cmp(d)}(e,t,p)}if("rsa"!==l&&"ecdsa/rsa"!==l)throw new Error("wrong public key type");t=n.concat([u,t]);for(var d=p.modulus.byteLength(),f=[1],h=0;t.length+f.length+2 */ const{EventEmitter:n}=e("events"),r=e("bencode"),s=e("bitfield").default,a=e("debug")("ut_metadata"),o=e("simple-sha1"),c=16384;t.exports=e=>{class t extends n{constructor(t){super(),this._wire=t,this._fetching=!1,this._metadataComplete=!1,this._metadataSize=null,this._remainingRejects=null,this._bitfield=new s(0,{grow:1e3}),i.isBuffer(e)&&this.setMetadata(e)}onHandshake(e,t,i){this._infoHash=e}onExtendedHandshake(e){return e.m&&e.m.ut_metadata?e.metadata_size?"number"!=typeof e.metadata_size||1e7this._metadataSize&&(i=this._metadataSize);const n=this.metadata.slice(t,i);this._data(e,n,this._metadataSize)}_onData(e,t,i){t.length>c||!this._fetching||(t.copy(this.metadata,e*c),this._bitfield.set(e),this._checkDone())}_onReject(e){this._remainingRejects>0&&this._fetching?(this._request(e),this._remainingRejects-=1):this.emit("warning",new Error('Peer sent "reject" too much'))}_requestPieces(){if(this._fetching){this.metadata=i.alloc(this._metadataSize);for(let e=0;e0?this._requestPieces():this.emit("warning",new Error("Peer sent invalid metadata"))}}return t.prototype.name="ut_metadata",t}}).call(this)}).call(this,e("buffer").Buffer)},{bencode:22,bitfield:26,buffer:109,debug:160,events:192,"simple-sha1":410}],485:[function(e,t,i){(function(e){(function(){function i(t){try{if(!e.localStorage)return!1}catch(e){return!1}var i=e.localStorage[t];return null!=i&&"true"===String(i).toLowerCase()}t.exports=function(e,t){if(i("noDeprecation"))return e;var n=!1;return function(){if(!n){if(i("throwDeprecation"))throw new Error(t);i("traceDeprecation")?console.trace(t):console.warn(t),n=!0}return e.apply(this,arguments)}}}).call(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],486:[function(e,t,i){(function(i){(function(){const n=e("binary-search"),r=e("events"),s=e("mp4-stream"),a=e("mp4-box-encoding"),o=e("range-slice-stream");class c{constructor(e,t){this._entries=e,this._countName=t||"count",this._index=0,this._offset=0,this.value=this._entries[0]}inc(){this._offset++,this._offset>=this._entries[this._index][this._countName]&&(this._index++,this._offset=0),this.value=this._entries[this._index]}}const l=1;t.exports=class extends r{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 i=this._file.createReadStream({start:e});i.pipe(this._decoder);const n=r=>{"moov"===r.type?(this._decoder.removeListener("box",n),this._decoder.decode((e=>{i.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()):(this._decoder.removeListener("box",n),t+=r.length,i.destroy(),this._decoder.destroy(),this._findMoov(e+t))};this._decoder.on("box",n)}_processMoov(e){const t=e.traks;this._tracks=[],this._hasVideo=!1,this._hasAudio=!1;for(let i=0;i=s.stsz.entries.length)break;if(f++,m+=e,f>=n.samplesPerChunk){f=0,m=0,h++;const e=s.stsc.entries[b+1];e&&h+1>=e.firstChunk&&b++}v+=t,g.inc(),y&&y.inc(),r&&_++}r.mdia.mdhd.duration=0,r.tkhd.duration=0;const x=n.sampleDescriptionId,w={type:"moov",mvhd:e.mvhd,traks:[{tkhd:r.tkhd,mdia:{mdhd:r.mdia.mdhd,hdlr:r.mdia.hdlr,elng:r.mdia.elng,minf:{vmhd:r.mdia.minf.vmhd,smhd:r.mdia.minf.smhd,dinf:r.mdia.minf.dinf,stbl:{stsd:s.stsd,stts:{version:0,flags:0,entries:[]},ctts:{version:0,flags:0,entries:[]},stsc:{version:0,flags:0,entries:[]},stsz:{version:0,flags:0,entries:[]},stco:{version:0,flags:0,entries:[]},stss:{version:0,flags:0,entries:[]}}}}}],mvex:{mehd:{fragmentDuration:e.mvhd.duration},trexs:[{trackId:r.tkhd.trackId,defaultSampleDescriptionIndex:x,defaultSampleDuration:0,defaultSampleSize:0,defaultSampleFlags:0}]}};this._tracks.push({fragmentSequence:1,trackId:r.tkhd.trackId,timeScale:r.mdia.mdhd.timeScale,samples:p,currSample:null,currTime:null,moov:w,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 r=a.encode(this._ftyp),s=this._tracks.map((e=>{const t=a.encode(e.moov);return{mime:e.mime,init:i.concat([r,t])}}));this.emit("ready",s)}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(((i,n)=>{i.outStream&&i.outStream.destroy(),i.inStream&&(i.inStream.destroy(),i.inStream=null);const r=i.outStream=s.encode(),a=this._generateFragment(n,e);if(!a)return r.finalize();(-1===t||a.ranges[0].start{r.destroyed||r.box(e.moof,(t=>{if(t)return this.emit("error",t);if(r.destroyed)return;i.inStream.slice(e.ranges).pipe(r.mediaData(e.length,(e=>{if(e)return this.emit("error",e);if(r.destroyed)return;const t=this._generateFragment(n);if(!t)return r.finalize();o(t)})))}))};o(a)})),t>=0){const e=this._fileStream=this._file.createReadStream({start:t});this._tracks.forEach((i=>{i.inStream=new o(t,{highWaterMark:1e7}),e.pipe(i.inStream)}))}return this._tracks.map((e=>e.outStream))}_findSampleBefore(e,t){const i=this._tracks[e],r=Math.floor(i.timeScale*t);let s=n(i.samples,r,((e,t)=>e.dts+e.presentationOffset-t));for(-1===s?s=0:s<0&&(s=-s-2);!i.samples[s].sync;)s--;return s}_generateFragment(e,t){const i=this._tracks[e];let n;if(n=void 0!==t?this._findSampleBefore(e,t):i.currSample,n>=i.samples.length)return null;const r=i.samples[n].dts;let s=0;const a=[];for(var o=n;o=i.timeScale*l)break;s+=e.size;const t=a.length-1;t<0||a[t].end!==e.offset?a.push({start:e.offset,end:e.offset+e.size}):a[t].end+=e.size}return i.currSample=o,{moof:this._generateMoof(e,n,o),ranges:a,length:s}}_generateMoof(e,t,i){const n=this._tracks[e],r=[];let s=0;for(let e=t;e{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)}a.prototype={_createMuxer(){this._muxer=new s(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 i={muxed:null,mediaSource:t,initFlushed:!1,onInitFlushed:null};return t.write(e.init,(e=>{i.initFlushed=!0,i.onInitFlushed&&i.onInitFlushed(e)})),i})),(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,i)=>{const n=()=>{t.muxed&&(t.muxed.destroy(),t.mediaSource=this._elemWrapper.createWriteStream(t.mediaSource),t.mediaSource.on("error",(e=>{this._elemWrapper.error(e)}))),t.muxed=e[i],r(t.muxed,t.mediaSource)};t.initFlushed?n():t.onInitFlushed=e=>{e?this._elemWrapper.error(e):n()}}))},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=a},{"./mp4-remuxer":486,mediasource:258,pump:348}],488:[function(e,t,i){(function(i){(function(){ /*! webtorrent. MIT License. WebTorrent LLC */ -const n=e("events"),r=e("path"),s=e("simple-concat"),a=e("create-torrent"),o=e("debug"),c=e("bittorrent-dht/client"),l=e("load-ip-set"),u=e("run-parallel"),p=e("parse-torrent"),d=e("simple-peer"),f=e("queue-microtask"),h=e("randombytes"),m=e("simple-sha1"),b=e("throughput"),{ThrottleGroup:v}=e("speed-limiter"),g=e("./lib/conn-pool.js"),y=e("./lib/torrent.js"),{version:_}=e("./package.json"),x=o("webtorrent"),w=_.replace(/\d*./g,(e=>("0"+e%100).slice(-2))).slice(0,4),k=`-WW${w}-`;class E extends n{constructor(t={}){super(),"string"==typeof t.peerId?this.peerId=t.peerId:i.isBuffer(t.peerId)?this.peerId=t.peerId.toString("hex"):this.peerId=i.from(k+h(9).toString("base64")).toString("hex"),this.peerIdBuffer=i.from(this.peerId,"hex"),"string"==typeof t.nodeId?this.nodeId=t.nodeId:i.isBuffer(t.nodeId)?this.nodeId=t.nodeId.toString("hex"):this.nodeId=h(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=t.torrentPort||0,this.dhtPort=t.dhtPort||0,this.tracker=void 0!==t.tracker?t.tracker:{},this.lsd=!1!==t.lsd,this.torrents=[],this.maxConns=Number(t.maxConns)||55,this.utp=E.UTP_SUPPORT&&!1!==t.utp,this._downloadLimit=Math.max("number"==typeof t.downloadLimit?t.downloadLimit:-1,-1),this._uploadLimit=Math.max("number"==typeof t.uploadLimit?t.uploadLimit:-1,-1),this.serviceWorker=null,this.workerKeepAliveInterval=null,this.workerPortCount=0,!0===t.secure&&e("./lib/peer").enableSecure(),this._debug("new webtorrent (peerId %s, nodeId %s, port %s)",this.peerId,this.nodeId,this.torrentPort),this.throttleGroups={down:new v({rate:Math.max(this._downloadLimit,0),enabled:this._downloadLimit>=0}),up:new v({rate:Math.max(this._uploadLimit,0),enabled:this._uploadLimit>=0})},this.tracker&&("object"!=typeof this.tracker&&(this.tracker={}),globalThis.WRTC&&!this.tracker.wrtc&&(this.tracker.wrtc=globalThis.WRTC)),"function"==typeof g?this._connPool=new g(this):f((()=>{this._onListening()})),this._downloadSpeed=b(),this._uploadSpeed=b(),!1!==t.dht&&"function"==typeof c?(this.dht=new c(Object.assign({},{nodeId:this.nodeId},t.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!==t.webSeeds;const n=()=>{this.destroyed||(this.ready=!0,this.emit("ready"))};"function"==typeof l&&null!=t.blocklist?l(t.blocklist,{headers:{"user-agent":`WebTorrent/${_} (https://webtorrent.io)`}},((e,t)=>{if(e)return console.error(`Failed to load blocklist: ${e.message}`);this.blocked=t,n()})):f(n)}loadWorker(e,t=(()=>{})){if(!(e instanceof ServiceWorker))throw new Error("Invalid worker registration");if("activated"!==e.state)throw new Error("Worker isn't activated");this.serviceWorker=e,navigator.serviceWorker.addEventListener("message",(e=>{const{data:t}=e;if(!t.type||"webtorrent"===!t.type||!t.url)return null;let[i,...n]=t.url.slice(t.url.indexOf(t.scope+"webtorrent/")+11+t.scope.length).split("/");if(n=decodeURI(n.join("/")),!i||!n)return null;const[r]=e.ports,s=this.get(i)&&this.get(i).files.find((e=>e.path===n));if(!s)return null;const[a,o,c]=s._serve(t),l=o&&o[Symbol.asyncIterator](),u=()=>{r.onmessage=null,o&&o.destroy(),c&&c.destroy(),this.workerPortCount--,this.workerPortCount||(clearInterval(this.workerKeepAliveInterval),this.workerKeepAliveInterval=null)};r.onmessage=async e=>{if(e.data){let e;try{e=(await l.next()).value}catch(e){}r.postMessage(e),e||u(),this.workerKeepAliveInterval||(this.workerKeepAliveInterval=setInterval((()=>fetch(`${this.serviceWorker.scriptURL.slice(0,this.serviceWorker.scriptURL.lastIndexOf("/")+1).slice(window.location.origin.length)}webtorrent/keepalive/`)),2e4))}else u()},this.workerPortCount++,r.postMessage(a)})),t(this.serviceWorker)}get downloadSpeed(){return this._downloadSpeed()}get uploadSpeed(){return this._uploadSpeed()}get progress(){const e=this.torrents.filter((e=>1!==e.progress));return e.reduce(((e,t)=>e+t.downloaded),0)/(e.reduce(((e,t)=>e+(t.length||0)),0)||1)}get ratio(){return this.torrents.reduce(((e,t)=>e+t.uploaded),0)/(this.torrents.reduce(((e,t)=>e+t.received),0)||1)}get(e){if(e instanceof y){if(this.torrents.includes(e))return e}else{let t;try{t=p(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}return null}add(e,t={},i=(()=>{})){if(this.destroyed)throw new Error("client is destroyed");"function"==typeof t&&([t,i]=[{},t]);const n=()=>{if(!this.destroyed)for(const e of this.torrents)if(e.infoHash===s.infoHash&&e!==s)return void s._destroy(new Error(`Cannot add duplicate torrent ${s.infoHash}`))},r=()=>{this.destroyed||(i(s),this.emit("torrent",s))};this._debug("add"),t=t?Object.assign({},t):{};const s=new y(e,this,t);return this.torrents.push(s),s.once("_infoHash",n),s.once("ready",r),s.once("close",(function e(){s.removeListener("_infoHash",n),s.removeListener("ready",r),s.removeListener("close",e)})),s}seed(e,t,i){if(this.destroyed)throw new Error("client is destroyed");"function"==typeof t&&([t,i]=[{},t]),this._debug("seed"),(t=t?Object.assign({},t):{}).skipVerify=!0;const n="string"==typeof e;n&&(t.path=r.dirname(e)),t.createdBy||(t.createdBy=`WebTorrent/${w}`);const o=e=>{this._debug("on seed"),"function"==typeof i&&i(e),e.emit("seed"),this.emit("seed",e)},c=this.add(null,t,(e=>{const i=[i=>{if(n||t.preloadedStore)return i();e.load(l,i)}];this.dht&&i.push((t=>{e.once("dhtAnnounce",t)})),u(i,(t=>{if(!this.destroyed)return t?e._destroy(t):void o(e)}))}));let l;var p;return p=e,"undefined"!=typeof FileList&&p instanceof FileList?e=Array.from(e):Array.isArray(e)||(e=[e]),u(e.map((e=>i=>{!t.preloadedStore&&function(e){return"object"==typeof e&&null!=e&&"function"==typeof e.pipe}(e)?s(e,((t,n)=>{if(t)return i(t);n.name=e.name,i(null,n)})):i(null,e)})),((e,n)=>{if(!this.destroyed)return e?c._destroy(e):void a.parseInput(n,t,((e,r)=>{if(!this.destroyed){if(e)return c._destroy(e);l=r.map((e=>e.getStream)),a(n,t,((e,t)=>{if(this.destroyed)return;if(e)return c._destroy(e);const n=this.get(t);n?(console.warn("A torrent with the same id is already being seeded"),c._destroy(),"function"==typeof i&&i(n)):c._onTorrentId(t)}))}}))})),c}remove(e,t,i){if("function"==typeof t)return this.remove(e,null,t);this._debug("remove");if(!this.get(e))throw new Error(`No torrent with id ${e}`);this._remove(e,t,i)}_remove(e,t,i){if("function"==typeof t)return this._remove(e,null,t);const n=this.get(e);n&&(this.torrents.splice(this.torrents.indexOf(n),1),n.destroy(t,i),this.dht&&this.dht._tables.remove(n.infoHash))}address(){return this.listening?this._connPool?this._connPool.tcpServer.address():{address:"0.0.0.0",family:"IPv4",port:0}:null}throttleDownload(e){return e=Number(e),!(isNaN(e)||!isFinite(e)||e<-1)&&(this._downloadLimit=e,this._downloadLimit<0?this.throttleGroups.down.setEnabled(!1):(this.throttleGroups.down.setEnabled(!0),void this.throttleGroups.down.setRate(this._downloadLimit)))}throttleUpload(e){return e=Number(e),!(isNaN(e)||!isFinite(e)||e<-1)&&(this._uploadLimit=e,this._uploadLimit<0?this.throttleGroups.up.setEnabled(!1):(this.throttleGroups.up.setEnabled(!0),void this.throttleGroups.up.setRate(this._uploadLimit)))}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 i=this.torrents.map((e=>t=>{e.destroy(t)}));this._connPool&&i.push((e=>{this._connPool.destroy(e)})),this.dht&&i.push((e=>{this.dht.destroy(e)})),u(i,t),e&&this.emit("error",e),this.torrents=[],this._connPool=null,this.dht=null,this.throttleGroups.down.destroy(),this.throttleGroups.up.destroy()}_onListening(){if(this._debug("listening"),this.listening=!0,this._connPool){const e=this._connPool.tcpServer.address();e&&(this.torrentPort=e.port)}this.emit("listening")}_debug(){const e=[].slice.call(arguments);e[0]=`[${this._debugId}] ${e[0]}`,x(...e)}_getByHash(e){for(const t of this.torrents)if(t.infoHashHash||(t.infoHashHash=m.sync(i.from("72657132"+t.infoHash,"hex"))),e===t.infoHashHash)return t;return null}}E.WEBRTC_SUPPORT=d.WEBRTC_SUPPORT,E.UTP_SUPPORT=g.UTP_SUPPORT,E.VERSION=_,t.exports=E}).call(this)}).call(this,e("buffer").Buffer)},{"./lib/conn-pool.js":66,"./lib/peer":491,"./lib/torrent.js":493,"./package.json":495,"bittorrent-dht/client":66,buffer:109,"create-torrent":143,debug:160,events:192,"load-ip-set":66,"parse-torrent":331,path:332,"queue-microtask":353,randombytes:356,"run-parallel":380,"simple-concat":392,"simple-peer":394,"simple-sha1":410,"speed-limiter":428,throughput:474}],489:[function(e,t,i){const n=e("stream"),r=e("debug"),s=e("end-of-stream"),a=r("webtorrent:file-stream");class o extends n.Readable{constructor(e,t){super(t),this._torrent=e._torrent;const i=t&&t.start||0,n=t&&t.end&&t.end{this._notify()})),s(this,(e=>{this.destroy(e)}))}_read(){this._reading||(this._reading=!0,this._notify())}_notify(){if(!this._reading||0===this._missing)return;if(!this._torrent.bitfield.get(this._piece))return this._torrent.critical(this._piece,this._piece+this._criticalLength);if(this._notifying)return;if(this._notifying=!0,this._torrent.destroyed)return this.destroy(new Error("Torrent removed"));const e=this._piece,t={};e===this._torrent.pieces.length-1&&(t.length=this._torrent.lastPieceLength),this._torrent.store.get(e,t,((t,i)=>{if(this._notifying=!1,!this.destroyed){if(a("read %s (length %s) (err %s)",e,i&&i.length,t&&t.message),t)return this.destroy(t);this._offset&&(i=i.slice(this._offset),this._offset=0),this._missing{const s=r===e.length-1?n:i;return t.get(r)?s:s-e[r].missing};let o=0;for(let t=r;t<=s;t+=1){const c=a(t);if(o+=c,t===r){const e=this.offset%i;o-=Math.min(e,c)}if(t===s){const t=(s===e.length-1?n:i)-(this.offset+this.length)%i;o-=Math.min(t,c)}}return o}get progress(){return this.length?this.downloaded/this.length:0}select(e){0!==this.length&&this._torrent.select(this._startPiece,this._endPiece,e)}deselect(){0!==this.length&&this._torrent.deselect(this._startPiece,this._endPiece,!1)}createReadStream(e){if(0===this.length){const e=new r;return u((()=>{e.end()})),e}const t=new h(this,e);return this._fileStreams.add(t),t.once("close",(()=>{this._fileStreams.delete(t)})),t}getBuffer(e){l(this.createReadStream(),this.length,e)}getBlob(e){if("undefined"==typeof window)throw new Error("browser-only method");o(this.createReadStream(),this._getMimeType()).then((t=>e(null,t)),(t=>e(t)))}getBlobURL(e){if("undefined"==typeof window)throw new Error("browser-only method");c(this.createReadStream(),this._getMimeType()).then((t=>e(null,t)),(t=>e(t)))}appendTo(e,t,i){if("undefined"==typeof window)throw new Error("browser-only method");a.append(this,e,t,i)}renderTo(e,t,i){if("undefined"==typeof window)throw new Error("browser-only method");a.render(this,e,t,i)}_serve(e){const t={status:200,headers:{"Accept-Ranges":"bytes","Content-Type":d.getType(this.name),"Cache-Control":"no-cache, no-store, must-revalidate, max-age=0",Expires:"0"},body:"HEAD"===e.method?"":"STREAM"};"document"===e.destination&&(t.headers["Content-Type"]="application/octet-stream",t.headers["Content-Disposition"]="attachment",t.body="DOWNLOAD");let i=p(this.length,e.headers.range||"");i.constructor===Array?(t.status=206,i=i[0],t.headers["Content-Range"]=`bytes ${i.start}-${i.end}/${this.length}`,t.headers["Content-Length"]=""+(i.end-i.start+1)):t.headers["Content-Length"]=this.length;const n="GET"===e.method&&this.createReadStream(i);let r=null;return n&&this.emit("stream",{stream:n,req:e,file:this},(e=>{r=e,f(e,(()=>{e&&e.destroy(),n.destroy()}))})),[t,r||n,r&&n]}getStreamURL(e=(()=>{})){if("undefined"==typeof window)throw new Error("browser-only method");if(!this._serviceWorker)throw new Error("No worker registered");if("activated"!==this._serviceWorker.state)throw new Error("Worker isn't activated");e(null,`${this._serviceWorker.scriptURL.slice(0,this._serviceWorker.scriptURL.lastIndexOf("/")+1).slice(window.location.origin.length)}webtorrent/${this._torrent.infoHash}/${encodeURI(this.path)}`)}streamTo(e,t=(()=>{})){if("undefined"==typeof window)throw new Error("browser-only method");if(!this._serviceWorker)throw new Error("No worker registered");if("activated"!==this._serviceWorker.state)throw new Error("Worker isn't activated");const i=this._serviceWorker.scriptURL.slice(0,this._serviceWorker.scriptURL.lastIndexOf("/")+1).slice(window.location.origin.length);e.src=`${i}webtorrent/${this._torrent.infoHash}/${encodeURI(this.path)}`,t(null,e)}_getMimeType(){return a.mime[s.extname(this.name).toLowerCase()]}_destroy(){this._destroyed=!0,this._torrent=null;for(const e of this._fileStreams)e.destroy();this._fileStreams.clear()}}},{"./file-stream.js":489,"end-of-stream":190,events:192,mime:281,path:332,"queue-microtask":353,"range-parser":358,"render-media":376,stream:433,"stream-to-blob":468,"stream-to-blob-url":467,"stream-with-known-length-to-buffer":469}],491:[function(e,t,i){const n=e("events"),{Transform:r}=e("stream"),s=e("unordered-array-remove"),a=e("debug"),o=e("bittorrent-protocol"),c=a("webtorrent:peer");let l=!1;i.enableSecure=()=>{l=!0},i.createWebRTCPeer=(e,t,i)=>{const n=new d(e.id,"webrtc");if(n.conn=e,n.swarm=t,n.throttleGroups=i,n.conn.connected)n.onConnect();else{const e=()=>{n.conn.removeListener("connect",t),n.conn.removeListener("error",i)},t=()=>{e(),n.onConnect()},i=t=>{e(),n.destroy(t)};n.conn.once("connect",t),n.conn.once("error",i),n.startConnectTimeout()}return n},i.createTCPIncomingPeer=(e,t)=>u(e,"tcpIncoming",t),i.createUTPIncomingPeer=(e,t)=>u(e,"utpIncoming",t),i.createTCPOutgoingPeer=(e,t,i)=>p(e,t,"tcpOutgoing",i),i.createUTPOutgoingPeer=(e,t,i)=>p(e,t,"utpOutgoing",i);const u=(e,t,i)=>{const n=`${e.remoteAddress}:${e.remotePort}`,r=new d(n,t);return r.conn=e,r.addr=n,r.throttleGroups=i,r.onConnect(),r},p=(e,t,i,n)=>{const r=new d(e,i);return r.addr=e,r.swarm=t,r.throttleGroups=n,r};i.createWebSeedPeer=(e,t,i,n)=>{const r=new d(t,"webSeed");return r.swarm=i,r.conn=e,r.throttleGroups=n,r.onConnect(),r};class d extends n{constructor(e,t){super(),this.id=e,this.type=t,c("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.sentPe1=!1,this.sentPe2=!1,this.sentPe3=!1,this.sentPe4=!1,this.sentHandshake=!1}onConnect(){if(this.destroyed)return;this.connected=!0,c("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 o(this.type,this.retries,l);t.once("end",(()=>{this.destroy()})),t.once("close",(()=>{this.destroy()})),t.once("finish",(()=>{this.destroy()})),t.once("error",(e=>{this.destroy(e)})),t.once("pe1",(()=>{this.onPe1()})),t.once("pe2",(()=>{this.onPe2()})),t.once("pe3",(()=>{this.onPe3()})),t.once("pe4",(()=>{this.onPe4()})),t.once("handshake",((e,t)=>{this.onHandshake(e,t)})),this.startHandshakeTimeout(),this.setThrottlePipes(),this.swarm&&("tcpOutgoing"===this.type?l&&0===this.retries&&!this.sentPe1?this.sendPe1():this.sentHandshake||this.handshake():"tcpIncoming"===this.type||this.sentHandshake||this.handshake())}sendPe1(){this.wire.sendPe1(),this.sentPe1=!0}onPe1(){this.sendPe2()}sendPe2(){this.wire.sendPe2(),this.sentPe2=!0}onPe2(){this.sendPe3()}sendPe3(){this.wire.sendPe3(this.swarm.infoHash),this.sentPe3=!0}onPe3(e){this.swarm&&(this.swarm.infoHashHash!==e&&this.destroy(new Error("unexpected crypto handshake info hash for this swarm")),this.sendPe4())}sendPe4(){this.wire.sendPe4(this.swarm.infoHash),this.sentPe4=!0}onPe4(){this.sentHandshake||this.handshake()}clearPipes(){this.conn.unpipe(),this.wire.unpipe()}setThrottlePipes(){const e=this;this.conn.pipe(this.throttleGroups.down.throttle()).pipe(new r({transform(t,i,n){e.emit("download",t.length),e.destroyed||n(null,t)}})).pipe(this.wire).pipe(this.throttleGroups.up.throttle()).pipe(new r({transform(t,i,n){e.emit("upload",t.length),e.destroyed||n(null,t)}})).pipe(this.conn)}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"));c("Peer %s got handshake %s",this.id,e),clearTimeout(this.handshakeTimeout),this.retries=0;let i=this.addr;!i&&this.conn.remoteAddress&&this.conn.remotePort&&(i=`${this.conn.remoteAddress}:${this.conn.remotePort}`),this.swarm._onWire(this.wire,i),this.swarm&&!this.swarm.destroyed&&(this.sentHandshake||this.handshake())}handshake(){const e={dht:!this.swarm.private&&!!this.swarm.client.dht,fast:!0};this.wire.handshake(this.swarm.infoHash,this.swarm.client.peerId,e),this.sentHandshake=!0}startConnectTimeout(){clearTimeout(this.connectTimeout);const e={webrtc:25e3,tcpOutgoing:5e3,utpOutgoing:5e3};this.connectTimeout=setTimeout((()=>{this.destroy(new Error("connect timeout"))}),e[this.type]),this.connectTimeout.unref&&this.connectTimeout.unref()}startHandshakeTimeout(){clearTimeout(this.handshakeTimeout),this.handshakeTimeout=setTimeout((()=>{this.destroy(new Error("handshake timeout"))}),25e3),this.handshakeTimeout.unref&&this.handshakeTimeout.unref()}destroy(e){if(this.destroyed)return;this.destroyed=!0,this.connected=!1,c("destroy %s %s (error: %s)",this.type,this.id,e&&(e.message||e)),clearTimeout(this.connectTimeout),clearTimeout(this.handshakeTimeout);const t=this.swarm,i=this.conn,n=this.wire;this.swarm=null,this.conn=null,this.wire=null,t&&n&&s(t.wires,t.wires.indexOf(n)),i&&(i.on("error",(()=>{})),i.destroy()),n&&n.destroy(),t&&t.removePeer(this.id)}}},{"bittorrent-protocol":27,debug:160,events:192,stream:433,"unordered-array-remove":481}],492:[function(e,t,i){t.exports=class{constructor(e){this._torrent=e,this._numPieces=e.pieces.length,this._pieces=new 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=[],i=1/0;for(let n=0;n{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;t0&&(i=Math.min(i,t))}return i}function $(){}t.exports=class extends r{constructor(e,t,i){super(),this._debugId="unknown infohash",this.client=t,this.announce=i.announce,this.urlList=i.urlList,this.path=i.path||V,this.addUID=i.addUID||!1,this.skipVerify=!!i.skipVerify,this._store=i.store||b,this._preloadedStore=i.preloadedStore||null,this._storeCacheSlots=void 0!==i.storeCacheSlots?i.storeCacheSlots:20,this._destroyStoreOnDestroy=i.destroyStoreOnDestroy||!1,this._getAnnounceOpts=i.getAnnounceOpts,"boolean"==typeof i.private&&(this.private=i.private),this.strategy=i.strategy||"sequential",this.maxWebConns=i.maxWebConns||4,this._rechokeNumSlots=!1===i.uploads||0===i.uploads?0:+i.uploads||10,this._rechokeOptimisticWire=null,this._rechokeOptimisticTime=0,this._rechokeIntervalId=null,this.ready=!1,this.destroyed=!1,this.paused=i.paused||!1,this.done=!1,this.metadata=null,this.store=null,this.storeOpts=i.storeOpts,this.files=[],this.pieces=[],this._amInterested=!1,this._selections=[],this._critical=[],this.wires=[],this._queue=[],this._peers={},this._peersLength=0,this.received=0,this.uploaded=0,this._downloadSpeed=T(),this._uploadSpeed=T(),this._servers=[],this._xsRequests=[],this._fileModtimes=i.fileModtimes,null!==e&&this._onTorrentId(e),this._debug("new torrent")}get timeRemaining(){return this.done?0:0===this.downloadSpeed?1/0:(this.length-this.downloaded)/this.downloadSpeed*1e3}get downloaded(){if(!this.bitfield)return 0;let e=0;for(let t=0,i=this.pieces.length;t{this.destroyed||this._onParsedTorrent(t)}))):E.remote(e,((e,t)=>{if(!this.destroyed)return 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._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),void 0!==this.private&&(e.private=this.private),this.announce&&(e.announce=e.announce.concat(this.announce)),this.client.tracker&&n.WEBTORRENT_ANNOUNCE&&!e.private&&(e.announce=e.announce.concat(n.WEBTORRENT_ANNOUNCE)),this.urlList&&(e.urlList=e.urlList.concat(this.urlList)),e.announce=Array.from(new Set(e.announce)),e.urlList=Array.from(new Set(e.urlList)),Object.assign(this,e),this.magnetURI=E.toMagnetURI(e),this.torrentFile=E.toTorrentFile(e)}_onListening(){this.destroyed||(this.info?this._onMetadata(this):(this.xs&&this._getMetadataFromServer(),this._startDiscovery()))}_startDiscovery(){if(this.discovery||this.destroyed)return;let e=this.client.tracker;e&&(e=Object.assign({},this.client.tracker,{getAnnounceOpts:()=>{if(this.destroyed)return;const e={uploaded:this.uploaded,downloaded:this.downloaded,left:Math.max(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.peerAddresses&&this.peerAddresses.forEach((e=>this.addPeer(e))),this.discovery=new m({infoHash:this.infoHash,announce:this.announce,peerId:this.client.peerId,dht:!this.private&&this.client.dht,tracker:e,port:this.client.torrentPort,userAgent:W,lsd:this.client.lsd}),this.discovery.on("error",(e=>{this._destroy(e)})),this.discovery.on("peer",((e,t)=>{this._debug("peer %s discovered via %s",e,t),"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)}))}_getMetadataFromServer(){const e=this,t=(Array.isArray(this.xs)?this.xs:[this.xs]).map((t=>i=>{!function(t,i){if(0!==t.indexOf("http://")&&0!==t.indexOf("https://"))return e.emit("warning",new Error(`skipping non-http xs param: ${t}`)),i(null);const n={url:t,method:"GET",headers:{"user-agent":W}};let r;try{r=v.concat(n,s)}catch(n){return e.emit("warning",new Error(`skipping invalid url xs param: ${t}`)),i(null)}function s(n,r,s){if(e.destroyed)return i(null);if(e.metadata)return i(null);if(n)return e.emit("warning",new Error(`http error from xs param: ${t}`)),i(null);if(200!==r.statusCode)return e.emit("warning",new Error(`non-200 status code ${r.statusCode} from xs param: ${t}`)),i(null);let a;try{a=E(s)}catch(n){}return a?a.infoHash!==e.infoHash?(e.emit("warning",new Error(`got torrent file with incorrect info hash from xs param: ${t}`)),i(null)):(e._onMetadata(a),void i(null)):(e.emit("warning",new Error(`got invalid torrent file from xs param: ${t}`)),i(null))}e._xsRequests.push(r)}(t,i)}));w(t)}_onMetadata(e){if(this.metadata||this.destroyed)return;let t;if(this._debug("got metadata"),this._xsRequests.forEach((e=>{e.abort()})),this._xsRequests=[],e&&e.infoHash)t=e;else try{t=E(e)}catch(e){return this._destroy(e)}this._processParsedTorrent(t),this.metadata=this.torrentFile,this.client.enableWebSeeds&&this.urlList.forEach((e=>{this.addWebSeed(e)})),this._rarityMap=new O(this),this.files=this.files.map((e=>new R(this,e)));let i=this._preloadedStore;if(i||(i=new this._store(this.pieceLength,{...this.storeOpts,torrent:this,path:this.path,files:this.files,length:this.length,name:this.name+" - "+this.infoHash.slice(0,8),addUID:this.addUID})),this._storeCacheSlots>0&&!(i instanceof _)&&(i=new p(i,{max:this._storeCacheSlots})),this.store=new g(i),this.so?this.files.forEach(((e,t)=>{this.so.includes(t)?this.files[t].select():this.files[t].deselect()})):0!==this.pieces.length&&this.select(0,this.pieces.length-1,!1),this._hashes=this.pieces,this.pieces=this.pieces.map(((e,t)=>{const i=t===this.pieces.length-1?this.lastPieceLength:this.pieceLength;return new S(i)})),this._reservations=this.pieces.map((()=>[])),this.bitfield=new u(this.pieces.length),this.emit("metadata"),!this.destroyed)if(this.skipVerify)this._markAllVerified(),this._onStore();else{const e=e=>{if(e)return this._destroy(e);this._debug("done verifying"),this._onStore()};this._debug("verifying existing torrent data"),this._fileModtimes&&this._store===b?this.getFileModtimes(((t,i)=>{if(t)return this._destroy(t);this.files.map(((e,t)=>i[t]===this._fileModtimes[t])).every((e=>e))?(this._markAllVerified(),this._onStore()):this._verifyPieces(e)})):this._verifyPieces(e)}}getFileModtimes(e){const t=[];k(this.files.map(((e,i)=>n=>{const r=this.addUID?c.join(this.name+" - "+this.infoHash.slice(0,8)):c.join(this.path,e.path);s.stat(r,((e,r)=>{if(e&&"ENOENT"!==e.code)return n(e);t[i]=r&&r.mtime.getTime(),n(null)}))})),H,(i=>{this._debug("done getting file modtimes"),e(i,t)}))}_verifyPieces(e){k(this.pieces.map(((e,t)=>e=>{if(this.destroyed)return e(new Error("torrent is destroyed"));const i={};t===this.pieces.length-1&&(i.length=this.lastPieceLength),this.store.get(t,i,((i,n)=>this.destroyed?e(new Error("torrent is destroyed")):i?A((()=>e(null))):void I(n,(i=>{if(this.destroyed)return e(new Error("torrent is destroyed"));i===this._hashes[t]?(this._debug("piece verified %s",t),this._markVerified(t)):this._debug("piece invalid %s",t),e(null)}))))})),H,e)}rescanFiles(e){if(this.destroyed)throw new Error("torrent is destroyed");e||(e=$),this._verifyPieces((t=>{if(t)return this._destroy(t),e(t);this._checkDone(),e(null)}))}_markAllVerified(){for(let e=0;ee))return!0;return!1}_onStore(){this.destroyed||(this._debug("on store"),this._startDiscovery(),this.ready=!0,this.emit("ready"),this._checkDone(),this._updateSelections(),this.wires.forEach((e=>{e.ut_metadata&&e.ut_metadata.setMetadata(this.metadata),this._onWireWithMetadata(e)})))}destroy(e,t){if("function"==typeof e)return this.destroy(null,e);this._destroy(null,e,t)}_destroy(e,t,i){if("function"==typeof t)return this._destroy(e,null,t);if(this.destroyed)return;this.destroyed=!0,this._debug("destroy"),this.client._remove(this),clearInterval(this._rechokeIntervalId),this._xsRequests.forEach((e=>{e.abort()})),this._rarityMap&&this._rarityMap.destroy();for(const e in this._peers)this.removePeer(e);this.files.forEach((e=>{e instanceof R&&e._destroy()}));const n=this._servers.map((e=>t=>{e.destroy(t)}));if(this.discovery&&n.push((e=>{this.discovery.destroy(e)})),this.store){let e=this._destroyStoreOnDestroy;t&&void 0!==t.destroyStore&&(e=t.destroyStore),n.push((t=>{e?this.store.destroy(t):this.store.close(t)}))}w(n,i),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(e){if(this.destroyed)throw new Error("torrent is destroyed");if(!this.infoHash)throw new Error("addPeer() must not be called before the `infoHash` event");let t;if(this.client.blocked){if("string"==typeof e){let i;try{i=l(e)}catch(t){return this._debug("ignoring peer: invalid %s",e),this.emit("invalidPeer",e),!1}t=i[0]}else"string"==typeof e.remoteAddress&&(t=e.remoteAddress);if(t&&this.client.blocked.contains(t))return this._debug("ignoring peer: blocked %s",e),"string"!=typeof e&&e.destroy(),this.emit("blockedPeer",e),!1}const i=this.client.utp&&this._isIPv4(t)?"utp":"tcp",n=!!this._addPeer(e,i);return n?this.emit("peer",e):this.emit("invalidPeer",e),n}_addPeer(e,t){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 i=e&&e.id||e;if(this._peers[i])return this._debug("ignoring peer: duplicate (%s)",i),"string"!=typeof e&&e.destroy(),null;if(this.paused)return this._debug("ignoring peer: torrent is paused"),"string"!=typeof e&&e.destroy(),null;let n;return this._debug("add peer %s",i),n="string"==typeof e?"utp"===t?L.createUTPOutgoingPeer(e,this,this.client.throttleGroups):L.createTCPOutgoingPeer(e,this,this.client.throttleGroups):L.createWebRTCPeer(e,this,this.client.throttleGroups),this._registerPeer(n),"string"==typeof e&&(this._queue.push(n),this._drain()),n}addWebSeed(e){if(this.destroyed)throw new Error("torrent is destroyed");let t,i;if("string"==typeof e){if(t=e,!/^https?:\/\/.+/.test(t))return this.emit("warning",new Error(`ignoring invalid web seed: ${t}`)),void this.emit("invalidPeer",t);if(this._peers[t])return this.emit("warning",new Error(`ignoring duplicate web seed: ${t}`)),void this.emit("invalidPeer",t);i=new q(t,this)}else{if(!e||"string"!=typeof e.connId)return void this.emit("warning",new Error("addWebSeed must be passed a string or connection object with id property"));if(i=e,t=i.connId,this._peers[t])return this.emit("warning",new Error(`ignoring duplicate web seed: ${t}`)),void this.emit("invalidPeer",t)}this._debug("add web seed %s",t);const n=L.createWebSeedPeer(i,t,this,this.client.throttleGroups);this._registerPeer(n),this.emit("peer",t)}_addIncomingPeer(e){return this.destroyed?e.destroy(new Error("torrent is destroyed")):this.paused?e.destroy(new Error("torrent is paused")):(this._debug("add incoming peer %s",e.id),void this._registerPeer(e))}_registerPeer(e){e.on("download",(e=>{this.destroyed||(this.received+=e,this._downloadSpeed(e),this.client._downloadSpeed(e),this.emit("download",e),this.destroyed||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.destroyed||this.client.emit("upload",e))})),this._peers[e.id]=e,this._peersLength+=1}removePeer(e){const t=e&&e.id||e;(e=this._peers[t])&&(this._debug("removePeer %s",t),delete this._peers[t],this._peersLength-=1,e.destroy(),this._drain())}select(e,t,i,n){if(this.destroyed)throw new Error("torrent is destroyed");if(e<0||tt.priority-e.priority)),this._updateSelections()}deselect(e,t,i){if(this.destroyed)throw new Error("torrent is destroyed");i=Number(i)||0,this._debug("deselect %s-%s (priority %s)",e,t,i);for(let n=0;n{if(!this.destroyed&&!this.client.dht.destroyed){if(!e.remoteAddress)return this._debug("ignoring PORT from peer with no address");if(0===i||i>65536)return this._debug("ignoring invalid PORT from peer");this._debug("port: %s (from %s)",i,t),this.client.dht.addNode({host:e.remoteAddress,port:i})}})),e.on("timeout",(()=>{this._debug("wire timeout (%s)",t),e.destroy()})),"webSeed"!==e.type&&e.setTimeout(3e4,!0),e.setKeepAlive(!0),e.use(C(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 B||this.private||(e.use(B()),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 i=this._peers[e];i&&!i.connected&&(this._debug("ut_pex: dropped peer: %s (from %s)",e,t),this.removePeer(e))})),e.once("close",(()=>{e.ut_pex.reset()}))),e.use(y()),this.emit("wire",e,t),this.ready&&A((()=>{this._onWireWithMetadata(e)}))}_onWireWithMetadata(e){let t=null;const i=()=>{this.destroyed||e.destroyed||(this._numQueued>2*(this._numConns-this.numPeers)&&e.amInterested?e.destroy():(t=setTimeout(i,D),t.unref&&t.unref()))};let n;const r=()=>{if(e.peerPieces.buffer.length===this.bitfield.buffer.length){for(n=0;n{r(),this._update(),this._updateWireInterest(e)})),e.on("have",(()=>{r(),this._update(),this._updateWireInterest(e)})),e.lt_donthave.on("donthave",(()=>{r(),this._update(),this._updateWireInterest(e)})),e.on("have-all",(()=>{e.isSeeder=!0,e.choke(),this._update(),this._updateWireInterest(e)})),e.on("have-none",(()=>{e.isSeeder=!1,this._update(),this._updateWireInterest(e)})),e.on("allowed-fast",(e=>{this._update()})),e.once("interested",(()=>{e.unchoke()})),e.once("close",(()=>{clearTimeout(t)})),e.on("choke",(()=>{clearTimeout(t),t=setTimeout(i,D),t.unref&&t.unref()})),e.on("unchoke",(()=>{clearTimeout(t),this._update()})),e.on("request",((t,i,n,r)=>{if(n>131072)return e.destroy();this.pieces[t]||this.store.get(t,{offset:i,length:n},r)})),e.hasFast&&this._hasAllPieces()?e.haveAll():e.hasFast&&this._hasNoPieces()?e.haveNone():e.bitfield(this.bitfield),this._updateWireInterest(e),e.peerExtensions.dht&&this.client.dht&&this.client.dht.listening&&e.port(this.client.dht.address().port),"webSeed"!==e.type&&(t=setTimeout(i,D),t.unref&&t.unref()),e.isSeeder=!1,r()}_updateSelections(){this.ready&&!this.destroyed&&(A((()=>{this._gcSelections()})),this._updateInterest(),this._update())}_gcSelections(){for(let e=0;ethis._updateWireInterest(e))),e!==this._amInterested&&(this._amInterested?this.emit("interested"):this.emit("uninterested"))}_updateWireInterest(e){let t=!1;for(let i=0;i{t._updateWire(e)}),{timeout:250}):t._updateWire(e)}_updateWire(e){const t=this,i=K(e,.5);if(e.requests.length>=i)return;const n=K(e,1);if(e.peerChoking)e.hasFast&&e.peerAllowedFastSet.length>0&&!this._hasMorePieces(e.peerAllowedFastSet.length-1)&&function(){if(e.requests.length>=n)return!1;for(const i of e.peerAllowedFastSet){if(e.peerPieces.get(i)&&!t.bitfield.get(i))for(;t._request(e,i,!1)&&e.requests.length=n.from+n.offset;--s)if(e.peerPieces.get(s)&&t._request(e,s,!1))return}}();a(!1)||a(!0)}function r(t,i,n,r){return s=>s>=t&&s<=i&&!(s in n)&&e.peerPieces.get(s)&&(!r||r(s))}function s(e){let i=e;for(let n=e;n=n)return!0;const a=function(){const i=e.downloadSpeed()||1;if(i>z)return()=>!0;const n=Math.max(1,e.requests.length)*S.BLOCK_LENGTH/i;let r=10,s=0;return e=>{if(!r||t.bitfield.get(e))return!0;let a=t.pieces[e].missing;for(;s0))return r--,!1}return!0}}();for(let o=0;o({wire:e,random:Math.random()}))).sort(((e,t)=>{const i=e.wire,n=t.wire;return i.downloadSpeed()!==n.downloadSpeed()?i.downloadSpeed()-n.downloadSpeed():i.uploadSpeed()!==n.uploadSpeed()?i.uploadSpeed()-n.uploadSpeed():i.amChoking!==n.amChoking?i.amChoking?-1:1:e.random-t.random})).map((e=>e.wire));this._rechokeOptimisticTime<=0?this._rechokeOptimisticWire=null:this._rechokeOptimisticTime-=1;let t=0;for(;e.length>0&&t0){const t=e.filter((e=>e.peerInterested));if(t.length>0){const e=t[(i=t.length,Math.random()*i|0)];e.unchoke(),this._rechokeOptimisticWire=e,this._rechokeOptimisticTime=2}}var i;e.filter((e=>e!==this._rechokeOptimisticWire)).forEach((e=>e.choke()))}_hotswap(e,t){const i=e.downloadSpeed();if(i=z||(2*o>i||o>a||(r=t,a=o))}if(!r)return!1;for(s=0;s=a)return!1;const o=n.pieces[t];let c=s?o.reserveRemaining():o.reserve();if(-1===c&&i&&n._hotswap(e,t)&&(c=s?o.reserveRemaining():o.reserve()),-1===c)return!1;let l=n._reservations[t];l||(l=n._reservations[t]=[]);let u=l.indexOf(null);-1===u&&(u=l.length),l[u]=e;const p=o.chunkOffset(c),d=s?o.chunkLengthRemaining(c):o.chunkLength(c);function f(){A((()=>{n._update()}))}return e.request(t,p,d,(function i(r,a){if(n.destroyed)return;if(!n.ready)return n.once("ready",(()=>{i(r,a)}));if(l[u]===e&&(l[u]=null),o!==n.pieces[t])return f();if(r)return n._debug("error getting piece %s (offset: %s length: %s) from %s: %s",t,p,d,`${e.remoteAddress}:${e.remotePort}`,r.message),s?o.cancelRemaining(c):o.cancel(c),void f();if(n._debug("got piece %s (offset: %s length: %s) from %s",t,p,d,`${e.remoteAddress}:${e.remotePort}`),!o.set(c,a,e))return f();const h=o.flush();I(h,(e=>{n.destroyed||(e===n._hashes[t]?(n._debug("piece verified %s",t),n.store.put(t,h,(e=>{e?n._destroy(e):(n.pieces[t]=null,n._markVerified(t),n.wires.forEach((e=>{e.have(t)})),n._checkDone()&&!n.destroyed&&n.discovery.complete(),f())}))):(n.pieces[t]=new S(o.length),n.emit("warning",new Error(`Piece ${t} failed verification`)),f()))}))})),!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(const t of this._selections){for(let i=t.from;i<=t.to;i++)if(!this.bitfield.get(i)){e=!1;break}if(!e)break}return!this.done&&e?(this.done=!0,this._debug(`torrent done: ${this.infoHash}`),this.emit("done")):this.done=!1,this._gcSelections(),e}load(e,t){if(this.destroyed)throw new Error("torrent is destroyed");if(!this.ready)return this.once("ready",(()=>{this.load(e,t)}));Array.isArray(e)||(e=[e]),t||(t=$);const i=new x(e),n=new d(this.store,this.pieceLength);M(i,n,(e=>{if(e)return t(e);this._markAllVerified(),this._checkDone(),t(null)}))}createServer(e){if("function"!=typeof P)throw new Error("node.js-only method");if(this.destroyed)throw new Error("torrent is destroyed");const t=new P(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?this.client._debugId:"No Client"}] [${this._debugId}] ${e[0]}`,N(...e)}_drain(){if(this._debug("_drain numConns %s maxConns %s",this._numConns,this.client.maxConns),"function"!=typeof a.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("%s connect attempt to %s",e.type,e.addr);const t=l(e.addr),i={host:t[0],port:t[1]};this.client.utp&&"utpOutgoing"===e.type?e.conn=U.connect(i.port,i.host):e.conn=a.connect(i);const n=e.conn;n.once("connect",(()=>{e.onConnect()})),n.once("error",(t=>{e.destroy(t)})),e.startConnectTimeout(),n.on("close",(()=>{if(this.destroyed)return;if(e.retries>=F.length){if(this.client.utp){const t=this._addPeer(e.addr,"tcp");t&&(t.retries=0)}else this._debug("conn %s closed: will not re-add (max %s attempts)",e.addr,F.length);return}const t=F[e.retries];this._debug("conn %s closed: will re-add to queue in %sms (attempt %s)",e.addr,t,e.retries+1);const i=setTimeout((()=>{if(this.destroyed)return;const t=l(e.addr)[0],i=this.client.utp&&this._isIPv4(t)?"utp":"tcp",n=this._addPeer(e.addr,i);n&&(n.retries=e.retries+1)}),t);i.unref&&i.unref()}))}_validAddr(e){let t;try{t=l(e)}catch(e){return!1}const i=t[0],n=t[1];return n>0&&n<65535&&!("127.0.0.1"===i&&n===this.client.torrentPort)}_isIPv4(e){return/^((?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])$/.test(e)}}}).call(this)}).call(this,e("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../package.json":495,"./file.js":490,"./peer.js":491,"./rarity-map.js":492,"./server.js":66,"./utp.js":66,"./webconn.js":494,_process:340,"addr-to-ip-port":2,bitfield:26,"cache-chunk-store":116,"chunk-store-stream/write":132,cpus:136,debug:160,events:192,fs:66,"fs-chunk-store":274,"immediate-chunk-store":244,lt_donthave:255,"memory-chunk-store":274,multistream:308,net:66,os:66,"parse-torrent":331,path:332,pump:348,"queue-microtask":353,"random-iterate":355,"run-parallel":380,"run-parallel-limit":379,"simple-get":393,"simple-sha1":410,throughput:474,"torrent-discovery":477,"torrent-piece":478,ut_metadata:484,ut_pex:66}],494:[function(e,t,i){(function(i){(function(){const{default:n}=e("bitfield"),r=e("debug"),s=e("simple-get"),a=e("lt_donthave"),o=e("simple-sha1"),c=e("bittorrent-protocol"),l=r("webtorrent:webconn"),u=e("../package.json").version;t.exports=class extends c{constructor(e,t){super(),this.url=e,this.connId=e,this.webPeerId=o.sync(e),this._torrent=t,this._init()}_init(){this.setKeepAlive(!0),this.use(a()),this.once("handshake",((e,t)=>{if(this.destroyed)return;this.handshake(e,this.webPeerId);const i=this._torrent.pieces.length,r=new n(i);for(let e=0;e<=i;e++)r.set(e,!0);this.bitfield(r)})),this.once("interested",(()=>{l("interested"),this.unchoke()})),this.on("uninterested",(()=>{l("uninterested")})),this.on("choke",(()=>{l("choke")})),this.on("unchoke",(()=>{l("unchoke")})),this.on("bitfield",(()=>{l("bitfield")})),this.lt_donthave.on("donthave",(()=>{l("donthave")})),this.on("request",((e,t,i,n)=>{l("request pieceIndex=%d offset=%d length=%d",e,t,i),this.httpRequest(e,t,i,((t,i)=>{if(t){this.lt_donthave.donthave(e);const t=setTimeout((()=>{this.destroyed||this.have(e)}),1e4);t.unref&&t.unref()}n(t,i)}))}))}httpRequest(e,t,n,r){const a=e*this._torrent.pieceLength+t,o=a+n-1,c=this._torrent.files;let p;if(c.length<=1)p=[{url:this.url,start:a,end:o}];else{const e=c.filter((e=>e.offset<=o&&e.offset+e.length>a));if(e.length<1)return r(new Error("Could not find file corresponding to web seed range request"));p=e.map((e=>{const t=e.offset+e.length-1;return{url:this.url+("/"===this.url[this.url.length-1]?"":"/")+e.path.replace(this._torrent.path,""),fileOffsetInRange:Math.max(e.offset-a,0),start:Math.max(a-e.offset,0),end:Math.min(t,o-e.offset)}}))}let d,f=0,h=!1;p.length>1&&(d=i.alloc(n)),p.forEach((i=>{const a=i.url,o=i.start,c=i.end;l("Requesting url=%s pieceIndex=%d offset=%d length=%d start=%d end=%d",a,e,t,n,o,c);const m={url:a,method:"GET",headers:{"user-agent":`WebTorrent/${u} (https://webtorrent.io)`,range:`bytes=${o}-${c}`},timeout:6e4};function b(e,t){if(e.statusCode<200||e.statusCode>=300){if(h)return;return h=!0,r(new Error(`Unexpected HTTP status code ${e.statusCode}`))}l("Got data of length %d",t.length),1===p.length?r(null,t):(t.copy(d,i.fileOffsetInRange),++f===p.length&&r(null,d))}s.concat(m,((e,t,i)=>{if(!h)return e?"undefined"==typeof window||a.startsWith(`${window.location.origin}/`)?(h=!0,r(e)):s.head(a,((t,i)=>{if(!h){if(t)return h=!0,r(t);if(i.statusCode<200||i.statusCode>=300)return h=!0,r(new Error(`Unexpected HTTP status code ${i.statusCode}`));if(i.url===a)return h=!0,r(e);m.url=i.url,s.concat(m,((e,t,i)=>{if(!h)return e?(h=!0,r(e)):void b(t,i)}))}})):void b(t,i)}))}))}destroy(){super.destroy(),this._torrent=null}}}).call(this)}).call(this,e("buffer").Buffer)},{"../package.json":495,bitfield:26,"bittorrent-protocol":27,buffer:109,debug:160,lt_donthave:255,"simple-get":393,"simple-sha1":410}],495:[function(e,t,i){t.exports={version:"1.8.20"}},{}],496:[function(e,t,i){t.exports=function e(t,i){if(t&&i)return e(t)(i);if("function"!=typeof t)throw new TypeError("need wrapper function");return Object.keys(t).forEach((function(e){n[e]=t[e]})),n;function n(){for(var e=new Array(arguments.length),i=0;i1080?(P.setProps({placement:"right"}),U.setProps({placement:"right"}),q.setProps({placement:"right"})):(P.setProps({placement:"top"}),U.setProps({placement:"top"}),q.setProps({placement:"top"}))}function H(e){G();try{console.info("Attempting parse"),l=n(e),W(),l.xs&&(console.info("Magnet includes xs, attempting remote parse"),F(l.xs))}catch(t){console.warn(t),"magnet"==c?(console.info("Attempting remote parse"),F(e)):(D.error("Problem parsing input. Is this a .torrent file?"),console.error("Problem parsing input"))}}function F(e){n.remote(e,(function(e,t){if(e)return D.error("Problem remotely fetching that file or parsing result"),console.warn(e),void G();c="remote-torrent-file",m.innerHTML='',b.setContent("Currently loaded information sourced from remotely fetched Torrent file"),l=t,W()}))}function W(){if(console.log(l),w.value=l.infoHash,v.value=l.name?l.name:"",l.created?(y.value=l.created.toISOString().slice(0,19),y.type="datetime-local"):y.type="text",_.value=l.createdBy?" by "+l.createdBy:"",x.value=l.comment?l.comment:"",M.innerHTML="",l.announce&&l.announce.length)for(let e=0;e',n.addEventListener("click",Z),t.appendChild(n),M.appendChild(t)}if(A.innerHTML="",l.urlList&&l.urlList.length)for(let e=0;e',n.addEventListener("click",Z),t.appendChild(n),A.appendChild(t)}if(T.innerHTML="",l.files&&l.files.length){if(C.style.display="none",l.files.length<100)for(let e of l.files){let t=K(s.lookup(e.name));T.appendChild(V(t,e.name,e.length))}else{for(let e=0;e<100;e++){let t=K(s.lookup(l.files[e].name));T.appendChild(V(t,l.files[e].name,l.files[e].length))}T.appendChild(V("","...and another "+(l.files.length-100)+" more files",""))}T.appendChild(V("folder-tree","",l.length)),q.setContent("Download Torrent file"),O.addEventListener("click",te),O.disabled=!1}else N.torrents.length>0?(C.style.display="none",T.innerHTML=''):(C.style.display="block",T.innerHTML=''),q.setContent("Files metadata is required to generate a Torrent file. Try fetching files list from WebTorrent."),O.removeEventListener("click",te),O.disabled=!0;B.setAttribute("data-clipboard-text",window.location.origin+"#"+n.toMagnetURI(l)),R.setAttribute("data-clipboard-text",n.toMagnetURI(l)),u.style.display="none",h.style.display="flex",window.location.hash=n.toMagnetURI(l),l.name?document.title="Torrent Parts | "+l.name:document.title="Torrent Parts | Inspect and edit what's in your Torrent file or Magnet link",b.enable()}function V(e,t,i){let n=document.createElement("tr"),s=document.createElement("td");e&&(s.innerHTML=''),n.appendChild(s);let a=document.createElement("td");a.innerHTML=t,n.appendChild(a);let o=document.createElement("td");return o.innerHTML=r.format(i,{decimalPlaces:1,unitSeparator:" "}),n.appendChild(o),n}function K(e){if(!e)return"file";switch(!0){case e.includes("msword"):case e.includes("wordprocessingml"):case e.includes("opendocument.text"):case e.includes("abiword"):return"file-word";case e.includes("ms-excel"):case e.includes("spreadsheet"):case e.includes("powerpoint"):case e.includes("presentation"):return"file-powerpoint";case e.includes("7z-"):case e.includes("iso9660"):case e.includes("zip"):case e.includes("octet-stream"):return"file-archive";case e.includes("csv"):return"file-csv";case e.includes("pdf"):return"file-pdf";case e.includes("font"):return"file-contract";case e.includes("text"):case e.includes("subrip"):case e.includes("vtt"):return"file-alt";case e.includes("audio"):return"file-audio";case e.includes("image"):return"file-image";case e.includes("video"):return"file-video";default:return"file"}}function $(e){this.dataset.group?l[this.dataset.group][this.dataset.index]=this.value?this.value:"":l[this.id]=this.value?this.value:"",window.location.hash=n.toMagnetURI(l),Q()}function G(){document.getElementById("magnet").value="",document.getElementById("torrent").value="",u.style.display="flex",h.style.display="none",v.value="",y.value="",_.value="",x.value="",w.value="",M.innerHTML="",A.innerHTML="",N.torrents.forEach((e=>e.destroy())),C.style.display="block",T.innerHTML="",window.location.hash="",B.setAttribute("data-clipboard-text",""),R.setAttribute("data-clipboard-text",""),document.title="Torrent Parts | Inspect and edit what's in your Torrent file or Magnet link",b.disable()}async function X(){k.className="disabled",k.innerHTML="Adding...";try{let e=await fetch("https://newtrackon.com/api/stable"),t=await e.text();l.announce=l.announce.concat(t.split("\n\n")),l.announce.push("http://bt1.archive.org:6969/announce"),l.announce.push("http://bt2.archive.org:6969/announce"),l.announce=l.announce.filter(((e,t)=>e&&l.announce.indexOf(e)===t)),D.success("Added known working trackers from newTrackon"),Q()}catch(e){D.error("Problem fetching trackers from newTrackon"),console.warn(e)}k.className="",k.innerHTML="Add Known Working Trackers",W()}function Y(){l[this.dataset.type].unshift(""),W()}function Z(){l[this.parentElement.className].splice(this.parentElement.dataset.index,1),W()}function J(e){l[e]=[],Q(),W()}function Q(){l.created=new Date,l.createdBy="Torrent Parts ",l.created?(y.value=l.created.toISOString().slice(0,19),y.type="datetime-local"):y.type="text",_.value=l.createdBy?" by "+l.createdBy:""}function ee(){console.info("Attempting fetching files from Webtorrent..."),C.style.display="none",l.announce.push("wss://tracker.webtorrent.io"),l.announce.push("wss://tracker.openwebtorrent.com"),l.announce.push("wss://tracker.btorrent.xyz"),l.announce.push("wss://tracker.fastcast.nz"),l.announce=l.announce.filter(((e,t)=>e&&l.announce.indexOf(e)===t)),N.add(n.toMagnetURI(l),(e=>{l.info=Object.assign({},e.info),l.files=e.files,l.infoBuffer=e.infoBuffer,l.length=e.length,l.lastPieceLength=e.lastPieceLength,Q(),W(),D.success("Fetched file details from Webtorrent peers"),e.destroy()})),W()}function te(){let e=n.toTorrentFile(l);if(null!==e&&navigator.msSaveBlob)return navigator.msSaveBlob(new Blob([e],{type:"application/x-bittorrent"}),l.name+".torrent");let t=document.createElement("a");t.style.display="none";let i=window.URL.createObjectURL(new Blob([e],{type:"application/x-bittorrent"}));t.setAttribute("href",i),t.setAttribute("download",l.name+".torrent"),document.body.appendChild(t),t.click(),window.URL.revokeObjectURL(i),t.remove()}window.addEventListener("resize",z),z(),document.addEventListener("DOMContentLoaded",(function(){document.getElementById("magnet").addEventListener("keyup",(function(e){e.preventDefault(),"Enter"===e.key&&(c="magnet",m.innerHTML='',b.setContent("Currently loaded information sourced from Magnet URL"),H(magnet.value))})),document.getElementById("torrent").addEventListener("change",(function(e){e.preventDefault(),e.target.files[0].arrayBuffer().then((function(e){c="torrent-file",m.innerHTML='',b.setContent("Currently loaded information sourced from Torrent file"),H(t.from(e))}))})),document.addEventListener("dragover",(function(e){e.preventDefault()})),document.addEventListener("drop",(function(e){e.preventDefault(),e.dataTransfer.items[0].getAsFile().arrayBuffer().then((function(e){c="torrent-file",m.innerHTML='',b.setContent("Currently loaded information sourced from Torrent file"),H(t.from(e))}))})),p.addEventListener("click",(function(e){e.preventDefault(),D.success("Parsing Ubuntu 20.04 Magnet URL"),c="magnet",m.innerHTML='',b.setContent("Currently loaded information sourced from Magnet URL"),H("magnet:?xt=urn:btih:9fc20b9e98ea98b4a35e6223041a5ef94ea27809&dn=ubuntu-20.04-desktop-amd64.iso&tr=https%3A%2F%2Ftorrent.ubuntu.com%2Fannounce&tr=https%3A%2F%2Fipv6.torrent.ubuntu.com%2Fannounce")})),d.addEventListener("click",(async function(e){e.preventDefault(),D.success("Fetching and Parsing “The WIRED CD” Torrent File..."),c="remote-torrent-file",m.innerHTML='',b.setContent("Currently loaded information sourced from remotely fetched Torrent file"),F("https://webtorrent.io/torrents/wired-cd.torrent")})),f.addEventListener("click",(async function(e){e.preventDefault(),D.success("Parsing Jack Johnson Archive.org Torrent File");let i=await fetch("/ext/jj2008-06-14.mk4_archive.torrent"),n=await i.arrayBuffer();c="torrent-file",m.innerHTML='',b.setContent("Currently loaded information sourced from Torrent file"),H(t.from(n))}));let e=new i("#copyURL");e.on("success",(function(e){D.success("Copied site URL to clipboard!"),console.info(e)})),e.on("failure",(function(e){D.error("Problem copying to clipboard"),console.warn(e)}));let n=new i("#copyMagnet");n.on("success",(function(e){D.success("Copied Magnet URL to clipboard!")})),n.on("failure",(function(e){D.error("Problem copying to clipboard"),console.warn(e)})),v.addEventListener("input",$),v.addEventListener("change",$),v.addEventListener("reset",$),v.addEventListener("paste",$),g.addEventListener("click",G),x.addEventListener("input",$),x.addEventListener("change",$),x.addEventListener("reset",$),x.addEventListener("paste",$),k.addEventListener("click",X),E.addEventListener("click",Y),S.addEventListener("click",(()=>J("announce"))),j.addEventListener("click",Y),I.addEventListener("click",(()=>J("urlList"))),C.addEventListener("click",ee),o("[data-tippy-content]",{theme:"torrent-parts",animation:"shift-away-subtle"}),b.disable(),window.location.hash&&(c="shared-url",m.innerHTML='',b.setContent("Currently loaded information sourced from shared torrent.parts link"),H(window.location.hash.split("#")[1]))}))}).call(this)}).call(this,e("buffer").Buffer)},{buffer:109,bytes:115,clipboard:134,"mime-types":279,"parse-torrent":331,"tippy.js":475,webtorrent:488}]},{},[498]); \ No newline at end of file +const n=e("events"),r=e("path"),s=e("simple-concat"),a=e("create-torrent"),o=e("debug"),c=e("bittorrent-dht/client"),l=e("load-ip-set"),u=e("run-parallel"),p=e("parse-torrent"),d=e("simple-peer"),f=e("queue-microtask"),h=e("randombytes"),m=e("simple-sha1"),b=e("throughput"),{ThrottleGroup:v}=e("speed-limiter"),g=e("./lib/conn-pool.js"),y=e("./lib/torrent.js"),{version:_}=e("./package.json"),x=o("webtorrent"),w=_.replace(/\d*./g,(e=>("0"+e%100).slice(-2))).slice(0,4),k=`-WW${w}-`;class E extends n{constructor(t={}){super(),"string"==typeof t.peerId?this.peerId=t.peerId:i.isBuffer(t.peerId)?this.peerId=t.peerId.toString("hex"):this.peerId=i.from(k+h(9).toString("base64")).toString("hex"),this.peerIdBuffer=i.from(this.peerId,"hex"),"string"==typeof t.nodeId?this.nodeId=t.nodeId:i.isBuffer(t.nodeId)?this.nodeId=t.nodeId.toString("hex"):this.nodeId=h(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=t.torrentPort||0,this.dhtPort=t.dhtPort||0,this.tracker=void 0!==t.tracker?t.tracker:{},this.lsd=!1!==t.lsd,this.torrents=[],this.maxConns=Number(t.maxConns)||55,this.utp=E.UTP_SUPPORT&&!1!==t.utp,this._downloadLimit=Math.max("number"==typeof t.downloadLimit?t.downloadLimit:-1,-1),this._uploadLimit=Math.max("number"==typeof t.uploadLimit?t.uploadLimit:-1,-1),this.serviceWorker=null,this.workerKeepAliveInterval=null,this.workerPortCount=0,!0===t.secure&&e("./lib/peer").enableSecure(),this._debug("new webtorrent (peerId %s, nodeId %s, port %s)",this.peerId,this.nodeId,this.torrentPort),this.throttleGroups={down:new v({rate:Math.max(this._downloadLimit,0),enabled:this._downloadLimit>=0}),up:new v({rate:Math.max(this._uploadLimit,0),enabled:this._uploadLimit>=0})},this.tracker&&("object"!=typeof this.tracker&&(this.tracker={}),globalThis.WRTC&&!this.tracker.wrtc&&(this.tracker.wrtc=globalThis.WRTC)),"function"==typeof g?this._connPool=new g(this):f((()=>{this._onListening()})),this._downloadSpeed=b(),this._uploadSpeed=b(),!1!==t.dht&&"function"==typeof c?(this.dht=new c(Object.assign({},{nodeId:this.nodeId},t.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!==t.webSeeds;const n=()=>{this.destroyed||(this.ready=!0,this.emit("ready"))};"function"==typeof l&&null!=t.blocklist?l(t.blocklist,{headers:{"user-agent":`WebTorrent/${_} (https://webtorrent.io)`}},((e,t)=>{if(e)return console.error(`Failed to load blocklist: ${e.message}`);this.blocked=t,n()})):f(n)}loadWorker(e,t=(()=>{})){if(!(e instanceof ServiceWorker))throw new Error("Invalid worker registration");if("activated"!==e.state)throw new Error("Worker isn't activated");this.serviceWorker=e,navigator.serviceWorker.addEventListener("message",(e=>{const{data:t}=e;if(!t.type||"webtorrent"===!t.type||!t.url)return null;let[i,...n]=t.url.slice(t.url.indexOf(t.scope+"webtorrent/")+11+t.scope.length).split("/");if(n=decodeURI(n.join("/")),!i||!n)return null;const[r]=e.ports,s=this.get(i)&&this.get(i).files.find((e=>e.path===n));if(!s)return null;const[a,o,c]=s._serve(t),l=o&&o[Symbol.asyncIterator](),u=()=>{r.onmessage=null,o&&o.destroy(),c&&c.destroy(),this.workerPortCount--,this.workerPortCount||(clearInterval(this.workerKeepAliveInterval),this.workerKeepAliveInterval=null)};r.onmessage=async e=>{if(e.data){let e;try{e=(await l.next()).value}catch(e){}r.postMessage(e),e||u(),this.workerKeepAliveInterval||(this.workerKeepAliveInterval=setInterval((()=>fetch(`${this.serviceWorker.scriptURL.slice(0,this.serviceWorker.scriptURL.lastIndexOf("/")+1).slice(window.location.origin.length)}webtorrent/keepalive/`)),2e4))}else u()},this.workerPortCount++,r.postMessage(a)})),t(this.serviceWorker)}get downloadSpeed(){return this._downloadSpeed()}get uploadSpeed(){return this._uploadSpeed()}get progress(){const e=this.torrents.filter((e=>1!==e.progress));return e.reduce(((e,t)=>e+t.downloaded),0)/(e.reduce(((e,t)=>e+(t.length||0)),0)||1)}get ratio(){return this.torrents.reduce(((e,t)=>e+t.uploaded),0)/(this.torrents.reduce(((e,t)=>e+t.received),0)||1)}get(e){if(e instanceof y){if(this.torrents.includes(e))return e}else{let t;try{t=p(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}return null}add(e,t={},i=(()=>{})){if(this.destroyed)throw new Error("client is destroyed");"function"==typeof t&&([t,i]=[{},t]);const n=()=>{if(!this.destroyed)for(const e of this.torrents)if(e.infoHash===s.infoHash&&e!==s)return void s._destroy(new Error(`Cannot add duplicate torrent ${s.infoHash}`))},r=()=>{this.destroyed||(i(s),this.emit("torrent",s))};this._debug("add"),t=t?Object.assign({},t):{};const s=new y(e,this,t);return this.torrents.push(s),s.once("_infoHash",n),s.once("ready",r),s.once("close",(function e(){s.removeListener("_infoHash",n),s.removeListener("ready",r),s.removeListener("close",e)})),s}seed(e,t,i){if(this.destroyed)throw new Error("client is destroyed");"function"==typeof t&&([t,i]=[{},t]),this._debug("seed"),(t=t?Object.assign({},t):{}).skipVerify=!0;const n="string"==typeof e;n&&(t.path=r.dirname(e)),t.createdBy||(t.createdBy=`WebTorrent/${w}`);const o=e=>{this._debug("on seed"),"function"==typeof i&&i(e),e.emit("seed"),this.emit("seed",e)},c=this.add(null,t,(e=>{const i=[i=>{if(n||t.preloadedStore)return i();e.load(l,i)}];this.dht&&i.push((t=>{e.once("dhtAnnounce",t)})),u(i,(t=>{if(!this.destroyed)return t?e._destroy(t):void o(e)}))}));let l;var p;return p=e,"undefined"!=typeof FileList&&p instanceof FileList?e=Array.from(e):Array.isArray(e)||(e=[e]),u(e.map((e=>i=>{!t.preloadedStore&&function(e){return"object"==typeof e&&null!=e&&"function"==typeof e.pipe}(e)?s(e,((t,n)=>{if(t)return i(t);n.name=e.name,i(null,n)})):i(null,e)})),((e,n)=>{if(!this.destroyed)return e?c._destroy(e):void a.parseInput(n,t,((e,r)=>{if(!this.destroyed){if(e)return c._destroy(e);l=r.map((e=>e.getStream)),a(n,t,((e,t)=>{if(this.destroyed)return;if(e)return c._destroy(e);const n=this.get(t);n?(console.warn("A torrent with the same id is already being seeded"),c._destroy(),"function"==typeof i&&i(n)):c._onTorrentId(t)}))}}))})),c}remove(e,t,i){if("function"==typeof t)return this.remove(e,null,t);this._debug("remove");if(!this.get(e))throw new Error(`No torrent with id ${e}`);this._remove(e,t,i)}_remove(e,t,i){if("function"==typeof t)return this._remove(e,null,t);const n=this.get(e);n&&(this.torrents.splice(this.torrents.indexOf(n),1),n.destroy(t,i),this.dht&&this.dht._tables.remove(n.infoHash))}address(){return this.listening?this._connPool?this._connPool.tcpServer.address():{address:"0.0.0.0",family:"IPv4",port:0}:null}throttleDownload(e){return e=Number(e),!(isNaN(e)||!isFinite(e)||e<-1)&&(this._downloadLimit=e,this._downloadLimit<0?this.throttleGroups.down.setEnabled(!1):(this.throttleGroups.down.setEnabled(!0),void this.throttleGroups.down.setRate(this._downloadLimit)))}throttleUpload(e){return e=Number(e),!(isNaN(e)||!isFinite(e)||e<-1)&&(this._uploadLimit=e,this._uploadLimit<0?this.throttleGroups.up.setEnabled(!1):(this.throttleGroups.up.setEnabled(!0),void this.throttleGroups.up.setRate(this._uploadLimit)))}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 i=this.torrents.map((e=>t=>{e.destroy(t)}));this._connPool&&i.push((e=>{this._connPool.destroy(e)})),this.dht&&i.push((e=>{this.dht.destroy(e)})),u(i,t),e&&this.emit("error",e),this.torrents=[],this._connPool=null,this.dht=null,this.throttleGroups.down.destroy(),this.throttleGroups.up.destroy()}_onListening(){if(this._debug("listening"),this.listening=!0,this._connPool){const e=this._connPool.tcpServer.address();e&&(this.torrentPort=e.port)}this.emit("listening")}_debug(){const e=[].slice.call(arguments);e[0]=`[${this._debugId}] ${e[0]}`,x(...e)}_getByHash(e){for(const t of this.torrents)if(t.infoHashHash||(t.infoHashHash=m.sync(i.from("72657132"+t.infoHash,"hex"))),e===t.infoHashHash)return t;return null}}E.WEBRTC_SUPPORT=d.WEBRTC_SUPPORT,E.UTP_SUPPORT=g.UTP_SUPPORT,E.VERSION=_,t.exports=E}).call(this)}).call(this,e("buffer").Buffer)},{"./lib/conn-pool.js":66,"./lib/peer":491,"./lib/torrent.js":493,"./package.json":495,"bittorrent-dht/client":66,buffer:109,"create-torrent":143,debug:160,events:192,"load-ip-set":66,"parse-torrent":331,path:332,"queue-microtask":353,randombytes:356,"run-parallel":380,"simple-concat":392,"simple-peer":394,"simple-sha1":410,"speed-limiter":428,throughput:474}],489:[function(e,t,i){const n=e("stream"),r=e("debug"),s=e("end-of-stream"),a=r("webtorrent:file-stream");class o extends n.Readable{constructor(e,t){super(t),this._torrent=e._torrent;const i=t&&t.start||0,n=t&&t.end&&t.end{this._notify()})),s(this,(e=>{this.destroy(e)}))}_read(){this._reading||(this._reading=!0,this._notify())}_notify(){if(!this._reading||0===this._missing)return;if(!this._torrent.bitfield.get(this._piece))return this._torrent.critical(this._piece,this._piece+this._criticalLength);if(this._notifying)return;if(this._notifying=!0,this._torrent.destroyed)return this.destroy(new Error("Torrent removed"));const e=this._piece,t={};e===this._torrent.pieces.length-1&&(t.length=this._torrent.lastPieceLength),this._torrent.store.get(e,t,((t,i)=>{if(this._notifying=!1,!this.destroyed){if(a("read %s (length %s) (err %s)",e,i&&i.length,t&&t.message),t)return this.destroy(t);this._offset&&(i=i.slice(this._offset),this._offset=0),this._missing{const s=r===e.length-1?n:i;return t.get(r)?s:s-e[r].missing};let o=0;for(let t=r;t<=s;t+=1){const c=a(t);if(o+=c,t===r){const e=this.offset%i;o-=Math.min(e,c)}if(t===s){const t=(s===e.length-1?n:i)-(this.offset+this.length)%i;o-=Math.min(t,c)}}return o}get progress(){return this.length?this.downloaded/this.length:0}select(e){0!==this.length&&this._torrent.select(this._startPiece,this._endPiece,e)}deselect(){0!==this.length&&this._torrent.deselect(this._startPiece,this._endPiece,!1)}createReadStream(e){if(0===this.length){const e=new r;return u((()=>{e.end()})),e}const t=new h(this,e);return this._fileStreams.add(t),t.once("close",(()=>{this._fileStreams.delete(t)})),t}getBuffer(e){l(this.createReadStream(),this.length,e)}getBlob(e){if("undefined"==typeof window)throw new Error("browser-only method");o(this.createReadStream(),this._getMimeType()).then((t=>e(null,t)),(t=>e(t)))}getBlobURL(e){if("undefined"==typeof window)throw new Error("browser-only method");c(this.createReadStream(),this._getMimeType()).then((t=>e(null,t)),(t=>e(t)))}appendTo(e,t,i){if("undefined"==typeof window)throw new Error("browser-only method");a.append(this,e,t,i)}renderTo(e,t,i){if("undefined"==typeof window)throw new Error("browser-only method");a.render(this,e,t,i)}_serve(e){const t={status:200,headers:{"Accept-Ranges":"bytes","Content-Type":d.getType(this.name),"Cache-Control":"no-cache, no-store, must-revalidate, max-age=0",Expires:"0"},body:"HEAD"===e.method?"":"STREAM"};"document"===e.destination&&(t.headers["Content-Type"]="application/octet-stream",t.headers["Content-Disposition"]="attachment",t.body="DOWNLOAD");let i=p(this.length,e.headers.range||"");i.constructor===Array?(t.status=206,i=i[0],t.headers["Content-Range"]=`bytes ${i.start}-${i.end}/${this.length}`,t.headers["Content-Length"]=""+(i.end-i.start+1)):t.headers["Content-Length"]=this.length;const n="GET"===e.method&&this.createReadStream(i);let r=null;return n&&this.emit("stream",{stream:n,req:e,file:this},(e=>{r=e,f(e,(()=>{e&&e.destroy(),n.destroy()}))})),[t,r||n,r&&n]}getStreamURL(e=(()=>{})){if("undefined"==typeof window)throw new Error("browser-only method");if(!this._serviceWorker)throw new Error("No worker registered");if("activated"!==this._serviceWorker.state)throw new Error("Worker isn't activated");e(null,`${this._serviceWorker.scriptURL.slice(0,this._serviceWorker.scriptURL.lastIndexOf("/")+1).slice(window.location.origin.length)}webtorrent/${this._torrent.infoHash}/${encodeURI(this.path)}`)}streamTo(e,t=(()=>{})){if("undefined"==typeof window)throw new Error("browser-only method");if(!this._serviceWorker)throw new Error("No worker registered");if("activated"!==this._serviceWorker.state)throw new Error("Worker isn't activated");const i=this._serviceWorker.scriptURL.slice(0,this._serviceWorker.scriptURL.lastIndexOf("/")+1).slice(window.location.origin.length);e.src=`${i}webtorrent/${this._torrent.infoHash}/${encodeURI(this.path)}`,t(null,e)}_getMimeType(){return a.mime[s.extname(this.name).toLowerCase()]}_destroy(){this._destroyed=!0,this._torrent=null;for(const e of this._fileStreams)e.destroy();this._fileStreams.clear()}}},{"./file-stream.js":489,"end-of-stream":190,events:192,mime:281,path:332,"queue-microtask":353,"range-parser":358,"render-media":376,stream:433,"stream-to-blob":468,"stream-to-blob-url":467,"stream-with-known-length-to-buffer":469}],491:[function(e,t,i){const n=e("events"),{Transform:r}=e("stream"),s=e("unordered-array-remove"),a=e("debug"),o=e("bittorrent-protocol"),c=a("webtorrent:peer");let l=!1;i.enableSecure=()=>{l=!0},i.createWebRTCPeer=(e,t,i)=>{const n=new d(e.id,"webrtc");if(n.conn=e,n.swarm=t,n.throttleGroups=i,n.conn.connected)n.onConnect();else{const e=()=>{n.conn.removeListener("connect",t),n.conn.removeListener("error",i)},t=()=>{e(),n.onConnect()},i=t=>{e(),n.destroy(t)};n.conn.once("connect",t),n.conn.once("error",i),n.startConnectTimeout()}return n},i.createTCPIncomingPeer=(e,t)=>u(e,"tcpIncoming",t),i.createUTPIncomingPeer=(e,t)=>u(e,"utpIncoming",t),i.createTCPOutgoingPeer=(e,t,i)=>p(e,t,"tcpOutgoing",i),i.createUTPOutgoingPeer=(e,t,i)=>p(e,t,"utpOutgoing",i);const u=(e,t,i)=>{const n=`${e.remoteAddress}:${e.remotePort}`,r=new d(n,t);return r.conn=e,r.addr=n,r.throttleGroups=i,r.onConnect(),r},p=(e,t,i,n)=>{const r=new d(e,i);return r.addr=e,r.swarm=t,r.throttleGroups=n,r};i.createWebSeedPeer=(e,t,i,n)=>{const r=new d(t,"webSeed");return r.swarm=i,r.conn=e,r.throttleGroups=n,r.onConnect(),r};class d extends n{constructor(e,t){super(),this.id=e,this.type=t,c("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.sentPe1=!1,this.sentPe2=!1,this.sentPe3=!1,this.sentPe4=!1,this.sentHandshake=!1}onConnect(){if(this.destroyed)return;this.connected=!0,c("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 o(this.type,this.retries,l);t.once("end",(()=>{this.destroy()})),t.once("close",(()=>{this.destroy()})),t.once("finish",(()=>{this.destroy()})),t.once("error",(e=>{this.destroy(e)})),t.once("pe1",(()=>{this.onPe1()})),t.once("pe2",(()=>{this.onPe2()})),t.once("pe3",(()=>{this.onPe3()})),t.once("pe4",(()=>{this.onPe4()})),t.once("handshake",((e,t)=>{this.onHandshake(e,t)})),this.startHandshakeTimeout(),this.setThrottlePipes(),this.swarm&&("tcpOutgoing"===this.type?l&&0===this.retries&&!this.sentPe1?this.sendPe1():this.sentHandshake||this.handshake():"tcpIncoming"===this.type||this.sentHandshake||this.handshake())}sendPe1(){this.wire.sendPe1(),this.sentPe1=!0}onPe1(){this.sendPe2()}sendPe2(){this.wire.sendPe2(),this.sentPe2=!0}onPe2(){this.sendPe3()}sendPe3(){this.wire.sendPe3(this.swarm.infoHash),this.sentPe3=!0}onPe3(e){this.swarm&&(this.swarm.infoHashHash!==e&&this.destroy(new Error("unexpected crypto handshake info hash for this swarm")),this.sendPe4())}sendPe4(){this.wire.sendPe4(this.swarm.infoHash),this.sentPe4=!0}onPe4(){this.sentHandshake||this.handshake()}clearPipes(){this.conn.unpipe(),this.wire.unpipe()}setThrottlePipes(){const e=this;this.conn.pipe(this.throttleGroups.down.throttle()).pipe(new r({transform(t,i,n){e.emit("download",t.length),e.destroyed||n(null,t)}})).pipe(this.wire).pipe(this.throttleGroups.up.throttle()).pipe(new r({transform(t,i,n){e.emit("upload",t.length),e.destroyed||n(null,t)}})).pipe(this.conn)}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"));c("Peer %s got handshake %s",this.id,e),clearTimeout(this.handshakeTimeout),this.retries=0;let i=this.addr;!i&&this.conn.remoteAddress&&this.conn.remotePort&&(i=`${this.conn.remoteAddress}:${this.conn.remotePort}`),this.swarm._onWire(this.wire,i),this.swarm&&!this.swarm.destroyed&&(this.sentHandshake||this.handshake())}handshake(){const e={dht:!this.swarm.private&&!!this.swarm.client.dht,fast:!0};this.wire.handshake(this.swarm.infoHash,this.swarm.client.peerId,e),this.sentHandshake=!0}startConnectTimeout(){clearTimeout(this.connectTimeout);const e={webrtc:25e3,tcpOutgoing:5e3,utpOutgoing:5e3};this.connectTimeout=setTimeout((()=>{this.destroy(new Error("connect timeout"))}),e[this.type]),this.connectTimeout.unref&&this.connectTimeout.unref()}startHandshakeTimeout(){clearTimeout(this.handshakeTimeout),this.handshakeTimeout=setTimeout((()=>{this.destroy(new Error("handshake timeout"))}),25e3),this.handshakeTimeout.unref&&this.handshakeTimeout.unref()}destroy(e){if(this.destroyed)return;this.destroyed=!0,this.connected=!1,c("destroy %s %s (error: %s)",this.type,this.id,e&&(e.message||e)),clearTimeout(this.connectTimeout),clearTimeout(this.handshakeTimeout);const t=this.swarm,i=this.conn,n=this.wire;this.swarm=null,this.conn=null,this.wire=null,t&&n&&s(t.wires,t.wires.indexOf(n)),i&&(i.on("error",(()=>{})),i.destroy()),n&&n.destroy(),t&&t.removePeer(this.id)}}},{"bittorrent-protocol":27,debug:160,events:192,stream:433,"unordered-array-remove":481}],492:[function(e,t,i){t.exports=class{constructor(e){this._torrent=e,this._numPieces=e.pieces.length,this._pieces=new 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=[],i=1/0;for(let n=0;n{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;t0&&(i=Math.min(i,t))}return i}function $(){}t.exports=class extends r{constructor(e,t,i){super(),this._debugId="unknown infohash",this.client=t,this.announce=i.announce,this.urlList=i.urlList,this.path=i.path||V,this.addUID=i.addUID||!1,this.skipVerify=!!i.skipVerify,this._store=i.store||b,this._preloadedStore=i.preloadedStore||null,this._storeCacheSlots=void 0!==i.storeCacheSlots?i.storeCacheSlots:20,this._destroyStoreOnDestroy=i.destroyStoreOnDestroy||!1,this._getAnnounceOpts=i.getAnnounceOpts,"boolean"==typeof i.private&&(this.private=i.private),this.strategy=i.strategy||"sequential",this.maxWebConns=i.maxWebConns||4,this._rechokeNumSlots=!1===i.uploads||0===i.uploads?0:+i.uploads||10,this._rechokeOptimisticWire=null,this._rechokeOptimisticTime=0,this._rechokeIntervalId=null,this.ready=!1,this.destroyed=!1,this.paused=i.paused||!1,this.done=!1,this.metadata=null,this.store=null,this.storeOpts=i.storeOpts,this.files=[],this.pieces=[],this._amInterested=!1,this._selections=[],this._critical=[],this.wires=[],this._queue=[],this._peers={},this._peersLength=0,this.received=0,this.uploaded=0,this._downloadSpeed=T(),this._uploadSpeed=T(),this._servers=[],this._xsRequests=[],this._fileModtimes=i.fileModtimes,null!==e&&this._onTorrentId(e),this._debug("new torrent")}get timeRemaining(){return this.done?0:0===this.downloadSpeed?1/0:(this.length-this.downloaded)/this.downloadSpeed*1e3}get downloaded(){if(!this.bitfield)return 0;let e=0;for(let t=0,i=this.pieces.length;t{this.destroyed||this._onParsedTorrent(t)}))):E.remote(e,((e,t)=>{if(!this.destroyed)return 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._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),void 0!==this.private&&(e.private=this.private),this.announce&&(e.announce=e.announce.concat(this.announce)),this.client.tracker&&n.WEBTORRENT_ANNOUNCE&&!e.private&&(e.announce=e.announce.concat(n.WEBTORRENT_ANNOUNCE)),this.urlList&&(e.urlList=e.urlList.concat(this.urlList)),e.announce=Array.from(new Set(e.announce)),e.urlList=Array.from(new Set(e.urlList)),Object.assign(this,e),this.magnetURI=E.toMagnetURI(e),this.torrentFile=E.toTorrentFile(e)}_onListening(){this.destroyed||(this.info?this._onMetadata(this):(this.xs&&this._getMetadataFromServer(),this._startDiscovery()))}_startDiscovery(){if(this.discovery||this.destroyed)return;let e=this.client.tracker;e&&(e=Object.assign({},this.client.tracker,{getAnnounceOpts:()=>{if(this.destroyed)return;const e={uploaded:this.uploaded,downloaded:this.downloaded,left:Math.max(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.peerAddresses&&this.peerAddresses.forEach((e=>this.addPeer(e))),this.discovery=new m({infoHash:this.infoHash,announce:this.announce,peerId:this.client.peerId,dht:!this.private&&this.client.dht,tracker:e,port:this.client.torrentPort,userAgent:W,lsd:this.client.lsd}),this.discovery.on("error",(e=>{this._destroy(e)})),this.discovery.on("peer",((e,t)=>{this._debug("peer %s discovered via %s",e,t),"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)}))}_getMetadataFromServer(){const e=this,t=(Array.isArray(this.xs)?this.xs:[this.xs]).map((t=>i=>{!function(t,i){if(0!==t.indexOf("http://")&&0!==t.indexOf("https://"))return e.emit("warning",new Error(`skipping non-http xs param: ${t}`)),i(null);const n={url:t,method:"GET",headers:{"user-agent":W}};let r;try{r=v.concat(n,s)}catch(n){return e.emit("warning",new Error(`skipping invalid url xs param: ${t}`)),i(null)}function s(n,r,s){if(e.destroyed)return i(null);if(e.metadata)return i(null);if(n)return e.emit("warning",new Error(`http error from xs param: ${t}`)),i(null);if(200!==r.statusCode)return e.emit("warning",new Error(`non-200 status code ${r.statusCode} from xs param: ${t}`)),i(null);let a;try{a=E(s)}catch(n){}return a?a.infoHash!==e.infoHash?(e.emit("warning",new Error(`got torrent file with incorrect info hash from xs param: ${t}`)),i(null)):(e._onMetadata(a),void i(null)):(e.emit("warning",new Error(`got invalid torrent file from xs param: ${t}`)),i(null))}e._xsRequests.push(r)}(t,i)}));w(t)}_onMetadata(e){if(this.metadata||this.destroyed)return;let t;if(this._debug("got metadata"),this._xsRequests.forEach((e=>{e.abort()})),this._xsRequests=[],e&&e.infoHash)t=e;else try{t=E(e)}catch(e){return this._destroy(e)}this._processParsedTorrent(t),this.metadata=this.torrentFile,this.client.enableWebSeeds&&this.urlList.forEach((e=>{this.addWebSeed(e)})),this._rarityMap=new O(this),this.files=this.files.map((e=>new R(this,e)));let i=this._preloadedStore;if(i||(i=new this._store(this.pieceLength,{...this.storeOpts,torrent:this,path:this.path,files:this.files,length:this.length,name:this.name+" - "+this.infoHash.slice(0,8),addUID:this.addUID})),this._storeCacheSlots>0&&!(i instanceof _)&&(i=new p(i,{max:this._storeCacheSlots})),this.store=new g(i),this.so?this.files.forEach(((e,t)=>{this.so.includes(t)?this.files[t].select():this.files[t].deselect()})):0!==this.pieces.length&&this.select(0,this.pieces.length-1,!1),this._hashes=this.pieces,this.pieces=this.pieces.map(((e,t)=>{const i=t===this.pieces.length-1?this.lastPieceLength:this.pieceLength;return new S(i)})),this._reservations=this.pieces.map((()=>[])),this.bitfield=new u(this.pieces.length),this.emit("metadata"),!this.destroyed)if(this.skipVerify)this._markAllVerified(),this._onStore();else{const e=e=>{if(e)return this._destroy(e);this._debug("done verifying"),this._onStore()};this._debug("verifying existing torrent data"),this._fileModtimes&&this._store===b?this.getFileModtimes(((t,i)=>{if(t)return this._destroy(t);this.files.map(((e,t)=>i[t]===this._fileModtimes[t])).every((e=>e))?(this._markAllVerified(),this._onStore()):this._verifyPieces(e)})):this._verifyPieces(e)}}getFileModtimes(e){const t=[];k(this.files.map(((e,i)=>n=>{const r=this.addUID?c.join(this.name+" - "+this.infoHash.slice(0,8)):c.join(this.path,e.path);s.stat(r,((e,r)=>{if(e&&"ENOENT"!==e.code)return n(e);t[i]=r&&r.mtime.getTime(),n(null)}))})),H,(i=>{this._debug("done getting file modtimes"),e(i,t)}))}_verifyPieces(e){k(this.pieces.map(((e,t)=>e=>{if(this.destroyed)return e(new Error("torrent is destroyed"));const i={};t===this.pieces.length-1&&(i.length=this.lastPieceLength),this.store.get(t,i,((i,n)=>this.destroyed?e(new Error("torrent is destroyed")):i?A((()=>e(null))):void I(n,(i=>{if(this.destroyed)return e(new Error("torrent is destroyed"));i===this._hashes[t]?(this._debug("piece verified %s",t),this._markVerified(t)):this._debug("piece invalid %s",t),e(null)}))))})),H,e)}rescanFiles(e){if(this.destroyed)throw new Error("torrent is destroyed");e||(e=$),this._verifyPieces((t=>{if(t)return this._destroy(t),e(t);this._checkDone(),e(null)}))}_markAllVerified(){for(let e=0;ee))return!0;return!1}_onStore(){this.destroyed||(this._debug("on store"),this._startDiscovery(),this.ready=!0,this.emit("ready"),this._checkDone(),this._updateSelections(),this.wires.forEach((e=>{e.ut_metadata&&e.ut_metadata.setMetadata(this.metadata),this._onWireWithMetadata(e)})))}destroy(e,t){if("function"==typeof e)return this.destroy(null,e);this._destroy(null,e,t)}_destroy(e,t,i){if("function"==typeof t)return this._destroy(e,null,t);if(this.destroyed)return;this.destroyed=!0,this._debug("destroy"),this.client._remove(this),clearInterval(this._rechokeIntervalId),this._xsRequests.forEach((e=>{e.abort()})),this._rarityMap&&this._rarityMap.destroy();for(const e in this._peers)this.removePeer(e);this.files.forEach((e=>{e instanceof R&&e._destroy()}));const n=this._servers.map((e=>t=>{e.destroy(t)}));if(this.discovery&&n.push((e=>{this.discovery.destroy(e)})),this.store){let e=this._destroyStoreOnDestroy;t&&void 0!==t.destroyStore&&(e=t.destroyStore),n.push((t=>{e?this.store.destroy(t):this.store.close(t)}))}w(n,i),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(e){if(this.destroyed)throw new Error("torrent is destroyed");if(!this.infoHash)throw new Error("addPeer() must not be called before the `infoHash` event");let t;if(this.client.blocked){if("string"==typeof e){let i;try{i=l(e)}catch(t){return this._debug("ignoring peer: invalid %s",e),this.emit("invalidPeer",e),!1}t=i[0]}else"string"==typeof e.remoteAddress&&(t=e.remoteAddress);if(t&&this.client.blocked.contains(t))return this._debug("ignoring peer: blocked %s",e),"string"!=typeof e&&e.destroy(),this.emit("blockedPeer",e),!1}const i=this.client.utp&&this._isIPv4(t)?"utp":"tcp",n=!!this._addPeer(e,i);return n?this.emit("peer",e):this.emit("invalidPeer",e),n}_addPeer(e,t){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 i=e&&e.id||e;if(this._peers[i])return this._debug("ignoring peer: duplicate (%s)",i),"string"!=typeof e&&e.destroy(),null;if(this.paused)return this._debug("ignoring peer: torrent is paused"),"string"!=typeof e&&e.destroy(),null;let n;return this._debug("add peer %s",i),n="string"==typeof e?"utp"===t?L.createUTPOutgoingPeer(e,this,this.client.throttleGroups):L.createTCPOutgoingPeer(e,this,this.client.throttleGroups):L.createWebRTCPeer(e,this,this.client.throttleGroups),this._registerPeer(n),"string"==typeof e&&(this._queue.push(n),this._drain()),n}addWebSeed(e){if(this.destroyed)throw new Error("torrent is destroyed");let t,i;if("string"==typeof e){if(t=e,!/^https?:\/\/.+/.test(t))return this.emit("warning",new Error(`ignoring invalid web seed: ${t}`)),void this.emit("invalidPeer",t);if(this._peers[t])return this.emit("warning",new Error(`ignoring duplicate web seed: ${t}`)),void this.emit("invalidPeer",t);i=new q(t,this)}else{if(!e||"string"!=typeof e.connId)return void this.emit("warning",new Error("addWebSeed must be passed a string or connection object with id property"));if(i=e,t=i.connId,this._peers[t])return this.emit("warning",new Error(`ignoring duplicate web seed: ${t}`)),void this.emit("invalidPeer",t)}this._debug("add web seed %s",t);const n=L.createWebSeedPeer(i,t,this,this.client.throttleGroups);this._registerPeer(n),this.emit("peer",t)}_addIncomingPeer(e){return this.destroyed?e.destroy(new Error("torrent is destroyed")):this.paused?e.destroy(new Error("torrent is paused")):(this._debug("add incoming peer %s",e.id),void this._registerPeer(e))}_registerPeer(e){e.on("download",(e=>{this.destroyed||(this.received+=e,this._downloadSpeed(e),this.client._downloadSpeed(e),this.emit("download",e),this.destroyed||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.destroyed||this.client.emit("upload",e))})),this._peers[e.id]=e,this._peersLength+=1}removePeer(e){const t=e&&e.id||e;(e=this._peers[t])&&(this._debug("removePeer %s",t),delete this._peers[t],this._peersLength-=1,e.destroy(),this._drain())}select(e,t,i,n){if(this.destroyed)throw new Error("torrent is destroyed");if(e<0||tt.priority-e.priority)),this._updateSelections()}deselect(e,t,i){if(this.destroyed)throw new Error("torrent is destroyed");i=Number(i)||0,this._debug("deselect %s-%s (priority %s)",e,t,i);for(let n=0;n{if(!this.destroyed&&!this.client.dht.destroyed){if(!e.remoteAddress)return this._debug("ignoring PORT from peer with no address");if(0===i||i>65536)return this._debug("ignoring invalid PORT from peer");this._debug("port: %s (from %s)",i,t),this.client.dht.addNode({host:e.remoteAddress,port:i})}})),e.on("timeout",(()=>{this._debug("wire timeout (%s)",t),e.destroy()})),"webSeed"!==e.type&&e.setTimeout(3e4,!0),e.setKeepAlive(!0),e.use(C(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 B||this.private||(e.use(B()),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 i=this._peers[e];i&&!i.connected&&(this._debug("ut_pex: dropped peer: %s (from %s)",e,t),this.removePeer(e))})),e.once("close",(()=>{e.ut_pex.reset()}))),e.use(y()),this.emit("wire",e,t),this.ready&&A((()=>{this._onWireWithMetadata(e)}))}_onWireWithMetadata(e){let t=null;const i=()=>{this.destroyed||e.destroyed||(this._numQueued>2*(this._numConns-this.numPeers)&&e.amInterested?e.destroy():(t=setTimeout(i,D),t.unref&&t.unref()))};let n;const r=()=>{if(e.peerPieces.buffer.length===this.bitfield.buffer.length){for(n=0;n{r(),this._update(),this._updateWireInterest(e)})),e.on("have",(()=>{r(),this._update(),this._updateWireInterest(e)})),e.lt_donthave.on("donthave",(()=>{r(),this._update(),this._updateWireInterest(e)})),e.on("have-all",(()=>{e.isSeeder=!0,e.choke(),this._update(),this._updateWireInterest(e)})),e.on("have-none",(()=>{e.isSeeder=!1,this._update(),this._updateWireInterest(e)})),e.on("allowed-fast",(e=>{this._update()})),e.once("interested",(()=>{e.unchoke()})),e.once("close",(()=>{clearTimeout(t)})),e.on("choke",(()=>{clearTimeout(t),t=setTimeout(i,D),t.unref&&t.unref()})),e.on("unchoke",(()=>{clearTimeout(t),this._update()})),e.on("request",((t,i,n,r)=>{if(n>131072)return e.destroy();this.pieces[t]||this.store.get(t,{offset:i,length:n},r)})),e.hasFast&&this._hasAllPieces()?e.haveAll():e.hasFast&&this._hasNoPieces()?e.haveNone():e.bitfield(this.bitfield),this._updateWireInterest(e),e.peerExtensions.dht&&this.client.dht&&this.client.dht.listening&&e.port(this.client.dht.address().port),"webSeed"!==e.type&&(t=setTimeout(i,D),t.unref&&t.unref()),e.isSeeder=!1,r()}_updateSelections(){this.ready&&!this.destroyed&&(A((()=>{this._gcSelections()})),this._updateInterest(),this._update())}_gcSelections(){for(let e=0;ethis._updateWireInterest(e))),e!==this._amInterested&&(this._amInterested?this.emit("interested"):this.emit("uninterested"))}_updateWireInterest(e){let t=!1;for(let i=0;i{t._updateWire(e)}),{timeout:250}):t._updateWire(e)}_updateWire(e){const t=this,i=K(e,.5);if(e.requests.length>=i)return;const n=K(e,1);if(e.peerChoking)e.hasFast&&e.peerAllowedFastSet.length>0&&!this._hasMorePieces(e.peerAllowedFastSet.length-1)&&function(){if(e.requests.length>=n)return!1;for(const i of e.peerAllowedFastSet){if(e.peerPieces.get(i)&&!t.bitfield.get(i))for(;t._request(e,i,!1)&&e.requests.length=n.from+n.offset;--s)if(e.peerPieces.get(s)&&t._request(e,s,!1))return}}();a(!1)||a(!0)}function r(t,i,n,r){return s=>s>=t&&s<=i&&!(s in n)&&e.peerPieces.get(s)&&(!r||r(s))}function s(e){let i=e;for(let n=e;n=n)return!0;const a=function(){const i=e.downloadSpeed()||1;if(i>z)return()=>!0;const n=Math.max(1,e.requests.length)*S.BLOCK_LENGTH/i;let r=10,s=0;return e=>{if(!r||t.bitfield.get(e))return!0;let a=t.pieces[e].missing;for(;s0))return r--,!1}return!0}}();for(let o=0;o({wire:e,random:Math.random()}))).sort(((e,t)=>{const i=e.wire,n=t.wire;return i.downloadSpeed()!==n.downloadSpeed()?i.downloadSpeed()-n.downloadSpeed():i.uploadSpeed()!==n.uploadSpeed()?i.uploadSpeed()-n.uploadSpeed():i.amChoking!==n.amChoking?i.amChoking?-1:1:e.random-t.random})).map((e=>e.wire));this._rechokeOptimisticTime<=0?this._rechokeOptimisticWire=null:this._rechokeOptimisticTime-=1;let t=0;for(;e.length>0&&t0){const t=e.filter((e=>e.peerInterested));if(t.length>0){const e=t[(i=t.length,Math.random()*i|0)];e.unchoke(),this._rechokeOptimisticWire=e,this._rechokeOptimisticTime=2}}var i;e.filter((e=>e!==this._rechokeOptimisticWire)).forEach((e=>e.choke()))}_hotswap(e,t){const i=e.downloadSpeed();if(i=z||(2*o>i||o>a||(r=t,a=o))}if(!r)return!1;for(s=0;s=a)return!1;const o=n.pieces[t];let c=s?o.reserveRemaining():o.reserve();if(-1===c&&i&&n._hotswap(e,t)&&(c=s?o.reserveRemaining():o.reserve()),-1===c)return!1;let l=n._reservations[t];l||(l=n._reservations[t]=[]);let u=l.indexOf(null);-1===u&&(u=l.length),l[u]=e;const p=o.chunkOffset(c),d=s?o.chunkLengthRemaining(c):o.chunkLength(c);function f(){A((()=>{n._update()}))}return e.request(t,p,d,(function i(r,a){if(n.destroyed)return;if(!n.ready)return n.once("ready",(()=>{i(r,a)}));if(l[u]===e&&(l[u]=null),o!==n.pieces[t])return f();if(r)return n._debug("error getting piece %s (offset: %s length: %s) from %s: %s",t,p,d,`${e.remoteAddress}:${e.remotePort}`,r.message),s?o.cancelRemaining(c):o.cancel(c),void f();if(n._debug("got piece %s (offset: %s length: %s) from %s",t,p,d,`${e.remoteAddress}:${e.remotePort}`),!o.set(c,a,e))return f();const h=o.flush();I(h,(e=>{n.destroyed||(e===n._hashes[t]?(n._debug("piece verified %s",t),n.store.put(t,h,(e=>{e?n._destroy(e):(n.pieces[t]=null,n._markVerified(t),n.wires.forEach((e=>{e.have(t)})),n._checkDone()&&!n.destroyed&&n.discovery.complete(),f())}))):(n.pieces[t]=new S(o.length),n.emit("warning",new Error(`Piece ${t} failed verification`)),f()))}))})),!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(const t of this._selections){for(let i=t.from;i<=t.to;i++)if(!this.bitfield.get(i)){e=!1;break}if(!e)break}return!this.done&&e?(this.done=!0,this._debug(`torrent done: ${this.infoHash}`),this.emit("done")):this.done=!1,this._gcSelections(),e}load(e,t){if(this.destroyed)throw new Error("torrent is destroyed");if(!this.ready)return this.once("ready",(()=>{this.load(e,t)}));Array.isArray(e)||(e=[e]),t||(t=$);const i=new x(e),n=new d(this.store,this.pieceLength);M(i,n,(e=>{if(e)return t(e);this._markAllVerified(),this._checkDone(),t(null)}))}createServer(e){if("function"!=typeof P)throw new Error("node.js-only method");if(this.destroyed)throw new Error("torrent is destroyed");const t=new P(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?this.client._debugId:"No Client"}] [${this._debugId}] ${e[0]}`,N(...e)}_drain(){if(this._debug("_drain numConns %s maxConns %s",this._numConns,this.client.maxConns),"function"!=typeof a.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("%s connect attempt to %s",e.type,e.addr);const t=l(e.addr),i={host:t[0],port:t[1]};this.client.utp&&"utpOutgoing"===e.type?e.conn=U.connect(i.port,i.host):e.conn=a.connect(i);const n=e.conn;n.once("connect",(()=>{e.onConnect()})),n.once("error",(t=>{e.destroy(t)})),e.startConnectTimeout(),n.on("close",(()=>{if(this.destroyed)return;if(e.retries>=F.length){if(this.client.utp){const t=this._addPeer(e.addr,"tcp");t&&(t.retries=0)}else this._debug("conn %s closed: will not re-add (max %s attempts)",e.addr,F.length);return}const t=F[e.retries];this._debug("conn %s closed: will re-add to queue in %sms (attempt %s)",e.addr,t,e.retries+1);const i=setTimeout((()=>{if(this.destroyed)return;const t=l(e.addr)[0],i=this.client.utp&&this._isIPv4(t)?"utp":"tcp",n=this._addPeer(e.addr,i);n&&(n.retries=e.retries+1)}),t);i.unref&&i.unref()}))}_validAddr(e){let t;try{t=l(e)}catch(e){return!1}const i=t[0],n=t[1];return n>0&&n<65535&&!("127.0.0.1"===i&&n===this.client.torrentPort)}_isIPv4(e){return/^((?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])$/.test(e)}}}).call(this)}).call(this,e("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../package.json":495,"./file.js":490,"./peer.js":491,"./rarity-map.js":492,"./server.js":66,"./utp.js":66,"./webconn.js":494,_process:340,"addr-to-ip-port":2,bitfield:26,"cache-chunk-store":116,"chunk-store-stream/write":132,cpus:136,debug:160,events:192,fs:66,"fs-chunk-store":274,"immediate-chunk-store":244,lt_donthave:255,"memory-chunk-store":274,multistream:308,net:66,os:66,"parse-torrent":331,path:332,pump:348,"queue-microtask":353,"random-iterate":355,"run-parallel":380,"run-parallel-limit":379,"simple-get":393,"simple-sha1":410,throughput:474,"torrent-discovery":477,"torrent-piece":478,ut_metadata:484,ut_pex:66}],494:[function(e,t,i){(function(i){(function(){const{default:n}=e("bitfield"),r=e("debug"),s=e("simple-get"),a=e("lt_donthave"),o=e("simple-sha1"),c=e("bittorrent-protocol"),l=r("webtorrent:webconn"),u=e("../package.json").version;t.exports=class extends c{constructor(e,t){super(),this.url=e,this.connId=e,this.webPeerId=o.sync(e),this._torrent=t,this._init()}_init(){this.setKeepAlive(!0),this.use(a()),this.once("handshake",((e,t)=>{if(this.destroyed)return;this.handshake(e,this.webPeerId);const i=this._torrent.pieces.length,r=new n(i);for(let e=0;e<=i;e++)r.set(e,!0);this.bitfield(r)})),this.once("interested",(()=>{l("interested"),this.unchoke()})),this.on("uninterested",(()=>{l("uninterested")})),this.on("choke",(()=>{l("choke")})),this.on("unchoke",(()=>{l("unchoke")})),this.on("bitfield",(()=>{l("bitfield")})),this.lt_donthave.on("donthave",(()=>{l("donthave")})),this.on("request",((e,t,i,n)=>{l("request pieceIndex=%d offset=%d length=%d",e,t,i),this.httpRequest(e,t,i,((t,i)=>{if(t){this.lt_donthave.donthave(e);const t=setTimeout((()=>{this.destroyed||this.have(e)}),1e4);t.unref&&t.unref()}n(t,i)}))}))}httpRequest(e,t,n,r){const a=e*this._torrent.pieceLength+t,o=a+n-1,c=this._torrent.files;let p;if(c.length<=1)p=[{url:this.url,start:a,end:o}];else{const e=c.filter((e=>e.offset<=o&&e.offset+e.length>a));if(e.length<1)return r(new Error("Could not find file corresponding to web seed range request"));p=e.map((e=>{const t=e.offset+e.length-1;return{url:this.url+("/"===this.url[this.url.length-1]?"":"/")+e.path.replace(this._torrent.path,""),fileOffsetInRange:Math.max(e.offset-a,0),start:Math.max(a-e.offset,0),end:Math.min(t,o-e.offset)}}))}let d,f=0,h=!1;p.length>1&&(d=i.alloc(n)),p.forEach((i=>{const a=i.url,o=i.start,c=i.end;l("Requesting url=%s pieceIndex=%d offset=%d length=%d start=%d end=%d",a,e,t,n,o,c);const m={url:a,method:"GET",headers:{"user-agent":`WebTorrent/${u} (https://webtorrent.io)`,range:`bytes=${o}-${c}`},timeout:6e4};function b(e,t){if(e.statusCode<200||e.statusCode>=300){if(h)return;return h=!0,r(new Error(`Unexpected HTTP status code ${e.statusCode}`))}l("Got data of length %d",t.length),1===p.length?r(null,t):(t.copy(d,i.fileOffsetInRange),++f===p.length&&r(null,d))}s.concat(m,((e,t,i)=>{if(!h)return e?"undefined"==typeof window||a.startsWith(`${window.location.origin}/`)?(h=!0,r(e)):s.head(a,((t,i)=>{if(!h){if(t)return h=!0,r(t);if(i.statusCode<200||i.statusCode>=300)return h=!0,r(new Error(`Unexpected HTTP status code ${i.statusCode}`));if(i.url===a)return h=!0,r(e);m.url=i.url,s.concat(m,((e,t,i)=>{if(!h)return e?(h=!0,r(e)):void b(t,i)}))}})):void b(t,i)}))}))}destroy(){super.destroy(),this._torrent=null}}}).call(this)}).call(this,e("buffer").Buffer)},{"../package.json":495,bitfield:26,"bittorrent-protocol":27,buffer:109,debug:160,lt_donthave:255,"simple-get":393,"simple-sha1":410}],495:[function(e,t,i){t.exports={version:"1.8.22"}},{}],496:[function(e,t,i){t.exports=function e(t,i){if(t&&i)return e(t)(i);if("function"!=typeof t)throw new TypeError("need wrapper function");return Object.keys(t).forEach((function(e){n[e]=t[e]})),n;function n(){for(var e=new Array(arguments.length),i=0;i1080?(P.setProps({placement:"right"}),U.setProps({placement:"right"}),q.setProps({placement:"right"})):(P.setProps({placement:"top"}),U.setProps({placement:"top"}),q.setProps({placement:"top"}))}function H(e){G();try{console.info("Attempting parse"),l=n(e),W(),l.xs&&(console.info("Magnet includes xs, attempting remote parse"),F(l.xs))}catch(t){console.warn(t),"magnet"==c?(console.info("Attempting remote parse"),F(e)):(D.error("Problem parsing input. Is this a .torrent file?"),console.error("Problem parsing input"))}}function F(e){n.remote(e,(function(e,t){if(e)return D.error("Problem remotely fetching that file or parsing result"),console.warn(e),void G();c="remote-torrent-file",m.innerHTML='',b.setContent("Currently loaded information sourced from remotely fetched Torrent file"),l=t,W()}))}function W(){if(console.log(l),w.value=l.infoHash,v.value=l.name?l.name:"",l.created?(y.value=l.created.toISOString().slice(0,19),y.type="datetime-local"):y.type="text",_.value=l.createdBy?" by "+l.createdBy:"",x.value=l.comment?l.comment:"",M.innerHTML="",l.announce&&l.announce.length)for(let e=0;e',n.addEventListener("click",Z),t.appendChild(n),M.appendChild(t)}if(A.innerHTML="",l.urlList&&l.urlList.length)for(let e=0;e',n.addEventListener("click",Z),t.appendChild(n),A.appendChild(t)}if(T.innerHTML="",l.files&&l.files.length){if(C.style.display="none",l.files.length<100)for(let e of l.files){let t=K(s.lookup(e.name));T.appendChild(V(t,e.name,e.length))}else{for(let e=0;e<100;e++){let t=K(s.lookup(l.files[e].name));T.appendChild(V(t,l.files[e].name,l.files[e].length))}T.appendChild(V("","...and another "+(l.files.length-100)+" more files",""))}T.appendChild(V("folder-tree","",l.length)),q.setContent("Download Torrent file"),O.addEventListener("click",te),O.disabled=!1}else N.torrents.length>0?(C.style.display="none",T.innerHTML=''):(C.style.display="block",T.innerHTML=''),q.setContent("Files metadata is required to generate a Torrent file. Try fetching files list from WebTorrent."),O.removeEventListener("click",te),O.disabled=!0;B.setAttribute("data-clipboard-text",window.location.origin+"#"+n.toMagnetURI(l)),R.setAttribute("data-clipboard-text",n.toMagnetURI(l)),u.style.display="none",h.style.display="flex",window.location.hash=n.toMagnetURI(l),l.name?document.title="Torrent Parts | "+l.name:document.title="Torrent Parts | Inspect and edit what's in your Torrent file or Magnet link",b.enable()}function V(e,t,i){let n=document.createElement("tr"),s=document.createElement("td");e&&(s.innerHTML=''),n.appendChild(s);let a=document.createElement("td");a.innerHTML=t,n.appendChild(a);let o=document.createElement("td");return o.innerHTML=r.format(i,{decimalPlaces:1,unitSeparator:" "}),n.appendChild(o),n}function K(e){if(!e)return"file";switch(!0){case e.includes("msword"):case e.includes("wordprocessingml"):case e.includes("opendocument.text"):case e.includes("abiword"):return"file-word";case e.includes("ms-excel"):case e.includes("spreadsheet"):case e.includes("powerpoint"):case e.includes("presentation"):return"file-powerpoint";case e.includes("7z-"):case e.includes("iso9660"):case e.includes("zip"):case e.includes("octet-stream"):return"file-archive";case e.includes("csv"):return"file-csv";case e.includes("pdf"):return"file-pdf";case e.includes("font"):return"file-contract";case e.includes("text"):case e.includes("subrip"):case e.includes("vtt"):return"file-alt";case e.includes("audio"):return"file-audio";case e.includes("image"):return"file-image";case e.includes("video"):return"file-video";default:return"file"}}function $(e){this.dataset.group?l[this.dataset.group][this.dataset.index]=this.value?this.value:"":l[this.id]=this.value?this.value:"",window.location.hash=n.toMagnetURI(l),Q()}function G(){document.getElementById("magnet").value="",document.getElementById("torrent").value="",u.style.display="flex",h.style.display="none",v.value="",y.value="",_.value="",x.value="",w.value="",M.innerHTML="",A.innerHTML="",N.torrents.forEach((e=>e.destroy())),C.style.display="block",T.innerHTML="",window.location.hash="",B.setAttribute("data-clipboard-text",""),R.setAttribute("data-clipboard-text",""),document.title="Torrent Parts | Inspect and edit what's in your Torrent file or Magnet link",b.disable()}async function X(){k.className="disabled",k.innerHTML="Adding...";try{let e=await fetch("https://newtrackon.com/api/stable"),t=await e.text();l.announce=l.announce.concat(t.split("\n\n")),l.announce.push("http://bt1.archive.org:6969/announce"),l.announce.push("http://bt2.archive.org:6969/announce"),l.announce=l.announce.filter(((e,t)=>e&&l.announce.indexOf(e)===t)),D.success("Added known working trackers from newTrackon"),Q()}catch(e){D.error("Problem fetching trackers from newTrackon"),console.warn(e)}k.className="",k.innerHTML="Add Known Working Trackers",W()}function Y(){l[this.dataset.type].unshift(""),W()}function Z(){l[this.parentElement.className].splice(this.parentElement.dataset.index,1),W()}function J(e){l[e]=[],Q(),W()}function Q(){l.created=new Date,l.createdBy="Torrent Parts ",l.created?(y.value=l.created.toISOString().slice(0,19),y.type="datetime-local"):y.type="text",_.value=l.createdBy?" by "+l.createdBy:""}function ee(){console.info("Attempting fetching files from Webtorrent..."),C.style.display="none",l.announce.push("wss://tracker.webtorrent.io"),l.announce.push("wss://tracker.openwebtorrent.com"),l.announce.push("wss://tracker.btorrent.xyz"),l.announce.push("wss://tracker.fastcast.nz"),l.announce=l.announce.filter(((e,t)=>e&&l.announce.indexOf(e)===t)),N.add(n.toMagnetURI(l),(e=>{l.info=Object.assign({},e.info),l.files=e.files,l.infoBuffer=e.infoBuffer,l.length=e.length,l.lastPieceLength=e.lastPieceLength,Q(),W(),D.success("Fetched file details from Webtorrent peers"),e.destroy()})),W()}function te(){let e=n.toTorrentFile(l);if(null!==e&&navigator.msSaveBlob)return navigator.msSaveBlob(new Blob([e],{type:"application/x-bittorrent"}),l.name+".torrent");let t=document.createElement("a");t.style.display="none";let i=window.URL.createObjectURL(new Blob([e],{type:"application/x-bittorrent"}));t.setAttribute("href",i),t.setAttribute("download",l.name+".torrent"),document.body.appendChild(t),t.click(),window.URL.revokeObjectURL(i),t.remove()}window.addEventListener("resize",z),z(),document.addEventListener("DOMContentLoaded",(function(){document.getElementById("magnet").addEventListener("keyup",(function(e){e.preventDefault(),"Enter"===e.key&&(c="magnet",m.innerHTML='',b.setContent("Currently loaded information sourced from Magnet URL"),H(magnet.value))})),document.getElementById("torrent").addEventListener("change",(function(e){e.preventDefault(),e.target.files[0].arrayBuffer().then((function(e){c="torrent-file",m.innerHTML='',b.setContent("Currently loaded information sourced from Torrent file"),H(t.from(e))}))})),document.addEventListener("dragover",(function(e){e.preventDefault()})),document.addEventListener("drop",(function(e){e.preventDefault(),e.dataTransfer.items[0].getAsFile().arrayBuffer().then((function(e){c="torrent-file",m.innerHTML='',b.setContent("Currently loaded information sourced from Torrent file"),H(t.from(e))}))})),p.addEventListener("click",(function(e){e.preventDefault(),D.success("Parsing Ubuntu 20.04 Magnet URL"),c="magnet",m.innerHTML='',b.setContent("Currently loaded information sourced from Magnet URL"),H("magnet:?xt=urn:btih:9fc20b9e98ea98b4a35e6223041a5ef94ea27809&dn=ubuntu-20.04-desktop-amd64.iso&tr=https%3A%2F%2Ftorrent.ubuntu.com%2Fannounce&tr=https%3A%2F%2Fipv6.torrent.ubuntu.com%2Fannounce")})),d.addEventListener("click",(async function(e){e.preventDefault(),D.success("Fetching and Parsing “The WIRED CD” Torrent File..."),c="remote-torrent-file",m.innerHTML='',b.setContent("Currently loaded information sourced from remotely fetched Torrent file"),F("https://webtorrent.io/torrents/wired-cd.torrent")})),f.addEventListener("click",(async function(e){e.preventDefault(),D.success("Parsing Jack Johnson Archive.org Torrent File");let i=await fetch("/ext/jj2008-06-14.mk4_archive.torrent"),n=await i.arrayBuffer();c="torrent-file",m.innerHTML='',b.setContent("Currently loaded information sourced from Torrent file"),H(t.from(n))}));let e=new i("#copyURL");e.on("success",(function(e){D.success("Copied site URL to clipboard!"),console.info(e)})),e.on("failure",(function(e){D.error("Problem copying to clipboard"),console.warn(e)}));let n=new i("#copyMagnet");n.on("success",(function(e){D.success("Copied Magnet URL to clipboard!")})),n.on("failure",(function(e){D.error("Problem copying to clipboard"),console.warn(e)})),v.addEventListener("input",$),v.addEventListener("change",$),v.addEventListener("reset",$),v.addEventListener("paste",$),g.addEventListener("click",G),x.addEventListener("input",$),x.addEventListener("change",$),x.addEventListener("reset",$),x.addEventListener("paste",$),k.addEventListener("click",X),E.addEventListener("click",Y),S.addEventListener("click",(()=>J("announce"))),j.addEventListener("click",Y),I.addEventListener("click",(()=>J("urlList"))),C.addEventListener("click",ee),o("[data-tippy-content]",{theme:"torrent-parts",animation:"shift-away-subtle"}),b.disable(),window.location.hash&&(c="shared-url",m.innerHTML='',b.setContent("Currently loaded information sourced from shared torrent.parts link"),H(window.location.hash.split("#")[1]))}))}).call(this)}).call(this,e("buffer").Buffer)},{buffer:109,bytes:115,clipboard:134,"mime-types":279,"parse-torrent":331,"tippy.js":475,webtorrent:488}]},{},[498]); \ No newline at end of file