opchrm 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,3912 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __commonJS = (cb, mod) => function __require() {
9
+ try {
10
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
11
+ } catch (e) {
12
+ throw mod = 0, e;
13
+ }
14
+ };
15
+ var __copyProps = (to, from, except, desc) => {
16
+ if (from && typeof from === "object" || typeof from === "function") {
17
+ for (let key of __getOwnPropNames(from))
18
+ if (!__hasOwnProp.call(to, key) && key !== except)
19
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
20
+ }
21
+ return to;
22
+ };
23
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
24
+ // If the importer is in node compatibility mode or this is not an ESM
25
+ // file that has been converted to a CommonJS file using a Babel-
26
+ // compatible transform (i.e. "__esModule" has not been set), then set
27
+ // "default" to the CommonJS "module.exports" for node compatibility.
28
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
29
+ mod
30
+ ));
31
+
32
+ // apps/daemon/node_modules/ws/lib/constants.js
33
+ var require_constants = __commonJS({
34
+ "apps/daemon/node_modules/ws/lib/constants.js"(exports2, module2) {
35
+ "use strict";
36
+ var BINARY_TYPES = ["nodebuffer", "arraybuffer", "fragments"];
37
+ var hasBlob = typeof Blob !== "undefined";
38
+ if (hasBlob) BINARY_TYPES.push("blob");
39
+ module2.exports = {
40
+ BINARY_TYPES,
41
+ CLOSE_TIMEOUT: 3e4,
42
+ EMPTY_BUFFER: Buffer.alloc(0),
43
+ GUID: "258EAFA5-E914-47DA-95CA-C5AB0DC85B11",
44
+ hasBlob,
45
+ kForOnEventAttribute: /* @__PURE__ */ Symbol("kIsForOnEventAttribute"),
46
+ kListener: /* @__PURE__ */ Symbol("kListener"),
47
+ kStatusCode: /* @__PURE__ */ Symbol("status-code"),
48
+ kWebSocket: /* @__PURE__ */ Symbol("websocket"),
49
+ NOOP: () => {
50
+ }
51
+ };
52
+ }
53
+ });
54
+
55
+ // apps/daemon/node_modules/ws/lib/buffer-util.js
56
+ var require_buffer_util = __commonJS({
57
+ "apps/daemon/node_modules/ws/lib/buffer-util.js"(exports2, module2) {
58
+ "use strict";
59
+ var { EMPTY_BUFFER } = require_constants();
60
+ var FastBuffer = Buffer[Symbol.species];
61
+ function concat(list, totalLength) {
62
+ if (list.length === 0) return EMPTY_BUFFER;
63
+ if (list.length === 1) return list[0];
64
+ const target = Buffer.allocUnsafe(totalLength);
65
+ let offset = 0;
66
+ for (let i = 0; i < list.length; i++) {
67
+ const buf = list[i];
68
+ target.set(buf, offset);
69
+ offset += buf.length;
70
+ }
71
+ if (offset < totalLength) {
72
+ return new FastBuffer(target.buffer, target.byteOffset, offset);
73
+ }
74
+ return target;
75
+ }
76
+ function _mask(source, mask, output, offset, length) {
77
+ for (let i = 0; i < length; i++) {
78
+ output[offset + i] = source[i] ^ mask[i & 3];
79
+ }
80
+ }
81
+ function _unmask(buffer, mask) {
82
+ for (let i = 0; i < buffer.length; i++) {
83
+ buffer[i] ^= mask[i & 3];
84
+ }
85
+ }
86
+ function toArrayBuffer(buf) {
87
+ if (buf.length === buf.buffer.byteLength) {
88
+ return buf.buffer;
89
+ }
90
+ return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length);
91
+ }
92
+ function toBuffer(data) {
93
+ toBuffer.readOnly = true;
94
+ if (Buffer.isBuffer(data)) return data;
95
+ let buf;
96
+ if (data instanceof ArrayBuffer) {
97
+ buf = new FastBuffer(data);
98
+ } else if (ArrayBuffer.isView(data)) {
99
+ buf = new FastBuffer(data.buffer, data.byteOffset, data.byteLength);
100
+ } else {
101
+ buf = Buffer.from(data);
102
+ toBuffer.readOnly = false;
103
+ }
104
+ return buf;
105
+ }
106
+ module2.exports = {
107
+ concat,
108
+ mask: _mask,
109
+ toArrayBuffer,
110
+ toBuffer,
111
+ unmask: _unmask
112
+ };
113
+ if (!process.env.WS_NO_BUFFER_UTIL) {
114
+ try {
115
+ const bufferUtil = require("bufferutil");
116
+ module2.exports.mask = function(source, mask, output, offset, length) {
117
+ if (length < 48) _mask(source, mask, output, offset, length);
118
+ else bufferUtil.mask(source, mask, output, offset, length);
119
+ };
120
+ module2.exports.unmask = function(buffer, mask) {
121
+ if (buffer.length < 32) _unmask(buffer, mask);
122
+ else bufferUtil.unmask(buffer, mask);
123
+ };
124
+ } catch (e) {
125
+ }
126
+ }
127
+ }
128
+ });
129
+
130
+ // apps/daemon/node_modules/ws/lib/limiter.js
131
+ var require_limiter = __commonJS({
132
+ "apps/daemon/node_modules/ws/lib/limiter.js"(exports2, module2) {
133
+ "use strict";
134
+ var kDone = /* @__PURE__ */ Symbol("kDone");
135
+ var kRun = /* @__PURE__ */ Symbol("kRun");
136
+ var Limiter = class {
137
+ /**
138
+ * Creates a new `Limiter`.
139
+ *
140
+ * @param {Number} [concurrency=Infinity] The maximum number of jobs allowed
141
+ * to run concurrently
142
+ */
143
+ constructor(concurrency) {
144
+ this[kDone] = () => {
145
+ this.pending--;
146
+ this[kRun]();
147
+ };
148
+ this.concurrency = concurrency || Infinity;
149
+ this.jobs = [];
150
+ this.pending = 0;
151
+ }
152
+ /**
153
+ * Adds a job to the queue.
154
+ *
155
+ * @param {Function} job The job to run
156
+ * @public
157
+ */
158
+ add(job) {
159
+ this.jobs.push(job);
160
+ this[kRun]();
161
+ }
162
+ /**
163
+ * Removes a job from the queue and runs it if possible.
164
+ *
165
+ * @private
166
+ */
167
+ [kRun]() {
168
+ if (this.pending === this.concurrency) return;
169
+ if (this.jobs.length) {
170
+ const job = this.jobs.shift();
171
+ this.pending++;
172
+ job(this[kDone]);
173
+ }
174
+ }
175
+ };
176
+ module2.exports = Limiter;
177
+ }
178
+ });
179
+
180
+ // apps/daemon/node_modules/ws/lib/permessage-deflate.js
181
+ var require_permessage_deflate = __commonJS({
182
+ "apps/daemon/node_modules/ws/lib/permessage-deflate.js"(exports2, module2) {
183
+ "use strict";
184
+ var zlib = require("zlib");
185
+ var bufferUtil = require_buffer_util();
186
+ var Limiter = require_limiter();
187
+ var { kStatusCode } = require_constants();
188
+ var FastBuffer = Buffer[Symbol.species];
189
+ var TRAILER = Buffer.from([0, 0, 255, 255]);
190
+ var kPerMessageDeflate = /* @__PURE__ */ Symbol("permessage-deflate");
191
+ var kTotalLength = /* @__PURE__ */ Symbol("total-length");
192
+ var kCallback = /* @__PURE__ */ Symbol("callback");
193
+ var kBuffers = /* @__PURE__ */ Symbol("buffers");
194
+ var kError = /* @__PURE__ */ Symbol("error");
195
+ var zlibLimiter;
196
+ var PerMessageDeflate2 = class {
197
+ /**
198
+ * Creates a PerMessageDeflate instance.
199
+ *
200
+ * @param {Object} [options] Configuration options
201
+ * @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support
202
+ * for, or request, a custom client window size
203
+ * @param {Boolean} [options.clientNoContextTakeover=false] Advertise/
204
+ * acknowledge disabling of client context takeover
205
+ * @param {Number} [options.concurrencyLimit=10] The number of concurrent
206
+ * calls to zlib
207
+ * @param {Boolean} [options.isServer=false] Create the instance in either
208
+ * server or client mode
209
+ * @param {Number} [options.maxPayload=0] The maximum allowed message length
210
+ * @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the
211
+ * use of a custom server window size
212
+ * @param {Boolean} [options.serverNoContextTakeover=false] Request/accept
213
+ * disabling of server context takeover
214
+ * @param {Number} [options.threshold=1024] Size (in bytes) below which
215
+ * messages should not be compressed if context takeover is disabled
216
+ * @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on
217
+ * deflate
218
+ * @param {Object} [options.zlibInflateOptions] Options to pass to zlib on
219
+ * inflate
220
+ */
221
+ constructor(options) {
222
+ this._options = options || {};
223
+ this._threshold = this._options.threshold !== void 0 ? this._options.threshold : 1024;
224
+ this._maxPayload = this._options.maxPayload | 0;
225
+ this._isServer = !!this._options.isServer;
226
+ this._deflate = null;
227
+ this._inflate = null;
228
+ this.params = null;
229
+ if (!zlibLimiter) {
230
+ const concurrency = this._options.concurrencyLimit !== void 0 ? this._options.concurrencyLimit : 10;
231
+ zlibLimiter = new Limiter(concurrency);
232
+ }
233
+ }
234
+ /**
235
+ * @type {String}
236
+ */
237
+ static get extensionName() {
238
+ return "permessage-deflate";
239
+ }
240
+ /**
241
+ * Create an extension negotiation offer.
242
+ *
243
+ * @return {Object} Extension parameters
244
+ * @public
245
+ */
246
+ offer() {
247
+ const params = {};
248
+ if (this._options.serverNoContextTakeover) {
249
+ params.server_no_context_takeover = true;
250
+ }
251
+ if (this._options.clientNoContextTakeover) {
252
+ params.client_no_context_takeover = true;
253
+ }
254
+ if (this._options.serverMaxWindowBits) {
255
+ params.server_max_window_bits = this._options.serverMaxWindowBits;
256
+ }
257
+ if (this._options.clientMaxWindowBits) {
258
+ params.client_max_window_bits = this._options.clientMaxWindowBits;
259
+ } else if (this._options.clientMaxWindowBits == null) {
260
+ params.client_max_window_bits = true;
261
+ }
262
+ return params;
263
+ }
264
+ /**
265
+ * Accept an extension negotiation offer/response.
266
+ *
267
+ * @param {Array} configurations The extension negotiation offers/reponse
268
+ * @return {Object} Accepted configuration
269
+ * @public
270
+ */
271
+ accept(configurations) {
272
+ configurations = this.normalizeParams(configurations);
273
+ this.params = this._isServer ? this.acceptAsServer(configurations) : this.acceptAsClient(configurations);
274
+ return this.params;
275
+ }
276
+ /**
277
+ * Releases all resources used by the extension.
278
+ *
279
+ * @public
280
+ */
281
+ cleanup() {
282
+ if (this._inflate) {
283
+ this._inflate.close();
284
+ this._inflate = null;
285
+ }
286
+ if (this._deflate) {
287
+ const callback = this._deflate[kCallback];
288
+ this._deflate.close();
289
+ this._deflate = null;
290
+ if (callback) {
291
+ callback(
292
+ new Error(
293
+ "The deflate stream was closed while data was being processed"
294
+ )
295
+ );
296
+ }
297
+ }
298
+ }
299
+ /**
300
+ * Accept an extension negotiation offer.
301
+ *
302
+ * @param {Array} offers The extension negotiation offers
303
+ * @return {Object} Accepted configuration
304
+ * @private
305
+ */
306
+ acceptAsServer(offers) {
307
+ const opts = this._options;
308
+ const accepted = offers.find((params) => {
309
+ if (opts.serverNoContextTakeover === false && params.server_no_context_takeover || params.server_max_window_bits && (opts.serverMaxWindowBits === false || typeof opts.serverMaxWindowBits === "number" && opts.serverMaxWindowBits > params.server_max_window_bits) || typeof opts.clientMaxWindowBits === "number" && (typeof params.client_max_window_bits === "number" ? opts.clientMaxWindowBits > params.client_max_window_bits : !params.client_max_window_bits)) {
310
+ return false;
311
+ }
312
+ return true;
313
+ });
314
+ if (!accepted) {
315
+ throw new Error("None of the extension offers can be accepted");
316
+ }
317
+ if (opts.serverNoContextTakeover) {
318
+ accepted.server_no_context_takeover = true;
319
+ }
320
+ if (opts.clientNoContextTakeover) {
321
+ accepted.client_no_context_takeover = true;
322
+ }
323
+ if (typeof opts.serverMaxWindowBits === "number") {
324
+ accepted.server_max_window_bits = opts.serverMaxWindowBits;
325
+ }
326
+ if (typeof opts.clientMaxWindowBits === "number") {
327
+ accepted.client_max_window_bits = opts.clientMaxWindowBits;
328
+ } else if (accepted.client_max_window_bits === true || opts.clientMaxWindowBits === false) {
329
+ delete accepted.client_max_window_bits;
330
+ }
331
+ return accepted;
332
+ }
333
+ /**
334
+ * Accept the extension negotiation response.
335
+ *
336
+ * @param {Array} response The extension negotiation response
337
+ * @return {Object} Accepted configuration
338
+ * @private
339
+ */
340
+ acceptAsClient(response) {
341
+ const params = response[0];
342
+ if (this._options.clientNoContextTakeover === false && params.client_no_context_takeover) {
343
+ throw new Error('Unexpected parameter "client_no_context_takeover"');
344
+ }
345
+ if (!params.client_max_window_bits) {
346
+ if (typeof this._options.clientMaxWindowBits === "number") {
347
+ params.client_max_window_bits = this._options.clientMaxWindowBits;
348
+ }
349
+ } else if (this._options.clientMaxWindowBits === false || typeof this._options.clientMaxWindowBits === "number" && params.client_max_window_bits > this._options.clientMaxWindowBits) {
350
+ throw new Error(
351
+ 'Unexpected or invalid parameter "client_max_window_bits"'
352
+ );
353
+ }
354
+ return params;
355
+ }
356
+ /**
357
+ * Normalize parameters.
358
+ *
359
+ * @param {Array} configurations The extension negotiation offers/reponse
360
+ * @return {Array} The offers/response with normalized parameters
361
+ * @private
362
+ */
363
+ normalizeParams(configurations) {
364
+ configurations.forEach((params) => {
365
+ Object.keys(params).forEach((key) => {
366
+ let value = params[key];
367
+ if (value.length > 1) {
368
+ throw new Error(`Parameter "${key}" must have only a single value`);
369
+ }
370
+ value = value[0];
371
+ if (key === "client_max_window_bits") {
372
+ if (value !== true) {
373
+ const num = +value;
374
+ if (!Number.isInteger(num) || num < 8 || num > 15) {
375
+ throw new TypeError(
376
+ `Invalid value for parameter "${key}": ${value}`
377
+ );
378
+ }
379
+ value = num;
380
+ } else if (!this._isServer) {
381
+ throw new TypeError(
382
+ `Invalid value for parameter "${key}": ${value}`
383
+ );
384
+ }
385
+ } else if (key === "server_max_window_bits") {
386
+ const num = +value;
387
+ if (!Number.isInteger(num) || num < 8 || num > 15) {
388
+ throw new TypeError(
389
+ `Invalid value for parameter "${key}": ${value}`
390
+ );
391
+ }
392
+ value = num;
393
+ } else if (key === "client_no_context_takeover" || key === "server_no_context_takeover") {
394
+ if (value !== true) {
395
+ throw new TypeError(
396
+ `Invalid value for parameter "${key}": ${value}`
397
+ );
398
+ }
399
+ } else {
400
+ throw new Error(`Unknown parameter "${key}"`);
401
+ }
402
+ params[key] = value;
403
+ });
404
+ });
405
+ return configurations;
406
+ }
407
+ /**
408
+ * Decompress data. Concurrency limited.
409
+ *
410
+ * @param {Buffer} data Compressed data
411
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
412
+ * @param {Function} callback Callback
413
+ * @public
414
+ */
415
+ decompress(data, fin, callback) {
416
+ zlibLimiter.add((done) => {
417
+ this._decompress(data, fin, (err, result) => {
418
+ done();
419
+ callback(err, result);
420
+ });
421
+ });
422
+ }
423
+ /**
424
+ * Compress data. Concurrency limited.
425
+ *
426
+ * @param {(Buffer|String)} data Data to compress
427
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
428
+ * @param {Function} callback Callback
429
+ * @public
430
+ */
431
+ compress(data, fin, callback) {
432
+ zlibLimiter.add((done) => {
433
+ this._compress(data, fin, (err, result) => {
434
+ done();
435
+ callback(err, result);
436
+ });
437
+ });
438
+ }
439
+ /**
440
+ * Decompress data.
441
+ *
442
+ * @param {Buffer} data Compressed data
443
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
444
+ * @param {Function} callback Callback
445
+ * @private
446
+ */
447
+ _decompress(data, fin, callback) {
448
+ const endpoint = this._isServer ? "client" : "server";
449
+ if (!this._inflate) {
450
+ const key = `${endpoint}_max_window_bits`;
451
+ const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
452
+ this._inflate = zlib.createInflateRaw({
453
+ ...this._options.zlibInflateOptions,
454
+ windowBits
455
+ });
456
+ this._inflate[kPerMessageDeflate] = this;
457
+ this._inflate[kTotalLength] = 0;
458
+ this._inflate[kBuffers] = [];
459
+ this._inflate.on("error", inflateOnError);
460
+ this._inflate.on("data", inflateOnData);
461
+ }
462
+ this._inflate[kCallback] = callback;
463
+ this._inflate.write(data);
464
+ if (fin) this._inflate.write(TRAILER);
465
+ this._inflate.flush(() => {
466
+ const err = this._inflate[kError];
467
+ if (err) {
468
+ this._inflate.close();
469
+ this._inflate = null;
470
+ callback(err);
471
+ return;
472
+ }
473
+ const data2 = bufferUtil.concat(
474
+ this._inflate[kBuffers],
475
+ this._inflate[kTotalLength]
476
+ );
477
+ if (this._inflate._readableState.endEmitted) {
478
+ this._inflate.close();
479
+ this._inflate = null;
480
+ } else {
481
+ this._inflate[kTotalLength] = 0;
482
+ this._inflate[kBuffers] = [];
483
+ if (fin && this.params[`${endpoint}_no_context_takeover`]) {
484
+ this._inflate.reset();
485
+ }
486
+ }
487
+ callback(null, data2);
488
+ });
489
+ }
490
+ /**
491
+ * Compress data.
492
+ *
493
+ * @param {(Buffer|String)} data Data to compress
494
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
495
+ * @param {Function} callback Callback
496
+ * @private
497
+ */
498
+ _compress(data, fin, callback) {
499
+ const endpoint = this._isServer ? "server" : "client";
500
+ if (!this._deflate) {
501
+ const key = `${endpoint}_max_window_bits`;
502
+ const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
503
+ this._deflate = zlib.createDeflateRaw({
504
+ ...this._options.zlibDeflateOptions,
505
+ windowBits
506
+ });
507
+ this._deflate[kTotalLength] = 0;
508
+ this._deflate[kBuffers] = [];
509
+ this._deflate.on("data", deflateOnData);
510
+ }
511
+ this._deflate[kCallback] = callback;
512
+ this._deflate.write(data);
513
+ this._deflate.flush(zlib.Z_SYNC_FLUSH, () => {
514
+ if (!this._deflate) {
515
+ return;
516
+ }
517
+ let data2 = bufferUtil.concat(
518
+ this._deflate[kBuffers],
519
+ this._deflate[kTotalLength]
520
+ );
521
+ if (fin) {
522
+ data2 = new FastBuffer(data2.buffer, data2.byteOffset, data2.length - 4);
523
+ }
524
+ this._deflate[kCallback] = null;
525
+ this._deflate[kTotalLength] = 0;
526
+ this._deflate[kBuffers] = [];
527
+ if (fin && this.params[`${endpoint}_no_context_takeover`]) {
528
+ this._deflate.reset();
529
+ }
530
+ callback(null, data2);
531
+ });
532
+ }
533
+ };
534
+ module2.exports = PerMessageDeflate2;
535
+ function deflateOnData(chunk) {
536
+ this[kBuffers].push(chunk);
537
+ this[kTotalLength] += chunk.length;
538
+ }
539
+ function inflateOnData(chunk) {
540
+ this[kTotalLength] += chunk.length;
541
+ if (this[kPerMessageDeflate]._maxPayload < 1 || this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload) {
542
+ this[kBuffers].push(chunk);
543
+ return;
544
+ }
545
+ this[kError] = new RangeError("Max payload size exceeded");
546
+ this[kError].code = "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH";
547
+ this[kError][kStatusCode] = 1009;
548
+ this.removeListener("data", inflateOnData);
549
+ this.reset();
550
+ }
551
+ function inflateOnError(err) {
552
+ this[kPerMessageDeflate]._inflate = null;
553
+ if (this[kError]) {
554
+ this[kCallback](this[kError]);
555
+ return;
556
+ }
557
+ err[kStatusCode] = 1007;
558
+ this[kCallback](err);
559
+ }
560
+ }
561
+ });
562
+
563
+ // apps/daemon/node_modules/ws/lib/validation.js
564
+ var require_validation = __commonJS({
565
+ "apps/daemon/node_modules/ws/lib/validation.js"(exports2, module2) {
566
+ "use strict";
567
+ var { isUtf8 } = require("buffer");
568
+ var { hasBlob } = require_constants();
569
+ var tokenChars = [
570
+ 0,
571
+ 0,
572
+ 0,
573
+ 0,
574
+ 0,
575
+ 0,
576
+ 0,
577
+ 0,
578
+ 0,
579
+ 0,
580
+ 0,
581
+ 0,
582
+ 0,
583
+ 0,
584
+ 0,
585
+ 0,
586
+ // 0 - 15
587
+ 0,
588
+ 0,
589
+ 0,
590
+ 0,
591
+ 0,
592
+ 0,
593
+ 0,
594
+ 0,
595
+ 0,
596
+ 0,
597
+ 0,
598
+ 0,
599
+ 0,
600
+ 0,
601
+ 0,
602
+ 0,
603
+ // 16 - 31
604
+ 0,
605
+ 1,
606
+ 0,
607
+ 1,
608
+ 1,
609
+ 1,
610
+ 1,
611
+ 1,
612
+ 0,
613
+ 0,
614
+ 1,
615
+ 1,
616
+ 0,
617
+ 1,
618
+ 1,
619
+ 0,
620
+ // 32 - 47
621
+ 1,
622
+ 1,
623
+ 1,
624
+ 1,
625
+ 1,
626
+ 1,
627
+ 1,
628
+ 1,
629
+ 1,
630
+ 1,
631
+ 0,
632
+ 0,
633
+ 0,
634
+ 0,
635
+ 0,
636
+ 0,
637
+ // 48 - 63
638
+ 0,
639
+ 1,
640
+ 1,
641
+ 1,
642
+ 1,
643
+ 1,
644
+ 1,
645
+ 1,
646
+ 1,
647
+ 1,
648
+ 1,
649
+ 1,
650
+ 1,
651
+ 1,
652
+ 1,
653
+ 1,
654
+ // 64 - 79
655
+ 1,
656
+ 1,
657
+ 1,
658
+ 1,
659
+ 1,
660
+ 1,
661
+ 1,
662
+ 1,
663
+ 1,
664
+ 1,
665
+ 1,
666
+ 0,
667
+ 0,
668
+ 0,
669
+ 1,
670
+ 1,
671
+ // 80 - 95
672
+ 1,
673
+ 1,
674
+ 1,
675
+ 1,
676
+ 1,
677
+ 1,
678
+ 1,
679
+ 1,
680
+ 1,
681
+ 1,
682
+ 1,
683
+ 1,
684
+ 1,
685
+ 1,
686
+ 1,
687
+ 1,
688
+ // 96 - 111
689
+ 1,
690
+ 1,
691
+ 1,
692
+ 1,
693
+ 1,
694
+ 1,
695
+ 1,
696
+ 1,
697
+ 1,
698
+ 1,
699
+ 1,
700
+ 0,
701
+ 1,
702
+ 0,
703
+ 1,
704
+ 0
705
+ // 112 - 127
706
+ ];
707
+ function isValidStatusCode(code) {
708
+ return code >= 1e3 && code <= 1014 && code !== 1004 && code !== 1005 && code !== 1006 || code >= 3e3 && code <= 4999;
709
+ }
710
+ function _isValidUTF8(buf) {
711
+ const len = buf.length;
712
+ let i = 0;
713
+ while (i < len) {
714
+ if ((buf[i] & 128) === 0) {
715
+ i++;
716
+ } else if ((buf[i] & 224) === 192) {
717
+ if (i + 1 === len || (buf[i + 1] & 192) !== 128 || (buf[i] & 254) === 192) {
718
+ return false;
719
+ }
720
+ i += 2;
721
+ } else if ((buf[i] & 240) === 224) {
722
+ if (i + 2 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || buf[i] === 224 && (buf[i + 1] & 224) === 128 || // Overlong
723
+ buf[i] === 237 && (buf[i + 1] & 224) === 160) {
724
+ return false;
725
+ }
726
+ i += 3;
727
+ } else if ((buf[i] & 248) === 240) {
728
+ 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
729
+ buf[i] === 244 && buf[i + 1] > 143 || buf[i] > 244) {
730
+ return false;
731
+ }
732
+ i += 4;
733
+ } else {
734
+ return false;
735
+ }
736
+ }
737
+ return true;
738
+ }
739
+ function isBlob(value) {
740
+ 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");
741
+ }
742
+ module2.exports = {
743
+ isBlob,
744
+ isValidStatusCode,
745
+ isValidUTF8: _isValidUTF8,
746
+ tokenChars
747
+ };
748
+ if (isUtf8) {
749
+ module2.exports.isValidUTF8 = function(buf) {
750
+ return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf);
751
+ };
752
+ } else if (!process.env.WS_NO_UTF_8_VALIDATE) {
753
+ try {
754
+ const isValidUTF8 = require("utf-8-validate");
755
+ module2.exports.isValidUTF8 = function(buf) {
756
+ return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf);
757
+ };
758
+ } catch (e) {
759
+ }
760
+ }
761
+ }
762
+ });
763
+
764
+ // apps/daemon/node_modules/ws/lib/receiver.js
765
+ var require_receiver = __commonJS({
766
+ "apps/daemon/node_modules/ws/lib/receiver.js"(exports2, module2) {
767
+ "use strict";
768
+ var { Writable } = require("stream");
769
+ var PerMessageDeflate2 = require_permessage_deflate();
770
+ var {
771
+ BINARY_TYPES,
772
+ EMPTY_BUFFER,
773
+ kStatusCode,
774
+ kWebSocket
775
+ } = require_constants();
776
+ var { concat, toArrayBuffer, unmask } = require_buffer_util();
777
+ var { isValidStatusCode, isValidUTF8 } = require_validation();
778
+ var FastBuffer = Buffer[Symbol.species];
779
+ var GET_INFO = 0;
780
+ var GET_PAYLOAD_LENGTH_16 = 1;
781
+ var GET_PAYLOAD_LENGTH_64 = 2;
782
+ var GET_MASK = 3;
783
+ var GET_DATA = 4;
784
+ var INFLATING = 5;
785
+ var DEFER_EVENT = 6;
786
+ var Receiver2 = class extends Writable {
787
+ /**
788
+ * Creates a Receiver instance.
789
+ *
790
+ * @param {Object} [options] Options object
791
+ * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
792
+ * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
793
+ * multiple times in the same tick
794
+ * @param {String} [options.binaryType=nodebuffer] The type for binary data
795
+ * @param {Object} [options.extensions] An object containing the negotiated
796
+ * extensions
797
+ * @param {Boolean} [options.isServer=false] Specifies whether to operate in
798
+ * client or server mode
799
+ * @param {Number} [options.maxBufferedChunks=0] The maximum number of
800
+ * buffered data chunks
801
+ * @param {Number} [options.maxFragments=0] The maximum number of message
802
+ * fragments
803
+ * @param {Number} [options.maxPayload=0] The maximum allowed message length
804
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
805
+ * not to skip UTF-8 validation for text and close messages
806
+ */
807
+ constructor(options = {}) {
808
+ super();
809
+ this._allowSynchronousEvents = options.allowSynchronousEvents !== void 0 ? options.allowSynchronousEvents : true;
810
+ this._binaryType = options.binaryType || BINARY_TYPES[0];
811
+ this._extensions = options.extensions || {};
812
+ this._isServer = !!options.isServer;
813
+ this._maxBufferedChunks = options.maxBufferedChunks | 0;
814
+ this._maxFragments = options.maxFragments | 0;
815
+ this._maxPayload = options.maxPayload | 0;
816
+ this._skipUTF8Validation = !!options.skipUTF8Validation;
817
+ this[kWebSocket] = void 0;
818
+ this._bufferedBytes = 0;
819
+ this._buffers = [];
820
+ this._compressed = false;
821
+ this._payloadLength = 0;
822
+ this._mask = void 0;
823
+ this._fragmented = 0;
824
+ this._masked = false;
825
+ this._fin = false;
826
+ this._opcode = 0;
827
+ this._totalPayloadLength = 0;
828
+ this._messageLength = 0;
829
+ this._numFragments = 0;
830
+ this._fragments = [];
831
+ this._errored = false;
832
+ this._loop = false;
833
+ this._state = GET_INFO;
834
+ }
835
+ /**
836
+ * Implements `Writable.prototype._write()`.
837
+ *
838
+ * @param {Buffer} chunk The chunk of data to write
839
+ * @param {String} encoding The character encoding of `chunk`
840
+ * @param {Function} cb Callback
841
+ * @private
842
+ */
843
+ _write(chunk, encoding, cb) {
844
+ if (this._opcode === 8 && this._state == GET_INFO) return cb();
845
+ if (this._maxBufferedChunks > 0 && this._buffers.length >= this._maxBufferedChunks) {
846
+ cb(
847
+ this.createError(
848
+ RangeError,
849
+ "Too many buffered chunks",
850
+ false,
851
+ 1008,
852
+ "WS_ERR_TOO_MANY_BUFFERED_PARTS"
853
+ )
854
+ );
855
+ return;
856
+ }
857
+ this._bufferedBytes += chunk.length;
858
+ this._buffers.push(chunk);
859
+ this.startLoop(cb);
860
+ }
861
+ /**
862
+ * Consumes `n` bytes from the buffered data.
863
+ *
864
+ * @param {Number} n The number of bytes to consume
865
+ * @return {Buffer} The consumed bytes
866
+ * @private
867
+ */
868
+ consume(n) {
869
+ this._bufferedBytes -= n;
870
+ if (n === this._buffers[0].length) return this._buffers.shift();
871
+ if (n < this._buffers[0].length) {
872
+ const buf = this._buffers[0];
873
+ this._buffers[0] = new FastBuffer(
874
+ buf.buffer,
875
+ buf.byteOffset + n,
876
+ buf.length - n
877
+ );
878
+ return new FastBuffer(buf.buffer, buf.byteOffset, n);
879
+ }
880
+ const dst = Buffer.allocUnsafe(n);
881
+ do {
882
+ const buf = this._buffers[0];
883
+ const offset = dst.length - n;
884
+ if (n >= buf.length) {
885
+ dst.set(this._buffers.shift(), offset);
886
+ } else {
887
+ dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset);
888
+ this._buffers[0] = new FastBuffer(
889
+ buf.buffer,
890
+ buf.byteOffset + n,
891
+ buf.length - n
892
+ );
893
+ }
894
+ n -= buf.length;
895
+ } while (n > 0);
896
+ return dst;
897
+ }
898
+ /**
899
+ * Starts the parsing loop.
900
+ *
901
+ * @param {Function} cb Callback
902
+ * @private
903
+ */
904
+ startLoop(cb) {
905
+ this._loop = true;
906
+ do {
907
+ switch (this._state) {
908
+ case GET_INFO:
909
+ this.getInfo(cb);
910
+ break;
911
+ case GET_PAYLOAD_LENGTH_16:
912
+ this.getPayloadLength16(cb);
913
+ break;
914
+ case GET_PAYLOAD_LENGTH_64:
915
+ this.getPayloadLength64(cb);
916
+ break;
917
+ case GET_MASK:
918
+ this.getMask();
919
+ break;
920
+ case GET_DATA:
921
+ this.getData(cb);
922
+ break;
923
+ case INFLATING:
924
+ case DEFER_EVENT:
925
+ this._loop = false;
926
+ return;
927
+ }
928
+ } while (this._loop);
929
+ if (!this._errored) cb();
930
+ }
931
+ /**
932
+ * Reads the first two bytes of a frame.
933
+ *
934
+ * @param {Function} cb Callback
935
+ * @private
936
+ */
937
+ getInfo(cb) {
938
+ if (this._bufferedBytes < 2) {
939
+ this._loop = false;
940
+ return;
941
+ }
942
+ const buf = this.consume(2);
943
+ if ((buf[0] & 48) !== 0) {
944
+ const error = this.createError(
945
+ RangeError,
946
+ "RSV2 and RSV3 must be clear",
947
+ true,
948
+ 1002,
949
+ "WS_ERR_UNEXPECTED_RSV_2_3"
950
+ );
951
+ cb(error);
952
+ return;
953
+ }
954
+ const compressed = (buf[0] & 64) === 64;
955
+ if (compressed && !this._extensions[PerMessageDeflate2.extensionName]) {
956
+ const error = this.createError(
957
+ RangeError,
958
+ "RSV1 must be clear",
959
+ true,
960
+ 1002,
961
+ "WS_ERR_UNEXPECTED_RSV_1"
962
+ );
963
+ cb(error);
964
+ return;
965
+ }
966
+ this._fin = (buf[0] & 128) === 128;
967
+ this._opcode = buf[0] & 15;
968
+ this._payloadLength = buf[1] & 127;
969
+ if (this._opcode === 0) {
970
+ if (compressed) {
971
+ const error = this.createError(
972
+ RangeError,
973
+ "RSV1 must be clear",
974
+ true,
975
+ 1002,
976
+ "WS_ERR_UNEXPECTED_RSV_1"
977
+ );
978
+ cb(error);
979
+ return;
980
+ }
981
+ if (!this._fragmented) {
982
+ const error = this.createError(
983
+ RangeError,
984
+ "invalid opcode 0",
985
+ true,
986
+ 1002,
987
+ "WS_ERR_INVALID_OPCODE"
988
+ );
989
+ cb(error);
990
+ return;
991
+ }
992
+ this._opcode = this._fragmented;
993
+ } else if (this._opcode === 1 || this._opcode === 2) {
994
+ if (this._fragmented) {
995
+ const error = this.createError(
996
+ RangeError,
997
+ `invalid opcode ${this._opcode}`,
998
+ true,
999
+ 1002,
1000
+ "WS_ERR_INVALID_OPCODE"
1001
+ );
1002
+ cb(error);
1003
+ return;
1004
+ }
1005
+ this._compressed = compressed;
1006
+ } else if (this._opcode > 7 && this._opcode < 11) {
1007
+ if (!this._fin) {
1008
+ const error = this.createError(
1009
+ RangeError,
1010
+ "FIN must be set",
1011
+ true,
1012
+ 1002,
1013
+ "WS_ERR_EXPECTED_FIN"
1014
+ );
1015
+ cb(error);
1016
+ return;
1017
+ }
1018
+ if (compressed) {
1019
+ const error = this.createError(
1020
+ RangeError,
1021
+ "RSV1 must be clear",
1022
+ true,
1023
+ 1002,
1024
+ "WS_ERR_UNEXPECTED_RSV_1"
1025
+ );
1026
+ cb(error);
1027
+ return;
1028
+ }
1029
+ if (this._payloadLength > 125 || this._opcode === 8 && this._payloadLength === 1) {
1030
+ const error = this.createError(
1031
+ RangeError,
1032
+ `invalid payload length ${this._payloadLength}`,
1033
+ true,
1034
+ 1002,
1035
+ "WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH"
1036
+ );
1037
+ cb(error);
1038
+ return;
1039
+ }
1040
+ } else {
1041
+ const error = this.createError(
1042
+ RangeError,
1043
+ `invalid opcode ${this._opcode}`,
1044
+ true,
1045
+ 1002,
1046
+ "WS_ERR_INVALID_OPCODE"
1047
+ );
1048
+ cb(error);
1049
+ return;
1050
+ }
1051
+ if (!this._fin && !this._fragmented) this._fragmented = this._opcode;
1052
+ this._masked = (buf[1] & 128) === 128;
1053
+ if (this._isServer) {
1054
+ if (!this._masked) {
1055
+ const error = this.createError(
1056
+ RangeError,
1057
+ "MASK must be set",
1058
+ true,
1059
+ 1002,
1060
+ "WS_ERR_EXPECTED_MASK"
1061
+ );
1062
+ cb(error);
1063
+ return;
1064
+ }
1065
+ } else if (this._masked) {
1066
+ const error = this.createError(
1067
+ RangeError,
1068
+ "MASK must be clear",
1069
+ true,
1070
+ 1002,
1071
+ "WS_ERR_UNEXPECTED_MASK"
1072
+ );
1073
+ cb(error);
1074
+ return;
1075
+ }
1076
+ if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16;
1077
+ else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64;
1078
+ else this.haveLength(cb);
1079
+ }
1080
+ /**
1081
+ * Gets extended payload length (7+16).
1082
+ *
1083
+ * @param {Function} cb Callback
1084
+ * @private
1085
+ */
1086
+ getPayloadLength16(cb) {
1087
+ if (this._bufferedBytes < 2) {
1088
+ this._loop = false;
1089
+ return;
1090
+ }
1091
+ this._payloadLength = this.consume(2).readUInt16BE(0);
1092
+ this.haveLength(cb);
1093
+ }
1094
+ /**
1095
+ * Gets extended payload length (7+64).
1096
+ *
1097
+ * @param {Function} cb Callback
1098
+ * @private
1099
+ */
1100
+ getPayloadLength64(cb) {
1101
+ if (this._bufferedBytes < 8) {
1102
+ this._loop = false;
1103
+ return;
1104
+ }
1105
+ const buf = this.consume(8);
1106
+ const num = buf.readUInt32BE(0);
1107
+ if (num > Math.pow(2, 53 - 32) - 1) {
1108
+ const error = this.createError(
1109
+ RangeError,
1110
+ "Unsupported WebSocket frame: payload length > 2^53 - 1",
1111
+ false,
1112
+ 1009,
1113
+ "WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH"
1114
+ );
1115
+ cb(error);
1116
+ return;
1117
+ }
1118
+ this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4);
1119
+ this.haveLength(cb);
1120
+ }
1121
+ /**
1122
+ * Payload length has been read.
1123
+ *
1124
+ * @param {Function} cb Callback
1125
+ * @private
1126
+ */
1127
+ haveLength(cb) {
1128
+ if (this._payloadLength && this._opcode < 8) {
1129
+ this._totalPayloadLength += this._payloadLength;
1130
+ if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) {
1131
+ const error = this.createError(
1132
+ RangeError,
1133
+ "Max payload size exceeded",
1134
+ false,
1135
+ 1009,
1136
+ "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"
1137
+ );
1138
+ cb(error);
1139
+ return;
1140
+ }
1141
+ }
1142
+ if (this._masked) this._state = GET_MASK;
1143
+ else this._state = GET_DATA;
1144
+ }
1145
+ /**
1146
+ * Reads mask bytes.
1147
+ *
1148
+ * @private
1149
+ */
1150
+ getMask() {
1151
+ if (this._bufferedBytes < 4) {
1152
+ this._loop = false;
1153
+ return;
1154
+ }
1155
+ this._mask = this.consume(4);
1156
+ this._state = GET_DATA;
1157
+ }
1158
+ /**
1159
+ * Reads data bytes.
1160
+ *
1161
+ * @param {Function} cb Callback
1162
+ * @private
1163
+ */
1164
+ getData(cb) {
1165
+ let data = EMPTY_BUFFER;
1166
+ if (this._payloadLength) {
1167
+ if (this._bufferedBytes < this._payloadLength) {
1168
+ this._loop = false;
1169
+ return;
1170
+ }
1171
+ data = this.consume(this._payloadLength);
1172
+ if (this._masked && (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0) {
1173
+ unmask(data, this._mask);
1174
+ }
1175
+ }
1176
+ if (this._opcode > 7) {
1177
+ this.controlMessage(data, cb);
1178
+ return;
1179
+ }
1180
+ if (this._maxFragments > 0 && ++this._numFragments > this._maxFragments) {
1181
+ const error = this.createError(
1182
+ RangeError,
1183
+ "Too many message fragments",
1184
+ false,
1185
+ 1008,
1186
+ "WS_ERR_TOO_MANY_BUFFERED_PARTS"
1187
+ );
1188
+ cb(error);
1189
+ return;
1190
+ }
1191
+ if (this._compressed) {
1192
+ this._state = INFLATING;
1193
+ this.decompress(data, cb);
1194
+ return;
1195
+ }
1196
+ if (data.length) {
1197
+ this._messageLength = this._totalPayloadLength;
1198
+ this._fragments.push(data);
1199
+ }
1200
+ this.dataMessage(cb);
1201
+ }
1202
+ /**
1203
+ * Decompresses data.
1204
+ *
1205
+ * @param {Buffer} data Compressed data
1206
+ * @param {Function} cb Callback
1207
+ * @private
1208
+ */
1209
+ decompress(data, cb) {
1210
+ const perMessageDeflate = this._extensions[PerMessageDeflate2.extensionName];
1211
+ perMessageDeflate.decompress(data, this._fin, (err, buf) => {
1212
+ if (err) return cb(err);
1213
+ if (buf.length) {
1214
+ this._messageLength += buf.length;
1215
+ if (this._messageLength > this._maxPayload && this._maxPayload > 0) {
1216
+ const error = this.createError(
1217
+ RangeError,
1218
+ "Max payload size exceeded",
1219
+ false,
1220
+ 1009,
1221
+ "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"
1222
+ );
1223
+ cb(error);
1224
+ return;
1225
+ }
1226
+ this._fragments.push(buf);
1227
+ }
1228
+ this.dataMessage(cb);
1229
+ if (this._state === GET_INFO) this.startLoop(cb);
1230
+ });
1231
+ }
1232
+ /**
1233
+ * Handles a data message.
1234
+ *
1235
+ * @param {Function} cb Callback
1236
+ * @private
1237
+ */
1238
+ dataMessage(cb) {
1239
+ if (!this._fin) {
1240
+ this._state = GET_INFO;
1241
+ return;
1242
+ }
1243
+ const messageLength = this._messageLength;
1244
+ const fragments = this._fragments;
1245
+ this._totalPayloadLength = 0;
1246
+ this._messageLength = 0;
1247
+ this._fragmented = 0;
1248
+ this._numFragments = 0;
1249
+ this._fragments = [];
1250
+ if (this._opcode === 2) {
1251
+ let data;
1252
+ if (this._binaryType === "nodebuffer") {
1253
+ data = concat(fragments, messageLength);
1254
+ } else if (this._binaryType === "arraybuffer") {
1255
+ data = toArrayBuffer(concat(fragments, messageLength));
1256
+ } else if (this._binaryType === "blob") {
1257
+ data = new Blob(fragments);
1258
+ } else {
1259
+ data = fragments;
1260
+ }
1261
+ if (this._allowSynchronousEvents) {
1262
+ this.emit("message", data, true);
1263
+ this._state = GET_INFO;
1264
+ } else {
1265
+ this._state = DEFER_EVENT;
1266
+ setImmediate(() => {
1267
+ this.emit("message", data, true);
1268
+ this._state = GET_INFO;
1269
+ this.startLoop(cb);
1270
+ });
1271
+ }
1272
+ } else {
1273
+ const buf = concat(fragments, messageLength);
1274
+ if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
1275
+ const error = this.createError(
1276
+ Error,
1277
+ "invalid UTF-8 sequence",
1278
+ true,
1279
+ 1007,
1280
+ "WS_ERR_INVALID_UTF8"
1281
+ );
1282
+ cb(error);
1283
+ return;
1284
+ }
1285
+ if (this._state === INFLATING || this._allowSynchronousEvents) {
1286
+ this.emit("message", buf, false);
1287
+ this._state = GET_INFO;
1288
+ } else {
1289
+ this._state = DEFER_EVENT;
1290
+ setImmediate(() => {
1291
+ this.emit("message", buf, false);
1292
+ this._state = GET_INFO;
1293
+ this.startLoop(cb);
1294
+ });
1295
+ }
1296
+ }
1297
+ }
1298
+ /**
1299
+ * Handles a control message.
1300
+ *
1301
+ * @param {Buffer} data Data to handle
1302
+ * @return {(Error|RangeError|undefined)} A possible error
1303
+ * @private
1304
+ */
1305
+ controlMessage(data, cb) {
1306
+ if (this._opcode === 8) {
1307
+ if (data.length === 0) {
1308
+ this._loop = false;
1309
+ this.emit("conclude", 1005, EMPTY_BUFFER);
1310
+ this.end();
1311
+ } else {
1312
+ const code = data.readUInt16BE(0);
1313
+ if (!isValidStatusCode(code)) {
1314
+ const error = this.createError(
1315
+ RangeError,
1316
+ `invalid status code ${code}`,
1317
+ true,
1318
+ 1002,
1319
+ "WS_ERR_INVALID_CLOSE_CODE"
1320
+ );
1321
+ cb(error);
1322
+ return;
1323
+ }
1324
+ const buf = new FastBuffer(
1325
+ data.buffer,
1326
+ data.byteOffset + 2,
1327
+ data.length - 2
1328
+ );
1329
+ if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
1330
+ const error = this.createError(
1331
+ Error,
1332
+ "invalid UTF-8 sequence",
1333
+ true,
1334
+ 1007,
1335
+ "WS_ERR_INVALID_UTF8"
1336
+ );
1337
+ cb(error);
1338
+ return;
1339
+ }
1340
+ this._loop = false;
1341
+ this.emit("conclude", code, buf);
1342
+ this.end();
1343
+ }
1344
+ this._state = GET_INFO;
1345
+ return;
1346
+ }
1347
+ if (this._allowSynchronousEvents) {
1348
+ this.emit(this._opcode === 9 ? "ping" : "pong", data);
1349
+ this._state = GET_INFO;
1350
+ } else {
1351
+ this._state = DEFER_EVENT;
1352
+ setImmediate(() => {
1353
+ this.emit(this._opcode === 9 ? "ping" : "pong", data);
1354
+ this._state = GET_INFO;
1355
+ this.startLoop(cb);
1356
+ });
1357
+ }
1358
+ }
1359
+ /**
1360
+ * Builds an error object.
1361
+ *
1362
+ * @param {function(new:Error|RangeError)} ErrorCtor The error constructor
1363
+ * @param {String} message The error message
1364
+ * @param {Boolean} prefix Specifies whether or not to add a default prefix to
1365
+ * `message`
1366
+ * @param {Number} statusCode The status code
1367
+ * @param {String} errorCode The exposed error code
1368
+ * @return {(Error|RangeError)} The error
1369
+ * @private
1370
+ */
1371
+ createError(ErrorCtor, message, prefix, statusCode, errorCode) {
1372
+ this._loop = false;
1373
+ this._errored = true;
1374
+ const err = new ErrorCtor(
1375
+ prefix ? `Invalid WebSocket frame: ${message}` : message
1376
+ );
1377
+ Error.captureStackTrace(err, this.createError);
1378
+ err.code = errorCode;
1379
+ err[kStatusCode] = statusCode;
1380
+ return err;
1381
+ }
1382
+ };
1383
+ module2.exports = Receiver2;
1384
+ }
1385
+ });
1386
+
1387
+ // apps/daemon/node_modules/ws/lib/sender.js
1388
+ var require_sender = __commonJS({
1389
+ "apps/daemon/node_modules/ws/lib/sender.js"(exports2, module2) {
1390
+ "use strict";
1391
+ var { Duplex } = require("stream");
1392
+ var { randomFillSync } = require("crypto");
1393
+ var {
1394
+ types: { isUint8Array }
1395
+ } = require("util");
1396
+ var PerMessageDeflate2 = require_permessage_deflate();
1397
+ var { EMPTY_BUFFER, kWebSocket, NOOP } = require_constants();
1398
+ var { isBlob, isValidStatusCode } = require_validation();
1399
+ var { mask: applyMask, toBuffer } = require_buffer_util();
1400
+ var kByteLength = /* @__PURE__ */ Symbol("kByteLength");
1401
+ var maskBuffer = Buffer.alloc(4);
1402
+ var RANDOM_POOL_SIZE = 8 * 1024;
1403
+ var randomPool;
1404
+ var randomPoolPointer = RANDOM_POOL_SIZE;
1405
+ var DEFAULT = 0;
1406
+ var DEFLATING = 1;
1407
+ var GET_BLOB_DATA = 2;
1408
+ var Sender2 = class _Sender {
1409
+ /**
1410
+ * Creates a Sender instance.
1411
+ *
1412
+ * @param {Duplex} socket The connection socket
1413
+ * @param {Object} [extensions] An object containing the negotiated extensions
1414
+ * @param {Function} [generateMask] The function used to generate the masking
1415
+ * key
1416
+ */
1417
+ constructor(socket, extensions, generateMask) {
1418
+ this._extensions = extensions || {};
1419
+ if (generateMask) {
1420
+ this._generateMask = generateMask;
1421
+ this._maskBuffer = Buffer.alloc(4);
1422
+ }
1423
+ this._socket = socket;
1424
+ this._firstFragment = true;
1425
+ this._compress = false;
1426
+ this._bufferedBytes = 0;
1427
+ this._queue = [];
1428
+ this._state = DEFAULT;
1429
+ this.onerror = NOOP;
1430
+ this[kWebSocket] = void 0;
1431
+ }
1432
+ /**
1433
+ * Frames a piece of data according to the HyBi WebSocket protocol.
1434
+ *
1435
+ * @param {(Buffer|String)} data The data to frame
1436
+ * @param {Object} options Options object
1437
+ * @param {Boolean} [options.fin=false] Specifies whether or not to set the
1438
+ * FIN bit
1439
+ * @param {Function} [options.generateMask] The function used to generate the
1440
+ * masking key
1441
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1442
+ * `data`
1443
+ * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
1444
+ * key
1445
+ * @param {Number} options.opcode The opcode
1446
+ * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
1447
+ * modified
1448
+ * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
1449
+ * RSV1 bit
1450
+ * @return {(Buffer|String)[]} The framed data
1451
+ * @public
1452
+ */
1453
+ static frame(data, options) {
1454
+ let mask;
1455
+ let merge = false;
1456
+ let offset = 2;
1457
+ let skipMasking = false;
1458
+ if (options.mask) {
1459
+ mask = options.maskBuffer || maskBuffer;
1460
+ if (options.generateMask) {
1461
+ options.generateMask(mask);
1462
+ } else {
1463
+ if (randomPoolPointer === RANDOM_POOL_SIZE) {
1464
+ if (randomPool === void 0) {
1465
+ randomPool = Buffer.alloc(RANDOM_POOL_SIZE);
1466
+ }
1467
+ randomFillSync(randomPool, 0, RANDOM_POOL_SIZE);
1468
+ randomPoolPointer = 0;
1469
+ }
1470
+ mask[0] = randomPool[randomPoolPointer++];
1471
+ mask[1] = randomPool[randomPoolPointer++];
1472
+ mask[2] = randomPool[randomPoolPointer++];
1473
+ mask[3] = randomPool[randomPoolPointer++];
1474
+ }
1475
+ skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0;
1476
+ offset = 6;
1477
+ }
1478
+ let dataLength;
1479
+ if (typeof data === "string") {
1480
+ if ((!options.mask || skipMasking) && options[kByteLength] !== void 0) {
1481
+ dataLength = options[kByteLength];
1482
+ } else {
1483
+ data = Buffer.from(data);
1484
+ dataLength = data.length;
1485
+ }
1486
+ } else {
1487
+ dataLength = data.length;
1488
+ merge = options.mask && options.readOnly && !skipMasking;
1489
+ }
1490
+ let payloadLength = dataLength;
1491
+ if (dataLength >= 65536) {
1492
+ offset += 8;
1493
+ payloadLength = 127;
1494
+ } else if (dataLength > 125) {
1495
+ offset += 2;
1496
+ payloadLength = 126;
1497
+ }
1498
+ const target = Buffer.allocUnsafe(merge ? dataLength + offset : offset);
1499
+ target[0] = options.fin ? options.opcode | 128 : options.opcode;
1500
+ if (options.rsv1) target[0] |= 64;
1501
+ target[1] = payloadLength;
1502
+ if (payloadLength === 126) {
1503
+ target.writeUInt16BE(dataLength, 2);
1504
+ } else if (payloadLength === 127) {
1505
+ target[2] = target[3] = 0;
1506
+ target.writeUIntBE(dataLength, 4, 6);
1507
+ }
1508
+ if (!options.mask) return [target, data];
1509
+ target[1] |= 128;
1510
+ target[offset - 4] = mask[0];
1511
+ target[offset - 3] = mask[1];
1512
+ target[offset - 2] = mask[2];
1513
+ target[offset - 1] = mask[3];
1514
+ if (skipMasking) return [target, data];
1515
+ if (merge) {
1516
+ applyMask(data, mask, target, offset, dataLength);
1517
+ return [target];
1518
+ }
1519
+ applyMask(data, mask, data, 0, dataLength);
1520
+ return [target, data];
1521
+ }
1522
+ /**
1523
+ * Sends a close message to the other peer.
1524
+ *
1525
+ * @param {Number} [code] The status code component of the body
1526
+ * @param {(String|Buffer)} [data] The message component of the body
1527
+ * @param {Boolean} [mask=false] Specifies whether or not to mask the message
1528
+ * @param {Function} [cb] Callback
1529
+ * @public
1530
+ */
1531
+ close(code, data, mask, cb) {
1532
+ let buf;
1533
+ if (code === void 0) {
1534
+ buf = EMPTY_BUFFER;
1535
+ } else if (typeof code !== "number" || !isValidStatusCode(code)) {
1536
+ throw new TypeError("First argument must be a valid error code number");
1537
+ } else if (data === void 0 || !data.length) {
1538
+ buf = Buffer.allocUnsafe(2);
1539
+ buf.writeUInt16BE(code, 0);
1540
+ } else {
1541
+ const length = Buffer.byteLength(data);
1542
+ if (length > 123) {
1543
+ throw new RangeError("The message must not be greater than 123 bytes");
1544
+ }
1545
+ buf = Buffer.allocUnsafe(2 + length);
1546
+ buf.writeUInt16BE(code, 0);
1547
+ if (typeof data === "string") {
1548
+ buf.write(data, 2);
1549
+ } else if (isUint8Array(data)) {
1550
+ buf.set(data, 2);
1551
+ } else {
1552
+ throw new TypeError("Second argument must be a string or a Uint8Array");
1553
+ }
1554
+ }
1555
+ const options = {
1556
+ [kByteLength]: buf.length,
1557
+ fin: true,
1558
+ generateMask: this._generateMask,
1559
+ mask,
1560
+ maskBuffer: this._maskBuffer,
1561
+ opcode: 8,
1562
+ readOnly: false,
1563
+ rsv1: false
1564
+ };
1565
+ if (this._state !== DEFAULT) {
1566
+ this.enqueue([this.dispatch, buf, false, options, cb]);
1567
+ } else {
1568
+ this.sendFrame(_Sender.frame(buf, options), cb);
1569
+ }
1570
+ }
1571
+ /**
1572
+ * Sends a ping message to the other peer.
1573
+ *
1574
+ * @param {*} data The message to send
1575
+ * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
1576
+ * @param {Function} [cb] Callback
1577
+ * @public
1578
+ */
1579
+ ping(data, mask, cb) {
1580
+ let byteLength;
1581
+ let readOnly;
1582
+ if (typeof data === "string") {
1583
+ byteLength = Buffer.byteLength(data);
1584
+ readOnly = false;
1585
+ } else if (isBlob(data)) {
1586
+ byteLength = data.size;
1587
+ readOnly = false;
1588
+ } else {
1589
+ data = toBuffer(data);
1590
+ byteLength = data.length;
1591
+ readOnly = toBuffer.readOnly;
1592
+ }
1593
+ if (byteLength > 125) {
1594
+ throw new RangeError("The data size must not be greater than 125 bytes");
1595
+ }
1596
+ const options = {
1597
+ [kByteLength]: byteLength,
1598
+ fin: true,
1599
+ generateMask: this._generateMask,
1600
+ mask,
1601
+ maskBuffer: this._maskBuffer,
1602
+ opcode: 9,
1603
+ readOnly,
1604
+ rsv1: false
1605
+ };
1606
+ if (isBlob(data)) {
1607
+ if (this._state !== DEFAULT) {
1608
+ this.enqueue([this.getBlobData, data, false, options, cb]);
1609
+ } else {
1610
+ this.getBlobData(data, false, options, cb);
1611
+ }
1612
+ } else if (this._state !== DEFAULT) {
1613
+ this.enqueue([this.dispatch, data, false, options, cb]);
1614
+ } else {
1615
+ this.sendFrame(_Sender.frame(data, options), cb);
1616
+ }
1617
+ }
1618
+ /**
1619
+ * Sends a pong message to the other peer.
1620
+ *
1621
+ * @param {*} data The message to send
1622
+ * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
1623
+ * @param {Function} [cb] Callback
1624
+ * @public
1625
+ */
1626
+ pong(data, mask, cb) {
1627
+ let byteLength;
1628
+ let readOnly;
1629
+ if (typeof data === "string") {
1630
+ byteLength = Buffer.byteLength(data);
1631
+ readOnly = false;
1632
+ } else if (isBlob(data)) {
1633
+ byteLength = data.size;
1634
+ readOnly = false;
1635
+ } else {
1636
+ data = toBuffer(data);
1637
+ byteLength = data.length;
1638
+ readOnly = toBuffer.readOnly;
1639
+ }
1640
+ if (byteLength > 125) {
1641
+ throw new RangeError("The data size must not be greater than 125 bytes");
1642
+ }
1643
+ const options = {
1644
+ [kByteLength]: byteLength,
1645
+ fin: true,
1646
+ generateMask: this._generateMask,
1647
+ mask,
1648
+ maskBuffer: this._maskBuffer,
1649
+ opcode: 10,
1650
+ readOnly,
1651
+ rsv1: false
1652
+ };
1653
+ if (isBlob(data)) {
1654
+ if (this._state !== DEFAULT) {
1655
+ this.enqueue([this.getBlobData, data, false, options, cb]);
1656
+ } else {
1657
+ this.getBlobData(data, false, options, cb);
1658
+ }
1659
+ } else if (this._state !== DEFAULT) {
1660
+ this.enqueue([this.dispatch, data, false, options, cb]);
1661
+ } else {
1662
+ this.sendFrame(_Sender.frame(data, options), cb);
1663
+ }
1664
+ }
1665
+ /**
1666
+ * Sends a data message to the other peer.
1667
+ *
1668
+ * @param {*} data The message to send
1669
+ * @param {Object} options Options object
1670
+ * @param {Boolean} [options.binary=false] Specifies whether `data` is binary
1671
+ * or text
1672
+ * @param {Boolean} [options.compress=false] Specifies whether or not to
1673
+ * compress `data`
1674
+ * @param {Boolean} [options.fin=false] Specifies whether the fragment is the
1675
+ * last one
1676
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1677
+ * `data`
1678
+ * @param {Function} [cb] Callback
1679
+ * @public
1680
+ */
1681
+ send(data, options, cb) {
1682
+ const perMessageDeflate = this._extensions[PerMessageDeflate2.extensionName];
1683
+ let opcode = options.binary ? 2 : 1;
1684
+ let rsv1 = options.compress;
1685
+ let byteLength;
1686
+ let readOnly;
1687
+ if (typeof data === "string") {
1688
+ byteLength = Buffer.byteLength(data);
1689
+ readOnly = false;
1690
+ } else if (isBlob(data)) {
1691
+ byteLength = data.size;
1692
+ readOnly = false;
1693
+ } else {
1694
+ data = toBuffer(data);
1695
+ byteLength = data.length;
1696
+ readOnly = toBuffer.readOnly;
1697
+ }
1698
+ if (this._firstFragment) {
1699
+ this._firstFragment = false;
1700
+ if (rsv1 && perMessageDeflate && perMessageDeflate.params[perMessageDeflate._isServer ? "server_no_context_takeover" : "client_no_context_takeover"]) {
1701
+ rsv1 = byteLength >= perMessageDeflate._threshold;
1702
+ }
1703
+ this._compress = rsv1;
1704
+ } else {
1705
+ rsv1 = false;
1706
+ opcode = 0;
1707
+ }
1708
+ if (options.fin) this._firstFragment = true;
1709
+ const opts = {
1710
+ [kByteLength]: byteLength,
1711
+ fin: options.fin,
1712
+ generateMask: this._generateMask,
1713
+ mask: options.mask,
1714
+ maskBuffer: this._maskBuffer,
1715
+ opcode,
1716
+ readOnly,
1717
+ rsv1
1718
+ };
1719
+ if (isBlob(data)) {
1720
+ if (this._state !== DEFAULT) {
1721
+ this.enqueue([this.getBlobData, data, this._compress, opts, cb]);
1722
+ } else {
1723
+ this.getBlobData(data, this._compress, opts, cb);
1724
+ }
1725
+ } else if (this._state !== DEFAULT) {
1726
+ this.enqueue([this.dispatch, data, this._compress, opts, cb]);
1727
+ } else {
1728
+ this.dispatch(data, this._compress, opts, cb);
1729
+ }
1730
+ }
1731
+ /**
1732
+ * Gets the contents of a blob as binary data.
1733
+ *
1734
+ * @param {Blob} blob The blob
1735
+ * @param {Boolean} [compress=false] Specifies whether or not to compress
1736
+ * the data
1737
+ * @param {Object} options Options object
1738
+ * @param {Boolean} [options.fin=false] Specifies whether or not to set the
1739
+ * FIN bit
1740
+ * @param {Function} [options.generateMask] The function used to generate the
1741
+ * masking key
1742
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1743
+ * `data`
1744
+ * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
1745
+ * key
1746
+ * @param {Number} options.opcode The opcode
1747
+ * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
1748
+ * modified
1749
+ * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
1750
+ * RSV1 bit
1751
+ * @param {Function} [cb] Callback
1752
+ * @private
1753
+ */
1754
+ getBlobData(blob, compress, options, cb) {
1755
+ this._bufferedBytes += options[kByteLength];
1756
+ this._state = GET_BLOB_DATA;
1757
+ blob.arrayBuffer().then((arrayBuffer) => {
1758
+ if (this._socket.destroyed) {
1759
+ const err = new Error(
1760
+ "The socket was closed while the blob was being read"
1761
+ );
1762
+ process.nextTick(callCallbacks, this, err, cb);
1763
+ return;
1764
+ }
1765
+ this._bufferedBytes -= options[kByteLength];
1766
+ const data = toBuffer(arrayBuffer);
1767
+ if (!compress) {
1768
+ this._state = DEFAULT;
1769
+ this.sendFrame(_Sender.frame(data, options), cb);
1770
+ this.dequeue();
1771
+ } else {
1772
+ this.dispatch(data, compress, options, cb);
1773
+ }
1774
+ }).catch((err) => {
1775
+ process.nextTick(onError, this, err, cb);
1776
+ });
1777
+ }
1778
+ /**
1779
+ * Dispatches a message.
1780
+ *
1781
+ * @param {(Buffer|String)} data The message to send
1782
+ * @param {Boolean} [compress=false] Specifies whether or not to compress
1783
+ * `data`
1784
+ * @param {Object} options Options object
1785
+ * @param {Boolean} [options.fin=false] Specifies whether or not to set the
1786
+ * FIN bit
1787
+ * @param {Function} [options.generateMask] The function used to generate the
1788
+ * masking key
1789
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1790
+ * `data`
1791
+ * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
1792
+ * key
1793
+ * @param {Number} options.opcode The opcode
1794
+ * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
1795
+ * modified
1796
+ * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
1797
+ * RSV1 bit
1798
+ * @param {Function} [cb] Callback
1799
+ * @private
1800
+ */
1801
+ dispatch(data, compress, options, cb) {
1802
+ if (!compress) {
1803
+ this.sendFrame(_Sender.frame(data, options), cb);
1804
+ return;
1805
+ }
1806
+ const perMessageDeflate = this._extensions[PerMessageDeflate2.extensionName];
1807
+ this._bufferedBytes += options[kByteLength];
1808
+ this._state = DEFLATING;
1809
+ perMessageDeflate.compress(data, options.fin, (_, buf) => {
1810
+ if (this._socket.destroyed) {
1811
+ const err = new Error(
1812
+ "The socket was closed while data was being compressed"
1813
+ );
1814
+ callCallbacks(this, err, cb);
1815
+ return;
1816
+ }
1817
+ this._bufferedBytes -= options[kByteLength];
1818
+ this._state = DEFAULT;
1819
+ options.readOnly = false;
1820
+ this.sendFrame(_Sender.frame(buf, options), cb);
1821
+ this.dequeue();
1822
+ });
1823
+ }
1824
+ /**
1825
+ * Executes queued send operations.
1826
+ *
1827
+ * @private
1828
+ */
1829
+ dequeue() {
1830
+ while (this._state === DEFAULT && this._queue.length) {
1831
+ const params = this._queue.shift();
1832
+ this._bufferedBytes -= params[3][kByteLength];
1833
+ Reflect.apply(params[0], this, params.slice(1));
1834
+ }
1835
+ }
1836
+ /**
1837
+ * Enqueues a send operation.
1838
+ *
1839
+ * @param {Array} params Send operation parameters.
1840
+ * @private
1841
+ */
1842
+ enqueue(params) {
1843
+ this._bufferedBytes += params[3][kByteLength];
1844
+ this._queue.push(params);
1845
+ }
1846
+ /**
1847
+ * Sends a frame.
1848
+ *
1849
+ * @param {(Buffer | String)[]} list The frame to send
1850
+ * @param {Function} [cb] Callback
1851
+ * @private
1852
+ */
1853
+ sendFrame(list, cb) {
1854
+ if (list.length === 2) {
1855
+ this._socket.cork();
1856
+ this._socket.write(list[0]);
1857
+ this._socket.write(list[1], cb);
1858
+ this._socket.uncork();
1859
+ } else {
1860
+ this._socket.write(list[0], cb);
1861
+ }
1862
+ }
1863
+ };
1864
+ module2.exports = Sender2;
1865
+ function callCallbacks(sender, err, cb) {
1866
+ if (typeof cb === "function") cb(err);
1867
+ for (let i = 0; i < sender._queue.length; i++) {
1868
+ const params = sender._queue[i];
1869
+ const callback = params[params.length - 1];
1870
+ if (typeof callback === "function") callback(err);
1871
+ }
1872
+ }
1873
+ function onError(sender, err, cb) {
1874
+ callCallbacks(sender, err, cb);
1875
+ sender.onerror(err);
1876
+ }
1877
+ }
1878
+ });
1879
+
1880
+ // apps/daemon/node_modules/ws/lib/event-target.js
1881
+ var require_event_target = __commonJS({
1882
+ "apps/daemon/node_modules/ws/lib/event-target.js"(exports2, module2) {
1883
+ "use strict";
1884
+ var { kForOnEventAttribute, kListener } = require_constants();
1885
+ var kCode = /* @__PURE__ */ Symbol("kCode");
1886
+ var kData = /* @__PURE__ */ Symbol("kData");
1887
+ var kError = /* @__PURE__ */ Symbol("kError");
1888
+ var kMessage = /* @__PURE__ */ Symbol("kMessage");
1889
+ var kReason = /* @__PURE__ */ Symbol("kReason");
1890
+ var kTarget = /* @__PURE__ */ Symbol("kTarget");
1891
+ var kType = /* @__PURE__ */ Symbol("kType");
1892
+ var kWasClean = /* @__PURE__ */ Symbol("kWasClean");
1893
+ var Event = class {
1894
+ /**
1895
+ * Create a new `Event`.
1896
+ *
1897
+ * @param {String} type The name of the event
1898
+ * @throws {TypeError} If the `type` argument is not specified
1899
+ */
1900
+ constructor(type) {
1901
+ this[kTarget] = null;
1902
+ this[kType] = type;
1903
+ }
1904
+ /**
1905
+ * @type {*}
1906
+ */
1907
+ get target() {
1908
+ return this[kTarget];
1909
+ }
1910
+ /**
1911
+ * @type {String}
1912
+ */
1913
+ get type() {
1914
+ return this[kType];
1915
+ }
1916
+ };
1917
+ Object.defineProperty(Event.prototype, "target", { enumerable: true });
1918
+ Object.defineProperty(Event.prototype, "type", { enumerable: true });
1919
+ var CloseEvent = class extends Event {
1920
+ /**
1921
+ * Create a new `CloseEvent`.
1922
+ *
1923
+ * @param {String} type The name of the event
1924
+ * @param {Object} [options] A dictionary object that allows for setting
1925
+ * attributes via object members of the same name
1926
+ * @param {Number} [options.code=0] The status code explaining why the
1927
+ * connection was closed
1928
+ * @param {String} [options.reason=''] A human-readable string explaining why
1929
+ * the connection was closed
1930
+ * @param {Boolean} [options.wasClean=false] Indicates whether or not the
1931
+ * connection was cleanly closed
1932
+ */
1933
+ constructor(type, options = {}) {
1934
+ super(type);
1935
+ this[kCode] = options.code === void 0 ? 0 : options.code;
1936
+ this[kReason] = options.reason === void 0 ? "" : options.reason;
1937
+ this[kWasClean] = options.wasClean === void 0 ? false : options.wasClean;
1938
+ }
1939
+ /**
1940
+ * @type {Number}
1941
+ */
1942
+ get code() {
1943
+ return this[kCode];
1944
+ }
1945
+ /**
1946
+ * @type {String}
1947
+ */
1948
+ get reason() {
1949
+ return this[kReason];
1950
+ }
1951
+ /**
1952
+ * @type {Boolean}
1953
+ */
1954
+ get wasClean() {
1955
+ return this[kWasClean];
1956
+ }
1957
+ };
1958
+ Object.defineProperty(CloseEvent.prototype, "code", { enumerable: true });
1959
+ Object.defineProperty(CloseEvent.prototype, "reason", { enumerable: true });
1960
+ Object.defineProperty(CloseEvent.prototype, "wasClean", { enumerable: true });
1961
+ var ErrorEvent = class extends Event {
1962
+ /**
1963
+ * Create a new `ErrorEvent`.
1964
+ *
1965
+ * @param {String} type The name of the event
1966
+ * @param {Object} [options] A dictionary object that allows for setting
1967
+ * attributes via object members of the same name
1968
+ * @param {*} [options.error=null] The error that generated this event
1969
+ * @param {String} [options.message=''] The error message
1970
+ */
1971
+ constructor(type, options = {}) {
1972
+ super(type);
1973
+ this[kError] = options.error === void 0 ? null : options.error;
1974
+ this[kMessage] = options.message === void 0 ? "" : options.message;
1975
+ }
1976
+ /**
1977
+ * @type {*}
1978
+ */
1979
+ get error() {
1980
+ return this[kError];
1981
+ }
1982
+ /**
1983
+ * @type {String}
1984
+ */
1985
+ get message() {
1986
+ return this[kMessage];
1987
+ }
1988
+ };
1989
+ Object.defineProperty(ErrorEvent.prototype, "error", { enumerable: true });
1990
+ Object.defineProperty(ErrorEvent.prototype, "message", { enumerable: true });
1991
+ var MessageEvent = class extends Event {
1992
+ /**
1993
+ * Create a new `MessageEvent`.
1994
+ *
1995
+ * @param {String} type The name of the event
1996
+ * @param {Object} [options] A dictionary object that allows for setting
1997
+ * attributes via object members of the same name
1998
+ * @param {*} [options.data=null] The message content
1999
+ */
2000
+ constructor(type, options = {}) {
2001
+ super(type);
2002
+ this[kData] = options.data === void 0 ? null : options.data;
2003
+ }
2004
+ /**
2005
+ * @type {*}
2006
+ */
2007
+ get data() {
2008
+ return this[kData];
2009
+ }
2010
+ };
2011
+ Object.defineProperty(MessageEvent.prototype, "data", { enumerable: true });
2012
+ var EventTarget = {
2013
+ /**
2014
+ * Register an event listener.
2015
+ *
2016
+ * @param {String} type A string representing the event type to listen for
2017
+ * @param {(Function|Object)} handler The listener to add
2018
+ * @param {Object} [options] An options object specifies characteristics about
2019
+ * the event listener
2020
+ * @param {Boolean} [options.once=false] A `Boolean` indicating that the
2021
+ * listener should be invoked at most once after being added. If `true`,
2022
+ * the listener would be automatically removed when invoked.
2023
+ * @public
2024
+ */
2025
+ addEventListener(type, handler, options = {}) {
2026
+ for (const listener of this.listeners(type)) {
2027
+ if (!options[kForOnEventAttribute] && listener[kListener] === handler && !listener[kForOnEventAttribute]) {
2028
+ return;
2029
+ }
2030
+ }
2031
+ let wrapper;
2032
+ if (type === "message") {
2033
+ wrapper = function onMessage(data, isBinary) {
2034
+ const event = new MessageEvent("message", {
2035
+ data: isBinary ? data : data.toString()
2036
+ });
2037
+ event[kTarget] = this;
2038
+ callListener(handler, this, event);
2039
+ };
2040
+ } else if (type === "close") {
2041
+ wrapper = function onClose(code, message) {
2042
+ const event = new CloseEvent("close", {
2043
+ code,
2044
+ reason: message.toString(),
2045
+ wasClean: this._closeFrameReceived && this._closeFrameSent
2046
+ });
2047
+ event[kTarget] = this;
2048
+ callListener(handler, this, event);
2049
+ };
2050
+ } else if (type === "error") {
2051
+ wrapper = function onError(error) {
2052
+ const event = new ErrorEvent("error", {
2053
+ error,
2054
+ message: error.message
2055
+ });
2056
+ event[kTarget] = this;
2057
+ callListener(handler, this, event);
2058
+ };
2059
+ } else if (type === "open") {
2060
+ wrapper = function onOpen() {
2061
+ const event = new Event("open");
2062
+ event[kTarget] = this;
2063
+ callListener(handler, this, event);
2064
+ };
2065
+ } else {
2066
+ return;
2067
+ }
2068
+ wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute];
2069
+ wrapper[kListener] = handler;
2070
+ if (options.once) {
2071
+ this.once(type, wrapper);
2072
+ } else {
2073
+ this.on(type, wrapper);
2074
+ }
2075
+ },
2076
+ /**
2077
+ * Remove an event listener.
2078
+ *
2079
+ * @param {String} type A string representing the event type to remove
2080
+ * @param {(Function|Object)} handler The listener to remove
2081
+ * @public
2082
+ */
2083
+ removeEventListener(type, handler) {
2084
+ for (const listener of this.listeners(type)) {
2085
+ if (listener[kListener] === handler && !listener[kForOnEventAttribute]) {
2086
+ this.removeListener(type, listener);
2087
+ break;
2088
+ }
2089
+ }
2090
+ }
2091
+ };
2092
+ module2.exports = {
2093
+ CloseEvent,
2094
+ ErrorEvent,
2095
+ Event,
2096
+ EventTarget,
2097
+ MessageEvent
2098
+ };
2099
+ function callListener(listener, thisArg, event) {
2100
+ if (typeof listener === "object" && listener.handleEvent) {
2101
+ listener.handleEvent.call(listener, event);
2102
+ } else {
2103
+ listener.call(thisArg, event);
2104
+ }
2105
+ }
2106
+ }
2107
+ });
2108
+
2109
+ // apps/daemon/node_modules/ws/lib/extension.js
2110
+ var require_extension = __commonJS({
2111
+ "apps/daemon/node_modules/ws/lib/extension.js"(exports2, module2) {
2112
+ "use strict";
2113
+ var { tokenChars } = require_validation();
2114
+ function push(dest, name, elem) {
2115
+ if (dest[name] === void 0) dest[name] = [elem];
2116
+ else dest[name].push(elem);
2117
+ }
2118
+ function parse(header) {
2119
+ const offers = /* @__PURE__ */ Object.create(null);
2120
+ let params = /* @__PURE__ */ Object.create(null);
2121
+ let mustUnescape = false;
2122
+ let isEscaping = false;
2123
+ let inQuotes = false;
2124
+ let extensionName;
2125
+ let paramName;
2126
+ let start = -1;
2127
+ let code = -1;
2128
+ let end = -1;
2129
+ let i = 0;
2130
+ for (; i < header.length; i++) {
2131
+ code = header.charCodeAt(i);
2132
+ if (extensionName === void 0) {
2133
+ if (end === -1 && tokenChars[code] === 1) {
2134
+ if (start === -1) start = i;
2135
+ } else if (i !== 0 && (code === 32 || code === 9)) {
2136
+ if (end === -1 && start !== -1) end = i;
2137
+ } else if (code === 59 || code === 44) {
2138
+ if (start === -1) {
2139
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2140
+ }
2141
+ if (end === -1) end = i;
2142
+ const name = header.slice(start, end);
2143
+ if (code === 44) {
2144
+ push(offers, name, params);
2145
+ params = /* @__PURE__ */ Object.create(null);
2146
+ } else {
2147
+ extensionName = name;
2148
+ }
2149
+ start = end = -1;
2150
+ } else {
2151
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2152
+ }
2153
+ } else if (paramName === void 0) {
2154
+ if (end === -1 && tokenChars[code] === 1) {
2155
+ if (start === -1) start = i;
2156
+ } else if (code === 32 || code === 9) {
2157
+ if (end === -1 && start !== -1) end = i;
2158
+ } else if (code === 59 || code === 44) {
2159
+ if (start === -1) {
2160
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2161
+ }
2162
+ if (end === -1) end = i;
2163
+ push(params, header.slice(start, end), true);
2164
+ if (code === 44) {
2165
+ push(offers, extensionName, params);
2166
+ params = /* @__PURE__ */ Object.create(null);
2167
+ extensionName = void 0;
2168
+ }
2169
+ start = end = -1;
2170
+ } else if (code === 61 && start !== -1 && end === -1) {
2171
+ paramName = header.slice(start, i);
2172
+ start = end = -1;
2173
+ } else {
2174
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2175
+ }
2176
+ } else {
2177
+ if (isEscaping) {
2178
+ if (tokenChars[code] !== 1) {
2179
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2180
+ }
2181
+ if (start === -1) start = i;
2182
+ else if (!mustUnescape) mustUnescape = true;
2183
+ isEscaping = false;
2184
+ } else if (inQuotes) {
2185
+ if (tokenChars[code] === 1) {
2186
+ if (start === -1) start = i;
2187
+ } else if (code === 34 && start !== -1) {
2188
+ inQuotes = false;
2189
+ end = i;
2190
+ } else if (code === 92) {
2191
+ isEscaping = true;
2192
+ } else {
2193
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2194
+ }
2195
+ } else if (code === 34 && header.charCodeAt(i - 1) === 61) {
2196
+ inQuotes = true;
2197
+ } else if (end === -1 && tokenChars[code] === 1) {
2198
+ if (start === -1) start = i;
2199
+ } else if (start !== -1 && (code === 32 || code === 9)) {
2200
+ if (end === -1) end = i;
2201
+ } else if (code === 59 || code === 44) {
2202
+ if (start === -1) {
2203
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2204
+ }
2205
+ if (end === -1) end = i;
2206
+ let value = header.slice(start, end);
2207
+ if (mustUnescape) {
2208
+ value = value.replace(/\\/g, "");
2209
+ mustUnescape = false;
2210
+ }
2211
+ push(params, paramName, value);
2212
+ if (code === 44) {
2213
+ push(offers, extensionName, params);
2214
+ params = /* @__PURE__ */ Object.create(null);
2215
+ extensionName = void 0;
2216
+ }
2217
+ paramName = void 0;
2218
+ start = end = -1;
2219
+ } else {
2220
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2221
+ }
2222
+ }
2223
+ }
2224
+ if (start === -1 || inQuotes || code === 32 || code === 9) {
2225
+ throw new SyntaxError("Unexpected end of input");
2226
+ }
2227
+ if (end === -1) end = i;
2228
+ const token2 = header.slice(start, end);
2229
+ if (extensionName === void 0) {
2230
+ push(offers, token2, params);
2231
+ } else {
2232
+ if (paramName === void 0) {
2233
+ push(params, token2, true);
2234
+ } else if (mustUnescape) {
2235
+ push(params, paramName, token2.replace(/\\/g, ""));
2236
+ } else {
2237
+ push(params, paramName, token2);
2238
+ }
2239
+ push(offers, extensionName, params);
2240
+ }
2241
+ return offers;
2242
+ }
2243
+ function format(extensions) {
2244
+ return Object.keys(extensions).map((extension2) => {
2245
+ let configurations = extensions[extension2];
2246
+ if (!Array.isArray(configurations)) configurations = [configurations];
2247
+ return configurations.map((params) => {
2248
+ return [extension2].concat(
2249
+ Object.keys(params).map((k) => {
2250
+ let values = params[k];
2251
+ if (!Array.isArray(values)) values = [values];
2252
+ return values.map((v) => v === true ? k : `${k}=${v}`).join("; ");
2253
+ })
2254
+ ).join("; ");
2255
+ }).join(", ");
2256
+ }).join(", ");
2257
+ }
2258
+ module2.exports = { format, parse };
2259
+ }
2260
+ });
2261
+
2262
+ // apps/daemon/node_modules/ws/lib/websocket.js
2263
+ var require_websocket = __commonJS({
2264
+ "apps/daemon/node_modules/ws/lib/websocket.js"(exports2, module2) {
2265
+ "use strict";
2266
+ var EventEmitter = require("events");
2267
+ var https = require("https");
2268
+ var http = require("http");
2269
+ var net = require("net");
2270
+ var tls = require("tls");
2271
+ var { randomBytes: randomBytes2, createHash } = require("crypto");
2272
+ var { Duplex, Readable } = require("stream");
2273
+ var { URL } = require("url");
2274
+ var PerMessageDeflate2 = require_permessage_deflate();
2275
+ var Receiver2 = require_receiver();
2276
+ var Sender2 = require_sender();
2277
+ var { isBlob } = require_validation();
2278
+ var {
2279
+ BINARY_TYPES,
2280
+ CLOSE_TIMEOUT,
2281
+ EMPTY_BUFFER,
2282
+ GUID,
2283
+ kForOnEventAttribute,
2284
+ kListener,
2285
+ kStatusCode,
2286
+ kWebSocket,
2287
+ NOOP
2288
+ } = require_constants();
2289
+ var {
2290
+ EventTarget: { addEventListener, removeEventListener }
2291
+ } = require_event_target();
2292
+ var { format, parse } = require_extension();
2293
+ var { toBuffer } = require_buffer_util();
2294
+ var kAborted = /* @__PURE__ */ Symbol("kAborted");
2295
+ var protocolVersions = [8, 13];
2296
+ var readyStates = ["CONNECTING", "OPEN", "CLOSING", "CLOSED"];
2297
+ var subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;
2298
+ var WebSocket2 = class _WebSocket extends EventEmitter {
2299
+ /**
2300
+ * Create a new `WebSocket`.
2301
+ *
2302
+ * @param {(String|URL)} address The URL to which to connect
2303
+ * @param {(String|String[])} [protocols] The subprotocols
2304
+ * @param {Object} [options] Connection options
2305
+ */
2306
+ constructor(address, protocols, options) {
2307
+ super();
2308
+ this._binaryType = BINARY_TYPES[0];
2309
+ this._closeCode = 1006;
2310
+ this._closeFrameReceived = false;
2311
+ this._closeFrameSent = false;
2312
+ this._closeMessage = EMPTY_BUFFER;
2313
+ this._closeTimer = null;
2314
+ this._errorEmitted = false;
2315
+ this._extensions = {};
2316
+ this._paused = false;
2317
+ this._protocol = "";
2318
+ this._readyState = _WebSocket.CONNECTING;
2319
+ this._receiver = null;
2320
+ this._sender = null;
2321
+ this._socket = null;
2322
+ if (address !== null) {
2323
+ this._bufferedAmount = 0;
2324
+ this._isServer = false;
2325
+ this._redirects = 0;
2326
+ if (protocols === void 0) {
2327
+ if (!options || options.protocols === void 0) {
2328
+ protocols = [];
2329
+ } else if (Array.isArray(options.protocols)) {
2330
+ protocols = options.protocols;
2331
+ } else {
2332
+ protocols = [options.protocols];
2333
+ }
2334
+ } else if (!Array.isArray(protocols)) {
2335
+ if (typeof protocols === "object" && protocols !== null) {
2336
+ options = protocols;
2337
+ if (options.protocols === void 0) {
2338
+ protocols = [];
2339
+ } else if (Array.isArray(options.protocols)) {
2340
+ protocols = options.protocols;
2341
+ } else {
2342
+ protocols = [options.protocols];
2343
+ }
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._sender.close(code, data, !this._isServer, (err) => {
2541
+ if (err) return;
2542
+ this._closeFrameSent = true;
2543
+ if (this._closeFrameReceived || this._receiver._writableState.errorEmitted) {
2544
+ this._socket.end();
2545
+ }
2546
+ });
2547
+ this._readyState = _WebSocket.CLOSING;
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
+ module2.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: 256 * 1024,
2762
+ maxFragments: 16 * 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
+ protocols: void 0,
2773
+ timeout: void 0,
2774
+ method: "GET",
2775
+ host: void 0,
2776
+ path: void 0,
2777
+ port: void 0
2778
+ };
2779
+ websocket._autoPong = opts.autoPong;
2780
+ websocket._closeTimeout = opts.closeTimeout;
2781
+ if (!protocolVersions.includes(opts.protocolVersion)) {
2782
+ throw new RangeError(
2783
+ `Unsupported protocol version: ${opts.protocolVersion} (supported versions: ${protocolVersions.join(", ")})`
2784
+ );
2785
+ }
2786
+ let parsedUrl;
2787
+ if (address instanceof URL) {
2788
+ parsedUrl = address;
2789
+ } else {
2790
+ try {
2791
+ parsedUrl = new URL(address);
2792
+ } catch {
2793
+ throw new SyntaxError(`Invalid URL: ${address}`);
2794
+ }
2795
+ }
2796
+ if (parsedUrl.protocol === "http:") {
2797
+ parsedUrl.protocol = "ws:";
2798
+ } else if (parsedUrl.protocol === "https:") {
2799
+ parsedUrl.protocol = "wss:";
2800
+ }
2801
+ websocket._url = parsedUrl.href;
2802
+ const isSecure = parsedUrl.protocol === "wss:";
2803
+ const isIpcUrl = parsedUrl.protocol === "ws+unix:";
2804
+ let invalidUrlMessage;
2805
+ if (parsedUrl.protocol !== "ws:" && !isSecure && !isIpcUrl) {
2806
+ invalidUrlMessage = `The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`;
2807
+ } else if (isIpcUrl && !parsedUrl.pathname) {
2808
+ invalidUrlMessage = "The URL's pathname is empty";
2809
+ } else if (parsedUrl.hash) {
2810
+ invalidUrlMessage = "The URL contains a fragment identifier";
2811
+ }
2812
+ if (invalidUrlMessage) {
2813
+ const err = new SyntaxError(invalidUrlMessage);
2814
+ if (websocket._redirects === 0) {
2815
+ throw err;
2816
+ } else {
2817
+ emitErrorAndClose(websocket, err);
2818
+ return;
2819
+ }
2820
+ }
2821
+ const defaultPort = isSecure ? 443 : 80;
2822
+ const key = randomBytes2(16).toString("base64");
2823
+ const request = isSecure ? https.request : http.request;
2824
+ const protocolSet = /* @__PURE__ */ new Set();
2825
+ let perMessageDeflate;
2826
+ opts.createConnection = opts.createConnection || (isSecure ? tlsConnect : netConnect);
2827
+ opts.defaultPort = opts.defaultPort || defaultPort;
2828
+ opts.port = parsedUrl.port || defaultPort;
2829
+ opts.host = parsedUrl.hostname.startsWith("[") ? parsedUrl.hostname.slice(1, -1) : parsedUrl.hostname;
2830
+ opts.headers = {
2831
+ ...opts.headers,
2832
+ "Sec-WebSocket-Version": opts.protocolVersion,
2833
+ "Sec-WebSocket-Key": key,
2834
+ Connection: "Upgrade",
2835
+ Upgrade: "websocket"
2836
+ };
2837
+ opts.path = parsedUrl.pathname + parsedUrl.search;
2838
+ opts.timeout = opts.handshakeTimeout;
2839
+ if (opts.perMessageDeflate) {
2840
+ perMessageDeflate = new PerMessageDeflate2({
2841
+ ...opts.perMessageDeflate,
2842
+ isServer: false,
2843
+ maxPayload: opts.maxPayload
2844
+ });
2845
+ opts.headers["Sec-WebSocket-Extensions"] = format({
2846
+ [PerMessageDeflate2.extensionName]: perMessageDeflate.offer()
2847
+ });
2848
+ }
2849
+ if (protocols.length) {
2850
+ for (const protocol of protocols) {
2851
+ if (typeof protocol !== "string" || !subprotocolRegex.test(protocol) || protocolSet.has(protocol)) {
2852
+ throw new SyntaxError(
2853
+ "An invalid or duplicated subprotocol was specified"
2854
+ );
2855
+ }
2856
+ protocolSet.add(protocol);
2857
+ }
2858
+ opts.headers["Sec-WebSocket-Protocol"] = protocols.join(",");
2859
+ }
2860
+ if (opts.origin) {
2861
+ if (opts.protocolVersion < 13) {
2862
+ opts.headers["Sec-WebSocket-Origin"] = opts.origin;
2863
+ } else {
2864
+ opts.headers.Origin = opts.origin;
2865
+ }
2866
+ }
2867
+ if (parsedUrl.username || parsedUrl.password) {
2868
+ opts.auth = `${parsedUrl.username}:${parsedUrl.password}`;
2869
+ }
2870
+ if (isIpcUrl) {
2871
+ const parts = opts.path.split(":");
2872
+ opts.socketPath = parts[0];
2873
+ opts.path = parts[1];
2874
+ }
2875
+ let req;
2876
+ if (opts.followRedirects) {
2877
+ if (websocket._redirects === 0) {
2878
+ websocket._originalIpc = isIpcUrl;
2879
+ websocket._originalSecure = isSecure;
2880
+ websocket._originalHostOrSocketPath = isIpcUrl ? opts.socketPath : parsedUrl.host;
2881
+ const headers = options && options.headers;
2882
+ options = { ...options, headers: {} };
2883
+ if (headers) {
2884
+ for (const [key2, value] of Object.entries(headers)) {
2885
+ options.headers[key2.toLowerCase()] = value;
2886
+ }
2887
+ }
2888
+ } else if (websocket.listenerCount("redirect") === 0) {
2889
+ const isSameHost = isIpcUrl ? websocket._originalIpc ? opts.socketPath === websocket._originalHostOrSocketPath : false : websocket._originalIpc ? false : parsedUrl.host === websocket._originalHostOrSocketPath;
2890
+ if (!isSameHost || websocket._originalSecure && !isSecure) {
2891
+ delete opts.headers.authorization;
2892
+ delete opts.headers.cookie;
2893
+ if (!isSameHost) delete opts.headers.host;
2894
+ opts.auth = void 0;
2895
+ }
2896
+ }
2897
+ if (opts.auth && !options.headers.authorization) {
2898
+ options.headers.authorization = "Basic " + Buffer.from(opts.auth).toString("base64");
2899
+ }
2900
+ req = websocket._req = request(opts);
2901
+ if (websocket._redirects) {
2902
+ websocket.emit("redirect", websocket.url, req);
2903
+ }
2904
+ } else {
2905
+ req = websocket._req = request(opts);
2906
+ }
2907
+ if (opts.timeout) {
2908
+ req.on("timeout", () => {
2909
+ abortHandshake(websocket, req, "Opening handshake has timed out");
2910
+ });
2911
+ }
2912
+ req.on("error", (err) => {
2913
+ if (req === null || req[kAborted]) return;
2914
+ req = websocket._req = null;
2915
+ emitErrorAndClose(websocket, err);
2916
+ });
2917
+ req.on("response", (res) => {
2918
+ const location = res.headers.location;
2919
+ const statusCode = res.statusCode;
2920
+ if (location && opts.followRedirects && statusCode >= 300 && statusCode < 400) {
2921
+ if (++websocket._redirects > opts.maxRedirects) {
2922
+ abortHandshake(websocket, req, "Maximum redirects exceeded");
2923
+ return;
2924
+ }
2925
+ req.abort();
2926
+ let addr;
2927
+ try {
2928
+ addr = new URL(location, address);
2929
+ } catch (e) {
2930
+ const err = new SyntaxError(`Invalid URL: ${location}`);
2931
+ emitErrorAndClose(websocket, err);
2932
+ return;
2933
+ }
2934
+ initAsClient(websocket, addr, protocols, options);
2935
+ } else if (!websocket.emit("unexpected-response", req, res)) {
2936
+ abortHandshake(
2937
+ websocket,
2938
+ req,
2939
+ `Unexpected server response: ${res.statusCode}`
2940
+ );
2941
+ }
2942
+ });
2943
+ req.on("upgrade", (res, socket, head) => {
2944
+ websocket.emit("upgrade", res);
2945
+ if (websocket.readyState !== WebSocket2.CONNECTING) return;
2946
+ req = websocket._req = null;
2947
+ const upgrade = res.headers.upgrade;
2948
+ if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") {
2949
+ abortHandshake(websocket, socket, "Invalid Upgrade header");
2950
+ return;
2951
+ }
2952
+ const digest = createHash("sha1").update(key + GUID).digest("base64");
2953
+ if (res.headers["sec-websocket-accept"] !== digest) {
2954
+ abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
2955
+ return;
2956
+ }
2957
+ const serverProt = res.headers["sec-websocket-protocol"];
2958
+ let protError;
2959
+ if (serverProt !== void 0) {
2960
+ if (!protocolSet.size) {
2961
+ protError = "Server sent a subprotocol but none was requested";
2962
+ } else if (!protocolSet.has(serverProt)) {
2963
+ protError = "Server sent an invalid subprotocol";
2964
+ }
2965
+ } else if (protocolSet.size) {
2966
+ protError = "Server sent no subprotocol";
2967
+ }
2968
+ if (protError) {
2969
+ abortHandshake(websocket, socket, protError);
2970
+ return;
2971
+ }
2972
+ if (serverProt) websocket._protocol = serverProt;
2973
+ const secWebSocketExtensions = res.headers["sec-websocket-extensions"];
2974
+ if (secWebSocketExtensions !== void 0) {
2975
+ if (!perMessageDeflate) {
2976
+ const message = "Server sent a Sec-WebSocket-Extensions header but no extension was requested";
2977
+ abortHandshake(websocket, socket, message);
2978
+ return;
2979
+ }
2980
+ let extensions;
2981
+ try {
2982
+ extensions = parse(secWebSocketExtensions);
2983
+ } catch (err) {
2984
+ const message = "Invalid Sec-WebSocket-Extensions header";
2985
+ abortHandshake(websocket, socket, message);
2986
+ return;
2987
+ }
2988
+ const extensionNames = Object.keys(extensions);
2989
+ if (extensionNames.length !== 1 || extensionNames[0] !== PerMessageDeflate2.extensionName) {
2990
+ const message = "Server indicated an extension that was not requested";
2991
+ abortHandshake(websocket, socket, message);
2992
+ return;
2993
+ }
2994
+ try {
2995
+ perMessageDeflate.accept(extensions[PerMessageDeflate2.extensionName]);
2996
+ } catch (err) {
2997
+ const message = "Invalid Sec-WebSocket-Extensions header";
2998
+ abortHandshake(websocket, socket, message);
2999
+ return;
3000
+ }
3001
+ websocket._extensions[PerMessageDeflate2.extensionName] = perMessageDeflate;
3002
+ }
3003
+ websocket.setSocket(socket, head, {
3004
+ allowSynchronousEvents: opts.allowSynchronousEvents,
3005
+ generateMask: opts.generateMask,
3006
+ maxBufferedChunks: opts.maxBufferedChunks,
3007
+ maxFragments: opts.maxFragments,
3008
+ maxPayload: opts.maxPayload,
3009
+ skipUTF8Validation: opts.skipUTF8Validation
3010
+ });
3011
+ });
3012
+ if (opts.finishRequest) {
3013
+ opts.finishRequest(req, websocket);
3014
+ } else {
3015
+ req.end();
3016
+ }
3017
+ }
3018
+ function emitErrorAndClose(websocket, err) {
3019
+ websocket._readyState = WebSocket2.CLOSING;
3020
+ websocket._errorEmitted = true;
3021
+ websocket.emit("error", err);
3022
+ websocket.emitClose();
3023
+ }
3024
+ function netConnect(options) {
3025
+ options.path = options.socketPath;
3026
+ return net.connect(options);
3027
+ }
3028
+ function tlsConnect(options) {
3029
+ options.path = void 0;
3030
+ if (!options.servername && options.servername !== "") {
3031
+ options.servername = net.isIP(options.host) ? "" : options.host;
3032
+ }
3033
+ return tls.connect(options);
3034
+ }
3035
+ function abortHandshake(websocket, stream, message) {
3036
+ websocket._readyState = WebSocket2.CLOSING;
3037
+ const err = new Error(message);
3038
+ Error.captureStackTrace(err, abortHandshake);
3039
+ if (stream.setHeader) {
3040
+ stream[kAborted] = true;
3041
+ stream.abort();
3042
+ if (stream.socket && !stream.socket.destroyed) {
3043
+ stream.socket.destroy();
3044
+ }
3045
+ process.nextTick(emitErrorAndClose, websocket, err);
3046
+ } else {
3047
+ stream.destroy(err);
3048
+ stream.once("error", websocket.emit.bind(websocket, "error"));
3049
+ stream.once("close", websocket.emitClose.bind(websocket));
3050
+ }
3051
+ }
3052
+ function sendAfterClose(websocket, data, cb) {
3053
+ if (data) {
3054
+ const length = isBlob(data) ? data.size : toBuffer(data).length;
3055
+ if (websocket._socket) websocket._sender._bufferedBytes += length;
3056
+ else websocket._bufferedAmount += length;
3057
+ }
3058
+ if (cb) {
3059
+ const err = new Error(
3060
+ `WebSocket is not open: readyState ${websocket.readyState} (${readyStates[websocket.readyState]})`
3061
+ );
3062
+ process.nextTick(cb, err);
3063
+ }
3064
+ }
3065
+ function receiverOnConclude(code, reason) {
3066
+ const websocket = this[kWebSocket];
3067
+ websocket._closeFrameReceived = true;
3068
+ websocket._closeMessage = reason;
3069
+ websocket._closeCode = code;
3070
+ if (websocket._socket[kWebSocket] === void 0) return;
3071
+ websocket._socket.removeListener("data", socketOnData);
3072
+ process.nextTick(resume, websocket._socket);
3073
+ if (code === 1005) websocket.close();
3074
+ else websocket.close(code, reason);
3075
+ }
3076
+ function receiverOnDrain() {
3077
+ const websocket = this[kWebSocket];
3078
+ if (!websocket.isPaused) websocket._socket.resume();
3079
+ }
3080
+ function receiverOnError(err) {
3081
+ const websocket = this[kWebSocket];
3082
+ if (websocket._socket[kWebSocket] !== void 0) {
3083
+ websocket._socket.removeListener("data", socketOnData);
3084
+ process.nextTick(resume, websocket._socket);
3085
+ websocket.close(err[kStatusCode]);
3086
+ }
3087
+ if (!websocket._errorEmitted) {
3088
+ websocket._errorEmitted = true;
3089
+ websocket.emit("error", err);
3090
+ }
3091
+ }
3092
+ function receiverOnFinish() {
3093
+ this[kWebSocket].emitClose();
3094
+ }
3095
+ function receiverOnMessage(data, isBinary) {
3096
+ this[kWebSocket].emit("message", data, isBinary);
3097
+ }
3098
+ function receiverOnPing(data) {
3099
+ const websocket = this[kWebSocket];
3100
+ if (websocket._autoPong) websocket.pong(data, !this._isServer, NOOP);
3101
+ websocket.emit("ping", data);
3102
+ }
3103
+ function receiverOnPong(data) {
3104
+ this[kWebSocket].emit("pong", data);
3105
+ }
3106
+ function resume(stream) {
3107
+ stream.resume();
3108
+ }
3109
+ function senderOnError(err) {
3110
+ const websocket = this[kWebSocket];
3111
+ if (websocket.readyState === WebSocket2.CLOSED) return;
3112
+ if (websocket.readyState === WebSocket2.OPEN) {
3113
+ websocket._readyState = WebSocket2.CLOSING;
3114
+ setCloseTimer(websocket);
3115
+ }
3116
+ this._socket.end();
3117
+ if (!websocket._errorEmitted) {
3118
+ websocket._errorEmitted = true;
3119
+ websocket.emit("error", err);
3120
+ }
3121
+ }
3122
+ function setCloseTimer(websocket) {
3123
+ websocket._closeTimer = setTimeout(
3124
+ websocket._socket.destroy.bind(websocket._socket),
3125
+ websocket._closeTimeout
3126
+ );
3127
+ }
3128
+ function socketOnClose() {
3129
+ const websocket = this[kWebSocket];
3130
+ this.removeListener("close", socketOnClose);
3131
+ this.removeListener("data", socketOnData);
3132
+ this.removeListener("end", socketOnEnd);
3133
+ websocket._readyState = WebSocket2.CLOSING;
3134
+ if (!this._readableState.endEmitted && !websocket._closeFrameReceived && !websocket._receiver._writableState.errorEmitted && this._readableState.length !== 0) {
3135
+ const chunk = this.read(this._readableState.length);
3136
+ websocket._receiver.write(chunk);
3137
+ }
3138
+ websocket._receiver.end();
3139
+ this[kWebSocket] = void 0;
3140
+ clearTimeout(websocket._closeTimer);
3141
+ if (websocket._receiver._writableState.finished || websocket._receiver._writableState.errorEmitted) {
3142
+ websocket.emitClose();
3143
+ } else {
3144
+ websocket._receiver.on("error", receiverOnFinish);
3145
+ websocket._receiver.on("finish", receiverOnFinish);
3146
+ }
3147
+ }
3148
+ function socketOnData(chunk) {
3149
+ if (!this[kWebSocket]._receiver.write(chunk)) {
3150
+ this.pause();
3151
+ }
3152
+ }
3153
+ function socketOnEnd() {
3154
+ const websocket = this[kWebSocket];
3155
+ websocket._readyState = WebSocket2.CLOSING;
3156
+ websocket._receiver.end();
3157
+ this.end();
3158
+ }
3159
+ function socketOnError() {
3160
+ const websocket = this[kWebSocket];
3161
+ this.removeListener("error", socketOnError);
3162
+ this.on("error", NOOP);
3163
+ if (websocket) {
3164
+ websocket._readyState = WebSocket2.CLOSING;
3165
+ this.destroy();
3166
+ }
3167
+ }
3168
+ }
3169
+ });
3170
+
3171
+ // apps/daemon/node_modules/ws/lib/stream.js
3172
+ var require_stream = __commonJS({
3173
+ "apps/daemon/node_modules/ws/lib/stream.js"(exports2, module2) {
3174
+ "use strict";
3175
+ var WebSocket2 = require_websocket();
3176
+ var { Duplex } = require("stream");
3177
+ function emitClose(stream) {
3178
+ stream.emit("close");
3179
+ }
3180
+ function duplexOnEnd() {
3181
+ if (!this.destroyed && this._writableState.finished) {
3182
+ this.destroy();
3183
+ }
3184
+ }
3185
+ function duplexOnError(err) {
3186
+ this.removeListener("error", duplexOnError);
3187
+ this.destroy();
3188
+ if (this.listenerCount("error") === 0) {
3189
+ this.emit("error", err);
3190
+ }
3191
+ }
3192
+ function createWebSocketStream2(ws, options) {
3193
+ let terminateOnDestroy = true;
3194
+ const duplex = new Duplex({
3195
+ ...options,
3196
+ autoDestroy: false,
3197
+ emitClose: false,
3198
+ objectMode: false,
3199
+ writableObjectMode: false
3200
+ });
3201
+ ws.on("message", function message(msg, isBinary) {
3202
+ const data = !isBinary && duplex._readableState.objectMode ? msg.toString() : msg;
3203
+ if (!duplex.push(data)) ws.pause();
3204
+ });
3205
+ ws.once("error", function error(err) {
3206
+ if (duplex.destroyed) return;
3207
+ terminateOnDestroy = false;
3208
+ duplex.destroy(err);
3209
+ });
3210
+ ws.once("close", function close() {
3211
+ if (duplex.destroyed) return;
3212
+ duplex.push(null);
3213
+ });
3214
+ duplex._destroy = function(err, callback) {
3215
+ if (ws.readyState === ws.CLOSED) {
3216
+ callback(err);
3217
+ process.nextTick(emitClose, duplex);
3218
+ return;
3219
+ }
3220
+ let called = false;
3221
+ ws.once("error", function error(err2) {
3222
+ called = true;
3223
+ callback(err2);
3224
+ });
3225
+ ws.once("close", function close() {
3226
+ if (!called) callback(err);
3227
+ process.nextTick(emitClose, duplex);
3228
+ });
3229
+ if (terminateOnDestroy) ws.terminate();
3230
+ };
3231
+ duplex._final = function(callback) {
3232
+ if (ws.readyState === ws.CONNECTING) {
3233
+ ws.once("open", function open() {
3234
+ duplex._final(callback);
3235
+ });
3236
+ return;
3237
+ }
3238
+ if (ws._socket === null) return;
3239
+ if (ws._socket._writableState.finished) {
3240
+ callback();
3241
+ if (duplex._readableState.endEmitted) duplex.destroy();
3242
+ } else {
3243
+ ws._socket.once("finish", function finish() {
3244
+ callback();
3245
+ });
3246
+ ws.close();
3247
+ }
3248
+ };
3249
+ duplex._read = function() {
3250
+ if (ws.isPaused) ws.resume();
3251
+ };
3252
+ duplex._write = function(chunk, encoding, callback) {
3253
+ if (ws.readyState === ws.CONNECTING) {
3254
+ ws.once("open", function open() {
3255
+ duplex._write(chunk, encoding, callback);
3256
+ });
3257
+ return;
3258
+ }
3259
+ ws.send(chunk, callback);
3260
+ };
3261
+ duplex.on("end", duplexOnEnd);
3262
+ duplex.on("error", duplexOnError);
3263
+ return duplex;
3264
+ }
3265
+ module2.exports = createWebSocketStream2;
3266
+ }
3267
+ });
3268
+
3269
+ // apps/daemon/node_modules/ws/lib/subprotocol.js
3270
+ var require_subprotocol = __commonJS({
3271
+ "apps/daemon/node_modules/ws/lib/subprotocol.js"(exports2, module2) {
3272
+ "use strict";
3273
+ var { tokenChars } = require_validation();
3274
+ function parse(header) {
3275
+ const protocols = /* @__PURE__ */ new Set();
3276
+ let start = -1;
3277
+ let end = -1;
3278
+ let i = 0;
3279
+ for (i; i < header.length; i++) {
3280
+ const code = header.charCodeAt(i);
3281
+ if (end === -1 && tokenChars[code] === 1) {
3282
+ if (start === -1) start = i;
3283
+ } else if (i !== 0 && (code === 32 || code === 9)) {
3284
+ if (end === -1 && start !== -1) end = i;
3285
+ } else if (code === 44) {
3286
+ if (start === -1) {
3287
+ throw new SyntaxError(`Unexpected character at index ${i}`);
3288
+ }
3289
+ if (end === -1) end = i;
3290
+ const protocol2 = header.slice(start, end);
3291
+ if (protocols.has(protocol2)) {
3292
+ throw new SyntaxError(`The "${protocol2}" subprotocol is duplicated`);
3293
+ }
3294
+ protocols.add(protocol2);
3295
+ start = end = -1;
3296
+ } else {
3297
+ throw new SyntaxError(`Unexpected character at index ${i}`);
3298
+ }
3299
+ }
3300
+ if (start === -1 || end !== -1) {
3301
+ throw new SyntaxError("Unexpected end of input");
3302
+ }
3303
+ const protocol = header.slice(start, i);
3304
+ if (protocols.has(protocol)) {
3305
+ throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);
3306
+ }
3307
+ protocols.add(protocol);
3308
+ return protocols;
3309
+ }
3310
+ module2.exports = { parse };
3311
+ }
3312
+ });
3313
+
3314
+ // apps/daemon/node_modules/ws/lib/websocket-server.js
3315
+ var require_websocket_server = __commonJS({
3316
+ "apps/daemon/node_modules/ws/lib/websocket-server.js"(exports2, module2) {
3317
+ "use strict";
3318
+ var EventEmitter = require("events");
3319
+ var http = require("http");
3320
+ var { Duplex } = require("stream");
3321
+ var { createHash } = require("crypto");
3322
+ var extension2 = require_extension();
3323
+ var PerMessageDeflate2 = require_permessage_deflate();
3324
+ var subprotocol2 = require_subprotocol();
3325
+ var WebSocket2 = require_websocket();
3326
+ var { CLOSE_TIMEOUT, GUID, kWebSocket } = require_constants();
3327
+ var keyRegex = /^[+/0-9A-Za-z]{22}==$/;
3328
+ var RUNNING = 0;
3329
+ var CLOSING = 1;
3330
+ var CLOSED = 2;
3331
+ var WebSocketServer2 = class extends EventEmitter {
3332
+ /**
3333
+ * Create a `WebSocketServer` instance.
3334
+ *
3335
+ * @param {Object} options Configuration options
3336
+ * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
3337
+ * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
3338
+ * multiple times in the same tick
3339
+ * @param {Boolean} [options.autoPong=true] Specifies whether or not to
3340
+ * automatically send a pong in response to a ping
3341
+ * @param {Number} [options.backlog=511] The maximum length of the queue of
3342
+ * pending connections
3343
+ * @param {Boolean} [options.clientTracking=true] Specifies whether or not to
3344
+ * track clients
3345
+ * @param {Number} [options.closeTimeout=30000] Duration in milliseconds to
3346
+ * wait for the closing handshake to finish after `websocket.close()` is
3347
+ * called
3348
+ * @param {Function} [options.handleProtocols] A hook to handle protocols
3349
+ * @param {String} [options.host] The hostname where to bind the server
3350
+ * @param {Number} [options.maxBufferedChunks=262144] The maximum number of
3351
+ * buffered data chunks
3352
+ * @param {Number} [options.maxFragments=16384] The maximum number of message
3353
+ * fragments
3354
+ * @param {Number} [options.maxPayload=104857600] The maximum allowed message
3355
+ * size
3356
+ * @param {Boolean} [options.noServer=false] Enable no server mode
3357
+ * @param {String} [options.path] Accept only connections matching this path
3358
+ * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable
3359
+ * permessage-deflate
3360
+ * @param {Number} [options.port] The port where to bind the server
3361
+ * @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S
3362
+ * server to use
3363
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
3364
+ * not to skip UTF-8 validation for text and close messages
3365
+ * @param {Function} [options.verifyClient] A hook to reject connections
3366
+ * @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket`
3367
+ * class to use. It must be the `WebSocket` class or class that extends it
3368
+ * @param {Function} [callback] A listener for the `listening` event
3369
+ */
3370
+ constructor(options, callback) {
3371
+ super();
3372
+ options = {
3373
+ allowSynchronousEvents: true,
3374
+ autoPong: true,
3375
+ maxBufferedChunks: 256 * 1024,
3376
+ maxFragments: 16 * 1024,
3377
+ maxPayload: 100 * 1024 * 1024,
3378
+ skipUTF8Validation: false,
3379
+ perMessageDeflate: false,
3380
+ handleProtocols: null,
3381
+ clientTracking: true,
3382
+ closeTimeout: CLOSE_TIMEOUT,
3383
+ verifyClient: null,
3384
+ noServer: false,
3385
+ backlog: null,
3386
+ // use default (511 as implemented in net.js)
3387
+ server: null,
3388
+ host: null,
3389
+ path: null,
3390
+ port: null,
3391
+ WebSocket: WebSocket2,
3392
+ ...options
3393
+ };
3394
+ if (options.port == null && !options.server && !options.noServer || options.port != null && (options.server || options.noServer) || options.server && options.noServer) {
3395
+ throw new TypeError(
3396
+ 'One and only one of the "port", "server", or "noServer" options must be specified'
3397
+ );
3398
+ }
3399
+ if (options.port != null) {
3400
+ this._server = http.createServer((req, res) => {
3401
+ const body = http.STATUS_CODES[426];
3402
+ res.writeHead(426, {
3403
+ "Content-Length": body.length,
3404
+ "Content-Type": "text/plain"
3405
+ });
3406
+ res.end(body);
3407
+ });
3408
+ this._server.listen(
3409
+ options.port,
3410
+ options.host,
3411
+ options.backlog,
3412
+ callback
3413
+ );
3414
+ } else if (options.server) {
3415
+ this._server = options.server;
3416
+ }
3417
+ if (this._server) {
3418
+ const emitConnection = this.emit.bind(this, "connection");
3419
+ this._removeListeners = addListeners(this._server, {
3420
+ listening: this.emit.bind(this, "listening"),
3421
+ error: this.emit.bind(this, "error"),
3422
+ upgrade: (req, socket, head) => {
3423
+ this.handleUpgrade(req, socket, head, emitConnection);
3424
+ }
3425
+ });
3426
+ }
3427
+ if (options.perMessageDeflate === true) options.perMessageDeflate = {};
3428
+ if (options.clientTracking) {
3429
+ this.clients = /* @__PURE__ */ new Set();
3430
+ this._shouldEmitClose = false;
3431
+ }
3432
+ this.options = options;
3433
+ this._state = RUNNING;
3434
+ }
3435
+ /**
3436
+ * Returns the bound address, the address family name, and port of the server
3437
+ * as reported by the operating system if listening on an IP socket.
3438
+ * If the server is listening on a pipe or UNIX domain socket, the name is
3439
+ * returned as a string.
3440
+ *
3441
+ * @return {(Object|String|null)} The address of the server
3442
+ * @public
3443
+ */
3444
+ address() {
3445
+ if (this.options.noServer) {
3446
+ throw new Error('The server is operating in "noServer" mode');
3447
+ }
3448
+ if (!this._server) return null;
3449
+ return this._server.address();
3450
+ }
3451
+ /**
3452
+ * Stop the server from accepting new connections and emit the `'close'` event
3453
+ * when all existing connections are closed.
3454
+ *
3455
+ * @param {Function} [cb] A one-time listener for the `'close'` event
3456
+ * @public
3457
+ */
3458
+ close(cb) {
3459
+ if (this._state === CLOSED) {
3460
+ if (cb) {
3461
+ this.once("close", () => {
3462
+ cb(new Error("The server is not running"));
3463
+ });
3464
+ }
3465
+ process.nextTick(emitClose, this);
3466
+ return;
3467
+ }
3468
+ if (cb) this.once("close", cb);
3469
+ if (this._state === CLOSING) return;
3470
+ this._state = CLOSING;
3471
+ if (this.options.noServer || this.options.server) {
3472
+ if (this._server) {
3473
+ this._removeListeners();
3474
+ this._removeListeners = this._server = null;
3475
+ }
3476
+ if (this.clients) {
3477
+ if (!this.clients.size) {
3478
+ process.nextTick(emitClose, this);
3479
+ } else {
3480
+ this._shouldEmitClose = true;
3481
+ }
3482
+ } else {
3483
+ process.nextTick(emitClose, this);
3484
+ }
3485
+ } else {
3486
+ const server2 = this._server;
3487
+ this._removeListeners();
3488
+ this._removeListeners = this._server = null;
3489
+ server2.close(() => {
3490
+ emitClose(this);
3491
+ });
3492
+ }
3493
+ }
3494
+ /**
3495
+ * See if a given request should be handled by this server instance.
3496
+ *
3497
+ * @param {http.IncomingMessage} req Request object to inspect
3498
+ * @return {Boolean} `true` if the request is valid, else `false`
3499
+ * @public
3500
+ */
3501
+ shouldHandle(req) {
3502
+ if (this.options.path) {
3503
+ const index = req.url.indexOf("?");
3504
+ const pathname = index !== -1 ? req.url.slice(0, index) : req.url;
3505
+ if (pathname !== this.options.path) return false;
3506
+ }
3507
+ return true;
3508
+ }
3509
+ /**
3510
+ * Handle a HTTP Upgrade request.
3511
+ *
3512
+ * @param {http.IncomingMessage} req The request object
3513
+ * @param {Duplex} socket The network socket between the server and client
3514
+ * @param {Buffer} head The first packet of the upgraded stream
3515
+ * @param {Function} cb Callback
3516
+ * @public
3517
+ */
3518
+ handleUpgrade(req, socket, head, cb) {
3519
+ socket.on("error", socketOnError);
3520
+ const key = req.headers["sec-websocket-key"];
3521
+ const upgrade = req.headers.upgrade;
3522
+ const version = +req.headers["sec-websocket-version"];
3523
+ if (req.method !== "GET") {
3524
+ const message = "Invalid HTTP method";
3525
+ abortHandshakeOrEmitwsClientError(this, req, socket, 405, message);
3526
+ return;
3527
+ }
3528
+ if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") {
3529
+ const message = "Invalid Upgrade header";
3530
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
3531
+ return;
3532
+ }
3533
+ if (key === void 0 || !keyRegex.test(key)) {
3534
+ const message = "Missing or invalid Sec-WebSocket-Key header";
3535
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
3536
+ return;
3537
+ }
3538
+ if (version !== 13 && version !== 8) {
3539
+ const message = "Missing or invalid Sec-WebSocket-Version header";
3540
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message, {
3541
+ "Sec-WebSocket-Version": "13, 8"
3542
+ });
3543
+ return;
3544
+ }
3545
+ if (!this.shouldHandle(req)) {
3546
+ abortHandshake(socket, 400);
3547
+ return;
3548
+ }
3549
+ const secWebSocketProtocol = req.headers["sec-websocket-protocol"];
3550
+ let protocols = /* @__PURE__ */ new Set();
3551
+ if (secWebSocketProtocol !== void 0) {
3552
+ try {
3553
+ protocols = subprotocol2.parse(secWebSocketProtocol);
3554
+ } catch (err) {
3555
+ const message = "Invalid Sec-WebSocket-Protocol header";
3556
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
3557
+ return;
3558
+ }
3559
+ }
3560
+ const secWebSocketExtensions = req.headers["sec-websocket-extensions"];
3561
+ const extensions = {};
3562
+ if (this.options.perMessageDeflate && secWebSocketExtensions !== void 0) {
3563
+ const perMessageDeflate = new PerMessageDeflate2({
3564
+ ...this.options.perMessageDeflate,
3565
+ isServer: true,
3566
+ maxPayload: this.options.maxPayload
3567
+ });
3568
+ try {
3569
+ const offers = extension2.parse(secWebSocketExtensions);
3570
+ if (offers[PerMessageDeflate2.extensionName]) {
3571
+ perMessageDeflate.accept(offers[PerMessageDeflate2.extensionName]);
3572
+ extensions[PerMessageDeflate2.extensionName] = perMessageDeflate;
3573
+ }
3574
+ } catch (err) {
3575
+ const message = "Invalid or unacceptable Sec-WebSocket-Extensions header";
3576
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
3577
+ return;
3578
+ }
3579
+ }
3580
+ if (this.options.verifyClient) {
3581
+ const info = {
3582
+ origin: req.headers[`${version === 8 ? "sec-websocket-origin" : "origin"}`],
3583
+ secure: !!(req.socket.authorized || req.socket.encrypted),
3584
+ req
3585
+ };
3586
+ if (this.options.verifyClient.length === 2) {
3587
+ this.options.verifyClient(info, (verified, code, message, headers) => {
3588
+ if (!verified) {
3589
+ return abortHandshake(socket, code || 401, message, headers);
3590
+ }
3591
+ this.completeUpgrade(
3592
+ extensions,
3593
+ key,
3594
+ protocols,
3595
+ req,
3596
+ socket,
3597
+ head,
3598
+ cb
3599
+ );
3600
+ });
3601
+ return;
3602
+ }
3603
+ if (!this.options.verifyClient(info)) return abortHandshake(socket, 401);
3604
+ }
3605
+ this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);
3606
+ }
3607
+ /**
3608
+ * Upgrade the connection to WebSocket.
3609
+ *
3610
+ * @param {Object} extensions The accepted extensions
3611
+ * @param {String} key The value of the `Sec-WebSocket-Key` header
3612
+ * @param {Set} protocols The subprotocols
3613
+ * @param {http.IncomingMessage} req The request object
3614
+ * @param {Duplex} socket The network socket between the server and client
3615
+ * @param {Buffer} head The first packet of the upgraded stream
3616
+ * @param {Function} cb Callback
3617
+ * @throws {Error} If called more than once with the same socket
3618
+ * @private
3619
+ */
3620
+ completeUpgrade(extensions, key, protocols, req, socket, head, cb) {
3621
+ if (!socket.readable || !socket.writable) return socket.destroy();
3622
+ if (socket[kWebSocket]) {
3623
+ throw new Error(
3624
+ "server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration"
3625
+ );
3626
+ }
3627
+ if (this._state > RUNNING) return abortHandshake(socket, 503);
3628
+ const digest = createHash("sha1").update(key + GUID).digest("base64");
3629
+ const headers = [
3630
+ "HTTP/1.1 101 Switching Protocols",
3631
+ "Upgrade: websocket",
3632
+ "Connection: Upgrade",
3633
+ `Sec-WebSocket-Accept: ${digest}`
3634
+ ];
3635
+ const ws = new this.options.WebSocket(null, void 0, this.options);
3636
+ if (protocols.size) {
3637
+ const protocol = this.options.handleProtocols ? this.options.handleProtocols(protocols, req) : protocols.values().next().value;
3638
+ if (protocol) {
3639
+ headers.push(`Sec-WebSocket-Protocol: ${protocol}`);
3640
+ ws._protocol = protocol;
3641
+ }
3642
+ }
3643
+ if (extensions[PerMessageDeflate2.extensionName]) {
3644
+ const params = extensions[PerMessageDeflate2.extensionName].params;
3645
+ const value = extension2.format({
3646
+ [PerMessageDeflate2.extensionName]: [params]
3647
+ });
3648
+ headers.push(`Sec-WebSocket-Extensions: ${value}`);
3649
+ ws._extensions = extensions;
3650
+ }
3651
+ this.emit("headers", headers, req);
3652
+ socket.write(headers.concat("\r\n").join("\r\n"));
3653
+ socket.removeListener("error", socketOnError);
3654
+ ws.setSocket(socket, head, {
3655
+ allowSynchronousEvents: this.options.allowSynchronousEvents,
3656
+ maxBufferedChunks: this.options.maxBufferedChunks,
3657
+ maxFragments: this.options.maxFragments,
3658
+ maxPayload: this.options.maxPayload,
3659
+ skipUTF8Validation: this.options.skipUTF8Validation
3660
+ });
3661
+ if (this.clients) {
3662
+ this.clients.add(ws);
3663
+ ws.on("close", () => {
3664
+ this.clients.delete(ws);
3665
+ if (this._shouldEmitClose && !this.clients.size) {
3666
+ process.nextTick(emitClose, this);
3667
+ }
3668
+ });
3669
+ }
3670
+ cb(ws, req);
3671
+ }
3672
+ };
3673
+ module2.exports = WebSocketServer2;
3674
+ function addListeners(server2, map) {
3675
+ for (const event of Object.keys(map)) server2.on(event, map[event]);
3676
+ return function removeListeners() {
3677
+ for (const event of Object.keys(map)) {
3678
+ server2.removeListener(event, map[event]);
3679
+ }
3680
+ };
3681
+ }
3682
+ function emitClose(server2) {
3683
+ server2._state = CLOSED;
3684
+ server2.emit("close");
3685
+ }
3686
+ function socketOnError() {
3687
+ this.destroy();
3688
+ }
3689
+ function abortHandshake(socket, code, message, headers) {
3690
+ message = message || http.STATUS_CODES[code];
3691
+ headers = {
3692
+ Connection: "close",
3693
+ "Content-Type": "text/html",
3694
+ "Content-Length": Buffer.byteLength(message),
3695
+ ...headers
3696
+ };
3697
+ socket.once("finish", socket.destroy);
3698
+ socket.end(
3699
+ `HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r
3700
+ ` + Object.keys(headers).map((h) => `${h}: ${headers[h]}`).join("\r\n") + "\r\n\r\n" + message
3701
+ );
3702
+ }
3703
+ function abortHandshakeOrEmitwsClientError(server2, req, socket, code, message, headers) {
3704
+ if (server2.listenerCount("wsClientError")) {
3705
+ const err = new Error(message);
3706
+ Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError);
3707
+ server2.emit("wsClientError", err, socket, req);
3708
+ } else {
3709
+ abortHandshake(socket, code, message, headers);
3710
+ }
3711
+ }
3712
+ }
3713
+ });
3714
+
3715
+ // apps/daemon/src/index.ts
3716
+ var import_node_http = require("node:http");
3717
+ var import_node_crypto2 = require("node:crypto");
3718
+
3719
+ // apps/daemon/node_modules/ws/wrapper.mjs
3720
+ var import_stream = __toESM(require_stream(), 1);
3721
+ var import_extension = __toESM(require_extension(), 1);
3722
+ var import_permessage_deflate = __toESM(require_permessage_deflate(), 1);
3723
+ var import_receiver = __toESM(require_receiver(), 1);
3724
+ var import_sender = __toESM(require_sender(), 1);
3725
+ var import_subprotocol = __toESM(require_subprotocol(), 1);
3726
+ var import_websocket = __toESM(require_websocket(), 1);
3727
+ var import_websocket_server = __toESM(require_websocket_server(), 1);
3728
+
3729
+ // packages/shared/src/types.ts
3730
+ var DEFAULT_PORT = 18721;
3731
+ var DEFAULT_TIMEOUT_MS = 15e3;
3732
+
3733
+ // apps/daemon/src/token-store.ts
3734
+ var import_node_crypto = require("node:crypto");
3735
+ var import_node_os = require("node:os");
3736
+ var import_node_path = require("node:path");
3737
+ var import_node_fs = require("node:fs");
3738
+ function configDir() {
3739
+ const dir = process.env.OPENCHROME_CONFIG_DIR ?? (0, import_node_path.join)((0, import_node_os.homedir)(), ".openchrome");
3740
+ (0, import_node_fs.mkdirSync)(dir, { recursive: true, mode: 448 });
3741
+ return dir;
3742
+ }
3743
+ function tokenPath() {
3744
+ return (0, import_node_path.join)(configDir(), "token");
3745
+ }
3746
+ function loadOrCreateToken() {
3747
+ const env = process.env.OPENCHROME_TOKEN;
3748
+ if (env) return env;
3749
+ const p = tokenPath();
3750
+ if ((0, import_node_fs.existsSync)(p)) {
3751
+ const t2 = (0, import_node_fs.readFileSync)(p, "utf8").trim();
3752
+ if (t2.startsWith("oc_")) return t2;
3753
+ }
3754
+ const t = "oc_" + (0, import_node_crypto.randomBytes)(16).toString("hex");
3755
+ (0, import_node_fs.writeFileSync)(p, t + "\n", { mode: 384 });
3756
+ return t;
3757
+ }
3758
+ function resetToken() {
3759
+ const p = tokenPath();
3760
+ const t = "oc_" + (0, import_node_crypto.randomBytes)(16).toString("hex");
3761
+ (0, import_node_fs.writeFileSync)(p, t + "\n", { mode: 384 });
3762
+ return t;
3763
+ }
3764
+
3765
+ // apps/daemon/src/tab-registry.ts
3766
+ var TabRegistry = class {
3767
+ extensionConnected = false;
3768
+ activeTab;
3769
+ pageGeneration = /* @__PURE__ */ new Map();
3770
+ lastSeen = /* @__PURE__ */ new Map();
3771
+ setTabs(tabs, activeTab) {
3772
+ this.lastSeen.clear();
3773
+ for (const t of tabs) this.lastSeen.set(t.id, t);
3774
+ if (activeTab !== void 0) this.activeTab = activeTab;
3775
+ }
3776
+ bumpGeneration(tabId) {
3777
+ const g = (this.pageGeneration.get(tabId) ?? 0) + 1;
3778
+ this.pageGeneration.set(tabId, g);
3779
+ return g;
3780
+ }
3781
+ };
3782
+
3783
+ // apps/daemon/src/index.ts
3784
+ var args = process.argv.slice(2);
3785
+ if (args.includes("--reset-token")) {
3786
+ console.log(resetToken());
3787
+ process.exit(0);
3788
+ }
3789
+ var port = Number(process.env.OPENCHROME_PORT ?? DEFAULT_PORT);
3790
+ var portFlag = args.indexOf("--port");
3791
+ if (portFlag >= 0 && args[portFlag + 1]) port = Number(args[portFlag + 1]);
3792
+ var token = loadOrCreateToken();
3793
+ var registry = new TabRegistry();
3794
+ var server = (0, import_node_http.createServer)();
3795
+ var wss = new import_websocket_server.default({ server });
3796
+ var activeShim = null;
3797
+ var extensionSock = null;
3798
+ var pending = /* @__PURE__ */ new Map();
3799
+ function send(ws, obj) {
3800
+ ws.send(JSON.stringify(obj));
3801
+ }
3802
+ function forwardToExtension(id, method, params, owner, timeoutMs) {
3803
+ if (!extensionSock || extensionSock.readyState !== import_websocket.default.OPEN) {
3804
+ send(owner, { id, type: "response", success: false, error: { code: "CHROME_NOT_CONNECTED", message: "extension not connected. Pair token and open Chrome." } });
3805
+ return;
3806
+ }
3807
+ const timer = setTimeout(() => {
3808
+ pending.delete(id);
3809
+ send(owner, { id, type: "response", success: false, error: { code: "COMMAND_TIMEOUT", message: `extension did not respond in ${timeoutMs}ms` } });
3810
+ }, timeoutMs);
3811
+ pending.set(id, { timer, owner });
3812
+ send(extensionSock, { id, type: "command", method, params });
3813
+ }
3814
+ wss.on("connection", (ws) => {
3815
+ let authed = false;
3816
+ let role = null;
3817
+ const heartbeat = setInterval(() => {
3818
+ try {
3819
+ ws.ping();
3820
+ } catch {
3821
+ }
3822
+ }, 5e3);
3823
+ let dead = setTimeout(() => ws.terminate(), 15e3);
3824
+ ws.on("pong", () => {
3825
+ clearTimeout(dead);
3826
+ dead = setTimeout(() => ws.terminate(), 15e3);
3827
+ });
3828
+ ws.on("message", (raw) => {
3829
+ let msg;
3830
+ try {
3831
+ msg = JSON.parse(String(raw));
3832
+ } catch {
3833
+ return;
3834
+ }
3835
+ if (msg.type === "register") {
3836
+ if (msg.token !== token) {
3837
+ send(ws, { id: msg.id, type: "response", success: false, error: { code: "AUTH_FAILED", message: "bad token" } });
3838
+ ws.close();
3839
+ return;
3840
+ }
3841
+ if (msg.role === "mcp-shim") {
3842
+ if (activeShim && activeShim !== ws && activeShim.readyState === import_websocket.default.OPEN) {
3843
+ send(ws, { id: msg.id, type: "response", success: false, error: { code: "SESSION_BUSY", message: "daemon already bound to another agent" } });
3844
+ ws.close();
3845
+ return;
3846
+ }
3847
+ activeShim = ws;
3848
+ }
3849
+ if (msg.role === "extension") {
3850
+ extensionSock = ws;
3851
+ registry.extensionConnected = true;
3852
+ }
3853
+ authed = true;
3854
+ role = msg.role;
3855
+ send(ws, { id: msg.id, type: "response", success: true, result: { ok: true } });
3856
+ return;
3857
+ }
3858
+ if (!authed) {
3859
+ send(ws, { id: msg.id, type: "response", success: false, error: { code: "AUTH_FAILED", message: "register first" } });
3860
+ return;
3861
+ }
3862
+ if (msg.type === "response") {
3863
+ const p = pending.get(msg.id);
3864
+ if (p) {
3865
+ clearTimeout(p.timer);
3866
+ pending.delete(msg.id);
3867
+ send(p.owner, msg);
3868
+ if (msg.success && msg.result && typeof msg.result === "object") {
3869
+ const r = msg.result;
3870
+ if (typeof r.activeTab === "number") registry.activeTab = r.activeTab;
3871
+ if (typeof r.tabId === "number" && msg.method?.includes("reload")) registry.bumpGeneration(r.tabId);
3872
+ }
3873
+ }
3874
+ return;
3875
+ }
3876
+ if (msg.type === "command") {
3877
+ const timeoutMs = Math.min(Number(msg.params?.timeoutMs ?? DEFAULT_TIMEOUT_MS) || DEFAULT_TIMEOUT_MS, 6e4);
3878
+ if (msg.method === "status.get") {
3879
+ send(ws, { id: msg.id, type: "response", success: true, result: { extensionConnected: registry.extensionConnected, daemonVersion: "0.1.0", activeTab: registry.activeTab, uptimeMs: Math.round(process.uptime() * 1e3) } });
3880
+ return;
3881
+ }
3882
+ if (role === "mcp-shim" && (msg.method.startsWith("tabs.") || msg.method.startsWith("page.") || msg.method.startsWith("element.") || msg.method.startsWith("input.") || msg.method.startsWith("console.") || msg.method.startsWith("network."))) {
3883
+ forwardToExtension(msg.id ?? (0, import_node_crypto2.randomUUID)(), msg.method, msg.params ?? {}, ws, timeoutMs);
3884
+ return;
3885
+ }
3886
+ send(ws, { id: msg.id, type: "response", success: false, error: { code: "CHROME_NOT_CONNECTED", message: `no handler for ${msg.method} (role=${role})` } });
3887
+ return;
3888
+ }
3889
+ if (msg.type === "event" && role === "extension" && msg.name === "tabs.changed") {
3890
+ registry.extensionConnected = true;
3891
+ return;
3892
+ }
3893
+ });
3894
+ ws.on("close", () => {
3895
+ clearInterval(heartbeat);
3896
+ clearTimeout(dead);
3897
+ if (activeShim === ws) activeShim = null;
3898
+ if (extensionSock === ws) {
3899
+ extensionSock = null;
3900
+ registry.extensionConnected = false;
3901
+ }
3902
+ for (const [id, p] of pending) {
3903
+ if (p.owner === ws) {
3904
+ clearTimeout(p.timer);
3905
+ pending.delete(id);
3906
+ }
3907
+ }
3908
+ });
3909
+ });
3910
+ server.listen(port, "127.0.0.1", () => {
3911
+ console.log(`openchrome daemon on ws://127.0.0.1:${port}`);
3912
+ });