@zoralabs/protocol-deployments 0.1.10 → 0.1.12

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