@latticexyz/world-module-erc20 2.2.18-8d0ce55e964e646a1c804c401df01c4deb866f30 → 2.2.18-9fa07c8489f1fbf167d0db01cd9aaa645a29c8e2

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