remotelink 0.4.2 → 0.4.3

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