@elizaos/plugin-tee 1.0.0-alpha.2 → 1.0.0-alpha.20

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