@wlfi-agent/cli 1.4.13 → 1.4.14

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