perstack 0.0.92 → 0.0.94

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