alink-cli 0.1.2 → 0.4.0

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