alink-cli 0.4.0 → 0.4.2

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