@kizenapps/cli 0.2.0 → 0.4.0

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