@gobi-starweaver/ws-cli 0.3.1

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