@tinycloud/cli 0.7.0-beta.14 → 0.7.0-beta.15

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