Files
bitvid/js/webtorrent.min.js

2 lines
211 KiB
JavaScript
Raw Permalink Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

var e,t,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 s=new Uint8Array(t);let i=0;for(let t=0,n=e.length;t<n;t++){const n=e[t];s.set(n,i),i+=n.byteLength||n.length}return s}e.exports=async function*(e,s=512,i={}){"object"==typeof s&&(s=(i=s).size);let{nopad:n,zeroPadding:r=!0}=i;n&&(r=!1);let o=[],a=0;for await(const i of e)if(a+=i.byteLength||i.length||1,o.push(i),a>=s){const e=t(o,a);let i=0;for(;a>=s;)yield e.slice(i,i+s),a-=s,i+=s;o=[e.slice(i,e.length)]}a&&(yield t(o,r?s:a))}},4497:(e,t,s)=>{const i=s(8454),n=s(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 i(t)}put(e,t,s=()=>{}){if(!this.cache)return n((()=>s(new Error("CacheStore closed"))));this.cache.remove(e),this.store.put(e,t,s)}get(e,t,s=()=>{}){if("function"==typeof t)return this.get(e,null,t);if(!this.cache)return n((()=>s(new Error("CacheStore closed"))));t||(t={});let i=this.cache.get(e);if(i){const e=t.offset||0,r=t.length||i.length-e;return 0===e&&r===i.length||(i=i.slice(e,r+e)),n((()=>s(null,i)))}let r=this.inProgressGets.get(e);const o=!!r;r||(r=[],this.inProgressGets.set(e,r)),r.push({opts:t,cb:s}),o||this.store.get(e,((t,s)=>{t||null==this.cache||this.cache.set(e,s);const i=this.inProgressGets.get(e);this.inProgressGets.delete(e);for(const{opts:e,cb:n}of i)if(t)n(t);else{const t=e.offset||0,i=e.length||s.length-t;let r=s;0===t&&i===s.length||(r=s.slice(t,i+t)),n(null,r)}}))}close(e=()=>{}){if(!this.cache)return n((()=>e(new Error("CacheStore closed"))));this.cache=null,this.store.close(e)}destroy(e=()=>{}){if(!this.cache)return n((()=>e(new Error("CacheStore closed"))));this.cache=null,this.store.destroy(e)}}},4018:e=>{e.exports=function(){for(var e=navigator.hardwareConcurrency||1,t=[],s=0;s<e;s++)t.push({model:"",speed:0,times:{user:0,nice:0,sys:0,idle:0,irq:0}});return t}},7833:(e,t,s)=>{var i=s(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 s="color: "+this.color;t.splice(1,0,s,"color: inherit");let i=0,n=0;t[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(i++,"%c"===e&&(n=i))})),t.splice(n,0,s)},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!==i&&"env"in i&&(e=i.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;let e;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&&(e=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(e[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=s(736)(t);const{formatters:n}=e.exports;n.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}},736:(e,t,s)=>{e.exports=function(e){function t(e){let s,n,r,o=null;function a(...e){if(!a.enabled)return;const i=a,n=Number(new Date),r=n-(s||n);i.diff=r,i.prev=s,i.curr=n,s=n,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,((s,n)=>{if("%%"===s)return"%";o++;const r=t.formatters[n];if("function"==typeof r){const t=e[o];s=r.call(i,t),e.splice(o,1),o--}return s})),t.formatArgs.call(i,e);(i.log||t.log).apply(i,e)}return a.namespace=e,a.useColors=t.useColors(),a.color=t.selectColor(e),a.extend=i,a.destroy=t.destroy,Object.defineProperty(a,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==o?o:(n!==t.namespaces&&(n=t.namespaces,r=t.enabled(e)),r),set:e=>{o=e}}),"function"==typeof t.init&&t.init(a),a}function i(e,s){const i=t(this.namespace+(void 0===s?":":s)+e);return i.log=this.log,i}function n(e,t){let s=0,i=0,n=-1,r=0;for(;s<e.length;)if(i<t.length&&(t[i]===e[s]||"*"===t[i]))"*"===t[i]?(n=i,r=s,i++):(s++,i++);else{if(-1===n)return!1;i=n+1,r++,s=r}for(;i<t.length&&"*"===t[i];)i++;return i===t.length}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,...t.skips.map((e=>"-"+e))].join(",");return t.enable(""),e},t.enable=function(e){t.save(e),t.namespaces=e,t.names=[],t.skips=[];const s=("string"==typeof e?e:"").trim().replace(" ",",").split(",").filter(Boolean);for(const e of s)"-"===e[0]?t.skips.push(e.slice(1)):t.names.push(e)},t.enabled=function(e){for(const s of t.skips)if(n(e,s))return!1;for(const s of t.names)if(n(e,s))return!0;return!1},t.humanize=s(6585),t.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(e).forEach((s=>{t[s]=e[s]})),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let s=0;for(let t=0;t<e.length;t++)s=(s<<5)-s+e.charCodeAt(t),s|=0;return t.colors[Math.abs(s)%t.colors.length]},t.enable(t.load()),t}},6611:(e,t,s)=>{var i=s(717),n=s(3519),r=function(){},o=function(e,t,s){if("function"==typeof t)return o(e,null,t);t||(t={}),s=n(s||r);var a=e._writableState,h=e._readableState,l=t.readable||!1!==t.readable&&e.readable,c=t.writable||!1!==t.writable&&e.writable,d=!1,u=function(){e.writable||p()},p=function(){c=!1,l||s.call(e)},f=function(){l=!1,c||s.call(e)},m=function(t){s.call(e,t?new Error("exited with error code: "+t):null)},_=function(t){s.call(e,t)},g=function(){i.nextTick(y)},y=function(){if(!d)return(!l||h&&h.ended&&!h.destroyed)&&(!c||a&&a.ended&&!a.destroyed)?void 0:s.call(e,new Error("premature close"))},w=function(){e.req.on("finish",p)};return!function(e){return e.setHeader&&"function"==typeof e.abort}(e)?c&&!a&&(e.on("end",u),e.on("close",u)):(e.on("complete",p),e.on("abort",g),e.req?w():e.on("request",w)),function(e){return e.stdio&&Array.isArray(e.stdio)&&3===e.stdio.length}(e)&&e.on("exit",m),e.on("end",f),e.on("finish",p),!1!==t.error&&e.on("error",_),e.on("close",g),function(){d=!0,e.removeListener("complete",p),e.removeListener("abort",g),e.removeListener("request",w),e.req&&e.req.removeListener("finish",p),e.removeListener("end",u),e.removeListener("close",u),e.removeListener("finish",p),e.removeListener("exit",m),e.removeListener("end",f),e.removeListener("error",_),e.removeListener("close",g)}};e.exports=o},6310:e=>{function t(e,t){for(const s in t)Object.defineProperty(e,s,{value:t[s],enumerable:!0,configurable:!0});return e}e.exports=function(e,s,i){if(!e||"string"==typeof e)throw new TypeError("Please pass an Error to err-code");i||(i={}),"object"==typeof s&&(i=s,s=""),s&&(i.code=s);try{return t(e,i)}catch(s){i.message=e.message,i.stack=e.stack;const n=function(){};n.prototype=Object.create(Object.getPrototypeOf(e));return t(new n,i)}}},580:e=>{var t=/["'&<>]/;e.exports=function(e){var s,i=""+e,n=t.exec(i);if(!n)return i;var r="",o=0,a=0;for(o=n.index;o<i.length;o++){switch(i.charCodeAt(o)){case 34:s="&quot;";break;case 38:s="&amp;";break;case 39:s="&#39;";break;case 60:s="&lt;";break;case 62:s="&gt;";break;default:continue}a!==o&&(r+=i.substring(a,o)),a=o+1,r+=s}return a!==o?r+i.substring(a,o):r}},7007:e=>{var t=Object.create||function(e){var t=function(){};return t.prototype=e,new t},s=Object.keys||function(e){var t=[];for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&t.push(s);return s},i=Function.prototype.bind||function(e){var t=this;return function(){return t.apply(e,arguments)}};function n(){this._events&&Object.prototype.hasOwnProperty.call(this,"_events")||(this._events=t(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0}e.exports=n,n.EventEmitter=n,n.prototype._events=void 0,n.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?n.defaultMaxListeners:e._maxListeners}function l(e,s,i,n){var r,o,a;if("function"!=typeof i)throw new TypeError('"listener" argument must be a function');if((o=e._events)?(o.newListener&&(e.emit("newListener",s,i.listener?i.listener:i),o=e._events),a=o[s]):(o=e._events=t(null),e._eventsCount=0),a){if("function"==typeof a?a=o[s]=n?[i,a]:[a,i]:n?a.unshift(i):a.push(i),!a.warned&&(r=h(e))&&r>0&&a.length>r){a.warned=!0;var l=new Error("Possible EventEmitter memory leak detected. "+a.length+' "'+String(s)+'" listeners added. Use emitter.setMaxListeners() to increase limit.');l.name="MaxListenersExceededWarning",l.emitter=e,l.type=s,l.count=a.length,"object"==typeof console&&console.warn&&console.warn("%s: %s",l.name,l.message)}}else a=o[s]=i,++e._eventsCount;return e}function c(){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;t<e.length;++t)e[t]=arguments[t];this.listener.apply(this.target,e)}}function d(e,t,s){var n={fired:!1,wrapFn:void 0,target:e,type:t,listener:s},r=i.call(c,n);return r.listener=s,n.wrapFn=r,r}function u(e,t,s){var i=e._events;if(!i)return[];var n=i[t];return n?"function"==typeof n?s?[n.listener||n]:[n]:s?function(e){for(var t=new Array(e.length),s=0;s<t.length;++s)t[s]=e[s].listener||e[s];return t}(n):f(n,n.length):[]}function p(e){var t=this._events;if(t){var s=t[e];if("function"==typeof s)return 1;if(s)return s.length}return 0}function f(e,t){for(var s=new Array(t),i=0;i<t;++i)s[i]=e[i];return s}r?Object.defineProperty(n,"defaultMaxListeners",{enumerable:!0,get:function(){return o},set:function(e){if("number"!=typeof e||e<0||e!=e)throw new TypeError('"defaultMaxListeners" must be a positive number');o=e}}):n.defaultMaxListeners=o,n.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||isNaN(e))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=e,this},n.prototype.getMaxListeners=function(){return h(this)},n.prototype.emit=function(e){var t,s,i,n,r,o,a="error"===e;if(o=this._events)a=a&&null==o.error;else if(!a)return!1;if(a){if(arguments.length>1&&(t=arguments[1]),t instanceof Error)throw t;var h=new Error('Unhandled "error" event. ('+t+")");throw h.context=t,h}if(!(s=o[e]))return!1;var l="function"==typeof s;switch(i=arguments.length){case 1:!function(e,t,s){if(t)e.call(s);else for(var i=e.length,n=f(e,i),r=0;r<i;++r)n[r].call(s)}(s,l,this);break;case 2:!function(e,t,s,i){if(t)e.call(s,i);else for(var n=e.length,r=f(e,n),o=0;o<n;++o)r[o].call(s,i)}(s,l,this,arguments[1]);break;case 3:!function(e,t,s,i,n){if(t)e.call(s,i,n);else for(var r=e.length,o=f(e,r),a=0;a<r;++a)o[a].call(s,i,n)}(s,l,this,arguments[1],arguments[2]);break;case 4:!function(e,t,s,i,n,r){if(t)e.call(s,i,n,r);else for(var o=e.length,a=f(e,o),h=0;h<o;++h)a[h].call(s,i,n,r)}(s,l,this,arguments[1],arguments[2],arguments[3]);break;default:for(n=new Array(i-1),r=1;r<i;r++)n[r-1]=arguments[r];!function(e,t,s,i){if(t)e.apply(s,i);else for(var n=e.length,r=f(e,n),o=0;o<n;++o)r[o].apply(s,i)}(s,l,this,n)}return!0},n.prototype.addListener=function(e,t){return l(this,e,t,!1)},n.prototype.on=n.prototype.addListener,n.prototype.prependListener=function(e,t){return l(this,e,t,!0)},n.prototype.once=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.on(e,d(this,e,t)),this},n.prototype.prependOnceListener=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.prependListener(e,d(this,e,t)),this},n.prototype.removeListener=function(e,s){var i,n,r,o,a;if("function"!=typeof s)throw new TypeError('"listener" argument must be a function');if(!(n=this._events))return this;if(!(i=n[e]))return this;if(i===s||i.listener===s)0==--this._eventsCount?this._events=t(null):(delete n[e],n.removeListener&&this.emit("removeListener",e,i.listener||s));else if("function"!=typeof i){for(r=-1,o=i.length-1;o>=0;o--)if(i[o]===s||i[o].listener===s){a=i[o].listener,r=o;break}if(r<0)return this;0===r?i.shift():function(e,t){for(var s=t,i=s+1,n=e.length;i<n;s+=1,i+=1)e[s]=e[i];e.pop()}(i,r),1===i.length&&(n[e]=i[0]),n.removeListener&&this.emit("removeListener",e,a||s)}return this},n.prototype.removeAllListeners=function(e){var i,n,r;if(!(n=this._events))return this;if(!n.removeListener)return 0===arguments.length?(this._events=t(null),this._eventsCount=0):n[e]&&(0==--this._eventsCount?this._events=t(null):delete n[e]),this;if(0===arguments.length){var o,a=s(n);for(r=0;r<a.length;++r)"removeListener"!==(o=a[r])&&this.removeAllListeners(o);return this.removeAllListeners("removeListener"),this._events=t(null),this._eventsCount=0,this}if("function"==typeof(i=n[e]))this.removeListener(e,i);else if(i)for(r=i.length-1;r>=0;r--)this.removeListener(e,i[r]);return this},n.prototype.listeners=function(e){return u(this,e,!0)},n.prototype.rawListeners=function(e){return u(this,e,!1)},n.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):p.call(e,t)},n.prototype.listenerCount=p,n.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,s)=>{const i=s(5809);e.exports=class{constructor(e){this.hwm=e||16,this.head=new i(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 i(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(),s=this;let i=t.read();return{next(){const e=i;return i=t.read(),e},return:async n=>(await i,t.releaseLock(),e||s.cancel(),{done:!0,value:n}),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})}))},3714:(e,t,s)=>{const i=s(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,s=()=>{}){this.mem[e]=t,this.store.put(e,t,(t=>{this.mem[e]=null,s(t)}))}get(e,t,s=()=>{}){if("function"==typeof t)return this.get(e,null,t);let n=this.mem[e];if(!n)return this.store.get(e,t,s);t||(t={});const r=t.offset||0,o=t.length||n.length-r;0===r&&o===n.length||(n=n.slice(r,o+r)),i((()=>s(null,n)))}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 s=function(){};s.prototype=t.prototype,e.prototype=new s,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,s)=>{t.RateLimiter=s(3065),t.TokenBucket=s(5472)},3085:(e,t,s)=>{var i=s(717);e.exports=function(){if(void 0!==i&&i.hrtime){var e=i.hrtime(),t=e[0],s=e[1];return 1e3*t+Math.floor(s/1e6)}return(new Date).getTime()}},3065:(e,t,s)=>{var i=s(717),n=s(5472),r=s(3085),o=function(e,t,s){this.tokenBucket=new n(e,e,t,null),this.tokenBucket.content=e,this.curIntervalStart=r(),this.tokensThisInterval=0,this.fireImmediately=s};o.prototype={tokenBucket:null,curIntervalStart:0,tokensThisInterval:0,fireImmediately:!1,removeTokens:function(e,t){if(e>this.tokenBucket.bucketSize)return i.nextTick(t.bind(null,"Requested tokens "+e+" exceeds maximum tokens per interval "+this.tokenBucket.bucketSize,null)),!1;var s=this,n=r();if((n<this.curIntervalStart||n-this.curIntervalStart>=this.tokenBucket.interval)&&(this.curIntervalStart=n,this.tokensThisInterval=0),e>this.tokenBucket.tokensPerInterval-this.tokensThisInterval){if(this.fireImmediately)i.nextTick(t.bind(null,null,-1));else{var o=Math.ceil(this.curIntervalStart+this.tokenBucket.interval-n);setTimeout((function(){s.tokenBucket.removeTokens(e,a)}),o)}return!1}return this.tokenBucket.removeTokens(e,a);function a(i,n){if(i)return t(i,null);s.tokensThisInterval+=e,t(null,n)}},tryRemoveTokens:function(e){if(e>this.tokenBucket.bucketSize)return!1;var t=r();if((t<this.curIntervalStart||t-this.curIntervalStart>=this.tokenBucket.interval)&&(this.curIntervalStart=t,this.tokensThisInterval=0),e>this.tokenBucket.tokensPerInterval-this.tokensThisInterval)return!1;var s=this.tokenBucket.tryRemoveTokens(e);return s&&(this.tokensThisInterval+=e),s},getTokensRemaining:function(){return this.tokenBucket.drip(),this.tokenBucket.content}},e.exports=o},5472:(e,t,s)=>{var i=s(717),n=function(e,t,s,i){if(this.bucketSize=e,this.tokensPerInterval=t,"string"==typeof s)switch(s){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 "+s)}else this.interval=s;this.parentBucket=i,this.content=0,this.lastDrip=+new Date};n.prototype={bucketSize:1,tokensPerInterval:1,interval:1e3,parentBucket:null,content:0,lastDrip:0,removeTokens:function(e,t){var s=this;return this.bucketSize?e>this.bucketSize?(i.nextTick(t.bind(null,"Requested tokens "+e+" exceeds bucket size "+this.bucketSize,null)),!1):(this.drip(),e>this.content?n():this.parentBucket?this.parentBucket.removeTokens(e,(function(i,r){return i?t(i,null):e>s.content?n():(s.content-=e,void t(null,Math.min(r,s.content)))})):(this.content-=e,i.nextTick(t.bind(null,null,this.content)),!0)):(i.nextTick(t.bind(null,null,e,Number.POSITIVE_INFINITY)),!0);function n(){var i=Math.ceil((e-s.content)*(s.interval/s.tokensPerInterval));return setTimeout((function(){s.removeTokens(e,t)}),i),!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 s=t*(this.tokensPerInterval/this.interval);this.content=Math.min(this.content+s,this.bucketSize)}else this.content=this.bucketSize}},e.exports=n},8454:(e,t,s)=>{var i=s(7007),n=s(6698);function r(e){if(!(this instanceof r))return new r(e);"number"==typeof e&&(e={max:e}),e||(e={}),i.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,n(r,i.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,s){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=s,this.cache[this.tail].prev=null):(this.cache[t].next=s,this.cache[s].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 s;if("string"!=typeof e&&(e=""+e),this.cache.hasOwnProperty(e)){if((s=this.cache[e]).value=t,this.maxAge&&(s.modified=Date.now()),e===this.head)return t;this._unlink(e,s.prev,s.next)}else s={value:t,modified:0,next:null,prev:null},this.maxAge&&(s.modified=Date.now()),this.cache[e]=s,this.length===this.max&&this.evict();return this.length++,s.next=null,s.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,s)=>{e.exports=n;const i=s(9596);function n(e,t){if(!(this instanceof n))return new n(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)}n.prototype.put=function(e,t,s=()=>{}){if(this.closed)return i((()=>s(new Error("Storage is closed"))));const n=e===this.lastChunkIndex;return n&&t.length!==this.lastChunkLength?i((()=>s(new Error("Last chunk length must be "+this.lastChunkLength)))):n||t.length===this.chunkLength?(this.chunks[e]=t,void i((()=>s(null)))):i((()=>s(new Error("Chunk length must be "+this.chunkLength))))},n.prototype.get=function(e,t,s=()=>{}){if("function"==typeof t)return this.get(e,null,t);if(this.closed)return i((()=>s(new Error("Storage is closed"))));let n=this.chunks[e];if(!n){const e=new Error("Chunk not found");return e.notFound=!0,i((()=>s(e)))}t||(t={});const r=t.offset||0,o=t.length||n.length-r;0===r&&o===n.length||(n=n.slice(r,o+r)),i((()=>s(null,n)))},n.prototype.close=n.prototype.destroy=function(e=()=>{}){if(this.closed)return i((()=>e(new Error("Storage is closed"))));this.closed=!0,this.chunks=null,i((()=>e(null)))}},8673:e=>{function t(){this._types=Object.create(null),this._extensions=Object.create(null);for(let e=0;e<arguments.length;e++)this.define(arguments[e]);this.define=this.define.bind(this),this.getType=this.getType.bind(this),this.getExtension=this.getExtension.bind(this)}t.prototype.define=function(e,t){for(let s in e){let i=e[s].map((function(e){return e.toLowerCase()}));s=s.toLowerCase();for(let e=0;e<i.length;e++){const n=i[e];if("*"!==n[0]){if(!t&&n in this._types)throw new Error('Attempt to change mapping for "'+n+'" extension from "'+this._types[n]+'" to "'+s+'". Pass `force=true` to allow this, otherwise remove "'+n+'" from the list of extensions for "'+s+'".');this._types[n]=s}}if(t||!this._extensions[s]){const e=i[0];this._extensions[s]="*"!==e[0]?e:e.substr(1)}}},t.prototype.getType=function(e){let t=(e=String(e)).replace(/^.*[/\\]/,"").toLowerCase(),s=t.replace(/^.*\./,"").toLowerCase(),i=t.length<e.length;return(s.length<t.length-1||!i)&&this._types[s]||null},t.prototype.getExtension=function(e){return(e=/^\s*([^;\s]*)/.test(e)&&RegExp.$1)&&this._extensions[e.toLowerCase()]||null},e.exports=t},1133:(e,t,s)=>{let i=s(8673);e.exports=new i(s(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,s=60*t,i=60*s,n=24*i,r=7*n,o=365.25*n;function a(e,t,s,i){var n=t>=1.5*s;return Math.round(e/s)+" "+i+(n?"s":"")}e.exports=function(e,h){h=h||{};var l=typeof e;if("string"===l&&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*n;case"hours":case"hour":case"hrs":case"hr":case"h":return h*i;case"minutes":case"minute":case"mins":case"min":case"m":return h*s;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"===l&&isFinite(e))return h.long?function(e){var r=Math.abs(e);if(r>=n)return a(e,r,n,"day");if(r>=i)return a(e,r,i,"hour");if(r>=s)return a(e,r,s,"minute");if(r>=t)return a(e,r,t,"second");return e+" ms"}(e):function(e){var r=Math.abs(e);if(r>=n)return Math.round(e/n)+"d";if(r>=i)return Math.round(e/i)+"h";if(r>=s)return Math.round(e/s)+"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,s)=>{var i=s(6587);function n(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)},s=e.name||"Function wrapped with `once`";return t.onceError=s+" shouldn't be called more than once",t.called=!1,t}e.exports=i(n),e.exports.strict=i(r),n.proto=n((function(){Object.defineProperty(Function.prototype,"once",{value:function(){return n(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<<Math.log2(e<1024?1:e/1024)+.5)}},815:(e,t,s)=>{var i,n=s(717),r=s(3519),o=s(6611);try{i=s(2376)}catch(e){}var a=function(){},h=/^v?\.0/.test(n.version),l=function(e){return"function"==typeof e},c=function(e,t,s,n){n=r(n);var c=!1;e.on("close",(function(){c=!0})),o(e,{readable:t,writable:s},(function(e){if(e)return n(e);c=!0,n()}));var d=!1;return function(t){if(!c&&!d)return d=!0,function(e){return!!h&&!!i&&(e instanceof(i.ReadStream||a)||e instanceof(i.WriteStream||a))&&l(e.close)}(e)?e.close(a):function(e){return e.setHeader&&l(e.abort)}(e)?e.abort():l(e.destroy)?e.destroy():void n(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),s=l(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 i=t.map((function(n,r){var o=r<t.length-1;return c(n,o,r>0,(function(t){e||(e=t),t&&i.forEach(d),o||(i.forEach(d),s(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 s=e.length-t,i=Math.random()*s|0,n=e[t+i],r=e[t];return e[t]=n,e[t+i]=r,t++,n}}},2878:e=>{function t(e,t){return{start:e.start,end:e.end,index:t}}function s(e){return{start:e.start,end:e.end}}function i(e,t){return e.index-t.index}function n(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(","),l=[];l.type=r.slice(0,a);for(var c=0;c<h.length;c++){var d=h[c].split("-"),u=parseInt(d[0],10),p=parseInt(d[1],10);isNaN(u)?(u=e-p,p=e-1):isNaN(p)&&(p=e-1),p>e-1&&(p=e-1),isNaN(u)||isNaN(p)||u>p||u<0||l.push({start:u,end:p})}if(l.length<1)return-1;return o&&o.combine?function(e){for(var r=e.map(t).sort(n),o=0,a=1;a<r.length;a++){var h=r[a],l=r[o];h.start>l.end+1?r[++o]=h:h.end>l.end&&(l.end=h.end,l.index=Math.min(l.index,h.index))}r.length=o+1;var c=r.sort(i).map(s);return c.type=e.type,c}(l):l}},8727:e=>{function t(e){return parseInt(e,10)===e}function s(e){function s(t){if(void 0===t){t=new Array(e);for(var s=0;s<e;s++)t[s]=Math.floor(Math.random()*e)}else if("string"==typeof t)t=(t=""+t).split("").map((function(t){return t.charCodeAt(0)%e}));else{if(!Array.isArray(t))throw new TypeError("invalid seed key specified");if(!t.every((function(e){return"number"==typeof e&&e===(0|e)})))throw new TypeError("invalid seed key specified: not array of integers")}for(var i=t.length,n=function(){for(var t=new Array(e),s=0;s<e;s++)t[s]=s;return t}(),r=0,o=0;o<e;o++){r=(r+n[o]+t[o%i])%e;var a=n[o];n[o]=n[r],n[r]=a}return n}function i(e){this.s=s(e),this.i=0,this.j=0}return i.prototype.randomNative=function(){this.i=(this.i+1)%e,this.j=(this.j+this.s[this.i])%e;var t=this.s[this.i];return this.s[this.i]=this.s[this.j],this.s[this.j]=t,this.s[(this.s[this.i]+this.s[this.j])%e]},i.prototype.randomUInt32=function(){return 256*(256*(256*this.randomByte()+this.randomByte())+this.randomByte())+this.randomByte()},i.prototype.randomFloat=function(){return this.randomUInt32()/4294967296},i.prototype.random=function(){var e,s;if(1===arguments.length)e=0,s=arguments[0];else{if(2!==arguments.length)throw new TypeError("random takes one or two integer arguments");e=arguments[0],s=arguments[1]}if(!t(e)||!t(s))throw new TypeError("random takes one or two integer arguments");return e+this.randomUInt32()%(s-e+1)},i.prototype.currentState=function(){return{i:this.i,j:this.j,s:this.s.slice()}},i.prototype.setState=function(t){var s=t.s,i=t.i,n=t.j;if(!(i===(0|i)&&0<=i&&i<e))throw new Error("state.i should be integer [0, "+(e-1)+"]");if(!(n===(0|n)&&0<=n&&n<e))throw new Error("state.j should be integer [0, "+(e-1)+"]");if(!Array.isArray(s)||s.length!==e)throw new Error("state should be array of length "+e);for(var r=0;r<e;r++)if(-1===s.indexOf(r))throw new Error("state should be permutation of 0.."+(e-1)+": "+r+" is missing");this.i=i,this.j=n,this.s=s.slice()},i}var i=s(256);i.prototype.randomByte=i.prototype.randomNative;var n=s(16);n.prototype.randomByte=function(){return 16*this.randomNative()+this.randomNative()};var r="a".charCodeAt(0),o="0".charCodeAt(0);function a(e){return e<10?String.fromCharCode(o+e):String.fromCharCode(r+e-10)}function h(e){return parseInt(e,16)}n.prototype.currentStateString=function(){var e=this.currentState();return a(e.i)+a(e.j)+e.s.map(a).join("")},n.prototype.setStateString=function(e){if(!e.match(/^[0-9a-f]{18}$/))throw new TypeError("RC4small stateString should be 18 hex character string");var t=h(e[0]),s=h(e[1]),i=e.split("").slice(2).map(h);this.setState({i:t,j:s,s:i})},i.RC4small=n,e.exports=i},5372:(e,t,s)=>{e.exports=function(e,t,s){if("number"!=typeof t)throw new Error("second argument must be a Number");let n,r,o,a,h,l,c=!0;Array.isArray(e)?(n=[],o=r=e.length):(a=Object.keys(e),n={},o=r=a.length);function d(e){function t(){s&&s(e,n),s=null}c?i(t):t()}function u(t,s,i){if(n[t]=i,s&&(h=!0),0==--o||s)d(s);else if(!h&&l<r){let t;a?(t=a[l],l+=1,e[t]((function(e,s){u(t,e,s)}))):(t=l,l+=1,e[t]((function(e,s){u(t,e,s)})))}}l=t,o?a?a.some((function(s,i){return e[s]((function(e,t){u(s,e,t)})),i===t-1})):e.some((function(e,s){return e((function(e,t){u(s,e,t)})),s===t-1})):d(null);c=!1};const i=s(9596)},8190:(e,t,s)=>{e.exports=function(e,t){let s,n,r,o=!0;Array.isArray(e)?(s=[],n=e.length):(r=Object.keys(e),s={},n=r.length);function a(e){function n(){t&&t(e,s),t=null}o?i(n):n()}function h(e,t,i){s[e]=i,(0==--n||t)&&a(t)}n?r?r.forEach((function(t){e[t]((function(e,s){h(t,e,s)}))})):e.forEach((function(e,t){e((function(e,s){h(t,e,s)}))})):a(null);o=!1};const i=s(9596)},7541:(e,t,s)=>{const i=s(8765),n=s(8499);e.exports={Throttle:i,ThrottleGroup:n}},8499:(e,t,s)=>{const{TokenBucket:i}=s(9439),n=s(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 i(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 n({...e,group:this})}destroy(){for(const e of this.throttles)e.destroy();this.throttles=[]}_addThrottle(e){if(!(e instanceof n))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,s)=>{const{EventEmitter:i}=s(7007),{Transform:n}=s(8179),{wait:r}=s(2072);e.exports=class extends n{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 i,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,s)=>{let i=!1;const n=this;function r(e){if(n._emitter.removeListener("disabled",r),n._emitter.removeListener("destroyed",r),!i){if(i=!0,e)return s(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 s=0,i=this._group.getChunksize(),n=e.slice(s,s+i);for(;n.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(n.length)&&(await this._waitForTokens(n.length),this._destroyed))return}catch(e){return t(e)}this.push(n),s+=i,i=this._areBothEnabled()?this._group.getChunksize():e.length-s,n=e.slice(s,s+i)}return t()}destroy(...e){this._group._removeThrottle(this),this._destroyed=!0,this._emitter.emit("destroyed"),super.destroy(...e)}};const o=s(8499)},2072:e=>{e.exports={wait:function(e){return new Promise((t=>setTimeout(t,e)))}}},8179:(e,t,s)=>{const{EventEmitter:i}=s(7007),n=new Error("Stream was destroyed"),r=new Error("Premature close"),o=s(2133),a=s(6080),h=s(5335),l=536870911,c=1^l,d=2^l,u=64,p=128,f=256,m=1024,_=2048,g=4096,y=8192,w=16384,b=32768,v=131072,k=131328,x=16^l,S=536805375,E=768^l,C=536838143,A=32^l,T=536739839,P=1<<18,I=2<<18,L=4<<18,O=8<<18,R=16<<18,H=32<<18,N=64<<18,M=128<<18,U=256<<18,F=512<<18,j=1024<<18,B=535822335,D=503316479,q=268435455,W=262160,$=536608751,z=8404992,V=14,G=15,K=8405006,Y=33587200,J=33587215,X=2359296,Q=270794767,Z=Symbol.asyncIterator||Symbol("asyncIterator");class ee{constructor(e,{highWaterMark:t=16384,map:s=null,mapWritable:i,byteLength:n,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||n||Se,this.map=i||s,this.afterWrite=ae.bind(this),this.afterUpdateNextTick=ce.bind(this)}get ended(){return!!(this.stream._duplexState&H)}push(e){return!(142606350&this.stream._duplexState)&&(null!==this.map&&(e=this.map(e)),this.buffered+=this.byteLength(e),this.queue.push(e),this.buffered<this.highWaterMark?(this.stream._duplexState|=O,!0):(this.stream._duplexState|=6291456,!1))}shift(){const e=this.queue.shift();return this.buffered-=this.byteLength(e),0===this.buffered&&(this.stream._duplexState&=534773759),e}end(e){"function"==typeof e?this.stream.once("finish",e):null!=e&&this.push(e),this.stream._duplexState=(this.stream._duplexState|F)&B}autoBatch(e,t){const s=[],i=this.stream;for(s.push(e);(i._duplexState&Q)===X;)s.push(i._writableState.shift());if(i._duplexState&G)return t(null);i._writev(s,t)}update(){const e=this.stream;e._duplexState|=I;do{for(;(e._duplexState&Q)===O;){const t=this.shift();e._duplexState|=67371008,e._write(t,this.afterWrite)}1310720&e._duplexState||this.updateNonPrimary()}while(!0===this.continueUpdate());e._duplexState&=536346623}updateNonPrimary(){const e=this.stream;if((144965647&e._duplexState)===F)return e._duplexState=e._duplexState|P,void e._final(re.bind(this));4!=(e._duplexState&V)?1==(e._duplexState&J)&&(e._duplexState=(e._duplexState|W)&c,e._open(de.bind(this))):e._duplexState&Y||(e._duplexState|=W,e._destroy(oe.bind(this)))}continueUpdate(){return!!(this.stream._duplexState&M)&&(this.stream._duplexState&=D,!0)}updateCallback(){(35127311&this.stream._duplexState)===L?this.update():this.updateNextTick()}updateNextTick(){this.stream._duplexState&M||(this.stream._duplexState|=M,this.stream._duplexState&I||o(this.afterUpdateNextTick))}}class te{constructor(e,{highWaterMark:t=16384,map:s=null,mapReadable:i,byteLength:n,byteLengthReadable:r}={}){this.stream=e,this.queue=new a,this.highWaterMark=0===t?1:t,this.buffered=0,this.readAhead=t>0,this.error=null,this.pipeline=null,this.byteLength=r||n||Se,this.map=i||s,this.pipeTo=null,this.afterRead=he.bind(this),this.afterUpdateNextTick=le.bind(this)}get ended(){return!!(this.stream._duplexState&w)}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 ie(this.stream,e,t),t&&this.stream.on("error",Ee),xe(e))e._writableState.pipeline=this.pipeline,t&&e.on("error",Ee),e.on("finish",this.pipeline.finished.bind(this.pipeline));else{const t=this.pipeline.done.bind(this.pipeline,e),s=this.pipeline.done.bind(this.pipeline,e,null);e.on("error",t),e.on("close",s),e.on("finish",this.pipeline.finished.bind(this.pipeline))}e.on("drain",ne.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))?(t._duplexState&=S,this.buffered<this.highWaterMark):(this.buffered+=this.byteLength(e),this.queue.push(e),t._duplexState=(t._duplexState|p)&S,this.buffered<this.highWaterMark)}shift(){const e=this.queue.shift();return this.buffered-=this.byteLength(e),0===this.buffered&&(this.stream._duplexState&=536862591),e}unshift(e){const t=[null!==this.map?this.map(e):e];for(;this.buffered>0;)t.push(this.shift());for(let e=0;e<t.length-1;e++){const s=t[e];this.buffered+=this.byteLength(s),this.queue.push(s)}this.push(t[t.length-1])}read(){const e=this.stream;if((16527&e._duplexState)===p){const t=this.shift();return null!==this.pipeTo&&!1===this.pipeTo.write(t)&&(e._duplexState&=E),e._duplexState&_&&e.emit("data",t),t}return!1===this.readAhead&&(e._duplexState|=v,this.updateNextTick()),null}drain(){const e=this.stream;for(;(16527&e._duplexState)===p&&768&e._duplexState;){const t=this.shift();null!==this.pipeTo&&!1===this.pipeTo.write(t)&&(e._duplexState&=E),e._duplexState&_&&e.emit("data",t)}}update(){const e=this.stream;e._duplexState|=32;do{for(this.drain();this.buffered<this.highWaterMark&&(214047&e._duplexState)===v;)e._duplexState|=65552,e._read(this.afterRead),this.drain();4224==(12431&e._duplexState)&&(e._duplexState|=y,e.emit("readable")),80&e._duplexState||this.updateNonPrimary()}while(!0===this.continueUpdate());e._duplexState&=A}updateNonPrimary(){const e=this.stream;(1167&e._duplexState)===m&&(e._duplexState=536869887&e._duplexState|16384,e.emit("end"),(e._duplexState&K)===z&&(e._duplexState|=4),null!==this.pipeTo&&this.pipeTo.end()),4!=(e._duplexState&V)?1==(e._duplexState&J)&&(e._duplexState=(e._duplexState|W)&c,e._open(de.bind(this))):e._duplexState&Y||(e._duplexState|=W,e._destroy(oe.bind(this)))}continueUpdate(){return!!(this.stream._duplexState&b)&&(this.stream._duplexState&=C,!0)}updateCallback(){(32879&this.stream._duplexState)===u?this.update():this.updateNextTick()}updateNextTick(){this.stream._duplexState&b||(this.stream._duplexState|=b,32&this.stream._duplexState||o(this.afterUpdateNextTick))}}class se{constructor(e){this.data=null,this.afterTransform=ue.bind(e),this.afterFinal=null}}class ie{constructor(e,t,s){this.from=e,this.to=t,this.afterPipe=s,this.error=null,this.pipeToFinished=!1}finished(){this.pipeToFinished=!0}done(e,t){t&&(this.error=t),e!==this.to||(this.to=null,null===this.from)?e!==this.from||(this.from=null,null===this.to)?(null!==this.afterPipe&&this.afterPipe(this.error),this.to=this.from=this.afterPipe=null):e._duplexState&w||this.to.destroy(this.error||new Error("Readable stream closed before ending")):this.from._duplexState&w&&this.pipeToFinished||this.from.destroy(this.error||new Error("Writable stream closed prematurely"))}}function ne(){this.stream._duplexState|=512,this.updateCallback()}function re(e){const t=this.stream;e&&t.destroy(e),t._duplexState&V||(t._duplexState|=H,t.emit("finish")),(t._duplexState&K)===z&&(t._duplexState|=4),t._duplexState&=402391039,t._duplexState&I?this.updateNextTick():this.update()}function oe(e){const t=this.stream;e||this.error===n||(e=this.error),e&&t.emit("error",e),t._duplexState|=8,t.emit("close");const s=t._readableState,i=t._writableState;if(null!==s&&null!==s.pipeline&&s.pipeline.done(t,e),null!==i){for(;null!==i.drains&&i.drains.length>0;)i.drains.shift().resolve(!1);null!==i.pipeline&&i.pipeline.done(t,e)}}function ae(e){const t=this.stream;e&&t.destroy(e),t._duplexState&=469499903,null!==this.drains&&function(e){for(let t=0;t<e.length;t++)0==--e[t].writes&&(e.shift().resolve(!0),t--)}(this.drains),(6553615&t._duplexState)===R&&(t._duplexState&=532676607,(t._duplexState&N)===N&&t.emit("drain")),this.updateCallback()}function he(e){e&&this.stream.destroy(e),this.stream._duplexState&=x,!1!==this.readAhead||this.stream._duplexState&f||(this.stream._duplexState&=T),this.updateCallback()}function le(){32&this.stream._duplexState||(this.stream._duplexState&=C,this.update())}function ce(){this.stream._duplexState&I||(this.stream._duplexState&=D,this.update())}function de(e){const t=this.stream;e&&t.destroy(e),4&t._duplexState||(17423&t._duplexState||(t._duplexState|=u),142606351&t._duplexState||(t._duplexState|=L),t.emit("open")),t._duplexState&=$,null!==t._writableState&&t._writableState.updateCallback(),null!==t._readableState&&t._readableState.updateCallback()}function ue(e,t){null!=t&&this.push(t),this._writableState.afterWrite(e)}function pe(e){null!==this._readableState&&("data"===e&&(this._duplexState|=133376,this._readableState.updateNextTick()),"readable"===e&&(this._duplexState|=g,this._readableState.updateNextTick())),null!==this._writableState&&"drain"===e&&(this._duplexState|=N,this._writableState.updateNextTick())}class fe extends i{constructor(e){super(),this._duplexState=0,this._readableState=null,this._writableState=null,e&&(e.open&&(this._open=e.open),e.destroy&&(this._destroy=e.destroy),e.predestroy&&(this._predestroy=e.predestroy),e.signal&&e.signal.addEventListener("abort",Ce.bind(this))),this.on("newListener",pe)}_open(e){e(null)}_destroy(e){e(null)}_predestroy(){}get readable(){return null!==this._readableState||void 0}get writable(){return null!==this._writableState||void 0}get destroyed(){return!!(8&this._duplexState)}get destroying(){return!!(this._duplexState&V)}destroy(e){this._duplexState&V||(e||(e=n),this._duplexState=535822271&this._duplexState|4,null!==this._readableState&&(this._readableState.highWaterMark=0,this._readableState.error=e),null!==this._writableState&&(this._writableState.highWaterMark=0,this._writableState.error=e),this._duplexState|=2,this._predestroy(),this._duplexState&=d,null!==this._readableState&&this._readableState.updateNextTick(),null!==this._writableState&&this._writableState.updateNextTick())}}class me extends fe{constructor(e){super(e),this._duplexState|=8519681,this._readableState=new te(this,e),e&&(!1===this._readableState.readAhead&&(this._duplexState&=T),e.read&&(this._read=e.read),e.eagerOpen&&this._readableState.updateNextTick(),e.encoding&&this.setEncoding(e.encoding))}setEncoding(e){const t=new h(e),s=this._readableState.map||ve;return this._readableState.map=function(e){const i=t.push(e);return""===i&&(0!==e.byteLength||t.remaining>0)?null:s(i)},this}_read(e){e(null)}pipe(e,t){return this._readableState.updateNextTick(),this._readableState.pipe(e,t),e}read(){return this._readableState.updateNextTick(),this._readableState.read()}push(e){return this._readableState.updateNextTick(),this._readableState.push(e)}unshift(e){return this._readableState.updateNextTick(),this._readableState.unshift(e)}resume(){return this._duplexState|=k,this._readableState.updateNextTick(),this}pause(){return this._duplexState&=!1===this._readableState.readAhead?536739583:536870655,this}static _fromAsyncIterator(e,t){let s;const i=new me({...t,read(t){e.next().then(n).then(t.bind(null,null)).catch(t)},predestroy(){s=e.return()},destroy(e){if(!s)return e(null);s.then(e.bind(null,null)).catch(e)}});return i;function n(e){e.done?i.push(null):i.push(e.value)}}static from(e,t){if(xe(s=e)&&s.readable)return e;var s;if(e[Z])return this._fromAsyncIterator(e[Z](),t);Array.isArray(e)||(e=void 0===e?[]:[e]);let i=0;return new me({...t,read(t){this.push(i===e.length?null:e[i++]),t(null)}})}static isBackpressured(e){return!!(17422&e._duplexState)||e._readableState.buffered>=e._readableState.highWaterMark}static isPaused(e){return!(e._duplexState&f)}[Z](){const e=this;let t=null,s=null,i=null;return this.on("error",(e=>{t=e})),this.on("readable",(function(){null!==s&&r(e.read())})),this.on("close",(function(){null!==s&&r(null)})),{[Z](){return this},next:()=>new Promise((function(t,n){s=t,i=n;const o=e.read();null!==o?r(o):8&e._duplexState&&r(null)})),return:()=>o(null),throw:e=>o(e)};function r(r){null!==i&&(t?i(t):null!==r||e._duplexState&w?s({value:r,done:null===r}):i(n),i=s=null)}function o(t){return e.destroy(t),new Promise(((s,i)=>{if(8&e._duplexState)return s({value:void 0,done:!0});e.once("close",(function(){t?i(t):s({value:void 0,done:!0})}))}))}}}class _e extends fe{constructor(e){super(e),this._duplexState|=16385,this._writableState=new ee(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|=j}uncork(){this._duplexState&=q,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 s;const i=((s=e)._writev!==_e.prototype._writev&&s._writev!==ge.prototype._writev?Math.min(1,t.queue.length):t.queue.length)+(e._duplexState&U?1:0);return 0===i?Promise.resolve(!0):(null===t.drains&&(t.drains=[]),new Promise((e=>{t.drains.push({writes:i,resolve:e})})))}write(e){return this._writableState.updateNextTick(),this._writableState.push(e)}end(e){return this._writableState.updateNextTick(),this._writableState.end(e),this}}class ge extends me{constructor(e){super(e),this._duplexState=1|this._duplexState&v,this._writableState=new ee(this,e),e&&(e.writev&&(this._writev=e.writev),e.write&&(this._write=e.write),e.final&&(this._final=e.final))}cork(){this._duplexState|=j}uncork(){this._duplexState&=q,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 ye extends ge{constructor(e){super(e),this._transformState=new se(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(we.bind(this))}}function we(e,t){const s=this._transformState.afterFinal;if(e)return s(e);null!=t&&this.push(t),this.push(null),s(null)}function be(e,...t){const s=Array.isArray(e)?[...e,...t]:[e,...t],i=s.length&&"function"==typeof s[s.length-1]?s.pop():null;if(s.length<2)throw new Error("Pipeline requires at least 2 streams");let n=s[0],o=null,a=null;for(let e=1;e<s.length;e++)o=s[e],xe(n)?n.pipe(o,l):(h(n,!0,e>1,l),n.pipe(o)),n=o;if(i){let e=!1;const t=xe(o)||!(!o._writableState||!o._writableState.autoDestroy);o.on("error",(e=>{null===a&&(a=e)})),o.on("finish",(()=>{e=!0,t||i(a)})),t&&o.on("close",(()=>i(a||(e?null:r))))}return o;function h(e,t,s,i){e.on("error",i),e.on("close",(function(){if(t&&e._readableState&&!e._readableState.ended)return i(r);if(s&&e._writableState&&!e._writableState.ended)return i(r)}))}function l(e){if(e&&!a){a=e;for(const t of s)t.destroy(e)}}}function ve(e){return e}function ke(e){return!!e._readableState||!!e._writableState}function xe(e){return"number"==typeof e._duplexState&&ke(e)}function Se(e){return function(e){return"object"==typeof e&&null!==e&&"number"==typeof e.byteLength}(e)?e.byteLength:1024}function Ee(){}function Ce(){this.destroy(new Error("Stream aborted."))}e.exports={pipeline:be,pipelinePromise:function(...e){return new Promise(((t,s)=>be(...e,(e=>{if(e)return s(e);t()}))))},isStream:ke,isStreamx:xe,isEnded:function(e){return!!e._readableState&&e._readableState.ended},isFinished:function(e){return!!e._writableState&&e._writableState.ended},getStreamError:function(e,t={}){const s=e._readableState&&e._readableState.error||e._writableState&&e._writableState.error;return t.all||s!==n?s:null},Stream:fe,Writable:_e,Readable:me,Duplex:ge,Transform:ye,PassThrough:class extends ye{}}},5335:(e,t,s)=>{const i=s(3198),n=s(3198);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 n;break;case"utf16le":case"base64":throw new Error("Unsupported encoding: "+this.encoding);default:this.decoder=new i(this.encoding)}}get remaining(){return this.decoder.remaining}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}}},3198:e=>{e.exports=class{constructor(e){this.decoder=new TextDecoder("utf16le"===e?"utf16-le":e)}get remaining(){return-1}decode(e){return this.decoder.decode(e,{stream:!0})}flush(){return this.decoder.decode(new Uint8Array(0))}}},1035:e=>{function t(e){return(+Date.now()-e)/100&65535}e.exports=function(e){const s=+Date.now(),i=10*(e||5),n=[0];let r=1,o=t(s)-1&65535;return function(e){const a=t(s);let h=a-o&65535;for(h>i&&(h=i),o=a;h--;)r===i&&(r=0),n[r]=n[0===r?i-1:r-1],r++;e&&(n[r-1]+=e);const l=n[r-1],c=n.length<i?0:n[r===i?0:r];return n.length<10?l:10*(l-c)/n.length}}},1314:e=>{e.exports=function(e,t){if(t>=e.length||t<0)return;var s=e.pop();if(t<e.length){var i=e[t];return e[t]=s,i}return s}},6587:e=>{e.exports=function e(t,s){if(t&&s)return e(t)(s);if("function"!=typeof t)throw new TypeError("need wrapper function");return Object.keys(t).forEach((function(e){i[e]=t[e]})),i;function i(){for(var e=new Array(arguments.length),s=0;s<e.length;s++)e[s]=arguments[s];var i=t.apply(this,e),n=e[e.length-1];return"function"==typeof i&&i!==n&&Object.keys(n).forEach((function(e){i[e]=n[e]})),i}}},4343:()=>{},6686:()=>{},4043:()=>{},7828:()=>{},6889:()=>{},8878:()=>{},2701:()=>{},7264:()=>{},1551:()=>{},826:()=>{},61:()=>{},7936:()=>{},2532:()=>{},2123:()=>{},3208:()=>{},2376:()=>{},3970:()=>{},2799:()=>{},8271:()=>{},3278:()=>{},6664:()=>{},1827:()=>{},6819:(e,t,s)=>{e.exports=s(8330).version},5658:(e,t,s)=>{s.r(t),s.d(t,{default:()=>_,enableSecure:()=>m});var i=s(7007),n=s(8179),r=s(1314),o=s(7833),a=s(6458);const h="tcpIncoming",l="tcpOutgoing",c="utpIncoming",d="utpOutgoing",u="webSeed",p=o("webtorrent:peer");let f=!1;const m=()=>{f=!0};class _ extends i{constructor(e,t){super(),this.id=e,this.type=t,p("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,p("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,f);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?f&&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,n.pipeline)(this.conn,this.throttleGroups.down.throttle(),new n.Transform({transform(t,s){e.emit("download",t.length),e.destroyed||s(null,t)}}),this.wire,this.throttleGroups.up.throttle(),new n.Transform({transform(t,s){e.emit("upload",t.length),e.destroyed||s(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"));p("Peer %s got handshake %s",this.id,e),clearTimeout(this.handshakeTimeout),this.retries=0;let s=this.addr;!s&&this.conn.remoteAddress&&this.conn.remotePort&&(s=`${this.conn.remoteAddress}:${this.conn.remotePort}`),this.swarm._onWire(this.wire,s),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,p("destroy %s %s (error: %s)",this.type,this.id,e&&(e.message||e)),clearTimeout(this.connectTimeout),clearTimeout(this.handshakeTimeout);const t=this.swarm,s=this.conn,i=this.wire;this.swarm=null,this.conn=null,this.wire=null,t&&i&&r(t.wires,t.wires.indexOf(i)),s&&(s.on("error",(()=>{})),s.destroy()),i&&i.destroy(),t&&t.removePeer(this.id)}}_.TYPE_TCP_INCOMING=h,_.TYPE_TCP_OUTGOING=l,_.TYPE_UTP_INCOMING=c,_.TYPE_UTP_OUTGOING=d,_.TYPE_WEBRTC="webrtc",_.TYPE_WEBSEED=u,_.SOURCE_MANUAL="manual",_.SOURCE_TRACKER="tracker",_.SOURCE_DHT="dht",_.SOURCE_LSD="lsd",_.SOURCE_UT_PEX="ut_pex",_.createWebRTCPeer=(e,t,s)=>{const i=new _(e.id,"webrtc");if(i.conn=e,i.swarm=t,i.throttleGroups=s,i.conn.connected)i.onConnect();else{const e=()=>{i.conn.removeListener("connect",t),i.conn.removeListener("error",s)},t=()=>{e(),i.onConnect()},s=t=>{e(),i.destroy(t)};i.conn.once("connect",t),i.conn.once("error",s),i.startConnectTimeout()}return i},_.createTCPIncomingPeer=(e,t)=>_._createIncomingPeer(e,h,t),_.createUTPIncomingPeer=(e,t)=>_._createIncomingPeer(e,c,t),_.createTCPOutgoingPeer=(e,t,s)=>_._createOutgoingPeer(e,t,l,s),_.createUTPOutgoingPeer=(e,t,s)=>_._createOutgoingPeer(e,t,d,s),_._createIncomingPeer=(e,t,s)=>{const i=`${e.remoteAddress}:${e.remotePort}`,n=new _(i,t);return n.conn=e,n.addr=i,n.throttleGroups=s,n.onConnect(),n},_._createOutgoingPeer=(e,t,s,i)=>{const n=new _(e,s);return n.addr=e,n.swarm=t,n.throttleGroups=i,n},_.createWebSeedPeer=(e,t,s,i)=>{const n=new _(t,u);return n.swarm=s,n.conn=e,n.throttleGroups=i,n.onConnect(),n}},988:(e,t,s)=>{s.d(t,{A:()=>f});var i=s(9639);function n(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,s){const n=[];let r=null;return o._encode(n,e),r=(0,i.xW)(n),o.bytes=r.length,ArrayBuffer.isView(t)?(t.set(r,s),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]),l=new Uint8Array([108]);o.buffer=function(e,t){e.push((0,i.L0)(t.length+":"),t)},o.string=function(e,t){e.push((0,i.L0)((0,i.L0)(t).byteLength+":"+t))},o.number=function(e,t){if(Number.isInteger(t))return e.push((0,i.L0)("i"+BigInt(t)+"e"));const s=2147483648,n=(t/s|0)*s+(t%s|0);e.push((0,i.L0)("i"+n+"e")),n===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 "'+n+'"'),console.trace())},o.dict=function(e,t){e.push(h);let s,i=0;const n=Object.keys(t).sort(),r=n.length;for(;i<r;i++)s=n[i],null!=t[s]&&(o.string(e,s),o._encode(e,t[s]));e.push(a)},o.dictMap=function(e,t){e.push(h);const s=Array.from(t.keys()).sort();for(const i of s)null!=t.get(i)&&(ArrayBuffer.isView(i)?o._encode(e,i):o.string(e,String(i)),o._encode(e,t.get(i)));e.push(a)},o.list=function(e,t){let s=0;const i=t.length;for(e.push(l);s<i;s++)null!=t[s]&&o._encode(e,t[s]);e.push(a)},o.listSet=function(e,t){e.push(l);for(const s of t)null!=s&&o._encode(e,s);e.push(a)};const c=o;function d(e,t,s){let i=0,n=1;for(let r=t;r<s;r++){const s=e[r];if(s<58&&s>=48)i=10*i+(s-48);else if(r!==t||43!==s){if(r!==t||45!==s){if(46===s)break;throw new Error("not a number: buffer["+r+"] = "+s)}n=-1}}return i*n}function u(e,t,s,n){return null==e||0===e.length?null:("number"!=typeof t&&null==n&&(n=t,t=void 0),"number"!=typeof s&&null==n&&(n=s,s=void 0),u.position=0,u.encoding=n||null,u.data=ArrayBuffer.isView(e)?new Uint8Array(e.slice(t,s)):(0,i.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 s=u.data.length,i=u.data;for(;t<s;){if(i[t]===e)return t;t++}throw new Error('Invalid data: Missing delimiter "'+String.fromCharCode(e)+'" [0x'+e.toString(16)+"]")},u.dictionary=function(){u.position++;const e={};for(;101!==u.data[u.position];){const t=u.buffer();let s=(0,i.dU)(t);s.includes("<22>")&&(s=(0,i.V5)(t)),e[s]=u.next()}return u.position++,e},u.list=function(){u.position++;const e=[];for(;101!==u.data[u.position];)e.push(u.next());return u.position++,e},u.integer=function(){const e=u.find(101),t=d(u.data,u.position+1,e);return u.position+=e+1-u.position,t},u.buffer=function(){let e=u.find(58);const t=d(u.data,u.position,e),s=++e+t;return u.position=s,u.encoding?(0,i.dU)(u.data.slice(e,s)):u.data.slice(e,s)};function p(e){if(null==e)return 0;const t=r(e);switch(t){case"arraybufferview":return function(e){const t=e.byteLength-e.byteOffset;return n(t)+1+t}(e);case"string":return function(e){const t=(0,i.L0)(e).byteLength;return n(t)+1+t}(e);case"array":case"set":return function(e){let t=2;for(const s of e)t+=p(s);return t}(e);case"number":return 1+n(Math.floor(e))+1;case"bigint":return 1+e.toString().length+1;case"object":return function(e){let t=2;const s=Object.keys(e);for(let r=0;r<s.length;r++){const o=(0,i.L0)(s[r]).byteLength;t+=n(o)+1+o,t+=p(e[s[r]])}return t}(e);case"map":return function(e){let t=2;for(const[s,r]of e){const e=(0,i.L0)(s).byteLength;t+=n(e)+1+e,t+=p(r)}return t}(e);default:throw new TypeError(`Unsupported value of type "${t}"`)}}const f={encode:c,decode:u,byteLength:p,encodingLength:p}},3033:(e,t,s)=>{function i(e){return(e>>3)+Number(e%8!=0)}s.d(t,{A:()=>n});class n{get length(){return this.buffer.length<<3}constructor(e=0,t){const s=null==t?void 0:t.grow;this.grow=s?Number.isFinite(s)?i(s):s:0,this.buffer="number"==typeof e?new Uint8Array(i(e)):e}get(e){const t=e>>3;return t<this.buffer.length&&!!(this.buffer[t]&128>>e%8)}set(e,t=!0){const s=e>>3;if(t){if(s>=this.buffer.length){const e=Math.max(s+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[s]|=128>>e%8}else s<this.buffer.length&&(this.buffer[s]&=~(128>>e%8))}setAll(e,t=0){const s=Math.min(i(t+e.length),this.grow);if(this.buffer.length<s){const e=new Uint8Array(s);e.set(this.buffer),this.buffer=e}let n=t>>3,r=128>>t%8;for(let t=0;t<e.length;t++)if(e[t]?this.buffer[n]|=r:this.buffer[n]&=~r,1===r){if(n+=1,n>=this.buffer.length)break;r=128}else r>>=1}forEach(e,t=0,s=8*this.buffer.length){let i=t>>3,n=128>>t%8;for(let r=t;r<s;r++)e(!!(this.buffer[i]&n),r),1===n?(i+=1,n=128):n>>=1}isEmpty(){for(let e=0;e<this.buffer.length;e++)if(0!==this.buffer[e])return!1;return!0}}},6458:(e,t,s)=>{s.d(t,{A:()=>I});var i=s(988),n=s(3033),r=s(7264),o=s(7833),a=s(8727),h=s(8179),l=s(9639),c=s(1035),d=s(1314);const u=o("bittorrent-protocol"),p=(0,l.L0)("BitTorrent protocol"),f=new Uint8Array([0,0,0,0]),m=new Uint8Array([0,0,0,1,0]),_=new Uint8Array([0,0,0,1,1]),g=new Uint8Array([0,0,0,1,2]),y=new Uint8Array([0,0,0,1,3]),w=[0,0,0,0,0,0,0,0],b=[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 s=e.length;s--;)e[s]^=t[s];return e}class A{constructor(e,t,s,i){this.piece=e,this.offset=t,this.length=s,this.callback=i}}class T{constructor(){this.buffer=new Uint8Array}get(e){return!0}set(e){}}class P extends h.Duplex{constructor(e=null,t=0,s=!1){super(),this._debugId=(0,l.V5)((0,l.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 n.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=c(),this.downloadSpeed=c(),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=s,s?(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 s=this._nextExt,i=new e(this);function n(){}"function"!=typeof i.onHandshake&&(i.onHandshake=n),"function"!=typeof i.onExtendedHandshake&&(i.onExtendedHandshake=n),"function"!=typeof i.onMessage&&(i.onMessage=n),this.extendedMapping[s]=t,this._ext[t]=i,this[t]=i,this._nextExt+=1}keepAlive(){this._debug("keep-alive"),this._push(f)}sendPe1(){if(this._peEnabled){const e=Math.floor(513*Math.random()),t=(0,l.po)(e);this._push((0,l.xW)([(0,l.fk)(this._myPubKey),t]))}}sendPe2(){const e=Math.floor(513*Math.random()),t=(0,l.po)(e);this._push((0,l.xW)([(0,l.fk)(this._myPubKey),t]))}async sendPe3(e){await this.setEncrypt(this._sharedSecret,e);const t=await(0,l.tW)((0,l.fk)(this._utfToHex("req1")+this._sharedSecret)),s=C(await(0,l.tW)((0,l.fk)(this._utfToHex("req2")+e)),await(0,l.tW)((0,l.fk)(this._utfToHex("req3")+this._sharedSecret))),i=new DataView((0,l.po)(2).buffer).getUint16(0)%512,n=(0,l.po)(i);let r=new Uint8Array(14+i+2);r.set(x),r.set(S,8);const o=new DataView(r.buffer);o.setInt16(12,i),n.copy(r,14),o.setInt16(14+i,0),r=this._encryptHandshake(r),this._push((0,l.xW)([t,s,r]))}async sendPe4(e){await this.setEncrypt(this._sharedSecret,e);const t=new DataView((0,l.po)(2).buffer).getUint16(0)%512,s=(0,l.po)(t);let i=new Uint8Array(14+t);const n=new DataView(i.buffer);i.set(x),i.set(E,8),n.setInt16(12,t),i.set(s,14),i=this._encryptHandshake(i),this._push(i),this._cryptoHandshakeDone=!0,this._debug("completed crypto handshake")}handshake(e,t,s){let i,n;if("string"==typeof e?(e=e.toLowerCase(),i=(0,l.fk)(e)):(i=e,e=(0,l.V5)(i)),"string"==typeof t?n=(0,l.fk)(t):(n=t,t=(0,l.V5)(n)),this._infoHash=i,20!==i.length||20!==n.length)throw new Error("infoHash and peerId MUST have length 20");this._debug("handshake i=%s p=%s exts=%o",e,t,s);const r=new Uint8Array(w);this.extensions={extended:!0,dht:!(!s||!s.dht),fast:!(!s||!s.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,l.xW)([p,r,i,n])),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 s=this.extendedMapping[t];e.m[s]=Number(t)}this.extended(0,i.A.encode(e)),this._extendedHandshakeSent=!0}choke(){if(!this.amChoking)if(this.amChoking=!0,this._debug("choke"),this._push(m),this.hasFast){let e=0;for(;this.peerRequests.length>e;){const t=this.peerRequests[e];this.allowedFastSet.includes(t.piece)?++e:this.reject(t.piece,t.offset,t.length)}}else for(;this.peerRequests.length;)this.peerRequests.pop()}unchoke(){this.amChoking&&(this.amChoking=!1,this._debug("unchoke"),this._push(_))}interested(){this.amInterested||(this.amInterested=!0,this._debug("interested"),this._push(g))}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,s,i){return i||(i=()=>{}),this._finished?i(new Error("wire is closed")):!this.peerChoking||this.hasFast&&this.peerAllowedFastSet.includes(e)?(this._debug("request index=%d offset=%d length=%d",e,t,s),this.requests.push(new A(e,t,s,i)),this._timeout||this._resetTimeout(!0),void this._message(6,[e,t,s],null)):i(new Error("peer is choking"))}piece(e,t,s){this._debug("piece index=%d offset=%d",e,t),this._message(7,[e,t],s),this.uploaded+=s.length,this.uploadSpeed(s.length),this.emit("upload",s.length)}cancel(e,t,s){this._debug("cancel index=%d offset=%d length=%d",e,t,s),this._callback(this._pull(this.requests,e,t,s),new Error("request was cancelled"),null),this._message(8,[e,t,s],null)}port(e){this._debug("port %d",e);const t=new Uint8Array(b);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,s){if(!this.hasFast)throw Error("fast extension is disabled");this._debug("reject index=%d offset=%d length=%d",e,t,s),this._pull(this.peerRequests,e,t,s),this._message(16,[e,t,s],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 s=new Uint8Array([e]),n=ArrayBuffer.isView(t)?t:i.A.encode(t);this._message(20,[],(0,l.xW)([s,n]))}}async setEncrypt(e,t){let s,i,n,r;switch(this.type){case"tcpIncoming":s=await(0,l.tW)((0,l.fk)(this._utfToHex("keyB")+e+t)),n=await(0,l.tW)((0,l.fk)(this._utfToHex("keyA")+e+t)),i=[];for(const e of s.values())i.push(e);r=[];for(const e of n.values())r.push(e);this._encryptGenerator=new a(i),this._decryptGenerator=new a(r);break;case"tcpOutgoing":s=await(0,l.tW)((0,l.fk)(this._utfToHex("keyA")+e+t)),n=await(0,l.tW)((0,l.fk)(this._utfToHex("keyB")+e+t)),i=[];for(const e of s.values())i.push(e);r=[];for(const e of n.values())r.push(e);this._encryptGenerator=new a(i),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,s){const i=s?s.length:0,n=new Uint8Array(5+4*t.length),r=new DataView(n.buffer);r.setUint32(0,n.length+i-4),n[4]=e;for(let e=0;e<t.length;e++)r.setUint32(5+4*e,t[e]);this._push(n),s&&this._push(s)}_push(e){if(!this._finished)return 2===this._encryptionMethod&&this._cryptoHandshakeDone&&(e=this._encrypt(e)),this.push(e)}_onKeepAlive(){this._debug("got keep-alive"),this.emit("keep-alive")}_onPe1(e){this._peerPubKey=(0,l.V5)(e),this._sharedSecret=this._dh.computeSecret(this._peerPubKey,"hex","hex"),this.emit("pe1")}_onPe2(e){this._peerPubKey=(0,l.V5)(e),this._sharedSecret=this._dh.computeSecret(this._peerPubKey,"hex","hex"),this.emit("pe2")}async _onPe3(e){const t=await(0,l.V5)(this._utfToHex("req3")+this._sharedSecret),s=(0,l.V5)(C(t,e));this.emit("pe3",s)}_onPe3Encrypted(e,t){if(!(0,l.LC)(e,x))return this._debug("Error: verification constant did not match"),void this.destroy();for(const e of t.values())0!==e&&this._peerCryptoProvide.push(e);this._peerCryptoProvide.includes(2)?this._encryptionMethod=2:(this._debug("Error: RC4 encryption method not provided by peer"),this.destroy())}_onPe4(e){this._encryptionMethod=e[3],S.includes(this._encryptionMethod)||(this._debug("Error: peer selected invalid crypto method"),this.destroy()),this._cryptoHandshakeDone=!0,this._debug("crypto handshake done"),this.emit("pe4")}_onHandshake(e,t,s){const i=(0,l.V5)(e),n=(0,l.V5)(t);this._debug("got handshake i=%s p=%s exts=%o",i,n,s),this.peerId=n,this.peerIdBuffer=t,this.peerExtensions=s,this.extensions.fast&&this.peerExtensions.fast&&(this._debug("fast extension is enabled"),this.hasFast=!0),this.emit("handshake",i,n,s);for(const e in this._ext)this._ext[e].onHandshake(i,n,s);s.extended&&this._handshakeSent&&!this._extendedHandshakeSent&&this._sendExtendedHandshake()}_onChoke(){if(this.peerChoking=!0,this._debug("got choke"),this.emit("choke"),!this.hasFast)for(;this.requests.length;)this._callback(this.requests.pop(),new Error("peer is choking"),null)}_onUnchoke(){this.peerChoking=!1,this._debug("got unchoke"),this.emit("unchoke")}_onInterested(){this.peerInterested=!0,this._debug("got interested"),this.emit("interested")}_onUninterested(){this.peerInterested=!1,this._debug("got uninterested"),this.emit("uninterested")}_onHave(e){this.peerPieces.get(e)||(this._debug("got have %d",e),this.peerPieces.set(e,!0),this.emit("have",e))}_onBitField(e){this.peerPieces=new n.A(e),this._debug("got bitfield"),this.emit("bitfield",this.peerPieces)}_onRequest(e,t,s){if(this.amChoking&&(!this.hasFast||!this.allowedFastSet.includes(e)))return void(this.hasFast&&this.reject(e,t,s));this._debug("got request index=%d offset=%d length=%d",e,t,s);const i=(i,r)=>{if(n===this._pull(this.peerRequests,e,t,s))return i?(this._debug("error satisfying request index=%d offset=%d length=%d (%s)",e,t,s,i.message),void(this.hasFast&&this.reject(e,t,s))):void this.piece(e,t,r)},n=new A(e,t,s,i);this.peerRequests.push(n),this.emit("request",e,t,s,i)}_onPiece(e,t,s){this._debug("got piece index=%d offset=%d",e,t),this._callback(this._pull(this.requests,e,t,s.length),null,s),this.downloaded+=s.length,this.downloadSpeed(s.length),this.emit("download",s.length),this.emit("piece",e,t,s)}_onCancel(e,t,s){this._debug("got cancel index=%d offset=%d length=%d",e,t,s),this._pull(this.peerRequests,e,t,s),this.emit("cancel",e,t,s)}_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 T,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,s){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,s),this._callback(this._pull(this.requests,e,t,s),new Error("request was rejected"),null),this.emit("reject",e,t,s)}_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=i.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,l.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,s){e&&(this._resetTimeout(!this.peerChoking&&!this._finished),e.callback(t,s))}_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,l.xW)([e,t])),this._parsePe3()}))}_parsePe2(){this._parse(96,(e=>{for(this._onPe2(e);!this._setGenerators;);this._parsePe4()}))}async _parsePe3(){const e=await(0,l.tW)((0,l.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)),s=this._decryptHandshake(e.slice(8,12)),i=new DataView(this._decryptHandshake(e.slice(12,14)).buffer).getUint16(0);this._parse(i,(e=>{e=this._decryptHandshake(e),this._parse(2,(i=>{const n=new DataView(this._decryptHandshake(i).buffer).getUint16(0);this._parse(n,(i=>{i=this._decryptHandshake(i),this._onPe3Encrypted(t,s,e,i);const r=n?i[0]:null,o=n?i.slice(1,20):null;19===r&&"BitTorrent protocol"===(0,l.dU)(o)?this._onHandshakeBuffer(i.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)),s=new DataView(this._decryptHandshake(e.slice(4,6)).buffer).getUint16(0);this._parse(s,(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,l.dU)(t))return this._debug("Error: wire not speaking BitTorrent protocol (%s)",(0,l.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,s,i){for(let n=0;n<e.length;n++){const r=e[n];if(r.piece===t&&r.offset===s&&r.length===i)return d(e,n),r}return null}_encryptHandshake(e){const t=new Uint8Array(e);if(!this._encryptGenerator)return this._debug("Warning: Encrypting without any generator"),t;for(let s=0;s<e.length;s++){const e=this._encryptGenerator.randomByte();t[s]=t[s]^e}return t}_encrypt(e){const t=new Uint8Array(e);if(!this._encryptGenerator||2!==this._encryptionMethod)return t;for(let s=0;s<e.length;s++){const e=this._encryptGenerator.randomByte();t[s]=t[s]^e}return t}_decryptHandshake(e){const t=new Uint8Array(e);if(!this._decryptGenerator)return this._debug("Warning: Decrypting without any generator"),t;for(let s=0;s<e.length;s++){const e=this._decryptGenerator.randomByte();t[s]=t[s]^e}return t}_decrypt(e){const t=new Uint8Array(e);if(!this._decryptGenerator||2!==this._encryptionMethod)return t;for(let s=0;s<e.length;s++){const e=this._decryptGenerator.randomByte();t[s]=t[s]^e}return t}_utfToHex(e){return(0,l.V5)((0,l.L0)(e))}}const I=P},9639:(e,t,s)=>{s.d(t,{NJ:()=>g,V5:()=>o,dU:()=>f,HB:()=>y,xW:()=>h,LC:()=>l,tW:()=>S,fk:()=>a,Ht:()=>w,po:()=>E,L0:()=>_});const i="0123456789abcdef",n=[],r=[];for(let e=0;e<256;e++)n[e]=i[e>>4&15]+i[15&e],e<16&&(e<10?r[48+e]=e:r[87+e]=e);const o=e=>{const t=e.length;let s="",i=0;for(;i<t;)s+=n[e[i++]];return s},a=e=>{const t=e.length>>1,s=t<<1,i=new Uint8Array(t);let n=0,o=0;for(;o<s;)i[n++]=r[e.charCodeAt(o++)]<<4|r[e.charCodeAt(o++)];return i},h=(e,t=0)=>{const s=e.length||0;if(!t){let i=s;for(;i--;)t+=e[i].length}const i=new Uint8Array(t);let n=t,r=s;for(;r--;)n-=e[r].length,i.set(e[r],n);return i},l=(e,t)=>{if(e.length!==t.length)return!1;for(let s=e.length;s>-1;s-=1)if(e[s]!==t[s])return!1;return!0};for(var c="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",d="undefined"==typeof Uint8Array?[]:new Uint8Array(256),u=0;u<64;u++)d[c.charCodeAt(u)]=u;const p=new TextDecoder,f=(e,t)=>{if(!t)return p.decode(e);return new TextDecoder(t).decode(e)},m=new TextEncoder,_=e=>m.encode(e),g=e=>function(e){var t,s=new Uint8Array(e),i=s.length,n="";for(t=0;t<i;t+=3)n+=c[s[t]>>2],n+=c[(3&s[t])<<4|s[t+1]>>4],n+=c[(15&s[t+1])<<2|s[t+2]>>6],n+=c[63&s[t+2]];return i%3==2?n=n.substring(0,n.length-1)+"=":i%3==1&&(n=n.substring(0,n.length-2)+"=="),n}(e),y=e=>{let t,s="",n=0;const r=e.length;for(;n<r;)t=e.charCodeAt(n++),s+=i[t>>4]+i[15&t];return s},w=e=>{const t=a(e);if(t.length<=65536)return String.fromCharCode(...t);let s="",i=0;for(;i<t.length;)s+=String.fromCharCode(...t.subarray(i,i+=65536));return s},b="undefined"!=typeof window?window:self,v=b.crypto||b.msCrypto||{},k=v.subtle||v.webkitSubtle,x={hex:o,base64:g},S=async(e,t,s="sha-1")=>{if(!k)throw new Error("no web crypto support");"string"==typeof e&&(e=_(e));const i=new Uint8Array(await k.digest(s,e));return t?x[t](i):i},E=e=>{const t=new Uint8Array(e);return v.getRandomValues(t)}},717:(e,t,s)=>{s.r(t),s.d(t,{addListener:()=>u,argv:()=>a,binding:()=>S,browser:()=>r,chdir:()=>E,cwd:()=>k,emit:()=>g,env:()=>o,listeners:()=>v,nextTick:()=>b,off:()=>f,on:()=>d,once:()=>p,prependListener:()=>y,prependOnceListener:()=>w,removeAllListeners:()=>_,removeListener:()=>m,title:()=>n,umask:()=>x,version:()=>h,versions:()=>l});var i=s(9596);const n="browser",r=!0,o={},a=[],h="",l={};function c(){}const d=c,u=c,p=c,f=c,m=c,_=c,g=c,y=c,w=c,b=(e,...t)=>i((()=>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.5.11"}}},i={};function n(e){var t=i[e];if(void 0!==t)return t.exports;var r=i[e]={exports:{}};return s[e](r,r.exports,n),r.exports}t=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__,n.t=function(s,i){if(1&i&&(s=this(s)),8&i)return s;if("object"==typeof s&&s){if(4&i&&s.__esModule)return s;if(16&i&&"function"==typeof s.then)return s}var r=Object.create(null);n.r(r);var o={};e=e||[null,t({}),t([]),t(t)];for(var a=2&i&&s;"object"==typeof a&&!~e.indexOf(a);a=t(a))Object.getOwnPropertyNames(a).forEach((e=>o[e]=()=>s[e]));return o.default=()=>s,n.d(r,o),r},n.d=(e,t)=>{for(var s in t)n.o(t,s)&&!n.o(e,s)&&Object.defineProperty(e,s,{enumerable:!0,get:t[s]})},n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var r={};n.d(r,{A:()=>Xt});var o=n(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 s,i="",n=0,r=-1,o=0;for(let a=0;a<=e.length;++a){if(a<e.length)s=e.charCodeAt(a);else{if(47===s)break;s=47}if(47===s){if(r===a-1||1===o);else if(r!==a-1&&2===o){if(i.length<2||2!==n||46!==i.charCodeAt(i.length-1)||46!==i.charCodeAt(i.length-2))if(i.length>2){const e=i.lastIndexOf("/");if(e!==i.length-1){-1===e?(i="",n=0):(i=i.slice(0,e),n=i.length-1-i.lastIndexOf("/")),r=a,o=0;continue}}else if(2===i.length||1===i.length){i="",n=0,r=a,o=0;continue}t&&(i.length>0?i+="/..":i="..",n=2)}else i.length>0?i+="/"+e.slice(r+1,a):i=e.slice(r+1,a),n=a-r-1;r=a,o=0}else 46===s&&-1!==o?++o:o=-1}return i}function l(){if(0===arguments.length)return".";let e;for(let t=0;t<arguments.length;++t){const s=arguments[t];a(s),s.length>0&&(void 0===e?e=s:e+="/"+s)}return void 0===e?".":function(e){if(a(e),0===e.length)return".";const t=47===e.charCodeAt(0),s=47===e.charCodeAt(e.length-1);return 0!==(e=h(e,!t)).length||t||(e="."),e.length>0&&s&&(e+="/"),t?"/"+e:e}(e)}n(717);const c="/";var d=n(988),u=n(1467),p=n(8444),f=n(2123);const m=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 _(e){return m.test(e)}var g=n(405),y=n(8190),w=n(9596),b=n(9639),v=(n(3468),n(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,s){var i;if(i=e,"undefined"!=typeof FileList&&i 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 n=null;e.forEach(((t,s)=>{if("string"==typeof t)return;let i=t.fullPath||t.name;i||(i=`Unknown File ${s+1}`,t.unknownName=!0),t[x]=i.split("/"),t[x][0]||t[x].shift(),t[x].length<2?n=null:0===s&&e.length>1?n=t[x][0]:t[x][0]!==n&&(n=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]&&_(t)}(e[x])))),n&&e.forEach((e=>{const t=(ArrayBuffer.isView(e)||T(e))&&!e[x];"string"==typeof e||t||e[x].shift()})),!t.name&&n&&(t.name=n),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 s,i=0,n=-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(s=e.length-1;s>=0;--s){const h=e.charCodeAt(s);if(47===h){if(!r){i=s+1;break}}else-1===a&&(r=!1,a=s+1),o>=0&&(h===t.charCodeAt(o)?-1==--o&&(n=s):(o=-1,n=a))}return i===n?n=a:-1===n&&(n=e.length),e.slice(i,n)}for(s=e.length-1;s>=0;--s)if(47===e.charCodeAt(s)){if(!r){i=s+1;break}}else-1===n&&(r=!1,n=s+1);return-1===n?"":e.slice(i,n)}(e),!0):!e.unknownName&&(t.name=e[x][e[x].length-1],!0))),t.name||(t.name=`Unnamed Torrent ${Date.now()}`),t.maxPieceLength||(t.maxPieceLength=4194304);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");f(e[0],((e,t)=>{if(e)return s(e);o=t,h()}))}else w(h);function h(){y(e.map((e=>t=>{const s={};if(A(e))s.getStream=e.stream(),s.length=e.size;else if(ArrayBuffer.isView(e))s.getStream=[e],s.length=e.length;else{if(!T(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")}s.getStream=async function*(e,t){for await(const s of e)t.length+=s.length,yield s}(e,s),s.length=0}s.path=e[x],t(null,s)})),((e,t)=>{if(e)return s(e);t=t.flat(),s(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 T(e){return"object"==typeof e&&null!=e&&"function"==typeof e.pipe}const P=function(e,t,s){"function"==typeof t&&([t,s]=[s,t]),S(e,t=t?Object.assign({},t):{},((e,i,n)=>{if(e)return s(e);t.singleFileTorrent=n,function(e,t,s){let i=t.announceList;i||("string"==typeof t.announce?i=[[t.announce]]:Array.isArray(t.announce)&&(i=t.announce.map((e=>[e]))));i||(i=[]);globalThis.WEBTORRENT_ANNOUNCE&&("string"==typeof globalThis.WEBTORRENT_ANNOUNCE?i.push([[globalThis.WEBTORRENT_ANNOUNCE]]):Array.isArray(globalThis.WEBTORRENT_ANNOUNCE)&&(i=i.concat(globalThis.WEBTORRENT_ANNOUNCE.map((e=>[e])))));void 0===t.announce&&void 0===t.announceList&&(i=i.concat(k));"string"==typeof t.urlList&&(t.urlList=[t.urlList]);const n={info:{name:t.name},"creation date":Math.ceil((Number(t.creationDate)||Date.now())/1e3),encoding:"UTF-8"};0!==i.length&&(n.announce=i[0][0],n["announce-list"]=i);void 0!==t.comment&&(n.comment=t.comment);void 0!==t.createdBy&&(n["created by"]=t.createdBy);void 0!==t.private&&(n.info.private=Number(t.private));void 0!==t.info&&Object.assign(n.info,t.info);void 0!==t.sslCert&&(n.info["ssl-cert"]=t.sslCert);void 0!==t.urlList&&(n["url-list"]=t.urlList);const r=e.reduce(C,0),o=t.pieceLength||Math.min(p(r),t.maxPieceLength);n.info["piece length"]=o,async function(e,t,s,i,n){const r=[];let o=0,a=0;const h=e.map((e=>e.getStream)),l=i.onProgress;let c=0,d=0,p=!1;const f=u(g(h),t,{zeroPadding:!1});try{for await(const e of f)await new Promise((t=>{o+=e.length;const i=d;++d,++c<E&&t(),(0,b.tW)(e,"hex").then((h=>{r[i]=h,--c,a+=e.length,l&&l(a,s),t(),p&&0===c&&n(null,(0,b.fk)(r.join("")),o)}))}));if(0===c)return n(null,(0,b.fk)(r.join("")),o);p=!0}catch(e){n(e)}}(e,o,r,t,((i,r,o)=>{if(i)return s(i);n.info.pieces=r,e.forEach((e=>{delete e.getStream})),t.singleFileTorrent?n.info.length=o:n.info.files=e,s(null,d.A.encode(n))}))}(i,t,s)}))};var I=n(7833),L=n(6664),O=n(1827),R=n(3208);self.Blob,self.File,self.FormData,self.Headers,self.Request,self.Response,self.AbortController,self.AbortSignal;const H=self.fetch||(()=>{throw new Error("global fetch is not available!")}),N=[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 M=function(e){if(!ArrayBuffer.isView(e)&&"string"!=typeof e)throw new TypeError("base32.decode only takes Buffer or string as parameter");let t,s=0,i=0,n=0;ArrayBuffer.isView(e)||(e=(0,b.L0)(e));const r=new Uint8Array(Math.ceil(5*e.length/8));for(let o=0;o<e.length&&61!==e[o];o++){const a=e[o]-48;if(!(a<N.length))throw new Error("Invalid input - it is not base32 encoded string");i=N[a],s<=3?(s=(s+5)%8,0===s?(t|=i,r[n]=t,n++,t=0):t|=255&i<<8-s):(s=(s+5)%8,t|=255&i>>>s,r[n]=t,n++,t=255&i<<8-s)}return r.subarray(0,n)};function U(e){return e.reduce(((e,t,s,i)=>{const n=t.split("-").map((e=>parseInt(e)));return e.concat(((e,t=e)=>Array.from({length:t-e+1},((t,s)=>s+e)))(...n))}),[])}const F=function(e){const t={},s=e.split("magnet:?")[1];let i;if((s&&s.length>=0?s.split("&"):[]).forEach((e=>{const s=e.split("=");if(2!==s.length)return;const i=s[0];let n=s[1];"dn"===i&&(n=decodeURIComponent(n).replace(/\+/g," ")),"tr"!==i&&"xs"!==i&&"as"!==i&&"ws"!==i||(n=decodeURIComponent(n)),"kt"===i&&(n=decodeURIComponent(n).split("+")),"ix"===i&&(n=Number(n)),"so"===i&&(n=U(decodeURIComponent(n).split(","))),t[i]?(Array.isArray(t[i])||(t[i]=[t[i]]),t[i].push(n)):t[i]=n})),t.xt){(Array.isArray(t.xt)?t.xt:[t.xt]).forEach((e=>{(i=e.match(/^urn:btih:(.{40})/))?t.infoHash=i[1].toLowerCase():(i=e.match(/^urn:btih:(.{32})/))?t.infoHash=(0,b.V5)(M(i[1])):(i=e.match(/^urn:btmh:1220(.{64})/))&&(t.infoHashV2=i[1].toLowerCase())}))}if(t.xs){(Array.isArray(t.xs)?t.xs:[t.xs]).forEach((e=>{(i=e.match(/^urn:btpk:(.{64})/))&&(t.publicKey=i[1].toLowerCase())}))}return t.infoHash&&(t.infoHashBuffer=(0,b.fk)(t.infoHash)),t.infoHashV2&&(t.infoHashV2Buffer=(0,b.fk)(t.infoHashV2)),t.publicKey&&(t.publicKeyBuffer=(0,b.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 j(e){if("string"==typeof e&&/^(stream-)?magnet:/.test(e)){const t=F(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 F(`magnet:?xt=urn:btih:${e}`);if(ArrayBuffer.isView(e)&&20===e.length)return F(`magnet:?xt=urn:btih:${(0,b.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,b.dU)(e.info["name.utf-8"]||e.info.name),announce:[]};t.infoHashBuffer=await(0,b.tW)(t.infoBuffer),t.infoHash=(0,b.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,b.dU)(e["created by"]));ArrayBuffer.isView(e.comment)&&(t.comment=(0,b.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,b.dU)(e))}))})):e.announce&&t.announce.push((0,b.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,b.dU)(e))),t.announce=Array.from(new Set(t.announce)),t.urlList=Array.from(new Set(t.urlList));const s=e.info.files||[e.info];t.files=s.map(((e,i)=>{const n=[].concat(t.name,e["path.utf-8"]||e.path||[]).map((e=>ArrayBuffer.isView(e)?(0,b.dU)(e):e));return{path:l.apply(null,[c].concat(n)).slice(1),name:n[n.length-1],length:e.length,offset:s.slice(0,i).reduce(D,0)}})),t.length=s.reduce(D,0);const i=t.files[t.files.length-1];return t.pieceLength=e.info["piece length"],t.lastPieceLength=(i.offset+i.length)%t.pieceLength||t.pieceLength,t.pieces=function(e){const t=[];for(let s=0;s<e.length;s+=20)t.push((0,b.V5)(e.slice(s,s+20)));return t}(e.info.pieces),t}(e);if(e&&e.infoHash)return e.infoHash=e.infoHash.toLowerCase(),e.announce||(e.announce=[]),"string"==typeof e.announce&&(e.announce=[e.announce]),e.urlList||(e.urlList=[]),e;throw new Error("Invalid torrent identifier")}async function B(e,t,s){if("function"==typeof t)return B(e,{},t);if("function"!=typeof s)throw new Error("second argument must be a Function");let i;try{i=await j(e)}catch(e){}if(i&&i.infoHash)w((()=>{s(null,i)}));else if(n=e,"undefined"!=typeof Blob&&n instanceof Blob)try{r(new Uint8Array(await e.arrayBuffer()))}catch(e){return s(new Error(`Error converting Blob: ${e.message}`))}else if(/^https?:/.test(e))try{const s=await H(e,{headers:{"user-agent":"WebTorrent (https://webtorrent.io)"},signal:AbortSignal.timeout(3e4),...t});r(new Uint8Array(await s.arrayBuffer()))}catch(e){return s(new Error(`Error downloading torrent: ${e.message}`))}else"function"==typeof R.readFile&&"string"==typeof e?R.readFile(e,((e,t)=>{if(e)return s(new Error("Invalid torrent identifier"));r(t)})):w((()=>{s(new Error("Invalid torrent identifier"))}));var n;async function r(e){try{i=await j(e)}catch(e){return s(e)}i&&i.infoHash?s(null,i):s(new Error("Invalid torrent identifier"))}}function D(e,t){return e+t.length}function q(e,t){if(!e)throw new Error(`Torrent is missing required field: ${t}`)}const W=j,$=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,b.V5)(e.infoHashBuffer)}`),e.infoHash&&t.add(`urn:btih:${e.infoHash}`),e.infoHashV2Buffer&&t.add(e.xt=`urn:btmh:1220${(0,b.V5)(e.infoHashV2Buffer)}`),e.infoHashV2&&t.add(`urn:btmh:1220${e.infoHashV2}`);const s=Array.from(t);1===s.length&&(e.xt=s[0]),s.length>1&&(e.xt=s),e.publicKeyBuffer&&(e.xs=`urn:btpk:${(0,b.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 i="magnet:?";return Object.keys(e).filter((e=>2===e.length||"x.pe"===e)).forEach(((t,s)=>{const n=Array.isArray(e[t])?e[t]:[e[t]];var r;n.forEach(((e,n)=>{(s>0||n>0)&&("kt"!==t&&"so"!==t||0===n)&&(i+="&"),"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&&(i+="kt"===t&&n>0?`+${e}`:`${t}=${e}`)})),"so"===t&&(i+=`${t}=${r=n,r.reduce(((e,t,s,i)=>(0!==s&&t===i[s-1]+1||e.push([]),e[e.length-1].push(t),e)),[]).map((e=>e.length>1?`${e[0]}-${e[e.length-1]}`:`${e[0]}`))}`)})),i},z="undefined"!=typeof window?window:self,V=z.RTCPeerConnection||z.mozRTCPeerConnection||z.webkitRTCPeerConnection,G=z.RTCSessionDescription||z.mozRTCSessionDescription||z.webkitRTCSessionDescription,K=z.RTCIceCandidate||z.mozRTCIceCandidate||z.webkitRTCIceCandidate;z.RTCIceTransport,z.RTCDataChannel,z.RTCSctpTransport,z.RTCDtlsTransport,z.RTCCertificate,z.MediaStream,z.MediaStreamTrack,z.MediaStreamTrackEvent,z.RTCPeerConnectionIceEvent,z.RTCDataChannelEvent,z.RTCTrackEvent,z.RTCError,z.RTCErrorEvent,z.RTCRtpTransceiver,z.RTCRtpReceiver,z.RTCRtpSender;var Y=n(8179),J=n(6310);const X=I("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,b.V5)((0,b.po)(4)).slice(0,7),this._debug("new peer %o",e),this.channelName=e.initiator?e.channelName||(0,b.V5)((0,b.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,!V)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 V(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 s;!t.address||t.address.endsWith(".local")?(s="Ignoring unsupported ICE candidate.",console.warn(s)):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((s=>{const i=[];s.forEach((e=>{i.push(t(e))})),e(null,i)}),(t=>e(t))):this._pc.getStats.length>0?this._pc.getStats((s=>{if(this.destroyed)return;const i=[];s.result().forEach((e=>{const s={};e.names().forEach((t=>{s[t]=e.stat(t)})),s.id=e.id,s.type=e.type,s.timestamp=e.timestamp,i.push(t(s))})),e(null,i)}),(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,s)=>{if(this.destroyed||this._destroying)return;t&&(s=[]);const i={},n={},r={};let o=!1;s.forEach((e=>{"remotecandidate"!==e.type&&"remote-candidate"!==e.type||(i[e.id]=e),"localcandidate"!==e.type&&"local-candidate"!==e.type||(n[e.id]=e),"candidatepair"!==e.type&&"candidate-pair"!==e.type||(r[e.id]=e)}));const a=e=>{o=!0;let t=n[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 s=i[e.remoteCandidateId];s&&(s.ip||s.address)?(this.remoteAddress=s.ip||s.address,this.remotePort=Number(s.port)):s&&s.ipAddress?(this.remoteAddress=s.ipAddress,this.remotePort=Number(s.portNumber)):"string"==typeof e.googRemoteAddress&&(s=e.googRemoteAddress.split(":"),this.remoteAddress=s[0],this.remotePort=Number(s[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(s.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(n).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,b.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=!!V,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 se=n(1035),ie=n(7541),ne=n(3278),re=n(8271),oe=n(6686),ae=n(7828),he=n(6889);const le=/^\[?([^\]]+)]?:(\d+)$/;let ce=new Map;function de(e){if(1e5===ce.size&&ce.clear(),!ce.has(e)){const t=le.exec(e);if(!t)throw new Error(`invalid addr: ${e}`);ce.set(e,[t[1],Number(t[2])])}return ce.get(e)}var ue=n(3033),pe=n(4497);async function*fe(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 s=t.chunkLength||e.chunkLength;if(!s)throw new Error("missing required `chunkLength` property");let i=t.length||e.length;if(!Number.isFinite(i))throw new Error("missing required `length` property");const n=t.offset||0,r=(t,s,i)=>new Promise(((n,r)=>{e.get(t,{offset:i,length:s},((e,t)=>{e&&r(e),n(t)}))}));let o=Math.floor(n/s);const a=n%s;if(n){const e=Math.min(i,s-a);i-=e,yield r(o++,e,a)}for(let e=i;e>0;++o,e-=s)yield r(o,Math.min(e,s))}async function me(e,t,s={}){if(!e?.put)throw new Error("First argument must be an abstract-chunk-store compliant store");const i=s.chunkLength||e.chunkLength;if(!i)throw new Error("missing required `chunkLength` property");const n=s.storeMaxOutstandingPuts||16;let r=0,o=0,a=()=>{},h=!1;for await(const l of u(t,i,{zeroPadding:s.zeroPadding||!1}))await new Promise((t=>{r++<=n&&t(),e.put(o++,l,(e=>{if(e)throw e;--r,t(),h&&0===r&&a()}))}));0!==r&&(h=new Promise((e=>{a=e})),await h)}var _e=n(4018),ge=n(3970),ye=n(3519),we=n(1551);const be={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},...n.t(we,2)};var ve=n(826),ke=n(61),xe=n(2701);const Se=I("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,b.V5)((0,b.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 w((()=>this.destroy(e)))}}this._ws.binaryType="arraybuffer",e.socket&&this.connected?w((()=>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,b.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())}},Te=I("bittorrent-tracker:websocket-tracker"),Pe={};class Ie extends Ae{constructor(e,t){super(e,t),Te("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 s=Math.min(e.numwant,5);this._generateOffers(s,(e=>{t.numwant=s,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,b.Ht)(e))):e.infoHash&&(0,b.Ht)(e.infoHash)||this.client._infoHashBinary};this._send(t)}destroy(e=Le){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,Pe[this.announceUrl]&&(Pe[this.announceUrl].consumers-=1),Pe[this.announceUrl].consumers>0)return e();let t,s=Pe[this.announceUrl];if(delete Pe[this.announceUrl],s.on("error",Le),s.once("close",e),!this.expectingResponse)return i();function i(){t&&(clearTimeout(t),t=null),s.removeListener("data",i),s.destroy(),s=null}t=setTimeout(i,be.DESTROY_TIMEOUT),s.once("data",i)}_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=Pe[this.announceUrl],this.socket)Pe[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=Pe[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,b.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 Te("ignoring websocket data from %s for %s (looking for %s: reused socket)",this.announceUrl,(0,b.HB)(e.info_hash),this.client.infoHash);if(e.peer_id&&e.peer_id===this.client._peerIdBinary)return;Te("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 s=e["warning message"];s&&this.client.emit("warning",new Error(s));const i=e.interval||e["min interval"];i&&this.setInterval(1e3*i);const n=e["tracker id"];if(n&&(this._trackerId=n),null!=e.complete){const t=Object.assign({},e,{announce:this.announceUrl,infoHash:(0,b.HB)(e.info_hash)});this.client.emit("update",t)}let r;if(e.offer&&e.peer_id&&(Te("creating peer (from remote offer)"),r=this._createPeer(),r.id=(0,b.HB)(e.peer_id),r.once("signal",(t=>{const s={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&&(s.trackerid=this._trackerId),this._send(s)})),this.client.emit("peer",r),r.signal(e.offer)),e.answer&&e.peer_id){const t=(0,b.HB)(e.offer_id);r=this.peers[t],r?(r.id=(0,b.HB)(e.peer_id),this.client.emit("peer",r),r.signal(e.answer),clearTimeout(r.trackerTimeout),r.trackerTimeout=null,delete this.peers[t]):Te(`got unexpected answer: ${JSON.stringify(e.answer)}`)}}_onScrapeResponse(e){e=e.files||{};const t=Object.keys(e);0!==t.length?t.forEach((t=>{const s=Object.assign(e[t],{announce:this.announceUrl,infoHash:(0,b.HB)(t)});this.client.emit("scrape",s)})):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(),Te("reconnecting socket in %s ms",e)}_send(e){if(this.destroyed)return;this.expectingResponse=!0;const t=JSON.stringify(e);Te("send %s",t),this.socket.send(t)}_generateOffers(e,t){const s=this,i=[];Te("generating %s offers",e);for(let t=0;t<e;++t)n();function n(){const e=(0,b.V5)((0,b.po)(20));Te("creating peer (from _generateOffers)");const t=s.peers[e]=s._createPeer({initiator:!0});t.once("signal",(t=>{i.push({offer:t,offer_id:(0,b.Ht)(e)}),r()})),t.trackerTimeout=setTimeout((()=>{Te("tracker timeout: destroying peer"),t.trackerTimeout=null,delete s.peers[e],t.destroy()}),5e4),t.trackerTimeout.unref&&t.trackerTimeout.unref()}function r(){i.length===e&&(Te("generated %s offers",e),t(i))}r()}_createPeer(e){const t=this;e=Object.assign({trickle:!1,config:t.client._rtcConfig,wrtc:t.client._wrtc},e);const s=new te(e);return s.once("error",i),s.once("connect",(function e(){s.removeListener("error",i),s.removeListener("connect",e)})),s;function i(e){t.client.emit("warning",new Error(`Connection error: ${e.message}`)),s.destroy()}}}function Le(){}Ie.prototype.DEFAULT_ANNOUNCE_INTERVAL=3e4,Ie._socketPool=Pe;const Oe=Ie;var Re=n(717);const He=I("bittorrent-tracker:client");class Ne 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,b.V5)(e.peerId),this._peerIdBuffer=(0,b.fk)(this.peerId),this._peerIdBinary=(0,b.Ht)(this.peerId),this.infoHash="string"==typeof e.infoHash?e.infoHash.toLowerCase():(0,b.V5)(e.infoHash),this._infoHashBuffer=(0,b.fk)(this.infoHash),this._infoHashBinary=(0,b.Ht)(this.infoHash),He("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,b.dU)(e)),"/"===e[e.length-1]&&(e=e.substring(0,e.length-1)),e))),t=Array.from(new Set(t));const s=!1!==this._wrtc&&(!!this._wrtc||te.WEBRTC_SUPPORT),i=e=>{w((()=>{this.emit("warning",e)}))};this._trackers=t.map((e=>{let t;try{t=be.parseUrl(e)}catch(t){return i(new Error(`Invalid tracker URL: ${e}`)),null}const n=t.port;if(n<0||n>65535)return i(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||!s||"ws:"===r&&"undefined"!=typeof window&&"https:"===window.location.protocol?(i(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",He("send `start` %o",e),this._announce(e),this._trackers.forEach((e=>{e.setInterval()}))}stop(e){(e=this._defaultAnnounceOpts(e)).event="stopped",He("send `stop` %o",e),this._announce(e)}complete(e){e||(e={}),(e=this._defaultAnnounceOpts(e)).event="completed",He("send `complete` %o",e),this._announce(e)}update(e){(e=this._defaultAnnounceOpts(e)).event&&delete e.event,He("send `update` %o",e),this._announce(e)}_announce(e){this._trackers.forEach((t=>{t.announce(e)}))}scrape(e){He("send `scrape`"),e||(e={}),this._trackers.forEach((t=>{t.scrape(e)}))}setInterval(e){He("setInterval %d",e),this._trackers.forEach((t=>{t.setInterval(e)}))}destroy(e){if(this.destroyed)return;this.destroyed=!0,He("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=be.DEFAULT_ANNOUNCE_PEERS),null==e.uploaded&&(e.uploaded=0),null==e.downloaded&&(e.downloaded=0),this._getAnnounceOpts&&(e=Object.assign({},e,this._getAnnounceOpts())),e}}Ne.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 s=Object.assign({},e,{infoHash:Array.isArray(e.infoHash)?e.infoHash[0]:e.infoHash,peerId:(0,b.L0)("01234567890123456789"),port:6881}),i=new Ne(s);i.once("error",t),i.once("warning",t);let n=Array.isArray(e.infoHash)?e.infoHash.length:1;const r={};return i.on("scrape",(e=>{if(n-=1,r[e.infoHash]=e,0===n){i.destroy();const e=Object.keys(r);1===e.length?t(null,r[e[0]]):t(null,r)}})),i.scrape({infoHash:e.infoHash}),i};const Me=Ne;n(7936);var Ue=n(2799),Fe=n(717);const je=I("torrent-discovery");class Be 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(!Fe.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 s=new ge.Client(t);return s.on("warning",this._onWarning),s.on("error",this._onError),s.listen(e),this._internalDHT=!0,s};!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 ge.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 Ue?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 Me(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||(je("dht announce"),this._dhtAnnouncing=!0,clearTimeout(this._dhtTimeout),this.dht.announce(this.infoHash,this._port,(e=>{this._dhtAnnouncing=!1,je("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 Ue(e);return t.on("warning",this._onWarning),t.on("error",this._onError),t.on("peer",this._onLSDPeer),t.start(),t}}const De=Be;const qe=["seeking position failed.","InvalidStateError"],We=["A requested file or directory could not be found at the time an operation was processed.","NotFoundError"],$e=e=>[`Failed to execute 'write' on 'UnderlyingSinkBase': Invalid params passed. ${e}`,"SyntaxError"];class ze extends WritableStream{constructor(e){super(e),Object.setPrototypeOf(this,FileSystemWritableFileStream.prototype),this._closed=!1}async close(){this._closed=!0;const e=this.getWriter(),t=e.close();return e.releaseLock(),t}seek(e){return this.write({type:"seek",position:e})}truncate(e){return this.write({type:"truncate",size:e})}write(e){if(this._closed)return Promise.reject(new TypeError("Cannot write to a CLOSED writable stream"));const t=this.getWriter(),s=t.write(e);return t.releaseLock(),s}}if(Object.defineProperty(ze.prototype,Symbol.toStringTag,{value:"FileSystemWritableFileStream",writable:!1,enumerable:!1,configurable:!0}),Object.defineProperties(ze.prototype,{close:{enumerable:!0},seek:{enumerable:!0},truncate:{enumerable:!0},write:{enumerable:!0}}),!globalThis.FileSystemFileHandle||globalThis.FileSystemFileHandle.prototype.createWritable||globalThis.FileSystemWritableFileStream||(globalThis.FileSystemWritableFileStream=ze),globalThis.FileSystemFileHandle&&!globalThis.FileSystemFileHandle.prototype.createWritable){const e=new WeakMap;let t;const s=()=>{let e,t;onmessage=async s=>{const i=s.ports[0],n=s.data;switch(n.type){case"open":{const s=n.name;let i=await navigator.storage.getDirectory();for(const e of n.path)i=await i.getDirectoryHandle(e);e=await i.getFileHandle(s),t=await e.createSyncAccessHandle();break}case"write":t.write(n.data,{at:n.position}),t.flush();break;case"truncate":t.truncate(n.size);break;case"abort":case"close":t.close()}i.postMessage(0)}};globalThis.FileSystemFileHandle.prototype.createWritable=async function(i){if(!t){const e=`(${s.toString()})()`,i=new Blob([e],{type:"text/javascript"});t=URL.createObjectURL(i)}const n=new Worker(t,{type:"module"});let r=0;const o=new TextEncoder;let a=await this.getFile().then((e=>e.size));const h=e=>new Promise(((t,s)=>{const i=new MessageChannel;i.port1.onmessage=e=>{e.data instanceof Error?s(e.data):t(e.data),i.port1.close(),i.port2.close(),i.port1.onmessage=null},n.postMessage(e,[i.port2])})),l=await navigator.storage.getDirectory(),c=await e.get(this),d=await l.resolve(c);if(null===d)throw new DOMException(...We);return await h({type:"open",path:d,name:this.name}),!1===i?.keepExistingData&&(await h({type:"truncate",size:0}),a=0),new ze({async write(e){if("write"===(e=e?.constructor===Object?{...e}:{type:"write",data:e,position:r}).type){if(!("data"in e))throw await h({type:"close"}),new DOMException(...$e("write requires a data argument"));if(e.position??=r,"string"==typeof e.data)e.data=o.encode(e.data);else if(e.data instanceof ArrayBuffer)e.data=new Uint8Array(e.data);else if(e.data instanceof Uint8Array||!ArrayBuffer.isView(e.data)){if(!(e.data instanceof Uint8Array)){const t=await new Response(e.data).arrayBuffer();e.data=new Uint8Array(t)}}else e.data=new Uint8Array(e.data.buffer,e.data.byteOffset,e.data.byteLength);Number.isInteger(e.position)&&e.position>=0&&(r=e.position),r+=e.data.byteLength,a+=e.data.byteLength}else{if("seek"===e.type){if(Number.isInteger(e.position)&&e.position>=0){if(a<e.position)throw new DOMException(...qe);return void(r=e.position)}throw await h({type:"close"}),new DOMException(...$e("seek requires a position argument"))}if("truncate"===e.type){if(!(Number.isInteger(e.size)&&e.size>=0))throw await h({type:"close"}),new DOMException(...$e("truncate requires a size argument"));a=e.size,r>a&&(r=a)}}await h(e)},async close(){await h({type:"close"}),n.terminate()},async abort(e){await h({type:"abort",reason:e}),n.terminate()}})};const i=FileSystemDirectoryHandle.prototype.getFileHandle;FileSystemDirectoryHandle.prototype.getFileHandle=async function(...t){const s=await i.call(this,...t);return e.set(s,this),s}}const Ve=/[<>:"/\\|?*\u0000-\u001F]/g;globalThis.navigator?.storage?.getDirectory&&navigator.storage.getDirectory().then((e=>{e.removeEntry("chunks",{recursive:!0}).catch((()=>{}))}));const Ge=(e,t)=>{};class Ke{name="";chunks=[];chunkMap=[];directoryMap={};files;rootDirPromise;storageDirPromise;chunksDirPromise;closing=!1;closed=!1;constructor(e,t={}){if(this.chunkLength=Number(e),!this.chunkLength)throw new Error("First argument must be a chunk length");if(!globalThis.navigator?.storage?.getDirectory)throw new Error("FSA API is not supported");if(this.closed=!1,this.name=t.name||crypto.randomUUID(),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.chunksDirPromise=this._getChunksDirHandle(),this.files=t.files.map(((e,t,s)=>{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 i=s[t-1];e.offset=i.offset+i.length}null==e.handle&&(e.handle=this._createFileHandle({path:e.path})),e.blob=this._createBlobReference(e.handle);const i=e.offset,n=e.offset+e.length,r=Math.floor(i/this.chunkLength),o=Math.floor((n-1)/this.chunkLength);for(let t=r;t<=o;++t){const s=t*this.chunkLength,r=i<s?0:i-s,o=n>s+this.chunkLength?this.chunkLength:n-s,a=i>s?0:s-i;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 s=await this.chunksDirPromise;this.chunks[e]=t=await s.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(Ve,""),{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 s=e.path=e.path.slice(0,t);return this.directoryMap[s]||(this.directoryMap[s]=(async()=>(await this._getDirectoryHandle(e)).getDirectoryHandle(s.slice(s.lastIndexOf("/")+1),{create:!0}))()),this.directoryMap[s]}async _getChunksDirHandle(){const e=await navigator.storage.getDirectory();return(await e.getDirectoryHandle("chunks",{create:!0})).getDirectoryHandle(this.name,{create:!0})}async put(e,t,s=Ge){try{return await this._put(e,t),s(null),null}catch(e){return queueMicrotask((()=>s(e))),e}}async getStreamForHandle(e){return(await e).createWritable({keepExistingData:!0})}async _put(e,t){if(this.closed)throw new Error("Storage is closed");const s=e===this.lastChunkIndex;if(s&&t.length!==this.lastChunkLength)throw new Error(`Last chunk length must be ${this.lastChunkLength}`);if(!s&&t.length!==this.chunkLength)throw new Error(`Chunk length must be ${this.chunkLength}`);const i=(async()=>{const s=await this._getChunkHandle(e),i=await s.createWritable({keepExistingData:!1});await i.write(t),await i.close()})();if(!this.files)return i;const n=this.chunkMap[e];if(!n)throw new Error("No files matching the request range");const r=n.map((async({file:e,offset:s,from:i,to:n})=>{e.stream||(e.stream=this.getStreamForHandle(e.handle)),await(await e.stream).write({type:"write",position:s,data:t.slice(i,n)})}));r.push(i),await Promise.all(r)}async get(e,t,s=Ge){null==t&&(t={});try{const i=await this._get(e,t);return s(null,i),i}catch(e){return s(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 s=e===this.lastChunkIndex?this.lastChunkLength:this.chunkLength,i=t.offset||0,n=t.length?i+t.length:s,r=t.length||s-i;if(i<0||i<0||n>s)throw new Error("Invalid offset and/or length");if(i===n)return new Uint8Array(0);if(!this.files||this.chunks[e]){const t=await this._getChunkHandle(e);let n=await t.getFile();0===i&&r===s||(n=n.slice(i,r+i));const o=await n.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>i&&e<n)),0===o.length))throw new Error("No files matching the request range");const a=o.map((async({from:e,to:s,offset:r,file:o})=>{t&&(s>n&&(s=n),e<i&&(r+=i-e,e=i));return(await o.blob).slice(r,r+s-e)})),h=await Promise.all(a),l=1===h.length?await h[0].arrayBuffer():await new Blob(h).arrayBuffer();if(0===l.byteLength)throw new Error(`Index ${e} does not exist`);return new Uint8Array(l)}async close(e=Ge){if(this.closing)return((e=Ge,t)=>queueMicrotask((()=>e(new Error(t)))))(e,"Storage is closed");this.closing=!0,this.chunkMap=void 0,this.directoryMap=void 0,this.files&&await this.cleanup(),this.closed=!0,queueMicrotask((()=>e(null)))}async cleanup(){if(this.closed||!this.files)return;const e=[];for(const t of this.files)t.stream&&(e.push(t.stream.then((e=>e.close()))),t.stream=void 0);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=this._getChunksDirHandle(),await this.chunksDirPromise})();await Promise.all(e);for(const e of this.files)e.blob=this._createBlobReference(e.handle);await t}async destroy(e=Ge){this.close((async t=>{if(t)return e(t);try{const e=await this.rootDirPromise;await e.removeEntry(this.name,{recursive:!0})}catch(t){return e(t)}e(null)}))}}var Ye=n(3714),Je=n(1314);const Xe=I("lt_donthave"),Qe=()=>{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)&&(Xe("got donthave %d",t),this._wire.peerPieces.set(t,!1),this.emit("donthave",t),this._failRequests(t))}donthave(e){if(!this._peerSupports)return;Xe("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 s=0;s<t.length;s++){const i=t[s];i.piece===e&&(Je(t,s),s-=1,this._wire._callback(i,new Error("peer sent donthave"),null))}}}return e.prototype.name="lt_donthave",e};var Ze=n(4862),et=n(5372);const tt=16384;class st{constructor(e){this.length=e,this.missing=e,this.sources=null,this._chunks=Math.ceil(e/tt),this._remainder=e%tt||tt,this._buffered=0,this._buffer=null,this._cancellations=null,this._reservations=0,this._flushed=!1}chunkLength(e){return e===this._chunks-1?this._remainder:tt}chunkLengthRemaining(e){return this.length-e*tt}chunkOffset(e){return e*tt}reserve(){return this.init()?this._cancellations.length?this._cancellations.pop():this._reservations<this._chunks?this._reservations++:-1:-1}reserveRemaining(){if(!this.init())return-1;if(this._cancellations.length||this._reservations<this._chunks){let e=this._reservations;for(;this._cancellations.length;)e=Math.min(e,this._cancellations.pop());return this._reservations=this._chunks,e}return-1}cancel(e){this.init()&&this._cancellations.push(e)}cancelRemaining(e){this.init()&&(this._reservations=e)}get(e){return this.init()?this._buffer[e]:null}set(e,t,s){if(!this.init())return!1;const i=t.length,n=Math.ceil(i/tt);for(let i=0;i<n;i++)if(!this._buffer[e+i]){const n=i*tt,r=t.slice(n,n+tt);this._buffered++,this._buffer[e+i]=r,this.missing-=r.length,this.sources.includes(s)||this.sources.push(s)}return this._buffered===this._chunks}flush(){if(!this._buffer||this._chunks!==this._buffered)return null;const e=(0,b.xW)(this._buffer,this.length);return this._buffer=null,this._cancellations=null,this.sources=null,this._flushed=!0,e}init(){return!this._flushed&&(this._buffer||(this._buffer=new Array(this._chunks),this._cancellations=[],this.sources=[]),!0)}}st.BLOCK_LENGTH=tt;var it=n(7373);const nt=I("ut_metadata"),rt=16384,ot=e=>{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,s){this._infoHash=e}onExtendedHandshake(e){return e.m&&e.m.ut_metadata?e.metadata_size?"number"!=typeof e.metadata_size||1e7<e.metadata_size||e.metadata_size<=0?this.emit("warning",new Error("Peer gave invalid metadata size")):(this._metadataSize=e.metadata_size,this._numPieces=Math.ceil(this._metadataSize/rt),this._remainingRejects=2*this._numPieces,void this._requestPieces()):this.emit("warning",new Error("Peer does not have metadata")):this.emit("warning",new Error("Peer does not support ut_metadata"))}onMessage(e){let t,s;try{const i=(0,b.dU)(e),n=i.indexOf("ee")+2;t=d.A.decode(i.substring(0,n)),s=e.slice(n)}catch(e){return}switch(t.msg_type){case 0:this._onRequest(t.piece);break;case 1:this._onData(t.piece,s,t.total_size);break;case 2:this._onReject(t.piece)}}fetch(){this._metadataComplete||(this._fetching=!0,this._metadataSize&&this._requestPieces())}cancel(){this._fetching=!1}async setMetadata(e){if(this._metadataComplete)return!0;nt("set metadata");try{const t=d.A.decode(e).info;t&&(e=d.A.encode(t))}catch(e){}return(!this._infoHash||this._infoHash===await(0,b.tW)(e,"hex"))&&(this.cancel(),this.metadata=e,this._metadataComplete=!0,this._metadataSize=this.metadata.length,this._wire.extendedHandshake.metadata_size=this._metadataSize,this.emit("metadata",d.A.encode({info:d.A.decode(this.metadata)})),!0)}_send(e,t){let s=d.A.encode(e);ArrayBuffer.isView(t)&&(s=(0,b.xW)([s,t])),this._wire.extended("ut_metadata",s)}_request(e){this._send({msg_type:0,piece:e})}_data(e,t,s){const i={msg_type:1,piece:e};"number"==typeof s&&(i.total_size=s),this._send(i,t)}_reject(e){this._send({msg_type:2,piece:e})}_onRequest(e){if(!this._metadataComplete)return void this._reject(e);const t=e*rt;let s=t+rt;s>this._metadataSize&&(s=this._metadataSize);const i=this.metadata.slice(t,s);this._data(e,i,this._metadataSize)}_onData(e,t,s){t.length>rt||!this._fetching||(this.metadata.set(t,e*rt),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;e<this._numPieces;e++)this._request(e)}}async _checkDone(){let e=!0;for(let t=0;t<this._numPieces;t++)if(!this._bitfield.get(t)){e=!1;break}if(!e)return;await this.setMetadata(this.metadata)||this._failedMetadata()}_failedMetadata(){this._bitfield=new ue.A(0,{grow:1e3}),this._remainingRejects-=this._numPieces,this._remainingRejects>0?this._requestPieces():this.emit("warning",new Error("Peer sent invalid metadata"))}}return t.prototype.name="ut_metadata",t};var at=n(8878),ht=n(1133);const lt=I("webtorrent:file-iterator");class ct extends o{constructor(e,{start:t,end:s}){super(),this._torrent=e._torrent,this._pieceLength=e._torrent.pieceLength,this._startPiece=(t+e.offset)/this._pieceLength|0,this._endPiece=(s+e.offset)/this._pieceLength|0,this._piece=this._startPiece,this._offset=t+e.offset-this._startPiece*this._pieceLength,this._missing=s-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 s=(i,n)=>{if(!this._torrent.bitfield.get(i)){const e=t=>{(t===i||this.destroyed)&&(this._torrent.removeListener("verified",e),s(i,n))};return this._torrent.on("verified",e),this._torrent.critical(i,i+this._criticalLength)}if(this._torrent.destroyed)return t(new Error("Torrent removed"));this._torrent.store.get(i,n,((s,n)=>this.destroyed?e({done:!0}):(lt("read %s and yielding (length %s) (err %s)",i,n?.length,s?.message),s?t(s):void e({value:n,done:!1}))))},i=Math.min(this._missing,this._pieceLength-this._offset);s(this._piece++,{length:i,offset:this._offset}),this._missing-=i,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 dt 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=ht.getType(this.name)||"application/octet-stream",this.offset=t.offset,this.done=!1;const s=t.offset,i=s+t.length-1;this._startPiece=s/this._torrent.pieceLength|0,this._endPiece=i/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:s,lastPieceLength:i}=this._torrent,{_startPiece:n,_endPiece:r}=this,o=n=>{const r=n===e.length-1?i:s;return t.get(n)?r:r-e[n].missing};let a=0;for(let t=n;t<=r;t+=1){const h=o(t);if(a+=h,t===n){const e=this.offset%s;a-=Math.min(e,h)}if(t===r){const t=(r===e.length-1?i:s)-(this.offset+this.length)%s;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??{},s=e?.end&&e.end<this.length?e.end:this.length-1;if(this.done)return fe(this._torrent.store,{offset:t+this.offset,length:s-t+1});const i=new ct(this,{start:t,end:s});return this._iterators.add(i),i.once("return",(()=>{this._iterators.delete(i)})),i}createReadStream(e){const t=this[Symbol.asyncIterator](e),s=Y.Readable.from(t);return this._fileStreams.add(s),s.once("close",(()=>{this._fileStreams.delete(s)})),s}async arrayBuffer(e={}){const{start:t=0}=e,s=e?.end&&e.end<this.length?e.end:this.length-1,i=new Uint8Array(s-t+1);let n=0;for await(const e of this[Symbol.asyncIterator]({start:t,end:s}))i.set(e,n),n+=e.length;return i.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:s,done:i}=await t.next();i?e.close():e.enqueue(s)},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 ut=n(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=[],s=1/0;for(let i=0;i<this._numPieces;++i){if(e&&!e(i))continue;const n=this._pieces[i];n===s?t.push(i):n<s&&(t=[i],s=n)}return t.length?t[Math.random()*t.length|0]:-1}destroy(){this._torrent.removeListener("wire",this._onWire),this._torrent.wires.forEach((e=>{this._cleanupWireEvents(e)})),this._torrent=null,this._pieces=null,this._onWire=null,this._onWireHave=null,this._onWireBitfield=null}_initWire(e){e._onClose=()=>{this._cleanupWireEvents(e);for(let t=0;t<this._numPieces;++t)this._pieces[t]-=e.peerPieces.get(t)},e.on("have",this._onWireHave),e.on("bitfield",this._onWireBitfield),e.once("close",e._onClose)}recalculate(){this._pieces.fill(0);for(const e of this._torrent.wires)for(let t=0;t<this._numPieces;++t)this._pieces[t]+=e.peerPieces.get(t)}_cleanupWireEvents(e){e.removeListener("have",this._onWireHave),e.removeListener("bitfield",this._onWireBitfield),e._onClose&&e.removeListener("close",e._onClose),e._onClose=null}}var ft=n(4343),mt=n(6458),_t=n(6819);const gt=I("webtorrent:webconn");class yt extends mt.A{constructor(e,t){super(),this.url=e,this.connId=e,this._torrent=t,this._init(e)}_init(e){this.setKeepAlive(!0),this.use(Qe()),this.once("handshake",(async(t,s)=>{const i=await(0,b.tW)(e,"hex");if(this.destroyed)return;this.handshake(t,i);const n=this._torrent.pieces.length,r=new ue.A(n);for(let e=0;e<=n;e++)r.set(e,!0);this.bitfield(r)})),this.once("interested",(()=>{gt("interested"),this.unchoke()})),this.on("uninterested",(()=>{gt("uninterested")})),this.on("choke",(()=>{gt("choke")})),this.on("unchoke",(()=>{gt("unchoke")})),this.on("bitfield",(()=>{gt("bitfield")})),this.lt_donthave.on("donthave",(()=>{gt("donthave")})),this.on("request",((e,t,s,i)=>{gt("request pieceIndex=%d offset=%d length=%d",e,t,s),this.httpRequest(e,t,s,((t,s)=>{if(t){this.lt_donthave.donthave(e);const t=setTimeout((()=>{this.destroyed||this.have(e)}),1e4);t.unref&&t.unref()}i(t,s)}))}))}async httpRequest(e,t,s,i){i=ye(i);const n=e*this._torrent.pieceLength+t,r=n+s-1,o=this._torrent.files;let a,h;if(o.length<=1)a=[{url:this.url,start:n,end:r}];else{const e=o.filter((e=>e.offset<=r&&e.offset+e.length>n));if(e.length<1)return i(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-n,0),start:Math.max(n-e.offset,0),end:Math.min(t,r-e.offset)}}))}try{h=await Promise.all(a.map((async({start:i,end:n,url:r})=>{gt("Requesting url=%s pieceIndex=%d offset=%d length=%d start=%d end=%d",r,e,t,s,i,n);const o=await H(r,{cache:"no-store",method:"GET",headers:{"Cache-Control":"no-store","user-agent":`WebTorrent/${_t} (https://webtorrent.io)`,range:`bytes=${i}-${n}`},signal:AbortSignal.timeout(6e4)});if(!o.ok)throw new Error(`Unexpected HTTP status code ${o.status}`);const a=new Uint8Array(await o.arrayBuffer());return gt("Got data of length %d",a.length),a})))}catch(e){return i(e)}i(null,(0,b.xW)(h))}destroy(){super.destroy(),this._torrent=null}}class wt{_items=[];remove(e){for(let t=0;t<this._items.length;t++){const s=this._items[t];if(s.isStreamSelection){if(!e.isStreamSelection)continue;if(s.from===e.from&&s.to===e.to){this._items.splice(t,1);break}}else if(bt(e,s))s.to=Math.max(e.from-1,0);else if(vt(e,s))s.from=e.to+1;else if(kt(e,s)){const i=[],n={...s,to:Math.max(e.from-1,0)};n.to-n.from>=0&&0!==e.from&&i.push(n);const r={...s,from:e.to+1};r.to-r.from>=0&&i.push(r),this._items.splice(t,1,...i),t=t-1+i.length}else xt(e,s)&&(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,s=[];for(const t of this._items)t.notify&&St(e,t)&&s.push(t.notify);s.length>0&&(e.notify=()=>{s.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 s=this._items[e];this._items[e]=this._items[t],this._items[t]=s}clear(){this._items.length=0}*[Symbol.iterator](){for(let e=0;e<this._items.length;e++){const t=this._items[e];t.remove=()=>{this._items.splice(e,1),e--},yield t,delete t.remove}}}function bt(e,t){return e.from<=t.to&&e.from>t.from&&e.to>t.to}function vt(e,t){return e.to>=t.from&&e.to<t.to&&e.from<t.from}function kt(e,t){const s=t.to-t.from,i=e.to-e.from;return e.from>=t.from&&e.to<=t.to&&i<s}function xt(e,t){return e.from<=t.from&&e.to>=t.to}const St=(e,t)=>()=>bt(e,t)||vt(e,t)||kt(e,t)||xt(e,t);var Et=n(717);const Ct=I("webtorrent:torrent"),At=5e3,Tt=3*st.BLOCK_LENGTH,Pt=Et.browser?_e().length:2,It=[1e3,5e3,15e3],Lt=`WebTorrent/${_t} (https://webtorrent.io)`,Ot=globalThis.navigator?.storage?.getDirectory&&globalThis.FileSystemFileHandle?.prototype?.createWritable,Rt=!Et.browser||Ot?Ke:Ze;let Ht;try{Ht=l(oe.statSync("/tmp")&&"/tmp","webtorrent")}catch(e){Ht=l("function"==typeof he.tmpdir?he.tmpdir():"/","webtorrent")}const Nt="undefined"!=typeof window&&"function"==typeof window.requestIdleCallback&&window.requestIdleCallback;class Mt extends o{constructor(e,t,s){super(),this._debugId="unknown infohash",this.client=t,this.announce=s.announce,this.urlList=s.urlList,this.path=s.path||Ht,this.addUID=s.addUID||!1,this.rootDir=s.rootDir||null,this.skipVerify=!!s.skipVerify,this._store=s.store||Rt,this._preloadedStore=s.preloadedStore||null,this._storeCacheSlots=void 0!==s.storeCacheSlots?s.storeCacheSlots:20,this._destroyStoreOnDestroy=s.destroyStoreOnDestroy||!1,this.store=null,this.storeOpts=s.storeOpts,this.alwaysChokeSeeders=s.alwaysChokeSeeders??!0,this._getAnnounceOpts=s.getAnnounceOpts,"boolean"==typeof s.private&&(this.private=s.private),this.strategy=s.strategy||"sequential",this.maxWebConns=s.maxWebConns||4,this._rechokeNumSlots=!1===s.uploads||0===s.uploads?0:+s.uploads||10,this._rechokeOptimisticWire=null,this._rechokeOptimisticTime=0,this._rechokeIntervalId=null,this._noPeersIntervalId=null,this._noPeersIntervalTime=s.noPeersIntervalTime?1e3*s.noPeersIntervalTime:3e4,this._startAsDeselected=s.deselect||!1,this.ready=!1,this.destroyed=!1,this.paused=s.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=se(),this._uploadSpeed=se(),this._servers=[],this._xsRequests=[],this._fileModtimes=s.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,s=this.pieces.length;t<s;++t)if(this.bitfield.get(t))e+=t===s-1?this.lastPieceLength:this.pieceLength;else{const s=this.pieces[t];e+=s.length-s.missing}return e}get downloadSpeed(){return this._downloadSpeed()}get uploadSpeed(){return this._uploadSpeed()}get progress(){return this.length?this.downloaded/this.length:0}get ratio(){return this.uploaded/(this.received||this.length)}get numPeers(){return this.wires.length}get torrentFileBlob(){return this.torrentFile?new Blob([this.torrentFile],{type:"application/x-bittorrent"}):null}get _numQueued(){return this._queue.length+(this._peersLength-this._numConns)}get _numConns(){let e=0;for(const t in this._peers)this._peers[t].connected&&(e+=1);return e}async _onTorrentId(e){if(this.destroyed)return;let t;try{t=await W(e)}catch(e){}t?(this.infoHash=t.infoHash,this._debugId=(0,b.V5)(t.infoHash).substring(0,7),w((()=>{this.destroyed||this._onParsedTorrent(t)}))):B(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,b.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,b.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,ut.default.SOURCE_MANUAL))),this.discovery=new De({infoHash:this.infoHash,announce:this.announce,peerId:this.client.peerId,dht:!this.private&&this.client.dht,tracker:e,port:this.client.torrentPort,userAgent:Lt,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={[ut.default.SOURCE_TRACKER]:{enabled:!!this.client.tracker,numPeers:0},[ut.default.SOURCE_DHT]:{enabled:!!this.client.dht,numPeers:0},[ut.default.SOURCE_LSD]:{enabled:!!this.client.lsd,numPeers:0},[ut.default.SOURCE_UT_PEX]:{enabled:this.client.utPex&&"function"==typeof at,numPeers:0}};for(const t of Object.values(this._peers)){const s=e[t.source];void 0!==s&&s.numPeers++}for(const t of Object.keys(e)){const s=e[t];s.enabled&&0===s.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 s=e._xsRequestsController.signal,i=t.map((t=>i=>{!async function(t,i){if(0!==t.indexOf("http://")&&0!==t.indexOf("https://"))return e.emit("warning",new Error(`skipping non-http xs param: ${t}`)),i(null);const n={method:"GET",headers:{"user-agent":Lt},signal:s};let r,o,a;try{r=await H(t,n)}catch(s){return e.emit("warning",new Error(`http error from xs param: ${t}`)),i(null)}if(e.destroyed)return i(null);if(e.metadata)return i(null);if(200!==r.status)return e.emit("warning",new Error(`non-200 status code ${r.status} from xs param: ${t}`)),i(null);try{o=new Uint8Array(await r.arrayBuffer())}catch(t){return e.emit("warning",t),i(null)}try{a=await W(o)}catch(e){}if(!a)return e.emit("warning",new Error(`got invalid torrent file from xs param: ${t}`)),i(null);if(a.infoHash!==e.infoHash)return e.emit("warning",new Error(`got torrent file with incorrect info hash from xs param: ${t}`)),i(null);e._onMetadata(a),i(null)}(t,i)}));y(i)}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 dt(this,e)));let s=this._preloadedStore;if(s||(s=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&&!(s instanceof Ze)&&(s=new pe(s,{max:this._storeCacheSlots})),this.store=new Ye(s),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 s=t===this.pieces.length-1?this.lastPieceLength:this.pieceLength;return new st(s)})),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===Ke?this.getFileModtimes(((t,s)=>{if(t)return this._destroy(t);this.files.map(((e,t)=>s[t]===this._fileModtimes[t])).every((e=>e))?(this._markAllVerified(),this._onStore()):this._verifyPieces(e)})):this._verifyPieces(e)}}getFileModtimes(e){const t=[];et(this.files.map(((e,s)=>i=>{const n=this.addUID?l(this.name+" - "+this.infoHash.slice(0,8)):l(this.path,e.path);oe.stat(n,((e,n)=>{if(e&&"ENOENT"!==e.code)return i(e);t[s]=n&&n.mtime.getTime(),i(null)}))})),Pt,(s=>{this._debug("done getting file modtimes"),e(s,t)}))}_verifyPieces(e){et(this.pieces.map(((e,t)=>e=>{if(this.destroyed)return e(new Error("torrent is destroyed"));const s={};t===this.pieces.length-1&&(s.length=this.lastPieceLength),this.store.get(t,s,(async(s,i)=>{if(this.destroyed)return e(new Error("torrent is destroyed"));if(s)return w((()=>e(null)));const n=await(0,b.tW)(i,"hex");if(this.destroyed)return e(new Error("torrent is destroyed"));n===this._hashes[t]?(this._debug("piece verified %s",t),this._markVerified(t)):(this._markUnverified(t),this._debug("piece invalid %s",t)),e(null)}))})),Pt,e)}rescanFiles(e){if(this.destroyed)throw new Error("torrent is destroyed");e||(e=Ft),this._verifyPieces((t=>{if(t)return this._destroy(t),e(t);this._checkDone(),e(null)}))}_markAllVerified(){for(let e=0;e<this.pieces.length;e++)this._markVerified(e)}_markVerified(e){this.pieces[e]=null,this._reservations[e]=null,this.bitfield.set(e,!0),this.emit("verified",e)}_markUnverified(e){const t=e===this.pieces.length-1?this.lastPieceLength:this.pieceLength;this.pieces[e]=new st(t),this.bitfield.set(e,!1),this._startAsDeselected||this.select(e,e,1),this.files.forEach((t=>{t.done&&t.includes(e)&&(t.done=!1)}))}_hasAllPieces(){for(let e=0;e<this.pieces.length;e++)if(!this.bitfield.get(e))return!1;return!0}_hasNoPieces(){return!this._hasMorePieces(0)}_hasMorePieces(e){let t=0;for(let s=0;s<this.pieces.length;s++)if(this.bitfield.get(s)&&(t+=1,t>e))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,s){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 dt&&e._destroy()}));const i=this._servers.map((e=>t=>{e.destroy(t)}));if(this.discovery&&i.push((e=>{this.discovery.destroy(e)})),this.store){let e=this._destroyStoreOnDestroy;t&&void 0!==t.destroyStore&&(e=t.destroyStore),i.push((t=>{e?this.store.destroy(t):this.store.close(t)}))}y(i,s),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 s;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}s=t[0]}else"string"==typeof e.remoteAddress&&(s=e.remoteAddress);if(this.client.blocked&&s&&this.client.blocked.contains(s))return this._debug("ignoring peer: blocked %s",e),"string"!=typeof e&&e.destroy(),this.emit("blockedPeer",e),!1;const i=this.client.utp&&this._isIPv4(s)?"utp":"tcp",n=!!this._addPeer(e,i,t);return n?this.emit("peer",e):this.emit("invalidPeer",e),n}_addPeer(e,t,s){if(this.destroyed)return"string"!=typeof e&&e.destroy(),null;if("string"==typeof e&&!this._validAddr(e))return this._debug("ignoring peer: invalid %s",e),null;const i=e&&e.id||e;if(this._peers[i])return this._debug("ignoring peer: duplicate (%s)",i),"string"!=typeof e&&e.destroy(),null;if(this.paused)return this._debug("ignoring peer: torrent is paused"),"string"!=typeof e&&e.destroy(),null;let n;return this._debug("add peer %s",i),n="string"==typeof e?"utp"===t?ut.default.createUTPOutgoingPeer(e,this,this.client.throttleGroups):ut.default.createTCPOutgoingPeer(e,this,this.client.throttleGroups):ut.default.createWebRTCPeer(e,this,this.client.throttleGroups),this._registerPeer(n),"string"==typeof e&&(this._queue.push(n),this._drain()),n}addWebSeed(e){if(this.destroyed)throw new Error("torrent is destroyed");let t,s;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);s=new yt(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(s=e,t=s.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 i=ut.default.createWebSeedPeer(s,t,this,this.client.throttleGroups);this._registerPeer(i),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,s,i,n=!1){if(this.destroyed)throw new Error("torrent is destroyed");if(e<0||t<e||this.pieces.length<=t)throw new Error(`invalid selection ${e} : ${t}`);s=Number(s)||0,this._debug("select %s-%s (priority %s)",e,t,s),this._selections.insert({from:e,to:t,offset:0,priority:s,notify:i,isStreamSelection:n}),this._selections.sort(((e,t)=>t.priority-e.priority)),this._updateSelections()}select(e,t,s,i){this._select(e,t,s,i,!1)}_deselect(e,t,s=!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:s}),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 s=e;s<=t;++s)this._critical[s]=!0;this._updateSelections()}_onWire(e,t){if(this._debug("got wire %s (%s)",e._debugId,t||"Unknown"),this.wires.push(e),t){const s=de(t);e.remoteAddress=s[0],e.remotePort=s[1]}this.client.dht&&this.client.dht.listening&&e.on("port",(s=>{if(!this.destroyed&&!this.client.dht.destroyed){if(!e.remoteAddress)return this._debug("ignoring PORT from peer with no address");if(0===s||s>65536)return this._debug("ignoring invalid PORT from peer");this._debug("port: %s (from %s)",s,t),this.client.dht.addNode({host:e.remoteAddress,port:s})}})),e.on("timeout",(()=>{this._debug("wire timeout (%s)",t),e.destroy()})),"webSeed"!==e.type&&e.setTimeout(3e4,!0),e.setKeepAlive(!0),e.use(ot(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 at&&!this.private&&(e.use(at()),e.ut_pex.on("peer",(e=>{this.done||(this._debug("ut_pex: got peer: %s (from %s)",e,t),this.addPeer(e,ut.default.SOURCE_UT_PEX))})),e.ut_pex.on("dropped",(e=>{const s=this._peers[e];s&&!s.connected&&(this._debug("ut_pex: dropped peer: %s (from %s)",e,t),this.removePeer(e))})),e.once("close",(()=>{e.ut_pex.reset()}))),e.use(Qe()),this.emit("wire",e,t),this.ready&&w((()=>{this._onWireWithMetadata(e)}))}_onWireWithMetadata(e){let t=null;const s=()=>{this.destroyed||e.destroyed||(this._numQueued>2*(this._numConns-this.numPeers)&&e.amInterested?e.destroy():(t=setTimeout(s,At),t.unref&&t.unref()))};let i;const n=()=>{if(e.peerPieces.buffer.length===this.bitfield.buffer.length){for(i=0;i<this.pieces.length;++i)if(!e.peerPieces.get(i))return;e.isSeeder=!0,this.alwaysChokeSeeders&&e.choke()}};e.on("bitfield",(()=>{n(),this._update(),this._updateWireInterest(e)})),e.on("have",(()=>{n(),this._update(),this._updateWireInterest(e)})),e.lt_donthave.on("donthave",(()=>{n(),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(s,At),t.unref&&t.unref()})),e.on("unchoke",(()=>{clearTimeout(t),this._update()})),e.on("request",((t,s,i,n)=>{if(i>131072)return e.destroy();this.pieces[t]||this.store.get(t,{offset:s,length:i},n)})),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(s,At),t.unref&&t.unref()),e.isSeeder=!1,n()}_updateSelections(){this.ready&&!this.destroyed&&(w((()=>{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.offset<e.to;)e.offset+=1;t!==e.offset&&e.notify?.(),e.to===e.from+e.offset&&(this.bitfield.get(e.from+e.offset)&&(e.remove(),e.notify?.(),this._updateInterest()))}this._selections.length||this.emit("idle")}_updateInterest(){const e=this._amInterested;this._amInterested=!!this._selections.length,this.wires.forEach((e=>this._updateWireInterest(e))),e!==this._amInterested&&(this._amInterested?this.emit("interested"):this.emit("uninterested"))}_updateWireInterest(e){let t=!1;for(let s=0;s<this.pieces.length;++s)if(this.pieces[s]&&e.peerPieces.get(s)){t=!0;break}t?e.interested():e.uninterested()}_update(){Nt?Nt((()=>this._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,s=Ut(e,.5);if(e.requests.length>=s)return;const i=Ut(e,1);if(e.peerChoking)e.hasFast&&e.peerAllowedFastSet.length>0&&!this._hasMorePieces(e.peerAllowedFastSet.length-1)&&function(){if(e.requests.length>=i)return!1;for(const s of e.peerAllowedFastSet){if(e.peerPieces.get(s)&&!t.bitfield.get(s))for(;t._request(e,s,!1)&&e.requests.length<i;);if(!(e.requests.length<i))return!0}}();else{if(!e.downloaded)return function(){if(e.requests.length)return;let s=t._selections.length;for(;s--;){const i=t._selections.get(s);let r;if("rarest"===t.strategy){const s=i.from+i.offset,o=i.to,a=o-s+1,h={};let l=0;const c=n(s,o,h);for(;l<a&&(r=t._rarityMap.getRarestPiece(c),!(r<0));){if(t._request(e,r,!1))return;h[r]=!0,l+=1}}else for(r=i.to;r>=i.from+i.offset;--r)if(e.peerPieces.get(r)&&t._request(e,r,!1))return}}();o(!1)||o(!0)}function n(t,s,i,n){return r=>r>=t&&r<=s&&!(r in i)&&e.peerPieces.get(r)&&(!n||n(r))}function r(e){let s=e;for(let i=e;i<t._selections.length&&t._selections.get(i).priority;i++)s=i;t._selections.swap(e,s)}function o(s){if(e.requests.length>=i)return!0;const o=function(){const s=e.downloadSpeed()||1;if(s>Tt)return()=>!0;const i=Math.max(1,e.requests.length)*st.BLOCK_LENGTH/s;let n=10,r=0;return e=>{if(!n||t.bitfield.get(e))return!0;let o=t.pieces[e].missing;for(;r<t.wires.length;r++){const a=t.wires[r],h=a.downloadSpeed();if(!(h<Tt)&&!(h<=s)&&a.peerPieces.get(e)&&!((o-=h*i)>0))return n--,!1}return!0}}();for(let a=0;a<t._selections.length;a++){const h=t._selections.get(a);let l;if("rarest"===t.strategy){const c=h.from+h.offset,d=h.to,u=d-c+1,p={};let f=0;const m=n(c,d,p,o);for(;f<u&&(l=t._rarityMap.getRarestPiece(m),!(l<0));){for(;t._request(e,l,t._critical[l]||s)&&e.requests.length<i;);if(!(e.requests.length<i))return h.priority&&r(a),!0;p[l]=!0,f++}}else for(l=h.from+h.offset;l<=h.to;l++)if(e.peerPieces.get(l)&&o(l)){for(;t._request(e,l,t._critical[l]||s)&&e.requests.length<i;);if(!(e.requests.length<i))return h.priority&&r(a),!0}}return!1}}_rechoke(){if(!this.ready)return;const e=this.wires.map((e=>({wire:e,random:Math.random()}))).sort(((e,t)=>{const s=e.wire,i=t.wire;return s.downloadSpeed()!==i.downloadSpeed()?s.downloadSpeed()-i.downloadSpeed():s.uploadSpeed()!==i.uploadSpeed()?s.uploadSpeed()-i.uploadSpeed():s.amChoking!==i.amChoking?s.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&&t<this._rechokeNumSlots-1;){const s=e.pop();s.isSeeder||s===this._rechokeOptimisticWire||(s.unchoke(),s.peerInterested&&t++)}if(null===this._rechokeOptimisticWire&&this._rechokeNumSlots>0){const t=e.filter((e=>e.peerInterested));if(t.length>0){const e=t[(s=t.length,Math.random()*s|0)];e.unchoke(),this._rechokeOptimisticWire=e,this._rechokeOptimisticTime=2}}var s;e.filter((e=>e!==this._rechokeOptimisticWire)).forEach((e=>e.choke()))}_hotswap(e,t){const s=e.downloadSpeed();if(s<st.BLOCK_LENGTH)return!1;if(!this._reservations[t])return!1;const i=this._reservations[t];if(!i)return!1;let n,r,o=1/0;for(r=0;r<i.length;r++){const t=i[r];if(!t||t===e)continue;const a=t.downloadSpeed();a>=Tt||(2*a>s||a>o||(n=t,o=a))}if(!n)return!1;for(r=0;r<i.length;r++)i[r]===n&&(i[r]=null);for(r=0;r<n.requests.length;r++){const e=n.requests[r];e.piece===t&&this.pieces[t].cancel(e.offset/st.BLOCK_LENGTH|0)}return this.emit("hotswap",n,e,t),!0}_request(e,t,s){const i=this,n=e.requests.length,r="webSeed"===e.type;if(i.bitfield.get(t))return!1;const o=r?Math.min(function(e,t,s){return 1+Math.ceil(t*e.downloadSpeed()/s)}(e,1,i.pieceLength),i.maxWebConns):Ut(e,1);if(n>=o)return!1;const a=i.pieces[t];let h=r?a.reserveRemaining():a.reserve();if(-1===h&&s&&i._hotswap(e,t)&&(h=r?a.reserveRemaining():a.reserve()),-1===h)return!1;let l=i._reservations[t];l||(l=i._reservations[t]=[]);let c=l.indexOf(null);-1===c&&(c=l.length),l[c]=e;const d=a.chunkOffset(h),u=r?a.chunkLengthRemaining(h):a.chunkLength(h);function p(){w((()=>{i._update()}))}return e.request(t,d,u,(async function s(n,o){if(i.destroyed)return;if(!i.ready)return i.once("ready",(()=>{s(n,o)}));if(l[c]===e&&(l[c]=null),a!==i.pieces[t])return p();if(n)return i._debug("error getting piece %s (offset: %s length: %s) from %s: %s",t,d,u,`${e.remoteAddress}:${e.remotePort}`,n.message),r?a.cancelRemaining(h):a.cancel(h),void p();if(i._debug("got piece %s (offset: %s length: %s) from %s",t,d,u,`${e.remoteAddress}:${e.remotePort}`),!a.set(h,o,e))return p();const f=a.flush(),m=await(0,b.tW)(f,"hex");i.destroyed||(m===i._hashes[t]?(i._debug("piece verified %s",t),i.store.put(t,f,(e=>{e?i._destroy(e):(i.pieces[t]=null,i._markVerified(t),i.wires.forEach((e=>{e.have(t)})),i._checkDone()&&!i.destroyed&&i.discovery.complete(),p())}))):(i.pieces[t]=new st(a.length),i.emit("warning",new Error(`Piece ${t} failed verification`)),p()))})),!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 s=t.from;s<=t.to;s++)if(!this.bitfield.get(s)){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=Ft);try{await me(this.store,g(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]}`,Ct(...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),s={host:t[0],port:t[1]};this.client.utp&&e.type===ut.default.TYPE_UTP_OUTGOING?e.conn=ft.connect(s.port,s.host):e.conn=ae.connect(s);const i=e.conn;i.once("connect",(()=>{this.destroyed||e.onConnect()})),i.once("error",(t=>{e.destroy(t)})),e.startConnectTimeout(),i.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 s=setTimeout((()=>{if(this.destroyed)return;const t=de(e.addr)[0],s=this.client.utp&&this._isIPv4(t)?"utp":"tcp",i=this._addPeer(e.addr,s,e.source);i&&(i.retries=e.retries+1)}),t);s.unref&&s.unref()}))}_validAddr(e){let t;try{t=de(e)}catch(e){return!1}const s=t[0],i=t[1];return i>0&&i<65535&&!("127.0.0.1"===s&&i===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 s=2+Math.ceil(t*e.downloadSpeed()/st.BLOCK_LENGTH);if(e.peerExtendedHandshake){const t=e.peerExtendedHandshake.reqq;"number"==typeof t&&t>0&&(s=Math.min(s,t))}return s}function Ft(){}var jt=n(4043),Bt=n(580),Dt=n(815),qt=n(2878);class Wt{constructor(e,t={}){this.client=e,t.origin||(t.origin="*"),this.opts=t,this.pendingReady=new Set}static serveIndexPage(e,t,s){const i=t.map((e=>`<li>\n <a href="${Bt(s)}/${e.infoHash}">\n ${Bt(e.name)}\n </a>\n (${Bt(e.length)} bytes)\n </li>`)).join("<br>");return e.status=200,e.headers["Content-Type"]="text/html",e.body=Vt("WebTorrent",`<h1>WebTorrent</h1>\n <ol>${i}</ol>`),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","<h1>405 - Method Not Allowed</h1>"),e}static serve404Page(e){return e.status=404,e.headers["Content-Type"]="text/html",e.body=Vt("404 - Not Found","<h1>404 - Not Found</h1>"),e}static serveTorrentPage(e,t,s){const i=e.files.map((t=>`<li>\n <a href="${Bt(s)}/${e.infoHash}/${Bt(t.path)}">\n ${Bt(t.path)}\n </a>\n (${Bt(t.length)} bytes)\n </li>`)).join("<br>");return t.status=200,t.headers["Content-Type"]="text/html",t.body=Vt(`${Bt(e.name)} - WebTorrent`,`<h1>${Bt(e.name)}</h1>\n <ol>${i}</ol>`),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,s){s.status=200,s.headers.Expires="0",s.headers["Cache-Control"]="no-cache, no-store, must-revalidate, max-age=0",s.headers["Accept-Ranges"]="bytes",s.headers["Content-Type"]=e.type,s.headers["transferMode.dlna.org"]="Streaming",s.headers["contentFeatures.dlna.org"]="DLNA.ORG_OP=01;DLNA.ORG_CI=0;DLNA.ORG_FLAGS=01700000000000000000000000000000","document"===t.destination?(s.headers["Content-Type"]="application/octet-stream",s.headers["Content-Disposition"]=`attachment; filename*=UTF-8''${Gt(e.name)}`,s.body="DOWNLOAD"):s.headers["Content-Disposition"]=`inline; filename*=UTF-8''${Gt(e.name)}`;let i=qt(e.length,t.headers.range||"");if(Array.isArray(i)?(s.status=206,i=i[0],s.headers["Content-Range"]=`bytes ${i.start}-${i.end}/${e.length}`,s.headers["Content-Length"]=i.end-i.start+1):(s.statusCode=200,i=null,s.headers["Content-Length"]=e.length),"GET"===t.method){const n=e[Symbol.asyncIterator](i);let r=null;e.emit("iterator",{iterator:n,req:t,file:e},(e=>{r=e}));const o=Y.Readable.from(r||n);let a=null;e.emit("stream",{stream:o,req:t,file:e},(e=>{a=Dt(o,e)})),s.body=a||o}else s.body=!1;return s}async onRequest(e,t){let s=new URL(e.url,"http://example.com").pathname;s=s.slice(s.indexOf(this.pathname)+this.pathname.length+1);const i={headers:{"X-Content-Type-Options":"nosniff","Content-Security-Policy":"base-uri 'none'; frame-ancestors 'none'; form-action 'none';"}};if(this.isOriginAllowed(e)&&(i.headers["Access-Control-Allow-Origin"]="*"===this.opts.origin?"*":e.headers.origin),"favicon.ico"===s)return t(Wt.serve404Page(i));if("OPTIONS"===e.method)return this.isOriginAllowed(e)?t(Wt.serveOptionsRequest(e,i)):t(Wt.serveMethodNotAllowed(i));const n=async()=>{this.pendingReady.delete(n);const e=await r();t(e)},r=async()=>{if(""===s)return Wt.serveIndexPage(i,this.client.torrents,this.pathname);let[t,...n]=s.split("/");n=decodeURI(n.join("/"));const r=await this.client.get(t);if(!t||!r)return Wt.serve404Page(i);if(!n)return Wt.serveTorrentPage(r,i,this.pathname);const o=r.files.find((e=>e.path.replace(/\\/g,"/")===n));return o?Wt.serveFile(o,e,i):Wt.serve404Page(i)};if("GET"===e.method||"HEAD"===e.method){if(this.client.ready){const e=await r();return t(e)}return this.pendingReady.add(n),void this.client.once("ready",n)}return t(Wt.serveMethodNotAllowed(i))}close(e=()=>{}){this.closed=!0,this.pendingReady.forEach((e=>{this.client.removeListener("ready",e)})),this.pendingReady.clear(),w(e)}destroy(e=()=>{}){this.closed?w(e):this.close(e),this.client=null}}class $t extends Wt{constructor(e,t){super(e,t),this.server=jt.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:s,body:i})=>{t.writeHead(e,s),i._readableState||i._writableState?Dt(i,t):t.end(i)})):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 zt extends Wt{constructor(e,t){super(e,t),this.registration=t.controller,this.workerKeepAliveInterval=null,this.workerPortCount=0;const s=new URL(t.controller.scope);this.pathname=s.pathname+"webtorrent",this._address={port:s.port,family:"IPv4",address:s.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[s]=e.ports;this.onRequest(t,(({status:e,headers:t,body:i})=>{const n=i[Symbol.asyncIterator]?.(),r=()=>{s.onmessage=null,i?.destroy&&i.destroy(),this.workerPortCount--,this.workerPortCount||(clearInterval(this.workerKeepAliveInterval),this.workerKeepAliveInterval=null)};s.onmessage=async e=>{if(e.data){let e;try{e=(await n.next()).value}catch(e){}s.postMessage(e),e||r(),this.workerKeepAliveInterval||(this.workerKeepAliveInterval=setInterval((()=>fetch(`${this.pathname}/keepalive/`)),2e4))}else r()},this.workerPortCount++,s.postMessage({status:e,headers:t,body:n?"STREAM":i})}))}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 <!DOCTYPE html>\n <html lang="en">\n <head>\n <meta charset="utf-8">\n <title>${e}</title>\n </head>\n <body>\n ${t}\n </body>\n </html>\n `}function Gt(e){return encodeURIComponent(e).replace(/['()]/g,escape).replace(/\*/g,"%2A").replace(/%(?:7C|60|5E)/g,unescape)}const Kt=I("webtorrent"),Yt=_t.replace(/\d*./g,(e=>("0"+e%100).slice(-2))).slice(0,4),Jt=`-WW${Yt}-`;class Xt extends o{constructor(e={}){super(),"string"==typeof e.peerId?this.peerId=e.peerId:ArrayBuffer.isView(e.peerId)?this.peerId=(0,b.V5)(e.peerId):this.peerId=(0,b.V5)((0,b.L0)(Jt+(0,b.NJ)((0,b.po)(9)))),this.peerIdBuffer=(0,b.fk)(this.peerId),"string"==typeof e.nodeId?this.nodeId=e.nodeId:ArrayBuffer.isView(e.nodeId)?this.nodeId=(0,b.V5)(e.nodeId):this.nodeId=(0,b.V5)((0,b.po)(20)),this.nodeIdBuffer=(0,b.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=Xt.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 ne&&(this.natTraversal=new ne({enableUPNP:this.natUpnp,enablePMP:this.natPmp,upnpPermanentFallback:"permanent"===e.natUpnp})),!0===e.secure&&Promise.resolve().then(n.bind(n,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 ie.ThrottleGroup({rate:Math.max(this._downloadLimit,0),enabled:this._downloadLimit>=0}),up:new ie.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):w((()=>{this._onListening()})),this._downloadSpeed=se(),this._uploadSpeed=se(),!1!==e.dht&&"function"==typeof L.Client?(this.dht=new L.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=>{Kt("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,s)=>{if(e)return console.error(`Failed to load blocklist: ${e.message}`);this.blocked=s,t()})):w(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 zt(this,e),this._server}return this._server=new $t(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 Mt){if(this.torrents.includes(e))return e}else{const t=this.torrents;let s;try{s=await W(e)}catch(e){}if(!s)return null;if(!s.infoHash)throw new Error("Invalid torrent identifier");for(const e of t)if(e.infoHash===s.infoHash)return e}return null}add(e,t={},s=()=>{}){if(this.destroyed)throw new Error("client is destroyed");"function"==typeof t&&([t,s]=[{},t]);const i=()=>{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 s(e)},n=()=>{this.destroyed||(s(r),this.emit("torrent",r))};this._debug("add"),t=t?Object.assign({},t):{};const r=new Mt(e,this,t);return this.torrents.push(r),r.once("_infoHash",i),r.once("ready",n),r.once("close",(function e(){r.removeListener("_infoHash",i),r.removeListener("ready",n),r.removeListener("close",e)})),this.emit("add",r),r}seed(e,t,s){if(this.destroyed)throw new Error("client is destroyed");"function"==typeof t&&([t,s]=[{},t]),this._debug("seed"),(t=t?Object.assign({},t):{}).skipVerify=!0;const i="string"==typeof e;i&&(t.path=function(e){if(a(e),0===e.length)return".";let t=e.charCodeAt(0);const s=47===t;let i=-1,n=!0;for(let s=e.length-1;s>=1;--s)if(t=e.charCodeAt(s),47===t){if(!n){i=s;break}}else n=!1;return-1===i?s?"/":".":s&&1===i?"//":e.slice(0,i)}(e)),t.createdBy||(t.createdBy=`WebTorrent/${Yt}`);const n=e=>{this._debug("on seed"),"function"==typeof s&&s(e),e.emit("seed"),this.emit("seed",e)},r=this.add(null,t,(e=>{const s=[s=>{if(i||t.preloadedStore)return s();e.load(o,s)}];this.dht&&s.push((t=>{e.once("dhtAnnounce",t)})),y(s,(t=>{if(!this.destroyed)return t?e._destroy(t):void n(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 s=>{if(!t.preloadedStore&&function(e){return"object"==typeof e&&null!=e&&"function"==typeof e.pipe}(e)){const t=[];try{for await(const s of e)t.push(s)}catch(e){return s(e)}const i=(0,b.xW)(t);i.name=e.name,s(null,i)}else s(null,e)})),((e,i)=>{if(!this.destroyed)return e?r._destroy(e):void function(e,t,s){"function"==typeof t&&([t,s]=[s,t]),S(e,t=t?Object.assign({},t):{},s)}(i,t,((e,n)=>{if(!this.destroyed){if(e)return r._destroy(e);o=n.map((e=>e.getStream)),P(i,t,(async(e,t)=>{if(this.destroyed)return;if(e)return r._destroy(e);const i=await this.get(t);i?(console.warn("A torrent with the same id is already being seeded"),r._destroy(),"function"==typeof s&&s(i)):r._onTorrentId(t)}))}}))})),r}async remove(e,t,s){if("function"==typeof t)return this.remove(e,null,t);this._debug("remove");const i=await this.get(e);if(!i)throw new Error(`No torrent with id ${e}`);this._remove(i,t,s)}_remove(e,t,s){if(!e)return;if("function"==typeof t)return this._remove(e,null,t);const i=this.torrents.indexOf(e);-1!==i&&(this.torrents.splice(i,1),e.destroy(t,s),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 s=this.torrents.map((e=>t=>{e.destroy(t)}));this._connPool&&s.push((e=>{this._connPool.destroy(e)})),this.dht&&s.push((e=>{this.dht.destroy(e)})),this._server&&s.push((e=>{this._server.destroy(e)})),this.natTraversal&&s.push((e=>{this.natTraversal.destroy().then((()=>e()))})),y(s,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=>{Kt("error mapping WebTorrent port via UPnP/PMP: %o",e)})))}this.emit("listening")}_debug(){const e=[].slice.call(arguments);e[0]=`[${this._debugId}] ${e[0]}`,Kt(...e)}async _getByHash(e){for(const t of this.torrents)if(t.infoHashHash||(t.infoHashHash=await(0,b.tW)((0,b.fk)("72657132"+t.infoHash),"hex")),e===t.infoHashHash)return t;return null}}Xt.WEBRTC_SUPPORT=te.WEBRTC_SUPPORT,Xt.UTP_SUPPORT=re.UTP_SUPPORT,Xt.VERSION=_t;var Qt=r.A;export{Qt as default};
//# sourceMappingURL=webtorrent.min.js.map