rtsp2web 3.1.6 → 3.1.7
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 +19 -19
- package/dist/rtsp2web.js +3 -3
- package/dist/rtsp2web.min.js +3 -3
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -10,8 +10,8 @@
|
|
|
10
10
|
|
|
11
11
|
- 上手简单,提供的示例代码完整可运行,无需繁琐复杂的技术负担,直接运行代码,快速解决视频流播放的问题;
|
|
12
12
|
- 延时非常低,视频流稳定,几乎是实时的,满足任何需求;不花钱,采用开源框架,无商业风险;
|
|
13
|
-
- 别的收费平台,需要暴露 RTSP 视频流链接给收费平台,rtsp2web 无需您提供 RTSP
|
|
14
|
-
- 高效兼容,大多数 nvr 或 ipc 或摄像头平台都支持输出 RTSP 视频流,rtsp2web 把 RTSP
|
|
13
|
+
- 别的收费平台,需要暴露 RTSP 视频流链接给收费平台,rtsp2web 无需您提供 RTSP 视频流,您的保密和安全牢牢掌握在您手中;
|
|
14
|
+
- 高效兼容,大多数 nvr 或 ipc 或摄像头平台都支持输出 RTSP 视频流,rtsp2web 把 RTSP 视频流转换到页面可播放,减少对接工作,无论您是什么摄像头;
|
|
15
15
|
- 支持前端使用 `jsmpeg.js`、`flv.js` 等播放器,满足不同技术栈团队使用;
|
|
16
16
|
- 删繁就简,无需插件就可在浏览器显示视频画面,兼容各大浏览器厂商;
|
|
17
17
|
- 省时省力,同一页面可以播放不同厂家的视频,无需任何额外操作,轻松支持多路视频同时播放;
|
|
@@ -29,7 +29,7 @@ FFmpeg 是一套可以用来记录、转换数字音频、视频,并能将其
|
|
|
29
29
|
|
|
30
30
|
**确保在你要运行 rtsp2web 的机器上已经安装了 FFmpeg。**
|
|
31
31
|
|
|
32
|
-
> _新打开一个命令行窗口,输入:ffmpeg -version ,如果有相关信息输出,则证明 FFmpeg 的安装是 OK 的。
|
|
32
|
+
> _新打开一个命令行窗口,输入:ffmpeg -version ,如果有相关信息输出,则证明 FFmpeg 的安装是 OK 的。_
|
|
33
33
|
|
|
34
34
|
<br>
|
|
35
35
|
|
|
@@ -66,17 +66,17 @@ new RTSP2web({
|
|
|
66
66
|
|
|
67
67
|
4.1、参数说明(在 `new RTSP2web` 时,可配置的参数如下:)
|
|
68
68
|
|
|
69
|
-
| 参数 |
|
|
70
|
-
| :-----------: |
|
|
71
|
-
| port |
|
|
72
|
-
| path |
|
|
73
|
-
| audio |
|
|
74
|
-
| freeTime |
|
|
75
|
-
| checkTime |
|
|
76
|
-
| q |
|
|
77
|
-
| transportType | 设置 RTSP 传输协议,默认值:无<br/>可选值:['tcp', 'udp', 'udp_multicast', 'http', 'https']<br/>ps: 这里默认值是无,也就是 rtsp2web
|
|
78
|
-
| webplayer |
|
|
79
|
-
| wss |
|
|
69
|
+
| 参数 | 解释说明 |
|
|
70
|
+
| :-----------: | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: |
|
|
71
|
+
| port | 转码推流服务占用的端口号;(type:Number)<br/>可以不传;默认值:9999 |
|
|
72
|
+
| path | FFmpeg 命令在你机器上的启动名称,(type: String) <br/> 一般情况下不传;默认值:'ffmpeg' |
|
|
73
|
+
| audio | 默认不传,有声音;默认值:true;即:输出音频。<br/>如果想禁止输出音频,可以配置 audio: false |
|
|
74
|
+
| freeTime | 任一视频流空闲(未被使用)时间超过这个值,就会停止该视频流的转码,释放机器资源(type: Number;单位:秒) <br/> 一般情况下可不传;默认值:20 |
|
|
75
|
+
| checkTime | 检测视频空闲的时间间隔(type: Number;单位:秒) <br/> 一般情况下可不传;默认值:10 |
|
|
76
|
+
| q | 视频质量;取值范围:0-1000;数字越小,视频越清晰,带宽消耗越大<br/> 默认值:8; |
|
|
77
|
+
| transportType | 设置 RTSP 传输协议,默认值:无<br/>可选值:['tcp', 'udp', 'udp_multicast', 'http', 'https']<br/>ps: 这里默认值是无,也就是 rtsp2web 会自动选择一种传输协议;但是,并不能保证一定成功,这个时候,rtsp2web 日志会打印错误信息或者长时间的等待,这个时候就需要你手动来配置这个参数了,`'tcp'`、`'udp'` 是最常见的选择;详情可以参阅文档最后的【常见问题解决办法】 |
|
|
78
|
+
| webplayer | 设置前端播放器(视频流转码器),默认不传,默认值:'jsmpeg'<br/>可选值:['jsmpeg', 'flv'];如果设置为 `flv`,那么前端页面请使用 `flv.js` 播放器,详情请参考下面 `flv.js` 小节了解详细的使用方法 |
|
|
79
|
+
| wss | 配置 wss;配置格式如下:<br/> `wss: {key: 'keyPath', cert: 'certPath'}` <br/>如果你是 pfx 的证书,那么配置格式如下:<br/>`wss: {pfx: 'pfxPath', passphrase: 'passphrasePath'}`<br/>如果你想使用`wss`的话请配置这个选项,否则不要使用这个配置。 |
|
|
80
80
|
|
|
81
81
|
---
|
|
82
82
|
|
|
@@ -147,7 +147,7 @@ new RTSP2web({
|
|
|
147
147
|
</html>
|
|
148
148
|
```
|
|
149
149
|
|
|
150
|
-
> PS:
|
|
150
|
+
> PS: 默认情况下,在页面中播放视频,需要依赖 `jsmpeg.js` 工具包,请记得引入 `jsmpeg.js`;
|
|
151
151
|
|
|
152
152
|
详细参考例子:[https://github.com/Neveryu/rtsp2web/tree/master/example](https://github.com/Neveryu/rtsp2web/tree/master/example)
|
|
153
153
|
|
|
@@ -197,7 +197,7 @@ new JSMpeg.Player(
|
|
|
197
197
|
|
|
198
198
|
`rtsp2web` 默认自动转码音频并输出,你也可以根据配置设置,选择禁止音频输出。
|
|
199
199
|
|
|
200
|
-
> _
|
|
200
|
+
> _在浏览器中,自动播放声音是突兀的;根据浏览器规则,需要用户在页面任意地方进行任意的点击操作,就有声音了;如果配置了输出音频,为了播放声音,可以点击页面任意地方。_
|
|
201
201
|
|
|
202
202
|
# WSS
|
|
203
203
|
|
|
@@ -274,7 +274,7 @@ new RTSP2web({
|
|
|
274
274
|
|
|
275
275
|
# 常见问题解决办法
|
|
276
276
|
|
|
277
|
-
###
|
|
277
|
+
### 一、某某模式转换失败 [或者] 进程退出,请检查 ffmpeg 参数... [或者] 长时间等待画面... [或者] 其他等等问题
|
|
278
278
|
|
|
279
279
|
如果出现了这之类的提示,大多数情况下,你可能需要尝试配置 `transportType` 为其他值试试,`'tcp'`, `'udp'`是最常见的选择。
|
|
280
280
|
|
|
@@ -282,13 +282,13 @@ new RTSP2web({
|
|
|
282
282
|
|
|
283
283
|
### 二、ffmpeg 进程关闭了,code:3221225477
|
|
284
284
|
|
|
285
|
-
> 如果出现了 `3221225477`;这是 NodeJS 内核反馈的[违反了访问规定]的问题,一般这个问题只发生在 `windows`
|
|
285
|
+
> 如果出现了 `3221225477`;这是 NodeJS 内核反馈的[违反了访问规定]的问题,一般这个问题只发生在 `windows` 平台上。据我所知,这似乎是与 Windows 访问冲突相关的错误。可以尝试的操作有:
|
|
286
286
|
|
|
287
287
|
- 1、执行 `npm cache verify`,然后再试试;
|
|
288
288
|
- 2、清除 `npm` 缓存:`npm cache clean --force`,再试试;
|
|
289
289
|
- 3、升级更新 `nodejs`,安装稳定版,再试试;
|
|
290
290
|
- 4、`rm -rf node_modules`,`delete package-lock.json`,重新安装,再试试;
|
|
291
|
-
- 5
|
|
291
|
+
- 5、切换合适的 `node` 版本可解决;切换当前 `node` 版本可解决这个问题。
|
|
292
292
|
- 6、也可以参考【办法一】来尝试解决这类问题;
|
|
293
293
|
|
|
294
294
|
### 三、转换失败,请尝试改变 transportType 的值,然后重试。
|
package/dist/rtsp2web.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
/*!
|
|
2
|
-
* rtsp2web v3.1.
|
|
2
|
+
* rtsp2web v3.1.7
|
|
3
3
|
* (c) 2020-2023 NeverYu
|
|
4
4
|
* My home page:https://neveryu.github.io/neveryu/
|
|
5
5
|
* 微信(wechat):miracle421354532
|
|
6
6
|
* Released under the ISC License.
|
|
7
7
|
*/
|
|
8
|
-
"use strict";var e=require("http"),t=require("https"),r=require("tls"),n=require("fs"),s=require("events"),i=require("net"),o=require("crypto"),a=require("stream"),c=require("url"),l=require("zlib"),h=require("buffer");function f(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var u=f(e),d=f(t),p=f(r),_=f(n),m=f(s),y=f(i),v=f(o),g=f(a),b=f(c),w=f(l),S=f(h);function x(){x=function(){return e};var e={},t=Object.prototype,r=t.hasOwnProperty,n=Object.defineProperty||function(e,t,r){e[t]=r.value},s="function"==typeof Symbol?Symbol:{},i=s.iterator||"@@iterator",o=s.asyncIterator||"@@asyncIterator",a=s.toStringTag||"@@toStringTag";function c(e,t,r){return Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{c({},"")}catch(e){c=function(e,t,r){return e[t]=r}}function l(e,t,r,s){var i=t&&t.prototype instanceof u?t:u,o=Object.create(i.prototype),a=new O(s||[]);return n(o,"_invoke",{value:w(e,r,a)}),o}function h(e,t,r){try{return{type:"normal",arg:e.call(t,r)}}catch(e){return{type:"throw",arg:e}}}e.wrap=l;var f={};function u(){}function d(){}function p(){}var _={};c(_,i,(function(){return this}));var m=Object.getPrototypeOf,y=m&&m(m(C([])));y&&y!==t&&r.call(y,i)&&(_=y);var v=p.prototype=u.prototype=Object.create(_);function g(e){["next","throw","return"].forEach((function(t){c(e,t,(function(e){return this._invoke(t,e)}))}))}function b(e,t){function s(n,i,o,a){var c=h(e[n],e,i);if("throw"!==c.type){var l=c.arg,f=l.value;return f&&"object"==typeof f&&r.call(f,"__await")?t.resolve(f.__await).then((function(e){s("next",e,o,a)}),(function(e){s("throw",e,o,a)})):t.resolve(f).then((function(e){l.value=e,o(l)}),(function(e){return s("throw",e,o,a)}))}a(c.arg)}var i;n(this,"_invoke",{value:function(e,r){function n(){return new t((function(t,n){s(e,r,t,n)}))}return i=i?i.then(n,n):n()}})}function w(e,t,r){var n="suspendedStart";return function(s,i){if("executing"===n)throw new Error("Generator is already running");if("completed"===n){if("throw"===s)throw i;return T()}for(r.method=s,r.arg=i;;){var o=r.delegate;if(o){var a=S(o,r);if(a){if(a===f)continue;return a}}if("next"===r.method)r.sent=r._sent=r.arg;else if("throw"===r.method){if("suspendedStart"===n)throw n="completed",r.arg;r.dispatchException(r.arg)}else"return"===r.method&&r.abrupt("return",r.arg);n="executing";var c=h(e,t,r);if("normal"===c.type){if(n=r.done?"completed":"suspendedYield",c.arg===f)continue;return{value:c.arg,done:r.done}}"throw"===c.type&&(n="completed",r.method="throw",r.arg=c.arg)}}}function S(e,t){var r=t.method,n=e.iterator[r];if(void 0===n)return t.delegate=null,"throw"===r&&e.iterator.return&&(t.method="return",t.arg=void 0,S(e,t),"throw"===t.method)||"return"!==r&&(t.method="throw",t.arg=new TypeError("The iterator does not provide a '"+r+"' method")),f;var s=h(n,e.iterator,t.arg);if("throw"===s.type)return t.method="throw",t.arg=s.arg,t.delegate=null,f;var i=s.arg;return i?i.done?(t[e.resultName]=i.value,t.next=e.nextLoc,"return"!==t.method&&(t.method="next",t.arg=void 0),t.delegate=null,f):i:(t.method="throw",t.arg=new TypeError("iterator result is not an object"),t.delegate=null,f)}function k(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function E(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function O(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(k,this),this.reset(!0)}function C(e){if(e){var t=e[i];if(t)return t.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var n=-1,s=function t(){for(;++n<e.length;)if(r.call(e,n))return t.value=e[n],t.done=!1,t;return t.value=void 0,t.done=!0,t};return s.next=s}}return{next:T}}function T(){return{value:void 0,done:!0}}return d.prototype=p,n(v,"constructor",{value:p,configurable:!0}),n(p,"constructor",{value:d,configurable:!0}),d.displayName=c(p,a,"GeneratorFunction"),e.isGeneratorFunction=function(e){var t="function"==typeof e&&e.constructor;return!!t&&(t===d||"GeneratorFunction"===(t.displayName||t.name))},e.mark=function(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,p):(e.__proto__=p,c(e,a,"GeneratorFunction")),e.prototype=Object.create(v),e},e.awrap=function(e){return{__await:e}},g(b.prototype),c(b.prototype,o,(function(){return this})),e.AsyncIterator=b,e.async=function(t,r,n,s,i){void 0===i&&(i=Promise);var o=new b(l(t,r,n,s),i);return e.isGeneratorFunction(r)?o:o.next().then((function(e){return e.done?e.value:o.next()}))},g(v),c(v,a,"Generator"),c(v,i,(function(){return this})),c(v,"toString",(function(){return"[object Generator]"})),e.keys=function(e){var t=Object(e),r=[];for(var n in t)r.push(n);return r.reverse(),function e(){for(;r.length;){var n=r.pop();if(n in t)return e.value=n,e.done=!1,e}return e.done=!0,e}},e.values=C,O.prototype={constructor:O,reset:function(e){if(this.prev=0,this.next=0,this.sent=this._sent=void 0,this.done=!1,this.delegate=null,this.method="next",this.arg=void 0,this.tryEntries.forEach(E),!e)for(var t in this)"t"===t.charAt(0)&&r.call(this,t)&&!isNaN(+t.slice(1))&&(this[t]=void 0)},stop:function(){this.done=!0;var e=this.tryEntries[0].completion;if("throw"===e.type)throw e.arg;return this.rval},dispatchException:function(e){if(this.done)throw e;var t=this;function n(r,n){return o.type="throw",o.arg=e,t.next=r,n&&(t.method="next",t.arg=void 0),!!n}for(var s=this.tryEntries.length-1;s>=0;--s){var i=this.tryEntries[s],o=i.completion;if("root"===i.tryLoc)return n("end");if(i.tryLoc<=this.prev){var a=r.call(i,"catchLoc"),c=r.call(i,"finallyLoc");if(a&&c){if(this.prev<i.catchLoc)return n(i.catchLoc,!0);if(this.prev<i.finallyLoc)return n(i.finallyLoc)}else if(a){if(this.prev<i.catchLoc)return n(i.catchLoc,!0)}else{if(!c)throw new Error("try statement without catch or finally");if(this.prev<i.finallyLoc)return n(i.finallyLoc)}}}},abrupt:function(e,t){for(var n=this.tryEntries.length-1;n>=0;--n){var s=this.tryEntries[n];if(s.tryLoc<=this.prev&&r.call(s,"finallyLoc")&&this.prev<s.finallyLoc){var i=s;break}}i&&("break"===e||"continue"===e)&&i.tryLoc<=t&&t<=i.finallyLoc&&(i=null);var o=i?i.completion:{};return o.type=e,o.arg=t,i?(this.method="next",this.next=i.finallyLoc,f):this.complete(o)},complete:function(e,t){if("throw"===e.type)throw e.arg;return"break"===e.type||"continue"===e.type?this.next=e.arg:"return"===e.type?(this.rval=this.arg=e.arg,this.method="return",this.next="end"):"normal"===e.type&&t&&(this.next=t),f},finish:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.finallyLoc===e)return this.complete(r.completion,r.afterLoc),E(r),f}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.tryLoc===e){var n=r.completion;if("throw"===n.type){var s=n.arg;E(r)}return s}}throw new Error("illegal catch attempt")},delegateYield:function(e,t,r){return this.delegate={iterator:C(e),resultName:t,nextLoc:r},"next"===this.method&&(this.arg=void 0),f}},e}function k(e){return k="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},k(e)}function E(e,t,r,n,s,i,o){try{var a=e[i](o),c=a.value}catch(e){return void r(e)}a.done?t(c):Promise.resolve(c).then(n,s)}function O(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function C(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,W(n.key),n)}}function T(e,t,r){return t&&C(e.prototype,t),r&&C(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function L(e,t,r){return(t=W(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function N(e){return N=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},N(e)}function P(e,t){return P=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},P(e,t)}function M(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function R(e){var t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}();return function(){var r,n=N(e);if(t){var s=N(this).constructor;r=Reflect.construct(n,arguments,s)}else r=n.apply(this,arguments);return function(e,t){if(t&&("object"==typeof t||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return M(e)}(this,r)}}function I(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,s,i,o,a=[],c=!0,l=!1;try{if(i=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;c=!1}else for(;!(c=(n=i.call(r)).done)&&(a.push(n.value),a.length!==t);c=!0);}catch(e){l=!0,s=e}finally{try{if(!c&&null!=r.return&&(o=r.return(),Object(o)!==o))return}finally{if(l)throw s}}return a}}(e,t)||A(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function U(e){return function(e){if(Array.isArray(e))return B(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||A(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function A(e,t){if(e){if("string"==typeof e)return B(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?B(e,t):void 0}}function B(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function j(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=A(e))||t&&e&&"number"==typeof e.length){r&&(e=r);var n=0,s=function(){};return{s:s,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:s}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,o=!0,a=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return o=e.done,e},e:function(e){a=!0,i=e},f:function(){try{o||null==r.return||r.return()}finally{if(a)throw i}}}}function W(e){var t=function(e,t){if("object"!=typeof e||null===e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var n=r.call(e,t||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:String(t)}var F="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},D={exports:{}};
|
|
8
|
+
"use strict";var e=require("http"),t=require("https"),r=require("tls"),n=require("fs"),s=require("events"),o=require("net"),i=require("crypto"),a=require("stream"),c=require("url"),l=require("zlib"),h=require("buffer");function f(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var u=f(e),d=f(t),p=f(r),m=f(n),_=f(s),y=f(o),v=f(i),g=f(a),b=f(c),w=f(l),S=f(h);function x(){x=function(){return e};var e={},t=Object.prototype,r=t.hasOwnProperty,n=Object.defineProperty||function(e,t,r){e[t]=r.value},s="function"==typeof Symbol?Symbol:{},o=s.iterator||"@@iterator",i=s.asyncIterator||"@@asyncIterator",a=s.toStringTag||"@@toStringTag";function c(e,t,r){return Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{c({},"")}catch(e){c=function(e,t,r){return e[t]=r}}function l(e,t,r,s){var o=t&&t.prototype instanceof u?t:u,i=Object.create(o.prototype),a=new O(s||[]);return n(i,"_invoke",{value:w(e,r,a)}),i}function h(e,t,r){try{return{type:"normal",arg:e.call(t,r)}}catch(e){return{type:"throw",arg:e}}}e.wrap=l;var f={};function u(){}function d(){}function p(){}var m={};c(m,o,(function(){return this}));var _=Object.getPrototypeOf,y=_&&_(_(C([])));y&&y!==t&&r.call(y,o)&&(m=y);var v=p.prototype=u.prototype=Object.create(m);function g(e){["next","throw","return"].forEach((function(t){c(e,t,(function(e){return this._invoke(t,e)}))}))}function b(e,t){function s(n,o,i,a){var c=h(e[n],e,o);if("throw"!==c.type){var l=c.arg,f=l.value;return f&&"object"==typeof f&&r.call(f,"__await")?t.resolve(f.__await).then((function(e){s("next",e,i,a)}),(function(e){s("throw",e,i,a)})):t.resolve(f).then((function(e){l.value=e,i(l)}),(function(e){return s("throw",e,i,a)}))}a(c.arg)}var o;n(this,"_invoke",{value:function(e,r){function n(){return new t((function(t,n){s(e,r,t,n)}))}return o=o?o.then(n,n):n()}})}function w(e,t,r){var n="suspendedStart";return function(s,o){if("executing"===n)throw new Error("Generator is already running");if("completed"===n){if("throw"===s)throw o;return T()}for(r.method=s,r.arg=o;;){var i=r.delegate;if(i){var a=S(i,r);if(a){if(a===f)continue;return a}}if("next"===r.method)r.sent=r._sent=r.arg;else if("throw"===r.method){if("suspendedStart"===n)throw n="completed",r.arg;r.dispatchException(r.arg)}else"return"===r.method&&r.abrupt("return",r.arg);n="executing";var c=h(e,t,r);if("normal"===c.type){if(n=r.done?"completed":"suspendedYield",c.arg===f)continue;return{value:c.arg,done:r.done}}"throw"===c.type&&(n="completed",r.method="throw",r.arg=c.arg)}}}function S(e,t){var r=t.method,n=e.iterator[r];if(void 0===n)return t.delegate=null,"throw"===r&&e.iterator.return&&(t.method="return",t.arg=void 0,S(e,t),"throw"===t.method)||"return"!==r&&(t.method="throw",t.arg=new TypeError("The iterator does not provide a '"+r+"' method")),f;var s=h(n,e.iterator,t.arg);if("throw"===s.type)return t.method="throw",t.arg=s.arg,t.delegate=null,f;var o=s.arg;return o?o.done?(t[e.resultName]=o.value,t.next=e.nextLoc,"return"!==t.method&&(t.method="next",t.arg=void 0),t.delegate=null,f):o:(t.method="throw",t.arg=new TypeError("iterator result is not an object"),t.delegate=null,f)}function k(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function E(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function O(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(k,this),this.reset(!0)}function C(e){if(e){var t=e[o];if(t)return t.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var n=-1,s=function t(){for(;++n<e.length;)if(r.call(e,n))return t.value=e[n],t.done=!1,t;return t.value=void 0,t.done=!0,t};return s.next=s}}return{next:T}}function T(){return{value:void 0,done:!0}}return d.prototype=p,n(v,"constructor",{value:p,configurable:!0}),n(p,"constructor",{value:d,configurable:!0}),d.displayName=c(p,a,"GeneratorFunction"),e.isGeneratorFunction=function(e){var t="function"==typeof e&&e.constructor;return!!t&&(t===d||"GeneratorFunction"===(t.displayName||t.name))},e.mark=function(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,p):(e.__proto__=p,c(e,a,"GeneratorFunction")),e.prototype=Object.create(v),e},e.awrap=function(e){return{__await:e}},g(b.prototype),c(b.prototype,i,(function(){return this})),e.AsyncIterator=b,e.async=function(t,r,n,s,o){void 0===o&&(o=Promise);var i=new b(l(t,r,n,s),o);return e.isGeneratorFunction(r)?i:i.next().then((function(e){return e.done?e.value:i.next()}))},g(v),c(v,a,"Generator"),c(v,o,(function(){return this})),c(v,"toString",(function(){return"[object Generator]"})),e.keys=function(e){var t=Object(e),r=[];for(var n in t)r.push(n);return r.reverse(),function e(){for(;r.length;){var n=r.pop();if(n in t)return e.value=n,e.done=!1,e}return e.done=!0,e}},e.values=C,O.prototype={constructor:O,reset:function(e){if(this.prev=0,this.next=0,this.sent=this._sent=void 0,this.done=!1,this.delegate=null,this.method="next",this.arg=void 0,this.tryEntries.forEach(E),!e)for(var t in this)"t"===t.charAt(0)&&r.call(this,t)&&!isNaN(+t.slice(1))&&(this[t]=void 0)},stop:function(){this.done=!0;var e=this.tryEntries[0].completion;if("throw"===e.type)throw e.arg;return this.rval},dispatchException:function(e){if(this.done)throw e;var t=this;function n(r,n){return i.type="throw",i.arg=e,t.next=r,n&&(t.method="next",t.arg=void 0),!!n}for(var s=this.tryEntries.length-1;s>=0;--s){var o=this.tryEntries[s],i=o.completion;if("root"===o.tryLoc)return n("end");if(o.tryLoc<=this.prev){var a=r.call(o,"catchLoc"),c=r.call(o,"finallyLoc");if(a&&c){if(this.prev<o.catchLoc)return n(o.catchLoc,!0);if(this.prev<o.finallyLoc)return n(o.finallyLoc)}else if(a){if(this.prev<o.catchLoc)return n(o.catchLoc,!0)}else{if(!c)throw new Error("try statement without catch or finally");if(this.prev<o.finallyLoc)return n(o.finallyLoc)}}}},abrupt:function(e,t){for(var n=this.tryEntries.length-1;n>=0;--n){var s=this.tryEntries[n];if(s.tryLoc<=this.prev&&r.call(s,"finallyLoc")&&this.prev<s.finallyLoc){var o=s;break}}o&&("break"===e||"continue"===e)&&o.tryLoc<=t&&t<=o.finallyLoc&&(o=null);var i=o?o.completion:{};return i.type=e,i.arg=t,o?(this.method="next",this.next=o.finallyLoc,f):this.complete(i)},complete:function(e,t){if("throw"===e.type)throw e.arg;return"break"===e.type||"continue"===e.type?this.next=e.arg:"return"===e.type?(this.rval=this.arg=e.arg,this.method="return",this.next="end"):"normal"===e.type&&t&&(this.next=t),f},finish:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.finallyLoc===e)return this.complete(r.completion,r.afterLoc),E(r),f}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.tryLoc===e){var n=r.completion;if("throw"===n.type){var s=n.arg;E(r)}return s}}throw new Error("illegal catch attempt")},delegateYield:function(e,t,r){return this.delegate={iterator:C(e),resultName:t,nextLoc:r},"next"===this.method&&(this.arg=void 0),f}},e}function k(e){return k="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},k(e)}function E(e,t,r,n,s,o,i){try{var a=e[o](i),c=a.value}catch(e){return void r(e)}a.done?t(c):Promise.resolve(c).then(n,s)}function O(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function C(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,W(n.key),n)}}function T(e,t,r){return t&&C(e.prototype,t),r&&C(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function L(e,t,r){return(t=W(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function N(e){return N=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},N(e)}function P(e,t){return P=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},P(e,t)}function M(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function R(e){var t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}();return function(){var r,n=N(e);if(t){var s=N(this).constructor;r=Reflect.construct(n,arguments,s)}else r=n.apply(this,arguments);return function(e,t){if(t&&("object"==typeof t||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return M(e)}(this,r)}}function I(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,s,o,i,a=[],c=!0,l=!1;try{if(o=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;c=!1}else for(;!(c=(n=o.call(r)).done)&&(a.push(n.value),a.length!==t);c=!0);}catch(e){l=!0,s=e}finally{try{if(!c&&null!=r.return&&(i=r.return(),Object(i)!==i))return}finally{if(l)throw s}}return a}}(e,t)||A(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function U(e){return function(e){if(Array.isArray(e))return B(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||A(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function A(e,t){if(e){if("string"==typeof e)return B(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?B(e,t):void 0}}function B(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function j(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=A(e))||t&&e&&"number"==typeof e.length){r&&(e=r);var n=0,s=function(){};return{s:s,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:s}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,i=!0,a=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return i=e.done,e},e:function(e){a=!0,o=e},f:function(){try{i||null==r.return||r.return()}finally{if(a)throw o}}}}function W(e){var t=function(e,t){if("object"!=typeof e||null===e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var n=r.call(e,t||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:String(t)}var F="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},D={exports:{}};
|
|
9
9
|
/*! https://mths.be/base64 v1.0.0 by @mathias | MIT license */
|
|
10
|
-
!function(e,t){!function(r){var n=t,s=e&&e.exports==n&&e,i="object"==typeof F&&F;i.global!==i&&i.window!==i||(r=i);var o=function(e){this.message=e};(o.prototype=new Error).name="InvalidCharacterError";var a=function(e){throw new o(e)},c="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",l=/[\t\n\f\r ]/g,h={encode:function(e){e=String(e),/[^\0-\xFF]/.test(e)&&a("The string to be encoded contains characters outside of the Latin1 range.");for(var t,r,n,s,i=e.length%3,o="",l=-1,h=e.length-i;++l<h;)t=e.charCodeAt(l)<<16,r=e.charCodeAt(++l)<<8,n=e.charCodeAt(++l),o+=c.charAt((s=t+r+n)>>18&63)+c.charAt(s>>12&63)+c.charAt(s>>6&63)+c.charAt(63&s);return 2==i?(t=e.charCodeAt(l)<<8,r=e.charCodeAt(++l),o+=c.charAt((s=t+r)>>10)+c.charAt(s>>4&63)+c.charAt(s<<2&63)+"="):1==i&&(s=e.charCodeAt(l),o+=c.charAt(s>>2)+c.charAt(s<<4&63)+"=="),o},decode:function(e){var t=(e=String(e).replace(l,"")).length;t%4==0&&(t=(e=e.replace(/==?$/,"")).length),(t%4==1||/[^+a-zA-Z0-9/]/.test(e))&&a("Invalid character: the string to be decoded is not correctly encoded.");for(var r,n,s=0,i="",o=-1;++o<t;)n=c.indexOf(e.charAt(o)),r=s%4?64*r+n:n,s++%4&&(i+=String.fromCharCode(255&r>>(-2*s&6)));return i},version:"1.0.0"};if(n&&!n.nodeType)if(s)s.exports=h;else for(var f in h)h.hasOwnProperty(f)&&(n[f]=h[f]);else r.base64=h}(F)}(D,D.exports);var G={exports:{}},q={BINARY_TYPES:["nodebuffer","arraybuffer","fragments"],EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}};const{EMPTY_BUFFER:$}=q,V=Buffer[Symbol.species];function z(e,t,r,n,s){for(let i=0;i<s;i++)r[n+i]=e[i]^t[3&i]}function H(e,t){for(let r=0;r<e.length;r++)e[r]^=t[3&r]}if(G.exports={concat:function(e,t){if(0===e.length)return $;if(1===e.length)return e[0];const r=Buffer.allocUnsafe(t);let n=0;for(let t=0;t<e.length;t++){const s=e[t];r.set(s,n),n+=s.length}return n<t?new V(r.buffer,r.byteOffset,n):r},mask:z,toArrayBuffer:function(e){return e.length===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.length)},toBuffer:function e(t){if(e.readOnly=!0,Buffer.isBuffer(t))return t;let r;return t instanceof ArrayBuffer?r=new V(t):ArrayBuffer.isView(t)?r=new V(t.buffer,t.byteOffset,t.byteLength):(r=Buffer.from(t),e.readOnly=!1),r},unmask:H},!process.env.WS_NO_BUFFER_UTIL)try{const e=require("bufferutil");G.exports.mask=function(t,r,n,s,i){i<48?z(t,r,n,s,i):e.mask(t,r,n,s,i)},G.exports.unmask=function(t,r){t.length<32?H(t,r):e.unmask(t,r)}}catch(e){}const Y=Symbol("kDone"),X=Symbol("kRun");var Q=class{constructor(e){this[Y]=()=>{this.pending--,this[X]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[X]()}[X](){if(this.pending!==this.concurrency&&this.jobs.length){const e=this.jobs.shift();this.pending++,e(this[Y])}}};const Z=w.default,K=G.exports,J=Q,{kStatusCode:ee}=q,te=Buffer[Symbol.species],re=Buffer.from([0,0,255,255]),ne=Symbol("permessage-deflate"),se=Symbol("total-length"),ie=Symbol("callback"),oe=Symbol("buffers"),ae=Symbol("error");let ce;var le=class{constructor(e,t,r){if(this._maxPayload=0|r,this._options=e||{},this._threshold=void 0!==this._options.threshold?this._options.threshold:1024,this._isServer=!!t,this._deflate=null,this._inflate=null,this.params=null,!ce){const e=void 0!==this._options.concurrencyLimit?this._options.concurrencyLimit:10;ce=new J(e)}}static get extensionName(){return"permessage-deflate"}offer(){const e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:null==this._options.clientMaxWindowBits&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){const e=this._deflate[ie];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){const t=this._options,r=e.find((e=>!(!1===t.serverNoContextTakeover&&e.server_no_context_takeover||e.server_max_window_bits&&(!1===t.serverMaxWindowBits||"number"==typeof t.serverMaxWindowBits&&t.serverMaxWindowBits>e.server_max_window_bits)||"number"==typeof t.clientMaxWindowBits&&!e.client_max_window_bits)));if(!r)throw new Error("None of the extension offers can be accepted");return t.serverNoContextTakeover&&(r.server_no_context_takeover=!0),t.clientNoContextTakeover&&(r.client_no_context_takeover=!0),"number"==typeof t.serverMaxWindowBits&&(r.server_max_window_bits=t.serverMaxWindowBits),"number"==typeof t.clientMaxWindowBits?r.client_max_window_bits=t.clientMaxWindowBits:!0!==r.client_max_window_bits&&!1!==t.clientMaxWindowBits||delete r.client_max_window_bits,r}acceptAsClient(e){const t=e[0];if(!1===this._options.clientNoContextTakeover&&t.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(t.client_max_window_bits){if(!1===this._options.clientMaxWindowBits||"number"==typeof this._options.clientMaxWindowBits&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"')}else"number"==typeof this._options.clientMaxWindowBits&&(t.client_max_window_bits=this._options.clientMaxWindowBits);return t}normalizeParams(e){return e.forEach((e=>{Object.keys(e).forEach((t=>{let r=e[t];if(r.length>1)throw new Error(`Parameter "${t}" must have only a single value`);if(r=r[0],"client_max_window_bits"===t){if(!0!==r){const e=+r;if(!Number.isInteger(e)||e<8||e>15)throw new TypeError(`Invalid value for parameter "${t}": ${r}`);r=e}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${t}": ${r}`)}else if("server_max_window_bits"===t){const e=+r;if(!Number.isInteger(e)||e<8||e>15)throw new TypeError(`Invalid value for parameter "${t}": ${r}`);r=e}else{if("client_no_context_takeover"!==t&&"server_no_context_takeover"!==t)throw new Error(`Unknown parameter "${t}"`);if(!0!==r)throw new TypeError(`Invalid value for parameter "${t}": ${r}`)}e[t]=r}))})),e}decompress(e,t,r){ce.add((n=>{this._decompress(e,t,((e,t)=>{n(),r(e,t)}))}))}compress(e,t,r){ce.add((n=>{this._compress(e,t,((e,t)=>{n(),r(e,t)}))}))}_decompress(e,t,r){const n=this._isServer?"client":"server";if(!this._inflate){const e=`${n}_max_window_bits`,t="number"!=typeof this.params[e]?Z.Z_DEFAULT_WINDOWBITS:this.params[e];this._inflate=Z.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[ne]=this,this._inflate[se]=0,this._inflate[oe]=[],this._inflate.on("error",ue),this._inflate.on("data",fe)}this._inflate[ie]=r,this._inflate.write(e),t&&this._inflate.write(re),this._inflate.flush((()=>{const e=this._inflate[ae];if(e)return this._inflate.close(),this._inflate=null,void r(e);const s=K.concat(this._inflate[oe],this._inflate[se]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[se]=0,this._inflate[oe]=[],t&&this.params[`${n}_no_context_takeover`]&&this._inflate.reset()),r(null,s)}))}_compress(e,t,r){const n=this._isServer?"server":"client";if(!this._deflate){const e=`${n}_max_window_bits`,t="number"!=typeof this.params[e]?Z.Z_DEFAULT_WINDOWBITS:this.params[e];this._deflate=Z.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[se]=0,this._deflate[oe]=[],this._deflate.on("data",he)}this._deflate[ie]=r,this._deflate.write(e),this._deflate.flush(Z.Z_SYNC_FLUSH,(()=>{if(!this._deflate)return;let e=K.concat(this._deflate[oe],this._deflate[se]);t&&(e=new te(e.buffer,e.byteOffset,e.length-4)),this._deflate[ie]=null,this._deflate[se]=0,this._deflate[oe]=[],t&&this.params[`${n}_no_context_takeover`]&&this._deflate.reset(),r(null,e)}))}};function he(e){this[oe].push(e),this[se]+=e.length}function fe(e){this[se]+=e.length,this[ne]._maxPayload<1||this[se]<=this[ne]._maxPayload?this[oe].push(e):(this[ae]=new RangeError("Max payload size exceeded"),this[ae].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[ae][ee]=1009,this.removeListener("data",fe),this.reset())}function ue(e){this[ne]._inflate=null,e[ee]=1007,this[ie](e)}var de={exports:{}};const{isUtf8:pe}=S.default;function _e(e){const t=e.length;let r=0;for(;r<t;)if(0==(128&e[r]))r++;else if(192==(224&e[r])){if(r+1===t||128!=(192&e[r+1])||192==(254&e[r]))return!1;r+=2}else if(224==(240&e[r])){if(r+2>=t||128!=(192&e[r+1])||128!=(192&e[r+2])||224===e[r]&&128==(224&e[r+1])||237===e[r]&&160==(224&e[r+1]))return!1;r+=3}else{if(240!=(248&e[r]))return!1;if(r+3>=t||128!=(192&e[r+1])||128!=(192&e[r+2])||128!=(192&e[r+3])||240===e[r]&&128==(240&e[r+1])||244===e[r]&&e[r+1]>143||e[r]>244)return!1;r+=4}return!0}if(de.exports={isValidStatusCode:function(e){return e>=1e3&&e<=1014&&1004!==e&&1005!==e&&1006!==e||e>=3e3&&e<=4999},isValidUTF8:_e,tokenChars:[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0]},pe)de.exports.isValidUTF8=function(e){return e.length<24?_e(e):pe(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{const e=require("utf-8-validate");de.exports.isValidUTF8=function(t){return t.length<32?_e(t):e(t)}}catch(e){}const{Writable:me}=g.default,ye=le,{BINARY_TYPES:ve,EMPTY_BUFFER:ge,kStatusCode:be,kWebSocket:we}=q,{concat:Se,toArrayBuffer:xe,unmask:ke}=G.exports,{isValidStatusCode:Ee,isValidUTF8:Oe}=de.exports,Ce=Buffer[Symbol.species];var Te=class extends me{constructor(e={}){super(),this._binaryType=e.binaryType||ve[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=0|e.maxPayload,this._skipUTF8Validation=!!e.skipUTF8Validation,this[we]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._state=0,this._loop=!1}_write(e,t,r){if(8===this._opcode&&0==this._state)return r();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(r)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){const t=this._buffers[0];return this._buffers[0]=new Ce(t.buffer,t.byteOffset+e,t.length-e),new Ce(t.buffer,t.byteOffset,e)}const t=Buffer.allocUnsafe(e);do{const r=this._buffers[0],n=t.length-e;e>=r.length?t.set(this._buffers.shift(),n):(t.set(new Uint8Array(r.buffer,r.byteOffset,e),n),this._buffers[0]=new Ce(r.buffer,r.byteOffset+e,r.length-e)),e-=r.length}while(e>0);return t}startLoop(e){let t;this._loop=!0;do{switch(this._state){case 0:t=this.getInfo();break;case 1:t=this.getPayloadLength16();break;case 2:t=this.getPayloadLength64();break;case 3:this.getMask();break;case 4:t=this.getData(e);break;default:return void(this._loop=!1)}}while(this._loop);e(t)}getInfo(){if(this._bufferedBytes<2)return void(this._loop=!1);const e=this.consume(2);if(0!=(48&e[0]))return this._loop=!1,Le(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");const t=64==(64&e[0]);if(t&&!this._extensions[ye.extensionName])return this._loop=!1,Le(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");if(this._fin=128==(128&e[0]),this._opcode=15&e[0],this._payloadLength=127&e[1],0===this._opcode){if(t)return this._loop=!1,Le(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");if(!this._fragmented)return this._loop=!1,Le(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");this._opcode=this._fragmented}else if(1===this._opcode||2===this._opcode){if(this._fragmented)return this._loop=!1,Le(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");this._compressed=t}else{if(!(this._opcode>7&&this._opcode<11))return this._loop=!1,Le(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");if(!this._fin)return this._loop=!1,Le(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");if(t)return this._loop=!1,Le(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");if(this._payloadLength>125||8===this._opcode&&1===this._payloadLength)return this._loop=!1,Le(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH")}if(this._fin||this._fragmented||(this._fragmented=this._opcode),this._masked=128==(128&e[1]),this._isServer){if(!this._masked)return this._loop=!1,Le(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK")}else if(this._masked)return this._loop=!1,Le(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");if(126===this._payloadLength)this._state=1;else{if(127!==this._payloadLength)return this.haveLength();this._state=2}}getPayloadLength16(){if(!(this._bufferedBytes<2))return this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength();this._loop=!1}getPayloadLength64(){if(this._bufferedBytes<8)return void(this._loop=!1);const e=this.consume(8),t=e.readUInt32BE(0);return t>Math.pow(2,21)-1?(this._loop=!1,Le(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH")):(this._payloadLength=t*Math.pow(2,32)+e.readUInt32BE(4),this.haveLength())}haveLength(){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0))return this._loop=!1,Le(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");this._masked?this._state=3:this._state=4}getMask(){this._bufferedBytes<4?this._loop=!1:(this._mask=this.consume(4),this._state=4)}getData(e){let t=ge;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength)return void(this._loop=!1);t=this.consume(this._payloadLength),this._masked&&0!=(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])&&ke(t,this._mask)}return this._opcode>7?this.controlMessage(t):this._compressed?(this._state=5,void this.decompress(t,e)):(t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage())}decompress(e,t){this._extensions[ye.extensionName].decompress(e,this._fin,((e,r)=>{if(e)return t(e);if(r.length){if(this._messageLength+=r.length,this._messageLength>this._maxPayload&&this._maxPayload>0)return t(Le(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"));this._fragments.push(r)}const n=this.dataMessage();if(n)return t(n);this.startLoop(t)}))}dataMessage(){if(this._fin){const e=this._messageLength,t=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],2===this._opcode){let r;r="nodebuffer"===this._binaryType?Se(t,e):"arraybuffer"===this._binaryType?xe(Se(t,e)):t,this.emit("message",r,!0)}else{const r=Se(t,e);if(!this._skipUTF8Validation&&!Oe(r))return this._loop=!1,Le(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");this.emit("message",r,!1)}}this._state=0}controlMessage(e){if(8===this._opcode)if(this._loop=!1,0===e.length)this.emit("conclude",1005,ge),this.end();else{const t=e.readUInt16BE(0);if(!Ee(t))return Le(RangeError,`invalid status code ${t}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");const r=new Ce(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Oe(r))return Le(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");this.emit("conclude",t,r),this.end()}else 9===this._opcode?this.emit("ping",e):this.emit("pong",e);this._state=0}};function Le(e,t,r,n,s){const i=new e(r?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(i,Le),i.code=s,i[be]=n,i}const{randomFillSync:Ne}=v.default,Pe=le,{EMPTY_BUFFER:Me}=q,{isValidStatusCode:Re}=de.exports,{mask:Ie,toBuffer:Ue}=G.exports,Ae=Symbol("kByteLength"),Be=Buffer.alloc(4);class je{constructor(e,t,r){this._extensions=t||{},r&&(this._generateMask=r,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._deflating=!1,this._queue=[]}static frame(e,t){let r,n,s=!1,i=2,o=!1;t.mask&&(r=t.maskBuffer||Be,t.generateMask?t.generateMask(r):Ne(r,0,4),o=0==(r[0]|r[1]|r[2]|r[3]),i=6),"string"==typeof e?n=t.mask&&!o||void 0===t[Ae]?(e=Buffer.from(e)).length:t[Ae]:(n=e.length,s=t.mask&&t.readOnly&&!o);let a=n;n>=65536?(i+=8,a=127):n>125&&(i+=2,a=126);const c=Buffer.allocUnsafe(s?n+i:i);return c[0]=t.fin?128|t.opcode:t.opcode,t.rsv1&&(c[0]|=64),c[1]=a,126===a?c.writeUInt16BE(n,2):127===a&&(c[2]=c[3]=0,c.writeUIntBE(n,4,6)),t.mask?(c[1]|=128,c[i-4]=r[0],c[i-3]=r[1],c[i-2]=r[2],c[i-1]=r[3],o?[c,e]:s?(Ie(e,r,c,i,n),[c]):(Ie(e,r,e,0,n),[c,e])):[c,e]}close(e,t,r,n){let s;if(void 0===e)s=Me;else{if("number"!=typeof e||!Re(e))throw new TypeError("First argument must be a valid error code number");if(void 0!==t&&t.length){const r=Buffer.byteLength(t);if(r>123)throw new RangeError("The message must not be greater than 123 bytes");s=Buffer.allocUnsafe(2+r),s.writeUInt16BE(e,0),"string"==typeof t?s.write(t,2):s.set(t,2)}else s=Buffer.allocUnsafe(2),s.writeUInt16BE(e,0)}const i={[Ae]:s.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._deflating?this.enqueue([this.dispatch,s,!1,i,n]):this.sendFrame(je.frame(s,i),n)}ping(e,t,r){let n,s;if("string"==typeof e?(n=Buffer.byteLength(e),s=!1):(n=(e=Ue(e)).length,s=Ue.readOnly),n>125)throw new RangeError("The data size must not be greater than 125 bytes");const i={[Ae]:n,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:s,rsv1:!1};this._deflating?this.enqueue([this.dispatch,e,!1,i,r]):this.sendFrame(je.frame(e,i),r)}pong(e,t,r){let n,s;if("string"==typeof e?(n=Buffer.byteLength(e),s=!1):(n=(e=Ue(e)).length,s=Ue.readOnly),n>125)throw new RangeError("The data size must not be greater than 125 bytes");const i={[Ae]:n,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:s,rsv1:!1};this._deflating?this.enqueue([this.dispatch,e,!1,i,r]):this.sendFrame(je.frame(e,i),r)}send(e,t,r){const n=this._extensions[Pe.extensionName];let s,i,o=t.binary?2:1,a=t.compress;if("string"==typeof e?(s=Buffer.byteLength(e),i=!1):(s=(e=Ue(e)).length,i=Ue.readOnly),this._firstFragment?(this._firstFragment=!1,a&&n&&n.params[n._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(a=s>=n._threshold),this._compress=a):(a=!1,o=0),t.fin&&(this._firstFragment=!0),n){const n={[Ae]:s,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:o,readOnly:i,rsv1:a};this._deflating?this.enqueue([this.dispatch,e,this._compress,n,r]):this.dispatch(e,this._compress,n,r)}else this.sendFrame(je.frame(e,{[Ae]:s,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:o,readOnly:i,rsv1:!1}),r)}dispatch(e,t,r,n){if(!t)return void this.sendFrame(je.frame(e,r),n);const s=this._extensions[Pe.extensionName];this._bufferedBytes+=r[Ae],this._deflating=!0,s.compress(e,r.fin,((e,t)=>{if(this._socket.destroyed){const e=new Error("The socket was closed while data was being compressed");"function"==typeof n&&n(e);for(let t=0;t<this._queue.length;t++){const r=this._queue[t],n=r[r.length-1];"function"==typeof n&&n(e)}}else this._bufferedBytes-=r[Ae],this._deflating=!1,r.readOnly=!1,this.sendFrame(je.frame(t,r),n),this.dequeue()}))}dequeue(){for(;!this._deflating&&this._queue.length;){const e=this._queue.shift();this._bufferedBytes-=e[3][Ae],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Ae],this._queue.push(e)}sendFrame(e,t){2===e.length?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}}var We=je;const{kForOnEventAttribute:Fe,kListener:De}=q,Ge=Symbol("kCode"),qe=Symbol("kData"),$e=Symbol("kError"),Ve=Symbol("kMessage"),ze=Symbol("kReason"),He=Symbol("kTarget"),Ye=Symbol("kType"),Xe=Symbol("kWasClean");class Qe{constructor(e){this[He]=null,this[Ye]=e}get target(){return this[He]}get type(){return this[Ye]}}Object.defineProperty(Qe.prototype,"target",{enumerable:!0}),Object.defineProperty(Qe.prototype,"type",{enumerable:!0});class Ze extends Qe{constructor(e,t={}){super(e),this[Ge]=void 0===t.code?0:t.code,this[ze]=void 0===t.reason?"":t.reason,this[Xe]=void 0!==t.wasClean&&t.wasClean}get code(){return this[Ge]}get reason(){return this[ze]}get wasClean(){return this[Xe]}}Object.defineProperty(Ze.prototype,"code",{enumerable:!0}),Object.defineProperty(Ze.prototype,"reason",{enumerable:!0}),Object.defineProperty(Ze.prototype,"wasClean",{enumerable:!0});class Ke extends Qe{constructor(e,t={}){super(e),this[$e]=void 0===t.error?null:t.error,this[Ve]=void 0===t.message?"":t.message}get error(){return this[$e]}get message(){return this[Ve]}}Object.defineProperty(Ke.prototype,"error",{enumerable:!0}),Object.defineProperty(Ke.prototype,"message",{enumerable:!0});class Je extends Qe{constructor(e,t={}){super(e),this[qe]=void 0===t.data?null:t.data}get data(){return this[qe]}}Object.defineProperty(Je.prototype,"data",{enumerable:!0});const et={addEventListener(e,t,r={}){for(const n of this.listeners(e))if(!r[Fe]&&n[De]===t&&!n[Fe])return;let n;if("message"===e)n=function(e,r){const n=new Je("message",{data:r?e:e.toString()});n[He]=this,rt(t,this,n)};else if("close"===e)n=function(e,r){const n=new Ze("close",{code:e,reason:r.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});n[He]=this,rt(t,this,n)};else if("error"===e)n=function(e){const r=new Ke("error",{error:e,message:e.message});r[He]=this,rt(t,this,r)};else{if("open"!==e)return;n=function(){const e=new Qe("open");e[He]=this,rt(t,this,e)}}n[Fe]=!!r[Fe],n[De]=t,r.once?this.once(e,n):this.on(e,n)},removeEventListener(e,t){for(const r of this.listeners(e))if(r[De]===t&&!r[Fe]){this.removeListener(e,r);break}}};var tt={CloseEvent:Ze,ErrorEvent:Ke,Event:Qe,EventTarget:et,MessageEvent:Je};function rt(e,t,r){"object"==typeof e&&e.handleEvent?e.handleEvent.call(e,r):e.call(t,r)}const{tokenChars:nt}=de.exports;function st(e,t,r){void 0===e[t]?e[t]=[r]:e[t].push(r)}var it={format:function(e){return Object.keys(e).map((t=>{let r=e[t];return Array.isArray(r)||(r=[r]),r.map((e=>[t].concat(Object.keys(e).map((t=>{let r=e[t];return Array.isArray(r)||(r=[r]),r.map((e=>!0===e?t:`${t}=${e}`)).join("; ")}))).join("; "))).join(", ")})).join(", ")},parse:function(e){const t=Object.create(null);let r,n,s=Object.create(null),i=!1,o=!1,a=!1,c=-1,l=-1,h=-1,f=0;for(;f<e.length;f++)if(l=e.charCodeAt(f),void 0===r)if(-1===h&&1===nt[l])-1===c&&(c=f);else if(0===f||32!==l&&9!==l){if(59!==l&&44!==l)throw new SyntaxError(`Unexpected character at index ${f}`);{if(-1===c)throw new SyntaxError(`Unexpected character at index ${f}`);-1===h&&(h=f);const n=e.slice(c,h);44===l?(st(t,n,s),s=Object.create(null)):r=n,c=h=-1}}else-1===h&&-1!==c&&(h=f);else if(void 0===n)if(-1===h&&1===nt[l])-1===c&&(c=f);else if(32===l||9===l)-1===h&&-1!==c&&(h=f);else if(59===l||44===l){if(-1===c)throw new SyntaxError(`Unexpected character at index ${f}`);-1===h&&(h=f),st(s,e.slice(c,h),!0),44===l&&(st(t,r,s),s=Object.create(null),r=void 0),c=h=-1}else{if(61!==l||-1===c||-1!==h)throw new SyntaxError(`Unexpected character at index ${f}`);n=e.slice(c,f),c=h=-1}else if(o){if(1!==nt[l])throw new SyntaxError(`Unexpected character at index ${f}`);-1===c?c=f:i||(i=!0),o=!1}else if(a)if(1===nt[l])-1===c&&(c=f);else if(34===l&&-1!==c)a=!1,h=f;else{if(92!==l)throw new SyntaxError(`Unexpected character at index ${f}`);o=!0}else if(34===l&&61===e.charCodeAt(f-1))a=!0;else if(-1===h&&1===nt[l])-1===c&&(c=f);else if(-1===c||32!==l&&9!==l){if(59!==l&&44!==l)throw new SyntaxError(`Unexpected character at index ${f}`);{if(-1===c)throw new SyntaxError(`Unexpected character at index ${f}`);-1===h&&(h=f);let o=e.slice(c,h);i&&(o=o.replace(/\\/g,""),i=!1),st(s,n,o),44===l&&(st(t,r,s),s=Object.create(null),r=void 0),n=void 0,c=h=-1}}else-1===h&&(h=f);if(-1===c||a||32===l||9===l)throw new SyntaxError("Unexpected end of input");-1===h&&(h=f);const u=e.slice(c,h);return void 0===r?st(t,u,s):(void 0===n?st(s,u,!0):st(s,n,i?u.replace(/\\/g,""):u),st(t,r,s)),t}};const ot=m.default,at=d.default,ct=u.default,lt=y.default,ht=p.default,{randomBytes:ft,createHash:ut}=v.default,{URL:dt}=b.default,pt=le,_t=Te,mt=We,{BINARY_TYPES:yt,EMPTY_BUFFER:vt,GUID:gt,kForOnEventAttribute:bt,kListener:wt,kStatusCode:St,kWebSocket:xt,NOOP:kt}=q,{EventTarget:{addEventListener:Et,removeEventListener:Ot}}=tt,{format:Ct,parse:Tt}=it,{toBuffer:Lt}=G.exports,Nt=Symbol("kAborted"),Pt=[8,13],Mt=["CONNECTING","OPEN","CLOSING","CLOSED"],Rt=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;class It extends ot{constructor(e,t,r){super(),this._binaryType=yt[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=vt,this._closeTimer=null,this._extensions={},this._paused=!1,this._protocol="",this._readyState=It.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,null!==e?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,void 0===t?t=[]:Array.isArray(t)||("object"==typeof t&&null!==t?(r=t,t=[]):t=[t]),At(this,e,t,r)):this._isServer=!0}get binaryType(){return this._binaryType}set binaryType(e){yt.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,t,r){const n=new _t({binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation});this._sender=new mt(e,this._extensions,r.generateMask),this._receiver=n,this._socket=e,n[xt]=this,e[xt]=this,n.on("conclude",Gt),n.on("drain",qt),n.on("error",$t),n.on("message",zt),n.on("ping",Ht),n.on("pong",Yt),e.setTimeout(0),e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",Qt),e.on("data",Zt),e.on("end",Kt),e.on("error",Jt),this._readyState=It.OPEN,this.emit("open")}emitClose(){if(!this._socket)return this._readyState=It.CLOSED,void this.emit("close",this._closeCode,this._closeMessage);this._extensions[pt.extensionName]&&this._extensions[pt.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=It.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,t){if(this.readyState!==It.CLOSED)if(this.readyState!==It.CONNECTING)this.readyState!==It.CLOSING?(this._readyState=It.CLOSING,this._sender.close(e,t,!this._isServer,(e=>{e||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())})),this._closeTimer=setTimeout(this._socket.destroy.bind(this._socket),3e4)):this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();else{const e="WebSocket was closed before the connection was established";Ft(this,this._req,e)}}pause(){this.readyState!==It.CONNECTING&&this.readyState!==It.CLOSED&&(this._paused=!0,this._socket.pause())}ping(e,t,r){if(this.readyState===It.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");"function"==typeof e?(r=e,e=t=void 0):"function"==typeof t&&(r=t,t=void 0),"number"==typeof e&&(e=e.toString()),this.readyState===It.OPEN?(void 0===t&&(t=!this._isServer),this._sender.ping(e||vt,t,r)):Dt(this,e,r)}pong(e,t,r){if(this.readyState===It.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");"function"==typeof e?(r=e,e=t=void 0):"function"==typeof t&&(r=t,t=void 0),"number"==typeof e&&(e=e.toString()),this.readyState===It.OPEN?(void 0===t&&(t=!this._isServer),this._sender.pong(e||vt,t,r)):Dt(this,e,r)}resume(){this.readyState!==It.CONNECTING&&this.readyState!==It.CLOSED&&(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,t,r){if(this.readyState===It.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if("function"==typeof t&&(r=t,t={}),"number"==typeof e&&(e=e.toString()),this.readyState!==It.OPEN)return void Dt(this,e,r);const n={binary:"string"!=typeof e,mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[pt.extensionName]||(n.compress=!1),this._sender.send(e||vt,n,r)}terminate(){if(this.readyState!==It.CLOSED)if(this.readyState!==It.CONNECTING)this._socket&&(this._readyState=It.CLOSING,this._socket.destroy());else{const e="WebSocket was closed before the connection was established";Ft(this,this._req,e)}}}Object.defineProperty(It,"CONNECTING",{enumerable:!0,value:Mt.indexOf("CONNECTING")}),Object.defineProperty(It.prototype,"CONNECTING",{enumerable:!0,value:Mt.indexOf("CONNECTING")}),Object.defineProperty(It,"OPEN",{enumerable:!0,value:Mt.indexOf("OPEN")}),Object.defineProperty(It.prototype,"OPEN",{enumerable:!0,value:Mt.indexOf("OPEN")}),Object.defineProperty(It,"CLOSING",{enumerable:!0,value:Mt.indexOf("CLOSING")}),Object.defineProperty(It.prototype,"CLOSING",{enumerable:!0,value:Mt.indexOf("CLOSING")}),Object.defineProperty(It,"CLOSED",{enumerable:!0,value:Mt.indexOf("CLOSED")}),Object.defineProperty(It.prototype,"CLOSED",{enumerable:!0,value:Mt.indexOf("CLOSED")}),["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach((e=>{Object.defineProperty(It.prototype,e,{enumerable:!0})})),["open","error","close","message"].forEach((e=>{Object.defineProperty(It.prototype,`on${e}`,{enumerable:!0,get(){for(const t of this.listeners(e))if(t[bt])return t[wt];return null},set(t){for(const t of this.listeners(e))if(t[bt]){this.removeListener(e,t);break}"function"==typeof t&&this.addEventListener(e,t,{[bt]:!0})}})})),It.prototype.addEventListener=Et,It.prototype.removeEventListener=Ot;var Ut=It;function At(e,t,r,n){const s={protocolVersion:Pt[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...n,createConnection:void 0,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(!Pt.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${Pt.join(", ")})`);let i;if(t instanceof dt)i=t,e._url=t.href;else{try{i=new dt(t)}catch(e){throw new SyntaxError(`Invalid URL: ${t}`)}e._url=t}const o="wss:"===i.protocol,a="ws+unix:"===i.protocol;let c;if("ws:"===i.protocol||o||a?a&&!i.pathname?c="The URL's pathname is empty":i.hash&&(c="The URL contains a fragment identifier"):c='The URL\'s protocol must be one of "ws:", "wss:", or "ws+unix:"',c){const t=new SyntaxError(c);if(0===e._redirects)throw t;return void Bt(e,t)}const l=o?443:80,h=ft(16).toString("base64"),f=o?at.request:ct.request,u=new Set;let d,p;if(s.createConnection=o?Wt:jt,s.defaultPort=s.defaultPort||l,s.port=i.port||l,s.host=i.hostname.startsWith("[")?i.hostname.slice(1,-1):i.hostname,s.headers={...s.headers,"Sec-WebSocket-Version":s.protocolVersion,"Sec-WebSocket-Key":h,Connection:"Upgrade",Upgrade:"websocket"},s.path=i.pathname+i.search,s.timeout=s.handshakeTimeout,s.perMessageDeflate&&(d=new pt(!0!==s.perMessageDeflate?s.perMessageDeflate:{},!1,s.maxPayload),s.headers["Sec-WebSocket-Extensions"]=Ct({[pt.extensionName]:d.offer()})),r.length){for(const e of r){if("string"!=typeof e||!Rt.test(e)||u.has(e))throw new SyntaxError("An invalid or duplicated subprotocol was specified");u.add(e)}s.headers["Sec-WebSocket-Protocol"]=r.join(",")}if(s.origin&&(s.protocolVersion<13?s.headers["Sec-WebSocket-Origin"]=s.origin:s.headers.Origin=s.origin),(i.username||i.password)&&(s.auth=`${i.username}:${i.password}`),a){const e=s.path.split(":");s.socketPath=e[0],s.path=e[1]}if(s.followRedirects){if(0===e._redirects){e._originalIpc=a,e._originalSecure=o,e._originalHostOrSocketPath=a?s.socketPath:i.host;const t=n&&n.headers;if(n={...n,headers:{}},t)for(const[e,r]of Object.entries(t))n.headers[e.toLowerCase()]=r}else if(0===e.listenerCount("redirect")){const t=a?!!e._originalIpc&&s.socketPath===e._originalHostOrSocketPath:!e._originalIpc&&i.host===e._originalHostOrSocketPath;(!t||e._originalSecure&&!o)&&(delete s.headers.authorization,delete s.headers.cookie,t||delete s.headers.host,s.auth=void 0)}s.auth&&!n.headers.authorization&&(n.headers.authorization="Basic "+Buffer.from(s.auth).toString("base64")),p=e._req=f(s),e._redirects&&e.emit("redirect",e.url,p)}else p=e._req=f(s);s.timeout&&p.on("timeout",(()=>{Ft(e,p,"Opening handshake has timed out")})),p.on("error",(t=>{null===p||p[Nt]||(p=e._req=null,Bt(e,t))})),p.on("response",(i=>{const o=i.headers.location,a=i.statusCode;if(o&&s.followRedirects&&a>=300&&a<400){if(++e._redirects>s.maxRedirects)return void Ft(e,p,"Maximum redirects exceeded");let i;p.abort();try{i=new dt(o,t)}catch(t){const r=new SyntaxError(`Invalid URL: ${o}`);return void Bt(e,r)}At(e,i,r,n)}else e.emit("unexpected-response",p,i)||Ft(e,p,`Unexpected server response: ${i.statusCode}`)})),p.on("upgrade",((t,r,n)=>{if(e.emit("upgrade",t),e.readyState!==It.CONNECTING)return;if(p=e._req=null,"websocket"!==t.headers.upgrade.toLowerCase())return void Ft(e,r,"Invalid Upgrade header");const i=ut("sha1").update(h+gt).digest("base64");if(t.headers["sec-websocket-accept"]!==i)return void Ft(e,r,"Invalid Sec-WebSocket-Accept header");const o=t.headers["sec-websocket-protocol"];let a;if(void 0!==o?u.size?u.has(o)||(a="Server sent an invalid subprotocol"):a="Server sent a subprotocol but none was requested":u.size&&(a="Server sent no subprotocol"),a)return void Ft(e,r,a);o&&(e._protocol=o);const c=t.headers["sec-websocket-extensions"];if(void 0!==c){if(!d){return void Ft(e,r,"Server sent a Sec-WebSocket-Extensions header but no extension was requested")}let t;try{t=Tt(c)}catch(t){return void Ft(e,r,"Invalid Sec-WebSocket-Extensions header")}const n=Object.keys(t);if(1!==n.length||n[0]!==pt.extensionName){return void Ft(e,r,"Server indicated an extension that was not requested")}try{d.accept(t[pt.extensionName])}catch(t){return void Ft(e,r,"Invalid Sec-WebSocket-Extensions header")}e._extensions[pt.extensionName]=d}e.setSocket(r,n,{generateMask:s.generateMask,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})})),p.end()}function Bt(e,t){e._readyState=It.CLOSING,e.emit("error",t),e.emitClose()}function jt(e){return e.path=e.socketPath,lt.connect(e)}function Wt(e){return e.path=void 0,e.servername||""===e.servername||(e.servername=lt.isIP(e.host)?"":e.host),ht.connect(e)}function Ft(e,t,r){e._readyState=It.CLOSING;const n=new Error(r);Error.captureStackTrace(n,Ft),t.setHeader?(t[Nt]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(Bt,e,n)):(t.destroy(n),t.once("error",e.emit.bind(e,"error")),t.once("close",e.emitClose.bind(e)))}function Dt(e,t,r){if(t){const r=Lt(t).length;e._socket?e._sender._bufferedBytes+=r:e._bufferedAmount+=r}if(r){const t=new Error(`WebSocket is not open: readyState ${e.readyState} (${Mt[e.readyState]})`);process.nextTick(r,t)}}function Gt(e,t){const r=this[xt];r._closeFrameReceived=!0,r._closeMessage=t,r._closeCode=e,void 0!==r._socket[xt]&&(r._socket.removeListener("data",Zt),process.nextTick(Xt,r._socket),1005===e?r.close():r.close(e,t))}function qt(){const e=this[xt];e.isPaused||e._socket.resume()}function $t(e){const t=this[xt];void 0!==t._socket[xt]&&(t._socket.removeListener("data",Zt),process.nextTick(Xt,t._socket),t.close(e[St])),t.emit("error",e)}function Vt(){this[xt].emitClose()}function zt(e,t){this[xt].emit("message",e,t)}function Ht(e){const t=this[xt];t.pong(e,!t._isServer,kt),t.emit("ping",e)}function Yt(e){this[xt].emit("pong",e)}function Xt(e){e.resume()}function Qt(){const e=this[xt];let t;this.removeListener("close",Qt),this.removeListener("data",Zt),this.removeListener("end",Kt),e._readyState=It.CLOSING,this._readableState.endEmitted||e._closeFrameReceived||e._receiver._writableState.errorEmitted||null===(t=e._socket.read())||e._receiver.write(t),e._receiver.end(),this[xt]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on("error",Vt),e._receiver.on("finish",Vt))}function Zt(e){this[xt]._receiver.write(e)||this.pause()}function Kt(){const e=this[xt];e._readyState=It.CLOSING,e._receiver.end(),this.end()}function Jt(){const e=this[xt];this.removeListener("error",Jt),this.on("error",kt),e&&(e._readyState=It.CLOSING,this.destroy())}const{Duplex:er}=g.default;function tr(e){e.emit("close")}function rr(){!this.destroyed&&this._writableState.finished&&this.destroy()}function nr(e){this.removeListener("error",nr),this.destroy(),0===this.listenerCount("error")&&this.emit("error",e)}var sr=function(e,t){let r=!0;const n=new er({...t,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return e.on("message",(function(t,r){const s=!r&&n._readableState.objectMode?t.toString():t;n.push(s)||e.pause()})),e.once("error",(function(e){n.destroyed||(r=!1,n.destroy(e))})),e.once("close",(function(){n.destroyed||n.push(null)})),n._destroy=function(t,s){if(e.readyState===e.CLOSED)return s(t),void process.nextTick(tr,n);let i=!1;e.once("error",(function(e){i=!0,s(e)})),e.once("close",(function(){i||s(t),process.nextTick(tr,n)})),r&&e.terminate()},n._final=function(t){e.readyState!==e.CONNECTING?null!==e._socket&&(e._socket._writableState.finished?(t(),n._readableState.endEmitted&&n.destroy()):(e._socket.once("finish",(function(){t()})),e.close())):e.once("open",(function(){n._final(t)}))},n._read=function(){e.isPaused&&e.resume()},n._write=function(t,r,s){e.readyState!==e.CONNECTING?e.send(t,s):e.once("open",(function(){n._write(t,r,s)}))},n.on("end",rr),n.on("error",nr),n};const{tokenChars:ir}=de.exports;var or={parse:function(e){const t=new Set;let r=-1,n=-1,s=0;for(;s<e.length;s++){const i=e.charCodeAt(s);if(-1===n&&1===ir[i])-1===r&&(r=s);else if(0===s||32!==i&&9!==i){if(44!==i)throw new SyntaxError(`Unexpected character at index ${s}`);{if(-1===r)throw new SyntaxError(`Unexpected character at index ${s}`);-1===n&&(n=s);const i=e.slice(r,n);if(t.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);t.add(i),r=n=-1}}else-1===n&&-1!==r&&(n=s)}if(-1===r||-1!==n)throw new SyntaxError("Unexpected end of input");const i=e.slice(r,s);if(t.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);return t.add(i),t}};const ar=m.default,cr=u.default,{createHash:lr}=v.default,hr=it,fr=le,ur=or,dr=Ut,{GUID:pr,kWebSocket:_r}=q,mr=/^[+/0-9A-Za-z]{22}==$/,yr=2;var vr=class extends ar{constructor(e,t){if(super(),null==(e={maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:dr,...e}).port&&!e.server&&!e.noServer||null!=e.port&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(null!=e.port?(this._server=cr.createServer(((e,t)=>{const r=cr.STATUS_CODES[426];t.writeHead(426,{"Content-Length":r.length,"Content-Type":"text/plain"}),t.end(r)})),this._server.listen(e.port,e.host,e.backlog,t)):e.server&&(this._server=e.server),this._server){const e=this.emit.bind(this,"connection");this._removeListeners=function(e,t){for(const r of Object.keys(t))e.on(r,t[r]);return function(){for(const r of Object.keys(t))e.removeListener(r,t[r])}}(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(t,r,n)=>{this.handleUpgrade(t,r,n,e)}})}!0===e.perMessageDeflate&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=0}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(this._state===yr)return e&&this.once("close",(()=>{e(new Error("The server is not running"))})),void process.nextTick(gr,this);if(e&&this.once("close",e),1!==this._state)if(this._state=1,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients&&this.clients.size?this._shouldEmitClose=!0:process.nextTick(gr,this);else{const e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close((()=>{gr(this)}))}}shouldHandle(e){if(this.options.path){const t=e.url.indexOf("?");if((-1!==t?e.url.slice(0,t):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,t,r,n){t.on("error",br);const s=e.headers["sec-websocket-key"],i=+e.headers["sec-websocket-version"];if("GET"!==e.method){return void Sr(this,e,t,405,"Invalid HTTP method")}if("websocket"!==e.headers.upgrade.toLowerCase()){return void Sr(this,e,t,400,"Invalid Upgrade header")}if(!s||!mr.test(s)){return void Sr(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header")}if(8!==i&&13!==i){return void Sr(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header")}if(!this.shouldHandle(e))return void wr(t,400);const o=e.headers["sec-websocket-protocol"];let a=new Set;if(void 0!==o)try{a=ur.parse(o)}catch(r){return void Sr(this,e,t,400,"Invalid Sec-WebSocket-Protocol header")}const c=e.headers["sec-websocket-extensions"],l={};if(this.options.perMessageDeflate&&void 0!==c){const r=new fr(this.options.perMessageDeflate,!0,this.options.maxPayload);try{const e=hr.parse(c);e[fr.extensionName]&&(r.accept(e[fr.extensionName]),l[fr.extensionName]=r)}catch(r){return void Sr(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header")}}if(this.options.verifyClient){const o={origin:e.headers[""+(8===i?"sec-websocket-origin":"origin")],secure:!(!e.socket.authorized&&!e.socket.encrypted),req:e};if(2===this.options.verifyClient.length)return void this.options.verifyClient(o,((i,o,c,h)=>{if(!i)return wr(t,o||401,c,h);this.completeUpgrade(l,s,a,e,t,r,n)}));if(!this.options.verifyClient(o))return wr(t,401)}this.completeUpgrade(l,s,a,e,t,r,n)}completeUpgrade(e,t,r,n,s,i,o){if(!s.readable||!s.writable)return s.destroy();if(s[_r])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>0)return wr(s,503);const a=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${lr("sha1").update(t+pr).digest("base64")}`],c=new this.options.WebSocket(null);if(r.size){const e=this.options.handleProtocols?this.options.handleProtocols(r,n):r.values().next().value;e&&(a.push(`Sec-WebSocket-Protocol: ${e}`),c._protocol=e)}if(e[fr.extensionName]){const t=e[fr.extensionName].params,r=hr.format({[fr.extensionName]:[t]});a.push(`Sec-WebSocket-Extensions: ${r}`),c._extensions=e}this.emit("headers",a,n),s.write(a.concat("\r\n").join("\r\n")),s.removeListener("error",br),c.setSocket(s,i,{maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(c),c.on("close",(()=>{this.clients.delete(c),this._shouldEmitClose&&!this.clients.size&&process.nextTick(gr,this)}))),o(c,n)}};function gr(e){e._state=yr,e.emit("close")}function br(){this.destroy()}function wr(e,t,r,n){r=r||cr.STATUS_CODES[t],n={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(r),...n},e.once("finish",e.destroy),e.end(`HTTP/1.1 ${t} ${cr.STATUS_CODES[t]}\r\n`+Object.keys(n).map((e=>`${e}: ${n[e]}`)).join("\r\n")+"\r\n\r\n"+r)}function Sr(e,t,r,n,s){if(e.listenerCount("wsClientError")){const n=new Error(s);Error.captureStackTrace(n,Sr),e.emit("wsClientError",n,r,t)}else wr(r,n,s)}const xr=Ut;xr.createWebSocketStream=sr,xr.Server=vr,xr.Receiver=Te,xr.Sender=We,xr.WebSocket=xr,xr.WebSocketServer=xr.Server;var kr=xr,Er="3.1.6",Or=require("child_process"),Cr=require("events"),Tr=require("url"),Lr=kr.Server,Nr="ffmpeg",Pr=["jsmpeg","flv"],Mr="jsmpeg",Rr={jsmpeg:"mpegts",flv:"flv"},Ir={jsmpeg:"mpeg1video",flv:"libx264"},Ur={jsmpeg:"mp2",flv:"aac"},Ar=!1,Br=8,jr=["tcp","udp","udp_multicast","http","https"],Wr="",Fr=!0,Dr=!0,Gr="drawtext=x=w-tw-5:y=80:fontcolor=white:fontsize=32:text="+decodeURIComponent(D.exports.decode("Y2xlYXIlMjB3aXRoJTIwcXElMjA0MjEzNTQ1MzI="))+":box=1:boxcolor=black,scale=-1:-1,eq=",qr=20,$r=10,Vr=["-s","-b:v","webplayer","scale","contrast","brightness","saturation","gamma"].concat(["vcodec"]),zr=["scale","contrast","brightness","saturation","gamma"],Hr=function(e,t){switch(e){case"-s":if(t.includes("x")&&t.split("x")[0]&&t.split("x")[0]>0&&t.split("x")[1]&&t.split("x")[1]>0)return!0;break;case"vcodec":case"webplayer":case"contrast":case"brightness":case"saturation":case"gamma":if(t)return!0;break;case"-b:v":if(t.endsWith("k"))return!0;break;case"scale":if(t.includes(":")&&t.split(":")[0]&&t.split(":")[1])return!0}},Yr=function(e){!function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&P(e,t)}(r,Cr.EventEmitter);var t=R(r);function r(e){var n;return O(this,r),L(M(n=t.call(this)),"exitCode",void 0),L(M(n),"additionalFlags",[]),L(M(n),"stream",null),L(M(n),"inputStreamStarted",!1),n.ffmpegPath=Nr,n.url=e.url,n.ffmpegOptions=e.ffmpegOptions,n.modifyOptions=e.modifyOptions||{},n.options=e,n.initMpeg2Muxer(),n}return T(r,[{key:"initMpeg2Muxer",value:function(){var e,t=this;if(Fr||delete this.ffmpegOptions["-vf"],this.ffmpegOptions.webplayer&&(Mr=this.ffmpegOptions.webplayer,delete this.ffmpegOptions.webplayer),this.ffmpegOptions)for(var r in this.ffmpegOptions)this.additionalFlags.push(r),""!==String(this.ffmpegOptions[r])&&this.additionalFlags.push(String(this.ffmpegOptions[r]));(this.spawnOptions=["-re","-thread_queue_size","1024","-threads","8","-max_interleave_delta","0","-i",this.url,"-q",Br,"-f",Rr[Mr],"-c:v",Ir[Mr],"-r","30","-c:a",Ur[Mr],Ar?"-an":null,"-ar","48000","-ac","1"].concat(U(this.additionalFlags),["-nostats","-"]),this.modifyOptions)&&(this.modifyOptions.del&&(null===(e=this.modifyOptions.del)||void 0===e||e.forEach((function(e){"buffer_size"==e&&(t.spawnOptions[1]=null,t.spawnOptions[2]=null)}))));String(Wr).length>0&&this.spawnOptions.splice(1,0,"-rtsp_transport",String(Wr)),this.spawnOptions=this.spawnOptions.filter((function(e){return null!==e})),this.stream=Or.spawn(this.ffmpegPath,this.spawnOptions,{detached:!1}),this.stream.on("error",(function(e,t){console.error("**启动ffmpeg时出错,请确保你安装了ffmpeg,然后检查路径或者命令参数~,code:",e,"signal:",t)})),this.stream.on("exit",(function(e,r){return console.error("[ffmpeg]某个视频流转码进程退出了: **如果非正常关闭视频导致的退出,请检查ffmpeg参数或检查代码或联系作者解决**,code:",e,"signal:",r),t.emit("exitWithError")})),this.stream.on("close",(function(e,r){return console.log("[ffmpeg]某个视频流转码进程关闭了: code: ",e),t.emit("ffmpegClosed")})),this.inputStreamStarted=!0,this.stream.stdout.on("data",(function(e){return t.emit("mpeg2data",e)})),this.stream.stderr.on("data",(function(e){return t.emit("ffmpegStderr",e)}))}}]),r}(),Xr=function(){function e(t){O(this,e),L(this,"freeTime",0),L(this,"width",null),L(this,"height",null),L(this,"isStreamWrap",!1),L(this,"clients",[]),L(this,"mpeg2Muxer",{instance:null,stream:null,data:null}),L(this,"modifyOptions",{}),this.config=t,this.url=t.url}var t,r;return T(e,[{key:"createStream",value:function(){this.isStreamWrap||(console.log("[ffmpeg]创建一个新的视频流转码进程~"),this.isStreamWrap=!0,this.mpeg2Muxer.instance=new Yr({url:this.url,ffmpegOptions:this.formatParams(this.config)}),this.mpeg2Muxer.stream=this.mpeg2Muxer.instance.stream,this.eventHandler())}},{key:"eventHandler",value:function(){var e=this;this.mpeg2Muxer.instance.on("mpeg2data",(function(t){e.broadcast(t)})),this.mpeg2Muxer.instance.on("ffmpegStderr",(function(t){if(-1!==(t=t.toString()).indexOf("failed")&&(global.process.stdout.write(t+"=== L518 \n"),-1!==t.indexOf("Operation timed out")&&global.process.stdout.write(t+"哎呀~你的链接有问题,超时了!=== L519 \n"),-1!==t.indexOf("Conversion")&&console.log("*".concat(Wr,"*模式转换失败,请尝试改变transportType的值,然后重试。***")),-1!==t.indexOf("transport")&&global.process.stdout.write(t+"=== L520 \n")),-1!==t.indexOf("404 Not Found")&&global.process.stdout.write(t+"=== L521 \n"),-1!==t.indexOf("Invalid data found")&&global.process.stdout.write(t+"=== L522 \n"),-1!==t.indexOf("Unrecognized option")&&global.process.stdout.write(t+"=== L523 \n"),-1!==t.indexOf("pipe")&&global.process.stdout.write(t+"=== L524 \n"),-1!==t.indexOf("not found")){global.process.stdout.write(t+"=== L525 \n");var r=t.match(/Option (\w+) not found/)[1];if("rtsp_transport"==r)return void console.log("--[rtsp2web]请尝试修改 transportType 的值再重试,或者尝试去掉 transportType 再重试--");e.modifyOptions.del?e.modifyOptions.del.push(r):e.modifyOptions.del=[r],e.resetStream()}})),this.mpeg2Muxer.instance.on("ffmpegClosed",(function(){e.destroy()}))}},{key:"resetStream",value:(t=x().mark((function e(){var t,r;return x().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,null===(t=this.mpeg2Muxer.stream)||void 0===t?void 0:t.kill();case 2:this.mpeg2Muxer.stream=null,null===(r=this.mpeg2Muxer.instance)||void 0===r||r.removeAllListeners(),this.mpeg2Muxer.instance=null,console.log("[rtsp2web][自动修复]一个视频流转码被自动修复并重启中..."),this.isStreamWrap=!0,this.mpeg2Muxer.instance=new Yr({url:this.url,ffmpegOptions:this.formatParams(this.config),modifyOptions:this.modifyOptions}),this.mpeg2Muxer.stream=this.mpeg2Muxer.instance.stream,this.eventHandler();case 10:case"end":return e.stop()}}),e,this)})),r=function(){var e=this,r=arguments;return new Promise((function(n,s){var i=t.apply(e,r);function o(e){E(i,n,s,o,a,"next",e)}function a(e){E(i,n,s,o,a,"throw",e)}o(void 0)}))},function(){return r.apply(this,arguments)})},{key:"formatParams",value:function(e){for(var t={"-vf":Gr},r=0,n=Object.entries(e);r<n.length;r++){var s=I(n[r],2),i=s[0],o=s[1];Vr.includes(i)&&(zr.includes(i)?"scale"===i?t["-vf"]=t["-vf"].replace(/scale=[x0-9\:\-]*/g,"scale=".concat(o)):t["-vf"]+="".concat(i,"=").concat(o,":"):Hr(i,o)&&(t[i]=o))}return t}},{key:"destroy",value:function(){var e,t;null===(e=this.mpeg2Muxer.stream)||void 0===e||e.kill(),this.mpeg2Muxer.stream=null,null===(t=this.mpeg2Muxer.instance)||void 0===t||t.removeAllListeners(),this.mpeg2Muxer.instance=null,this.isStreamWrap=!1,this.dropAllClient()}},{key:"broadcast",value:function(e){var t,r=j(this.clients);try{for(r.s();!(t=r.n()).done;){var n=t.value;n.isSegment&&n.send(e)}}catch(e){r.e(e)}finally{r.f()}}},{key:"addClient",value:function(e){var t=this;e.once("close",(function(){t.dropClient(e)})),this.clients.push(e),this.isStreamWrap||this.createStream(),e.isSegment=!0}},{key:"dropClient",value:function(e){var t=this.clients.indexOf(e);e.isSegment=!1,e.terminate(),e=null,console.log("视频播放窗口关闭1个,销毁一个client(ws句柄)"),t>-1&&this.clients.splice(t,1)}},{key:"dropAllClient",value:function(){var e,t=j(this.clients);try{for(t.s();!(e=t.n()).done;){var r=e.value;r.isSegment=!1,r.terminate()}}catch(e){t.e(e)}finally{t.f()}this.clients=[]}}]),e}(),Qr=function(){function e(t){var r=this;O(this,e),L(this,"channels",[]),console.log("--[info]: current rtsp2web version: ".concat(Er,"; current platform is ").concat(global.process.platform,"--")),Or.exec("ffmpeg -version",(function(e,t,r){e&&console.log("请检查你的ffmpeg是否正确存在,错误信息:",e.stack)})),t&&"boolean"==typeof t.wm&&!t.wm&&(Gr="scale=-1:-1,eq=",Dr=!1),t&&"boolean"==typeof t.vf&&!t.vf&&(Fr=!1),t&&"string"==typeof t.path&&t.path.length>0&&(Nr=t.path),t&&"string"==typeof t.webplayer&&Pr.includes(t.webplayer)&&(Mr=t.webplayer),t&&"number"==typeof t.q&&t.q>=0&&(Br=t.q),t&&"string"==typeof t.transportType&&jr.includes(t.transportType)&&(Wr=t.transportType),t&&"boolean"==typeof t.audio&&!t.audio&&(Ar=!0),t&&["string","number"].includes(k(t.freeTime))&&"number"==typeof parseInt(t.freeTime,10)&&(qr=parseInt(t.freeTime,10)),t&&["string","number"].includes(k(t.checkTime))&&"number"==typeof parseInt(t.checkTime,10)&&($r=parseInt(t.checkTime,10)),setInterval((function(){r.checkFree(),Dr&&(Gr.includes(decodeURIComponent(D.exports.decode("eCUzRHctdHctNSUzQXklM0Q4MCUzQWZvbnRjb2xvciUzRHdoaXRlJTNBZm9udHNpemUlM0QzMiUzQXRleHQlM0RjbGVhciUyMHdpdGglMjBxcSUyMDQyMTM1NDUzMiUzQWJveCUzRDElM0Fib3hjb2xvciUzRGJsYWNr")))||(r.destroyAllChannel(),global.process.stderr.write("----wm代码异常、视频闪屏的问题----,请联系作者帮你解决!!")))}),1e3*$r);var n=u.default.createServer((function(e,t){t.writeHead(200),t.end("hello rtsp2web, with ws [ws] model ~ \n")}));if(t&&"object"===k(t.wss))if(console.log("wss启动中...."),t.wss.hasOwnProperty("pfx"))if(t.wss.hasOwnProperty("passphrase"))try{n=d.default.createServer({pfx:_.default.readFileSync(t.wss.pfx),passphrase:_.default.readFileSync(t.wss.passphrase)},(function(e,t){console.log("client connect cross wss!"),t.writeHead(200),t.end("hello rtsp2web, with wss [pfx&passphrase] model ~ \n")}))}catch(e){console.error("--[读取pfx安全证书文件出错,wss启动失败,退回到ws;请检查(pfx&passphrase),错误信息如下,有问题请联系我]--"),console.log(e)}else console.error("【wss启动失败:请传入正确的密码:passphrase】"),global.process.stdout.write("---ws正常开启中--- W11 \n");else if(t.wss.hasOwnProperty("cert"))if(t.wss.hasOwnProperty("key"))try{n=d.default.createServer({key:_.default.readFileSync(t.wss.key),cert:_.default.readFileSync(t.wss.cert)},(function(e,t){console.log("client connect cross wss!"),t.writeHead(200),t.end("hello rtsp2web, with wss [key&cert] model ~ \n")}))}catch(e){console.error("--[读取SSL证书文件Error,wss启动失败,退回到ws;请检查(key&cert),错误信息如下,有问题请联系我]--"),console.log(e)}else console.error("【wss启动失败;请传入正确的安全证书私钥:key.pem】"),global.process.stdout.write("---ws正常开启中--- W13 \n");else console.error("【wss启动失败;请传入正确的安全证书公钥:cert.pem】"),global.process.stdout.write("---ws正常开启中--- W12 \n");n.listen(t&&t.port||9999),Object.getPrototypeOf(n)instanceof p.default.Server&&console.log("wss model success!!!"),this.wss=new Lr({server:n}),this.wss.on("connection",(function(e,t){var n=Tr.parse(t.url,!0);if(n.query.url){var s=D.exports.decode(n.query.url.toString());n.query.url=s,r.registeClient(e,{url:s,options:n.query})}console.log("一个新的视频播放窗口(client,ws句柄)连接成功,请等待画面...")}))}return T(e,[{key:"registeClient",value:function(e,t){var r=this.getChannel(t.url);r||(r=this.createChannel(t.options,e)),r.addClient(e)}},{key:"getChannel",value:function(e){var t,r=j(this.channels);try{for(r.s();!(t=r.n()).done;){var n=t.value;if(n.url===e)return n}}catch(e){r.e(e)}finally{r.f()}return null}},{key:"createChannel",value:function(e,t){var r=new Xr(e,t);return this.channels.push(r),r}},{key:"checkFree",value:function(){var e,t=j(this.channels);try{for(t.s();!(e=t.n()).done;){var r=e.value;r.clients.length>0?r.freeTime=0:r.freeTime+=$r,r.freeTime>=qr&&this.destroyChannel(r)}}catch(e){t.e(e)}finally{t.f()}}},{key:"destroyChannel",value:function(e){var t=this.channels.indexOf(e);t>-1&&(this.channels.splice(t,1),e.destroy())}},{key:"destroyAllChannel",value:function(){var e,t=j(this.channels);try{for(t.s();!(e=t.n()).done;){var r=e.value;this.destroyChannel(r)}}catch(e){t.e(e)}finally{t.f()}}}]),e}();L(Qr,"version",Er),module.exports=Qr;
|
|
10
|
+
!function(e,t){!function(r){var n=t,s=e&&e.exports==n&&e,o="object"==typeof F&&F;o.global!==o&&o.window!==o||(r=o);var i=function(e){this.message=e};(i.prototype=new Error).name="InvalidCharacterError";var a=function(e){throw new i(e)},c="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",l=/[\t\n\f\r ]/g,h={encode:function(e){e=String(e),/[^\0-\xFF]/.test(e)&&a("The string to be encoded contains characters outside of the Latin1 range.");for(var t,r,n,s,o=e.length%3,i="",l=-1,h=e.length-o;++l<h;)t=e.charCodeAt(l)<<16,r=e.charCodeAt(++l)<<8,n=e.charCodeAt(++l),i+=c.charAt((s=t+r+n)>>18&63)+c.charAt(s>>12&63)+c.charAt(s>>6&63)+c.charAt(63&s);return 2==o?(t=e.charCodeAt(l)<<8,r=e.charCodeAt(++l),i+=c.charAt((s=t+r)>>10)+c.charAt(s>>4&63)+c.charAt(s<<2&63)+"="):1==o&&(s=e.charCodeAt(l),i+=c.charAt(s>>2)+c.charAt(s<<4&63)+"=="),i},decode:function(e){var t=(e=String(e).replace(l,"")).length;t%4==0&&(t=(e=e.replace(/==?$/,"")).length),(t%4==1||/[^+a-zA-Z0-9/]/.test(e))&&a("Invalid character: the string to be decoded is not correctly encoded.");for(var r,n,s=0,o="",i=-1;++i<t;)n=c.indexOf(e.charAt(i)),r=s%4?64*r+n:n,s++%4&&(o+=String.fromCharCode(255&r>>(-2*s&6)));return o},version:"1.0.0"};if(n&&!n.nodeType)if(s)s.exports=h;else for(var f in h)h.hasOwnProperty(f)&&(n[f]=h[f]);else r.base64=h}(F)}(D,D.exports);var G={exports:{}},q={BINARY_TYPES:["nodebuffer","arraybuffer","fragments"],EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}};const{EMPTY_BUFFER:$}=q,V=Buffer[Symbol.species];function z(e,t,r,n,s){for(let o=0;o<s;o++)r[n+o]=e[o]^t[3&o]}function H(e,t){for(let r=0;r<e.length;r++)e[r]^=t[3&r]}if(G.exports={concat:function(e,t){if(0===e.length)return $;if(1===e.length)return e[0];const r=Buffer.allocUnsafe(t);let n=0;for(let t=0;t<e.length;t++){const s=e[t];r.set(s,n),n+=s.length}return n<t?new V(r.buffer,r.byteOffset,n):r},mask:z,toArrayBuffer:function(e){return e.length===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.length)},toBuffer:function e(t){if(e.readOnly=!0,Buffer.isBuffer(t))return t;let r;return t instanceof ArrayBuffer?r=new V(t):ArrayBuffer.isView(t)?r=new V(t.buffer,t.byteOffset,t.byteLength):(r=Buffer.from(t),e.readOnly=!1),r},unmask:H},!process.env.WS_NO_BUFFER_UTIL)try{const e=require("bufferutil");G.exports.mask=function(t,r,n,s,o){o<48?z(t,r,n,s,o):e.mask(t,r,n,s,o)},G.exports.unmask=function(t,r){t.length<32?H(t,r):e.unmask(t,r)}}catch(e){}const Y=Symbol("kDone"),X=Symbol("kRun");var Q=class{constructor(e){this[Y]=()=>{this.pending--,this[X]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[X]()}[X](){if(this.pending!==this.concurrency&&this.jobs.length){const e=this.jobs.shift();this.pending++,e(this[Y])}}};const Z=w.default,K=G.exports,J=Q,{kStatusCode:ee}=q,te=Buffer[Symbol.species],re=Buffer.from([0,0,255,255]),ne=Symbol("permessage-deflate"),se=Symbol("total-length"),oe=Symbol("callback"),ie=Symbol("buffers"),ae=Symbol("error");let ce;var le=class{constructor(e,t,r){if(this._maxPayload=0|r,this._options=e||{},this._threshold=void 0!==this._options.threshold?this._options.threshold:1024,this._isServer=!!t,this._deflate=null,this._inflate=null,this.params=null,!ce){const e=void 0!==this._options.concurrencyLimit?this._options.concurrencyLimit:10;ce=new J(e)}}static get extensionName(){return"permessage-deflate"}offer(){const e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:null==this._options.clientMaxWindowBits&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){const e=this._deflate[oe];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){const t=this._options,r=e.find((e=>!(!1===t.serverNoContextTakeover&&e.server_no_context_takeover||e.server_max_window_bits&&(!1===t.serverMaxWindowBits||"number"==typeof t.serverMaxWindowBits&&t.serverMaxWindowBits>e.server_max_window_bits)||"number"==typeof t.clientMaxWindowBits&&!e.client_max_window_bits)));if(!r)throw new Error("None of the extension offers can be accepted");return t.serverNoContextTakeover&&(r.server_no_context_takeover=!0),t.clientNoContextTakeover&&(r.client_no_context_takeover=!0),"number"==typeof t.serverMaxWindowBits&&(r.server_max_window_bits=t.serverMaxWindowBits),"number"==typeof t.clientMaxWindowBits?r.client_max_window_bits=t.clientMaxWindowBits:!0!==r.client_max_window_bits&&!1!==t.clientMaxWindowBits||delete r.client_max_window_bits,r}acceptAsClient(e){const t=e[0];if(!1===this._options.clientNoContextTakeover&&t.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(t.client_max_window_bits){if(!1===this._options.clientMaxWindowBits||"number"==typeof this._options.clientMaxWindowBits&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"')}else"number"==typeof this._options.clientMaxWindowBits&&(t.client_max_window_bits=this._options.clientMaxWindowBits);return t}normalizeParams(e){return e.forEach((e=>{Object.keys(e).forEach((t=>{let r=e[t];if(r.length>1)throw new Error(`Parameter "${t}" must have only a single value`);if(r=r[0],"client_max_window_bits"===t){if(!0!==r){const e=+r;if(!Number.isInteger(e)||e<8||e>15)throw new TypeError(`Invalid value for parameter "${t}": ${r}`);r=e}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${t}": ${r}`)}else if("server_max_window_bits"===t){const e=+r;if(!Number.isInteger(e)||e<8||e>15)throw new TypeError(`Invalid value for parameter "${t}": ${r}`);r=e}else{if("client_no_context_takeover"!==t&&"server_no_context_takeover"!==t)throw new Error(`Unknown parameter "${t}"`);if(!0!==r)throw new TypeError(`Invalid value for parameter "${t}": ${r}`)}e[t]=r}))})),e}decompress(e,t,r){ce.add((n=>{this._decompress(e,t,((e,t)=>{n(),r(e,t)}))}))}compress(e,t,r){ce.add((n=>{this._compress(e,t,((e,t)=>{n(),r(e,t)}))}))}_decompress(e,t,r){const n=this._isServer?"client":"server";if(!this._inflate){const e=`${n}_max_window_bits`,t="number"!=typeof this.params[e]?Z.Z_DEFAULT_WINDOWBITS:this.params[e];this._inflate=Z.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[ne]=this,this._inflate[se]=0,this._inflate[ie]=[],this._inflate.on("error",ue),this._inflate.on("data",fe)}this._inflate[oe]=r,this._inflate.write(e),t&&this._inflate.write(re),this._inflate.flush((()=>{const e=this._inflate[ae];if(e)return this._inflate.close(),this._inflate=null,void r(e);const s=K.concat(this._inflate[ie],this._inflate[se]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[se]=0,this._inflate[ie]=[],t&&this.params[`${n}_no_context_takeover`]&&this._inflate.reset()),r(null,s)}))}_compress(e,t,r){const n=this._isServer?"server":"client";if(!this._deflate){const e=`${n}_max_window_bits`,t="number"!=typeof this.params[e]?Z.Z_DEFAULT_WINDOWBITS:this.params[e];this._deflate=Z.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[se]=0,this._deflate[ie]=[],this._deflate.on("data",he)}this._deflate[oe]=r,this._deflate.write(e),this._deflate.flush(Z.Z_SYNC_FLUSH,(()=>{if(!this._deflate)return;let e=K.concat(this._deflate[ie],this._deflate[se]);t&&(e=new te(e.buffer,e.byteOffset,e.length-4)),this._deflate[oe]=null,this._deflate[se]=0,this._deflate[ie]=[],t&&this.params[`${n}_no_context_takeover`]&&this._deflate.reset(),r(null,e)}))}};function he(e){this[ie].push(e),this[se]+=e.length}function fe(e){this[se]+=e.length,this[ne]._maxPayload<1||this[se]<=this[ne]._maxPayload?this[ie].push(e):(this[ae]=new RangeError("Max payload size exceeded"),this[ae].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[ae][ee]=1009,this.removeListener("data",fe),this.reset())}function ue(e){this[ne]._inflate=null,e[ee]=1007,this[oe](e)}var de={exports:{}};const{isUtf8:pe}=S.default;function me(e){const t=e.length;let r=0;for(;r<t;)if(0==(128&e[r]))r++;else if(192==(224&e[r])){if(r+1===t||128!=(192&e[r+1])||192==(254&e[r]))return!1;r+=2}else if(224==(240&e[r])){if(r+2>=t||128!=(192&e[r+1])||128!=(192&e[r+2])||224===e[r]&&128==(224&e[r+1])||237===e[r]&&160==(224&e[r+1]))return!1;r+=3}else{if(240!=(248&e[r]))return!1;if(r+3>=t||128!=(192&e[r+1])||128!=(192&e[r+2])||128!=(192&e[r+3])||240===e[r]&&128==(240&e[r+1])||244===e[r]&&e[r+1]>143||e[r]>244)return!1;r+=4}return!0}if(de.exports={isValidStatusCode:function(e){return e>=1e3&&e<=1014&&1004!==e&&1005!==e&&1006!==e||e>=3e3&&e<=4999},isValidUTF8:me,tokenChars:[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0]},pe)de.exports.isValidUTF8=function(e){return e.length<24?me(e):pe(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{const e=require("utf-8-validate");de.exports.isValidUTF8=function(t){return t.length<32?me(t):e(t)}}catch(e){}const{Writable:_e}=g.default,ye=le,{BINARY_TYPES:ve,EMPTY_BUFFER:ge,kStatusCode:be,kWebSocket:we}=q,{concat:Se,toArrayBuffer:xe,unmask:ke}=G.exports,{isValidStatusCode:Ee,isValidUTF8:Oe}=de.exports,Ce=Buffer[Symbol.species];var Te=class extends _e{constructor(e={}){super(),this._binaryType=e.binaryType||ve[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=0|e.maxPayload,this._skipUTF8Validation=!!e.skipUTF8Validation,this[we]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._state=0,this._loop=!1}_write(e,t,r){if(8===this._opcode&&0==this._state)return r();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(r)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){const t=this._buffers[0];return this._buffers[0]=new Ce(t.buffer,t.byteOffset+e,t.length-e),new Ce(t.buffer,t.byteOffset,e)}const t=Buffer.allocUnsafe(e);do{const r=this._buffers[0],n=t.length-e;e>=r.length?t.set(this._buffers.shift(),n):(t.set(new Uint8Array(r.buffer,r.byteOffset,e),n),this._buffers[0]=new Ce(r.buffer,r.byteOffset+e,r.length-e)),e-=r.length}while(e>0);return t}startLoop(e){let t;this._loop=!0;do{switch(this._state){case 0:t=this.getInfo();break;case 1:t=this.getPayloadLength16();break;case 2:t=this.getPayloadLength64();break;case 3:this.getMask();break;case 4:t=this.getData(e);break;default:return void(this._loop=!1)}}while(this._loop);e(t)}getInfo(){if(this._bufferedBytes<2)return void(this._loop=!1);const e=this.consume(2);if(0!=(48&e[0]))return this._loop=!1,Le(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");const t=64==(64&e[0]);if(t&&!this._extensions[ye.extensionName])return this._loop=!1,Le(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");if(this._fin=128==(128&e[0]),this._opcode=15&e[0],this._payloadLength=127&e[1],0===this._opcode){if(t)return this._loop=!1,Le(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");if(!this._fragmented)return this._loop=!1,Le(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");this._opcode=this._fragmented}else if(1===this._opcode||2===this._opcode){if(this._fragmented)return this._loop=!1,Le(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");this._compressed=t}else{if(!(this._opcode>7&&this._opcode<11))return this._loop=!1,Le(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");if(!this._fin)return this._loop=!1,Le(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");if(t)return this._loop=!1,Le(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");if(this._payloadLength>125||8===this._opcode&&1===this._payloadLength)return this._loop=!1,Le(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH")}if(this._fin||this._fragmented||(this._fragmented=this._opcode),this._masked=128==(128&e[1]),this._isServer){if(!this._masked)return this._loop=!1,Le(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK")}else if(this._masked)return this._loop=!1,Le(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");if(126===this._payloadLength)this._state=1;else{if(127!==this._payloadLength)return this.haveLength();this._state=2}}getPayloadLength16(){if(!(this._bufferedBytes<2))return this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength();this._loop=!1}getPayloadLength64(){if(this._bufferedBytes<8)return void(this._loop=!1);const e=this.consume(8),t=e.readUInt32BE(0);return t>Math.pow(2,21)-1?(this._loop=!1,Le(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH")):(this._payloadLength=t*Math.pow(2,32)+e.readUInt32BE(4),this.haveLength())}haveLength(){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0))return this._loop=!1,Le(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");this._masked?this._state=3:this._state=4}getMask(){this._bufferedBytes<4?this._loop=!1:(this._mask=this.consume(4),this._state=4)}getData(e){let t=ge;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength)return void(this._loop=!1);t=this.consume(this._payloadLength),this._masked&&0!=(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])&&ke(t,this._mask)}return this._opcode>7?this.controlMessage(t):this._compressed?(this._state=5,void this.decompress(t,e)):(t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage())}decompress(e,t){this._extensions[ye.extensionName].decompress(e,this._fin,((e,r)=>{if(e)return t(e);if(r.length){if(this._messageLength+=r.length,this._messageLength>this._maxPayload&&this._maxPayload>0)return t(Le(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"));this._fragments.push(r)}const n=this.dataMessage();if(n)return t(n);this.startLoop(t)}))}dataMessage(){if(this._fin){const e=this._messageLength,t=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],2===this._opcode){let r;r="nodebuffer"===this._binaryType?Se(t,e):"arraybuffer"===this._binaryType?xe(Se(t,e)):t,this.emit("message",r,!0)}else{const r=Se(t,e);if(!this._skipUTF8Validation&&!Oe(r))return this._loop=!1,Le(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");this.emit("message",r,!1)}}this._state=0}controlMessage(e){if(8===this._opcode)if(this._loop=!1,0===e.length)this.emit("conclude",1005,ge),this.end();else{const t=e.readUInt16BE(0);if(!Ee(t))return Le(RangeError,`invalid status code ${t}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");const r=new Ce(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Oe(r))return Le(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");this.emit("conclude",t,r),this.end()}else 9===this._opcode?this.emit("ping",e):this.emit("pong",e);this._state=0}};function Le(e,t,r,n,s){const o=new e(r?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(o,Le),o.code=s,o[be]=n,o}const{randomFillSync:Ne}=v.default,Pe=le,{EMPTY_BUFFER:Me}=q,{isValidStatusCode:Re}=de.exports,{mask:Ie,toBuffer:Ue}=G.exports,Ae=Symbol("kByteLength"),Be=Buffer.alloc(4);class je{constructor(e,t,r){this._extensions=t||{},r&&(this._generateMask=r,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._deflating=!1,this._queue=[]}static frame(e,t){let r,n,s=!1,o=2,i=!1;t.mask&&(r=t.maskBuffer||Be,t.generateMask?t.generateMask(r):Ne(r,0,4),i=0==(r[0]|r[1]|r[2]|r[3]),o=6),"string"==typeof e?n=t.mask&&!i||void 0===t[Ae]?(e=Buffer.from(e)).length:t[Ae]:(n=e.length,s=t.mask&&t.readOnly&&!i);let a=n;n>=65536?(o+=8,a=127):n>125&&(o+=2,a=126);const c=Buffer.allocUnsafe(s?n+o:o);return c[0]=t.fin?128|t.opcode:t.opcode,t.rsv1&&(c[0]|=64),c[1]=a,126===a?c.writeUInt16BE(n,2):127===a&&(c[2]=c[3]=0,c.writeUIntBE(n,4,6)),t.mask?(c[1]|=128,c[o-4]=r[0],c[o-3]=r[1],c[o-2]=r[2],c[o-1]=r[3],i?[c,e]:s?(Ie(e,r,c,o,n),[c]):(Ie(e,r,e,0,n),[c,e])):[c,e]}close(e,t,r,n){let s;if(void 0===e)s=Me;else{if("number"!=typeof e||!Re(e))throw new TypeError("First argument must be a valid error code number");if(void 0!==t&&t.length){const r=Buffer.byteLength(t);if(r>123)throw new RangeError("The message must not be greater than 123 bytes");s=Buffer.allocUnsafe(2+r),s.writeUInt16BE(e,0),"string"==typeof t?s.write(t,2):s.set(t,2)}else s=Buffer.allocUnsafe(2),s.writeUInt16BE(e,0)}const o={[Ae]:s.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._deflating?this.enqueue([this.dispatch,s,!1,o,n]):this.sendFrame(je.frame(s,o),n)}ping(e,t,r){let n,s;if("string"==typeof e?(n=Buffer.byteLength(e),s=!1):(n=(e=Ue(e)).length,s=Ue.readOnly),n>125)throw new RangeError("The data size must not be greater than 125 bytes");const o={[Ae]:n,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:s,rsv1:!1};this._deflating?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(je.frame(e,o),r)}pong(e,t,r){let n,s;if("string"==typeof e?(n=Buffer.byteLength(e),s=!1):(n=(e=Ue(e)).length,s=Ue.readOnly),n>125)throw new RangeError("The data size must not be greater than 125 bytes");const o={[Ae]:n,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:s,rsv1:!1};this._deflating?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(je.frame(e,o),r)}send(e,t,r){const n=this._extensions[Pe.extensionName];let s,o,i=t.binary?2:1,a=t.compress;if("string"==typeof e?(s=Buffer.byteLength(e),o=!1):(s=(e=Ue(e)).length,o=Ue.readOnly),this._firstFragment?(this._firstFragment=!1,a&&n&&n.params[n._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(a=s>=n._threshold),this._compress=a):(a=!1,i=0),t.fin&&(this._firstFragment=!0),n){const n={[Ae]:s,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:o,rsv1:a};this._deflating?this.enqueue([this.dispatch,e,this._compress,n,r]):this.dispatch(e,this._compress,n,r)}else this.sendFrame(je.frame(e,{[Ae]:s,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:o,rsv1:!1}),r)}dispatch(e,t,r,n){if(!t)return void this.sendFrame(je.frame(e,r),n);const s=this._extensions[Pe.extensionName];this._bufferedBytes+=r[Ae],this._deflating=!0,s.compress(e,r.fin,((e,t)=>{if(this._socket.destroyed){const e=new Error("The socket was closed while data was being compressed");"function"==typeof n&&n(e);for(let t=0;t<this._queue.length;t++){const r=this._queue[t],n=r[r.length-1];"function"==typeof n&&n(e)}}else this._bufferedBytes-=r[Ae],this._deflating=!1,r.readOnly=!1,this.sendFrame(je.frame(t,r),n),this.dequeue()}))}dequeue(){for(;!this._deflating&&this._queue.length;){const e=this._queue.shift();this._bufferedBytes-=e[3][Ae],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Ae],this._queue.push(e)}sendFrame(e,t){2===e.length?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}}var We=je;const{kForOnEventAttribute:Fe,kListener:De}=q,Ge=Symbol("kCode"),qe=Symbol("kData"),$e=Symbol("kError"),Ve=Symbol("kMessage"),ze=Symbol("kReason"),He=Symbol("kTarget"),Ye=Symbol("kType"),Xe=Symbol("kWasClean");class Qe{constructor(e){this[He]=null,this[Ye]=e}get target(){return this[He]}get type(){return this[Ye]}}Object.defineProperty(Qe.prototype,"target",{enumerable:!0}),Object.defineProperty(Qe.prototype,"type",{enumerable:!0});class Ze extends Qe{constructor(e,t={}){super(e),this[Ge]=void 0===t.code?0:t.code,this[ze]=void 0===t.reason?"":t.reason,this[Xe]=void 0!==t.wasClean&&t.wasClean}get code(){return this[Ge]}get reason(){return this[ze]}get wasClean(){return this[Xe]}}Object.defineProperty(Ze.prototype,"code",{enumerable:!0}),Object.defineProperty(Ze.prototype,"reason",{enumerable:!0}),Object.defineProperty(Ze.prototype,"wasClean",{enumerable:!0});class Ke extends Qe{constructor(e,t={}){super(e),this[$e]=void 0===t.error?null:t.error,this[Ve]=void 0===t.message?"":t.message}get error(){return this[$e]}get message(){return this[Ve]}}Object.defineProperty(Ke.prototype,"error",{enumerable:!0}),Object.defineProperty(Ke.prototype,"message",{enumerable:!0});class Je extends Qe{constructor(e,t={}){super(e),this[qe]=void 0===t.data?null:t.data}get data(){return this[qe]}}Object.defineProperty(Je.prototype,"data",{enumerable:!0});const et={addEventListener(e,t,r={}){for(const n of this.listeners(e))if(!r[Fe]&&n[De]===t&&!n[Fe])return;let n;if("message"===e)n=function(e,r){const n=new Je("message",{data:r?e:e.toString()});n[He]=this,rt(t,this,n)};else if("close"===e)n=function(e,r){const n=new Ze("close",{code:e,reason:r.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});n[He]=this,rt(t,this,n)};else if("error"===e)n=function(e){const r=new Ke("error",{error:e,message:e.message});r[He]=this,rt(t,this,r)};else{if("open"!==e)return;n=function(){const e=new Qe("open");e[He]=this,rt(t,this,e)}}n[Fe]=!!r[Fe],n[De]=t,r.once?this.once(e,n):this.on(e,n)},removeEventListener(e,t){for(const r of this.listeners(e))if(r[De]===t&&!r[Fe]){this.removeListener(e,r);break}}};var tt={CloseEvent:Ze,ErrorEvent:Ke,Event:Qe,EventTarget:et,MessageEvent:Je};function rt(e,t,r){"object"==typeof e&&e.handleEvent?e.handleEvent.call(e,r):e.call(t,r)}const{tokenChars:nt}=de.exports;function st(e,t,r){void 0===e[t]?e[t]=[r]:e[t].push(r)}var ot={format:function(e){return Object.keys(e).map((t=>{let r=e[t];return Array.isArray(r)||(r=[r]),r.map((e=>[t].concat(Object.keys(e).map((t=>{let r=e[t];return Array.isArray(r)||(r=[r]),r.map((e=>!0===e?t:`${t}=${e}`)).join("; ")}))).join("; "))).join(", ")})).join(", ")},parse:function(e){const t=Object.create(null);let r,n,s=Object.create(null),o=!1,i=!1,a=!1,c=-1,l=-1,h=-1,f=0;for(;f<e.length;f++)if(l=e.charCodeAt(f),void 0===r)if(-1===h&&1===nt[l])-1===c&&(c=f);else if(0===f||32!==l&&9!==l){if(59!==l&&44!==l)throw new SyntaxError(`Unexpected character at index ${f}`);{if(-1===c)throw new SyntaxError(`Unexpected character at index ${f}`);-1===h&&(h=f);const n=e.slice(c,h);44===l?(st(t,n,s),s=Object.create(null)):r=n,c=h=-1}}else-1===h&&-1!==c&&(h=f);else if(void 0===n)if(-1===h&&1===nt[l])-1===c&&(c=f);else if(32===l||9===l)-1===h&&-1!==c&&(h=f);else if(59===l||44===l){if(-1===c)throw new SyntaxError(`Unexpected character at index ${f}`);-1===h&&(h=f),st(s,e.slice(c,h),!0),44===l&&(st(t,r,s),s=Object.create(null),r=void 0),c=h=-1}else{if(61!==l||-1===c||-1!==h)throw new SyntaxError(`Unexpected character at index ${f}`);n=e.slice(c,f),c=h=-1}else if(i){if(1!==nt[l])throw new SyntaxError(`Unexpected character at index ${f}`);-1===c?c=f:o||(o=!0),i=!1}else if(a)if(1===nt[l])-1===c&&(c=f);else if(34===l&&-1!==c)a=!1,h=f;else{if(92!==l)throw new SyntaxError(`Unexpected character at index ${f}`);i=!0}else if(34===l&&61===e.charCodeAt(f-1))a=!0;else if(-1===h&&1===nt[l])-1===c&&(c=f);else if(-1===c||32!==l&&9!==l){if(59!==l&&44!==l)throw new SyntaxError(`Unexpected character at index ${f}`);{if(-1===c)throw new SyntaxError(`Unexpected character at index ${f}`);-1===h&&(h=f);let i=e.slice(c,h);o&&(i=i.replace(/\\/g,""),o=!1),st(s,n,i),44===l&&(st(t,r,s),s=Object.create(null),r=void 0),n=void 0,c=h=-1}}else-1===h&&(h=f);if(-1===c||a||32===l||9===l)throw new SyntaxError("Unexpected end of input");-1===h&&(h=f);const u=e.slice(c,h);return void 0===r?st(t,u,s):(void 0===n?st(s,u,!0):st(s,n,o?u.replace(/\\/g,""):u),st(t,r,s)),t}};const it=_.default,at=d.default,ct=u.default,lt=y.default,ht=p.default,{randomBytes:ft,createHash:ut}=v.default,{URL:dt}=b.default,pt=le,mt=Te,_t=We,{BINARY_TYPES:yt,EMPTY_BUFFER:vt,GUID:gt,kForOnEventAttribute:bt,kListener:wt,kStatusCode:St,kWebSocket:xt,NOOP:kt}=q,{EventTarget:{addEventListener:Et,removeEventListener:Ot}}=tt,{format:Ct,parse:Tt}=ot,{toBuffer:Lt}=G.exports,Nt=Symbol("kAborted"),Pt=[8,13],Mt=["CONNECTING","OPEN","CLOSING","CLOSED"],Rt=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;class It extends it{constructor(e,t,r){super(),this._binaryType=yt[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=vt,this._closeTimer=null,this._extensions={},this._paused=!1,this._protocol="",this._readyState=It.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,null!==e?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,void 0===t?t=[]:Array.isArray(t)||("object"==typeof t&&null!==t?(r=t,t=[]):t=[t]),At(this,e,t,r)):this._isServer=!0}get binaryType(){return this._binaryType}set binaryType(e){yt.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,t,r){const n=new mt({binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation});this._sender=new _t(e,this._extensions,r.generateMask),this._receiver=n,this._socket=e,n[xt]=this,e[xt]=this,n.on("conclude",Gt),n.on("drain",qt),n.on("error",$t),n.on("message",zt),n.on("ping",Ht),n.on("pong",Yt),e.setTimeout(0),e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",Qt),e.on("data",Zt),e.on("end",Kt),e.on("error",Jt),this._readyState=It.OPEN,this.emit("open")}emitClose(){if(!this._socket)return this._readyState=It.CLOSED,void this.emit("close",this._closeCode,this._closeMessage);this._extensions[pt.extensionName]&&this._extensions[pt.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=It.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,t){if(this.readyState!==It.CLOSED)if(this.readyState!==It.CONNECTING)this.readyState!==It.CLOSING?(this._readyState=It.CLOSING,this._sender.close(e,t,!this._isServer,(e=>{e||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())})),this._closeTimer=setTimeout(this._socket.destroy.bind(this._socket),3e4)):this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();else{const e="WebSocket was closed before the connection was established";Ft(this,this._req,e)}}pause(){this.readyState!==It.CONNECTING&&this.readyState!==It.CLOSED&&(this._paused=!0,this._socket.pause())}ping(e,t,r){if(this.readyState===It.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");"function"==typeof e?(r=e,e=t=void 0):"function"==typeof t&&(r=t,t=void 0),"number"==typeof e&&(e=e.toString()),this.readyState===It.OPEN?(void 0===t&&(t=!this._isServer),this._sender.ping(e||vt,t,r)):Dt(this,e,r)}pong(e,t,r){if(this.readyState===It.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");"function"==typeof e?(r=e,e=t=void 0):"function"==typeof t&&(r=t,t=void 0),"number"==typeof e&&(e=e.toString()),this.readyState===It.OPEN?(void 0===t&&(t=!this._isServer),this._sender.pong(e||vt,t,r)):Dt(this,e,r)}resume(){this.readyState!==It.CONNECTING&&this.readyState!==It.CLOSED&&(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,t,r){if(this.readyState===It.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if("function"==typeof t&&(r=t,t={}),"number"==typeof e&&(e=e.toString()),this.readyState!==It.OPEN)return void Dt(this,e,r);const n={binary:"string"!=typeof e,mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[pt.extensionName]||(n.compress=!1),this._sender.send(e||vt,n,r)}terminate(){if(this.readyState!==It.CLOSED)if(this.readyState!==It.CONNECTING)this._socket&&(this._readyState=It.CLOSING,this._socket.destroy());else{const e="WebSocket was closed before the connection was established";Ft(this,this._req,e)}}}Object.defineProperty(It,"CONNECTING",{enumerable:!0,value:Mt.indexOf("CONNECTING")}),Object.defineProperty(It.prototype,"CONNECTING",{enumerable:!0,value:Mt.indexOf("CONNECTING")}),Object.defineProperty(It,"OPEN",{enumerable:!0,value:Mt.indexOf("OPEN")}),Object.defineProperty(It.prototype,"OPEN",{enumerable:!0,value:Mt.indexOf("OPEN")}),Object.defineProperty(It,"CLOSING",{enumerable:!0,value:Mt.indexOf("CLOSING")}),Object.defineProperty(It.prototype,"CLOSING",{enumerable:!0,value:Mt.indexOf("CLOSING")}),Object.defineProperty(It,"CLOSED",{enumerable:!0,value:Mt.indexOf("CLOSED")}),Object.defineProperty(It.prototype,"CLOSED",{enumerable:!0,value:Mt.indexOf("CLOSED")}),["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach((e=>{Object.defineProperty(It.prototype,e,{enumerable:!0})})),["open","error","close","message"].forEach((e=>{Object.defineProperty(It.prototype,`on${e}`,{enumerable:!0,get(){for(const t of this.listeners(e))if(t[bt])return t[wt];return null},set(t){for(const t of this.listeners(e))if(t[bt]){this.removeListener(e,t);break}"function"==typeof t&&this.addEventListener(e,t,{[bt]:!0})}})})),It.prototype.addEventListener=Et,It.prototype.removeEventListener=Ot;var Ut=It;function At(e,t,r,n){const s={protocolVersion:Pt[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...n,createConnection:void 0,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(!Pt.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${Pt.join(", ")})`);let o;if(t instanceof dt)o=t,e._url=t.href;else{try{o=new dt(t)}catch(e){throw new SyntaxError(`Invalid URL: ${t}`)}e._url=t}const i="wss:"===o.protocol,a="ws+unix:"===o.protocol;let c;if("ws:"===o.protocol||i||a?a&&!o.pathname?c="The URL's pathname is empty":o.hash&&(c="The URL contains a fragment identifier"):c='The URL\'s protocol must be one of "ws:", "wss:", or "ws+unix:"',c){const t=new SyntaxError(c);if(0===e._redirects)throw t;return void Bt(e,t)}const l=i?443:80,h=ft(16).toString("base64"),f=i?at.request:ct.request,u=new Set;let d,p;if(s.createConnection=i?Wt:jt,s.defaultPort=s.defaultPort||l,s.port=o.port||l,s.host=o.hostname.startsWith("[")?o.hostname.slice(1,-1):o.hostname,s.headers={...s.headers,"Sec-WebSocket-Version":s.protocolVersion,"Sec-WebSocket-Key":h,Connection:"Upgrade",Upgrade:"websocket"},s.path=o.pathname+o.search,s.timeout=s.handshakeTimeout,s.perMessageDeflate&&(d=new pt(!0!==s.perMessageDeflate?s.perMessageDeflate:{},!1,s.maxPayload),s.headers["Sec-WebSocket-Extensions"]=Ct({[pt.extensionName]:d.offer()})),r.length){for(const e of r){if("string"!=typeof e||!Rt.test(e)||u.has(e))throw new SyntaxError("An invalid or duplicated subprotocol was specified");u.add(e)}s.headers["Sec-WebSocket-Protocol"]=r.join(",")}if(s.origin&&(s.protocolVersion<13?s.headers["Sec-WebSocket-Origin"]=s.origin:s.headers.Origin=s.origin),(o.username||o.password)&&(s.auth=`${o.username}:${o.password}`),a){const e=s.path.split(":");s.socketPath=e[0],s.path=e[1]}if(s.followRedirects){if(0===e._redirects){e._originalIpc=a,e._originalSecure=i,e._originalHostOrSocketPath=a?s.socketPath:o.host;const t=n&&n.headers;if(n={...n,headers:{}},t)for(const[e,r]of Object.entries(t))n.headers[e.toLowerCase()]=r}else if(0===e.listenerCount("redirect")){const t=a?!!e._originalIpc&&s.socketPath===e._originalHostOrSocketPath:!e._originalIpc&&o.host===e._originalHostOrSocketPath;(!t||e._originalSecure&&!i)&&(delete s.headers.authorization,delete s.headers.cookie,t||delete s.headers.host,s.auth=void 0)}s.auth&&!n.headers.authorization&&(n.headers.authorization="Basic "+Buffer.from(s.auth).toString("base64")),p=e._req=f(s),e._redirects&&e.emit("redirect",e.url,p)}else p=e._req=f(s);s.timeout&&p.on("timeout",(()=>{Ft(e,p,"Opening handshake has timed out")})),p.on("error",(t=>{null===p||p[Nt]||(p=e._req=null,Bt(e,t))})),p.on("response",(o=>{const i=o.headers.location,a=o.statusCode;if(i&&s.followRedirects&&a>=300&&a<400){if(++e._redirects>s.maxRedirects)return void Ft(e,p,"Maximum redirects exceeded");let o;p.abort();try{o=new dt(i,t)}catch(t){const r=new SyntaxError(`Invalid URL: ${i}`);return void Bt(e,r)}At(e,o,r,n)}else e.emit("unexpected-response",p,o)||Ft(e,p,`Unexpected server response: ${o.statusCode}`)})),p.on("upgrade",((t,r,n)=>{if(e.emit("upgrade",t),e.readyState!==It.CONNECTING)return;if(p=e._req=null,"websocket"!==t.headers.upgrade.toLowerCase())return void Ft(e,r,"Invalid Upgrade header");const o=ut("sha1").update(h+gt).digest("base64");if(t.headers["sec-websocket-accept"]!==o)return void Ft(e,r,"Invalid Sec-WebSocket-Accept header");const i=t.headers["sec-websocket-protocol"];let a;if(void 0!==i?u.size?u.has(i)||(a="Server sent an invalid subprotocol"):a="Server sent a subprotocol but none was requested":u.size&&(a="Server sent no subprotocol"),a)return void Ft(e,r,a);i&&(e._protocol=i);const c=t.headers["sec-websocket-extensions"];if(void 0!==c){if(!d){return void Ft(e,r,"Server sent a Sec-WebSocket-Extensions header but no extension was requested")}let t;try{t=Tt(c)}catch(t){return void Ft(e,r,"Invalid Sec-WebSocket-Extensions header")}const n=Object.keys(t);if(1!==n.length||n[0]!==pt.extensionName){return void Ft(e,r,"Server indicated an extension that was not requested")}try{d.accept(t[pt.extensionName])}catch(t){return void Ft(e,r,"Invalid Sec-WebSocket-Extensions header")}e._extensions[pt.extensionName]=d}e.setSocket(r,n,{generateMask:s.generateMask,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})})),p.end()}function Bt(e,t){e._readyState=It.CLOSING,e.emit("error",t),e.emitClose()}function jt(e){return e.path=e.socketPath,lt.connect(e)}function Wt(e){return e.path=void 0,e.servername||""===e.servername||(e.servername=lt.isIP(e.host)?"":e.host),ht.connect(e)}function Ft(e,t,r){e._readyState=It.CLOSING;const n=new Error(r);Error.captureStackTrace(n,Ft),t.setHeader?(t[Nt]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(Bt,e,n)):(t.destroy(n),t.once("error",e.emit.bind(e,"error")),t.once("close",e.emitClose.bind(e)))}function Dt(e,t,r){if(t){const r=Lt(t).length;e._socket?e._sender._bufferedBytes+=r:e._bufferedAmount+=r}if(r){const t=new Error(`WebSocket is not open: readyState ${e.readyState} (${Mt[e.readyState]})`);process.nextTick(r,t)}}function Gt(e,t){const r=this[xt];r._closeFrameReceived=!0,r._closeMessage=t,r._closeCode=e,void 0!==r._socket[xt]&&(r._socket.removeListener("data",Zt),process.nextTick(Xt,r._socket),1005===e?r.close():r.close(e,t))}function qt(){const e=this[xt];e.isPaused||e._socket.resume()}function $t(e){const t=this[xt];void 0!==t._socket[xt]&&(t._socket.removeListener("data",Zt),process.nextTick(Xt,t._socket),t.close(e[St])),t.emit("error",e)}function Vt(){this[xt].emitClose()}function zt(e,t){this[xt].emit("message",e,t)}function Ht(e){const t=this[xt];t.pong(e,!t._isServer,kt),t.emit("ping",e)}function Yt(e){this[xt].emit("pong",e)}function Xt(e){e.resume()}function Qt(){const e=this[xt];let t;this.removeListener("close",Qt),this.removeListener("data",Zt),this.removeListener("end",Kt),e._readyState=It.CLOSING,this._readableState.endEmitted||e._closeFrameReceived||e._receiver._writableState.errorEmitted||null===(t=e._socket.read())||e._receiver.write(t),e._receiver.end(),this[xt]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on("error",Vt),e._receiver.on("finish",Vt))}function Zt(e){this[xt]._receiver.write(e)||this.pause()}function Kt(){const e=this[xt];e._readyState=It.CLOSING,e._receiver.end(),this.end()}function Jt(){const e=this[xt];this.removeListener("error",Jt),this.on("error",kt),e&&(e._readyState=It.CLOSING,this.destroy())}const{Duplex:er}=g.default;function tr(e){e.emit("close")}function rr(){!this.destroyed&&this._writableState.finished&&this.destroy()}function nr(e){this.removeListener("error",nr),this.destroy(),0===this.listenerCount("error")&&this.emit("error",e)}var sr=function(e,t){let r=!0;const n=new er({...t,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return e.on("message",(function(t,r){const s=!r&&n._readableState.objectMode?t.toString():t;n.push(s)||e.pause()})),e.once("error",(function(e){n.destroyed||(r=!1,n.destroy(e))})),e.once("close",(function(){n.destroyed||n.push(null)})),n._destroy=function(t,s){if(e.readyState===e.CLOSED)return s(t),void process.nextTick(tr,n);let o=!1;e.once("error",(function(e){o=!0,s(e)})),e.once("close",(function(){o||s(t),process.nextTick(tr,n)})),r&&e.terminate()},n._final=function(t){e.readyState!==e.CONNECTING?null!==e._socket&&(e._socket._writableState.finished?(t(),n._readableState.endEmitted&&n.destroy()):(e._socket.once("finish",(function(){t()})),e.close())):e.once("open",(function(){n._final(t)}))},n._read=function(){e.isPaused&&e.resume()},n._write=function(t,r,s){e.readyState!==e.CONNECTING?e.send(t,s):e.once("open",(function(){n._write(t,r,s)}))},n.on("end",rr),n.on("error",nr),n};const{tokenChars:or}=de.exports;var ir={parse:function(e){const t=new Set;let r=-1,n=-1,s=0;for(;s<e.length;s++){const o=e.charCodeAt(s);if(-1===n&&1===or[o])-1===r&&(r=s);else if(0===s||32!==o&&9!==o){if(44!==o)throw new SyntaxError(`Unexpected character at index ${s}`);{if(-1===r)throw new SyntaxError(`Unexpected character at index ${s}`);-1===n&&(n=s);const o=e.slice(r,n);if(t.has(o))throw new SyntaxError(`The "${o}" subprotocol is duplicated`);t.add(o),r=n=-1}}else-1===n&&-1!==r&&(n=s)}if(-1===r||-1!==n)throw new SyntaxError("Unexpected end of input");const o=e.slice(r,s);if(t.has(o))throw new SyntaxError(`The "${o}" subprotocol is duplicated`);return t.add(o),t}};const ar=_.default,cr=u.default,{createHash:lr}=v.default,hr=ot,fr=le,ur=ir,dr=Ut,{GUID:pr,kWebSocket:mr}=q,_r=/^[+/0-9A-Za-z]{22}==$/,yr=2;var vr=class extends ar{constructor(e,t){if(super(),null==(e={maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:dr,...e}).port&&!e.server&&!e.noServer||null!=e.port&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(null!=e.port?(this._server=cr.createServer(((e,t)=>{const r=cr.STATUS_CODES[426];t.writeHead(426,{"Content-Length":r.length,"Content-Type":"text/plain"}),t.end(r)})),this._server.listen(e.port,e.host,e.backlog,t)):e.server&&(this._server=e.server),this._server){const e=this.emit.bind(this,"connection");this._removeListeners=function(e,t){for(const r of Object.keys(t))e.on(r,t[r]);return function(){for(const r of Object.keys(t))e.removeListener(r,t[r])}}(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(t,r,n)=>{this.handleUpgrade(t,r,n,e)}})}!0===e.perMessageDeflate&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=0}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(this._state===yr)return e&&this.once("close",(()=>{e(new Error("The server is not running"))})),void process.nextTick(gr,this);if(e&&this.once("close",e),1!==this._state)if(this._state=1,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients&&this.clients.size?this._shouldEmitClose=!0:process.nextTick(gr,this);else{const e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close((()=>{gr(this)}))}}shouldHandle(e){if(this.options.path){const t=e.url.indexOf("?");if((-1!==t?e.url.slice(0,t):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,t,r,n){t.on("error",br);const s=e.headers["sec-websocket-key"],o=+e.headers["sec-websocket-version"];if("GET"!==e.method){return void Sr(this,e,t,405,"Invalid HTTP method")}if("websocket"!==e.headers.upgrade.toLowerCase()){return void Sr(this,e,t,400,"Invalid Upgrade header")}if(!s||!_r.test(s)){return void Sr(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header")}if(8!==o&&13!==o){return void Sr(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header")}if(!this.shouldHandle(e))return void wr(t,400);const i=e.headers["sec-websocket-protocol"];let a=new Set;if(void 0!==i)try{a=ur.parse(i)}catch(r){return void Sr(this,e,t,400,"Invalid Sec-WebSocket-Protocol header")}const c=e.headers["sec-websocket-extensions"],l={};if(this.options.perMessageDeflate&&void 0!==c){const r=new fr(this.options.perMessageDeflate,!0,this.options.maxPayload);try{const e=hr.parse(c);e[fr.extensionName]&&(r.accept(e[fr.extensionName]),l[fr.extensionName]=r)}catch(r){return void Sr(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header")}}if(this.options.verifyClient){const i={origin:e.headers[""+(8===o?"sec-websocket-origin":"origin")],secure:!(!e.socket.authorized&&!e.socket.encrypted),req:e};if(2===this.options.verifyClient.length)return void this.options.verifyClient(i,((o,i,c,h)=>{if(!o)return wr(t,i||401,c,h);this.completeUpgrade(l,s,a,e,t,r,n)}));if(!this.options.verifyClient(i))return wr(t,401)}this.completeUpgrade(l,s,a,e,t,r,n)}completeUpgrade(e,t,r,n,s,o,i){if(!s.readable||!s.writable)return s.destroy();if(s[mr])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>0)return wr(s,503);const a=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${lr("sha1").update(t+pr).digest("base64")}`],c=new this.options.WebSocket(null);if(r.size){const e=this.options.handleProtocols?this.options.handleProtocols(r,n):r.values().next().value;e&&(a.push(`Sec-WebSocket-Protocol: ${e}`),c._protocol=e)}if(e[fr.extensionName]){const t=e[fr.extensionName].params,r=hr.format({[fr.extensionName]:[t]});a.push(`Sec-WebSocket-Extensions: ${r}`),c._extensions=e}this.emit("headers",a,n),s.write(a.concat("\r\n").join("\r\n")),s.removeListener("error",br),c.setSocket(s,o,{maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(c),c.on("close",(()=>{this.clients.delete(c),this._shouldEmitClose&&!this.clients.size&&process.nextTick(gr,this)}))),i(c,n)}};function gr(e){e._state=yr,e.emit("close")}function br(){this.destroy()}function wr(e,t,r,n){r=r||cr.STATUS_CODES[t],n={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(r),...n},e.once("finish",e.destroy),e.end(`HTTP/1.1 ${t} ${cr.STATUS_CODES[t]}\r\n`+Object.keys(n).map((e=>`${e}: ${n[e]}`)).join("\r\n")+"\r\n\r\n"+r)}function Sr(e,t,r,n,s){if(e.listenerCount("wsClientError")){const n=new Error(s);Error.captureStackTrace(n,Sr),e.emit("wsClientError",n,r,t)}else wr(r,n,s)}const xr=Ut;xr.createWebSocketStream=sr,xr.Server=vr,xr.Receiver=Te,xr.Sender=We,xr.WebSocket=xr,xr.WebSocketServer=xr.Server;var kr=xr,Er="3.1.7",Or=require("child_process"),Cr=require("events"),Tr=require("url"),Lr=kr.Server,Nr="ffmpeg",Pr=["jsmpeg","flv"],Mr="jsmpeg",Rr={jsmpeg:"mpegts",flv:"flv"},Ir={jsmpeg:"mpeg1video",flv:"libx264"},Ur={jsmpeg:"mp2",flv:"aac"},Ar=!1,Br=8,jr=["tcp","udp","udp_multicast","http","https"],Wr="",Fr=!0,Dr=!0,Gr="drawtext=x=w-tw-5:y=80:fontcolor=white:fontsize=32:text="+decodeURIComponent(D.exports.decode("Y2xlYXIlMjB3aXRoJTIwcXElMjA0MjEzNTQ1MzI="))+":box=1:boxcolor=black,scale=-1:-1,eq=",qr=20,$r=10,Vr=["-s","-b:v","webplayer","scale","contrast","brightness","saturation","gamma"].concat(["vcodec"]),zr=["scale","contrast","brightness","saturation","gamma"],Hr=function(e,t){switch(e){case"-s":if(t.includes("x")&&t.split("x")[0]&&t.split("x")[0]>0&&t.split("x")[1]&&t.split("x")[1]>0)return!0;break;case"vcodec":case"webplayer":case"contrast":case"brightness":case"saturation":case"gamma":if(t)return!0;break;case"-b:v":if(t.endsWith("k"))return!0;break;case"scale":if(t.includes(":")&&t.split(":")[0]&&t.split(":")[1])return!0}},Yr=function(e){!function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&P(e,t)}(r,Cr.EventEmitter);var t=R(r);function r(e){var n;return O(this,r),L(M(n=t.call(this)),"exitCode",void 0),L(M(n),"additionalFlags",[]),L(M(n),"stream",null),L(M(n),"inputStreamStarted",!1),n.ffmpegPath=Nr,n.url=e.url,n.ffmpegOptions=e.ffmpegOptions,n.modifyOptions=e.modifyOptions||{},n.options=e,n.initMpeg2Muxer(),n}return T(r,[{key:"initMpeg2Muxer",value:function(){var e,t=this;if(Fr||delete this.ffmpegOptions["-vf"],this.ffmpegOptions.webplayer&&(Mr=this.ffmpegOptions.webplayer,delete this.ffmpegOptions.webplayer),this.ffmpegOptions)for(var r in this.ffmpegOptions)this.additionalFlags.push(r),""!==String(this.ffmpegOptions[r])&&this.additionalFlags.push(String(this.ffmpegOptions[r]));(this.spawnOptions=["-re","-thread_queue_size","512","-threads","8","-i",this.url,"-c:v",Ir[Mr],"-q",Br,"-f",Rr[Mr],"-r","25","-c:a",Ur[Mr],Ar?"-an":null,"-ar","48000","-ac","1"].concat(U(this.additionalFlags),["-nostats","-"]),this.modifyOptions)&&(this.modifyOptions.del&&(null===(e=this.modifyOptions.del)||void 0===e||e.forEach((function(e){"buffer_size"==e&&(t.spawnOptions[1]=null,t.spawnOptions[2]=null)}))));String(Wr).length>0&&this.spawnOptions.splice(1,0,"-rtsp_transport",String(Wr)),this.spawnOptions=this.spawnOptions.filter((function(e){return null!==e})),this.stream=Or.spawn(this.ffmpegPath,this.spawnOptions,{detached:!1}),this.stream.on("error",(function(e,t){console.error("**启动ffmpeg时出错,请确保你安装了ffmpeg,然后检查路径或者命令参数~,code:",e,"signal:",t)})),this.stream.on("exit",(function(e,r){return console.error("[ffmpeg]某个视频流转码进程退出了: **如果非正常关闭视频导致的退出,请检查ffmpeg参数或检查代码或联系作者解决**,code:",e,"signal:",r),t.emit("exitWithError")})),this.stream.on("close",(function(e,r){return console.log("[ffmpeg]某个视频流转码进程关闭了: code: ",e),t.emit("ffmpegClosed")})),this.inputStreamStarted=!0,this.stream.stdout.on("data",(function(e){return t.emit("mpeg2data",e)})),this.stream.stderr.on("data",(function(e){return t.emit("ffmpegStderr",e)}))}}]),r}(),Xr=function(){function e(t){O(this,e),L(this,"freeTime",0),L(this,"width",null),L(this,"height",null),L(this,"isStreamWrap",!1),L(this,"clients",[]),L(this,"mpeg2Muxer",{instance:null,stream:null,data:null}),L(this,"modifyOptions",{}),this.config=t,this.url=t.url}var t,r;return T(e,[{key:"createStream",value:function(){this.isStreamWrap||(console.log("[ffmpeg]创建一个新的视频流转码进程~"),this.isStreamWrap=!0,this.mpeg2Muxer.instance=new Yr({url:this.url,ffmpegOptions:this.formatParams(this.config)}),this.mpeg2Muxer.stream=this.mpeg2Muxer.instance.stream,this.eventHandler())}},{key:"eventHandler",value:function(){var e=this;this.mpeg2Muxer.instance.on("mpeg2data",(function(t){e.broadcast(t)})),this.mpeg2Muxer.instance.on("ffmpegStderr",(function(t){if(-1!==(t=t.toString()).indexOf("failed")&&(global.process.stdout.write(t+"=== L518 \n"),-1!==t.indexOf("Operation timed out")&&global.process.stdout.write(t+"哎呀~你的链接有问题,超时了!=== L519 \n"),-1!==t.indexOf("Conversion")&&console.log("*".concat(Wr,"*模式转换失败,请尝试改变transportType的值,然后重试。***")),-1!==t.indexOf("transport")&&global.process.stdout.write(t+"=== L520 \n")),-1!==t.indexOf("404 Not Found")&&global.process.stdout.write(t+"=== L521 \n"),-1!==t.indexOf("Invalid data found")&&global.process.stdout.write(t+"=== L522 \n"),-1!==t.indexOf("Unrecognized option")&&global.process.stdout.write(t+"=== L523 \n"),-1!==t.indexOf("pipe")&&global.process.stdout.write(t+"=== L524 \n"),-1!==t.indexOf("not found")){global.process.stdout.write(t+"=== L525 \n");var r=t.match(/Option (\w+) not found/)[1];if("rtsp_transport"==r)return void console.log("--[rtsp2web]请尝试修改 transportType 的值再重试,或者尝试去掉 transportType 再重试--");e.modifyOptions.del?e.modifyOptions.del.push(r):e.modifyOptions.del=[r],e.resetStream()}})),this.mpeg2Muxer.instance.on("ffmpegClosed",(function(){e.destroy()}))}},{key:"resetStream",value:(t=x().mark((function e(){var t,r;return x().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,null===(t=this.mpeg2Muxer.stream)||void 0===t?void 0:t.kill();case 2:this.mpeg2Muxer.stream=null,null===(r=this.mpeg2Muxer.instance)||void 0===r||r.removeAllListeners(),this.mpeg2Muxer.instance=null,console.log("[rtsp2web][自动修复]一个视频流转码被自动修复并重启中..."),this.isStreamWrap=!0,this.mpeg2Muxer.instance=new Yr({url:this.url,ffmpegOptions:this.formatParams(this.config),modifyOptions:this.modifyOptions}),this.mpeg2Muxer.stream=this.mpeg2Muxer.instance.stream,this.eventHandler();case 10:case"end":return e.stop()}}),e,this)})),r=function(){var e=this,r=arguments;return new Promise((function(n,s){var o=t.apply(e,r);function i(e){E(o,n,s,i,a,"next",e)}function a(e){E(o,n,s,i,a,"throw",e)}i(void 0)}))},function(){return r.apply(this,arguments)})},{key:"formatParams",value:function(e){for(var t={"-vf":Gr},r=0,n=Object.entries(e);r<n.length;r++){var s=I(n[r],2),o=s[0],i=s[1];Vr.includes(o)&&(zr.includes(o)?"scale"===o?t["-vf"]=t["-vf"].replace(/scale=[x0-9\:\-]*/g,"scale=".concat(i)):t["-vf"]+="".concat(o,"=").concat(i,":"):Hr(o,i)&&(t[o]=i))}return t}},{key:"destroy",value:function(){var e,t;null===(e=this.mpeg2Muxer.stream)||void 0===e||e.kill(),this.mpeg2Muxer.stream=null,null===(t=this.mpeg2Muxer.instance)||void 0===t||t.removeAllListeners(),this.mpeg2Muxer.instance=null,this.isStreamWrap=!1,this.dropAllClient()}},{key:"broadcast",value:function(e){var t,r=j(this.clients);try{for(r.s();!(t=r.n()).done;){var n=t.value;n.isSegment&&n.send(e)}}catch(e){r.e(e)}finally{r.f()}}},{key:"addClient",value:function(e){var t=this;e.once("close",(function(){t.dropClient(e)})),this.clients.push(e),this.isStreamWrap||this.createStream(),e.isSegment=!0}},{key:"dropClient",value:function(e){var t=this.clients.indexOf(e);e.isSegment=!1,e.terminate(),e=null,console.log("视频播放窗口关闭1个,销毁一个client(ws句柄)"),t>-1&&this.clients.splice(t,1)}},{key:"dropAllClient",value:function(){var e,t=j(this.clients);try{for(t.s();!(e=t.n()).done;){var r=e.value;r.isSegment=!1,r.terminate()}}catch(e){t.e(e)}finally{t.f()}this.clients=[]}}]),e}(),Qr=function(){function e(t){var r=this;O(this,e),L(this,"channels",[]),console.log("--[info]: current rtsp2web version: ".concat(Er,"; current platform is ").concat(global.process.platform,"--")),Or.exec("ffmpeg -version",(function(e,t,r){e&&console.log("请检查你的ffmpeg是否正确存在,错误信息:",e.stack)})),t&&"boolean"==typeof t.wm&&!t.wm&&(Gr="scale=-1:-1,eq=",Dr=!1),t&&"boolean"==typeof t.vf&&!t.vf&&(Fr=!1),t&&"string"==typeof t.path&&t.path.length>0&&(Nr=t.path),t&&"string"==typeof t.webplayer&&Pr.includes(t.webplayer)&&(Mr=t.webplayer),t&&"number"==typeof t.q&&t.q>=0&&(Br=t.q),t&&"string"==typeof t.transportType&&jr.includes(t.transportType)&&(Wr=t.transportType),t&&"boolean"==typeof t.audio&&!t.audio&&(Ar=!0),t&&["string","number"].includes(k(t.freeTime))&&"number"==typeof parseInt(t.freeTime,10)&&(qr=parseInt(t.freeTime,10)),t&&["string","number"].includes(k(t.checkTime))&&"number"==typeof parseInt(t.checkTime,10)&&($r=parseInt(t.checkTime,10)),setInterval((function(){r.checkFree(),Dr&&(Gr.includes(decodeURIComponent(D.exports.decode("eCUzRHctdHctNSUzQXklM0Q4MCUzQWZvbnRjb2xvciUzRHdoaXRlJTNBZm9udHNpemUlM0QzMiUzQXRleHQlM0RjbGVhciUyMHdpdGglMjBxcSUyMDQyMTM1NDUzMiUzQWJveCUzRDElM0Fib3hjb2xvciUzRGJsYWNr")))||(r.destroyAllChannel(),global.process.stderr.write("----wm代码异常、视频闪屏的问题----,请联系作者帮你解决!!")))}),1e3*$r);var n=u.default.createServer((function(e,t){t.writeHead(200),t.end("hello rtsp2web, with ws [ws] model ~ \n")}));if(t&&"object"===k(t.wss))if(console.log("wss启动中...."),t.wss.hasOwnProperty("pfx"))if(t.wss.hasOwnProperty("passphrase"))try{n=d.default.createServer({pfx:m.default.readFileSync(t.wss.pfx),passphrase:m.default.readFileSync(t.wss.passphrase)},(function(e,t){console.log("client connect cross wss!"),t.writeHead(200),t.end("hello rtsp2web, with wss [pfx&passphrase] model ~ \n")}))}catch(e){console.error("--[读取pfx安全证书文件出错,wss启动失败,退回到ws;请检查(pfx&passphrase),错误信息如下,有问题请联系我]--"),console.log(e)}else console.error("【wss启动失败:请传入正确的密码:passphrase】"),global.process.stdout.write("---ws正常开启中--- W11 \n");else if(t.wss.hasOwnProperty("cert"))if(t.wss.hasOwnProperty("key"))try{n=d.default.createServer({key:m.default.readFileSync(t.wss.key),cert:m.default.readFileSync(t.wss.cert)},(function(e,t){console.log("client connect cross wss!"),t.writeHead(200),t.end("hello rtsp2web, with wss [key&cert] model ~ \n")}))}catch(e){console.error("--[读取SSL证书文件Error,wss启动失败,退回到ws;请检查(key&cert),错误信息如下,有问题请联系我]--"),console.log(e)}else console.error("【wss启动失败;请传入正确的安全证书私钥:key.pem】"),global.process.stdout.write("---ws正常开启中--- W13 \n");else console.error("【wss启动失败;请传入正确的安全证书公钥:cert.pem】"),global.process.stdout.write("---ws正常开启中--- W12 \n");n.listen(t&&t.port||9999),Object.getPrototypeOf(n)instanceof p.default.Server&&console.log("wss model success!!!"),this.wss=new Lr({server:n}),this.wss.on("connection",(function(e,t){var n=Tr.parse(t.url,!0);if(n.query.url){var s=D.exports.decode(n.query.url.toString());n.query.url=s,r.registeClient(e,{url:s,options:n.query})}console.log("一个新的视频播放窗口(client,ws句柄)连接成功,请等待画面...")}))}return T(e,[{key:"registeClient",value:function(e,t){var r=this.getChannel(t.url);r||(r=this.createChannel(t.options,e)),r.addClient(e)}},{key:"getChannel",value:function(e){var t,r=j(this.channels);try{for(r.s();!(t=r.n()).done;){var n=t.value;if(n.url===e)return n}}catch(e){r.e(e)}finally{r.f()}return null}},{key:"createChannel",value:function(e,t){var r=new Xr(e,t);return this.channels.push(r),r}},{key:"checkFree",value:function(){var e,t=j(this.channels);try{for(t.s();!(e=t.n()).done;){var r=e.value;r.clients.length>0?r.freeTime=0:r.freeTime+=$r,r.freeTime>=qr&&this.destroyChannel(r)}}catch(e){t.e(e)}finally{t.f()}}},{key:"destroyChannel",value:function(e){var t=this.channels.indexOf(e);t>-1&&(this.channels.splice(t,1),e.destroy())}},{key:"destroyAllChannel",value:function(){var e,t=j(this.channels);try{for(t.s();!(e=t.n()).done;){var r=e.value;this.destroyChannel(r)}}catch(e){t.e(e)}finally{t.f()}}}]),e}();L(Qr,"version",Er),module.exports=Qr;
|
package/dist/rtsp2web.min.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
/*!
|
|
2
|
-
* rtsp2web v3.1.
|
|
2
|
+
* rtsp2web v3.1.7
|
|
3
3
|
* (c) 2020-2023 NeverYu
|
|
4
4
|
* My home page:https://neveryu.github.io/neveryu/
|
|
5
5
|
* 微信(wechat):miracle421354532
|
|
6
6
|
* Released under the ISC License.
|
|
7
7
|
*/
|
|
8
|
-
"use strict";var e=require("http"),t=require("https"),r=require("tls"),n=require("fs"),s=require("events"),i=require("net"),o=require("crypto"),a=require("stream"),c=require("url"),l=require("zlib"),h=require("buffer");function f(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var u=f(e),d=f(t),p=f(r),_=f(n),m=f(s),y=f(i),v=f(o),g=f(a),b=f(c),w=f(l),S=f(h);function x(){x=function(){return e};var e={},t=Object.prototype,r=t.hasOwnProperty,n=Object.defineProperty||function(e,t,r){e[t]=r.value},s="function"==typeof Symbol?Symbol:{},i=s.iterator||"@@iterator",o=s.asyncIterator||"@@asyncIterator",a=s.toStringTag||"@@toStringTag";function c(e,t,r){return Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{c({},"")}catch(e){c=function(e,t,r){return e[t]=r}}function l(e,t,r,s){var i=t&&t.prototype instanceof u?t:u,o=Object.create(i.prototype),a=new O(s||[]);return n(o,"_invoke",{value:w(e,r,a)}),o}function h(e,t,r){try{return{type:"normal",arg:e.call(t,r)}}catch(e){return{type:"throw",arg:e}}}e.wrap=l;var f={};function u(){}function d(){}function p(){}var _={};c(_,i,(function(){return this}));var m=Object.getPrototypeOf,y=m&&m(m(C([])));y&&y!==t&&r.call(y,i)&&(_=y);var v=p.prototype=u.prototype=Object.create(_);function g(e){["next","throw","return"].forEach((function(t){c(e,t,(function(e){return this._invoke(t,e)}))}))}function b(e,t){function s(n,i,o,a){var c=h(e[n],e,i);if("throw"!==c.type){var l=c.arg,f=l.value;return f&&"object"==typeof f&&r.call(f,"__await")?t.resolve(f.__await).then((function(e){s("next",e,o,a)}),(function(e){s("throw",e,o,a)})):t.resolve(f).then((function(e){l.value=e,o(l)}),(function(e){return s("throw",e,o,a)}))}a(c.arg)}var i;n(this,"_invoke",{value:function(e,r){function n(){return new t((function(t,n){s(e,r,t,n)}))}return i=i?i.then(n,n):n()}})}function w(e,t,r){var n="suspendedStart";return function(s,i){if("executing"===n)throw new Error("Generator is already running");if("completed"===n){if("throw"===s)throw i;return T()}for(r.method=s,r.arg=i;;){var o=r.delegate;if(o){var a=S(o,r);if(a){if(a===f)continue;return a}}if("next"===r.method)r.sent=r._sent=r.arg;else if("throw"===r.method){if("suspendedStart"===n)throw n="completed",r.arg;r.dispatchException(r.arg)}else"return"===r.method&&r.abrupt("return",r.arg);n="executing";var c=h(e,t,r);if("normal"===c.type){if(n=r.done?"completed":"suspendedYield",c.arg===f)continue;return{value:c.arg,done:r.done}}"throw"===c.type&&(n="completed",r.method="throw",r.arg=c.arg)}}}function S(e,t){var r=t.method,n=e.iterator[r];if(void 0===n)return t.delegate=null,"throw"===r&&e.iterator.return&&(t.method="return",t.arg=void 0,S(e,t),"throw"===t.method)||"return"!==r&&(t.method="throw",t.arg=new TypeError("The iterator does not provide a '"+r+"' method")),f;var s=h(n,e.iterator,t.arg);if("throw"===s.type)return t.method="throw",t.arg=s.arg,t.delegate=null,f;var i=s.arg;return i?i.done?(t[e.resultName]=i.value,t.next=e.nextLoc,"return"!==t.method&&(t.method="next",t.arg=void 0),t.delegate=null,f):i:(t.method="throw",t.arg=new TypeError("iterator result is not an object"),t.delegate=null,f)}function k(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function E(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function O(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(k,this),this.reset(!0)}function C(e){if(e){var t=e[i];if(t)return t.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var n=-1,s=function t(){for(;++n<e.length;)if(r.call(e,n))return t.value=e[n],t.done=!1,t;return t.value=void 0,t.done=!0,t};return s.next=s}}return{next:T}}function T(){return{value:void 0,done:!0}}return d.prototype=p,n(v,"constructor",{value:p,configurable:!0}),n(p,"constructor",{value:d,configurable:!0}),d.displayName=c(p,a,"GeneratorFunction"),e.isGeneratorFunction=function(e){var t="function"==typeof e&&e.constructor;return!!t&&(t===d||"GeneratorFunction"===(t.displayName||t.name))},e.mark=function(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,p):(e.__proto__=p,c(e,a,"GeneratorFunction")),e.prototype=Object.create(v),e},e.awrap=function(e){return{__await:e}},g(b.prototype),c(b.prototype,o,(function(){return this})),e.AsyncIterator=b,e.async=function(t,r,n,s,i){void 0===i&&(i=Promise);var o=new b(l(t,r,n,s),i);return e.isGeneratorFunction(r)?o:o.next().then((function(e){return e.done?e.value:o.next()}))},g(v),c(v,a,"Generator"),c(v,i,(function(){return this})),c(v,"toString",(function(){return"[object Generator]"})),e.keys=function(e){var t=Object(e),r=[];for(var n in t)r.push(n);return r.reverse(),function e(){for(;r.length;){var n=r.pop();if(n in t)return e.value=n,e.done=!1,e}return e.done=!0,e}},e.values=C,O.prototype={constructor:O,reset:function(e){if(this.prev=0,this.next=0,this.sent=this._sent=void 0,this.done=!1,this.delegate=null,this.method="next",this.arg=void 0,this.tryEntries.forEach(E),!e)for(var t in this)"t"===t.charAt(0)&&r.call(this,t)&&!isNaN(+t.slice(1))&&(this[t]=void 0)},stop:function(){this.done=!0;var e=this.tryEntries[0].completion;if("throw"===e.type)throw e.arg;return this.rval},dispatchException:function(e){if(this.done)throw e;var t=this;function n(r,n){return o.type="throw",o.arg=e,t.next=r,n&&(t.method="next",t.arg=void 0),!!n}for(var s=this.tryEntries.length-1;s>=0;--s){var i=this.tryEntries[s],o=i.completion;if("root"===i.tryLoc)return n("end");if(i.tryLoc<=this.prev){var a=r.call(i,"catchLoc"),c=r.call(i,"finallyLoc");if(a&&c){if(this.prev<i.catchLoc)return n(i.catchLoc,!0);if(this.prev<i.finallyLoc)return n(i.finallyLoc)}else if(a){if(this.prev<i.catchLoc)return n(i.catchLoc,!0)}else{if(!c)throw new Error("try statement without catch or finally");if(this.prev<i.finallyLoc)return n(i.finallyLoc)}}}},abrupt:function(e,t){for(var n=this.tryEntries.length-1;n>=0;--n){var s=this.tryEntries[n];if(s.tryLoc<=this.prev&&r.call(s,"finallyLoc")&&this.prev<s.finallyLoc){var i=s;break}}i&&("break"===e||"continue"===e)&&i.tryLoc<=t&&t<=i.finallyLoc&&(i=null);var o=i?i.completion:{};return o.type=e,o.arg=t,i?(this.method="next",this.next=i.finallyLoc,f):this.complete(o)},complete:function(e,t){if("throw"===e.type)throw e.arg;return"break"===e.type||"continue"===e.type?this.next=e.arg:"return"===e.type?(this.rval=this.arg=e.arg,this.method="return",this.next="end"):"normal"===e.type&&t&&(this.next=t),f},finish:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.finallyLoc===e)return this.complete(r.completion,r.afterLoc),E(r),f}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.tryLoc===e){var n=r.completion;if("throw"===n.type){var s=n.arg;E(r)}return s}}throw new Error("illegal catch attempt")},delegateYield:function(e,t,r){return this.delegate={iterator:C(e),resultName:t,nextLoc:r},"next"===this.method&&(this.arg=void 0),f}},e}function k(e){return k="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},k(e)}function E(e,t,r,n,s,i,o){try{var a=e[i](o),c=a.value}catch(e){return void r(e)}a.done?t(c):Promise.resolve(c).then(n,s)}function O(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function C(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,W(n.key),n)}}function T(e,t,r){return t&&C(e.prototype,t),r&&C(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function L(e,t,r){return(t=W(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function N(e){return N=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},N(e)}function P(e,t){return P=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},P(e,t)}function M(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function R(e){var t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}();return function(){var r,n=N(e);if(t){var s=N(this).constructor;r=Reflect.construct(n,arguments,s)}else r=n.apply(this,arguments);return function(e,t){if(t&&("object"==typeof t||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return M(e)}(this,r)}}function I(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,s,i,o,a=[],c=!0,l=!1;try{if(i=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;c=!1}else for(;!(c=(n=i.call(r)).done)&&(a.push(n.value),a.length!==t);c=!0);}catch(e){l=!0,s=e}finally{try{if(!c&&null!=r.return&&(o=r.return(),Object(o)!==o))return}finally{if(l)throw s}}return a}}(e,t)||A(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function U(e){return function(e){if(Array.isArray(e))return B(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||A(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function A(e,t){if(e){if("string"==typeof e)return B(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?B(e,t):void 0}}function B(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function j(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=A(e))||t&&e&&"number"==typeof e.length){r&&(e=r);var n=0,s=function(){};return{s:s,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:s}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,o=!0,a=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return o=e.done,e},e:function(e){a=!0,i=e},f:function(){try{o||null==r.return||r.return()}finally{if(a)throw i}}}}function W(e){var t=function(e,t){if("object"!=typeof e||null===e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var n=r.call(e,t||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:String(t)}var F="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},D={exports:{}};
|
|
8
|
+
"use strict";var e=require("http"),t=require("https"),r=require("tls"),n=require("fs"),s=require("events"),o=require("net"),i=require("crypto"),a=require("stream"),c=require("url"),l=require("zlib"),h=require("buffer");function f(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var u=f(e),d=f(t),p=f(r),m=f(n),_=f(s),y=f(o),v=f(i),g=f(a),b=f(c),w=f(l),S=f(h);function x(){x=function(){return e};var e={},t=Object.prototype,r=t.hasOwnProperty,n=Object.defineProperty||function(e,t,r){e[t]=r.value},s="function"==typeof Symbol?Symbol:{},o=s.iterator||"@@iterator",i=s.asyncIterator||"@@asyncIterator",a=s.toStringTag||"@@toStringTag";function c(e,t,r){return Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{c({},"")}catch(e){c=function(e,t,r){return e[t]=r}}function l(e,t,r,s){var o=t&&t.prototype instanceof u?t:u,i=Object.create(o.prototype),a=new O(s||[]);return n(i,"_invoke",{value:w(e,r,a)}),i}function h(e,t,r){try{return{type:"normal",arg:e.call(t,r)}}catch(e){return{type:"throw",arg:e}}}e.wrap=l;var f={};function u(){}function d(){}function p(){}var m={};c(m,o,(function(){return this}));var _=Object.getPrototypeOf,y=_&&_(_(C([])));y&&y!==t&&r.call(y,o)&&(m=y);var v=p.prototype=u.prototype=Object.create(m);function g(e){["next","throw","return"].forEach((function(t){c(e,t,(function(e){return this._invoke(t,e)}))}))}function b(e,t){function s(n,o,i,a){var c=h(e[n],e,o);if("throw"!==c.type){var l=c.arg,f=l.value;return f&&"object"==typeof f&&r.call(f,"__await")?t.resolve(f.__await).then((function(e){s("next",e,i,a)}),(function(e){s("throw",e,i,a)})):t.resolve(f).then((function(e){l.value=e,i(l)}),(function(e){return s("throw",e,i,a)}))}a(c.arg)}var o;n(this,"_invoke",{value:function(e,r){function n(){return new t((function(t,n){s(e,r,t,n)}))}return o=o?o.then(n,n):n()}})}function w(e,t,r){var n="suspendedStart";return function(s,o){if("executing"===n)throw new Error("Generator is already running");if("completed"===n){if("throw"===s)throw o;return T()}for(r.method=s,r.arg=o;;){var i=r.delegate;if(i){var a=S(i,r);if(a){if(a===f)continue;return a}}if("next"===r.method)r.sent=r._sent=r.arg;else if("throw"===r.method){if("suspendedStart"===n)throw n="completed",r.arg;r.dispatchException(r.arg)}else"return"===r.method&&r.abrupt("return",r.arg);n="executing";var c=h(e,t,r);if("normal"===c.type){if(n=r.done?"completed":"suspendedYield",c.arg===f)continue;return{value:c.arg,done:r.done}}"throw"===c.type&&(n="completed",r.method="throw",r.arg=c.arg)}}}function S(e,t){var r=t.method,n=e.iterator[r];if(void 0===n)return t.delegate=null,"throw"===r&&e.iterator.return&&(t.method="return",t.arg=void 0,S(e,t),"throw"===t.method)||"return"!==r&&(t.method="throw",t.arg=new TypeError("The iterator does not provide a '"+r+"' method")),f;var s=h(n,e.iterator,t.arg);if("throw"===s.type)return t.method="throw",t.arg=s.arg,t.delegate=null,f;var o=s.arg;return o?o.done?(t[e.resultName]=o.value,t.next=e.nextLoc,"return"!==t.method&&(t.method="next",t.arg=void 0),t.delegate=null,f):o:(t.method="throw",t.arg=new TypeError("iterator result is not an object"),t.delegate=null,f)}function k(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function E(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function O(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(k,this),this.reset(!0)}function C(e){if(e){var t=e[o];if(t)return t.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var n=-1,s=function t(){for(;++n<e.length;)if(r.call(e,n))return t.value=e[n],t.done=!1,t;return t.value=void 0,t.done=!0,t};return s.next=s}}return{next:T}}function T(){return{value:void 0,done:!0}}return d.prototype=p,n(v,"constructor",{value:p,configurable:!0}),n(p,"constructor",{value:d,configurable:!0}),d.displayName=c(p,a,"GeneratorFunction"),e.isGeneratorFunction=function(e){var t="function"==typeof e&&e.constructor;return!!t&&(t===d||"GeneratorFunction"===(t.displayName||t.name))},e.mark=function(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,p):(e.__proto__=p,c(e,a,"GeneratorFunction")),e.prototype=Object.create(v),e},e.awrap=function(e){return{__await:e}},g(b.prototype),c(b.prototype,i,(function(){return this})),e.AsyncIterator=b,e.async=function(t,r,n,s,o){void 0===o&&(o=Promise);var i=new b(l(t,r,n,s),o);return e.isGeneratorFunction(r)?i:i.next().then((function(e){return e.done?e.value:i.next()}))},g(v),c(v,a,"Generator"),c(v,o,(function(){return this})),c(v,"toString",(function(){return"[object Generator]"})),e.keys=function(e){var t=Object(e),r=[];for(var n in t)r.push(n);return r.reverse(),function e(){for(;r.length;){var n=r.pop();if(n in t)return e.value=n,e.done=!1,e}return e.done=!0,e}},e.values=C,O.prototype={constructor:O,reset:function(e){if(this.prev=0,this.next=0,this.sent=this._sent=void 0,this.done=!1,this.delegate=null,this.method="next",this.arg=void 0,this.tryEntries.forEach(E),!e)for(var t in this)"t"===t.charAt(0)&&r.call(this,t)&&!isNaN(+t.slice(1))&&(this[t]=void 0)},stop:function(){this.done=!0;var e=this.tryEntries[0].completion;if("throw"===e.type)throw e.arg;return this.rval},dispatchException:function(e){if(this.done)throw e;var t=this;function n(r,n){return i.type="throw",i.arg=e,t.next=r,n&&(t.method="next",t.arg=void 0),!!n}for(var s=this.tryEntries.length-1;s>=0;--s){var o=this.tryEntries[s],i=o.completion;if("root"===o.tryLoc)return n("end");if(o.tryLoc<=this.prev){var a=r.call(o,"catchLoc"),c=r.call(o,"finallyLoc");if(a&&c){if(this.prev<o.catchLoc)return n(o.catchLoc,!0);if(this.prev<o.finallyLoc)return n(o.finallyLoc)}else if(a){if(this.prev<o.catchLoc)return n(o.catchLoc,!0)}else{if(!c)throw new Error("try statement without catch or finally");if(this.prev<o.finallyLoc)return n(o.finallyLoc)}}}},abrupt:function(e,t){for(var n=this.tryEntries.length-1;n>=0;--n){var s=this.tryEntries[n];if(s.tryLoc<=this.prev&&r.call(s,"finallyLoc")&&this.prev<s.finallyLoc){var o=s;break}}o&&("break"===e||"continue"===e)&&o.tryLoc<=t&&t<=o.finallyLoc&&(o=null);var i=o?o.completion:{};return i.type=e,i.arg=t,o?(this.method="next",this.next=o.finallyLoc,f):this.complete(i)},complete:function(e,t){if("throw"===e.type)throw e.arg;return"break"===e.type||"continue"===e.type?this.next=e.arg:"return"===e.type?(this.rval=this.arg=e.arg,this.method="return",this.next="end"):"normal"===e.type&&t&&(this.next=t),f},finish:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.finallyLoc===e)return this.complete(r.completion,r.afterLoc),E(r),f}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.tryLoc===e){var n=r.completion;if("throw"===n.type){var s=n.arg;E(r)}return s}}throw new Error("illegal catch attempt")},delegateYield:function(e,t,r){return this.delegate={iterator:C(e),resultName:t,nextLoc:r},"next"===this.method&&(this.arg=void 0),f}},e}function k(e){return k="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},k(e)}function E(e,t,r,n,s,o,i){try{var a=e[o](i),c=a.value}catch(e){return void r(e)}a.done?t(c):Promise.resolve(c).then(n,s)}function O(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function C(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,W(n.key),n)}}function T(e,t,r){return t&&C(e.prototype,t),r&&C(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function L(e,t,r){return(t=W(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function N(e){return N=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},N(e)}function P(e,t){return P=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},P(e,t)}function M(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function R(e){var t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}();return function(){var r,n=N(e);if(t){var s=N(this).constructor;r=Reflect.construct(n,arguments,s)}else r=n.apply(this,arguments);return function(e,t){if(t&&("object"==typeof t||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return M(e)}(this,r)}}function I(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,s,o,i,a=[],c=!0,l=!1;try{if(o=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;c=!1}else for(;!(c=(n=o.call(r)).done)&&(a.push(n.value),a.length!==t);c=!0);}catch(e){l=!0,s=e}finally{try{if(!c&&null!=r.return&&(i=r.return(),Object(i)!==i))return}finally{if(l)throw s}}return a}}(e,t)||A(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function U(e){return function(e){if(Array.isArray(e))return B(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||A(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function A(e,t){if(e){if("string"==typeof e)return B(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?B(e,t):void 0}}function B(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function j(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=A(e))||t&&e&&"number"==typeof e.length){r&&(e=r);var n=0,s=function(){};return{s:s,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:s}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,i=!0,a=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return i=e.done,e},e:function(e){a=!0,o=e},f:function(){try{i||null==r.return||r.return()}finally{if(a)throw o}}}}function W(e){var t=function(e,t){if("object"!=typeof e||null===e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var n=r.call(e,t||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:String(t)}var F="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},D={exports:{}};
|
|
9
9
|
/*! https://mths.be/base64 v1.0.0 by @mathias | MIT license */
|
|
10
|
-
!function(e,t){!function(r){var n=t,s=e&&e.exports==n&&e,i="object"==typeof F&&F;i.global!==i&&i.window!==i||(r=i);var o=function(e){this.message=e};(o.prototype=new Error).name="InvalidCharacterError";var a=function(e){throw new o(e)},c="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",l=/[\t\n\f\r ]/g,h={encode:function(e){e=String(e),/[^\0-\xFF]/.test(e)&&a("The string to be encoded contains characters outside of the Latin1 range.");for(var t,r,n,s,i=e.length%3,o="",l=-1,h=e.length-i;++l<h;)t=e.charCodeAt(l)<<16,r=e.charCodeAt(++l)<<8,n=e.charCodeAt(++l),o+=c.charAt((s=t+r+n)>>18&63)+c.charAt(s>>12&63)+c.charAt(s>>6&63)+c.charAt(63&s);return 2==i?(t=e.charCodeAt(l)<<8,r=e.charCodeAt(++l),o+=c.charAt((s=t+r)>>10)+c.charAt(s>>4&63)+c.charAt(s<<2&63)+"="):1==i&&(s=e.charCodeAt(l),o+=c.charAt(s>>2)+c.charAt(s<<4&63)+"=="),o},decode:function(e){var t=(e=String(e).replace(l,"")).length;t%4==0&&(t=(e=e.replace(/==?$/,"")).length),(t%4==1||/[^+a-zA-Z0-9/]/.test(e))&&a("Invalid character: the string to be decoded is not correctly encoded.");for(var r,n,s=0,i="",o=-1;++o<t;)n=c.indexOf(e.charAt(o)),r=s%4?64*r+n:n,s++%4&&(i+=String.fromCharCode(255&r>>(-2*s&6)));return i},version:"1.0.0"};if(n&&!n.nodeType)if(s)s.exports=h;else for(var f in h)h.hasOwnProperty(f)&&(n[f]=h[f]);else r.base64=h}(F)}(D,D.exports);var G={exports:{}},q={BINARY_TYPES:["nodebuffer","arraybuffer","fragments"],EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}};const{EMPTY_BUFFER:$}=q,V=Buffer[Symbol.species];function z(e,t,r,n,s){for(let i=0;i<s;i++)r[n+i]=e[i]^t[3&i]}function H(e,t){for(let r=0;r<e.length;r++)e[r]^=t[3&r]}if(G.exports={concat:function(e,t){if(0===e.length)return $;if(1===e.length)return e[0];const r=Buffer.allocUnsafe(t);let n=0;for(let t=0;t<e.length;t++){const s=e[t];r.set(s,n),n+=s.length}return n<t?new V(r.buffer,r.byteOffset,n):r},mask:z,toArrayBuffer:function(e){return e.length===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.length)},toBuffer:function e(t){if(e.readOnly=!0,Buffer.isBuffer(t))return t;let r;return t instanceof ArrayBuffer?r=new V(t):ArrayBuffer.isView(t)?r=new V(t.buffer,t.byteOffset,t.byteLength):(r=Buffer.from(t),e.readOnly=!1),r},unmask:H},!process.env.WS_NO_BUFFER_UTIL)try{const e=require("bufferutil");G.exports.mask=function(t,r,n,s,i){i<48?z(t,r,n,s,i):e.mask(t,r,n,s,i)},G.exports.unmask=function(t,r){t.length<32?H(t,r):e.unmask(t,r)}}catch(e){}const Y=Symbol("kDone"),X=Symbol("kRun");var Q=class{constructor(e){this[Y]=()=>{this.pending--,this[X]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[X]()}[X](){if(this.pending!==this.concurrency&&this.jobs.length){const e=this.jobs.shift();this.pending++,e(this[Y])}}};const Z=w.default,K=G.exports,J=Q,{kStatusCode:ee}=q,te=Buffer[Symbol.species],re=Buffer.from([0,0,255,255]),ne=Symbol("permessage-deflate"),se=Symbol("total-length"),ie=Symbol("callback"),oe=Symbol("buffers"),ae=Symbol("error");let ce;var le=class{constructor(e,t,r){if(this._maxPayload=0|r,this._options=e||{},this._threshold=void 0!==this._options.threshold?this._options.threshold:1024,this._isServer=!!t,this._deflate=null,this._inflate=null,this.params=null,!ce){const e=void 0!==this._options.concurrencyLimit?this._options.concurrencyLimit:10;ce=new J(e)}}static get extensionName(){return"permessage-deflate"}offer(){const e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:null==this._options.clientMaxWindowBits&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){const e=this._deflate[ie];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){const t=this._options,r=e.find((e=>!(!1===t.serverNoContextTakeover&&e.server_no_context_takeover||e.server_max_window_bits&&(!1===t.serverMaxWindowBits||"number"==typeof t.serverMaxWindowBits&&t.serverMaxWindowBits>e.server_max_window_bits)||"number"==typeof t.clientMaxWindowBits&&!e.client_max_window_bits)));if(!r)throw new Error("None of the extension offers can be accepted");return t.serverNoContextTakeover&&(r.server_no_context_takeover=!0),t.clientNoContextTakeover&&(r.client_no_context_takeover=!0),"number"==typeof t.serverMaxWindowBits&&(r.server_max_window_bits=t.serverMaxWindowBits),"number"==typeof t.clientMaxWindowBits?r.client_max_window_bits=t.clientMaxWindowBits:!0!==r.client_max_window_bits&&!1!==t.clientMaxWindowBits||delete r.client_max_window_bits,r}acceptAsClient(e){const t=e[0];if(!1===this._options.clientNoContextTakeover&&t.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(t.client_max_window_bits){if(!1===this._options.clientMaxWindowBits||"number"==typeof this._options.clientMaxWindowBits&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"')}else"number"==typeof this._options.clientMaxWindowBits&&(t.client_max_window_bits=this._options.clientMaxWindowBits);return t}normalizeParams(e){return e.forEach((e=>{Object.keys(e).forEach((t=>{let r=e[t];if(r.length>1)throw new Error(`Parameter "${t}" must have only a single value`);if(r=r[0],"client_max_window_bits"===t){if(!0!==r){const e=+r;if(!Number.isInteger(e)||e<8||e>15)throw new TypeError(`Invalid value for parameter "${t}": ${r}`);r=e}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${t}": ${r}`)}else if("server_max_window_bits"===t){const e=+r;if(!Number.isInteger(e)||e<8||e>15)throw new TypeError(`Invalid value for parameter "${t}": ${r}`);r=e}else{if("client_no_context_takeover"!==t&&"server_no_context_takeover"!==t)throw new Error(`Unknown parameter "${t}"`);if(!0!==r)throw new TypeError(`Invalid value for parameter "${t}": ${r}`)}e[t]=r}))})),e}decompress(e,t,r){ce.add((n=>{this._decompress(e,t,((e,t)=>{n(),r(e,t)}))}))}compress(e,t,r){ce.add((n=>{this._compress(e,t,((e,t)=>{n(),r(e,t)}))}))}_decompress(e,t,r){const n=this._isServer?"client":"server";if(!this._inflate){const e=`${n}_max_window_bits`,t="number"!=typeof this.params[e]?Z.Z_DEFAULT_WINDOWBITS:this.params[e];this._inflate=Z.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[ne]=this,this._inflate[se]=0,this._inflate[oe]=[],this._inflate.on("error",ue),this._inflate.on("data",fe)}this._inflate[ie]=r,this._inflate.write(e),t&&this._inflate.write(re),this._inflate.flush((()=>{const e=this._inflate[ae];if(e)return this._inflate.close(),this._inflate=null,void r(e);const s=K.concat(this._inflate[oe],this._inflate[se]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[se]=0,this._inflate[oe]=[],t&&this.params[`${n}_no_context_takeover`]&&this._inflate.reset()),r(null,s)}))}_compress(e,t,r){const n=this._isServer?"server":"client";if(!this._deflate){const e=`${n}_max_window_bits`,t="number"!=typeof this.params[e]?Z.Z_DEFAULT_WINDOWBITS:this.params[e];this._deflate=Z.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[se]=0,this._deflate[oe]=[],this._deflate.on("data",he)}this._deflate[ie]=r,this._deflate.write(e),this._deflate.flush(Z.Z_SYNC_FLUSH,(()=>{if(!this._deflate)return;let e=K.concat(this._deflate[oe],this._deflate[se]);t&&(e=new te(e.buffer,e.byteOffset,e.length-4)),this._deflate[ie]=null,this._deflate[se]=0,this._deflate[oe]=[],t&&this.params[`${n}_no_context_takeover`]&&this._deflate.reset(),r(null,e)}))}};function he(e){this[oe].push(e),this[se]+=e.length}function fe(e){this[se]+=e.length,this[ne]._maxPayload<1||this[se]<=this[ne]._maxPayload?this[oe].push(e):(this[ae]=new RangeError("Max payload size exceeded"),this[ae].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[ae][ee]=1009,this.removeListener("data",fe),this.reset())}function ue(e){this[ne]._inflate=null,e[ee]=1007,this[ie](e)}var de={exports:{}};const{isUtf8:pe}=S.default;function _e(e){const t=e.length;let r=0;for(;r<t;)if(0==(128&e[r]))r++;else if(192==(224&e[r])){if(r+1===t||128!=(192&e[r+1])||192==(254&e[r]))return!1;r+=2}else if(224==(240&e[r])){if(r+2>=t||128!=(192&e[r+1])||128!=(192&e[r+2])||224===e[r]&&128==(224&e[r+1])||237===e[r]&&160==(224&e[r+1]))return!1;r+=3}else{if(240!=(248&e[r]))return!1;if(r+3>=t||128!=(192&e[r+1])||128!=(192&e[r+2])||128!=(192&e[r+3])||240===e[r]&&128==(240&e[r+1])||244===e[r]&&e[r+1]>143||e[r]>244)return!1;r+=4}return!0}if(de.exports={isValidStatusCode:function(e){return e>=1e3&&e<=1014&&1004!==e&&1005!==e&&1006!==e||e>=3e3&&e<=4999},isValidUTF8:_e,tokenChars:[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0]},pe)de.exports.isValidUTF8=function(e){return e.length<24?_e(e):pe(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{const e=require("utf-8-validate");de.exports.isValidUTF8=function(t){return t.length<32?_e(t):e(t)}}catch(e){}const{Writable:me}=g.default,ye=le,{BINARY_TYPES:ve,EMPTY_BUFFER:ge,kStatusCode:be,kWebSocket:we}=q,{concat:Se,toArrayBuffer:xe,unmask:ke}=G.exports,{isValidStatusCode:Ee,isValidUTF8:Oe}=de.exports,Ce=Buffer[Symbol.species];var Te=class extends me{constructor(e={}){super(),this._binaryType=e.binaryType||ve[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=0|e.maxPayload,this._skipUTF8Validation=!!e.skipUTF8Validation,this[we]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._state=0,this._loop=!1}_write(e,t,r){if(8===this._opcode&&0==this._state)return r();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(r)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){const t=this._buffers[0];return this._buffers[0]=new Ce(t.buffer,t.byteOffset+e,t.length-e),new Ce(t.buffer,t.byteOffset,e)}const t=Buffer.allocUnsafe(e);do{const r=this._buffers[0],n=t.length-e;e>=r.length?t.set(this._buffers.shift(),n):(t.set(new Uint8Array(r.buffer,r.byteOffset,e),n),this._buffers[0]=new Ce(r.buffer,r.byteOffset+e,r.length-e)),e-=r.length}while(e>0);return t}startLoop(e){let t;this._loop=!0;do{switch(this._state){case 0:t=this.getInfo();break;case 1:t=this.getPayloadLength16();break;case 2:t=this.getPayloadLength64();break;case 3:this.getMask();break;case 4:t=this.getData(e);break;default:return void(this._loop=!1)}}while(this._loop);e(t)}getInfo(){if(this._bufferedBytes<2)return void(this._loop=!1);const e=this.consume(2);if(0!=(48&e[0]))return this._loop=!1,Le(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");const t=64==(64&e[0]);if(t&&!this._extensions[ye.extensionName])return this._loop=!1,Le(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");if(this._fin=128==(128&e[0]),this._opcode=15&e[0],this._payloadLength=127&e[1],0===this._opcode){if(t)return this._loop=!1,Le(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");if(!this._fragmented)return this._loop=!1,Le(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");this._opcode=this._fragmented}else if(1===this._opcode||2===this._opcode){if(this._fragmented)return this._loop=!1,Le(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");this._compressed=t}else{if(!(this._opcode>7&&this._opcode<11))return this._loop=!1,Le(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");if(!this._fin)return this._loop=!1,Le(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");if(t)return this._loop=!1,Le(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");if(this._payloadLength>125||8===this._opcode&&1===this._payloadLength)return this._loop=!1,Le(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH")}if(this._fin||this._fragmented||(this._fragmented=this._opcode),this._masked=128==(128&e[1]),this._isServer){if(!this._masked)return this._loop=!1,Le(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK")}else if(this._masked)return this._loop=!1,Le(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");if(126===this._payloadLength)this._state=1;else{if(127!==this._payloadLength)return this.haveLength();this._state=2}}getPayloadLength16(){if(!(this._bufferedBytes<2))return this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength();this._loop=!1}getPayloadLength64(){if(this._bufferedBytes<8)return void(this._loop=!1);const e=this.consume(8),t=e.readUInt32BE(0);return t>Math.pow(2,21)-1?(this._loop=!1,Le(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH")):(this._payloadLength=t*Math.pow(2,32)+e.readUInt32BE(4),this.haveLength())}haveLength(){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0))return this._loop=!1,Le(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");this._masked?this._state=3:this._state=4}getMask(){this._bufferedBytes<4?this._loop=!1:(this._mask=this.consume(4),this._state=4)}getData(e){let t=ge;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength)return void(this._loop=!1);t=this.consume(this._payloadLength),this._masked&&0!=(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])&&ke(t,this._mask)}return this._opcode>7?this.controlMessage(t):this._compressed?(this._state=5,void this.decompress(t,e)):(t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage())}decompress(e,t){this._extensions[ye.extensionName].decompress(e,this._fin,((e,r)=>{if(e)return t(e);if(r.length){if(this._messageLength+=r.length,this._messageLength>this._maxPayload&&this._maxPayload>0)return t(Le(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"));this._fragments.push(r)}const n=this.dataMessage();if(n)return t(n);this.startLoop(t)}))}dataMessage(){if(this._fin){const e=this._messageLength,t=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],2===this._opcode){let r;r="nodebuffer"===this._binaryType?Se(t,e):"arraybuffer"===this._binaryType?xe(Se(t,e)):t,this.emit("message",r,!0)}else{const r=Se(t,e);if(!this._skipUTF8Validation&&!Oe(r))return this._loop=!1,Le(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");this.emit("message",r,!1)}}this._state=0}controlMessage(e){if(8===this._opcode)if(this._loop=!1,0===e.length)this.emit("conclude",1005,ge),this.end();else{const t=e.readUInt16BE(0);if(!Ee(t))return Le(RangeError,`invalid status code ${t}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");const r=new Ce(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Oe(r))return Le(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");this.emit("conclude",t,r),this.end()}else 9===this._opcode?this.emit("ping",e):this.emit("pong",e);this._state=0}};function Le(e,t,r,n,s){const i=new e(r?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(i,Le),i.code=s,i[be]=n,i}const{randomFillSync:Ne}=v.default,Pe=le,{EMPTY_BUFFER:Me}=q,{isValidStatusCode:Re}=de.exports,{mask:Ie,toBuffer:Ue}=G.exports,Ae=Symbol("kByteLength"),Be=Buffer.alloc(4);class je{constructor(e,t,r){this._extensions=t||{},r&&(this._generateMask=r,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._deflating=!1,this._queue=[]}static frame(e,t){let r,n,s=!1,i=2,o=!1;t.mask&&(r=t.maskBuffer||Be,t.generateMask?t.generateMask(r):Ne(r,0,4),o=0==(r[0]|r[1]|r[2]|r[3]),i=6),"string"==typeof e?n=t.mask&&!o||void 0===t[Ae]?(e=Buffer.from(e)).length:t[Ae]:(n=e.length,s=t.mask&&t.readOnly&&!o);let a=n;n>=65536?(i+=8,a=127):n>125&&(i+=2,a=126);const c=Buffer.allocUnsafe(s?n+i:i);return c[0]=t.fin?128|t.opcode:t.opcode,t.rsv1&&(c[0]|=64),c[1]=a,126===a?c.writeUInt16BE(n,2):127===a&&(c[2]=c[3]=0,c.writeUIntBE(n,4,6)),t.mask?(c[1]|=128,c[i-4]=r[0],c[i-3]=r[1],c[i-2]=r[2],c[i-1]=r[3],o?[c,e]:s?(Ie(e,r,c,i,n),[c]):(Ie(e,r,e,0,n),[c,e])):[c,e]}close(e,t,r,n){let s;if(void 0===e)s=Me;else{if("number"!=typeof e||!Re(e))throw new TypeError("First argument must be a valid error code number");if(void 0!==t&&t.length){const r=Buffer.byteLength(t);if(r>123)throw new RangeError("The message must not be greater than 123 bytes");s=Buffer.allocUnsafe(2+r),s.writeUInt16BE(e,0),"string"==typeof t?s.write(t,2):s.set(t,2)}else s=Buffer.allocUnsafe(2),s.writeUInt16BE(e,0)}const i={[Ae]:s.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._deflating?this.enqueue([this.dispatch,s,!1,i,n]):this.sendFrame(je.frame(s,i),n)}ping(e,t,r){let n,s;if("string"==typeof e?(n=Buffer.byteLength(e),s=!1):(n=(e=Ue(e)).length,s=Ue.readOnly),n>125)throw new RangeError("The data size must not be greater than 125 bytes");const i={[Ae]:n,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:s,rsv1:!1};this._deflating?this.enqueue([this.dispatch,e,!1,i,r]):this.sendFrame(je.frame(e,i),r)}pong(e,t,r){let n,s;if("string"==typeof e?(n=Buffer.byteLength(e),s=!1):(n=(e=Ue(e)).length,s=Ue.readOnly),n>125)throw new RangeError("The data size must not be greater than 125 bytes");const i={[Ae]:n,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:s,rsv1:!1};this._deflating?this.enqueue([this.dispatch,e,!1,i,r]):this.sendFrame(je.frame(e,i),r)}send(e,t,r){const n=this._extensions[Pe.extensionName];let s,i,o=t.binary?2:1,a=t.compress;if("string"==typeof e?(s=Buffer.byteLength(e),i=!1):(s=(e=Ue(e)).length,i=Ue.readOnly),this._firstFragment?(this._firstFragment=!1,a&&n&&n.params[n._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(a=s>=n._threshold),this._compress=a):(a=!1,o=0),t.fin&&(this._firstFragment=!0),n){const n={[Ae]:s,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:o,readOnly:i,rsv1:a};this._deflating?this.enqueue([this.dispatch,e,this._compress,n,r]):this.dispatch(e,this._compress,n,r)}else this.sendFrame(je.frame(e,{[Ae]:s,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:o,readOnly:i,rsv1:!1}),r)}dispatch(e,t,r,n){if(!t)return void this.sendFrame(je.frame(e,r),n);const s=this._extensions[Pe.extensionName];this._bufferedBytes+=r[Ae],this._deflating=!0,s.compress(e,r.fin,((e,t)=>{if(this._socket.destroyed){const e=new Error("The socket was closed while data was being compressed");"function"==typeof n&&n(e);for(let t=0;t<this._queue.length;t++){const r=this._queue[t],n=r[r.length-1];"function"==typeof n&&n(e)}}else this._bufferedBytes-=r[Ae],this._deflating=!1,r.readOnly=!1,this.sendFrame(je.frame(t,r),n),this.dequeue()}))}dequeue(){for(;!this._deflating&&this._queue.length;){const e=this._queue.shift();this._bufferedBytes-=e[3][Ae],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Ae],this._queue.push(e)}sendFrame(e,t){2===e.length?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}}var We=je;const{kForOnEventAttribute:Fe,kListener:De}=q,Ge=Symbol("kCode"),qe=Symbol("kData"),$e=Symbol("kError"),Ve=Symbol("kMessage"),ze=Symbol("kReason"),He=Symbol("kTarget"),Ye=Symbol("kType"),Xe=Symbol("kWasClean");class Qe{constructor(e){this[He]=null,this[Ye]=e}get target(){return this[He]}get type(){return this[Ye]}}Object.defineProperty(Qe.prototype,"target",{enumerable:!0}),Object.defineProperty(Qe.prototype,"type",{enumerable:!0});class Ze extends Qe{constructor(e,t={}){super(e),this[Ge]=void 0===t.code?0:t.code,this[ze]=void 0===t.reason?"":t.reason,this[Xe]=void 0!==t.wasClean&&t.wasClean}get code(){return this[Ge]}get reason(){return this[ze]}get wasClean(){return this[Xe]}}Object.defineProperty(Ze.prototype,"code",{enumerable:!0}),Object.defineProperty(Ze.prototype,"reason",{enumerable:!0}),Object.defineProperty(Ze.prototype,"wasClean",{enumerable:!0});class Ke extends Qe{constructor(e,t={}){super(e),this[$e]=void 0===t.error?null:t.error,this[Ve]=void 0===t.message?"":t.message}get error(){return this[$e]}get message(){return this[Ve]}}Object.defineProperty(Ke.prototype,"error",{enumerable:!0}),Object.defineProperty(Ke.prototype,"message",{enumerable:!0});class Je extends Qe{constructor(e,t={}){super(e),this[qe]=void 0===t.data?null:t.data}get data(){return this[qe]}}Object.defineProperty(Je.prototype,"data",{enumerable:!0});const et={addEventListener(e,t,r={}){for(const n of this.listeners(e))if(!r[Fe]&&n[De]===t&&!n[Fe])return;let n;if("message"===e)n=function(e,r){const n=new Je("message",{data:r?e:e.toString()});n[He]=this,rt(t,this,n)};else if("close"===e)n=function(e,r){const n=new Ze("close",{code:e,reason:r.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});n[He]=this,rt(t,this,n)};else if("error"===e)n=function(e){const r=new Ke("error",{error:e,message:e.message});r[He]=this,rt(t,this,r)};else{if("open"!==e)return;n=function(){const e=new Qe("open");e[He]=this,rt(t,this,e)}}n[Fe]=!!r[Fe],n[De]=t,r.once?this.once(e,n):this.on(e,n)},removeEventListener(e,t){for(const r of this.listeners(e))if(r[De]===t&&!r[Fe]){this.removeListener(e,r);break}}};var tt={CloseEvent:Ze,ErrorEvent:Ke,Event:Qe,EventTarget:et,MessageEvent:Je};function rt(e,t,r){"object"==typeof e&&e.handleEvent?e.handleEvent.call(e,r):e.call(t,r)}const{tokenChars:nt}=de.exports;function st(e,t,r){void 0===e[t]?e[t]=[r]:e[t].push(r)}var it={format:function(e){return Object.keys(e).map((t=>{let r=e[t];return Array.isArray(r)||(r=[r]),r.map((e=>[t].concat(Object.keys(e).map((t=>{let r=e[t];return Array.isArray(r)||(r=[r]),r.map((e=>!0===e?t:`${t}=${e}`)).join("; ")}))).join("; "))).join(", ")})).join(", ")},parse:function(e){const t=Object.create(null);let r,n,s=Object.create(null),i=!1,o=!1,a=!1,c=-1,l=-1,h=-1,f=0;for(;f<e.length;f++)if(l=e.charCodeAt(f),void 0===r)if(-1===h&&1===nt[l])-1===c&&(c=f);else if(0===f||32!==l&&9!==l){if(59!==l&&44!==l)throw new SyntaxError(`Unexpected character at index ${f}`);{if(-1===c)throw new SyntaxError(`Unexpected character at index ${f}`);-1===h&&(h=f);const n=e.slice(c,h);44===l?(st(t,n,s),s=Object.create(null)):r=n,c=h=-1}}else-1===h&&-1!==c&&(h=f);else if(void 0===n)if(-1===h&&1===nt[l])-1===c&&(c=f);else if(32===l||9===l)-1===h&&-1!==c&&(h=f);else if(59===l||44===l){if(-1===c)throw new SyntaxError(`Unexpected character at index ${f}`);-1===h&&(h=f),st(s,e.slice(c,h),!0),44===l&&(st(t,r,s),s=Object.create(null),r=void 0),c=h=-1}else{if(61!==l||-1===c||-1!==h)throw new SyntaxError(`Unexpected character at index ${f}`);n=e.slice(c,f),c=h=-1}else if(o){if(1!==nt[l])throw new SyntaxError(`Unexpected character at index ${f}`);-1===c?c=f:i||(i=!0),o=!1}else if(a)if(1===nt[l])-1===c&&(c=f);else if(34===l&&-1!==c)a=!1,h=f;else{if(92!==l)throw new SyntaxError(`Unexpected character at index ${f}`);o=!0}else if(34===l&&61===e.charCodeAt(f-1))a=!0;else if(-1===h&&1===nt[l])-1===c&&(c=f);else if(-1===c||32!==l&&9!==l){if(59!==l&&44!==l)throw new SyntaxError(`Unexpected character at index ${f}`);{if(-1===c)throw new SyntaxError(`Unexpected character at index ${f}`);-1===h&&(h=f);let o=e.slice(c,h);i&&(o=o.replace(/\\/g,""),i=!1),st(s,n,o),44===l&&(st(t,r,s),s=Object.create(null),r=void 0),n=void 0,c=h=-1}}else-1===h&&(h=f);if(-1===c||a||32===l||9===l)throw new SyntaxError("Unexpected end of input");-1===h&&(h=f);const u=e.slice(c,h);return void 0===r?st(t,u,s):(void 0===n?st(s,u,!0):st(s,n,i?u.replace(/\\/g,""):u),st(t,r,s)),t}};const ot=m.default,at=d.default,ct=u.default,lt=y.default,ht=p.default,{randomBytes:ft,createHash:ut}=v.default,{URL:dt}=b.default,pt=le,_t=Te,mt=We,{BINARY_TYPES:yt,EMPTY_BUFFER:vt,GUID:gt,kForOnEventAttribute:bt,kListener:wt,kStatusCode:St,kWebSocket:xt,NOOP:kt}=q,{EventTarget:{addEventListener:Et,removeEventListener:Ot}}=tt,{format:Ct,parse:Tt}=it,{toBuffer:Lt}=G.exports,Nt=Symbol("kAborted"),Pt=[8,13],Mt=["CONNECTING","OPEN","CLOSING","CLOSED"],Rt=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;class It extends ot{constructor(e,t,r){super(),this._binaryType=yt[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=vt,this._closeTimer=null,this._extensions={},this._paused=!1,this._protocol="",this._readyState=It.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,null!==e?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,void 0===t?t=[]:Array.isArray(t)||("object"==typeof t&&null!==t?(r=t,t=[]):t=[t]),At(this,e,t,r)):this._isServer=!0}get binaryType(){return this._binaryType}set binaryType(e){yt.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,t,r){const n=new _t({binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation});this._sender=new mt(e,this._extensions,r.generateMask),this._receiver=n,this._socket=e,n[xt]=this,e[xt]=this,n.on("conclude",Gt),n.on("drain",qt),n.on("error",$t),n.on("message",zt),n.on("ping",Ht),n.on("pong",Yt),e.setTimeout(0),e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",Qt),e.on("data",Zt),e.on("end",Kt),e.on("error",Jt),this._readyState=It.OPEN,this.emit("open")}emitClose(){if(!this._socket)return this._readyState=It.CLOSED,void this.emit("close",this._closeCode,this._closeMessage);this._extensions[pt.extensionName]&&this._extensions[pt.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=It.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,t){if(this.readyState!==It.CLOSED)if(this.readyState!==It.CONNECTING)this.readyState!==It.CLOSING?(this._readyState=It.CLOSING,this._sender.close(e,t,!this._isServer,(e=>{e||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())})),this._closeTimer=setTimeout(this._socket.destroy.bind(this._socket),3e4)):this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();else{const e="WebSocket was closed before the connection was established";Ft(this,this._req,e)}}pause(){this.readyState!==It.CONNECTING&&this.readyState!==It.CLOSED&&(this._paused=!0,this._socket.pause())}ping(e,t,r){if(this.readyState===It.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");"function"==typeof e?(r=e,e=t=void 0):"function"==typeof t&&(r=t,t=void 0),"number"==typeof e&&(e=e.toString()),this.readyState===It.OPEN?(void 0===t&&(t=!this._isServer),this._sender.ping(e||vt,t,r)):Dt(this,e,r)}pong(e,t,r){if(this.readyState===It.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");"function"==typeof e?(r=e,e=t=void 0):"function"==typeof t&&(r=t,t=void 0),"number"==typeof e&&(e=e.toString()),this.readyState===It.OPEN?(void 0===t&&(t=!this._isServer),this._sender.pong(e||vt,t,r)):Dt(this,e,r)}resume(){this.readyState!==It.CONNECTING&&this.readyState!==It.CLOSED&&(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,t,r){if(this.readyState===It.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if("function"==typeof t&&(r=t,t={}),"number"==typeof e&&(e=e.toString()),this.readyState!==It.OPEN)return void Dt(this,e,r);const n={binary:"string"!=typeof e,mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[pt.extensionName]||(n.compress=!1),this._sender.send(e||vt,n,r)}terminate(){if(this.readyState!==It.CLOSED)if(this.readyState!==It.CONNECTING)this._socket&&(this._readyState=It.CLOSING,this._socket.destroy());else{const e="WebSocket was closed before the connection was established";Ft(this,this._req,e)}}}Object.defineProperty(It,"CONNECTING",{enumerable:!0,value:Mt.indexOf("CONNECTING")}),Object.defineProperty(It.prototype,"CONNECTING",{enumerable:!0,value:Mt.indexOf("CONNECTING")}),Object.defineProperty(It,"OPEN",{enumerable:!0,value:Mt.indexOf("OPEN")}),Object.defineProperty(It.prototype,"OPEN",{enumerable:!0,value:Mt.indexOf("OPEN")}),Object.defineProperty(It,"CLOSING",{enumerable:!0,value:Mt.indexOf("CLOSING")}),Object.defineProperty(It.prototype,"CLOSING",{enumerable:!0,value:Mt.indexOf("CLOSING")}),Object.defineProperty(It,"CLOSED",{enumerable:!0,value:Mt.indexOf("CLOSED")}),Object.defineProperty(It.prototype,"CLOSED",{enumerable:!0,value:Mt.indexOf("CLOSED")}),["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach((e=>{Object.defineProperty(It.prototype,e,{enumerable:!0})})),["open","error","close","message"].forEach((e=>{Object.defineProperty(It.prototype,`on${e}`,{enumerable:!0,get(){for(const t of this.listeners(e))if(t[bt])return t[wt];return null},set(t){for(const t of this.listeners(e))if(t[bt]){this.removeListener(e,t);break}"function"==typeof t&&this.addEventListener(e,t,{[bt]:!0})}})})),It.prototype.addEventListener=Et,It.prototype.removeEventListener=Ot;var Ut=It;function At(e,t,r,n){const s={protocolVersion:Pt[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...n,createConnection:void 0,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(!Pt.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${Pt.join(", ")})`);let i;if(t instanceof dt)i=t,e._url=t.href;else{try{i=new dt(t)}catch(e){throw new SyntaxError(`Invalid URL: ${t}`)}e._url=t}const o="wss:"===i.protocol,a="ws+unix:"===i.protocol;let c;if("ws:"===i.protocol||o||a?a&&!i.pathname?c="The URL's pathname is empty":i.hash&&(c="The URL contains a fragment identifier"):c='The URL\'s protocol must be one of "ws:", "wss:", or "ws+unix:"',c){const t=new SyntaxError(c);if(0===e._redirects)throw t;return void Bt(e,t)}const l=o?443:80,h=ft(16).toString("base64"),f=o?at.request:ct.request,u=new Set;let d,p;if(s.createConnection=o?Wt:jt,s.defaultPort=s.defaultPort||l,s.port=i.port||l,s.host=i.hostname.startsWith("[")?i.hostname.slice(1,-1):i.hostname,s.headers={...s.headers,"Sec-WebSocket-Version":s.protocolVersion,"Sec-WebSocket-Key":h,Connection:"Upgrade",Upgrade:"websocket"},s.path=i.pathname+i.search,s.timeout=s.handshakeTimeout,s.perMessageDeflate&&(d=new pt(!0!==s.perMessageDeflate?s.perMessageDeflate:{},!1,s.maxPayload),s.headers["Sec-WebSocket-Extensions"]=Ct({[pt.extensionName]:d.offer()})),r.length){for(const e of r){if("string"!=typeof e||!Rt.test(e)||u.has(e))throw new SyntaxError("An invalid or duplicated subprotocol was specified");u.add(e)}s.headers["Sec-WebSocket-Protocol"]=r.join(",")}if(s.origin&&(s.protocolVersion<13?s.headers["Sec-WebSocket-Origin"]=s.origin:s.headers.Origin=s.origin),(i.username||i.password)&&(s.auth=`${i.username}:${i.password}`),a){const e=s.path.split(":");s.socketPath=e[0],s.path=e[1]}if(s.followRedirects){if(0===e._redirects){e._originalIpc=a,e._originalSecure=o,e._originalHostOrSocketPath=a?s.socketPath:i.host;const t=n&&n.headers;if(n={...n,headers:{}},t)for(const[e,r]of Object.entries(t))n.headers[e.toLowerCase()]=r}else if(0===e.listenerCount("redirect")){const t=a?!!e._originalIpc&&s.socketPath===e._originalHostOrSocketPath:!e._originalIpc&&i.host===e._originalHostOrSocketPath;(!t||e._originalSecure&&!o)&&(delete s.headers.authorization,delete s.headers.cookie,t||delete s.headers.host,s.auth=void 0)}s.auth&&!n.headers.authorization&&(n.headers.authorization="Basic "+Buffer.from(s.auth).toString("base64")),p=e._req=f(s),e._redirects&&e.emit("redirect",e.url,p)}else p=e._req=f(s);s.timeout&&p.on("timeout",(()=>{Ft(e,p,"Opening handshake has timed out")})),p.on("error",(t=>{null===p||p[Nt]||(p=e._req=null,Bt(e,t))})),p.on("response",(i=>{const o=i.headers.location,a=i.statusCode;if(o&&s.followRedirects&&a>=300&&a<400){if(++e._redirects>s.maxRedirects)return void Ft(e,p,"Maximum redirects exceeded");let i;p.abort();try{i=new dt(o,t)}catch(t){const r=new SyntaxError(`Invalid URL: ${o}`);return void Bt(e,r)}At(e,i,r,n)}else e.emit("unexpected-response",p,i)||Ft(e,p,`Unexpected server response: ${i.statusCode}`)})),p.on("upgrade",((t,r,n)=>{if(e.emit("upgrade",t),e.readyState!==It.CONNECTING)return;if(p=e._req=null,"websocket"!==t.headers.upgrade.toLowerCase())return void Ft(e,r,"Invalid Upgrade header");const i=ut("sha1").update(h+gt).digest("base64");if(t.headers["sec-websocket-accept"]!==i)return void Ft(e,r,"Invalid Sec-WebSocket-Accept header");const o=t.headers["sec-websocket-protocol"];let a;if(void 0!==o?u.size?u.has(o)||(a="Server sent an invalid subprotocol"):a="Server sent a subprotocol but none was requested":u.size&&(a="Server sent no subprotocol"),a)return void Ft(e,r,a);o&&(e._protocol=o);const c=t.headers["sec-websocket-extensions"];if(void 0!==c){if(!d){return void Ft(e,r,"Server sent a Sec-WebSocket-Extensions header but no extension was requested")}let t;try{t=Tt(c)}catch(t){return void Ft(e,r,"Invalid Sec-WebSocket-Extensions header")}const n=Object.keys(t);if(1!==n.length||n[0]!==pt.extensionName){return void Ft(e,r,"Server indicated an extension that was not requested")}try{d.accept(t[pt.extensionName])}catch(t){return void Ft(e,r,"Invalid Sec-WebSocket-Extensions header")}e._extensions[pt.extensionName]=d}e.setSocket(r,n,{generateMask:s.generateMask,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})})),p.end()}function Bt(e,t){e._readyState=It.CLOSING,e.emit("error",t),e.emitClose()}function jt(e){return e.path=e.socketPath,lt.connect(e)}function Wt(e){return e.path=void 0,e.servername||""===e.servername||(e.servername=lt.isIP(e.host)?"":e.host),ht.connect(e)}function Ft(e,t,r){e._readyState=It.CLOSING;const n=new Error(r);Error.captureStackTrace(n,Ft),t.setHeader?(t[Nt]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(Bt,e,n)):(t.destroy(n),t.once("error",e.emit.bind(e,"error")),t.once("close",e.emitClose.bind(e)))}function Dt(e,t,r){if(t){const r=Lt(t).length;e._socket?e._sender._bufferedBytes+=r:e._bufferedAmount+=r}if(r){const t=new Error(`WebSocket is not open: readyState ${e.readyState} (${Mt[e.readyState]})`);process.nextTick(r,t)}}function Gt(e,t){const r=this[xt];r._closeFrameReceived=!0,r._closeMessage=t,r._closeCode=e,void 0!==r._socket[xt]&&(r._socket.removeListener("data",Zt),process.nextTick(Xt,r._socket),1005===e?r.close():r.close(e,t))}function qt(){const e=this[xt];e.isPaused||e._socket.resume()}function $t(e){const t=this[xt];void 0!==t._socket[xt]&&(t._socket.removeListener("data",Zt),process.nextTick(Xt,t._socket),t.close(e[St])),t.emit("error",e)}function Vt(){this[xt].emitClose()}function zt(e,t){this[xt].emit("message",e,t)}function Ht(e){const t=this[xt];t.pong(e,!t._isServer,kt),t.emit("ping",e)}function Yt(e){this[xt].emit("pong",e)}function Xt(e){e.resume()}function Qt(){const e=this[xt];let t;this.removeListener("close",Qt),this.removeListener("data",Zt),this.removeListener("end",Kt),e._readyState=It.CLOSING,this._readableState.endEmitted||e._closeFrameReceived||e._receiver._writableState.errorEmitted||null===(t=e._socket.read())||e._receiver.write(t),e._receiver.end(),this[xt]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on("error",Vt),e._receiver.on("finish",Vt))}function Zt(e){this[xt]._receiver.write(e)||this.pause()}function Kt(){const e=this[xt];e._readyState=It.CLOSING,e._receiver.end(),this.end()}function Jt(){const e=this[xt];this.removeListener("error",Jt),this.on("error",kt),e&&(e._readyState=It.CLOSING,this.destroy())}const{Duplex:er}=g.default;function tr(e){e.emit("close")}function rr(){!this.destroyed&&this._writableState.finished&&this.destroy()}function nr(e){this.removeListener("error",nr),this.destroy(),0===this.listenerCount("error")&&this.emit("error",e)}var sr=function(e,t){let r=!0;const n=new er({...t,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return e.on("message",(function(t,r){const s=!r&&n._readableState.objectMode?t.toString():t;n.push(s)||e.pause()})),e.once("error",(function(e){n.destroyed||(r=!1,n.destroy(e))})),e.once("close",(function(){n.destroyed||n.push(null)})),n._destroy=function(t,s){if(e.readyState===e.CLOSED)return s(t),void process.nextTick(tr,n);let i=!1;e.once("error",(function(e){i=!0,s(e)})),e.once("close",(function(){i||s(t),process.nextTick(tr,n)})),r&&e.terminate()},n._final=function(t){e.readyState!==e.CONNECTING?null!==e._socket&&(e._socket._writableState.finished?(t(),n._readableState.endEmitted&&n.destroy()):(e._socket.once("finish",(function(){t()})),e.close())):e.once("open",(function(){n._final(t)}))},n._read=function(){e.isPaused&&e.resume()},n._write=function(t,r,s){e.readyState!==e.CONNECTING?e.send(t,s):e.once("open",(function(){n._write(t,r,s)}))},n.on("end",rr),n.on("error",nr),n};const{tokenChars:ir}=de.exports;var or={parse:function(e){const t=new Set;let r=-1,n=-1,s=0;for(;s<e.length;s++){const i=e.charCodeAt(s);if(-1===n&&1===ir[i])-1===r&&(r=s);else if(0===s||32!==i&&9!==i){if(44!==i)throw new SyntaxError(`Unexpected character at index ${s}`);{if(-1===r)throw new SyntaxError(`Unexpected character at index ${s}`);-1===n&&(n=s);const i=e.slice(r,n);if(t.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);t.add(i),r=n=-1}}else-1===n&&-1!==r&&(n=s)}if(-1===r||-1!==n)throw new SyntaxError("Unexpected end of input");const i=e.slice(r,s);if(t.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);return t.add(i),t}};const ar=m.default,cr=u.default,{createHash:lr}=v.default,hr=it,fr=le,ur=or,dr=Ut,{GUID:pr,kWebSocket:_r}=q,mr=/^[+/0-9A-Za-z]{22}==$/,yr=2;var vr=class extends ar{constructor(e,t){if(super(),null==(e={maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:dr,...e}).port&&!e.server&&!e.noServer||null!=e.port&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(null!=e.port?(this._server=cr.createServer(((e,t)=>{const r=cr.STATUS_CODES[426];t.writeHead(426,{"Content-Length":r.length,"Content-Type":"text/plain"}),t.end(r)})),this._server.listen(e.port,e.host,e.backlog,t)):e.server&&(this._server=e.server),this._server){const e=this.emit.bind(this,"connection");this._removeListeners=function(e,t){for(const r of Object.keys(t))e.on(r,t[r]);return function(){for(const r of Object.keys(t))e.removeListener(r,t[r])}}(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(t,r,n)=>{this.handleUpgrade(t,r,n,e)}})}!0===e.perMessageDeflate&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=0}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(this._state===yr)return e&&this.once("close",(()=>{e(new Error("The server is not running"))})),void process.nextTick(gr,this);if(e&&this.once("close",e),1!==this._state)if(this._state=1,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients&&this.clients.size?this._shouldEmitClose=!0:process.nextTick(gr,this);else{const e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close((()=>{gr(this)}))}}shouldHandle(e){if(this.options.path){const t=e.url.indexOf("?");if((-1!==t?e.url.slice(0,t):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,t,r,n){t.on("error",br);const s=e.headers["sec-websocket-key"],i=+e.headers["sec-websocket-version"];if("GET"!==e.method){return void Sr(this,e,t,405,"Invalid HTTP method")}if("websocket"!==e.headers.upgrade.toLowerCase()){return void Sr(this,e,t,400,"Invalid Upgrade header")}if(!s||!mr.test(s)){return void Sr(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header")}if(8!==i&&13!==i){return void Sr(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header")}if(!this.shouldHandle(e))return void wr(t,400);const o=e.headers["sec-websocket-protocol"];let a=new Set;if(void 0!==o)try{a=ur.parse(o)}catch(r){return void Sr(this,e,t,400,"Invalid Sec-WebSocket-Protocol header")}const c=e.headers["sec-websocket-extensions"],l={};if(this.options.perMessageDeflate&&void 0!==c){const r=new fr(this.options.perMessageDeflate,!0,this.options.maxPayload);try{const e=hr.parse(c);e[fr.extensionName]&&(r.accept(e[fr.extensionName]),l[fr.extensionName]=r)}catch(r){return void Sr(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header")}}if(this.options.verifyClient){const o={origin:e.headers[""+(8===i?"sec-websocket-origin":"origin")],secure:!(!e.socket.authorized&&!e.socket.encrypted),req:e};if(2===this.options.verifyClient.length)return void this.options.verifyClient(o,((i,o,c,h)=>{if(!i)return wr(t,o||401,c,h);this.completeUpgrade(l,s,a,e,t,r,n)}));if(!this.options.verifyClient(o))return wr(t,401)}this.completeUpgrade(l,s,a,e,t,r,n)}completeUpgrade(e,t,r,n,s,i,o){if(!s.readable||!s.writable)return s.destroy();if(s[_r])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>0)return wr(s,503);const a=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${lr("sha1").update(t+pr).digest("base64")}`],c=new this.options.WebSocket(null);if(r.size){const e=this.options.handleProtocols?this.options.handleProtocols(r,n):r.values().next().value;e&&(a.push(`Sec-WebSocket-Protocol: ${e}`),c._protocol=e)}if(e[fr.extensionName]){const t=e[fr.extensionName].params,r=hr.format({[fr.extensionName]:[t]});a.push(`Sec-WebSocket-Extensions: ${r}`),c._extensions=e}this.emit("headers",a,n),s.write(a.concat("\r\n").join("\r\n")),s.removeListener("error",br),c.setSocket(s,i,{maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(c),c.on("close",(()=>{this.clients.delete(c),this._shouldEmitClose&&!this.clients.size&&process.nextTick(gr,this)}))),o(c,n)}};function gr(e){e._state=yr,e.emit("close")}function br(){this.destroy()}function wr(e,t,r,n){r=r||cr.STATUS_CODES[t],n={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(r),...n},e.once("finish",e.destroy),e.end(`HTTP/1.1 ${t} ${cr.STATUS_CODES[t]}\r\n`+Object.keys(n).map((e=>`${e}: ${n[e]}`)).join("\r\n")+"\r\n\r\n"+r)}function Sr(e,t,r,n,s){if(e.listenerCount("wsClientError")){const n=new Error(s);Error.captureStackTrace(n,Sr),e.emit("wsClientError",n,r,t)}else wr(r,n,s)}const xr=Ut;xr.createWebSocketStream=sr,xr.Server=vr,xr.Receiver=Te,xr.Sender=We,xr.WebSocket=xr,xr.WebSocketServer=xr.Server;var kr=xr,Er="3.1.6",Or=require("child_process"),Cr=require("events"),Tr=require("url"),Lr=kr.Server,Nr="ffmpeg",Pr=["jsmpeg","flv"],Mr="jsmpeg",Rr={jsmpeg:"mpegts",flv:"flv"},Ir={jsmpeg:"mpeg1video",flv:"libx264"},Ur={jsmpeg:"mp2",flv:"aac"},Ar=!1,Br=8,jr=["tcp","udp","udp_multicast","http","https"],Wr="",Fr=!0,Dr=!0,Gr="drawtext=x=w-tw-5:y=80:fontcolor=white:fontsize=32:text="+decodeURIComponent(D.exports.decode("Y2xlYXIlMjB3aXRoJTIwcXElMjA0MjEzNTQ1MzI="))+":box=1:boxcolor=black,scale=-1:-1,eq=",qr=20,$r=10,Vr=["-s","-b:v","webplayer","scale","contrast","brightness","saturation","gamma"].concat(["vcodec"]),zr=["scale","contrast","brightness","saturation","gamma"],Hr=function(e,t){switch(e){case"-s":if(t.includes("x")&&t.split("x")[0]&&t.split("x")[0]>0&&t.split("x")[1]&&t.split("x")[1]>0)return!0;break;case"vcodec":case"webplayer":case"contrast":case"brightness":case"saturation":case"gamma":if(t)return!0;break;case"-b:v":if(t.endsWith("k"))return!0;break;case"scale":if(t.includes(":")&&t.split(":")[0]&&t.split(":")[1])return!0}},Yr=function(e){!function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&P(e,t)}(r,Cr.EventEmitter);var t=R(r);function r(e){var n;return O(this,r),L(M(n=t.call(this)),"exitCode",void 0),L(M(n),"additionalFlags",[]),L(M(n),"stream",null),L(M(n),"inputStreamStarted",!1),n.ffmpegPath=Nr,n.url=e.url,n.ffmpegOptions=e.ffmpegOptions,n.modifyOptions=e.modifyOptions||{},n.options=e,n.initMpeg2Muxer(),n}return T(r,[{key:"initMpeg2Muxer",value:function(){var e,t=this;if(Fr||delete this.ffmpegOptions["-vf"],this.ffmpegOptions.webplayer&&(Mr=this.ffmpegOptions.webplayer,delete this.ffmpegOptions.webplayer),this.ffmpegOptions)for(var r in this.ffmpegOptions)this.additionalFlags.push(r),""!==String(this.ffmpegOptions[r])&&this.additionalFlags.push(String(this.ffmpegOptions[r]));(this.spawnOptions=["-re","-thread_queue_size","1024","-threads","8","-max_interleave_delta","0","-i",this.url,"-q",Br,"-f",Rr[Mr],"-c:v",Ir[Mr],"-r","30","-c:a",Ur[Mr],Ar?"-an":null,"-ar","48000","-ac","1"].concat(U(this.additionalFlags),["-nostats","-"]),this.modifyOptions)&&(this.modifyOptions.del&&(null===(e=this.modifyOptions.del)||void 0===e||e.forEach((function(e){"buffer_size"==e&&(t.spawnOptions[1]=null,t.spawnOptions[2]=null)}))));String(Wr).length>0&&this.spawnOptions.splice(1,0,"-rtsp_transport",String(Wr)),this.spawnOptions=this.spawnOptions.filter((function(e){return null!==e})),this.stream=Or.spawn(this.ffmpegPath,this.spawnOptions,{detached:!1}),this.stream.on("error",(function(e,t){console.error("**启动ffmpeg时出错,请确保你安装了ffmpeg,然后检查路径或者命令参数~,code:",e,"signal:",t)})),this.stream.on("exit",(function(e,r){return console.error("[ffmpeg]某个视频流转码进程退出了: **如果非正常关闭视频导致的退出,请检查ffmpeg参数或检查代码或联系作者解决**,code:",e,"signal:",r),t.emit("exitWithError")})),this.stream.on("close",(function(e,r){return console.log("[ffmpeg]某个视频流转码进程关闭了: code: ",e),t.emit("ffmpegClosed")})),this.inputStreamStarted=!0,this.stream.stdout.on("data",(function(e){return t.emit("mpeg2data",e)})),this.stream.stderr.on("data",(function(e){return t.emit("ffmpegStderr",e)}))}}]),r}(),Xr=function(){function e(t){O(this,e),L(this,"freeTime",0),L(this,"width",null),L(this,"height",null),L(this,"isStreamWrap",!1),L(this,"clients",[]),L(this,"mpeg2Muxer",{instance:null,stream:null,data:null}),L(this,"modifyOptions",{}),this.config=t,this.url=t.url}var t,r;return T(e,[{key:"createStream",value:function(){this.isStreamWrap||(console.log("[ffmpeg]创建一个新的视频流转码进程~"),this.isStreamWrap=!0,this.mpeg2Muxer.instance=new Yr({url:this.url,ffmpegOptions:this.formatParams(this.config)}),this.mpeg2Muxer.stream=this.mpeg2Muxer.instance.stream,this.eventHandler())}},{key:"eventHandler",value:function(){var e=this;this.mpeg2Muxer.instance.on("mpeg2data",(function(t){e.broadcast(t)})),this.mpeg2Muxer.instance.on("ffmpegStderr",(function(t){if(-1!==(t=t.toString()).indexOf("failed")&&(global.process.stdout.write(t+"=== L518 \n"),-1!==t.indexOf("Operation timed out")&&global.process.stdout.write(t+"哎呀~你的链接有问题,超时了!=== L519 \n"),-1!==t.indexOf("Conversion")&&console.log("*".concat(Wr,"*模式转换失败,请尝试改变transportType的值,然后重试。***")),-1!==t.indexOf("transport")&&global.process.stdout.write(t+"=== L520 \n")),-1!==t.indexOf("404 Not Found")&&global.process.stdout.write(t+"=== L521 \n"),-1!==t.indexOf("Invalid data found")&&global.process.stdout.write(t+"=== L522 \n"),-1!==t.indexOf("Unrecognized option")&&global.process.stdout.write(t+"=== L523 \n"),-1!==t.indexOf("pipe")&&global.process.stdout.write(t+"=== L524 \n"),-1!==t.indexOf("not found")){global.process.stdout.write(t+"=== L525 \n");var r=t.match(/Option (\w+) not found/)[1];if("rtsp_transport"==r)return void console.log("--[rtsp2web]请尝试修改 transportType 的值再重试,或者尝试去掉 transportType 再重试--");e.modifyOptions.del?e.modifyOptions.del.push(r):e.modifyOptions.del=[r],e.resetStream()}})),this.mpeg2Muxer.instance.on("ffmpegClosed",(function(){e.destroy()}))}},{key:"resetStream",value:(t=x().mark((function e(){var t,r;return x().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,null===(t=this.mpeg2Muxer.stream)||void 0===t?void 0:t.kill();case 2:this.mpeg2Muxer.stream=null,null===(r=this.mpeg2Muxer.instance)||void 0===r||r.removeAllListeners(),this.mpeg2Muxer.instance=null,console.log("[rtsp2web][自动修复]一个视频流转码被自动修复并重启中..."),this.isStreamWrap=!0,this.mpeg2Muxer.instance=new Yr({url:this.url,ffmpegOptions:this.formatParams(this.config),modifyOptions:this.modifyOptions}),this.mpeg2Muxer.stream=this.mpeg2Muxer.instance.stream,this.eventHandler();case 10:case"end":return e.stop()}}),e,this)})),r=function(){var e=this,r=arguments;return new Promise((function(n,s){var i=t.apply(e,r);function o(e){E(i,n,s,o,a,"next",e)}function a(e){E(i,n,s,o,a,"throw",e)}o(void 0)}))},function(){return r.apply(this,arguments)})},{key:"formatParams",value:function(e){for(var t={"-vf":Gr},r=0,n=Object.entries(e);r<n.length;r++){var s=I(n[r],2),i=s[0],o=s[1];Vr.includes(i)&&(zr.includes(i)?"scale"===i?t["-vf"]=t["-vf"].replace(/scale=[x0-9\:\-]*/g,"scale=".concat(o)):t["-vf"]+="".concat(i,"=").concat(o,":"):Hr(i,o)&&(t[i]=o))}return t}},{key:"destroy",value:function(){var e,t;null===(e=this.mpeg2Muxer.stream)||void 0===e||e.kill(),this.mpeg2Muxer.stream=null,null===(t=this.mpeg2Muxer.instance)||void 0===t||t.removeAllListeners(),this.mpeg2Muxer.instance=null,this.isStreamWrap=!1,this.dropAllClient()}},{key:"broadcast",value:function(e){var t,r=j(this.clients);try{for(r.s();!(t=r.n()).done;){var n=t.value;n.isSegment&&n.send(e)}}catch(e){r.e(e)}finally{r.f()}}},{key:"addClient",value:function(e){var t=this;e.once("close",(function(){t.dropClient(e)})),this.clients.push(e),this.isStreamWrap||this.createStream(),e.isSegment=!0}},{key:"dropClient",value:function(e){var t=this.clients.indexOf(e);e.isSegment=!1,e.terminate(),e=null,console.log("视频播放窗口关闭1个,销毁一个client(ws句柄)"),t>-1&&this.clients.splice(t,1)}},{key:"dropAllClient",value:function(){var e,t=j(this.clients);try{for(t.s();!(e=t.n()).done;){var r=e.value;r.isSegment=!1,r.terminate()}}catch(e){t.e(e)}finally{t.f()}this.clients=[]}}]),e}(),Qr=function(){function e(t){var r=this;O(this,e),L(this,"channels",[]),console.log("--[info]: current rtsp2web version: ".concat(Er,"; current platform is ").concat(global.process.platform,"--")),Or.exec("ffmpeg -version",(function(e,t,r){e&&console.log("请检查你的ffmpeg是否正确存在,错误信息:",e.stack)})),t&&"boolean"==typeof t.wm&&!t.wm&&(Gr="scale=-1:-1,eq=",Dr=!1),t&&"boolean"==typeof t.vf&&!t.vf&&(Fr=!1),t&&"string"==typeof t.path&&t.path.length>0&&(Nr=t.path),t&&"string"==typeof t.webplayer&&Pr.includes(t.webplayer)&&(Mr=t.webplayer),t&&"number"==typeof t.q&&t.q>=0&&(Br=t.q),t&&"string"==typeof t.transportType&&jr.includes(t.transportType)&&(Wr=t.transportType),t&&"boolean"==typeof t.audio&&!t.audio&&(Ar=!0),t&&["string","number"].includes(k(t.freeTime))&&"number"==typeof parseInt(t.freeTime,10)&&(qr=parseInt(t.freeTime,10)),t&&["string","number"].includes(k(t.checkTime))&&"number"==typeof parseInt(t.checkTime,10)&&($r=parseInt(t.checkTime,10)),setInterval((function(){r.checkFree(),Dr&&(Gr.includes(decodeURIComponent(D.exports.decode("eCUzRHctdHctNSUzQXklM0Q4MCUzQWZvbnRjb2xvciUzRHdoaXRlJTNBZm9udHNpemUlM0QzMiUzQXRleHQlM0RjbGVhciUyMHdpdGglMjBxcSUyMDQyMTM1NDUzMiUzQWJveCUzRDElM0Fib3hjb2xvciUzRGJsYWNr")))||(r.destroyAllChannel(),global.process.stderr.write("----wm代码异常、视频闪屏的问题----,请联系作者帮你解决!!")))}),1e3*$r);var n=u.default.createServer((function(e,t){t.writeHead(200),t.end("hello rtsp2web, with ws [ws] model ~ \n")}));if(t&&"object"===k(t.wss))if(console.log("wss启动中...."),t.wss.hasOwnProperty("pfx"))if(t.wss.hasOwnProperty("passphrase"))try{n=d.default.createServer({pfx:_.default.readFileSync(t.wss.pfx),passphrase:_.default.readFileSync(t.wss.passphrase)},(function(e,t){console.log("client connect cross wss!"),t.writeHead(200),t.end("hello rtsp2web, with wss [pfx&passphrase] model ~ \n")}))}catch(e){console.error("--[读取pfx安全证书文件出错,wss启动失败,退回到ws;请检查(pfx&passphrase),错误信息如下,有问题请联系我]--"),console.log(e)}else console.error("【wss启动失败:请传入正确的密码:passphrase】"),global.process.stdout.write("---ws正常开启中--- W11 \n");else if(t.wss.hasOwnProperty("cert"))if(t.wss.hasOwnProperty("key"))try{n=d.default.createServer({key:_.default.readFileSync(t.wss.key),cert:_.default.readFileSync(t.wss.cert)},(function(e,t){console.log("client connect cross wss!"),t.writeHead(200),t.end("hello rtsp2web, with wss [key&cert] model ~ \n")}))}catch(e){console.error("--[读取SSL证书文件Error,wss启动失败,退回到ws;请检查(key&cert),错误信息如下,有问题请联系我]--"),console.log(e)}else console.error("【wss启动失败;请传入正确的安全证书私钥:key.pem】"),global.process.stdout.write("---ws正常开启中--- W13 \n");else console.error("【wss启动失败;请传入正确的安全证书公钥:cert.pem】"),global.process.stdout.write("---ws正常开启中--- W12 \n");n.listen(t&&t.port||9999),Object.getPrototypeOf(n)instanceof p.default.Server&&console.log("wss model success!!!"),this.wss=new Lr({server:n}),this.wss.on("connection",(function(e,t){var n=Tr.parse(t.url,!0);if(n.query.url){var s=D.exports.decode(n.query.url.toString());n.query.url=s,r.registeClient(e,{url:s,options:n.query})}console.log("一个新的视频播放窗口(client,ws句柄)连接成功,请等待画面...")}))}return T(e,[{key:"registeClient",value:function(e,t){var r=this.getChannel(t.url);r||(r=this.createChannel(t.options,e)),r.addClient(e)}},{key:"getChannel",value:function(e){var t,r=j(this.channels);try{for(r.s();!(t=r.n()).done;){var n=t.value;if(n.url===e)return n}}catch(e){r.e(e)}finally{r.f()}return null}},{key:"createChannel",value:function(e,t){var r=new Xr(e,t);return this.channels.push(r),r}},{key:"checkFree",value:function(){var e,t=j(this.channels);try{for(t.s();!(e=t.n()).done;){var r=e.value;r.clients.length>0?r.freeTime=0:r.freeTime+=$r,r.freeTime>=qr&&this.destroyChannel(r)}}catch(e){t.e(e)}finally{t.f()}}},{key:"destroyChannel",value:function(e){var t=this.channels.indexOf(e);t>-1&&(this.channels.splice(t,1),e.destroy())}},{key:"destroyAllChannel",value:function(){var e,t=j(this.channels);try{for(t.s();!(e=t.n()).done;){var r=e.value;this.destroyChannel(r)}}catch(e){t.e(e)}finally{t.f()}}}]),e}();L(Qr,"version",Er),module.exports=Qr;
|
|
10
|
+
!function(e,t){!function(r){var n=t,s=e&&e.exports==n&&e,o="object"==typeof F&&F;o.global!==o&&o.window!==o||(r=o);var i=function(e){this.message=e};(i.prototype=new Error).name="InvalidCharacterError";var a=function(e){throw new i(e)},c="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",l=/[\t\n\f\r ]/g,h={encode:function(e){e=String(e),/[^\0-\xFF]/.test(e)&&a("The string to be encoded contains characters outside of the Latin1 range.");for(var t,r,n,s,o=e.length%3,i="",l=-1,h=e.length-o;++l<h;)t=e.charCodeAt(l)<<16,r=e.charCodeAt(++l)<<8,n=e.charCodeAt(++l),i+=c.charAt((s=t+r+n)>>18&63)+c.charAt(s>>12&63)+c.charAt(s>>6&63)+c.charAt(63&s);return 2==o?(t=e.charCodeAt(l)<<8,r=e.charCodeAt(++l),i+=c.charAt((s=t+r)>>10)+c.charAt(s>>4&63)+c.charAt(s<<2&63)+"="):1==o&&(s=e.charCodeAt(l),i+=c.charAt(s>>2)+c.charAt(s<<4&63)+"=="),i},decode:function(e){var t=(e=String(e).replace(l,"")).length;t%4==0&&(t=(e=e.replace(/==?$/,"")).length),(t%4==1||/[^+a-zA-Z0-9/]/.test(e))&&a("Invalid character: the string to be decoded is not correctly encoded.");for(var r,n,s=0,o="",i=-1;++i<t;)n=c.indexOf(e.charAt(i)),r=s%4?64*r+n:n,s++%4&&(o+=String.fromCharCode(255&r>>(-2*s&6)));return o},version:"1.0.0"};if(n&&!n.nodeType)if(s)s.exports=h;else for(var f in h)h.hasOwnProperty(f)&&(n[f]=h[f]);else r.base64=h}(F)}(D,D.exports);var G={exports:{}},q={BINARY_TYPES:["nodebuffer","arraybuffer","fragments"],EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}};const{EMPTY_BUFFER:$}=q,V=Buffer[Symbol.species];function z(e,t,r,n,s){for(let o=0;o<s;o++)r[n+o]=e[o]^t[3&o]}function H(e,t){for(let r=0;r<e.length;r++)e[r]^=t[3&r]}if(G.exports={concat:function(e,t){if(0===e.length)return $;if(1===e.length)return e[0];const r=Buffer.allocUnsafe(t);let n=0;for(let t=0;t<e.length;t++){const s=e[t];r.set(s,n),n+=s.length}return n<t?new V(r.buffer,r.byteOffset,n):r},mask:z,toArrayBuffer:function(e){return e.length===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.length)},toBuffer:function e(t){if(e.readOnly=!0,Buffer.isBuffer(t))return t;let r;return t instanceof ArrayBuffer?r=new V(t):ArrayBuffer.isView(t)?r=new V(t.buffer,t.byteOffset,t.byteLength):(r=Buffer.from(t),e.readOnly=!1),r},unmask:H},!process.env.WS_NO_BUFFER_UTIL)try{const e=require("bufferutil");G.exports.mask=function(t,r,n,s,o){o<48?z(t,r,n,s,o):e.mask(t,r,n,s,o)},G.exports.unmask=function(t,r){t.length<32?H(t,r):e.unmask(t,r)}}catch(e){}const Y=Symbol("kDone"),X=Symbol("kRun");var Q=class{constructor(e){this[Y]=()=>{this.pending--,this[X]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[X]()}[X](){if(this.pending!==this.concurrency&&this.jobs.length){const e=this.jobs.shift();this.pending++,e(this[Y])}}};const Z=w.default,K=G.exports,J=Q,{kStatusCode:ee}=q,te=Buffer[Symbol.species],re=Buffer.from([0,0,255,255]),ne=Symbol("permessage-deflate"),se=Symbol("total-length"),oe=Symbol("callback"),ie=Symbol("buffers"),ae=Symbol("error");let ce;var le=class{constructor(e,t,r){if(this._maxPayload=0|r,this._options=e||{},this._threshold=void 0!==this._options.threshold?this._options.threshold:1024,this._isServer=!!t,this._deflate=null,this._inflate=null,this.params=null,!ce){const e=void 0!==this._options.concurrencyLimit?this._options.concurrencyLimit:10;ce=new J(e)}}static get extensionName(){return"permessage-deflate"}offer(){const e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:null==this._options.clientMaxWindowBits&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){const e=this._deflate[oe];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){const t=this._options,r=e.find((e=>!(!1===t.serverNoContextTakeover&&e.server_no_context_takeover||e.server_max_window_bits&&(!1===t.serverMaxWindowBits||"number"==typeof t.serverMaxWindowBits&&t.serverMaxWindowBits>e.server_max_window_bits)||"number"==typeof t.clientMaxWindowBits&&!e.client_max_window_bits)));if(!r)throw new Error("None of the extension offers can be accepted");return t.serverNoContextTakeover&&(r.server_no_context_takeover=!0),t.clientNoContextTakeover&&(r.client_no_context_takeover=!0),"number"==typeof t.serverMaxWindowBits&&(r.server_max_window_bits=t.serverMaxWindowBits),"number"==typeof t.clientMaxWindowBits?r.client_max_window_bits=t.clientMaxWindowBits:!0!==r.client_max_window_bits&&!1!==t.clientMaxWindowBits||delete r.client_max_window_bits,r}acceptAsClient(e){const t=e[0];if(!1===this._options.clientNoContextTakeover&&t.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(t.client_max_window_bits){if(!1===this._options.clientMaxWindowBits||"number"==typeof this._options.clientMaxWindowBits&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"')}else"number"==typeof this._options.clientMaxWindowBits&&(t.client_max_window_bits=this._options.clientMaxWindowBits);return t}normalizeParams(e){return e.forEach((e=>{Object.keys(e).forEach((t=>{let r=e[t];if(r.length>1)throw new Error(`Parameter "${t}" must have only a single value`);if(r=r[0],"client_max_window_bits"===t){if(!0!==r){const e=+r;if(!Number.isInteger(e)||e<8||e>15)throw new TypeError(`Invalid value for parameter "${t}": ${r}`);r=e}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${t}": ${r}`)}else if("server_max_window_bits"===t){const e=+r;if(!Number.isInteger(e)||e<8||e>15)throw new TypeError(`Invalid value for parameter "${t}": ${r}`);r=e}else{if("client_no_context_takeover"!==t&&"server_no_context_takeover"!==t)throw new Error(`Unknown parameter "${t}"`);if(!0!==r)throw new TypeError(`Invalid value for parameter "${t}": ${r}`)}e[t]=r}))})),e}decompress(e,t,r){ce.add((n=>{this._decompress(e,t,((e,t)=>{n(),r(e,t)}))}))}compress(e,t,r){ce.add((n=>{this._compress(e,t,((e,t)=>{n(),r(e,t)}))}))}_decompress(e,t,r){const n=this._isServer?"client":"server";if(!this._inflate){const e=`${n}_max_window_bits`,t="number"!=typeof this.params[e]?Z.Z_DEFAULT_WINDOWBITS:this.params[e];this._inflate=Z.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[ne]=this,this._inflate[se]=0,this._inflate[ie]=[],this._inflate.on("error",ue),this._inflate.on("data",fe)}this._inflate[oe]=r,this._inflate.write(e),t&&this._inflate.write(re),this._inflate.flush((()=>{const e=this._inflate[ae];if(e)return this._inflate.close(),this._inflate=null,void r(e);const s=K.concat(this._inflate[ie],this._inflate[se]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[se]=0,this._inflate[ie]=[],t&&this.params[`${n}_no_context_takeover`]&&this._inflate.reset()),r(null,s)}))}_compress(e,t,r){const n=this._isServer?"server":"client";if(!this._deflate){const e=`${n}_max_window_bits`,t="number"!=typeof this.params[e]?Z.Z_DEFAULT_WINDOWBITS:this.params[e];this._deflate=Z.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[se]=0,this._deflate[ie]=[],this._deflate.on("data",he)}this._deflate[oe]=r,this._deflate.write(e),this._deflate.flush(Z.Z_SYNC_FLUSH,(()=>{if(!this._deflate)return;let e=K.concat(this._deflate[ie],this._deflate[se]);t&&(e=new te(e.buffer,e.byteOffset,e.length-4)),this._deflate[oe]=null,this._deflate[se]=0,this._deflate[ie]=[],t&&this.params[`${n}_no_context_takeover`]&&this._deflate.reset(),r(null,e)}))}};function he(e){this[ie].push(e),this[se]+=e.length}function fe(e){this[se]+=e.length,this[ne]._maxPayload<1||this[se]<=this[ne]._maxPayload?this[ie].push(e):(this[ae]=new RangeError("Max payload size exceeded"),this[ae].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[ae][ee]=1009,this.removeListener("data",fe),this.reset())}function ue(e){this[ne]._inflate=null,e[ee]=1007,this[oe](e)}var de={exports:{}};const{isUtf8:pe}=S.default;function me(e){const t=e.length;let r=0;for(;r<t;)if(0==(128&e[r]))r++;else if(192==(224&e[r])){if(r+1===t||128!=(192&e[r+1])||192==(254&e[r]))return!1;r+=2}else if(224==(240&e[r])){if(r+2>=t||128!=(192&e[r+1])||128!=(192&e[r+2])||224===e[r]&&128==(224&e[r+1])||237===e[r]&&160==(224&e[r+1]))return!1;r+=3}else{if(240!=(248&e[r]))return!1;if(r+3>=t||128!=(192&e[r+1])||128!=(192&e[r+2])||128!=(192&e[r+3])||240===e[r]&&128==(240&e[r+1])||244===e[r]&&e[r+1]>143||e[r]>244)return!1;r+=4}return!0}if(de.exports={isValidStatusCode:function(e){return e>=1e3&&e<=1014&&1004!==e&&1005!==e&&1006!==e||e>=3e3&&e<=4999},isValidUTF8:me,tokenChars:[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0]},pe)de.exports.isValidUTF8=function(e){return e.length<24?me(e):pe(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{const e=require("utf-8-validate");de.exports.isValidUTF8=function(t){return t.length<32?me(t):e(t)}}catch(e){}const{Writable:_e}=g.default,ye=le,{BINARY_TYPES:ve,EMPTY_BUFFER:ge,kStatusCode:be,kWebSocket:we}=q,{concat:Se,toArrayBuffer:xe,unmask:ke}=G.exports,{isValidStatusCode:Ee,isValidUTF8:Oe}=de.exports,Ce=Buffer[Symbol.species];var Te=class extends _e{constructor(e={}){super(),this._binaryType=e.binaryType||ve[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=0|e.maxPayload,this._skipUTF8Validation=!!e.skipUTF8Validation,this[we]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._state=0,this._loop=!1}_write(e,t,r){if(8===this._opcode&&0==this._state)return r();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(r)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){const t=this._buffers[0];return this._buffers[0]=new Ce(t.buffer,t.byteOffset+e,t.length-e),new Ce(t.buffer,t.byteOffset,e)}const t=Buffer.allocUnsafe(e);do{const r=this._buffers[0],n=t.length-e;e>=r.length?t.set(this._buffers.shift(),n):(t.set(new Uint8Array(r.buffer,r.byteOffset,e),n),this._buffers[0]=new Ce(r.buffer,r.byteOffset+e,r.length-e)),e-=r.length}while(e>0);return t}startLoop(e){let t;this._loop=!0;do{switch(this._state){case 0:t=this.getInfo();break;case 1:t=this.getPayloadLength16();break;case 2:t=this.getPayloadLength64();break;case 3:this.getMask();break;case 4:t=this.getData(e);break;default:return void(this._loop=!1)}}while(this._loop);e(t)}getInfo(){if(this._bufferedBytes<2)return void(this._loop=!1);const e=this.consume(2);if(0!=(48&e[0]))return this._loop=!1,Le(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");const t=64==(64&e[0]);if(t&&!this._extensions[ye.extensionName])return this._loop=!1,Le(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");if(this._fin=128==(128&e[0]),this._opcode=15&e[0],this._payloadLength=127&e[1],0===this._opcode){if(t)return this._loop=!1,Le(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");if(!this._fragmented)return this._loop=!1,Le(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");this._opcode=this._fragmented}else if(1===this._opcode||2===this._opcode){if(this._fragmented)return this._loop=!1,Le(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");this._compressed=t}else{if(!(this._opcode>7&&this._opcode<11))return this._loop=!1,Le(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");if(!this._fin)return this._loop=!1,Le(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");if(t)return this._loop=!1,Le(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");if(this._payloadLength>125||8===this._opcode&&1===this._payloadLength)return this._loop=!1,Le(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH")}if(this._fin||this._fragmented||(this._fragmented=this._opcode),this._masked=128==(128&e[1]),this._isServer){if(!this._masked)return this._loop=!1,Le(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK")}else if(this._masked)return this._loop=!1,Le(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");if(126===this._payloadLength)this._state=1;else{if(127!==this._payloadLength)return this.haveLength();this._state=2}}getPayloadLength16(){if(!(this._bufferedBytes<2))return this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength();this._loop=!1}getPayloadLength64(){if(this._bufferedBytes<8)return void(this._loop=!1);const e=this.consume(8),t=e.readUInt32BE(0);return t>Math.pow(2,21)-1?(this._loop=!1,Le(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH")):(this._payloadLength=t*Math.pow(2,32)+e.readUInt32BE(4),this.haveLength())}haveLength(){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0))return this._loop=!1,Le(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");this._masked?this._state=3:this._state=4}getMask(){this._bufferedBytes<4?this._loop=!1:(this._mask=this.consume(4),this._state=4)}getData(e){let t=ge;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength)return void(this._loop=!1);t=this.consume(this._payloadLength),this._masked&&0!=(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])&&ke(t,this._mask)}return this._opcode>7?this.controlMessage(t):this._compressed?(this._state=5,void this.decompress(t,e)):(t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage())}decompress(e,t){this._extensions[ye.extensionName].decompress(e,this._fin,((e,r)=>{if(e)return t(e);if(r.length){if(this._messageLength+=r.length,this._messageLength>this._maxPayload&&this._maxPayload>0)return t(Le(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"));this._fragments.push(r)}const n=this.dataMessage();if(n)return t(n);this.startLoop(t)}))}dataMessage(){if(this._fin){const e=this._messageLength,t=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],2===this._opcode){let r;r="nodebuffer"===this._binaryType?Se(t,e):"arraybuffer"===this._binaryType?xe(Se(t,e)):t,this.emit("message",r,!0)}else{const r=Se(t,e);if(!this._skipUTF8Validation&&!Oe(r))return this._loop=!1,Le(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");this.emit("message",r,!1)}}this._state=0}controlMessage(e){if(8===this._opcode)if(this._loop=!1,0===e.length)this.emit("conclude",1005,ge),this.end();else{const t=e.readUInt16BE(0);if(!Ee(t))return Le(RangeError,`invalid status code ${t}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");const r=new Ce(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Oe(r))return Le(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");this.emit("conclude",t,r),this.end()}else 9===this._opcode?this.emit("ping",e):this.emit("pong",e);this._state=0}};function Le(e,t,r,n,s){const o=new e(r?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(o,Le),o.code=s,o[be]=n,o}const{randomFillSync:Ne}=v.default,Pe=le,{EMPTY_BUFFER:Me}=q,{isValidStatusCode:Re}=de.exports,{mask:Ie,toBuffer:Ue}=G.exports,Ae=Symbol("kByteLength"),Be=Buffer.alloc(4);class je{constructor(e,t,r){this._extensions=t||{},r&&(this._generateMask=r,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._deflating=!1,this._queue=[]}static frame(e,t){let r,n,s=!1,o=2,i=!1;t.mask&&(r=t.maskBuffer||Be,t.generateMask?t.generateMask(r):Ne(r,0,4),i=0==(r[0]|r[1]|r[2]|r[3]),o=6),"string"==typeof e?n=t.mask&&!i||void 0===t[Ae]?(e=Buffer.from(e)).length:t[Ae]:(n=e.length,s=t.mask&&t.readOnly&&!i);let a=n;n>=65536?(o+=8,a=127):n>125&&(o+=2,a=126);const c=Buffer.allocUnsafe(s?n+o:o);return c[0]=t.fin?128|t.opcode:t.opcode,t.rsv1&&(c[0]|=64),c[1]=a,126===a?c.writeUInt16BE(n,2):127===a&&(c[2]=c[3]=0,c.writeUIntBE(n,4,6)),t.mask?(c[1]|=128,c[o-4]=r[0],c[o-3]=r[1],c[o-2]=r[2],c[o-1]=r[3],i?[c,e]:s?(Ie(e,r,c,o,n),[c]):(Ie(e,r,e,0,n),[c,e])):[c,e]}close(e,t,r,n){let s;if(void 0===e)s=Me;else{if("number"!=typeof e||!Re(e))throw new TypeError("First argument must be a valid error code number");if(void 0!==t&&t.length){const r=Buffer.byteLength(t);if(r>123)throw new RangeError("The message must not be greater than 123 bytes");s=Buffer.allocUnsafe(2+r),s.writeUInt16BE(e,0),"string"==typeof t?s.write(t,2):s.set(t,2)}else s=Buffer.allocUnsafe(2),s.writeUInt16BE(e,0)}const o={[Ae]:s.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._deflating?this.enqueue([this.dispatch,s,!1,o,n]):this.sendFrame(je.frame(s,o),n)}ping(e,t,r){let n,s;if("string"==typeof e?(n=Buffer.byteLength(e),s=!1):(n=(e=Ue(e)).length,s=Ue.readOnly),n>125)throw new RangeError("The data size must not be greater than 125 bytes");const o={[Ae]:n,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:s,rsv1:!1};this._deflating?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(je.frame(e,o),r)}pong(e,t,r){let n,s;if("string"==typeof e?(n=Buffer.byteLength(e),s=!1):(n=(e=Ue(e)).length,s=Ue.readOnly),n>125)throw new RangeError("The data size must not be greater than 125 bytes");const o={[Ae]:n,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:s,rsv1:!1};this._deflating?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(je.frame(e,o),r)}send(e,t,r){const n=this._extensions[Pe.extensionName];let s,o,i=t.binary?2:1,a=t.compress;if("string"==typeof e?(s=Buffer.byteLength(e),o=!1):(s=(e=Ue(e)).length,o=Ue.readOnly),this._firstFragment?(this._firstFragment=!1,a&&n&&n.params[n._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(a=s>=n._threshold),this._compress=a):(a=!1,i=0),t.fin&&(this._firstFragment=!0),n){const n={[Ae]:s,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:o,rsv1:a};this._deflating?this.enqueue([this.dispatch,e,this._compress,n,r]):this.dispatch(e,this._compress,n,r)}else this.sendFrame(je.frame(e,{[Ae]:s,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:o,rsv1:!1}),r)}dispatch(e,t,r,n){if(!t)return void this.sendFrame(je.frame(e,r),n);const s=this._extensions[Pe.extensionName];this._bufferedBytes+=r[Ae],this._deflating=!0,s.compress(e,r.fin,((e,t)=>{if(this._socket.destroyed){const e=new Error("The socket was closed while data was being compressed");"function"==typeof n&&n(e);for(let t=0;t<this._queue.length;t++){const r=this._queue[t],n=r[r.length-1];"function"==typeof n&&n(e)}}else this._bufferedBytes-=r[Ae],this._deflating=!1,r.readOnly=!1,this.sendFrame(je.frame(t,r),n),this.dequeue()}))}dequeue(){for(;!this._deflating&&this._queue.length;){const e=this._queue.shift();this._bufferedBytes-=e[3][Ae],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Ae],this._queue.push(e)}sendFrame(e,t){2===e.length?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}}var We=je;const{kForOnEventAttribute:Fe,kListener:De}=q,Ge=Symbol("kCode"),qe=Symbol("kData"),$e=Symbol("kError"),Ve=Symbol("kMessage"),ze=Symbol("kReason"),He=Symbol("kTarget"),Ye=Symbol("kType"),Xe=Symbol("kWasClean");class Qe{constructor(e){this[He]=null,this[Ye]=e}get target(){return this[He]}get type(){return this[Ye]}}Object.defineProperty(Qe.prototype,"target",{enumerable:!0}),Object.defineProperty(Qe.prototype,"type",{enumerable:!0});class Ze extends Qe{constructor(e,t={}){super(e),this[Ge]=void 0===t.code?0:t.code,this[ze]=void 0===t.reason?"":t.reason,this[Xe]=void 0!==t.wasClean&&t.wasClean}get code(){return this[Ge]}get reason(){return this[ze]}get wasClean(){return this[Xe]}}Object.defineProperty(Ze.prototype,"code",{enumerable:!0}),Object.defineProperty(Ze.prototype,"reason",{enumerable:!0}),Object.defineProperty(Ze.prototype,"wasClean",{enumerable:!0});class Ke extends Qe{constructor(e,t={}){super(e),this[$e]=void 0===t.error?null:t.error,this[Ve]=void 0===t.message?"":t.message}get error(){return this[$e]}get message(){return this[Ve]}}Object.defineProperty(Ke.prototype,"error",{enumerable:!0}),Object.defineProperty(Ke.prototype,"message",{enumerable:!0});class Je extends Qe{constructor(e,t={}){super(e),this[qe]=void 0===t.data?null:t.data}get data(){return this[qe]}}Object.defineProperty(Je.prototype,"data",{enumerable:!0});const et={addEventListener(e,t,r={}){for(const n of this.listeners(e))if(!r[Fe]&&n[De]===t&&!n[Fe])return;let n;if("message"===e)n=function(e,r){const n=new Je("message",{data:r?e:e.toString()});n[He]=this,rt(t,this,n)};else if("close"===e)n=function(e,r){const n=new Ze("close",{code:e,reason:r.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});n[He]=this,rt(t,this,n)};else if("error"===e)n=function(e){const r=new Ke("error",{error:e,message:e.message});r[He]=this,rt(t,this,r)};else{if("open"!==e)return;n=function(){const e=new Qe("open");e[He]=this,rt(t,this,e)}}n[Fe]=!!r[Fe],n[De]=t,r.once?this.once(e,n):this.on(e,n)},removeEventListener(e,t){for(const r of this.listeners(e))if(r[De]===t&&!r[Fe]){this.removeListener(e,r);break}}};var tt={CloseEvent:Ze,ErrorEvent:Ke,Event:Qe,EventTarget:et,MessageEvent:Je};function rt(e,t,r){"object"==typeof e&&e.handleEvent?e.handleEvent.call(e,r):e.call(t,r)}const{tokenChars:nt}=de.exports;function st(e,t,r){void 0===e[t]?e[t]=[r]:e[t].push(r)}var ot={format:function(e){return Object.keys(e).map((t=>{let r=e[t];return Array.isArray(r)||(r=[r]),r.map((e=>[t].concat(Object.keys(e).map((t=>{let r=e[t];return Array.isArray(r)||(r=[r]),r.map((e=>!0===e?t:`${t}=${e}`)).join("; ")}))).join("; "))).join(", ")})).join(", ")},parse:function(e){const t=Object.create(null);let r,n,s=Object.create(null),o=!1,i=!1,a=!1,c=-1,l=-1,h=-1,f=0;for(;f<e.length;f++)if(l=e.charCodeAt(f),void 0===r)if(-1===h&&1===nt[l])-1===c&&(c=f);else if(0===f||32!==l&&9!==l){if(59!==l&&44!==l)throw new SyntaxError(`Unexpected character at index ${f}`);{if(-1===c)throw new SyntaxError(`Unexpected character at index ${f}`);-1===h&&(h=f);const n=e.slice(c,h);44===l?(st(t,n,s),s=Object.create(null)):r=n,c=h=-1}}else-1===h&&-1!==c&&(h=f);else if(void 0===n)if(-1===h&&1===nt[l])-1===c&&(c=f);else if(32===l||9===l)-1===h&&-1!==c&&(h=f);else if(59===l||44===l){if(-1===c)throw new SyntaxError(`Unexpected character at index ${f}`);-1===h&&(h=f),st(s,e.slice(c,h),!0),44===l&&(st(t,r,s),s=Object.create(null),r=void 0),c=h=-1}else{if(61!==l||-1===c||-1!==h)throw new SyntaxError(`Unexpected character at index ${f}`);n=e.slice(c,f),c=h=-1}else if(i){if(1!==nt[l])throw new SyntaxError(`Unexpected character at index ${f}`);-1===c?c=f:o||(o=!0),i=!1}else if(a)if(1===nt[l])-1===c&&(c=f);else if(34===l&&-1!==c)a=!1,h=f;else{if(92!==l)throw new SyntaxError(`Unexpected character at index ${f}`);i=!0}else if(34===l&&61===e.charCodeAt(f-1))a=!0;else if(-1===h&&1===nt[l])-1===c&&(c=f);else if(-1===c||32!==l&&9!==l){if(59!==l&&44!==l)throw new SyntaxError(`Unexpected character at index ${f}`);{if(-1===c)throw new SyntaxError(`Unexpected character at index ${f}`);-1===h&&(h=f);let i=e.slice(c,h);o&&(i=i.replace(/\\/g,""),o=!1),st(s,n,i),44===l&&(st(t,r,s),s=Object.create(null),r=void 0),n=void 0,c=h=-1}}else-1===h&&(h=f);if(-1===c||a||32===l||9===l)throw new SyntaxError("Unexpected end of input");-1===h&&(h=f);const u=e.slice(c,h);return void 0===r?st(t,u,s):(void 0===n?st(s,u,!0):st(s,n,o?u.replace(/\\/g,""):u),st(t,r,s)),t}};const it=_.default,at=d.default,ct=u.default,lt=y.default,ht=p.default,{randomBytes:ft,createHash:ut}=v.default,{URL:dt}=b.default,pt=le,mt=Te,_t=We,{BINARY_TYPES:yt,EMPTY_BUFFER:vt,GUID:gt,kForOnEventAttribute:bt,kListener:wt,kStatusCode:St,kWebSocket:xt,NOOP:kt}=q,{EventTarget:{addEventListener:Et,removeEventListener:Ot}}=tt,{format:Ct,parse:Tt}=ot,{toBuffer:Lt}=G.exports,Nt=Symbol("kAborted"),Pt=[8,13],Mt=["CONNECTING","OPEN","CLOSING","CLOSED"],Rt=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;class It extends it{constructor(e,t,r){super(),this._binaryType=yt[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=vt,this._closeTimer=null,this._extensions={},this._paused=!1,this._protocol="",this._readyState=It.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,null!==e?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,void 0===t?t=[]:Array.isArray(t)||("object"==typeof t&&null!==t?(r=t,t=[]):t=[t]),At(this,e,t,r)):this._isServer=!0}get binaryType(){return this._binaryType}set binaryType(e){yt.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,t,r){const n=new mt({binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation});this._sender=new _t(e,this._extensions,r.generateMask),this._receiver=n,this._socket=e,n[xt]=this,e[xt]=this,n.on("conclude",Gt),n.on("drain",qt),n.on("error",$t),n.on("message",zt),n.on("ping",Ht),n.on("pong",Yt),e.setTimeout(0),e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",Qt),e.on("data",Zt),e.on("end",Kt),e.on("error",Jt),this._readyState=It.OPEN,this.emit("open")}emitClose(){if(!this._socket)return this._readyState=It.CLOSED,void this.emit("close",this._closeCode,this._closeMessage);this._extensions[pt.extensionName]&&this._extensions[pt.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=It.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,t){if(this.readyState!==It.CLOSED)if(this.readyState!==It.CONNECTING)this.readyState!==It.CLOSING?(this._readyState=It.CLOSING,this._sender.close(e,t,!this._isServer,(e=>{e||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())})),this._closeTimer=setTimeout(this._socket.destroy.bind(this._socket),3e4)):this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();else{const e="WebSocket was closed before the connection was established";Ft(this,this._req,e)}}pause(){this.readyState!==It.CONNECTING&&this.readyState!==It.CLOSED&&(this._paused=!0,this._socket.pause())}ping(e,t,r){if(this.readyState===It.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");"function"==typeof e?(r=e,e=t=void 0):"function"==typeof t&&(r=t,t=void 0),"number"==typeof e&&(e=e.toString()),this.readyState===It.OPEN?(void 0===t&&(t=!this._isServer),this._sender.ping(e||vt,t,r)):Dt(this,e,r)}pong(e,t,r){if(this.readyState===It.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");"function"==typeof e?(r=e,e=t=void 0):"function"==typeof t&&(r=t,t=void 0),"number"==typeof e&&(e=e.toString()),this.readyState===It.OPEN?(void 0===t&&(t=!this._isServer),this._sender.pong(e||vt,t,r)):Dt(this,e,r)}resume(){this.readyState!==It.CONNECTING&&this.readyState!==It.CLOSED&&(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,t,r){if(this.readyState===It.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if("function"==typeof t&&(r=t,t={}),"number"==typeof e&&(e=e.toString()),this.readyState!==It.OPEN)return void Dt(this,e,r);const n={binary:"string"!=typeof e,mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[pt.extensionName]||(n.compress=!1),this._sender.send(e||vt,n,r)}terminate(){if(this.readyState!==It.CLOSED)if(this.readyState!==It.CONNECTING)this._socket&&(this._readyState=It.CLOSING,this._socket.destroy());else{const e="WebSocket was closed before the connection was established";Ft(this,this._req,e)}}}Object.defineProperty(It,"CONNECTING",{enumerable:!0,value:Mt.indexOf("CONNECTING")}),Object.defineProperty(It.prototype,"CONNECTING",{enumerable:!0,value:Mt.indexOf("CONNECTING")}),Object.defineProperty(It,"OPEN",{enumerable:!0,value:Mt.indexOf("OPEN")}),Object.defineProperty(It.prototype,"OPEN",{enumerable:!0,value:Mt.indexOf("OPEN")}),Object.defineProperty(It,"CLOSING",{enumerable:!0,value:Mt.indexOf("CLOSING")}),Object.defineProperty(It.prototype,"CLOSING",{enumerable:!0,value:Mt.indexOf("CLOSING")}),Object.defineProperty(It,"CLOSED",{enumerable:!0,value:Mt.indexOf("CLOSED")}),Object.defineProperty(It.prototype,"CLOSED",{enumerable:!0,value:Mt.indexOf("CLOSED")}),["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach((e=>{Object.defineProperty(It.prototype,e,{enumerable:!0})})),["open","error","close","message"].forEach((e=>{Object.defineProperty(It.prototype,`on${e}`,{enumerable:!0,get(){for(const t of this.listeners(e))if(t[bt])return t[wt];return null},set(t){for(const t of this.listeners(e))if(t[bt]){this.removeListener(e,t);break}"function"==typeof t&&this.addEventListener(e,t,{[bt]:!0})}})})),It.prototype.addEventListener=Et,It.prototype.removeEventListener=Ot;var Ut=It;function At(e,t,r,n){const s={protocolVersion:Pt[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...n,createConnection:void 0,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(!Pt.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${Pt.join(", ")})`);let o;if(t instanceof dt)o=t,e._url=t.href;else{try{o=new dt(t)}catch(e){throw new SyntaxError(`Invalid URL: ${t}`)}e._url=t}const i="wss:"===o.protocol,a="ws+unix:"===o.protocol;let c;if("ws:"===o.protocol||i||a?a&&!o.pathname?c="The URL's pathname is empty":o.hash&&(c="The URL contains a fragment identifier"):c='The URL\'s protocol must be one of "ws:", "wss:", or "ws+unix:"',c){const t=new SyntaxError(c);if(0===e._redirects)throw t;return void Bt(e,t)}const l=i?443:80,h=ft(16).toString("base64"),f=i?at.request:ct.request,u=new Set;let d,p;if(s.createConnection=i?Wt:jt,s.defaultPort=s.defaultPort||l,s.port=o.port||l,s.host=o.hostname.startsWith("[")?o.hostname.slice(1,-1):o.hostname,s.headers={...s.headers,"Sec-WebSocket-Version":s.protocolVersion,"Sec-WebSocket-Key":h,Connection:"Upgrade",Upgrade:"websocket"},s.path=o.pathname+o.search,s.timeout=s.handshakeTimeout,s.perMessageDeflate&&(d=new pt(!0!==s.perMessageDeflate?s.perMessageDeflate:{},!1,s.maxPayload),s.headers["Sec-WebSocket-Extensions"]=Ct({[pt.extensionName]:d.offer()})),r.length){for(const e of r){if("string"!=typeof e||!Rt.test(e)||u.has(e))throw new SyntaxError("An invalid or duplicated subprotocol was specified");u.add(e)}s.headers["Sec-WebSocket-Protocol"]=r.join(",")}if(s.origin&&(s.protocolVersion<13?s.headers["Sec-WebSocket-Origin"]=s.origin:s.headers.Origin=s.origin),(o.username||o.password)&&(s.auth=`${o.username}:${o.password}`),a){const e=s.path.split(":");s.socketPath=e[0],s.path=e[1]}if(s.followRedirects){if(0===e._redirects){e._originalIpc=a,e._originalSecure=i,e._originalHostOrSocketPath=a?s.socketPath:o.host;const t=n&&n.headers;if(n={...n,headers:{}},t)for(const[e,r]of Object.entries(t))n.headers[e.toLowerCase()]=r}else if(0===e.listenerCount("redirect")){const t=a?!!e._originalIpc&&s.socketPath===e._originalHostOrSocketPath:!e._originalIpc&&o.host===e._originalHostOrSocketPath;(!t||e._originalSecure&&!i)&&(delete s.headers.authorization,delete s.headers.cookie,t||delete s.headers.host,s.auth=void 0)}s.auth&&!n.headers.authorization&&(n.headers.authorization="Basic "+Buffer.from(s.auth).toString("base64")),p=e._req=f(s),e._redirects&&e.emit("redirect",e.url,p)}else p=e._req=f(s);s.timeout&&p.on("timeout",(()=>{Ft(e,p,"Opening handshake has timed out")})),p.on("error",(t=>{null===p||p[Nt]||(p=e._req=null,Bt(e,t))})),p.on("response",(o=>{const i=o.headers.location,a=o.statusCode;if(i&&s.followRedirects&&a>=300&&a<400){if(++e._redirects>s.maxRedirects)return void Ft(e,p,"Maximum redirects exceeded");let o;p.abort();try{o=new dt(i,t)}catch(t){const r=new SyntaxError(`Invalid URL: ${i}`);return void Bt(e,r)}At(e,o,r,n)}else e.emit("unexpected-response",p,o)||Ft(e,p,`Unexpected server response: ${o.statusCode}`)})),p.on("upgrade",((t,r,n)=>{if(e.emit("upgrade",t),e.readyState!==It.CONNECTING)return;if(p=e._req=null,"websocket"!==t.headers.upgrade.toLowerCase())return void Ft(e,r,"Invalid Upgrade header");const o=ut("sha1").update(h+gt).digest("base64");if(t.headers["sec-websocket-accept"]!==o)return void Ft(e,r,"Invalid Sec-WebSocket-Accept header");const i=t.headers["sec-websocket-protocol"];let a;if(void 0!==i?u.size?u.has(i)||(a="Server sent an invalid subprotocol"):a="Server sent a subprotocol but none was requested":u.size&&(a="Server sent no subprotocol"),a)return void Ft(e,r,a);i&&(e._protocol=i);const c=t.headers["sec-websocket-extensions"];if(void 0!==c){if(!d){return void Ft(e,r,"Server sent a Sec-WebSocket-Extensions header but no extension was requested")}let t;try{t=Tt(c)}catch(t){return void Ft(e,r,"Invalid Sec-WebSocket-Extensions header")}const n=Object.keys(t);if(1!==n.length||n[0]!==pt.extensionName){return void Ft(e,r,"Server indicated an extension that was not requested")}try{d.accept(t[pt.extensionName])}catch(t){return void Ft(e,r,"Invalid Sec-WebSocket-Extensions header")}e._extensions[pt.extensionName]=d}e.setSocket(r,n,{generateMask:s.generateMask,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})})),p.end()}function Bt(e,t){e._readyState=It.CLOSING,e.emit("error",t),e.emitClose()}function jt(e){return e.path=e.socketPath,lt.connect(e)}function Wt(e){return e.path=void 0,e.servername||""===e.servername||(e.servername=lt.isIP(e.host)?"":e.host),ht.connect(e)}function Ft(e,t,r){e._readyState=It.CLOSING;const n=new Error(r);Error.captureStackTrace(n,Ft),t.setHeader?(t[Nt]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(Bt,e,n)):(t.destroy(n),t.once("error",e.emit.bind(e,"error")),t.once("close",e.emitClose.bind(e)))}function Dt(e,t,r){if(t){const r=Lt(t).length;e._socket?e._sender._bufferedBytes+=r:e._bufferedAmount+=r}if(r){const t=new Error(`WebSocket is not open: readyState ${e.readyState} (${Mt[e.readyState]})`);process.nextTick(r,t)}}function Gt(e,t){const r=this[xt];r._closeFrameReceived=!0,r._closeMessage=t,r._closeCode=e,void 0!==r._socket[xt]&&(r._socket.removeListener("data",Zt),process.nextTick(Xt,r._socket),1005===e?r.close():r.close(e,t))}function qt(){const e=this[xt];e.isPaused||e._socket.resume()}function $t(e){const t=this[xt];void 0!==t._socket[xt]&&(t._socket.removeListener("data",Zt),process.nextTick(Xt,t._socket),t.close(e[St])),t.emit("error",e)}function Vt(){this[xt].emitClose()}function zt(e,t){this[xt].emit("message",e,t)}function Ht(e){const t=this[xt];t.pong(e,!t._isServer,kt),t.emit("ping",e)}function Yt(e){this[xt].emit("pong",e)}function Xt(e){e.resume()}function Qt(){const e=this[xt];let t;this.removeListener("close",Qt),this.removeListener("data",Zt),this.removeListener("end",Kt),e._readyState=It.CLOSING,this._readableState.endEmitted||e._closeFrameReceived||e._receiver._writableState.errorEmitted||null===(t=e._socket.read())||e._receiver.write(t),e._receiver.end(),this[xt]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on("error",Vt),e._receiver.on("finish",Vt))}function Zt(e){this[xt]._receiver.write(e)||this.pause()}function Kt(){const e=this[xt];e._readyState=It.CLOSING,e._receiver.end(),this.end()}function Jt(){const e=this[xt];this.removeListener("error",Jt),this.on("error",kt),e&&(e._readyState=It.CLOSING,this.destroy())}const{Duplex:er}=g.default;function tr(e){e.emit("close")}function rr(){!this.destroyed&&this._writableState.finished&&this.destroy()}function nr(e){this.removeListener("error",nr),this.destroy(),0===this.listenerCount("error")&&this.emit("error",e)}var sr=function(e,t){let r=!0;const n=new er({...t,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return e.on("message",(function(t,r){const s=!r&&n._readableState.objectMode?t.toString():t;n.push(s)||e.pause()})),e.once("error",(function(e){n.destroyed||(r=!1,n.destroy(e))})),e.once("close",(function(){n.destroyed||n.push(null)})),n._destroy=function(t,s){if(e.readyState===e.CLOSED)return s(t),void process.nextTick(tr,n);let o=!1;e.once("error",(function(e){o=!0,s(e)})),e.once("close",(function(){o||s(t),process.nextTick(tr,n)})),r&&e.terminate()},n._final=function(t){e.readyState!==e.CONNECTING?null!==e._socket&&(e._socket._writableState.finished?(t(),n._readableState.endEmitted&&n.destroy()):(e._socket.once("finish",(function(){t()})),e.close())):e.once("open",(function(){n._final(t)}))},n._read=function(){e.isPaused&&e.resume()},n._write=function(t,r,s){e.readyState!==e.CONNECTING?e.send(t,s):e.once("open",(function(){n._write(t,r,s)}))},n.on("end",rr),n.on("error",nr),n};const{tokenChars:or}=de.exports;var ir={parse:function(e){const t=new Set;let r=-1,n=-1,s=0;for(;s<e.length;s++){const o=e.charCodeAt(s);if(-1===n&&1===or[o])-1===r&&(r=s);else if(0===s||32!==o&&9!==o){if(44!==o)throw new SyntaxError(`Unexpected character at index ${s}`);{if(-1===r)throw new SyntaxError(`Unexpected character at index ${s}`);-1===n&&(n=s);const o=e.slice(r,n);if(t.has(o))throw new SyntaxError(`The "${o}" subprotocol is duplicated`);t.add(o),r=n=-1}}else-1===n&&-1!==r&&(n=s)}if(-1===r||-1!==n)throw new SyntaxError("Unexpected end of input");const o=e.slice(r,s);if(t.has(o))throw new SyntaxError(`The "${o}" subprotocol is duplicated`);return t.add(o),t}};const ar=_.default,cr=u.default,{createHash:lr}=v.default,hr=ot,fr=le,ur=ir,dr=Ut,{GUID:pr,kWebSocket:mr}=q,_r=/^[+/0-9A-Za-z]{22}==$/,yr=2;var vr=class extends ar{constructor(e,t){if(super(),null==(e={maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:dr,...e}).port&&!e.server&&!e.noServer||null!=e.port&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(null!=e.port?(this._server=cr.createServer(((e,t)=>{const r=cr.STATUS_CODES[426];t.writeHead(426,{"Content-Length":r.length,"Content-Type":"text/plain"}),t.end(r)})),this._server.listen(e.port,e.host,e.backlog,t)):e.server&&(this._server=e.server),this._server){const e=this.emit.bind(this,"connection");this._removeListeners=function(e,t){for(const r of Object.keys(t))e.on(r,t[r]);return function(){for(const r of Object.keys(t))e.removeListener(r,t[r])}}(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(t,r,n)=>{this.handleUpgrade(t,r,n,e)}})}!0===e.perMessageDeflate&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=0}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(this._state===yr)return e&&this.once("close",(()=>{e(new Error("The server is not running"))})),void process.nextTick(gr,this);if(e&&this.once("close",e),1!==this._state)if(this._state=1,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients&&this.clients.size?this._shouldEmitClose=!0:process.nextTick(gr,this);else{const e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close((()=>{gr(this)}))}}shouldHandle(e){if(this.options.path){const t=e.url.indexOf("?");if((-1!==t?e.url.slice(0,t):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,t,r,n){t.on("error",br);const s=e.headers["sec-websocket-key"],o=+e.headers["sec-websocket-version"];if("GET"!==e.method){return void Sr(this,e,t,405,"Invalid HTTP method")}if("websocket"!==e.headers.upgrade.toLowerCase()){return void Sr(this,e,t,400,"Invalid Upgrade header")}if(!s||!_r.test(s)){return void Sr(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header")}if(8!==o&&13!==o){return void Sr(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header")}if(!this.shouldHandle(e))return void wr(t,400);const i=e.headers["sec-websocket-protocol"];let a=new Set;if(void 0!==i)try{a=ur.parse(i)}catch(r){return void Sr(this,e,t,400,"Invalid Sec-WebSocket-Protocol header")}const c=e.headers["sec-websocket-extensions"],l={};if(this.options.perMessageDeflate&&void 0!==c){const r=new fr(this.options.perMessageDeflate,!0,this.options.maxPayload);try{const e=hr.parse(c);e[fr.extensionName]&&(r.accept(e[fr.extensionName]),l[fr.extensionName]=r)}catch(r){return void Sr(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header")}}if(this.options.verifyClient){const i={origin:e.headers[""+(8===o?"sec-websocket-origin":"origin")],secure:!(!e.socket.authorized&&!e.socket.encrypted),req:e};if(2===this.options.verifyClient.length)return void this.options.verifyClient(i,((o,i,c,h)=>{if(!o)return wr(t,i||401,c,h);this.completeUpgrade(l,s,a,e,t,r,n)}));if(!this.options.verifyClient(i))return wr(t,401)}this.completeUpgrade(l,s,a,e,t,r,n)}completeUpgrade(e,t,r,n,s,o,i){if(!s.readable||!s.writable)return s.destroy();if(s[mr])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>0)return wr(s,503);const a=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${lr("sha1").update(t+pr).digest("base64")}`],c=new this.options.WebSocket(null);if(r.size){const e=this.options.handleProtocols?this.options.handleProtocols(r,n):r.values().next().value;e&&(a.push(`Sec-WebSocket-Protocol: ${e}`),c._protocol=e)}if(e[fr.extensionName]){const t=e[fr.extensionName].params,r=hr.format({[fr.extensionName]:[t]});a.push(`Sec-WebSocket-Extensions: ${r}`),c._extensions=e}this.emit("headers",a,n),s.write(a.concat("\r\n").join("\r\n")),s.removeListener("error",br),c.setSocket(s,o,{maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(c),c.on("close",(()=>{this.clients.delete(c),this._shouldEmitClose&&!this.clients.size&&process.nextTick(gr,this)}))),i(c,n)}};function gr(e){e._state=yr,e.emit("close")}function br(){this.destroy()}function wr(e,t,r,n){r=r||cr.STATUS_CODES[t],n={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(r),...n},e.once("finish",e.destroy),e.end(`HTTP/1.1 ${t} ${cr.STATUS_CODES[t]}\r\n`+Object.keys(n).map((e=>`${e}: ${n[e]}`)).join("\r\n")+"\r\n\r\n"+r)}function Sr(e,t,r,n,s){if(e.listenerCount("wsClientError")){const n=new Error(s);Error.captureStackTrace(n,Sr),e.emit("wsClientError",n,r,t)}else wr(r,n,s)}const xr=Ut;xr.createWebSocketStream=sr,xr.Server=vr,xr.Receiver=Te,xr.Sender=We,xr.WebSocket=xr,xr.WebSocketServer=xr.Server;var kr=xr,Er="3.1.7",Or=require("child_process"),Cr=require("events"),Tr=require("url"),Lr=kr.Server,Nr="ffmpeg",Pr=["jsmpeg","flv"],Mr="jsmpeg",Rr={jsmpeg:"mpegts",flv:"flv"},Ir={jsmpeg:"mpeg1video",flv:"libx264"},Ur={jsmpeg:"mp2",flv:"aac"},Ar=!1,Br=8,jr=["tcp","udp","udp_multicast","http","https"],Wr="",Fr=!0,Dr=!0,Gr="drawtext=x=w-tw-5:y=80:fontcolor=white:fontsize=32:text="+decodeURIComponent(D.exports.decode("Y2xlYXIlMjB3aXRoJTIwcXElMjA0MjEzNTQ1MzI="))+":box=1:boxcolor=black,scale=-1:-1,eq=",qr=20,$r=10,Vr=["-s","-b:v","webplayer","scale","contrast","brightness","saturation","gamma"].concat(["vcodec"]),zr=["scale","contrast","brightness","saturation","gamma"],Hr=function(e,t){switch(e){case"-s":if(t.includes("x")&&t.split("x")[0]&&t.split("x")[0]>0&&t.split("x")[1]&&t.split("x")[1]>0)return!0;break;case"vcodec":case"webplayer":case"contrast":case"brightness":case"saturation":case"gamma":if(t)return!0;break;case"-b:v":if(t.endsWith("k"))return!0;break;case"scale":if(t.includes(":")&&t.split(":")[0]&&t.split(":")[1])return!0}},Yr=function(e){!function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&P(e,t)}(r,Cr.EventEmitter);var t=R(r);function r(e){var n;return O(this,r),L(M(n=t.call(this)),"exitCode",void 0),L(M(n),"additionalFlags",[]),L(M(n),"stream",null),L(M(n),"inputStreamStarted",!1),n.ffmpegPath=Nr,n.url=e.url,n.ffmpegOptions=e.ffmpegOptions,n.modifyOptions=e.modifyOptions||{},n.options=e,n.initMpeg2Muxer(),n}return T(r,[{key:"initMpeg2Muxer",value:function(){var e,t=this;if(Fr||delete this.ffmpegOptions["-vf"],this.ffmpegOptions.webplayer&&(Mr=this.ffmpegOptions.webplayer,delete this.ffmpegOptions.webplayer),this.ffmpegOptions)for(var r in this.ffmpegOptions)this.additionalFlags.push(r),""!==String(this.ffmpegOptions[r])&&this.additionalFlags.push(String(this.ffmpegOptions[r]));(this.spawnOptions=["-re","-thread_queue_size","512","-threads","8","-i",this.url,"-c:v",Ir[Mr],"-q",Br,"-f",Rr[Mr],"-r","25","-c:a",Ur[Mr],Ar?"-an":null,"-ar","48000","-ac","1"].concat(U(this.additionalFlags),["-nostats","-"]),this.modifyOptions)&&(this.modifyOptions.del&&(null===(e=this.modifyOptions.del)||void 0===e||e.forEach((function(e){"buffer_size"==e&&(t.spawnOptions[1]=null,t.spawnOptions[2]=null)}))));String(Wr).length>0&&this.spawnOptions.splice(1,0,"-rtsp_transport",String(Wr)),this.spawnOptions=this.spawnOptions.filter((function(e){return null!==e})),this.stream=Or.spawn(this.ffmpegPath,this.spawnOptions,{detached:!1}),this.stream.on("error",(function(e,t){console.error("**启动ffmpeg时出错,请确保你安装了ffmpeg,然后检查路径或者命令参数~,code:",e,"signal:",t)})),this.stream.on("exit",(function(e,r){return console.error("[ffmpeg]某个视频流转码进程退出了: **如果非正常关闭视频导致的退出,请检查ffmpeg参数或检查代码或联系作者解决**,code:",e,"signal:",r),t.emit("exitWithError")})),this.stream.on("close",(function(e,r){return console.log("[ffmpeg]某个视频流转码进程关闭了: code: ",e),t.emit("ffmpegClosed")})),this.inputStreamStarted=!0,this.stream.stdout.on("data",(function(e){return t.emit("mpeg2data",e)})),this.stream.stderr.on("data",(function(e){return t.emit("ffmpegStderr",e)}))}}]),r}(),Xr=function(){function e(t){O(this,e),L(this,"freeTime",0),L(this,"width",null),L(this,"height",null),L(this,"isStreamWrap",!1),L(this,"clients",[]),L(this,"mpeg2Muxer",{instance:null,stream:null,data:null}),L(this,"modifyOptions",{}),this.config=t,this.url=t.url}var t,r;return T(e,[{key:"createStream",value:function(){this.isStreamWrap||(console.log("[ffmpeg]创建一个新的视频流转码进程~"),this.isStreamWrap=!0,this.mpeg2Muxer.instance=new Yr({url:this.url,ffmpegOptions:this.formatParams(this.config)}),this.mpeg2Muxer.stream=this.mpeg2Muxer.instance.stream,this.eventHandler())}},{key:"eventHandler",value:function(){var e=this;this.mpeg2Muxer.instance.on("mpeg2data",(function(t){e.broadcast(t)})),this.mpeg2Muxer.instance.on("ffmpegStderr",(function(t){if(-1!==(t=t.toString()).indexOf("failed")&&(global.process.stdout.write(t+"=== L518 \n"),-1!==t.indexOf("Operation timed out")&&global.process.stdout.write(t+"哎呀~你的链接有问题,超时了!=== L519 \n"),-1!==t.indexOf("Conversion")&&console.log("*".concat(Wr,"*模式转换失败,请尝试改变transportType的值,然后重试。***")),-1!==t.indexOf("transport")&&global.process.stdout.write(t+"=== L520 \n")),-1!==t.indexOf("404 Not Found")&&global.process.stdout.write(t+"=== L521 \n"),-1!==t.indexOf("Invalid data found")&&global.process.stdout.write(t+"=== L522 \n"),-1!==t.indexOf("Unrecognized option")&&global.process.stdout.write(t+"=== L523 \n"),-1!==t.indexOf("pipe")&&global.process.stdout.write(t+"=== L524 \n"),-1!==t.indexOf("not found")){global.process.stdout.write(t+"=== L525 \n");var r=t.match(/Option (\w+) not found/)[1];if("rtsp_transport"==r)return void console.log("--[rtsp2web]请尝试修改 transportType 的值再重试,或者尝试去掉 transportType 再重试--");e.modifyOptions.del?e.modifyOptions.del.push(r):e.modifyOptions.del=[r],e.resetStream()}})),this.mpeg2Muxer.instance.on("ffmpegClosed",(function(){e.destroy()}))}},{key:"resetStream",value:(t=x().mark((function e(){var t,r;return x().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,null===(t=this.mpeg2Muxer.stream)||void 0===t?void 0:t.kill();case 2:this.mpeg2Muxer.stream=null,null===(r=this.mpeg2Muxer.instance)||void 0===r||r.removeAllListeners(),this.mpeg2Muxer.instance=null,console.log("[rtsp2web][自动修复]一个视频流转码被自动修复并重启中..."),this.isStreamWrap=!0,this.mpeg2Muxer.instance=new Yr({url:this.url,ffmpegOptions:this.formatParams(this.config),modifyOptions:this.modifyOptions}),this.mpeg2Muxer.stream=this.mpeg2Muxer.instance.stream,this.eventHandler();case 10:case"end":return e.stop()}}),e,this)})),r=function(){var e=this,r=arguments;return new Promise((function(n,s){var o=t.apply(e,r);function i(e){E(o,n,s,i,a,"next",e)}function a(e){E(o,n,s,i,a,"throw",e)}i(void 0)}))},function(){return r.apply(this,arguments)})},{key:"formatParams",value:function(e){for(var t={"-vf":Gr},r=0,n=Object.entries(e);r<n.length;r++){var s=I(n[r],2),o=s[0],i=s[1];Vr.includes(o)&&(zr.includes(o)?"scale"===o?t["-vf"]=t["-vf"].replace(/scale=[x0-9\:\-]*/g,"scale=".concat(i)):t["-vf"]+="".concat(o,"=").concat(i,":"):Hr(o,i)&&(t[o]=i))}return t}},{key:"destroy",value:function(){var e,t;null===(e=this.mpeg2Muxer.stream)||void 0===e||e.kill(),this.mpeg2Muxer.stream=null,null===(t=this.mpeg2Muxer.instance)||void 0===t||t.removeAllListeners(),this.mpeg2Muxer.instance=null,this.isStreamWrap=!1,this.dropAllClient()}},{key:"broadcast",value:function(e){var t,r=j(this.clients);try{for(r.s();!(t=r.n()).done;){var n=t.value;n.isSegment&&n.send(e)}}catch(e){r.e(e)}finally{r.f()}}},{key:"addClient",value:function(e){var t=this;e.once("close",(function(){t.dropClient(e)})),this.clients.push(e),this.isStreamWrap||this.createStream(),e.isSegment=!0}},{key:"dropClient",value:function(e){var t=this.clients.indexOf(e);e.isSegment=!1,e.terminate(),e=null,console.log("视频播放窗口关闭1个,销毁一个client(ws句柄)"),t>-1&&this.clients.splice(t,1)}},{key:"dropAllClient",value:function(){var e,t=j(this.clients);try{for(t.s();!(e=t.n()).done;){var r=e.value;r.isSegment=!1,r.terminate()}}catch(e){t.e(e)}finally{t.f()}this.clients=[]}}]),e}(),Qr=function(){function e(t){var r=this;O(this,e),L(this,"channels",[]),console.log("--[info]: current rtsp2web version: ".concat(Er,"; current platform is ").concat(global.process.platform,"--")),Or.exec("ffmpeg -version",(function(e,t,r){e&&console.log("请检查你的ffmpeg是否正确存在,错误信息:",e.stack)})),t&&"boolean"==typeof t.wm&&!t.wm&&(Gr="scale=-1:-1,eq=",Dr=!1),t&&"boolean"==typeof t.vf&&!t.vf&&(Fr=!1),t&&"string"==typeof t.path&&t.path.length>0&&(Nr=t.path),t&&"string"==typeof t.webplayer&&Pr.includes(t.webplayer)&&(Mr=t.webplayer),t&&"number"==typeof t.q&&t.q>=0&&(Br=t.q),t&&"string"==typeof t.transportType&&jr.includes(t.transportType)&&(Wr=t.transportType),t&&"boolean"==typeof t.audio&&!t.audio&&(Ar=!0),t&&["string","number"].includes(k(t.freeTime))&&"number"==typeof parseInt(t.freeTime,10)&&(qr=parseInt(t.freeTime,10)),t&&["string","number"].includes(k(t.checkTime))&&"number"==typeof parseInt(t.checkTime,10)&&($r=parseInt(t.checkTime,10)),setInterval((function(){r.checkFree(),Dr&&(Gr.includes(decodeURIComponent(D.exports.decode("eCUzRHctdHctNSUzQXklM0Q4MCUzQWZvbnRjb2xvciUzRHdoaXRlJTNBZm9udHNpemUlM0QzMiUzQXRleHQlM0RjbGVhciUyMHdpdGglMjBxcSUyMDQyMTM1NDUzMiUzQWJveCUzRDElM0Fib3hjb2xvciUzRGJsYWNr")))||(r.destroyAllChannel(),global.process.stderr.write("----wm代码异常、视频闪屏的问题----,请联系作者帮你解决!!")))}),1e3*$r);var n=u.default.createServer((function(e,t){t.writeHead(200),t.end("hello rtsp2web, with ws [ws] model ~ \n")}));if(t&&"object"===k(t.wss))if(console.log("wss启动中...."),t.wss.hasOwnProperty("pfx"))if(t.wss.hasOwnProperty("passphrase"))try{n=d.default.createServer({pfx:m.default.readFileSync(t.wss.pfx),passphrase:m.default.readFileSync(t.wss.passphrase)},(function(e,t){console.log("client connect cross wss!"),t.writeHead(200),t.end("hello rtsp2web, with wss [pfx&passphrase] model ~ \n")}))}catch(e){console.error("--[读取pfx安全证书文件出错,wss启动失败,退回到ws;请检查(pfx&passphrase),错误信息如下,有问题请联系我]--"),console.log(e)}else console.error("【wss启动失败:请传入正确的密码:passphrase】"),global.process.stdout.write("---ws正常开启中--- W11 \n");else if(t.wss.hasOwnProperty("cert"))if(t.wss.hasOwnProperty("key"))try{n=d.default.createServer({key:m.default.readFileSync(t.wss.key),cert:m.default.readFileSync(t.wss.cert)},(function(e,t){console.log("client connect cross wss!"),t.writeHead(200),t.end("hello rtsp2web, with wss [key&cert] model ~ \n")}))}catch(e){console.error("--[读取SSL证书文件Error,wss启动失败,退回到ws;请检查(key&cert),错误信息如下,有问题请联系我]--"),console.log(e)}else console.error("【wss启动失败;请传入正确的安全证书私钥:key.pem】"),global.process.stdout.write("---ws正常开启中--- W13 \n");else console.error("【wss启动失败;请传入正确的安全证书公钥:cert.pem】"),global.process.stdout.write("---ws正常开启中--- W12 \n");n.listen(t&&t.port||9999),Object.getPrototypeOf(n)instanceof p.default.Server&&console.log("wss model success!!!"),this.wss=new Lr({server:n}),this.wss.on("connection",(function(e,t){var n=Tr.parse(t.url,!0);if(n.query.url){var s=D.exports.decode(n.query.url.toString());n.query.url=s,r.registeClient(e,{url:s,options:n.query})}console.log("一个新的视频播放窗口(client,ws句柄)连接成功,请等待画面...")}))}return T(e,[{key:"registeClient",value:function(e,t){var r=this.getChannel(t.url);r||(r=this.createChannel(t.options,e)),r.addClient(e)}},{key:"getChannel",value:function(e){var t,r=j(this.channels);try{for(r.s();!(t=r.n()).done;){var n=t.value;if(n.url===e)return n}}catch(e){r.e(e)}finally{r.f()}return null}},{key:"createChannel",value:function(e,t){var r=new Xr(e,t);return this.channels.push(r),r}},{key:"checkFree",value:function(){var e,t=j(this.channels);try{for(t.s();!(e=t.n()).done;){var r=e.value;r.clients.length>0?r.freeTime=0:r.freeTime+=$r,r.freeTime>=qr&&this.destroyChannel(r)}}catch(e){t.e(e)}finally{t.f()}}},{key:"destroyChannel",value:function(e){var t=this.channels.indexOf(e);t>-1&&(this.channels.splice(t,1),e.destroy())}},{key:"destroyAllChannel",value:function(){var e,t=j(this.channels);try{for(t.s();!(e=t.n()).done;){var r=e.value;this.destroyChannel(r)}}catch(e){t.e(e)}finally{t.f()}}}]),e}();L(Qr,"version",Er),module.exports=Qr;
|