@alfe.ai/openclaw 0.0.1

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