perstack 0.0.84 → 0.0.85

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