@tachybase/plugin-online-user 0.23.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/.turbo/turbo-build.log +14 -0
  2. package/README.md +1 -0
  3. package/client.d.ts +2 -0
  4. package/client.js +1 -0
  5. package/dist/client/OnlineUserProvider.d.ts +2 -0
  6. package/dist/client/index.d.ts +7 -0
  7. package/dist/client/index.js +1 -0
  8. package/dist/client/locale.d.ts +9 -0
  9. package/dist/externalVersion.js +10 -0
  10. package/dist/index.d.ts +2 -0
  11. package/dist/index.js +39 -0
  12. package/dist/locale/en-US.json +3 -0
  13. package/dist/locale/zh-CN.json +3 -0
  14. package/dist/node_modules/redis/LICENSE +21 -0
  15. package/dist/node_modules/redis/dist/index.d.ts +302 -0
  16. package/dist/node_modules/redis/dist/index.js +1 -0
  17. package/dist/node_modules/redis/package.json +1 -0
  18. package/dist/node_modules/ws/LICENSE +20 -0
  19. package/dist/node_modules/ws/browser.js +8 -0
  20. package/dist/node_modules/ws/index.js +1 -0
  21. package/dist/node_modules/ws/lib/buffer-util.js +131 -0
  22. package/dist/node_modules/ws/lib/constants.js +18 -0
  23. package/dist/node_modules/ws/lib/event-target.js +292 -0
  24. package/dist/node_modules/ws/lib/extension.js +203 -0
  25. package/dist/node_modules/ws/lib/limiter.js +55 -0
  26. package/dist/node_modules/ws/lib/permessage-deflate.js +514 -0
  27. package/dist/node_modules/ws/lib/receiver.js +706 -0
  28. package/dist/node_modules/ws/lib/sender.js +602 -0
  29. package/dist/node_modules/ws/lib/stream.js +159 -0
  30. package/dist/node_modules/ws/lib/subprotocol.js +62 -0
  31. package/dist/node_modules/ws/lib/validation.js +152 -0
  32. package/dist/node_modules/ws/lib/websocket-server.js +540 -0
  33. package/dist/node_modules/ws/lib/websocket.js +1388 -0
  34. package/dist/node_modules/ws/package.json +1 -0
  35. package/dist/server/index.d.ts +1 -0
  36. package/dist/server/index.js +33 -0
  37. package/dist/server/plugin.d.ts +11 -0
  38. package/dist/server/plugin.js +48 -0
  39. package/dist/server/services/connection-manager.d.ts +9 -0
  40. package/dist/server/services/connection-manager.js +181 -0
  41. package/package.json +25 -0
  42. package/server.d.ts +2 -0
  43. package/server.js +1 -0
@@ -0,0 +1 @@
1
+ {"name":"redis","description":"A modern, high performance Redis client","version":"4.7.0","license":"MIT","main":"./dist/index.js","types":"./dist/index.d.ts","files":["dist/"],"workspaces":["./packages/*"],"scripts":{"test":"npm run test -ws --if-present","build:client":"npm run build -w ./packages/client","build:test-utils":"npm run build -w ./packages/test-utils","build:tests-tools":"npm run build:client && npm run build:test-utils","build:modules":"find ./packages -mindepth 1 -maxdepth 1 -type d ! -name 'client' ! -name 'test-utils' -exec npm run build -w {} \\;","build":"tsc","build-all":"npm run build:client && npm run build:test-utils && npm run build:modules && npm run build","documentation":"npm run documentation -ws --if-present","gh-pages":"gh-pages -d ./documentation -e ./documentation -u 'documentation-bot <documentation@bot>'"},"dependencies":{"@redis/bloom":"1.2.0","@redis/client":"1.6.0","@redis/graph":"1.1.1","@redis/json":"1.0.7","@redis/search":"1.2.0","@redis/time-series":"1.1.0"},"devDependencies":{"@tsconfig/node14":"^14.1.0","gh-pages":"^6.0.0","release-it":"^16.1.5","typescript":"^5.2.2"},"repository":{"type":"git","url":"git://github.com/redis/node-redis.git"},"bugs":{"url":"https://github.com/redis/node-redis/issues"},"homepage":"https://github.com/redis/node-redis","keywords":["redis"],"_lastModified":"2024-12-22T16:07:05.381Z"}
@@ -0,0 +1,20 @@
1
+ Copyright (c) 2011 Einar Otto Stangvik <einaros@gmail.com>
2
+ Copyright (c) 2013 Arnout Kazemier and contributors
3
+ Copyright (c) 2016 Luigi Pinca and contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
6
+ this software and associated documentation files (the "Software"), to deal in
7
+ the Software without restriction, including without limitation the rights to
8
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
9
+ the Software, and to permit persons to whom the Software is furnished to do so,
10
+ subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
17
+ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
18
+ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
19
+ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
20
+ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,8 @@
1
+ 'use strict';
2
+
3
+ module.exports = function () {
4
+ throw new Error(
5
+ 'ws does not work in the browser. Browser clients must use the native ' +
6
+ 'WebSocket object'
7
+ );
8
+ };
@@ -0,0 +1 @@
1
+ (function(){var __webpack_modules__={99:function(e,t,s){"use strict";const r=s(12);r.createWebSocketStream=s(391);r.Server=s(186);r.Receiver=s(198);r.Sender=s(994);r.WebSocket=r;r.WebSocketServer=r.Server;e.exports=r},914:function(e,t,s){"use strict";const{EMPTY_BUFFER:r}=s(190);const n=Buffer[Symbol.species];function concat(e,t){if(e.length===0)return r;if(e.length===1)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}if(i<t){return new n(s.buffer,s.byteOffset,i)}return s}function _mask(e,t,s,r,n){for(let i=0;i<n;i++){s[r+i]=e[i]^t[i&3]}}function _unmask(e,t){for(let s=0;s<e.length;s++){e[s]^=t[s&3]}}function toArrayBuffer(e){if(e.length===e.buffer.byteLength){return e.buffer}return e.buffer.slice(e.byteOffset,e.byteOffset+e.length)}function toBuffer(e){toBuffer.readOnly=true;if(Buffer.isBuffer(e))return e;let t;if(e instanceof ArrayBuffer){t=new n(e)}else if(ArrayBuffer.isView(e)){t=new n(e.buffer,e.byteOffset,e.byteLength)}else{t=Buffer.from(e);toBuffer.readOnly=false}return t}e.exports={concat:concat,mask:_mask,toArrayBuffer:toArrayBuffer,toBuffer:toBuffer,unmask:_unmask};if(!process.env.WS_NO_BUFFER_UTIL){try{const t=s(653);e.exports.mask=function(e,s,r,n,i){if(i<48)_mask(e,s,r,n,i);else t.mask(e,s,r,n,i)};e.exports.unmask=function(e,s){if(e.length<32)_unmask(e,s);else t.unmask(e,s)}}catch(e){}}},190:function(e){"use strict";const t=["nodebuffer","arraybuffer","fragments"];const s=typeof Blob!=="undefined";if(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:()=>{}}},789:function(e,t,s){"use strict";const{kForOnEventAttribute:r,kListener:n}=s(190);const i=Symbol("kCode");const o=Symbol("kData");const a=Symbol("kError");const c=Symbol("kMessage");const l=Symbol("kReason");const f=Symbol("kTarget");const h=Symbol("kType");const u=Symbol("kWasClean");class Event{constructor(e){this[f]=null;this[h]=e}get target(){return this[f]}get type(){return this[h]}}Object.defineProperty(Event.prototype,"target",{enumerable:true});Object.defineProperty(Event.prototype,"type",{enumerable:true});class CloseEvent extends Event{constructor(e,t={}){super(e);this[i]=t.code===undefined?0:t.code;this[l]=t.reason===undefined?"":t.reason;this[u]=t.wasClean===undefined?false:t.wasClean}get code(){return this[i]}get reason(){return this[l]}get wasClean(){return this[u]}}Object.defineProperty(CloseEvent.prototype,"code",{enumerable:true});Object.defineProperty(CloseEvent.prototype,"reason",{enumerable:true});Object.defineProperty(CloseEvent.prototype,"wasClean",{enumerable:true});class ErrorEvent extends Event{constructor(e,t={}){super(e);this[a]=t.error===undefined?null:t.error;this[c]=t.message===undefined?"":t.message}get error(){return this[a]}get message(){return this[c]}}Object.defineProperty(ErrorEvent.prototype,"error",{enumerable:true});Object.defineProperty(ErrorEvent.prototype,"message",{enumerable:true});class MessageEvent extends Event{constructor(e,t={}){super(e);this[o]=t.data===undefined?null:t.data}get data(){return this[o]}}Object.defineProperty(MessageEvent.prototype,"data",{enumerable:true});const d={addEventListener(e,t,s={}){for(const i of this.listeners(e)){if(!s[r]&&i[n]===t&&!i[r]){return}}let i;if(e==="message"){i=function onMessage(e,s){const r=new MessageEvent("message",{data:s?e:e.toString()});r[f]=this;callListener(t,this,r)}}else if(e==="close"){i=function onClose(e,s){const r=new CloseEvent("close",{code:e,reason:s.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});r[f]=this;callListener(t,this,r)}}else if(e==="error"){i=function onError(e){const s=new ErrorEvent("error",{error:e,message:e.message});s[f]=this;callListener(t,this,s)}}else if(e==="open"){i=function onOpen(){const e=new Event("open");e[f]=this;callListener(t,this,e)}}else{return}i[r]=!!s[r];i[n]=t;if(s.once){this.once(e,i)}else{this.on(e,i)}},removeEventListener(e,t){for(const s of this.listeners(e)){if(s[n]===t&&!s[r]){this.removeListener(e,s);break}}}};e.exports={CloseEvent:CloseEvent,ErrorEvent:ErrorEvent,Event:Event,EventTarget:d,MessageEvent:MessageEvent};function callListener(e,t,s){if(typeof e==="object"&&e.handleEvent){e.handleEvent.call(e,s)}else{e.call(t,s)}}},966:function(e,t,s){"use strict";const{tokenChars:r}=s(408);function push(e,t,s){if(e[t]===undefined)e[t]=[s];else e[t].push(s)}function parse(e){const t=Object.create(null);let s=Object.create(null);let n=false;let i=false;let o=false;let a;let c;let l=-1;let f=-1;let h=-1;let u=0;for(;u<e.length;u++){f=e.charCodeAt(u);if(a===undefined){if(h===-1&&r[f]===1){if(l===-1)l=u}else if(u!==0&&(f===32||f===9)){if(h===-1&&l!==-1)h=u}else if(f===59||f===44){if(l===-1){throw new SyntaxError(`Unexpected character at index ${u}`)}if(h===-1)h=u;const r=e.slice(l,h);if(f===44){push(t,r,s);s=Object.create(null)}else{a=r}l=h=-1}else{throw new SyntaxError(`Unexpected character at index ${u}`)}}else if(c===undefined){if(h===-1&&r[f]===1){if(l===-1)l=u}else if(f===32||f===9){if(h===-1&&l!==-1)h=u}else if(f===59||f===44){if(l===-1){throw new SyntaxError(`Unexpected character at index ${u}`)}if(h===-1)h=u;push(s,e.slice(l,h),true);if(f===44){push(t,a,s);s=Object.create(null);a=undefined}l=h=-1}else if(f===61&&l!==-1&&h===-1){c=e.slice(l,u);l=h=-1}else{throw new SyntaxError(`Unexpected character at index ${u}`)}}else{if(i){if(r[f]!==1){throw new SyntaxError(`Unexpected character at index ${u}`)}if(l===-1)l=u;else if(!n)n=true;i=false}else if(o){if(r[f]===1){if(l===-1)l=u}else if(f===34&&l!==-1){o=false;h=u}else if(f===92){i=true}else{throw new SyntaxError(`Unexpected character at index ${u}`)}}else if(f===34&&e.charCodeAt(u-1)===61){o=true}else if(h===-1&&r[f]===1){if(l===-1)l=u}else if(l!==-1&&(f===32||f===9)){if(h===-1)h=u}else if(f===59||f===44){if(l===-1){throw new SyntaxError(`Unexpected character at index ${u}`)}if(h===-1)h=u;let r=e.slice(l,h);if(n){r=r.replace(/\\/g,"");n=false}push(s,c,r);if(f===44){push(t,a,s);s=Object.create(null);a=undefined}c=undefined;l=h=-1}else{throw new SyntaxError(`Unexpected character at index ${u}`)}}}if(l===-1||o||f===32||f===9){throw new SyntaxError("Unexpected end of input")}if(h===-1)h=u;const d=e.slice(l,h);if(a===undefined){push(t,d,s)}else{if(c===undefined){push(s,d,true)}else if(n){push(s,c,d.replace(/\\/g,""))}else{push(s,c,d)}push(t,a,s)}return t}function format(e){return Object.keys(e).map((t=>{let s=e[t];if(!Array.isArray(s))s=[s];return s.map((e=>[t].concat(Object.keys(e).map((t=>{let s=e[t];if(!Array.isArray(s))s=[s];return s.map((e=>e===true?t:`${t}=${e}`)).join("; ")}))).join("; "))).join(", ")})).join(", ")}e.exports={format:format,parse:parse}},207:function(e){"use strict";const t=Symbol("kDone");const s=Symbol("kRun");class Limiter{constructor(e){this[t]=()=>{this.pending--;this[s]()};this.concurrency=e||Infinity;this.jobs=[];this.pending=0}add(e){this.jobs.push(e);this[s]()}[s](){if(this.pending===this.concurrency)return;if(this.jobs.length){const e=this.jobs.shift();this.pending++;e(this[t])}}}e.exports=Limiter},843:function(e,t,s){"use strict";const r=s(106);const n=s(914);const i=s(207);const{kStatusCode:o}=s(190);const a=Buffer[Symbol.species];const c=Buffer.from([0,0,255,255]);const l=Symbol("permessage-deflate");const f=Symbol("total-length");const h=Symbol("callback");const u=Symbol("buffers");const d=Symbol("error");let _;class PerMessageDeflate{constructor(e,t,s){this._maxPayload=s|0;this._options=e||{};this._threshold=this._options.threshold!==undefined?this._options.threshold:1024;this._isServer=!!t;this._deflate=null;this._inflate=null;this.params=null;if(!_){const e=this._options.concurrencyLimit!==undefined?this._options.concurrencyLimit:10;_=new i(e)}}static get extensionName(){return"permessage-deflate"}offer(){const e={};if(this._options.serverNoContextTakeover){e.server_no_context_takeover=true}if(this._options.clientNoContextTakeover){e.client_no_context_takeover=true}if(this._options.serverMaxWindowBits){e.server_max_window_bits=this._options.serverMaxWindowBits}if(this._options.clientMaxWindowBits){e.client_max_window_bits=this._options.clientMaxWindowBits}else if(this._options.clientMaxWindowBits==null){e.client_max_window_bits=true}return e}accept(e){e=this.normalizeParams(e);this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e);return this.params}cleanup(){if(this._inflate){this._inflate.close();this._inflate=null}if(this._deflate){const e=this._deflate[h];this._deflate.close();this._deflate=null;if(e){e(new Error("The deflate stream was closed while data was being processed"))}}}acceptAsServer(e){const t=this._options;const s=e.find((e=>{if(t.serverNoContextTakeover===false&&e.server_no_context_takeover||e.server_max_window_bits&&(t.serverMaxWindowBits===false||typeof t.serverMaxWindowBits==="number"&&t.serverMaxWindowBits>e.server_max_window_bits)||typeof t.clientMaxWindowBits==="number"&&!e.client_max_window_bits){return false}return true}));if(!s){throw new Error("None of the extension offers can be accepted")}if(t.serverNoContextTakeover){s.server_no_context_takeover=true}if(t.clientNoContextTakeover){s.client_no_context_takeover=true}if(typeof t.serverMaxWindowBits==="number"){s.server_max_window_bits=t.serverMaxWindowBits}if(typeof t.clientMaxWindowBits==="number"){s.client_max_window_bits=t.clientMaxWindowBits}else if(s.client_max_window_bits===true||t.clientMaxWindowBits===false){delete s.client_max_window_bits}return s}acceptAsClient(e){const t=e[0];if(this._options.clientNoContextTakeover===false&&t.client_no_context_takeover){throw new Error('Unexpected parameter "client_no_context_takeover"')}if(!t.client_max_window_bits){if(typeof this._options.clientMaxWindowBits==="number"){t.client_max_window_bits=this._options.clientMaxWindowBits}}else if(this._options.clientMaxWindowBits===false||typeof this._options.clientMaxWindowBits==="number"&&t.client_max_window_bits>this._options.clientMaxWindowBits){throw new Error('Unexpected or invalid parameter "client_max_window_bits"')}return t}normalizeParams(e){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`)}s=s[0];if(t==="client_max_window_bits"){if(s!==true){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(t==="server_max_window_bits"){const e=+s;if(!Number.isInteger(e)||e<8||e>15){throw new TypeError(`Invalid value for parameter "${t}": ${s}`)}s=e}else if(t==="client_no_context_takeover"||t==="server_no_context_takeover"){if(s!==true){throw new TypeError(`Invalid value for parameter "${t}": ${s}`)}}else{throw new Error(`Unknown parameter "${t}"`)}e[t]=s}))}));return 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`;const t=typeof this.params[e]!=="number"?r.Z_DEFAULT_WINDOWBITS:this.params[e];this._inflate=r.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t});this._inflate[l]=this;this._inflate[f]=0;this._inflate[u]=[];this._inflate.on("error",inflateOnError);this._inflate.on("data",inflateOnData)}this._inflate[h]=s;this._inflate.write(e);if(t)this._inflate.write(c);this._inflate.flush((()=>{const e=this._inflate[d];if(e){this._inflate.close();this._inflate=null;s(e);return}const r=n.concat(this._inflate[u],this._inflate[f]);if(this._inflate._readableState.endEmitted){this._inflate.close();this._inflate=null}else{this._inflate[f]=0;this._inflate[u]=[];if(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`;const t=typeof this.params[e]!=="number"?r.Z_DEFAULT_WINDOWBITS:this.params[e];this._deflate=r.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t});this._deflate[f]=0;this._deflate[u]=[];this._deflate.on("data",deflateOnData)}this._deflate[h]=s;this._deflate.write(e);this._deflate.flush(r.Z_SYNC_FLUSH,(()=>{if(!this._deflate){return}let e=n.concat(this._deflate[u],this._deflate[f]);if(t){e=new a(e.buffer,e.byteOffset,e.length-4)}this._deflate[h]=null;this._deflate[f]=0;this._deflate[u]=[];if(t&&this.params[`${i}_no_context_takeover`]){this._deflate.reset()}s(null,e)}))}}e.exports=PerMessageDeflate;function deflateOnData(e){this[u].push(e);this[f]+=e.length}function inflateOnData(e){this[f]+=e.length;if(this[l]._maxPayload<1||this[f]<=this[l]._maxPayload){this[u].push(e);return}this[d]=new RangeError("Max payload size exceeded");this[d].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH";this[d][o]=1009;this.removeListener("data",inflateOnData);this.reset()}function inflateOnError(e){this[l]._inflate=null;e[o]=1007;this[h](e)}},198:function(e,t,s){"use strict";const{Writable:r}=s(203);const n=s(843);const{BINARY_TYPES:i,EMPTY_BUFFER:o,kStatusCode:a,kWebSocket:c}=s(190);const{concat:l,toArrayBuffer:f,unmask:h}=s(914);const{isValidStatusCode:u,isValidUTF8:d}=s(408);const _=Buffer[Symbol.species];const p=0;const m=1;const b=2;const S=3;const y=4;const k=5;const g=6;class Receiver extends r{constructor(e={}){super();this._allowSynchronousEvents=e.allowSynchronousEvents!==undefined?e.allowSynchronousEvents:true;this._binaryType=e.binaryType||i[0];this._extensions=e.extensions||{};this._isServer=!!e.isServer;this._maxPayload=e.maxPayload|0;this._skipUTF8Validation=!!e.skipUTF8Validation;this[c]=undefined;this._bufferedBytes=0;this._buffers=[];this._compressed=false;this._payloadLength=0;this._mask=undefined;this._fragmented=0;this._masked=false;this._fin=false;this._opcode=0;this._totalPayloadLength=0;this._messageLength=0;this._fragments=[];this._errored=false;this._loop=false;this._state=p}_write(e,t,s){if(this._opcode===8&&this._state==p)return s();this._bufferedBytes+=e.length;this._buffers.push(e);this.startLoop(s)}consume(e){this._bufferedBytes-=e;if(e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){const t=this._buffers[0];this._buffers[0]=new _(t.buffer,t.byteOffset+e,t.length-e);return new _(t.buffer,t.byteOffset,e)}const t=Buffer.allocUnsafe(e);do{const s=this._buffers[0];const r=t.length-e;if(e>=s.length){t.set(this._buffers.shift(),r)}else{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=true;do{switch(this._state){case p:this.getInfo(e);break;case m:this.getPayloadLength16(e);break;case b:this.getPayloadLength64(e);break;case S:this.getMask();break;case y:this.getData(e);break;case k:case g:this._loop=false;return}}while(this._loop);if(!this._errored)e()}getInfo(e){if(this._bufferedBytes<2){this._loop=false;return}const t=this.consume(2);if((t[0]&48)!==0){const t=this.createError(RangeError,"RSV2 and RSV3 must be clear",true,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(t);return}const s=(t[0]&64)===64;if(s&&!this._extensions[n.extensionName]){const t=this.createError(RangeError,"RSV1 must be clear",true,1002,"WS_ERR_UNEXPECTED_RSV_1");e(t);return}this._fin=(t[0]&128)===128;this._opcode=t[0]&15;this._payloadLength=t[1]&127;if(this._opcode===0){if(s){const t=this.createError(RangeError,"RSV1 must be clear",true,1002,"WS_ERR_UNEXPECTED_RSV_1");e(t);return}if(!this._fragmented){const t=this.createError(RangeError,"invalid opcode 0",true,1002,"WS_ERR_INVALID_OPCODE");e(t);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){const t=this.createError(RangeError,`invalid opcode ${this._opcode}`,true,1002,"WS_ERR_INVALID_OPCODE");e(t);return}this._compressed=s}else if(this._opcode>7&&this._opcode<11){if(!this._fin){const t=this.createError(RangeError,"FIN must be set",true,1002,"WS_ERR_EXPECTED_FIN");e(t);return}if(s){const t=this.createError(RangeError,"RSV1 must be clear",true,1002,"WS_ERR_UNEXPECTED_RSV_1");e(t);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){const t=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,true,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(t);return}}else{const t=this.createError(RangeError,`invalid opcode ${this._opcode}`,true,1002,"WS_ERR_INVALID_OPCODE");e(t);return}if(!this._fin&&!this._fragmented)this._fragmented=this._opcode;this._masked=(t[1]&128)===128;if(this._isServer){if(!this._masked){const t=this.createError(RangeError,"MASK must be set",true,1002,"WS_ERR_EXPECTED_MASK");e(t);return}}else if(this._masked){const t=this.createError(RangeError,"MASK must be clear",true,1002,"WS_ERR_UNEXPECTED_MASK");e(t);return}if(this._payloadLength===126)this._state=m;else if(this._payloadLength===127)this._state=b;else this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=false;return}this._payloadLength=this.consume(2).readUInt16BE(0);this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=false;return}const t=this.consume(8);const s=t.readUInt32BE(0);if(s>Math.pow(2,53-32)-1){const t=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",false,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(t);return}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;if(this._totalPayloadLength>this._maxPayload&&this._maxPayload>0){const t=this.createError(RangeError,"Max payload size exceeded",false,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(t);return}}if(this._masked)this._state=S;else this._state=y}getMask(){if(this._bufferedBytes<4){this._loop=false;return}this._mask=this.consume(4);this._state=y}getData(e){let t=o;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=false;return}t=this.consume(this._payloadLength);if(this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0){h(t,this._mask)}}if(this._opcode>7){this.controlMessage(t,e);return}if(this._compressed){this._state=k;this.decompress(t,e);return}if(t.length){this._messageLength=this._totalPayloadLength;this._fragments.push(t)}this.dataMessage(e)}decompress(e,t){const s=this._extensions[n.extensionName];s.decompress(e,this._fin,((e,s)=>{if(e)return t(e);if(s.length){this._messageLength+=s.length;if(this._messageLength>this._maxPayload&&this._maxPayload>0){const e=this.createError(RangeError,"Max payload size exceeded",false,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");t(e);return}this._fragments.push(s)}this.dataMessage(t);if(this._state===p)this.startLoop(t)}))}dataMessage(e){if(!this._fin){this._state=p;return}const t=this._messageLength;const s=this._fragments;this._totalPayloadLength=0;this._messageLength=0;this._fragmented=0;this._fragments=[];if(this._opcode===2){let r;if(this._binaryType==="nodebuffer"){r=l(s,t)}else if(this._binaryType==="arraybuffer"){r=f(l(s,t))}else if(this._binaryType==="blob"){r=new Blob(s)}else{r=s}if(this._allowSynchronousEvents){this.emit("message",r,true);this._state=p}else{this._state=g;setImmediate((()=>{this.emit("message",r,true);this._state=p;this.startLoop(e)}))}}else{const r=l(s,t);if(!this._skipUTF8Validation&&!d(r)){const t=this.createError(Error,"invalid UTF-8 sequence",true,1007,"WS_ERR_INVALID_UTF8");e(t);return}if(this._state===k||this._allowSynchronousEvents){this.emit("message",r,false);this._state=p}else{this._state=g;setImmediate((()=>{this.emit("message",r,false);this._state=p;this.startLoop(e)}))}}}controlMessage(e,t){if(this._opcode===8){if(e.length===0){this._loop=false;this.emit("conclude",1005,o);this.end()}else{const s=e.readUInt16BE(0);if(!u(s)){const e=this.createError(RangeError,`invalid status code ${s}`,true,1002,"WS_ERR_INVALID_CLOSE_CODE");t(e);return}const r=new _(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!d(r)){const e=this.createError(Error,"invalid UTF-8 sequence",true,1007,"WS_ERR_INVALID_UTF8");t(e);return}this._loop=false;this.emit("conclude",s,r);this.end()}this._state=p;return}if(this._allowSynchronousEvents){this.emit(this._opcode===9?"ping":"pong",e);this._state=p}else{this._state=g;setImmediate((()=>{this.emit(this._opcode===9?"ping":"pong",e);this._state=p;this.startLoop(t)}))}}createError(e,t,s,r,n){this._loop=false;this._errored=true;const i=new e(s?`Invalid WebSocket frame: ${t}`:t);Error.captureStackTrace(i,this.createError);i.code=n;i[a]=r;return i}}e.exports=Receiver},994:function(e,t,s){"use strict";const{Duplex:r}=s(203);const{randomFillSync:n}=s(982);const i=s(843);const{EMPTY_BUFFER:o,kWebSocket:a,NOOP:c}=s(190);const{isBlob:l,isValidStatusCode:f}=s(408);const{mask:h,toBuffer:u}=s(914);const d=Symbol("kByteLength");const _=Buffer.alloc(4);const p=8*1024;let m;let b=p;const S=0;const y=1;const k=2;class Sender{constructor(e,t,s){this._extensions=t||{};if(s){this._generateMask=s;this._maskBuffer=Buffer.alloc(4)}this._socket=e;this._firstFragment=true;this._compress=false;this._bufferedBytes=0;this._queue=[];this._state=S;this.onerror=c;this[a]=undefined}static frame(e,t){let s;let r=false;let i=2;let o=false;if(t.mask){s=t.maskBuffer||_;if(t.generateMask){t.generateMask(s)}else{if(b===p){if(m===undefined){m=Buffer.alloc(p)}n(m,0,p);b=0}s[0]=m[b++];s[1]=m[b++];s[2]=m[b++];s[3]=m[b++]}o=(s[0]|s[1]|s[2]|s[3])===0;i=6}let a;if(typeof e==="string"){if((!t.mask||o)&&t[d]!==undefined){a=t[d]}else{e=Buffer.from(e);a=e.length}}else{a=e.length;r=t.mask&&t.readOnly&&!o}let c=a;if(a>=65536){i+=8;c=127}else if(a>125){i+=2;c=126}const l=Buffer.allocUnsafe(r?a+i:i);l[0]=t.fin?t.opcode|128:t.opcode;if(t.rsv1)l[0]|=64;l[1]=c;if(c===126){l.writeUInt16BE(a,2)}else if(c===127){l[2]=l[3]=0;l.writeUIntBE(a,4,6)}if(!t.mask)return[l,e];l[1]|=128;l[i-4]=s[0];l[i-3]=s[1];l[i-2]=s[2];l[i-1]=s[3];if(o)return[l,e];if(r){h(e,s,l,i,a);return[l]}h(e,s,e,0,a);return[l,e]}close(e,t,s,r){let n;if(e===undefined){n=o}else if(typeof e!=="number"||!f(e)){throw new TypeError("First argument must be a valid error code number")}else if(t===undefined||!t.length){n=Buffer.allocUnsafe(2);n.writeUInt16BE(e,0)}else{const s=Buffer.byteLength(t);if(s>123){throw new RangeError("The message must not be greater than 123 bytes")}n=Buffer.allocUnsafe(2+s);n.writeUInt16BE(e,0);if(typeof t==="string"){n.write(t,2)}else{n.set(t,2)}}const i={[d]:n.length,fin:true,generateMask:this._generateMask,mask:s,maskBuffer:this._maskBuffer,opcode:8,readOnly:false,rsv1:false};if(this._state!==S){this.enqueue([this.dispatch,n,false,i,r])}else{this.sendFrame(Sender.frame(n,i),r)}}ping(e,t,s){let r;let n;if(typeof e==="string"){r=Buffer.byteLength(e);n=false}else if(l(e)){r=e.size;n=false}else{e=u(e);r=e.length;n=u.readOnly}if(r>125){throw new RangeError("The data size must not be greater than 125 bytes")}const i={[d]:r,fin:true,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:n,rsv1:false};if(l(e)){if(this._state!==S){this.enqueue([this.getBlobData,e,false,i,s])}else{this.getBlobData(e,false,i,s)}}else if(this._state!==S){this.enqueue([this.dispatch,e,false,i,s])}else{this.sendFrame(Sender.frame(e,i),s)}}pong(e,t,s){let r;let n;if(typeof e==="string"){r=Buffer.byteLength(e);n=false}else if(l(e)){r=e.size;n=false}else{e=u(e);r=e.length;n=u.readOnly}if(r>125){throw new RangeError("The data size must not be greater than 125 bytes")}const i={[d]:r,fin:true,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:n,rsv1:false};if(l(e)){if(this._state!==S){this.enqueue([this.getBlobData,e,false,i,s])}else{this.getBlobData(e,false,i,s)}}else if(this._state!==S){this.enqueue([this.dispatch,e,false,i,s])}else{this.sendFrame(Sender.frame(e,i),s)}}send(e,t,s){const r=this._extensions[i.extensionName];let n=t.binary?2:1;let o=t.compress;let a;let c;if(typeof e==="string"){a=Buffer.byteLength(e);c=false}else if(l(e)){a=e.size;c=false}else{e=u(e);a=e.length;c=u.readOnly}if(this._firstFragment){this._firstFragment=false;if(o&&r&&r.params[r._isServer?"server_no_context_takeover":"client_no_context_takeover"]){o=a>=r._threshold}this._compress=o}else{o=false;n=0}if(t.fin)this._firstFragment=true;const f={[d]:a,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:n,readOnly:c,rsv1:o};if(l(e)){if(this._state!==S){this.enqueue([this.getBlobData,e,this._compress,f,s])}else{this.getBlobData(e,this._compress,f,s)}}else if(this._state!==S){this.enqueue([this.dispatch,e,this._compress,f,s])}else{this.dispatch(e,this._compress,f,s)}}getBlobData(e,t,s,r){this._bufferedBytes+=s[d];this._state=k;e.arrayBuffer().then((e=>{if(this._socket.destroyed){const e=new Error("The socket was closed while the blob was being read");process.nextTick(callCallbacks,this,e,r);return}this._bufferedBytes-=s[d];const n=u(e);if(!t){this._state=S;this.sendFrame(Sender.frame(n,s),r);this.dequeue()}else{this.dispatch(n,t,s,r)}})).catch((e=>{process.nextTick(onError,this,e,r)}))}dispatch(e,t,s,r){if(!t){this.sendFrame(Sender.frame(e,s),r);return}const n=this._extensions[i.extensionName];this._bufferedBytes+=s[d];this._state=y;n.compress(e,s.fin,((e,t)=>{if(this._socket.destroyed){const e=new Error("The socket was closed while data was being compressed");callCallbacks(this,e,r);return}this._bufferedBytes-=s[d];this._state=S;s.readOnly=false;this.sendFrame(Sender.frame(t,s),r);this.dequeue()}))}dequeue(){while(this._state===S&&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){if(e.length===2){this._socket.cork();this._socket.write(e[0]);this._socket.write(e[1],t);this._socket.uncork()}else{this._socket.write(e[0],t)}}}e.exports=Sender;function callCallbacks(e,t,s){if(typeof s==="function")s(t);for(let s=0;s<e._queue.length;s++){const r=e._queue[s];const n=r[r.length-1];if(typeof n==="function")n(t)}}function onError(e,t,s){callCallbacks(e,t,s);e.onerror(t)}},391:function(e,t,s){"use strict";const{Duplex:r}=s(203);function emitClose(e){e.emit("close")}function duplexOnEnd(){if(!this.destroyed&&this._writableState.finished){this.destroy()}}function duplexOnError(e){this.removeListener("error",duplexOnError);this.destroy();if(this.listenerCount("error")===0){this.emit("error",e)}}function createWebSocketStream(e,t){let s=true;const n=new r({...t,autoDestroy:false,emitClose:false,objectMode:false,writableObjectMode:false});e.on("message",(function message(t,s){const r=!s&&n._readableState.objectMode?t.toString():t;if(!n.push(r))e.pause()}));e.once("error",(function error(e){if(n.destroyed)return;s=false;n.destroy(e)}));e.once("close",(function close(){if(n.destroyed)return;n.push(null)}));n._destroy=function(t,r){if(e.readyState===e.CLOSED){r(t);process.nextTick(emitClose,n);return}let i=false;e.once("error",(function error(e){i=true;r(e)}));e.once("close",(function close(){if(!i)r(t);process.nextTick(emitClose,n)}));if(s)e.terminate()};n._final=function(t){if(e.readyState===e.CONNECTING){e.once("open",(function open(){n._final(t)}));return}if(e._socket===null)return;if(e._socket._writableState.finished){t();if(n._readableState.endEmitted)n.destroy()}else{e._socket.once("finish",(function finish(){t()}));e.close()}};n._read=function(){if(e.isPaused)e.resume()};n._write=function(t,s,r){if(e.readyState===e.CONNECTING){e.once("open",(function open(){n._write(t,s,r)}));return}e.send(t,r)};n.on("end",duplexOnEnd);n.on("error",duplexOnError);return n}e.exports=createWebSocketStream},189:function(e,t,s){"use strict";const{tokenChars:r}=s(408);function parse(e){const t=new Set;let s=-1;let n=-1;let i=0;for(i;i<e.length;i++){const o=e.charCodeAt(i);if(n===-1&&r[o]===1){if(s===-1)s=i}else if(i!==0&&(o===32||o===9)){if(n===-1&&s!==-1)n=i}else if(o===44){if(s===-1){throw new SyntaxError(`Unexpected character at index ${i}`)}if(n===-1)n=i;const r=e.slice(s,n);if(t.has(r)){throw new SyntaxError(`The "${r}" subprotocol is duplicated`)}t.add(r);s=n=-1}else{throw new SyntaxError(`Unexpected character at index ${i}`)}}if(s===-1||n!==-1){throw new SyntaxError("Unexpected end of input")}const o=e.slice(s,i);if(t.has(o)){throw new SyntaxError(`The "${o}" subprotocol is duplicated`)}t.add(o);return t}e.exports={parse:parse}},408:function(e,t,s){"use strict";const{isUtf8:r}=s(181);const{hasBlob:n}=s(190);const i=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function isValidStatusCode(e){return e>=1e3&&e<=1014&&e!==1004&&e!==1005&&e!==1006||e>=3e3&&e<=4999}function _isValidUTF8(e){const t=e.length;let s=0;while(s<t){if((e[s]&128)===0){s++}else if((e[s]&224)===192){if(s+1===t||(e[s+1]&192)!==128||(e[s]&254)===192){return false}s+=2}else if((e[s]&240)===224){if(s+2>=t||(e[s+1]&192)!==128||(e[s+2]&192)!==128||e[s]===224&&(e[s+1]&224)===128||e[s]===237&&(e[s+1]&224)===160){return false}s+=3}else if((e[s]&248)===240){if(s+3>=t||(e[s+1]&192)!==128||(e[s+2]&192)!==128||(e[s+3]&192)!==128||e[s]===240&&(e[s+1]&240)===128||e[s]===244&&e[s+1]>143||e[s]>244){return false}s+=4}else{return false}}return true}function isBlob(e){return n&&typeof e==="object"&&typeof e.arrayBuffer==="function"&&typeof e.type==="string"&&typeof e.stream==="function"&&(e[Symbol.toStringTag]==="Blob"||e[Symbol.toStringTag]==="File")}e.exports={isBlob:isBlob,isValidStatusCode:isValidStatusCode,isValidUTF8:_isValidUTF8,tokenChars:i};if(r){e.exports.isValidUTF8=function(e){return e.length<24?_isValidUTF8(e):r(e)}}else if(!process.env.WS_NO_UTF_8_VALIDATE){try{const t=s(4);e.exports.isValidUTF8=function(e){return e.length<32?_isValidUTF8(e):t(e)}}catch(e){}}},186:function(e,t,s){"use strict";const r=s(434);const n=s(611);const{Duplex:i}=s(203);const{createHash:o}=s(982);const a=s(966);const c=s(843);const l=s(189);const f=s(12);const{GUID:h,kWebSocket:u}=s(190);const d=/^[+/0-9A-Za-z]{22}==$/;const _=0;const p=1;const m=2;class WebSocketServer extends r{constructor(e,t){super();e={allowSynchronousEvents:true,autoPong:true,maxPayload:100*1024*1024,skipUTF8Validation:false,perMessageDeflate:false,handleProtocols:null,clientTracking:true,verifyClient:null,noServer:false,backlog:null,server:null,host:null,path:null,port:null,WebSocket:f,...e};if(e.port==null&&!e.server&&!e.noServer||e.port!=null&&(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(e.port!=null){this._server=n.createServer(((e,t)=>{const s=n.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)}else if(e.server){this._server=e.server}if(this._server){const e=this.emit.bind(this,"connection");this._removeListeners=addListeners(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(t,s,r)=>{this.handleUpgrade(t,s,r,e)}})}if(e.perMessageDeflate===true)e.perMessageDeflate={};if(e.clientTracking){this.clients=new Set;this._shouldEmitClose=false}this.options=e;this._state=_}address(){if(this.options.noServer){throw new Error('The server is operating in "noServer" mode')}if(!this._server)return null;return this._server.address()}close(e){if(this._state===m){if(e){this.once("close",(()=>{e(new Error("The server is not running"))}))}process.nextTick(emitClose,this);return}if(e)this.once("close",e);if(this._state===p)return;this._state=p;if(this.options.noServer||this.options.server){if(this._server){this._removeListeners();this._removeListeners=this._server=null}if(this.clients){if(!this.clients.size){process.nextTick(emitClose,this)}else{this._shouldEmitClose=true}}else{process.nextTick(emitClose,this)}}else{const e=this._server;this._removeListeners();this._removeListeners=this._server=null;e.close((()=>{emitClose(this)}))}}shouldHandle(e){if(this.options.path){const t=e.url.indexOf("?");const s=t!==-1?e.url.slice(0,t):e.url;if(s!==this.options.path)return false}return true}handleUpgrade(e,t,s,r){t.on("error",socketOnError);const n=e.headers["sec-websocket-key"];const i=e.headers.upgrade;const o=+e.headers["sec-websocket-version"];if(e.method!=="GET"){const s="Invalid HTTP method";abortHandshakeOrEmitwsClientError(this,e,t,405,s);return}if(i===undefined||i.toLowerCase()!=="websocket"){const s="Invalid Upgrade header";abortHandshakeOrEmitwsClientError(this,e,t,400,s);return}if(n===undefined||!d.test(n)){const s="Missing or invalid Sec-WebSocket-Key header";abortHandshakeOrEmitwsClientError(this,e,t,400,s);return}if(o!==8&&o!==13){const s="Missing or invalid Sec-WebSocket-Version header";abortHandshakeOrEmitwsClientError(this,e,t,400,s);return}if(!this.shouldHandle(e)){abortHandshake(t,400);return}const f=e.headers["sec-websocket-protocol"];let h=new Set;if(f!==undefined){try{h=l.parse(f)}catch(s){const r="Invalid Sec-WebSocket-Protocol header";abortHandshakeOrEmitwsClientError(this,e,t,400,r);return}}const u=e.headers["sec-websocket-extensions"];const _={};if(this.options.perMessageDeflate&&u!==undefined){const s=new c(this.options.perMessageDeflate,true,this.options.maxPayload);try{const e=a.parse(u);if(e[c.extensionName]){s.accept(e[c.extensionName]);_[c.extensionName]=s}}catch(s){const r="Invalid or unacceptable Sec-WebSocket-Extensions header";abortHandshakeOrEmitwsClientError(this,e,t,400,r);return}}if(this.options.verifyClient){const i={origin:e.headers[`${o===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(i,((i,o,a,c)=>{if(!i){return abortHandshake(t,o||401,a,c)}this.completeUpgrade(_,n,h,e,t,s,r)}));return}if(!this.options.verifyClient(i))return abortHandshake(t,401)}this.completeUpgrade(_,n,h,e,t,s,r)}completeUpgrade(e,t,s,r,n,i,l){if(!n.readable||!n.writable)return n.destroy();if(n[u]){throw new Error("server.handleUpgrade() was called more than once with the same "+"socket, possibly due to a misconfiguration")}if(this._state>_)return abortHandshake(n,503);const f=o("sha1").update(t+h).digest("base64");const d=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${f}`];const p=new this.options.WebSocket(null,undefined,this.options);if(s.size){const e=this.options.handleProtocols?this.options.handleProtocols(s,r):s.values().next().value;if(e){d.push(`Sec-WebSocket-Protocol: ${e}`);p._protocol=e}}if(e[c.extensionName]){const t=e[c.extensionName].params;const s=a.format({[c.extensionName]:[t]});d.push(`Sec-WebSocket-Extensions: ${s}`);p._extensions=e}this.emit("headers",d,r);n.write(d.concat("\r\n").join("\r\n"));n.removeListener("error",socketOnError);p.setSocket(n,i,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation});if(this.clients){this.clients.add(p);p.on("close",(()=>{this.clients.delete(p);if(this._shouldEmitClose&&!this.clients.size){process.nextTick(emitClose,this)}}))}l(p,r)}}e.exports=WebSocketServer;function addListeners(e,t){for(const s of Object.keys(t))e.on(s,t[s]);return function removeListeners(){for(const s of Object.keys(t)){e.removeListener(s,t[s])}}}function emitClose(e){e._state=m;e.emit("close")}function socketOnError(){this.destroy()}function abortHandshake(e,t,s,r){s=s||n.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} ${n.STATUS_CODES[t]}\r\n`+Object.keys(r).map((e=>`${e}: ${r[e]}`)).join("\r\n")+"\r\n\r\n"+s)}function abortHandshakeOrEmitwsClientError(e,t,s,r,n){if(e.listenerCount("wsClientError")){const r=new Error(n);Error.captureStackTrace(r,abortHandshakeOrEmitwsClientError);e.emit("wsClientError",r,s,t)}else{abortHandshake(s,r,n)}}},12:function(e,t,s){"use strict";const r=s(434);const n=s(692);const i=s(611);const o=s(278);const a=s(756);const{randomBytes:c,createHash:l}=s(982);const{Duplex:f,Readable:h}=s(203);const{URL:u}=s(16);const d=s(843);const _=s(198);const p=s(994);const{isBlob:m}=s(408);const{BINARY_TYPES:b,EMPTY_BUFFER:S,GUID:y,kForOnEventAttribute:k,kListener:g,kStatusCode:E,kWebSocket:w,NOOP:v}=s(190);const{EventTarget:{addEventListener:x,removeEventListener:O}}=s(789);const{format:C,parse:T}=s(966);const{toBuffer:L}=s(914);const N=30*1e3;const P=Symbol("kAborted");const W=[8,13];const B=["CONNECTING","OPEN","CLOSING","CLOSED"];const R=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;class WebSocket extends r{constructor(e,t,s){super();this._binaryType=b[0];this._closeCode=1006;this._closeFrameReceived=false;this._closeFrameSent=false;this._closeMessage=S;this._closeTimer=null;this._errorEmitted=false;this._extensions={};this._paused=false;this._protocol="";this._readyState=WebSocket.CONNECTING;this._receiver=null;this._sender=null;this._socket=null;if(e!==null){this._bufferedAmount=0;this._isServer=false;this._redirects=0;if(t===undefined){t=[]}else if(!Array.isArray(t)){if(typeof t==="object"&&t!==null){s=t;t=[]}else{t=[t]}}initAsClient(this,e,t,s)}else{this._autoPong=s.autoPong;this._isServer=true}}get binaryType(){return this._binaryType}set binaryType(e){if(!b.includes(e))return;this._binaryType=e;if(this._receiver)this._receiver._binaryType=e}get bufferedAmount(){if(!this._socket)return this._bufferedAmount;return this._socket._writableState.length+this._sender._bufferedBytes}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});const n=new p(e,this._extensions,s.generateMask);this._receiver=r;this._sender=n;this._socket=e;r[w]=this;n[w]=this;e[w]=this;r.on("conclude",receiverOnConclude);r.on("drain",receiverOnDrain);r.on("error",receiverOnError);r.on("message",receiverOnMessage);r.on("ping",receiverOnPing);r.on("pong",receiverOnPong);n.onerror=senderOnError;if(e.setTimeout)e.setTimeout(0);if(e.setNoDelay)e.setNoDelay();if(t.length>0)e.unshift(t);e.on("close",socketOnClose);e.on("data",socketOnData);e.on("end",socketOnEnd);e.on("error",socketOnError);this._readyState=WebSocket.OPEN;this.emit("open")}emitClose(){if(!this._socket){this._readyState=WebSocket.CLOSED;this.emit("close",this._closeCode,this._closeMessage);return}if(this._extensions[d.extensionName]){this._extensions[d.extensionName].cleanup()}this._receiver.removeAllListeners();this._readyState=WebSocket.CLOSED;this.emit("close",this._closeCode,this._closeMessage)}close(e,t){if(this.readyState===WebSocket.CLOSED)return;if(this.readyState===WebSocket.CONNECTING){const e="WebSocket was closed before the connection was established";abortHandshake(this,this._req,e);return}if(this.readyState===WebSocket.CLOSING){if(this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)){this._socket.end()}return}this._readyState=WebSocket.CLOSING;this._sender.close(e,t,!this._isServer,(e=>{if(e)return;this._closeFrameSent=true;if(this._closeFrameReceived||this._receiver._writableState.errorEmitted){this._socket.end()}}));setCloseTimer(this)}pause(){if(this.readyState===WebSocket.CONNECTING||this.readyState===WebSocket.CLOSED){return}this._paused=true;this._socket.pause()}ping(e,t,s){if(this.readyState===WebSocket.CONNECTING){throw new Error("WebSocket is not open: readyState 0 (CONNECTING)")}if(typeof e==="function"){s=e;e=t=undefined}else if(typeof t==="function"){s=t;t=undefined}if(typeof e==="number")e=e.toString();if(this.readyState!==WebSocket.OPEN){sendAfterClose(this,e,s);return}if(t===undefined)t=!this._isServer;this._sender.ping(e||S,t,s)}pong(e,t,s){if(this.readyState===WebSocket.CONNECTING){throw new Error("WebSocket is not open: readyState 0 (CONNECTING)")}if(typeof e==="function"){s=e;e=t=undefined}else if(typeof t==="function"){s=t;t=undefined}if(typeof e==="number")e=e.toString();if(this.readyState!==WebSocket.OPEN){sendAfterClose(this,e,s);return}if(t===undefined)t=!this._isServer;this._sender.pong(e||S,t,s)}resume(){if(this.readyState===WebSocket.CONNECTING||this.readyState===WebSocket.CLOSED){return}this._paused=false;if(!this._receiver._writableState.needDrain)this._socket.resume()}send(e,t,s){if(this.readyState===WebSocket.CONNECTING){throw new Error("WebSocket is not open: readyState 0 (CONNECTING)")}if(typeof t==="function"){s=t;t={}}if(typeof e==="number")e=e.toString();if(this.readyState!==WebSocket.OPEN){sendAfterClose(this,e,s);return}const r={binary:typeof e!=="string",mask:!this._isServer,compress:true,fin:true,...t};if(!this._extensions[d.extensionName]){r.compress=false}this._sender.send(e||S,r,s)}terminate(){if(this.readyState===WebSocket.CLOSED)return;if(this.readyState===WebSocket.CONNECTING){const e="WebSocket was closed before the connection was established";abortHandshake(this,this._req,e);return}if(this._socket){this._readyState=WebSocket.CLOSING;this._socket.destroy()}}}Object.defineProperty(WebSocket,"CONNECTING",{enumerable:true,value:B.indexOf("CONNECTING")});Object.defineProperty(WebSocket.prototype,"CONNECTING",{enumerable:true,value:B.indexOf("CONNECTING")});Object.defineProperty(WebSocket,"OPEN",{enumerable:true,value:B.indexOf("OPEN")});Object.defineProperty(WebSocket.prototype,"OPEN",{enumerable:true,value:B.indexOf("OPEN")});Object.defineProperty(WebSocket,"CLOSING",{enumerable:true,value:B.indexOf("CLOSING")});Object.defineProperty(WebSocket.prototype,"CLOSING",{enumerable:true,value:B.indexOf("CLOSING")});Object.defineProperty(WebSocket,"CLOSED",{enumerable:true,value:B.indexOf("CLOSED")});Object.defineProperty(WebSocket.prototype,"CLOSED",{enumerable:true,value:B.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach((e=>{Object.defineProperty(WebSocket.prototype,e,{enumerable:true})}));["open","error","close","message"].forEach((e=>{Object.defineProperty(WebSocket.prototype,`on${e}`,{enumerable:true,get(){for(const t of this.listeners(e)){if(t[k])return t[g]}return null},set(t){for(const t of this.listeners(e)){if(t[k]){this.removeListener(e,t);break}}if(typeof t!=="function")return;this.addEventListener(e,t,{[k]:true})}})}));WebSocket.prototype.addEventListener=x;WebSocket.prototype.removeEventListener=O;e.exports=WebSocket;function initAsClient(e,t,s,r){const o={allowSynchronousEvents:true,autoPong:true,protocolVersion:W[1],maxPayload:100*1024*1024,skipUTF8Validation:false,perMessageDeflate:true,followRedirects:false,maxRedirects:10,...r,socketPath:undefined,hostname:undefined,protocol:undefined,timeout:undefined,method:"GET",host:undefined,path:undefined,port:undefined};e._autoPong=o.autoPong;if(!W.includes(o.protocolVersion)){throw new RangeError(`Unsupported protocol version: ${o.protocolVersion} `+`(supported versions: ${W.join(", ")})`)}let a;if(t instanceof u){a=t}else{try{a=new u(t)}catch(e){throw new SyntaxError(`Invalid URL: ${t}`)}}if(a.protocol==="http:"){a.protocol="ws:"}else if(a.protocol==="https:"){a.protocol="wss:"}e._url=a.href;const f=a.protocol==="wss:";const h=a.protocol==="ws+unix:";let _;if(a.protocol!=="ws:"&&!f&&!h){_='The URL\'s protocol must be one of "ws:", "wss:", '+'"http:", "https", or "ws+unix:"'}else if(h&&!a.pathname){_="The URL's pathname is empty"}else if(a.hash){_="The URL contains a fragment identifier"}if(_){const t=new SyntaxError(_);if(e._redirects===0){throw t}else{emitErrorAndClose(e,t);return}}const p=f?443:80;const m=c(16).toString("base64");const b=f?n.request:i.request;const S=new Set;let k;o.createConnection=o.createConnection||(f?tlsConnect:netConnect);o.defaultPort=o.defaultPort||p;o.port=a.port||p;o.host=a.hostname.startsWith("[")?a.hostname.slice(1,-1):a.hostname;o.headers={...o.headers,"Sec-WebSocket-Version":o.protocolVersion,"Sec-WebSocket-Key":m,Connection:"Upgrade",Upgrade:"websocket"};o.path=a.pathname+a.search;o.timeout=o.handshakeTimeout;if(o.perMessageDeflate){k=new d(o.perMessageDeflate!==true?o.perMessageDeflate:{},false,o.maxPayload);o.headers["Sec-WebSocket-Extensions"]=C({[d.extensionName]:k.offer()})}if(s.length){for(const e of s){if(typeof e!=="string"||!R.test(e)||S.has(e)){throw new SyntaxError("An invalid or duplicated subprotocol was specified")}S.add(e)}o.headers["Sec-WebSocket-Protocol"]=s.join(",")}if(o.origin){if(o.protocolVersion<13){o.headers["Sec-WebSocket-Origin"]=o.origin}else{o.headers.Origin=o.origin}}if(a.username||a.password){o.auth=`${a.username}:${a.password}`}if(h){const e=o.path.split(":");o.socketPath=e[0];o.path=e[1]}let g;if(o.followRedirects){if(e._redirects===0){e._originalIpc=h;e._originalSecure=f;e._originalHostOrSocketPath=h?o.socketPath:a.host;const t=r&&r.headers;r={...r,headers:{}};if(t){for(const[e,s]of Object.entries(t)){r.headers[e.toLowerCase()]=s}}}else if(e.listenerCount("redirect")===0){const t=h?e._originalIpc?o.socketPath===e._originalHostOrSocketPath:false:e._originalIpc?false:a.host===e._originalHostOrSocketPath;if(!t||e._originalSecure&&!f){delete o.headers.authorization;delete o.headers.cookie;if(!t)delete o.headers.host;o.auth=undefined}}if(o.auth&&!r.headers.authorization){r.headers.authorization="Basic "+Buffer.from(o.auth).toString("base64")}g=e._req=b(o);if(e._redirects){e.emit("redirect",e.url,g)}}else{g=e._req=b(o)}if(o.timeout){g.on("timeout",(()=>{abortHandshake(e,g,"Opening handshake has timed out")}))}g.on("error",(t=>{if(g===null||g[P])return;g=e._req=null;emitErrorAndClose(e,t)}));g.on("response",(n=>{const i=n.headers.location;const a=n.statusCode;if(i&&o.followRedirects&&a>=300&&a<400){if(++e._redirects>o.maxRedirects){abortHandshake(e,g,"Maximum redirects exceeded");return}g.abort();let n;try{n=new u(i,t)}catch(t){const s=new SyntaxError(`Invalid URL: ${i}`);emitErrorAndClose(e,s);return}initAsClient(e,n,s,r)}else if(!e.emit("unexpected-response",g,n)){abortHandshake(e,g,`Unexpected server response: ${n.statusCode}`)}}));g.on("upgrade",((t,s,r)=>{e.emit("upgrade",t);if(e.readyState!==WebSocket.CONNECTING)return;g=e._req=null;const n=t.headers.upgrade;if(n===undefined||n.toLowerCase()!=="websocket"){abortHandshake(e,s,"Invalid Upgrade header");return}const i=l("sha1").update(m+y).digest("base64");if(t.headers["sec-websocket-accept"]!==i){abortHandshake(e,s,"Invalid Sec-WebSocket-Accept header");return}const a=t.headers["sec-websocket-protocol"];let c;if(a!==undefined){if(!S.size){c="Server sent a subprotocol but none was requested"}else if(!S.has(a)){c="Server sent an invalid subprotocol"}}else if(S.size){c="Server sent no subprotocol"}if(c){abortHandshake(e,s,c);return}if(a)e._protocol=a;const f=t.headers["sec-websocket-extensions"];if(f!==undefined){if(!k){const t="Server sent a Sec-WebSocket-Extensions header but no extension "+"was requested";abortHandshake(e,s,t);return}let t;try{t=T(f)}catch(t){const r="Invalid Sec-WebSocket-Extensions header";abortHandshake(e,s,r);return}const r=Object.keys(t);if(r.length!==1||r[0]!==d.extensionName){const t="Server indicated an extension that was not requested";abortHandshake(e,s,t);return}try{k.accept(t[d.extensionName])}catch(t){const r="Invalid Sec-WebSocket-Extensions header";abortHandshake(e,s,r);return}e._extensions[d.extensionName]=k}e.setSocket(s,r,{allowSynchronousEvents:o.allowSynchronousEvents,generateMask:o.generateMask,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation})}));if(o.finishRequest){o.finishRequest(g,e)}else{g.end()}}function emitErrorAndClose(e,t){e._readyState=WebSocket.CLOSING;e._errorEmitted=true;e.emit("error",t);e.emitClose()}function netConnect(e){e.path=e.socketPath;return o.connect(e)}function tlsConnect(e){e.path=undefined;if(!e.servername&&e.servername!==""){e.servername=o.isIP(e.host)?"":e.host}return a.connect(e)}function abortHandshake(e,t,s){e._readyState=WebSocket.CLOSING;const r=new Error(s);Error.captureStackTrace(r,abortHandshake);if(t.setHeader){t[P]=true;t.abort();if(t.socket&&!t.socket.destroyed){t.socket.destroy()}process.nextTick(emitErrorAndClose,e,r)}else{t.destroy(r);t.once("error",e.emit.bind(e,"error"));t.once("close",e.emitClose.bind(e))}}function sendAfterClose(e,t,s){if(t){const s=m(t)?t.size:L(t).length;if(e._socket)e._sender._bufferedBytes+=s;else e._bufferedAmount+=s}if(s){const t=new Error(`WebSocket is not open: readyState ${e.readyState} `+`(${B[e.readyState]})`);process.nextTick(s,t)}}function receiverOnConclude(e,t){const s=this[w];s._closeFrameReceived=true;s._closeMessage=t;s._closeCode=e;if(s._socket[w]===undefined)return;s._socket.removeListener("data",socketOnData);process.nextTick(resume,s._socket);if(e===1005)s.close();else s.close(e,t)}function receiverOnDrain(){const e=this[w];if(!e.isPaused)e._socket.resume()}function receiverOnError(e){const t=this[w];if(t._socket[w]!==undefined){t._socket.removeListener("data",socketOnData);process.nextTick(resume,t._socket);t.close(e[E])}if(!t._errorEmitted){t._errorEmitted=true;t.emit("error",e)}}function receiverOnFinish(){this[w].emitClose()}function receiverOnMessage(e,t){this[w].emit("message",e,t)}function receiverOnPing(e){const t=this[w];if(t._autoPong)t.pong(e,!this._isServer,v);t.emit("ping",e)}function receiverOnPong(e){this[w].emit("pong",e)}function resume(e){e.resume()}function senderOnError(e){const t=this[w];if(t.readyState===WebSocket.CLOSED)return;if(t.readyState===WebSocket.OPEN){t._readyState=WebSocket.CLOSING;setCloseTimer(t)}this._socket.end();if(!t._errorEmitted){t._errorEmitted=true;t.emit("error",e)}}function setCloseTimer(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),N)}function socketOnClose(){const e=this[w];this.removeListener("close",socketOnClose);this.removeListener("data",socketOnData);this.removeListener("end",socketOnEnd);e._readyState=WebSocket.CLOSING;let t;if(!this._readableState.endEmitted&&!e._closeFrameReceived&&!e._receiver._writableState.errorEmitted&&(t=e._socket.read())!==null){e._receiver.write(t)}e._receiver.end();this[w]=undefined;clearTimeout(e._closeTimer);if(e._receiver._writableState.finished||e._receiver._writableState.errorEmitted){e.emitClose()}else{e._receiver.on("error",receiverOnFinish);e._receiver.on("finish",receiverOnFinish)}}function socketOnData(e){if(!this[w]._receiver.write(e)){this.pause()}}function socketOnEnd(){const e=this[w];e._readyState=WebSocket.CLOSING;e._receiver.end();this.end()}function socketOnError(){const e=this[w];this.removeListener("error",socketOnError);this.on("error",v);if(e){e._readyState=WebSocket.CLOSING;this.destroy()}}},653:function(module){module.exports=eval("require")("bufferutil")},4:function(module){module.exports=eval("require")("utf-8-validate")},181:function(e){"use strict";e.exports=require("buffer")},982:function(e){"use strict";e.exports=require("crypto")},434:function(e){"use strict";e.exports=require("events")},611:function(e){"use strict";e.exports=require("http")},692:function(e){"use strict";e.exports=require("https")},278:function(e){"use strict";e.exports=require("net")},203:function(e){"use strict";e.exports=require("stream")},756:function(e){"use strict";e.exports=require("tls")},16:function(e){"use strict";e.exports=require("url")},106:function(e){"use strict";e.exports=require("zlib")}};var __webpack_module_cache__={};function __nccwpck_require__(e){var t=__webpack_module_cache__[e];if(t!==undefined){return t.exports}var s=__webpack_module_cache__[e]={exports:{}};var r=true;try{__webpack_modules__[e](s,s.exports,__nccwpck_require__);r=false}finally{if(r)delete __webpack_module_cache__[e]}return s.exports}if(typeof __nccwpck_require__!=="undefined")__nccwpck_require__.ab=__dirname+"/";var __webpack_exports__=__nccwpck_require__(99);module.exports=__webpack_exports__})();
@@ -0,0 +1,131 @@
1
+ 'use strict';
2
+
3
+ const { EMPTY_BUFFER } = require('./constants');
4
+
5
+ const FastBuffer = Buffer[Symbol.species];
6
+
7
+ /**
8
+ * Merges an array of buffers into a new buffer.
9
+ *
10
+ * @param {Buffer[]} list The array of buffers to concat
11
+ * @param {Number} totalLength The total length of buffers in the list
12
+ * @return {Buffer} The resulting buffer
13
+ * @public
14
+ */
15
+ function concat(list, totalLength) {
16
+ if (list.length === 0) return EMPTY_BUFFER;
17
+ if (list.length === 1) return list[0];
18
+
19
+ const target = Buffer.allocUnsafe(totalLength);
20
+ let offset = 0;
21
+
22
+ for (let i = 0; i < list.length; i++) {
23
+ const buf = list[i];
24
+ target.set(buf, offset);
25
+ offset += buf.length;
26
+ }
27
+
28
+ if (offset < totalLength) {
29
+ return new FastBuffer(target.buffer, target.byteOffset, offset);
30
+ }
31
+
32
+ return target;
33
+ }
34
+
35
+ /**
36
+ * Masks a buffer using the given mask.
37
+ *
38
+ * @param {Buffer} source The buffer to mask
39
+ * @param {Buffer} mask The mask to use
40
+ * @param {Buffer} output The buffer where to store the result
41
+ * @param {Number} offset The offset at which to start writing
42
+ * @param {Number} length The number of bytes to mask.
43
+ * @public
44
+ */
45
+ function _mask(source, mask, output, offset, length) {
46
+ for (let i = 0; i < length; i++) {
47
+ output[offset + i] = source[i] ^ mask[i & 3];
48
+ }
49
+ }
50
+
51
+ /**
52
+ * Unmasks a buffer using the given mask.
53
+ *
54
+ * @param {Buffer} buffer The buffer to unmask
55
+ * @param {Buffer} mask The mask to use
56
+ * @public
57
+ */
58
+ function _unmask(buffer, mask) {
59
+ for (let i = 0; i < buffer.length; i++) {
60
+ buffer[i] ^= mask[i & 3];
61
+ }
62
+ }
63
+
64
+ /**
65
+ * Converts a buffer to an `ArrayBuffer`.
66
+ *
67
+ * @param {Buffer} buf The buffer to convert
68
+ * @return {ArrayBuffer} Converted buffer
69
+ * @public
70
+ */
71
+ function toArrayBuffer(buf) {
72
+ if (buf.length === buf.buffer.byteLength) {
73
+ return buf.buffer;
74
+ }
75
+
76
+ return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length);
77
+ }
78
+
79
+ /**
80
+ * Converts `data` to a `Buffer`.
81
+ *
82
+ * @param {*} data The data to convert
83
+ * @return {Buffer} The buffer
84
+ * @throws {TypeError}
85
+ * @public
86
+ */
87
+ function toBuffer(data) {
88
+ toBuffer.readOnly = true;
89
+
90
+ if (Buffer.isBuffer(data)) return data;
91
+
92
+ let buf;
93
+
94
+ if (data instanceof ArrayBuffer) {
95
+ buf = new FastBuffer(data);
96
+ } else if (ArrayBuffer.isView(data)) {
97
+ buf = new FastBuffer(data.buffer, data.byteOffset, data.byteLength);
98
+ } else {
99
+ buf = Buffer.from(data);
100
+ toBuffer.readOnly = false;
101
+ }
102
+
103
+ return buf;
104
+ }
105
+
106
+ module.exports = {
107
+ concat,
108
+ mask: _mask,
109
+ toArrayBuffer,
110
+ toBuffer,
111
+ unmask: _unmask
112
+ };
113
+
114
+ /* istanbul ignore else */
115
+ if (!process.env.WS_NO_BUFFER_UTIL) {
116
+ try {
117
+ const bufferUtil = require('bufferutil');
118
+
119
+ module.exports.mask = function (source, mask, output, offset, length) {
120
+ if (length < 48) _mask(source, mask, output, offset, length);
121
+ else bufferUtil.mask(source, mask, output, offset, length);
122
+ };
123
+
124
+ module.exports.unmask = function (buffer, mask) {
125
+ if (buffer.length < 32) _unmask(buffer, mask);
126
+ else bufferUtil.unmask(buffer, mask);
127
+ };
128
+ } catch (e) {
129
+ // Continue regardless of the error.
130
+ }
131
+ }
@@ -0,0 +1,18 @@
1
+ 'use strict';
2
+
3
+ const BINARY_TYPES = ['nodebuffer', 'arraybuffer', 'fragments'];
4
+ const hasBlob = typeof Blob !== 'undefined';
5
+
6
+ if (hasBlob) BINARY_TYPES.push('blob');
7
+
8
+ module.exports = {
9
+ BINARY_TYPES,
10
+ EMPTY_BUFFER: Buffer.alloc(0),
11
+ GUID: '258EAFA5-E914-47DA-95CA-C5AB0DC85B11',
12
+ hasBlob,
13
+ kForOnEventAttribute: Symbol('kIsForOnEventAttribute'),
14
+ kListener: Symbol('kListener'),
15
+ kStatusCode: Symbol('status-code'),
16
+ kWebSocket: Symbol('websocket'),
17
+ NOOP: () => {}
18
+ };
@@ -0,0 +1,292 @@
1
+ 'use strict';
2
+
3
+ const { kForOnEventAttribute, kListener } = require('./constants');
4
+
5
+ const kCode = Symbol('kCode');
6
+ const kData = Symbol('kData');
7
+ const kError = Symbol('kError');
8
+ const kMessage = Symbol('kMessage');
9
+ const kReason = Symbol('kReason');
10
+ const kTarget = Symbol('kTarget');
11
+ const kType = Symbol('kType');
12
+ const kWasClean = Symbol('kWasClean');
13
+
14
+ /**
15
+ * Class representing an event.
16
+ */
17
+ class Event {
18
+ /**
19
+ * Create a new `Event`.
20
+ *
21
+ * @param {String} type The name of the event
22
+ * @throws {TypeError} If the `type` argument is not specified
23
+ */
24
+ constructor(type) {
25
+ this[kTarget] = null;
26
+ this[kType] = type;
27
+ }
28
+
29
+ /**
30
+ * @type {*}
31
+ */
32
+ get target() {
33
+ return this[kTarget];
34
+ }
35
+
36
+ /**
37
+ * @type {String}
38
+ */
39
+ get type() {
40
+ return this[kType];
41
+ }
42
+ }
43
+
44
+ Object.defineProperty(Event.prototype, 'target', { enumerable: true });
45
+ Object.defineProperty(Event.prototype, 'type', { enumerable: true });
46
+
47
+ /**
48
+ * Class representing a close event.
49
+ *
50
+ * @extends Event
51
+ */
52
+ class CloseEvent extends Event {
53
+ /**
54
+ * Create a new `CloseEvent`.
55
+ *
56
+ * @param {String} type The name of the event
57
+ * @param {Object} [options] A dictionary object that allows for setting
58
+ * attributes via object members of the same name
59
+ * @param {Number} [options.code=0] The status code explaining why the
60
+ * connection was closed
61
+ * @param {String} [options.reason=''] A human-readable string explaining why
62
+ * the connection was closed
63
+ * @param {Boolean} [options.wasClean=false] Indicates whether or not the
64
+ * connection was cleanly closed
65
+ */
66
+ constructor(type, options = {}) {
67
+ super(type);
68
+
69
+ this[kCode] = options.code === undefined ? 0 : options.code;
70
+ this[kReason] = options.reason === undefined ? '' : options.reason;
71
+ this[kWasClean] = options.wasClean === undefined ? false : options.wasClean;
72
+ }
73
+
74
+ /**
75
+ * @type {Number}
76
+ */
77
+ get code() {
78
+ return this[kCode];
79
+ }
80
+
81
+ /**
82
+ * @type {String}
83
+ */
84
+ get reason() {
85
+ return this[kReason];
86
+ }
87
+
88
+ /**
89
+ * @type {Boolean}
90
+ */
91
+ get wasClean() {
92
+ return this[kWasClean];
93
+ }
94
+ }
95
+
96
+ Object.defineProperty(CloseEvent.prototype, 'code', { enumerable: true });
97
+ Object.defineProperty(CloseEvent.prototype, 'reason', { enumerable: true });
98
+ Object.defineProperty(CloseEvent.prototype, 'wasClean', { enumerable: true });
99
+
100
+ /**
101
+ * Class representing an error event.
102
+ *
103
+ * @extends Event
104
+ */
105
+ class ErrorEvent extends Event {
106
+ /**
107
+ * Create a new `ErrorEvent`.
108
+ *
109
+ * @param {String} type The name of the event
110
+ * @param {Object} [options] A dictionary object that allows for setting
111
+ * attributes via object members of the same name
112
+ * @param {*} [options.error=null] The error that generated this event
113
+ * @param {String} [options.message=''] The error message
114
+ */
115
+ constructor(type, options = {}) {
116
+ super(type);
117
+
118
+ this[kError] = options.error === undefined ? null : options.error;
119
+ this[kMessage] = options.message === undefined ? '' : options.message;
120
+ }
121
+
122
+ /**
123
+ * @type {*}
124
+ */
125
+ get error() {
126
+ return this[kError];
127
+ }
128
+
129
+ /**
130
+ * @type {String}
131
+ */
132
+ get message() {
133
+ return this[kMessage];
134
+ }
135
+ }
136
+
137
+ Object.defineProperty(ErrorEvent.prototype, 'error', { enumerable: true });
138
+ Object.defineProperty(ErrorEvent.prototype, 'message', { enumerable: true });
139
+
140
+ /**
141
+ * Class representing a message event.
142
+ *
143
+ * @extends Event
144
+ */
145
+ class MessageEvent extends Event {
146
+ /**
147
+ * Create a new `MessageEvent`.
148
+ *
149
+ * @param {String} type The name of the event
150
+ * @param {Object} [options] A dictionary object that allows for setting
151
+ * attributes via object members of the same name
152
+ * @param {*} [options.data=null] The message content
153
+ */
154
+ constructor(type, options = {}) {
155
+ super(type);
156
+
157
+ this[kData] = options.data === undefined ? null : options.data;
158
+ }
159
+
160
+ /**
161
+ * @type {*}
162
+ */
163
+ get data() {
164
+ return this[kData];
165
+ }
166
+ }
167
+
168
+ Object.defineProperty(MessageEvent.prototype, 'data', { enumerable: true });
169
+
170
+ /**
171
+ * This provides methods for emulating the `EventTarget` interface. It's not
172
+ * meant to be used directly.
173
+ *
174
+ * @mixin
175
+ */
176
+ const EventTarget = {
177
+ /**
178
+ * Register an event listener.
179
+ *
180
+ * @param {String} type A string representing the event type to listen for
181
+ * @param {(Function|Object)} handler The listener to add
182
+ * @param {Object} [options] An options object specifies characteristics about
183
+ * the event listener
184
+ * @param {Boolean} [options.once=false] A `Boolean` indicating that the
185
+ * listener should be invoked at most once after being added. If `true`,
186
+ * the listener would be automatically removed when invoked.
187
+ * @public
188
+ */
189
+ addEventListener(type, handler, options = {}) {
190
+ for (const listener of this.listeners(type)) {
191
+ if (
192
+ !options[kForOnEventAttribute] &&
193
+ listener[kListener] === handler &&
194
+ !listener[kForOnEventAttribute]
195
+ ) {
196
+ return;
197
+ }
198
+ }
199
+
200
+ let wrapper;
201
+
202
+ if (type === 'message') {
203
+ wrapper = function onMessage(data, isBinary) {
204
+ const event = new MessageEvent('message', {
205
+ data: isBinary ? data : data.toString()
206
+ });
207
+
208
+ event[kTarget] = this;
209
+ callListener(handler, this, event);
210
+ };
211
+ } else if (type === 'close') {
212
+ wrapper = function onClose(code, message) {
213
+ const event = new CloseEvent('close', {
214
+ code,
215
+ reason: message.toString(),
216
+ wasClean: this._closeFrameReceived && this._closeFrameSent
217
+ });
218
+
219
+ event[kTarget] = this;
220
+ callListener(handler, this, event);
221
+ };
222
+ } else if (type === 'error') {
223
+ wrapper = function onError(error) {
224
+ const event = new ErrorEvent('error', {
225
+ error,
226
+ message: error.message
227
+ });
228
+
229
+ event[kTarget] = this;
230
+ callListener(handler, this, event);
231
+ };
232
+ } else if (type === 'open') {
233
+ wrapper = function onOpen() {
234
+ const event = new Event('open');
235
+
236
+ event[kTarget] = this;
237
+ callListener(handler, this, event);
238
+ };
239
+ } else {
240
+ return;
241
+ }
242
+
243
+ wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute];
244
+ wrapper[kListener] = handler;
245
+
246
+ if (options.once) {
247
+ this.once(type, wrapper);
248
+ } else {
249
+ this.on(type, wrapper);
250
+ }
251
+ },
252
+
253
+ /**
254
+ * Remove an event listener.
255
+ *
256
+ * @param {String} type A string representing the event type to remove
257
+ * @param {(Function|Object)} handler The listener to remove
258
+ * @public
259
+ */
260
+ removeEventListener(type, handler) {
261
+ for (const listener of this.listeners(type)) {
262
+ if (listener[kListener] === handler && !listener[kForOnEventAttribute]) {
263
+ this.removeListener(type, listener);
264
+ break;
265
+ }
266
+ }
267
+ }
268
+ };
269
+
270
+ module.exports = {
271
+ CloseEvent,
272
+ ErrorEvent,
273
+ Event,
274
+ EventTarget,
275
+ MessageEvent
276
+ };
277
+
278
+ /**
279
+ * Call an event listener
280
+ *
281
+ * @param {(Function|Object)} listener The listener to call
282
+ * @param {*} thisArg The value to use as `this`` when calling the listener
283
+ * @param {Event} event The event to pass to the listener
284
+ * @private
285
+ */
286
+ function callListener(listener, thisArg, event) {
287
+ if (typeof listener === 'object' && listener.handleEvent) {
288
+ listener.handleEvent.call(listener, event);
289
+ } else {
290
+ listener.call(thisArg, event);
291
+ }
292
+ }