privateer-agent 0.15.4 → 0.15.6

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