@honeybbq/teamspeak 0.0.1 → 1.0.0-beta.8

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 (393) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +726 -2
  3. package/dist/client/abort.d.ts +5 -0
  4. package/dist/client/abort.d.ts.map +1 -0
  5. package/dist/client/abort.js +23 -0
  6. package/dist/client/abort.js.map +1 -0
  7. package/dist/client/address.d.ts +17 -0
  8. package/dist/client/address.d.ts.map +1 -0
  9. package/dist/client/address.js +66 -0
  10. package/dist/client/address.js.map +1 -0
  11. package/dist/client/api/voice.d.ts +24 -0
  12. package/dist/client/api/voice.d.ts.map +1 -0
  13. package/dist/client/api/voice.js +33 -0
  14. package/dist/client/api/voice.js.map +1 -0
  15. package/dist/client/capabilities.d.ts +68 -0
  16. package/dist/client/capabilities.d.ts.map +1 -0
  17. package/dist/client/capabilities.js +59 -0
  18. package/dist/client/capabilities.js.map +1 -0
  19. package/dist/client/client.d.ts +196 -0
  20. package/dist/client/client.d.ts.map +1 -0
  21. package/dist/client/client.js +1523 -0
  22. package/dist/client/client.js.map +1 -0
  23. package/dist/client/commands.d.ts +66 -0
  24. package/dist/client/commands.d.ts.map +1 -0
  25. package/dist/client/commands.js +162 -0
  26. package/dist/client/commands.js.map +1 -0
  27. package/dist/client/crypto/crypt-ops.d.ts +7 -0
  28. package/dist/client/crypto/crypt-ops.d.ts.map +1 -0
  29. package/dist/client/crypto/crypt-ops.js +2 -0
  30. package/dist/client/crypto/crypt-ops.js.map +1 -0
  31. package/dist/client/crypto/crypt.d.ts +37 -0
  32. package/dist/client/crypto/crypt.d.ts.map +1 -0
  33. package/dist/client/crypto/crypt.js +203 -0
  34. package/dist/client/crypto/crypt.js.map +1 -0
  35. package/dist/client/crypto/eax.d.ts +12 -0
  36. package/dist/client/crypto/eax.d.ts.map +1 -0
  37. package/dist/client/crypto/eax.js +118 -0
  38. package/dist/client/crypto/eax.js.map +1 -0
  39. package/dist/client/crypto/identity.d.ts +97 -0
  40. package/dist/client/crypto/identity.d.ts.map +1 -0
  41. package/dist/client/crypto/identity.js +412 -0
  42. package/dist/client/crypto/identity.js.map +1 -0
  43. package/dist/client/crypto/index.d.ts +7 -0
  44. package/dist/client/crypto/index.d.ts.map +1 -0
  45. package/dist/client/crypto/index.js +5 -0
  46. package/dist/client/crypto/index.js.map +1 -0
  47. package/dist/client/crypto/primitives.d.ts +43 -0
  48. package/dist/client/crypto/primitives.d.ts.map +1 -0
  49. package/dist/client/crypto/primitives.js +116 -0
  50. package/dist/client/crypto/primitives.js.map +1 -0
  51. package/dist/client/diagnostics.d.ts +45 -0
  52. package/dist/client/diagnostics.d.ts.map +1 -0
  53. package/dist/client/diagnostics.js +30 -0
  54. package/dist/client/diagnostics.js.map +1 -0
  55. package/dist/client/discovery/index.d.ts +2 -0
  56. package/dist/client/discovery/index.d.ts.map +1 -0
  57. package/dist/client/discovery/index.js +2 -0
  58. package/dist/client/discovery/index.js.map +1 -0
  59. package/dist/client/discovery/resolver.d.ts +26 -0
  60. package/dist/client/discovery/resolver.d.ts.map +1 -0
  61. package/dist/client/discovery/resolver.js +275 -0
  62. package/dist/client/discovery/resolver.js.map +1 -0
  63. package/dist/client/errors.d.ts +82 -0
  64. package/dist/client/errors.d.ts.map +1 -0
  65. package/dist/client/errors.js +201 -0
  66. package/dist/client/errors.js.map +1 -0
  67. package/dist/client/events.d.ts +3 -0
  68. package/dist/client/events.d.ts.map +1 -0
  69. package/dist/client/events.js +8 -0
  70. package/dist/client/events.js.map +1 -0
  71. package/dist/client/handshake/crypt-handshake.d.ts +17 -0
  72. package/dist/client/handshake/crypt-handshake.d.ts.map +1 -0
  73. package/dist/client/handshake/crypt-handshake.js +128 -0
  74. package/dist/client/handshake/crypt-handshake.js.map +1 -0
  75. package/dist/client/handshake/crypt-init2.d.ts +7 -0
  76. package/dist/client/handshake/crypt-init2.d.ts.map +1 -0
  77. package/dist/client/handshake/crypt-init2.js +37 -0
  78. package/dist/client/handshake/crypt-init2.js.map +1 -0
  79. package/dist/client/handshake/index.d.ts +4 -0
  80. package/dist/client/handshake/index.d.ts.map +1 -0
  81. package/dist/client/handshake/index.js +4 -0
  82. package/dist/client/handshake/index.js.map +1 -0
  83. package/dist/client/handshake/license.d.ts +35 -0
  84. package/dist/client/handshake/license.d.ts.map +1 -0
  85. package/dist/client/handshake/license.js +169 -0
  86. package/dist/client/handshake/license.js.map +1 -0
  87. package/dist/client/handshake.d.ts +27 -0
  88. package/dist/client/handshake.d.ts.map +1 -0
  89. package/dist/client/handshake.js +126 -0
  90. package/dist/client/handshake.js.map +1 -0
  91. package/dist/client/helpers.d.ts +6 -0
  92. package/dist/client/helpers.d.ts.map +1 -0
  93. package/dist/client/helpers.js +13 -0
  94. package/dist/client/helpers.js.map +1 -0
  95. package/dist/client/hooks.d.ts +7 -0
  96. package/dist/client/hooks.d.ts.map +1 -0
  97. package/dist/client/hooks.js +28 -0
  98. package/dist/client/hooks.js.map +1 -0
  99. package/dist/client/index.d.ts +26 -0
  100. package/dist/client/index.d.ts.map +1 -0
  101. package/dist/client/index.js +28 -0
  102. package/dist/client/index.js.map +1 -0
  103. package/dist/client/reconnect.d.ts +12 -0
  104. package/dist/client/reconnect.d.ts.map +1 -0
  105. package/dist/client/reconnect.js +44 -0
  106. package/dist/client/reconnect.js.map +1 -0
  107. package/dist/client/throttle.d.ts +20 -0
  108. package/dist/client/throttle.d.ts.map +1 -0
  109. package/dist/client/throttle.js +83 -0
  110. package/dist/client/throttle.js.map +1 -0
  111. package/dist/client/trace.d.ts +223 -0
  112. package/dist/client/trace.d.ts.map +1 -0
  113. package/dist/client/trace.js +13 -0
  114. package/dist/client/trace.js.map +1 -0
  115. package/dist/client/transfer.d.ts +111 -0
  116. package/dist/client/transfer.d.ts.map +1 -0
  117. package/dist/client/transfer.js +243 -0
  118. package/dist/client/transfer.js.map +1 -0
  119. package/dist/client/transport/generation-window.d.ts +30 -0
  120. package/dist/client/transport/generation-window.d.ts.map +1 -0
  121. package/dist/client/transport/generation-window.js +97 -0
  122. package/dist/client/transport/generation-window.js.map +1 -0
  123. package/dist/client/transport/handler.d.ts +61 -0
  124. package/dist/client/transport/handler.d.ts.map +1 -0
  125. package/dist/client/transport/handler.js +793 -0
  126. package/dist/client/transport/handler.js.map +1 -0
  127. package/dist/client/transport/index.d.ts +6 -0
  128. package/dist/client/transport/index.d.ts.map +1 -0
  129. package/dist/client/transport/index.js +5 -0
  130. package/dist/client/transport/index.js.map +1 -0
  131. package/dist/client/transport/packet.d.ts +36 -0
  132. package/dist/client/transport/packet.d.ts.map +1 -0
  133. package/dist/client/transport/packet.js +55 -0
  134. package/dist/client/transport/packet.js.map +1 -0
  135. package/dist/client/transport/quicklz.d.ts +24 -0
  136. package/dist/client/transport/quicklz.d.ts.map +1 -0
  137. package/dist/client/transport/quicklz.js +179 -0
  138. package/dist/client/transport/quicklz.js.map +1 -0
  139. package/dist/client/types.d.ts +226 -0
  140. package/dist/client/types.d.ts.map +1 -0
  141. package/dist/client/types.js +39 -0
  142. package/dist/client/types.js.map +1 -0
  143. package/dist/core/api/channels.d.ts +182 -0
  144. package/dist/core/api/channels.d.ts.map +1 -0
  145. package/dist/core/api/channels.js +155 -0
  146. package/dist/core/api/channels.js.map +1 -0
  147. package/dist/core/api/clients.d.ts +304 -0
  148. package/dist/core/api/clients.d.ts.map +1 -0
  149. package/dist/core/api/clients.js +260 -0
  150. package/dist/core/api/clients.js.map +1 -0
  151. package/dist/core/api/command.d.ts +305 -0
  152. package/dist/core/api/command.d.ts.map +1 -0
  153. package/dist/core/api/command.js +363 -0
  154. package/dist/core/api/command.js.map +1 -0
  155. package/dist/core/api/files.d.ts +153 -0
  156. package/dist/core/api/files.d.ts.map +1 -0
  157. package/dist/core/api/files.js +181 -0
  158. package/dist/core/api/files.js.map +1 -0
  159. package/dist/core/api/groups.d.ts +248 -0
  160. package/dist/core/api/groups.d.ts.map +1 -0
  161. package/dist/core/api/groups.js +271 -0
  162. package/dist/core/api/groups.js.map +1 -0
  163. package/dist/core/api/moderation.d.ts +205 -0
  164. package/dist/core/api/moderation.d.ts.map +1 -0
  165. package/dist/core/api/moderation.js +209 -0
  166. package/dist/core/api/moderation.js.map +1 -0
  167. package/dist/core/api/parse.d.ts +16 -0
  168. package/dist/core/api/parse.d.ts.map +1 -0
  169. package/dist/core/api/parse.js +40 -0
  170. package/dist/core/api/parse.js.map +1 -0
  171. package/dist/core/api/server.d.ts +310 -0
  172. package/dist/core/api/server.d.ts.map +1 -0
  173. package/dist/core/api/server.js +290 -0
  174. package/dist/core/api/server.js.map +1 -0
  175. package/dist/core/command/command.d.ts +20 -0
  176. package/dist/core/command/command.d.ts.map +1 -0
  177. package/dist/core/command/command.js +112 -0
  178. package/dist/core/command/command.js.map +1 -0
  179. package/dist/core/command/ids.d.ts +125 -0
  180. package/dist/core/command/ids.d.ts.map +1 -0
  181. package/dist/core/command/ids.js +85 -0
  182. package/dist/core/command/ids.js.map +1 -0
  183. package/dist/core/command/parser.d.ts +17 -0
  184. package/dist/core/command/parser.d.ts.map +1 -0
  185. package/dist/core/command/parser.js +65 -0
  186. package/dist/core/command/parser.js.map +1 -0
  187. package/dist/core/command/request.d.ts +61 -0
  188. package/dist/core/command/request.d.ts.map +1 -0
  189. package/dist/core/command/request.js +64 -0
  190. package/dist/core/command/request.js.map +1 -0
  191. package/dist/core/command/responses.d.ts +59 -0
  192. package/dist/core/command/responses.d.ts.map +1 -0
  193. package/dist/core/command/responses.js +74 -0
  194. package/dist/core/command/responses.js.map +1 -0
  195. package/dist/core/command-name.d.ts +333 -0
  196. package/dist/core/command-name.d.ts.map +1 -0
  197. package/dist/core/command-name.js +331 -0
  198. package/dist/core/command-name.js.map +1 -0
  199. package/dist/core/enums.d.ts +146 -0
  200. package/dist/core/enums.d.ts.map +1 -0
  201. package/dist/core/enums.js +132 -0
  202. package/dist/core/enums.js.map +1 -0
  203. package/dist/core/errorcode.d.ts +413 -0
  204. package/dist/core/errorcode.d.ts.map +1 -0
  205. package/dist/core/errorcode.js +410 -0
  206. package/dist/core/errorcode.js.map +1 -0
  207. package/dist/core/errors.d.ts +111 -0
  208. package/dist/core/errors.d.ts.map +1 -0
  209. package/dist/core/errors.js +233 -0
  210. package/dist/core/errors.js.map +1 -0
  211. package/dist/core/events.d.ts +207 -0
  212. package/dist/core/events.d.ts.map +1 -0
  213. package/dist/core/events.js +6 -0
  214. package/dist/core/events.js.map +1 -0
  215. package/dist/core/helpers.d.ts +42 -0
  216. package/dist/core/helpers.d.ts.map +1 -0
  217. package/dist/core/helpers.js +156 -0
  218. package/dist/core/helpers.js.map +1 -0
  219. package/dist/core/index.d.ts +35 -0
  220. package/dist/core/index.d.ts.map +1 -0
  221. package/dist/core/index.js +34 -0
  222. package/dist/core/index.js.map +1 -0
  223. package/dist/core/internal.d.ts +23 -0
  224. package/dist/core/internal.d.ts.map +1 -0
  225. package/dist/core/internal.js +20 -0
  226. package/dist/core/internal.js.map +1 -0
  227. package/dist/core/middleware.d.ts +14 -0
  228. package/dist/core/middleware.d.ts.map +1 -0
  229. package/dist/core/middleware.js +18 -0
  230. package/dist/core/middleware.js.map +1 -0
  231. package/dist/core/notification-name.d.ts +154 -0
  232. package/dist/core/notification-name.d.ts.map +1 -0
  233. package/dist/core/notification-name.js +152 -0
  234. package/dist/core/notification-name.js.map +1 -0
  235. package/dist/core/notifications.d.ts +43 -0
  236. package/dist/core/notifications.d.ts.map +1 -0
  237. package/dist/core/notifications.js +116 -0
  238. package/dist/core/notifications.js.map +1 -0
  239. package/dist/core/permission-name.d.ts +533 -0
  240. package/dist/core/permission-name.d.ts.map +1 -0
  241. package/dist/core/permission-name.js +531 -0
  242. package/dist/core/permission-name.js.map +1 -0
  243. package/dist/core/permission.d.ts +31 -0
  244. package/dist/core/permission.d.ts.map +1 -0
  245. package/dist/core/permission.js +20 -0
  246. package/dist/core/permission.js.map +1 -0
  247. package/dist/core/property-name.d.ts +403 -0
  248. package/dist/core/property-name.d.ts.map +1 -0
  249. package/dist/core/property-name.js +405 -0
  250. package/dist/core/property-name.js.map +1 -0
  251. package/dist/core/reason.d.ts +39 -0
  252. package/dist/core/reason.d.ts.map +1 -0
  253. package/dist/core/reason.js +36 -0
  254. package/dist/core/reason.js.map +1 -0
  255. package/dist/core/reconnect.d.ts +59 -0
  256. package/dist/core/reconnect.d.ts.map +1 -0
  257. package/dist/core/reconnect.js +55 -0
  258. package/dist/core/reconnect.js.map +1 -0
  259. package/dist/core/types.d.ts +110 -0
  260. package/dist/core/types.d.ts.map +1 -0
  261. package/dist/core/types.js +27 -0
  262. package/dist/core/types.js.map +1 -0
  263. package/dist/query/client.d.ts +194 -0
  264. package/dist/query/client.d.ts.map +1 -0
  265. package/dist/query/client.js +969 -0
  266. package/dist/query/client.js.map +1 -0
  267. package/dist/query/errors.d.ts +61 -0
  268. package/dist/query/errors.d.ts.map +1 -0
  269. package/dist/query/errors.js +100 -0
  270. package/dist/query/errors.js.map +1 -0
  271. package/dist/query/index.d.ts +36 -0
  272. package/dist/query/index.d.ts.map +1 -0
  273. package/dist/query/index.js +34 -0
  274. package/dist/query/index.js.map +1 -0
  275. package/dist/query/knownhosts.d.ts +61 -0
  276. package/dist/query/knownhosts.d.ts.map +1 -0
  277. package/dist/query/knownhosts.js +223 -0
  278. package/dist/query/knownhosts.js.map +1 -0
  279. package/dist/query/lines.d.ts +14 -0
  280. package/dist/query/lines.d.ts.map +1 -0
  281. package/dist/query/lines.js +29 -0
  282. package/dist/query/lines.js.map +1 -0
  283. package/dist/query/options.d.ts +187 -0
  284. package/dist/query/options.d.ts.map +1 -0
  285. package/dist/query/options.js +213 -0
  286. package/dist/query/options.js.map +1 -0
  287. package/dist/query/reconnect.d.ts +29 -0
  288. package/dist/query/reconnect.d.ts.map +1 -0
  289. package/dist/query/reconnect.js +87 -0
  290. package/dist/query/reconnect.js.map +1 -0
  291. package/dist/query/ssh.d.ts +345 -0
  292. package/dist/query/ssh.d.ts.map +1 -0
  293. package/dist/query/ssh.js +241 -0
  294. package/dist/query/ssh.js.map +1 -0
  295. package/dist/query/stream.d.ts +38 -0
  296. package/dist/query/stream.d.ts.map +1 -0
  297. package/dist/query/stream.js +70 -0
  298. package/dist/query/stream.js.map +1 -0
  299. package/dist/query/tcp.d.ts +38 -0
  300. package/dist/query/tcp.d.ts.map +1 -0
  301. package/dist/query/tcp.js +53 -0
  302. package/dist/query/tcp.js.map +1 -0
  303. package/dist/query/transport.d.ts +36 -0
  304. package/dist/query/transport.d.ts.map +1 -0
  305. package/dist/query/transport.js +2 -0
  306. package/dist/query/transport.js.map +1 -0
  307. package/dist/query/web.d.ts +54 -0
  308. package/dist/query/web.d.ts.map +1 -0
  309. package/dist/query/web.js +146 -0
  310. package/dist/query/web.js.map +1 -0
  311. package/dist/versions/index.d.ts +3094 -0
  312. package/dist/versions/index.d.ts.map +1 -0
  313. package/dist/versions/index.js +9237 -0
  314. package/dist/versions/index.js.map +1 -0
  315. package/package.json +118 -4
  316. package/src/client/abort.ts +24 -0
  317. package/src/client/address.ts +74 -0
  318. package/src/client/api/voice.ts +61 -0
  319. package/src/client/capabilities.ts +106 -0
  320. package/src/client/client.ts +1809 -0
  321. package/src/client/commands.ts +193 -0
  322. package/src/client/crypto/crypt-ops.ts +6 -0
  323. package/src/client/crypto/crypt.ts +275 -0
  324. package/src/client/crypto/eax.ts +152 -0
  325. package/src/client/crypto/identity.ts +484 -0
  326. package/src/client/crypto/index.ts +21 -0
  327. package/src/client/crypto/primitives.ts +141 -0
  328. package/src/client/diagnostics.ts +58 -0
  329. package/src/client/discovery/index.ts +1 -0
  330. package/src/client/discovery/resolver.ts +325 -0
  331. package/src/client/errors.ts +217 -0
  332. package/src/client/events.ts +12 -0
  333. package/src/client/handshake/crypt-handshake.ts +157 -0
  334. package/src/client/handshake/crypt-init2.ts +48 -0
  335. package/src/client/handshake/index.ts +3 -0
  336. package/src/client/handshake/license.ts +208 -0
  337. package/src/client/handshake.ts +150 -0
  338. package/src/client/helpers.ts +10 -0
  339. package/src/client/hooks.ts +30 -0
  340. package/src/client/index.ts +93 -0
  341. package/src/client/reconnect.ts +43 -0
  342. package/src/client/throttle.ts +92 -0
  343. package/src/client/trace.ts +237 -0
  344. package/src/client/transfer.ts +436 -0
  345. package/src/client/transport/generation-window.ts +108 -0
  346. package/src/client/transport/handler.ts +926 -0
  347. package/src/client/transport/index.ts +14 -0
  348. package/src/client/transport/packet.ts +69 -0
  349. package/src/client/transport/quicklz.ts +209 -0
  350. package/src/client/types.ts +268 -0
  351. package/src/core/api/channels.ts +396 -0
  352. package/src/core/api/clients.ts +654 -0
  353. package/src/core/api/command.ts +563 -0
  354. package/src/core/api/files.ts +405 -0
  355. package/src/core/api/groups.ts +622 -0
  356. package/src/core/api/moderation.ts +525 -0
  357. package/src/core/api/parse.ts +52 -0
  358. package/src/core/api/server.ts +709 -0
  359. package/src/core/command/command.ts +125 -0
  360. package/src/core/command/ids.ts +149 -0
  361. package/src/core/command/parser.ts +68 -0
  362. package/src/core/command/request.ts +119 -0
  363. package/src/core/command/responses.ts +114 -0
  364. package/src/core/command-name.ts +334 -0
  365. package/src/core/enums.ts +167 -0
  366. package/src/core/errorcode.ts +412 -0
  367. package/src/core/errors.ts +258 -0
  368. package/src/core/events.ts +219 -0
  369. package/src/core/helpers.ts +161 -0
  370. package/src/core/index.ts +126 -0
  371. package/src/core/internal.ts +23 -0
  372. package/src/core/middleware.ts +24 -0
  373. package/src/core/notification-name.ts +155 -0
  374. package/src/core/notifications.ts +157 -0
  375. package/src/core/permission-name.ts +538 -0
  376. package/src/core/permission.ts +34 -0
  377. package/src/core/property-name.ts +411 -0
  378. package/src/core/reason.ts +38 -0
  379. package/src/core/reconnect.ts +98 -0
  380. package/src/core/types.ts +138 -0
  381. package/src/query/client.ts +1129 -0
  382. package/src/query/errors.ts +108 -0
  383. package/src/query/index.ts +65 -0
  384. package/src/query/knownhosts.ts +257 -0
  385. package/src/query/lines.ts +28 -0
  386. package/src/query/options.ts +388 -0
  387. package/src/query/reconnect.ts +84 -0
  388. package/src/query/ssh.ts +614 -0
  389. package/src/query/stream.ts +91 -0
  390. package/src/query/tcp.ts +85 -0
  391. package/src/query/transport.ts +35 -0
  392. package/src/query/web.ts +195 -0
  393. package/src/versions/index.ts +10774 -0
@@ -0,0 +1,1523 @@
1
+ import {} from "./types.js";
2
+ import { ConnectPhase } from "./trace.js";
3
+ import { callHook } from "./hooks.js";
4
+ import { puzzleOf } from "./handshake/crypt-handshake.js";
5
+ import { asChannelID, asClientID, AlreadyConnectedError, backoffDelay, ClientStatus, ErrorCode, Reason, TeamspeakError, noopLogger, } from "@honeybbq/teamspeak";
6
+ import { HandshakeError, RemovedError } from "./errors.js";
7
+ import { abortable, abortReason } from "./abort.js";
8
+ import { Crypt } from "./crypto/index.js";
9
+ import { RESOLVE_BUDGET_MS, Resolver } from "./discovery/resolver.js";
10
+ import { PacketHandler } from "./transport/handler.js";
11
+ import { PacketType } from "./transport/packet.js";
12
+ import { CommandTracker, appendReturnCode } from "./commands.js";
13
+ import { buildCommandChain, encodeRequest, parseServerError, resolveBackoffPolicy, } from "../core/internal.js";
14
+ import { uploadFileData, downloadFileData } from "./transfer.js";
15
+ import { buildEventChain } from "./events.js";
16
+ import { processInit1 } from "./handshake/crypt-handshake.js";
17
+ import { handleHandshakeInitIV, handleHandshakeExpand2, defaultClientVersion, handleInitServer, prepareClientPassword, } from "./handshake.js";
18
+ import { handleNotification } from "../core/internal.js";
19
+ import { parseCommand } from "../core/internal.js";
20
+ import { CommandThrottle } from "./throttle.js";
21
+ import { splitCommandRows, sleep } from "../core/internal.js";
22
+ import { isAutoNicknameMatch } from "./helpers.js";
23
+ import { CommandTimeoutError, NotConnectedError } from "@honeybbq/teamspeak";
24
+ import { responseSpec } from "../core/internal.js";
25
+ import { unknownServerCapabilities } from "./capabilities.js";
26
+ import { joinHostPort, parseConnectAddress, splitHostPort } from "./address.js";
27
+ import { commandChannel, incomingChannel } from "./diagnostics.js";
28
+ import { defaultShouldRetry } from "./reconnect.js";
29
+ /** The signature is Ed25519, 64 bytes; the server verifies it, so only its shape is checked. */
30
+ function normalizeClientVersion(version) {
31
+ if (version === undefined)
32
+ return defaultClientVersion;
33
+ const { platform, version: text, sign } = version;
34
+ for (const [name, value] of [
35
+ ["platform", platform],
36
+ ["version", text],
37
+ ["sign", sign],
38
+ ]) {
39
+ if (typeof value !== "string" || value === "") {
40
+ throw new TypeError(`a client version's ${name} is a non-empty string`);
41
+ }
42
+ }
43
+ const raw = Buffer.from(sign, "base64");
44
+ if (raw.length !== 64 || raw.toString("base64") !== sign) {
45
+ throw new RangeError("a client version's sign is the base64 of a 64-byte signature");
46
+ }
47
+ return { platform, version: text, sign };
48
+ }
49
+ function normalizeClientInitOptions(options) {
50
+ return {
51
+ serverPasswordHash: prepareClientPassword(options.serverPassword ?? ""),
52
+ defaultChannel: options.defaultChannel ?? "",
53
+ defaultChannelPasswordHash: prepareClientPassword(options.defaultChannelPassword ?? ""),
54
+ version: normalizeClientVersion(options.version),
55
+ };
56
+ }
57
+ let internalsOf;
58
+ let sentLineHook;
59
+ /**
60
+ * Observe every command line the client sends, as encoded. A seam for the
61
+ * package's own tests; not exported from the package.
62
+ *
63
+ * @internal
64
+ */
65
+ export function onSentLine(hook) {
66
+ sentLineHook = hook;
67
+ }
68
+ /** @internal The internals of `client`. */
69
+ export function clientInternals(client) {
70
+ return internalsOf(client);
71
+ }
72
+ /** How long a command waits for its answer unless told otherwise. */
73
+ const DEFAULT_COMMAND_TIMEOUT_MS = 10_000;
74
+ /**
75
+ * How long `disconnect()` waits for the server to acknowledge its goodbye
76
+ * unless told otherwise: the acknowledgement is a courtesy, and a connection
77
+ * that has already died would otherwise hold it for a full command timeout.
78
+ */
79
+ const DISCONNECT_TIMEOUT_MS = 1_000;
80
+ /** How long each reconnection attempt may take. */
81
+ const RECONNECT_ATTEMPT_TIMEOUT_MS = 30_000;
82
+ /** The `initserver` parameters a trace never sees, because they could carry a secret. */
83
+ const SECRET_INITSERVER_PARAMS = new Set([
84
+ "client_server_password",
85
+ "client_default_channel_password",
86
+ "client_default_token",
87
+ "client_key_offset",
88
+ ]);
89
+ function newConnectAttempt() {
90
+ let resolve;
91
+ let reject;
92
+ const promise = new Promise((res, rej) => {
93
+ resolve = res;
94
+ reject = rej;
95
+ });
96
+ // The failure is reported to whoever awaits connect(); an attempt nobody
97
+ // awaits any more must not surface as an unhandled rejection.
98
+ promise.catch(() => { });
99
+ const controller = new AbortController();
100
+ const attempt = {
101
+ promise,
102
+ signal: controller.signal,
103
+ settled: false,
104
+ trace: undefined,
105
+ onFail: undefined,
106
+ resolve() {
107
+ if (attempt.settled)
108
+ return;
109
+ attempt.settled = true;
110
+ resolve();
111
+ },
112
+ reject(error) {
113
+ if (attempt.settled)
114
+ return;
115
+ attempt.settled = true;
116
+ attempt.onFail?.(error);
117
+ controller.abort(error);
118
+ reject(error);
119
+ },
120
+ rejectAfter(error, until) {
121
+ if (attempt.settled)
122
+ return;
123
+ attempt.settled = true;
124
+ attempt.onFail?.(error);
125
+ controller.abort(error);
126
+ void until.finally(() => reject(error));
127
+ },
128
+ };
129
+ return attempt;
130
+ }
131
+ /**
132
+ * Voice deliveries are dropped while more than this many deliveries of any
133
+ * kind are waiting: audio is fifty packets a second per speaker, and a
134
+ * listener that cannot keep up would otherwise queue it without bound.
135
+ */
136
+ const MAX_PENDING_DELIVERIES = 256;
137
+ /** How often dropped voice is reported, at most. */
138
+ const VOICE_DROP_WARN_INTERVAL_MS = 10_000;
139
+ /** The only commands handled before crypto init completes. */
140
+ const PRE_INIT_COMMANDS = new Set(["clientinitiv", "initivexpand2", "error"]);
141
+ /**
142
+ * A TeamSpeak client over the voice protocol.
143
+ *
144
+ * Listeners run one at a time, in the order their events arrived, after the
145
+ * packet that carried them has been handled, so a listener may call the client
146
+ * and await an answer.
147
+ */
148
+ export class Client {
149
+ static {
150
+ internalsOf = (client) => client.#internals;
151
+ }
152
+ #crypt;
153
+ #handler;
154
+ #logger;
155
+ #nickname;
156
+ #clid = 0;
157
+ /**
158
+ * What the server reported about itself in initserver, including the UID
159
+ * hash it uses: TS3 hashes the public key with SHA-1 and TS6 with SHA-256.
160
+ */
161
+ #capabilities = unknownServerCapabilities();
162
+ #internals;
163
+ #identity;
164
+ #addr;
165
+ #resolver;
166
+ #clientInitOptions;
167
+ #socketFactory;
168
+ #fileTransferSocketFactory;
169
+ /** A copy of the caller's trace, so changing theirs later changes nothing. */
170
+ #trace;
171
+ /** The session in progress, for its `sessionEnd`; cleared when that has been reported. */
172
+ #session;
173
+ /** Undefined when the client does not reconnect. */
174
+ #reconnectOptions;
175
+ /**
176
+ * Set while a reconnect attempt is in flight, so overlapping failures do not
177
+ * start competing loops.
178
+ */
179
+ #reconnecting = false;
180
+ /** The reconnect loop's latest attempt; 0 while it has made none. */
181
+ #loopAttempt = 0;
182
+ /** The last answer of `shouldRetry`, so that one failure asks it once. */
183
+ #retryAnswer;
184
+ /**
185
+ * Why the last established session dropped: a reconnect loop whose own
186
+ * attempt connected and then dropped before the loop resumed retries for it.
187
+ */
188
+ #lastDrop;
189
+ /** Set by an explicit disconnect(), which must never be undone by a retry. */
190
+ #stopped = false;
191
+ /**
192
+ * The goodbye of a disconnect() still in progress, which a connect() waits
193
+ * for: tearing the old session down after a new one has started would end
194
+ * the new one instead.
195
+ */
196
+ #leaving;
197
+ /** Ends a disconnect()'s wait for its goodbye to be answered, while it waits. */
198
+ #goodbyeAnswered;
199
+ /** How many times disconnect() was called, so a waiting connect() sees one. */
200
+ #disconnects = 0;
201
+ /**
202
+ * Settles once the last queued `disconnected` has been delivered. A
203
+ * connect() waits for it, so the end of one session is never heard during
204
+ * the next: not by a listener added for the new session, and not by an
205
+ * events() iterator started for it.
206
+ */
207
+ #disconnectedDelivered;
208
+ /** Cuts short the reconnect loop's wait, on disconnect(). */
209
+ #stopReconnecting;
210
+ #status = ClientStatus.Disconnected;
211
+ #throttle = new CommandThrottle();
212
+ #cmdTrack = new CommandTracker(() => this.#clid);
213
+ #clients = new Map();
214
+ #attempt = newConnectAttempt();
215
+ #listeners = new Map();
216
+ /** Deliveries waiting for their turn; see #emit. */
217
+ #queue = [];
218
+ #draining = false;
219
+ #voiceDropped = 0;
220
+ #voiceDropWarnedAt = -Infinity;
221
+ #eventMiddlewares;
222
+ #send;
223
+ #eventChain;
224
+ constructor(identity, addr, nickname, options = {}) {
225
+ this.#identity = identity;
226
+ this.#addr = addr;
227
+ this.#nickname = nickname;
228
+ this.#logger = options.logger ?? noopLogger;
229
+ this.#resolver = options.resolver ?? new Resolver({ nicknameLookup: options.nicknameLookup });
230
+ this.#clientInitOptions = normalizeClientInitOptions(options);
231
+ this.#socketFactory = options.socketFactory;
232
+ this.#fileTransferSocketFactory = options.fileTransferSocketFactory;
233
+ this.#reconnectOptions = options.reconnect;
234
+ this.#trace = options.trace === undefined ? undefined : { ...options.trace };
235
+ this.#crypt = new Crypt(identity);
236
+ this.#handler = this.#newHandler();
237
+ // oxlint-disable-next-line no-this-alias -- accessors cannot be arrow functions
238
+ const self = this;
239
+ this.#internals = {
240
+ get crypt() {
241
+ return self.#crypt;
242
+ },
243
+ get handler() {
244
+ return self.#handler;
245
+ },
246
+ get logger() {
247
+ return self.#logger;
248
+ },
249
+ get initOptions() {
250
+ return self.#clientInitOptions;
251
+ },
252
+ get nickname() {
253
+ return self.#nickname;
254
+ },
255
+ set nickname(value) {
256
+ self.#nickname = value;
257
+ },
258
+ get clid() {
259
+ return self.#clid;
260
+ },
261
+ set clid(value) {
262
+ self.#clid = value;
263
+ },
264
+ get capabilities() {
265
+ return self.#capabilities;
266
+ },
267
+ set capabilities(value) {
268
+ self.#capabilities = value;
269
+ },
270
+ markConnected: (initServer) => this.#markConnected(initServer),
271
+ markHandshakeDone: (serverPublicKey) => this.#markHandshakeDone(serverPublicKey),
272
+ execNoWait: (command) => this.#execNoWait(command, undefined, true),
273
+ handlePacket: (packet) => this.#handlePacket(packet),
274
+ };
275
+ // Built once: the chains are read on every command and event, and
276
+ // changing them while those run would make the behaviour depend on timing.
277
+ const cmdMiddlewares = options.commandMiddleware ?? [];
278
+ this.#eventMiddlewares = options.eventMiddleware ?? [];
279
+ this.#send = buildCommandChain(cmdMiddlewares, (request, commandOptions = {}) => this.#exec(encodeRequest(request, prepareClientPassword), commandOptions, false));
280
+ this.#eventChain = buildEventChain([...this.#eventMiddlewares], (event) => this.#deliver(event.name, event.payload));
281
+ }
282
+ /** Where the client is in its connection's life. */
283
+ get status() {
284
+ return this.#status;
285
+ }
286
+ // ---- Connection -----------------------------------------------------------
287
+ /**
288
+ * Connect to the server. Resolves once the handshake completes.
289
+ *
290
+ * An address that cannot be one — no host, a port outside 1–65535 — rejects
291
+ * with an InvalidAddressError at once, before anything starts. A host name
292
+ * that does not resolve fails the attempt with a TeamspeakError whose
293
+ * `cause` is the lookup's error.
294
+ *
295
+ * A failed attempt rejects with its cause, such as the server's error for a
296
+ * rejected password. Aborting `signal` abandons the attempt and rejects with
297
+ * the signal's reason. The signal bounds only the connecting: once this
298
+ * resolves, the connection lasts until `disconnect()` or a drop.
299
+ * `connect()` does not retry; the `reconnect` option only retries a
300
+ * connection that drops after it was established.
301
+ *
302
+ * Called while a `disconnect()` is still saying goodbye, or while an earlier
303
+ * session's `disconnected` is still waiting to be delivered, this waits for
304
+ * that first, so the old session is closed, and its `disconnected`
305
+ * delivered, before the new one starts: no listener or `events()` iterator
306
+ * of the new session hears the old one end. A `disconnect()` called during
307
+ * that wait wins: this then rejects with a NotConnectedError.
308
+ *
309
+ * `connected` is delivered after this resolves, so a listener added right
310
+ * after `await client.connect()` still hears it.
311
+ */
312
+ async connect(options = {}) {
313
+ return this.#connect(options, 1, false);
314
+ }
315
+ async #connect(options, attemptNumber, reconnect) {
316
+ const { signal } = options;
317
+ signal?.throwIfAborted();
318
+ const disconnects = this.#disconnects;
319
+ if (this.#leaving !== undefined)
320
+ await abortable(this.#leaving, signal);
321
+ while (this.#disconnectedDelivered !== undefined) {
322
+ await abortable(this.#disconnectedDelivered, signal);
323
+ }
324
+ if (this.#disconnects !== disconnects)
325
+ throw new NotConnectedError();
326
+ if (this.#status !== ClientStatus.Disconnected)
327
+ throw new AlreadyConnectedError();
328
+ // Checked before anything changes: an address that can never work leaves
329
+ // the client as it was, with no attempt to announce the end of.
330
+ parseConnectAddress(this.#addr);
331
+ this.#stopped = false;
332
+ this.#resetForConnect();
333
+ this.#status = ClientStatus.Connecting;
334
+ const attempt = this.#attempt;
335
+ const trace = {
336
+ attempt: attemptNumber,
337
+ reconnect,
338
+ startedAt: performance.now(),
339
+ connectStartedAt: 0,
340
+ phase: ConnectPhase.Open,
341
+ target: "",
342
+ sessionStarted: false,
343
+ welcomeDone: false,
344
+ channels: 0,
345
+ };
346
+ attempt.trace = trace;
347
+ attempt.onFail = (error) => this.#callHook(this.#trace?.attemptFailed, () => ({
348
+ attempt: trace.attempt,
349
+ reconnect: trace.reconnect,
350
+ phase: trace.phase,
351
+ error,
352
+ target: trace.target,
353
+ durationMs: performance.now() - trace.startedAt,
354
+ }));
355
+ // The handshake may complete just as the signal fires, in which case
356
+ // #failConnection leaves the session alone and the caller gets the
357
+ // connection it made rather than one it would believe had failed.
358
+ const onAbort = () => this.#failConnection(abortReason(signal));
359
+ signal?.addEventListener("abort", onAbort, { once: true });
360
+ try {
361
+ try {
362
+ this.#callHook(this.#trace?.resolveStart, () => ({
363
+ attempt: trace.attempt,
364
+ reconnect: trace.reconnect,
365
+ addr: this.#addr,
366
+ }));
367
+ const resolveStarted = performance.now();
368
+ const resolution = await this.#resolveAddr(attempt.signal);
369
+ const targetAddr = resolution.target;
370
+ trace.target = targetAddr;
371
+ if (!attempt.settled) {
372
+ this.#callHook(this.#trace?.resolveDone, () => ({
373
+ attempt: trace.attempt,
374
+ reconnect: trace.reconnect,
375
+ addr: this.#addr,
376
+ target: targetAddr,
377
+ source: resolution.source,
378
+ candidates: resolution.candidates,
379
+ error: resolution.error,
380
+ durationMs: performance.now() - resolveStarted,
381
+ }));
382
+ }
383
+ if (!attempt.settled) {
384
+ this.#logger.info("connecting to server", { address: targetAddr });
385
+ trace.connectStartedAt = performance.now();
386
+ this.#callHook(this.#trace?.connectStart, () => ({
387
+ attempt: trace.attempt,
388
+ reconnect: trace.reconnect,
389
+ target: targetAddr,
390
+ }));
391
+ }
392
+ if (!attempt.settled) {
393
+ await this.#handler.connect(targetAddr, attempt.signal);
394
+ // The socket is open and the first packet is out: a failure from
395
+ // here to the shared secret is the handshake's.
396
+ if (trace.phase === ConnectPhase.Open)
397
+ trace.phase = ConnectPhase.Handshake;
398
+ }
399
+ }
400
+ catch (error) {
401
+ // Without this the client stays Connecting and every later connect()
402
+ // fails with AlreadyConnectedError.
403
+ this.#failConnection(error);
404
+ }
405
+ await attempt.promise;
406
+ }
407
+ finally {
408
+ signal?.removeEventListener("abort", onAbort);
409
+ }
410
+ }
411
+ /**
412
+ * Leave the server and close the connection.
413
+ *
414
+ * Says goodbye first, waiting for the server's acknowledgement for a second
415
+ * at most, or less if `signal` aborts sooner. The connection is closed
416
+ * either way. A `connect()` still waiting for its handshake rejects with a
417
+ * NotConnectedError, and so do the commands still waiting for an answer.
418
+ * Resolves once `disconnected` has been delivered to the listeners, so one
419
+ * added after `await client.disconnect()` does not hear it. Does nothing on
420
+ * a client that is not connected; called again while an earlier call is
421
+ * still saying goodbye, it waits for that one.
422
+ */
423
+ async disconnect(options = {}) {
424
+ // Recorded before anything else: a dropped socket during the goodbye below
425
+ // must not be mistaken for an outage worth retrying.
426
+ this.#stopped = true;
427
+ this.#disconnects++;
428
+ this.#stopReconnecting?.abort();
429
+ if (this.#leaving !== undefined)
430
+ return this.#leaving;
431
+ // Already ended, by a drop or a failed attempt: its `disconnected` may
432
+ // still be on its way.
433
+ if (this.#status === ClientStatus.Disconnected)
434
+ return this.#disconnectedDelivered;
435
+ const wasConnected = this.#status === ClientStatus.Connected;
436
+ this.#status = ClientStatus.Disconnected;
437
+ let left;
438
+ this.#attempt.rejectAfter(new NotConnectedError(), new Promise((r) => (left = r)));
439
+ const leaving = this.#leave(wasConnected, options.signal).finally(left);
440
+ this.#leaving = leaving;
441
+ try {
442
+ await leaving;
443
+ }
444
+ finally {
445
+ this.#leaving = undefined;
446
+ }
447
+ }
448
+ async #leave(wasConnected, signal) {
449
+ this.#logger.info("disconnecting from server");
450
+ if (wasConnected) {
451
+ this.#callHook(this.#trace?.disconnectStart, () => ({}));
452
+ const goodbyeStarted = performance.now();
453
+ // The server answers clientdisconnect with a notifyclientleftview about
454
+ // this client, and no error line; either one ends the wait. A goodbye
455
+ // that is not answered in time is a courtesy lost: the connection
456
+ // closes regardless.
457
+ const left = new Promise((resolve) => {
458
+ this.#goodbyeAnswered = () => resolve(true);
459
+ });
460
+ // On the internal path: the status already says Disconnected.
461
+ const answered = this.#exec("clientdisconnect reasonmsg=Shutdown", { signal, timeoutMs: DISCONNECT_TIMEOUT_MS }, true).then(() => true, () => false);
462
+ const acknowledged = await Promise.race([answered, left]);
463
+ this.#goodbyeAnswered = undefined;
464
+ this.#callHook(this.#trace?.disconnectDone, () => ({
465
+ acknowledged,
466
+ durationMs: performance.now() - goodbyeStarted,
467
+ }));
468
+ }
469
+ this.#handler.close();
470
+ this.#cmdTrack.reset(new NotConnectedError());
471
+ this.#endSession(undefined);
472
+ // Announced here; #handleConnectionClosed stays quiet once the status is
473
+ // already Disconnected, so listeners hear about it once.
474
+ await this.#announceDisconnected(undefined, false);
475
+ }
476
+ /** `await using client = …` disconnects when the scope ends. */
477
+ [Symbol.asyncDispose]() {
478
+ return this.disconnect();
479
+ }
480
+ // ---- Commands ------------------------------------------------------------
481
+ /**
482
+ * Send a raw command line and return the rows that answer it: the escape
483
+ * hatch for a command the typed functions do not cover. The line is sent as
484
+ * given, so its values must already be escaped and any channel password
485
+ * already hashed. `CommandName` lists the command names.
486
+ *
487
+ * Rejects with a NotConnectedError unless the client is connected: while it
488
+ * is still connecting, the session's keys may not exist yet.
489
+ */
490
+ // oxlint-disable-next-line typescript/array-type -- the public API report spells this `[]`; respelling it changes the report
491
+ exec(command, options = {}) {
492
+ return this.#exec(command, options, false);
493
+ }
494
+ /**
495
+ * Send a raw command line without waiting for an answer, for the few
496
+ * commands the server answers with nothing at all. `CommandName` lists
497
+ * the command names.
498
+ *
499
+ * Commands are paced by a flood throttle; aborting `signal` while this waits
500
+ * for its turn rejects with the signal's reason and sends nothing. Rejects
501
+ * with a NotConnectedError unless the client is connected.
502
+ */
503
+ execNoWait(command, options = {}) {
504
+ return this.#execNoWait(command, options.signal, false);
505
+ }
506
+ /**
507
+ * Whether a command may go out now. The handshake's own commands (`internal`)
508
+ * need only an open socket; everything else needs a connected session, so
509
+ * nothing a caller sends can go out under the public dummy key, or after
510
+ * disconnect() has begun saying goodbye.
511
+ */
512
+ #canSend(internal) {
513
+ return this.#handler.isOpen && (internal || this.#status === ClientStatus.Connected);
514
+ }
515
+ async #execNoWait(command, signal, internal) {
516
+ signal?.throwIfAborted();
517
+ if (!this.#canSend(internal))
518
+ throw new NotConnectedError();
519
+ await this.#throttle.wait(signal);
520
+ if (!this.#canSend(internal))
521
+ throw new NotConnectedError();
522
+ this.#sendLine(command);
523
+ }
524
+ /**
525
+ * Send a typed command; this is the CommandExecutor the typed commands run on.
526
+ *
527
+ * The request passes through the `commandMiddleware` first. Channel
528
+ * passwords are then hashed, because that is this protocol's rule: the voice
529
+ * protocol expects `base64(sha1(password))`, where ServerQuery takes the
530
+ * password itself.
531
+ */
532
+ // oxlint-disable-next-line typescript/array-type -- the public API report spells this `[]`; respelling it changes the report
533
+ send(request, options = {}) {
534
+ return this.#send(request, options);
535
+ }
536
+ #sendLine(line) {
537
+ const hook = sentLineHook;
538
+ if (hook)
539
+ hook(this, line);
540
+ this.#handler.sendPacket(PacketType.Command, Buffer.from(line), 0);
541
+ }
542
+ #exec(command, options, internal) {
543
+ if (!commandChannel.hasSubscribers)
544
+ return this.#execUntraced(command, options, internal);
545
+ const trace = { command: parseCommand(command)?.name ?? "", client: this };
546
+ return commandChannel.tracePromise(() => this.#execUntraced(command, options, internal), trace);
547
+ }
548
+ async #execUntraced(command, options, internal) {
549
+ const { signal, timeoutMs = DEFAULT_COMMAND_TIMEOUT_MS } = options;
550
+ signal?.throwIfAborted();
551
+ // A command sent on no socket used to vanish and surface 10 seconds later
552
+ // as a timeout, which reads like a slow server rather than a usage error.
553
+ if (!this.#canSend(internal))
554
+ throw new NotConnectedError();
555
+ // Which notifications answer this command, and — for answers that arrive
556
+ // after the `error` — the request field they echo back.
557
+ const parsed = parseCommand(command);
558
+ const spec = responseSpec(parsed?.name ?? "");
559
+ const key = spec?.correlated?.key;
560
+ const correlation = key === undefined ? undefined : parsed?.params[key];
561
+ const [rc, answered] = this.#cmdTrack.register(spec, correlation);
562
+ let timer;
563
+ let onAbort;
564
+ // Started before the throttle: the timeout bounds the whole command, its
565
+ // wait for a turn included, and so does the signal.
566
+ const givenUp = new Promise((_, reject) => {
567
+ timer = setTimeout(() => reject(new CommandTimeoutError(parsed?.name ?? "")), timeoutMs);
568
+ onAbort = () => reject(abortReason(signal));
569
+ signal?.addEventListener("abort", onAbort, { once: true });
570
+ });
571
+ givenUp.catch(() => { });
572
+ const throttleAbort = new AbortController();
573
+ try {
574
+ const withRc = appendReturnCode(command, rc);
575
+ await Promise.race([this.#throttle.wait(throttleAbort.signal), givenUp]);
576
+ if (!this.#canSend(internal))
577
+ throw new NotConnectedError();
578
+ this.#sendLine(withRc);
579
+ const result = await Promise.race([answered, givenUp]);
580
+ if (result.err)
581
+ throw result.err;
582
+ return result.data;
583
+ }
584
+ finally {
585
+ // A command given up while it waited for its turn gives the turn back.
586
+ throttleAbort.abort();
587
+ // Cleared, not left to fire: a pending timer keeps the process alive for
588
+ // the full timeout after the last command has long been answered.
589
+ clearTimeout(timer);
590
+ if (onAbort)
591
+ signal?.removeEventListener("abort", onAbort);
592
+ this.#cmdTrack.unregister(rc);
593
+ }
594
+ }
595
+ // ---- Events --------------------------------------------------------------
596
+ /**
597
+ * Listen for an event. Returns a function that removes the listener.
598
+ *
599
+ * The event is named by an {@link EventName} constant or by its string, and
600
+ * the listener's payload type follows from it:
601
+ *
602
+ * ```ts
603
+ * client.on(EventName.TextMessage, (message) => console.log(message.message));
604
+ * ```
605
+ *
606
+ * A listener that throws does not stop the others: the rest of the event's
607
+ * listeners, and the events after it, are still delivered, and the exception
608
+ * is rethrown on its own, from a microtask, so it surfaces as an
609
+ * `uncaughtException` just as an EventEmitter listener's would. An async
610
+ * listener's rejection is not caught, and surfaces as an unhandled
611
+ * rejection.
612
+ */
613
+ on(event, listener) {
614
+ const subscription = {
615
+ listener: listener,
616
+ removed: false,
617
+ };
618
+ // A new array rather than an edit in place: a delivery may be iterating
619
+ // over the old one.
620
+ this.#listeners.set(event, [...(this.#listeners.get(event) ?? []), subscription]);
621
+ const unsubscribe = () => {
622
+ if (subscription.removed)
623
+ return;
624
+ subscription.removed = true;
625
+ const list = this.#listeners.get(event) ?? [];
626
+ this.#listeners.set(event, list.filter((s) => s !== subscription));
627
+ };
628
+ return Object.assign(unsubscribe, { [Symbol.dispose]: unsubscribe });
629
+ }
630
+ /** Listen for the next occurrence of an event only. */
631
+ once(event, listener) {
632
+ const unsubscribe = this.on(event, ((payload) => {
633
+ unsubscribe();
634
+ listener(payload);
635
+ }));
636
+ return unsubscribe;
637
+ }
638
+ /**
639
+ * An event as an async iterator, for `for await`:
640
+ *
641
+ * ```ts
642
+ * for await (const message of client.events("textMessage", { signal })) { … }
643
+ * ```
644
+ *
645
+ * Events that arrive while the loop body runs are buffered, so none is
646
+ * missed. The buffer is unbounded: an iterator that is not consumed as fast
647
+ * as events arrive holds every one of them in memory until it is read, so
648
+ * stop iterating (or abort `signal`) when you stop reading. Voice is the
649
+ * exception: at most 256 `voiceData` frames are buffered, and the rest are
650
+ * dropped, as for a listener that falls behind.
651
+ *
652
+ * Iteration ends when the loop exits early (`break`, `return`, a throw), and
653
+ * — for every event but `disconnected` — when the client disconnects. When
654
+ * `signal` aborts, listening stops at once, whatever is buffered is
655
+ * discarded, and the pending and every later `next()` reject with the
656
+ * signal's reason, as `events.on` in Node does.
657
+ *
658
+ * `next()` may be called again before an earlier call has settled; the calls
659
+ * are answered in order.
660
+ */
661
+ events(event, options = {}) {
662
+ const { signal } = options;
663
+ const buffered = [];
664
+ // The next() calls waiting for an event, oldest first.
665
+ const waiting = [];
666
+ let ended = false;
667
+ let aborted = false;
668
+ const finishWaiting = () => {
669
+ for (const waiter of waiting.splice(0)) {
670
+ waiter.resolve({ value: undefined, done: true });
671
+ }
672
+ };
673
+ const stopListening = this.on(event, ((payload) => {
674
+ if (ended)
675
+ return;
676
+ const waiter = waiting.shift();
677
+ if (waiter) {
678
+ waiter.resolve({ value: payload, done: false });
679
+ return;
680
+ }
681
+ if (event === "voiceData" && buffered.length >= MAX_PENDING_DELIVERIES) {
682
+ this.#dropVoice();
683
+ return;
684
+ }
685
+ buffered.push(payload);
686
+ }));
687
+ // Ends after what is already buffered, which arrived before the disconnect.
688
+ const stopOnDisconnect = event === "disconnected"
689
+ ? undefined
690
+ : this.on("disconnected", () => {
691
+ cleanup();
692
+ finishWaiting();
693
+ });
694
+ const cleanup = () => {
695
+ ended = true;
696
+ stopListening();
697
+ stopOnDisconnect?.();
698
+ signal?.removeEventListener("abort", abort);
699
+ };
700
+ const abort = () => {
701
+ aborted = true;
702
+ buffered.length = 0;
703
+ cleanup();
704
+ const reason = abortReason(signal);
705
+ for (const waiter of waiting.splice(0))
706
+ waiter.reject(reason);
707
+ };
708
+ if (signal?.aborted)
709
+ abort();
710
+ else
711
+ signal?.addEventListener("abort", abort, { once: true });
712
+ const iterator = {
713
+ next() {
714
+ if (aborted)
715
+ return Promise.reject(abortReason(signal));
716
+ if (buffered.length > 0)
717
+ return Promise.resolve({ value: buffered.shift(), done: false });
718
+ if (ended) {
719
+ cleanup();
720
+ return Promise.resolve({ value: undefined, done: true });
721
+ }
722
+ return new Promise((resolve, reject) => waiting.push({ resolve, reject }));
723
+ },
724
+ return() {
725
+ buffered.length = 0;
726
+ cleanup();
727
+ finishWaiting();
728
+ return Promise.resolve({ value: undefined, done: true });
729
+ },
730
+ [Symbol.asyncIterator]() {
731
+ return iterator;
732
+ },
733
+ };
734
+ return iterator;
735
+ }
736
+ // ---- API shorthand -------------------------------------------------------
737
+ /** This client's id on the server, assigned in the handshake; 0 before it. */
738
+ get clientID() {
739
+ return asClientID(this.#clid);
740
+ }
741
+ /**
742
+ * What the connected server is: version, generation, and the uid hash it
743
+ * uses. Read from `initserver`; before connecting the family is `unknown`
744
+ * and the uid hash SHA-1.
745
+ */
746
+ get serverCapabilities() {
747
+ return this.#capabilities;
748
+ }
749
+ /**
750
+ * Our own `client_unique_identifier`, hashed with the algorithm the connected
751
+ * server uses.
752
+ *
753
+ * TS3 uses SHA-1 and TS6 SHA-256, so this reads the algorithm learned during
754
+ * initserver rather than assuming one. Comparing a hard-coded SHA-1 UID to a
755
+ * TS6 server silently never matches.
756
+ */
757
+ get uid() {
758
+ return this.#identity.uid(this.#capabilities.uidAlgorithm);
759
+ }
760
+ /** The channel this client is in, as it last learned; 0 before connecting. */
761
+ get channelID() {
762
+ return this.#clients.get(this.#clid)?.channelID ?? asChannelID(0n);
763
+ }
764
+ /**
765
+ * Send Opus voice directly to specific clients, bypassing channel routing.
766
+ * Throws a NotConnectedError unless the client is connected, and a
767
+ * RangeError for no target, more than 32, or an id that is not a client id.
768
+ */
769
+ sendWhisper(data, targets, codec) {
770
+ if (!this.#canSend(false))
771
+ throw new NotConnectedError();
772
+ this.#handler.sendWhisperPacket(data, [...(targets.clients ?? [])], codec);
773
+ }
774
+ /**
775
+ * Send one encoded audio frame to the channel this client is in. Throws a
776
+ * NotConnectedError unless the client is connected.
777
+ */
778
+ sendVoice(data, codec, options) {
779
+ // Reserved: VoiceOptions has no fields to read yet.
780
+ void options;
781
+ if (!this.#canSend(false))
782
+ throw new NotConnectedError();
783
+ this.#handler.sendVoicePacket(data, codec);
784
+ }
785
+ // ---- File Transfer -------------------------------------------------------
786
+ /**
787
+ * Upload `data` over a negotiated transfer, through the client's
788
+ * `fileTransferSocketFactory` if it has one.
789
+ */
790
+ uploadFileData(host, info, data, options = {}) {
791
+ return uploadFileData(host, info, data, {
792
+ ...options,
793
+ socketFactory: this.#fileTransferSocketFactory,
794
+ });
795
+ }
796
+ /**
797
+ * Download a negotiated transfer into `dest`, through the client's
798
+ * `fileTransferSocketFactory` if it has one.
799
+ */
800
+ downloadFileData(host, info, dest, options = {}) {
801
+ return downloadFileData(host, info, dest, {
802
+ ...options,
803
+ socketFactory: this.#fileTransferSocketFactory,
804
+ });
805
+ }
806
+ // ---- Internal (package-visible) ------------------------------------------
807
+ #markConnected(initServer = {}) {
808
+ // Only the attempt in progress can complete: never one that disconnect()
809
+ // or a failure has already ended.
810
+ if (this.#status !== ClientStatus.Connecting || this.#attempt.settled)
811
+ return;
812
+ this.#status = ClientStatus.Connected;
813
+ // Settled before the hook runs, so that nothing it does can turn this
814
+ // attempt into a failed one; connect() resumes only after the hook returns.
815
+ this.#attempt.resolve();
816
+ const trace = this.#attempt.trace;
817
+ if (trace !== undefined) {
818
+ trace.sessionStarted = true;
819
+ this.#session = {
820
+ clientID: asClientID(this.#clid),
821
+ startedAt: performance.now(),
822
+ attempt: trace.attempt,
823
+ reconnect: trace.reconnect,
824
+ };
825
+ this.#callHook(this.#trace?.sessionStart, () => {
826
+ const safe = {};
827
+ for (const [key, value] of Object.entries(initServer)) {
828
+ if (!SECRET_INITSERVER_PARAMS.has(key))
829
+ safe[key] = value;
830
+ }
831
+ const talkPower = Number.parseInt(initServer["client_talk_power"] ?? "", 10);
832
+ return {
833
+ attempt: trace.attempt,
834
+ reconnect: trace.reconnect,
835
+ clientID: asClientID(this.#clid),
836
+ nickname: initServer["acn"] ?? this.#nickname,
837
+ talkPower: Number.isNaN(talkPower) ? 0 : talkPower,
838
+ initServer: Object.freeze(safe),
839
+ capabilities: this.#capabilities,
840
+ durationMs: performance.now() - trace.connectStartedAt,
841
+ };
842
+ });
843
+ }
844
+ this.#emit("connected", { reconnected: trace?.reconnect ?? false });
845
+ }
846
+ /** The socket is open: the attempt's handshake begins. */
847
+ #markConnectDone(socket) {
848
+ const trace = this.#attempt.trace;
849
+ if (trace === undefined || this.#attempt.settled || trace.phase !== ConnectPhase.Open)
850
+ return;
851
+ trace.phase = ConnectPhase.Handshake;
852
+ this.#callHook(this.#trace?.connectDone, () => {
853
+ let localAddr = "";
854
+ try {
855
+ const local = socket.address?.();
856
+ if (local !== undefined)
857
+ localAddr = joinHostPort(local.address, String(local.port));
858
+ }
859
+ catch {
860
+ // A socket that cannot say where it is bound has no local address to report.
861
+ }
862
+ return {
863
+ attempt: trace.attempt,
864
+ reconnect: trace.reconnect,
865
+ target: trace.target,
866
+ localAddr,
867
+ durationMs: performance.now() - trace.connectStartedAt,
868
+ };
869
+ });
870
+ }
871
+ #markHandshakeDone(serverPublicKey = "") {
872
+ const trace = this.#attempt.trace;
873
+ if (trace === undefined || this.#attempt.settled || trace.phase !== ConnectPhase.Handshake) {
874
+ return;
875
+ }
876
+ trace.phase = ConnectPhase.Join;
877
+ this.#callHook(this.#trace?.handshakeDone, () => {
878
+ const puzzle = puzzleOf(this.#crypt);
879
+ return {
880
+ attempt: trace.attempt,
881
+ reconnect: trace.reconnect,
882
+ durationMs: performance.now() - trace.connectStartedAt,
883
+ puzzleLevel: puzzle.level,
884
+ puzzleDurationMs: puzzle.durationMs,
885
+ // The handler is this attempt's own, so its count starts at the socket.
886
+ resends: this.#handler.resends,
887
+ serverPublicKey,
888
+ };
889
+ });
890
+ }
891
+ #markWelcomeDone() {
892
+ const trace = this.#attempt.trace;
893
+ if (trace === undefined || !trace.sessionStarted || trace.welcomeDone)
894
+ return;
895
+ if (this.#status !== ClientStatus.Connected)
896
+ return;
897
+ trace.welcomeDone = true;
898
+ this.#callHook(this.#trace?.welcomeDone, () => ({
899
+ attempt: trace.attempt,
900
+ reconnect: trace.reconnect,
901
+ channelID: this.channelID,
902
+ channels: trace.channels,
903
+ clients: this.#clients.size,
904
+ durationMs: performance.now() - trace.connectStartedAt,
905
+ }));
906
+ }
907
+ /** Report the end of the session in progress, once. */
908
+ #endSession(error) {
909
+ const session = this.#session;
910
+ if (session === undefined)
911
+ return;
912
+ this.#session = undefined;
913
+ this.#callHook(this.#trace?.sessionEnd, () => ({
914
+ clientID: session.clientID,
915
+ error,
916
+ durationMs: performance.now() - session.startedAt,
917
+ attempt: session.attempt,
918
+ reconnect: session.reconnect,
919
+ }));
920
+ }
921
+ /**
922
+ * Call a trace hook, if there is one, and never let it touch the
923
+ * connection: see callHook. The info is built only when there is a hook.
924
+ */
925
+ #callHook(hook, info) {
926
+ callHook(hook, this.#trace, info);
927
+ }
928
+ // ---- Private -------------------------------------------------------------
929
+ #newHandler() {
930
+ const handler = new PacketHandler(this.#crypt, this.#logger, this.#socketFactory);
931
+ // Each callback checks that its handler is still the current one: a
932
+ // packet or close reported late by one a later connect() already replaced
933
+ // must not reach, or tear down, the new connection.
934
+ handler.onPacket = (p) => {
935
+ if (handler === this.#handler)
936
+ this.#handlePacket(p);
937
+ };
938
+ handler.onClosed = (err) => {
939
+ if (handler === this.#handler)
940
+ this.#handleConnectionClosed(err);
941
+ };
942
+ handler.onOpen = (socket) => {
943
+ if (handler === this.#handler)
944
+ this.#markConnectDone(socket);
945
+ };
946
+ handler.onReceiveError = (error) => {
947
+ if (handler === this.#handler)
948
+ this.#handleReceiveError(error);
949
+ };
950
+ return handler;
951
+ }
952
+ #resetForConnect() {
953
+ this.#handler.close();
954
+ this.#crypt = new Crypt(this.#identity);
955
+ this.#handler = this.#newHandler();
956
+ this.#attempt = newConnectAttempt();
957
+ this.#cmdTrack.reset(new NotConnectedError());
958
+ this.#clients.clear();
959
+ this.#clid = 0;
960
+ this.#capabilities = unknownServerCapabilities();
961
+ }
962
+ async #resolveAddr(signal) {
963
+ // Parsed, not tested for a colon: an IPv6 literal has colons and no port.
964
+ const { host, port } = splitHostPort(this.#addr);
965
+ const fallback = joinHostPort(host, port);
966
+ // Every resolver, a custom one too, gets the same budget: past it the
967
+ // address is used as given. A timer the tests can control, not
968
+ // AbortSignal.timeout().
969
+ const budget = new AbortController();
970
+ const timer = setTimeout(() => budget.abort(new TeamspeakError("address resolution took too long")), RESOLVE_BUDGET_MS);
971
+ const lookup = AbortSignal.any([signal, budget.signal]);
972
+ try {
973
+ // Raced against the signal: a resolver that ignores it must still not
974
+ // hold up an attempt that has been given up.
975
+ const resolved = await abortable(this.#resolver.resolve(this.#addr, { signal: lookup }), lookup);
976
+ const first = resolved[0];
977
+ return {
978
+ target: first?.addr ?? fallback,
979
+ source: first?.source ?? "",
980
+ candidates: resolved,
981
+ error: undefined,
982
+ };
983
+ }
984
+ catch (error) {
985
+ signal.throwIfAborted();
986
+ const reason = budget.signal.aborted ? budget.signal.reason : error;
987
+ this.#logger.warn("address resolution failed, falling back to direct", {
988
+ error: String(reason),
989
+ });
990
+ return { target: fallback, source: "", candidates: [], error: reason };
991
+ }
992
+ finally {
993
+ clearTimeout(timer);
994
+ }
995
+ }
996
+ /**
997
+ * A datagram from the server could not be handled. During the handshake that
998
+ * is the connection failing, reported as a HandshakeError with the cause;
999
+ * once connected, one bad packet is not worth the session, so it is dropped.
1000
+ */
1001
+ #handleReceiveError(error) {
1002
+ if (this.#status !== ClientStatus.Connected) {
1003
+ this.#failConnection(error instanceof HandshakeError
1004
+ ? error
1005
+ : new HandshakeError("the handshake failed on a malformed packet", { cause: error }));
1006
+ return;
1007
+ }
1008
+ this.#logger.debug("dropped a malformed packet", { error: String(error) });
1009
+ }
1010
+ #handlePacket(p) {
1011
+ const pType = p.typeFlagged & 0x0f;
1012
+ if (pType === 8 /* Init1 */) {
1013
+ if (this.#crypt.cryptoInitComplete)
1014
+ return;
1015
+ const response = processInit1(this.#crypt, p.data);
1016
+ if (response) {
1017
+ this.#handler.sendPacket(PacketType.Init1, response, 0);
1018
+ }
1019
+ return;
1020
+ }
1021
+ if ((pType === 0 /* Voice */ || pType === 1) /* VoiceWhisper */ && p.data.length > 5) {
1022
+ this.#handleVoicePacket(p.data);
1023
+ return;
1024
+ }
1025
+ if ((pType === 2 /* Command */ || pType === 3) /* CommandLow */ && p.data.length > 0) {
1026
+ this.#handleCommandLines(Buffer.from(p.data).toString("utf8"));
1027
+ }
1028
+ }
1029
+ /**
1030
+ * Parse an incoming S2C voice packet.
1031
+ * Format: [VId: u16] [CId: u16] [Codec: u8] [Data: var]
1032
+ */
1033
+ #handleVoicePacket(payload) {
1034
+ // Audio arrives fifty times a second per speaker; build no event nobody
1035
+ // will see.
1036
+ if (!this.#listeners.get("voiceData")?.length && this.#eventMiddlewares.length === 0)
1037
+ return;
1038
+ if (this.#queue.length > MAX_PENDING_DELIVERIES) {
1039
+ this.#dropVoice();
1040
+ return;
1041
+ }
1042
+ const view = new DataView(payload.buffer, payload.byteOffset, payload.byteLength);
1043
+ const clientId = view.getUint16(2, false);
1044
+ if (clientId === this.#clid)
1045
+ return;
1046
+ // Copied: the packet's buffer is reused once this returns, and a listener
1047
+ // runs later.
1048
+ const data = payload.slice(5);
1049
+ this.#emitServerEvent({
1050
+ name: "voiceData",
1051
+ payload: { clientID: asClientID(clientId), codec: payload[4], data },
1052
+ });
1053
+ }
1054
+ #handleCommandLines(s) {
1055
+ if (!s)
1056
+ return;
1057
+ const lines = s.split("\0").join("\n").split("\n");
1058
+ for (const line of lines) {
1059
+ const trimmed = line.replace(/\r$/, "");
1060
+ if (!trimmed)
1061
+ continue;
1062
+ for (const row of splitCommandRows(trimmed)) {
1063
+ this.#handleCommandStr(row);
1064
+ }
1065
+ }
1066
+ }
1067
+ #handleCommandStr(s) {
1068
+ const cmd = parseCommand(s);
1069
+ if (!cmd)
1070
+ return;
1071
+ // Before crypto init a packet needs only the public dummy key, so anyone
1072
+ // on the path could have sent it: nothing but the handshake's own steps,
1073
+ // and an error that may end the attempt, is taken then. A notification
1074
+ // would be a forged event, a row a forged answer.
1075
+ if (!this.#crypt.cryptoInitComplete && !PRE_INIT_COMMANDS.has(cmd.name)) {
1076
+ this.#logger.debug("dropped a command that arrived before crypto init", {
1077
+ command: cmd.name,
1078
+ });
1079
+ return;
1080
+ }
1081
+ if (incomingChannel.hasSubscribers)
1082
+ incomingChannel.publish({ command: cmd.name, client: this });
1083
+ // No name means a response row: the server sends data without echoing the
1084
+ // command, so the row belongs to whichever command is awaiting a result.
1085
+ if (cmd.name === "") {
1086
+ if (Object.keys(cmd.params).length > 0)
1087
+ this.#cmdTrack.buffer(cmd.params);
1088
+ return;
1089
+ }
1090
+ // `channellistfinished` ends the server's welcome sequence. It carries no
1091
+ // data of its own, so it is the only reliable marker: the guard used to
1092
+ // trip on our own notifycliententerview, which the server sends *in the
1093
+ // middle* of the sequence — the channellist rows after it were then
1094
+ // buffered as if they were the response to the caller's first command,
1095
+ // which is how a channellist could come back with duplicate and empty rows.
1096
+ if (cmd.name === "channellistfinished") {
1097
+ this.#cmdTrack.signalWelcomeComplete();
1098
+ this.#markWelcomeDone();
1099
+ return;
1100
+ }
1101
+ if (cmd.name === "channellist") {
1102
+ const trace = this.#attempt.trace;
1103
+ if (trace !== undefined && !trace.welcomeDone)
1104
+ trace.channels++;
1105
+ }
1106
+ // The server answers our goodbye by announcing that we left, not with an
1107
+ // error line; that announcement is what disconnect() waits for.
1108
+ if (cmd.name === "notifyclientleftview" &&
1109
+ this.#goodbyeAnswered !== undefined &&
1110
+ cmd.params["clid"] === String(this.#clid)) {
1111
+ this.#goodbyeAnswered();
1112
+ }
1113
+ if (cmd.name.startsWith("notify")) {
1114
+ // Some commands are answered by a notification instead of data rows;
1115
+ // it still goes on to be dispatched as an event, since the same
1116
+ // notification also arrives unprompted.
1117
+ if (this.#cmdTrack.expects(cmd.name)) {
1118
+ this.#cmdTrack.buffer(cmd.params, cmd.name);
1119
+ this.#cmdTrack.offerCorrelated(cmd.name, cmd.params);
1120
+ }
1121
+ const result = handleNotification(cmd, this.#clid, this.#clients);
1122
+ this.#processNotificationResult(result);
1123
+ if (this.#listeners.get("notification")?.length || this.#eventMiddlewares.length > 0) {
1124
+ this.#emitServerEvent({
1125
+ name: "notification",
1126
+ payload: { name: cmd.name, params: { ...cmd.params } },
1127
+ });
1128
+ }
1129
+ return;
1130
+ }
1131
+ switch (cmd.name) {
1132
+ // The handshake's steps happen once: repeated after crypto init, they
1133
+ // could only re-key or re-announce a session that is already set up.
1134
+ case "clientinitiv":
1135
+ if (!this.#crypt.cryptoInitComplete)
1136
+ handleHandshakeInitIV(this.#internals, cmd.params);
1137
+ break;
1138
+ case "initivexpand2":
1139
+ if (!this.#crypt.cryptoInitComplete)
1140
+ handleHandshakeExpand2(this.#internals, cmd.params);
1141
+ break;
1142
+ case "initserver":
1143
+ // Only on a session with its keys: before crypto init a packet needs
1144
+ // nothing but the public dummy key, and an initserver taken then would
1145
+ // report a connection whose next command — clientinit with its password
1146
+ // hashes among them — goes out under that dummy key.
1147
+ if (this.#status === ClientStatus.Connecting && this.#crypt.cryptoInitComplete) {
1148
+ handleInitServer(this.#internals, cmd.params);
1149
+ }
1150
+ break;
1151
+ case "error":
1152
+ this.#handleError(cmd.params);
1153
+ break;
1154
+ default:
1155
+ // A named command the SDK does not model. Held under its own name, so
1156
+ // it answers a command only if that command declared it — not merely by
1157
+ // arriving while one is in flight.
1158
+ this.#cmdTrack.buffer(cmd.params, cmd.name);
1159
+ break;
1160
+ }
1161
+ }
1162
+ #handleError(params) {
1163
+ const { err, rc } = parseServerError(params);
1164
+ if (rc !== null) {
1165
+ this.#cmdTrack.resolve(rc, err);
1166
+ }
1167
+ else {
1168
+ // No return_code: server is acknowledging an unsolicited command
1169
+ // (welcome-sequence channellist, no-RC commands like clientupdate, etc.).
1170
+ // Discard any rows buffered since the last resolved command.
1171
+ this.#cmdTrack.discardBuffer();
1172
+ }
1173
+ // A server error before the welcome sequence finished is the connection
1174
+ // failure itself — a rejected password, or an invalid clientinit parameter.
1175
+ // Report it as the cause instead of leaving the caller with a bare timeout.
1176
+ if (err && this.#status !== ClientStatus.Connected) {
1177
+ this.#failConnection(err);
1178
+ return;
1179
+ }
1180
+ // Only a connected session gets here, so only after crypto init: an error
1181
+ // under the public dummy key can fail an attempt, never stop the client.
1182
+ if (err?.code === ErrorCode.ConnectFailedBanned) {
1183
+ this.#logger.warn("banned by the server, closing the connection");
1184
+ setImmediate(() => {
1185
+ this.disconnect().catch(() => { });
1186
+ });
1187
+ }
1188
+ }
1189
+ #processNotificationResult(result) {
1190
+ switch (result.kind) {
1191
+ case "clientEnter": {
1192
+ const info = result.info;
1193
+ // Identify self by the clid initserver already assigned rather than by
1194
+ // nickname: any other client whose nickname happens to be "<our
1195
+ // nick><digits>" — which is how the server renames a client whose
1196
+ // nickname was taken — would otherwise be mistaken for us, poisoning
1197
+ // every outgoing packet header with a foreign clientID until the server
1198
+ // drops the connection for command-resend timeout.
1199
+ //
1200
+ // This no longer marks the end of the welcome sequence: the server
1201
+ // sends more welcome data after it, and `channellistfinished` is the
1202
+ // real terminator.
1203
+ if (info.id === this.#clid) {
1204
+ // Carries the rename the server applied if our nickname was taken.
1205
+ this.#nickname = info.nickname;
1206
+ }
1207
+ else if (this.#clid === 0 && isAutoNicknameMatch(this.#nickname, info.nickname)) {
1208
+ // initserver carried no aclid, so the welcome enter is the only way
1209
+ // to learn our clid. Gated on clid still being unknown so a later
1210
+ // lookalike can never hijack an established session.
1211
+ this.#clid = info.id;
1212
+ this.#handler.setClientID(info.id);
1213
+ this.#nickname = info.nickname;
1214
+ }
1215
+ this.#emitServerEvent({ name: "clientEnter", payload: info });
1216
+ break;
1217
+ }
1218
+ case "clientLeave": {
1219
+ const event = result.event;
1220
+ this.#emitServerEvent({ name: "clientLeave", payload: event });
1221
+ if (!result.isSelf)
1222
+ break;
1223
+ if (event.reason === Reason.KickServer || event.reason === Reason.KickServerBan) {
1224
+ this.#emit("kicked", kickedEvent(event));
1225
+ }
1226
+ this.#removedByServer(new RemovedError(event.reason, event.reasonMessage, event.invokerName));
1227
+ break;
1228
+ }
1229
+ case "clientMoved":
1230
+ this.#emitServerEvent({ name: "clientMoved", payload: result.event });
1231
+ // A channel kick moves the client to the default channel; it arrives
1232
+ // as a move, not as leaving view, which is where it used to be looked
1233
+ // for.
1234
+ if (result.event.clientID === this.#clid && result.event.reason === Reason.KickChannel) {
1235
+ this.#emit("kicked", kickedEvent(result.event));
1236
+ }
1237
+ break;
1238
+ case "textMessage":
1239
+ this.#emitServerEvent({ name: "textMessage", payload: result.message });
1240
+ break;
1241
+ case "poked":
1242
+ this.#emitServerEvent({ name: "poked", payload: result.event });
1243
+ break;
1244
+ case "unknown":
1245
+ break;
1246
+ }
1247
+ }
1248
+ /**
1249
+ * End a session the server has ended. The server stops answering a client it
1250
+ * has removed, so waiting for the transport to notice reported the end a
1251
+ * minute late, without its cause, and with the client claiming to be
1252
+ * connected meanwhile.
1253
+ */
1254
+ #removedByServer(cause) {
1255
+ this.#handleConnectionClosed(cause);
1256
+ this.#handler.close();
1257
+ }
1258
+ /**
1259
+ * Count a dropped voice delivery, and report the drops now and then: at most
1260
+ * once every ten seconds, with how many were dropped since the last report.
1261
+ */
1262
+ #dropVoice() {
1263
+ this.#voiceDropped++;
1264
+ const now = performance.now();
1265
+ if (now - this.#voiceDropWarnedAt < VOICE_DROP_WARN_INTERVAL_MS)
1266
+ return;
1267
+ this.#voiceDropWarnedAt = now;
1268
+ // The count since the last warning, so each one says how bad it is now.
1269
+ this.#logger.warn("voice dropped: listeners are not keeping up", {
1270
+ dropped: this.#voiceDropped,
1271
+ });
1272
+ this.#voiceDropped = 0;
1273
+ }
1274
+ /** Queue a server event, through the event middleware. */
1275
+ #emitServerEvent(event) {
1276
+ this.#enqueue(() => this.#eventChain(event));
1277
+ }
1278
+ /**
1279
+ * Queue `disconnected`; the promise settles once it has been delivered, and
1280
+ * a connect() waits for it until then.
1281
+ */
1282
+ #announceDisconnected(cause, willReconnect) {
1283
+ const delivered = new Promise((resolve) => this.#enqueue(() => {
1284
+ try {
1285
+ this.#deliver("disconnected", { error: cause, willReconnect });
1286
+ }
1287
+ finally {
1288
+ resolve();
1289
+ }
1290
+ }));
1291
+ this.#disconnectedDelivered = delivered;
1292
+ void delivered.then(() => {
1293
+ if (this.#disconnectedDelivered === delivered)
1294
+ this.#disconnectedDelivered = undefined;
1295
+ });
1296
+ return delivered;
1297
+ }
1298
+ /** Queue a lifecycle event, which middleware does not see. */
1299
+ #emit(event, payload) {
1300
+ this.#enqueue(() => this.#deliver(event, payload));
1301
+ }
1302
+ #deliver(event, payload) {
1303
+ for (const subscription of this.#listeners.get(event) ?? []) {
1304
+ // Checked at delivery: a listener removed while its event was queued
1305
+ // does not get it.
1306
+ if (subscription.removed)
1307
+ continue;
1308
+ try {
1309
+ subscription.listener(payload);
1310
+ }
1311
+ catch (error) {
1312
+ // Rethrown on its own, as an uncaught exception, so it surfaces as one
1313
+ // from an EventEmitter listener would, and the listeners after it
1314
+ // still get the event.
1315
+ queueMicrotask(() => {
1316
+ throw error;
1317
+ });
1318
+ }
1319
+ }
1320
+ }
1321
+ /**
1322
+ * Run deliveries one at a time, in order, once the packet being handled is
1323
+ * done with. A listener that throws does so as an uncaught exception, as it
1324
+ * would from an EventEmitter, and the listeners and deliveries behind it
1325
+ * still run.
1326
+ */
1327
+ #enqueue(delivery) {
1328
+ this.#queue.push(delivery);
1329
+ if (this.#draining)
1330
+ return;
1331
+ this.#draining = true;
1332
+ setImmediate(this.#drain);
1333
+ }
1334
+ #drain = () => {
1335
+ try {
1336
+ while (this.#queue.length > 0)
1337
+ this.#queue.shift()();
1338
+ }
1339
+ finally {
1340
+ if (this.#queue.length > 0)
1341
+ setImmediate(this.#drain);
1342
+ else
1343
+ this.#draining = false;
1344
+ }
1345
+ };
1346
+ #handleConnectionClosed(err) {
1347
+ if (this.#status === ClientStatus.Disconnected)
1348
+ return;
1349
+ // Nothing in flight can be answered any more; failing it now, with the
1350
+ // reason, beats every caller timing out one by one.
1351
+ this.#cmdTrack.reset(new NotConnectedError(err ? { cause: err } : undefined));
1352
+ if (this.#status !== ClientStatus.Connected) {
1353
+ // The socket closed before the handshake finished, so this is a failed
1354
+ // connection attempt rather than a disconnect of a live session.
1355
+ this.#failConnection(err ?? new TeamspeakError("connection closed before the TeamSpeak handshake completed"));
1356
+ return;
1357
+ }
1358
+ this.#status = ClientStatus.Disconnected;
1359
+ // Never undefined for a drop: undefined means disconnect() only.
1360
+ const cause = err ?? new TeamspeakError("connection closed");
1361
+ this.#lastDrop = cause;
1362
+ this.#endSession(cause);
1363
+ // Announced first, then retried: a caller watching `disconnected` should
1364
+ // hear about the drop even when a reconnect is already on its way, because
1365
+ // a silent recovery hides an outage.
1366
+ void this.#announceDisconnected(cause, this.#willReconnect(cause, this.#loopAttempt + 1));
1367
+ this.#scheduleReconnect(cause).catch((error) => {
1368
+ this.#logger.error("reconnecting failed", { error: String(error) });
1369
+ });
1370
+ }
1371
+ /**
1372
+ * Whether the reconnect loop will make attempt number `attempt` after `err`.
1373
+ * `disconnected` reports it, and the loop acts on the same answer: the
1374
+ * caller's `shouldRetry` is asked once per failure, not once to announce it
1375
+ * and again to act on it.
1376
+ */
1377
+ #willReconnect(err, attempt) {
1378
+ const options = this.#reconnectOptions;
1379
+ if (options === undefined || this.#stopped)
1380
+ return false;
1381
+ const { maxAttempts } = resolveBackoffPolicy(options);
1382
+ if (maxAttempts !== 0 && attempt > maxAttempts)
1383
+ return false;
1384
+ const asked = this.#retryAnswer;
1385
+ if (asked?.err === err && asked.attempt === attempt)
1386
+ return asked.retry;
1387
+ let retry;
1388
+ let threw = false;
1389
+ try {
1390
+ retry = (options.shouldRetry ?? defaultShouldRetry)(err, attempt);
1391
+ }
1392
+ catch (error) {
1393
+ this.#logger.error("shouldRetry threw; not reconnecting", { error: String(error) });
1394
+ retry = false;
1395
+ threw = true;
1396
+ }
1397
+ this.#retryAnswer = { err, attempt, retry, threw };
1398
+ return retry;
1399
+ }
1400
+ /**
1401
+ * Retry a dropped connection according to the reconnect policy.
1402
+ *
1403
+ * Never runs after an explicit disconnect, and never more than one at a time:
1404
+ * two failures in quick succession would otherwise start competing loops, and
1405
+ * a loop shorter than the server's antiflood window bans the IP rather than
1406
+ * reconnecting it. A drop while the loop runs is the loop's to retry: it
1407
+ * ends only once its attempt is still connected when it resumes.
1408
+ */
1409
+ async #scheduleReconnect(err) {
1410
+ const options = this.#reconnectOptions;
1411
+ if (options === undefined || this.#stopped || this.#reconnecting)
1412
+ return;
1413
+ const policy = resolveBackoffPolicy(options);
1414
+ this.#reconnecting = true;
1415
+ const stop = new AbortController();
1416
+ this.#stopReconnecting = stop;
1417
+ // The attempts the loop has made, and why it stopped, for `reconnectStopped`.
1418
+ let made = 0;
1419
+ let stoppedBy;
1420
+ try {
1421
+ for (let attempt = 1; policy.maxAttempts === 0 || attempt <= policy.maxAttempts; attempt++) {
1422
+ if (this.#stopped) {
1423
+ stoppedBy = { cause: undefined };
1424
+ return;
1425
+ }
1426
+ if (!this.#willReconnect(err, attempt)) {
1427
+ if (!this.#retryAnswer?.threw) {
1428
+ this.#logger.info("not retrying", { attempt, reason: err.message });
1429
+ }
1430
+ stoppedBy = { cause: err };
1431
+ return;
1432
+ }
1433
+ const delay = backoffDelay(policy, attempt);
1434
+ this.#logger.info("reconnecting", { attempt, delayMs: delay });
1435
+ this.#callHook(this.#trace?.reconnectScheduled, () => ({
1436
+ attempt,
1437
+ delayMs: delay,
1438
+ cause: err,
1439
+ }));
1440
+ // A timer that keeps the process alive: an application that does
1441
+ // nothing but stay connected would otherwise exit during the wait.
1442
+ await sleep(delay, stop.signal);
1443
+ if (this.#stopped) {
1444
+ stoppedBy = { cause: undefined };
1445
+ return;
1446
+ }
1447
+ // Connected, or connecting, by hand during the wait: nothing is left to
1448
+ // retry, and an attempt now would only fail with AlreadyConnectedError.
1449
+ if (this.#status !== ClientStatus.Disconnected) {
1450
+ this.#logger.info("reconnect loop ended: connected by other means", { attempt });
1451
+ return;
1452
+ }
1453
+ try {
1454
+ made++;
1455
+ this.#loopAttempt = attempt;
1456
+ await this.#connect({ signal: AbortSignal.timeout(RECONNECT_ATTEMPT_TIMEOUT_MS) }, attempt, true);
1457
+ // Read afresh: the status may have changed while connect() resolved.
1458
+ if (this.status === ClientStatus.Connected) {
1459
+ this.#logger.info("reconnected", { attempt });
1460
+ return;
1461
+ }
1462
+ // The new session dropped before this loop resumed — initserver and
1463
+ // the server's goodbye in one datagram, say. That drop found this
1464
+ // loop running and left the retrying to it.
1465
+ err = this.#lastDrop ?? new TeamspeakError("connection closed");
1466
+ }
1467
+ catch (retryErr) {
1468
+ if (retryErr instanceof AlreadyConnectedError)
1469
+ return;
1470
+ err =
1471
+ retryErr instanceof Error
1472
+ ? retryErr
1473
+ : new TeamspeakError(String(retryErr), { cause: retryErr });
1474
+ }
1475
+ }
1476
+ this.#logger.warn("reconnect attempts exhausted", { attempts: policy.maxAttempts });
1477
+ stoppedBy = { cause: err };
1478
+ }
1479
+ finally {
1480
+ if (stoppedBy !== undefined) {
1481
+ const { cause } = stoppedBy;
1482
+ this.#callHook(this.#trace?.reconnectStopped, () => ({ attempts: made, cause }));
1483
+ }
1484
+ this.#reconnecting = false;
1485
+ this.#loopAttempt = 0;
1486
+ if (this.#stopReconnecting === stop)
1487
+ this.#stopReconnecting = undefined;
1488
+ }
1489
+ }
1490
+ /**
1491
+ * A connection attempt has failed for good: settle it with the cause, and
1492
+ * tear the connection down. Does nothing once the handshake has completed,
1493
+ * so it cannot end a live session.
1494
+ *
1495
+ * Without this, a handshake the server rejects (a wrong password, say, which
1496
+ * the server answers with an error instead of closing the socket) surfaces
1497
+ * only as the caller's own timeout, and the client stays in `Connecting`
1498
+ * forever without ever emitting `disconnected`.
1499
+ */
1500
+ #failConnection(error) {
1501
+ if (this.#status === ClientStatus.Connected)
1502
+ return;
1503
+ this.#attempt.reject(error);
1504
+ if (this.#status === ClientStatus.Disconnected)
1505
+ return;
1506
+ this.#status = ClientStatus.Disconnected;
1507
+ this.#handler.close();
1508
+ const cause = error instanceof Error ? error : new TeamspeakError(String(error), { cause: error });
1509
+ // Only an attempt of the reconnect loop can be followed by another; a
1510
+ // connect() that fails is the caller's to retry.
1511
+ void this.#announceDisconnected(cause, this.#reconnecting && this.#willReconnect(cause, this.#loopAttempt + 1));
1512
+ }
1513
+ }
1514
+ function kickedEvent(event) {
1515
+ return {
1516
+ reason: event.reason,
1517
+ reasonMessage: event.reasonMessage,
1518
+ invokerName: event.invokerName,
1519
+ invokerUID: event.invokerUID,
1520
+ invokerID: event.invokerID,
1521
+ };
1522
+ }
1523
+ //# sourceMappingURL=client.js.map