@workflow/web 5.0.0-beta.39 → 5.0.0-beta.40

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