@ibm/mapepire-js
Version:
Db2 client for node
1 lines • 59.6 kB
JavaScript
(()=>{"use strict";var e={440(e,t,s){var r=this&&this.__createBinding||(Object.create?function(e,t,s,r){void 0===r&&(r=s);var o=Object.getOwnPropertyDescriptor(t,s);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[s]}}),Object.defineProperty(e,r,o)}:function(e,t,s,r){void 0===r&&(r=s),e[r]=t[s]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),i=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var s in e)"default"!==s&&Object.prototype.hasOwnProperty.call(e,s)&&r(t,e,s);return o(t,e),t},n=this&&this.__exportStar||function(e,t){for(var s in e)"default"===s||Object.prototype.hasOwnProperty.call(t,s)||r(t,e,s)};Object.defineProperty(t,"__esModule",{value:!0}),t.States=t.getRootCertificate=t.getCertificate=t.Pool=t.SQLJob=void 0;var a=s(781);Object.defineProperty(t,"SQLJob",{enumerable:!0,get:function(){return a.SQLJob}});var c=s(696);Object.defineProperty(t,"Pool",{enumerable:!0,get:function(){return c.Pool}});var h=s(369);Object.defineProperty(t,"getCertificate",{enumerable:!0,get:function(){return h.getCertificate}}),Object.defineProperty(t,"getRootCertificate",{enumerable:!0,get:function(){return h.getRootCertificate}}),t.States=i(s(748)),n(s(209),t)},696(e,t,s){Object.defineProperty(t,"__esModule",{value:!0}),t.Pool=void 0;const r=s(781),o=s(748),i=[o.JobStatus.ENDED,o.JobStatus.NOT_STARTED];t.Pool=class{options;jobs=[];constructor(e){this.options=e}init(){let e=[];if(this.options.maxSize<=0)return Promise.reject("Max size must be greater than 0");if(this.options.startingSize<=0)return Promise.reject("Starting size must be greater than 0");if(this.options.startingSize>this.options.maxSize)return Promise.reject("Max size must be greater than or equal to starting size");for(let t=0;t<this.options.startingSize;t++)e.push(this.addJob());return Promise.all(e)}hasSpace(){return this.jobs.filter(e=>!i.includes(e.getStatus())).length<this.options.maxSize}getActiveJobCount(){return this.jobs.filter(e=>"busy"===e.getStatus()||"ready"===e.getStatus()).length}cleanup(){for(let e=this.jobs.length-1;e>=0;e--)i.includes(this.jobs[e].getStatus())&&this.jobs.splice(e,1)}async addJob(e={}){e.existingJob&&this.cleanup();const t=e.existingJob||new r.SQLJob(this.options.opts);return!0!==e.poolIgnore&&this.jobs.push(t),"notStarted"===t.getStatus()&&await t.connect(this.options.creds),t}getReadyJob(){return this.jobs.find(e=>"ready"===e.getStatus())}getReadyJobIndex(){return this.jobs.findIndex(e=>"ready"===e.getStatus())}getJob(){const e=this.getReadyJob();if(!e){const e=this.jobs.filter(e=>"busy"===e.getStatus()).sort((e,t)=>e.getRunningCount()-t.getRunningCount())[0];return this.hasSpace()&&e.getRunningCount()>2&&this.addJob(),e}return e}async waitForJob(e=!1){const t=this.getReadyJob();return t||(this.hasSpace()||e?await this.addJob():this.getJob())}async popJob(){const e=this.getReadyJobIndex();return e>-1?this.jobs.splice(e,1)[0]:await this.addJob({poolIgnore:!0})}query(e,t){return this.getJob().query(e,t)}execute(e,t){return this.getJob().execute(e,t)}sql(e,...t){const s=this.getJob(),r=e.join("?");return s.execute(r,{parameters:t})}end(){this.jobs.forEach(e=>e.close())}}},912(e,t,s){Object.defineProperty(t,"__esModule",{value:!0}),t.Query=void 0;const r=s(781);class o{job;static globalQueryList=[];correlationId;sql;isPrepared=!1;parameters;rowsToFetch=100;isCLCommand;state="NOT_YET_RUN";isTerseResults;constructor(e,t,s={isClCommand:!1,parameters:void 0}){if(this.job=e,"string"!=typeof t)throw new TypeError("Query must be of type string");this.job=e,this.isPrepared=void 0!==s.parameters,this.parameters=s.parameters,this.sql=t,this.isCLCommand=s.isClCommand,this.isTerseResults=s.isTerseResults,o.globalQueryList.push(this)}static byId(e){return void 0===e||""===e?void 0:o.globalQueryList.find(t=>t.correlationId===e)}static getOpenIds(e){return this.globalQueryList.filter(t=>t.job==e||void 0===e).filter(e=>"NOT_YET_RUN"===e.getState()||"RUN_MORE_DATA_AVAILABLE"===e.getState()).map(e=>e.correlationId)}static async cleanup(){let e=[];for(const t of this.globalQueryList)"RUN_DONE"!==t.getState()&&"ERROR"!==t.getState()||e.push(t.close());await Promise.all(e),this.globalQueryList=this.globalQueryList.filter(e=>"RUN_DONE"!==e.getState())}addToBatch(e){if(this.parameters=this.parameters??[],!Array.isArray(e)||!e.every(Array.isArray))throw new Error("Parameter 'parameters' must be a 2D array of parameters to the query");return this.parameters.push(...e),this.isPrepared=!0,this.parameters}async execute(e=this.rowsToFetch){if("number"!=typeof e)throw new Error("rowsToFetch must be a number");if(e<=0)throw new Error("rowsToFetch must be greater than 0");switch(this.state){case"RUN_MORE_DATA_AVAILABLE":throw new Error("Statement has already been run");case"RUN_DONE":throw new Error("Statement has already been fully run")}let t;t=this.isCLCommand?{id:r.SQLJob.getNewUniqueId("clcommand"),type:"cl",terse:this.isTerseResults,cmd:this.sql}:{id:r.SQLJob.getNewUniqueId("query"),type:this.isPrepared?"prepare_sql_execute":"sql",sql:this.sql,terse:this.isTerseResults,rows:e,parameters:this.parameters},this.rowsToFetch=e;let s=await this.job.send(t);if(this.state=s.is_done?"RUN_DONE":"RUN_MORE_DATA_AVAILABLE",!0!==s.success&&!this.isCLCommand){this.state="ERROR";let e=[s.error,s.sql_state,s.sql_rc].filter(e=>void 0!==e);throw 0===e.length&&e.push("Failed to run query (unknown error)"),new Error(e.join(", "))}return this.correlationId=s.id,s}async fetchMore(e=this.rowsToFetch){switch(this.state){case"NOT_YET_RUN":throw new Error("Statement has not yet been run");case"RUN_DONE":throw new Error("Statement has already been fully run")}let t={id:r.SQLJob.getNewUniqueId("fetchMore"),cont_id:this.correlationId,type:"sqlmore",sql:this.sql,rows:e};this.rowsToFetch=e;let s=await this.job.send(t);if(this.state=s.is_done?"RUN_DONE":"RUN_MORE_DATA_AVAILABLE",!0!==s.success)throw this.state="ERROR",new Error(s.error||"Failed to run query (unknown error)");return s}async close(){if(this.correlationId&&"RUN_DONE"!==this.state){this.state="RUN_DONE";let e={id:r.SQLJob.getNewUniqueId("sqlclose"),cont_id:this.correlationId,type:"sqlclose"};return this.job.send(e)}void 0===this.correlationId&&(this.state="RUN_DONE")}getHostJob(){return this.job}getId(){return this.correlationId}getState(){return this.state}}t.Query=o},781(e,t,s){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.UrlToDaemon=t.SQLJob=t.DEFAULT_PORT=void 0;const o=s(203),i=r(s(699)),n=s(912),a=s(748),c=["select count(*) as thecount"," from qsys2.db_transaction_info"," where JOB_NAME = qsys2.job_name and"," (local_record_changes_pending = 'YES' or local_object_changes_pending = 'YES')"].join("\n");t.DEFAULT_PORT=8076;class h{options;static uniqueIdCounter=0;socket;responseEmitter=new o.EventEmitter;status=a.JobStatus.NOT_STARTED;traceFile;isTracingChannelData=!1;uniqueId=h.getNewUniqueId("sqljob");id;static getNewUniqueId(e="id"){return e+ ++h.uniqueIdCounter}constructor(e={}){this.options=e}enableLocalTrace(){this.isTracingChannelData=!0}getChannel(e){return new Promise((s,r)=>{const o=new i.default(`wss://${e.host}:${e.port||t.DEFAULT_PORT}/db/`,{headers:{authorization:`Basic ${Buffer.from(`${e.user}:${e.password}`).toString("base64")}`},ca:e.ca,timeout:5e3,rejectUnauthorized:e.rejectUnauthorized});o.on("error",e=>{console.log(e),r(e)}),o.on("message",e=>{const t=e.toString();this.isTracingChannelData&&console.log(t);try{let e=JSON.parse(t);this.responseEmitter.emit(e.id,e)}catch(e){console.log("Error: "+e)}}),o.once("open",()=>{s(o)})})}async send(e){return this.isTracingChannelData&&console.log(e),this.socket.send(JSON.stringify(e)),new Promise((t,s)=>{this.status=a.JobStatus.BUSY;const r=()=>{this.responseEmitter.removeAllListeners(e.id),this.responseEmitter.removeAllListeners(`${e.id}_conn_fail`)};this.responseEmitter.on(e.id,e=>{r(),this.status=0===this.getRunningCount()?a.JobStatus.READY:a.JobStatus.BUSY,t(e)}),this.responseEmitter.on(`${e.id}_conn_fail`,e=>{r(),s(e)})})}getStatus(){return this.status}getRunningCount(){return this.responseEmitter.eventNames().length/2}async connect(e){this.status=a.JobStatus.CONNECTING,this.socket=await this.getChannel(e),this.socket.on("error",e=>{console.log(e),this.dispose()}),this.socket.on("close",(e,t)=>{const s=this.responseEmitter.eventNames().filter(e=>"string"==typeof e&&e.endsWith("_conn_fail"));for(const r of s){const s=`Connection failed with code ${e}`+(t.length>0?`: ${t.toString()}`:"");this.responseEmitter.emit(r,new Error(s))}this.responseEmitter.removeAllListeners(),this.dispose()});const t=Object.keys(this.options).map(e=>Array.isArray(this.options[e])?`${e}=${this.options[e].join(",")}`:`${e}=${this.options[e]}`).join(";"),s={id:h.getNewUniqueId(),type:"connect",technique:"tcp",application:"Node.js client",props:t.length>0?t:void 0},r=await this.send(s);if(!0!==r.success)throw this.dispose(),this.status=a.JobStatus.CONNECTING,new Error(r.error||"Failed to connect to server.");return this.status=a.JobStatus.READY,this.id=r.job,this.isTracingChannelData=!1,r}query(e,t){return new n.Query(this,e,t)}async execute(e,t){const s=this.query(e,t),r=await s.execute();if(await s.close(),r.error)throw new Error(r.error);return r}async getVersion(){const e={id:h.getNewUniqueId(),type:"getversion"},t=await this.send(e);if(!0!==t.success)throw new Error(t.error||"Failed to get version from backend");return t}async explain(e,t=a.ExplainType.RUN){const s={id:h.getNewUniqueId(),type:"dove",sql:e,run:"run"===t},r=await this.send(s);if(!0!==r.success)throw new Error(r.error||"Failed to explain.");return r}getTraceFilePath(){return this.traceFile}async getTraceData(){const e={id:h.getNewUniqueId(),type:"gettracedata"},t=await this.send(e);if(!0!==t.success)throw new Error(t.error||"Failed to get trace data from backend");return t}async setTraceConfig(e,t){const s={id:h.getNewUniqueId(),type:"setconfig",tracedest:e,tracelevel:t};this.isTracingChannelData=!0;const r=await this.send(s);if(!0!==r.success)throw new Error(r.error||"Failed to set trace options on backend");return this.traceFile=r.tracedest&&"/"===r.tracedest[0]?r.tracedest:void 0,r}clcommand(e){return new n.Query(this,e,{isClCommand:!0})}underCommitControl(){return this.options["transaction isolation"]&&"none"!==this.options["transaction isolation"]}async getPendingTransactions(){const e=await this.query(c).execute(1);return e.success&&e.data&&1===e.data.length&&e.data[0].THECOUNT?e.data[0].THECOUNT:0}async endTransaction(e){let t;switch(e){case a.TransactionEndType.COMMIT:case a.TransactionEndType.ROLLBACK:t=e.toUpperCase();break;default:throw new Error(`TransactionEndType ${e} not valid`)}return this.query(t).execute()}getUniqueId(){return this.uniqueId}async close(){this.responseEmitter.removeAllListeners(),this.dispose()}getSocket(){return this.socket}dispose(){this.socket&&this.socket.close(),this.status=a.JobStatus.ENDED}}t.SQLJob=h,t.UrlToDaemon=function(e){const t=new URL(e);if("db2i:"!==t.protocol)throw new Error(`Invalid protocol ${t.protocol}. Only db2i is supported.`);const s=["username","password","hostname"];for(let e of s)if(!t[e])throw new Error(`Missing required field ${e}.`);const r=Buffer.from(t.password,"base64").toString(),[o,i]=r.split(":");return{host:t.hostname,port:parseInt(t.port||"8076"),user:t.username,password:o}}},748(e,t){var s,r,o;Object.defineProperty(t,"__esModule",{value:!0}),t.TransactionEndType=t.ExplainType=t.JobStatus=void 0,(o=t.JobStatus||(t.JobStatus={})).NOT_STARTED="notStarted",o.CONNECTING="connecting",o.READY="ready",o.BUSY="busy",o.ENDED="ended",(r=t.ExplainType||(t.ExplainType={})).RUN="run",r.DO_NOT_RUN="doNotRun",(s=t.TransactionEndType||(t.TransactionEndType={})).COMMIT="COMMIT",s.ROLLBACK="ROLLBACK"},369(e,t,s){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isSameCertificate=t.getRootCertificate=t.getCertificate=void 0;const o=r(s(756)),i=s(781);function n(e){return new Promise((t,s)=>{const r=o.default.connect(e.port||i.DEFAULT_PORT,e.host,{rejectUnauthorized:!1});r.once("secureConnect",()=>{const e=r.getPeerCertificate(!0);r.end(),t(e)}),r.once("error",e=>{"reason"in e&&"sslv3 alert handshake failure"===e.reason&&(e.message+=". Please ensure the Mapepire server is being run with Java version >= 11."),s(e)})})}function a(e,t){const s=Object.keys(e),r=Object.keys(t);if(s.length!==r.length)return!1;for(let o of s)if(!r.includes(o)||e[o]!==t[o])return!1;return!0}t.getCertificate=n,t.getRootCertificate=async function(e){let t=await n(e);for(;t&&t.issuerCertificate&&!a(t.subject,t.issuer);)t=t.issuerCertificate;const s=o.default.rootCertificates;let r=t.raw.toString("base64");const i=[];for(let e=0;e<r.length;e+=64)i.push(r.substring(e,e+64));r="-----BEGIN CERTIFICATE-----\n"+i.join("\n")+"\n-----END CERTIFICATE-----";for(let e of s)if(e.replace(/\n/g,"")===r.replace(/\n/g,""))return;return r},t.isSameCertificate=a},209(e,t){Object.defineProperty(t,"__esModule",{value:!0})},699(e,t,s){const r=s(60);r.createWebSocketStream=s(719),r.Server=s(722),r.Receiver=s(286),r.Sender=s(914),r.WebSocket=r,r.WebSocketServer=r.Server,e.exports=r},338(e,t,s){const{EMPTY_BUFFER:r}=s(614),o=Buffer[Symbol.species];function i(e,t,s,r,o){for(let i=0;i<o;i++)s[r+i]=e[i]^t[3&i]}function n(e,t){for(let s=0;s<e.length;s++)e[s]^=t[3&s]}if(e.exports={concat:function(e,t){if(0===e.length)return r;if(1===e.length)return e[0];const s=Buffer.allocUnsafe(t);let i=0;for(let t=0;t<e.length;t++){const r=e[t];s.set(r,i),i+=r.length}return i<t?new o(s.buffer,s.byteOffset,i):s},mask:i,toArrayBuffer:function(e){return e.length===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.length)},toBuffer:function e(t){if(e.readOnly=!0,Buffer.isBuffer(t))return t;let s;return t instanceof ArrayBuffer?s=new o(t):ArrayBuffer.isView(t)?s=new o(t.buffer,t.byteOffset,t.byteLength):(s=Buffer.from(t),e.readOnly=!1),s},unmask:n},!process.env.WS_NO_BUFFER_UTIL)try{const t=s(Object(function(){var e=new Error("Cannot find module 'bufferutil'");throw e.code="MODULE_NOT_FOUND",e}()));e.exports.mask=function(e,s,r,o,n){n<48?i(e,s,r,o,n):t.mask(e,s,r,o,n)},e.exports.unmask=function(e,s){e.length<32?n(e,s):t.unmask(e,s)}}catch(e){}},614(e){const t=["nodebuffer","arraybuffer","fragments"],s="undefined"!=typeof Blob;s&&t.push("blob"),e.exports={BINARY_TYPES:t,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:s,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}},597(e,t,s){const{kForOnEventAttribute:r,kListener:o}=s(614),i=Symbol("kCode"),n=Symbol("kData"),a=Symbol("kError"),c=Symbol("kMessage"),h=Symbol("kReason"),l=Symbol("kTarget"),d=Symbol("kType"),u=Symbol("kWasClean");class f{constructor(e){this[l]=null,this[d]=e}get target(){return this[l]}get type(){return this[d]}}Object.defineProperty(f.prototype,"target",{enumerable:!0}),Object.defineProperty(f.prototype,"type",{enumerable:!0});class _ extends f{constructor(e,t={}){super(e),this[i]=void 0===t.code?0:t.code,this[h]=void 0===t.reason?"":t.reason,this[u]=void 0!==t.wasClean&&t.wasClean}get code(){return this[i]}get reason(){return this[h]}get wasClean(){return this[u]}}Object.defineProperty(_.prototype,"code",{enumerable:!0}),Object.defineProperty(_.prototype,"reason",{enumerable:!0}),Object.defineProperty(_.prototype,"wasClean",{enumerable:!0});class p extends f{constructor(e,t={}){super(e),this[a]=void 0===t.error?null:t.error,this[c]=void 0===t.message?"":t.message}get error(){return this[a]}get message(){return this[c]}}Object.defineProperty(p.prototype,"error",{enumerable:!0}),Object.defineProperty(p.prototype,"message",{enumerable:!0});class m extends f{constructor(e,t={}){super(e),this[n]=void 0===t.data?null:t.data}get data(){return this[n]}}Object.defineProperty(m.prototype,"data",{enumerable:!0});const y={addEventListener(e,t,s={}){for(const i of this.listeners(e))if(!s[r]&&i[o]===t&&!i[r])return;let i;if("message"===e)i=function(e,s){const r=new m("message",{data:s?e:e.toString()});r[l]=this,b(t,this,r)};else if("close"===e)i=function(e,s){const r=new _("close",{code:e,reason:s.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});r[l]=this,b(t,this,r)};else if("error"===e)i=function(e){const s=new p("error",{error:e,message:e.message});s[l]=this,b(t,this,s)};else{if("open"!==e)return;i=function(){const e=new f("open");e[l]=this,b(t,this,e)}}i[r]=!!s[r],i[o]=t,s.once?this.once(e,i):this.on(e,i)},removeEventListener(e,t){for(const s of this.listeners(e))if(s[o]===t&&!s[r]){this.removeListener(e,s);break}}};function b(e,t,s){"object"==typeof e&&e.handleEvent?e.handleEvent.call(e,s):e.call(t,s)}e.exports={CloseEvent:_,ErrorEvent:p,Event:f,EventTarget:y,MessageEvent:m}},926(e,t,s){const{tokenChars:r}=s(880);function o(e,t,s){void 0===e[t]?e[t]=[s]:e[t].push(s)}e.exports={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(e){const t=Object.create(null);let s,i,n=Object.create(null),a=!1,c=!1,h=!1,l=-1,d=-1,u=-1,f=0;for(;f<e.length;f++)if(d=e.charCodeAt(f),void 0===s)if(-1===u&&1===r[d])-1===l&&(l=f);else if(0===f||32!==d&&9!==d){if(59!==d&&44!==d)throw new SyntaxError(`Unexpected character at index ${f}`);{if(-1===l)throw new SyntaxError(`Unexpected character at index ${f}`);-1===u&&(u=f);const r=e.slice(l,u);44===d?(o(t,r,n),n=Object.create(null)):s=r,l=u=-1}}else-1===u&&-1!==l&&(u=f);else if(void 0===i)if(-1===u&&1===r[d])-1===l&&(l=f);else if(32===d||9===d)-1===u&&-1!==l&&(u=f);else if(59===d||44===d){if(-1===l)throw new SyntaxError(`Unexpected character at index ${f}`);-1===u&&(u=f),o(n,e.slice(l,u),!0),44===d&&(o(t,s,n),n=Object.create(null),s=void 0),l=u=-1}else{if(61!==d||-1===l||-1!==u)throw new SyntaxError(`Unexpected character at index ${f}`);i=e.slice(l,f),l=u=-1}else if(c){if(1!==r[d])throw new SyntaxError(`Unexpected character at index ${f}`);-1===l?l=f:a||(a=!0),c=!1}else if(h)if(1===r[d])-1===l&&(l=f);else if(34===d&&-1!==l)h=!1,u=f;else{if(92!==d)throw new SyntaxError(`Unexpected character at index ${f}`);c=!0}else if(34===d&&61===e.charCodeAt(f-1))h=!0;else if(-1===u&&1===r[d])-1===l&&(l=f);else if(-1===l||32!==d&&9!==d){if(59!==d&&44!==d)throw new SyntaxError(`Unexpected character at index ${f}`);{if(-1===l)throw new SyntaxError(`Unexpected character at index ${f}`);-1===u&&(u=f);let r=e.slice(l,u);a&&(r=r.replace(/\\/g,""),a=!1),o(n,i,r),44===d&&(o(t,s,n),n=Object.create(null),s=void 0),i=void 0,l=u=-1}}else-1===u&&(u=f);if(-1===l||h||32===d||9===d)throw new SyntaxError("Unexpected end of input");-1===u&&(u=f);const _=e.slice(l,u);return void 0===s?o(t,_,n):(void 0===i?o(n,_,!0):o(n,i,a?_.replace(/\\/g,""):_),o(t,s,n)),t}}},759(e){const t=Symbol("kDone"),s=Symbol("kRun");e.exports=class{constructor(e){this[t]=()=>{this.pending--,this[s]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[s]()}[s](){if(this.pending!==this.concurrency&&this.jobs.length){const e=this.jobs.shift();this.pending++,e(this[t])}}}},971(e,t,s){const r=s(106),o=s(338),i=s(759),{kStatusCode:n}=s(614),a=Buffer[Symbol.species],c=Buffer.from([0,0,255,255]),h=Symbol("permessage-deflate"),l=Symbol("total-length"),d=Symbol("callback"),u=Symbol("buffers"),f=Symbol("error");let _;function p(e){this[u].push(e),this[l]+=e.length}function m(e){this[l]+=e.length,this[h]._maxPayload<1||this[l]<=this[h]._maxPayload?this[u].push(e):(this[f]=new RangeError("Max payload size exceeded"),this[f].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[f][n]=1009,this.removeListener("data",m),this.reset())}function y(e){this[h]._inflate=null,e[n]=1007,this[d](e)}e.exports=class{constructor(e,t,s){if(this._maxPayload=0|s,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,!_){const e=void 0!==this._options.concurrencyLimit?this._options.concurrencyLimit:10;_=new i(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[d];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){_.add(r=>{this._decompress(e,t,(e,t)=>{r(),s(e,t)})})}compress(e,t,s){_.add(r=>{this._compress(e,t,(e,t)=>{r(),s(e,t)})})}_decompress(e,t,s){const i=this._isServer?"client":"server";if(!this._inflate){const e=`${i}_max_window_bits`,t="number"!=typeof this.params[e]?r.Z_DEFAULT_WINDOWBITS:this.params[e];this._inflate=r.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[h]=this,this._inflate[l]=0,this._inflate[u]=[],this._inflate.on("error",y),this._inflate.on("data",m)}this._inflate[d]=s,this._inflate.write(e),t&&this._inflate.write(c),this._inflate.flush(()=>{const e=this._inflate[f];if(e)return this._inflate.close(),this._inflate=null,void s(e);const r=o.concat(this._inflate[u],this._inflate[l]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[l]=0,this._inflate[u]=[],t&&this.params[`${i}_no_context_takeover`]&&this._inflate.reset()),s(null,r)})}_compress(e,t,s){const i=this._isServer?"server":"client";if(!this._deflate){const e=`${i}_max_window_bits`,t="number"!=typeof this.params[e]?r.Z_DEFAULT_WINDOWBITS:this.params[e];this._deflate=r.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[l]=0,this._deflate[u]=[],this._deflate.on("data",p)}this._deflate[d]=s,this._deflate.write(e),this._deflate.flush(r.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let e=o.concat(this._deflate[u],this._deflate[l]);t&&(e=new a(e.buffer,e.byteOffset,e.length-4)),this._deflate[d]=null,this._deflate[l]=0,this._deflate[u]=[],t&&this.params[`${i}_no_context_takeover`]&&this._deflate.reset(),s(null,e)})}}},286(e,t,s){const{Writable:r}=s(203),o=s(971),{BINARY_TYPES:i,EMPTY_BUFFER:n,kStatusCode:a,kWebSocket:c}=s(614),{concat:h,toArrayBuffer:l,unmask:d}=s(338),{isValidStatusCode:u,isValidUTF8:f}=s(880),_=Buffer[Symbol.species];e.exports=class extends r{constructor(e={}){super(),this._allowSynchronousEvents=void 0===e.allowSynchronousEvents||e.allowSynchronousEvents,this._binaryType=e.binaryType||i[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=0|e.maxPayload,this._skipUTF8Validation=!!e.skipUTF8Validation,this[c]=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 _(t.buffer,t.byteOffset+e,t.length-e),new _(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 _(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 t=this.consume(2);if(48&t[0])return void e(this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3"));const s=!(64&~t[0]);if(!s||this._extensions[o.extensionName]){if(this._fin=!(128&~t[0]),this._opcode=15&t[0],this._payloadLength=127&t[1],0===this._opcode){if(s)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=s}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(s)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&~t[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);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")):(this._payloadLength=s*Math.pow(2,32)+t.readUInt32BE(4),this.haveLength(e))}haveLength(e){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")):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=n;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])&&d(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,t){this._extensions[o.extensionName].decompress(e,this._fin,(e,s)=>{if(e)return t(e);if(s.length){if(this._messageLength+=s.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 t(e)}this._fragments.push(s)}this.dataMessage(t),0===this._state&&this.startLoop(t)})}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?h(s,t):"arraybuffer"===this._binaryType?l(h(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=h(s,t);if(!this._skipUTF8Validation&&!f(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,n),this.end();else{const s=e.readUInt16BE(0);if(!u(s)){const e=this.createError(RangeError,`invalid status code ${s}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");return void t(e)}const r=new _(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!f(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[a]=r,i}}},914(e,t,s){const{Duplex:r}=s(203),{randomFillSync:o}=s(982),i=s(971),{EMPTY_BUFFER:n,kWebSocket:a,NOOP:c}=s(614),{isBlob:h,isValidStatusCode:l}=s(880),{mask:d,toBuffer:u}=s(338),f=Symbol("kByteLength"),_=Buffer.alloc(4),p=8192;let m,y=p;class b{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=c,this[a]=void 0}static frame(e,t){let s,r,i=!1,n=2,a=!1;t.mask&&(s=t.maskBuffer||_,t.generateMask?t.generateMask(s):(y===p&&(void 0===m&&(m=Buffer.alloc(p)),o(m,0,p),y=0),s[0]=m[y++],s[1]=m[y++],s[2]=m[y++],s[3]=m[y++]),a=0===(s[0]|s[1]|s[2]|s[3]),n=6),"string"==typeof e?r=t.mask&&!a||void 0===t[f]?(e=Buffer.from(e)).length:t[f]:(r=e.length,i=t.mask&&t.readOnly&&!a);let c=r;r>=65536?(n+=8,c=127):r>125&&(n+=2,c=126);const h=Buffer.allocUnsafe(i?r+n:n);return h[0]=t.fin?128|t.opcode:t.opcode,t.rsv1&&(h[0]|=64),h[1]=c,126===c?h.writeUInt16BE(r,2):127===c&&(h[2]=h[3]=0,h.writeUIntBE(r,4,6)),t.mask?(h[1]|=128,h[n-4]=s[0],h[n-3]=s[1],h[n-2]=s[2],h[n-1]=s[3],a?[h,e]:i?(d(e,s,h,n,r),[h]):(d(e,s,e,0,r),[h,e])):[h,e]}close(e,t,s,r){let o;if(void 0===e)o=n;else{if("number"!=typeof e||!l(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={[f]: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,r]):this.sendFrame(b.frame(o,i),r)}ping(e,t,s){let r,o;if("string"==typeof e?(r=Buffer.byteLength(e),o=!1):h(e)?(r=e.size,o=!1):(r=(e=u(e)).length,o=u.readOnly),r>125)throw new RangeError("The data size must not be greater than 125 bytes");const i={[f]:r,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:o,rsv1:!1};h(e)?0!==this._state?this.enqueue([this.getBlobData,e,!1,i,s]):this.getBlobData(e,!1,i,s):0!==this._state?this.enqueue([this.dispatch,e,!1,i,s]):this.sendFrame(b.frame(e,i),s)}pong(e,t,s){let r,o;if("string"==typeof e?(r=Buffer.byteLength(e),o=!1):h(e)?(r=e.size,o=!1):(r=(e=u(e)).length,o=u.readOnly),r>125)throw new RangeError("The data size must not be greater than 125 bytes");const i={[f]:r,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:o,rsv1:!1};h(e)?0!==this._state?this.enqueue([this.getBlobData,e,!1,i,s]):this.getBlobData(e,!1,i,s):0!==this._state?this.enqueue([this.dispatch,e,!1,i,s]):this.sendFrame(b.frame(e,i),s)}send(e,t,s){const r=this._extensions[i.extensionName];let o,n,a=t.binary?2:1,c=t.compress;"string"==typeof e?(o=Buffer.byteLength(e),n=!1):h(e)?(o=e.size,n=!1):(o=(e=u(e)).length,n=u.readOnly),this._firstFragment?(this._firstFragment=!1,c&&r&&r.params[r._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(c=o>=r._threshold),this._compress=c):(c=!1,a=0),t.fin&&(this._firstFragment=!0);const l={[f]:o,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:a,readOnly:n,rsv1:c};h(e)?0!==this._state?this.enqueue([this.getBlobData,e,this._compress,l,s]):this.getBlobData(e,this._compress,l,s):0!==this._state?this.enqueue([this.dispatch,e,this._compress,l,s]):this.dispatch(e,this._compress,l,s)}getBlobData(e,t,s,r){this._bufferedBytes+=s[f],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(g,this,e,r)}this._bufferedBytes-=s[f];const o=u(e);t?this.dispatch(o,t,s,r):(this._state=0,this.sendFrame(b.frame(o,s),r),this.dequeue())}).catch(e=>{process.nextTick(v,this,e,r)})}dispatch(e,t,s,r){if(!t)return void this.sendFrame(b.frame(e,s),r);const o=this._extensions[i.extensionName];this._bufferedBytes+=s[f],this._state=1,o.compress(e,s.fin,(e,t)=>{this._socket.destroyed?g(this,new Error("The socket was closed while data was being compressed"),r):(this._bufferedBytes-=s[f],this._state=0,s.readOnly=!1,this.sendFrame(b.frame(t,s),r),this.dequeue())})}dequeue(){for(;0===this._state&&this._queue.length;){const e=this._queue.shift();this._bufferedBytes-=e[3][f],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][f],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 g(e,t,s){"function"==typeof s&&s(t);for(let s=0;s<e._queue.length;s++){const r=e._queue[s],o=r[r.length-1];"function"==typeof o&&o(t)}}function v(e,t,s){g(e,t,s),e.onerror(t)}e.exports=b},719(e,t,s){const{Duplex:r}=s(203);function o(e){e.emit("close")}function i(){!this.destroyed&&this._writableState.finished&&this.destroy()}function n(e){this.removeListener("error",n),this.destroy(),0===this.listenerCount("error")&&this.emit("error",e)}e.exports=function(e,t){let s=!0;const a=new r({...t,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return e.on("message",function(t,s){const r=!s&&a._readableState.objectMode?t.toString():t;a.push(r)||e.pause()}),e.once("error",function(e){a.destroyed||(s=!1,a.destroy(e))}),e.once("close",function(){a.destroyed||a.push(null)}),a._destroy=function(t,r){if(e.readyState===e.CLOSED)return r(t),void process.nextTick(o,a);let i=!1;e.once("error",function(e){i=!0,r(e)}),e.once("close",function(){i||r(t),process.nextTick(o,a)}),s&&e.terminate()},a._final=function(t){e.readyState!==e.CONNECTING?null!==e._socket&&(e._socket._writableState.finished?(t(),a._readableState.endEmitted&&a.destroy()):(e._socket.once("finish",function(){t()}),e.close())):e.once("open",function(){a._final(t)})},a._read=function(){e.isPaused&&e.resume()},a._write=function(t,s,r){e.readyState!==e.CONNECTING?e.send(t,r):e.once("open",function(){a._write(t,s,r)})},a.on("end",i),a.on("error",n),a}},237(e,t,s){const{tokenChars:r}=s(880);e.exports={parse:function(e){const t=new Set;let s=-1,o=-1,i=0;for(;i<e.length;i++){const n=e.charCodeAt(i);if(-1===o&&1===r[n])-1===s&&(s=i);else if(0===i||32!==n&&9!==n){if(44!==n)throw new SyntaxError(`Unexpected character at index ${i}`);{if(-1===s)throw new SyntaxError(`Unexpected character at index ${i}`);-1===o&&(o=i);const r=e.slice(s,o);if(t.has(r))throw new SyntaxError(`The "${r}" subprotocol is duplicated`);t.add(r),s=o=-1}}else-1===o&&-1!==s&&(o=i)}if(-1===s||-1!==o)throw new SyntaxError("Unexpected end of input");const n=e.slice(s,i);if(t.has(n))throw new SyntaxError(`The "${n}" subprotocol is duplicated`);return t.add(n),t}}},880(e,t,s){const{isUtf8:r}=s(181),{hasBlob:o}=s(614);function i(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(e.exports={isBlob:function(e){return o&&"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:i,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]},r)e.exports.isValidUTF8=function(e){return e.length<24?i(e):r(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{const t=s(Object(function(){var e=new Error("Cannot find module 'utf-8-validate'");throw e.code="MODULE_NOT_FOUND",e}()));e.exports.isValidUTF8=function(e){return e.length<32?i(e):t(e)}}catch(e){}},722(e,t,s){const r=s(434),o=s(611),{Duplex:i}=s(203),{createHash:n}=s(982),a=s(926),c=s(971),h=s(237),l=s(60),{GUID:d,kWebSocket:u}=s(614),f=/^[+/0-9A-Za-z]{22}==$/;function _(e){e._state=2,e.emit("close")}function p(){this.destroy()}function m(e,t,s,r){s=s||o.STATUS_CODES[t],r={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(s),...r},e.once("finish",e.destroy),e.end(`HTTP/1.1 ${t} ${o.STATUS_CODES[t]}\r\n`+Object.keys(r).map(e=>`${e}: ${r[e]}`).join("\r\n")+"\r\n\r\n"+s)}function y(e,t,s,r,o){if(e.listenerCount("wsClientError")){const r=new Error(o);Error.captureStackTrace(r,y),e.emit("wsClientError",r,s,t)}else m(s,r,o)}e.exports=class extends r{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:l,...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=o.createServer((e,t)=>{const s=o.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(_,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(_,this);else{const e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close(()=>{_(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",p);const o=e.headers["sec-websocket-key"],i=e.headers.upgrade,n=+e.headers["sec-websocket-version"];if("GET"!==e.method)return void y(this,e,t,405,"Invalid HTTP method");if(void 0===i||"websocket"!==i.toLowerCase())return void y(this,e,t,400,"Invalid Upgrade header");if(void 0===o||!f.test(o))return void y(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header");if(8!==n&&13!==n)return void y(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header");if(!this.shouldHandle(e))return void m(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 y(this,e,t,400,"Invalid Sec-WebSocket-Protocol header")}const u=e.headers["sec-websocket-extensions"],_={};if(this.options.perMessageDeflate&&void 0!==u){const s=new c(this.options.perMessageDeflate,!0,this.options.maxPayload);try{const e=a.parse(u);e[c.extensionName]&&(s.accept(e[c.extensionName]),_[c.extensionName]=s)}catch(s){return void y(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header")}}if(this.options.verifyClient){const i={origin:e.headers[8===n?"sec-websocket-origin":"origin"],secure:!(!e.socket.authorized&&!e.socket.encrypted),req:e};if(2===this.options.verifyClient.length)return void this.options.verifyClient(i,(i,n,a,c)=>{if(!i)return m(t,n||401,a,c);this.completeUpgrade(_,o,d,e,t,s,r)});if(!this.options.verifyClient(i))return m(t,401)}this.completeUpgrade(_,o,d,e,t,s,r)}completeUpgrade(e,t,s,r,o,i,h){if(!o.readable||!o.writable)return o.destroy();if(o[u])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>0)return m(o,503);const l=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${n("sha1").update(t+d).digest("base64")}`],f=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&&(l.push(`Sec-WebSocket-Protocol: ${e}`),f._protocol=e)}if(e[c.extensionName]){const t=e[c.extensionName].params,s=a.format({[c.extensionName]:[t]});l.push(`Sec-WebSocket-Extensions: ${s}`),f._extensions=e}this.emit("headers",l,r),o.write(l.concat("\r\n").join("\r\n")),o.removeListener("error",p),f.setSocket(o,i,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(f),f.on("close",()=>{this.clients.delete(f),this._shouldEmitClose&&!this.clients.size&&process.nextTick(_,this)})),h(f,r)}}},60(e,t,s){const r=s(434),o=s(692),i=s(611),n=s(278),a=s(756),{randomBytes:c,createHash:h}=s(982),{Duplex:l,Readable:d}=s(203),{URL:u}=s(16),f=s(971),_=s(286),p=s(914),{isBlob:m}=s(880),{BINARY_TYPES:y,EMPTY_BUFFER:b,GUID:g,kForOnEventAttribute:v,kListener:S,kStatusCode:w,kWebSocket:E,NOOP:k}=s(614),{EventTarget:{addEventListener:x,removeEventListener:T}}=s(597),{format:O,parse:C}=s(926),{toBuffer:N}=s(338),L=Symbol("kAborted"),R=[8,13],P=["CONNECTING","OPEN","CLOSING","CLOSED"],U=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;class I extends r{constructor(e,t,s){super(),this._binaryType=y[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=b,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=I.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]),B(this,e,t,s)):(this._autoPong=s.autoPong,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){y.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 _({allowSynchronousEvents:s.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation}),o=new p(e,this._extensions,s.generateMask);this._receiver=r,this._sender=o,this._socket=e,r[E]=this,o[E]=this,e[E]=this,r.on("conclude",q),r.on("drain",W),r.on("error",$),r.on("message",V),r.on("ping",J),r.on("pong",z),o.onerror=Q,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",K),e.on("data",X),e.on("end",Z),e.on("error",ee),this._readyState=I.OPEN,this.emit("open")}emitClose(){if(!this._socket)return this._readyState=I.CLOSED,void this.emit("close",this._closeCode,this._closeMessage);this._extensions[f.extensionName]&&this._extensions[f.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=I.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,t){if(this.readyState!==I.CLOSED){if(this.readyState===I.CONNECTING){const e="WebSocket was closed before the connection was established";return void M(this,this._req,e)}this.readyState!==I.CLOSING?(this._readyState=I.CLOSING,this._sender.close(e,t,!this._isServer,e=>{e||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),H(this)):this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end()}}pause(){this.readyState!==I.CONNECTING&&this.readyState!==I.CLOSED&&(this._paused=!0,this._socket.pause())}ping(e,t,s){if(this.readyState===I.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===I.OPEN?(void 0===t&&(t=!this._isServer),this._sender.ping(e||b,t,s)):F(this,e,s)}pong(e,t,s){if(this.readyState===I.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===I.OPEN?(void 0===t&&(t=!this._isServer),this._sender.pong(e||b,t,s)):F(this,e,s)}resume(){this.readyState!==I.CONNECTING&&this.readyState!==I.CLOSED&&(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,t,s){if(this.readyState===I.CONNECTING)throw new Error("WebSock