@workflow/web 5.0.0-beta.5 → 5.0.0-beta.51

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