@vitejs/devtools-rpc 0.0.0-alpha.32 → 0.0.0-alpha.34

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