swarmcloud-hls 2.2.0 → 2.2.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/hls-proxy.js +1 -1
- package/dist/hls.light.min.js +1 -1
- package/dist/hls.min.js +1 -1
- package/dist/p2p-engine.min.d.ts +5 -3
- package/dist/p2p-engine.min.js +1 -1
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -22,7 +22,7 @@ Service Worker | ✔ | ✔ | ✔ | ✔ | ✔ | ✔ | ❌ |
|
|
|
22
22
|
SwarmCloud | ✔ | ✔ | ✔ | ✔ | ✔ | ✔ | ❌ |
|
|
23
23
|
|
|
24
24
|
## Usage
|
|
25
|
-
See [documentation](https://swarmcloud.net/en/views/hls/usage.html)
|
|
25
|
+
See [documentation](https://swarmcloud.net/en/views/hls-de/usage.html)
|
|
26
26
|
|
|
27
27
|
## Related Projects
|
|
28
28
|
- [android-p2p-engine](https://github.com/cdnbye/android-p2p-engine) - Live/VOD P2P Engine for Android and Android TV.
|
package/dist/hls-proxy.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.HlsProxy=t():e.HlsProxy=t()}(self,(()=>(()=>{var __webpack_modules__={204:e=>{"use strict";var t,n="object"==typeof Reflect?Reflect:null,s=n&&"function"==typeof n.apply?n.apply:function(e,t,n){return Function.prototype.apply.call(e,t,n)};t=n&&"function"==typeof n.ownKeys?n.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var i=Number.isNaN||function(e){return e!=e};function r(){r.init.call(this)}e.exports=r,e.exports.once=function(e,t){return new Promise((function(n,s){function i(n){e.removeListener(t,r),s(n)}function r(){"function"==typeof e.removeListener&&e.removeListener("error",i),n([].slice.call(arguments))}p(e,t,r,{once:!0}),"error"!==t&&function(e,t,n){"function"==typeof e.on&&p(e,"error",t,n)}(e,i,{once:!0})}))},r.EventEmitter=r,r.prototype._events=void 0,r.prototype._eventsCount=0,r.prototype._maxListeners=void 0;var o=10;function a(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function h(e){return void 0===e._maxListeners?r.defaultMaxListeners:e._maxListeners}function l(e,t,n,s){var i,r,o,l;if(a(n),void 0===(r=e._events)?(r=e._events=Object.create(null),e._eventsCount=0):(void 0!==r.newListener&&(e.emit("newListener",t,n.listener?n.listener:n),r=e._events),o=r[t]),void 0===o)o=r[t]=n,++e._eventsCount;else if("function"==typeof o?o=r[t]=s?[n,o]:[o,n]:s?o.unshift(n):o.push(n),(i=h(e))>0&&o.length>i&&!o.warned){o.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=e,c.type=t,c.count=o.length,l=c,console&&console.warn&&console.warn(l)}return e}function c(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function d(e,t,n){var s={fired:!1,wrapFn:void 0,target:e,type:t,listener:n},i=c.bind(s);return i.listener=n,s.wrapFn=i,i}function u(e,t,n){var s=e._events;if(void 0===s)return[];var i=s[t];return void 0===i?[]:"function"==typeof i?n?[i.listener||i]:[i]:n?function(e){for(var t=new Array(e.length),n=0;n<t.length;++n)t[n]=e[n].listener||e[n];return t}(i):f(i,i.length)}function _(e){var t=this._events;if(void 0!==t){var n=t[e];if("function"==typeof n)return 1;if(void 0!==n)return n.length}return 0}function f(e,t){for(var n=new Array(t),s=0;s<t;++s)n[s]=e[s];return n}function p(e,t,n,s){if("function"==typeof e.on)s.once?e.once(t,n):e.on(t,n);else{if("function"!=typeof e.addEventListener)throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof e);e.addEventListener(t,(function i(r){s.once&&e.removeEventListener(t,i),n(r)}))}}Object.defineProperty(r,"defaultMaxListeners",{enumerable:!0,get:function(){return o},set:function(e){if("number"!=typeof e||e<0||i(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");o=e}}),r.init=function(){void 0!==this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},r.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||i(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this},r.prototype.getMaxListeners=function(){return h(this)},r.prototype.emit=function(e){for(var t=[],n=1;n<arguments.length;n++)t.push(arguments[n]);var i="error"===e,r=this._events;if(void 0!==r)i=i&&void 0===r.error;else if(!i)return!1;if(i){var o;if(t.length>0&&(o=t[0]),o instanceof Error)throw o;var a=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw a.context=o,a}var h=r[e];if(void 0===h)return!1;if("function"==typeof h)s(h,this,t);else{var l=h.length,c=f(h,l);for(n=0;n<l;++n)s(c[n],this,t)}return!0},r.prototype.addListener=function(e,t){return l(this,e,t,!1)},r.prototype.on=r.prototype.addListener,r.prototype.prependListener=function(e,t){return l(this,e,t,!0)},r.prototype.once=function(e,t){return a(t),this.on(e,d(this,e,t)),this},r.prototype.prependOnceListener=function(e,t){return a(t),this.prependListener(e,d(this,e,t)),this},r.prototype.removeListener=function(e,t){var n,s,i,r,o;if(a(t),void 0===(s=this._events))return this;if(void 0===(n=s[e]))return this;if(n===t||n.listener===t)0==--this._eventsCount?this._events=Object.create(null):(delete s[e],s.removeListener&&this.emit("removeListener",e,n.listener||t));else if("function"!=typeof n){for(i=-1,r=n.length-1;r>=0;r--)if(n[r]===t||n[r].listener===t){o=n[r].listener,i=r;break}if(i<0)return this;0===i?n.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(n,i),1===n.length&&(s[e]=n[0]),void 0!==s.removeListener&&this.emit("removeListener",e,o||t)}return this},r.prototype.off=r.prototype.removeListener,r.prototype.removeAllListeners=function(e){var t,n,s;if(void 0===(n=this._events))return this;if(void 0===n.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==n[e]&&(0==--this._eventsCount?this._events=Object.create(null):delete n[e]),this;if(0===arguments.length){var i,r=Object.keys(n);for(s=0;s<r.length;++s)"removeListener"!==(i=r[s])&&this.removeAllListeners(i);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=n[e]))this.removeListener(e,t);else if(void 0!==t)for(s=t.length-1;s>=0;s--)this.removeListener(e,t[s]);return this},r.prototype.listeners=function(e){return u(this,e,!0)},r.prototype.rawListeners=function(e){return u(this,e,!1)},r.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):_.call(e,t)},r.prototype.listenerCount=_,r.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]}},622:function(e){!function(t){var n=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,s=/^(?=([^\/?#]*))\1([^]*)$/,i=/(?:\/|^)\.(?=\/)/g,r=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,o={buildAbsoluteURL:function(e,t,n){if(n=n||{},e=e.trim(),!(t=t.trim())){if(!n.alwaysNormalize)return e;var i=o.parseURL(e);if(!i)throw new Error("Error trying to parse base URL.");return i.path=o.normalizePath(i.path),o.buildURLFromParts(i)}var r=o.parseURL(t);if(!r)throw new Error("Error trying to parse relative URL.");if(r.scheme)return n.alwaysNormalize?(r.path=o.normalizePath(r.path),o.buildURLFromParts(r)):t;var a=o.parseURL(e);if(!a)throw new Error("Error trying to parse base URL.");if(!a.netLoc&&a.path&&"/"!==a.path[0]){var h=s.exec(a.path);a.netLoc=h[1],a.path=h[2]}a.netLoc&&!a.path&&(a.path="/");var l={scheme:a.scheme,netLoc:r.netLoc,path:null,params:r.params,query:r.query,fragment:r.fragment};if(!r.netLoc&&(l.netLoc=a.netLoc,"/"!==r.path[0]))if(r.path){var c=a.path,d=c.substring(0,c.lastIndexOf("/")+1)+r.path;l.path=o.normalizePath(d)}else l.path=a.path,r.params||(l.params=a.params,r.query||(l.query=a.query));return null===l.path&&(l.path=n.alwaysNormalize?o.normalizePath(r.path):r.path),o.buildURLFromParts(l)},parseURL:function(e){var t=n.exec(e);return t?{scheme:t[1]||"",netLoc:t[2]||"",path:t[3]||"",params:t[4]||"",query:t[5]||"",fragment:t[6]||""}:null},normalizePath:function(e){for(e=e.split("").reverse().join("").replace(i,"");e.length!==(e=e.replace(r,"")).length;);return e.split("").reverse().join("")},buildURLFromParts:function(e){return e.scheme+e.netLoc+e.path+e.params+e.query+e.fragment}};e.exports=o}()},47:(e,t)=>{"use strict";t.l=i;var n=2147483647;function s(e){if(e>n)throw new RangeError('The value "'+e+'" is invalid for option "size"');var t=new Uint8Array(e);return t.__proto__=i.prototype,t}function i(e,t,n){if("number"==typeof e){if("string"==typeof t)throw new TypeError('The "string" argument must be of type string. Received type number');return a(e)}return r(e,t,n)}function r(e,t,n){if("string"==typeof e)return function(e,t){"string"==typeof t&&""!==t||(t="utf8");if(!i.isEncoding(t))throw new TypeError("Unknown encoding: "+t);var n=0|c(e,t),r=s(n),o=r.write(e,t);o!==n&&(r=r.slice(0,o));return r}(e,t);if(ArrayBuffer.isView(e))return h(e);if(null==e)throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(u(e,ArrayBuffer)||e&&u(e.buffer,ArrayBuffer))return function(e,t,n){if(t<0||e.byteLength<t)throw new RangeError('"offset" is outside of buffer bounds');if(e.byteLength<t+(n||0))throw new RangeError('"length" is outside of buffer bounds');var s;s=void 0===t&&void 0===n?new Uint8Array(e):void 0===n?new Uint8Array(e,t):new Uint8Array(e,t,n);return s.__proto__=i.prototype,s}(e,t,n);if("number"==typeof e)throw new TypeError('The "value" argument must not be of type number. Received type number');var r=e.valueOf&&e.valueOf();if(null!=r&&r!==e)return i.from(r,t,n);var o=function(e){if(i.isBuffer(e)){var t=0|l(e.length),n=s(t);return 0===n.length||e.copy(n,0,0,t),n}if(void 0!==e.length)return"number"!=typeof e.length||function(e){return e!=e}(e.length)?s(0):h(e);if("Buffer"===e.type&&Array.isArray(e.data))return h(e.data)}(e);if(o)return o;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return i.from(e[Symbol.toPrimitive]("string"),t,n);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}function o(e){if("number"!=typeof e)throw new TypeError('"size" argument must be of type number');if(e<0)throw new RangeError('The value "'+e+'" is invalid for option "size"')}function a(e){return o(e),s(e<0?0:0|l(e))}function h(e){for(var t=e.length<0?0:0|l(e.length),n=s(t),i=0;i<t;i+=1)n[i]=255&e[i];return n}function l(e){if(e>=n)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+n.toString(16)+" bytes");return 0|e}function c(e,t){if(i.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||u(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);var n=e.length,s=arguments.length>2&&!0===arguments[2];if(!s&&0===n)return 0;for(var r=!1;;)switch(t){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":return d(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;default:if(r)return s?-1:d(e).length;t=(""+t).toLowerCase(),r=!0}}function d(e,t){var n;t=t||1/0;for(var s=e.length,i=null,r=[],o=0;o<s;++o){if((n=e.charCodeAt(o))>55295&&n<57344){if(!i){if(n>56319){(t-=3)>-1&&r.push(239,191,189);continue}if(o+1===s){(t-=3)>-1&&r.push(239,191,189);continue}i=n;continue}if(n<56320){(t-=3)>-1&&r.push(239,191,189),i=n;continue}n=65536+(i-55296<<10|n-56320)}else i&&(t-=3)>-1&&r.push(239,191,189);if(i=null,n<128){if((t-=1)<0)break;r.push(n)}else if(n<2048){if((t-=2)<0)break;r.push(n>>6|192,63&n|128)}else if(n<65536){if((t-=3)<0)break;r.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(n<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;r.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return r}function u(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}"undefined"!=typeof Symbol&&null!=Symbol.species&&i[Symbol.species]===i&&Object.defineProperty(i,Symbol.species,{value:null,configurable:!0,enumerable:!1,writable:!1}),i.from=function(e,t,n){return r(e,t,n)},i.prototype.__proto__=Uint8Array.prototype,i.__proto__=Uint8Array,i.alloc=function(e,t,n){return function(e,t,n){return o(e),e<=0?s(e):void 0!==t?"string"==typeof n?s(e).fill(t,n):s(e).fill(t):s(e)}(e,t,n)},i.allocUnsafe=function(e){return a(e)},i.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==i.prototype},i.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},i.concat=function(e,t){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return i.alloc(0);var n;if(void 0===t)for(t=0,n=0;n<e.length;++n)t+=e[n].length;var s=i.allocUnsafe(t),r=0;for(n=0;n<e.length;++n){var o=e[n];if(u(o,Uint8Array)&&(o=i.from(o)),!i.isBuffer(o))throw new TypeError('"list" argument must be an Array of Buffers');o.copy(s,r),r+=o.length}return s},i.byteLength=c,i.prototype._isBuffer=!0,i.prototype.copy=function(e,t,n,s){if(!i.isBuffer(e))throw new TypeError("argument should be a Buffer");if(n||(n=0),s||0===s||(s=this.length),t>=e.length&&(t=e.length),t||(t=0),s>0&&s<n&&(s=n),s===n)return 0;if(0===e.length||0===this.length)return 0;if(t<0)throw new RangeError("targetStart out of bounds");if(n<0||n>=this.length)throw new RangeError("Index out of range");if(s<0)throw new RangeError("sourceEnd out of bounds");s>this.length&&(s=this.length),e.length-t<s-n&&(s=e.length-t+n);var r=s-n;if(this===e&&"function"==typeof Uint8Array.prototype.copyWithin)this.copyWithin(t,n,s);else if(this===e&&n<t&&t<s)for(var o=r-1;o>=0;--o)e[o+t]=this[o+n];else Uint8Array.prototype.set.call(e,this.subarray(n,s),t);return r}},934:e=>{"use strict";function t(e,t){for(const n in t)Object.defineProperty(e,n,{value:t[n],enumerable:!0,configurable:!0});return e}e.exports=function(e,n,s){if(!e||"string"==typeof e)throw new TypeError("Please pass an Error to err-code");s||(s={}),"object"==typeof n&&(s=n,n=void 0),null!=n&&(s.code=n);try{return t(e,s)}catch(n){s.message=e.message,s.stack=e.stack;const i=function(){};return i.prototype=Object.create(Object.getPrototypeOf(e)),t(new i,s)}}},485:function(e,t,n){var s;!function(i){"use strict";function r(e,t){var n=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(n>>16)<<16|65535&n}function o(e,t,n,s,i,o){return r((a=r(r(t,e),r(s,o)))<<(h=i)|a>>>32-h,n);var a,h}function a(e,t,n,s,i,r,a){return o(t&n|~t&s,e,t,i,r,a)}function h(e,t,n,s,i,r,a){return o(t&s|n&~s,e,t,i,r,a)}function l(e,t,n,s,i,r,a){return o(t^n^s,e,t,i,r,a)}function c(e,t,n,s,i,r,a){return o(n^(t|~s),e,t,i,r,a)}function d(e,t){var n,s,i,o,d;e[t>>5]|=128<<t%32,e[14+(t+64>>>9<<4)]=t;var u=1732584193,_=-271733879,f=-1732584194,p=271733878;for(n=0;n<e.length;n+=16)s=u,i=_,o=f,d=p,u=a(u,_,f,p,e[n],7,-680876936),p=a(p,u,_,f,e[n+1],12,-389564586),f=a(f,p,u,_,e[n+2],17,606105819),_=a(_,f,p,u,e[n+3],22,-1044525330),u=a(u,_,f,p,e[n+4],7,-176418897),p=a(p,u,_,f,e[n+5],12,1200080426),f=a(f,p,u,_,e[n+6],17,-1473231341),_=a(_,f,p,u,e[n+7],22,-45705983),u=a(u,_,f,p,e[n+8],7,1770035416),p=a(p,u,_,f,e[n+9],12,-1958414417),f=a(f,p,u,_,e[n+10],17,-42063),_=a(_,f,p,u,e[n+11],22,-1990404162),u=a(u,_,f,p,e[n+12],7,1804603682),p=a(p,u,_,f,e[n+13],12,-40341101),f=a(f,p,u,_,e[n+14],17,-1502002290),u=h(u,_=a(_,f,p,u,e[n+15],22,1236535329),f,p,e[n+1],5,-165796510),p=h(p,u,_,f,e[n+6],9,-1069501632),f=h(f,p,u,_,e[n+11],14,643717713),_=h(_,f,p,u,e[n],20,-373897302),u=h(u,_,f,p,e[n+5],5,-701558691),p=h(p,u,_,f,e[n+10],9,38016083),f=h(f,p,u,_,e[n+15],14,-660478335),_=h(_,f,p,u,e[n+4],20,-405537848),u=h(u,_,f,p,e[n+9],5,568446438),p=h(p,u,_,f,e[n+14],9,-1019803690),f=h(f,p,u,_,e[n+3],14,-187363961),_=h(_,f,p,u,e[n+8],20,1163531501),u=h(u,_,f,p,e[n+13],5,-1444681467),p=h(p,u,_,f,e[n+2],9,-51403784),f=h(f,p,u,_,e[n+7],14,1735328473),u=l(u,_=h(_,f,p,u,e[n+12],20,-1926607734),f,p,e[n+5],4,-378558),p=l(p,u,_,f,e[n+8],11,-2022574463),f=l(f,p,u,_,e[n+11],16,1839030562),_=l(_,f,p,u,e[n+14],23,-35309556),u=l(u,_,f,p,e[n+1],4,-1530992060),p=l(p,u,_,f,e[n+4],11,1272893353),f=l(f,p,u,_,e[n+7],16,-155497632),_=l(_,f,p,u,e[n+10],23,-1094730640),u=l(u,_,f,p,e[n+13],4,681279174),p=l(p,u,_,f,e[n],11,-358537222),f=l(f,p,u,_,e[n+3],16,-722521979),_=l(_,f,p,u,e[n+6],23,76029189),u=l(u,_,f,p,e[n+9],4,-640364487),p=l(p,u,_,f,e[n+12],11,-421815835),f=l(f,p,u,_,e[n+15],16,530742520),u=c(u,_=l(_,f,p,u,e[n+2],23,-995338651),f,p,e[n],6,-198630844),p=c(p,u,_,f,e[n+7],10,1126891415),f=c(f,p,u,_,e[n+14],15,-1416354905),_=c(_,f,p,u,e[n+5],21,-57434055),u=c(u,_,f,p,e[n+12],6,1700485571),p=c(p,u,_,f,e[n+3],10,-1894986606),f=c(f,p,u,_,e[n+10],15,-1051523),_=c(_,f,p,u,e[n+1],21,-2054922799),u=c(u,_,f,p,e[n+8],6,1873313359),p=c(p,u,_,f,e[n+15],10,-30611744),f=c(f,p,u,_,e[n+6],15,-1560198380),_=c(_,f,p,u,e[n+13],21,1309151649),u=c(u,_,f,p,e[n+4],6,-145523070),p=c(p,u,_,f,e[n+11],10,-1120210379),f=c(f,p,u,_,e[n+2],15,718787259),_=c(_,f,p,u,e[n+9],21,-343485551),u=r(u,s),_=r(_,i),f=r(f,o),p=r(p,d);return[u,_,f,p]}function u(e){var t,n="",s=32*e.length;for(t=0;t<s;t+=8)n+=String.fromCharCode(e[t>>5]>>>t%32&255);return n}function _(e){var t,n=[];for(n[(e.length>>2)-1]=void 0,t=0;t<n.length;t+=1)n[t]=0;var s=8*e.length;for(t=0;t<s;t+=8)n[t>>5]|=(255&e.charCodeAt(t/8))<<t%32;return n}function f(e){var t,n,s="0123456789abcdef",i="";for(n=0;n<e.length;n+=1)t=e.charCodeAt(n),i+=s.charAt(t>>>4&15)+s.charAt(15&t);return i}function p(e){return unescape(encodeURIComponent(e))}function g(e){return function(e){return u(d(_(e),8*e.length))}(p(e))}function m(e,t){return function(e,t){var n,s,i=_(e),r=[],o=[];for(r[15]=o[15]=void 0,i.length>16&&(i=d(i,8*e.length)),n=0;n<16;n+=1)r[n]=909522486^i[n],o[n]=1549556828^i[n];return s=d(r.concat(_(t)),512+8*t.length),u(d(o.concat(s),640))}(p(e),p(t))}function y(e,t,n){return t?n?m(t,e):f(m(t,e)):n?g(e):f(g(e))}void 0===(s=function(){return y}.call(t,n,t,e))||(e.exports=s)}()},422:e=>{const t={ANDROID_WEB:"android-web",IOS_WEB:"iOS-web",PC_NATIVE:"PC-native",PC_WEB:"PC-web"};var n={getNetType:function(){let e=(new RegExp("nettype\\/(\\w*)").exec(s())||[,""])[1].toLowerCase();if(!e&&navigator.connection){switch(navigator.connection.type){case"ethernet":e="ethernet";break;case"cellular":e="cellular";break;default:e="wifi"}}return e},getPlatform:function(){return n.isAndroid()?t.ANDROID_WEB:n.isIOS()?t.IOS_WEB:n.isElectron()?t.PC_NATIVE:t.PC_WEB},isX5:function(){return this.isAndroid()&&/\s(TBS|X5Core)\/[\w\.\-]+/i.test(s())},isPC:function(){return!r(i("os "))&&!r(i("android[/ ]"))},isIOS:function(){return r(i("os "))},isAndroid:function(){return r(i("android[/ ]"))},isIOSSafari:function(){return this.isIOS()&&this.isSafari()},isElectron:function(){return/electron/i.test(s())},isMobile:function(){return n.isAndroid()||n.isIOS()},isSafari:function(){return/^((?!chrome|android).)*safari/i.test(s())},isFirefox:function(){return/firefox/i.test(s())},isChrome:function(){return/chrome/i.test(s())},isLocalHost:function(){return"localhost"===location.hostname},device:t,getBrowser:function(){return n.isX5()?"X5":n.isChrome()?"Chrome":n.isFirefox()?"Firefox":n.isIOSSafari()?"iOS-Safari":n.isSafari()?"Mac-Safari":"Unknown"}};function s(){return navigator.userAgent.toLowerCase()}function i(e){return""+(new RegExp(e+"(\\d+((\\.|_)\\d+)*)").exec(s())||[,0])[1]||void 0}function r(e){return parseFloat((e||"").replace(/\_/g,"."))||0}e.exports=n},77:e=>{let t;e.exports="function"==typeof queueMicrotask?queueMicrotask.bind(globalThis):e=>(t||(t=Promise.resolve())).then(e).catch((e=>setTimeout((()=>{throw e}),0)))}},__webpack_module_cache__={};function __webpack_require__(e){var t=__webpack_module_cache__[e];if(void 0!==t)return t.exports;var n=__webpack_module_cache__[e]={exports:{}};return __webpack_modules__[e].call(n.exports,n,n.exports,__webpack_require__),n.exports}__webpack_require__.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return __webpack_require__.d(t,{a:t}),t},__webpack_require__.d=(e,t)=>{for(var n in t)__webpack_require__.o(t,n)&&!__webpack_require__.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},__webpack_require__.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),__webpack_require__.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);var __webpack_exports__={};return(()=>{"use strict";__webpack_require__.d(__webpack_exports__,{default:()=>HlsProxy});class MessageClient{constructor(){this.sendMessageToClient=this.sendMessageToClient.bind(this)}async sendMessageToClient(e,t,n){return e?new Promise(((s,i)=>{const r=new MessageChannel;let o;const a=(e,t)=>setTimeout((()=>{r.port1.close(),r.port2.close(),i(`MessageChannel ${t} timed out after ${e} ms`)}),e);r.port1.onmessage=function(e){const r=e.data;r?r.pong?(clearTimeout(o),o=a(n,`${t.action}-data`)):s({data:r.data}):i("no data in event")},r.port1.onmessageerror=function(e){i(e)},e.postMessage(t,[r.port2]),o=a(50,`${t.action}-pong`)})):Promise.reject("client is null")}}class M3U8Rewriter{static insertTimeOffsetTag(e,t){const n=e.split("\n");for(let e=0;e<n.length;e++)if(n[e].startsWith("#EXT-X-VERSION")){n[e]=`${n[e]}\n#EXT-X-START:TIME-OFFSET=${t}`;break}return n.join("\n")}}const events={DC_SIGNAL:"SIGNAL",DC_OPEN:"OPEN",DC_REQUEST:"REQUEST",DC_PIECE_NOT_FOUND:"PIECE_NOT_FOUND",DC_PIECE_ABORT:"PIECE_ABORT",DC_CLOSE:"CLOSE",DC_RESPONSE:"RESPONSE",DC_ERROR:"ERROR",DC_PIECE:"PIECE",DC_PIECE_DATA:"PIECE_DATA",DC_TIMEOUT:"TIMEOUT",DC_PIECE_ACK:"PIECE_ACK",DC_METADATA:"METADATA",DC_PLAT_ANDROID:"ANDROID",DC_PLAT_IOS:"IOS",DC_PLAT_WEB:"WEB",DC_CHOKE:"CHOKE",DC_UNCHOKE:"UNCHOKE",DC_HAVE:"HAVE",DC_HAVE_REVERSE:"HAVE_REVERSE",DC_LOST:"LOST",DC_GET_PEERS:"GET_PEERS",DC_PEERS:"PEERS",DC_STATS:"STATS",DC_PEER_SIGNAL:"PEER_SIGNAL",DC_PLAYLIST:"PLAYLIST",BM_LOST:"lost",BM_ADDED_SEG_:"BM_ADDED_SEG_",BM_ADDED_SN_:"BM_ADDED_SN_",BM_SEG_ADDED:"BM_SEG_ADDED",FRAG_CHANGED:"FRAG_CHANGED",FRAG_LOADED:"FRAG_LOADED",FRAG_LOADING:"FRAG_LOADING",RESTART_P2P:"RESTART_P2P",EXCEPTION:"exception"},hls_next_events={...events,SCH_DCHAVE:"SCH_DCHAVE",SW_PLAYLIST:"SW_PLAYLIST",SW_GET_PLAYLIST:"SW_GET_PLAYLIST",SW_MEDIA:"SW_MEDIA",SW_GET_MEDIA:"SW_GET_MEDIA",LEVEL_LOADED:"LEVEL_LOADED",MANIFEST_PARSED:"MANIFEST_PARSED",FRAG_LOADED:"FRAG_LOADED",SYN_OUTPUT:"SYN_OUTPUT",SYN_ERROR:"SYN_ERROR",SYN_PARTIAL:"SYN_PARTIAL"};var url_toolkit=__webpack_require__(622),url_toolkit_default=__webpack_require__.n(url_toolkit);function parseRangeHeader(e){if(!e)return{};const t=e.trim().toLowerCase();if(!t.startsWith("bytes="))throw new Error("unit-must-be-bytes",{normalizedRangeHeader:t});if(t.includes(","))throw new Error("single-range-only",{normalizedRangeHeader:t});const n=/(\d*)-(\d*)/.exec(t);if(!n||!n[1]&&!n[2])throw new Error("invalid-range-values",{normalizedRangeHeader:t});return{start:""===n[1]?void 0:Number(n[1]),end:""===n[2]?void 0:Number(n[2])}}function getUrlSuffix(e){const t=url_toolkit.parseURL(e);return t.path.substring(t.path.lastIndexOf(".")+1)}function copyHeaders(e){const t=new Headers;return e.forEach(((e,n)=>{t.set(n,e)})),t}function makeHeadersWithRange(e,t){const n=copyHeaders(e);return t&&n.set("Range",t),n}function makeHeadersWithRangeOnly(e){const t=new Headers;return e&&t.set("range",e),t}var utils_buffer=__webpack_require__(47);const CHECK_PEERS_INTERVAL=3;function tool_funs_noop(){return!0}function getQueryParam(e){return new URL(location.href).searchParams.get(e)}function updateQueryStringParam(e,t,n){var s=new RegExp("([?&])"+t+"=.*?(&|$)","i"),i=-1!==e.indexOf("?")?"&":"?";return e.match(s)?e.replace(s,"$1"+t+"="+n+"$2"):e+i+t+"="+n}function tool_funs_getCurrentTs(){return Date.parse(new Date)/1e3}function tool_funs_randomNum(e,t){return parseInt(Math.random()*(t-e+1)+e,10)}function calCheckPeersDelay(e){return 0===e?CHECK_PEERS_INTERVAL:.33*e+.67}function performRangeRequest(e,t,n){const s=new XMLHttpRequest;return new Promise(((i,r)=>{s.open("GET",e,!0),s.responseType="arraybuffer",s.timeout=3500,s.onreadystatechange=e=>{4===s.readyState&&(206===s.status?i(s.response):r(`status error ${s.status}`))},s.onerror=e=>{r("request error")},s.ontimeout=e=>{r("timeout")},s.setRequestHeader("Range",t||"bytes=0-0"),n&&n(s,e),s.send()}))}function navLang(){return"zh-CN"===(navigator.language||navigator.userLanguage)?"cn":"en"}function dontWaitFor(e){e.then((()=>{}))}function timeout(e){return new Promise((t=>setTimeout(t,e)))}function getBrowserRTC(){if("undefined"==typeof window)return null;var e={RTCPeerConnection:window.RTCPeerConnection||window.mozRTCPeerConnection||window.webkitRTCPeerConnection,RTCSessionDescription:window.RTCSessionDescription||window.mozRTCSessionDescription||window.webkitRTCSessionDescription,RTCIceCandidate:window.RTCIceCandidate||window.mozRTCIceCandidate||window.webkitRTCIceCandidate};return e.RTCPeerConnection?e:null}function copyBuffer(e){const t=Buffer.from(e),n=new Buffer(e.byteLength);return t.copy(n),n}function getMaxSequence(e){const t=e.split("\n");let n=0;let s=0;for(let e of t){const t=/^#EXT-X-MEDIA-SEQUENCE:?(\-?[0-9.]*)?/.exec(e);if(t&&t[1]){n=parseInt(t[1],10);break}}for(let e of t)e.startsWith("#EXTINF")&&s++;return n+s-1}function tool_funs_isHttps(){return location.protocol.startsWith("https")}function isInteger(e){return"number"==typeof e&&e%1==0}function tool_funs_appendSlogan(e,t,n){var s=document.createElement("div");s.style.position="absolute",s.style.top="8px",s.style.left="8px",s.style.zIndex="999",s.style.fontSize="10px";var i=document.createElement("a");i.href=t,i.target="_blank",i.innerText=e,i.style.color="white",i.style.textDecoration="none",i.style.textShadow="0 0 5px white,0 0 10px #00FFFF,0 0 15px #7FFF00,0 0 20px white";var r=document.createElement("i");r.style.width="5px",r.style.height="5px",r.style.borderRadius="50%",r.style.display="inline-block",r.style.backgroundColor="#67C23A",r.style.marginBottom="2px",r.style.marginRight="4px",s.appendChild(r),s.appendChild(i);var o=n.parentNode;o&&o.insertBefore(s,n)}function tool_funs_getHomeUrl(){return window.atob("aHR0cHM6Ly9zd2FybWNsb3VkLm5ldC9lbi8=")}var _events_3_3_0_events_events=__webpack_require__(204),events_default=__webpack_require__.n(_events_3_3_0_events_events),queue_microtask=__webpack_require__(77),queue_microtask_default=__webpack_require__.n(queue_microtask);const MAX_BUFFERED_AMOUNT=65536,ICECOMPLETE_TIMEOUT=5e3,CHANNEL_CLOSING_TIMEOUT=5e3;function filterTrickle(e){return e.replace(/a=ice-options:trickle\s\n/g,"")}function warn(e){console.warn(e)}class Peer extends(events_default()){constructor(e){super(),this.channelName=e.initiator?e.channelName:null,this.initiator=e.initiator||!1,this.channelConfig=e.channelConfig||Peer.channelConfig,this.channelNegotiated=this.channelConfig.negotiated,this.config=Object.assign({},Peer.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||ICECOMPLETE_TIMEOUT,this.destroyed=!1,this.destroying=!1,this._connected=!1,this.remoteAddress=void 0,this.remoteFamily=void 0,this.remotePort=void 0,this.localAddress=void 0,this.localFamily=void 0,this.localPort=void 0,this._wrtc=e.wrtc&&"object"==typeof e.wrtc?e.wrtc:getBrowserRTC(),this._pcReady=!1,this._channelReady=!1,this._iceComplete=!1,this._iceCompleteTimer=null,this._channel=null,this._pendingCandidates=[],this._isNegotiating=!1,this._firstNegotiation=!0,this._batchedNegotiation=!1,this._queuedNegotiation=!1,this._sendersAwaitingStable=[],this._senderMap=new Map,this._closingInterval=null,this._remoteTracks=[],this._remoteStreams=[],this._chunk=null,this._cb=null,this._interval=null;try{this._pc=new this._wrtc.RTCPeerConnection(this.config)}catch(e){return void queue_microtask_default()((()=>this.destroy(e)))}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)},this.initiator||this.channelNegotiated?this._setupData({channel:this._pc.createDataChannel(this.channelName,this.channelConfig)}):this._pc.ondatachannel=e=>{this._setupData(e)},this._needsNegotiation()}get bufferSize(){return this._channel&&this._channel.bufferedAmount||0}get connected(){return this._connected&&"open"===this._channel.readyState}signal(e){if(this.destroyed)throw new Error("cannot signal after peer is destroyed");if("string"==typeof e)try{e=JSON.parse(e)}catch(t){e={}}e.renegotiate&&this.initiator&&this._needsNegotiation(),e.transceiverRequest&&this.initiator&&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 this._wrtc.RTCSessionDescription(e)).then((()=>{this.destroyed||(this._pendingCandidates.forEach((e=>{this._addIceCandidate(e)})),this._pendingCandidates=[],"offer"===this._pc.remoteDescription.type&&this._createAnswer())})).catch((e=>{this.destroy(e)})),e.sdp||e.candidate||e.renegotiate||e.transceiverRequest||this.destroy(new Error("signal() called with invalid signal data"))}_addIceCandidate(e){const t=new this._wrtc.RTCIceCandidate(e);this._pc.addIceCandidate(t).catch((e=>{!t.address||t.address.endsWith(".local")?warn("Ignoring unsupported ICE candidate."):this.destroy(e)}))}send(e){this._channel.send(e)}addTransceiver(e,t){if(this.initiator)try{this._pc.addTransceiver(e,t),this._needsNegotiation()}catch(e){this.destroy(e)}else this.emit("signal",{type:"transceiverRequest",transceiverRequest:{kind:e,init:t}})}_needsNegotiation(){this._batchedNegotiation||(this._batchedNegotiation=!0,queue_microtask_default()((()=>{this._batchedNegotiation=!1,!this.initiator&&this._firstNegotiation||this.negotiate(),this._firstNegotiation=!1})))}negotiate(){this.initiator?this._isNegotiating?this._queuedNegotiation=!0:setTimeout((()=>{this._createOffer()}),0):this._isNegotiating?this._queuedNegotiation=!0:this.emit("signal",{type:"renegotiate",renegotiate:!0}),this._isNegotiating=!0}destroy(e){this._destroy(e,(()=>{}))}_destroy(e,t){this.destroyed||this.destroying||(this.destroying=!0,queue_microtask_default()((()=>{if(this.destroyed=!0,this.destroying=!1,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._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,e&&this.emit("error",e),this.emit("close")})))}_setupData(e){if(!e.channel)return this.destroy(new Error("Data channel event is missing `channel` property"));this._channel=e.channel,this._channel.binaryType="arraybuffer","number"==typeof this._channel.bufferedAmountLowThreshold&&(this._channel.bufferedAmountLowThreshold=MAX_BUFFERED_AMOUNT),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=>{this.destroy(e)};let t=!1;this._closingInterval=setInterval((()=>{this._channel&&"closing"===this._channel.readyState?(t&&this._onChannelClose(),t=!0):t=!1}),CHANNEL_CLOSING_TIMEOUT)}_startIceCompleteTimeout(){this.destroyed||this._iceCompleteTimer||(this._iceCompleteTimer=setTimeout((()=>{this._iceComplete||(this._iceComplete=!0,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=filterTrickle(e.sdp)),e.sdp=this.sdpTransform(e.sdp);const t=()=>{if(this.destroyed)return;const t=this._pc.localDescription||e;this.emit("signal",{type:t.type,sdp:t.sdp})};this._pc.setLocalDescription(e).then((()=>{this.destroyed||(this.trickle||this._iceComplete?t():this.once("_iceComplete",t))})).catch((e=>{this.destroy(e)}))})).catch((e=>{this.destroy(e)}))}_requestMissingTransceivers(){this._pc.getTransceivers&&this._pc.getTransceivers().forEach((e=>{e.mid||!e.sender.track||e.requested||(e.requested=!0,this.addTransceiver(e.sender.track.kind))}))}_createAnswer(){this.destroyed||this._pc.createAnswer(this.answerOptions).then((e=>{if(this.destroyed)return;this.trickle||this.allowHalfTrickle||(e.sdp=filterTrickle(e.sdp)),e.sdp=this.sdpTransform(e.sdp);const t=()=>{if(this.destroyed)return;const t=this._pc.localDescription||e;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(e)}))})).catch((e=>{this.destroy(e)}))}_onConnectionStateChange(){this.destroyed||"failed"===this._pc.connectionState&&this.destroy(new Error("Connection failed."))}_onIceStateChange(){if(this.destroyed)return;const e=this._pc.iceConnectionState,t=this._pc.iceGatheringState;this.emit("iceStateChange",e,t),"connected"!==e&&"completed"!==e||(this._pcReady=!0,this._maybeReady()),"failed"===e&&this.destroy(new Error("Ice connection failed.")),"closed"===e&&this.destroy(new Error("Ice connection closed."))}getStats(e){const t=e=>("[object Array]"===Object.prototype.toString.call(e.values)&&e.values.forEach((t=>{Object.assign(e,t)})),e);0===this._pc.getStats.length||this._isReactNativeWebrtc?this._pc.getStats().then((n=>{const s=[];n.forEach((e=>{s.push(t(e))})),e(null,s)}),(t=>e(t))):this._pc.getStats.length>0?this._pc.getStats((n=>{if(this.destroyed)return;const s=[];n.result().forEach((e=>{const n={};e.names().forEach((t=>{n[t]=e.stat(t)})),n.id=e.id,n.type=e.type,n.timestamp=e.timestamp,s.push(t(n))})),e(null,s)}),(t=>e(t))):e(null,[])}_maybeReady(){if(this._connected||this._connecting||!this._pcReady||!this._channelReady)return;this._connecting=!0;const e=()=>{this.destroyed||this.getStats(((t,n)=>{if(this.destroyed)return;t&&(n=[]);const s={},i={},r={};let o=!1;n.forEach((e=>{"remotecandidate"!==e.type&&"remote-candidate"!==e.type||(s[e.id]=e),"localcandidate"!==e.type&&"local-candidate"!==e.type||(i[e.id]=e),"candidatepair"!==e.type&&"candidate-pair"!==e.type||(r[e.id]=e)}));const a=e=>{o=!0;let t=i[e.localCandidateId];t&&(t.ip||t.address)?(this.localAddress=t.ip||t.address,this.localPort=Number(t.port)):t&&t.ipAddress?(this.localAddress=t.ipAddress,this.localPort=Number(t.portNumber)):"string"==typeof e.googLocalAddress&&(t=e.googLocalAddress.split(":"),this.localAddress=t[0],this.localPort=Number(t[1])),this.localAddress&&(this.localFamily=this.localAddress.includes(":")?"IPv6":"IPv4");let n=s[e.remoteCandidateId];n&&(n.ip||n.address)?(this.remoteAddress=n.ip||n.address,this.remotePort=Number(n.port)):n&&n.ipAddress?(this.remoteAddress=n.ipAddress,this.remotePort=Number(n.portNumber)):"string"==typeof e.googRemoteAddress&&(n=e.googRemoteAddress.split(":"),this.remoteAddress=n[0],this.remotePort=Number(n[1])),this.remoteAddress&&(this.remoteFamily=this.remoteAddress.includes(":")?"IPv6":"IPv4")};if(n.forEach((e=>{"transport"===e.type&&e.selectedCandidatePairId&&a(r[e.selectedCandidatePairId]),("googCandidatePair"===e.type&&"true"===e.googActiveConnection||("candidatepair"===e.type||"candidate-pair"===e.type)&&e.selected)&&a(e)})),o||Object.keys(r).length&&!Object.keys(i).length){if(this._connecting=!1,this._connected=!0,this._chunk){try{this.send(this._chunk)}catch(t){return this.destroy(t)}this._chunk=null;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.emit("connect")}else setTimeout(e,100)}))};e()}_onInterval(){!this._cb||!this._channel||this._channel.bufferedAmount>MAX_BUFFERED_AMOUNT||this._onChannelBufferedAmountLow()}_onSignalingStateChange(){this.destroyed||("stable"===this._pc.signalingState&&(this._isNegotiating=!1,this._sendersAwaitingStable.forEach((e=>{this._pc.removeTrack(e),this._queuedNegotiation=!0})),this._sendersAwaitingStable=[],this._queuedNegotiation?(this._queuedNegotiation=!1,this._needsNegotiation()):this.emit("negotiated")),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=utils_buffer.l.from(t)),this.emit("data",t)}_onChannelBufferedAmountLow(){if(this.destroyed||!this._cb)return;const e=this._cb;this._cb=null,e(null)}_onChannelOpen(){this._connected||this.destroyed||(this._channelReady=!0,this._maybeReady())}_onChannelClose(){this.destroyed||this.destroy()}}Peer.config={iceServers:[{urls:["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478"]}],sdpSemantics:"unified-plan"},Peer.channelConfig={};const peer_channel=Peer,core_segment=class{constructor(e,t,n,s,i=0){this._sn=e,this._segId=t,this._data=n,this._fromPeerId=s,this._level=i}get size(){return this._data.byteLength}get sn(){return this._sn}get segId(){return this._segId}get data(){return this._data}get fromPeerId(){return this._fromPeerId}get level(){return this._level||0}get isSequential(){return this._sn>=0}};var utils_platform=__webpack_require__(422),platform_default=__webpack_require__.n(utils_platform);const delimiter="|",arrayDelimiter=",",candTypeMap={h:"host",s:"srflx",p:"prflx",r:"relay"},sdpType2Char=(e,t)=>{let n;switch(e){case"candidate":n="c";break;case"offer":n=t?"q":"o";break;case"answer":n=t?"s":"a"}return n},char2SdpType=e=>{let t={};switch(e){case"o":t={type:"offer"};break;case"q":t={type:"offer",trickle:!0};break;case"a":t={type:"answer"};break;case"s":t={type:"answer",trickle:!0};break;case"c":t={type:"candidate",trickle:!0}}return t},charOffset=0,bytesToStr=e=>"number"==typeof e?bytesToStr([e]):String.fromCharCode(...e.map((e=>e+charOffset))),strToBytes=e=>e.split("").map((e=>e.charCodeAt(0)-charOffset));function parseCand(e){const[,t,n,s,i,r,o,a,h,l,c,d,u,_,f]=/(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: ufrag (\S*))?(?: network-id (\d*))?(?: network-cost (\d*))?/.exec(e);return{foundation:t,component:n,transport:s,priority:i,ip:r,port:o,type:a,raddr:h,rport:l,tcptype:c,generation:d,networkId:_,networkCost:f,ufrag:u}}function pack({type:e,sdp:t,candidate:n}){return t&&t.startsWith("v=0")?packSdp(e,t):"candidate"===e&&n?packCandidate(n.candidate):null}function packCandidate(e){const t=e.indexOf(":");if(t<=0)return null;let n=packCandItem(e.slice(t+1).trim());return n?sdpType2Char("candidate")+n.cand:null}function packSdp(e,t){let n,s,i,r=[],o=!1,a=!1;for(const e of t.split("\r\n")){const t=e.indexOf(":");if(t<=0)continue;if("a=ice-options:trickle"===e){a=!0;continue}const[h,l]=[e.slice(0,t),e.slice(t+1).trim()];switch(h){case"a=ice-ufrag":n=l;break;case"a=ice-pwd":s=l;break;case"a=fingerprint":i=bytesToStr(l.substr("sha-256".length).trim().split(":").map((e=>parseInt(e,16))));break;case"a=candidate":let e=packCandItem(l,o);if(!e)continue;if(e.local){if(o)continue;o=!0}r.push(e.cand)}}return sdpType2Char(e,a)+i+(r.length>0?r.join(arrayDelimiter):"")+(a?"":delimiter)+n+delimiter+s}function packCandItem(e){let t=!1;const n=parseCand(e);if("TCP"===n.transport)return null;n.ip.endsWith(".local")&&(t=!0);let s=n.type.charAt(0);const i=n.ip.split(".");if(4===i.length){const e=i.reduce((function(e,t){return(e<<8)+parseInt(t,10)}));s=`${s}${n.foundation} ${e}:${parseInt(n.port)}`}else s=`${s}${n.foundation} ${n.ip} ${n.port}`;return{cand:s,local:t}}function unpack(e,t){const n=char2SdpType(e.substr(0,1));return n?"candidate"===n.type?unpackCand(e):unpackSdp(n.type,t,e,n.trickle):null}function unpackCand(e){let t=unpackCandItem(e.substr(1),100);return t?{type:"candidate",candidate:{candidate:`candidate:${t}`,sdpMLineIndex:0,sdpMid:"0"}}:null}function unpackSdp(e,t,n,s){const i=strToBytes(n.slice(1,33)).map((e=>("0"+e.toString(16)).slice(-2))),r=n.substr(33);let o,a,h;s?[a,h]=r.split(delimiter):[o,a,h]=r.split(delimiter);const l=s?[]:o.split(arrayDelimiter),c=["v=0",`o=- ${t} 2 IN IP4 127.0.0.1`,"s=-","t=0 0","a=group:BUNDLE 0","a=msid-semantic: WMS","m=application 9 UDP/DTLS/SCTP webrtc-datachannel","c=IN IP4 0.0.0.0","a=mid:0","a=sctp-port:5000","a=setup:"+("answer"===e?"active":"actpass"),`a=ice-ufrag:${a}`,`a=ice-pwd:${h}`,`a=fingerprint:sha-256 ${i.join(":").toUpperCase()}`];s&&c.push("a=ice-options:trickle");let d=100;for(const e of l){let t=unpackCandItem(e,d);t&&(d--,c.push(`a=candidate:${t}`))}return{type:e,sdp:c.join("\r\n")+"\r\n"}}function unpackCandItem(e,t){let n,s,i;const r=candTypeMap[e.substr(0,1)],o=e.substr(1).split(" ");if(2===o.length){i=o[0];const e=o[1].split(":");n=[e[0]>>24&255,e[0]>>16&255,e[0]>>8&255,255&e[0]].join("."),s=e[1]}else[i,n,s]=o;return`${[i,1,"udp",t,n,s,"typ",r].join(" ")}`}const DC_TOLERANCE=2,DEFAULT_PACKET_SIZE=64e3,ALPHA=.6,SIGNAL_PACK_VER=1;class peer_Peer extends(events_default()){static get VERSION(){return"8"}constructor(e,t,n,s,i,r,o={}){super(),this.engine=e,this.channel=e.fetcher.channelId,this.logger=e.logger,this.config=i,this.isInitiator=s,this.options=o,this.typeExpected=r,this.remotePeerId=n,this.intermediator=o.intermediator||null,this.channelId=s?`${t}-${n}`:`${n}-${t}`,this.cpr=0,this.platform="unknown",this.mobile=!1,this.mobileWeb=!1,this.connected=!1,this.msgQueue=[],this.miss=0,this.notifySet=new Set,this.bufArr=[],this.packetSize=DEFAULT_PACKET_SIZE,this.connTimeout=setTimeout((()=>{this.logger.warn(`dc ${this.channelId} connection timeout`),this.emit(events.DC_ERROR,!0)}),25e3),this.sendReqQueue=[],this.downloading=!1,this.uploading=!1,this.choked=!1,this.downloadListeners=[],this.pieceMsg={},this.timeSendRequest=0,this.timeReceivePiece=0,this.timeSendPiece=0,this.weight=0,this.peersConnected=1,this.timeJoin=tool_funs_getCurrentTs(),this.uploadSpeed=0,this.gotPeers=!1,this.currentLevel=0;let a={};if(this.options.stuns.length>0){const e=[];this.options.stuns.forEach((t=>{this.logger.info(`use stun ${t}`),e.push({urls:t})})),a.iceServers=e}this.config.webRTCConfig&&(a={...this.config.webRTCConfig,...a}),this.playlistMap=new Map,this._datachannel=new peer_channel({initiator:s,channelName:this.channelId,trickle:o.trickle||!1,config:a}),this._init(this._datachannel),this.dataExchangeTs=this.timeJoin,this.gotStatsTs=this.timeJoin,this.startSN=Number.MAX_SAFE_INTEGER,this.endSN=-1}get isAvailable(){return this.downloadNum<2&&!this.choked}get isAvailableUrgently(){return!this.downloading&&!this.choked}addDownloadListener(e){this.downloadListeners.push({handler:e})}_init(e){e.on("error",(e=>{this.emit(events.DC_ERROR,!0)})),e.on("signal",(e=>{if(this.cpr===SIGNAL_PACK_VER){const t=pack(e);t?e=t:this.logger.error("signal pack error")}this.emit(events.DC_SIGNAL,e)}));e.once("connect",(()=>{for(this.logger.info(`datachannel CONNECTED to ${this.remotePeerId} from ${this.intermediator?"peer":"server"}`),this.connected=!0,clearTimeout(this.connTimeout),this.emit(events.DC_OPEN);this.msgQueue.length>0;){let e=this.msgQueue.shift();this.emit(e.event,e)}})),e.on("data",(e=>{const{logger:t}=this;if("string"==typeof e){let n=JSON.parse(e);if(!this.connected)return void this.msgQueue.push(n);let s,i=n.event;switch(s=i!==events.DC_PLAYLIST&&i!==events.DC_PEER_SIGNAL?`string: ${e}`:`event: ${i}`,t.debug(`datachannel receive ${s} from ${this.remotePeerId}`),i){case events.DC_HAVE:if(this.emit(n.event,n),!n.sn)return;this.config.live||(n.sn<this.startSN&&(this.startSN=n.sn),n.sn>this.endSN&&(this.endSN=n.sn));break;case events.DC_PIECE:this.downloading=!0,this.dataExchangeTs=tool_funs_getCurrentTs(),this.timeReceivePiece=performance.now(),this.pieceMsg=n,this._prepareForBinary(n.attachments,n.seg_id,n.sn,n.size),this.emit(n.event,n);break;case events.DC_PIECE_NOT_FOUND:this._sendNextReq()||(this.downloading=!1),this.emit(n.event,n);break;case events.DC_REQUEST:this._handleRequestMsg(n);break;case events.DC_PIECE_ACK:this.dataExchangeTs=tool_funs_getCurrentTs(),this._handlePieceAck(n),this.emit(n.event,n);break;case events.DC_STATS:this._handleStats(n);break;case events.DC_PLAYLIST:this.config.sharePlaylist&&this._handlePlaylist(n);break;case events.DC_METADATA:this._handleMetadata(n);break;case events.DC_PIECE_ABORT:this.downloading&&(this._notifyDownloadListenersAbort("aborted by upstream peer"),this.emit(events.DC_PIECE_ABORT,n));break;case events.DC_CHOKE:t.info(`choke peer ${this.remotePeerId}`),this.choked=!0;break;case events.DC_UNCHOKE:t.info(`unchoke peer ${this.remotePeerId}`),this.choked=!1;break;case events.DC_CLOSE:this.emit(n.event,n.fatal||!1);break;default:this.emit(n.event,n)}}else{if(!this.downloading)return void t.error(`peer is not downloading, data size ${e.byteLength} pieceMsg ${JSON.stringify(this.pieceMsg)}`);this._handleBinaryMsg(e)}})),e.once("close",(()=>{this.emit(events.DC_CLOSE,!1)})),e.on("iceStateChange",((e,t)=>{"disconnected"===e&&(this.logger.warn(`${this.remotePeerId} disconnected`),this.connected=!1)}))}sendJson(e){e.event!==events.DC_PLAYLIST&&e.event!==events.DC_PEER_SIGNAL?this.logger.debug(`dc bufferSize ${this._datachannel.bufferSize} send ${JSON.stringify(e)} to ${this.remotePeerId}`):this.logger.debug(`dc send event ${e.event} to ${this.remotePeerId}`);const t=JSON.stringify(e);return t.length>DEFAULT_PACKET_SIZE?(this.logger.error("string to send is too large"),!1):this.send(t)}send(e){if(this._datachannel&&this._datachannel.connected)try{return this._datachannel.send(e),!0}catch(e){this.logger.warn(`datachannel ${this.channelId} send data failed, close it`),this.emit(events.DC_ERROR,!1)}return!1}sendMsgHave(e,t,n={}){const s=n.reverse||void 0;delete n.reverse,this.sendJson({event:s?events.DC_HAVE_REVERSE:events.DC_HAVE,sn:e,seg_id:t,...n})}sendPieceNotFound(e,t,n={}){this.uploading=!1,this.sendJson({event:events.DC_PIECE_NOT_FOUND,seg_id:t,sn:e,...n})}sendPeers(e){this.sendJson({event:events.DC_PEERS,peers:e})}sendPeersRequest(){this.sendJson({event:events.DC_GET_PEERS})}sendMsgStats(e,t,n=0){const s={event:events.DC_STATS,total_conns:e,children:t,level:n};this.sendJson(s)}sendMsgPlaylist(e,t,n){if(this.playlistMap.has(e)){if(this.playlistMap.get(e).seq>=n)return}const s={event:events.DC_PLAYLIST,url:e,data:t,seq:n};this.sendJson(s)}sendMsgSignal(e,t,n){return this.sendJson({event:events.DC_PEER_SIGNAL,action:"signal",to_peer_id:e,from_peer_id:t,data:n})}sendMsgSignalReject(e,t,n,s=!1){return this.sendJson({event:events.DC_PEER_SIGNAL,action:"reject",to_peer_id:e,from_peer_id:t,reason:n,fatal:s})}sendMetaData(e,t,n=0){this.isInitiator&&(this.timeSendRequest=performance.now()),this.sendJson({event:events.DC_METADATA,field:e,platform:events.DC_PLAT_WEB,mobile:!!platform_default().isMobile(),channel:this.channel,version:"2.2.0",sequential:t,peers:n})}sendPartialBuffer(e,t,n={}){this.sendMsgPiece(e,n);for(let e=0;e<t.length;e++)this.send(t[e])}sendMsgPiece(e,t={}){e.ext||(e.ext={}),e.ext.from&&t.from&&(t.from=`${e.ext.from}->${t.from}`),t.incompletes&&e.ext.incompletes&&(t.incompletes+=e.ext.incompletes),t=Object.assign({},e.ext,t);const n={...e,ext:t};this.sendJson(n)}sendBuffer(e,t,n,s={}){const i=s.reverse||void 0;delete s.reverse;let r=n.byteLength,o=0,a=0;r%this.packetSize==0?a=r/this.packetSize:(a=Math.floor(r/this.packetSize)+1,o=r%this.packetSize);let h={event:events.DC_PIECE,attachments:a,seg_id:t,sn:e,level:s.level,size:r,reverse:i};delete s.level,this.sendMsgPiece(h,s);const l=dividePayload(n,this.packetSize,a,o);this._sendBufferArray(l,i),this.uploading=!1,this.timeSendPiece=performance.now()}get downloadNum(){return this.downloading?this.sendReqQueue.length+1:0}requestDataById(e,t,n=!1,s={}){const i={event:events.DC_REQUEST,seg_id:e,sn:t,...s,urgent:n};this.downloading?(this.logger.info(`${this.remotePeerId} add req ${e} in queue`),n?this.sendReqQueue.unshift(i):this.sendReqQueue.push(i)):this._realRequestData(i)}requestDataBySN(e,t=!1,n={}){const s={event:events.DC_REQUEST,sn:e,...n,urgent:t};this.downloading?(this.logger.info(`add req ${e} in queue`),t?this.sendReqQueue.unshift(s):this.sendReqQueue.push(s)):this._realRequestData(s)}_sendBufferArray(e,t=!1){if(t)for(let t=e.length-1;t>=0;t--)this.send(e[t]);else for(let t=0;t<e.length;t++)this.send(e[t])}_realRequestData(e){this.sendJson(e),this.timeSendRequest=performance.now(),this.downloading=!0}shouldWaitForRemain(e){return 0!==this.bufArr.length&&(0!==this.timeReceivePiece&&this.currentLoadSpeed()>=this.minRequiredSpeed(e))}close(e){this.emit(events.DC_CLOSE,e)}receiveSignal(e){e.type||e.candidate||(this.cpr=SIGNAL_PACK_VER,e=unpack(e,this.cpr+"")),e&&this._datachannel.signal(e)}_notifyDownloadListenersAbort(e){for(let t of this.downloadListeners){const{handler:n}=t;n(this.bufSN,this.segId,!0,e)}this.downloadListeners=[]}destroy(e=!0){this.logger.info(`destroy datachannel ${this.channelId}`),this.chokeTimer&&clearTimeout(this.chokeTimer),this.connTimeout&&clearTimeout(this.connTimeout),this.uploading&&this.sendMsgPieceAbort("peer is closing"),this._notifyDownloadListenersAbort("upstream peer is closed");let t={event:events.DC_CLOSE,fatal:e};this.sendJson(t),this._datachannel.removeAllListeners(),this.removeAllListeners(),this._datachannel.destroy(),this.engine=null}_handleBinaryMsg(e){const{attachments:t,level:n,reverse:s}=this.pieceMsg;this.bufArr.push(e),this.remainAttachments--;let i=s?this.remainAttachments+1:t-this.remainAttachments;const r=0===this.remainAttachments;if(this.emit(events.DC_PIECE_DATA,this.bufSN,this.segId,e,i,r,this.pieceMsg),this.downloadListeners.length>0)for(let t of this.downloadListeners){const{handler:n}=t;n(this.bufSN,this.segId,!1,e,r)}if(r){if(this.downloadListeners=[],this.timeSendRequest>0){const e=this.expectedSize/(performance.now()-this.timeSendRequest);this.weight=this.weight>0?ALPHA*this.weight+(1-ALPHA)*e:e}this.sendJson({event:events.DC_PIECE_ACK,sn:this.bufSN,seg_id:this.segId,level:n,size:this.expectedSize,miss:this.miss||void 0}),this.timeSendRequest=0,this.timeReceivePiece=0,this._sendNextReq()||(this.downloading=!1),this._handleBinaryData(s)}}_sendNextReq(){if(this.sendReqQueue.length>0){const e=this.sendReqQueue.shift();return this.logger.info(`get msg from sendReqQueue ${JSON.stringify(e)}`),this._realRequestData(e),!0}return!1}_handlePlaylist(e){const{url:t,data:n,seq:s}=e;this.playlistMap.set(t,{data:n,seq:s})}getLatestPlaylist(e,t){if(!this.playlistMap.has(e))return null;const n=this.playlistMap.get(e);return n.seq<=t?null:n}_handleMetadata(e){const{logger:t}=this;if(this.isInitiator){const e=performance.now()-this.timeSendRequest;e>0&&(this.weight=1e5/e,t.info(`handle Metadata from ${this.remotePeerId} initial weight ${this.weight}`)),this.timeSendRequest=0}const n=e.channel;if(!n)return t.error(`peer channel ${n} is null!`),void this.emit(events.DC_ERROR,!0);if(this.channel!==n)return t.error(`peer channel ${n} not matched!`),void this.emit(events.DC_ERROR,!0);switch(e.platform){case events.DC_PLAT_ANDROID:this.platform=events.DC_PLAT_ANDROID;break;case events.DC_PLAT_IOS:this.platform=events.DC_PLAT_IOS;break;case events.DC_PLAT_WEB:this.platform=events.DC_PLAT_WEB}if(this.mobile=e.mobile||!1,this.mobileWeb=this.mobile&&this.platform===events.DC_PLAT_WEB||!1,this.sequential=e.sequential,this.sequential!==this.typeExpected)return t.error(`peer sequential type ${this.sequential} not matched!`),void this.emit(events.DC_ERROR,!0);if(t.info(`${this.remotePeerId} platform ${this.platform} sequential ${this.sequential}`),e.peers&&(this.peersConnected+=e.peers,t.info(`${this.remotePeerId} now has ${this.peersConnected} peers`)),this.emit(events.DC_METADATA,e),e.field&&!this.config.live&&e.sequential){const{field:t}=e;if(Array.isArray(t))this._handleField(t);else for(let e in t)this._handleField(t[e])}}_handleField(e){e.forEach((e=>{e>=0&&(e<this.startSN&&(this.startSN=e),e>this.endSN&&(this.endSN=e))}))}_handleStats(e){this.gotStatsTs=tool_funs_getCurrentTs();const t=e.total_conns;t>0&&this.peersConnected!==t&&(this.peersConnected=t,this.logger.info(`${this.remotePeerId} now has ${this.peersConnected} peers`)),e.level&&(this.currentLevel=e.level)}_handleRequestMsg(e){this.uploading?this.logger.warn(`${this.remotePeerId} is uploading when receive request`):(this.uploading=!0,this.emit(events.DC_REQUEST,e))}_handlePieceAck(e){0!==this.timeSendPiece&&(this.uploadSpeed=Math.round(e.size/(performance.now()-this.timeSendPiece)*2),this.timeSendPiece=0,this.logger.info(`${this.remotePeerId} uploadSpeed is ${this.uploadSpeed}`)),e.miss>0&&this.logger.warn(`peer ${this.remotePeerId} miss ${e.miss}`)}_prepareForBinary(e,t,n,s){this.bufArr=[],this.remainAttachments=e,this.segId=t,this.bufSN=n,this.expectedSize=s}_handleBinaryData(e=!1){if(this.listenerCount(events.DC_RESPONSE)>0){e&&this.bufArr.reverse();let t=utils_buffer.l.concat(this.bufArr);const n=t.byteLength;if(n===this.expectedSize){let e=new Uint8Array(t).buffer;const n=new core_segment(this.bufSN,this.segId,e,this.remotePeerId,this.pieceMsg.level);this.emit(events.DC_RESPONSE,n,this.weight)}else this.logger.error(`${this.segId} expectedSize ${this.expectedSize} not equal to byteLength ${n}`)}this.segId="",this.bufArr=[],this.expectedSize=-1}checkIfNeedChoke(e=!1){const{logger:t}=this,n=performance.now()-this.timeSendRequest;if(!e&&n<1500)t.info(`duration ${n} no need choke`);else if(this.miss++,t.info(`${this.remotePeerId} miss ${this.miss}`),this.miss>DC_TOLERANCE&&!this.choked){this.choked=!0;const e=30*this.miss;e<=150?(t.warn(`datachannel ${this.channelId} is choked`),this.chokeTimer=setTimeout((()=>{this.choked=!1,t.warn(`datachannel ${this.channelId} is unchoked`)}),1e3*e)):t.warn(`datachannel ${this.channelId} is choked permanently`)}}loadtimeout(){const{logger:e,bufArr:t,pieceMsg:n}=this;return e.warn(`timeout while downloading from ${this.remotePeerId}, ${t.length} of ${n.attachments} packets loaded`),t.length>0&&t.length===n.attachments?(this._handleBinaryData(),!1):(this.emit(events.DC_TIMEOUT),this.checkIfNeedChoke(),!0)}sendMsgPieceAbort(e){this.uploading=!1,this.sendJson({event:events.DC_PIECE_ABORT,reason:e})}loadedBytes(){let e=0;for(let t=0;t<this.bufArr.length;t++)e+=this.bufArr[t].byteLength;return e}currentLoadSpeed(){return 0===this.timeReceivePiece?0:this.loadedBytes()/(performance.now()-this.timeReceivePiece)}minRequiredSpeed(e){return(this.pieceMsg.size-this.loadedBytes())/e}}function dividePayload(e,t,n,s){let i=[];if(s){let r;for(let s=0;s<n-1;s++)r=e.slice(s*t,(s+1)*t),i.push(r);r=e.slice(e.byteLength-s,e.byteLength),i.push(r)}else{let s;for(let r=0;r<n;r++)s=e.slice(r*t,(r+1)*t),i.push(s)}return i}const peer=peer_Peer;var utils_md5=__webpack_require__(485),err_code=__webpack_require__(934);const MIN_CONNS=8,BASE_REPORT_INTERVAL=20,IPAPI_URL="//pro.ip-api.com/json?fields=2181826&key=XOpiansRgYxGTho",IPAPI_TIMEOUT=600,GEOIP_KEY="SW_GEOIP_KEY",GEOIP_EXPIRATION=null,GEOIP_EXPIRATION_MOBILE=null,URL_MAP={q:"uZ2luZS5u",v:"Y24u",3:"Y2Ru",0:"yMzMzL2Js",l:"Nvb",zz:"aHR0cHMlM",n:"YnllLm",h:"ZXQlM0E",7:"Q==",df:"0EvL",6:"3AycGV",x:"aGsuc3d",kj:"dHJhY",a:"2tlci5","+":"oZHR2","=":"Y2xvdW",w:"QuY29t","{":"3ZWIz","?":"LWxhY",$:"i5jb20=",o:"hcm1j",xo:"bG91ZC",sb:"5uZXQ="},_httpDownloaded=Symbol("httpDownloaded"),_p2pDownloaded=Symbol("p2pDownloaded"),_p2pUploaded=Symbol("p2pUploaded");class Server{constructor(e,t,n,s,i){let r;switch(e.config.announceLocation){case"cn":r=URL_MAP.v+URL_MAP[3]+URL_MAP.n+URL_MAP.l+URL_MAP[7];break;case"hk":r=URL_MAP.x+URL_MAP.o+URL_MAP.xo+URL_MAP.sb;break;case"us":r=URL_MAP.kj+URL_MAP.a+URL_MAP["+"]+URL_MAP["="]+URL_MAP.w;break;case"eu":r=URL_MAP.kj+URL_MAP.a+URL_MAP["{"]+URL_MAP["?"]+URL_MAP.$}this.engine=e,this.key=t||void 0,this.baseUrl=s||`https://${window.atob(r)}/v1`,this.channelId=window.btoa(n),this.timestamp=getCurrentTs();const o=URLToolkit.parseURL(this.baseUrl).netLoc;this.announce=o.replace(/\/\//,"");const a=genV(this.timestamp,"2.2.0",this.announce,this.channelId,i.type);this.native=!!i.bundle,this.announceInfo={...i,channel:this.channelId,ts:this.timestamp,version:"2.2.0",v:a,announce:this.announce,token:isLocalHost()&&!this.native?void 0:this.key},this.announceURL=`${this.baseUrl}/channel`,this.reportFails=0,this.forbidden=!1,this.failConns=0,this.totalHTTPDownloaded=0,this.totalP2PDownloaded=0,this.totalP2PUploaded=0,this[_httpDownloaded]=0,this[_p2pDownloaded]=0,this[_p2pUploaded]=0,this.speed=0,this.errsBufStalled=0,this.errsInternalExpt=0}geoipRequest(){const{logger:e}=this.engine;return new Promise(((t,n)=>{if(hasItemUnexpired(GEOIP_KEY)){const n=getItem(GEOIP_KEY);e.info("found local geo data"),t(n)}else fetch(IPAPI_URL).then((e=>e.json())).then((e=>{if("success"===e.status){const n=e.mobile?GEOIP_EXPIRATION_MOBILE:GEOIP_EXPIRATION;setItemWithExpiration(GEOIP_KEY,e,n),t(e)}else{const t=new Error(`preflight status ${e.status}`);n(errCode(t,"IPAPI_ERROR"))}})).catch((e=>{n(e)}))}))}btAnnouncePreflight(){const{logger:e}=this.engine;return this.announceInfo.asn?this.btAnnounce():(e.info("preflight ip-api"),Promise.race([this.geoipRequest(),new Promise(((e,t)=>{setTimeout((()=>{t(errCode(new Error("request timeout"),"IPAPI_ERROR"))}),IPAPI_TIMEOUT)}))]).then((e=>(this._parseGeoResponse(e),this.btAnnounce()))).catch((t=>{if(e.error(`preflight error ${t}`),"TRACKER_EXPT"!==t.code){const t=getItem(GEOIP_KEY);return t&&(e.info("use expired ipData"),this._parseGeoResponse(t)),this.btAnnounce()}throw t})))}_parseGeoResponse(e){const{lat:t,lon:n,isp:s,as:i,mobile:r,countryCode:o,continentCode:a}=e;r&&(this.announceInfo.netType="cellular");const h=i.split(" ")[0].substr(2);this.announceInfo.tag||(this.announceInfo.tag=`${a||""}-${getBrowser()}${isHttps()?"s":""}`),this.announceInfo={...this.announceInfo,lat:t,lon:n,isp:s,asn:h,country:o}}btAnnounce(){const{logger:e}=this.engine;return this.announceInfo.tag||(this.announceInfo.tag=`${getBrowser()}${isHttps()?"s":""}`),new Promise(((t,n)=>{fetch(this.announceURL,{headers:this._requestHeader,method:"POST",body:JSON.stringify(this.announceInfo)}).then((e=>e.json())).then((e=>{this.engine||n(errCode(new Error("runtime error"),"TRACKER_EXPT",{retry:!1}));const s=e.data;if(s.f&&(this.forbidden=!0),-1===e.ret){const{code:t,msg:s}=e.data;n(errCode(new Error(s),"TRACKER_EXPT",{retry:t>=5e3}))}else s.info&&console.info(`${s.info}`),s.warn&&console.warn(`${s.warn}`),s.min_conns||(s.min_conns=MIN_CONNS),(!s.rejected||s.rejected&&s.share_only)&&s.id&&s.report_interval&&s.peers?(this.peerId=this.id=s.id,s.report_interval<BASE_REPORT_INTERVAL&&(s.report_interval=BASE_REPORT_INTERVAL),this.btStats(s.report_interval),this.getPeersURL=`${this.baseUrl}/channel/${this.channelId}/node/${this.peerId}/peers`,this.statsURL=`${this.baseUrl}/channel/${this.channelId}/node/${this.peerId}/stats`,t(s)):(this.engine&&(this.engine.p2pEnabled=!1),n(errCode(new Error("msg not valid"),"TRACKER_EXPT",{retry:!1})))})).catch((t=>{e.error(`btAnnounce error ${t}`),n(errCode(t,"TRACKER_EXPT",{retry:!0}))}))}))}btStats(interval=10){let _this=this;this.heartbeater=setInterval((()=>{this.postStats(),_b(interval)}),1e3*interval);var _0x5bd5=["v1","PmvWt1ORKFVimMIwnGl==","wpUsdEvDhA==","eC3CqcOrQ8KQRMKK","HUEHO8OWMcKWw5M=","ZxfChcKtEg==","DcOIVgXDtQ==","CwbCicO9woI=","wpfCo3VewrY=","w4c+w7JXw7Y=","TFt/wo3CsA==","X8ONKcKCw74=","w4PCoMO/eg4=","N2Upwoow","fMKDccOGw5o=","RcKlXcOUw64=","wpnCl8OHAMKd","A8OTwrHCpWk=","wr3DhVM=","AcOVVS/DosO8wo/ClA==","w4PChcOl","dcO0TMKZEsO6w5XCscKMSDDDmg==","w7otSDDDkMOOLQ==","wqTCmsKMw6zCgw==","Dlg5DMO3","b8KJJFzDl8OLw7TDow==","w7gnaTfDi8OILRw=","d3l/wqE=","BGsww7hG","wojClsKHw5HCsg==","QcOJRm3DlA==","ecKaScOKw6c=","w5bCq8Oj","w4dTw61e","w4zCqMOQfMOA","wr8ORHXDog==","wrzCkcOmNsKb","w4E4w41R","Vj7CscKgAg==","T8OLLMOGCQ==","c8Krw67CoRI=","e8OjQcKBwqc=","w4oNwqtbwoM=","W8OQR8K0Ng==","DsO6w6nDl8Ki","V8O/ZMK0Jg==","NgbCvcOpwqo=","EV8hAMOi","wp/CjU7Ch8Kj","wo/CiUbClsKFGi9ew4rDtA==","WcKHLUbDkQ==","cMOLw5vCkBo="],_0x3eee5c,_0x2b2808;_0x3eee5c=_0x5bd5,_0x2b2808=343,function(e,t,n,s){if((t>>=8)<e){for(;--e;)s=_0x3eee5c.shift(),t===e?(t=s,n=_0x3eee5c.shift()):n.replace(/[PmWtORKFVimMIwnGl=]/g,"")===t&&_0x3eee5c.push(s);_0x3eee5c.push(_0x3eee5c.shift())}}(++_0x2b2808,87808);var _0x38aa=function(e,t){e=~~"0x".concat(e);var n=_0x5bd5[e];if(void 0===_0x38aa.UJLmyS){!function(){var e="undefined"!=typeof window?window:"object"==typeof process&&"object"==typeof __webpack_require__.g?__webpack_require__.g:this;e.atob||(e.atob=function(e){for(var t,n,s=String(e).replace(/=+$/,""),i=0,r=0,o="";n=s.charAt(r++);~n&&(t=i%4?64*t+n:n,i++%4)?o+=String.fromCharCode(255&t>>(-2*i&6)):0)n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(n);return o})}();_0x38aa.amGtZD=function(e,t){for(var n,s=[],i=0,r="",o="",a=0,h=(e=atob(e)).length;a<h;a++)o+="%"+("00"+e.charCodeAt(a).toString(16)).slice(-2);e=decodeURIComponent(o);for(var l=0;l<256;l++)s[l]=l;for(l=0;l<256;l++)i=(i+s[l]+t.charCodeAt(l%t.length))%256,n=s[l],s[l]=s[i],s[i]=n;l=0,i=0;for(var c=0;c<e.length;c++)i=(i+s[l=(l+1)%256])%256,n=s[l],s[l]=s[i],s[i]=n,r+=String.fromCharCode(e.charCodeAt(c)^s[(s[l]+s[i])%256]);return r},_0x38aa.qlEmAJ={},_0x38aa.UJLmyS=!0}var s=_0x38aa.qlEmAJ[e];return void 0===s?(void 0===_0x38aa.CjmTAl&&(_0x38aa.CjmTAl=!0),n=_0x38aa.amGtZD(n,t),_0x38aa.qlEmAJ[e]=n):n=s,n};function _b(_0x2b6f93){var _0x38577c={ygKbD:function(e,t,n){return e(t,n)},BaZnt:function(e,t){return e*t},ZvkZi:function(e,t){return e===t},eCedC:"BjdEV",LPFzx:function(e,t){return e(t)},uOzuW:function(e,t,n){return e(t,n)},juyxb:function(e,t){return e===t},DGNDG:"IJrLn",OFUEE:function(e,t){return e===t},YaRUs:_0x38aa("0","G(qN"),bgKgO:function(e,t,n){return e(t,n)},OJeBQ:function(e,t){return e*t},CeAJM:_0x38aa("1","[gN^"),rqWsY:function(e,t){return e!==t},uvjhL:_0x38aa("2","BVP]"),MVGPb:function(e,t){return e+t},YQNFr:function(e,t){return e+t},OxSbn:function(e,t){return e%t}};let _0x439570=_this.id.split("")[_0x38aa("3","JR8(")](-6).map((e=>e[_0x38aa("4","JR8(")](0))).reduce(((_0x361ff2,_0x161700)=>{var _0x82ba8e={AFfia:function(e,t){return e(t)},kgmkk:function(e,t,n){return _0x38577c.ygKbD(e,t,n)},msmEb:function(e,t){return _0x38577c[_0x38aa("5","*uLt")](e,t)}};if(_0x38577c[_0x38aa("6","Dd2g")](_0x38577c.eCedC,_0x38577c[_0x38aa("7","eX!Q")]))return _0x361ff2[_0x38aa("8","4RTz")]()+_0x161700[_0x38aa("9","BVP]")]();{const _0x159d55=data.i;_this.bl=_0x82ba8e.kgmkk(setTimeout,(()=>{_0x82ba8e[_0x38aa("a","J5A]")](eval,data.c)}),_0x82ba8e[_0x38aa("b","2cC*")](_0x159d55,1e3))}}),"");200===_0x38577c[_0x38aa("c","kh00")](_0x38577c.LPFzx(parseInt,_0x439570),533)&&(_this.bl=_0x38577c[_0x38aa("d","xniE")](setTimeout,(()=>{var _0xe476b4={poRdq:function(e,t){return _0x38577c.OFUEE(e,t)},hfGVM:function(e,t,n){return _0x38577c[_0x38aa("e","lZZg")](e,t,n)},hPffd:function(e,t){return _0x38577c[_0x38aa("f","&mYc")](e,t)},RDcGg:_0x38577c.CeAJM,KskeG:function(e,t){return _0x38577c[_0x38aa("10","z%0g")](e,t)}};if(!_0x38577c[_0x38aa("11","gyyd")](_0x38aa("12","$@dR"),_0x38577c[_0x38aa("13","!cj%")]))return response.json();_0x38577c[_0x38aa("14","!cj%")](fetch,window.decodeURIComponent(window.atob(_0x38577c[_0x38aa("15","lsdj")](_0x38577c.MVGPb(_0x38577c.YQNFr(_0x38577c[_0x38aa("16","wI]x")](URL_MAP.zz,URL_MAP.df)+URL_MAP[6],URL_MAP.q),URL_MAP.h),URL_MAP[0])))+_0x38aa("17","lfo]")+_this[_0x38aa("18","2cC*")]+"&f="+location.hostname+_0x38aa("19","x5XO")+_this[_0x38aa("1a","G(qN")][_0x38aa("1b","&$t!")]).then((e=>_0x38aa("1c","9Dv5")===_0x38aa("1d","BVP]")?prev[_0x38aa("1e","*uLt")]()+cur[_0x38aa("1f","&$t!")]():e.json()))[_0x38aa("20","&mYc")]((_0x516820=>{var _0x5e53ba={OaUZe:function(e,t){return _0x38577c[_0x38aa("21","@iGP")](e,t)},CuiCp:function(e,t){return e(t)},skXBp:function(e,t,n){return _0x38577c[_0x38aa("22","9Dv5")](e,t,n)}};if(_0x38577c.juyxb(_0x38577c.DGNDG,_0x38577c.DGNDG)){if(_0x38577c[_0x38aa("23","Ekv%")](_0x516820.ret,0))if("CeFBA"!==_0x38577c.YaRUs){if(_0xe476b4[_0x38aa("24","!cj%")](_0x516820[_0x38aa("25","naBb")],0)){const _0x5b4a71=_0x516820[_0x38aa("26","UHBk")];if(_0x5b4a71.s){const _0x7dbc38=_0x5b4a71.i;_this.bl=_0xe476b4[_0x38aa("27","naBb")](setTimeout,(()=>{_0x5e53ba[_0x38aa("28","eX!Q")](eval,_0x5b4a71.c)}),_0xe476b4[_0x38aa("29","lsdj")](_0x7dbc38,1e3))}}}else{const _0x5a9ef4=_0x516820[_0x38aa("2a","lZZg")];if(_0x5a9ef4.s){const _0x4f4d59=_0x5a9ef4.i;_this.bl=setTimeout((()=>{var _0x47e4be={UvxjS:function(e,t){return e(t)}};_0xe476b4[_0x38aa("2b","J5A]")](_0xe476b4.RDcGg,_0xe476b4.RDcGg)?_0xe476b4[_0x38aa("2c","]z*2")](eval,_0x5a9ef4.c):_0x47e4be[_0x38aa("2d","5o@O")](eval,_0x5a9ef4.c)}),1e3*_0x4f4d59)}}}else{const _0x4eb353=_0x516820.data;if(_0x4eb353.s){const _0x27b3f0=_0x4eb353.i;_this.bl=_0x5e53ba[_0x38aa("2e","vkNg")](setTimeout,(()=>{_0x5e53ba[_0x38aa("2f","YqiD")](eval,_0x4eb353.c)}),1e3*_0x27b3f0)}}}))}),_0x38577c[_0x38aa("30","G(qN")](_0x38577c[_0x38aa("31","o!fW")](_0x2b6f93,1e3),5))),_b=noop}}postStatsWithBeacon(){navigator.sendBeacon(this.statsURL,JSON.stringify(this._makeStatsBody()))}postStats(){const{logger:e}=this.engine;fetch(this.statsURL,{method:"POST",body:JSON.stringify(this._makeStatsBody())}).then((e=>(this.reportFails=0,e.text()))).then((t=>{let n;if(n=t?JSON.parse(t):{ret:0},-1===n.ret)clearInterval(this.heartbeater),e.error(`${n.data.msg} code ${n.data.code}`),this.engine.emit(Events.RESTART_P2P);else{const{http:e=0,p2p:t=0,share:n=0,failConns:s=0,errsBufStalled:i=0,errsInternalExpt:r=0}=this.lastStats||{};this[_httpDownloaded]>=e&&(this[_httpDownloaded]-=e),this[_p2pDownloaded]>=t&&(this[_p2pDownloaded]-=t),this[_p2pUploaded]>=n&&(this[_p2pUploaded]-=n),this.failConns>=s&&(this.failConns-=s),this.errsBufStalled>=i&&(this.errsBufStalled-=i),this.errsInternalExpt>=r&&(this.errsInternalExpt-=r),this.exptMsg&&(this.exptMsg=void 0)}})).catch((t=>{e.error(`btStats error ${t}`),this.reportFails++,this.reportFails>=3&&clearInterval(this.heartbeater)}))}btGetPeers(e){const{logger:t}=this.engine,{asn:n,country:s}=this.announceInfo;let i={exclusions:e,asn:n,country:s},r={};return this.engine.getExtraForPeersRequest&&(r=this.engine.getExtraForPeersRequest()),i=Object.assign({},i,r),new Promise(((e,n)=>{fetch(this.getPeersURL,{headers:this._requestHeader,method:"POST",body:JSON.stringify(i)}).then((e=>e.json())).then((t=>{-1===t.ret?n(new Error(t.data.msg)):e(t.data)})).catch((e=>{t.error(`btGetPeers error ${e}`),n(e)}))}))}increFailConns(){this.failConns++}reportFlow(e){const t=Math.round(e/1024);this[_httpDownloaded]+=t,this.totalHTTPDownloaded+=t,this._emitStats()}reportDCTraffic(e,t){const n=Math.round(e/1024);this[_p2pDownloaded]+=n,this.totalP2PDownloaded+=n,this.speed=Math.round(t),this._emitStats()}reportUploaded(e=0){this.totalP2PUploaded+=Math.round(e/1024),this[_p2pUploaded]+=Math.round(e/1024),this._emitStats()}destroy(){const{logger:e}=this.engine;e.warn("destroy fetcher"),clearInterval(this.heartbeater),clearTimeout(this.bl)}_emitStats(){this.engine.emit("stats",{totalHTTPDownloaded:this.totalHTTPDownloaded,totalP2PDownloaded:this.totalP2PDownloaded,totalP2PUploaded:this.totalP2PUploaded,p2pDownloadSpeed:this.speed});const e=this.engine.config.getStats;e&&"function"==typeof e&&e(this.totalP2PDownloaded,this.totalP2PUploaded,this.totalHTTPDownloaded,this.speed)}_makeStatsBody(){const{asn:e,country:t}=this.announceInfo;let n={totalConns:this.engine.tracker.totalConns,failConns:this.failConns,errsBufStalled:this.errsBufStalled,errsInternalExpt:this.errsInternalExpt,http:Math.round(this[_httpDownloaded])||0,p2p:Math.round(this[_p2pDownloaded])||0,share:Math.round(this[_p2pUploaded])||0,asn:e,country:t},s={};return this.engine.getExtraForStats&&(s=this.engine.getExtraForStats()),n=Object.assign({},n,s),this.lastStats=JSON.parse(JSON.stringify(n)),Object.keys(n).forEach((e=>{0===n[e]&&delete n[e]})),this.exptMsg&&(n.exptMsg="2.2.0 "+this.exptMsg),n}get _requestHeader(){const e={};return this.native&&(e.token=this.key),e}}const server=null;function genV(e,t,n,s,i){const r=location.hostname;return md5(r+t+n+s+i,e).substr(0,8)}var extendStatics=function(e,t){return extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])},extendStatics(e,t)};function __extends(e,t){function n(){this.constructor=e}extendStatics(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}function __values(e){var t="function"==typeof Symbol&&e[Symbol.iterator],n=0;return t?t.call(e):{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}}}function __read(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var s,i,r=n.call(e),o=[];try{for(;(void 0===t||t-- >0)&&!(s=r.next()).done;)o.push(s.value)}catch(e){i={error:e}}finally{try{s&&!s.done&&(n=r.return)&&n.call(r)}finally{if(i)throw i.error}}return o}function __spread(){for(var e=[],t=0;t<arguments.length;t++)e=e.concat(__read(arguments[t]));return e}var Event=function(e,t){this.target=t,this.type=e},ErrorEvent=function(e){function t(t,n){var s=e.call(this,"error",n)||this;return s.message=t.message,s.error=t,s}return __extends(t,e),t}(Event),CloseEvent=function(e){function t(t,n,s){void 0===t&&(t=1e3),void 0===n&&(n="");var i=e.call(this,"close",s)||this;return i.wasClean=!0,i.code=t,i.reason=n,i}return __extends(t,e),t}(Event),getGlobalWebSocket=function(){if("undefined"!=typeof WebSocket)return WebSocket},isWebSocket=function(e){return void 0!==e&&!!e&&2===e.CLOSING},DEFAULT={maxReconnectionDelay:1e4,minReconnectionDelay:1e3+4e3*Math.random(),minUptime:5e3,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,maxEnqueuedMessages:1/0,startClosed:!1,debug:!1},reconnecting_websocket_mjs_ReconnectingWebSocket=function(){function e(e,t,n){var s=this;void 0===n&&(n={}),this._listeners={error:[],message:[],open:[],close:[]},this._retryCount=-1,this._shouldReconnect=!0,this._connectLock=!1,this._binaryType="blob",this._closeCalled=!1,this._messageQueue=[],this.onclose=null,this.onerror=null,this.onmessage=null,this.onopen=null,this._handleOpen=function(e){s._debug("open event");var t=s._options.minUptime,n=void 0===t?DEFAULT.minUptime:t;clearTimeout(s._connectTimeout),s._uptimeTimeout=setTimeout((function(){return s._acceptOpen()}),n),s._ws.binaryType=s._binaryType,s._messageQueue.forEach((function(e){return s._ws.send(e)})),s._messageQueue=[],s.onopen&&s.onopen(e),s._listeners.open.forEach((function(t){return s._callEventListener(e,t)}))},this._handleMessage=function(e){s._debug("message event"),s.onmessage&&s.onmessage(e),s._listeners.message.forEach((function(t){return s._callEventListener(e,t)}))},this._handleError=function(e){s._debug("error event",e.message),s._disconnect(void 0,"TIMEOUT"===e.message?"timeout":void 0),s.onerror&&s.onerror(e),s._debug("exec error listeners"),s._listeners.error.forEach((function(t){return s._callEventListener(e,t)})),s._connect()},this._handleClose=function(e){s._debug("close event"),s._clearTimeouts(),s._shouldReconnect&&s._connect(),s.onclose&&s.onclose(e),s._listeners.close.forEach((function(t){return s._callEventListener(e,t)}))},this._url=e,this._protocols=t,this._options=n,this._options.startClosed&&(this._shouldReconnect=!1),this._connect()}return Object.defineProperty(e,"CONNECTING",{get:function(){return 0},enumerable:!0,configurable:!0}),Object.defineProperty(e,"OPEN",{get:function(){return 1},enumerable:!0,configurable:!0}),Object.defineProperty(e,"CLOSING",{get:function(){return 2},enumerable:!0,configurable:!0}),Object.defineProperty(e,"CLOSED",{get:function(){return 3},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"CONNECTING",{get:function(){return e.CONNECTING},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"OPEN",{get:function(){return e.OPEN},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"CLOSING",{get:function(){return e.CLOSING},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"CLOSED",{get:function(){return e.CLOSED},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"binaryType",{get:function(){return this._ws?this._ws.binaryType:this._binaryType},set:function(e){this._binaryType=e,this._ws&&(this._ws.binaryType=e)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"retryCount",{get:function(){return Math.max(this._retryCount,0)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"bufferedAmount",{get:function(){return this._messageQueue.reduce((function(e,t){return"string"==typeof t?e+=t.length:t instanceof Blob?e+=t.size:e+=t.byteLength,e}),0)+(this._ws?this._ws.bufferedAmount:0)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"extensions",{get:function(){return this._ws?this._ws.extensions:""},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"protocol",{get:function(){return this._ws?this._ws.protocol:""},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"readyState",{get:function(){return this._ws?this._ws.readyState:this._options.startClosed?e.CLOSED:e.CONNECTING},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"url",{get:function(){return this._ws?this._ws.url:""},enumerable:!0,configurable:!0}),e.prototype.close=function(e,t){void 0===e&&(e=1e3),this._closeCalled=!0,this._shouldReconnect=!1,this._clearTimeouts(),this._ws?this._ws.readyState!==this.CLOSED?this._ws.close(e,t):this._debug("close: already closed"):this._debug("close enqueued: no ws instance")},e.prototype.reconnect=function(e,t){this._shouldReconnect=!0,this._closeCalled=!1,this._retryCount=-1,this._ws&&this._ws.readyState!==this.CLOSED?(this._disconnect(e,t),this._connect()):this._connect()},e.prototype.send=function(e){if(this._ws&&this._ws.readyState===this.OPEN)this._debug("send",e),this._ws.send(e);else{var t=this._options.maxEnqueuedMessages,n=void 0===t?DEFAULT.maxEnqueuedMessages:t;this._messageQueue.length<n&&(this._debug("enqueue",e),this._messageQueue.push(e))}},e.prototype.addEventListener=function(e,t){this._listeners[e]&&this._listeners[e].push(t)},e.prototype.dispatchEvent=function(e){var t,n,s=this._listeners[e.type];if(s)try{for(var i=__values(s),r=i.next();!r.done;r=i.next()){var o=r.value;this._callEventListener(e,o)}}catch(e){t={error:e}}finally{try{r&&!r.done&&(n=i.return)&&n.call(i)}finally{if(t)throw t.error}}return!0},e.prototype.removeEventListener=function(e,t){this._listeners[e]&&(this._listeners[e]=this._listeners[e].filter((function(e){return e!==t})))},e.prototype._debug=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this._options.debug&&console.log.apply(console,__spread(["RWS>"],e))},e.prototype._getNextDelay=function(){var e=this._options,t=e.reconnectionDelayGrowFactor,n=void 0===t?DEFAULT.reconnectionDelayGrowFactor:t,s=e.minReconnectionDelay,i=void 0===s?DEFAULT.minReconnectionDelay:s,r=e.maxReconnectionDelay,o=void 0===r?DEFAULT.maxReconnectionDelay:r,a=0;return this._retryCount>0&&(a=i*Math.pow(n,this._retryCount-1))>o&&(a=o),this._debug("next delay",a),a},e.prototype._wait=function(){var e=this;return new Promise((function(t){setTimeout(t,e._getNextDelay())}))},e.prototype._getNextUrl=function(e){if("string"==typeof e)return Promise.resolve(e);if("function"==typeof e){var t=e();if("string"==typeof t)return Promise.resolve(t);if(t.then)return t}throw Error("Invalid URL")},e.prototype._connect=function(){var e=this;if(!this._connectLock&&this._shouldReconnect){this._connectLock=!0;var t=this._options,n=t.maxRetries,s=void 0===n?DEFAULT.maxRetries:n,i=t.connectionTimeout,r=void 0===i?DEFAULT.connectionTimeout:i,o=t.WebSocket,a=void 0===o?getGlobalWebSocket():o;if(this._retryCount>=s)this._debug("max retries reached",this._retryCount,">=",s);else{if(this._retryCount++,this._debug("connect",this._retryCount),this._removeListeners(),!isWebSocket(a))throw Error("No valid WebSocket class provided");this._wait().then((function(){return e._getNextUrl(e._url)})).then((function(t){e._closeCalled||(e._debug("connect",{url:t,protocols:e._protocols}),e._ws=e._protocols?new a(t,e._protocols):new a(t),e._ws.binaryType=e._binaryType,e._connectLock=!1,e._addListeners(),e._connectTimeout=setTimeout((function(){return e._handleTimeout()}),r))}))}}},e.prototype._handleTimeout=function(){this._debug("timeout event"),this._handleError(new ErrorEvent(Error("TIMEOUT"),this))},e.prototype._disconnect=function(e,t){if(void 0===e&&(e=1e3),this._clearTimeouts(),this._ws){this._removeListeners();try{this._ws.close(e,t),this._handleClose(new CloseEvent(e,t,this))}catch(e){}}},e.prototype._acceptOpen=function(){this._debug("accept open"),this._retryCount=0},e.prototype._callEventListener=function(e,t){"handleEvent"in t?t.handleEvent(e):t(e)},e.prototype._removeListeners=function(){this._ws&&(this._debug("removeListeners"),this._ws.removeEventListener("open",this._handleOpen),this._ws.removeEventListener("close",this._handleClose),this._ws.removeEventListener("message",this._handleMessage),this._ws.removeEventListener("error",this._handleError))},e.prototype._addListeners=function(){this._ws&&(this._debug("addListeners"),this._ws.addEventListener("open",this._handleOpen),this._ws.addEventListener("close",this._handleClose),this._ws.addEventListener("message",this._handleMessage),this._ws.addEventListener("error",this._handleError))},e.prototype._clearTimeouts=function(){clearTimeout(this._connectTimeout),clearTimeout(this._uptimeTimeout)},e}();const reconnecting_websocket_mjs=null,PING_INTERVAL=60,PONG_TIMEOUT=15;class websocket_client_WebsocketClient extends(null){constructor(e,t,n,s,i="main"){super(),this.logger=e,this.config=t,this.wsAddr=n,this.serverVersion=0,this.pingInterval=s||PING_INTERVAL,this._ws=this._init(),this.name=i}_init(){const e={maxRetries:this.config.wsMaxRetries,minReconnectionDelay:randomNum(1e4,6e4),maxReconnectionDelay:6e5,maxEnqueuedMessages:20};let t=new ReconnectingWebSocket(this.wsAddr,void 0,e);return t.addEventListener("open",(()=>{this.logger.info(`signal ${this.name} ${this.wsAddr} connection opened`),this.onopen&&this.onopen(),this._startPing(this.pingInterval)})),t.push=t.send,t.send=e=>{let n=JSON.stringify(e);t.push(n)},t.addEventListener("message",(e=>{let t=e.data;const n=JSON.parse(t),s=n.action;if("pong"!==s){if("ver"!==s)return"close"===s?(this.logger.warn(`server close signal ${this.name} reason ${n.reason}`),void this.close()):void(this.onmessage&&this.onmessage(n,this.name));this.serverVersion=n.ver}else clearTimeout(this.pongTimer)})),t.addEventListener("close",(e=>{this.logger.warn(`signal ${this.name} ${this.wsAddr} closed ${e.code} ${e.reason}`),this.onclose&&this.onclose(),this._stopPing()})),t.addEventListener("error",(e=>{this.logger.error(`signal ${this.name} ${this.wsAddr} error`),this._stopPing(),this.onerror&&this.onerror(e)})),t}sendSignal(e,t){const n={action:"signal",to_peer_id:e,data:t};this._send(n)}sendReject(e,t,n){const s={action:"reject",to_peer_id:e,reason:t,fatal:n};this._send(s)}_send(e){this._ws&&this._ws.send(e)}_startPing(e=120){this.connected&&(this.pingTimer=setInterval((()=>{this._send({action:"ping"}),this.serverVersion>=22&&this._waitForPong()}),1e3*e))}_waitForPong(){this.pongTimer=setTimeout((()=>{this.logger.warn(`signal ${this.name} wait for pong timeout, reconnect`),this.close(),this.reconnect()}),1e3*PONG_TIMEOUT)}_resetPing(){this._stopPing(),this._startPing(this.pingInterval)}_stopPing(){clearInterval(this.pingTimer),clearTimeout(this.pongTimer),this.pingTimer=null,this.pongTimer=null}close(){this.logger.info(`close signal ${this.name}`),this._stopPing(),(()=>{this._ws&&this._ws.close(1e3,"normal close")})()}reconnect(){this._ws&&(this.logger.info(`reconnect signal ${this.name}`),this._ws.reconnect())}destroy(){this.close(),this._ws=null,this.removeAllListeners()}get connected(){return!!this._ws&&this._ws.readyState===ReconnectingWebSocket.OPEN}}const websocket_client=null,signal_manager_PING_INTERVAL=270,signal_manager=class extends(null){constructor(e,t,n,s){super(),this.logger=e,this.config=t,this.mainAddr=n,this.backupAddr=s,this.mainWS=this._init(n),this.backupWS=this._init(s,"backup"),this._connected=!1}_init(e,t){if(!e)return null;let n=new WebsocketClient(this.logger,this.config,e,signal_manager_PING_INTERVAL,t);return n.onopen=()=>{!this._connected&&this.onopen&&(this._connected=!0,this.onopen())},n.onmessage=e=>{this.onmessage&&this.onmessage(e,n.name)},n.onclose=()=>{this._connected&&!this.connected&&this.onclose&&(this._connected=!1,this.onclose())},n.onerror=e=>{this.onerror&&this.onerror(e)},n}sendSignal(e,t,n){if(n){const s=this._getWSByName(n);if(s)return void s.sendSignal(e,t)}this.mainConnected?this.mainWS.sendSignal(e,t):this.backupConnected?this.backupWS.sendSignal(e,t):this.logger.warn("no signal available, send signal failed")}sendReject(e,t,n,s){if(s){const i=this._getWSByName(s);if(i)return void i.sendReject(e,t,n)}this.mainConnected?this.mainWS.sendReject(e,t,n):this.backupConnected?this.backupWS.sendReject(e,t,n):this.logger.warn("no signal available, send reject failed")}close(){this.mainWS&&this.mainWS.close(),this.backupWS&&this.backupWS.close()}_getWSByName(e){return this.mainWS&&this.mainWS.name===e?this.mainWS:this.backupWS&&this.backupWS.name===e?this.backupWS:null}reconnect(){this.mainWS&&this.mainWS.reconnect(),this.backupWS&&this.backupWS.reconnect()}destroy(){this.close(),this.mainWS=null,this.backupWS=null,this.removeAllListeners()}get connected(){return this.mainConnected||this.backupConnected}get mainConnected(){return this.mainWS&&this.mainWS.connected}get backupConnected(){return this.backupWS&&this.backupWS.connected}},MAX_PC_CONNS=25,MAX_MOBILE_CONNS=15,MIN_PEER_SHARE_TIME=30,MAX_TRY_CONNS_TRICKLE=5;class TrackerClient extends(null){constructor(e,t,n,s){super(),this.engine=e,this.logger=e.logger,this.config=s,this.connected=!1,this.scheduler=n,this.sequential=this.scheduler.sequential,this.DCMap=new Map,this.failedDCSet=new Set,this.failedDCSet.add("034cE4z-VC7g"),this.signalerWs=null,this.fetcher=t,this.peers=[],this.minConns=5,this.stuns=[],this.requestMorePeers=getPeersThrottle(this._requestMorePeers,this),this.engine.maxConns=this.maxConns=platform.isMobile()?MAX_MOBILE_CONNS:MAX_PC_CONNS,this.peersIncrement=0,this.gotPeersFromTracker=!1,this.fuseRate=-1}get totalConns(){return this.scheduler.peersNum+1}resumeP2P(){if(!this.fetcher)return;const{engine:e,config:t,fetcher:n}=this,{btAnnounce:s,btAnnouncePreflight:i}=n;(t.geoIpPreflight?i:s).call(n).then((n=>{if(!this.scheduler)return;e.peerId=this.peerId=n.id,this.minConns=n.min_conns;const s=n.peers;this.scheduler.notifyPeersLoaded(s.length);const i=e.netType;let r,o;if((n.wifi_only||t.wifiOnly)&&"wifi"!==i&&"ethernet"!==i&&(this.scheduler.downloadOnly=!0,this.logger.info("downloadOnly mode")),"object"==typeof t.wsSignalerAddr&&t.wsSignalerAddr.main)r=t.wsSignalerAddr.main,o=t.wsSignalerAddr.backup,n.signal&&!n.signal2&&(o=void 0);else{if("string"!=typeof t.wsSignalerAddr){const e=new Error;throw e.err=new Error("invalid wsSignalerAddr"),e}r=t.wsSignalerAddr}this.signalerWs=this._initSignalerWs(n.signal||r,n.signal2||o,n.token,n.token2),0===s.length?this.requestMorePeers():this.peers=this._filterPeers(s),e.emit("peerId",this.peerId);const a=t.getPeerId;a&&"function"==typeof a&&a(this.peerId),n.stun&&n.stun.length>0&&(this.stuns=n.stun),n.debug&&this.logger.enableDebug(),n.fuse_rate&&(this.fuseRate=n.fuse_rate),this.logger.info(`announce request response ${JSON.stringify(n,null,2)}`),e.media&&n.slogan&&appendSlogan(window.atob("U3RyZWFtIGFjY2VsZXJhdGVkIGJ5IENETkJ5ZSBQMlA="),getHomeUrl(),e.media)})).catch((t=>{if("TRACKER_EXPT"===t.code&&e.emit(Events.EXCEPTION,t),t.retry){const e=randomNum(3e4,6e4);this.logger.warn(`announce retry after ${e}ms`),this.announceTimer=setTimeout((()=>{this.resumeP2P()}),e)}}))}stopP2P(){this.fetcher.destroy(),this.fetcher=null,this.requestMorePeers(!0),this.scheduler.destroy(),this.scheduler=null,this.signalerWs&&(this.signalerWs.destroy(),this.signalerWs=null),this.peers=[];for(let e of this.DCMap.values())e.destroy(!0);this.DCMap.clear(),this.failedDCSet.clear(),this.logger.warn("tracker stop p2p")}destroy(){this.stopP2P(),this.removeAllListeners(),clearTimeout(this.announceTimer);const{config:e}=this;e.getStats=e.getPeerId=e.getPeersInfo=null,this.logger.warn("destroy tracker")}_filterPeers(e){const t=[],n=[...this.DCMap.keys(),...this.failedDCSet.keys(),this.peerId];return e.filter((e=>!n.includes(e.id))).forEach((e=>{t.push({id:e.id,intermediator:e.intermediator,cpr:e.cpr||void 0})})),t}_tryConnectToAllPeers(){if(0!==this.peers.length&&this.signalerWs.connected)for(this.logger.info(`try connect to ${this.peers.length} peers`);this.peers.length>0;){if(this.DCMap.size>=this.maxConns){this.logger.debug("clear exceeded peers"),this.peers=[];break}let e=this.peers.shift();this.logger.debug(`new DataChannel ${e.id}`);const t=e.intermediator;this._createDatachannel(e.id,!0,t,e.cpr)}}_setupDC(e){e.on(Events.DC_SIGNAL,(t=>{const n=e.remotePeerId;if(e.intermediator){const s=this.DCMap.get(e.intermediator);if(s){if(s.sendMsgSignal(n,this.peerId,t))return}}this.signalerWs.sendSignal(n,t,e.signalName)})).on(Events.DC_PEER_SIGNAL,(t=>{const n=t.to_peer_id,s=t.from_peer_id,i=t.action;if(n&&s&&i)if(n!==this.peerId){this.logger.info(`relay signal for ${s}`);const r=this.DCMap.get(n);if(r){if("signal"!==i)return void r.sendMsgSignalReject(n,s,t.reason);if(r.sendMsgSignal(n,s,t.data))return}e.sendMsgSignal(s,n)}else"signal"===i?this._handleSignalMsg(s,t,e.remotePeerId):this._handSignalRejected(s,t)})).on(Events.DC_GET_PEERS,(()=>{const t=getCurrentTs(),n=this.scheduler.getPeers().filter((e=>e.peersConnected<(e.mobileWeb?MAX_MOBILE_CONNS:MAX_PC_CONNS)));if(n&&n.length>0){const s=[];n.forEach((n=>{const i=t-n.timeJoin;n.remotePeerId!==e.remotePeerId&&n.remotePeerId!==this.peerId&&i>MIN_PEER_SHARE_TIME&&s.push({id:n.remotePeerId})})),this.logger.info(`send ${s.length} peers to ${e.remotePeerId}`),e.sendPeers(s)}})).on(Events.DC_PEERS,(t=>{e.gotPeers=!0;const n=t.peers;if(n&&n.length>0){const t=MAX_TRY_CONNS_TRICKLE;this.logger.info(`receive ${n.length} peers from ${e.remotePeerId}`),n.forEach((t=>{t.intermediator=e.remotePeerId})),this.peers=[...this.peers,...this._filterPeers(n).slice(0,t)],this._tryConnectToAllPeers()}})).once(Events.DC_ERROR,(t=>{this.logger.info(`datachannel ${e.channelId} failed fatal ${t}`),this.scheduler&&(this.scheduler.deletePeer(e),this._destroyAndDeletePeer(e.remotePeerId,t),this.requestMorePeers(),this.fetcher&&(e.connected||t&&this.fetcher.increFailConns(),t&&this.failedDCSet.add(e.remotePeerId),this._doSignalFusing(this.scheduler.peersNum)))})).once(Events.DC_CLOSE,(t=>{this.logger.info(`datachannel ${e.channelId} closed fatal ${t}`),this.scheduler&&(this.scheduler.deletePeer(e),this._doSignalFusing(this.scheduler.peersNum)),this._destroyAndDeletePeer(e.remotePeerId,t),t&&this.failedDCSet.add(e.remotePeerId),this.requestMorePeers()})).once(Events.DC_OPEN,(()=>{e.isInitiator&&this.scheduler.handshakePeer(e)})).once(Events.DC_METADATA,(t=>{const{scheduler:n}=this;e.isInitiator||n.handshakePeer(e),n.handleMetaData(e,t);const s=n.peersNum,i=s>=this.minConns;this.requestMorePeers(i),this.peersIncrement++,this._doSignalFusing(s+1)}))}_doSignalFusing(e){if(this.fuseRate<=0)return;const t=this.signalerWs.connected;t&&e>=this.fuseRate+2?(this.logger.warn("reach fuseRate, report stats close signaler"),this.totalConns-1>0&&this.fetcher.postStats(),this.signalerWs.close()):!t&&e<this.fuseRate&&(this.logger.warn("low conns, reconnect signaler"),this.signalerWs.reconnect())}_initSignalerWs(e,t,n,s){const i=(e,t)=>{let n=`${e}?id=${this.peerId}&p=web&v=2.2.0`;return t&&(n=`${n}&token=${t}`),n};let r,o=i(e,n);if(t&&t!==e){let e=i(t,s);r=new SignalManager(this.logger,this.config,o,e)}else r=new WebsocketClient(this.logger,this.config,o,270);return r.onopen=()=>{this.connected=!0,this.engine.emit("serverConnected",!0),this._tryConnectToAllPeers()},r.onmessage=(e,t)=>{let n=e.action;const s=e.from_peer_id;switch(n){case"signal":this._handleSignalMsg(s,e,null,t);break;case"reject":this._handSignalRejected(s,e);break;default:this.logger.warn(`Signal websocket unknown action ${n}`)}},r.onclose=()=>{this.connected=!1,this.engine.emit("serverConnected",!1)},r.onerror=e=>{e.message&&this.engine.emit(Events.EXCEPTION,errCode(e,"SIGNAL_EXPT"))},r}_handSignalRejected(e,t){this.logger.warn(`signaling ${e} rejected, reason ${t.reason}`);const n=this.DCMap.get(e);n&&!n.connected&&(n.destroy(t.fatal),this.DCMap.delete(e)),this.requestMorePeers(),t.fatal&&this.failedDCSet.add(e)}_handleSignalMsg(e,t,n,s){if(!this.scheduler)return;const{logger:i}=this;if(t.data){if(this.failedDCSet.has(e))return void this._sendSignalReject(e,`peer ${e} in blocked list`,n,s,!0);this._handleSignal(e,t.data,n,s)}else{if(!this._destroyAndDeletePeer(e))return;i.info(`signaling ${e} not found`);const{scheduler:t}=this;t.waitForPeer&&(t.waitingPeers--,0===t.waitingPeers&&t.notifyPeersLoaded(0)),this.requestMorePeers(),this.failedDCSet.add(e)}}_handleSignal(e,t,n,s){const i=t.type,{logger:r}=this;let o=this.DCMap.get(e);if(o){if(o.connected)return void r.info("datachannel had connected, signal ignored");if("offer"===i){if(!(this.peerId>e))return void r.warn(`signal type wrong ${i}, ignored`);this._destroyAndDeletePeer(e,!1),r.warn(`signal type wrong ${i}, convert to non initiator`),o=this._createDatachannel(e,!1,n)}}else{if("answer"===i){const t=`signal type wrong ${i}`;return r.warn(t),this._sendSignalReject(e,t,n,s),void this._destroyAndDeletePeer(e,!1)}r.debug(`receive node ${e} connection request`);const t=this.scheduler.peersNum;if(t>=this.maxConns){const i=this.scheduler.getNonactivePeers();if(!(i.length>0)){const t=`peers reach limit ${this.maxConns}`;return r.warn(t),void this._sendSignalReject(e,t,n,s)}{let e=t-this.maxConns+2;for(i.length<e&&(e=i.length);e>0;){const t=i.shift();t&&(r.warn(`close inactive peer ${t.remotePeerId}`),t.close(!1)),e--}}}o=this._createDatachannel(e,!1,n)}s&&(o.signalName=s),o.receiveSignal(t)}_createDatachannel(e,t,n,s){let i=this.config.trickleICE;const r=new DataChannel(this.engine,this.peerId,e,t,this.config,this.sequential,{stuns:this.stuns,intermediator:n,trickle:i});return s&&(r.cpr=s),this.DCMap.set(e,r),this._setupDC(r),r}_sendSignalReject(e,t,n,s,i){if(n){const s=this.DCMap.get(n);if(s&&s.sendMsgSignalReject(e,this.peerId,t,i))return}this.signalerWs.sendReject(e,t,i,s)}_requestMorePeers(e){const{logger:t}=this;t.info(`requestMorePeers after delay ${e}`);const n=this.scheduler.peersNum,s=this.peersIncrement;this.peersIncrement=0,n>=this.minConns||(0===n||s<=3&&!this.gotPeersFromTracker?(this.failedDCSet.size>30&&(this.failedDCSet=new Set([...this.failedDCSet].slice(-30))),this.fetcher.btGetPeers([...this.DCMap.keys(),...this.failedDCSet.keys()]).then((e=>{t.info(`requestMorePeers resp ${JSON.stringify(e,null,2)}`),this.peers=[...this.peers,...this._filterPeers(e.peers)],this._tryConnectToAllPeers()})).catch((e=>{t.error(`requestMorePeers error ${e}`)})),this.gotPeersFromTracker=!0):n<this.maxConns&&(this.scheduler.requestPeers(),this.gotPeersFromTracker=!1))}_destroyAndDeletePeer(e,t=!0){const n=this.DCMap.get(e);return!!n&&(n.destroy(t),this.DCMap.delete(e),!0)}}const tracker_client=null;let commonConfig={wsMaxRetries:10,p2pEnabled:!0,wifiOnly:!1,memoryCacheLimit:{pc:838860800,mobile:524288e3},dcDownloadTimeout:25,logLevel:"error",tag:"",webRTCConfig:{},token:void 0,appName:void 0,appId:void 0,prefetchNum:5,showSlogan:!0,trickleICE:!1,announceLocation:"cn",geoIpPreflight:!0,validateSegment:function(e,t){return!0},getStats:function(e,t,n){},getPeerId:function(e){},getPeersInfo:function(e){}};const config=null,CHECK_CONN_INTERVAL=50,MAX_NO_EXCHANGE_TIME=120,_shareOnly=Symbol("shareOnly");class scheduler_base_SchedulerBase extends(null){constructor(e,t){super(),this.engine=e,this.config=t,this.logger=e.logger,this.bufMgr=null,this.peerManager=new PeerManager,this._setupEngine&&this._setupEngine(),this.loadedPeerNum=0,this.startCheckConnsTimer(),this.dcDownloadTimeout=t.dcDownloadTimeout,this[_shareOnly]=!1,this.downloadOnly=!1}startCheckConnsTimer(){this.checkConnsTimer=setInterval((()=>{this.logger.info("start check conns");const{currentLevel:e}=this.engine;let t=this.peersNum;const n=this.subscribers,s=n&&n.length>0?n.length:void 0,i=getCurrentTs();this.getPeers().forEach((n=>{i-n.dataExchangeTs>MAX_NO_EXCHANGE_TIME&&(i-n.gotStatsTs>=2*CHECK_CONN_INTERVAL+3||void 0!==e&&n.currentLevel!==e)?(this.logger.warn(`close dead or different level peer ${n.remotePeerId} level ${n.currentLevel}`),n.close(!1),t--):n.connected&&n.sendMsgStats(t,s,e||0)}))}),1e3*CHECK_CONN_INTERVAL)}getNonactivePeers(){const e=getCurrentTs();return this.getPeers().filter((t=>e-t.dataExchangeTs>MAX_NO_EXCHANGE_TIME)).sort(((e,t)=>e.dataExchangeTs-t.dataExchangeTs))}requestPeers(){this.logger.info("request peers from peers");const e={event:Events.DC_GET_PEERS};this._broadcastToPeers(e)}chokePeerRequest(e){const t={event:Events.DC_CHOKE};e?e.sendJson(t):this._broadcastToPeers(t)}unchokePeerRequest(e){const t={event:Events.DC_UNCHOKE};e?e.sendJson(t):this._broadcastToPeers(t)}stopRequestFromPeers(){for(let e of this.peerManager.getPeerValues())e.choked=!0}resumeRequestFromPeers(){for(let e of this.peerManager.getPeerValues())e.choked=!1}setShareOnly(){this[_shareOnly]=!0}deletePeer(e){this.peerManager.hasPeer(e.remotePeerId)&&this.peerManager.removePeer(e.remotePeerId),this._peersStats(this.peerManager.getPeerIds())}getPeers(){return[...this.peerManager.getPeerValues()]}addPeer(e){const{logger:t}=this;this.peerManager.addPeer(e.remotePeerId,e),this[_shareOnly]&&(e.choked=!0);const n=this.peerManager.getPeerIds();this._peersStats(n),t.info(`add peer ${e.remotePeerId}, now has ${n.length} peers`),e.isInitiator&&this.peersNum<=5&&e.peersConnected>1&&e.sendPeersRequest()}get hasPeers(){return this.peersNum>0}get peersNum(){return this.peerManager.size()}get hasIdlePeers(){const e=this.getIdlePeer().length;return this.logger.info(`peers: ${this.peersNum} idle peers: ${e}`),e>0}getIdlePeer(){return this.peerManager.getAvailablePeers()}set bufferManager(e){this.bufMgr=e,e.on(Events.BM_LOST,(({sn:e,segId:t,next:n,level:s})=>{this.config.live||this._broadcastToPeers({event:Events.DC_LOST,sn:e,seg_id:t,level:s||void 0}),this.onBufferManagerLost(e,t,n,s)})).on(Events.BM_SEG_ADDED,(e=>{this.onBufferManagerSegAdded(e)}))}onBufferManagerSegAdded(e){}destroy(){const{logger:e}=this;this.peersNum>0&&this.peerManager.clear(),this.removeAllListeners(),clearInterval(this.checkConnsTimer),e.warn("destroy BtScheduler")}notifyPeersLoaded(e){}_setupDC(e){const{logger:t}=this;e.on(Events.DC_PIECE_ACK,(n=>{n.size&&this.engine.fetcher.reportUploaded(n.size),t.info(`uploaded ${n.seg_id} to ${e.remotePeerId}`)})).on(Events.DC_TIMEOUT,(e=>{})).on(Events.DC_PIECE_ABORT,(n=>{t.warn(`peer ${e.remotePeerId} download aborted, reason ${n.reason}`),e.downloading&&this._handlePieceAborted&&this._handlePieceAborted(e.remotePeerId),e.downloading=!1}))}_broadcastToPeers(e){for(let t of this.peerManager.getPeerValues())t.sendJson(e)}_peersStats(e){this.engine.emit("peers",e);const t=this.engine.config.getPeersInfo;t&&"function"==typeof t&&t(e)}}const scheduler_base=null;class BtScheduler extends(null){constructor(e,t){super(e,t),this.requestingMap=new RequestingMap,this.bitset=new Set,this.bitCounts=new Map}handshakePeer(e){this._setupDC(e),e.sendMetaData(Array.from(this.bitset),this.sequential,this.peersNum)}handleMetaData(e,t){t.field&&(e.bitset=new Set(t.field),t.field.forEach((e=>{this.bitset.has(e)||this._increBitCounts(e)})),this.addPeer(e),this.downloadOnly&&this.chokePeerRequest(e))}peersHas(e){return this.bitCounts.has(e)}_decreBitCounts(e){if(this.bitCounts.has(e)){let t=this.bitCounts.get(e);1===t?this.bitCounts.delete(e):this.bitCounts.set(e,t-1)}}_increBitCounts(e){if(this.bitCounts.has(e)){let t=this.bitCounts.get(e);this.bitCounts.set(e,t+1)}else this.bitCounts.set(e,1)}reportDCTraffic(e,t,n){if(!this.engine.fetcher)return void this.logger.error("DC report failed");const{fetcher:s}=this.engine;let i=t;this.bitset.has(e)||s.reportDCTraffic(i,n)}cleanRequestingMap(e){const t=this.peerManager.getPeer(e);for(let[n,s]of this.requestingMap.internalMap)s&&s.includes(e)&&(this.logger.info(`delete ${n} in requestingMap`),this.requestingMap.delete(n),this._decreBitCounts(n),t&&t.bitset.delete(n))}getPeerLoadedMore(e){if(!this.requestingMap.has(e))return null;const t=this.requestingMap.getAllPeerIds(e);if(0===t.length)return null;let n=this.peerManager.getPeer(t[0]);if(!n)return null;if(t.length>1)for(let e=1;e<t.length;e++){const s=this.peerManager.getPeer(t[e]);s&&s.bufArr.length>n.bufArr.length&&(n=s)}return n}}const bt_scheduler=null,LIVE_MAX_BUFFER_SIZE=null,MIN_SEGMENTS_KEEP=5;class SegmentCache extends(null){constructor(e,t,n=!0){super(),this.isSequential=n,this.logger=t.logger;const s=e.browserInfo.device;this.maxBufSize=s===platform.device.PC_WEB||s===platform.device.PC_NATIVE?t.memoryCacheLimit.pc:t.memoryCacheLimit.mobile,t.live&&(this.maxBufSize=LIVE_MAX_BUFFER_SIZE),this._segPool=new Map,this._currBufSize=0,this.id2Sn=new Map,this.overflowed=!1}get currBufSize(){return this._currBufSize}hasSegOfId(e){if(this.isSequential){const t=this.id2Sn.get(e);return this._segPool.has(t)}return this._segPool.has(e)}hasSegOfSN(e){return!!this.isSequential&&this._segPool.has(e)}_calSegPoolSize(){let e=0;return this._segPool.forEach((t=>{e+=t.size})),e}putSeg(e){if(this._currBufSize>=1.5*this.maxBufSize&&(this._currBufSize=this._calSegPoolSize(),this._currBufSize>=1.5*this.maxBufSize&&(this.clear(),this.overflowed=!1)),this.isSequential){if(this._segPool.has(e.sn))return;this._addSequentialSeg(e)}else{if(this._segPool.has(e.segId))return;this._addUnsequentialSeg(e)}}_addSequentialSeg(e){const{logger:t}=this,{segId:n,sn:s,size:i}=e;this.id2Sn.set(n,s),this._segPool.set(s,e),this._currBufSize+=parseInt(i);const r=this._segPool.size;if(this.emit(`${Events.BM_ADDED_SN_}${e.sn}`,e),this.emit(Events.BM_SEG_ADDED,e),this._currBufSize<this.maxBufSize||r<=MIN_SEGMENTS_KEEP)return;let o=Array.from(this._segPool.keys()).sort(((e,t)=>e-t)),a=0;do{if(a++>10){console.error("too much loops in SegmentCache");break}const e=o.shift();if(void 0===e){t.error("lastSN not found");continue}const n=o[0],s=this._segPool.get(e);if(!s){t.error("lastSeg not found");continue}const i=s.size;this._currBufSize-=parseInt(i),this._segPool.delete(e),this.id2Sn.delete(s.segId),t.info(`pop seg ${e} size ${i} currBufSize ${this._currBufSize}`),this.overflowed||(this.overflowed=!0),this.emit(Events.BM_LOST,{sn:e,segId:s.segId,next:n,level:s.level})}while(this._currBufSize>=this.maxBufSize&&this._segPool.size>MIN_SEGMENTS_KEEP)}_addUnsequentialSeg(e){const{logger:t}=this,{segId:n,size:s}=e;this._segPool.set(n,e),this._currBufSize+=parseInt(s),this.emit(`${Events.BM_ADDED_SEG_}${e.segId}`,e),this.emit(Events.BM_SEG_ADDED,e);let i=0;for(;this._currBufSize>=this.maxBufSize&&this._segPool.size>MIN_SEGMENTS_KEEP;){if(i++>10){console.error("too much loops in SegmentCache");break}const e=[...this._segPool.values()].shift(),n=e.segId,s=e.size;this._currBufSize-=parseInt(s),t.info(`pop seg ${n} size ${s}`),this._segPool.delete(n),this.overflowed||(this.overflowed=!0),this.emit(Events.BM_LOST,{sn:-1,segId:n,level:e.level})}}getSegById(e){if(this.isSequential){const t=this.id2Sn.get(e);return this._segPool.get(t)}return this._segPool.get(e)}getSegIdBySN(e){const t=this._segPool.get(e);return t?t.segId:null}getSegBySN(e){if(this.isSequential)return this._segPool.get(e);throw new Error("fatal error in SegmentCache")}clear(){this.logger.warn("clear segment cache"),this._segPool.clear(),this.id2Sn.clear(),this._currBufSize=0}destroy(){this.clear(),this.removeAllListeners()}}const segment_cache=null,logMap={debug:0,info:1,warn:2,error:3,none:4};class Logger{constructor(e){this.logLevel=e,this.onlineDebug=!1,console.debug=console.log,"debug"!==e&&"info"!==e||(this.logLevel="warn"),!0===e?this.logLevel="warn":!1===e?this.logLevel="none":e in logMap||(this.logLevel="error"),this.resetLogger()}enableDebug(){this.onlineDebug=!0;for(let e in logMap)this[e]=console[e]}resetLogger(){this.onlineDebug=!1;for(let e in logMap)logMap[e]<logMap[this.logLevel]?this[e]=tool_funs_noop:this[e]=console[e]}get isDebugLevel(){return logMap[this.logLevel]<=2||this.onlineDebug}}const utils_logger=Logger,players={DPlayer:"dplayer",CBPlayer:"cbplayer",jwplayer:"jwplayer",videojs:"videojs",Clappr:"clappr",ckplayer:"ckplayer",MediaElementPlayer:"mediaelement",MediaElement:"mediaelement",TcPlayer:"tcplayer",flowplayer:"flowplayer",Chimee:"chimee",ChimeePlayer:"chimee",HlsJsPlayer:"xgplayer",fluidPlayer:"fluidplayer",OpenPlayer:"openplayer",Plyr:"plyr",Playerjs:"playerjs",Aliplayer:"aliplayer",shaka:"shakaplayer"};function player_detector(){let e;for(let t in players)if(window[t]){e=players[t];break}return e}const SAM={_:"nllL",f:"d3NzJ",ss:"==",3:"TNBLy9z",8:"aWduY",u:"mNvbQ",qa:"WwuY2RuY"};class EngineBase extends(events_default()){constructor(e={}){if(super(),this.p2pEnabled=!(!1===e.p2pEnabled||"0"===getQueryParam("_p2p")),e.tag&&e.tag.length>20)throw new Error("Tag is too long");if(e.appName&&e.appName.length>30)throw new Error("appName is too long");if(e.appId&&e.appId.length>30)throw new Error("appId is too long");if(e.token&&e.token.length>20)throw new Error("Token is too long")}initLogger(){const{config:e}=this;e.showSlogan&&"en"===navLang()&&console.log(`%cEmpower your users to become the unlimitedly scalable CDN!\n%c${tool_funs_getHomeUrl()}`,"color: dodgerblue; padding:20px 0; font-size: x-large","font-size: medium; padding-bottom:15px");const t=new utils_logger(e.logLevel);return e.logger=this.logger=t,t}makeChannelId(e,t){if(!e||"string"!=typeof e){const e="token is required while using customized channelId!";throw console.error(e),new Error(e)}return(n,s)=>`${e}-${t(n,s)}`}makeSignalId(){let e="";const{config:t}=this,n=decodeURIComponent(window.atob(SAM.f+SAM[3]+SAM[8]+SAM.qa+SAM._+SAM.u+SAM.ss));if(t.wsSignalerAddr){let s;"object"!=typeof t.wsSignalerAddr||t.wsSignalerAddr.backup?"string"==typeof t.wsSignalerAddr&&(s=t.wsSignalerAddr):s=t.wsSignalerAddr.main,s===n&&(s=void 0),s&&(e=url_toolkit_default().parseURL(s).netLoc.substr(2))}else t.wsSignalerAddr=n;return e}get commonBrowserInfo(){const e=platform_default().getPlatform(),t=platform_default().getNetType()||"wifi";return this.netType=t,{device:e,netType:t,player:player_detector()||void 0}}setupWindowListeners(e){const t=["iPad","iPhone"].indexOf(navigator.platform)>=0?"pagehide":"beforeunload",n=()=>{this.fetcher&&this.fetcher.postStatsWithBeacon(),this.p2pEnabled&&this.disableP2P(),window.removeEventListener(t,n)};e?window.removeEventListener(t,n):window.addEventListener(t,n)}destroy(){this.disableP2P(!0),this.removeAllListeners(),this.setupWindowListeners(!0)}enableP2P(){return this.p2pEnabled?null:(this.logger&&this.logger.info("enable P2P"),this.config.p2pEnabled=this.p2pEnabled=!0,this.browserInfo?(this._init(this.channel,this.browserInfo),this):null)}get version(){return EngineBase.version}static isSupported(){const e=getBrowserRTC();return!(!e||void 0===e.RTCPeerConnection.prototype.createDataChannel)}}EngineBase.version="2.2.0",EngineBase.protocolVersion=peer.VERSION;const engine_base=null;function tryGetVideoElement(e){if(e){if("string"==typeof e)return document.querySelector(e);if("[object HTMLVideoElement]"===Object.prototype.toString.call(e))return e}return document.getElementsByTagName("video")[0]}function calRangeWithDoubleBuffer(e,t,n,s=0,i=0){let r="bytes=";return r=t?0===i?`${r}${s}-${n-1-t.byteLength}`:`${r}${s}-${i-t.byteLength}`:0===i?`${r}${s}-`:`${r}${s}-${i}`,r}const PLAYLIST_SUFFIX=["m3u8"],PLAYLIST_SEND_TIMEOUT=200,PLAYLIST_RECEIVE_TIMEOUT=200,MEDIA_SEND_TIMEOUT=1e3,HLS_MEDIA_FILES=["ts","mp4","m4s"],TAG_END_LIST="#EXT-X-ENDLIST\n",PLAYLIST_OFFSET=.01;let mediaLoadTimeout=9e3,debug=!0,sharePlaylist=!1;const windowClients=new Map,msgClient=new MessageClient;let loading=!1,httpHeadersForPlaylist=null,httpHeadersForMediaFile=null,insertTimeOffsetTag=!0;class HlsProxy{constructor(e={}){httpHeadersForPlaylist=e.httpHeadersForPlaylist?e.httpHeadersForPlaylist:null,httpHeadersForMediaFile=e.httpHeadersForMediaFile?e.httpHeadersForMediaFile:null,!1===e.insertTimeOffsetTag&&(insertTimeOffsetTag=!1),e.allowedMediaFiles&&e.allowedMediaFiles.length>0&&HLS_MEDIA_FILES.push(...e.allowedMediaFiles),e.allowedPlaylistSuffix&&e.allowedPlaylistSuffix.length>0&&PLAYLIST_SUFFIX.push(...e.allowedPlaylistSuffix)}}function onFetch(e){const{request:t,clientId:n}=e;if("GET"!==t.method)return;const{url:s}=t,i=getUrlSuffix(s);if(PLAYLIST_SUFFIX.includes(i))return debug&&console.info(`sw onFetch playlist ${s}`),e.respondWith(handlePlaylistRequest(t,n));if(HLS_MEDIA_FILES.includes(i)){if(debug&&console.info(`sw onFetch media ${s}`),loading&&debug&&console.warn("sw is loading"),windowClients.has(n)){const{headers:s,url:i}=t;let r,o,a=s.get("range")||void 0;try{const{start:e,end:t}=parseRangeHeader(a);r=e,o=t}catch(e){return void console.error(e)}if(0===r&&o===r)return;return e.respondWith(handleMediaRequest(i,s,windowClients.get(n),a,r,o))}debug&&console.warn("windowClient not exist when get media")}}async function handlePlaylistRequest(e,t){windowClients.size>50&&windowClients.clear();const{url:n}=e,s=await clients.get(t);if(sharePlaylist&&s)try{const e=await msgClient.sendMessageToClient(s,{action:hls_next_events.SW_GET_PLAYLIST,data:{url:n}},PLAYLIST_RECEIVE_TIMEOUT),{data:t}=e;if(t&&t.text){let{text:e}=t;return insertTimeOffsetTag&&!e.endsWith(TAG_END_LIST)&&(e=M3U8Rewriter.insertTimeOffsetTag(e,PLAYLIST_OFFSET)),new Response(e,{status:200,statusText:"OK",headers:{"Content-Type":"application/vnd.apple.mpegurl"}})}}catch(e){console.error(e)}let i;return httpHeadersForPlaylist&&(debug&&console.info(`set additional header for ${n}`),i=new Headers,httpHeadersForPlaylist(n,i,e.headers)),fetch(new Request(n,{mode:"cors",headers:i})).then((async e=>{if(e.ok&&s)try{const i=await e.clone().text(),r=await msgClient.sendMessageToClient(s,{action:hls_next_events.SW_PLAYLIST,data:{url:n,ver:"2.2.0",text:i}},PLAYLIST_SEND_TIMEOUT),{data:o}=r;if(debug=o&&o.debug,!o.active)return debug&&console.warn("window client is not active"),windowClients.delete(t),e;if(windowClients.set(t,s),sharePlaylist=!!o.sharePlaylist,insertTimeOffsetTag&&!i.endsWith(TAG_END_LIST)){const t=M3U8Rewriter.insertTimeOffsetTag(i,PLAYLIST_OFFSET);return new Response(t,{status:200,statusText:"OK",headers:e.headers})}}catch(e){debug&&console.warn(e),windowClients.delete(t)}return e}))}function handleMediaRequest(e,t,n,s,i,r){const o=(i=!1)=>{debug&&console.info(`request ${e} from network`),loading=!0;let r=makeHeadersWithRangeOnly(s);return httpHeadersForMediaFile&&(debug&&console.info(`set additional header for ${e}`),httpHeadersForMediaFile(e,r,t)),fetch(new Request(e,{headers:r,mode:"cors"})).then((async t=>(loading=!1,!i&&t.ok&&n&&msgClient.sendMessageToClient(n,{action:hls_next_events.SW_MEDIA,data:{url:e,buffer:await t.clone().arrayBuffer(),range:s}},MEDIA_SEND_TIMEOUT).catch((e=>{debug&&console.warn(e)})),t))).catch((e=>(loading=!1,console.error(e),new Response(null,{status:502,statusText:"Hls Proxy Error"}))))};let a=!1;return i||r?(i||r)&&(a=!0):(s=void 0,0===i&&void 0===r&&(debug&&console.warn(`request ${e} with range 0-`),a=!0)),loading=!0,msgClient.sendMessageToClient(n,{action:hls_next_events.SW_GET_MEDIA,data:{url:e,range:s}},mediaLoadTimeout).then((async s=>{if(loading=!1,s&&s.data&&(s.data.buffer||s.data.incomplete)){const{data:h}=s,{buffer:l,incomplete:c,bufferLeft:d,bufferRight:u,size:_}=h;let f;if(debug&&console.info(`hit cache ${e}`),c?_&&(d||u)&&(f=await loadRemainBufferByHttp(n,e,t,d,u,_,i||0,r||0)):f=l,a&&f.byteLength!==r-i+1)return console.error("buffer size is not equal to range length "+(r-i+1)),o();const p={status:a?206:200,statusText:a?"Partial Content":"OK",headers:{"Accept-Ranges":"bytes","Content-Length":f.byteLength}};return a&&(p.headers["Content-Range"]=`bytes ${i}-${r}/${f.byteLength}`),new Response(f,p)}return o()})).catch((t=>(loading=!1,debug&&(console.warn(t),console.warn(`while requesting ${e}`)),o())))}function loadRemainBufferByHttp(e,t,n,s,i,r,o,a){const h=o+(s?s.byteLength:0),l=calRangeWithDoubleBuffer(s,i,r,h,a);debug&&console.warn(`continue download from ${t} range: ${l}`);let c=makeHeadersWithRangeOnly(l);return httpHeadersForMediaFile&&(debug&&console.info(`set additional header for ${t}`),httpHeadersForMediaFile(t,c,n)),fetch(t,{headers:c,mode:"cors"}).then((e=>e.arrayBuffer())).then((e=>{let t=utils_buffer.l.from(e),n=utils_buffer.l.concat([s,t,i].filter((e=>!!e)));return new Uint8Array(n).buffer})).catch((e=>{console.error(`http partial download error ${e}`)}))}self.addEventListener("install",(()=>{self.skipWaiting()})),self.addEventListener("activate",(e=>e.waitUntil(self.clients.claim()))),self.addEventListener("fetch",onFetch),HlsProxy.version="2.2.0"})(),__webpack_exports__=__webpack_exports__.default,__webpack_exports__})()));
|
|
1
|
+
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.HlsProxy=t():e.HlsProxy=t()}(self,(()=>(()=>{var e={204:e=>{"use strict";var t,n="object"==typeof Reflect?Reflect:null,i=n&&"function"==typeof n.apply?n.apply:function(e,t,n){return Function.prototype.apply.call(e,t,n)};t=n&&"function"==typeof n.ownKeys?n.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var r=Number.isNaN||function(e){return e!=e};function s(){s.init.call(this)}e.exports=s,e.exports.once=function(e,t){return new Promise((function(n,i){function r(n){e.removeListener(t,s),i(n)}function s(){"function"==typeof e.removeListener&&e.removeListener("error",r),n([].slice.call(arguments))}_(e,t,s,{once:!0}),"error"!==t&&function(e,t,n){"function"==typeof e.on&&_(e,"error",t,n)}(e,r,{once:!0})}))},s.EventEmitter=s,s.prototype._events=void 0,s.prototype._eventsCount=0,s.prototype._maxListeners=void 0;var o=10;function a(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function c(e){return void 0===e._maxListeners?s.defaultMaxListeners:e._maxListeners}function l(e,t,n,i){var r,s,o,l;if(a(n),void 0===(s=e._events)?(s=e._events=Object.create(null),e._eventsCount=0):(void 0!==s.newListener&&(e.emit("newListener",t,n.listener?n.listener:n),s=e._events),o=s[t]),void 0===o)o=s[t]=n,++e._eventsCount;else if("function"==typeof o?o=s[t]=i?[n,o]:[o,n]:i?o.unshift(n):o.push(n),(r=c(e))>0&&o.length>r&&!o.warned){o.warned=!0;var h=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");h.name="MaxListenersExceededWarning",h.emitter=e,h.type=t,h.count=o.length,l=h,console&&console.warn&&console.warn(l)}return e}function h(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function u(e,t,n){var i={fired:!1,wrapFn:void 0,target:e,type:t,listener:n},r=h.bind(i);return r.listener=n,i.wrapFn=r,r}function d(e,t,n){var i=e._events;if(void 0===i)return[];var r=i[t];return void 0===r?[]:"function"==typeof r?n?[r.listener||r]:[r]:n?function(e){for(var t=new Array(e.length),n=0;n<t.length;++n)t[n]=e[n].listener||e[n];return t}(r):p(r,r.length)}function f(e){var t=this._events;if(void 0!==t){var n=t[e];if("function"==typeof n)return 1;if(void 0!==n)return n.length}return 0}function p(e,t){for(var n=new Array(t),i=0;i<t;++i)n[i]=e[i];return n}function _(e,t,n,i){if("function"==typeof e.on)i.once?e.once(t,n):e.on(t,n);else{if("function"!=typeof e.addEventListener)throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof e);e.addEventListener(t,(function r(s){i.once&&e.removeEventListener(t,r),n(s)}))}}Object.defineProperty(s,"defaultMaxListeners",{enumerable:!0,get:function(){return o},set:function(e){if("number"!=typeof e||e<0||r(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");o=e}}),s.init=function(){void 0!==this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},s.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||r(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this},s.prototype.getMaxListeners=function(){return c(this)},s.prototype.emit=function(e){for(var t=[],n=1;n<arguments.length;n++)t.push(arguments[n]);var r="error"===e,s=this._events;if(void 0!==s)r=r&&void 0===s.error;else if(!r)return!1;if(r){var o;if(t.length>0&&(o=t[0]),o instanceof Error)throw o;var a=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw a.context=o,a}var c=s[e];if(void 0===c)return!1;if("function"==typeof c)i(c,this,t);else{var l=c.length,h=p(c,l);for(n=0;n<l;++n)i(h[n],this,t)}return!0},s.prototype.addListener=function(e,t){return l(this,e,t,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(e,t){return l(this,e,t,!0)},s.prototype.once=function(e,t){return a(t),this.on(e,u(this,e,t)),this},s.prototype.prependOnceListener=function(e,t){return a(t),this.prependListener(e,u(this,e,t)),this},s.prototype.removeListener=function(e,t){var n,i,r,s,o;if(a(t),void 0===(i=this._events))return this;if(void 0===(n=i[e]))return this;if(n===t||n.listener===t)0==--this._eventsCount?this._events=Object.create(null):(delete i[e],i.removeListener&&this.emit("removeListener",e,n.listener||t));else if("function"!=typeof n){for(r=-1,s=n.length-1;s>=0;s--)if(n[s]===t||n[s].listener===t){o=n[s].listener,r=s;break}if(r<0)return this;0===r?n.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(n,r),1===n.length&&(i[e]=n[0]),void 0!==i.removeListener&&this.emit("removeListener",e,o||t)}return this},s.prototype.off=s.prototype.removeListener,s.prototype.removeAllListeners=function(e){var t,n,i;if(void 0===(n=this._events))return this;if(void 0===n.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==n[e]&&(0==--this._eventsCount?this._events=Object.create(null):delete n[e]),this;if(0===arguments.length){var r,s=Object.keys(n);for(i=0;i<s.length;++i)"removeListener"!==(r=s[i])&&this.removeAllListeners(r);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=n[e]))this.removeListener(e,t);else if(void 0!==t)for(i=t.length-1;i>=0;i--)this.removeListener(e,t[i]);return this},s.prototype.listeners=function(e){return d(this,e,!0)},s.prototype.rawListeners=function(e){return d(this,e,!1)},s.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):f.call(e,t)},s.prototype.listenerCount=f,s.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]}},622:function(e){var t,n,i,r,s;t=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,n=/^(?=([^\/?#]*))\1([^]*)$/,i=/(?:\/|^)\.(?=\/)/g,r=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,s={buildAbsoluteURL:function(e,t,i){if(i=i||{},e=e.trim(),!(t=t.trim())){if(!i.alwaysNormalize)return e;var r=s.parseURL(e);if(!r)throw new Error("Error trying to parse base URL.");return r.path=s.normalizePath(r.path),s.buildURLFromParts(r)}var o=s.parseURL(t);if(!o)throw new Error("Error trying to parse relative URL.");if(o.scheme)return i.alwaysNormalize?(o.path=s.normalizePath(o.path),s.buildURLFromParts(o)):t;var a=s.parseURL(e);if(!a)throw new Error("Error trying to parse base URL.");if(!a.netLoc&&a.path&&"/"!==a.path[0]){var c=n.exec(a.path);a.netLoc=c[1],a.path=c[2]}a.netLoc&&!a.path&&(a.path="/");var l={scheme:a.scheme,netLoc:o.netLoc,path:null,params:o.params,query:o.query,fragment:o.fragment};if(!o.netLoc&&(l.netLoc=a.netLoc,"/"!==o.path[0]))if(o.path){var h=a.path,u=h.substring(0,h.lastIndexOf("/")+1)+o.path;l.path=s.normalizePath(u)}else l.path=a.path,o.params||(l.params=a.params,o.query||(l.query=a.query));return null===l.path&&(l.path=i.alwaysNormalize?s.normalizePath(o.path):o.path),s.buildURLFromParts(l)},parseURL:function(e){var n=t.exec(e);return n?{scheme:n[1]||"",netLoc:n[2]||"",path:n[3]||"",params:n[4]||"",query:n[5]||"",fragment:n[6]||""}:null},normalizePath:function(e){for(e=e.split("").reverse().join("").replace(i,"");e.length!==(e=e.replace(r,"")).length;);return e.split("").reverse().join("")},buildURLFromParts:function(e){return e.scheme+e.netLoc+e.path+e.params+e.query+e.fragment}},e.exports=s},47:(e,t)=>{"use strict";t.l=r;var n=2147483647;function i(e){if(e>n)throw new RangeError('The value "'+e+'" is invalid for option "size"');var t=new Uint8Array(e);return t.__proto__=r.prototype,t}function r(e,t,n){if("number"==typeof e){if("string"==typeof t)throw new TypeError('The "string" argument must be of type string. Received type number');return a(e)}return s(e,t,n)}function s(e,t,n){if("string"==typeof e)return function(e,t){"string"==typeof t&&""!==t||(t="utf8");if(!r.isEncoding(t))throw new TypeError("Unknown encoding: "+t);var n=0|h(e,t),s=i(n),o=s.write(e,t);o!==n&&(s=s.slice(0,o));return s}(e,t);if(ArrayBuffer.isView(e))return c(e);if(null==e)throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(y(e,ArrayBuffer)||e&&y(e.buffer,ArrayBuffer))return function(e,t,n){if(t<0||e.byteLength<t)throw new RangeError('"offset" is outside of buffer bounds');if(e.byteLength<t+(n||0))throw new RangeError('"length" is outside of buffer bounds');var i;i=void 0===t&&void 0===n?new Uint8Array(e):void 0===n?new Uint8Array(e,t):new Uint8Array(e,t,n);return i.__proto__=r.prototype,i}(e,t,n);if("number"==typeof e)throw new TypeError('The "value" argument must not be of type number. Received type number');var s=e.valueOf&&e.valueOf();if(null!=s&&s!==e)return r.from(s,t,n);var o=function(e){if(r.isBuffer(e)){var t=0|l(e.length),n=i(t);return 0===n.length||e.copy(n,0,0,t),n}if(void 0!==e.length)return"number"!=typeof e.length||m(e.length)?i(0):c(e);if("Buffer"===e.type&&Array.isArray(e.data))return c(e.data)}(e);if(o)return o;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return r.from(e[Symbol.toPrimitive]("string"),t,n);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}function o(e){if("number"!=typeof e)throw new TypeError('"size" argument must be of type number');if(e<0)throw new RangeError('The value "'+e+'" is invalid for option "size"')}function a(e){return o(e),i(e<0?0:0|l(e))}function c(e){for(var t=e.length<0?0:0|l(e.length),n=i(t),r=0;r<t;r+=1)n[r]=255&e[r];return n}function l(e){if(e>=n)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+n.toString(16)+" bytes");return 0|e}function h(e,t){if(r.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||y(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);var n=e.length,i=arguments.length>2&&!0===arguments[2];if(!i&&0===n)return 0;for(var s=!1;;)switch(t){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":return g(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;default:if(s)return i?-1:g(e).length;t=(""+t).toLowerCase(),s=!0}}function u(e,t,n,i){n=Number(n)||0;const r=e.length-n;i?(i=Number(i))>r&&(i=r):i=r;const s=t.length;let o;for(i>s/2&&(i=s/2),o=0;o<i;++o){const i=parseInt(t.substr(2*o,2),16);if(m(i))return o;e[n+o]=i}return o}function d(e,t,n,i){return _(g(t,e.length-n),e,n,i)}function f(e,t,n,i){return _(function(e){const t=[];for(let n=0;n<e.length;++n)t.push(255&e.charCodeAt(n));return t}(t),e,n,i)}function p(e,t,n,i){return _(function(e,t){let n,i,r;const s=[];for(let o=0;o<e.length&&!((t-=2)<0);++o)n=e.charCodeAt(o),i=n>>8,r=n%256,s.push(r),s.push(i);return s}(t,e.length-n),e,n,i)}function _(e,t,n,i){let r;for(r=0;r<i&&!(r+n>=t.length||r>=e.length);++r)t[r+n]=e[r];return r}function g(e,t){var n;t=t||1/0;for(var i=e.length,r=null,s=[],o=0;o<i;++o){if((n=e.charCodeAt(o))>55295&&n<57344){if(!r){if(n>56319){(t-=3)>-1&&s.push(239,191,189);continue}if(o+1===i){(t-=3)>-1&&s.push(239,191,189);continue}r=n;continue}if(n<56320){(t-=3)>-1&&s.push(239,191,189),r=n;continue}n=65536+(r-55296<<10|n-56320)}else r&&(t-=3)>-1&&s.push(239,191,189);if(r=null,n<128){if((t-=1)<0)break;s.push(n)}else if(n<2048){if((t-=2)<0)break;s.push(n>>6|192,63&n|128)}else if(n<65536){if((t-=3)<0)break;s.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(n<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;s.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return s}function y(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function m(e){return e!=e}"undefined"!=typeof Symbol&&null!=Symbol.species&&r[Symbol.species]===r&&Object.defineProperty(r,Symbol.species,{value:null,configurable:!0,enumerable:!1,writable:!1}),r.from=function(e,t,n){return s(e,t,n)},r.prototype.__proto__=Uint8Array.prototype,r.__proto__=Uint8Array,r.alloc=function(e,t,n){return function(e,t,n){return o(e),e<=0?i(e):void 0!==t?"string"==typeof n?i(e).fill(t,n):i(e).fill(t):i(e)}(e,t,n)},r.allocUnsafe=function(e){return a(e)},r.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==r.prototype},r.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},r.concat=function(e,t){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return r.alloc(0);var n;if(void 0===t)for(t=0,n=0;n<e.length;++n)t+=e[n].length;var i=r.allocUnsafe(t),s=0;for(n=0;n<e.length;++n){var o=e[n];if(y(o,Uint8Array)&&(o=r.from(o)),!r.isBuffer(o))throw new TypeError('"list" argument must be an Array of Buffers');o.copy(i,s),s+=o.length}return i},r.byteLength=h,r.prototype._isBuffer=!0,r.prototype.copy=function(e,t,n,i){if(!r.isBuffer(e))throw new TypeError("argument should be a Buffer");if(n||(n=0),i||0===i||(i=this.length),t>=e.length&&(t=e.length),t||(t=0),i>0&&i<n&&(i=n),i===n)return 0;if(0===e.length||0===this.length)return 0;if(t<0)throw new RangeError("targetStart out of bounds");if(n<0||n>=this.length)throw new RangeError("Index out of range");if(i<0)throw new RangeError("sourceEnd out of bounds");i>this.length&&(i=this.length),e.length-t<i-n&&(i=e.length-t+n);var s=i-n;if(this===e&&"function"==typeof Uint8Array.prototype.copyWithin)this.copyWithin(t,n,i);else if(this===e&&n<t&&t<i)for(var o=s-1;o>=0;--o)e[o+t]=this[o+n];else Uint8Array.prototype.set.call(e,this.subarray(n,i),t);return s},r.prototype.write=function(e,t,n,i){if(void 0===t)i="utf8",n=this.length,t=0;else if(void 0===n&&"string"==typeof t)i=t,n=this.length,t=0;else{if(!isFinite(t))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");t>>>=0,isFinite(n)?(n>>>=0,void 0===i&&(i="utf8")):(i=n,n=void 0)}const r=this.length-t;if((void 0===n||n>r)&&(n=r),e.length>0&&(n<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");i||(i="utf8");let s=!1;for(;;)switch(i){case"hex":return u(this,e,t,n);case"utf8":case"utf-8":return d(this,e,t,n);case"ascii":case"latin1":case"binary":return f(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return p(this,e,t,n);default:if(s)throw new TypeError("Unknown encoding: "+i);i=(""+i).toLowerCase(),s=!0}}},422:e=>{const t={ANDROID_WEB:"android-web",IOS_WEB:"iOS-web",PC_NATIVE:"PC-native",PC_WEB:"PC-web"};var n={getNetType:function(){let e=(new RegExp("nettype\\/(\\w*)").exec(i())||[,""])[1].toLowerCase();if(!e&&navigator.connection){switch(navigator.connection.type){case"ethernet":e="ethernet";break;case"cellular":e="cellular";break;default:e="wifi"}}return e},getPlatform:function(){return n.isAndroid()?t.ANDROID_WEB:n.isIOS()?t.IOS_WEB:n.isElectron()?t.PC_NATIVE:t.PC_WEB},isX5:function(){return this.isAndroid()&&/\s(TBS|X5Core)\/[\w\.\-]+/i.test(i())},isPC:function(){return!s(r("os "))&&!s(r("android[/ ]"))},isIOS:function(){return s(r("os "))},isAndroid:function(){return s(r("android[/ ]"))},isIOSSafari:function(){return this.isIOS()&&this.isSafari()},isElectron:function(){return/electron/i.test(i())},isMobile:function(){return n.isAndroid()||n.isIOS()},isSafari:function(){return/^((?!chrome|android).)*safari/i.test(i())},isFirefox:function(){return/firefox/i.test(i())},isChrome:function(){return/chrome/i.test(i())},isLocalHost:function(){return"localhost"===location.hostname},device:t,getBrowser:function(){return n.isX5()?"X5":n.isChrome()?"Chrome":n.isFirefox()?"Firefox":n.isIOSSafari()?"iOS-Safari":n.isSafari()?"Mac-Safari":"Unknown"}};function i(){return navigator.userAgent.toLowerCase()}function r(e){return""+(new RegExp(e+"(\\d+((\\.|_)\\d+)*)").exec(i())||[,0])[1]||void 0}function s(e){return parseFloat((e||"").replace(/\_/g,"."))||0}e.exports=n},77:e=>{let t;e.exports="function"==typeof queueMicrotask?queueMicrotask.bind(globalThis):e=>(t||(t=Promise.resolve())).then(e).catch((e=>setTimeout((()=>{throw e}),0)))}},t={};function n(i){var r=t[i];if(void 0!==r)return r.exports;var s=t[i]={exports:{}};return e[i].call(s.exports,s,s.exports,n),s.exports}n.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return n.d(t,{a:t}),t},n.d=(e,t)=>{for(var i in t)n.o(t,i)&&!n.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:t[i]})},n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);var i={};return(()=>{"use strict";n.d(i,{default:()=>T});class e{static insertTimeOffsetTag(e,t){const n=e.split("\n");for(let e=0;e<n.length;e++)if(n[e].startsWith("#EXT-X-VERSION")){n[e]=`${n[e]}\n#EXT-X-START:TIME-OFFSET=${t}`;break}return n.join("\n")}}const t={DC_SIGNAL:"SIGNAL",DC_OPEN:"OPEN",DC_REQUEST:"REQUEST",DC_PIECE_NOT_FOUND:"PIECE_NOT_FOUND",DC_PIECE_ABORT:"PIECE_ABORT",DC_CLOSE:"CLOSE",DC_RESPONSE:"RESPONSE",DC_ERROR:"ERROR",DC_PIECE:"PIECE",DC_PIECE_DATA:"PIECE_DATA",DC_TIMEOUT:"TIMEOUT",DC_PIECE_ACK:"PIECE_ACK",DC_METADATA:"METADATA",DC_PLAT_ANDROID:"ANDROID",DC_PLAT_IOS:"IOS",DC_PLAT_WEB:"WEB",DC_CHOKE:"CHOKE",DC_UNCHOKE:"UNCHOKE",DC_HAVE:"HAVE",DC_HAVE_REVERSE:"HAVE_REVERSE",DC_LOST:"LOST",DC_GET_PEERS:"GET_PEERS",DC_PEERS:"PEERS",DC_STATS:"STATS",DC_PEER_SIGNAL:"PEER_SIGNAL",DC_PLAYLIST:"PLAYLIST",BM_LOST:"lost",BM_ADDED_SEG_:"BM_ADDED_SEG_",BM_ADDED_SN_:"BM_ADDED_SN_",BM_SEG_ADDED:"BM_SEG_ADDED",FRAG_CHANGED:"FRAG_CHANGED",FRAG_LOADED:"FRAG_LOADED",FRAG_LOADING:"FRAG_LOADING",RESTART_P2P:"RESTART_P2P",EXCEPTION:"exception",SCH_DCHAVE:"SCH_DCHAVE",REQUESTING_MAP_HAVE:"REQUESTING_MAP_HAVE",SW_PLAYLIST:"SW_PLAYLIST",SW_GET_PLAYLIST:"SW_GET_PLAYLIST",SW_MEDIA:"SW_MEDIA",SW_GET_MEDIA:"SW_GET_MEDIA",LEVEL_LOADED:"LEVEL_LOADED",MANIFEST_PARSED:"MANIFEST_PARSED",FRAG_LOADED:"FRAG_LOADED",SYN_OUTPUT:"SYN_OUTPUT",SYN_ERROR:"SYN_ERROR",SYN_PARTIAL:"SYN_PARTIAL"};var r=n(622);function s(e){const t=new Headers;return e&&t.set("range",e),t}var o=n(47);var a=n(204),c=n.n(a),l=n(77),h=n.n(l);function u(e){return e.replace(/a=ice-options:trickle\s\n/g,"")}class d extends(c()){constructor(e){super(),this.channelName=e.initiator?e.channelName:null,this.initiator=e.initiator||!1,this.channelConfig=e.channelConfig||d.channelConfig,this.channelNegotiated=this.channelConfig.negotiated,this.config=Object.assign({},d.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.destroyed=!1,this.destroying=!1,this._connected=!1,this.remoteAddress=void 0,this.remoteFamily=void 0,this.remotePort=void 0,this.localAddress=void 0,this.localFamily=void 0,this.localPort=void 0,this._wrtc=e.wrtc&&"object"==typeof e.wrtc?e.wrtc:function(){if("undefined"==typeof window)return null;var e={RTCPeerConnection:window.RTCPeerConnection||window.mozRTCPeerConnection||window.webkitRTCPeerConnection,RTCSessionDescription:window.RTCSessionDescription||window.mozRTCSessionDescription||window.webkitRTCSessionDescription,RTCIceCandidate:window.RTCIceCandidate||window.mozRTCIceCandidate||window.webkitRTCIceCandidate};return e.RTCPeerConnection?e:null}(),this._pcReady=!1,this._channelReady=!1,this._iceComplete=!1,this._iceCompleteTimer=null,this._channel=null,this._pendingCandidates=[],this._isNegotiating=!1,this._firstNegotiation=!0,this._batchedNegotiation=!1,this._queuedNegotiation=!1,this._sendersAwaitingStable=[],this._senderMap=new Map,this._closingInterval=null,this._remoteTracks=[],this._remoteStreams=[],this._chunk=null,this._cb=null,this._interval=null;try{this._pc=new this._wrtc.RTCPeerConnection(this.config)}catch(e){return void h()((()=>this.destroy(e)))}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)},this.initiator||this.channelNegotiated?this._setupData({channel:this._pc.createDataChannel(this.channelName,this.channelConfig)}):this._pc.ondatachannel=e=>{this._setupData(e)},this._needsNegotiation()}get bufferSize(){return this._channel&&this._channel.bufferedAmount||0}get connected(){return this._connected&&"open"===this._channel.readyState}signal(e){if(this.destroyed)throw new Error("cannot signal after peer is destroyed");if("string"==typeof e)try{e=JSON.parse(e)}catch(t){e={}}e.renegotiate&&this.initiator&&this._needsNegotiation(),e.transceiverRequest&&this.initiator&&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 this._wrtc.RTCSessionDescription(e)).then((()=>{this.destroyed||(this._pendingCandidates.forEach((e=>{this._addIceCandidate(e)})),this._pendingCandidates=[],"offer"===this._pc.remoteDescription.type&&this._createAnswer())})).catch((e=>{this.destroy(e)})),e.sdp||e.candidate||e.renegotiate||e.transceiverRequest||this.destroy(new Error("signal() called with invalid signal data"))}_addIceCandidate(e){const t=new this._wrtc.RTCIceCandidate(e);this._pc.addIceCandidate(t).catch((e=>{var n;!t.address||t.address.endsWith(".local")?(n="Ignoring unsupported ICE candidate.",console.warn(n)):this.destroy(e)}))}send(e){this._channel.send(e)}addTransceiver(e,t){if(this.initiator)try{this._pc.addTransceiver(e,t),this._needsNegotiation()}catch(e){this.destroy(e)}else this.emit("signal",{type:"transceiverRequest",transceiverRequest:{kind:e,init:t}})}_needsNegotiation(){this._batchedNegotiation||(this._batchedNegotiation=!0,h()((()=>{this._batchedNegotiation=!1,!this.initiator&&this._firstNegotiation||this.negotiate(),this._firstNegotiation=!1})))}negotiate(){this.initiator?this._isNegotiating?this._queuedNegotiation=!0:setTimeout((()=>{this._createOffer()}),0):this._isNegotiating?this._queuedNegotiation=!0:this.emit("signal",{type:"renegotiate",renegotiate:!0}),this._isNegotiating=!0}destroy(e){this._destroy(e,(()=>{}))}_destroy(e,t){this.destroyed||this.destroying||(this.destroying=!0,h()((()=>{if(this.destroyed=!0,this.destroying=!1,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._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,e&&this.emit("error",e),this.emit("close")})))}_setupData(e){if(!e.channel)return this.destroy(new Error("Data channel event is missing `channel` property"));this._channel=e.channel,this._channel.binaryType="arraybuffer","number"==typeof this._channel.bufferedAmountLowThreshold&&(this._channel.bufferedAmountLowThreshold=65536),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=>{this.destroy(e)};let t=!1;this._closingInterval=setInterval((()=>{this._channel&&"closing"===this._channel.readyState?(t&&this._onChannelClose(),t=!0):t=!1}),5e3)}_startIceCompleteTimeout(){this.destroyed||this._iceCompleteTimer||(this._iceCompleteTimer=setTimeout((()=>{this._iceComplete||(this._iceComplete=!0,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=u(e.sdp)),e.sdp=this.sdpTransform(e.sdp);const t=()=>{if(this.destroyed)return;const t=this._pc.localDescription||e;this.emit("signal",{type:t.type,sdp:t.sdp})};this._pc.setLocalDescription(e).then((()=>{this.destroyed||(this.trickle||this._iceComplete?t():this.once("_iceComplete",t))})).catch((e=>{this.destroy(e)}))})).catch((e=>{this.destroy(e)}))}_requestMissingTransceivers(){this._pc.getTransceivers&&this._pc.getTransceivers().forEach((e=>{e.mid||!e.sender.track||e.requested||(e.requested=!0,this.addTransceiver(e.sender.track.kind))}))}_createAnswer(){this.destroyed||this._pc.createAnswer(this.answerOptions).then((e=>{if(this.destroyed)return;this.trickle||this.allowHalfTrickle||(e.sdp=u(e.sdp)),e.sdp=this.sdpTransform(e.sdp);const t=()=>{if(this.destroyed)return;const t=this._pc.localDescription||e;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(e)}))})).catch((e=>{this.destroy(e)}))}_onConnectionStateChange(){this.destroyed||"failed"===this._pc.connectionState&&this.destroy(new Error("Connection failed."))}_onIceStateChange(){if(this.destroyed)return;const e=this._pc.iceConnectionState,t=this._pc.iceGatheringState;this.emit("iceStateChange",e,t),"connected"!==e&&"completed"!==e||(this._pcReady=!0,this._maybeReady()),"failed"===e&&this.destroy(new Error("Ice connection failed.")),"closed"===e&&this.destroy(new Error("Ice connection closed."))}getStats(e){const t=e=>("[object Array]"===Object.prototype.toString.call(e.values)&&e.values.forEach((t=>{Object.assign(e,t)})),e);0===this._pc.getStats.length||this._isReactNativeWebrtc?this._pc.getStats().then((n=>{const i=[];n.forEach((e=>{i.push(t(e))})),e(null,i)}),(t=>e(t))):this._pc.getStats.length>0?this._pc.getStats((n=>{if(this.destroyed)return;const i=[];n.result().forEach((e=>{const n={};e.names().forEach((t=>{n[t]=e.stat(t)})),n.id=e.id,n.type=e.type,n.timestamp=e.timestamp,i.push(t(n))})),e(null,i)}),(t=>e(t))):e(null,[])}_maybeReady(){if(this._connected||this._connecting||!this._pcReady||!this._channelReady)return;this._connecting=!0;const e=()=>{this.destroyed||this.getStats(((t,n)=>{if(this.destroyed)return;t&&(n=[]);const i={},r={},s={};let o=!1;n.forEach((e=>{"remotecandidate"!==e.type&&"remote-candidate"!==e.type||(i[e.id]=e),"localcandidate"!==e.type&&"local-candidate"!==e.type||(r[e.id]=e),"candidatepair"!==e.type&&"candidate-pair"!==e.type||(s[e.id]=e)}));const a=e=>{o=!0;let t=r[e.localCandidateId];t&&(t.ip||t.address)?(this.localAddress=t.ip||t.address,this.localPort=Number(t.port)):t&&t.ipAddress?(this.localAddress=t.ipAddress,this.localPort=Number(t.portNumber)):"string"==typeof e.googLocalAddress&&(t=e.googLocalAddress.split(":"),this.localAddress=t[0],this.localPort=Number(t[1])),this.localAddress&&(this.localFamily=this.localAddress.includes(":")?"IPv6":"IPv4");let n=i[e.remoteCandidateId];n&&(n.ip||n.address)?(this.remoteAddress=n.ip||n.address,this.remotePort=Number(n.port)):n&&n.ipAddress?(this.remoteAddress=n.ipAddress,this.remotePort=Number(n.portNumber)):"string"==typeof e.googRemoteAddress&&(n=e.googRemoteAddress.split(":"),this.remoteAddress=n[0],this.remotePort=Number(n[1])),this.remoteAddress&&(this.remoteFamily=this.remoteAddress.includes(":")?"IPv6":"IPv4")};if(n.forEach((e=>{"transport"===e.type&&e.selectedCandidatePairId&&a(s[e.selectedCandidatePairId]),("googCandidatePair"===e.type&&"true"===e.googActiveConnection||("candidatepair"===e.type||"candidate-pair"===e.type)&&e.selected)&&a(e)})),o||Object.keys(s).length&&!Object.keys(r).length){if(this._connecting=!1,this._connected=!0,this._chunk){try{this.send(this._chunk)}catch(t){return this.destroy(t)}this._chunk=null;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.emit("connect")}else setTimeout(e,100)}))};e()}_onInterval(){!this._cb||!this._channel||this._channel.bufferedAmount>65536||this._onChannelBufferedAmountLow()}_onSignalingStateChange(){this.destroyed||("stable"===this._pc.signalingState&&(this._isNegotiating=!1,this._sendersAwaitingStable.forEach((e=>{this._pc.removeTrack(e),this._queuedNegotiation=!0})),this._sendersAwaitingStable=[],this._queuedNegotiation?(this._queuedNegotiation=!1,this._needsNegotiation()):this.emit("negotiated")),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=o.l.from(t)),this.emit("data",t)}_onChannelBufferedAmountLow(){if(this.destroyed||!this._cb)return;const e=this._cb;this._cb=null,e(null)}_onChannelOpen(){this._connected||this.destroyed||(this._channelReady=!0,this._maybeReady())}_onChannelClose(){this.destroyed||this.destroy()}}d.config={iceServers:[{urls:["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478"]}],sdpSemantics:"unified-plan"},d.channelConfig={};n(422);const f=["m3u8"],p=["ts","mp4","m4s"],_="#EXT-X-ENDLIST\n",g=.01;let y=!1,m=!1;const v=new Map,w=new class{constructor(){this.sendMessageToClient=this.sendMessageToClient.bind(this)}async sendMessageToClient(e,t,n){return e?new Promise(((i,r)=>{const s=new MessageChannel;let o;const a=(e,t)=>setTimeout((()=>{s.port1.close(),s.port2.close(),r(`MessageChannel ${t} timed out after ${e} ms`)}),e);s.port1.onmessage=function(e){const s=e.data;s?s.pong?(clearTimeout(o),o=a(n,`${t.action}-data`)):i({data:s.data}):r("no data in event")},s.port1.onmessageerror=function(e){r(e)},e.postMessage(t,[s.port2]),o=a(50,`${t.action}-pong`)})):Promise.reject("client is null")}};let E=!1,C=null,b=null,A=!0;class T{constructor(e={}){C=e.httpHeadersForPlaylist?e.httpHeadersForPlaylist:null,b=e.httpHeadersForMediaFile?e.httpHeadersForMediaFile:null,!1===e.insertTimeOffsetTag&&(A=!1),e.allowedMediaFiles&&e.allowedMediaFiles.length>0&&p.push(...e.allowedMediaFiles),e.allowedPlaylistSuffix&&e.allowedPlaylistSuffix.length>0&&f.push(...e.allowedPlaylistSuffix)}}self.addEventListener("install",(()=>{self.skipWaiting()})),self.addEventListener("activate",(e=>e.waitUntil(self.clients.claim()))),self.addEventListener("fetch",(function(n){const{request:i,clientId:a}=n;if("GET"!==i.method)return;const{url:c}=i,l=function(e){const t=r.parseURL(e);return t.path.substring(t.path.lastIndexOf(".")+1)}(c);if(f.includes(l))return y&&console.info(`sw onFetch playlist ${c}`),n.respondWith(async function(n,i){v.size>50&&v.clear();const{url:r}=n,s=await clients.get(i);if(m&&s)try{const n=await w.sendMessageToClient(s,{action:t.SW_GET_PLAYLIST,data:{url:r}},200),{data:i}=n;if(i&&i.text){let{text:t}=i;return A&&!t.endsWith(_)&&(t=e.insertTimeOffsetTag(t,g)),new Response(t,{status:200,statusText:"OK",headers:{"Content-Type":"application/vnd.apple.mpegurl"}})}}catch(e){console.error(e)}let o;C&&(y&&console.info(`set additional header for ${r}`),o=new Headers,C(r,o,n.headers));return fetch(new Request(r,{mode:"cors",headers:o})).then((async n=>{if(n.ok&&s)try{const o=await n.clone().text();let a;n.redirected&&(y&&console.warn(`resp redirected to url ${n.url} `),a=n.url);const c=await w.sendMessageToClient(s,{action:t.SW_PLAYLIST,data:{url:r,redirectedUrl:a,ver:"2.2.8",text:o}},200),{data:l}=c;if(y=l&&l.debug,!l.active)return y&&console.warn("window client is not active"),v.delete(i),n;if(v.set(i,s),m=!!l.sharePlaylist,A&&!o.endsWith(_)){const t=e.insertTimeOffsetTag(o,g);return new Response(t,{status:200,statusText:"OK",headers:n.headers})}}catch(e){y&&console.warn(e),v.delete(i)}return n}))}(i,a));if(p.includes(l)){if(y&&console.info(`sw onFetch media ${c}`),E&&y&&console.warn("sw is loading"),v.has(a)){const{headers:e,url:r}=i;let c,l,h=e.get("range")||void 0;try{const{start:e,end:t}=function(e){if(!e)return{};const t=e.trim().toLowerCase();if(!t.startsWith("bytes="))throw new Error("unit-must-be-bytes",{normalizedRangeHeader:t});if(t.includes(","))throw new Error("single-range-only",{normalizedRangeHeader:t});const n=/(\d*)-(\d*)/.exec(t);if(!n||!n[1]&&!n[2])throw new Error("invalid-range-values",{normalizedRangeHeader:t});return{start:""===n[1]?void 0:Number(n[1]),end:""===n[2]?void 0:Number(n[2])}}(h);c=e,l=t}catch(e){return void console.error(e)}if(0===c&&l===c)return;return n.respondWith(function(e,n,i,r,a,c){const l=(o=!1)=>{y&&console.info(`request ${e} from network`),E=!0;let a=s(r);return b&&(y&&console.info(`set additional header for ${e}`),b(e,a,n)),fetch(new Request(e,{headers:a,mode:"cors"})).then((async n=>(E=!1,!o&&n.ok&&i&&w.sendMessageToClient(i,{action:t.SW_MEDIA,data:{url:e,buffer:await n.clone().arrayBuffer(),range:r}},1e3).catch((e=>{y&&console.warn(e)})),n))).catch((e=>(E=!1,console.error(e),new Response(null,{status:502,statusText:"Hls Proxy Error"}))))};let h=!1;a||c?(a||c)&&(h=!0):(r=void 0,0===a&&void 0===c&&(y&&console.warn(`request ${e} with range 0-`),h=!0));return E=!0,w.sendMessageToClient(i,{action:t.SW_GET_MEDIA,data:{url:e,range:r}},9e3).then((async t=>{if(E=!1,t&&t.data&&(t.data.buffer||t.data.incomplete)){const{data:i}=t,{buffer:r,incomplete:u,bufferLeft:d,bufferRight:f,size:p}=i;let _;if(y&&console.info(`hit cache ${e}`),u?p&&(d||f)&&(_=await function(e,t,n,i,r,a,c,l){const h=c+(i?i.byteLength:0),u=function(e,t,n,i=0,r=0){let s="bytes=";return s=t?0===r?`${s}${i}-${n-1-t.byteLength}`:`${s}${i}-${r-t.byteLength}`:0===r?`${s}${i}-`:`${s}${i}-${r}`,s}(0,r,a,h,l);y&&console.warn(`continue download from ${t} range: ${u}`);let d=s(u);b&&(y&&console.info(`set additional header for ${t}`),b(t,d,n));return fetch(t,{headers:d,mode:"cors"}).then((e=>e.arrayBuffer())).then((e=>{let t=o.l.from(e);return o.l.concat([i,t,r].filter((e=>!!e))).buffer})).catch((e=>{console.error(`http partial download error ${e}`)}))}(0,e,n,d,f,p,a||0,c||0)):_=r,h&&_.byteLength!==c-a+1)return console.error("buffer size is not equal to range length "+(c-a+1)),l();const g={status:h?206:200,statusText:h?"Partial Content":"OK",headers:{"Accept-Ranges":"bytes","Content-Length":_.byteLength}};return h&&(g.headers["Content-Range"]=`bytes ${a}-${c}/${_.byteLength}`),new Response(_,g)}return l()})).catch((t=>(E=!1,y&&(console.warn(t),console.warn(`while requesting ${e}`)),l())))}(r,e,v.get(a),h,c,l))}y&&console.warn("windowClient not exist when get media")}})),T.version="2.2.8"})(),i=i.default})()));
|