@google/gemini-cli 0.49.0-nightly.20260625.gd845bc5d4 → 0.49.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/bundle/{chunk-DQARXBEA.js → chunk-2KPOY3PT.js} +1 -1
  2. package/bundle/{chunk-GP3HT3XA.js → chunk-5D76V46E.js} +1 -1
  3. package/bundle/{chunk-W4CY6ZAV.js → chunk-6SAPFKW2.js} +7 -7
  4. package/bundle/{chunk-KZTYIR7T.js → chunk-DG2DMXNL.js} +4 -4
  5. package/bundle/{chunk-M3LLLH4Q.js → chunk-DUXXYDOU.js} +14099 -7557
  6. package/bundle/{chunk-VFEUUHDP.js → chunk-GD7RCEFJ.js} +1 -1
  7. package/bundle/{chunk-Z7VJ5D2F.js → chunk-HHBELWTD.js} +1 -1
  8. package/bundle/{chunk-2H7H7LHE.js → chunk-KUPS66EC.js} +1 -1
  9. package/bundle/{chunk-ZUVD4OMS.js → chunk-KVKWITLW.js} +1 -1
  10. package/bundle/{chunk-CZXPXLF4.js → chunk-LJT2N46V.js} +2 -2
  11. package/bundle/{chunk-KEKQ7HNE.js → chunk-MT2PHBHF.js} +54 -67
  12. package/bundle/{chunk-6WLO7RJO.js → chunk-O3DZHA75.js} +3 -3
  13. package/bundle/{chunk-N6JHSW2E.js → chunk-QJ52LUEZ.js} +1 -1
  14. package/bundle/{chunk-PGI5U4RD.js → chunk-RWFC7SH2.js} +8 -9
  15. package/bundle/{chunk-LZSQIPID.js → chunk-SWRFLYQS.js} +3 -3
  16. package/bundle/{chunk-D7ASGNGV.js → chunk-THSPF7UM.js} +7 -7
  17. package/bundle/{chunk-JNWGPSWO.js → chunk-UTCNY4YR.js} +1 -1
  18. package/bundle/{chunk-4ZKDF6RJ.js → chunk-UXLDTYS5.js} +1 -1
  19. package/bundle/{chunk-LHQTFC5V.js → chunk-V33X6KEX.js} +2 -2
  20. package/bundle/{chunk-IH4N7SHL.js → chunk-VLV2BYPM.js} +4 -4
  21. package/bundle/{chunk-5VDCISGZ.js → chunk-VSVATFSS.js} +2 -2
  22. package/bundle/{chunk-NSCBFJB5.js → chunk-WDIGNHW2.js} +5 -8
  23. package/bundle/{chunk-DVXL5G45.js → chunk-YAWAHLTJ.js} +1 -1
  24. package/bundle/{chunk-SM66ZQJE.js → chunk-YP5PXUYC.js} +3 -3
  25. package/bundle/{cleanup-7ZAS2HJC.js → cleanup-J3QILUCY.js} +2 -2
  26. package/bundle/{cleanup-OWDILGDO.js → cleanup-UIXA2GEB.js} +2 -2
  27. package/bundle/{cleanup-UAXXCVMU.js → cleanup-YMPS4FUE.js} +2 -2
  28. package/bundle/{core-U7XFRGTW.js → core-64JIIVRX.js} +1 -1
  29. package/bundle/{dist-5MIUEMAQ.js → core-ELQDFBG3.js} +1 -1
  30. package/bundle/{devtoolsService-5OSGJYDS.js → devtoolsService-HCHZ2F6P.js} +2 -2
  31. package/bundle/{devtoolsService-6LH5MZBL.js → devtoolsService-HSYIYY4G.js} +3 -4
  32. package/bundle/{devtoolsService-6HAVTQZ5.js → devtoolsService-YX6EFIXG.js} +2 -2
  33. package/bundle/{dist-B6J3QDWI.js → dist-CLCQE7YY.js} +1 -1
  34. package/bundle/{gemini-H6TAAPCA.js → gemini-APNDCIQH.js} +196 -212
  35. package/bundle/{gemini-6SJTD2W4.js → gemini-FSMCKCVD.js} +14 -14
  36. package/bundle/{gemini-3BRU2HQK.js → gemini-MHDYPMBW.js} +13 -13
  37. package/bundle/gemini.js +7 -7
  38. package/bundle/{interactiveCli-B6MSN4C4.js → interactiveCli-4GI574PD.js} +8 -8
  39. package/bundle/{interactiveCli-KOS354WR.js → interactiveCli-PM57R35K.js} +295 -314
  40. package/bundle/{interactiveCli-BS2D2SBI.js → interactiveCli-PR7HIXJT.js} +8 -8
  41. package/bundle/{liteRtServerManager-FWHYC4A3.js → liteRtServerManager-IXIJTRUX.js} +4 -4
  42. package/bundle/{liteRtServerManager-HIIW3S66.js → liteRtServerManager-SRAMJKDM.js} +4 -4
  43. package/bundle/{liteRtServerManager-M7B3AIIU.js → liteRtServerManager-TYKWESZG.js} +4 -4
  44. package/bundle/{oauth2-provider-RILC6FBL.js → oauth2-provider-4UAT62TZ.js} +1 -1
  45. package/bundle/{oauth2-provider-G7I2PMHS.js → oauth2-provider-I7ZHNJPU.js} +72 -38
  46. package/bundle/{oauth2-provider-EA2VTAQO.js → oauth2-provider-UU4JM5RG.js} +1 -1
  47. package/bundle/{start-AVLVGFFA.js → start-C5MXXCE7.js} +6 -6
  48. package/bundle/{start-CCQWWAKJ.js → start-RIHKQGGY.js} +6 -6
  49. package/bundle/{start-FI6MCT26.js → start-W4HQTHNO.js} +6 -6
  50. package/package.json +1 -1
  51. package/bundle/chunk-6VICSAQD.js +0 -154
  52. package/bundle/chunk-EB5KWRK7.js +0 -512
  53. package/bundle/chunk-IP2NI6CQ.js +0 -398
  54. package/bundle/chunk-M43EUC7R.js +0 -1571
  55. package/bundle/chunk-P3C2ZDOD.js +0 -102505
  56. package/bundle/chunk-SSMJN6LA.js +0 -387674
  57. package/bundle/chunk-TNS2COLB.js +0 -17332
  58. package/bundle/chunk-YNU56L7B.js +0 -118
  59. package/bundle/cleanup-VF75F443.js +0 -32
  60. package/bundle/devtoolsService-OV63XS6S.js +0 -4359
  61. package/bundle/dist-GPCVSENP.js +0 -2150
  62. package/bundle/gemini-R6VOKNQ4.js +0 -29270
  63. package/bundle/interactiveCli-HSHPW4IB.js +0 -34767
  64. package/bundle/liteRtServerManager-ZMLRN3HQ.js +0 -65
  65. package/bundle/oauth2-provider-KED65L5Q.js +0 -235
  66. package/bundle/start-OOI6CRQA.js +0 -18
@@ -1,4359 +0,0 @@
1
- const require = (await import('node:module')).createRequire(import.meta.url); const __chunk_filename = (await import('node:url')).fileURLToPath(import.meta.url); const __chunk_dirname = (await import('node:path')).dirname(__chunk_filename);
2
- import {
3
- CoreEvent,
4
- coreEvents,
5
- debugLogger
6
- } from "./chunk-SSMJN6LA.js";
7
- import "./chunk-664ZODQF.js";
8
- import "./chunk-TUDYL3X4.js";
9
- import "./chunk-IUUIT4SU.js";
10
- import {
11
- __commonJS,
12
- __require,
13
- __toESM
14
- } from "./chunk-34MYV7JD.js";
15
-
16
- // packages/cli/node_modules/ws/lib/stream.js
17
- var require_stream = __commonJS({
18
- "packages/cli/node_modules/ws/lib/stream.js"(exports, module) {
19
- "use strict";
20
- var { Duplex } = __require("stream");
21
- function emitClose(stream) {
22
- stream.emit("close");
23
- }
24
- function duplexOnEnd() {
25
- if (!this.destroyed && this._writableState.finished) {
26
- this.destroy();
27
- }
28
- }
29
- function duplexOnError(err) {
30
- this.removeListener("error", duplexOnError);
31
- this.destroy();
32
- if (this.listenerCount("error") === 0) {
33
- this.emit("error", err);
34
- }
35
- }
36
- function createWebSocketStream2(ws, options) {
37
- let terminateOnDestroy = true;
38
- const duplex = new Duplex({
39
- ...options,
40
- autoDestroy: false,
41
- emitClose: false,
42
- objectMode: false,
43
- writableObjectMode: false
44
- });
45
- ws.on("message", function message(msg, isBinary) {
46
- const data = !isBinary && duplex._readableState.objectMode ? msg.toString() : msg;
47
- if (!duplex.push(data)) ws.pause();
48
- });
49
- ws.once("error", function error(err) {
50
- if (duplex.destroyed) return;
51
- terminateOnDestroy = false;
52
- duplex.destroy(err);
53
- });
54
- ws.once("close", function close() {
55
- if (duplex.destroyed) return;
56
- duplex.push(null);
57
- });
58
- duplex._destroy = function(err, callback) {
59
- if (ws.readyState === ws.CLOSED) {
60
- callback(err);
61
- process.nextTick(emitClose, duplex);
62
- return;
63
- }
64
- let called = false;
65
- ws.once("error", function error(err2) {
66
- called = true;
67
- callback(err2);
68
- });
69
- ws.once("close", function close() {
70
- if (!called) callback(err);
71
- process.nextTick(emitClose, duplex);
72
- });
73
- if (terminateOnDestroy) ws.terminate();
74
- };
75
- duplex._final = function(callback) {
76
- if (ws.readyState === ws.CONNECTING) {
77
- ws.once("open", function open() {
78
- duplex._final(callback);
79
- });
80
- return;
81
- }
82
- if (ws._socket === null) return;
83
- if (ws._socket._writableState.finished) {
84
- callback();
85
- if (duplex._readableState.endEmitted) duplex.destroy();
86
- } else {
87
- ws._socket.once("finish", function finish() {
88
- callback();
89
- });
90
- ws.close();
91
- }
92
- };
93
- duplex._read = function() {
94
- if (ws.isPaused) ws.resume();
95
- };
96
- duplex._write = function(chunk, encoding, callback) {
97
- if (ws.readyState === ws.CONNECTING) {
98
- ws.once("open", function open() {
99
- duplex._write(chunk, encoding, callback);
100
- });
101
- return;
102
- }
103
- ws.send(chunk, callback);
104
- };
105
- duplex.on("end", duplexOnEnd);
106
- duplex.on("error", duplexOnError);
107
- return duplex;
108
- }
109
- module.exports = createWebSocketStream2;
110
- }
111
- });
112
-
113
- // packages/cli/node_modules/ws/lib/constants.js
114
- var require_constants = __commonJS({
115
- "packages/cli/node_modules/ws/lib/constants.js"(exports, module) {
116
- "use strict";
117
- module.exports = {
118
- BINARY_TYPES: ["nodebuffer", "arraybuffer", "fragments"],
119
- EMPTY_BUFFER: Buffer.alloc(0),
120
- GUID: "258EAFA5-E914-47DA-95CA-C5AB0DC85B11",
121
- kForOnEventAttribute: Symbol("kIsForOnEventAttribute"),
122
- kListener: Symbol("kListener"),
123
- kStatusCode: Symbol("status-code"),
124
- kWebSocket: Symbol("websocket"),
125
- NOOP: () => {
126
- }
127
- };
128
- }
129
- });
130
-
131
- // packages/cli/node_modules/ws/lib/buffer-util.js
132
- var require_buffer_util = __commonJS({
133
- "packages/cli/node_modules/ws/lib/buffer-util.js"(exports, module) {
134
- "use strict";
135
- var { EMPTY_BUFFER } = require_constants();
136
- var FastBuffer = Buffer[Symbol.species];
137
- function concat(list, totalLength) {
138
- if (list.length === 0) return EMPTY_BUFFER;
139
- if (list.length === 1) return list[0];
140
- const target = Buffer.allocUnsafe(totalLength);
141
- let offset = 0;
142
- for (let i = 0; i < list.length; i++) {
143
- const buf = list[i];
144
- target.set(buf, offset);
145
- offset += buf.length;
146
- }
147
- if (offset < totalLength) {
148
- return new FastBuffer(target.buffer, target.byteOffset, offset);
149
- }
150
- return target;
151
- }
152
- function _mask(source, mask, output, offset, length) {
153
- for (let i = 0; i < length; i++) {
154
- output[offset + i] = source[i] ^ mask[i & 3];
155
- }
156
- }
157
- function _unmask(buffer, mask) {
158
- for (let i = 0; i < buffer.length; i++) {
159
- buffer[i] ^= mask[i & 3];
160
- }
161
- }
162
- function toArrayBuffer(buf) {
163
- if (buf.length === buf.buffer.byteLength) {
164
- return buf.buffer;
165
- }
166
- return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length);
167
- }
168
- function toBuffer(data) {
169
- toBuffer.readOnly = true;
170
- if (Buffer.isBuffer(data)) return data;
171
- let buf;
172
- if (data instanceof ArrayBuffer) {
173
- buf = new FastBuffer(data);
174
- } else if (ArrayBuffer.isView(data)) {
175
- buf = new FastBuffer(data.buffer, data.byteOffset, data.byteLength);
176
- } else {
177
- buf = Buffer.from(data);
178
- toBuffer.readOnly = false;
179
- }
180
- return buf;
181
- }
182
- module.exports = {
183
- concat,
184
- mask: _mask,
185
- toArrayBuffer,
186
- toBuffer,
187
- unmask: _unmask
188
- };
189
- if (!process.env.WS_NO_BUFFER_UTIL) {
190
- try {
191
- const bufferUtil = __require("bufferutil");
192
- module.exports.mask = function(source, mask, output, offset, length) {
193
- if (length < 48) _mask(source, mask, output, offset, length);
194
- else bufferUtil.mask(source, mask, output, offset, length);
195
- };
196
- module.exports.unmask = function(buffer, mask) {
197
- if (buffer.length < 32) _unmask(buffer, mask);
198
- else bufferUtil.unmask(buffer, mask);
199
- };
200
- } catch (e) {
201
- }
202
- }
203
- }
204
- });
205
-
206
- // packages/cli/node_modules/ws/lib/limiter.js
207
- var require_limiter = __commonJS({
208
- "packages/cli/node_modules/ws/lib/limiter.js"(exports, module) {
209
- "use strict";
210
- var kDone = Symbol("kDone");
211
- var kRun = Symbol("kRun");
212
- var Limiter = class {
213
- /**
214
- * Creates a new `Limiter`.
215
- *
216
- * @param {Number} [concurrency=Infinity] The maximum number of jobs allowed
217
- * to run concurrently
218
- */
219
- constructor(concurrency) {
220
- this[kDone] = () => {
221
- this.pending--;
222
- this[kRun]();
223
- };
224
- this.concurrency = concurrency || Infinity;
225
- this.jobs = [];
226
- this.pending = 0;
227
- }
228
- /**
229
- * Adds a job to the queue.
230
- *
231
- * @param {Function} job The job to run
232
- * @public
233
- */
234
- add(job) {
235
- this.jobs.push(job);
236
- this[kRun]();
237
- }
238
- /**
239
- * Removes a job from the queue and runs it if possible.
240
- *
241
- * @private
242
- */
243
- [kRun]() {
244
- if (this.pending === this.concurrency) return;
245
- if (this.jobs.length) {
246
- const job = this.jobs.shift();
247
- this.pending++;
248
- job(this[kDone]);
249
- }
250
- }
251
- };
252
- module.exports = Limiter;
253
- }
254
- });
255
-
256
- // packages/cli/node_modules/ws/lib/permessage-deflate.js
257
- var require_permessage_deflate = __commonJS({
258
- "packages/cli/node_modules/ws/lib/permessage-deflate.js"(exports, module) {
259
- "use strict";
260
- var zlib2 = __require("zlib");
261
- var bufferUtil = require_buffer_util();
262
- var Limiter = require_limiter();
263
- var { kStatusCode } = require_constants();
264
- var FastBuffer = Buffer[Symbol.species];
265
- var TRAILER = Buffer.from([0, 0, 255, 255]);
266
- var kPerMessageDeflate = Symbol("permessage-deflate");
267
- var kTotalLength = Symbol("total-length");
268
- var kCallback = Symbol("callback");
269
- var kBuffers = Symbol("buffers");
270
- var kError = Symbol("error");
271
- var zlibLimiter;
272
- var PerMessageDeflate = class {
273
- /**
274
- * Creates a PerMessageDeflate instance.
275
- *
276
- * @param {Object} [options] Configuration options
277
- * @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support
278
- * for, or request, a custom client window size
279
- * @param {Boolean} [options.clientNoContextTakeover=false] Advertise/
280
- * acknowledge disabling of client context takeover
281
- * @param {Number} [options.concurrencyLimit=10] The number of concurrent
282
- * calls to zlib
283
- * @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the
284
- * use of a custom server window size
285
- * @param {Boolean} [options.serverNoContextTakeover=false] Request/accept
286
- * disabling of server context takeover
287
- * @param {Number} [options.threshold=1024] Size (in bytes) below which
288
- * messages should not be compressed if context takeover is disabled
289
- * @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on
290
- * deflate
291
- * @param {Object} [options.zlibInflateOptions] Options to pass to zlib on
292
- * inflate
293
- * @param {Boolean} [isServer=false] Create the instance in either server or
294
- * client mode
295
- * @param {Number} [maxPayload=0] The maximum allowed message length
296
- */
297
- constructor(options, isServer, maxPayload) {
298
- this._maxPayload = maxPayload | 0;
299
- this._options = options || {};
300
- this._threshold = this._options.threshold !== void 0 ? this._options.threshold : 1024;
301
- this._isServer = !!isServer;
302
- this._deflate = null;
303
- this._inflate = null;
304
- this.params = null;
305
- if (!zlibLimiter) {
306
- const concurrency = this._options.concurrencyLimit !== void 0 ? this._options.concurrencyLimit : 10;
307
- zlibLimiter = new Limiter(concurrency);
308
- }
309
- }
310
- /**
311
- * @type {String}
312
- */
313
- static get extensionName() {
314
- return "permessage-deflate";
315
- }
316
- /**
317
- * Create an extension negotiation offer.
318
- *
319
- * @return {Object} Extension parameters
320
- * @public
321
- */
322
- offer() {
323
- const params = {};
324
- if (this._options.serverNoContextTakeover) {
325
- params.server_no_context_takeover = true;
326
- }
327
- if (this._options.clientNoContextTakeover) {
328
- params.client_no_context_takeover = true;
329
- }
330
- if (this._options.serverMaxWindowBits) {
331
- params.server_max_window_bits = this._options.serverMaxWindowBits;
332
- }
333
- if (this._options.clientMaxWindowBits) {
334
- params.client_max_window_bits = this._options.clientMaxWindowBits;
335
- } else if (this._options.clientMaxWindowBits == null) {
336
- params.client_max_window_bits = true;
337
- }
338
- return params;
339
- }
340
- /**
341
- * Accept an extension negotiation offer/response.
342
- *
343
- * @param {Array} configurations The extension negotiation offers/reponse
344
- * @return {Object} Accepted configuration
345
- * @public
346
- */
347
- accept(configurations) {
348
- configurations = this.normalizeParams(configurations);
349
- this.params = this._isServer ? this.acceptAsServer(configurations) : this.acceptAsClient(configurations);
350
- return this.params;
351
- }
352
- /**
353
- * Releases all resources used by the extension.
354
- *
355
- * @public
356
- */
357
- cleanup() {
358
- if (this._inflate) {
359
- this._inflate.close();
360
- this._inflate = null;
361
- }
362
- if (this._deflate) {
363
- const callback = this._deflate[kCallback];
364
- this._deflate.close();
365
- this._deflate = null;
366
- if (callback) {
367
- callback(
368
- new Error(
369
- "The deflate stream was closed while data was being processed"
370
- )
371
- );
372
- }
373
- }
374
- }
375
- /**
376
- * Accept an extension negotiation offer.
377
- *
378
- * @param {Array} offers The extension negotiation offers
379
- * @return {Object} Accepted configuration
380
- * @private
381
- */
382
- acceptAsServer(offers) {
383
- const opts = this._options;
384
- const accepted = offers.find((params) => {
385
- if (opts.serverNoContextTakeover === false && params.server_no_context_takeover || params.server_max_window_bits && (opts.serverMaxWindowBits === false || typeof opts.serverMaxWindowBits === "number" && opts.serverMaxWindowBits > params.server_max_window_bits) || typeof opts.clientMaxWindowBits === "number" && !params.client_max_window_bits) {
386
- return false;
387
- }
388
- return true;
389
- });
390
- if (!accepted) {
391
- throw new Error("None of the extension offers can be accepted");
392
- }
393
- if (opts.serverNoContextTakeover) {
394
- accepted.server_no_context_takeover = true;
395
- }
396
- if (opts.clientNoContextTakeover) {
397
- accepted.client_no_context_takeover = true;
398
- }
399
- if (typeof opts.serverMaxWindowBits === "number") {
400
- accepted.server_max_window_bits = opts.serverMaxWindowBits;
401
- }
402
- if (typeof opts.clientMaxWindowBits === "number") {
403
- accepted.client_max_window_bits = opts.clientMaxWindowBits;
404
- } else if (accepted.client_max_window_bits === true || opts.clientMaxWindowBits === false) {
405
- delete accepted.client_max_window_bits;
406
- }
407
- return accepted;
408
- }
409
- /**
410
- * Accept the extension negotiation response.
411
- *
412
- * @param {Array} response The extension negotiation response
413
- * @return {Object} Accepted configuration
414
- * @private
415
- */
416
- acceptAsClient(response) {
417
- const params = response[0];
418
- if (this._options.clientNoContextTakeover === false && params.client_no_context_takeover) {
419
- throw new Error('Unexpected parameter "client_no_context_takeover"');
420
- }
421
- if (!params.client_max_window_bits) {
422
- if (typeof this._options.clientMaxWindowBits === "number") {
423
- params.client_max_window_bits = this._options.clientMaxWindowBits;
424
- }
425
- } else if (this._options.clientMaxWindowBits === false || typeof this._options.clientMaxWindowBits === "number" && params.client_max_window_bits > this._options.clientMaxWindowBits) {
426
- throw new Error(
427
- 'Unexpected or invalid parameter "client_max_window_bits"'
428
- );
429
- }
430
- return params;
431
- }
432
- /**
433
- * Normalize parameters.
434
- *
435
- * @param {Array} configurations The extension negotiation offers/reponse
436
- * @return {Array} The offers/response with normalized parameters
437
- * @private
438
- */
439
- normalizeParams(configurations) {
440
- configurations.forEach((params) => {
441
- Object.keys(params).forEach((key) => {
442
- let value = params[key];
443
- if (value.length > 1) {
444
- throw new Error(`Parameter "${key}" must have only a single value`);
445
- }
446
- value = value[0];
447
- if (key === "client_max_window_bits") {
448
- if (value !== true) {
449
- const num = +value;
450
- if (!Number.isInteger(num) || num < 8 || num > 15) {
451
- throw new TypeError(
452
- `Invalid value for parameter "${key}": ${value}`
453
- );
454
- }
455
- value = num;
456
- } else if (!this._isServer) {
457
- throw new TypeError(
458
- `Invalid value for parameter "${key}": ${value}`
459
- );
460
- }
461
- } else if (key === "server_max_window_bits") {
462
- const num = +value;
463
- if (!Number.isInteger(num) || num < 8 || num > 15) {
464
- throw new TypeError(
465
- `Invalid value for parameter "${key}": ${value}`
466
- );
467
- }
468
- value = num;
469
- } else if (key === "client_no_context_takeover" || key === "server_no_context_takeover") {
470
- if (value !== true) {
471
- throw new TypeError(
472
- `Invalid value for parameter "${key}": ${value}`
473
- );
474
- }
475
- } else {
476
- throw new Error(`Unknown parameter "${key}"`);
477
- }
478
- params[key] = value;
479
- });
480
- });
481
- return configurations;
482
- }
483
- /**
484
- * Decompress data. Concurrency limited.
485
- *
486
- * @param {Buffer} data Compressed data
487
- * @param {Boolean} fin Specifies whether or not this is the last fragment
488
- * @param {Function} callback Callback
489
- * @public
490
- */
491
- decompress(data, fin, callback) {
492
- zlibLimiter.add((done) => {
493
- this._decompress(data, fin, (err, result) => {
494
- done();
495
- callback(err, result);
496
- });
497
- });
498
- }
499
- /**
500
- * Compress data. Concurrency limited.
501
- *
502
- * @param {(Buffer|String)} data Data to compress
503
- * @param {Boolean} fin Specifies whether or not this is the last fragment
504
- * @param {Function} callback Callback
505
- * @public
506
- */
507
- compress(data, fin, callback) {
508
- zlibLimiter.add((done) => {
509
- this._compress(data, fin, (err, result) => {
510
- done();
511
- callback(err, result);
512
- });
513
- });
514
- }
515
- /**
516
- * Decompress data.
517
- *
518
- * @param {Buffer} data Compressed data
519
- * @param {Boolean} fin Specifies whether or not this is the last fragment
520
- * @param {Function} callback Callback
521
- * @private
522
- */
523
- _decompress(data, fin, callback) {
524
- const endpoint = this._isServer ? "client" : "server";
525
- if (!this._inflate) {
526
- const key = `${endpoint}_max_window_bits`;
527
- const windowBits = typeof this.params[key] !== "number" ? zlib2.Z_DEFAULT_WINDOWBITS : this.params[key];
528
- this._inflate = zlib2.createInflateRaw({
529
- ...this._options.zlibInflateOptions,
530
- windowBits
531
- });
532
- this._inflate[kPerMessageDeflate] = this;
533
- this._inflate[kTotalLength] = 0;
534
- this._inflate[kBuffers] = [];
535
- this._inflate.on("error", inflateOnError);
536
- this._inflate.on("data", inflateOnData);
537
- }
538
- this._inflate[kCallback] = callback;
539
- this._inflate.write(data);
540
- if (fin) this._inflate.write(TRAILER);
541
- this._inflate.flush(() => {
542
- const err = this._inflate[kError];
543
- if (err) {
544
- this._inflate.close();
545
- this._inflate = null;
546
- callback(err);
547
- return;
548
- }
549
- const data2 = bufferUtil.concat(
550
- this._inflate[kBuffers],
551
- this._inflate[kTotalLength]
552
- );
553
- if (this._inflate._readableState.endEmitted) {
554
- this._inflate.close();
555
- this._inflate = null;
556
- } else {
557
- this._inflate[kTotalLength] = 0;
558
- this._inflate[kBuffers] = [];
559
- if (fin && this.params[`${endpoint}_no_context_takeover`]) {
560
- this._inflate.reset();
561
- }
562
- }
563
- callback(null, data2);
564
- });
565
- }
566
- /**
567
- * Compress data.
568
- *
569
- * @param {(Buffer|String)} data Data to compress
570
- * @param {Boolean} fin Specifies whether or not this is the last fragment
571
- * @param {Function} callback Callback
572
- * @private
573
- */
574
- _compress(data, fin, callback) {
575
- const endpoint = this._isServer ? "server" : "client";
576
- if (!this._deflate) {
577
- const key = `${endpoint}_max_window_bits`;
578
- const windowBits = typeof this.params[key] !== "number" ? zlib2.Z_DEFAULT_WINDOWBITS : this.params[key];
579
- this._deflate = zlib2.createDeflateRaw({
580
- ...this._options.zlibDeflateOptions,
581
- windowBits
582
- });
583
- this._deflate[kTotalLength] = 0;
584
- this._deflate[kBuffers] = [];
585
- this._deflate.on("data", deflateOnData);
586
- }
587
- this._deflate[kCallback] = callback;
588
- this._deflate.write(data);
589
- this._deflate.flush(zlib2.Z_SYNC_FLUSH, () => {
590
- if (!this._deflate) {
591
- return;
592
- }
593
- let data2 = bufferUtil.concat(
594
- this._deflate[kBuffers],
595
- this._deflate[kTotalLength]
596
- );
597
- if (fin) {
598
- data2 = new FastBuffer(data2.buffer, data2.byteOffset, data2.length - 4);
599
- }
600
- this._deflate[kCallback] = null;
601
- this._deflate[kTotalLength] = 0;
602
- this._deflate[kBuffers] = [];
603
- if (fin && this.params[`${endpoint}_no_context_takeover`]) {
604
- this._deflate.reset();
605
- }
606
- callback(null, data2);
607
- });
608
- }
609
- };
610
- module.exports = PerMessageDeflate;
611
- function deflateOnData(chunk) {
612
- this[kBuffers].push(chunk);
613
- this[kTotalLength] += chunk.length;
614
- }
615
- function inflateOnData(chunk) {
616
- this[kTotalLength] += chunk.length;
617
- if (this[kPerMessageDeflate]._maxPayload < 1 || this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload) {
618
- this[kBuffers].push(chunk);
619
- return;
620
- }
621
- this[kError] = new RangeError("Max payload size exceeded");
622
- this[kError].code = "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH";
623
- this[kError][kStatusCode] = 1009;
624
- this.removeListener("data", inflateOnData);
625
- this.reset();
626
- }
627
- function inflateOnError(err) {
628
- this[kPerMessageDeflate]._inflate = null;
629
- err[kStatusCode] = 1007;
630
- this[kCallback](err);
631
- }
632
- }
633
- });
634
-
635
- // packages/cli/node_modules/ws/lib/validation.js
636
- var require_validation = __commonJS({
637
- "packages/cli/node_modules/ws/lib/validation.js"(exports, module) {
638
- "use strict";
639
- var { isUtf8 } = __require("buffer");
640
- var tokenChars = [
641
- 0,
642
- 0,
643
- 0,
644
- 0,
645
- 0,
646
- 0,
647
- 0,
648
- 0,
649
- 0,
650
- 0,
651
- 0,
652
- 0,
653
- 0,
654
- 0,
655
- 0,
656
- 0,
657
- // 0 - 15
658
- 0,
659
- 0,
660
- 0,
661
- 0,
662
- 0,
663
- 0,
664
- 0,
665
- 0,
666
- 0,
667
- 0,
668
- 0,
669
- 0,
670
- 0,
671
- 0,
672
- 0,
673
- 0,
674
- // 16 - 31
675
- 0,
676
- 1,
677
- 0,
678
- 1,
679
- 1,
680
- 1,
681
- 1,
682
- 1,
683
- 0,
684
- 0,
685
- 1,
686
- 1,
687
- 0,
688
- 1,
689
- 1,
690
- 0,
691
- // 32 - 47
692
- 1,
693
- 1,
694
- 1,
695
- 1,
696
- 1,
697
- 1,
698
- 1,
699
- 1,
700
- 1,
701
- 1,
702
- 0,
703
- 0,
704
- 0,
705
- 0,
706
- 0,
707
- 0,
708
- // 48 - 63
709
- 0,
710
- 1,
711
- 1,
712
- 1,
713
- 1,
714
- 1,
715
- 1,
716
- 1,
717
- 1,
718
- 1,
719
- 1,
720
- 1,
721
- 1,
722
- 1,
723
- 1,
724
- 1,
725
- // 64 - 79
726
- 1,
727
- 1,
728
- 1,
729
- 1,
730
- 1,
731
- 1,
732
- 1,
733
- 1,
734
- 1,
735
- 1,
736
- 1,
737
- 0,
738
- 0,
739
- 0,
740
- 1,
741
- 1,
742
- // 80 - 95
743
- 1,
744
- 1,
745
- 1,
746
- 1,
747
- 1,
748
- 1,
749
- 1,
750
- 1,
751
- 1,
752
- 1,
753
- 1,
754
- 1,
755
- 1,
756
- 1,
757
- 1,
758
- 1,
759
- // 96 - 111
760
- 1,
761
- 1,
762
- 1,
763
- 1,
764
- 1,
765
- 1,
766
- 1,
767
- 1,
768
- 1,
769
- 1,
770
- 1,
771
- 0,
772
- 1,
773
- 0,
774
- 1,
775
- 0
776
- // 112 - 127
777
- ];
778
- function isValidStatusCode(code) {
779
- return code >= 1e3 && code <= 1014 && code !== 1004 && code !== 1005 && code !== 1006 || code >= 3e3 && code <= 4999;
780
- }
781
- function _isValidUTF8(buf) {
782
- const len = buf.length;
783
- let i = 0;
784
- while (i < len) {
785
- if ((buf[i] & 128) === 0) {
786
- i++;
787
- } else if ((buf[i] & 224) === 192) {
788
- if (i + 1 === len || (buf[i + 1] & 192) !== 128 || (buf[i] & 254) === 192) {
789
- return false;
790
- }
791
- i += 2;
792
- } else if ((buf[i] & 240) === 224) {
793
- if (i + 2 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || buf[i] === 224 && (buf[i + 1] & 224) === 128 || // Overlong
794
- buf[i] === 237 && (buf[i + 1] & 224) === 160) {
795
- return false;
796
- }
797
- i += 3;
798
- } else if ((buf[i] & 248) === 240) {
799
- 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
800
- buf[i] === 244 && buf[i + 1] > 143 || buf[i] > 244) {
801
- return false;
802
- }
803
- i += 4;
804
- } else {
805
- return false;
806
- }
807
- }
808
- return true;
809
- }
810
- module.exports = {
811
- isValidStatusCode,
812
- isValidUTF8: _isValidUTF8,
813
- tokenChars
814
- };
815
- if (isUtf8) {
816
- module.exports.isValidUTF8 = function(buf) {
817
- return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf);
818
- };
819
- } else if (!process.env.WS_NO_UTF_8_VALIDATE) {
820
- try {
821
- const isValidUTF8 = __require("utf-8-validate");
822
- module.exports.isValidUTF8 = function(buf) {
823
- return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf);
824
- };
825
- } catch (e) {
826
- }
827
- }
828
- }
829
- });
830
-
831
- // packages/cli/node_modules/ws/lib/receiver.js
832
- var require_receiver = __commonJS({
833
- "packages/cli/node_modules/ws/lib/receiver.js"(exports, module) {
834
- "use strict";
835
- var { Writable } = __require("stream");
836
- var PerMessageDeflate = require_permessage_deflate();
837
- var {
838
- BINARY_TYPES,
839
- EMPTY_BUFFER,
840
- kStatusCode,
841
- kWebSocket
842
- } = require_constants();
843
- var { concat, toArrayBuffer, unmask } = require_buffer_util();
844
- var { isValidStatusCode, isValidUTF8 } = require_validation();
845
- var FastBuffer = Buffer[Symbol.species];
846
- var promise = Promise.resolve();
847
- var queueTask = typeof queueMicrotask === "function" ? queueMicrotask : queueMicrotaskShim;
848
- var GET_INFO = 0;
849
- var GET_PAYLOAD_LENGTH_16 = 1;
850
- var GET_PAYLOAD_LENGTH_64 = 2;
851
- var GET_MASK = 3;
852
- var GET_DATA = 4;
853
- var INFLATING = 5;
854
- var DEFER_EVENT = 6;
855
- var Receiver2 = class extends Writable {
856
- /**
857
- * Creates a Receiver instance.
858
- *
859
- * @param {Object} [options] Options object
860
- * @param {Boolean} [options.allowSynchronousEvents=false] Specifies whether
861
- * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
862
- * multiple times in the same tick
863
- * @param {String} [options.binaryType=nodebuffer] The type for binary data
864
- * @param {Object} [options.extensions] An object containing the negotiated
865
- * extensions
866
- * @param {Boolean} [options.isServer=false] Specifies whether to operate in
867
- * client or server mode
868
- * @param {Number} [options.maxPayload=0] The maximum allowed message length
869
- * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
870
- * not to skip UTF-8 validation for text and close messages
871
- */
872
- constructor(options = {}) {
873
- super();
874
- this._allowSynchronousEvents = !!options.allowSynchronousEvents;
875
- this._binaryType = options.binaryType || BINARY_TYPES[0];
876
- this._extensions = options.extensions || {};
877
- this._isServer = !!options.isServer;
878
- this._maxPayload = options.maxPayload | 0;
879
- this._skipUTF8Validation = !!options.skipUTF8Validation;
880
- this[kWebSocket] = void 0;
881
- this._bufferedBytes = 0;
882
- this._buffers = [];
883
- this._compressed = false;
884
- this._payloadLength = 0;
885
- this._mask = void 0;
886
- this._fragmented = 0;
887
- this._masked = false;
888
- this._fin = false;
889
- this._opcode = 0;
890
- this._totalPayloadLength = 0;
891
- this._messageLength = 0;
892
- this._fragments = [];
893
- this._errored = false;
894
- this._loop = false;
895
- this._state = GET_INFO;
896
- }
897
- /**
898
- * Implements `Writable.prototype._write()`.
899
- *
900
- * @param {Buffer} chunk The chunk of data to write
901
- * @param {String} encoding The character encoding of `chunk`
902
- * @param {Function} cb Callback
903
- * @private
904
- */
905
- _write(chunk, encoding, cb) {
906
- if (this._opcode === 8 && this._state == GET_INFO) return cb();
907
- this._bufferedBytes += chunk.length;
908
- this._buffers.push(chunk);
909
- this.startLoop(cb);
910
- }
911
- /**
912
- * Consumes `n` bytes from the buffered data.
913
- *
914
- * @param {Number} n The number of bytes to consume
915
- * @return {Buffer} The consumed bytes
916
- * @private
917
- */
918
- consume(n) {
919
- this._bufferedBytes -= n;
920
- if (n === this._buffers[0].length) return this._buffers.shift();
921
- if (n < this._buffers[0].length) {
922
- const buf = this._buffers[0];
923
- this._buffers[0] = new FastBuffer(
924
- buf.buffer,
925
- buf.byteOffset + n,
926
- buf.length - n
927
- );
928
- return new FastBuffer(buf.buffer, buf.byteOffset, n);
929
- }
930
- const dst = Buffer.allocUnsafe(n);
931
- do {
932
- const buf = this._buffers[0];
933
- const offset = dst.length - n;
934
- if (n >= buf.length) {
935
- dst.set(this._buffers.shift(), offset);
936
- } else {
937
- dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset);
938
- this._buffers[0] = new FastBuffer(
939
- buf.buffer,
940
- buf.byteOffset + n,
941
- buf.length - n
942
- );
943
- }
944
- n -= buf.length;
945
- } while (n > 0);
946
- return dst;
947
- }
948
- /**
949
- * Starts the parsing loop.
950
- *
951
- * @param {Function} cb Callback
952
- * @private
953
- */
954
- startLoop(cb) {
955
- this._loop = true;
956
- do {
957
- switch (this._state) {
958
- case GET_INFO:
959
- this.getInfo(cb);
960
- break;
961
- case GET_PAYLOAD_LENGTH_16:
962
- this.getPayloadLength16(cb);
963
- break;
964
- case GET_PAYLOAD_LENGTH_64:
965
- this.getPayloadLength64(cb);
966
- break;
967
- case GET_MASK:
968
- this.getMask();
969
- break;
970
- case GET_DATA:
971
- this.getData(cb);
972
- break;
973
- case INFLATING:
974
- case DEFER_EVENT:
975
- this._loop = false;
976
- return;
977
- }
978
- } while (this._loop);
979
- if (!this._errored) cb();
980
- }
981
- /**
982
- * Reads the first two bytes of a frame.
983
- *
984
- * @param {Function} cb Callback
985
- * @private
986
- */
987
- getInfo(cb) {
988
- if (this._bufferedBytes < 2) {
989
- this._loop = false;
990
- return;
991
- }
992
- const buf = this.consume(2);
993
- if ((buf[0] & 48) !== 0) {
994
- const error = this.createError(
995
- RangeError,
996
- "RSV2 and RSV3 must be clear",
997
- true,
998
- 1002,
999
- "WS_ERR_UNEXPECTED_RSV_2_3"
1000
- );
1001
- cb(error);
1002
- return;
1003
- }
1004
- const compressed = (buf[0] & 64) === 64;
1005
- if (compressed && !this._extensions[PerMessageDeflate.extensionName]) {
1006
- const error = this.createError(
1007
- RangeError,
1008
- "RSV1 must be clear",
1009
- true,
1010
- 1002,
1011
- "WS_ERR_UNEXPECTED_RSV_1"
1012
- );
1013
- cb(error);
1014
- return;
1015
- }
1016
- this._fin = (buf[0] & 128) === 128;
1017
- this._opcode = buf[0] & 15;
1018
- this._payloadLength = buf[1] & 127;
1019
- if (this._opcode === 0) {
1020
- if (compressed) {
1021
- const error = this.createError(
1022
- RangeError,
1023
- "RSV1 must be clear",
1024
- true,
1025
- 1002,
1026
- "WS_ERR_UNEXPECTED_RSV_1"
1027
- );
1028
- cb(error);
1029
- return;
1030
- }
1031
- if (!this._fragmented) {
1032
- const error = this.createError(
1033
- RangeError,
1034
- "invalid opcode 0",
1035
- true,
1036
- 1002,
1037
- "WS_ERR_INVALID_OPCODE"
1038
- );
1039
- cb(error);
1040
- return;
1041
- }
1042
- this._opcode = this._fragmented;
1043
- } else if (this._opcode === 1 || this._opcode === 2) {
1044
- if (this._fragmented) {
1045
- const error = this.createError(
1046
- RangeError,
1047
- `invalid opcode ${this._opcode}`,
1048
- true,
1049
- 1002,
1050
- "WS_ERR_INVALID_OPCODE"
1051
- );
1052
- cb(error);
1053
- return;
1054
- }
1055
- this._compressed = compressed;
1056
- } else if (this._opcode > 7 && this._opcode < 11) {
1057
- if (!this._fin) {
1058
- const error = this.createError(
1059
- RangeError,
1060
- "FIN must be set",
1061
- true,
1062
- 1002,
1063
- "WS_ERR_EXPECTED_FIN"
1064
- );
1065
- cb(error);
1066
- return;
1067
- }
1068
- if (compressed) {
1069
- const error = this.createError(
1070
- RangeError,
1071
- "RSV1 must be clear",
1072
- true,
1073
- 1002,
1074
- "WS_ERR_UNEXPECTED_RSV_1"
1075
- );
1076
- cb(error);
1077
- return;
1078
- }
1079
- if (this._payloadLength > 125 || this._opcode === 8 && this._payloadLength === 1) {
1080
- const error = this.createError(
1081
- RangeError,
1082
- `invalid payload length ${this._payloadLength}`,
1083
- true,
1084
- 1002,
1085
- "WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH"
1086
- );
1087
- cb(error);
1088
- return;
1089
- }
1090
- } else {
1091
- const error = this.createError(
1092
- RangeError,
1093
- `invalid opcode ${this._opcode}`,
1094
- true,
1095
- 1002,
1096
- "WS_ERR_INVALID_OPCODE"
1097
- );
1098
- cb(error);
1099
- return;
1100
- }
1101
- if (!this._fin && !this._fragmented) this._fragmented = this._opcode;
1102
- this._masked = (buf[1] & 128) === 128;
1103
- if (this._isServer) {
1104
- if (!this._masked) {
1105
- const error = this.createError(
1106
- RangeError,
1107
- "MASK must be set",
1108
- true,
1109
- 1002,
1110
- "WS_ERR_EXPECTED_MASK"
1111
- );
1112
- cb(error);
1113
- return;
1114
- }
1115
- } else if (this._masked) {
1116
- const error = this.createError(
1117
- RangeError,
1118
- "MASK must be clear",
1119
- true,
1120
- 1002,
1121
- "WS_ERR_UNEXPECTED_MASK"
1122
- );
1123
- cb(error);
1124
- return;
1125
- }
1126
- if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16;
1127
- else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64;
1128
- else this.haveLength(cb);
1129
- }
1130
- /**
1131
- * Gets extended payload length (7+16).
1132
- *
1133
- * @param {Function} cb Callback
1134
- * @private
1135
- */
1136
- getPayloadLength16(cb) {
1137
- if (this._bufferedBytes < 2) {
1138
- this._loop = false;
1139
- return;
1140
- }
1141
- this._payloadLength = this.consume(2).readUInt16BE(0);
1142
- this.haveLength(cb);
1143
- }
1144
- /**
1145
- * Gets extended payload length (7+64).
1146
- *
1147
- * @param {Function} cb Callback
1148
- * @private
1149
- */
1150
- getPayloadLength64(cb) {
1151
- if (this._bufferedBytes < 8) {
1152
- this._loop = false;
1153
- return;
1154
- }
1155
- const buf = this.consume(8);
1156
- const num = buf.readUInt32BE(0);
1157
- if (num > Math.pow(2, 53 - 32) - 1) {
1158
- const error = this.createError(
1159
- RangeError,
1160
- "Unsupported WebSocket frame: payload length > 2^53 - 1",
1161
- false,
1162
- 1009,
1163
- "WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH"
1164
- );
1165
- cb(error);
1166
- return;
1167
- }
1168
- this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4);
1169
- this.haveLength(cb);
1170
- }
1171
- /**
1172
- * Payload length has been read.
1173
- *
1174
- * @param {Function} cb Callback
1175
- * @private
1176
- */
1177
- haveLength(cb) {
1178
- if (this._payloadLength && this._opcode < 8) {
1179
- this._totalPayloadLength += this._payloadLength;
1180
- if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) {
1181
- const error = this.createError(
1182
- RangeError,
1183
- "Max payload size exceeded",
1184
- false,
1185
- 1009,
1186
- "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"
1187
- );
1188
- cb(error);
1189
- return;
1190
- }
1191
- }
1192
- if (this._masked) this._state = GET_MASK;
1193
- else this._state = GET_DATA;
1194
- }
1195
- /**
1196
- * Reads mask bytes.
1197
- *
1198
- * @private
1199
- */
1200
- getMask() {
1201
- if (this._bufferedBytes < 4) {
1202
- this._loop = false;
1203
- return;
1204
- }
1205
- this._mask = this.consume(4);
1206
- this._state = GET_DATA;
1207
- }
1208
- /**
1209
- * Reads data bytes.
1210
- *
1211
- * @param {Function} cb Callback
1212
- * @private
1213
- */
1214
- getData(cb) {
1215
- let data = EMPTY_BUFFER;
1216
- if (this._payloadLength) {
1217
- if (this._bufferedBytes < this._payloadLength) {
1218
- this._loop = false;
1219
- return;
1220
- }
1221
- data = this.consume(this._payloadLength);
1222
- if (this._masked && (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0) {
1223
- unmask(data, this._mask);
1224
- }
1225
- }
1226
- if (this._opcode > 7) {
1227
- this.controlMessage(data, cb);
1228
- return;
1229
- }
1230
- if (this._compressed) {
1231
- this._state = INFLATING;
1232
- this.decompress(data, cb);
1233
- return;
1234
- }
1235
- if (data.length) {
1236
- this._messageLength = this._totalPayloadLength;
1237
- this._fragments.push(data);
1238
- }
1239
- this.dataMessage(cb);
1240
- }
1241
- /**
1242
- * Decompresses data.
1243
- *
1244
- * @param {Buffer} data Compressed data
1245
- * @param {Function} cb Callback
1246
- * @private
1247
- */
1248
- decompress(data, cb) {
1249
- const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
1250
- perMessageDeflate.decompress(data, this._fin, (err, buf) => {
1251
- if (err) return cb(err);
1252
- if (buf.length) {
1253
- this._messageLength += buf.length;
1254
- if (this._messageLength > this._maxPayload && this._maxPayload > 0) {
1255
- const error = this.createError(
1256
- RangeError,
1257
- "Max payload size exceeded",
1258
- false,
1259
- 1009,
1260
- "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"
1261
- );
1262
- cb(error);
1263
- return;
1264
- }
1265
- this._fragments.push(buf);
1266
- }
1267
- this.dataMessage(cb);
1268
- if (this._state === GET_INFO) this.startLoop(cb);
1269
- });
1270
- }
1271
- /**
1272
- * Handles a data message.
1273
- *
1274
- * @param {Function} cb Callback
1275
- * @private
1276
- */
1277
- dataMessage(cb) {
1278
- if (!this._fin) {
1279
- this._state = GET_INFO;
1280
- return;
1281
- }
1282
- const messageLength = this._messageLength;
1283
- const fragments = this._fragments;
1284
- this._totalPayloadLength = 0;
1285
- this._messageLength = 0;
1286
- this._fragmented = 0;
1287
- this._fragments = [];
1288
- if (this._opcode === 2) {
1289
- let data;
1290
- if (this._binaryType === "nodebuffer") {
1291
- data = concat(fragments, messageLength);
1292
- } else if (this._binaryType === "arraybuffer") {
1293
- data = toArrayBuffer(concat(fragments, messageLength));
1294
- } else {
1295
- data = fragments;
1296
- }
1297
- if (this._state === INFLATING || this._allowSynchronousEvents) {
1298
- this.emit("message", data, true);
1299
- this._state = GET_INFO;
1300
- } else {
1301
- this._state = DEFER_EVENT;
1302
- queueTask(() => {
1303
- this.emit("message", data, true);
1304
- this._state = GET_INFO;
1305
- this.startLoop(cb);
1306
- });
1307
- }
1308
- } else {
1309
- const buf = concat(fragments, messageLength);
1310
- if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
1311
- const error = this.createError(
1312
- Error,
1313
- "invalid UTF-8 sequence",
1314
- true,
1315
- 1007,
1316
- "WS_ERR_INVALID_UTF8"
1317
- );
1318
- cb(error);
1319
- return;
1320
- }
1321
- if (this._state === INFLATING || this._allowSynchronousEvents) {
1322
- this.emit("message", buf, false);
1323
- this._state = GET_INFO;
1324
- } else {
1325
- this._state = DEFER_EVENT;
1326
- queueTask(() => {
1327
- this.emit("message", buf, false);
1328
- this._state = GET_INFO;
1329
- this.startLoop(cb);
1330
- });
1331
- }
1332
- }
1333
- }
1334
- /**
1335
- * Handles a control message.
1336
- *
1337
- * @param {Buffer} data Data to handle
1338
- * @return {(Error|RangeError|undefined)} A possible error
1339
- * @private
1340
- */
1341
- controlMessage(data, cb) {
1342
- if (this._opcode === 8) {
1343
- if (data.length === 0) {
1344
- this._loop = false;
1345
- this.emit("conclude", 1005, EMPTY_BUFFER);
1346
- this.end();
1347
- } else {
1348
- const code = data.readUInt16BE(0);
1349
- if (!isValidStatusCode(code)) {
1350
- const error = this.createError(
1351
- RangeError,
1352
- `invalid status code ${code}`,
1353
- true,
1354
- 1002,
1355
- "WS_ERR_INVALID_CLOSE_CODE"
1356
- );
1357
- cb(error);
1358
- return;
1359
- }
1360
- const buf = new FastBuffer(
1361
- data.buffer,
1362
- data.byteOffset + 2,
1363
- data.length - 2
1364
- );
1365
- if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
1366
- const error = this.createError(
1367
- Error,
1368
- "invalid UTF-8 sequence",
1369
- true,
1370
- 1007,
1371
- "WS_ERR_INVALID_UTF8"
1372
- );
1373
- cb(error);
1374
- return;
1375
- }
1376
- this._loop = false;
1377
- this.emit("conclude", code, buf);
1378
- this.end();
1379
- }
1380
- this._state = GET_INFO;
1381
- return;
1382
- }
1383
- if (this._allowSynchronousEvents) {
1384
- this.emit(this._opcode === 9 ? "ping" : "pong", data);
1385
- this._state = GET_INFO;
1386
- } else {
1387
- this._state = DEFER_EVENT;
1388
- queueTask(() => {
1389
- this.emit(this._opcode === 9 ? "ping" : "pong", data);
1390
- this._state = GET_INFO;
1391
- this.startLoop(cb);
1392
- });
1393
- }
1394
- }
1395
- /**
1396
- * Builds an error object.
1397
- *
1398
- * @param {function(new:Error|RangeError)} ErrorCtor The error constructor
1399
- * @param {String} message The error message
1400
- * @param {Boolean} prefix Specifies whether or not to add a default prefix to
1401
- * `message`
1402
- * @param {Number} statusCode The status code
1403
- * @param {String} errorCode The exposed error code
1404
- * @return {(Error|RangeError)} The error
1405
- * @private
1406
- */
1407
- createError(ErrorCtor, message, prefix, statusCode, errorCode) {
1408
- this._loop = false;
1409
- this._errored = true;
1410
- const err = new ErrorCtor(
1411
- prefix ? `Invalid WebSocket frame: ${message}` : message
1412
- );
1413
- Error.captureStackTrace(err, this.createError);
1414
- err.code = errorCode;
1415
- err[kStatusCode] = statusCode;
1416
- return err;
1417
- }
1418
- };
1419
- module.exports = Receiver2;
1420
- function queueMicrotaskShim(cb) {
1421
- promise.then(cb).catch(throwErrorNextTick);
1422
- }
1423
- function throwError(err) {
1424
- throw err;
1425
- }
1426
- function throwErrorNextTick(err) {
1427
- process.nextTick(throwError, err);
1428
- }
1429
- }
1430
- });
1431
-
1432
- // packages/cli/node_modules/ws/lib/sender.js
1433
- var require_sender = __commonJS({
1434
- "packages/cli/node_modules/ws/lib/sender.js"(exports, module) {
1435
- "use strict";
1436
- var { Duplex } = __require("stream");
1437
- var { randomFillSync } = __require("crypto");
1438
- var PerMessageDeflate = require_permessage_deflate();
1439
- var { EMPTY_BUFFER } = require_constants();
1440
- var { isValidStatusCode } = require_validation();
1441
- var { mask: applyMask, toBuffer } = require_buffer_util();
1442
- var kByteLength = Symbol("kByteLength");
1443
- var maskBuffer = Buffer.alloc(4);
1444
- var Sender2 = class _Sender {
1445
- /**
1446
- * Creates a Sender instance.
1447
- *
1448
- * @param {Duplex} socket The connection socket
1449
- * @param {Object} [extensions] An object containing the negotiated extensions
1450
- * @param {Function} [generateMask] The function used to generate the masking
1451
- * key
1452
- */
1453
- constructor(socket, extensions, generateMask) {
1454
- this._extensions = extensions || {};
1455
- if (generateMask) {
1456
- this._generateMask = generateMask;
1457
- this._maskBuffer = Buffer.alloc(4);
1458
- }
1459
- this._socket = socket;
1460
- this._firstFragment = true;
1461
- this._compress = false;
1462
- this._bufferedBytes = 0;
1463
- this._deflating = false;
1464
- this._queue = [];
1465
- }
1466
- /**
1467
- * Frames a piece of data according to the HyBi WebSocket protocol.
1468
- *
1469
- * @param {(Buffer|String)} data The data to frame
1470
- * @param {Object} options Options object
1471
- * @param {Boolean} [options.fin=false] Specifies whether or not to set the
1472
- * FIN bit
1473
- * @param {Function} [options.generateMask] The function used to generate the
1474
- * masking key
1475
- * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1476
- * `data`
1477
- * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
1478
- * key
1479
- * @param {Number} options.opcode The opcode
1480
- * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
1481
- * modified
1482
- * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
1483
- * RSV1 bit
1484
- * @return {(Buffer|String)[]} The framed data
1485
- * @public
1486
- */
1487
- static frame(data, options) {
1488
- let mask;
1489
- let merge = false;
1490
- let offset = 2;
1491
- let skipMasking = false;
1492
- if (options.mask) {
1493
- mask = options.maskBuffer || maskBuffer;
1494
- if (options.generateMask) {
1495
- options.generateMask(mask);
1496
- } else {
1497
- randomFillSync(mask, 0, 4);
1498
- }
1499
- skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0;
1500
- offset = 6;
1501
- }
1502
- let dataLength;
1503
- if (typeof data === "string") {
1504
- if ((!options.mask || skipMasking) && options[kByteLength] !== void 0) {
1505
- dataLength = options[kByteLength];
1506
- } else {
1507
- data = Buffer.from(data);
1508
- dataLength = data.length;
1509
- }
1510
- } else {
1511
- dataLength = data.length;
1512
- merge = options.mask && options.readOnly && !skipMasking;
1513
- }
1514
- let payloadLength = dataLength;
1515
- if (dataLength >= 65536) {
1516
- offset += 8;
1517
- payloadLength = 127;
1518
- } else if (dataLength > 125) {
1519
- offset += 2;
1520
- payloadLength = 126;
1521
- }
1522
- const target = Buffer.allocUnsafe(merge ? dataLength + offset : offset);
1523
- target[0] = options.fin ? options.opcode | 128 : options.opcode;
1524
- if (options.rsv1) target[0] |= 64;
1525
- target[1] = payloadLength;
1526
- if (payloadLength === 126) {
1527
- target.writeUInt16BE(dataLength, 2);
1528
- } else if (payloadLength === 127) {
1529
- target[2] = target[3] = 0;
1530
- target.writeUIntBE(dataLength, 4, 6);
1531
- }
1532
- if (!options.mask) return [target, data];
1533
- target[1] |= 128;
1534
- target[offset - 4] = mask[0];
1535
- target[offset - 3] = mask[1];
1536
- target[offset - 2] = mask[2];
1537
- target[offset - 1] = mask[3];
1538
- if (skipMasking) return [target, data];
1539
- if (merge) {
1540
- applyMask(data, mask, target, offset, dataLength);
1541
- return [target];
1542
- }
1543
- applyMask(data, mask, data, 0, dataLength);
1544
- return [target, data];
1545
- }
1546
- /**
1547
- * Sends a close message to the other peer.
1548
- *
1549
- * @param {Number} [code] The status code component of the body
1550
- * @param {(String|Buffer)} [data] The message component of the body
1551
- * @param {Boolean} [mask=false] Specifies whether or not to mask the message
1552
- * @param {Function} [cb] Callback
1553
- * @public
1554
- */
1555
- close(code, data, mask, cb) {
1556
- let buf;
1557
- if (code === void 0) {
1558
- buf = EMPTY_BUFFER;
1559
- } else if (typeof code !== "number" || !isValidStatusCode(code)) {
1560
- throw new TypeError("First argument must be a valid error code number");
1561
- } else if (data === void 0 || !data.length) {
1562
- buf = Buffer.allocUnsafe(2);
1563
- buf.writeUInt16BE(code, 0);
1564
- } else {
1565
- const length = Buffer.byteLength(data);
1566
- if (length > 123) {
1567
- throw new RangeError("The message must not be greater than 123 bytes");
1568
- }
1569
- buf = Buffer.allocUnsafe(2 + length);
1570
- buf.writeUInt16BE(code, 0);
1571
- if (typeof data === "string") {
1572
- buf.write(data, 2);
1573
- } else {
1574
- buf.set(data, 2);
1575
- }
1576
- }
1577
- const options = {
1578
- [kByteLength]: buf.length,
1579
- fin: true,
1580
- generateMask: this._generateMask,
1581
- mask,
1582
- maskBuffer: this._maskBuffer,
1583
- opcode: 8,
1584
- readOnly: false,
1585
- rsv1: false
1586
- };
1587
- if (this._deflating) {
1588
- this.enqueue([this.dispatch, buf, false, options, cb]);
1589
- } else {
1590
- this.sendFrame(_Sender.frame(buf, options), cb);
1591
- }
1592
- }
1593
- /**
1594
- * Sends a ping message to the other peer.
1595
- *
1596
- * @param {*} data The message to send
1597
- * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
1598
- * @param {Function} [cb] Callback
1599
- * @public
1600
- */
1601
- ping(data, mask, cb) {
1602
- let byteLength;
1603
- let readOnly;
1604
- if (typeof data === "string") {
1605
- byteLength = Buffer.byteLength(data);
1606
- readOnly = false;
1607
- } else {
1608
- data = toBuffer(data);
1609
- byteLength = data.length;
1610
- readOnly = toBuffer.readOnly;
1611
- }
1612
- if (byteLength > 125) {
1613
- throw new RangeError("The data size must not be greater than 125 bytes");
1614
- }
1615
- const options = {
1616
- [kByteLength]: byteLength,
1617
- fin: true,
1618
- generateMask: this._generateMask,
1619
- mask,
1620
- maskBuffer: this._maskBuffer,
1621
- opcode: 9,
1622
- readOnly,
1623
- rsv1: false
1624
- };
1625
- if (this._deflating) {
1626
- this.enqueue([this.dispatch, data, false, options, cb]);
1627
- } else {
1628
- this.sendFrame(_Sender.frame(data, options), cb);
1629
- }
1630
- }
1631
- /**
1632
- * Sends a pong message to the other peer.
1633
- *
1634
- * @param {*} data The message to send
1635
- * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
1636
- * @param {Function} [cb] Callback
1637
- * @public
1638
- */
1639
- pong(data, mask, cb) {
1640
- let byteLength;
1641
- let readOnly;
1642
- if (typeof data === "string") {
1643
- byteLength = Buffer.byteLength(data);
1644
- readOnly = false;
1645
- } else {
1646
- data = toBuffer(data);
1647
- byteLength = data.length;
1648
- readOnly = toBuffer.readOnly;
1649
- }
1650
- if (byteLength > 125) {
1651
- throw new RangeError("The data size must not be greater than 125 bytes");
1652
- }
1653
- const options = {
1654
- [kByteLength]: byteLength,
1655
- fin: true,
1656
- generateMask: this._generateMask,
1657
- mask,
1658
- maskBuffer: this._maskBuffer,
1659
- opcode: 10,
1660
- readOnly,
1661
- rsv1: false
1662
- };
1663
- if (this._deflating) {
1664
- this.enqueue([this.dispatch, data, false, options, cb]);
1665
- } else {
1666
- this.sendFrame(_Sender.frame(data, options), cb);
1667
- }
1668
- }
1669
- /**
1670
- * Sends a data message to the other peer.
1671
- *
1672
- * @param {*} data The message to send
1673
- * @param {Object} options Options object
1674
- * @param {Boolean} [options.binary=false] Specifies whether `data` is binary
1675
- * or text
1676
- * @param {Boolean} [options.compress=false] Specifies whether or not to
1677
- * compress `data`
1678
- * @param {Boolean} [options.fin=false] Specifies whether the fragment is the
1679
- * last one
1680
- * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1681
- * `data`
1682
- * @param {Function} [cb] Callback
1683
- * @public
1684
- */
1685
- send(data, options, cb) {
1686
- const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
1687
- let opcode = options.binary ? 2 : 1;
1688
- let rsv1 = options.compress;
1689
- let byteLength;
1690
- let readOnly;
1691
- if (typeof data === "string") {
1692
- byteLength = Buffer.byteLength(data);
1693
- readOnly = false;
1694
- } else {
1695
- data = toBuffer(data);
1696
- byteLength = data.length;
1697
- readOnly = toBuffer.readOnly;
1698
- }
1699
- if (this._firstFragment) {
1700
- this._firstFragment = false;
1701
- if (rsv1 && perMessageDeflate && perMessageDeflate.params[perMessageDeflate._isServer ? "server_no_context_takeover" : "client_no_context_takeover"]) {
1702
- rsv1 = byteLength >= perMessageDeflate._threshold;
1703
- }
1704
- this._compress = rsv1;
1705
- } else {
1706
- rsv1 = false;
1707
- opcode = 0;
1708
- }
1709
- if (options.fin) this._firstFragment = true;
1710
- if (perMessageDeflate) {
1711
- const opts = {
1712
- [kByteLength]: byteLength,
1713
- fin: options.fin,
1714
- generateMask: this._generateMask,
1715
- mask: options.mask,
1716
- maskBuffer: this._maskBuffer,
1717
- opcode,
1718
- readOnly,
1719
- rsv1
1720
- };
1721
- if (this._deflating) {
1722
- this.enqueue([this.dispatch, data, this._compress, opts, cb]);
1723
- } else {
1724
- this.dispatch(data, this._compress, opts, cb);
1725
- }
1726
- } else {
1727
- this.sendFrame(
1728
- _Sender.frame(data, {
1729
- [kByteLength]: byteLength,
1730
- fin: options.fin,
1731
- generateMask: this._generateMask,
1732
- mask: options.mask,
1733
- maskBuffer: this._maskBuffer,
1734
- opcode,
1735
- readOnly,
1736
- rsv1: false
1737
- }),
1738
- cb
1739
- );
1740
- }
1741
- }
1742
- /**
1743
- * Dispatches a message.
1744
- *
1745
- * @param {(Buffer|String)} data The message to send
1746
- * @param {Boolean} [compress=false] Specifies whether or not to compress
1747
- * `data`
1748
- * @param {Object} options Options object
1749
- * @param {Boolean} [options.fin=false] Specifies whether or not to set the
1750
- * FIN bit
1751
- * @param {Function} [options.generateMask] The function used to generate the
1752
- * masking key
1753
- * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1754
- * `data`
1755
- * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
1756
- * key
1757
- * @param {Number} options.opcode The opcode
1758
- * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
1759
- * modified
1760
- * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
1761
- * RSV1 bit
1762
- * @param {Function} [cb] Callback
1763
- * @private
1764
- */
1765
- dispatch(data, compress, options, cb) {
1766
- if (!compress) {
1767
- this.sendFrame(_Sender.frame(data, options), cb);
1768
- return;
1769
- }
1770
- const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
1771
- this._bufferedBytes += options[kByteLength];
1772
- this._deflating = true;
1773
- perMessageDeflate.compress(data, options.fin, (_, buf) => {
1774
- if (this._socket.destroyed) {
1775
- const err = new Error(
1776
- "The socket was closed while data was being compressed"
1777
- );
1778
- if (typeof cb === "function") cb(err);
1779
- for (let i = 0; i < this._queue.length; i++) {
1780
- const params = this._queue[i];
1781
- const callback = params[params.length - 1];
1782
- if (typeof callback === "function") callback(err);
1783
- }
1784
- return;
1785
- }
1786
- this._bufferedBytes -= options[kByteLength];
1787
- this._deflating = false;
1788
- options.readOnly = false;
1789
- this.sendFrame(_Sender.frame(buf, options), cb);
1790
- this.dequeue();
1791
- });
1792
- }
1793
- /**
1794
- * Executes queued send operations.
1795
- *
1796
- * @private
1797
- */
1798
- dequeue() {
1799
- while (!this._deflating && this._queue.length) {
1800
- const params = this._queue.shift();
1801
- this._bufferedBytes -= params[3][kByteLength];
1802
- Reflect.apply(params[0], this, params.slice(1));
1803
- }
1804
- }
1805
- /**
1806
- * Enqueues a send operation.
1807
- *
1808
- * @param {Array} params Send operation parameters.
1809
- * @private
1810
- */
1811
- enqueue(params) {
1812
- this._bufferedBytes += params[3][kByteLength];
1813
- this._queue.push(params);
1814
- }
1815
- /**
1816
- * Sends a frame.
1817
- *
1818
- * @param {Buffer[]} list The frame to send
1819
- * @param {Function} [cb] Callback
1820
- * @private
1821
- */
1822
- sendFrame(list, cb) {
1823
- if (list.length === 2) {
1824
- this._socket.cork();
1825
- this._socket.write(list[0]);
1826
- this._socket.write(list[1], cb);
1827
- this._socket.uncork();
1828
- } else {
1829
- this._socket.write(list[0], cb);
1830
- }
1831
- }
1832
- };
1833
- module.exports = Sender2;
1834
- }
1835
- });
1836
-
1837
- // packages/cli/node_modules/ws/lib/event-target.js
1838
- var require_event_target = __commonJS({
1839
- "packages/cli/node_modules/ws/lib/event-target.js"(exports, module) {
1840
- "use strict";
1841
- var { kForOnEventAttribute, kListener } = require_constants();
1842
- var kCode = Symbol("kCode");
1843
- var kData = Symbol("kData");
1844
- var kError = Symbol("kError");
1845
- var kMessage = Symbol("kMessage");
1846
- var kReason = Symbol("kReason");
1847
- var kTarget = Symbol("kTarget");
1848
- var kType = Symbol("kType");
1849
- var kWasClean = Symbol("kWasClean");
1850
- var Event = class {
1851
- /**
1852
- * Create a new `Event`.
1853
- *
1854
- * @param {String} type The name of the event
1855
- * @throws {TypeError} If the `type` argument is not specified
1856
- */
1857
- constructor(type) {
1858
- this[kTarget] = null;
1859
- this[kType] = type;
1860
- }
1861
- /**
1862
- * @type {*}
1863
- */
1864
- get target() {
1865
- return this[kTarget];
1866
- }
1867
- /**
1868
- * @type {String}
1869
- */
1870
- get type() {
1871
- return this[kType];
1872
- }
1873
- };
1874
- Object.defineProperty(Event.prototype, "target", { enumerable: true });
1875
- Object.defineProperty(Event.prototype, "type", { enumerable: true });
1876
- var CloseEvent = class extends Event {
1877
- /**
1878
- * Create a new `CloseEvent`.
1879
- *
1880
- * @param {String} type The name of the event
1881
- * @param {Object} [options] A dictionary object that allows for setting
1882
- * attributes via object members of the same name
1883
- * @param {Number} [options.code=0] The status code explaining why the
1884
- * connection was closed
1885
- * @param {String} [options.reason=''] A human-readable string explaining why
1886
- * the connection was closed
1887
- * @param {Boolean} [options.wasClean=false] Indicates whether or not the
1888
- * connection was cleanly closed
1889
- */
1890
- constructor(type, options = {}) {
1891
- super(type);
1892
- this[kCode] = options.code === void 0 ? 0 : options.code;
1893
- this[kReason] = options.reason === void 0 ? "" : options.reason;
1894
- this[kWasClean] = options.wasClean === void 0 ? false : options.wasClean;
1895
- }
1896
- /**
1897
- * @type {Number}
1898
- */
1899
- get code() {
1900
- return this[kCode];
1901
- }
1902
- /**
1903
- * @type {String}
1904
- */
1905
- get reason() {
1906
- return this[kReason];
1907
- }
1908
- /**
1909
- * @type {Boolean}
1910
- */
1911
- get wasClean() {
1912
- return this[kWasClean];
1913
- }
1914
- };
1915
- Object.defineProperty(CloseEvent.prototype, "code", { enumerable: true });
1916
- Object.defineProperty(CloseEvent.prototype, "reason", { enumerable: true });
1917
- Object.defineProperty(CloseEvent.prototype, "wasClean", { enumerable: true });
1918
- var ErrorEvent = class extends Event {
1919
- /**
1920
- * Create a new `ErrorEvent`.
1921
- *
1922
- * @param {String} type The name of the event
1923
- * @param {Object} [options] A dictionary object that allows for setting
1924
- * attributes via object members of the same name
1925
- * @param {*} [options.error=null] The error that generated this event
1926
- * @param {String} [options.message=''] The error message
1927
- */
1928
- constructor(type, options = {}) {
1929
- super(type);
1930
- this[kError] = options.error === void 0 ? null : options.error;
1931
- this[kMessage] = options.message === void 0 ? "" : options.message;
1932
- }
1933
- /**
1934
- * @type {*}
1935
- */
1936
- get error() {
1937
- return this[kError];
1938
- }
1939
- /**
1940
- * @type {String}
1941
- */
1942
- get message() {
1943
- return this[kMessage];
1944
- }
1945
- };
1946
- Object.defineProperty(ErrorEvent.prototype, "error", { enumerable: true });
1947
- Object.defineProperty(ErrorEvent.prototype, "message", { enumerable: true });
1948
- var MessageEvent = class extends Event {
1949
- /**
1950
- * Create a new `MessageEvent`.
1951
- *
1952
- * @param {String} type The name of the event
1953
- * @param {Object} [options] A dictionary object that allows for setting
1954
- * attributes via object members of the same name
1955
- * @param {*} [options.data=null] The message content
1956
- */
1957
- constructor(type, options = {}) {
1958
- super(type);
1959
- this[kData] = options.data === void 0 ? null : options.data;
1960
- }
1961
- /**
1962
- * @type {*}
1963
- */
1964
- get data() {
1965
- return this[kData];
1966
- }
1967
- };
1968
- Object.defineProperty(MessageEvent.prototype, "data", { enumerable: true });
1969
- var EventTarget = {
1970
- /**
1971
- * Register an event listener.
1972
- *
1973
- * @param {String} type A string representing the event type to listen for
1974
- * @param {(Function|Object)} handler The listener to add
1975
- * @param {Object} [options] An options object specifies characteristics about
1976
- * the event listener
1977
- * @param {Boolean} [options.once=false] A `Boolean` indicating that the
1978
- * listener should be invoked at most once after being added. If `true`,
1979
- * the listener would be automatically removed when invoked.
1980
- * @public
1981
- */
1982
- addEventListener(type, handler, options = {}) {
1983
- for (const listener of this.listeners(type)) {
1984
- if (!options[kForOnEventAttribute] && listener[kListener] === handler && !listener[kForOnEventAttribute]) {
1985
- return;
1986
- }
1987
- }
1988
- let wrapper;
1989
- if (type === "message") {
1990
- wrapper = function onMessage(data, isBinary) {
1991
- const event = new MessageEvent("message", {
1992
- data: isBinary ? data : data.toString()
1993
- });
1994
- event[kTarget] = this;
1995
- callListener(handler, this, event);
1996
- };
1997
- } else if (type === "close") {
1998
- wrapper = function onClose(code, message) {
1999
- const event = new CloseEvent("close", {
2000
- code,
2001
- reason: message.toString(),
2002
- wasClean: this._closeFrameReceived && this._closeFrameSent
2003
- });
2004
- event[kTarget] = this;
2005
- callListener(handler, this, event);
2006
- };
2007
- } else if (type === "error") {
2008
- wrapper = function onError(error) {
2009
- const event = new ErrorEvent("error", {
2010
- error,
2011
- message: error.message
2012
- });
2013
- event[kTarget] = this;
2014
- callListener(handler, this, event);
2015
- };
2016
- } else if (type === "open") {
2017
- wrapper = function onOpen() {
2018
- const event = new Event("open");
2019
- event[kTarget] = this;
2020
- callListener(handler, this, event);
2021
- };
2022
- } else {
2023
- return;
2024
- }
2025
- wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute];
2026
- wrapper[kListener] = handler;
2027
- if (options.once) {
2028
- this.once(type, wrapper);
2029
- } else {
2030
- this.on(type, wrapper);
2031
- }
2032
- },
2033
- /**
2034
- * Remove an event listener.
2035
- *
2036
- * @param {String} type A string representing the event type to remove
2037
- * @param {(Function|Object)} handler The listener to remove
2038
- * @public
2039
- */
2040
- removeEventListener(type, handler) {
2041
- for (const listener of this.listeners(type)) {
2042
- if (listener[kListener] === handler && !listener[kForOnEventAttribute]) {
2043
- this.removeListener(type, listener);
2044
- break;
2045
- }
2046
- }
2047
- }
2048
- };
2049
- module.exports = {
2050
- CloseEvent,
2051
- ErrorEvent,
2052
- Event,
2053
- EventTarget,
2054
- MessageEvent
2055
- };
2056
- function callListener(listener, thisArg, event) {
2057
- if (typeof listener === "object" && listener.handleEvent) {
2058
- listener.handleEvent.call(listener, event);
2059
- } else {
2060
- listener.call(thisArg, event);
2061
- }
2062
- }
2063
- }
2064
- });
2065
-
2066
- // packages/cli/node_modules/ws/lib/extension.js
2067
- var require_extension = __commonJS({
2068
- "packages/cli/node_modules/ws/lib/extension.js"(exports, module) {
2069
- "use strict";
2070
- var { tokenChars } = require_validation();
2071
- function push(dest, name, elem) {
2072
- if (dest[name] === void 0) dest[name] = [elem];
2073
- else dest[name].push(elem);
2074
- }
2075
- function parse(header) {
2076
- const offers = /* @__PURE__ */ Object.create(null);
2077
- let params = /* @__PURE__ */ Object.create(null);
2078
- let mustUnescape = false;
2079
- let isEscaping = false;
2080
- let inQuotes = false;
2081
- let extensionName;
2082
- let paramName;
2083
- let start = -1;
2084
- let code = -1;
2085
- let end = -1;
2086
- let i = 0;
2087
- for (; i < header.length; i++) {
2088
- code = header.charCodeAt(i);
2089
- if (extensionName === void 0) {
2090
- if (end === -1 && tokenChars[code] === 1) {
2091
- if (start === -1) start = i;
2092
- } else if (i !== 0 && (code === 32 || code === 9)) {
2093
- if (end === -1 && start !== -1) end = i;
2094
- } else if (code === 59 || code === 44) {
2095
- if (start === -1) {
2096
- throw new SyntaxError(`Unexpected character at index ${i}`);
2097
- }
2098
- if (end === -1) end = i;
2099
- const name = header.slice(start, end);
2100
- if (code === 44) {
2101
- push(offers, name, params);
2102
- params = /* @__PURE__ */ Object.create(null);
2103
- } else {
2104
- extensionName = name;
2105
- }
2106
- start = end = -1;
2107
- } else {
2108
- throw new SyntaxError(`Unexpected character at index ${i}`);
2109
- }
2110
- } else if (paramName === void 0) {
2111
- if (end === -1 && tokenChars[code] === 1) {
2112
- if (start === -1) start = i;
2113
- } else if (code === 32 || code === 9) {
2114
- if (end === -1 && start !== -1) end = i;
2115
- } else if (code === 59 || code === 44) {
2116
- if (start === -1) {
2117
- throw new SyntaxError(`Unexpected character at index ${i}`);
2118
- }
2119
- if (end === -1) end = i;
2120
- push(params, header.slice(start, end), true);
2121
- if (code === 44) {
2122
- push(offers, extensionName, params);
2123
- params = /* @__PURE__ */ Object.create(null);
2124
- extensionName = void 0;
2125
- }
2126
- start = end = -1;
2127
- } else if (code === 61 && start !== -1 && end === -1) {
2128
- paramName = header.slice(start, i);
2129
- start = end = -1;
2130
- } else {
2131
- throw new SyntaxError(`Unexpected character at index ${i}`);
2132
- }
2133
- } else {
2134
- if (isEscaping) {
2135
- if (tokenChars[code] !== 1) {
2136
- throw new SyntaxError(`Unexpected character at index ${i}`);
2137
- }
2138
- if (start === -1) start = i;
2139
- else if (!mustUnescape) mustUnescape = true;
2140
- isEscaping = false;
2141
- } else if (inQuotes) {
2142
- if (tokenChars[code] === 1) {
2143
- if (start === -1) start = i;
2144
- } else if (code === 34 && start !== -1) {
2145
- inQuotes = false;
2146
- end = i;
2147
- } else if (code === 92) {
2148
- isEscaping = true;
2149
- } else {
2150
- throw new SyntaxError(`Unexpected character at index ${i}`);
2151
- }
2152
- } else if (code === 34 && header.charCodeAt(i - 1) === 61) {
2153
- inQuotes = true;
2154
- } else if (end === -1 && tokenChars[code] === 1) {
2155
- if (start === -1) start = i;
2156
- } else if (start !== -1 && (code === 32 || code === 9)) {
2157
- if (end === -1) end = i;
2158
- } else if (code === 59 || code === 44) {
2159
- if (start === -1) {
2160
- throw new SyntaxError(`Unexpected character at index ${i}`);
2161
- }
2162
- if (end === -1) end = i;
2163
- let value = header.slice(start, end);
2164
- if (mustUnescape) {
2165
- value = value.replace(/\\/g, "");
2166
- mustUnescape = false;
2167
- }
2168
- push(params, paramName, value);
2169
- if (code === 44) {
2170
- push(offers, extensionName, params);
2171
- params = /* @__PURE__ */ Object.create(null);
2172
- extensionName = void 0;
2173
- }
2174
- paramName = void 0;
2175
- start = end = -1;
2176
- } else {
2177
- throw new SyntaxError(`Unexpected character at index ${i}`);
2178
- }
2179
- }
2180
- }
2181
- if (start === -1 || inQuotes || code === 32 || code === 9) {
2182
- throw new SyntaxError("Unexpected end of input");
2183
- }
2184
- if (end === -1) end = i;
2185
- const token = header.slice(start, end);
2186
- if (extensionName === void 0) {
2187
- push(offers, token, params);
2188
- } else {
2189
- if (paramName === void 0) {
2190
- push(params, token, true);
2191
- } else if (mustUnescape) {
2192
- push(params, paramName, token.replace(/\\/g, ""));
2193
- } else {
2194
- push(params, paramName, token);
2195
- }
2196
- push(offers, extensionName, params);
2197
- }
2198
- return offers;
2199
- }
2200
- function format(extensions) {
2201
- return Object.keys(extensions).map((extension) => {
2202
- let configurations = extensions[extension];
2203
- if (!Array.isArray(configurations)) configurations = [configurations];
2204
- return configurations.map((params) => {
2205
- return [extension].concat(
2206
- Object.keys(params).map((k) => {
2207
- let values = params[k];
2208
- if (!Array.isArray(values)) values = [values];
2209
- return values.map((v) => v === true ? k : `${k}=${v}`).join("; ");
2210
- })
2211
- ).join("; ");
2212
- }).join(", ");
2213
- }).join(", ");
2214
- }
2215
- module.exports = { format, parse };
2216
- }
2217
- });
2218
-
2219
- // packages/cli/node_modules/ws/lib/websocket.js
2220
- var require_websocket = __commonJS({
2221
- "packages/cli/node_modules/ws/lib/websocket.js"(exports, module) {
2222
- "use strict";
2223
- var EventEmitter2 = __require("events");
2224
- var https2 = __require("https");
2225
- var http2 = __require("http");
2226
- var net = __require("net");
2227
- var tls = __require("tls");
2228
- var { randomBytes, createHash } = __require("crypto");
2229
- var { Duplex, Readable } = __require("stream");
2230
- var { URL: URL2 } = __require("url");
2231
- var PerMessageDeflate = require_permessage_deflate();
2232
- var Receiver2 = require_receiver();
2233
- var Sender2 = require_sender();
2234
- var {
2235
- BINARY_TYPES,
2236
- EMPTY_BUFFER,
2237
- GUID,
2238
- kForOnEventAttribute,
2239
- kListener,
2240
- kStatusCode,
2241
- kWebSocket,
2242
- NOOP
2243
- } = require_constants();
2244
- var {
2245
- EventTarget: { addEventListener, removeEventListener }
2246
- } = require_event_target();
2247
- var { format, parse } = require_extension();
2248
- var { toBuffer } = require_buffer_util();
2249
- var closeTimeout = 30 * 1e3;
2250
- var kAborted = Symbol("kAborted");
2251
- var protocolVersions = [8, 13];
2252
- var readyStates = ["CONNECTING", "OPEN", "CLOSING", "CLOSED"];
2253
- var subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;
2254
- var WebSocket2 = class _WebSocket extends EventEmitter2 {
2255
- /**
2256
- * Create a new `WebSocket`.
2257
- *
2258
- * @param {(String|URL)} address The URL to which to connect
2259
- * @param {(String|String[])} [protocols] The subprotocols
2260
- * @param {Object} [options] Connection options
2261
- */
2262
- constructor(address, protocols, options) {
2263
- super();
2264
- this._binaryType = BINARY_TYPES[0];
2265
- this._closeCode = 1006;
2266
- this._closeFrameReceived = false;
2267
- this._closeFrameSent = false;
2268
- this._closeMessage = EMPTY_BUFFER;
2269
- this._closeTimer = null;
2270
- this._extensions = {};
2271
- this._paused = false;
2272
- this._protocol = "";
2273
- this._readyState = _WebSocket.CONNECTING;
2274
- this._receiver = null;
2275
- this._sender = null;
2276
- this._socket = null;
2277
- if (address !== null) {
2278
- this._bufferedAmount = 0;
2279
- this._isServer = false;
2280
- this._redirects = 0;
2281
- if (protocols === void 0) {
2282
- protocols = [];
2283
- } else if (!Array.isArray(protocols)) {
2284
- if (typeof protocols === "object" && protocols !== null) {
2285
- options = protocols;
2286
- protocols = [];
2287
- } else {
2288
- protocols = [protocols];
2289
- }
2290
- }
2291
- initAsClient(this, address, protocols, options);
2292
- } else {
2293
- this._autoPong = options.autoPong;
2294
- this._isServer = true;
2295
- }
2296
- }
2297
- /**
2298
- * This deviates from the WHATWG interface since ws doesn't support the
2299
- * required default "blob" type (instead we define a custom "nodebuffer"
2300
- * type).
2301
- *
2302
- * @type {String}
2303
- */
2304
- get binaryType() {
2305
- return this._binaryType;
2306
- }
2307
- set binaryType(type) {
2308
- if (!BINARY_TYPES.includes(type)) return;
2309
- this._binaryType = type;
2310
- if (this._receiver) this._receiver._binaryType = type;
2311
- }
2312
- /**
2313
- * @type {Number}
2314
- */
2315
- get bufferedAmount() {
2316
- if (!this._socket) return this._bufferedAmount;
2317
- return this._socket._writableState.length + this._sender._bufferedBytes;
2318
- }
2319
- /**
2320
- * @type {String}
2321
- */
2322
- get extensions() {
2323
- return Object.keys(this._extensions).join();
2324
- }
2325
- /**
2326
- * @type {Boolean}
2327
- */
2328
- get isPaused() {
2329
- return this._paused;
2330
- }
2331
- /**
2332
- * @type {Function}
2333
- */
2334
- /* istanbul ignore next */
2335
- get onclose() {
2336
- return null;
2337
- }
2338
- /**
2339
- * @type {Function}
2340
- */
2341
- /* istanbul ignore next */
2342
- get onerror() {
2343
- return null;
2344
- }
2345
- /**
2346
- * @type {Function}
2347
- */
2348
- /* istanbul ignore next */
2349
- get onopen() {
2350
- return null;
2351
- }
2352
- /**
2353
- * @type {Function}
2354
- */
2355
- /* istanbul ignore next */
2356
- get onmessage() {
2357
- return null;
2358
- }
2359
- /**
2360
- * @type {String}
2361
- */
2362
- get protocol() {
2363
- return this._protocol;
2364
- }
2365
- /**
2366
- * @type {Number}
2367
- */
2368
- get readyState() {
2369
- return this._readyState;
2370
- }
2371
- /**
2372
- * @type {String}
2373
- */
2374
- get url() {
2375
- return this._url;
2376
- }
2377
- /**
2378
- * Set up the socket and the internal resources.
2379
- *
2380
- * @param {Duplex} socket The network socket between the server and client
2381
- * @param {Buffer} head The first packet of the upgraded stream
2382
- * @param {Object} options Options object
2383
- * @param {Boolean} [options.allowSynchronousEvents=false] Specifies whether
2384
- * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
2385
- * multiple times in the same tick
2386
- * @param {Function} [options.generateMask] The function used to generate the
2387
- * masking key
2388
- * @param {Number} [options.maxPayload=0] The maximum allowed message size
2389
- * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
2390
- * not to skip UTF-8 validation for text and close messages
2391
- * @private
2392
- */
2393
- setSocket(socket, head, options) {
2394
- const receiver = new Receiver2({
2395
- allowSynchronousEvents: options.allowSynchronousEvents,
2396
- binaryType: this.binaryType,
2397
- extensions: this._extensions,
2398
- isServer: this._isServer,
2399
- maxPayload: options.maxPayload,
2400
- skipUTF8Validation: options.skipUTF8Validation
2401
- });
2402
- this._sender = new Sender2(socket, this._extensions, options.generateMask);
2403
- this._receiver = receiver;
2404
- this._socket = socket;
2405
- receiver[kWebSocket] = this;
2406
- socket[kWebSocket] = this;
2407
- receiver.on("conclude", receiverOnConclude);
2408
- receiver.on("drain", receiverOnDrain);
2409
- receiver.on("error", receiverOnError);
2410
- receiver.on("message", receiverOnMessage);
2411
- receiver.on("ping", receiverOnPing);
2412
- receiver.on("pong", receiverOnPong);
2413
- if (socket.setTimeout) socket.setTimeout(0);
2414
- if (socket.setNoDelay) socket.setNoDelay();
2415
- if (head.length > 0) socket.unshift(head);
2416
- socket.on("close", socketOnClose);
2417
- socket.on("data", socketOnData);
2418
- socket.on("end", socketOnEnd);
2419
- socket.on("error", socketOnError);
2420
- this._readyState = _WebSocket.OPEN;
2421
- this.emit("open");
2422
- }
2423
- /**
2424
- * Emit the `'close'` event.
2425
- *
2426
- * @private
2427
- */
2428
- emitClose() {
2429
- if (!this._socket) {
2430
- this._readyState = _WebSocket.CLOSED;
2431
- this.emit("close", this._closeCode, this._closeMessage);
2432
- return;
2433
- }
2434
- if (this._extensions[PerMessageDeflate.extensionName]) {
2435
- this._extensions[PerMessageDeflate.extensionName].cleanup();
2436
- }
2437
- this._receiver.removeAllListeners();
2438
- this._readyState = _WebSocket.CLOSED;
2439
- this.emit("close", this._closeCode, this._closeMessage);
2440
- }
2441
- /**
2442
- * Start a closing handshake.
2443
- *
2444
- * +----------+ +-----------+ +----------+
2445
- * - - -|ws.close()|-->|close frame|-->|ws.close()|- - -
2446
- * | +----------+ +-----------+ +----------+ |
2447
- * +----------+ +-----------+ |
2448
- * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING
2449
- * +----------+ +-----------+ |
2450
- * | | | +---+ |
2451
- * +------------------------+-->|fin| - - - -
2452
- * | +---+ | +---+
2453
- * - - - - -|fin|<---------------------+
2454
- * +---+
2455
- *
2456
- * @param {Number} [code] Status code explaining why the connection is closing
2457
- * @param {(String|Buffer)} [data] The reason why the connection is
2458
- * closing
2459
- * @public
2460
- */
2461
- close(code, data) {
2462
- if (this.readyState === _WebSocket.CLOSED) return;
2463
- if (this.readyState === _WebSocket.CONNECTING) {
2464
- const msg = "WebSocket was closed before the connection was established";
2465
- abortHandshake(this, this._req, msg);
2466
- return;
2467
- }
2468
- if (this.readyState === _WebSocket.CLOSING) {
2469
- if (this._closeFrameSent && (this._closeFrameReceived || this._receiver._writableState.errorEmitted)) {
2470
- this._socket.end();
2471
- }
2472
- return;
2473
- }
2474
- this._readyState = _WebSocket.CLOSING;
2475
- this._sender.close(code, data, !this._isServer, (err) => {
2476
- if (err) return;
2477
- this._closeFrameSent = true;
2478
- if (this._closeFrameReceived || this._receiver._writableState.errorEmitted) {
2479
- this._socket.end();
2480
- }
2481
- });
2482
- this._closeTimer = setTimeout(
2483
- this._socket.destroy.bind(this._socket),
2484
- closeTimeout
2485
- );
2486
- }
2487
- /**
2488
- * Pause the socket.
2489
- *
2490
- * @public
2491
- */
2492
- pause() {
2493
- if (this.readyState === _WebSocket.CONNECTING || this.readyState === _WebSocket.CLOSED) {
2494
- return;
2495
- }
2496
- this._paused = true;
2497
- this._socket.pause();
2498
- }
2499
- /**
2500
- * Send a ping.
2501
- *
2502
- * @param {*} [data] The data to send
2503
- * @param {Boolean} [mask] Indicates whether or not to mask `data`
2504
- * @param {Function} [cb] Callback which is executed when the ping is sent
2505
- * @public
2506
- */
2507
- ping(data, mask, cb) {
2508
- if (this.readyState === _WebSocket.CONNECTING) {
2509
- throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
2510
- }
2511
- if (typeof data === "function") {
2512
- cb = data;
2513
- data = mask = void 0;
2514
- } else if (typeof mask === "function") {
2515
- cb = mask;
2516
- mask = void 0;
2517
- }
2518
- if (typeof data === "number") data = data.toString();
2519
- if (this.readyState !== _WebSocket.OPEN) {
2520
- sendAfterClose(this, data, cb);
2521
- return;
2522
- }
2523
- if (mask === void 0) mask = !this._isServer;
2524
- this._sender.ping(data || EMPTY_BUFFER, mask, cb);
2525
- }
2526
- /**
2527
- * Send a pong.
2528
- *
2529
- * @param {*} [data] The data to send
2530
- * @param {Boolean} [mask] Indicates whether or not to mask `data`
2531
- * @param {Function} [cb] Callback which is executed when the pong is sent
2532
- * @public
2533
- */
2534
- pong(data, mask, cb) {
2535
- if (this.readyState === _WebSocket.CONNECTING) {
2536
- throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
2537
- }
2538
- if (typeof data === "function") {
2539
- cb = data;
2540
- data = mask = void 0;
2541
- } else if (typeof mask === "function") {
2542
- cb = mask;
2543
- mask = void 0;
2544
- }
2545
- if (typeof data === "number") data = data.toString();
2546
- if (this.readyState !== _WebSocket.OPEN) {
2547
- sendAfterClose(this, data, cb);
2548
- return;
2549
- }
2550
- if (mask === void 0) mask = !this._isServer;
2551
- this._sender.pong(data || EMPTY_BUFFER, mask, cb);
2552
- }
2553
- /**
2554
- * Resume the socket.
2555
- *
2556
- * @public
2557
- */
2558
- resume() {
2559
- if (this.readyState === _WebSocket.CONNECTING || this.readyState === _WebSocket.CLOSED) {
2560
- return;
2561
- }
2562
- this._paused = false;
2563
- if (!this._receiver._writableState.needDrain) this._socket.resume();
2564
- }
2565
- /**
2566
- * Send a data message.
2567
- *
2568
- * @param {*} data The message to send
2569
- * @param {Object} [options] Options object
2570
- * @param {Boolean} [options.binary] Specifies whether `data` is binary or
2571
- * text
2572
- * @param {Boolean} [options.compress] Specifies whether or not to compress
2573
- * `data`
2574
- * @param {Boolean} [options.fin=true] Specifies whether the fragment is the
2575
- * last one
2576
- * @param {Boolean} [options.mask] Specifies whether or not to mask `data`
2577
- * @param {Function} [cb] Callback which is executed when data is written out
2578
- * @public
2579
- */
2580
- send(data, options, cb) {
2581
- if (this.readyState === _WebSocket.CONNECTING) {
2582
- throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
2583
- }
2584
- if (typeof options === "function") {
2585
- cb = options;
2586
- options = {};
2587
- }
2588
- if (typeof data === "number") data = data.toString();
2589
- if (this.readyState !== _WebSocket.OPEN) {
2590
- sendAfterClose(this, data, cb);
2591
- return;
2592
- }
2593
- const opts = {
2594
- binary: typeof data !== "string",
2595
- mask: !this._isServer,
2596
- compress: true,
2597
- fin: true,
2598
- ...options
2599
- };
2600
- if (!this._extensions[PerMessageDeflate.extensionName]) {
2601
- opts.compress = false;
2602
- }
2603
- this._sender.send(data || EMPTY_BUFFER, opts, cb);
2604
- }
2605
- /**
2606
- * Forcibly close the connection.
2607
- *
2608
- * @public
2609
- */
2610
- terminate() {
2611
- if (this.readyState === _WebSocket.CLOSED) return;
2612
- if (this.readyState === _WebSocket.CONNECTING) {
2613
- const msg = "WebSocket was closed before the connection was established";
2614
- abortHandshake(this, this._req, msg);
2615
- return;
2616
- }
2617
- if (this._socket) {
2618
- this._readyState = _WebSocket.CLOSING;
2619
- this._socket.destroy();
2620
- }
2621
- }
2622
- };
2623
- Object.defineProperty(WebSocket2, "CONNECTING", {
2624
- enumerable: true,
2625
- value: readyStates.indexOf("CONNECTING")
2626
- });
2627
- Object.defineProperty(WebSocket2.prototype, "CONNECTING", {
2628
- enumerable: true,
2629
- value: readyStates.indexOf("CONNECTING")
2630
- });
2631
- Object.defineProperty(WebSocket2, "OPEN", {
2632
- enumerable: true,
2633
- value: readyStates.indexOf("OPEN")
2634
- });
2635
- Object.defineProperty(WebSocket2.prototype, "OPEN", {
2636
- enumerable: true,
2637
- value: readyStates.indexOf("OPEN")
2638
- });
2639
- Object.defineProperty(WebSocket2, "CLOSING", {
2640
- enumerable: true,
2641
- value: readyStates.indexOf("CLOSING")
2642
- });
2643
- Object.defineProperty(WebSocket2.prototype, "CLOSING", {
2644
- enumerable: true,
2645
- value: readyStates.indexOf("CLOSING")
2646
- });
2647
- Object.defineProperty(WebSocket2, "CLOSED", {
2648
- enumerable: true,
2649
- value: readyStates.indexOf("CLOSED")
2650
- });
2651
- Object.defineProperty(WebSocket2.prototype, "CLOSED", {
2652
- enumerable: true,
2653
- value: readyStates.indexOf("CLOSED")
2654
- });
2655
- [
2656
- "binaryType",
2657
- "bufferedAmount",
2658
- "extensions",
2659
- "isPaused",
2660
- "protocol",
2661
- "readyState",
2662
- "url"
2663
- ].forEach((property) => {
2664
- Object.defineProperty(WebSocket2.prototype, property, { enumerable: true });
2665
- });
2666
- ["open", "error", "close", "message"].forEach((method) => {
2667
- Object.defineProperty(WebSocket2.prototype, `on${method}`, {
2668
- enumerable: true,
2669
- get() {
2670
- for (const listener of this.listeners(method)) {
2671
- if (listener[kForOnEventAttribute]) return listener[kListener];
2672
- }
2673
- return null;
2674
- },
2675
- set(handler) {
2676
- for (const listener of this.listeners(method)) {
2677
- if (listener[kForOnEventAttribute]) {
2678
- this.removeListener(method, listener);
2679
- break;
2680
- }
2681
- }
2682
- if (typeof handler !== "function") return;
2683
- this.addEventListener(method, handler, {
2684
- [kForOnEventAttribute]: true
2685
- });
2686
- }
2687
- });
2688
- });
2689
- WebSocket2.prototype.addEventListener = addEventListener;
2690
- WebSocket2.prototype.removeEventListener = removeEventListener;
2691
- module.exports = WebSocket2;
2692
- function initAsClient(websocket, address, protocols, options) {
2693
- const opts = {
2694
- allowSynchronousEvents: false,
2695
- autoPong: true,
2696
- protocolVersion: protocolVersions[1],
2697
- maxPayload: 100 * 1024 * 1024,
2698
- skipUTF8Validation: false,
2699
- perMessageDeflate: true,
2700
- followRedirects: false,
2701
- maxRedirects: 10,
2702
- ...options,
2703
- createConnection: void 0,
2704
- socketPath: void 0,
2705
- hostname: void 0,
2706
- protocol: void 0,
2707
- timeout: void 0,
2708
- method: "GET",
2709
- host: void 0,
2710
- path: void 0,
2711
- port: void 0
2712
- };
2713
- websocket._autoPong = opts.autoPong;
2714
- if (!protocolVersions.includes(opts.protocolVersion)) {
2715
- throw new RangeError(
2716
- `Unsupported protocol version: ${opts.protocolVersion} (supported versions: ${protocolVersions.join(", ")})`
2717
- );
2718
- }
2719
- let parsedUrl;
2720
- if (address instanceof URL2) {
2721
- parsedUrl = address;
2722
- } else {
2723
- try {
2724
- parsedUrl = new URL2(address);
2725
- } catch (e) {
2726
- throw new SyntaxError(`Invalid URL: ${address}`);
2727
- }
2728
- }
2729
- if (parsedUrl.protocol === "http:") {
2730
- parsedUrl.protocol = "ws:";
2731
- } else if (parsedUrl.protocol === "https:") {
2732
- parsedUrl.protocol = "wss:";
2733
- }
2734
- websocket._url = parsedUrl.href;
2735
- const isSecure = parsedUrl.protocol === "wss:";
2736
- const isIpcUrl = parsedUrl.protocol === "ws+unix:";
2737
- let invalidUrlMessage;
2738
- if (parsedUrl.protocol !== "ws:" && !isSecure && !isIpcUrl) {
2739
- invalidUrlMessage = `The URL's protocol must be one of "ws:", "wss:", "http:", "https", or "ws+unix:"`;
2740
- } else if (isIpcUrl && !parsedUrl.pathname) {
2741
- invalidUrlMessage = "The URL's pathname is empty";
2742
- } else if (parsedUrl.hash) {
2743
- invalidUrlMessage = "The URL contains a fragment identifier";
2744
- }
2745
- if (invalidUrlMessage) {
2746
- const err = new SyntaxError(invalidUrlMessage);
2747
- if (websocket._redirects === 0) {
2748
- throw err;
2749
- } else {
2750
- emitErrorAndClose(websocket, err);
2751
- return;
2752
- }
2753
- }
2754
- const defaultPort = isSecure ? 443 : 80;
2755
- const key = randomBytes(16).toString("base64");
2756
- const request = isSecure ? https2.request : http2.request;
2757
- const protocolSet = /* @__PURE__ */ new Set();
2758
- let perMessageDeflate;
2759
- opts.createConnection = isSecure ? tlsConnect : netConnect;
2760
- opts.defaultPort = opts.defaultPort || defaultPort;
2761
- opts.port = parsedUrl.port || defaultPort;
2762
- opts.host = parsedUrl.hostname.startsWith("[") ? parsedUrl.hostname.slice(1, -1) : parsedUrl.hostname;
2763
- opts.headers = {
2764
- ...opts.headers,
2765
- "Sec-WebSocket-Version": opts.protocolVersion,
2766
- "Sec-WebSocket-Key": key,
2767
- Connection: "Upgrade",
2768
- Upgrade: "websocket"
2769
- };
2770
- opts.path = parsedUrl.pathname + parsedUrl.search;
2771
- opts.timeout = opts.handshakeTimeout;
2772
- if (opts.perMessageDeflate) {
2773
- perMessageDeflate = new PerMessageDeflate(
2774
- opts.perMessageDeflate !== true ? opts.perMessageDeflate : {},
2775
- false,
2776
- opts.maxPayload
2777
- );
2778
- opts.headers["Sec-WebSocket-Extensions"] = format({
2779
- [PerMessageDeflate.extensionName]: perMessageDeflate.offer()
2780
- });
2781
- }
2782
- if (protocols.length) {
2783
- for (const protocol of protocols) {
2784
- if (typeof protocol !== "string" || !subprotocolRegex.test(protocol) || protocolSet.has(protocol)) {
2785
- throw new SyntaxError(
2786
- "An invalid or duplicated subprotocol was specified"
2787
- );
2788
- }
2789
- protocolSet.add(protocol);
2790
- }
2791
- opts.headers["Sec-WebSocket-Protocol"] = protocols.join(",");
2792
- }
2793
- if (opts.origin) {
2794
- if (opts.protocolVersion < 13) {
2795
- opts.headers["Sec-WebSocket-Origin"] = opts.origin;
2796
- } else {
2797
- opts.headers.Origin = opts.origin;
2798
- }
2799
- }
2800
- if (parsedUrl.username || parsedUrl.password) {
2801
- opts.auth = `${parsedUrl.username}:${parsedUrl.password}`;
2802
- }
2803
- if (isIpcUrl) {
2804
- const parts = opts.path.split(":");
2805
- opts.socketPath = parts[0];
2806
- opts.path = parts[1];
2807
- }
2808
- let req;
2809
- if (opts.followRedirects) {
2810
- if (websocket._redirects === 0) {
2811
- websocket._originalIpc = isIpcUrl;
2812
- websocket._originalSecure = isSecure;
2813
- websocket._originalHostOrSocketPath = isIpcUrl ? opts.socketPath : parsedUrl.host;
2814
- const headers = options && options.headers;
2815
- options = { ...options, headers: {} };
2816
- if (headers) {
2817
- for (const [key2, value] of Object.entries(headers)) {
2818
- options.headers[key2.toLowerCase()] = value;
2819
- }
2820
- }
2821
- } else if (websocket.listenerCount("redirect") === 0) {
2822
- const isSameHost = isIpcUrl ? websocket._originalIpc ? opts.socketPath === websocket._originalHostOrSocketPath : false : websocket._originalIpc ? false : parsedUrl.host === websocket._originalHostOrSocketPath;
2823
- if (!isSameHost || websocket._originalSecure && !isSecure) {
2824
- delete opts.headers.authorization;
2825
- delete opts.headers.cookie;
2826
- if (!isSameHost) delete opts.headers.host;
2827
- opts.auth = void 0;
2828
- }
2829
- }
2830
- if (opts.auth && !options.headers.authorization) {
2831
- options.headers.authorization = "Basic " + Buffer.from(opts.auth).toString("base64");
2832
- }
2833
- req = websocket._req = request(opts);
2834
- if (websocket._redirects) {
2835
- websocket.emit("redirect", websocket.url, req);
2836
- }
2837
- } else {
2838
- req = websocket._req = request(opts);
2839
- }
2840
- if (opts.timeout) {
2841
- req.on("timeout", () => {
2842
- abortHandshake(websocket, req, "Opening handshake has timed out");
2843
- });
2844
- }
2845
- req.on("error", (err) => {
2846
- if (req === null || req[kAborted]) return;
2847
- req = websocket._req = null;
2848
- emitErrorAndClose(websocket, err);
2849
- });
2850
- req.on("response", (res) => {
2851
- const location = res.headers.location;
2852
- const statusCode = res.statusCode;
2853
- if (location && opts.followRedirects && statusCode >= 300 && statusCode < 400) {
2854
- if (++websocket._redirects > opts.maxRedirects) {
2855
- abortHandshake(websocket, req, "Maximum redirects exceeded");
2856
- return;
2857
- }
2858
- req.abort();
2859
- let addr;
2860
- try {
2861
- addr = new URL2(location, address);
2862
- } catch (e) {
2863
- const err = new SyntaxError(`Invalid URL: ${location}`);
2864
- emitErrorAndClose(websocket, err);
2865
- return;
2866
- }
2867
- initAsClient(websocket, addr, protocols, options);
2868
- } else if (!websocket.emit("unexpected-response", req, res)) {
2869
- abortHandshake(
2870
- websocket,
2871
- req,
2872
- `Unexpected server response: ${res.statusCode}`
2873
- );
2874
- }
2875
- });
2876
- req.on("upgrade", (res, socket, head) => {
2877
- websocket.emit("upgrade", res);
2878
- if (websocket.readyState !== WebSocket2.CONNECTING) return;
2879
- req = websocket._req = null;
2880
- if (res.headers.upgrade.toLowerCase() !== "websocket") {
2881
- abortHandshake(websocket, socket, "Invalid Upgrade header");
2882
- return;
2883
- }
2884
- const digest = createHash("sha1").update(key + GUID).digest("base64");
2885
- if (res.headers["sec-websocket-accept"] !== digest) {
2886
- abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
2887
- return;
2888
- }
2889
- const serverProt = res.headers["sec-websocket-protocol"];
2890
- let protError;
2891
- if (serverProt !== void 0) {
2892
- if (!protocolSet.size) {
2893
- protError = "Server sent a subprotocol but none was requested";
2894
- } else if (!protocolSet.has(serverProt)) {
2895
- protError = "Server sent an invalid subprotocol";
2896
- }
2897
- } else if (protocolSet.size) {
2898
- protError = "Server sent no subprotocol";
2899
- }
2900
- if (protError) {
2901
- abortHandshake(websocket, socket, protError);
2902
- return;
2903
- }
2904
- if (serverProt) websocket._protocol = serverProt;
2905
- const secWebSocketExtensions = res.headers["sec-websocket-extensions"];
2906
- if (secWebSocketExtensions !== void 0) {
2907
- if (!perMessageDeflate) {
2908
- const message = "Server sent a Sec-WebSocket-Extensions header but no extension was requested";
2909
- abortHandshake(websocket, socket, message);
2910
- return;
2911
- }
2912
- let extensions;
2913
- try {
2914
- extensions = parse(secWebSocketExtensions);
2915
- } catch (err) {
2916
- const message = "Invalid Sec-WebSocket-Extensions header";
2917
- abortHandshake(websocket, socket, message);
2918
- return;
2919
- }
2920
- const extensionNames = Object.keys(extensions);
2921
- if (extensionNames.length !== 1 || extensionNames[0] !== PerMessageDeflate.extensionName) {
2922
- const message = "Server indicated an extension that was not requested";
2923
- abortHandshake(websocket, socket, message);
2924
- return;
2925
- }
2926
- try {
2927
- perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName]);
2928
- } catch (err) {
2929
- const message = "Invalid Sec-WebSocket-Extensions header";
2930
- abortHandshake(websocket, socket, message);
2931
- return;
2932
- }
2933
- websocket._extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
2934
- }
2935
- websocket.setSocket(socket, head, {
2936
- allowSynchronousEvents: opts.allowSynchronousEvents,
2937
- generateMask: opts.generateMask,
2938
- maxPayload: opts.maxPayload,
2939
- skipUTF8Validation: opts.skipUTF8Validation
2940
- });
2941
- });
2942
- if (opts.finishRequest) {
2943
- opts.finishRequest(req, websocket);
2944
- } else {
2945
- req.end();
2946
- }
2947
- }
2948
- function emitErrorAndClose(websocket, err) {
2949
- websocket._readyState = WebSocket2.CLOSING;
2950
- websocket.emit("error", err);
2951
- websocket.emitClose();
2952
- }
2953
- function netConnect(options) {
2954
- options.path = options.socketPath;
2955
- return net.connect(options);
2956
- }
2957
- function tlsConnect(options) {
2958
- options.path = void 0;
2959
- if (!options.servername && options.servername !== "") {
2960
- options.servername = net.isIP(options.host) ? "" : options.host;
2961
- }
2962
- return tls.connect(options);
2963
- }
2964
- function abortHandshake(websocket, stream, message) {
2965
- websocket._readyState = WebSocket2.CLOSING;
2966
- const err = new Error(message);
2967
- Error.captureStackTrace(err, abortHandshake);
2968
- if (stream.setHeader) {
2969
- stream[kAborted] = true;
2970
- stream.abort();
2971
- if (stream.socket && !stream.socket.destroyed) {
2972
- stream.socket.destroy();
2973
- }
2974
- process.nextTick(emitErrorAndClose, websocket, err);
2975
- } else {
2976
- stream.destroy(err);
2977
- stream.once("error", websocket.emit.bind(websocket, "error"));
2978
- stream.once("close", websocket.emitClose.bind(websocket));
2979
- }
2980
- }
2981
- function sendAfterClose(websocket, data, cb) {
2982
- if (data) {
2983
- const length = toBuffer(data).length;
2984
- if (websocket._socket) websocket._sender._bufferedBytes += length;
2985
- else websocket._bufferedAmount += length;
2986
- }
2987
- if (cb) {
2988
- const err = new Error(
2989
- `WebSocket is not open: readyState ${websocket.readyState} (${readyStates[websocket.readyState]})`
2990
- );
2991
- process.nextTick(cb, err);
2992
- }
2993
- }
2994
- function receiverOnConclude(code, reason) {
2995
- const websocket = this[kWebSocket];
2996
- websocket._closeFrameReceived = true;
2997
- websocket._closeMessage = reason;
2998
- websocket._closeCode = code;
2999
- if (websocket._socket[kWebSocket] === void 0) return;
3000
- websocket._socket.removeListener("data", socketOnData);
3001
- process.nextTick(resume, websocket._socket);
3002
- if (code === 1005) websocket.close();
3003
- else websocket.close(code, reason);
3004
- }
3005
- function receiverOnDrain() {
3006
- const websocket = this[kWebSocket];
3007
- if (!websocket.isPaused) websocket._socket.resume();
3008
- }
3009
- function receiverOnError(err) {
3010
- const websocket = this[kWebSocket];
3011
- if (websocket._socket[kWebSocket] !== void 0) {
3012
- websocket._socket.removeListener("data", socketOnData);
3013
- process.nextTick(resume, websocket._socket);
3014
- websocket.close(err[kStatusCode]);
3015
- }
3016
- websocket.emit("error", err);
3017
- }
3018
- function receiverOnFinish() {
3019
- this[kWebSocket].emitClose();
3020
- }
3021
- function receiverOnMessage(data, isBinary) {
3022
- this[kWebSocket].emit("message", data, isBinary);
3023
- }
3024
- function receiverOnPing(data) {
3025
- const websocket = this[kWebSocket];
3026
- if (websocket._autoPong) websocket.pong(data, !this._isServer, NOOP);
3027
- websocket.emit("ping", data);
3028
- }
3029
- function receiverOnPong(data) {
3030
- this[kWebSocket].emit("pong", data);
3031
- }
3032
- function resume(stream) {
3033
- stream.resume();
3034
- }
3035
- function socketOnClose() {
3036
- const websocket = this[kWebSocket];
3037
- this.removeListener("close", socketOnClose);
3038
- this.removeListener("data", socketOnData);
3039
- this.removeListener("end", socketOnEnd);
3040
- websocket._readyState = WebSocket2.CLOSING;
3041
- let chunk;
3042
- if (!this._readableState.endEmitted && !websocket._closeFrameReceived && !websocket._receiver._writableState.errorEmitted && (chunk = websocket._socket.read()) !== null) {
3043
- websocket._receiver.write(chunk);
3044
- }
3045
- websocket._receiver.end();
3046
- this[kWebSocket] = void 0;
3047
- clearTimeout(websocket._closeTimer);
3048
- if (websocket._receiver._writableState.finished || websocket._receiver._writableState.errorEmitted) {
3049
- websocket.emitClose();
3050
- } else {
3051
- websocket._receiver.on("error", receiverOnFinish);
3052
- websocket._receiver.on("finish", receiverOnFinish);
3053
- }
3054
- }
3055
- function socketOnData(chunk) {
3056
- if (!this[kWebSocket]._receiver.write(chunk)) {
3057
- this.pause();
3058
- }
3059
- }
3060
- function socketOnEnd() {
3061
- const websocket = this[kWebSocket];
3062
- websocket._readyState = WebSocket2.CLOSING;
3063
- websocket._receiver.end();
3064
- this.end();
3065
- }
3066
- function socketOnError() {
3067
- const websocket = this[kWebSocket];
3068
- this.removeListener("error", socketOnError);
3069
- this.on("error", NOOP);
3070
- if (websocket) {
3071
- websocket._readyState = WebSocket2.CLOSING;
3072
- this.destroy();
3073
- }
3074
- }
3075
- }
3076
- });
3077
-
3078
- // packages/cli/node_modules/ws/lib/subprotocol.js
3079
- var require_subprotocol = __commonJS({
3080
- "packages/cli/node_modules/ws/lib/subprotocol.js"(exports, module) {
3081
- "use strict";
3082
- var { tokenChars } = require_validation();
3083
- function parse(header) {
3084
- const protocols = /* @__PURE__ */ new Set();
3085
- let start = -1;
3086
- let end = -1;
3087
- let i = 0;
3088
- for (i; i < header.length; i++) {
3089
- const code = header.charCodeAt(i);
3090
- if (end === -1 && tokenChars[code] === 1) {
3091
- if (start === -1) start = i;
3092
- } else if (i !== 0 && (code === 32 || code === 9)) {
3093
- if (end === -1 && start !== -1) end = i;
3094
- } else if (code === 44) {
3095
- if (start === -1) {
3096
- throw new SyntaxError(`Unexpected character at index ${i}`);
3097
- }
3098
- if (end === -1) end = i;
3099
- const protocol2 = header.slice(start, end);
3100
- if (protocols.has(protocol2)) {
3101
- throw new SyntaxError(`The "${protocol2}" subprotocol is duplicated`);
3102
- }
3103
- protocols.add(protocol2);
3104
- start = end = -1;
3105
- } else {
3106
- throw new SyntaxError(`Unexpected character at index ${i}`);
3107
- }
3108
- }
3109
- if (start === -1 || end !== -1) {
3110
- throw new SyntaxError("Unexpected end of input");
3111
- }
3112
- const protocol = header.slice(start, i);
3113
- if (protocols.has(protocol)) {
3114
- throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);
3115
- }
3116
- protocols.add(protocol);
3117
- return protocols;
3118
- }
3119
- module.exports = { parse };
3120
- }
3121
- });
3122
-
3123
- // packages/cli/node_modules/ws/lib/websocket-server.js
3124
- var require_websocket_server = __commonJS({
3125
- "packages/cli/node_modules/ws/lib/websocket-server.js"(exports, module) {
3126
- "use strict";
3127
- var EventEmitter2 = __require("events");
3128
- var http2 = __require("http");
3129
- var { Duplex } = __require("stream");
3130
- var { createHash } = __require("crypto");
3131
- var extension = require_extension();
3132
- var PerMessageDeflate = require_permessage_deflate();
3133
- var subprotocol = require_subprotocol();
3134
- var WebSocket2 = require_websocket();
3135
- var { GUID, kWebSocket } = require_constants();
3136
- var keyRegex = /^[+/0-9A-Za-z]{22}==$/;
3137
- var RUNNING = 0;
3138
- var CLOSING = 1;
3139
- var CLOSED = 2;
3140
- var WebSocketServer2 = class extends EventEmitter2 {
3141
- /**
3142
- * Create a `WebSocketServer` instance.
3143
- *
3144
- * @param {Object} options Configuration options
3145
- * @param {Boolean} [options.allowSynchronousEvents=false] Specifies whether
3146
- * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
3147
- * multiple times in the same tick
3148
- * @param {Boolean} [options.autoPong=true] Specifies whether or not to
3149
- * automatically send a pong in response to a ping
3150
- * @param {Number} [options.backlog=511] The maximum length of the queue of
3151
- * pending connections
3152
- * @param {Boolean} [options.clientTracking=true] Specifies whether or not to
3153
- * track clients
3154
- * @param {Function} [options.handleProtocols] A hook to handle protocols
3155
- * @param {String} [options.host] The hostname where to bind the server
3156
- * @param {Number} [options.maxPayload=104857600] The maximum allowed message
3157
- * size
3158
- * @param {Boolean} [options.noServer=false] Enable no server mode
3159
- * @param {String} [options.path] Accept only connections matching this path
3160
- * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable
3161
- * permessage-deflate
3162
- * @param {Number} [options.port] The port where to bind the server
3163
- * @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S
3164
- * server to use
3165
- * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
3166
- * not to skip UTF-8 validation for text and close messages
3167
- * @param {Function} [options.verifyClient] A hook to reject connections
3168
- * @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket`
3169
- * class to use. It must be the `WebSocket` class or class that extends it
3170
- * @param {Function} [callback] A listener for the `listening` event
3171
- */
3172
- constructor(options, callback) {
3173
- super();
3174
- options = {
3175
- allowSynchronousEvents: false,
3176
- autoPong: true,
3177
- maxPayload: 100 * 1024 * 1024,
3178
- skipUTF8Validation: false,
3179
- perMessageDeflate: false,
3180
- handleProtocols: null,
3181
- clientTracking: true,
3182
- verifyClient: null,
3183
- noServer: false,
3184
- backlog: null,
3185
- // use default (511 as implemented in net.js)
3186
- server: null,
3187
- host: null,
3188
- path: null,
3189
- port: null,
3190
- WebSocket: WebSocket2,
3191
- ...options
3192
- };
3193
- if (options.port == null && !options.server && !options.noServer || options.port != null && (options.server || options.noServer) || options.server && options.noServer) {
3194
- throw new TypeError(
3195
- 'One and only one of the "port", "server", or "noServer" options must be specified'
3196
- );
3197
- }
3198
- if (options.port != null) {
3199
- this._server = http2.createServer((req, res) => {
3200
- const body = http2.STATUS_CODES[426];
3201
- res.writeHead(426, {
3202
- "Content-Length": body.length,
3203
- "Content-Type": "text/plain"
3204
- });
3205
- res.end(body);
3206
- });
3207
- this._server.listen(
3208
- options.port,
3209
- options.host,
3210
- options.backlog,
3211
- callback
3212
- );
3213
- } else if (options.server) {
3214
- this._server = options.server;
3215
- }
3216
- if (this._server) {
3217
- const emitConnection = this.emit.bind(this, "connection");
3218
- this._removeListeners = addListeners(this._server, {
3219
- listening: this.emit.bind(this, "listening"),
3220
- error: this.emit.bind(this, "error"),
3221
- upgrade: (req, socket, head) => {
3222
- this.handleUpgrade(req, socket, head, emitConnection);
3223
- }
3224
- });
3225
- }
3226
- if (options.perMessageDeflate === true) options.perMessageDeflate = {};
3227
- if (options.clientTracking) {
3228
- this.clients = /* @__PURE__ */ new Set();
3229
- this._shouldEmitClose = false;
3230
- }
3231
- this.options = options;
3232
- this._state = RUNNING;
3233
- }
3234
- /**
3235
- * Returns the bound address, the address family name, and port of the server
3236
- * as reported by the operating system if listening on an IP socket.
3237
- * If the server is listening on a pipe or UNIX domain socket, the name is
3238
- * returned as a string.
3239
- *
3240
- * @return {(Object|String|null)} The address of the server
3241
- * @public
3242
- */
3243
- address() {
3244
- if (this.options.noServer) {
3245
- throw new Error('The server is operating in "noServer" mode');
3246
- }
3247
- if (!this._server) return null;
3248
- return this._server.address();
3249
- }
3250
- /**
3251
- * Stop the server from accepting new connections and emit the `'close'` event
3252
- * when all existing connections are closed.
3253
- *
3254
- * @param {Function} [cb] A one-time listener for the `'close'` event
3255
- * @public
3256
- */
3257
- close(cb) {
3258
- if (this._state === CLOSED) {
3259
- if (cb) {
3260
- this.once("close", () => {
3261
- cb(new Error("The server is not running"));
3262
- });
3263
- }
3264
- process.nextTick(emitClose, this);
3265
- return;
3266
- }
3267
- if (cb) this.once("close", cb);
3268
- if (this._state === CLOSING) return;
3269
- this._state = CLOSING;
3270
- if (this.options.noServer || this.options.server) {
3271
- if (this._server) {
3272
- this._removeListeners();
3273
- this._removeListeners = this._server = null;
3274
- }
3275
- if (this.clients) {
3276
- if (!this.clients.size) {
3277
- process.nextTick(emitClose, this);
3278
- } else {
3279
- this._shouldEmitClose = true;
3280
- }
3281
- } else {
3282
- process.nextTick(emitClose, this);
3283
- }
3284
- } else {
3285
- const server = this._server;
3286
- this._removeListeners();
3287
- this._removeListeners = this._server = null;
3288
- server.close(() => {
3289
- emitClose(this);
3290
- });
3291
- }
3292
- }
3293
- /**
3294
- * See if a given request should be handled by this server instance.
3295
- *
3296
- * @param {http.IncomingMessage} req Request object to inspect
3297
- * @return {Boolean} `true` if the request is valid, else `false`
3298
- * @public
3299
- */
3300
- shouldHandle(req) {
3301
- if (this.options.path) {
3302
- const index = req.url.indexOf("?");
3303
- const pathname = index !== -1 ? req.url.slice(0, index) : req.url;
3304
- if (pathname !== this.options.path) return false;
3305
- }
3306
- return true;
3307
- }
3308
- /**
3309
- * Handle a HTTP Upgrade request.
3310
- *
3311
- * @param {http.IncomingMessage} req The request object
3312
- * @param {Duplex} socket The network socket between the server and client
3313
- * @param {Buffer} head The first packet of the upgraded stream
3314
- * @param {Function} cb Callback
3315
- * @public
3316
- */
3317
- handleUpgrade(req, socket, head, cb) {
3318
- socket.on("error", socketOnError);
3319
- const key = req.headers["sec-websocket-key"];
3320
- const version = +req.headers["sec-websocket-version"];
3321
- if (req.method !== "GET") {
3322
- const message = "Invalid HTTP method";
3323
- abortHandshakeOrEmitwsClientError(this, req, socket, 405, message);
3324
- return;
3325
- }
3326
- if (req.headers.upgrade.toLowerCase() !== "websocket") {
3327
- const message = "Invalid Upgrade header";
3328
- abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
3329
- return;
3330
- }
3331
- if (!key || !keyRegex.test(key)) {
3332
- const message = "Missing or invalid Sec-WebSocket-Key header";
3333
- abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
3334
- return;
3335
- }
3336
- if (version !== 8 && version !== 13) {
3337
- const message = "Missing or invalid Sec-WebSocket-Version header";
3338
- abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
3339
- return;
3340
- }
3341
- if (!this.shouldHandle(req)) {
3342
- abortHandshake(socket, 400);
3343
- return;
3344
- }
3345
- const secWebSocketProtocol = req.headers["sec-websocket-protocol"];
3346
- let protocols = /* @__PURE__ */ new Set();
3347
- if (secWebSocketProtocol !== void 0) {
3348
- try {
3349
- protocols = subprotocol.parse(secWebSocketProtocol);
3350
- } catch (err) {
3351
- const message = "Invalid Sec-WebSocket-Protocol header";
3352
- abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
3353
- return;
3354
- }
3355
- }
3356
- const secWebSocketExtensions = req.headers["sec-websocket-extensions"];
3357
- const extensions = {};
3358
- if (this.options.perMessageDeflate && secWebSocketExtensions !== void 0) {
3359
- const perMessageDeflate = new PerMessageDeflate(
3360
- this.options.perMessageDeflate,
3361
- true,
3362
- this.options.maxPayload
3363
- );
3364
- try {
3365
- const offers = extension.parse(secWebSocketExtensions);
3366
- if (offers[PerMessageDeflate.extensionName]) {
3367
- perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]);
3368
- extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
3369
- }
3370
- } catch (err) {
3371
- const message = "Invalid or unacceptable Sec-WebSocket-Extensions header";
3372
- abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
3373
- return;
3374
- }
3375
- }
3376
- if (this.options.verifyClient) {
3377
- const info = {
3378
- origin: req.headers[`${version === 8 ? "sec-websocket-origin" : "origin"}`],
3379
- secure: !!(req.socket.authorized || req.socket.encrypted),
3380
- req
3381
- };
3382
- if (this.options.verifyClient.length === 2) {
3383
- this.options.verifyClient(info, (verified, code, message, headers) => {
3384
- if (!verified) {
3385
- return abortHandshake(socket, code || 401, message, headers);
3386
- }
3387
- this.completeUpgrade(
3388
- extensions,
3389
- key,
3390
- protocols,
3391
- req,
3392
- socket,
3393
- head,
3394
- cb
3395
- );
3396
- });
3397
- return;
3398
- }
3399
- if (!this.options.verifyClient(info)) return abortHandshake(socket, 401);
3400
- }
3401
- this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);
3402
- }
3403
- /**
3404
- * Upgrade the connection to WebSocket.
3405
- *
3406
- * @param {Object} extensions The accepted extensions
3407
- * @param {String} key The value of the `Sec-WebSocket-Key` header
3408
- * @param {Set} protocols The subprotocols
3409
- * @param {http.IncomingMessage} req The request object
3410
- * @param {Duplex} socket The network socket between the server and client
3411
- * @param {Buffer} head The first packet of the upgraded stream
3412
- * @param {Function} cb Callback
3413
- * @throws {Error} If called more than once with the same socket
3414
- * @private
3415
- */
3416
- completeUpgrade(extensions, key, protocols, req, socket, head, cb) {
3417
- if (!socket.readable || !socket.writable) return socket.destroy();
3418
- if (socket[kWebSocket]) {
3419
- throw new Error(
3420
- "server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration"
3421
- );
3422
- }
3423
- if (this._state > RUNNING) return abortHandshake(socket, 503);
3424
- const digest = createHash("sha1").update(key + GUID).digest("base64");
3425
- const headers = [
3426
- "HTTP/1.1 101 Switching Protocols",
3427
- "Upgrade: websocket",
3428
- "Connection: Upgrade",
3429
- `Sec-WebSocket-Accept: ${digest}`
3430
- ];
3431
- const ws = new this.options.WebSocket(null, void 0, this.options);
3432
- if (protocols.size) {
3433
- const protocol = this.options.handleProtocols ? this.options.handleProtocols(protocols, req) : protocols.values().next().value;
3434
- if (protocol) {
3435
- headers.push(`Sec-WebSocket-Protocol: ${protocol}`);
3436
- ws._protocol = protocol;
3437
- }
3438
- }
3439
- if (extensions[PerMessageDeflate.extensionName]) {
3440
- const params = extensions[PerMessageDeflate.extensionName].params;
3441
- const value = extension.format({
3442
- [PerMessageDeflate.extensionName]: [params]
3443
- });
3444
- headers.push(`Sec-WebSocket-Extensions: ${value}`);
3445
- ws._extensions = extensions;
3446
- }
3447
- this.emit("headers", headers, req);
3448
- socket.write(headers.concat("\r\n").join("\r\n"));
3449
- socket.removeListener("error", socketOnError);
3450
- ws.setSocket(socket, head, {
3451
- allowSynchronousEvents: this.options.allowSynchronousEvents,
3452
- maxPayload: this.options.maxPayload,
3453
- skipUTF8Validation: this.options.skipUTF8Validation
3454
- });
3455
- if (this.clients) {
3456
- this.clients.add(ws);
3457
- ws.on("close", () => {
3458
- this.clients.delete(ws);
3459
- if (this._shouldEmitClose && !this.clients.size) {
3460
- process.nextTick(emitClose, this);
3461
- }
3462
- });
3463
- }
3464
- cb(ws, req);
3465
- }
3466
- };
3467
- module.exports = WebSocketServer2;
3468
- function addListeners(server, map) {
3469
- for (const event of Object.keys(map)) server.on(event, map[event]);
3470
- return function removeListeners() {
3471
- for (const event of Object.keys(map)) {
3472
- server.removeListener(event, map[event]);
3473
- }
3474
- };
3475
- }
3476
- function emitClose(server) {
3477
- server._state = CLOSED;
3478
- server.emit("close");
3479
- }
3480
- function socketOnError() {
3481
- this.destroy();
3482
- }
3483
- function abortHandshake(socket, code, message, headers) {
3484
- message = message || http2.STATUS_CODES[code];
3485
- headers = {
3486
- Connection: "close",
3487
- "Content-Type": "text/html",
3488
- "Content-Length": Buffer.byteLength(message),
3489
- ...headers
3490
- };
3491
- socket.once("finish", socket.destroy);
3492
- socket.end(
3493
- `HTTP/1.1 ${code} ${http2.STATUS_CODES[code]}\r
3494
- ` + Object.keys(headers).map((h) => `${h}: ${headers[h]}`).join("\r\n") + "\r\n\r\n" + message
3495
- );
3496
- }
3497
- function abortHandshakeOrEmitwsClientError(server, req, socket, code, message) {
3498
- if (server.listenerCount("wsClientError")) {
3499
- const err = new Error(message);
3500
- Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError);
3501
- server.emit("wsClientError", err, socket, req);
3502
- } else {
3503
- abortHandshake(socket, code, message);
3504
- }
3505
- }
3506
- }
3507
- });
3508
-
3509
- // packages/cli/node_modules/ws/wrapper.mjs
3510
- var import_stream = __toESM(require_stream(), 1);
3511
- var import_receiver = __toESM(require_receiver(), 1);
3512
- var import_sender = __toESM(require_sender(), 1);
3513
- var import_websocket = __toESM(require_websocket(), 1);
3514
- var import_websocket_server = __toESM(require_websocket_server(), 1);
3515
- var wrapper_default = import_websocket.default;
3516
-
3517
- // packages/cli/src/utils/activityLogger.ts
3518
- import http from "node:http";
3519
- import https from "node:https";
3520
- import zlib from "node:zlib";
3521
- import fs from "node:fs";
3522
- import path from "node:path";
3523
- import { EventEmitter } from "node:events";
3524
- var ACTIVITY_ID_HEADER = "x-activity-request-id";
3525
- var MAX_BUFFER_SIZE = 100;
3526
- function isHeaderRecord(h) {
3527
- return !Array.isArray(h);
3528
- }
3529
- function isRequestOptions(value) {
3530
- return typeof value === "object" && value !== null && !(value instanceof URL) && !Array.isArray(value);
3531
- }
3532
- function isIncomingMessageCallback(value) {
3533
- return typeof value === "function";
3534
- }
3535
- function callHttpRequest(originalFn, args) {
3536
- if (args.length === 0) {
3537
- return originalFn({});
3538
- }
3539
- if (args.length === 1) {
3540
- const first = args[0];
3541
- if (typeof first === "string" || first instanceof URL) {
3542
- return originalFn(first);
3543
- }
3544
- if (isRequestOptions(first)) {
3545
- return originalFn(first);
3546
- }
3547
- return originalFn({});
3548
- }
3549
- if (args.length === 2) {
3550
- const first = args[0];
3551
- const second = args[1];
3552
- if (typeof first === "string" || first instanceof URL) {
3553
- if (isIncomingMessageCallback(second)) {
3554
- return originalFn(first, second);
3555
- }
3556
- if (isRequestOptions(second)) {
3557
- return originalFn(first, second);
3558
- }
3559
- }
3560
- if (isRequestOptions(first) && isIncomingMessageCallback(second)) {
3561
- return originalFn(first, second);
3562
- }
3563
- }
3564
- if (args.length === 3) {
3565
- const first = args[0];
3566
- const second = args[1];
3567
- const third = args[2];
3568
- if ((typeof first === "string" || first instanceof URL) && isRequestOptions(second) && isIncomingMessageCallback(third)) {
3569
- return originalFn(first, second, third);
3570
- }
3571
- }
3572
- return originalFn({});
3573
- }
3574
- var ActivityLogger = class _ActivityLogger extends EventEmitter {
3575
- static instance;
3576
- isInterceptionEnabled = false;
3577
- requestStartTimes = /* @__PURE__ */ new Map();
3578
- networkLoggingEnabled = false;
3579
- networkBufferMap = /* @__PURE__ */ new Map();
3580
- networkBufferIds = [];
3581
- consoleBuffer = [];
3582
- bufferLimit = 10;
3583
- static getInstance() {
3584
- if (!_ActivityLogger.instance) {
3585
- _ActivityLogger.instance = new _ActivityLogger();
3586
- }
3587
- return _ActivityLogger.instance;
3588
- }
3589
- enableNetworkLogging() {
3590
- this.networkLoggingEnabled = true;
3591
- this.emit("network-logging-enabled");
3592
- }
3593
- disableNetworkLogging() {
3594
- this.networkLoggingEnabled = false;
3595
- }
3596
- isNetworkLoggingEnabled() {
3597
- return this.networkLoggingEnabled;
3598
- }
3599
- /**
3600
- * Atomically returns and clears all buffered logs.
3601
- * Prevents data loss from events emitted between get and clear.
3602
- */
3603
- drainBufferedLogs() {
3604
- const network = [];
3605
- for (const id of this.networkBufferIds) {
3606
- const events = this.networkBufferMap.get(id);
3607
- if (events) network.push(...events);
3608
- }
3609
- const console = [...this.consoleBuffer];
3610
- this.networkBufferMap.clear();
3611
- this.networkBufferIds = [];
3612
- this.consoleBuffer = [];
3613
- return { network, console };
3614
- }
3615
- getBufferedLogs() {
3616
- const network = [];
3617
- for (const id of this.networkBufferIds) {
3618
- const events = this.networkBufferMap.get(id);
3619
- if (events) network.push(...events);
3620
- }
3621
- return {
3622
- network,
3623
- console: [...this.consoleBuffer]
3624
- };
3625
- }
3626
- clearBufferedLogs() {
3627
- this.networkBufferMap.clear();
3628
- this.networkBufferIds = [];
3629
- this.consoleBuffer = [];
3630
- }
3631
- stringifyHeaders(headers) {
3632
- const result = {};
3633
- if (!headers) return result;
3634
- if (headers instanceof Headers) {
3635
- headers.forEach((v, k) => {
3636
- result[k.toLowerCase()] = v;
3637
- });
3638
- } else if (typeof headers === "object" && headers !== null) {
3639
- for (const [key, val] of Object.entries(headers)) {
3640
- result[key.toLowerCase()] = Array.isArray(val) ? val.join(", ") : String(val);
3641
- }
3642
- }
3643
- return result;
3644
- }
3645
- sanitizeNetworkLog(log) {
3646
- if (!log || typeof log !== "object") return log;
3647
- const sanitized = { ...log };
3648
- if ("headers" in sanitized && sanitized.headers) {
3649
- const headers = { ...sanitized.headers };
3650
- for (const key of Object.keys(headers)) {
3651
- if (["authorization", "cookie", "x-goog-api-key"].includes(
3652
- key.toLowerCase()
3653
- )) {
3654
- headers[key] = "[REDACTED]";
3655
- }
3656
- }
3657
- sanitized.headers = headers;
3658
- }
3659
- if ("response" in sanitized && sanitized.response?.headers) {
3660
- const resHeaders = { ...sanitized.response.headers };
3661
- for (const key of Object.keys(resHeaders)) {
3662
- if (["set-cookie"].includes(key.toLowerCase())) {
3663
- resHeaders[key] = "[REDACTED]";
3664
- }
3665
- }
3666
- sanitized.response = { ...sanitized.response, headers: resHeaders };
3667
- }
3668
- return sanitized;
3669
- }
3670
- /** @internal Emit a network event — public for testing only. */
3671
- emitNetworkEvent(payload) {
3672
- this.safeEmitNetwork(payload);
3673
- }
3674
- safeEmitNetwork(payload) {
3675
- const sanitized = this.sanitizeNetworkLog(payload);
3676
- const id = sanitized.id;
3677
- if (!this.networkBufferMap.has(id)) {
3678
- this.networkBufferIds.push(id);
3679
- this.networkBufferMap.set(id, []);
3680
- if (this.networkBufferIds.length > this.bufferLimit) {
3681
- const evictId = this.networkBufferIds.shift();
3682
- this.networkBufferMap.delete(evictId);
3683
- }
3684
- }
3685
- this.networkBufferMap.get(id).push(sanitized);
3686
- this.emit("network", sanitized);
3687
- }
3688
- enable() {
3689
- if (this.isInterceptionEnabled) return;
3690
- this.isInterceptionEnabled = true;
3691
- this.patchGlobalFetch();
3692
- this.patchNodeHttp();
3693
- }
3694
- patchGlobalFetch() {
3695
- if (!global.fetch) return;
3696
- const originalFetch = global.fetch;
3697
- global.fetch = async (input, init) => {
3698
- const url = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
3699
- if (url.includes("127.0.0.1") || url.includes("localhost"))
3700
- return originalFetch(input, init);
3701
- const id = Math.random().toString(36).substring(7);
3702
- const inputMethod = typeof input === "object" && "method" in input ? input.method : void 0;
3703
- const inputHeaders = typeof input === "object" && "headers" in input ? input.headers : void 0;
3704
- const method = (init?.method ?? inputMethod ?? "GET").toUpperCase();
3705
- const headers = new Headers(init?.headers ?? inputHeaders ?? {});
3706
- headers.set(ACTIVITY_ID_HEADER, id);
3707
- const newInit = {
3708
- ...init,
3709
- method,
3710
- headers
3711
- };
3712
- let reqBody = "";
3713
- const body = newInit.body;
3714
- if (body) {
3715
- if (typeof body === "string") reqBody = body;
3716
- else if (body instanceof URLSearchParams) reqBody = body.toString();
3717
- }
3718
- this.requestStartTimes.set(id, Date.now());
3719
- this.safeEmitNetwork({
3720
- id,
3721
- timestamp: Date.now(),
3722
- method,
3723
- url,
3724
- headers: this.stringifyHeaders(newInit.headers),
3725
- body: reqBody,
3726
- pending: true
3727
- });
3728
- try {
3729
- const response = await originalFetch(input, newInit);
3730
- const clonedRes = response.clone();
3731
- if (clonedRes.body) {
3732
- const reader = clonedRes.body.getReader();
3733
- const decoder = new TextDecoder();
3734
- const chunks = [];
3735
- let chunkIndex = 0;
3736
- const readStream = async () => {
3737
- try {
3738
- while (true) {
3739
- const { done, value } = await reader.read();
3740
- if (done) break;
3741
- const chunkData = decoder.decode(value, { stream: true });
3742
- chunks.push(chunkData);
3743
- this.safeEmitNetwork({
3744
- id,
3745
- pending: true,
3746
- chunk: {
3747
- index: chunkIndex++,
3748
- data: chunkData,
3749
- timestamp: Date.now()
3750
- }
3751
- });
3752
- }
3753
- const startTime = this.requestStartTimes.get(id);
3754
- const durationMs = startTime ? Date.now() - startTime : 0;
3755
- this.requestStartTimes.delete(id);
3756
- this.safeEmitNetwork({
3757
- id,
3758
- pending: false,
3759
- response: {
3760
- status: response.status,
3761
- headers: this.stringifyHeaders(response.headers),
3762
- body: chunks.join(""),
3763
- durationMs
3764
- }
3765
- });
3766
- } catch (err) {
3767
- const message = err instanceof Error ? err.message : String(err);
3768
- this.safeEmitNetwork({
3769
- id,
3770
- pending: false,
3771
- error: `Failed to read response body: ${message}`
3772
- });
3773
- }
3774
- };
3775
- void readStream();
3776
- } else {
3777
- clonedRes.text().then((text) => {
3778
- const startTime = this.requestStartTimes.get(id);
3779
- const durationMs = startTime ? Date.now() - startTime : 0;
3780
- this.requestStartTimes.delete(id);
3781
- this.safeEmitNetwork({
3782
- id,
3783
- pending: false,
3784
- response: {
3785
- status: response.status,
3786
- headers: this.stringifyHeaders(response.headers),
3787
- body: text,
3788
- durationMs
3789
- }
3790
- });
3791
- }).catch((err) => {
3792
- const message = err instanceof Error ? err.message : String(err);
3793
- this.safeEmitNetwork({
3794
- id,
3795
- pending: false,
3796
- error: `Failed to read response body: ${message}`
3797
- });
3798
- });
3799
- }
3800
- return response;
3801
- } catch (err) {
3802
- this.requestStartTimes.delete(id);
3803
- const message = err instanceof Error ? err.message : String(err);
3804
- this.safeEmitNetwork({ id, pending: false, error: message });
3805
- throw err;
3806
- }
3807
- };
3808
- }
3809
- patchNodeHttp() {
3810
- const self = this;
3811
- const originalRequest = http.request;
3812
- const originalHttpsRequest = https.request;
3813
- const wrapRequest = (originalFn, args, protocol) => {
3814
- const firstArg = args[0];
3815
- let options;
3816
- if (typeof firstArg === "string") {
3817
- options = firstArg;
3818
- } else if (firstArg instanceof URL) {
3819
- options = firstArg;
3820
- } else if (firstArg && typeof firstArg === "object") {
3821
- options = isRequestOptions(firstArg) ? firstArg : {};
3822
- } else {
3823
- options = {};
3824
- }
3825
- let url = "";
3826
- if (typeof options === "string") {
3827
- url = options;
3828
- } else if (options instanceof URL) {
3829
- url = options.href;
3830
- } else {
3831
- const href = "href" in options && typeof options.href === "string" ? options.href : "";
3832
- url = href || `${protocol}//${options.hostname || options.host || "localhost"}${options.path || "/"}`;
3833
- }
3834
- if (url.includes("127.0.0.1") || url.includes("localhost")) {
3835
- return callHttpRequest(originalFn, args);
3836
- }
3837
- const rawHeaders = typeof options === "object" && options !== null && !(options instanceof URL) ? options.headers : void 0;
3838
- let headers = {};
3839
- if (rawHeaders && isHeaderRecord(rawHeaders)) {
3840
- headers = rawHeaders;
3841
- }
3842
- if (headers[ACTIVITY_ID_HEADER]) {
3843
- delete headers[ACTIVITY_ID_HEADER];
3844
- return callHttpRequest(originalFn, args);
3845
- }
3846
- const id = Math.random().toString(36).substring(7);
3847
- this.requestStartTimes.set(id, Date.now());
3848
- const req = callHttpRequest(originalFn, args);
3849
- const requestChunks = [];
3850
- const oldWrite = req.write;
3851
- const oldEnd = req.end;
3852
- req.write = function(chunk, ...etc) {
3853
- if (chunk) {
3854
- const arg0 = etc[0];
3855
- const encoding = typeof arg0 === "string" && Buffer.isEncoding(arg0) ? arg0 : void 0;
3856
- requestChunks.push(
3857
- Buffer.isBuffer(chunk) ? chunk : typeof chunk === "string" ? Buffer.from(chunk, encoding) : Buffer.from(
3858
- chunk instanceof Uint8Array ? chunk : String(chunk)
3859
- )
3860
- );
3861
- }
3862
- return oldWrite.apply(this, [chunk, ...etc]);
3863
- };
3864
- req.end = function(chunkOrCb, ...etc) {
3865
- const chunk = typeof chunkOrCb === "function" ? void 0 : chunkOrCb;
3866
- if (chunk) {
3867
- const arg0 = etc[0];
3868
- const encoding = typeof arg0 === "string" && Buffer.isEncoding(arg0) ? arg0 : void 0;
3869
- requestChunks.push(
3870
- Buffer.isBuffer(chunk) ? chunk : typeof chunk === "string" ? Buffer.from(chunk, encoding) : Buffer.from(
3871
- chunk instanceof Uint8Array ? chunk : String(chunk)
3872
- )
3873
- );
3874
- }
3875
- const body = Buffer.concat(requestChunks).toString("utf8");
3876
- self.safeEmitNetwork({
3877
- id,
3878
- timestamp: Date.now(),
3879
- method: req.method || "GET",
3880
- url,
3881
- headers: self.stringifyHeaders(req.getHeaders()),
3882
- body,
3883
- pending: true
3884
- });
3885
- return oldEnd.apply(this, [chunkOrCb, ...etc]);
3886
- };
3887
- req.on("response", (res) => {
3888
- const responseChunks = [];
3889
- let chunkIndex = 0;
3890
- res.on("data", (chunk) => {
3891
- const chunkBuffer = Buffer.from(chunk);
3892
- responseChunks.push(chunkBuffer);
3893
- self.safeEmitNetwork({
3894
- id,
3895
- pending: true,
3896
- chunk: {
3897
- index: chunkIndex++,
3898
- data: chunkBuffer.toString("utf8"),
3899
- timestamp: Date.now()
3900
- }
3901
- });
3902
- });
3903
- res.on("end", () => {
3904
- const buffer = Buffer.concat(responseChunks);
3905
- const encoding = res.headers["content-encoding"];
3906
- const processBuffer = (finalBuffer) => {
3907
- const resBody = finalBuffer.toString("utf8");
3908
- const startTime = self.requestStartTimes.get(id);
3909
- const durationMs = startTime ? Date.now() - startTime : 0;
3910
- self.requestStartTimes.delete(id);
3911
- self.safeEmitNetwork({
3912
- id,
3913
- pending: false,
3914
- response: {
3915
- status: res.statusCode || 0,
3916
- headers: self.stringifyHeaders(res.headers),
3917
- body: resBody,
3918
- durationMs
3919
- }
3920
- });
3921
- };
3922
- if (encoding === "gzip") {
3923
- zlib.gunzip(buffer, (err, decompressed) => {
3924
- processBuffer(err ? buffer : decompressed);
3925
- });
3926
- } else if (encoding === "deflate") {
3927
- zlib.inflate(buffer, (err, decompressed) => {
3928
- processBuffer(err ? buffer : decompressed);
3929
- });
3930
- } else {
3931
- processBuffer(buffer);
3932
- }
3933
- });
3934
- });
3935
- req.on("error", (err) => {
3936
- self.requestStartTimes.delete(id);
3937
- const message = err.message;
3938
- self.safeEmitNetwork({
3939
- id,
3940
- pending: false,
3941
- error: message
3942
- });
3943
- });
3944
- return req;
3945
- };
3946
- Object.defineProperty(http, "request", {
3947
- value: (url, options, callback) => {
3948
- const args = callback !== void 0 ? [url, options, callback] : options !== void 0 ? [url, options] : [url];
3949
- return wrapRequest(originalRequest, args, "http:");
3950
- },
3951
- writable: true,
3952
- configurable: true
3953
- });
3954
- Object.defineProperty(https, "request", {
3955
- value: (url, options, callback) => {
3956
- const args = callback !== void 0 ? [url, options, callback] : options !== void 0 ? [url, options] : [url];
3957
- return wrapRequest(
3958
- originalHttpsRequest,
3959
- args,
3960
- "https:"
3961
- );
3962
- },
3963
- writable: true,
3964
- configurable: true
3965
- });
3966
- }
3967
- logConsole(payload) {
3968
- const enriched = { ...payload, timestamp: Date.now() };
3969
- this.consoleBuffer.push(enriched);
3970
- if (this.consoleBuffer.length > this.bufferLimit) {
3971
- this.consoleBuffer.shift();
3972
- }
3973
- this.emit("console", enriched);
3974
- }
3975
- };
3976
- function setupFileLogging(capture, config, customPath) {
3977
- const logFile = customPath || (config.storage ? path.join(
3978
- config.storage.getProjectTempLogsDir(),
3979
- `session-${config.getSessionId()}.jsonl`
3980
- ) : null);
3981
- if (!logFile) return;
3982
- const logsDir = path.dirname(logFile);
3983
- if (!fs.existsSync(logsDir)) {
3984
- fs.mkdirSync(logsDir, { recursive: true });
3985
- }
3986
- const writeToLog = (type, payload) => {
3987
- try {
3988
- const entry = JSON.stringify({
3989
- type,
3990
- payload,
3991
- sessionId: config.getSessionId(),
3992
- timestamp: Date.now()
3993
- }) + "\n";
3994
- fs.promises.appendFile(logFile, entry).catch((err) => {
3995
- debugLogger.error("Failed to write to activity log:", err);
3996
- });
3997
- } catch (err) {
3998
- debugLogger.error("Failed to prepare activity log entry:", err);
3999
- }
4000
- };
4001
- capture.on("console", (payload) => writeToLog("console", payload));
4002
- capture.on("network", (payload) => writeToLog("network", payload));
4003
- }
4004
- function setupNetworkLogging(capture, host, port, config, onReconnectFailed) {
4005
- const transportBuffer = [];
4006
- let ws = null;
4007
- let reconnectTimer = null;
4008
- let sessionId = null;
4009
- let pingInterval = null;
4010
- let reconnectAttempts = 0;
4011
- const MAX_RECONNECT_ATTEMPTS = 2;
4012
- const connect = () => {
4013
- try {
4014
- ws = new wrapper_default(`ws://${host}:${port}/ws`);
4015
- ws.on("open", () => {
4016
- debugLogger.debug(`WebSocket connected to ${host}:${port}`);
4017
- reconnectAttempts = 0;
4018
- sendMessage({
4019
- type: "register",
4020
- sessionId: config.getSessionId(),
4021
- timestamp: Date.now()
4022
- });
4023
- });
4024
- ws.on("message", (data) => {
4025
- try {
4026
- const parsed = JSON.parse(data.toString());
4027
- if (typeof parsed === "object" && parsed !== null && "type" in parsed && typeof parsed.type === "string") {
4028
- handleServerMessage({
4029
- type: parsed.type,
4030
- sessionId: "sessionId" in parsed && typeof parsed.sessionId === "string" ? parsed.sessionId : void 0
4031
- });
4032
- }
4033
- } catch (err) {
4034
- debugLogger.debug("Invalid WebSocket message:", err);
4035
- }
4036
- });
4037
- ws.on("close", () => {
4038
- debugLogger.debug(`WebSocket disconnected from ${host}:${port}`);
4039
- cleanup();
4040
- scheduleReconnect();
4041
- });
4042
- ws.on("error", (err) => {
4043
- debugLogger.debug(`WebSocket error:`, err);
4044
- });
4045
- } catch (err) {
4046
- debugLogger.debug(`Failed to connect WebSocket:`, err);
4047
- scheduleReconnect();
4048
- }
4049
- };
4050
- const handleServerMessage = (message) => {
4051
- switch (message.type) {
4052
- case "registered":
4053
- sessionId = message.sessionId || null;
4054
- debugLogger.debug(`WebSocket session registered: ${sessionId}`);
4055
- if (pingInterval) clearInterval(pingInterval);
4056
- pingInterval = setInterval(() => {
4057
- sendMessage({ type: "pong", timestamp: Date.now() });
4058
- }, 15e3);
4059
- flushBuffer();
4060
- break;
4061
- case "trigger-debugger": {
4062
- import("node:inspector").then((inspector) => {
4063
- inspector.open();
4064
- debugLogger.log(
4065
- "Node debugger attached. Open chrome://inspect in Chrome to start debugging."
4066
- );
4067
- return import("./events-XB7DADIJ.js");
4068
- }).then(({ appEvents, AppEvent, TransientMessageType }) => {
4069
- appEvents.emit(AppEvent.TransientMessage, {
4070
- message: "Debugger attached from DevTools.",
4071
- type: TransientMessageType.Hint
4072
- });
4073
- }).catch(
4074
- (err) => debugLogger.debug("Failed to trigger debugger:", err)
4075
- );
4076
- break;
4077
- }
4078
- case "ping":
4079
- sendMessage({ type: "pong", timestamp: Date.now() });
4080
- break;
4081
- default:
4082
- break;
4083
- }
4084
- };
4085
- const sendMessage = (message) => {
4086
- if (ws && ws.readyState === wrapper_default.OPEN) {
4087
- ws.send(JSON.stringify(message));
4088
- }
4089
- };
4090
- const sendToNetwork = (type, payload) => {
4091
- const message = {
4092
- type,
4093
- payload,
4094
- sessionId: sessionId || config.getSessionId(),
4095
- timestamp: Date.now()
4096
- };
4097
- if (!ws || ws.readyState !== wrapper_default.OPEN || !capture.isNetworkLoggingEnabled()) {
4098
- transportBuffer.push(message);
4099
- if (transportBuffer.length > MAX_BUFFER_SIZE) transportBuffer.shift();
4100
- return;
4101
- }
4102
- sendMessage(message);
4103
- };
4104
- const flushBuffer = () => {
4105
- if (!ws || ws.readyState !== wrapper_default.OPEN || !capture.isNetworkLoggingEnabled()) {
4106
- return;
4107
- }
4108
- const { network, console: consoleLogs } = capture.drainBufferedLogs();
4109
- const allInitialLogs = [
4110
- ...network.map((l) => ({
4111
- type: "network",
4112
- payload: l,
4113
- timestamp: "timestamp" in l && l.timestamp ? l.timestamp : Date.now()
4114
- })),
4115
- ...consoleLogs.map((l) => ({
4116
- type: "console",
4117
- payload: l,
4118
- timestamp: l.timestamp
4119
- }))
4120
- ].sort((a, b) => a.timestamp - b.timestamp);
4121
- debugLogger.debug(
4122
- `Flushing ${allInitialLogs.length} initial buffered logs and ${transportBuffer.length} transport buffered logs...`
4123
- );
4124
- for (const log of allInitialLogs) {
4125
- sendMessage({
4126
- type: log.type,
4127
- payload: log.payload,
4128
- sessionId: sessionId || config.getSessionId(),
4129
- timestamp: Date.now()
4130
- });
4131
- }
4132
- while (transportBuffer.length > 0) {
4133
- const message = transportBuffer.shift();
4134
- sendMessage(message);
4135
- }
4136
- };
4137
- const cleanup = () => {
4138
- if (pingInterval) {
4139
- clearInterval(pingInterval);
4140
- pingInterval = null;
4141
- }
4142
- ws = null;
4143
- };
4144
- const scheduleReconnect = () => {
4145
- if (reconnectTimer) return;
4146
- reconnectAttempts++;
4147
- if (reconnectAttempts > MAX_RECONNECT_ATTEMPTS && onReconnectFailed) {
4148
- debugLogger.debug(
4149
- `WebSocket reconnect failed after ${MAX_RECONNECT_ATTEMPTS} attempts, promoting to server...`
4150
- );
4151
- onReconnectFailed();
4152
- return;
4153
- }
4154
- reconnectTimer = setTimeout(() => {
4155
- reconnectTimer = null;
4156
- debugLogger.debug("Reconnecting WebSocket...");
4157
- connect();
4158
- }, 1e3);
4159
- };
4160
- connect();
4161
- capture.on("console", (payload) => sendToNetwork("console", payload));
4162
- capture.on("network", (payload) => sendToNetwork("network", payload));
4163
- capture.on("network-logging-enabled", () => {
4164
- debugLogger.debug("Network logging enabled, flushing buffer...");
4165
- flushBuffer();
4166
- });
4167
- process.on("exit", () => {
4168
- if (reconnectTimer) clearTimeout(reconnectTimer);
4169
- if (ws) ws.close();
4170
- cleanup();
4171
- });
4172
- }
4173
- var bridgeAttached = false;
4174
- function bridgeCoreEvents(capture) {
4175
- if (bridgeAttached) return;
4176
- bridgeAttached = true;
4177
- coreEvents.on(CoreEvent.ConsoleLog, (payload) => {
4178
- capture.logConsole(payload);
4179
- });
4180
- }
4181
- function initActivityLogger(config, options) {
4182
- const capture = ActivityLogger.getInstance();
4183
- capture.enable();
4184
- if (options.mode === "network") {
4185
- setupNetworkLogging(
4186
- capture,
4187
- options.host,
4188
- options.port,
4189
- config,
4190
- options.onReconnectFailed
4191
- );
4192
- capture.enableNetworkLogging();
4193
- } else if (options.mode === "file") {
4194
- setupFileLogging(capture, config, options.filePath);
4195
- }
4196
- bridgeCoreEvents(capture);
4197
- }
4198
- function addNetworkTransport(config, host, port, onReconnectFailed) {
4199
- const capture = ActivityLogger.getInstance();
4200
- setupNetworkLogging(capture, host, port, config, onReconnectFailed);
4201
- }
4202
-
4203
- // packages/cli/src/utils/devtoolsService.ts
4204
- var DEFAULT_DEVTOOLS_PORT = 25417;
4205
- var DEFAULT_DEVTOOLS_HOST = "127.0.0.1";
4206
- var MAX_PROMOTION_ATTEMPTS = 3;
4207
- var promotionAttempts = 0;
4208
- var serverStartPromise = null;
4209
- var connectedUrl = null;
4210
- function probeDevTools(host, port) {
4211
- return new Promise((resolve) => {
4212
- const ws = new wrapper_default(`ws://${host}:${port}/ws`);
4213
- const timer = setTimeout(() => {
4214
- ws.close();
4215
- resolve(false);
4216
- }, 500);
4217
- ws.on("open", () => {
4218
- clearTimeout(timer);
4219
- ws.close();
4220
- resolve(true);
4221
- });
4222
- ws.on("error", () => {
4223
- clearTimeout(timer);
4224
- ws.close();
4225
- resolve(false);
4226
- });
4227
- });
4228
- }
4229
- async function startOrJoinDevTools(defaultHost, defaultPort) {
4230
- const mod = await import("./src-XZYPU6PJ.js");
4231
- const devtools = mod.DevTools.getInstance();
4232
- const url = await devtools.start();
4233
- const actualPort = devtools.getPort();
4234
- if (actualPort === defaultPort) {
4235
- debugLogger.log(`DevTools available at: ${url}`);
4236
- return { host: defaultHost, port: actualPort };
4237
- }
4238
- const winnerAlive = await probeDevTools(defaultHost, defaultPort);
4239
- if (winnerAlive) {
4240
- await devtools.stop();
4241
- debugLogger.log(
4242
- `DevTools (existing) at: http://${defaultHost}:${defaultPort}`
4243
- );
4244
- return { host: defaultHost, port: defaultPort };
4245
- }
4246
- debugLogger.log(`DevTools available at: ${url}`);
4247
- return { host: defaultHost, port: actualPort };
4248
- }
4249
- async function handlePromotion(config) {
4250
- promotionAttempts++;
4251
- if (promotionAttempts > MAX_PROMOTION_ATTEMPTS) {
4252
- debugLogger.debug(
4253
- `Giving up on DevTools promotion after ${MAX_PROMOTION_ATTEMPTS} attempts`
4254
- );
4255
- return;
4256
- }
4257
- try {
4258
- const result = await startOrJoinDevTools(
4259
- DEFAULT_DEVTOOLS_HOST,
4260
- DEFAULT_DEVTOOLS_PORT
4261
- );
4262
- addNetworkTransport(
4263
- config,
4264
- result.host,
4265
- result.port,
4266
- () => handlePromotion(config)
4267
- );
4268
- } catch (err) {
4269
- debugLogger.debug("Failed to promote to DevTools server:", err);
4270
- }
4271
- }
4272
- function setupInitialActivityLogger(config) {
4273
- const target = process.env["GEMINI_CLI_ACTIVITY_LOG_TARGET"];
4274
- if (target) {
4275
- if (!config.storage) return;
4276
- initActivityLogger(config, { mode: "file", filePath: target });
4277
- } else {
4278
- initActivityLogger(config, { mode: "buffer" });
4279
- }
4280
- }
4281
- function startDevToolsServer(config) {
4282
- if (connectedUrl) return Promise.resolve(connectedUrl);
4283
- if (serverStartPromise) return serverStartPromise;
4284
- serverStartPromise = startDevToolsServerImpl(config).catch((err) => {
4285
- serverStartPromise = null;
4286
- throw err;
4287
- });
4288
- return serverStartPromise;
4289
- }
4290
- async function startDevToolsServerImpl(config) {
4291
- const onReconnectFailed = () => handlePromotion(config);
4292
- const existing = await probeDevTools(
4293
- DEFAULT_DEVTOOLS_HOST,
4294
- DEFAULT_DEVTOOLS_PORT
4295
- );
4296
- let host = DEFAULT_DEVTOOLS_HOST;
4297
- let port = DEFAULT_DEVTOOLS_PORT;
4298
- if (existing) {
4299
- debugLogger.log(
4300
- `DevTools (existing) at: http://${DEFAULT_DEVTOOLS_HOST}:${DEFAULT_DEVTOOLS_PORT}`
4301
- );
4302
- } else {
4303
- try {
4304
- const result = await startOrJoinDevTools(
4305
- DEFAULT_DEVTOOLS_HOST,
4306
- DEFAULT_DEVTOOLS_PORT
4307
- );
4308
- host = result.host;
4309
- port = result.port;
4310
- } catch (err) {
4311
- debugLogger.debug("Failed to start DevTools:", err);
4312
- throw err;
4313
- }
4314
- }
4315
- addNetworkTransport(config, host, port, onReconnectFailed);
4316
- const capture = ActivityLogger.getInstance();
4317
- capture.enableNetworkLogging();
4318
- const url = `http://localhost:${port}`;
4319
- connectedUrl = url;
4320
- return url;
4321
- }
4322
- async function toggleDevToolsPanel(config, isOpen, toggle, setOpen) {
4323
- if (isOpen) {
4324
- toggle();
4325
- return;
4326
- }
4327
- try {
4328
- const { openBrowserSecurely, shouldLaunchBrowser } = await import("./dist-B6J3QDWI.js");
4329
- const url = await startDevToolsServer(config);
4330
- if (shouldLaunchBrowser()) {
4331
- try {
4332
- await openBrowserSecurely(url);
4333
- return;
4334
- } catch (e) {
4335
- debugLogger.warn("Failed to open browser securely:", e);
4336
- }
4337
- }
4338
- setOpen();
4339
- } catch (e) {
4340
- setOpen();
4341
- debugLogger.error("Failed to start DevTools server:", e);
4342
- }
4343
- }
4344
- function resetForTesting() {
4345
- promotionAttempts = 0;
4346
- serverStartPromise = null;
4347
- connectedUrl = null;
4348
- }
4349
- export {
4350
- resetForTesting,
4351
- setupInitialActivityLogger,
4352
- startDevToolsServer,
4353
- toggleDevToolsPanel
4354
- };
4355
- /**
4356
- * @license
4357
- * Copyright 2025 Google LLC
4358
- * SPDX-License-Identifier: Apache-2.0
4359
- */