save-forever-mcp 0.1.0

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