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