@sayna-ai/node-sdk 0.0.16 → 0.0.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,2888 +1,30 @@
1
- var __create = Object.create;
2
- var __getProtoOf = Object.getPrototypeOf;
3
1
  var __defProp = Object.defineProperty;
4
2
  var __getOwnPropNames = Object.getOwnPropertyNames;
5
3
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
4
  var __hasOwnProp = Object.prototype.hasOwnProperty;
7
- var __toESM = (mod, isNodeMode, target) => {
8
- target = mod != null ? __create(__getProtoOf(mod)) : {};
9
- const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
10
- for (let key of __getOwnPropNames(mod))
11
- if (!__hasOwnProp.call(to, key))
12
- __defProp(to, key, {
13
- get: () => mod[key],
14
- enumerable: true
15
- });
16
- return to;
17
- };
18
- var __moduleCache = /* @__PURE__ */ new WeakMap;
19
- var __toCommonJS = (from) => {
20
- var entry = __moduleCache.get(from), desc;
21
- if (entry)
22
- return entry;
23
- entry = __defProp({}, "__esModule", { value: true });
24
- if (from && typeof from === "object" || typeof from === "function")
25
- __getOwnPropNames(from).map((key) => !__hasOwnProp.call(entry, key) && __defProp(entry, key, {
26
- get: () => from[key],
27
- enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
28
- }));
29
- __moduleCache.set(from, entry);
30
- return entry;
31
- };
32
- var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
33
- var __export = (target, all) => {
34
- for (var name in all)
35
- __defProp(target, name, {
36
- get: all[name],
37
- enumerable: true,
38
- configurable: true,
39
- set: (newValue) => all[name] = () => newValue
40
- });
41
- };
42
-
43
- // node_modules/ws/lib/constants.js
44
- var require_constants = __commonJS((exports2, module2) => {
45
- var BINARY_TYPES = ["nodebuffer", "arraybuffer", "fragments"];
46
- var hasBlob = typeof Blob !== "undefined";
47
- if (hasBlob)
48
- BINARY_TYPES.push("blob");
49
- module2.exports = {
50
- BINARY_TYPES,
51
- CLOSE_TIMEOUT: 30000,
52
- EMPTY_BUFFER: Buffer.alloc(0),
53
- GUID: "258EAFA5-E914-47DA-95CA-C5AB0DC85B11",
54
- hasBlob,
55
- kForOnEventAttribute: Symbol("kIsForOnEventAttribute"),
56
- kListener: Symbol("kListener"),
57
- kStatusCode: Symbol("status-code"),
58
- kWebSocket: Symbol("websocket"),
59
- NOOP: () => {}
60
- };
61
- });
62
-
63
- // node_modules/ws/lib/buffer-util.js
64
- var require_buffer_util = __commonJS((exports2, module2) => {
65
- var { EMPTY_BUFFER } = require_constants();
66
- var FastBuffer = Buffer[Symbol.species];
67
- function concat(list, totalLength) {
68
- if (list.length === 0)
69
- return EMPTY_BUFFER;
70
- if (list.length === 1)
71
- return list[0];
72
- const target = Buffer.allocUnsafe(totalLength);
73
- let offset = 0;
74
- for (let i = 0;i < list.length; i++) {
75
- const buf = list[i];
76
- target.set(buf, offset);
77
- offset += buf.length;
78
- }
79
- if (offset < totalLength) {
80
- return new FastBuffer(target.buffer, target.byteOffset, offset);
81
- }
82
- return target;
83
- }
84
- function _mask(source, mask, output, offset, length) {
85
- for (let i = 0;i < length; i++) {
86
- output[offset + i] = source[i] ^ mask[i & 3];
87
- }
88
- }
89
- function _unmask(buffer, mask) {
90
- for (let i = 0;i < buffer.length; i++) {
91
- buffer[i] ^= mask[i & 3];
92
- }
93
- }
94
- function toArrayBuffer(buf) {
95
- if (buf.length === buf.buffer.byteLength) {
96
- return buf.buffer;
97
- }
98
- return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length);
99
- }
100
- function toBuffer(data) {
101
- toBuffer.readOnly = true;
102
- if (Buffer.isBuffer(data))
103
- return data;
104
- let buf;
105
- if (data instanceof ArrayBuffer) {
106
- buf = new FastBuffer(data);
107
- } else if (ArrayBuffer.isView(data)) {
108
- buf = new FastBuffer(data.buffer, data.byteOffset, data.byteLength);
109
- } else {
110
- buf = Buffer.from(data);
111
- toBuffer.readOnly = false;
112
- }
113
- return buf;
114
- }
115
- module2.exports = {
116
- concat,
117
- mask: _mask,
118
- toArrayBuffer,
119
- toBuffer,
120
- unmask: _unmask
121
- };
122
- if (!process.env.WS_NO_BUFFER_UTIL) {
123
- try {
124
- const bufferUtil = (()=>{throw new Error("Cannot require module "+"bufferutil");})();
125
- module2.exports.mask = function(source, mask, output, offset, length) {
126
- if (length < 48)
127
- _mask(source, mask, output, offset, length);
128
- else
129
- bufferUtil.mask(source, mask, output, offset, length);
130
- };
131
- module2.exports.unmask = function(buffer, mask) {
132
- if (buffer.length < 32)
133
- _unmask(buffer, mask);
134
- else
135
- bufferUtil.unmask(buffer, mask);
136
- };
137
- } catch (e) {}
138
- }
139
- });
140
-
141
- // node_modules/ws/lib/limiter.js
142
- var require_limiter = __commonJS((exports2, module2) => {
143
- var kDone = Symbol("kDone");
144
- var kRun = Symbol("kRun");
145
-
146
- class Limiter {
147
- constructor(concurrency) {
148
- this[kDone] = () => {
149
- this.pending--;
150
- this[kRun]();
151
- };
152
- this.concurrency = concurrency || Infinity;
153
- this.jobs = [];
154
- this.pending = 0;
155
- }
156
- add(job) {
157
- this.jobs.push(job);
158
- this[kRun]();
159
- }
160
- [kRun]() {
161
- if (this.pending === this.concurrency)
162
- return;
163
- if (this.jobs.length) {
164
- const job = this.jobs.shift();
165
- this.pending++;
166
- job(this[kDone]);
167
- }
168
- }
169
- }
170
- module2.exports = Limiter;
171
- });
172
-
173
- // node_modules/ws/lib/permessage-deflate.js
174
- var require_permessage_deflate = __commonJS((exports2, module2) => {
175
- var zlib = require("zlib");
176
- var bufferUtil = require_buffer_util();
177
- var Limiter = require_limiter();
178
- var { kStatusCode } = require_constants();
179
- var FastBuffer = Buffer[Symbol.species];
180
- var TRAILER = Buffer.from([0, 0, 255, 255]);
181
- var kPerMessageDeflate = Symbol("permessage-deflate");
182
- var kTotalLength = Symbol("total-length");
183
- var kCallback = Symbol("callback");
184
- var kBuffers = Symbol("buffers");
185
- var kError = Symbol("error");
186
- var zlibLimiter;
187
-
188
- class PerMessageDeflate {
189
- constructor(options, isServer, maxPayload) {
190
- this._maxPayload = maxPayload | 0;
191
- this._options = options || {};
192
- this._threshold = this._options.threshold !== undefined ? this._options.threshold : 1024;
193
- this._isServer = !!isServer;
194
- this._deflate = null;
195
- this._inflate = null;
196
- this.params = null;
197
- if (!zlibLimiter) {
198
- const concurrency = this._options.concurrencyLimit !== undefined ? this._options.concurrencyLimit : 10;
199
- zlibLimiter = new Limiter(concurrency);
200
- }
201
- }
202
- static get extensionName() {
203
- return "permessage-deflate";
204
- }
205
- offer() {
206
- const params = {};
207
- if (this._options.serverNoContextTakeover) {
208
- params.server_no_context_takeover = true;
209
- }
210
- if (this._options.clientNoContextTakeover) {
211
- params.client_no_context_takeover = true;
212
- }
213
- if (this._options.serverMaxWindowBits) {
214
- params.server_max_window_bits = this._options.serverMaxWindowBits;
215
- }
216
- if (this._options.clientMaxWindowBits) {
217
- params.client_max_window_bits = this._options.clientMaxWindowBits;
218
- } else if (this._options.clientMaxWindowBits == null) {
219
- params.client_max_window_bits = true;
220
- }
221
- return params;
222
- }
223
- accept(configurations) {
224
- configurations = this.normalizeParams(configurations);
225
- this.params = this._isServer ? this.acceptAsServer(configurations) : this.acceptAsClient(configurations);
226
- return this.params;
227
- }
228
- cleanup() {
229
- if (this._inflate) {
230
- this._inflate.close();
231
- this._inflate = null;
232
- }
233
- if (this._deflate) {
234
- const callback = this._deflate[kCallback];
235
- this._deflate.close();
236
- this._deflate = null;
237
- if (callback) {
238
- callback(new Error("The deflate stream was closed while data was being processed"));
239
- }
240
- }
241
- }
242
- acceptAsServer(offers) {
243
- const opts = this._options;
244
- const accepted = offers.find((params) => {
245
- if (opts.serverNoContextTakeover === false && params.server_no_context_takeover || params.server_max_window_bits && (opts.serverMaxWindowBits === false || typeof opts.serverMaxWindowBits === "number" && opts.serverMaxWindowBits > params.server_max_window_bits) || typeof opts.clientMaxWindowBits === "number" && !params.client_max_window_bits) {
246
- return false;
247
- }
248
- return true;
249
- });
250
- if (!accepted) {
251
- throw new Error("None of the extension offers can be accepted");
252
- }
253
- if (opts.serverNoContextTakeover) {
254
- accepted.server_no_context_takeover = true;
255
- }
256
- if (opts.clientNoContextTakeover) {
257
- accepted.client_no_context_takeover = true;
258
- }
259
- if (typeof opts.serverMaxWindowBits === "number") {
260
- accepted.server_max_window_bits = opts.serverMaxWindowBits;
261
- }
262
- if (typeof opts.clientMaxWindowBits === "number") {
263
- accepted.client_max_window_bits = opts.clientMaxWindowBits;
264
- } else if (accepted.client_max_window_bits === true || opts.clientMaxWindowBits === false) {
265
- delete accepted.client_max_window_bits;
266
- }
267
- return accepted;
268
- }
269
- acceptAsClient(response) {
270
- const params = response[0];
271
- if (this._options.clientNoContextTakeover === false && params.client_no_context_takeover) {
272
- throw new Error('Unexpected parameter "client_no_context_takeover"');
273
- }
274
- if (!params.client_max_window_bits) {
275
- if (typeof this._options.clientMaxWindowBits === "number") {
276
- params.client_max_window_bits = this._options.clientMaxWindowBits;
277
- }
278
- } else if (this._options.clientMaxWindowBits === false || typeof this._options.clientMaxWindowBits === "number" && params.client_max_window_bits > this._options.clientMaxWindowBits) {
279
- throw new Error('Unexpected or invalid parameter "client_max_window_bits"');
280
- }
281
- return params;
282
- }
283
- normalizeParams(configurations) {
284
- configurations.forEach((params) => {
285
- Object.keys(params).forEach((key) => {
286
- let value = params[key];
287
- if (value.length > 1) {
288
- throw new Error(`Parameter "${key}" must have only a single value`);
289
- }
290
- value = value[0];
291
- if (key === "client_max_window_bits") {
292
- if (value !== true) {
293
- const num = +value;
294
- if (!Number.isInteger(num) || num < 8 || num > 15) {
295
- throw new TypeError(`Invalid value for parameter "${key}": ${value}`);
296
- }
297
- value = num;
298
- } else if (!this._isServer) {
299
- throw new TypeError(`Invalid value for parameter "${key}": ${value}`);
300
- }
301
- } else if (key === "server_max_window_bits") {
302
- const num = +value;
303
- if (!Number.isInteger(num) || num < 8 || num > 15) {
304
- throw new TypeError(`Invalid value for parameter "${key}": ${value}`);
305
- }
306
- value = num;
307
- } else if (key === "client_no_context_takeover" || key === "server_no_context_takeover") {
308
- if (value !== true) {
309
- throw new TypeError(`Invalid value for parameter "${key}": ${value}`);
310
- }
311
- } else {
312
- throw new Error(`Unknown parameter "${key}"`);
313
- }
314
- params[key] = value;
315
- });
316
- });
317
- return configurations;
318
- }
319
- decompress(data, fin, callback) {
320
- zlibLimiter.add((done) => {
321
- this._decompress(data, fin, (err, result) => {
322
- done();
323
- callback(err, result);
324
- });
325
- });
326
- }
327
- compress(data, fin, callback) {
328
- zlibLimiter.add((done) => {
329
- this._compress(data, fin, (err, result) => {
330
- done();
331
- callback(err, result);
332
- });
333
- });
334
- }
335
- _decompress(data, fin, callback) {
336
- const endpoint = this._isServer ? "client" : "server";
337
- if (!this._inflate) {
338
- const key = `${endpoint}_max_window_bits`;
339
- const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
340
- this._inflate = zlib.createInflateRaw({
341
- ...this._options.zlibInflateOptions,
342
- windowBits
343
- });
344
- this._inflate[kPerMessageDeflate] = this;
345
- this._inflate[kTotalLength] = 0;
346
- this._inflate[kBuffers] = [];
347
- this._inflate.on("error", inflateOnError);
348
- this._inflate.on("data", inflateOnData);
349
- }
350
- this._inflate[kCallback] = callback;
351
- this._inflate.write(data);
352
- if (fin)
353
- this._inflate.write(TRAILER);
354
- this._inflate.flush(() => {
355
- const err = this._inflate[kError];
356
- if (err) {
357
- this._inflate.close();
358
- this._inflate = null;
359
- callback(err);
360
- return;
361
- }
362
- const data2 = bufferUtil.concat(this._inflate[kBuffers], this._inflate[kTotalLength]);
363
- if (this._inflate._readableState.endEmitted) {
364
- this._inflate.close();
365
- this._inflate = null;
366
- } else {
367
- this._inflate[kTotalLength] = 0;
368
- this._inflate[kBuffers] = [];
369
- if (fin && this.params[`${endpoint}_no_context_takeover`]) {
370
- this._inflate.reset();
371
- }
372
- }
373
- callback(null, data2);
374
- });
375
- }
376
- _compress(data, fin, callback) {
377
- const endpoint = this._isServer ? "server" : "client";
378
- if (!this._deflate) {
379
- const key = `${endpoint}_max_window_bits`;
380
- const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
381
- this._deflate = zlib.createDeflateRaw({
382
- ...this._options.zlibDeflateOptions,
383
- windowBits
384
- });
385
- this._deflate[kTotalLength] = 0;
386
- this._deflate[kBuffers] = [];
387
- this._deflate.on("data", deflateOnData);
388
- }
389
- this._deflate[kCallback] = callback;
390
- this._deflate.write(data);
391
- this._deflate.flush(zlib.Z_SYNC_FLUSH, () => {
392
- if (!this._deflate) {
393
- return;
394
- }
395
- let data2 = bufferUtil.concat(this._deflate[kBuffers], this._deflate[kTotalLength]);
396
- if (fin) {
397
- data2 = new FastBuffer(data2.buffer, data2.byteOffset, data2.length - 4);
398
- }
399
- this._deflate[kCallback] = null;
400
- this._deflate[kTotalLength] = 0;
401
- this._deflate[kBuffers] = [];
402
- if (fin && this.params[`${endpoint}_no_context_takeover`]) {
403
- this._deflate.reset();
404
- }
405
- callback(null, data2);
406
- });
407
- }
408
- }
409
- module2.exports = PerMessageDeflate;
410
- function deflateOnData(chunk) {
411
- this[kBuffers].push(chunk);
412
- this[kTotalLength] += chunk.length;
413
- }
414
- function inflateOnData(chunk) {
415
- this[kTotalLength] += chunk.length;
416
- if (this[kPerMessageDeflate]._maxPayload < 1 || this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload) {
417
- this[kBuffers].push(chunk);
418
- return;
419
- }
420
- this[kError] = new RangeError("Max payload size exceeded");
421
- this[kError].code = "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH";
422
- this[kError][kStatusCode] = 1009;
423
- this.removeListener("data", inflateOnData);
424
- this.reset();
425
- }
426
- function inflateOnError(err) {
427
- this[kPerMessageDeflate]._inflate = null;
428
- if (this[kError]) {
429
- this[kCallback](this[kError]);
430
- return;
431
- }
432
- err[kStatusCode] = 1007;
433
- this[kCallback](err);
434
- }
435
- });
436
-
437
- // node_modules/ws/lib/validation.js
438
- var require_validation = __commonJS((exports2, module2) => {
439
- var { isUtf8 } = require("buffer");
440
- var { hasBlob } = require_constants();
441
- var tokenChars = [
442
- 0,
443
- 0,
444
- 0,
445
- 0,
446
- 0,
447
- 0,
448
- 0,
449
- 0,
450
- 0,
451
- 0,
452
- 0,
453
- 0,
454
- 0,
455
- 0,
456
- 0,
457
- 0,
458
- 0,
459
- 0,
460
- 0,
461
- 0,
462
- 0,
463
- 0,
464
- 0,
465
- 0,
466
- 0,
467
- 0,
468
- 0,
469
- 0,
470
- 0,
471
- 0,
472
- 0,
473
- 0,
474
- 0,
475
- 1,
476
- 0,
477
- 1,
478
- 1,
479
- 1,
480
- 1,
481
- 1,
482
- 0,
483
- 0,
484
- 1,
485
- 1,
486
- 0,
487
- 1,
488
- 1,
489
- 0,
490
- 1,
491
- 1,
492
- 1,
493
- 1,
494
- 1,
495
- 1,
496
- 1,
497
- 1,
498
- 1,
499
- 1,
500
- 0,
501
- 0,
502
- 0,
503
- 0,
504
- 0,
505
- 0,
506
- 0,
507
- 1,
508
- 1,
509
- 1,
510
- 1,
511
- 1,
512
- 1,
513
- 1,
514
- 1,
515
- 1,
516
- 1,
517
- 1,
518
- 1,
519
- 1,
520
- 1,
521
- 1,
522
- 1,
523
- 1,
524
- 1,
525
- 1,
526
- 1,
527
- 1,
528
- 1,
529
- 1,
530
- 1,
531
- 1,
532
- 1,
533
- 0,
534
- 0,
535
- 0,
536
- 1,
537
- 1,
538
- 1,
539
- 1,
540
- 1,
541
- 1,
542
- 1,
543
- 1,
544
- 1,
545
- 1,
546
- 1,
547
- 1,
548
- 1,
549
- 1,
550
- 1,
551
- 1,
552
- 1,
553
- 1,
554
- 1,
555
- 1,
556
- 1,
557
- 1,
558
- 1,
559
- 1,
560
- 1,
561
- 1,
562
- 1,
563
- 1,
564
- 1,
565
- 0,
566
- 1,
567
- 0,
568
- 1,
569
- 0
570
- ];
571
- function isValidStatusCode(code) {
572
- return code >= 1000 && code <= 1014 && code !== 1004 && code !== 1005 && code !== 1006 || code >= 3000 && code <= 4999;
573
- }
574
- function _isValidUTF8(buf) {
575
- const len = buf.length;
576
- let i = 0;
577
- while (i < len) {
578
- if ((buf[i] & 128) === 0) {
579
- i++;
580
- } else if ((buf[i] & 224) === 192) {
581
- if (i + 1 === len || (buf[i + 1] & 192) !== 128 || (buf[i] & 254) === 192) {
582
- return false;
583
- }
584
- i += 2;
585
- } else if ((buf[i] & 240) === 224) {
586
- if (i + 2 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || buf[i] === 224 && (buf[i + 1] & 224) === 128 || buf[i] === 237 && (buf[i + 1] & 224) === 160) {
587
- return false;
588
- }
589
- i += 3;
590
- } else if ((buf[i] & 248) === 240) {
591
- 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 || buf[i] === 244 && buf[i + 1] > 143 || buf[i] > 244) {
592
- return false;
593
- }
594
- i += 4;
595
- } else {
596
- return false;
597
- }
598
- }
599
- return true;
600
- }
601
- function isBlob(value) {
602
- 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");
603
- }
604
- module2.exports = {
605
- isBlob,
606
- isValidStatusCode,
607
- isValidUTF8: _isValidUTF8,
608
- tokenChars
609
- };
610
- if (isUtf8) {
611
- module2.exports.isValidUTF8 = function(buf) {
612
- return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf);
613
- };
614
- } else if (!process.env.WS_NO_UTF_8_VALIDATE) {
615
- try {
616
- const isValidUTF8 = (()=>{throw new Error("Cannot require module "+"utf-8-validate");})();
617
- module2.exports.isValidUTF8 = function(buf) {
618
- return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf);
619
- };
620
- } catch (e) {}
621
- }
622
- });
623
-
624
- // node_modules/ws/lib/receiver.js
625
- var require_receiver = __commonJS((exports2, module2) => {
626
- var { Writable } = require("stream");
627
- var PerMessageDeflate = require_permessage_deflate();
628
- var {
629
- BINARY_TYPES,
630
- EMPTY_BUFFER,
631
- kStatusCode,
632
- kWebSocket
633
- } = require_constants();
634
- var { concat, toArrayBuffer, unmask } = require_buffer_util();
635
- var { isValidStatusCode, isValidUTF8 } = require_validation();
636
- var FastBuffer = Buffer[Symbol.species];
637
- var GET_INFO = 0;
638
- var GET_PAYLOAD_LENGTH_16 = 1;
639
- var GET_PAYLOAD_LENGTH_64 = 2;
640
- var GET_MASK = 3;
641
- var GET_DATA = 4;
642
- var INFLATING = 5;
643
- var DEFER_EVENT = 6;
644
-
645
- class Receiver extends Writable {
646
- constructor(options = {}) {
647
- super();
648
- this._allowSynchronousEvents = options.allowSynchronousEvents !== undefined ? options.allowSynchronousEvents : true;
649
- this._binaryType = options.binaryType || BINARY_TYPES[0];
650
- this._extensions = options.extensions || {};
651
- this._isServer = !!options.isServer;
652
- this._maxPayload = options.maxPayload | 0;
653
- this._skipUTF8Validation = !!options.skipUTF8Validation;
654
- this[kWebSocket] = undefined;
655
- this._bufferedBytes = 0;
656
- this._buffers = [];
657
- this._compressed = false;
658
- this._payloadLength = 0;
659
- this._mask = undefined;
660
- this._fragmented = 0;
661
- this._masked = false;
662
- this._fin = false;
663
- this._opcode = 0;
664
- this._totalPayloadLength = 0;
665
- this._messageLength = 0;
666
- this._fragments = [];
667
- this._errored = false;
668
- this._loop = false;
669
- this._state = GET_INFO;
670
- }
671
- _write(chunk, encoding, cb) {
672
- if (this._opcode === 8 && this._state == GET_INFO)
673
- return cb();
674
- this._bufferedBytes += chunk.length;
675
- this._buffers.push(chunk);
676
- this.startLoop(cb);
677
- }
678
- consume(n) {
679
- this._bufferedBytes -= n;
680
- if (n === this._buffers[0].length)
681
- return this._buffers.shift();
682
- if (n < this._buffers[0].length) {
683
- const buf = this._buffers[0];
684
- this._buffers[0] = new FastBuffer(buf.buffer, buf.byteOffset + n, buf.length - n);
685
- return new FastBuffer(buf.buffer, buf.byteOffset, n);
686
- }
687
- const dst = Buffer.allocUnsafe(n);
688
- do {
689
- const buf = this._buffers[0];
690
- const offset = dst.length - n;
691
- if (n >= buf.length) {
692
- dst.set(this._buffers.shift(), offset);
693
- } else {
694
- dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset);
695
- this._buffers[0] = new FastBuffer(buf.buffer, buf.byteOffset + n, buf.length - n);
696
- }
697
- n -= buf.length;
698
- } while (n > 0);
699
- return dst;
700
- }
701
- startLoop(cb) {
702
- this._loop = true;
703
- do {
704
- switch (this._state) {
705
- case GET_INFO:
706
- this.getInfo(cb);
707
- break;
708
- case GET_PAYLOAD_LENGTH_16:
709
- this.getPayloadLength16(cb);
710
- break;
711
- case GET_PAYLOAD_LENGTH_64:
712
- this.getPayloadLength64(cb);
713
- break;
714
- case GET_MASK:
715
- this.getMask();
716
- break;
717
- case GET_DATA:
718
- this.getData(cb);
719
- break;
720
- case INFLATING:
721
- case DEFER_EVENT:
722
- this._loop = false;
723
- return;
724
- }
725
- } while (this._loop);
726
- if (!this._errored)
727
- cb();
728
- }
729
- getInfo(cb) {
730
- if (this._bufferedBytes < 2) {
731
- this._loop = false;
732
- return;
733
- }
734
- const buf = this.consume(2);
735
- if ((buf[0] & 48) !== 0) {
736
- const error = this.createError(RangeError, "RSV2 and RSV3 must be clear", true, 1002, "WS_ERR_UNEXPECTED_RSV_2_3");
737
- cb(error);
738
- return;
739
- }
740
- const compressed = (buf[0] & 64) === 64;
741
- if (compressed && !this._extensions[PerMessageDeflate.extensionName]) {
742
- const error = this.createError(RangeError, "RSV1 must be clear", true, 1002, "WS_ERR_UNEXPECTED_RSV_1");
743
- cb(error);
744
- return;
745
- }
746
- this._fin = (buf[0] & 128) === 128;
747
- this._opcode = buf[0] & 15;
748
- this._payloadLength = buf[1] & 127;
749
- if (this._opcode === 0) {
750
- if (compressed) {
751
- const error = this.createError(RangeError, "RSV1 must be clear", true, 1002, "WS_ERR_UNEXPECTED_RSV_1");
752
- cb(error);
753
- return;
754
- }
755
- if (!this._fragmented) {
756
- const error = this.createError(RangeError, "invalid opcode 0", true, 1002, "WS_ERR_INVALID_OPCODE");
757
- cb(error);
758
- return;
759
- }
760
- this._opcode = this._fragmented;
761
- } else if (this._opcode === 1 || this._opcode === 2) {
762
- if (this._fragmented) {
763
- const error = this.createError(RangeError, `invalid opcode ${this._opcode}`, true, 1002, "WS_ERR_INVALID_OPCODE");
764
- cb(error);
765
- return;
766
- }
767
- this._compressed = compressed;
768
- } else if (this._opcode > 7 && this._opcode < 11) {
769
- if (!this._fin) {
770
- const error = this.createError(RangeError, "FIN must be set", true, 1002, "WS_ERR_EXPECTED_FIN");
771
- cb(error);
772
- return;
773
- }
774
- if (compressed) {
775
- const error = this.createError(RangeError, "RSV1 must be clear", true, 1002, "WS_ERR_UNEXPECTED_RSV_1");
776
- cb(error);
777
- return;
778
- }
779
- if (this._payloadLength > 125 || this._opcode === 8 && this._payloadLength === 1) {
780
- const error = this.createError(RangeError, `invalid payload length ${this._payloadLength}`, true, 1002, "WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");
781
- cb(error);
782
- return;
783
- }
784
- } else {
785
- const error = this.createError(RangeError, `invalid opcode ${this._opcode}`, true, 1002, "WS_ERR_INVALID_OPCODE");
786
- cb(error);
787
- return;
788
- }
789
- if (!this._fin && !this._fragmented)
790
- this._fragmented = this._opcode;
791
- this._masked = (buf[1] & 128) === 128;
792
- if (this._isServer) {
793
- if (!this._masked) {
794
- const error = this.createError(RangeError, "MASK must be set", true, 1002, "WS_ERR_EXPECTED_MASK");
795
- cb(error);
796
- return;
797
- }
798
- } else if (this._masked) {
799
- const error = this.createError(RangeError, "MASK must be clear", true, 1002, "WS_ERR_UNEXPECTED_MASK");
800
- cb(error);
801
- return;
802
- }
803
- if (this._payloadLength === 126)
804
- this._state = GET_PAYLOAD_LENGTH_16;
805
- else if (this._payloadLength === 127)
806
- this._state = GET_PAYLOAD_LENGTH_64;
807
- else
808
- this.haveLength(cb);
809
- }
810
- getPayloadLength16(cb) {
811
- if (this._bufferedBytes < 2) {
812
- this._loop = false;
813
- return;
814
- }
815
- this._payloadLength = this.consume(2).readUInt16BE(0);
816
- this.haveLength(cb);
817
- }
818
- getPayloadLength64(cb) {
819
- if (this._bufferedBytes < 8) {
820
- this._loop = false;
821
- return;
822
- }
823
- const buf = this.consume(8);
824
- const num = buf.readUInt32BE(0);
825
- if (num > Math.pow(2, 53 - 32) - 1) {
826
- const error = this.createError(RangeError, "Unsupported WebSocket frame: payload length > 2^53 - 1", false, 1009, "WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");
827
- cb(error);
828
- return;
829
- }
830
- this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4);
831
- this.haveLength(cb);
832
- }
833
- haveLength(cb) {
834
- if (this._payloadLength && this._opcode < 8) {
835
- this._totalPayloadLength += this._payloadLength;
836
- if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) {
837
- const error = this.createError(RangeError, "Max payload size exceeded", false, 1009, "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");
838
- cb(error);
839
- return;
840
- }
841
- }
842
- if (this._masked)
843
- this._state = GET_MASK;
844
- else
845
- this._state = GET_DATA;
846
- }
847
- getMask() {
848
- if (this._bufferedBytes < 4) {
849
- this._loop = false;
850
- return;
851
- }
852
- this._mask = this.consume(4);
853
- this._state = GET_DATA;
854
- }
855
- getData(cb) {
856
- let data = EMPTY_BUFFER;
857
- if (this._payloadLength) {
858
- if (this._bufferedBytes < this._payloadLength) {
859
- this._loop = false;
860
- return;
861
- }
862
- data = this.consume(this._payloadLength);
863
- if (this._masked && (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0) {
864
- unmask(data, this._mask);
865
- }
866
- }
867
- if (this._opcode > 7) {
868
- this.controlMessage(data, cb);
869
- return;
870
- }
871
- if (this._compressed) {
872
- this._state = INFLATING;
873
- this.decompress(data, cb);
874
- return;
875
- }
876
- if (data.length) {
877
- this._messageLength = this._totalPayloadLength;
878
- this._fragments.push(data);
879
- }
880
- this.dataMessage(cb);
881
- }
882
- decompress(data, cb) {
883
- const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
884
- perMessageDeflate.decompress(data, this._fin, (err, buf) => {
885
- if (err)
886
- return cb(err);
887
- if (buf.length) {
888
- this._messageLength += buf.length;
889
- if (this._messageLength > this._maxPayload && this._maxPayload > 0) {
890
- const error = this.createError(RangeError, "Max payload size exceeded", false, 1009, "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");
891
- cb(error);
892
- return;
893
- }
894
- this._fragments.push(buf);
895
- }
896
- this.dataMessage(cb);
897
- if (this._state === GET_INFO)
898
- this.startLoop(cb);
899
- });
900
- }
901
- dataMessage(cb) {
902
- if (!this._fin) {
903
- this._state = GET_INFO;
904
- return;
905
- }
906
- const messageLength = this._messageLength;
907
- const fragments = this._fragments;
908
- this._totalPayloadLength = 0;
909
- this._messageLength = 0;
910
- this._fragmented = 0;
911
- this._fragments = [];
912
- if (this._opcode === 2) {
913
- let data;
914
- if (this._binaryType === "nodebuffer") {
915
- data = concat(fragments, messageLength);
916
- } else if (this._binaryType === "arraybuffer") {
917
- data = toArrayBuffer(concat(fragments, messageLength));
918
- } else if (this._binaryType === "blob") {
919
- data = new Blob(fragments);
920
- } else {
921
- data = fragments;
922
- }
923
- if (this._allowSynchronousEvents) {
924
- this.emit("message", data, true);
925
- this._state = GET_INFO;
926
- } else {
927
- this._state = DEFER_EVENT;
928
- setImmediate(() => {
929
- this.emit("message", data, true);
930
- this._state = GET_INFO;
931
- this.startLoop(cb);
932
- });
933
- }
934
- } else {
935
- const buf = concat(fragments, messageLength);
936
- if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
937
- const error = this.createError(Error, "invalid UTF-8 sequence", true, 1007, "WS_ERR_INVALID_UTF8");
938
- cb(error);
939
- return;
940
- }
941
- if (this._state === INFLATING || this._allowSynchronousEvents) {
942
- this.emit("message", buf, false);
943
- this._state = GET_INFO;
944
- } else {
945
- this._state = DEFER_EVENT;
946
- setImmediate(() => {
947
- this.emit("message", buf, false);
948
- this._state = GET_INFO;
949
- this.startLoop(cb);
950
- });
951
- }
952
- }
953
- }
954
- controlMessage(data, cb) {
955
- if (this._opcode === 8) {
956
- if (data.length === 0) {
957
- this._loop = false;
958
- this.emit("conclude", 1005, EMPTY_BUFFER);
959
- this.end();
960
- } else {
961
- const code = data.readUInt16BE(0);
962
- if (!isValidStatusCode(code)) {
963
- const error = this.createError(RangeError, `invalid status code ${code}`, true, 1002, "WS_ERR_INVALID_CLOSE_CODE");
964
- cb(error);
965
- return;
966
- }
967
- const buf = new FastBuffer(data.buffer, data.byteOffset + 2, data.length - 2);
968
- if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
969
- const error = this.createError(Error, "invalid UTF-8 sequence", true, 1007, "WS_ERR_INVALID_UTF8");
970
- cb(error);
971
- return;
972
- }
973
- this._loop = false;
974
- this.emit("conclude", code, buf);
975
- this.end();
976
- }
977
- this._state = GET_INFO;
978
- return;
979
- }
980
- if (this._allowSynchronousEvents) {
981
- this.emit(this._opcode === 9 ? "ping" : "pong", data);
982
- this._state = GET_INFO;
983
- } else {
984
- this._state = DEFER_EVENT;
985
- setImmediate(() => {
986
- this.emit(this._opcode === 9 ? "ping" : "pong", data);
987
- this._state = GET_INFO;
988
- this.startLoop(cb);
989
- });
990
- }
991
- }
992
- createError(ErrorCtor, message, prefix, statusCode, errorCode) {
993
- this._loop = false;
994
- this._errored = true;
995
- const err = new ErrorCtor(prefix ? `Invalid WebSocket frame: ${message}` : message);
996
- Error.captureStackTrace(err, this.createError);
997
- err.code = errorCode;
998
- err[kStatusCode] = statusCode;
999
- return err;
1000
- }
1001
- }
1002
- module2.exports = Receiver;
1003
- });
1004
-
1005
- // node_modules/ws/lib/sender.js
1006
- var require_sender = __commonJS((exports2, module2) => {
1007
- var { Duplex } = require("stream");
1008
- var { randomFillSync } = require("crypto");
1009
- var PerMessageDeflate = require_permessage_deflate();
1010
- var { EMPTY_BUFFER, kWebSocket, NOOP } = require_constants();
1011
- var { isBlob, isValidStatusCode } = require_validation();
1012
- var { mask: applyMask, toBuffer } = require_buffer_util();
1013
- var kByteLength = Symbol("kByteLength");
1014
- var maskBuffer = Buffer.alloc(4);
1015
- var RANDOM_POOL_SIZE = 8 * 1024;
1016
- var randomPool;
1017
- var randomPoolPointer = RANDOM_POOL_SIZE;
1018
- var DEFAULT = 0;
1019
- var DEFLATING = 1;
1020
- var GET_BLOB_DATA = 2;
1021
-
1022
- class Sender {
1023
- constructor(socket, extensions, generateMask) {
1024
- this._extensions = extensions || {};
1025
- if (generateMask) {
1026
- this._generateMask = generateMask;
1027
- this._maskBuffer = Buffer.alloc(4);
1028
- }
1029
- this._socket = socket;
1030
- this._firstFragment = true;
1031
- this._compress = false;
1032
- this._bufferedBytes = 0;
1033
- this._queue = [];
1034
- this._state = DEFAULT;
1035
- this.onerror = NOOP;
1036
- this[kWebSocket] = undefined;
1037
- }
1038
- static frame(data, options) {
1039
- let mask;
1040
- let merge = false;
1041
- let offset = 2;
1042
- let skipMasking = false;
1043
- if (options.mask) {
1044
- mask = options.maskBuffer || maskBuffer;
1045
- if (options.generateMask) {
1046
- options.generateMask(mask);
1047
- } else {
1048
- if (randomPoolPointer === RANDOM_POOL_SIZE) {
1049
- if (randomPool === undefined) {
1050
- randomPool = Buffer.alloc(RANDOM_POOL_SIZE);
1051
- }
1052
- randomFillSync(randomPool, 0, RANDOM_POOL_SIZE);
1053
- randomPoolPointer = 0;
1054
- }
1055
- mask[0] = randomPool[randomPoolPointer++];
1056
- mask[1] = randomPool[randomPoolPointer++];
1057
- mask[2] = randomPool[randomPoolPointer++];
1058
- mask[3] = randomPool[randomPoolPointer++];
1059
- }
1060
- skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0;
1061
- offset = 6;
1062
- }
1063
- let dataLength;
1064
- if (typeof data === "string") {
1065
- if ((!options.mask || skipMasking) && options[kByteLength] !== undefined) {
1066
- dataLength = options[kByteLength];
1067
- } else {
1068
- data = Buffer.from(data);
1069
- dataLength = data.length;
1070
- }
1071
- } else {
1072
- dataLength = data.length;
1073
- merge = options.mask && options.readOnly && !skipMasking;
1074
- }
1075
- let payloadLength = dataLength;
1076
- if (dataLength >= 65536) {
1077
- offset += 8;
1078
- payloadLength = 127;
1079
- } else if (dataLength > 125) {
1080
- offset += 2;
1081
- payloadLength = 126;
1082
- }
1083
- const target = Buffer.allocUnsafe(merge ? dataLength + offset : offset);
1084
- target[0] = options.fin ? options.opcode | 128 : options.opcode;
1085
- if (options.rsv1)
1086
- target[0] |= 64;
1087
- target[1] = payloadLength;
1088
- if (payloadLength === 126) {
1089
- target.writeUInt16BE(dataLength, 2);
1090
- } else if (payloadLength === 127) {
1091
- target[2] = target[3] = 0;
1092
- target.writeUIntBE(dataLength, 4, 6);
1093
- }
1094
- if (!options.mask)
1095
- return [target, data];
1096
- target[1] |= 128;
1097
- target[offset - 4] = mask[0];
1098
- target[offset - 3] = mask[1];
1099
- target[offset - 2] = mask[2];
1100
- target[offset - 1] = mask[3];
1101
- if (skipMasking)
1102
- return [target, data];
1103
- if (merge) {
1104
- applyMask(data, mask, target, offset, dataLength);
1105
- return [target];
1106
- }
1107
- applyMask(data, mask, data, 0, dataLength);
1108
- return [target, data];
1109
- }
1110
- close(code, data, mask, cb) {
1111
- let buf;
1112
- if (code === undefined) {
1113
- buf = EMPTY_BUFFER;
1114
- } else if (typeof code !== "number" || !isValidStatusCode(code)) {
1115
- throw new TypeError("First argument must be a valid error code number");
1116
- } else if (data === undefined || !data.length) {
1117
- buf = Buffer.allocUnsafe(2);
1118
- buf.writeUInt16BE(code, 0);
1119
- } else {
1120
- const length = Buffer.byteLength(data);
1121
- if (length > 123) {
1122
- throw new RangeError("The message must not be greater than 123 bytes");
1123
- }
1124
- buf = Buffer.allocUnsafe(2 + length);
1125
- buf.writeUInt16BE(code, 0);
1126
- if (typeof data === "string") {
1127
- buf.write(data, 2);
1128
- } else {
1129
- buf.set(data, 2);
1130
- }
1131
- }
1132
- const options = {
1133
- [kByteLength]: buf.length,
1134
- fin: true,
1135
- generateMask: this._generateMask,
1136
- mask,
1137
- maskBuffer: this._maskBuffer,
1138
- opcode: 8,
1139
- readOnly: false,
1140
- rsv1: false
1141
- };
1142
- if (this._state !== DEFAULT) {
1143
- this.enqueue([this.dispatch, buf, false, options, cb]);
1144
- } else {
1145
- this.sendFrame(Sender.frame(buf, options), cb);
1146
- }
1147
- }
1148
- ping(data, mask, cb) {
1149
- let byteLength;
1150
- let readOnly;
1151
- if (typeof data === "string") {
1152
- byteLength = Buffer.byteLength(data);
1153
- readOnly = false;
1154
- } else if (isBlob(data)) {
1155
- byteLength = data.size;
1156
- readOnly = false;
1157
- } else {
1158
- data = toBuffer(data);
1159
- byteLength = data.length;
1160
- readOnly = toBuffer.readOnly;
1161
- }
1162
- if (byteLength > 125) {
1163
- throw new RangeError("The data size must not be greater than 125 bytes");
1164
- }
1165
- const options = {
1166
- [kByteLength]: byteLength,
1167
- fin: true,
1168
- generateMask: this._generateMask,
1169
- mask,
1170
- maskBuffer: this._maskBuffer,
1171
- opcode: 9,
1172
- readOnly,
1173
- rsv1: false
1174
- };
1175
- if (isBlob(data)) {
1176
- if (this._state !== DEFAULT) {
1177
- this.enqueue([this.getBlobData, data, false, options, cb]);
1178
- } else {
1179
- this.getBlobData(data, false, options, cb);
1180
- }
1181
- } else if (this._state !== DEFAULT) {
1182
- this.enqueue([this.dispatch, data, false, options, cb]);
1183
- } else {
1184
- this.sendFrame(Sender.frame(data, options), cb);
1185
- }
1186
- }
1187
- pong(data, mask, cb) {
1188
- let byteLength;
1189
- let readOnly;
1190
- if (typeof data === "string") {
1191
- byteLength = Buffer.byteLength(data);
1192
- readOnly = false;
1193
- } else if (isBlob(data)) {
1194
- byteLength = data.size;
1195
- readOnly = false;
1196
- } else {
1197
- data = toBuffer(data);
1198
- byteLength = data.length;
1199
- readOnly = toBuffer.readOnly;
1200
- }
1201
- if (byteLength > 125) {
1202
- throw new RangeError("The data size must not be greater than 125 bytes");
1203
- }
1204
- const options = {
1205
- [kByteLength]: byteLength,
1206
- fin: true,
1207
- generateMask: this._generateMask,
1208
- mask,
1209
- maskBuffer: this._maskBuffer,
1210
- opcode: 10,
1211
- readOnly,
1212
- rsv1: false
1213
- };
1214
- if (isBlob(data)) {
1215
- if (this._state !== DEFAULT) {
1216
- this.enqueue([this.getBlobData, data, false, options, cb]);
1217
- } else {
1218
- this.getBlobData(data, false, options, cb);
1219
- }
1220
- } else if (this._state !== DEFAULT) {
1221
- this.enqueue([this.dispatch, data, false, options, cb]);
1222
- } else {
1223
- this.sendFrame(Sender.frame(data, options), cb);
1224
- }
1225
- }
1226
- send(data, options, cb) {
1227
- const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
1228
- let opcode = options.binary ? 2 : 1;
1229
- let rsv1 = options.compress;
1230
- let byteLength;
1231
- let readOnly;
1232
- if (typeof data === "string") {
1233
- byteLength = Buffer.byteLength(data);
1234
- readOnly = false;
1235
- } else if (isBlob(data)) {
1236
- byteLength = data.size;
1237
- readOnly = false;
1238
- } else {
1239
- data = toBuffer(data);
1240
- byteLength = data.length;
1241
- readOnly = toBuffer.readOnly;
1242
- }
1243
- if (this._firstFragment) {
1244
- this._firstFragment = false;
1245
- if (rsv1 && perMessageDeflate && perMessageDeflate.params[perMessageDeflate._isServer ? "server_no_context_takeover" : "client_no_context_takeover"]) {
1246
- rsv1 = byteLength >= perMessageDeflate._threshold;
1247
- }
1248
- this._compress = rsv1;
1249
- } else {
1250
- rsv1 = false;
1251
- opcode = 0;
1252
- }
1253
- if (options.fin)
1254
- this._firstFragment = true;
1255
- const opts = {
1256
- [kByteLength]: byteLength,
1257
- fin: options.fin,
1258
- generateMask: this._generateMask,
1259
- mask: options.mask,
1260
- maskBuffer: this._maskBuffer,
1261
- opcode,
1262
- readOnly,
1263
- rsv1
1264
- };
1265
- if (isBlob(data)) {
1266
- if (this._state !== DEFAULT) {
1267
- this.enqueue([this.getBlobData, data, this._compress, opts, cb]);
1268
- } else {
1269
- this.getBlobData(data, this._compress, opts, cb);
1270
- }
1271
- } else if (this._state !== DEFAULT) {
1272
- this.enqueue([this.dispatch, data, this._compress, opts, cb]);
1273
- } else {
1274
- this.dispatch(data, this._compress, opts, cb);
1275
- }
1276
- }
1277
- getBlobData(blob, compress, options, cb) {
1278
- this._bufferedBytes += options[kByteLength];
1279
- this._state = GET_BLOB_DATA;
1280
- blob.arrayBuffer().then((arrayBuffer) => {
1281
- if (this._socket.destroyed) {
1282
- const err = new Error("The socket was closed while the blob was being read");
1283
- process.nextTick(callCallbacks, this, err, cb);
1284
- return;
1285
- }
1286
- this._bufferedBytes -= options[kByteLength];
1287
- const data = toBuffer(arrayBuffer);
1288
- if (!compress) {
1289
- this._state = DEFAULT;
1290
- this.sendFrame(Sender.frame(data, options), cb);
1291
- this.dequeue();
1292
- } else {
1293
- this.dispatch(data, compress, options, cb);
1294
- }
1295
- }).catch((err) => {
1296
- process.nextTick(onError, this, err, cb);
1297
- });
1298
- }
1299
- dispatch(data, compress, options, cb) {
1300
- if (!compress) {
1301
- this.sendFrame(Sender.frame(data, options), cb);
1302
- return;
1303
- }
1304
- const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
1305
- this._bufferedBytes += options[kByteLength];
1306
- this._state = DEFLATING;
1307
- perMessageDeflate.compress(data, options.fin, (_, buf) => {
1308
- if (this._socket.destroyed) {
1309
- const err = new Error("The socket was closed while data was being compressed");
1310
- callCallbacks(this, err, cb);
1311
- return;
1312
- }
1313
- this._bufferedBytes -= options[kByteLength];
1314
- this._state = DEFAULT;
1315
- options.readOnly = false;
1316
- this.sendFrame(Sender.frame(buf, options), cb);
1317
- this.dequeue();
1318
- });
1319
- }
1320
- dequeue() {
1321
- while (this._state === DEFAULT && this._queue.length) {
1322
- const params = this._queue.shift();
1323
- this._bufferedBytes -= params[3][kByteLength];
1324
- Reflect.apply(params[0], this, params.slice(1));
1325
- }
1326
- }
1327
- enqueue(params) {
1328
- this._bufferedBytes += params[3][kByteLength];
1329
- this._queue.push(params);
1330
- }
1331
- sendFrame(list, cb) {
1332
- if (list.length === 2) {
1333
- this._socket.cork();
1334
- this._socket.write(list[0]);
1335
- this._socket.write(list[1], cb);
1336
- this._socket.uncork();
1337
- } else {
1338
- this._socket.write(list[0], cb);
1339
- }
1340
- }
1341
- }
1342
- module2.exports = Sender;
1343
- function callCallbacks(sender, err, cb) {
1344
- if (typeof cb === "function")
1345
- cb(err);
1346
- for (let i = 0;i < sender._queue.length; i++) {
1347
- const params = sender._queue[i];
1348
- const callback = params[params.length - 1];
1349
- if (typeof callback === "function")
1350
- callback(err);
1351
- }
1352
- }
1353
- function onError(sender, err, cb) {
1354
- callCallbacks(sender, err, cb);
1355
- sender.onerror(err);
1356
- }
1357
- });
1358
-
1359
- // node_modules/ws/lib/event-target.js
1360
- var require_event_target = __commonJS((exports2, module2) => {
1361
- var { kForOnEventAttribute, kListener } = require_constants();
1362
- var kCode = Symbol("kCode");
1363
- var kData = Symbol("kData");
1364
- var kError = Symbol("kError");
1365
- var kMessage = Symbol("kMessage");
1366
- var kReason = Symbol("kReason");
1367
- var kTarget = Symbol("kTarget");
1368
- var kType = Symbol("kType");
1369
- var kWasClean = Symbol("kWasClean");
1370
-
1371
- class Event {
1372
- constructor(type) {
1373
- this[kTarget] = null;
1374
- this[kType] = type;
1375
- }
1376
- get target() {
1377
- return this[kTarget];
1378
- }
1379
- get type() {
1380
- return this[kType];
1381
- }
1382
- }
1383
- Object.defineProperty(Event.prototype, "target", { enumerable: true });
1384
- Object.defineProperty(Event.prototype, "type", { enumerable: true });
1385
-
1386
- class CloseEvent extends Event {
1387
- constructor(type, options = {}) {
1388
- super(type);
1389
- this[kCode] = options.code === undefined ? 0 : options.code;
1390
- this[kReason] = options.reason === undefined ? "" : options.reason;
1391
- this[kWasClean] = options.wasClean === undefined ? false : options.wasClean;
1392
- }
1393
- get code() {
1394
- return this[kCode];
1395
- }
1396
- get reason() {
1397
- return this[kReason];
1398
- }
1399
- get wasClean() {
1400
- return this[kWasClean];
1401
- }
1402
- }
1403
- Object.defineProperty(CloseEvent.prototype, "code", { enumerable: true });
1404
- Object.defineProperty(CloseEvent.prototype, "reason", { enumerable: true });
1405
- Object.defineProperty(CloseEvent.prototype, "wasClean", { enumerable: true });
1406
-
1407
- class ErrorEvent extends Event {
1408
- constructor(type, options = {}) {
1409
- super(type);
1410
- this[kError] = options.error === undefined ? null : options.error;
1411
- this[kMessage] = options.message === undefined ? "" : options.message;
1412
- }
1413
- get error() {
1414
- return this[kError];
1415
- }
1416
- get message() {
1417
- return this[kMessage];
1418
- }
1419
- }
1420
- Object.defineProperty(ErrorEvent.prototype, "error", { enumerable: true });
1421
- Object.defineProperty(ErrorEvent.prototype, "message", { enumerable: true });
1422
-
1423
- class MessageEvent extends Event {
1424
- constructor(type, options = {}) {
1425
- super(type);
1426
- this[kData] = options.data === undefined ? null : options.data;
1427
- }
1428
- get data() {
1429
- return this[kData];
1430
- }
1431
- }
1432
- Object.defineProperty(MessageEvent.prototype, "data", { enumerable: true });
1433
- var EventTarget = {
1434
- addEventListener(type, handler, options = {}) {
1435
- for (const listener of this.listeners(type)) {
1436
- if (!options[kForOnEventAttribute] && listener[kListener] === handler && !listener[kForOnEventAttribute]) {
1437
- return;
1438
- }
1439
- }
1440
- let wrapper;
1441
- if (type === "message") {
1442
- wrapper = function onMessage(data, isBinary) {
1443
- const event = new MessageEvent("message", {
1444
- data: isBinary ? data : data.toString()
1445
- });
1446
- event[kTarget] = this;
1447
- callListener(handler, this, event);
1448
- };
1449
- } else if (type === "close") {
1450
- wrapper = function onClose(code, message) {
1451
- const event = new CloseEvent("close", {
1452
- code,
1453
- reason: message.toString(),
1454
- wasClean: this._closeFrameReceived && this._closeFrameSent
1455
- });
1456
- event[kTarget] = this;
1457
- callListener(handler, this, event);
1458
- };
1459
- } else if (type === "error") {
1460
- wrapper = function onError(error) {
1461
- const event = new ErrorEvent("error", {
1462
- error,
1463
- message: error.message
1464
- });
1465
- event[kTarget] = this;
1466
- callListener(handler, this, event);
1467
- };
1468
- } else if (type === "open") {
1469
- wrapper = function onOpen() {
1470
- const event = new Event("open");
1471
- event[kTarget] = this;
1472
- callListener(handler, this, event);
1473
- };
1474
- } else {
1475
- return;
1476
- }
1477
- wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute];
1478
- wrapper[kListener] = handler;
1479
- if (options.once) {
1480
- this.once(type, wrapper);
1481
- } else {
1482
- this.on(type, wrapper);
1483
- }
1484
- },
1485
- removeEventListener(type, handler) {
1486
- for (const listener of this.listeners(type)) {
1487
- if (listener[kListener] === handler && !listener[kForOnEventAttribute]) {
1488
- this.removeListener(type, listener);
1489
- break;
1490
- }
1491
- }
1492
- }
1493
- };
1494
- module2.exports = {
1495
- CloseEvent,
1496
- ErrorEvent,
1497
- Event,
1498
- EventTarget,
1499
- MessageEvent
1500
- };
1501
- function callListener(listener, thisArg, event) {
1502
- if (typeof listener === "object" && listener.handleEvent) {
1503
- listener.handleEvent.call(listener, event);
1504
- } else {
1505
- listener.call(thisArg, event);
1506
- }
1507
- }
1508
- });
1509
-
1510
- // node_modules/ws/lib/extension.js
1511
- var require_extension = __commonJS((exports2, module2) => {
1512
- var { tokenChars } = require_validation();
1513
- function push(dest, name, elem) {
1514
- if (dest[name] === undefined)
1515
- dest[name] = [elem];
1516
- else
1517
- dest[name].push(elem);
1518
- }
1519
- function parse(header) {
1520
- const offers = Object.create(null);
1521
- let params = Object.create(null);
1522
- let mustUnescape = false;
1523
- let isEscaping = false;
1524
- let inQuotes = false;
1525
- let extensionName;
1526
- let paramName;
1527
- let start = -1;
1528
- let code = -1;
1529
- let end = -1;
1530
- let i = 0;
1531
- for (;i < header.length; i++) {
1532
- code = header.charCodeAt(i);
1533
- if (extensionName === undefined) {
1534
- if (end === -1 && tokenChars[code] === 1) {
1535
- if (start === -1)
1536
- start = i;
1537
- } else if (i !== 0 && (code === 32 || code === 9)) {
1538
- if (end === -1 && start !== -1)
1539
- end = i;
1540
- } else if (code === 59 || code === 44) {
1541
- if (start === -1) {
1542
- throw new SyntaxError(`Unexpected character at index ${i}`);
1543
- }
1544
- if (end === -1)
1545
- end = i;
1546
- const name = header.slice(start, end);
1547
- if (code === 44) {
1548
- push(offers, name, params);
1549
- params = Object.create(null);
1550
- } else {
1551
- extensionName = name;
1552
- }
1553
- start = end = -1;
1554
- } else {
1555
- throw new SyntaxError(`Unexpected character at index ${i}`);
1556
- }
1557
- } else if (paramName === undefined) {
1558
- if (end === -1 && tokenChars[code] === 1) {
1559
- if (start === -1)
1560
- start = i;
1561
- } else if (code === 32 || code === 9) {
1562
- if (end === -1 && start !== -1)
1563
- end = i;
1564
- } else if (code === 59 || code === 44) {
1565
- if (start === -1) {
1566
- throw new SyntaxError(`Unexpected character at index ${i}`);
1567
- }
1568
- if (end === -1)
1569
- end = i;
1570
- push(params, header.slice(start, end), true);
1571
- if (code === 44) {
1572
- push(offers, extensionName, params);
1573
- params = Object.create(null);
1574
- extensionName = undefined;
1575
- }
1576
- start = end = -1;
1577
- } else if (code === 61 && start !== -1 && end === -1) {
1578
- paramName = header.slice(start, i);
1579
- start = end = -1;
1580
- } else {
1581
- throw new SyntaxError(`Unexpected character at index ${i}`);
1582
- }
1583
- } else {
1584
- if (isEscaping) {
1585
- if (tokenChars[code] !== 1) {
1586
- throw new SyntaxError(`Unexpected character at index ${i}`);
1587
- }
1588
- if (start === -1)
1589
- start = i;
1590
- else if (!mustUnescape)
1591
- mustUnescape = true;
1592
- isEscaping = false;
1593
- } else if (inQuotes) {
1594
- if (tokenChars[code] === 1) {
1595
- if (start === -1)
1596
- start = i;
1597
- } else if (code === 34 && start !== -1) {
1598
- inQuotes = false;
1599
- end = i;
1600
- } else if (code === 92) {
1601
- isEscaping = true;
1602
- } else {
1603
- throw new SyntaxError(`Unexpected character at index ${i}`);
1604
- }
1605
- } else if (code === 34 && header.charCodeAt(i - 1) === 61) {
1606
- inQuotes = true;
1607
- } else if (end === -1 && tokenChars[code] === 1) {
1608
- if (start === -1)
1609
- start = i;
1610
- } else if (start !== -1 && (code === 32 || code === 9)) {
1611
- if (end === -1)
1612
- end = i;
1613
- } else if (code === 59 || code === 44) {
1614
- if (start === -1) {
1615
- throw new SyntaxError(`Unexpected character at index ${i}`);
1616
- }
1617
- if (end === -1)
1618
- end = i;
1619
- let value = header.slice(start, end);
1620
- if (mustUnescape) {
1621
- value = value.replace(/\\/g, "");
1622
- mustUnescape = false;
1623
- }
1624
- push(params, paramName, value);
1625
- if (code === 44) {
1626
- push(offers, extensionName, params);
1627
- params = Object.create(null);
1628
- extensionName = undefined;
1629
- }
1630
- paramName = undefined;
1631
- start = end = -1;
1632
- } else {
1633
- throw new SyntaxError(`Unexpected character at index ${i}`);
1634
- }
1635
- }
1636
- }
1637
- if (start === -1 || inQuotes || code === 32 || code === 9) {
1638
- throw new SyntaxError("Unexpected end of input");
1639
- }
1640
- if (end === -1)
1641
- end = i;
1642
- const token = header.slice(start, end);
1643
- if (extensionName === undefined) {
1644
- push(offers, token, params);
1645
- } else {
1646
- if (paramName === undefined) {
1647
- push(params, token, true);
1648
- } else if (mustUnescape) {
1649
- push(params, paramName, token.replace(/\\/g, ""));
1650
- } else {
1651
- push(params, paramName, token);
1652
- }
1653
- push(offers, extensionName, params);
1654
- }
1655
- return offers;
1656
- }
1657
- function format(extensions) {
1658
- return Object.keys(extensions).map((extension) => {
1659
- let configurations = extensions[extension];
1660
- if (!Array.isArray(configurations))
1661
- configurations = [configurations];
1662
- return configurations.map((params) => {
1663
- return [extension].concat(Object.keys(params).map((k) => {
1664
- let values = params[k];
1665
- if (!Array.isArray(values))
1666
- values = [values];
1667
- return values.map((v) => v === true ? k : `${k}=${v}`).join("; ");
1668
- })).join("; ");
1669
- }).join(", ");
1670
- }).join(", ");
1671
- }
1672
- module2.exports = { format, parse };
1673
- });
1674
-
1675
- // node_modules/ws/lib/websocket.js
1676
- var require_websocket = __commonJS((exports2, module2) => {
1677
- var EventEmitter = require("events");
1678
- var https = require("https");
1679
- var http = require("http");
1680
- var net = require("net");
1681
- var tls = require("tls");
1682
- var { randomBytes, createHash } = require("crypto");
1683
- var { Duplex, Readable } = require("stream");
1684
- var { URL } = require("url");
1685
- var PerMessageDeflate = require_permessage_deflate();
1686
- var Receiver = require_receiver();
1687
- var Sender = require_sender();
1688
- var { isBlob } = require_validation();
1689
- var {
1690
- BINARY_TYPES,
1691
- CLOSE_TIMEOUT,
1692
- EMPTY_BUFFER,
1693
- GUID,
1694
- kForOnEventAttribute,
1695
- kListener,
1696
- kStatusCode,
1697
- kWebSocket,
1698
- NOOP
1699
- } = require_constants();
1700
- var {
1701
- EventTarget: { addEventListener, removeEventListener }
1702
- } = require_event_target();
1703
- var { format, parse } = require_extension();
1704
- var { toBuffer } = require_buffer_util();
1705
- var kAborted = Symbol("kAborted");
1706
- var protocolVersions = [8, 13];
1707
- var readyStates = ["CONNECTING", "OPEN", "CLOSING", "CLOSED"];
1708
- var subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;
1709
-
1710
- class WebSocket extends EventEmitter {
1711
- constructor(address, protocols, options) {
1712
- super();
1713
- this._binaryType = BINARY_TYPES[0];
1714
- this._closeCode = 1006;
1715
- this._closeFrameReceived = false;
1716
- this._closeFrameSent = false;
1717
- this._closeMessage = EMPTY_BUFFER;
1718
- this._closeTimer = null;
1719
- this._errorEmitted = false;
1720
- this._extensions = {};
1721
- this._paused = false;
1722
- this._protocol = "";
1723
- this._readyState = WebSocket.CONNECTING;
1724
- this._receiver = null;
1725
- this._sender = null;
1726
- this._socket = null;
1727
- if (address !== null) {
1728
- this._bufferedAmount = 0;
1729
- this._isServer = false;
1730
- this._redirects = 0;
1731
- if (protocols === undefined) {
1732
- protocols = [];
1733
- } else if (!Array.isArray(protocols)) {
1734
- if (typeof protocols === "object" && protocols !== null) {
1735
- options = protocols;
1736
- protocols = [];
1737
- } else {
1738
- protocols = [protocols];
1739
- }
1740
- }
1741
- initAsClient(this, address, protocols, options);
1742
- } else {
1743
- this._autoPong = options.autoPong;
1744
- this._closeTimeout = options.closeTimeout;
1745
- this._isServer = true;
1746
- }
1747
- }
1748
- get binaryType() {
1749
- return this._binaryType;
1750
- }
1751
- set binaryType(type) {
1752
- if (!BINARY_TYPES.includes(type))
1753
- return;
1754
- this._binaryType = type;
1755
- if (this._receiver)
1756
- this._receiver._binaryType = type;
1757
- }
1758
- get bufferedAmount() {
1759
- if (!this._socket)
1760
- return this._bufferedAmount;
1761
- return this._socket._writableState.length + this._sender._bufferedBytes;
1762
- }
1763
- get extensions() {
1764
- return Object.keys(this._extensions).join();
1765
- }
1766
- get isPaused() {
1767
- return this._paused;
1768
- }
1769
- get onclose() {
1770
- return null;
1771
- }
1772
- get onerror() {
1773
- return null;
1774
- }
1775
- get onopen() {
1776
- return null;
1777
- }
1778
- get onmessage() {
1779
- return null;
1780
- }
1781
- get protocol() {
1782
- return this._protocol;
1783
- }
1784
- get readyState() {
1785
- return this._readyState;
1786
- }
1787
- get url() {
1788
- return this._url;
1789
- }
1790
- setSocket(socket, head, options) {
1791
- const receiver = new Receiver({
1792
- allowSynchronousEvents: options.allowSynchronousEvents,
1793
- binaryType: this.binaryType,
1794
- extensions: this._extensions,
1795
- isServer: this._isServer,
1796
- maxPayload: options.maxPayload,
1797
- skipUTF8Validation: options.skipUTF8Validation
1798
- });
1799
- const sender = new Sender(socket, this._extensions, options.generateMask);
1800
- this._receiver = receiver;
1801
- this._sender = sender;
1802
- this._socket = socket;
1803
- receiver[kWebSocket] = this;
1804
- sender[kWebSocket] = this;
1805
- socket[kWebSocket] = this;
1806
- receiver.on("conclude", receiverOnConclude);
1807
- receiver.on("drain", receiverOnDrain);
1808
- receiver.on("error", receiverOnError);
1809
- receiver.on("message", receiverOnMessage);
1810
- receiver.on("ping", receiverOnPing);
1811
- receiver.on("pong", receiverOnPong);
1812
- sender.onerror = senderOnError;
1813
- if (socket.setTimeout)
1814
- socket.setTimeout(0);
1815
- if (socket.setNoDelay)
1816
- socket.setNoDelay();
1817
- if (head.length > 0)
1818
- socket.unshift(head);
1819
- socket.on("close", socketOnClose);
1820
- socket.on("data", socketOnData);
1821
- socket.on("end", socketOnEnd);
1822
- socket.on("error", socketOnError);
1823
- this._readyState = WebSocket.OPEN;
1824
- this.emit("open");
1825
- }
1826
- emitClose() {
1827
- if (!this._socket) {
1828
- this._readyState = WebSocket.CLOSED;
1829
- this.emit("close", this._closeCode, this._closeMessage);
1830
- return;
1831
- }
1832
- if (this._extensions[PerMessageDeflate.extensionName]) {
1833
- this._extensions[PerMessageDeflate.extensionName].cleanup();
1834
- }
1835
- this._receiver.removeAllListeners();
1836
- this._readyState = WebSocket.CLOSED;
1837
- this.emit("close", this._closeCode, this._closeMessage);
1838
- }
1839
- close(code, data) {
1840
- if (this.readyState === WebSocket.CLOSED)
1841
- return;
1842
- if (this.readyState === WebSocket.CONNECTING) {
1843
- const msg = "WebSocket was closed before the connection was established";
1844
- abortHandshake(this, this._req, msg);
1845
- return;
1846
- }
1847
- if (this.readyState === WebSocket.CLOSING) {
1848
- if (this._closeFrameSent && (this._closeFrameReceived || this._receiver._writableState.errorEmitted)) {
1849
- this._socket.end();
1850
- }
1851
- return;
1852
- }
1853
- this._readyState = WebSocket.CLOSING;
1854
- this._sender.close(code, data, !this._isServer, (err) => {
1855
- if (err)
1856
- return;
1857
- this._closeFrameSent = true;
1858
- if (this._closeFrameReceived || this._receiver._writableState.errorEmitted) {
1859
- this._socket.end();
1860
- }
1861
- });
1862
- setCloseTimer(this);
1863
- }
1864
- pause() {
1865
- if (this.readyState === WebSocket.CONNECTING || this.readyState === WebSocket.CLOSED) {
1866
- return;
1867
- }
1868
- this._paused = true;
1869
- this._socket.pause();
1870
- }
1871
- ping(data, mask, cb) {
1872
- if (this.readyState === WebSocket.CONNECTING) {
1873
- throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
1874
- }
1875
- if (typeof data === "function") {
1876
- cb = data;
1877
- data = mask = undefined;
1878
- } else if (typeof mask === "function") {
1879
- cb = mask;
1880
- mask = undefined;
1881
- }
1882
- if (typeof data === "number")
1883
- data = data.toString();
1884
- if (this.readyState !== WebSocket.OPEN) {
1885
- sendAfterClose(this, data, cb);
1886
- return;
1887
- }
1888
- if (mask === undefined)
1889
- mask = !this._isServer;
1890
- this._sender.ping(data || EMPTY_BUFFER, mask, cb);
1891
- }
1892
- pong(data, mask, cb) {
1893
- if (this.readyState === WebSocket.CONNECTING) {
1894
- throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
1895
- }
1896
- if (typeof data === "function") {
1897
- cb = data;
1898
- data = mask = undefined;
1899
- } else if (typeof mask === "function") {
1900
- cb = mask;
1901
- mask = undefined;
1902
- }
1903
- if (typeof data === "number")
1904
- data = data.toString();
1905
- if (this.readyState !== WebSocket.OPEN) {
1906
- sendAfterClose(this, data, cb);
1907
- return;
1908
- }
1909
- if (mask === undefined)
1910
- mask = !this._isServer;
1911
- this._sender.pong(data || EMPTY_BUFFER, mask, cb);
1912
- }
1913
- resume() {
1914
- if (this.readyState === WebSocket.CONNECTING || this.readyState === WebSocket.CLOSED) {
1915
- return;
1916
- }
1917
- this._paused = false;
1918
- if (!this._receiver._writableState.needDrain)
1919
- this._socket.resume();
1920
- }
1921
- send(data, options, cb) {
1922
- if (this.readyState === WebSocket.CONNECTING) {
1923
- throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
1924
- }
1925
- if (typeof options === "function") {
1926
- cb = options;
1927
- options = {};
1928
- }
1929
- if (typeof data === "number")
1930
- data = data.toString();
1931
- if (this.readyState !== WebSocket.OPEN) {
1932
- sendAfterClose(this, data, cb);
1933
- return;
1934
- }
1935
- const opts = {
1936
- binary: typeof data !== "string",
1937
- mask: !this._isServer,
1938
- compress: true,
1939
- fin: true,
1940
- ...options
1941
- };
1942
- if (!this._extensions[PerMessageDeflate.extensionName]) {
1943
- opts.compress = false;
1944
- }
1945
- this._sender.send(data || EMPTY_BUFFER, opts, cb);
1946
- }
1947
- terminate() {
1948
- if (this.readyState === WebSocket.CLOSED)
1949
- return;
1950
- if (this.readyState === WebSocket.CONNECTING) {
1951
- const msg = "WebSocket was closed before the connection was established";
1952
- abortHandshake(this, this._req, msg);
1953
- return;
1954
- }
1955
- if (this._socket) {
1956
- this._readyState = WebSocket.CLOSING;
1957
- this._socket.destroy();
1958
- }
1959
- }
1960
- }
1961
- Object.defineProperty(WebSocket, "CONNECTING", {
1962
- enumerable: true,
1963
- value: readyStates.indexOf("CONNECTING")
1964
- });
1965
- Object.defineProperty(WebSocket.prototype, "CONNECTING", {
1966
- enumerable: true,
1967
- value: readyStates.indexOf("CONNECTING")
1968
- });
1969
- Object.defineProperty(WebSocket, "OPEN", {
1970
- enumerable: true,
1971
- value: readyStates.indexOf("OPEN")
1972
- });
1973
- Object.defineProperty(WebSocket.prototype, "OPEN", {
1974
- enumerable: true,
1975
- value: readyStates.indexOf("OPEN")
1976
- });
1977
- Object.defineProperty(WebSocket, "CLOSING", {
1978
- enumerable: true,
1979
- value: readyStates.indexOf("CLOSING")
1980
- });
1981
- Object.defineProperty(WebSocket.prototype, "CLOSING", {
1982
- enumerable: true,
1983
- value: readyStates.indexOf("CLOSING")
1984
- });
1985
- Object.defineProperty(WebSocket, "CLOSED", {
1986
- enumerable: true,
1987
- value: readyStates.indexOf("CLOSED")
1988
- });
1989
- Object.defineProperty(WebSocket.prototype, "CLOSED", {
1990
- enumerable: true,
1991
- value: readyStates.indexOf("CLOSED")
1992
- });
1993
- [
1994
- "binaryType",
1995
- "bufferedAmount",
1996
- "extensions",
1997
- "isPaused",
1998
- "protocol",
1999
- "readyState",
2000
- "url"
2001
- ].forEach((property) => {
2002
- Object.defineProperty(WebSocket.prototype, property, { enumerable: true });
2003
- });
2004
- ["open", "error", "close", "message"].forEach((method) => {
2005
- Object.defineProperty(WebSocket.prototype, `on${method}`, {
5
+ var __moduleCache = /* @__PURE__ */ new WeakMap;
6
+ var __toCommonJS = (from) => {
7
+ var entry = __moduleCache.get(from), desc;
8
+ if (entry)
9
+ return entry;
10
+ entry = __defProp({}, "__esModule", { value: true });
11
+ if (from && typeof from === "object" || typeof from === "function")
12
+ __getOwnPropNames(from).map((key) => !__hasOwnProp.call(entry, key) && __defProp(entry, key, {
13
+ get: () => from[key],
14
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
15
+ }));
16
+ __moduleCache.set(from, entry);
17
+ return entry;
18
+ };
19
+ var __export = (target, all) => {
20
+ for (var name in all)
21
+ __defProp(target, name, {
22
+ get: all[name],
2006
23
  enumerable: true,
2007
- get() {
2008
- for (const listener of this.listeners(method)) {
2009
- if (listener[kForOnEventAttribute])
2010
- return listener[kListener];
2011
- }
2012
- return null;
2013
- },
2014
- set(handler) {
2015
- for (const listener of this.listeners(method)) {
2016
- if (listener[kForOnEventAttribute]) {
2017
- this.removeListener(method, listener);
2018
- break;
2019
- }
2020
- }
2021
- if (typeof handler !== "function")
2022
- return;
2023
- this.addEventListener(method, handler, {
2024
- [kForOnEventAttribute]: true
2025
- });
2026
- }
2027
- });
2028
- });
2029
- WebSocket.prototype.addEventListener = addEventListener;
2030
- WebSocket.prototype.removeEventListener = removeEventListener;
2031
- module2.exports = WebSocket;
2032
- function initAsClient(websocket, address, protocols, options) {
2033
- const opts = {
2034
- allowSynchronousEvents: true,
2035
- autoPong: true,
2036
- closeTimeout: CLOSE_TIMEOUT,
2037
- protocolVersion: protocolVersions[1],
2038
- maxPayload: 100 * 1024 * 1024,
2039
- skipUTF8Validation: false,
2040
- perMessageDeflate: true,
2041
- followRedirects: false,
2042
- maxRedirects: 10,
2043
- ...options,
2044
- socketPath: undefined,
2045
- hostname: undefined,
2046
- protocol: undefined,
2047
- timeout: undefined,
2048
- method: "GET",
2049
- host: undefined,
2050
- path: undefined,
2051
- port: undefined
2052
- };
2053
- websocket._autoPong = opts.autoPong;
2054
- websocket._closeTimeout = opts.closeTimeout;
2055
- if (!protocolVersions.includes(opts.protocolVersion)) {
2056
- throw new RangeError(`Unsupported protocol version: ${opts.protocolVersion} ` + `(supported versions: ${protocolVersions.join(", ")})`);
2057
- }
2058
- let parsedUrl;
2059
- if (address instanceof URL) {
2060
- parsedUrl = address;
2061
- } else {
2062
- try {
2063
- parsedUrl = new URL(address);
2064
- } catch (e) {
2065
- throw new SyntaxError(`Invalid URL: ${address}`);
2066
- }
2067
- }
2068
- if (parsedUrl.protocol === "http:") {
2069
- parsedUrl.protocol = "ws:";
2070
- } else if (parsedUrl.protocol === "https:") {
2071
- parsedUrl.protocol = "wss:";
2072
- }
2073
- websocket._url = parsedUrl.href;
2074
- const isSecure = parsedUrl.protocol === "wss:";
2075
- const isIpcUrl = parsedUrl.protocol === "ws+unix:";
2076
- let invalidUrlMessage;
2077
- if (parsedUrl.protocol !== "ws:" && !isSecure && !isIpcUrl) {
2078
- invalidUrlMessage = `The URL's protocol must be one of "ws:", "wss:", ` + '"http:", "https:", or "ws+unix:"';
2079
- } else if (isIpcUrl && !parsedUrl.pathname) {
2080
- invalidUrlMessage = "The URL's pathname is empty";
2081
- } else if (parsedUrl.hash) {
2082
- invalidUrlMessage = "The URL contains a fragment identifier";
2083
- }
2084
- if (invalidUrlMessage) {
2085
- const err = new SyntaxError(invalidUrlMessage);
2086
- if (websocket._redirects === 0) {
2087
- throw err;
2088
- } else {
2089
- emitErrorAndClose(websocket, err);
2090
- return;
2091
- }
2092
- }
2093
- const defaultPort = isSecure ? 443 : 80;
2094
- const key = randomBytes(16).toString("base64");
2095
- const request = isSecure ? https.request : http.request;
2096
- const protocolSet = new Set;
2097
- let perMessageDeflate;
2098
- opts.createConnection = opts.createConnection || (isSecure ? tlsConnect : netConnect);
2099
- opts.defaultPort = opts.defaultPort || defaultPort;
2100
- opts.port = parsedUrl.port || defaultPort;
2101
- opts.host = parsedUrl.hostname.startsWith("[") ? parsedUrl.hostname.slice(1, -1) : parsedUrl.hostname;
2102
- opts.headers = {
2103
- ...opts.headers,
2104
- "Sec-WebSocket-Version": opts.protocolVersion,
2105
- "Sec-WebSocket-Key": key,
2106
- Connection: "Upgrade",
2107
- Upgrade: "websocket"
2108
- };
2109
- opts.path = parsedUrl.pathname + parsedUrl.search;
2110
- opts.timeout = opts.handshakeTimeout;
2111
- if (opts.perMessageDeflate) {
2112
- perMessageDeflate = new PerMessageDeflate(opts.perMessageDeflate !== true ? opts.perMessageDeflate : {}, false, opts.maxPayload);
2113
- opts.headers["Sec-WebSocket-Extensions"] = format({
2114
- [PerMessageDeflate.extensionName]: perMessageDeflate.offer()
2115
- });
2116
- }
2117
- if (protocols.length) {
2118
- for (const protocol of protocols) {
2119
- if (typeof protocol !== "string" || !subprotocolRegex.test(protocol) || protocolSet.has(protocol)) {
2120
- throw new SyntaxError("An invalid or duplicated subprotocol was specified");
2121
- }
2122
- protocolSet.add(protocol);
2123
- }
2124
- opts.headers["Sec-WebSocket-Protocol"] = protocols.join(",");
2125
- }
2126
- if (opts.origin) {
2127
- if (opts.protocolVersion < 13) {
2128
- opts.headers["Sec-WebSocket-Origin"] = opts.origin;
2129
- } else {
2130
- opts.headers.Origin = opts.origin;
2131
- }
2132
- }
2133
- if (parsedUrl.username || parsedUrl.password) {
2134
- opts.auth = `${parsedUrl.username}:${parsedUrl.password}`;
2135
- }
2136
- if (isIpcUrl) {
2137
- const parts = opts.path.split(":");
2138
- opts.socketPath = parts[0];
2139
- opts.path = parts[1];
2140
- }
2141
- let req;
2142
- if (opts.followRedirects) {
2143
- if (websocket._redirects === 0) {
2144
- websocket._originalIpc = isIpcUrl;
2145
- websocket._originalSecure = isSecure;
2146
- websocket._originalHostOrSocketPath = isIpcUrl ? opts.socketPath : parsedUrl.host;
2147
- const headers = options && options.headers;
2148
- options = { ...options, headers: {} };
2149
- if (headers) {
2150
- for (const [key2, value] of Object.entries(headers)) {
2151
- options.headers[key2.toLowerCase()] = value;
2152
- }
2153
- }
2154
- } else if (websocket.listenerCount("redirect") === 0) {
2155
- const isSameHost = isIpcUrl ? websocket._originalIpc ? opts.socketPath === websocket._originalHostOrSocketPath : false : websocket._originalIpc ? false : parsedUrl.host === websocket._originalHostOrSocketPath;
2156
- if (!isSameHost || websocket._originalSecure && !isSecure) {
2157
- delete opts.headers.authorization;
2158
- delete opts.headers.cookie;
2159
- if (!isSameHost)
2160
- delete opts.headers.host;
2161
- opts.auth = undefined;
2162
- }
2163
- }
2164
- if (opts.auth && !options.headers.authorization) {
2165
- options.headers.authorization = "Basic " + Buffer.from(opts.auth).toString("base64");
2166
- }
2167
- req = websocket._req = request(opts);
2168
- if (websocket._redirects) {
2169
- websocket.emit("redirect", websocket.url, req);
2170
- }
2171
- } else {
2172
- req = websocket._req = request(opts);
2173
- }
2174
- if (opts.timeout) {
2175
- req.on("timeout", () => {
2176
- abortHandshake(websocket, req, "Opening handshake has timed out");
2177
- });
2178
- }
2179
- req.on("error", (err) => {
2180
- if (req === null || req[kAborted])
2181
- return;
2182
- req = websocket._req = null;
2183
- emitErrorAndClose(websocket, err);
2184
- });
2185
- req.on("response", (res) => {
2186
- const location = res.headers.location;
2187
- const statusCode = res.statusCode;
2188
- if (location && opts.followRedirects && statusCode >= 300 && statusCode < 400) {
2189
- if (++websocket._redirects > opts.maxRedirects) {
2190
- abortHandshake(websocket, req, "Maximum redirects exceeded");
2191
- return;
2192
- }
2193
- req.abort();
2194
- let addr;
2195
- try {
2196
- addr = new URL(location, address);
2197
- } catch (e) {
2198
- const err = new SyntaxError(`Invalid URL: ${location}`);
2199
- emitErrorAndClose(websocket, err);
2200
- return;
2201
- }
2202
- initAsClient(websocket, addr, protocols, options);
2203
- } else if (!websocket.emit("unexpected-response", req, res)) {
2204
- abortHandshake(websocket, req, `Unexpected server response: ${res.statusCode}`);
2205
- }
2206
- });
2207
- req.on("upgrade", (res, socket, head) => {
2208
- websocket.emit("upgrade", res);
2209
- if (websocket.readyState !== WebSocket.CONNECTING)
2210
- return;
2211
- req = websocket._req = null;
2212
- const upgrade = res.headers.upgrade;
2213
- if (upgrade === undefined || upgrade.toLowerCase() !== "websocket") {
2214
- abortHandshake(websocket, socket, "Invalid Upgrade header");
2215
- return;
2216
- }
2217
- const digest = createHash("sha1").update(key + GUID).digest("base64");
2218
- if (res.headers["sec-websocket-accept"] !== digest) {
2219
- abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
2220
- return;
2221
- }
2222
- const serverProt = res.headers["sec-websocket-protocol"];
2223
- let protError;
2224
- if (serverProt !== undefined) {
2225
- if (!protocolSet.size) {
2226
- protError = "Server sent a subprotocol but none was requested";
2227
- } else if (!protocolSet.has(serverProt)) {
2228
- protError = "Server sent an invalid subprotocol";
2229
- }
2230
- } else if (protocolSet.size) {
2231
- protError = "Server sent no subprotocol";
2232
- }
2233
- if (protError) {
2234
- abortHandshake(websocket, socket, protError);
2235
- return;
2236
- }
2237
- if (serverProt)
2238
- websocket._protocol = serverProt;
2239
- const secWebSocketExtensions = res.headers["sec-websocket-extensions"];
2240
- if (secWebSocketExtensions !== undefined) {
2241
- if (!perMessageDeflate) {
2242
- const message = "Server sent a Sec-WebSocket-Extensions header but no extension " + "was requested";
2243
- abortHandshake(websocket, socket, message);
2244
- return;
2245
- }
2246
- let extensions;
2247
- try {
2248
- extensions = parse(secWebSocketExtensions);
2249
- } catch (err) {
2250
- const message = "Invalid Sec-WebSocket-Extensions header";
2251
- abortHandshake(websocket, socket, message);
2252
- return;
2253
- }
2254
- const extensionNames = Object.keys(extensions);
2255
- if (extensionNames.length !== 1 || extensionNames[0] !== PerMessageDeflate.extensionName) {
2256
- const message = "Server indicated an extension that was not requested";
2257
- abortHandshake(websocket, socket, message);
2258
- return;
2259
- }
2260
- try {
2261
- perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName]);
2262
- } catch (err) {
2263
- const message = "Invalid Sec-WebSocket-Extensions header";
2264
- abortHandshake(websocket, socket, message);
2265
- return;
2266
- }
2267
- websocket._extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
2268
- }
2269
- websocket.setSocket(socket, head, {
2270
- allowSynchronousEvents: opts.allowSynchronousEvents,
2271
- generateMask: opts.generateMask,
2272
- maxPayload: opts.maxPayload,
2273
- skipUTF8Validation: opts.skipUTF8Validation
2274
- });
2275
- });
2276
- if (opts.finishRequest) {
2277
- opts.finishRequest(req, websocket);
2278
- } else {
2279
- req.end();
2280
- }
2281
- }
2282
- function emitErrorAndClose(websocket, err) {
2283
- websocket._readyState = WebSocket.CLOSING;
2284
- websocket._errorEmitted = true;
2285
- websocket.emit("error", err);
2286
- websocket.emitClose();
2287
- }
2288
- function netConnect(options) {
2289
- options.path = options.socketPath;
2290
- return net.connect(options);
2291
- }
2292
- function tlsConnect(options) {
2293
- options.path = undefined;
2294
- if (!options.servername && options.servername !== "") {
2295
- options.servername = net.isIP(options.host) ? "" : options.host;
2296
- }
2297
- return tls.connect(options);
2298
- }
2299
- function abortHandshake(websocket, stream, message) {
2300
- websocket._readyState = WebSocket.CLOSING;
2301
- const err = new Error(message);
2302
- Error.captureStackTrace(err, abortHandshake);
2303
- if (stream.setHeader) {
2304
- stream[kAborted] = true;
2305
- stream.abort();
2306
- if (stream.socket && !stream.socket.destroyed) {
2307
- stream.socket.destroy();
2308
- }
2309
- process.nextTick(emitErrorAndClose, websocket, err);
2310
- } else {
2311
- stream.destroy(err);
2312
- stream.once("error", websocket.emit.bind(websocket, "error"));
2313
- stream.once("close", websocket.emitClose.bind(websocket));
2314
- }
2315
- }
2316
- function sendAfterClose(websocket, data, cb) {
2317
- if (data) {
2318
- const length = isBlob(data) ? data.size : toBuffer(data).length;
2319
- if (websocket._socket)
2320
- websocket._sender._bufferedBytes += length;
2321
- else
2322
- websocket._bufferedAmount += length;
2323
- }
2324
- if (cb) {
2325
- const err = new Error(`WebSocket is not open: readyState ${websocket.readyState} ` + `(${readyStates[websocket.readyState]})`);
2326
- process.nextTick(cb, err);
2327
- }
2328
- }
2329
- function receiverOnConclude(code, reason) {
2330
- const websocket = this[kWebSocket];
2331
- websocket._closeFrameReceived = true;
2332
- websocket._closeMessage = reason;
2333
- websocket._closeCode = code;
2334
- if (websocket._socket[kWebSocket] === undefined)
2335
- return;
2336
- websocket._socket.removeListener("data", socketOnData);
2337
- process.nextTick(resume, websocket._socket);
2338
- if (code === 1005)
2339
- websocket.close();
2340
- else
2341
- websocket.close(code, reason);
2342
- }
2343
- function receiverOnDrain() {
2344
- const websocket = this[kWebSocket];
2345
- if (!websocket.isPaused)
2346
- websocket._socket.resume();
2347
- }
2348
- function receiverOnError(err) {
2349
- const websocket = this[kWebSocket];
2350
- if (websocket._socket[kWebSocket] !== undefined) {
2351
- websocket._socket.removeListener("data", socketOnData);
2352
- process.nextTick(resume, websocket._socket);
2353
- websocket.close(err[kStatusCode]);
2354
- }
2355
- if (!websocket._errorEmitted) {
2356
- websocket._errorEmitted = true;
2357
- websocket.emit("error", err);
2358
- }
2359
- }
2360
- function receiverOnFinish() {
2361
- this[kWebSocket].emitClose();
2362
- }
2363
- function receiverOnMessage(data, isBinary) {
2364
- this[kWebSocket].emit("message", data, isBinary);
2365
- }
2366
- function receiverOnPing(data) {
2367
- const websocket = this[kWebSocket];
2368
- if (websocket._autoPong)
2369
- websocket.pong(data, !this._isServer, NOOP);
2370
- websocket.emit("ping", data);
2371
- }
2372
- function receiverOnPong(data) {
2373
- this[kWebSocket].emit("pong", data);
2374
- }
2375
- function resume(stream) {
2376
- stream.resume();
2377
- }
2378
- function senderOnError(err) {
2379
- const websocket = this[kWebSocket];
2380
- if (websocket.readyState === WebSocket.CLOSED)
2381
- return;
2382
- if (websocket.readyState === WebSocket.OPEN) {
2383
- websocket._readyState = WebSocket.CLOSING;
2384
- setCloseTimer(websocket);
2385
- }
2386
- this._socket.end();
2387
- if (!websocket._errorEmitted) {
2388
- websocket._errorEmitted = true;
2389
- websocket.emit("error", err);
2390
- }
2391
- }
2392
- function setCloseTimer(websocket) {
2393
- websocket._closeTimer = setTimeout(websocket._socket.destroy.bind(websocket._socket), websocket._closeTimeout);
2394
- }
2395
- function socketOnClose() {
2396
- const websocket = this[kWebSocket];
2397
- this.removeListener("close", socketOnClose);
2398
- this.removeListener("data", socketOnData);
2399
- this.removeListener("end", socketOnEnd);
2400
- websocket._readyState = WebSocket.CLOSING;
2401
- if (!this._readableState.endEmitted && !websocket._closeFrameReceived && !websocket._receiver._writableState.errorEmitted && this._readableState.length !== 0) {
2402
- const chunk = this.read(this._readableState.length);
2403
- websocket._receiver.write(chunk);
2404
- }
2405
- websocket._receiver.end();
2406
- this[kWebSocket] = undefined;
2407
- clearTimeout(websocket._closeTimer);
2408
- if (websocket._receiver._writableState.finished || websocket._receiver._writableState.errorEmitted) {
2409
- websocket.emitClose();
2410
- } else {
2411
- websocket._receiver.on("error", receiverOnFinish);
2412
- websocket._receiver.on("finish", receiverOnFinish);
2413
- }
2414
- }
2415
- function socketOnData(chunk) {
2416
- if (!this[kWebSocket]._receiver.write(chunk)) {
2417
- this.pause();
2418
- }
2419
- }
2420
- function socketOnEnd() {
2421
- const websocket = this[kWebSocket];
2422
- websocket._readyState = WebSocket.CLOSING;
2423
- websocket._receiver.end();
2424
- this.end();
2425
- }
2426
- function socketOnError() {
2427
- const websocket = this[kWebSocket];
2428
- this.removeListener("error", socketOnError);
2429
- this.on("error", NOOP);
2430
- if (websocket) {
2431
- websocket._readyState = WebSocket.CLOSING;
2432
- this.destroy();
2433
- }
2434
- }
2435
- });
2436
-
2437
- // node_modules/ws/lib/stream.js
2438
- var require_stream = __commonJS((exports2, module2) => {
2439
- var WebSocket = require_websocket();
2440
- var { Duplex } = require("stream");
2441
- function emitClose(stream) {
2442
- stream.emit("close");
2443
- }
2444
- function duplexOnEnd() {
2445
- if (!this.destroyed && this._writableState.finished) {
2446
- this.destroy();
2447
- }
2448
- }
2449
- function duplexOnError(err) {
2450
- this.removeListener("error", duplexOnError);
2451
- this.destroy();
2452
- if (this.listenerCount("error") === 0) {
2453
- this.emit("error", err);
2454
- }
2455
- }
2456
- function createWebSocketStream(ws, options) {
2457
- let terminateOnDestroy = true;
2458
- const duplex = new Duplex({
2459
- ...options,
2460
- autoDestroy: false,
2461
- emitClose: false,
2462
- objectMode: false,
2463
- writableObjectMode: false
2464
- });
2465
- ws.on("message", function message(msg, isBinary) {
2466
- const data = !isBinary && duplex._readableState.objectMode ? msg.toString() : msg;
2467
- if (!duplex.push(data))
2468
- ws.pause();
2469
- });
2470
- ws.once("error", function error(err) {
2471
- if (duplex.destroyed)
2472
- return;
2473
- terminateOnDestroy = false;
2474
- duplex.destroy(err);
2475
- });
2476
- ws.once("close", function close() {
2477
- if (duplex.destroyed)
2478
- return;
2479
- duplex.push(null);
24
+ configurable: true,
25
+ set: (newValue) => all[name] = () => newValue
2480
26
  });
2481
- duplex._destroy = function(err, callback) {
2482
- if (ws.readyState === ws.CLOSED) {
2483
- callback(err);
2484
- process.nextTick(emitClose, duplex);
2485
- return;
2486
- }
2487
- let called = false;
2488
- ws.once("error", function error(err2) {
2489
- called = true;
2490
- callback(err2);
2491
- });
2492
- ws.once("close", function close() {
2493
- if (!called)
2494
- callback(err);
2495
- process.nextTick(emitClose, duplex);
2496
- });
2497
- if (terminateOnDestroy)
2498
- ws.terminate();
2499
- };
2500
- duplex._final = function(callback) {
2501
- if (ws.readyState === ws.CONNECTING) {
2502
- ws.once("open", function open() {
2503
- duplex._final(callback);
2504
- });
2505
- return;
2506
- }
2507
- if (ws._socket === null)
2508
- return;
2509
- if (ws._socket._writableState.finished) {
2510
- callback();
2511
- if (duplex._readableState.endEmitted)
2512
- duplex.destroy();
2513
- } else {
2514
- ws._socket.once("finish", function finish() {
2515
- callback();
2516
- });
2517
- ws.close();
2518
- }
2519
- };
2520
- duplex._read = function() {
2521
- if (ws.isPaused)
2522
- ws.resume();
2523
- };
2524
- duplex._write = function(chunk, encoding, callback) {
2525
- if (ws.readyState === ws.CONNECTING) {
2526
- ws.once("open", function open() {
2527
- duplex._write(chunk, encoding, callback);
2528
- });
2529
- return;
2530
- }
2531
- ws.send(chunk, callback);
2532
- };
2533
- duplex.on("end", duplexOnEnd);
2534
- duplex.on("error", duplexOnError);
2535
- return duplex;
2536
- }
2537
- module2.exports = createWebSocketStream;
2538
- });
2539
-
2540
- // node_modules/ws/lib/subprotocol.js
2541
- var require_subprotocol = __commonJS((exports2, module2) => {
2542
- var { tokenChars } = require_validation();
2543
- function parse(header) {
2544
- const protocols = new Set;
2545
- let start = -1;
2546
- let end = -1;
2547
- let i = 0;
2548
- for (i;i < header.length; i++) {
2549
- const code = header.charCodeAt(i);
2550
- if (end === -1 && tokenChars[code] === 1) {
2551
- if (start === -1)
2552
- start = i;
2553
- } else if (i !== 0 && (code === 32 || code === 9)) {
2554
- if (end === -1 && start !== -1)
2555
- end = i;
2556
- } else if (code === 44) {
2557
- if (start === -1) {
2558
- throw new SyntaxError(`Unexpected character at index ${i}`);
2559
- }
2560
- if (end === -1)
2561
- end = i;
2562
- const protocol2 = header.slice(start, end);
2563
- if (protocols.has(protocol2)) {
2564
- throw new SyntaxError(`The "${protocol2}" subprotocol is duplicated`);
2565
- }
2566
- protocols.add(protocol2);
2567
- start = end = -1;
2568
- } else {
2569
- throw new SyntaxError(`Unexpected character at index ${i}`);
2570
- }
2571
- }
2572
- if (start === -1 || end !== -1) {
2573
- throw new SyntaxError("Unexpected end of input");
2574
- }
2575
- const protocol = header.slice(start, i);
2576
- if (protocols.has(protocol)) {
2577
- throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);
2578
- }
2579
- protocols.add(protocol);
2580
- return protocols;
2581
- }
2582
- module2.exports = { parse };
2583
- });
2584
-
2585
- // node_modules/ws/lib/websocket-server.js
2586
- var require_websocket_server = __commonJS((exports2, module2) => {
2587
- var EventEmitter = require("events");
2588
- var http = require("http");
2589
- var { Duplex } = require("stream");
2590
- var { createHash } = require("crypto");
2591
- var extension = require_extension();
2592
- var PerMessageDeflate = require_permessage_deflate();
2593
- var subprotocol = require_subprotocol();
2594
- var WebSocket = require_websocket();
2595
- var { CLOSE_TIMEOUT, GUID, kWebSocket } = require_constants();
2596
- var keyRegex = /^[+/0-9A-Za-z]{22}==$/;
2597
- var RUNNING = 0;
2598
- var CLOSING = 1;
2599
- var CLOSED = 2;
2600
-
2601
- class WebSocketServer extends EventEmitter {
2602
- constructor(options, callback) {
2603
- super();
2604
- options = {
2605
- allowSynchronousEvents: true,
2606
- autoPong: true,
2607
- maxPayload: 100 * 1024 * 1024,
2608
- skipUTF8Validation: false,
2609
- perMessageDeflate: false,
2610
- handleProtocols: null,
2611
- clientTracking: true,
2612
- closeTimeout: CLOSE_TIMEOUT,
2613
- verifyClient: null,
2614
- noServer: false,
2615
- backlog: null,
2616
- server: null,
2617
- host: null,
2618
- path: null,
2619
- port: null,
2620
- WebSocket,
2621
- ...options
2622
- };
2623
- if (options.port == null && !options.server && !options.noServer || options.port != null && (options.server || options.noServer) || options.server && options.noServer) {
2624
- throw new TypeError('One and only one of the "port", "server", or "noServer" options ' + "must be specified");
2625
- }
2626
- if (options.port != null) {
2627
- this._server = http.createServer((req, res) => {
2628
- const body = http.STATUS_CODES[426];
2629
- res.writeHead(426, {
2630
- "Content-Length": body.length,
2631
- "Content-Type": "text/plain"
2632
- });
2633
- res.end(body);
2634
- });
2635
- this._server.listen(options.port, options.host, options.backlog, callback);
2636
- } else if (options.server) {
2637
- this._server = options.server;
2638
- }
2639
- if (this._server) {
2640
- const emitConnection = this.emit.bind(this, "connection");
2641
- this._removeListeners = addListeners(this._server, {
2642
- listening: this.emit.bind(this, "listening"),
2643
- error: this.emit.bind(this, "error"),
2644
- upgrade: (req, socket, head) => {
2645
- this.handleUpgrade(req, socket, head, emitConnection);
2646
- }
2647
- });
2648
- }
2649
- if (options.perMessageDeflate === true)
2650
- options.perMessageDeflate = {};
2651
- if (options.clientTracking) {
2652
- this.clients = new Set;
2653
- this._shouldEmitClose = false;
2654
- }
2655
- this.options = options;
2656
- this._state = RUNNING;
2657
- }
2658
- address() {
2659
- if (this.options.noServer) {
2660
- throw new Error('The server is operating in "noServer" mode');
2661
- }
2662
- if (!this._server)
2663
- return null;
2664
- return this._server.address();
2665
- }
2666
- close(cb) {
2667
- if (this._state === CLOSED) {
2668
- if (cb) {
2669
- this.once("close", () => {
2670
- cb(new Error("The server is not running"));
2671
- });
2672
- }
2673
- process.nextTick(emitClose, this);
2674
- return;
2675
- }
2676
- if (cb)
2677
- this.once("close", cb);
2678
- if (this._state === CLOSING)
2679
- return;
2680
- this._state = CLOSING;
2681
- if (this.options.noServer || this.options.server) {
2682
- if (this._server) {
2683
- this._removeListeners();
2684
- this._removeListeners = this._server = null;
2685
- }
2686
- if (this.clients) {
2687
- if (!this.clients.size) {
2688
- process.nextTick(emitClose, this);
2689
- } else {
2690
- this._shouldEmitClose = true;
2691
- }
2692
- } else {
2693
- process.nextTick(emitClose, this);
2694
- }
2695
- } else {
2696
- const server = this._server;
2697
- this._removeListeners();
2698
- this._removeListeners = this._server = null;
2699
- server.close(() => {
2700
- emitClose(this);
2701
- });
2702
- }
2703
- }
2704
- shouldHandle(req) {
2705
- if (this.options.path) {
2706
- const index = req.url.indexOf("?");
2707
- const pathname = index !== -1 ? req.url.slice(0, index) : req.url;
2708
- if (pathname !== this.options.path)
2709
- return false;
2710
- }
2711
- return true;
2712
- }
2713
- handleUpgrade(req, socket, head, cb) {
2714
- socket.on("error", socketOnError);
2715
- const key = req.headers["sec-websocket-key"];
2716
- const upgrade = req.headers.upgrade;
2717
- const version = +req.headers["sec-websocket-version"];
2718
- if (req.method !== "GET") {
2719
- const message = "Invalid HTTP method";
2720
- abortHandshakeOrEmitwsClientError(this, req, socket, 405, message);
2721
- return;
2722
- }
2723
- if (upgrade === undefined || upgrade.toLowerCase() !== "websocket") {
2724
- const message = "Invalid Upgrade header";
2725
- abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
2726
- return;
2727
- }
2728
- if (key === undefined || !keyRegex.test(key)) {
2729
- const message = "Missing or invalid Sec-WebSocket-Key header";
2730
- abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
2731
- return;
2732
- }
2733
- if (version !== 13 && version !== 8) {
2734
- const message = "Missing or invalid Sec-WebSocket-Version header";
2735
- abortHandshakeOrEmitwsClientError(this, req, socket, 400, message, {
2736
- "Sec-WebSocket-Version": "13, 8"
2737
- });
2738
- return;
2739
- }
2740
- if (!this.shouldHandle(req)) {
2741
- abortHandshake(socket, 400);
2742
- return;
2743
- }
2744
- const secWebSocketProtocol = req.headers["sec-websocket-protocol"];
2745
- let protocols = new Set;
2746
- if (secWebSocketProtocol !== undefined) {
2747
- try {
2748
- protocols = subprotocol.parse(secWebSocketProtocol);
2749
- } catch (err) {
2750
- const message = "Invalid Sec-WebSocket-Protocol header";
2751
- abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
2752
- return;
2753
- }
2754
- }
2755
- const secWebSocketExtensions = req.headers["sec-websocket-extensions"];
2756
- const extensions = {};
2757
- if (this.options.perMessageDeflate && secWebSocketExtensions !== undefined) {
2758
- const perMessageDeflate = new PerMessageDeflate(this.options.perMessageDeflate, true, this.options.maxPayload);
2759
- try {
2760
- const offers = extension.parse(secWebSocketExtensions);
2761
- if (offers[PerMessageDeflate.extensionName]) {
2762
- perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]);
2763
- extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
2764
- }
2765
- } catch (err) {
2766
- const message = "Invalid or unacceptable Sec-WebSocket-Extensions header";
2767
- abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
2768
- return;
2769
- }
2770
- }
2771
- if (this.options.verifyClient) {
2772
- const info = {
2773
- origin: req.headers[`${version === 8 ? "sec-websocket-origin" : "origin"}`],
2774
- secure: !!(req.socket.authorized || req.socket.encrypted),
2775
- req
2776
- };
2777
- if (this.options.verifyClient.length === 2) {
2778
- this.options.verifyClient(info, (verified, code, message, headers) => {
2779
- if (!verified) {
2780
- return abortHandshake(socket, code || 401, message, headers);
2781
- }
2782
- this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);
2783
- });
2784
- return;
2785
- }
2786
- if (!this.options.verifyClient(info))
2787
- return abortHandshake(socket, 401);
2788
- }
2789
- this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);
2790
- }
2791
- completeUpgrade(extensions, key, protocols, req, socket, head, cb) {
2792
- if (!socket.readable || !socket.writable)
2793
- return socket.destroy();
2794
- if (socket[kWebSocket]) {
2795
- throw new Error("server.handleUpgrade() was called more than once with the same " + "socket, possibly due to a misconfiguration");
2796
- }
2797
- if (this._state > RUNNING)
2798
- return abortHandshake(socket, 503);
2799
- const digest = createHash("sha1").update(key + GUID).digest("base64");
2800
- const headers = [
2801
- "HTTP/1.1 101 Switching Protocols",
2802
- "Upgrade: websocket",
2803
- "Connection: Upgrade",
2804
- `Sec-WebSocket-Accept: ${digest}`
2805
- ];
2806
- const ws = new this.options.WebSocket(null, undefined, this.options);
2807
- if (protocols.size) {
2808
- const protocol = this.options.handleProtocols ? this.options.handleProtocols(protocols, req) : protocols.values().next().value;
2809
- if (protocol) {
2810
- headers.push(`Sec-WebSocket-Protocol: ${protocol}`);
2811
- ws._protocol = protocol;
2812
- }
2813
- }
2814
- if (extensions[PerMessageDeflate.extensionName]) {
2815
- const params = extensions[PerMessageDeflate.extensionName].params;
2816
- const value = extension.format({
2817
- [PerMessageDeflate.extensionName]: [params]
2818
- });
2819
- headers.push(`Sec-WebSocket-Extensions: ${value}`);
2820
- ws._extensions = extensions;
2821
- }
2822
- this.emit("headers", headers, req);
2823
- socket.write(headers.concat(`\r
2824
- `).join(`\r
2825
- `));
2826
- socket.removeListener("error", socketOnError);
2827
- ws.setSocket(socket, head, {
2828
- allowSynchronousEvents: this.options.allowSynchronousEvents,
2829
- maxPayload: this.options.maxPayload,
2830
- skipUTF8Validation: this.options.skipUTF8Validation
2831
- });
2832
- if (this.clients) {
2833
- this.clients.add(ws);
2834
- ws.on("close", () => {
2835
- this.clients.delete(ws);
2836
- if (this._shouldEmitClose && !this.clients.size) {
2837
- process.nextTick(emitClose, this);
2838
- }
2839
- });
2840
- }
2841
- cb(ws, req);
2842
- }
2843
- }
2844
- module2.exports = WebSocketServer;
2845
- function addListeners(server, map) {
2846
- for (const event of Object.keys(map))
2847
- server.on(event, map[event]);
2848
- return function removeListeners() {
2849
- for (const event of Object.keys(map)) {
2850
- server.removeListener(event, map[event]);
2851
- }
2852
- };
2853
- }
2854
- function emitClose(server) {
2855
- server._state = CLOSED;
2856
- server.emit("close");
2857
- }
2858
- function socketOnError() {
2859
- this.destroy();
2860
- }
2861
- function abortHandshake(socket, code, message, headers) {
2862
- message = message || http.STATUS_CODES[code];
2863
- headers = {
2864
- Connection: "close",
2865
- "Content-Type": "text/html",
2866
- "Content-Length": Buffer.byteLength(message),
2867
- ...headers
2868
- };
2869
- socket.once("finish", socket.destroy);
2870
- socket.end(`HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r
2871
- ` + Object.keys(headers).map((h) => `${h}: ${headers[h]}`).join(`\r
2872
- `) + `\r
2873
- \r
2874
- ` + message);
2875
- }
2876
- function abortHandshakeOrEmitwsClientError(server, req, socket, code, message, headers) {
2877
- if (server.listenerCount("wsClientError")) {
2878
- const err = new Error(message);
2879
- Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError);
2880
- server.emit("wsClientError", err, socket, req);
2881
- } else {
2882
- abortHandshake(socket, code, message, headers);
2883
- }
2884
- }
2885
- });
27
+ };
2886
28
 
2887
29
  // src/index.ts
2888
30
  var exports_src = {};
@@ -2954,15 +96,16 @@ class SaynaServerError extends SaynaError {
2954
96
  }
2955
97
  }
2956
98
 
2957
- // node_modules/ws/wrapper.mjs
2958
- var import_stream = __toESM(require_stream(), 1);
2959
- var import_receiver = __toESM(require_receiver(), 1);
2960
- var import_sender = __toESM(require_sender(), 1);
2961
- var import_websocket = __toESM(require_websocket(), 1);
2962
- var import_websocket_server = __toESM(require_websocket_server(), 1);
2963
- var wrapper_default = import_websocket.default;
2964
-
2965
99
  // src/sayna-client.ts
100
+ var isBun = typeof process !== "undefined" && typeof process.versions?.bun === "string";
101
+ var hasNativeWebSocket = typeof globalThis.WebSocket !== "undefined";
102
+ var WS;
103
+ if (hasNativeWebSocket) {
104
+ WS = globalThis.WebSocket;
105
+ } else {
106
+ WS = require("ws");
107
+ }
108
+
2966
109
  class SaynaClient {
2967
110
  url;
2968
111
  sttConfig;
@@ -3017,8 +160,7 @@ class SaynaClient {
3017
160
  this.readyPromiseResolve = resolve;
3018
161
  this.readyPromiseReject = reject;
3019
162
  try {
3020
- const headers = this.apiKey ? { Authorization: `Bearer ${this.apiKey}` } : undefined;
3021
- this.websocket = headers ? new wrapper_default(wsUrl, undefined, { headers }) : new wrapper_default(wsUrl);
163
+ this.websocket = this.createWebSocket(wsUrl);
3022
164
  this.websocket.binaryType = "arraybuffer";
3023
165
  this.websocket.onopen = () => {
3024
166
  this.isConnected = true;
@@ -3174,6 +316,21 @@ class SaynaClient {
3174
316
  }
3175
317
  }
3176
318
  }
319
+ createWebSocket(url) {
320
+ if (!this.apiKey) {
321
+ return new WS(url);
322
+ }
323
+ const headers = { Authorization: `Bearer ${this.apiKey}` };
324
+ if (!hasNativeWebSocket) {
325
+ return new WS(url, undefined, { headers });
326
+ }
327
+ if (isBun) {
328
+ return new WS(url, { headers });
329
+ }
330
+ const separator = url.includes("?") ? "&" : "?";
331
+ const urlWithToken = `${url}${separator}token=${encodeURIComponent(this.apiKey)}`;
332
+ return new WS(urlWithToken);
333
+ }
3177
334
  cleanup() {
3178
335
  this.isConnected = false;
3179
336
  this.isReady = false;
@@ -3238,7 +395,7 @@ class SaynaClient {
3238
395
  this.websocket.onmessage = null;
3239
396
  this.websocket.onerror = null;
3240
397
  this.websocket.onclose = null;
3241
- if (this.websocket.readyState === wrapper_default.OPEN) {
398
+ if (this.websocket.readyState === WS.OPEN) {
3242
399
  this.websocket.close(1000, "Client disconnect");
3243
400
  }
3244
401
  this.websocket = undefined;
@@ -3709,4 +866,4 @@ async function saynaConnect(url, sttConfig, ttsConfig, livekitConfig, withoutAud
3709
866
  return client;
3710
867
  }
3711
868
 
3712
- //# debugId=60C9CBFBEDADAA1664756E2164756E21
869
+ //# debugId=109874985838504164756E2164756E21