skalpel 2.0.14 → 2.0.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli/index.js CHANGED
@@ -1,4 +1,3772 @@
1
1
  #!/usr/bin/env node
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
9
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
10
+ }) : x)(function(x) {
11
+ if (typeof require !== "undefined") return require.apply(this, arguments);
12
+ throw Error('Dynamic require of "' + x + '" is not supported');
13
+ });
14
+ var __esm = (fn, res) => function __init() {
15
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
16
+ };
17
+ var __commonJS = (cb, mod) => function __require2() {
18
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
19
+ };
20
+ var __copyProps = (to, from, except, desc) => {
21
+ if (from && typeof from === "object" || typeof from === "function") {
22
+ for (let key of __getOwnPropNames(from))
23
+ if (!__hasOwnProp.call(to, key) && key !== except)
24
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
25
+ }
26
+ return to;
27
+ };
28
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
29
+ // If the importer is in node compatibility mode or this is not an ESM
30
+ // file that has been converted to a CommonJS file using a Babel-
31
+ // compatible transform (i.e. "__esModule" has not been set), then set
32
+ // "default" to the CommonJS "module.exports" for node compatibility.
33
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
34
+ mod
35
+ ));
36
+
37
+ // node_modules/ws/lib/constants.js
38
+ var require_constants = __commonJS({
39
+ "node_modules/ws/lib/constants.js"(exports, module) {
40
+ "use strict";
41
+ var BINARY_TYPES = ["nodebuffer", "arraybuffer", "fragments"];
42
+ var hasBlob = typeof Blob !== "undefined";
43
+ if (hasBlob) BINARY_TYPES.push("blob");
44
+ module.exports = {
45
+ BINARY_TYPES,
46
+ CLOSE_TIMEOUT: 3e4,
47
+ EMPTY_BUFFER: Buffer.alloc(0),
48
+ GUID: "258EAFA5-E914-47DA-95CA-C5AB0DC85B11",
49
+ hasBlob,
50
+ kForOnEventAttribute: /* @__PURE__ */ Symbol("kIsForOnEventAttribute"),
51
+ kListener: /* @__PURE__ */ Symbol("kListener"),
52
+ kStatusCode: /* @__PURE__ */ Symbol("status-code"),
53
+ kWebSocket: /* @__PURE__ */ Symbol("websocket"),
54
+ NOOP: () => {
55
+ }
56
+ };
57
+ }
58
+ });
59
+
60
+ // node_modules/ws/lib/buffer-util.js
61
+ var require_buffer_util = __commonJS({
62
+ "node_modules/ws/lib/buffer-util.js"(exports, module) {
63
+ "use strict";
64
+ var { EMPTY_BUFFER } = require_constants();
65
+ var FastBuffer = Buffer[Symbol.species];
66
+ function concat(list, totalLength) {
67
+ if (list.length === 0) return EMPTY_BUFFER;
68
+ if (list.length === 1) return list[0];
69
+ const target = Buffer.allocUnsafe(totalLength);
70
+ let offset = 0;
71
+ for (let i = 0; i < list.length; i++) {
72
+ const buf = list[i];
73
+ target.set(buf, offset);
74
+ offset += buf.length;
75
+ }
76
+ if (offset < totalLength) {
77
+ return new FastBuffer(target.buffer, target.byteOffset, offset);
78
+ }
79
+ return target;
80
+ }
81
+ function _mask(source, mask, output, offset, length) {
82
+ for (let i = 0; i < length; i++) {
83
+ output[offset + i] = source[i] ^ mask[i & 3];
84
+ }
85
+ }
86
+ function _unmask(buffer, mask) {
87
+ for (let i = 0; i < buffer.length; i++) {
88
+ buffer[i] ^= mask[i & 3];
89
+ }
90
+ }
91
+ function toArrayBuffer(buf) {
92
+ if (buf.length === buf.buffer.byteLength) {
93
+ return buf.buffer;
94
+ }
95
+ return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length);
96
+ }
97
+ function toBuffer(data) {
98
+ toBuffer.readOnly = true;
99
+ if (Buffer.isBuffer(data)) return data;
100
+ let buf;
101
+ if (data instanceof ArrayBuffer) {
102
+ buf = new FastBuffer(data);
103
+ } else if (ArrayBuffer.isView(data)) {
104
+ buf = new FastBuffer(data.buffer, data.byteOffset, data.byteLength);
105
+ } else {
106
+ buf = Buffer.from(data);
107
+ toBuffer.readOnly = false;
108
+ }
109
+ return buf;
110
+ }
111
+ module.exports = {
112
+ concat,
113
+ mask: _mask,
114
+ toArrayBuffer,
115
+ toBuffer,
116
+ unmask: _unmask
117
+ };
118
+ if (!process.env.WS_NO_BUFFER_UTIL) {
119
+ try {
120
+ const bufferUtil = __require("bufferutil");
121
+ module.exports.mask = function(source, mask, output, offset, length) {
122
+ if (length < 48) _mask(source, mask, output, offset, length);
123
+ else bufferUtil.mask(source, mask, output, offset, length);
124
+ };
125
+ module.exports.unmask = function(buffer, mask) {
126
+ if (buffer.length < 32) _unmask(buffer, mask);
127
+ else bufferUtil.unmask(buffer, mask);
128
+ };
129
+ } catch (e) {
130
+ }
131
+ }
132
+ }
133
+ });
134
+
135
+ // node_modules/ws/lib/limiter.js
136
+ var require_limiter = __commonJS({
137
+ "node_modules/ws/lib/limiter.js"(exports, module) {
138
+ "use strict";
139
+ var kDone = /* @__PURE__ */ Symbol("kDone");
140
+ var kRun = /* @__PURE__ */ Symbol("kRun");
141
+ var Limiter = class {
142
+ /**
143
+ * Creates a new `Limiter`.
144
+ *
145
+ * @param {Number} [concurrency=Infinity] The maximum number of jobs allowed
146
+ * to run concurrently
147
+ */
148
+ constructor(concurrency) {
149
+ this[kDone] = () => {
150
+ this.pending--;
151
+ this[kRun]();
152
+ };
153
+ this.concurrency = concurrency || Infinity;
154
+ this.jobs = [];
155
+ this.pending = 0;
156
+ }
157
+ /**
158
+ * Adds a job to the queue.
159
+ *
160
+ * @param {Function} job The job to run
161
+ * @public
162
+ */
163
+ add(job) {
164
+ this.jobs.push(job);
165
+ this[kRun]();
166
+ }
167
+ /**
168
+ * Removes a job from the queue and runs it if possible.
169
+ *
170
+ * @private
171
+ */
172
+ [kRun]() {
173
+ if (this.pending === this.concurrency) return;
174
+ if (this.jobs.length) {
175
+ const job = this.jobs.shift();
176
+ this.pending++;
177
+ job(this[kDone]);
178
+ }
179
+ }
180
+ };
181
+ module.exports = Limiter;
182
+ }
183
+ });
184
+
185
+ // node_modules/ws/lib/permessage-deflate.js
186
+ var require_permessage_deflate = __commonJS({
187
+ "node_modules/ws/lib/permessage-deflate.js"(exports, module) {
188
+ "use strict";
189
+ var zlib = __require("zlib");
190
+ var bufferUtil = require_buffer_util();
191
+ var Limiter = require_limiter();
192
+ var { kStatusCode } = require_constants();
193
+ var FastBuffer = Buffer[Symbol.species];
194
+ var TRAILER = Buffer.from([0, 0, 255, 255]);
195
+ var kPerMessageDeflate = /* @__PURE__ */ Symbol("permessage-deflate");
196
+ var kTotalLength = /* @__PURE__ */ Symbol("total-length");
197
+ var kCallback = /* @__PURE__ */ Symbol("callback");
198
+ var kBuffers = /* @__PURE__ */ Symbol("buffers");
199
+ var kError = /* @__PURE__ */ Symbol("error");
200
+ var zlibLimiter;
201
+ var PerMessageDeflate2 = class {
202
+ /**
203
+ * Creates a PerMessageDeflate instance.
204
+ *
205
+ * @param {Object} [options] Configuration options
206
+ * @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support
207
+ * for, or request, a custom client window size
208
+ * @param {Boolean} [options.clientNoContextTakeover=false] Advertise/
209
+ * acknowledge disabling of client context takeover
210
+ * @param {Number} [options.concurrencyLimit=10] The number of concurrent
211
+ * calls to zlib
212
+ * @param {Boolean} [options.isServer=false] Create the instance in either
213
+ * server or client mode
214
+ * @param {Number} [options.maxPayload=0] The maximum allowed message length
215
+ * @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the
216
+ * use of a custom server window size
217
+ * @param {Boolean} [options.serverNoContextTakeover=false] Request/accept
218
+ * disabling of server context takeover
219
+ * @param {Number} [options.threshold=1024] Size (in bytes) below which
220
+ * messages should not be compressed if context takeover is disabled
221
+ * @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on
222
+ * deflate
223
+ * @param {Object} [options.zlibInflateOptions] Options to pass to zlib on
224
+ * inflate
225
+ */
226
+ constructor(options) {
227
+ this._options = options || {};
228
+ this._threshold = this._options.threshold !== void 0 ? this._options.threshold : 1024;
229
+ this._maxPayload = this._options.maxPayload | 0;
230
+ this._isServer = !!this._options.isServer;
231
+ this._deflate = null;
232
+ this._inflate = null;
233
+ this.params = null;
234
+ if (!zlibLimiter) {
235
+ const concurrency = this._options.concurrencyLimit !== void 0 ? this._options.concurrencyLimit : 10;
236
+ zlibLimiter = new Limiter(concurrency);
237
+ }
238
+ }
239
+ /**
240
+ * @type {String}
241
+ */
242
+ static get extensionName() {
243
+ return "permessage-deflate";
244
+ }
245
+ /**
246
+ * Create an extension negotiation offer.
247
+ *
248
+ * @return {Object} Extension parameters
249
+ * @public
250
+ */
251
+ offer() {
252
+ const params = {};
253
+ if (this._options.serverNoContextTakeover) {
254
+ params.server_no_context_takeover = true;
255
+ }
256
+ if (this._options.clientNoContextTakeover) {
257
+ params.client_no_context_takeover = true;
258
+ }
259
+ if (this._options.serverMaxWindowBits) {
260
+ params.server_max_window_bits = this._options.serverMaxWindowBits;
261
+ }
262
+ if (this._options.clientMaxWindowBits) {
263
+ params.client_max_window_bits = this._options.clientMaxWindowBits;
264
+ } else if (this._options.clientMaxWindowBits == null) {
265
+ params.client_max_window_bits = true;
266
+ }
267
+ return params;
268
+ }
269
+ /**
270
+ * Accept an extension negotiation offer/response.
271
+ *
272
+ * @param {Array} configurations The extension negotiation offers/reponse
273
+ * @return {Object} Accepted configuration
274
+ * @public
275
+ */
276
+ accept(configurations) {
277
+ configurations = this.normalizeParams(configurations);
278
+ this.params = this._isServer ? this.acceptAsServer(configurations) : this.acceptAsClient(configurations);
279
+ return this.params;
280
+ }
281
+ /**
282
+ * Releases all resources used by the extension.
283
+ *
284
+ * @public
285
+ */
286
+ cleanup() {
287
+ if (this._inflate) {
288
+ this._inflate.close();
289
+ this._inflate = null;
290
+ }
291
+ if (this._deflate) {
292
+ const callback = this._deflate[kCallback];
293
+ this._deflate.close();
294
+ this._deflate = null;
295
+ if (callback) {
296
+ callback(
297
+ new Error(
298
+ "The deflate stream was closed while data was being processed"
299
+ )
300
+ );
301
+ }
302
+ }
303
+ }
304
+ /**
305
+ * Accept an extension negotiation offer.
306
+ *
307
+ * @param {Array} offers The extension negotiation offers
308
+ * @return {Object} Accepted configuration
309
+ * @private
310
+ */
311
+ acceptAsServer(offers) {
312
+ const opts = this._options;
313
+ const accepted = offers.find((params) => {
314
+ if (opts.serverNoContextTakeover === false && params.server_no_context_takeover || params.server_max_window_bits && (opts.serverMaxWindowBits === false || typeof opts.serverMaxWindowBits === "number" && opts.serverMaxWindowBits > params.server_max_window_bits) || typeof opts.clientMaxWindowBits === "number" && !params.client_max_window_bits) {
315
+ return false;
316
+ }
317
+ return true;
318
+ });
319
+ if (!accepted) {
320
+ throw new Error("None of the extension offers can be accepted");
321
+ }
322
+ if (opts.serverNoContextTakeover) {
323
+ accepted.server_no_context_takeover = true;
324
+ }
325
+ if (opts.clientNoContextTakeover) {
326
+ accepted.client_no_context_takeover = true;
327
+ }
328
+ if (typeof opts.serverMaxWindowBits === "number") {
329
+ accepted.server_max_window_bits = opts.serverMaxWindowBits;
330
+ }
331
+ if (typeof opts.clientMaxWindowBits === "number") {
332
+ accepted.client_max_window_bits = opts.clientMaxWindowBits;
333
+ } else if (accepted.client_max_window_bits === true || opts.clientMaxWindowBits === false) {
334
+ delete accepted.client_max_window_bits;
335
+ }
336
+ return accepted;
337
+ }
338
+ /**
339
+ * Accept the extension negotiation response.
340
+ *
341
+ * @param {Array} response The extension negotiation response
342
+ * @return {Object} Accepted configuration
343
+ * @private
344
+ */
345
+ acceptAsClient(response) {
346
+ const params = response[0];
347
+ if (this._options.clientNoContextTakeover === false && params.client_no_context_takeover) {
348
+ throw new Error('Unexpected parameter "client_no_context_takeover"');
349
+ }
350
+ if (!params.client_max_window_bits) {
351
+ if (typeof this._options.clientMaxWindowBits === "number") {
352
+ params.client_max_window_bits = this._options.clientMaxWindowBits;
353
+ }
354
+ } else if (this._options.clientMaxWindowBits === false || typeof this._options.clientMaxWindowBits === "number" && params.client_max_window_bits > this._options.clientMaxWindowBits) {
355
+ throw new Error(
356
+ 'Unexpected or invalid parameter "client_max_window_bits"'
357
+ );
358
+ }
359
+ return params;
360
+ }
361
+ /**
362
+ * Normalize parameters.
363
+ *
364
+ * @param {Array} configurations The extension negotiation offers/reponse
365
+ * @return {Array} The offers/response with normalized parameters
366
+ * @private
367
+ */
368
+ normalizeParams(configurations) {
369
+ configurations.forEach((params) => {
370
+ Object.keys(params).forEach((key) => {
371
+ let value = params[key];
372
+ if (value.length > 1) {
373
+ throw new Error(`Parameter "${key}" must have only a single value`);
374
+ }
375
+ value = value[0];
376
+ if (key === "client_max_window_bits") {
377
+ if (value !== true) {
378
+ const num = +value;
379
+ if (!Number.isInteger(num) || num < 8 || num > 15) {
380
+ throw new TypeError(
381
+ `Invalid value for parameter "${key}": ${value}`
382
+ );
383
+ }
384
+ value = num;
385
+ } else if (!this._isServer) {
386
+ throw new TypeError(
387
+ `Invalid value for parameter "${key}": ${value}`
388
+ );
389
+ }
390
+ } else if (key === "server_max_window_bits") {
391
+ const num = +value;
392
+ if (!Number.isInteger(num) || num < 8 || num > 15) {
393
+ throw new TypeError(
394
+ `Invalid value for parameter "${key}": ${value}`
395
+ );
396
+ }
397
+ value = num;
398
+ } else if (key === "client_no_context_takeover" || key === "server_no_context_takeover") {
399
+ if (value !== true) {
400
+ throw new TypeError(
401
+ `Invalid value for parameter "${key}": ${value}`
402
+ );
403
+ }
404
+ } else {
405
+ throw new Error(`Unknown parameter "${key}"`);
406
+ }
407
+ params[key] = value;
408
+ });
409
+ });
410
+ return configurations;
411
+ }
412
+ /**
413
+ * Decompress data. Concurrency limited.
414
+ *
415
+ * @param {Buffer} data Compressed data
416
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
417
+ * @param {Function} callback Callback
418
+ * @public
419
+ */
420
+ decompress(data, fin, callback) {
421
+ zlibLimiter.add((done) => {
422
+ this._decompress(data, fin, (err, result) => {
423
+ done();
424
+ callback(err, result);
425
+ });
426
+ });
427
+ }
428
+ /**
429
+ * Compress data. Concurrency limited.
430
+ *
431
+ * @param {(Buffer|String)} data Data to compress
432
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
433
+ * @param {Function} callback Callback
434
+ * @public
435
+ */
436
+ compress(data, fin, callback) {
437
+ zlibLimiter.add((done) => {
438
+ this._compress(data, fin, (err, result) => {
439
+ done();
440
+ callback(err, result);
441
+ });
442
+ });
443
+ }
444
+ /**
445
+ * Decompress data.
446
+ *
447
+ * @param {Buffer} data Compressed data
448
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
449
+ * @param {Function} callback Callback
450
+ * @private
451
+ */
452
+ _decompress(data, fin, callback) {
453
+ const endpoint = this._isServer ? "client" : "server";
454
+ if (!this._inflate) {
455
+ const key = `${endpoint}_max_window_bits`;
456
+ const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
457
+ this._inflate = zlib.createInflateRaw({
458
+ ...this._options.zlibInflateOptions,
459
+ windowBits
460
+ });
461
+ this._inflate[kPerMessageDeflate] = this;
462
+ this._inflate[kTotalLength] = 0;
463
+ this._inflate[kBuffers] = [];
464
+ this._inflate.on("error", inflateOnError);
465
+ this._inflate.on("data", inflateOnData);
466
+ }
467
+ this._inflate[kCallback] = callback;
468
+ this._inflate.write(data);
469
+ if (fin) this._inflate.write(TRAILER);
470
+ this._inflate.flush(() => {
471
+ const err = this._inflate[kError];
472
+ if (err) {
473
+ this._inflate.close();
474
+ this._inflate = null;
475
+ callback(err);
476
+ return;
477
+ }
478
+ const data2 = bufferUtil.concat(
479
+ this._inflate[kBuffers],
480
+ this._inflate[kTotalLength]
481
+ );
482
+ if (this._inflate._readableState.endEmitted) {
483
+ this._inflate.close();
484
+ this._inflate = null;
485
+ } else {
486
+ this._inflate[kTotalLength] = 0;
487
+ this._inflate[kBuffers] = [];
488
+ if (fin && this.params[`${endpoint}_no_context_takeover`]) {
489
+ this._inflate.reset();
490
+ }
491
+ }
492
+ callback(null, data2);
493
+ });
494
+ }
495
+ /**
496
+ * Compress data.
497
+ *
498
+ * @param {(Buffer|String)} data Data to compress
499
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
500
+ * @param {Function} callback Callback
501
+ * @private
502
+ */
503
+ _compress(data, fin, callback) {
504
+ const endpoint = this._isServer ? "server" : "client";
505
+ if (!this._deflate) {
506
+ const key = `${endpoint}_max_window_bits`;
507
+ const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
508
+ this._deflate = zlib.createDeflateRaw({
509
+ ...this._options.zlibDeflateOptions,
510
+ windowBits
511
+ });
512
+ this._deflate[kTotalLength] = 0;
513
+ this._deflate[kBuffers] = [];
514
+ this._deflate.on("data", deflateOnData);
515
+ }
516
+ this._deflate[kCallback] = callback;
517
+ this._deflate.write(data);
518
+ this._deflate.flush(zlib.Z_SYNC_FLUSH, () => {
519
+ if (!this._deflate) {
520
+ return;
521
+ }
522
+ let data2 = bufferUtil.concat(
523
+ this._deflate[kBuffers],
524
+ this._deflate[kTotalLength]
525
+ );
526
+ if (fin) {
527
+ data2 = new FastBuffer(data2.buffer, data2.byteOffset, data2.length - 4);
528
+ }
529
+ this._deflate[kCallback] = null;
530
+ this._deflate[kTotalLength] = 0;
531
+ this._deflate[kBuffers] = [];
532
+ if (fin && this.params[`${endpoint}_no_context_takeover`]) {
533
+ this._deflate.reset();
534
+ }
535
+ callback(null, data2);
536
+ });
537
+ }
538
+ };
539
+ module.exports = PerMessageDeflate2;
540
+ function deflateOnData(chunk) {
541
+ this[kBuffers].push(chunk);
542
+ this[kTotalLength] += chunk.length;
543
+ }
544
+ function inflateOnData(chunk) {
545
+ this[kTotalLength] += chunk.length;
546
+ if (this[kPerMessageDeflate]._maxPayload < 1 || this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload) {
547
+ this[kBuffers].push(chunk);
548
+ return;
549
+ }
550
+ this[kError] = new RangeError("Max payload size exceeded");
551
+ this[kError].code = "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH";
552
+ this[kError][kStatusCode] = 1009;
553
+ this.removeListener("data", inflateOnData);
554
+ this.reset();
555
+ }
556
+ function inflateOnError(err) {
557
+ this[kPerMessageDeflate]._inflate = null;
558
+ if (this[kError]) {
559
+ this[kCallback](this[kError]);
560
+ return;
561
+ }
562
+ err[kStatusCode] = 1007;
563
+ this[kCallback](err);
564
+ }
565
+ }
566
+ });
567
+
568
+ // node_modules/ws/lib/validation.js
569
+ var require_validation = __commonJS({
570
+ "node_modules/ws/lib/validation.js"(exports, module) {
571
+ "use strict";
572
+ var { isUtf8 } = __require("buffer");
573
+ var { hasBlob } = require_constants();
574
+ var tokenChars = [
575
+ 0,
576
+ 0,
577
+ 0,
578
+ 0,
579
+ 0,
580
+ 0,
581
+ 0,
582
+ 0,
583
+ 0,
584
+ 0,
585
+ 0,
586
+ 0,
587
+ 0,
588
+ 0,
589
+ 0,
590
+ 0,
591
+ // 0 - 15
592
+ 0,
593
+ 0,
594
+ 0,
595
+ 0,
596
+ 0,
597
+ 0,
598
+ 0,
599
+ 0,
600
+ 0,
601
+ 0,
602
+ 0,
603
+ 0,
604
+ 0,
605
+ 0,
606
+ 0,
607
+ 0,
608
+ // 16 - 31
609
+ 0,
610
+ 1,
611
+ 0,
612
+ 1,
613
+ 1,
614
+ 1,
615
+ 1,
616
+ 1,
617
+ 0,
618
+ 0,
619
+ 1,
620
+ 1,
621
+ 0,
622
+ 1,
623
+ 1,
624
+ 0,
625
+ // 32 - 47
626
+ 1,
627
+ 1,
628
+ 1,
629
+ 1,
630
+ 1,
631
+ 1,
632
+ 1,
633
+ 1,
634
+ 1,
635
+ 1,
636
+ 0,
637
+ 0,
638
+ 0,
639
+ 0,
640
+ 0,
641
+ 0,
642
+ // 48 - 63
643
+ 0,
644
+ 1,
645
+ 1,
646
+ 1,
647
+ 1,
648
+ 1,
649
+ 1,
650
+ 1,
651
+ 1,
652
+ 1,
653
+ 1,
654
+ 1,
655
+ 1,
656
+ 1,
657
+ 1,
658
+ 1,
659
+ // 64 - 79
660
+ 1,
661
+ 1,
662
+ 1,
663
+ 1,
664
+ 1,
665
+ 1,
666
+ 1,
667
+ 1,
668
+ 1,
669
+ 1,
670
+ 1,
671
+ 0,
672
+ 0,
673
+ 0,
674
+ 1,
675
+ 1,
676
+ // 80 - 95
677
+ 1,
678
+ 1,
679
+ 1,
680
+ 1,
681
+ 1,
682
+ 1,
683
+ 1,
684
+ 1,
685
+ 1,
686
+ 1,
687
+ 1,
688
+ 1,
689
+ 1,
690
+ 1,
691
+ 1,
692
+ 1,
693
+ // 96 - 111
694
+ 1,
695
+ 1,
696
+ 1,
697
+ 1,
698
+ 1,
699
+ 1,
700
+ 1,
701
+ 1,
702
+ 1,
703
+ 1,
704
+ 1,
705
+ 0,
706
+ 1,
707
+ 0,
708
+ 1,
709
+ 0
710
+ // 112 - 127
711
+ ];
712
+ function isValidStatusCode(code) {
713
+ return code >= 1e3 && code <= 1014 && code !== 1004 && code !== 1005 && code !== 1006 || code >= 3e3 && code <= 4999;
714
+ }
715
+ function _isValidUTF8(buf) {
716
+ const len = buf.length;
717
+ let i = 0;
718
+ while (i < len) {
719
+ if ((buf[i] & 128) === 0) {
720
+ i++;
721
+ } else if ((buf[i] & 224) === 192) {
722
+ if (i + 1 === len || (buf[i + 1] & 192) !== 128 || (buf[i] & 254) === 192) {
723
+ return false;
724
+ }
725
+ i += 2;
726
+ } else if ((buf[i] & 240) === 224) {
727
+ if (i + 2 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || buf[i] === 224 && (buf[i + 1] & 224) === 128 || // Overlong
728
+ buf[i] === 237 && (buf[i + 1] & 224) === 160) {
729
+ return false;
730
+ }
731
+ i += 3;
732
+ } else if ((buf[i] & 248) === 240) {
733
+ 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
734
+ buf[i] === 244 && buf[i + 1] > 143 || buf[i] > 244) {
735
+ return false;
736
+ }
737
+ i += 4;
738
+ } else {
739
+ return false;
740
+ }
741
+ }
742
+ return true;
743
+ }
744
+ function isBlob(value) {
745
+ 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");
746
+ }
747
+ module.exports = {
748
+ isBlob,
749
+ isValidStatusCode,
750
+ isValidUTF8: _isValidUTF8,
751
+ tokenChars
752
+ };
753
+ if (isUtf8) {
754
+ module.exports.isValidUTF8 = function(buf) {
755
+ return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf);
756
+ };
757
+ } else if (!process.env.WS_NO_UTF_8_VALIDATE) {
758
+ try {
759
+ const isValidUTF8 = __require("utf-8-validate");
760
+ module.exports.isValidUTF8 = function(buf) {
761
+ return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf);
762
+ };
763
+ } catch (e) {
764
+ }
765
+ }
766
+ }
767
+ });
768
+
769
+ // node_modules/ws/lib/receiver.js
770
+ var require_receiver = __commonJS({
771
+ "node_modules/ws/lib/receiver.js"(exports, module) {
772
+ "use strict";
773
+ var { Writable } = __require("stream");
774
+ var PerMessageDeflate2 = require_permessage_deflate();
775
+ var {
776
+ BINARY_TYPES,
777
+ EMPTY_BUFFER,
778
+ kStatusCode,
779
+ kWebSocket
780
+ } = require_constants();
781
+ var { concat, toArrayBuffer, unmask } = require_buffer_util();
782
+ var { isValidStatusCode, isValidUTF8 } = require_validation();
783
+ var FastBuffer = Buffer[Symbol.species];
784
+ var GET_INFO = 0;
785
+ var GET_PAYLOAD_LENGTH_16 = 1;
786
+ var GET_PAYLOAD_LENGTH_64 = 2;
787
+ var GET_MASK = 3;
788
+ var GET_DATA = 4;
789
+ var INFLATING = 5;
790
+ var DEFER_EVENT = 6;
791
+ var Receiver2 = class extends Writable {
792
+ /**
793
+ * Creates a Receiver instance.
794
+ *
795
+ * @param {Object} [options] Options object
796
+ * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
797
+ * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
798
+ * multiple times in the same tick
799
+ * @param {String} [options.binaryType=nodebuffer] The type for binary data
800
+ * @param {Object} [options.extensions] An object containing the negotiated
801
+ * extensions
802
+ * @param {Boolean} [options.isServer=false] Specifies whether to operate in
803
+ * client or server mode
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._maxPayload = options.maxPayload | 0;
815
+ this._skipUTF8Validation = !!options.skipUTF8Validation;
816
+ this[kWebSocket] = void 0;
817
+ this._bufferedBytes = 0;
818
+ this._buffers = [];
819
+ this._compressed = false;
820
+ this._payloadLength = 0;
821
+ this._mask = void 0;
822
+ this._fragmented = 0;
823
+ this._masked = false;
824
+ this._fin = false;
825
+ this._opcode = 0;
826
+ this._totalPayloadLength = 0;
827
+ this._messageLength = 0;
828
+ this._fragments = [];
829
+ this._errored = false;
830
+ this._loop = false;
831
+ this._state = GET_INFO;
832
+ }
833
+ /**
834
+ * Implements `Writable.prototype._write()`.
835
+ *
836
+ * @param {Buffer} chunk The chunk of data to write
837
+ * @param {String} encoding The character encoding of `chunk`
838
+ * @param {Function} cb Callback
839
+ * @private
840
+ */
841
+ _write(chunk, encoding, cb) {
842
+ if (this._opcode === 8 && this._state == GET_INFO) return cb();
843
+ this._bufferedBytes += chunk.length;
844
+ this._buffers.push(chunk);
845
+ this.startLoop(cb);
846
+ }
847
+ /**
848
+ * Consumes `n` bytes from the buffered data.
849
+ *
850
+ * @param {Number} n The number of bytes to consume
851
+ * @return {Buffer} The consumed bytes
852
+ * @private
853
+ */
854
+ consume(n) {
855
+ this._bufferedBytes -= n;
856
+ if (n === this._buffers[0].length) return this._buffers.shift();
857
+ if (n < this._buffers[0].length) {
858
+ const buf = this._buffers[0];
859
+ this._buffers[0] = new FastBuffer(
860
+ buf.buffer,
861
+ buf.byteOffset + n,
862
+ buf.length - n
863
+ );
864
+ return new FastBuffer(buf.buffer, buf.byteOffset, n);
865
+ }
866
+ const dst = Buffer.allocUnsafe(n);
867
+ do {
868
+ const buf = this._buffers[0];
869
+ const offset = dst.length - n;
870
+ if (n >= buf.length) {
871
+ dst.set(this._buffers.shift(), offset);
872
+ } else {
873
+ dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset);
874
+ this._buffers[0] = new FastBuffer(
875
+ buf.buffer,
876
+ buf.byteOffset + n,
877
+ buf.length - n
878
+ );
879
+ }
880
+ n -= buf.length;
881
+ } while (n > 0);
882
+ return dst;
883
+ }
884
+ /**
885
+ * Starts the parsing loop.
886
+ *
887
+ * @param {Function} cb Callback
888
+ * @private
889
+ */
890
+ startLoop(cb) {
891
+ this._loop = true;
892
+ do {
893
+ switch (this._state) {
894
+ case GET_INFO:
895
+ this.getInfo(cb);
896
+ break;
897
+ case GET_PAYLOAD_LENGTH_16:
898
+ this.getPayloadLength16(cb);
899
+ break;
900
+ case GET_PAYLOAD_LENGTH_64:
901
+ this.getPayloadLength64(cb);
902
+ break;
903
+ case GET_MASK:
904
+ this.getMask();
905
+ break;
906
+ case GET_DATA:
907
+ this.getData(cb);
908
+ break;
909
+ case INFLATING:
910
+ case DEFER_EVENT:
911
+ this._loop = false;
912
+ return;
913
+ }
914
+ } while (this._loop);
915
+ if (!this._errored) cb();
916
+ }
917
+ /**
918
+ * Reads the first two bytes of a frame.
919
+ *
920
+ * @param {Function} cb Callback
921
+ * @private
922
+ */
923
+ getInfo(cb) {
924
+ if (this._bufferedBytes < 2) {
925
+ this._loop = false;
926
+ return;
927
+ }
928
+ const buf = this.consume(2);
929
+ if ((buf[0] & 48) !== 0) {
930
+ const error = this.createError(
931
+ RangeError,
932
+ "RSV2 and RSV3 must be clear",
933
+ true,
934
+ 1002,
935
+ "WS_ERR_UNEXPECTED_RSV_2_3"
936
+ );
937
+ cb(error);
938
+ return;
939
+ }
940
+ const compressed = (buf[0] & 64) === 64;
941
+ if (compressed && !this._extensions[PerMessageDeflate2.extensionName]) {
942
+ const error = this.createError(
943
+ RangeError,
944
+ "RSV1 must be clear",
945
+ true,
946
+ 1002,
947
+ "WS_ERR_UNEXPECTED_RSV_1"
948
+ );
949
+ cb(error);
950
+ return;
951
+ }
952
+ this._fin = (buf[0] & 128) === 128;
953
+ this._opcode = buf[0] & 15;
954
+ this._payloadLength = buf[1] & 127;
955
+ if (this._opcode === 0) {
956
+ if (compressed) {
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
+ if (!this._fragmented) {
968
+ const error = this.createError(
969
+ RangeError,
970
+ "invalid opcode 0",
971
+ true,
972
+ 1002,
973
+ "WS_ERR_INVALID_OPCODE"
974
+ );
975
+ cb(error);
976
+ return;
977
+ }
978
+ this._opcode = this._fragmented;
979
+ } else if (this._opcode === 1 || this._opcode === 2) {
980
+ if (this._fragmented) {
981
+ const error = this.createError(
982
+ RangeError,
983
+ `invalid opcode ${this._opcode}`,
984
+ true,
985
+ 1002,
986
+ "WS_ERR_INVALID_OPCODE"
987
+ );
988
+ cb(error);
989
+ return;
990
+ }
991
+ this._compressed = compressed;
992
+ } else if (this._opcode > 7 && this._opcode < 11) {
993
+ if (!this._fin) {
994
+ const error = this.createError(
995
+ RangeError,
996
+ "FIN must be set",
997
+ true,
998
+ 1002,
999
+ "WS_ERR_EXPECTED_FIN"
1000
+ );
1001
+ cb(error);
1002
+ return;
1003
+ }
1004
+ if (compressed) {
1005
+ const error = this.createError(
1006
+ RangeError,
1007
+ "RSV1 must be clear",
1008
+ true,
1009
+ 1002,
1010
+ "WS_ERR_UNEXPECTED_RSV_1"
1011
+ );
1012
+ cb(error);
1013
+ return;
1014
+ }
1015
+ if (this._payloadLength > 125 || this._opcode === 8 && this._payloadLength === 1) {
1016
+ const error = this.createError(
1017
+ RangeError,
1018
+ `invalid payload length ${this._payloadLength}`,
1019
+ true,
1020
+ 1002,
1021
+ "WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH"
1022
+ );
1023
+ cb(error);
1024
+ return;
1025
+ }
1026
+ } else {
1027
+ const error = this.createError(
1028
+ RangeError,
1029
+ `invalid opcode ${this._opcode}`,
1030
+ true,
1031
+ 1002,
1032
+ "WS_ERR_INVALID_OPCODE"
1033
+ );
1034
+ cb(error);
1035
+ return;
1036
+ }
1037
+ if (!this._fin && !this._fragmented) this._fragmented = this._opcode;
1038
+ this._masked = (buf[1] & 128) === 128;
1039
+ if (this._isServer) {
1040
+ if (!this._masked) {
1041
+ const error = this.createError(
1042
+ RangeError,
1043
+ "MASK must be set",
1044
+ true,
1045
+ 1002,
1046
+ "WS_ERR_EXPECTED_MASK"
1047
+ );
1048
+ cb(error);
1049
+ return;
1050
+ }
1051
+ } else if (this._masked) {
1052
+ const error = this.createError(
1053
+ RangeError,
1054
+ "MASK must be clear",
1055
+ true,
1056
+ 1002,
1057
+ "WS_ERR_UNEXPECTED_MASK"
1058
+ );
1059
+ cb(error);
1060
+ return;
1061
+ }
1062
+ if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16;
1063
+ else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64;
1064
+ else this.haveLength(cb);
1065
+ }
1066
+ /**
1067
+ * Gets extended payload length (7+16).
1068
+ *
1069
+ * @param {Function} cb Callback
1070
+ * @private
1071
+ */
1072
+ getPayloadLength16(cb) {
1073
+ if (this._bufferedBytes < 2) {
1074
+ this._loop = false;
1075
+ return;
1076
+ }
1077
+ this._payloadLength = this.consume(2).readUInt16BE(0);
1078
+ this.haveLength(cb);
1079
+ }
1080
+ /**
1081
+ * Gets extended payload length (7+64).
1082
+ *
1083
+ * @param {Function} cb Callback
1084
+ * @private
1085
+ */
1086
+ getPayloadLength64(cb) {
1087
+ if (this._bufferedBytes < 8) {
1088
+ this._loop = false;
1089
+ return;
1090
+ }
1091
+ const buf = this.consume(8);
1092
+ const num = buf.readUInt32BE(0);
1093
+ if (num > Math.pow(2, 53 - 32) - 1) {
1094
+ const error = this.createError(
1095
+ RangeError,
1096
+ "Unsupported WebSocket frame: payload length > 2^53 - 1",
1097
+ false,
1098
+ 1009,
1099
+ "WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH"
1100
+ );
1101
+ cb(error);
1102
+ return;
1103
+ }
1104
+ this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4);
1105
+ this.haveLength(cb);
1106
+ }
1107
+ /**
1108
+ * Payload length has been read.
1109
+ *
1110
+ * @param {Function} cb Callback
1111
+ * @private
1112
+ */
1113
+ haveLength(cb) {
1114
+ if (this._payloadLength && this._opcode < 8) {
1115
+ this._totalPayloadLength += this._payloadLength;
1116
+ if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) {
1117
+ const error = this.createError(
1118
+ RangeError,
1119
+ "Max payload size exceeded",
1120
+ false,
1121
+ 1009,
1122
+ "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"
1123
+ );
1124
+ cb(error);
1125
+ return;
1126
+ }
1127
+ }
1128
+ if (this._masked) this._state = GET_MASK;
1129
+ else this._state = GET_DATA;
1130
+ }
1131
+ /**
1132
+ * Reads mask bytes.
1133
+ *
1134
+ * @private
1135
+ */
1136
+ getMask() {
1137
+ if (this._bufferedBytes < 4) {
1138
+ this._loop = false;
1139
+ return;
1140
+ }
1141
+ this._mask = this.consume(4);
1142
+ this._state = GET_DATA;
1143
+ }
1144
+ /**
1145
+ * Reads data bytes.
1146
+ *
1147
+ * @param {Function} cb Callback
1148
+ * @private
1149
+ */
1150
+ getData(cb) {
1151
+ let data = EMPTY_BUFFER;
1152
+ if (this._payloadLength) {
1153
+ if (this._bufferedBytes < this._payloadLength) {
1154
+ this._loop = false;
1155
+ return;
1156
+ }
1157
+ data = this.consume(this._payloadLength);
1158
+ if (this._masked && (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0) {
1159
+ unmask(data, this._mask);
1160
+ }
1161
+ }
1162
+ if (this._opcode > 7) {
1163
+ this.controlMessage(data, cb);
1164
+ return;
1165
+ }
1166
+ if (this._compressed) {
1167
+ this._state = INFLATING;
1168
+ this.decompress(data, cb);
1169
+ return;
1170
+ }
1171
+ if (data.length) {
1172
+ this._messageLength = this._totalPayloadLength;
1173
+ this._fragments.push(data);
1174
+ }
1175
+ this.dataMessage(cb);
1176
+ }
1177
+ /**
1178
+ * Decompresses data.
1179
+ *
1180
+ * @param {Buffer} data Compressed data
1181
+ * @param {Function} cb Callback
1182
+ * @private
1183
+ */
1184
+ decompress(data, cb) {
1185
+ const perMessageDeflate = this._extensions[PerMessageDeflate2.extensionName];
1186
+ perMessageDeflate.decompress(data, this._fin, (err, buf) => {
1187
+ if (err) return cb(err);
1188
+ if (buf.length) {
1189
+ this._messageLength += buf.length;
1190
+ if (this._messageLength > this._maxPayload && this._maxPayload > 0) {
1191
+ const error = this.createError(
1192
+ RangeError,
1193
+ "Max payload size exceeded",
1194
+ false,
1195
+ 1009,
1196
+ "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"
1197
+ );
1198
+ cb(error);
1199
+ return;
1200
+ }
1201
+ this._fragments.push(buf);
1202
+ }
1203
+ this.dataMessage(cb);
1204
+ if (this._state === GET_INFO) this.startLoop(cb);
1205
+ });
1206
+ }
1207
+ /**
1208
+ * Handles a data message.
1209
+ *
1210
+ * @param {Function} cb Callback
1211
+ * @private
1212
+ */
1213
+ dataMessage(cb) {
1214
+ if (!this._fin) {
1215
+ this._state = GET_INFO;
1216
+ return;
1217
+ }
1218
+ const messageLength = this._messageLength;
1219
+ const fragments = this._fragments;
1220
+ this._totalPayloadLength = 0;
1221
+ this._messageLength = 0;
1222
+ this._fragmented = 0;
1223
+ this._fragments = [];
1224
+ if (this._opcode === 2) {
1225
+ let data;
1226
+ if (this._binaryType === "nodebuffer") {
1227
+ data = concat(fragments, messageLength);
1228
+ } else if (this._binaryType === "arraybuffer") {
1229
+ data = toArrayBuffer(concat(fragments, messageLength));
1230
+ } else if (this._binaryType === "blob") {
1231
+ data = new Blob(fragments);
1232
+ } else {
1233
+ data = fragments;
1234
+ }
1235
+ if (this._allowSynchronousEvents) {
1236
+ this.emit("message", data, true);
1237
+ this._state = GET_INFO;
1238
+ } else {
1239
+ this._state = DEFER_EVENT;
1240
+ setImmediate(() => {
1241
+ this.emit("message", data, true);
1242
+ this._state = GET_INFO;
1243
+ this.startLoop(cb);
1244
+ });
1245
+ }
1246
+ } else {
1247
+ const buf = concat(fragments, messageLength);
1248
+ if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
1249
+ const error = this.createError(
1250
+ Error,
1251
+ "invalid UTF-8 sequence",
1252
+ true,
1253
+ 1007,
1254
+ "WS_ERR_INVALID_UTF8"
1255
+ );
1256
+ cb(error);
1257
+ return;
1258
+ }
1259
+ if (this._state === INFLATING || this._allowSynchronousEvents) {
1260
+ this.emit("message", buf, false);
1261
+ this._state = GET_INFO;
1262
+ } else {
1263
+ this._state = DEFER_EVENT;
1264
+ setImmediate(() => {
1265
+ this.emit("message", buf, false);
1266
+ this._state = GET_INFO;
1267
+ this.startLoop(cb);
1268
+ });
1269
+ }
1270
+ }
1271
+ }
1272
+ /**
1273
+ * Handles a control message.
1274
+ *
1275
+ * @param {Buffer} data Data to handle
1276
+ * @return {(Error|RangeError|undefined)} A possible error
1277
+ * @private
1278
+ */
1279
+ controlMessage(data, cb) {
1280
+ if (this._opcode === 8) {
1281
+ if (data.length === 0) {
1282
+ this._loop = false;
1283
+ this.emit("conclude", 1005, EMPTY_BUFFER);
1284
+ this.end();
1285
+ } else {
1286
+ const code = data.readUInt16BE(0);
1287
+ if (!isValidStatusCode(code)) {
1288
+ const error = this.createError(
1289
+ RangeError,
1290
+ `invalid status code ${code}`,
1291
+ true,
1292
+ 1002,
1293
+ "WS_ERR_INVALID_CLOSE_CODE"
1294
+ );
1295
+ cb(error);
1296
+ return;
1297
+ }
1298
+ const buf = new FastBuffer(
1299
+ data.buffer,
1300
+ data.byteOffset + 2,
1301
+ data.length - 2
1302
+ );
1303
+ if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
1304
+ const error = this.createError(
1305
+ Error,
1306
+ "invalid UTF-8 sequence",
1307
+ true,
1308
+ 1007,
1309
+ "WS_ERR_INVALID_UTF8"
1310
+ );
1311
+ cb(error);
1312
+ return;
1313
+ }
1314
+ this._loop = false;
1315
+ this.emit("conclude", code, buf);
1316
+ this.end();
1317
+ }
1318
+ this._state = GET_INFO;
1319
+ return;
1320
+ }
1321
+ if (this._allowSynchronousEvents) {
1322
+ this.emit(this._opcode === 9 ? "ping" : "pong", data);
1323
+ this._state = GET_INFO;
1324
+ } else {
1325
+ this._state = DEFER_EVENT;
1326
+ setImmediate(() => {
1327
+ this.emit(this._opcode === 9 ? "ping" : "pong", data);
1328
+ this._state = GET_INFO;
1329
+ this.startLoop(cb);
1330
+ });
1331
+ }
1332
+ }
1333
+ /**
1334
+ * Builds an error object.
1335
+ *
1336
+ * @param {function(new:Error|RangeError)} ErrorCtor The error constructor
1337
+ * @param {String} message The error message
1338
+ * @param {Boolean} prefix Specifies whether or not to add a default prefix to
1339
+ * `message`
1340
+ * @param {Number} statusCode The status code
1341
+ * @param {String} errorCode The exposed error code
1342
+ * @return {(Error|RangeError)} The error
1343
+ * @private
1344
+ */
1345
+ createError(ErrorCtor, message, prefix, statusCode, errorCode) {
1346
+ this._loop = false;
1347
+ this._errored = true;
1348
+ const err = new ErrorCtor(
1349
+ prefix ? `Invalid WebSocket frame: ${message}` : message
1350
+ );
1351
+ Error.captureStackTrace(err, this.createError);
1352
+ err.code = errorCode;
1353
+ err[kStatusCode] = statusCode;
1354
+ return err;
1355
+ }
1356
+ };
1357
+ module.exports = Receiver2;
1358
+ }
1359
+ });
1360
+
1361
+ // node_modules/ws/lib/sender.js
1362
+ var require_sender = __commonJS({
1363
+ "node_modules/ws/lib/sender.js"(exports, module) {
1364
+ "use strict";
1365
+ var { Duplex } = __require("stream");
1366
+ var { randomFillSync } = __require("crypto");
1367
+ var PerMessageDeflate2 = require_permessage_deflate();
1368
+ var { EMPTY_BUFFER, kWebSocket, NOOP } = require_constants();
1369
+ var { isBlob, isValidStatusCode } = require_validation();
1370
+ var { mask: applyMask, toBuffer } = require_buffer_util();
1371
+ var kByteLength = /* @__PURE__ */ Symbol("kByteLength");
1372
+ var maskBuffer = Buffer.alloc(4);
1373
+ var RANDOM_POOL_SIZE = 8 * 1024;
1374
+ var randomPool;
1375
+ var randomPoolPointer = RANDOM_POOL_SIZE;
1376
+ var DEFAULT = 0;
1377
+ var DEFLATING = 1;
1378
+ var GET_BLOB_DATA = 2;
1379
+ var Sender2 = class _Sender {
1380
+ /**
1381
+ * Creates a Sender instance.
1382
+ *
1383
+ * @param {Duplex} socket The connection socket
1384
+ * @param {Object} [extensions] An object containing the negotiated extensions
1385
+ * @param {Function} [generateMask] The function used to generate the masking
1386
+ * key
1387
+ */
1388
+ constructor(socket, extensions, generateMask) {
1389
+ this._extensions = extensions || {};
1390
+ if (generateMask) {
1391
+ this._generateMask = generateMask;
1392
+ this._maskBuffer = Buffer.alloc(4);
1393
+ }
1394
+ this._socket = socket;
1395
+ this._firstFragment = true;
1396
+ this._compress = false;
1397
+ this._bufferedBytes = 0;
1398
+ this._queue = [];
1399
+ this._state = DEFAULT;
1400
+ this.onerror = NOOP;
1401
+ this[kWebSocket] = void 0;
1402
+ }
1403
+ /**
1404
+ * Frames a piece of data according to the HyBi WebSocket protocol.
1405
+ *
1406
+ * @param {(Buffer|String)} data The data to frame
1407
+ * @param {Object} options Options object
1408
+ * @param {Boolean} [options.fin=false] Specifies whether or not to set the
1409
+ * FIN bit
1410
+ * @param {Function} [options.generateMask] The function used to generate the
1411
+ * masking key
1412
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1413
+ * `data`
1414
+ * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
1415
+ * key
1416
+ * @param {Number} options.opcode The opcode
1417
+ * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
1418
+ * modified
1419
+ * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
1420
+ * RSV1 bit
1421
+ * @return {(Buffer|String)[]} The framed data
1422
+ * @public
1423
+ */
1424
+ static frame(data, options) {
1425
+ let mask;
1426
+ let merge = false;
1427
+ let offset = 2;
1428
+ let skipMasking = false;
1429
+ if (options.mask) {
1430
+ mask = options.maskBuffer || maskBuffer;
1431
+ if (options.generateMask) {
1432
+ options.generateMask(mask);
1433
+ } else {
1434
+ if (randomPoolPointer === RANDOM_POOL_SIZE) {
1435
+ if (randomPool === void 0) {
1436
+ randomPool = Buffer.alloc(RANDOM_POOL_SIZE);
1437
+ }
1438
+ randomFillSync(randomPool, 0, RANDOM_POOL_SIZE);
1439
+ randomPoolPointer = 0;
1440
+ }
1441
+ mask[0] = randomPool[randomPoolPointer++];
1442
+ mask[1] = randomPool[randomPoolPointer++];
1443
+ mask[2] = randomPool[randomPoolPointer++];
1444
+ mask[3] = randomPool[randomPoolPointer++];
1445
+ }
1446
+ skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0;
1447
+ offset = 6;
1448
+ }
1449
+ let dataLength;
1450
+ if (typeof data === "string") {
1451
+ if ((!options.mask || skipMasking) && options[kByteLength] !== void 0) {
1452
+ dataLength = options[kByteLength];
1453
+ } else {
1454
+ data = Buffer.from(data);
1455
+ dataLength = data.length;
1456
+ }
1457
+ } else {
1458
+ dataLength = data.length;
1459
+ merge = options.mask && options.readOnly && !skipMasking;
1460
+ }
1461
+ let payloadLength = dataLength;
1462
+ if (dataLength >= 65536) {
1463
+ offset += 8;
1464
+ payloadLength = 127;
1465
+ } else if (dataLength > 125) {
1466
+ offset += 2;
1467
+ payloadLength = 126;
1468
+ }
1469
+ const target = Buffer.allocUnsafe(merge ? dataLength + offset : offset);
1470
+ target[0] = options.fin ? options.opcode | 128 : options.opcode;
1471
+ if (options.rsv1) target[0] |= 64;
1472
+ target[1] = payloadLength;
1473
+ if (payloadLength === 126) {
1474
+ target.writeUInt16BE(dataLength, 2);
1475
+ } else if (payloadLength === 127) {
1476
+ target[2] = target[3] = 0;
1477
+ target.writeUIntBE(dataLength, 4, 6);
1478
+ }
1479
+ if (!options.mask) return [target, data];
1480
+ target[1] |= 128;
1481
+ target[offset - 4] = mask[0];
1482
+ target[offset - 3] = mask[1];
1483
+ target[offset - 2] = mask[2];
1484
+ target[offset - 1] = mask[3];
1485
+ if (skipMasking) return [target, data];
1486
+ if (merge) {
1487
+ applyMask(data, mask, target, offset, dataLength);
1488
+ return [target];
1489
+ }
1490
+ applyMask(data, mask, data, 0, dataLength);
1491
+ return [target, data];
1492
+ }
1493
+ /**
1494
+ * Sends a close message to the other peer.
1495
+ *
1496
+ * @param {Number} [code] The status code component of the body
1497
+ * @param {(String|Buffer)} [data] The message component of the body
1498
+ * @param {Boolean} [mask=false] Specifies whether or not to mask the message
1499
+ * @param {Function} [cb] Callback
1500
+ * @public
1501
+ */
1502
+ close(code, data, mask, cb) {
1503
+ let buf;
1504
+ if (code === void 0) {
1505
+ buf = EMPTY_BUFFER;
1506
+ } else if (typeof code !== "number" || !isValidStatusCode(code)) {
1507
+ throw new TypeError("First argument must be a valid error code number");
1508
+ } else if (data === void 0 || !data.length) {
1509
+ buf = Buffer.allocUnsafe(2);
1510
+ buf.writeUInt16BE(code, 0);
1511
+ } else {
1512
+ const length = Buffer.byteLength(data);
1513
+ if (length > 123) {
1514
+ throw new RangeError("The message must not be greater than 123 bytes");
1515
+ }
1516
+ buf = Buffer.allocUnsafe(2 + length);
1517
+ buf.writeUInt16BE(code, 0);
1518
+ if (typeof data === "string") {
1519
+ buf.write(data, 2);
1520
+ } else {
1521
+ buf.set(data, 2);
1522
+ }
1523
+ }
1524
+ const options = {
1525
+ [kByteLength]: buf.length,
1526
+ fin: true,
1527
+ generateMask: this._generateMask,
1528
+ mask,
1529
+ maskBuffer: this._maskBuffer,
1530
+ opcode: 8,
1531
+ readOnly: false,
1532
+ rsv1: false
1533
+ };
1534
+ if (this._state !== DEFAULT) {
1535
+ this.enqueue([this.dispatch, buf, false, options, cb]);
1536
+ } else {
1537
+ this.sendFrame(_Sender.frame(buf, options), cb);
1538
+ }
1539
+ }
1540
+ /**
1541
+ * Sends a ping message to the other peer.
1542
+ *
1543
+ * @param {*} data The message to send
1544
+ * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
1545
+ * @param {Function} [cb] Callback
1546
+ * @public
1547
+ */
1548
+ ping(data, mask, cb) {
1549
+ let byteLength;
1550
+ let readOnly;
1551
+ if (typeof data === "string") {
1552
+ byteLength = Buffer.byteLength(data);
1553
+ readOnly = false;
1554
+ } else if (isBlob(data)) {
1555
+ byteLength = data.size;
1556
+ readOnly = false;
1557
+ } else {
1558
+ data = toBuffer(data);
1559
+ byteLength = data.length;
1560
+ readOnly = toBuffer.readOnly;
1561
+ }
1562
+ if (byteLength > 125) {
1563
+ throw new RangeError("The data size must not be greater than 125 bytes");
1564
+ }
1565
+ const options = {
1566
+ [kByteLength]: byteLength,
1567
+ fin: true,
1568
+ generateMask: this._generateMask,
1569
+ mask,
1570
+ maskBuffer: this._maskBuffer,
1571
+ opcode: 9,
1572
+ readOnly,
1573
+ rsv1: false
1574
+ };
1575
+ if (isBlob(data)) {
1576
+ if (this._state !== DEFAULT) {
1577
+ this.enqueue([this.getBlobData, data, false, options, cb]);
1578
+ } else {
1579
+ this.getBlobData(data, false, options, cb);
1580
+ }
1581
+ } else if (this._state !== DEFAULT) {
1582
+ this.enqueue([this.dispatch, data, false, options, cb]);
1583
+ } else {
1584
+ this.sendFrame(_Sender.frame(data, options), cb);
1585
+ }
1586
+ }
1587
+ /**
1588
+ * Sends a pong message to the other peer.
1589
+ *
1590
+ * @param {*} data The message to send
1591
+ * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
1592
+ * @param {Function} [cb] Callback
1593
+ * @public
1594
+ */
1595
+ pong(data, mask, cb) {
1596
+ let byteLength;
1597
+ let readOnly;
1598
+ if (typeof data === "string") {
1599
+ byteLength = Buffer.byteLength(data);
1600
+ readOnly = false;
1601
+ } else if (isBlob(data)) {
1602
+ byteLength = data.size;
1603
+ readOnly = false;
1604
+ } else {
1605
+ data = toBuffer(data);
1606
+ byteLength = data.length;
1607
+ readOnly = toBuffer.readOnly;
1608
+ }
1609
+ if (byteLength > 125) {
1610
+ throw new RangeError("The data size must not be greater than 125 bytes");
1611
+ }
1612
+ const options = {
1613
+ [kByteLength]: byteLength,
1614
+ fin: true,
1615
+ generateMask: this._generateMask,
1616
+ mask,
1617
+ maskBuffer: this._maskBuffer,
1618
+ opcode: 10,
1619
+ readOnly,
1620
+ rsv1: false
1621
+ };
1622
+ if (isBlob(data)) {
1623
+ if (this._state !== DEFAULT) {
1624
+ this.enqueue([this.getBlobData, data, false, options, cb]);
1625
+ } else {
1626
+ this.getBlobData(data, false, options, cb);
1627
+ }
1628
+ } else if (this._state !== DEFAULT) {
1629
+ this.enqueue([this.dispatch, data, false, options, cb]);
1630
+ } else {
1631
+ this.sendFrame(_Sender.frame(data, options), cb);
1632
+ }
1633
+ }
1634
+ /**
1635
+ * Sends a data message to the other peer.
1636
+ *
1637
+ * @param {*} data The message to send
1638
+ * @param {Object} options Options object
1639
+ * @param {Boolean} [options.binary=false] Specifies whether `data` is binary
1640
+ * or text
1641
+ * @param {Boolean} [options.compress=false] Specifies whether or not to
1642
+ * compress `data`
1643
+ * @param {Boolean} [options.fin=false] Specifies whether the fragment is the
1644
+ * last one
1645
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1646
+ * `data`
1647
+ * @param {Function} [cb] Callback
1648
+ * @public
1649
+ */
1650
+ send(data, options, cb) {
1651
+ const perMessageDeflate = this._extensions[PerMessageDeflate2.extensionName];
1652
+ let opcode = options.binary ? 2 : 1;
1653
+ let rsv1 = options.compress;
1654
+ let byteLength;
1655
+ let readOnly;
1656
+ if (typeof data === "string") {
1657
+ byteLength = Buffer.byteLength(data);
1658
+ readOnly = false;
1659
+ } else if (isBlob(data)) {
1660
+ byteLength = data.size;
1661
+ readOnly = false;
1662
+ } else {
1663
+ data = toBuffer(data);
1664
+ byteLength = data.length;
1665
+ readOnly = toBuffer.readOnly;
1666
+ }
1667
+ if (this._firstFragment) {
1668
+ this._firstFragment = false;
1669
+ if (rsv1 && perMessageDeflate && perMessageDeflate.params[perMessageDeflate._isServer ? "server_no_context_takeover" : "client_no_context_takeover"]) {
1670
+ rsv1 = byteLength >= perMessageDeflate._threshold;
1671
+ }
1672
+ this._compress = rsv1;
1673
+ } else {
1674
+ rsv1 = false;
1675
+ opcode = 0;
1676
+ }
1677
+ if (options.fin) this._firstFragment = true;
1678
+ const opts = {
1679
+ [kByteLength]: byteLength,
1680
+ fin: options.fin,
1681
+ generateMask: this._generateMask,
1682
+ mask: options.mask,
1683
+ maskBuffer: this._maskBuffer,
1684
+ opcode,
1685
+ readOnly,
1686
+ rsv1
1687
+ };
1688
+ if (isBlob(data)) {
1689
+ if (this._state !== DEFAULT) {
1690
+ this.enqueue([this.getBlobData, data, this._compress, opts, cb]);
1691
+ } else {
1692
+ this.getBlobData(data, this._compress, opts, cb);
1693
+ }
1694
+ } else if (this._state !== DEFAULT) {
1695
+ this.enqueue([this.dispatch, data, this._compress, opts, cb]);
1696
+ } else {
1697
+ this.dispatch(data, this._compress, opts, cb);
1698
+ }
1699
+ }
1700
+ /**
1701
+ * Gets the contents of a blob as binary data.
1702
+ *
1703
+ * @param {Blob} blob The blob
1704
+ * @param {Boolean} [compress=false] Specifies whether or not to compress
1705
+ * the data
1706
+ * @param {Object} options Options object
1707
+ * @param {Boolean} [options.fin=false] Specifies whether or not to set the
1708
+ * FIN bit
1709
+ * @param {Function} [options.generateMask] The function used to generate the
1710
+ * masking key
1711
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1712
+ * `data`
1713
+ * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
1714
+ * key
1715
+ * @param {Number} options.opcode The opcode
1716
+ * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
1717
+ * modified
1718
+ * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
1719
+ * RSV1 bit
1720
+ * @param {Function} [cb] Callback
1721
+ * @private
1722
+ */
1723
+ getBlobData(blob, compress, options, cb) {
1724
+ this._bufferedBytes += options[kByteLength];
1725
+ this._state = GET_BLOB_DATA;
1726
+ blob.arrayBuffer().then((arrayBuffer) => {
1727
+ if (this._socket.destroyed) {
1728
+ const err = new Error(
1729
+ "The socket was closed while the blob was being read"
1730
+ );
1731
+ process.nextTick(callCallbacks, this, err, cb);
1732
+ return;
1733
+ }
1734
+ this._bufferedBytes -= options[kByteLength];
1735
+ const data = toBuffer(arrayBuffer);
1736
+ if (!compress) {
1737
+ this._state = DEFAULT;
1738
+ this.sendFrame(_Sender.frame(data, options), cb);
1739
+ this.dequeue();
1740
+ } else {
1741
+ this.dispatch(data, compress, options, cb);
1742
+ }
1743
+ }).catch((err) => {
1744
+ process.nextTick(onError, this, err, cb);
1745
+ });
1746
+ }
1747
+ /**
1748
+ * Dispatches a message.
1749
+ *
1750
+ * @param {(Buffer|String)} data The message to send
1751
+ * @param {Boolean} [compress=false] Specifies whether or not to compress
1752
+ * `data`
1753
+ * @param {Object} options Options object
1754
+ * @param {Boolean} [options.fin=false] Specifies whether or not to set the
1755
+ * FIN bit
1756
+ * @param {Function} [options.generateMask] The function used to generate the
1757
+ * masking key
1758
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1759
+ * `data`
1760
+ * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
1761
+ * key
1762
+ * @param {Number} options.opcode The opcode
1763
+ * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
1764
+ * modified
1765
+ * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
1766
+ * RSV1 bit
1767
+ * @param {Function} [cb] Callback
1768
+ * @private
1769
+ */
1770
+ dispatch(data, compress, options, cb) {
1771
+ if (!compress) {
1772
+ this.sendFrame(_Sender.frame(data, options), cb);
1773
+ return;
1774
+ }
1775
+ const perMessageDeflate = this._extensions[PerMessageDeflate2.extensionName];
1776
+ this._bufferedBytes += options[kByteLength];
1777
+ this._state = DEFLATING;
1778
+ perMessageDeflate.compress(data, options.fin, (_, buf) => {
1779
+ if (this._socket.destroyed) {
1780
+ const err = new Error(
1781
+ "The socket was closed while data was being compressed"
1782
+ );
1783
+ callCallbacks(this, err, cb);
1784
+ return;
1785
+ }
1786
+ this._bufferedBytes -= options[kByteLength];
1787
+ this._state = DEFAULT;
1788
+ options.readOnly = false;
1789
+ this.sendFrame(_Sender.frame(buf, options), cb);
1790
+ this.dequeue();
1791
+ });
1792
+ }
1793
+ /**
1794
+ * Executes queued send operations.
1795
+ *
1796
+ * @private
1797
+ */
1798
+ dequeue() {
1799
+ while (this._state === DEFAULT && this._queue.length) {
1800
+ const params = this._queue.shift();
1801
+ this._bufferedBytes -= params[3][kByteLength];
1802
+ Reflect.apply(params[0], this, params.slice(1));
1803
+ }
1804
+ }
1805
+ /**
1806
+ * Enqueues a send operation.
1807
+ *
1808
+ * @param {Array} params Send operation parameters.
1809
+ * @private
1810
+ */
1811
+ enqueue(params) {
1812
+ this._bufferedBytes += params[3][kByteLength];
1813
+ this._queue.push(params);
1814
+ }
1815
+ /**
1816
+ * Sends a frame.
1817
+ *
1818
+ * @param {(Buffer | String)[]} list The frame to send
1819
+ * @param {Function} [cb] Callback
1820
+ * @private
1821
+ */
1822
+ sendFrame(list, cb) {
1823
+ if (list.length === 2) {
1824
+ this._socket.cork();
1825
+ this._socket.write(list[0]);
1826
+ this._socket.write(list[1], cb);
1827
+ this._socket.uncork();
1828
+ } else {
1829
+ this._socket.write(list[0], cb);
1830
+ }
1831
+ }
1832
+ };
1833
+ module.exports = Sender2;
1834
+ function callCallbacks(sender, err, cb) {
1835
+ if (typeof cb === "function") cb(err);
1836
+ for (let i = 0; i < sender._queue.length; i++) {
1837
+ const params = sender._queue[i];
1838
+ const callback = params[params.length - 1];
1839
+ if (typeof callback === "function") callback(err);
1840
+ }
1841
+ }
1842
+ function onError(sender, err, cb) {
1843
+ callCallbacks(sender, err, cb);
1844
+ sender.onerror(err);
1845
+ }
1846
+ }
1847
+ });
1848
+
1849
+ // node_modules/ws/lib/event-target.js
1850
+ var require_event_target = __commonJS({
1851
+ "node_modules/ws/lib/event-target.js"(exports, module) {
1852
+ "use strict";
1853
+ var { kForOnEventAttribute, kListener } = require_constants();
1854
+ var kCode = /* @__PURE__ */ Symbol("kCode");
1855
+ var kData = /* @__PURE__ */ Symbol("kData");
1856
+ var kError = /* @__PURE__ */ Symbol("kError");
1857
+ var kMessage = /* @__PURE__ */ Symbol("kMessage");
1858
+ var kReason = /* @__PURE__ */ Symbol("kReason");
1859
+ var kTarget = /* @__PURE__ */ Symbol("kTarget");
1860
+ var kType = /* @__PURE__ */ Symbol("kType");
1861
+ var kWasClean = /* @__PURE__ */ Symbol("kWasClean");
1862
+ var Event = class {
1863
+ /**
1864
+ * Create a new `Event`.
1865
+ *
1866
+ * @param {String} type The name of the event
1867
+ * @throws {TypeError} If the `type` argument is not specified
1868
+ */
1869
+ constructor(type) {
1870
+ this[kTarget] = null;
1871
+ this[kType] = type;
1872
+ }
1873
+ /**
1874
+ * @type {*}
1875
+ */
1876
+ get target() {
1877
+ return this[kTarget];
1878
+ }
1879
+ /**
1880
+ * @type {String}
1881
+ */
1882
+ get type() {
1883
+ return this[kType];
1884
+ }
1885
+ };
1886
+ Object.defineProperty(Event.prototype, "target", { enumerable: true });
1887
+ Object.defineProperty(Event.prototype, "type", { enumerable: true });
1888
+ var CloseEvent = class extends Event {
1889
+ /**
1890
+ * Create a new `CloseEvent`.
1891
+ *
1892
+ * @param {String} type The name of the event
1893
+ * @param {Object} [options] A dictionary object that allows for setting
1894
+ * attributes via object members of the same name
1895
+ * @param {Number} [options.code=0] The status code explaining why the
1896
+ * connection was closed
1897
+ * @param {String} [options.reason=''] A human-readable string explaining why
1898
+ * the connection was closed
1899
+ * @param {Boolean} [options.wasClean=false] Indicates whether or not the
1900
+ * connection was cleanly closed
1901
+ */
1902
+ constructor(type, options = {}) {
1903
+ super(type);
1904
+ this[kCode] = options.code === void 0 ? 0 : options.code;
1905
+ this[kReason] = options.reason === void 0 ? "" : options.reason;
1906
+ this[kWasClean] = options.wasClean === void 0 ? false : options.wasClean;
1907
+ }
1908
+ /**
1909
+ * @type {Number}
1910
+ */
1911
+ get code() {
1912
+ return this[kCode];
1913
+ }
1914
+ /**
1915
+ * @type {String}
1916
+ */
1917
+ get reason() {
1918
+ return this[kReason];
1919
+ }
1920
+ /**
1921
+ * @type {Boolean}
1922
+ */
1923
+ get wasClean() {
1924
+ return this[kWasClean];
1925
+ }
1926
+ };
1927
+ Object.defineProperty(CloseEvent.prototype, "code", { enumerable: true });
1928
+ Object.defineProperty(CloseEvent.prototype, "reason", { enumerable: true });
1929
+ Object.defineProperty(CloseEvent.prototype, "wasClean", { enumerable: true });
1930
+ var ErrorEvent = class extends Event {
1931
+ /**
1932
+ * Create a new `ErrorEvent`.
1933
+ *
1934
+ * @param {String} type The name of the event
1935
+ * @param {Object} [options] A dictionary object that allows for setting
1936
+ * attributes via object members of the same name
1937
+ * @param {*} [options.error=null] The error that generated this event
1938
+ * @param {String} [options.message=''] The error message
1939
+ */
1940
+ constructor(type, options = {}) {
1941
+ super(type);
1942
+ this[kError] = options.error === void 0 ? null : options.error;
1943
+ this[kMessage] = options.message === void 0 ? "" : options.message;
1944
+ }
1945
+ /**
1946
+ * @type {*}
1947
+ */
1948
+ get error() {
1949
+ return this[kError];
1950
+ }
1951
+ /**
1952
+ * @type {String}
1953
+ */
1954
+ get message() {
1955
+ return this[kMessage];
1956
+ }
1957
+ };
1958
+ Object.defineProperty(ErrorEvent.prototype, "error", { enumerable: true });
1959
+ Object.defineProperty(ErrorEvent.prototype, "message", { enumerable: true });
1960
+ var MessageEvent = class extends Event {
1961
+ /**
1962
+ * Create a new `MessageEvent`.
1963
+ *
1964
+ * @param {String} type The name of the event
1965
+ * @param {Object} [options] A dictionary object that allows for setting
1966
+ * attributes via object members of the same name
1967
+ * @param {*} [options.data=null] The message content
1968
+ */
1969
+ constructor(type, options = {}) {
1970
+ super(type);
1971
+ this[kData] = options.data === void 0 ? null : options.data;
1972
+ }
1973
+ /**
1974
+ * @type {*}
1975
+ */
1976
+ get data() {
1977
+ return this[kData];
1978
+ }
1979
+ };
1980
+ Object.defineProperty(MessageEvent.prototype, "data", { enumerable: true });
1981
+ var EventTarget = {
1982
+ /**
1983
+ * Register an event listener.
1984
+ *
1985
+ * @param {String} type A string representing the event type to listen for
1986
+ * @param {(Function|Object)} handler The listener to add
1987
+ * @param {Object} [options] An options object specifies characteristics about
1988
+ * the event listener
1989
+ * @param {Boolean} [options.once=false] A `Boolean` indicating that the
1990
+ * listener should be invoked at most once after being added. If `true`,
1991
+ * the listener would be automatically removed when invoked.
1992
+ * @public
1993
+ */
1994
+ addEventListener(type, handler, options = {}) {
1995
+ for (const listener of this.listeners(type)) {
1996
+ if (!options[kForOnEventAttribute] && listener[kListener] === handler && !listener[kForOnEventAttribute]) {
1997
+ return;
1998
+ }
1999
+ }
2000
+ let wrapper;
2001
+ if (type === "message") {
2002
+ wrapper = function onMessage(data, isBinary) {
2003
+ const event = new MessageEvent("message", {
2004
+ data: isBinary ? data : data.toString()
2005
+ });
2006
+ event[kTarget] = this;
2007
+ callListener(handler, this, event);
2008
+ };
2009
+ } else if (type === "close") {
2010
+ wrapper = function onClose(code, message) {
2011
+ const event = new CloseEvent("close", {
2012
+ code,
2013
+ reason: message.toString(),
2014
+ wasClean: this._closeFrameReceived && this._closeFrameSent
2015
+ });
2016
+ event[kTarget] = this;
2017
+ callListener(handler, this, event);
2018
+ };
2019
+ } else if (type === "error") {
2020
+ wrapper = function onError(error) {
2021
+ const event = new ErrorEvent("error", {
2022
+ error,
2023
+ message: error.message
2024
+ });
2025
+ event[kTarget] = this;
2026
+ callListener(handler, this, event);
2027
+ };
2028
+ } else if (type === "open") {
2029
+ wrapper = function onOpen() {
2030
+ const event = new Event("open");
2031
+ event[kTarget] = this;
2032
+ callListener(handler, this, event);
2033
+ };
2034
+ } else {
2035
+ return;
2036
+ }
2037
+ wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute];
2038
+ wrapper[kListener] = handler;
2039
+ if (options.once) {
2040
+ this.once(type, wrapper);
2041
+ } else {
2042
+ this.on(type, wrapper);
2043
+ }
2044
+ },
2045
+ /**
2046
+ * Remove an event listener.
2047
+ *
2048
+ * @param {String} type A string representing the event type to remove
2049
+ * @param {(Function|Object)} handler The listener to remove
2050
+ * @public
2051
+ */
2052
+ removeEventListener(type, handler) {
2053
+ for (const listener of this.listeners(type)) {
2054
+ if (listener[kListener] === handler && !listener[kForOnEventAttribute]) {
2055
+ this.removeListener(type, listener);
2056
+ break;
2057
+ }
2058
+ }
2059
+ }
2060
+ };
2061
+ module.exports = {
2062
+ CloseEvent,
2063
+ ErrorEvent,
2064
+ Event,
2065
+ EventTarget,
2066
+ MessageEvent
2067
+ };
2068
+ function callListener(listener, thisArg, event) {
2069
+ if (typeof listener === "object" && listener.handleEvent) {
2070
+ listener.handleEvent.call(listener, event);
2071
+ } else {
2072
+ listener.call(thisArg, event);
2073
+ }
2074
+ }
2075
+ }
2076
+ });
2077
+
2078
+ // node_modules/ws/lib/extension.js
2079
+ var require_extension = __commonJS({
2080
+ "node_modules/ws/lib/extension.js"(exports, module) {
2081
+ "use strict";
2082
+ var { tokenChars } = require_validation();
2083
+ function push(dest, name, elem) {
2084
+ if (dest[name] === void 0) dest[name] = [elem];
2085
+ else dest[name].push(elem);
2086
+ }
2087
+ function parse(header) {
2088
+ const offers = /* @__PURE__ */ Object.create(null);
2089
+ let params = /* @__PURE__ */ Object.create(null);
2090
+ let mustUnescape = false;
2091
+ let isEscaping = false;
2092
+ let inQuotes = false;
2093
+ let extensionName;
2094
+ let paramName;
2095
+ let start = -1;
2096
+ let code = -1;
2097
+ let end = -1;
2098
+ let i = 0;
2099
+ for (; i < header.length; i++) {
2100
+ code = header.charCodeAt(i);
2101
+ if (extensionName === void 0) {
2102
+ if (end === -1 && tokenChars[code] === 1) {
2103
+ if (start === -1) start = i;
2104
+ } else if (i !== 0 && (code === 32 || code === 9)) {
2105
+ if (end === -1 && start !== -1) end = i;
2106
+ } else if (code === 59 || code === 44) {
2107
+ if (start === -1) {
2108
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2109
+ }
2110
+ if (end === -1) end = i;
2111
+ const name = header.slice(start, end);
2112
+ if (code === 44) {
2113
+ push(offers, name, params);
2114
+ params = /* @__PURE__ */ Object.create(null);
2115
+ } else {
2116
+ extensionName = name;
2117
+ }
2118
+ start = end = -1;
2119
+ } else {
2120
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2121
+ }
2122
+ } else if (paramName === void 0) {
2123
+ if (end === -1 && tokenChars[code] === 1) {
2124
+ if (start === -1) start = i;
2125
+ } else if (code === 32 || code === 9) {
2126
+ if (end === -1 && start !== -1) end = i;
2127
+ } else if (code === 59 || code === 44) {
2128
+ if (start === -1) {
2129
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2130
+ }
2131
+ if (end === -1) end = i;
2132
+ push(params, header.slice(start, end), true);
2133
+ if (code === 44) {
2134
+ push(offers, extensionName, params);
2135
+ params = /* @__PURE__ */ Object.create(null);
2136
+ extensionName = void 0;
2137
+ }
2138
+ start = end = -1;
2139
+ } else if (code === 61 && start !== -1 && end === -1) {
2140
+ paramName = header.slice(start, i);
2141
+ start = end = -1;
2142
+ } else {
2143
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2144
+ }
2145
+ } else {
2146
+ if (isEscaping) {
2147
+ if (tokenChars[code] !== 1) {
2148
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2149
+ }
2150
+ if (start === -1) start = i;
2151
+ else if (!mustUnescape) mustUnescape = true;
2152
+ isEscaping = false;
2153
+ } else if (inQuotes) {
2154
+ if (tokenChars[code] === 1) {
2155
+ if (start === -1) start = i;
2156
+ } else if (code === 34 && start !== -1) {
2157
+ inQuotes = false;
2158
+ end = i;
2159
+ } else if (code === 92) {
2160
+ isEscaping = true;
2161
+ } else {
2162
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2163
+ }
2164
+ } else if (code === 34 && header.charCodeAt(i - 1) === 61) {
2165
+ inQuotes = true;
2166
+ } else if (end === -1 && tokenChars[code] === 1) {
2167
+ if (start === -1) start = i;
2168
+ } else if (start !== -1 && (code === 32 || code === 9)) {
2169
+ if (end === -1) end = i;
2170
+ } else if (code === 59 || code === 44) {
2171
+ if (start === -1) {
2172
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2173
+ }
2174
+ if (end === -1) end = i;
2175
+ let value = header.slice(start, end);
2176
+ if (mustUnescape) {
2177
+ value = value.replace(/\\/g, "");
2178
+ mustUnescape = false;
2179
+ }
2180
+ push(params, paramName, value);
2181
+ if (code === 44) {
2182
+ push(offers, extensionName, params);
2183
+ params = /* @__PURE__ */ Object.create(null);
2184
+ extensionName = void 0;
2185
+ }
2186
+ paramName = void 0;
2187
+ start = end = -1;
2188
+ } else {
2189
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2190
+ }
2191
+ }
2192
+ }
2193
+ if (start === -1 || inQuotes || code === 32 || code === 9) {
2194
+ throw new SyntaxError("Unexpected end of input");
2195
+ }
2196
+ if (end === -1) end = i;
2197
+ const token = header.slice(start, end);
2198
+ if (extensionName === void 0) {
2199
+ push(offers, token, params);
2200
+ } else {
2201
+ if (paramName === void 0) {
2202
+ push(params, token, true);
2203
+ } else if (mustUnescape) {
2204
+ push(params, paramName, token.replace(/\\/g, ""));
2205
+ } else {
2206
+ push(params, paramName, token);
2207
+ }
2208
+ push(offers, extensionName, params);
2209
+ }
2210
+ return offers;
2211
+ }
2212
+ function format(extensions) {
2213
+ return Object.keys(extensions).map((extension2) => {
2214
+ let configurations = extensions[extension2];
2215
+ if (!Array.isArray(configurations)) configurations = [configurations];
2216
+ return configurations.map((params) => {
2217
+ return [extension2].concat(
2218
+ Object.keys(params).map((k) => {
2219
+ let values = params[k];
2220
+ if (!Array.isArray(values)) values = [values];
2221
+ return values.map((v) => v === true ? k : `${k}=${v}`).join("; ");
2222
+ })
2223
+ ).join("; ");
2224
+ }).join(", ");
2225
+ }).join(", ");
2226
+ }
2227
+ module.exports = { format, parse };
2228
+ }
2229
+ });
2230
+
2231
+ // node_modules/ws/lib/websocket.js
2232
+ var require_websocket = __commonJS({
2233
+ "node_modules/ws/lib/websocket.js"(exports, module) {
2234
+ "use strict";
2235
+ var EventEmitter2 = __require("events");
2236
+ var https = __require("https");
2237
+ var http3 = __require("http");
2238
+ var net3 = __require("net");
2239
+ var tls = __require("tls");
2240
+ var { randomBytes, createHash: createHash2 } = __require("crypto");
2241
+ var { Duplex, Readable } = __require("stream");
2242
+ var { URL: URL2 } = __require("url");
2243
+ var PerMessageDeflate2 = require_permessage_deflate();
2244
+ var Receiver2 = require_receiver();
2245
+ var Sender2 = require_sender();
2246
+ var { isBlob } = require_validation();
2247
+ var {
2248
+ BINARY_TYPES,
2249
+ CLOSE_TIMEOUT,
2250
+ EMPTY_BUFFER,
2251
+ GUID,
2252
+ kForOnEventAttribute,
2253
+ kListener,
2254
+ kStatusCode,
2255
+ kWebSocket,
2256
+ NOOP
2257
+ } = require_constants();
2258
+ var {
2259
+ EventTarget: { addEventListener, removeEventListener }
2260
+ } = require_event_target();
2261
+ var { format, parse } = require_extension();
2262
+ var { toBuffer } = require_buffer_util();
2263
+ var kAborted = /* @__PURE__ */ Symbol("kAborted");
2264
+ var protocolVersions = [8, 13];
2265
+ var readyStates = ["CONNECTING", "OPEN", "CLOSING", "CLOSED"];
2266
+ var subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;
2267
+ var WebSocket2 = class _WebSocket extends EventEmitter2 {
2268
+ /**
2269
+ * Create a new `WebSocket`.
2270
+ *
2271
+ * @param {(String|URL)} address The URL to which to connect
2272
+ * @param {(String|String[])} [protocols] The subprotocols
2273
+ * @param {Object} [options] Connection options
2274
+ */
2275
+ constructor(address, protocols, options) {
2276
+ super();
2277
+ this._binaryType = BINARY_TYPES[0];
2278
+ this._closeCode = 1006;
2279
+ this._closeFrameReceived = false;
2280
+ this._closeFrameSent = false;
2281
+ this._closeMessage = EMPTY_BUFFER;
2282
+ this._closeTimer = null;
2283
+ this._errorEmitted = false;
2284
+ this._extensions = {};
2285
+ this._paused = false;
2286
+ this._protocol = "";
2287
+ this._readyState = _WebSocket.CONNECTING;
2288
+ this._receiver = null;
2289
+ this._sender = null;
2290
+ this._socket = null;
2291
+ if (address !== null) {
2292
+ this._bufferedAmount = 0;
2293
+ this._isServer = false;
2294
+ this._redirects = 0;
2295
+ if (protocols === void 0) {
2296
+ protocols = [];
2297
+ } else if (!Array.isArray(protocols)) {
2298
+ if (typeof protocols === "object" && protocols !== null) {
2299
+ options = protocols;
2300
+ protocols = [];
2301
+ } else {
2302
+ protocols = [protocols];
2303
+ }
2304
+ }
2305
+ initAsClient(this, address, protocols, options);
2306
+ } else {
2307
+ this._autoPong = options.autoPong;
2308
+ this._closeTimeout = options.closeTimeout;
2309
+ this._isServer = true;
2310
+ }
2311
+ }
2312
+ /**
2313
+ * For historical reasons, the custom "nodebuffer" type is used by the default
2314
+ * instead of "blob".
2315
+ *
2316
+ * @type {String}
2317
+ */
2318
+ get binaryType() {
2319
+ return this._binaryType;
2320
+ }
2321
+ set binaryType(type) {
2322
+ if (!BINARY_TYPES.includes(type)) return;
2323
+ this._binaryType = type;
2324
+ if (this._receiver) this._receiver._binaryType = type;
2325
+ }
2326
+ /**
2327
+ * @type {Number}
2328
+ */
2329
+ get bufferedAmount() {
2330
+ if (!this._socket) return this._bufferedAmount;
2331
+ return this._socket._writableState.length + this._sender._bufferedBytes;
2332
+ }
2333
+ /**
2334
+ * @type {String}
2335
+ */
2336
+ get extensions() {
2337
+ return Object.keys(this._extensions).join();
2338
+ }
2339
+ /**
2340
+ * @type {Boolean}
2341
+ */
2342
+ get isPaused() {
2343
+ return this._paused;
2344
+ }
2345
+ /**
2346
+ * @type {Function}
2347
+ */
2348
+ /* istanbul ignore next */
2349
+ get onclose() {
2350
+ return null;
2351
+ }
2352
+ /**
2353
+ * @type {Function}
2354
+ */
2355
+ /* istanbul ignore next */
2356
+ get onerror() {
2357
+ return null;
2358
+ }
2359
+ /**
2360
+ * @type {Function}
2361
+ */
2362
+ /* istanbul ignore next */
2363
+ get onopen() {
2364
+ return null;
2365
+ }
2366
+ /**
2367
+ * @type {Function}
2368
+ */
2369
+ /* istanbul ignore next */
2370
+ get onmessage() {
2371
+ return null;
2372
+ }
2373
+ /**
2374
+ * @type {String}
2375
+ */
2376
+ get protocol() {
2377
+ return this._protocol;
2378
+ }
2379
+ /**
2380
+ * @type {Number}
2381
+ */
2382
+ get readyState() {
2383
+ return this._readyState;
2384
+ }
2385
+ /**
2386
+ * @type {String}
2387
+ */
2388
+ get url() {
2389
+ return this._url;
2390
+ }
2391
+ /**
2392
+ * Set up the socket and the internal resources.
2393
+ *
2394
+ * @param {Duplex} socket The network socket between the server and client
2395
+ * @param {Buffer} head The first packet of the upgraded stream
2396
+ * @param {Object} options Options object
2397
+ * @param {Boolean} [options.allowSynchronousEvents=false] Specifies whether
2398
+ * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
2399
+ * multiple times in the same tick
2400
+ * @param {Function} [options.generateMask] The function used to generate the
2401
+ * masking key
2402
+ * @param {Number} [options.maxPayload=0] The maximum allowed message size
2403
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
2404
+ * not to skip UTF-8 validation for text and close messages
2405
+ * @private
2406
+ */
2407
+ setSocket(socket, head, options) {
2408
+ const receiver = new Receiver2({
2409
+ allowSynchronousEvents: options.allowSynchronousEvents,
2410
+ binaryType: this.binaryType,
2411
+ extensions: this._extensions,
2412
+ isServer: this._isServer,
2413
+ maxPayload: options.maxPayload,
2414
+ skipUTF8Validation: options.skipUTF8Validation
2415
+ });
2416
+ const sender = new Sender2(socket, this._extensions, options.generateMask);
2417
+ this._receiver = receiver;
2418
+ this._sender = sender;
2419
+ this._socket = socket;
2420
+ receiver[kWebSocket] = this;
2421
+ sender[kWebSocket] = this;
2422
+ socket[kWebSocket] = this;
2423
+ receiver.on("conclude", receiverOnConclude);
2424
+ receiver.on("drain", receiverOnDrain);
2425
+ receiver.on("error", receiverOnError);
2426
+ receiver.on("message", receiverOnMessage);
2427
+ receiver.on("ping", receiverOnPing);
2428
+ receiver.on("pong", receiverOnPong);
2429
+ sender.onerror = senderOnError;
2430
+ if (socket.setTimeout) socket.setTimeout(0);
2431
+ if (socket.setNoDelay) socket.setNoDelay();
2432
+ if (head.length > 0) socket.unshift(head);
2433
+ socket.on("close", socketOnClose);
2434
+ socket.on("data", socketOnData);
2435
+ socket.on("end", socketOnEnd);
2436
+ socket.on("error", socketOnError);
2437
+ this._readyState = _WebSocket.OPEN;
2438
+ this.emit("open");
2439
+ }
2440
+ /**
2441
+ * Emit the `'close'` event.
2442
+ *
2443
+ * @private
2444
+ */
2445
+ emitClose() {
2446
+ if (!this._socket) {
2447
+ this._readyState = _WebSocket.CLOSED;
2448
+ this.emit("close", this._closeCode, this._closeMessage);
2449
+ return;
2450
+ }
2451
+ if (this._extensions[PerMessageDeflate2.extensionName]) {
2452
+ this._extensions[PerMessageDeflate2.extensionName].cleanup();
2453
+ }
2454
+ this._receiver.removeAllListeners();
2455
+ this._readyState = _WebSocket.CLOSED;
2456
+ this.emit("close", this._closeCode, this._closeMessage);
2457
+ }
2458
+ /**
2459
+ * Start a closing handshake.
2460
+ *
2461
+ * +----------+ +-----------+ +----------+
2462
+ * - - -|ws.close()|-->|close frame|-->|ws.close()|- - -
2463
+ * | +----------+ +-----------+ +----------+ |
2464
+ * +----------+ +-----------+ |
2465
+ * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING
2466
+ * +----------+ +-----------+ |
2467
+ * | | | +---+ |
2468
+ * +------------------------+-->|fin| - - - -
2469
+ * | +---+ | +---+
2470
+ * - - - - -|fin|<---------------------+
2471
+ * +---+
2472
+ *
2473
+ * @param {Number} [code] Status code explaining why the connection is closing
2474
+ * @param {(String|Buffer)} [data] The reason why the connection is
2475
+ * closing
2476
+ * @public
2477
+ */
2478
+ close(code, data) {
2479
+ if (this.readyState === _WebSocket.CLOSED) return;
2480
+ if (this.readyState === _WebSocket.CONNECTING) {
2481
+ const msg = "WebSocket was closed before the connection was established";
2482
+ abortHandshake(this, this._req, msg);
2483
+ return;
2484
+ }
2485
+ if (this.readyState === _WebSocket.CLOSING) {
2486
+ if (this._closeFrameSent && (this._closeFrameReceived || this._receiver._writableState.errorEmitted)) {
2487
+ this._socket.end();
2488
+ }
2489
+ return;
2490
+ }
2491
+ this._readyState = _WebSocket.CLOSING;
2492
+ this._sender.close(code, data, !this._isServer, (err) => {
2493
+ if (err) return;
2494
+ this._closeFrameSent = true;
2495
+ if (this._closeFrameReceived || this._receiver._writableState.errorEmitted) {
2496
+ this._socket.end();
2497
+ }
2498
+ });
2499
+ setCloseTimer(this);
2500
+ }
2501
+ /**
2502
+ * Pause the socket.
2503
+ *
2504
+ * @public
2505
+ */
2506
+ pause() {
2507
+ if (this.readyState === _WebSocket.CONNECTING || this.readyState === _WebSocket.CLOSED) {
2508
+ return;
2509
+ }
2510
+ this._paused = true;
2511
+ this._socket.pause();
2512
+ }
2513
+ /**
2514
+ * Send a ping.
2515
+ *
2516
+ * @param {*} [data] The data to send
2517
+ * @param {Boolean} [mask] Indicates whether or not to mask `data`
2518
+ * @param {Function} [cb] Callback which is executed when the ping is sent
2519
+ * @public
2520
+ */
2521
+ ping(data, mask, cb) {
2522
+ if (this.readyState === _WebSocket.CONNECTING) {
2523
+ throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
2524
+ }
2525
+ if (typeof data === "function") {
2526
+ cb = data;
2527
+ data = mask = void 0;
2528
+ } else if (typeof mask === "function") {
2529
+ cb = mask;
2530
+ mask = void 0;
2531
+ }
2532
+ if (typeof data === "number") data = data.toString();
2533
+ if (this.readyState !== _WebSocket.OPEN) {
2534
+ sendAfterClose(this, data, cb);
2535
+ return;
2536
+ }
2537
+ if (mask === void 0) mask = !this._isServer;
2538
+ this._sender.ping(data || EMPTY_BUFFER, mask, cb);
2539
+ }
2540
+ /**
2541
+ * Send a pong.
2542
+ *
2543
+ * @param {*} [data] The data to send
2544
+ * @param {Boolean} [mask] Indicates whether or not to mask `data`
2545
+ * @param {Function} [cb] Callback which is executed when the pong is sent
2546
+ * @public
2547
+ */
2548
+ pong(data, mask, cb) {
2549
+ if (this.readyState === _WebSocket.CONNECTING) {
2550
+ throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
2551
+ }
2552
+ if (typeof data === "function") {
2553
+ cb = data;
2554
+ data = mask = void 0;
2555
+ } else if (typeof mask === "function") {
2556
+ cb = mask;
2557
+ mask = void 0;
2558
+ }
2559
+ if (typeof data === "number") data = data.toString();
2560
+ if (this.readyState !== _WebSocket.OPEN) {
2561
+ sendAfterClose(this, data, cb);
2562
+ return;
2563
+ }
2564
+ if (mask === void 0) mask = !this._isServer;
2565
+ this._sender.pong(data || EMPTY_BUFFER, mask, cb);
2566
+ }
2567
+ /**
2568
+ * Resume the socket.
2569
+ *
2570
+ * @public
2571
+ */
2572
+ resume() {
2573
+ if (this.readyState === _WebSocket.CONNECTING || this.readyState === _WebSocket.CLOSED) {
2574
+ return;
2575
+ }
2576
+ this._paused = false;
2577
+ if (!this._receiver._writableState.needDrain) this._socket.resume();
2578
+ }
2579
+ /**
2580
+ * Send a data message.
2581
+ *
2582
+ * @param {*} data The message to send
2583
+ * @param {Object} [options] Options object
2584
+ * @param {Boolean} [options.binary] Specifies whether `data` is binary or
2585
+ * text
2586
+ * @param {Boolean} [options.compress] Specifies whether or not to compress
2587
+ * `data`
2588
+ * @param {Boolean} [options.fin=true] Specifies whether the fragment is the
2589
+ * last one
2590
+ * @param {Boolean} [options.mask] Specifies whether or not to mask `data`
2591
+ * @param {Function} [cb] Callback which is executed when data is written out
2592
+ * @public
2593
+ */
2594
+ send(data, options, cb) {
2595
+ if (this.readyState === _WebSocket.CONNECTING) {
2596
+ throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
2597
+ }
2598
+ if (typeof options === "function") {
2599
+ cb = options;
2600
+ options = {};
2601
+ }
2602
+ if (typeof data === "number") data = data.toString();
2603
+ if (this.readyState !== _WebSocket.OPEN) {
2604
+ sendAfterClose(this, data, cb);
2605
+ return;
2606
+ }
2607
+ const opts = {
2608
+ binary: typeof data !== "string",
2609
+ mask: !this._isServer,
2610
+ compress: true,
2611
+ fin: true,
2612
+ ...options
2613
+ };
2614
+ if (!this._extensions[PerMessageDeflate2.extensionName]) {
2615
+ opts.compress = false;
2616
+ }
2617
+ this._sender.send(data || EMPTY_BUFFER, opts, cb);
2618
+ }
2619
+ /**
2620
+ * Forcibly close the connection.
2621
+ *
2622
+ * @public
2623
+ */
2624
+ terminate() {
2625
+ if (this.readyState === _WebSocket.CLOSED) return;
2626
+ if (this.readyState === _WebSocket.CONNECTING) {
2627
+ const msg = "WebSocket was closed before the connection was established";
2628
+ abortHandshake(this, this._req, msg);
2629
+ return;
2630
+ }
2631
+ if (this._socket) {
2632
+ this._readyState = _WebSocket.CLOSING;
2633
+ this._socket.destroy();
2634
+ }
2635
+ }
2636
+ };
2637
+ Object.defineProperty(WebSocket2, "CONNECTING", {
2638
+ enumerable: true,
2639
+ value: readyStates.indexOf("CONNECTING")
2640
+ });
2641
+ Object.defineProperty(WebSocket2.prototype, "CONNECTING", {
2642
+ enumerable: true,
2643
+ value: readyStates.indexOf("CONNECTING")
2644
+ });
2645
+ Object.defineProperty(WebSocket2, "OPEN", {
2646
+ enumerable: true,
2647
+ value: readyStates.indexOf("OPEN")
2648
+ });
2649
+ Object.defineProperty(WebSocket2.prototype, "OPEN", {
2650
+ enumerable: true,
2651
+ value: readyStates.indexOf("OPEN")
2652
+ });
2653
+ Object.defineProperty(WebSocket2, "CLOSING", {
2654
+ enumerable: true,
2655
+ value: readyStates.indexOf("CLOSING")
2656
+ });
2657
+ Object.defineProperty(WebSocket2.prototype, "CLOSING", {
2658
+ enumerable: true,
2659
+ value: readyStates.indexOf("CLOSING")
2660
+ });
2661
+ Object.defineProperty(WebSocket2, "CLOSED", {
2662
+ enumerable: true,
2663
+ value: readyStates.indexOf("CLOSED")
2664
+ });
2665
+ Object.defineProperty(WebSocket2.prototype, "CLOSED", {
2666
+ enumerable: true,
2667
+ value: readyStates.indexOf("CLOSED")
2668
+ });
2669
+ [
2670
+ "binaryType",
2671
+ "bufferedAmount",
2672
+ "extensions",
2673
+ "isPaused",
2674
+ "protocol",
2675
+ "readyState",
2676
+ "url"
2677
+ ].forEach((property) => {
2678
+ Object.defineProperty(WebSocket2.prototype, property, { enumerable: true });
2679
+ });
2680
+ ["open", "error", "close", "message"].forEach((method) => {
2681
+ Object.defineProperty(WebSocket2.prototype, `on${method}`, {
2682
+ enumerable: true,
2683
+ get() {
2684
+ for (const listener of this.listeners(method)) {
2685
+ if (listener[kForOnEventAttribute]) return listener[kListener];
2686
+ }
2687
+ return null;
2688
+ },
2689
+ set(handler) {
2690
+ for (const listener of this.listeners(method)) {
2691
+ if (listener[kForOnEventAttribute]) {
2692
+ this.removeListener(method, listener);
2693
+ break;
2694
+ }
2695
+ }
2696
+ if (typeof handler !== "function") return;
2697
+ this.addEventListener(method, handler, {
2698
+ [kForOnEventAttribute]: true
2699
+ });
2700
+ }
2701
+ });
2702
+ });
2703
+ WebSocket2.prototype.addEventListener = addEventListener;
2704
+ WebSocket2.prototype.removeEventListener = removeEventListener;
2705
+ module.exports = WebSocket2;
2706
+ function initAsClient(websocket, address, protocols, options) {
2707
+ const opts = {
2708
+ allowSynchronousEvents: true,
2709
+ autoPong: true,
2710
+ closeTimeout: CLOSE_TIMEOUT,
2711
+ protocolVersion: protocolVersions[1],
2712
+ maxPayload: 100 * 1024 * 1024,
2713
+ skipUTF8Validation: false,
2714
+ perMessageDeflate: true,
2715
+ followRedirects: false,
2716
+ maxRedirects: 10,
2717
+ ...options,
2718
+ socketPath: void 0,
2719
+ hostname: void 0,
2720
+ protocol: void 0,
2721
+ timeout: void 0,
2722
+ method: "GET",
2723
+ host: void 0,
2724
+ path: void 0,
2725
+ port: void 0
2726
+ };
2727
+ websocket._autoPong = opts.autoPong;
2728
+ websocket._closeTimeout = opts.closeTimeout;
2729
+ if (!protocolVersions.includes(opts.protocolVersion)) {
2730
+ throw new RangeError(
2731
+ `Unsupported protocol version: ${opts.protocolVersion} (supported versions: ${protocolVersions.join(", ")})`
2732
+ );
2733
+ }
2734
+ let parsedUrl;
2735
+ if (address instanceof URL2) {
2736
+ parsedUrl = address;
2737
+ } else {
2738
+ try {
2739
+ parsedUrl = new URL2(address);
2740
+ } catch {
2741
+ throw new SyntaxError(`Invalid URL: ${address}`);
2742
+ }
2743
+ }
2744
+ if (parsedUrl.protocol === "http:") {
2745
+ parsedUrl.protocol = "ws:";
2746
+ } else if (parsedUrl.protocol === "https:") {
2747
+ parsedUrl.protocol = "wss:";
2748
+ }
2749
+ websocket._url = parsedUrl.href;
2750
+ const isSecure = parsedUrl.protocol === "wss:";
2751
+ const isIpcUrl = parsedUrl.protocol === "ws+unix:";
2752
+ let invalidUrlMessage;
2753
+ if (parsedUrl.protocol !== "ws:" && !isSecure && !isIpcUrl) {
2754
+ invalidUrlMessage = `The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`;
2755
+ } else if (isIpcUrl && !parsedUrl.pathname) {
2756
+ invalidUrlMessage = "The URL's pathname is empty";
2757
+ } else if (parsedUrl.hash) {
2758
+ invalidUrlMessage = "The URL contains a fragment identifier";
2759
+ }
2760
+ if (invalidUrlMessage) {
2761
+ const err = new SyntaxError(invalidUrlMessage);
2762
+ if (websocket._redirects === 0) {
2763
+ throw err;
2764
+ } else {
2765
+ emitErrorAndClose(websocket, err);
2766
+ return;
2767
+ }
2768
+ }
2769
+ const defaultPort = isSecure ? 443 : 80;
2770
+ const key = randomBytes(16).toString("base64");
2771
+ const request = isSecure ? https.request : http3.request;
2772
+ const protocolSet = /* @__PURE__ */ new Set();
2773
+ let perMessageDeflate;
2774
+ opts.createConnection = opts.createConnection || (isSecure ? tlsConnect : netConnect);
2775
+ opts.defaultPort = opts.defaultPort || defaultPort;
2776
+ opts.port = parsedUrl.port || defaultPort;
2777
+ opts.host = parsedUrl.hostname.startsWith("[") ? parsedUrl.hostname.slice(1, -1) : parsedUrl.hostname;
2778
+ opts.headers = {
2779
+ ...opts.headers,
2780
+ "Sec-WebSocket-Version": opts.protocolVersion,
2781
+ "Sec-WebSocket-Key": key,
2782
+ Connection: "Upgrade",
2783
+ Upgrade: "websocket"
2784
+ };
2785
+ opts.path = parsedUrl.pathname + parsedUrl.search;
2786
+ opts.timeout = opts.handshakeTimeout;
2787
+ if (opts.perMessageDeflate) {
2788
+ perMessageDeflate = new PerMessageDeflate2({
2789
+ ...opts.perMessageDeflate,
2790
+ isServer: false,
2791
+ maxPayload: opts.maxPayload
2792
+ });
2793
+ opts.headers["Sec-WebSocket-Extensions"] = format({
2794
+ [PerMessageDeflate2.extensionName]: perMessageDeflate.offer()
2795
+ });
2796
+ }
2797
+ if (protocols.length) {
2798
+ for (const protocol of protocols) {
2799
+ if (typeof protocol !== "string" || !subprotocolRegex.test(protocol) || protocolSet.has(protocol)) {
2800
+ throw new SyntaxError(
2801
+ "An invalid or duplicated subprotocol was specified"
2802
+ );
2803
+ }
2804
+ protocolSet.add(protocol);
2805
+ }
2806
+ opts.headers["Sec-WebSocket-Protocol"] = protocols.join(",");
2807
+ }
2808
+ if (opts.origin) {
2809
+ if (opts.protocolVersion < 13) {
2810
+ opts.headers["Sec-WebSocket-Origin"] = opts.origin;
2811
+ } else {
2812
+ opts.headers.Origin = opts.origin;
2813
+ }
2814
+ }
2815
+ if (parsedUrl.username || parsedUrl.password) {
2816
+ opts.auth = `${parsedUrl.username}:${parsedUrl.password}`;
2817
+ }
2818
+ if (isIpcUrl) {
2819
+ const parts = opts.path.split(":");
2820
+ opts.socketPath = parts[0];
2821
+ opts.path = parts[1];
2822
+ }
2823
+ let req;
2824
+ if (opts.followRedirects) {
2825
+ if (websocket._redirects === 0) {
2826
+ websocket._originalIpc = isIpcUrl;
2827
+ websocket._originalSecure = isSecure;
2828
+ websocket._originalHostOrSocketPath = isIpcUrl ? opts.socketPath : parsedUrl.host;
2829
+ const headers = options && options.headers;
2830
+ options = { ...options, headers: {} };
2831
+ if (headers) {
2832
+ for (const [key2, value] of Object.entries(headers)) {
2833
+ options.headers[key2.toLowerCase()] = value;
2834
+ }
2835
+ }
2836
+ } else if (websocket.listenerCount("redirect") === 0) {
2837
+ const isSameHost = isIpcUrl ? websocket._originalIpc ? opts.socketPath === websocket._originalHostOrSocketPath : false : websocket._originalIpc ? false : parsedUrl.host === websocket._originalHostOrSocketPath;
2838
+ if (!isSameHost || websocket._originalSecure && !isSecure) {
2839
+ delete opts.headers.authorization;
2840
+ delete opts.headers.cookie;
2841
+ if (!isSameHost) delete opts.headers.host;
2842
+ opts.auth = void 0;
2843
+ }
2844
+ }
2845
+ if (opts.auth && !options.headers.authorization) {
2846
+ options.headers.authorization = "Basic " + Buffer.from(opts.auth).toString("base64");
2847
+ }
2848
+ req = websocket._req = request(opts);
2849
+ if (websocket._redirects) {
2850
+ websocket.emit("redirect", websocket.url, req);
2851
+ }
2852
+ } else {
2853
+ req = websocket._req = request(opts);
2854
+ }
2855
+ if (opts.timeout) {
2856
+ req.on("timeout", () => {
2857
+ abortHandshake(websocket, req, "Opening handshake has timed out");
2858
+ });
2859
+ }
2860
+ req.on("error", (err) => {
2861
+ if (req === null || req[kAborted]) return;
2862
+ req = websocket._req = null;
2863
+ emitErrorAndClose(websocket, err);
2864
+ });
2865
+ req.on("response", (res) => {
2866
+ const location = res.headers.location;
2867
+ const statusCode = res.statusCode;
2868
+ if (location && opts.followRedirects && statusCode >= 300 && statusCode < 400) {
2869
+ if (++websocket._redirects > opts.maxRedirects) {
2870
+ abortHandshake(websocket, req, "Maximum redirects exceeded");
2871
+ return;
2872
+ }
2873
+ req.abort();
2874
+ let addr;
2875
+ try {
2876
+ addr = new URL2(location, address);
2877
+ } catch (e) {
2878
+ const err = new SyntaxError(`Invalid URL: ${location}`);
2879
+ emitErrorAndClose(websocket, err);
2880
+ return;
2881
+ }
2882
+ initAsClient(websocket, addr, protocols, options);
2883
+ } else if (!websocket.emit("unexpected-response", req, res)) {
2884
+ abortHandshake(
2885
+ websocket,
2886
+ req,
2887
+ `Unexpected server response: ${res.statusCode}`
2888
+ );
2889
+ }
2890
+ });
2891
+ req.on("upgrade", (res, socket, head) => {
2892
+ websocket.emit("upgrade", res);
2893
+ if (websocket.readyState !== WebSocket2.CONNECTING) return;
2894
+ req = websocket._req = null;
2895
+ const upgrade = res.headers.upgrade;
2896
+ if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") {
2897
+ abortHandshake(websocket, socket, "Invalid Upgrade header");
2898
+ return;
2899
+ }
2900
+ const digest = createHash2("sha1").update(key + GUID).digest("base64");
2901
+ if (res.headers["sec-websocket-accept"] !== digest) {
2902
+ abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
2903
+ return;
2904
+ }
2905
+ const serverProt = res.headers["sec-websocket-protocol"];
2906
+ let protError;
2907
+ if (serverProt !== void 0) {
2908
+ if (!protocolSet.size) {
2909
+ protError = "Server sent a subprotocol but none was requested";
2910
+ } else if (!protocolSet.has(serverProt)) {
2911
+ protError = "Server sent an invalid subprotocol";
2912
+ }
2913
+ } else if (protocolSet.size) {
2914
+ protError = "Server sent no subprotocol";
2915
+ }
2916
+ if (protError) {
2917
+ abortHandshake(websocket, socket, protError);
2918
+ return;
2919
+ }
2920
+ if (serverProt) websocket._protocol = serverProt;
2921
+ const secWebSocketExtensions = res.headers["sec-websocket-extensions"];
2922
+ if (secWebSocketExtensions !== void 0) {
2923
+ if (!perMessageDeflate) {
2924
+ const message = "Server sent a Sec-WebSocket-Extensions header but no extension was requested";
2925
+ abortHandshake(websocket, socket, message);
2926
+ return;
2927
+ }
2928
+ let extensions;
2929
+ try {
2930
+ extensions = parse(secWebSocketExtensions);
2931
+ } catch (err) {
2932
+ const message = "Invalid Sec-WebSocket-Extensions header";
2933
+ abortHandshake(websocket, socket, message);
2934
+ return;
2935
+ }
2936
+ const extensionNames = Object.keys(extensions);
2937
+ if (extensionNames.length !== 1 || extensionNames[0] !== PerMessageDeflate2.extensionName) {
2938
+ const message = "Server indicated an extension that was not requested";
2939
+ abortHandshake(websocket, socket, message);
2940
+ return;
2941
+ }
2942
+ try {
2943
+ perMessageDeflate.accept(extensions[PerMessageDeflate2.extensionName]);
2944
+ } catch (err) {
2945
+ const message = "Invalid Sec-WebSocket-Extensions header";
2946
+ abortHandshake(websocket, socket, message);
2947
+ return;
2948
+ }
2949
+ websocket._extensions[PerMessageDeflate2.extensionName] = perMessageDeflate;
2950
+ }
2951
+ websocket.setSocket(socket, head, {
2952
+ allowSynchronousEvents: opts.allowSynchronousEvents,
2953
+ generateMask: opts.generateMask,
2954
+ maxPayload: opts.maxPayload,
2955
+ skipUTF8Validation: opts.skipUTF8Validation
2956
+ });
2957
+ });
2958
+ if (opts.finishRequest) {
2959
+ opts.finishRequest(req, websocket);
2960
+ } else {
2961
+ req.end();
2962
+ }
2963
+ }
2964
+ function emitErrorAndClose(websocket, err) {
2965
+ websocket._readyState = WebSocket2.CLOSING;
2966
+ websocket._errorEmitted = true;
2967
+ websocket.emit("error", err);
2968
+ websocket.emitClose();
2969
+ }
2970
+ function netConnect(options) {
2971
+ options.path = options.socketPath;
2972
+ return net3.connect(options);
2973
+ }
2974
+ function tlsConnect(options) {
2975
+ options.path = void 0;
2976
+ if (!options.servername && options.servername !== "") {
2977
+ options.servername = net3.isIP(options.host) ? "" : options.host;
2978
+ }
2979
+ return tls.connect(options);
2980
+ }
2981
+ function abortHandshake(websocket, stream, message) {
2982
+ websocket._readyState = WebSocket2.CLOSING;
2983
+ const err = new Error(message);
2984
+ Error.captureStackTrace(err, abortHandshake);
2985
+ if (stream.setHeader) {
2986
+ stream[kAborted] = true;
2987
+ stream.abort();
2988
+ if (stream.socket && !stream.socket.destroyed) {
2989
+ stream.socket.destroy();
2990
+ }
2991
+ process.nextTick(emitErrorAndClose, websocket, err);
2992
+ } else {
2993
+ stream.destroy(err);
2994
+ stream.once("error", websocket.emit.bind(websocket, "error"));
2995
+ stream.once("close", websocket.emitClose.bind(websocket));
2996
+ }
2997
+ }
2998
+ function sendAfterClose(websocket, data, cb) {
2999
+ if (data) {
3000
+ const length = isBlob(data) ? data.size : toBuffer(data).length;
3001
+ if (websocket._socket) websocket._sender._bufferedBytes += length;
3002
+ else websocket._bufferedAmount += length;
3003
+ }
3004
+ if (cb) {
3005
+ const err = new Error(
3006
+ `WebSocket is not open: readyState ${websocket.readyState} (${readyStates[websocket.readyState]})`
3007
+ );
3008
+ process.nextTick(cb, err);
3009
+ }
3010
+ }
3011
+ function receiverOnConclude(code, reason) {
3012
+ const websocket = this[kWebSocket];
3013
+ websocket._closeFrameReceived = true;
3014
+ websocket._closeMessage = reason;
3015
+ websocket._closeCode = code;
3016
+ if (websocket._socket[kWebSocket] === void 0) return;
3017
+ websocket._socket.removeListener("data", socketOnData);
3018
+ process.nextTick(resume, websocket._socket);
3019
+ if (code === 1005) websocket.close();
3020
+ else websocket.close(code, reason);
3021
+ }
3022
+ function receiverOnDrain() {
3023
+ const websocket = this[kWebSocket];
3024
+ if (!websocket.isPaused) websocket._socket.resume();
3025
+ }
3026
+ function receiverOnError(err) {
3027
+ const websocket = this[kWebSocket];
3028
+ if (websocket._socket[kWebSocket] !== void 0) {
3029
+ websocket._socket.removeListener("data", socketOnData);
3030
+ process.nextTick(resume, websocket._socket);
3031
+ websocket.close(err[kStatusCode]);
3032
+ }
3033
+ if (!websocket._errorEmitted) {
3034
+ websocket._errorEmitted = true;
3035
+ websocket.emit("error", err);
3036
+ }
3037
+ }
3038
+ function receiverOnFinish() {
3039
+ this[kWebSocket].emitClose();
3040
+ }
3041
+ function receiverOnMessage(data, isBinary) {
3042
+ this[kWebSocket].emit("message", data, isBinary);
3043
+ }
3044
+ function receiverOnPing(data) {
3045
+ const websocket = this[kWebSocket];
3046
+ if (websocket._autoPong) websocket.pong(data, !this._isServer, NOOP);
3047
+ websocket.emit("ping", data);
3048
+ }
3049
+ function receiverOnPong(data) {
3050
+ this[kWebSocket].emit("pong", data);
3051
+ }
3052
+ function resume(stream) {
3053
+ stream.resume();
3054
+ }
3055
+ function senderOnError(err) {
3056
+ const websocket = this[kWebSocket];
3057
+ if (websocket.readyState === WebSocket2.CLOSED) return;
3058
+ if (websocket.readyState === WebSocket2.OPEN) {
3059
+ websocket._readyState = WebSocket2.CLOSING;
3060
+ setCloseTimer(websocket);
3061
+ }
3062
+ this._socket.end();
3063
+ if (!websocket._errorEmitted) {
3064
+ websocket._errorEmitted = true;
3065
+ websocket.emit("error", err);
3066
+ }
3067
+ }
3068
+ function setCloseTimer(websocket) {
3069
+ websocket._closeTimer = setTimeout(
3070
+ websocket._socket.destroy.bind(websocket._socket),
3071
+ websocket._closeTimeout
3072
+ );
3073
+ }
3074
+ function socketOnClose() {
3075
+ const websocket = this[kWebSocket];
3076
+ this.removeListener("close", socketOnClose);
3077
+ this.removeListener("data", socketOnData);
3078
+ this.removeListener("end", socketOnEnd);
3079
+ websocket._readyState = WebSocket2.CLOSING;
3080
+ if (!this._readableState.endEmitted && !websocket._closeFrameReceived && !websocket._receiver._writableState.errorEmitted && this._readableState.length !== 0) {
3081
+ const chunk = this.read(this._readableState.length);
3082
+ websocket._receiver.write(chunk);
3083
+ }
3084
+ websocket._receiver.end();
3085
+ this[kWebSocket] = void 0;
3086
+ clearTimeout(websocket._closeTimer);
3087
+ if (websocket._receiver._writableState.finished || websocket._receiver._writableState.errorEmitted) {
3088
+ websocket.emitClose();
3089
+ } else {
3090
+ websocket._receiver.on("error", receiverOnFinish);
3091
+ websocket._receiver.on("finish", receiverOnFinish);
3092
+ }
3093
+ }
3094
+ function socketOnData(chunk) {
3095
+ if (!this[kWebSocket]._receiver.write(chunk)) {
3096
+ this.pause();
3097
+ }
3098
+ }
3099
+ function socketOnEnd() {
3100
+ const websocket = this[kWebSocket];
3101
+ websocket._readyState = WebSocket2.CLOSING;
3102
+ websocket._receiver.end();
3103
+ this.end();
3104
+ }
3105
+ function socketOnError() {
3106
+ const websocket = this[kWebSocket];
3107
+ this.removeListener("error", socketOnError);
3108
+ this.on("error", NOOP);
3109
+ if (websocket) {
3110
+ websocket._readyState = WebSocket2.CLOSING;
3111
+ this.destroy();
3112
+ }
3113
+ }
3114
+ }
3115
+ });
3116
+
3117
+ // node_modules/ws/lib/stream.js
3118
+ var require_stream = __commonJS({
3119
+ "node_modules/ws/lib/stream.js"(exports, module) {
3120
+ "use strict";
3121
+ var WebSocket2 = require_websocket();
3122
+ var { Duplex } = __require("stream");
3123
+ function emitClose(stream) {
3124
+ stream.emit("close");
3125
+ }
3126
+ function duplexOnEnd() {
3127
+ if (!this.destroyed && this._writableState.finished) {
3128
+ this.destroy();
3129
+ }
3130
+ }
3131
+ function duplexOnError(err) {
3132
+ this.removeListener("error", duplexOnError);
3133
+ this.destroy();
3134
+ if (this.listenerCount("error") === 0) {
3135
+ this.emit("error", err);
3136
+ }
3137
+ }
3138
+ function createWebSocketStream2(ws, options) {
3139
+ let terminateOnDestroy = true;
3140
+ const duplex = new Duplex({
3141
+ ...options,
3142
+ autoDestroy: false,
3143
+ emitClose: false,
3144
+ objectMode: false,
3145
+ writableObjectMode: false
3146
+ });
3147
+ ws.on("message", function message(msg, isBinary) {
3148
+ const data = !isBinary && duplex._readableState.objectMode ? msg.toString() : msg;
3149
+ if (!duplex.push(data)) ws.pause();
3150
+ });
3151
+ ws.once("error", function error(err) {
3152
+ if (duplex.destroyed) return;
3153
+ terminateOnDestroy = false;
3154
+ duplex.destroy(err);
3155
+ });
3156
+ ws.once("close", function close() {
3157
+ if (duplex.destroyed) return;
3158
+ duplex.push(null);
3159
+ });
3160
+ duplex._destroy = function(err, callback) {
3161
+ if (ws.readyState === ws.CLOSED) {
3162
+ callback(err);
3163
+ process.nextTick(emitClose, duplex);
3164
+ return;
3165
+ }
3166
+ let called = false;
3167
+ ws.once("error", function error(err2) {
3168
+ called = true;
3169
+ callback(err2);
3170
+ });
3171
+ ws.once("close", function close() {
3172
+ if (!called) callback(err);
3173
+ process.nextTick(emitClose, duplex);
3174
+ });
3175
+ if (terminateOnDestroy) ws.terminate();
3176
+ };
3177
+ duplex._final = function(callback) {
3178
+ if (ws.readyState === ws.CONNECTING) {
3179
+ ws.once("open", function open() {
3180
+ duplex._final(callback);
3181
+ });
3182
+ return;
3183
+ }
3184
+ if (ws._socket === null) return;
3185
+ if (ws._socket._writableState.finished) {
3186
+ callback();
3187
+ if (duplex._readableState.endEmitted) duplex.destroy();
3188
+ } else {
3189
+ ws._socket.once("finish", function finish() {
3190
+ callback();
3191
+ });
3192
+ ws.close();
3193
+ }
3194
+ };
3195
+ duplex._read = function() {
3196
+ if (ws.isPaused) ws.resume();
3197
+ };
3198
+ duplex._write = function(chunk, encoding, callback) {
3199
+ if (ws.readyState === ws.CONNECTING) {
3200
+ ws.once("open", function open() {
3201
+ duplex._write(chunk, encoding, callback);
3202
+ });
3203
+ return;
3204
+ }
3205
+ ws.send(chunk, callback);
3206
+ };
3207
+ duplex.on("end", duplexOnEnd);
3208
+ duplex.on("error", duplexOnError);
3209
+ return duplex;
3210
+ }
3211
+ module.exports = createWebSocketStream2;
3212
+ }
3213
+ });
3214
+
3215
+ // node_modules/ws/lib/subprotocol.js
3216
+ var require_subprotocol = __commonJS({
3217
+ "node_modules/ws/lib/subprotocol.js"(exports, module) {
3218
+ "use strict";
3219
+ var { tokenChars } = require_validation();
3220
+ function parse(header) {
3221
+ const protocols = /* @__PURE__ */ new Set();
3222
+ let start = -1;
3223
+ let end = -1;
3224
+ let i = 0;
3225
+ for (i; i < header.length; i++) {
3226
+ const code = header.charCodeAt(i);
3227
+ if (end === -1 && tokenChars[code] === 1) {
3228
+ if (start === -1) start = i;
3229
+ } else if (i !== 0 && (code === 32 || code === 9)) {
3230
+ if (end === -1 && start !== -1) end = i;
3231
+ } else if (code === 44) {
3232
+ if (start === -1) {
3233
+ throw new SyntaxError(`Unexpected character at index ${i}`);
3234
+ }
3235
+ if (end === -1) end = i;
3236
+ const protocol2 = header.slice(start, end);
3237
+ if (protocols.has(protocol2)) {
3238
+ throw new SyntaxError(`The "${protocol2}" subprotocol is duplicated`);
3239
+ }
3240
+ protocols.add(protocol2);
3241
+ start = end = -1;
3242
+ } else {
3243
+ throw new SyntaxError(`Unexpected character at index ${i}`);
3244
+ }
3245
+ }
3246
+ if (start === -1 || end !== -1) {
3247
+ throw new SyntaxError("Unexpected end of input");
3248
+ }
3249
+ const protocol = header.slice(start, i);
3250
+ if (protocols.has(protocol)) {
3251
+ throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);
3252
+ }
3253
+ protocols.add(protocol);
3254
+ return protocols;
3255
+ }
3256
+ module.exports = { parse };
3257
+ }
3258
+ });
3259
+
3260
+ // node_modules/ws/lib/websocket-server.js
3261
+ var require_websocket_server = __commonJS({
3262
+ "node_modules/ws/lib/websocket-server.js"(exports, module) {
3263
+ "use strict";
3264
+ var EventEmitter2 = __require("events");
3265
+ var http3 = __require("http");
3266
+ var { Duplex } = __require("stream");
3267
+ var { createHash: createHash2 } = __require("crypto");
3268
+ var extension2 = require_extension();
3269
+ var PerMessageDeflate2 = require_permessage_deflate();
3270
+ var subprotocol2 = require_subprotocol();
3271
+ var WebSocket2 = require_websocket();
3272
+ var { CLOSE_TIMEOUT, GUID, kWebSocket } = require_constants();
3273
+ var keyRegex = /^[+/0-9A-Za-z]{22}==$/;
3274
+ var RUNNING = 0;
3275
+ var CLOSING = 1;
3276
+ var CLOSED = 2;
3277
+ var WebSocketServer2 = class extends EventEmitter2 {
3278
+ /**
3279
+ * Create a `WebSocketServer` instance.
3280
+ *
3281
+ * @param {Object} options Configuration options
3282
+ * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
3283
+ * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
3284
+ * multiple times in the same tick
3285
+ * @param {Boolean} [options.autoPong=true] Specifies whether or not to
3286
+ * automatically send a pong in response to a ping
3287
+ * @param {Number} [options.backlog=511] The maximum length of the queue of
3288
+ * pending connections
3289
+ * @param {Boolean} [options.clientTracking=true] Specifies whether or not to
3290
+ * track clients
3291
+ * @param {Number} [options.closeTimeout=30000] Duration in milliseconds to
3292
+ * wait for the closing handshake to finish after `websocket.close()` is
3293
+ * called
3294
+ * @param {Function} [options.handleProtocols] A hook to handle protocols
3295
+ * @param {String} [options.host] The hostname where to bind the server
3296
+ * @param {Number} [options.maxPayload=104857600] The maximum allowed message
3297
+ * size
3298
+ * @param {Boolean} [options.noServer=false] Enable no server mode
3299
+ * @param {String} [options.path] Accept only connections matching this path
3300
+ * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable
3301
+ * permessage-deflate
3302
+ * @param {Number} [options.port] The port where to bind the server
3303
+ * @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S
3304
+ * server to use
3305
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
3306
+ * not to skip UTF-8 validation for text and close messages
3307
+ * @param {Function} [options.verifyClient] A hook to reject connections
3308
+ * @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket`
3309
+ * class to use. It must be the `WebSocket` class or class that extends it
3310
+ * @param {Function} [callback] A listener for the `listening` event
3311
+ */
3312
+ constructor(options, callback) {
3313
+ super();
3314
+ options = {
3315
+ allowSynchronousEvents: true,
3316
+ autoPong: true,
3317
+ maxPayload: 100 * 1024 * 1024,
3318
+ skipUTF8Validation: false,
3319
+ perMessageDeflate: false,
3320
+ handleProtocols: null,
3321
+ clientTracking: true,
3322
+ closeTimeout: CLOSE_TIMEOUT,
3323
+ verifyClient: null,
3324
+ noServer: false,
3325
+ backlog: null,
3326
+ // use default (511 as implemented in net.js)
3327
+ server: null,
3328
+ host: null,
3329
+ path: null,
3330
+ port: null,
3331
+ WebSocket: WebSocket2,
3332
+ ...options
3333
+ };
3334
+ if (options.port == null && !options.server && !options.noServer || options.port != null && (options.server || options.noServer) || options.server && options.noServer) {
3335
+ throw new TypeError(
3336
+ 'One and only one of the "port", "server", or "noServer" options must be specified'
3337
+ );
3338
+ }
3339
+ if (options.port != null) {
3340
+ this._server = http3.createServer((req, res) => {
3341
+ const body = http3.STATUS_CODES[426];
3342
+ res.writeHead(426, {
3343
+ "Content-Length": body.length,
3344
+ "Content-Type": "text/plain"
3345
+ });
3346
+ res.end(body);
3347
+ });
3348
+ this._server.listen(
3349
+ options.port,
3350
+ options.host,
3351
+ options.backlog,
3352
+ callback
3353
+ );
3354
+ } else if (options.server) {
3355
+ this._server = options.server;
3356
+ }
3357
+ if (this._server) {
3358
+ const emitConnection = this.emit.bind(this, "connection");
3359
+ this._removeListeners = addListeners(this._server, {
3360
+ listening: this.emit.bind(this, "listening"),
3361
+ error: this.emit.bind(this, "error"),
3362
+ upgrade: (req, socket, head) => {
3363
+ this.handleUpgrade(req, socket, head, emitConnection);
3364
+ }
3365
+ });
3366
+ }
3367
+ if (options.perMessageDeflate === true) options.perMessageDeflate = {};
3368
+ if (options.clientTracking) {
3369
+ this.clients = /* @__PURE__ */ new Set();
3370
+ this._shouldEmitClose = false;
3371
+ }
3372
+ this.options = options;
3373
+ this._state = RUNNING;
3374
+ }
3375
+ /**
3376
+ * Returns the bound address, the address family name, and port of the server
3377
+ * as reported by the operating system if listening on an IP socket.
3378
+ * If the server is listening on a pipe or UNIX domain socket, the name is
3379
+ * returned as a string.
3380
+ *
3381
+ * @return {(Object|String|null)} The address of the server
3382
+ * @public
3383
+ */
3384
+ address() {
3385
+ if (this.options.noServer) {
3386
+ throw new Error('The server is operating in "noServer" mode');
3387
+ }
3388
+ if (!this._server) return null;
3389
+ return this._server.address();
3390
+ }
3391
+ /**
3392
+ * Stop the server from accepting new connections and emit the `'close'` event
3393
+ * when all existing connections are closed.
3394
+ *
3395
+ * @param {Function} [cb] A one-time listener for the `'close'` event
3396
+ * @public
3397
+ */
3398
+ close(cb) {
3399
+ if (this._state === CLOSED) {
3400
+ if (cb) {
3401
+ this.once("close", () => {
3402
+ cb(new Error("The server is not running"));
3403
+ });
3404
+ }
3405
+ process.nextTick(emitClose, this);
3406
+ return;
3407
+ }
3408
+ if (cb) this.once("close", cb);
3409
+ if (this._state === CLOSING) return;
3410
+ this._state = CLOSING;
3411
+ if (this.options.noServer || this.options.server) {
3412
+ if (this._server) {
3413
+ this._removeListeners();
3414
+ this._removeListeners = this._server = null;
3415
+ }
3416
+ if (this.clients) {
3417
+ if (!this.clients.size) {
3418
+ process.nextTick(emitClose, this);
3419
+ } else {
3420
+ this._shouldEmitClose = true;
3421
+ }
3422
+ } else {
3423
+ process.nextTick(emitClose, this);
3424
+ }
3425
+ } else {
3426
+ const server = this._server;
3427
+ this._removeListeners();
3428
+ this._removeListeners = this._server = null;
3429
+ server.close(() => {
3430
+ emitClose(this);
3431
+ });
3432
+ }
3433
+ }
3434
+ /**
3435
+ * See if a given request should be handled by this server instance.
3436
+ *
3437
+ * @param {http.IncomingMessage} req Request object to inspect
3438
+ * @return {Boolean} `true` if the request is valid, else `false`
3439
+ * @public
3440
+ */
3441
+ shouldHandle(req) {
3442
+ if (this.options.path) {
3443
+ const index = req.url.indexOf("?");
3444
+ const pathname = index !== -1 ? req.url.slice(0, index) : req.url;
3445
+ if (pathname !== this.options.path) return false;
3446
+ }
3447
+ return true;
3448
+ }
3449
+ /**
3450
+ * Handle a HTTP Upgrade request.
3451
+ *
3452
+ * @param {http.IncomingMessage} req The request object
3453
+ * @param {Duplex} socket The network socket between the server and client
3454
+ * @param {Buffer} head The first packet of the upgraded stream
3455
+ * @param {Function} cb Callback
3456
+ * @public
3457
+ */
3458
+ handleUpgrade(req, socket, head, cb) {
3459
+ socket.on("error", socketOnError);
3460
+ const key = req.headers["sec-websocket-key"];
3461
+ const upgrade = req.headers.upgrade;
3462
+ const version = +req.headers["sec-websocket-version"];
3463
+ if (req.method !== "GET") {
3464
+ const message = "Invalid HTTP method";
3465
+ abortHandshakeOrEmitwsClientError(this, req, socket, 405, message);
3466
+ return;
3467
+ }
3468
+ if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") {
3469
+ const message = "Invalid Upgrade header";
3470
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
3471
+ return;
3472
+ }
3473
+ if (key === void 0 || !keyRegex.test(key)) {
3474
+ const message = "Missing or invalid Sec-WebSocket-Key header";
3475
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
3476
+ return;
3477
+ }
3478
+ if (version !== 13 && version !== 8) {
3479
+ const message = "Missing or invalid Sec-WebSocket-Version header";
3480
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message, {
3481
+ "Sec-WebSocket-Version": "13, 8"
3482
+ });
3483
+ return;
3484
+ }
3485
+ if (!this.shouldHandle(req)) {
3486
+ abortHandshake(socket, 400);
3487
+ return;
3488
+ }
3489
+ const secWebSocketProtocol = req.headers["sec-websocket-protocol"];
3490
+ let protocols = /* @__PURE__ */ new Set();
3491
+ if (secWebSocketProtocol !== void 0) {
3492
+ try {
3493
+ protocols = subprotocol2.parse(secWebSocketProtocol);
3494
+ } catch (err) {
3495
+ const message = "Invalid Sec-WebSocket-Protocol header";
3496
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
3497
+ return;
3498
+ }
3499
+ }
3500
+ const secWebSocketExtensions = req.headers["sec-websocket-extensions"];
3501
+ const extensions = {};
3502
+ if (this.options.perMessageDeflate && secWebSocketExtensions !== void 0) {
3503
+ const perMessageDeflate = new PerMessageDeflate2({
3504
+ ...this.options.perMessageDeflate,
3505
+ isServer: true,
3506
+ maxPayload: this.options.maxPayload
3507
+ });
3508
+ try {
3509
+ const offers = extension2.parse(secWebSocketExtensions);
3510
+ if (offers[PerMessageDeflate2.extensionName]) {
3511
+ perMessageDeflate.accept(offers[PerMessageDeflate2.extensionName]);
3512
+ extensions[PerMessageDeflate2.extensionName] = perMessageDeflate;
3513
+ }
3514
+ } catch (err) {
3515
+ const message = "Invalid or unacceptable Sec-WebSocket-Extensions header";
3516
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
3517
+ return;
3518
+ }
3519
+ }
3520
+ if (this.options.verifyClient) {
3521
+ const info = {
3522
+ origin: req.headers[`${version === 8 ? "sec-websocket-origin" : "origin"}`],
3523
+ secure: !!(req.socket.authorized || req.socket.encrypted),
3524
+ req
3525
+ };
3526
+ if (this.options.verifyClient.length === 2) {
3527
+ this.options.verifyClient(info, (verified, code, message, headers) => {
3528
+ if (!verified) {
3529
+ return abortHandshake(socket, code || 401, message, headers);
3530
+ }
3531
+ this.completeUpgrade(
3532
+ extensions,
3533
+ key,
3534
+ protocols,
3535
+ req,
3536
+ socket,
3537
+ head,
3538
+ cb
3539
+ );
3540
+ });
3541
+ return;
3542
+ }
3543
+ if (!this.options.verifyClient(info)) return abortHandshake(socket, 401);
3544
+ }
3545
+ this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);
3546
+ }
3547
+ /**
3548
+ * Upgrade the connection to WebSocket.
3549
+ *
3550
+ * @param {Object} extensions The accepted extensions
3551
+ * @param {String} key The value of the `Sec-WebSocket-Key` header
3552
+ * @param {Set} protocols The subprotocols
3553
+ * @param {http.IncomingMessage} req The request object
3554
+ * @param {Duplex} socket The network socket between the server and client
3555
+ * @param {Buffer} head The first packet of the upgraded stream
3556
+ * @param {Function} cb Callback
3557
+ * @throws {Error} If called more than once with the same socket
3558
+ * @private
3559
+ */
3560
+ completeUpgrade(extensions, key, protocols, req, socket, head, cb) {
3561
+ if (!socket.readable || !socket.writable) return socket.destroy();
3562
+ if (socket[kWebSocket]) {
3563
+ throw new Error(
3564
+ "server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration"
3565
+ );
3566
+ }
3567
+ if (this._state > RUNNING) return abortHandshake(socket, 503);
3568
+ const digest = createHash2("sha1").update(key + GUID).digest("base64");
3569
+ const headers = [
3570
+ "HTTP/1.1 101 Switching Protocols",
3571
+ "Upgrade: websocket",
3572
+ "Connection: Upgrade",
3573
+ `Sec-WebSocket-Accept: ${digest}`
3574
+ ];
3575
+ const ws = new this.options.WebSocket(null, void 0, this.options);
3576
+ if (protocols.size) {
3577
+ const protocol = this.options.handleProtocols ? this.options.handleProtocols(protocols, req) : protocols.values().next().value;
3578
+ if (protocol) {
3579
+ headers.push(`Sec-WebSocket-Protocol: ${protocol}`);
3580
+ ws._protocol = protocol;
3581
+ }
3582
+ }
3583
+ if (extensions[PerMessageDeflate2.extensionName]) {
3584
+ const params = extensions[PerMessageDeflate2.extensionName].params;
3585
+ const value = extension2.format({
3586
+ [PerMessageDeflate2.extensionName]: [params]
3587
+ });
3588
+ headers.push(`Sec-WebSocket-Extensions: ${value}`);
3589
+ ws._extensions = extensions;
3590
+ }
3591
+ this.emit("headers", headers, req);
3592
+ socket.write(headers.concat("\r\n").join("\r\n"));
3593
+ socket.removeListener("error", socketOnError);
3594
+ ws.setSocket(socket, head, {
3595
+ allowSynchronousEvents: this.options.allowSynchronousEvents,
3596
+ maxPayload: this.options.maxPayload,
3597
+ skipUTF8Validation: this.options.skipUTF8Validation
3598
+ });
3599
+ if (this.clients) {
3600
+ this.clients.add(ws);
3601
+ ws.on("close", () => {
3602
+ this.clients.delete(ws);
3603
+ if (this._shouldEmitClose && !this.clients.size) {
3604
+ process.nextTick(emitClose, this);
3605
+ }
3606
+ });
3607
+ }
3608
+ cb(ws, req);
3609
+ }
3610
+ };
3611
+ module.exports = WebSocketServer2;
3612
+ function addListeners(server, map) {
3613
+ for (const event of Object.keys(map)) server.on(event, map[event]);
3614
+ return function removeListeners() {
3615
+ for (const event of Object.keys(map)) {
3616
+ server.removeListener(event, map[event]);
3617
+ }
3618
+ };
3619
+ }
3620
+ function emitClose(server) {
3621
+ server._state = CLOSED;
3622
+ server.emit("close");
3623
+ }
3624
+ function socketOnError() {
3625
+ this.destroy();
3626
+ }
3627
+ function abortHandshake(socket, code, message, headers) {
3628
+ message = message || http3.STATUS_CODES[code];
3629
+ headers = {
3630
+ Connection: "close",
3631
+ "Content-Type": "text/html",
3632
+ "Content-Length": Buffer.byteLength(message),
3633
+ ...headers
3634
+ };
3635
+ socket.once("finish", socket.destroy);
3636
+ socket.end(
3637
+ `HTTP/1.1 ${code} ${http3.STATUS_CODES[code]}\r
3638
+ ` + Object.keys(headers).map((h) => `${h}: ${headers[h]}`).join("\r\n") + "\r\n\r\n" + message
3639
+ );
3640
+ }
3641
+ function abortHandshakeOrEmitwsClientError(server, req, socket, code, message, headers) {
3642
+ if (server.listenerCount("wsClientError")) {
3643
+ const err = new Error(message);
3644
+ Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError);
3645
+ server.emit("wsClientError", err, socket, req);
3646
+ } else {
3647
+ abortHandshake(socket, code, message, headers);
3648
+ }
3649
+ }
3650
+ }
3651
+ });
3652
+
3653
+ // node_modules/ws/wrapper.mjs
3654
+ var import_stream, import_extension, import_permessage_deflate, import_receiver, import_sender, import_subprotocol, import_websocket, import_websocket_server, wrapper_default;
3655
+ var init_wrapper = __esm({
3656
+ "node_modules/ws/wrapper.mjs"() {
3657
+ "use strict";
3658
+ import_stream = __toESM(require_stream(), 1);
3659
+ import_extension = __toESM(require_extension(), 1);
3660
+ import_permessage_deflate = __toESM(require_permessage_deflate(), 1);
3661
+ import_receiver = __toESM(require_receiver(), 1);
3662
+ import_sender = __toESM(require_sender(), 1);
3663
+ import_subprotocol = __toESM(require_subprotocol(), 1);
3664
+ import_websocket = __toESM(require_websocket(), 1);
3665
+ import_websocket_server = __toESM(require_websocket_server(), 1);
3666
+ wrapper_default = import_websocket.default;
3667
+ }
3668
+ });
3669
+
3670
+ // src/proxy/dispatcher.ts
3671
+ import { Agent } from "undici";
3672
+ var skalpelDispatcher;
3673
+ var init_dispatcher = __esm({
3674
+ "src/proxy/dispatcher.ts"() {
3675
+ "use strict";
3676
+ skalpelDispatcher = new Agent({
3677
+ keepAliveTimeout: 1e4,
3678
+ keepAliveMaxTimeout: 6e4,
3679
+ connections: 100,
3680
+ pipelining: 1
3681
+ });
3682
+ }
3683
+ });
3684
+
3685
+ // src/proxy/envelope.ts
3686
+ var init_envelope = __esm({
3687
+ "src/proxy/envelope.ts"() {
3688
+ "use strict";
3689
+ }
3690
+ });
3691
+
3692
+ // src/proxy/recovery.ts
3693
+ import { createHash } from "crypto";
3694
+ var MUTEX_MAX_ENTRIES, LruMutexMap, refreshMutex;
3695
+ var init_recovery = __esm({
3696
+ "src/proxy/recovery.ts"() {
3697
+ "use strict";
3698
+ MUTEX_MAX_ENTRIES = 1024;
3699
+ LruMutexMap = class extends Map {
3700
+ set(key, value) {
3701
+ if (this.has(key)) {
3702
+ super.delete(key);
3703
+ } else if (this.size >= MUTEX_MAX_ENTRIES) {
3704
+ const oldest = this.keys().next().value;
3705
+ if (oldest !== void 0) super.delete(oldest);
3706
+ }
3707
+ return super.set(key, value);
3708
+ }
3709
+ };
3710
+ refreshMutex = new LruMutexMap();
3711
+ }
3712
+ });
3713
+
3714
+ // src/proxy/fetch-error.ts
3715
+ var init_fetch_error = __esm({
3716
+ "src/proxy/fetch-error.ts"() {
3717
+ "use strict";
3718
+ }
3719
+ });
3720
+
3721
+ // src/proxy/streaming.ts
3722
+ var HOP_BY_HOP, STRIP_HEADERS;
3723
+ var init_streaming = __esm({
3724
+ "src/proxy/streaming.ts"() {
3725
+ "use strict";
3726
+ init_dispatcher();
3727
+ init_handler();
3728
+ init_envelope();
3729
+ init_recovery();
3730
+ init_fetch_error();
3731
+ HOP_BY_HOP = /* @__PURE__ */ new Set([
3732
+ "connection",
3733
+ "keep-alive",
3734
+ "proxy-authenticate",
3735
+ "proxy-authorization",
3736
+ "te",
3737
+ "trailer",
3738
+ "transfer-encoding",
3739
+ "upgrade"
3740
+ ]);
3741
+ STRIP_HEADERS = /* @__PURE__ */ new Set([
3742
+ ...HOP_BY_HOP,
3743
+ "content-encoding",
3744
+ "content-length"
3745
+ ]);
3746
+ }
3747
+ });
3748
+
3749
+ // src/proxy/ws-client.ts
3750
+ import { EventEmitter } from "events";
3751
+ var init_ws_client = __esm({
3752
+ "src/proxy/ws-client.ts"() {
3753
+ "use strict";
3754
+ init_wrapper();
3755
+ }
3756
+ });
3757
+
3758
+ // src/proxy/handler.ts
3759
+ var init_handler = __esm({
3760
+ "src/proxy/handler.ts"() {
3761
+ "use strict";
3762
+ init_streaming();
3763
+ init_dispatcher();
3764
+ init_envelope();
3765
+ init_ws_client();
3766
+ init_recovery();
3767
+ init_fetch_error();
3768
+ }
3769
+ });
2
3770
 
3
3771
  // src/cli/index.ts
4
3772
  import { Command } from "commander";
@@ -204,9 +3972,11 @@ ${envContent}`);
204
3972
  }
205
3973
 
206
3974
  // src/cli/doctor.ts
3975
+ init_wrapper();
207
3976
  import * as fs4 from "fs";
208
3977
  import * as path4 from "path";
209
3978
  import * as os2 from "os";
3979
+ import net from "net";
210
3980
 
211
3981
  // src/cli/agents/detect.ts
212
3982
  import { execSync } from "child_process";
@@ -362,6 +4132,70 @@ function checkCodexConfig(config) {
362
4132
  message: `missing TOML: ${missing.map((m) => m.split("\n")[0]).join("; ")}`
363
4133
  };
364
4134
  }
4135
+ async function checkCodexWebSocket(config) {
4136
+ const tcpOk = await new Promise((resolve2) => {
4137
+ const sock = net.connect({ host: "127.0.0.1", port: config.openaiPort, timeout: 1e3 });
4138
+ const done = (ok) => {
4139
+ sock.removeAllListeners();
4140
+ try {
4141
+ sock.destroy();
4142
+ } catch {
4143
+ }
4144
+ resolve2(ok);
4145
+ };
4146
+ sock.once("connect", () => done(true));
4147
+ sock.once("error", () => done(false));
4148
+ sock.once("timeout", () => done(false));
4149
+ });
4150
+ if (!tcpOk) {
4151
+ return {
4152
+ name: "Codex WebSocket",
4153
+ status: "skipped",
4154
+ message: "WebSocket: SKIPPED (proxy not running)"
4155
+ };
4156
+ }
4157
+ return new Promise((resolve2) => {
4158
+ const url = `ws://localhost:${config.openaiPort}/v1/responses`;
4159
+ let settled = false;
4160
+ const ws = new wrapper_default(url, ["skalpel-codex-v1"]);
4161
+ const settle = (result) => {
4162
+ if (settled) return;
4163
+ settled = true;
4164
+ try {
4165
+ ws.close();
4166
+ } catch {
4167
+ }
4168
+ resolve2(result);
4169
+ };
4170
+ const timeout = setTimeout(() => {
4171
+ settle({
4172
+ name: "Codex WebSocket",
4173
+ status: "fail",
4174
+ message: "WebSocket: FAIL handshake timeout after 5s"
4175
+ });
4176
+ }, 5e3);
4177
+ ws.once("open", () => {
4178
+ clearTimeout(timeout);
4179
+ settle({ name: "Codex WebSocket", status: "ok", message: "WebSocket: OK" });
4180
+ });
4181
+ ws.once("error", (err) => {
4182
+ clearTimeout(timeout);
4183
+ settle({
4184
+ name: "Codex WebSocket",
4185
+ status: "fail",
4186
+ message: `WebSocket: FAIL ${err.message}`
4187
+ });
4188
+ });
4189
+ ws.once("unexpected-response", (_req, res) => {
4190
+ clearTimeout(timeout);
4191
+ settle({
4192
+ name: "Codex WebSocket",
4193
+ status: "fail",
4194
+ message: `WebSocket: FAIL unexpected HTTP ${res.statusCode}`
4195
+ });
4196
+ });
4197
+ });
4198
+ }
365
4199
  async function checkCodexProxyProbe(config) {
366
4200
  const url = `http://localhost:${config.openaiPort}/v1/responses`;
367
4201
  try {
@@ -508,7 +4342,8 @@ async function runDoctor() {
508
4342
  const config = { openaiPort };
509
4343
  checks.push(checkCodexConfig(config));
510
4344
  checks.push(await checkCodexProxyProbe(config));
511
- const icons = { ok: "+", warn: "!", fail: "x", error: "x" };
4345
+ checks.push(await checkCodexWebSocket(config));
4346
+ const icons = { ok: "+", warn: "!", fail: "x", error: "x", skipped: "-" };
512
4347
  for (const check of checks) {
513
4348
  const icon = icons[check.status];
514
4349
  print2(` [${icon}] ${check.name}: ${check.message}`);
@@ -711,7 +4546,7 @@ async function runReplay(filePaths) {
711
4546
 
712
4547
  // src/cli/start.ts
713
4548
  import { spawn } from "child_process";
714
- import path10 from "path";
4549
+ import path12 from "path";
715
4550
  import { fileURLToPath as fileURLToPath2 } from "url";
716
4551
 
717
4552
  // src/proxy/config.ts
@@ -848,6 +4683,20 @@ function removePid(pidFile) {
848
4683
  }
849
4684
  }
850
4685
 
4686
+ // src/proxy/health-check.ts
4687
+ async function isProxyAlive(port, timeoutMs = 2e3) {
4688
+ const controller = new AbortController();
4689
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
4690
+ try {
4691
+ const res = await fetch(`http://localhost:${port}/health`, { signal: controller.signal });
4692
+ return res.ok;
4693
+ } catch {
4694
+ return false;
4695
+ } finally {
4696
+ clearTimeout(timer);
4697
+ }
4698
+ }
4699
+
851
4700
  // src/cli/service/install.ts
852
4701
  import fs8 from "fs";
853
4702
  import path9 from "path";
@@ -1186,216 +5035,36 @@ function uninstallService() {
1186
5035
  } catch {
1187
5036
  }
1188
5037
  break;
1189
- }
1190
- }
1191
- }
1192
-
1193
- // src/cli/start.ts
1194
- function print5(msg) {
1195
- console.log(msg);
1196
- }
1197
- async function runStart() {
1198
- const config = loadConfig();
1199
- if (!config.apiKey) {
1200
- print5(' Error: No API key configured. Run "skalpel init" or set SKALPEL_API_KEY.');
1201
- process.exit(1);
1202
- }
1203
- const existingPid = readPid(config.pidFile);
1204
- if (existingPid !== null) {
1205
- print5(` Proxy is already running (pid=${existingPid}).`);
1206
- return;
1207
- }
1208
- if (isServiceInstalled()) {
1209
- startService();
1210
- print5(` Skalpel proxy started via system service on ports ${config.anthropicPort}, ${config.openaiPort}, and ${config.cursorPort}`);
1211
- return;
1212
- }
1213
- const dirname = path10.dirname(fileURLToPath2(import.meta.url));
1214
- const runnerScript = path10.resolve(dirname, "proxy-runner.js");
1215
- const child = spawn(process.execPath, [runnerScript], {
1216
- detached: true,
1217
- stdio: "ignore"
1218
- });
1219
- child.unref();
1220
- print5(` Skalpel proxy started on ports ${config.anthropicPort}, ${config.openaiPort}, and ${config.cursorPort}`);
1221
- }
1222
-
1223
- // src/proxy/server.ts
1224
- import http from "http";
1225
-
1226
- // src/proxy/dispatcher.ts
1227
- import { Agent } from "undici";
1228
- var skalpelDispatcher = new Agent({
1229
- keepAliveTimeout: 1e4,
1230
- keepAliveMaxTimeout: 6e4,
1231
- connections: 100,
1232
- pipelining: 1
1233
- });
1234
-
1235
- // src/proxy/recovery.ts
1236
- import { createHash } from "crypto";
1237
- var MUTEX_MAX_ENTRIES = 1024;
1238
- var LruMutexMap = class extends Map {
1239
- set(key, value) {
1240
- if (this.has(key)) {
1241
- super.delete(key);
1242
- } else if (this.size >= MUTEX_MAX_ENTRIES) {
1243
- const oldest = this.keys().next().value;
1244
- if (oldest !== void 0) super.delete(oldest);
1245
- }
1246
- return super.set(key, value);
1247
- }
1248
- };
1249
- var refreshMutex = new LruMutexMap();
1250
-
1251
- // src/proxy/streaming.ts
1252
- var HOP_BY_HOP = /* @__PURE__ */ new Set([
1253
- "connection",
1254
- "keep-alive",
1255
- "proxy-authenticate",
1256
- "proxy-authorization",
1257
- "te",
1258
- "trailer",
1259
- "transfer-encoding",
1260
- "upgrade"
1261
- ]);
1262
- var STRIP_HEADERS = /* @__PURE__ */ new Set([
1263
- ...HOP_BY_HOP,
1264
- "content-encoding",
1265
- "content-length"
1266
- ]);
1267
-
1268
- // src/proxy/logger.ts
1269
- import fs9 from "fs";
1270
- import path11 from "path";
1271
- var MAX_SIZE = 5 * 1024 * 1024;
1272
-
1273
- // src/proxy/server.ts
1274
- var proxyStartTime = 0;
1275
- function stopProxy(config) {
1276
- const pid = readPid(config.pidFile);
1277
- if (pid === null) return false;
1278
- try {
1279
- process.kill(pid, "SIGTERM");
1280
- } catch {
1281
- }
1282
- removePid(config.pidFile);
1283
- return true;
1284
- }
1285
- function getProxyStatus(config) {
1286
- const pid = readPid(config.pidFile);
1287
- return {
1288
- running: pid !== null,
1289
- pid,
1290
- uptime: proxyStartTime > 0 ? Date.now() - proxyStartTime : 0,
1291
- anthropicPort: config.anthropicPort,
1292
- openaiPort: config.openaiPort,
1293
- cursorPort: config.cursorPort
1294
- };
1295
- }
1296
-
1297
- // src/cli/stop.ts
1298
- function print6(msg) {
1299
- console.log(msg);
1300
- }
1301
- async function runStop() {
1302
- const config = loadConfig();
1303
- if (isServiceInstalled()) {
1304
- stopService();
1305
- }
1306
- const stopped = stopProxy(config);
1307
- if (stopped) {
1308
- print6(" Skalpel proxy stopped.");
1309
- } else {
1310
- print6(" Proxy is not running.");
1311
- }
1312
- }
1313
-
1314
- // src/cli/status.ts
1315
- function print7(msg) {
1316
- console.log(msg);
1317
- }
1318
- async function runStatus() {
1319
- const config = loadConfig();
1320
- const status = getProxyStatus(config);
1321
- print7("");
1322
- print7(" Skalpel Proxy Status");
1323
- print7(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500");
1324
- print7(` Status: ${status.running ? "running" : "stopped"}`);
1325
- if (status.pid !== null) {
1326
- print7(` PID: ${status.pid}`);
1327
- }
1328
- print7(` Anthropic: port ${status.anthropicPort}`);
1329
- print7(` OpenAI: port ${status.openaiPort}`);
1330
- print7(` Cursor: port ${status.cursorPort}`);
1331
- print7(` Config: ${config.configFile}`);
1332
- print7("");
1333
- }
1334
-
1335
- // src/cli/logs.ts
1336
- import fs10 from "fs";
1337
- function print8(msg) {
1338
- console.log(msg);
1339
- }
1340
- async function runLogs(options) {
1341
- const config = loadConfig();
1342
- const logFile = config.logFile;
1343
- const lineCount = parseInt(options.lines ?? "50", 10);
1344
- if (!fs10.existsSync(logFile)) {
1345
- print8(` No log file found at ${logFile}`);
1346
- return;
1347
- }
1348
- const content = fs10.readFileSync(logFile, "utf-8");
1349
- const lines = content.trimEnd().split("\n");
1350
- const tail = lines.slice(-lineCount);
1351
- for (const line of tail) {
1352
- print8(line);
1353
- }
1354
- if (options.follow) {
1355
- let position = fs10.statSync(logFile).size;
1356
- fs10.watchFile(logFile, { interval: 500 }, () => {
1357
- try {
1358
- const stat = fs10.statSync(logFile);
1359
- if (stat.size > position) {
1360
- const fd = fs10.openSync(logFile, "r");
1361
- const buf = Buffer.alloc(stat.size - position);
1362
- fs10.readSync(fd, buf, 0, buf.length, position);
1363
- fs10.closeSync(fd);
1364
- process.stdout.write(buf.toString("utf-8"));
1365
- position = stat.size;
1366
- }
1367
- } catch {
1368
- }
1369
- });
5038
+ }
1370
5039
  }
1371
5040
  }
1372
5041
 
1373
5042
  // src/cli/agents/configure.ts
1374
- import fs11 from "fs";
1375
- import path12 from "path";
5043
+ import fs9 from "fs";
5044
+ import path10 from "path";
1376
5045
  import os7 from "os";
1377
5046
  var CURSOR_API_BASE_URL_KEY = "openai.apiBaseUrl";
1378
5047
  var DIRECT_MODE_BASE_URL = "https://api.skalpel.ai";
1379
5048
  var CODEX_DIRECT_PROVIDER_ID = "skalpel";
1380
5049
  var CODEX_PROXY_PROVIDER_ID = "skalpel-proxy";
1381
5050
  function ensureDir(dir) {
1382
- fs11.mkdirSync(dir, { recursive: true });
5051
+ fs9.mkdirSync(dir, { recursive: true });
1383
5052
  }
1384
5053
  function createBackup(filePath) {
1385
- if (fs11.existsSync(filePath)) {
1386
- fs11.copyFileSync(filePath, `${filePath}.skalpel-backup`);
5054
+ if (fs9.existsSync(filePath)) {
5055
+ fs9.copyFileSync(filePath, `${filePath}.skalpel-backup`);
1387
5056
  }
1388
5057
  }
1389
5058
  function readJsonFile(filePath) {
1390
5059
  try {
1391
- return JSON.parse(fs11.readFileSync(filePath, "utf-8"));
5060
+ return JSON.parse(fs9.readFileSync(filePath, "utf-8"));
1392
5061
  } catch {
1393
5062
  return null;
1394
5063
  }
1395
5064
  }
1396
5065
  function configureClaudeCode(agent, proxyConfig, direct = false) {
1397
- const configPath = agent.configPath ?? path12.join(os7.homedir(), ".claude", "settings.json");
1398
- const configDir = path12.dirname(configPath);
5066
+ const configPath = agent.configPath ?? path10.join(os7.homedir(), ".claude", "settings.json");
5067
+ const configDir = path10.dirname(configPath);
1399
5068
  ensureDir(configDir);
1400
5069
  createBackup(configPath);
1401
5070
  const config = readJsonFile(configPath) ?? {};
@@ -1410,11 +5079,11 @@ function configureClaudeCode(agent, proxyConfig, direct = false) {
1410
5079
  env.ANTHROPIC_BASE_URL = `http://localhost:${proxyConfig.anthropicPort}`;
1411
5080
  delete env.ANTHROPIC_CUSTOM_HEADERS;
1412
5081
  }
1413
- fs11.writeFileSync(configPath, JSON.stringify(config, null, 2) + "\n");
5082
+ fs9.writeFileSync(configPath, JSON.stringify(config, null, 2) + "\n");
1414
5083
  }
1415
5084
  function readTomlFile(filePath) {
1416
5085
  try {
1417
- return fs11.readFileSync(filePath, "utf-8");
5086
+ return fs9.readFileSync(filePath, "utf-8");
1418
5087
  } catch {
1419
5088
  return "";
1420
5089
  }
@@ -1503,9 +5172,9 @@ function removeCodexProxyProvider(content) {
1503
5172
  return before.length > 0 && rest.length > 0 ? before + "\n" + rest : before + rest;
1504
5173
  }
1505
5174
  function configureCodex(agent, proxyConfig, direct = false) {
1506
- const configDir = process.platform === "win32" ? path12.join(os7.homedir(), "AppData", "Roaming", "codex") : path12.join(os7.homedir(), ".codex");
1507
- const configPath = agent.configPath ?? path12.join(configDir, "config.toml");
1508
- ensureDir(path12.dirname(configPath));
5175
+ const configDir = process.platform === "win32" ? path10.join(os7.homedir(), "AppData", "Roaming", "codex") : path10.join(os7.homedir(), ".codex");
5176
+ const configPath = agent.configPath ?? path10.join(configDir, "config.toml");
5177
+ ensureDir(path10.dirname(configPath));
1509
5178
  createBackup(configPath);
1510
5179
  let content = readTomlFile(configPath);
1511
5180
  if (direct) {
@@ -1518,15 +5187,15 @@ function configureCodex(agent, proxyConfig, direct = false) {
1518
5187
  content = upsertCodexProxyProvider(content, proxyConfig.openaiPort);
1519
5188
  content = removeCodexDirectProvider(content);
1520
5189
  }
1521
- fs11.writeFileSync(configPath, content);
5190
+ fs9.writeFileSync(configPath, content);
1522
5191
  }
1523
5192
  function getCursorConfigDir() {
1524
5193
  if (process.platform === "darwin") {
1525
- return path12.join(os7.homedir(), "Library", "Application Support", "Cursor", "User");
5194
+ return path10.join(os7.homedir(), "Library", "Application Support", "Cursor", "User");
1526
5195
  } else if (process.platform === "win32") {
1527
- return path12.join(process.env.APPDATA ?? path12.join(os7.homedir(), "AppData", "Roaming"), "Cursor", "User");
5196
+ return path10.join(process.env.APPDATA ?? path10.join(os7.homedir(), "AppData", "Roaming"), "Cursor", "User");
1528
5197
  }
1529
- return path12.join(os7.homedir(), ".config", "Cursor", "User");
5198
+ return path10.join(os7.homedir(), ".config", "Cursor", "User");
1530
5199
  }
1531
5200
  function configureCursor(agent, proxyConfig, direct = false) {
1532
5201
  if (direct) {
@@ -1534,8 +5203,8 @@ function configureCursor(agent, proxyConfig, direct = false) {
1534
5203
  return;
1535
5204
  }
1536
5205
  const configDir = getCursorConfigDir();
1537
- const configPath = agent.configPath ?? path12.join(configDir, "settings.json");
1538
- ensureDir(path12.dirname(configPath));
5206
+ const configPath = agent.configPath ?? path10.join(configDir, "settings.json");
5207
+ ensureDir(path10.dirname(configPath));
1539
5208
  createBackup(configPath);
1540
5209
  const config = readJsonFile(configPath) ?? {};
1541
5210
  const existingUrl = config[CURSOR_API_BASE_URL_KEY];
@@ -1544,7 +5213,7 @@ function configureCursor(agent, proxyConfig, direct = false) {
1544
5213
  saveConfig(proxyConfig);
1545
5214
  }
1546
5215
  config[CURSOR_API_BASE_URL_KEY] = `http://localhost:${proxyConfig.cursorPort}`;
1547
- fs11.writeFileSync(configPath, JSON.stringify(config, null, 2) + "\n");
5216
+ fs9.writeFileSync(configPath, JSON.stringify(config, null, 2) + "\n");
1548
5217
  }
1549
5218
  function configureAgent(agent, proxyConfig, direct = false) {
1550
5219
  switch (agent.name) {
@@ -1560,8 +5229,8 @@ function configureAgent(agent, proxyConfig, direct = false) {
1560
5229
  }
1561
5230
  }
1562
5231
  function unconfigureClaudeCode(agent) {
1563
- const configPath = agent.configPath ?? path12.join(os7.homedir(), ".claude", "settings.json");
1564
- if (!fs11.existsSync(configPath)) return;
5232
+ const configPath = agent.configPath ?? path10.join(os7.homedir(), ".claude", "settings.json");
5233
+ if (!fs9.existsSync(configPath)) return;
1565
5234
  const config = readJsonFile(configPath);
1566
5235
  if (config === null) {
1567
5236
  console.warn(` [!] Could not parse ${configPath} \u2014 skipping to avoid data loss. Remove ANTHROPIC_BASE_URL manually if needed.`);
@@ -1575,42 +5244,42 @@ function unconfigureClaudeCode(agent) {
1575
5244
  delete config.env;
1576
5245
  }
1577
5246
  }
1578
- fs11.writeFileSync(configPath, JSON.stringify(config, null, 2) + "\n");
5247
+ fs9.writeFileSync(configPath, JSON.stringify(config, null, 2) + "\n");
1579
5248
  const backupPath = `${configPath}.skalpel-backup`;
1580
- if (fs11.existsSync(backupPath)) {
1581
- fs11.unlinkSync(backupPath);
5249
+ if (fs9.existsSync(backupPath)) {
5250
+ fs9.unlinkSync(backupPath);
1582
5251
  }
1583
5252
  }
1584
5253
  function unconfigureCodex(agent) {
1585
- const configDir = process.platform === "win32" ? path12.join(os7.homedir(), "AppData", "Roaming", "codex") : path12.join(os7.homedir(), ".codex");
1586
- const configPath = agent.configPath ?? path12.join(configDir, "config.toml");
1587
- if (fs11.existsSync(configPath)) {
5254
+ const configDir = process.platform === "win32" ? path10.join(os7.homedir(), "AppData", "Roaming", "codex") : path10.join(os7.homedir(), ".codex");
5255
+ const configPath = agent.configPath ?? path10.join(configDir, "config.toml");
5256
+ if (fs9.existsSync(configPath)) {
1588
5257
  let content = readTomlFile(configPath);
1589
5258
  content = removeTomlKey(content, "openai_base_url");
1590
5259
  content = removeTomlKey(content, "model_provider");
1591
5260
  content = removeCodexDirectProvider(content);
1592
5261
  content = removeCodexProxyProvider(content);
1593
- fs11.writeFileSync(configPath, content);
5262
+ fs9.writeFileSync(configPath, content);
1594
5263
  }
1595
5264
  const backupPath = `${configPath}.skalpel-backup`;
1596
- if (fs11.existsSync(backupPath)) {
1597
- fs11.unlinkSync(backupPath);
5265
+ if (fs9.existsSync(backupPath)) {
5266
+ fs9.unlinkSync(backupPath);
1598
5267
  }
1599
5268
  }
1600
5269
  function unconfigureCursor(agent) {
1601
5270
  const configDir = getCursorConfigDir();
1602
- const configPath = agent.configPath ?? path12.join(configDir, "settings.json");
1603
- if (!fs11.existsSync(configPath)) return;
5271
+ const configPath = agent.configPath ?? path10.join(configDir, "settings.json");
5272
+ if (!fs9.existsSync(configPath)) return;
1604
5273
  const config = readJsonFile(configPath);
1605
5274
  if (config === null) {
1606
5275
  console.warn(` [!] Could not parse ${configPath} \u2014 skipping to avoid data loss. Remove ${CURSOR_API_BASE_URL_KEY} manually if needed.`);
1607
5276
  return;
1608
5277
  }
1609
5278
  delete config[CURSOR_API_BASE_URL_KEY];
1610
- fs11.writeFileSync(configPath, JSON.stringify(config, null, 2) + "\n");
5279
+ fs9.writeFileSync(configPath, JSON.stringify(config, null, 2) + "\n");
1611
5280
  const backupPath = `${configPath}.skalpel-backup`;
1612
- if (fs11.existsSync(backupPath)) {
1613
- fs11.unlinkSync(backupPath);
5281
+ if (fs9.existsSync(backupPath)) {
5282
+ fs9.unlinkSync(backupPath);
1614
5283
  }
1615
5284
  }
1616
5285
  function unconfigureAgent(agent) {
@@ -1628,8 +5297,8 @@ function unconfigureAgent(agent) {
1628
5297
  }
1629
5298
 
1630
5299
  // src/cli/agents/shell.ts
1631
- import fs12 from "fs";
1632
- import path13 from "path";
5300
+ import fs10 from "fs";
5301
+ import path11 from "path";
1633
5302
  import os8 from "os";
1634
5303
  var BEGIN_MARKER = "# BEGIN SKALPEL PROXY - do not edit manually";
1635
5304
  var END_MARKER = "# END SKALPEL PROXY";
@@ -1638,21 +5307,21 @@ var PS_END_MARKER = "# END SKALPEL PROXY";
1638
5307
  function getUnixProfilePaths() {
1639
5308
  const home = os8.homedir();
1640
5309
  const candidates = [
1641
- path13.join(home, ".bashrc"),
1642
- path13.join(home, ".zshrc"),
1643
- path13.join(home, ".bash_profile"),
1644
- path13.join(home, ".profile")
5310
+ path11.join(home, ".bashrc"),
5311
+ path11.join(home, ".zshrc"),
5312
+ path11.join(home, ".bash_profile"),
5313
+ path11.join(home, ".profile")
1645
5314
  ];
1646
- return candidates.filter((p) => fs12.existsSync(p));
5315
+ return candidates.filter((p) => fs10.existsSync(p));
1647
5316
  }
1648
5317
  function getPowerShellProfilePath() {
1649
5318
  if (process.platform !== "win32") return null;
1650
5319
  if (process.env.PROFILE) return process.env.PROFILE;
1651
- const docsDir = path13.join(os8.homedir(), "Documents");
1652
- const psProfile = path13.join(docsDir, "PowerShell", "Microsoft.PowerShell_profile.ps1");
1653
- const wpProfile = path13.join(docsDir, "WindowsPowerShell", "Microsoft.PowerShell_profile.ps1");
1654
- if (fs12.existsSync(psProfile)) return psProfile;
1655
- if (fs12.existsSync(wpProfile)) return wpProfile;
5320
+ const docsDir = path11.join(os8.homedir(), "Documents");
5321
+ const psProfile = path11.join(docsDir, "PowerShell", "Microsoft.PowerShell_profile.ps1");
5322
+ const wpProfile = path11.join(docsDir, "WindowsPowerShell", "Microsoft.PowerShell_profile.ps1");
5323
+ if (fs10.existsSync(psProfile)) return psProfile;
5324
+ if (fs10.existsSync(wpProfile)) return wpProfile;
1656
5325
  return psProfile;
1657
5326
  }
1658
5327
  function generateUnixBlock(proxyConfig) {
@@ -1673,13 +5342,13 @@ function generatePowerShellBlock(proxyConfig) {
1673
5342
  }
1674
5343
  function createBackup2(filePath) {
1675
5344
  const backupPath = `${filePath}.skalpel-backup`;
1676
- fs12.copyFileSync(filePath, backupPath);
5345
+ fs10.copyFileSync(filePath, backupPath);
1677
5346
  }
1678
5347
  function updateProfileFile(filePath, block, beginMarker, endMarker) {
1679
- if (fs12.existsSync(filePath)) {
5348
+ if (fs10.existsSync(filePath)) {
1680
5349
  createBackup2(filePath);
1681
5350
  }
1682
- let content = fs12.existsSync(filePath) ? fs12.readFileSync(filePath, "utf-8") : "";
5351
+ let content = fs10.existsSync(filePath) ? fs10.readFileSync(filePath, "utf-8") : "";
1683
5352
  const beginIdx = content.indexOf(beginMarker);
1684
5353
  const endIdx = content.indexOf(endMarker);
1685
5354
  if (beginIdx !== -1 && endIdx !== -1) {
@@ -1692,15 +5361,15 @@ function updateProfileFile(filePath, block, beginMarker, endMarker) {
1692
5361
  content = block + "\n";
1693
5362
  }
1694
5363
  }
1695
- fs12.writeFileSync(filePath, content);
5364
+ fs10.writeFileSync(filePath, content);
1696
5365
  }
1697
5366
  function configureShellEnvVars(_agents, proxyConfig) {
1698
5367
  const modified = [];
1699
5368
  if (process.platform === "win32") {
1700
5369
  const psProfile = getPowerShellProfilePath();
1701
5370
  if (psProfile) {
1702
- const dir = path13.dirname(psProfile);
1703
- fs12.mkdirSync(dir, { recursive: true });
5371
+ const dir = path11.dirname(psProfile);
5372
+ fs10.mkdirSync(dir, { recursive: true });
1704
5373
  const block = generatePowerShellBlock(proxyConfig);
1705
5374
  updateProfileFile(psProfile, block, PS_BEGIN_MARKER, PS_END_MARKER);
1706
5375
  modified.push(psProfile);
@@ -1719,28 +5388,28 @@ function removeShellEnvVars() {
1719
5388
  const restored = [];
1720
5389
  const home = os8.homedir();
1721
5390
  const allProfiles = [
1722
- path13.join(home, ".bashrc"),
1723
- path13.join(home, ".zshrc"),
1724
- path13.join(home, ".bash_profile"),
1725
- path13.join(home, ".profile")
5391
+ path11.join(home, ".bashrc"),
5392
+ path11.join(home, ".zshrc"),
5393
+ path11.join(home, ".bash_profile"),
5394
+ path11.join(home, ".profile")
1726
5395
  ];
1727
5396
  if (process.platform === "win32") {
1728
5397
  const psProfile = getPowerShellProfilePath();
1729
5398
  if (psProfile) allProfiles.push(psProfile);
1730
5399
  }
1731
5400
  for (const profilePath of allProfiles) {
1732
- if (!fs12.existsSync(profilePath)) continue;
1733
- const content = fs12.readFileSync(profilePath, "utf-8");
5401
+ if (!fs10.existsSync(profilePath)) continue;
5402
+ const content = fs10.readFileSync(profilePath, "utf-8");
1734
5403
  const beginIdx = content.indexOf(BEGIN_MARKER);
1735
5404
  const endIdx = content.indexOf(END_MARKER);
1736
5405
  if (beginIdx === -1 || endIdx === -1) continue;
1737
5406
  const before = content.slice(0, beginIdx);
1738
5407
  const after = content.slice(endIdx + END_MARKER.length);
1739
5408
  const cleaned = (before.replace(/\n+$/, "") + after.replace(/^\n+/, "\n")).trimEnd() + "\n";
1740
- fs12.writeFileSync(profilePath, cleaned);
5409
+ fs10.writeFileSync(profilePath, cleaned);
1741
5410
  const backupPath = `${profilePath}.skalpel-backup`;
1742
- if (fs12.existsSync(backupPath)) {
1743
- fs12.unlinkSync(backupPath);
5411
+ if (fs10.existsSync(backupPath)) {
5412
+ fs10.unlinkSync(backupPath);
1744
5413
  }
1745
5414
  restored.push(profilePath);
1746
5415
  }
@@ -1753,6 +5422,230 @@ function removeShellBlock() {
1753
5422
  return removeShellEnvVars();
1754
5423
  }
1755
5424
 
5425
+ // src/cli/start.ts
5426
+ function print5(msg) {
5427
+ console.log(msg);
5428
+ }
5429
+ function reconfigureAgents(config) {
5430
+ const direct = config.mode === "direct";
5431
+ const agents = detectAgents();
5432
+ for (const agent of agents) {
5433
+ if (agent.installed) {
5434
+ try {
5435
+ configureAgent(agent, config, direct);
5436
+ } catch {
5437
+ }
5438
+ }
5439
+ }
5440
+ try {
5441
+ configureShellEnvVars(agents.filter((a) => a.installed), config);
5442
+ } catch {
5443
+ }
5444
+ }
5445
+ async function runStart() {
5446
+ const config = loadConfig();
5447
+ if (!config.apiKey) {
5448
+ print5(' Error: No API key configured. Run "skalpel init" or set SKALPEL_API_KEY.');
5449
+ process.exit(1);
5450
+ }
5451
+ const existingPid = readPid(config.pidFile);
5452
+ if (existingPid !== null) {
5453
+ print5(` Proxy is already running (pid=${existingPid}).`);
5454
+ return;
5455
+ }
5456
+ const alive = await isProxyAlive(config.anthropicPort);
5457
+ if (alive) {
5458
+ print5(" Proxy is already running (detected via health check).");
5459
+ return;
5460
+ }
5461
+ if (isServiceInstalled()) {
5462
+ startService();
5463
+ reconfigureAgents(config);
5464
+ print5(` Skalpel proxy started via system service on ports ${config.anthropicPort}, ${config.openaiPort}, and ${config.cursorPort}`);
5465
+ return;
5466
+ }
5467
+ const dirname = path12.dirname(fileURLToPath2(import.meta.url));
5468
+ const runnerScript = path12.resolve(dirname, "proxy-runner.js");
5469
+ const child = spawn(process.execPath, [runnerScript], {
5470
+ detached: true,
5471
+ stdio: "ignore"
5472
+ });
5473
+ child.unref();
5474
+ reconfigureAgents(config);
5475
+ print5(` Skalpel proxy started on ports ${config.anthropicPort}, ${config.openaiPort}, and ${config.cursorPort}`);
5476
+ }
5477
+
5478
+ // src/cli/stop.ts
5479
+ import { execSync as execSync5 } from "child_process";
5480
+
5481
+ // src/proxy/server.ts
5482
+ init_handler();
5483
+ import http from "http";
5484
+
5485
+ // src/proxy/logger.ts
5486
+ import fs11 from "fs";
5487
+ import path13 from "path";
5488
+ var MAX_SIZE = 5 * 1024 * 1024;
5489
+
5490
+ // src/proxy/ws-server.ts
5491
+ init_wrapper();
5492
+ var WS_SUBPROTOCOL = "skalpel-codex-v1";
5493
+ var wss = new import_websocket_server.default({
5494
+ noServer: true,
5495
+ handleProtocols: (protocols) => protocols.has(WS_SUBPROTOCOL) ? WS_SUBPROTOCOL : false
5496
+ });
5497
+
5498
+ // src/proxy/server.ts
5499
+ var proxyStartTime = 0;
5500
+ function stopProxy(config) {
5501
+ const pid = readPid(config.pidFile);
5502
+ if (pid === null) return false;
5503
+ try {
5504
+ process.kill(pid, "SIGTERM");
5505
+ } catch {
5506
+ }
5507
+ removePid(config.pidFile);
5508
+ return true;
5509
+ }
5510
+ async function getProxyStatus(config) {
5511
+ const pid = readPid(config.pidFile);
5512
+ if (pid !== null) {
5513
+ return {
5514
+ running: true,
5515
+ pid,
5516
+ uptime: proxyStartTime > 0 ? Date.now() - proxyStartTime : 0,
5517
+ anthropicPort: config.anthropicPort,
5518
+ openaiPort: config.openaiPort,
5519
+ cursorPort: config.cursorPort
5520
+ };
5521
+ }
5522
+ const alive = await isProxyAlive(config.anthropicPort);
5523
+ return {
5524
+ running: alive,
5525
+ pid: null,
5526
+ uptime: 0,
5527
+ anthropicPort: config.anthropicPort,
5528
+ openaiPort: config.openaiPort,
5529
+ cursorPort: config.cursorPort
5530
+ };
5531
+ }
5532
+
5533
+ // src/cli/stop.ts
5534
+ function print6(msg) {
5535
+ console.log(msg);
5536
+ }
5537
+ async function runStop() {
5538
+ const config = loadConfig();
5539
+ if (isServiceInstalled()) {
5540
+ stopService();
5541
+ }
5542
+ const stopped = stopProxy(config);
5543
+ if (stopped) {
5544
+ print6(" Skalpel proxy stopped.");
5545
+ } else {
5546
+ const alive = await isProxyAlive(config.anthropicPort);
5547
+ if (alive) {
5548
+ let killedViaPort = false;
5549
+ if (process.platform === "darwin" || process.platform === "linux") {
5550
+ try {
5551
+ const pids = execSync5(`lsof -ti :${config.anthropicPort}`, { timeout: 3e3 }).toString().trim().split("\n").filter(Boolean);
5552
+ for (const p of pids) {
5553
+ const pid = parseInt(p, 10);
5554
+ if (Number.isInteger(pid) && pid > 0) {
5555
+ try {
5556
+ process.kill(pid, "SIGTERM");
5557
+ } catch {
5558
+ }
5559
+ }
5560
+ }
5561
+ killedViaPort = true;
5562
+ } catch {
5563
+ }
5564
+ }
5565
+ if (killedViaPort) {
5566
+ print6(" Skalpel proxy stopped (found via port detection).");
5567
+ } else {
5568
+ print6(" Proxy appears to be running but could not be stopped automatically.");
5569
+ print6(` Try: kill $(lsof -ti :${config.anthropicPort})`);
5570
+ }
5571
+ } else {
5572
+ print6(" Proxy is not running.");
5573
+ }
5574
+ }
5575
+ const agents = detectAgents();
5576
+ for (const agent of agents) {
5577
+ if (agent.installed) {
5578
+ try {
5579
+ unconfigureAgent(agent);
5580
+ } catch {
5581
+ }
5582
+ }
5583
+ }
5584
+ try {
5585
+ removeShellEnvVars();
5586
+ } catch {
5587
+ }
5588
+ }
5589
+
5590
+ // src/cli/status.ts
5591
+ function print7(msg) {
5592
+ console.log(msg);
5593
+ }
5594
+ async function runStatus() {
5595
+ const config = loadConfig();
5596
+ const status = await getProxyStatus(config);
5597
+ print7("");
5598
+ print7(" Skalpel Proxy Status");
5599
+ print7(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500");
5600
+ print7(` Status: ${status.running ? "running" : "stopped"}`);
5601
+ if (status.pid !== null) {
5602
+ print7(` PID: ${status.pid}`);
5603
+ }
5604
+ print7(` Anthropic: port ${status.anthropicPort}`);
5605
+ print7(` OpenAI: port ${status.openaiPort}`);
5606
+ print7(` Cursor: port ${status.cursorPort}`);
5607
+ print7(` Config: ${config.configFile}`);
5608
+ print7("");
5609
+ }
5610
+
5611
+ // src/cli/logs.ts
5612
+ import fs12 from "fs";
5613
+ function print8(msg) {
5614
+ console.log(msg);
5615
+ }
5616
+ async function runLogs(options) {
5617
+ const config = loadConfig();
5618
+ const logFile = config.logFile;
5619
+ const lineCount = parseInt(options.lines ?? "50", 10);
5620
+ if (!fs12.existsSync(logFile)) {
5621
+ print8(` No log file found at ${logFile}`);
5622
+ return;
5623
+ }
5624
+ const content = fs12.readFileSync(logFile, "utf-8");
5625
+ const lines = content.trimEnd().split("\n");
5626
+ const tail = lines.slice(-lineCount);
5627
+ for (const line of tail) {
5628
+ print8(line);
5629
+ }
5630
+ if (options.follow) {
5631
+ let position = fs12.statSync(logFile).size;
5632
+ fs12.watchFile(logFile, { interval: 500 }, () => {
5633
+ try {
5634
+ const stat = fs12.statSync(logFile);
5635
+ if (stat.size > position) {
5636
+ const fd = fs12.openSync(logFile, "r");
5637
+ const buf = Buffer.alloc(stat.size - position);
5638
+ fs12.readSync(fd, buf, 0, buf.length, position);
5639
+ fs12.closeSync(fd);
5640
+ process.stdout.write(buf.toString("utf-8"));
5641
+ position = stat.size;
5642
+ }
5643
+ } catch {
5644
+ }
5645
+ });
5646
+ }
5647
+ }
5648
+
1756
5649
  // src/cli/config-cmd.ts
1757
5650
  function print9(msg) {
1758
5651
  console.log(msg);
@@ -1924,8 +5817,8 @@ async function runWizard(options) {
1924
5817
  print11(" Welcome to Skalpel! Let's optimize your coding agent costs.");
1925
5818
  print11(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500");
1926
5819
  print11("");
1927
- const skalpelDir = path14.join(os9.homedir(), ".skalpel");
1928
- const configPath = path14.join(skalpelDir, "config.json");
5820
+ const skalpelDir2 = path14.join(os9.homedir(), ".skalpel");
5821
+ const configPath = path14.join(skalpelDir2, "config.json");
1929
5822
  let apiKey = "";
1930
5823
  if (isAuto && options?.apiKey) {
1931
5824
  apiKey = options.apiKey;
@@ -1964,7 +5857,7 @@ async function runWizard(options) {
1964
5857
  }
1965
5858
  }
1966
5859
  print11("");
1967
- fs13.mkdirSync(skalpelDir, { recursive: true });
5860
+ fs13.mkdirSync(skalpelDir2, { recursive: true });
1968
5861
  const proxyConfig = loadConfig(configPath);
1969
5862
  proxyConfig.apiKey = apiKey;
1970
5863
  saveConfig(proxyConfig);
@@ -2169,15 +6062,15 @@ async function runUninstall(options) {
2169
6062
  }
2170
6063
  }
2171
6064
  print12("");
2172
- const skalpelDir = path15.join(os10.homedir(), ".skalpel");
2173
- if (fs14.existsSync(skalpelDir)) {
6065
+ const skalpelDir2 = path15.join(os10.homedir(), ".skalpel");
6066
+ if (fs14.existsSync(skalpelDir2)) {
2174
6067
  let shouldRemove = force;
2175
6068
  if (!force) {
2176
6069
  const removeDir = await ask(" Remove ~/.skalpel/ directory (contains config and logs)? (y/N): ");
2177
6070
  shouldRemove = removeDir.toLowerCase() === "y";
2178
6071
  }
2179
6072
  if (shouldRemove) {
2180
- fs14.rmSync(skalpelDir, { recursive: true, force: true });
6073
+ fs14.rmSync(skalpelDir2, { recursive: true, force: true });
2181
6074
  print12(" [+] Removed ~/.skalpel/");
2182
6075
  removed.push("~/.skalpel/ directory");
2183
6076
  }
@@ -2231,6 +6124,311 @@ function clearNpxCache() {
2231
6124
  }
2232
6125
  }
2233
6126
 
6127
+ // src/cli/auth/callback-server.ts
6128
+ import * as http2 from "http";
6129
+ import * as net2 from "net";
6130
+
6131
+ // src/cli/auth/session-storage.ts
6132
+ import * as fs15 from "fs";
6133
+ import * as os11 from "os";
6134
+ import * as path16 from "path";
6135
+ function sessionFilePath() {
6136
+ return path16.join(os11.homedir(), ".skalpel", "session.json");
6137
+ }
6138
+ function skalpelDir() {
6139
+ return path16.join(os11.homedir(), ".skalpel");
6140
+ }
6141
+ function isValidSession(value) {
6142
+ if (!value || typeof value !== "object") return false;
6143
+ const v = value;
6144
+ if (typeof v.accessToken !== "string" || v.accessToken.length === 0) return false;
6145
+ if (typeof v.refreshToken !== "string" || v.refreshToken.length === 0) return false;
6146
+ if (typeof v.expiresAt !== "number" || !Number.isFinite(v.expiresAt)) return false;
6147
+ if (!v.user || typeof v.user !== "object") return false;
6148
+ const user = v.user;
6149
+ if (typeof user.id !== "string" || user.id.length === 0) return false;
6150
+ if (typeof user.email !== "string" || user.email.length === 0) return false;
6151
+ return true;
6152
+ }
6153
+ async function readSession() {
6154
+ const file = sessionFilePath();
6155
+ try {
6156
+ const raw = await fs15.promises.readFile(file, "utf-8");
6157
+ const parsed = JSON.parse(raw);
6158
+ if (!isValidSession(parsed)) return null;
6159
+ return parsed;
6160
+ } catch (err) {
6161
+ if (err.code === "ENOENT") return null;
6162
+ return null;
6163
+ }
6164
+ }
6165
+ async function writeSession(session) {
6166
+ if (!isValidSession(session)) {
6167
+ throw new Error("writeSession: invalid session shape");
6168
+ }
6169
+ const dir = skalpelDir();
6170
+ await fs15.promises.mkdir(dir, { recursive: true, mode: 448 });
6171
+ const file = sessionFilePath();
6172
+ const tmp = `${file}.tmp-${process.pid}-${Date.now()}`;
6173
+ const json = JSON.stringify(session, null, 2);
6174
+ await fs15.promises.writeFile(tmp, json, { mode: 384 });
6175
+ try {
6176
+ await fs15.promises.chmod(tmp, 384);
6177
+ } catch {
6178
+ }
6179
+ await fs15.promises.rename(tmp, file);
6180
+ try {
6181
+ await fs15.promises.chmod(file, 384);
6182
+ } catch {
6183
+ }
6184
+ }
6185
+ async function deleteSession() {
6186
+ const file = sessionFilePath();
6187
+ try {
6188
+ await fs15.promises.unlink(file);
6189
+ } catch (err) {
6190
+ if (err.code === "ENOENT") return;
6191
+ throw err;
6192
+ }
6193
+ }
6194
+
6195
+ // src/cli/auth/callback-server.ts
6196
+ var MAX_BODY_BYTES = 16 * 1024;
6197
+ var DEFAULT_TIMEOUT_MS = 18e4;
6198
+ var DEFAULT_ALLOWED_ORIGINS = [
6199
+ "https://app.skalpel.ai",
6200
+ "https://skalpel.ai"
6201
+ ];
6202
+ function allowedOrigins() {
6203
+ const extras = [];
6204
+ const webappUrl = process.env.SKALPEL_WEBAPP_URL;
6205
+ if (webappUrl) {
6206
+ try {
6207
+ const u = new URL(webappUrl);
6208
+ extras.push(`${u.protocol}//${u.host}`);
6209
+ } catch {
6210
+ }
6211
+ }
6212
+ return [...DEFAULT_ALLOWED_ORIGINS, ...extras];
6213
+ }
6214
+ function validatePort(port) {
6215
+ if (!Number.isInteger(port) || port < 1024 || port > 65535) {
6216
+ throw new Error(`Invalid port: ${port} (must be an integer in 1024-65535)`);
6217
+ }
6218
+ }
6219
+ async function findOpenPort(preferred = 51732) {
6220
+ if (preferred !== 0) validatePort(preferred);
6221
+ const tryBind = (port) => new Promise((resolve2) => {
6222
+ const server = net2.createServer();
6223
+ server.once("error", () => {
6224
+ server.close(() => resolve2(null));
6225
+ });
6226
+ server.listen(port, "127.0.0.1", () => {
6227
+ const address = server.address();
6228
+ const boundPort = address && typeof address === "object" ? address.port : null;
6229
+ server.close(() => resolve2(boundPort));
6230
+ });
6231
+ });
6232
+ const preferredResult = await tryBind(preferred);
6233
+ if (preferredResult !== null) return preferredResult;
6234
+ const fallback = await tryBind(0);
6235
+ if (fallback !== null) return fallback;
6236
+ throw new Error("findOpenPort: no open port available");
6237
+ }
6238
+ function buildCorsHeaders(origin) {
6239
+ const allowed = allowedOrigins();
6240
+ const selected = origin && allowed.includes(origin) ? origin : allowed[0];
6241
+ return {
6242
+ "Access-Control-Allow-Origin": selected,
6243
+ "Access-Control-Allow-Methods": "POST, OPTIONS",
6244
+ "Access-Control-Allow-Headers": "content-type",
6245
+ "Access-Control-Max-Age": "600",
6246
+ Vary: "Origin"
6247
+ };
6248
+ }
6249
+ async function startCallbackServer(port, timeoutMsOrOptions = DEFAULT_TIMEOUT_MS, maxBodyBytesArg) {
6250
+ validatePort(port);
6251
+ const opts = typeof timeoutMsOrOptions === "number" ? { timeoutMs: timeoutMsOrOptions, maxBodyBytes: maxBodyBytesArg } : timeoutMsOrOptions ?? {};
6252
+ const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
6253
+ const maxBytes = opts.maxBodyBytes ?? MAX_BODY_BYTES;
6254
+ return new Promise((resolve2, reject) => {
6255
+ let settled = false;
6256
+ let timer;
6257
+ const server = http2.createServer((req, res) => {
6258
+ const origin = req.headers.origin;
6259
+ const corsHeaders = buildCorsHeaders(origin);
6260
+ if (req.method === "OPTIONS") {
6261
+ res.writeHead(204, corsHeaders);
6262
+ res.end();
6263
+ return;
6264
+ }
6265
+ if (req.method === "GET" && (req.url === "/callback" || req.url === "/")) {
6266
+ res.writeHead(200, {
6267
+ ...corsHeaders,
6268
+ "Content-Type": "text/html; charset=utf-8"
6269
+ });
6270
+ res.end(
6271
+ '<!doctype html><meta charset="utf-8"><title>Skalpel CLI</title><p>You can close this tab and return to your terminal.</p>'
6272
+ );
6273
+ return;
6274
+ }
6275
+ if (req.method !== "POST" || req.url !== "/callback") {
6276
+ res.writeHead(404, corsHeaders);
6277
+ res.end();
6278
+ return;
6279
+ }
6280
+ const contentType = (req.headers["content-type"] || "").toLowerCase();
6281
+ if (!contentType.includes("application/json")) {
6282
+ res.writeHead(415, { ...corsHeaders, "Content-Type": "application/json" });
6283
+ res.end(JSON.stringify({ error: "Unsupported Media Type" }));
6284
+ return;
6285
+ }
6286
+ let total = 0;
6287
+ const chunks = [];
6288
+ let aborted = false;
6289
+ req.on("data", (chunk) => {
6290
+ if (aborted) return;
6291
+ total += chunk.length;
6292
+ if (total > maxBytes) {
6293
+ aborted = true;
6294
+ res.writeHead(413, {
6295
+ ...corsHeaders,
6296
+ "Content-Type": "application/json",
6297
+ Connection: "close"
6298
+ });
6299
+ res.end(JSON.stringify({ error: "Payload too large" }));
6300
+ return;
6301
+ }
6302
+ chunks.push(chunk);
6303
+ });
6304
+ req.on("end", () => {
6305
+ if (aborted) return;
6306
+ const raw = Buffer.concat(chunks).toString("utf-8");
6307
+ let parsed;
6308
+ try {
6309
+ parsed = JSON.parse(raw);
6310
+ } catch {
6311
+ res.writeHead(400, { ...corsHeaders, "Content-Type": "application/json" });
6312
+ res.end(JSON.stringify({ error: "Invalid JSON" }));
6313
+ return;
6314
+ }
6315
+ if (!isValidSession(parsed)) {
6316
+ res.writeHead(400, { ...corsHeaders, "Content-Type": "application/json" });
6317
+ res.end(JSON.stringify({ error: "Invalid session shape" }));
6318
+ if (!settled) {
6319
+ settled = true;
6320
+ if (timer) clearTimeout(timer);
6321
+ server.close(() => reject(new Error("Invalid session received")));
6322
+ }
6323
+ return;
6324
+ }
6325
+ res.writeHead(200, { ...corsHeaders, "Content-Type": "application/json" });
6326
+ res.end(JSON.stringify({ ok: true }));
6327
+ if (!settled) {
6328
+ settled = true;
6329
+ if (timer) clearTimeout(timer);
6330
+ server.close(() => resolve2(parsed));
6331
+ }
6332
+ });
6333
+ req.on("error", () => {
6334
+ });
6335
+ });
6336
+ server.once("error", (err) => {
6337
+ if (settled) return;
6338
+ settled = true;
6339
+ if (timer) clearTimeout(timer);
6340
+ reject(err);
6341
+ });
6342
+ server.listen(port, "127.0.0.1", () => {
6343
+ timer = setTimeout(() => {
6344
+ if (settled) return;
6345
+ settled = true;
6346
+ server.close(() => reject(new Error("Login timed out")));
6347
+ }, timeoutMs);
6348
+ if (timer.unref) timer.unref();
6349
+ });
6350
+ });
6351
+ }
6352
+
6353
+ // src/cli/auth/browser.ts
6354
+ async function openUrl(url) {
6355
+ if (!/^https?:\/\//i.test(url)) {
6356
+ throw new Error(`openUrl: refusing to open non-http(s) URL: ${url}`);
6357
+ }
6358
+ try {
6359
+ const mod = await import("open");
6360
+ const opener = mod.default;
6361
+ if (typeof opener !== "function") {
6362
+ throw new Error("open package exports no default function");
6363
+ }
6364
+ await opener(url);
6365
+ return { opened: true, fallback: false };
6366
+ } catch {
6367
+ console.log("");
6368
+ console.log(" Could not open your browser automatically.");
6369
+ console.log(" Please open this URL manually to continue:");
6370
+ console.log("");
6371
+ console.log(` ${url}`);
6372
+ console.log("");
6373
+ return { opened: false, fallback: true };
6374
+ }
6375
+ }
6376
+
6377
+ // src/cli/login.ts
6378
+ var DEFAULT_WEBAPP_URL = "https://app.skalpel.ai";
6379
+ var DEFAULT_TIMEOUT_MS2 = 18e4;
6380
+ async function runLogin(options = {}) {
6381
+ const webappUrl = options.webappUrl ?? process.env.SKALPEL_WEBAPP_URL ?? DEFAULT_WEBAPP_URL;
6382
+ const preferredPort = options.preferredPort ?? 51732;
6383
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS2;
6384
+ const log = options.logger ?? console;
6385
+ const _findPort = options.findOpenPort ?? findOpenPort;
6386
+ const _startServer = options.startCallbackServer ?? startCallbackServer;
6387
+ const _openUrl = options.openUrl ?? openUrl;
6388
+ const _writeSession = options.writeSession ?? writeSession;
6389
+ const port = await _findPort(preferredPort);
6390
+ const authorizeUrl = `${webappUrl.replace(/\/$/, "")}/cli/authorize?port=${port}`;
6391
+ log.log("");
6392
+ log.log(` Opening browser to ${authorizeUrl}`);
6393
+ log.log(" Waiting for authentication (timeout 3 min)...");
6394
+ log.log("");
6395
+ const serverPromise = _startServer(port, timeoutMs);
6396
+ try {
6397
+ await _openUrl(authorizeUrl);
6398
+ } catch {
6399
+ log.log(" Browser launch failed. Please open the URL above manually.");
6400
+ }
6401
+ let session;
6402
+ try {
6403
+ session = await serverPromise;
6404
+ } catch (err) {
6405
+ const msg = err instanceof Error ? err.message : String(err);
6406
+ log.error("");
6407
+ log.error(` Login failed: ${msg}`);
6408
+ log.error("");
6409
+ process.exitCode = 1;
6410
+ throw err;
6411
+ }
6412
+ await _writeSession(session);
6413
+ log.log("");
6414
+ log.log(` \u2713 Logged in as ${session.user.email}`);
6415
+ log.log("");
6416
+ }
6417
+
6418
+ // src/cli/logout.ts
6419
+ async function runLogout(options = {}) {
6420
+ const log = options.logger ?? console;
6421
+ const _readSession = options.readSession ?? readSession;
6422
+ const _deleteSession = options.deleteSession ?? deleteSession;
6423
+ const existing = await _readSession();
6424
+ if (!existing) {
6425
+ log.log(" Not logged in.");
6426
+ return;
6427
+ }
6428
+ await _deleteSession();
6429
+ log.log(` \u2713 Logged out.`);
6430
+ }
6431
+
2234
6432
  // src/cli/index.ts
2235
6433
  var require3 = createRequire2(import.meta.url);
2236
6434
  var pkg2 = require3("../../package.json");
@@ -2243,6 +6441,8 @@ program.command("replay").description("Replay saved request files").argument("<f
2243
6441
  program.command("start").description("Start the Skalpel proxy").action(runStart);
2244
6442
  program.command("stop").description("Stop the Skalpel proxy").action(runStop);
2245
6443
  program.command("status").description("Show proxy status").action(runStatus);
6444
+ program.command("login").description("Log in to your Skalpel account (opens browser)").action(() => runLogin());
6445
+ program.command("logout").description("Log out of your Skalpel account").action(() => runLogout());
2246
6446
  program.command("logs").description("View proxy logs").option("-n, --lines <count>", "Number of lines to show", "50").option("-f, --follow", "Follow log output").action(runLogs);
2247
6447
  program.command("config").description("View or edit proxy configuration").argument("[subcommand]", "path | set").argument("[args...]", "Arguments for subcommand").action(runConfig);
2248
6448
  program.command("update").description("Update Skalpel to the latest version").action(runUpdate);