@sunpix/claude-code-web
Version:
A web-based interface for interacting with Claude Code CLI
1 lines • 160 kB
JavaScript
import process from 'node:process';globalThis._importMeta_=globalThis._importMeta_||{url:"file:///_entry.js",env:process.env};import e,{Server as t}from"node:http";import s,{Server as r}from"node:https";import n,{createHash as o}from"node:crypto";import i from"stream";import a from"events";import c from"http";import u from"crypto";import l from"buffer";import h from"zlib";import d from"https";import f from"net";import p from"tls";import m from"url";import{EventEmitter as g}from"node:events";import{Buffer as y}from"node:buffer";import{promises as _,existsSync as b}from"node:fs";import{resolve as w,dirname as v,join as x}from"node:path";import{query as S}from"@anthropic-ai/claude-code";import k,{promises as E}from"fs";import j from"path";import T from"os";import C from"fs/promises";import{watch as O}from"chokidar";import I from"readline";import{fileURLToPath as A}from"node:url";n.webcrypto;const R=()=>n.randomUUID(),N=Symbol.for("nodejs.util.inspect.custom");function B(e){if(null==e)return"";const t=typeof e;return"string"===t?e:"number"===t||"boolean"===t||"bigint"===t?e.toString():"function"===t||"symbol"===t?"{}":e instanceof Uint8Array||e instanceof ArrayBuffer?e:function(e){if(null===e||"object"!=typeof e)return!1;const t=Object.getPrototypeOf(e);if(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t))return!1;if(Symbol.iterator in e)return!1;if(Symbol.toStringTag in e)return"[object Module]"===Object.prototype.toString.call(e);return!0}(e)?JSON.stringify(e):e}class P{event;peer;rawData;#e;#t;#s;#r;#n;#o;constructor(e,t,s){this.rawData=e||"",this.peer=t,this.event=s}get id(){return this.#e||(this.#e=R()),this.#e}uint8Array(){const e=this.#t;if(e)return e;const t=this.rawData;if(t instanceof Uint8Array)return this.#t=t;if(t instanceof ArrayBuffer||t instanceof SharedArrayBuffer)return this.#s=t,this.#t=new Uint8Array(t);if("string"==typeof t)return this.#n=t,this.#t=(new TextEncoder).encode(this.#n);if(Symbol.iterator in t)return this.#t=new Uint8Array(t);if("number"==typeof t?.length)return this.#t=new Uint8Array(t);if(t instanceof DataView)return this.#t=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new TypeError(`Unsupported message type: ${Object.prototype.toString.call(t)}`)}arrayBuffer(){const e=this.#s;if(e)return e;const t=this.rawData;return t instanceof ArrayBuffer||t instanceof SharedArrayBuffer?this.#s=t:this.#s=this.uint8Array().buffer}blob(){const e=this.#r;if(e)return e;const t=this.rawData;return t instanceof Blob?this.#r=t:this.#r=new Blob([this.uint8Array()])}text(){const e=this.#n;if(e)return e;const t=this.rawData;return this.#n="string"==typeof t?t:(new TextDecoder).decode(this.uint8Array())}json(){const e=this.#o;return e||(this.#o=JSON.parse(this.text()))}get data(){switch(this.peer?.websocket?.binaryType){case"arraybuffer":return this.arrayBuffer();case"blob":return this.blob();case"nodebuffer":return globalThis.Buffer?Buffer.from(this.uint8Array()):this.uint8Array();case"uint8array":return this.uint8Array();case"text":return this.text();default:return this.rawData}}toString(){return this.text()}[Symbol.toPrimitive](){return this.text()}[N](){return{data:this.rawData}}}class M{_internal;_topics;_id;#i;constructor(e){this._topics=new Set,this._internal=e}get context(){return this._internal.context??={}}get id(){return this._id||(this._id=R()),this._id}get remoteAddress(){}get request(){return this._internal.request}get websocket(){if(!this.#i){const t=this._internal.ws,s=this._internal.request;this.#i=s?(e=s,new Proxy(t,{get:(t,s)=>{const r=Reflect.get(t,s);if(!r)switch(s){case"protocol":return e?.headers?.get("sec-websocket-protocol")||"";case"extensions":return e?.headers?.get("sec-websocket-extensions")||"";case"url":return e?.url?.replace(/^http/,"ws")||void 0}return r}})):t}var e;return this.#i}get peers(){return this._internal.peers||new Set}get topics(){return this._topics}terminate(){this.close()}subscribe(e){this._topics.add(e)}unsubscribe(e){this._topics.delete(e)}toString(){return this.id}[Symbol.toPrimitive](){return this.id}[Symbol.toStringTag](){return"WebSocket"}[N](){return Object.fromEntries([["id",this.id],["remoteAddress",this.remoteAddress],["peers",this.peers],["webSocket",this.websocket]].filter(e=>e[1]))}}class L{options;constructor(e){this.options=e||{}}callHook(e,t,s){const r=this.options.hooks?.[e],n=r?.(t,s),o=this.options.resolve?.(t);if(!o)return n;const i=o instanceof Promise?o.then(t=>t?.[e]):o?.[e];return Promise.all([n,i]).then(([e,r])=>{const n=r?.(t,s);return n instanceof Promise?n.then(t=>t||e):n||e})}async upgrade(e){let t=e.context;t||(t={},Object.defineProperty(e,"context",{enumerable:!0,value:t}));try{const s=await this.callHook("upgrade",e);if(!s)return{context:t};if(!1===s.ok)return{context:t,endResponse:s};if(s.headers)return{context:t,upgradeHeaders:s.headers}}catch(e){const s=e.response||e;if(s instanceof Response)return{context:t,endResponse:s};throw e}return{context:t}}}function U(e){return{peers:e,publish(t,s,r){let n;for(const s of e)if(s.topics.has(t)){n=s;break}n&&(n.send(s,r),n.publish(t,s,r))}}}class D extends Error{constructor(...e){super(...e),this.name="WSError"}}function z(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var q,H,W,F,$,Z,G,V={exports:{}};function J(){if(H)return q;H=1;const e=["nodebuffer","arraybuffer","fragments"],t="undefined"!=typeof Blob;return t&&e.push("blob"),q={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 K(){if(W)return V.exports;W=1;const{EMPTY_BUFFER:e}=J(),t=Buffer[Symbol.species];function s(e,t,s,r,n){for(let o=0;o<n;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(V.exports={concat:function(s,r){if(0===s.length)return e;if(1===s.length)return s[0];const n=Buffer.allocUnsafe(r);let o=0;for(let e=0;e<s.length;e++){const t=s[e];n.set(t,o),o+=t.length}return o<r?new t(n.buffer,n.byteOffset,o):n},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");V.exports.mask=function(t,r,n,o,i){i<48?s(t,r,n,o,i):e.mask(t,r,n,o,i)},V.exports.unmask=function(t,s){t.length<32?r(t,s):e.unmask(t,s)}}catch(e){}return V.exports}function X(){if(G)return Z;G=1;const e=h,t=K(),s=function(){if($)return F;$=1;const e=Symbol("kDone"),t=Symbol("kRun");return F=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}=J(),n=Buffer[Symbol.species],o=Buffer.from([0,0,255,255]),i=Symbol("permessage-deflate"),a=Symbol("total-length"),c=Symbol("callback"),u=Symbol("buffers"),l=Symbol("error");let d;function f(e){this[u].push(e),this[a]+=e.length}function p(e){this[a]+=e.length,this[i]._maxPayload<1||this[a]<=this[i]._maxPayload?this[u].push(e):(this[l]=new RangeError("Max payload size exceeded"),this[l].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[l][r]=1009,this.removeListener("data",p),this.reset())}function m(e){this[i]._inflate=null,this[l]?this[c](this[l]):(e[r]=1007,this[c](e))}return Z=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,!d){const e=void 0!==this._options.concurrencyLimit?this._options.concurrencyLimit:10;d=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){d.add(r=>{this._decompress(e,t,(e,t)=>{r(),s(e,t)})})}compress(e,t,s){d.add(r=>{this._compress(e,t,(e,t)=>{r(),s(e,t)})})}_decompress(s,r,n){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[i]=this,this._inflate[a]=0,this._inflate[u]=[],this._inflate.on("error",m),this._inflate.on("data",p)}this._inflate[c]=n,this._inflate.write(s),r&&this._inflate.write(o),this._inflate.flush(()=>{const e=this._inflate[l];if(e)return this._inflate.close(),this._inflate=null,void n(e);const s=t.concat(this._inflate[u],this._inflate[a]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[a]=0,this._inflate[u]=[],r&&this.params[`${h}_no_context_takeover`]&&this._inflate.reset()),n(null,s)})}_compress(s,r,o){const i=this._isServer?"server":"client";if(!this._deflate){const t=`${i}_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[u]=[],this._deflate.on("data",f)}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[u],this._deflate[a]);r&&(e=new n(e.buffer,e.byteOffset,e.length-4)),this._deflate[c]=null,this._deflate[a]=0,this._deflate[u]=[],r&&this.params[`${i}_no_context_takeover`]&&this._deflate.reset(),o(null,e)})}},Z}var Y,Q,ee,te,se,re,ne,oe,ie,ae,ce,ue,le,he,de,fe,pe,me={exports:{}};function ge(){if(Y)return me.exports;Y=1;const{isUtf8:e}=l,{hasBlob:t}=J();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(me.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)me.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");me.exports.isValidUTF8=function(t){return t.length<32?s(t):e(t)}}catch(e){}return me.exports}function ye(){if(ee)return Q;ee=1;const{Writable:e}=i,t=X(),{BINARY_TYPES:s,EMPTY_BUFFER:r,kStatusCode:n,kWebSocket:o}=J(),{concat:a,toArrayBuffer:c,unmask:u}=K(),{isValidStatusCode:l,isValidUTF8:h}=ge(),d=Buffer[Symbol.species];return Q=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 d(t.buffer,t.byteOffset+e,t.length-e),new d(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 d(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]){return void e(this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1"))}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)}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){return void e(this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH"))}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)){return void e(this.createError(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=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])&&u(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?c(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&&!h(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 d(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!h(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 i=new e(s?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(i,this.createError),i.code=o,i[n]=r,i}}}function _e(){if(se)return te;se=1;const{Duplex:e}=i,{randomFillSync:t}=u,s=X(),{EMPTY_BUFFER:r,kWebSocket:n,NOOP:o}=J(),{isBlob:a,isValidStatusCode:c}=ge(),{mask:l,toBuffer:h}=K(),d=Symbol("kByteLength"),f=Buffer.alloc(4),p=8192;let m,g=p;class y{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=o,this[n]=void 0}static frame(e,s){let r,n,o=!1,i=2,a=!1;s.mask&&(r=s.maskBuffer||f,s.generateMask?s.generateMask(r):(g===p&&(void 0===m&&(m=Buffer.alloc(p)),t(m,0,p),g=0),r[0]=m[g++],r[1]=m[g++],r[2]=m[g++],r[3]=m[g++]),a=0===(r[0]|r[1]|r[2]|r[3]),i=6),"string"==typeof e?n=s.mask&&!a||void 0===s[d]?(e=Buffer.from(e)).length:s[d]:(n=e.length,o=s.mask&&s.readOnly&&!a);let c=n;n>=65536?(i+=8,c=127):n>125&&(i+=2,c=126);const u=Buffer.allocUnsafe(o?n+i:i);return u[0]=s.fin?128|s.opcode:s.opcode,s.rsv1&&(u[0]|=64),u[1]=c,126===c?u.writeUInt16BE(n,2):127===c&&(u[2]=u[3]=0,u.writeUIntBE(n,4,6)),s.mask?(u[1]|=128,u[i-4]=r[0],u[i-3]=r[1],u[i-2]=r[2],u[i-1]=r[3],a?[u,e]:o?(l(e,r,u,i,n),[u]):(l(e,r,e,0,n),[u,e])):[u,e]}close(e,t,s,n){let o;if(void 0===e)o=r;else{if("number"!=typeof e||!c(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 i={[d]:o.length,fin:!0,generateMask:this._generateMask,mask:s,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};0!==this._state?this.enqueue([this.dispatch,o,!1,i,n]):this.sendFrame(y.frame(o,i),n)}ping(e,t,s){let r,n;if("string"==typeof e?(r=Buffer.byteLength(e),n=!1):a(e)?(r=e.size,n=!1):(r=(e=h(e)).length,n=h.readOnly),r>125)throw new RangeError("The data size must not be greater than 125 bytes");const o={[d]:r,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:n,rsv1:!1};a(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(y.frame(e,o),s)}pong(e,t,s){let r,n;if("string"==typeof e?(r=Buffer.byteLength(e),n=!1):a(e)?(r=e.size,n=!1):(r=(e=h(e)).length,n=h.readOnly),r>125)throw new RangeError("The data size must not be greater than 125 bytes");const o={[d]:r,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:n,rsv1:!1};a(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(y.frame(e,o),s)}send(e,t,r){const n=this._extensions[s.extensionName];let o,i,c=t.binary?2:1,u=t.compress;"string"==typeof e?(o=Buffer.byteLength(e),i=!1):a(e)?(o=e.size,i=!1):(o=(e=h(e)).length,i=h.readOnly),this._firstFragment?(this._firstFragment=!1,u&&n&&n.params[n._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(u=o>=n._threshold),this._compress=u):(u=!1,c=0),t.fin&&(this._firstFragment=!0);const l={[d]:o,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:c,readOnly:i,rsv1:u};a(e)?0!==this._state?this.enqueue([this.getBlobData,e,this._compress,l,r]):this.getBlobData(e,this._compress,l,r):0!==this._state?this.enqueue([this.dispatch,e,this._compress,l,r]):this.dispatch(e,this._compress,l,r)}getBlobData(e,t,s,r){this._bufferedBytes+=s[d],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(_,this,e,r)}this._bufferedBytes-=s[d];const n=h(e);t?this.dispatch(n,t,s,r):(this._state=0,this.sendFrame(y.frame(n,s),r),this.dequeue())}).catch(e=>{process.nextTick(b,this,e,r)})}dispatch(e,t,r,n){if(!t)return void this.sendFrame(y.frame(e,r),n);const o=this._extensions[s.extensionName];this._bufferedBytes+=r[d],this._state=1,o.compress(e,r.fin,(e,t)=>{if(this._socket.destroyed){return void _(this,new Error("The socket was closed while data was being compressed"),n)}this._bufferedBytes-=r[d],this._state=0,r.readOnly=!1,this.sendFrame(y.frame(t,r),n),this.dequeue()})}dequeue(){for(;0===this._state&&this._queue.length;){const e=this._queue.shift();this._bufferedBytes-=e[3][d],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][d],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 _(e,t,s){"function"==typeof s&&s(t);for(let s=0;s<e._queue.length;s++){const r=e._queue[s],n=r[r.length-1];"function"==typeof n&&n(t)}}function b(e,t,s){_(e,t,s),e.onerror(t)}return te=y}function be(){if(ie)return oe;ie=1;const{tokenChars:e}=ge();function t(e,t,s){void 0===e[t]?e[t]=[s]:e[t].push(s)}return oe={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 n,o,i=Object.create(null),a=!1,c=!1,u=!1,l=-1,h=-1,d=-1,f=0;for(;f<s.length;f++)if(h=s.charCodeAt(f),void 0===n)if(-1===d&&1===e[h])-1===l&&(l=f);else if(0===f||32!==h&&9!==h){if(59!==h&&44!==h)throw new SyntaxError(`Unexpected character at index ${f}`);{if(-1===l)throw new SyntaxError(`Unexpected character at index ${f}`);-1===d&&(d=f);const e=s.slice(l,d);44===h?(t(r,e,i),i=Object.create(null)):n=e,l=d=-1}}else-1===d&&-1!==l&&(d=f);else if(void 0===o)if(-1===d&&1===e[h])-1===l&&(l=f);else if(32===h||9===h)-1===d&&-1!==l&&(d=f);else if(59===h||44===h){if(-1===l)throw new SyntaxError(`Unexpected character at index ${f}`);-1===d&&(d=f),t(i,s.slice(l,d),!0),44===h&&(t(r,n,i),i=Object.create(null),n=void 0),l=d=-1}else{if(61!==h||-1===l||-1!==d)throw new SyntaxError(`Unexpected character at index ${f}`);o=s.slice(l,f),l=d=-1}else if(c){if(1!==e[h])throw new SyntaxError(`Unexpected character at index ${f}`);-1===l?l=f:a||(a=!0),c=!1}else if(u)if(1===e[h])-1===l&&(l=f);else if(34===h&&-1!==l)u=!1,d=f;else{if(92!==h)throw new SyntaxError(`Unexpected character at index ${f}`);c=!0}else if(34===h&&61===s.charCodeAt(f-1))u=!0;else if(-1===d&&1===e[h])-1===l&&(l=f);else if(-1===l||32!==h&&9!==h){if(59!==h&&44!==h)throw new SyntaxError(`Unexpected character at index ${f}`);{if(-1===l)throw new SyntaxError(`Unexpected character at index ${f}`);-1===d&&(d=f);let e=s.slice(l,d);a&&(e=e.replace(/\\/g,""),a=!1),t(i,o,e),44===h&&(t(r,n,i),i=Object.create(null),n=void 0),o=void 0,l=d=-1}}else-1===d&&(d=f);if(-1===l||u||32===h||9===h)throw new SyntaxError("Unexpected end of input");-1===d&&(d=f);const p=s.slice(l,d);return void 0===n?t(r,p,i):(void 0===o?t(i,p,!0):t(i,o,a?p.replace(/\\/g,""):p),t(r,n,i)),r}},oe}function we(){if(ce)return ae;ce=1;const e=a,t=d,s=c,r=f,n=p,{randomBytes:o,createHash:l}=u,{Duplex:h,Readable:g}=i,{URL:y}=m,_=X(),b=ye(),w=_e(),{isBlob:v}=ge(),{BINARY_TYPES:x,EMPTY_BUFFER:S,GUID:k,kForOnEventAttribute:E,kListener:j,kStatusCode:T,kWebSocket:C,NOOP:O}=J(),{EventTarget:{addEventListener:I,removeEventListener:A}}=function(){if(ne)return re;ne=1;const{kForOnEventAttribute:e,kListener:t}=J(),s=Symbol("kCode"),r=Symbol("kData"),n=Symbol("kError"),o=Symbol("kMessage"),i=Symbol("kReason"),a=Symbol("kTarget"),c=Symbol("kType"),u=Symbol("kWasClean");class l{constructor(e){this[a]=null,this[c]=e}get target(){return this[a]}get type(){return this[c]}}Object.defineProperty(l.prototype,"target",{enumerable:!0}),Object.defineProperty(l.prototype,"type",{enumerable:!0});class h extends l{constructor(e,t={}){super(e),this[s]=void 0===t.code?0:t.code,this[i]=void 0===t.reason?"":t.reason,this[u]=void 0!==t.wasClean&&t.wasClean}get code(){return this[s]}get reason(){return this[i]}get wasClean(){return this[u]}}Object.defineProperty(h.prototype,"code",{enumerable:!0}),Object.defineProperty(h.prototype,"reason",{enumerable:!0}),Object.defineProperty(h.prototype,"wasClean",{enumerable:!0});class d extends l{constructor(e,t={}){super(e),this[n]=void 0===t.error?null:t.error,this[o]=void 0===t.message?"":t.message}get error(){return this[n]}get message(){return this[o]}}Object.defineProperty(d.prototype,"error",{enumerable:!0}),Object.defineProperty(d.prototype,"message",{enumerable:!0});class f extends l{constructor(e,t={}){super(e),this[r]=void 0===t.data?null:t.data}get data(){return this[r]}}Object.defineProperty(f.prototype,"data",{enumerable:!0});const p={addEventListener(s,r,n={}){for(const o of this.listeners(s))if(!n[e]&&o[t]===r&&!o[e])return;let o;if("message"===s)o=function(e,t){const s=new f("message",{data:t?e:e.toString()});s[a]=this,m(r,this,s)};else if("close"===s)o=function(e,t){const s=new h("close",{code:e,reason:t.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});s[a]=this,m(r,this,s)};else if("error"===s)o=function(e){const t=new d("error",{error:e,message:e.message});t[a]=this,m(r,this,t)};else{if("open"!==s)return;o=function(){const e=new l("open");e[a]=this,m(r,this,e)}}o[e]=!!n[e],o[t]=r,n.once?this.once(s,o):this.on(s,o)},removeEventListener(s,r){for(const n of this.listeners(s))if(n[t]===r&&!n[e]){this.removeListener(s,n);break}}};function m(e,t,s){"object"==typeof e&&e.handleEvent?e.handleEvent.call(e,s):e.call(t,s)}return re={CloseEvent:h,ErrorEvent:d,Event:l,EventTarget:p,MessageEvent:f}}(),{format:R,parse:N}=be(),{toBuffer:B}=K(),P=Symbol("kAborted"),M=[8,13],L=["CONNECTING","OPEN","CLOSING","CLOSED"],U=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;class D extends e{constructor(e,t,s){super(),this._binaryType=x[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=S,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=D.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]),z(this,e,t,s)):(this._autoPong=s.autoPong,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){x.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 b({allowSynchronousEvents:s.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation}),n=new w(e,this._extensions,s.generateMask);this._receiver=r,this._sender=n,this._socket=e,r[C]=this,n[C]=this,e[C]=this,r.on("conclude",Z),r.on("drain",G),r.on("error",V),r.on("message",Q),r.on("ping",ee),r.on("pong",te),n.onerror=oe,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",ue),e.on("data",le),e.on("end",he),e.on("error",de),this._readyState=D.OPEN,this.emit("open")}emitClose(){if(!this._socket)return this._readyState=D.CLOSED,void this.emit("close",this._closeCode,this._closeMessage);this._extensions[_.extensionName]&&this._extensions[_.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=D.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,t){if(this.readyState!==D.CLOSED){if(this.readyState===D.CONNECTING){const e="WebSocket was closed before the connection was established";return void F(this,this._req,e)}this.readyState!==D.CLOSING?(this._readyState=D.CLOSING,this._sender.close(e,t,!this._isServer,e=>{e||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),ie(this)):this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end()}}pause(){this.readyState!==D.CONNECTING&&this.readyState!==D.CLOSED&&(this._paused=!0,this._socket.pause())}ping(e,t,s){if(this.readyState===D.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===D.OPEN?(void 0===t&&(t=!this._isServer),this._sender.ping(e||S,t,s)):$(this,e,s)}pong(e,t,s){if(this.readyState===D.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===D.OPEN?(void 0===t&&(t=!this._isServer),this._sender.pong(e||S,t,s)):$(this,e,s)}resume(){this.readyState!==D.CONNECTING&&this.readyState!==D.CLOSED&&(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,t,s){if(this.readyState===D.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!==D.OPEN)return void $(this,e,s);const r={binary:"string"!=typeof e,mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[_.extensionName]||(r.compress=!1),this._sender.send(e||S,r,s)}terminate(){if(this.readyState!==D.CLOSED){if(this.readyState===D.CONNECTING){const e="WebSocket was closed before the connection was established";return void F(this,this._req,e)}this._socket&&(this._readyState=D.CLOSING,this._socket.destroy())}}}function z(e,r,n,i){const a={allowSynchronousEvents:!0,autoPong:!0,protocolVersion:M[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...i,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=a.autoPong,!M.includes(a.protocolVersion))throw new RangeError(`Unsupported protocol version: ${a.protocolVersion} (supported versions: ${M.join(", ")})`);let c;if(r instanceof y)c=r;else try{c=new y(r)}catch(e){throw new SyntaxError(`Invalid URL: ${r}`)}"http:"===c.protocol?c.protocol="ws:":"https:"===c.protocol&&(c.protocol="wss:"),e._url=c.href;const u="wss:"===c.protocol,h="ws+unix:"===c.protocol;let d;if("ws:"===c.protocol||u||h?h&&!c.pathname?d="The URL's pathname is empty":c.hash&&(d="The URL contains a fragment identifier"):d='The URL\'s protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"',d){const t=new SyntaxError(d);if(0===e._redirects)throw t;return void q(e,t)}const f=u?443:80,p=o(16).toString("base64"),m=u?t.request:s.request,g=new Set;let b,w;if(a.createConnection=a.createConnection||(u?W:H),a.defaultPort=a.defaultPort||f,a.port=c.port||f,a.host=c.hostname.startsWith("[")?c.hostname.slice(1,-1):c.hostname,a.headers={...a.headers,"Sec-WebSocket-Version":a.protocolVersion,"Sec-WebSocket-Key":p,Connection:"Upgrade",Upgrade:"websocket"},a.path=c.pathname+c.search,a.timeout=a.handshakeTimeout,a.perMessageDeflate&&(b=new _(!0!==a.perMessageDeflate?a.perMessageDeflate:{},!1,a.maxPayload),a.headers["Sec-WebSocket-Extensions"]=R({[_.extensionName]:b.offer()})),n.length){for(const e of n){if("string"!=typeof e||!U.test(e)||g.has(e))throw new SyntaxError("An invalid or duplicated subprotocol was specified");g.add(e)}a.headers["Sec-WebSocket-Protocol"]=n.join(",")}if(a.origin&&(a.protocolVersion<13?a.headers["Sec-WebSocket-Origin"]=a.origin:a.headers.Origin=a.origin),(c.username||c.password)&&(a.auth=`${c.username}:${c.password}`),h){const e=a.path.split(":");a.socketPath=e[0],a.path=e[1]}if(a.followRedirects){if(0===e._redirects){e._originalIpc=h,e._originalSecure=u,e._originalHostOrSocketPath=h?a.socketPath:c.host;const t=i&&i.headers;if(i={...i,headers:{}},t)for(const[e,s]of Object.entries(t))i.headers[e.toLowerCase()]=s}else if(0===e.listenerCount("redirect")){const t=h?!!e._originalIpc&&a.socketPath===e._originalHostOrSocketPath:!e._originalIpc&&c.host===e._originalHostOrSocketPath;(!t||e._originalSecure&&!u)&&(delete a.headers.authorization,delete a.headers.cookie,t||delete a.headers.host,a.auth=void 0)}a.auth&&!i.headers.authorization&&(i.headers.authorization="Basic "+Buffer.from(a.auth).toString("base64")),w=e._req=m(a),e._redirects&&e.emit("redirect",e.url,w)}else w=e._req=m(a);a.timeout&&w.on("timeout",()=>{F(e,w,"Opening handshake has timed out")}),w.on("error",t=>{null===w||w[P]||(w=e._req=null,q(e,t))}),w.on("response",t=>{const s=t.headers.location,o=t.statusCode;if(s&&a.followRedirects&&o>=300&&o<400){if(++e._redirects>a.maxRedirects)return void F(e,w,"Maximum redirects exceeded");let t;w.abort();try{t=new y(s,r)}catch(t){const r=new SyntaxError(`Invalid URL: ${s}`);return void q(e,r)}z(e,t,n,i)}else e.emit("unexpected-response",w,t)||F(e,w,`Unexpected server response: ${t.statusCode}`)}),w.on("upgrade",(t,s,r)=>{if(e.emit("upgrade",t),e.readyState!==D.CONNECTING)return;w=e._req=null;const n=t.headers.upgrade;if(void 0===n||"websocket"!==n.toLowerCase())return void F(e,s,"Invalid Upgrade header");const o=l("sha1").update(p+k).digest("base64");if(t.headers["sec-websocket-accept"]!==o)return void F(e,s,"Invalid Sec-WebSocket-Accept header");const i=t.headers["sec-websocket-protocol"];let c;if(void 0!==i?g.size?g.has(i)||(c="Server sent an invalid subprotocol"):c="Server sent a subprotocol but none was requested":g.size&&(c="Server sent no subprotocol"),c)return void F(e,s,c);i&&(e._protocol=i);const u=t.headers["sec-websocket-extensions"];if(void 0!==u){if(!b){return void F(e,s,"Server sent a Sec-WebSocket-Extensions header but no extension was requested")}let t;try{t=N(u)}catch(t){return void F(e,s,"Invalid Sec-WebSocket-Extensions header")}const r=Object.keys(t);if(1!==r.length||r[0]!==_.extensionName){return void F(e,s,"Server indicated an extension that was not requested")}try{b.accept(t[_.extensionName])}catch(t){return void F(e,s,"Invalid Sec-WebSocket-Extensions header")}e._extensions[_.extensionName]=b}e.setSocket(s,r,{allowSynchronousEvents:a.allowSynchronousEvents,generateMask:a.generateMask,maxPayload:a.maxPayload,skipUTF8Validation:a.skipUTF8Validation})}),a.finishRequest?a.finishRequest(w,e):w.end()}function q(e,t){e._readyState=D.CLOSING,e._errorEmitted=!0,e.emit("error",t),e.emitClose()}function H(e){return e.path=e.socketPath,r.connect(e)}function W(e){return e.path=void 0,e.servername||""===e.servername||(e.servername=r.isIP(e.host)?"":e.host),n.connect(e)}function F(e,t,s){e._readyState=D.CLOSING;const r=new Error(s);Error.captureStackTrace(r,F),t.setHeader?(t[P]=!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 $(e,t,s){if(t){const s=v(t)?t.size:B(t).length;e._socket?e._sender._bufferedBytes+=s:e._bufferedAmount+=s}if(s){const t=new Error(`WebSocket is not open: readyState ${e.readyState} (${L[e.readyState]})`);process.nextTick(s,t)}}function Z(e,t){const s=this[C];s._closeFrameReceived=!0,s._closeMessage=t,s._closeCode=e,void 0!==s._socket[C]&&(s._socket.removeListener("data",le),process.nextTick(se,s._socket),1005===e?s.close():s.close(e,t))}function G(){const e=this[C];e.isPaused||e._socket.resume()}function V(e){const t=this[C];void 0!==t._socket[C]&&(t._socket.removeListener("data",le),process.nextTick(se,t._socket),t.close(e[T])),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e))}function Y(){this[C].emitClose()}function Q(e,t){this[C].emit("message",e,t)}function ee(e){const t=this[C];t._autoPong&&t.pong(e,!this._isServer,O),t.emit("ping",e)}function te(e){this[C].emit("pong",e)}function se(e){e.resume()}function oe(e){const t=this[C];t.readyState!==D.CLOSED&&(t.readyState===D.OPEN&&(t._readyState=D.CLOSING,ie(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e)))}function ie(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),3e4)}function ue(){const e=this[C];let t;this.removeListener("close",ue),this.removeListener("data",le),this.removeListener("end",he),e._readyState=D.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",Y),e._receiver.on("finish",Y))}function le(e){this[C]._receiver.write(e)||this.pause()}function he(){const e=this[C];e._readyState=D.CLOSING,e._receiver.end(),this.end()}function de(){const e=this[C];this.removeListener("error",de),this.on("error",O),e&&(e._readyState=D.CLOSING,this.destroy())}return Object.defineProperty(D,"CONNECTING",{enumerable:!0,value:L.indexOf("CONNECTING")}),Object.defineProperty(D.prototype,"CONNECTING",{enumerable:!0,value:L.indexOf("CONNECTING")}),Object.defineProperty(D,"OPEN",{enumerable:!0,value:L.indexOf("OPEN")}),Object.defineProperty(D.prototype,"OPEN",{enumerable:!0,value:L.indexOf("OPEN")}),Object.defineProperty(D,"CLOSING",{enumerable:!0,value:L.indexOf("CLOSING")}),Object.defineProperty(D.prototype,"CLOSING",{enumerable:!0,value:L.indexOf("CLOSING")}),Object.defineProperty(D,"CLOSED",{enumerable:!0,value:L.indexOf("CLOSED")}),Object.defineProperty(D.prototype,"CLOSED",{enumerable:!0,value:L.indexOf("CLOSED")}),["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(e=>{Object.defineProperty(D.prototype,e,{enumerable:!0})}),["open","error","close","message"].forEach(e=>{Object.defineProperty(D.prototype,`on${e}`,{enumerable:!0,get(){for(const t of this.listeners(e))if(t[E])return t[j];return null},set(t){for(const t of this.listeners(e))if(t[E]){this.removeListener(e,t);break}"function"==typeof t&&this.addEventListener(e,t,{[E]:!0})}})}),D.prototype.addEventListener=I,D.prototype.removeEventListener=A,ae=D}function ve(){if(de)return he;de=1;const{tokenChars:e}=ge();return he={parse:function(t){const s=new Set;let r=-1,n=-1,o=0;for(;o<t.length;o++){const i=t.charCodeAt(o);if(-1===n&&1===e[i])-1===r&&(r=o);else if(0===o||32!==i&&9!==i){if(44!==i)throw new SyntaxError(`Unexpected character at index ${o}`);{if(-1===r)throw new SyntaxError(`Unexpected character at index ${o}`);-1===n&&(n=o);const e=t.slice(r,n);if(s.has(e))throw new SyntaxError(`The "${e}" subprotocol is duplicated`);s.add(e),r=n=-1}}else-1===n&&-1!==r&&(n=o)}if(-1===r||-1!==n)throw new SyntaxError("Unexpected end of input");const i=t.slice(r,o);if(s.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);return s.add(i),s}},he}!function(){if(le)return ue;le=1,we();const{Duplex:e}=i;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)}ue=function(n,o){let i=!0;const a=new e({...o,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return n.on("message",function(e,t){const s=!t&&a._readableState.objectMode?e.toString():e;a.push(s)||n.pause()}),n.once("error",function(e){a.destroyed||(i=!1,a.destroy(e))}),n.once("close",function(){a.destroyed||a.push(null)}),a._destroy=function(e,s){if(n.readyState===n.CLOSED)return s(e),void process.nextTick(t,a);let r=!1;n.once("error",function(e){r=!0,s(e)}),n.once("close",function(){r||s(e),process.nextTick(t,a)}),i&&n.terminate()},a._final=function(e){n.readyState!==n.CONNECTING?null!==n._socket&&(n._socket._writableState.finished?(e(),a._readableState.endEmitted&&a.destroy()):(n._socket.once("finish",function(){e()}),n.close())):n.once("open",function(){a._final(e)})},a._read=function(){n.isPaused&&n.resume()},a._write=function(e,t,s){n.readyState!==n.CONNECTING?n.send(e,s):n.once("open",function(){a._write(e,t,s)})},a.on("end",s),a.on("error",r),a}}(),ye(),_e(),we();var xe=function(){if(pe)return fe;pe=1;const e=a,t=c,{Duplex:s}=i,{createHash:r}=u,n=be(),o=X(),l=ve(),h=we(),{GUID:d,kWebSocket:f}=J(),p=/^[+/0-9A-Za-z]{22}==$/;function m(e){e._state=2,e.emit("close")}function g(){this.destroy()}function y(e,s,r,n){r=r||t.STATUS_CODES[s],n={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(r),...n},e.once("finish",e.destroy),e.end(`HTTP/1.1 ${s} ${t.STATUS_CODES[s]}\r\n`+Object.keys(n).map(e=>`${e}: ${n[e]}`).join("\r\n")+"\r\n\r\n"+r)}function _(e,t,s,r,n){if(e.listenerCount("wsClientError")){const r=new Error(n);Error.captureStackTrace(r,_),e.emit("wsClientError",r,s,t)}else y(s,r,n)}return fe=class extends e{constructor(e,s){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:h,...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=t.createServer((e,s)=>{const r=t.STATUS_CODES[426];s.writeHead(426,{"Content-Length":r.length,"Content-Type":"text/plain"}),s.end(r)}),this._server.listen(e.port,e.host,e.backlog,s)):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(m,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(m,this);else{const e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close(()=>{m(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",g);const i=e.headers["sec-websocket-key"],a=e.headers.upgrade,c=+e.headers["sec-websocket-version"];if("GET"!==e.method){return void _(this,e,t,405,"Invalid HTTP method")}if(void 0===a||"websocket"!==a.toLowerCase()){return void _(this,e,t,400,"Invalid Upgrade header")}if(void 0===i||!p.test(i)){return void _(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header")}if(8!==c&&13!==c){return void _(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header")}if(!this.shouldHandle(e))return void y(t,400);const u=e.headers["sec-websocket-protocol"];let h=new Set;if(void 0!==u)try{h=l.parse(u)}catch(s){return void _(this,e,t,400,"Invalid Sec-WebSocket-Protocol header")}const d=e.headers["sec-websocket-extensions"],f={};if(this.options.perMessageDeflate&&void 0!==d){const s=new o(this.options.perMessageDeflate,!0,this.options.maxPayload);try{const e=n.parse(d);e[o.extensionName]&&(s.accept(e[o.extensionName]),f[o.extensionName]=s)}catch(s){return void _(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header")}}if(this.options.verifyClient){const n={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(n,(n,o,a,c)=>{if(!n)return y(t,o||401,a,c);this.completeUpgrade(f,i,h,e,t,s,r)});if(!this.options.verifyClient(n))return y(t,401)}this.completeUpgrade(f,i,h,e,t,s,r)}completeUpgrade(e,t,s,i,a,c,u){if(!a.readable||!a.writable)return a.destroy();if(a[f])throw new Error("server.handleUpgrade() was called mor