silvery 0.19.2 → 0.21.1

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 (172) hide show
  1. package/README.md +9 -4
  2. package/dist/Text-BRf-59j2.mjs +237 -0
  3. package/dist/Text-BRf-59j2.mjs.map +1 -0
  4. package/dist/ag-BeFC4S2N.mjs +8727 -0
  5. package/dist/ag-BeFC4S2N.mjs.map +1 -0
  6. package/dist/{animation-Cn64yepo.mjs → animation-N8MFybTk.mjs} +2 -2
  7. package/dist/animation-N8MFybTk.mjs.map +1 -0
  8. package/dist/{ansi-CLOitHKx.mjs → ansi-C6Qs1Wn2.mjs} +1 -1
  9. package/dist/{ansi-CLOitHKx.mjs.map → ansi-C6Qs1Wn2.mjs.map} +1 -1
  10. package/dist/{ansi-Cc33mW54.d.mts → ansi-CBkam1ty.d.mts} +1 -1
  11. package/dist/{ansi-Cc33mW54.d.mts.map → ansi-CBkam1ty.d.mts.map} +1 -1
  12. package/dist/ansi-OYRLxxZQ.mjs +10669 -0
  13. package/dist/ansi-OYRLxxZQ.mjs.map +1 -0
  14. package/dist/bound-term-BumfuXXW.d.mts +4902 -0
  15. package/dist/bound-term-BumfuXXW.d.mts.map +1 -0
  16. package/dist/{chunk-Vs_PY4HZ.mjs → chunk-hT5z_Zn9.mjs} +1 -3
  17. package/dist/cli-DG6zsfsS.mjs +4 -0
  18. package/dist/context-BU5LkkIy.mjs.map +1 -1
  19. package/dist/{devtools-DxkSLXDA.mjs → devtools-9zfhpFyG.mjs} +3 -3
  20. package/dist/{devtools-DxkSLXDA.mjs.map → devtools-9zfhpFyG.mjs.map} +1 -1
  21. package/dist/devtools-nmPUmYU_.mjs +2 -0
  22. package/dist/easing-B0oZKDki.d.mts +24 -0
  23. package/dist/easing-B0oZKDki.d.mts.map +1 -0
  24. package/dist/{eta-Bb3RH3wh.mjs → eta-DGOuC8yU.mjs} +5 -1
  25. package/dist/{eta-Bb3RH3wh.mjs.map → eta-DGOuC8yU.mjs.map} +1 -1
  26. package/dist/flexily-zero-adapter-CEJOcbNp.mjs +306 -0
  27. package/dist/flexily-zero-adapter-CEJOcbNp.mjs.map +1 -0
  28. package/dist/{flexily-zero-adapter-CMxXhdOL.mjs → flexily-zero-adapter-D6hcFgrH.mjs} +1 -1
  29. package/dist/image-1nRyKa60.mjs +5960 -0
  30. package/dist/image-1nRyKa60.mjs.map +1 -0
  31. package/dist/{index-D3saHouR.d.mts → index-2E1jYgak.d.mts} +1057 -1133
  32. package/dist/index-2E1jYgak.d.mts.map +1 -0
  33. package/dist/index-Bi4Jdz5g.d.mts +453 -0
  34. package/dist/index-Bi4Jdz5g.d.mts.map +1 -0
  35. package/dist/index-Dg1YaeJb.d.mts +336 -0
  36. package/dist/index-Dg1YaeJb.d.mts.map +1 -0
  37. package/dist/{index-BXslOebb.d.mts → index-DnuadDNL.d.mts} +5750 -4158
  38. package/dist/index-DnuadDNL.d.mts.map +1 -0
  39. package/dist/index.d.mts +8 -5
  40. package/dist/index.d.mts.map +1 -1
  41. package/dist/index.mjs +16 -12
  42. package/dist/index.mjs.map +1 -1
  43. package/dist/layout-engine-Ca_nbtfL.mjs +67 -0
  44. package/dist/layout-engine-Ca_nbtfL.mjs.map +1 -0
  45. package/dist/{layout-engine-B6Cdz1yZ.mjs → layout-engine-CgsoBRIn.mjs} +1 -1
  46. package/dist/layout-signals-Dch2EiCy.mjs +1111 -0
  47. package/dist/layout-signals-Dch2EiCy.mjs.map +1 -0
  48. package/dist/mouse-events-hnbJZRwK.mjs +1071 -0
  49. package/dist/mouse-events-hnbJZRwK.mjs.map +1 -0
  50. package/dist/{multi-progress-DAQC7eap.d.mts → multi-progress-Bg4ngK80.d.mts} +2 -2
  51. package/dist/{multi-progress-DAQC7eap.d.mts.map → multi-progress-Bg4ngK80.d.mts.map} +1 -1
  52. package/dist/{multi-progress-Bq9Oi_WI.mjs → multi-progress-CaXTuL9G.mjs} +3 -3
  53. package/dist/{multi-progress-Bq9Oi_WI.mjs.map → multi-progress-CaXTuL9G.mjs.map} +1 -1
  54. package/dist/{node-BeWlnCPY.mjs → node-BiFu8I9Y.mjs} +4 -4
  55. package/dist/node-BiFu8I9Y.mjs.map +1 -0
  56. package/dist/progress-B_UPy6zk.mjs +675 -0
  57. package/dist/progress-B_UPy6zk.mjs.map +1 -0
  58. package/dist/{progress-bar-CXE5Qfkd.mjs → progress-bar-DmIMPdL0.mjs} +4 -4
  59. package/dist/{progress-bar-CXE5Qfkd.mjs.map → progress-bar-DmIMPdL0.mjs.map} +1 -1
  60. package/dist/reconciler-NBDSEm8k.mjs +2178 -0
  61. package/dist/reconciler-NBDSEm8k.mjs.map +1 -0
  62. package/dist/render-string-B4h4SmK7.mjs +211 -0
  63. package/dist/render-string-B4h4SmK7.mjs.map +1 -0
  64. package/dist/{render-string-CDCeYkS3.mjs → render-string-BntLj7Xq.mjs} +1 -1
  65. package/dist/runtime.d.mts +3 -2
  66. package/dist/runtime.mjs +3 -3
  67. package/dist/{src-B5GjfG7g.mjs → schemes-DYt2ushj.mjs} +23 -1812
  68. package/dist/schemes-DYt2ushj.mjs.map +1 -0
  69. package/dist/{spinner-CGo34vyR.d.mts → spinner-CLgzJ_QF.d.mts} +2 -2
  70. package/dist/{spinner-CGo34vyR.d.mts.map → spinner-CLgzJ_QF.d.mts.map} +1 -1
  71. package/dist/{spinner-CeOmcuw_.mjs → spinner-Py8_-hn9.mjs} +23 -8
  72. package/dist/spinner-Py8_-hn9.mjs.map +1 -0
  73. package/dist/src-B9S_woYc.mjs +25024 -0
  74. package/dist/src-B9S_woYc.mjs.map +1 -0
  75. package/dist/src-CbhWmUnF.mjs +3928 -0
  76. package/dist/src-CbhWmUnF.mjs.map +1 -0
  77. package/dist/src-Dvq-s8iD.mjs +939 -0
  78. package/dist/src-Dvq-s8iD.mjs.map +1 -0
  79. package/dist/src-Oe6x5PrS.mjs +4621 -0
  80. package/dist/src-Oe6x5PrS.mjs.map +1 -0
  81. package/dist/{types-Bk2yw9Qj.mjs → src-WeA_J4BV.mjs} +34 -94
  82. package/dist/src-WeA_J4BV.mjs.map +1 -0
  83. package/dist/steps-DYrzCUCK.d.mts +202 -0
  84. package/dist/steps-DYrzCUCK.d.mts.map +1 -0
  85. package/dist/svg-DhxQkz-O.mjs +255 -0
  86. package/dist/svg-DhxQkz-O.mjs.map +1 -0
  87. package/dist/svg-Hk7lIl4F.d.mts +82 -0
  88. package/dist/svg-Hk7lIl4F.d.mts.map +1 -0
  89. package/dist/term.d.mts +3 -0
  90. package/dist/term.mjs +4 -0
  91. package/dist/theme.d.mts +95 -2
  92. package/dist/theme.d.mts.map +1 -0
  93. package/dist/theme.mjs +4 -3
  94. package/dist/{types-BH_v3iMT.d.mts → types-Bx-XZNbE.d.mts} +2 -15
  95. package/dist/types-Bx-XZNbE.d.mts.map +1 -0
  96. package/dist/ui/animation.d.mts +2 -1
  97. package/dist/ui/animation.mjs +1 -1
  98. package/dist/ui/ansi.d.mts +1 -1
  99. package/dist/ui/ansi.mjs +1 -1
  100. package/dist/ui/cli.d.mts +3 -3
  101. package/dist/ui/cli.mjs +5 -5
  102. package/dist/ui/display.d.mts +1 -1
  103. package/dist/ui/display.mjs.map +1 -1
  104. package/dist/ui/image.d.mts +2 -2
  105. package/dist/ui/image.mjs +2 -2
  106. package/dist/ui/input.d.mts +1 -1
  107. package/dist/ui/input.mjs.map +1 -1
  108. package/dist/ui/progress.d.mts +5 -249
  109. package/dist/ui/progress.mjs +5 -858
  110. package/dist/ui/react.d.mts +1 -1
  111. package/dist/ui/react.mjs +2 -2
  112. package/dist/ui/react.mjs.map +1 -1
  113. package/dist/ui/recording-chrome-react.d.mts +21 -0
  114. package/dist/ui/recording-chrome-react.d.mts.map +1 -0
  115. package/dist/ui/recording-chrome-react.mjs +105 -0
  116. package/dist/ui/recording-chrome-react.mjs.map +1 -0
  117. package/dist/ui/recording-chrome.d.mts +2 -0
  118. package/dist/ui/recording-chrome.mjs +2 -0
  119. package/dist/ui/utils.mjs +1 -1
  120. package/dist/ui/wrappers.d.mts +3 -3
  121. package/dist/ui/wrappers.mjs +2 -2
  122. package/dist/ui.d.mts +7 -6
  123. package/dist/ui.mjs +8 -7
  124. package/dist/{useLatest-Bg2x4bfP.d.mts → useLatest-DC8i7guK.d.mts} +5 -25
  125. package/dist/useLatest-DC8i7guK.d.mts.map +1 -0
  126. package/dist/useLayout-BKsQl2Or.mjs +424 -0
  127. package/dist/useLayout-BKsQl2Or.mjs.map +1 -0
  128. package/dist/{with-text-input-CRfoiFFG.d.mts → with-text-input-DG4f7JII.d.mts} +4 -55
  129. package/dist/with-text-input-DG4f7JII.d.mts.map +1 -0
  130. package/dist/wrapper-D7gNSsgf.mjs +3589 -0
  131. package/dist/wrapper-D7gNSsgf.mjs.map +1 -0
  132. package/dist/{wrappers-UTADQkSY.mjs → wrappers-CypAzrMO.mjs} +19 -161
  133. package/dist/wrappers-CypAzrMO.mjs.map +1 -0
  134. package/dist/yoga-adapter-1ex8r0ws.mjs +2 -0
  135. package/dist/{yoga-adapter-8oRGRw8V.mjs → yoga-adapter-SsEIqMc1.mjs} +28 -2
  136. package/dist/yoga-adapter-SsEIqMc1.mjs.map +1 -0
  137. package/package.json +63 -12
  138. package/dist/animation-Cn64yepo.mjs.map +0 -1
  139. package/dist/cli-BKp0YtBD.mjs +0 -4
  140. package/dist/devtools-9QY4teqI.mjs +0 -2
  141. package/dist/flexily-zero-adapter-BlQa46nr.mjs +0 -3385
  142. package/dist/flexily-zero-adapter-BlQa46nr.mjs.map +0 -1
  143. package/dist/image-CTII5QWI.mjs +0 -477
  144. package/dist/image-CTII5QWI.mjs.map +0 -1
  145. package/dist/index-BXslOebb.d.mts.map +0 -1
  146. package/dist/index-BnA7mNpo.d.mts +0 -175
  147. package/dist/index-BnA7mNpo.d.mts.map +0 -1
  148. package/dist/index-D3saHouR.d.mts.map +0 -1
  149. package/dist/layout-engine-ClUgv6jB.mjs +0 -50
  150. package/dist/layout-engine-ClUgv6jB.mjs.map +0 -1
  151. package/dist/node-BeWlnCPY.mjs.map +0 -1
  152. package/dist/reconciler-Cwgm8hRR.mjs +0 -8459
  153. package/dist/reconciler-Cwgm8hRR.mjs.map +0 -1
  154. package/dist/render-string-Darrg7ku.mjs +0 -5529
  155. package/dist/render-string-Darrg7ku.mjs.map +0 -1
  156. package/dist/spinner-CeOmcuw_.mjs.map +0 -1
  157. package/dist/src-B5GjfG7g.mjs.map +0 -1
  158. package/dist/src-CChwjk0Z.mjs +0 -738
  159. package/dist/src-CChwjk0Z.mjs.map +0 -1
  160. package/dist/src-CF-6UN01.mjs +0 -19434
  161. package/dist/src-CF-6UN01.mjs.map +0 -1
  162. package/dist/src-NCKb8kE5.mjs +0 -2660
  163. package/dist/src-NCKb8kE5.mjs.map +0 -1
  164. package/dist/types-BH_v3iMT.d.mts.map +0 -1
  165. package/dist/types-Bk2yw9Qj.mjs.map +0 -1
  166. package/dist/ui/progress.d.mts.map +0 -1
  167. package/dist/ui/progress.mjs.map +0 -1
  168. package/dist/useLatest-Bg2x4bfP.d.mts.map +0 -1
  169. package/dist/with-text-input-CRfoiFFG.d.mts.map +0 -1
  170. package/dist/wrappers-UTADQkSY.mjs.map +0 -1
  171. package/dist/yoga-adapter-8oRGRw8V.mjs.map +0 -1
  172. package/dist/yoga-adapter-D_CcxSt5.mjs +0 -2
@@ -0,0 +1,3589 @@
1
+ import { i as __toESM, r as __require, t as __commonJSMin } from "./chunk-hT5z_Zn9.mjs";
2
+ //#region node_modules/ws/lib/constants.js
3
+ var require_constants = /* @__PURE__ */ __commonJSMin(((exports, module) => {
4
+ const BINARY_TYPES = [
5
+ "nodebuffer",
6
+ "arraybuffer",
7
+ "fragments"
8
+ ];
9
+ const hasBlob = typeof Blob !== "undefined";
10
+ if (hasBlob) BINARY_TYPES.push("blob");
11
+ module.exports = {
12
+ BINARY_TYPES,
13
+ CLOSE_TIMEOUT: 3e4,
14
+ EMPTY_BUFFER: Buffer.alloc(0),
15
+ GUID: "258EAFA5-E914-47DA-95CA-C5AB0DC85B11",
16
+ hasBlob,
17
+ kForOnEventAttribute: Symbol("kIsForOnEventAttribute"),
18
+ kListener: Symbol("kListener"),
19
+ kStatusCode: Symbol("status-code"),
20
+ kWebSocket: Symbol("websocket"),
21
+ NOOP: () => {}
22
+ };
23
+ }));
24
+ //#endregion
25
+ //#region node_modules/ws/lib/buffer-util.js
26
+ var require_buffer_util = /* @__PURE__ */ __commonJSMin(((exports, module) => {
27
+ const { EMPTY_BUFFER } = require_constants();
28
+ const FastBuffer = Buffer[Symbol.species];
29
+ /**
30
+ * Merges an array of buffers into a new buffer.
31
+ *
32
+ * @param {Buffer[]} list The array of buffers to concat
33
+ * @param {Number} totalLength The total length of buffers in the list
34
+ * @return {Buffer} The resulting buffer
35
+ * @public
36
+ */
37
+ function concat(list, totalLength) {
38
+ if (list.length === 0) return EMPTY_BUFFER;
39
+ if (list.length === 1) return list[0];
40
+ const target = Buffer.allocUnsafe(totalLength);
41
+ let offset = 0;
42
+ for (let i = 0; i < list.length; i++) {
43
+ const buf = list[i];
44
+ target.set(buf, offset);
45
+ offset += buf.length;
46
+ }
47
+ if (offset < totalLength) return new FastBuffer(target.buffer, target.byteOffset, offset);
48
+ return target;
49
+ }
50
+ /**
51
+ * Masks a buffer using the given mask.
52
+ *
53
+ * @param {Buffer} source The buffer to mask
54
+ * @param {Buffer} mask The mask to use
55
+ * @param {Buffer} output The buffer where to store the result
56
+ * @param {Number} offset The offset at which to start writing
57
+ * @param {Number} length The number of bytes to mask.
58
+ * @public
59
+ */
60
+ function _mask(source, mask, output, offset, length) {
61
+ for (let i = 0; i < length; i++) output[offset + i] = source[i] ^ mask[i & 3];
62
+ }
63
+ /**
64
+ * Unmasks a buffer using the given mask.
65
+ *
66
+ * @param {Buffer} buffer The buffer to unmask
67
+ * @param {Buffer} mask The mask to use
68
+ * @public
69
+ */
70
+ function _unmask(buffer, mask) {
71
+ for (let i = 0; i < buffer.length; i++) buffer[i] ^= mask[i & 3];
72
+ }
73
+ /**
74
+ * Converts a buffer to an `ArrayBuffer`.
75
+ *
76
+ * @param {Buffer} buf The buffer to convert
77
+ * @return {ArrayBuffer} Converted buffer
78
+ * @public
79
+ */
80
+ function toArrayBuffer(buf) {
81
+ if (buf.length === buf.buffer.byteLength) return buf.buffer;
82
+ return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length);
83
+ }
84
+ /**
85
+ * Converts `data` to a `Buffer`.
86
+ *
87
+ * @param {*} data The data to convert
88
+ * @return {Buffer} The buffer
89
+ * @throws {TypeError}
90
+ * @public
91
+ */
92
+ function toBuffer(data) {
93
+ toBuffer.readOnly = true;
94
+ if (Buffer.isBuffer(data)) return data;
95
+ let buf;
96
+ if (data instanceof ArrayBuffer) buf = new FastBuffer(data);
97
+ else if (ArrayBuffer.isView(data)) buf = new FastBuffer(data.buffer, data.byteOffset, data.byteLength);
98
+ else {
99
+ buf = Buffer.from(data);
100
+ toBuffer.readOnly = false;
101
+ }
102
+ return buf;
103
+ }
104
+ module.exports = {
105
+ concat,
106
+ mask: _mask,
107
+ toArrayBuffer,
108
+ toBuffer,
109
+ unmask: _unmask
110
+ };
111
+ /* istanbul ignore else */
112
+ if (!process.env.WS_NO_BUFFER_UTIL) try {
113
+ const bufferUtil = __require("bufferutil");
114
+ module.exports.mask = function(source, mask, output, offset, length) {
115
+ if (length < 48) _mask(source, mask, output, offset, length);
116
+ else bufferUtil.mask(source, mask, output, offset, length);
117
+ };
118
+ module.exports.unmask = function(buffer, mask) {
119
+ if (buffer.length < 32) _unmask(buffer, mask);
120
+ else bufferUtil.unmask(buffer, mask);
121
+ };
122
+ } catch (e) {}
123
+ }));
124
+ //#endregion
125
+ //#region node_modules/ws/lib/limiter.js
126
+ var require_limiter = /* @__PURE__ */ __commonJSMin(((exports, module) => {
127
+ const kDone = Symbol("kDone");
128
+ const kRun = Symbol("kRun");
129
+ /**
130
+ * A very simple job queue with adjustable concurrency. Adapted from
131
+ * https://github.com/STRML/async-limiter
132
+ */
133
+ var Limiter = class {
134
+ /**
135
+ * Creates a new `Limiter`.
136
+ *
137
+ * @param {Number} [concurrency=Infinity] The maximum number of jobs allowed
138
+ * to run concurrently
139
+ */
140
+ constructor(concurrency) {
141
+ this[kDone] = () => {
142
+ this.pending--;
143
+ this[kRun]();
144
+ };
145
+ this.concurrency = concurrency || Infinity;
146
+ this.jobs = [];
147
+ this.pending = 0;
148
+ }
149
+ /**
150
+ * Adds a job to the queue.
151
+ *
152
+ * @param {Function} job The job to run
153
+ * @public
154
+ */
155
+ add(job) {
156
+ this.jobs.push(job);
157
+ this[kRun]();
158
+ }
159
+ /**
160
+ * Removes a job from the queue and runs it if possible.
161
+ *
162
+ * @private
163
+ */
164
+ [kRun]() {
165
+ if (this.pending === this.concurrency) return;
166
+ if (this.jobs.length) {
167
+ const job = this.jobs.shift();
168
+ this.pending++;
169
+ job(this[kDone]);
170
+ }
171
+ }
172
+ };
173
+ module.exports = Limiter;
174
+ }));
175
+ //#endregion
176
+ //#region node_modules/ws/lib/permessage-deflate.js
177
+ var require_permessage_deflate = /* @__PURE__ */ __commonJSMin(((exports, module) => {
178
+ const zlib = __require("zlib");
179
+ const bufferUtil = require_buffer_util();
180
+ const Limiter = require_limiter();
181
+ const { kStatusCode } = require_constants();
182
+ const FastBuffer = Buffer[Symbol.species];
183
+ const TRAILER = Buffer.from([
184
+ 0,
185
+ 0,
186
+ 255,
187
+ 255
188
+ ]);
189
+ const kPerMessageDeflate = Symbol("permessage-deflate");
190
+ const kTotalLength = Symbol("total-length");
191
+ const kCallback = Symbol("callback");
192
+ const kBuffers = Symbol("buffers");
193
+ const kError = Symbol("error");
194
+ let zlibLimiter;
195
+ /**
196
+ * permessage-deflate implementation.
197
+ */
198
+ var PerMessageDeflate = class {
199
+ /**
200
+ * Creates a PerMessageDeflate instance.
201
+ *
202
+ * @param {Object} [options] Configuration options
203
+ * @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support
204
+ * for, or request, a custom client window size
205
+ * @param {Boolean} [options.clientNoContextTakeover=false] Advertise/
206
+ * acknowledge disabling of client context takeover
207
+ * @param {Number} [options.concurrencyLimit=10] The number of concurrent
208
+ * calls to zlib
209
+ * @param {Boolean} [options.isServer=false] Create the instance in either
210
+ * server or client mode
211
+ * @param {Number} [options.maxPayload=0] The maximum allowed message length
212
+ * @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the
213
+ * use of a custom server window size
214
+ * @param {Boolean} [options.serverNoContextTakeover=false] Request/accept
215
+ * disabling of server context takeover
216
+ * @param {Number} [options.threshold=1024] Size (in bytes) below which
217
+ * messages should not be compressed if context takeover is disabled
218
+ * @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on
219
+ * deflate
220
+ * @param {Object} [options.zlibInflateOptions] Options to pass to zlib on
221
+ * inflate
222
+ */
223
+ constructor(options) {
224
+ this._options = options || {};
225
+ this._threshold = this._options.threshold !== void 0 ? this._options.threshold : 1024;
226
+ this._maxPayload = this._options.maxPayload | 0;
227
+ this._isServer = !!this._options.isServer;
228
+ this._deflate = null;
229
+ this._inflate = null;
230
+ this.params = null;
231
+ if (!zlibLimiter) zlibLimiter = new Limiter(this._options.concurrencyLimit !== void 0 ? this._options.concurrencyLimit : 10);
232
+ }
233
+ /**
234
+ * @type {String}
235
+ */
236
+ static get extensionName() {
237
+ return "permessage-deflate";
238
+ }
239
+ /**
240
+ * Create an extension negotiation offer.
241
+ *
242
+ * @return {Object} Extension parameters
243
+ * @public
244
+ */
245
+ offer() {
246
+ const params = {};
247
+ if (this._options.serverNoContextTakeover) params.server_no_context_takeover = true;
248
+ if (this._options.clientNoContextTakeover) params.client_no_context_takeover = true;
249
+ if (this._options.serverMaxWindowBits) params.server_max_window_bits = this._options.serverMaxWindowBits;
250
+ if (this._options.clientMaxWindowBits) params.client_max_window_bits = this._options.clientMaxWindowBits;
251
+ else if (this._options.clientMaxWindowBits == null) params.client_max_window_bits = true;
252
+ return params;
253
+ }
254
+ /**
255
+ * Accept an extension negotiation offer/response.
256
+ *
257
+ * @param {Array} configurations The extension negotiation offers/reponse
258
+ * @return {Object} Accepted configuration
259
+ * @public
260
+ */
261
+ accept(configurations) {
262
+ configurations = this.normalizeParams(configurations);
263
+ this.params = this._isServer ? this.acceptAsServer(configurations) : this.acceptAsClient(configurations);
264
+ return this.params;
265
+ }
266
+ /**
267
+ * Releases all resources used by the extension.
268
+ *
269
+ * @public
270
+ */
271
+ cleanup() {
272
+ if (this._inflate) {
273
+ this._inflate.close();
274
+ this._inflate = null;
275
+ }
276
+ if (this._deflate) {
277
+ const callback = this._deflate[kCallback];
278
+ this._deflate.close();
279
+ this._deflate = null;
280
+ if (callback) callback(/* @__PURE__ */ new Error("The deflate stream was closed while data was being processed"));
281
+ }
282
+ }
283
+ /**
284
+ * Accept an extension negotiation offer.
285
+ *
286
+ * @param {Array} offers The extension negotiation offers
287
+ * @return {Object} Accepted configuration
288
+ * @private
289
+ */
290
+ acceptAsServer(offers) {
291
+ const opts = this._options;
292
+ const accepted = offers.find((params) => {
293
+ if (opts.serverNoContextTakeover === false && params.server_no_context_takeover || params.server_max_window_bits && (opts.serverMaxWindowBits === false || typeof opts.serverMaxWindowBits === "number" && opts.serverMaxWindowBits > params.server_max_window_bits) || typeof opts.clientMaxWindowBits === "number" && !params.client_max_window_bits) return false;
294
+ return true;
295
+ });
296
+ if (!accepted) throw new Error("None of the extension offers can be accepted");
297
+ if (opts.serverNoContextTakeover) accepted.server_no_context_takeover = true;
298
+ if (opts.clientNoContextTakeover) accepted.client_no_context_takeover = true;
299
+ if (typeof opts.serverMaxWindowBits === "number") accepted.server_max_window_bits = opts.serverMaxWindowBits;
300
+ if (typeof opts.clientMaxWindowBits === "number") accepted.client_max_window_bits = opts.clientMaxWindowBits;
301
+ else if (accepted.client_max_window_bits === true || opts.clientMaxWindowBits === false) delete accepted.client_max_window_bits;
302
+ return accepted;
303
+ }
304
+ /**
305
+ * Accept the extension negotiation response.
306
+ *
307
+ * @param {Array} response The extension negotiation response
308
+ * @return {Object} Accepted configuration
309
+ * @private
310
+ */
311
+ acceptAsClient(response) {
312
+ const params = response[0];
313
+ if (this._options.clientNoContextTakeover === false && params.client_no_context_takeover) throw new Error("Unexpected parameter \"client_no_context_takeover\"");
314
+ if (!params.client_max_window_bits) {
315
+ if (typeof this._options.clientMaxWindowBits === "number") params.client_max_window_bits = this._options.clientMaxWindowBits;
316
+ } else if (this._options.clientMaxWindowBits === false || typeof this._options.clientMaxWindowBits === "number" && params.client_max_window_bits > this._options.clientMaxWindowBits) throw new Error("Unexpected or invalid parameter \"client_max_window_bits\"");
317
+ return params;
318
+ }
319
+ /**
320
+ * Normalize parameters.
321
+ *
322
+ * @param {Array} configurations The extension negotiation offers/reponse
323
+ * @return {Array} The offers/response with normalized parameters
324
+ * @private
325
+ */
326
+ normalizeParams(configurations) {
327
+ configurations.forEach((params) => {
328
+ Object.keys(params).forEach((key) => {
329
+ let value = params[key];
330
+ if (value.length > 1) throw new Error(`Parameter "${key}" must have only a single value`);
331
+ value = value[0];
332
+ if (key === "client_max_window_bits") {
333
+ if (value !== true) {
334
+ const num = +value;
335
+ if (!Number.isInteger(num) || num < 8 || num > 15) throw new TypeError(`Invalid value for parameter "${key}": ${value}`);
336
+ value = num;
337
+ } else if (!this._isServer) throw new TypeError(`Invalid value for parameter "${key}": ${value}`);
338
+ } else if (key === "server_max_window_bits") {
339
+ const num = +value;
340
+ if (!Number.isInteger(num) || num < 8 || num > 15) throw new TypeError(`Invalid value for parameter "${key}": ${value}`);
341
+ value = num;
342
+ } else if (key === "client_no_context_takeover" || key === "server_no_context_takeover") {
343
+ if (value !== true) throw new TypeError(`Invalid value for parameter "${key}": ${value}`);
344
+ } else throw new Error(`Unknown parameter "${key}"`);
345
+ params[key] = value;
346
+ });
347
+ });
348
+ return configurations;
349
+ }
350
+ /**
351
+ * Decompress data. Concurrency limited.
352
+ *
353
+ * @param {Buffer} data Compressed data
354
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
355
+ * @param {Function} callback Callback
356
+ * @public
357
+ */
358
+ decompress(data, fin, callback) {
359
+ zlibLimiter.add((done) => {
360
+ this._decompress(data, fin, (err, result) => {
361
+ done();
362
+ callback(err, result);
363
+ });
364
+ });
365
+ }
366
+ /**
367
+ * Compress data. Concurrency limited.
368
+ *
369
+ * @param {(Buffer|String)} data Data to compress
370
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
371
+ * @param {Function} callback Callback
372
+ * @public
373
+ */
374
+ compress(data, fin, callback) {
375
+ zlibLimiter.add((done) => {
376
+ this._compress(data, fin, (err, result) => {
377
+ done();
378
+ callback(err, result);
379
+ });
380
+ });
381
+ }
382
+ /**
383
+ * Decompress data.
384
+ *
385
+ * @param {Buffer} data Compressed data
386
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
387
+ * @param {Function} callback Callback
388
+ * @private
389
+ */
390
+ _decompress(data, fin, callback) {
391
+ const endpoint = this._isServer ? "client" : "server";
392
+ if (!this._inflate) {
393
+ const key = `${endpoint}_max_window_bits`;
394
+ const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
395
+ this._inflate = zlib.createInflateRaw({
396
+ ...this._options.zlibInflateOptions,
397
+ windowBits
398
+ });
399
+ this._inflate[kPerMessageDeflate] = this;
400
+ this._inflate[kTotalLength] = 0;
401
+ this._inflate[kBuffers] = [];
402
+ this._inflate.on("error", inflateOnError);
403
+ this._inflate.on("data", inflateOnData);
404
+ }
405
+ this._inflate[kCallback] = callback;
406
+ this._inflate.write(data);
407
+ if (fin) this._inflate.write(TRAILER);
408
+ this._inflate.flush(() => {
409
+ const err = this._inflate[kError];
410
+ if (err) {
411
+ this._inflate.close();
412
+ this._inflate = null;
413
+ callback(err);
414
+ return;
415
+ }
416
+ const data = bufferUtil.concat(this._inflate[kBuffers], this._inflate[kTotalLength]);
417
+ if (this._inflate._readableState.endEmitted) {
418
+ this._inflate.close();
419
+ this._inflate = null;
420
+ } else {
421
+ this._inflate[kTotalLength] = 0;
422
+ this._inflate[kBuffers] = [];
423
+ if (fin && this.params[`${endpoint}_no_context_takeover`]) this._inflate.reset();
424
+ }
425
+ callback(null, data);
426
+ });
427
+ }
428
+ /**
429
+ * Compress data.
430
+ *
431
+ * @param {(Buffer|String)} data Data to compress
432
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
433
+ * @param {Function} callback Callback
434
+ * @private
435
+ */
436
+ _compress(data, fin, callback) {
437
+ const endpoint = this._isServer ? "server" : "client";
438
+ if (!this._deflate) {
439
+ const key = `${endpoint}_max_window_bits`;
440
+ const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
441
+ this._deflate = zlib.createDeflateRaw({
442
+ ...this._options.zlibDeflateOptions,
443
+ windowBits
444
+ });
445
+ this._deflate[kTotalLength] = 0;
446
+ this._deflate[kBuffers] = [];
447
+ this._deflate.on("data", deflateOnData);
448
+ }
449
+ this._deflate[kCallback] = callback;
450
+ this._deflate.write(data);
451
+ this._deflate.flush(zlib.Z_SYNC_FLUSH, () => {
452
+ if (!this._deflate) return;
453
+ let data = bufferUtil.concat(this._deflate[kBuffers], this._deflate[kTotalLength]);
454
+ if (fin) data = new FastBuffer(data.buffer, data.byteOffset, data.length - 4);
455
+ this._deflate[kCallback] = null;
456
+ this._deflate[kTotalLength] = 0;
457
+ this._deflate[kBuffers] = [];
458
+ if (fin && this.params[`${endpoint}_no_context_takeover`]) this._deflate.reset();
459
+ callback(null, data);
460
+ });
461
+ }
462
+ };
463
+ module.exports = PerMessageDeflate;
464
+ /**
465
+ * The listener of the `zlib.DeflateRaw` stream `'data'` event.
466
+ *
467
+ * @param {Buffer} chunk A chunk of data
468
+ * @private
469
+ */
470
+ function deflateOnData(chunk) {
471
+ this[kBuffers].push(chunk);
472
+ this[kTotalLength] += chunk.length;
473
+ }
474
+ /**
475
+ * The listener of the `zlib.InflateRaw` stream `'data'` event.
476
+ *
477
+ * @param {Buffer} chunk A chunk of data
478
+ * @private
479
+ */
480
+ function inflateOnData(chunk) {
481
+ this[kTotalLength] += chunk.length;
482
+ if (this[kPerMessageDeflate]._maxPayload < 1 || this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload) {
483
+ this[kBuffers].push(chunk);
484
+ return;
485
+ }
486
+ this[kError] = /* @__PURE__ */ new RangeError("Max payload size exceeded");
487
+ this[kError].code = "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH";
488
+ this[kError][kStatusCode] = 1009;
489
+ this.removeListener("data", inflateOnData);
490
+ this.reset();
491
+ }
492
+ /**
493
+ * The listener of the `zlib.InflateRaw` stream `'error'` event.
494
+ *
495
+ * @param {Error} err The emitted error
496
+ * @private
497
+ */
498
+ function inflateOnError(err) {
499
+ this[kPerMessageDeflate]._inflate = null;
500
+ if (this[kError]) {
501
+ this[kCallback](this[kError]);
502
+ return;
503
+ }
504
+ err[kStatusCode] = 1007;
505
+ this[kCallback](err);
506
+ }
507
+ }));
508
+ //#endregion
509
+ //#region node_modules/ws/lib/validation.js
510
+ var require_validation = /* @__PURE__ */ __commonJSMin(((exports, module) => {
511
+ const { isUtf8 } = __require("buffer");
512
+ const { hasBlob } = require_constants();
513
+ const tokenChars = [
514
+ 0,
515
+ 0,
516
+ 0,
517
+ 0,
518
+ 0,
519
+ 0,
520
+ 0,
521
+ 0,
522
+ 0,
523
+ 0,
524
+ 0,
525
+ 0,
526
+ 0,
527
+ 0,
528
+ 0,
529
+ 0,
530
+ 0,
531
+ 0,
532
+ 0,
533
+ 0,
534
+ 0,
535
+ 0,
536
+ 0,
537
+ 0,
538
+ 0,
539
+ 0,
540
+ 0,
541
+ 0,
542
+ 0,
543
+ 0,
544
+ 0,
545
+ 0,
546
+ 0,
547
+ 1,
548
+ 0,
549
+ 1,
550
+ 1,
551
+ 1,
552
+ 1,
553
+ 1,
554
+ 0,
555
+ 0,
556
+ 1,
557
+ 1,
558
+ 0,
559
+ 1,
560
+ 1,
561
+ 0,
562
+ 1,
563
+ 1,
564
+ 1,
565
+ 1,
566
+ 1,
567
+ 1,
568
+ 1,
569
+ 1,
570
+ 1,
571
+ 1,
572
+ 0,
573
+ 0,
574
+ 0,
575
+ 0,
576
+ 0,
577
+ 0,
578
+ 0,
579
+ 1,
580
+ 1,
581
+ 1,
582
+ 1,
583
+ 1,
584
+ 1,
585
+ 1,
586
+ 1,
587
+ 1,
588
+ 1,
589
+ 1,
590
+ 1,
591
+ 1,
592
+ 1,
593
+ 1,
594
+ 1,
595
+ 1,
596
+ 1,
597
+ 1,
598
+ 1,
599
+ 1,
600
+ 1,
601
+ 1,
602
+ 1,
603
+ 1,
604
+ 1,
605
+ 0,
606
+ 0,
607
+ 0,
608
+ 1,
609
+ 1,
610
+ 1,
611
+ 1,
612
+ 1,
613
+ 1,
614
+ 1,
615
+ 1,
616
+ 1,
617
+ 1,
618
+ 1,
619
+ 1,
620
+ 1,
621
+ 1,
622
+ 1,
623
+ 1,
624
+ 1,
625
+ 1,
626
+ 1,
627
+ 1,
628
+ 1,
629
+ 1,
630
+ 1,
631
+ 1,
632
+ 1,
633
+ 1,
634
+ 1,
635
+ 1,
636
+ 1,
637
+ 0,
638
+ 1,
639
+ 0,
640
+ 1,
641
+ 0
642
+ ];
643
+ /**
644
+ * Checks if a status code is allowed in a close frame.
645
+ *
646
+ * @param {Number} code The status code
647
+ * @return {Boolean} `true` if the status code is valid, else `false`
648
+ * @public
649
+ */
650
+ function isValidStatusCode(code) {
651
+ return code >= 1e3 && code <= 1014 && code !== 1004 && code !== 1005 && code !== 1006 || code >= 3e3 && code <= 4999;
652
+ }
653
+ /**
654
+ * Checks if a given buffer contains only correct UTF-8.
655
+ * Ported from https://www.cl.cam.ac.uk/%7Emgk25/ucs/utf8_check.c by
656
+ * Markus Kuhn.
657
+ *
658
+ * @param {Buffer} buf The buffer to check
659
+ * @return {Boolean} `true` if `buf` contains only correct UTF-8, else `false`
660
+ * @public
661
+ */
662
+ function _isValidUTF8(buf) {
663
+ const len = buf.length;
664
+ let i = 0;
665
+ while (i < len) if ((buf[i] & 128) === 0) i++;
666
+ else if ((buf[i] & 224) === 192) {
667
+ if (i + 1 === len || (buf[i + 1] & 192) !== 128 || (buf[i] & 254) === 192) return false;
668
+ i += 2;
669
+ } else if ((buf[i] & 240) === 224) {
670
+ if (i + 2 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || buf[i] === 224 && (buf[i + 1] & 224) === 128 || buf[i] === 237 && (buf[i + 1] & 224) === 160) return false;
671
+ i += 3;
672
+ } else if ((buf[i] & 248) === 240) {
673
+ if (i + 3 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || (buf[i + 3] & 192) !== 128 || buf[i] === 240 && (buf[i + 1] & 240) === 128 || buf[i] === 244 && buf[i + 1] > 143 || buf[i] > 244) return false;
674
+ i += 4;
675
+ } else return false;
676
+ return true;
677
+ }
678
+ /**
679
+ * Determines whether a value is a `Blob`.
680
+ *
681
+ * @param {*} value The value to be tested
682
+ * @return {Boolean} `true` if `value` is a `Blob`, else `false`
683
+ * @private
684
+ */
685
+ function isBlob(value) {
686
+ return hasBlob && typeof value === "object" && typeof value.arrayBuffer === "function" && typeof value.type === "string" && typeof value.stream === "function" && (value[Symbol.toStringTag] === "Blob" || value[Symbol.toStringTag] === "File");
687
+ }
688
+ module.exports = {
689
+ isBlob,
690
+ isValidStatusCode,
691
+ isValidUTF8: _isValidUTF8,
692
+ tokenChars
693
+ };
694
+ if (isUtf8) module.exports.isValidUTF8 = function(buf) {
695
+ return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf);
696
+ };
697
+ else if (!process.env.WS_NO_UTF_8_VALIDATE) try {
698
+ const isValidUTF8 = __require("utf-8-validate");
699
+ module.exports.isValidUTF8 = function(buf) {
700
+ return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf);
701
+ };
702
+ } catch (e) {}
703
+ }));
704
+ //#endregion
705
+ //#region node_modules/ws/lib/receiver.js
706
+ var require_receiver = /* @__PURE__ */ __commonJSMin(((exports, module) => {
707
+ const { Writable } = __require("stream");
708
+ const PerMessageDeflate = require_permessage_deflate();
709
+ const { BINARY_TYPES, EMPTY_BUFFER, kStatusCode, kWebSocket } = require_constants();
710
+ const { concat, toArrayBuffer, unmask } = require_buffer_util();
711
+ const { isValidStatusCode, isValidUTF8 } = require_validation();
712
+ const FastBuffer = Buffer[Symbol.species];
713
+ const GET_INFO = 0;
714
+ const GET_PAYLOAD_LENGTH_16 = 1;
715
+ const GET_PAYLOAD_LENGTH_64 = 2;
716
+ const GET_MASK = 3;
717
+ const GET_DATA = 4;
718
+ const INFLATING = 5;
719
+ const DEFER_EVENT = 6;
720
+ /**
721
+ * HyBi Receiver implementation.
722
+ *
723
+ * @extends Writable
724
+ */
725
+ var Receiver = class extends Writable {
726
+ /**
727
+ * Creates a Receiver instance.
728
+ *
729
+ * @param {Object} [options] Options object
730
+ * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
731
+ * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
732
+ * multiple times in the same tick
733
+ * @param {String} [options.binaryType=nodebuffer] The type for binary data
734
+ * @param {Object} [options.extensions] An object containing the negotiated
735
+ * extensions
736
+ * @param {Boolean} [options.isServer=false] Specifies whether to operate in
737
+ * client or server mode
738
+ * @param {Number} [options.maxBufferedChunks=0] The maximum number of
739
+ * buffered data chunks
740
+ * @param {Number} [options.maxFragments=0] The maximum number of message
741
+ * fragments
742
+ * @param {Number} [options.maxPayload=0] The maximum allowed message length
743
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
744
+ * not to skip UTF-8 validation for text and close messages
745
+ */
746
+ constructor(options = {}) {
747
+ super();
748
+ this._allowSynchronousEvents = options.allowSynchronousEvents !== void 0 ? options.allowSynchronousEvents : true;
749
+ this._binaryType = options.binaryType || BINARY_TYPES[0];
750
+ this._extensions = options.extensions || {};
751
+ this._isServer = !!options.isServer;
752
+ this._maxBufferedChunks = options.maxBufferedChunks | 0;
753
+ this._maxFragments = options.maxFragments | 0;
754
+ this._maxPayload = options.maxPayload | 0;
755
+ this._skipUTF8Validation = !!options.skipUTF8Validation;
756
+ this[kWebSocket] = void 0;
757
+ this._bufferedBytes = 0;
758
+ this._buffers = [];
759
+ this._compressed = false;
760
+ this._payloadLength = 0;
761
+ this._mask = void 0;
762
+ this._fragmented = 0;
763
+ this._masked = false;
764
+ this._fin = false;
765
+ this._opcode = 0;
766
+ this._totalPayloadLength = 0;
767
+ this._messageLength = 0;
768
+ this._fragments = [];
769
+ this._errored = false;
770
+ this._loop = false;
771
+ this._state = GET_INFO;
772
+ }
773
+ /**
774
+ * Implements `Writable.prototype._write()`.
775
+ *
776
+ * @param {Buffer} chunk The chunk of data to write
777
+ * @param {String} encoding The character encoding of `chunk`
778
+ * @param {Function} cb Callback
779
+ * @private
780
+ */
781
+ _write(chunk, encoding, cb) {
782
+ if (this._opcode === 8 && this._state == GET_INFO) return cb();
783
+ if (this._maxBufferedChunks > 0 && this._buffers.length >= this._maxBufferedChunks) {
784
+ cb(this.createError(RangeError, "Too many buffered chunks", false, 1008, "WS_ERR_TOO_MANY_BUFFERED_PARTS"));
785
+ return;
786
+ }
787
+ this._bufferedBytes += chunk.length;
788
+ this._buffers.push(chunk);
789
+ this.startLoop(cb);
790
+ }
791
+ /**
792
+ * Consumes `n` bytes from the buffered data.
793
+ *
794
+ * @param {Number} n The number of bytes to consume
795
+ * @return {Buffer} The consumed bytes
796
+ * @private
797
+ */
798
+ consume(n) {
799
+ this._bufferedBytes -= n;
800
+ if (n === this._buffers[0].length) return this._buffers.shift();
801
+ if (n < this._buffers[0].length) {
802
+ const buf = this._buffers[0];
803
+ this._buffers[0] = new FastBuffer(buf.buffer, buf.byteOffset + n, buf.length - n);
804
+ return new FastBuffer(buf.buffer, buf.byteOffset, n);
805
+ }
806
+ const dst = Buffer.allocUnsafe(n);
807
+ do {
808
+ const buf = this._buffers[0];
809
+ const offset = dst.length - n;
810
+ if (n >= buf.length) dst.set(this._buffers.shift(), offset);
811
+ else {
812
+ dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset);
813
+ this._buffers[0] = new FastBuffer(buf.buffer, buf.byteOffset + n, buf.length - n);
814
+ }
815
+ n -= buf.length;
816
+ } while (n > 0);
817
+ return dst;
818
+ }
819
+ /**
820
+ * Starts the parsing loop.
821
+ *
822
+ * @param {Function} cb Callback
823
+ * @private
824
+ */
825
+ startLoop(cb) {
826
+ this._loop = true;
827
+ do
828
+ switch (this._state) {
829
+ case GET_INFO:
830
+ this.getInfo(cb);
831
+ break;
832
+ case GET_PAYLOAD_LENGTH_16:
833
+ this.getPayloadLength16(cb);
834
+ break;
835
+ case GET_PAYLOAD_LENGTH_64:
836
+ this.getPayloadLength64(cb);
837
+ break;
838
+ case GET_MASK:
839
+ this.getMask();
840
+ break;
841
+ case GET_DATA:
842
+ this.getData(cb);
843
+ break;
844
+ case INFLATING:
845
+ case DEFER_EVENT:
846
+ this._loop = false;
847
+ return;
848
+ }
849
+ while (this._loop);
850
+ if (!this._errored) cb();
851
+ }
852
+ /**
853
+ * Reads the first two bytes of a frame.
854
+ *
855
+ * @param {Function} cb Callback
856
+ * @private
857
+ */
858
+ getInfo(cb) {
859
+ if (this._bufferedBytes < 2) {
860
+ this._loop = false;
861
+ return;
862
+ }
863
+ const buf = this.consume(2);
864
+ if ((buf[0] & 48) !== 0) {
865
+ cb(this.createError(RangeError, "RSV2 and RSV3 must be clear", true, 1002, "WS_ERR_UNEXPECTED_RSV_2_3"));
866
+ return;
867
+ }
868
+ const compressed = (buf[0] & 64) === 64;
869
+ if (compressed && !this._extensions[PerMessageDeflate.extensionName]) {
870
+ cb(this.createError(RangeError, "RSV1 must be clear", true, 1002, "WS_ERR_UNEXPECTED_RSV_1"));
871
+ return;
872
+ }
873
+ this._fin = (buf[0] & 128) === 128;
874
+ this._opcode = buf[0] & 15;
875
+ this._payloadLength = buf[1] & 127;
876
+ if (this._opcode === 0) {
877
+ if (compressed) {
878
+ cb(this.createError(RangeError, "RSV1 must be clear", true, 1002, "WS_ERR_UNEXPECTED_RSV_1"));
879
+ return;
880
+ }
881
+ if (!this._fragmented) {
882
+ cb(this.createError(RangeError, "invalid opcode 0", true, 1002, "WS_ERR_INVALID_OPCODE"));
883
+ return;
884
+ }
885
+ this._opcode = this._fragmented;
886
+ } else if (this._opcode === 1 || this._opcode === 2) {
887
+ if (this._fragmented) {
888
+ cb(this.createError(RangeError, `invalid opcode ${this._opcode}`, true, 1002, "WS_ERR_INVALID_OPCODE"));
889
+ return;
890
+ }
891
+ this._compressed = compressed;
892
+ } else if (this._opcode > 7 && this._opcode < 11) {
893
+ if (!this._fin) {
894
+ cb(this.createError(RangeError, "FIN must be set", true, 1002, "WS_ERR_EXPECTED_FIN"));
895
+ return;
896
+ }
897
+ if (compressed) {
898
+ cb(this.createError(RangeError, "RSV1 must be clear", true, 1002, "WS_ERR_UNEXPECTED_RSV_1"));
899
+ return;
900
+ }
901
+ if (this._payloadLength > 125 || this._opcode === 8 && this._payloadLength === 1) {
902
+ cb(this.createError(RangeError, `invalid payload length ${this._payloadLength}`, true, 1002, "WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH"));
903
+ return;
904
+ }
905
+ } else {
906
+ cb(this.createError(RangeError, `invalid opcode ${this._opcode}`, true, 1002, "WS_ERR_INVALID_OPCODE"));
907
+ return;
908
+ }
909
+ if (!this._fin && !this._fragmented) this._fragmented = this._opcode;
910
+ this._masked = (buf[1] & 128) === 128;
911
+ if (this._isServer) {
912
+ if (!this._masked) {
913
+ cb(this.createError(RangeError, "MASK must be set", true, 1002, "WS_ERR_EXPECTED_MASK"));
914
+ return;
915
+ }
916
+ } else if (this._masked) {
917
+ cb(this.createError(RangeError, "MASK must be clear", true, 1002, "WS_ERR_UNEXPECTED_MASK"));
918
+ return;
919
+ }
920
+ if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16;
921
+ else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64;
922
+ else this.haveLength(cb);
923
+ }
924
+ /**
925
+ * Gets extended payload length (7+16).
926
+ *
927
+ * @param {Function} cb Callback
928
+ * @private
929
+ */
930
+ getPayloadLength16(cb) {
931
+ if (this._bufferedBytes < 2) {
932
+ this._loop = false;
933
+ return;
934
+ }
935
+ this._payloadLength = this.consume(2).readUInt16BE(0);
936
+ this.haveLength(cb);
937
+ }
938
+ /**
939
+ * Gets extended payload length (7+64).
940
+ *
941
+ * @param {Function} cb Callback
942
+ * @private
943
+ */
944
+ getPayloadLength64(cb) {
945
+ if (this._bufferedBytes < 8) {
946
+ this._loop = false;
947
+ return;
948
+ }
949
+ const buf = this.consume(8);
950
+ const num = buf.readUInt32BE(0);
951
+ if (num > Math.pow(2, 21) - 1) {
952
+ cb(this.createError(RangeError, "Unsupported WebSocket frame: payload length > 2^53 - 1", false, 1009, "WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH"));
953
+ return;
954
+ }
955
+ this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4);
956
+ this.haveLength(cb);
957
+ }
958
+ /**
959
+ * Payload length has been read.
960
+ *
961
+ * @param {Function} cb Callback
962
+ * @private
963
+ */
964
+ haveLength(cb) {
965
+ if (this._payloadLength && this._opcode < 8) {
966
+ this._totalPayloadLength += this._payloadLength;
967
+ if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) {
968
+ cb(this.createError(RangeError, "Max payload size exceeded", false, 1009, "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"));
969
+ return;
970
+ }
971
+ }
972
+ if (this._masked) this._state = GET_MASK;
973
+ else this._state = GET_DATA;
974
+ }
975
+ /**
976
+ * Reads mask bytes.
977
+ *
978
+ * @private
979
+ */
980
+ getMask() {
981
+ if (this._bufferedBytes < 4) {
982
+ this._loop = false;
983
+ return;
984
+ }
985
+ this._mask = this.consume(4);
986
+ this._state = GET_DATA;
987
+ }
988
+ /**
989
+ * Reads data bytes.
990
+ *
991
+ * @param {Function} cb Callback
992
+ * @private
993
+ */
994
+ getData(cb) {
995
+ let data = EMPTY_BUFFER;
996
+ if (this._payloadLength) {
997
+ if (this._bufferedBytes < this._payloadLength) {
998
+ this._loop = false;
999
+ return;
1000
+ }
1001
+ data = this.consume(this._payloadLength);
1002
+ if (this._masked && (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0) unmask(data, this._mask);
1003
+ }
1004
+ if (this._opcode > 7) {
1005
+ this.controlMessage(data, cb);
1006
+ return;
1007
+ }
1008
+ if (this._compressed) {
1009
+ this._state = INFLATING;
1010
+ this.decompress(data, cb);
1011
+ return;
1012
+ }
1013
+ if (data.length) {
1014
+ if (this._maxFragments > 0 && this._fragments.length >= this._maxFragments) {
1015
+ cb(this.createError(RangeError, "Too many message fragments", false, 1008, "WS_ERR_TOO_MANY_BUFFERED_PARTS"));
1016
+ return;
1017
+ }
1018
+ this._messageLength = this._totalPayloadLength;
1019
+ this._fragments.push(data);
1020
+ }
1021
+ this.dataMessage(cb);
1022
+ }
1023
+ /**
1024
+ * Decompresses data.
1025
+ *
1026
+ * @param {Buffer} data Compressed data
1027
+ * @param {Function} cb Callback
1028
+ * @private
1029
+ */
1030
+ decompress(data, cb) {
1031
+ this._extensions[PerMessageDeflate.extensionName].decompress(data, this._fin, (err, buf) => {
1032
+ if (err) return cb(err);
1033
+ if (buf.length) {
1034
+ this._messageLength += buf.length;
1035
+ if (this._messageLength > this._maxPayload && this._maxPayload > 0) {
1036
+ cb(this.createError(RangeError, "Max payload size exceeded", false, 1009, "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"));
1037
+ return;
1038
+ }
1039
+ if (this._maxFragments > 0 && this._fragments.length >= this._maxFragments) {
1040
+ cb(this.createError(RangeError, "Too many message fragments", false, 1008, "WS_ERR_TOO_MANY_BUFFERED_PARTS"));
1041
+ return;
1042
+ }
1043
+ this._fragments.push(buf);
1044
+ }
1045
+ this.dataMessage(cb);
1046
+ if (this._state === GET_INFO) this.startLoop(cb);
1047
+ });
1048
+ }
1049
+ /**
1050
+ * Handles a data message.
1051
+ *
1052
+ * @param {Function} cb Callback
1053
+ * @private
1054
+ */
1055
+ dataMessage(cb) {
1056
+ if (!this._fin) {
1057
+ this._state = GET_INFO;
1058
+ return;
1059
+ }
1060
+ const messageLength = this._messageLength;
1061
+ const fragments = this._fragments;
1062
+ this._totalPayloadLength = 0;
1063
+ this._messageLength = 0;
1064
+ this._fragmented = 0;
1065
+ this._fragments = [];
1066
+ if (this._opcode === 2) {
1067
+ let data;
1068
+ if (this._binaryType === "nodebuffer") data = concat(fragments, messageLength);
1069
+ else if (this._binaryType === "arraybuffer") data = toArrayBuffer(concat(fragments, messageLength));
1070
+ else if (this._binaryType === "blob") data = new Blob(fragments);
1071
+ else data = fragments;
1072
+ if (this._allowSynchronousEvents) {
1073
+ this.emit("message", data, true);
1074
+ this._state = GET_INFO;
1075
+ } else {
1076
+ this._state = DEFER_EVENT;
1077
+ setImmediate(() => {
1078
+ this.emit("message", data, true);
1079
+ this._state = GET_INFO;
1080
+ this.startLoop(cb);
1081
+ });
1082
+ }
1083
+ } else {
1084
+ const buf = concat(fragments, messageLength);
1085
+ if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
1086
+ cb(this.createError(Error, "invalid UTF-8 sequence", true, 1007, "WS_ERR_INVALID_UTF8"));
1087
+ return;
1088
+ }
1089
+ if (this._state === INFLATING || this._allowSynchronousEvents) {
1090
+ this.emit("message", buf, false);
1091
+ this._state = GET_INFO;
1092
+ } else {
1093
+ this._state = DEFER_EVENT;
1094
+ setImmediate(() => {
1095
+ this.emit("message", buf, false);
1096
+ this._state = GET_INFO;
1097
+ this.startLoop(cb);
1098
+ });
1099
+ }
1100
+ }
1101
+ }
1102
+ /**
1103
+ * Handles a control message.
1104
+ *
1105
+ * @param {Buffer} data Data to handle
1106
+ * @return {(Error|RangeError|undefined)} A possible error
1107
+ * @private
1108
+ */
1109
+ controlMessage(data, cb) {
1110
+ if (this._opcode === 8) {
1111
+ if (data.length === 0) {
1112
+ this._loop = false;
1113
+ this.emit("conclude", 1005, EMPTY_BUFFER);
1114
+ this.end();
1115
+ } else {
1116
+ const code = data.readUInt16BE(0);
1117
+ if (!isValidStatusCode(code)) {
1118
+ cb(this.createError(RangeError, `invalid status code ${code}`, true, 1002, "WS_ERR_INVALID_CLOSE_CODE"));
1119
+ return;
1120
+ }
1121
+ const buf = new FastBuffer(data.buffer, data.byteOffset + 2, data.length - 2);
1122
+ if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
1123
+ cb(this.createError(Error, "invalid UTF-8 sequence", true, 1007, "WS_ERR_INVALID_UTF8"));
1124
+ return;
1125
+ }
1126
+ this._loop = false;
1127
+ this.emit("conclude", code, buf);
1128
+ this.end();
1129
+ }
1130
+ this._state = GET_INFO;
1131
+ return;
1132
+ }
1133
+ if (this._allowSynchronousEvents) {
1134
+ this.emit(this._opcode === 9 ? "ping" : "pong", data);
1135
+ this._state = GET_INFO;
1136
+ } else {
1137
+ this._state = DEFER_EVENT;
1138
+ setImmediate(() => {
1139
+ this.emit(this._opcode === 9 ? "ping" : "pong", data);
1140
+ this._state = GET_INFO;
1141
+ this.startLoop(cb);
1142
+ });
1143
+ }
1144
+ }
1145
+ /**
1146
+ * Builds an error object.
1147
+ *
1148
+ * @param {function(new:Error|RangeError)} ErrorCtor The error constructor
1149
+ * @param {String} message The error message
1150
+ * @param {Boolean} prefix Specifies whether or not to add a default prefix to
1151
+ * `message`
1152
+ * @param {Number} statusCode The status code
1153
+ * @param {String} errorCode The exposed error code
1154
+ * @return {(Error|RangeError)} The error
1155
+ * @private
1156
+ */
1157
+ createError(ErrorCtor, message, prefix, statusCode, errorCode) {
1158
+ this._loop = false;
1159
+ this._errored = true;
1160
+ const err = new ErrorCtor(prefix ? `Invalid WebSocket frame: ${message}` : message);
1161
+ Error.captureStackTrace(err, this.createError);
1162
+ err.code = errorCode;
1163
+ err[kStatusCode] = statusCode;
1164
+ return err;
1165
+ }
1166
+ };
1167
+ module.exports = Receiver;
1168
+ }));
1169
+ //#endregion
1170
+ //#region node_modules/ws/lib/sender.js
1171
+ var require_sender = /* @__PURE__ */ __commonJSMin(((exports, module) => {
1172
+ const { Duplex: Duplex$3 } = __require("stream");
1173
+ const { randomFillSync } = __require("crypto");
1174
+ const { types: { isUint8Array } } = __require("util");
1175
+ const PerMessageDeflate = require_permessage_deflate();
1176
+ const { EMPTY_BUFFER, kWebSocket, NOOP } = require_constants();
1177
+ const { isBlob, isValidStatusCode } = require_validation();
1178
+ const { mask: applyMask, toBuffer } = require_buffer_util();
1179
+ const kByteLength = Symbol("kByteLength");
1180
+ const maskBuffer = Buffer.alloc(4);
1181
+ const RANDOM_POOL_SIZE = 8 * 1024;
1182
+ let randomPool;
1183
+ let randomPoolPointer = RANDOM_POOL_SIZE;
1184
+ const DEFAULT = 0;
1185
+ const DEFLATING = 1;
1186
+ const GET_BLOB_DATA = 2;
1187
+ module.exports = class Sender {
1188
+ /**
1189
+ * Creates a Sender instance.
1190
+ *
1191
+ * @param {Duplex} socket The connection socket
1192
+ * @param {Object} [extensions] An object containing the negotiated extensions
1193
+ * @param {Function} [generateMask] The function used to generate the masking
1194
+ * key
1195
+ */
1196
+ constructor(socket, extensions, generateMask) {
1197
+ this._extensions = extensions || {};
1198
+ if (generateMask) {
1199
+ this._generateMask = generateMask;
1200
+ this._maskBuffer = Buffer.alloc(4);
1201
+ }
1202
+ this._socket = socket;
1203
+ this._firstFragment = true;
1204
+ this._compress = false;
1205
+ this._bufferedBytes = 0;
1206
+ this._queue = [];
1207
+ this._state = DEFAULT;
1208
+ this.onerror = NOOP;
1209
+ this[kWebSocket] = void 0;
1210
+ }
1211
+ /**
1212
+ * Frames a piece of data according to the HyBi WebSocket protocol.
1213
+ *
1214
+ * @param {(Buffer|String)} data The data to frame
1215
+ * @param {Object} options Options object
1216
+ * @param {Boolean} [options.fin=false] Specifies whether or not to set the
1217
+ * FIN bit
1218
+ * @param {Function} [options.generateMask] The function used to generate the
1219
+ * masking key
1220
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1221
+ * `data`
1222
+ * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
1223
+ * key
1224
+ * @param {Number} options.opcode The opcode
1225
+ * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
1226
+ * modified
1227
+ * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
1228
+ * RSV1 bit
1229
+ * @return {(Buffer|String)[]} The framed data
1230
+ * @public
1231
+ */
1232
+ static frame(data, options) {
1233
+ let mask;
1234
+ let merge = false;
1235
+ let offset = 2;
1236
+ let skipMasking = false;
1237
+ if (options.mask) {
1238
+ mask = options.maskBuffer || maskBuffer;
1239
+ if (options.generateMask) options.generateMask(mask);
1240
+ else {
1241
+ if (randomPoolPointer === RANDOM_POOL_SIZE) {
1242
+ /* istanbul ignore else */
1243
+ if (randomPool === void 0) randomPool = Buffer.alloc(RANDOM_POOL_SIZE);
1244
+ randomFillSync(randomPool, 0, RANDOM_POOL_SIZE);
1245
+ randomPoolPointer = 0;
1246
+ }
1247
+ mask[0] = randomPool[randomPoolPointer++];
1248
+ mask[1] = randomPool[randomPoolPointer++];
1249
+ mask[2] = randomPool[randomPoolPointer++];
1250
+ mask[3] = randomPool[randomPoolPointer++];
1251
+ }
1252
+ skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0;
1253
+ offset = 6;
1254
+ }
1255
+ let dataLength;
1256
+ if (typeof data === "string") if ((!options.mask || skipMasking) && options[kByteLength] !== void 0) dataLength = options[kByteLength];
1257
+ else {
1258
+ data = Buffer.from(data);
1259
+ dataLength = data.length;
1260
+ }
1261
+ else {
1262
+ dataLength = data.length;
1263
+ merge = options.mask && options.readOnly && !skipMasking;
1264
+ }
1265
+ let payloadLength = dataLength;
1266
+ if (dataLength >= 65536) {
1267
+ offset += 8;
1268
+ payloadLength = 127;
1269
+ } else if (dataLength > 125) {
1270
+ offset += 2;
1271
+ payloadLength = 126;
1272
+ }
1273
+ const target = Buffer.allocUnsafe(merge ? dataLength + offset : offset);
1274
+ target[0] = options.fin ? options.opcode | 128 : options.opcode;
1275
+ if (options.rsv1) target[0] |= 64;
1276
+ target[1] = payloadLength;
1277
+ if (payloadLength === 126) target.writeUInt16BE(dataLength, 2);
1278
+ else if (payloadLength === 127) {
1279
+ target[2] = target[3] = 0;
1280
+ target.writeUIntBE(dataLength, 4, 6);
1281
+ }
1282
+ if (!options.mask) return [target, data];
1283
+ target[1] |= 128;
1284
+ target[offset - 4] = mask[0];
1285
+ target[offset - 3] = mask[1];
1286
+ target[offset - 2] = mask[2];
1287
+ target[offset - 1] = mask[3];
1288
+ if (skipMasking) return [target, data];
1289
+ if (merge) {
1290
+ applyMask(data, mask, target, offset, dataLength);
1291
+ return [target];
1292
+ }
1293
+ applyMask(data, mask, data, 0, dataLength);
1294
+ return [target, data];
1295
+ }
1296
+ /**
1297
+ * Sends a close message to the other peer.
1298
+ *
1299
+ * @param {Number} [code] The status code component of the body
1300
+ * @param {(String|Buffer)} [data] The message component of the body
1301
+ * @param {Boolean} [mask=false] Specifies whether or not to mask the message
1302
+ * @param {Function} [cb] Callback
1303
+ * @public
1304
+ */
1305
+ close(code, data, mask, cb) {
1306
+ let buf;
1307
+ if (code === void 0) buf = EMPTY_BUFFER;
1308
+ else if (typeof code !== "number" || !isValidStatusCode(code)) throw new TypeError("First argument must be a valid error code number");
1309
+ else if (data === void 0 || !data.length) {
1310
+ buf = Buffer.allocUnsafe(2);
1311
+ buf.writeUInt16BE(code, 0);
1312
+ } else {
1313
+ const length = Buffer.byteLength(data);
1314
+ if (length > 123) throw new RangeError("The message must not be greater than 123 bytes");
1315
+ buf = Buffer.allocUnsafe(2 + length);
1316
+ buf.writeUInt16BE(code, 0);
1317
+ if (typeof data === "string") buf.write(data, 2);
1318
+ else if (isUint8Array(data)) buf.set(data, 2);
1319
+ else throw new TypeError("Second argument must be a string or a Uint8Array");
1320
+ }
1321
+ const options = {
1322
+ [kByteLength]: buf.length,
1323
+ fin: true,
1324
+ generateMask: this._generateMask,
1325
+ mask,
1326
+ maskBuffer: this._maskBuffer,
1327
+ opcode: 8,
1328
+ readOnly: false,
1329
+ rsv1: false
1330
+ };
1331
+ if (this._state !== DEFAULT) this.enqueue([
1332
+ this.dispatch,
1333
+ buf,
1334
+ false,
1335
+ options,
1336
+ cb
1337
+ ]);
1338
+ else this.sendFrame(Sender.frame(buf, options), cb);
1339
+ }
1340
+ /**
1341
+ * Sends a ping message to the other peer.
1342
+ *
1343
+ * @param {*} data The message to send
1344
+ * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
1345
+ * @param {Function} [cb] Callback
1346
+ * @public
1347
+ */
1348
+ ping(data, mask, cb) {
1349
+ let byteLength;
1350
+ let readOnly;
1351
+ if (typeof data === "string") {
1352
+ byteLength = Buffer.byteLength(data);
1353
+ readOnly = false;
1354
+ } else if (isBlob(data)) {
1355
+ byteLength = data.size;
1356
+ readOnly = false;
1357
+ } else {
1358
+ data = toBuffer(data);
1359
+ byteLength = data.length;
1360
+ readOnly = toBuffer.readOnly;
1361
+ }
1362
+ if (byteLength > 125) throw new RangeError("The data size must not be greater than 125 bytes");
1363
+ const options = {
1364
+ [kByteLength]: byteLength,
1365
+ fin: true,
1366
+ generateMask: this._generateMask,
1367
+ mask,
1368
+ maskBuffer: this._maskBuffer,
1369
+ opcode: 9,
1370
+ readOnly,
1371
+ rsv1: false
1372
+ };
1373
+ if (isBlob(data)) if (this._state !== DEFAULT) this.enqueue([
1374
+ this.getBlobData,
1375
+ data,
1376
+ false,
1377
+ options,
1378
+ cb
1379
+ ]);
1380
+ else this.getBlobData(data, false, options, cb);
1381
+ else if (this._state !== DEFAULT) this.enqueue([
1382
+ this.dispatch,
1383
+ data,
1384
+ false,
1385
+ options,
1386
+ cb
1387
+ ]);
1388
+ else this.sendFrame(Sender.frame(data, options), cb);
1389
+ }
1390
+ /**
1391
+ * Sends a pong message to the other peer.
1392
+ *
1393
+ * @param {*} data The message to send
1394
+ * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
1395
+ * @param {Function} [cb] Callback
1396
+ * @public
1397
+ */
1398
+ pong(data, mask, cb) {
1399
+ let byteLength;
1400
+ let readOnly;
1401
+ if (typeof data === "string") {
1402
+ byteLength = Buffer.byteLength(data);
1403
+ readOnly = false;
1404
+ } else if (isBlob(data)) {
1405
+ byteLength = data.size;
1406
+ readOnly = false;
1407
+ } else {
1408
+ data = toBuffer(data);
1409
+ byteLength = data.length;
1410
+ readOnly = toBuffer.readOnly;
1411
+ }
1412
+ if (byteLength > 125) throw new RangeError("The data size must not be greater than 125 bytes");
1413
+ const options = {
1414
+ [kByteLength]: byteLength,
1415
+ fin: true,
1416
+ generateMask: this._generateMask,
1417
+ mask,
1418
+ maskBuffer: this._maskBuffer,
1419
+ opcode: 10,
1420
+ readOnly,
1421
+ rsv1: false
1422
+ };
1423
+ if (isBlob(data)) if (this._state !== DEFAULT) this.enqueue([
1424
+ this.getBlobData,
1425
+ data,
1426
+ false,
1427
+ options,
1428
+ cb
1429
+ ]);
1430
+ else this.getBlobData(data, false, options, cb);
1431
+ else if (this._state !== DEFAULT) this.enqueue([
1432
+ this.dispatch,
1433
+ data,
1434
+ false,
1435
+ options,
1436
+ cb
1437
+ ]);
1438
+ else this.sendFrame(Sender.frame(data, options), cb);
1439
+ }
1440
+ /**
1441
+ * Sends a data message to the other peer.
1442
+ *
1443
+ * @param {*} data The message to send
1444
+ * @param {Object} options Options object
1445
+ * @param {Boolean} [options.binary=false] Specifies whether `data` is binary
1446
+ * or text
1447
+ * @param {Boolean} [options.compress=false] Specifies whether or not to
1448
+ * compress `data`
1449
+ * @param {Boolean} [options.fin=false] Specifies whether the fragment is the
1450
+ * last one
1451
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1452
+ * `data`
1453
+ * @param {Function} [cb] Callback
1454
+ * @public
1455
+ */
1456
+ send(data, options, cb) {
1457
+ const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
1458
+ let opcode = options.binary ? 2 : 1;
1459
+ let rsv1 = options.compress;
1460
+ let byteLength;
1461
+ let readOnly;
1462
+ if (typeof data === "string") {
1463
+ byteLength = Buffer.byteLength(data);
1464
+ readOnly = false;
1465
+ } else if (isBlob(data)) {
1466
+ byteLength = data.size;
1467
+ readOnly = false;
1468
+ } else {
1469
+ data = toBuffer(data);
1470
+ byteLength = data.length;
1471
+ readOnly = toBuffer.readOnly;
1472
+ }
1473
+ if (this._firstFragment) {
1474
+ this._firstFragment = false;
1475
+ if (rsv1 && perMessageDeflate && perMessageDeflate.params[perMessageDeflate._isServer ? "server_no_context_takeover" : "client_no_context_takeover"]) rsv1 = byteLength >= perMessageDeflate._threshold;
1476
+ this._compress = rsv1;
1477
+ } else {
1478
+ rsv1 = false;
1479
+ opcode = 0;
1480
+ }
1481
+ if (options.fin) this._firstFragment = true;
1482
+ const opts = {
1483
+ [kByteLength]: byteLength,
1484
+ fin: options.fin,
1485
+ generateMask: this._generateMask,
1486
+ mask: options.mask,
1487
+ maskBuffer: this._maskBuffer,
1488
+ opcode,
1489
+ readOnly,
1490
+ rsv1
1491
+ };
1492
+ if (isBlob(data)) if (this._state !== DEFAULT) this.enqueue([
1493
+ this.getBlobData,
1494
+ data,
1495
+ this._compress,
1496
+ opts,
1497
+ cb
1498
+ ]);
1499
+ else this.getBlobData(data, this._compress, opts, cb);
1500
+ else if (this._state !== DEFAULT) this.enqueue([
1501
+ this.dispatch,
1502
+ data,
1503
+ this._compress,
1504
+ opts,
1505
+ cb
1506
+ ]);
1507
+ else this.dispatch(data, this._compress, opts, cb);
1508
+ }
1509
+ /**
1510
+ * Gets the contents of a blob as binary data.
1511
+ *
1512
+ * @param {Blob} blob The blob
1513
+ * @param {Boolean} [compress=false] Specifies whether or not to compress
1514
+ * the data
1515
+ * @param {Object} options Options object
1516
+ * @param {Boolean} [options.fin=false] Specifies whether or not to set the
1517
+ * FIN bit
1518
+ * @param {Function} [options.generateMask] The function used to generate the
1519
+ * masking key
1520
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1521
+ * `data`
1522
+ * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
1523
+ * key
1524
+ * @param {Number} options.opcode The opcode
1525
+ * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
1526
+ * modified
1527
+ * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
1528
+ * RSV1 bit
1529
+ * @param {Function} [cb] Callback
1530
+ * @private
1531
+ */
1532
+ getBlobData(blob, compress, options, cb) {
1533
+ this._bufferedBytes += options[kByteLength];
1534
+ this._state = GET_BLOB_DATA;
1535
+ blob.arrayBuffer().then((arrayBuffer) => {
1536
+ if (this._socket.destroyed) {
1537
+ const err = /* @__PURE__ */ new Error("The socket was closed while the blob was being read");
1538
+ process.nextTick(callCallbacks, this, err, cb);
1539
+ return;
1540
+ }
1541
+ this._bufferedBytes -= options[kByteLength];
1542
+ const data = toBuffer(arrayBuffer);
1543
+ if (!compress) {
1544
+ this._state = DEFAULT;
1545
+ this.sendFrame(Sender.frame(data, options), cb);
1546
+ this.dequeue();
1547
+ } else this.dispatch(data, compress, options, cb);
1548
+ }).catch((err) => {
1549
+ process.nextTick(onError, this, err, cb);
1550
+ });
1551
+ }
1552
+ /**
1553
+ * Dispatches a message.
1554
+ *
1555
+ * @param {(Buffer|String)} data The message to send
1556
+ * @param {Boolean} [compress=false] Specifies whether or not to compress
1557
+ * `data`
1558
+ * @param {Object} options Options object
1559
+ * @param {Boolean} [options.fin=false] Specifies whether or not to set the
1560
+ * FIN bit
1561
+ * @param {Function} [options.generateMask] The function used to generate the
1562
+ * masking key
1563
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1564
+ * `data`
1565
+ * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
1566
+ * key
1567
+ * @param {Number} options.opcode The opcode
1568
+ * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
1569
+ * modified
1570
+ * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
1571
+ * RSV1 bit
1572
+ * @param {Function} [cb] Callback
1573
+ * @private
1574
+ */
1575
+ dispatch(data, compress, options, cb) {
1576
+ if (!compress) {
1577
+ this.sendFrame(Sender.frame(data, options), cb);
1578
+ return;
1579
+ }
1580
+ const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
1581
+ this._bufferedBytes += options[kByteLength];
1582
+ this._state = DEFLATING;
1583
+ perMessageDeflate.compress(data, options.fin, (_, buf) => {
1584
+ if (this._socket.destroyed) {
1585
+ const err = /* @__PURE__ */ new Error("The socket was closed while data was being compressed");
1586
+ callCallbacks(this, err, cb);
1587
+ return;
1588
+ }
1589
+ this._bufferedBytes -= options[kByteLength];
1590
+ this._state = DEFAULT;
1591
+ options.readOnly = false;
1592
+ this.sendFrame(Sender.frame(buf, options), cb);
1593
+ this.dequeue();
1594
+ });
1595
+ }
1596
+ /**
1597
+ * Executes queued send operations.
1598
+ *
1599
+ * @private
1600
+ */
1601
+ dequeue() {
1602
+ while (this._state === DEFAULT && this._queue.length) {
1603
+ const params = this._queue.shift();
1604
+ this._bufferedBytes -= params[3][kByteLength];
1605
+ Reflect.apply(params[0], this, params.slice(1));
1606
+ }
1607
+ }
1608
+ /**
1609
+ * Enqueues a send operation.
1610
+ *
1611
+ * @param {Array} params Send operation parameters.
1612
+ * @private
1613
+ */
1614
+ enqueue(params) {
1615
+ this._bufferedBytes += params[3][kByteLength];
1616
+ this._queue.push(params);
1617
+ }
1618
+ /**
1619
+ * Sends a frame.
1620
+ *
1621
+ * @param {(Buffer | String)[]} list The frame to send
1622
+ * @param {Function} [cb] Callback
1623
+ * @private
1624
+ */
1625
+ sendFrame(list, cb) {
1626
+ if (list.length === 2) {
1627
+ this._socket.cork();
1628
+ this._socket.write(list[0]);
1629
+ this._socket.write(list[1], cb);
1630
+ this._socket.uncork();
1631
+ } else this._socket.write(list[0], cb);
1632
+ }
1633
+ };
1634
+ /**
1635
+ * Calls queued callbacks with an error.
1636
+ *
1637
+ * @param {Sender} sender The `Sender` instance
1638
+ * @param {Error} err The error to call the callbacks with
1639
+ * @param {Function} [cb] The first callback
1640
+ * @private
1641
+ */
1642
+ function callCallbacks(sender, err, cb) {
1643
+ if (typeof cb === "function") cb(err);
1644
+ for (let i = 0; i < sender._queue.length; i++) {
1645
+ const params = sender._queue[i];
1646
+ const callback = params[params.length - 1];
1647
+ if (typeof callback === "function") callback(err);
1648
+ }
1649
+ }
1650
+ /**
1651
+ * Handles a `Sender` error.
1652
+ *
1653
+ * @param {Sender} sender The `Sender` instance
1654
+ * @param {Error} err The error
1655
+ * @param {Function} [cb] The first pending callback
1656
+ * @private
1657
+ */
1658
+ function onError(sender, err, cb) {
1659
+ callCallbacks(sender, err, cb);
1660
+ sender.onerror(err);
1661
+ }
1662
+ }));
1663
+ //#endregion
1664
+ //#region node_modules/ws/lib/event-target.js
1665
+ var require_event_target = /* @__PURE__ */ __commonJSMin(((exports, module) => {
1666
+ const { kForOnEventAttribute, kListener } = require_constants();
1667
+ const kCode = Symbol("kCode");
1668
+ const kData = Symbol("kData");
1669
+ const kError = Symbol("kError");
1670
+ const kMessage = Symbol("kMessage");
1671
+ const kReason = Symbol("kReason");
1672
+ const kTarget = Symbol("kTarget");
1673
+ const kType = Symbol("kType");
1674
+ const kWasClean = Symbol("kWasClean");
1675
+ /**
1676
+ * Class representing an event.
1677
+ */
1678
+ var Event = class {
1679
+ /**
1680
+ * Create a new `Event`.
1681
+ *
1682
+ * @param {String} type The name of the event
1683
+ * @throws {TypeError} If the `type` argument is not specified
1684
+ */
1685
+ constructor(type) {
1686
+ this[kTarget] = null;
1687
+ this[kType] = type;
1688
+ }
1689
+ /**
1690
+ * @type {*}
1691
+ */
1692
+ get target() {
1693
+ return this[kTarget];
1694
+ }
1695
+ /**
1696
+ * @type {String}
1697
+ */
1698
+ get type() {
1699
+ return this[kType];
1700
+ }
1701
+ };
1702
+ Object.defineProperty(Event.prototype, "target", { enumerable: true });
1703
+ Object.defineProperty(Event.prototype, "type", { enumerable: true });
1704
+ /**
1705
+ * Class representing a close event.
1706
+ *
1707
+ * @extends Event
1708
+ */
1709
+ var CloseEvent = class extends Event {
1710
+ /**
1711
+ * Create a new `CloseEvent`.
1712
+ *
1713
+ * @param {String} type The name of the event
1714
+ * @param {Object} [options] A dictionary object that allows for setting
1715
+ * attributes via object members of the same name
1716
+ * @param {Number} [options.code=0] The status code explaining why the
1717
+ * connection was closed
1718
+ * @param {String} [options.reason=''] A human-readable string explaining why
1719
+ * the connection was closed
1720
+ * @param {Boolean} [options.wasClean=false] Indicates whether or not the
1721
+ * connection was cleanly closed
1722
+ */
1723
+ constructor(type, options = {}) {
1724
+ super(type);
1725
+ this[kCode] = options.code === void 0 ? 0 : options.code;
1726
+ this[kReason] = options.reason === void 0 ? "" : options.reason;
1727
+ this[kWasClean] = options.wasClean === void 0 ? false : options.wasClean;
1728
+ }
1729
+ /**
1730
+ * @type {Number}
1731
+ */
1732
+ get code() {
1733
+ return this[kCode];
1734
+ }
1735
+ /**
1736
+ * @type {String}
1737
+ */
1738
+ get reason() {
1739
+ return this[kReason];
1740
+ }
1741
+ /**
1742
+ * @type {Boolean}
1743
+ */
1744
+ get wasClean() {
1745
+ return this[kWasClean];
1746
+ }
1747
+ };
1748
+ Object.defineProperty(CloseEvent.prototype, "code", { enumerable: true });
1749
+ Object.defineProperty(CloseEvent.prototype, "reason", { enumerable: true });
1750
+ Object.defineProperty(CloseEvent.prototype, "wasClean", { enumerable: true });
1751
+ /**
1752
+ * Class representing an error event.
1753
+ *
1754
+ * @extends Event
1755
+ */
1756
+ var ErrorEvent = class extends Event {
1757
+ /**
1758
+ * Create a new `ErrorEvent`.
1759
+ *
1760
+ * @param {String} type The name of the event
1761
+ * @param {Object} [options] A dictionary object that allows for setting
1762
+ * attributes via object members of the same name
1763
+ * @param {*} [options.error=null] The error that generated this event
1764
+ * @param {String} [options.message=''] The error message
1765
+ */
1766
+ constructor(type, options = {}) {
1767
+ super(type);
1768
+ this[kError] = options.error === void 0 ? null : options.error;
1769
+ this[kMessage] = options.message === void 0 ? "" : options.message;
1770
+ }
1771
+ /**
1772
+ * @type {*}
1773
+ */
1774
+ get error() {
1775
+ return this[kError];
1776
+ }
1777
+ /**
1778
+ * @type {String}
1779
+ */
1780
+ get message() {
1781
+ return this[kMessage];
1782
+ }
1783
+ };
1784
+ Object.defineProperty(ErrorEvent.prototype, "error", { enumerable: true });
1785
+ Object.defineProperty(ErrorEvent.prototype, "message", { enumerable: true });
1786
+ /**
1787
+ * Class representing a message event.
1788
+ *
1789
+ * @extends Event
1790
+ */
1791
+ var MessageEvent = class extends Event {
1792
+ /**
1793
+ * Create a new `MessageEvent`.
1794
+ *
1795
+ * @param {String} type The name of the event
1796
+ * @param {Object} [options] A dictionary object that allows for setting
1797
+ * attributes via object members of the same name
1798
+ * @param {*} [options.data=null] The message content
1799
+ */
1800
+ constructor(type, options = {}) {
1801
+ super(type);
1802
+ this[kData] = options.data === void 0 ? null : options.data;
1803
+ }
1804
+ /**
1805
+ * @type {*}
1806
+ */
1807
+ get data() {
1808
+ return this[kData];
1809
+ }
1810
+ };
1811
+ Object.defineProperty(MessageEvent.prototype, "data", { enumerable: true });
1812
+ module.exports = {
1813
+ CloseEvent,
1814
+ ErrorEvent,
1815
+ Event,
1816
+ EventTarget: {
1817
+ /**
1818
+ * Register an event listener.
1819
+ *
1820
+ * @param {String} type A string representing the event type to listen for
1821
+ * @param {(Function|Object)} handler The listener to add
1822
+ * @param {Object} [options] An options object specifies characteristics about
1823
+ * the event listener
1824
+ * @param {Boolean} [options.once=false] A `Boolean` indicating that the
1825
+ * listener should be invoked at most once after being added. If `true`,
1826
+ * the listener would be automatically removed when invoked.
1827
+ * @public
1828
+ */
1829
+ addEventListener(type, handler, options = {}) {
1830
+ for (const listener of this.listeners(type)) if (!options[kForOnEventAttribute] && listener[kListener] === handler && !listener[kForOnEventAttribute]) return;
1831
+ let wrapper;
1832
+ if (type === "message") wrapper = function onMessage(data, isBinary) {
1833
+ const event = new MessageEvent("message", { data: isBinary ? data : data.toString() });
1834
+ event[kTarget] = this;
1835
+ callListener(handler, this, event);
1836
+ };
1837
+ else if (type === "close") wrapper = function onClose(code, message) {
1838
+ const event = new CloseEvent("close", {
1839
+ code,
1840
+ reason: message.toString(),
1841
+ wasClean: this._closeFrameReceived && this._closeFrameSent
1842
+ });
1843
+ event[kTarget] = this;
1844
+ callListener(handler, this, event);
1845
+ };
1846
+ else if (type === "error") wrapper = function onError(error) {
1847
+ const event = new ErrorEvent("error", {
1848
+ error,
1849
+ message: error.message
1850
+ });
1851
+ event[kTarget] = this;
1852
+ callListener(handler, this, event);
1853
+ };
1854
+ else if (type === "open") wrapper = function onOpen() {
1855
+ const event = new Event("open");
1856
+ event[kTarget] = this;
1857
+ callListener(handler, this, event);
1858
+ };
1859
+ else return;
1860
+ wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute];
1861
+ wrapper[kListener] = handler;
1862
+ if (options.once) this.once(type, wrapper);
1863
+ else this.on(type, wrapper);
1864
+ },
1865
+ /**
1866
+ * Remove an event listener.
1867
+ *
1868
+ * @param {String} type A string representing the event type to remove
1869
+ * @param {(Function|Object)} handler The listener to remove
1870
+ * @public
1871
+ */
1872
+ removeEventListener(type, handler) {
1873
+ for (const listener of this.listeners(type)) if (listener[kListener] === handler && !listener[kForOnEventAttribute]) {
1874
+ this.removeListener(type, listener);
1875
+ break;
1876
+ }
1877
+ }
1878
+ },
1879
+ MessageEvent
1880
+ };
1881
+ /**
1882
+ * Call an event listener
1883
+ *
1884
+ * @param {(Function|Object)} listener The listener to call
1885
+ * @param {*} thisArg The value to use as `this`` when calling the listener
1886
+ * @param {Event} event The event to pass to the listener
1887
+ * @private
1888
+ */
1889
+ function callListener(listener, thisArg, event) {
1890
+ if (typeof listener === "object" && listener.handleEvent) listener.handleEvent.call(listener, event);
1891
+ else listener.call(thisArg, event);
1892
+ }
1893
+ }));
1894
+ //#endregion
1895
+ //#region node_modules/ws/lib/extension.js
1896
+ var require_extension = /* @__PURE__ */ __commonJSMin(((exports, module) => {
1897
+ const { tokenChars } = require_validation();
1898
+ /**
1899
+ * Adds an offer to the map of extension offers or a parameter to the map of
1900
+ * parameters.
1901
+ *
1902
+ * @param {Object} dest The map of extension offers or parameters
1903
+ * @param {String} name The extension or parameter name
1904
+ * @param {(Object|Boolean|String)} elem The extension parameters or the
1905
+ * parameter value
1906
+ * @private
1907
+ */
1908
+ function push(dest, name, elem) {
1909
+ if (dest[name] === void 0) dest[name] = [elem];
1910
+ else dest[name].push(elem);
1911
+ }
1912
+ /**
1913
+ * Parses the `Sec-WebSocket-Extensions` header into an object.
1914
+ *
1915
+ * @param {String} header The field value of the header
1916
+ * @return {Object} The parsed object
1917
+ * @public
1918
+ */
1919
+ function parse(header) {
1920
+ const offers = Object.create(null);
1921
+ let params = Object.create(null);
1922
+ let mustUnescape = false;
1923
+ let isEscaping = false;
1924
+ let inQuotes = false;
1925
+ let extensionName;
1926
+ let paramName;
1927
+ let start = -1;
1928
+ let code = -1;
1929
+ let end = -1;
1930
+ let i = 0;
1931
+ for (; i < header.length; i++) {
1932
+ code = header.charCodeAt(i);
1933
+ if (extensionName === void 0) if (end === -1 && tokenChars[code] === 1) {
1934
+ if (start === -1) start = i;
1935
+ } else if (i !== 0 && (code === 32 || code === 9)) {
1936
+ if (end === -1 && start !== -1) end = i;
1937
+ } else if (code === 59 || code === 44) {
1938
+ if (start === -1) throw new SyntaxError(`Unexpected character at index ${i}`);
1939
+ if (end === -1) end = i;
1940
+ const name = header.slice(start, end);
1941
+ if (code === 44) {
1942
+ push(offers, name, params);
1943
+ params = Object.create(null);
1944
+ } else extensionName = name;
1945
+ start = end = -1;
1946
+ } else throw new SyntaxError(`Unexpected character at index ${i}`);
1947
+ else if (paramName === void 0) if (end === -1 && tokenChars[code] === 1) {
1948
+ if (start === -1) start = i;
1949
+ } else if (code === 32 || code === 9) {
1950
+ if (end === -1 && start !== -1) end = i;
1951
+ } else if (code === 59 || code === 44) {
1952
+ if (start === -1) throw new SyntaxError(`Unexpected character at index ${i}`);
1953
+ if (end === -1) end = i;
1954
+ push(params, header.slice(start, end), true);
1955
+ if (code === 44) {
1956
+ push(offers, extensionName, params);
1957
+ params = Object.create(null);
1958
+ extensionName = void 0;
1959
+ }
1960
+ start = end = -1;
1961
+ } else if (code === 61 && start !== -1 && end === -1) {
1962
+ paramName = header.slice(start, i);
1963
+ start = end = -1;
1964
+ } else throw new SyntaxError(`Unexpected character at index ${i}`);
1965
+ else if (isEscaping) {
1966
+ if (tokenChars[code] !== 1) throw new SyntaxError(`Unexpected character at index ${i}`);
1967
+ if (start === -1) start = i;
1968
+ else if (!mustUnescape) mustUnescape = true;
1969
+ isEscaping = false;
1970
+ } else if (inQuotes) if (tokenChars[code] === 1) {
1971
+ if (start === -1) start = i;
1972
+ } else if (code === 34 && start !== -1) {
1973
+ inQuotes = false;
1974
+ end = i;
1975
+ } else if (code === 92) isEscaping = true;
1976
+ else throw new SyntaxError(`Unexpected character at index ${i}`);
1977
+ else if (code === 34 && header.charCodeAt(i - 1) === 61) inQuotes = true;
1978
+ else if (end === -1 && tokenChars[code] === 1) {
1979
+ if (start === -1) start = i;
1980
+ } else if (start !== -1 && (code === 32 || code === 9)) {
1981
+ if (end === -1) end = i;
1982
+ } else if (code === 59 || code === 44) {
1983
+ if (start === -1) throw new SyntaxError(`Unexpected character at index ${i}`);
1984
+ if (end === -1) end = i;
1985
+ let value = header.slice(start, end);
1986
+ if (mustUnescape) {
1987
+ value = value.replace(/\\/g, "");
1988
+ mustUnescape = false;
1989
+ }
1990
+ push(params, paramName, value);
1991
+ if (code === 44) {
1992
+ push(offers, extensionName, params);
1993
+ params = Object.create(null);
1994
+ extensionName = void 0;
1995
+ }
1996
+ paramName = void 0;
1997
+ start = end = -1;
1998
+ } else throw new SyntaxError(`Unexpected character at index ${i}`);
1999
+ }
2000
+ if (start === -1 || inQuotes || code === 32 || code === 9) throw new SyntaxError("Unexpected end of input");
2001
+ if (end === -1) end = i;
2002
+ const token = header.slice(start, end);
2003
+ if (extensionName === void 0) push(offers, token, params);
2004
+ else {
2005
+ if (paramName === void 0) push(params, token, true);
2006
+ else if (mustUnescape) push(params, paramName, token.replace(/\\/g, ""));
2007
+ else push(params, paramName, token);
2008
+ push(offers, extensionName, params);
2009
+ }
2010
+ return offers;
2011
+ }
2012
+ /**
2013
+ * Builds the `Sec-WebSocket-Extensions` header field value.
2014
+ *
2015
+ * @param {Object} extensions The map of extensions and parameters to format
2016
+ * @return {String} A string representing the given object
2017
+ * @public
2018
+ */
2019
+ function format(extensions) {
2020
+ return Object.keys(extensions).map((extension) => {
2021
+ let configurations = extensions[extension];
2022
+ if (!Array.isArray(configurations)) configurations = [configurations];
2023
+ return configurations.map((params) => {
2024
+ return [extension].concat(Object.keys(params).map((k) => {
2025
+ let values = params[k];
2026
+ if (!Array.isArray(values)) values = [values];
2027
+ return values.map((v) => v === true ? k : `${k}=${v}`).join("; ");
2028
+ })).join("; ");
2029
+ }).join(", ");
2030
+ }).join(", ");
2031
+ }
2032
+ module.exports = {
2033
+ format,
2034
+ parse
2035
+ };
2036
+ }));
2037
+ //#endregion
2038
+ //#region node_modules/ws/lib/websocket.js
2039
+ var require_websocket = /* @__PURE__ */ __commonJSMin(((exports, module) => {
2040
+ const EventEmitter$1 = __require("events");
2041
+ const https = __require("https");
2042
+ const http$1 = __require("http");
2043
+ const net = __require("net");
2044
+ const tls = __require("tls");
2045
+ const { randomBytes, createHash: createHash$1 } = __require("crypto");
2046
+ const { Duplex: Duplex$2, Readable } = __require("stream");
2047
+ const { URL } = __require("url");
2048
+ const PerMessageDeflate = require_permessage_deflate();
2049
+ const Receiver = require_receiver();
2050
+ const Sender = require_sender();
2051
+ const { isBlob } = require_validation();
2052
+ const { BINARY_TYPES, CLOSE_TIMEOUT, EMPTY_BUFFER, GUID, kForOnEventAttribute, kListener, kStatusCode, kWebSocket, NOOP } = require_constants();
2053
+ const { EventTarget: { addEventListener, removeEventListener } } = require_event_target();
2054
+ const { format, parse } = require_extension();
2055
+ const { toBuffer } = require_buffer_util();
2056
+ const kAborted = Symbol("kAborted");
2057
+ const protocolVersions = [8, 13];
2058
+ const readyStates = [
2059
+ "CONNECTING",
2060
+ "OPEN",
2061
+ "CLOSING",
2062
+ "CLOSED"
2063
+ ];
2064
+ const subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;
2065
+ /**
2066
+ * Class representing a WebSocket.
2067
+ *
2068
+ * @extends EventEmitter
2069
+ */
2070
+ var WebSocket = class WebSocket extends EventEmitter$1 {
2071
+ /**
2072
+ * Create a new `WebSocket`.
2073
+ *
2074
+ * @param {(String|URL)} address The URL to which to connect
2075
+ * @param {(String|String[])} [protocols] The subprotocols
2076
+ * @param {Object} [options] Connection options
2077
+ */
2078
+ constructor(address, protocols, options) {
2079
+ super();
2080
+ this._binaryType = BINARY_TYPES[0];
2081
+ this._closeCode = 1006;
2082
+ this._closeFrameReceived = false;
2083
+ this._closeFrameSent = false;
2084
+ this._closeMessage = EMPTY_BUFFER;
2085
+ this._closeTimer = null;
2086
+ this._errorEmitted = false;
2087
+ this._extensions = {};
2088
+ this._paused = false;
2089
+ this._protocol = "";
2090
+ this._readyState = WebSocket.CONNECTING;
2091
+ this._receiver = null;
2092
+ this._sender = null;
2093
+ this._socket = null;
2094
+ if (address !== null) {
2095
+ this._bufferedAmount = 0;
2096
+ this._isServer = false;
2097
+ this._redirects = 0;
2098
+ if (protocols === void 0) protocols = [];
2099
+ else if (!Array.isArray(protocols)) if (typeof protocols === "object" && protocols !== null) {
2100
+ options = protocols;
2101
+ protocols = [];
2102
+ } else protocols = [protocols];
2103
+ initAsClient(this, address, protocols, options);
2104
+ } else {
2105
+ this._autoPong = options.autoPong;
2106
+ this._closeTimeout = options.closeTimeout;
2107
+ this._isServer = true;
2108
+ }
2109
+ }
2110
+ /**
2111
+ * For historical reasons, the custom "nodebuffer" type is used by the default
2112
+ * instead of "blob".
2113
+ *
2114
+ * @type {String}
2115
+ */
2116
+ get binaryType() {
2117
+ return this._binaryType;
2118
+ }
2119
+ set binaryType(type) {
2120
+ if (!BINARY_TYPES.includes(type)) return;
2121
+ this._binaryType = type;
2122
+ if (this._receiver) this._receiver._binaryType = type;
2123
+ }
2124
+ /**
2125
+ * @type {Number}
2126
+ */
2127
+ get bufferedAmount() {
2128
+ if (!this._socket) return this._bufferedAmount;
2129
+ return this._socket._writableState.length + this._sender._bufferedBytes;
2130
+ }
2131
+ /**
2132
+ * @type {String}
2133
+ */
2134
+ get extensions() {
2135
+ return Object.keys(this._extensions).join();
2136
+ }
2137
+ /**
2138
+ * @type {Boolean}
2139
+ */
2140
+ get isPaused() {
2141
+ return this._paused;
2142
+ }
2143
+ /**
2144
+ * @type {Function}
2145
+ */
2146
+ /* istanbul ignore next */
2147
+ get onclose() {
2148
+ return null;
2149
+ }
2150
+ /**
2151
+ * @type {Function}
2152
+ */
2153
+ /* istanbul ignore next */
2154
+ get onerror() {
2155
+ return null;
2156
+ }
2157
+ /**
2158
+ * @type {Function}
2159
+ */
2160
+ /* istanbul ignore next */
2161
+ get onopen() {
2162
+ return null;
2163
+ }
2164
+ /**
2165
+ * @type {Function}
2166
+ */
2167
+ /* istanbul ignore next */
2168
+ get onmessage() {
2169
+ return null;
2170
+ }
2171
+ /**
2172
+ * @type {String}
2173
+ */
2174
+ get protocol() {
2175
+ return this._protocol;
2176
+ }
2177
+ /**
2178
+ * @type {Number}
2179
+ */
2180
+ get readyState() {
2181
+ return this._readyState;
2182
+ }
2183
+ /**
2184
+ * @type {String}
2185
+ */
2186
+ get url() {
2187
+ return this._url;
2188
+ }
2189
+ /**
2190
+ * Set up the socket and the internal resources.
2191
+ *
2192
+ * @param {Duplex} socket The network socket between the server and client
2193
+ * @param {Buffer} head The first packet of the upgraded stream
2194
+ * @param {Object} options Options object
2195
+ * @param {Boolean} [options.allowSynchronousEvents=false] Specifies whether
2196
+ * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
2197
+ * multiple times in the same tick
2198
+ * @param {Function} [options.generateMask] The function used to generate the
2199
+ * masking key
2200
+ * @param {Number} [options.maxBufferedChunks=0] The maximum number of
2201
+ * buffered data chunks
2202
+ * @param {Number} [options.maxFragments=0] The maximum number of message
2203
+ * fragments
2204
+ * @param {Number} [options.maxPayload=0] The maximum allowed message size
2205
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
2206
+ * not to skip UTF-8 validation for text and close messages
2207
+ * @private
2208
+ */
2209
+ setSocket(socket, head, options) {
2210
+ const receiver = new Receiver({
2211
+ allowSynchronousEvents: options.allowSynchronousEvents,
2212
+ binaryType: this.binaryType,
2213
+ extensions: this._extensions,
2214
+ isServer: this._isServer,
2215
+ maxBufferedChunks: options.maxBufferedChunks,
2216
+ maxFragments: options.maxFragments,
2217
+ maxPayload: options.maxPayload,
2218
+ skipUTF8Validation: options.skipUTF8Validation
2219
+ });
2220
+ const sender = new Sender(socket, this._extensions, options.generateMask);
2221
+ this._receiver = receiver;
2222
+ this._sender = sender;
2223
+ this._socket = socket;
2224
+ receiver[kWebSocket] = this;
2225
+ sender[kWebSocket] = this;
2226
+ socket[kWebSocket] = this;
2227
+ receiver.on("conclude", receiverOnConclude);
2228
+ receiver.on("drain", receiverOnDrain);
2229
+ receiver.on("error", receiverOnError);
2230
+ receiver.on("message", receiverOnMessage);
2231
+ receiver.on("ping", receiverOnPing);
2232
+ receiver.on("pong", receiverOnPong);
2233
+ sender.onerror = senderOnError;
2234
+ if (socket.setTimeout) socket.setTimeout(0);
2235
+ if (socket.setNoDelay) socket.setNoDelay();
2236
+ if (head.length > 0) socket.unshift(head);
2237
+ socket.on("close", socketOnClose);
2238
+ socket.on("data", socketOnData);
2239
+ socket.on("end", socketOnEnd);
2240
+ socket.on("error", socketOnError);
2241
+ this._readyState = WebSocket.OPEN;
2242
+ this.emit("open");
2243
+ }
2244
+ /**
2245
+ * Emit the `'close'` event.
2246
+ *
2247
+ * @private
2248
+ */
2249
+ emitClose() {
2250
+ if (!this._socket) {
2251
+ this._readyState = WebSocket.CLOSED;
2252
+ this.emit("close", this._closeCode, this._closeMessage);
2253
+ return;
2254
+ }
2255
+ if (this._extensions[PerMessageDeflate.extensionName]) this._extensions[PerMessageDeflate.extensionName].cleanup();
2256
+ this._receiver.removeAllListeners();
2257
+ this._readyState = WebSocket.CLOSED;
2258
+ this.emit("close", this._closeCode, this._closeMessage);
2259
+ }
2260
+ /**
2261
+ * Start a closing handshake.
2262
+ *
2263
+ * +----------+ +-----------+ +----------+
2264
+ * - - -|ws.close()|-->|close frame|-->|ws.close()|- - -
2265
+ * | +----------+ +-----------+ +----------+ |
2266
+ * +----------+ +-----------+ |
2267
+ * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING
2268
+ * +----------+ +-----------+ |
2269
+ * | | | +---+ |
2270
+ * +------------------------+-->|fin| - - - -
2271
+ * | +---+ | +---+
2272
+ * - - - - -|fin|<---------------------+
2273
+ * +---+
2274
+ *
2275
+ * @param {Number} [code] Status code explaining why the connection is closing
2276
+ * @param {(String|Buffer)} [data] The reason why the connection is
2277
+ * closing
2278
+ * @public
2279
+ */
2280
+ close(code, data) {
2281
+ if (this.readyState === WebSocket.CLOSED) return;
2282
+ if (this.readyState === WebSocket.CONNECTING) {
2283
+ abortHandshake(this, this._req, "WebSocket was closed before the connection was established");
2284
+ return;
2285
+ }
2286
+ if (this.readyState === WebSocket.CLOSING) {
2287
+ if (this._closeFrameSent && (this._closeFrameReceived || this._receiver._writableState.errorEmitted)) this._socket.end();
2288
+ return;
2289
+ }
2290
+ this._readyState = WebSocket.CLOSING;
2291
+ this._sender.close(code, data, !this._isServer, (err) => {
2292
+ if (err) return;
2293
+ this._closeFrameSent = true;
2294
+ if (this._closeFrameReceived || this._receiver._writableState.errorEmitted) this._socket.end();
2295
+ });
2296
+ setCloseTimer(this);
2297
+ }
2298
+ /**
2299
+ * Pause the socket.
2300
+ *
2301
+ * @public
2302
+ */
2303
+ pause() {
2304
+ if (this.readyState === WebSocket.CONNECTING || this.readyState === WebSocket.CLOSED) return;
2305
+ this._paused = true;
2306
+ this._socket.pause();
2307
+ }
2308
+ /**
2309
+ * Send a ping.
2310
+ *
2311
+ * @param {*} [data] The data to send
2312
+ * @param {Boolean} [mask] Indicates whether or not to mask `data`
2313
+ * @param {Function} [cb] Callback which is executed when the ping is sent
2314
+ * @public
2315
+ */
2316
+ ping(data, mask, cb) {
2317
+ if (this.readyState === WebSocket.CONNECTING) throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
2318
+ if (typeof data === "function") {
2319
+ cb = data;
2320
+ data = mask = void 0;
2321
+ } else if (typeof mask === "function") {
2322
+ cb = mask;
2323
+ mask = void 0;
2324
+ }
2325
+ if (typeof data === "number") data = data.toString();
2326
+ if (this.readyState !== WebSocket.OPEN) {
2327
+ sendAfterClose(this, data, cb);
2328
+ return;
2329
+ }
2330
+ if (mask === void 0) mask = !this._isServer;
2331
+ this._sender.ping(data || EMPTY_BUFFER, mask, cb);
2332
+ }
2333
+ /**
2334
+ * Send a pong.
2335
+ *
2336
+ * @param {*} [data] The data to send
2337
+ * @param {Boolean} [mask] Indicates whether or not to mask `data`
2338
+ * @param {Function} [cb] Callback which is executed when the pong is sent
2339
+ * @public
2340
+ */
2341
+ pong(data, mask, cb) {
2342
+ if (this.readyState === WebSocket.CONNECTING) throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
2343
+ if (typeof data === "function") {
2344
+ cb = data;
2345
+ data = mask = void 0;
2346
+ } else if (typeof mask === "function") {
2347
+ cb = mask;
2348
+ mask = void 0;
2349
+ }
2350
+ if (typeof data === "number") data = data.toString();
2351
+ if (this.readyState !== WebSocket.OPEN) {
2352
+ sendAfterClose(this, data, cb);
2353
+ return;
2354
+ }
2355
+ if (mask === void 0) mask = !this._isServer;
2356
+ this._sender.pong(data || EMPTY_BUFFER, mask, cb);
2357
+ }
2358
+ /**
2359
+ * Resume the socket.
2360
+ *
2361
+ * @public
2362
+ */
2363
+ resume() {
2364
+ if (this.readyState === WebSocket.CONNECTING || this.readyState === WebSocket.CLOSED) return;
2365
+ this._paused = false;
2366
+ if (!this._receiver._writableState.needDrain) this._socket.resume();
2367
+ }
2368
+ /**
2369
+ * Send a data message.
2370
+ *
2371
+ * @param {*} data The message to send
2372
+ * @param {Object} [options] Options object
2373
+ * @param {Boolean} [options.binary] Specifies whether `data` is binary or
2374
+ * text
2375
+ * @param {Boolean} [options.compress] Specifies whether or not to compress
2376
+ * `data`
2377
+ * @param {Boolean} [options.fin=true] Specifies whether the fragment is the
2378
+ * last one
2379
+ * @param {Boolean} [options.mask] Specifies whether or not to mask `data`
2380
+ * @param {Function} [cb] Callback which is executed when data is written out
2381
+ * @public
2382
+ */
2383
+ send(data, options, cb) {
2384
+ if (this.readyState === WebSocket.CONNECTING) throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
2385
+ if (typeof options === "function") {
2386
+ cb = options;
2387
+ options = {};
2388
+ }
2389
+ if (typeof data === "number") data = data.toString();
2390
+ if (this.readyState !== WebSocket.OPEN) {
2391
+ sendAfterClose(this, data, cb);
2392
+ return;
2393
+ }
2394
+ const opts = {
2395
+ binary: typeof data !== "string",
2396
+ mask: !this._isServer,
2397
+ compress: true,
2398
+ fin: true,
2399
+ ...options
2400
+ };
2401
+ if (!this._extensions[PerMessageDeflate.extensionName]) opts.compress = false;
2402
+ this._sender.send(data || EMPTY_BUFFER, opts, cb);
2403
+ }
2404
+ /**
2405
+ * Forcibly close the connection.
2406
+ *
2407
+ * @public
2408
+ */
2409
+ terminate() {
2410
+ if (this.readyState === WebSocket.CLOSED) return;
2411
+ if (this.readyState === WebSocket.CONNECTING) {
2412
+ abortHandshake(this, this._req, "WebSocket was closed before the connection was established");
2413
+ return;
2414
+ }
2415
+ if (this._socket) {
2416
+ this._readyState = WebSocket.CLOSING;
2417
+ this._socket.destroy();
2418
+ }
2419
+ }
2420
+ };
2421
+ /**
2422
+ * @constant {Number} CONNECTING
2423
+ * @memberof WebSocket
2424
+ */
2425
+ Object.defineProperty(WebSocket, "CONNECTING", {
2426
+ enumerable: true,
2427
+ value: readyStates.indexOf("CONNECTING")
2428
+ });
2429
+ /**
2430
+ * @constant {Number} CONNECTING
2431
+ * @memberof WebSocket.prototype
2432
+ */
2433
+ Object.defineProperty(WebSocket.prototype, "CONNECTING", {
2434
+ enumerable: true,
2435
+ value: readyStates.indexOf("CONNECTING")
2436
+ });
2437
+ /**
2438
+ * @constant {Number} OPEN
2439
+ * @memberof WebSocket
2440
+ */
2441
+ Object.defineProperty(WebSocket, "OPEN", {
2442
+ enumerable: true,
2443
+ value: readyStates.indexOf("OPEN")
2444
+ });
2445
+ /**
2446
+ * @constant {Number} OPEN
2447
+ * @memberof WebSocket.prototype
2448
+ */
2449
+ Object.defineProperty(WebSocket.prototype, "OPEN", {
2450
+ enumerable: true,
2451
+ value: readyStates.indexOf("OPEN")
2452
+ });
2453
+ /**
2454
+ * @constant {Number} CLOSING
2455
+ * @memberof WebSocket
2456
+ */
2457
+ Object.defineProperty(WebSocket, "CLOSING", {
2458
+ enumerable: true,
2459
+ value: readyStates.indexOf("CLOSING")
2460
+ });
2461
+ /**
2462
+ * @constant {Number} CLOSING
2463
+ * @memberof WebSocket.prototype
2464
+ */
2465
+ Object.defineProperty(WebSocket.prototype, "CLOSING", {
2466
+ enumerable: true,
2467
+ value: readyStates.indexOf("CLOSING")
2468
+ });
2469
+ /**
2470
+ * @constant {Number} CLOSED
2471
+ * @memberof WebSocket
2472
+ */
2473
+ Object.defineProperty(WebSocket, "CLOSED", {
2474
+ enumerable: true,
2475
+ value: readyStates.indexOf("CLOSED")
2476
+ });
2477
+ /**
2478
+ * @constant {Number} CLOSED
2479
+ * @memberof WebSocket.prototype
2480
+ */
2481
+ Object.defineProperty(WebSocket.prototype, "CLOSED", {
2482
+ enumerable: true,
2483
+ value: readyStates.indexOf("CLOSED")
2484
+ });
2485
+ [
2486
+ "binaryType",
2487
+ "bufferedAmount",
2488
+ "extensions",
2489
+ "isPaused",
2490
+ "protocol",
2491
+ "readyState",
2492
+ "url"
2493
+ ].forEach((property) => {
2494
+ Object.defineProperty(WebSocket.prototype, property, { enumerable: true });
2495
+ });
2496
+ [
2497
+ "open",
2498
+ "error",
2499
+ "close",
2500
+ "message"
2501
+ ].forEach((method) => {
2502
+ Object.defineProperty(WebSocket.prototype, `on${method}`, {
2503
+ enumerable: true,
2504
+ get() {
2505
+ for (const listener of this.listeners(method)) if (listener[kForOnEventAttribute]) return listener[kListener];
2506
+ return null;
2507
+ },
2508
+ set(handler) {
2509
+ for (const listener of this.listeners(method)) if (listener[kForOnEventAttribute]) {
2510
+ this.removeListener(method, listener);
2511
+ break;
2512
+ }
2513
+ if (typeof handler !== "function") return;
2514
+ this.addEventListener(method, handler, { [kForOnEventAttribute]: true });
2515
+ }
2516
+ });
2517
+ });
2518
+ WebSocket.prototype.addEventListener = addEventListener;
2519
+ WebSocket.prototype.removeEventListener = removeEventListener;
2520
+ module.exports = WebSocket;
2521
+ /**
2522
+ * Initialize a WebSocket client.
2523
+ *
2524
+ * @param {WebSocket} websocket The client to initialize
2525
+ * @param {(String|URL)} address The URL to which to connect
2526
+ * @param {Array} protocols The subprotocols
2527
+ * @param {Object} [options] Connection options
2528
+ * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether any
2529
+ * of the `'message'`, `'ping'`, and `'pong'` events can be emitted multiple
2530
+ * times in the same tick
2531
+ * @param {Boolean} [options.autoPong=true] Specifies whether or not to
2532
+ * automatically send a pong in response to a ping
2533
+ * @param {Number} [options.closeTimeout=30000] Duration in milliseconds to wait
2534
+ * for the closing handshake to finish after `websocket.close()` is called
2535
+ * @param {Function} [options.finishRequest] A function which can be used to
2536
+ * customize the headers of each http request before it is sent
2537
+ * @param {Boolean} [options.followRedirects=false] Whether or not to follow
2538
+ * redirects
2539
+ * @param {Function} [options.generateMask] The function used to generate the
2540
+ * masking key
2541
+ * @param {Number} [options.handshakeTimeout] Timeout in milliseconds for the
2542
+ * handshake request
2543
+ * @param {Number} [options.maxBufferedChunks=1048576] The maximum number of
2544
+ * buffered data chunks
2545
+ * @param {Number} [options.maxFragments=131072] The maximum number of message
2546
+ * fragments
2547
+ * @param {Number} [options.maxPayload=104857600] The maximum allowed message
2548
+ * size
2549
+ * @param {Number} [options.maxRedirects=10] The maximum number of redirects
2550
+ * allowed
2551
+ * @param {String} [options.origin] Value of the `Origin` or
2552
+ * `Sec-WebSocket-Origin` header
2553
+ * @param {(Boolean|Object)} [options.perMessageDeflate=true] Enable/disable
2554
+ * permessage-deflate
2555
+ * @param {Number} [options.protocolVersion=13] Value of the
2556
+ * `Sec-WebSocket-Version` header
2557
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
2558
+ * not to skip UTF-8 validation for text and close messages
2559
+ * @private
2560
+ */
2561
+ function initAsClient(websocket, address, protocols, options) {
2562
+ const opts = {
2563
+ allowSynchronousEvents: true,
2564
+ autoPong: true,
2565
+ closeTimeout: CLOSE_TIMEOUT,
2566
+ protocolVersion: protocolVersions[1],
2567
+ maxBufferedChunks: 1024 * 1024,
2568
+ maxFragments: 128 * 1024,
2569
+ maxPayload: 100 * 1024 * 1024,
2570
+ skipUTF8Validation: false,
2571
+ perMessageDeflate: true,
2572
+ followRedirects: false,
2573
+ maxRedirects: 10,
2574
+ ...options,
2575
+ socketPath: void 0,
2576
+ hostname: void 0,
2577
+ protocol: void 0,
2578
+ timeout: void 0,
2579
+ method: "GET",
2580
+ host: void 0,
2581
+ path: void 0,
2582
+ port: void 0
2583
+ };
2584
+ websocket._autoPong = opts.autoPong;
2585
+ websocket._closeTimeout = opts.closeTimeout;
2586
+ if (!protocolVersions.includes(opts.protocolVersion)) throw new RangeError(`Unsupported protocol version: ${opts.protocolVersion} (supported versions: ${protocolVersions.join(", ")})`);
2587
+ let parsedUrl;
2588
+ if (address instanceof URL) parsedUrl = address;
2589
+ else try {
2590
+ parsedUrl = new URL(address);
2591
+ } catch {
2592
+ throw new SyntaxError(`Invalid URL: ${address}`);
2593
+ }
2594
+ if (parsedUrl.protocol === "http:") parsedUrl.protocol = "ws:";
2595
+ else if (parsedUrl.protocol === "https:") parsedUrl.protocol = "wss:";
2596
+ websocket._url = parsedUrl.href;
2597
+ const isSecure = parsedUrl.protocol === "wss:";
2598
+ const isIpcUrl = parsedUrl.protocol === "ws+unix:";
2599
+ let invalidUrlMessage;
2600
+ if (parsedUrl.protocol !== "ws:" && !isSecure && !isIpcUrl) invalidUrlMessage = "The URL's protocol must be one of \"ws:\", \"wss:\", \"http:\", \"https:\", or \"ws+unix:\"";
2601
+ else if (isIpcUrl && !parsedUrl.pathname) invalidUrlMessage = "The URL's pathname is empty";
2602
+ else if (parsedUrl.hash) invalidUrlMessage = "The URL contains a fragment identifier";
2603
+ if (invalidUrlMessage) {
2604
+ const err = new SyntaxError(invalidUrlMessage);
2605
+ if (websocket._redirects === 0) throw err;
2606
+ else {
2607
+ emitErrorAndClose(websocket, err);
2608
+ return;
2609
+ }
2610
+ }
2611
+ const defaultPort = isSecure ? 443 : 80;
2612
+ const key = randomBytes(16).toString("base64");
2613
+ const request = isSecure ? https.request : http$1.request;
2614
+ const protocolSet = /* @__PURE__ */ new Set();
2615
+ let perMessageDeflate;
2616
+ opts.createConnection = opts.createConnection || (isSecure ? tlsConnect : netConnect);
2617
+ opts.defaultPort = opts.defaultPort || defaultPort;
2618
+ opts.port = parsedUrl.port || defaultPort;
2619
+ opts.host = parsedUrl.hostname.startsWith("[") ? parsedUrl.hostname.slice(1, -1) : parsedUrl.hostname;
2620
+ opts.headers = {
2621
+ ...opts.headers,
2622
+ "Sec-WebSocket-Version": opts.protocolVersion,
2623
+ "Sec-WebSocket-Key": key,
2624
+ Connection: "Upgrade",
2625
+ Upgrade: "websocket"
2626
+ };
2627
+ opts.path = parsedUrl.pathname + parsedUrl.search;
2628
+ opts.timeout = opts.handshakeTimeout;
2629
+ if (opts.perMessageDeflate) {
2630
+ perMessageDeflate = new PerMessageDeflate({
2631
+ ...opts.perMessageDeflate,
2632
+ isServer: false,
2633
+ maxPayload: opts.maxPayload
2634
+ });
2635
+ opts.headers["Sec-WebSocket-Extensions"] = format({ [PerMessageDeflate.extensionName]: perMessageDeflate.offer() });
2636
+ }
2637
+ if (protocols.length) {
2638
+ for (const protocol of protocols) {
2639
+ if (typeof protocol !== "string" || !subprotocolRegex.test(protocol) || protocolSet.has(protocol)) throw new SyntaxError("An invalid or duplicated subprotocol was specified");
2640
+ protocolSet.add(protocol);
2641
+ }
2642
+ opts.headers["Sec-WebSocket-Protocol"] = protocols.join(",");
2643
+ }
2644
+ if (opts.origin) if (opts.protocolVersion < 13) opts.headers["Sec-WebSocket-Origin"] = opts.origin;
2645
+ else opts.headers.Origin = opts.origin;
2646
+ if (parsedUrl.username || parsedUrl.password) opts.auth = `${parsedUrl.username}:${parsedUrl.password}`;
2647
+ if (isIpcUrl) {
2648
+ const parts = opts.path.split(":");
2649
+ opts.socketPath = parts[0];
2650
+ opts.path = parts[1];
2651
+ }
2652
+ let req;
2653
+ if (opts.followRedirects) {
2654
+ if (websocket._redirects === 0) {
2655
+ websocket._originalIpc = isIpcUrl;
2656
+ websocket._originalSecure = isSecure;
2657
+ websocket._originalHostOrSocketPath = isIpcUrl ? opts.socketPath : parsedUrl.host;
2658
+ const headers = options && options.headers;
2659
+ options = {
2660
+ ...options,
2661
+ headers: {}
2662
+ };
2663
+ if (headers) for (const [key, value] of Object.entries(headers)) options.headers[key.toLowerCase()] = value;
2664
+ } else if (websocket.listenerCount("redirect") === 0) {
2665
+ const isSameHost = isIpcUrl ? websocket._originalIpc ? opts.socketPath === websocket._originalHostOrSocketPath : false : websocket._originalIpc ? false : parsedUrl.host === websocket._originalHostOrSocketPath;
2666
+ if (!isSameHost || websocket._originalSecure && !isSecure) {
2667
+ delete opts.headers.authorization;
2668
+ delete opts.headers.cookie;
2669
+ if (!isSameHost) delete opts.headers.host;
2670
+ opts.auth = void 0;
2671
+ }
2672
+ }
2673
+ if (opts.auth && !options.headers.authorization) options.headers.authorization = "Basic " + Buffer.from(opts.auth).toString("base64");
2674
+ req = websocket._req = request(opts);
2675
+ if (websocket._redirects) websocket.emit("redirect", websocket.url, req);
2676
+ } else req = websocket._req = request(opts);
2677
+ if (opts.timeout) req.on("timeout", () => {
2678
+ abortHandshake(websocket, req, "Opening handshake has timed out");
2679
+ });
2680
+ req.on("error", (err) => {
2681
+ if (req === null || req[kAborted]) return;
2682
+ req = websocket._req = null;
2683
+ emitErrorAndClose(websocket, err);
2684
+ });
2685
+ req.on("response", (res) => {
2686
+ const location = res.headers.location;
2687
+ const statusCode = res.statusCode;
2688
+ if (location && opts.followRedirects && statusCode >= 300 && statusCode < 400) {
2689
+ if (++websocket._redirects > opts.maxRedirects) {
2690
+ abortHandshake(websocket, req, "Maximum redirects exceeded");
2691
+ return;
2692
+ }
2693
+ req.abort();
2694
+ let addr;
2695
+ try {
2696
+ addr = new URL(location, address);
2697
+ } catch (e) {
2698
+ emitErrorAndClose(websocket, /* @__PURE__ */ new SyntaxError(`Invalid URL: ${location}`));
2699
+ return;
2700
+ }
2701
+ initAsClient(websocket, addr, protocols, options);
2702
+ } else if (!websocket.emit("unexpected-response", req, res)) abortHandshake(websocket, req, `Unexpected server response: ${res.statusCode}`);
2703
+ });
2704
+ req.on("upgrade", (res, socket, head) => {
2705
+ websocket.emit("upgrade", res);
2706
+ if (websocket.readyState !== WebSocket.CONNECTING) return;
2707
+ req = websocket._req = null;
2708
+ const upgrade = res.headers.upgrade;
2709
+ if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") {
2710
+ abortHandshake(websocket, socket, "Invalid Upgrade header");
2711
+ return;
2712
+ }
2713
+ const digest = createHash$1("sha1").update(key + GUID).digest("base64");
2714
+ if (res.headers["sec-websocket-accept"] !== digest) {
2715
+ abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
2716
+ return;
2717
+ }
2718
+ const serverProt = res.headers["sec-websocket-protocol"];
2719
+ let protError;
2720
+ if (serverProt !== void 0) {
2721
+ if (!protocolSet.size) protError = "Server sent a subprotocol but none was requested";
2722
+ else if (!protocolSet.has(serverProt)) protError = "Server sent an invalid subprotocol";
2723
+ } else if (protocolSet.size) protError = "Server sent no subprotocol";
2724
+ if (protError) {
2725
+ abortHandshake(websocket, socket, protError);
2726
+ return;
2727
+ }
2728
+ if (serverProt) websocket._protocol = serverProt;
2729
+ const secWebSocketExtensions = res.headers["sec-websocket-extensions"];
2730
+ if (secWebSocketExtensions !== void 0) {
2731
+ if (!perMessageDeflate) {
2732
+ abortHandshake(websocket, socket, "Server sent a Sec-WebSocket-Extensions header but no extension was requested");
2733
+ return;
2734
+ }
2735
+ let extensions;
2736
+ try {
2737
+ extensions = parse(secWebSocketExtensions);
2738
+ } catch (err) {
2739
+ abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Extensions header");
2740
+ return;
2741
+ }
2742
+ const extensionNames = Object.keys(extensions);
2743
+ if (extensionNames.length !== 1 || extensionNames[0] !== PerMessageDeflate.extensionName) {
2744
+ abortHandshake(websocket, socket, "Server indicated an extension that was not requested");
2745
+ return;
2746
+ }
2747
+ try {
2748
+ perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName]);
2749
+ } catch (err) {
2750
+ abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Extensions header");
2751
+ return;
2752
+ }
2753
+ websocket._extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
2754
+ }
2755
+ websocket.setSocket(socket, head, {
2756
+ allowSynchronousEvents: opts.allowSynchronousEvents,
2757
+ generateMask: opts.generateMask,
2758
+ maxBufferedChunks: opts.maxBufferedChunks,
2759
+ maxFragments: opts.maxFragments,
2760
+ maxPayload: opts.maxPayload,
2761
+ skipUTF8Validation: opts.skipUTF8Validation
2762
+ });
2763
+ });
2764
+ if (opts.finishRequest) opts.finishRequest(req, websocket);
2765
+ else req.end();
2766
+ }
2767
+ /**
2768
+ * Emit the `'error'` and `'close'` events.
2769
+ *
2770
+ * @param {WebSocket} websocket The WebSocket instance
2771
+ * @param {Error} The error to emit
2772
+ * @private
2773
+ */
2774
+ function emitErrorAndClose(websocket, err) {
2775
+ websocket._readyState = WebSocket.CLOSING;
2776
+ websocket._errorEmitted = true;
2777
+ websocket.emit("error", err);
2778
+ websocket.emitClose();
2779
+ }
2780
+ /**
2781
+ * Create a `net.Socket` and initiate a connection.
2782
+ *
2783
+ * @param {Object} options Connection options
2784
+ * @return {net.Socket} The newly created socket used to start the connection
2785
+ * @private
2786
+ */
2787
+ function netConnect(options) {
2788
+ options.path = options.socketPath;
2789
+ return net.connect(options);
2790
+ }
2791
+ /**
2792
+ * Create a `tls.TLSSocket` and initiate a connection.
2793
+ *
2794
+ * @param {Object} options Connection options
2795
+ * @return {tls.TLSSocket} The newly created socket used to start the connection
2796
+ * @private
2797
+ */
2798
+ function tlsConnect(options) {
2799
+ options.path = void 0;
2800
+ if (!options.servername && options.servername !== "") options.servername = net.isIP(options.host) ? "" : options.host;
2801
+ return tls.connect(options);
2802
+ }
2803
+ /**
2804
+ * Abort the handshake and emit an error.
2805
+ *
2806
+ * @param {WebSocket} websocket The WebSocket instance
2807
+ * @param {(http.ClientRequest|net.Socket|tls.Socket)} stream The request to
2808
+ * abort or the socket to destroy
2809
+ * @param {String} message The error message
2810
+ * @private
2811
+ */
2812
+ function abortHandshake(websocket, stream, message) {
2813
+ websocket._readyState = WebSocket.CLOSING;
2814
+ const err = new Error(message);
2815
+ Error.captureStackTrace(err, abortHandshake);
2816
+ if (stream.setHeader) {
2817
+ stream[kAborted] = true;
2818
+ stream.abort();
2819
+ if (stream.socket && !stream.socket.destroyed) stream.socket.destroy();
2820
+ process.nextTick(emitErrorAndClose, websocket, err);
2821
+ } else {
2822
+ stream.destroy(err);
2823
+ stream.once("error", websocket.emit.bind(websocket, "error"));
2824
+ stream.once("close", websocket.emitClose.bind(websocket));
2825
+ }
2826
+ }
2827
+ /**
2828
+ * Handle cases where the `ping()`, `pong()`, or `send()` methods are called
2829
+ * when the `readyState` attribute is `CLOSING` or `CLOSED`.
2830
+ *
2831
+ * @param {WebSocket} websocket The WebSocket instance
2832
+ * @param {*} [data] The data to send
2833
+ * @param {Function} [cb] Callback
2834
+ * @private
2835
+ */
2836
+ function sendAfterClose(websocket, data, cb) {
2837
+ if (data) {
2838
+ const length = isBlob(data) ? data.size : toBuffer(data).length;
2839
+ if (websocket._socket) websocket._sender._bufferedBytes += length;
2840
+ else websocket._bufferedAmount += length;
2841
+ }
2842
+ if (cb) {
2843
+ const err = /* @__PURE__ */ new Error(`WebSocket is not open: readyState ${websocket.readyState} (${readyStates[websocket.readyState]})`);
2844
+ process.nextTick(cb, err);
2845
+ }
2846
+ }
2847
+ /**
2848
+ * The listener of the `Receiver` `'conclude'` event.
2849
+ *
2850
+ * @param {Number} code The status code
2851
+ * @param {Buffer} reason The reason for closing
2852
+ * @private
2853
+ */
2854
+ function receiverOnConclude(code, reason) {
2855
+ const websocket = this[kWebSocket];
2856
+ websocket._closeFrameReceived = true;
2857
+ websocket._closeMessage = reason;
2858
+ websocket._closeCode = code;
2859
+ if (websocket._socket[kWebSocket] === void 0) return;
2860
+ websocket._socket.removeListener("data", socketOnData);
2861
+ process.nextTick(resume, websocket._socket);
2862
+ if (code === 1005) websocket.close();
2863
+ else websocket.close(code, reason);
2864
+ }
2865
+ /**
2866
+ * The listener of the `Receiver` `'drain'` event.
2867
+ *
2868
+ * @private
2869
+ */
2870
+ function receiverOnDrain() {
2871
+ const websocket = this[kWebSocket];
2872
+ if (!websocket.isPaused) websocket._socket.resume();
2873
+ }
2874
+ /**
2875
+ * The listener of the `Receiver` `'error'` event.
2876
+ *
2877
+ * @param {(RangeError|Error)} err The emitted error
2878
+ * @private
2879
+ */
2880
+ function receiverOnError(err) {
2881
+ const websocket = this[kWebSocket];
2882
+ if (websocket._socket[kWebSocket] !== void 0) {
2883
+ websocket._socket.removeListener("data", socketOnData);
2884
+ process.nextTick(resume, websocket._socket);
2885
+ websocket.close(err[kStatusCode]);
2886
+ }
2887
+ if (!websocket._errorEmitted) {
2888
+ websocket._errorEmitted = true;
2889
+ websocket.emit("error", err);
2890
+ }
2891
+ }
2892
+ /**
2893
+ * The listener of the `Receiver` `'finish'` event.
2894
+ *
2895
+ * @private
2896
+ */
2897
+ function receiverOnFinish() {
2898
+ this[kWebSocket].emitClose();
2899
+ }
2900
+ /**
2901
+ * The listener of the `Receiver` `'message'` event.
2902
+ *
2903
+ * @param {Buffer|ArrayBuffer|Buffer[])} data The message
2904
+ * @param {Boolean} isBinary Specifies whether the message is binary or not
2905
+ * @private
2906
+ */
2907
+ function receiverOnMessage(data, isBinary) {
2908
+ this[kWebSocket].emit("message", data, isBinary);
2909
+ }
2910
+ /**
2911
+ * The listener of the `Receiver` `'ping'` event.
2912
+ *
2913
+ * @param {Buffer} data The data included in the ping frame
2914
+ * @private
2915
+ */
2916
+ function receiverOnPing(data) {
2917
+ const websocket = this[kWebSocket];
2918
+ if (websocket._autoPong) websocket.pong(data, !this._isServer, NOOP);
2919
+ websocket.emit("ping", data);
2920
+ }
2921
+ /**
2922
+ * The listener of the `Receiver` `'pong'` event.
2923
+ *
2924
+ * @param {Buffer} data The data included in the pong frame
2925
+ * @private
2926
+ */
2927
+ function receiverOnPong(data) {
2928
+ this[kWebSocket].emit("pong", data);
2929
+ }
2930
+ /**
2931
+ * Resume a readable stream
2932
+ *
2933
+ * @param {Readable} stream The readable stream
2934
+ * @private
2935
+ */
2936
+ function resume(stream) {
2937
+ stream.resume();
2938
+ }
2939
+ /**
2940
+ * The `Sender` error event handler.
2941
+ *
2942
+ * @param {Error} The error
2943
+ * @private
2944
+ */
2945
+ function senderOnError(err) {
2946
+ const websocket = this[kWebSocket];
2947
+ if (websocket.readyState === WebSocket.CLOSED) return;
2948
+ if (websocket.readyState === WebSocket.OPEN) {
2949
+ websocket._readyState = WebSocket.CLOSING;
2950
+ setCloseTimer(websocket);
2951
+ }
2952
+ this._socket.end();
2953
+ if (!websocket._errorEmitted) {
2954
+ websocket._errorEmitted = true;
2955
+ websocket.emit("error", err);
2956
+ }
2957
+ }
2958
+ /**
2959
+ * Set a timer to destroy the underlying raw socket of a WebSocket.
2960
+ *
2961
+ * @param {WebSocket} websocket The WebSocket instance
2962
+ * @private
2963
+ */
2964
+ function setCloseTimer(websocket) {
2965
+ websocket._closeTimer = setTimeout(websocket._socket.destroy.bind(websocket._socket), websocket._closeTimeout);
2966
+ }
2967
+ /**
2968
+ * The listener of the socket `'close'` event.
2969
+ *
2970
+ * @private
2971
+ */
2972
+ function socketOnClose() {
2973
+ const websocket = this[kWebSocket];
2974
+ this.removeListener("close", socketOnClose);
2975
+ this.removeListener("data", socketOnData);
2976
+ this.removeListener("end", socketOnEnd);
2977
+ websocket._readyState = WebSocket.CLOSING;
2978
+ if (!this._readableState.endEmitted && !websocket._closeFrameReceived && !websocket._receiver._writableState.errorEmitted && this._readableState.length !== 0) {
2979
+ const chunk = this.read(this._readableState.length);
2980
+ websocket._receiver.write(chunk);
2981
+ }
2982
+ websocket._receiver.end();
2983
+ this[kWebSocket] = void 0;
2984
+ clearTimeout(websocket._closeTimer);
2985
+ if (websocket._receiver._writableState.finished || websocket._receiver._writableState.errorEmitted) websocket.emitClose();
2986
+ else {
2987
+ websocket._receiver.on("error", receiverOnFinish);
2988
+ websocket._receiver.on("finish", receiverOnFinish);
2989
+ }
2990
+ }
2991
+ /**
2992
+ * The listener of the socket `'data'` event.
2993
+ *
2994
+ * @param {Buffer} chunk A chunk of data
2995
+ * @private
2996
+ */
2997
+ function socketOnData(chunk) {
2998
+ if (!this[kWebSocket]._receiver.write(chunk)) this.pause();
2999
+ }
3000
+ /**
3001
+ * The listener of the socket `'end'` event.
3002
+ *
3003
+ * @private
3004
+ */
3005
+ function socketOnEnd() {
3006
+ const websocket = this[kWebSocket];
3007
+ websocket._readyState = WebSocket.CLOSING;
3008
+ websocket._receiver.end();
3009
+ this.end();
3010
+ }
3011
+ /**
3012
+ * The listener of the socket `'error'` event.
3013
+ *
3014
+ * @private
3015
+ */
3016
+ function socketOnError() {
3017
+ const websocket = this[kWebSocket];
3018
+ this.removeListener("error", socketOnError);
3019
+ this.on("error", NOOP);
3020
+ if (websocket) {
3021
+ websocket._readyState = WebSocket.CLOSING;
3022
+ this.destroy();
3023
+ }
3024
+ }
3025
+ }));
3026
+ //#endregion
3027
+ //#region node_modules/ws/lib/stream.js
3028
+ var require_stream = /* @__PURE__ */ __commonJSMin(((exports, module) => {
3029
+ require_websocket();
3030
+ const { Duplex: Duplex$1 } = __require("stream");
3031
+ /**
3032
+ * Emits the `'close'` event on a stream.
3033
+ *
3034
+ * @param {Duplex} stream The stream.
3035
+ * @private
3036
+ */
3037
+ function emitClose(stream) {
3038
+ stream.emit("close");
3039
+ }
3040
+ /**
3041
+ * The listener of the `'end'` event.
3042
+ *
3043
+ * @private
3044
+ */
3045
+ function duplexOnEnd() {
3046
+ if (!this.destroyed && this._writableState.finished) this.destroy();
3047
+ }
3048
+ /**
3049
+ * The listener of the `'error'` event.
3050
+ *
3051
+ * @param {Error} err The error
3052
+ * @private
3053
+ */
3054
+ function duplexOnError(err) {
3055
+ this.removeListener("error", duplexOnError);
3056
+ this.destroy();
3057
+ if (this.listenerCount("error") === 0) this.emit("error", err);
3058
+ }
3059
+ /**
3060
+ * Wraps a `WebSocket` in a duplex stream.
3061
+ *
3062
+ * @param {WebSocket} ws The `WebSocket` to wrap
3063
+ * @param {Object} [options] The options for the `Duplex` constructor
3064
+ * @return {Duplex} The duplex stream
3065
+ * @public
3066
+ */
3067
+ function createWebSocketStream(ws, options) {
3068
+ let terminateOnDestroy = true;
3069
+ const duplex = new Duplex$1({
3070
+ ...options,
3071
+ autoDestroy: false,
3072
+ emitClose: false,
3073
+ objectMode: false,
3074
+ writableObjectMode: false
3075
+ });
3076
+ ws.on("message", function message(msg, isBinary) {
3077
+ const data = !isBinary && duplex._readableState.objectMode ? msg.toString() : msg;
3078
+ if (!duplex.push(data)) ws.pause();
3079
+ });
3080
+ ws.once("error", function error(err) {
3081
+ if (duplex.destroyed) return;
3082
+ terminateOnDestroy = false;
3083
+ duplex.destroy(err);
3084
+ });
3085
+ ws.once("close", function close() {
3086
+ if (duplex.destroyed) return;
3087
+ duplex.push(null);
3088
+ });
3089
+ duplex._destroy = function(err, callback) {
3090
+ if (ws.readyState === ws.CLOSED) {
3091
+ callback(err);
3092
+ process.nextTick(emitClose, duplex);
3093
+ return;
3094
+ }
3095
+ let called = false;
3096
+ ws.once("error", function error(err) {
3097
+ called = true;
3098
+ callback(err);
3099
+ });
3100
+ ws.once("close", function close() {
3101
+ if (!called) callback(err);
3102
+ process.nextTick(emitClose, duplex);
3103
+ });
3104
+ if (terminateOnDestroy) ws.terminate();
3105
+ };
3106
+ duplex._final = function(callback) {
3107
+ if (ws.readyState === ws.CONNECTING) {
3108
+ ws.once("open", function open() {
3109
+ duplex._final(callback);
3110
+ });
3111
+ return;
3112
+ }
3113
+ if (ws._socket === null) return;
3114
+ if (ws._socket._writableState.finished) {
3115
+ callback();
3116
+ if (duplex._readableState.endEmitted) duplex.destroy();
3117
+ } else {
3118
+ ws._socket.once("finish", function finish() {
3119
+ callback();
3120
+ });
3121
+ ws.close();
3122
+ }
3123
+ };
3124
+ duplex._read = function() {
3125
+ if (ws.isPaused) ws.resume();
3126
+ };
3127
+ duplex._write = function(chunk, encoding, callback) {
3128
+ if (ws.readyState === ws.CONNECTING) {
3129
+ ws.once("open", function open() {
3130
+ duplex._write(chunk, encoding, callback);
3131
+ });
3132
+ return;
3133
+ }
3134
+ ws.send(chunk, callback);
3135
+ };
3136
+ duplex.on("end", duplexOnEnd);
3137
+ duplex.on("error", duplexOnError);
3138
+ return duplex;
3139
+ }
3140
+ module.exports = createWebSocketStream;
3141
+ }));
3142
+ //#endregion
3143
+ //#region node_modules/ws/lib/subprotocol.js
3144
+ var require_subprotocol = /* @__PURE__ */ __commonJSMin(((exports, module) => {
3145
+ const { tokenChars } = require_validation();
3146
+ /**
3147
+ * Parses the `Sec-WebSocket-Protocol` header into a set of subprotocol names.
3148
+ *
3149
+ * @param {String} header The field value of the header
3150
+ * @return {Set} The subprotocol names
3151
+ * @public
3152
+ */
3153
+ function parse(header) {
3154
+ const protocols = /* @__PURE__ */ new Set();
3155
+ let start = -1;
3156
+ let end = -1;
3157
+ let i = 0;
3158
+ for (; i < header.length; i++) {
3159
+ const code = header.charCodeAt(i);
3160
+ if (end === -1 && tokenChars[code] === 1) {
3161
+ if (start === -1) start = i;
3162
+ } else if (i !== 0 && (code === 32 || code === 9)) {
3163
+ if (end === -1 && start !== -1) end = i;
3164
+ } else if (code === 44) {
3165
+ if (start === -1) throw new SyntaxError(`Unexpected character at index ${i}`);
3166
+ if (end === -1) end = i;
3167
+ const protocol = header.slice(start, end);
3168
+ if (protocols.has(protocol)) throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);
3169
+ protocols.add(protocol);
3170
+ start = end = -1;
3171
+ } else throw new SyntaxError(`Unexpected character at index ${i}`);
3172
+ }
3173
+ if (start === -1 || end !== -1) throw new SyntaxError("Unexpected end of input");
3174
+ const protocol = header.slice(start, i);
3175
+ if (protocols.has(protocol)) throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);
3176
+ protocols.add(protocol);
3177
+ return protocols;
3178
+ }
3179
+ module.exports = { parse };
3180
+ }));
3181
+ //#endregion
3182
+ //#region node_modules/ws/lib/websocket-server.js
3183
+ var require_websocket_server = /* @__PURE__ */ __commonJSMin(((exports, module) => {
3184
+ const EventEmitter = __require("events");
3185
+ const http = __require("http");
3186
+ const { Duplex } = __require("stream");
3187
+ const { createHash } = __require("crypto");
3188
+ const extension = require_extension();
3189
+ const PerMessageDeflate = require_permessage_deflate();
3190
+ const subprotocol = require_subprotocol();
3191
+ const WebSocket = require_websocket();
3192
+ const { CLOSE_TIMEOUT, GUID, kWebSocket } = require_constants();
3193
+ const keyRegex = /^[+/0-9A-Za-z]{22}==$/;
3194
+ const RUNNING = 0;
3195
+ const CLOSING = 1;
3196
+ const CLOSED = 2;
3197
+ /**
3198
+ * Class representing a WebSocket server.
3199
+ *
3200
+ * @extends EventEmitter
3201
+ */
3202
+ var WebSocketServer = class extends EventEmitter {
3203
+ /**
3204
+ * Create a `WebSocketServer` instance.
3205
+ *
3206
+ * @param {Object} options Configuration options
3207
+ * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
3208
+ * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
3209
+ * multiple times in the same tick
3210
+ * @param {Boolean} [options.autoPong=true] Specifies whether or not to
3211
+ * automatically send a pong in response to a ping
3212
+ * @param {Number} [options.backlog=511] The maximum length of the queue of
3213
+ * pending connections
3214
+ * @param {Boolean} [options.clientTracking=true] Specifies whether or not to
3215
+ * track clients
3216
+ * @param {Number} [options.closeTimeout=30000] Duration in milliseconds to
3217
+ * wait for the closing handshake to finish after `websocket.close()` is
3218
+ * called
3219
+ * @param {Function} [options.handleProtocols] A hook to handle protocols
3220
+ * @param {String} [options.host] The hostname where to bind the server
3221
+ * @param {Number} [options.maxBufferedChunks=1048576] The maximum number of
3222
+ * buffered data chunks
3223
+ * @param {Number} [options.maxFragments=131072] The maximum number of message
3224
+ * fragments
3225
+ * @param {Number} [options.maxPayload=104857600] The maximum allowed message
3226
+ * size
3227
+ * @param {Boolean} [options.noServer=false] Enable no server mode
3228
+ * @param {String} [options.path] Accept only connections matching this path
3229
+ * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable
3230
+ * permessage-deflate
3231
+ * @param {Number} [options.port] The port where to bind the server
3232
+ * @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S
3233
+ * server to use
3234
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
3235
+ * not to skip UTF-8 validation for text and close messages
3236
+ * @param {Function} [options.verifyClient] A hook to reject connections
3237
+ * @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket`
3238
+ * class to use. It must be the `WebSocket` class or class that extends it
3239
+ * @param {Function} [callback] A listener for the `listening` event
3240
+ */
3241
+ constructor(options, callback) {
3242
+ super();
3243
+ options = {
3244
+ allowSynchronousEvents: true,
3245
+ autoPong: true,
3246
+ maxBufferedChunks: 1024 * 1024,
3247
+ maxFragments: 128 * 1024,
3248
+ maxPayload: 100 * 1024 * 1024,
3249
+ skipUTF8Validation: false,
3250
+ perMessageDeflate: false,
3251
+ handleProtocols: null,
3252
+ clientTracking: true,
3253
+ closeTimeout: CLOSE_TIMEOUT,
3254
+ verifyClient: null,
3255
+ noServer: false,
3256
+ backlog: null,
3257
+ server: null,
3258
+ host: null,
3259
+ path: null,
3260
+ port: null,
3261
+ WebSocket,
3262
+ ...options
3263
+ };
3264
+ if (options.port == null && !options.server && !options.noServer || options.port != null && (options.server || options.noServer) || options.server && options.noServer) throw new TypeError("One and only one of the \"port\", \"server\", or \"noServer\" options must be specified");
3265
+ if (options.port != null) {
3266
+ this._server = http.createServer((req, res) => {
3267
+ const body = http.STATUS_CODES[426];
3268
+ res.writeHead(426, {
3269
+ "Content-Length": body.length,
3270
+ "Content-Type": "text/plain"
3271
+ });
3272
+ res.end(body);
3273
+ });
3274
+ this._server.listen(options.port, options.host, options.backlog, callback);
3275
+ } else if (options.server) this._server = options.server;
3276
+ if (this._server) {
3277
+ const emitConnection = this.emit.bind(this, "connection");
3278
+ this._removeListeners = addListeners(this._server, {
3279
+ listening: this.emit.bind(this, "listening"),
3280
+ error: this.emit.bind(this, "error"),
3281
+ upgrade: (req, socket, head) => {
3282
+ this.handleUpgrade(req, socket, head, emitConnection);
3283
+ }
3284
+ });
3285
+ }
3286
+ if (options.perMessageDeflate === true) options.perMessageDeflate = {};
3287
+ if (options.clientTracking) {
3288
+ this.clients = /* @__PURE__ */ new Set();
3289
+ this._shouldEmitClose = false;
3290
+ }
3291
+ this.options = options;
3292
+ this._state = RUNNING;
3293
+ }
3294
+ /**
3295
+ * Returns the bound address, the address family name, and port of the server
3296
+ * as reported by the operating system if listening on an IP socket.
3297
+ * If the server is listening on a pipe or UNIX domain socket, the name is
3298
+ * returned as a string.
3299
+ *
3300
+ * @return {(Object|String|null)} The address of the server
3301
+ * @public
3302
+ */
3303
+ address() {
3304
+ if (this.options.noServer) throw new Error("The server is operating in \"noServer\" mode");
3305
+ if (!this._server) return null;
3306
+ return this._server.address();
3307
+ }
3308
+ /**
3309
+ * Stop the server from accepting new connections and emit the `'close'` event
3310
+ * when all existing connections are closed.
3311
+ *
3312
+ * @param {Function} [cb] A one-time listener for the `'close'` event
3313
+ * @public
3314
+ */
3315
+ close(cb) {
3316
+ if (this._state === CLOSED) {
3317
+ if (cb) this.once("close", () => {
3318
+ cb(/* @__PURE__ */ new Error("The server is not running"));
3319
+ });
3320
+ process.nextTick(emitClose, this);
3321
+ return;
3322
+ }
3323
+ if (cb) this.once("close", cb);
3324
+ if (this._state === CLOSING) return;
3325
+ this._state = CLOSING;
3326
+ if (this.options.noServer || this.options.server) {
3327
+ if (this._server) {
3328
+ this._removeListeners();
3329
+ this._removeListeners = this._server = null;
3330
+ }
3331
+ if (this.clients) if (!this.clients.size) process.nextTick(emitClose, this);
3332
+ else this._shouldEmitClose = true;
3333
+ else process.nextTick(emitClose, this);
3334
+ } else {
3335
+ const server = this._server;
3336
+ this._removeListeners();
3337
+ this._removeListeners = this._server = null;
3338
+ server.close(() => {
3339
+ emitClose(this);
3340
+ });
3341
+ }
3342
+ }
3343
+ /**
3344
+ * See if a given request should be handled by this server instance.
3345
+ *
3346
+ * @param {http.IncomingMessage} req Request object to inspect
3347
+ * @return {Boolean} `true` if the request is valid, else `false`
3348
+ * @public
3349
+ */
3350
+ shouldHandle(req) {
3351
+ if (this.options.path) {
3352
+ const index = req.url.indexOf("?");
3353
+ if ((index !== -1 ? req.url.slice(0, index) : req.url) !== this.options.path) return false;
3354
+ }
3355
+ return true;
3356
+ }
3357
+ /**
3358
+ * Handle a HTTP Upgrade request.
3359
+ *
3360
+ * @param {http.IncomingMessage} req The request object
3361
+ * @param {Duplex} socket The network socket between the server and client
3362
+ * @param {Buffer} head The first packet of the upgraded stream
3363
+ * @param {Function} cb Callback
3364
+ * @public
3365
+ */
3366
+ handleUpgrade(req, socket, head, cb) {
3367
+ socket.on("error", socketOnError);
3368
+ const key = req.headers["sec-websocket-key"];
3369
+ const upgrade = req.headers.upgrade;
3370
+ const version = +req.headers["sec-websocket-version"];
3371
+ if (req.method !== "GET") {
3372
+ abortHandshakeOrEmitwsClientError(this, req, socket, 405, "Invalid HTTP method");
3373
+ return;
3374
+ }
3375
+ if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") {
3376
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, "Invalid Upgrade header");
3377
+ return;
3378
+ }
3379
+ if (key === void 0 || !keyRegex.test(key)) {
3380
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, "Missing or invalid Sec-WebSocket-Key header");
3381
+ return;
3382
+ }
3383
+ if (version !== 13 && version !== 8) {
3384
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, "Missing or invalid Sec-WebSocket-Version header", { "Sec-WebSocket-Version": "13, 8" });
3385
+ return;
3386
+ }
3387
+ if (!this.shouldHandle(req)) {
3388
+ abortHandshake(socket, 400);
3389
+ return;
3390
+ }
3391
+ const secWebSocketProtocol = req.headers["sec-websocket-protocol"];
3392
+ let protocols = /* @__PURE__ */ new Set();
3393
+ if (secWebSocketProtocol !== void 0) try {
3394
+ protocols = subprotocol.parse(secWebSocketProtocol);
3395
+ } catch (err) {
3396
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, "Invalid Sec-WebSocket-Protocol header");
3397
+ return;
3398
+ }
3399
+ const secWebSocketExtensions = req.headers["sec-websocket-extensions"];
3400
+ const extensions = {};
3401
+ if (this.options.perMessageDeflate && secWebSocketExtensions !== void 0) {
3402
+ const perMessageDeflate = new PerMessageDeflate({
3403
+ ...this.options.perMessageDeflate,
3404
+ isServer: true,
3405
+ maxPayload: this.options.maxPayload
3406
+ });
3407
+ try {
3408
+ const offers = extension.parse(secWebSocketExtensions);
3409
+ if (offers[PerMessageDeflate.extensionName]) {
3410
+ perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]);
3411
+ extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
3412
+ }
3413
+ } catch (err) {
3414
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, "Invalid or unacceptable Sec-WebSocket-Extensions header");
3415
+ return;
3416
+ }
3417
+ }
3418
+ if (this.options.verifyClient) {
3419
+ const info = {
3420
+ origin: req.headers[`${version === 8 ? "sec-websocket-origin" : "origin"}`],
3421
+ secure: !!(req.socket.authorized || req.socket.encrypted),
3422
+ req
3423
+ };
3424
+ if (this.options.verifyClient.length === 2) {
3425
+ this.options.verifyClient(info, (verified, code, message, headers) => {
3426
+ if (!verified) return abortHandshake(socket, code || 401, message, headers);
3427
+ this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);
3428
+ });
3429
+ return;
3430
+ }
3431
+ if (!this.options.verifyClient(info)) return abortHandshake(socket, 401);
3432
+ }
3433
+ this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);
3434
+ }
3435
+ /**
3436
+ * Upgrade the connection to WebSocket.
3437
+ *
3438
+ * @param {Object} extensions The accepted extensions
3439
+ * @param {String} key The value of the `Sec-WebSocket-Key` header
3440
+ * @param {Set} protocols The subprotocols
3441
+ * @param {http.IncomingMessage} req The request object
3442
+ * @param {Duplex} socket The network socket between the server and client
3443
+ * @param {Buffer} head The first packet of the upgraded stream
3444
+ * @param {Function} cb Callback
3445
+ * @throws {Error} If called more than once with the same socket
3446
+ * @private
3447
+ */
3448
+ completeUpgrade(extensions, key, protocols, req, socket, head, cb) {
3449
+ if (!socket.readable || !socket.writable) return socket.destroy();
3450
+ if (socket[kWebSocket]) throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");
3451
+ if (this._state > RUNNING) return abortHandshake(socket, 503);
3452
+ const headers = [
3453
+ "HTTP/1.1 101 Switching Protocols",
3454
+ "Upgrade: websocket",
3455
+ "Connection: Upgrade",
3456
+ `Sec-WebSocket-Accept: ${createHash("sha1").update(key + GUID).digest("base64")}`
3457
+ ];
3458
+ const ws = new this.options.WebSocket(null, void 0, this.options);
3459
+ if (protocols.size) {
3460
+ const protocol = this.options.handleProtocols ? this.options.handleProtocols(protocols, req) : protocols.values().next().value;
3461
+ if (protocol) {
3462
+ headers.push(`Sec-WebSocket-Protocol: ${protocol}`);
3463
+ ws._protocol = protocol;
3464
+ }
3465
+ }
3466
+ if (extensions[PerMessageDeflate.extensionName]) {
3467
+ const params = extensions[PerMessageDeflate.extensionName].params;
3468
+ const value = extension.format({ [PerMessageDeflate.extensionName]: [params] });
3469
+ headers.push(`Sec-WebSocket-Extensions: ${value}`);
3470
+ ws._extensions = extensions;
3471
+ }
3472
+ this.emit("headers", headers, req);
3473
+ socket.write(headers.concat("\r\n").join("\r\n"));
3474
+ socket.removeListener("error", socketOnError);
3475
+ ws.setSocket(socket, head, {
3476
+ allowSynchronousEvents: this.options.allowSynchronousEvents,
3477
+ maxBufferedChunks: this.options.maxBufferedChunks,
3478
+ maxFragments: this.options.maxFragments,
3479
+ maxPayload: this.options.maxPayload,
3480
+ skipUTF8Validation: this.options.skipUTF8Validation
3481
+ });
3482
+ if (this.clients) {
3483
+ this.clients.add(ws);
3484
+ ws.on("close", () => {
3485
+ this.clients.delete(ws);
3486
+ if (this._shouldEmitClose && !this.clients.size) process.nextTick(emitClose, this);
3487
+ });
3488
+ }
3489
+ cb(ws, req);
3490
+ }
3491
+ };
3492
+ module.exports = WebSocketServer;
3493
+ /**
3494
+ * Add event listeners on an `EventEmitter` using a map of <event, listener>
3495
+ * pairs.
3496
+ *
3497
+ * @param {EventEmitter} server The event emitter
3498
+ * @param {Object.<String, Function>} map The listeners to add
3499
+ * @return {Function} A function that will remove the added listeners when
3500
+ * called
3501
+ * @private
3502
+ */
3503
+ function addListeners(server, map) {
3504
+ for (const event of Object.keys(map)) server.on(event, map[event]);
3505
+ return function removeListeners() {
3506
+ for (const event of Object.keys(map)) server.removeListener(event, map[event]);
3507
+ };
3508
+ }
3509
+ /**
3510
+ * Emit a `'close'` event on an `EventEmitter`.
3511
+ *
3512
+ * @param {EventEmitter} server The event emitter
3513
+ * @private
3514
+ */
3515
+ function emitClose(server) {
3516
+ server._state = CLOSED;
3517
+ server.emit("close");
3518
+ }
3519
+ /**
3520
+ * Handle socket errors.
3521
+ *
3522
+ * @private
3523
+ */
3524
+ function socketOnError() {
3525
+ this.destroy();
3526
+ }
3527
+ /**
3528
+ * Close the connection when preconditions are not fulfilled.
3529
+ *
3530
+ * @param {Duplex} socket The socket of the upgrade request
3531
+ * @param {Number} code The HTTP response status code
3532
+ * @param {String} [message] The HTTP response body
3533
+ * @param {Object} [headers] Additional HTTP response headers
3534
+ * @private
3535
+ */
3536
+ function abortHandshake(socket, code, message, headers) {
3537
+ message = message || http.STATUS_CODES[code];
3538
+ headers = {
3539
+ Connection: "close",
3540
+ "Content-Type": "text/html",
3541
+ "Content-Length": Buffer.byteLength(message),
3542
+ ...headers
3543
+ };
3544
+ socket.once("finish", socket.destroy);
3545
+ socket.end(`HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r\n` + Object.keys(headers).map((h) => `${h}: ${headers[h]}`).join("\r\n") + "\r\n\r\n" + message);
3546
+ }
3547
+ /**
3548
+ * Emit a `'wsClientError'` event on a `WebSocketServer` if there is at least
3549
+ * one listener for it, otherwise call `abortHandshake()`.
3550
+ *
3551
+ * @param {WebSocketServer} server The WebSocket server
3552
+ * @param {http.IncomingMessage} req The request object
3553
+ * @param {Duplex} socket The socket of the upgrade request
3554
+ * @param {Number} code The HTTP response status code
3555
+ * @param {String} message The HTTP response body
3556
+ * @param {Object} [headers] The HTTP response headers
3557
+ * @private
3558
+ */
3559
+ function abortHandshakeOrEmitwsClientError(server, req, socket, code, message, headers) {
3560
+ if (server.listenerCount("wsClientError")) {
3561
+ const err = new Error(message);
3562
+ Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError);
3563
+ server.emit("wsClientError", err, socket, req);
3564
+ } else abortHandshake(socket, code, message, headers);
3565
+ }
3566
+ }));
3567
+ //#endregion
3568
+ //#region node_modules/ws/wrapper.mjs
3569
+ var import_stream = /* @__PURE__ */ __toESM(require_stream(), 1);
3570
+ var import_extension = /* @__PURE__ */ __toESM(require_extension(), 1);
3571
+ var import_permessage_deflate = /* @__PURE__ */ __toESM(require_permessage_deflate(), 1);
3572
+ var import_receiver = /* @__PURE__ */ __toESM(require_receiver(), 1);
3573
+ var import_sender = /* @__PURE__ */ __toESM(require_sender(), 1);
3574
+ var import_subprotocol = /* @__PURE__ */ __toESM(require_subprotocol(), 1);
3575
+ var import_websocket = /* @__PURE__ */ __toESM(require_websocket(), 1);
3576
+ var import_websocket_server = /* @__PURE__ */ __toESM(require_websocket_server(), 1);
3577
+ var wrapper_default = import_websocket.default;
3578
+ //#endregion
3579
+ var PerMessageDeflate = import_permessage_deflate.default;
3580
+ var Receiver = import_receiver.default;
3581
+ var Sender = import_sender.default;
3582
+ var WebSocket = import_websocket.default;
3583
+ var WebSocketServer = import_websocket_server.default;
3584
+ var createWebSocketStream = import_stream.default;
3585
+ var extension = import_extension.default;
3586
+ var subprotocol = import_subprotocol.default;
3587
+ export { PerMessageDeflate, Receiver, Sender, WebSocket, WebSocketServer, createWebSocketStream, wrapper_default as default, extension, subprotocol };
3588
+
3589
+ //# sourceMappingURL=wrapper-D7gNSsgf.mjs.map