@n-dream/builders-cli 0.0.0-stage → 0.1.0

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