nudbclient
Version:
Universal Realtime Database for Node.js and Browser
3 lines (2 loc) • 49.9 kB
JavaScript
import e from"events";import t from"https";import s from"http";import r from"net";import i from"tls";import o from"crypto";import n from"stream";import a from"url";import h from"zlib";import c from"buffer";function l(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function d(e,t){for(var s=0;s<t.length;s++){var r=t[s];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,p(r.key),r)}}function f(e,t,s){return(t=p(t))in e?Object.defineProperty(e,t,{value:s,enumerable:!0,configurable:!0,writable:!0}):e[t]=s,e}function u(e,t){var s=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),s.push.apply(s,r)}return s}function _(e){for(var t=1;t<arguments.length;t++){var s=null!=arguments[t]?arguments[t]:{};t%2?u(Object(s),!0).forEach((function(t){f(e,t,s[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(s)):u(Object(s)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(s,t))}))}return e}function p(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var s=e[Symbol.toPrimitive];if(void 0!==s){var r=s.call(e,t||"default");if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}var m,y,b,v,g,S,w,k={exports:{}};function E(){if(y)return m;y=1;const e=["nodebuffer","arraybuffer","fragments"],t="undefined"!=typeof Blob;return t&&e.push("blob"),m={BINARY_TYPES:e,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:t,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}}function x(){if(b)return k.exports;b=1;const{EMPTY_BUFFER:e}=E(),t=Buffer[Symbol.species];function s(e,t,s,r,i){for(let o=0;o<i;o++)s[r+o]=e[o]^t[3&o]}function r(e,t){for(let s=0;s<e.length;s++)e[s]^=t[3&s]}if(k.exports={concat:function(s,r){if(0===s.length)return e;if(1===s.length)return s[0];const i=Buffer.allocUnsafe(r);let o=0;for(let e=0;e<s.length;e++){const t=s[e];i.set(t,o),o+=t.length}return o<r?new t(i.buffer,i.byteOffset,o):i},mask:s,toArrayBuffer:function(e){return e.length===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.length)},toBuffer:function e(s){if(e.readOnly=!0,Buffer.isBuffer(s))return s;let r;return s instanceof ArrayBuffer?r=new t(s):ArrayBuffer.isView(s)?r=new t(s.buffer,s.byteOffset,s.byteLength):(r=Buffer.from(s),e.readOnly=!1),r},unmask:r},!process.env.WS_NO_BUFFER_UTIL)try{const e=require("bufferutil");k.exports.mask=function(t,r,i,o,n){n<48?s(t,r,i,o,n):e.mask(t,r,i,o,n)},k.exports.unmask=function(t,s){t.length<32?r(t,s):e.unmask(t,s)}}catch(e){}return k.exports}function O(){if(w)return S;w=1;const e=h,t=x(),s=function(){if(g)return v;g=1;const e=Symbol("kDone"),t=Symbol("kRun");return v=class{constructor(s){this[e]=()=>{this.pending--,this[t]()},this.concurrency=s||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[t]()}[t](){if(this.pending!==this.concurrency&&this.jobs.length){const t=this.jobs.shift();this.pending++,t(this[e])}}}}(),{kStatusCode:r}=E(),i=Buffer[Symbol.species],o=Buffer.from([0,0,255,255]),n=Symbol("permessage-deflate"),a=Symbol("total-length"),c=Symbol("callback"),l=Symbol("buffers"),d=Symbol("error");let f;function u(e){this[l].push(e),this[a]+=e.length}function _(e){this[a]+=e.length,this[n]._maxPayload<1||this[a]<=this[n]._maxPayload?this[l].push(e):(this[d]=new RangeError("Max payload size exceeded"),this[d].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[d][r]=1009,this.removeListener("data",_),this.reset())}function p(e){this[n]._inflate=null,this[d]?this[c](this[d]):(e[r]=1007,this[c](e))}return S=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,!f){const e=void 0!==this._options.concurrencyLimit?this._options.concurrencyLimit:10;f=new s(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[c];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,s=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(!s)throw new Error("None of the extension offers can be accepted");return t.serverNoContextTakeover&&(s.server_no_context_takeover=!0),t.clientNoContextTakeover&&(s.client_no_context_takeover=!0),"number"==typeof t.serverMaxWindowBits&&(s.server_max_window_bits=t.serverMaxWindowBits),"number"==typeof t.clientMaxWindowBits?s.client_max_window_bits=t.clientMaxWindowBits:!0!==s.client_max_window_bits&&!1!==t.clientMaxWindowBits||delete s.client_max_window_bits,s}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 s=e[t];if(s.length>1)throw new Error(`Parameter "${t}" must have only a single value`);if(s=s[0],"client_max_window_bits"===t){if(!0!==s){const e=+s;if(!Number.isInteger(e)||e<8||e>15)throw new TypeError(`Invalid value for parameter "${t}": ${s}`);s=e}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${t}": ${s}`)}else if("server_max_window_bits"===t){const e=+s;if(!Number.isInteger(e)||e<8||e>15)throw new TypeError(`Invalid value for parameter "${t}": ${s}`);s=e}else{if("client_no_context_takeover"!==t&&"server_no_context_takeover"!==t)throw new Error(`Unknown parameter "${t}"`);if(!0!==s)throw new TypeError(`Invalid value for parameter "${t}": ${s}`)}e[t]=s}))})),e}decompress(e,t,s){f.add((r=>{this._decompress(e,t,((e,t)=>{r(),s(e,t)}))}))}compress(e,t,s){f.add((r=>{this._compress(e,t,((e,t)=>{r(),s(e,t)}))}))}_decompress(s,r,i){const h=this._isServer?"client":"server";if(!this._inflate){const t=`${h}_max_window_bits`,s="number"!=typeof this.params[t]?e.Z_DEFAULT_WINDOWBITS:this.params[t];this._inflate=e.createInflateRaw({...this._options.zlibInflateOptions,windowBits:s}),this._inflate[n]=this,this._inflate[a]=0,this._inflate[l]=[],this._inflate.on("error",p),this._inflate.on("data",_)}this._inflate[c]=i,this._inflate.write(s),r&&this._inflate.write(o),this._inflate.flush((()=>{const e=this._inflate[d];if(e)return this._inflate.close(),this._inflate=null,void i(e);const s=t.concat(this._inflate[l],this._inflate[a]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[a]=0,this._inflate[l]=[],r&&this.params[`${h}_no_context_takeover`]&&this._inflate.reset()),i(null,s)}))}_compress(s,r,o){const n=this._isServer?"server":"client";if(!this._deflate){const t=`${n}_max_window_bits`,s="number"!=typeof this.params[t]?e.Z_DEFAULT_WINDOWBITS:this.params[t];this._deflate=e.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:s}),this._deflate[a]=0,this._deflate[l]=[],this._deflate.on("data",u)}this._deflate[c]=o,this._deflate.write(s),this._deflate.flush(e.Z_SYNC_FLUSH,(()=>{if(!this._deflate)return;let e=t.concat(this._deflate[l],this._deflate[a]);r&&(e=new i(e.buffer,e.byteOffset,e.length-4)),this._deflate[c]=null,this._deflate[a]=0,this._deflate[l]=[],r&&this.params[`${n}_no_context_takeover`]&&this._deflate.reset(),o(null,e)}))}}}var T,C,N,L,P,B,R,U,I,M,W,D,A,j,F,$,G,V,q,z,H,Y={exports:{}};function X(){if(T)return Y.exports;T=1;const{isUtf8:e}=c,{hasBlob:t}=E();function s(e){const t=e.length;let s=0;for(;s<t;)if(128&e[s])if(192==(224&e[s])){if(s+1===t||128!=(192&e[s+1])||192==(254&e[s]))return!1;s+=2}else if(224==(240&e[s])){if(s+2>=t||128!=(192&e[s+1])||128!=(192&e[s+2])||224===e[s]&&128==(224&e[s+1])||237===e[s]&&160==(224&e[s+1]))return!1;s+=3}else{if(240!=(248&e[s]))return!1;if(s+3>=t||128!=(192&e[s+1])||128!=(192&e[s+2])||128!=(192&e[s+3])||240===e[s]&&128==(240&e[s+1])||244===e[s]&&e[s+1]>143||e[s]>244)return!1;s+=4}else s++;return!0}if(Y.exports={isBlob:function(e){return t&&"object"==typeof e&&"function"==typeof e.arrayBuffer&&"string"==typeof e.type&&"function"==typeof e.stream&&("Blob"===e[Symbol.toStringTag]||"File"===e[Symbol.toStringTag])},isValidStatusCode:function(e){return e>=1e3&&e<=1014&&1004!==e&&1005!==e&&1006!==e||e>=3e3&&e<=4999},isValidUTF8:s,tokenChars:[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0]},e)Y.exports.isValidUTF8=function(t){return t.length<24?s(t):e(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{const e=require("utf-8-validate");Y.exports.isValidUTF8=function(t){return t.length<32?s(t):e(t)}}catch(e){}return Y.exports}function K(){if(N)return C;N=1;const{Writable:e}=n,t=O(),{BINARY_TYPES:s,EMPTY_BUFFER:r,kStatusCode:i,kWebSocket:o}=E(),{concat:a,toArrayBuffer:h,unmask:c}=x(),{isValidStatusCode:l,isValidUTF8:d}=X(),f=Buffer[Symbol.species];return C=class extends e{constructor(e={}){super(),this._allowSynchronousEvents=void 0===e.allowSynchronousEvents||e.allowSynchronousEvents,this._binaryType=e.binaryType||s[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=0|e.maxPayload,this._skipUTF8Validation=!!e.skipUTF8Validation,this[o]=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._errored=!1,this._loop=!1,this._state=0}_write(e,t,s){if(8===this._opcode&&0==this._state)return s();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(s)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){const t=this._buffers[0];return this._buffers[0]=new f(t.buffer,t.byteOffset+e,t.length-e),new f(t.buffer,t.byteOffset,e)}const t=Buffer.allocUnsafe(e);do{const s=this._buffers[0],r=t.length-e;e>=s.length?t.set(this._buffers.shift(),r):(t.set(new Uint8Array(s.buffer,s.byteOffset,e),r),this._buffers[0]=new f(s.buffer,s.byteOffset+e,s.length-e)),e-=s.length}while(e>0);return t}startLoop(e){this._loop=!0;do{switch(this._state){case 0:this.getInfo(e);break;case 1:this.getPayloadLength16(e);break;case 2:this.getPayloadLength64(e);break;case 3:this.getMask();break;case 4:this.getData(e);break;case 5:case 6:return void(this._loop=!1)}}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2)return void(this._loop=!1);const s=this.consume(2);if(48&s[0]){return void e(this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3"))}const r=!(64&~s[0]);if(!r||this._extensions[t.extensionName]){if(this._fin=!(128&~s[0]),this._opcode=15&s[0],this._payloadLength=127&s[1],0===this._opcode){if(r){return void e(this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1"))}if(!this._fragmented){return void e(this.createError(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 void e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE"))}this._compressed=r}else{if(!(this._opcode>7&&this._opcode<11)){return void e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE"))}if(!this._fin){return void e(this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN"))}if(r){return void e(this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1"))}if(this._payloadLength>125||8===this._opcode&&1===this._payloadLength){return void e(this.createError(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&~s[1]),this._isServer){if(!this._masked){return void e(this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK"))}}else if(this._masked){return void e(this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK"))}126===this._payloadLength?this._state=1:127===this._payloadLength?this._state=2:this.haveLength(e)}else{e(this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1"))}}getPayloadLength16(e){this._bufferedBytes<2?this._loop=!1:(this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e))}getPayloadLength64(e){if(this._bufferedBytes<8)return void(this._loop=!1);const t=this.consume(8),s=t.readUInt32BE(0);if(s>Math.pow(2,21)-1){e(this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH"))}else this._payloadLength=s*Math.pow(2,32)+t.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){e(this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"))}else 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=r;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])&&c(t,this._mask)}if(this._opcode>7)this.controlMessage(t,e);else{if(this._compressed)return this._state=5,void this.decompress(t,e);t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}}decompress(e,s){this._extensions[t.extensionName].decompress(e,this._fin,((e,t)=>{if(e)return s(e);if(t.length){if(this._messageLength+=t.length,this._messageLength>this._maxPayload&&this._maxPayload>0){const e=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");return void s(e)}this._fragments.push(t)}this.dataMessage(s),0===this._state&&this.startLoop(s)}))}dataMessage(e){if(!this._fin)return void(this._state=0);const t=this._messageLength,s=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],2===this._opcode){let r;r="nodebuffer"===this._binaryType?a(s,t):"arraybuffer"===this._binaryType?h(a(s,t)):"blob"===this._binaryType?new Blob(s):s,this._allowSynchronousEvents?(this.emit("message",r,!0),this._state=0):(this._state=6,setImmediate((()=>{this.emit("message",r,!0),this._state=0,this.startLoop(e)})))}else{const r=a(s,t);if(!this._skipUTF8Validation&&!d(r)){const t=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");return void e(t)}5===this._state||this._allowSynchronousEvents?(this.emit("message",r,!1),this._state=0):(this._state=6,setImmediate((()=>{this.emit("message",r,!1),this._state=0,this.startLoop(e)})))}}controlMessage(e,t){if(8!==this._opcode)this._allowSynchronousEvents?(this.emit(9===this._opcode?"ping":"pong",e),this._state=0):(this._state=6,setImmediate((()=>{this.emit(9===this._opcode?"ping":"pong",e),this._state=0,this.startLoop(t)})));else{if(0===e.length)this._loop=!1,this.emit("conclude",1005,r),this.end();else{const s=e.readUInt16BE(0);if(!l(s)){const e=this.createError(RangeError,`invalid status code ${s}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");return void t(e)}const r=new f(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!d(r)){const e=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");return void t(e)}this._loop=!1,this.emit("conclude",s,r),this.end()}this._state=0}}createError(e,t,s,r,o){this._loop=!1,this._errored=!0;const n=new e(s?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(n,this.createError),n.code=o,n[i]=r,n}}}function Z(){if(P)return L;P=1;const{randomFillSync:e}=o,t=O(),{EMPTY_BUFFER:s,kWebSocket:r,NOOP:i}=E(),{isBlob:n,isValidStatusCode:a}=X(),{mask:h,toBuffer:c}=x(),l=Symbol("kByteLength"),d=Buffer.alloc(4),f=8192;let u,_=f;class p{constructor(e,t,s){this._extensions=t||{},s&&(this._generateMask=s,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=0,this.onerror=i,this[r]=void 0}static frame(t,s){let r,i,o=!1,n=2,a=!1;s.mask&&(r=s.maskBuffer||d,s.generateMask?s.generateMask(r):(_===f&&(void 0===u&&(u=Buffer.alloc(f)),e(u,0,f),_=0),r[0]=u[_++],r[1]=u[_++],r[2]=u[_++],r[3]=u[_++]),a=0===(r[0]|r[1]|r[2]|r[3]),n=6),"string"==typeof t?i=s.mask&&!a||void 0===s[l]?(t=Buffer.from(t)).length:s[l]:(i=t.length,o=s.mask&&s.readOnly&&!a);let c=i;i>=65536?(n+=8,c=127):i>125&&(n+=2,c=126);const p=Buffer.allocUnsafe(o?i+n:n);return p[0]=s.fin?128|s.opcode:s.opcode,s.rsv1&&(p[0]|=64),p[1]=c,126===c?p.writeUInt16BE(i,2):127===c&&(p[2]=p[3]=0,p.writeUIntBE(i,4,6)),s.mask?(p[1]|=128,p[n-4]=r[0],p[n-3]=r[1],p[n-2]=r[2],p[n-1]=r[3],a?[p,t]:o?(h(t,r,p,n,i),[p]):(h(t,r,t,0,i),[p,t])):[p,t]}close(e,t,r,i){let o;if(void 0===e)o=s;else{if("number"!=typeof e||!a(e))throw new TypeError("First argument must be a valid error code number");if(void 0!==t&&t.length){const s=Buffer.byteLength(t);if(s>123)throw new RangeError("The message must not be greater than 123 bytes");o=Buffer.allocUnsafe(2+s),o.writeUInt16BE(e,0),"string"==typeof t?o.write(t,2):o.set(t,2)}else o=Buffer.allocUnsafe(2),o.writeUInt16BE(e,0)}const n={[l]:o.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};0!==this._state?this.enqueue([this.dispatch,o,!1,n,i]):this.sendFrame(p.frame(o,n),i)}ping(e,t,s){let r,i;if("string"==typeof e?(r=Buffer.byteLength(e),i=!1):n(e)?(r=e.size,i=!1):(r=(e=c(e)).length,i=c.readOnly),r>125)throw new RangeError("The data size must not be greater than 125 bytes");const o={[l]:r,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};n(e)?0!==this._state?this.enqueue([this.getBlobData,e,!1,o,s]):this.getBlobData(e,!1,o,s):0!==this._state?this.enqueue([this.dispatch,e,!1,o,s]):this.sendFrame(p.frame(e,o),s)}pong(e,t,s){let r,i;if("string"==typeof e?(r=Buffer.byteLength(e),i=!1):n(e)?(r=e.size,i=!1):(r=(e=c(e)).length,i=c.readOnly),r>125)throw new RangeError("The data size must not be greater than 125 bytes");const o={[l]:r,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};n(e)?0!==this._state?this.enqueue([this.getBlobData,e,!1,o,s]):this.getBlobData(e,!1,o,s):0!==this._state?this.enqueue([this.dispatch,e,!1,o,s]):this.sendFrame(p.frame(e,o),s)}send(e,s,r){const i=this._extensions[t.extensionName];let o,a,h=s.binary?2:1,d=s.compress;"string"==typeof e?(o=Buffer.byteLength(e),a=!1):n(e)?(o=e.size,a=!1):(o=(e=c(e)).length,a=c.readOnly),this._firstFragment?(this._firstFragment=!1,d&&i&&i.params[i._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(d=o>=i._threshold),this._compress=d):(d=!1,h=0),s.fin&&(this._firstFragment=!0);const f={[l]:o,fin:s.fin,generateMask:this._generateMask,mask:s.mask,maskBuffer:this._maskBuffer,opcode:h,readOnly:a,rsv1:d};n(e)?0!==this._state?this.enqueue([this.getBlobData,e,this._compress,f,r]):this.getBlobData(e,this._compress,f,r):0!==this._state?this.enqueue([this.dispatch,e,this._compress,f,r]):this.dispatch(e,this._compress,f,r)}getBlobData(e,t,s,r){this._bufferedBytes+=s[l],this._state=2,e.arrayBuffer().then((e=>{if(this._socket.destroyed){const e=new Error("The socket was closed while the blob was being read");return void process.nextTick(m,this,e,r)}this._bufferedBytes-=s[l];const i=c(e);t?this.dispatch(i,t,s,r):(this._state=0,this.sendFrame(p.frame(i,s),r),this.dequeue())})).catch((e=>{process.nextTick(y,this,e,r)}))}dispatch(e,s,r,i){if(!s)return void this.sendFrame(p.frame(e,r),i);const o=this._extensions[t.extensionName];this._bufferedBytes+=r[l],this._state=1,o.compress(e,r.fin,((e,t)=>{if(this._socket.destroyed){m(this,new Error("The socket was closed while data was being compressed"),i)}else this._bufferedBytes-=r[l],this._state=0,r.readOnly=!1,this.sendFrame(p.frame(t,r),i),this.dequeue()}))}dequeue(){for(;0===this._state&&this._queue.length;){const e=this._queue.shift();this._bufferedBytes-=e[3][l],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][l],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)}}function m(e,t,s){"function"==typeof s&&s(t);for(let s=0;s<e._queue.length;s++){const r=e._queue[s],i=r[r.length-1];"function"==typeof i&&i(t)}}function y(e,t,s){m(e,t,s),e.onerror(t)}return L=p}function J(){if(I)return U;I=1;const{tokenChars:e}=X();function t(e,t,s){void 0===e[t]?e[t]=[s]:e[t].push(s)}return U={format:function(e){return Object.keys(e).map((t=>{let s=e[t];return Array.isArray(s)||(s=[s]),s.map((e=>[t].concat(Object.keys(e).map((t=>{let s=e[t];return Array.isArray(s)||(s=[s]),s.map((e=>!0===e?t:`${t}=${e}`)).join("; ")}))).join("; "))).join(", ")})).join(", ")},parse:function(s){const r=Object.create(null);let i,o,n=Object.create(null),a=!1,h=!1,c=!1,l=-1,d=-1,f=-1,u=0;for(;u<s.length;u++)if(d=s.charCodeAt(u),void 0===i)if(-1===f&&1===e[d])-1===l&&(l=u);else if(0===u||32!==d&&9!==d){if(59!==d&&44!==d)throw new SyntaxError(`Unexpected character at index ${u}`);{if(-1===l)throw new SyntaxError(`Unexpected character at index ${u}`);-1===f&&(f=u);const e=s.slice(l,f);44===d?(t(r,e,n),n=Object.create(null)):i=e,l=f=-1}}else-1===f&&-1!==l&&(f=u);else if(void 0===o)if(-1===f&&1===e[d])-1===l&&(l=u);else if(32===d||9===d)-1===f&&-1!==l&&(f=u);else if(59===d||44===d){if(-1===l)throw new SyntaxError(`Unexpected character at index ${u}`);-1===f&&(f=u),t(n,s.slice(l,f),!0),44===d&&(t(r,i,n),n=Object.create(null),i=void 0),l=f=-1}else{if(61!==d||-1===l||-1!==f)throw new SyntaxError(`Unexpected character at index ${u}`);o=s.slice(l,u),l=f=-1}else if(h){if(1!==e[d])throw new SyntaxError(`Unexpected character at index ${u}`);-1===l?l=u:a||(a=!0),h=!1}else if(c)if(1===e[d])-1===l&&(l=u);else if(34===d&&-1!==l)c=!1,f=u;else{if(92!==d)throw new SyntaxError(`Unexpected character at index ${u}`);h=!0}else if(34===d&&61===s.charCodeAt(u-1))c=!0;else if(-1===f&&1===e[d])-1===l&&(l=u);else if(-1===l||32!==d&&9!==d){if(59!==d&&44!==d)throw new SyntaxError(`Unexpected character at index ${u}`);{if(-1===l)throw new SyntaxError(`Unexpected character at index ${u}`);-1===f&&(f=u);let e=s.slice(l,f);a&&(e=e.replace(/\\/g,""),a=!1),t(n,o,e),44===d&&(t(r,i,n),n=Object.create(null),i=void 0),o=void 0,l=f=-1}}else-1===f&&(f=u);if(-1===l||c||32===d||9===d)throw new SyntaxError("Unexpected end of input");-1===f&&(f=u);const _=s.slice(l,f);return void 0===i?t(r,_,n):(void 0===o?t(n,_,!0):t(n,o,a?_.replace(/\\/g,""):_),t(r,i,n)),r}}}function Q(){if(W)return M;W=1;const n=e,h=t,c=s,l=r,d=i,{randomBytes:f,createHash:u}=o,{URL:_}=a,p=O(),m=K(),y=Z(),{isBlob:b}=X(),{BINARY_TYPES:v,EMPTY_BUFFER:g,GUID:S,kForOnEventAttribute:w,kListener:k,kStatusCode:T,kWebSocket:C,NOOP:N}=E(),{EventTarget:{addEventListener:L,removeEventListener:P}}=function(){if(R)return B;R=1;const{kForOnEventAttribute:e,kListener:t}=E(),s=Symbol("kCode"),r=Symbol("kData"),i=Symbol("kError"),o=Symbol("kMessage"),n=Symbol("kReason"),a=Symbol("kTarget"),h=Symbol("kType"),c=Symbol("kWasClean");class l{constructor(e){this[a]=null,this[h]=e}get target(){return this[a]}get type(){return this[h]}}Object.defineProperty(l.prototype,"target",{enumerable:!0}),Object.defineProperty(l.prototype,"type",{enumerable:!0});class d extends l{constructor(e,t={}){super(e),this[s]=void 0===t.code?0:t.code,this[n]=void 0===t.reason?"":t.reason,this[c]=void 0!==t.wasClean&&t.wasClean}get code(){return this[s]}get reason(){return this[n]}get wasClean(){return this[c]}}Object.defineProperty(d.prototype,"code",{enumerable:!0}),Object.defineProperty(d.prototype,"reason",{enumerable:!0}),Object.defineProperty(d.prototype,"wasClean",{enumerable:!0});class f extends l{constructor(e,t={}){super(e),this[i]=void 0===t.error?null:t.error,this[o]=void 0===t.message?"":t.message}get error(){return this[i]}get message(){return this[o]}}Object.defineProperty(f.prototype,"error",{enumerable:!0}),Object.defineProperty(f.prototype,"message",{enumerable:!0});class u extends l{constructor(e,t={}){super(e),this[r]=void 0===t.data?null:t.data}get data(){return this[r]}}Object.defineProperty(u.prototype,"data",{enumerable:!0});const _={addEventListener(s,r,i={}){for(const o of this.listeners(s))if(!i[e]&&o[t]===r&&!o[e])return;let o;if("message"===s)o=function(e,t){const s=new u("message",{data:t?e:e.toString()});s[a]=this,p(r,this,s)};else if("close"===s)o=function(e,t){const s=new d("close",{code:e,reason:t.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});s[a]=this,p(r,this,s)};else if("error"===s)o=function(e){const t=new f("error",{error:e,message:e.message});t[a]=this,p(r,this,t)};else{if("open"!==s)return;o=function(){const e=new l("open");e[a]=this,p(r,this,e)}}o[e]=!!i[e],o[t]=r,i.once?this.once(s,o):this.on(s,o)},removeEventListener(s,r){for(const i of this.listeners(s))if(i[t]===r&&!i[e]){this.removeListener(s,i);break}}};function p(e,t,s){"object"==typeof e&&e.handleEvent?e.handleEvent.call(e,s):e.call(t,s)}return B={CloseEvent:d,ErrorEvent:f,Event:l,EventTarget:_,MessageEvent:u}}(),{format:U,parse:I}=J(),{toBuffer:D}=x(),A=Symbol("kAborted"),j=[8,13],F=["CONNECTING","OPEN","CLOSING","CLOSED"],$=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;class G extends n{constructor(e,t,s){super(),this._binaryType=v[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=g,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=G.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?(s=t,t=[]):t=[t]),V(this,e,t,s)):(this._autoPong=s.autoPong,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){v.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,s){const r=new m({allowSynchronousEvents:s.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation}),i=new y(e,this._extensions,s.generateMask);this._receiver=r,this._sender=i,this._socket=e,r[C]=this,i[C]=this,e[C]=this,r.on("conclude",ee),r.on("drain",te),r.on("error",se),r.on("message",ie),r.on("ping",oe),r.on("pong",ne),i.onerror=he,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",le),e.on("data",de),e.on("end",fe),e.on("error",ue),this._readyState=G.OPEN,this.emit("open")}emitClose(){if(!this._socket)return this._readyState=G.CLOSED,void this.emit("close",this._closeCode,this._closeMessage);this._extensions[p.extensionName]&&this._extensions[p.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=G.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,t){if(this.readyState!==G.CLOSED)if(this.readyState!==G.CONNECTING)this.readyState!==G.CLOSING?(this._readyState=G.CLOSING,this._sender.close(e,t,!this._isServer,(e=>{e||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())})),ce(this)):this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();else{const e="WebSocket was closed before the connection was established";Y(this,this._req,e)}}pause(){this.readyState!==G.CONNECTING&&this.readyState!==G.CLOSED&&(this._paused=!0,this._socket.pause())}ping(e,t,s){if(this.readyState===G.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");"function"==typeof e?(s=e,e=t=void 0):"function"==typeof t&&(s=t,t=void 0),"number"==typeof e&&(e=e.toString()),this.readyState===G.OPEN?(void 0===t&&(t=!this._isServer),this._sender.ping(e||g,t,s)):Q(this,e,s)}pong(e,t,s){if(this.readyState===G.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");"function"==typeof e?(s=e,e=t=void 0):"function"==typeof t&&(s=t,t=void 0),"number"==typeof e&&(e=e.toString()),this.readyState===G.OPEN?(void 0===t&&(t=!this._isServer),this._sender.pong(e||g,t,s)):Q(this,e,s)}resume(){this.readyState!==G.CONNECTING&&this.readyState!==G.CLOSED&&(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,t,s){if(this.readyState===G.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if("function"==typeof t&&(s=t,t={}),"number"==typeof e&&(e=e.toString()),this.readyState!==G.OPEN)return void Q(this,e,s);const r={binary:"string"!=typeof e,mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[p.extensionName]||(r.compress=!1),this._sender.send(e||g,r,s)}terminate(){if(this.readyState!==G.CLOSED)if(this.readyState!==G.CONNECTING)this._socket&&(this._readyState=G.CLOSING,this._socket.destroy());else{const e="WebSocket was closed before the connection was established";Y(this,this._req,e)}}}function V(e,t,s,r){const i={allowSynchronousEvents:!0,autoPong:!0,protocolVersion:j[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...r,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(e._autoPong=i.autoPong,!j.includes(i.protocolVersion))throw new RangeError(`Unsupported protocol version: ${i.protocolVersion} (supported versions: ${j.join(", ")})`);let o;if(t instanceof _)o=t;else try{o=new _(t)}catch(e){throw new SyntaxError(`Invalid URL: ${t}`)}"http:"===o.protocol?o.protocol="ws:":"https:"===o.protocol&&(o.protocol="wss:"),e._url=o.href;const n="wss:"===o.protocol,a="ws+unix:"===o.protocol;let l;if("ws:"===o.protocol||n||a?a&&!o.pathname?l="The URL's pathname is empty":o.hash&&(l="The URL contains a fragment identifier"):l='The URL\'s protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"',l){const t=new SyntaxError(l);if(0===e._redirects)throw t;return void q(e,t)}const d=n?443:80,m=f(16).toString("base64"),y=n?h.request:c.request,b=new Set;let v,g;if(i.createConnection=i.createConnection||(n?H:z),i.defaultPort=i.defaultPort||d,i.port=o.port||d,i.host=o.hostname.startsWith("[")?o.hostname.slice(1,-1):o.hostname,i.headers={...i.headers,"Sec-WebSocket-Version":i.protocolVersion,"Sec-WebSocket-Key":m,Connection:"Upgrade",Upgrade:"websocket"},i.path=o.pathname+o.search,i.timeout=i.handshakeTimeout,i.perMessageDeflate&&(v=new p(!0!==i.perMessageDeflate?i.perMessageDeflate:{},!1,i.maxPayload),i.headers["Sec-WebSocket-Extensions"]=U({[p.extensionName]:v.offer()})),s.length){for(const e of s){if("string"!=typeof e||!$.test(e)||b.has(e))throw new SyntaxError("An invalid or duplicated subprotocol was specified");b.add(e)}i.headers["Sec-WebSocket-Protocol"]=s.join(",")}if(i.origin&&(i.protocolVersion<13?i.headers["Sec-WebSocket-Origin"]=i.origin:i.headers.Origin=i.origin),(o.username||o.password)&&(i.auth=`${o.username}:${o.password}`),a){const e=i.path.split(":");i.socketPath=e[0],i.path=e[1]}if(i.followRedirects){if(0===e._redirects){e._originalIpc=a,e._originalSecure=n,e._originalHostOrSocketPath=a?i.socketPath:o.host;const t=r&&r.headers;if(r={...r,headers:{}},t)for(const[e,s]of Object.entries(t))r.headers[e.toLowerCase()]=s}else if(0===e.listenerCount("redirect")){const t=a?!!e._originalIpc&&i.socketPath===e._originalHostOrSocketPath:!e._originalIpc&&o.host===e._originalHostOrSocketPath;(!t||e._originalSecure&&!n)&&(delete i.headers.authorization,delete i.headers.cookie,t||delete i.headers.host,i.auth=void 0)}i.auth&&!r.headers.authorization&&(r.headers.authorization="Basic "+Buffer.from(i.auth).toString("base64")),g=e._req=y(i),e._redirects&&e.emit("redirect",e.url,g)}else g=e._req=y(i);i.timeout&&g.on("timeout",(()=>{Y(e,g,"Opening handshake has timed out")})),g.on("error",(t=>{null===g||g[A]||(g=e._req=null,q(e,t))})),g.on("response",(o=>{const n=o.headers.location,a=o.statusCode;if(n&&i.followRedirects&&a>=300&&a<400){if(++e._redirects>i.maxRedirects)return void Y(e,g,"Maximum redirects exceeded");let o;g.abort();try{o=new _(n,t)}catch(t){const s=new SyntaxError(`Invalid URL: ${n}`);return void q(e,s)}V(e,o,s,r)}else e.emit("unexpected-response",g,o)||Y(e,g,`Unexpected server response: ${o.statusCode}`)})),g.on("upgrade",((t,s,r)=>{if(e.emit("upgrade",t),e.readyState!==G.CONNECTING)return;g=e._req=null;const o=t.headers.upgrade;if(void 0===o||"websocket"!==o.toLowerCase())return void Y(e,s,"Invalid Upgrade header");const n=u("sha1").update(m+S).digest("base64");if(t.headers["sec-websocket-accept"]!==n)return void Y(e,s,"Invalid Sec-WebSocket-Accept header");const a=t.headers["sec-websocket-protocol"];let h;if(void 0!==a?b.size?b.has(a)||(h="Server sent an invalid subprotocol"):h="Server sent a subprotocol but none was requested":b.size&&(h="Server sent no subprotocol"),h)return void Y(e,s,h);a&&(e._protocol=a);const c=t.headers["sec-websocket-extensions"];if(void 0!==c){if(!v){return void Y(e,s,"Server sent a Sec-WebSocket-Extensions header but no extension was requested")}let t;try{t=I(c)}catch(t){return void Y(e,s,"Invalid Sec-WebSocket-Extensions header")}const r=Object.keys(t);if(1!==r.length||r[0]!==p.extensionName){return void Y(e,s,"Server indicated an extension that was not requested")}try{v.accept(t[p.extensionName])}catch(t){return void Y(e,s,"Invalid Sec-WebSocket-Extensions header")}e._extensions[p.extensionName]=v}e.setSocket(s,r,{allowSynchronousEvents:i.allowSynchronousEvents,generateMask:i.generateMask,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation})})),i.finishRequest?i.finishRequest(g,e):g.end()}function q(e,t){e._readyState=G.CLOSING,e._errorEmitted=!0,e.emit("error",t),e.emitClose()}function z(e){return e.path=e.socketPath,l.connect(e)}function H(e){return e.path=void 0,e.servername||""===e.servername||(e.servername=l.isIP(e.host)?"":e.host),d.connect(e)}function Y(e,t,s){e._readyState=G.CLOSING;const r=new Error(s);Error.captureStackTrace(r,Y),t.setHeader?(t[A]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(q,e,r)):(t.destroy(r),t.once("error",e.emit.bind(e,"error")),t.once("close",e.emitClose.bind(e)))}function Q(e,t,s){if(t){const s=b(t)?t.size:D(t).length;e._socket?e._sender._bufferedBytes+=s:e._bufferedAmount+=s}if(s){const t=new Error(`WebSocket is not open: readyState ${e.readyState} (${F[e.readyState]})`);process.nextTick(s,t)}}function ee(e,t){const s=this[C];s._closeFrameReceived=!0,s._closeMessage=t,s._closeCode=e,void 0!==s._socket[C]&&(s._socket.removeListener("data",de),process.nextTick(ae,s._socket),1005===e?s.close():s.close(e,t))}function te(){const e=this[C];e.isPaused||e._socket.resume()}function se(e){const t=this[C];void 0!==t._socket[C]&&(t._socket.removeListener("data",de),process.nextTick(ae,t._socket),t.close(e[T])),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e))}function re(){this[C].emitClose()}function ie(e,t){this[C].emit("message",e,t)}function oe(e){const t=this[C];t._autoPong&&t.pong(e,!this._isServer,N),t.emit("ping",e)}function ne(e){this[C].emit("pong",e)}function ae(e){e.resume()}function he(e){const t=this[C];t.readyState!==G.CLOSED&&(t.readyState===G.OPEN&&(t._readyState=G.CLOSING,ce(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e)))}function ce(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),3e4)}function le(){const e=this[C];let t;this.removeListener("close",le),this.removeListener("data",de),this.removeListener("end",fe),e._readyState=G.CLOSING,this._readableState.endEmitted||e._closeFrameReceived||e._receiver._writableState.errorEmitted||null===(t=e._socket.read())||e._receiver.write(t),e._receiver.end(),this[C]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on("error",re),e._receiver.on("finish",re))}function de(e){this[C]._receiver.write(e)||this.pause()}function fe(){const e=this[C];e._readyState=G.CLOSING,e._receiver.end(),this.end()}function ue(){const e=this[C];this.removeListener("error",ue),this.on("error",N),e&&(e._readyState=G.CLOSING,this.destroy())}return Object.defineProperty(G,"CONNECTING",{enumerable:!0,value:F.indexOf("CONNECTING")}),Object.defineProperty(G.prototype,"CONNECTING",{enumerable:!0,value:F.indexOf("CONNECTING")}),Object.defineProperty(G,"OPEN",{enumerable:!0,value:F.indexOf("OPEN")}),Object.defineProperty(G.prototype,"OPEN",{enumerable:!0,value:F.indexOf("OPEN")}),Object.defineProperty(G,"CLOSING",{enumerable:!0,value:F.indexOf("CLOSING")}),Object.defineProperty(G.prototype,"CLOSING",{enumerable:!0,value:F.indexOf("CLOSING")}),Object.defineProperty(G,"CLOSED",{enumerable:!0,value:F.indexOf("CLOSED")}),Object.defineProperty(G.prototype,"CLOSED",{enumerable:!0,value:F.indexOf("CLOSED")}),["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach((e=>{Object.defineProperty(G.prototype,e,{enumerable:!0})})),["open","error","close","message"].forEach((e=>{Object.defineProperty(G.prototype,`on${e}`,{enumerable:!0,get(){for(const t of this.listeners(e))if(t[w])return t[k];return null},set(t){for(const t of this.listeners(e))if(t[w]){this.removeListener(e,t);break}"function"==typeof t&&this.addEventListener(e,t,{[w]:!0})}})})),G.prototype.addEventListener=L,G.prototype.removeEventListener=P,M=G}function ee(){if(F)return j;F=1;const{tokenChars:e}=X();return j={parse:function(t){const s=new Set;let r=-1,i=-1,o=0;for(;o<t.length;o++){const n=t.charCodeAt(o);if(-1===i&&1===e[n])-1===r&&(r=o);else if(0===o||32!==n&&9!==n){if(44!==n)throw new SyntaxError(`Unexpected character at index ${o}`);{if(-1===r)throw new SyntaxError(`Unexpected character at index ${o}`);-1===i&&(i=o);const e=t.slice(r,i);if(s.has(e))throw new SyntaxError(`The "${e}" subprotocol is duplicated`);s.add(e),r=i=-1}}else-1===i&&-1!==r&&(i=o)}if(-1===r||-1!==i)throw new SyntaxError("Unexpected end of input");const n=t.slice(r,o);if(s.has(n))throw new SyntaxError(`The "${n}" subprotocol is duplicated`);return s.add(n),s}}}function te(){if(G)return $;G=1;const t=e,r=s,{createHash:i}=o,n=J(),a=O(),h=ee(),c=Q(),{GUID:l,kWebSocket:d}=E(),f=/^[+/0-9A-Za-z]{22}==$/;function u(e){e._state=2,e.emit("close")}function _(){this.destroy()}function p(e,t,s,i){s=s||r.STATUS_CODES[t],i={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(s),...i},e.once("finish",e.destroy),e.end(`HTTP/1.1 ${t} ${r.STATUS_CODES[t]}\r\n`+Object.keys(i).map((e=>`${e}: ${i[e]}`)).join("\r\n")+"\r\n\r\n"+s)}function m(e,t,s,r,i){if(e.listenerCount("wsClientError")){const r=new Error(i);Error.captureStackTrace(r,m),e.emit("wsClientError",r,s,t)}else p(s,r,i)}return $=class extends t{constructor(e,t){if(super(),null==(e={allowSynchronousEvents:!0,autoPong:!0,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:c,...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=r.createServer(((e,t)=>{const s=r.STATUS_CODES[426];t.writeHead(426,{"Content-Length":s.length,"Content-Type":"text/plain"}),t.end(s)})),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 s of Object.keys(t))e.on(s,t[s]);return function(){for(const s of Object.keys(t))e.removeListener(s,t[s])}}(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(t,s,r)=>{this.handleUpgrade(t,s,r,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(u,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(u,this);else{const e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close((()=>{u(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,s,r){t.on("error",_);const i=e.headers["sec-websocket-key"],o=e.headers.upgrade,c=+e.headers["sec-websocket-version"];if("GET"!==e.method){return void m(this,e,t,405,"Invalid HTTP method")}if(void 0===o||"websocket"!==o.toLowerCase()){return void m(this,e,t,400,"Invalid Upgrade header")}if(void 0===i||!f.test(i)){return void m(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header")}if(8!==c&&13!==c){return void m(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header")}if(!this.shouldHandle(e))return void p(t,400);const l=e.headers["sec-websocket-protocol"];let d=new Set;if(void 0!==l)try{d=h.parse(l)}catch(s){return void m(this,e,t,400,"Invalid Sec-WebSocket-Protocol header")}const u=e.headers["sec-websocket-extensions"],y={};if(this.options.perMessageDeflate&&void 0!==u){const s=new a(this.options.perMessageDeflate,!0,this.options.maxPayload);try{const e=n.parse(u);e[a.extensionName]&&(s.accept(e[a.extensionName]),y[a.extensionName]=s)}catch(s){return void m(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header")}}if(this.options.verifyClient){const o={origin:e.headers[""+(8===c?"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,((o,n,a,h)=>{if(!o)return p(t,n||401,a,h);this.completeUpgrade(y,i,d,e,t,s,r)}));if(!this.options.verifyClient(o))return p(t,401)}this.completeUpgrade(y,i,d,e,t,s,r)}completeUpgrade(e,t,s,r,o,h,c){if(!o.readable||!o.writable)return o.destroy();if(o[d])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>0)return p(o,503);const f=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${i("sha1").update(t+l).digest("base64")}`],m=new this.options.WebSocket(null,void 0,this.options);if(s.size){const e=this.options.handleProtocols?this.options.handleProtocols(s,r):s.values().next().value;e&&(f.push(`Sec-WebSocket-Protocol: ${e}`),m._protocol=e)}if(e[a.extensionName]){const t=e[a.extensionName].params,s=n.format({[a.extensionName]:[t]});f.push(`Sec-WebSocket-Extensions: ${s}`),m._extensions=e}this.emit("headers",f,r),o.write(f.concat("\r\n").join("\r\n")),o.removeListener("error",_),m.setSocket(o,h,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(m),m.on("close",(()=>{this.clients.delete(m),this._shouldEmitClose&&!this.clients.size&&process.nextTick(u,this)}))),c(m,r)}},$}function se(){if(q)return V;q=1;const e=Q();return e.createWebSocketStream=function(){if(A)return D;A=1,Q();const{Duplex:e}=n;function t(e){e.emit("close")}function s(){!this.destroyed&&this._writableState.finished&&this.destroy()}function r(e){this.removeListener("error",r),this.destroy(),0===this.listenerCount("error")&&this.emit("error",e)}return D=function(i,o){let n=!0;const a=new e({...o,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return i.on("message",(function(e,t){const s=!t&&a._readableState.objectMode?e.toString():e;a.push(s)||i.pause()})),i.once("error",(function(e){a.destroyed||(n=!1,a.destroy(e))})),i.once("close",(function(){a.destroyed||a.push(null)})),a._destroy=function(e,s){if(i.readyState===i.CLOSED)return s(e),void process.nextTick(t,a);let r=!1;i.once("error",(function(e){r=!0,s(e)})),i.once("close",(function(){r||s(e),process.nextTick(t,a)})),n&&i.terminate()},a._final=function(e){i.readyState!==i.CONNECTING?null!==i._socket&&(i._socket._writableState.finished?(e(),a._readableState.endEmitted&&a.destroy()):(i._socket.once("finish",(function(){e()})),i.close())):i.once("open",(function(){a._final(e)}))},a._read=function(){i.isPaused&&i.resume()},a._write=function(e,t,s){i.readyState!==i.CONNECTING?i.send(e,s):i.once("open",(function(){a._write(e,t,s)}))},a.on("end",s),a.on("error",r),a},D}(),e.Server=te(),e.Receiver=K(),e.Sender=Z(),e.WebSocket=e,e.WebSocketServer=e.Server,V=e}var re=l(function(){if(H)return z;H=1;var e=function(){return e=function e(t){var s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.wsUrl=t,this.socket=null,this.listeners={},this.dataCallbacks={},this.queue=[],this.headers=s.headers||{},this.connect()},(t=[{key:"connect",value:function(){var e=this,t="undefined"!=typeof WebSocket?WebSocket:se();this.socket=new t(this.wsUrl),this.socket.onopen=function(){for(console.log("🟢 WebSocket connected");e.queue.length>0;){var t=e.queue.shift();e.socket.send(JSON.stringify(t))}Object.keys(e.listeners).forEach((function(t){e.sendMessage({type:"subscribe",path:t})}))},this.socket.onmessage=function(t){try{var s=JSON.parse(t.data);"update"===s.type&&e.listeners[s.path]&&e.listeners[s.path].forEach((function(e){return e(s.data)})),"data"===s.type&&e.dataCallbacks[s.path]&&(e.dataCallbacks[s.path].forEach((function(e){return e(s.data)})),delete e.dataCallbacks[s.path])}catch(e){console.error("Error parsing message:",e)}},this.socket.onclose=function(){console.warn("🔴 WebSocket disconnected. Reconnecting..."),setTimeout((function(){return e.connect()}),3e3)}}},{key:"_generateId",value:function(){for(var e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",t="",s=0;s<17;s++)t+=e.charAt(Math.floor(62*Math.random()));return"".concat(Date.now()).concat(t)}},{key:"setHeader",value:function(e,t){this.headers[e]=t}},{key:"sendMessage",value:function(e){var t=_(_({},e),{},{headers:this.headers});1===this.socket.readyState?this.socket.send(JSON.stringify(t)):this.queue.push(t)}},{key:"subscribe",value:function(e){this.sendMessage({type:"subscribe",path:e})}},{key:"on",value:function(e,t){this.listeners[e]||(this.listeners[e]=[],this.subscribe(e)),this.listeners[e].push(t)}},{key:"get",value:function(e,t){this.dataCallbacks[e]||(this.dataCallbacks[e]=[]),this.dataCallbacks[e].push(t),this.sendMessage({type:"get",path:e})}},{key:"set",value:function(e,t){this.sendMessage({type:"set",path:e,data:t})}},{key:"push",value:function(e,t){var s=this._generateId();return this.set("".concat(e,"/").concat(s),t),s}},{key:"update",value:function(e,t){this.sendMessage({type:"update",path:e,data:t})}},{key:"delete",value:function(e){this.sendMessage({type:"delete",path:e})}}])&&d(e.prototype,t),s&&d(e,s),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,s}();return"undefined"!=typeof window&&(window.Nudb=e),z=e}());export{re as default};
//# sourceMappingURL=index.js.map