@scalequality/cli 0.4.30 → 0.4.31

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/connect.cjs CHANGED
@@ -6,6 +6,13 @@ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
6
  var __getOwnPropNames = Object.getOwnPropertyNames;
7
7
  var __getProtoOf = Object.getPrototypeOf;
8
8
  var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __commonJS = (cb, mod) => function __require() {
10
+ try {
11
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
12
+ } catch (e) {
13
+ throw mod = 0, e;
14
+ }
15
+ };
9
16
  var __export = (target, all) => {
10
17
  for (var name in all)
11
18
  __defProp(target, name, { get: all[name], enumerable: true });
@@ -16,20 +23,3690 @@ var __copyProps = (to, from, except, desc) => {
16
23
  if (!__hasOwnProp.call(to, key) && key !== except)
17
24
  __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
18
25
  }
19
- return to;
20
- };
21
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
22
- // If the importer is in node compatibility mode or this is not an ESM
23
- // file that has been converted to a CommonJS file using a Babel-
24
- // compatible transform (i.e. "__esModule" has not been set), then set
25
- // "default" to the CommonJS "module.exports" for node compatibility.
26
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
27
- mod
28
- ));
26
+ return to;
27
+ };
28
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
29
+ // If the importer is in node compatibility mode or this is not an ESM
30
+ // file that has been converted to a CommonJS file using a Babel-
31
+ // compatible transform (i.e. "__esModule" has not been set), then set
32
+ // "default" to the CommonJS "module.exports" for node compatibility.
33
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
34
+ mod
35
+ ));
36
+
37
+ // node_modules/ws/lib/constants.js
38
+ var require_constants = __commonJS({
39
+ "node_modules/ws/lib/constants.js"(exports2, module2) {
40
+ "use strict";
41
+ var BINARY_TYPES = ["nodebuffer", "arraybuffer", "fragments"];
42
+ var hasBlob = typeof Blob !== "undefined";
43
+ if (hasBlob) BINARY_TYPES.push("blob");
44
+ module2.exports = {
45
+ BINARY_TYPES,
46
+ CLOSE_TIMEOUT: 3e4,
47
+ EMPTY_BUFFER: Buffer.alloc(0),
48
+ GUID: "258EAFA5-E914-47DA-95CA-C5AB0DC85B11",
49
+ hasBlob,
50
+ kForOnEventAttribute: /* @__PURE__ */ Symbol("kIsForOnEventAttribute"),
51
+ kListener: /* @__PURE__ */ Symbol("kListener"),
52
+ kStatusCode: /* @__PURE__ */ Symbol("status-code"),
53
+ kWebSocket: /* @__PURE__ */ Symbol("websocket"),
54
+ NOOP: () => {
55
+ }
56
+ };
57
+ }
58
+ });
59
+
60
+ // node_modules/ws/lib/buffer-util.js
61
+ var require_buffer_util = __commonJS({
62
+ "node_modules/ws/lib/buffer-util.js"(exports2, module2) {
63
+ "use strict";
64
+ var { EMPTY_BUFFER } = require_constants();
65
+ var FastBuffer = Buffer[Symbol.species];
66
+ function concat(list, totalLength) {
67
+ if (list.length === 0) return EMPTY_BUFFER;
68
+ if (list.length === 1) return list[0];
69
+ const target = Buffer.allocUnsafe(totalLength);
70
+ let offset = 0;
71
+ for (let i = 0; i < list.length; i++) {
72
+ const buf = list[i];
73
+ target.set(buf, offset);
74
+ offset += buf.length;
75
+ }
76
+ if (offset < totalLength) {
77
+ return new FastBuffer(target.buffer, target.byteOffset, offset);
78
+ }
79
+ return target;
80
+ }
81
+ function _mask(source, mask, output, offset, length) {
82
+ for (let i = 0; i < length; i++) {
83
+ output[offset + i] = source[i] ^ mask[i & 3];
84
+ }
85
+ }
86
+ function _unmask(buffer, mask) {
87
+ for (let i = 0; i < buffer.length; i++) {
88
+ buffer[i] ^= mask[i & 3];
89
+ }
90
+ }
91
+ function toArrayBuffer(buf) {
92
+ if (buf.length === buf.buffer.byteLength) {
93
+ return buf.buffer;
94
+ }
95
+ return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length);
96
+ }
97
+ function toBuffer(data) {
98
+ toBuffer.readOnly = true;
99
+ if (Buffer.isBuffer(data)) return data;
100
+ let buf;
101
+ if (data instanceof ArrayBuffer) {
102
+ buf = new FastBuffer(data);
103
+ } else if (ArrayBuffer.isView(data)) {
104
+ buf = new FastBuffer(data.buffer, data.byteOffset, data.byteLength);
105
+ } else {
106
+ buf = Buffer.from(data);
107
+ toBuffer.readOnly = false;
108
+ }
109
+ return buf;
110
+ }
111
+ module2.exports = {
112
+ concat,
113
+ mask: _mask,
114
+ toArrayBuffer,
115
+ toBuffer,
116
+ unmask: _unmask
117
+ };
118
+ if (!process.env.WS_NO_BUFFER_UTIL) {
119
+ try {
120
+ const bufferUtil = require("bufferutil");
121
+ module2.exports.mask = function(source, mask, output, offset, length) {
122
+ if (length < 48) _mask(source, mask, output, offset, length);
123
+ else bufferUtil.mask(source, mask, output, offset, length);
124
+ };
125
+ module2.exports.unmask = function(buffer, mask) {
126
+ if (buffer.length < 32) _unmask(buffer, mask);
127
+ else bufferUtil.unmask(buffer, mask);
128
+ };
129
+ } catch (e) {
130
+ }
131
+ }
132
+ }
133
+ });
134
+
135
+ // node_modules/ws/lib/limiter.js
136
+ var require_limiter = __commonJS({
137
+ "node_modules/ws/lib/limiter.js"(exports2, module2) {
138
+ "use strict";
139
+ var kDone = /* @__PURE__ */ Symbol("kDone");
140
+ var kRun = /* @__PURE__ */ Symbol("kRun");
141
+ var Limiter = class {
142
+ /**
143
+ * Creates a new `Limiter`.
144
+ *
145
+ * @param {Number} [concurrency=Infinity] The maximum number of jobs allowed
146
+ * to run concurrently
147
+ */
148
+ constructor(concurrency) {
149
+ this[kDone] = () => {
150
+ this.pending--;
151
+ this[kRun]();
152
+ };
153
+ this.concurrency = concurrency || Infinity;
154
+ this.jobs = [];
155
+ this.pending = 0;
156
+ }
157
+ /**
158
+ * Adds a job to the queue.
159
+ *
160
+ * @param {Function} job The job to run
161
+ * @public
162
+ */
163
+ add(job) {
164
+ this.jobs.push(job);
165
+ this[kRun]();
166
+ }
167
+ /**
168
+ * Removes a job from the queue and runs it if possible.
169
+ *
170
+ * @private
171
+ */
172
+ [kRun]() {
173
+ if (this.pending === this.concurrency) return;
174
+ if (this.jobs.length) {
175
+ const job = this.jobs.shift();
176
+ this.pending++;
177
+ job(this[kDone]);
178
+ }
179
+ }
180
+ };
181
+ module2.exports = Limiter;
182
+ }
183
+ });
184
+
185
+ // node_modules/ws/lib/permessage-deflate.js
186
+ var require_permessage_deflate = __commonJS({
187
+ "node_modules/ws/lib/permessage-deflate.js"(exports2, module2) {
188
+ "use strict";
189
+ var zlib = require("zlib");
190
+ var bufferUtil = require_buffer_util();
191
+ var Limiter = require_limiter();
192
+ var { kStatusCode } = require_constants();
193
+ var FastBuffer = Buffer[Symbol.species];
194
+ var TRAILER = Buffer.from([0, 0, 255, 255]);
195
+ var kPerMessageDeflate = /* @__PURE__ */ Symbol("permessage-deflate");
196
+ var kTotalLength = /* @__PURE__ */ Symbol("total-length");
197
+ var kCallback = /* @__PURE__ */ Symbol("callback");
198
+ var kBuffers = /* @__PURE__ */ Symbol("buffers");
199
+ var kError = /* @__PURE__ */ Symbol("error");
200
+ var zlibLimiter;
201
+ var PerMessageDeflate2 = class {
202
+ /**
203
+ * Creates a PerMessageDeflate instance.
204
+ *
205
+ * @param {Object} [options] Configuration options
206
+ * @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support
207
+ * for, or request, a custom client window size
208
+ * @param {Boolean} [options.clientNoContextTakeover=false] Advertise/
209
+ * acknowledge disabling of client context takeover
210
+ * @param {Number} [options.concurrencyLimit=10] The number of concurrent
211
+ * calls to zlib
212
+ * @param {Boolean} [options.isServer=false] Create the instance in either
213
+ * server or client mode
214
+ * @param {Number} [options.maxPayload=0] The maximum allowed message length
215
+ * @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the
216
+ * use of a custom server window size
217
+ * @param {Boolean} [options.serverNoContextTakeover=false] Request/accept
218
+ * disabling of server context takeover
219
+ * @param {Number} [options.threshold=1024] Size (in bytes) below which
220
+ * messages should not be compressed if context takeover is disabled
221
+ * @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on
222
+ * deflate
223
+ * @param {Object} [options.zlibInflateOptions] Options to pass to zlib on
224
+ * inflate
225
+ */
226
+ constructor(options) {
227
+ this._options = options || {};
228
+ this._threshold = this._options.threshold !== void 0 ? this._options.threshold : 1024;
229
+ this._maxPayload = this._options.maxPayload | 0;
230
+ this._isServer = !!this._options.isServer;
231
+ this._deflate = null;
232
+ this._inflate = null;
233
+ this.params = null;
234
+ if (!zlibLimiter) {
235
+ const concurrency = this._options.concurrencyLimit !== void 0 ? this._options.concurrencyLimit : 10;
236
+ zlibLimiter = new Limiter(concurrency);
237
+ }
238
+ }
239
+ /**
240
+ * @type {String}
241
+ */
242
+ static get extensionName() {
243
+ return "permessage-deflate";
244
+ }
245
+ /**
246
+ * Create an extension negotiation offer.
247
+ *
248
+ * @return {Object} Extension parameters
249
+ * @public
250
+ */
251
+ offer() {
252
+ const params = {};
253
+ if (this._options.serverNoContextTakeover) {
254
+ params.server_no_context_takeover = true;
255
+ }
256
+ if (this._options.clientNoContextTakeover) {
257
+ params.client_no_context_takeover = true;
258
+ }
259
+ if (this._options.serverMaxWindowBits) {
260
+ params.server_max_window_bits = this._options.serverMaxWindowBits;
261
+ }
262
+ if (this._options.clientMaxWindowBits) {
263
+ params.client_max_window_bits = this._options.clientMaxWindowBits;
264
+ } else if (this._options.clientMaxWindowBits == null) {
265
+ params.client_max_window_bits = true;
266
+ }
267
+ return params;
268
+ }
269
+ /**
270
+ * Accept an extension negotiation offer/response.
271
+ *
272
+ * @param {Array} configurations The extension negotiation offers/reponse
273
+ * @return {Object} Accepted configuration
274
+ * @public
275
+ */
276
+ accept(configurations) {
277
+ configurations = this.normalizeParams(configurations);
278
+ this.params = this._isServer ? this.acceptAsServer(configurations) : this.acceptAsClient(configurations);
279
+ return this.params;
280
+ }
281
+ /**
282
+ * Releases all resources used by the extension.
283
+ *
284
+ * @public
285
+ */
286
+ cleanup() {
287
+ if (this._inflate) {
288
+ this._inflate.close();
289
+ this._inflate = null;
290
+ }
291
+ if (this._deflate) {
292
+ const callback = this._deflate[kCallback];
293
+ this._deflate.close();
294
+ this._deflate = null;
295
+ if (callback) {
296
+ callback(
297
+ new Error(
298
+ "The deflate stream was closed while data was being processed"
299
+ )
300
+ );
301
+ }
302
+ }
303
+ }
304
+ /**
305
+ * Accept an extension negotiation offer.
306
+ *
307
+ * @param {Array} offers The extension negotiation offers
308
+ * @return {Object} Accepted configuration
309
+ * @private
310
+ */
311
+ acceptAsServer(offers) {
312
+ const opts = this._options;
313
+ const accepted = offers.find((params) => {
314
+ if (opts.serverNoContextTakeover === false && params.server_no_context_takeover || params.server_max_window_bits && (opts.serverMaxWindowBits === false || typeof opts.serverMaxWindowBits === "number" && opts.serverMaxWindowBits > params.server_max_window_bits) || typeof opts.clientMaxWindowBits === "number" && (typeof params.client_max_window_bits === "number" ? opts.clientMaxWindowBits > params.client_max_window_bits : !params.client_max_window_bits)) {
315
+ return false;
316
+ }
317
+ return true;
318
+ });
319
+ if (!accepted) {
320
+ throw new Error("None of the extension offers can be accepted");
321
+ }
322
+ if (opts.serverNoContextTakeover) {
323
+ accepted.server_no_context_takeover = true;
324
+ }
325
+ if (opts.clientNoContextTakeover) {
326
+ accepted.client_no_context_takeover = true;
327
+ }
328
+ if (typeof opts.serverMaxWindowBits === "number") {
329
+ accepted.server_max_window_bits = opts.serverMaxWindowBits;
330
+ }
331
+ if (typeof opts.clientMaxWindowBits === "number") {
332
+ accepted.client_max_window_bits = opts.clientMaxWindowBits;
333
+ } else if (accepted.client_max_window_bits === true || opts.clientMaxWindowBits === false) {
334
+ delete accepted.client_max_window_bits;
335
+ }
336
+ return accepted;
337
+ }
338
+ /**
339
+ * Accept the extension negotiation response.
340
+ *
341
+ * @param {Array} response The extension negotiation response
342
+ * @return {Object} Accepted configuration
343
+ * @private
344
+ */
345
+ acceptAsClient(response) {
346
+ const params = response[0];
347
+ if (this._options.clientNoContextTakeover === false && params.client_no_context_takeover) {
348
+ throw new Error('Unexpected parameter "client_no_context_takeover"');
349
+ }
350
+ if (!params.client_max_window_bits) {
351
+ if (typeof this._options.clientMaxWindowBits === "number") {
352
+ params.client_max_window_bits = this._options.clientMaxWindowBits;
353
+ }
354
+ } else if (this._options.clientMaxWindowBits === false || typeof this._options.clientMaxWindowBits === "number" && params.client_max_window_bits > this._options.clientMaxWindowBits) {
355
+ throw new Error(
356
+ 'Unexpected or invalid parameter "client_max_window_bits"'
357
+ );
358
+ }
359
+ return params;
360
+ }
361
+ /**
362
+ * Normalize parameters.
363
+ *
364
+ * @param {Array} configurations The extension negotiation offers/reponse
365
+ * @return {Array} The offers/response with normalized parameters
366
+ * @private
367
+ */
368
+ normalizeParams(configurations) {
369
+ configurations.forEach((params) => {
370
+ Object.keys(params).forEach((key) => {
371
+ let value = params[key];
372
+ if (value.length > 1) {
373
+ throw new Error(`Parameter "${key}" must have only a single value`);
374
+ }
375
+ value = value[0];
376
+ if (key === "client_max_window_bits") {
377
+ if (value !== true) {
378
+ const num = +value;
379
+ if (!Number.isInteger(num) || num < 8 || num > 15) {
380
+ throw new TypeError(
381
+ `Invalid value for parameter "${key}": ${value}`
382
+ );
383
+ }
384
+ value = num;
385
+ } else if (!this._isServer) {
386
+ throw new TypeError(
387
+ `Invalid value for parameter "${key}": ${value}`
388
+ );
389
+ }
390
+ } else if (key === "server_max_window_bits") {
391
+ const num = +value;
392
+ if (!Number.isInteger(num) || num < 8 || num > 15) {
393
+ throw new TypeError(
394
+ `Invalid value for parameter "${key}": ${value}`
395
+ );
396
+ }
397
+ value = num;
398
+ } else if (key === "client_no_context_takeover" || key === "server_no_context_takeover") {
399
+ if (value !== true) {
400
+ throw new TypeError(
401
+ `Invalid value for parameter "${key}": ${value}`
402
+ );
403
+ }
404
+ } else {
405
+ throw new Error(`Unknown parameter "${key}"`);
406
+ }
407
+ params[key] = value;
408
+ });
409
+ });
410
+ return configurations;
411
+ }
412
+ /**
413
+ * Decompress data. Concurrency limited.
414
+ *
415
+ * @param {Buffer} data Compressed data
416
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
417
+ * @param {Function} callback Callback
418
+ * @public
419
+ */
420
+ decompress(data, fin, callback) {
421
+ zlibLimiter.add((done) => {
422
+ this._decompress(data, fin, (err, result) => {
423
+ done();
424
+ callback(err, result);
425
+ });
426
+ });
427
+ }
428
+ /**
429
+ * Compress data. Concurrency limited.
430
+ *
431
+ * @param {(Buffer|String)} data Data to compress
432
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
433
+ * @param {Function} callback Callback
434
+ * @public
435
+ */
436
+ compress(data, fin, callback) {
437
+ zlibLimiter.add((done) => {
438
+ this._compress(data, fin, (err, result) => {
439
+ done();
440
+ callback(err, result);
441
+ });
442
+ });
443
+ }
444
+ /**
445
+ * Decompress data.
446
+ *
447
+ * @param {Buffer} data Compressed data
448
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
449
+ * @param {Function} callback Callback
450
+ * @private
451
+ */
452
+ _decompress(data, fin, callback) {
453
+ const endpoint = this._isServer ? "client" : "server";
454
+ if (!this._inflate) {
455
+ const key = `${endpoint}_max_window_bits`;
456
+ const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
457
+ this._inflate = zlib.createInflateRaw({
458
+ ...this._options.zlibInflateOptions,
459
+ windowBits
460
+ });
461
+ this._inflate[kPerMessageDeflate] = this;
462
+ this._inflate[kTotalLength] = 0;
463
+ this._inflate[kBuffers] = [];
464
+ this._inflate.on("error", inflateOnError);
465
+ this._inflate.on("data", inflateOnData);
466
+ }
467
+ this._inflate[kCallback] = callback;
468
+ this._inflate.write(data);
469
+ if (fin) this._inflate.write(TRAILER);
470
+ this._inflate.flush(() => {
471
+ const err = this._inflate[kError];
472
+ if (err) {
473
+ this._inflate.close();
474
+ this._inflate = null;
475
+ callback(err);
476
+ return;
477
+ }
478
+ const data2 = bufferUtil.concat(
479
+ this._inflate[kBuffers],
480
+ this._inflate[kTotalLength]
481
+ );
482
+ if (this._inflate._readableState.endEmitted) {
483
+ this._inflate.close();
484
+ this._inflate = null;
485
+ } else {
486
+ this._inflate[kTotalLength] = 0;
487
+ this._inflate[kBuffers] = [];
488
+ if (fin && this.params[`${endpoint}_no_context_takeover`]) {
489
+ this._inflate.reset();
490
+ }
491
+ }
492
+ callback(null, data2);
493
+ });
494
+ }
495
+ /**
496
+ * Compress data.
497
+ *
498
+ * @param {(Buffer|String)} data Data to compress
499
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
500
+ * @param {Function} callback Callback
501
+ * @private
502
+ */
503
+ _compress(data, fin, callback) {
504
+ const endpoint = this._isServer ? "server" : "client";
505
+ if (!this._deflate) {
506
+ const key = `${endpoint}_max_window_bits`;
507
+ const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
508
+ this._deflate = zlib.createDeflateRaw({
509
+ ...this._options.zlibDeflateOptions,
510
+ windowBits
511
+ });
512
+ this._deflate[kTotalLength] = 0;
513
+ this._deflate[kBuffers] = [];
514
+ this._deflate.on("data", deflateOnData);
515
+ }
516
+ this._deflate[kCallback] = callback;
517
+ this._deflate.write(data);
518
+ this._deflate.flush(zlib.Z_SYNC_FLUSH, () => {
519
+ if (!this._deflate) {
520
+ return;
521
+ }
522
+ let data2 = bufferUtil.concat(
523
+ this._deflate[kBuffers],
524
+ this._deflate[kTotalLength]
525
+ );
526
+ if (fin) {
527
+ data2 = new FastBuffer(data2.buffer, data2.byteOffset, data2.length - 4);
528
+ }
529
+ this._deflate[kCallback] = null;
530
+ this._deflate[kTotalLength] = 0;
531
+ this._deflate[kBuffers] = [];
532
+ if (fin && this.params[`${endpoint}_no_context_takeover`]) {
533
+ this._deflate.reset();
534
+ }
535
+ callback(null, data2);
536
+ });
537
+ }
538
+ };
539
+ module2.exports = PerMessageDeflate2;
540
+ function deflateOnData(chunk) {
541
+ this[kBuffers].push(chunk);
542
+ this[kTotalLength] += chunk.length;
543
+ }
544
+ function inflateOnData(chunk) {
545
+ this[kTotalLength] += chunk.length;
546
+ if (this[kPerMessageDeflate]._maxPayload < 1 || this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload) {
547
+ this[kBuffers].push(chunk);
548
+ return;
549
+ }
550
+ this[kError] = new RangeError("Max payload size exceeded");
551
+ this[kError].code = "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH";
552
+ this[kError][kStatusCode] = 1009;
553
+ this.removeListener("data", inflateOnData);
554
+ this.reset();
555
+ }
556
+ function inflateOnError(err) {
557
+ this[kPerMessageDeflate]._inflate = null;
558
+ if (this[kError]) {
559
+ this[kCallback](this[kError]);
560
+ return;
561
+ }
562
+ err[kStatusCode] = 1007;
563
+ this[kCallback](err);
564
+ }
565
+ }
566
+ });
567
+
568
+ // node_modules/ws/lib/validation.js
569
+ var require_validation = __commonJS({
570
+ "node_modules/ws/lib/validation.js"(exports2, module2) {
571
+ "use strict";
572
+ var { isUtf8 } = require("buffer");
573
+ var { hasBlob } = require_constants();
574
+ var tokenChars = [
575
+ 0,
576
+ 0,
577
+ 0,
578
+ 0,
579
+ 0,
580
+ 0,
581
+ 0,
582
+ 0,
583
+ 0,
584
+ 0,
585
+ 0,
586
+ 0,
587
+ 0,
588
+ 0,
589
+ 0,
590
+ 0,
591
+ // 0 - 15
592
+ 0,
593
+ 0,
594
+ 0,
595
+ 0,
596
+ 0,
597
+ 0,
598
+ 0,
599
+ 0,
600
+ 0,
601
+ 0,
602
+ 0,
603
+ 0,
604
+ 0,
605
+ 0,
606
+ 0,
607
+ 0,
608
+ // 16 - 31
609
+ 0,
610
+ 1,
611
+ 0,
612
+ 1,
613
+ 1,
614
+ 1,
615
+ 1,
616
+ 1,
617
+ 0,
618
+ 0,
619
+ 1,
620
+ 1,
621
+ 0,
622
+ 1,
623
+ 1,
624
+ 0,
625
+ // 32 - 47
626
+ 1,
627
+ 1,
628
+ 1,
629
+ 1,
630
+ 1,
631
+ 1,
632
+ 1,
633
+ 1,
634
+ 1,
635
+ 1,
636
+ 0,
637
+ 0,
638
+ 0,
639
+ 0,
640
+ 0,
641
+ 0,
642
+ // 48 - 63
643
+ 0,
644
+ 1,
645
+ 1,
646
+ 1,
647
+ 1,
648
+ 1,
649
+ 1,
650
+ 1,
651
+ 1,
652
+ 1,
653
+ 1,
654
+ 1,
655
+ 1,
656
+ 1,
657
+ 1,
658
+ 1,
659
+ // 64 - 79
660
+ 1,
661
+ 1,
662
+ 1,
663
+ 1,
664
+ 1,
665
+ 1,
666
+ 1,
667
+ 1,
668
+ 1,
669
+ 1,
670
+ 1,
671
+ 0,
672
+ 0,
673
+ 0,
674
+ 1,
675
+ 1,
676
+ // 80 - 95
677
+ 1,
678
+ 1,
679
+ 1,
680
+ 1,
681
+ 1,
682
+ 1,
683
+ 1,
684
+ 1,
685
+ 1,
686
+ 1,
687
+ 1,
688
+ 1,
689
+ 1,
690
+ 1,
691
+ 1,
692
+ 1,
693
+ // 96 - 111
694
+ 1,
695
+ 1,
696
+ 1,
697
+ 1,
698
+ 1,
699
+ 1,
700
+ 1,
701
+ 1,
702
+ 1,
703
+ 1,
704
+ 1,
705
+ 0,
706
+ 1,
707
+ 0,
708
+ 1,
709
+ 0
710
+ // 112 - 127
711
+ ];
712
+ function isValidStatusCode(code) {
713
+ return code >= 1e3 && code <= 1014 && code !== 1004 && code !== 1005 && code !== 1006 || code >= 3e3 && code <= 4999;
714
+ }
715
+ function _isValidUTF8(buf) {
716
+ const len = buf.length;
717
+ let i = 0;
718
+ while (i < len) {
719
+ if ((buf[i] & 128) === 0) {
720
+ i++;
721
+ } else if ((buf[i] & 224) === 192) {
722
+ if (i + 1 === len || (buf[i + 1] & 192) !== 128 || (buf[i] & 254) === 192) {
723
+ return false;
724
+ }
725
+ i += 2;
726
+ } else if ((buf[i] & 240) === 224) {
727
+ if (i + 2 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || buf[i] === 224 && (buf[i + 1] & 224) === 128 || // Overlong
728
+ buf[i] === 237 && (buf[i + 1] & 224) === 160) {
729
+ return false;
730
+ }
731
+ i += 3;
732
+ } else if ((buf[i] & 248) === 240) {
733
+ if (i + 3 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || (buf[i + 3] & 192) !== 128 || buf[i] === 240 && (buf[i + 1] & 240) === 128 || // Overlong
734
+ buf[i] === 244 && buf[i + 1] > 143 || buf[i] > 244) {
735
+ return false;
736
+ }
737
+ i += 4;
738
+ } else {
739
+ return false;
740
+ }
741
+ }
742
+ return true;
743
+ }
744
+ function isBlob(value) {
745
+ return hasBlob && typeof value === "object" && typeof value.arrayBuffer === "function" && typeof value.type === "string" && typeof value.stream === "function" && (value[Symbol.toStringTag] === "Blob" || value[Symbol.toStringTag] === "File");
746
+ }
747
+ module2.exports = {
748
+ isBlob,
749
+ isValidStatusCode,
750
+ isValidUTF8: _isValidUTF8,
751
+ tokenChars
752
+ };
753
+ if (isUtf8) {
754
+ module2.exports.isValidUTF8 = function(buf) {
755
+ return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf);
756
+ };
757
+ } else if (!process.env.WS_NO_UTF_8_VALIDATE) {
758
+ try {
759
+ const isValidUTF8 = require("utf-8-validate");
760
+ module2.exports.isValidUTF8 = function(buf) {
761
+ return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf);
762
+ };
763
+ } catch (e) {
764
+ }
765
+ }
766
+ }
767
+ });
768
+
769
+ // node_modules/ws/lib/receiver.js
770
+ var require_receiver = __commonJS({
771
+ "node_modules/ws/lib/receiver.js"(exports2, module2) {
772
+ "use strict";
773
+ var { Writable } = require("stream");
774
+ var PerMessageDeflate2 = require_permessage_deflate();
775
+ var {
776
+ BINARY_TYPES,
777
+ EMPTY_BUFFER,
778
+ kStatusCode,
779
+ kWebSocket
780
+ } = require_constants();
781
+ var { concat, toArrayBuffer, unmask } = require_buffer_util();
782
+ var { isValidStatusCode, isValidUTF8 } = require_validation();
783
+ var FastBuffer = Buffer[Symbol.species];
784
+ var GET_INFO = 0;
785
+ var GET_PAYLOAD_LENGTH_16 = 1;
786
+ var GET_PAYLOAD_LENGTH_64 = 2;
787
+ var GET_MASK = 3;
788
+ var GET_DATA = 4;
789
+ var INFLATING = 5;
790
+ var DEFER_EVENT = 6;
791
+ var Receiver2 = class extends Writable {
792
+ /**
793
+ * Creates a Receiver instance.
794
+ *
795
+ * @param {Object} [options] Options object
796
+ * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
797
+ * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
798
+ * multiple times in the same tick
799
+ * @param {String} [options.binaryType=nodebuffer] The type for binary data
800
+ * @param {Object} [options.extensions] An object containing the negotiated
801
+ * extensions
802
+ * @param {Boolean} [options.isServer=false] Specifies whether to operate in
803
+ * client or server mode
804
+ * @param {Number} [options.maxBufferedChunks=0] The maximum number of
805
+ * buffered data chunks
806
+ * @param {Number} [options.maxFragments=0] The maximum number of message
807
+ * fragments
808
+ * @param {Number} [options.maxPayload=0] The maximum allowed message length
809
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
810
+ * not to skip UTF-8 validation for text and close messages
811
+ */
812
+ constructor(options = {}) {
813
+ super();
814
+ this._allowSynchronousEvents = options.allowSynchronousEvents !== void 0 ? options.allowSynchronousEvents : true;
815
+ this._binaryType = options.binaryType || BINARY_TYPES[0];
816
+ this._extensions = options.extensions || {};
817
+ this._isServer = !!options.isServer;
818
+ this._maxBufferedChunks = options.maxBufferedChunks | 0;
819
+ this._maxFragments = options.maxFragments | 0;
820
+ this._maxPayload = options.maxPayload | 0;
821
+ this._skipUTF8Validation = !!options.skipUTF8Validation;
822
+ this[kWebSocket] = void 0;
823
+ this._bufferedBytes = 0;
824
+ this._buffers = [];
825
+ this._compressed = false;
826
+ this._payloadLength = 0;
827
+ this._mask = void 0;
828
+ this._fragmented = 0;
829
+ this._masked = false;
830
+ this._fin = false;
831
+ this._opcode = 0;
832
+ this._totalPayloadLength = 0;
833
+ this._messageLength = 0;
834
+ this._numFragments = 0;
835
+ this._fragments = [];
836
+ this._errored = false;
837
+ this._loop = false;
838
+ this._state = GET_INFO;
839
+ }
840
+ /**
841
+ * Implements `Writable.prototype._write()`.
842
+ *
843
+ * @param {Buffer} chunk The chunk of data to write
844
+ * @param {String} encoding The character encoding of `chunk`
845
+ * @param {Function} cb Callback
846
+ * @private
847
+ */
848
+ _write(chunk, encoding, cb) {
849
+ if (this._opcode === 8 && this._state == GET_INFO) return cb();
850
+ if (this._maxBufferedChunks > 0 && this._buffers.length >= this._maxBufferedChunks) {
851
+ cb(
852
+ this.createError(
853
+ RangeError,
854
+ "Too many buffered chunks",
855
+ false,
856
+ 1008,
857
+ "WS_ERR_TOO_MANY_BUFFERED_PARTS"
858
+ )
859
+ );
860
+ return;
861
+ }
862
+ this._bufferedBytes += chunk.length;
863
+ this._buffers.push(chunk);
864
+ this.startLoop(cb);
865
+ }
866
+ /**
867
+ * Consumes `n` bytes from the buffered data.
868
+ *
869
+ * @param {Number} n The number of bytes to consume
870
+ * @return {Buffer} The consumed bytes
871
+ * @private
872
+ */
873
+ consume(n) {
874
+ this._bufferedBytes -= n;
875
+ if (n === this._buffers[0].length) return this._buffers.shift();
876
+ if (n < this._buffers[0].length) {
877
+ const buf = this._buffers[0];
878
+ this._buffers[0] = new FastBuffer(
879
+ buf.buffer,
880
+ buf.byteOffset + n,
881
+ buf.length - n
882
+ );
883
+ return new FastBuffer(buf.buffer, buf.byteOffset, n);
884
+ }
885
+ const dst = Buffer.allocUnsafe(n);
886
+ do {
887
+ const buf = this._buffers[0];
888
+ const offset = dst.length - n;
889
+ if (n >= buf.length) {
890
+ dst.set(this._buffers.shift(), offset);
891
+ } else {
892
+ dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset);
893
+ this._buffers[0] = new FastBuffer(
894
+ buf.buffer,
895
+ buf.byteOffset + n,
896
+ buf.length - n
897
+ );
898
+ }
899
+ n -= buf.length;
900
+ } while (n > 0);
901
+ return dst;
902
+ }
903
+ /**
904
+ * Starts the parsing loop.
905
+ *
906
+ * @param {Function} cb Callback
907
+ * @private
908
+ */
909
+ startLoop(cb) {
910
+ this._loop = true;
911
+ do {
912
+ switch (this._state) {
913
+ case GET_INFO:
914
+ this.getInfo(cb);
915
+ break;
916
+ case GET_PAYLOAD_LENGTH_16:
917
+ this.getPayloadLength16(cb);
918
+ break;
919
+ case GET_PAYLOAD_LENGTH_64:
920
+ this.getPayloadLength64(cb);
921
+ break;
922
+ case GET_MASK:
923
+ this.getMask();
924
+ break;
925
+ case GET_DATA:
926
+ this.getData(cb);
927
+ break;
928
+ case INFLATING:
929
+ case DEFER_EVENT:
930
+ this._loop = false;
931
+ return;
932
+ }
933
+ } while (this._loop);
934
+ if (!this._errored) cb();
935
+ }
936
+ /**
937
+ * Reads the first two bytes of a frame.
938
+ *
939
+ * @param {Function} cb Callback
940
+ * @private
941
+ */
942
+ getInfo(cb) {
943
+ if (this._bufferedBytes < 2) {
944
+ this._loop = false;
945
+ return;
946
+ }
947
+ const buf = this.consume(2);
948
+ if ((buf[0] & 48) !== 0) {
949
+ const error = this.createError(
950
+ RangeError,
951
+ "RSV2 and RSV3 must be clear",
952
+ true,
953
+ 1002,
954
+ "WS_ERR_UNEXPECTED_RSV_2_3"
955
+ );
956
+ cb(error);
957
+ return;
958
+ }
959
+ const compressed = (buf[0] & 64) === 64;
960
+ if (compressed && !this._extensions[PerMessageDeflate2.extensionName]) {
961
+ const error = this.createError(
962
+ RangeError,
963
+ "RSV1 must be clear",
964
+ true,
965
+ 1002,
966
+ "WS_ERR_UNEXPECTED_RSV_1"
967
+ );
968
+ cb(error);
969
+ return;
970
+ }
971
+ this._fin = (buf[0] & 128) === 128;
972
+ this._opcode = buf[0] & 15;
973
+ this._payloadLength = buf[1] & 127;
974
+ if (this._opcode === 0) {
975
+ if (compressed) {
976
+ const error = this.createError(
977
+ RangeError,
978
+ "RSV1 must be clear",
979
+ true,
980
+ 1002,
981
+ "WS_ERR_UNEXPECTED_RSV_1"
982
+ );
983
+ cb(error);
984
+ return;
985
+ }
986
+ if (!this._fragmented) {
987
+ const error = this.createError(
988
+ RangeError,
989
+ "invalid opcode 0",
990
+ true,
991
+ 1002,
992
+ "WS_ERR_INVALID_OPCODE"
993
+ );
994
+ cb(error);
995
+ return;
996
+ }
997
+ this._opcode = this._fragmented;
998
+ } else if (this._opcode === 1 || this._opcode === 2) {
999
+ if (this._fragmented) {
1000
+ const error = this.createError(
1001
+ RangeError,
1002
+ `invalid opcode ${this._opcode}`,
1003
+ true,
1004
+ 1002,
1005
+ "WS_ERR_INVALID_OPCODE"
1006
+ );
1007
+ cb(error);
1008
+ return;
1009
+ }
1010
+ this._compressed = compressed;
1011
+ } else if (this._opcode > 7 && this._opcode < 11) {
1012
+ if (!this._fin) {
1013
+ const error = this.createError(
1014
+ RangeError,
1015
+ "FIN must be set",
1016
+ true,
1017
+ 1002,
1018
+ "WS_ERR_EXPECTED_FIN"
1019
+ );
1020
+ cb(error);
1021
+ return;
1022
+ }
1023
+ if (compressed) {
1024
+ const error = this.createError(
1025
+ RangeError,
1026
+ "RSV1 must be clear",
1027
+ true,
1028
+ 1002,
1029
+ "WS_ERR_UNEXPECTED_RSV_1"
1030
+ );
1031
+ cb(error);
1032
+ return;
1033
+ }
1034
+ if (this._payloadLength > 125 || this._opcode === 8 && this._payloadLength === 1) {
1035
+ const error = this.createError(
1036
+ RangeError,
1037
+ `invalid payload length ${this._payloadLength}`,
1038
+ true,
1039
+ 1002,
1040
+ "WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH"
1041
+ );
1042
+ cb(error);
1043
+ return;
1044
+ }
1045
+ } else {
1046
+ const error = this.createError(
1047
+ RangeError,
1048
+ `invalid opcode ${this._opcode}`,
1049
+ true,
1050
+ 1002,
1051
+ "WS_ERR_INVALID_OPCODE"
1052
+ );
1053
+ cb(error);
1054
+ return;
1055
+ }
1056
+ if (!this._fin && !this._fragmented) this._fragmented = this._opcode;
1057
+ this._masked = (buf[1] & 128) === 128;
1058
+ if (this._isServer) {
1059
+ if (!this._masked) {
1060
+ const error = this.createError(
1061
+ RangeError,
1062
+ "MASK must be set",
1063
+ true,
1064
+ 1002,
1065
+ "WS_ERR_EXPECTED_MASK"
1066
+ );
1067
+ cb(error);
1068
+ return;
1069
+ }
1070
+ } else if (this._masked) {
1071
+ const error = this.createError(
1072
+ RangeError,
1073
+ "MASK must be clear",
1074
+ true,
1075
+ 1002,
1076
+ "WS_ERR_UNEXPECTED_MASK"
1077
+ );
1078
+ cb(error);
1079
+ return;
1080
+ }
1081
+ if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16;
1082
+ else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64;
1083
+ else this.haveLength(cb);
1084
+ }
1085
+ /**
1086
+ * Gets extended payload length (7+16).
1087
+ *
1088
+ * @param {Function} cb Callback
1089
+ * @private
1090
+ */
1091
+ getPayloadLength16(cb) {
1092
+ if (this._bufferedBytes < 2) {
1093
+ this._loop = false;
1094
+ return;
1095
+ }
1096
+ this._payloadLength = this.consume(2).readUInt16BE(0);
1097
+ this.haveLength(cb);
1098
+ }
1099
+ /**
1100
+ * Gets extended payload length (7+64).
1101
+ *
1102
+ * @param {Function} cb Callback
1103
+ * @private
1104
+ */
1105
+ getPayloadLength64(cb) {
1106
+ if (this._bufferedBytes < 8) {
1107
+ this._loop = false;
1108
+ return;
1109
+ }
1110
+ const buf = this.consume(8);
1111
+ const num = buf.readUInt32BE(0);
1112
+ if (num > Math.pow(2, 53 - 32) - 1) {
1113
+ const error = this.createError(
1114
+ RangeError,
1115
+ "Unsupported WebSocket frame: payload length > 2^53 - 1",
1116
+ false,
1117
+ 1009,
1118
+ "WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH"
1119
+ );
1120
+ cb(error);
1121
+ return;
1122
+ }
1123
+ this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4);
1124
+ this.haveLength(cb);
1125
+ }
1126
+ /**
1127
+ * Payload length has been read.
1128
+ *
1129
+ * @param {Function} cb Callback
1130
+ * @private
1131
+ */
1132
+ haveLength(cb) {
1133
+ if (this._payloadLength && this._opcode < 8) {
1134
+ this._totalPayloadLength += this._payloadLength;
1135
+ if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) {
1136
+ const error = this.createError(
1137
+ RangeError,
1138
+ "Max payload size exceeded",
1139
+ false,
1140
+ 1009,
1141
+ "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"
1142
+ );
1143
+ cb(error);
1144
+ return;
1145
+ }
1146
+ }
1147
+ if (this._masked) this._state = GET_MASK;
1148
+ else this._state = GET_DATA;
1149
+ }
1150
+ /**
1151
+ * Reads mask bytes.
1152
+ *
1153
+ * @private
1154
+ */
1155
+ getMask() {
1156
+ if (this._bufferedBytes < 4) {
1157
+ this._loop = false;
1158
+ return;
1159
+ }
1160
+ this._mask = this.consume(4);
1161
+ this._state = GET_DATA;
1162
+ }
1163
+ /**
1164
+ * Reads data bytes.
1165
+ *
1166
+ * @param {Function} cb Callback
1167
+ * @private
1168
+ */
1169
+ getData(cb) {
1170
+ let data = EMPTY_BUFFER;
1171
+ if (this._payloadLength) {
1172
+ if (this._bufferedBytes < this._payloadLength) {
1173
+ this._loop = false;
1174
+ return;
1175
+ }
1176
+ data = this.consume(this._payloadLength);
1177
+ if (this._masked && (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0) {
1178
+ unmask(data, this._mask);
1179
+ }
1180
+ }
1181
+ if (this._opcode > 7) {
1182
+ this.controlMessage(data, cb);
1183
+ return;
1184
+ }
1185
+ if (this._maxFragments > 0 && ++this._numFragments > this._maxFragments) {
1186
+ const error = this.createError(
1187
+ RangeError,
1188
+ "Too many message fragments",
1189
+ false,
1190
+ 1008,
1191
+ "WS_ERR_TOO_MANY_BUFFERED_PARTS"
1192
+ );
1193
+ cb(error);
1194
+ return;
1195
+ }
1196
+ if (this._compressed) {
1197
+ this._state = INFLATING;
1198
+ this.decompress(data, cb);
1199
+ return;
1200
+ }
1201
+ if (data.length) {
1202
+ this._messageLength = this._totalPayloadLength;
1203
+ this._fragments.push(data);
1204
+ }
1205
+ this.dataMessage(cb);
1206
+ }
1207
+ /**
1208
+ * Decompresses data.
1209
+ *
1210
+ * @param {Buffer} data Compressed data
1211
+ * @param {Function} cb Callback
1212
+ * @private
1213
+ */
1214
+ decompress(data, cb) {
1215
+ const perMessageDeflate = this._extensions[PerMessageDeflate2.extensionName];
1216
+ perMessageDeflate.decompress(data, this._fin, (err, buf) => {
1217
+ if (err) return cb(err);
1218
+ if (buf.length) {
1219
+ this._messageLength += buf.length;
1220
+ if (this._messageLength > this._maxPayload && this._maxPayload > 0) {
1221
+ const error = this.createError(
1222
+ RangeError,
1223
+ "Max payload size exceeded",
1224
+ false,
1225
+ 1009,
1226
+ "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"
1227
+ );
1228
+ cb(error);
1229
+ return;
1230
+ }
1231
+ this._fragments.push(buf);
1232
+ }
1233
+ this.dataMessage(cb);
1234
+ if (this._state === GET_INFO) this.startLoop(cb);
1235
+ });
1236
+ }
1237
+ /**
1238
+ * Handles a data message.
1239
+ *
1240
+ * @param {Function} cb Callback
1241
+ * @private
1242
+ */
1243
+ dataMessage(cb) {
1244
+ if (!this._fin) {
1245
+ this._state = GET_INFO;
1246
+ return;
1247
+ }
1248
+ const messageLength = this._messageLength;
1249
+ const fragments = this._fragments;
1250
+ this._totalPayloadLength = 0;
1251
+ this._messageLength = 0;
1252
+ this._fragmented = 0;
1253
+ this._numFragments = 0;
1254
+ this._fragments = [];
1255
+ if (this._opcode === 2) {
1256
+ let data;
1257
+ if (this._binaryType === "nodebuffer") {
1258
+ data = concat(fragments, messageLength);
1259
+ } else if (this._binaryType === "arraybuffer") {
1260
+ data = toArrayBuffer(concat(fragments, messageLength));
1261
+ } else if (this._binaryType === "blob") {
1262
+ data = new Blob(fragments);
1263
+ } else {
1264
+ data = fragments;
1265
+ }
1266
+ if (this._allowSynchronousEvents) {
1267
+ this.emit("message", data, true);
1268
+ this._state = GET_INFO;
1269
+ } else {
1270
+ this._state = DEFER_EVENT;
1271
+ setImmediate(() => {
1272
+ this.emit("message", data, true);
1273
+ this._state = GET_INFO;
1274
+ this.startLoop(cb);
1275
+ });
1276
+ }
1277
+ } else {
1278
+ const buf = concat(fragments, messageLength);
1279
+ if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
1280
+ const error = this.createError(
1281
+ Error,
1282
+ "invalid UTF-8 sequence",
1283
+ true,
1284
+ 1007,
1285
+ "WS_ERR_INVALID_UTF8"
1286
+ );
1287
+ cb(error);
1288
+ return;
1289
+ }
1290
+ if (this._state === INFLATING || this._allowSynchronousEvents) {
1291
+ this.emit("message", buf, false);
1292
+ this._state = GET_INFO;
1293
+ } else {
1294
+ this._state = DEFER_EVENT;
1295
+ setImmediate(() => {
1296
+ this.emit("message", buf, false);
1297
+ this._state = GET_INFO;
1298
+ this.startLoop(cb);
1299
+ });
1300
+ }
1301
+ }
1302
+ }
1303
+ /**
1304
+ * Handles a control message.
1305
+ *
1306
+ * @param {Buffer} data Data to handle
1307
+ * @return {(Error|RangeError|undefined)} A possible error
1308
+ * @private
1309
+ */
1310
+ controlMessage(data, cb) {
1311
+ if (this._opcode === 8) {
1312
+ if (data.length === 0) {
1313
+ this._loop = false;
1314
+ this.emit("conclude", 1005, EMPTY_BUFFER);
1315
+ this.end();
1316
+ } else {
1317
+ const code = data.readUInt16BE(0);
1318
+ if (!isValidStatusCode(code)) {
1319
+ const error = this.createError(
1320
+ RangeError,
1321
+ `invalid status code ${code}`,
1322
+ true,
1323
+ 1002,
1324
+ "WS_ERR_INVALID_CLOSE_CODE"
1325
+ );
1326
+ cb(error);
1327
+ return;
1328
+ }
1329
+ const buf = new FastBuffer(
1330
+ data.buffer,
1331
+ data.byteOffset + 2,
1332
+ data.length - 2
1333
+ );
1334
+ if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
1335
+ const error = this.createError(
1336
+ Error,
1337
+ "invalid UTF-8 sequence",
1338
+ true,
1339
+ 1007,
1340
+ "WS_ERR_INVALID_UTF8"
1341
+ );
1342
+ cb(error);
1343
+ return;
1344
+ }
1345
+ this._loop = false;
1346
+ this.emit("conclude", code, buf);
1347
+ this.end();
1348
+ }
1349
+ this._state = GET_INFO;
1350
+ return;
1351
+ }
1352
+ if (this._allowSynchronousEvents) {
1353
+ this.emit(this._opcode === 9 ? "ping" : "pong", data);
1354
+ this._state = GET_INFO;
1355
+ } else {
1356
+ this._state = DEFER_EVENT;
1357
+ setImmediate(() => {
1358
+ this.emit(this._opcode === 9 ? "ping" : "pong", data);
1359
+ this._state = GET_INFO;
1360
+ this.startLoop(cb);
1361
+ });
1362
+ }
1363
+ }
1364
+ /**
1365
+ * Builds an error object.
1366
+ *
1367
+ * @param {function(new:Error|RangeError)} ErrorCtor The error constructor
1368
+ * @param {String} message The error message
1369
+ * @param {Boolean} prefix Specifies whether or not to add a default prefix to
1370
+ * `message`
1371
+ * @param {Number} statusCode The status code
1372
+ * @param {String} errorCode The exposed error code
1373
+ * @return {(Error|RangeError)} The error
1374
+ * @private
1375
+ */
1376
+ createError(ErrorCtor, message, prefix, statusCode, errorCode) {
1377
+ this._loop = false;
1378
+ this._errored = true;
1379
+ const err = new ErrorCtor(
1380
+ prefix ? `Invalid WebSocket frame: ${message}` : message
1381
+ );
1382
+ Error.captureStackTrace(err, this.createError);
1383
+ err.code = errorCode;
1384
+ err[kStatusCode] = statusCode;
1385
+ return err;
1386
+ }
1387
+ };
1388
+ module2.exports = Receiver2;
1389
+ }
1390
+ });
1391
+
1392
+ // node_modules/ws/lib/sender.js
1393
+ var require_sender = __commonJS({
1394
+ "node_modules/ws/lib/sender.js"(exports2, module2) {
1395
+ "use strict";
1396
+ var { Duplex } = require("stream");
1397
+ var { randomFillSync } = require("crypto");
1398
+ var {
1399
+ types: { isUint8Array }
1400
+ } = require("util");
1401
+ var PerMessageDeflate2 = require_permessage_deflate();
1402
+ var { EMPTY_BUFFER, kWebSocket, NOOP } = require_constants();
1403
+ var { isBlob, isValidStatusCode } = require_validation();
1404
+ var { mask: applyMask, toBuffer } = require_buffer_util();
1405
+ var kByteLength = /* @__PURE__ */ Symbol("kByteLength");
1406
+ var maskBuffer = Buffer.alloc(4);
1407
+ var RANDOM_POOL_SIZE = 8 * 1024;
1408
+ var randomPool;
1409
+ var randomPoolPointer = RANDOM_POOL_SIZE;
1410
+ var DEFAULT = 0;
1411
+ var DEFLATING = 1;
1412
+ var GET_BLOB_DATA = 2;
1413
+ var Sender2 = class _Sender {
1414
+ /**
1415
+ * Creates a Sender instance.
1416
+ *
1417
+ * @param {Duplex} socket The connection socket
1418
+ * @param {Object} [extensions] An object containing the negotiated extensions
1419
+ * @param {Function} [generateMask] The function used to generate the masking
1420
+ * key
1421
+ */
1422
+ constructor(socket, extensions, generateMask) {
1423
+ this._extensions = extensions || {};
1424
+ if (generateMask) {
1425
+ this._generateMask = generateMask;
1426
+ this._maskBuffer = Buffer.alloc(4);
1427
+ }
1428
+ this._socket = socket;
1429
+ this._firstFragment = true;
1430
+ this._compress = false;
1431
+ this._bufferedBytes = 0;
1432
+ this._queue = [];
1433
+ this._state = DEFAULT;
1434
+ this.onerror = NOOP;
1435
+ this[kWebSocket] = void 0;
1436
+ }
1437
+ /**
1438
+ * Frames a piece of data according to the HyBi WebSocket protocol.
1439
+ *
1440
+ * @param {(Buffer|String)} data The data to frame
1441
+ * @param {Object} options Options object
1442
+ * @param {Boolean} [options.fin=false] Specifies whether or not to set the
1443
+ * FIN bit
1444
+ * @param {Function} [options.generateMask] The function used to generate the
1445
+ * masking key
1446
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1447
+ * `data`
1448
+ * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
1449
+ * key
1450
+ * @param {Number} options.opcode The opcode
1451
+ * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
1452
+ * modified
1453
+ * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
1454
+ * RSV1 bit
1455
+ * @return {(Buffer|String)[]} The framed data
1456
+ * @public
1457
+ */
1458
+ static frame(data, options) {
1459
+ let mask;
1460
+ let merge = false;
1461
+ let offset = 2;
1462
+ let skipMasking = false;
1463
+ if (options.mask) {
1464
+ mask = options.maskBuffer || maskBuffer;
1465
+ if (options.generateMask) {
1466
+ options.generateMask(mask);
1467
+ } else {
1468
+ if (randomPoolPointer === RANDOM_POOL_SIZE) {
1469
+ if (randomPool === void 0) {
1470
+ randomPool = Buffer.alloc(RANDOM_POOL_SIZE);
1471
+ }
1472
+ randomFillSync(randomPool, 0, RANDOM_POOL_SIZE);
1473
+ randomPoolPointer = 0;
1474
+ }
1475
+ mask[0] = randomPool[randomPoolPointer++];
1476
+ mask[1] = randomPool[randomPoolPointer++];
1477
+ mask[2] = randomPool[randomPoolPointer++];
1478
+ mask[3] = randomPool[randomPoolPointer++];
1479
+ }
1480
+ skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0;
1481
+ offset = 6;
1482
+ }
1483
+ let dataLength;
1484
+ if (typeof data === "string") {
1485
+ if ((!options.mask || skipMasking) && options[kByteLength] !== void 0) {
1486
+ dataLength = options[kByteLength];
1487
+ } else {
1488
+ data = Buffer.from(data);
1489
+ dataLength = data.length;
1490
+ }
1491
+ } else {
1492
+ dataLength = data.length;
1493
+ merge = options.mask && options.readOnly && !skipMasking;
1494
+ }
1495
+ let payloadLength = dataLength;
1496
+ if (dataLength >= 65536) {
1497
+ offset += 8;
1498
+ payloadLength = 127;
1499
+ } else if (dataLength > 125) {
1500
+ offset += 2;
1501
+ payloadLength = 126;
1502
+ }
1503
+ const target = Buffer.allocUnsafe(merge ? dataLength + offset : offset);
1504
+ target[0] = options.fin ? options.opcode | 128 : options.opcode;
1505
+ if (options.rsv1) target[0] |= 64;
1506
+ target[1] = payloadLength;
1507
+ if (payloadLength === 126) {
1508
+ target.writeUInt16BE(dataLength, 2);
1509
+ } else if (payloadLength === 127) {
1510
+ target[2] = target[3] = 0;
1511
+ target.writeUIntBE(dataLength, 4, 6);
1512
+ }
1513
+ if (!options.mask) return [target, data];
1514
+ target[1] |= 128;
1515
+ target[offset - 4] = mask[0];
1516
+ target[offset - 3] = mask[1];
1517
+ target[offset - 2] = mask[2];
1518
+ target[offset - 1] = mask[3];
1519
+ if (skipMasking) return [target, data];
1520
+ if (merge) {
1521
+ applyMask(data, mask, target, offset, dataLength);
1522
+ return [target];
1523
+ }
1524
+ applyMask(data, mask, data, 0, dataLength);
1525
+ return [target, data];
1526
+ }
1527
+ /**
1528
+ * Sends a close message to the other peer.
1529
+ *
1530
+ * @param {Number} [code] The status code component of the body
1531
+ * @param {(String|Buffer)} [data] The message component of the body
1532
+ * @param {Boolean} [mask=false] Specifies whether or not to mask the message
1533
+ * @param {Function} [cb] Callback
1534
+ * @public
1535
+ */
1536
+ close(code, data, mask, cb) {
1537
+ let buf;
1538
+ if (code === void 0) {
1539
+ buf = EMPTY_BUFFER;
1540
+ } else if (typeof code !== "number" || !isValidStatusCode(code)) {
1541
+ throw new TypeError("First argument must be a valid error code number");
1542
+ } else if (data === void 0 || !data.length) {
1543
+ buf = Buffer.allocUnsafe(2);
1544
+ buf.writeUInt16BE(code, 0);
1545
+ } else {
1546
+ const length = Buffer.byteLength(data);
1547
+ if (length > 123) {
1548
+ throw new RangeError("The message must not be greater than 123 bytes");
1549
+ }
1550
+ buf = Buffer.allocUnsafe(2 + length);
1551
+ buf.writeUInt16BE(code, 0);
1552
+ if (typeof data === "string") {
1553
+ buf.write(data, 2);
1554
+ } else if (isUint8Array(data)) {
1555
+ buf.set(data, 2);
1556
+ } else {
1557
+ throw new TypeError("Second argument must be a string or a Uint8Array");
1558
+ }
1559
+ }
1560
+ const options = {
1561
+ [kByteLength]: buf.length,
1562
+ fin: true,
1563
+ generateMask: this._generateMask,
1564
+ mask,
1565
+ maskBuffer: this._maskBuffer,
1566
+ opcode: 8,
1567
+ readOnly: false,
1568
+ rsv1: false
1569
+ };
1570
+ if (this._state !== DEFAULT) {
1571
+ this.enqueue([this.dispatch, buf, false, options, cb]);
1572
+ } else {
1573
+ this.sendFrame(_Sender.frame(buf, options), cb);
1574
+ }
1575
+ }
1576
+ /**
1577
+ * Sends a ping message to the other peer.
1578
+ *
1579
+ * @param {*} data The message to send
1580
+ * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
1581
+ * @param {Function} [cb] Callback
1582
+ * @public
1583
+ */
1584
+ ping(data, mask, cb) {
1585
+ let byteLength;
1586
+ let readOnly;
1587
+ if (typeof data === "string") {
1588
+ byteLength = Buffer.byteLength(data);
1589
+ readOnly = false;
1590
+ } else if (isBlob(data)) {
1591
+ byteLength = data.size;
1592
+ readOnly = false;
1593
+ } else {
1594
+ data = toBuffer(data);
1595
+ byteLength = data.length;
1596
+ readOnly = toBuffer.readOnly;
1597
+ }
1598
+ if (byteLength > 125) {
1599
+ throw new RangeError("The data size must not be greater than 125 bytes");
1600
+ }
1601
+ const options = {
1602
+ [kByteLength]: byteLength,
1603
+ fin: true,
1604
+ generateMask: this._generateMask,
1605
+ mask,
1606
+ maskBuffer: this._maskBuffer,
1607
+ opcode: 9,
1608
+ readOnly,
1609
+ rsv1: false
1610
+ };
1611
+ if (isBlob(data)) {
1612
+ if (this._state !== DEFAULT) {
1613
+ this.enqueue([this.getBlobData, data, false, options, cb]);
1614
+ } else {
1615
+ this.getBlobData(data, false, options, cb);
1616
+ }
1617
+ } else if (this._state !== DEFAULT) {
1618
+ this.enqueue([this.dispatch, data, false, options, cb]);
1619
+ } else {
1620
+ this.sendFrame(_Sender.frame(data, options), cb);
1621
+ }
1622
+ }
1623
+ /**
1624
+ * Sends a pong message to the other peer.
1625
+ *
1626
+ * @param {*} data The message to send
1627
+ * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
1628
+ * @param {Function} [cb] Callback
1629
+ * @public
1630
+ */
1631
+ pong(data, mask, cb) {
1632
+ let byteLength;
1633
+ let readOnly;
1634
+ if (typeof data === "string") {
1635
+ byteLength = Buffer.byteLength(data);
1636
+ readOnly = false;
1637
+ } else if (isBlob(data)) {
1638
+ byteLength = data.size;
1639
+ readOnly = false;
1640
+ } else {
1641
+ data = toBuffer(data);
1642
+ byteLength = data.length;
1643
+ readOnly = toBuffer.readOnly;
1644
+ }
1645
+ if (byteLength > 125) {
1646
+ throw new RangeError("The data size must not be greater than 125 bytes");
1647
+ }
1648
+ const options = {
1649
+ [kByteLength]: byteLength,
1650
+ fin: true,
1651
+ generateMask: this._generateMask,
1652
+ mask,
1653
+ maskBuffer: this._maskBuffer,
1654
+ opcode: 10,
1655
+ readOnly,
1656
+ rsv1: false
1657
+ };
1658
+ if (isBlob(data)) {
1659
+ if (this._state !== DEFAULT) {
1660
+ this.enqueue([this.getBlobData, data, false, options, cb]);
1661
+ } else {
1662
+ this.getBlobData(data, false, options, cb);
1663
+ }
1664
+ } else if (this._state !== DEFAULT) {
1665
+ this.enqueue([this.dispatch, data, false, options, cb]);
1666
+ } else {
1667
+ this.sendFrame(_Sender.frame(data, options), cb);
1668
+ }
1669
+ }
1670
+ /**
1671
+ * Sends a data message to the other peer.
1672
+ *
1673
+ * @param {*} data The message to send
1674
+ * @param {Object} options Options object
1675
+ * @param {Boolean} [options.binary=false] Specifies whether `data` is binary
1676
+ * or text
1677
+ * @param {Boolean} [options.compress=false] Specifies whether or not to
1678
+ * compress `data`
1679
+ * @param {Boolean} [options.fin=false] Specifies whether the fragment is the
1680
+ * last one
1681
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1682
+ * `data`
1683
+ * @param {Function} [cb] Callback
1684
+ * @public
1685
+ */
1686
+ send(data, options, cb) {
1687
+ const perMessageDeflate = this._extensions[PerMessageDeflate2.extensionName];
1688
+ let opcode = options.binary ? 2 : 1;
1689
+ let rsv1 = options.compress;
1690
+ let byteLength;
1691
+ let readOnly;
1692
+ if (typeof data === "string") {
1693
+ byteLength = Buffer.byteLength(data);
1694
+ readOnly = false;
1695
+ } else if (isBlob(data)) {
1696
+ byteLength = data.size;
1697
+ readOnly = false;
1698
+ } else {
1699
+ data = toBuffer(data);
1700
+ byteLength = data.length;
1701
+ readOnly = toBuffer.readOnly;
1702
+ }
1703
+ if (this._firstFragment) {
1704
+ this._firstFragment = false;
1705
+ if (rsv1 && perMessageDeflate && perMessageDeflate.params[perMessageDeflate._isServer ? "server_no_context_takeover" : "client_no_context_takeover"]) {
1706
+ rsv1 = byteLength >= perMessageDeflate._threshold;
1707
+ }
1708
+ this._compress = rsv1;
1709
+ } else {
1710
+ rsv1 = false;
1711
+ opcode = 0;
1712
+ }
1713
+ if (options.fin) this._firstFragment = true;
1714
+ const opts = {
1715
+ [kByteLength]: byteLength,
1716
+ fin: options.fin,
1717
+ generateMask: this._generateMask,
1718
+ mask: options.mask,
1719
+ maskBuffer: this._maskBuffer,
1720
+ opcode,
1721
+ readOnly,
1722
+ rsv1
1723
+ };
1724
+ if (isBlob(data)) {
1725
+ if (this._state !== DEFAULT) {
1726
+ this.enqueue([this.getBlobData, data, this._compress, opts, cb]);
1727
+ } else {
1728
+ this.getBlobData(data, this._compress, opts, cb);
1729
+ }
1730
+ } else if (this._state !== DEFAULT) {
1731
+ this.enqueue([this.dispatch, data, this._compress, opts, cb]);
1732
+ } else {
1733
+ this.dispatch(data, this._compress, opts, cb);
1734
+ }
1735
+ }
1736
+ /**
1737
+ * Gets the contents of a blob as binary data.
1738
+ *
1739
+ * @param {Blob} blob The blob
1740
+ * @param {Boolean} [compress=false] Specifies whether or not to compress
1741
+ * the data
1742
+ * @param {Object} options Options object
1743
+ * @param {Boolean} [options.fin=false] Specifies whether or not to set the
1744
+ * FIN bit
1745
+ * @param {Function} [options.generateMask] The function used to generate the
1746
+ * masking key
1747
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1748
+ * `data`
1749
+ * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
1750
+ * key
1751
+ * @param {Number} options.opcode The opcode
1752
+ * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
1753
+ * modified
1754
+ * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
1755
+ * RSV1 bit
1756
+ * @param {Function} [cb] Callback
1757
+ * @private
1758
+ */
1759
+ getBlobData(blob, compress, options, cb) {
1760
+ this._bufferedBytes += options[kByteLength];
1761
+ this._state = GET_BLOB_DATA;
1762
+ blob.arrayBuffer().then((arrayBuffer) => {
1763
+ if (this._socket.destroyed) {
1764
+ const err = new Error(
1765
+ "The socket was closed while the blob was being read"
1766
+ );
1767
+ process.nextTick(callCallbacks, this, err, cb);
1768
+ return;
1769
+ }
1770
+ this._bufferedBytes -= options[kByteLength];
1771
+ const data = toBuffer(arrayBuffer);
1772
+ if (!compress) {
1773
+ this._state = DEFAULT;
1774
+ this.sendFrame(_Sender.frame(data, options), cb);
1775
+ this.dequeue();
1776
+ } else {
1777
+ this.dispatch(data, compress, options, cb);
1778
+ }
1779
+ }).catch((err) => {
1780
+ process.nextTick(onError, this, err, cb);
1781
+ });
1782
+ }
1783
+ /**
1784
+ * Dispatches a message.
1785
+ *
1786
+ * @param {(Buffer|String)} data The message to send
1787
+ * @param {Boolean} [compress=false] Specifies whether or not to compress
1788
+ * `data`
1789
+ * @param {Object} options Options object
1790
+ * @param {Boolean} [options.fin=false] Specifies whether or not to set the
1791
+ * FIN bit
1792
+ * @param {Function} [options.generateMask] The function used to generate the
1793
+ * masking key
1794
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1795
+ * `data`
1796
+ * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
1797
+ * key
1798
+ * @param {Number} options.opcode The opcode
1799
+ * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
1800
+ * modified
1801
+ * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
1802
+ * RSV1 bit
1803
+ * @param {Function} [cb] Callback
1804
+ * @private
1805
+ */
1806
+ dispatch(data, compress, options, cb) {
1807
+ if (!compress) {
1808
+ this.sendFrame(_Sender.frame(data, options), cb);
1809
+ return;
1810
+ }
1811
+ const perMessageDeflate = this._extensions[PerMessageDeflate2.extensionName];
1812
+ this._bufferedBytes += options[kByteLength];
1813
+ this._state = DEFLATING;
1814
+ perMessageDeflate.compress(data, options.fin, (_, buf) => {
1815
+ if (this._socket.destroyed) {
1816
+ const err = new Error(
1817
+ "The socket was closed while data was being compressed"
1818
+ );
1819
+ callCallbacks(this, err, cb);
1820
+ return;
1821
+ }
1822
+ this._bufferedBytes -= options[kByteLength];
1823
+ this._state = DEFAULT;
1824
+ options.readOnly = false;
1825
+ this.sendFrame(_Sender.frame(buf, options), cb);
1826
+ this.dequeue();
1827
+ });
1828
+ }
1829
+ /**
1830
+ * Executes queued send operations.
1831
+ *
1832
+ * @private
1833
+ */
1834
+ dequeue() {
1835
+ while (this._state === DEFAULT && this._queue.length) {
1836
+ const params = this._queue.shift();
1837
+ this._bufferedBytes -= params[3][kByteLength];
1838
+ Reflect.apply(params[0], this, params.slice(1));
1839
+ }
1840
+ }
1841
+ /**
1842
+ * Enqueues a send operation.
1843
+ *
1844
+ * @param {Array} params Send operation parameters.
1845
+ * @private
1846
+ */
1847
+ enqueue(params) {
1848
+ this._bufferedBytes += params[3][kByteLength];
1849
+ this._queue.push(params);
1850
+ }
1851
+ /**
1852
+ * Sends a frame.
1853
+ *
1854
+ * @param {(Buffer | String)[]} list The frame to send
1855
+ * @param {Function} [cb] Callback
1856
+ * @private
1857
+ */
1858
+ sendFrame(list, cb) {
1859
+ if (list.length === 2) {
1860
+ this._socket.cork();
1861
+ this._socket.write(list[0]);
1862
+ this._socket.write(list[1], cb);
1863
+ this._socket.uncork();
1864
+ } else {
1865
+ this._socket.write(list[0], cb);
1866
+ }
1867
+ }
1868
+ };
1869
+ module2.exports = Sender2;
1870
+ function callCallbacks(sender, err, cb) {
1871
+ if (typeof cb === "function") cb(err);
1872
+ for (let i = 0; i < sender._queue.length; i++) {
1873
+ const params = sender._queue[i];
1874
+ const callback = params[params.length - 1];
1875
+ if (typeof callback === "function") callback(err);
1876
+ }
1877
+ }
1878
+ function onError(sender, err, cb) {
1879
+ callCallbacks(sender, err, cb);
1880
+ sender.onerror(err);
1881
+ }
1882
+ }
1883
+ });
1884
+
1885
+ // node_modules/ws/lib/event-target.js
1886
+ var require_event_target = __commonJS({
1887
+ "node_modules/ws/lib/event-target.js"(exports2, module2) {
1888
+ "use strict";
1889
+ var { kForOnEventAttribute, kListener } = require_constants();
1890
+ var kCode = /* @__PURE__ */ Symbol("kCode");
1891
+ var kData = /* @__PURE__ */ Symbol("kData");
1892
+ var kError = /* @__PURE__ */ Symbol("kError");
1893
+ var kMessage = /* @__PURE__ */ Symbol("kMessage");
1894
+ var kReason = /* @__PURE__ */ Symbol("kReason");
1895
+ var kTarget = /* @__PURE__ */ Symbol("kTarget");
1896
+ var kType = /* @__PURE__ */ Symbol("kType");
1897
+ var kWasClean = /* @__PURE__ */ Symbol("kWasClean");
1898
+ var Event = class {
1899
+ /**
1900
+ * Create a new `Event`.
1901
+ *
1902
+ * @param {String} type The name of the event
1903
+ * @throws {TypeError} If the `type` argument is not specified
1904
+ */
1905
+ constructor(type) {
1906
+ this[kTarget] = null;
1907
+ this[kType] = type;
1908
+ }
1909
+ /**
1910
+ * @type {*}
1911
+ */
1912
+ get target() {
1913
+ return this[kTarget];
1914
+ }
1915
+ /**
1916
+ * @type {String}
1917
+ */
1918
+ get type() {
1919
+ return this[kType];
1920
+ }
1921
+ };
1922
+ Object.defineProperty(Event.prototype, "target", { enumerable: true });
1923
+ Object.defineProperty(Event.prototype, "type", { enumerable: true });
1924
+ var CloseEvent = class extends Event {
1925
+ /**
1926
+ * Create a new `CloseEvent`.
1927
+ *
1928
+ * @param {String} type The name of the event
1929
+ * @param {Object} [options] A dictionary object that allows for setting
1930
+ * attributes via object members of the same name
1931
+ * @param {Number} [options.code=0] The status code explaining why the
1932
+ * connection was closed
1933
+ * @param {String} [options.reason=''] A human-readable string explaining why
1934
+ * the connection was closed
1935
+ * @param {Boolean} [options.wasClean=false] Indicates whether or not the
1936
+ * connection was cleanly closed
1937
+ */
1938
+ constructor(type, options = {}) {
1939
+ super(type);
1940
+ this[kCode] = options.code === void 0 ? 0 : options.code;
1941
+ this[kReason] = options.reason === void 0 ? "" : options.reason;
1942
+ this[kWasClean] = options.wasClean === void 0 ? false : options.wasClean;
1943
+ }
1944
+ /**
1945
+ * @type {Number}
1946
+ */
1947
+ get code() {
1948
+ return this[kCode];
1949
+ }
1950
+ /**
1951
+ * @type {String}
1952
+ */
1953
+ get reason() {
1954
+ return this[kReason];
1955
+ }
1956
+ /**
1957
+ * @type {Boolean}
1958
+ */
1959
+ get wasClean() {
1960
+ return this[kWasClean];
1961
+ }
1962
+ };
1963
+ Object.defineProperty(CloseEvent.prototype, "code", { enumerable: true });
1964
+ Object.defineProperty(CloseEvent.prototype, "reason", { enumerable: true });
1965
+ Object.defineProperty(CloseEvent.prototype, "wasClean", { enumerable: true });
1966
+ var ErrorEvent = class extends Event {
1967
+ /**
1968
+ * Create a new `ErrorEvent`.
1969
+ *
1970
+ * @param {String} type The name of the event
1971
+ * @param {Object} [options] A dictionary object that allows for setting
1972
+ * attributes via object members of the same name
1973
+ * @param {*} [options.error=null] The error that generated this event
1974
+ * @param {String} [options.message=''] The error message
1975
+ */
1976
+ constructor(type, options = {}) {
1977
+ super(type);
1978
+ this[kError] = options.error === void 0 ? null : options.error;
1979
+ this[kMessage] = options.message === void 0 ? "" : options.message;
1980
+ }
1981
+ /**
1982
+ * @type {*}
1983
+ */
1984
+ get error() {
1985
+ return this[kError];
1986
+ }
1987
+ /**
1988
+ * @type {String}
1989
+ */
1990
+ get message() {
1991
+ return this[kMessage];
1992
+ }
1993
+ };
1994
+ Object.defineProperty(ErrorEvent.prototype, "error", { enumerable: true });
1995
+ Object.defineProperty(ErrorEvent.prototype, "message", { enumerable: true });
1996
+ var MessageEvent = class extends Event {
1997
+ /**
1998
+ * Create a new `MessageEvent`.
1999
+ *
2000
+ * @param {String} type The name of the event
2001
+ * @param {Object} [options] A dictionary object that allows for setting
2002
+ * attributes via object members of the same name
2003
+ * @param {*} [options.data=null] The message content
2004
+ */
2005
+ constructor(type, options = {}) {
2006
+ super(type);
2007
+ this[kData] = options.data === void 0 ? null : options.data;
2008
+ }
2009
+ /**
2010
+ * @type {*}
2011
+ */
2012
+ get data() {
2013
+ return this[kData];
2014
+ }
2015
+ };
2016
+ Object.defineProperty(MessageEvent.prototype, "data", { enumerable: true });
2017
+ var EventTarget = {
2018
+ /**
2019
+ * Register an event listener.
2020
+ *
2021
+ * @param {String} type A string representing the event type to listen for
2022
+ * @param {(Function|Object)} handler The listener to add
2023
+ * @param {Object} [options] An options object specifies characteristics about
2024
+ * the event listener
2025
+ * @param {Boolean} [options.once=false] A `Boolean` indicating that the
2026
+ * listener should be invoked at most once after being added. If `true`,
2027
+ * the listener would be automatically removed when invoked.
2028
+ * @public
2029
+ */
2030
+ addEventListener(type, handler, options = {}) {
2031
+ for (const listener of this.listeners(type)) {
2032
+ if (!options[kForOnEventAttribute] && listener[kListener] === handler && !listener[kForOnEventAttribute]) {
2033
+ return;
2034
+ }
2035
+ }
2036
+ let wrapper;
2037
+ if (type === "message") {
2038
+ wrapper = function onMessage(data, isBinary) {
2039
+ const event = new MessageEvent("message", {
2040
+ data: isBinary ? data : data.toString()
2041
+ });
2042
+ event[kTarget] = this;
2043
+ callListener(handler, this, event);
2044
+ };
2045
+ } else if (type === "close") {
2046
+ wrapper = function onClose(code, message) {
2047
+ const event = new CloseEvent("close", {
2048
+ code,
2049
+ reason: message.toString(),
2050
+ wasClean: this._closeFrameReceived && this._closeFrameSent
2051
+ });
2052
+ event[kTarget] = this;
2053
+ callListener(handler, this, event);
2054
+ };
2055
+ } else if (type === "error") {
2056
+ wrapper = function onError(error) {
2057
+ const event = new ErrorEvent("error", {
2058
+ error,
2059
+ message: error.message
2060
+ });
2061
+ event[kTarget] = this;
2062
+ callListener(handler, this, event);
2063
+ };
2064
+ } else if (type === "open") {
2065
+ wrapper = function onOpen() {
2066
+ const event = new Event("open");
2067
+ event[kTarget] = this;
2068
+ callListener(handler, this, event);
2069
+ };
2070
+ } else {
2071
+ return;
2072
+ }
2073
+ wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute];
2074
+ wrapper[kListener] = handler;
2075
+ if (options.once) {
2076
+ this.once(type, wrapper);
2077
+ } else {
2078
+ this.on(type, wrapper);
2079
+ }
2080
+ },
2081
+ /**
2082
+ * Remove an event listener.
2083
+ *
2084
+ * @param {String} type A string representing the event type to remove
2085
+ * @param {(Function|Object)} handler The listener to remove
2086
+ * @public
2087
+ */
2088
+ removeEventListener(type, handler) {
2089
+ for (const listener of this.listeners(type)) {
2090
+ if (listener[kListener] === handler && !listener[kForOnEventAttribute]) {
2091
+ this.removeListener(type, listener);
2092
+ break;
2093
+ }
2094
+ }
2095
+ }
2096
+ };
2097
+ module2.exports = {
2098
+ CloseEvent,
2099
+ ErrorEvent,
2100
+ Event,
2101
+ EventTarget,
2102
+ MessageEvent
2103
+ };
2104
+ function callListener(listener, thisArg, event) {
2105
+ if (typeof listener === "object" && listener.handleEvent) {
2106
+ listener.handleEvent.call(listener, event);
2107
+ } else {
2108
+ listener.call(thisArg, event);
2109
+ }
2110
+ }
2111
+ }
2112
+ });
2113
+
2114
+ // node_modules/ws/lib/extension.js
2115
+ var require_extension = __commonJS({
2116
+ "node_modules/ws/lib/extension.js"(exports2, module2) {
2117
+ "use strict";
2118
+ var { tokenChars } = require_validation();
2119
+ function push(dest, name, elem) {
2120
+ if (dest[name] === void 0) dest[name] = [elem];
2121
+ else dest[name].push(elem);
2122
+ }
2123
+ function parse2(header) {
2124
+ const offers = /* @__PURE__ */ Object.create(null);
2125
+ let params = /* @__PURE__ */ Object.create(null);
2126
+ let mustUnescape = false;
2127
+ let isEscaping = false;
2128
+ let inQuotes = false;
2129
+ let extensionName;
2130
+ let paramName;
2131
+ let start = -1;
2132
+ let code = -1;
2133
+ let end = -1;
2134
+ let i = 0;
2135
+ for (; i < header.length; i++) {
2136
+ code = header.charCodeAt(i);
2137
+ if (extensionName === void 0) {
2138
+ if (end === -1 && tokenChars[code] === 1) {
2139
+ if (start === -1) start = i;
2140
+ } else if (i !== 0 && (code === 32 || code === 9)) {
2141
+ if (end === -1 && start !== -1) end = i;
2142
+ } else if (code === 59 || code === 44) {
2143
+ if (start === -1) {
2144
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2145
+ }
2146
+ if (end === -1) end = i;
2147
+ const name = header.slice(start, end);
2148
+ if (code === 44) {
2149
+ push(offers, name, params);
2150
+ params = /* @__PURE__ */ Object.create(null);
2151
+ } else {
2152
+ extensionName = name;
2153
+ }
2154
+ start = end = -1;
2155
+ } else {
2156
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2157
+ }
2158
+ } else if (paramName === void 0) {
2159
+ if (end === -1 && tokenChars[code] === 1) {
2160
+ if (start === -1) start = i;
2161
+ } else if (code === 32 || code === 9) {
2162
+ if (end === -1 && start !== -1) end = i;
2163
+ } else if (code === 59 || code === 44) {
2164
+ if (start === -1) {
2165
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2166
+ }
2167
+ if (end === -1) end = i;
2168
+ push(params, header.slice(start, end), true);
2169
+ if (code === 44) {
2170
+ push(offers, extensionName, params);
2171
+ params = /* @__PURE__ */ Object.create(null);
2172
+ extensionName = void 0;
2173
+ }
2174
+ start = end = -1;
2175
+ } else if (code === 61 && start !== -1 && end === -1) {
2176
+ paramName = header.slice(start, i);
2177
+ start = end = -1;
2178
+ } else {
2179
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2180
+ }
2181
+ } else {
2182
+ if (isEscaping) {
2183
+ if (tokenChars[code] !== 1) {
2184
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2185
+ }
2186
+ if (start === -1) start = i;
2187
+ else if (!mustUnescape) mustUnescape = true;
2188
+ isEscaping = false;
2189
+ } else if (inQuotes) {
2190
+ if (tokenChars[code] === 1) {
2191
+ if (start === -1) start = i;
2192
+ } else if (code === 34 && start !== -1) {
2193
+ inQuotes = false;
2194
+ end = i;
2195
+ } else if (code === 92) {
2196
+ isEscaping = true;
2197
+ } else {
2198
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2199
+ }
2200
+ } else if (code === 34 && header.charCodeAt(i - 1) === 61) {
2201
+ inQuotes = true;
2202
+ } else if (end === -1 && tokenChars[code] === 1) {
2203
+ if (start === -1) start = i;
2204
+ } else if (start !== -1 && (code === 32 || code === 9)) {
2205
+ if (end === -1) end = i;
2206
+ } else if (code === 59 || code === 44) {
2207
+ if (start === -1) {
2208
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2209
+ }
2210
+ if (end === -1) end = i;
2211
+ let value = header.slice(start, end);
2212
+ if (mustUnescape) {
2213
+ value = value.replace(/\\/g, "");
2214
+ mustUnescape = false;
2215
+ }
2216
+ push(params, paramName, value);
2217
+ if (code === 44) {
2218
+ push(offers, extensionName, params);
2219
+ params = /* @__PURE__ */ Object.create(null);
2220
+ extensionName = void 0;
2221
+ }
2222
+ paramName = void 0;
2223
+ start = end = -1;
2224
+ } else {
2225
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2226
+ }
2227
+ }
2228
+ }
2229
+ if (start === -1 || inQuotes || code === 32 || code === 9) {
2230
+ throw new SyntaxError("Unexpected end of input");
2231
+ }
2232
+ if (end === -1) end = i;
2233
+ const token = header.slice(start, end);
2234
+ if (extensionName === void 0) {
2235
+ push(offers, token, params);
2236
+ } else {
2237
+ if (paramName === void 0) {
2238
+ push(params, token, true);
2239
+ } else if (mustUnescape) {
2240
+ push(params, paramName, token.replace(/\\/g, ""));
2241
+ } else {
2242
+ push(params, paramName, token);
2243
+ }
2244
+ push(offers, extensionName, params);
2245
+ }
2246
+ return offers;
2247
+ }
2248
+ function format(extensions) {
2249
+ return Object.keys(extensions).map((extension2) => {
2250
+ let configurations = extensions[extension2];
2251
+ if (!Array.isArray(configurations)) configurations = [configurations];
2252
+ return configurations.map((params) => {
2253
+ return [extension2].concat(
2254
+ Object.keys(params).map((k) => {
2255
+ let values = params[k];
2256
+ if (!Array.isArray(values)) values = [values];
2257
+ return values.map((v) => v === true ? k : `${k}=${v}`).join("; ");
2258
+ })
2259
+ ).join("; ");
2260
+ }).join(", ");
2261
+ }).join(", ");
2262
+ }
2263
+ module2.exports = { format, parse: parse2 };
2264
+ }
2265
+ });
2266
+
2267
+ // node_modules/ws/lib/websocket.js
2268
+ var require_websocket = __commonJS({
2269
+ "node_modules/ws/lib/websocket.js"(exports2, module2) {
2270
+ "use strict";
2271
+ var EventEmitter = require("events");
2272
+ var https = require("https");
2273
+ var http = require("http");
2274
+ var net = require("net");
2275
+ var tls = require("tls");
2276
+ var { randomBytes, createHash: createHash10 } = require("crypto");
2277
+ var { Duplex, Readable } = require("stream");
2278
+ var { URL: URL2 } = require("url");
2279
+ var PerMessageDeflate2 = require_permessage_deflate();
2280
+ var Receiver2 = require_receiver();
2281
+ var Sender2 = require_sender();
2282
+ var { isBlob } = require_validation();
2283
+ var {
2284
+ BINARY_TYPES,
2285
+ CLOSE_TIMEOUT,
2286
+ EMPTY_BUFFER,
2287
+ GUID,
2288
+ kForOnEventAttribute,
2289
+ kListener,
2290
+ kStatusCode,
2291
+ kWebSocket,
2292
+ NOOP
2293
+ } = require_constants();
2294
+ var {
2295
+ EventTarget: { addEventListener, removeEventListener }
2296
+ } = require_event_target();
2297
+ var { format, parse: parse2 } = require_extension();
2298
+ var { toBuffer } = require_buffer_util();
2299
+ var kAborted = /* @__PURE__ */ Symbol("kAborted");
2300
+ var protocolVersions = [8, 13];
2301
+ var readyStates = ["CONNECTING", "OPEN", "CLOSING", "CLOSED"];
2302
+ var subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;
2303
+ var WebSocket2 = class _WebSocket extends EventEmitter {
2304
+ /**
2305
+ * Create a new `WebSocket`.
2306
+ *
2307
+ * @param {(String|URL)} address The URL to which to connect
2308
+ * @param {(String|String[])} [protocols] The subprotocols
2309
+ * @param {Object} [options] Connection options
2310
+ */
2311
+ constructor(address, protocols, options) {
2312
+ super();
2313
+ this._binaryType = BINARY_TYPES[0];
2314
+ this._closeCode = 1006;
2315
+ this._closeFrameReceived = false;
2316
+ this._closeFrameSent = false;
2317
+ this._closeMessage = EMPTY_BUFFER;
2318
+ this._closeTimer = null;
2319
+ this._errorEmitted = false;
2320
+ this._extensions = {};
2321
+ this._paused = false;
2322
+ this._protocol = "";
2323
+ this._readyState = _WebSocket.CONNECTING;
2324
+ this._receiver = null;
2325
+ this._sender = null;
2326
+ this._socket = null;
2327
+ if (address !== null) {
2328
+ this._bufferedAmount = 0;
2329
+ this._isServer = false;
2330
+ this._redirects = 0;
2331
+ if (protocols === void 0) {
2332
+ protocols = [];
2333
+ } else if (!Array.isArray(protocols)) {
2334
+ if (typeof protocols === "object" && protocols !== null) {
2335
+ options = protocols;
2336
+ protocols = [];
2337
+ } else {
2338
+ protocols = [protocols];
2339
+ }
2340
+ }
2341
+ initAsClient(this, address, protocols, options);
2342
+ } else {
2343
+ this._autoPong = options.autoPong;
2344
+ this._closeTimeout = options.closeTimeout;
2345
+ this._isServer = true;
2346
+ }
2347
+ }
2348
+ /**
2349
+ * For historical reasons, the custom "nodebuffer" type is used by the default
2350
+ * instead of "blob".
2351
+ *
2352
+ * @type {String}
2353
+ */
2354
+ get binaryType() {
2355
+ return this._binaryType;
2356
+ }
2357
+ set binaryType(type) {
2358
+ if (!BINARY_TYPES.includes(type)) return;
2359
+ this._binaryType = type;
2360
+ if (this._receiver) this._receiver._binaryType = type;
2361
+ }
2362
+ /**
2363
+ * @type {Number}
2364
+ */
2365
+ get bufferedAmount() {
2366
+ if (!this._socket) return this._bufferedAmount;
2367
+ return this._socket._writableState.length + this._sender._bufferedBytes;
2368
+ }
2369
+ /**
2370
+ * @type {String}
2371
+ */
2372
+ get extensions() {
2373
+ return Object.keys(this._extensions).join();
2374
+ }
2375
+ /**
2376
+ * @type {Boolean}
2377
+ */
2378
+ get isPaused() {
2379
+ return this._paused;
2380
+ }
2381
+ /**
2382
+ * @type {Function}
2383
+ */
2384
+ /* istanbul ignore next */
2385
+ get onclose() {
2386
+ return null;
2387
+ }
2388
+ /**
2389
+ * @type {Function}
2390
+ */
2391
+ /* istanbul ignore next */
2392
+ get onerror() {
2393
+ return null;
2394
+ }
2395
+ /**
2396
+ * @type {Function}
2397
+ */
2398
+ /* istanbul ignore next */
2399
+ get onopen() {
2400
+ return null;
2401
+ }
2402
+ /**
2403
+ * @type {Function}
2404
+ */
2405
+ /* istanbul ignore next */
2406
+ get onmessage() {
2407
+ return null;
2408
+ }
2409
+ /**
2410
+ * @type {String}
2411
+ */
2412
+ get protocol() {
2413
+ return this._protocol;
2414
+ }
2415
+ /**
2416
+ * @type {Number}
2417
+ */
2418
+ get readyState() {
2419
+ return this._readyState;
2420
+ }
2421
+ /**
2422
+ * @type {String}
2423
+ */
2424
+ get url() {
2425
+ return this._url;
2426
+ }
2427
+ /**
2428
+ * Set up the socket and the internal resources.
2429
+ *
2430
+ * @param {Duplex} socket The network socket between the server and client
2431
+ * @param {Buffer} head The first packet of the upgraded stream
2432
+ * @param {Object} options Options object
2433
+ * @param {Boolean} [options.allowSynchronousEvents=false] Specifies whether
2434
+ * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
2435
+ * multiple times in the same tick
2436
+ * @param {Function} [options.generateMask] The function used to generate the
2437
+ * masking key
2438
+ * @param {Number} [options.maxBufferedChunks=0] The maximum number of
2439
+ * buffered data chunks
2440
+ * @param {Number} [options.maxFragments=0] The maximum number of message
2441
+ * fragments
2442
+ * @param {Number} [options.maxPayload=0] The maximum allowed message size
2443
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
2444
+ * not to skip UTF-8 validation for text and close messages
2445
+ * @private
2446
+ */
2447
+ setSocket(socket, head, options) {
2448
+ const receiver = new Receiver2({
2449
+ allowSynchronousEvents: options.allowSynchronousEvents,
2450
+ binaryType: this.binaryType,
2451
+ extensions: this._extensions,
2452
+ isServer: this._isServer,
2453
+ maxBufferedChunks: options.maxBufferedChunks,
2454
+ maxFragments: options.maxFragments,
2455
+ maxPayload: options.maxPayload,
2456
+ skipUTF8Validation: options.skipUTF8Validation
2457
+ });
2458
+ const sender = new Sender2(socket, this._extensions, options.generateMask);
2459
+ this._receiver = receiver;
2460
+ this._sender = sender;
2461
+ this._socket = socket;
2462
+ receiver[kWebSocket] = this;
2463
+ sender[kWebSocket] = this;
2464
+ socket[kWebSocket] = this;
2465
+ receiver.on("conclude", receiverOnConclude);
2466
+ receiver.on("drain", receiverOnDrain);
2467
+ receiver.on("error", receiverOnError);
2468
+ receiver.on("message", receiverOnMessage);
2469
+ receiver.on("ping", receiverOnPing);
2470
+ receiver.on("pong", receiverOnPong);
2471
+ sender.onerror = senderOnError;
2472
+ if (socket.setTimeout) socket.setTimeout(0);
2473
+ if (socket.setNoDelay) socket.setNoDelay();
2474
+ if (head.length > 0) socket.unshift(head);
2475
+ socket.on("close", socketOnClose);
2476
+ socket.on("data", socketOnData);
2477
+ socket.on("end", socketOnEnd);
2478
+ socket.on("error", socketOnError);
2479
+ this._readyState = _WebSocket.OPEN;
2480
+ this.emit("open");
2481
+ }
2482
+ /**
2483
+ * Emit the `'close'` event.
2484
+ *
2485
+ * @private
2486
+ */
2487
+ emitClose() {
2488
+ if (!this._socket) {
2489
+ this._readyState = _WebSocket.CLOSED;
2490
+ this.emit("close", this._closeCode, this._closeMessage);
2491
+ return;
2492
+ }
2493
+ if (this._extensions[PerMessageDeflate2.extensionName]) {
2494
+ this._extensions[PerMessageDeflate2.extensionName].cleanup();
2495
+ }
2496
+ this._receiver.removeAllListeners();
2497
+ this._readyState = _WebSocket.CLOSED;
2498
+ this.emit("close", this._closeCode, this._closeMessage);
2499
+ }
2500
+ /**
2501
+ * Start a closing handshake.
2502
+ *
2503
+ * +----------+ +-----------+ +----------+
2504
+ * - - -|ws.close()|-->|close frame|-->|ws.close()|- - -
2505
+ * | +----------+ +-----------+ +----------+ |
2506
+ * +----------+ +-----------+ |
2507
+ * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING
2508
+ * +----------+ +-----------+ |
2509
+ * | | | +---+ |
2510
+ * +------------------------+-->|fin| - - - -
2511
+ * | +---+ | +---+
2512
+ * - - - - -|fin|<---------------------+
2513
+ * +---+
2514
+ *
2515
+ * @param {Number} [code] Status code explaining why the connection is closing
2516
+ * @param {(String|Buffer)} [data] The reason why the connection is
2517
+ * closing
2518
+ * @public
2519
+ */
2520
+ close(code, data) {
2521
+ if (this.readyState === _WebSocket.CLOSED) return;
2522
+ if (this.readyState === _WebSocket.CONNECTING) {
2523
+ const msg = "WebSocket was closed before the connection was established";
2524
+ abortHandshake(this, this._req, msg);
2525
+ return;
2526
+ }
2527
+ if (this.readyState === _WebSocket.CLOSING) {
2528
+ if (this._closeFrameSent && (this._closeFrameReceived || this._receiver._writableState.errorEmitted)) {
2529
+ this._socket.end();
2530
+ }
2531
+ return;
2532
+ }
2533
+ this._readyState = _WebSocket.CLOSING;
2534
+ this._sender.close(code, data, !this._isServer, (err) => {
2535
+ if (err) return;
2536
+ this._closeFrameSent = true;
2537
+ if (this._closeFrameReceived || this._receiver._writableState.errorEmitted) {
2538
+ this._socket.end();
2539
+ }
2540
+ });
2541
+ setCloseTimer(this);
2542
+ }
2543
+ /**
2544
+ * Pause the socket.
2545
+ *
2546
+ * @public
2547
+ */
2548
+ pause() {
2549
+ if (this.readyState === _WebSocket.CONNECTING || this.readyState === _WebSocket.CLOSED) {
2550
+ return;
2551
+ }
2552
+ this._paused = true;
2553
+ this._socket.pause();
2554
+ }
2555
+ /**
2556
+ * Send a ping.
2557
+ *
2558
+ * @param {*} [data] The data to send
2559
+ * @param {Boolean} [mask] Indicates whether or not to mask `data`
2560
+ * @param {Function} [cb] Callback which is executed when the ping is sent
2561
+ * @public
2562
+ */
2563
+ ping(data, mask, cb) {
2564
+ if (this.readyState === _WebSocket.CONNECTING) {
2565
+ throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
2566
+ }
2567
+ if (typeof data === "function") {
2568
+ cb = data;
2569
+ data = mask = void 0;
2570
+ } else if (typeof mask === "function") {
2571
+ cb = mask;
2572
+ mask = void 0;
2573
+ }
2574
+ if (typeof data === "number") data = data.toString();
2575
+ if (this.readyState !== _WebSocket.OPEN) {
2576
+ sendAfterClose(this, data, cb);
2577
+ return;
2578
+ }
2579
+ if (mask === void 0) mask = !this._isServer;
2580
+ this._sender.ping(data || EMPTY_BUFFER, mask, cb);
2581
+ }
2582
+ /**
2583
+ * Send a pong.
2584
+ *
2585
+ * @param {*} [data] The data to send
2586
+ * @param {Boolean} [mask] Indicates whether or not to mask `data`
2587
+ * @param {Function} [cb] Callback which is executed when the pong is sent
2588
+ * @public
2589
+ */
2590
+ pong(data, mask, cb) {
2591
+ if (this.readyState === _WebSocket.CONNECTING) {
2592
+ throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
2593
+ }
2594
+ if (typeof data === "function") {
2595
+ cb = data;
2596
+ data = mask = void 0;
2597
+ } else if (typeof mask === "function") {
2598
+ cb = mask;
2599
+ mask = void 0;
2600
+ }
2601
+ if (typeof data === "number") data = data.toString();
2602
+ if (this.readyState !== _WebSocket.OPEN) {
2603
+ sendAfterClose(this, data, cb);
2604
+ return;
2605
+ }
2606
+ if (mask === void 0) mask = !this._isServer;
2607
+ this._sender.pong(data || EMPTY_BUFFER, mask, cb);
2608
+ }
2609
+ /**
2610
+ * Resume the socket.
2611
+ *
2612
+ * @public
2613
+ */
2614
+ resume() {
2615
+ if (this.readyState === _WebSocket.CONNECTING || this.readyState === _WebSocket.CLOSED) {
2616
+ return;
2617
+ }
2618
+ this._paused = false;
2619
+ if (!this._receiver._writableState.needDrain) this._socket.resume();
2620
+ }
2621
+ /**
2622
+ * Send a data message.
2623
+ *
2624
+ * @param {*} data The message to send
2625
+ * @param {Object} [options] Options object
2626
+ * @param {Boolean} [options.binary] Specifies whether `data` is binary or
2627
+ * text
2628
+ * @param {Boolean} [options.compress] Specifies whether or not to compress
2629
+ * `data`
2630
+ * @param {Boolean} [options.fin=true] Specifies whether the fragment is the
2631
+ * last one
2632
+ * @param {Boolean} [options.mask] Specifies whether or not to mask `data`
2633
+ * @param {Function} [cb] Callback which is executed when data is written out
2634
+ * @public
2635
+ */
2636
+ send(data, options, cb) {
2637
+ if (this.readyState === _WebSocket.CONNECTING) {
2638
+ throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
2639
+ }
2640
+ if (typeof options === "function") {
2641
+ cb = options;
2642
+ options = {};
2643
+ }
2644
+ if (typeof data === "number") data = data.toString();
2645
+ if (this.readyState !== _WebSocket.OPEN) {
2646
+ sendAfterClose(this, data, cb);
2647
+ return;
2648
+ }
2649
+ const opts = {
2650
+ binary: typeof data !== "string",
2651
+ mask: !this._isServer,
2652
+ compress: true,
2653
+ fin: true,
2654
+ ...options
2655
+ };
2656
+ if (!this._extensions[PerMessageDeflate2.extensionName]) {
2657
+ opts.compress = false;
2658
+ }
2659
+ this._sender.send(data || EMPTY_BUFFER, opts, cb);
2660
+ }
2661
+ /**
2662
+ * Forcibly close the connection.
2663
+ *
2664
+ * @public
2665
+ */
2666
+ terminate() {
2667
+ if (this.readyState === _WebSocket.CLOSED) return;
2668
+ if (this.readyState === _WebSocket.CONNECTING) {
2669
+ const msg = "WebSocket was closed before the connection was established";
2670
+ abortHandshake(this, this._req, msg);
2671
+ return;
2672
+ }
2673
+ if (this._socket) {
2674
+ this._readyState = _WebSocket.CLOSING;
2675
+ this._socket.destroy();
2676
+ }
2677
+ }
2678
+ };
2679
+ Object.defineProperty(WebSocket2, "CONNECTING", {
2680
+ enumerable: true,
2681
+ value: readyStates.indexOf("CONNECTING")
2682
+ });
2683
+ Object.defineProperty(WebSocket2.prototype, "CONNECTING", {
2684
+ enumerable: true,
2685
+ value: readyStates.indexOf("CONNECTING")
2686
+ });
2687
+ Object.defineProperty(WebSocket2, "OPEN", {
2688
+ enumerable: true,
2689
+ value: readyStates.indexOf("OPEN")
2690
+ });
2691
+ Object.defineProperty(WebSocket2.prototype, "OPEN", {
2692
+ enumerable: true,
2693
+ value: readyStates.indexOf("OPEN")
2694
+ });
2695
+ Object.defineProperty(WebSocket2, "CLOSING", {
2696
+ enumerable: true,
2697
+ value: readyStates.indexOf("CLOSING")
2698
+ });
2699
+ Object.defineProperty(WebSocket2.prototype, "CLOSING", {
2700
+ enumerable: true,
2701
+ value: readyStates.indexOf("CLOSING")
2702
+ });
2703
+ Object.defineProperty(WebSocket2, "CLOSED", {
2704
+ enumerable: true,
2705
+ value: readyStates.indexOf("CLOSED")
2706
+ });
2707
+ Object.defineProperty(WebSocket2.prototype, "CLOSED", {
2708
+ enumerable: true,
2709
+ value: readyStates.indexOf("CLOSED")
2710
+ });
2711
+ [
2712
+ "binaryType",
2713
+ "bufferedAmount",
2714
+ "extensions",
2715
+ "isPaused",
2716
+ "protocol",
2717
+ "readyState",
2718
+ "url"
2719
+ ].forEach((property) => {
2720
+ Object.defineProperty(WebSocket2.prototype, property, { enumerable: true });
2721
+ });
2722
+ ["open", "error", "close", "message"].forEach((method) => {
2723
+ Object.defineProperty(WebSocket2.prototype, `on${method}`, {
2724
+ enumerable: true,
2725
+ get() {
2726
+ for (const listener of this.listeners(method)) {
2727
+ if (listener[kForOnEventAttribute]) return listener[kListener];
2728
+ }
2729
+ return null;
2730
+ },
2731
+ set(handler) {
2732
+ for (const listener of this.listeners(method)) {
2733
+ if (listener[kForOnEventAttribute]) {
2734
+ this.removeListener(method, listener);
2735
+ break;
2736
+ }
2737
+ }
2738
+ if (typeof handler !== "function") return;
2739
+ this.addEventListener(method, handler, {
2740
+ [kForOnEventAttribute]: true
2741
+ });
2742
+ }
2743
+ });
2744
+ });
2745
+ WebSocket2.prototype.addEventListener = addEventListener;
2746
+ WebSocket2.prototype.removeEventListener = removeEventListener;
2747
+ module2.exports = WebSocket2;
2748
+ function initAsClient(websocket, address, protocols, options) {
2749
+ const opts = {
2750
+ allowSynchronousEvents: true,
2751
+ autoPong: true,
2752
+ closeTimeout: CLOSE_TIMEOUT,
2753
+ protocolVersion: protocolVersions[1],
2754
+ maxBufferedChunks: 256 * 1024,
2755
+ maxFragments: 16 * 1024,
2756
+ maxPayload: 100 * 1024 * 1024,
2757
+ skipUTF8Validation: false,
2758
+ perMessageDeflate: true,
2759
+ followRedirects: false,
2760
+ maxRedirects: 10,
2761
+ ...options,
2762
+ socketPath: void 0,
2763
+ hostname: void 0,
2764
+ protocol: void 0,
2765
+ timeout: void 0,
2766
+ method: "GET",
2767
+ host: void 0,
2768
+ path: void 0,
2769
+ port: void 0
2770
+ };
2771
+ websocket._autoPong = opts.autoPong;
2772
+ websocket._closeTimeout = opts.closeTimeout;
2773
+ if (!protocolVersions.includes(opts.protocolVersion)) {
2774
+ throw new RangeError(
2775
+ `Unsupported protocol version: ${opts.protocolVersion} (supported versions: ${protocolVersions.join(", ")})`
2776
+ );
2777
+ }
2778
+ let parsedUrl;
2779
+ if (address instanceof URL2) {
2780
+ parsedUrl = address;
2781
+ } else {
2782
+ try {
2783
+ parsedUrl = new URL2(address);
2784
+ } catch {
2785
+ throw new SyntaxError(`Invalid URL: ${address}`);
2786
+ }
2787
+ }
2788
+ if (parsedUrl.protocol === "http:") {
2789
+ parsedUrl.protocol = "ws:";
2790
+ } else if (parsedUrl.protocol === "https:") {
2791
+ parsedUrl.protocol = "wss:";
2792
+ }
2793
+ websocket._url = parsedUrl.href;
2794
+ const isSecure = parsedUrl.protocol === "wss:";
2795
+ const isIpcUrl = parsedUrl.protocol === "ws+unix:";
2796
+ let invalidUrlMessage;
2797
+ if (parsedUrl.protocol !== "ws:" && !isSecure && !isIpcUrl) {
2798
+ invalidUrlMessage = `The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`;
2799
+ } else if (isIpcUrl && !parsedUrl.pathname) {
2800
+ invalidUrlMessage = "The URL's pathname is empty";
2801
+ } else if (parsedUrl.hash) {
2802
+ invalidUrlMessage = "The URL contains a fragment identifier";
2803
+ }
2804
+ if (invalidUrlMessage) {
2805
+ const err = new SyntaxError(invalidUrlMessage);
2806
+ if (websocket._redirects === 0) {
2807
+ throw err;
2808
+ } else {
2809
+ emitErrorAndClose(websocket, err);
2810
+ return;
2811
+ }
2812
+ }
2813
+ const defaultPort = isSecure ? 443 : 80;
2814
+ const key = randomBytes(16).toString("base64");
2815
+ const request = isSecure ? https.request : http.request;
2816
+ const protocolSet = /* @__PURE__ */ new Set();
2817
+ let perMessageDeflate;
2818
+ opts.createConnection = opts.createConnection || (isSecure ? tlsConnect : netConnect);
2819
+ opts.defaultPort = opts.defaultPort || defaultPort;
2820
+ opts.port = parsedUrl.port || defaultPort;
2821
+ opts.host = parsedUrl.hostname.startsWith("[") ? parsedUrl.hostname.slice(1, -1) : parsedUrl.hostname;
2822
+ opts.headers = {
2823
+ ...opts.headers,
2824
+ "Sec-WebSocket-Version": opts.protocolVersion,
2825
+ "Sec-WebSocket-Key": key,
2826
+ Connection: "Upgrade",
2827
+ Upgrade: "websocket"
2828
+ };
2829
+ opts.path = parsedUrl.pathname + parsedUrl.search;
2830
+ opts.timeout = opts.handshakeTimeout;
2831
+ if (opts.perMessageDeflate) {
2832
+ perMessageDeflate = new PerMessageDeflate2({
2833
+ ...opts.perMessageDeflate,
2834
+ isServer: false,
2835
+ maxPayload: opts.maxPayload
2836
+ });
2837
+ opts.headers["Sec-WebSocket-Extensions"] = format({
2838
+ [PerMessageDeflate2.extensionName]: perMessageDeflate.offer()
2839
+ });
2840
+ }
2841
+ if (protocols.length) {
2842
+ for (const protocol of protocols) {
2843
+ if (typeof protocol !== "string" || !subprotocolRegex.test(protocol) || protocolSet.has(protocol)) {
2844
+ throw new SyntaxError(
2845
+ "An invalid or duplicated subprotocol was specified"
2846
+ );
2847
+ }
2848
+ protocolSet.add(protocol);
2849
+ }
2850
+ opts.headers["Sec-WebSocket-Protocol"] = protocols.join(",");
2851
+ }
2852
+ if (opts.origin) {
2853
+ if (opts.protocolVersion < 13) {
2854
+ opts.headers["Sec-WebSocket-Origin"] = opts.origin;
2855
+ } else {
2856
+ opts.headers.Origin = opts.origin;
2857
+ }
2858
+ }
2859
+ if (parsedUrl.username || parsedUrl.password) {
2860
+ opts.auth = `${parsedUrl.username}:${parsedUrl.password}`;
2861
+ }
2862
+ if (isIpcUrl) {
2863
+ const parts = opts.path.split(":");
2864
+ opts.socketPath = parts[0];
2865
+ opts.path = parts[1];
2866
+ }
2867
+ let req;
2868
+ if (opts.followRedirects) {
2869
+ if (websocket._redirects === 0) {
2870
+ websocket._originalIpc = isIpcUrl;
2871
+ websocket._originalSecure = isSecure;
2872
+ websocket._originalHostOrSocketPath = isIpcUrl ? opts.socketPath : parsedUrl.host;
2873
+ const headers = options && options.headers;
2874
+ options = { ...options, headers: {} };
2875
+ if (headers) {
2876
+ for (const [key2, value] of Object.entries(headers)) {
2877
+ options.headers[key2.toLowerCase()] = value;
2878
+ }
2879
+ }
2880
+ } else if (websocket.listenerCount("redirect") === 0) {
2881
+ const isSameHost = isIpcUrl ? websocket._originalIpc ? opts.socketPath === websocket._originalHostOrSocketPath : false : websocket._originalIpc ? false : parsedUrl.host === websocket._originalHostOrSocketPath;
2882
+ if (!isSameHost || websocket._originalSecure && !isSecure) {
2883
+ delete opts.headers.authorization;
2884
+ delete opts.headers.cookie;
2885
+ if (!isSameHost) delete opts.headers.host;
2886
+ opts.auth = void 0;
2887
+ }
2888
+ }
2889
+ if (opts.auth && !options.headers.authorization) {
2890
+ options.headers.authorization = "Basic " + Buffer.from(opts.auth).toString("base64");
2891
+ }
2892
+ req = websocket._req = request(opts);
2893
+ if (websocket._redirects) {
2894
+ websocket.emit("redirect", websocket.url, req);
2895
+ }
2896
+ } else {
2897
+ req = websocket._req = request(opts);
2898
+ }
2899
+ if (opts.timeout) {
2900
+ req.on("timeout", () => {
2901
+ abortHandshake(websocket, req, "Opening handshake has timed out");
2902
+ });
2903
+ }
2904
+ req.on("error", (err) => {
2905
+ if (req === null || req[kAborted]) return;
2906
+ req = websocket._req = null;
2907
+ emitErrorAndClose(websocket, err);
2908
+ });
2909
+ req.on("response", (res) => {
2910
+ const location = res.headers.location;
2911
+ const statusCode = res.statusCode;
2912
+ if (location && opts.followRedirects && statusCode >= 300 && statusCode < 400) {
2913
+ if (++websocket._redirects > opts.maxRedirects) {
2914
+ abortHandshake(websocket, req, "Maximum redirects exceeded");
2915
+ return;
2916
+ }
2917
+ req.abort();
2918
+ let addr;
2919
+ try {
2920
+ addr = new URL2(location, address);
2921
+ } catch (e) {
2922
+ const err = new SyntaxError(`Invalid URL: ${location}`);
2923
+ emitErrorAndClose(websocket, err);
2924
+ return;
2925
+ }
2926
+ initAsClient(websocket, addr, protocols, options);
2927
+ } else if (!websocket.emit("unexpected-response", req, res)) {
2928
+ abortHandshake(
2929
+ websocket,
2930
+ req,
2931
+ `Unexpected server response: ${res.statusCode}`
2932
+ );
2933
+ }
2934
+ });
2935
+ req.on("upgrade", (res, socket, head) => {
2936
+ websocket.emit("upgrade", res);
2937
+ if (websocket.readyState !== WebSocket2.CONNECTING) return;
2938
+ req = websocket._req = null;
2939
+ const upgrade = res.headers.upgrade;
2940
+ if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") {
2941
+ abortHandshake(websocket, socket, "Invalid Upgrade header");
2942
+ return;
2943
+ }
2944
+ const digest = createHash10("sha1").update(key + GUID).digest("base64");
2945
+ if (res.headers["sec-websocket-accept"] !== digest) {
2946
+ abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
2947
+ return;
2948
+ }
2949
+ const serverProt = res.headers["sec-websocket-protocol"];
2950
+ let protError;
2951
+ if (serverProt !== void 0) {
2952
+ if (!protocolSet.size) {
2953
+ protError = "Server sent a subprotocol but none was requested";
2954
+ } else if (!protocolSet.has(serverProt)) {
2955
+ protError = "Server sent an invalid subprotocol";
2956
+ }
2957
+ } else if (protocolSet.size) {
2958
+ protError = "Server sent no subprotocol";
2959
+ }
2960
+ if (protError) {
2961
+ abortHandshake(websocket, socket, protError);
2962
+ return;
2963
+ }
2964
+ if (serverProt) websocket._protocol = serverProt;
2965
+ const secWebSocketExtensions = res.headers["sec-websocket-extensions"];
2966
+ if (secWebSocketExtensions !== void 0) {
2967
+ if (!perMessageDeflate) {
2968
+ const message = "Server sent a Sec-WebSocket-Extensions header but no extension was requested";
2969
+ abortHandshake(websocket, socket, message);
2970
+ return;
2971
+ }
2972
+ let extensions;
2973
+ try {
2974
+ extensions = parse2(secWebSocketExtensions);
2975
+ } catch (err) {
2976
+ const message = "Invalid Sec-WebSocket-Extensions header";
2977
+ abortHandshake(websocket, socket, message);
2978
+ return;
2979
+ }
2980
+ const extensionNames = Object.keys(extensions);
2981
+ if (extensionNames.length !== 1 || extensionNames[0] !== PerMessageDeflate2.extensionName) {
2982
+ const message = "Server indicated an extension that was not requested";
2983
+ abortHandshake(websocket, socket, message);
2984
+ return;
2985
+ }
2986
+ try {
2987
+ perMessageDeflate.accept(extensions[PerMessageDeflate2.extensionName]);
2988
+ } catch (err) {
2989
+ const message = "Invalid Sec-WebSocket-Extensions header";
2990
+ abortHandshake(websocket, socket, message);
2991
+ return;
2992
+ }
2993
+ websocket._extensions[PerMessageDeflate2.extensionName] = perMessageDeflate;
2994
+ }
2995
+ websocket.setSocket(socket, head, {
2996
+ allowSynchronousEvents: opts.allowSynchronousEvents,
2997
+ generateMask: opts.generateMask,
2998
+ maxBufferedChunks: opts.maxBufferedChunks,
2999
+ maxFragments: opts.maxFragments,
3000
+ maxPayload: opts.maxPayload,
3001
+ skipUTF8Validation: opts.skipUTF8Validation
3002
+ });
3003
+ });
3004
+ if (opts.finishRequest) {
3005
+ opts.finishRequest(req, websocket);
3006
+ } else {
3007
+ req.end();
3008
+ }
3009
+ }
3010
+ function emitErrorAndClose(websocket, err) {
3011
+ websocket._readyState = WebSocket2.CLOSING;
3012
+ websocket._errorEmitted = true;
3013
+ websocket.emit("error", err);
3014
+ websocket.emitClose();
3015
+ }
3016
+ function netConnect(options) {
3017
+ options.path = options.socketPath;
3018
+ return net.connect(options);
3019
+ }
3020
+ function tlsConnect(options) {
3021
+ options.path = void 0;
3022
+ if (!options.servername && options.servername !== "") {
3023
+ options.servername = net.isIP(options.host) ? "" : options.host;
3024
+ }
3025
+ return tls.connect(options);
3026
+ }
3027
+ function abortHandshake(websocket, stream, message) {
3028
+ websocket._readyState = WebSocket2.CLOSING;
3029
+ const err = new Error(message);
3030
+ Error.captureStackTrace(err, abortHandshake);
3031
+ if (stream.setHeader) {
3032
+ stream[kAborted] = true;
3033
+ stream.abort();
3034
+ if (stream.socket && !stream.socket.destroyed) {
3035
+ stream.socket.destroy();
3036
+ }
3037
+ process.nextTick(emitErrorAndClose, websocket, err);
3038
+ } else {
3039
+ stream.destroy(err);
3040
+ stream.once("error", websocket.emit.bind(websocket, "error"));
3041
+ stream.once("close", websocket.emitClose.bind(websocket));
3042
+ }
3043
+ }
3044
+ function sendAfterClose(websocket, data, cb) {
3045
+ if (data) {
3046
+ const length = isBlob(data) ? data.size : toBuffer(data).length;
3047
+ if (websocket._socket) websocket._sender._bufferedBytes += length;
3048
+ else websocket._bufferedAmount += length;
3049
+ }
3050
+ if (cb) {
3051
+ const err = new Error(
3052
+ `WebSocket is not open: readyState ${websocket.readyState} (${readyStates[websocket.readyState]})`
3053
+ );
3054
+ process.nextTick(cb, err);
3055
+ }
3056
+ }
3057
+ function receiverOnConclude(code, reason) {
3058
+ const websocket = this[kWebSocket];
3059
+ websocket._closeFrameReceived = true;
3060
+ websocket._closeMessage = reason;
3061
+ websocket._closeCode = code;
3062
+ if (websocket._socket[kWebSocket] === void 0) return;
3063
+ websocket._socket.removeListener("data", socketOnData);
3064
+ process.nextTick(resume, websocket._socket);
3065
+ if (code === 1005) websocket.close();
3066
+ else websocket.close(code, reason);
3067
+ }
3068
+ function receiverOnDrain() {
3069
+ const websocket = this[kWebSocket];
3070
+ if (!websocket.isPaused) websocket._socket.resume();
3071
+ }
3072
+ function receiverOnError(err) {
3073
+ const websocket = this[kWebSocket];
3074
+ if (websocket._socket[kWebSocket] !== void 0) {
3075
+ websocket._socket.removeListener("data", socketOnData);
3076
+ process.nextTick(resume, websocket._socket);
3077
+ websocket.close(err[kStatusCode]);
3078
+ }
3079
+ if (!websocket._errorEmitted) {
3080
+ websocket._errorEmitted = true;
3081
+ websocket.emit("error", err);
3082
+ }
3083
+ }
3084
+ function receiverOnFinish() {
3085
+ this[kWebSocket].emitClose();
3086
+ }
3087
+ function receiverOnMessage(data, isBinary) {
3088
+ this[kWebSocket].emit("message", data, isBinary);
3089
+ }
3090
+ function receiverOnPing(data) {
3091
+ const websocket = this[kWebSocket];
3092
+ if (websocket._autoPong) websocket.pong(data, !this._isServer, NOOP);
3093
+ websocket.emit("ping", data);
3094
+ }
3095
+ function receiverOnPong(data) {
3096
+ this[kWebSocket].emit("pong", data);
3097
+ }
3098
+ function resume(stream) {
3099
+ stream.resume();
3100
+ }
3101
+ function senderOnError(err) {
3102
+ const websocket = this[kWebSocket];
3103
+ if (websocket.readyState === WebSocket2.CLOSED) return;
3104
+ if (websocket.readyState === WebSocket2.OPEN) {
3105
+ websocket._readyState = WebSocket2.CLOSING;
3106
+ setCloseTimer(websocket);
3107
+ }
3108
+ this._socket.end();
3109
+ if (!websocket._errorEmitted) {
3110
+ websocket._errorEmitted = true;
3111
+ websocket.emit("error", err);
3112
+ }
3113
+ }
3114
+ function setCloseTimer(websocket) {
3115
+ websocket._closeTimer = setTimeout(
3116
+ websocket._socket.destroy.bind(websocket._socket),
3117
+ websocket._closeTimeout
3118
+ );
3119
+ }
3120
+ function socketOnClose() {
3121
+ const websocket = this[kWebSocket];
3122
+ this.removeListener("close", socketOnClose);
3123
+ this.removeListener("data", socketOnData);
3124
+ this.removeListener("end", socketOnEnd);
3125
+ websocket._readyState = WebSocket2.CLOSING;
3126
+ if (!this._readableState.endEmitted && !websocket._closeFrameReceived && !websocket._receiver._writableState.errorEmitted && this._readableState.length !== 0) {
3127
+ const chunk = this.read(this._readableState.length);
3128
+ websocket._receiver.write(chunk);
3129
+ }
3130
+ websocket._receiver.end();
3131
+ this[kWebSocket] = void 0;
3132
+ clearTimeout(websocket._closeTimer);
3133
+ if (websocket._receiver._writableState.finished || websocket._receiver._writableState.errorEmitted) {
3134
+ websocket.emitClose();
3135
+ } else {
3136
+ websocket._receiver.on("error", receiverOnFinish);
3137
+ websocket._receiver.on("finish", receiverOnFinish);
3138
+ }
3139
+ }
3140
+ function socketOnData(chunk) {
3141
+ if (!this[kWebSocket]._receiver.write(chunk)) {
3142
+ this.pause();
3143
+ }
3144
+ }
3145
+ function socketOnEnd() {
3146
+ const websocket = this[kWebSocket];
3147
+ websocket._readyState = WebSocket2.CLOSING;
3148
+ websocket._receiver.end();
3149
+ this.end();
3150
+ }
3151
+ function socketOnError() {
3152
+ const websocket = this[kWebSocket];
3153
+ this.removeListener("error", socketOnError);
3154
+ this.on("error", NOOP);
3155
+ if (websocket) {
3156
+ websocket._readyState = WebSocket2.CLOSING;
3157
+ this.destroy();
3158
+ }
3159
+ }
3160
+ }
3161
+ });
3162
+
3163
+ // node_modules/ws/lib/stream.js
3164
+ var require_stream = __commonJS({
3165
+ "node_modules/ws/lib/stream.js"(exports2, module2) {
3166
+ "use strict";
3167
+ var WebSocket2 = require_websocket();
3168
+ var { Duplex } = require("stream");
3169
+ function emitClose(stream) {
3170
+ stream.emit("close");
3171
+ }
3172
+ function duplexOnEnd() {
3173
+ if (!this.destroyed && this._writableState.finished) {
3174
+ this.destroy();
3175
+ }
3176
+ }
3177
+ function duplexOnError(err) {
3178
+ this.removeListener("error", duplexOnError);
3179
+ this.destroy();
3180
+ if (this.listenerCount("error") === 0) {
3181
+ this.emit("error", err);
3182
+ }
3183
+ }
3184
+ function createWebSocketStream2(ws, options) {
3185
+ let terminateOnDestroy = true;
3186
+ const duplex = new Duplex({
3187
+ ...options,
3188
+ autoDestroy: false,
3189
+ emitClose: false,
3190
+ objectMode: false,
3191
+ writableObjectMode: false
3192
+ });
3193
+ ws.on("message", function message(msg, isBinary) {
3194
+ const data = !isBinary && duplex._readableState.objectMode ? msg.toString() : msg;
3195
+ if (!duplex.push(data)) ws.pause();
3196
+ });
3197
+ ws.once("error", function error(err) {
3198
+ if (duplex.destroyed) return;
3199
+ terminateOnDestroy = false;
3200
+ duplex.destroy(err);
3201
+ });
3202
+ ws.once("close", function close() {
3203
+ if (duplex.destroyed) return;
3204
+ duplex.push(null);
3205
+ });
3206
+ duplex._destroy = function(err, callback) {
3207
+ if (ws.readyState === ws.CLOSED) {
3208
+ callback(err);
3209
+ process.nextTick(emitClose, duplex);
3210
+ return;
3211
+ }
3212
+ let called = false;
3213
+ ws.once("error", function error(err2) {
3214
+ called = true;
3215
+ callback(err2);
3216
+ });
3217
+ ws.once("close", function close() {
3218
+ if (!called) callback(err);
3219
+ process.nextTick(emitClose, duplex);
3220
+ });
3221
+ if (terminateOnDestroy) ws.terminate();
3222
+ };
3223
+ duplex._final = function(callback) {
3224
+ if (ws.readyState === ws.CONNECTING) {
3225
+ ws.once("open", function open2() {
3226
+ duplex._final(callback);
3227
+ });
3228
+ return;
3229
+ }
3230
+ if (ws._socket === null) return;
3231
+ if (ws._socket._writableState.finished) {
3232
+ callback();
3233
+ if (duplex._readableState.endEmitted) duplex.destroy();
3234
+ } else {
3235
+ ws._socket.once("finish", function finish() {
3236
+ callback();
3237
+ });
3238
+ ws.close();
3239
+ }
3240
+ };
3241
+ duplex._read = function() {
3242
+ if (ws.isPaused) ws.resume();
3243
+ };
3244
+ duplex._write = function(chunk, encoding, callback) {
3245
+ if (ws.readyState === ws.CONNECTING) {
3246
+ ws.once("open", function open2() {
3247
+ duplex._write(chunk, encoding, callback);
3248
+ });
3249
+ return;
3250
+ }
3251
+ ws.send(chunk, callback);
3252
+ };
3253
+ duplex.on("end", duplexOnEnd);
3254
+ duplex.on("error", duplexOnError);
3255
+ return duplex;
3256
+ }
3257
+ module2.exports = createWebSocketStream2;
3258
+ }
3259
+ });
3260
+
3261
+ // node_modules/ws/lib/subprotocol.js
3262
+ var require_subprotocol = __commonJS({
3263
+ "node_modules/ws/lib/subprotocol.js"(exports2, module2) {
3264
+ "use strict";
3265
+ var { tokenChars } = require_validation();
3266
+ function parse2(header) {
3267
+ const protocols = /* @__PURE__ */ new Set();
3268
+ let start = -1;
3269
+ let end = -1;
3270
+ let i = 0;
3271
+ for (i; i < header.length; i++) {
3272
+ const code = header.charCodeAt(i);
3273
+ if (end === -1 && tokenChars[code] === 1) {
3274
+ if (start === -1) start = i;
3275
+ } else if (i !== 0 && (code === 32 || code === 9)) {
3276
+ if (end === -1 && start !== -1) end = i;
3277
+ } else if (code === 44) {
3278
+ if (start === -1) {
3279
+ throw new SyntaxError(`Unexpected character at index ${i}`);
3280
+ }
3281
+ if (end === -1) end = i;
3282
+ const protocol2 = header.slice(start, end);
3283
+ if (protocols.has(protocol2)) {
3284
+ throw new SyntaxError(`The "${protocol2}" subprotocol is duplicated`);
3285
+ }
3286
+ protocols.add(protocol2);
3287
+ start = end = -1;
3288
+ } else {
3289
+ throw new SyntaxError(`Unexpected character at index ${i}`);
3290
+ }
3291
+ }
3292
+ if (start === -1 || end !== -1) {
3293
+ throw new SyntaxError("Unexpected end of input");
3294
+ }
3295
+ const protocol = header.slice(start, i);
3296
+ if (protocols.has(protocol)) {
3297
+ throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);
3298
+ }
3299
+ protocols.add(protocol);
3300
+ return protocols;
3301
+ }
3302
+ module2.exports = { parse: parse2 };
3303
+ }
3304
+ });
3305
+
3306
+ // node_modules/ws/lib/websocket-server.js
3307
+ var require_websocket_server = __commonJS({
3308
+ "node_modules/ws/lib/websocket-server.js"(exports2, module2) {
3309
+ "use strict";
3310
+ var EventEmitter = require("events");
3311
+ var http = require("http");
3312
+ var { Duplex } = require("stream");
3313
+ var { createHash: createHash10 } = require("crypto");
3314
+ var extension2 = require_extension();
3315
+ var PerMessageDeflate2 = require_permessage_deflate();
3316
+ var subprotocol2 = require_subprotocol();
3317
+ var WebSocket2 = require_websocket();
3318
+ var { CLOSE_TIMEOUT, GUID, kWebSocket } = require_constants();
3319
+ var keyRegex = /^[+/0-9A-Za-z]{22}==$/;
3320
+ var RUNNING = 0;
3321
+ var CLOSING = 1;
3322
+ var CLOSED = 2;
3323
+ var WebSocketServer2 = class extends EventEmitter {
3324
+ /**
3325
+ * Create a `WebSocketServer` instance.
3326
+ *
3327
+ * @param {Object} options Configuration options
3328
+ * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
3329
+ * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
3330
+ * multiple times in the same tick
3331
+ * @param {Boolean} [options.autoPong=true] Specifies whether or not to
3332
+ * automatically send a pong in response to a ping
3333
+ * @param {Number} [options.backlog=511] The maximum length of the queue of
3334
+ * pending connections
3335
+ * @param {Boolean} [options.clientTracking=true] Specifies whether or not to
3336
+ * track clients
3337
+ * @param {Number} [options.closeTimeout=30000] Duration in milliseconds to
3338
+ * wait for the closing handshake to finish after `websocket.close()` is
3339
+ * called
3340
+ * @param {Function} [options.handleProtocols] A hook to handle protocols
3341
+ * @param {String} [options.host] The hostname where to bind the server
3342
+ * @param {Number} [options.maxBufferedChunks=262144] The maximum number of
3343
+ * buffered data chunks
3344
+ * @param {Number} [options.maxFragments=16384] The maximum number of message
3345
+ * fragments
3346
+ * @param {Number} [options.maxPayload=104857600] The maximum allowed message
3347
+ * size
3348
+ * @param {Boolean} [options.noServer=false] Enable no server mode
3349
+ * @param {String} [options.path] Accept only connections matching this path
3350
+ * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable
3351
+ * permessage-deflate
3352
+ * @param {Number} [options.port] The port where to bind the server
3353
+ * @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S
3354
+ * server to use
3355
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
3356
+ * not to skip UTF-8 validation for text and close messages
3357
+ * @param {Function} [options.verifyClient] A hook to reject connections
3358
+ * @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket`
3359
+ * class to use. It must be the `WebSocket` class or class that extends it
3360
+ * @param {Function} [callback] A listener for the `listening` event
3361
+ */
3362
+ constructor(options, callback) {
3363
+ super();
3364
+ options = {
3365
+ allowSynchronousEvents: true,
3366
+ autoPong: true,
3367
+ maxBufferedChunks: 256 * 1024,
3368
+ maxFragments: 16 * 1024,
3369
+ maxPayload: 100 * 1024 * 1024,
3370
+ skipUTF8Validation: false,
3371
+ perMessageDeflate: false,
3372
+ handleProtocols: null,
3373
+ clientTracking: true,
3374
+ closeTimeout: CLOSE_TIMEOUT,
3375
+ verifyClient: null,
3376
+ noServer: false,
3377
+ backlog: null,
3378
+ // use default (511 as implemented in net.js)
3379
+ server: null,
3380
+ host: null,
3381
+ path: null,
3382
+ port: null,
3383
+ WebSocket: WebSocket2,
3384
+ ...options
3385
+ };
3386
+ if (options.port == null && !options.server && !options.noServer || options.port != null && (options.server || options.noServer) || options.server && options.noServer) {
3387
+ throw new TypeError(
3388
+ 'One and only one of the "port", "server", or "noServer" options must be specified'
3389
+ );
3390
+ }
3391
+ if (options.port != null) {
3392
+ this._server = http.createServer((req, res) => {
3393
+ const body = http.STATUS_CODES[426];
3394
+ res.writeHead(426, {
3395
+ "Content-Length": body.length,
3396
+ "Content-Type": "text/plain"
3397
+ });
3398
+ res.end(body);
3399
+ });
3400
+ this._server.listen(
3401
+ options.port,
3402
+ options.host,
3403
+ options.backlog,
3404
+ callback
3405
+ );
3406
+ } else if (options.server) {
3407
+ this._server = options.server;
3408
+ }
3409
+ if (this._server) {
3410
+ const emitConnection = this.emit.bind(this, "connection");
3411
+ this._removeListeners = addListeners(this._server, {
3412
+ listening: this.emit.bind(this, "listening"),
3413
+ error: this.emit.bind(this, "error"),
3414
+ upgrade: (req, socket, head) => {
3415
+ this.handleUpgrade(req, socket, head, emitConnection);
3416
+ }
3417
+ });
3418
+ }
3419
+ if (options.perMessageDeflate === true) options.perMessageDeflate = {};
3420
+ if (options.clientTracking) {
3421
+ this.clients = /* @__PURE__ */ new Set();
3422
+ this._shouldEmitClose = false;
3423
+ }
3424
+ this.options = options;
3425
+ this._state = RUNNING;
3426
+ }
3427
+ /**
3428
+ * Returns the bound address, the address family name, and port of the server
3429
+ * as reported by the operating system if listening on an IP socket.
3430
+ * If the server is listening on a pipe or UNIX domain socket, the name is
3431
+ * returned as a string.
3432
+ *
3433
+ * @return {(Object|String|null)} The address of the server
3434
+ * @public
3435
+ */
3436
+ address() {
3437
+ if (this.options.noServer) {
3438
+ throw new Error('The server is operating in "noServer" mode');
3439
+ }
3440
+ if (!this._server) return null;
3441
+ return this._server.address();
3442
+ }
3443
+ /**
3444
+ * Stop the server from accepting new connections and emit the `'close'` event
3445
+ * when all existing connections are closed.
3446
+ *
3447
+ * @param {Function} [cb] A one-time listener for the `'close'` event
3448
+ * @public
3449
+ */
3450
+ close(cb) {
3451
+ if (this._state === CLOSED) {
3452
+ if (cb) {
3453
+ this.once("close", () => {
3454
+ cb(new Error("The server is not running"));
3455
+ });
3456
+ }
3457
+ process.nextTick(emitClose, this);
3458
+ return;
3459
+ }
3460
+ if (cb) this.once("close", cb);
3461
+ if (this._state === CLOSING) return;
3462
+ this._state = CLOSING;
3463
+ if (this.options.noServer || this.options.server) {
3464
+ if (this._server) {
3465
+ this._removeListeners();
3466
+ this._removeListeners = this._server = null;
3467
+ }
3468
+ if (this.clients) {
3469
+ if (!this.clients.size) {
3470
+ process.nextTick(emitClose, this);
3471
+ } else {
3472
+ this._shouldEmitClose = true;
3473
+ }
3474
+ } else {
3475
+ process.nextTick(emitClose, this);
3476
+ }
3477
+ } else {
3478
+ const server = this._server;
3479
+ this._removeListeners();
3480
+ this._removeListeners = this._server = null;
3481
+ server.close(() => {
3482
+ emitClose(this);
3483
+ });
3484
+ }
3485
+ }
3486
+ /**
3487
+ * See if a given request should be handled by this server instance.
3488
+ *
3489
+ * @param {http.IncomingMessage} req Request object to inspect
3490
+ * @return {Boolean} `true` if the request is valid, else `false`
3491
+ * @public
3492
+ */
3493
+ shouldHandle(req) {
3494
+ if (this.options.path) {
3495
+ const index = req.url.indexOf("?");
3496
+ const pathname = index !== -1 ? req.url.slice(0, index) : req.url;
3497
+ if (pathname !== this.options.path) return false;
3498
+ }
3499
+ return true;
3500
+ }
3501
+ /**
3502
+ * Handle a HTTP Upgrade request.
3503
+ *
3504
+ * @param {http.IncomingMessage} req The request object
3505
+ * @param {Duplex} socket The network socket between the server and client
3506
+ * @param {Buffer} head The first packet of the upgraded stream
3507
+ * @param {Function} cb Callback
3508
+ * @public
3509
+ */
3510
+ handleUpgrade(req, socket, head, cb) {
3511
+ socket.on("error", socketOnError);
3512
+ const key = req.headers["sec-websocket-key"];
3513
+ const upgrade = req.headers.upgrade;
3514
+ const version = +req.headers["sec-websocket-version"];
3515
+ if (req.method !== "GET") {
3516
+ const message = "Invalid HTTP method";
3517
+ abortHandshakeOrEmitwsClientError(this, req, socket, 405, message);
3518
+ return;
3519
+ }
3520
+ if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") {
3521
+ const message = "Invalid Upgrade header";
3522
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
3523
+ return;
3524
+ }
3525
+ if (key === void 0 || !keyRegex.test(key)) {
3526
+ const message = "Missing or invalid Sec-WebSocket-Key header";
3527
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
3528
+ return;
3529
+ }
3530
+ if (version !== 13 && version !== 8) {
3531
+ const message = "Missing or invalid Sec-WebSocket-Version header";
3532
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message, {
3533
+ "Sec-WebSocket-Version": "13, 8"
3534
+ });
3535
+ return;
3536
+ }
3537
+ if (!this.shouldHandle(req)) {
3538
+ abortHandshake(socket, 400);
3539
+ return;
3540
+ }
3541
+ const secWebSocketProtocol = req.headers["sec-websocket-protocol"];
3542
+ let protocols = /* @__PURE__ */ new Set();
3543
+ if (secWebSocketProtocol !== void 0) {
3544
+ try {
3545
+ protocols = subprotocol2.parse(secWebSocketProtocol);
3546
+ } catch (err) {
3547
+ const message = "Invalid Sec-WebSocket-Protocol header";
3548
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
3549
+ return;
3550
+ }
3551
+ }
3552
+ const secWebSocketExtensions = req.headers["sec-websocket-extensions"];
3553
+ const extensions = {};
3554
+ if (this.options.perMessageDeflate && secWebSocketExtensions !== void 0) {
3555
+ const perMessageDeflate = new PerMessageDeflate2({
3556
+ ...this.options.perMessageDeflate,
3557
+ isServer: true,
3558
+ maxPayload: this.options.maxPayload
3559
+ });
3560
+ try {
3561
+ const offers = extension2.parse(secWebSocketExtensions);
3562
+ if (offers[PerMessageDeflate2.extensionName]) {
3563
+ perMessageDeflate.accept(offers[PerMessageDeflate2.extensionName]);
3564
+ extensions[PerMessageDeflate2.extensionName] = perMessageDeflate;
3565
+ }
3566
+ } catch (err) {
3567
+ const message = "Invalid or unacceptable Sec-WebSocket-Extensions header";
3568
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
3569
+ return;
3570
+ }
3571
+ }
3572
+ if (this.options.verifyClient) {
3573
+ const info = {
3574
+ origin: req.headers[`${version === 8 ? "sec-websocket-origin" : "origin"}`],
3575
+ secure: !!(req.socket.authorized || req.socket.encrypted),
3576
+ req
3577
+ };
3578
+ if (this.options.verifyClient.length === 2) {
3579
+ this.options.verifyClient(info, (verified, code, message, headers) => {
3580
+ if (!verified) {
3581
+ return abortHandshake(socket, code || 401, message, headers);
3582
+ }
3583
+ this.completeUpgrade(
3584
+ extensions,
3585
+ key,
3586
+ protocols,
3587
+ req,
3588
+ socket,
3589
+ head,
3590
+ cb
3591
+ );
3592
+ });
3593
+ return;
3594
+ }
3595
+ if (!this.options.verifyClient(info)) return abortHandshake(socket, 401);
3596
+ }
3597
+ this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);
3598
+ }
3599
+ /**
3600
+ * Upgrade the connection to WebSocket.
3601
+ *
3602
+ * @param {Object} extensions The accepted extensions
3603
+ * @param {String} key The value of the `Sec-WebSocket-Key` header
3604
+ * @param {Set} protocols The subprotocols
3605
+ * @param {http.IncomingMessage} req The request object
3606
+ * @param {Duplex} socket The network socket between the server and client
3607
+ * @param {Buffer} head The first packet of the upgraded stream
3608
+ * @param {Function} cb Callback
3609
+ * @throws {Error} If called more than once with the same socket
3610
+ * @private
3611
+ */
3612
+ completeUpgrade(extensions, key, protocols, req, socket, head, cb) {
3613
+ if (!socket.readable || !socket.writable) return socket.destroy();
3614
+ if (socket[kWebSocket]) {
3615
+ throw new Error(
3616
+ "server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration"
3617
+ );
3618
+ }
3619
+ if (this._state > RUNNING) return abortHandshake(socket, 503);
3620
+ const digest = createHash10("sha1").update(key + GUID).digest("base64");
3621
+ const headers = [
3622
+ "HTTP/1.1 101 Switching Protocols",
3623
+ "Upgrade: websocket",
3624
+ "Connection: Upgrade",
3625
+ `Sec-WebSocket-Accept: ${digest}`
3626
+ ];
3627
+ const ws = new this.options.WebSocket(null, void 0, this.options);
3628
+ if (protocols.size) {
3629
+ const protocol = this.options.handleProtocols ? this.options.handleProtocols(protocols, req) : protocols.values().next().value;
3630
+ if (protocol) {
3631
+ headers.push(`Sec-WebSocket-Protocol: ${protocol}`);
3632
+ ws._protocol = protocol;
3633
+ }
3634
+ }
3635
+ if (extensions[PerMessageDeflate2.extensionName]) {
3636
+ const params = extensions[PerMessageDeflate2.extensionName].params;
3637
+ const value = extension2.format({
3638
+ [PerMessageDeflate2.extensionName]: [params]
3639
+ });
3640
+ headers.push(`Sec-WebSocket-Extensions: ${value}`);
3641
+ ws._extensions = extensions;
3642
+ }
3643
+ this.emit("headers", headers, req);
3644
+ socket.write(headers.concat("\r\n").join("\r\n"));
3645
+ socket.removeListener("error", socketOnError);
3646
+ ws.setSocket(socket, head, {
3647
+ allowSynchronousEvents: this.options.allowSynchronousEvents,
3648
+ maxBufferedChunks: this.options.maxBufferedChunks,
3649
+ maxFragments: this.options.maxFragments,
3650
+ maxPayload: this.options.maxPayload,
3651
+ skipUTF8Validation: this.options.skipUTF8Validation
3652
+ });
3653
+ if (this.clients) {
3654
+ this.clients.add(ws);
3655
+ ws.on("close", () => {
3656
+ this.clients.delete(ws);
3657
+ if (this._shouldEmitClose && !this.clients.size) {
3658
+ process.nextTick(emitClose, this);
3659
+ }
3660
+ });
3661
+ }
3662
+ cb(ws, req);
3663
+ }
3664
+ };
3665
+ module2.exports = WebSocketServer2;
3666
+ function addListeners(server, map) {
3667
+ for (const event of Object.keys(map)) server.on(event, map[event]);
3668
+ return function removeListeners() {
3669
+ for (const event of Object.keys(map)) {
3670
+ server.removeListener(event, map[event]);
3671
+ }
3672
+ };
3673
+ }
3674
+ function emitClose(server) {
3675
+ server._state = CLOSED;
3676
+ server.emit("close");
3677
+ }
3678
+ function socketOnError() {
3679
+ this.destroy();
3680
+ }
3681
+ function abortHandshake(socket, code, message, headers) {
3682
+ message = message || http.STATUS_CODES[code];
3683
+ headers = {
3684
+ Connection: "close",
3685
+ "Content-Type": "text/html",
3686
+ "Content-Length": Buffer.byteLength(message),
3687
+ ...headers
3688
+ };
3689
+ socket.once("finish", socket.destroy);
3690
+ socket.end(
3691
+ `HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r
3692
+ ` + Object.keys(headers).map((h) => `${h}: ${headers[h]}`).join("\r\n") + "\r\n\r\n" + message
3693
+ );
3694
+ }
3695
+ function abortHandshakeOrEmitwsClientError(server, req, socket, code, message, headers) {
3696
+ if (server.listenerCount("wsClientError")) {
3697
+ const err = new Error(message);
3698
+ Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError);
3699
+ server.emit("wsClientError", err, socket, req);
3700
+ } else {
3701
+ abortHandshake(socket, code, message, headers);
3702
+ }
3703
+ }
3704
+ }
3705
+ });
29
3706
 
30
3707
  // src/main/workspace-connect.ts
31
- var import_fs12 = require("fs");
32
- var import_os6 = require("os");
3708
+ var import_fs13 = require("fs");
3709
+ var import_os7 = require("os");
33
3710
  var import_path19 = require("path");
34
3711
  var import_url2 = require("url");
35
3712
 
@@ -885,8 +4562,8 @@ async function checkpointPatch(root, base, scope, opts = {}) {
885
4562
  const kept = [];
886
4563
  const carried = [];
887
4564
  for (const c of changes) {
888
- const size = c.binary || c.status === "deleted" ? 0 : (await (0, import_promises2.stat)((0, import_path2.join)(root, c.path)).catch(() => null))?.size ?? 0;
889
- const large = size > CHECKPOINT_KEPT_TEXT.bytes || c.additions + c.deletions > CHECKPOINT_KEPT_TEXT.lines;
4565
+ const size2 = c.binary || c.status === "deleted" ? 0 : (await (0, import_promises2.stat)((0, import_path2.join)(root, c.path)).catch(() => null))?.size ?? 0;
4566
+ const large = size2 > CHECKPOINT_KEPT_TEXT.bytes || c.additions + c.deletions > CHECKPOINT_KEPT_TEXT.lines;
890
4567
  if (c.binary || large) kept.push(c);
891
4568
  else carried.push(c.path);
892
4569
  }
@@ -2017,7 +5694,7 @@ var HttpSessionTransport = class {
2017
5694
  root;
2018
5695
  gone;
2019
5696
  async bootstrap() {
2020
- const raw = await this.get(`/bootstrap?features=${ENGINE_FEATURES.join(",")}`, this.opts.requestTimeoutMs ?? 3e4);
5697
+ const raw = await this.get(`/bootstrap?features=${(this.opts.features ?? ENGINE_FEATURES).join(",")}`, this.opts.requestTimeoutMs ?? 3e4);
2021
5698
  const parts = checkpointPartsOf(raw?.checkpointParts);
2022
5699
  if (parts && typeof raw?.checkpointPatch !== "string") raw.checkpointPatch = await this.checkpointFromParts(parts);
2023
5700
  return toSessionBootstrap(raw);
@@ -2307,6 +5984,11 @@ function toSessionBootstrap(raw) {
2307
5984
  folderLink: typeof session.folderLink?.projectId === "string" && session.folderLink.projectId ? { projectId: session.folderLink.projectId } : null,
2308
5985
  imageGeneration: raw?.imageGeneration === true,
2309
5986
  webSearch: raw?.webSearch === true,
5987
+ // The Design canvas, its versions and the model's question card: offered only when the API says it takes them.
5988
+ designCanvas: raw?.designCanvas === true,
5989
+ designVersions: raw?.designVersions === true,
5990
+ askQuestions: raw?.askQuestions === true,
5991
+ terminalOrigins: Array.isArray(raw?.terminalOrigins) ? raw.terminalOrigins.filter((o) => typeof o === "string" && /^https?:\/\/[^/\s]+$/.test(o)).slice(0, 4) : [],
2310
5992
  transcript: transcriptOf(raw?.transcript),
2311
5993
  baseMeasurements: raw?.baseMeasurements && typeof raw.baseMeasurements === "object" && !Array.isArray(raw.baseMeasurements) ? raw.baseMeasurements : {},
2312
5994
  pullRequests: pullRequestsOf(raw?.pullRequests),
@@ -4116,8 +7798,8 @@ var LogFile = class {
4116
7798
  file;
4117
7799
  write(text3) {
4118
7800
  try {
4119
- const size = (0, import_fs5.statSync)(this.file, { throwIfNoEntry: false })?.size ?? 0;
4120
- if (size > MAX_LOG_BYTES) {
7801
+ const size2 = (0, import_fs5.statSync)(this.file, { throwIfNoEntry: false })?.size ?? 0;
7802
+ if (size2 > MAX_LOG_BYTES) {
4121
7803
  try {
4122
7804
  (0, import_fs5.unlinkSync)(`${this.file}.1`);
4123
7805
  } catch {
@@ -4133,12 +7815,12 @@ var LogFile = class {
4133
7815
  };
4134
7816
  function tailFile(file, lines2) {
4135
7817
  if (!(0, import_fs5.existsSync)(file)) return null;
4136
- const size = (0, import_fs5.statSync)(file).size;
4137
- const length = Math.min(size, 1024 * 1024);
7818
+ const size2 = (0, import_fs5.statSync)(file).size;
7819
+ const length = Math.min(size2, 1024 * 1024);
4138
7820
  const buf = Buffer.alloc(length);
4139
7821
  const fd = (0, import_fs5.openSync)(file, "r");
4140
7822
  try {
4141
- (0, import_fs5.readSync)(fd, buf, 0, length, size - length);
7823
+ (0, import_fs5.readSync)(fd, buf, 0, length, size2 - length);
4142
7824
  } finally {
4143
7825
  (0, import_fs5.closeSync)(fd);
4144
7826
  }
@@ -4152,8 +7834,242 @@ function packageRootOf(bundleDir) {
4152
7834
  return pkg?.name === "@scalequality/cli" && (0, import_path6.basename)(bundleDir) === "dist" ? root : null;
4153
7835
  }
4154
7836
 
4155
- // src/application/services/workspaceSandbox/machineCli.ts
7837
+ // src/application/services/workspaceSandbox/terminalHost.ts
7838
+ var import_crypto5 = require("crypto");
4156
7839
  var import_fs6 = require("fs");
7840
+ var import_http = require("http");
7841
+
7842
+ // node_modules/ws/wrapper.mjs
7843
+ var import_stream = __toESM(require_stream(), 1);
7844
+ var import_extension = __toESM(require_extension(), 1);
7845
+ var import_permessage_deflate = __toESM(require_permessage_deflate(), 1);
7846
+ var import_receiver = __toESM(require_receiver(), 1);
7847
+ var import_sender = __toESM(require_sender(), 1);
7848
+ var import_subprotocol = __toESM(require_subprotocol(), 1);
7849
+ var import_websocket = __toESM(require_websocket(), 1);
7850
+ var import_websocket_server = __toESM(require_websocket_server(), 1);
7851
+
7852
+ // src/application/services/workspaceSandbox/terminalHost.ts
7853
+ var TERMINAL_FEATURE = "terminal_v1";
7854
+ var TERMINAL_PORT = 9231;
7855
+ var MAX_BUFFER = 256 * 1024;
7856
+ var DETACH_MS = 15 * 6e4;
7857
+ var HELLO_MS = 5e3;
7858
+ var MAX_TABS = 8;
7859
+ var MAX_INPUT = 64 * 1024;
7860
+ var MAX_TOKENS = 64;
7861
+ function loadPty() {
7862
+ try {
7863
+ const mod = require("@lydell/node-pty");
7864
+ return typeof mod.spawn === "function" ? mod.spawn : null;
7865
+ } catch {
7866
+ return null;
7867
+ }
7868
+ }
7869
+ var tokenHash = (token) => (0, import_crypto5.createHash)("sha256").update(token).digest("hex");
7870
+ function cloudTerminalUser(passwd = "/etc/passwd") {
7871
+ try {
7872
+ const line = (0, import_fs6.readFileSync)(passwd, "utf8").split("\n").find((l) => l.startsWith("workspace:"));
7873
+ const [, , uid, gid, , home, shell] = (line ?? "").split(":");
7874
+ const u = Number(uid), g = Number(gid);
7875
+ if (!line || !Number.isInteger(u) || u <= 0 || !Number.isInteger(g) || g <= 0 || !home) return null;
7876
+ return { uid: u, gid: g, home, shell: shell?.trim() || "/bin/bash" };
7877
+ } catch {
7878
+ return null;
7879
+ }
7880
+ }
7881
+ function terminalSupported(mode) {
7882
+ return !!loadPty() && (mode === "local" || !!cloudTerminalUser());
7883
+ }
7884
+ var TAB_ID = /^[A-Za-z0-9_-]{1,40}$/;
7885
+ var size = (v, fallback, max) => typeof v === "number" && Number.isInteger(v) && v >= 2 && v <= max ? v : fallback;
7886
+ function parse(raw) {
7887
+ try {
7888
+ const m = JSON.parse(raw.toString());
7889
+ if (m.t === "hello" && typeof m.token === "string" && typeof m.tab === "string") return m;
7890
+ if (m.t === "in" && typeof m.d === "string") return m;
7891
+ if (m.t === "resize") return m;
7892
+ if (m.t === "close") return { t: "close" };
7893
+ } catch {
7894
+ }
7895
+ return null;
7896
+ }
7897
+ var TerminalHost = class {
7898
+ constructor(o) {
7899
+ this.o = o;
7900
+ }
7901
+ o;
7902
+ server = null;
7903
+ wss = null;
7904
+ port = null;
7905
+ tokens = /* @__PURE__ */ new Set();
7906
+ tabs = /* @__PURE__ */ new Map();
7907
+ /** When the person last typed in any tab (the cloud counts it as activity, so the machine does not idle away). */
7908
+ lastInputAt = 0;
7909
+ get open() {
7910
+ return this.tabs.size;
7911
+ }
7912
+ /** Lets one more page in: the sha256 of the token the API gave it. The latest ones are kept. */
7913
+ allow(hash) {
7914
+ if (!/^[0-9a-f]{64}$/.test(hash)) return;
7915
+ this.tokens.add(hash);
7916
+ while (this.tokens.size > MAX_TOKENS) this.tokens.delete(this.tokens.values().next().value);
7917
+ }
7918
+ /** Starts listening once; the port it listens on. */
7919
+ async start() {
7920
+ if (this.port !== null) return this.port;
7921
+ const server = (0, import_http.createServer)((_req, res) => {
7922
+ res.writeHead(426, { "content-type": "text/plain; charset=utf-8" }).end("WebSocket only.");
7923
+ });
7924
+ const wss = new import_websocket_server.default({ server, maxPayload: 1024 * 1024, verifyClient: (info) => this.originAllowed(info.origin) });
7925
+ wss.on("connection", (socket) => this.accept(socket));
7926
+ this.wss = wss;
7927
+ await new Promise((resolve8, reject) => {
7928
+ server.once("error", reject);
7929
+ server.listen(this.o.port, this.o.bind, () => {
7930
+ server.off("error", reject);
7931
+ resolve8();
7932
+ });
7933
+ });
7934
+ this.server = server;
7935
+ this.port = server.address().port;
7936
+ this.o.log.info("terminal listening", { port: this.port, bind: this.o.bind });
7937
+ return this.port;
7938
+ }
7939
+ originAllowed(origin) {
7940
+ return !!origin && this.o.origins().includes(origin);
7941
+ }
7942
+ known(token) {
7943
+ const hash = Buffer.from(tokenHash(token), "hex");
7944
+ for (const h of this.tokens) if ((0, import_crypto5.timingSafeEqual)(Buffer.from(h, "hex"), hash)) return true;
7945
+ return false;
7946
+ }
7947
+ accept(socket) {
7948
+ let tab = null;
7949
+ const hello = setTimeout(() => socket.close(4401, "no hello"), HELLO_MS);
7950
+ const send = (m) => {
7951
+ if (socket.readyState === socket.OPEN) socket.send(JSON.stringify(m));
7952
+ };
7953
+ socket.on("message", (raw) => {
7954
+ const m = parse(raw);
7955
+ if (!m) return;
7956
+ if (!tab) {
7957
+ if (m.t !== "hello") return;
7958
+ clearTimeout(hello);
7959
+ if (!this.known(m.token)) {
7960
+ socket.close(4401, "token");
7961
+ return;
7962
+ }
7963
+ if (!TAB_ID.test(m.tab)) {
7964
+ socket.close(4400, "tab");
7965
+ return;
7966
+ }
7967
+ tab = this.attach(m.tab, socket, size(m.cols, 80, 500), size(m.rows, 24, 200), send);
7968
+ return;
7969
+ }
7970
+ if (m.t === "in") {
7971
+ this.lastInputAt = (this.o.now ?? Date.now)();
7972
+ tab.pty.write(m.d.slice(0, MAX_INPUT));
7973
+ } else if (m.t === "resize") {
7974
+ try {
7975
+ tab.pty.resize(size(m.cols, 80, 500), size(m.rows, 24, 200));
7976
+ } catch {
7977
+ }
7978
+ } else if (m.t === "close") {
7979
+ this.end(tab.id);
7980
+ }
7981
+ });
7982
+ socket.on("close", () => {
7983
+ clearTimeout(hello);
7984
+ if (tab && tab.socket === socket) this.detach(tab);
7985
+ });
7986
+ socket.on("error", () => void 0);
7987
+ }
7988
+ /** The tab this page opens: its shell again (the screen it had, then what comes), or a new shell. */
7989
+ attach(id, socket, cols, rows, send) {
7990
+ const existing = this.tabs.get(id);
7991
+ if (existing) {
7992
+ if (existing.detachTimer) {
7993
+ clearTimeout(existing.detachTimer);
7994
+ existing.detachTimer = null;
7995
+ }
7996
+ const previous = existing.socket;
7997
+ existing.socket = socket;
7998
+ if (previous && previous !== socket) previous.close(4409, "opened elsewhere");
7999
+ send({ t: "ready", tab: id, shell: existing.shell, replay: existing.buffer });
8000
+ try {
8001
+ existing.pty.resize(cols, rows);
8002
+ } catch {
8003
+ }
8004
+ return existing;
8005
+ }
8006
+ if (this.tabs.size >= MAX_TABS) {
8007
+ send({ t: "error", code: "TOO_MANY_TERMINALS" });
8008
+ socket.close(4429, "too many");
8009
+ return null;
8010
+ }
8011
+ let pty;
8012
+ let shell = "shell";
8013
+ try {
8014
+ const sh = this.o.shell();
8015
+ shell = (sh.file.split(/[\\/]/).pop() ?? "shell").replace(/\.exe$/i, "") || "shell";
8016
+ pty = this.o.spawn(sh.file, sh.args, { name: "xterm-256color", cols, rows, cwd: sh.cwd, env: sh.env, ...sh.uid !== void 0 ? { uid: sh.uid, gid: sh.gid } : {} });
8017
+ } catch (e) {
8018
+ this.o.log.warn("terminal could not start", { error: e.message });
8019
+ send({ t: "error", code: "TERMINAL_START_FAILED" });
8020
+ socket.close(4500, "start");
8021
+ return null;
8022
+ }
8023
+ const tab = { id, shell, pty, buffer: "", socket, detachTimer: null };
8024
+ this.tabs.set(id, tab);
8025
+ pty.onData((d) => {
8026
+ tab.buffer = (tab.buffer + d).slice(-MAX_BUFFER);
8027
+ if (tab.socket?.readyState === tab.socket?.OPEN) tab.socket.send(JSON.stringify({ t: "out", d }));
8028
+ });
8029
+ pty.onExit(({ exitCode }) => {
8030
+ if (tab.socket?.readyState === tab.socket?.OPEN) {
8031
+ tab.socket.send(JSON.stringify({ t: "exit", code: exitCode }));
8032
+ tab.socket.close(1e3, "exited");
8033
+ }
8034
+ if (this.tabs.get(id) === tab) this.tabs.delete(id);
8035
+ if (tab.detachTimer) clearTimeout(tab.detachTimer);
8036
+ });
8037
+ send({ t: "ready", tab: id, shell, replay: "" });
8038
+ return tab;
8039
+ }
8040
+ detach(tab) {
8041
+ tab.socket = null;
8042
+ if (tab.detachTimer) clearTimeout(tab.detachTimer);
8043
+ tab.detachTimer = setTimeout(() => this.end(tab.id), DETACH_MS);
8044
+ tab.detachTimer.unref?.();
8045
+ }
8046
+ /** Ends one tab's shell (the person closed it). */
8047
+ end(id) {
8048
+ const tab = this.tabs.get(id);
8049
+ if (!tab) return;
8050
+ this.tabs.delete(id);
8051
+ if (tab.detachTimer) clearTimeout(tab.detachTimer);
8052
+ try {
8053
+ tab.pty.kill();
8054
+ } catch {
8055
+ }
8056
+ tab.socket?.close(1e3, "closed");
8057
+ }
8058
+ /** Ends every shell and stops listening (the engine stops). */
8059
+ async stop() {
8060
+ for (const id of [...this.tabs.keys()]) this.end(id);
8061
+ const server = this.server, wss = this.wss;
8062
+ this.server = null;
8063
+ this.wss = null;
8064
+ this.port = null;
8065
+ for (const client of wss?.clients ?? []) client.terminate();
8066
+ wss?.close();
8067
+ if (server) await new Promise((resolve8) => server.close(() => resolve8()));
8068
+ }
8069
+ };
8070
+
8071
+ // src/application/services/workspaceSandbox/machineCli.ts
8072
+ var import_fs7 = require("fs");
4157
8073
  var import_promises8 = require("fs/promises");
4158
8074
  var import_path8 = require("path");
4159
8075
 
@@ -4451,14 +8367,14 @@ var CredentialStore = class {
4451
8367
  }
4452
8368
  file;
4453
8369
  read() {
4454
- if (!(0, import_fs6.existsSync)(this.file)) return { version: 1, apis: {} };
8370
+ if (!(0, import_fs7.existsSync)(this.file)) return { version: 1, apis: {} };
4455
8371
  try {
4456
- const mode = (0, import_fs6.statSync)(this.file).mode & 511;
4457
- if (mode & 63) (0, import_fs6.chmodSync)(this.file, 384);
8372
+ const mode = (0, import_fs7.statSync)(this.file).mode & 511;
8373
+ if (mode & 63) (0, import_fs7.chmodSync)(this.file, 384);
4458
8374
  } catch {
4459
8375
  }
4460
8376
  try {
4461
- const raw = JSON.parse((0, import_fs6.readFileSync)(this.file, "utf8"));
8377
+ const raw = JSON.parse((0, import_fs7.readFileSync)(this.file, "utf8"));
4462
8378
  const apis = {};
4463
8379
  for (const [api, c] of Object.entries(raw.apis ?? {})) {
4464
8380
  if (c && typeof c.machineId === "string" && typeof c.machineToken === "string" && typeof c.orgId === "string") {
@@ -4478,15 +8394,15 @@ var CredentialStore = class {
4478
8394
  }
4479
8395
  }
4480
8396
  write(data) {
4481
- (0, import_fs6.mkdirSync)((0, import_path8.dirname)(this.file), { recursive: true, mode: 448 });
8397
+ (0, import_fs7.mkdirSync)((0, import_path8.dirname)(this.file), { recursive: true, mode: 448 });
4482
8398
  const tmp = `${this.file}.${process.pid}.tmp`;
4483
- (0, import_fs6.writeFileSync)(tmp, `${JSON.stringify(data, null, 2)}
8399
+ (0, import_fs7.writeFileSync)(tmp, `${JSON.stringify(data, null, 2)}
4484
8400
  `, { mode: 384 });
4485
8401
  try {
4486
- (0, import_fs6.chmodSync)(tmp, 384);
8402
+ (0, import_fs7.chmodSync)(tmp, 384);
4487
8403
  } catch {
4488
8404
  }
4489
- (0, import_fs6.renameSync)(tmp, this.file);
8405
+ (0, import_fs7.renameSync)(tmp, this.file);
4490
8406
  }
4491
8407
  get(api) {
4492
8408
  return this.read().apis[api] ?? null;
@@ -4653,7 +8569,7 @@ async function copyClaudeTranscript(sources, externalId, root, engineConfigDir)
4653
8569
  if (!original) return false;
4654
8570
  const targetDir = (0, import_path8.join)(engineConfigDir, "projects", claudeProjectDir(root));
4655
8571
  const target = (0, import_path8.join)(targetDir, `${externalId}.jsonl`);
4656
- if ((0, import_fs6.existsSync)(target)) return true;
8572
+ if ((0, import_fs7.existsSync)(target)) return true;
4657
8573
  await (0, import_promises8.mkdir)(targetDir, { recursive: true, mode: 448 });
4658
8574
  const partial = `${target}.${process.pid}.partial`;
4659
8575
  try {
@@ -4829,6 +8745,13 @@ var MachineAgent = class {
4829
8745
  case "command_rules":
4830
8746
  answer = this.applyRules(p);
4831
8747
  break;
8748
+ // Something the person asked for needs a newer CLI (the pane's terminal): look for it now, not in 6 hours.
8749
+ case "update_cli":
8750
+ if (this.deps.updateNow) {
8751
+ this.deps.updateNow();
8752
+ answer = { ok: true, result: {} };
8753
+ } else answer = { ok: false, error: { code: "AUTO_UPDATE_UNAVAILABLE" } };
8754
+ break;
4832
8755
  default:
4833
8756
  answer = { ok: false, error: { code: "UNKNOWN_COMMAND" } };
4834
8757
  }
@@ -4936,69 +8859,70 @@ async function addFolder(credentials2, api, path, home) {
4936
8859
  // src/application/services/workspaceSandbox/WorkspaceEngine.ts
4937
8860
  var import_child_process5 = require("child_process");
4938
8861
  var import_promises16 = require("fs/promises");
4939
- var import_fs10 = require("fs");
4940
- var import_crypto8 = require("crypto");
8862
+ var import_fs11 = require("fs");
8863
+ var import_os6 = require("os");
8864
+ var import_crypto9 = require("crypto");
4941
8865
  var import_path17 = require("path");
4942
8866
 
4943
8867
  // src/application/services/execution/LanguageAdapter.ts
4944
8868
  var import_async_hooks = require("async_hooks");
4945
8869
  var sandboxEnvExtras = new import_async_hooks.AsyncLocalStorage();
8870
+ var SANDBOX_ENV_KEEP = [
8871
+ "PATH",
8872
+ "HOME",
8873
+ "LANG",
8874
+ "LC_ALL",
8875
+ "TMPDIR",
8876
+ "TEMP",
8877
+ "TMP",
8878
+ "SHELL",
8879
+ "USER",
8880
+ "TERM",
8881
+ "NODE_PATH",
8882
+ "NVM_DIR",
8883
+ "NVM_BIN",
8884
+ // Python essentials when present.
8885
+ "PYENV_ROOT",
8886
+ "VIRTUAL_ENV",
8887
+ "PIP_CACHE_DIR",
8888
+ // Multilanguage toolchain locations/config set in the prod image
8889
+ // (Dockerfile). Without these the Go/Java/.NET subprocesses fall back to
8890
+ // defaults that may try to DOWNLOAD a toolchain (Go GOTOOLCHAIN=auto),
8891
+ // fail to find the runtime (.NET DOTNET_ROOT), or write to a read-only
8892
+ // HOME (GOCACHE/NUGET). They must pass through to the child process.
8893
+ "GOTOOLCHAIN",
8894
+ "GOPATH",
8895
+ "GOCACHE",
8896
+ "GOMODCACHE",
8897
+ "GOFLAGS",
8898
+ "JAVA_HOME",
8899
+ "MAVEN_OPTS",
8900
+ "M2_HOME",
8901
+ "DOTNET_ROOT",
8902
+ "DOTNET_CLI_HOME",
8903
+ "NUGET_PACKAGES",
8904
+ "DOTNET_CLI_TELEMETRY_OPTOUT",
8905
+ "DOTNET_NOLOGO",
8906
+ "DOTNET_SKIP_FIRST_TIME_EXPERIENCE",
8907
+ // Exact runtime locations/configuration defined by the service and
8908
+ // dedicated coverage images. Keep toolchains usable without passing
8909
+ // unrelated service credentials into the customer's subprocess.
8910
+ "GRADLE_USER_HOME",
8911
+ "SBT_OPTS",
8912
+ "RUSTUP_HOME",
8913
+ "CARGO_HOME",
8914
+ "BUNDLE_PATH",
8915
+ "PUB_CACHE",
8916
+ "FLUTTER_ROOT",
8917
+ "MIX_HOME",
8918
+ "HEX_HOME",
8919
+ "MISE_DATA_DIR",
8920
+ "MISE_CACHE_DIR",
8921
+ "ELIXIR_ERL_OPTIONS"
8922
+ ];
4946
8923
  function sandboxTestEnv() {
4947
- const keep = [
4948
- "PATH",
4949
- "HOME",
4950
- "LANG",
4951
- "LC_ALL",
4952
- "TMPDIR",
4953
- "TEMP",
4954
- "TMP",
4955
- "SHELL",
4956
- "USER",
4957
- "TERM",
4958
- "NODE_PATH",
4959
- "NVM_DIR",
4960
- "NVM_BIN",
4961
- // Python essentials when present.
4962
- "PYENV_ROOT",
4963
- "VIRTUAL_ENV",
4964
- "PIP_CACHE_DIR",
4965
- // Multilanguage toolchain locations/config set in the prod image
4966
- // (Dockerfile). Without these the Go/Java/.NET subprocesses fall back to
4967
- // defaults that may try to DOWNLOAD a toolchain (Go GOTOOLCHAIN=auto),
4968
- // fail to find the runtime (.NET DOTNET_ROOT), or write to a read-only
4969
- // HOME (GOCACHE/NUGET). They must pass through to the child process.
4970
- "GOTOOLCHAIN",
4971
- "GOPATH",
4972
- "GOCACHE",
4973
- "GOMODCACHE",
4974
- "GOFLAGS",
4975
- "JAVA_HOME",
4976
- "MAVEN_OPTS",
4977
- "M2_HOME",
4978
- "DOTNET_ROOT",
4979
- "DOTNET_CLI_HOME",
4980
- "NUGET_PACKAGES",
4981
- "DOTNET_CLI_TELEMETRY_OPTOUT",
4982
- "DOTNET_NOLOGO",
4983
- "DOTNET_SKIP_FIRST_TIME_EXPERIENCE",
4984
- // Exact runtime locations/configuration defined by the service and
4985
- // dedicated coverage images. Keep toolchains usable without passing
4986
- // unrelated service credentials into the customer's subprocess.
4987
- "GRADLE_USER_HOME",
4988
- "SBT_OPTS",
4989
- "RUSTUP_HOME",
4990
- "CARGO_HOME",
4991
- "BUNDLE_PATH",
4992
- "PUB_CACHE",
4993
- "FLUTTER_ROOT",
4994
- "MIX_HOME",
4995
- "HEX_HOME",
4996
- "MISE_DATA_DIR",
4997
- "MISE_CACHE_DIR",
4998
- "ELIXIR_ERL_OPTIONS"
4999
- ];
5000
8924
  const env = {};
5001
- for (const k of keep) {
8925
+ for (const k of SANDBOX_ENV_KEEP) {
5002
8926
  if (process.env[k] != null) env[k] = process.env[k];
5003
8927
  }
5004
8928
  env.NODE_ENV = "test";
@@ -5060,7 +8984,7 @@ var ApprovalBroker = class {
5060
8984
 
5061
8985
  // src/application/services/workspaceSandbox/appScreenshot.ts
5062
8986
  var import_child_process3 = require("child_process");
5063
- var import_fs7 = require("fs");
8987
+ var import_fs8 = require("fs");
5064
8988
  var import_promises9 = require("fs/promises");
5065
8989
  var import_os4 = require("os");
5066
8990
  var import_path9 = require("path");
@@ -5081,9 +9005,9 @@ function chromeCandidates(env = process.env, platform2 = process.platform) {
5081
9005
  return [...own, "/usr/bin/chromium", "/usr/bin/chromium-browser", "/usr/bin/google-chrome", "/usr/bin/google-chrome-stable", "/snap/bin/chromium"];
5082
9006
  }
5083
9007
  function findChrome(candidates = chromeCandidates()) {
5084
- return candidates.find((path) => (0, import_fs7.existsSync)(path)) ?? null;
9008
+ return candidates.find((path) => (0, import_fs8.existsSync)(path)) ?? null;
5085
9009
  }
5086
- async function screenshotPage(chrome, url, target, size) {
9010
+ async function screenshotPage(chrome, url, target, size2) {
5087
9011
  const profile = await (0, import_promises9.mkdtemp)((0, import_path9.join)((0, import_os4.tmpdir)(), "sq-shot-"));
5088
9012
  try {
5089
9013
  await new Promise((resolve8, reject) => {
@@ -5096,7 +9020,7 @@ async function screenshotPage(chrome, url, target, size) {
5096
9020
  "--no-first-run",
5097
9021
  "--no-default-browser-check",
5098
9022
  `--user-data-dir=${profile}`,
5099
- `--window-size=${size.width},${size.height}`,
9023
+ `--window-size=${size2.width},${size2.height}`,
5100
9024
  "--virtual-time-budget=8000",
5101
9025
  `--screenshot=${target}`,
5102
9026
  url
@@ -8366,8 +12290,8 @@ var ZodSet = class _ZodSet extends ZodType {
8366
12290
  maxSize: { value: maxSize, message: errorUtil.toString(message) }
8367
12291
  });
8368
12292
  }
8369
- size(size, message) {
8370
- return this.min(size, message).max(size, message);
12293
+ size(size2, message) {
12294
+ return this.min(size2, message).max(size2, message);
8371
12295
  }
8372
12296
  nonempty(message) {
8373
12297
  return this.min(1, message);
@@ -9635,7 +13559,7 @@ function limitInEngineText(text3) {
9635
13559
  }
9636
13560
 
9637
13561
  // src/application/services/workspaceSandbox/scalequalityTools.ts
9638
- var import_crypto5 = require("crypto");
13562
+ var import_crypto6 = require("crypto");
9639
13563
 
9640
13564
  // src/application/services/workspaceSandbox/types.ts
9641
13565
  function isApprovalRequired(r) {
@@ -9714,7 +13638,7 @@ function buildScaleQualityServer(sdk, host) {
9714
13638
  const tools = REMOTE_TOOLS.map(
9715
13639
  (spec) => sdk.tool(spec.name, spec.description, spec.shape, async (args) => {
9716
13640
  const a = { ...args ?? {} };
9717
- if (spec.idempotent && typeof a.idempotencyKey !== "string") a.idempotencyKey = (0, import_crypto5.randomUUID)();
13641
+ if (spec.idempotent && typeof a.idempotencyKey !== "string") a.idempotencyKey = (0, import_crypto6.randomUUID)();
9718
13642
  return callScaleQualityTool(host, spec.name, a);
9719
13643
  })
9720
13644
  );
@@ -10340,7 +14264,7 @@ function blockText(content) {
10340
14264
  }
10341
14265
 
10342
14266
  // src/application/services/workspaceSandbox/inputChannel.ts
10343
- var import_crypto6 = require("crypto");
14267
+ var import_crypto7 = require("crypto");
10344
14268
  var InputChannel = class {
10345
14269
  buffer = [];
10346
14270
  waiting = null;
@@ -10398,7 +14322,7 @@ var InputChannel = class {
10398
14322
  var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
10399
14323
  function messageUuid(id) {
10400
14324
  if (UUID.test(id)) return id.toLowerCase();
10401
- const h = (0, import_crypto6.createHash)("sha256").update(`sq-message:${id}`).digest("hex");
14325
+ const h = (0, import_crypto7.createHash)("sha256").update(`sq-message:${id}`).digest("hex");
10402
14326
  return `${h.slice(0, 8)}-${h.slice(8, 12)}-5${h.slice(13, 16)}-${(parseInt(h[16], 16) & 3 | 8).toString(16)}${h.slice(17, 20)}-${h.slice(20, 32)}`;
10403
14327
  }
10404
14328
  function userMessage(text3, images, uuid2, priority) {
@@ -10671,16 +14595,16 @@ function buildSystemAppend(c) {
10671
14595
  "- Keep it short, like a colleague reporting in a chat: a few lines for most turns, no headings, a short list only when there are several separate items. Never repeat the same fact in two places.",
10672
14596
  "- End with at most one question or one suggested next step, never a menu of options. When there is an obvious next step, say it in one line.",
10673
14597
  "- To show the user an image (a screenshot, a design, a reference board, a chart), write it as a Markdown image with its path in the workspace, for example `![Login screen](docs/login.png)`: the screen displays it in the conversation, and the user can open it larger. An https image address works the same way. Never say you cannot show an image; read it yourself first when you need to know what it shows.",
10674
- "- To show the user a page you built (a prototype, a screen, a mockup, a chart, a small game, an HTML report), save it as an .html file in the workspace and write it as a Markdown image with that path, for example `![Battle HUD](prototype/hud.html)`: the screen runs the page in the conversation, with its code one click away. Stylesheets, scripts and images it links from the workspace go with it; scripts from a CDN load only from cdn.jsdelivr.net, cdnjs.cloudflare.com, unpkg.com or cdn.tailwindcss.com, and it calls no other address. Never say the conversation cannot show a page or a preview, and never offer to open it on the user's computer instead.",
14598
+ "- To show the user a page you built (" + (c.designCanvas ? "a chart, a small game, an HTML report; a prototype, a screen, a mockup or slides are a design, as Designs and prototypes says" : "a prototype, a screen, a mockup, a chart, a small game, an HTML report") + "), save it as an .html file in the workspace and write it as a Markdown image with that path, for example `![Battle HUD](prototype/hud.html)`: the screen runs the page in the conversation, with its code one click away. Stylesheets, scripts and images it links from the workspace go with it; scripts from a CDN load only from cdn.jsdelivr.net, cdnjs.cloudflare.com, unpkg.com or cdn.tailwindcss.com, and it calls no other address. Never say the conversation cannot show a page or a preview, and never offer to open it on the user's computer instead.",
10675
14599
  c.local ? "- To show the user an app you started on this machine (a web dev server: Vite, Next, a game build served over http), run it in the background and write its address as a Markdown image, for example `![Battle HUD](http://localhost:5173)`: the screen runs the app in the conversation, since the user's browser is on this same machine. Never say you cannot show the running app." : "- To show the user an app you started in the workspace (a web dev server: Vite, Next, a game build served over http, on a port from 1024 up), run it in the background and write its address as a Markdown image, for example `![Battle HUD](http://localhost:5173)`: the screen runs the app in the conversation through ScaleQuality, live (hot reload included). The page there has no cookies or browser storage of its own. Never say you cannot show the running app.",
10676
- "- After you build or change a screen of an app you started, call screenshot_app with its http://localhost address and Read the PNG to check it looks right before you say it is done.",
14600
+ "- After you build or change a screen of an app you started, call screenshot_app with its http://localhost address and Read the PNG to check it looks right before you say it is done. The screenshot is for you: show the user the page, the design or the running app itself, never a screenshot of something you built.",
10677
14601
  ...c.webSearch ? ["- To look something up on the web (current documentation, a version, an error message, an API), call web_search; read a page in full with WebFetch. Never say you cannot search the web."] : [],
10678
14602
  ...c.imageGeneration ? ["- To create a new image (a character sheet, concept art, a sprite, an icon, a mockup, a reference board), call generate_image with a detailed prompt and where to save it, then show it from that path. Never say you cannot create images, and never answer an image request with only a prompt for another tool."] : []
10679
14603
  ].join("\n");
10680
14604
  }
10681
14605
 
10682
14606
  // src/application/services/workspaceSandbox/testCommand.ts
10683
- var import_fs8 = require("fs");
14607
+ var import_fs9 = require("fs");
10684
14608
  var import_promises12 = require("fs/promises");
10685
14609
  var import_path13 = require("path");
10686
14610
  function commandForFramework(framework, dir, pkgTestScript) {
@@ -10694,13 +14618,13 @@ function commandForFramework(framework, dir, pkgTestScript) {
10694
14618
  case "go-test":
10695
14619
  return "go test ./...";
10696
14620
  case "junit":
10697
- return (0, import_fs8.existsSync)((0, import_path13.join)(dir, "gradlew")) ? "./gradlew test" : (0, import_fs8.existsSync)((0, import_path13.join)(dir, "build.gradle")) || (0, import_fs8.existsSync)((0, import_path13.join)(dir, "build.gradle.kts")) ? "gradle test" : "mvn -q test";
14621
+ return (0, import_fs9.existsSync)((0, import_path13.join)(dir, "gradlew")) ? "./gradlew test" : (0, import_fs9.existsSync)((0, import_path13.join)(dir, "build.gradle")) || (0, import_fs9.existsSync)((0, import_path13.join)(dir, "build.gradle.kts")) ? "gradle test" : "mvn -q test";
10698
14622
  case "xunit":
10699
14623
  case "nunit":
10700
14624
  case "mstest":
10701
14625
  return "dotnet test";
10702
14626
  case "phpunit":
10703
- return (0, import_fs8.existsSync)((0, import_path13.join)(dir, "vendor", "bin", "phpunit")) ? "vendor/bin/phpunit" : "phpunit";
14627
+ return (0, import_fs9.existsSync)((0, import_path13.join)(dir, "vendor", "bin", "phpunit")) ? "vendor/bin/phpunit" : "phpunit";
10704
14628
  case "rspec":
10705
14629
  return "bundle exec rspec";
10706
14630
  case "cargo-test":
@@ -10708,7 +14632,7 @@ function commandForFramework(framework, dir, pkgTestScript) {
10708
14632
  case "exunit":
10709
14633
  return "mix test";
10710
14634
  case "dart-test":
10711
- return (0, import_fs8.existsSync)((0, import_path13.join)(dir, "pubspec.yaml")) && /flutter:/.test(safeRead((0, import_path13.join)(dir, "pubspec.yaml"))) ? "flutter test" : "dart test";
14635
+ return (0, import_fs9.existsSync)((0, import_path13.join)(dir, "pubspec.yaml")) && /flutter:/.test(safeRead((0, import_path13.join)(dir, "pubspec.yaml"))) ? "flutter test" : "dart test";
10712
14636
  case "xctest":
10713
14637
  return "swift test";
10714
14638
  case "scalatest":
@@ -10721,7 +14645,7 @@ function commandForFramework(framework, dir, pkgTestScript) {
10721
14645
  }
10722
14646
  function safeRead(p) {
10723
14647
  try {
10724
- return (0, import_fs8.readFileSync)(p, "utf8");
14648
+ return (0, import_fs9.readFileSync)(p, "utf8");
10725
14649
  } catch {
10726
14650
  return "";
10727
14651
  }
@@ -10737,7 +14661,7 @@ async function hasTestScript(dir) {
10737
14661
  }
10738
14662
  }
10739
14663
  async function detectTestCommandFromManifests(dir) {
10740
- const has = (f) => (0, import_fs8.existsSync)((0, import_path13.join)(dir, f));
14664
+ const has = (f) => (0, import_fs9.existsSync)((0, import_path13.join)(dir, f));
10741
14665
  const pkgScript = await hasTestScript(dir);
10742
14666
  if (pkgScript) return { command: "npm test --silent", framework: "npm-script", source: "manifest" };
10743
14667
  const checks = [
@@ -10761,8 +14685,8 @@ async function detectTestCommandFromManifests(dir) {
10761
14685
  }
10762
14686
 
10763
14687
  // src/application/services/workspaceSandbox/transcript.ts
10764
- var import_crypto7 = require("crypto");
10765
- var import_fs9 = require("fs");
14688
+ var import_crypto8 = require("crypto");
14689
+ var import_fs10 = require("fs");
10766
14690
  var import_promises13 = require("fs/promises");
10767
14691
  var import_path14 = require("path");
10768
14692
  var import_zlib2 = require("zlib");
@@ -10807,7 +14731,7 @@ async function packTranscript(configDir, sessionId, redactor, caps = TRANSCRIPT_
10807
14731
  const zipped = (0, import_zlib2.gzipSync)(Buffer.from(text3, "utf8"), { level: 9 });
10808
14732
  if (zipped.length > caps.maxCompressedBytes) return { tooLarge: true, bytes: zipped.length };
10809
14733
  return {
10810
- payload: { sdkSessionId: sessionId, encoding: "gzip-base64", data: zipped.toString("base64"), bytes: Buffer.byteLength(text3), sha256: (0, import_crypto7.createHash)("sha256").update(text3).digest("hex") },
14734
+ payload: { sdkSessionId: sessionId, encoding: "gzip-base64", data: zipped.toString("base64"), bytes: Buffer.byteLength(text3), sha256: (0, import_crypto8.createHash)("sha256").update(text3).digest("hex") },
10811
14735
  secretsRemoved: removed
10812
14736
  };
10813
14737
  }
@@ -10820,7 +14744,7 @@ async function restoreTranscript(configDir, cwd, t) {
10820
14744
  } catch {
10821
14745
  return false;
10822
14746
  }
10823
- if (t.sha256 && (0, import_crypto7.createHash)("sha256").update(text3).digest("hex") !== t.sha256) return false;
14747
+ if (t.sha256 && (0, import_crypto8.createHash)("sha256").update(text3).digest("hex") !== t.sha256) return false;
10824
14748
  const dir = (0, import_path14.join)(configDir, "projects", engineProjectDir(cwd));
10825
14749
  await (0, import_promises13.mkdir)(dir, { recursive: true, mode: 448 });
10826
14750
  const target = (0, import_path14.join)(dir, `${t.sdkSessionId}.jsonl`);
@@ -10833,7 +14757,7 @@ async function restoreTranscript(configDir, cwd, t) {
10833
14757
  await (0, import_promises13.rm)(partial, { force: true }).catch(() => void 0);
10834
14758
  return false;
10835
14759
  }
10836
- return (0, import_fs9.existsSync)(target);
14760
+ return (0, import_fs10.existsSync)(target);
10837
14761
  }
10838
14762
 
10839
14763
  // src/application/services/workspaceSandbox/askQuestion.ts
@@ -10970,17 +14894,17 @@ async function listFiles(root, rel, denied = []) {
10970
14894
  const child = (0, import_path15.join)(abs, d.name);
10971
14895
  if (deniedReal.some((x) => child === x || child.startsWith(x + import_path15.sep))) continue;
10972
14896
  let type = d.isDirectory() ? "dir" : d.isFile() ? "file" : null;
10973
- let size;
14897
+ let size2;
10974
14898
  if (d.isSymbolicLink()) {
10975
14899
  const inside3 = await resolveInside(root, (0, import_path15.relative)(root, child)).catch(() => null);
10976
14900
  const target = inside3 ? await (0, import_promises14.stat)(child).catch(() => null) : null;
10977
14901
  type = target?.isDirectory() ? "dir" : target?.isFile() ? "file" : null;
10978
- size = target?.isFile() ? target.size : void 0;
14902
+ size2 = target?.isFile() ? target.size : void 0;
10979
14903
  } else if (type === "file") {
10980
- size = (await (0, import_promises14.stat)(child).catch(() => null))?.size;
14904
+ size2 = (await (0, import_promises14.stat)(child).catch(() => null))?.size;
10981
14905
  }
10982
14906
  if (!type) continue;
10983
- entries.push({ name: d.name, path: clean ? `${clean}/${d.name}` : d.name, type, ...size !== void 0 ? { size } : {} });
14907
+ entries.push({ name: d.name, path: clean ? `${clean}/${d.name}` : d.name, type, ...size2 !== void 0 ? { size: size2 } : {} });
10984
14908
  }
10985
14909
  entries.sort((a, b) => a.type === b.type ? a.name.localeCompare(b.name) : a.type === "dir" ? -1 : 1);
10986
14910
  return { path: clean, entries: entries.slice(0, FILE_CAPS.maxEntries), truncated: entries.length > FILE_CAPS.maxEntries };
@@ -11388,6 +15312,18 @@ ${lines2.join("\n")}
11388
15312
 
11389
15313
  // src/application/services/workspaceSandbox/WorkspaceEngine.ts
11390
15314
  var WARM_IDLE_MS = 15 * 6e4;
15315
+ var TERMINAL_PULSE_MS = 4 * 6e4;
15316
+ var TERMINAL_IDLE_MS = 20 * 6e4;
15317
+ var TERMINAL_LOCAL_ENV = ["SSH_AUTH_SOCK", "EDITOR", "VISUAL", "PAGER", "LC_CTYPE"];
15318
+ function localLoginShell() {
15319
+ if (process.platform === "win32") return process.env.COMSPEC || "powershell.exe";
15320
+ let shell = null;
15321
+ try {
15322
+ shell = (0, import_os6.userInfo)().shell;
15323
+ } catch {
15324
+ }
15325
+ return shell || process.env.SHELL || (process.platform === "darwin" ? "/bin/zsh" : "/bin/bash");
15326
+ }
11391
15327
  var STOP_GRACE_MS = 8e3;
11392
15328
  var INTERRUPT_TIMEOUT_MS = 3e3;
11393
15329
  var MODEL_TOOLS = ["Read", "Write", "Edit", "NotebookEdit", "Glob", "Grep", "Bash", "TaskStop", "TodoWrite", "Agent", "WebFetch", "Skill"];
@@ -11538,6 +15474,11 @@ var WorkspaceEngine = class {
11538
15474
  waitAbort = null;
11539
15475
  /** The model's question the turn waits on (AskUserQuestion). */
11540
15476
  questions = new QuestionDesk();
15477
+ /** The pane's terminal, started the first time the person opens one (terminalHost.ts). */
15478
+ terminal = null;
15479
+ terminalPulse = null;
15480
+ /** Folders already opened to the cloud terminal's user (setfacl), so each is done once. */
15481
+ terminalShared = /* @__PURE__ */ new Set();
11541
15482
  /** The last status said for each message of the person, so each one is said once. */
11542
15483
  statuses = /* @__PURE__ */ new Map();
11543
15484
  pollAbort = new AbortController();
@@ -11872,7 +15813,7 @@ var WorkspaceEngine = class {
11872
15813
  const privateDirs = (this.deps.privateDirs ?? []).map((d) => (0, import_path17.resolve)(d));
11873
15814
  const taken = (name2) => {
11874
15815
  const dir = (0, import_path17.resolve)(this.deps.root, name2);
11875
- return this.repos.has(dir) || privateDirs.includes(dir) || (0, import_fs10.existsSync)(dir);
15816
+ return this.repos.has(dir) || privateDirs.includes(dir) || (0, import_fs11.existsSync)(dir);
11876
15817
  };
11877
15818
  let name = clash || taken(short) ? full : short;
11878
15819
  for (let n = 2; taken(name); n++) name = `${full}-${n}`;
@@ -12028,6 +15969,9 @@ var WorkspaceEngine = class {
12028
15969
  case "read_file":
12029
15970
  await this.answerFileRequest(c.id, c.kind, p);
12030
15971
  return;
15972
+ case "terminal_open":
15973
+ await this.openTerminal(c.id, p);
15974
+ return;
12031
15975
  case "scope":
12032
15976
  this.applyScope(p);
12033
15977
  return;
@@ -12115,6 +16059,121 @@ var WorkspaceEngine = class {
12115
16059
  }
12116
16060
  }
12117
16061
  /** v4: the file viewer's reads, answered through the reply route (the API keeps the answer a few minutes). */
16062
+ /**
16063
+ * The pane's terminal (Erik, 24/10/2026): the API sends the sha256 of the token it gave the person's page, the
16064
+ * terminal starts the first time (this computer's loopback on a free port, or the cloud task's on TERMINAL_PORT) and
16065
+ * the reply says its port. An engine without a pseudo-terminal here, or a cloud image without its unprivileged user,
16066
+ * says it has none.
16067
+ */
16068
+ async openTerminal(commandId, p) {
16069
+ if (!this.deps.transport.reply) return;
16070
+ let reply;
16071
+ try {
16072
+ const spawn4 = this.deps.terminalPty === void 0 ? loadPty() : this.deps.terminalPty;
16073
+ const user = this.local ? null : this.deps.terminalUser === void 0 ? cloudTerminalUser() : this.deps.terminalUser;
16074
+ const hash = typeof p.tokenHash === "string" ? p.tokenHash : "";
16075
+ if (!spawn4 || !this.local && !user) reply = { ok: false, error: { code: "TERMINAL_UNAVAILABLE" } };
16076
+ else if (!/^[0-9a-f]{64}$/.test(hash)) reply = { ok: false, error: { code: "INVALID_ARGUMENTS" } };
16077
+ else {
16078
+ if (!this.terminal) {
16079
+ this.terminal = new TerminalHost({
16080
+ spawn: spawn4,
16081
+ shell: () => this.terminalShell(user),
16082
+ bind: "127.0.0.1",
16083
+ port: this.local ? 0 : TERMINAL_PORT,
16084
+ origins: () => this.boot?.terminalOrigins ?? [],
16085
+ log: this.deps.log
16086
+ });
16087
+ }
16088
+ if (user) await this.shareWithTerminal(user.uid);
16089
+ this.terminal.allow(hash);
16090
+ const port = await this.terminal.start();
16091
+ this.pulseTerminal();
16092
+ reply = { ok: true, result: { port } };
16093
+ }
16094
+ } catch (e) {
16095
+ this.deps.log.warn("terminal could not open", { error: this.redactor.text(e.message) });
16096
+ reply = { ok: false, error: { code: "TERMINAL_UNAVAILABLE" } };
16097
+ }
16098
+ await this.deps.transport.reply(commandId, reply).catch((e) => this.deps.log.warn("terminal reply failed", { error: e.message }));
16099
+ }
16100
+ /**
16101
+ * The shell a terminal tab runs: the person's own login shell in the session's folder on their computer; in the
16102
+ * cloud, bash as the unprivileged `workspace` user, with its own home for the toolchains' caches. Either way the
16103
+ * environment is the allowlist of the model's commands (toolchains, never a token, a key or a service variable).
16104
+ */
16105
+ terminalShell(user) {
16106
+ const env = {};
16107
+ for (const k of [...SANDBOX_ENV_KEEP, ...this.local ? [...LOCAL_ENV_PASSTHROUGH, ...TERMINAL_LOCAL_ENV] : []]) {
16108
+ const v = process.env[k];
16109
+ if (typeof v === "string") env[k] = v;
16110
+ }
16111
+ Object.assign(env, { TERM: "xterm-256color", COLORTERM: "truecolor", TERM_PROGRAM: "ScaleQuality" });
16112
+ if (!env.LANG) env.LANG = "en_US.UTF-8";
16113
+ if (!user) {
16114
+ const shell = localLoginShell();
16115
+ return { file: shell, args: process.platform === "win32" ? [] : ["-l"], cwd: this.deps.root, env: { ...env, SHELL: shell } };
16116
+ }
16117
+ const caches = {
16118
+ CARGO_HOME: ".cargo",
16119
+ GOPATH: "go",
16120
+ GOCACHE: ".cache/go-build",
16121
+ GOMODCACHE: "go/pkg/mod",
16122
+ GRADLE_USER_HOME: ".gradle",
16123
+ PIP_CACHE_DIR: ".cache/pip",
16124
+ NUGET_PACKAGES: ".nuget/packages",
16125
+ DOTNET_CLI_HOME: ".",
16126
+ PUB_CACHE: ".pub-cache",
16127
+ BUNDLE_PATH: ".bundle"
16128
+ };
16129
+ for (const [k, rel] of Object.entries(caches)) if (env[k] !== void 0) env[k] = (0, import_path17.join)(user.home, rel);
16130
+ return {
16131
+ file: user.shell,
16132
+ args: ["-l"],
16133
+ cwd: this.deps.root,
16134
+ env: { ...env, HOME: user.home, USER: "workspace", LOGNAME: "workspace", SHELL: user.shell },
16135
+ uid: user.uid,
16136
+ gid: user.gid
16137
+ };
16138
+ }
16139
+ /**
16140
+ * The cloud terminal's user may read and change the session's repositories, and what is created in them later
16141
+ * (default ACL), never the engine's own folders (its state and transcripts stay root's, 0700).
16142
+ */
16143
+ async shareWithTerminal(uid) {
16144
+ const root = (0, import_path17.resolve)(this.deps.root);
16145
+ const own = new Set((this.deps.privateDirs ?? []).map((d) => (0, import_path17.resolve)(d)));
16146
+ for (const dir of own) await (0, import_promises16.chmod)(dir, 448).catch(() => void 0);
16147
+ const acl = (args) => new Promise((done) => {
16148
+ const child = (0, import_child_process5.spawn)("setfacl", args, { stdio: "ignore" });
16149
+ child.on("error", () => done(false));
16150
+ child.on("close", (code) => done(code === 0));
16151
+ });
16152
+ if (!this.terminalShared.has(root)) {
16153
+ if (!await acl(["-m", `u:${uid}:rwx`, "-m", `d:u:${uid}:rwX`, root])) this.deps.log.warn("terminal: the workspace folder could not be shared with its user");
16154
+ this.terminalShared.add(root);
16155
+ }
16156
+ for (const name of await (0, import_promises16.readdir)(root).catch(() => [])) {
16157
+ const path = (0, import_path17.join)(root, name);
16158
+ if (this.terminalShared.has(path) || own.has(path) || [...own].some((d) => d.startsWith(path + import_path17.sep))) continue;
16159
+ if (await acl(["-R", "-m", `u:${uid}:rwX`, "-m", `d:u:${uid}:rwX`, path])) this.terminalShared.add(path);
16160
+ }
16161
+ }
16162
+ /**
16163
+ * While a terminal is open on the person's computer, or typed into in the last minutes in the cloud, the session
16164
+ * is in use: a small event every few minutes keeps it from going idle (the cloud machine, so it does not stop
16165
+ * under the person's hands; the computer, so its shells live as long as they are open).
16166
+ */
16167
+ pulseTerminal() {
16168
+ if (this.terminalPulse) return;
16169
+ this.terminalPulse = setInterval(() => {
16170
+ const t = this.terminal;
16171
+ if (!t || !t.open) return;
16172
+ if (!this.local && Date.now() - t.lastInputAt > TERMINAL_IDLE_MS) return;
16173
+ this.emit({ type: "terminal_activity", data: { open: t.open } });
16174
+ }, TERMINAL_PULSE_MS);
16175
+ this.terminalPulse.unref?.();
16176
+ }
12118
16177
  async answerFileRequest(commandId, kind, p) {
12119
16178
  if (!this.deps.transport.reply) return;
12120
16179
  let reply;
@@ -12449,7 +16508,7 @@ ${String(item.content)}` : String(item.content);
12449
16508
  return {
12450
16509
  registry: this.registry,
12451
16510
  currentBranch: async () => (await git(["rev-parse", "--abbrev-ref", "HEAD"], { cwd: this.deps.root, timeoutMs: 3e3 })).trim() || null,
12452
- installedLocally: (name) => [this.deps.root, ...[...this.repos.values()].map((r) => r.root)].some((dir) => (0, import_fs10.existsSync)((0, import_path17.join)(dir, "node_modules", name, "package.json")) || (0, import_fs10.existsSync)((0, import_path17.join)(dir, "node_modules", ".bin", name)))
16511
+ installedLocally: (name) => [this.deps.root, ...[...this.repos.values()].map((r) => r.root)].some((dir) => (0, import_fs11.existsSync)((0, import_path17.join)(dir, "node_modules", name, "package.json")) || (0, import_fs11.existsSync)((0, import_path17.join)(dir, "node_modules", ".bin", name)))
12453
16512
  };
12454
16513
  }
12455
16514
  /**
@@ -12689,7 +16748,7 @@ ${String(item.content)}` : String(item.content);
12689
16748
  }
12690
16749
  /** A file the person attached, saved whole in the engine's own folder (the file tools read there, nothing writes there). */
12691
16750
  async saveAttachment(name, bytes) {
12692
- const dir = (0, import_path17.join)(this.deps.configDir, "attachments", (0, import_crypto8.randomUUID)());
16751
+ const dir = (0, import_path17.join)(this.deps.configDir, "attachments", (0, import_crypto9.randomUUID)());
12693
16752
  await (0, import_promises16.mkdir)(dir, { recursive: true });
12694
16753
  const path = (0, import_path17.join)(dir, (0, import_path17.basename)(name ?? "").replace(/[\u0000-\u001f\\/:]/g, "_").replace(/^\.+/, "") || "attachment");
12695
16754
  await (0, import_promises16.writeFile)(path, bytes);
@@ -13641,6 +17700,8 @@ ${patch}`;
13641
17700
  async shutdown(opts, reason = "shutdown", pausedCode = "ENGINE_STOPPED") {
13642
17701
  if (this.stopping) return;
13643
17702
  this.stopping = true;
17703
+ if (this.terminalPulse) clearInterval(this.terminalPulse);
17704
+ await this.terminal?.stop().catch(() => void 0);
13644
17705
  this.queue.length = 0;
13645
17706
  this.dropWarm();
13646
17707
  this.turnAbort?.abort();
@@ -13682,7 +17743,7 @@ ${patch}`;
13682
17743
  this.pendingCheckpoints.delete(repo2.localId);
13683
17744
  repo2.dormant = !repo2.unsaved;
13684
17745
  }
13685
- const stateDir = this.deps.stateDir ?? (0, import_path17.join)(this.deps.scratch, `folder-${(0, import_crypto8.createHash)("sha256").update(local.root).digest("hex").slice(0, 16)}`);
17746
+ const stateDir = this.deps.stateDir ?? (0, import_path17.join)(this.deps.scratch, `folder-${(0, import_crypto9.createHash)("sha256").update(local.root).digest("hex").slice(0, 16)}`);
13686
17747
  const tracker = new LooseFileTracker({ root: local.root, stateDir, excluded: () => local.repos.map((r) => r.root) });
13687
17748
  const tracked = local.gitAvailable && await tracker.init().then(() => true, (e) => {
13688
17749
  this.deps.log.warn("loose files not tracked", { error: e.message });
@@ -13917,7 +17978,7 @@ ${patch}`;
13917
17978
  if (!transport.searchWeb) return text("Web search is not available in this session. Tell the user plainly.", true);
13918
17979
  let found;
13919
17980
  try {
13920
- found = await transport.searchWeb({ query: query.slice(0, 1e3), idempotencyKey: (0, import_crypto8.randomUUID)() });
17981
+ found = await transport.searchWeb({ query: query.slice(0, 1e3), idempotencyKey: (0, import_crypto9.randomUUID)() });
13921
17982
  } catch (e) {
13922
17983
  const why = e instanceof SessionGoneError ? `refused (${e.status})` : e instanceof TransportError && e.status ? `failed (${e.status})` : "failed";
13923
17984
  return text(`The web search ${why}. Tell the user plainly in one sentence, or use WebFetch on a page you know.`, true);
@@ -13954,7 +18015,7 @@ ${sources}` : ""}`);
13954
18015
  }
13955
18016
  let created;
13956
18017
  try {
13957
- created = await transport.generateImage({ prompt: args.prompt.slice(0, 4e3), ...reference ? { reference } : {}, idempotencyKey: (0, import_crypto8.randomUUID)() });
18018
+ created = await transport.generateImage({ prompt: args.prompt.slice(0, 4e3), ...reference ? { reference } : {}, idempotencyKey: (0, import_crypto9.randomUUID)() });
13958
18019
  } catch (e) {
13959
18020
  const why = e instanceof SessionGoneError ? `refused (${e.status})` : e instanceof TransportError && e.status ? `failed (${e.status})` : "failed";
13960
18021
  return text(`The image could not be created: ScaleQuality ${why}. Tell the user plainly in one sentence; do not claim an image was made and do not offer a prompt for another tool instead.`, true);
@@ -14443,7 +18504,7 @@ function buildQueryOptions(o) {
14443
18504
  }
14444
18505
  function spawnKey(i) {
14445
18506
  const { orgMcpServers, ...data } = i;
14446
- return (0, import_crypto8.createHash)("sha256").update(JSON.stringify({ ...data, orgMcpServers: Object.keys(orgMcpServers).sort() })).digest("hex");
18507
+ return (0, import_crypto9.createHash)("sha256").update(JSON.stringify({ ...data, orgMcpServers: Object.keys(orgMcpServers).sort() })).digest("hex");
14447
18508
  }
14448
18509
  function timedGate(gate, took) {
14449
18510
  const timed = async (run3) => {
@@ -14465,12 +18526,12 @@ async function hasLocalTranscript(configDir, sessionId) {
14465
18526
  if (!/^[A-Za-z0-9-]{8,80}$/.test(sessionId)) return false;
14466
18527
  const projects = (0, import_path17.join)(configDir, "projects");
14467
18528
  const dirs = await (0, import_promises16.readdir)(projects).catch(() => []);
14468
- return dirs.some((d) => (0, import_fs10.existsSync)((0, import_path17.join)(projects, d, `${sessionId}.jsonl`)));
18529
+ return dirs.some((d) => (0, import_fs11.existsSync)((0, import_path17.join)(projects, d, `${sessionId}.jsonl`)));
14469
18530
  }
14470
18531
 
14471
18532
  // src/application/services/workspaceSandbox/selfUpdate.ts
14472
- var import_crypto9 = require("crypto");
14473
- var import_fs11 = require("fs");
18533
+ var import_crypto10 = require("crypto");
18534
+ var import_fs12 = require("fs");
14474
18535
  var import_path18 = require("path");
14475
18536
  var REGISTRY_LATEST = "https://registry.npmjs.org/@scalequality%2fcli/latest";
14476
18537
  var UPDATE_FIRST_CHECK_MS = 2 * 6e4;
@@ -14496,18 +18557,18 @@ function isNewer(candidate, current) {
14496
18557
  }
14497
18558
  function readJson2(file) {
14498
18559
  try {
14499
- const v = JSON.parse((0, import_fs11.readFileSync)(file, "utf8"));
18560
+ const v = JSON.parse((0, import_fs12.readFileSync)(file, "utf8"));
14500
18561
  return v && typeof v === "object" ? v : null;
14501
18562
  } catch {
14502
18563
  return null;
14503
18564
  }
14504
18565
  }
14505
18566
  function writeJsonAtomic(file, value) {
14506
- (0, import_fs11.mkdirSync)((0, import_path18.dirname)(file), { recursive: true, mode: 448 });
18567
+ (0, import_fs12.mkdirSync)((0, import_path18.dirname)(file), { recursive: true, mode: 448 });
14507
18568
  const tmp = `${file}.${process.pid}.tmp`;
14508
- (0, import_fs11.writeFileSync)(tmp, `${JSON.stringify(value, null, 2)}
18569
+ (0, import_fs12.writeFileSync)(tmp, `${JSON.stringify(value, null, 2)}
14509
18570
  `, { mode: 384 });
14510
- (0, import_fs11.renameSync)(tmp, file);
18571
+ (0, import_fs12.renameSync)(tmp, file);
14511
18572
  }
14512
18573
  var installed = (v) => {
14513
18574
  const r = v;
@@ -14563,8 +18624,8 @@ function installLauncher(home, copy) {
14563
18624
  writeJsonAtomic(currentPath(home), { version: copy.version, bin: copy.bin, previous: null, pending: false, attempts: 0, rejected: current?.rejected ?? [] });
14564
18625
  const file = launcherPath(home);
14565
18626
  const tmp = `${file}.${process.pid}.tmp`;
14566
- (0, import_fs11.writeFileSync)(tmp, launcherSource(copy.bin), { mode: 420 });
14567
- (0, import_fs11.renameSync)(tmp, file);
18627
+ (0, import_fs12.writeFileSync)(tmp, launcherSource(copy.bin), { mode: 420 });
18628
+ (0, import_fs12.renameSync)(tmp, file);
14568
18629
  return file;
14569
18630
  }
14570
18631
  function confirmCurrent(home, version) {
@@ -14576,17 +18637,17 @@ function confirmCurrent(home, version) {
14576
18637
  }
14577
18638
  function behindCurrent(home, version) {
14578
18639
  const current = readCurrent(home);
14579
- if (!current || current.pending || current.version === version || !isNewer(current.version, version) || !(0, import_fs11.existsSync)(current.bin)) return null;
18640
+ if (!current || current.pending || current.version === version || !isNewer(current.version, version) || !(0, import_fs12.existsSync)(current.bin)) return null;
14580
18641
  return current.version;
14581
18642
  }
14582
18643
  function autoUpdateEnabled(home, env) {
14583
- return env.SCALEQUALITY_NO_AUTO_UPDATE !== "1" && !(0, import_fs11.existsSync)(autoUpdateOffPath(home));
18644
+ return env.SCALEQUALITY_NO_AUTO_UPDATE !== "1" && !(0, import_fs12.existsSync)(autoUpdateOffPath(home));
14584
18645
  }
14585
18646
  function setAutoUpdate(home, on) {
14586
- if (on) (0, import_fs11.rmSync)(autoUpdateOffPath(home), { force: true });
18647
+ if (on) (0, import_fs12.rmSync)(autoUpdateOffPath(home), { force: true });
14587
18648
  else {
14588
- (0, import_fs11.mkdirSync)(cliDir(home), { recursive: true, mode: 448 });
14589
- (0, import_fs11.writeFileSync)(autoUpdateOffPath(home), `${(/* @__PURE__ */ new Date()).toISOString()}
18649
+ (0, import_fs12.mkdirSync)(cliDir(home), { recursive: true, mode: 448 });
18650
+ (0, import_fs12.writeFileSync)(autoUpdateOffPath(home), `${(/* @__PURE__ */ new Date()).toISOString()}
14590
18651
  `, { mode: 384 });
14591
18652
  }
14592
18653
  }
@@ -14600,7 +18661,7 @@ async function latestVersion(fetchImpl = fetch) {
14600
18661
  return null;
14601
18662
  }
14602
18663
  }
14603
- function npmCli(nodePath, exists = import_fs11.existsSync, resolve8 = realOrNull, pathEnv = process.env.PATH ?? "") {
18664
+ function npmCli(nodePath, exists = import_fs12.existsSync, resolve8 = realOrNull, pathEnv = process.env.PATH ?? "") {
14604
18665
  const dir = (0, import_path18.dirname)(nodePath);
14605
18666
  const script = (p) => p && /npm-cli\.js$/.test(p) && exists(p) ? p : null;
14606
18667
  const linked = (p) => exists(p) ? script(resolve8(p)) : null;
@@ -14613,7 +18674,7 @@ function npmCli(nodePath, exists = import_fs11.existsSync, resolve8 = realOrNull
14613
18674
  }
14614
18675
  function realOrNull(p) {
14615
18676
  try {
14616
- return (0, import_fs11.realpathSync)(p);
18677
+ return (0, import_fs12.realpathSync)(p);
14617
18678
  } catch {
14618
18679
  return null;
14619
18680
  }
@@ -14634,10 +18695,10 @@ async function installVersion(o) {
14634
18695
  const npm = o.npm === void 0 ? npmCli(o.nodePath) : o.npm;
14635
18696
  if (!npm) throw new UpdateError("NPM_NOT_FOUND", `npm was not found next to ${o.nodePath}.`);
14636
18697
  const staging = (0, import_path18.join)(cliDir(o.home), `.update-${o.version}`);
14637
- (0, import_fs11.rmSync)(staging, { recursive: true, force: true });
14638
- (0, import_fs11.mkdirSync)(staging, { recursive: true, mode: 448 });
18698
+ (0, import_fs12.rmSync)(staging, { recursive: true, force: true });
18699
+ (0, import_fs12.mkdirSync)(staging, { recursive: true, mode: 448 });
14639
18700
  try {
14640
- (0, import_fs11.writeFileSync)((0, import_path18.join)(staging, "package.json"), '{ "private": true }\n');
18701
+ (0, import_fs12.writeFileSync)((0, import_path18.join)(staging, "package.json"), '{ "private": true }\n');
14641
18702
  const r = await o.run(o.nodePath, [
14642
18703
  npm,
14643
18704
  "install",
@@ -14657,7 +18718,7 @@ async function installVersion(o) {
14657
18718
  if (pkg?.name !== "@scalequality/cli" || pkg?.version !== o.version) throw new UpdateError("WRONG_PACKAGE", `npm installed ${String(pkg?.name)}@${String(pkg?.version)} instead of ${o.version}.`);
14658
18719
  const build = readJson2((0, import_path18.join)(root, "dist", "connect.build.json"));
14659
18720
  const bundle = (0, import_path18.join)(root, "dist", "connect.cjs");
14660
- const sha = (0, import_fs11.existsSync)(bundle) ? (0, import_crypto9.createHash)("sha256").update((0, import_fs11.readFileSync)(bundle)).digest("hex") : null;
18721
+ const sha = (0, import_fs12.existsSync)(bundle) ? (0, import_crypto10.createHash)("sha256").update((0, import_fs12.readFileSync)(bundle)).digest("hex") : null;
14661
18722
  if (!sha || typeof build?.sha256 !== "string" || build.sha256 !== sha) throw new UpdateError("BUNDLE_MISMATCH", `The engine of ${o.version} does not match the sha256 it declares.`);
14662
18723
  let copy;
14663
18724
  try {
@@ -14667,7 +18728,7 @@ async function installVersion(o) {
14667
18728
  }
14668
18729
  return { version: copy.version, bin: copy.bin };
14669
18730
  } finally {
14670
- (0, import_fs11.rmSync)(staging, { recursive: true, force: true });
18731
+ (0, import_fs12.rmSync)(staging, { recursive: true, force: true });
14671
18732
  }
14672
18733
  }
14673
18734
  function stageVersion(home, next, running) {
@@ -14713,7 +18774,7 @@ var say = (line = "") => {
14713
18774
  };
14714
18775
  var cliVersion = process.env.SCALEQUALITY_CLI_VERSION || "dev";
14715
18776
  var userAgent = (mode) => `scalequality-cli/${cliVersion} (${mode}; node ${process.versions.node}; ${process.platform})`;
14716
- var HOME = (0, import_os6.homedir)();
18777
+ var HOME = (0, import_os7.homedir)();
14717
18778
  var SQ_HOME = (0, import_path19.join)(HOME, ".scalequality");
14718
18779
  var ENGINE_HOME = (0, import_path19.join)(SQ_HOME, "workspace");
14719
18780
  var credentials = new CredentialStore((0, import_path19.join)(SQ_HOME, "credentials.json"));
@@ -14731,8 +18792,8 @@ function startFailure(e, api) {
14731
18792
  function engineDirs() {
14732
18793
  const configDir = (0, import_path19.join)(ENGINE_HOME, "claude-home");
14733
18794
  const scratch = (0, import_path19.join)(ENGINE_HOME, "tmp");
14734
- (0, import_fs12.mkdirSync)(configDir, { recursive: true, mode: 448 });
14735
- (0, import_fs12.mkdirSync)(scratch, { recursive: true, mode: 448 });
18795
+ (0, import_fs13.mkdirSync)(configDir, { recursive: true, mode: 448 });
18796
+ (0, import_fs13.mkdirSync)(scratch, { recursive: true, mode: 448 });
14736
18797
  return { configDir, scratch };
14737
18798
  }
14738
18799
  function createLocalEngine(o) {
@@ -14769,6 +18830,8 @@ function createLocalEngine(o) {
14769
18830
  secret: o.secret,
14770
18831
  userAgent: userAgent(o.mode),
14771
18832
  decisions,
18833
+ // The pane's terminal, where this computer has its pseudo-terminal (the CLI installs it beside the engine).
18834
+ features: [...ENGINE_FEATURES, ...terminalSupported("local") ? [TERMINAL_FEATURE] : []],
14772
18835
  onBootstrapError: (e) => {
14773
18836
  startError = startFailure(e, o.api);
14774
18837
  }
@@ -14885,7 +18948,7 @@ function chooseApi(explicit) {
14885
18948
  const saved = credentials.apis();
14886
18949
  return saved.length === 1 ? saved[0] : DEFAULT_API;
14887
18950
  }
14888
- var osLabel = () => `${(0, import_os6.platform)()} ${(0, import_os6.release)()}`.slice(0, 100);
18951
+ var osLabel = () => `${(0, import_os7.platform)()} ${(0, import_os7.release)()}`.slice(0, 100);
14889
18952
  function usageError(command, message) {
14890
18953
  say(style.red(message));
14891
18954
  say();
@@ -14895,7 +18958,7 @@ function usageError(command, message) {
14895
18958
  function serviceEnv() {
14896
18959
  let user = process.env.USER || process.env.USERNAME || "";
14897
18960
  try {
14898
- user = (0, import_os6.userInfo)().username || user;
18961
+ user = (0, import_os7.userInfo)().username || user;
14899
18962
  } catch {
14900
18963
  }
14901
18964
  return {
@@ -14949,7 +19012,7 @@ async function loginMain(api, name, thenUp, verbose) {
14949
19012
  const client = new MachineClient(api, { userAgent: userAgent("login") });
14950
19013
  let auth;
14951
19014
  try {
14952
- auth = await client.authorize({ name: name ?? ((0, import_os6.hostname)() || "Computer").slice(0, 100), os: osLabel(), cliVersion });
19015
+ auth = await client.authorize({ name: name ?? ((0, import_os7.hostname)() || "Computer").slice(0, 100), os: osLabel(), cliVersion });
14953
19016
  } catch (e) {
14954
19017
  say(style.red(e instanceof MachineApiError && e.status === null ? `Could not reach ScaleQuality at ${api}.` : "ScaleQuality could not start the login. Try again in a moment."));
14955
19018
  process.exit(1);
@@ -14978,7 +19041,7 @@ async function loginMain(api, name, thenUp, verbose) {
14978
19041
  machineId: token.machineId,
14979
19042
  machineToken: token.machineToken,
14980
19043
  orgId: token.orgId,
14981
- name: name ?? ((0, import_os6.hostname)() || "Computer").slice(0, 100),
19044
+ name: name ?? ((0, import_os7.hostname)() || "Computer").slice(0, 100),
14982
19045
  folders: previous?.folders ?? [],
14983
19046
  createdAt: (/* @__PURE__ */ new Date()).toISOString()
14984
19047
  });
@@ -15071,7 +19134,18 @@ async function upMain(api, verbose, service) {
15071
19134
  void engine.run().catch(() => resolveDone());
15072
19135
  return { stop: () => engine.shutdown({ checkpoint: true }), done };
15073
19136
  };
15074
- agent = new MachineAgent({ api, client, credentials, home: HOME, info: { os: osLabel(), cliVersion }, sources: defaultImportSources(HOME), startSession, say });
19137
+ let updateNow;
19138
+ agent = new MachineAgent({
19139
+ api,
19140
+ client,
19141
+ credentials,
19142
+ home: HOME,
19143
+ info: { os: osLabel(), cliVersion },
19144
+ sources: defaultImportSources(HOME),
19145
+ startSession,
19146
+ say,
19147
+ updateNow: () => updateNow?.()
19148
+ });
15075
19149
  async function shutdown() {
15076
19150
  if (shuttingDown) process.exit(130);
15077
19151
  shuttingDown = true;
@@ -15088,7 +19162,7 @@ async function upMain(api, verbose, service) {
15088
19162
  process.on("unhandledRejection", (e) => {
15089
19163
  if (verbose || service) say(style.dim(`[warn] unhandled rejection ${e?.message}`));
15090
19164
  });
15091
- if (service && process.env.SCALEQUALITY_LAUNCHER === "1") startSelfUpdate(api, () => agent.sessions.size > 0, () => {
19165
+ if (service && process.env.SCALEQUALITY_LAUNCHER === "1") updateNow = startSelfUpdate(api, () => agent.sessions.size > 0, () => {
15092
19166
  agent.stop();
15093
19167
  releaseLock(HOME, api);
15094
19168
  if (process.platform === "win32") {
@@ -15167,6 +19241,7 @@ function startSelfUpdate(api, busy, restart) {
15167
19241
  }
15168
19242
  }, UPDATE_IDLE_POLL_MS).unref();
15169
19243
  say(style.dim(autoUpdateEnabled(HOME, process.env) ? ` Updates install by themselves while no session runs (scalequality service auto-update off${apiFlag(api)} to stop).` : " Automatic updates are off."));
19244
+ return () => void check();
15170
19245
  }
15171
19246
  async function addMain(api, path) {
15172
19247
  try {