tenjin-cli 0.1.0-alpha.0

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