@0xobelisk/sui-client 1.0.6 → 1.0.7

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