open-agents-ai 0.56.0 → 0.58.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +4118 -477
  2. package/package.json +2 -1
package/dist/index.js CHANGED
@@ -1,7 +1,11 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __createRequire } from "node:module"; const require = __createRequire(import.meta.url);
3
+ var __create = Object.create;
3
4
  var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
6
  var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
9
  var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
6
10
  get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
7
11
  }) : x)(function(x) {
@@ -11,10 +15,29 @@ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require
11
15
  var __esm = (fn, res) => function __init() {
12
16
  return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
13
17
  };
18
+ var __commonJS = (cb, mod) => function __require2() {
19
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
20
+ };
14
21
  var __export = (target, all) => {
15
22
  for (var name in all)
16
23
  __defProp(target, name, { get: all[name], enumerable: true });
17
24
  };
25
+ var __copyProps = (to, from, except, desc) => {
26
+ if (from && typeof from === "object" || typeof from === "function") {
27
+ for (let key of __getOwnPropNames(from))
28
+ if (!__hasOwnProp.call(to, key) && key !== except)
29
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
30
+ }
31
+ return to;
32
+ };
33
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
34
+ // If the importer is in node compatibility mode or this is not an ESM
35
+ // file that has been converted to a CommonJS file using a Babel-
36
+ // compatible transform (i.e. "__esModule" has not been set), then set
37
+ // "default" to the CommonJS "module.exports" for node compatibility.
38
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
39
+ mod
40
+ ));
18
41
 
19
42
  // packages/cli/dist/config.js
20
43
  import { readFileSync, existsSync, mkdirSync, writeFileSync } from "node:fs";
@@ -16860,238 +16883,3866 @@ transcribe-cli error: ${transcribeCliError}` : "";
16860
16883
  }
16861
16884
  });
16862
16885
 
16863
- // packages/cli/dist/tui/render.js
16864
- function ansi2(code, text) {
16865
- return isTTY2 ? `\x1B[${code}m${text}\x1B[0m` : text;
16866
- }
16867
- function fg256(code, text) {
16868
- return isTTY2 ? `\x1B[38;5;${code}m${text}\x1B[0m` : text;
16869
- }
16870
- function setEmojisEnabled(enabled) {
16871
- _emojisEnabled = enabled;
16872
- }
16873
- function getEmojisEnabled() {
16874
- return _emojisEnabled;
16875
- }
16876
- function setColorsEnabled(enabled) {
16877
- _colorsEnabled = enabled;
16878
- }
16879
- function getColorsEnabled() {
16880
- return _colorsEnabled;
16881
- }
16882
- function getTermWidth() {
16883
- return process.stdout.columns ?? 80;
16884
- }
16885
- function formatMarkdownLine(line) {
16886
- const headingMatch = line.match(/^(#{1,6})\s+(.*)/);
16887
- if (headingMatch) {
16888
- const level = headingMatch[1].length;
16889
- const text = headingMatch[2];
16890
- const colors = [MD.heading1, MD.heading2, MD.heading3, MD.heading3, 183, 183];
16891
- return c2.bold(fg256(colors[level - 1] ?? 147, formatInlineMarkdown(text)));
16892
- }
16893
- if (/^[-*_]{3,}\s*$/.test(line)) {
16894
- const w = getTermWidth() - 10;
16895
- return fg256(MD.hr, "\u2500".repeat(Math.min(w, 60)));
16896
- }
16897
- if (/^>\s?/.test(line)) {
16898
- const content = line.replace(/^>\s?/, "");
16899
- return fg256(MD.blockquote, "\u2502 ") + c2.italic(fg256(MD.blockquote, formatInlineMarkdown(content)));
16900
- }
16901
- if (/^\|(.+)\|/.test(line)) {
16902
- if (/^\|[\s:_-]+\|/.test(line)) {
16903
- return fg256(MD.tableBar, line);
16904
- }
16905
- return line.replace(/([^|]+)/g, (cell) => {
16906
- const trimmed = cell.trim();
16907
- if (!trimmed)
16908
- return cell;
16909
- const leading = cell.match(/^(\s*)/)?.[1] ?? "";
16910
- const trailing = cell.match(/(\s*)$/)?.[1] ?? "";
16911
- return leading + formatInlineMarkdown(trimmed) + trailing;
16912
- });
16913
- }
16914
- const ulMatch = line.match(/^(\s*)([-*+])\s+(.*)/);
16915
- if (ulMatch) {
16916
- return ulMatch[1] + fg256(MD.listBullet, "\u2022") + " " + formatInlineMarkdown(ulMatch[3]);
16917
- }
16918
- const olMatch = line.match(/^(\s*)(\d+[.)])\s+(.*)/);
16919
- if (olMatch) {
16920
- return olMatch[1] + fg256(MD.listBullet, olMatch[2]) + " " + formatInlineMarkdown(olMatch[3]);
16886
+ // node_modules/.pnpm/ws@8.19.0/node_modules/ws/lib/constants.js
16887
+ var require_constants = __commonJS({
16888
+ "node_modules/.pnpm/ws@8.19.0/node_modules/ws/lib/constants.js"(exports, module) {
16889
+ "use strict";
16890
+ var BINARY_TYPES = ["nodebuffer", "arraybuffer", "fragments"];
16891
+ var hasBlob = typeof Blob !== "undefined";
16892
+ if (hasBlob) BINARY_TYPES.push("blob");
16893
+ module.exports = {
16894
+ BINARY_TYPES,
16895
+ CLOSE_TIMEOUT: 3e4,
16896
+ EMPTY_BUFFER: Buffer.alloc(0),
16897
+ GUID: "258EAFA5-E914-47DA-95CA-C5AB0DC85B11",
16898
+ hasBlob,
16899
+ kForOnEventAttribute: /* @__PURE__ */ Symbol("kIsForOnEventAttribute"),
16900
+ kListener: /* @__PURE__ */ Symbol("kListener"),
16901
+ kStatusCode: /* @__PURE__ */ Symbol("status-code"),
16902
+ kWebSocket: /* @__PURE__ */ Symbol("websocket"),
16903
+ NOOP: () => {
16904
+ }
16905
+ };
16921
16906
  }
16922
- return formatInlineMarkdown(line);
16923
- }
16924
- function formatInlineMarkdown(text) {
16925
- let result = text;
16926
- result = result.replace(/`([^`]+)`/g, (_m, code) => fg256(MD.inlineCode, code));
16927
- result = result.replace(/\*{3}([^*]+)\*{3}/g, (_m, t) => c2.bold(c2.italic(t)));
16928
- result = result.replace(/\*{2}([^*]+)\*{2}/g, (_m, t) => c2.bold(t));
16929
- result = result.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g, (_m, t) => c2.italic(t));
16930
- result = result.replace(/\[([^\]]+)\]\(([^)]+)\)/g, (_m, label, url) => c2.bold(fg256(MD.link, label)) + " " + c2.dim(fg256(MD.link, `(${url})`)));
16931
- result = result.replace(/__([^_]+)__/g, (_m, t) => c2.bold(t));
16932
- result = result.replace(/(?<!_)_([^_]+)_(?!_)/g, (_m, t) => c2.italic(t));
16933
- result = result.replace(/~~([^~]+)~~/g, (_m, t) => c2.dim(t));
16934
- return result;
16935
- }
16936
- function formatMarkdownBlock(text) {
16937
- const lines = text.split("\n");
16938
- const result = [];
16939
- let inCodeBlock = false;
16940
- let codeLang = "";
16941
- for (const line of lines) {
16942
- const trimmedLine = line.trimStart();
16943
- if (trimmedLine.startsWith("```")) {
16944
- if (inCodeBlock) {
16945
- result.push(c2.dim(" ```"));
16946
- inCodeBlock = false;
16947
- codeLang = "";
16907
+ });
16908
+
16909
+ // node_modules/.pnpm/ws@8.19.0/node_modules/ws/lib/buffer-util.js
16910
+ var require_buffer_util = __commonJS({
16911
+ "node_modules/.pnpm/ws@8.19.0/node_modules/ws/lib/buffer-util.js"(exports, module) {
16912
+ "use strict";
16913
+ var { EMPTY_BUFFER } = require_constants();
16914
+ var FastBuffer = Buffer[Symbol.species];
16915
+ function concat(list, totalLength) {
16916
+ if (list.length === 0) return EMPTY_BUFFER;
16917
+ if (list.length === 1) return list[0];
16918
+ const target = Buffer.allocUnsafe(totalLength);
16919
+ let offset = 0;
16920
+ for (let i = 0; i < list.length; i++) {
16921
+ const buf = list[i];
16922
+ target.set(buf, offset);
16923
+ offset += buf.length;
16924
+ }
16925
+ if (offset < totalLength) {
16926
+ return new FastBuffer(target.buffer, target.byteOffset, offset);
16927
+ }
16928
+ return target;
16929
+ }
16930
+ function _mask(source, mask, output, offset, length) {
16931
+ for (let i = 0; i < length; i++) {
16932
+ output[offset + i] = source[i] ^ mask[i & 3];
16933
+ }
16934
+ }
16935
+ function _unmask(buffer, mask) {
16936
+ for (let i = 0; i < buffer.length; i++) {
16937
+ buffer[i] ^= mask[i & 3];
16938
+ }
16939
+ }
16940
+ function toArrayBuffer(buf) {
16941
+ if (buf.length === buf.buffer.byteLength) {
16942
+ return buf.buffer;
16943
+ }
16944
+ return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length);
16945
+ }
16946
+ function toBuffer(data) {
16947
+ toBuffer.readOnly = true;
16948
+ if (Buffer.isBuffer(data)) return data;
16949
+ let buf;
16950
+ if (data instanceof ArrayBuffer) {
16951
+ buf = new FastBuffer(data);
16952
+ } else if (ArrayBuffer.isView(data)) {
16953
+ buf = new FastBuffer(data.buffer, data.byteOffset, data.byteLength);
16948
16954
  } else {
16949
- codeLang = trimmedLine.slice(3).trim();
16950
- result.push(c2.dim(" ```" + codeLang));
16951
- inCodeBlock = true;
16955
+ buf = Buffer.from(data);
16956
+ toBuffer.readOnly = false;
16952
16957
  }
16953
- continue;
16958
+ return buf;
16954
16959
  }
16955
- if (inCodeBlock) {
16956
- result.push(" " + c2.dim(line));
16957
- } else {
16958
- result.push(formatMarkdownLine(line));
16960
+ module.exports = {
16961
+ concat,
16962
+ mask: _mask,
16963
+ toArrayBuffer,
16964
+ toBuffer,
16965
+ unmask: _unmask
16966
+ };
16967
+ if (!process.env.WS_NO_BUFFER_UTIL) {
16968
+ try {
16969
+ const bufferUtil = __require("bufferutil");
16970
+ module.exports.mask = function(source, mask, output, offset, length) {
16971
+ if (length < 48) _mask(source, mask, output, offset, length);
16972
+ else bufferUtil.mask(source, mask, output, offset, length);
16973
+ };
16974
+ module.exports.unmask = function(buffer, mask) {
16975
+ if (buffer.length < 32) _unmask(buffer, mask);
16976
+ else bufferUtil.unmask(buffer, mask);
16977
+ };
16978
+ } catch (e) {
16979
+ }
16959
16980
  }
16960
16981
  }
16961
- return result.join("\n");
16962
- }
16963
- function renderUserMessage(text) {
16964
- process.stdout.write(`
16965
- ${c2.bold(c2.blue("> "))}${c2.bold(text)}
16966
- `);
16967
- }
16968
- function renderAssistantText(text) {
16969
- if (!text.trim())
16970
- return;
16971
- const formatted = formatMarkdownBlock(text);
16972
- const lines = formatted.split("\n");
16973
- for (const line of lines) {
16974
- process.stdout.write(` ${line}
16975
- `);
16976
- }
16977
- }
16978
- function renderVoiceText(text) {
16979
- process.stdout.write(` ${c2.dim("\u{1F50A}")} ${c2.italic(c2.dim(text))}
16980
- `);
16981
- }
16982
- function renderUserInterrupt(text) {
16983
- process.stdout.write(`
16984
- ${c2.cyan("\u21AA")} ${c2.bold("Context added:")} ${text}
16985
- `);
16986
- }
16987
- function renderTaskAborted() {
16988
- process.stdout.write(`
16989
- ${c2.yellow("\u26A0")} ${c2.bold("Task aborted by user")}
16990
- `);
16991
- }
16992
- function renderToolCallStart(toolName, args, verbose) {
16993
- const icon = TOOL_ICONS[toolName] ?? "\u{1F527}";
16994
- const label = TOOL_LABELS[toolName] ?? toolName;
16995
- const argsSummary = formatToolArgs(toolName, args, verbose);
16996
- const colorFn = _colorsEnabled ? TOOL_COLORS[toolName] ?? c2.dim : (t) => t;
16997
- const emojiPrefix = _emojisEnabled ? `${icon} ` : "";
16998
- process.stdout.write(`
16999
- ${c2.dim("\u23BF")} ${emojiPrefix}${colorFn(c2.bold(label))}${argsSummary ? c2.dim(": ") + argsSummary : ""}
17000
- `);
17001
- }
17002
- function renderToolResult(toolName, success, output, verbose) {
17003
- const maxW = verbose ? Math.max(getTermWidth() - 10, 200) : getTermWidth() - 10;
17004
- const prefix = ` ${c2.dim("\u23BF")} `;
17005
- switch (toolName) {
17006
- case "file_write": {
17007
- const summary = extractFirstLine(output, maxW);
17008
- if (success) {
17009
- process.stdout.write(`${prefix}${c2.dim(summary)}
17010
- `);
17011
- } else {
17012
- process.stdout.write(`${prefix}${c2.red(summary)}
17013
- `);
16982
+ });
16983
+
16984
+ // node_modules/.pnpm/ws@8.19.0/node_modules/ws/lib/limiter.js
16985
+ var require_limiter = __commonJS({
16986
+ "node_modules/.pnpm/ws@8.19.0/node_modules/ws/lib/limiter.js"(exports, module) {
16987
+ "use strict";
16988
+ var kDone = /* @__PURE__ */ Symbol("kDone");
16989
+ var kRun = /* @__PURE__ */ Symbol("kRun");
16990
+ var Limiter = class {
16991
+ /**
16992
+ * Creates a new `Limiter`.
16993
+ *
16994
+ * @param {Number} [concurrency=Infinity] The maximum number of jobs allowed
16995
+ * to run concurrently
16996
+ */
16997
+ constructor(concurrency) {
16998
+ this[kDone] = () => {
16999
+ this.pending--;
17000
+ this[kRun]();
17001
+ };
17002
+ this.concurrency = concurrency || Infinity;
17003
+ this.jobs = [];
17004
+ this.pending = 0;
17014
17005
  }
17015
- return;
17016
- }
17017
- case "file_edit": {
17018
- const summary = extractFirstLine(output, maxW);
17019
- if (success) {
17020
- process.stdout.write(`${prefix}${c2.dim(summary)}
17021
- `);
17022
- } else {
17023
- process.stdout.write(`${prefix}${c2.red(summary)}
17024
- `);
17006
+ /**
17007
+ * Adds a job to the queue.
17008
+ *
17009
+ * @param {Function} job The job to run
17010
+ * @public
17011
+ */
17012
+ add(job) {
17013
+ this.jobs.push(job);
17014
+ this[kRun]();
17025
17015
  }
17026
- return;
17027
- }
17028
- case "file_read": {
17029
- if (!success) {
17030
- process.stdout.write(`${prefix}${c2.red(extractFirstLine(output, maxW))}
17031
- `);
17032
- return;
17016
+ /**
17017
+ * Removes a job from the queue and runs it if possible.
17018
+ *
17019
+ * @private
17020
+ */
17021
+ [kRun]() {
17022
+ if (this.pending === this.concurrency) return;
17023
+ if (this.jobs.length) {
17024
+ const job = this.jobs.shift();
17025
+ this.pending++;
17026
+ job(this[kDone]);
17027
+ }
17033
17028
  }
17034
- renderCodePreview(output, prefix, maxW, 6);
17035
- return;
17036
- }
17037
- case "shell":
17038
- case "background_run": {
17039
- renderShellOutput(output, success, prefix, maxW, 8);
17040
- return;
17041
- }
17042
- case "grep_search": {
17043
- renderShellOutput(output, success, prefix, maxW, 6);
17044
- return;
17045
- }
17046
- case "task_complete": {
17047
- process.stdout.write(`${prefix}${c2.green("\u2714")} ${c2.dim("Done")}
17048
- `);
17049
- return;
17050
- }
17051
- default:
17052
- break;
17053
- }
17054
- const lines = output.split("\n").filter((l) => l.trim());
17055
- if (lines.length === 0) {
17056
- const icon = success ? _emojisEnabled ? c2.green("\u2714") : c2.green("+") : _emojisEnabled ? c2.red("\u2716") : c2.red("x");
17057
- process.stdout.write(`${prefix}${icon} ${success ? c2.dim("Done") : c2.red("Failed")}
17058
- `);
17059
- return;
17029
+ };
17030
+ module.exports = Limiter;
17060
17031
  }
17061
- const maxLines = verbose ? 200 : 6;
17062
- const shown = lines.slice(0, maxLines);
17063
- for (const line of shown) {
17064
- if (isRawJsonDump(line) && !verbose) {
17065
- process.stdout.write(`${prefix}${c2.dim("(content omitted)")}
17066
- `);
17067
- return;
17068
- }
17069
- if (verbose) {
17070
- const termW = getTermWidth() - 10;
17071
- if (line.length > termW) {
17072
- let remaining = line;
17073
- let first = true;
17074
- while (remaining.length > 0) {
17075
- if (remaining.length <= termW) {
17076
- const formatted2 = formatMarkdownLine(remaining);
17077
- process.stdout.write(`${first ? prefix : prefix + " "}${formatted2 === remaining ? highlightToolOutput(remaining) : formatted2}
17078
- `);
17079
- break;
17080
- }
17081
- let breakAt = remaining.lastIndexOf(" ", termW);
17082
- if (breakAt < termW * 0.3)
17083
- breakAt = termW;
17084
- const chunk = remaining.slice(0, breakAt);
17085
- remaining = remaining.slice(breakAt).trimStart();
17086
- const formatted = formatMarkdownLine(chunk);
17087
- process.stdout.write(`${first ? prefix : prefix + " "}${formatted === chunk ? highlightToolOutput(chunk) : formatted}
17088
- `);
17089
- first = false;
17032
+ });
17033
+
17034
+ // node_modules/.pnpm/ws@8.19.0/node_modules/ws/lib/permessage-deflate.js
17035
+ var require_permessage_deflate = __commonJS({
17036
+ "node_modules/.pnpm/ws@8.19.0/node_modules/ws/lib/permessage-deflate.js"(exports, module) {
17037
+ "use strict";
17038
+ var zlib = __require("zlib");
17039
+ var bufferUtil = require_buffer_util();
17040
+ var Limiter = require_limiter();
17041
+ var { kStatusCode } = require_constants();
17042
+ var FastBuffer = Buffer[Symbol.species];
17043
+ var TRAILER = Buffer.from([0, 0, 255, 255]);
17044
+ var kPerMessageDeflate = /* @__PURE__ */ Symbol("permessage-deflate");
17045
+ var kTotalLength = /* @__PURE__ */ Symbol("total-length");
17046
+ var kCallback = /* @__PURE__ */ Symbol("callback");
17047
+ var kBuffers = /* @__PURE__ */ Symbol("buffers");
17048
+ var kError = /* @__PURE__ */ Symbol("error");
17049
+ var zlibLimiter;
17050
+ var PerMessageDeflate = class {
17051
+ /**
17052
+ * Creates a PerMessageDeflate instance.
17053
+ *
17054
+ * @param {Object} [options] Configuration options
17055
+ * @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support
17056
+ * for, or request, a custom client window size
17057
+ * @param {Boolean} [options.clientNoContextTakeover=false] Advertise/
17058
+ * acknowledge disabling of client context takeover
17059
+ * @param {Number} [options.concurrencyLimit=10] The number of concurrent
17060
+ * calls to zlib
17061
+ * @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the
17062
+ * use of a custom server window size
17063
+ * @param {Boolean} [options.serverNoContextTakeover=false] Request/accept
17064
+ * disabling of server context takeover
17065
+ * @param {Number} [options.threshold=1024] Size (in bytes) below which
17066
+ * messages should not be compressed if context takeover is disabled
17067
+ * @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on
17068
+ * deflate
17069
+ * @param {Object} [options.zlibInflateOptions] Options to pass to zlib on
17070
+ * inflate
17071
+ * @param {Boolean} [isServer=false] Create the instance in either server or
17072
+ * client mode
17073
+ * @param {Number} [maxPayload=0] The maximum allowed message length
17074
+ */
17075
+ constructor(options, isServer, maxPayload) {
17076
+ this._maxPayload = maxPayload | 0;
17077
+ this._options = options || {};
17078
+ this._threshold = this._options.threshold !== void 0 ? this._options.threshold : 1024;
17079
+ this._isServer = !!isServer;
17080
+ this._deflate = null;
17081
+ this._inflate = null;
17082
+ this.params = null;
17083
+ if (!zlibLimiter) {
17084
+ const concurrency = this._options.concurrencyLimit !== void 0 ? this._options.concurrencyLimit : 10;
17085
+ zlibLimiter = new Limiter(concurrency);
17090
17086
  }
17091
- } else {
17092
- const formatted = formatMarkdownLine(line);
17093
- process.stdout.write(`${prefix}${formatted === line ? highlightToolOutput(line) : formatted}
17094
- `);
17087
+ }
17088
+ /**
17089
+ * @type {String}
17090
+ */
17091
+ static get extensionName() {
17092
+ return "permessage-deflate";
17093
+ }
17094
+ /**
17095
+ * Create an extension negotiation offer.
17096
+ *
17097
+ * @return {Object} Extension parameters
17098
+ * @public
17099
+ */
17100
+ offer() {
17101
+ const params = {};
17102
+ if (this._options.serverNoContextTakeover) {
17103
+ params.server_no_context_takeover = true;
17104
+ }
17105
+ if (this._options.clientNoContextTakeover) {
17106
+ params.client_no_context_takeover = true;
17107
+ }
17108
+ if (this._options.serverMaxWindowBits) {
17109
+ params.server_max_window_bits = this._options.serverMaxWindowBits;
17110
+ }
17111
+ if (this._options.clientMaxWindowBits) {
17112
+ params.client_max_window_bits = this._options.clientMaxWindowBits;
17113
+ } else if (this._options.clientMaxWindowBits == null) {
17114
+ params.client_max_window_bits = true;
17115
+ }
17116
+ return params;
17117
+ }
17118
+ /**
17119
+ * Accept an extension negotiation offer/response.
17120
+ *
17121
+ * @param {Array} configurations The extension negotiation offers/reponse
17122
+ * @return {Object} Accepted configuration
17123
+ * @public
17124
+ */
17125
+ accept(configurations) {
17126
+ configurations = this.normalizeParams(configurations);
17127
+ this.params = this._isServer ? this.acceptAsServer(configurations) : this.acceptAsClient(configurations);
17128
+ return this.params;
17129
+ }
17130
+ /**
17131
+ * Releases all resources used by the extension.
17132
+ *
17133
+ * @public
17134
+ */
17135
+ cleanup() {
17136
+ if (this._inflate) {
17137
+ this._inflate.close();
17138
+ this._inflate = null;
17139
+ }
17140
+ if (this._deflate) {
17141
+ const callback = this._deflate[kCallback];
17142
+ this._deflate.close();
17143
+ this._deflate = null;
17144
+ if (callback) {
17145
+ callback(
17146
+ new Error(
17147
+ "The deflate stream was closed while data was being processed"
17148
+ )
17149
+ );
17150
+ }
17151
+ }
17152
+ }
17153
+ /**
17154
+ * Accept an extension negotiation offer.
17155
+ *
17156
+ * @param {Array} offers The extension negotiation offers
17157
+ * @return {Object} Accepted configuration
17158
+ * @private
17159
+ */
17160
+ acceptAsServer(offers) {
17161
+ const opts = this._options;
17162
+ const accepted = offers.find((params) => {
17163
+ 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) {
17164
+ return false;
17165
+ }
17166
+ return true;
17167
+ });
17168
+ if (!accepted) {
17169
+ throw new Error("None of the extension offers can be accepted");
17170
+ }
17171
+ if (opts.serverNoContextTakeover) {
17172
+ accepted.server_no_context_takeover = true;
17173
+ }
17174
+ if (opts.clientNoContextTakeover) {
17175
+ accepted.client_no_context_takeover = true;
17176
+ }
17177
+ if (typeof opts.serverMaxWindowBits === "number") {
17178
+ accepted.server_max_window_bits = opts.serverMaxWindowBits;
17179
+ }
17180
+ if (typeof opts.clientMaxWindowBits === "number") {
17181
+ accepted.client_max_window_bits = opts.clientMaxWindowBits;
17182
+ } else if (accepted.client_max_window_bits === true || opts.clientMaxWindowBits === false) {
17183
+ delete accepted.client_max_window_bits;
17184
+ }
17185
+ return accepted;
17186
+ }
17187
+ /**
17188
+ * Accept the extension negotiation response.
17189
+ *
17190
+ * @param {Array} response The extension negotiation response
17191
+ * @return {Object} Accepted configuration
17192
+ * @private
17193
+ */
17194
+ acceptAsClient(response) {
17195
+ const params = response[0];
17196
+ if (this._options.clientNoContextTakeover === false && params.client_no_context_takeover) {
17197
+ throw new Error('Unexpected parameter "client_no_context_takeover"');
17198
+ }
17199
+ if (!params.client_max_window_bits) {
17200
+ if (typeof this._options.clientMaxWindowBits === "number") {
17201
+ params.client_max_window_bits = this._options.clientMaxWindowBits;
17202
+ }
17203
+ } else if (this._options.clientMaxWindowBits === false || typeof this._options.clientMaxWindowBits === "number" && params.client_max_window_bits > this._options.clientMaxWindowBits) {
17204
+ throw new Error(
17205
+ 'Unexpected or invalid parameter "client_max_window_bits"'
17206
+ );
17207
+ }
17208
+ return params;
17209
+ }
17210
+ /**
17211
+ * Normalize parameters.
17212
+ *
17213
+ * @param {Array} configurations The extension negotiation offers/reponse
17214
+ * @return {Array} The offers/response with normalized parameters
17215
+ * @private
17216
+ */
17217
+ normalizeParams(configurations) {
17218
+ configurations.forEach((params) => {
17219
+ Object.keys(params).forEach((key) => {
17220
+ let value = params[key];
17221
+ if (value.length > 1) {
17222
+ throw new Error(`Parameter "${key}" must have only a single value`);
17223
+ }
17224
+ value = value[0];
17225
+ if (key === "client_max_window_bits") {
17226
+ if (value !== true) {
17227
+ const num = +value;
17228
+ if (!Number.isInteger(num) || num < 8 || num > 15) {
17229
+ throw new TypeError(
17230
+ `Invalid value for parameter "${key}": ${value}`
17231
+ );
17232
+ }
17233
+ value = num;
17234
+ } else if (!this._isServer) {
17235
+ throw new TypeError(
17236
+ `Invalid value for parameter "${key}": ${value}`
17237
+ );
17238
+ }
17239
+ } else if (key === "server_max_window_bits") {
17240
+ const num = +value;
17241
+ if (!Number.isInteger(num) || num < 8 || num > 15) {
17242
+ throw new TypeError(
17243
+ `Invalid value for parameter "${key}": ${value}`
17244
+ );
17245
+ }
17246
+ value = num;
17247
+ } else if (key === "client_no_context_takeover" || key === "server_no_context_takeover") {
17248
+ if (value !== true) {
17249
+ throw new TypeError(
17250
+ `Invalid value for parameter "${key}": ${value}`
17251
+ );
17252
+ }
17253
+ } else {
17254
+ throw new Error(`Unknown parameter "${key}"`);
17255
+ }
17256
+ params[key] = value;
17257
+ });
17258
+ });
17259
+ return configurations;
17260
+ }
17261
+ /**
17262
+ * Decompress data. Concurrency limited.
17263
+ *
17264
+ * @param {Buffer} data Compressed data
17265
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
17266
+ * @param {Function} callback Callback
17267
+ * @public
17268
+ */
17269
+ decompress(data, fin, callback) {
17270
+ zlibLimiter.add((done) => {
17271
+ this._decompress(data, fin, (err, result) => {
17272
+ done();
17273
+ callback(err, result);
17274
+ });
17275
+ });
17276
+ }
17277
+ /**
17278
+ * Compress data. Concurrency limited.
17279
+ *
17280
+ * @param {(Buffer|String)} data Data to compress
17281
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
17282
+ * @param {Function} callback Callback
17283
+ * @public
17284
+ */
17285
+ compress(data, fin, callback) {
17286
+ zlibLimiter.add((done) => {
17287
+ this._compress(data, fin, (err, result) => {
17288
+ done();
17289
+ callback(err, result);
17290
+ });
17291
+ });
17292
+ }
17293
+ /**
17294
+ * Decompress data.
17295
+ *
17296
+ * @param {Buffer} data Compressed data
17297
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
17298
+ * @param {Function} callback Callback
17299
+ * @private
17300
+ */
17301
+ _decompress(data, fin, callback) {
17302
+ const endpoint = this._isServer ? "client" : "server";
17303
+ if (!this._inflate) {
17304
+ const key = `${endpoint}_max_window_bits`;
17305
+ const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
17306
+ this._inflate = zlib.createInflateRaw({
17307
+ ...this._options.zlibInflateOptions,
17308
+ windowBits
17309
+ });
17310
+ this._inflate[kPerMessageDeflate] = this;
17311
+ this._inflate[kTotalLength] = 0;
17312
+ this._inflate[kBuffers] = [];
17313
+ this._inflate.on("error", inflateOnError);
17314
+ this._inflate.on("data", inflateOnData);
17315
+ }
17316
+ this._inflate[kCallback] = callback;
17317
+ this._inflate.write(data);
17318
+ if (fin) this._inflate.write(TRAILER);
17319
+ this._inflate.flush(() => {
17320
+ const err = this._inflate[kError];
17321
+ if (err) {
17322
+ this._inflate.close();
17323
+ this._inflate = null;
17324
+ callback(err);
17325
+ return;
17326
+ }
17327
+ const data2 = bufferUtil.concat(
17328
+ this._inflate[kBuffers],
17329
+ this._inflate[kTotalLength]
17330
+ );
17331
+ if (this._inflate._readableState.endEmitted) {
17332
+ this._inflate.close();
17333
+ this._inflate = null;
17334
+ } else {
17335
+ this._inflate[kTotalLength] = 0;
17336
+ this._inflate[kBuffers] = [];
17337
+ if (fin && this.params[`${endpoint}_no_context_takeover`]) {
17338
+ this._inflate.reset();
17339
+ }
17340
+ }
17341
+ callback(null, data2);
17342
+ });
17343
+ }
17344
+ /**
17345
+ * Compress data.
17346
+ *
17347
+ * @param {(Buffer|String)} data Data to compress
17348
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
17349
+ * @param {Function} callback Callback
17350
+ * @private
17351
+ */
17352
+ _compress(data, fin, callback) {
17353
+ const endpoint = this._isServer ? "server" : "client";
17354
+ if (!this._deflate) {
17355
+ const key = `${endpoint}_max_window_bits`;
17356
+ const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
17357
+ this._deflate = zlib.createDeflateRaw({
17358
+ ...this._options.zlibDeflateOptions,
17359
+ windowBits
17360
+ });
17361
+ this._deflate[kTotalLength] = 0;
17362
+ this._deflate[kBuffers] = [];
17363
+ this._deflate.on("data", deflateOnData);
17364
+ }
17365
+ this._deflate[kCallback] = callback;
17366
+ this._deflate.write(data);
17367
+ this._deflate.flush(zlib.Z_SYNC_FLUSH, () => {
17368
+ if (!this._deflate) {
17369
+ return;
17370
+ }
17371
+ let data2 = bufferUtil.concat(
17372
+ this._deflate[kBuffers],
17373
+ this._deflate[kTotalLength]
17374
+ );
17375
+ if (fin) {
17376
+ data2 = new FastBuffer(data2.buffer, data2.byteOffset, data2.length - 4);
17377
+ }
17378
+ this._deflate[kCallback] = null;
17379
+ this._deflate[kTotalLength] = 0;
17380
+ this._deflate[kBuffers] = [];
17381
+ if (fin && this.params[`${endpoint}_no_context_takeover`]) {
17382
+ this._deflate.reset();
17383
+ }
17384
+ callback(null, data2);
17385
+ });
17386
+ }
17387
+ };
17388
+ module.exports = PerMessageDeflate;
17389
+ function deflateOnData(chunk) {
17390
+ this[kBuffers].push(chunk);
17391
+ this[kTotalLength] += chunk.length;
17392
+ }
17393
+ function inflateOnData(chunk) {
17394
+ this[kTotalLength] += chunk.length;
17395
+ if (this[kPerMessageDeflate]._maxPayload < 1 || this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload) {
17396
+ this[kBuffers].push(chunk);
17397
+ return;
17398
+ }
17399
+ this[kError] = new RangeError("Max payload size exceeded");
17400
+ this[kError].code = "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH";
17401
+ this[kError][kStatusCode] = 1009;
17402
+ this.removeListener("data", inflateOnData);
17403
+ this.reset();
17404
+ }
17405
+ function inflateOnError(err) {
17406
+ this[kPerMessageDeflate]._inflate = null;
17407
+ if (this[kError]) {
17408
+ this[kCallback](this[kError]);
17409
+ return;
17410
+ }
17411
+ err[kStatusCode] = 1007;
17412
+ this[kCallback](err);
17413
+ }
17414
+ }
17415
+ });
17416
+
17417
+ // node_modules/.pnpm/ws@8.19.0/node_modules/ws/lib/validation.js
17418
+ var require_validation = __commonJS({
17419
+ "node_modules/.pnpm/ws@8.19.0/node_modules/ws/lib/validation.js"(exports, module) {
17420
+ "use strict";
17421
+ var { isUtf8 } = __require("buffer");
17422
+ var { hasBlob } = require_constants();
17423
+ var tokenChars = [
17424
+ 0,
17425
+ 0,
17426
+ 0,
17427
+ 0,
17428
+ 0,
17429
+ 0,
17430
+ 0,
17431
+ 0,
17432
+ 0,
17433
+ 0,
17434
+ 0,
17435
+ 0,
17436
+ 0,
17437
+ 0,
17438
+ 0,
17439
+ 0,
17440
+ // 0 - 15
17441
+ 0,
17442
+ 0,
17443
+ 0,
17444
+ 0,
17445
+ 0,
17446
+ 0,
17447
+ 0,
17448
+ 0,
17449
+ 0,
17450
+ 0,
17451
+ 0,
17452
+ 0,
17453
+ 0,
17454
+ 0,
17455
+ 0,
17456
+ 0,
17457
+ // 16 - 31
17458
+ 0,
17459
+ 1,
17460
+ 0,
17461
+ 1,
17462
+ 1,
17463
+ 1,
17464
+ 1,
17465
+ 1,
17466
+ 0,
17467
+ 0,
17468
+ 1,
17469
+ 1,
17470
+ 0,
17471
+ 1,
17472
+ 1,
17473
+ 0,
17474
+ // 32 - 47
17475
+ 1,
17476
+ 1,
17477
+ 1,
17478
+ 1,
17479
+ 1,
17480
+ 1,
17481
+ 1,
17482
+ 1,
17483
+ 1,
17484
+ 1,
17485
+ 0,
17486
+ 0,
17487
+ 0,
17488
+ 0,
17489
+ 0,
17490
+ 0,
17491
+ // 48 - 63
17492
+ 0,
17493
+ 1,
17494
+ 1,
17495
+ 1,
17496
+ 1,
17497
+ 1,
17498
+ 1,
17499
+ 1,
17500
+ 1,
17501
+ 1,
17502
+ 1,
17503
+ 1,
17504
+ 1,
17505
+ 1,
17506
+ 1,
17507
+ 1,
17508
+ // 64 - 79
17509
+ 1,
17510
+ 1,
17511
+ 1,
17512
+ 1,
17513
+ 1,
17514
+ 1,
17515
+ 1,
17516
+ 1,
17517
+ 1,
17518
+ 1,
17519
+ 1,
17520
+ 0,
17521
+ 0,
17522
+ 0,
17523
+ 1,
17524
+ 1,
17525
+ // 80 - 95
17526
+ 1,
17527
+ 1,
17528
+ 1,
17529
+ 1,
17530
+ 1,
17531
+ 1,
17532
+ 1,
17533
+ 1,
17534
+ 1,
17535
+ 1,
17536
+ 1,
17537
+ 1,
17538
+ 1,
17539
+ 1,
17540
+ 1,
17541
+ 1,
17542
+ // 96 - 111
17543
+ 1,
17544
+ 1,
17545
+ 1,
17546
+ 1,
17547
+ 1,
17548
+ 1,
17549
+ 1,
17550
+ 1,
17551
+ 1,
17552
+ 1,
17553
+ 1,
17554
+ 0,
17555
+ 1,
17556
+ 0,
17557
+ 1,
17558
+ 0
17559
+ // 112 - 127
17560
+ ];
17561
+ function isValidStatusCode(code) {
17562
+ return code >= 1e3 && code <= 1014 && code !== 1004 && code !== 1005 && code !== 1006 || code >= 3e3 && code <= 4999;
17563
+ }
17564
+ function _isValidUTF8(buf) {
17565
+ const len = buf.length;
17566
+ let i = 0;
17567
+ while (i < len) {
17568
+ if ((buf[i] & 128) === 0) {
17569
+ i++;
17570
+ } else if ((buf[i] & 224) === 192) {
17571
+ if (i + 1 === len || (buf[i + 1] & 192) !== 128 || (buf[i] & 254) === 192) {
17572
+ return false;
17573
+ }
17574
+ i += 2;
17575
+ } else if ((buf[i] & 240) === 224) {
17576
+ if (i + 2 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || buf[i] === 224 && (buf[i + 1] & 224) === 128 || // Overlong
17577
+ buf[i] === 237 && (buf[i + 1] & 224) === 160) {
17578
+ return false;
17579
+ }
17580
+ i += 3;
17581
+ } else if ((buf[i] & 248) === 240) {
17582
+ if (i + 3 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || (buf[i + 3] & 192) !== 128 || buf[i] === 240 && (buf[i + 1] & 240) === 128 || // Overlong
17583
+ buf[i] === 244 && buf[i + 1] > 143 || buf[i] > 244) {
17584
+ return false;
17585
+ }
17586
+ i += 4;
17587
+ } else {
17588
+ return false;
17589
+ }
17590
+ }
17591
+ return true;
17592
+ }
17593
+ function isBlob(value) {
17594
+ 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");
17595
+ }
17596
+ module.exports = {
17597
+ isBlob,
17598
+ isValidStatusCode,
17599
+ isValidUTF8: _isValidUTF8,
17600
+ tokenChars
17601
+ };
17602
+ if (isUtf8) {
17603
+ module.exports.isValidUTF8 = function(buf) {
17604
+ return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf);
17605
+ };
17606
+ } else if (!process.env.WS_NO_UTF_8_VALIDATE) {
17607
+ try {
17608
+ const isValidUTF8 = __require("utf-8-validate");
17609
+ module.exports.isValidUTF8 = function(buf) {
17610
+ return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf);
17611
+ };
17612
+ } catch (e) {
17613
+ }
17614
+ }
17615
+ }
17616
+ });
17617
+
17618
+ // node_modules/.pnpm/ws@8.19.0/node_modules/ws/lib/receiver.js
17619
+ var require_receiver = __commonJS({
17620
+ "node_modules/.pnpm/ws@8.19.0/node_modules/ws/lib/receiver.js"(exports, module) {
17621
+ "use strict";
17622
+ var { Writable: Writable2 } = __require("stream");
17623
+ var PerMessageDeflate = require_permessage_deflate();
17624
+ var {
17625
+ BINARY_TYPES,
17626
+ EMPTY_BUFFER,
17627
+ kStatusCode,
17628
+ kWebSocket
17629
+ } = require_constants();
17630
+ var { concat, toArrayBuffer, unmask } = require_buffer_util();
17631
+ var { isValidStatusCode, isValidUTF8 } = require_validation();
17632
+ var FastBuffer = Buffer[Symbol.species];
17633
+ var GET_INFO = 0;
17634
+ var GET_PAYLOAD_LENGTH_16 = 1;
17635
+ var GET_PAYLOAD_LENGTH_64 = 2;
17636
+ var GET_MASK = 3;
17637
+ var GET_DATA = 4;
17638
+ var INFLATING = 5;
17639
+ var DEFER_EVENT = 6;
17640
+ var Receiver2 = class extends Writable2 {
17641
+ /**
17642
+ * Creates a Receiver instance.
17643
+ *
17644
+ * @param {Object} [options] Options object
17645
+ * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
17646
+ * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
17647
+ * multiple times in the same tick
17648
+ * @param {String} [options.binaryType=nodebuffer] The type for binary data
17649
+ * @param {Object} [options.extensions] An object containing the negotiated
17650
+ * extensions
17651
+ * @param {Boolean} [options.isServer=false] Specifies whether to operate in
17652
+ * client or server mode
17653
+ * @param {Number} [options.maxPayload=0] The maximum allowed message length
17654
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
17655
+ * not to skip UTF-8 validation for text and close messages
17656
+ */
17657
+ constructor(options = {}) {
17658
+ super();
17659
+ this._allowSynchronousEvents = options.allowSynchronousEvents !== void 0 ? options.allowSynchronousEvents : true;
17660
+ this._binaryType = options.binaryType || BINARY_TYPES[0];
17661
+ this._extensions = options.extensions || {};
17662
+ this._isServer = !!options.isServer;
17663
+ this._maxPayload = options.maxPayload | 0;
17664
+ this._skipUTF8Validation = !!options.skipUTF8Validation;
17665
+ this[kWebSocket] = void 0;
17666
+ this._bufferedBytes = 0;
17667
+ this._buffers = [];
17668
+ this._compressed = false;
17669
+ this._payloadLength = 0;
17670
+ this._mask = void 0;
17671
+ this._fragmented = 0;
17672
+ this._masked = false;
17673
+ this._fin = false;
17674
+ this._opcode = 0;
17675
+ this._totalPayloadLength = 0;
17676
+ this._messageLength = 0;
17677
+ this._fragments = [];
17678
+ this._errored = false;
17679
+ this._loop = false;
17680
+ this._state = GET_INFO;
17681
+ }
17682
+ /**
17683
+ * Implements `Writable.prototype._write()`.
17684
+ *
17685
+ * @param {Buffer} chunk The chunk of data to write
17686
+ * @param {String} encoding The character encoding of `chunk`
17687
+ * @param {Function} cb Callback
17688
+ * @private
17689
+ */
17690
+ _write(chunk, encoding, cb) {
17691
+ if (this._opcode === 8 && this._state == GET_INFO) return cb();
17692
+ this._bufferedBytes += chunk.length;
17693
+ this._buffers.push(chunk);
17694
+ this.startLoop(cb);
17695
+ }
17696
+ /**
17697
+ * Consumes `n` bytes from the buffered data.
17698
+ *
17699
+ * @param {Number} n The number of bytes to consume
17700
+ * @return {Buffer} The consumed bytes
17701
+ * @private
17702
+ */
17703
+ consume(n) {
17704
+ this._bufferedBytes -= n;
17705
+ if (n === this._buffers[0].length) return this._buffers.shift();
17706
+ if (n < this._buffers[0].length) {
17707
+ const buf = this._buffers[0];
17708
+ this._buffers[0] = new FastBuffer(
17709
+ buf.buffer,
17710
+ buf.byteOffset + n,
17711
+ buf.length - n
17712
+ );
17713
+ return new FastBuffer(buf.buffer, buf.byteOffset, n);
17714
+ }
17715
+ const dst = Buffer.allocUnsafe(n);
17716
+ do {
17717
+ const buf = this._buffers[0];
17718
+ const offset = dst.length - n;
17719
+ if (n >= buf.length) {
17720
+ dst.set(this._buffers.shift(), offset);
17721
+ } else {
17722
+ dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset);
17723
+ this._buffers[0] = new FastBuffer(
17724
+ buf.buffer,
17725
+ buf.byteOffset + n,
17726
+ buf.length - n
17727
+ );
17728
+ }
17729
+ n -= buf.length;
17730
+ } while (n > 0);
17731
+ return dst;
17732
+ }
17733
+ /**
17734
+ * Starts the parsing loop.
17735
+ *
17736
+ * @param {Function} cb Callback
17737
+ * @private
17738
+ */
17739
+ startLoop(cb) {
17740
+ this._loop = true;
17741
+ do {
17742
+ switch (this._state) {
17743
+ case GET_INFO:
17744
+ this.getInfo(cb);
17745
+ break;
17746
+ case GET_PAYLOAD_LENGTH_16:
17747
+ this.getPayloadLength16(cb);
17748
+ break;
17749
+ case GET_PAYLOAD_LENGTH_64:
17750
+ this.getPayloadLength64(cb);
17751
+ break;
17752
+ case GET_MASK:
17753
+ this.getMask();
17754
+ break;
17755
+ case GET_DATA:
17756
+ this.getData(cb);
17757
+ break;
17758
+ case INFLATING:
17759
+ case DEFER_EVENT:
17760
+ this._loop = false;
17761
+ return;
17762
+ }
17763
+ } while (this._loop);
17764
+ if (!this._errored) cb();
17765
+ }
17766
+ /**
17767
+ * Reads the first two bytes of a frame.
17768
+ *
17769
+ * @param {Function} cb Callback
17770
+ * @private
17771
+ */
17772
+ getInfo(cb) {
17773
+ if (this._bufferedBytes < 2) {
17774
+ this._loop = false;
17775
+ return;
17776
+ }
17777
+ const buf = this.consume(2);
17778
+ if ((buf[0] & 48) !== 0) {
17779
+ const error = this.createError(
17780
+ RangeError,
17781
+ "RSV2 and RSV3 must be clear",
17782
+ true,
17783
+ 1002,
17784
+ "WS_ERR_UNEXPECTED_RSV_2_3"
17785
+ );
17786
+ cb(error);
17787
+ return;
17788
+ }
17789
+ const compressed = (buf[0] & 64) === 64;
17790
+ if (compressed && !this._extensions[PerMessageDeflate.extensionName]) {
17791
+ const error = this.createError(
17792
+ RangeError,
17793
+ "RSV1 must be clear",
17794
+ true,
17795
+ 1002,
17796
+ "WS_ERR_UNEXPECTED_RSV_1"
17797
+ );
17798
+ cb(error);
17799
+ return;
17800
+ }
17801
+ this._fin = (buf[0] & 128) === 128;
17802
+ this._opcode = buf[0] & 15;
17803
+ this._payloadLength = buf[1] & 127;
17804
+ if (this._opcode === 0) {
17805
+ if (compressed) {
17806
+ const error = this.createError(
17807
+ RangeError,
17808
+ "RSV1 must be clear",
17809
+ true,
17810
+ 1002,
17811
+ "WS_ERR_UNEXPECTED_RSV_1"
17812
+ );
17813
+ cb(error);
17814
+ return;
17815
+ }
17816
+ if (!this._fragmented) {
17817
+ const error = this.createError(
17818
+ RangeError,
17819
+ "invalid opcode 0",
17820
+ true,
17821
+ 1002,
17822
+ "WS_ERR_INVALID_OPCODE"
17823
+ );
17824
+ cb(error);
17825
+ return;
17826
+ }
17827
+ this._opcode = this._fragmented;
17828
+ } else if (this._opcode === 1 || this._opcode === 2) {
17829
+ if (this._fragmented) {
17830
+ const error = this.createError(
17831
+ RangeError,
17832
+ `invalid opcode ${this._opcode}`,
17833
+ true,
17834
+ 1002,
17835
+ "WS_ERR_INVALID_OPCODE"
17836
+ );
17837
+ cb(error);
17838
+ return;
17839
+ }
17840
+ this._compressed = compressed;
17841
+ } else if (this._opcode > 7 && this._opcode < 11) {
17842
+ if (!this._fin) {
17843
+ const error = this.createError(
17844
+ RangeError,
17845
+ "FIN must be set",
17846
+ true,
17847
+ 1002,
17848
+ "WS_ERR_EXPECTED_FIN"
17849
+ );
17850
+ cb(error);
17851
+ return;
17852
+ }
17853
+ if (compressed) {
17854
+ const error = this.createError(
17855
+ RangeError,
17856
+ "RSV1 must be clear",
17857
+ true,
17858
+ 1002,
17859
+ "WS_ERR_UNEXPECTED_RSV_1"
17860
+ );
17861
+ cb(error);
17862
+ return;
17863
+ }
17864
+ if (this._payloadLength > 125 || this._opcode === 8 && this._payloadLength === 1) {
17865
+ const error = this.createError(
17866
+ RangeError,
17867
+ `invalid payload length ${this._payloadLength}`,
17868
+ true,
17869
+ 1002,
17870
+ "WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH"
17871
+ );
17872
+ cb(error);
17873
+ return;
17874
+ }
17875
+ } else {
17876
+ const error = this.createError(
17877
+ RangeError,
17878
+ `invalid opcode ${this._opcode}`,
17879
+ true,
17880
+ 1002,
17881
+ "WS_ERR_INVALID_OPCODE"
17882
+ );
17883
+ cb(error);
17884
+ return;
17885
+ }
17886
+ if (!this._fin && !this._fragmented) this._fragmented = this._opcode;
17887
+ this._masked = (buf[1] & 128) === 128;
17888
+ if (this._isServer) {
17889
+ if (!this._masked) {
17890
+ const error = this.createError(
17891
+ RangeError,
17892
+ "MASK must be set",
17893
+ true,
17894
+ 1002,
17895
+ "WS_ERR_EXPECTED_MASK"
17896
+ );
17897
+ cb(error);
17898
+ return;
17899
+ }
17900
+ } else if (this._masked) {
17901
+ const error = this.createError(
17902
+ RangeError,
17903
+ "MASK must be clear",
17904
+ true,
17905
+ 1002,
17906
+ "WS_ERR_UNEXPECTED_MASK"
17907
+ );
17908
+ cb(error);
17909
+ return;
17910
+ }
17911
+ if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16;
17912
+ else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64;
17913
+ else this.haveLength(cb);
17914
+ }
17915
+ /**
17916
+ * Gets extended payload length (7+16).
17917
+ *
17918
+ * @param {Function} cb Callback
17919
+ * @private
17920
+ */
17921
+ getPayloadLength16(cb) {
17922
+ if (this._bufferedBytes < 2) {
17923
+ this._loop = false;
17924
+ return;
17925
+ }
17926
+ this._payloadLength = this.consume(2).readUInt16BE(0);
17927
+ this.haveLength(cb);
17928
+ }
17929
+ /**
17930
+ * Gets extended payload length (7+64).
17931
+ *
17932
+ * @param {Function} cb Callback
17933
+ * @private
17934
+ */
17935
+ getPayloadLength64(cb) {
17936
+ if (this._bufferedBytes < 8) {
17937
+ this._loop = false;
17938
+ return;
17939
+ }
17940
+ const buf = this.consume(8);
17941
+ const num = buf.readUInt32BE(0);
17942
+ if (num > Math.pow(2, 53 - 32) - 1) {
17943
+ const error = this.createError(
17944
+ RangeError,
17945
+ "Unsupported WebSocket frame: payload length > 2^53 - 1",
17946
+ false,
17947
+ 1009,
17948
+ "WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH"
17949
+ );
17950
+ cb(error);
17951
+ return;
17952
+ }
17953
+ this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4);
17954
+ this.haveLength(cb);
17955
+ }
17956
+ /**
17957
+ * Payload length has been read.
17958
+ *
17959
+ * @param {Function} cb Callback
17960
+ * @private
17961
+ */
17962
+ haveLength(cb) {
17963
+ if (this._payloadLength && this._opcode < 8) {
17964
+ this._totalPayloadLength += this._payloadLength;
17965
+ if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) {
17966
+ const error = this.createError(
17967
+ RangeError,
17968
+ "Max payload size exceeded",
17969
+ false,
17970
+ 1009,
17971
+ "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"
17972
+ );
17973
+ cb(error);
17974
+ return;
17975
+ }
17976
+ }
17977
+ if (this._masked) this._state = GET_MASK;
17978
+ else this._state = GET_DATA;
17979
+ }
17980
+ /**
17981
+ * Reads mask bytes.
17982
+ *
17983
+ * @private
17984
+ */
17985
+ getMask() {
17986
+ if (this._bufferedBytes < 4) {
17987
+ this._loop = false;
17988
+ return;
17989
+ }
17990
+ this._mask = this.consume(4);
17991
+ this._state = GET_DATA;
17992
+ }
17993
+ /**
17994
+ * Reads data bytes.
17995
+ *
17996
+ * @param {Function} cb Callback
17997
+ * @private
17998
+ */
17999
+ getData(cb) {
18000
+ let data = EMPTY_BUFFER;
18001
+ if (this._payloadLength) {
18002
+ if (this._bufferedBytes < this._payloadLength) {
18003
+ this._loop = false;
18004
+ return;
18005
+ }
18006
+ data = this.consume(this._payloadLength);
18007
+ if (this._masked && (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0) {
18008
+ unmask(data, this._mask);
18009
+ }
18010
+ }
18011
+ if (this._opcode > 7) {
18012
+ this.controlMessage(data, cb);
18013
+ return;
18014
+ }
18015
+ if (this._compressed) {
18016
+ this._state = INFLATING;
18017
+ this.decompress(data, cb);
18018
+ return;
18019
+ }
18020
+ if (data.length) {
18021
+ this._messageLength = this._totalPayloadLength;
18022
+ this._fragments.push(data);
18023
+ }
18024
+ this.dataMessage(cb);
18025
+ }
18026
+ /**
18027
+ * Decompresses data.
18028
+ *
18029
+ * @param {Buffer} data Compressed data
18030
+ * @param {Function} cb Callback
18031
+ * @private
18032
+ */
18033
+ decompress(data, cb) {
18034
+ const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
18035
+ perMessageDeflate.decompress(data, this._fin, (err, buf) => {
18036
+ if (err) return cb(err);
18037
+ if (buf.length) {
18038
+ this._messageLength += buf.length;
18039
+ if (this._messageLength > this._maxPayload && this._maxPayload > 0) {
18040
+ const error = this.createError(
18041
+ RangeError,
18042
+ "Max payload size exceeded",
18043
+ false,
18044
+ 1009,
18045
+ "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"
18046
+ );
18047
+ cb(error);
18048
+ return;
18049
+ }
18050
+ this._fragments.push(buf);
18051
+ }
18052
+ this.dataMessage(cb);
18053
+ if (this._state === GET_INFO) this.startLoop(cb);
18054
+ });
18055
+ }
18056
+ /**
18057
+ * Handles a data message.
18058
+ *
18059
+ * @param {Function} cb Callback
18060
+ * @private
18061
+ */
18062
+ dataMessage(cb) {
18063
+ if (!this._fin) {
18064
+ this._state = GET_INFO;
18065
+ return;
18066
+ }
18067
+ const messageLength = this._messageLength;
18068
+ const fragments = this._fragments;
18069
+ this._totalPayloadLength = 0;
18070
+ this._messageLength = 0;
18071
+ this._fragmented = 0;
18072
+ this._fragments = [];
18073
+ if (this._opcode === 2) {
18074
+ let data;
18075
+ if (this._binaryType === "nodebuffer") {
18076
+ data = concat(fragments, messageLength);
18077
+ } else if (this._binaryType === "arraybuffer") {
18078
+ data = toArrayBuffer(concat(fragments, messageLength));
18079
+ } else if (this._binaryType === "blob") {
18080
+ data = new Blob(fragments);
18081
+ } else {
18082
+ data = fragments;
18083
+ }
18084
+ if (this._allowSynchronousEvents) {
18085
+ this.emit("message", data, true);
18086
+ this._state = GET_INFO;
18087
+ } else {
18088
+ this._state = DEFER_EVENT;
18089
+ setImmediate(() => {
18090
+ this.emit("message", data, true);
18091
+ this._state = GET_INFO;
18092
+ this.startLoop(cb);
18093
+ });
18094
+ }
18095
+ } else {
18096
+ const buf = concat(fragments, messageLength);
18097
+ if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
18098
+ const error = this.createError(
18099
+ Error,
18100
+ "invalid UTF-8 sequence",
18101
+ true,
18102
+ 1007,
18103
+ "WS_ERR_INVALID_UTF8"
18104
+ );
18105
+ cb(error);
18106
+ return;
18107
+ }
18108
+ if (this._state === INFLATING || this._allowSynchronousEvents) {
18109
+ this.emit("message", buf, false);
18110
+ this._state = GET_INFO;
18111
+ } else {
18112
+ this._state = DEFER_EVENT;
18113
+ setImmediate(() => {
18114
+ this.emit("message", buf, false);
18115
+ this._state = GET_INFO;
18116
+ this.startLoop(cb);
18117
+ });
18118
+ }
18119
+ }
18120
+ }
18121
+ /**
18122
+ * Handles a control message.
18123
+ *
18124
+ * @param {Buffer} data Data to handle
18125
+ * @return {(Error|RangeError|undefined)} A possible error
18126
+ * @private
18127
+ */
18128
+ controlMessage(data, cb) {
18129
+ if (this._opcode === 8) {
18130
+ if (data.length === 0) {
18131
+ this._loop = false;
18132
+ this.emit("conclude", 1005, EMPTY_BUFFER);
18133
+ this.end();
18134
+ } else {
18135
+ const code = data.readUInt16BE(0);
18136
+ if (!isValidStatusCode(code)) {
18137
+ const error = this.createError(
18138
+ RangeError,
18139
+ `invalid status code ${code}`,
18140
+ true,
18141
+ 1002,
18142
+ "WS_ERR_INVALID_CLOSE_CODE"
18143
+ );
18144
+ cb(error);
18145
+ return;
18146
+ }
18147
+ const buf = new FastBuffer(
18148
+ data.buffer,
18149
+ data.byteOffset + 2,
18150
+ data.length - 2
18151
+ );
18152
+ if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
18153
+ const error = this.createError(
18154
+ Error,
18155
+ "invalid UTF-8 sequence",
18156
+ true,
18157
+ 1007,
18158
+ "WS_ERR_INVALID_UTF8"
18159
+ );
18160
+ cb(error);
18161
+ return;
18162
+ }
18163
+ this._loop = false;
18164
+ this.emit("conclude", code, buf);
18165
+ this.end();
18166
+ }
18167
+ this._state = GET_INFO;
18168
+ return;
18169
+ }
18170
+ if (this._allowSynchronousEvents) {
18171
+ this.emit(this._opcode === 9 ? "ping" : "pong", data);
18172
+ this._state = GET_INFO;
18173
+ } else {
18174
+ this._state = DEFER_EVENT;
18175
+ setImmediate(() => {
18176
+ this.emit(this._opcode === 9 ? "ping" : "pong", data);
18177
+ this._state = GET_INFO;
18178
+ this.startLoop(cb);
18179
+ });
18180
+ }
18181
+ }
18182
+ /**
18183
+ * Builds an error object.
18184
+ *
18185
+ * @param {function(new:Error|RangeError)} ErrorCtor The error constructor
18186
+ * @param {String} message The error message
18187
+ * @param {Boolean} prefix Specifies whether or not to add a default prefix to
18188
+ * `message`
18189
+ * @param {Number} statusCode The status code
18190
+ * @param {String} errorCode The exposed error code
18191
+ * @return {(Error|RangeError)} The error
18192
+ * @private
18193
+ */
18194
+ createError(ErrorCtor, message, prefix, statusCode, errorCode) {
18195
+ this._loop = false;
18196
+ this._errored = true;
18197
+ const err = new ErrorCtor(
18198
+ prefix ? `Invalid WebSocket frame: ${message}` : message
18199
+ );
18200
+ Error.captureStackTrace(err, this.createError);
18201
+ err.code = errorCode;
18202
+ err[kStatusCode] = statusCode;
18203
+ return err;
18204
+ }
18205
+ };
18206
+ module.exports = Receiver2;
18207
+ }
18208
+ });
18209
+
18210
+ // node_modules/.pnpm/ws@8.19.0/node_modules/ws/lib/sender.js
18211
+ var require_sender = __commonJS({
18212
+ "node_modules/.pnpm/ws@8.19.0/node_modules/ws/lib/sender.js"(exports, module) {
18213
+ "use strict";
18214
+ var { Duplex } = __require("stream");
18215
+ var { randomFillSync } = __require("crypto");
18216
+ var PerMessageDeflate = require_permessage_deflate();
18217
+ var { EMPTY_BUFFER, kWebSocket, NOOP } = require_constants();
18218
+ var { isBlob, isValidStatusCode } = require_validation();
18219
+ var { mask: applyMask, toBuffer } = require_buffer_util();
18220
+ var kByteLength = /* @__PURE__ */ Symbol("kByteLength");
18221
+ var maskBuffer = Buffer.alloc(4);
18222
+ var RANDOM_POOL_SIZE = 8 * 1024;
18223
+ var randomPool;
18224
+ var randomPoolPointer = RANDOM_POOL_SIZE;
18225
+ var DEFAULT = 0;
18226
+ var DEFLATING = 1;
18227
+ var GET_BLOB_DATA = 2;
18228
+ var Sender2 = class _Sender {
18229
+ /**
18230
+ * Creates a Sender instance.
18231
+ *
18232
+ * @param {Duplex} socket The connection socket
18233
+ * @param {Object} [extensions] An object containing the negotiated extensions
18234
+ * @param {Function} [generateMask] The function used to generate the masking
18235
+ * key
18236
+ */
18237
+ constructor(socket, extensions, generateMask) {
18238
+ this._extensions = extensions || {};
18239
+ if (generateMask) {
18240
+ this._generateMask = generateMask;
18241
+ this._maskBuffer = Buffer.alloc(4);
18242
+ }
18243
+ this._socket = socket;
18244
+ this._firstFragment = true;
18245
+ this._compress = false;
18246
+ this._bufferedBytes = 0;
18247
+ this._queue = [];
18248
+ this._state = DEFAULT;
18249
+ this.onerror = NOOP;
18250
+ this[kWebSocket] = void 0;
18251
+ }
18252
+ /**
18253
+ * Frames a piece of data according to the HyBi WebSocket protocol.
18254
+ *
18255
+ * @param {(Buffer|String)} data The data to frame
18256
+ * @param {Object} options Options object
18257
+ * @param {Boolean} [options.fin=false] Specifies whether or not to set the
18258
+ * FIN bit
18259
+ * @param {Function} [options.generateMask] The function used to generate the
18260
+ * masking key
18261
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
18262
+ * `data`
18263
+ * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
18264
+ * key
18265
+ * @param {Number} options.opcode The opcode
18266
+ * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
18267
+ * modified
18268
+ * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
18269
+ * RSV1 bit
18270
+ * @return {(Buffer|String)[]} The framed data
18271
+ * @public
18272
+ */
18273
+ static frame(data, options) {
18274
+ let mask;
18275
+ let merge = false;
18276
+ let offset = 2;
18277
+ let skipMasking = false;
18278
+ if (options.mask) {
18279
+ mask = options.maskBuffer || maskBuffer;
18280
+ if (options.generateMask) {
18281
+ options.generateMask(mask);
18282
+ } else {
18283
+ if (randomPoolPointer === RANDOM_POOL_SIZE) {
18284
+ if (randomPool === void 0) {
18285
+ randomPool = Buffer.alloc(RANDOM_POOL_SIZE);
18286
+ }
18287
+ randomFillSync(randomPool, 0, RANDOM_POOL_SIZE);
18288
+ randomPoolPointer = 0;
18289
+ }
18290
+ mask[0] = randomPool[randomPoolPointer++];
18291
+ mask[1] = randomPool[randomPoolPointer++];
18292
+ mask[2] = randomPool[randomPoolPointer++];
18293
+ mask[3] = randomPool[randomPoolPointer++];
18294
+ }
18295
+ skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0;
18296
+ offset = 6;
18297
+ }
18298
+ let dataLength;
18299
+ if (typeof data === "string") {
18300
+ if ((!options.mask || skipMasking) && options[kByteLength] !== void 0) {
18301
+ dataLength = options[kByteLength];
18302
+ } else {
18303
+ data = Buffer.from(data);
18304
+ dataLength = data.length;
18305
+ }
18306
+ } else {
18307
+ dataLength = data.length;
18308
+ merge = options.mask && options.readOnly && !skipMasking;
18309
+ }
18310
+ let payloadLength = dataLength;
18311
+ if (dataLength >= 65536) {
18312
+ offset += 8;
18313
+ payloadLength = 127;
18314
+ } else if (dataLength > 125) {
18315
+ offset += 2;
18316
+ payloadLength = 126;
18317
+ }
18318
+ const target = Buffer.allocUnsafe(merge ? dataLength + offset : offset);
18319
+ target[0] = options.fin ? options.opcode | 128 : options.opcode;
18320
+ if (options.rsv1) target[0] |= 64;
18321
+ target[1] = payloadLength;
18322
+ if (payloadLength === 126) {
18323
+ target.writeUInt16BE(dataLength, 2);
18324
+ } else if (payloadLength === 127) {
18325
+ target[2] = target[3] = 0;
18326
+ target.writeUIntBE(dataLength, 4, 6);
18327
+ }
18328
+ if (!options.mask) return [target, data];
18329
+ target[1] |= 128;
18330
+ target[offset - 4] = mask[0];
18331
+ target[offset - 3] = mask[1];
18332
+ target[offset - 2] = mask[2];
18333
+ target[offset - 1] = mask[3];
18334
+ if (skipMasking) return [target, data];
18335
+ if (merge) {
18336
+ applyMask(data, mask, target, offset, dataLength);
18337
+ return [target];
18338
+ }
18339
+ applyMask(data, mask, data, 0, dataLength);
18340
+ return [target, data];
18341
+ }
18342
+ /**
18343
+ * Sends a close message to the other peer.
18344
+ *
18345
+ * @param {Number} [code] The status code component of the body
18346
+ * @param {(String|Buffer)} [data] The message component of the body
18347
+ * @param {Boolean} [mask=false] Specifies whether or not to mask the message
18348
+ * @param {Function} [cb] Callback
18349
+ * @public
18350
+ */
18351
+ close(code, data, mask, cb) {
18352
+ let buf;
18353
+ if (code === void 0) {
18354
+ buf = EMPTY_BUFFER;
18355
+ } else if (typeof code !== "number" || !isValidStatusCode(code)) {
18356
+ throw new TypeError("First argument must be a valid error code number");
18357
+ } else if (data === void 0 || !data.length) {
18358
+ buf = Buffer.allocUnsafe(2);
18359
+ buf.writeUInt16BE(code, 0);
18360
+ } else {
18361
+ const length = Buffer.byteLength(data);
18362
+ if (length > 123) {
18363
+ throw new RangeError("The message must not be greater than 123 bytes");
18364
+ }
18365
+ buf = Buffer.allocUnsafe(2 + length);
18366
+ buf.writeUInt16BE(code, 0);
18367
+ if (typeof data === "string") {
18368
+ buf.write(data, 2);
18369
+ } else {
18370
+ buf.set(data, 2);
18371
+ }
18372
+ }
18373
+ const options = {
18374
+ [kByteLength]: buf.length,
18375
+ fin: true,
18376
+ generateMask: this._generateMask,
18377
+ mask,
18378
+ maskBuffer: this._maskBuffer,
18379
+ opcode: 8,
18380
+ readOnly: false,
18381
+ rsv1: false
18382
+ };
18383
+ if (this._state !== DEFAULT) {
18384
+ this.enqueue([this.dispatch, buf, false, options, cb]);
18385
+ } else {
18386
+ this.sendFrame(_Sender.frame(buf, options), cb);
18387
+ }
18388
+ }
18389
+ /**
18390
+ * Sends a ping message to the other peer.
18391
+ *
18392
+ * @param {*} data The message to send
18393
+ * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
18394
+ * @param {Function} [cb] Callback
18395
+ * @public
18396
+ */
18397
+ ping(data, mask, cb) {
18398
+ let byteLength;
18399
+ let readOnly;
18400
+ if (typeof data === "string") {
18401
+ byteLength = Buffer.byteLength(data);
18402
+ readOnly = false;
18403
+ } else if (isBlob(data)) {
18404
+ byteLength = data.size;
18405
+ readOnly = false;
18406
+ } else {
18407
+ data = toBuffer(data);
18408
+ byteLength = data.length;
18409
+ readOnly = toBuffer.readOnly;
18410
+ }
18411
+ if (byteLength > 125) {
18412
+ throw new RangeError("The data size must not be greater than 125 bytes");
18413
+ }
18414
+ const options = {
18415
+ [kByteLength]: byteLength,
18416
+ fin: true,
18417
+ generateMask: this._generateMask,
18418
+ mask,
18419
+ maskBuffer: this._maskBuffer,
18420
+ opcode: 9,
18421
+ readOnly,
18422
+ rsv1: false
18423
+ };
18424
+ if (isBlob(data)) {
18425
+ if (this._state !== DEFAULT) {
18426
+ this.enqueue([this.getBlobData, data, false, options, cb]);
18427
+ } else {
18428
+ this.getBlobData(data, false, options, cb);
18429
+ }
18430
+ } else if (this._state !== DEFAULT) {
18431
+ this.enqueue([this.dispatch, data, false, options, cb]);
18432
+ } else {
18433
+ this.sendFrame(_Sender.frame(data, options), cb);
18434
+ }
18435
+ }
18436
+ /**
18437
+ * Sends a pong message to the other peer.
18438
+ *
18439
+ * @param {*} data The message to send
18440
+ * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
18441
+ * @param {Function} [cb] Callback
18442
+ * @public
18443
+ */
18444
+ pong(data, mask, cb) {
18445
+ let byteLength;
18446
+ let readOnly;
18447
+ if (typeof data === "string") {
18448
+ byteLength = Buffer.byteLength(data);
18449
+ readOnly = false;
18450
+ } else if (isBlob(data)) {
18451
+ byteLength = data.size;
18452
+ readOnly = false;
18453
+ } else {
18454
+ data = toBuffer(data);
18455
+ byteLength = data.length;
18456
+ readOnly = toBuffer.readOnly;
18457
+ }
18458
+ if (byteLength > 125) {
18459
+ throw new RangeError("The data size must not be greater than 125 bytes");
18460
+ }
18461
+ const options = {
18462
+ [kByteLength]: byteLength,
18463
+ fin: true,
18464
+ generateMask: this._generateMask,
18465
+ mask,
18466
+ maskBuffer: this._maskBuffer,
18467
+ opcode: 10,
18468
+ readOnly,
18469
+ rsv1: false
18470
+ };
18471
+ if (isBlob(data)) {
18472
+ if (this._state !== DEFAULT) {
18473
+ this.enqueue([this.getBlobData, data, false, options, cb]);
18474
+ } else {
18475
+ this.getBlobData(data, false, options, cb);
18476
+ }
18477
+ } else if (this._state !== DEFAULT) {
18478
+ this.enqueue([this.dispatch, data, false, options, cb]);
18479
+ } else {
18480
+ this.sendFrame(_Sender.frame(data, options), cb);
18481
+ }
18482
+ }
18483
+ /**
18484
+ * Sends a data message to the other peer.
18485
+ *
18486
+ * @param {*} data The message to send
18487
+ * @param {Object} options Options object
18488
+ * @param {Boolean} [options.binary=false] Specifies whether `data` is binary
18489
+ * or text
18490
+ * @param {Boolean} [options.compress=false] Specifies whether or not to
18491
+ * compress `data`
18492
+ * @param {Boolean} [options.fin=false] Specifies whether the fragment is the
18493
+ * last one
18494
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
18495
+ * `data`
18496
+ * @param {Function} [cb] Callback
18497
+ * @public
18498
+ */
18499
+ send(data, options, cb) {
18500
+ const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
18501
+ let opcode = options.binary ? 2 : 1;
18502
+ let rsv1 = options.compress;
18503
+ let byteLength;
18504
+ let readOnly;
18505
+ if (typeof data === "string") {
18506
+ byteLength = Buffer.byteLength(data);
18507
+ readOnly = false;
18508
+ } else if (isBlob(data)) {
18509
+ byteLength = data.size;
18510
+ readOnly = false;
18511
+ } else {
18512
+ data = toBuffer(data);
18513
+ byteLength = data.length;
18514
+ readOnly = toBuffer.readOnly;
18515
+ }
18516
+ if (this._firstFragment) {
18517
+ this._firstFragment = false;
18518
+ if (rsv1 && perMessageDeflate && perMessageDeflate.params[perMessageDeflate._isServer ? "server_no_context_takeover" : "client_no_context_takeover"]) {
18519
+ rsv1 = byteLength >= perMessageDeflate._threshold;
18520
+ }
18521
+ this._compress = rsv1;
18522
+ } else {
18523
+ rsv1 = false;
18524
+ opcode = 0;
18525
+ }
18526
+ if (options.fin) this._firstFragment = true;
18527
+ const opts = {
18528
+ [kByteLength]: byteLength,
18529
+ fin: options.fin,
18530
+ generateMask: this._generateMask,
18531
+ mask: options.mask,
18532
+ maskBuffer: this._maskBuffer,
18533
+ opcode,
18534
+ readOnly,
18535
+ rsv1
18536
+ };
18537
+ if (isBlob(data)) {
18538
+ if (this._state !== DEFAULT) {
18539
+ this.enqueue([this.getBlobData, data, this._compress, opts, cb]);
18540
+ } else {
18541
+ this.getBlobData(data, this._compress, opts, cb);
18542
+ }
18543
+ } else if (this._state !== DEFAULT) {
18544
+ this.enqueue([this.dispatch, data, this._compress, opts, cb]);
18545
+ } else {
18546
+ this.dispatch(data, this._compress, opts, cb);
18547
+ }
18548
+ }
18549
+ /**
18550
+ * Gets the contents of a blob as binary data.
18551
+ *
18552
+ * @param {Blob} blob The blob
18553
+ * @param {Boolean} [compress=false] Specifies whether or not to compress
18554
+ * the data
18555
+ * @param {Object} options Options object
18556
+ * @param {Boolean} [options.fin=false] Specifies whether or not to set the
18557
+ * FIN bit
18558
+ * @param {Function} [options.generateMask] The function used to generate the
18559
+ * masking key
18560
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
18561
+ * `data`
18562
+ * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
18563
+ * key
18564
+ * @param {Number} options.opcode The opcode
18565
+ * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
18566
+ * modified
18567
+ * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
18568
+ * RSV1 bit
18569
+ * @param {Function} [cb] Callback
18570
+ * @private
18571
+ */
18572
+ getBlobData(blob, compress, options, cb) {
18573
+ this._bufferedBytes += options[kByteLength];
18574
+ this._state = GET_BLOB_DATA;
18575
+ blob.arrayBuffer().then((arrayBuffer) => {
18576
+ if (this._socket.destroyed) {
18577
+ const err = new Error(
18578
+ "The socket was closed while the blob was being read"
18579
+ );
18580
+ process.nextTick(callCallbacks, this, err, cb);
18581
+ return;
18582
+ }
18583
+ this._bufferedBytes -= options[kByteLength];
18584
+ const data = toBuffer(arrayBuffer);
18585
+ if (!compress) {
18586
+ this._state = DEFAULT;
18587
+ this.sendFrame(_Sender.frame(data, options), cb);
18588
+ this.dequeue();
18589
+ } else {
18590
+ this.dispatch(data, compress, options, cb);
18591
+ }
18592
+ }).catch((err) => {
18593
+ process.nextTick(onError, this, err, cb);
18594
+ });
18595
+ }
18596
+ /**
18597
+ * Dispatches a message.
18598
+ *
18599
+ * @param {(Buffer|String)} data The message to send
18600
+ * @param {Boolean} [compress=false] Specifies whether or not to compress
18601
+ * `data`
18602
+ * @param {Object} options Options object
18603
+ * @param {Boolean} [options.fin=false] Specifies whether or not to set the
18604
+ * FIN bit
18605
+ * @param {Function} [options.generateMask] The function used to generate the
18606
+ * masking key
18607
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
18608
+ * `data`
18609
+ * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
18610
+ * key
18611
+ * @param {Number} options.opcode The opcode
18612
+ * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
18613
+ * modified
18614
+ * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
18615
+ * RSV1 bit
18616
+ * @param {Function} [cb] Callback
18617
+ * @private
18618
+ */
18619
+ dispatch(data, compress, options, cb) {
18620
+ if (!compress) {
18621
+ this.sendFrame(_Sender.frame(data, options), cb);
18622
+ return;
18623
+ }
18624
+ const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
18625
+ this._bufferedBytes += options[kByteLength];
18626
+ this._state = DEFLATING;
18627
+ perMessageDeflate.compress(data, options.fin, (_, buf) => {
18628
+ if (this._socket.destroyed) {
18629
+ const err = new Error(
18630
+ "The socket was closed while data was being compressed"
18631
+ );
18632
+ callCallbacks(this, err, cb);
18633
+ return;
18634
+ }
18635
+ this._bufferedBytes -= options[kByteLength];
18636
+ this._state = DEFAULT;
18637
+ options.readOnly = false;
18638
+ this.sendFrame(_Sender.frame(buf, options), cb);
18639
+ this.dequeue();
18640
+ });
18641
+ }
18642
+ /**
18643
+ * Executes queued send operations.
18644
+ *
18645
+ * @private
18646
+ */
18647
+ dequeue() {
18648
+ while (this._state === DEFAULT && this._queue.length) {
18649
+ const params = this._queue.shift();
18650
+ this._bufferedBytes -= params[3][kByteLength];
18651
+ Reflect.apply(params[0], this, params.slice(1));
18652
+ }
18653
+ }
18654
+ /**
18655
+ * Enqueues a send operation.
18656
+ *
18657
+ * @param {Array} params Send operation parameters.
18658
+ * @private
18659
+ */
18660
+ enqueue(params) {
18661
+ this._bufferedBytes += params[3][kByteLength];
18662
+ this._queue.push(params);
18663
+ }
18664
+ /**
18665
+ * Sends a frame.
18666
+ *
18667
+ * @param {(Buffer | String)[]} list The frame to send
18668
+ * @param {Function} [cb] Callback
18669
+ * @private
18670
+ */
18671
+ sendFrame(list, cb) {
18672
+ if (list.length === 2) {
18673
+ this._socket.cork();
18674
+ this._socket.write(list[0]);
18675
+ this._socket.write(list[1], cb);
18676
+ this._socket.uncork();
18677
+ } else {
18678
+ this._socket.write(list[0], cb);
18679
+ }
18680
+ }
18681
+ };
18682
+ module.exports = Sender2;
18683
+ function callCallbacks(sender, err, cb) {
18684
+ if (typeof cb === "function") cb(err);
18685
+ for (let i = 0; i < sender._queue.length; i++) {
18686
+ const params = sender._queue[i];
18687
+ const callback = params[params.length - 1];
18688
+ if (typeof callback === "function") callback(err);
18689
+ }
18690
+ }
18691
+ function onError(sender, err, cb) {
18692
+ callCallbacks(sender, err, cb);
18693
+ sender.onerror(err);
18694
+ }
18695
+ }
18696
+ });
18697
+
18698
+ // node_modules/.pnpm/ws@8.19.0/node_modules/ws/lib/event-target.js
18699
+ var require_event_target = __commonJS({
18700
+ "node_modules/.pnpm/ws@8.19.0/node_modules/ws/lib/event-target.js"(exports, module) {
18701
+ "use strict";
18702
+ var { kForOnEventAttribute, kListener } = require_constants();
18703
+ var kCode = /* @__PURE__ */ Symbol("kCode");
18704
+ var kData = /* @__PURE__ */ Symbol("kData");
18705
+ var kError = /* @__PURE__ */ Symbol("kError");
18706
+ var kMessage = /* @__PURE__ */ Symbol("kMessage");
18707
+ var kReason = /* @__PURE__ */ Symbol("kReason");
18708
+ var kTarget = /* @__PURE__ */ Symbol("kTarget");
18709
+ var kType = /* @__PURE__ */ Symbol("kType");
18710
+ var kWasClean = /* @__PURE__ */ Symbol("kWasClean");
18711
+ var Event = class {
18712
+ /**
18713
+ * Create a new `Event`.
18714
+ *
18715
+ * @param {String} type The name of the event
18716
+ * @throws {TypeError} If the `type` argument is not specified
18717
+ */
18718
+ constructor(type) {
18719
+ this[kTarget] = null;
18720
+ this[kType] = type;
18721
+ }
18722
+ /**
18723
+ * @type {*}
18724
+ */
18725
+ get target() {
18726
+ return this[kTarget];
18727
+ }
18728
+ /**
18729
+ * @type {String}
18730
+ */
18731
+ get type() {
18732
+ return this[kType];
18733
+ }
18734
+ };
18735
+ Object.defineProperty(Event.prototype, "target", { enumerable: true });
18736
+ Object.defineProperty(Event.prototype, "type", { enumerable: true });
18737
+ var CloseEvent = class extends Event {
18738
+ /**
18739
+ * Create a new `CloseEvent`.
18740
+ *
18741
+ * @param {String} type The name of the event
18742
+ * @param {Object} [options] A dictionary object that allows for setting
18743
+ * attributes via object members of the same name
18744
+ * @param {Number} [options.code=0] The status code explaining why the
18745
+ * connection was closed
18746
+ * @param {String} [options.reason=''] A human-readable string explaining why
18747
+ * the connection was closed
18748
+ * @param {Boolean} [options.wasClean=false] Indicates whether or not the
18749
+ * connection was cleanly closed
18750
+ */
18751
+ constructor(type, options = {}) {
18752
+ super(type);
18753
+ this[kCode] = options.code === void 0 ? 0 : options.code;
18754
+ this[kReason] = options.reason === void 0 ? "" : options.reason;
18755
+ this[kWasClean] = options.wasClean === void 0 ? false : options.wasClean;
18756
+ }
18757
+ /**
18758
+ * @type {Number}
18759
+ */
18760
+ get code() {
18761
+ return this[kCode];
18762
+ }
18763
+ /**
18764
+ * @type {String}
18765
+ */
18766
+ get reason() {
18767
+ return this[kReason];
18768
+ }
18769
+ /**
18770
+ * @type {Boolean}
18771
+ */
18772
+ get wasClean() {
18773
+ return this[kWasClean];
18774
+ }
18775
+ };
18776
+ Object.defineProperty(CloseEvent.prototype, "code", { enumerable: true });
18777
+ Object.defineProperty(CloseEvent.prototype, "reason", { enumerable: true });
18778
+ Object.defineProperty(CloseEvent.prototype, "wasClean", { enumerable: true });
18779
+ var ErrorEvent = class extends Event {
18780
+ /**
18781
+ * Create a new `ErrorEvent`.
18782
+ *
18783
+ * @param {String} type The name of the event
18784
+ * @param {Object} [options] A dictionary object that allows for setting
18785
+ * attributes via object members of the same name
18786
+ * @param {*} [options.error=null] The error that generated this event
18787
+ * @param {String} [options.message=''] The error message
18788
+ */
18789
+ constructor(type, options = {}) {
18790
+ super(type);
18791
+ this[kError] = options.error === void 0 ? null : options.error;
18792
+ this[kMessage] = options.message === void 0 ? "" : options.message;
18793
+ }
18794
+ /**
18795
+ * @type {*}
18796
+ */
18797
+ get error() {
18798
+ return this[kError];
18799
+ }
18800
+ /**
18801
+ * @type {String}
18802
+ */
18803
+ get message() {
18804
+ return this[kMessage];
18805
+ }
18806
+ };
18807
+ Object.defineProperty(ErrorEvent.prototype, "error", { enumerable: true });
18808
+ Object.defineProperty(ErrorEvent.prototype, "message", { enumerable: true });
18809
+ var MessageEvent = class extends Event {
18810
+ /**
18811
+ * Create a new `MessageEvent`.
18812
+ *
18813
+ * @param {String} type The name of the event
18814
+ * @param {Object} [options] A dictionary object that allows for setting
18815
+ * attributes via object members of the same name
18816
+ * @param {*} [options.data=null] The message content
18817
+ */
18818
+ constructor(type, options = {}) {
18819
+ super(type);
18820
+ this[kData] = options.data === void 0 ? null : options.data;
18821
+ }
18822
+ /**
18823
+ * @type {*}
18824
+ */
18825
+ get data() {
18826
+ return this[kData];
18827
+ }
18828
+ };
18829
+ Object.defineProperty(MessageEvent.prototype, "data", { enumerable: true });
18830
+ var EventTarget = {
18831
+ /**
18832
+ * Register an event listener.
18833
+ *
18834
+ * @param {String} type A string representing the event type to listen for
18835
+ * @param {(Function|Object)} handler The listener to add
18836
+ * @param {Object} [options] An options object specifies characteristics about
18837
+ * the event listener
18838
+ * @param {Boolean} [options.once=false] A `Boolean` indicating that the
18839
+ * listener should be invoked at most once after being added. If `true`,
18840
+ * the listener would be automatically removed when invoked.
18841
+ * @public
18842
+ */
18843
+ addEventListener(type, handler, options = {}) {
18844
+ for (const listener of this.listeners(type)) {
18845
+ if (!options[kForOnEventAttribute] && listener[kListener] === handler && !listener[kForOnEventAttribute]) {
18846
+ return;
18847
+ }
18848
+ }
18849
+ let wrapper;
18850
+ if (type === "message") {
18851
+ wrapper = function onMessage(data, isBinary) {
18852
+ const event = new MessageEvent("message", {
18853
+ data: isBinary ? data : data.toString()
18854
+ });
18855
+ event[kTarget] = this;
18856
+ callListener(handler, this, event);
18857
+ };
18858
+ } else if (type === "close") {
18859
+ wrapper = function onClose(code, message) {
18860
+ const event = new CloseEvent("close", {
18861
+ code,
18862
+ reason: message.toString(),
18863
+ wasClean: this._closeFrameReceived && this._closeFrameSent
18864
+ });
18865
+ event[kTarget] = this;
18866
+ callListener(handler, this, event);
18867
+ };
18868
+ } else if (type === "error") {
18869
+ wrapper = function onError(error) {
18870
+ const event = new ErrorEvent("error", {
18871
+ error,
18872
+ message: error.message
18873
+ });
18874
+ event[kTarget] = this;
18875
+ callListener(handler, this, event);
18876
+ };
18877
+ } else if (type === "open") {
18878
+ wrapper = function onOpen() {
18879
+ const event = new Event("open");
18880
+ event[kTarget] = this;
18881
+ callListener(handler, this, event);
18882
+ };
18883
+ } else {
18884
+ return;
18885
+ }
18886
+ wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute];
18887
+ wrapper[kListener] = handler;
18888
+ if (options.once) {
18889
+ this.once(type, wrapper);
18890
+ } else {
18891
+ this.on(type, wrapper);
18892
+ }
18893
+ },
18894
+ /**
18895
+ * Remove an event listener.
18896
+ *
18897
+ * @param {String} type A string representing the event type to remove
18898
+ * @param {(Function|Object)} handler The listener to remove
18899
+ * @public
18900
+ */
18901
+ removeEventListener(type, handler) {
18902
+ for (const listener of this.listeners(type)) {
18903
+ if (listener[kListener] === handler && !listener[kForOnEventAttribute]) {
18904
+ this.removeListener(type, listener);
18905
+ break;
18906
+ }
18907
+ }
18908
+ }
18909
+ };
18910
+ module.exports = {
18911
+ CloseEvent,
18912
+ ErrorEvent,
18913
+ Event,
18914
+ EventTarget,
18915
+ MessageEvent
18916
+ };
18917
+ function callListener(listener, thisArg, event) {
18918
+ if (typeof listener === "object" && listener.handleEvent) {
18919
+ listener.handleEvent.call(listener, event);
18920
+ } else {
18921
+ listener.call(thisArg, event);
18922
+ }
18923
+ }
18924
+ }
18925
+ });
18926
+
18927
+ // node_modules/.pnpm/ws@8.19.0/node_modules/ws/lib/extension.js
18928
+ var require_extension = __commonJS({
18929
+ "node_modules/.pnpm/ws@8.19.0/node_modules/ws/lib/extension.js"(exports, module) {
18930
+ "use strict";
18931
+ var { tokenChars } = require_validation();
18932
+ function push(dest, name, elem) {
18933
+ if (dest[name] === void 0) dest[name] = [elem];
18934
+ else dest[name].push(elem);
18935
+ }
18936
+ function parse(header) {
18937
+ const offers = /* @__PURE__ */ Object.create(null);
18938
+ let params = /* @__PURE__ */ Object.create(null);
18939
+ let mustUnescape = false;
18940
+ let isEscaping = false;
18941
+ let inQuotes = false;
18942
+ let extensionName;
18943
+ let paramName;
18944
+ let start = -1;
18945
+ let code = -1;
18946
+ let end = -1;
18947
+ let i = 0;
18948
+ for (; i < header.length; i++) {
18949
+ code = header.charCodeAt(i);
18950
+ if (extensionName === void 0) {
18951
+ if (end === -1 && tokenChars[code] === 1) {
18952
+ if (start === -1) start = i;
18953
+ } else if (i !== 0 && (code === 32 || code === 9)) {
18954
+ if (end === -1 && start !== -1) end = i;
18955
+ } else if (code === 59 || code === 44) {
18956
+ if (start === -1) {
18957
+ throw new SyntaxError(`Unexpected character at index ${i}`);
18958
+ }
18959
+ if (end === -1) end = i;
18960
+ const name = header.slice(start, end);
18961
+ if (code === 44) {
18962
+ push(offers, name, params);
18963
+ params = /* @__PURE__ */ Object.create(null);
18964
+ } else {
18965
+ extensionName = name;
18966
+ }
18967
+ start = end = -1;
18968
+ } else {
18969
+ throw new SyntaxError(`Unexpected character at index ${i}`);
18970
+ }
18971
+ } else if (paramName === void 0) {
18972
+ if (end === -1 && tokenChars[code] === 1) {
18973
+ if (start === -1) start = i;
18974
+ } else if (code === 32 || code === 9) {
18975
+ if (end === -1 && start !== -1) end = i;
18976
+ } else if (code === 59 || code === 44) {
18977
+ if (start === -1) {
18978
+ throw new SyntaxError(`Unexpected character at index ${i}`);
18979
+ }
18980
+ if (end === -1) end = i;
18981
+ push(params, header.slice(start, end), true);
18982
+ if (code === 44) {
18983
+ push(offers, extensionName, params);
18984
+ params = /* @__PURE__ */ Object.create(null);
18985
+ extensionName = void 0;
18986
+ }
18987
+ start = end = -1;
18988
+ } else if (code === 61 && start !== -1 && end === -1) {
18989
+ paramName = header.slice(start, i);
18990
+ start = end = -1;
18991
+ } else {
18992
+ throw new SyntaxError(`Unexpected character at index ${i}`);
18993
+ }
18994
+ } else {
18995
+ if (isEscaping) {
18996
+ if (tokenChars[code] !== 1) {
18997
+ throw new SyntaxError(`Unexpected character at index ${i}`);
18998
+ }
18999
+ if (start === -1) start = i;
19000
+ else if (!mustUnescape) mustUnescape = true;
19001
+ isEscaping = false;
19002
+ } else if (inQuotes) {
19003
+ if (tokenChars[code] === 1) {
19004
+ if (start === -1) start = i;
19005
+ } else if (code === 34 && start !== -1) {
19006
+ inQuotes = false;
19007
+ end = i;
19008
+ } else if (code === 92) {
19009
+ isEscaping = true;
19010
+ } else {
19011
+ throw new SyntaxError(`Unexpected character at index ${i}`);
19012
+ }
19013
+ } else if (code === 34 && header.charCodeAt(i - 1) === 61) {
19014
+ inQuotes = true;
19015
+ } else if (end === -1 && tokenChars[code] === 1) {
19016
+ if (start === -1) start = i;
19017
+ } else if (start !== -1 && (code === 32 || code === 9)) {
19018
+ if (end === -1) end = i;
19019
+ } else if (code === 59 || code === 44) {
19020
+ if (start === -1) {
19021
+ throw new SyntaxError(`Unexpected character at index ${i}`);
19022
+ }
19023
+ if (end === -1) end = i;
19024
+ let value = header.slice(start, end);
19025
+ if (mustUnescape) {
19026
+ value = value.replace(/\\/g, "");
19027
+ mustUnescape = false;
19028
+ }
19029
+ push(params, paramName, value);
19030
+ if (code === 44) {
19031
+ push(offers, extensionName, params);
19032
+ params = /* @__PURE__ */ Object.create(null);
19033
+ extensionName = void 0;
19034
+ }
19035
+ paramName = void 0;
19036
+ start = end = -1;
19037
+ } else {
19038
+ throw new SyntaxError(`Unexpected character at index ${i}`);
19039
+ }
19040
+ }
19041
+ }
19042
+ if (start === -1 || inQuotes || code === 32 || code === 9) {
19043
+ throw new SyntaxError("Unexpected end of input");
19044
+ }
19045
+ if (end === -1) end = i;
19046
+ const token = header.slice(start, end);
19047
+ if (extensionName === void 0) {
19048
+ push(offers, token, params);
19049
+ } else {
19050
+ if (paramName === void 0) {
19051
+ push(params, token, true);
19052
+ } else if (mustUnescape) {
19053
+ push(params, paramName, token.replace(/\\/g, ""));
19054
+ } else {
19055
+ push(params, paramName, token);
19056
+ }
19057
+ push(offers, extensionName, params);
19058
+ }
19059
+ return offers;
19060
+ }
19061
+ function format(extensions) {
19062
+ return Object.keys(extensions).map((extension) => {
19063
+ let configurations = extensions[extension];
19064
+ if (!Array.isArray(configurations)) configurations = [configurations];
19065
+ return configurations.map((params) => {
19066
+ return [extension].concat(
19067
+ Object.keys(params).map((k) => {
19068
+ let values = params[k];
19069
+ if (!Array.isArray(values)) values = [values];
19070
+ return values.map((v) => v === true ? k : `${k}=${v}`).join("; ");
19071
+ })
19072
+ ).join("; ");
19073
+ }).join(", ");
19074
+ }).join(", ");
19075
+ }
19076
+ module.exports = { format, parse };
19077
+ }
19078
+ });
19079
+
19080
+ // node_modules/.pnpm/ws@8.19.0/node_modules/ws/lib/websocket.js
19081
+ var require_websocket = __commonJS({
19082
+ "node_modules/.pnpm/ws@8.19.0/node_modules/ws/lib/websocket.js"(exports, module) {
19083
+ "use strict";
19084
+ var EventEmitter3 = __require("events");
19085
+ var https = __require("https");
19086
+ var http = __require("http");
19087
+ var net = __require("net");
19088
+ var tls = __require("tls");
19089
+ var { randomBytes: randomBytes5, createHash: createHash2 } = __require("crypto");
19090
+ var { Duplex, Readable } = __require("stream");
19091
+ var { URL: URL2 } = __require("url");
19092
+ var PerMessageDeflate = require_permessage_deflate();
19093
+ var Receiver2 = require_receiver();
19094
+ var Sender2 = require_sender();
19095
+ var { isBlob } = require_validation();
19096
+ var {
19097
+ BINARY_TYPES,
19098
+ CLOSE_TIMEOUT,
19099
+ EMPTY_BUFFER,
19100
+ GUID,
19101
+ kForOnEventAttribute,
19102
+ kListener,
19103
+ kStatusCode,
19104
+ kWebSocket,
19105
+ NOOP
19106
+ } = require_constants();
19107
+ var {
19108
+ EventTarget: { addEventListener, removeEventListener }
19109
+ } = require_event_target();
19110
+ var { format, parse } = require_extension();
19111
+ var { toBuffer } = require_buffer_util();
19112
+ var kAborted = /* @__PURE__ */ Symbol("kAborted");
19113
+ var protocolVersions = [8, 13];
19114
+ var readyStates = ["CONNECTING", "OPEN", "CLOSING", "CLOSED"];
19115
+ var subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;
19116
+ var WebSocket2 = class _WebSocket extends EventEmitter3 {
19117
+ /**
19118
+ * Create a new `WebSocket`.
19119
+ *
19120
+ * @param {(String|URL)} address The URL to which to connect
19121
+ * @param {(String|String[])} [protocols] The subprotocols
19122
+ * @param {Object} [options] Connection options
19123
+ */
19124
+ constructor(address, protocols, options) {
19125
+ super();
19126
+ this._binaryType = BINARY_TYPES[0];
19127
+ this._closeCode = 1006;
19128
+ this._closeFrameReceived = false;
19129
+ this._closeFrameSent = false;
19130
+ this._closeMessage = EMPTY_BUFFER;
19131
+ this._closeTimer = null;
19132
+ this._errorEmitted = false;
19133
+ this._extensions = {};
19134
+ this._paused = false;
19135
+ this._protocol = "";
19136
+ this._readyState = _WebSocket.CONNECTING;
19137
+ this._receiver = null;
19138
+ this._sender = null;
19139
+ this._socket = null;
19140
+ if (address !== null) {
19141
+ this._bufferedAmount = 0;
19142
+ this._isServer = false;
19143
+ this._redirects = 0;
19144
+ if (protocols === void 0) {
19145
+ protocols = [];
19146
+ } else if (!Array.isArray(protocols)) {
19147
+ if (typeof protocols === "object" && protocols !== null) {
19148
+ options = protocols;
19149
+ protocols = [];
19150
+ } else {
19151
+ protocols = [protocols];
19152
+ }
19153
+ }
19154
+ initAsClient(this, address, protocols, options);
19155
+ } else {
19156
+ this._autoPong = options.autoPong;
19157
+ this._closeTimeout = options.closeTimeout;
19158
+ this._isServer = true;
19159
+ }
19160
+ }
19161
+ /**
19162
+ * For historical reasons, the custom "nodebuffer" type is used by the default
19163
+ * instead of "blob".
19164
+ *
19165
+ * @type {String}
19166
+ */
19167
+ get binaryType() {
19168
+ return this._binaryType;
19169
+ }
19170
+ set binaryType(type) {
19171
+ if (!BINARY_TYPES.includes(type)) return;
19172
+ this._binaryType = type;
19173
+ if (this._receiver) this._receiver._binaryType = type;
19174
+ }
19175
+ /**
19176
+ * @type {Number}
19177
+ */
19178
+ get bufferedAmount() {
19179
+ if (!this._socket) return this._bufferedAmount;
19180
+ return this._socket._writableState.length + this._sender._bufferedBytes;
19181
+ }
19182
+ /**
19183
+ * @type {String}
19184
+ */
19185
+ get extensions() {
19186
+ return Object.keys(this._extensions).join();
19187
+ }
19188
+ /**
19189
+ * @type {Boolean}
19190
+ */
19191
+ get isPaused() {
19192
+ return this._paused;
19193
+ }
19194
+ /**
19195
+ * @type {Function}
19196
+ */
19197
+ /* istanbul ignore next */
19198
+ get onclose() {
19199
+ return null;
19200
+ }
19201
+ /**
19202
+ * @type {Function}
19203
+ */
19204
+ /* istanbul ignore next */
19205
+ get onerror() {
19206
+ return null;
19207
+ }
19208
+ /**
19209
+ * @type {Function}
19210
+ */
19211
+ /* istanbul ignore next */
19212
+ get onopen() {
19213
+ return null;
19214
+ }
19215
+ /**
19216
+ * @type {Function}
19217
+ */
19218
+ /* istanbul ignore next */
19219
+ get onmessage() {
19220
+ return null;
19221
+ }
19222
+ /**
19223
+ * @type {String}
19224
+ */
19225
+ get protocol() {
19226
+ return this._protocol;
19227
+ }
19228
+ /**
19229
+ * @type {Number}
19230
+ */
19231
+ get readyState() {
19232
+ return this._readyState;
19233
+ }
19234
+ /**
19235
+ * @type {String}
19236
+ */
19237
+ get url() {
19238
+ return this._url;
19239
+ }
19240
+ /**
19241
+ * Set up the socket and the internal resources.
19242
+ *
19243
+ * @param {Duplex} socket The network socket between the server and client
19244
+ * @param {Buffer} head The first packet of the upgraded stream
19245
+ * @param {Object} options Options object
19246
+ * @param {Boolean} [options.allowSynchronousEvents=false] Specifies whether
19247
+ * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
19248
+ * multiple times in the same tick
19249
+ * @param {Function} [options.generateMask] The function used to generate the
19250
+ * masking key
19251
+ * @param {Number} [options.maxPayload=0] The maximum allowed message size
19252
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
19253
+ * not to skip UTF-8 validation for text and close messages
19254
+ * @private
19255
+ */
19256
+ setSocket(socket, head, options) {
19257
+ const receiver = new Receiver2({
19258
+ allowSynchronousEvents: options.allowSynchronousEvents,
19259
+ binaryType: this.binaryType,
19260
+ extensions: this._extensions,
19261
+ isServer: this._isServer,
19262
+ maxPayload: options.maxPayload,
19263
+ skipUTF8Validation: options.skipUTF8Validation
19264
+ });
19265
+ const sender = new Sender2(socket, this._extensions, options.generateMask);
19266
+ this._receiver = receiver;
19267
+ this._sender = sender;
19268
+ this._socket = socket;
19269
+ receiver[kWebSocket] = this;
19270
+ sender[kWebSocket] = this;
19271
+ socket[kWebSocket] = this;
19272
+ receiver.on("conclude", receiverOnConclude);
19273
+ receiver.on("drain", receiverOnDrain);
19274
+ receiver.on("error", receiverOnError);
19275
+ receiver.on("message", receiverOnMessage);
19276
+ receiver.on("ping", receiverOnPing);
19277
+ receiver.on("pong", receiverOnPong);
19278
+ sender.onerror = senderOnError;
19279
+ if (socket.setTimeout) socket.setTimeout(0);
19280
+ if (socket.setNoDelay) socket.setNoDelay();
19281
+ if (head.length > 0) socket.unshift(head);
19282
+ socket.on("close", socketOnClose);
19283
+ socket.on("data", socketOnData);
19284
+ socket.on("end", socketOnEnd);
19285
+ socket.on("error", socketOnError);
19286
+ this._readyState = _WebSocket.OPEN;
19287
+ this.emit("open");
19288
+ }
19289
+ /**
19290
+ * Emit the `'close'` event.
19291
+ *
19292
+ * @private
19293
+ */
19294
+ emitClose() {
19295
+ if (!this._socket) {
19296
+ this._readyState = _WebSocket.CLOSED;
19297
+ this.emit("close", this._closeCode, this._closeMessage);
19298
+ return;
19299
+ }
19300
+ if (this._extensions[PerMessageDeflate.extensionName]) {
19301
+ this._extensions[PerMessageDeflate.extensionName].cleanup();
19302
+ }
19303
+ this._receiver.removeAllListeners();
19304
+ this._readyState = _WebSocket.CLOSED;
19305
+ this.emit("close", this._closeCode, this._closeMessage);
19306
+ }
19307
+ /**
19308
+ * Start a closing handshake.
19309
+ *
19310
+ * +----------+ +-----------+ +----------+
19311
+ * - - -|ws.close()|-->|close frame|-->|ws.close()|- - -
19312
+ * | +----------+ +-----------+ +----------+ |
19313
+ * +----------+ +-----------+ |
19314
+ * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING
19315
+ * +----------+ +-----------+ |
19316
+ * | | | +---+ |
19317
+ * +------------------------+-->|fin| - - - -
19318
+ * | +---+ | +---+
19319
+ * - - - - -|fin|<---------------------+
19320
+ * +---+
19321
+ *
19322
+ * @param {Number} [code] Status code explaining why the connection is closing
19323
+ * @param {(String|Buffer)} [data] The reason why the connection is
19324
+ * closing
19325
+ * @public
19326
+ */
19327
+ close(code, data) {
19328
+ if (this.readyState === _WebSocket.CLOSED) return;
19329
+ if (this.readyState === _WebSocket.CONNECTING) {
19330
+ const msg = "WebSocket was closed before the connection was established";
19331
+ abortHandshake(this, this._req, msg);
19332
+ return;
19333
+ }
19334
+ if (this.readyState === _WebSocket.CLOSING) {
19335
+ if (this._closeFrameSent && (this._closeFrameReceived || this._receiver._writableState.errorEmitted)) {
19336
+ this._socket.end();
19337
+ }
19338
+ return;
19339
+ }
19340
+ this._readyState = _WebSocket.CLOSING;
19341
+ this._sender.close(code, data, !this._isServer, (err) => {
19342
+ if (err) return;
19343
+ this._closeFrameSent = true;
19344
+ if (this._closeFrameReceived || this._receiver._writableState.errorEmitted) {
19345
+ this._socket.end();
19346
+ }
19347
+ });
19348
+ setCloseTimer(this);
19349
+ }
19350
+ /**
19351
+ * Pause the socket.
19352
+ *
19353
+ * @public
19354
+ */
19355
+ pause() {
19356
+ if (this.readyState === _WebSocket.CONNECTING || this.readyState === _WebSocket.CLOSED) {
19357
+ return;
19358
+ }
19359
+ this._paused = true;
19360
+ this._socket.pause();
19361
+ }
19362
+ /**
19363
+ * Send a ping.
19364
+ *
19365
+ * @param {*} [data] The data to send
19366
+ * @param {Boolean} [mask] Indicates whether or not to mask `data`
19367
+ * @param {Function} [cb] Callback which is executed when the ping is sent
19368
+ * @public
19369
+ */
19370
+ ping(data, mask, cb) {
19371
+ if (this.readyState === _WebSocket.CONNECTING) {
19372
+ throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
19373
+ }
19374
+ if (typeof data === "function") {
19375
+ cb = data;
19376
+ data = mask = void 0;
19377
+ } else if (typeof mask === "function") {
19378
+ cb = mask;
19379
+ mask = void 0;
19380
+ }
19381
+ if (typeof data === "number") data = data.toString();
19382
+ if (this.readyState !== _WebSocket.OPEN) {
19383
+ sendAfterClose(this, data, cb);
19384
+ return;
19385
+ }
19386
+ if (mask === void 0) mask = !this._isServer;
19387
+ this._sender.ping(data || EMPTY_BUFFER, mask, cb);
19388
+ }
19389
+ /**
19390
+ * Send a pong.
19391
+ *
19392
+ * @param {*} [data] The data to send
19393
+ * @param {Boolean} [mask] Indicates whether or not to mask `data`
19394
+ * @param {Function} [cb] Callback which is executed when the pong is sent
19395
+ * @public
19396
+ */
19397
+ pong(data, mask, cb) {
19398
+ if (this.readyState === _WebSocket.CONNECTING) {
19399
+ throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
19400
+ }
19401
+ if (typeof data === "function") {
19402
+ cb = data;
19403
+ data = mask = void 0;
19404
+ } else if (typeof mask === "function") {
19405
+ cb = mask;
19406
+ mask = void 0;
19407
+ }
19408
+ if (typeof data === "number") data = data.toString();
19409
+ if (this.readyState !== _WebSocket.OPEN) {
19410
+ sendAfterClose(this, data, cb);
19411
+ return;
19412
+ }
19413
+ if (mask === void 0) mask = !this._isServer;
19414
+ this._sender.pong(data || EMPTY_BUFFER, mask, cb);
19415
+ }
19416
+ /**
19417
+ * Resume the socket.
19418
+ *
19419
+ * @public
19420
+ */
19421
+ resume() {
19422
+ if (this.readyState === _WebSocket.CONNECTING || this.readyState === _WebSocket.CLOSED) {
19423
+ return;
19424
+ }
19425
+ this._paused = false;
19426
+ if (!this._receiver._writableState.needDrain) this._socket.resume();
19427
+ }
19428
+ /**
19429
+ * Send a data message.
19430
+ *
19431
+ * @param {*} data The message to send
19432
+ * @param {Object} [options] Options object
19433
+ * @param {Boolean} [options.binary] Specifies whether `data` is binary or
19434
+ * text
19435
+ * @param {Boolean} [options.compress] Specifies whether or not to compress
19436
+ * `data`
19437
+ * @param {Boolean} [options.fin=true] Specifies whether the fragment is the
19438
+ * last one
19439
+ * @param {Boolean} [options.mask] Specifies whether or not to mask `data`
19440
+ * @param {Function} [cb] Callback which is executed when data is written out
19441
+ * @public
19442
+ */
19443
+ send(data, options, cb) {
19444
+ if (this.readyState === _WebSocket.CONNECTING) {
19445
+ throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
19446
+ }
19447
+ if (typeof options === "function") {
19448
+ cb = options;
19449
+ options = {};
19450
+ }
19451
+ if (typeof data === "number") data = data.toString();
19452
+ if (this.readyState !== _WebSocket.OPEN) {
19453
+ sendAfterClose(this, data, cb);
19454
+ return;
19455
+ }
19456
+ const opts = {
19457
+ binary: typeof data !== "string",
19458
+ mask: !this._isServer,
19459
+ compress: true,
19460
+ fin: true,
19461
+ ...options
19462
+ };
19463
+ if (!this._extensions[PerMessageDeflate.extensionName]) {
19464
+ opts.compress = false;
19465
+ }
19466
+ this._sender.send(data || EMPTY_BUFFER, opts, cb);
19467
+ }
19468
+ /**
19469
+ * Forcibly close the connection.
19470
+ *
19471
+ * @public
19472
+ */
19473
+ terminate() {
19474
+ if (this.readyState === _WebSocket.CLOSED) return;
19475
+ if (this.readyState === _WebSocket.CONNECTING) {
19476
+ const msg = "WebSocket was closed before the connection was established";
19477
+ abortHandshake(this, this._req, msg);
19478
+ return;
19479
+ }
19480
+ if (this._socket) {
19481
+ this._readyState = _WebSocket.CLOSING;
19482
+ this._socket.destroy();
19483
+ }
19484
+ }
19485
+ };
19486
+ Object.defineProperty(WebSocket2, "CONNECTING", {
19487
+ enumerable: true,
19488
+ value: readyStates.indexOf("CONNECTING")
19489
+ });
19490
+ Object.defineProperty(WebSocket2.prototype, "CONNECTING", {
19491
+ enumerable: true,
19492
+ value: readyStates.indexOf("CONNECTING")
19493
+ });
19494
+ Object.defineProperty(WebSocket2, "OPEN", {
19495
+ enumerable: true,
19496
+ value: readyStates.indexOf("OPEN")
19497
+ });
19498
+ Object.defineProperty(WebSocket2.prototype, "OPEN", {
19499
+ enumerable: true,
19500
+ value: readyStates.indexOf("OPEN")
19501
+ });
19502
+ Object.defineProperty(WebSocket2, "CLOSING", {
19503
+ enumerable: true,
19504
+ value: readyStates.indexOf("CLOSING")
19505
+ });
19506
+ Object.defineProperty(WebSocket2.prototype, "CLOSING", {
19507
+ enumerable: true,
19508
+ value: readyStates.indexOf("CLOSING")
19509
+ });
19510
+ Object.defineProperty(WebSocket2, "CLOSED", {
19511
+ enumerable: true,
19512
+ value: readyStates.indexOf("CLOSED")
19513
+ });
19514
+ Object.defineProperty(WebSocket2.prototype, "CLOSED", {
19515
+ enumerable: true,
19516
+ value: readyStates.indexOf("CLOSED")
19517
+ });
19518
+ [
19519
+ "binaryType",
19520
+ "bufferedAmount",
19521
+ "extensions",
19522
+ "isPaused",
19523
+ "protocol",
19524
+ "readyState",
19525
+ "url"
19526
+ ].forEach((property) => {
19527
+ Object.defineProperty(WebSocket2.prototype, property, { enumerable: true });
19528
+ });
19529
+ ["open", "error", "close", "message"].forEach((method) => {
19530
+ Object.defineProperty(WebSocket2.prototype, `on${method}`, {
19531
+ enumerable: true,
19532
+ get() {
19533
+ for (const listener of this.listeners(method)) {
19534
+ if (listener[kForOnEventAttribute]) return listener[kListener];
19535
+ }
19536
+ return null;
19537
+ },
19538
+ set(handler) {
19539
+ for (const listener of this.listeners(method)) {
19540
+ if (listener[kForOnEventAttribute]) {
19541
+ this.removeListener(method, listener);
19542
+ break;
19543
+ }
19544
+ }
19545
+ if (typeof handler !== "function") return;
19546
+ this.addEventListener(method, handler, {
19547
+ [kForOnEventAttribute]: true
19548
+ });
19549
+ }
19550
+ });
19551
+ });
19552
+ WebSocket2.prototype.addEventListener = addEventListener;
19553
+ WebSocket2.prototype.removeEventListener = removeEventListener;
19554
+ module.exports = WebSocket2;
19555
+ function initAsClient(websocket, address, protocols, options) {
19556
+ const opts = {
19557
+ allowSynchronousEvents: true,
19558
+ autoPong: true,
19559
+ closeTimeout: CLOSE_TIMEOUT,
19560
+ protocolVersion: protocolVersions[1],
19561
+ maxPayload: 100 * 1024 * 1024,
19562
+ skipUTF8Validation: false,
19563
+ perMessageDeflate: true,
19564
+ followRedirects: false,
19565
+ maxRedirects: 10,
19566
+ ...options,
19567
+ socketPath: void 0,
19568
+ hostname: void 0,
19569
+ protocol: void 0,
19570
+ timeout: void 0,
19571
+ method: "GET",
19572
+ host: void 0,
19573
+ path: void 0,
19574
+ port: void 0
19575
+ };
19576
+ websocket._autoPong = opts.autoPong;
19577
+ websocket._closeTimeout = opts.closeTimeout;
19578
+ if (!protocolVersions.includes(opts.protocolVersion)) {
19579
+ throw new RangeError(
19580
+ `Unsupported protocol version: ${opts.protocolVersion} (supported versions: ${protocolVersions.join(", ")})`
19581
+ );
19582
+ }
19583
+ let parsedUrl;
19584
+ if (address instanceof URL2) {
19585
+ parsedUrl = address;
19586
+ } else {
19587
+ try {
19588
+ parsedUrl = new URL2(address);
19589
+ } catch (e) {
19590
+ throw new SyntaxError(`Invalid URL: ${address}`);
19591
+ }
19592
+ }
19593
+ if (parsedUrl.protocol === "http:") {
19594
+ parsedUrl.protocol = "ws:";
19595
+ } else if (parsedUrl.protocol === "https:") {
19596
+ parsedUrl.protocol = "wss:";
19597
+ }
19598
+ websocket._url = parsedUrl.href;
19599
+ const isSecure = parsedUrl.protocol === "wss:";
19600
+ const isIpcUrl = parsedUrl.protocol === "ws+unix:";
19601
+ let invalidUrlMessage;
19602
+ if (parsedUrl.protocol !== "ws:" && !isSecure && !isIpcUrl) {
19603
+ invalidUrlMessage = `The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`;
19604
+ } else if (isIpcUrl && !parsedUrl.pathname) {
19605
+ invalidUrlMessage = "The URL's pathname is empty";
19606
+ } else if (parsedUrl.hash) {
19607
+ invalidUrlMessage = "The URL contains a fragment identifier";
19608
+ }
19609
+ if (invalidUrlMessage) {
19610
+ const err = new SyntaxError(invalidUrlMessage);
19611
+ if (websocket._redirects === 0) {
19612
+ throw err;
19613
+ } else {
19614
+ emitErrorAndClose(websocket, err);
19615
+ return;
19616
+ }
19617
+ }
19618
+ const defaultPort = isSecure ? 443 : 80;
19619
+ const key = randomBytes5(16).toString("base64");
19620
+ const request = isSecure ? https.request : http.request;
19621
+ const protocolSet = /* @__PURE__ */ new Set();
19622
+ let perMessageDeflate;
19623
+ opts.createConnection = opts.createConnection || (isSecure ? tlsConnect : netConnect);
19624
+ opts.defaultPort = opts.defaultPort || defaultPort;
19625
+ opts.port = parsedUrl.port || defaultPort;
19626
+ opts.host = parsedUrl.hostname.startsWith("[") ? parsedUrl.hostname.slice(1, -1) : parsedUrl.hostname;
19627
+ opts.headers = {
19628
+ ...opts.headers,
19629
+ "Sec-WebSocket-Version": opts.protocolVersion,
19630
+ "Sec-WebSocket-Key": key,
19631
+ Connection: "Upgrade",
19632
+ Upgrade: "websocket"
19633
+ };
19634
+ opts.path = parsedUrl.pathname + parsedUrl.search;
19635
+ opts.timeout = opts.handshakeTimeout;
19636
+ if (opts.perMessageDeflate) {
19637
+ perMessageDeflate = new PerMessageDeflate(
19638
+ opts.perMessageDeflate !== true ? opts.perMessageDeflate : {},
19639
+ false,
19640
+ opts.maxPayload
19641
+ );
19642
+ opts.headers["Sec-WebSocket-Extensions"] = format({
19643
+ [PerMessageDeflate.extensionName]: perMessageDeflate.offer()
19644
+ });
19645
+ }
19646
+ if (protocols.length) {
19647
+ for (const protocol of protocols) {
19648
+ if (typeof protocol !== "string" || !subprotocolRegex.test(protocol) || protocolSet.has(protocol)) {
19649
+ throw new SyntaxError(
19650
+ "An invalid or duplicated subprotocol was specified"
19651
+ );
19652
+ }
19653
+ protocolSet.add(protocol);
19654
+ }
19655
+ opts.headers["Sec-WebSocket-Protocol"] = protocols.join(",");
19656
+ }
19657
+ if (opts.origin) {
19658
+ if (opts.protocolVersion < 13) {
19659
+ opts.headers["Sec-WebSocket-Origin"] = opts.origin;
19660
+ } else {
19661
+ opts.headers.Origin = opts.origin;
19662
+ }
19663
+ }
19664
+ if (parsedUrl.username || parsedUrl.password) {
19665
+ opts.auth = `${parsedUrl.username}:${parsedUrl.password}`;
19666
+ }
19667
+ if (isIpcUrl) {
19668
+ const parts = opts.path.split(":");
19669
+ opts.socketPath = parts[0];
19670
+ opts.path = parts[1];
19671
+ }
19672
+ let req;
19673
+ if (opts.followRedirects) {
19674
+ if (websocket._redirects === 0) {
19675
+ websocket._originalIpc = isIpcUrl;
19676
+ websocket._originalSecure = isSecure;
19677
+ websocket._originalHostOrSocketPath = isIpcUrl ? opts.socketPath : parsedUrl.host;
19678
+ const headers = options && options.headers;
19679
+ options = { ...options, headers: {} };
19680
+ if (headers) {
19681
+ for (const [key2, value] of Object.entries(headers)) {
19682
+ options.headers[key2.toLowerCase()] = value;
19683
+ }
19684
+ }
19685
+ } else if (websocket.listenerCount("redirect") === 0) {
19686
+ const isSameHost = isIpcUrl ? websocket._originalIpc ? opts.socketPath === websocket._originalHostOrSocketPath : false : websocket._originalIpc ? false : parsedUrl.host === websocket._originalHostOrSocketPath;
19687
+ if (!isSameHost || websocket._originalSecure && !isSecure) {
19688
+ delete opts.headers.authorization;
19689
+ delete opts.headers.cookie;
19690
+ if (!isSameHost) delete opts.headers.host;
19691
+ opts.auth = void 0;
19692
+ }
19693
+ }
19694
+ if (opts.auth && !options.headers.authorization) {
19695
+ options.headers.authorization = "Basic " + Buffer.from(opts.auth).toString("base64");
19696
+ }
19697
+ req = websocket._req = request(opts);
19698
+ if (websocket._redirects) {
19699
+ websocket.emit("redirect", websocket.url, req);
19700
+ }
19701
+ } else {
19702
+ req = websocket._req = request(opts);
19703
+ }
19704
+ if (opts.timeout) {
19705
+ req.on("timeout", () => {
19706
+ abortHandshake(websocket, req, "Opening handshake has timed out");
19707
+ });
19708
+ }
19709
+ req.on("error", (err) => {
19710
+ if (req === null || req[kAborted]) return;
19711
+ req = websocket._req = null;
19712
+ emitErrorAndClose(websocket, err);
19713
+ });
19714
+ req.on("response", (res) => {
19715
+ const location = res.headers.location;
19716
+ const statusCode = res.statusCode;
19717
+ if (location && opts.followRedirects && statusCode >= 300 && statusCode < 400) {
19718
+ if (++websocket._redirects > opts.maxRedirects) {
19719
+ abortHandshake(websocket, req, "Maximum redirects exceeded");
19720
+ return;
19721
+ }
19722
+ req.abort();
19723
+ let addr;
19724
+ try {
19725
+ addr = new URL2(location, address);
19726
+ } catch (e) {
19727
+ const err = new SyntaxError(`Invalid URL: ${location}`);
19728
+ emitErrorAndClose(websocket, err);
19729
+ return;
19730
+ }
19731
+ initAsClient(websocket, addr, protocols, options);
19732
+ } else if (!websocket.emit("unexpected-response", req, res)) {
19733
+ abortHandshake(
19734
+ websocket,
19735
+ req,
19736
+ `Unexpected server response: ${res.statusCode}`
19737
+ );
19738
+ }
19739
+ });
19740
+ req.on("upgrade", (res, socket, head) => {
19741
+ websocket.emit("upgrade", res);
19742
+ if (websocket.readyState !== WebSocket2.CONNECTING) return;
19743
+ req = websocket._req = null;
19744
+ const upgrade = res.headers.upgrade;
19745
+ if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") {
19746
+ abortHandshake(websocket, socket, "Invalid Upgrade header");
19747
+ return;
19748
+ }
19749
+ const digest = createHash2("sha1").update(key + GUID).digest("base64");
19750
+ if (res.headers["sec-websocket-accept"] !== digest) {
19751
+ abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
19752
+ return;
19753
+ }
19754
+ const serverProt = res.headers["sec-websocket-protocol"];
19755
+ let protError;
19756
+ if (serverProt !== void 0) {
19757
+ if (!protocolSet.size) {
19758
+ protError = "Server sent a subprotocol but none was requested";
19759
+ } else if (!protocolSet.has(serverProt)) {
19760
+ protError = "Server sent an invalid subprotocol";
19761
+ }
19762
+ } else if (protocolSet.size) {
19763
+ protError = "Server sent no subprotocol";
19764
+ }
19765
+ if (protError) {
19766
+ abortHandshake(websocket, socket, protError);
19767
+ return;
19768
+ }
19769
+ if (serverProt) websocket._protocol = serverProt;
19770
+ const secWebSocketExtensions = res.headers["sec-websocket-extensions"];
19771
+ if (secWebSocketExtensions !== void 0) {
19772
+ if (!perMessageDeflate) {
19773
+ const message = "Server sent a Sec-WebSocket-Extensions header but no extension was requested";
19774
+ abortHandshake(websocket, socket, message);
19775
+ return;
19776
+ }
19777
+ let extensions;
19778
+ try {
19779
+ extensions = parse(secWebSocketExtensions);
19780
+ } catch (err) {
19781
+ const message = "Invalid Sec-WebSocket-Extensions header";
19782
+ abortHandshake(websocket, socket, message);
19783
+ return;
19784
+ }
19785
+ const extensionNames = Object.keys(extensions);
19786
+ if (extensionNames.length !== 1 || extensionNames[0] !== PerMessageDeflate.extensionName) {
19787
+ const message = "Server indicated an extension that was not requested";
19788
+ abortHandshake(websocket, socket, message);
19789
+ return;
19790
+ }
19791
+ try {
19792
+ perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName]);
19793
+ } catch (err) {
19794
+ const message = "Invalid Sec-WebSocket-Extensions header";
19795
+ abortHandshake(websocket, socket, message);
19796
+ return;
19797
+ }
19798
+ websocket._extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
19799
+ }
19800
+ websocket.setSocket(socket, head, {
19801
+ allowSynchronousEvents: opts.allowSynchronousEvents,
19802
+ generateMask: opts.generateMask,
19803
+ maxPayload: opts.maxPayload,
19804
+ skipUTF8Validation: opts.skipUTF8Validation
19805
+ });
19806
+ });
19807
+ if (opts.finishRequest) {
19808
+ opts.finishRequest(req, websocket);
19809
+ } else {
19810
+ req.end();
19811
+ }
19812
+ }
19813
+ function emitErrorAndClose(websocket, err) {
19814
+ websocket._readyState = WebSocket2.CLOSING;
19815
+ websocket._errorEmitted = true;
19816
+ websocket.emit("error", err);
19817
+ websocket.emitClose();
19818
+ }
19819
+ function netConnect(options) {
19820
+ options.path = options.socketPath;
19821
+ return net.connect(options);
19822
+ }
19823
+ function tlsConnect(options) {
19824
+ options.path = void 0;
19825
+ if (!options.servername && options.servername !== "") {
19826
+ options.servername = net.isIP(options.host) ? "" : options.host;
19827
+ }
19828
+ return tls.connect(options);
19829
+ }
19830
+ function abortHandshake(websocket, stream, message) {
19831
+ websocket._readyState = WebSocket2.CLOSING;
19832
+ const err = new Error(message);
19833
+ Error.captureStackTrace(err, abortHandshake);
19834
+ if (stream.setHeader) {
19835
+ stream[kAborted] = true;
19836
+ stream.abort();
19837
+ if (stream.socket && !stream.socket.destroyed) {
19838
+ stream.socket.destroy();
19839
+ }
19840
+ process.nextTick(emitErrorAndClose, websocket, err);
19841
+ } else {
19842
+ stream.destroy(err);
19843
+ stream.once("error", websocket.emit.bind(websocket, "error"));
19844
+ stream.once("close", websocket.emitClose.bind(websocket));
19845
+ }
19846
+ }
19847
+ function sendAfterClose(websocket, data, cb) {
19848
+ if (data) {
19849
+ const length = isBlob(data) ? data.size : toBuffer(data).length;
19850
+ if (websocket._socket) websocket._sender._bufferedBytes += length;
19851
+ else websocket._bufferedAmount += length;
19852
+ }
19853
+ if (cb) {
19854
+ const err = new Error(
19855
+ `WebSocket is not open: readyState ${websocket.readyState} (${readyStates[websocket.readyState]})`
19856
+ );
19857
+ process.nextTick(cb, err);
19858
+ }
19859
+ }
19860
+ function receiverOnConclude(code, reason) {
19861
+ const websocket = this[kWebSocket];
19862
+ websocket._closeFrameReceived = true;
19863
+ websocket._closeMessage = reason;
19864
+ websocket._closeCode = code;
19865
+ if (websocket._socket[kWebSocket] === void 0) return;
19866
+ websocket._socket.removeListener("data", socketOnData);
19867
+ process.nextTick(resume, websocket._socket);
19868
+ if (code === 1005) websocket.close();
19869
+ else websocket.close(code, reason);
19870
+ }
19871
+ function receiverOnDrain() {
19872
+ const websocket = this[kWebSocket];
19873
+ if (!websocket.isPaused) websocket._socket.resume();
19874
+ }
19875
+ function receiverOnError(err) {
19876
+ const websocket = this[kWebSocket];
19877
+ if (websocket._socket[kWebSocket] !== void 0) {
19878
+ websocket._socket.removeListener("data", socketOnData);
19879
+ process.nextTick(resume, websocket._socket);
19880
+ websocket.close(err[kStatusCode]);
19881
+ }
19882
+ if (!websocket._errorEmitted) {
19883
+ websocket._errorEmitted = true;
19884
+ websocket.emit("error", err);
19885
+ }
19886
+ }
19887
+ function receiverOnFinish() {
19888
+ this[kWebSocket].emitClose();
19889
+ }
19890
+ function receiverOnMessage(data, isBinary) {
19891
+ this[kWebSocket].emit("message", data, isBinary);
19892
+ }
19893
+ function receiverOnPing(data) {
19894
+ const websocket = this[kWebSocket];
19895
+ if (websocket._autoPong) websocket.pong(data, !this._isServer, NOOP);
19896
+ websocket.emit("ping", data);
19897
+ }
19898
+ function receiverOnPong(data) {
19899
+ this[kWebSocket].emit("pong", data);
19900
+ }
19901
+ function resume(stream) {
19902
+ stream.resume();
19903
+ }
19904
+ function senderOnError(err) {
19905
+ const websocket = this[kWebSocket];
19906
+ if (websocket.readyState === WebSocket2.CLOSED) return;
19907
+ if (websocket.readyState === WebSocket2.OPEN) {
19908
+ websocket._readyState = WebSocket2.CLOSING;
19909
+ setCloseTimer(websocket);
19910
+ }
19911
+ this._socket.end();
19912
+ if (!websocket._errorEmitted) {
19913
+ websocket._errorEmitted = true;
19914
+ websocket.emit("error", err);
19915
+ }
19916
+ }
19917
+ function setCloseTimer(websocket) {
19918
+ websocket._closeTimer = setTimeout(
19919
+ websocket._socket.destroy.bind(websocket._socket),
19920
+ websocket._closeTimeout
19921
+ );
19922
+ }
19923
+ function socketOnClose() {
19924
+ const websocket = this[kWebSocket];
19925
+ this.removeListener("close", socketOnClose);
19926
+ this.removeListener("data", socketOnData);
19927
+ this.removeListener("end", socketOnEnd);
19928
+ websocket._readyState = WebSocket2.CLOSING;
19929
+ if (!this._readableState.endEmitted && !websocket._closeFrameReceived && !websocket._receiver._writableState.errorEmitted && this._readableState.length !== 0) {
19930
+ const chunk = this.read(this._readableState.length);
19931
+ websocket._receiver.write(chunk);
19932
+ }
19933
+ websocket._receiver.end();
19934
+ this[kWebSocket] = void 0;
19935
+ clearTimeout(websocket._closeTimer);
19936
+ if (websocket._receiver._writableState.finished || websocket._receiver._writableState.errorEmitted) {
19937
+ websocket.emitClose();
19938
+ } else {
19939
+ websocket._receiver.on("error", receiverOnFinish);
19940
+ websocket._receiver.on("finish", receiverOnFinish);
19941
+ }
19942
+ }
19943
+ function socketOnData(chunk) {
19944
+ if (!this[kWebSocket]._receiver.write(chunk)) {
19945
+ this.pause();
19946
+ }
19947
+ }
19948
+ function socketOnEnd() {
19949
+ const websocket = this[kWebSocket];
19950
+ websocket._readyState = WebSocket2.CLOSING;
19951
+ websocket._receiver.end();
19952
+ this.end();
19953
+ }
19954
+ function socketOnError() {
19955
+ const websocket = this[kWebSocket];
19956
+ this.removeListener("error", socketOnError);
19957
+ this.on("error", NOOP);
19958
+ if (websocket) {
19959
+ websocket._readyState = WebSocket2.CLOSING;
19960
+ this.destroy();
19961
+ }
19962
+ }
19963
+ }
19964
+ });
19965
+
19966
+ // node_modules/.pnpm/ws@8.19.0/node_modules/ws/lib/stream.js
19967
+ var require_stream = __commonJS({
19968
+ "node_modules/.pnpm/ws@8.19.0/node_modules/ws/lib/stream.js"(exports, module) {
19969
+ "use strict";
19970
+ var WebSocket2 = require_websocket();
19971
+ var { Duplex } = __require("stream");
19972
+ function emitClose(stream) {
19973
+ stream.emit("close");
19974
+ }
19975
+ function duplexOnEnd() {
19976
+ if (!this.destroyed && this._writableState.finished) {
19977
+ this.destroy();
19978
+ }
19979
+ }
19980
+ function duplexOnError(err) {
19981
+ this.removeListener("error", duplexOnError);
19982
+ this.destroy();
19983
+ if (this.listenerCount("error") === 0) {
19984
+ this.emit("error", err);
19985
+ }
19986
+ }
19987
+ function createWebSocketStream2(ws, options) {
19988
+ let terminateOnDestroy = true;
19989
+ const duplex = new Duplex({
19990
+ ...options,
19991
+ autoDestroy: false,
19992
+ emitClose: false,
19993
+ objectMode: false,
19994
+ writableObjectMode: false
19995
+ });
19996
+ ws.on("message", function message(msg, isBinary) {
19997
+ const data = !isBinary && duplex._readableState.objectMode ? msg.toString() : msg;
19998
+ if (!duplex.push(data)) ws.pause();
19999
+ });
20000
+ ws.once("error", function error(err) {
20001
+ if (duplex.destroyed) return;
20002
+ terminateOnDestroy = false;
20003
+ duplex.destroy(err);
20004
+ });
20005
+ ws.once("close", function close() {
20006
+ if (duplex.destroyed) return;
20007
+ duplex.push(null);
20008
+ });
20009
+ duplex._destroy = function(err, callback) {
20010
+ if (ws.readyState === ws.CLOSED) {
20011
+ callback(err);
20012
+ process.nextTick(emitClose, duplex);
20013
+ return;
20014
+ }
20015
+ let called = false;
20016
+ ws.once("error", function error(err2) {
20017
+ called = true;
20018
+ callback(err2);
20019
+ });
20020
+ ws.once("close", function close() {
20021
+ if (!called) callback(err);
20022
+ process.nextTick(emitClose, duplex);
20023
+ });
20024
+ if (terminateOnDestroy) ws.terminate();
20025
+ };
20026
+ duplex._final = function(callback) {
20027
+ if (ws.readyState === ws.CONNECTING) {
20028
+ ws.once("open", function open() {
20029
+ duplex._final(callback);
20030
+ });
20031
+ return;
20032
+ }
20033
+ if (ws._socket === null) return;
20034
+ if (ws._socket._writableState.finished) {
20035
+ callback();
20036
+ if (duplex._readableState.endEmitted) duplex.destroy();
20037
+ } else {
20038
+ ws._socket.once("finish", function finish() {
20039
+ callback();
20040
+ });
20041
+ ws.close();
20042
+ }
20043
+ };
20044
+ duplex._read = function() {
20045
+ if (ws.isPaused) ws.resume();
20046
+ };
20047
+ duplex._write = function(chunk, encoding, callback) {
20048
+ if (ws.readyState === ws.CONNECTING) {
20049
+ ws.once("open", function open() {
20050
+ duplex._write(chunk, encoding, callback);
20051
+ });
20052
+ return;
20053
+ }
20054
+ ws.send(chunk, callback);
20055
+ };
20056
+ duplex.on("end", duplexOnEnd);
20057
+ duplex.on("error", duplexOnError);
20058
+ return duplex;
20059
+ }
20060
+ module.exports = createWebSocketStream2;
20061
+ }
20062
+ });
20063
+
20064
+ // node_modules/.pnpm/ws@8.19.0/node_modules/ws/lib/subprotocol.js
20065
+ var require_subprotocol = __commonJS({
20066
+ "node_modules/.pnpm/ws@8.19.0/node_modules/ws/lib/subprotocol.js"(exports, module) {
20067
+ "use strict";
20068
+ var { tokenChars } = require_validation();
20069
+ function parse(header) {
20070
+ const protocols = /* @__PURE__ */ new Set();
20071
+ let start = -1;
20072
+ let end = -1;
20073
+ let i = 0;
20074
+ for (i; i < header.length; i++) {
20075
+ const code = header.charCodeAt(i);
20076
+ if (end === -1 && tokenChars[code] === 1) {
20077
+ if (start === -1) start = i;
20078
+ } else if (i !== 0 && (code === 32 || code === 9)) {
20079
+ if (end === -1 && start !== -1) end = i;
20080
+ } else if (code === 44) {
20081
+ if (start === -1) {
20082
+ throw new SyntaxError(`Unexpected character at index ${i}`);
20083
+ }
20084
+ if (end === -1) end = i;
20085
+ const protocol2 = header.slice(start, end);
20086
+ if (protocols.has(protocol2)) {
20087
+ throw new SyntaxError(`The "${protocol2}" subprotocol is duplicated`);
20088
+ }
20089
+ protocols.add(protocol2);
20090
+ start = end = -1;
20091
+ } else {
20092
+ throw new SyntaxError(`Unexpected character at index ${i}`);
20093
+ }
20094
+ }
20095
+ if (start === -1 || end !== -1) {
20096
+ throw new SyntaxError("Unexpected end of input");
20097
+ }
20098
+ const protocol = header.slice(start, i);
20099
+ if (protocols.has(protocol)) {
20100
+ throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);
20101
+ }
20102
+ protocols.add(protocol);
20103
+ return protocols;
20104
+ }
20105
+ module.exports = { parse };
20106
+ }
20107
+ });
20108
+
20109
+ // node_modules/.pnpm/ws@8.19.0/node_modules/ws/lib/websocket-server.js
20110
+ var require_websocket_server = __commonJS({
20111
+ "node_modules/.pnpm/ws@8.19.0/node_modules/ws/lib/websocket-server.js"(exports, module) {
20112
+ "use strict";
20113
+ var EventEmitter3 = __require("events");
20114
+ var http = __require("http");
20115
+ var { Duplex } = __require("stream");
20116
+ var { createHash: createHash2 } = __require("crypto");
20117
+ var extension = require_extension();
20118
+ var PerMessageDeflate = require_permessage_deflate();
20119
+ var subprotocol = require_subprotocol();
20120
+ var WebSocket2 = require_websocket();
20121
+ var { CLOSE_TIMEOUT, GUID, kWebSocket } = require_constants();
20122
+ var keyRegex = /^[+/0-9A-Za-z]{22}==$/;
20123
+ var RUNNING = 0;
20124
+ var CLOSING = 1;
20125
+ var CLOSED = 2;
20126
+ var WebSocketServer2 = class extends EventEmitter3 {
20127
+ /**
20128
+ * Create a `WebSocketServer` instance.
20129
+ *
20130
+ * @param {Object} options Configuration options
20131
+ * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
20132
+ * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
20133
+ * multiple times in the same tick
20134
+ * @param {Boolean} [options.autoPong=true] Specifies whether or not to
20135
+ * automatically send a pong in response to a ping
20136
+ * @param {Number} [options.backlog=511] The maximum length of the queue of
20137
+ * pending connections
20138
+ * @param {Boolean} [options.clientTracking=true] Specifies whether or not to
20139
+ * track clients
20140
+ * @param {Number} [options.closeTimeout=30000] Duration in milliseconds to
20141
+ * wait for the closing handshake to finish after `websocket.close()` is
20142
+ * called
20143
+ * @param {Function} [options.handleProtocols] A hook to handle protocols
20144
+ * @param {String} [options.host] The hostname where to bind the server
20145
+ * @param {Number} [options.maxPayload=104857600] The maximum allowed message
20146
+ * size
20147
+ * @param {Boolean} [options.noServer=false] Enable no server mode
20148
+ * @param {String} [options.path] Accept only connections matching this path
20149
+ * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable
20150
+ * permessage-deflate
20151
+ * @param {Number} [options.port] The port where to bind the server
20152
+ * @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S
20153
+ * server to use
20154
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
20155
+ * not to skip UTF-8 validation for text and close messages
20156
+ * @param {Function} [options.verifyClient] A hook to reject connections
20157
+ * @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket`
20158
+ * class to use. It must be the `WebSocket` class or class that extends it
20159
+ * @param {Function} [callback] A listener for the `listening` event
20160
+ */
20161
+ constructor(options, callback) {
20162
+ super();
20163
+ options = {
20164
+ allowSynchronousEvents: true,
20165
+ autoPong: true,
20166
+ maxPayload: 100 * 1024 * 1024,
20167
+ skipUTF8Validation: false,
20168
+ perMessageDeflate: false,
20169
+ handleProtocols: null,
20170
+ clientTracking: true,
20171
+ closeTimeout: CLOSE_TIMEOUT,
20172
+ verifyClient: null,
20173
+ noServer: false,
20174
+ backlog: null,
20175
+ // use default (511 as implemented in net.js)
20176
+ server: null,
20177
+ host: null,
20178
+ path: null,
20179
+ port: null,
20180
+ WebSocket: WebSocket2,
20181
+ ...options
20182
+ };
20183
+ if (options.port == null && !options.server && !options.noServer || options.port != null && (options.server || options.noServer) || options.server && options.noServer) {
20184
+ throw new TypeError(
20185
+ 'One and only one of the "port", "server", or "noServer" options must be specified'
20186
+ );
20187
+ }
20188
+ if (options.port != null) {
20189
+ this._server = http.createServer((req, res) => {
20190
+ const body = http.STATUS_CODES[426];
20191
+ res.writeHead(426, {
20192
+ "Content-Length": body.length,
20193
+ "Content-Type": "text/plain"
20194
+ });
20195
+ res.end(body);
20196
+ });
20197
+ this._server.listen(
20198
+ options.port,
20199
+ options.host,
20200
+ options.backlog,
20201
+ callback
20202
+ );
20203
+ } else if (options.server) {
20204
+ this._server = options.server;
20205
+ }
20206
+ if (this._server) {
20207
+ const emitConnection = this.emit.bind(this, "connection");
20208
+ this._removeListeners = addListeners(this._server, {
20209
+ listening: this.emit.bind(this, "listening"),
20210
+ error: this.emit.bind(this, "error"),
20211
+ upgrade: (req, socket, head) => {
20212
+ this.handleUpgrade(req, socket, head, emitConnection);
20213
+ }
20214
+ });
20215
+ }
20216
+ if (options.perMessageDeflate === true) options.perMessageDeflate = {};
20217
+ if (options.clientTracking) {
20218
+ this.clients = /* @__PURE__ */ new Set();
20219
+ this._shouldEmitClose = false;
20220
+ }
20221
+ this.options = options;
20222
+ this._state = RUNNING;
20223
+ }
20224
+ /**
20225
+ * Returns the bound address, the address family name, and port of the server
20226
+ * as reported by the operating system if listening on an IP socket.
20227
+ * If the server is listening on a pipe or UNIX domain socket, the name is
20228
+ * returned as a string.
20229
+ *
20230
+ * @return {(Object|String|null)} The address of the server
20231
+ * @public
20232
+ */
20233
+ address() {
20234
+ if (this.options.noServer) {
20235
+ throw new Error('The server is operating in "noServer" mode');
20236
+ }
20237
+ if (!this._server) return null;
20238
+ return this._server.address();
20239
+ }
20240
+ /**
20241
+ * Stop the server from accepting new connections and emit the `'close'` event
20242
+ * when all existing connections are closed.
20243
+ *
20244
+ * @param {Function} [cb] A one-time listener for the `'close'` event
20245
+ * @public
20246
+ */
20247
+ close(cb) {
20248
+ if (this._state === CLOSED) {
20249
+ if (cb) {
20250
+ this.once("close", () => {
20251
+ cb(new Error("The server is not running"));
20252
+ });
20253
+ }
20254
+ process.nextTick(emitClose, this);
20255
+ return;
20256
+ }
20257
+ if (cb) this.once("close", cb);
20258
+ if (this._state === CLOSING) return;
20259
+ this._state = CLOSING;
20260
+ if (this.options.noServer || this.options.server) {
20261
+ if (this._server) {
20262
+ this._removeListeners();
20263
+ this._removeListeners = this._server = null;
20264
+ }
20265
+ if (this.clients) {
20266
+ if (!this.clients.size) {
20267
+ process.nextTick(emitClose, this);
20268
+ } else {
20269
+ this._shouldEmitClose = true;
20270
+ }
20271
+ } else {
20272
+ process.nextTick(emitClose, this);
20273
+ }
20274
+ } else {
20275
+ const server = this._server;
20276
+ this._removeListeners();
20277
+ this._removeListeners = this._server = null;
20278
+ server.close(() => {
20279
+ emitClose(this);
20280
+ });
20281
+ }
20282
+ }
20283
+ /**
20284
+ * See if a given request should be handled by this server instance.
20285
+ *
20286
+ * @param {http.IncomingMessage} req Request object to inspect
20287
+ * @return {Boolean} `true` if the request is valid, else `false`
20288
+ * @public
20289
+ */
20290
+ shouldHandle(req) {
20291
+ if (this.options.path) {
20292
+ const index = req.url.indexOf("?");
20293
+ const pathname = index !== -1 ? req.url.slice(0, index) : req.url;
20294
+ if (pathname !== this.options.path) return false;
20295
+ }
20296
+ return true;
20297
+ }
20298
+ /**
20299
+ * Handle a HTTP Upgrade request.
20300
+ *
20301
+ * @param {http.IncomingMessage} req The request object
20302
+ * @param {Duplex} socket The network socket between the server and client
20303
+ * @param {Buffer} head The first packet of the upgraded stream
20304
+ * @param {Function} cb Callback
20305
+ * @public
20306
+ */
20307
+ handleUpgrade(req, socket, head, cb) {
20308
+ socket.on("error", socketOnError);
20309
+ const key = req.headers["sec-websocket-key"];
20310
+ const upgrade = req.headers.upgrade;
20311
+ const version = +req.headers["sec-websocket-version"];
20312
+ if (req.method !== "GET") {
20313
+ const message = "Invalid HTTP method";
20314
+ abortHandshakeOrEmitwsClientError(this, req, socket, 405, message);
20315
+ return;
20316
+ }
20317
+ if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") {
20318
+ const message = "Invalid Upgrade header";
20319
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
20320
+ return;
20321
+ }
20322
+ if (key === void 0 || !keyRegex.test(key)) {
20323
+ const message = "Missing or invalid Sec-WebSocket-Key header";
20324
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
20325
+ return;
20326
+ }
20327
+ if (version !== 13 && version !== 8) {
20328
+ const message = "Missing or invalid Sec-WebSocket-Version header";
20329
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message, {
20330
+ "Sec-WebSocket-Version": "13, 8"
20331
+ });
20332
+ return;
20333
+ }
20334
+ if (!this.shouldHandle(req)) {
20335
+ abortHandshake(socket, 400);
20336
+ return;
20337
+ }
20338
+ const secWebSocketProtocol = req.headers["sec-websocket-protocol"];
20339
+ let protocols = /* @__PURE__ */ new Set();
20340
+ if (secWebSocketProtocol !== void 0) {
20341
+ try {
20342
+ protocols = subprotocol.parse(secWebSocketProtocol);
20343
+ } catch (err) {
20344
+ const message = "Invalid Sec-WebSocket-Protocol header";
20345
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
20346
+ return;
20347
+ }
20348
+ }
20349
+ const secWebSocketExtensions = req.headers["sec-websocket-extensions"];
20350
+ const extensions = {};
20351
+ if (this.options.perMessageDeflate && secWebSocketExtensions !== void 0) {
20352
+ const perMessageDeflate = new PerMessageDeflate(
20353
+ this.options.perMessageDeflate,
20354
+ true,
20355
+ this.options.maxPayload
20356
+ );
20357
+ try {
20358
+ const offers = extension.parse(secWebSocketExtensions);
20359
+ if (offers[PerMessageDeflate.extensionName]) {
20360
+ perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]);
20361
+ extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
20362
+ }
20363
+ } catch (err) {
20364
+ const message = "Invalid or unacceptable Sec-WebSocket-Extensions header";
20365
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
20366
+ return;
20367
+ }
20368
+ }
20369
+ if (this.options.verifyClient) {
20370
+ const info = {
20371
+ origin: req.headers[`${version === 8 ? "sec-websocket-origin" : "origin"}`],
20372
+ secure: !!(req.socket.authorized || req.socket.encrypted),
20373
+ req
20374
+ };
20375
+ if (this.options.verifyClient.length === 2) {
20376
+ this.options.verifyClient(info, (verified, code, message, headers) => {
20377
+ if (!verified) {
20378
+ return abortHandshake(socket, code || 401, message, headers);
20379
+ }
20380
+ this.completeUpgrade(
20381
+ extensions,
20382
+ key,
20383
+ protocols,
20384
+ req,
20385
+ socket,
20386
+ head,
20387
+ cb
20388
+ );
20389
+ });
20390
+ return;
20391
+ }
20392
+ if (!this.options.verifyClient(info)) return abortHandshake(socket, 401);
20393
+ }
20394
+ this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);
20395
+ }
20396
+ /**
20397
+ * Upgrade the connection to WebSocket.
20398
+ *
20399
+ * @param {Object} extensions The accepted extensions
20400
+ * @param {String} key The value of the `Sec-WebSocket-Key` header
20401
+ * @param {Set} protocols The subprotocols
20402
+ * @param {http.IncomingMessage} req The request object
20403
+ * @param {Duplex} socket The network socket between the server and client
20404
+ * @param {Buffer} head The first packet of the upgraded stream
20405
+ * @param {Function} cb Callback
20406
+ * @throws {Error} If called more than once with the same socket
20407
+ * @private
20408
+ */
20409
+ completeUpgrade(extensions, key, protocols, req, socket, head, cb) {
20410
+ if (!socket.readable || !socket.writable) return socket.destroy();
20411
+ if (socket[kWebSocket]) {
20412
+ throw new Error(
20413
+ "server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration"
20414
+ );
20415
+ }
20416
+ if (this._state > RUNNING) return abortHandshake(socket, 503);
20417
+ const digest = createHash2("sha1").update(key + GUID).digest("base64");
20418
+ const headers = [
20419
+ "HTTP/1.1 101 Switching Protocols",
20420
+ "Upgrade: websocket",
20421
+ "Connection: Upgrade",
20422
+ `Sec-WebSocket-Accept: ${digest}`
20423
+ ];
20424
+ const ws = new this.options.WebSocket(null, void 0, this.options);
20425
+ if (protocols.size) {
20426
+ const protocol = this.options.handleProtocols ? this.options.handleProtocols(protocols, req) : protocols.values().next().value;
20427
+ if (protocol) {
20428
+ headers.push(`Sec-WebSocket-Protocol: ${protocol}`);
20429
+ ws._protocol = protocol;
20430
+ }
20431
+ }
20432
+ if (extensions[PerMessageDeflate.extensionName]) {
20433
+ const params = extensions[PerMessageDeflate.extensionName].params;
20434
+ const value = extension.format({
20435
+ [PerMessageDeflate.extensionName]: [params]
20436
+ });
20437
+ headers.push(`Sec-WebSocket-Extensions: ${value}`);
20438
+ ws._extensions = extensions;
20439
+ }
20440
+ this.emit("headers", headers, req);
20441
+ socket.write(headers.concat("\r\n").join("\r\n"));
20442
+ socket.removeListener("error", socketOnError);
20443
+ ws.setSocket(socket, head, {
20444
+ allowSynchronousEvents: this.options.allowSynchronousEvents,
20445
+ maxPayload: this.options.maxPayload,
20446
+ skipUTF8Validation: this.options.skipUTF8Validation
20447
+ });
20448
+ if (this.clients) {
20449
+ this.clients.add(ws);
20450
+ ws.on("close", () => {
20451
+ this.clients.delete(ws);
20452
+ if (this._shouldEmitClose && !this.clients.size) {
20453
+ process.nextTick(emitClose, this);
20454
+ }
20455
+ });
20456
+ }
20457
+ cb(ws, req);
20458
+ }
20459
+ };
20460
+ module.exports = WebSocketServer2;
20461
+ function addListeners(server, map) {
20462
+ for (const event of Object.keys(map)) server.on(event, map[event]);
20463
+ return function removeListeners() {
20464
+ for (const event of Object.keys(map)) {
20465
+ server.removeListener(event, map[event]);
20466
+ }
20467
+ };
20468
+ }
20469
+ function emitClose(server) {
20470
+ server._state = CLOSED;
20471
+ server.emit("close");
20472
+ }
20473
+ function socketOnError() {
20474
+ this.destroy();
20475
+ }
20476
+ function abortHandshake(socket, code, message, headers) {
20477
+ message = message || http.STATUS_CODES[code];
20478
+ headers = {
20479
+ Connection: "close",
20480
+ "Content-Type": "text/html",
20481
+ "Content-Length": Buffer.byteLength(message),
20482
+ ...headers
20483
+ };
20484
+ socket.once("finish", socket.destroy);
20485
+ socket.end(
20486
+ `HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r
20487
+ ` + Object.keys(headers).map((h) => `${h}: ${headers[h]}`).join("\r\n") + "\r\n\r\n" + message
20488
+ );
20489
+ }
20490
+ function abortHandshakeOrEmitwsClientError(server, req, socket, code, message, headers) {
20491
+ if (server.listenerCount("wsClientError")) {
20492
+ const err = new Error(message);
20493
+ Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError);
20494
+ server.emit("wsClientError", err, socket, req);
20495
+ } else {
20496
+ abortHandshake(socket, code, message, headers);
20497
+ }
20498
+ }
20499
+ }
20500
+ });
20501
+
20502
+ // node_modules/.pnpm/ws@8.19.0/node_modules/ws/wrapper.mjs
20503
+ var import_stream, import_receiver, import_sender, import_websocket, import_websocket_server;
20504
+ var init_wrapper = __esm({
20505
+ "node_modules/.pnpm/ws@8.19.0/node_modules/ws/wrapper.mjs"() {
20506
+ import_stream = __toESM(require_stream(), 1);
20507
+ import_receiver = __toESM(require_receiver(), 1);
20508
+ import_sender = __toESM(require_sender(), 1);
20509
+ import_websocket = __toESM(require_websocket(), 1);
20510
+ import_websocket_server = __toESM(require_websocket_server(), 1);
20511
+ }
20512
+ });
20513
+
20514
+ // packages/cli/dist/tui/render.js
20515
+ function ansi2(code, text) {
20516
+ return isTTY2 ? `\x1B[${code}m${text}\x1B[0m` : text;
20517
+ }
20518
+ function fg256(code, text) {
20519
+ return isTTY2 ? `\x1B[38;5;${code}m${text}\x1B[0m` : text;
20520
+ }
20521
+ function setEmojisEnabled(enabled) {
20522
+ _emojisEnabled = enabled;
20523
+ }
20524
+ function getEmojisEnabled() {
20525
+ return _emojisEnabled;
20526
+ }
20527
+ function setColorsEnabled(enabled) {
20528
+ _colorsEnabled = enabled;
20529
+ }
20530
+ function getColorsEnabled() {
20531
+ return _colorsEnabled;
20532
+ }
20533
+ function getTermWidth() {
20534
+ return process.stdout.columns ?? 80;
20535
+ }
20536
+ function formatMarkdownLine(line) {
20537
+ const headingMatch = line.match(/^(#{1,6})\s+(.*)/);
20538
+ if (headingMatch) {
20539
+ const level = headingMatch[1].length;
20540
+ const text = headingMatch[2];
20541
+ const colors = [MD.heading1, MD.heading2, MD.heading3, MD.heading3, 183, 183];
20542
+ return c2.bold(fg256(colors[level - 1] ?? 147, formatInlineMarkdown(text)));
20543
+ }
20544
+ if (/^[-*_]{3,}\s*$/.test(line)) {
20545
+ const w = getTermWidth() - 10;
20546
+ return fg256(MD.hr, "\u2500".repeat(Math.min(w, 60)));
20547
+ }
20548
+ if (/^>\s?/.test(line)) {
20549
+ const content = line.replace(/^>\s?/, "");
20550
+ return fg256(MD.blockquote, "\u2502 ") + c2.italic(fg256(MD.blockquote, formatInlineMarkdown(content)));
20551
+ }
20552
+ if (/^\|(.+)\|/.test(line)) {
20553
+ if (/^\|[\s:_-]+\|/.test(line)) {
20554
+ return fg256(MD.tableBar, line);
20555
+ }
20556
+ return line.replace(/([^|]+)/g, (cell) => {
20557
+ const trimmed = cell.trim();
20558
+ if (!trimmed)
20559
+ return cell;
20560
+ const leading = cell.match(/^(\s*)/)?.[1] ?? "";
20561
+ const trailing = cell.match(/(\s*)$/)?.[1] ?? "";
20562
+ return leading + formatInlineMarkdown(trimmed) + trailing;
20563
+ });
20564
+ }
20565
+ const ulMatch = line.match(/^(\s*)([-*+])\s+(.*)/);
20566
+ if (ulMatch) {
20567
+ return ulMatch[1] + fg256(MD.listBullet, "\u2022") + " " + formatInlineMarkdown(ulMatch[3]);
20568
+ }
20569
+ const olMatch = line.match(/^(\s*)(\d+[.)])\s+(.*)/);
20570
+ if (olMatch) {
20571
+ return olMatch[1] + fg256(MD.listBullet, olMatch[2]) + " " + formatInlineMarkdown(olMatch[3]);
20572
+ }
20573
+ return formatInlineMarkdown(line);
20574
+ }
20575
+ function formatInlineMarkdown(text) {
20576
+ let result = text;
20577
+ result = result.replace(/`([^`]+)`/g, (_m, code) => fg256(MD.inlineCode, code));
20578
+ result = result.replace(/\*{3}([^*]+)\*{3}/g, (_m, t) => c2.bold(c2.italic(t)));
20579
+ result = result.replace(/\*{2}([^*]+)\*{2}/g, (_m, t) => c2.bold(t));
20580
+ result = result.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g, (_m, t) => c2.italic(t));
20581
+ result = result.replace(/\[([^\]]+)\]\(([^)]+)\)/g, (_m, label, url) => c2.bold(fg256(MD.link, label)) + " " + c2.dim(fg256(MD.link, `(${url})`)));
20582
+ result = result.replace(/__([^_]+)__/g, (_m, t) => c2.bold(t));
20583
+ result = result.replace(/(?<!_)_([^_]+)_(?!_)/g, (_m, t) => c2.italic(t));
20584
+ result = result.replace(/~~([^~]+)~~/g, (_m, t) => c2.dim(t));
20585
+ return result;
20586
+ }
20587
+ function formatMarkdownBlock(text) {
20588
+ const lines = text.split("\n");
20589
+ const result = [];
20590
+ let inCodeBlock = false;
20591
+ let codeLang = "";
20592
+ for (const line of lines) {
20593
+ const trimmedLine = line.trimStart();
20594
+ if (trimmedLine.startsWith("```")) {
20595
+ if (inCodeBlock) {
20596
+ result.push(c2.dim(" ```"));
20597
+ inCodeBlock = false;
20598
+ codeLang = "";
20599
+ } else {
20600
+ codeLang = trimmedLine.slice(3).trim();
20601
+ result.push(c2.dim(" ```" + codeLang));
20602
+ inCodeBlock = true;
20603
+ }
20604
+ continue;
20605
+ }
20606
+ if (inCodeBlock) {
20607
+ result.push(" " + c2.dim(line));
20608
+ } else {
20609
+ result.push(formatMarkdownLine(line));
20610
+ }
20611
+ }
20612
+ return result.join("\n");
20613
+ }
20614
+ function renderUserMessage(text) {
20615
+ process.stdout.write(`
20616
+ ${c2.bold(c2.blue("> "))}${c2.bold(text)}
20617
+ `);
20618
+ }
20619
+ function renderAssistantText(text) {
20620
+ if (!text.trim())
20621
+ return;
20622
+ const formatted = formatMarkdownBlock(text);
20623
+ const lines = formatted.split("\n");
20624
+ for (const line of lines) {
20625
+ process.stdout.write(` ${line}
20626
+ `);
20627
+ }
20628
+ }
20629
+ function renderVoiceText(text) {
20630
+ process.stdout.write(` ${c2.dim("\u{1F50A}")} ${c2.italic(c2.dim(text))}
20631
+ `);
20632
+ }
20633
+ function renderUserInterrupt(text) {
20634
+ process.stdout.write(`
20635
+ ${c2.cyan("\u21AA")} ${c2.bold("Context added:")} ${text}
20636
+ `);
20637
+ }
20638
+ function renderTaskAborted() {
20639
+ process.stdout.write(`
20640
+ ${c2.yellow("\u26A0")} ${c2.bold("Task aborted by user")}
20641
+ `);
20642
+ }
20643
+ function renderToolCallStart(toolName, args, verbose) {
20644
+ const icon = TOOL_ICONS[toolName] ?? "\u{1F527}";
20645
+ const label = TOOL_LABELS[toolName] ?? toolName;
20646
+ const argsSummary = formatToolArgs(toolName, args, verbose);
20647
+ const colorFn = _colorsEnabled ? TOOL_COLORS[toolName] ?? c2.dim : (t) => t;
20648
+ const emojiPrefix = _emojisEnabled ? `${icon} ` : "";
20649
+ process.stdout.write(`
20650
+ ${c2.dim("\u23BF")} ${emojiPrefix}${colorFn(c2.bold(label))}${argsSummary ? c2.dim(": ") + argsSummary : ""}
20651
+ `);
20652
+ }
20653
+ function renderToolResult(toolName, success, output, verbose) {
20654
+ const maxW = verbose ? Math.max(getTermWidth() - 10, 200) : getTermWidth() - 10;
20655
+ const prefix = ` ${c2.dim("\u23BF")} `;
20656
+ switch (toolName) {
20657
+ case "file_write": {
20658
+ const summary = extractFirstLine(output, maxW);
20659
+ if (success) {
20660
+ process.stdout.write(`${prefix}${c2.dim(summary)}
20661
+ `);
20662
+ } else {
20663
+ process.stdout.write(`${prefix}${c2.red(summary)}
20664
+ `);
20665
+ }
20666
+ return;
20667
+ }
20668
+ case "file_edit": {
20669
+ const summary = extractFirstLine(output, maxW);
20670
+ if (success) {
20671
+ process.stdout.write(`${prefix}${c2.dim(summary)}
20672
+ `);
20673
+ } else {
20674
+ process.stdout.write(`${prefix}${c2.red(summary)}
20675
+ `);
20676
+ }
20677
+ return;
20678
+ }
20679
+ case "file_read": {
20680
+ if (!success) {
20681
+ process.stdout.write(`${prefix}${c2.red(extractFirstLine(output, maxW))}
20682
+ `);
20683
+ return;
20684
+ }
20685
+ renderCodePreview(output, prefix, maxW, 6);
20686
+ return;
20687
+ }
20688
+ case "shell":
20689
+ case "background_run": {
20690
+ renderShellOutput(output, success, prefix, maxW, 8);
20691
+ return;
20692
+ }
20693
+ case "grep_search": {
20694
+ renderShellOutput(output, success, prefix, maxW, 6);
20695
+ return;
20696
+ }
20697
+ case "task_complete": {
20698
+ process.stdout.write(`${prefix}${c2.green("\u2714")} ${c2.dim("Done")}
20699
+ `);
20700
+ return;
20701
+ }
20702
+ default:
20703
+ break;
20704
+ }
20705
+ const lines = output.split("\n").filter((l) => l.trim());
20706
+ if (lines.length === 0) {
20707
+ const icon = success ? _emojisEnabled ? c2.green("\u2714") : c2.green("+") : _emojisEnabled ? c2.red("\u2716") : c2.red("x");
20708
+ process.stdout.write(`${prefix}${icon} ${success ? c2.dim("Done") : c2.red("Failed")}
20709
+ `);
20710
+ return;
20711
+ }
20712
+ const maxLines = verbose ? 200 : 6;
20713
+ const shown = lines.slice(0, maxLines);
20714
+ for (const line of shown) {
20715
+ if (isRawJsonDump(line) && !verbose) {
20716
+ process.stdout.write(`${prefix}${c2.dim("(content omitted)")}
20717
+ `);
20718
+ return;
20719
+ }
20720
+ if (verbose) {
20721
+ const termW = getTermWidth() - 10;
20722
+ if (line.length > termW) {
20723
+ let remaining = line;
20724
+ let first = true;
20725
+ while (remaining.length > 0) {
20726
+ if (remaining.length <= termW) {
20727
+ const formatted2 = formatMarkdownLine(remaining);
20728
+ process.stdout.write(`${first ? prefix : prefix + " "}${formatted2 === remaining ? highlightToolOutput(remaining) : formatted2}
20729
+ `);
20730
+ break;
20731
+ }
20732
+ let breakAt = remaining.lastIndexOf(" ", termW);
20733
+ if (breakAt < termW * 0.3)
20734
+ breakAt = termW;
20735
+ const chunk = remaining.slice(0, breakAt);
20736
+ remaining = remaining.slice(breakAt).trimStart();
20737
+ const formatted = formatMarkdownLine(chunk);
20738
+ process.stdout.write(`${first ? prefix : prefix + " "}${formatted === chunk ? highlightToolOutput(chunk) : formatted}
20739
+ `);
20740
+ first = false;
20741
+ }
20742
+ } else {
20743
+ const formatted = formatMarkdownLine(line);
20744
+ process.stdout.write(`${prefix}${formatted === line ? highlightToolOutput(line) : formatted}
20745
+ `);
17095
20746
  }
17096
20747
  } else {
17097
20748
  const cropped = line.length > maxW ? line.slice(0, maxW - 3) + "..." : line;
@@ -17749,64 +21400,7 @@ var init_render = __esm({
17749
21400
  // packages/cli/dist/tui/voice-session.js
17750
21401
  import { createServer } from "node:http";
17751
21402
  import { spawn as spawn10, execSync as execSync19 } from "node:child_process";
17752
- import { createHash } from "node:crypto";
17753
21403
  import { EventEmitter as EventEmitter2 } from "node:events";
17754
- function parseWebSocketFrame(buf) {
17755
- if (buf.length < 2)
17756
- return null;
17757
- const firstByte = buf[0];
17758
- const secondByte = buf[1];
17759
- const opcode = firstByte & 15;
17760
- const masked = (secondByte & 128) !== 0;
17761
- let payloadLength = secondByte & 127;
17762
- let offset = 2;
17763
- if (payloadLength === 126) {
17764
- if (buf.length < 4)
17765
- return null;
17766
- payloadLength = buf.readUInt16BE(2);
17767
- offset = 4;
17768
- } else if (payloadLength === 127) {
17769
- if (buf.length < 10)
17770
- return null;
17771
- payloadLength = Number(buf.readBigUInt64BE(2));
17772
- offset = 10;
17773
- }
17774
- const maskKeyLength = masked ? 4 : 0;
17775
- const totalLength = offset + maskKeyLength + payloadLength;
17776
- if (buf.length < totalLength)
17777
- return null;
17778
- let payload;
17779
- if (masked) {
17780
- const maskKey = buf.subarray(offset, offset + 4);
17781
- payload = Buffer.alloc(payloadLength);
17782
- for (let i = 0; i < payloadLength; i++) {
17783
- payload[i] = buf[offset + 4 + i] ^ maskKey[i % 4];
17784
- }
17785
- } else {
17786
- payload = buf.subarray(offset, offset + payloadLength);
17787
- }
17788
- return { opcode, payload, complete: true };
17789
- }
17790
- function createWebSocketFrame(opcode, payload) {
17791
- const len = payload.length;
17792
- let header;
17793
- if (len < 126) {
17794
- header = Buffer.alloc(2);
17795
- header[0] = 128 | opcode;
17796
- header[1] = len;
17797
- } else if (len < 65536) {
17798
- header = Buffer.alloc(4);
17799
- header[0] = 128 | opcode;
17800
- header[1] = 126;
17801
- header.writeUInt16BE(len, 2);
17802
- } else {
17803
- header = Buffer.alloc(10);
17804
- header[0] = 128 | opcode;
17805
- header[1] = 127;
17806
- header.writeBigUInt64BE(BigInt(len), 2);
17807
- }
17808
- return Buffer.concat([header, payload]);
17809
- }
17810
21404
  function generateFrontendHTML() {
17811
21405
  return `<!DOCTYPE html>
17812
21406
  <html lang="en">
@@ -17818,8 +21412,8 @@ function generateFrontendHTML() {
17818
21412
  * { margin: 0; padding: 0; box-sizing: border-box; }
17819
21413
  body {
17820
21414
  background: #0a0a0f;
17821
- color: #e0e0e0;
17822
- font-family: 'SF Mono', 'Cascadia Code', 'Fira Code', monospace;
21415
+ color: #c4b5fd;
21416
+ font-family: 'SF Mono', 'Cascadia Code', 'Fira Code', 'JetBrains Mono', monospace;
17823
21417
  display: flex;
17824
21418
  flex-direction: column;
17825
21419
  align-items: center;
@@ -17827,78 +21421,170 @@ function generateFrontendHTML() {
17827
21421
  min-height: 100vh;
17828
21422
  overflow: hidden;
17829
21423
  }
17830
- #presence {
17831
- width: 200px; height: 200px;
17832
- border-radius: 50%;
17833
- background: radial-gradient(circle, rgba(100,180,255,0.3) 0%, rgba(100,180,255,0.05) 70%, transparent 100%);
17834
- box-shadow: 0 0 60px rgba(100,180,255,0.2);
17835
- transition: transform 0.05s ease;
17836
- margin-bottom: 2rem;
17837
- }
17838
- #presence.speaking {
17839
- background: radial-gradient(circle, rgba(100,255,180,0.4) 0%, rgba(100,255,180,0.08) 70%, transparent 100%);
17840
- box-shadow: 0 0 80px rgba(100,255,180,0.3);
21424
+ #waveform {
21425
+ width: 90%; max-width: 700px;
21426
+ height: 80px;
21427
+ display: flex;
21428
+ align-items: center;
21429
+ justify-content: center;
21430
+ font-size: 2rem;
21431
+ line-height: 1;
21432
+ letter-spacing: 0.05em;
21433
+ white-space: nowrap;
21434
+ overflow: hidden;
21435
+ margin-bottom: 1.5rem;
21436
+ user-select: none;
17841
21437
  }
17842
- #presence.listening {
17843
- background: radial-gradient(circle, rgba(255,180,100,0.4) 0%, rgba(255,180,100,0.08) 70%, transparent 100%);
17844
- box-shadow: 0 0 80px rgba(255,180,100,0.3);
21438
+ #title {
21439
+ font-size: 0.75rem;
21440
+ color: #7c3aed;
21441
+ letter-spacing: 0.3em;
21442
+ text-transform: uppercase;
21443
+ margin-bottom: 1.5rem;
17845
21444
  }
17846
21445
  #status {
17847
- font-size: 0.9rem;
17848
- color: #888;
21446
+ font-size: 0.85rem;
21447
+ color: #6b6b8a;
17849
21448
  margin-bottom: 1rem;
17850
21449
  }
17851
- #status .connected { color: #6f6; }
17852
- #status .disconnected { color: #f66; }
21450
+ #status .connected { color: #a78bfa; }
21451
+ #status .disconnected { color: #f87171; }
17853
21452
  #transcripts {
17854
21453
  width: 90%; max-width: 600px; max-height: 40vh;
17855
21454
  overflow-y: auto; padding: 1rem;
17856
- background: rgba(255,255,255,0.03);
17857
- border-radius: 8px;
17858
- border: 1px solid rgba(255,255,255,0.06);
21455
+ background: rgba(139,92,246,0.04);
21456
+ border-radius: 4px;
21457
+ border: 1px solid rgba(139,92,246,0.12);
17859
21458
  }
17860
21459
  .transcript {
17861
- padding: 0.4rem 0;
17862
- border-bottom: 1px solid rgba(255,255,255,0.04);
17863
- font-size: 0.85rem;
21460
+ padding: 0.35rem 0;
21461
+ border-bottom: 1px solid rgba(139,92,246,0.08);
21462
+ font-size: 0.8rem;
21463
+ color: #a5a0c8;
17864
21464
  }
17865
21465
  .transcript .speaker { font-weight: bold; margin-right: 0.5rem; }
17866
- .transcript .speaker.user { color: #ffb06a; }
17867
- .transcript .speaker.agent { color: #6ab4ff; }
21466
+ .transcript .speaker.user { color: #c084fc; }
21467
+ .transcript .speaker.agent { color: #8b5cf6; }
17868
21468
  #controls { margin-top: 1.5rem; }
17869
21469
  button {
17870
- background: rgba(100,180,255,0.15);
17871
- border: 1px solid rgba(100,180,255,0.3);
17872
- color: #e0e0e0;
17873
- padding: 0.6rem 1.5rem;
17874
- border-radius: 6px;
21470
+ background: rgba(139,92,246,0.12);
21471
+ border: 1px solid rgba(139,92,246,0.3);
21472
+ color: #c4b5fd;
21473
+ padding: 0.5rem 1.4rem;
21474
+ border-radius: 4px;
17875
21475
  font-family: inherit;
17876
- font-size: 0.9rem;
21476
+ font-size: 0.8rem;
17877
21477
  cursor: pointer;
17878
21478
  transition: all 0.2s;
21479
+ letter-spacing: 0.05em;
17879
21480
  }
17880
- button:hover { background: rgba(100,180,255,0.25); }
17881
- button.active { background: rgba(255,100,100,0.2); border-color: rgba(255,100,100,0.4); }
21481
+ button:hover { background: rgba(139,92,246,0.22); }
21482
+ button.active { background: rgba(239,68,68,0.15); border-color: rgba(239,68,68,0.35); color: #fca5a5; }
17882
21483
  </style>
17883
21484
  </head>
17884
21485
  <body>
17885
- <div id="presence"></div>
21486
+ <div id="title">open agents &mdash; voice session</div>
21487
+ <div id="waveform"></div>
17886
21488
  <div id="status">
17887
- <span class="disconnected">Connecting...</span>
21489
+ <span class="disconnected">connecting...</span>
17888
21490
  </div>
17889
21491
  <div id="transcripts"></div>
17890
21492
  <div id="controls">
17891
- <button id="micBtn" onclick="toggleMic()">Start Mic</button>
21493
+ <button id="micBtn" onclick="toggleMic()">start mic</button>
17892
21494
  </div>
17893
21495
 
17894
21496
  <script>
17895
- const presence = document.getElementById('presence');
21497
+ const waveEl = document.getElementById('waveform');
17896
21498
  const statusEl = document.getElementById('status');
17897
21499
  const transcriptsEl = document.getElementById('transcripts');
17898
21500
  const micBtn = document.getElementById('micBtn');
17899
21501
 
21502
+ // ---------------------------------------------------------------------------
21503
+ // Braille waveform \u2014 ported from TUI braille-spinner.ts
21504
+ // ---------------------------------------------------------------------------
21505
+
21506
+ const DENSITY = [
21507
+ '\\u2800', '\\u2840', '\\u28C0', '\\u28C4', '\\u28E4', '\\u28E6', '\\u28F6', '\\u28F7', '\\u28FF'
21508
+ ];
21509
+ const WAVE = [...DENSITY, ...DENSITY.slice(1, -1).reverse()]; // 16 entries
21510
+
21511
+ // Color themes: arrays of 9 CSS colors (sparse -> dense)
21512
+ const THEME_IDLE = ['#1e1b2e','#3b2d6b','#5b3fa0','#7c3aed','#8b5cf6','#a78bfa','#c4b5fd','#ddd6fe','#ede9fe'];
21513
+ const THEME_SPEAKING = ['#0a2e1a','#0d5f2f','#15803d','#22c55e','#4ade80','#86efac','#bbf7d0','#dcfce7','#f0fdf4'];
21514
+ const THEME_LISTENING = ['#2e1b0a','#6b3d0d','#a05f15','#ed8b3a','#f6a05c','#fabe8b','#fdd5b5','#fde6d6','#fef3e9'];
21515
+
21516
+ function buildColorRamp(ramp) {
21517
+ return [...ramp, ...ramp.slice(1, -1).reverse()]; // 16 entries
21518
+ }
21519
+
21520
+ let waveFrame = 0;
21521
+ let waveState = 'idle'; // 'idle' | 'speaking' | 'listening'
21522
+ let micLevel = 0; // 0-1, drives wave amplitude when listening
21523
+
21524
+ function renderWave() {
21525
+ const cols = Math.min(40, Math.floor(waveEl.offsetWidth / 20)) || 30;
21526
+ const cycleLen = WAVE.length; // 16
21527
+ const theme = waveState === 'speaking' ? THEME_SPEAKING :
21528
+ waveState === 'listening' ? THEME_LISTENING : THEME_IDLE;
21529
+ const colorRamp = buildColorRamp(theme);
21530
+
21531
+ // Dynamic speed: slow breathing when idle, faster when active
21532
+ const breathPhase = Math.sin(waveFrame * 0.06);
21533
+ let speed;
21534
+ if (waveState === 'speaking') {
21535
+ speed = 2.5 + breathPhase * 0.5;
21536
+ } else if (waveState === 'listening') {
21537
+ speed = 2.0 + micLevel * 3.0 + breathPhase * 0.3;
21538
+ } else {
21539
+ speed = 1.2 + breathPhase * 0.8;
21540
+ }
21541
+
21542
+ // Amplitude: gentle when idle, driven by audio level when active
21543
+ const densityScale = waveState === 'idle' ? 0.35 + breathPhase * 0.15 :
21544
+ waveState === 'listening' ? 0.3 + micLevel * 0.7 :
21545
+ 0.6 + breathPhase * 0.2;
21546
+
21547
+ // Slinky effect: per-column phase distortion
21548
+ const slinkyAmp = 1.5 + densityScale * 2.0;
21549
+
21550
+ let html = '';
21551
+ for (let col = 0; col < cols; col++) {
21552
+ const slinkyOffset = Math.sin(col * 0.1 + waveFrame * 0.02) * slinkyAmp;
21553
+ const rawPhase = col * speed + waveFrame + slinkyOffset;
21554
+ const normalizedPhase = ((rawPhase % cycleLen) + cycleLen) % cycleLen;
21555
+ const waveIdx = Math.round(normalizedPhase) % cycleLen;
21556
+
21557
+ // Scale amplitude by density
21558
+ let amplitude = waveIdx <= 8 ? waveIdx : 16 - waveIdx;
21559
+ const scaledAmp = Math.round(amplitude * densityScale);
21560
+ let scaledIdx = waveIdx <= 8 ? scaledAmp : 16 - scaledAmp;
21561
+ scaledIdx = Math.max(0, Math.min(cycleLen - 1, scaledIdx));
21562
+
21563
+ const ch = WAVE[scaledIdx];
21564
+ const color = colorRamp[scaledIdx];
21565
+ html += '<span style="color:' + color + '">' + ch + '</span>';
21566
+ }
21567
+ waveEl.innerHTML = html;
21568
+ }
21569
+
21570
+ let waveTimer = null;
21571
+ function startWave() {
21572
+ if (waveTimer) return;
21573
+ waveTimer = setInterval(() => {
21574
+ waveFrame++;
21575
+ renderWave();
21576
+ }, 80);
21577
+ }
21578
+
21579
+ startWave();
21580
+
21581
+ // ---------------------------------------------------------------------------
21582
+ // WebSocket
21583
+ // ---------------------------------------------------------------------------
21584
+
17900
21585
  let ws = null;
17901
- let audioCtx = null;
21586
+ let playbackCtx = null;
21587
+ let micCtx = null;
17902
21588
  let micStream = null;
17903
21589
  let scriptProcessor = null;
17904
21590
  let micActive = false;
@@ -17906,27 +21592,39 @@ let playbackQueue = [];
17906
21592
  let isPlaying = false;
17907
21593
  let reconnectDelay = 1000;
17908
21594
  let reconnectTimer = null;
21595
+ let connecting = false;
21596
+ let disconnectGrace = null;
17909
21597
 
17910
- // Connect WebSocket
17911
21598
  function connect() {
21599
+ if (connecting) return;
21600
+ connecting = true;
17912
21601
  if (reconnectTimer) { clearTimeout(reconnectTimer); reconnectTimer = null; }
21602
+ if (ws) {
21603
+ try { ws.onclose = null; ws.onerror = null; ws.onopen = null; ws.onmessage = null; ws.close(); } catch(e) {}
21604
+ ws = null;
21605
+ }
17913
21606
  const proto = location.protocol === 'https:' ? 'wss:' : 'ws:';
17914
21607
  ws = new WebSocket(proto + '//' + location.host + '/ws');
17915
21608
  ws.binaryType = 'arraybuffer';
17916
21609
 
17917
21610
  ws.onopen = () => {
17918
- statusEl.innerHTML = '<span class="connected">Connected</span>';
17919
- reconnectDelay = 1000; // Reset backoff on successful connection
21611
+ connecting = false;
21612
+ if (disconnectGrace) { clearTimeout(disconnectGrace); disconnectGrace = null; }
21613
+ statusEl.innerHTML = '<span class="connected">connected</span>';
21614
+ reconnectDelay = 1000;
17920
21615
  };
17921
21616
 
17922
- ws.onerror = () => {
17923
- // Error fires before close \u2014 just update status, close handler does reconnect
17924
- statusEl.innerHTML = '<span class="disconnected">Connection error</span>';
17925
- };
21617
+ ws.onerror = () => {};
17926
21618
 
17927
21619
  ws.onclose = () => {
17928
- statusEl.innerHTML = '<span class="disconnected">Disconnected \u2014 reconnecting...</span>';
17929
- // Exponential backoff: 1s, 2s, 4s, max 10s
21620
+ connecting = false;
21621
+ ws = null;
21622
+ if (!disconnectGrace) {
21623
+ disconnectGrace = setTimeout(() => {
21624
+ disconnectGrace = null;
21625
+ statusEl.innerHTML = '<span class="disconnected">reconnecting...</span>';
21626
+ }, 2000);
21627
+ }
17930
21628
  reconnectTimer = setTimeout(connect, reconnectDelay);
17931
21629
  reconnectDelay = Math.min(reconnectDelay * 2, 10000);
17932
21630
  };
@@ -17936,21 +21634,18 @@ function connect() {
17936
21634
  try {
17937
21635
  const msg = JSON.parse(evt.data);
17938
21636
  if (msg.type === 'keepalive') {
17939
- // Respond to keep connection alive through proxies
17940
21637
  if (ws.readyState === 1) ws.send(JSON.stringify({ type: 'pong' }));
17941
21638
  return;
17942
21639
  }
17943
21640
  if (msg.type === 'transcript') {
17944
21641
  addTranscript(msg.speaker, msg.text);
17945
21642
  } else if (msg.type === 'speaking_start') {
17946
- presence.classList.add('speaking');
17947
- presence.classList.remove('listening');
21643
+ waveState = 'speaking';
17948
21644
  } else if (msg.type === 'speaking_end') {
17949
- presence.classList.remove('speaking');
21645
+ waveState = micActive ? 'listening' : 'idle';
17950
21646
  }
17951
21647
  } catch {}
17952
21648
  } else {
17953
- // Binary = PCM audio from agent TTS
17954
21649
  playbackQueue.push(new Int16Array(evt.data));
17955
21650
  if (!isPlaying) drainPlayback();
17956
21651
  }
@@ -17961,7 +21656,7 @@ function addTranscript(speaker, text) {
17961
21656
  const div = document.createElement('div');
17962
21657
  div.className = 'transcript';
17963
21658
  div.innerHTML = '<span class="speaker ' + speaker + '">' +
17964
- (speaker === 'user' ? 'You' : 'Agent') + ':</span> ' + escapeHtml(text);
21659
+ (speaker === 'user' ? 'you' : 'agent') + ':</span> ' + escapeHtml(text);
17965
21660
  transcriptsEl.appendChild(div);
17966
21661
  transcriptsEl.scrollTop = transcriptsEl.scrollHeight;
17967
21662
  }
@@ -17971,7 +21666,7 @@ function escapeHtml(s) {
17971
21666
  }
17972
21667
 
17973
21668
  async function drainPlayback() {
17974
- if (!audioCtx) audioCtx = new AudioContext({ sampleRate: 22050 });
21669
+ if (!playbackCtx) playbackCtx = new AudioContext({ sampleRate: 22050 });
17975
21670
  isPlaying = true;
17976
21671
  while (playbackQueue.length > 0) {
17977
21672
  const int16 = playbackQueue.shift();
@@ -17979,20 +21674,16 @@ async function drainPlayback() {
17979
21674
  for (let i = 0; i < int16.length; i++) {
17980
21675
  float32[i] = int16[i] < 0 ? int16[i] / 0x8000 : int16[i] / 0x7FFF;
17981
21676
  }
17982
- const buf = audioCtx.createBuffer(1, float32.length, 22050);
21677
+ const buf = playbackCtx.createBuffer(1, float32.length, 22050);
17983
21678
  buf.getChannelData(0).set(float32);
17984
- const src = audioCtx.createBufferSource();
21679
+ const src = playbackCtx.createBufferSource();
17985
21680
  src.buffer = buf;
17986
- src.connect(audioCtx.destination);
21681
+ src.connect(playbackCtx.destination);
17987
21682
  src.start();
17988
- // Animate presence
17989
- const scale = 1 + Math.min(0.3, rms(float32) * 3);
17990
- presence.style.transform = 'scale(' + scale + ')';
17991
21683
  await new Promise(r => src.onended = r);
17992
- presence.style.transform = 'scale(1)';
17993
21684
  }
17994
21685
  isPlaying = false;
17995
- presence.classList.remove('speaking');
21686
+ if (!micActive) waveState = 'idle';
17996
21687
  }
17997
21688
 
17998
21689
  function rms(arr) {
@@ -18002,18 +21693,14 @@ function rms(arr) {
18002
21693
  }
18003
21694
 
18004
21695
  async function toggleMic() {
18005
- if (micActive) {
18006
- stopMic();
18007
- return;
18008
- }
21696
+ if (micActive) { stopMic(); return; }
18009
21697
  try {
18010
- if (!audioCtx) audioCtx = new AudioContext({ sampleRate: 16000 });
21698
+ if (!micCtx) micCtx = new AudioContext({ sampleRate: 16000 });
18011
21699
  micStream = await navigator.mediaDevices.getUserMedia({
18012
21700
  audio: { sampleRate: 16000, channelCount: 1, echoCancellation: true, noiseSuppression: true }
18013
21701
  });
18014
- const source = audioCtx.createMediaStreamSource(micStream);
18015
- // Downsample to 16kHz PCM16
18016
- scriptProcessor = audioCtx.createScriptProcessor(4096, 1, 1);
21702
+ const source = micCtx.createMediaStreamSource(micStream);
21703
+ scriptProcessor = micCtx.createScriptProcessor(4096, 1, 1);
18017
21704
  scriptProcessor.onaudioprocess = (e) => {
18018
21705
  if (!micActive || !ws || ws.readyState !== 1) return;
18019
21706
  const input = e.inputBuffer.getChannelData(0);
@@ -18023,33 +21710,28 @@ async function toggleMic() {
18023
21710
  int16[i] = s < 0 ? s * 0x8000 : s * 0x7FFF;
18024
21711
  }
18025
21712
  ws.send(int16.buffer);
18026
- // Animate presence while user speaks
18027
- const level = rms(input);
18028
- if (level > 0.01) {
18029
- presence.classList.add('listening');
18030
- presence.style.transform = 'scale(' + (1 + Math.min(0.3, level * 5)) + ')';
18031
- }
21713
+ micLevel = Math.min(1, rms(input) * 5);
18032
21714
  };
18033
21715
  source.connect(scriptProcessor);
18034
- scriptProcessor.connect(audioCtx.destination);
21716
+ scriptProcessor.connect(micCtx.destination);
18035
21717
  micActive = true;
18036
- micBtn.textContent = 'Stop Mic';
21718
+ waveState = 'listening';
21719
+ micBtn.textContent = 'stop mic';
18037
21720
  micBtn.classList.add('active');
18038
- // Notify server
18039
21721
  ws.send(JSON.stringify({ type: 'mic_start', username: 'web-user' }));
18040
21722
  } catch (err) {
18041
- statusEl.innerHTML = '<span class="disconnected">Mic error: ' + err.message + '</span>';
21723
+ statusEl.innerHTML = '<span class="disconnected">mic error: ' + err.message + '</span>';
18042
21724
  }
18043
21725
  }
18044
21726
 
18045
21727
  function stopMic() {
18046
21728
  micActive = false;
21729
+ micLevel = 0;
21730
+ waveState = 'idle';
18047
21731
  if (scriptProcessor) { scriptProcessor.disconnect(); scriptProcessor = null; }
18048
21732
  if (micStream) { micStream.getTracks().forEach(t => t.stop()); micStream = null; }
18049
- micBtn.textContent = 'Start Mic';
21733
+ micBtn.textContent = 'start mic';
18050
21734
  micBtn.classList.remove('active');
18051
- presence.classList.remove('listening');
18052
- presence.style.transform = 'scale(1)';
18053
21735
  if (ws && ws.readyState === 1) {
18054
21736
  ws.send(JSON.stringify({ type: 'mic_stop' }));
18055
21737
  }
@@ -18095,10 +21777,12 @@ var VoiceSession;
18095
21777
  var init_voice_session = __esm({
18096
21778
  "packages/cli/dist/tui/voice-session.js"() {
18097
21779
  "use strict";
21780
+ init_wrapper();
18098
21781
  init_render();
18099
21782
  VoiceSession = class extends EventEmitter2 {
18100
21783
  state;
18101
21784
  server = null;
21785
+ wss = null;
18102
21786
  cloudflaredProcess = null;
18103
21787
  wsClients = /* @__PURE__ */ new Map();
18104
21788
  runtimeTimer = null;
@@ -18141,13 +21825,8 @@ var init_voice_session = __esm({
18141
21825
  this.server = createServer((req, res) => this.handleHTTP(req, res));
18142
21826
  this.server.timeout = 0;
18143
21827
  this.server.keepAliveTimeout = 0;
18144
- this.server.on("upgrade", (req, socket, head) => {
18145
- if (req.url === "/ws") {
18146
- this.handleWebSocketUpgrade(req, socket, head);
18147
- } else {
18148
- socket.destroy();
18149
- }
18150
- });
21828
+ this.wss = new import_websocket_server.default({ server: this.server, path: "/ws" });
21829
+ this.wss.on("connection", (ws, req) => this.handleWSConnection(ws, req));
18151
21830
  await new Promise((resolve28, reject) => {
18152
21831
  this.server.listen(port, "127.0.0.1", () => resolve28());
18153
21832
  this.server.on("error", reject);
@@ -18184,16 +21863,18 @@ var init_voice_session = __esm({
18184
21863
  clearTimeout(this.idleTimer);
18185
21864
  this.idleTimer = null;
18186
21865
  }
18187
- for (const [id, socket] of this.wsClients) {
21866
+ for (const [id, ws] of this.wsClients) {
18188
21867
  try {
18189
- const closeFrame = createWebSocketFrame(8, Buffer.alloc(0));
18190
- socket.write(closeFrame);
18191
- socket.end();
21868
+ ws.close(1e3, "session ended");
18192
21869
  } catch {
18193
21870
  }
18194
21871
  }
18195
21872
  this.wsClients.clear();
18196
21873
  this.state.connectedUsers.clear();
21874
+ if (this.wss) {
21875
+ this.wss.close();
21876
+ this.wss = null;
21877
+ }
18197
21878
  if (this.cloudflaredProcess) {
18198
21879
  try {
18199
21880
  this.cloudflaredProcess.kill("SIGTERM");
@@ -18214,10 +21895,10 @@ var init_voice_session = __esm({
18214
21895
  */
18215
21896
  sendAudioToClients(pcmInt16) {
18216
21897
  this.ttsSpeaking = true;
18217
- const frame = createWebSocketFrame(2, pcmInt16);
18218
- for (const socket of this.wsClients.values()) {
21898
+ for (const ws of this.wsClients.values()) {
18219
21899
  try {
18220
- socket.write(frame);
21900
+ if (ws.readyState === import_websocket.default.OPEN)
21901
+ ws.send(pcmInt16);
18221
21902
  } catch {
18222
21903
  }
18223
21904
  }
@@ -18228,10 +21909,10 @@ var init_voice_session = __esm({
18228
21909
  sendSpeakingState(speaking) {
18229
21910
  this.ttsSpeaking = speaking;
18230
21911
  const msg = JSON.stringify({ type: speaking ? "speaking_start" : "speaking_end" });
18231
- const frame = createWebSocketFrame(1, Buffer.from(msg));
18232
- for (const socket of this.wsClients.values()) {
21912
+ for (const ws of this.wsClients.values()) {
18233
21913
  try {
18234
- socket.write(frame);
21914
+ if (ws.readyState === import_websocket.default.OPEN)
21915
+ ws.send(msg);
18235
21916
  } catch {
18236
21917
  }
18237
21918
  }
@@ -18242,10 +21923,10 @@ var init_voice_session = __esm({
18242
21923
  sendTranscript(speaker, text) {
18243
21924
  this.state.transcripts.push({ speaker, text, ts: Date.now() });
18244
21925
  const msg = JSON.stringify({ type: "transcript", speaker, text });
18245
- const frame = createWebSocketFrame(1, Buffer.from(msg));
18246
- for (const socket of this.wsClients.values()) {
21926
+ for (const ws of this.wsClients.values()) {
18247
21927
  try {
18248
- socket.write(frame);
21928
+ if (ws.readyState === import_websocket.default.OPEN)
21929
+ ws.send(msg);
18249
21930
  } catch {
18250
21931
  }
18251
21932
  }
@@ -18267,108 +21948,58 @@ var init_voice_session = __esm({
18267
21948
  res.end("Not found");
18268
21949
  }
18269
21950
  }
18270
- // ── WebSocket upgrade ─────────────────────────────────────────────────
18271
- handleWebSocketUpgrade(req, socket, head) {
18272
- const key = req.headers["sec-websocket-key"];
18273
- if (!key) {
18274
- socket.destroy();
18275
- return;
18276
- }
18277
- const magic = "258EAFA5-E914-47DA-95CA-5AB9DC085B62";
18278
- const accept = createHash("sha1").update(key + magic).digest("base64");
18279
- socket.setNoDelay(true);
18280
- socket.setKeepAlive(true, 1e4);
18281
- socket.setTimeout(0);
18282
- socket.write(`HTTP/1.1 101 Switching Protocols\r
18283
- Upgrade: websocket\r
18284
- Connection: Upgrade\r
18285
- Sec-WebSocket-Accept: ${accept}\r
18286
- \r
18287
- `);
21951
+ // ── WebSocket connection handler (using ws package) ──────────────────
21952
+ handleWSConnection(ws, req) {
18288
21953
  const clientId = `ws-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
18289
- this.wsClients.set(clientId, socket);
21954
+ this.wsClients.set(clientId, ws);
18290
21955
  this.state.connectedUsers.set(clientId, { username: "web-user", connectedAt: Date.now() });
18291
21956
  this.emit("userConnected", clientId, "web-user");
18292
21957
  this.resetIdleTimer();
18293
- try {
18294
- socket.write(createWebSocketFrame(9, Buffer.from("keepalive")));
18295
- } catch {
18296
- }
18297
- const pingInterval = setInterval(() => {
18298
- if (socket.destroyed) {
18299
- clearInterval(pingInterval);
21958
+ const keepaliveInterval = setInterval(() => {
21959
+ if (ws.readyState !== import_websocket.default.OPEN) {
21960
+ clearInterval(keepaliveInterval);
18300
21961
  return;
18301
21962
  }
18302
21963
  try {
18303
- socket.write(createWebSocketFrame(9, Buffer.from("keepalive")));
18304
- socket.write(createWebSocketFrame(1, Buffer.from(JSON.stringify({ type: "keepalive" }))));
21964
+ ws.send(JSON.stringify({ type: "keepalive", ts: Date.now() }));
18305
21965
  } catch {
18306
- clearInterval(pingInterval);
18307
- }
18308
- }, 5e3);
18309
- let frameBuffer = Buffer.alloc(0);
18310
- socket.on("data", (data) => {
18311
- frameBuffer = Buffer.concat([frameBuffer, data]);
18312
- while (frameBuffer.length >= 2) {
18313
- const frame = parseWebSocketFrame(frameBuffer);
18314
- if (!frame)
18315
- break;
18316
- const secondByte = frameBuffer[1];
18317
- const masked = (secondByte & 128) !== 0;
18318
- let payloadLen = secondByte & 127;
18319
- let headerLen = 2;
18320
- if (payloadLen === 126) {
18321
- headerLen = 4;
18322
- payloadLen = frameBuffer.readUInt16BE(2);
18323
- } else if (payloadLen === 127) {
18324
- headerLen = 10;
18325
- payloadLen = Number(frameBuffer.readBigUInt64BE(2));
21966
+ clearInterval(keepaliveInterval);
21967
+ }
21968
+ }, 1e4);
21969
+ ws.on("message", (data, isBinary) => {
21970
+ if (isBinary) {
21971
+ if (!this.ttsSpeaking) {
21972
+ this.onUserAudio?.(Buffer.isBuffer(data) ? data : Buffer.from(data), clientId);
18326
21973
  }
18327
- const consumed = headerLen + (masked ? 4 : 0) + payloadLen;
18328
- frameBuffer = frameBuffer.subarray(consumed);
18329
- if (frame.opcode === 8) {
18330
- try {
18331
- socket.write(createWebSocketFrame(8, Buffer.alloc(0)));
18332
- } catch {
18333
- }
18334
- socket.end();
18335
- return;
18336
- } else if (frame.opcode === 9) {
18337
- socket.write(createWebSocketFrame(10, frame.payload));
18338
- } else if (frame.opcode === 10) {
18339
- } else if (frame.opcode === 1) {
18340
- try {
18341
- const msg = JSON.parse(frame.payload.toString());
18342
- if (msg.type === "mic_start" && msg.username) {
18343
- const entry = this.state.connectedUsers.get(clientId);
18344
- if (entry)
18345
- entry.username = msg.username;
18346
- }
18347
- } catch {
18348
- }
18349
- } else if (frame.opcode === 2) {
18350
- if (!this.ttsSpeaking) {
18351
- this.onUserAudio?.(frame.payload, clientId);
21974
+ } else {
21975
+ try {
21976
+ const msg = JSON.parse(data.toString());
21977
+ if (msg.type === "mic_start" && msg.username) {
21978
+ const entry = this.state.connectedUsers.get(clientId);
21979
+ if (entry)
21980
+ entry.username = msg.username;
18352
21981
  }
21982
+ } catch {
18353
21983
  }
18354
21984
  }
18355
21985
  });
18356
- socket.on("close", () => {
18357
- clearInterval(pingInterval);
21986
+ ws.on("close", (code, reason) => {
21987
+ clearInterval(keepaliveInterval);
18358
21988
  this.wsClients.delete(clientId);
18359
21989
  this.state.connectedUsers.delete(clientId);
21990
+ if (code > 0 && code !== 1e3 && code !== 1001) {
21991
+ this.emit("wsClose", clientId, code, reason.toString());
21992
+ }
18360
21993
  this.emit("userDisconnected", clientId);
18361
21994
  this.resetIdleTimer();
18362
21995
  });
18363
- socket.on("error", () => {
18364
- clearInterval(pingInterval);
21996
+ ws.on("error", (err) => {
21997
+ clearInterval(keepaliveInterval);
18365
21998
  this.wsClients.delete(clientId);
18366
21999
  this.state.connectedUsers.delete(clientId);
22000
+ this.emit("wsError", clientId, err);
18367
22001
  this.resetIdleTimer();
18368
22002
  });
18369
- if (head.length > 0) {
18370
- socket.emit("data", head);
18371
- }
18372
22003
  }
18373
22004
  // ── Cloudflared tunnel ────────────────────────────────────────────────
18374
22005
  startCloudflared(port) {
@@ -27628,6 +31259,8 @@ with summary "no_reply" to silently skip without responding.
27628
31259
  callStarter = null;
27629
31260
  /** Callback to stop a call session (wired from interactive.ts) */
27630
31261
  callStopper = null;
31262
+ /** Guard against concurrent call starts (cloudflared tunnel takes seconds) */
31263
+ callStartInProgress = false;
27631
31264
  /** Callback to write content into the scrollable TUI waterfall area (wired from interactive.ts) */
27632
31265
  writeContent = null;
27633
31266
  /** Media cache — fileUniqueId → cache entry */
@@ -27856,6 +31489,11 @@ with summary "no_reply" to silently skip without responding.
27856
31489
  return;
27857
31490
  }
27858
31491
  if (this.callStarter) {
31492
+ if (this.callStartInProgress) {
31493
+ await this.sendMessage(msg.chatId, "Call session is starting, please wait...");
31494
+ return;
31495
+ }
31496
+ this.callStartInProgress = true;
27859
31497
  try {
27860
31498
  const newUrl = await this.callStarter();
27861
31499
  if (newUrl) {
@@ -27866,6 +31504,8 @@ with summary "no_reply" to silently skip without responding.
27866
31504
  } catch (err) {
27867
31505
  await this.sendMessage(msg.chatId, `Call error: ${err instanceof Error ? err.message : String(err)}`).catch(() => {
27868
31506
  });
31507
+ } finally {
31508
+ this.callStartInProgress = false;
27869
31509
  }
27870
31510
  return;
27871
31511
  }
@@ -31175,7 +34815,7 @@ Respond concisely and safely. Remember: you are talking to the general public.`;
31175
34815
  return voiceSession.tunnelUrl;
31176
34816
  }
31177
34817
  voiceSession = new VoiceSession();
31178
- const callState = { transcriber: null };
34818
+ const callState = { transcriber: null, loading: false };
31179
34819
  const engine = getListenEngine();
31180
34820
  voiceSession.onUserAudio = (pcmChunk, userId) => {
31181
34821
  if (callState.transcriber)
@@ -31183,7 +34823,8 @@ Respond concisely and safely. Remember: you are talking to the general public.`;
31183
34823
  };
31184
34824
  voiceSession.on("userConnected", (id, username) => {
31185
34825
  writeContent(() => renderVoiceSessionUser("connected", username));
31186
- if (!callState.transcriber) {
34826
+ if (!callState.transcriber && !callState.loading) {
34827
+ callState.loading = true;
31187
34828
  engine.createCallTranscriber().then((t) => {
31188
34829
  if (!t || !voiceSession?.isActive)
31189
34830
  return;
@@ -31207,6 +34848,13 @@ Respond concisely and safely. Remember: you are talking to the general public.`;
31207
34848
  voiceSession.on("userDisconnected", (id) => {
31208
34849
  writeContent(() => renderVoiceSessionUser("disconnected", id));
31209
34850
  });
34851
+ voiceSession.on("wsClose", (id, code, reason) => {
34852
+ if (code > 0)
34853
+ writeContent(() => renderInfo(`WS close: ${id} code=${code} ${reason}`));
34854
+ });
34855
+ voiceSession.on("wsError", (id, err) => {
34856
+ writeContent(() => renderWarning(`WS error: ${id} ${err.message}`));
34857
+ });
31210
34858
  voiceSession.on("idle_timeout", () => {
31211
34859
  writeContent(() => renderWarning("Call session auto-closed (1 min idle \u2014 no users connected)"));
31212
34860
  if (callState.transcriber) {
@@ -31229,13 +34877,6 @@ Respond concisely and safely. Remember: you are talking to the general public.`;
31229
34877
  }
31230
34878
  };
31231
34879
  }
31232
- if (telegramBridge?.isActive && savedSettings.telegramAdmin) {
31233
- const adminChatId = parseInt(savedSettings.telegramAdmin, 10);
31234
- if (!isNaN(adminChatId)) {
31235
- telegramBridge.sendCallButton(adminChatId, tunnelUrl).catch(() => {
31236
- });
31237
- }
31238
- }
31239
34880
  return tunnelUrl;
31240
34881
  } catch (err) {
31241
34882
  writeContent(() => renderWarning(`Voice session failed: ${err instanceof Error ? err.message : String(err)}`));
@@ -31727,13 +35368,13 @@ NEW TASK: ${fullInput}`;
31727
35368
  writeContent(() => renderError(errMsg));
31728
35369
  if (failureStore) {
31729
35370
  try {
31730
- const { createHash: createHash3 } = await import("node:crypto");
35371
+ const { createHash: createHash2 } = await import("node:crypto");
31731
35372
  failureStore.insert({
31732
35373
  taskId: "",
31733
35374
  sessionId: `${Date.now()}`,
31734
35375
  repoRoot,
31735
35376
  failureType: "runtime-error",
31736
- fingerprint: createHash3("sha256").update(errMsg.slice(0, 200)).digest("hex").slice(0, 16),
35377
+ fingerprint: createHash2("sha256").update(errMsg.slice(0, 200)).digest("hex").slice(0, 16),
31737
35378
  filePath: null,
31738
35379
  errorMessage: errMsg.slice(0, 500),
31739
35380
  context: null,
@@ -31994,7 +35635,7 @@ var init_run = __esm({
31994
35635
  import { glob } from "glob";
31995
35636
  import ignore from "ignore";
31996
35637
  import { readFile as readFile14, stat as stat4 } from "node:fs/promises";
31997
- import { createHash as createHash2 } from "node:crypto";
35638
+ import { createHash } from "node:crypto";
31998
35639
  import { join as join41, relative as relative3, extname as extname10, basename as basename15 } from "node:path";
31999
35640
  var DEFAULT_EXCLUDE, LANGUAGE_MAP, CodebaseIndexer;
32000
35641
  var init_codebase_indexer = __esm({
@@ -32060,7 +35701,7 @@ var init_codebase_indexer = __esm({
32060
35701
  if (fileStat.size > this.config.maxFileSize)
32061
35702
  continue;
32062
35703
  const content = await readFile14(fullPath);
32063
- const hash = createHash2("sha256").update(content).digest("hex");
35704
+ const hash = createHash("sha256").update(content).digest("hex");
32064
35705
  const ext = extname10(relativePath);
32065
35706
  indexed.push({
32066
35707
  path: fullPath,