linkque-cli-v2 1.0.2-beta.0

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