@elizaos/plugin-tee 1.0.0-alpha.25 → 1.0.0-alpha.27

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