rtsp2web 2.4.5 → 2.4.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 CHANGED
@@ -114,7 +114,7 @@ new RTSP2web({
114
114
  | :-------: | :----------------------------------------------------------------------------------------------------------------------------: |
115
115
  | -s | 视频分辨率大小,不传即表示与源视频大小一致<br> 传值示例: 1920x1080、1280x720、640x360 <br> 降低分辨率会降低清晰度 |
116
116
  | -b:v | 释义:码率,默认可以不设置,那就是使用源码率<br>传值示例:2000k、100k、1k<br>码率调小,这样其实也间接让文件变小了<br>码率调小,画质有可能会降低|
117
- | scale | 缩放;间接的,也能调整视频的分辨率;<br> 默认值: -1:-1;即与视频源大小保持一致;<br>功能与 -s 参数相似;但是可以只传一个宽度或者高度,另一个参数用 -1 表示<br>如: 1280:-1、-1:360,视频将会自适应现实<br>降低分辨率会降低清晰度 |
117
+ | scale | 缩放;间接的,也能调整视频的分辨率;<br> 默认值: -1:-1;即与视频源大小保持一致;<br>功能与 -s 参数相似;但是可以只传一个宽度或者高度,另一个参数用 -1 表示<br>如: 1280:-1、-1:360,视频将会自适应显示<br>降低分辨率会降低清晰度 |
118
118
  | vcodec/codec:v/-c:v | 释义:视频编解码方式;<br>请确保你了解该参数的意义,默认可以不传 |
119
119
  | contrast | 释义:对比度,亮的地方更亮,暗的地方更暗。<br>取值范围[-100.0, 100.0],默认值为0。建议不调整,或者在[-2.0, 2.0]范围内进行小的调整 |
120
120
  | brightness | 释义:亮度,如果觉得视频有点暗,可以进行小的调整。<br>取值范围: [-1.0, 1.0],默认值为0。|
@@ -143,6 +143,8 @@ wechat: miracle421354532
143
143
  `rtsp2web` 支持直接开启 `wss` 协议;
144
144
 
145
145
  # change log [更新日志]
146
+ 【2023-02-20】默认支持播放声音;断网重连??
147
+
146
148
  【2023-02-15】支持升级为 `wss` 了,默认是 `ws`。基于 `https` 的站点不能请求 `ws`,要升级为 `wss`。
147
149
  > *你也可以用其他工具或者服务器来反向代理一把。*
148
150
 
package/dist/rtsp2web.js CHANGED
@@ -1,11 +1,10 @@
1
1
  /*!
2
- * rtsp2web v2.4.5
2
+ * rtsp2web v2.4.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("fs"),s=require("events"),n=require("net"),i=require("tls"),o=require("crypto"),a=require("stream"),c=require("url"),l=require("zlib");function h(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var f=h(e),d=h(t),u=h(r),p=h(s),_=h(n),m=h(i),y=h(o),v=h(a),g=h(c),b=h(l);function S(e){return S="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},S(e)}function w(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function k(e,t){for(var r=0;r<t.length;r++){var s=t[r];s.enumerable=s.enumerable||!1,s.configurable=!0,"value"in s&&(s.writable=!0),Object.defineProperty(e,s.key,s)}}function x(e,t,r){return t&&k(e.prototype,t),r&&k(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function E(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function O(e){return O=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)},O(e)}function C(e,t){return C=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e},C(e,t)}function T(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function N(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 T(e)}function L(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,s=O(e);if(t){var n=O(this).constructor;r=Reflect.construct(s,arguments,n)}else r=s.apply(this,arguments);return N(this,r)}}function P(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)return;var s,n,i=[],o=!0,a=!1;try{for(r=r.call(e);!(o=(s=r.next()).done)&&(i.push(s.value),!t||i.length!==t);o=!0);}catch(e){a=!0,n=e}finally{try{o||null==r.return||r.return()}finally{if(a)throw n}}return i}(e,t)||B(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 R(e){return function(e){if(Array.isArray(e))return A(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||B(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 B(e,t){if(e){if("string"==typeof e)return A(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)?A(e,t):void 0}}function A(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,s=new Array(t);r<t;r++)s[r]=e[r];return s}function I(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=B(e))||t&&e&&"number"==typeof e.length){r&&(e=r);var s=0,n=function(){};return{s:n,n:function(){return s>=e.length?{done:!0}:{done:!1,value:e[s++]}},e:function(e){throw e},f:n}}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}}}}var U="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},M={exports:{}};
9
- /*! https://mths.be/base64 v1.0.0 by @mathias | MIT license */
10
- !function(e,t){!function(r){var s=t,n=e&&e.exports==s&&e,i="object"==typeof U&&U;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,s,n,i=e.length%3,o="",l=-1,h=e.length-i;++l<h;)t=e.charCodeAt(l)<<16,r=e.charCodeAt(++l)<<8,s=e.charCodeAt(++l),o+=c.charAt((n=t+r+s)>>18&63)+c.charAt(n>>12&63)+c.charAt(n>>6&63)+c.charAt(63&n);return 2==i?(t=e.charCodeAt(l)<<8,r=e.charCodeAt(++l),o+=c.charAt((n=t+r)>>10)+c.charAt(n>>4&63)+c.charAt(n<<2&63)+"="):1==i&&(n=e.charCodeAt(l),o+=c.charAt(n>>2)+c.charAt(n<<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,s,n=0,i="",o=-1;++o<t;)s=c.indexOf(e.charAt(o)),r=n%4?64*r+s:s,n++%4&&(i+=String.fromCharCode(255&r>>(-2*n&6)));return i},version:"1.0.0"};if(s&&!s.nodeType)if(n)n.exports=h;else for(var f in h)h.hasOwnProperty(f)&&(s[f]=h[f]);else r.base64=h}(U)}(M,M.exports);var W={exports:{}},F={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:D}=F;function j(e,t){if(0===e.length)return D;if(1===e.length)return e[0];const r=Buffer.allocUnsafe(t);let s=0;for(let t=0;t<e.length;t++){const n=e[t];r.set(n,s),s+=n.length}return s<t?r.slice(0,s):r}function $(e,t,r,s,n){for(let i=0;i<n;i++)r[s+i]=e[i]^t[3&i]}function q(e,t){for(let r=0;r<e.length;r++)e[r]^=t[3&r]}function G(e){return e.byteLength===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)}function V(e){if(V.readOnly=!0,Buffer.isBuffer(e))return e;let t;return e instanceof ArrayBuffer?t=Buffer.from(e):ArrayBuffer.isView(e)?t=Buffer.from(e.buffer,e.byteOffset,e.byteLength):(t=Buffer.from(e),V.readOnly=!1),t}try{const e=require("bufferutil");W.exports={concat:j,mask(t,r,s,n,i){i<48?$(t,r,s,n,i):e.mask(t,r,s,n,i)},toArrayBuffer:G,toBuffer:V,unmask(t,r){t.length<32?q(t,r):e.unmask(t,r)}}}catch(e){W.exports={concat:j,mask:$,toArrayBuffer:G,toBuffer:V,unmask:q}}const z=Symbol("kDone"),H=Symbol("kRun");var Y=class{constructor(e){this[z]=()=>{this.pending--,this[H]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[H]()}[H](){if(this.pending!==this.concurrency&&this.jobs.length){const e=this.jobs.shift();this.pending++,e(this[z])}}};const X=b.default,Z=W.exports,K=Y,{kStatusCode:Q}=F,J=Buffer.from([0,0,255,255]),ee=Symbol("permessage-deflate"),te=Symbol("total-length"),re=Symbol("callback"),se=Symbol("buffers"),ne=Symbol("error");let ie;var oe=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,!ie){const e=void 0!==this._options.concurrencyLimit?this._options.concurrencyLimit:10;ie=new K(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[re];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){ie.add((s=>{this._decompress(e,t,((e,t)=>{s(),r(e,t)}))}))}compress(e,t,r){ie.add((s=>{this._compress(e,t,((e,t)=>{s(),r(e,t)}))}))}_decompress(e,t,r){const s=this._isServer?"client":"server";if(!this._inflate){const e=`${s}_max_window_bits`,t="number"!=typeof this.params[e]?X.Z_DEFAULT_WINDOWBITS:this.params[e];this._inflate=X.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[ee]=this,this._inflate[te]=0,this._inflate[se]=[],this._inflate.on("error",le),this._inflate.on("data",ce)}this._inflate[re]=r,this._inflate.write(e),t&&this._inflate.write(J),this._inflate.flush((()=>{const e=this._inflate[ne];if(e)return this._inflate.close(),this._inflate=null,void r(e);const n=Z.concat(this._inflate[se],this._inflate[te]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[te]=0,this._inflate[se]=[],t&&this.params[`${s}_no_context_takeover`]&&this._inflate.reset()),r(null,n)}))}_compress(e,t,r){const s=this._isServer?"server":"client";if(!this._deflate){const e=`${s}_max_window_bits`,t="number"!=typeof this.params[e]?X.Z_DEFAULT_WINDOWBITS:this.params[e];this._deflate=X.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[te]=0,this._deflate[se]=[],this._deflate.on("data",ae)}this._deflate[re]=r,this._deflate.write(e),this._deflate.flush(X.Z_SYNC_FLUSH,(()=>{if(!this._deflate)return;let e=Z.concat(this._deflate[se],this._deflate[te]);t&&(e=e.slice(0,e.length-4)),this._deflate[re]=null,this._deflate[te]=0,this._deflate[se]=[],t&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),r(null,e)}))}};function ae(e){this[se].push(e),this[te]+=e.length}function ce(e){this[te]+=e.length,this[ee]._maxPayload<1||this[te]<=this[ee]._maxPayload?this[se].push(e):(this[ne]=new RangeError("Max payload size exceeded"),this[ne].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[ne][Q]=1009,this.removeListener("data",ce),this.reset())}function le(e){this[ee]._inflate=null,e[Q]=1007,this[re](e)}var he={exports:{}};const fe=[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];function de(e){return e>=1e3&&e<=1014&&1004!==e&&1005!==e&&1006!==e||e>=3e3&&e<=4999}function ue(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}try{const e=require("utf-8-validate");he.exports={isValidStatusCode:de,isValidUTF8:t=>t.length<150?ue(t):e(t),tokenChars:fe}}catch(e){he.exports={isValidStatusCode:de,isValidUTF8:ue,tokenChars:fe}}const{Writable:pe}=v.default,_e=oe,{BINARY_TYPES:me,EMPTY_BUFFER:ye,kStatusCode:ve,kWebSocket:ge}=F,{concat:be,toArrayBuffer:Se,unmask:we}=W.exports,{isValidStatusCode:ke,isValidUTF8:xe}=he.exports;var Ee=class extends pe{constructor(e={}){super(),this._binaryType=e.binaryType||me[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=0|e.maxPayload,this._skipUTF8Validation=!!e.skipUTF8Validation,this[ge]=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]=t.slice(e),t.slice(0,e)}const t=Buffer.allocUnsafe(e);do{const r=this._buffers[0],s=t.length-e;e>=r.length?t.set(this._buffers.shift(),s):(t.set(new Uint8Array(r.buffer,r.byteOffset,e),s),this._buffers[0]=r.slice(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,Oe(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[_e.extensionName])return this._loop=!1,Oe(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,Oe(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");if(!this._fragmented)return this._loop=!1,Oe(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,Oe(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,Oe(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");if(!this._fin)return this._loop=!1,Oe(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");if(t)return this._loop=!1,Oe(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");if(this._payloadLength>125)return this._loop=!1,Oe(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,Oe(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK")}else if(this._masked)return this._loop=!1,Oe(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,Oe(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,Oe(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=ye;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])&&we(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[_e.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(Oe(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"));this._fragments.push(r)}const s=this.dataMessage();if(s)return t(s);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?be(t,e):"arraybuffer"===this._binaryType?Se(be(t,e)):t,this.emit("message",r,!0)}else{const r=be(t,e);if(!this._skipUTF8Validation&&!xe(r))return this._loop=!1,Oe(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,ye),this.end();else{if(1===e.length)return Oe(RangeError,"invalid payload length 1",!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");{const t=e.readUInt16BE(0);if(!ke(t))return Oe(RangeError,`invalid status code ${t}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");const r=e.slice(2);if(!this._skipUTF8Validation&&!xe(r))return Oe(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 Oe(e,t,r,s,n){const i=new e(r?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(i,Oe),i.code=n,i[ve]=s,i}const{randomFillSync:Ce}=y.default,Te=oe,{EMPTY_BUFFER:Ne}=F,{isValidStatusCode:Le}=he.exports,{mask:Pe,toBuffer:Re}=W.exports,Be=Symbol("kByteLength"),Ae=Buffer.alloc(4);class Ie{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,s,n=!1,i=2,o=!1;t.mask&&(r=t.maskBuffer||Ae,t.generateMask?t.generateMask(r):Ce(r,0,4),o=0==(r[0]|r[1]|r[2]|r[3]),i=6),"string"==typeof e?s=t.mask&&!o||void 0===t[Be]?(e=Buffer.from(e)).length:t[Be]:(s=e.length,n=t.mask&&t.readOnly&&!o);let a=s;s>=65536?(i+=8,a=127):s>125&&(i+=2,a=126);const c=Buffer.allocUnsafe(n?s+i:i);return c[0]=t.fin?128|t.opcode:t.opcode,t.rsv1&&(c[0]|=64),c[1]=a,126===a?c.writeUInt16BE(s,2):127===a&&(c[2]=c[3]=0,c.writeUIntBE(s,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]:n?(Pe(e,r,c,i,s),[c]):(Pe(e,r,e,0,s),[c,e])):[c,e]}close(e,t,r,s){let n;if(void 0===e)n=Ne;else{if("number"!=typeof e||!Le(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");n=Buffer.allocUnsafe(2+r),n.writeUInt16BE(e,0),"string"==typeof t?n.write(t,2):n.set(t,2)}else n=Buffer.allocUnsafe(2),n.writeUInt16BE(e,0)}const i={[Be]:n.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._deflating?this.enqueue([this.dispatch,n,!1,i,s]):this.sendFrame(Ie.frame(n,i),s)}ping(e,t,r){let s,n;if("string"==typeof e?(s=Buffer.byteLength(e),n=!1):(s=(e=Re(e)).length,n=Re.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");const i={[Be]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:n,rsv1:!1};this._deflating?this.enqueue([this.dispatch,e,!1,i,r]):this.sendFrame(Ie.frame(e,i),r)}pong(e,t,r){let s,n;if("string"==typeof e?(s=Buffer.byteLength(e),n=!1):(s=(e=Re(e)).length,n=Re.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");const i={[Be]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:n,rsv1:!1};this._deflating?this.enqueue([this.dispatch,e,!1,i,r]):this.sendFrame(Ie.frame(e,i),r)}send(e,t,r){const s=this._extensions[Te.extensionName];let n,i,o=t.binary?2:1,a=t.compress;if("string"==typeof e?(n=Buffer.byteLength(e),i=!1):(n=(e=Re(e)).length,i=Re.readOnly),this._firstFragment?(this._firstFragment=!1,a&&s&&s.params[s._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(a=n>=s._threshold),this._compress=a):(a=!1,o=0),t.fin&&(this._firstFragment=!0),s){const s={[Be]:n,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,s,r]):this.dispatch(e,this._compress,s,r)}else this.sendFrame(Ie.frame(e,{[Be]:n,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:o,readOnly:i,rsv1:!1}),r)}dispatch(e,t,r,s){if(!t)return void this.sendFrame(Ie.frame(e,r),s);const n=this._extensions[Te.extensionName];this._bufferedBytes+=r[Be],this._deflating=!0,n.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 s&&s(e);for(let t=0;t<this._queue.length;t++){const r=this._queue[t],s=r[r.length-1];"function"==typeof s&&s(e)}}else this._bufferedBytes-=r[Be],this._deflating=!1,r.readOnly=!1,this.sendFrame(Ie.frame(t,r),s),this.dequeue()}))}dequeue(){for(;!this._deflating&&this._queue.length;){const e=this._queue.shift();this._bufferedBytes-=e[3][Be],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Be],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 Ue=Ie;const{kForOnEventAttribute:Me,kListener:We}=F,Fe=Symbol("kCode"),De=Symbol("kData"),je=Symbol("kError"),$e=Symbol("kMessage"),qe=Symbol("kReason"),Ge=Symbol("kTarget"),Ve=Symbol("kType"),ze=Symbol("kWasClean");class He{constructor(e){this[Ge]=null,this[Ve]=e}get target(){return this[Ge]}get type(){return this[Ve]}}Object.defineProperty(He.prototype,"target",{enumerable:!0}),Object.defineProperty(He.prototype,"type",{enumerable:!0});class Ye extends He{constructor(e,t={}){super(e),this[Fe]=void 0===t.code?0:t.code,this[qe]=void 0===t.reason?"":t.reason,this[ze]=void 0!==t.wasClean&&t.wasClean}get code(){return this[Fe]}get reason(){return this[qe]}get wasClean(){return this[ze]}}Object.defineProperty(Ye.prototype,"code",{enumerable:!0}),Object.defineProperty(Ye.prototype,"reason",{enumerable:!0}),Object.defineProperty(Ye.prototype,"wasClean",{enumerable:!0});class Xe extends He{constructor(e,t={}){super(e),this[je]=void 0===t.error?null:t.error,this[$e]=void 0===t.message?"":t.message}get error(){return this[je]}get message(){return this[$e]}}Object.defineProperty(Xe.prototype,"error",{enumerable:!0}),Object.defineProperty(Xe.prototype,"message",{enumerable:!0});class Ze extends He{constructor(e,t={}){super(e),this[De]=void 0===t.data?null:t.data}get data(){return this[De]}}Object.defineProperty(Ze.prototype,"data",{enumerable:!0});const Ke={addEventListener(e,t,r={}){let s;if("message"===e)s=function(e,r){const s=new Ze("message",{data:r?e:e.toString()});s[Ge]=this,t.call(this,s)};else if("close"===e)s=function(e,r){const s=new Ye("close",{code:e,reason:r.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});s[Ge]=this,t.call(this,s)};else if("error"===e)s=function(e){const r=new Xe("error",{error:e,message:e.message});r[Ge]=this,t.call(this,r)};else{if("open"!==e)return;s=function(){const e=new He("open");e[Ge]=this,t.call(this,e)}}s[Me]=!!r[Me],s[We]=t,r.once?this.once(e,s):this.on(e,s)},removeEventListener(e,t){for(const r of this.listeners(e))if(r[We]===t&&!r[Me]){this.removeListener(e,r);break}}};var Qe={CloseEvent:Ye,ErrorEvent:Xe,Event:He,EventTarget:Ke,MessageEvent:Ze};const{tokenChars:Je}=he.exports;function et(e,t,r){void 0===e[t]?e[t]=[r]:e[t].push(r)}var tt={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,s,n=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===Je[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 s=e.slice(c,h);44===l?(et(t,s,n),n=Object.create(null)):r=s,c=h=-1}}else-1===h&&-1!==c&&(h=f);else if(void 0===s)if(-1===h&&1===Je[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),et(n,e.slice(c,h),!0),44===l&&(et(t,r,n),n=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}`);s=e.slice(c,f),c=h=-1}else if(o){if(1!==Je[l])throw new SyntaxError(`Unexpected character at index ${f}`);-1===c?c=f:i||(i=!0),o=!1}else if(a)if(1===Je[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===Je[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),et(n,s,o),44===l&&(et(t,r,n),n=Object.create(null),r=void 0),s=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 d=e.slice(c,h);return void 0===r?et(t,d,n):(void 0===s?et(n,d,!0):et(n,s,i?d.replace(/\\/g,""):d),et(t,r,n)),t}};const rt=p.default,st=d.default,nt=f.default,it=_.default,ot=m.default,{randomBytes:at,createHash:ct}=y.default,{URL:lt}=g.default,ht=oe,ft=Ee,dt=Ue,{BINARY_TYPES:ut,EMPTY_BUFFER:pt,GUID:_t,kForOnEventAttribute:mt,kListener:yt,kStatusCode:vt,kWebSocket:gt,NOOP:bt}=F,{EventTarget:{addEventListener:St,removeEventListener:wt}}=Qe,{format:kt,parse:xt}=tt,{toBuffer:Et}=W.exports,Ot=["CONNECTING","OPEN","CLOSING","CLOSED"],Ct=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,Tt=[8,13];class Nt extends rt{constructor(e,t,r){super(),this._binaryType=ut[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=pt,this._closeTimer=null,this._extensions={},this._paused=!1,this._protocol="",this._readyState=Nt.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]),Pt(this,e,t,r)):this._isServer=!0}get binaryType(){return this._binaryType}set binaryType(e){ut.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 s=new ft({binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation});this._sender=new dt(e,this._extensions,r.generateMask),this._receiver=s,this._socket=e,s[gt]=this,e[gt]=this,s.on("conclude",Mt),s.on("drain",Wt),s.on("error",Ft),s.on("message",jt),s.on("ping",$t),s.on("pong",qt),e.setTimeout(0),e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",Vt),e.on("data",zt),e.on("end",Ht),e.on("error",Yt),this._readyState=Nt.OPEN,this.emit("open")}emitClose(){if(!this._socket)return this._readyState=Nt.CLOSED,void this.emit("close",this._closeCode,this._closeMessage);this._extensions[ht.extensionName]&&this._extensions[ht.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=Nt.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,t){if(this.readyState!==Nt.CLOSED){if(this.readyState===Nt.CONNECTING){const e="WebSocket was closed before the connection was established";return It(this,this._req,e)}this.readyState!==Nt.CLOSING?(this._readyState=Nt.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()}}pause(){this.readyState!==Nt.CONNECTING&&this.readyState!==Nt.CLOSED&&(this._paused=!0,this._socket.pause())}ping(e,t,r){if(this.readyState===Nt.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===Nt.OPEN?(void 0===t&&(t=!this._isServer),this._sender.ping(e||pt,t,r)):Ut(this,e,r)}pong(e,t,r){if(this.readyState===Nt.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===Nt.OPEN?(void 0===t&&(t=!this._isServer),this._sender.pong(e||pt,t,r)):Ut(this,e,r)}resume(){this.readyState!==Nt.CONNECTING&&this.readyState!==Nt.CLOSED&&(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,t,r){if(this.readyState===Nt.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!==Nt.OPEN)return void Ut(this,e,r);const s={binary:"string"!=typeof e,mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[ht.extensionName]||(s.compress=!1),this._sender.send(e||pt,s,r)}terminate(){if(this.readyState!==Nt.CLOSED){if(this.readyState===Nt.CONNECTING){const e="WebSocket was closed before the connection was established";return It(this,this._req,e)}this._socket&&(this._readyState=Nt.CLOSING,this._socket.destroy())}}}Object.defineProperty(Nt,"CONNECTING",{enumerable:!0,value:Ot.indexOf("CONNECTING")}),Object.defineProperty(Nt.prototype,"CONNECTING",{enumerable:!0,value:Ot.indexOf("CONNECTING")}),Object.defineProperty(Nt,"OPEN",{enumerable:!0,value:Ot.indexOf("OPEN")}),Object.defineProperty(Nt.prototype,"OPEN",{enumerable:!0,value:Ot.indexOf("OPEN")}),Object.defineProperty(Nt,"CLOSING",{enumerable:!0,value:Ot.indexOf("CLOSING")}),Object.defineProperty(Nt.prototype,"CLOSING",{enumerable:!0,value:Ot.indexOf("CLOSING")}),Object.defineProperty(Nt,"CLOSED",{enumerable:!0,value:Ot.indexOf("CLOSED")}),Object.defineProperty(Nt.prototype,"CLOSED",{enumerable:!0,value:Ot.indexOf("CLOSED")}),["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach((e=>{Object.defineProperty(Nt.prototype,e,{enumerable:!0})})),["open","error","close","message"].forEach((e=>{Object.defineProperty(Nt.prototype,`on${e}`,{enumerable:!0,get(){for(const t of this.listeners(e))if(t[mt])return t[yt];return null},set(t){for(const t of this.listeners(e))if(t[mt]){this.removeListener(e,t);break}"function"==typeof t&&this.addEventListener(e,t,{[mt]:!0})}})})),Nt.prototype.addEventListener=St,Nt.prototype.removeEventListener=wt;var Lt=Nt;function Pt(e,t,r,s){const n={protocolVersion:Tt[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...s,createConnection:void 0,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:void 0,host:void 0,path:void 0,port:void 0};if(!Tt.includes(n.protocolVersion))throw new RangeError(`Unsupported protocol version: ${n.protocolVersion} (supported versions: ${Tt.join(", ")})`);let i;if(t instanceof lt)i=t,e._url=t.href;else{try{i=new lt(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 Rt(e,t)}const l=o?443:80,h=at(16).toString("base64"),f=o?st.get:nt.get,d=new Set;let u;if(n.createConnection=o?At:Bt,n.defaultPort=n.defaultPort||l,n.port=i.port||l,n.host=i.hostname.startsWith("[")?i.hostname.slice(1,-1):i.hostname,n.headers={"Sec-WebSocket-Version":n.protocolVersion,"Sec-WebSocket-Key":h,Connection:"Upgrade",Upgrade:"websocket",...n.headers},n.path=i.pathname+i.search,n.timeout=n.handshakeTimeout,n.perMessageDeflate&&(u=new ht(!0!==n.perMessageDeflate?n.perMessageDeflate:{},!1,n.maxPayload),n.headers["Sec-WebSocket-Extensions"]=kt({[ht.extensionName]:u.offer()})),r.length){for(const e of r){if("string"!=typeof e||!Ct.test(e)||d.has(e))throw new SyntaxError("An invalid or duplicated subprotocol was specified");d.add(e)}n.headers["Sec-WebSocket-Protocol"]=r.join(",")}if(n.origin&&(n.protocolVersion<13?n.headers["Sec-WebSocket-Origin"]=n.origin:n.headers.Origin=n.origin),(i.username||i.password)&&(n.auth=`${i.username}:${i.password}`),a){const e=n.path.split(":");n.socketPath=e[0],n.path=e[1]}if(n.followRedirects){if(0===e._redirects){e._originalHost=i.host;const t=s&&s.headers;if(s={...s,headers:{}},t)for(const[e,r]of Object.entries(t))s.headers[e.toLowerCase()]=r}else i.host!==e._originalHost&&(delete n.headers.authorization,delete n.headers.cookie,delete n.headers.host,n.auth=void 0);n.auth&&!s.headers.authorization&&(s.headers.authorization="Basic "+Buffer.from(n.auth).toString("base64"))}let p=e._req=f(n);n.timeout&&p.on("timeout",(()=>{It(e,p,"Opening handshake has timed out")})),p.on("error",(t=>{null===p||p.aborted||(p=e._req=null,Rt(e,t))})),p.on("response",(i=>{const o=i.headers.location,a=i.statusCode;if(o&&n.followRedirects&&a>=300&&a<400){if(++e._redirects>n.maxRedirects)return void It(e,p,"Maximum redirects exceeded");let i;p.abort();try{i=new lt(o,t)}catch(t){const r=new SyntaxError(`Invalid URL: ${o}`);return void Rt(e,r)}Pt(e,i,r,s)}else e.emit("unexpected-response",p,i)||It(e,p,`Unexpected server response: ${i.statusCode}`)})),p.on("upgrade",((t,r,s)=>{if(e.emit("upgrade",t),e.readyState!==Nt.CONNECTING)return;p=e._req=null;const i=ct("sha1").update(h+_t).digest("base64");if(t.headers["sec-websocket-accept"]!==i)return void It(e,r,"Invalid Sec-WebSocket-Accept header");const o=t.headers["sec-websocket-protocol"];let a;if(void 0!==o?d.size?d.has(o)||(a="Server sent an invalid subprotocol"):a="Server sent a subprotocol but none was requested":d.size&&(a="Server sent no subprotocol"),a)return void It(e,r,a);o&&(e._protocol=o);const c=t.headers["sec-websocket-extensions"];if(void 0!==c){if(!u){return void It(e,r,"Server sent a Sec-WebSocket-Extensions header but no extension was requested")}let t;try{t=xt(c)}catch(t){return void It(e,r,"Invalid Sec-WebSocket-Extensions header")}const s=Object.keys(t);if(1!==s.length||s[0]!==ht.extensionName){return void It(e,r,"Server indicated an extension that was not requested")}try{u.accept(t[ht.extensionName])}catch(t){return void It(e,r,"Invalid Sec-WebSocket-Extensions header")}e._extensions[ht.extensionName]=u}e.setSocket(r,s,{generateMask:n.generateMask,maxPayload:n.maxPayload,skipUTF8Validation:n.skipUTF8Validation})}))}function Rt(e,t){e._readyState=Nt.CLOSING,e.emit("error",t),e.emitClose()}function Bt(e){return e.path=e.socketPath,it.connect(e)}function At(e){return e.path=void 0,e.servername||""===e.servername||(e.servername=it.isIP(e.host)?"":e.host),ot.connect(e)}function It(e,t,r){e._readyState=Nt.CLOSING;const s=new Error(r);Error.captureStackTrace(s,It),t.setHeader?(t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),t.once("abort",e.emitClose.bind(e)),e.emit("error",s)):(t.destroy(s),t.once("error",e.emit.bind(e,"error")),t.once("close",e.emitClose.bind(e)))}function Ut(e,t,r){if(t){const r=Et(t).length;e._socket?e._sender._bufferedBytes+=r:e._bufferedAmount+=r}if(r){r(new Error(`WebSocket is not open: readyState ${e.readyState} (${Ot[e.readyState]})`))}}function Mt(e,t){const r=this[gt];r._closeFrameReceived=!0,r._closeMessage=t,r._closeCode=e,void 0!==r._socket[gt]&&(r._socket.removeListener("data",zt),process.nextTick(Gt,r._socket),1005===e?r.close():r.close(e,t))}function Wt(){const e=this[gt];e.isPaused||e._socket.resume()}function Ft(e){const t=this[gt];void 0!==t._socket[gt]&&(t._socket.removeListener("data",zt),process.nextTick(Gt,t._socket),t.close(e[vt])),t.emit("error",e)}function Dt(){this[gt].emitClose()}function jt(e,t){this[gt].emit("message",e,t)}function $t(e){const t=this[gt];t.pong(e,!t._isServer,bt),t.emit("ping",e)}function qt(e){this[gt].emit("pong",e)}function Gt(e){e.resume()}function Vt(){const e=this[gt];let t;this.removeListener("close",Vt),this.removeListener("data",zt),this.removeListener("end",Ht),e._readyState=Nt.CLOSING,this._readableState.endEmitted||e._closeFrameReceived||e._receiver._writableState.errorEmitted||null===(t=e._socket.read())||e._receiver.write(t),e._receiver.end(),this[gt]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on("error",Dt),e._receiver.on("finish",Dt))}function zt(e){this[gt]._receiver.write(e)||this.pause()}function Ht(){const e=this[gt];e._readyState=Nt.CLOSING,e._receiver.end(),this.end()}function Yt(){const e=this[gt];this.removeListener("error",Yt),this.on("error",bt),e&&(e._readyState=Nt.CLOSING,this.destroy())}const{Duplex:Xt}=v.default;function Zt(e){e.emit("close")}function Kt(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Qt(e){this.removeListener("error",Qt),this.destroy(),0===this.listenerCount("error")&&this.emit("error",e)}var Jt=function(e,t){let r=!0;const s=new Xt({...t,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return e.on("message",(function(t,r){const n=!r&&s._readableState.objectMode?t.toString():t;s.push(n)||e.pause()})),e.once("error",(function(e){s.destroyed||(r=!1,s.destroy(e))})),e.once("close",(function(){s.destroyed||s.push(null)})),s._destroy=function(t,n){if(e.readyState===e.CLOSED)return n(t),void process.nextTick(Zt,s);let i=!1;e.once("error",(function(e){i=!0,n(e)})),e.once("close",(function(){i||n(t),process.nextTick(Zt,s)})),r&&e.terminate()},s._final=function(t){e.readyState!==e.CONNECTING?null!==e._socket&&(e._socket._writableState.finished?(t(),s._readableState.endEmitted&&s.destroy()):(e._socket.once("finish",(function(){t()})),e.close())):e.once("open",(function(){s._final(t)}))},s._read=function(){e.isPaused&&e.resume()},s._write=function(t,r,n){e.readyState!==e.CONNECTING?e.send(t,n):e.once("open",(function(){s._write(t,r,n)}))},s.on("end",Kt),s.on("error",Qt),s};const{tokenChars:er}=he.exports;var tr={parse:function(e){const t=new Set;let r=-1,s=-1,n=0;for(;n<e.length;n++){const i=e.charCodeAt(n);if(-1===s&&1===er[i])-1===r&&(r=n);else if(0===n||32!==i&&9!==i){if(44!==i)throw new SyntaxError(`Unexpected character at index ${n}`);{if(-1===r)throw new SyntaxError(`Unexpected character at index ${n}`);-1===s&&(s=n);const i=e.slice(r,s);if(t.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);t.add(i),r=s=-1}}else-1===s&&-1!==r&&(s=n)}if(-1===r||-1!==s)throw new SyntaxError("Unexpected end of input");const i=e.slice(r,n);if(t.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);return t.add(i),t}};const rr=p.default,sr=f.default,{createHash:nr}=y.default,ir=tt,or=oe,ar=tr,cr=Lt,{GUID:lr,kWebSocket:hr}=F,fr=/^[+/0-9A-Za-z]{22}==$/;var dr=class extends rr{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:cr,...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=sr.createServer(((e,t)=>{const r=sr.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,s)=>{this.handleUpgrade(t,r,s,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(2===this._state)return e&&this.once("close",(()=>{e(new Error("The server is not running"))})),void process.nextTick(ur,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(ur,this);else{const e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close((()=>{ur(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,s){t.on("error",pr);const n=void 0!==e.headers["sec-websocket-key"]&&e.headers["sec-websocket-key"],i=+e.headers["sec-websocket-version"];if("GET"!==e.method||"websocket"!==e.headers.upgrade.toLowerCase()||!n||!fr.test(n)||8!==i&&13!==i||!this.shouldHandle(e))return _r(t,400);const o=e.headers["sec-websocket-protocol"];let a=new Set;if(void 0!==o)try{a=ar.parse(o)}catch(e){return _r(t,400)}const c=e.headers["sec-websocket-extensions"],l={};if(this.options.perMessageDeflate&&void 0!==c){const e=new or(this.options.perMessageDeflate,!0,this.options.maxPayload);try{const t=ir.parse(c);t[or.extensionName]&&(e.accept(t[or.extensionName]),l[or.extensionName]=e)}catch(e){return _r(t,400)}}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 _r(t,o||401,c,h);this.completeUpgrade(l,n,a,e,t,r,s)}));if(!this.options.verifyClient(o))return _r(t,401)}this.completeUpgrade(l,n,a,e,t,r,s)}completeUpgrade(e,t,r,s,n,i,o){if(!n.readable||!n.writable)return n.destroy();if(n[hr])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>0)return _r(n,503);const a=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${nr("sha1").update(t+lr).digest("base64")}`],c=new this.options.WebSocket(null);if(r.size){const e=this.options.handleProtocols?this.options.handleProtocols(r,s):r.values().next().value;e&&(a.push(`Sec-WebSocket-Protocol: ${e}`),c._protocol=e)}if(e[or.extensionName]){const t=e[or.extensionName].params,r=ir.format({[or.extensionName]:[t]});a.push(`Sec-WebSocket-Extensions: ${r}`),c._extensions=e}this.emit("headers",a,s),n.write(a.concat("\r\n").join("\r\n")),n.removeListener("error",pr),c.setSocket(n,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(ur,this)}))),o(c,s)}};function ur(e){e._state=2,e.emit("close")}function pr(){this.destroy()}function _r(e,t,r,s){e.writable&&(r=r||sr.STATUS_CODES[t],s={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(r),...s},e.write(`HTTP/1.1 ${t} ${sr.STATUS_CODES[t]}\r\n`+Object.keys(s).map((e=>`${e}: ${s[e]}`)).join("\r\n")+"\r\n\r\n"+r)),e.removeListener("error",pr),e.destroy()}const mr=Lt;mr.createWebSocketStream=Jt,mr.Server=dr,mr.Receiver=Ee,mr.Sender=Ue,mr.WebSocket=mr,mr.WebSocketServer=mr.Server;var yr=mr,vr=require("child_process"),gr=require("events"),br=require("url"),Sr=yr.Server,wr="mpeg1video",kr="drawtext=x=w-tw-100:y=100:fontcolor=white:fontsize=36:text=水印QQ:421354532:box=1:boxcolor=black,scale=-1:-1,eq=",xr=["vcodec","c:v","-c:v","codec:v"],Er=["-s","-b:v","scale","contrast","brightness","saturation","gamma"].concat(xr),Or=["scale","contrast","brightness","saturation","gamma"],Cr=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"c:v":case"-c:v":case"codec:v":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}},Tr=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&&C(e,t)}(r,gr.EventEmitter);var t=L(r);function r(e){var s;return w(this,r),E(T(s=t.call(this)),"exitCode",void 0),E(T(s),"additionalFlags",[]),E(T(s),"stream",null),E(T(s),"inputStreamStarted",!1),s.options=e,s.ffmpegPath=e.ffmpegPath||"ffmpeg",s.url=e.url,s.ffmpegOptions=e.ffmpegOptions,s.initMpeg2Muxer(),s}return x(r,[{key:"initMpeg2Muxer",value:function(){var e=this;if(this.ffmpegOptions)for(var t in this.ffmpegOptions)this.additionalFlags.push(t),""!==String(this.ffmpegOptions[t])&&this.additionalFlags.push(String(this.ffmpegOptions[t]));this.spawnOptions=["-rtsp_transport","tcp","-thread_queue_size","256","-i",this.url,"-f","mpegts"].concat(R(this.additionalFlags),["-nostats","-r","29.97","-"]),this.stream=vr.spawn(this.ffmpegPath,this.spawnOptions,{detached:!1}),this.stream.on("error",(function(e,t){console.error("启动ffmpeg时出错,请确保你安装了ffmpeg,然后检查路径或者命令参数")})),this.stream.on("close",(function(t,r){return console.log("ffmpeg关闭,code:",t),e.emit("ffmpegClosed")})),this.stream.on("exit",(function(t,r){if(1===t)return console.error("***由于ffmpeg退出,ffmpeg启动不成功,请检查ffmpeg参数或相关情况或联系作者***"),e.exitCode=1,e.emit("exitWithError")})),this.inputStreamStarted=!0,this.stream.stdout.on("data",(function(t){return e.emit("mpeg2data",t)})),this.stream.stderr.on("data",(function(t){return e.emit("ffmpegStderr",t)}))}}]),r}(),Nr=function(){function e(t){w(this,e),E(this,"freeTime",0),E(this,"isStreamWrap",!1),E(this,"clients",[]),E(this,"mpeg2Muxer",{instance:null,stream:null,data:null}),this.config=t,this.url=t.url}return x(e,[{key:"createStream",value:function(){var e=this;this.isStreamWrap||(console.log("创建一个新的ffmpeg子进程"),this.isStreamWrap=!0,this.mpeg2Muxer.instance=new Tr({ffmpegOptions:this.formatParams(this.config),url:this.url,ffmpegPath:"ffmpeg"}),this.mpeg2Muxer.stream=this.mpeg2Muxer.instance.stream,this.mpeg2Muxer.instance.on("mpeg2data",(function(t){e.broadcast(t)})),this.mpeg2Muxer.instance.on("exitWithError",(function(){})),this.mpeg2Muxer.instance.on("ffmpegClosed",(function(){e.destroy()})))}},{key:"formatParams",value:function(e){for(var t={"-codec:v":wr,"-vf":kr},r=0,s=Object.entries(e);r<s.length;r++){var n=P(s[r],2),i=n[0],o=n[1];"wm"===i&&"0"===o&&(t["-vf"]="scale=-1:-1,eq="),Er.includes(i)&&(Or.includes(i)?"scale"===i?t["-vf"]=t["-vf"].replace(/scale=[x0-9\:\-]*/g,"scale=".concat(o)):t["-vf"]+="".concat(i,"=").concat(o,":"):xr.includes(i)?t["-codec:v"]=o:Cr(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=I(this.clients);try{for(r.s();!(t=r.n()).done;){var s=t.value;s.isSegment&&s.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("视频关闭,销毁一个client(ws句柄)"),t>-1&&this.clients.splice(t,1)}},{key:"dropAllClient",value:function(){var e,t=I(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}(),Lr=function(){function e(t){var r=this;w(this,e),E(this,"channels",[]),t&&"boolean"==typeof t.wm&&!t.wm&&(kr="scale=-1:-1,eq="),t&&"string"==typeof t.vcodec&&t.vcodec.length>0&&(wr=t.vcodec),setInterval((function(){return r.checkFree()}),1e4);var s=f.default.createServer();if(t&&"object"===S(t.wss))if(console.log("wss启动中...."),t.wss.hasOwnProperty("pfx"))if(t.wss.hasOwnProperty("passphrase"))try{s=d.default.createServer({pfx:u.default.readFileSync(t.wss.pfx),passphrase:t.wss.passphrase})}catch(e){console.error("--【读取pfx安全证书文件出错,wss启动失败,退回到ws;错误信息如下,有问题请联系我】--"),console.log(e)}else console.error("【wss启动失败;请传入正确的pfx文件指定密码:passphrase】");else if(t.wss.hasOwnProperty("cert"))if(t.wss.hasOwnProperty("key"))try{s=d.default.createServer({cert:u.default.readFileSync(t.wss.cert),key:u.default.readFileSync(t.wss.key)})}catch(e){console.error("--【读取cert安全证书文件出错,wss启动失败,退回到ws;错误信息如下,有问题请联系我】--"),console.log(e)}else console.error("【wss启动失败;请传入正确的安全证书私钥:key】");else console.error("【wss启动失败;请传入正确的安全证书公钥:cert】");this.wss=new Sr({server:s}),this.wss.on("connection",(function(e,t){var s=br.parse(t.url,!0);if(s.query.url){var n=M.exports.decode(s.query.url.toString());s.query.url=n,r.registeClient(e,{url:n,options:s.query})}console.log("一个新的client(ws句柄)连接成功")})),s.listen(t&&t.port||9999)}return x(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=I(this.channels);try{for(r.s();!(t=r.n()).done;){var s=t.value;if(s.url===e)return s}}catch(e){r.e(e)}finally{r.f()}return null}},{key:"createChannel",value:function(e,t){var r=new Nr(e,t);return this.channels.push(r),r}},{key:"checkFree",value:function(){var e,t=I(this.channels);try{for(t.s();!(e=t.n()).done;){var r=e.value;r.clients.length>0?r.freeTime=0:r.freeTime+=10,r.freeTime>=60&&this.destroyedChannel(r)}}catch(e){t.e(e)}finally{t.f()}}},{key:"destroyedChannel",value:function(e){var t=this.channels.indexOf(e);t>-1&&(this.channels.splice(t,1),e.destroy())}}]),e}();E(Lr,"version","2.4.5"),module.exports=Lr;
8
+ "use strict";var e=require("http"),t=require("https"),r=require("fs"),n=require("net"),s=require("path"),i=require("crypto"),o=require("child_process"),a=require("events"),c=require("tls"),l=require("stream"),u=require("url"),f=require("zlib");function h(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var p=h(e),d=h(t),m=h(r),_=h(n),y=h(s),g=h(i),v=h(o),E=h(a),w=h(c),b=h(l),S=h(u),x=h(f);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 T(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function P(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,n.key,n)}}function C(e,t,r){return t&&P(e.prototype,t),r&&P(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function N(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function O(e){return O=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)},O(e)}function I(e,t){return I=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e},I(e,t)}function A(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function L(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 A(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=O(e);if(t){var s=O(this).constructor;r=Reflect.construct(n,arguments,s)}else r=n.apply(this,arguments);return L(this,r)}}function F(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)return;var n,s,i=[],o=!0,a=!1;try{for(r=r.call(e);!(o=(n=r.next()).done)&&(i.push(n.value),!t||i.length!==t);o=!0);}catch(e){a=!0,s=e}finally{try{o||null==r.return||r.return()}finally{if(a)throw s}}return i}(e,t)||U(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 M(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)||U(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 U(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 W(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=U(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}}}}var D="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function j(e){throw new Error('Could not dynamically require "'+e+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var q={},K={};Object.defineProperty(K,"__esModule",{value:!0}),K.promisify=$;function $(e){if("function"!=typeof e)throw new TypeError("Argument to promisify must be a function");var t=e["__ES6-PROMISIFY--CUSTOM-ARGUMENTS__"],r=$.Promise||Promise;if("function"!=typeof r)throw new Error("No Promise implementation found; do you need a polyfill?");return function(){for(var n=this,s=arguments.length,i=new Array(s),o=0;o<s;o++)i[o]=arguments[o];return new r((function(r,s){i.push((function(e){if(e)return s(e);for(var n=arguments.length,i=new Array(n>1?n-1:0),o=1;o<n;o++)i[o-1]=arguments[o];if(1===i.length||!t)return r(i[0]);var a={};i.forEach((function(e,r){var n=t[r];n&&(a[n]=e)})),r(a)})),e.apply(n,i)}))}}$.argumentNames="__ES6-PROMISIFY--CUSTOM-ARGUMENTS__",$.Promise=void 0;var G={exports:{}},V="win32"===process.platform,z=V?/[^:]\\$/:/.\/$/,Y=function(){var e;return e=V?process.env.TEMP||process.env.TMP||(process.env.SystemRoot||process.env.windir)+"\\temp":process.env.TMPDIR||process.env.TMP||process.env.TEMP||"/tmp",z.test(e)&&(e=e.slice(0,-1)),e};!function(e){var t=y.default,r=m.default,n=g.default,s=Y,i=process.env.PEMJS_TMPDIR||s();e.exports.isNumber=function(e){return!Array.isArray(e)&&/^\d+$/g.test(e)},e.exports.isHex=function(e){return/^(0x){0,1}([0-9A-F]{1,40}|[0-9A-F]{1,40})$/gi.test(e)},e.exports.toHex=function(e){for(var t="",r=0;r<e.length;r++)t+=""+e.charCodeAt(r).toString(16);return t},e.exports.ciphers=["aes128","aes192","aes256","camellia128","camellia192","camellia256","des","des3","idea"];var o=e.exports.ciphers;e.exports.createPasswordFile=function(e,s,a){if(!(e&&Object.prototype.hasOwnProperty.call(e,"password")&&Object.prototype.hasOwnProperty.call(e,"passType")&&/^(word|in|out)$/.test(e.passType)))return!1;var c=t.join(i,n.randomBytes(20).toString("hex"));return a.push(c),e.password=e.password.trim(),""===e.password&&(e.mustPass=!0),e.cipher&&-1!==o.indexOf(e.cipher)&&s.push("-"+e.cipher),s.push("-pass"+e.passType),e.mustPass?s.push("pass:"+e.password):(r.writeFileSync(c,e.password),s.push("file:"+c)),!0},e.exports.deleteTempFiles=function(e,t){var n=[];if("string"==typeof e)n.push(e);else{if(!Array.isArray(e))return t(new Error("Unexcepted files parameter type; only string or array supported"));n=e}var s=function(e,t){if(!e.length)return t(null);var n=e.shift();if(!n||"string"!=typeof n)return s(e,t);r.unlink(n,(function(r){return r&&"ENOENT"===r.code?s(e,t):r?t(r):s(e,t)}))};s(n,t)}}(G);var H=Z;Z.sync=function(e,t){return X(J.statSync(e),e,t)};var J=m.default;function X(e,t,r){return!(!e.isSymbolicLink()&&!e.isFile())&&function(e,t){var r=void 0!==t.pathExt?t.pathExt:process.env.PATHEXT;if(!r)return!0;if(-1!==(r=r.split(";")).indexOf(""))return!0;for(var n=0;n<r.length;n++){var s=r[n].toLowerCase();if(s&&e.substr(-s.length).toLowerCase()===s)return!0}return!1}(t,r)}function Z(e,t,r){J.stat(e,(function(n,s){r(n,!n&&X(s,e,t))}))}var Q=re;re.sync=function(e,t){return ne(te.statSync(e),t)};var ee,te=m.default;function re(e,t,r){te.stat(e,(function(e,n){r(e,!e&&ne(n,t))}))}function ne(e,t){return e.isFile()&&function(e,t){var r=e.mode,n=e.uid,s=e.gid,i=void 0!==t.uid?t.uid:process.getuid&&process.getuid(),o=void 0!==t.gid?t.gid:process.getgid&&process.getgid(),a=parseInt("100",8),c=parseInt("010",8),l=parseInt("001",8),u=a|c;return r&l||r&c&&s===o||r&a&&n===i||r&u&&0===i}(e,t)}ee="win32"===process.platform||D.TESTING_WINDOWS?H:Q;var se=ie;function ie(e,t,r){if("function"==typeof t&&(r=t,t={}),!r){if("function"!=typeof Promise)throw new TypeError("callback not provided");return new Promise((function(r,n){ie(e,t||{},(function(e,t){e?n(e):r(t)}))}))}ee(e,t||{},(function(e,n){e&&("EACCES"===e.code||t&&t.ignoreErrors)&&(e=null,n=!1),r(e,n)}))}ie.sync=function(e,t){try{return ee.sync(e,t||{})}catch(e){if(t&&t.ignoreErrors||"EACCES"===e.code)return!1;throw e}};const oe="win32"===process.platform||"cygwin"===process.env.OSTYPE||"msys"===process.env.OSTYPE,ae=y.default,ce=oe?";":":",le=se,ue=e=>Object.assign(new Error(`not found: ${e}`),{code:"ENOENT"}),fe=(e,t)=>{const r=t.colon||ce,n=e.match(/\//)||oe&&e.match(/\\/)?[""]:[...oe?[process.cwd()]:[],...(t.path||process.env.PATH||"").split(r)],s=oe?t.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",i=oe?s.split(r):[""];return oe&&-1!==e.indexOf(".")&&""!==i[0]&&i.unshift(""),{pathEnv:n,pathExt:i,pathExtExe:s}},he=(e,t,r)=>{"function"==typeof t&&(r=t,t={}),t||(t={});const{pathEnv:n,pathExt:s,pathExtExe:i}=fe(e,t),o=[],a=r=>new Promise(((s,i)=>{if(r===n.length)return t.all&&o.length?s(o):i(ue(e));const a=n[r],l=/^".*"$/.test(a)?a.slice(1,-1):a,u=ae.join(l,e),f=!l&&/^\.[\\\/]/.test(e)?e.slice(0,2)+u:u;s(c(f,r,0))})),c=(e,r,n)=>new Promise(((l,u)=>{if(n===s.length)return l(a(r+1));const f=s[n];le(e+f,{pathExt:i},((s,i)=>{if(!s&&i){if(!t.all)return l(e+f);o.push(e+f)}return l(c(e,r,n+1))}))}));return r?a(0).then((e=>r(null,e)),r):a(0)};var pe=he;he.sync=(e,t)=>{t=t||{};const{pathEnv:r,pathExt:n,pathExtExe:s}=fe(e,t),i=[];for(let o=0;o<r.length;o++){const a=r[o],c=/^".*"$/.test(a)?a.slice(1,-1):a,l=ae.join(c,e),u=!c&&/^\.[\\\/]/.test(e)?e.slice(0,2)+l:l;for(let e=0;e<n.length;e++){const r=u+n[e];try{if(le.sync(r,{pathExt:s})){if(!t.all)return r;i.push(r)}}catch(e){}}}if(t.all&&i.length)return i;if(t.nothrow)return null;throw ue(e)};var de=G.exports,me=v.default.spawn,_e=y.default,ye=m.default,ge=Y,ve=g.default,Ee=pe,we={},be=process.env.PEMJS_TMPDIR||ge();function Se(e,t){we[e]=t}function xe(e){return we[e]||null}function ke(e,t,r){var n=xe("pathOpenSSL")||process.env.OPENSSL_BIN||"openssl";!function(e,t){Ee(e,(function(r){if(r)return t(new Error("Could not find openssl on your system on this path: "+e));t()}))}(n,(function(s){if(s)return r(s);var i=me(n,e),o="",a=t?Buffer.alloc(0):"";i.stdout.on("data",(function(e){t?a=Buffer.concat([a,e]):a+=e.toString("binary")})),i.stderr.on("data",(function(e){o+=e.toString("binary")}));var c=2,l=-1,u=!1,f=function(t){if(!u)return t?(u=!0,r(t)):--c<1?(u=!0,l&&(2!==l||""!==o&&!/depth lookup: unable to/.test(o))?r(new Error("Invalid openssl exit code: "+l+"\n% openssl "+e.join(" ")+"\n"+o),l):r(null,l,a,o)):void 0};i.on("error",f),i.on("exit",(function(e){l=e,f()})),i.on("close",(function(){a=t?a:Buffer.from(a,"binary").toString("utf-8"),o=Buffer.from(o,"binary").toString("utf-8"),f()}))}))}function Te(e,t,r,n){n||"function"!=typeof r||(n=r,r=!1);var s,i,o,a=[],c=[];if(t)for(t=[].concat(t),i=0;i<e.length;i++)"--TMPFILE--"===e[i]&&(s=_e.join(be,ve.randomBytes(20).toString("hex")),a.push({path:s,contents:t.shift()}),e[i]=s,c.push(s));for(i=0;i<a.length;i++)o=a[i],ye.writeFileSync(o.path,o.contents);ke(e,r,(function(e,t,r,s){de.deleteTempFiles(c,(function(i){n(e||i,t,r,s)}))}))}ke(["version"],!1,(function(e,t,r,n){var s=(String(r)+"\n"+String(n)+"\n"+String(e)).match(/^LibreSSL/i);Se("openSslVersion",(s&&s[0]?"LibreSSL":"openssl").toUpperCase())}));var Pe={exec:function(e,t,r,n){n||"function"!=typeof r||(n=r,r=!1),Te(e,r,(function(e,r,s,i){var o,a;return e?n(e):(o=(o=s.match(new RegExp("\\-+BEGIN "+t+"\\-+$","m")))?o.index:-1,"EC PARAMETERS"===t&&(t="EC PRIVATE KEY"),a=(a=s.match(new RegExp("^\\-+END "+t+"\\-+","m")))?a.index+a[0].length:-1,o>=0&&a>=0?n(null,s.substring(o,a)):n(new Error(t+" not found from openssl output:\n---stdout---\n"+s+"\n---stderr---\n"+i+"\ncode: "+r)))}))},execBinary:function(e,t,r){r||"function"!=typeof t||(r=t,t=!1),Te(e,t,!0,(function(e,t,n,s){return e?r(e):r(null,n)}))},spawn:ke,spawnWrapper:Te,set:Se,get:xe},Ce={},Ne=Pe,Oe=G.exports;Ce.PEM2DER=function(e,t,r,n){n||"function"!=typeof r||(n=r,r="x509");var s=[r,"-outform","der","-in",e,"-out",t];Ne.spawnWrapper(s,!1,(function(e,t){e?n(e):n(null,0===t)}))},Ce.DER2PEM=function(e,t,r,n){n||"function"!=typeof r||(n=r,r="x509");var s=[r,"-inform","der","-in",e,"-out",t];Ne.spawnWrapper(s,!1,(function(e,t){e?n(e):n(null,0===t)}))},Ce.PEM2P7B=function(e,t,r){var n=["crl2pkcs7","-nocrl","-certfile",e.cert,"-out",t];e.ca&&(Array.isArray(e.ca)||(e.ca=[e.ca]),e.ca.forEach((function(e){n.push("-certfile"),n.push(e)}))),Ne.spawnWrapper(n,!1,(function(e,t){e?r(e):r(null,0===t)}))},Ce.P7B2PEM=function(e,t,r){var n=["pkcs7","-print_certs","-in",e,"-out",t];Ne.spawnWrapper(n,!1,(function(e,t){e?r(e):r(null,0===t)}))},Ce.PEM2PFX=function(e,t,r,n){var s=["pkcs12","-export","-out",t,"-inkey",e.key,"-in",e.cert];e.ca&&(Array.isArray(e.ca)||(e.ca=[e.ca]),e.ca.forEach((function(e){s.push("-certfile"),s.push(e)})));var i=[];Oe.createPasswordFile({cipher:"",password:r,passType:"in"},s,i),Oe.createPasswordFile({cipher:"",password:r,passType:"out"},s,i),Ne.spawnWrapper(s,!1,(function(e,t){Oe.deleteTempFiles(i,(function(r){!function(e){e?n(e):n(null,0===t)}(e||r)}))}))},Ce.PFX2PEM=function(e,t,r,n){var s=["pkcs12","-in",e,"-out",t,"-nodes"],i=[];Oe.createPasswordFile({cipher:"",password:r,passType:"in"},s,i),Oe.createPasswordFile({cipher:"",password:r,passType:"out"},s,i),Ne.spawnWrapper(s,!1,(function(e,t){Oe.deleteTempFiles(i,(function(r){!function(e){e?n(e):n(null,0===t)}(e||r)}))}))},Ce.P7B2PFX=function(e,t,r,n){var s=e.cert.replace(/\.[^.]+$/,".cer"),i=["pkcs7","-print_certs","-in",e.cert,"-out",s];Ne.spawnWrapper(i,!1,(function(i,o){if(i)n(i);else{var a=["pkcs12","-export","-in",s,"-inkey",e.key,"-out",t];e.ca&&(Array.isArray(e.ca)||(e.ca=[e.ca]),e.ca.forEach((function(e){a.push("-certfile"),a.push(e)})));var c=[s];Oe.createPasswordFile({cipher:"",password:r,passType:"in"},a,c),Oe.createPasswordFile({cipher:"",password:r,passType:"out"},a,c),Ne.spawnWrapper(a,!1,(function(e,t){Oe.deleteTempFiles(c,(function(r){!function(e){e?n(e):n(null,0===t)}(e||r)}))}))}}))};const{promisify:Ie}=K;var Ae=_.default,Le=G.exports,Re=Pe;q.createPrivateKey=Fe,q.createDhparam=Me,q.createEcparam=Ue,q.createCSR=Be,q.createCertificate=We,q.readCertificateInfo=je,q.getPublicKey=De,q.getFingerprint=$e,q.getModulus=qe,q.getDhparamInfo=Ke,q.createPkcs12=Ge,q.readPkcs12=Ve,q.verifySigningChain=He,q.checkCertificate=ze,q.checkPkcs12=Ye,q.config=function(e){Object.keys(e).forEach((function(t){Re.set(t,e[t])}))},q.convert=Ce;function Fe(e,t,r){r||t||"function"!=typeof e?!r&&e&&"function"==typeof t&&(r=t,t={}):(r=e,e=void 0,t={}),e=Number(e)||2048;var n=["genrsa"],s=[];t&&t.cipher&&-1!==Number(Le.ciphers.indexOf(t.cipher))&&t.password&&Le.createPasswordFile({cipher:t.cipher,password:t.password,passType:"out"},n,s),n.push(e),Re.exec(n,"RSA PRIVATE KEY",(function(e,t){Le.deleteTempFiles(s,(function(n){!function(e){if(e)return r(e);r(null,{key:t})}(e||n)}))}))}function Me(e,t){t||"function"!=typeof e||(t=e,e=void 0);var r=["dhparam","-outform","PEM",e=Number(e)||512];Re.exec(r,"DH PARAMETERS",(function(e,r){return e?t(e):t(null,{dhparam:r})}))}function Ue(e,t,r,n){n||void 0!==r||t||"function"!=typeof e?!n&&void 0===r&&e&&"function"==typeof t?(n=t,t=void 0):!n&&"function"==typeof r&&e&&t&&(n=r,r=void 0):(n=e,e=void 0);var s=["ecparam","-name",e=e||"secp256k1","-genkey","-param_enc",t=t||"explicit"],i="EC PARAMETERS";(r=r||!1)&&(s.push("-noout"),i="EC PRIVATE KEY"),Re.exec(s,i,(function(e,t){return e?n(e):n(null,{ecparam:t})}))}function Be(e,t){if(t||"function"!=typeof e||(t=e,e=void 0),(e=e||{}).commonName&&(Ae.isIPv4(e.commonName)||Ae.isIPv6(e.commonName))&&(e.altNames?-1===e.altNames.indexOf(e.commonName)&&(e.altNames=e.altNames.concat([e.commonName])):e.altNames=[e.commonName]),e.clientKey){var r=["req","-new","-"+(e.hash||"sha256")];e.csrConfigFile?(r.push("-config"),r.push(e.csrConfigFile)):(r.push("-subj"),r.push(function(e){var t={C:(e=e||{}).country||e.C,ST:e.state||e.ST,L:e.locality||e.L,O:e.organization||e.O,OU:e.organizationUnit||e.OU,CN:e.commonName||e.CN||"localhost",DC:e.dc||e.DC||"",emailAddress:e.emailAddress};return Object.keys(t).map((function(e){if(t[e]){if("object"==typeof t[e]&&t[e].length>=1){var r="";return t[e].map((function(t){r+="/"+e+"="+t.replace(/[^\w .*\-,@']+/g," ").trim()})),r}return"/"+e+"="+t[e].replace(/[^\w .*\-,@']+/g," ").trim()}})).join("")}(e))),r.push("-key"),r.push("--TMPFILE--");var n=[e.clientKey],s=null;if(e.altNames&&Array.isArray(e.altNames)&&e.altNames.length){r.push("-extensions"),r.push("v3_req"),r.push("-config"),r.push("--TMPFILE--");for(var i=[],o=0;o<e.altNames.length;o++)i.push((Ae.isIP(e.altNames[o])?"IP":"DNS")+"."+(o+1)+" = "+e.altNames[o]);n.push(s=["[req]","req_extensions = v3_req","distinguished_name = req_distinguished_name","[v3_req]","subjectAltName = @alt_names","[alt_names]",i.join("\n"),"[req_distinguished_name]","commonName = Common Name","commonName_max = 64"].join("\n"))}else e.config&&(s=e.config);var a=[];e.clientKeyPassword&&Le.createPasswordFile({cipher:"",password:e.clientKeyPassword,passType:"in"},r,a),Re.exec(r,"CERTIFICATE REQUEST",n,(function(r,n){Le.deleteTempFiles(a,(function(i){!function(r){if(r)return t(r);t(null,{csr:n,config:s,clientKey:e.clientKey})}(r||i)}))}))}else Fe(e.keyBitsize||2048,(function(r,n){if(r)return t(r);e.clientKey=n.key,Be(e,t)}))}function We(e,t){if(t||"function"!=typeof e||(t=e,e=void 0),(e=e||{}).csr){if(e.clientKey||(e.clientKey=""),!e.serviceKey){if(!e.selfSigned)return void Fe(e.keyBitsize||2048,(function(r,n){if(r)return t(r);e.serviceKey=n.key,We(e,t)}));e.serviceKey=e.clientKey}je(e.csr,(function(r,n){if(r)return t(r);var s=["x509","-req","-"+(e.hash||"sha256"),"-days",Number(e.days)||"365","-in","--TMPFILE--"],i=[e.csr],o=[];if(e.serviceCertificate?(s.push("-CA"),s.push("--TMPFILE--"),s.push("-CAkey"),s.push("--TMPFILE--"),e.serial?(s.push("-set_serial"),Le.isNumber(e.serial)?s.push("0x"+("0000000000000000000000000000000000000000"+e.serial.toString(16)).slice(-40)):Le.isHex(e.serial)?(e.serial.startsWith("0x")&&(e.serial=e.serial.substring(2,e.serial.length)),s.push("0x"+("0000000000000000000000000000000000000000"+e.serial).slice(-40))):s.push("0x"+("0000000000000000000000000000000000000000"+Le.toHex(e.serial)).slice(-40))):(s.push("-CAcreateserial"),e.serialFile&&(s.push("-CAserial"),s.push(e.serialFile+".srl"))),e.serviceKeyPassword&&Le.createPasswordFile({cipher:"",password:e.serviceKeyPassword,passType:"in"},s,o),i.push(e.serviceCertificate),i.push(e.serviceKey)):(s.push("-signkey"),s.push("--TMPFILE--"),e.serviceKeyPassword&&Le.createPasswordFile({cipher:"",password:e.serviceKeyPassword,passType:"in"},s,o),i.push(e.serviceKey)),e.config)s.push("-extensions"),s.push("v3_req"),s.push("-extfile"),s.push("--TMPFILE--"),i.push(e.config);else if(e.extFile)s.push("-extfile"),s.push(e.extFile);else{var a=[];if(n&&n.san){for(var c=0;c<n.san.dns.length;c++)a.push("DNS."+(c+1)+" = "+n.san.dns[c]);for(var l=0;l<n.san.ip.length;l++)a.push("IP."+(l+1)+" = "+n.san.ip[l]);for(var u=0;u<n.san.email.length;u++)a.push("email."+(u+1)+" = "+n.san.email[u]);s.push("-extensions"),s.push("v3_req"),s.push("-extfile"),s.push("--TMPFILE--"),i.push(["[v3_req]","subjectAltName = @alt_names","[alt_names]",a.join("\n")].join("\n"))}}e.clientKeyPassword&&Le.createPasswordFile({cipher:"",password:e.clientKeyPassword,passType:"in"},s,o),Re.exec(s,"CERTIFICATE",i,(function(r,n){Le.deleteTempFiles(o,(function(s){!function(r){if(r)return t(r);var s={csr:e.csr,clientKey:e.clientKey,certificate:n,serviceKey:e.serviceKey};t(null,s)}(r||s)}))}))}))}else Be(e,(function(r,n){if(r)return t(r);e.csr=n.csr,e.config=n.config,e.clientKey=n.clientKey,We(e,t)}))}function De(e,t){var r;t||"function"!=typeof e||(t=e,e=void 0),r=(e=(e||"").toString()).match(/BEGIN(\sNEW)? CERTIFICATE REQUEST/)?["req","-in","--TMPFILE--","-pubkey","-noout"]:e.match(/BEGIN RSA PRIVATE KEY/)||e.match(/BEGIN PRIVATE KEY/)?["rsa","-in","--TMPFILE--","-pubout"]:["x509","-in","--TMPFILE--","-pubkey","-noout"],Re.exec(r,"PUBLIC KEY",e,(function(e,r){return e?t(e):t(null,{publicKey:r})}))}function je(e,t){t||"function"!=typeof e||(t=e,e=void 0);var r=[(e=(e||"").toString()).match(/BEGIN(\sNEW)? CERTIFICATE REQUEST/)?"req":"x509","-noout","-nameopt","RFC2253,sep_multiline,space_eq,-esc_msb,utf8","-text","-in","--TMPFILE--"];Re.spawnWrapper(r,e,(function(e,r,n,s){return e?t(e):s?t(s):function(e,t){try{var r,n,s,i;e=(e||"").toString();var o,a,c,l={issuer:{}},u={};if((r=e.match(/\s*Serial Number:\r?\n?\s*([^\r\n]*)\r?\n\s*\b/))&&r.length>1&&(l.serial=r[1]),(n=e.match(/\s*Subject:\r?\n(\s*(([a-zA-Z0-9.]+)\s=\s[^\r\n]+\r?\n))*\s*\b/))&&n.length>1){if(s=Je(n=n[0],/\s([a-zA-Z0-9.]+)\s=\s([^\r\n].*)/g))for(c=0;c<s.length;c++)(a=s[c][1].trim()).match("(C|ST|L|O|OU|CN|emailAddress|DC)")||""===a||(l[a]=s[c][2].trim());s=n.match(/\sC\s=\s([^\r\n].*?)[\r\n]/),l.country=s&&s[1]||"",s=n.match(/\sST\s=\s([^\r\n].*?)[\r\n]/),l.state=s&&s[1]||"",s=n.match(/\sL\s=\s([^\r\n].*?)[\r\n]/),l.locality=s&&s[1]||"",s=Je(n,/\sO\s=\s([^\r\n].*)/g),l.organization=s?s.length>1?s.sort((function(e,t){var r=e[1].toUpperCase(),n=t[1].toUpperCase();return n>r?-1:r>n?1:0})).sort((function(e,t){return e[1].length-t[1].length})).map((function(e){return e[1]})):s[0][1]:"",s=Je(n,/\sOU\s=\s([^\r\n].*)/g),l.organizationUnit=s?s.length>1?s.sort((function(e,t){var r=e[1].toUpperCase(),n=t[1].toUpperCase();return n>r?-1:r>n?1:0})).sort((function(e,t){return e[1].length-t[1].length})).map((function(e){return e[1]})):s[0][1]:"",s=Je(n,/\sCN\s=\s([^\r\n].*)/g),l.commonName=s?s.length>1?s.sort((function(e,t){var r=e[1].toUpperCase(),n=t[1].toUpperCase();return n>r?-1:r>n?1:0})).sort((function(e,t){return e[1].length-t[1].length})).map((function(e){return e[1]})):s[0][1]:"",s=Je(n,/emailAddress\s=\s([^\r\n].*)/g),l.emailAddress=s?s.length>1?s.sort((function(e,t){var r=e[1].toUpperCase(),n=t[1].toUpperCase();return n>r?-1:r>n?1:0})).sort((function(e,t){return e[1].length-t[1].length})).map((function(e){return e[1]})):s[0][1]:"",s=Je(n,/\sDC\s=\s([^\r\n].*)/g),l.dc=s?s.length>1?s.sort((function(e,t){var r=e[1].toUpperCase(),n=t[1].toUpperCase();return n>r?-1:r>n?1:0})).sort((function(e,t){return e[1].length-t[1].length})).map((function(e){return e[1]})):s[0][1]:""}if((i=e.match(/\s*Issuer:\r?\n(\s*([a-zA-Z0-9.]+)\s=\s[^\r\n].*\r?\n)*\s*\b/))&&i.length>1){for(s=Je(i=i[0],/\s([a-zA-Z0-9.]+)\s=\s([^\r\n].*)/g),c=0;c<s.length;c++)(a=s[c][1].toString()).match("(C|ST|L|O|OU|CN|emailAddress|DC)")||(l.issuer[a]=s[c][2].toString());s=i.match(/\sC\s=\s([^\r\n].*?)[\r\n]/),l.issuer.country=s&&s[1]||"",s=i.match(/\sST\s=\s([^\r\n].*?)[\r\n]/),l.issuer.state=s&&s[1]||"",s=i.match(/\sL\s=\s([^\r\n].*?)[\r\n]/),l.issuer.locality=s&&s[1]||"",s=Je(i,/\sO\s=\s([^\r\n].*)/g),l.issuer.organization=s?s.length>1?s.sort((function(e,t){var r=e[1].toUpperCase(),n=t[1].toUpperCase();return n>r?-1:r>n?1:0})).sort((function(e,t){return e[1].length-t[1].length})).map((function(e){return e[1]})):s[0][1]:"",s=Je(i,/\sOU\s=\s([^\r\n].*)/g),l.issuer.organizationUnit=s?s.length>1?s.sort((function(e,t){var r=e[1].toUpperCase(),n=t[1].toUpperCase();return n>r?-1:r>n?1:0})).sort((function(e,t){return e[1].length-t[1].length})).map((function(e){return e[1]})):s[0][1]:"",s=Je(i,/\sCN\s=\s([^\r\n].*)/g),l.issuer.commonName=s?s.length>1?s.sort((function(e,t){var r=e[1].toUpperCase(),n=t[1].toUpperCase();return n>r?-1:r>n?1:0})).sort((function(e,t){return e[1].length-t[1].length})).map((function(e){return e[1]})):s[0][1]:"",s=Je(i,/\sDC\s=\s([^\r\n].*)/g),l.issuer.dc=s?s.length>1?s.sort((function(e,t){var r=e[1].toUpperCase(),n=t[1].toUpperCase();return n>r?-1:r>n?1:0})).sort((function(e,t){return e[1].length-t[1].length})).map((function(e){return e[1]})):s[0][1]:""}(o=e.match(/X509v3 Subject Alternative Name: \r?\n([^\r\n]*)\r?\n/))&&o.length>1&&(o=o[1].trim()+"\n",l.san={},s=Xe("DNS:([^,\\r\\n].*?)[,\\r\\n\\s]",o),l.san.dns=s||"",s=Xe("IP Address:([^,\\r\\n].*?)[,\\r\\n\\s]",o),l.san.ip=s||"",s=Xe("email:([^,\\r\\n].*?)[,\\r\\n\\s]",o),l.san.email=s||""),(s=e.match(/Not Before\s?:\s?([^\r\n]*)\r?\n/))&&s.length>1&&(u.start=Date.parse(s&&s[1]||"")),(s=e.match(/Not After\s?:\s?([^\r\n]*)\r?\n/))&&s.length>1&&(u.end=Date.parse(s&&s[1]||"")),u.start&&u.end&&(l.validity=u),(s=e.match(/Signature Algorithm: ([^\r\n]*)\r?\n/))&&s.length>1&&(l.signatureAlgorithm=s&&s[1]||""),(s=e.match(/Public[ -]Key: ([^\r\n]*)\r?\n/))&&s.length>1&&(l.publicKeySize=(s&&s[1]||"").replace(/[()]/g,"")),(s=e.match(/Public Key Algorithm: ([^\r\n]*)\r?\n/))&&s.length>1&&(l.publicKeyAlgorithm=s&&s[1]||""),t(null,l)}catch(e){t(e)}}(n,t)}))}function qe(e,t,r,n){n||r||"function"!=typeof t?!n&&r&&"function"==typeof r&&(n=r,r=!1):(n=t,t=void 0,r=!1),r&&"md5"!==r&&(r=!1);var s=[(e=Buffer.isBuffer(e)&&e.toString()||e).match(/BEGIN(\sNEW)? CERTIFICATE REQUEST/)?"req":e.match(/BEGIN RSA PRIVATE KEY/)||e.match(/BEGIN PRIVATE KEY/)?"rsa":"x509","-noout","-modulus","-in","--TMPFILE--"],i=[];t&&Le.createPasswordFile({cipher:"",password:t,passType:"in"},s,i),Re.spawnWrapper(s,e,(function(e,t,s,o){Le.deleteTempFiles(i,(function(t){!function(e){if(e)return n(e);var t=s.match(/Modulus=([0-9a-fA-F]+)$/m);t?n(null,{modulus:r?j(r)(t[1]):t[1]}):n(new Error("No modulus"))}(e||t||o)}))}))}function Ke(e,t){e=Buffer.isBuffer(e)&&e.toString()||e;Re.spawnWrapper(["dhparam","-text","-in","--TMPFILE--"],e,(function(e,r,n,s){if(e)return t(e);if(s)return t(s);var i={},o=n.match(/Parameters: \((\d+) bit\)/);o&&(i.size=Number(o[1]));var a="";return n.split("\n").forEach((function(e){/\s+([0-9a-f][0-9a-f]:)+[0-9a-f]?[0-9a-f]?/g.test(e)&&(a+=e.trim())})),a&&(i.prime=a),o||a?t(null,i):t(new Error("No DH info found"))}))}function $e(e,t,r){r||"function"!=typeof t||(r=t,t=void 0);var n=["x509","-in","--TMPFILE--","-fingerprint","-noout","-"+(t=t||"sha1")];Re.spawnWrapper(n,e,(function(e,t,n,s){if(e)return r(e);if(s)return r(s);var i=n.match(/Fingerprint=([0-9a-fA-F:]+)$/m);return i?r(null,{fingerprint:i[1]}):r(new Error("No fingerprint"))}))}function Ge(e,t,r,n,s){s||"function"!=typeof n||(s=n,n={});var i=["pkcs12","-export"],o=[];n.cipher&&n.clientKeyPassword&&Le.createPasswordFile({cipher:n.cipher,password:n.clientKeyPassword,passType:"in"},i,o),Le.createPasswordFile({cipher:"",password:r,passType:"word"},i,o),i.push("-in"),i.push("--TMPFILE--"),i.push("-inkey"),i.push("--TMPFILE--");var a=[t,e];n.certFiles&&(a.push(n.certFiles.join("")),i.push("-certfile"),i.push("--TMPFILE--")),Re.execBinary(i,a,(function(e,t){Le.deleteTempFiles(o,(function(r){var n;(n=e||r)?s(n):s(null,{pkcs12:t})}))}))}function Ve(e,t,r){r||"function"!=typeof t||(r=t,t={}),t.p12Password=t.p12Password||"";var n=[],s=[],i=["pkcs12","-in",e];Le.createPasswordFile({cipher:"",password:t.p12Password,passType:"in"},i,s),Buffer.isBuffer(e)&&(n=[e],i[2]="--TMPFILE--"),t.clientKeyPassword?Le.createPasswordFile({cipher:"",password:t.clientKeyPassword,passType:"out"},i,s):i.push("-nodes"),Re.execBinary(i,n,(function(e,n){Le.deleteTempFiles(s,(function(s){!function(e){var s={};if(e&&-1!==e.message.indexOf("No such file or directory")&&(e.code="ENOENT"),!e){var i=Ze(n,"-----BEGIN CERTIFICATE-----","-----END CERTIFICATE-----");if(s.cert=i.shift(),s.ca=i,s.key=Ze(n,"-----BEGIN PRIVATE KEY-----","-----END PRIVATE KEY-----").pop(),s.key)return Re.exec(["rsa","-in","--TMPFILE--"],"RSA PRIVATE KEY",[s.key],(function(e,t){return s.key=t,r(e,s)}));t.clientKeyPassword?s.key=Ze(n,"-----BEGIN ENCRYPTED PRIVATE KEY-----","-----END ENCRYPTED PRIVATE KEY-----").pop():s.key=Ze(n,"-----BEGIN RSA PRIVATE KEY-----","-----END RSA PRIVATE KEY-----").pop()}r(e,s)}(e||s)}))}))}function ze(e,t,r){var n,s=[];r||"function"!=typeof t||(r=t,t=void 0),e=(e||"").toString(),n=e.match(/BEGIN(\sNEW)? CERTIFICATE REQUEST/)?["req","-text","-noout","-verify","-in","--TMPFILE--"]:e.match(/BEGIN RSA PRIVATE KEY/)||e.match(/BEGIN PRIVATE KEY/)?["rsa","-noout","-check","-in","--TMPFILE--"]:["x509","-text","-noout","-in","--TMPFILE--"],t&&Le.createPasswordFile({cipher:"",password:t,passType:"in"},n,s),Re.spawnWrapper(n,e,(function(e,t,i,o){Le.deleteTempFiles(s,(function(t){!function(e){if(e&&"verify OK"!==e.toString().trim())return r(e);var t;t="rsa"===n[0]?/^Rsa key ok$/i.test(i.trim()):/Signature Algorithm/im.test(i);r(null,t)}(e||t||o)}))}))}function Ye(e,t,r){r||"function"!=typeof t||(r=t,t="");var n=[],s=[],i=["pkcs12","-info","-in",e,"-noout","-maciter","-nodes"];Le.createPasswordFile({cipher:"",password:t,passType:"in"},i,s),Buffer.isBuffer(e)&&(n=[e],i[3]="--TMPFILE--"),Re.spawnWrapper(i,n,(function(e,t,n,i){Le.deleteTempFiles(s,(function(t){!function(e){if(e)return r(e);r(null,/MAC verified OK/im.test(i)||!/MAC verified OK/im.test(i)&&!/Mac verify error/im.test(i))}(e||t)}))}))}function He(e,t,r){r||"function"!=typeof t||(r=t,t=void 0),Array.isArray(e)||(e=[e]),Array.isArray(t)||void 0===t||""!==t&&(t=[t]);var n=[];void 0!==t&&n.push(t.join("\n")),n.push(e.join("\n"));var s=["verify"];void 0!==t&&(s.push("-CAfile"),s.push("--TMPFILE--")),s.push("--TMPFILE--"),Re.spawnWrapper(s,n,(function(e,t,n,s){if(e)return r(e);r(null,": OK"===n.trim().slice(-4))}))}function Je(e,t){var r=[];return e.replace(t,(function(){var e=[].slice.call(arguments,0),t=e.splice(-2);e.index=t[0],e.input=t[1],r.push(e)})),r.length?r:null}function Xe(e,t){for(var r,n,s=new RegExp(e,"g"),i=t.match(s)||[],o=[],a=0;a<i.length;a++)r=new RegExp(e),n=i[a].match(r),o.push(n[1]);return o}function Ze(e,t,r){Buffer.isBuffer(e)&&(e=e.toString("utf8"));var n=[];if(!e)return n;for(var s=e.indexOf(t);-1!==s;){var i=(e=e.substring(s)).indexOf(r);if(-1===i)break;i+=r.length,n.push(e.substring(0,i)),s=e.indexOf(t,i)}return n}q.promisified={createPrivateKey:Ie(Fe),createDhparam:Ie(Me),createEcparam:Ie(Ue),createCSR:Ie(Be),createCertificate:Ie(We),readCertificateInfo:Ie(je),getPublicKey:Ie(De),getFingerprint:Ie($e),getModulus:Ie(qe),getDhparamInfo:Ie(Ke),createPkcs12:Ie(Ge),readPkcs12:Ie(Ve),verifySigningChain:Ie(He),checkCertificate:Ie(ze),checkPkcs12:Ie(Ye)};var Qe={exports:{}};
9
+ /*! https://mths.be/base64 v1.0.0 by @mathias | MIT license */!function(e,t){!function(r){var n=t,s=e&&e.exports==n&&e,i="object"==typeof D&&D;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,u={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,u=e.length-i;++l<u;)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=u;else for(var f in u)u.hasOwnProperty(f)&&(n[f]=u[f]);else r.base64=u}(D)}(Qe,Qe.exports);var et={exports:{}},tt={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:rt}=tt;function nt(e,t){if(0===e.length)return rt;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?r.slice(0,n):r}function st(e,t,r,n,s){for(let i=0;i<s;i++)r[n+i]=e[i]^t[3&i]}function it(e,t){for(let r=0;r<e.length;r++)e[r]^=t[3&r]}function ot(e){return e.byteLength===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)}function at(e){if(at.readOnly=!0,Buffer.isBuffer(e))return e;let t;return e instanceof ArrayBuffer?t=Buffer.from(e):ArrayBuffer.isView(e)?t=Buffer.from(e.buffer,e.byteOffset,e.byteLength):(t=Buffer.from(e),at.readOnly=!1),t}try{const e=require("bufferutil");et.exports={concat:nt,mask(t,r,n,s,i){i<48?st(t,r,n,s,i):e.mask(t,r,n,s,i)},toArrayBuffer:ot,toBuffer:at,unmask(t,r){t.length<32?it(t,r):e.unmask(t,r)}}}catch(e){et.exports={concat:nt,mask:st,toArrayBuffer:ot,toBuffer:at,unmask:it}}const ct=Symbol("kDone"),lt=Symbol("kRun");var ut=class{constructor(e){this[ct]=()=>{this.pending--,this[lt]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[lt]()}[lt](){if(this.pending!==this.concurrency&&this.jobs.length){const e=this.jobs.shift();this.pending++,e(this[ct])}}};const ft=x.default,ht=et.exports,pt=ut,{kStatusCode:dt}=tt,mt=Buffer.from([0,0,255,255]),_t=Symbol("permessage-deflate"),yt=Symbol("total-length"),gt=Symbol("callback"),vt=Symbol("buffers"),Et=Symbol("error");let wt;var bt=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,!wt){const e=void 0!==this._options.concurrencyLimit?this._options.concurrencyLimit:10;wt=new pt(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[gt];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){wt.add((n=>{this._decompress(e,t,((e,t)=>{n(),r(e,t)}))}))}compress(e,t,r){wt.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]?ft.Z_DEFAULT_WINDOWBITS:this.params[e];this._inflate=ft.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[_t]=this,this._inflate[yt]=0,this._inflate[vt]=[],this._inflate.on("error",kt),this._inflate.on("data",xt)}this._inflate[gt]=r,this._inflate.write(e),t&&this._inflate.write(mt),this._inflate.flush((()=>{const e=this._inflate[Et];if(e)return this._inflate.close(),this._inflate=null,void r(e);const s=ht.concat(this._inflate[vt],this._inflate[yt]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[yt]=0,this._inflate[vt]=[],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]?ft.Z_DEFAULT_WINDOWBITS:this.params[e];this._deflate=ft.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[yt]=0,this._deflate[vt]=[],this._deflate.on("data",St)}this._deflate[gt]=r,this._deflate.write(e),this._deflate.flush(ft.Z_SYNC_FLUSH,(()=>{if(!this._deflate)return;let e=ht.concat(this._deflate[vt],this._deflate[yt]);t&&(e=e.slice(0,e.length-4)),this._deflate[gt]=null,this._deflate[yt]=0,this._deflate[vt]=[],t&&this.params[`${n}_no_context_takeover`]&&this._deflate.reset(),r(null,e)}))}};function St(e){this[vt].push(e),this[yt]+=e.length}function xt(e){this[yt]+=e.length,this[_t]._maxPayload<1||this[yt]<=this[_t]._maxPayload?this[vt].push(e):(this[Et]=new RangeError("Max payload size exceeded"),this[Et].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Et][dt]=1009,this.removeListener("data",xt),this.reset())}function kt(e){this[_t]._inflate=null,e[dt]=1007,this[gt](e)}var Tt={exports:{}};const Pt=[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];function Ct(e){return e>=1e3&&e<=1014&&1004!==e&&1005!==e&&1006!==e||e>=3e3&&e<=4999}function Nt(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}try{const e=require("utf-8-validate");Tt.exports={isValidStatusCode:Ct,isValidUTF8:t=>t.length<150?Nt(t):e(t),tokenChars:Pt}}catch(e){Tt.exports={isValidStatusCode:Ct,isValidUTF8:Nt,tokenChars:Pt}}const{Writable:Ot}=b.default,It=bt,{BINARY_TYPES:At,EMPTY_BUFFER:Lt,kStatusCode:Rt,kWebSocket:Ft}=tt,{concat:Mt,toArrayBuffer:Ut,unmask:Bt}=et.exports,{isValidStatusCode:Wt,isValidUTF8:Dt}=Tt.exports;var jt=class extends Ot{constructor(e={}){super(),this._binaryType=e.binaryType||At[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=0|e.maxPayload,this._skipUTF8Validation=!!e.skipUTF8Validation,this[Ft]=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]=t.slice(e),t.slice(0,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]=r.slice(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,qt(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[It.extensionName])return this._loop=!1,qt(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,qt(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");if(!this._fragmented)return this._loop=!1,qt(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,qt(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,qt(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");if(!this._fin)return this._loop=!1,qt(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");if(t)return this._loop=!1,qt(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");if(this._payloadLength>125)return this._loop=!1,qt(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,qt(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK")}else if(this._masked)return this._loop=!1,qt(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,qt(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,qt(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=Lt;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])&&Bt(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[It.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(qt(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?Mt(t,e):"arraybuffer"===this._binaryType?Ut(Mt(t,e)):t,this.emit("message",r,!0)}else{const r=Mt(t,e);if(!this._skipUTF8Validation&&!Dt(r))return this._loop=!1,qt(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,Lt),this.end();else{if(1===e.length)return qt(RangeError,"invalid payload length 1",!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");{const t=e.readUInt16BE(0);if(!Wt(t))return qt(RangeError,`invalid status code ${t}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");const r=e.slice(2);if(!this._skipUTF8Validation&&!Dt(r))return qt(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 qt(e,t,r,n,s){const i=new e(r?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(i,qt),i.code=s,i[Rt]=n,i}const{randomFillSync:Kt}=g.default,$t=bt,{EMPTY_BUFFER:Gt}=tt,{isValidStatusCode:Vt}=Tt.exports,{mask:zt,toBuffer:Yt}=et.exports,Ht=Symbol("kByteLength"),Jt=Buffer.alloc(4);class Xt{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||Jt,t.generateMask?t.generateMask(r):Kt(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[Ht]?(e=Buffer.from(e)).length:t[Ht]:(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?(zt(e,r,c,i,n),[c]):(zt(e,r,e,0,n),[c,e])):[c,e]}close(e,t,r,n){let s;if(void 0===e)s=Gt;else{if("number"!=typeof e||!Vt(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={[Ht]: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(Xt.frame(s,i),n)}ping(e,t,r){let n,s;if("string"==typeof e?(n=Buffer.byteLength(e),s=!1):(n=(e=Yt(e)).length,s=Yt.readOnly),n>125)throw new RangeError("The data size must not be greater than 125 bytes");const i={[Ht]: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(Xt.frame(e,i),r)}pong(e,t,r){let n,s;if("string"==typeof e?(n=Buffer.byteLength(e),s=!1):(n=(e=Yt(e)).length,s=Yt.readOnly),n>125)throw new RangeError("The data size must not be greater than 125 bytes");const i={[Ht]: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(Xt.frame(e,i),r)}send(e,t,r){const n=this._extensions[$t.extensionName];let s,i,o=t.binary?2:1,a=t.compress;if("string"==typeof e?(s=Buffer.byteLength(e),i=!1):(s=(e=Yt(e)).length,i=Yt.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={[Ht]: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(Xt.frame(e,{[Ht]: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(Xt.frame(e,r),n);const s=this._extensions[$t.extensionName];this._bufferedBytes+=r[Ht],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[Ht],this._deflating=!1,r.readOnly=!1,this.sendFrame(Xt.frame(t,r),n),this.dequeue()}))}dequeue(){for(;!this._deflating&&this._queue.length;){const e=this._queue.shift();this._bufferedBytes-=e[3][Ht],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Ht],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 Zt=Xt;const{kForOnEventAttribute:Qt,kListener:er}=tt,tr=Symbol("kCode"),rr=Symbol("kData"),nr=Symbol("kError"),sr=Symbol("kMessage"),ir=Symbol("kReason"),or=Symbol("kTarget"),ar=Symbol("kType"),cr=Symbol("kWasClean");class lr{constructor(e){this[or]=null,this[ar]=e}get target(){return this[or]}get type(){return this[ar]}}Object.defineProperty(lr.prototype,"target",{enumerable:!0}),Object.defineProperty(lr.prototype,"type",{enumerable:!0});class ur extends lr{constructor(e,t={}){super(e),this[tr]=void 0===t.code?0:t.code,this[ir]=void 0===t.reason?"":t.reason,this[cr]=void 0!==t.wasClean&&t.wasClean}get code(){return this[tr]}get reason(){return this[ir]}get wasClean(){return this[cr]}}Object.defineProperty(ur.prototype,"code",{enumerable:!0}),Object.defineProperty(ur.prototype,"reason",{enumerable:!0}),Object.defineProperty(ur.prototype,"wasClean",{enumerable:!0});class fr extends lr{constructor(e,t={}){super(e),this[nr]=void 0===t.error?null:t.error,this[sr]=void 0===t.message?"":t.message}get error(){return this[nr]}get message(){return this[sr]}}Object.defineProperty(fr.prototype,"error",{enumerable:!0}),Object.defineProperty(fr.prototype,"message",{enumerable:!0});class hr extends lr{constructor(e,t={}){super(e),this[rr]=void 0===t.data?null:t.data}get data(){return this[rr]}}Object.defineProperty(hr.prototype,"data",{enumerable:!0});const pr={addEventListener(e,t,r={}){let n;if("message"===e)n=function(e,r){const n=new hr("message",{data:r?e:e.toString()});n[or]=this,t.call(this,n)};else if("close"===e)n=function(e,r){const n=new ur("close",{code:e,reason:r.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});n[or]=this,t.call(this,n)};else if("error"===e)n=function(e){const r=new fr("error",{error:e,message:e.message});r[or]=this,t.call(this,r)};else{if("open"!==e)return;n=function(){const e=new lr("open");e[or]=this,t.call(this,e)}}n[Qt]=!!r[Qt],n[er]=t,r.once?this.once(e,n):this.on(e,n)},removeEventListener(e,t){for(const r of this.listeners(e))if(r[er]===t&&!r[Qt]){this.removeListener(e,r);break}}};var dr={CloseEvent:ur,ErrorEvent:fr,Event:lr,EventTarget:pr,MessageEvent:hr};const{tokenChars:mr}=Tt.exports;function _r(e,t,r){void 0===e[t]?e[t]=[r]:e[t].push(r)}var yr={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,u=-1,f=0;for(;f<e.length;f++)if(l=e.charCodeAt(f),void 0===r)if(-1===u&&1===mr[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===u&&(u=f);const n=e.slice(c,u);44===l?(_r(t,n,s),s=Object.create(null)):r=n,c=u=-1}}else-1===u&&-1!==c&&(u=f);else if(void 0===n)if(-1===u&&1===mr[l])-1===c&&(c=f);else if(32===l||9===l)-1===u&&-1!==c&&(u=f);else if(59===l||44===l){if(-1===c)throw new SyntaxError(`Unexpected character at index ${f}`);-1===u&&(u=f),_r(s,e.slice(c,u),!0),44===l&&(_r(t,r,s),s=Object.create(null),r=void 0),c=u=-1}else{if(61!==l||-1===c||-1!==u)throw new SyntaxError(`Unexpected character at index ${f}`);n=e.slice(c,f),c=u=-1}else if(o){if(1!==mr[l])throw new SyntaxError(`Unexpected character at index ${f}`);-1===c?c=f:i||(i=!0),o=!1}else if(a)if(1===mr[l])-1===c&&(c=f);else if(34===l&&-1!==c)a=!1,u=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===u&&1===mr[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===u&&(u=f);let o=e.slice(c,u);i&&(o=o.replace(/\\/g,""),i=!1),_r(s,n,o),44===l&&(_r(t,r,s),s=Object.create(null),r=void 0),n=void 0,c=u=-1}}else-1===u&&(u=f);if(-1===c||a||32===l||9===l)throw new SyntaxError("Unexpected end of input");-1===u&&(u=f);const h=e.slice(c,u);return void 0===r?_r(t,h,s):(void 0===n?_r(s,h,!0):_r(s,n,i?h.replace(/\\/g,""):h),_r(t,r,s)),t}};const gr=E.default,vr=d.default,Er=p.default,wr=_.default,br=w.default,{randomBytes:Sr,createHash:xr}=g.default,{URL:kr}=S.default,Tr=bt,Pr=jt,Cr=Zt,{BINARY_TYPES:Nr,EMPTY_BUFFER:Or,GUID:Ir,kForOnEventAttribute:Ar,kListener:Lr,kStatusCode:Rr,kWebSocket:Fr,NOOP:Mr}=tt,{EventTarget:{addEventListener:Ur,removeEventListener:Br}}=dr,{format:Wr,parse:Dr}=yr,{toBuffer:jr}=et.exports,qr=["CONNECTING","OPEN","CLOSING","CLOSED"],Kr=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,$r=[8,13];class Gr extends gr{constructor(e,t,r){super(),this._binaryType=Nr[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Or,this._closeTimer=null,this._extensions={},this._paused=!1,this._protocol="",this._readyState=Gr.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]),zr(this,e,t,r)):this._isServer=!0}get binaryType(){return this._binaryType}set binaryType(e){Nr.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 Pr({binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation});this._sender=new Cr(e,this._extensions,r.generateMask),this._receiver=n,this._socket=e,n[Fr]=this,e[Fr]=this,n.on("conclude",Qr),n.on("drain",en),n.on("error",tn),n.on("message",nn),n.on("ping",sn),n.on("pong",on),e.setTimeout(0),e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",cn),e.on("data",ln),e.on("end",un),e.on("error",fn),this._readyState=Gr.OPEN,this.emit("open")}emitClose(){if(!this._socket)return this._readyState=Gr.CLOSED,void this.emit("close",this._closeCode,this._closeMessage);this._extensions[Tr.extensionName]&&this._extensions[Tr.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=Gr.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,t){if(this.readyState!==Gr.CLOSED){if(this.readyState===Gr.CONNECTING){const e="WebSocket was closed before the connection was established";return Xr(this,this._req,e)}this.readyState!==Gr.CLOSING?(this._readyState=Gr.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()}}pause(){this.readyState!==Gr.CONNECTING&&this.readyState!==Gr.CLOSED&&(this._paused=!0,this._socket.pause())}ping(e,t,r){if(this.readyState===Gr.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===Gr.OPEN?(void 0===t&&(t=!this._isServer),this._sender.ping(e||Or,t,r)):Zr(this,e,r)}pong(e,t,r){if(this.readyState===Gr.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===Gr.OPEN?(void 0===t&&(t=!this._isServer),this._sender.pong(e||Or,t,r)):Zr(this,e,r)}resume(){this.readyState!==Gr.CONNECTING&&this.readyState!==Gr.CLOSED&&(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,t,r){if(this.readyState===Gr.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!==Gr.OPEN)return void Zr(this,e,r);const n={binary:"string"!=typeof e,mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[Tr.extensionName]||(n.compress=!1),this._sender.send(e||Or,n,r)}terminate(){if(this.readyState!==Gr.CLOSED){if(this.readyState===Gr.CONNECTING){const e="WebSocket was closed before the connection was established";return Xr(this,this._req,e)}this._socket&&(this._readyState=Gr.CLOSING,this._socket.destroy())}}}Object.defineProperty(Gr,"CONNECTING",{enumerable:!0,value:qr.indexOf("CONNECTING")}),Object.defineProperty(Gr.prototype,"CONNECTING",{enumerable:!0,value:qr.indexOf("CONNECTING")}),Object.defineProperty(Gr,"OPEN",{enumerable:!0,value:qr.indexOf("OPEN")}),Object.defineProperty(Gr.prototype,"OPEN",{enumerable:!0,value:qr.indexOf("OPEN")}),Object.defineProperty(Gr,"CLOSING",{enumerable:!0,value:qr.indexOf("CLOSING")}),Object.defineProperty(Gr.prototype,"CLOSING",{enumerable:!0,value:qr.indexOf("CLOSING")}),Object.defineProperty(Gr,"CLOSED",{enumerable:!0,value:qr.indexOf("CLOSED")}),Object.defineProperty(Gr.prototype,"CLOSED",{enumerable:!0,value:qr.indexOf("CLOSED")}),["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach((e=>{Object.defineProperty(Gr.prototype,e,{enumerable:!0})})),["open","error","close","message"].forEach((e=>{Object.defineProperty(Gr.prototype,`on${e}`,{enumerable:!0,get(){for(const t of this.listeners(e))if(t[Ar])return t[Lr];return null},set(t){for(const t of this.listeners(e))if(t[Ar]){this.removeListener(e,t);break}"function"==typeof t&&this.addEventListener(e,t,{[Ar]:!0})}})})),Gr.prototype.addEventListener=Ur,Gr.prototype.removeEventListener=Br;var Vr=Gr;function zr(e,t,r,n){const s={protocolVersion:$r[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:void 0,host:void 0,path:void 0,port:void 0};if(!$r.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${$r.join(", ")})`);let i;if(t instanceof kr)i=t,e._url=t.href;else{try{i=new kr(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 Yr(e,t)}const l=o?443:80,u=Sr(16).toString("base64"),f=o?vr.get:Er.get,h=new Set;let p;if(s.createConnection=o?Jr:Hr,s.defaultPort=s.defaultPort||l,s.port=i.port||l,s.host=i.hostname.startsWith("[")?i.hostname.slice(1,-1):i.hostname,s.headers={"Sec-WebSocket-Version":s.protocolVersion,"Sec-WebSocket-Key":u,Connection:"Upgrade",Upgrade:"websocket",...s.headers},s.path=i.pathname+i.search,s.timeout=s.handshakeTimeout,s.perMessageDeflate&&(p=new Tr(!0!==s.perMessageDeflate?s.perMessageDeflate:{},!1,s.maxPayload),s.headers["Sec-WebSocket-Extensions"]=Wr({[Tr.extensionName]:p.offer()})),r.length){for(const e of r){if("string"!=typeof e||!Kr.test(e)||h.has(e))throw new SyntaxError("An invalid or duplicated subprotocol was specified");h.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._originalHost=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 i.host!==e._originalHost&&(delete s.headers.authorization,delete s.headers.cookie,delete s.headers.host,s.auth=void 0);s.auth&&!n.headers.authorization&&(n.headers.authorization="Basic "+Buffer.from(s.auth).toString("base64"))}let d=e._req=f(s);s.timeout&&d.on("timeout",(()=>{Xr(e,d,"Opening handshake has timed out")})),d.on("error",(t=>{null===d||d.aborted||(d=e._req=null,Yr(e,t))})),d.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 Xr(e,d,"Maximum redirects exceeded");let i;d.abort();try{i=new kr(o,t)}catch(t){const r=new SyntaxError(`Invalid URL: ${o}`);return void Yr(e,r)}zr(e,i,r,n)}else e.emit("unexpected-response",d,i)||Xr(e,d,`Unexpected server response: ${i.statusCode}`)})),d.on("upgrade",((t,r,n)=>{if(e.emit("upgrade",t),e.readyState!==Gr.CONNECTING)return;d=e._req=null;const i=xr("sha1").update(u+Ir).digest("base64");if(t.headers["sec-websocket-accept"]!==i)return void Xr(e,r,"Invalid Sec-WebSocket-Accept header");const o=t.headers["sec-websocket-protocol"];let a;if(void 0!==o?h.size?h.has(o)||(a="Server sent an invalid subprotocol"):a="Server sent a subprotocol but none was requested":h.size&&(a="Server sent no subprotocol"),a)return void Xr(e,r,a);o&&(e._protocol=o);const c=t.headers["sec-websocket-extensions"];if(void 0!==c){if(!p){return void Xr(e,r,"Server sent a Sec-WebSocket-Extensions header but no extension was requested")}let t;try{t=Dr(c)}catch(t){return void Xr(e,r,"Invalid Sec-WebSocket-Extensions header")}const n=Object.keys(t);if(1!==n.length||n[0]!==Tr.extensionName){return void Xr(e,r,"Server indicated an extension that was not requested")}try{p.accept(t[Tr.extensionName])}catch(t){return void Xr(e,r,"Invalid Sec-WebSocket-Extensions header")}e._extensions[Tr.extensionName]=p}e.setSocket(r,n,{generateMask:s.generateMask,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})}))}function Yr(e,t){e._readyState=Gr.CLOSING,e.emit("error",t),e.emitClose()}function Hr(e){return e.path=e.socketPath,wr.connect(e)}function Jr(e){return e.path=void 0,e.servername||""===e.servername||(e.servername=wr.isIP(e.host)?"":e.host),br.connect(e)}function Xr(e,t,r){e._readyState=Gr.CLOSING;const n=new Error(r);Error.captureStackTrace(n,Xr),t.setHeader?(t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),t.once("abort",e.emitClose.bind(e)),e.emit("error",n)):(t.destroy(n),t.once("error",e.emit.bind(e,"error")),t.once("close",e.emitClose.bind(e)))}function Zr(e,t,r){if(t){const r=jr(t).length;e._socket?e._sender._bufferedBytes+=r:e._bufferedAmount+=r}if(r){r(new Error(`WebSocket is not open: readyState ${e.readyState} (${qr[e.readyState]})`))}}function Qr(e,t){const r=this[Fr];r._closeFrameReceived=!0,r._closeMessage=t,r._closeCode=e,void 0!==r._socket[Fr]&&(r._socket.removeListener("data",ln),process.nextTick(an,r._socket),1005===e?r.close():r.close(e,t))}function en(){const e=this[Fr];e.isPaused||e._socket.resume()}function tn(e){const t=this[Fr];void 0!==t._socket[Fr]&&(t._socket.removeListener("data",ln),process.nextTick(an,t._socket),t.close(e[Rr])),t.emit("error",e)}function rn(){this[Fr].emitClose()}function nn(e,t){this[Fr].emit("message",e,t)}function sn(e){const t=this[Fr];t.pong(e,!t._isServer,Mr),t.emit("ping",e)}function on(e){this[Fr].emit("pong",e)}function an(e){e.resume()}function cn(){const e=this[Fr];let t;this.removeListener("close",cn),this.removeListener("data",ln),this.removeListener("end",un),e._readyState=Gr.CLOSING,this._readableState.endEmitted||e._closeFrameReceived||e._receiver._writableState.errorEmitted||null===(t=e._socket.read())||e._receiver.write(t),e._receiver.end(),this[Fr]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on("error",rn),e._receiver.on("finish",rn))}function ln(e){this[Fr]._receiver.write(e)||this.pause()}function un(){const e=this[Fr];e._readyState=Gr.CLOSING,e._receiver.end(),this.end()}function fn(){const e=this[Fr];this.removeListener("error",fn),this.on("error",Mr),e&&(e._readyState=Gr.CLOSING,this.destroy())}const{Duplex:hn}=b.default;function pn(e){e.emit("close")}function dn(){!this.destroyed&&this._writableState.finished&&this.destroy()}function mn(e){this.removeListener("error",mn),this.destroy(),0===this.listenerCount("error")&&this.emit("error",e)}var _n=function(e,t){let r=!0;const n=new hn({...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(pn,n);let i=!1;e.once("error",(function(e){i=!0,s(e)})),e.once("close",(function(){i||s(t),process.nextTick(pn,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",dn),n.on("error",mn),n};const{tokenChars:yn}=Tt.exports;var gn={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===yn[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 vn=E.default,En=p.default,{createHash:wn}=g.default,bn=yr,Sn=bt,xn=gn,kn=Vr,{GUID:Tn,kWebSocket:Pn}=tt,Cn=/^[+/0-9A-Za-z]{22}==$/;var Nn=class extends vn{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:kn,...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=En.createServer(((e,t)=>{const r=En.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(2===this._state)return e&&this.once("close",(()=>{e(new Error("The server is not running"))})),void process.nextTick(On,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(On,this);else{const e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close((()=>{On(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",In);const s=void 0!==e.headers["sec-websocket-key"]&&e.headers["sec-websocket-key"],i=+e.headers["sec-websocket-version"];if("GET"!==e.method||"websocket"!==e.headers.upgrade.toLowerCase()||!s||!Cn.test(s)||8!==i&&13!==i||!this.shouldHandle(e))return An(t,400);const o=e.headers["sec-websocket-protocol"];let a=new Set;if(void 0!==o)try{a=xn.parse(o)}catch(e){return An(t,400)}const c=e.headers["sec-websocket-extensions"],l={};if(this.options.perMessageDeflate&&void 0!==c){const e=new Sn(this.options.perMessageDeflate,!0,this.options.maxPayload);try{const t=bn.parse(c);t[Sn.extensionName]&&(e.accept(t[Sn.extensionName]),l[Sn.extensionName]=e)}catch(e){return An(t,400)}}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,u)=>{if(!i)return An(t,o||401,c,u);this.completeUpgrade(l,s,a,e,t,r,n)}));if(!this.options.verifyClient(o))return An(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[Pn])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>0)return An(s,503);const a=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${wn("sha1").update(t+Tn).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[Sn.extensionName]){const t=e[Sn.extensionName].params,r=bn.format({[Sn.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",In),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(On,this)}))),o(c,n)}};function On(e){e._state=2,e.emit("close")}function In(){this.destroy()}function An(e,t,r,n){e.writable&&(r=r||En.STATUS_CODES[t],n={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(r),...n},e.write(`HTTP/1.1 ${t} ${En.STATUS_CODES[t]}\r\n`+Object.keys(n).map((e=>`${e}: ${n[e]}`)).join("\r\n")+"\r\n\r\n"+r)),e.removeListener("error",In),e.destroy()}const Ln=Vr;Ln.createWebSocketStream=_n,Ln.Server=Nn,Ln.Receiver=jt,Ln.Sender=Zt,Ln.WebSocket=Ln,Ln.WebSocketServer=Ln.Server;var Rn=Ln,Fn=require("child_process"),Mn=require("events"),Un=require("url"),Bn=Rn.Server,Wn="mpeg1video",Dn=!1,jn="drawtext=x=w-tw-100:y=100:fontcolor=white:fontsize=36:text="+decodeURIComponent(Qe.exports.decode("JUU1JThFJUJCJUU5JTk5JUE0JUU2JUIwJUI0JUU1JThEJUIwUVElRUYlQkMlOUE0MjEzNTQ1MzI="))+":box=1:boxcolor=black,scale=-1:-1,eq=",qn=["vcodec","c:v","-c:v","codec:v"],Kn=["-s","-b:v","scale","contrast","brightness","saturation","gamma"].concat(qn),$n=["scale","contrast","brightness","saturation","gamma"],Gn=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"c:v":case"-c:v":case"codec:v":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}},Vn=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&&I(e,t)}(r,Mn.EventEmitter);var t=R(r);function r(e){var n;return T(this,r),N(A(n=t.call(this)),"exitCode",void 0),N(A(n),"additionalFlags",[]),N(A(n),"stream",null),N(A(n),"inputStreamStarted",!1),n.options=e,n.ffmpegPath=e.ffmpegPath||"ffmpeg",n.url=e.url,n.ffmpegOptions=e.ffmpegOptions,n.initMpeg2Muxer(),n}return C(r,[{key:"initMpeg2Muxer",value:function(){var e=this;if(this.ffmpegOptions)for(var t in this.ffmpegOptions)this.additionalFlags.push(t),""!==String(this.ffmpegOptions[t])&&this.additionalFlags.push(String(this.ffmpegOptions[t]));this.spawnOptions=["-rtsp_transport","tcp","-thread_queue_size","256","-i",this.url,"-f","mpegts"].concat(M(this.additionalFlags),["-codec:a","mp2",Dn?"-an":null,"-ar","44100","-ac","2","-nostats","-r","29.97","-"]),this.spawnOptions=this.spawnOptions.filter((function(e){return null!==e})),this.stream=Fn.spawn(this.ffmpegPath,this.spawnOptions,{detached:!1}),this.stream.on("error",(function(e,t){console.error("启动ffmpeg时出错,请确保你安装了ffmpeg,然后检查路径或者命令参数")})),this.stream.on("exit",(function(t,r){if(1===t)return console.error("***由于ffmpeg退出,ffmpeg启动不成功,请检查ffmpeg参数或相关情况或联系作者***"),e.exitCode=1,e.emit("exitWithError")})),this.stream.on("close",(function(t,r){return console.log("ffmpeg关闭,code:",t),e.emit("ffmpegClosed")})),this.inputStreamStarted=!0,this.stream.stdout.on("data",(function(t){return e.emit("mpeg2data",t)})),this.stream.stderr.on("data",(function(t){return e.emit("ffmpegStderr",t)}))}}]),r}(),zn=function(){function e(t){T(this,e),N(this,"freeTime",0),N(this,"isStreamWrap",!1),N(this,"clients",[]),N(this,"mpeg2Muxer",{instance:null,stream:null,data:null}),this.config=t,this.url=t.url}return C(e,[{key:"createStream",value:function(){var e=this;this.isStreamWrap||(console.log("创建一个新的ffmpeg子进程"),this.isStreamWrap=!0,this.mpeg2Muxer.instance=new Vn({ffmpegOptions:this.formatParams(this.config),url:this.url,ffmpegPath:"ffmpeg"}),this.mpeg2Muxer.stream=this.mpeg2Muxer.instance.stream,this.mpeg2Muxer.instance.on("mpeg2data",(function(t){e.broadcast(t)})),this.mpeg2Muxer.instance.on("exitWithError",(function(){})),this.mpeg2Muxer.instance.on("ffmpegClosed",(function(){e.destroy()})))}},{key:"formatParams",value:function(e){for(var t={"-codec:v":Wn,"-vf":jn},r=0,n=Object.entries(e);r<n.length;r++){var s=F(n[r],2),i=s[0],o=s[1];"wm"===i&&"0"===o&&(t["-vf"]="scale=-1:-1,eq="),Kn.includes(i)&&($n.includes(i)?"scale"===i?t["-vf"]=t["-vf"].replace(/scale=[x0-9\:\-]*/g,"scale=".concat(o)):t["-vf"]+="".concat(i,"=").concat(o,":"):qn.includes(i)?t["-codec:v"]=o:Gn(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=W(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("视频关闭,销毁一个client(ws句柄)"),t>-1&&this.clients.splice(t,1)}},{key:"dropAllClient",value:function(){var e,t=W(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}(),Yn=function(){function e(t){var r=this;T(this,e),N(this,"channels",[]),t&&"boolean"==typeof t.wm&&!t.wm&&(jn="scale=-1:-1,eq="),t&&"string"==typeof t.vcodec&&t.vcodec.length>0&&(Wn=t.vcodec),t&&"boolean"==typeof t.audio&&!t.audio&&(Dn=!0),setInterval((function(){return r.checkFree()}),1e4);var n=p.default.createServer();if(t&&"object"===k(t.wss))if(console.log("wss启动中...."),t.wss.hasOwnProperty("pfx"))if(t.wss.hasOwnProperty("passphrase"))try{var s={pfx:m.default.readFileSync(t.wss.pfx),passphrase:m.default.readFileSync(t.wss.passphrase)};q.readPkcs12(s.pfx,{p12Password:s.passphrase},(function(e,t){n=d.default.createServer({cert:t.cert,key:t.key})}))}catch(e){console.error("--【读取pfx安全证书文件出错,wss启动失败,退回到ws;错误信息如下,有问题请联系我】--"),console.log(e)}else console.error("【wss启动失败;请传入正确的pfx文件指定密码:passphrase】");else if(t.wss.hasOwnProperty("cert"))if(t.wss.hasOwnProperty("key"))try{n=d.default.createServer({cert:m.default.readFileSync(t.wss.cert),key:m.default.readFileSync(t.wss.key)})}catch(e){console.error("--【读取cert安全证书文件出错,wss启动失败,退回到ws;错误信息如下,有问题请联系我】--"),console.log(e)}else console.error("【wss启动失败;请传入正确的安全证书私钥:key】");else console.error("【wss启动失败;请传入正确的安全证书公钥:cert】");this.wss=new Bn({server:n}),this.wss.on("connection",(function(e,t){var n=Un.parse(t.url,!0);if(n.query.url){var s=Qe.exports.decode(n.query.url.toString());n.query.url=s,r.registeClient(e,{url:s,options:n.query})}console.log("一个新的client(ws句柄)连接成功")})),n.listen(t&&t.port||9999)}return C(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=W(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 zn(e,t);return this.channels.push(r),r}},{key:"checkFree",value:function(){var e,t=W(this.channels);try{for(t.s();!(e=t.n()).done;){var r=e.value;r.clients.length>0?r.freeTime=0:r.freeTime+=10,r.freeTime>=60&&this.destroyedChannel(r)}}catch(e){t.e(e)}finally{t.f()}}},{key:"destroyedChannel",value:function(e){var t=this.channels.indexOf(e);t>-1&&(this.channels.splice(t,1),e.destroy())}}]),e}();N(Yn,"version","2.4.7"),module.exports=Yn;
11
10
  //# sourceMappingURL=rtsp2web.js.map