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