All Downloads are FREE. Search and download functionalities are using the official Maven repository.

META-INF.resources.webtorrent.min.js Maven / Gradle / Ivy

var e,t,n={5570:(e,t,n)=>{const s=n(1436),i=n(7007).EventEmitter,r=n(9596);e.exports=class extends i{constructor(e,t){if(t||(t={}),super(),this.chunkLength=Number(e),!this.chunkLength)throw new Error("First argument must be a chunk length");this.closed=!1,this.destroyed=!1,this.length=Number(t.length)||1/0,this.name=t.name||"idb-chunk-store",this.length!==1/0&&(this.lastChunkLength=this.length%this.chunkLength||this.chunkLength,this.lastChunkIndex=Math.ceil(this.length/this.chunkLength)-1),this.dbPromise=s.openDB(this.name,void 0,{upgrade:e=>{e.createObjectStore("chunks")},blocking:()=>{this.close()},terminated:()=>{this.closed=!0,this.emit("error",new Error("Database unexpectedly closed"))}})}put(e,t,n=(()=>{})){if(this.closed)return r((()=>n(new Error("Storage is closed"))));const s=e===this.lastChunkIndex;return s&&t.length!==this.lastChunkLength?r((()=>n(new Error("Last chunk length must be "+this.lastChunkLength)))):s||t.length===this.chunkLength?(0===t.byteOffset&&t.byteLength===t.buffer.byteLength||(t=t.slice()),void(async()=>{try{const n=await this.dbPromise;await n.put("chunks",t,e)}catch(e){return void n(e)}n(null)})()):r((()=>n(new Error("Chunk length must be "+this.chunkLength))))}get(e,t,n=(()=>{})){return"function"==typeof t?this.get(e,{},t):(t||(t={}),this.closed?r((()=>n(new Error("Storage is closed")))):void(async()=>{let s;try{const t=await this.dbPromise;s=await t.get("chunks",e)}catch(e){return void n(e)}if(null==s){const e=new Error("Chunk not found");return e.notFound=!0,void n(e)}const i=t.offset||0,r=t.length||s.length-i;0===i&&r===s.length||(s=s.slice(i,r+i)),n(null,s)})())}close(e=(()=>{})){if(this.closed)return r((()=>e(new Error("Storage is closed"))));this.closed=!0,(async()=>{try{(await this.dbPromise).close()}catch(t){return void e(t)}e(null)})()}destroy(e=(()=>{})){return this.closed?r((()=>e(new Error("Storage is closed")))):this.destroyed?r((()=>e(new Error("Storage is destroyed")))):(this.destroyed=!0,void this.close((async t=>{if(t)e(t);else{try{await s.deleteDB(this.name)}catch(t){return void e(t)}e(null)}})))}}},5682:(e,t,n)=>{const s=n(6209),i=n(943),r=n(1847),o=n(6679),a=n(5435),h=255===new Uint8Array(Uint16Array.of(255).buffer)[0];function c(e){switch(e){case"ascii":return s;case"base64":return i;case"hex":return r;case"utf8":case"utf-8":case void 0:return o;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return a;default:throw new Error(`Unknown encoding: ${e}`)}}function l(e){return e instanceof Uint8Array}function d(e,t,n){return"string"==typeof e?function(e,t){const n=c(t),s=new Uint8Array(n.byteLength(e));return n.write(s,e,0,s.byteLength),s}(e,t):Array.isArray(e)?function(e){const t=new Uint8Array(e.length);return t.set(e),t}(e):ArrayBuffer.isView(e)?function(e){const t=new Uint8Array(e.byteLength);return t.set(e),t}(e):function(e,t,n){return new Uint8Array(e,t,n)}(e,t,n)}function u(e,t,n,s,i){if(0===e.byteLength)return-1;if("string"==typeof n?(s=n,n=0):void 0===n?n=i?0:e.length-1:n<0&&(n+=e.byteLength),n>=e.byteLength){if(i)return-1;n=e.byteLength-1}else if(n<0){if(!i)return-1;n=0}if("string"==typeof t)t=d(t,s);else if("number"==typeof t)return t&=255,i?e.indexOf(t,n):e.lastIndexOf(t,n);if(0===t.byteLength)return-1;if(i){let s=-1;for(let i=n;ie.byteLength&&(n=e.byteLength-t.byteLength);for(let s=n;s>=0;s--){let n=!0;for(let i=0;ii)return 1}return e.byteLength>t.byteLength?1:e.byteLengthe+t.byteLength),0));const n=new Uint8Array(t);let s=0;for(const t of e){if(s+t.byteLength>n.byteLength){const e=t.subarray(0,n.byteLength-s);return n.set(e,s),n}n.set(t,s),s+=t.byteLength}return n},copy:function(e,t,n=0,s=0,i=e.byteLength){if(i>0&&i=e.byteLength)throw new RangeError("sourceStart is out of range");if(i<0)throw new RangeError("sourceEnd is out of range");n>=t.byteLength&&(n=t.byteLength),i>e.byteLength&&(i=e.byteLength),t.byteLength-n=i||s<=n?"":(n<0&&(n=0),s>i&&(s=i),(0!==n||s{function t(e){return e.length}e.exports={byteLength:t,toString:function(e){const t=e.byteLength;let n="";for(let s=0;s{const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",n=new Uint8Array(256);for(let e=0;e<64;e++)n[t.charCodeAt(e)]=e;function s(e){let t=e.length;return 61===e.charCodeAt(t-1)&&t--,t>1&&61===e.charCodeAt(t-1)&&t--,3*t>>>2}n[45]=62,n[95]=63,e.exports={byteLength:s,toString:function(e){const n=e.byteLength;let s="";for(let i=0;i>2]+t[(3&e[i])<<4|e[i+1]>>4]+t[(15&e[i+1])<<2|e[i+2]>>6]+t[63&e[i+2]];return n%3==2?s=s.substring(0,s.length-1)+"=":n%3==1&&(s=s.substring(0,s.length-2)+"=="),s},write:function(e,t,i=0,r=s(t)){const o=Math.min(r,e.byteLength-i);for(let s=0,i=0;i>4,e[i++]=(15&o)<<4|a>>2,e[i++]=(3&a)<<6|63&h}return o}}},1847:e=>{function t(e){return e.length>>>1}function n(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-65+10:e>=97&&e<=102?e-97+10:void 0}e.exports={byteLength:t,toString:function(e){const t=e.byteLength;e=new DataView(e.buffer,e.byteOffset,t);let n="",s=0;for(let i=t-t%4;s{function t(e){return 2*e.length}e.exports={byteLength:t,toString:function(e){const t=e.byteLength;let n="";for(let s=0;s>8,o=i%256;e[s+2*t]=o,e[s+2*t+1]=r}return r}}},6679:e=>{function t(e){let t=0;for(let n=0,s=e.length;n=55296&&i<=56319&&n+1=56320&&s<=57343){t+=4,n++;continue}}t+=i<=127?1:i<=2047?2:3}return t}let n,s;if("undefined"!=typeof TextDecoder){const e=new TextDecoder;n=function(t){return e.decode(t)}}else n=function(e){const t=e.byteLength;let n="",s=0;for(;s0){let t=0;for(;t>s,s-=6;s>=0;)e[a++]=128|t>>s&63,s-=6;o+=t>=65536?2:1}return r};e.exports={byteLength:t,toString:n,write:s}},1467:e=>{function t(e,t){if("string"==typeof e[0])return e.join("");if("number"==typeof e[0])return new Uint8Array(e);const n=new Uint8Array(t);let s=0;for(let t=0,i=e.length;t=n){const e=t(o,a);let s=0;for(;a>=n;)yield e.slice(s,s+n),a-=n,s+=n;o=[e.slice(s,e.length)]}a&&(yield t(o,r?n:a))}},4497:(e,t,n)=>{const s=n(8454),i=n(9596);e.exports=class{constructor(e,t){if(this.store=e,this.chunkLength=e.chunkLength,this.inProgressGets=new Map,!this.store||!this.store.get||!this.store.put)throw new Error("First argument must be abstract-chunk-store compliant");this.cache=new s(t)}put(e,t,n=(()=>{})){if(!this.cache)return i((()=>n(new Error("CacheStore closed"))));this.cache.remove(e),this.store.put(e,t,n)}get(e,t,n=(()=>{})){if("function"==typeof t)return this.get(e,null,t);if(!this.cache)return i((()=>n(new Error("CacheStore closed"))));t||(t={});let s=this.cache.get(e);if(s){const e=t.offset||0,r=t.length||s.length-e;return 0===e&&r===s.length||(s=s.slice(e,r+e)),i((()=>n(null,s)))}let r=this.inProgressGets.get(e);const o=!!r;r||(r=[],this.inProgressGets.set(e,r)),r.push({opts:t,cb:n}),o||this.store.get(e,((t,n)=>{t||null==this.cache||this.cache.set(e,n);const s=this.inProgressGets.get(e);this.inProgressGets.delete(e);for(const{opts:e,cb:i}of s)if(t)i(t);else{const t=e.offset||0,s=e.length||n.length-t;let r=n;0===t&&s===n.length||(r=n.slice(t,s+t)),i(null,r)}}))}close(e=(()=>{})){if(!this.cache)return i((()=>e(new Error("CacheStore closed"))));this.cache=null,this.store.close(e)}destroy(e=(()=>{})){if(!this.cache)return i((()=>e(new Error("CacheStore closed"))));this.cache=null,this.store.destroy(e)}}},4018:e=>{e.exports=function(){for(var e=navigator.hardwareConcurrency||1,t=[],n=0;n{var s=n(717);t.formatArgs=function(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;const n="color: "+this.color;t.splice(1,0,n,"color: inherit");let s=0,i=0;t[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(s++,"%c"===e&&(i=s))})),t.splice(i,0,n)},t.save=function(e){try{e?t.storage.setItem("debug",e):t.storage.removeItem("debug")}catch(e){}},t.load=function(){let e;try{e=t.storage.getItem("debug")}catch(e){}!e&&void 0!==s&&"env"in s&&(e=s.env.DEBUG);return e},t.useColors=function(){if("undefined"!=typeof window&&window.process&&("renderer"===window.process.type||window.process.__nwjs))return!0;if("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;return"undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},t.storage=function(){try{return localStorage}catch(e){}}(),t.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],t.log=console.debug||console.log||(()=>{}),e.exports=n(736)(t);const{formatters:i}=e.exports;i.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}},736:(e,t,n)=>{e.exports=function(e){function t(e){let n,i,r,o=null;function a(...e){if(!a.enabled)return;const s=a,i=Number(new Date),r=i-(n||i);s.diff=r,s.prev=n,s.curr=i,n=i,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let o=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,((n,i)=>{if("%%"===n)return"%";o++;const r=t.formatters[i];if("function"==typeof r){const t=e[o];n=r.call(s,t),e.splice(o,1),o--}return n})),t.formatArgs.call(s,e);(s.log||t.log).apply(s,e)}return a.namespace=e,a.useColors=t.useColors(),a.color=t.selectColor(e),a.extend=s,a.destroy=t.destroy,Object.defineProperty(a,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==o?o:(i!==t.namespaces&&(i=t.namespaces,r=t.enabled(e)),r),set:e=>{o=e}}),"function"==typeof t.init&&t.init(a),a}function s(e,n){const s=t(this.namespace+(void 0===n?":":n)+e);return s.log=this.log,s}function i(e){return e.toString().substring(2,e.toString().length-2).replace(/\.\*\?$/,"*")}return t.debug=t,t.default=t,t.coerce=function(e){if(e instanceof Error)return e.stack||e.message;return e},t.disable=function(){const e=[...t.names.map(i),...t.skips.map(i).map((e=>"-"+e))].join(",");return t.enable(""),e},t.enable=function(e){let n;t.save(e),t.namespaces=e,t.names=[],t.skips=[];const s=("string"==typeof e?e:"").split(/[\s,]+/),i=s.length;for(n=0;n{t[n]=e[n]})),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let n=0;for(let t=0;t{var s=n(717),i=n(3519),r=function(){},o=function(e,t,n){if("function"==typeof t)return o(e,null,t);t||(t={}),n=i(n||r);var a=e._writableState,h=e._readableState,c=t.readable||!1!==t.readable&&e.readable,l=t.writable||!1!==t.writable&&e.writable,d=!1,u=function(){e.writable||f()},f=function(){l=!1,c||n.call(e)},p=function(){c=!1,l||n.call(e)},g=function(t){n.call(e,t?new Error("exited with error code: "+t):null)},m=function(t){n.call(e,t)},_=function(){s.nextTick(y)},y=function(){if(!d)return(!c||h&&h.ended&&!h.destroyed)&&(!l||a&&a.ended&&!a.destroyed)?void 0:n.call(e,new Error("premature close"))},b=function(){e.req.on("finish",f)};return!function(e){return e.setHeader&&"function"==typeof e.abort}(e)?l&&!a&&(e.on("end",u),e.on("close",u)):(e.on("complete",f),e.on("abort",_),e.req?b():e.on("request",b)),function(e){return e.stdio&&Array.isArray(e.stdio)&&3===e.stdio.length}(e)&&e.on("exit",g),e.on("end",p),e.on("finish",f),!1!==t.error&&e.on("error",m),e.on("close",_),function(){d=!0,e.removeListener("complete",f),e.removeListener("abort",_),e.removeListener("request",b),e.req&&e.req.removeListener("finish",f),e.removeListener("end",u),e.removeListener("close",u),e.removeListener("finish",f),e.removeListener("exit",g),e.removeListener("end",p),e.removeListener("error",m),e.removeListener("close",_)}};e.exports=o},6310:e=>{function t(e,t){for(const n in t)Object.defineProperty(e,n,{value:t[n],enumerable:!0,configurable:!0});return e}e.exports=function(e,n,s){if(!e||"string"==typeof e)throw new TypeError("Please pass an Error to err-code");s||(s={}),"object"==typeof n&&(s=n,n=""),n&&(s.code=n);try{return t(e,s)}catch(n){s.message=e.message,s.stack=e.stack;const i=function(){};i.prototype=Object.create(Object.getPrototypeOf(e));return t(new i,s)}}},580:e=>{var t=/["'&<>]/;e.exports=function(e){var n,s=""+e,i=t.exec(s);if(!i)return s;var r="",o=0,a=0;for(o=i.index;o{var t=Object.create||function(e){var t=function(){};return t.prototype=e,new t},n=Object.keys||function(e){var t=[];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.push(n);return n},s=Function.prototype.bind||function(e){var t=this;return function(){return t.apply(e,arguments)}};function i(){this._events&&Object.prototype.hasOwnProperty.call(this,"_events")||(this._events=t(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0}e.exports=i,i.EventEmitter=i,i.prototype._events=void 0,i.prototype._maxListeners=void 0;var r,o=10;try{var a={};Object.defineProperty&&Object.defineProperty(a,"x",{value:0}),r=0===a.x}catch(e){r=!1}function h(e){return void 0===e._maxListeners?i.defaultMaxListeners:e._maxListeners}function c(e,n,s,i){var r,o,a;if("function"!=typeof s)throw new TypeError('"listener" argument must be a function');if((o=e._events)?(o.newListener&&(e.emit("newListener",n,s.listener?s.listener:s),o=e._events),a=o[n]):(o=e._events=t(null),e._eventsCount=0),a){if("function"==typeof a?a=o[n]=i?[s,a]:[a,s]:i?a.unshift(s):a.push(s),!a.warned&&(r=h(e))&&r>0&&a.length>r){a.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+a.length+' "'+String(n)+'" listeners added. Use emitter.setMaxListeners() to increase limit.');c.name="MaxListenersExceededWarning",c.emitter=e,c.type=n,c.count=a.length,"object"==typeof console&&console.warn&&console.warn("%s: %s",c.name,c.message)}}else a=o[n]=s,++e._eventsCount;return e}function l(){if(!this.fired)switch(this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length){case 0:return this.listener.call(this.target);case 1:return this.listener.call(this.target,arguments[0]);case 2:return this.listener.call(this.target,arguments[0],arguments[1]);case 3:return this.listener.call(this.target,arguments[0],arguments[1],arguments[2]);default:for(var e=new Array(arguments.length),t=0;t1&&(t=arguments[1]),t instanceof Error)throw t;var h=new Error('Unhandled "error" event. ('+t+")");throw h.context=t,h}if(!(n=o[e]))return!1;var c="function"==typeof n;switch(s=arguments.length){case 1:!function(e,t,n){if(t)e.call(n);else for(var s=e.length,i=p(e,s),r=0;r=0;o--)if(s[o]===n||s[o].listener===n){a=s[o].listener,r=o;break}if(r<0)return this;0===r?s.shift():function(e,t){for(var n=t,s=n+1,i=e.length;s=0;r--)this.removeListener(e,s[r]);return this},i.prototype.listeners=function(e){return u(this,e,!0)},i.prototype.rawListeners=function(e){return u(this,e,!1)},i.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):f.call(e,t)},i.prototype.listenerCount=f,i.prototype.eventNames=function(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]}},5809:e=>{e.exports=class{constructor(e){if(!(e>0)||e-1&e)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}clear(){this.top=this.btm=0,this.next=null,this.buffer.fill(void 0)}push(e){return void 0===this.buffer[this.top]&&(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){const e=this.buffer[this.btm];if(void 0!==e)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}peek(){return this.buffer[this.btm]}isEmpty(){return void 0===this.buffer[this.btm]}}},6080:(e,t,n)=>{const s=n(5809);e.exports=class{constructor(e){this.hwm=e||16,this.head=new s(this.hwm),this.tail=this.head,this.length=0}clear(){this.head=this.tail,this.head.clear(),this.length=0}push(e){if(this.length++,!this.head.push(e)){const t=this.head;this.head=t.next=new s(2*this.head.buffer.length),this.head.push(e)}}shift(){0!==this.length&&this.length--;const e=this.tail.shift();if(void 0===e&&this.tail.next){const e=this.tail.next;return this.tail.next=null,this.tail=e,this.tail.shift()}return e}peek(){const e=this.tail.peek();return void 0===e&&this.tail.next?this.tail.next.peek():e}isEmpty(){return 0===this.length}}},3468:()=>{"undefined"!=typeof ReadableStream&&(ReadableStream.prototype[Symbol.asyncIterator]||(ReadableStream.prototype[Symbol.asyncIterator]=function({preventCancel:e}={}){const t=this.getReader(),n=this;let s=t.read();return{next(){const e=s;return s=t.read(),e},return:async i=>(await s,t.releaseLock(),e||n.cancel(),{done:!0,value:i}),async throw(e){throw await this.return(),e},[Symbol.asyncIterator](){return this}}}),ReadableStream.prototype.getIterator||(ReadableStream.prototype.getIterator=function({preventCancel:e}={}){return this[Symbol.asyncIterator]({preventCancel:e})}))},1436:(e,t,n)=>{n.r(t),n.d(t,{deleteDB:()=>_,openDB:()=>m,unwrap:()=>g,wrap:()=>p});const s=(e,t)=>t.some((t=>e instanceof t));let i,r;const o=new WeakMap,a=new WeakMap,h=new WeakMap,c=new WeakMap,l=new WeakMap;let d={get(e,t,n){if(e instanceof IDBTransaction){if("done"===t)return a.get(e);if("objectStoreNames"===t)return e.objectStoreNames||h.get(e);if("store"===t)return n.objectStoreNames[1]?void 0:n.objectStore(n.objectStoreNames[0])}return p(e[t])},set:(e,t,n)=>(e[t]=n,!0),has:(e,t)=>e instanceof IDBTransaction&&("done"===t||"store"===t)||t in e};function u(e){return e!==IDBDatabase.prototype.transaction||"objectStoreNames"in IDBTransaction.prototype?(r||(r=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])).includes(e)?function(...t){return e.apply(g(this),t),p(o.get(this))}:function(...t){return p(e.apply(g(this),t))}:function(t,...n){const s=e.call(g(this),t,...n);return h.set(s,t.sort?t.sort():[t]),p(s)}}function f(e){return"function"==typeof e?u(e):(e instanceof IDBTransaction&&function(e){if(a.has(e))return;const t=new Promise(((t,n)=>{const s=()=>{e.removeEventListener("complete",i),e.removeEventListener("error",r),e.removeEventListener("abort",r)},i=()=>{t(),s()},r=()=>{n(e.error||new DOMException("AbortError","AbortError")),s()};e.addEventListener("complete",i),e.addEventListener("error",r),e.addEventListener("abort",r)}));a.set(e,t)}(e),s(e,i||(i=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction]))?new Proxy(e,d):e)}function p(e){if(e instanceof IDBRequest)return function(e){const t=new Promise(((t,n)=>{const s=()=>{e.removeEventListener("success",i),e.removeEventListener("error",r)},i=()=>{t(p(e.result)),s()},r=()=>{n(e.error),s()};e.addEventListener("success",i),e.addEventListener("error",r)}));return t.then((t=>{t instanceof IDBCursor&&o.set(t,e)})).catch((()=>{})),l.set(t,e),t}(e);if(c.has(e))return c.get(e);const t=f(e);return t!==e&&(c.set(e,t),l.set(t,e)),t}const g=e=>l.get(e);function m(e,t,{blocked:n,upgrade:s,blocking:i,terminated:r}={}){const o=indexedDB.open(e,t),a=p(o);return s&&o.addEventListener("upgradeneeded",(e=>{s(p(o.result),e.oldVersion,e.newVersion,p(o.transaction))})),n&&o.addEventListener("blocked",(()=>n())),a.then((e=>{r&&e.addEventListener("close",(()=>r())),i&&e.addEventListener("versionchange",(()=>i()))})).catch((()=>{})),a}function _(e,{blocked:t}={}){const n=indexedDB.deleteDatabase(e);return t&&n.addEventListener("blocked",(()=>t())),p(n).then((()=>{}))}const y=["get","getKey","getAll","getAllKeys","count"],b=["put","add","delete","clear"],w=new Map;function v(e,t){if(!(e instanceof IDBDatabase)||t in e||"string"!=typeof t)return;if(w.get(t))return w.get(t);const n=t.replace(/FromIndex$/,""),s=t!==n,i=b.includes(n);if(!(n in(s?IDBIndex:IDBObjectStore).prototype)||!i&&!y.includes(n))return;const r=async function(e,...t){const r=this.transaction(e,i?"readwrite":"readonly");let o=r.store;return s&&(o=o.index(t.shift())),(await Promise.all([o[n](...t),i&&r.done]))[0]};return w.set(t,r),r}d=(e=>({...e,get:(t,n,s)=>v(t,n)||e.get(t,n,s),has:(t,n)=>!!v(t,n)||e.has(t,n)}))(d)},3714:(e,t,n)=>{const s=n(9596);e.exports=class{constructor(e){if(this.store=e,this.chunkLength=e.chunkLength,!this.store||!this.store.get||!this.store.put)throw new Error("First argument must be abstract-chunk-store compliant");this.mem=[]}put(e,t,n=(()=>{})){this.mem[e]=t,this.store.put(e,t,(t=>{this.mem[e]=null,n(t)}))}get(e,t,n=(()=>{})){if("function"==typeof t)return this.get(e,null,t);let i=this.mem[e];if(!i)return this.store.get(e,t,n);t||(t={});const r=t.offset||0,o=t.length||i.length-r;0===r&&o===i.length||(i=i.slice(r,o+r)),s((()=>n(null,i)))}close(e=(()=>{})){this.store.close(e)}destroy(e=(()=>{})){this.store.destroy(e)}}},6698:e=>{"function"==typeof Object.create?e.exports=function(e,t){t&&(e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:e.exports=function(e,t){if(t){e.super_=t;var n=function(){};n.prototype=t.prototype,e.prototype=new n,e.prototype.constructor=e}}},405:e=>{e.exports=async function*(e){for(let t of e)"function"==typeof t&&(t=t()),yield*t}},9439:(e,t,n)=>{t.RateLimiter=n(3065),t.TokenBucket=n(5472)},3085:(e,t,n)=>{var s=n(717);e.exports=function(){if(void 0!==s&&s.hrtime){var e=s.hrtime(),t=e[0],n=e[1];return 1e3*t+Math.floor(n/1e6)}return(new Date).getTime()}},3065:(e,t,n)=>{var s=n(717),i=n(5472),r=n(3085),o=function(e,t,n){this.tokenBucket=new i(e,e,t,null),this.tokenBucket.content=e,this.curIntervalStart=r(),this.tokensThisInterval=0,this.fireImmediately=n};o.prototype={tokenBucket:null,curIntervalStart:0,tokensThisInterval:0,fireImmediately:!1,removeTokens:function(e,t){if(e>this.tokenBucket.bucketSize)return s.nextTick(t.bind(null,"Requested tokens "+e+" exceeds maximum tokens per interval "+this.tokenBucket.bucketSize,null)),!1;var n=this,i=r();if((i=this.tokenBucket.interval)&&(this.curIntervalStart=i,this.tokensThisInterval=0),e>this.tokenBucket.tokensPerInterval-this.tokensThisInterval){if(this.fireImmediately)s.nextTick(t.bind(null,null,-1));else{var o=Math.ceil(this.curIntervalStart+this.tokenBucket.interval-i);setTimeout((function(){n.tokenBucket.removeTokens(e,a)}),o)}return!1}return this.tokenBucket.removeTokens(e,a);function a(s,i){if(s)return t(s,null);n.tokensThisInterval+=e,t(null,i)}},tryRemoveTokens:function(e){if(e>this.tokenBucket.bucketSize)return!1;var t=r();if((t=this.tokenBucket.interval)&&(this.curIntervalStart=t,this.tokensThisInterval=0),e>this.tokenBucket.tokensPerInterval-this.tokensThisInterval)return!1;var n=this.tokenBucket.tryRemoveTokens(e);return n&&(this.tokensThisInterval+=e),n},getTokensRemaining:function(){return this.tokenBucket.drip(),this.tokenBucket.content}},e.exports=o},5472:(e,t,n)=>{var s=n(717),i=function(e,t,n,s){if(this.bucketSize=e,this.tokensPerInterval=t,"string"==typeof n)switch(n){case"sec":case"second":this.interval=1e3;break;case"min":case"minute":this.interval=6e4;break;case"hr":case"hour":this.interval=36e5;break;case"day":this.interval=864e5;break;default:throw new Error("Invaid interval "+n)}else this.interval=n;this.parentBucket=s,this.content=0,this.lastDrip=+new Date};i.prototype={bucketSize:1,tokensPerInterval:1,interval:1e3,parentBucket:null,content:0,lastDrip:0,removeTokens:function(e,t){var n=this;return this.bucketSize?e>this.bucketSize?(s.nextTick(t.bind(null,"Requested tokens "+e+" exceeds bucket size "+this.bucketSize,null)),!1):(this.drip(),e>this.content?i():this.parentBucket?this.parentBucket.removeTokens(e,(function(s,r){return s?t(s,null):e>n.content?i():(n.content-=e,void t(null,Math.min(r,n.content)))})):(this.content-=e,s.nextTick(t.bind(null,null,this.content)),!0)):(s.nextTick(t.bind(null,null,e,Number.POSITIVE_INFINITY)),!0);function i(){var s=Math.ceil((e-n.content)*(n.interval/n.tokensPerInterval));return setTimeout((function(){n.removeTokens(e,t)}),s),!1}},tryRemoveTokens:function(e){return!this.bucketSize||!(e>this.bucketSize)&&(this.drip(),!(e>this.content)&&(!(this.parentBucket&&!this.parentBucket.tryRemoveTokens(e))&&(this.content-=e,!0)))},drip:function(){if(this.tokensPerInterval){var e=+new Date,t=Math.max(e-this.lastDrip,0);this.lastDrip=e;var n=t*(this.tokensPerInterval/this.interval);this.content=Math.min(this.content+n,this.bucketSize)}else this.content=this.bucketSize}},e.exports=i},8454:(e,t,n)=>{var s=n(7007),i=n(6698);function r(e){if(!(this instanceof r))return new r(e);"number"==typeof e&&(e={max:e}),e||(e={}),s.EventEmitter.call(this),this.cache={},this.head=this.tail=null,this.length=0,this.max=e.max||1e3,this.maxAge=e.maxAge||0}e.exports=r,i(r,s.EventEmitter),Object.defineProperty(r.prototype,"keys",{get:function(){return Object.keys(this.cache)}}),r.prototype.clear=function(){this.cache={},this.head=this.tail=null,this.length=0},r.prototype.remove=function(e){if("string"!=typeof e&&(e=""+e),this.cache.hasOwnProperty(e)){var t=this.cache[e];return delete this.cache[e],this._unlink(e,t.prev,t.next),t.value}},r.prototype._unlink=function(e,t,n){this.length--,0===this.length?this.head=this.tail=null:this.head===e?(this.head=t,this.cache[this.head].next=null):this.tail===e?(this.tail=n,this.cache[this.tail].prev=null):(this.cache[t].next=n,this.cache[n].prev=t)},r.prototype.peek=function(e){if(this.cache.hasOwnProperty(e)){var t=this.cache[e];if(this._checkAge(e,t))return t.value}},r.prototype.set=function(e,t){var n;if("string"!=typeof e&&(e=""+e),this.cache.hasOwnProperty(e)){if((n=this.cache[e]).value=t,this.maxAge&&(n.modified=Date.now()),e===this.head)return t;this._unlink(e,n.prev,n.next)}else n={value:t,modified:0,next:null,prev:null},this.maxAge&&(n.modified=Date.now()),this.cache[e]=n,this.length===this.max&&this.evict();return this.length++,n.next=null,n.prev=this.head,this.head&&(this.cache[this.head].next=e),this.head=e,this.tail||(this.tail=e),t},r.prototype._checkAge=function(e,t){return!(this.maxAge&&Date.now()-t.modified>this.maxAge)||(this.remove(e),this.emit("evict",{key:e,value:t.value}),!1)},r.prototype.get=function(e){if("string"!=typeof e&&(e=""+e),this.cache.hasOwnProperty(e)){var t=this.cache[e];if(this._checkAge(e,t))return this.head!==e&&(e===this.tail?(this.tail=t.next,this.cache[this.tail].prev=null):this.cache[t.prev].next=t.next,this.cache[t.next].prev=t.prev,this.cache[this.head].next=e,t.prev=this.head,t.next=null,this.head=e),t.value}},r.prototype.evict=function(){if(this.tail){var e=this.tail,t=this.remove(this.tail);this.emit("evict",{key:e,value:t})}}},4862:(e,t,n)=>{e.exports=i;const s=n(9596);function i(e,t){if(!(this instanceof i))return new i(e,t);if(t||(t={}),this.chunkLength=Number(e),!this.chunkLength)throw new Error("First argument must be a chunk length");this.chunks=[],this.closed=!1,this.length=Number(t.length)||1/0,this.length!==1/0&&(this.lastChunkLength=this.length%this.chunkLength||this.chunkLength,this.lastChunkIndex=Math.ceil(this.length/this.chunkLength)-1)}i.prototype.put=function(e,t,n=(()=>{})){if(this.closed)return s((()=>n(new Error("Storage is closed"))));const i=e===this.lastChunkIndex;return i&&t.length!==this.lastChunkLength?s((()=>n(new Error("Last chunk length must be "+this.lastChunkLength)))):i||t.length===this.chunkLength?(this.chunks[e]=t,void s((()=>n(null)))):s((()=>n(new Error("Chunk length must be "+this.chunkLength))))},i.prototype.get=function(e,t,n=(()=>{})){if("function"==typeof t)return this.get(e,null,t);if(this.closed)return s((()=>n(new Error("Storage is closed"))));let i=this.chunks[e];if(!i){const e=new Error("Chunk not found");return e.notFound=!0,s((()=>n(e)))}t||(t={});const r=t.offset||0,o=t.length||i.length-r;0===r&&o===i.length||(i=i.slice(r,o+r)),s((()=>n(null,i)))},i.prototype.close=i.prototype.destroy=function(e=(()=>{})){if(this.closed)return s((()=>e(new Error("Storage is closed"))));this.closed=!0,this.chunks=null,s((()=>e(null)))}},8673:e=>{function t(){this._types=Object.create(null),this._extensions=Object.create(null);for(let e=0;e{let s=n(8673);e.exports=new s(n(8446))},8446:e=>{e.exports={"application/andrew-inset":["ez"],"application/applixware":["aw"],"application/atom+xml":["atom"],"application/atomcat+xml":["atomcat"],"application/atomdeleted+xml":["atomdeleted"],"application/atomsvc+xml":["atomsvc"],"application/atsc-dwd+xml":["dwd"],"application/atsc-held+xml":["held"],"application/atsc-rsat+xml":["rsat"],"application/bdoc":["bdoc"],"application/calendar+xml":["xcs"],"application/ccxml+xml":["ccxml"],"application/cdfx+xml":["cdfx"],"application/cdmi-capability":["cdmia"],"application/cdmi-container":["cdmic"],"application/cdmi-domain":["cdmid"],"application/cdmi-object":["cdmio"],"application/cdmi-queue":["cdmiq"],"application/cu-seeme":["cu"],"application/dash+xml":["mpd"],"application/davmount+xml":["davmount"],"application/docbook+xml":["dbk"],"application/dssc+der":["dssc"],"application/dssc+xml":["xdssc"],"application/ecmascript":["es","ecma"],"application/emma+xml":["emma"],"application/emotionml+xml":["emotionml"],"application/epub+zip":["epub"],"application/exi":["exi"],"application/express":["exp"],"application/fdt+xml":["fdt"],"application/font-tdpfr":["pfr"],"application/geo+json":["geojson"],"application/gml+xml":["gml"],"application/gpx+xml":["gpx"],"application/gxf":["gxf"],"application/gzip":["gz"],"application/hjson":["hjson"],"application/hyperstudio":["stk"],"application/inkml+xml":["ink","inkml"],"application/ipfix":["ipfix"],"application/its+xml":["its"],"application/java-archive":["jar","war","ear"],"application/java-serialized-object":["ser"],"application/java-vm":["class"],"application/javascript":["js","mjs"],"application/json":["json","map"],"application/json5":["json5"],"application/jsonml+json":["jsonml"],"application/ld+json":["jsonld"],"application/lgr+xml":["lgr"],"application/lost+xml":["lostxml"],"application/mac-binhex40":["hqx"],"application/mac-compactpro":["cpt"],"application/mads+xml":["mads"],"application/manifest+json":["webmanifest"],"application/marc":["mrc"],"application/marcxml+xml":["mrcx"],"application/mathematica":["ma","nb","mb"],"application/mathml+xml":["mathml"],"application/mbox":["mbox"],"application/mediaservercontrol+xml":["mscml"],"application/metalink+xml":["metalink"],"application/metalink4+xml":["meta4"],"application/mets+xml":["mets"],"application/mmt-aei+xml":["maei"],"application/mmt-usd+xml":["musd"],"application/mods+xml":["mods"],"application/mp21":["m21","mp21"],"application/mp4":["mp4s","m4p"],"application/msword":["doc","dot"],"application/mxf":["mxf"],"application/n-quads":["nq"],"application/n-triples":["nt"],"application/node":["cjs"],"application/octet-stream":["bin","dms","lrf","mar","so","dist","distz","pkg","bpk","dump","elc","deploy","exe","dll","deb","dmg","iso","img","msi","msp","msm","buffer"],"application/oda":["oda"],"application/oebps-package+xml":["opf"],"application/ogg":["ogx"],"application/omdoc+xml":["omdoc"],"application/onenote":["onetoc","onetoc2","onetmp","onepkg"],"application/oxps":["oxps"],"application/p2p-overlay+xml":["relo"],"application/patch-ops-error+xml":["xer"],"application/pdf":["pdf"],"application/pgp-encrypted":["pgp"],"application/pgp-signature":["asc","sig"],"application/pics-rules":["prf"],"application/pkcs10":["p10"],"application/pkcs7-mime":["p7m","p7c"],"application/pkcs7-signature":["p7s"],"application/pkcs8":["p8"],"application/pkix-attr-cert":["ac"],"application/pkix-cert":["cer"],"application/pkix-crl":["crl"],"application/pkix-pkipath":["pkipath"],"application/pkixcmp":["pki"],"application/pls+xml":["pls"],"application/postscript":["ai","eps","ps"],"application/provenance+xml":["provx"],"application/pskc+xml":["pskcxml"],"application/raml+yaml":["raml"],"application/rdf+xml":["rdf","owl"],"application/reginfo+xml":["rif"],"application/relax-ng-compact-syntax":["rnc"],"application/resource-lists+xml":["rl"],"application/resource-lists-diff+xml":["rld"],"application/rls-services+xml":["rs"],"application/route-apd+xml":["rapd"],"application/route-s-tsid+xml":["sls"],"application/route-usd+xml":["rusd"],"application/rpki-ghostbusters":["gbr"],"application/rpki-manifest":["mft"],"application/rpki-roa":["roa"],"application/rsd+xml":["rsd"],"application/rss+xml":["rss"],"application/rtf":["rtf"],"application/sbml+xml":["sbml"],"application/scvp-cv-request":["scq"],"application/scvp-cv-response":["scs"],"application/scvp-vp-request":["spq"],"application/scvp-vp-response":["spp"],"application/sdp":["sdp"],"application/senml+xml":["senmlx"],"application/sensml+xml":["sensmlx"],"application/set-payment-initiation":["setpay"],"application/set-registration-initiation":["setreg"],"application/shf+xml":["shf"],"application/sieve":["siv","sieve"],"application/smil+xml":["smi","smil"],"application/sparql-query":["rq"],"application/sparql-results+xml":["srx"],"application/srgs":["gram"],"application/srgs+xml":["grxml"],"application/sru+xml":["sru"],"application/ssdl+xml":["ssdl"],"application/ssml+xml":["ssml"],"application/swid+xml":["swidtag"],"application/tei+xml":["tei","teicorpus"],"application/thraud+xml":["tfi"],"application/timestamped-data":["tsd"],"application/toml":["toml"],"application/trig":["trig"],"application/ttml+xml":["ttml"],"application/ubjson":["ubj"],"application/urc-ressheet+xml":["rsheet"],"application/urc-targetdesc+xml":["td"],"application/voicexml+xml":["vxml"],"application/wasm":["wasm"],"application/widget":["wgt"],"application/winhlp":["hlp"],"application/wsdl+xml":["wsdl"],"application/wspolicy+xml":["wspolicy"],"application/xaml+xml":["xaml"],"application/xcap-att+xml":["xav"],"application/xcap-caps+xml":["xca"],"application/xcap-diff+xml":["xdf"],"application/xcap-el+xml":["xel"],"application/xcap-ns+xml":["xns"],"application/xenc+xml":["xenc"],"application/xhtml+xml":["xhtml","xht"],"application/xliff+xml":["xlf"],"application/xml":["xml","xsl","xsd","rng"],"application/xml-dtd":["dtd"],"application/xop+xml":["xop"],"application/xproc+xml":["xpl"],"application/xslt+xml":["*xsl","xslt"],"application/xspf+xml":["xspf"],"application/xv+xml":["mxml","xhvml","xvml","xvm"],"application/yang":["yang"],"application/yin+xml":["yin"],"application/zip":["zip"],"audio/3gpp":["*3gpp"],"audio/adpcm":["adp"],"audio/amr":["amr"],"audio/basic":["au","snd"],"audio/midi":["mid","midi","kar","rmi"],"audio/mobile-xmf":["mxmf"],"audio/mp3":["*mp3"],"audio/mp4":["m4a","mp4a"],"audio/mpeg":["mpga","mp2","mp2a","mp3","m2a","m3a"],"audio/ogg":["oga","ogg","spx","opus"],"audio/s3m":["s3m"],"audio/silk":["sil"],"audio/wav":["wav"],"audio/wave":["*wav"],"audio/webm":["weba"],"audio/xm":["xm"],"font/collection":["ttc"],"font/otf":["otf"],"font/ttf":["ttf"],"font/woff":["woff"],"font/woff2":["woff2"],"image/aces":["exr"],"image/apng":["apng"],"image/avif":["avif"],"image/bmp":["bmp"],"image/cgm":["cgm"],"image/dicom-rle":["drle"],"image/emf":["emf"],"image/fits":["fits"],"image/g3fax":["g3"],"image/gif":["gif"],"image/heic":["heic"],"image/heic-sequence":["heics"],"image/heif":["heif"],"image/heif-sequence":["heifs"],"image/hej2k":["hej2"],"image/hsj2":["hsj2"],"image/ief":["ief"],"image/jls":["jls"],"image/jp2":["jp2","jpg2"],"image/jpeg":["jpeg","jpg","jpe"],"image/jph":["jph"],"image/jphc":["jhc"],"image/jpm":["jpm"],"image/jpx":["jpx","jpf"],"image/jxr":["jxr"],"image/jxra":["jxra"],"image/jxrs":["jxrs"],"image/jxs":["jxs"],"image/jxsc":["jxsc"],"image/jxsi":["jxsi"],"image/jxss":["jxss"],"image/ktx":["ktx"],"image/ktx2":["ktx2"],"image/png":["png"],"image/sgi":["sgi"],"image/svg+xml":["svg","svgz"],"image/t38":["t38"],"image/tiff":["tif","tiff"],"image/tiff-fx":["tfx"],"image/webp":["webp"],"image/wmf":["wmf"],"message/disposition-notification":["disposition-notification"],"message/global":["u8msg"],"message/global-delivery-status":["u8dsn"],"message/global-disposition-notification":["u8mdn"],"message/global-headers":["u8hdr"],"message/rfc822":["eml","mime"],"model/3mf":["3mf"],"model/gltf+json":["gltf"],"model/gltf-binary":["glb"],"model/iges":["igs","iges"],"model/mesh":["msh","mesh","silo"],"model/mtl":["mtl"],"model/obj":["obj"],"model/step+xml":["stpx"],"model/step+zip":["stpz"],"model/step-xml+zip":["stpxz"],"model/stl":["stl"],"model/vrml":["wrl","vrml"],"model/x3d+binary":["*x3db","x3dbz"],"model/x3d+fastinfoset":["x3db"],"model/x3d+vrml":["*x3dv","x3dvz"],"model/x3d+xml":["x3d","x3dz"],"model/x3d-vrml":["x3dv"],"text/cache-manifest":["appcache","manifest"],"text/calendar":["ics","ifb"],"text/coffeescript":["coffee","litcoffee"],"text/css":["css"],"text/csv":["csv"],"text/html":["html","htm","shtml"],"text/jade":["jade"],"text/jsx":["jsx"],"text/less":["less"],"text/markdown":["markdown","md"],"text/mathml":["mml"],"text/mdx":["mdx"],"text/n3":["n3"],"text/plain":["txt","text","conf","def","list","log","in","ini"],"text/richtext":["rtx"],"text/rtf":["*rtf"],"text/sgml":["sgml","sgm"],"text/shex":["shex"],"text/slim":["slim","slm"],"text/spdx":["spdx"],"text/stylus":["stylus","styl"],"text/tab-separated-values":["tsv"],"text/troff":["t","tr","roff","man","me","ms"],"text/turtle":["ttl"],"text/uri-list":["uri","uris","urls"],"text/vcard":["vcard"],"text/vtt":["vtt"],"text/xml":["*xml"],"text/yaml":["yaml","yml"],"video/3gpp":["3gp","3gpp"],"video/3gpp2":["3g2"],"video/h261":["h261"],"video/h263":["h263"],"video/h264":["h264"],"video/iso.segment":["m4s"],"video/jpeg":["jpgv"],"video/jpm":["*jpm","jpgm"],"video/mj2":["mj2","mjp2"],"video/mp2t":["ts"],"video/mp4":["mp4","mp4v","mpg4"],"video/mpeg":["mpeg","mpg","mpe","m1v","m2v"],"video/ogg":["ogv"],"video/quicktime":["qt","mov"],"video/webm":["webm"]}},6585:e=>{var t=1e3,n=60*t,s=60*n,i=24*s,r=7*i,o=365.25*i;function a(e,t,n,s){var i=t>=1.5*n;return Math.round(e/n)+" "+s+(i?"s":"")}e.exports=function(e,h){h=h||{};var c=typeof e;if("string"===c&&e.length>0)return function(e){if((e=String(e)).length>100)return;var a=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(!a)return;var h=parseFloat(a[1]);switch((a[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return h*o;case"weeks":case"week":case"w":return h*r;case"days":case"day":case"d":return h*i;case"hours":case"hour":case"hrs":case"hr":case"h":return h*s;case"minutes":case"minute":case"mins":case"min":case"m":return h*n;case"seconds":case"second":case"secs":case"sec":case"s":return h*t;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return h;default:return}}(e);if("number"===c&&isFinite(e))return h.long?function(e){var r=Math.abs(e);if(r>=i)return a(e,r,i,"day");if(r>=s)return a(e,r,s,"hour");if(r>=n)return a(e,r,n,"minute");if(r>=t)return a(e,r,t,"second");return e+" ms"}(e):function(e){var r=Math.abs(e);if(r>=i)return Math.round(e/i)+"d";if(r>=s)return Math.round(e/s)+"h";if(r>=n)return Math.round(e/n)+"m";if(r>=t)return Math.round(e/t)+"s";return e+"ms"}(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))}},3519:(e,t,n)=>{var s=n(6587);function i(e){var t=function(){return t.called?t.value:(t.called=!0,t.value=e.apply(this,arguments))};return t.called=!1,t}function r(e){var t=function(){if(t.called)throw new Error(t.onceError);return t.called=!0,t.value=e.apply(this,arguments)},n=e.name||"Function wrapped with `once`";return t.onceError=n+" shouldn't be called more than once",t.called=!1,t}e.exports=s(i),e.exports.strict=s(r),i.proto=i((function(){Object.defineProperty(Function.prototype,"once",{value:function(){return i(this)},configurable:!0}),Object.defineProperty(Function.prototype,"onceStrict",{value:function(){return r(this)},configurable:!0})}))},8444:e=>{e.exports=function(e){return Math.max(16384,1<{var s=n(717),i=n(3519),r=n(6611),o=n(2376),a=function(){},h=/^v?\.0/.test(s.version),c=function(e){return"function"==typeof e},l=function(e,t,n,s){s=i(s);var l=!1;e.on("close",(function(){l=!0})),r(e,{readable:t,writable:n},(function(e){if(e)return s(e);l=!0,s()}));var d=!1;return function(t){if(!l&&!d)return d=!0,function(e){return!!h&&!!o&&(e instanceof(o.ReadStream||a)||e instanceof(o.WriteStream||a))&&c(e.close)}(e)?e.close(a):function(e){return e.setHeader&&c(e.abort)}(e)?e.abort():c(e.destroy)?e.destroy():void s(t||new Error("stream was destroyed"))}},d=function(e){e()},u=function(e,t){return e.pipe(t)};e.exports=function(){var e,t=Array.prototype.slice.call(arguments),n=c(t[t.length-1]||a)&&t.pop()||a;if(Array.isArray(t[0])&&(t=t[0]),t.length<2)throw new Error("pump requires two streams per minimum");var s=t.map((function(i,r){var o=r0,(function(t){e||(e=t),t&&s.forEach(d),o||(s.forEach(d),n(e))}))}));return t.reduce(u)}},9596:e=>{let t;e.exports="function"==typeof queueMicrotask?queueMicrotask.bind("undefined"!=typeof window?window:globalThis):e=>(t||(t=Promise.resolve())).then(e).catch((e=>setTimeout((()=>{throw e}),0)))},2133:e=>{e.exports="function"==typeof queueMicrotask?queueMicrotask:e=>Promise.resolve().then(e)},7373:e=>{e.exports=function(e){var t=0;return function(){if(t===e.length)return null;var n=e.length-t,s=Math.random()*n|0,i=e[t+s],r=e[t];return e[t]=i,e[t+s]=r,t++,i}}},2878:e=>{function t(e,t){return{start:e.start,end:e.end,index:t}}function n(e){return{start:e.start,end:e.end}}function s(e,t){return e.index-t.index}function i(e,t){return e.start-t.start}e.exports=function(e,r,o){if("string"!=typeof r)throw new TypeError("argument str must be a string");var a=r.indexOf("=");if(-1===a)return-2;var h=r.slice(a+1).split(","),c=[];c.type=r.slice(0,a);for(var l=0;le-1&&(f=e-1),isNaN(u)||isNaN(f)||u>f||u<0||c.push({start:u,end:f})}if(c.length<1)return-1;return o&&o.combine?function(e){for(var r=e.map(t).sort(i),o=0,a=1;ac.end+1?r[++o]=h:h.end>c.end&&(c.end=h.end,c.index=Math.min(c.index,h.index))}r.length=o+1;var l=r.sort(s).map(n);return l.type=e.type,l}(c):c}},8727:e=>{function t(e){return parseInt(e,10)===e}function n(e){function n(t){if(void 0===t){t=new Array(e);for(var n=0;n{e.exports=function(e,t,n){if("number"!=typeof t)throw new Error("second argument must be a Number");let i,r,o,a,h,c,l=!0;Array.isArray(e)?(i=[],o=r=e.length):(a=Object.keys(e),i={},o=r=a.length);function d(e){function t(){n&&n(e,i),n=null}l?s(t):t()}function u(t,n,s){if(i[t]=s,n&&(h=!0),0==--o||n)d(n);else if(!h&&c{e.exports=function(e,t){let n,i,r,o=!0;Array.isArray(e)?(n=[],i=e.length):(r=Object.keys(e),n={},i=r.length);function a(e){function i(){t&&t(e,n),t=null}o?s(i):i()}function h(e,t,s){n[e]=s,(0==--i||t)&&a(t)}i?r?r.forEach((function(t){e[t]((function(e,n){h(t,e,n)}))})):e.forEach((function(e,t){e((function(e,n){h(t,e,n)}))})):a(null);o=!1};const s=n(9596)},7541:(e,t,n)=>{const s=n(8765),i=n(8499);e.exports={Throttle:s,ThrottleGroup:i}},8499:(e,t,n)=>{const{TokenBucket:s}=n(9439),i=n(8765);e.exports=class{constructor(e={}){if("object"!=typeof e)throw new Error("Options must be an object");this.throttles=[],this.setEnabled(e.enabled),this.setRate(e.rate,e.chunksize)}getEnabled(){return this._enabled}getRate(){return this.bucket.tokensPerInterval}getChunksize(){return this.chunksize}setEnabled(e=!0){if("boolean"!=typeof e)throw new Error("Enabled must be a boolean");this._enabled=e;for(const t of this.throttles)t.setEnabled(e)}setRate(e,t=null){if(!Number.isInteger(e)||e<0)throw new Error("Rate must be an integer bigger than zero");if(e=parseInt(e),t&&("number"!=typeof t||t<=0))throw new Error("Chunksize must be bigger than zero");if(t=t||Math.max(parseInt(e/10),1),t=parseInt(t),e>0&&t>e)throw new Error("Chunk size must be smaller than rate");this.bucket||(this.bucket=new s(e,e,"second",null)),this.bucket.bucketSize=e,this.bucket.tokensPerInterval=e,this.chunksize=t}setChunksize(e){if(!Number.isInteger(e)||e<=0)throw new Error("Chunk size must be an integer bigger than zero");const t=this.getRate();if(e=parseInt(e),t>0&&e>t)throw new Error("Chunk size must be smaller than rate");this.chunksize=e}throttle(e={}){if("object"!=typeof e)throw new Error("Options must be an object");return new i({...e,group:this})}destroy(){for(const e of this.throttles)e.destroy();this.throttles=[]}_addThrottle(e){if(!(e instanceof i))throw new Error("Throttle must be an instance of Throttle");this.throttles.push(e)}_removeThrottle(e){const t=this.throttles.indexOf(e);t>-1&&this.throttles.splice(t,1)}}},8765:(e,t,n)=>{const{EventEmitter:s}=n(7007),{Transform:i}=n(8179),{wait:r}=n(2072);e.exports=class extends i{constructor(e={}){if(super(),"object"!=typeof e)throw new Error("Options must be an object");const t=Object.assign({},e);if(t.group&&!(t.group instanceof o))throw new Error("Group must be an instanece of ThrottleGroup");t.group||(t.group=new o(t)),this._setEnabled(t.enabled||t.group.enabled),this._group=t.group,this._emitter=new s,this._destroyed=!1,this._group._addThrottle(this)}getEnabled(){return this._enabled}getGroup(){return this._group}_setEnabled(e=!0){if("boolean"!=typeof e)throw new Error("Enabled must be a boolean");this._enabled=e}setEnabled(e){this._setEnabled(e),this._enabled?this._emitter.emit("enabled"):this._emitter.emit("disabled")}_transform(e,t){this._processChunk(e,t)}async _waitForTokens(e){return new Promise(((t,n)=>{let s=!1;const i=this;function r(e){if(i._emitter.removeListener("disabled",r),i._emitter.removeListener("destroyed",r),!s){if(s=!0,e)return n(e);t()}}this._emitter.once("disabled",r),this._emitter.once("destroyed",r),this._group.bucket.removeTokens(e,r)}))}_areBothEnabled(){return this._enabled&&this._group.getEnabled()}async _processChunk(e,t){if(!this._areBothEnabled())return t(null,e);let n=0,s=this._group.getChunksize(),i=e.slice(n,n+s);for(;i.length>0;){if(this._areBothEnabled())try{for(;0===this._group.getRate()&&!this._destroyed&&this._areBothEnabled();)if(await r(1e3),this._destroyed)return;if(this._areBothEnabled()&&!this._group.bucket.tryRemoveTokens(i.length)&&(await this._waitForTokens(i.length),this._destroyed))return}catch(e){return t(e)}this.push(i),n+=s,s=this._areBothEnabled()?this._group.getChunksize():e.length-n,i=e.slice(n,n+s)}return t()}destroy(...e){this._group._removeThrottle(this),this._destroyed=!0,this._emitter.emit("destroyed"),super.destroy(...e)}};const o=n(8499)},2072:e=>{e.exports={wait:function(e){return new Promise((t=>setTimeout(t,e)))}}},8179:(e,t,n)=>{const{EventEmitter:s}=n(7007),i=new Error("Stream was destroyed"),r=new Error("Premature close"),o=n(2133),a=n(6080),h=n(5335),c=536870911,l=1^c,d=2^c,u=64,f=128,p=256,g=1024,m=2048,_=4096,y=8192,b=16384,w=32768,v=131072,k=131328,x=16^c,S=768^c,E=536838143,C=32^c,A=536739839,P=2<<18,T=4<<18,L=8<<18,I=16<<18,O=32<<18,R=64<<18,N=128<<18,H=256<<18,U=512<<18,M=1024<<18,B=469499903,D=535822335,j=503316479,F=268435455,q=262160,W=536608751,$=8404992,V=14,z=15,G=8405006,K=33587200,Y=33587215,J=2359296,X=270794767,Q=Symbol.asyncIterator||Symbol("asyncIterator");class Z{constructor(e,{highWaterMark:t=16384,map:n=null,mapWritable:s,byteLength:i,byteLengthWritable:r}={}){this.stream=e,this.queue=new a,this.highWaterMark=t,this.buffered=0,this.error=null,this.pipeline=null,this.drains=null,this.byteLength=r||i||xe,this.map=s||n,this.afterWrite=oe.bind(this),this.afterUpdateNextTick=ce.bind(this)}get ended(){return!!(this.stream._duplexState&O)}push(e){return null!==this.map&&(e=this.map(e)),this.buffered+=this.byteLength(e),this.queue.push(e),this.buffered0,this.error=null,this.pipeline=null,this.byteLength=r||i||xe,this.map=s||n,this.pipeTo=null,this.afterRead=ae.bind(this),this.afterUpdateNextTick=he.bind(this)}get ended(){return!!(this.stream._duplexState&b)}pipe(e,t){if(null!==this.pipeTo)throw new Error("Can only pipe to one destination");if("function"!=typeof t&&(t=null),this.stream._duplexState|=512,this.pipeTo=e,this.pipeline=new ne(this.stream,e,t),t&&this.stream.on("error",Se),ke(e))e._writableState.pipeline=this.pipeline,t&&e.on("error",Se),e.on("finish",this.pipeline.finished.bind(this.pipeline));else{const t=this.pipeline.done.bind(this.pipeline,e),n=this.pipeline.done.bind(this.pipeline,e,null);e.on("error",t),e.on("close",n),e.on("finish",this.pipeline.finished.bind(this.pipeline))}e.on("drain",se.bind(this)),this.stream.emit("piping",e),e.emit("pipe",this.stream)}push(e){const t=this.stream;return null===e?(this.highWaterMark=0,t._duplexState=536805311&t._duplexState|1024,!1):(null!==this.map&&null===(e=this.map(e))||(this.buffered+=this.byteLength(e),this.queue.push(e),t._duplexState=536805375&t._duplexState|128),this.buffered0;)t.push(this.shift());for(let e=0;e0;)s.drains.shift().resolve(!1);null!==s.pipeline&&s.pipeline.done(t,e)}}function oe(e){const t=this.stream;e&&t.destroy(e),t._duplexState&=B,null!==this.drains&&function(e){for(let t=0;t=e._readableState.highWaterMark}static isPaused(e){return!(e._duplexState&p)}[Q](){const e=this;let t=null,n=null,s=null;return this.on("error",(e=>{t=e})),this.on("readable",(function(){null!==n&&r(e.read())})),this.on("close",(function(){null!==n&&r(null)})),{[Q](){return this},next:()=>new Promise((function(t,i){n=t,s=i;const o=e.read();null!==o?r(o):8&e._duplexState&&r(null)})),return:()=>o(null),throw:e=>o(e)};function r(r){null!==s&&(t?s(t):null!==r||e._duplexState&b?n({value:r,done:null===r}):s(i),s=n=null)}function o(t){return e.destroy(t),new Promise(((n,s)=>{if(8&e._duplexState)return n({value:void 0,done:!0});e.once("close",(function(){t?s(t):n({value:void 0,done:!0})}))}))}}}class ge extends fe{constructor(e){super(e),this._duplexState|=16385,this._writableState=new Z(this,e),e&&(e.writev&&(this._writev=e.writev),e.write&&(this._write=e.write),e.final&&(this._final=e.final),e.eagerOpen&&this._writableState.updateNextTick())}cork(){this._duplexState|=M}uncork(){this._duplexState&=F,this._writableState.updateNextTick()}_writev(e,t){t(null)}_write(e,t){this._writableState.autoBatch(e,t)}_final(e){e(null)}static isBackpressured(e){return!!(146800654&e._duplexState)}static drained(e){if(e.destroyed)return Promise.resolve(!1);const t=e._writableState;var n;const s=((n=e)._writev!==ge.prototype._writev&&n._writev!==me.prototype._writev?Math.min(1,t.queue.length):t.queue.length)+(e._duplexState&H?1:0);return 0===s?Promise.resolve(!0):(null===t.drains&&(t.drains=[]),new Promise((e=>{t.drains.push({writes:s,resolve:e})})))}write(e){return this._writableState.updateNextTick(),this._writableState.push(e)}end(e){return this._writableState.updateNextTick(),this._writableState.end(e),this}}class me extends pe{constructor(e){super(e),this._duplexState=1|this._duplexState&v,this._writableState=new Z(this,e),e&&(e.writev&&(this._writev=e.writev),e.write&&(this._write=e.write),e.final&&(this._final=e.final))}cork(){this._duplexState|=M}uncork(){this._duplexState&=F,this._writableState.updateNextTick()}_writev(e,t){t(null)}_write(e,t){this._writableState.autoBatch(e,t)}_final(e){e(null)}write(e){return this._writableState.updateNextTick(),this._writableState.push(e)}end(e){return this._writableState.updateNextTick(),this._writableState.end(e),this}}class _e extends me{constructor(e){super(e),this._transformState=new te(this),e&&(e.transform&&(this._transform=e.transform),e.flush&&(this._flush=e.flush))}_write(e,t){this._readableState.buffered>=this._readableState.highWaterMark?this._transformState.data=e:this._transform(e,this._transformState.afterTransform)}_read(e){if(null!==this._transformState.data){const t=this._transformState.data;this._transformState.data=null,e(null),this._transform(t,this._transformState.afterTransform)}else e(null)}destroy(e){super.destroy(e),null!==this._transformState.data&&(this._transformState.data=null,this._transformState.afterTransform())}_transform(e,t){t(null,e)}_flush(e){e(null)}_final(e){this._transformState.afterFinal=e,this._flush(ye.bind(this))}}function ye(e,t){const n=this._transformState.afterFinal;if(e)return n(e);null!=t&&this.push(t),this.push(null),n(null)}function be(e,...t){const n=Array.isArray(e)?[...e,...t]:[e,...t],s=n.length&&"function"==typeof n[n.length-1]?n.pop():null;if(n.length<2)throw new Error("Pipeline requires at least 2 streams");let i=n[0],o=null,a=null;for(let e=1;e1,c),i.pipe(o)),i=o;if(s){let e=!1;const t=ke(o)||!(!o._writableState||!o._writableState.autoDestroy);o.on("error",(e=>{null===a&&(a=e)})),o.on("finish",(()=>{e=!0,t||s(a)})),t&&o.on("close",(()=>s(a||(e?null:r))))}return o;function h(e,t,n,s){e.on("error",s),e.on("close",(function(){if(t&&e._readableState&&!e._readableState.ended)return s(r);if(n&&e._writableState&&!e._writableState.ended)return s(r)}))}function c(e){if(e&&!a){a=e;for(const t of n)t.destroy(e)}}}function we(e){return e}function ve(e){return!!e._readableState||!!e._writableState}function ke(e){return"number"==typeof e._duplexState&&ve(e)}function xe(e){return function(e){return"object"==typeof e&&null!==e&&"number"==typeof e.byteLength}(e)?e.byteLength:1024}function Se(){}function Ee(){this.destroy(new Error("Stream aborted."))}e.exports={pipeline:be,pipelinePromise:function(...e){return new Promise(((t,n)=>be(...e,(e=>{if(e)return n(e);t()}))))},isStream:ve,isStreamx:ke,getStreamError:function(e){const t=e._readableState&&e._readableState.error||e._writableState&&e._writableState.error;return t===i?null:t},Stream:fe,Writable:ge,Readable:pe,Duplex:me,Transform:_e,PassThrough:class extends _e{}}},5335:(e,t,n)=>{const s=n(4611),i=n(6045);e.exports=class{constructor(e="utf8"){switch(this.encoding=function(e){switch(e=e.toLowerCase()){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return e;default:throw new Error("Unknown encoding: "+e)}}(e),this.encoding){case"utf8":this.decoder=new i;break;case"utf16le":case"base64":throw new Error("Unsupported encoding: "+this.encoding);default:this.decoder=new s(this.encoding)}}push(e){return"string"==typeof e?e:this.decoder.decode(e)}write(e){return this.push(e)}end(e){let t="";return e&&(t=this.push(e)),t+=this.decoder.flush(),t}}},4611:(e,t,n)=>{const s=n(5682);e.exports=class{constructor(e){this.encoding=e}decode(e){return s.toString(e,this.encoding)}flush(){return""}}},6045:(e,t,n)=>{const s=n(5682);e.exports=class{constructor(){this.codePoint=0,this.bytesSeen=0,this.bytesNeeded=0,this.lowerBoundary=128,this.upperBoundary=191}decode(e){if(0===this.bytesNeeded){let t=!0;for(let n=Math.max(0,e.byteLength-4),s=e.byteLength;nthis.upperBoundary?(this.codePoint=0,this.bytesNeeded=0,this.bytesSeen=0,this.lowerBoundary=128,this.upperBoundary=191,t+="�"):(this.lowerBoundary=128,this.upperBoundary=191,this.codePoint=this.codePoint<<6|63&s,this.bytesSeen++,this.bytesSeen===this.bytesNeeded&&(t+=String.fromCodePoint(this.codePoint),this.codePoint=0,this.bytesNeeded=0,this.bytesSeen=0)):s<=127?t+=String.fromCharCode(s):s>=194&&s<=223?(this.bytesNeeded=1,this.codePoint=31&s):s>=224&&s<=239?(224===s?this.lowerBoundary=160:237===s&&(this.upperBoundary=159),this.bytesNeeded=2,this.codePoint=15&s):s>=240&&s<=244?(240===s&&(this.lowerBoundary=144),244===s&&(this.upperBoundary=143),this.bytesNeeded=3,this.codePoint=7&s):t+="�"}return t}flush(){const e=this.bytesNeeded>0?"�":"";return this.codePoint=0,this.bytesNeeded=0,this.bytesSeen=0,this.lowerBoundary=128,this.upperBoundary=191,e}}},1035:e=>{function t(e){return(+Date.now()-e)/100&65535}e.exports=function(e){const n=+Date.now(),s=10*(e||5),i=[0];let r=1,o=t(n)-1&65535;return function(e){const a=t(n);let h=a-o&65535;for(h>s&&(h=s),o=a;h--;)r===s&&(r=0),i[r]=i[0===r?s-1:r-1],r++;e&&(i[r-1]+=e);const c=i[r-1],l=i.length{e.exports=function(e,t){if(t>=e.length||t<0)return;var n=e.pop();if(t{e.exports=function e(t,n){if(t&&n)return e(t)(n);if("function"!=typeof t)throw new TypeError("need wrapper function");return Object.keys(t).forEach((function(e){s[e]=t[e]})),s;function s(){for(var e=new Array(arguments.length),n=0;n{},6686:()=>{},4043:()=>{},7828:()=>{},6889:()=>{},8878:()=>{},2701:()=>{},7264:()=>{},1551:()=>{},826:()=>{},61:()=>{},7936:()=>{},2532:()=>{},2123:()=>{},3208:()=>{},2376:()=>{},3970:()=>{},2799:()=>{},8271:()=>{},3278:()=>{},6664:()=>{},1827:()=>{},6819:(e,t,n)=>{e.exports=n(8330).version},5658:(e,t,n)=>{n.r(t),n.d(t,{default:()=>m,enableSecure:()=>g});var s=n(7007),i=n(8179),r=n(1314),o=n(7833),a=n(6458);const h="tcpIncoming",c="tcpOutgoing",l="utpIncoming",d="utpOutgoing",u="webSeed",f=o("webtorrent:peer");let p=!1;const g=()=>{p=!0};class m extends s{constructor(e,t){super(),this.id=e,this.type=t,f("new %s Peer %s",t,e),this.addr=null,this.conn=null,this.swarm=null,this.wire=null,this.source=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,f("Peer %s connected",this.id),clearTimeout(this.connectTimeout);const e=this.conn;e.once("end",(()=>{this.destroy()})),e.once("close",(()=>{this.destroy()})),e.once("finish",(()=>{this.destroy()})),e.once("error",(e=>{this.destroy(e)}));const t=this.wire=new a.A(this.type,this.retries,p);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?p&&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;(0,i.pipeline)(this.conn,this.throttleGroups.down.throttle(),new i.Transform({transform(t,n){e.emit("download",t.length),e.destroyed||n(null,t)}}),this.wire,this.throttleGroups.up.throttle(),new i.Transform({transform(t,n){e.emit("upload",t.length),e.destroyed||n(null,t)}}),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"));f("Peer %s got handshake %s",this.id,e),clearTimeout(this.handshakeTimeout),this.retries=0;let n=this.addr;!n&&this.conn.remoteAddress&&this.conn.remotePort&&(n=`${this.conn.remoteAddress}:${this.conn.remotePort}`),this.swarm._onWire(this.wire,n),this.swarm&&!this.swarm.destroyed&&(this.sentHandshake||this.handshake())}handshake(){const e={dht:!this.swarm.private&&!!this.swarm.client.dht,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,f("destroy %s %s (error: %s)",this.type,this.id,e&&(e.message||e)),clearTimeout(this.connectTimeout),clearTimeout(this.handshakeTimeout);const t=this.swarm,n=this.conn,s=this.wire;this.swarm=null,this.conn=null,this.wire=null,t&&s&&r(t.wires,t.wires.indexOf(s)),n&&(n.on("error",(()=>{})),n.destroy()),s&&s.destroy(),t&&t.removePeer(this.id)}}m.TYPE_TCP_INCOMING=h,m.TYPE_TCP_OUTGOING=c,m.TYPE_UTP_INCOMING=l,m.TYPE_UTP_OUTGOING=d,m.TYPE_WEBRTC="webrtc",m.TYPE_WEBSEED=u,m.SOURCE_MANUAL="manual",m.SOURCE_TRACKER="tracker",m.SOURCE_DHT="dht",m.SOURCE_LSD="lsd",m.SOURCE_UT_PEX="ut_pex",m.createWebRTCPeer=(e,t,n)=>{const s=new m(e.id,"webrtc");if(s.conn=e,s.swarm=t,s.throttleGroups=n,s.conn.connected)s.onConnect();else{const e=()=>{s.conn.removeListener("connect",t),s.conn.removeListener("error",n)},t=()=>{e(),s.onConnect()},n=t=>{e(),s.destroy(t)};s.conn.once("connect",t),s.conn.once("error",n),s.startConnectTimeout()}return s},m.createTCPIncomingPeer=(e,t)=>m._createIncomingPeer(e,h,t),m.createUTPIncomingPeer=(e,t)=>m._createIncomingPeer(e,l,t),m.createTCPOutgoingPeer=(e,t,n)=>m._createOutgoingPeer(e,t,c,n),m.createUTPOutgoingPeer=(e,t,n)=>m._createOutgoingPeer(e,t,d,n),m._createIncomingPeer=(e,t,n)=>{const s=`${e.remoteAddress}:${e.remotePort}`,i=new m(s,t);return i.conn=e,i.addr=s,i.throttleGroups=n,i.onConnect(),i},m._createOutgoingPeer=(e,t,n,s)=>{const i=new m(e,n);return i.addr=e,i.swarm=t,i.throttleGroups=s,i},m.createWebSeedPeer=(e,t,n,s)=>{const i=new m(t,u);return i.swarm=n,i.conn=e,i.throttleGroups=s,i.onConnect(),i}},988:(e,t,n)=>{n.d(t,{A:()=>p});var s=n(9639);function i(e){const t=e<0?1:0;return e=Math.abs(Number(e||1)),Math.floor(Math.log10(e))+1+t}function r(e){return ArrayBuffer.isView(e)?"arraybufferview":Array.isArray(e)?"array":e instanceof Number?"number":e instanceof Boolean?"boolean":e instanceof Set?"set":e instanceof Map?"map":e instanceof String?"string":e instanceof ArrayBuffer?"arraybuffer":typeof e}function o(e,t,n){const i=[];let r=null;return o._encode(i,e),r=(0,s.xW)(i),o.bytes=r.length,ArrayBuffer.isView(t)?(t.set(r,n),t):r}o.bytes=-1,o._floatConversionDetected=!1,o._encode=function(e,t){if(null!=t)switch(r(t)){case"object":o.dict(e,t);break;case"map":o.dictMap(e,t);break;case"array":o.list(e,t);break;case"set":o.listSet(e,t);break;case"string":o.string(e,t);break;case"number":case"boolean":o.number(e,t);break;case"arraybufferview":o.buffer(e,new Uint8Array(t.buffer,t.byteOffset,t.byteLength));break;case"arraybuffer":o.buffer(e,new Uint8Array(t))}};const a=new Uint8Array([101]),h=new Uint8Array([100]),c=new Uint8Array([108]);o.buffer=function(e,t){e.push((0,s.L0)(t.length+":"),t)},o.string=function(e,t){e.push((0,s.L0)((0,s.L0)(t).byteLength+":"+t))},o.number=function(e,t){if(Number.isInteger(t))return e.push((0,s.L0)("i"+BigInt(t)+"e"));const n=2147483648,i=(t/n|0)*n+(t%n|0);e.push((0,s.L0)("i"+i+"e")),i===t||o._floatConversionDetected||(o._floatConversionDetected=!0,console.warn('WARNING: Possible data corruption detected with value "'+t+'":','Bencoding only defines support for integers, value was converted to "'+i+'"'),console.trace())},o.dict=function(e,t){e.push(h);let n,s=0;const i=Object.keys(t).sort(),r=i.length;for(;s=48)s=10*s+(n-48);else if(r!==t||43!==n){if(r!==t||45!==n){if(46===n)break;throw new Error("not a number: buffer["+r+"] = "+n)}i=-1}}return s*i}function u(e,t,n,i){return null==e||0===e.length?null:("number"!=typeof t&&null==i&&(i=t,t=void 0),"number"!=typeof n&&null==i&&(i=n,n=void 0),u.position=0,u.encoding=i||null,u.data=ArrayBuffer.isView(e)?new Uint8Array(e.slice(t,n)):(0,s.L0)(e),u.bytes=u.data.length,u.next())}u.bytes=0,u.position=0,u.data=null,u.encoding=null,u.next=function(){switch(u.data[u.position]){case 100:return u.dictionary();case 108:return u.list();case 105:return u.integer();default:return u.buffer()}},u.find=function(e){let t=u.position;const n=u.data.length,s=u.data;for(;t{function s(e){return(e>>3)+Number(e%8!=0)}n.d(t,{A:()=>i});class i{get length(){return this.buffer.length<<3}constructor(e=0,t){const n=null==t?void 0:t.grow;this.grow=n?Number.isFinite(n)?s(n):n:0,this.buffer="number"==typeof e?new Uint8Array(s(e)):e}get(e){const t=e>>3;return t>e%8)}set(e,t=!0){const n=e>>3;if(t){if(n>=this.buffer.length){const e=Math.max(n+1,Math.min(2*this.buffer.length,this.grow));if(e<=this.grow){const t=new Uint8Array(e);t.set(this.buffer),this.buffer=t}}this.buffer[n]|=128>>e%8}else n>e%8))}setAll(e,t=0){const n=Math.min(s(t+e.length),this.grow);if(this.buffer.length>3,r=128>>t%8;for(let t=0;t=this.buffer.length)break;r=128}else r>>=1}forEach(e,t=0,n=8*this.buffer.length){let s=t>>3,i=128>>t%8;for(let r=t;r>=1}isEmpty(){for(let e=0;e{n.d(t,{A:()=>L});var s=n(988),i=n(3033),r=n(7264),o=n(7833),a=n(8727),h=n(8179),c=n(9639),l=n(1035),d=n(1314);const u=o("bittorrent-protocol"),f=(0,c.L0)("BitTorrent protocol"),p=new Uint8Array([0,0,0,0]),g=new Uint8Array([0,0,0,1,0]),m=new Uint8Array([0,0,0,1,1]),_=new Uint8Array([0,0,0,1,2]),y=new Uint8Array([0,0,0,1,3]),b=[0,0,0,0,0,0,0,0],w=[0,0,0,3,9,0,0],v=new Uint8Array([0,0,0,1,14]),k=new Uint8Array([0,0,0,1,15]),x=new Uint8Array([0,0,0,0,0,0,0,0]),S=new Uint8Array([0,0,1,2]),E=new Uint8Array([0,0,0,2]);function C(e,t){for(let n=e.length;n--;)e[n]^=t[n];return e}class A{constructor(e,t,n,s){this.piece=e,this.offset=t,this.length=n,this.callback=s}}class P{constructor(){this.buffer=new Uint8Array}get(e){return!0}set(e){}}class T extends h.Duplex{constructor(e=null,t=0,n=!1){super(),this._debugId=(0,c.V5)((0,c.po)(4)),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 i.A(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=l(),this.downloadSpeed=l(),this._keepAliveInterval=null,this._timeout=null,this._timeoutMs=0,this._timeoutExpiresAt=null,this._finished=!1,this._parserSize=0,this._parser=null,this._buffer=[],this._bufferSize=0,this._peEnabled=n,n?(this._dh=r.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._debug("destroy"),this.end(),this}end(e){if(!this.destroyed&&!this.destroying)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 n=this._nextExt,s=new e(this);function i(){}"function"!=typeof s.onHandshake&&(s.onHandshake=i),"function"!=typeof s.onExtendedHandshake&&(s.onExtendedHandshake=i),"function"!=typeof s.onMessage&&(s.onMessage=i),this.extendedMapping[n]=t,this._ext[t]=s,this[t]=s,this._nextExt+=1}keepAlive(){this._debug("keep-alive"),this._push(p)}sendPe1(){if(this._peEnabled){const e=Math.floor(513*Math.random()),t=(0,c.po)(e);this._push((0,c.xW)([(0,c.fk)(this._myPubKey),t]))}}sendPe2(){const e=Math.floor(513*Math.random()),t=(0,c.po)(e);this._push((0,c.xW)([(0,c.fk)(this._myPubKey),t]))}async sendPe3(e){await this.setEncrypt(this._sharedSecret,e);const t=await(0,c.tW)((0,c.fk)(this._utfToHex("req1")+this._sharedSecret)),n=C(await(0,c.tW)((0,c.fk)(this._utfToHex("req2")+e)),await(0,c.tW)((0,c.fk)(this._utfToHex("req3")+this._sharedSecret))),s=new DataView((0,c.po)(2).buffer).getUint16(0)%512,i=(0,c.po)(s);let r=new Uint8Array(14+s+2);r.set(x),r.set(S,8);const o=new DataView(r.buffer);o.setInt16(12,s),i.copy(r,14),o.setInt16(14+s,0),r=this._encryptHandshake(r),this._push((0,c.xW)([t,n,r]))}async sendPe4(e){await this.setEncrypt(this._sharedSecret,e);const t=new DataView((0,c.po)(2).buffer).getUint16(0)%512,n=(0,c.po)(t);let s=new Uint8Array(14+t);const i=new DataView(s.buffer);s.set(x),s.set(E,8),i.setInt16(12,t),s.set(n,14),s=this._encryptHandshake(s),this._push(s),this._cryptoHandshakeDone=!0,this._debug("completed crypto handshake")}handshake(e,t,n){let s,i;if("string"==typeof e?(e=e.toLowerCase(),s=(0,c.fk)(e)):(s=e,e=(0,c.V5)(s)),"string"==typeof t?i=(0,c.fk)(t):(i=t,t=(0,c.V5)(i)),this._infoHash=s,20!==s.length||20!==i.length)throw new Error("infoHash and peerId MUST have length 20");this._debug("handshake i=%s p=%s exts=%o",e,t,n);const r=new Uint8Array(b);this.extensions={extended:!0,dht:!(!n||!n.dht),fast:!(!n||!n.fast)},r[5]|=16,this.extensions.dht&&(r[7]|=1),this.extensions.fast&&(r[7]|=4),this.extensions.fast&&this.peerExtensions.fast&&(this._debug("fast extension is enabled"),this.hasFast=!0),this._push((0,c.xW)([f,r,s,i])),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 n=this.extendedMapping[t];e.m[n]=Number(t)}this.extended(0,s.A.encode(e)),this._extendedHandshakeSent=!0}choke(){if(!this.amChoking)if(this.amChoking=!0,this._debug("choke"),this._push(g),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(m))}interested(){this.amInterested||(this.amInterested=!0,this._debug("interested"),this._push(_))}uninterested(){this.amInterested&&(this.amInterested=!1,this._debug("uninterested"),this._push(y))}have(e){this._debug("have %d",e),this._message(4,[e],null)}bitfield(e){this._debug("bitfield"),ArrayBuffer.isView(e)||(e=e.buffer),this._message(5,[],e)}request(e,t,n,s){return s||(s=()=>{}),this._finished?s(new Error("wire is closed")):!this.peerChoking||this.hasFast&&this.peerAllowedFastSet.includes(e)?(this._debug("request index=%d offset=%d length=%d",e,t,n),this.requests.push(new A(e,t,n,s)),this._timeout||this._resetTimeout(!0),void this._message(6,[e,t,n],null)):s(new Error("peer is choking"))}piece(e,t,n){this._debug("piece index=%d offset=%d",e,t),this._message(7,[e,t],n),this.uploaded+=n.length,this.uploadSpeed(n.length),this.emit("upload",n.length)}cancel(e,t,n){this._debug("cancel index=%d offset=%d length=%d",e,t,n),this._callback(this._pull(this.requests,e,t,n),new Error("request was cancelled"),null),this._message(8,[e,t,n],null)}port(e){this._debug("port %d",e);const t=new Uint8Array(w);new DataView(t.buffer).setUint16(5,e),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(v)}haveNone(){if(!this.hasFast)throw Error("fast extension is disabled");this._debug("have-none"),this._push(k)}reject(e,t,n){if(!this.hasFast)throw Error("fast extension is disabled");this._debug("reject index=%d offset=%d length=%d",e,t,n),this._pull(this.peerRequests,e,t,n),this._message(16,[e,t,n],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=new Uint8Array([e]),i=ArrayBuffer.isView(t)?t:s.A.encode(t);this._message(20,[],(0,c.xW)([n,i]))}}async setEncrypt(e,t){let n,s,i,r;switch(this.type){case"tcpIncoming":n=await(0,c.tW)((0,c.fk)(this._utfToHex("keyB")+e+t)),i=await(0,c.tW)((0,c.fk)(this._utfToHex("keyA")+e+t)),s=[];for(const e of n.values())s.push(e);r=[];for(const e of i.values())r.push(e);this._encryptGenerator=new a(s),this._decryptGenerator=new a(r);break;case"tcpOutgoing":n=await(0,c.tW)((0,c.fk)(this._utfToHex("keyA")+e+t)),i=await(0,c.tW)((0,c.fk)(this._utfToHex("keyB")+e+t)),s=[];for(const e of n.values())s.push(e);r=[];for(const e of i.values())r.push(e);this._encryptGenerator=new a(s),this._decryptGenerator=new a(r);break;default:return!1}for(let e=0;e<1024;e++)this._encryptGenerator.randomByte(),this._decryptGenerator.randomByte();return this._setGenerators=!0,!0}_message(e,t,n){const s=n?n.length:0,i=new Uint8Array(5+4*t.length),r=new DataView(i.buffer);r.setUint32(0,i.length+s-4),i[4]=e;for(let e=0;e{if(i===this._pull(this.peerRequests,e,t,n))return s?(this._debug("error satisfying request index=%d offset=%d length=%d (%s)",e,t,n,s.message),void(this.hasFast&&this.reject(e,t,n))):void this.piece(e,t,r)},i=new A(e,t,n,s);this.peerRequests.push(i),this.emit("request",e,t,n,s)}_onPiece(e,t,n){this._debug("got piece index=%d offset=%d",e,t),this._callback(this._pull(this.requests,e,t,n.length),null,n),this.downloaded+=n.length,this.downloadSpeed(n.length),this.emit("download",n.length),this.emit("piece",e,t,n)}_onCancel(e,t,n){this._debug("got cancel index=%d offset=%d length=%d",e,t,n),this._pull(this.peerRequests,e,t,n),this.emit("cancel",e,t,n)}_onPort(e){this._debug("got port %d",e),this.emit("port",e)}_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 P,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,n){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,n),this._callback(this._pull(this.requests,e,t,n),new Error("request was rejected"),null),this.emit("reject",e,t,n)}_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=s.A.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){if(2===this._encryptionMethod&&this._cryptoHandshakeDone&&(e=this._decrypt(e)),this._bufferSize+=e.length,this._buffer.push(e),this._buffer.length>1&&(this._buffer=[(0,c.xW)(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(new Uint8Array);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))}t(null)}_callback(e,t,n){e&&(this._resetTimeout(!this.peerChoking&&!this._finished),e.callback(t,n))}_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=new DataView(e.buffer,e.byteOffset,e.byteLength).getUint32(0);t>0?this._parse(t,this._onMessage):(this._onKeepAlive(),this._parse(4,this._onMessageLength))}_onMessage(e){this._parse(4,this._onMessageLength);const t=new DataView(e.buffer,e.byteOffset,e.byteLength);switch(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(t.getUint32(1));case 5:return this._onBitField(e.slice(1));case 6:return this._onRequest(t.getUint32(1),t.getUint32(5),t.getUint32(9));case 7:return this._onPiece(t.getUint32(1),t.getUint32(5),e.slice(9));case 8:return this._onCancel(t.getUint32(1),t.getUint32(5),t.getUint32(9));case 9:return this._onPort(t.getUint16(1));case 13:return this._onSuggest(t.getUint32(1));case 14:return this._onHaveAll();case 15:return this._onHaveNone();case 16:return this._onReject(t.getUint32(1),t.getUint32(5),t.getUint32(9));case 17:return this._onAllowedFast(t.getUint32(1));case 20:return this._onExtended(e[1],e.slice(2));default:return this._debug("got unknown message"),this.emit("unknownmessage",e)}}_determineHandshakeType(){this._parse(1,(e=>{const t=e[0];19===t?this._parse(t+48,this._onHandshakeBuffer):this._parsePe1(e)}))}_parsePe1(e){this._parse(95,(t=>{this._onPe1((0,c.xW)([e,t])),this._parsePe3()}))}_parsePe2(){this._parse(96,(e=>{for(this._onPe2(e);!this._setGenerators;);this._parsePe4()}))}async _parsePe3(){const e=await(0,c.tW)((0,c.fk)(this._utfToHex("req1")+this._sharedSecret));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)),n=this._decryptHandshake(e.slice(8,12)),s=new DataView(this._decryptHandshake(e.slice(12,14)).buffer).getUint16(0);this._parse(s,(e=>{e=this._decryptHandshake(e),this._parse(2,(s=>{const i=new DataView(this._decryptHandshake(s).buffer).getUint16(0);this._parse(i,(s=>{s=this._decryptHandshake(s),this._onPe3Encrypted(t,n,e,s);const r=i?s[0]:null,o=i?s.slice(1,20):null;19===r&&"BitTorrent protocol"===(0,c.dU)(o)?this._onHandshakeBuffer(s.slice(1)):this._parseHandshake()}))}))}))}))}_parsePe4(){const e=this._decryptHandshake(x);this._parseUntil(e,512),this._parse(6,(e=>{const t=this._decryptHandshake(e.slice(0,4)),n=new DataView(this._decryptHandshake(e.slice(4,6)).buffer).getUint16(0);this._parse(n,(e=>{this._decryptHandshake(e),this._onPe4(t),this._parseHandshake(null)}))}))}_parseHandshake(){this._parse(1,(e=>{const t=e[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"!==(0,c.dU)(t))return this._debug("Error: wire not speaking BitTorrent protocol (%s)",(0,c.dU)(t)),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]}`,u(...e)}_pull(e,t,n,s){for(let i=0;i{n.d(t,{NJ:()=>_,V5:()=>o,dU:()=>p,HB:()=>y,xW:()=>h,LC:()=>c,tW:()=>S,fk:()=>a,Ht:()=>b,po:()=>E,L0:()=>m});const s="0123456789abcdef",i=[],r=[];for(let e=0;e<256;e++)i[e]=s[e>>4&15]+s[15&e],e<16&&(e<10?r[48+e]=e:r[87+e]=e);const o=e=>{const t=e.length;let n="",s=0;for(;s{const t=e.length>>1,n=t<<1,s=new Uint8Array(t);let i=0,o=0;for(;o{const n=e.length||0;if(!t){let s=n;for(;s--;)t+=e[s].length}const s=new Uint8Array(t);let i=t,r=n;for(;r--;)i-=e[r].length,s.set(e[r],i);return s},c=(e,t)=>{if(e.length!==t.length)return!1;for(let n=e.length;n>-1;n-=1)if(e[n]!==t[n])return!1;return!0};for(var l="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",d="undefined"==typeof Uint8Array?[]:new Uint8Array(256),u=0;u<64;u++)d[l.charCodeAt(u)]=u;const f=new TextDecoder,p=(e,t)=>{if(!t)return f.decode(e);return new TextDecoder(t).decode(e)},g=new TextEncoder,m=e=>g.encode(e),_=e=>function(e){var t,n=new Uint8Array(e),s=n.length,i="";for(t=0;t>2],i+=l[(3&n[t])<<4|n[t+1]>>4],i+=l[(15&n[t+1])<<2|n[t+2]>>6],i+=l[63&n[t+2]];return s%3==2?i=i.substring(0,i.length-1)+"=":s%3==1&&(i=i.substring(0,i.length-2)+"=="),i}(e),y=e=>{let t,n="",i=0;const r=e.length;for(;i>4]+s[15&t];return n},b=e=>{const t=a(e);if(t.length<=65536)return String.fromCharCode(...t);let n="",s=0;for(;s{if(!k)throw new Error("no web crypto support");"string"==typeof e&&(e=m(e));const s=new Uint8Array(await k.digest(n,e));return t?x[t](s):s},E=e=>{const t=new Uint8Array(e);return v.getRandomValues(t)}},717:(e,t,n)=>{n.r(t),n.d(t,{addListener:()=>u,argv:()=>a,binding:()=>S,browser:()=>r,chdir:()=>E,cwd:()=>k,emit:()=>_,env:()=>o,listeners:()=>v,nextTick:()=>w,off:()=>p,on:()=>d,once:()=>f,prependListener:()=>y,prependOnceListener:()=>b,removeAllListeners:()=>m,removeListener:()=>g,title:()=>i,umask:()=>x,version:()=>h,versions:()=>c});var s=n(9596);const i="browser",r=!0,o={},a=[],h="",c={};function l(){}const d=l,u=l,f=l,p=l,g=l,m=l,_=l,y=l,b=l,w=(e,...t)=>s((()=>e(...t))),v=e=>[],k=()=>"/",x=()=>0,S=e=>{throw new Error("process.binding is not supported")},E=e=>{throw new Error("process.chdir is not supported")}},8330:e=>{e.exports={version:"2.4.1"}}},s={};function i(e){var t=s[e];if(void 0!==t)return t.exports;var r=s[e]={exports:{}};return n[e](r,r.exports,i),r.exports}t=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__,i.t=function(n,s){if(1&s&&(n=this(n)),8&s)return n;if("object"==typeof n&&n){if(4&s&&n.__esModule)return n;if(16&s&&"function"==typeof n.then)return n}var r=Object.create(null);i.r(r);var o={};e=e||[null,t({}),t([]),t(t)];for(var a=2&s&&n;"object"==typeof a&&!~e.indexOf(a);a=t(a))Object.getOwnPropertyNames(a).forEach((e=>o[e]=()=>n[e]));return o.default=()=>n,i.d(r,o),r},i.d=(e,t)=>{for(var n in t)i.o(t,n)&&!i.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},i.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),i.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var r={};i.d(r,{A:()=>Jt});var o=i(7007);function a(e){if("string"!=typeof e)throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}function h(e,t){let n,s="",i=0,r=-1,o=0;for(let a=0;a<=e.length;++a){if(a2){const e=s.lastIndexOf("/");if(e!==s.length-1){-1===e?(s="",i=0):(s=s.slice(0,e),i=s.length-1-s.lastIndexOf("/")),r=a,o=0;continue}}else if(2===s.length||1===s.length){s="",i=0,r=a,o=0;continue}t&&(s.length>0?s+="/..":s="..",i=2)}else s.length>0?s+="/"+e.slice(r+1,a):s=e.slice(r+1,a),i=a-r-1;r=a,o=0}else 46===n&&-1!==o?++o:o=-1}return s}function c(){if(0===arguments.length)return".";let e;for(let t=0;t0&&(void 0===e?e=n:e+="/"+n)}return void 0===e?".":function(e){if(a(e),0===e.length)return".";const t=47===e.charCodeAt(0),n=47===e.charCodeAt(e.length-1);return 0!==(e=h(e,!t)).length||t||(e="."),e.length>0&&n&&(e+="/"),t?"/"+e:e}(e)}i(717);const l="/";var d=i(988),u=i(1467),f=i(8444),p=i(2123);const g=new RegExp(["^npm-debug\\.log$","^\\..*\\.swp$","^\\.DS_Store$","^\\.AppleDouble$","^\\.LSOverride$","^Icon\\r$","^\\._.*","^\\.Spotlight-V100(?:$|\\/)","\\.Trashes","^__MACOSX$","~$","^Thumbs\\.db$","^ehthumbs\\.db$","^[Dd]esktop\\.ini$","@eaDir$"].join("|"));function m(e){return g.test(e)}var _=i(405),y=i(8190),b=i(9596),w=i(9639),v=(i(3468),i(2532));const k=[["udp://tracker.leechers-paradise.org:6969"],["udp://tracker.coppersurfer.tk:6969"],["udp://tracker.opentrackr.org:1337"],["udp://explodie.org:6969"],["udp://tracker.empire-js.us:1337"],["wss://tracker.btorrent.xyz"],["wss://tracker.openwebtorrent.com"],["wss://tracker.webtorrent.dev"]];const x=Symbol("itemPath");function S(e,t,n){var s;if(s=e,"undefined"!=typeof FileList&&s instanceof FileList&&(e=Array.from(e)),Array.isArray(e)||(e=[e]),0===e.length)throw new Error("invalid input type");e.forEach((e=>{if(null==e)throw new Error(`invalid input type: ${e}`)})),1!==(e=e.map((e=>A(e)&&"string"==typeof e.path&&"function"==typeof v?e.path:e))).length||"string"==typeof e[0]||e[0].name||(e[0].name=t.name);let i=null;e.forEach(((t,n)=>{if("string"==typeof t)return;let s=t.fullPath||t.name;s||(s=`Unknown File ${n+1}`,t.unknownName=!0),t[x]=s.split("/"),t[x][0]||t[x].shift(),t[x].length<2?i=null:0===n&&e.length>1?i=t[x][0]:t[x][0]!==i&&(i=null)}));(void 0===t.filterJunkFiles||t.filterJunkFiles)&&(e=e.filter((e=>"string"==typeof e||!function(e){const t=e[e.length-1];return"."===t[0]&&m(t)}(e[x])))),i&&e.forEach((e=>{const t=(ArrayBuffer.isView(e)||P(e))&&!e[x];"string"==typeof e||t||e[x].shift()})),!t.name&&i&&(t.name=i),t.name||e.some((e=>"string"==typeof e?(t.name=function(e,t){if(void 0!==t&&"string"!=typeof t)throw new TypeError('"ext" argument must be a string');a(e);let n,s=0,i=-1,r=!0;if(void 0!==t&&t.length>0&&t.length<=e.length){if(t.length===e.length&&t===e)return"";let o=t.length-1,a=-1;for(n=e.length-1;n>=0;--n){const h=e.charCodeAt(n);if(47===h){if(!r){s=n+1;break}}else-1===a&&(r=!1,a=n+1),o>=0&&(h===t.charCodeAt(o)?-1==--o&&(i=n):(o=-1,i=a))}return s===i?i=a:-1===i&&(i=e.length),e.slice(s,i)}for(n=e.length-1;n>=0;--n)if(47===e.charCodeAt(n)){if(!r){s=n+1;break}}else-1===i&&(r=!1,i=n+1);return-1===i?"":e.slice(s,i)}(e),!0):!e.unknownName&&(t.name=e[x][e[x].length-1],!0))),t.name||(t.name=`Unnamed Torrent ${Date.now()}`);const r=e.reduce(((e,t)=>e+Number("string"==typeof t)),0);let o=1===e.length;if(1===e.length&&"string"==typeof e[0]){if("function"!=typeof v)throw new Error("filesystem paths do not work in the browser");p(e[0],((e,t)=>{if(e)return n(e);o=t,h()}))}else b(h);function h(){y(e.map((e=>t=>{const n={};if(A(e))n.getStream=e.stream(),n.length=e.size;else if(ArrayBuffer.isView(e))n.getStream=[e],n.length=e.length;else{if(!P(e)){if("string"==typeof e){if("function"!=typeof v)throw new Error("filesystem paths do not work in the browser");return void v(e,r>1||o,t)}throw new Error("invalid input type")}n.getStream=async function*(e,t){for await(const n of e)t.length+=n.length,yield n}(e,n),n.length=0}n.path=e[x],t(null,n)})),((e,t)=>{if(e)return n(e);t=t.flat(),n(null,t,o)}))}}const E=5;function C(e,t){return e+t.length}function A(e){return"undefined"!=typeof Blob&&e instanceof Blob}function P(e){return"object"==typeof e&&null!=e&&"function"==typeof e.pipe}const T=function(e,t,n){"function"==typeof t&&([t,n]=[n,t]),S(e,t=t?Object.assign({},t):{},((e,s,i)=>{if(e)return n(e);t.singleFileTorrent=i,function(e,t,n){let s=t.announceList;s||("string"==typeof t.announce?s=[[t.announce]]:Array.isArray(t.announce)&&(s=t.announce.map((e=>[e]))));s||(s=[]);globalThis.WEBTORRENT_ANNOUNCE&&("string"==typeof globalThis.WEBTORRENT_ANNOUNCE?s.push([[globalThis.WEBTORRENT_ANNOUNCE]]):Array.isArray(globalThis.WEBTORRENT_ANNOUNCE)&&(s=s.concat(globalThis.WEBTORRENT_ANNOUNCE.map((e=>[e])))));void 0===t.announce&&void 0===t.announceList&&(s=s.concat(k));"string"==typeof t.urlList&&(t.urlList=[t.urlList]);const i={info:{name:t.name},"creation date":Math.ceil((Number(t.creationDate)||Date.now())/1e3),encoding:"UTF-8"};0!==s.length&&(i.announce=s[0][0],i["announce-list"]=s);void 0!==t.comment&&(i.comment=t.comment);void 0!==t.createdBy&&(i["created by"]=t.createdBy);void 0!==t.private&&(i.info.private=Number(t.private));void 0!==t.info&&Object.assign(i.info,t.info);void 0!==t.sslCert&&(i.info["ssl-cert"]=t.sslCert);void 0!==t.urlList&&(i["url-list"]=t.urlList);const r=e.reduce(C,0),o=t.pieceLength||f(r);i.info["piece length"]=o,async function(e,t,n,s,i){const r=[];let o=0,a=0;const h=e.map((e=>e.getStream)),c=s.onProgress;let l=0,d=0,f=!1;const p=u(_(h),t,{zeroPadding:!1});try{for await(const e of p)await new Promise((t=>{o+=e.length;const s=d;++d,++l{r[s]=h,--l,a+=e.length,c&&c(a,n),t(),f&&0===l&&i(null,(0,w.fk)(r.join("")),o)}))}));if(0===l)return i(null,(0,w.fk)(r.join("")),o);f=!0}catch(e){i(e)}}(e,o,r,t,((s,r,o)=>{if(s)return n(s);i.info.pieces=r,e.forEach((e=>{delete e.getStream})),t.singleFileTorrent?i.info.length=o:i.info.files=e,n(null,d.A.encode(i))}))}(s,t,n)}))};var L=i(7833),I=i(6664),O=i(1827),R=i(3208);self.Blob,self.File,self.FormData,self.Headers,self.Request,self.Response,self.AbortController,self.AbortSignal;const N=self.fetch||(()=>{throw new Error("global fetch is not available!")}),H=[255,255,26,27,28,29,30,31,255,255,255,255,255,255,255,255,255,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,255,255,255,255,255,255,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,255,255,255,255,255];const U=function(e){if(!ArrayBuffer.isView(e)&&"string"!=typeof e)throw new TypeError("base32.decode only takes Buffer or string as parameter");let t,n=0,s=0,i=0;ArrayBuffer.isView(e)||(e=(0,w.L0)(e));const r=new Uint8Array(Math.ceil(5*e.length/8));for(let o=0;o>>n,r[i]=t,i++,t=255&s<<8-n)}return r.subarray(0,i)};function M(e){return e.reduce(((e,t,n,s)=>{const i=t.split("-").map((e=>parseInt(e)));return e.concat(((e,t=e)=>Array.from({length:t-e+1},((t,n)=>n+e)))(...i))}),[])}const B=function(e){const t={},n=e.split("magnet:?")[1];let s;if((n&&n.length>=0?n.split("&"):[]).forEach((e=>{const n=e.split("=");if(2!==n.length)return;const s=n[0];let i=n[1];"dn"===s&&(i=decodeURIComponent(i).replace(/\+/g," ")),"tr"!==s&&"xs"!==s&&"as"!==s&&"ws"!==s||(i=decodeURIComponent(i)),"kt"===s&&(i=decodeURIComponent(i).split("+")),"ix"===s&&(i=Number(i)),"so"===s&&(i=M(decodeURIComponent(i).split(","))),t[s]?(Array.isArray(t[s])||(t[s]=[t[s]]),t[s].push(i)):t[s]=i})),t.xt){(Array.isArray(t.xt)?t.xt:[t.xt]).forEach((e=>{(s=e.match(/^urn:btih:(.{40})/))?t.infoHash=s[1].toLowerCase():(s=e.match(/^urn:btih:(.{32})/))?t.infoHash=(0,w.V5)(U(s[1])):(s=e.match(/^urn:btmh:1220(.{64})/))&&(t.infoHashV2=s[1].toLowerCase())}))}if(t.xs){(Array.isArray(t.xs)?t.xs:[t.xs]).forEach((e=>{(s=e.match(/^urn:btpk:(.{64})/))&&(t.publicKey=s[1].toLowerCase())}))}return t.infoHash&&(t.infoHashBuffer=(0,w.fk)(t.infoHash)),t.infoHashV2&&(t.infoHashV2Buffer=(0,w.fk)(t.infoHashV2)),t.publicKey&&(t.publicKeyBuffer=(0,w.fk)(t.publicKey)),t.dn&&(t.name=t.dn),t.kt&&(t.keywords=t.kt),t.announce=[],("string"==typeof t.tr||Array.isArray(t.tr))&&(t.announce=t.announce.concat(t.tr)),t.urlList=[],("string"==typeof t.as||Array.isArray(t.as))&&(t.urlList=t.urlList.concat(t.as)),("string"==typeof t.ws||Array.isArray(t.ws))&&(t.urlList=t.urlList.concat(t.ws)),t.peerAddresses=[],("string"==typeof t["x.pe"]||Array.isArray(t["x.pe"]))&&(t.peerAddresses=t.peerAddresses.concat(t["x.pe"])),t.announce=Array.from(new Set(t.announce)),t.urlList=Array.from(new Set(t.urlList)),t.peerAddresses=Array.from(new Set(t.peerAddresses)),t};async function D(e){if("string"==typeof e&&/^(stream-)?magnet:/.test(e)){const t=B(e);if(!t.infoHash)throw new Error("Invalid torrent identifier");return t}if("string"==typeof e&&(/^[a-f0-9]{40}$/i.test(e)||/^[a-z2-7]{32}$/i.test(e)))return B(`magnet:?xt=urn:btih:${e}`);if(ArrayBuffer.isView(e)&&20===e.length)return B(`magnet:?xt=urn:btih:${(0,w.V5)(e)}`);if(ArrayBuffer.isView(e))return await async function(e){ArrayBuffer.isView(e)&&(e=d.A.decode(e));q(e.info,"info"),q(e.info["name.utf-8"]||e.info.name,"info.name"),q(e.info["piece length"],"info['piece length']"),q(e.info.pieces,"info.pieces"),e.info.files?e.info.files.forEach((e=>{q("number"==typeof e.length,"info.files[0].length"),q(e["path.utf-8"]||e.path,"info.files[0].path")})):q("number"==typeof e.info.length,"info.length");const t={info:e.info,infoBuffer:d.A.encode(e.info),name:(0,w.dU)(e.info["name.utf-8"]||e.info.name),announce:[]};t.infoHashBuffer=await(0,w.tW)(t.infoBuffer),t.infoHash=(0,w.V5)(t.infoHashBuffer),void 0!==e.info.private&&(t.private=!!e.info.private);e["creation date"]&&(t.created=new Date(1e3*e["creation date"]));e["created by"]&&(t.createdBy=(0,w.dU)(e["created by"]));ArrayBuffer.isView(e.comment)&&(t.comment=(0,w.dU)(e.comment));Array.isArray(e["announce-list"])&&e["announce-list"].length>0?e["announce-list"].forEach((e=>{e.forEach((e=>{t.announce.push((0,w.dU)(e))}))})):e.announce&&t.announce.push((0,w.dU)(e.announce));ArrayBuffer.isView(e["url-list"])&&(e["url-list"]=e["url-list"].length>0?[e["url-list"]]:[]);t.urlList=(e["url-list"]||[]).map((e=>(0,w.dU)(e))),t.announce=Array.from(new Set(t.announce)),t.urlList=Array.from(new Set(t.urlList));const n=e.info.files||[e.info];t.files=n.map(((e,s)=>{const i=[].concat(t.name,e["path.utf-8"]||e.path||[]).map((e=>ArrayBuffer.isView(e)?(0,w.dU)(e):e));return{path:c.apply(null,[l].concat(i)).slice(1),name:i[i.length-1],length:e.length,offset:n.slice(0,s).reduce(F,0)}})),t.length=n.reduce(F,0);const s=t.files[t.files.length-1];return t.pieceLength=e.info["piece length"],t.lastPieceLength=(s.offset+s.length)%t.pieceLength||t.pieceLength,t.pieces=function(e){const t=[];for(let n=0;n{n(null,s)}));else if(i=e,"undefined"!=typeof Blob&&i instanceof Blob)try{r(new Uint8Array(await e.arrayBuffer()))}catch(e){return n(new Error(`Error converting Blob: ${e.message}`))}else if(/^https?:/.test(e))try{const n=await N(e,{headers:{"user-agent":"WebTorrent (https://webtorrent.io)"},signal:AbortSignal.timeout(3e4),...t});r(new Uint8Array(await n.arrayBuffer()))}catch(e){return n(new Error(`Error downloading torrent: ${e.message}`))}else"function"==typeof R.readFile&&"string"==typeof e?R.readFile(e,((e,t)=>{if(e)return n(new Error("Invalid torrent identifier"));r(t)})):b((()=>{n(new Error("Invalid torrent identifier"))}));var i;async function r(e){try{s=await D(e)}catch(e){return n(e)}s&&s.infoHash?n(null,s):n(new Error("Invalid torrent identifier"))}}function F(e,t){return e+t.length}function q(e,t){if(!e)throw new Error(`Torrent is missing required field: ${t}`)}const W=D,$=function(e){e=Object.assign({},e);let t=new Set;e.xt&&"string"==typeof e.xt&&t.add(e.xt),e.xt&&Array.isArray(e.xt)&&(t=new Set(e.xt)),e.infoHashBuffer&&t.add(`urn:btih:${(0,w.V5)(e.infoHashBuffer)}`),e.infoHash&&t.add(`urn:btih:${e.infoHash}`),e.infoHashV2Buffer&&t.add(e.xt=`urn:btmh:1220${(0,w.V5)(e.infoHashV2Buffer)}`),e.infoHashV2&&t.add(`urn:btmh:1220${e.infoHashV2}`);const n=Array.from(t);1===n.length&&(e.xt=n[0]),n.length>1&&(e.xt=n),e.publicKeyBuffer&&(e.xs=`urn:btpk:${(0,w.V5)(e.publicKeyBuffer)}`),e.publicKey&&(e.xs=`urn:btpk:${e.publicKey}`),e.name&&(e.dn=e.name),e.keywords&&(e.kt=e.keywords),e.announce&&(e.tr=e.announce),e.urlList&&(e.ws=e.urlList,delete e.as),e.peerAddresses&&(e["x.pe"]=e.peerAddresses);let s="magnet:?";return Object.keys(e).filter((e=>2===e.length||"x.pe"===e)).forEach(((t,n)=>{const i=Array.isArray(e[t])?e[t]:[e[t]];var r;i.forEach(((e,i)=>{(n>0||i>0)&&("kt"!==t&&"so"!==t||0===i)&&(s+="&"),"dn"===t&&(e=encodeURIComponent(e).replace(/%20/g,"+")),"tr"!==t&&"as"!==t&&"ws"!==t||(e=encodeURIComponent(e)),"xs"!==t||e.startsWith("urn:btpk:")||(e=encodeURIComponent(e)),"kt"===t&&(e=encodeURIComponent(e)),"so"!==t&&(s+="kt"===t&&i>0?`+${e}`:`${t}=${e}`)})),"so"===t&&(s+=`${t}=${r=i,r.reduce(((e,t,n,s)=>(0!==n&&t===s[n-1]+1||e.push([]),e[e.length-1].push(t),e)),[]).map((e=>e.length>1?`${e[0]}-${e[e.length-1]}`:`${e[0]}`))}`)})),s},V="undefined"!=typeof window?window:self,z=V.RTCPeerConnection||V.mozRTCPeerConnection||V.webkitRTCPeerConnection,G=V.RTCSessionDescription||V.mozRTCSessionDescription||V.webkitRTCSessionDescription,K=V.RTCIceCandidate||V.mozRTCIceCandidate||V.webkitRTCIceCandidate;V.RTCIceTransport,V.RTCDataChannel,V.RTCSctpTransport,V.RTCDtlsTransport,V.RTCCertificate,V.MediaStream,V.MediaStreamTrack,V.MediaStreamTrackEvent,V.RTCPeerConnectionIceEvent,V.RTCDataChannelEvent,V.RTCTrackEvent,V.RTCError,V.RTCErrorEvent,V.RTCRtpTransceiver,V.RTCRtpReceiver,V.RTCRtpSender;var Y=i(8179),J=i(6310);const X=L("simple-peer"),Q=65536;function Z(e){return e.replace(/a=ice-options:trickle\s\n/g,"")}class ee extends Y.Duplex{_pc;constructor(e){if(super(e=Object.assign({allowHalfOpen:!1},e)),this.__objectMode=!!e.objectMode,this._id=(0,w.V5)((0,w.po)(4)).slice(0,7),this._debug("new peer %o",e),this.channelName=e.initiator?e.channelName||(0,w.V5)((0,w.po)(20)):null,this.initiator=e.initiator||!1,this.channelConfig=e.channelConfig||ee.channelConfig,this.channelNegotiated=this.channelConfig.negotiated,this.config=Object.assign({},ee.config,e.config),this.offerOptions=e.offerOptions||{},this.answerOptions=e.answerOptions||{},this.sdpTransform=e.sdpTransform||(e=>e),this.trickle=void 0===e.trickle||e.trickle,this.allowHalfTrickle=void 0!==e.allowHalfTrickle&&e.allowHalfTrickle,this.iceCompleteTimeout=e.iceCompleteTimeout||5e3,this._destroying=!1,this._connected=!1,this.remoteAddress=void 0,this.remoteFamily=void 0,this.remotePort=void 0,this.localAddress=void 0,this.localFamily=void 0,this.localPort=void 0,!z)throw"undefined"==typeof window?J(new Error("No WebRTC support: Specify `opts.wrtc` option in this environment"),"ERR_WEBRTC_SUPPORT"):J(new Error("No WebRTC support: Not a supported browser"),"ERR_WEBRTC_SUPPORT");this._pcReady=!1,this._channelReady=!1,this._iceComplete=!1,this._iceCompleteTimer=null,this._channel=null,this._pendingCandidates=[],this._isNegotiating=!1,this._firstNegotiation=!0,this._batchedNegotiation=!1,this._queuedNegotiation=!1,this._sendersAwaitingStable=[],this._closingInterval=null,this._remoteTracks=[],this._remoteStreams=[],this._chunk=null,this._cb=null,this._interval=null;try{this._pc=new z(this.config)}catch(e){return void this.__destroy(J(e,"ERR_PC_CONSTRUCTOR"))}this._isReactNativeWebrtc="number"==typeof this._pc._peerConnectionId,this._pc.oniceconnectionstatechange=()=>{this._onIceStateChange()},this._pc.onicegatheringstatechange=()=>{this._onIceStateChange()},this._pc.onconnectionstatechange=()=>{this._onConnectionStateChange()},this._pc.onsignalingstatechange=()=>{this._onSignalingStateChange()},this._pc.onicecandidate=e=>{this._onIceCandidate(e)},"object"==typeof this._pc.peerIdentity&&this._pc.peerIdentity.catch((e=>{this.__destroy(J(e,"ERR_PC_PEER_IDENTITY"))})),this.initiator||this.channelNegotiated?this._setupData({channel:this._pc.createDataChannel(this.channelName,this.channelConfig)}):this._pc.ondatachannel=e=>{this._setupData(e)},this._debug("initial negotiation"),this._needsNegotiation(),this._onFinishBound=()=>{this._onFinish()},this.once("finish",this._onFinishBound)}get bufferSize(){return this._channel&&this._channel.bufferedAmount||0}get connected(){return this._connected&&"open"===this._channel.readyState}address(){return{port:this.localPort,family:this.localFamily,address:this.localAddress}}signal(e){if(!this._destroying){if(this.destroyed)throw J(new Error("cannot signal after peer is destroyed"),"ERR_DESTROYED");if("string"==typeof e)try{e=JSON.parse(e)}catch(t){e={}}this._debug("signal()"),e.renegotiate&&this.initiator&&(this._debug("got request to renegotiate"),this._needsNegotiation()),e.transceiverRequest&&this.initiator&&(this._debug("got request for transceiver"),this.addTransceiver(e.transceiverRequest.kind,e.transceiverRequest.init)),e.candidate&&(this._pc.remoteDescription&&this._pc.remoteDescription.type?this._addIceCandidate(e.candidate):this._pendingCandidates.push(e.candidate)),e.sdp&&this._pc.setRemoteDescription(new G(e)).then((()=>{this.destroyed||(this._pendingCandidates.forEach((e=>{this._addIceCandidate(e)})),this._pendingCandidates=[],"offer"===this._pc.remoteDescription.type&&this._createAnswer())})).catch((e=>{this.__destroy(J(e,"ERR_SET_REMOTE_DESCRIPTION"))})),e.sdp||e.candidate||e.renegotiate||e.transceiverRequest||this.__destroy(J(new Error("signal() called with invalid signal data"),"ERR_SIGNALING"))}}_addIceCandidate(e){const t=new K(e);this._pc.addIceCandidate(t).catch((e=>{var n;!t.address||t.address.endsWith(".local")?(n="Ignoring unsupported ICE candidate.",console.warn(n)):this.__destroy(J(e,"ERR_ADD_ICE_CANDIDATE"))}))}send(e){if(!this._destroying){if(this.destroyed)throw J(new Error("cannot send after peer is destroyed"),"ERR_DESTROYED");this._channel.send(e)}}_needsNegotiation(){this._debug("_needsNegotiation"),this._batchedNegotiation||(this._batchedNegotiation=!0,queueMicrotask((()=>{this._batchedNegotiation=!1,this.initiator||!this._firstNegotiation?(this._debug("starting batched negotiation"),this.negotiate()):this._debug("non-initiator initial negotiation request discarded"),this._firstNegotiation=!1})))}negotiate(){if(!this._destroying){if(this.destroyed)throw J(new Error("cannot negotiate after peer is destroyed"),"ERR_DESTROYED");this.initiator?this._isNegotiating?(this._queuedNegotiation=!0,this._debug("already negotiating, queueing")):(this._debug("start negotiation"),setTimeout((()=>{this._createOffer()}),0)):this._isNegotiating?(this._queuedNegotiation=!0,this._debug("already negotiating, queueing")):(this._debug("requesting negotiation from initiator"),this.emit("signal",{type:"renegotiate",renegotiate:!0})),this._isNegotiating=!0}}_final(e){this._readableState.ended||this.push(null),e(null)}__destroy(e){this.end(),this._destroy((()=>{}),e)}_destroy(e,t){this.destroyed||this._destroying||(this._destroying=!0,this._debug("destroying (error: %s)",t&&(t.message||t)),setTimeout((()=>{if(this._connected=!1,this._pcReady=!1,this._channelReady=!1,this._remoteTracks=null,this._remoteStreams=null,this._senderMap=null,clearInterval(this._closingInterval),this._closingInterval=null,clearInterval(this._interval),this._interval=null,this._chunk=null,this._cb=null,this._onFinishBound&&this.removeListener("finish",this._onFinishBound),this._onFinishBound=null,this._channel){try{this._channel.close()}catch(e){}this._channel.onmessage=null,this._channel.onopen=null,this._channel.onclose=null,this._channel.onerror=null}if(this._pc){try{this._pc.close()}catch(e){}this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ontrack=null,this._pc.ondatachannel=null}this._pc=null,this._channel=null,t&&this.emit("error",t),e()}),0))}_setupData(e){if(!e.channel)return this.__destroy(J(new Error("Data channel event is missing `channel` property"),"ERR_DATA_CHANNEL"));this._channel=e.channel,this._channel.binaryType="arraybuffer","number"==typeof this._channel.bufferedAmountLowThreshold&&(this._channel.bufferedAmountLowThreshold=Q),this.channelName=this._channel.label,this._channel.onmessage=e=>{this._onChannelMessage(e)},this._channel.onbufferedamountlow=()=>{this._onChannelBufferedAmountLow()},this._channel.onopen=()=>{this._onChannelOpen()},this._channel.onclose=()=>{this._onChannelClose()},this._channel.onerror=e=>{const t=e.error instanceof Error?e.error:new Error(`Datachannel error: ${e.message} ${e.filename}:${e.lineno}:${e.colno}`);this.__destroy(J(t,"ERR_DATA_CHANNEL"))};let t=!1;this._closingInterval=setInterval((()=>{this._channel&&"closing"===this._channel.readyState?(t&&this._onChannelClose(),t=!0):t=!1}),5e3)}_write(e,t){if(this.destroyed)return t(J(new Error("cannot write after peer is destroyed"),"ERR_DATA_CHANNEL"));if(this._connected){try{this.send(e)}catch(e){return this.__destroy(J(e,"ERR_DATA_CHANNEL"))}this._channel.bufferedAmount>Q?(this._debug("start backpressure: bufferedAmount %d",this._channel.bufferedAmount),this._cb=t):t(null)}else this._debug("write before connect"),this._chunk=e,this._cb=t}_onFinish(){if(this.destroyed)return;const e=()=>{setTimeout((()=>this.__destroy()),1e3)};this._connected?e():this.once("connect",e)}_startIceCompleteTimeout(){this.destroyed||this._iceCompleteTimer||(this._debug("started iceComplete timeout"),this._iceCompleteTimer=setTimeout((()=>{this._iceComplete||(this._iceComplete=!0,this._debug("iceComplete timeout completed"),this.emit("iceTimeout"),this.emit("_iceComplete"))}),this.iceCompleteTimeout))}_createOffer(){this.destroyed||this._pc.createOffer(this.offerOptions).then((e=>{if(this.destroyed)return;this.trickle||this.allowHalfTrickle||(e.sdp=Z(e.sdp)),e.sdp=this.sdpTransform(e.sdp);const t=()=>{if(this.destroyed)return;const t=this._pc.localDescription||e;this._debug("signal"),this.emit("signal",{type:t.type,sdp:t.sdp})};this._pc.setLocalDescription(e).then((()=>{this._debug("createOffer success"),this.destroyed||(this.trickle||this._iceComplete?t():this.once("_iceComplete",t))})).catch((e=>{this.__destroy(J(e,"ERR_SET_LOCAL_DESCRIPTION"))}))})).catch((e=>{this.__destroy(J(e,"ERR_CREATE_OFFER"))}))}_createAnswer(){this.destroyed||this._pc.createAnswer(this.answerOptions).then((e=>{if(this.destroyed)return;this.trickle||this.allowHalfTrickle||(e.sdp=Z(e.sdp)),e.sdp=this.sdpTransform(e.sdp);const t=()=>{if(this.destroyed)return;const t=this._pc.localDescription||e;this._debug("signal"),this.emit("signal",{type:t.type,sdp:t.sdp}),this.initiator||this._requestMissingTransceivers?.()};this._pc.setLocalDescription(e).then((()=>{this.destroyed||(this.trickle||this._iceComplete?t():this.once("_iceComplete",t))})).catch((e=>{this.__destroy(J(e,"ERR_SET_LOCAL_DESCRIPTION"))}))})).catch((e=>{this.__destroy(J(e,"ERR_CREATE_ANSWER"))}))}_onConnectionStateChange(){this.destroyed||this._destroying||"failed"===this._pc.connectionState&&this.__destroy(J(new Error("Connection failed."),"ERR_CONNECTION_FAILURE"))}_onIceStateChange(){if(this.destroyed)return;const e=this._pc.iceConnectionState,t=this._pc.iceGatheringState;this._debug("iceStateChange (connection: %s) (gathering: %s)",e,t),this.emit("iceStateChange",e,t),"connected"!==e&&"completed"!==e||(this._pcReady=!0,this._maybeReady()),"failed"===e&&this.__destroy(J(new Error("Ice connection failed."),"ERR_ICE_CONNECTION_FAILURE")),"closed"===e&&this.__destroy(J(new Error("Ice connection closed."),"ERR_ICE_CONNECTION_CLOSED"))}getStats(e){const t=e=>("[object Array]"===Object.prototype.toString.call(e.values)&&e.values.forEach((t=>{Object.assign(e,t)})),e);0===this._pc.getStats.length||this._isReactNativeWebrtc?this._pc.getStats().then((n=>{const s=[];n.forEach((e=>{s.push(t(e))})),e(null,s)}),(t=>e(t))):this._pc.getStats.length>0?this._pc.getStats((n=>{if(this.destroyed)return;const s=[];n.result().forEach((e=>{const n={};e.names().forEach((t=>{n[t]=e.stat(t)})),n.id=e.id,n.type=e.type,n.timestamp=e.timestamp,s.push(t(n))})),e(null,s)}),(t=>e(t))):e(null,[])}_maybeReady(){if(this._debug("maybeReady pc %s channel %s",this._pcReady,this._channelReady),this._connected||this._connecting||!this._pcReady||!this._channelReady)return;this._connecting=!0;const e=()=>{this.destroyed||this._destroying||this.getStats(((t,n)=>{if(this.destroyed||this._destroying)return;t&&(n=[]);const s={},i={},r={};let o=!1;n.forEach((e=>{"remotecandidate"!==e.type&&"remote-candidate"!==e.type||(s[e.id]=e),"localcandidate"!==e.type&&"local-candidate"!==e.type||(i[e.id]=e),"candidatepair"!==e.type&&"candidate-pair"!==e.type||(r[e.id]=e)}));const a=e=>{o=!0;let t=i[e.localCandidateId];t&&(t.ip||t.address)?(this.localAddress=t.ip||t.address,this.localPort=Number(t.port)):t&&t.ipAddress?(this.localAddress=t.ipAddress,this.localPort=Number(t.portNumber)):"string"==typeof e.googLocalAddress&&(t=e.googLocalAddress.split(":"),this.localAddress=t[0],this.localPort=Number(t[1])),this.localAddress&&(this.localFamily=this.localAddress.includes(":")?"IPv6":"IPv4");let n=s[e.remoteCandidateId];n&&(n.ip||n.address)?(this.remoteAddress=n.ip||n.address,this.remotePort=Number(n.port)):n&&n.ipAddress?(this.remoteAddress=n.ipAddress,this.remotePort=Number(n.portNumber)):"string"==typeof e.googRemoteAddress&&(n=e.googRemoteAddress.split(":"),this.remoteAddress=n[0],this.remotePort=Number(n[1])),this.remoteAddress&&(this.remoteFamily=this.remoteAddress.includes(":")?"IPv6":"IPv4"),this._debug("connect local: %s:%s remote: %s:%s",this.localAddress,this.localPort,this.remoteAddress,this.remotePort)};if(n.forEach((e=>{"transport"===e.type&&e.selectedCandidatePairId&&a(r[e.selectedCandidatePairId]),("googCandidatePair"===e.type&&"true"===e.googActiveConnection||("candidatepair"===e.type||"candidate-pair"===e.type)&&e.selected)&&a(e)})),o||Object.keys(r).length&&!Object.keys(i).length){if(this._connecting=!1,this._connected=!0,this._chunk){try{this.send(this._chunk)}catch(t){return this.__destroy(J(t,"ERR_DATA_CHANNEL"))}this._chunk=null,this._debug('sent chunk from "write before connect"');const e=this._cb;this._cb=null,e(null)}"number"!=typeof this._channel.bufferedAmountLowThreshold&&(this._interval=setInterval((()=>this._onInterval()),150),this._interval.unref&&this._interval.unref()),this._debug("connect"),this.emit("connect")}else setTimeout(e,100)}))};e()}_onInterval(){!this._cb||!this._channel||this._channel.bufferedAmount>Q||this._onChannelBufferedAmountLow()}_onSignalingStateChange(){this.destroyed||("stable"===this._pc.signalingState&&(this._isNegotiating=!1,this._debug("flushing sender queue",this._sendersAwaitingStable),this._sendersAwaitingStable.forEach((e=>{this._pc.removeTrack(e),this._queuedNegotiation=!0})),this._sendersAwaitingStable=[],this._queuedNegotiation?(this._debug("flushing negotiation queue"),this._queuedNegotiation=!1,this._needsNegotiation()):(this._debug("negotiated"),this.emit("negotiated"))),this._debug("signalingStateChange %s",this._pc.signalingState),this.emit("signalingStateChange",this._pc.signalingState))}_onIceCandidate(e){this.destroyed||(e.candidate&&this.trickle?this.emit("signal",{type:"candidate",candidate:{candidate:e.candidate.candidate,sdpMLineIndex:e.candidate.sdpMLineIndex,sdpMid:e.candidate.sdpMid}}):e.candidate||this._iceComplete||(this._iceComplete=!0,this.emit("_iceComplete")),e.candidate&&this._startIceCompleteTimeout())}_onChannelMessage(e){if(this.destroyed)return;let t=e.data;t instanceof ArrayBuffer?t=new Uint8Array(t):!1===this.__objectMode&&(t=(0,w.L0)(t)),this.push(t)}_onChannelBufferedAmountLow(){if(this.destroyed||!this._cb)return;this._debug("ending backpressure: bufferedAmount %d",this._channel.bufferedAmount);const e=this._cb;this._cb=null,e(null)}_onChannelOpen(){this._connected||this.destroyed||(this._debug("on channel open"),this._channelReady=!0,this._maybeReady())}_onChannelClose(){this.destroyed||(this._debug("on channel close"),this.__destroy())}_debug(){const e=[].slice.call(arguments);e[0]="["+this._id+"] "+e[0],X.apply(null,e)}}ee.WEBRTC_SUPPORT=!!z,ee.config={iceServers:[{urls:["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478"]}],sdpSemantics:"unified-plan"},ee.channelConfig={};const te=ee;var ne=i(1035),se=i(7541),ie=i(3278),re=i(8271),oe=i(6686),ae=i(7828),he=i(6889);const ce=/^\[?([^\]]+)]?:(\d+)$/;let le=new Map;function de(e){if(1e5===le.size&&le.clear(),!le.has(e)){const t=ce.exec(e);if(!t)throw new Error(`invalid addr: ${e}`);le.set(e,[t[1],Number(t[2])])}return le.get(e)}var ue=i(3033),fe=i(4497);async function*pe(e,t={}){if(e?.[Symbol.asyncIterator])return void(yield*e[Symbol.asyncIterator](t.offset));if(!e?.get)throw new Error("First argument must be an abstract-chunk-store compliant store");const n=t.chunkLength||e.chunkLength;if(!n)throw new Error("missing required `chunkLength` property");let s=t.length||e.length;if(!Number.isFinite(s))throw new Error("missing required `length` property");const i=t.offset||0,r=(t,n,s)=>new Promise(((i,r)=>{e.get(t,{offset:s,length:n},((e,t)=>{e&&r(e),i(t)}))}));let o=Math.floor(i/n);const a=i%n;if(i){const e=Math.min(s,n-a);s-=e,yield r(o++,e,a)}for(let e=s;e>0;++o,e-=n)yield r(o,Math.min(e,n))}async function ge(e,t,n={}){if(!e?.put)throw new Error("First argument must be an abstract-chunk-store compliant store");const s=n.chunkLength||e.chunkLength;if(!s)throw new Error("missing required `chunkLength` property");const i=n.storeMaxOutstandingPuts||16;let r=0,o=0,a=()=>{},h=!1;for await(const c of u(t,s,{zeroPadding:n.zeroPadding||!1}))await new Promise((t=>{r++<=i&&t(),e.put(o++,c,(e=>{if(e)throw e;--r,t(),h&&0===r&&a()}))}));0!==r&&(h=new Promise((e=>{a=e})),await h)}var me=i(4018),_e=i(3970),ye=i(3519),be=i(1551);const we={DEFAULT_ANNOUNCE_PEERS:50,MAX_ANNOUNCE_PEERS:82,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},...i.t(be,2)};var ve=i(826),ke=i(61),xe=i(2701);const Se=L("simple-websocket"),Ee="function"!=typeof xe?WebSocket:xe;class Ce extends Y.Duplex{constructor(e={}){if("string"==typeof e&&(e={url:e}),super(e=Object.assign({allowHalfOpen:!1},e)),this.__objectMode=!!e.objectMode,null!=e.objectMode&&delete e.objectMode,null==e.url&&null==e.socket)throw new Error("Missing required `url` or `socket` option");if(null!=e.url&&null!=e.socket)throw new Error("Must specify either `url` or `socket` option, not both");if(this._id=(0,w.V5)((0,w.po)(4)).slice(0,7),this._debug("new websocket: %o",e),this.connected=!1,this._chunk=null,this._cb=null,this._interval=null,e.socket)this.url=e.socket.url,this._ws=e.socket,this.connected=e.socket.readyState===Ee.OPEN;else{this.url=e.url;try{this._ws="function"==typeof xe?new Ee(e.url,{...e,encoding:void 0}):new Ee(e.url)}catch(e){return void b((()=>this.destroy(e)))}}this._ws.binaryType="arraybuffer",e.socket&&this.connected?b((()=>this._handleOpen())):this._ws.onopen=()=>this._handleOpen(),this._ws.onmessage=e=>this._handleMessage(e),this._ws.onclose=()=>this._handleClose(),this._ws.onerror=e=>this._handleError(e),this._handleFinishBound=()=>this._handleFinish(),this.once("finish",this._handleFinishBound)}send(e){this._ws.send(e)}_final(e){this._readableState.ended||this.push(null),e(null)}_destroy(e){if(!this.destroyed){if(this._writableState.ended||this.end(),this.connected=!1,clearInterval(this._interval),this._interval=null,this._chunk=null,this._cb=null,this._handleFinishBound&&this.removeListener("finish",this._handleFinishBound),this._handleFinishBound=null,this._ws){const e=this._ws,t=()=>{e.onclose=null};if(e.readyState===Ee.CLOSED)t();else try{e.onclose=t,e.close()}catch(e){t()}e.onopen=null,e.onmessage=null,e.onerror=()=>{}}this._ws=null,e()}}_write(e,t){if(this.destroyed)return t(new Error("cannot write after socket is destroyed"));if(this.connected){try{this.send(e)}catch(e){return this.destroy(e)}"function"!=typeof xe&&this._ws.bufferedAmount>65536?(this._debug("start backpressure: bufferedAmount %d",this._ws.bufferedAmount),this._cb=t):t(null)}else this._debug("write before connect"),this._chunk=e,this._cb=t}_handleOpen(){if(!this.connected&&!this.destroyed){if(this.connected=!0,this._chunk){try{this.send(this._chunk)}catch(e){return this.destroy(e)}this._chunk=null,this._debug('sent chunk from "write before connect"');const e=this._cb;this._cb=null,e(null)}"function"!=typeof xe&&(this._interval=setInterval((()=>this._onInterval()),150),this._interval.unref&&this._interval.unref()),this._debug("connect"),this.emit("connect")}}_handleMessage(e){if(this.destroyed)return;let t=e.data;t instanceof ArrayBuffer&&(t=new Uint8Array(t)),!1===this.__objectMode&&(t=(0,w.L0)(t)),this.push(t)}_handleClose(){this.destroyed||(this._debug("on close"),this.destroy())}_handleError(e){this.destroy(new Error(`Error connecting to ${this.url}`))}_handleFinish(){if(this.destroyed)return;const e=()=>{setTimeout((()=>this.destroy()),1e3)};this.connected?e():this.once("connect",e)}_onInterval(){if(!this._cb||!this._ws||this._ws.bufferedAmount>65536)return;this._debug("ending backpressure: bufferedAmount %d",this._ws.bufferedAmount);const e=this._cb;this._cb=null,e(null)}_debug(){const e=[].slice.call(arguments);e[0]="["+this._id+"] "+e[0],Se.apply(null,e)}}Ce.WEBSOCKET_SUPPORT=!!Ee;const Ae=class extends o{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())}},Pe=L("bittorrent-tracker:websocket-tracker"),Te={};class Le extends Ae{constructor(e,t){super(e,t),Pe("new websocket tracker %s",t),this.peers={},this.socket=null,this.reconnecting=!1,this.retries=0,this.reconnectTimer=null,this.expectingResponse=!1,this._openSocket()}announce(e){if(this.destroyed||this.reconnecting)return;if(!this.socket.connected)return void this.socket.once("connect",(()=>{this.announce(e)}));const t=Object.assign({},e,{action:"announce",info_hash:this.client._infoHashBinary,peer_id:this.client._peerIdBinary});if(this._trackerId&&(t.trackerid=this._trackerId),"stopped"===e.event||"completed"===e.event)this._send(t);else{const n=Math.min(e.numwant,5);this._generateOffers(n,(e=>{t.numwant=n,t.offers=e,this._send(t)}))}}scrape(e){if(this.destroyed||this.reconnecting)return;if(!this.socket.connected)return void this.socket.once("connect",(()=>{this.scrape(e)}));const t={action:"scrape",info_hash:Array.isArray(e.infoHash)&&e.infoHash.length>0?e.infoHash.map((e=>(0,w.Ht)(e))):e.infoHash&&(0,w.Ht)(e.infoHash)||this.client._infoHashBinary};this._send(t)}destroy(e=Ie){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,Te[this.announceUrl]&&(Te[this.announceUrl].consumers-=1),Te[this.announceUrl].consumers>0)return e();let t,n=Te[this.announceUrl];if(delete Te[this.announceUrl],n.on("error",Ie),n.once("close",e),!this.expectingResponse)return s();function s(){t&&(clearTimeout(t),t=null),n.removeListener("data",s),n.destroy(),n=null}t=setTimeout(s,we.DESTROY_TIMEOUT),n.once("data",s)}_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=Te[this.announceUrl],this.socket)Te[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=this.client._proxyOpts.socksProxy)),this.socket=Te[this.announceUrl]=new Ce({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((0,w.dU)(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 Pe("ignoring websocket data from %s for %s (looking for %s: reused socket)",this.announceUrl,(0,w.HB)(e.info_hash),this.client.infoHash);if(e.peer_id&&e.peer_id===this.client._peerIdBinary)return;Pe("received %s from %s for %s",JSON.stringify(e),this.announceUrl,this.client.infoHash);const t=e["failure reason"];if(t)return this.client.emit("warning",new Error(t));const n=e["warning message"];n&&this.client.emit("warning",new Error(n));const s=e.interval||e["min interval"];s&&this.setInterval(1e3*s);const i=e["tracker id"];if(i&&(this._trackerId=i),null!=e.complete){const t=Object.assign({},e,{announce:this.announceUrl,infoHash:(0,w.HB)(e.info_hash)});this.client.emit("update",t)}let r;if(e.offer&&e.peer_id&&(Pe("creating peer (from remote offer)"),r=this._createPeer(),r.id=(0,w.HB)(e.peer_id),r.once("signal",(t=>{const n={action:"announce",info_hash:this.client._infoHashBinary,peer_id:this.client._peerIdBinary,to_peer_id:e.peer_id,answer:t,offer_id:e.offer_id};this._trackerId&&(n.trackerid=this._trackerId),this._send(n)})),this.client.emit("peer",r),r.signal(e.offer)),e.answer&&e.peer_id){const t=(0,w.HB)(e.offer_id);r=this.peers[t],r?(r.id=(0,w.HB)(e.peer_id),this.client.emit("peer",r),r.signal(e.answer),clearTimeout(r.trackerTimeout),r.trackerTimeout=null,delete this.peers[t]):Pe(`got unexpected answer: ${JSON.stringify(e.answer)}`)}}_onScrapeResponse(e){e=e.files||{};const t=Object.keys(e);0!==t.length?t.forEach((t=>{const n=Object.assign(e[t],{announce:this.announceUrl,infoHash:(0,w.HB)(t)});this.client.emit("scrape",n)})):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(),Pe("reconnecting socket in %s ms",e)}_send(e){if(this.destroyed)return;this.expectingResponse=!0;const t=JSON.stringify(e);Pe("send %s",t),this.socket.send(t)}_generateOffers(e,t){const n=this,s=[];Pe("generating %s offers",e);for(let t=0;t{s.push({offer:t,offer_id:(0,w.Ht)(e)}),r()})),t.trackerTimeout=setTimeout((()=>{Pe("tracker timeout: destroying peer"),t.trackerTimeout=null,delete n.peers[e],t.destroy()}),5e4),t.trackerTimeout.unref&&t.trackerTimeout.unref()}function r(){s.length===e&&(Pe("generated %s offers",e),t(s))}r()}_createPeer(e){const t=this;e=Object.assign({trickle:!1,config:t.client._rtcConfig,wrtc:t.client._wrtc},e);const n=new te(e);return n.once("error",s),n.once("connect",(function e(){n.removeListener("error",s),n.removeListener("connect",e)})),n;function s(e){t.client.emit("warning",new Error(`Connection error: ${e.message}`)),n.destroy()}}}function Ie(){}Le.prototype.DEFAULT_ANNOUNCE_INTERVAL=3e4,Le._socketPool=Te;const Oe=Le;var Re=i(717);const Ne=L("bittorrent-tracker:client");class He extends o{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(!Re.browser&&!e.port)throw new Error("Option `port` is required");this.peerId="string"==typeof e.peerId?e.peerId:(0,w.V5)(e.peerId),this._peerIdBuffer=(0,w.fk)(this.peerId),this._peerIdBinary=(0,w.Ht)(this.peerId),this.infoHash="string"==typeof e.infoHash?e.infoHash.toLowerCase():(0,w.V5)(e.infoHash),this._infoHashBuffer=(0,w.fk)(this.infoHash),this._infoHashBinary=(0,w.Ht)(this.infoHash),Ne("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=>(ArrayBuffer.isView(e)&&(e=(0,w.dU)(e)),"/"===e[e.length-1]&&(e=e.substring(0,e.length-1)),e))),t=Array.from(new Set(t));const n=!1!==this._wrtc&&(!!this._wrtc||te.WEBRTC_SUPPORT),s=e=>{b((()=>{this.emit("warning",e)}))};this._trackers=t.map((e=>{let t;try{t=we.parseUrl(e)}catch(t){return s(new Error(`Invalid tracker URL: ${e}`)),null}const i=t.port;if(i<0||i>65535)return s(new Error(`Invalid tracker port: ${e}`)),null;const r=t.protocol;return"http:"!==r&&"https:"!==r||"function"!=typeof ve?"udp:"===r&&"function"==typeof ke?new ke(this,e):"ws:"!==r&&"wss:"!==r||!n||"ws:"===r&&"undefined"!=typeof window&&"https:"===window.location.protocol?(s(new Error(`Unsupported tracker protocol: ${e}`)),null):new Oe(this,e):new ve(this,e)})).filter(Boolean)}start(e){(e=this._defaultAnnounceOpts(e)).event="started",Ne("send `start` %o",e),this._announce(e),this._trackers.forEach((e=>{e.setInterval()}))}stop(e){(e=this._defaultAnnounceOpts(e)).event="stopped",Ne("send `stop` %o",e),this._announce(e)}complete(e){e||(e={}),(e=this._defaultAnnounceOpts(e)).event="completed",Ne("send `complete` %o",e),this._announce(e)}update(e){(e=this._defaultAnnounceOpts(e)).event&&delete e.event,Ne("send `update` %o",e),this._announce(e)}_announce(e){this._trackers.forEach((t=>{t.announce(e)}))}scrape(e){Ne("send `scrape`"),e||(e={}),this._trackers.forEach((t=>{t.scrape(e)}))}setInterval(e){Ne("setInterval %d",e),this._trackers.forEach((t=>{t.setInterval(e)}))}destroy(e){if(this.destroyed)return;this.destroyed=!0,Ne("destroy");const t=this._trackers.map((e=>t=>{e.destroy(t)}));y(t,e),this._trackers=[],this._getAnnounceOpts=null}_defaultAnnounceOpts(e={}){return null==e.numwant&&(e.numwant=we.DEFAULT_ANNOUNCE_PEERS),null==e.uploaded&&(e.uploaded=0),null==e.downloaded&&(e.downloaded=0),this._getAnnounceOpts&&(e=Object.assign({},e,this._getAnnounceOpts())),e}}He.scrape=(e,t)=>{if(t=ye(t),!e.infoHash)throw new Error("Option `infoHash` is required");if(!e.announce)throw new Error("Option `announce` is required");const n=Object.assign({},e,{infoHash:Array.isArray(e.infoHash)?e.infoHash[0]:e.infoHash,peerId:(0,w.L0)("01234567890123456789"),port:6881}),s=new He(n);s.once("error",t),s.once("warning",t);let i=Array.isArray(e.infoHash)?e.infoHash.length:1;const r={};return s.on("scrape",(e=>{if(i-=1,r[e.infoHash]=e,0===i){s.destroy();const e=Object.keys(r);1===e.length?t(null,r[e[0]]):t(null,r)}})),s.scrape({infoHash:e.infoHash}),s};const Ue=He;i(7936);var Me=i(2799),Be=i(717);const De=L("torrent-discovery");class je extends o.EventEmitter{constructor(e){if(super(),!e.peerId)throw new Error("Option `peerId` is required");if(!e.infoHash)throw new Error("Option `infoHash` is required");if(!Be.browser&&!e.port)throw new Error("Option `port` is required");this.peerId="string"==typeof e.peerId?e.peerId:e.peerId.toString("hex"),this.infoHash="string"==typeof e.infoHash?e.infoHash.toLowerCase():e.infoHash.toString("hex"),this._port=e.port,this._userAgent=e.userAgent,this.destroyed=!1,this._announce=e.announce||[],this._intervalMs=e.intervalMs||9e5,this._trackerOpts=null,this._dhtAnnouncing=!1,this._dhtTimeout=!1,this._internalDHT=!1,this._onWarning=e=>{this.emit("warning",e)},this._onError=e=>{this.emit("error",e)},this._onDHTPeer=(e,t)=>{t.toString("hex")===this.infoHash&&this.emit("peer",`${e.host}:${e.port}`,"dht")},this._onTrackerPeer=e=>{this.emit("peer",e,"tracker")},this._onTrackerAnnounce=()=>{this.emit("trackerAnnounce")},this._onLSDPeer=(e,t)=>{this.emit("peer",e,"lsd")};const t=(e,t)=>{const n=new _e.Client(t);return n.on("warning",this._onWarning),n.on("error",this._onError),n.listen(e),this._internalDHT=!0,n};!1===e.tracker?this.tracker=null:e.tracker&&"object"==typeof e.tracker?(this._trackerOpts=Object.assign({},e.tracker),this.tracker=this._createTracker()):this.tracker=this._createTracker(),!1===e.dht||"function"!=typeof _e.Client?this.dht=null:e.dht&&"function"==typeof e.dht.addNode?this.dht=e.dht:e.dht&&"object"==typeof e.dht?this.dht=t(e.dhtPort,e.dht):this.dht=t(e.dhtPort),this.dht&&(this.dht.on("peer",this._onDHTPeer),this._dhtAnnounce()),!1===e.lsd||"function"!=typeof Me?this.lsd=null:this.lsd=this._createLSD()}updatePort(e){e!==this._port&&(this._port=e,this.dht&&this._dhtAnnounce(),this.tracker&&(this.tracker.stop(),this.tracker.destroy((()=>{this.tracker=this._createTracker()}))))}complete(e){this.tracker&&this.tracker.complete(e)}destroy(e){if(this.destroyed)return;this.destroyed=!0,clearTimeout(this._dhtTimeout);const t=[];this.tracker&&(this.tracker.stop(),this.tracker.removeListener("warning",this._onWarning),this.tracker.removeListener("error",this._onError),this.tracker.removeListener("peer",this._onTrackerPeer),this.tracker.removeListener("update",this._onTrackerAnnounce),t.push((e=>{this.tracker.destroy(e)}))),this.dht&&this.dht.removeListener("peer",this._onDHTPeer),this._internalDHT&&(this.dht.removeListener("warning",this._onWarning),this.dht.removeListener("error",this._onError),t.push((e=>{this.dht.destroy(e)}))),this.lsd&&(this.lsd.removeListener("warning",this._onWarning),this.lsd.removeListener("error",this._onError),this.lsd.removeListener("peer",this._onLSDPeer),t.push((e=>{this.lsd.destroy(e)}))),y(t,e),this.dht=null,this.tracker=null,this.lsd=null,this._announce=null}_createTracker(){const e=Object.assign({},this._trackerOpts,{infoHash:this.infoHash,announce:this._announce,peerId:this.peerId,port:this._port,userAgent:this._userAgent}),t=new Ue(e);return t.on("warning",this._onWarning),t.on("error",this._onError),t.on("peer",this._onTrackerPeer),t.on("update",this._onTrackerAnnounce),t.setInterval(this._intervalMs),t.start(),t}_dhtAnnounce(){this._dhtAnnouncing||(De("dht announce"),this._dhtAnnouncing=!0,clearTimeout(this._dhtTimeout),this.dht.announce(this.infoHash,this._port,(e=>{this._dhtAnnouncing=!1,De("dht announce complete"),e&&this.emit("warning",e),this.emit("dhtAnnounce"),this.destroyed||(this._dhtTimeout=setTimeout((()=>{this._dhtAnnounce()}),this._intervalMs+Math.floor(Math.random()*this._intervalMs/5)),this._dhtTimeout.unref&&this._dhtTimeout.unref())})))}_createLSD(){const e=Object.assign({},{infoHash:this.infoHash,peerId:this.peerId,port:this._port}),t=new Me(e);return t.on("warning",this._onWarning),t.on("error",this._onError),t.on("peer",this._onLSDPeer),t.start(),t}}const Fe=je;const qe=/[<>:"/\\|?*\u0000-\u001F]/g;"undefined"!=typeof navigator&&navigator.storage?.getDirectory&&navigator.storage.getDirectory().then((e=>{e.removeEntry("chunks",{recursive:!0}).catch((()=>{}))}));const We=()=>{};class $e{constructor(e,t={}){if(this.chunkLength=Number(e),!this.chunkLength)throw new Error("First argument must be a chunk length");if("undefined"==typeof navigator||!navigator.storage?.getDirectory)throw new Error("FSA API is not supported");if(this.closed=!1,this.name=t.name||crypto.randomUUID(),this.chunks=[],this.rootDirPromise=t.rootDir||navigator.storage.getDirectory(),this.storageDirPromise=(async()=>(await this.rootDirPromise).getDirectoryHandle(this.name,{create:!0}))(),this.chunksDirPromise=this.storageDirPromise,t.files&&t.rootDir){if(this.chunkMap=[],this.directoryMap={},this.chunksDirPromise=this._getChunksDirHandle(),this.files=t.files.map(((e,t,n)=>{if(null==e.path)throw new Error("File is missing `path` property");if(null==e.length)throw new Error("File is missing `length` property");if(null==e.offset)if(0===t)e.offset=0;else{const s=n[t-1];e.offset=s.offset+s.length}null==e.handle&&(e.handle=this._createFileHandle({path:e.path})),e.blob=this._createBlobReference(e.handle);const s=e.offset,i=e.offset+e.length,r=Math.floor(s/this.chunkLength),o=Math.floor((i-1)/this.chunkLength);for(let t=r;t<=o;++t){const n=t*this.chunkLength,r=sn+this.chunkLength?this.chunkLength:i-n,a=s>n?0:n-s;this.chunkMap[t]||(this.chunkMap[t]=[]),this.chunkMap[t].push({from:r,to:o,offset:a,file:e})}return e})),window.addEventListener("pagehide",(()=>this.cleanup())),this.length=this.files.reduce(((e,t)=>e+t.length),0),null!=t.length&&t.length!==this.length)throw new Error("total `files` length is not equal to explicit `length` option")}else this.length=Number(t.length)||1/0;this.length!==1/0&&(this.lastChunkLength=this.length%this.chunkLength||this.chunkLength,this.lastChunkIndex=Math.ceil(this.length/this.chunkLength)-1)}async _getChunkHandle(e){let t=this.chunks[e];if(!t){const n=await this.chunksDirPromise;this.chunks[e]=t=await n.getFileHandle(e,{create:!0})}return t}async _createFileHandle(e){const t=e.path.slice(e.path.lastIndexOf("/")+1);return(await this._getDirectoryHandle(e)).getFileHandle(t.replace(qe,""),{create:!0})}async _createBlobReference(e){return(await e).getFile()}async _getDirectoryHandle(e){const t=e.path.lastIndexOf("/");if(-1===t||0===t)return this.storageDirPromise;const n=e.path=e.path.slice(0,t);return this.directoryMap[n]||(this.directoryMap[n]=(async()=>(await this._getDirectoryHandle(e)).getDirectoryHandle(n.slice(n.lastIndexOf("/")+1),{create:!0}))()),this.directoryMap[n]}async _getChunksDirHandle(){const e=await navigator.storage.getDirectory();return(await e.getDirectoryHandle("chunks",{create:!0})).getDirectoryHandle(this.name,{create:!0})}async put(e,t,n=We){try{return await this._put(e,t),n(null),null}catch(e){return queueMicrotask((()=>n(e))),e}}async _put(e,t){if(this.closed)throw new Error("Storage is closed");const n=e===this.lastChunkIndex;if(n&&t.length!==this.lastChunkLength)throw new Error(`Last chunk length must be ${this.lastChunkLength}`);if(!n&&t.length!==this.chunkLength)throw new Error(`Chunk length must be ${this.chunkLength}`);const s=(async()=>{const n=await this._getChunkHandle(e),s=await n.createWritable({keepExistingData:!1});await s.write(t),await s.close()})();if(!this.files)return s;const i=this.chunkMap[e];if(!i)throw new Error("No files matching the request range");const r=i.map((async({file:e,offset:n,from:s,to:i})=>{e.stream||(e.stream=await(await e.handle).createWritable({keepExistingData:!0})),await e.stream.write({type:"write",position:n,data:t.slice(s,i)})}));r.push(s),await Promise.all(r)}async get(e,t,n=We){null==t&&(t={});try{const s=await this._get(e,t);return n(null,s),s}catch(e){return n(e),e}}async _get(e,t){if("function"==typeof t)return this.get(e,void 0,t);if(this.closed)throw new Error("Storage is closed");const n=e===this.lastChunkIndex?this.lastChunkLength:this.chunkLength,s=t.offset||0,i=t.length?s+t.length:n,r=t.length||n-s;if(s<0||s<0||i>n)throw new Error("Invalid offset and/or length");if(s===i)return new Uint8Array(0);if(!this.files||this.chunks[e]){const t=await this._getChunkHandle(e);let i=await t.getFile();0===s&&r===n||(i=i.slice(s,r+s));const o=await i.arrayBuffer();if(0===o.byteLength)throw new Error(`Index ${e} does not exist`);return new Uint8Array(o)}let o=this.chunkMap[e];if(!o)throw new Error("No files matching the request range");if(t&&(o=o.filter((({from:e,to:t})=>t>s&&e{t&&(n>i&&(n=i),equeueMicrotask((()=>e(new Error(t)))))(e,"Storage is closed");this.closed=!0,this.chunkMap=null,this.directoryMap=null,this.files&&await this.cleanup(),queueMicrotask((()=>e(null)))}async cleanup(){const e=[];for(const t of this.files)t.stream&&(e.push(t.stream.close()),t.stream=null);const t=(async()=>{const e=await this.chunksDirPromise;this.chunks=[];for await(const t of e.keys())await e.removeEntry(t,{recursive:!0});this.chunksDirPromise=await this._getChunksDirHandle()})();await Promise.all(e);for(const e of this.files)e.blob=this._createBlobReference(e.handle);await t}async destroy(e=We){this.close((async t=>{if(t)e(t);else{try{const e=await this.rootDirPromise;await e.removeEntry(this.name,{recursive:!0})}catch(t){return void e(t)}e(null)}}))}}var Ve=i(5570),ze=i(4862);const Ge=!!("undefined"!=typeof globalThis&&globalThis||"undefined"!=typeof self&&self||"undefined"!=typeof window&&window||"undefined"!=typeof globalThis&&globalThis).chrome?1/0:2130706432,Ke="undefined"!=typeof navigator&&navigator.storage?.getDirectory&&FileSystemFileHandle?.prototype?.createWritable,Ye=()=>{};class Je{constructor(e,t={}){if(this.chunkLength=Number(e),!this.chunkLength)throw new Error("First argument must be a chunk length");this.length=Number(t.length)||1/0,this.limit=t.limit||Ge,this.fallbackStore=null,this.dataStore=null,this.chunkCount=0,this.stores=[],this._init(t),this.dataStore&&(t.max>0&&(this.dataStore=new fe(this.dataStore,{max:t.max})),this.stores.push(this.dataStore)),this.stores.push(this.fallbackStore)}_init(e){if(e.onlyMem||this.limit=this.length)return void(this.fallbackStore=new t(this.chunkLength,e));this.chunkCount=Math.floor(Math.min(this.length,this.limit)/this.chunkLength);const n=this.chunkCount*this.chunkLength,s=this.length-n;this.dataStore=new t(this.chunkLength,{...e,length:n}),this.fallbackStore=new ze(this.chunkLength,{...e,length:s})}get(e,t,n){e>=this.chunkCount?this.fallbackStore.get(e-this.chunkCount,t,n):this.dataStore.get(e,t,n)}put(e,t,n){e>=this.chunkCount?this.fallbackStore.put(e-this.chunkCount,t,n):this.dataStore.put(e,t,n)}close(e=Ye){Promise.all(this.stores.map((e=>new Promise((t=>e.close(t)))))).then((t=>{const n=t.find((e=>e));e(n)}))}destroy(e=Ye){Promise.all(this.stores.map((e=>new Promise((t=>e.destroy(t)))))).then((t=>{const n=t.find((e=>e));e(n)}))}}var Xe=i(3714),Qe=i(1314);const Ze=L("lt_donthave"),et=()=>{class e extends o.EventEmitter{constructor(e){super(),this._peerSupports=!1,this._wire=e}onExtendedHandshake(){this._peerSupports=!0}onMessage(e){let t;try{t=new DataView(e.buffer).getUint32(0)}catch(e){return}this._wire.peerPieces.get(t)&&(Ze("got donthave %d",t),this._wire.peerPieces.set(t,!1),this.emit("donthave",t),this._failRequests(t))}donthave(e){if(!this._peerSupports)return;Ze("donthave %d",e);const t=new Uint8Array(4);new DataView(t.buffer).setUint32(0,e),this._wire.extended("lt_donthave",t)}_failRequests(e){const t=this._wire.requests;for(let n=0;n{class t extends o.EventEmitter{constructor(t){super(),this._wire=t,this._fetching=!1,this._metadataComplete=!1,this._metadataSize=null,this._remainingRejects=null,this._bitfield=new ue.A(0,{grow:1e3}),ArrayBuffer.isView(e)&&this.setMetadata(e)}onHandshake(e,t,n){this._infoHash=e}onExtendedHandshake(e){return e.m&&e.m.ut_metadata?e.metadata_size?"number"!=typeof e.metadata_size||1e7this._metadataSize&&(n=this._metadataSize);const s=this.metadata.slice(t,n);this._data(e,s,this._metadataSize)}_onData(e,t,n){t.length>ot||!this._fetching||(this.metadata.set(t,e*ot),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=new Uint8Array(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};var ht=i(8878),ct=i(1133);const lt=L("webtorrent:file-iterator");class dt extends o{constructor(e,{start:t,end:n}){super(),this._torrent=e._torrent,this._pieceLength=e._torrent.pieceLength,this._startPiece=(t+e.offset)/this._pieceLength|0,this._endPiece=(n+e.offset)/this._pieceLength|0,this._piece=this._startPiece,this._offset=t+e.offset-this._startPiece*this._pieceLength,this._missing=n-t+1,this._criticalLength=Math.min(1048576/this._pieceLength|0,2),this._torrent._select(this._startPiece,this._endPiece,1,null,!0),this.destroyed=!1}[Symbol.asyncIterator](){return this}next(){return new Promise(((e,t)=>{if(0===this._missing||this.destroyed)return e({done:!0}),this.destroy();const n=(s,i)=>{if(!this._torrent.bitfield.get(s)){const e=t=>{(t===s||this.destroyed)&&(this._torrent.removeListener("verified",e),n(s,i))};return this._torrent.on("verified",e),this._torrent.critical(s,s+this._criticalLength)}if(this._torrent.destroyed)return t(new Error("Torrent removed"));this._torrent.store.get(s,i,((n,i)=>this.destroyed?e({done:!0}):(lt("read %s and yielding (length %s) (err %s)",s,i?.length,n?.message),n?t(n):void e({value:i,done:!1}))))},s=Math.min(this._missing,this._pieceLength-this._offset);n(this._piece++,{length:s,offset:this._offset}),this._missing-=s,this._offset=0}))}async return(){return this.destroy(),{done:!0}}async throw(e){throw e}destroy(e=(()=>{}),t){this.destroyed||(this.destroyed=!0,this._torrent.destroyed||this._torrent._deselect(this._startPiece,this._endPiece,!0),this.emit("return"),e(t))}}class ut extends o{constructor(e,t){super(),this._torrent=e,this._destroyed=!1,this._fileStreams=new Set,this._iterators=new Set,this.name=t.name,this.path=t.path,this.length=t.length,this.size=t.length,this.type=ct.getType(this.name)||"application/octet-stream",this.offset=t.offset,this.done=!1;const n=t.offset,s=n+t.length-1;this._startPiece=n/this._torrent.pieceLength|0,this._endPiece=s/this._torrent.pieceLength|0,0===this.length&&(this.done=!0,this.emit("done")),this._client=e.client}get downloaded(){if(this._destroyed||!this._torrent.bitfield)return 0;const{pieces:e,bitfield:t,pieceLength:n,lastPieceLength:s}=this._torrent,{_startPiece:i,_endPiece:r}=this,o=i=>{const r=i===e.length-1?s:n;return t.get(i)?r:r-e[i].missing};let a=0;for(let t=i;t<=r;t+=1){const h=o(t);if(a+=h,t===i){const e=this.offset%n;a-=Math.min(e,h)}if(t===r){const t=(r===e.length-1?s:n)-(this.offset+this.length)%n;a-=Math.min(t,h)}}return a}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)}[Symbol.asyncIterator](e={}){if(0===this.length)return async function*(){}();const{start:t=0}=e??{},n=e?.end&&e.end{this._iterators.delete(s)})),s}createReadStream(e){const t=this[Symbol.asyncIterator](e),n=Y.Readable.from(t);return this._fileStreams.add(n),n.once("close",(()=>{this._fileStreams.delete(n)})),n}async arrayBuffer(e){const t=new Uint8Array(this.length);let n=0;for await(const s of this[Symbol.asyncIterator](e))t.set(s,n),n+=s.length;return t.buffer}async blob(e){return new Blob([await this.arrayBuffer(e)],{type:this.type})}stream(e){let t;return new ReadableStream({start:()=>{t=this[Symbol.asyncIterator](e)},async pull(e){const{value:n,done:s}=await t.next();s?e.close():e.enqueue(n)},cancel(){t.return()}})}get streamURL(){if(!this._client._server)throw new Error("No server created");return`${this._client._server.pathname}/${this._torrent.infoHash}/${this.path}`}streamTo(e){return e.src=this.streamURL,e}includes(e){return this._startPiece<=e&&this._endPiece>=e}_destroy(){this._destroyed=!0,this._torrent=null;for(const e of this._fileStreams)e.destroy();this._fileStreams.clear();for(const e of this._iterators)e.destroy();this._iterators.clear()}}var ft=i(5658);class pt{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=[],n=1/0;for(let s=0;s{this._cleanupWireEvents(e)})),this._torrent=null,this._pieces=null,this._onWire=null,this._onWireHave=null,this._onWireBitfield=null}_initWire(e){e._onClose=()=>{this._cleanupWireEvents(e);for(let t=0;t{const s=await(0,w.tW)(e,"hex");if(this.destroyed)return;this.handshake(t,s);const i=this._torrent.pieces.length,r=new ue.A(i);for(let e=0;e<=i;e++)r.set(e,!0);this.bitfield(r)})),this.once("interested",(()=>{yt("interested"),this.unchoke()})),this.on("uninterested",(()=>{yt("uninterested")})),this.on("choke",(()=>{yt("choke")})),this.on("unchoke",(()=>{yt("unchoke")})),this.on("bitfield",(()=>{yt("bitfield")})),this.lt_donthave.on("donthave",(()=>{yt("donthave")})),this.on("request",((e,t,n,s)=>{yt("request pieceIndex=%d offset=%d length=%d",e,t,n),this.httpRequest(e,t,n,((t,n)=>{if(t){this.lt_donthave.donthave(e);const t=setTimeout((()=>{this.destroyed||this.have(e)}),1e4);t.unref&&t.unref()}s(t,n)}))}))}async httpRequest(e,t,n,s){s=ye(s);const i=e*this._torrent.pieceLength+t,r=i+n-1,o=this._torrent.files;let a,h;if(o.length<=1)a=[{url:this.url,start:i,end:r}];else{const e=o.filter((e=>e.offset<=r&&e.offset+e.length>i));if(e.length<1)return s(new Error("Could not find file corresponding to web seed range request"));a=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-i,0),start:Math.max(i-e.offset,0),end:Math.min(t,r-e.offset)}}))}try{h=await Promise.all(a.map((async({start:s,end:i,url:r})=>{yt("Requesting url=%s pieceIndex=%d offset=%d length=%d start=%d end=%d",r,e,t,n,s,i);const o=await N(r,{cache:"no-store",method:"GET",headers:{"Cache-Control":"no-store","user-agent":`WebTorrent/${_t} (https://webtorrent.io)`,range:`bytes=${s}-${i}`},signal:AbortSignal.timeout(6e4)});if(!o.ok)throw new Error(`Unexpected HTTP status code ${o.status}`);const a=new Uint8Array(await o.arrayBuffer());return yt("Got data of length %d",a.length),a})))}catch(e){return s(e)}s(null,(0,w.xW)(h))}destroy(){super.destroy(),this._torrent=null}}class wt{_items=[];remove(e){for(let t=0;t=0&&0!==e.from&&s.push(i);const r={...n,from:e.to+1};r.to-r.from>=0&&s.push(r),this._items.splice(t,1,...s),t=t-1+s.length}else St(e,n)&&(this._items.splice(t,1),t--)}}insert(e){if(e.from>e.to)throw new Error("Invalid interval");if(!e.isStreamSelection){const{notify:t}=e,n=[];for(const t of this._items)t.notify&&Et(e,t)&&n.push(t.notify);n.length>0&&(e.notify=()=>{n.forEach((e=>e())),t?.()}),this.remove(e)}this._items.push(e)}sort(e=((e,t)=>e.from-t.from)){this._items.sort(e)}get length(){return this._items.length}get(e){return this._items[e]}swap(e,t){const n=this._items[e];this._items[e]=this._items[t],this._items[t]=n}clear(){this._items.length=0}*[Symbol.iterator](){for(let e=0;e{this._items.splice(e,1),e--},yield t,delete t.remove}}}function vt(e,t){return e.from<=t.to&&e.from>t.from&&e.to>t.to}function kt(e,t){return e.to>=t.from&&e.to=t.from&&e.to<=t.to&&s=t.to}const Et=(e,t)=>()=>vt(e,t)||kt(e,t)||xt(e,t)||St(e,t);var Ct=i(717);const At=L("webtorrent:torrent"),Pt=5e3,Tt=3*st.BLOCK_LENGTH,Lt=Ct.browser?me().length:2,It=[1e3,5e3,15e3],Ot=`WebTorrent/${_t} (https://webtorrent.io)`;let Rt;try{Rt=c(oe.statSync("/tmp")&&"/tmp","webtorrent")}catch(e){Rt=c("function"==typeof he.tmpdir?he.tmpdir():"/","webtorrent")}const Nt="undefined"!=typeof window&&"function"==typeof window.requestIdleCallback&&window.requestIdleCallback;class Ht extends o{constructor(e,t,n){super(),this._debugId="unknown infohash",this.client=t,this.announce=n.announce,this.urlList=n.urlList,this.path=n.path||Rt,this.addUID=n.addUID||!1,this.rootDir=n.rootDir||null,this.skipVerify=!!n.skipVerify,this._store=n.store||Je,this._preloadedStore=n.preloadedStore||null,this._storeCacheSlots=void 0!==n.storeCacheSlots?n.storeCacheSlots:20,this._destroyStoreOnDestroy=n.destroyStoreOnDestroy||!1,this.store=null,this.storeOpts=n.storeOpts,this.alwaysChokeSeeders=n.alwaysChokeSeeders??!0,this._getAnnounceOpts=n.getAnnounceOpts,"boolean"==typeof n.private&&(this.private=n.private),this.strategy=n.strategy||"sequential",this.maxWebConns=n.maxWebConns||4,this._rechokeNumSlots=!1===n.uploads||0===n.uploads?0:+n.uploads||10,this._rechokeOptimisticWire=null,this._rechokeOptimisticTime=0,this._rechokeIntervalId=null,this._noPeersIntervalId=null,this._noPeersIntervalTime=n.noPeersIntervalTime?1e3*n.noPeersIntervalTime:3e4,this._startAsDeselected=n.deselect||!1,this.ready=!1,this.destroyed=!1,this.paused=n.paused||!1,this.done=!1,this.metadata=null,this.files=[],this.pieces=[],this._amInterested=!1,this._selections=new wt,this._critical=[],this.wires=[],this._queue=[],this._peers={},this._peersLength=0,this.received=0,this.uploaded=0,this._downloadSpeed=ne(),this._uploadSpeed=ne(),this._servers=[],this._xsRequests=[],this._fileModtimes=n.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,n=this.pieces.length;t{this.destroyed||this._onParsedTorrent(t)}))):j(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=(0,w.V5)(e.infoHash).substring(0,7),void 0!==this.private&&(e.private=this.private),Array.isArray(this.announce)&&(e.announce=e.announce.concat(this.announce)),this.client.tracker&&Array.isArray(this.client.tracker.announce)&&!e.private&&(e.announce=e.announce.concat(this.client.tracker.announce)),this.client.tracker&&globalThis.WEBTORRENT_ANNOUNCE&&!e.private&&(e.announce=e.announce.concat(globalThis.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),this.torrentFile=function(e){const t={info:e.info};return t["announce-list"]=(e.announce||[]).map((e=>(t.announce||(t.announce=e),[e=(0,w.L0)(e)]))),t["url-list"]=e.urlList||[],void 0!==e.private&&(t.private=Number(e.private)),e.created&&(t["creation date"]=e.created.getTime()/1e3|0),e.createdBy&&(t["created by"]=e.createdBy),e.comment&&(t.comment=e.comment),d.A.encode(t)}(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,ft.default.SOURCE_MANUAL))),this.discovery=new Fe({infoHash:this.infoHash,announce:this.announce,peerId:this.client.peerId,dht:!this.private&&this.client.dht,tracker:e,port:this.client.torrentPort,userAgent:Ot,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),this.client.seedOutgoingConnections||!this.done?this.addPeer(e,t):this._debug("ignoring peer %s: torrent is done and seedOutgoingConnections is false",e)})),this.discovery.on("trackerAnnounce",(()=>{this.emit("trackerAnnounce")})),this.discovery.on("dhtAnnounce",(()=>{this.emit("dhtAnnounce")})),this.discovery.on("warning",(e=>{this.emit("warning",e)})),this._noPeersIntervalId=setInterval((()=>{if(this.destroyed)return;const e={[ft.default.SOURCE_TRACKER]:{enabled:!!this.client.tracker,numPeers:0},[ft.default.SOURCE_DHT]:{enabled:!!this.client.dht,numPeers:0},[ft.default.SOURCE_LSD]:{enabled:!!this.client.lsd,numPeers:0},[ft.default.SOURCE_UT_PEX]:{enabled:this.client.utPex&&"function"==typeof ht,numPeers:0}};for(const t of Object.values(this._peers)){const n=e[t.source];void 0!==n&&n.numPeers++}for(const t of Object.keys(e)){const n=e[t];n.enabled&&0===n.numPeers&&this.emit("noPeers",t)}}),this._noPeersIntervalTime),this._noPeersIntervalId.unref&&this._noPeersIntervalId.unref()}_getMetadataFromServer(){const e=this,t=Array.isArray(this.xs)?this.xs:[this.xs];e._xsRequestsController=new AbortController;const n=e._xsRequestsController.signal,s=t.map((t=>s=>{!async function(t,s){if(0!==t.indexOf("http://")&&0!==t.indexOf("https://"))return e.emit("warning",new Error(`skipping non-http xs param: ${t}`)),s(null);const i={method:"GET",headers:{"user-agent":Ot},signal:n};let r,o,a;try{r=await N(t,i)}catch(n){return e.emit("warning",new Error(`http error from xs param: ${t}`)),s(null)}if(e.destroyed)return s(null);if(e.metadata)return s(null);if(200!==r.status)return e.emit("warning",new Error(`non-200 status code ${r.status} from xs param: ${t}`)),s(null);try{o=new Uint8Array(await r.arrayBuffer())}catch(t){return e.emit("warning",t),s(null)}try{a=await W(o)}catch(e){}if(!a)return e.emit("warning",new Error(`got invalid torrent file from xs param: ${t}`)),s(null);if(a.infoHash!==e.infoHash)return e.emit("warning",new Error(`got torrent file with incorrect info hash from xs param: ${t}`)),s(null);e._onMetadata(a),s(null)}(t,s)}));y(s)}async _onMetadata(e){if(this.metadata||this.destroyed)return;let t;if(this._debug("got metadata"),this._xsRequestsController?.abort(),this._xsRequestsController=null,e&&e.infoHash)t=e;else try{t=await W(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 pt(this),this.files=this.files.map((e=>new ut(this,e)));let n=this._preloadedStore;if(n||(n=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,rootDir:this.rootDir,max:this._storeCacheSlots})),this._storeCacheSlots>0&&!(n instanceof ze||n instanceof Je)&&(n=new fe(n,{max:this._storeCacheSlots})),this.store=new Xe(n),this.so&&!this._startAsDeselected?this.files.forEach(((e,t)=>{this.so.includes(t)&&this.files[t].select()})):0===this.pieces.length||this._startAsDeselected||this.select(0,this.pieces.length-1,0),this._hashes=this.pieces,this.pieces=this.pieces.map(((e,t)=>{const n=t===this.pieces.length-1?this.lastPieceLength:this.pieceLength;return new st(n)})),this._reservations=this.pieces.map((()=>[])),this.bitfield=new ue.A(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===Je?this.getFileModtimes(((t,n)=>{if(t)return this._destroy(t);this.files.map(((e,t)=>n[t]===this._fileModtimes[t])).every((e=>e))?(this._markAllVerified(),this._onStore()):this._verifyPieces(e)})):this._verifyPieces(e)}}getFileModtimes(e){const t=[];tt(this.files.map(((e,n)=>s=>{const i=this.addUID?c(this.name+" - "+this.infoHash.slice(0,8)):c(this.path,e.path);oe.stat(i,((e,i)=>{if(e&&"ENOENT"!==e.code)return s(e);t[n]=i&&i.mtime.getTime(),s(null)}))})),Lt,(n=>{this._debug("done getting file modtimes"),e(n,t)}))}_verifyPieces(e){tt(this.pieces.map(((e,t)=>e=>{if(this.destroyed)return e(new Error("torrent is destroyed"));const n={};t===this.pieces.length-1&&(n.length=this.lastPieceLength),this.store.get(t,n,(async(n,s)=>{if(this.destroyed)return e(new Error("torrent is destroyed"));if(n)return b((()=>e(null)));const i=await(0,w.tW)(s,"hex");if(this.destroyed)return e(new Error("torrent is destroyed"));i===this._hashes[t]?(this._debug("piece verified %s",t),this._markVerified(t)):(this._markUnverified(t),this._debug("piece invalid %s",t)),e(null)}))})),Lt,e)}rescanFiles(e){if(this.destroyed)throw new Error("torrent is destroyed");e||(e=Mt),this._verifyPieces((t=>{if(t)return this._destroy(t),e(t);this._checkDone(),e(null)}))}_markAllVerified(){for(let e=0;e{t.done&&t.includes(e)&&(t.done=!1)}))}_hasAllPieces(){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,n){if("function"==typeof t)return this._destroy(e,null,t);if(this.destroyed)return;this.destroyed=!0,this._debug("destroy"),this.client._remove(this),this._selections.clear(),clearInterval(this._rechokeIntervalId),clearInterval(this._noPeersIntervalId),this._xsRequestsController?.abort(),this._rarityMap&&this._rarityMap.destroy();for(const e in this._peers)this.removePeer(e);this.files.forEach((e=>{e instanceof ut&&e._destroy()}));const s=this._servers.map((e=>t=>{e.destroy(t)}));if(this.discovery&&s.push((e=>{this.discovery.destroy(e)})),this.store){let e=this._destroyStoreOnDestroy;t&&void 0!==t.destroyStore&&(e=t.destroyStore),s.push((t=>{e?this.store.destroy(t):this.store.close(t)}))}y(s,n),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,t){if(this.destroyed)throw new Error("torrent is destroyed");if(!this.infoHash)throw new Error("addPeer() must not be called before the `infoHash` event");let n;if(this.client.blocked){if("string"==typeof e){let t;try{t=de(e)}catch(t){return this._debug("ignoring peer: invalid %s",e),this.emit("invalidPeer",e),!1}n=t[0]}else"string"==typeof e.remoteAddress&&(n=e.remoteAddress);if(n&&this.client.blocked.contains(n))return this._debug("ignoring peer: blocked %s",e),"string"!=typeof e&&e.destroy(),this.emit("blockedPeer",e),!1}const s=this.client.utp&&this._isIPv4(n)?"utp":"tcp",i=!!this._addPeer(e,s,t);return i?this.emit("peer",e):this.emit("invalidPeer",e),i}_addPeer(e,t,n){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 s=e&&e.id||e;if(this._peers[s])return this._debug("ignoring peer: duplicate (%s)",s),"string"!=typeof e&&e.destroy(),null;if(this.paused)return this._debug("ignoring peer: torrent is paused"),"string"!=typeof e&&e.destroy(),null;let i;return this._debug("add peer %s",s),i="string"==typeof e?"utp"===t?ft.default.createUTPOutgoingPeer(e,this,this.client.throttleGroups):ft.default.createTCPOutgoingPeer(e,this,this.client.throttleGroups):ft.default.createWebRTCPeer(e,this,this.client.throttleGroups),this._registerPeer(i),"string"==typeof e&&(this._queue.push(i),this._drain()),i}addWebSeed(e){if(this.destroyed)throw new Error("torrent is destroyed");let t,n;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);n=new bt(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(n=e,t=n.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 s=ft.default.createWebSeedPeer(n,t,this,this.client.throttleGroups);this._registerPeer(s),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?.id||e;e&&!e.id&&(e=this._peers?.[t]),e&&(e.destroy(),this.destroyed||(this._debug("removePeer %s",t),delete this._peers[t],this._peersLength-=1,this._drain()))}_select(e,t,n,s,i=!1){if(this.destroyed)throw new Error("torrent is destroyed");if(e<0||tt.priority-e.priority)),this._updateSelections()}select(e,t,n,s){this._select(e,t,n,s,!1)}_deselect(e,t,n=!1){if(this.destroyed)throw new Error("torrent is destroyed");this._debug("deselect %s-%s",e,t),this._selections.remove({from:e,to:t,isStreamSelection:n}),this._updateSelections()}deselect(e,t){this._deselect(e,t,!1)}critical(e,t){if(this.destroyed)throw new Error("torrent is destroyed");this._debug("critical %s-%s",e,t);for(let n=e;n<=t;++n)this._critical[n]=!0;this._updateSelections()}_onWire(e,t){if(this._debug("got wire %s (%s)",e._debugId,t||"Unknown"),this.wires.push(e),t){const n=de(t);e.remoteAddress=n[0],e.remotePort=n[1]}this.client.dht&&this.client.dht.listening&&e.on("port",(n=>{if(!this.destroyed&&!this.client.dht.destroyed){if(!e.remoteAddress)return this._debug("ignoring PORT from peer with no address");if(0===n||n>65536)return this._debug("ignoring invalid PORT from peer");this._debug("port: %s (from %s)",n,t),this.client.dht.addNode({host:e.remoteAddress,port:n})}})),e.on("timeout",(()=>{this._debug("wire timeout (%s)",t),e.destroy()})),"webSeed"!==e.type&&e.setTimeout(3e4,!0),e.setKeepAlive(!0),e.use(at(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()),this.client.utPex&&"function"==typeof ht&&!this.private&&(e.use(ht()),e.ut_pex.on("peer",(e=>{this.done||(this._debug("ut_pex: got peer: %s (from %s)",e,t),this.addPeer(e,ft.default.SOURCE_UT_PEX))})),e.ut_pex.on("dropped",(e=>{const n=this._peers[e];n&&!n.connected&&(this._debug("ut_pex: dropped peer: %s (from %s)",e,t),this.removePeer(e))})),e.once("close",(()=>{e.ut_pex.reset()}))),e.use(et()),this.emit("wire",e,t),this.ready&&b((()=>{this._onWireWithMetadata(e)}))}_onWireWithMetadata(e){let t=null;const n=()=>{this.destroyed||e.destroyed||(this._numQueued>2*(this._numConns-this.numPeers)&&e.amInterested?e.destroy():(t=setTimeout(n,Pt),t.unref&&t.unref()))};let s;const i=()=>{if(e.peerPieces.buffer.length===this.bitfield.buffer.length){for(s=0;s{i(),this._update(),this._updateWireInterest(e)})),e.on("have",(()=>{i(),this._update(),this._updateWireInterest(e)})),e.lt_donthave.on("donthave",(()=>{i(),this._update(),this._updateWireInterest(e)})),e.on("have-all",(()=>{e.isSeeder=!0,this.alwaysChokeSeeders&&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(n,Pt),t.unref&&t.unref()})),e.on("unchoke",(()=>{clearTimeout(t),this._update()})),e.on("request",((t,n,s,i)=>{if(s>131072)return e.destroy();this.pieces[t]||this.store.get(t,{offset:n,length:s},i)})),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(n,Pt),t.unref&&t.unref()),e.isSeeder=!1,i()}_updateSelections(){this.ready&&!this.destroyed&&(b((()=>{this._gcSelections()})),this._updateInterest(),this._update())}_gcSelections(){for(const e of this._selections){const t=e.offset;for(;this.bitfield.get(e.from+e.offset)&&e.from+e.offsetthis._updateWireInterest(e))),e!==this._amInterested&&(this._amInterested?this.emit("interested"):this.emit("uninterested"))}_updateWireInterest(e){let t=!1;for(let n=0;nthis._updateWireWrapper()),{timeout:250}):this._updateWireWrapper()}_updateWireWrapper(){if(this.destroyed)return;const e=it(this.wires);let t;for(;t=e();)this._updateWire(t)}_updateWire(e){if(e.destroyed)return!1;const t=this,n=Ut(e,.5);if(e.requests.length>=n)return;const s=Ut(e,1);if(e.peerChoking)e.hasFast&&e.peerAllowedFastSet.length>0&&!this._hasMorePieces(e.peerAllowedFastSet.length-1)&&function(){if(e.requests.length>=s)return!1;for(const n of e.peerAllowedFastSet){if(e.peerPieces.get(n)&&!t.bitfield.get(n))for(;t._request(e,n,!1)&&e.requests.length=s.from+s.offset;--r)if(e.peerPieces.get(r)&&t._request(e,r,!1))return}}();o(!1)||o(!0)}function i(t,n,s,i){return r=>r>=t&&r<=n&&!(r in s)&&e.peerPieces.get(r)&&(!i||i(r))}function r(e){let n=e;for(let s=e;s=s)return!0;const o=function(){const n=e.downloadSpeed()||1;if(n>Tt)return()=>!0;const s=Math.max(1,e.requests.length)*st.BLOCK_LENGTH/n;let i=10,r=0;return e=>{if(!i||t.bitfield.get(e))return!0;let o=t.pieces[e].missing;for(;r0))return i--,!1}return!0}}();for(let a=0;a({wire:e,random:Math.random()}))).sort(((e,t)=>{const n=e.wire,s=t.wire;return n.downloadSpeed()!==s.downloadSpeed()?n.downloadSpeed()-s.downloadSpeed():n.uploadSpeed()!==s.uploadSpeed()?n.uploadSpeed()-s.uploadSpeed():n.amChoking!==s.amChoking?n.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[(n=t.length,Math.random()*n|0)];e.unchoke(),this._rechokeOptimisticWire=e,this._rechokeOptimisticTime=2}}var n;e.filter((e=>e!==this._rechokeOptimisticWire)).forEach((e=>e.choke()))}_hotswap(e,t){const n=e.downloadSpeed();if(n=Tt||(2*a>n||a>o||(i=t,o=a))}if(!i)return!1;for(r=0;r=o)return!1;const a=s.pieces[t];let h=r?a.reserveRemaining():a.reserve();if(-1===h&&n&&s._hotswap(e,t)&&(h=r?a.reserveRemaining():a.reserve()),-1===h)return!1;let c=s._reservations[t];c||(c=s._reservations[t]=[]);let l=c.indexOf(null);-1===l&&(l=c.length),c[l]=e;const d=a.chunkOffset(h),u=r?a.chunkLengthRemaining(h):a.chunkLength(h);function f(){b((()=>{s._update()}))}return e.request(t,d,u,(async function n(i,o){if(s.destroyed)return;if(!s.ready)return s.once("ready",(()=>{n(i,o)}));if(c[l]===e&&(c[l]=null),a!==s.pieces[t])return f();if(i)return s._debug("error getting piece %s (offset: %s length: %s) from %s: %s",t,d,u,`${e.remoteAddress}:${e.remotePort}`,i.message),r?a.cancelRemaining(h):a.cancel(h),void f();if(s._debug("got piece %s (offset: %s length: %s) from %s",t,d,u,`${e.remoteAddress}:${e.remotePort}`),!a.set(h,o,e))return f();const p=a.flush(),g=await(0,w.tW)(p,"hex");s.destroyed||(g===s._hashes[t]?(s._debug("piece verified %s",t),s.store.put(t,p,(e=>{e?s._destroy(e):(s.pieces[t]=null,s._markVerified(t),s.wires.forEach((e=>{e.have(t)})),s._checkDone()&&!s.destroyed&&s.discovery.complete(),f())}))):(s.pieces[t]=new st(a.length),s.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 n=t.from;n<=t.to;n++)if(!this.bitfield.get(n)){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}async 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=Mt);try{await ge(this.store,_(e),{chunkLength:this.pieceLength}),this._markAllVerified(),this._checkDone(),t(null)}catch(e){return t(e),e}}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]}`,At(...e)}_drain(){if(this._debug("_drain numConns %s maxConns %s",this._numConns,this.client.maxConns),"function"!=typeof ae.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=de(e.addr),n={host:t[0],port:t[1]};this.client.utp&&e.type===ft.default.TYPE_UTP_OUTGOING?e.conn=gt.connect(n.port,n.host):e.conn=ae.connect(n);const s=e.conn;s.once("connect",(()=>{this.destroyed||e.onConnect()})),s.once("error",(t=>{e.destroy(t)})),e.startConnectTimeout(),s.on("close",(()=>{if(this.destroyed)return;if(e.retries>=It.length){if(this.client.utp){const t=this._addPeer(e.addr,"tcp",e.source);t&&(t.retries=0)}else this._debug("conn %s closed: will not re-add (max %s attempts)",e.addr,It.length);return}const t=It[e.retries];this._debug("conn %s closed: will re-add to queue in %sms (attempt %s)",e.addr,t,e.retries+1);const n=setTimeout((()=>{if(this.destroyed)return;const t=de(e.addr)[0],n=this.client.utp&&this._isIPv4(t)?"utp":"tcp",s=this._addPeer(e.addr,n,e.source);s&&(s.retries=e.retries+1)}),t);n.unref&&n.unref()}))}_validAddr(e){let t;try{t=de(e)}catch(e){return!1}const n=t[0],s=t[1];return s>0&&s<65535&&!("127.0.0.1"===n&&s===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)}}function Ut(e,t){let n=2+Math.ceil(t*e.downloadSpeed()/st.BLOCK_LENGTH);if(e.peerExtendedHandshake){const t=e.peerExtendedHandshake.reqq;"number"==typeof t&&t>0&&(n=Math.min(n,t))}return n}function Mt(){}var Bt=i(4043),Dt=i(580),jt=i(815),Ft=i(2878);class qt{constructor(e,t={}){this.client=e,t.origin||(t.origin="*"),this.opts=t,this.pendingReady=new Set}static serveIndexPage(e,t,n){const s=t.map((e=>`
  • \n \n ${Dt(e.name)}\n \n (${Dt(e.length)} bytes)\n
  • `)).join("
    ");return e.status=200,e.headers["Content-Type"]="text/html",e.body=Vt("WebTorrent",`

    WebTorrent

    \n
      ${s}
    `),e}isOriginAllowed(e){return!1!==this.opts.origin&&("*"===this.opts.origin||e.headers.origin===this.opts.origin)}static serveMethodNotAllowed(e){return e.status=405,e.headers["Content-Type"]="text/html",e.body=Vt("405 - Method Not Allowed","

    405 - Method Not Allowed

    "),e}static serve404Page(e){return e.status=404,e.headers["Content-Type"]="text/html",e.body=Vt("404 - Not Found","

    404 - Not Found

    "),e}static serveTorrentPage(e,t,n){const s=e.files.map((t=>`
  • \n \n ${Dt(t.path)}\n \n (${Dt(t.length)} bytes)\n
  • `)).join("
    ");return t.status=200,t.headers["Content-Type"]="text/html",t.body=Vt(`${Dt(e.name)} - WebTorrent`,`

    ${Dt(e.name)}

    \n
      ${s}
    `),t}static serveOptionsRequest(e,t){return t.status=204,t.headers["Access-Control-Max-Age"]="600",t.headers["Access-Control-Allow-Methods"]="GET,HEAD",e.headers["access-control-request-headers"]&&(t.headers["Access-Control-Allow-Headers"]=e.headers["access-control-request-headers"]),t}static serveFile(e,t,n){n.status=200,n.headers.Expires="0",n.headers["Cache-Control"]="no-cache, no-store, must-revalidate, max-age=0",n.headers["Accept-Ranges"]="bytes",n.headers["Content-Type"]=e.type,n.headers["transferMode.dlna.org"]="Streaming",n.headers["contentFeatures.dlna.org"]="DLNA.ORG_OP=01;DLNA.ORG_CI=0;DLNA.ORG_FLAGS=01700000000000000000000000000000","document"===t.destination?(n.headers["Content-Type"]="application/octet-stream",n.headers["Content-Disposition"]=`attachment; filename*=UTF-8''${zt(e.name)}`,n.body="DOWNLOAD"):n.headers["Content-Disposition"]=`inline; filename*=UTF-8''${zt(e.name)}`;let s=Ft(e.length,t.headers.range||"");if(Array.isArray(s)?(n.status=206,s=s[0],n.headers["Content-Range"]=`bytes ${s.start}-${s.end}/${e.length}`,n.headers["Content-Length"]=s.end-s.start+1):(n.statusCode=200,s=null,n.headers["Content-Length"]=e.length),"GET"===t.method){const i=e[Symbol.asyncIterator](s);let r=null;e.emit("iterator",{iterator:i,req:t,file:e},(e=>{r=e}));const o=Y.Readable.from(r||i);let a=null;e.emit("stream",{stream:o,req:t,file:e},(e=>{a=jt(o,e)})),n.body=a||o}else n.body=!1;return n}async onRequest(e,t){let n=new URL(e.url,"http://example.com").pathname;n=n.slice(n.indexOf(this.pathname)+this.pathname.length+1);const s={headers:{"X-Content-Type-Options":"nosniff","Content-Security-Policy":"base-uri 'none'; frame-ancestors 'none'; form-action 'none';"}};if(this.isOriginAllowed(e)&&(s.headers["Access-Control-Allow-Origin"]="*"===this.opts.origin?"*":e.headers.origin),"favicon.ico"===n)return t(qt.serve404Page(s));if("OPTIONS"===e.method)return this.isOriginAllowed(e)?t(qt.serveOptionsRequest(e,s)):t(qt.serveMethodNotAllowed(s));const i=async()=>{this.pendingReady.delete(i);const e=await r();t(e)},r=async()=>{if(""===n)return qt.serveIndexPage(s,this.client.torrents,this.pathname);let[t,...i]=n.split("/");i=decodeURI(i.join("/"));const r=await this.client.get(t);if(!t||!r)return qt.serve404Page(s);if(!i)return qt.serveTorrentPage(r,s,this.pathname);const o=r.files.find((e=>e.path.replace(/\\/g,"/")===i));return o?qt.serveFile(o,e,s):qt.serve404Page(s)};if("GET"===e.method||"HEAD"===e.method){if(this.client.ready){const e=await r();return t(e)}return this.pendingReady.add(i),void this.client.once("ready",i)}return t(qt.serveMethodNotAllowed(s))}close(e=(()=>{})){this.closed=!0,this.pendingReady.forEach((e=>{this.client.removeListener("ready",e)})),this.pendingReady.clear(),b(e)}destroy(e=(()=>{})){this.closed?b(e):this.close(e),this.client=null}}class Wt extends qt{constructor(e,t){super(e,t),this.server=Bt.createServer(),this._listen=this.server.listen,this.server.listen=this.listen.bind(this),this._close=this.server.close,this.server.close=this.close.bind(this),this.sockets=new Set,this.closed=!1,this.pathname=t?.pathname||"/webtorrent"}wrapRequest(e,t){return this.opts.hostname&&e.headers.host!==`${this.opts.hostname}:${this.server.address().port}`?e.destroy():new URL(e.url,"http://example.com").pathname.startsWith(this.pathname)?void this.onRequest(e,(({status:e,headers:n,body:s})=>{t.writeHead(e,n),s._readableState||s._writableState?jt(s,t):t.end(s)})):e.destroy()}onConnection(e){e.setTimeout(36e6),this.sockets.add(e),e.once("close",(()=>{this.sockets.delete(e)}))}address(){return this.server.address()}listen(...e){return this.closed=!1,this.server.on("connection",this.onConnection.bind(this)),this.server.on("request",this.wrapRequest.bind(this)),this._listen.apply(this.server,e)}close(e=(()=>{})){this.server.removeAllListeners("connection"),this.server.removeAllListeners("request"),this.server.removeAllListeners("listening"),super.close(),this._close.call(this.server,e)}destroy(e){this.sockets.forEach((e=>{e.destroy()})),super.destroy(e)}}class $t extends qt{constructor(e,t){super(e,t),this.registration=t.controller,this.workerKeepAliveInterval=null,this.workerPortCount=0;const n=new URL(t.controller.scope);this.pathname=n.pathname+"webtorrent",this._address={port:n.port,family:"IPv4",address:n.hostname},this.boundHandler=this.wrapRequest.bind(this),navigator.serviceWorker.addEventListener("message",this.boundHandler),fetch(`${this.pathname}/cancel/`).then((e=>{e.body.cancel()}))}wrapRequest(e){const t=e.data;if("webtorrent"===!t?.type||!t.url)return null;const[n]=e.ports;this.onRequest(t,(({status:e,headers:t,body:s})=>{const i=s[Symbol.asyncIterator]?.(),r=()=>{n.onmessage=null,s?.destroy&&s.destroy(),this.workerPortCount--,this.workerPortCount||(clearInterval(this.workerKeepAliveInterval),this.workerKeepAliveInterval=null)};n.onmessage=async e=>{if(e.data){let e;try{e=(await i.next()).value}catch(e){}n.postMessage(e),e||r(),this.workerKeepAliveInterval||(this.workerKeepAliveInterval=setInterval((()=>fetch(`${this.pathname}/keepalive/`)),2e4))}else r()},this.workerPortCount++,n.postMessage({status:e,headers:t,body:i?"STREAM":s})}))}listen(e,t){t()}address(){return this._address}close(e){navigator.serviceWorker.removeEventListener("message",this.boundHandler),super.close(e)}destroy(e){super.destroy(e)}}function Vt(e,t){return`\n \n \n \n \n ${e}\n \n \n ${t}\n \n \n `}function zt(e){return encodeURIComponent(e).replace(/['()]/g,escape).replace(/\*/g,"%2A").replace(/%(?:7C|60|5E)/g,unescape)}const Gt=L("webtorrent"),Kt=_t.replace(/\d*./g,(e=>("0"+e%100).slice(-2))).slice(0,4),Yt=`-WW${Kt}-`;class Jt extends o{constructor(e={}){super(),"string"==typeof e.peerId?this.peerId=e.peerId:ArrayBuffer.isView(e.peerId)?this.peerId=(0,w.V5)(e.peerId):this.peerId=(0,w.V5)((0,w.L0)(Yt+(0,w.NJ)((0,w.po)(9)))),this.peerIdBuffer=(0,w.fk)(this.peerId),"string"==typeof e.nodeId?this.nodeId=e.nodeId:ArrayBuffer.isView(e.nodeId)?this.nodeId=(0,w.V5)(e.nodeId):this.nodeId=(0,w.V5)((0,w.po)(20)),this.nodeIdBuffer=(0,w.fk)(this.nodeId),this._debugId=this.peerId.substring(0,7),this.destroyed=!1,this.listening=!1,this.torrentPort=e.torrentPort||0,this.dhtPort=e.dhtPort||0,this.tracker=void 0!==e.tracker?e.tracker:{},this.lsd=!1!==e.lsd,this.utPex=!1!==e.utPex,this.natUpnp=e.natUpnp??!0,this.natPmp=e.natPmp??!0,this.torrents=[],this.maxConns=Number(e.maxConns)||55,this.utp=Jt.UTP_SUPPORT&&!1!==e.utp,this.seedOutgoingConnections=e.seedOutgoingConnections??!0,this._downloadLimit=Math.max("number"==typeof e.downloadLimit?e.downloadLimit:-1,-1),this._uploadLimit=Math.max("number"==typeof e.uploadLimit?e.uploadLimit:-1,-1),(this.natUpnp||this.natPmp)&&"function"==typeof ie&&(this.natTraversal=new ie({enableUPNP:this.natUpnp,enablePMP:this.natPmp,upnpPermanentFallback:"permanent"===e.natUpnp})),!0===e.secure&&Promise.resolve().then(i.bind(i,5658)).then((({enableSecure:e})=>e())),this._debug("new webtorrent (peerId %s, nodeId %s, port %s)",this.peerId,this.nodeId,this.torrentPort),this.throttleGroups={down:new se.ThrottleGroup({rate:Math.max(this._downloadLimit,0),enabled:this._downloadLimit>=0}),up:new se.ThrottleGroup({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 re?this._connPool=new re(this):b((()=>{this._onListening()})),this._downloadSpeed=ne(),this._uploadSpeed=ne(),!1!==e.dht&&"function"==typeof I.Client?(this.dht=new I.Client(Object.assign({},{nodeId:this.nodeId},e.dht)),this.dht.once("error",(e=>{this._destroy(e)})),this.dht.once("listening",(()=>{const e=this.dht.address();e&&(this.dhtPort=e.port,this.natTraversal&&this.natTraversal.map({publicPort:this.dhtPort,privatePort:this.dhtPort,protocol:"udp",description:"WebTorrent DHT"}).catch((e=>{Gt("error mapping DHT port via UPnP/PMP: %o",e)})))})),this.dht.setMaxListeners(0),this.dht.listen(this.dhtPort)):this.dht=!1,this.enableWebSeeds=!1!==e.webSeeds;const t=()=>{this.destroyed||(this.ready=!0,this.emit("ready"))};"function"==typeof O&&null!=e.blocklist?O(e.blocklist,{headers:{"user-agent":`WebTorrent/${_t} (https://webtorrent.io)`}},((e,n)=>{if(e)return console.error(`Failed to load blocklist: ${e.message}`);this.blocked=n,t()})):b(t)}createServer(e,t){if(this.destroyed)throw new Error("torrent is destroyed");if(this._server)throw new Error("server already created");if("undefined"!=typeof window&&"node"!==t||"browser"===t){if(!(e?.controller instanceof ServiceWorkerRegistration))throw new Error("Invalid worker registration");if("activated"!==e.controller.active.state)throw new Error("Worker isn't activated");return this._server=new $t(this,e),this._server}return this._server=new Wt(this,e),this._server}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)}async get(e){if(e instanceof Ht){if(this.torrents.includes(e))return e}else{const t=this.torrents;let n;try{n=await W(e)}catch(e){}if(!n)return null;if(!n.infoHash)throw new Error("Invalid torrent identifier");for(const e of t)if(e.infoHash===n.infoHash)return e}return null}add(e,t={},n=(()=>{})){if(this.destroyed)throw new Error("client is destroyed");"function"==typeof t&&([t,n]=[{},t]);const s=()=>{if(!this.destroyed)for(const e of this.torrents)if(e.infoHash===r.infoHash&&e!==r)return r._destroy(new Error(`Cannot add duplicate torrent ${r.infoHash}`)),void n(e)},i=()=>{this.destroyed||(n(r),this.emit("torrent",r))};this._debug("add"),t=t?Object.assign({},t):{};const r=new Ht(e,this,t);return this.torrents.push(r),r.once("_infoHash",s),r.once("ready",i),r.once("close",(function e(){r.removeListener("_infoHash",s),r.removeListener("ready",i),r.removeListener("close",e)})),this.emit("add",r),r}seed(e,t,n){if(this.destroyed)throw new Error("client is destroyed");"function"==typeof t&&([t,n]=[{},t]),this._debug("seed"),(t=t?Object.assign({},t):{}).skipVerify=!0;const s="string"==typeof e;s&&(t.path=function(e){if(a(e),0===e.length)return".";let t=e.charCodeAt(0);const n=47===t;let s=-1,i=!0;for(let n=e.length-1;n>=1;--n)if(t=e.charCodeAt(n),47===t){if(!i){s=n;break}}else i=!1;return-1===s?n?"/":".":n&&1===s?"//":e.slice(0,s)}(e)),t.createdBy||(t.createdBy=`WebTorrent/${Kt}`);const i=e=>{this._debug("on seed"),"function"==typeof n&&n(e),e.emit("seed"),this.emit("seed",e)},r=this.add(null,t,(e=>{const n=[n=>{if(s||t.preloadedStore)return n();e.load(o,n)}];this.dht&&n.push((t=>{e.once("dhtAnnounce",t)})),y(n,(t=>{if(!this.destroyed)return t?e._destroy(t):void i(e)}))}));let o;var h;return h=e,"undefined"!=typeof FileList&&h instanceof FileList?e=Array.from(e):Array.isArray(e)||(e=[e]),y(e.map((e=>async n=>{if(!t.preloadedStore&&function(e){return"object"==typeof e&&null!=e&&"function"==typeof e.pipe}(e)){const t=[];try{for await(const n of e)t.push(n)}catch(e){return n(e)}const s=(0,w.xW)(t);s.name=e.name,n(null,s)}else n(null,e)})),((e,s)=>{if(!this.destroyed)return e?r._destroy(e):void function(e,t,n){"function"==typeof t&&([t,n]=[n,t]),S(e,t=t?Object.assign({},t):{},n)}(s,t,((e,i)=>{if(!this.destroyed){if(e)return r._destroy(e);o=i.map((e=>e.getStream)),T(s,t,(async(e,t)=>{if(this.destroyed)return;if(e)return r._destroy(e);const s=await this.get(t);s?(console.warn("A torrent with the same id is already being seeded"),r._destroy(),"function"==typeof n&&n(s)):r._onTorrentId(t)}))}}))})),r}async remove(e,t,n){if("function"==typeof t)return this.remove(e,null,t);this._debug("remove");const s=await this.get(e);if(!s)throw new Error(`No torrent with id ${e}`);this._remove(s,t,n)}_remove(e,t,n){if(!e)return;if("function"==typeof t)return this._remove(e,null,t);const s=this.torrents.indexOf(e);-1!==s&&(this.torrents.splice(s,1),e.destroy(t,n),this.dht&&this.dht._tables.remove(e.infoHash),this.emit("remove",e))}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 n=this.torrents.map((e=>t=>{e.destroy(t)}));this._connPool&&n.push((e=>{this._connPool.destroy(e)})),this.dht&&n.push((e=>{this.dht.destroy(e)})),this._server&&n.push((e=>{this._server.destroy(e)})),this.natTraversal&&n.push((e=>{this.natTraversal.destroy().then((()=>e()))})),y(n,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.natTraversal&&this.natTraversal.map({publicPort:this.torrentPort,privatePort:this.torrentPort,protocol:this.utp?null:"tcp",description:"WebTorrent Torrent"}).catch((e=>{Gt("error mapping WebTorrent port via UPnP/PMP: %o",e)})))}this.emit("listening")}_debug(){const e=[].slice.call(arguments);e[0]=`[${this._debugId}] ${e[0]}`,Gt(...e)}async _getByHash(e){for(const t of this.torrents)if(t.infoHashHash||(t.infoHashHash=await(0,w.tW)((0,w.fk)("72657132"+t.infoHash),"hex")),e===t.infoHashHash)return t;return null}}Jt.WEBRTC_SUPPORT=te.WEBRTC_SUPPORT,Jt.UTP_SUPPORT=re.UTP_SUPPORT,Jt.VERSION=_t;var Xt=r.A;export{Xt as default}; //# sourceMappingURL=webtorrent.min.js.map




    © 2015 - 2024 Weber Informatics LLC | Privacy Policy