@anam-ai/js-sdk 3.4.1-oz-alpha.5 → 3.5.0-mic-test.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (424) hide show
  1. package/dist/main/AnamClient.d.ts.map +1 -0
  2. package/dist/main/AnamClient.js +424 -0
  3. package/dist/main/AnamClient.js.map +1 -0
  4. package/dist/{types → main}/index.d.ts +2 -1
  5. package/dist/main/index.d.ts.map +1 -0
  6. package/dist/main/index.js +50 -0
  7. package/dist/main/index.js.map +1 -0
  8. package/dist/{types → main}/lib/ClientError.d.ts +1 -0
  9. package/dist/main/lib/ClientError.d.ts.map +1 -0
  10. package/dist/main/lib/ClientError.js +34 -0
  11. package/dist/main/lib/ClientError.js.map +1 -0
  12. package/dist/main/lib/ClientMetrics.js +287 -0
  13. package/dist/main/lib/ClientMetrics.js.map +1 -0
  14. package/dist/{types → main}/lib/constants.d.ts +0 -1
  15. package/dist/{types → main}/lib/constants.d.ts.map +1 -1
  16. package/dist/main/lib/constants.js +14 -0
  17. package/dist/main/lib/constants.js.map +1 -0
  18. package/dist/main/lib/correlationId.js +13 -0
  19. package/dist/main/lib/correlationId.js.map +1 -0
  20. package/dist/main/lib/version.js +6 -0
  21. package/dist/main/lib/version.js.map +1 -0
  22. package/dist/{types → main}/modules/CoreApiRestClient.d.ts.map +1 -1
  23. package/dist/main/modules/CoreApiRestClient.js +127 -0
  24. package/dist/main/modules/CoreApiRestClient.js.map +1 -0
  25. package/dist/main/modules/EngineApiRestClient.js +42 -0
  26. package/dist/main/modules/EngineApiRestClient.js.map +1 -0
  27. package/dist/main/modules/InternalEventEmitter.js +28 -0
  28. package/dist/main/modules/InternalEventEmitter.js.map +1 -0
  29. package/dist/main/modules/MessageHistoryClient.js +70 -0
  30. package/dist/main/modules/MessageHistoryClient.js.map +1 -0
  31. package/dist/main/modules/PublicEventEmitter.js +37 -0
  32. package/dist/main/modules/PublicEventEmitter.js.map +1 -0
  33. package/dist/{types → main}/modules/SignallingClient.d.ts +14 -8
  34. package/dist/main/modules/SignallingClient.d.ts.map +1 -0
  35. package/dist/main/modules/SignallingClient.js +210 -0
  36. package/dist/main/modules/SignallingClient.js.map +1 -0
  37. package/dist/{types → main}/modules/StreamingClient.d.ts +8 -0
  38. package/dist/main/modules/StreamingClient.d.ts.map +1 -0
  39. package/dist/main/modules/StreamingClient.js +590 -0
  40. package/dist/main/modules/StreamingClient.js.map +1 -0
  41. package/dist/main/modules/index.js +18 -0
  42. package/dist/main/modules/index.js.map +1 -0
  43. package/dist/main/types/AnamClientOptions.js +3 -0
  44. package/dist/main/types/AnamClientOptions.js.map +1 -0
  45. package/dist/main/types/AnamInternalClientOptions.js +3 -0
  46. package/dist/main/types/AnamInternalClientOptions.js.map +1 -0
  47. package/dist/main/types/AnamPublicClientOptions.js +3 -0
  48. package/dist/main/types/AnamPublicClientOptions.js.map +1 -0
  49. package/dist/main/types/InputAudioState.d.ts +11 -0
  50. package/dist/main/types/InputAudioState.d.ts.map +1 -0
  51. package/dist/main/types/InputAudioState.js +11 -0
  52. package/dist/main/types/InputAudioState.js.map +1 -0
  53. package/dist/main/types/PersonaConfig.js +8 -0
  54. package/dist/main/types/PersonaConfig.js.map +1 -0
  55. package/dist/main/types/TalkMessageStream.js +93 -0
  56. package/dist/main/types/TalkMessageStream.js.map +1 -0
  57. package/dist/main/types/TalkMessageStreamState.js +11 -0
  58. package/dist/main/types/TalkMessageStreamState.js.map +1 -0
  59. package/dist/main/types/VoiceDetectionOptions.js +3 -0
  60. package/dist/main/types/VoiceDetectionOptions.js.map +1 -0
  61. package/dist/main/types/coreApi/CoreApiRestClientOptions.js +3 -0
  62. package/dist/main/types/coreApi/CoreApiRestClientOptions.js.map +1 -0
  63. package/dist/main/types/coreApi/StartSessionOptions.js +3 -0
  64. package/dist/main/types/coreApi/StartSessionOptions.js.map +1 -0
  65. package/dist/{types → main}/types/coreApi/StartSessionResponse.d.ts +2 -2
  66. package/dist/{types → main}/types/coreApi/StartSessionResponse.d.ts.map +1 -1
  67. package/dist/main/types/coreApi/StartSessionResponse.js +3 -0
  68. package/dist/main/types/coreApi/StartSessionResponse.js.map +1 -0
  69. package/dist/main/types/coreApi/index.js +3 -0
  70. package/dist/main/types/coreApi/index.js.map +1 -0
  71. package/dist/main/types/engineApi/EngineApiRestClientOptions.js +3 -0
  72. package/dist/main/types/engineApi/EngineApiRestClientOptions.js.map +1 -0
  73. package/dist/main/types/engineApi/index.js +2 -0
  74. package/dist/main/types/engineApi/index.js.map +1 -0
  75. package/dist/main/types/events/EventCallback.js +3 -0
  76. package/dist/main/types/events/EventCallback.js.map +1 -0
  77. package/dist/main/types/events/index.js +10 -0
  78. package/dist/main/types/events/index.js.map +1 -0
  79. package/dist/main/types/events/internal/InternalEvent.js +10 -0
  80. package/dist/main/types/events/internal/InternalEvent.js.map +1 -0
  81. package/dist/main/types/events/internal/InternalEventCallbacks.js +4 -0
  82. package/dist/main/types/events/internal/InternalEventCallbacks.js.map +1 -0
  83. package/dist/{types → main}/types/events/public/AnamEvent.d.ts +4 -1
  84. package/dist/{types → main}/types/events/public/AnamEvent.d.ts.map +1 -1
  85. package/dist/main/types/events/public/AnamEvent.js +21 -0
  86. package/dist/main/types/events/public/AnamEvent.js.map +1 -0
  87. package/dist/main/types/events/public/ConnectionClosedCodes.js +12 -0
  88. package/dist/main/types/events/public/ConnectionClosedCodes.js.map +1 -0
  89. package/dist/{types → main}/types/events/public/EventCallbacks.d.ts +3 -0
  90. package/dist/{types → main}/types/events/public/EventCallbacks.d.ts.map +1 -1
  91. package/dist/main/types/events/public/EventCallbacks.js +4 -0
  92. package/dist/main/types/events/public/EventCallbacks.js.map +1 -0
  93. package/dist/{types → main}/types/index.d.ts +1 -0
  94. package/dist/{types → main}/types/index.d.ts.map +1 -1
  95. package/dist/main/types/index.js +16 -0
  96. package/dist/main/types/index.js.map +1 -0
  97. package/dist/main/types/messageHistory/Message.js +3 -0
  98. package/dist/main/types/messageHistory/Message.js.map +1 -0
  99. package/dist/main/types/messageHistory/MessageRole.js +9 -0
  100. package/dist/main/types/messageHistory/MessageRole.js.map +1 -0
  101. package/dist/main/types/messageHistory/MessageStreamEvent.js +3 -0
  102. package/dist/main/types/messageHistory/MessageStreamEvent.js.map +1 -0
  103. package/dist/main/types/messageHistory/index.js +6 -0
  104. package/dist/main/types/messageHistory/index.js.map +1 -0
  105. package/dist/{types → main}/types/signalling/SignalMessage.d.ts +0 -2
  106. package/dist/{types → main}/types/signalling/SignalMessage.d.ts.map +1 -1
  107. package/dist/main/types/signalling/SignalMessage.js +16 -0
  108. package/dist/main/types/signalling/SignalMessage.js.map +1 -0
  109. package/dist/main/types/signalling/SignallingClientOptions.d.ts +12 -0
  110. package/dist/main/types/signalling/SignallingClientOptions.d.ts.map +1 -0
  111. package/dist/main/types/signalling/SignallingClientOptions.js +3 -0
  112. package/dist/main/types/signalling/SignallingClientOptions.js.map +1 -0
  113. package/dist/main/types/signalling/TalkMessageStreamPayload.js +3 -0
  114. package/dist/main/types/signalling/TalkMessageStreamPayload.js.map +1 -0
  115. package/dist/main/types/signalling/TalkStreamInterruptedSignalMessage.js +11 -0
  116. package/dist/main/types/signalling/TalkStreamInterruptedSignalMessage.js.map +1 -0
  117. package/dist/main/types/signalling/index.d.ts +4 -0
  118. package/dist/main/types/signalling/index.d.ts.map +1 -0
  119. package/dist/main/types/signalling/index.js +6 -0
  120. package/dist/main/types/signalling/index.js.map +1 -0
  121. package/dist/main/types/streaming/InputAudioOptions.js +3 -0
  122. package/dist/main/types/streaming/InputAudioOptions.js.map +1 -0
  123. package/dist/main/types/streaming/StreamingClientOptions.js +3 -0
  124. package/dist/main/types/streaming/StreamingClientOptions.js.map +1 -0
  125. package/dist/main/types/streaming/WebRtcTextMessageEvent.js +3 -0
  126. package/dist/main/types/streaming/WebRtcTextMessageEvent.js.map +1 -0
  127. package/dist/main/types/streaming/index.js +3 -0
  128. package/dist/main/types/streaming/index.js.map +1 -0
  129. package/dist/module/AnamClient.d.ts +61 -0
  130. package/dist/module/AnamClient.d.ts.map +1 -0
  131. package/dist/module/AnamClient.js +421 -0
  132. package/dist/module/AnamClient.js.map +1 -0
  133. package/dist/module/index.d.ts +26 -0
  134. package/dist/module/index.d.ts.map +1 -0
  135. package/dist/module/index.js +27 -0
  136. package/dist/module/index.js.map +1 -0
  137. package/dist/module/lib/ClientError.d.ts +19 -0
  138. package/dist/module/lib/ClientError.d.ts.map +1 -0
  139. package/dist/module/lib/ClientError.js +30 -0
  140. package/dist/module/lib/ClientError.js.map +1 -0
  141. package/dist/module/lib/ClientMetrics.d.ts +56 -0
  142. package/dist/module/lib/ClientMetrics.d.ts.map +1 -0
  143. package/dist/module/lib/ClientMetrics.js +280 -0
  144. package/dist/module/lib/ClientMetrics.js.map +1 -0
  145. package/dist/module/lib/constants.d.ts +10 -0
  146. package/dist/module/lib/constants.d.ts.map +1 -0
  147. package/dist/module/lib/constants.js +11 -0
  148. package/dist/module/lib/constants.js.map +1 -0
  149. package/dist/module/lib/correlationId.d.ts +2 -0
  150. package/dist/module/lib/correlationId.d.ts.map +1 -0
  151. package/dist/module/lib/correlationId.js +9 -0
  152. package/dist/module/lib/correlationId.js.map +1 -0
  153. package/dist/module/lib/version.d.ts +3 -0
  154. package/dist/module/lib/version.d.ts.map +1 -0
  155. package/dist/module/lib/version.js +3 -0
  156. package/dist/module/lib/version.js.map +1 -0
  157. package/dist/module/modules/CoreApiRestClient.d.ts +13 -0
  158. package/dist/module/modules/CoreApiRestClient.d.ts.map +1 -0
  159. package/dist/module/modules/CoreApiRestClient.js +123 -0
  160. package/dist/module/modules/CoreApiRestClient.js.map +1 -0
  161. package/dist/module/modules/EngineApiRestClient.d.ts +7 -0
  162. package/dist/module/modules/EngineApiRestClient.d.ts.map +1 -0
  163. package/dist/module/modules/EngineApiRestClient.js +38 -0
  164. package/dist/module/modules/EngineApiRestClient.js.map +1 -0
  165. package/dist/module/modules/InternalEventEmitter.d.ts +9 -0
  166. package/dist/module/modules/InternalEventEmitter.d.ts.map +1 -0
  167. package/dist/module/modules/InternalEventEmitter.js +24 -0
  168. package/dist/module/modules/InternalEventEmitter.js.map +1 -0
  169. package/dist/module/modules/MessageHistoryClient.d.ts +13 -0
  170. package/dist/module/modules/MessageHistoryClient.d.ts.map +1 -0
  171. package/dist/module/modules/MessageHistoryClient.js +66 -0
  172. package/dist/module/modules/MessageHistoryClient.js.map +1 -0
  173. package/dist/module/modules/PublicEventEmitter.d.ts +9 -0
  174. package/dist/module/modules/PublicEventEmitter.d.ts.map +1 -0
  175. package/dist/module/modules/PublicEventEmitter.js +33 -0
  176. package/dist/module/modules/PublicEventEmitter.js.map +1 -0
  177. package/dist/module/modules/SignallingClient.d.ts +31 -0
  178. package/dist/module/modules/SignallingClient.d.ts.map +1 -0
  179. package/dist/module/modules/SignallingClient.js +206 -0
  180. package/dist/module/modules/SignallingClient.js.map +1 -0
  181. package/dist/module/modules/StreamingClient.d.ts +72 -0
  182. package/dist/module/modules/StreamingClient.d.ts.map +1 -0
  183. package/dist/module/modules/StreamingClient.js +586 -0
  184. package/dist/module/modules/StreamingClient.js.map +1 -0
  185. package/dist/module/modules/index.d.ts +8 -0
  186. package/dist/module/modules/index.d.ts.map +1 -0
  187. package/dist/module/modules/index.js +8 -0
  188. package/dist/module/modules/index.js.map +1 -0
  189. package/dist/module/types/AnamClientOptions.d.ts +4 -0
  190. package/dist/module/types/AnamClientOptions.d.ts.map +1 -0
  191. package/dist/module/types/AnamClientOptions.js +2 -0
  192. package/dist/module/types/AnamClientOptions.js.map +1 -0
  193. package/dist/module/types/AnamInternalClientOptions.d.ts +4 -0
  194. package/dist/module/types/AnamInternalClientOptions.d.ts.map +1 -0
  195. package/dist/module/types/AnamInternalClientOptions.js +2 -0
  196. package/dist/module/types/AnamInternalClientOptions.js.map +1 -0
  197. package/dist/module/types/AnamPublicClientOptions.d.ts +13 -0
  198. package/dist/module/types/AnamPublicClientOptions.d.ts.map +1 -0
  199. package/dist/module/types/AnamPublicClientOptions.js +2 -0
  200. package/dist/module/types/AnamPublicClientOptions.js.map +1 -0
  201. package/dist/module/types/InputAudioState.d.ts +11 -0
  202. package/dist/module/types/InputAudioState.d.ts.map +1 -0
  203. package/dist/module/types/InputAudioState.js +8 -0
  204. package/dist/module/types/InputAudioState.js.map +1 -0
  205. package/dist/module/types/PersonaConfig.d.ts +13 -0
  206. package/dist/module/types/PersonaConfig.d.ts.map +1 -0
  207. package/dist/module/types/PersonaConfig.js +4 -0
  208. package/dist/module/types/PersonaConfig.js.map +1 -0
  209. package/dist/module/types/TalkMessageStream.d.ts +18 -0
  210. package/dist/module/types/TalkMessageStream.d.ts.map +1 -0
  211. package/dist/module/types/TalkMessageStream.js +89 -0
  212. package/dist/module/types/TalkMessageStream.js.map +1 -0
  213. package/dist/module/types/TalkMessageStreamState.d.ts +7 -0
  214. package/dist/module/types/TalkMessageStreamState.d.ts.map +1 -0
  215. package/dist/module/types/TalkMessageStreamState.js +8 -0
  216. package/dist/module/types/TalkMessageStreamState.js.map +1 -0
  217. package/dist/module/types/VoiceDetectionOptions.d.ts +4 -0
  218. package/dist/module/types/VoiceDetectionOptions.d.ts.map +1 -0
  219. package/dist/module/types/VoiceDetectionOptions.js +2 -0
  220. package/dist/module/types/VoiceDetectionOptions.js.map +1 -0
  221. package/dist/module/types/coreApi/CoreApiRestClientOptions.d.ts +5 -0
  222. package/dist/module/types/coreApi/CoreApiRestClientOptions.d.ts.map +1 -0
  223. package/dist/module/types/coreApi/CoreApiRestClientOptions.js +2 -0
  224. package/dist/module/types/coreApi/CoreApiRestClientOptions.js.map +1 -0
  225. package/dist/module/types/coreApi/StartSessionOptions.d.ts +5 -0
  226. package/dist/module/types/coreApi/StartSessionOptions.d.ts.map +1 -0
  227. package/dist/module/types/coreApi/StartSessionOptions.js +2 -0
  228. package/dist/module/types/coreApi/StartSessionOptions.js.map +1 -0
  229. package/dist/module/types/coreApi/StartSessionResponse.d.ts +13 -0
  230. package/dist/module/types/coreApi/StartSessionResponse.d.ts.map +1 -0
  231. package/dist/module/types/coreApi/StartSessionResponse.js +2 -0
  232. package/dist/module/types/coreApi/StartSessionResponse.js.map +1 -0
  233. package/dist/module/types/coreApi/index.d.ts +4 -0
  234. package/dist/module/types/coreApi/index.d.ts.map +1 -0
  235. package/dist/module/types/coreApi/index.js +2 -0
  236. package/dist/module/types/coreApi/index.js.map +1 -0
  237. package/dist/module/types/engineApi/EngineApiRestClientOptions.d.ts +4 -0
  238. package/dist/module/types/engineApi/EngineApiRestClientOptions.d.ts.map +1 -0
  239. package/dist/module/types/engineApi/EngineApiRestClientOptions.js +2 -0
  240. package/dist/module/types/engineApi/EngineApiRestClientOptions.js.map +1 -0
  241. package/dist/module/types/engineApi/index.d.ts +1 -0
  242. package/dist/module/types/engineApi/index.d.ts.map +1 -0
  243. package/dist/module/types/engineApi/index.js +2 -0
  244. package/dist/module/types/engineApi/index.js.map +1 -0
  245. package/dist/module/types/events/EventCallback.d.ts +2 -0
  246. package/dist/module/types/events/EventCallback.d.ts.map +1 -0
  247. package/dist/module/types/events/EventCallback.js +2 -0
  248. package/dist/module/types/events/EventCallback.js.map +1 -0
  249. package/dist/module/types/events/index.d.ts +7 -0
  250. package/dist/module/types/events/index.d.ts.map +1 -0
  251. package/dist/module/types/events/index.js +4 -0
  252. package/dist/module/types/events/index.js.map +1 -0
  253. package/dist/module/types/events/internal/InternalEvent.d.ts +6 -0
  254. package/dist/module/types/events/internal/InternalEvent.d.ts.map +1 -0
  255. package/dist/module/types/events/internal/InternalEvent.js +7 -0
  256. package/dist/module/types/events/internal/InternalEvent.js.map +1 -0
  257. package/dist/module/types/events/internal/InternalEventCallbacks.d.ts +7 -0
  258. package/dist/module/types/events/internal/InternalEventCallbacks.d.ts.map +1 -0
  259. package/dist/module/types/events/internal/InternalEventCallbacks.js +2 -0
  260. package/dist/module/types/events/internal/InternalEventCallbacks.js.map +1 -0
  261. package/dist/module/types/events/public/AnamEvent.d.ts +17 -0
  262. package/dist/module/types/events/public/AnamEvent.d.ts.map +1 -0
  263. package/dist/module/types/events/public/AnamEvent.js +18 -0
  264. package/dist/module/types/events/public/AnamEvent.js.map +1 -0
  265. package/dist/module/types/events/public/ConnectionClosedCodes.d.ts +8 -0
  266. package/dist/module/types/events/public/ConnectionClosedCodes.d.ts.map +1 -0
  267. package/dist/module/types/events/public/ConnectionClosedCodes.js +9 -0
  268. package/dist/module/types/events/public/ConnectionClosedCodes.js.map +1 -0
  269. package/dist/module/types/events/public/EventCallbacks.d.ts +19 -0
  270. package/dist/module/types/events/public/EventCallbacks.d.ts.map +1 -0
  271. package/dist/module/types/events/public/EventCallbacks.js +2 -0
  272. package/dist/module/types/events/public/EventCallbacks.js.map +1 -0
  273. package/dist/module/types/index.d.ts +15 -0
  274. package/dist/module/types/index.d.ts.map +1 -0
  275. package/dist/module/types/index.js +7 -0
  276. package/dist/module/types/index.js.map +1 -0
  277. package/dist/module/types/messageHistory/Message.d.ts +8 -0
  278. package/dist/module/types/messageHistory/Message.d.ts.map +1 -0
  279. package/dist/module/types/messageHistory/Message.js +2 -0
  280. package/dist/module/types/messageHistory/Message.js.map +1 -0
  281. package/dist/module/types/messageHistory/MessageRole.d.ts +5 -0
  282. package/dist/module/types/messageHistory/MessageRole.d.ts.map +1 -0
  283. package/dist/module/types/messageHistory/MessageRole.js +6 -0
  284. package/dist/module/types/messageHistory/MessageRole.js.map +1 -0
  285. package/dist/module/types/messageHistory/MessageStreamEvent.d.ts +9 -0
  286. package/dist/module/types/messageHistory/MessageStreamEvent.d.ts.map +1 -0
  287. package/dist/module/types/messageHistory/MessageStreamEvent.js +2 -0
  288. package/dist/module/types/messageHistory/MessageStreamEvent.js.map +1 -0
  289. package/dist/module/types/messageHistory/index.d.ts +4 -0
  290. package/dist/module/types/messageHistory/index.d.ts.map +1 -0
  291. package/dist/module/types/messageHistory/index.js +2 -0
  292. package/dist/module/types/messageHistory/index.js.map +1 -0
  293. package/dist/module/types/signalling/SignalMessage.d.ts +17 -0
  294. package/dist/module/types/signalling/SignalMessage.d.ts.map +1 -0
  295. package/dist/module/types/signalling/SignalMessage.js +13 -0
  296. package/dist/module/types/signalling/SignalMessage.js.map +1 -0
  297. package/dist/module/types/signalling/SignallingClientOptions.d.ts +12 -0
  298. package/dist/module/types/signalling/SignallingClientOptions.d.ts.map +1 -0
  299. package/dist/module/types/signalling/SignallingClientOptions.js +2 -0
  300. package/dist/module/types/signalling/SignallingClientOptions.js.map +1 -0
  301. package/dist/module/types/signalling/TalkMessageStreamPayload.d.ts +7 -0
  302. package/dist/module/types/signalling/TalkMessageStreamPayload.d.ts.map +1 -0
  303. package/dist/module/types/signalling/TalkMessageStreamPayload.js +2 -0
  304. package/dist/module/types/signalling/TalkMessageStreamPayload.js.map +1 -0
  305. package/dist/module/types/signalling/TalkStreamInterruptedSignalMessage.d.ts +5 -0
  306. package/dist/module/types/signalling/TalkStreamInterruptedSignalMessage.d.ts.map +1 -0
  307. package/dist/module/types/signalling/TalkStreamInterruptedSignalMessage.js +7 -0
  308. package/dist/module/types/signalling/TalkStreamInterruptedSignalMessage.js.map +1 -0
  309. package/dist/module/types/signalling/index.d.ts +4 -0
  310. package/dist/module/types/signalling/index.d.ts.map +1 -0
  311. package/dist/module/types/signalling/index.js +2 -0
  312. package/dist/module/types/signalling/index.js.map +1 -0
  313. package/dist/module/types/streaming/InputAudioOptions.d.ts +8 -0
  314. package/dist/module/types/streaming/InputAudioOptions.d.ts.map +1 -0
  315. package/dist/module/types/streaming/InputAudioOptions.js +2 -0
  316. package/dist/module/types/streaming/InputAudioOptions.js.map +1 -0
  317. package/dist/module/types/streaming/StreamingClientOptions.d.ts +14 -0
  318. package/dist/module/types/streaming/StreamingClientOptions.d.ts.map +1 -0
  319. package/dist/module/types/streaming/StreamingClientOptions.js +2 -0
  320. package/dist/module/types/streaming/StreamingClientOptions.js.map +1 -0
  321. package/dist/module/types/streaming/WebRtcTextMessageEvent.d.ts +9 -0
  322. package/dist/module/types/streaming/WebRtcTextMessageEvent.d.ts.map +1 -0
  323. package/dist/module/types/streaming/WebRtcTextMessageEvent.js +2 -0
  324. package/dist/module/types/streaming/WebRtcTextMessageEvent.js.map +1 -0
  325. package/dist/module/types/streaming/index.d.ts +4 -0
  326. package/dist/module/types/streaming/index.d.ts.map +1 -0
  327. package/dist/module/types/streaming/index.js +2 -0
  328. package/dist/module/types/streaming/index.js.map +1 -0
  329. package/dist/umd/anam.js +2 -0
  330. package/dist/umd/anam.js.LICENSE.txt +8 -0
  331. package/package.json +15 -29
  332. package/dist/index.cjs.js +0 -31
  333. package/dist/index.cjs.js.map +0 -7
  334. package/dist/index.esm.js +0 -31
  335. package/dist/index.esm.js.map +0 -7
  336. package/dist/index.js +0 -16
  337. package/dist/index.umd.js +0 -31
  338. package/dist/index.umd.js.map +0 -7
  339. package/dist/types/AnamClient.d.ts.map +0 -1
  340. package/dist/types/index.d.ts.map +0 -1
  341. package/dist/types/lib/ClientError.d.ts.map +0 -1
  342. package/dist/types/modules/SignallingClient.d.ts.map +0 -1
  343. package/dist/types/modules/StreamingClient.d.ts.map +0 -1
  344. package/dist/types/types/InputAudioState.d.ts +0 -4
  345. package/dist/types/types/InputAudioState.d.ts.map +0 -1
  346. package/dist/types/types/signalling/SignallingClientOptions.d.ts +0 -5
  347. package/dist/types/types/signalling/SignallingClientOptions.d.ts.map +0 -1
  348. package/dist/types/types/signalling/index.d.ts +0 -4
  349. package/dist/types/types/signalling/index.d.ts.map +0 -1
  350. package/src/shims/browser-polyfills.js +0 -11
  351. package/src/shims/empty.js +0 -3
  352. package/src/shims/keyv-mock.js +0 -13
  353. /package/dist/{types → main}/AnamClient.d.ts +0 -0
  354. /package/dist/{types → main}/lib/ClientMetrics.d.ts +0 -0
  355. /package/dist/{types → main}/lib/ClientMetrics.d.ts.map +0 -0
  356. /package/dist/{types → main}/lib/correlationId.d.ts +0 -0
  357. /package/dist/{types → main}/lib/correlationId.d.ts.map +0 -0
  358. /package/dist/{types → main}/lib/version.d.ts +0 -0
  359. /package/dist/{types → main}/lib/version.d.ts.map +0 -0
  360. /package/dist/{types → main}/modules/CoreApiRestClient.d.ts +0 -0
  361. /package/dist/{types → main}/modules/EngineApiRestClient.d.ts +0 -0
  362. /package/dist/{types → main}/modules/EngineApiRestClient.d.ts.map +0 -0
  363. /package/dist/{types → main}/modules/InternalEventEmitter.d.ts +0 -0
  364. /package/dist/{types → main}/modules/InternalEventEmitter.d.ts.map +0 -0
  365. /package/dist/{types → main}/modules/MessageHistoryClient.d.ts +0 -0
  366. /package/dist/{types → main}/modules/MessageHistoryClient.d.ts.map +0 -0
  367. /package/dist/{types → main}/modules/PublicEventEmitter.d.ts +0 -0
  368. /package/dist/{types → main}/modules/PublicEventEmitter.d.ts.map +0 -0
  369. /package/dist/{types → main}/modules/index.d.ts +0 -0
  370. /package/dist/{types → main}/modules/index.d.ts.map +0 -0
  371. /package/dist/{types → main}/types/AnamClientOptions.d.ts +0 -0
  372. /package/dist/{types → main}/types/AnamClientOptions.d.ts.map +0 -0
  373. /package/dist/{types → main}/types/AnamInternalClientOptions.d.ts +0 -0
  374. /package/dist/{types → main}/types/AnamInternalClientOptions.d.ts.map +0 -0
  375. /package/dist/{types → main}/types/AnamPublicClientOptions.d.ts +0 -0
  376. /package/dist/{types → main}/types/AnamPublicClientOptions.d.ts.map +0 -0
  377. /package/dist/{types → main}/types/PersonaConfig.d.ts +0 -0
  378. /package/dist/{types → main}/types/PersonaConfig.d.ts.map +0 -0
  379. /package/dist/{types → main}/types/TalkMessageStream.d.ts +0 -0
  380. /package/dist/{types → main}/types/TalkMessageStream.d.ts.map +0 -0
  381. /package/dist/{types → main}/types/TalkMessageStreamState.d.ts +0 -0
  382. /package/dist/{types → main}/types/TalkMessageStreamState.d.ts.map +0 -0
  383. /package/dist/{types → main}/types/VoiceDetectionOptions.d.ts +0 -0
  384. /package/dist/{types → main}/types/VoiceDetectionOptions.d.ts.map +0 -0
  385. /package/dist/{types → main}/types/coreApi/CoreApiRestClientOptions.d.ts +0 -0
  386. /package/dist/{types → main}/types/coreApi/CoreApiRestClientOptions.d.ts.map +0 -0
  387. /package/dist/{types → main}/types/coreApi/StartSessionOptions.d.ts +0 -0
  388. /package/dist/{types → main}/types/coreApi/StartSessionOptions.d.ts.map +0 -0
  389. /package/dist/{types → main}/types/coreApi/index.d.ts +0 -0
  390. /package/dist/{types → main}/types/coreApi/index.d.ts.map +0 -0
  391. /package/dist/{types → main}/types/engineApi/EngineApiRestClientOptions.d.ts +0 -0
  392. /package/dist/{types → main}/types/engineApi/EngineApiRestClientOptions.d.ts.map +0 -0
  393. /package/dist/{types → main}/types/engineApi/index.d.ts +0 -0
  394. /package/dist/{types → main}/types/engineApi/index.d.ts.map +0 -0
  395. /package/dist/{types → main}/types/events/EventCallback.d.ts +0 -0
  396. /package/dist/{types → main}/types/events/EventCallback.d.ts.map +0 -0
  397. /package/dist/{types → main}/types/events/index.d.ts +0 -0
  398. /package/dist/{types → main}/types/events/index.d.ts.map +0 -0
  399. /package/dist/{types → main}/types/events/internal/InternalEvent.d.ts +0 -0
  400. /package/dist/{types → main}/types/events/internal/InternalEvent.d.ts.map +0 -0
  401. /package/dist/{types → main}/types/events/internal/InternalEventCallbacks.d.ts +0 -0
  402. /package/dist/{types → main}/types/events/internal/InternalEventCallbacks.d.ts.map +0 -0
  403. /package/dist/{types → main}/types/events/public/ConnectionClosedCodes.d.ts +0 -0
  404. /package/dist/{types → main}/types/events/public/ConnectionClosedCodes.d.ts.map +0 -0
  405. /package/dist/{types → main}/types/messageHistory/Message.d.ts +0 -0
  406. /package/dist/{types → main}/types/messageHistory/Message.d.ts.map +0 -0
  407. /package/dist/{types → main}/types/messageHistory/MessageRole.d.ts +0 -0
  408. /package/dist/{types → main}/types/messageHistory/MessageRole.d.ts.map +0 -0
  409. /package/dist/{types → main}/types/messageHistory/MessageStreamEvent.d.ts +0 -0
  410. /package/dist/{types → main}/types/messageHistory/MessageStreamEvent.d.ts.map +0 -0
  411. /package/dist/{types → main}/types/messageHistory/index.d.ts +0 -0
  412. /package/dist/{types → main}/types/messageHistory/index.d.ts.map +0 -0
  413. /package/dist/{types → main}/types/signalling/TalkMessageStreamPayload.d.ts +0 -0
  414. /package/dist/{types → main}/types/signalling/TalkMessageStreamPayload.d.ts.map +0 -0
  415. /package/dist/{types → main}/types/signalling/TalkStreamInterruptedSignalMessage.d.ts +0 -0
  416. /package/dist/{types → main}/types/signalling/TalkStreamInterruptedSignalMessage.d.ts.map +0 -0
  417. /package/dist/{types → main}/types/streaming/InputAudioOptions.d.ts +0 -0
  418. /package/dist/{types → main}/types/streaming/InputAudioOptions.d.ts.map +0 -0
  419. /package/dist/{types → main}/types/streaming/StreamingClientOptions.d.ts +0 -0
  420. /package/dist/{types → main}/types/streaming/StreamingClientOptions.d.ts.map +0 -0
  421. /package/dist/{types → main}/types/streaming/WebRtcTextMessageEvent.d.ts +0 -0
  422. /package/dist/{types → main}/types/streaming/WebRtcTextMessageEvent.d.ts.map +0 -0
  423. /package/dist/{types → main}/types/streaming/index.d.ts +0 -0
  424. /package/dist/{types → main}/types/streaming/index.d.ts.map +0 -0
package/dist/index.esm.js DELETED
@@ -1,31 +0,0 @@
1
- var Oc=Object.create;var zs=Object.defineProperty;var Tc=Object.getOwnPropertyDescriptor;var _c=Object.getOwnPropertyNames;var Mc=Object.getPrototypeOf,kc=Object.prototype.hasOwnProperty;var Pc=(l,i)=>()=>(l&&(i=l(l=0)),i);var jt=(l,i)=>()=>(i||l((i={exports:{}}).exports,i),i.exports);var Nc=(l,i,r,h)=>{if(i&&typeof i=="object"||typeof i=="function")for(let d of _c(i))!kc.call(l,d)&&d!==r&&zs(l,d,{get:()=>i[d],enumerable:!(h=Tc(i,d))||h.enumerable});return l};var Js=(l,i,r)=>(r=l!=null?Oc(Mc(l)):{},Nc(i||!l||!l.__esModule?zs(r,"default",{value:l,enumerable:!0}):r,l));var M=Pc(()=>{"use strict";typeof globalThis>"u"&&typeof window<"u"&&(window.globalThis=window);typeof globalThis>"u"&&typeof window<"u"&&(window.global=window);typeof self>"u"&&typeof window<"u"&&(window.self=window)});var Xs=jt(Wt=>{"use strict";M();Wt.byteLength=xc;Wt.toByteArray=Bc;Wt.fromByteArray=Gc;var pe=[],ae=[],Lc=typeof Uint8Array<"u"?Uint8Array:Array,Bn="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(Te=0,Qs=Bn.length;Te<Qs;++Te)pe[Te]=Bn[Te],ae[Bn.charCodeAt(Te)]=Te;var Te,Qs;ae[45]=62;ae[95]=63;function Ys(l){var i=l.length;if(i%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=l.indexOf("=");r===-1&&(r=i);var h=r===i?0:4-r%4;return[r,h]}function xc(l){var i=Ys(l),r=i[0],h=i[1];return(r+h)*3/4-h}function Uc(l,i,r){return(i+r)*3/4-r}function Bc(l){var i,r=Ys(l),h=r[0],d=r[1],p=new Lc(Uc(l,h,d)),m=0,I=d>0?h-4:h,y;for(y=0;y<I;y+=4)i=ae[l.charCodeAt(y)]<<18|ae[l.charCodeAt(y+1)]<<12|ae[l.charCodeAt(y+2)]<<6|ae[l.charCodeAt(y+3)],p[m++]=i>>16&255,p[m++]=i>>8&255,p[m++]=i&255;return d===2&&(i=ae[l.charCodeAt(y)]<<2|ae[l.charCodeAt(y+1)]>>4,p[m++]=i&255),d===1&&(i=ae[l.charCodeAt(y)]<<10|ae[l.charCodeAt(y+1)]<<4|ae[l.charCodeAt(y+2)]>>2,p[m++]=i>>8&255,p[m++]=i&255),p}function Dc(l){return pe[l>>18&63]+pe[l>>12&63]+pe[l>>6&63]+pe[l&63]}function Fc(l,i,r){for(var h,d=[],p=i;p<r;p+=3)h=(l[p]<<16&16711680)+(l[p+1]<<8&65280)+(l[p+2]&255),d.push(Dc(h));return d.join("")}function Gc(l){for(var i,r=l.length,h=r%3,d=[],p=16383,m=0,I=r-h;m<I;m+=p)d.push(Fc(l,m,m+p>I?I:m+p));return h===1?(i=l[r-1],d.push(pe[i>>2]+pe[i<<4&63]+"==")):h===2&&(i=(l[r-2]<<8)+l[r-1],d.push(pe[i>>10]+pe[i>>4&63]+pe[i<<2&63]+"=")),d.join("")}});var Zs=jt(Dn=>{M();Dn.read=function(l,i,r,h,d){var p,m,I=d*8-h-1,y=(1<<I)-1,k=y>>1,U=-7,O=r?d-1:0,H=r?-1:1,re=l[i+O];for(O+=H,p=re&(1<<-U)-1,re>>=-U,U+=I;U>0;p=p*256+l[i+O],O+=H,U-=8);for(m=p&(1<<-U)-1,p>>=-U,U+=h;U>0;m=m*256+l[i+O],O+=H,U-=8);if(p===0)p=1-k;else{if(p===y)return m?NaN:(re?-1:1)*(1/0);m=m+Math.pow(2,h),p=p-k}return(re?-1:1)*m*Math.pow(2,p-h)};Dn.write=function(l,i,r,h,d,p){var m,I,y,k=p*8-d-1,U=(1<<k)-1,O=U>>1,H=d===23?Math.pow(2,-24)-Math.pow(2,-77):0,re=h?0:p-1,Pe=h?1:-1,Zt=i<0||i===0&&1/i<0?1:0;for(i=Math.abs(i),isNaN(i)||i===1/0?(I=isNaN(i)?1:0,m=U):(m=Math.floor(Math.log(i)/Math.LN2),i*(y=Math.pow(2,-m))<1&&(m--,y*=2),m+O>=1?i+=H/y:i+=H*Math.pow(2,1-O),i*y>=2&&(m++,y/=2),m+O>=U?(I=0,m=U):m+O>=1?(I=(i*y-1)*Math.pow(2,d),m=m+O):(I=i*Math.pow(2,O-1)*Math.pow(2,d),m=0));d>=8;l[r+re]=I&255,re+=Pe,I/=256,d-=8);for(m=m<<d|I,k+=d;k>0;l[r+re]=m&255,re+=Pe,m/=256,k-=8);l[r+re-Pe]|=Zt*128}});var mr=jt(Je=>{"use strict";M();var Fn=Xs(),$e=Zs(),er=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;Je.Buffer=S;Je.SlowBuffer=Kc;Je.INSPECT_MAX_BYTES=50;var Kt=2147483647;Je.kMaxLength=Kt;S.TYPED_ARRAY_SUPPORT=qc();!S.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function qc(){try{let l=new Uint8Array(1),i={foo:function(){return 42}};return Object.setPrototypeOf(i,Uint8Array.prototype),Object.setPrototypeOf(l,i),l.foo()===42}catch{return!1}}Object.defineProperty(S.prototype,"parent",{enumerable:!0,get:function(){if(S.isBuffer(this))return this.buffer}});Object.defineProperty(S.prototype,"offset",{enumerable:!0,get:function(){if(S.isBuffer(this))return this.byteOffset}});function Se(l){if(l>Kt)throw new RangeError('The value "'+l+'" is invalid for option "size"');let i=new Uint8Array(l);return Object.setPrototypeOf(i,S.prototype),i}function S(l,i,r){if(typeof l=="number"){if(typeof i=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return Vn(l)}return sr(l,i,r)}S.poolSize=8192;function sr(l,i,r){if(typeof l=="string")return Vc(l,i);if(ArrayBuffer.isView(l))return jc(l);if(l==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof l);if(ge(l,ArrayBuffer)||l&&ge(l.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(ge(l,SharedArrayBuffer)||l&&ge(l.buffer,SharedArrayBuffer)))return qn(l,i,r);if(typeof l=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');let h=l.valueOf&&l.valueOf();if(h!=null&&h!==l)return S.from(h,i,r);let d=Wc(l);if(d)return d;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof l[Symbol.toPrimitive]=="function")return S.from(l[Symbol.toPrimitive]("string"),i,r);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof l)}S.from=function(l,i,r){return sr(l,i,r)};Object.setPrototypeOf(S.prototype,Uint8Array.prototype);Object.setPrototypeOf(S,Uint8Array);function rr(l){if(typeof l!="number")throw new TypeError('"size" argument must be of type number');if(l<0)throw new RangeError('The value "'+l+'" is invalid for option "size"')}function Hc(l,i,r){return rr(l),l<=0?Se(l):i!==void 0?typeof r=="string"?Se(l).fill(i,r):Se(l).fill(i):Se(l)}S.alloc=function(l,i,r){return Hc(l,i,r)};function Vn(l){return rr(l),Se(l<0?0:jn(l)|0)}S.allocUnsafe=function(l){return Vn(l)};S.allocUnsafeSlow=function(l){return Vn(l)};function Vc(l,i){if((typeof i!="string"||i==="")&&(i="utf8"),!S.isEncoding(i))throw new TypeError("Unknown encoding: "+i);let r=or(l,i)|0,h=Se(r),d=h.write(l,i);return d!==r&&(h=h.slice(0,d)),h}function Gn(l){let i=l.length<0?0:jn(l.length)|0,r=Se(i);for(let h=0;h<i;h+=1)r[h]=l[h]&255;return r}function jc(l){if(ge(l,Uint8Array)){let i=new Uint8Array(l);return qn(i.buffer,i.byteOffset,i.byteLength)}return Gn(l)}function qn(l,i,r){if(i<0||l.byteLength<i)throw new RangeError('"offset" is outside of buffer bounds');if(l.byteLength<i+(r||0))throw new RangeError('"length" is outside of buffer bounds');let h;return i===void 0&&r===void 0?h=new Uint8Array(l):r===void 0?h=new Uint8Array(l,i):h=new Uint8Array(l,i,r),Object.setPrototypeOf(h,S.prototype),h}function Wc(l){if(S.isBuffer(l)){let i=jn(l.length)|0,r=Se(i);return r.length===0||l.copy(r,0,0,i),r}if(l.length!==void 0)return typeof l.length!="number"||Kn(l.length)?Se(0):Gn(l);if(l.type==="Buffer"&&Array.isArray(l.data))return Gn(l.data)}function jn(l){if(l>=Kt)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+Kt.toString(16)+" bytes");return l|0}function Kc(l){return+l!=l&&(l=0),S.alloc(+l)}S.isBuffer=function(i){return i!=null&&i._isBuffer===!0&&i!==S.prototype};S.compare=function(i,r){if(ge(i,Uint8Array)&&(i=S.from(i,i.offset,i.byteLength)),ge(r,Uint8Array)&&(r=S.from(r,r.offset,r.byteLength)),!S.isBuffer(i)||!S.isBuffer(r))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(i===r)return 0;let h=i.length,d=r.length;for(let p=0,m=Math.min(h,d);p<m;++p)if(i[p]!==r[p]){h=i[p],d=r[p];break}return h<d?-1:d<h?1:0};S.isEncoding=function(i){switch(String(i).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}};S.concat=function(i,r){if(!Array.isArray(i))throw new TypeError('"list" argument must be an Array of Buffers');if(i.length===0)return S.alloc(0);let h;if(r===void 0)for(r=0,h=0;h<i.length;++h)r+=i[h].length;let d=S.allocUnsafe(r),p=0;for(h=0;h<i.length;++h){let m=i[h];if(ge(m,Uint8Array))p+m.length>d.length?(S.isBuffer(m)||(m=S.from(m)),m.copy(d,p)):Uint8Array.prototype.set.call(d,m,p);else if(S.isBuffer(m))m.copy(d,p);else throw new TypeError('"list" argument must be an Array of Buffers');p+=m.length}return d};function or(l,i){if(S.isBuffer(l))return l.length;if(ArrayBuffer.isView(l)||ge(l,ArrayBuffer))return l.byteLength;if(typeof l!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof l);let r=l.length,h=arguments.length>2&&arguments[2]===!0;if(!h&&r===0)return 0;let d=!1;for(;;)switch(i){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return Hn(l).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return r*2;case"hex":return r>>>1;case"base64":return gr(l).length;default:if(d)return h?-1:Hn(l).length;i=(""+i).toLowerCase(),d=!0}}S.byteLength=or;function $c(l,i,r){let h=!1;if((i===void 0||i<0)&&(i=0),i>this.length||((r===void 0||r>this.length)&&(r=this.length),r<=0)||(r>>>=0,i>>>=0,r<=i))return"";for(l||(l="utf8");;)switch(l){case"hex":return il(this,i,r);case"utf8":case"utf-8":return cr(this,i,r);case"ascii":return tl(this,i,r);case"latin1":case"binary":return nl(this,i,r);case"base64":return Zc(this,i,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return sl(this,i,r);default:if(h)throw new TypeError("Unknown encoding: "+l);l=(l+"").toLowerCase(),h=!0}}S.prototype._isBuffer=!0;function _e(l,i,r){let h=l[i];l[i]=l[r],l[r]=h}S.prototype.swap16=function(){let i=this.length;if(i%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let r=0;r<i;r+=2)_e(this,r,r+1);return this};S.prototype.swap32=function(){let i=this.length;if(i%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let r=0;r<i;r+=4)_e(this,r,r+3),_e(this,r+1,r+2);return this};S.prototype.swap64=function(){let i=this.length;if(i%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let r=0;r<i;r+=8)_e(this,r,r+7),_e(this,r+1,r+6),_e(this,r+2,r+5),_e(this,r+3,r+4);return this};S.prototype.toString=function(){let i=this.length;return i===0?"":arguments.length===0?cr(this,0,i):$c.apply(this,arguments)};S.prototype.toLocaleString=S.prototype.toString;S.prototype.equals=function(i){if(!S.isBuffer(i))throw new TypeError("Argument must be a Buffer");return this===i?!0:S.compare(this,i)===0};S.prototype.inspect=function(){let i="",r=Je.INSPECT_MAX_BYTES;return i=this.toString("hex",0,r).replace(/(.{2})/g,"$1 ").trim(),this.length>r&&(i+=" ... "),"<Buffer "+i+">"};er&&(S.prototype[er]=S.prototype.inspect);S.prototype.compare=function(i,r,h,d,p){if(ge(i,Uint8Array)&&(i=S.from(i,i.offset,i.byteLength)),!S.isBuffer(i))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof i);if(r===void 0&&(r=0),h===void 0&&(h=i?i.length:0),d===void 0&&(d=0),p===void 0&&(p=this.length),r<0||h>i.length||d<0||p>this.length)throw new RangeError("out of range index");if(d>=p&&r>=h)return 0;if(d>=p)return-1;if(r>=h)return 1;if(r>>>=0,h>>>=0,d>>>=0,p>>>=0,this===i)return 0;let m=p-d,I=h-r,y=Math.min(m,I),k=this.slice(d,p),U=i.slice(r,h);for(let O=0;O<y;++O)if(k[O]!==U[O]){m=k[O],I=U[O];break}return m<I?-1:I<m?1:0};function ar(l,i,r,h,d){if(l.length===0)return-1;if(typeof r=="string"?(h=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),r=+r,Kn(r)&&(r=d?0:l.length-1),r<0&&(r=l.length+r),r>=l.length){if(d)return-1;r=l.length-1}else if(r<0)if(d)r=0;else return-1;if(typeof i=="string"&&(i=S.from(i,h)),S.isBuffer(i))return i.length===0?-1:tr(l,i,r,h,d);if(typeof i=="number")return i=i&255,typeof Uint8Array.prototype.indexOf=="function"?d?Uint8Array.prototype.indexOf.call(l,i,r):Uint8Array.prototype.lastIndexOf.call(l,i,r):tr(l,[i],r,h,d);throw new TypeError("val must be string, number or Buffer")}function tr(l,i,r,h,d){let p=1,m=l.length,I=i.length;if(h!==void 0&&(h=String(h).toLowerCase(),h==="ucs2"||h==="ucs-2"||h==="utf16le"||h==="utf-16le")){if(l.length<2||i.length<2)return-1;p=2,m/=2,I/=2,r/=2}function y(U,O){return p===1?U[O]:U.readUInt16BE(O*p)}let k;if(d){let U=-1;for(k=r;k<m;k++)if(y(l,k)===y(i,U===-1?0:k-U)){if(U===-1&&(U=k),k-U+1===I)return U*p}else U!==-1&&(k-=k-U),U=-1}else for(r+I>m&&(r=m-I),k=r;k>=0;k--){let U=!0;for(let O=0;O<I;O++)if(y(l,k+O)!==y(i,O)){U=!1;break}if(U)return k}return-1}S.prototype.includes=function(i,r,h){return this.indexOf(i,r,h)!==-1};S.prototype.indexOf=function(i,r,h){return ar(this,i,r,h,!0)};S.prototype.lastIndexOf=function(i,r,h){return ar(this,i,r,h,!1)};function zc(l,i,r,h){r=Number(r)||0;let d=l.length-r;h?(h=Number(h),h>d&&(h=d)):h=d;let p=i.length;h>p/2&&(h=p/2);let m;for(m=0;m<h;++m){let I=parseInt(i.substr(m*2,2),16);if(Kn(I))return m;l[r+m]=I}return m}function Jc(l,i,r,h){return $t(Hn(i,l.length-r),l,r,h)}function Qc(l,i,r,h){return $t(cl(i),l,r,h)}function Yc(l,i,r,h){return $t(gr(i),l,r,h)}function Xc(l,i,r,h){return $t(ll(i,l.length-r),l,r,h)}S.prototype.write=function(i,r,h,d){if(r===void 0)d="utf8",h=this.length,r=0;else if(h===void 0&&typeof r=="string")d=r,h=this.length,r=0;else if(isFinite(r))r=r>>>0,isFinite(h)?(h=h>>>0,d===void 0&&(d="utf8")):(d=h,h=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");let p=this.length-r;if((h===void 0||h>p)&&(h=p),i.length>0&&(h<0||r<0)||r>this.length)throw new RangeError("Attempt to write outside buffer bounds");d||(d="utf8");let m=!1;for(;;)switch(d){case"hex":return zc(this,i,r,h);case"utf8":case"utf-8":return Jc(this,i,r,h);case"ascii":case"latin1":case"binary":return Qc(this,i,r,h);case"base64":return Yc(this,i,r,h);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Xc(this,i,r,h);default:if(m)throw new TypeError("Unknown encoding: "+d);d=(""+d).toLowerCase(),m=!0}};S.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function Zc(l,i,r){return i===0&&r===l.length?Fn.fromByteArray(l):Fn.fromByteArray(l.slice(i,r))}function cr(l,i,r){r=Math.min(l.length,r);let h=[],d=i;for(;d<r;){let p=l[d],m=null,I=p>239?4:p>223?3:p>191?2:1;if(d+I<=r){let y,k,U,O;switch(I){case 1:p<128&&(m=p);break;case 2:y=l[d+1],(y&192)===128&&(O=(p&31)<<6|y&63,O>127&&(m=O));break;case 3:y=l[d+1],k=l[d+2],(y&192)===128&&(k&192)===128&&(O=(p&15)<<12|(y&63)<<6|k&63,O>2047&&(O<55296||O>57343)&&(m=O));break;case 4:y=l[d+1],k=l[d+2],U=l[d+3],(y&192)===128&&(k&192)===128&&(U&192)===128&&(O=(p&15)<<18|(y&63)<<12|(k&63)<<6|U&63,O>65535&&O<1114112&&(m=O))}}m===null?(m=65533,I=1):m>65535&&(m-=65536,h.push(m>>>10&1023|55296),m=56320|m&1023),h.push(m),d+=I}return el(h)}var nr=4096;function el(l){let i=l.length;if(i<=nr)return String.fromCharCode.apply(String,l);let r="",h=0;for(;h<i;)r+=String.fromCharCode.apply(String,l.slice(h,h+=nr));return r}function tl(l,i,r){let h="";r=Math.min(l.length,r);for(let d=i;d<r;++d)h+=String.fromCharCode(l[d]&127);return h}function nl(l,i,r){let h="";r=Math.min(l.length,r);for(let d=i;d<r;++d)h+=String.fromCharCode(l[d]);return h}function il(l,i,r){let h=l.length;(!i||i<0)&&(i=0),(!r||r<0||r>h)&&(r=h);let d="";for(let p=i;p<r;++p)d+=hl[l[p]];return d}function sl(l,i,r){let h=l.slice(i,r),d="";for(let p=0;p<h.length-1;p+=2)d+=String.fromCharCode(h[p]+h[p+1]*256);return d}S.prototype.slice=function(i,r){let h=this.length;i=~~i,r=r===void 0?h:~~r,i<0?(i+=h,i<0&&(i=0)):i>h&&(i=h),r<0?(r+=h,r<0&&(r=0)):r>h&&(r=h),r<i&&(r=i);let d=this.subarray(i,r);return Object.setPrototypeOf(d,S.prototype),d};function z(l,i,r){if(l%1!==0||l<0)throw new RangeError("offset is not uint");if(l+i>r)throw new RangeError("Trying to access beyond buffer length")}S.prototype.readUintLE=S.prototype.readUIntLE=function(i,r,h){i=i>>>0,r=r>>>0,h||z(i,r,this.length);let d=this[i],p=1,m=0;for(;++m<r&&(p*=256);)d+=this[i+m]*p;return d};S.prototype.readUintBE=S.prototype.readUIntBE=function(i,r,h){i=i>>>0,r=r>>>0,h||z(i,r,this.length);let d=this[i+--r],p=1;for(;r>0&&(p*=256);)d+=this[i+--r]*p;return d};S.prototype.readUint8=S.prototype.readUInt8=function(i,r){return i=i>>>0,r||z(i,1,this.length),this[i]};S.prototype.readUint16LE=S.prototype.readUInt16LE=function(i,r){return i=i>>>0,r||z(i,2,this.length),this[i]|this[i+1]<<8};S.prototype.readUint16BE=S.prototype.readUInt16BE=function(i,r){return i=i>>>0,r||z(i,2,this.length),this[i]<<8|this[i+1]};S.prototype.readUint32LE=S.prototype.readUInt32LE=function(i,r){return i=i>>>0,r||z(i,4,this.length),(this[i]|this[i+1]<<8|this[i+2]<<16)+this[i+3]*16777216};S.prototype.readUint32BE=S.prototype.readUInt32BE=function(i,r){return i=i>>>0,r||z(i,4,this.length),this[i]*16777216+(this[i+1]<<16|this[i+2]<<8|this[i+3])};S.prototype.readBigUInt64LE=we(function(i){i=i>>>0,ze(i,"offset");let r=this[i],h=this[i+7];(r===void 0||h===void 0)&&mt(i,this.length-8);let d=r+this[++i]*2**8+this[++i]*2**16+this[++i]*2**24,p=this[++i]+this[++i]*2**8+this[++i]*2**16+h*2**24;return BigInt(d)+(BigInt(p)<<BigInt(32))});S.prototype.readBigUInt64BE=we(function(i){i=i>>>0,ze(i,"offset");let r=this[i],h=this[i+7];(r===void 0||h===void 0)&&mt(i,this.length-8);let d=r*2**24+this[++i]*2**16+this[++i]*2**8+this[++i],p=this[++i]*2**24+this[++i]*2**16+this[++i]*2**8+h;return(BigInt(d)<<BigInt(32))+BigInt(p)});S.prototype.readIntLE=function(i,r,h){i=i>>>0,r=r>>>0,h||z(i,r,this.length);let d=this[i],p=1,m=0;for(;++m<r&&(p*=256);)d+=this[i+m]*p;return p*=128,d>=p&&(d-=Math.pow(2,8*r)),d};S.prototype.readIntBE=function(i,r,h){i=i>>>0,r=r>>>0,h||z(i,r,this.length);let d=r,p=1,m=this[i+--d];for(;d>0&&(p*=256);)m+=this[i+--d]*p;return p*=128,m>=p&&(m-=Math.pow(2,8*r)),m};S.prototype.readInt8=function(i,r){return i=i>>>0,r||z(i,1,this.length),this[i]&128?(255-this[i]+1)*-1:this[i]};S.prototype.readInt16LE=function(i,r){i=i>>>0,r||z(i,2,this.length);let h=this[i]|this[i+1]<<8;return h&32768?h|4294901760:h};S.prototype.readInt16BE=function(i,r){i=i>>>0,r||z(i,2,this.length);let h=this[i+1]|this[i]<<8;return h&32768?h|4294901760:h};S.prototype.readInt32LE=function(i,r){return i=i>>>0,r||z(i,4,this.length),this[i]|this[i+1]<<8|this[i+2]<<16|this[i+3]<<24};S.prototype.readInt32BE=function(i,r){return i=i>>>0,r||z(i,4,this.length),this[i]<<24|this[i+1]<<16|this[i+2]<<8|this[i+3]};S.prototype.readBigInt64LE=we(function(i){i=i>>>0,ze(i,"offset");let r=this[i],h=this[i+7];(r===void 0||h===void 0)&&mt(i,this.length-8);let d=this[i+4]+this[i+5]*2**8+this[i+6]*2**16+(h<<24);return(BigInt(d)<<BigInt(32))+BigInt(r+this[++i]*2**8+this[++i]*2**16+this[++i]*2**24)});S.prototype.readBigInt64BE=we(function(i){i=i>>>0,ze(i,"offset");let r=this[i],h=this[i+7];(r===void 0||h===void 0)&&mt(i,this.length-8);let d=(r<<24)+this[++i]*2**16+this[++i]*2**8+this[++i];return(BigInt(d)<<BigInt(32))+BigInt(this[++i]*2**24+this[++i]*2**16+this[++i]*2**8+h)});S.prototype.readFloatLE=function(i,r){return i=i>>>0,r||z(i,4,this.length),$e.read(this,i,!0,23,4)};S.prototype.readFloatBE=function(i,r){return i=i>>>0,r||z(i,4,this.length),$e.read(this,i,!1,23,4)};S.prototype.readDoubleLE=function(i,r){return i=i>>>0,r||z(i,8,this.length),$e.read(this,i,!0,52,8)};S.prototype.readDoubleBE=function(i,r){return i=i>>>0,r||z(i,8,this.length),$e.read(this,i,!1,52,8)};function te(l,i,r,h,d,p){if(!S.isBuffer(l))throw new TypeError('"buffer" argument must be a Buffer instance');if(i>d||i<p)throw new RangeError('"value" argument is out of bounds');if(r+h>l.length)throw new RangeError("Index out of range")}S.prototype.writeUintLE=S.prototype.writeUIntLE=function(i,r,h,d){if(i=+i,r=r>>>0,h=h>>>0,!d){let I=Math.pow(2,8*h)-1;te(this,i,r,h,I,0)}let p=1,m=0;for(this[r]=i&255;++m<h&&(p*=256);)this[r+m]=i/p&255;return r+h};S.prototype.writeUintBE=S.prototype.writeUIntBE=function(i,r,h,d){if(i=+i,r=r>>>0,h=h>>>0,!d){let I=Math.pow(2,8*h)-1;te(this,i,r,h,I,0)}let p=h-1,m=1;for(this[r+p]=i&255;--p>=0&&(m*=256);)this[r+p]=i/m&255;return r+h};S.prototype.writeUint8=S.prototype.writeUInt8=function(i,r,h){return i=+i,r=r>>>0,h||te(this,i,r,1,255,0),this[r]=i&255,r+1};S.prototype.writeUint16LE=S.prototype.writeUInt16LE=function(i,r,h){return i=+i,r=r>>>0,h||te(this,i,r,2,65535,0),this[r]=i&255,this[r+1]=i>>>8,r+2};S.prototype.writeUint16BE=S.prototype.writeUInt16BE=function(i,r,h){return i=+i,r=r>>>0,h||te(this,i,r,2,65535,0),this[r]=i>>>8,this[r+1]=i&255,r+2};S.prototype.writeUint32LE=S.prototype.writeUInt32LE=function(i,r,h){return i=+i,r=r>>>0,h||te(this,i,r,4,4294967295,0),this[r+3]=i>>>24,this[r+2]=i>>>16,this[r+1]=i>>>8,this[r]=i&255,r+4};S.prototype.writeUint32BE=S.prototype.writeUInt32BE=function(i,r,h){return i=+i,r=r>>>0,h||te(this,i,r,4,4294967295,0),this[r]=i>>>24,this[r+1]=i>>>16,this[r+2]=i>>>8,this[r+3]=i&255,r+4};function lr(l,i,r,h,d){pr(i,h,d,l,r,7);let p=Number(i&BigInt(4294967295));l[r++]=p,p=p>>8,l[r++]=p,p=p>>8,l[r++]=p,p=p>>8,l[r++]=p;let m=Number(i>>BigInt(32)&BigInt(4294967295));return l[r++]=m,m=m>>8,l[r++]=m,m=m>>8,l[r++]=m,m=m>>8,l[r++]=m,r}function hr(l,i,r,h,d){pr(i,h,d,l,r,7);let p=Number(i&BigInt(4294967295));l[r+7]=p,p=p>>8,l[r+6]=p,p=p>>8,l[r+5]=p,p=p>>8,l[r+4]=p;let m=Number(i>>BigInt(32)&BigInt(4294967295));return l[r+3]=m,m=m>>8,l[r+2]=m,m=m>>8,l[r+1]=m,m=m>>8,l[r]=m,r+8}S.prototype.writeBigUInt64LE=we(function(i,r=0){return lr(this,i,r,BigInt(0),BigInt("0xffffffffffffffff"))});S.prototype.writeBigUInt64BE=we(function(i,r=0){return hr(this,i,r,BigInt(0),BigInt("0xffffffffffffffff"))});S.prototype.writeIntLE=function(i,r,h,d){if(i=+i,r=r>>>0,!d){let y=Math.pow(2,8*h-1);te(this,i,r,h,y-1,-y)}let p=0,m=1,I=0;for(this[r]=i&255;++p<h&&(m*=256);)i<0&&I===0&&this[r+p-1]!==0&&(I=1),this[r+p]=(i/m>>0)-I&255;return r+h};S.prototype.writeIntBE=function(i,r,h,d){if(i=+i,r=r>>>0,!d){let y=Math.pow(2,8*h-1);te(this,i,r,h,y-1,-y)}let p=h-1,m=1,I=0;for(this[r+p]=i&255;--p>=0&&(m*=256);)i<0&&I===0&&this[r+p+1]!==0&&(I=1),this[r+p]=(i/m>>0)-I&255;return r+h};S.prototype.writeInt8=function(i,r,h){return i=+i,r=r>>>0,h||te(this,i,r,1,127,-128),i<0&&(i=255+i+1),this[r]=i&255,r+1};S.prototype.writeInt16LE=function(i,r,h){return i=+i,r=r>>>0,h||te(this,i,r,2,32767,-32768),this[r]=i&255,this[r+1]=i>>>8,r+2};S.prototype.writeInt16BE=function(i,r,h){return i=+i,r=r>>>0,h||te(this,i,r,2,32767,-32768),this[r]=i>>>8,this[r+1]=i&255,r+2};S.prototype.writeInt32LE=function(i,r,h){return i=+i,r=r>>>0,h||te(this,i,r,4,2147483647,-2147483648),this[r]=i&255,this[r+1]=i>>>8,this[r+2]=i>>>16,this[r+3]=i>>>24,r+4};S.prototype.writeInt32BE=function(i,r,h){return i=+i,r=r>>>0,h||te(this,i,r,4,2147483647,-2147483648),i<0&&(i=4294967295+i+1),this[r]=i>>>24,this[r+1]=i>>>16,this[r+2]=i>>>8,this[r+3]=i&255,r+4};S.prototype.writeBigInt64LE=we(function(i,r=0){return lr(this,i,r,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});S.prototype.writeBigInt64BE=we(function(i,r=0){return hr(this,i,r,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function ur(l,i,r,h,d,p){if(r+h>l.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function dr(l,i,r,h,d){return i=+i,r=r>>>0,d||ur(l,i,r,4,34028234663852886e22,-34028234663852886e22),$e.write(l,i,r,h,23,4),r+4}S.prototype.writeFloatLE=function(i,r,h){return dr(this,i,r,!0,h)};S.prototype.writeFloatBE=function(i,r,h){return dr(this,i,r,!1,h)};function fr(l,i,r,h,d){return i=+i,r=r>>>0,d||ur(l,i,r,8,17976931348623157e292,-17976931348623157e292),$e.write(l,i,r,h,52,8),r+8}S.prototype.writeDoubleLE=function(i,r,h){return fr(this,i,r,!0,h)};S.prototype.writeDoubleBE=function(i,r,h){return fr(this,i,r,!1,h)};S.prototype.copy=function(i,r,h,d){if(!S.isBuffer(i))throw new TypeError("argument should be a Buffer");if(h||(h=0),!d&&d!==0&&(d=this.length),r>=i.length&&(r=i.length),r||(r=0),d>0&&d<h&&(d=h),d===h||i.length===0||this.length===0)return 0;if(r<0)throw new RangeError("targetStart out of bounds");if(h<0||h>=this.length)throw new RangeError("Index out of range");if(d<0)throw new RangeError("sourceEnd out of bounds");d>this.length&&(d=this.length),i.length-r<d-h&&(d=i.length-r+h);let p=d-h;return this===i&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(r,h,d):Uint8Array.prototype.set.call(i,this.subarray(h,d),r),p};S.prototype.fill=function(i,r,h,d){if(typeof i=="string"){if(typeof r=="string"?(d=r,r=0,h=this.length):typeof h=="string"&&(d=h,h=this.length),d!==void 0&&typeof d!="string")throw new TypeError("encoding must be a string");if(typeof d=="string"&&!S.isEncoding(d))throw new TypeError("Unknown encoding: "+d);if(i.length===1){let m=i.charCodeAt(0);(d==="utf8"&&m<128||d==="latin1")&&(i=m)}}else typeof i=="number"?i=i&255:typeof i=="boolean"&&(i=Number(i));if(r<0||this.length<r||this.length<h)throw new RangeError("Out of range index");if(h<=r)return this;r=r>>>0,h=h===void 0?this.length:h>>>0,i||(i=0);let p;if(typeof i=="number")for(p=r;p<h;++p)this[p]=i;else{let m=S.isBuffer(i)?i:S.from(i,d),I=m.length;if(I===0)throw new TypeError('The value "'+i+'" is invalid for argument "value"');for(p=0;p<h-r;++p)this[p+r]=m[p%I]}return this};var Ke={};function Wn(l,i,r){Ke[l]=class extends r{constructor(){super(),Object.defineProperty(this,"message",{value:i.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${l}]`,this.stack,delete this.name}get code(){return l}set code(d){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:d,writable:!0})}toString(){return`${this.name} [${l}]: ${this.message}`}}}Wn("ERR_BUFFER_OUT_OF_BOUNDS",function(l){return l?`${l} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError);Wn("ERR_INVALID_ARG_TYPE",function(l,i){return`The "${l}" argument must be of type number. Received type ${typeof i}`},TypeError);Wn("ERR_OUT_OF_RANGE",function(l,i,r){let h=`The value of "${l}" is out of range.`,d=r;return Number.isInteger(r)&&Math.abs(r)>2**32?d=ir(String(r)):typeof r=="bigint"&&(d=String(r),(r>BigInt(2)**BigInt(32)||r<-(BigInt(2)**BigInt(32)))&&(d=ir(d)),d+="n"),h+=` It must be ${i}. Received ${d}`,h},RangeError);function ir(l){let i="",r=l.length,h=l[0]==="-"?1:0;for(;r>=h+4;r-=3)i=`_${l.slice(r-3,r)}${i}`;return`${l.slice(0,r)}${i}`}function rl(l,i,r){ze(i,"offset"),(l[i]===void 0||l[i+r]===void 0)&&mt(i,l.length-(r+1))}function pr(l,i,r,h,d,p){if(l>r||l<i){let m=typeof i=="bigint"?"n":"",I;throw p>3?i===0||i===BigInt(0)?I=`>= 0${m} and < 2${m} ** ${(p+1)*8}${m}`:I=`>= -(2${m} ** ${(p+1)*8-1}${m}) and < 2 ** ${(p+1)*8-1}${m}`:I=`>= ${i}${m} and <= ${r}${m}`,new Ke.ERR_OUT_OF_RANGE("value",I,l)}rl(h,d,p)}function ze(l,i){if(typeof l!="number")throw new Ke.ERR_INVALID_ARG_TYPE(i,"number",l)}function mt(l,i,r){throw Math.floor(l)!==l?(ze(l,r),new Ke.ERR_OUT_OF_RANGE(r||"offset","an integer",l)):i<0?new Ke.ERR_BUFFER_OUT_OF_BOUNDS:new Ke.ERR_OUT_OF_RANGE(r||"offset",`>= ${r?1:0} and <= ${i}`,l)}var ol=/[^+/0-9A-Za-z-_]/g;function al(l){if(l=l.split("=")[0],l=l.trim().replace(ol,""),l.length<2)return"";for(;l.length%4!==0;)l=l+"=";return l}function Hn(l,i){i=i||1/0;let r,h=l.length,d=null,p=[];for(let m=0;m<h;++m){if(r=l.charCodeAt(m),r>55295&&r<57344){if(!d){if(r>56319){(i-=3)>-1&&p.push(239,191,189);continue}else if(m+1===h){(i-=3)>-1&&p.push(239,191,189);continue}d=r;continue}if(r<56320){(i-=3)>-1&&p.push(239,191,189),d=r;continue}r=(d-55296<<10|r-56320)+65536}else d&&(i-=3)>-1&&p.push(239,191,189);if(d=null,r<128){if((i-=1)<0)break;p.push(r)}else if(r<2048){if((i-=2)<0)break;p.push(r>>6|192,r&63|128)}else if(r<65536){if((i-=3)<0)break;p.push(r>>12|224,r>>6&63|128,r&63|128)}else if(r<1114112){if((i-=4)<0)break;p.push(r>>18|240,r>>12&63|128,r>>6&63|128,r&63|128)}else throw new Error("Invalid code point")}return p}function cl(l){let i=[];for(let r=0;r<l.length;++r)i.push(l.charCodeAt(r)&255);return i}function ll(l,i){let r,h,d,p=[];for(let m=0;m<l.length&&!((i-=2)<0);++m)r=l.charCodeAt(m),h=r>>8,d=r%256,p.push(d),p.push(h);return p}function gr(l){return Fn.toByteArray(al(l))}function $t(l,i,r,h){let d;for(d=0;d<h&&!(d+r>=i.length||d>=l.length);++d)i[d+r]=l[d];return d}function ge(l,i){return l instanceof i||l!=null&&l.constructor!=null&&l.constructor.name!=null&&l.constructor.name===i.name}function Kn(l){return l!==l}var hl=function(){let l="0123456789abcdef",i=new Array(256);for(let r=0;r<16;++r){let h=r*16;for(let d=0;d<16;++d)i[h+d]=l[r]+l[d]}return i}();function we(l){return typeof BigInt>"u"?ul:l}function ul(){throw new Error("BigInt not supported")}});var _r=jt((St,ri)=>{M();(function(l,i){typeof St=="object"&&typeof ri=="object"?ri.exports=i():typeof define=="function"&&define.amd?define([],i):typeof St=="object"?St.Ably=i():l.Ably=i()})(St,()=>{var l={},i={exports:l},r=Object.defineProperty,h=Object.defineProperties,d=Object.getOwnPropertyDescriptor,p=Object.getOwnPropertyDescriptors,m=Object.getOwnPropertyNames,I=Object.getOwnPropertySymbols,y=Object.prototype.hasOwnProperty,k=Object.prototype.propertyIsEnumerable,U=(e,t,n)=>t in e?r(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,O=(e,t)=>{for(var n in t||(t={}))y.call(t,n)&&U(e,n,t[n]);if(I)for(var n of I(t))k.call(t,n)&&U(e,n,t[n]);return e},H=(e,t)=>h(e,p(t)),re=(e,t)=>{var n={};for(var s in e)y.call(e,s)&&t.indexOf(s)<0&&(n[s]=e[s]);if(e!=null&&I)for(var s of I(e))t.indexOf(s)<0&&k.call(e,s)&&(n[s]=e[s]);return n},Pe=(e,t)=>{for(var n in t)r(e,n,{get:t[n],enumerable:!0})},Zt=(e,t,n,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of m(t))!y.call(e,o)&&o!==n&&r(e,o,{get:()=>t[o],enumerable:!(s=d(t,o))||s.enumerable});return e},Lr=e=>Zt(r({},"__esModule",{value:!0}),e),oi={};Pe(oi,{ErrorInfo:()=>C,Realtime:()=>On,Rest:()=>Rn,default:()=>vc,makeProtocolMessageFromDeserialized:()=>As,msgpack:()=>xn}),i.exports=Lr(oi);var b=class{},ai=typeof globalThis<"u"?globalThis:typeof window<"u"?window:self;function Tt(e,t){return`${e}`.padStart(t?3:2,"0")}function xr(e){return b.Config.logTimestamps?function(t){let n=new Date;e(Tt(n.getHours())+":"+Tt(n.getMinutes())+":"+Tt(n.getSeconds())+"."+Tt(n.getMilliseconds(),1)+" "+t)}:function(t){e(t)}}var Ur=()=>{var e;let t,n;return typeof((e=ai?.console)==null?void 0:e.log)=="function"?(t=function(...s){console.log.apply(console,s)},n=console.warn?function(...s){console.warn.apply(console,s)}:t):t=n=function(){},[t,n].map(xr)},me=class yt{constructor(){this.deprecated=(t,n)=>{this.deprecationWarning(`${t} is deprecated and will be removed in a future version. ${n}`)},this.shouldLog=t=>t<=this.logLevel,this.setLog=(t,n)=>{t!==void 0&&(this.logLevel=t),n!==void 0&&(this.logHandler=this.logErrorHandler=n)},this.logLevel=yt.defaultLogLevel,this.logHandler=yt.defaultLogHandler,this.logErrorHandler=yt.defaultLogErrorHandler}static initLogHandlers(){let[t,n]=Ur();this.defaultLogHandler=t,this.defaultLogErrorHandler=n,this.defaultLogger=new yt}static logActionNoStrip(t,n,s,o){t.logAction(n,s,o)}logAction(t,n,s){this.shouldLog(t)&&(t===1?this.logErrorHandler:this.logHandler)("Ably: "+n+": "+s,t)}renamedClientOption(t,n){this.deprecationWarning(`The \`${t}\` client option has been renamed to \`${n}\`. Please update your code to use \`${n}\` instead. \`${t}\` will be removed in a future version.`)}renamedMethod(t,n,s){this.deprecationWarning(`\`${t}\`\u2019s \`${n}\` method has been renamed to \`${s}\`. Please update your code to use \`${s}\` instead. \`${n}\` will be removed in a future version.`)}deprecationWarning(t){this.shouldLog(1)&&this.logErrorHandler(`Ably: Deprecation warning - ${t}`,1)}};me.defaultLogLevel=1,me.LOG_NONE=0,me.LOG_ERROR=1,me.LOG_MAJOR=2,me.LOG_MINOR=3,me.LOG_MICRO=4,me.logAction=(e,t,n,s)=>{me.logActionNoStrip(e,t,n,s)};var Br=me,c=Br,Ne={};Pe(Ne,{Format:()=>Ei,allSame:()=>yi,allToLowerCase:()=>nn,allToUpperCase:()=>wi,arrChooseN:()=>Ai,arrDeleteValue:()=>pi,arrEquals:()=>Ti,arrIntersect:()=>di,arrIntersectOb:()=>fi,arrPopRandomElement:()=>en,arrWithoutValue:()=>Vr,cheapRandStr:()=>Mt,containsValue:()=>Hr,copy:()=>Le,createMissingPluginError:()=>Pt,dataSizeBytes:()=>Si,decodeBody:()=>ne,encodeBody:()=>le,ensureArray:()=>li,forInOwnNonNullProperties:()=>mi,getBackoffCoefficient:()=>bi,getGlobalObject:()=>rn,getJitterCoefficient:()=>vi,getRetryTime:()=>sn,inherits:()=>qr,inspectBody:()=>Ci,inspectError:()=>G,intersect:()=>ui,isEmpty:()=>Fr,isErrorInfoOrPartialErrorInfo:()=>tn,isNil:()=>ce,isObject:()=>xe,keysArray:()=>tt,matchDerivedChannel:()=>Oi,mixin:()=>B,parseQueryString:()=>_t,prototypicalClone:()=>hi,randomString:()=>Ri,shallowClone:()=>Gr,shallowEquals:()=>Ii,throwMissingPluginError:()=>Q,toBase64:()=>kt,toQueryString:()=>nt,valuesArray:()=>gi,whenPromiseSettles:()=>X,withTimeoutAsync:()=>_i});function ci(e){let t="["+e.constructor.name;return e.message&&(t+=": "+e.message),e.statusCode&&(t+="; statusCode="+e.statusCode),e.code&&(t+="; code="+e.code),e.cause&&(t+="; cause="+G(e.cause)),e.href&&!(e.message&&e.message.indexOf("help.ably.io")>-1)&&(t+="; see "+e.href+" "),t+="]",t}var C=class Qn extends Error{constructor(t,n,s,o){super(t),typeof Object.setPrototypeOf<"u"&&Object.setPrototypeOf(this,Qn.prototype),this.code=n,this.statusCode=s,this.cause=o}toString(){return ci(this)}static fromValues(t){let{message:n,code:s,statusCode:o}=t;if(typeof n!="string"||typeof s!="number"||typeof o!="number")throw new Error("ErrorInfo.fromValues(): invalid values: "+b.Config.inspect(t));let a=Object.assign(new Qn(n,s,o),t);return a.code&&!a.href&&(a.href="https://help.ably.io/error/"+a.code),a}},J=class Yn extends Error{constructor(t,n,s,o){super(t),typeof Object.setPrototypeOf<"u"&&Object.setPrototypeOf(this,Yn.prototype),this.code=n,this.statusCode=s,this.cause=o}toString(){return ci(this)}static fromValues(t){let{message:n,code:s,statusCode:o}=t;if(typeof n!="string"||!ce(s)&&typeof s!="number"||!ce(o)&&typeof o!="number")throw new Error("PartialErrorInfo.fromValues(): invalid values: "+b.Config.inspect(t));let a=Object.assign(new Yn(n,s,o),t);return a.code&&!a.href&&(a.href="https://help.ably.io/error/"+a.code),a}};function Dr(e){return Math.floor(Math.random()*e.length)}function B(e,...t){for(let n=0;n<t.length;n++){let s=t[n];if(!s)break;for(let o in s)Object.prototype.hasOwnProperty.call(s,o)&&(e[o]=s[o])}return e}function Le(e){return B({},e)}function li(e){return ce(e)?[]:Array.isArray(e)?e:[e]}function xe(e){return Object.prototype.toString.call(e)=="[object Object]"}function Fr(e){for(let t in e)return!1;return!0}function ce(e){return e==null}function Gr(e){let t=new Object;for(let n in e)t[n]=e[n];return t}function hi(e,t){class n{}n.prototype=e;let s=new n;return t&&B(s,t),s}var qr=function(e,t){if(b.Config.inherits){b.Config.inherits(e,t);return}e.super_=t,e.prototype=hi(t.prototype,{constructor:e})};function Hr(e,t){for(let n in e)if(e[n]==t)return!0;return!1}function ui(e,t){return Array.isArray(t)?di(e,t):fi(e,t)}function di(e,t){let n=[];for(let s=0;s<e.length;s++){let o=e[s];t.indexOf(o)!=-1&&n.push(o)}return n}function fi(e,t){let n=[];for(let s=0;s<e.length;s++){let o=e[s];o in t&&n.push(o)}return n}function pi(e,t){let n=e.indexOf(t),s=n!=-1;return s&&e.splice(n,1),s}function Vr(e,t){let n=e.slice();return pi(n,t),n}function tt(e,t){let n=[];for(let s in e)t&&!Object.prototype.hasOwnProperty.call(e,s)||n.push(s);return n}function gi(e,t){let n=[];for(let s in e)t&&!Object.prototype.hasOwnProperty.call(e,s)||n.push(e[s]);return n}function mi(e,t){for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&e[n]&&t(n)}function yi(e,t){if(e.length===0)return!0;let n=e[0][t];return e.every(function(s){return s[t]===n})}var Ei=(e=>(e.msgpack="msgpack",e.json="json",e))(Ei||{});function en(e){return e.splice(Dr(e),1)[0]}function nt(e){let t=[];if(e)for(let n in e)t.push(encodeURIComponent(n)+"="+encodeURIComponent(e[n]));return t.length?"?"+t.join("&"):""}function _t(e){let t,n=/([^?&=]+)=?([^&]*)/g,s={};for(;t=n.exec(e);)s[decodeURIComponent(t[1])]=decodeURIComponent(t[2]);return s}function tn(e){return typeof e=="object"&&e!==null&&(e instanceof C||e instanceof J)}function G(e){var t,n;return e instanceof Error||((t=e?.constructor)==null?void 0:t.name)==="ErrorInfo"||((n=e?.constructor)==null?void 0:n.name)==="PartialErrorInfo"?e.toString():b.Config.inspect(e)}function Ci(e){return b.BufferUtils.isBuffer(e)?e.toString():typeof e=="string"?e:b.Config.inspect(e)}function Si(e){if(b.BufferUtils.isBuffer(e))return b.BufferUtils.byteLength(e);if(typeof e=="string")return b.Config.stringByteSize(e);if(typeof e=="number")return 8;if(typeof e=="boolean")return 1;throw new Error(`Expected input of Utils.dataSizeBytes to be a string, a number, a boolean or a buffer, but was: ${typeof e}`)}function Mt(){return String(Math.random()).substr(2)}var Ri=async e=>{let t=await b.Config.getRandomArrayBuffer(e);return b.BufferUtils.base64Encode(t)};function Ai(e,t){let n=Math.min(t,e.length),s=e.slice(),o=[];for(let a=0;a<n;a++)o.push(en(s));return o}function X(e,t){e.then(n=>{t?.(null,n)}).catch(n=>{t?.(n)})}function ne(e,t,n){return n=="msgpack"?(t||Q("MsgPack"),t.decode(e)):JSON.parse(String(e))}function le(e,t,n){return n=="msgpack"?(t||Q("MsgPack"),t.encode(e,!0)):JSON.stringify(e)}function nn(e){return e.map(function(t){return t&&t.toLowerCase()})}function wi(e){return e.map(function(t){return t&&t.toUpperCase()})}function bi(e){return Math.min((e+2)/3,2)}function vi(){return 1-Math.random()*.2}function sn(e,t){return e*bi(t)*vi()}function rn(){return typeof globalThis<"u"?globalThis:typeof window<"u"?window:self}function Ii(e,t){return Object.keys(e).every(n=>e[n]===t[n])&&Object.keys(t).every(n=>t[n]===e[n])}function Oi(e){let t=/^(\[([^?]*)(?:(.*))\])?(.+)$/,n=e.match(t);if(!n||!n.length||n.length<5)throw new C("regex match failed",400,40010);if(n[2])throw new C(`cannot use a derived option with a ${n[2]} channel`,400,40010);return{qualifierParam:n[3]||"",channelName:n[4]}}function kt(e){let t=b.BufferUtils,n=t.utf8Encode(e);return t.base64Encode(n)}function Ti(e,t){return e.length===t.length&&e.every(function(n,s){return n===t[s]})}function Pt(e){return new C(`${e} plugin not provided`,40019,400)}function Q(e){throw Pt(e)}async function _i(e,t=5e3,n="Timeout expired"){let s=new C(n,5e4,500);return Promise.race([e,new Promise((o,a)=>setTimeout(()=>a(s),t))])}var Mi="2.10.1",jr="ably-js/"+Mi,he={ENDPOINT:"main",ENVIRONMENT:"",REST_HOST:"rest.ably.io",REALTIME_HOST:"realtime.ably.io",FALLBACK_HOSTS:["main.a.fallback.ably-realtime.com","main.b.fallback.ably-realtime.com","main.c.fallback.ably-realtime.com","main.d.fallback.ably-realtime.com","main.e.fallback.ably-realtime.com"],PORT:80,TLS_PORT:443,TIMEOUTS:{disconnectedRetryTimeout:15e3,suspendedRetryTimeout:3e4,httpRequestTimeout:1e4,httpMaxRetryDuration:15e3,channelRetryTimeout:15e3,fallbackRetryTimeout:6e5,connectionStateTtl:12e4,realtimeRequestTimeout:1e4,recvTimeout:9e4,webSocketConnectTimeout:1e4,webSocketSlowTimeout:4e3},httpMaxRetryCount:3,maxMessageSize:65536,version:Mi,protocolVersion:3,agent:jr,getPort:Wr,getHttpScheme:Kr,getPrimaryDomainFromEndpoint:Pi,getEndpointFallbackHosts:Ni,getFallbackHosts:xi,getHosts:$r,checkHost:Ui,objectifyOptions:Jr,normaliseOptions:Yr,defaultGetHeaders:Xr,defaultPostHeaders:Zr};function Wr(e,t){return t||e.tls?e.tlsPort:e.port}function Kr(e){return e.tls?"https://":"http://"}function ki(e){return e.includes(".")||e.includes("::")||e==="localhost"}function Pi(e){return ki(e)?e:e.startsWith("nonprod:")?`${e.replace("nonprod:","")}.realtime.ably-nonprod.net`:`${e}.realtime.ably.net`}function Ni(e){if(ki(e))return[];if(e.startsWith("nonprod:")){let t=e.replace("nonprod:","");return Li(t,"ably-realtime-nonprod.com")}return Li(e,"ably-realtime.com")}function Li(e,t){return["a","b","c","d","e"].map(n=>`${e}.${n}.fallback.${t}`)}function xi(e){let t=e.fallbackHosts,n=typeof e.httpMaxRetryCount<"u"?e.httpMaxRetryCount:he.httpMaxRetryCount;return t?Ai(t,n):[]}function $r(e){return[e.primaryDomain].concat(xi(e))}function Ui(e){if(typeof e!="string")throw new C("host must be a string; was a "+typeof e,4e4,400);if(!e.length)throw new C("host must not be zero-length",4e4,400)}function zr(e){let t={};for(let n in he.TIMEOUTS)t[n]=e[n]||he.TIMEOUTS[n];return t}function on(e){let t=he.agent;if(e.agents)for(var n in e.agents)t+=" "+n+"/"+e.agents[n];return t}function Jr(e,t,n,s,o){if(e===void 0){let u=t?`${n} must be initialized with either a client options object, an Ably API key, or an Ably Token`:`${n} must be initialized with a client options object`;throw c.logAction(s,c.LOG_ERROR,`${n}()`,u),new Error(u)}let a;if(typeof e=="string")if(e.indexOf(":")==-1){if(!t){let u=`${n} cannot be initialized with just an Ably Token; you must provide a client options object with a \`plugins\` property. (Set this Ably Token as the object\u2019s \`token\` property.)`;throw c.logAction(s,c.LOG_ERROR,`${n}()`,u),new Error(u)}a={token:e}}else{if(!t){let u=`${n} cannot be initialized with just an Ably API key; you must provide a client options object with a \`plugins\` property. (Set this Ably API key as the object\u2019s \`key\` property.)`;throw c.logAction(s,c.LOG_ERROR,`${n}()`,u),new Error(u)}a={key:e}}else a=e;return o&&(a=H(O({},a),{plugins:O(O({},o),a.plugins)})),a}function Qr(e){if(e.endpoint&&(e.environment||e.restHost||e.realtimeHost))throw new C("The `endpoint` option cannot be used in conjunction with the `environment`, `restHost`, or `realtimeHost` options.",40106,400);if(e.environment&&(e.restHost||e.realtimeHost))throw new C("The `environment` option cannot be used in conjunction with the `restHost`, or `realtimeHost` options.",40106,400)}function Yr(e,t,n){let s=n??c.defaultLogger;e.environment&&s.deprecated("The `environment` client option","Use the `endpoint` client option instead."),e.restHost&&s.deprecated("The `restHost` client option","Use the `endpoint` client option instead."),e.realtimeHost&&s.deprecated("The `realtimeHost` client option","Use the `endpoint` client option instead."),Qr(e),typeof e.recover=="function"&&e.closeOnUnload===!0&&(c.logAction(s,c.LOG_ERROR,"Defaults.normaliseOptions","closeOnUnload was true and a session recovery function was set - these are mutually exclusive, so unsetting the latter"),e.recover=void 0),"closeOnUnload"in e||(e.closeOnUnload=!e.recover),"queueMessages"in e||(e.queueMessages=!0);let o=e.endpoint||he.ENDPOINT;!e.fallbackHosts&&!e.restHost&&!e.realtimeHost&&!e.port&&!e.tlsPort&&(e.fallbackHosts=Ni(e.environment||o));let a=e.environment&&`${e.environment}.realtime.ably.net`,f=e.restHost||e.realtimeHost||a||Pi(o);(e.fallbackHosts||[]).concat(f).forEach(Ui),e.port=e.port||he.PORT,e.tlsPort=e.tlsPort||he.TLS_PORT,"tls"in e||(e.tls=!0);let E=zr(e);t?"useBinaryProtocol"in e?e.useBinaryProtocol=b.Config.supportsBinary&&e.useBinaryProtocol:e.useBinaryProtocol=b.Config.preferBinary:e.useBinaryProtocol=!1;let g={};e.clientId&&(g["X-Ably-ClientId"]=b.BufferUtils.base64Encode(b.BufferUtils.utf8Encode(e.clientId))),"idempotentRestPublishing"in e||(e.idempotentRestPublishing=!0);let A=null,w=e.connectivityCheckUrl;if(e.connectivityCheckUrl){let[R,T]=e.connectivityCheckUrl.split("?");A=T?_t(T):{},R.indexOf("://")===-1&&(R="https://"+R),w=R}let v=e.wsConnectivityCheckUrl;return v&&v.indexOf("://")===-1&&(v="wss://"+v),H(O({},e),{primaryDomain:f,maxMessageSize:e.maxMessageSize||he.maxMessageSize,timeouts:E,connectivityCheckParams:A,connectivityCheckUrl:w,wsConnectivityCheckUrl:v,headers:g})}function Nt(e,t,n){let s=n||{};if(s.cipher){e||Q("Crypto");let o=e.getCipher(s.cipher,t);s.cipher=o.cipherParams,s.channelCipher=o.cipher}else"cipher"in s&&(s.cipher=void 0,s.channelCipher=null);return s}var Bi={json:"application/json",xml:"application/xml",html:"text/html",msgpack:"application/x-msgpack",text:"text/plain"},Lt={format:"json",protocolVersion:he.protocolVersion};function Xr(e,{format:t=Lt.format,protocolVersion:n=Lt.protocolVersion}={}){return{accept:Bi[t],"X-Ably-Version":n.toString(),"Ably-Agent":on(e)}}function Zr(e,{format:t=Lt.format,protocolVersion:n=Lt.protocolVersion}={}){let s;return{accept:s=Bi[t],"content-type":s,"X-Ably-Version":n.toString(),"Ably-Agent":on(e)}}var L=he;function eo(e){return Object.assign(he,e)}var to=class wr{constructor(t,n){this.logger=t,this.members=n||[]}call(t,n){for(let s of this.members)if(s)try{s(t,n)}catch(o){c.logAction(this.logger,c.LOG_ERROR,"Multicaster multiple callback handler","Unexpected exception: "+o+"; stack = "+o.stack)}}push(...t){this.members.push(...t)}createPromise(){return new Promise((t,n)=>{this.push((s,o)=>{s?n(s):t(o)})})}resolveAll(t){this.call(null,t)}rejectAll(t){this.call(t)}static create(t,n){let s=new wr(t,n);return Object.assign((o,a)=>s.call(o,a),{push:o=>s.push(o),createPromise:()=>s.createPromise(),resolveAll:o=>s.resolveAll(o),rejectAll:o=>s.rejectAll(o)})}},an=to,Di=(e=>(e.Get="get",e.Delete="delete",e.Post="post",e.Put="put",e.Patch="patch",e))(Di||{}),V=Di,Fi=(e=>(e[e.Success=200]="Success",e[e.NoContent=204]="NoContent",e[e.BadRequest=400]="BadRequest",e[e.Unauthorized=401]="Unauthorized",e[e.Forbidden=403]="Forbidden",e[e.RequestTimeout=408]="RequestTimeout",e[e.InternalServerError=500]="InternalServerError",e))(Fi||{});function no(e){return e>=200&&e<400}var xt=Fi,cn=Math.pow(2,17);function io(){return("000000"+Math.floor(Math.random()*1e16)).slice(-16)}function so(e){return!!e.connection}function Gi(e){return tn(e)?(e.code||(e.statusCode===403?e.code=40300:(e.code=40170,e.statusCode=401)),e):new C(G(e),e.code||40170,e.statusCode||401)}var ro=(e,t)=>{let n=b.BufferUtils,s=n.utf8Encode(e),o=n.utf8Encode(t),a=n.hmacSha256(s,o);return n.base64Encode(a)};function qi(e){if(!e)return"";typeof e=="string"&&(e=JSON.parse(e));let t=Object.create(null),n=tt(e,!0);if(!n)return"";n.sort();for(let s=0;s<n.length;s++)t[n[s]]=e[n[s]].sort();return JSON.stringify(t)}function Hi(e,t){if(e.authCallback)c.logAction(t,c.LOG_MINOR,"Auth()","using token auth with authCallback");else if(e.authUrl)c.logAction(t,c.LOG_MINOR,"Auth()","using token auth with authUrl");else if(e.key)c.logAction(t,c.LOG_MINOR,"Auth()","using token auth with client-side signing");else if(e.tokenDetails)c.logAction(t,c.LOG_MINOR,"Auth()","using token auth with supplied token only");else{let n="authOptions must include valid authentication parameters";throw c.logAction(t,c.LOG_ERROR,"Auth()",n),new Error(n)}}function oo(e){return"useTokenAuth"in e&&!e.useTokenAuth}function Vi(e){return e.useTokenAuth||!oo(e)&&(e.authCallback||e.authUrl||e.token||e.tokenDetails)}function ao(e){return!e.key&&!e.authCallback&&!e.authUrl}var co=0;function lo(){return co++}var ho=class{constructor(e,t){if(this.authOptions={},this.client=e,this.tokenParams=t.defaultTokenParams||{},this.currentTokenRequestId=null,this.waitingForTokenRequest=null,Vi(t))ao(t)&&c.logAction(this.logger,c.LOG_ERROR,"Auth()","Warning: library initialized with a token literal without any way to renew the token when it expires (no authUrl, authCallback, or key). See https://help.ably.io/error/40171 for help"),this._saveTokenOptions(t.defaultTokenParams,t),Hi(this.authOptions,this.logger);else{if(!t.key){let n="No authentication options provided; need one of: key, authUrl, or authCallback (or for testing only, token or tokenDetails)";throw c.logAction(this.logger,c.LOG_ERROR,"Auth()",n),new C(n,40160,401)}c.logAction(this.logger,c.LOG_MINOR,"Auth()","anonymous, using basic auth"),this._saveBasicOptions(t)}}get logger(){return this.client.logger}async authorize(e,t){if(t&&t.key&&this.authOptions.key!==t.key)throw new C("Unable to update auth options with incompatible key",40102,401);try{let n=await this._forceNewToken(e??null,t??null);return so(this.client)?new Promise((s,o)=>{this.client.connection.connectionManager.onAuthUpdated(n,(a,u)=>a?o(a):s(u))}):n}catch(n){throw this.client.connection&&n.statusCode===xt.Forbidden&&this.client.connection.connectionManager.actOnErrorFromAuthorize(n),n}}async _forceNewToken(e,t){this.tokenDetails=null,this._saveTokenOptions(e,t),Hi(this.authOptions,this.logger);try{return this._ensureValidAuthCredentials(!0)}finally{delete this.tokenParams.timestamp,delete this.authOptions.queryTime}}async requestToken(e,t){let n=t||this.authOptions,s=e||Le(this.tokenParams),o,a=this.client;if(n.authCallback)c.logAction(this.logger,c.LOG_MINOR,"Auth.requestToken()","using token auth with authCallback"),o=n.authCallback;else if(n.authUrl)c.logAction(this.logger,c.LOG_MINOR,"Auth.requestToken()","using token auth with authUrl"),o=(f,E)=>{let g=B({accept:"application/json, text/plain"},n.authHeaders),A=n.authMethod&&n.authMethod.toLowerCase()==="post",w,v=n.authUrl.indexOf("?");v>-1&&(w=_t(n.authUrl.slice(v)),n.authUrl=n.authUrl.slice(0,v),A||(n.authParams=B(w,n.authParams)));let R=B({},n.authParams||{},f),T=_=>{var N,D;let F=(N=_.body)!=null?N:null,q=null;if(_.error)c.logAction(this.logger,c.LOG_MICRO,"Auth.requestToken().tokenRequestCallback","Received Error: "+G(_.error));else{let Y=(D=_.headers["content-type"])!=null?D:null;Array.isArray(Y)?q=Y.join(", "):q=Y,c.logAction(this.logger,c.LOG_MICRO,"Auth.requestToken().tokenRequestCallback","Received; content-type: "+q+"; body: "+Ci(F))}if(_.error){E(_.error,null);return}if(_.unpacked){E(null,F);return}if(b.BufferUtils.isBuffer(F)&&(F=F.toString()),!q){E(new C("authUrl response is missing a content-type header",40170,401),null);return}let x=q.indexOf("application/json")>-1,se=q.indexOf("text/plain")>-1||q.indexOf("application/jwt")>-1;if(!x&&!se){E(new C("authUrl responded with unacceptable content-type "+q+", should be either text/plain, application/jwt or application/json",40170,401),null);return}if(x){if(F.length>cn){E(new C("authUrl response exceeded max permitted length",40170,401),null);return}try{F=JSON.parse(F)}catch(Y){E(new C("Unexpected error processing authURL response; err = "+Y.message,40170,401),null);return}}E(null,F,q)};if(c.logAction(this.logger,c.LOG_MICRO,"Auth.requestToken().tokenRequestCallback","Requesting token from "+n.authUrl+"; Params: "+JSON.stringify(R)+"; method: "+(A?"POST":"GET")),A){let _=g||{};_["content-type"]="application/x-www-form-urlencoded";let N=nt(R).slice(1);X(this.client.http.doUri(V.Post,n.authUrl,_,N,w),(D,F)=>T(D||F))}else X(this.client.http.doUri(V.Get,n.authUrl,g||{},null,R),(_,N)=>T(_||N))};else if(n.key)c.logAction(this.logger,c.LOG_MINOR,"Auth.requestToken()","using token auth with client-side signing"),o=(f,E)=>{X(this.createTokenRequest(f,n),(g,A)=>E(g,A??null))};else{let f="Need a new token, but authOptions does not include any way to request one (no authUrl, authCallback, or key)";throw c.logAction(this.logger,c.LOG_ERROR,"Auth()","library initialized with a token literal without any way to renew the token when it expires (no authUrl, authCallback, or key). See https://help.ably.io/error/40171 for help"),new C(f,40171,403)}"capability"in s&&(s.capability=qi(s.capability));let u=(f,E)=>{let g=f.keyName,A="/keys/"+g+"/requestToken",w=function(R){return a.baseUri(R)+A},v=L.defaultPostHeaders(this.client.options);n.requestHeaders&&B(v,n.requestHeaders),c.logAction(this.logger,c.LOG_MICRO,"Auth.requestToken().requestToken","Sending POST to "+A+"; Token params: "+JSON.stringify(f)),X(this.client.http.do(V.Post,w,v,JSON.stringify(f),null),(R,T)=>R?E(R):E(T.error,T.body,T.unpacked))};return new Promise((f,E)=>{let g=!1,A=this.client.options.timeouts.realtimeRequestTimeout,w=setTimeout(()=>{g=!0;let v="Token request callback timed out after "+A/1e3+" seconds";c.logAction(this.logger,c.LOG_ERROR,"Auth.requestToken()",v),E(new C(v,40170,401))},A);o(s,(v,R,T)=>{if(g)return;if(clearTimeout(w),v){c.logAction(this.logger,c.LOG_ERROR,"Auth.requestToken()","token request signing call returned error; err = "+G(v)),E(Gi(v));return}if(typeof R=="string"){R.length===0?E(new C("Token string is empty",40170,401)):R.length>cn?E(new C("Token string exceeded max permitted length (was "+R.length+" bytes)",40170,401)):R==="undefined"||R==="null"?E(new C("Token string was literal null/undefined",40170,401)):R[0]==="{"&&!(T&&T.indexOf("application/jwt")>-1)?E(new C("Token was double-encoded; make sure you're not JSON-encoding an already encoded token request or details",40170,401)):f({token:R});return}if(typeof R!="object"||R===null){let N="Expected token request callback to call back with a token string or token request/details object, but got a "+typeof R;c.logAction(this.logger,c.LOG_ERROR,"Auth.requestToken()",N),E(new C(N,40170,401));return}let _=JSON.stringify(R).length;if(_>cn&&!n.suppressMaxLengthCheck){E(new C("Token request/details object exceeded max permitted stringified size (was "+_+" bytes)",40170,401));return}if("issued"in R){f(R);return}if(!("keyName"in R)){let N="Expected token request callback to call back with a token string, token request object, or token details object";c.logAction(this.logger,c.LOG_ERROR,"Auth.requestToken()",N),E(new C(N,40170,401));return}u(R,(N,D,F)=>{if(N){c.logAction(this.logger,c.LOG_ERROR,"Auth.requestToken()","token request API call returned error; err = "+G(N)),E(Gi(N));return}F||(D=JSON.parse(D)),c.logAction(this.logger,c.LOG_MINOR,"Auth.getToken()","token received"),f(D)})})})}async createTokenRequest(e,t){t=t||this.authOptions,e=e||Le(this.tokenParams);let n=t.key;if(!n)throw new C("No key specified",40101,403);let s=n.split(":"),o=s[0],a=s[1];if(!a)throw new C("Invalid key specified",40101,403);if(e.clientId==="")throw new C("clientId can\u2019t be an empty string",40012,400);"capability"in e&&(e.capability=qi(e.capability));let u=B({keyName:o},e),f=e.clientId||"",E=e.ttl||"",g=e.capability||"";u.timestamp||(u.timestamp=await this._getTimestamp(t&&t.queryTime));let A=u.nonce||(u.nonce=io()),w=u.timestamp,v=u.keyName+`
2
- `+E+`
3
- `+g+`
4
- `+f+`
5
- `+w+`
6
- `+A+`
7
- `;return u.mac=u.mac||ro(v,a),c.logAction(this.logger,c.LOG_MINOR,"Auth.getTokenRequest()","generated signed request"),u}async getAuthParams(){if(this.method=="basic")return{key:this.key};{let e=await this._ensureValidAuthCredentials(!1);if(!e)throw new Error("Auth.getAuthParams(): _ensureValidAuthCredentials returned no error or tokenDetails");return{access_token:e.token}}}async getAuthHeaders(){if(this.method=="basic")return{authorization:"Basic "+this.basicKey};{let e=await this._ensureValidAuthCredentials(!1);if(!e)throw new Error("Auth.getAuthParams(): _ensureValidAuthCredentials returned no error or tokenDetails");return{authorization:"Bearer "+kt(e.token)}}}_saveBasicOptions(e){this.method="basic",this.key=e.key,this.basicKey=kt(e.key),this.authOptions=e||{},"clientId"in e&&this._userSetClientId(e.clientId)}_saveTokenOptions(e,t){this.method="token",e&&(this.tokenParams=e),t&&(t.token&&(t.tokenDetails=typeof t.token=="string"?{token:t.token}:t.token),t.tokenDetails&&(this.tokenDetails=t.tokenDetails),"clientId"in t&&this._userSetClientId(t.clientId),this.authOptions=t)}async _ensureValidAuthCredentials(e){let t=this.tokenDetails;if(t){if(this._tokenClientIdMismatch(t.clientId))throw new C("Mismatch between clientId in token ("+t.clientId+") and current clientId ("+this.clientId+")",40102,403);if(!this.client.isTimeOffsetSet()||!t.expires||t.expires>=this.client.getTimestampUsingOffset())return c.logAction(this.logger,c.LOG_MINOR,"Auth.getToken()","using cached token; expires = "+t.expires),t;c.logAction(this.logger,c.LOG_MINOR,"Auth.getToken()","deleting expired token"),this.tokenDetails=null}let n=(this.waitingForTokenRequest||(this.waitingForTokenRequest=an.create(this.logger))).createPromise();if(this.currentTokenRequestId!==null&&!e)return n;let s=this.currentTokenRequestId=lo(),o,a=null;try{o=await this.requestToken(this.tokenParams,this.authOptions)}catch(f){a=f}if(this.currentTokenRequestId>s)return c.logAction(this.logger,c.LOG_MINOR,"Auth._ensureValidAuthCredentials()","Discarding token request response; overtaken by newer one"),n;this.currentTokenRequestId=null;let u=this.waitingForTokenRequest;return this.waitingForTokenRequest=null,a?(u?.rejectAll(a),n):(u?.resolveAll(this.tokenDetails=o),n)}_userSetClientId(e){if(typeof e=="string"||e===null){if(e==="*")throw new C('Can\u2019t use "*" as a clientId as that string is reserved. (To change the default token request behaviour to use a wildcard clientId, instantiate the library with {defaultTokenParams: {clientId: "*"}}), or if calling authorize(), pass it in as a tokenParam: authorize({clientId: "*"}, authOptions)',40012,400);{let t=this._uncheckedSetClientId(e);if(t)throw t}}else throw new C("clientId must be either a string or null",40012,400)}_uncheckedSetClientId(e){if(this._tokenClientIdMismatch(e)){let t="Unexpected clientId mismatch: client has "+this.clientId+", requested "+e,n=new C(t,40102,401);return c.logAction(this.logger,c.LOG_ERROR,"Auth._uncheckedSetClientId()",t),n}else return this.clientId=this.tokenParams.clientId=e,null}_tokenClientIdMismatch(e){return!!(this.clientId&&this.clientId!=="*"&&e&&e!=="*"&&this.clientId!==e)}static isTokenErr(e){return e.code&&e.code>=40140&&e.code<40150}revokeTokens(e,t){return this.client.rest.revokeTokens(e,t)}async _getTimestamp(e){return this.client.getTimestamp(e||!!this.authOptions.queryTime)}},ye=ho;function ln(e){let t=[];if(e)for(let n in e)t.push(n+"="+e[n]);return t.join("&")}function Ue(e,t){return e+(t?"?":"")+ln(t)}function uo(e,t,n,s,o){e.error?c.logActionNoStrip(o,c.LOG_MICRO,"Http."+t+"()","Received Error; "+Ue(n,s)+"; Error: "+G(e.error)):c.logActionNoStrip(o,c.LOG_MICRO,"Http."+t+"()","Received; "+Ue(n,s)+"; Headers: "+ln(e.headers)+"; StatusCode: "+e.statusCode+"; Body"+(b.BufferUtils.isBuffer(e.body)?" (Base64): "+b.BufferUtils.base64Encode(e.body):": "+e.body))}function fo(e,t,n,s,o){o.shouldLog(c.LOG_MICRO)&&c.logActionNoStrip(o,c.LOG_MICRO,"Http."+e+"()","Sending; "+Ue(t,s)+"; Body"+(b.BufferUtils.isBuffer(n)?" (Base64): "+b.BufferUtils.base64Encode(n):": "+n))}var hn=class{constructor(e){this.client=e,this.platformHttp=new b.Http(e),this.checkConnectivity=this.platformHttp.checkConnectivity?()=>this.platformHttp.checkConnectivity():void 0}get logger(){var e,t;return(t=(e=this.client)==null?void 0:e.logger)!=null?t:c.defaultLogger}get supportsAuthHeaders(){return this.platformHttp.supportsAuthHeaders}get supportsLinkHeaders(){return this.platformHttp.supportsLinkHeaders}_getHosts(e){let t=e.connection,n=t&&t.connectionManager.host;return n?[n].concat(L.getFallbackHosts(e.options)):L.getHosts(e.options)}async do(e,t,n,s,o){try{let a=this.client;if(!a)return{error:new C("http.do called without client",5e4,500)};let u=typeof t=="function"?t:function(w){return a.baseUri(w)+t},f=a._currentFallback;if(f)if(f.validUntil>Date.now()){let w=await this.doUri(e,u(f.host),n,s,o);return w.error&&this.platformHttp.shouldFallback(w.error)?(a._currentFallback=null,this.do(e,t,n,s,o)):w}else a._currentFallback=null;let E=this._getHosts(a);if(E.length===1)return this.doUri(e,u(E[0]),n,s,o);let g=null,A=async(w,v)=>{let R=w.shift();g=g??new Date;let T=await this.doUri(e,u(R),n,s,o);return T.error&&this.platformHttp.shouldFallback(T.error)&&w.length?Date.now()-g.getTime()>a.options.timeouts.httpMaxRetryDuration?{error:new C(`Timeout for trying fallback hosts retries. Total elapsed time exceeded the ${a.options.timeouts.httpMaxRetryDuration}ms limit`,50003,500)}:A(w,!0):(v&&(a._currentFallback={host:R,validUntil:Date.now()+a.options.timeouts.fallbackRetryTimeout}),T)};return A(E)}catch(a){return{error:new C(`Unexpected error in Http.do: ${G(a)}`,500,5e4)}}}async doUri(e,t,n,s,o){try{fo(e,t,s,o,this.logger);let a=await this.platformHttp.doUri(e,t,n,s,o);return this.logger.shouldLog(c.LOG_MICRO)&&uo(a,e,t,o,this.logger),a}catch(a){return{error:new C(`Unexpected error in Http.doUri: ${G(a)}`,500,5e4)}}}};function po(e,t,n,s){try{n.apply(t,s)}catch(o){c.logAction(e,c.LOG_ERROR,"EventEmitter.emit()","Unexpected listener exception: "+o+"; stack = "+(o&&o.stack))}}function un(e,t,n){let s,o,a;for(let u=0;u<e.length;u++)if(s=e[u],n&&(s=s[n]),Array.isArray(s)){for(;(o=s.indexOf(t))!==-1;)s.splice(o,1);n&&s.length===0&&delete e[u][n]}else if(xe(s))for(a in s)Object.prototype.hasOwnProperty.call(s,a)&&Array.isArray(s[a])&&un([s],t,a)}var go=class{constructor(e){this.logger=e,this.any=[],this.events=Object.create(null),this.anyOnce=[],this.eventsOnce=Object.create(null)}on(...e){if(e.length===1){let t=e[0];if(typeof t=="function")this.any.push(t);else throw new Error("EventListener.on(): Invalid arguments: "+b.Config.inspect(e))}if(e.length===2){let[t,n]=e;if(typeof n!="function")throw new Error("EventListener.on(): Invalid arguments: "+b.Config.inspect(e));if(ce(t))this.any.push(n);else if(Array.isArray(t))t.forEach(s=>{this.on(s,n)});else{if(typeof t!="string")throw new Error("EventListener.on(): Invalid arguments: "+b.Config.inspect(e));(this.events[t]||(this.events[t]=[])).push(n)}}}off(...e){if(e.length==0||ce(e[0])&&ce(e[1])){this.any=[],this.events=Object.create(null),this.anyOnce=[],this.eventsOnce=Object.create(null);return}let[t,n]=e,s=null,o=null;if(e.length===1||!n)typeof t=="function"?s=t:o=t;else{if(typeof n!="function")throw new Error("EventEmitter.off(): invalid arguments:"+b.Config.inspect(e));[o,s]=[t,n]}if(s&&ce(o)){un([this.any,this.events,this.anyOnce,this.eventsOnce],s);return}if(Array.isArray(o)){o.forEach(a=>{this.off(a,s)});return}if(typeof o!="string")throw new Error("EventEmitter.off(): invalid arguments:"+b.Config.inspect(e));s?un([this.events,this.eventsOnce],s,o):(delete this.events[o],delete this.eventsOnce[o])}listeners(e){if(e){let t=this.events[e]||[];return this.eventsOnce[e]&&Array.prototype.push.apply(t,this.eventsOnce[e]),t.length?t:null}return this.any.length?this.any:null}emit(e,...t){let n={event:e},s=[];this.anyOnce.length&&(Array.prototype.push.apply(s,this.anyOnce),this.anyOnce=[]),this.any.length&&Array.prototype.push.apply(s,this.any);let o=this.eventsOnce[e];o&&(Array.prototype.push.apply(s,o),delete this.eventsOnce[e]);let a=this.events[e];a&&Array.prototype.push.apply(s,a),s.forEach(u=>{po(this.logger,n,u,t)})}once(...e){let t=e.length;if(t===0||t===1&&typeof e[0]!="function"){let o=e[0];return new Promise(a=>{this.once(o,a)})}let[n,s]=e;if(e.length===1&&typeof n=="function")this.anyOnce.push(n);else if(ce(n)){if(typeof s!="function")throw new Error("EventEmitter.once(): Invalid arguments:"+b.Config.inspect(e));this.anyOnce.push(s)}else if(Array.isArray(n)){let o=this,a=function(){let u=Array.prototype.slice.call(arguments);if(n.forEach(function(f){o.off(f,a)}),typeof s!="function")throw new Error("EventEmitter.once(): Invalid arguments:"+b.Config.inspect(e));s.apply(this,u)};n.forEach(function(u){o.on(u,a)})}else{if(typeof n!="string")throw new Error("EventEmitter.once(): Invalid arguments:"+b.Config.inspect(e));let o=this.eventsOnce[n]||(this.eventsOnce[n]=[]);if(s){if(typeof s!="function")throw new Error("EventEmitter.once(): Invalid arguments:"+b.Config.inspect(e));o.push(s)}}}async whenState(e,t){if(typeof e!="string"||typeof t!="string")throw new Error("whenState requires a valid state String argument");return e===t?null:this.once(e)}},$=go,P={HEARTBEAT:0,ACK:1,NACK:2,CONNECT:3,CONNECTED:4,DISCONNECT:5,DISCONNECTED:6,CLOSE:7,CLOSED:8,ERROR:9,ATTACH:10,ATTACHED:11,DETACH:12,DETACHED:13,PRESENCE:14,MESSAGE:15,SYNC:16,AUTH:17,ACTIVATE:18,OBJECT:19,OBJECT_SYNC:20,ANNOTATION:21},ji=[];Object.keys(P).forEach(function(e){ji[P[e]]=e});var Z={HAS_PRESENCE:1,HAS_BACKLOG:2,RESUMED:4,TRANSIENT:16,ATTACH_RESUME:32,HAS_OBJECTS:128,PRESENCE:65536,PUBLISH:1<<17,SUBSCRIBE:1<<18,PRESENCE_SUBSCRIBE:1<<19,ANNOTATION_PUBLISH:1<<21,ANNOTATION_SUBSCRIBE:1<<22,OBJECT_SUBSCRIBE:1<<24,OBJECT_PUBLISH:1<<25},mo=Object.keys(Z);Z.MODE_ALL=Z.PRESENCE|Z.PUBLISH|Z.SUBSCRIBE|Z.PRESENCE_SUBSCRIBE|Z.ANNOTATION_PUBLISH|Z.ANNOTATION_SUBSCRIBE|Z.OBJECT_SUBSCRIBE|Z.OBJECT_PUBLISH;var Wi=["PRESENCE","PUBLISH","SUBSCRIBE","PRESENCE_SUBSCRIBE","ANNOTATION_PUBLISH","ANNOTATION_SUBSCRIBE","OBJECT_SUBSCRIBE","OBJECT_PUBLISH"];function yo(e){return!e||!e.channelOptions?{channelOptions:e,plugins:{},baseEncodedPreviousPayload:void 0}:e}function Ki(e,t,n){if(n&&n.cipher){e||Q("Crypto");let s=e.getCipher(n.cipher,t);return{cipher:s.cipherParams,channelCipher:s.cipher}}return n??{}}async function Eo(e,t){let{data:n,encoding:s}=await $i(e.data,e.encoding,t);return e.data=n,e.encoding=s,e}async function $i(e,t,n){let s=n.channelCipher,o=e,a=t?t+"/":"";b.BufferUtils.isBuffer(o)||(o=b.BufferUtils.utf8Encode(String(o)),a=a+"utf-8/");let u=await s.encrypt(o);return a=a+"cipher+"+s.algorithm,{data:u,encoding:a}}async function dn(e,t){let n=typeof e.data=="string"||b.BufferUtils.isBuffer(e.data)||e.data===null||e.data===void 0,{data:s,encoding:o}=zi(e.data,e.encoding,n);return e.data=s,e.encoding=o,t!=null&&t.cipher?Eo(e,t):e}function zi(e,t,n){if(n)return{data:e,encoding:t};if(xe(e)||Array.isArray(e))return{data:JSON.stringify(e),encoding:t?t+"/json":"json"};throw new C("Data type is unsupported",40013,400)}async function fn(e,t){let{data:n,encoding:s,error:o}=await Ji(e.data,e.encoding,t);if(e.data=n,e.encoding=s,o)throw o}async function Ji(e,t,n){let s=yo(n),o=e,a=e,u=t,f;if(t){let E=t.split("/"),g,A=E.length,w="";try{for(;(g=A)>0;){let v=E[--A].match(/([-\w]+)(\+([\w-]+))?/);if(!v)break;switch(w=v[1],w){case"base64":a=b.BufferUtils.base64Decode(String(a)),g==E.length&&(o=a);continue;case"utf-8":a=b.BufferUtils.utf8Decode(a);continue;case"json":a=JSON.parse(a);continue;case"cipher":if(s.channelOptions!=null&&s.channelOptions.cipher&&s.channelOptions.channelCipher){let R=v[3],T=s.channelOptions.channelCipher;if(R!=T.algorithm)throw new Error("Unable to decrypt message with given cipher; incompatible cipher params");a=await T.decrypt(a);continue}else throw new Error("Unable to decrypt message; not an encrypted channel");case"vcdiff":if(!s.plugins||!s.plugins.vcdiff)throw new C("Missing Vcdiff decoder (https://github.com/ably-forks/vcdiff-decoder)",40019,400);if(typeof Uint8Array>"u")throw new C("Delta decoding not supported on this browser (need ArrayBuffer & Uint8Array)",40020,400);try{let R=s.baseEncodedPreviousPayload;typeof R=="string"&&(R=b.BufferUtils.utf8Encode(R));let T=b.BufferUtils.toBuffer(R);a=b.BufferUtils.toBuffer(a),a=b.BufferUtils.arrayBufferViewToBuffer(s.plugins.vcdiff.decode(a,T)),o=a}catch(R){throw new C("Vcdiff delta decode failed with "+R,40018,400)}continue;default:throw new Error("Unknown encoding")}}}catch(v){let R=v;f=new C(`Error processing the ${w} encoding, decoder returned \u2018${R.message}\u2019`,R.code||40013,400)}finally{u=g<=0?null:E.slice(0,g).join("/")}}return f?{error:f,data:a,encoding:u}:(s.baseEncodedPreviousPayload=o,{data:a,encoding:u})}function pn(...e){let t=e.length>0?"json":"msgpack",{data:n,encoding:s}=Qi(this.data,this.encoding,t);return Object.assign({},this,{encoding:s,data:n})}function Qi(e,t,n){return!e||!b.BufferUtils.isBuffer(e)?{data:e,encoding:t}:n==="msgpack"?{data:b.BufferUtils.toBuffer(e),encoding:t}:{data:b.BufferUtils.base64Encode(e),encoding:t?t+"/base64":"base64"}}var Ut={encryptData:$i,encodeData:zi,encodeDataForWire:Qi,decodeData:Ji};function Bt(e){let{id:t,connectionId:n,timestamp:s}=e,o;switch(e.action){case P.MESSAGE:{o=e.messages;break}case P.PRESENCE:case P.SYNC:o=e.presence;break;case P.ANNOTATION:o=e.annotations;break;case P.OBJECT:case P.OBJECT_SYNC:o=e.state;break;default:throw new C("Unexpected action "+e.action,4e4,400)}for(let a=0;a<o.length;a++){let u=o[a];u.connectionId||(u.connectionId=n),u.timestamp||(u.timestamp=s),t&&!u.id&&(u.id=t+":"+a)}}function Be(e,t){let n="["+t;for(let s in e)s==="data"?typeof e.data=="string"?n+="; data="+e.data:b.BufferUtils.isBuffer(e.data)?n+="; data (buffer)="+b.BufferUtils.base64Encode(e.data):typeof e.data<"u"&&(n+="; data (json)="+JSON.stringify(e.data)):s&&(s==="extras"||s==="operation")?n+="; "+s+"="+JSON.stringify(e[s]):e[s]!==void 0&&(n+="; "+s+"="+e[s]);return n+="]",n}var De=class{},Yi=class{constructor(e){this.Platform=b,this.ErrorInfo=C,this.Logger=c,this.Defaults=L,this.Utils=Ne,this.EventEmitter=$,this.MessageEncoding=Ut;var t,n,s,o,a,u,f,E,g,A;this._additionalHTTPRequestImplementations=(t=e.plugins)!=null?t:null,this.logger=new c,this.logger.setLog(e.logLevel,e.logHandler),c.logAction(this.logger,c.LOG_MICRO,"BaseClient()","initialized with clientOptions "+b.Config.inspect(e)),this._MsgPack=(s=(n=e.plugins)==null?void 0:n.MsgPack)!=null?s:null;let w=this.options=L.normaliseOptions(e,this._MsgPack,this.logger);if(w.key){let v=w.key.match(/^([^:\s]+):([^:.\s]+)$/);if(!v){let R="invalid key parameter";throw c.logAction(this.logger,c.LOG_ERROR,"BaseClient()",R),new C(R,40400,404)}w.keyName=v[1],w.keySecret=v[2]}if("clientId"in w)if(typeof w.clientId=="string"||w.clientId===null){if(w.clientId==="*")throw new C('Can\u2019t use "*" as a clientId as that string is reserved. (To change the default token request behaviour to use a wildcard clientId, use {defaultTokenParams: {clientId: "*"}})',40012,400)}else throw new C("clientId must be either a string or null",40012,400);c.logAction(this.logger,c.LOG_MINOR,"BaseClient()","started; version = "+L.version),this._currentFallback=null,this.serverTimeOffset=null,this.http=new hn(this),this.auth=new ye(this,w),this._rest=(o=e.plugins)!=null&&o.Rest?new e.plugins.Rest(this):null,this._Crypto=(u=(a=e.plugins)==null?void 0:a.Crypto)!=null?u:null,this.__FilteredSubscriptions=(E=(f=e.plugins)==null?void 0:f.MessageInteractions)!=null?E:null,this._Annotations=(A=(g=e.plugins)==null?void 0:g.Annotations)!=null?A:null}get rest(){return this._rest||Q("Rest"),this._rest}get _FilteredSubscriptions(){return this.__FilteredSubscriptions||Q("MessageInteractions"),this.__FilteredSubscriptions}get channels(){return this.rest.channels}get push(){return this.rest.push}device(){var e;return(!((e=this.options.plugins)!=null&&e.Push)||!this.push.LocalDevice)&&Q("Push"),this._device||(this._device=this.push.LocalDevice.load(this)),this._device}baseUri(e){return L.getHttpScheme(this.options)+e+":"+L.getPort(this.options,!1)}async stats(e){return this.rest.stats(e)}async time(e){return this.rest.time(e)}async request(e,t,n,s,o,a){return this.rest.request(e,t,n,s,o,a)}batchPublish(e){return this.rest.batchPublish(e)}batchPresence(e){return this.rest.batchPresence(e)}setLog(e){this.logger.setLog(e.level,e.handler)}async getTimestamp(e){return!this.isTimeOffsetSet()&&e?this.time():this.getTimestampUsingOffset()}getTimestampUsingOffset(){return Date.now()+(this.serverTimeOffset||0)}isTimeOffsetSet(){return this.serverTimeOffset!==null}};Yi.Platform=b;var Xi=Yi,Co=class Qe{toJSON(){var t,n,s;return{id:this.id,deviceSecret:this.deviceSecret,platform:this.platform,formFactor:this.formFactor,clientId:this.clientId,metadata:this.metadata,deviceIdentityToken:this.deviceIdentityToken,push:{recipient:(t=this.push)==null?void 0:t.recipient,state:(n=this.push)==null?void 0:n.state,error:(s=this.push)==null?void 0:s.error}}}toString(){var t,n,s,o;let a="[DeviceDetails";return this.id&&(a+="; id="+this.id),this.platform&&(a+="; platform="+this.platform),this.formFactor&&(a+="; formFactor="+this.formFactor),this.clientId&&(a+="; clientId="+this.clientId),this.metadata&&(a+="; metadata="+this.metadata),this.deviceIdentityToken&&(a+="; deviceIdentityToken="+JSON.stringify(this.deviceIdentityToken)),(t=this.push)!=null&&t.recipient&&(a+="; push.recipient="+JSON.stringify(this.push.recipient)),(n=this.push)!=null&&n.state&&(a+="; push.state="+this.push.state),(s=this.push)!=null&&s.error&&(a+="; push.error="+JSON.stringify(this.push.error)),(o=this.push)!=null&&o.metadata&&(a+="; push.metadata="+this.push.metadata),a+="]",a}static toRequestBody(t,n,s){return le(t,n,s)}static fromResponseBody(t,n,s){return s&&(t=ne(t,n,s)),Array.isArray(t)?Qe.fromValuesArray(t):Qe.fromValues(t)}static fromValues(t){return t.error=t.error&&C.fromValues(t.error),Object.assign(new Qe,t)}static fromLocalDevice(t){return Object.assign(new Qe,t)}static fromValuesArray(t){let n=t.length,s=new Array(n);for(let o=0;o<n;o++)s[o]=Qe.fromValues(t[o]);return s}},Fe=Co;async function Zi(e,t,n,s){if(e.http.supportsAuthHeaders){let o=await e.auth.getAuthHeaders();return s(B(o,t),n)}else{let o=await e.auth.getAuthParams();return s(t,B(o,n))}}function So(e,t,n){if(e.err&&!e.body)return{err:e.err};if(e.statusCode===xt.NoContent)return H(O({},e),{body:[],unpacked:!0});let s=e.body;if(!e.unpacked)try{s=ne(s,t,n)}catch(f){return tn(f)?{err:f}:{err:new J(G(f),null)}}if(!s)return{err:new J("unenvelope(): Response body is missing",null)};let{statusCode:o,response:a,headers:u}=s;if(o===void 0)return H(O({},e),{body:s,unpacked:!0});if(o<200||o>=300){let f=a&&a.error||e.err;return f||(f=new Error("Error in unenveloping "+s),f.statusCode=o),{err:f,body:a,headers:u,unpacked:!0,statusCode:o}}return{err:e.err,body:a,headers:u,unpacked:!0,statusCode:o}}function Ro(e,t,n,s,o){e.err?c.logAction(o,c.LOG_MICRO,"Resource."+t+"()","Received Error; "+Ue(n,s)+"; Error: "+G(e.err)):c.logAction(o,c.LOG_MICRO,"Resource."+t+"()","Received; "+Ue(n,s)+"; Headers: "+ln(e.headers)+"; StatusCode: "+e.statusCode+"; Body: "+(b.BufferUtils.isBuffer(e.body)?" (Base64): "+b.BufferUtils.base64Encode(e.body):": "+b.Config.inspect(e.body)))}var Ao=class Ye{static async get(t,n,s,o,a,u){return Ye.do(V.Get,t,n,null,s,o,a,u??!1)}static async delete(t,n,s,o,a,u){return Ye.do(V.Delete,t,n,null,s,o,a,u)}static async post(t,n,s,o,a,u,f){return Ye.do(V.Post,t,n,s,o,a,u,f)}static async patch(t,n,s,o,a,u,f){return Ye.do(V.Patch,t,n,s,o,a,u,f)}static async put(t,n,s,o,a,u,f){return Ye.do(V.Put,t,n,s,o,a,u,f)}static async do(t,n,s,o,a,u,f,E){f&&((u=u||{}).envelope=f);let g=n.logger;async function A(v,R){var T;if(g.shouldLog(c.LOG_MICRO)){let N=o;if(((T=v["content-type"])==null?void 0:T.indexOf("msgpack"))>0)try{n._MsgPack||Q("MsgPack"),N=n._MsgPack.decode(o)}catch(D){c.logAction(g,c.LOG_MICRO,"Resource."+t+"()","Sending MsgPack Decoding Error: "+G(D))}c.logAction(g,c.LOG_MICRO,"Resource."+t+"()","Sending; "+Ue(s,R)+"; Body: "+N)}let _=await n.http.do(t,s,v,o,R);return _.error&&ye.isTokenErr(_.error)?(await n.auth.authorize(null,null),Zi(n,v,R,A)):{err:_.error,body:_.body,headers:_.headers,unpacked:_.unpacked,statusCode:_.statusCode}}let w=await Zi(n,a,u,A);if(f&&(w=So(w,n._MsgPack,f)),g.shouldLog(c.LOG_MICRO)&&Ro(w,t,s,u,g),E){if(w.err)throw w.err;{let v=O({},w);return delete v.err,v}}return w}},W=Ao;function wo(e){let t=e.match(/^\.\/(\w+)\?(.*)$/);return t&&t[2]&&_t(t[2])}function bo(e){typeof e=="string"&&(e=e.split(","));let t={};for(let n=0;n<e.length;n++){let s=e[n].match(/^\s*<(.+)>;\s*rel="(\w+)"$/);if(s){let o=wo(s[1]);o&&(t[s[2]]=o)}}return t}function vo(e,t,n){return!(n&&(t||typeof e.code=="number"))}var Io=class{constructor(e,t,n,s,o,a){this.client=e,this.path=t,this.headers=n,this.envelope=s??null,this.bodyHandler=o,this.useHttpPaginatedResponse=a||!1}get logger(){return this.client.logger}async get(e){let t=await W.get(this.client,this.path,this.headers,e,this.envelope,!1);return this.handlePage(t)}async delete(e){let t=await W.delete(this.client,this.path,this.headers,e,this.envelope,!1);return this.handlePage(t)}async post(e,t){let n=await W.post(this.client,this.path,t,this.headers,e,this.envelope,!1);return this.handlePage(n)}async put(e,t){let n=await W.put(this.client,this.path,t,this.headers,e,this.envelope,!1);return this.handlePage(n)}async patch(e,t){let n=await W.patch(this.client,this.path,t,this.headers,e,this.envelope,!1);return this.handlePage(n)}async handlePage(e){if(e.err&&vo(e.err,e.body,this.useHttpPaginatedResponse))throw c.logAction(this.logger,c.LOG_ERROR,"PaginatedResource.handlePage()","Unexpected error getting resource: err = "+G(e.err)),e.err;let t,n,s;try{t=e.statusCode==xt.NoContent?[]:await this.bodyHandler(e.body,e.headers||{},e.unpacked)}catch(o){throw e.err||o}return e.headers&&(n=e.headers.Link||e.headers.link)&&(s=bo(n)),this.useHttpPaginatedResponse?new Oo(this,t,e.headers||{},e.statusCode,s,e.err):new es(this,t,s)}},es=class{constructor(e,t,n){this.resource=e,this.items=t,this._relParams=n}async first(){if(this.hasFirst())return this.get(this._relParams.first);throw new C("No link to the first page of results",40400,404)}async current(){if(this.hasCurrent())return this.get(this._relParams.current);throw new C("No link to the current page of results",40400,404)}async next(){return this.hasNext()?this.get(this._relParams.next):null}hasFirst(){return this._relParams!=null&&"first"in this._relParams}hasCurrent(){return this._relParams!=null&&"current"in this._relParams}hasNext(){return this._relParams!=null&&"next"in this._relParams}isLast(){return!this.hasNext()}async get(e){let t=this.resource,n=await W.get(t.client,t.path,t.headers,e,t.envelope,!1);return t.handlePage(n)}},Oo=class extends es{constructor(e,t,n,s,o,a){super(e,t,o),this.statusCode=s,this.success=s<300&&s>=200,this.headers=n,this.errorCode=a&&a.code,this.errorMessage=a&&a.message}toJSON(){return{items:this.items,statusCode:this.statusCode,success:this.success,headers:this.headers,errorCode:this.errorCode,errorMessage:this.errorMessage}}},de=Io,ts=class Et{toJSON(){return{channel:this.channel,deviceId:this.deviceId,clientId:this.clientId}}toString(){let t="[PushChannelSubscription";return this.channel&&(t+="; channel="+this.channel),this.deviceId&&(t+="; deviceId="+this.deviceId),this.clientId&&(t+="; clientId="+this.clientId),t+="]",t}static fromResponseBody(t,n,s){return s&&(t=ne(t,n,s)),Array.isArray(t)?Et.fromValuesArray(t):Et.fromValues(t)}static fromValues(t){return Object.assign(new Et,t)}static fromValuesArray(t){let n=t.length,s=new Array(n);for(let o=0;o<n;o++)s[o]=Et.fromValues(t[o]);return s}};ts.toRequestBody=le;var To=ts,Dt=To,_o=class{constructor(e){var t;this.client=e,this.admin=new Mo(e),b.Config.push&&((t=e.options.plugins)!=null&&t.Push)&&(this.stateMachine=new e.options.plugins.Push.ActivationStateMachine(e),this.LocalDevice=e.options.plugins.Push.localDeviceFactory(Fe))}async activate(e,t){await new Promise((n,s)=>{var o;if(!((o=this.client.options.plugins)!=null&&o.Push)){s(Pt("Push"));return}if(!this.stateMachine){s(new C("This platform is not supported as a target of push notifications",4e4,400));return}if(this.stateMachine.activatedCallback){s(new C("Activation already in progress",4e4,400));return}this.stateMachine.activatedCallback=a=>{if(a){s(a);return}n()},this.stateMachine.updateFailedCallback=t,this.stateMachine.handleEvent(new this.client.options.plugins.Push.CalledActivate(this.stateMachine,e))})}async deactivate(e){await new Promise((t,n)=>{var s;if(!((s=this.client.options.plugins)!=null&&s.Push)){n(Pt("Push"));return}if(!this.stateMachine){n(new C("This platform is not supported as a target of push notifications",4e4,400));return}if(this.stateMachine.deactivatedCallback){n(new C("Deactivation already in progress",4e4,400));return}this.stateMachine.deactivatedCallback=o=>{if(o){n(o);return}t()},this.stateMachine.handleEvent(new this.client.options.plugins.Push.CalledDeactivate(this.stateMachine,e))})}},Mo=class{constructor(e){this.client=e,this.deviceRegistrations=new ko(e),this.channelSubscriptions=new Po(e)}async publish(e,t){let n=this.client,s=n.options.useBinaryProtocol?"msgpack":"json",o=L.defaultPostHeaders(n.options,{format:s}),a={},u=B({recipient:e},t);B(o,n.options.headers),n.options.pushFullWait&&B(a,{fullWait:"true"});let f=le(u,n._MsgPack,s);await W.post(n,"/push/publish",f,o,a,null,!0)}},ko=class{constructor(e){this.client=e}async save(e){let t=this.client,n=Fe.fromValues(e),s=t.options.useBinaryProtocol?"msgpack":"json",o=L.defaultPostHeaders(t.options,{format:s}),a={};B(o,t.options.headers),t.options.pushFullWait&&B(a,{fullWait:"true"});let u=le(n,t._MsgPack,s),f=await W.put(t,"/push/deviceRegistrations/"+encodeURIComponent(e.id),u,o,a,null,!0);return Fe.fromResponseBody(f.body,t._MsgPack,f.unpacked?void 0:s)}async get(e){let t=this.client,n=t.options.useBinaryProtocol?"msgpack":"json",s=L.defaultGetHeaders(t.options,{format:n}),o=e.id||e;if(typeof o!="string"||!o.length)throw new C("First argument to DeviceRegistrations#get must be a deviceId string or DeviceDetails",4e4,400);B(s,t.options.headers);let a=await W.get(t,"/push/deviceRegistrations/"+encodeURIComponent(o),s,{},null,!0);return Fe.fromResponseBody(a.body,t._MsgPack,a.unpacked?void 0:n)}async list(e){let t=this.client,n=t.options.useBinaryProtocol?"msgpack":"json",s=this.client.http.supportsLinkHeaders?void 0:n,o=L.defaultGetHeaders(t.options,{format:n});return B(o,t.options.headers),new de(t,"/push/deviceRegistrations",o,s,async function(a,u,f){return Fe.fromResponseBody(a,t._MsgPack,f?void 0:n)}).get(e)}async remove(e){let t=this.client,n=t.options.useBinaryProtocol?"msgpack":"json",s=L.defaultGetHeaders(t.options,{format:n}),o={},a=e.id||e;if(typeof a!="string"||!a.length)throw new C("First argument to DeviceRegistrations#remove must be a deviceId string or DeviceDetails",4e4,400);B(s,t.options.headers),t.options.pushFullWait&&B(o,{fullWait:"true"}),await W.delete(t,"/push/deviceRegistrations/"+encodeURIComponent(a),s,o,null,!0)}async removeWhere(e){let t=this.client,n=t.options.useBinaryProtocol?"msgpack":"json",s=L.defaultGetHeaders(t.options,{format:n});B(s,t.options.headers),t.options.pushFullWait&&B(e,{fullWait:"true"}),await W.delete(t,"/push/deviceRegistrations",s,e,null,!0)}},Po=class br{constructor(t){this.remove=br.prototype.removeWhere,this.client=t}async save(t){let n=this.client,s=Dt.fromValues(t),o=n.options.useBinaryProtocol?"msgpack":"json",a=L.defaultPostHeaders(n.options,{format:o}),u={};B(a,n.options.headers),n.options.pushFullWait&&B(u,{fullWait:"true"});let f=le(s,n._MsgPack,o),E=await W.post(n,"/push/channelSubscriptions",f,a,u,null,!0);return Dt.fromResponseBody(E.body,n._MsgPack,E.unpacked?void 0:o)}async list(t){let n=this.client,s=n.options.useBinaryProtocol?"msgpack":"json",o=this.client.http.supportsLinkHeaders?void 0:s,a=L.defaultGetHeaders(n.options,{format:s});return B(a,n.options.headers),new de(n,"/push/channelSubscriptions",a,o,async function(u,f,E){return Dt.fromResponseBody(u,n._MsgPack,E?void 0:s)}).get(t)}async removeWhere(t){let n=this.client,s=n.options.useBinaryProtocol?"msgpack":"json",o=L.defaultGetHeaders(n.options,{format:s});B(o,n.options.headers),n.options.pushFullWait&&B(t,{fullWait:"true"}),await W.delete(n,"/push/channelSubscriptions",o,t,null,!0)}async listChannels(t){let n=this.client,s=n.options.useBinaryProtocol?"msgpack":"json",o=this.client.http.supportsLinkHeaders?void 0:s,a=L.defaultGetHeaders(n.options,{format:s});return B(a,n.options.headers),n.options.pushFullWait&&B(t,{fullWait:"true"}),new de(n,"/push/channels",a,o,async function(u,f,E){let g=!E&&s?ne(u,n._MsgPack,s):u;for(let A=0;A<g.length;A++)g[A]=String(g[A]);return g}).get(t)}},No=_o,ns=["absent","present","enter","leave","update"];async function is(e,t,n,s){let o=Ki(t,e,s??null);return it.fromValues(n).decode(o,e)}async function Lo(e,t,n,s){return Promise.all(n.map(function(o){return is(e,t,o,s)}))}async function xo(e,t){return it.fromValues(e).decode(t.channelOptions,t.logger)}async function ss(e,t){return Promise.all(e.map(function(n){return xo(n,t)}))}var rs=class Ct extends De{isSynthesized(){return!this.id||!this.connectionId?!0:this.id.substring(this.connectionId.length,0)!==this.connectionId}parseId(){if(!this.id)throw new Error("parseId(): Presence message does not contain an id");let t=this.id.split(":");return{connectionId:t[0],msgSerial:parseInt(t[1],10),index:parseInt(t[2],10)}}async encode(t){let n=Object.assign(new it,this,{action:ns.indexOf(this.action||"present")});return dn(n,t)}static fromValues(t){return Object.assign(new Ct,t)}static fromValuesArray(t){return t.map(n=>Ct.fromValues(n))}static fromData(t){return t instanceof Ct?t:Ct.fromValues({data:t})}toString(){return Be(this,"PresenceMessage")}},it=class Xn extends De{toJSON(...t){return pn.call(this,...t)}static fromValues(t){return Object.assign(new Xn,t)}static fromValuesArray(t){return t.map(n=>Xn.fromValues(n))}async decode(t,n){let s=Object.assign(new rs,H(O({},this),{action:ns[this.action]}));try{await fn(s,t)}catch(o){c.logAction(n,c.LOG_ERROR,"WirePresenceMessage.decode()",G(o))}return s}toString(){return Be(this,"WirePresenceMessage")}},Ee=rs,Uo=class{constructor(e){this.channel=e}get logger(){return this.channel.logger}async get(e){c.logAction(this.logger,c.LOG_MICRO,"RestPresence.get()","channel = "+this.channel.name);let t=this.channel.client,n=t.options.useBinaryProtocol?"msgpack":"json",s=this.channel.client.http.supportsLinkHeaders?void 0:n,o=L.defaultGetHeaders(t.options,{format:n});return B(o,t.options.headers),new de(t,this.channel.client.rest.presenceMixin.basePath(this),o,s,async(a,u,f)=>{let E=f?a:ne(a,t._MsgPack,n);return ss(E,this.channel)}).get(e)}async history(e){return c.logAction(this.logger,c.LOG_MICRO,"RestPresence.history()","channel = "+this.channel.name),this.channel.client.rest.presenceMixin.history(this,e)}},Bo=Uo,os=["message.create","message.update","message.delete","meta","message.summary"];function Do(e){return os[e||0]||"unknown"}function Fo(e){let t=0;return e.name&&(t+=e.name.length),e.clientId&&(t+=e.clientId.length),e.extras&&(t+=JSON.stringify(e.extras).length),e.data&&(t+=Si(e.data)),t}async function as(e,t,n,s){let o=Ki(t,e,s??null);return st.fromValues(n).decode(o,e)}async function Go(e,t,n,s){return Promise.all(n.map(function(o){return as(e,t,o,s)}))}async function qo(e,t){return st.fromValues(e).decode(t.channelOptions,t.logger)}async function Ho(e,t){return Promise.all(e.map(function(n){return qo(n,t)}))}async function cs(e,t){return Promise.all(e.map(n=>n.encode(t)))}var Vo=le;function gn(e){let t,n=0;for(let s=0;s<e.length;s++)t=e[s],n+=t.size||(t.size=Fo(t));return n}var ls=class Zn extends De{expandFields(){this.action==="message.create"&&(this.version&&!this.serial&&(this.serial=this.version),this.timestamp&&!this.createdAt&&(this.createdAt=this.timestamp))}async encode(t){let n=Object.assign(new st,this,{action:os.indexOf(this.action||"message.create")});return dn(n,t)}static fromValues(t){return Object.assign(new Zn,t)}static fromValuesArray(t){return t.map(n=>Zn.fromValues(n))}toString(){return Be(this,"Message")}},st=class ei extends De{toJSON(...t){return pn.call(this,...t)}static fromValues(t){return Object.assign(new ei,t)}static fromValuesArray(t){return t.map(n=>ei.fromValues(n))}async decodeWithErr(t,n){let s=Object.assign(new ls,H(O({},this),{action:Do(this.action)})),o;try{await fn(s,t)}catch(a){c.logAction(n,c.LOG_ERROR,"WireMessage.decode()",G(a)),o=a}return s.expandFields(),{decoded:s,err:o}}async decode(t,n){let{decoded:s}=await this.decodeWithErr(t,n);return s}toString(){return Be(this,"WireMessage")}},Re=ls,jo=9;function Wo(e){return e.every(function(t){return!t.id})}var Ko=class{constructor(e,t,n){this._annotations=null;var s,o;c.logAction(e.logger,c.LOG_MINOR,"RestChannel()","started; name = "+t),this.name=t,this.client=e,this.presence=new Bo(this),this.channelOptions=Nt((s=e._Crypto)!=null?s:null,this.logger,n),(o=e.options.plugins)!=null&&o.Push&&(this._push=new e.options.plugins.Push.PushChannel(this)),e._Annotations&&(this._annotations=new e._Annotations.RestAnnotations(this))}get annotations(){return this._annotations||Q("Annotations"),this._annotations}get push(){return this._push||Q("Push"),this._push}get logger(){return this.client.logger}setOptions(e){var t;this.channelOptions=Nt((t=this.client._Crypto)!=null?t:null,this.logger,e)}async history(e){return c.logAction(this.logger,c.LOG_MICRO,"RestChannel.history()","channel = "+this.name),this.client.rest.channelMixin.history(this,e)}async publish(...e){let t=e[0],n=e[1],s,o;if(typeof t=="string"||t===null)s=[Re.fromValues({name:t,data:n})],o=e[2];else if(xe(t))s=[Re.fromValues(t)],o=e[1];else if(Array.isArray(t))s=Re.fromValuesArray(t),o=e[1];else throw new C("The single-argument form of publish() expects a message object or an array of message objects",40013,400);o||(o={});let a=this.client,u=a.options,f=u.useBinaryProtocol?"msgpack":"json",E=a.options.idempotentRestPublishing,g=L.defaultPostHeaders(a.options,{format:f});if(B(g,u.headers),E&&Wo(s)){let R=await Ri(jo);s.forEach(function(T,_){T.id=R+":"+_.toString()})}let A=await cs(s,this.channelOptions),w=gn(A),v=u.maxMessageSize;if(w>v)throw new C(`Maximum size of messages that can be published at once exceeded (was ${w} bytes; limit is ${v} bytes)`,40009,400);await this._publish(Vo(A,a._MsgPack,f),g,o)}async _publish(e,t,n){await W.post(this.client,this.client.rest.channelMixin.basePath(this)+"/messages",e,t,n,null,!0)}async status(){return this.client.rest.channelMixin.status(this)}},$o=Ko,zo=class vr{constructor(t){this.entries=t&&t.entries||void 0,this.schema=t&&t.schema||void 0,this.appId=t&&t.appId||void 0,this.inProgress=t&&t.inProgress||void 0,this.unit=t&&t.unit||void 0,this.intervalId=t&&t.intervalId||void 0}static fromValues(t){return new vr(t)}},Jo=zo,hs=class{static basePath(e){return"/channels/"+encodeURIComponent(e.name)}static history(e,t){let n=e.client,s=n.options.useBinaryProtocol?"msgpack":"json",o=e.client.http.supportsLinkHeaders?void 0:s,a=L.defaultGetHeaders(n.options,{format:s});return B(a,n.options.headers),new de(n,this.basePath(e)+"/messages",a,o,async function(u,f,E){let g=E?u:ne(u,n._MsgPack,s);return Ho(g,e)}).get(t)}static async status(e){let t=e.client.options.useBinaryProtocol?"msgpack":"json",n=L.defaultPostHeaders(e.client.options,{format:t});return(await W.get(e.client,this.basePath(e),n,{},t,!0)).body}},Qo=class{static basePath(e){return hs.basePath(e.channel)+"/presence"}static async history(e,t){let n=e.channel.client,s=n.options.useBinaryProtocol?"msgpack":"json",o=e.channel.client.http.supportsLinkHeaders?void 0:s,a=L.defaultGetHeaders(n.options,{format:s});return B(a,n.options.headers),new de(n,this.basePath(e)+"/history",a,o,async(u,f,E)=>{let g=E?u:ne(u,n._MsgPack,s);return ss(g,e.channel)}).get(t)}},us=class{constructor(e){this.channelMixin=hs,this.presenceMixin=Qo,this.Resource=W,this.PaginatedResource=de,this.DeviceDetails=Fe,this.PushChannelSubscription=Dt,this.client=e,this.channels=new Yo(this.client),this.push=new No(this.client)}async stats(e){let t=L.defaultGetHeaders(this.client.options),n=this.client.options.useBinaryProtocol?"msgpack":"json",s=this.client.http.supportsLinkHeaders?void 0:n;return B(t,this.client.options.headers),new de(this.client,"/stats",t,s,function(o,a,u){let f=u?o:JSON.parse(o);for(let E=0;E<f.length;E++)f[E]=Jo.fromValues(f[E]);return f}).get(e)}async time(e){let t=L.defaultGetHeaders(this.client.options);this.client.options.headers&&B(t,this.client.options.headers);let n=f=>this.client.baseUri(f)+"/time",{error:s,body:o,unpacked:a}=await this.client.http.do(V.Get,n,t,null,e);if(s)throw s;a||(o=JSON.parse(o));let u=o[0];if(!u)throw new C("Internal error (unexpected result type from GET /time)",5e4,500);return this.client.serverTimeOffset=u-Date.now(),u}async request(e,t,n,s,o,a){var u;let[f,E,g]=this.client.options.useBinaryProtocol?(this.client._MsgPack||Q("MsgPack"),[this.client._MsgPack.encode,this.client._MsgPack.decode,"msgpack"]):[JSON.stringify,JSON.parse,"json"],A=this.client.http.supportsLinkHeaders?void 0:g;s=s||{};let w=e.toLowerCase(),v=w=="get"?L.defaultGetHeaders(this.client.options,{format:g,protocolVersion:n}):L.defaultPostHeaders(this.client.options,{format:g,protocolVersion:n});typeof o!="string"&&(o=(u=f(o))!=null?u:null),B(v,this.client.options.headers),a&&B(v,a);let R=new de(this.client,t,v,A,async function(T,_,N){return li(N?T:E(T))},!0);if(!b.Http.methods.includes(w))throw new C("Unsupported method "+w,40500,405);return b.Http.methodsWithBody.includes(w)?R[w](s,o):R[w](s)}async batchPublish(e){let t,n;Array.isArray(e)?(t=e,n=!1):(t=[e],n=!0);let s=this.client.options.useBinaryProtocol?"msgpack":"json",o=L.defaultPostHeaders(this.client.options,{format:s});this.client.options.headers&&B(o,this.client.options.headers);let a=le(t,this.client._MsgPack,s),u=await W.post(this.client,"/messages",a,o,{},null,!0),f=u.unpacked?u.body:ne(u.body,this.client._MsgPack,s);return n?f[0]:f}async batchPresence(e){let t=this.client.options.useBinaryProtocol?"msgpack":"json",n=L.defaultPostHeaders(this.client.options,{format:t});this.client.options.headers&&B(n,this.client.options.headers);let s=e.join(","),o=await W.get(this.client,"/presence",n,{channels:s},null,!0);return o.unpacked?o.body:ne(o.body,this.client._MsgPack,t)}async revokeTokens(e,t){if(Vi(this.client.options))throw new C("Cannot revoke tokens when using token auth",40162,401);let n=this.client.options.keyName,s=t??{},o=O({targets:e.map(g=>`${g.type}:${g.value}`)},s),a=this.client.options.useBinaryProtocol?"msgpack":"json",u=L.defaultPostHeaders(this.client.options,{format:a});this.client.options.headers&&B(u,this.client.options.headers);let f=le(o,this.client._MsgPack,a),E=await W.post(this.client,`/keys/${n}/revokeTokens`,f,u,{},null,!0);return E.unpacked?E.body:ne(E.body,this.client._MsgPack,a)}},Yo=class{constructor(e){this.client=e,this.all=Object.create(null)}get(e,t){e=String(e);let n=this.all[e];return n?t&&n.setOptions(t):this.all[e]=n=new $o(this.client,e,t),n}release(e){delete this.all[String(e)]}},Xo=class extends Xi{constructor(e){super(L.objectifyOptions(e,!1,"BaseRest",c.defaultLogger,{Rest:us}))}},ds={Rest:us},fs=class extends Re{static async fromEncoded(e,t){return as(c.defaultLogger,b.Crypto,e,t)}static async fromEncodedArray(e,t){return Go(c.defaultLogger,b.Crypto,e,t)}static fromValues(e){return Re.fromValues(e)}},ps=class extends Ee{static async fromEncoded(e,t){return is(c.defaultLogger,b.Crypto,e,t)}static async fromEncodedArray(e,t){return Lo(c.defaultLogger,b.Crypto,e,t)}static fromValues(e){return Ee.fromValues(e)}},gs=["annotation.create","annotation.delete"];async function ms(e,t,n){return Ge.fromValues(t).decode(n||{},e)}async function Zo(e,t,n){return Promise.all(t.map(function(s){return ms(e,s,n)}))}async function ea(e,t){return Ge.fromValues(e).decode(t.channelOptions,t.logger)}async function ta(e,t){return Promise.all(e.map(function(n){return ea(n,t)}))}var ys=class ti extends De{async encode(){let t=Object.assign(new Ge,this,{action:gs.indexOf(this.action||"annotation.create")});return dn(t,{})}static fromValues(t){return Object.assign(new ti,t)}static fromValuesArray(t){return t.map(n=>ti.fromValues(n))}toString(){return Be(this,"Annotation")}},Ge=class ni extends De{toJSON(...t){return pn.call(this,...t)}static fromValues(t){return Object.assign(new ni,t)}static fromValuesArray(t){return t.map(n=>ni.fromValues(n))}async decode(t,n){let s=Object.assign(new ys,H(O({},this),{action:gs[this.action]}));try{await fn(s,t)}catch(o){c.logAction(n,c.LOG_ERROR,"WireAnnotation.decode()",G(o))}return s}toString(){return Be(this,"WireAnnotation")}},qe=ys,Es=class extends qe{static async fromEncoded(e,t){return ms(c.defaultLogger,e,t)}static async fromEncodedArray(e,t){return Zo(c.defaultLogger,e,t)}static fromValues(e){return qe.fromValues(e)}};function Cs(e){let t;switch(typeof e){case"string":t=e;break;case"object":t=e.serial;break}if(!t||typeof t!="string")throw new C("First argument of annotations.publish() must be either a Message (or at least an object with a string `serial` property) or a message serial (string)",40003,400);return t}function Ss(e,t){let n=Cs(e);if(!t||typeof t!="object")throw new C("Second argument of annotations.publish() must be an object (the intended annotation to publish)",40003,400);let s=qe.fromValues(t);return s.messageSerial=n,s.action||(s.action="annotation.create"),s}function Rs(e,t){return e.client.rest.channelMixin.basePath(e)+"/messages/"+encodeURIComponent(t)+"/annotations"}var na=class{constructor(e){this.channel=e}async publish(e,t){let n=Ss(e,t),s=await n.encode(),o=this.channel.client,a=o.options,u=a.useBinaryProtocol?"msgpack":"json",f=L.defaultPostHeaders(o.options,{format:u}),E={};B(f,o.options.headers);let g=le([s],o._MsgPack,u);await W.post(o,Rs(this.channel,n.messageSerial),g,f,E,null,!0)}async delete(e,t){return t.action="annotation.delete",this.publish(e,t)}async get(e,t){let n=this.channel.client,s=Cs(e),o=n.options.useBinaryProtocol?"msgpack":"json",a=n.http.supportsLinkHeaders?void 0:o,u=L.defaultGetHeaders(n.options,{format:o});return B(u,n.options.headers),new de(n,Rs(this.channel,s),u,a,async(f,E,g)=>{let A=g?f:ne(f,n._MsgPack,o);return ta(A,this.channel)}).get(t)}},Ft=na,ia=le;function Gt(e){let t=[];if(e)for(let n=0;n<e.length;n++)t.push(e[n].toString());return"[ "+t.join(", ")+" ]"}function sa(e,t,n,s,o,a){let u=ne(e,t,a);return mn(u,n,s,o)}function mn(e,t,n,s){let o;e.error&&(o=C.fromValues(e.error));let a;e.messages&&(a=st.fromValuesArray(e.messages));let u;t&&e.presence&&(u=t.WirePresenceMessage.fromValuesArray(e.presence));let f;n&&e.annotations&&(f=n.WireAnnotation.fromValuesArray(e.annotations));let E;return s&&e.state&&(E=s.ObjectMessage.fromValuesArray(e.state,Ne,Ut)),Object.assign(new En,H(O({},e),{presence:u,messages:a,annotations:f,state:E,error:o}))}function As(e){return t=>{var n;return mn(t,{PresenceMessage:Ee,WirePresenceMessage:it},{Annotation:qe,WireAnnotation:Ge,RealtimeAnnotations:Sn,RestAnnotations:Ft},(n=e?.ObjectsPlugin)!=null?n:null)}}function ie(e){return Object.assign(new En,e)}function yn(e,t,n,s){let o="[ProtocolMessage";e.action!==void 0&&(o+="; action="+ji[e.action]||e.action);let a=["id","channel","channelSerial","connectionId","count","msgSerial","timestamp"],u;for(let f=0;f<a.length;f++)u=a[f],e[u]!==void 0&&(o+="; "+u+"="+e[u]);if(e.messages&&(o+="; messages="+Gt(st.fromValuesArray(e.messages))),e.presence&&t&&(o+="; presence="+Gt(t.WirePresenceMessage.fromValuesArray(e.presence))),e.annotations&&n&&(o+="; annotations="+Gt(n.WireAnnotation.fromValuesArray(e.annotations))),e.state&&s&&(o+="; state="+Gt(s.ObjectMessage.fromValuesArray(e.state,Ne,Ut))),e.error&&(o+="; error="+C.fromValues(e.error).toString()),e.auth&&e.auth.accessToken&&(o+="; token="+e.auth.accessToken),e.flags&&(o+="; flags="+mo.filter(e.hasFlag).join(",")),e.params){let f="";mi(e.params,function(E){f.length>0&&(f+="; "),f+=E+"="+e.params[E]}),f.length>0&&(o+="; params=["+f+"]")}return o+="]",o}var En=class{constructor(){this.hasFlag=e=>(this.flags&Z[e])>0}setFlag(e){return this.flags=this.flags|Z[e]}getMode(){return(this.flags||0)&Z.MODE_ALL}encodeModesToFlags(e){e.forEach(t=>this.setFlag(t))}decodeModesFromFlags(){let e=[];return Wi.forEach(t=>{this.hasFlag(t)&&e.push(t)}),e.length>0?e:void 0}},ra=En,oa=class{constructor(e,t,n,s,o){this.previous=e,this.current=t,t==="attached"&&(this.resumed=n,this.hasBacklog=s),o&&(this.reason=o)}},Cn=oa,ws=function(){};function aa(e){if(e&&"params"in e&&!xe(e.params))return new C("options.params must be an object",4e4,400);if(e&&"modes"in e){if(!Array.isArray(e.modes))return new C("options.modes must be an array",4e4,400);for(let t=0;t<e.modes.length;t++){let n=e.modes[t];if(!n||typeof n!="string"||!Wi.includes(String.prototype.toUpperCase.call(n)))return new C("Invalid channel mode: "+n,4e4,400)}}}var ca=class ii extends ${constructor(t,n,s){var o,a,u;super(t.logger),this._annotations=null,this._mode=0,this.retryCount=0,this.history=async function(f){c.logAction(this.logger,c.LOG_MICRO,"RealtimeChannel.history()","channel = "+this.name);let E=this.client.rest.channelMixin;if(f&&f.untilAttach){if(this.state!=="attached")throw new C("option untilAttach requires the channel to be attached",4e4,400);if(!this.properties.attachSerial)throw new C("untilAttach was specified and channel is attached, but attachSerial is not defined",4e4,400);delete f.untilAttach,f.from_serial=this.properties.attachSerial}return E.history(this,f)},this.whenState=f=>$.prototype.whenState.call(this,f,this.state),c.logAction(this.logger,c.LOG_MINOR,"RealtimeChannel()","started; name = "+n),this.name=n,this.channelOptions=Nt((o=t._Crypto)!=null?o:null,this.logger,s),this.client=t,this._presence=t._RealtimePresence?new t._RealtimePresence.RealtimePresence(this):null,t._Annotations&&(this._annotations=new t._Annotations.RealtimeAnnotations(this)),this.connectionManager=t.connection.connectionManager,this.state="initialized",this.subscriptions=new $(this.logger),this.syncChannelSerial=void 0,this.properties={attachSerial:void 0,channelSerial:void 0},this.setOptions(s),this.errorReason=null,this._attachResume=!1,this._decodingContext={channelOptions:this.channelOptions,plugins:t.options.plugins||{},baseEncodedPreviousPayload:void 0},this._lastPayload={messageId:null,protocolMessageChannelSerial:null,decodeFailureRecoveryInProgress:null},this._allChannelChanges=new $(this.logger),(a=t.options.plugins)!=null&&a.Push&&(this._push=new t.options.plugins.Push.PushChannel(this)),(u=t.options.plugins)!=null&&u.Objects&&(this._objects=new t.options.plugins.Objects.Objects(this))}get presence(){return this._presence||Q("RealtimePresence"),this._presence}get annotations(){return this._annotations||Q("Annotations"),this._annotations}get push(){return this._push||Q("Push"),this._push}get objects(){return this._objects||Q("Objects"),this._objects}invalidStateError(){return new C("Channel operation failed as channel state is "+this.state,90001,400,this.errorReason||void 0)}static processListenerArgs(t){return t=Array.prototype.slice.call(t),typeof t[0]=="function"&&t.unshift(null),t}async setOptions(t){var n;let s=this.channelOptions,o=aa(t);if(o)throw o;if(this.channelOptions=Nt((n=this.client._Crypto)!=null?n:null,this.logger,t),this._decodingContext&&(this._decodingContext.channelOptions=this.channelOptions),this._shouldReattachToSetOptions(t,s))return this.attachImpl(),new Promise((a,u)=>{this._allChannelChanges.once(["attached","update","detached","failed"],function(f){switch(this.event){case"update":case"attached":a();break;default:u(f.reason)}})})}_shouldReattachToSetOptions(t,n){if(!(this.state==="attached"||this.state==="attaching"))return!1;if(t?.params){let s=bs(t.params),o=bs(n.params);if(Object.keys(s).length!==Object.keys(o).length||!Ii(o,s))return!0}return!!(t?.modes&&(!n.modes||!Ti(t.modes,n.modes)))}async publish(...t){let n;if(t.length==1)if(xe(t[0]))n=[Re.fromValues(t[0])];else if(Array.isArray(t[0]))n=Re.fromValuesArray(t[0]);else throw new C("The single-argument form of publish() expects a message object or an array of message objects",40013,400);else n=[Re.fromValues({name:t[0],data:t[1]})];let o=this.client.options.maxMessageSize,a=await cs(n,this.channelOptions),u=gn(a);if(u>o)throw new C(`Maximum size of messages that can be published at once exceeded (was ${u} bytes; limit is ${o} bytes)`,40009,400);this.throwIfUnpublishableState(),c.logAction(this.logger,c.LOG_MICRO,"RealtimeChannel.publish()","sending message; channel state is "+this.state+", message count = "+a.length);let f=ie({action:P.MESSAGE,channel:this.name,messages:a});return this.sendMessage(f)}throwIfUnpublishableState(){if(!this.connectionManager.activeState())throw this.connectionManager.getError();if(this.state==="failed"||this.state==="suspended")throw this.invalidStateError()}onEvent(t){c.logAction(this.logger,c.LOG_MICRO,"RealtimeChannel.onEvent()","received message");let n=this.subscriptions;for(let s=0;s<t.length;s++){let o=t[s];n.emit(o.name,o)}}async attach(){return this.state==="attached"?null:new Promise((t,n)=>{this._attach(!1,null,(s,o)=>s?n(s):t(o))})}_attach(t,n,s){s||(s=a=>{a&&c.logAction(this.logger,c.LOG_ERROR,"RealtimeChannel._attach()","Channel attach failed: "+a.toString())});let o=this.connectionManager;if(!o.activeState()){s(o.getError());return}(this.state!=="attaching"||t)&&this.requestState("attaching",n),this.once(function(a){switch(this.event){case"attached":s?.(null,a);break;case"detached":case"suspended":case"failed":s?.(a.reason||o.getError()||new C("Unable to attach; reason unknown; state = "+this.event,9e4,500));break;case"detaching":s?.(new C("Attach request superseded by a subsequent detach request",9e4,409));break}})}attachImpl(){c.logAction(this.logger,c.LOG_MICRO,"RealtimeChannel.attachImpl()","sending ATTACH message");let t=ie({action:P.ATTACH,channel:this.name,params:this.channelOptions.params,channelSerial:this.properties.channelSerial});this.channelOptions.modes&&t.encodeModesToFlags(wi(this.channelOptions.modes)),this._attachResume&&t.setFlag("ATTACH_RESUME"),this._lastPayload.decodeFailureRecoveryInProgress&&(t.channelSerial=this._lastPayload.protocolMessageChannelSerial),this.sendMessage(t).catch(ws)}async detach(){let t=this.connectionManager;if(!t.activeState())throw t.getError();switch(this.state){case"suspended":this.notifyState("detached");return;case"detached":return;case"failed":throw new C("Unable to detach; channel state = failed",90001,400);default:this.requestState("detaching");case"detaching":return new Promise((n,s)=>{this.once(function(o){switch(this.event){case"detached":n();break;case"attached":case"suspended":case"failed":s(o.reason||t.getError()||new C("Unable to detach; reason unknown; state = "+this.event,9e4,500));break;case"attaching":s(new C("Detach request superseded by a subsequent attach request",9e4,409));break}})})}}detachImpl(){c.logAction(this.logger,c.LOG_MICRO,"RealtimeChannel.detach()","sending DETACH message");let t=ie({action:P.DETACH,channel:this.name});this.sendMessage(t).catch(ws)}async subscribe(...t){let[n,s]=ii.processListenerArgs(t);if(this.state==="failed")throw C.fromValues(this.invalidStateError());return n&&typeof n=="object"&&!Array.isArray(n)?this.client._FilteredSubscriptions.subscribeFilter(this,n,s):this.subscriptions.on(n,s),this.channelOptions.attachOnSubscribe!==!1?this.attach():null}unsubscribe(...t){var n;let[s,o]=ii.processListenerArgs(t);if(typeof s=="object"&&!o||(n=this.filteredSubscriptions)!=null&&n.has(o)){this.client._FilteredSubscriptions.getAndDeleteFilteredSubscriptions(this,s,o).forEach(a=>this.subscriptions.off(a));return}this.subscriptions.off(s,o)}sync(){switch(this.state){case"initialized":case"detaching":case"detached":throw new J("Unable to sync to channel; not attached",4e4);default:}let t=this.connectionManager;if(!t.activeState())throw t.getError();let n=ie({action:P.SYNC,channel:this.name});this.syncChannelSerial&&(n.channelSerial=this.syncChannelSerial),t.send(n)}async sendMessage(t){return new Promise((n,s)=>{this.connectionManager.send(t,this.client.options.queueMessages,o=>{o?s(o):n()})})}async sendPresence(t){let n=ie({action:P.PRESENCE,channel:this.name,presence:t});return this.sendMessage(n)}sendState(t){let n=ie({action:P.OBJECT,channel:this.name,state:t});return this.sendMessage(n)}async processMessage(t){(t.action===P.ATTACHED||t.action===P.MESSAGE||t.action===P.PRESENCE||t.action===P.OBJECT||t.action===P.ANNOTATION)&&this.setChannelSerial(t.channelSerial);let n,s=!1;switch(t.action){case P.ATTACHED:{this.properties.attachSerial=t.channelSerial,this._mode=t.getMode(),this.params=t.params||{};let o=t.decodeModesFromFlags();this.modes=o&&nn(o)||void 0;let a=t.hasFlag("RESUMED"),u=t.hasFlag("HAS_PRESENCE"),f=t.hasFlag("HAS_BACKLOG"),E=t.hasFlag("HAS_OBJECTS");if(this.state==="attached"){a||(this._presence&&this._presence.onAttached(u),this._objects&&this._objects.onAttached(E));let g=new Cn(this.state,this.state,a,f,t.error);this._allChannelChanges.emit("update",g),(!a||this.channelOptions.updateOnAttached)&&this.emit("update",g)}else this.state==="detaching"?this.checkPendingState():this.notifyState("attached",t.error,a,u,f,E);break}case P.DETACHED:{let o=t.error?C.fromValues(t.error):new C("Channel detached",90001,404);this.state==="detaching"?this.notifyState("detached",o):this.state==="attaching"?this.notifyState("suspended",o):(this.state==="attached"||this.state==="suspended")&&this.requestState("attaching",o);break}case P.SYNC:if(s=!0,n=this.syncChannelSerial=t.channelSerial,!t.presence)break;case P.PRESENCE:{if(!t.presence)break;Bt(t);let o=this.channelOptions;if(this._presence){let a=await Promise.all(t.presence.map(u=>u.decode(o,this.logger)));this._presence.setPresence(a,s,n)}break}case P.OBJECT:case P.OBJECT_SYNC:{if(!this._objects||!t.state)return;Bt(t);let o=t.state,a=this.client.connection.connectionManager.getActiveTransportFormat();await Promise.all(o.map(u=>this.client._objectsPlugin.ObjectMessage.decode(u,this.client,this.logger,c,Ne,a))),t.action===P.OBJECT?this._objects.handleObjectMessages(o):this._objects.handleObjectSyncMessages(o,t.channelSerial);break}case P.MESSAGE:{if(this.state!=="attached"){c.logAction(this.logger,c.LOG_MAJOR,"RealtimeChannel.processMessage()",'Message "'+t.id+'" skipped as this channel "'+this.name+'" state is not "attached" (state is "'+this.state+'").');return}Bt(t);let o=t.messages,a=o[0],u=o[o.length-1];if(a.extras&&a.extras.delta&&a.extras.delta.from!==this._lastPayload.messageId){let E='Delta message decode failure - previous message not available for message "'+t.id+'" on this channel "'+this.name+'".';c.logAction(this.logger,c.LOG_ERROR,"RealtimeChannel.processMessage()",E),this._startDecodeFailureRecovery(new C(E,40018,400));break}let f=[];for(let E=0;E<o.length;E++){let{decoded:g,err:A}=await o[E].decodeWithErr(this._decodingContext,this.logger);if(f[E]=g,A)switch(A.code){case 40018:this._startDecodeFailureRecovery(A);return;case 40019:case 40021:this.notifyState("failed",A);return;default:}}this._lastPayload.messageId=u.id,this._lastPayload.protocolMessageChannelSerial=t.channelSerial,this.onEvent(f);break}case P.ANNOTATION:{Bt(t);let o=this.channelOptions;if(this._annotations){let a=await Promise.all((t.annotations||[]).map(u=>u.decode(o,this.logger)));this._annotations._processIncoming(a)}break}case P.ERROR:{let o=t.error;o&&o.code==80016?this.checkPendingState():this.notifyState("failed",C.fromValues(o));break}default:c.logAction(this.logger,c.LOG_MAJOR,"RealtimeChannel.processMessage()","Protocol error: unrecognised message action ("+t.action+")")}}_startDecodeFailureRecovery(t){this._lastPayload.decodeFailureRecoveryInProgress||(c.logAction(this.logger,c.LOG_MAJOR,"RealtimeChannel.processMessage()","Starting decode failure recovery process."),this._lastPayload.decodeFailureRecoveryInProgress=!0,this._attach(!0,t,()=>{this._lastPayload.decodeFailureRecoveryInProgress=!1}))}onAttached(){c.logAction(this.logger,c.LOG_MINOR,"RealtimeChannel.onAttached","activating channel; name = "+this.name)}notifyState(t,n,s,o,a,u){if(c.logAction(this.logger,c.LOG_MICRO,"RealtimeChannel.notifyState","name = "+this.name+", current state = "+this.state+", notifying state "+t),this.clearStateTimer(),["detached","suspended","failed"].includes(t)&&(this.properties.channelSerial=null),t===this.state)return;this._presence&&this._presence.actOnChannelState(t,o,n),this._objects&&this._objects.actOnChannelState(t,u),t==="suspended"&&this.connectionManager.state.sendEvents?this.startRetryTimer():this.cancelRetryTimer(),n&&(this.errorReason=n);let f=new Cn(this.state,t,s,a,n),E='Channel state for channel "'+this.name+'"',g=t+(n?"; reason: "+n:"");t==="failed"?c.logAction(this.logger,c.LOG_ERROR,E,g):c.logAction(this.logger,c.LOG_MAJOR,E,g),t!=="attaching"&&t!=="suspended"&&(this.retryCount=0),t==="attached"&&this.onAttached(),t==="attached"?this._attachResume=!0:(t==="detaching"||t==="failed")&&(this._attachResume=!1),this.state=t,this._allChannelChanges.emit(t,f),this.emit(t,f)}requestState(t,n){c.logAction(this.logger,c.LOG_MINOR,"RealtimeChannel.requestState","name = "+this.name+", state = "+t),this.notifyState(t,n),this.checkPendingState()}checkPendingState(){if(!this.connectionManager.state.sendEvents){c.logAction(this.logger,c.LOG_MINOR,"RealtimeChannel.checkPendingState","sendEvents is false; state is "+this.connectionManager.state.state);return}switch(c.logAction(this.logger,c.LOG_MINOR,"RealtimeChannel.checkPendingState","name = "+this.name+", state = "+this.state),this.state){case"attaching":this.startStateTimerIfNotRunning(),this.attachImpl();break;case"detaching":this.startStateTimerIfNotRunning(),this.detachImpl();break;case"attached":this.sync();break;default:break}}timeoutPendingState(){switch(this.state){case"attaching":{let t=new C("Channel attach timed out",90007,408);this.notifyState("suspended",t);break}case"detaching":{let t=new C("Channel detach timed out",90007,408);this.notifyState("attached",t);break}default:this.checkPendingState();break}}startStateTimerIfNotRunning(){this.stateTimer||(this.stateTimer=setTimeout(()=>{c.logAction(this.logger,c.LOG_MINOR,"RealtimeChannel.startStateTimerIfNotRunning","timer expired"),this.stateTimer=null,this.timeoutPendingState()},this.client.options.timeouts.realtimeRequestTimeout))}clearStateTimer(){let t=this.stateTimer;t&&(clearTimeout(t),this.stateTimer=null)}startRetryTimer(){if(this.retryTimer)return;this.retryCount++;let t=sn(this.client.options.timeouts.channelRetryTimeout,this.retryCount);this.retryTimer=setTimeout(()=>{this.state==="suspended"&&this.connectionManager.state.sendEvents&&(this.retryTimer=null,c.logAction(this.logger,c.LOG_MINOR,"RealtimeChannel retry timer expired","attempting a new attach"),this.requestState("attaching"))},t)}cancelRetryTimer(){this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=null)}getReleaseErr(){let t=this.state;return t==="initialized"||t==="detached"||t==="failed"?null:new C("Can only release a channel in a state where there is no possibility of further updates from the server being received (initialized, detached, or failed); was "+t,90001,400)}setChannelSerial(t){c.logAction(this.logger,c.LOG_MICRO,"RealtimeChannel.setChannelSerial()","Updating channel serial; serial = "+t+"; previous = "+this.properties.channelSerial),t&&(this.properties.channelSerial=t)}async status(){return this.client.rest.channelMixin.status(this)}};function bs(e){let t=e||{},{agent:n}=t;return re(t,["agent"])}var rt=ca,la=class{constructor(e){this.channel=e,this.logger=e.logger,this.subscriptions=new $(this.logger)}async publish(e,t){let n=this.channel.name,s=Ss(e,t),o=await s.encode();this.channel.throwIfUnpublishableState(),c.logAction(this.logger,c.LOG_MICRO,"RealtimeAnnotations.publish()","channelName = "+n+", sending annotation with messageSerial = "+s.messageSerial+", type = "+s.type);let a=ie({action:P.ANNOTATION,channel:n,annotations:[o]});return this.channel.sendMessage(a)}async delete(e,t){return t.action="annotation.delete",this.publish(e,t)}async subscribe(...e){let t=rt.processListenerArgs(e),n=t[0],s=t[1],o=this.channel;if(o.state==="failed")throw C.fromValues(o.invalidStateError());if(this.subscriptions.on(n,s),this.channel.channelOptions.attachOnSubscribe!==!1&&await o.attach(),(this.channel.state==="attached"&&this.channel._mode&Z.ANNOTATION_SUBSCRIBE)===0)throw new C("You are trying to add an annotation listener, but you haven't requested the annotation_subscribe channel mode in ChannelOptions, so this won't do anything (we only deliver annotations to clients who have explicitly requested them)",93001,400)}unsubscribe(...e){let t=rt.processListenerArgs(e),n=t[0],s=t[1];this.subscriptions.off(n,s)}_processIncoming(e){for(let t of e)this.subscriptions.emit(t.type||"",t)}async get(e,t){return Ft.prototype.get.call(this,e,t)}},Sn=la,Ie=class Qt extends Xo{constructor(t){var n,s;if(!Qt._MsgPack)throw new Error("Expected DefaultRest._MsgPack to have been set");super(L.objectifyOptions(t,!0,"Rest",c.defaultLogger,H(O({},ds),{Crypto:(n=Qt.Crypto)!=null?n:void 0,MsgPack:(s=Qt._MsgPack)!=null?s:void 0,Annotations:{Annotation:qe,WireAnnotation:Ge,RealtimeAnnotations:Sn,RestAnnotations:Ft}})))}static get Crypto(){if(this._Crypto===null)throw new Error("Encryption not enabled; use ably.encryption.js instead");return this._Crypto}static set Crypto(t){this._Crypto=t}};Ie._Crypto=null,Ie.Message=fs,Ie.PresenceMessage=ps,Ie.Annotation=Es,Ie._MsgPack=null,Ie._Http=hn;var Rn=Ie,ha=class extends ${constructor(e){super(e),this.messages=[]}count(){return this.messages.length}push(e){this.messages.push(e)}shift(){return this.messages.shift()}last(){return this.messages[this.messages.length-1]}copyAll(){return this.messages.slice()}append(e){this.messages.push.apply(this.messages,e)}prepend(e){this.messages.unshift.apply(this.messages,e)}completeMessages(e,t,n){c.logAction(this.logger,c.LOG_MICRO,"MessageQueue.completeMessages()","serial = "+e+"; count = "+t),n=n||null;let s=this.messages;if(s.length===0)throw new Error("MessageQueue.completeMessages(): completeMessages called on any empty MessageQueue");let o=s[0];if(o){let a=o.message.msgSerial,u=e+t;if(u>a){let f=s.splice(0,u-a);for(let E of f)E.callback(n)}s.length==0&&this.emit("idle")}}completeAllMessages(e){this.completeMessages(0,Number.MAX_SAFE_INTEGER||Number.MAX_VALUE,e)}resetSendAttempted(){for(let e of this.messages)e.sendAttempted=!1}clear(){c.logAction(this.logger,c.LOG_MICRO,"MessageQueue.clear()","clearing "+this.messages.length+" messages"),this.messages=[],this.emit("idle")}},vs=ha,Is=class{constructor(e,t){this.message=e,this.callback=t,this.merged=!1;let n=e.action;this.sendAttempted=!1,this.ackRequired=typeof n=="number"&&[P.MESSAGE,P.PRESENCE,P.ANNOTATION,P.OBJECT].includes(n)}},ua=class extends ${constructor(e){super(e.logger),this.transport=e,this.messageQueue=new vs(this.logger),e.on("ack",(t,n)=>{this.onAck(t,n)}),e.on("nack",(t,n,s)=>{this.onNack(t,n,s)})}onAck(e,t){c.logAction(this.logger,c.LOG_MICRO,"Protocol.onAck()","serial = "+e+"; count = "+t),this.messageQueue.completeMessages(e,t)}onNack(e,t,n){c.logAction(this.logger,c.LOG_ERROR,"Protocol.onNack()","serial = "+e+"; count = "+t+"; err = "+G(n)),n||(n=new C("Unable to send message; channel not responding",50001,500)),this.messageQueue.completeMessages(e,t,n)}onceIdle(e){let t=this.messageQueue;if(t.count()===0){e();return}t.once("idle",e)}send(e){e.ackRequired&&this.messageQueue.push(e),this.logger.shouldLog(c.LOG_MICRO)&&c.logActionNoStrip(this.logger,c.LOG_MICRO,"Protocol.send()","sending msg; "+yn(e.message,this.transport.connectionManager.realtime._RealtimePresence,this.transport.connectionManager.realtime._Annotations,this.transport.connectionManager.realtime._objectsPlugin)),e.sendAttempted=!0,this.transport.send(e.message)}getTransport(){return this.transport}getPendingMessages(){return this.messageQueue.copyAll()}clearPendingMessages(){return this.messageQueue.clear()}finish(){let e=this.transport;this.onceIdle(function(){e.disconnect()})}},da=ua,fa=class{constructor(e,t,n,s){this.previous=e,this.current=t,n&&(this.retryIn=n),s&&(this.reason=s)}},qt=fa,Ae={DISCONNECTED:80003,SUSPENDED:80002,FAILED:8e4,CLOSING:80017,CLOSED:80017,UNKNOWN_CONNECTION_ERR:50002,UNKNOWN_CHANNEL_ERR:50001},pa={disconnected:()=>C.fromValues({statusCode:400,code:Ae.DISCONNECTED,message:"Connection to server temporarily unavailable"}),suspended:()=>C.fromValues({statusCode:400,code:Ae.SUSPENDED,message:"Connection to server unavailable"}),failed:()=>C.fromValues({statusCode:400,code:Ae.FAILED,message:"Connection failed or disconnected by server"}),closing:()=>C.fromValues({statusCode:400,code:Ae.CLOSING,message:"Connection closing"}),closed:()=>C.fromValues({statusCode:400,code:Ae.CLOSED,message:"Connection closed"}),unknownConnectionErr:()=>C.fromValues({statusCode:500,code:Ae.UNKNOWN_CONNECTION_ERR,message:"Internal connection error"}),unknownChannelErr:()=>C.fromValues({statusCode:500,code:Ae.UNKNOWN_CONNECTION_ERR,message:"Internal channel error"})};function ga(e){return!e.statusCode||!e.code||e.statusCode>=500?!0:Object.values(Ae).includes(e.code)}var Oe=pa,ma=ie({action:P.CLOSE}),ya=ie({action:P.DISCONNECT}),Ea=class extends ${constructor(e,t,n,s){super(e.logger),s&&(n.format=void 0,n.heartbeats=!0),this.connectionManager=e,this.auth=t,this.params=n,this.timeouts=n.options.timeouts,this.format=n.format,this.isConnected=!1,this.isFinished=!1,this.isDisposed=!1,this.maxIdleInterval=null,this.idleTimer=null,this.lastActivity=null}connect(){}close(){this.isConnected&&this.requestClose(),this.finish("closed",Oe.closed())}disconnect(e){this.isConnected&&this.requestDisconnect(),this.finish("disconnected",e||Oe.disconnected())}fail(e){this.isConnected&&this.requestDisconnect(),this.finish("failed",e||Oe.failed())}finish(e,t){var n;this.isFinished||(this.isFinished=!0,this.isConnected=!1,this.maxIdleInterval=null,clearTimeout((n=this.idleTimer)!=null?n:void 0),this.idleTimer=null,this.emit(e,t),this.dispose())}onProtocolMessage(e){switch(this.logger.shouldLog(c.LOG_MICRO)&&c.logActionNoStrip(this.logger,c.LOG_MICRO,"Transport.onProtocolMessage()","received on "+this.shortName+": "+yn(e,this.connectionManager.realtime._RealtimePresence,this.connectionManager.realtime._Annotations,this.connectionManager.realtime._objectsPlugin)+"; connectionId = "+this.connectionManager.connectionId),this.onActivity(),e.action){case P.HEARTBEAT:c.logActionNoStrip(this.logger,c.LOG_MICRO,"Transport.onProtocolMessage()",this.shortName+" heartbeat; connectionId = "+this.connectionManager.connectionId),this.emit("heartbeat",e.id);break;case P.CONNECTED:this.onConnect(e),this.emit("connected",e.error,e.connectionId,e.connectionDetails,e);break;case P.CLOSED:this.onClose(e);break;case P.DISCONNECTED:this.onDisconnect(e);break;case P.ACK:this.emit("ack",e.msgSerial,e.count);break;case P.NACK:this.emit("nack",e.msgSerial,e.count,e.error);break;case P.SYNC:this.connectionManager.onChannelMessage(e,this);break;case P.ACTIVATE:break;case P.AUTH:X(this.auth.authorize(),t=>{t&&c.logAction(this.logger,c.LOG_ERROR,"Transport.onProtocolMessage()","Ably requested re-authentication, but unable to obtain a new token: "+G(t))});break;case P.ERROR:if(c.logAction(this.logger,c.LOG_MINOR,"Transport.onProtocolMessage()","received error action; connectionId = "+this.connectionManager.connectionId+"; err = "+b.Config.inspect(e.error)+(e.channel?", channel: "+e.channel:"")),e.channel===void 0){this.onFatalError(e);break}this.connectionManager.onChannelMessage(e,this);break;default:this.connectionManager.onChannelMessage(e,this)}}onConnect(e){if(this.isConnected=!0,!e.connectionDetails)throw new Error("Transport.onConnect(): Connect message recieved without connectionDetails");let t=e.connectionDetails.maxIdleInterval;t&&(this.maxIdleInterval=t+this.timeouts.realtimeRequestTimeout,this.onActivity())}onDisconnect(e){let t=e&&e.error;c.logAction(this.logger,c.LOG_MINOR,"Transport.onDisconnect()","err = "+G(t)),this.finish("disconnected",t)}onFatalError(e){let t=e&&e.error;c.logAction(this.logger,c.LOG_MINOR,"Transport.onFatalError()","err = "+G(t)),this.finish("failed",t)}onClose(e){let t=e&&e.error;c.logAction(this.logger,c.LOG_MINOR,"Transport.onClose()","err = "+G(t)),this.finish("closed",t)}requestClose(){c.logAction(this.logger,c.LOG_MINOR,"Transport.requestClose()",""),this.send(ma)}requestDisconnect(){c.logAction(this.logger,c.LOG_MINOR,"Transport.requestDisconnect()",""),this.send(ya)}ping(e){let t={action:P.HEARTBEAT};e&&(t.id=e),this.send(ie(t))}dispose(){c.logAction(this.logger,c.LOG_MINOR,"Transport.dispose()",""),this.isDisposed=!0,this.off()}onActivity(){this.maxIdleInterval&&(this.lastActivity=this.connectionManager.lastActivity=Date.now(),this.setIdleTimer(this.maxIdleInterval+100))}setIdleTimer(e){this.idleTimer||(this.idleTimer=setTimeout(()=>{this.onIdleTimerExpire()},e))}onIdleTimerExpire(){if(!this.lastActivity||!this.maxIdleInterval)throw new Error("Transport.onIdleTimerExpire(): lastActivity/maxIdleInterval not set");this.idleTimer=null;let e=Date.now()-this.lastActivity,t=this.maxIdleInterval-e;if(t<=0){let n="No activity seen from realtime in "+e+"ms; assuming connection has dropped";c.logAction(this.logger,c.LOG_ERROR,"Transport.onIdleTimerExpire()",n),this.disconnect(new C(n,80003,408))}else this.setIdleTimer(t+100)}static tryConnect(e,t,n,s,o){let a=new e(t,n,s),u,f=function(g){clearTimeout(u),o({event:this.event,error:g})},E=t.options.timeouts.realtimeRequestTimeout;return u=setTimeout(()=>{a.off(["preconnect","disconnected","failed"]),a.dispose(),f.call({event:"disconnected"},new C("Timeout waiting for transport to indicate itself viable",5e4,500))},E),a.on(["failed","disconnected"],f),a.on("preconnect",function(){c.logAction(t.logger,c.LOG_MINOR,"Transport.tryConnect()","viable transport "+a),clearTimeout(u),a.off(["failed","disconnected"],f),o(null,a)}),a.connect(),a}static isAvailable(){throw new C("isAvailable not implemented for transport",5e4,500)}},He=Ea,ee;(e=>{e.WebSocket="web_socket",e.Comet="comet",e.XhrPolling="xhr_polling"})(ee||(ee={}));var Ca=typeof globalThis<"u"?globalThis:typeof window<"u"?window:self,An=()=>{var e;return typeof b.WebStorage<"u"&&((e=b.WebStorage)==null?void 0:e.localSupported)},ot=()=>{var e;return typeof b.WebStorage<"u"&&((e=b.WebStorage)==null?void 0:e.sessionSupported)},Os=function(){},wn="ably-transport-preference";function Sa(e,t,n){let s;if(e.channel!==t.channel||(s=e.action)!==P.PRESENCE&&s!==P.MESSAGE||s!==t.action)return!1;let o=s===P.PRESENCE?"presence":"messages",a=e[o].concat(t[o]);return gn(a)>n||!yi(a,"clientId")||!a.every(function(f){return!f.id})?!1:(e[o]=a,!0)}function bn(e){try{return JSON.parse(e)}catch{return null}}var Ra=class{constructor(e,t,n,s){this.options=e,this.host=t,this.mode=n,this.connectionKey=s,this.format=e.useBinaryProtocol?"msgpack":"json"}getConnectParams(e){let t=e?Le(e):{},n=this.options;switch(this.mode){case"resume":t.resume=this.connectionKey;break;case"recover":{let s=bn(n.recover);s&&(t.recover=s.connectionKey);break}default:}return n.clientId!==void 0&&(t.clientId=n.clientId),n.echoMessages===!1&&(t.echo="false"),this.format!==void 0&&(t.format=this.format),this.stream!==void 0&&(t.stream=this.stream),this.heartbeats!==void 0&&(t.heartbeats=this.heartbeats),t.v=L.protocolVersion,t.agent=on(this.options),n.transportParams!==void 0&&B(t,n.transportParams),t}toString(){let e="[mode="+this.mode;return this.host&&(e+=",host="+this.host),this.connectionKey&&(e+=",connectionKey="+this.connectionKey),this.format&&(e+=",format="+this.format),e+="]",e}},Aa=class Ir extends ${constructor(t,n){super(t.logger),this.supportedTransports={},this.disconnectedRetryCount=0,this.pendingChannelMessagesState={isProcessing:!1,queue:[]},this.realtime=t,this.initTransports(),this.options=n;let s=n.timeouts,o=s.webSocketConnectTimeout+s.realtimeRequestTimeout;if(this.states={initialized:{state:"initialized",terminal:!1,queueEvents:!0,sendEvents:!1,failState:"disconnected"},connecting:{state:"connecting",terminal:!1,queueEvents:!0,sendEvents:!1,retryDelay:o,failState:"disconnected"},connected:{state:"connected",terminal:!1,queueEvents:!1,sendEvents:!0,failState:"disconnected"},disconnected:{state:"disconnected",terminal:!1,queueEvents:!0,sendEvents:!1,retryDelay:s.disconnectedRetryTimeout,failState:"disconnected"},suspended:{state:"suspended",terminal:!1,queueEvents:!1,sendEvents:!1,retryDelay:s.suspendedRetryTimeout,failState:"suspended"},closing:{state:"closing",terminal:!1,queueEvents:!1,sendEvents:!1,retryDelay:s.realtimeRequestTimeout,failState:"closed"},closed:{state:"closed",terminal:!0,queueEvents:!1,sendEvents:!1,failState:"closed"},failed:{state:"failed",terminal:!0,queueEvents:!1,sendEvents:!1,failState:"failed"}},this.state=this.states.initialized,this.errorReason=null,this.queuedMessages=new vs(this.logger),this.msgSerial=0,this.connectionDetails=void 0,this.connectionId=void 0,this.connectionKey=void 0,this.connectionStateTtl=s.connectionStateTtl,this.maxIdleInterval=null,this.transports=ui(n.transports||L.defaultTransports,this.supportedTransports),this.transportPreference=null,this.transports.includes(ee.WebSocket)&&(this.webSocketTransportAvailable=!0),this.transports.includes(ee.XhrPolling)?this.baseTransport=ee.XhrPolling:this.transports.includes(ee.Comet)&&(this.baseTransport=ee.Comet),this.domains=L.getHosts(n),this.activeProtocol=null,this.host=null,this.lastAutoReconnectAttempt=null,this.lastActivity=null,this.forceFallbackHost=!1,this.connectCounter=0,this.wsCheckResult=null,this.webSocketSlowTimer=null,this.webSocketGiveUpTimer=null,this.abandonedWebSocket=!1,c.logAction(this.logger,c.LOG_MINOR,"Realtime.ConnectionManager()","started"),c.logAction(this.logger,c.LOG_MICRO,"Realtime.ConnectionManager()","requested transports = ["+(n.transports||L.defaultTransports)+"]"),c.logAction(this.logger,c.LOG_MICRO,"Realtime.ConnectionManager()","available transports = ["+this.transports+"]"),c.logAction(this.logger,c.LOG_MICRO,"Realtime.ConnectionManager()","http domains = ["+this.domains+"]"),!this.transports.length){let u="no requested transports available";throw c.logAction(this.logger,c.LOG_ERROR,"realtime.ConnectionManager()",u),new Error(u)}let a=b.Config.addEventListener;a&&(ot()&&typeof n.recover=="function"&&a("beforeunload",this.persistConnection.bind(this)),n.closeOnUnload===!0&&a("beforeunload",()=>{c.logAction(this.logger,c.LOG_MAJOR,"Realtime.ConnectionManager()","beforeunload event has triggered the connection to close as closeOnUnload is true"),this.requestState({state:"closing"})}),a("online",()=>{var u;this.state==this.states.disconnected||this.state==this.states.suspended?(c.logAction(this.logger,c.LOG_MINOR,"ConnectionManager caught browser \u2018online\u2019 event","reattempting connection"),this.requestState({state:"connecting"})):this.state==this.states.connecting&&((u=this.pendingTransport)==null||u.off(),this.disconnectAllTransports(),this.startConnect())}),a("offline",()=>{this.state==this.states.connected&&(c.logAction(this.logger,c.LOG_MINOR,"ConnectionManager caught browser \u2018offline\u2019 event","disconnecting active transport"),this.disconnectAllTransports())}))}static supportedTransports(t){let n={supportedTransports:{}};return this.initTransports(t,n),n.supportedTransports}static initTransports(t,n){let s=O(O({},b.Transports.bundledImplementations),t);[ee.WebSocket,...b.Transports.order].forEach(o=>{let a=s[o];a&&a.isAvailable()&&(n.supportedTransports[o]=a)})}initTransports(){Ir.initTransports(this.realtime._additionalTransportImplementations,this)}createTransportParams(t,n){return new Ra(this.options,t,n,this.connectionKey)}getTransportParams(t){(s=>{if(this.connectionKey){s("resume");return}if(typeof this.options.recover=="string"){s("recover");return}let o=this.options.recover,a=this.getSessionRecoverData(),u=this.sessionRecoveryName();if(a&&typeof o=="function"){c.logAction(this.logger,c.LOG_MINOR,"ConnectionManager.getTransportParams()","Calling clientOptions-provided recover function with last session data (recovery scope: "+u+")"),o(a,f=>{f?(this.options.recover=a.recoveryKey,s("recover")):s("clean")});return}s("clean")})(s=>{let o=this.createTransportParams(null,s);if(s==="recover"){c.logAction(this.logger,c.LOG_MINOR,"ConnectionManager.getTransportParams()","Transport recovery mode = recover; recoveryKey = "+this.options.recover);let a=bn(this.options.recover);a&&(this.msgSerial=a.msgSerial)}else c.logAction(this.logger,c.LOG_MINOR,"ConnectionManager.getTransportParams()","Transport params = "+o.toString());t(o)})}tryATransport(t,n,s){c.logAction(this.logger,c.LOG_MICRO,"ConnectionManager.tryATransport()","trying "+n),this.proposedTransport=He.tryConnect(this.supportedTransports[n],this,this.realtime.auth,t,(o,a)=>{let u=this.state;if(u==this.states.closing||u==this.states.closed||u==this.states.failed){a&&(c.logAction(this.logger,c.LOG_MINOR,"ConnectionManager.tryATransport()","connection "+u.state+" while we were attempting the transport; closing "+a),a.close()),s(!0);return}if(o){c.logAction(this.logger,c.LOG_MINOR,"ConnectionManager.tryATransport()","transport "+n+" "+o.event+", err: "+o.error.toString()),ye.isTokenErr(o.error)&&!(this.errorReason&&ye.isTokenErr(this.errorReason))?(this.errorReason=o.error,X(this.realtime.auth._forceNewToken(null,null),f=>{if(f){this.actOnErrorFromAuthorize(f);return}this.tryATransport(t,n,s)})):o.event==="failed"?(this.notifyState({state:"failed",error:o.error}),s(!0)):o.event==="disconnected"&&(ga(o.error)?s(!1):(this.notifyState({state:this.states.connecting.failState,error:o.error}),s(!0)));return}c.logAction(this.logger,c.LOG_MICRO,"ConnectionManager.tryATransport()","viable transport "+n+"; setting pending"),this.setTransportPending(a,t),s(null,a)})}setTransportPending(t,n){let s=n.mode;c.logAction(this.logger,c.LOG_MINOR,"ConnectionManager.setTransportPending()","transport = "+t+"; mode = "+s),this.pendingTransport=t,this.cancelWebSocketSlowTimer(),this.cancelWebSocketGiveUpTimer(),t.once("connected",(a,u,f)=>{this.activateTransport(a,t,u,f),s==="recover"&&this.options.recover&&(delete this.options.recover,this.unpersistConnection())});let o=this;t.on(["disconnected","closed","failed"],function(a){o.deactivateTransport(t,this.event,a)}),this.emit("transport.pending",t)}activateTransport(t,n,s,o){c.logAction(this.logger,c.LOG_MINOR,"ConnectionManager.activateTransport()","transport = "+n),t&&c.logAction(this.logger,c.LOG_ERROR,"ConnectionManager.activateTransport()","error = "+t),s&&c.logAction(this.logger,c.LOG_MICRO,"ConnectionManager.activateTransport()","connectionId = "+s),o&&c.logAction(this.logger,c.LOG_MICRO,"ConnectionManager.activateTransport()","connectionDetails = "+JSON.stringify(o)),this.persistTransportPreference(n);let a=this.state,u=this.states.connected.state;if(c.logAction(this.logger,c.LOG_MINOR,"ConnectionManager.activateTransport()","current state = "+a.state),a.state==this.states.closing.state||a.state==this.states.closed.state||a.state==this.states.failed.state)return c.logAction(this.logger,c.LOG_MINOR,"ConnectionManager.activateTransport()","Disconnecting transport and abandoning"),n.disconnect(),!1;if(delete this.pendingTransport,!n.isConnected)return c.logAction(this.logger,c.LOG_MINOR,"ConnectionManager.activateTransport()","Declining to activate transport "+n+" since it appears to no longer be connected"),!1;let f=this.activeProtocol;this.activeProtocol=new da(n),this.host=n.params.host;let E=o.connectionKey;if(E&&this.connectionKey!=E&&this.setConnection(s,o,!!t),this.onConnectionDetailsUpdate(o,n),b.Config.nextTick(()=>{n.on("connected",(g,A,w)=>{this.onConnectionDetailsUpdate(w,n),this.emit("update",new qt(u,u,null,g))})}),a.state===this.states.connected.state?t&&(this.errorReason=this.realtime.connection.errorReason=t,this.emit("update",new qt(u,u,null,t))):(this.notifyState({state:"connected",error:t}),this.errorReason=this.realtime.connection.errorReason=t||null),this.emit("transport.active",n),f)if(f.messageQueue.count()>0&&c.logAction(this.logger,c.LOG_ERROR,"ConnectionManager.activateTransport()","Previous active protocol (for transport "+f.transport.shortName+", new one is "+n.shortName+") finishing with "+f.messageQueue.count()+" messages still pending"),f.transport===n){let g="Assumption violated: activating a transport that was also the transport for the previous active protocol; transport = "+n.shortName+"; stack = "+new Error().stack;c.logAction(this.logger,c.LOG_ERROR,"ConnectionManager.activateTransport()",g)}else f.finish();return!0}deactivateTransport(t,n,s){let o=this.activeProtocol,a=o&&o.getTransport()===t,u=t===this.pendingTransport,f=this.noTransportsScheduledForActivation();if(c.logAction(this.logger,c.LOG_MINOR,"ConnectionManager.deactivateTransport()","transport = "+t),c.logAction(this.logger,c.LOG_MINOR,"ConnectionManager.deactivateTransport()","state = "+n+(a?"; was active":u?"; was pending":"")+(f?"":"; another transport is scheduled for activation")),s&&s.message&&c.logAction(this.logger,c.LOG_MICRO,"ConnectionManager.deactivateTransport()","reason = "+s.message),a&&(c.logAction(this.logger,c.LOG_MICRO,"ConnectionManager.deactivateTransport()","Getting, clearing, and requeuing "+this.activeProtocol.messageQueue.count()+" pending messages"),this.queuePendingMessages(o.getPendingMessages()),o.clearPendingMessages(),this.activeProtocol=this.host=null),this.emit("transport.inactive",t),a&&f||a&&n==="failed"||n==="closed"||o===null&&u){if(n==="disconnected"&&s&&s.statusCode>500&&this.domains.length>1){this.unpersistTransportPreference(),this.forceFallbackHost=!0,this.notifyState({state:n,error:s,retryImmediately:!0});return}let E=n==="failed"&&ye.isTokenErr(s)?"disconnected":n;this.notifyState({state:E,error:s});return}}noTransportsScheduledForActivation(){return!this.pendingTransport||!this.pendingTransport.isConnected}setConnection(t,n,s){let o=this.connectionId;(o&&o!==t||!o&&s)&&(c.logAction(this.logger,c.LOG_MINOR,"ConnectionManager.setConnection()","Resetting msgSerial"),this.msgSerial=0,this.queuedMessages.resetSendAttempted()),this.connectionId!==t&&c.logAction(this.logger,c.LOG_MINOR,"ConnectionManager.setConnection()","New connectionId; reattaching any attached channels"),this.realtime.connection.id=this.connectionId=t,this.realtime.connection.key=this.connectionKey=n.connectionKey}clearConnection(){this.realtime.connection.id=this.connectionId=void 0,this.realtime.connection.key=this.connectionKey=void 0,this.msgSerial=0,this.unpersistConnection()}createRecoveryKey(){return this.connectionKey?JSON.stringify({connectionKey:this.connectionKey,msgSerial:this.msgSerial,channelSerials:this.realtime.channels.channelSerials()}):null}checkConnectionStateFreshness(){if(!this.lastActivity||!this.connectionId)return;let t=Date.now()-this.lastActivity;t>this.connectionStateTtl+this.maxIdleInterval&&(c.logAction(this.logger,c.LOG_MINOR,"ConnectionManager.checkConnectionStateFreshness()","Last known activity from realtime was "+t+"ms ago; discarding connection state"),this.clearConnection(),this.states.connecting.failState="suspended")}persistConnection(){if(ot()){let t=this.createRecoveryKey();t&&this.setSessionRecoverData({recoveryKey:t,disconnectedAt:Date.now(),location:Ca.location,clientId:this.realtime.auth.clientId})}}unpersistConnection(){this.clearSessionRecoverData()}getActiveTransportFormat(){var t;return(t=this.activeProtocol)==null?void 0:t.getTransport().format}getError(){if(this.errorReason){let t=J.fromValues(this.errorReason);return t.cause=this.errorReason,t}return this.getStateError()}getStateError(){var t,n;return(n=(t=Oe)[this.state.state])==null?void 0:n.call(t)}activeState(){return this.state.queueEvents||this.state.sendEvents}enactStateChange(t){let n="Connection state",s=t.current+(t.reason?"; reason: "+t.reason:"");t.current==="failed"?c.logAction(this.logger,c.LOG_ERROR,n,s):c.logAction(this.logger,c.LOG_MAJOR,n,s),c.logAction(this.logger,c.LOG_MINOR,"ConnectionManager.enactStateChange","setting new state: "+t.current+"; reason = "+(t.reason&&t.reason.message));let o=this.state=this.states[t.current];t.reason&&(this.errorReason=t.reason,this.realtime.connection.errorReason=t.reason),(o.terminal||o.state==="suspended")&&this.clearConnection(),this.emit("connectionstate",t)}startTransitionTimer(t){c.logAction(this.logger,c.LOG_MINOR,"ConnectionManager.startTransitionTimer()","transitionState: "+t.state),this.transitionTimer&&(c.logAction(this.logger,c.LOG_MINOR,"ConnectionManager.startTransitionTimer()","clearing already-running timer"),clearTimeout(this.transitionTimer)),this.transitionTimer=setTimeout(()=>{this.transitionTimer&&(this.transitionTimer=null,c.logAction(this.logger,c.LOG_MINOR,"ConnectionManager "+t.state+" timer expired","requesting new state: "+t.failState),this.notifyState({state:t.failState}))},t.retryDelay)}cancelTransitionTimer(){c.logAction(this.logger,c.LOG_MINOR,"ConnectionManager.cancelTransitionTimer()",""),this.transitionTimer&&(clearTimeout(this.transitionTimer),this.transitionTimer=null)}startSuspendTimer(){this.suspendTimer||(this.suspendTimer=setTimeout(()=>{this.suspendTimer&&(this.suspendTimer=null,c.logAction(this.logger,c.LOG_MINOR,"ConnectionManager suspend timer expired","requesting new state: suspended"),this.states.connecting.failState="suspended",this.notifyState({state:"suspended"}))},this.connectionStateTtl))}checkSuspendTimer(t){t!=="disconnected"&&t!=="suspended"&&t!=="connecting"&&this.cancelSuspendTimer()}cancelSuspendTimer(){this.states.connecting.failState="disconnected",this.suspendTimer&&(clearTimeout(this.suspendTimer),this.suspendTimer=null)}startRetryTimer(t){this.retryTimer=setTimeout(()=>{c.logAction(this.logger,c.LOG_MINOR,"ConnectionManager retry timer expired","retrying"),this.retryTimer=null,this.requestState({state:"connecting"})},t)}cancelRetryTimer(){this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=null)}startWebSocketSlowTimer(){this.webSocketSlowTimer=setTimeout(()=>{c.logAction(this.logger,c.LOG_MINOR,"ConnectionManager WebSocket slow timer","checking connectivity"),this.checkWsConnectivity().then(()=>{c.logAction(this.logger,c.LOG_MINOR,"ConnectionManager WebSocket slow timer","ws connectivity check succeeded"),this.wsCheckResult=!0}).catch(()=>{c.logAction(this.logger,c.LOG_MAJOR,"ConnectionManager WebSocket slow timer","ws connectivity check failed"),this.wsCheckResult=!1}),this.realtime.http.checkConnectivity&&X(this.realtime.http.checkConnectivity(),(t,n)=>{t||!n?(c.logAction(this.logger,c.LOG_MAJOR,"ConnectionManager WebSocket slow timer","http connectivity check failed"),this.cancelWebSocketGiveUpTimer(),this.notifyState({state:"disconnected",error:new C("Unable to connect (network unreachable)",80003,404)})):c.logAction(this.logger,c.LOG_MINOR,"ConnectionManager WebSocket slow timer","http connectivity check succeeded")})},this.options.timeouts.webSocketSlowTimeout)}cancelWebSocketSlowTimer(){this.webSocketSlowTimer&&(clearTimeout(this.webSocketSlowTimer),this.webSocketSlowTimer=null)}startWebSocketGiveUpTimer(t){this.webSocketGiveUpTimer=setTimeout(()=>{var n,s;this.wsCheckResult||(c.logAction(this.logger,c.LOG_MINOR,"ConnectionManager WebSocket give up timer","websocket connection took more than 10s; "+(this.baseTransport?"trying base transport":"")),this.baseTransport?(this.abandonedWebSocket=!0,(n=this.proposedTransport)==null||n.dispose(),(s=this.pendingTransport)==null||s.dispose(),this.connectBase(t,++this.connectCounter)):c.logAction(this.logger,c.LOG_MAJOR,"ConnectionManager WebSocket give up timer","websocket connectivity appears to be unavailable but no other transports to try"))},this.options.timeouts.webSocketConnectTimeout)}cancelWebSocketGiveUpTimer(){this.webSocketGiveUpTimer&&(clearTimeout(this.webSocketGiveUpTimer),this.webSocketGiveUpTimer=null)}notifyState(t){var n,s;let o=t.state,a=o==="disconnected"&&(this.state===this.states.connected||t.retryImmediately||this.state===this.states.connecting&&t.error&&ye.isTokenErr(t.error)&&!(this.errorReason&&ye.isTokenErr(this.errorReason)));if(c.logAction(this.logger,c.LOG_MINOR,"ConnectionManager.notifyState()","new state: "+o+(a?"; will retry connection immediately":"")),o==this.state.state||(this.cancelTransitionTimer(),this.cancelRetryTimer(),this.cancelWebSocketSlowTimer(),this.cancelWebSocketGiveUpTimer(),this.checkSuspendTimer(t.state),(o==="suspended"||o==="connected")&&(this.disconnectedRetryCount=0),this.state.terminal))return;let u=this.states[t.state],f=u.retryDelay;u.state==="disconnected"&&(this.disconnectedRetryCount++,f=sn(u.retryDelay,this.disconnectedRetryCount));let E=new qt(this.state.state,u.state,f,t.error||((s=(n=Oe)[u.state])==null?void 0:s.call(n)));if(a){let g=()=>{this.state===this.states.disconnected&&(this.lastAutoReconnectAttempt=Date.now(),this.requestState({state:"connecting"}))},A=this.lastAutoReconnectAttempt&&Date.now()-this.lastAutoReconnectAttempt+1;A&&A<1e3?(c.logAction(this.logger,c.LOG_MICRO,"ConnectionManager.notifyState()","Last reconnect attempt was only "+A+"ms ago, waiting another "+(1e3-A)+"ms before trying again"),setTimeout(g,1e3-A)):b.Config.nextTick(g)}else(o==="disconnected"||o==="suspended")&&this.startRetryTimer(f);(o==="disconnected"&&!a||o==="suspended"||u.terminal)&&b.Config.nextTick(()=>{this.disconnectAllTransports()}),o=="connected"&&!this.activeProtocol&&c.logAction(this.logger,c.LOG_ERROR,"ConnectionManager.notifyState()","Broken invariant: attempted to go into connected state, but there is no active protocol"),this.enactStateChange(E),this.state.sendEvents?this.sendQueuedMessages():this.state.queueEvents||(this.realtime.channels.propogateConnectionInterruption(o,E.reason),this.failQueuedMessages(E.reason))}requestState(t){var n,s;let o=t.state;if(c.logAction(this.logger,c.LOG_MINOR,"ConnectionManager.requestState()","requested state: "+o+"; current state: "+this.state.state),o==this.state.state||(this.cancelWebSocketSlowTimer(),this.cancelWebSocketGiveUpTimer(),this.cancelTransitionTimer(),this.cancelRetryTimer(),this.checkSuspendTimer(o),o=="connecting"&&this.state.state=="connected")||o=="closing"&&this.state.state=="closed")return;let a=this.states[o],u=new qt(this.state.state,a.state,null,t.error||((s=(n=Oe)[a.state])==null?void 0:s.call(n)));this.enactStateChange(u),o=="connecting"&&b.Config.nextTick(()=>{this.startConnect()}),o=="closing"&&this.closeImpl()}startConnect(){if(this.state!==this.states.connecting){c.logAction(this.logger,c.LOG_MINOR,"ConnectionManager.startConnect()","Must be in connecting state to connect, but was "+this.state.state);return}let t=this.realtime.auth,n=++this.connectCounter,s=()=>{this.checkConnectionStateFreshness(),this.getTransportParams(o=>{if(o.mode==="recover"&&o.options.recover){let a=bn(o.options.recover);a&&this.realtime.channels.recoverChannels(a.channelSerials)}n===this.connectCounter&&this.connectImpl(o,n)})};if(c.logAction(this.logger,c.LOG_MINOR,"ConnectionManager.startConnect()","starting connection"),this.startSuspendTimer(),this.startTransitionTimer(this.states.connecting),t.method==="basic")s();else{let o=a=>{n===this.connectCounter&&(a?this.actOnErrorFromAuthorize(a):s())};this.errorReason&&ye.isTokenErr(this.errorReason)?X(t._forceNewToken(null,null),o):X(t._ensureValidAuthCredentials(!1),o)}}connectImpl(t,n){let s=this.state.state;if(s!==this.states.connecting.state){c.logAction(this.logger,c.LOG_MINOR,"ConnectionManager.connectImpl()","Must be in connecting state to connect, but was "+s);return}let o=this.getTransportPreference();o&&o===this.baseTransport&&this.webSocketTransportAvailable&&this.checkWsConnectivity().then(()=>{this.unpersistTransportPreference(),this.state===this.states.connecting&&(c.logAction(this.logger,c.LOG_MINOR,"ConnectionManager.connectImpl():","web socket connectivity available, cancelling connection attempt with "+this.baseTransport),this.disconnectAllTransports(),this.connectWs(t,++this.connectCounter))}).catch(Os),o&&o===this.baseTransport||this.baseTransport&&!this.webSocketTransportAvailable?this.connectBase(t,n):this.connectWs(t,n)}connectWs(t,n){c.logAction(this.logger,c.LOG_MICRO,"ConnectionManager.connectWs()"),this.wsCheckResult=null,this.abandonedWebSocket=!1,this.startWebSocketSlowTimer(),this.startWebSocketGiveUpTimer(t),this.tryTransportWithFallbacks("web_socket",t,!0,n,()=>this.wsCheckResult!==!1&&!this.abandonedWebSocket)}connectBase(t,n){c.logAction(this.logger,c.LOG_MICRO,"ConnectionManager.connectBase()"),this.baseTransport?this.tryTransportWithFallbacks(this.baseTransport,t,!1,n,()=>!0):this.notifyState({state:"disconnected",error:new C("No transports left to try",8e4,404)})}tryTransportWithFallbacks(t,n,s,o,a){c.logAction(this.logger,c.LOG_MICRO,"ConnectionManager.tryTransportWithFallbacks()",t);let u=w=>{this.notifyState({state:this.states.connecting.failState,error:w})},f=this.domains.slice(),E=(w,v)=>{if(o===this.connectCounter){if(!a()){v&&v.dispose();return}!v&&!w&&A()}},g=f.shift();if(!g){u(new C("Unable to connect (no available host)",80003,404));return}n.host=g;let A=()=>{if(!f.length){u(new C("Unable to connect (and no more fallback hosts to try)",80003,404));return}if(!this.realtime.http.checkConnectivity){u(new J("Internal error: Http.checkConnectivity not set",null,500));return}X(this.realtime.http.checkConnectivity(),(w,v)=>{if(o===this.connectCounter&&a()){if(w){u(w);return}if(!v){u(new C("Unable to connect (network unreachable)",80003,404));return}n.host=en(f),this.tryATransport(n,t,E)}})};if(this.forceFallbackHost&&f.length){this.forceFallbackHost=!1,A();return}this.tryATransport(n,t,E)}closeImpl(){c.logAction(this.logger,c.LOG_MINOR,"ConnectionManager.closeImpl()","closing connection"),this.cancelSuspendTimer(),this.startTransitionTimer(this.states.closing),this.pendingTransport&&(c.logAction(this.logger,c.LOG_MICRO,"ConnectionManager.closeImpl()","Closing pending transport: "+this.pendingTransport),this.pendingTransport.close()),this.activeProtocol&&(c.logAction(this.logger,c.LOG_MICRO,"ConnectionManager.closeImpl()","Closing active transport: "+this.activeProtocol.getTransport()),this.activeProtocol.getTransport().close()),this.notifyState({state:"closed"})}onAuthUpdated(t,n){var s;switch(this.state.state){case"connected":{c.logAction(this.logger,c.LOG_MICRO,"ConnectionManager.onAuthUpdated()","Sending AUTH message on active transport");let o=(s=this.activeProtocol)==null?void 0:s.getTransport();o&&o.onAuthUpdated&&o.onAuthUpdated(t);let a=ie({action:P.AUTH,auth:{accessToken:t.token}});this.send(a);let u=()=>{this.off(f),n(null,t)},f=E=>{E.current==="failed"&&(this.off(u),this.off(f),n(E.reason||this.getStateError()))};this.once("connectiondetails",u),this.on("connectionstate",f);break}case"connecting":c.logAction(this.logger,c.LOG_MICRO,"ConnectionManager.onAuthUpdated()","Aborting current connection attempts in order to start again with the new auth details"),this.disconnectAllTransports();default:{c.logAction(this.logger,c.LOG_MICRO,"ConnectionManager.onAuthUpdated()","Connection state is "+this.state.state+"; waiting until either connected or failed");let o=a=>{switch(a.current){case"connected":this.off(o),n(null,t);break;case"failed":case"closed":case"suspended":this.off(o),n(a.reason||this.getStateError());break;default:break}};this.on("connectionstate",o),this.state.state==="connecting"?this.startConnect():this.requestState({state:"connecting"})}}}disconnectAllTransports(){c.logAction(this.logger,c.LOG_MINOR,"ConnectionManager.disconnectAllTransports()","Disconnecting all transports"),this.connectCounter++,this.pendingTransport&&(c.logAction(this.logger,c.LOG_MICRO,"ConnectionManager.disconnectAllTransports()","Disconnecting pending transport: "+this.pendingTransport),this.pendingTransport.disconnect()),delete this.pendingTransport,this.proposedTransport&&(c.logAction(this.logger,c.LOG_MICRO,"ConnectionManager.disconnectAllTransports()","Disconnecting proposed transport: "+this.pendingTransport),this.proposedTransport.disconnect()),delete this.pendingTransport,this.activeProtocol&&(c.logAction(this.logger,c.LOG_MICRO,"ConnectionManager.disconnectAllTransports()","Disconnecting active transport: "+this.activeProtocol.getTransport()),this.activeProtocol.getTransport().disconnect())}send(t,n,s){s=s||Os;let o=this.state;if(o.sendEvents){c.logAction(this.logger,c.LOG_MICRO,"ConnectionManager.send()","sending event"),this.sendImpl(new Is(t,s));return}if(!(n&&o.queueEvents)){let u="rejecting event, queueEvent was "+n+", state was "+o.state;c.logAction(this.logger,c.LOG_MICRO,"ConnectionManager.send()",u),s(this.errorReason||new C(u,9e4,400));return}this.logger.shouldLog(c.LOG_MICRO)&&c.logAction(this.logger,c.LOG_MICRO,"ConnectionManager.send()","queueing msg; "+yn(t,this.realtime._RealtimePresence,this.realtime._Annotations,this.realtime._objectsPlugin)),this.queue(t,s)}sendImpl(t){let n=t.message;t.ackRequired&&!t.sendAttempted&&(n.msgSerial=this.msgSerial++);try{this.activeProtocol.send(t)}catch(s){c.logAction(this.logger,c.LOG_ERROR,"ConnectionManager.sendImpl()","Unexpected exception in transport.send(): "+s.stack)}}queue(t,n){c.logAction(this.logger,c.LOG_MICRO,"ConnectionManager.queue()","queueing event");let s=this.queuedMessages.last(),o=this.options.maxMessageSize;s&&!s.sendAttempted&&Sa(s.message,t,o)?(s.merged||(s.callback=an.create(this.logger,[s.callback]),s.merged=!0),s.callback.push(n)):this.queuedMessages.push(new Is(t,n))}sendQueuedMessages(){c.logAction(this.logger,c.LOG_MICRO,"ConnectionManager.sendQueuedMessages()","sending "+this.queuedMessages.count()+" queued messages");let t;for(;t=this.queuedMessages.shift();)this.sendImpl(t)}queuePendingMessages(t){t&&t.length&&(c.logAction(this.logger,c.LOG_MICRO,"ConnectionManager.queuePendingMessages()","queueing "+t.length+" pending messages"),this.queuedMessages.prepend(t))}failQueuedMessages(t){let n=this.queuedMessages.count();n>0&&(c.logAction(this.logger,c.LOG_ERROR,"ConnectionManager.failQueuedMessages()","failing "+n+" queued messages, err = "+G(t)),this.queuedMessages.completeAllMessages(t))}onChannelMessage(t,n){this.pendingChannelMessagesState.queue.push({message:t,transport:n}),this.pendingChannelMessagesState.isProcessing||this.processNextPendingChannelMessage()}processNextPendingChannelMessage(){if(this.pendingChannelMessagesState.queue.length>0){this.pendingChannelMessagesState.isProcessing=!0;let t=this.pendingChannelMessagesState.queue.shift();this.processChannelMessage(t.message).catch(n=>{c.logAction(this.logger,c.LOG_ERROR,"ConnectionManager.processNextPendingChannelMessage() received error ",n)}).finally(()=>{this.pendingChannelMessagesState.isProcessing=!1,this.processNextPendingChannelMessage()})}}async processChannelMessage(t){await this.realtime.channels.processChannelMessage(t)}async ping(){var t;if(this.state.state!=="connected")throw new C("Unable to ping service; not connected",4e4,400);let n=(t=this.activeProtocol)==null?void 0:t.getTransport();if(!n)throw this.getStateError();c.logAction(this.logger,c.LOG_MINOR,"ConnectionManager.ping()","transport = "+n);let s=Date.now(),o=Mt();return _i(new Promise(a=>{let u=f=>{f===o&&(n.off("heartbeat",u),a(Date.now()-s))};n.on("heartbeat",u),n.ping(o)}),this.options.timeouts.realtimeRequestTimeout,"Timeout waiting for heartbeat response")}abort(t){this.activeProtocol.getTransport().fail(t)}getTransportPreference(){var t,n;return this.transportPreference||An()&&((n=(t=b.WebStorage)==null?void 0:t.get)==null?void 0:n.call(t,wn))}persistTransportPreference(t){var n,s;this.transportPreference=t.shortName,An()&&((s=(n=b.WebStorage)==null?void 0:n.set)==null||s.call(n,wn,t.shortName))}unpersistTransportPreference(){var t,n;this.transportPreference=null,An()&&((n=(t=b.WebStorage)==null?void 0:t.remove)==null||n.call(t,wn))}actOnErrorFromAuthorize(t){if(t.code===40171)this.notifyState({state:"failed",error:t});else if(t.code===40102)this.notifyState({state:"failed",error:t});else if(t.statusCode===xt.Forbidden){let n="Client configured authentication provider returned 403; failing the connection";c.logAction(this.logger,c.LOG_ERROR,"ConnectionManager.actOnErrorFromAuthorize()",n),this.notifyState({state:"failed",error:new C(n,80019,403,t)})}else{let n="Client configured authentication provider request failed";c.logAction(this.logger,c.LOG_MINOR,"ConnectionManager.actOnErrorFromAuthorize",n),this.notifyState({state:this.state.failState,error:new C(n,80019,401,t)})}}onConnectionDetailsUpdate(t,n){if(!t)return;this.connectionDetails=t,t.maxMessageSize&&(this.options.maxMessageSize=t.maxMessageSize);let s=t.clientId;if(s){let a=this.realtime.auth._uncheckedSetClientId(s);if(a){c.logAction(this.logger,c.LOG_ERROR,"ConnectionManager.onConnectionDetailsUpdate()",a.message),n.fail(a);return}}let o=t.connectionStateTtl;o&&(this.connectionStateTtl=o),this.maxIdleInterval=t.maxIdleInterval,this.emit("connectiondetails",t)}checkWsConnectivity(){let t=this.options.wsConnectivityCheckUrl||L.wsConnectivityCheckUrl,n=new b.Config.WebSocket(t);return new Promise((s,o)=>{let a=!1;n.onopen=()=>{a||(a=!0,s(),n.close())},n.onclose=n.onerror=()=>{a||(a=!0,o())}})}sessionRecoveryName(){return this.options.recoveryKeyStorageName||"ably-connection-recovery"}getSessionRecoverData(){var t,n;return ot()&&((n=(t=b.WebStorage)==null?void 0:t.getSession)==null?void 0:n.call(t,this.sessionRecoveryName()))}setSessionRecoverData(t){var n,s;return ot()&&((s=(n=b.WebStorage)==null?void 0:n.setSession)==null?void 0:s.call(n,this.sessionRecoveryName(),t))}clearSessionRecoverData(){var t,n;return ot()&&((n=(t=b.WebStorage)==null?void 0:t.removeSession)==null?void 0:n.call(t,this.sessionRecoveryName()))}},Ts=Aa,wa=class extends ${constructor(e,t){super(e.logger),this.whenState=n=>$.prototype.whenState.call(this,n,this.state),this.ably=e,this.connectionManager=new Ts(e,t),this.state=this.connectionManager.state.state,this.key=void 0,this.id=void 0,this.errorReason=null,this.connectionManager.on("connectionstate",n=>{let s=this.state=n.current;b.Config.nextTick(()=>{this.emit(s,n)})}),this.connectionManager.on("update",n=>{b.Config.nextTick(()=>{this.emit("update",n)})})}connect(){c.logAction(this.logger,c.LOG_MINOR,"Connection.connect()",""),this.connectionManager.requestState({state:"connecting"})}async ping(){return c.logAction(this.logger,c.LOG_MINOR,"Connection.ping()",""),this.connectionManager.ping()}close(){c.logAction(this.logger,c.LOG_MINOR,"Connection.close()","connectionKey = "+this.key),this.connectionManager.requestState({state:"closing"})}get recoveryKey(){return this.logger.deprecationWarning("The `Connection.recoveryKey` attribute has been replaced by the `Connection.createRecoveryKey()` method. Replace your usage of `recoveryKey` with the return value of `createRecoveryKey()`. `recoveryKey` will be removed in a future version."),this.createRecoveryKey()}createRecoveryKey(){return this.connectionManager.createRecoveryKey()}},ba=wa,_s=class Or extends Xi{constructor(t){var n,s,o,a;if(super(L.objectifyOptions(t,!1,"BaseRealtime",c.defaultLogger)),c.logAction(this.logger,c.LOG_MINOR,"Realtime()",""),typeof EdgeRuntime=="string")throw new C(`Ably.Realtime instance cannot be used in Vercel Edge runtime. If you are running Vercel Edge functions, please replace your "new Ably.Realtime()" with "new Ably.Rest()" and use Ably Rest API instead of the Realtime API. If you are server-rendering your application in the Vercel Edge runtime, please use the condition "if (typeof EdgeRuntime === 'string')" to prevent instantiating Ably.Realtime instance during SSR in the Vercel Edge runtime.`,4e4,400);this._additionalTransportImplementations=Or.transportImplementationsFromPlugins(this.options.plugins),this._RealtimePresence=(s=(n=this.options.plugins)==null?void 0:n.RealtimePresence)!=null?s:null,this._objectsPlugin=(a=(o=this.options.plugins)==null?void 0:o.Objects)!=null?a:null,this.connection=new ba(this,this.options),this._channels=new Ia(this),this.options.autoConnect!==!1&&this.connect()}static transportImplementationsFromPlugins(t){let n={};return t?.WebSocketTransport&&(n[ee.WebSocket]=t.WebSocketTransport),t?.XHRPolling&&(n[ee.XhrPolling]=t.XHRPolling),n}get channels(){return this._channels}connect(){c.logAction(this.logger,c.LOG_MINOR,"Realtime.connect()",""),this.connection.connect()}close(){c.logAction(this.logger,c.LOG_MINOR,"Realtime.close()",""),this.connection.close()}};_s.EventEmitter=$;var va=_s,Ia=class extends ${constructor(e){super(e.logger),this.realtime=e,this.all=Object.create(null),e.connection.connectionManager.on("transport.active",()=>{this.onTransportActive()})}channelSerials(){let e={};for(let t of tt(this.all,!0)){let n=this.all[t];n.properties.channelSerial&&(e[t]=n.properties.channelSerial)}return e}recoverChannels(e){for(let t of tt(e,!0)){let n=this.get(t);n.properties.channelSerial=e[t]}}async processChannelMessage(e){let t=e.channel;if(t===void 0){c.logAction(this.logger,c.LOG_ERROR,"Channels.processChannelMessage()","received event unspecified channel, action = "+e.action);return}let n=this.all[t];if(!n){c.logAction(this.logger,c.LOG_ERROR,"Channels.processChannelMessage()","received event for non-existent channel: "+t);return}await n.processMessage(e)}onTransportActive(){for(let e in this.all){let t=this.all[e];t.state==="attaching"||t.state==="detaching"?t.checkPendingState():t.state==="suspended"?t._attach(!1,null):t.state==="attached"&&t.requestState("attaching")}}propogateConnectionInterruption(e,t){let n={closing:"detached",closed:"detached",failed:"failed",suspended:"suspended"},s=["attaching","attached","detaching","suspended"],o=n[e];for(let a in this.all){let u=this.all[a];s.includes(u.state)&&u.notifyState(o,t)}}get(e,t){e=String(e);let n=this.all[e];if(!n)n=this.all[e]=new rt(this.realtime,e,t);else if(t){if(n._shouldReattachToSetOptions(t,n.channelOptions))throw new C("Channels.get() cannot be used to set channel options that would cause the channel to reattach. Please, use RealtimeChannel.setOptions() instead.",4e4,400);n.setOptions(t)}return n}getDerived(e,t,n){if(t.filter){let s=kt(t.filter),o=Oi(e);e=`[filter=${s}${o.qualifierParam}]${o.channelName}`}return this.get(e,n)}release(e){e=String(e);let t=this.all[e];if(!t)return;let n=t.getReleaseErr();if(n)throw n;delete this.all[e]}},Oa=va;function Ta(e,t){if(e.isSynthesized()||t.isSynthesized())return e.timestamp>=t.timestamp;let n=e.parseId(),s=t.parseId();return n.msgSerial===s.msgSerial?n.index>s.index:n.msgSerial>s.msgSerial}var vn=class extends ${constructor(e,t,n=Ta){super(e.logger),this.presence=e,this.map=Object.create(null),this.syncInProgress=!1,this.residualMembers=null,this.memberKey=t,this.newerThan=n}get(e){return this.map[e]}getClient(e){let t=this.map,n=[];for(let s in t){let o=t[s];o.clientId==e&&o.action!="absent"&&n.push(o)}return n}list(e){let t=this.map,n=e&&e.clientId,s=e&&e.connectionId,o=[];for(let a in t){let u=t[a];u.action!=="absent"&&(n&&n!=u.clientId||s&&s!=u.connectionId||o.push(u))}return o}put(e){(e.action==="enter"||e.action==="update")&&(e=Ee.fromValues(e),e.action="present");let t=this.map,n=this.memberKey(e);this.residualMembers&&delete this.residualMembers[n];let s=t[n];return s&&!this.newerThan(e,s)?!1:(t[n]=e,!0)}values(){let e=this.map,t=[];for(let n in e){let s=e[n];s.action!="absent"&&t.push(s)}return t}remove(e){let t=this.map,n=this.memberKey(e),s=t[n];return s&&!this.newerThan(e,s)?!1:(this.syncInProgress?(e=Ee.fromValues(e),e.action="absent",t[n]=e):delete t[n],!!s)}startSync(){let e=this.map,t=this.syncInProgress;c.logAction(this.logger,c.LOG_MINOR,"PresenceMap.startSync()","channel = "+this.presence.channel.name+"; syncInProgress = "+t),this.syncInProgress||(this.residualMembers=Le(e),this.setInProgress(!0))}endSync(){let e=this.map,t=this.syncInProgress;if(c.logAction(this.logger,c.LOG_MINOR,"PresenceMap.endSync()","channel = "+this.presence.channel.name+"; syncInProgress = "+t),t){for(let n in e)e[n].action==="absent"&&delete e[n];this.presence._synthesizeLeaves(gi(this.residualMembers));for(let n in this.residualMembers)delete e[n];this.residualMembers=null,this.setInProgress(!1)}this.emit("sync")}waitSync(e){let t=this.syncInProgress;if(c.logAction(this.logger,c.LOG_MINOR,"PresenceMap.waitSync()","channel = "+this.presence.channel.name+"; syncInProgress = "+t),!t){e();return}this.once("sync",e)}clear(){this.map={},this.setInProgress(!1),this.residualMembers=null}setInProgress(e){c.logAction(this.logger,c.LOG_MICRO,"PresenceMap.setInProgress()","inProgress = "+e),this.syncInProgress=e,this.presence.syncComplete=!e}};function _a(e){return e.channel.client.auth.clientId}function In(e){let t=e.channel.client,n=t.auth.clientId;return(!n||n==="*")&&t.connection.state==="connected"}function Ma(e,t,n){switch(e.state){case"attached":case"suspended":n();break;case"initialized":case"detached":case"detaching":case"attaching":X(e.attach(),function(s){s?t(s):n()});break;default:t(C.fromValues(e.invalidStateError()))}}var ka=class extends ${constructor(e){super(e.logger),this.channel=e,this.syncComplete=!1,this.members=new vn(this,t=>t.clientId+":"+t.connectionId),this._myMembers=new vn(this,t=>t.clientId),this.subscriptions=new $(this.logger),this.pendingPresence=[]}async enter(e){if(In(this))throw new C("clientId must be specified to enter a presence channel",40012,400);return this._enterOrUpdateClient(void 0,void 0,e,"enter")}async update(e){if(In(this))throw new C("clientId must be specified to update presence data",40012,400);return this._enterOrUpdateClient(void 0,void 0,e,"update")}async enterClient(e,t){return this._enterOrUpdateClient(void 0,e,t,"enter")}async updateClient(e,t){return this._enterOrUpdateClient(void 0,e,t,"update")}async _enterOrUpdateClient(e,t,n,s){let o=this.channel;if(!o.connectionManager.activeState())throw o.connectionManager.getError();c.logAction(this.logger,c.LOG_MICRO,"RealtimePresence."+s+"Client()","channel = "+o.name+", id = "+e+", client = "+(t||"(implicit) "+_a(this)));let a=Ee.fromData(n);a.action=s,e&&(a.id=e),t&&(a.clientId=t);let u=await a.encode(o.channelOptions);switch(o.state){case"attached":return o.sendPresence([u]);case"initialized":case"detached":o.attach();case"attaching":return new Promise((f,E)=>{this.pendingPresence.push({presence:u,callback:g=>g?E(g):f()})});default:{let f=new J("Unable to "+s+" presence channel while in "+o.state+" state",90001);throw f.code=90001,f}}}async leave(e){if(In(this))throw new C("clientId must have been specified to enter or leave a presence channel",40012,400);return this.leaveClient(void 0,e)}async leaveClient(e,t){let n=this.channel;if(!n.connectionManager.activeState())throw n.connectionManager.getError();c.logAction(this.logger,c.LOG_MICRO,"RealtimePresence.leaveClient()","leaving; channel = "+this.channel.name+", client = "+e);let s=Ee.fromData(t);s.action="leave",e&&(s.clientId=e);let o=await s.encode(n.channelOptions);switch(n.state){case"attached":return n.sendPresence([o]);case"attaching":return new Promise((a,u)=>{this.pendingPresence.push({presence:o,callback:f=>f?u(f):a()})});case"initialized":case"failed":throw new J("Unable to leave presence channel (incompatible state)",90001);default:throw n.invalidStateError()}}async get(e){let t=!e||("waitForSync"in e?e.waitForSync:!0);return new Promise((n,s)=>{function o(a){n(e?a.list(e):a.values())}if(this.channel.state==="suspended"){t?s(C.fromValues({statusCode:400,code:91005,message:"Presence state is out of sync due to channel being in the SUSPENDED state"})):o(this.members);return}Ma(this.channel,a=>s(a),()=>{let a=this.members;t?a.waitSync(function(){o(a)}):o(a)})})}async history(e){c.logAction(this.logger,c.LOG_MICRO,"RealtimePresence.history()","channel = "+this.name);let t=this.channel.client.rest.presenceMixin;if(e&&e.untilAttach)if(this.channel.state==="attached")delete e.untilAttach,e.from_serial=this.channel.properties.attachSerial;else throw new C("option untilAttach requires the channel to be attached, was: "+this.channel.state,4e4,400);return t.history(this,e)}setPresence(e,t,n){c.logAction(this.logger,c.LOG_MICRO,"RealtimePresence.setPresence()","received presence for "+e.length+" participants; syncChannelSerial = "+n);let s,o,a=this.members,u=this._myMembers,f=[],E=this.channel.connectionManager.connectionId;t&&(this.members.startSync(),n&&(o=n.match(/^[\w-]+:(.*)$/))&&(s=o[1]));for(let g of e)switch(g.action){case"leave":a.remove(g)&&f.push(g),g.connectionId===E&&!g.isSynthesized()&&u.remove(g);break;case"enter":case"present":case"update":a.put(g)&&f.push(g),g.connectionId===E&&u.put(g);break}t&&!s&&(a.endSync(),this.channel.syncChannelSerial=null);for(let g=0;g<f.length;g++){let A=f[g];this.subscriptions.emit(A.action,A)}}onAttached(e){c.logAction(this.logger,c.LOG_MINOR,"RealtimePresence.onAttached()","channel = "+this.channel.name+", hasPresence = "+e),e?this.members.startSync():(this._synthesizeLeaves(this.members.values()),this.members.clear()),this._ensureMyMembersPresent();let t=this.pendingPresence,n=t.length;if(n){this.pendingPresence=[];let s=[],o=an.create(this.logger);c.logAction(this.logger,c.LOG_MICRO,"RealtimePresence.onAttached","sending "+n+" queued presence messages");for(let a=0;a<n;a++){let u=t[a];s.push(u.presence),o.push(u.callback)}this.channel.sendPresence(s).then(()=>o()).catch(a=>o(a))}}actOnChannelState(e,t,n){switch(e){case"attached":this.onAttached(t);break;case"detached":case"failed":this._clearMyMembers(),this.members.clear();case"suspended":this.failPendingPresence(n);break}}failPendingPresence(e){if(this.pendingPresence.length){c.logAction(this.logger,c.LOG_MINOR,"RealtimeChannel.failPendingPresence","channel; name = "+this.channel.name+", err = "+G(e));for(let t=0;t<this.pendingPresence.length;t++)try{this.pendingPresence[t].callback(e)}catch{}this.pendingPresence=[]}}_clearMyMembers(){this._myMembers.clear()}_ensureMyMembersPresent(){let e=this._myMembers,t=this.channel.connectionManager.connectionId;for(let n in e.map){let s=e.map[n];c.logAction(this.logger,c.LOG_MICRO,"RealtimePresence._ensureMyMembersPresent()",'Auto-reentering clientId "'+s.clientId+'" into the presence set');let o=s.connectionId===t?s.id:void 0;this._enterOrUpdateClient(o,s.clientId,s.data,"enter").catch(a=>{let u=new C("Presence auto re-enter failed",91004,400,a);c.logAction(this.logger,c.LOG_ERROR,"RealtimePresence._ensureMyMembersPresent()","Presence auto re-enter failed; reason = "+G(a));let f=new Cn(this.channel.state,this.channel.state,!0,!1,u);this.channel.emit("update",f)})}}_synthesizeLeaves(e){let t=this.subscriptions;e.forEach(function(n){let s=Ee.fromValues({action:"leave",connectionId:n.connectionId,clientId:n.clientId,data:n.data,encoding:n.encoding,timestamp:Date.now()});t.emit("leave",s)})}async subscribe(...e){let t=rt.processListenerArgs(e),n=t[0],s=t[1],o=this.channel;if(o.state==="failed")throw C.fromValues(o.invalidStateError());this.subscriptions.on(n,s),o.channelOptions.attachOnSubscribe!==!1&&await o.attach()}unsubscribe(...e){let t=rt.processListenerArgs(e),n=t[0],s=t[1];this.subscriptions.off(n,s)}},Pa=ka,Na=ee.WebSocket;function La(e){return!!e.on}var xa=class extends He{constructor(e,t,n){super(e,t,n),this.shortName=Na,n.heartbeats=b.Config.useProtocolHeartbeats,this.wsHost=n.host}static isAvailable(){return!!b.Config.WebSocket}createWebSocket(e,t){return this.uri=e+nt(t),new b.Config.WebSocket(this.uri)}toString(){return"WebSocketTransport; uri="+this.uri}connect(){c.logAction(this.logger,c.LOG_MINOR,"WebSocketTransport.connect()","starting"),He.prototype.connect.call(this);let e=this,t=this.params,n=t.options,o=(n.tls?"wss://":"ws://")+this.wsHost+":"+L.getPort(n)+"/";c.logAction(this.logger,c.LOG_MINOR,"WebSocketTransport.connect()","uri: "+o),X(this.auth.getAuthParams(),function(a,u){if(e.isDisposed)return;let f="";for(let g in u)f+=" "+g+": "+u[g]+";";if(c.logAction(e.logger,c.LOG_MINOR,"WebSocketTransport.connect()","authParams:"+f+" err: "+a),a){e.disconnect(a);return}let E=t.getConnectParams(u);try{let g=e.wsConnection=e.createWebSocket(o,E);g.binaryType=b.Config.binaryType,g.onopen=function(){e.onWsOpen()},g.onclose=function(A){e.onWsClose(A)},g.onmessage=function(A){e.onWsData(A.data)},g.onerror=function(A){e.onWsError(A)},La(g)&&g.on("ping",function(){e.onActivity()})}catch(g){c.logAction(e.logger,c.LOG_ERROR,"WebSocketTransport.connect()","Unexpected exception creating websocket: err = "+(g.stack||g.message)),e.disconnect(g)}})}send(e){let t=this.wsConnection;if(!t){c.logAction(this.logger,c.LOG_ERROR,"WebSocketTransport.send()","No socket connection");return}try{t.send(ia(e,this.connectionManager.realtime._MsgPack,this.params.format))}catch(n){let s="Exception from ws connection when trying to send: "+G(n);c.logAction(this.logger,c.LOG_ERROR,"WebSocketTransport.send()",s),this.finish("disconnected",new C(s,5e4,500))}}onWsData(e){c.logAction(this.logger,c.LOG_MICRO,"WebSocketTransport.onWsData()","data received; length = "+e.length+"; type = "+typeof e);try{this.onProtocolMessage(sa(e,this.connectionManager.realtime._MsgPack,this.connectionManager.realtime._RealtimePresence,this.connectionManager.realtime._Annotations,this.connectionManager.realtime._objectsPlugin,this.format))}catch(t){c.logAction(this.logger,c.LOG_ERROR,"WebSocketTransport.onWsData()","Unexpected exception handing channel message: "+t.stack)}}onWsOpen(){c.logAction(this.logger,c.LOG_MINOR,"WebSocketTransport.onWsOpen()","opened WebSocket"),this.emit("preconnect")}onWsClose(e){let t,n;if(typeof e=="object"?(n=e.code,t=e.wasClean||n===1e3):(n=e,t=n==1e3),delete this.wsConnection,t){c.logAction(this.logger,c.LOG_MINOR,"WebSocketTransport.onWsClose()","Cleanly closed WebSocket");let s=new C("Websocket closed",80003,400);this.finish("disconnected",s)}else{let s="Unclean disconnection of WebSocket ; code = "+n,o=new C(s,80003,400);c.logAction(this.logger,c.LOG_MINOR,"WebSocketTransport.onWsClose()",s),this.finish("disconnected",o)}this.emit("disposed")}onWsError(e){c.logAction(this.logger,c.LOG_MINOR,"WebSocketTransport.onError()","Error from WebSocket: "+e.message),b.Config.nextTick(()=>{this.disconnect(Error(e.message))})}dispose(){c.logAction(this.logger,c.LOG_MINOR,"WebSocketTransport.dispose()",""),this.isDisposed=!0;let e=this.wsConnection;e&&(e.onmessage=function(){},delete this.wsConnection,b.Config.nextTick(()=>{if(c.logAction(this.logger,c.LOG_MICRO,"WebSocketTransport.dispose()","closing websocket"),!e)throw new Error("WebSocketTransport.dispose(): wsConnection is not defined");e.close()}))}},Ms=xa,Ua=class{static subscribeFilter(e,t,n){let s=o=>{var a,u,f,E,g,A;let w={name:o.name,refTimeserial:(u=(a=o.extras)==null?void 0:a.ref)==null?void 0:u.timeserial,refType:(E=(f=o.extras)==null?void 0:f.ref)==null?void 0:E.type,isRef:!!((A=(g=o.extras)==null?void 0:g.ref)!=null&&A.timeserial),clientId:o.clientId};Object.entries(t).find(([v,R])=>R!==void 0?w[v]!==R:!1)||n(o)};this.addFilteredSubscription(e,t,n,s),e.subscriptions.on(s)}static addFilteredSubscription(e,t,n,s){var o;if(e.filteredSubscriptions||(e.filteredSubscriptions=new Map),e.filteredSubscriptions.has(n)){let a=e.filteredSubscriptions.get(n);a.set(t,((o=a?.get(t))==null?void 0:o.concat(s))||[s])}else e.filteredSubscriptions.set(n,new Map([[t,[s]]]))}static getAndDeleteFilteredSubscriptions(e,t,n){if(!e.filteredSubscriptions)return[];if(!n&&t)return Array.from(e.filteredSubscriptions.entries()).map(([a,u])=>{var f;let E=u.get(t);return u.delete(t),u.size===0&&((f=e.filteredSubscriptions)==null||f.delete(a)),E}).reduce((a,u)=>u?a.concat(...u):a,[]);if(!n||!e.filteredSubscriptions.has(n))return[];let s=e.filteredSubscriptions.get(n);if(!t){let a=Array.from(s.values()).reduce((u,f)=>u.concat(...f),[]);return e.filteredSubscriptions.delete(n),a}let o=s.get(t);return s.delete(t),o||[]}},oe=class si extends Oa{constructor(t){var n;let s=si._MsgPack;if(!s)throw new Error("Expected DefaultRealtime._MsgPack to have been set");super(L.objectifyOptions(t,!0,"Realtime",c.defaultLogger,H(O({},ds),{Crypto:(n=si.Crypto)!=null?n:void 0,MsgPack:s,RealtimePresence:{RealtimePresence:Pa,PresenceMessage:Ee,WirePresenceMessage:it},Annotations:{Annotation:qe,WireAnnotation:Ge,RealtimeAnnotations:Sn,RestAnnotations:Ft},WebSocketTransport:Ms,MessageInteractions:Ua})))}static get Crypto(){if(this._Crypto===null)throw new Error("Encryption not enabled; use ably.encryption.js instead");return this._Crypto}static set Crypto(t){this._Crypto=t}};oe.Utils=Ne,oe.ConnectionManager=Ts,oe.ProtocolMessage=ra,oe._Crypto=null,oe.Message=fs,oe.PresenceMessage=ps,oe.Annotation=Es,oe._MsgPack=null,oe._Http=hn,oe._PresenceMap=vn,oe._MessageEncoding=Ut;var On=oe,Tn=Uint8Array,at=Uint32Array,_n=Math.pow,ks=new at(8),Ps=[],ct=new at(64);function Ns(e){return(e-(e|0))*_n(2,32)|0}for(var lt=2,ht=0;ht<64;){for(Mn=!0,Ht=2;Ht<=lt/2;Ht++)lt%Ht===0&&(Mn=!1);Mn&&(ht<8&&(ks[ht]=Ns(_n(lt,1/2))),Ps[ht]=Ns(_n(lt,1/3)),ht++),lt++}var Mn,Ht,Ba=!!new Tn(new at([1]).buffer)[0];function kn(e){return Ba?e>>>24|(e>>>16&255)<<8|(e&65280)<<8|e<<24:e}function fe(e,t){return e>>>t|e<<32-t}function Vt(e){var t=ks.slice(),n=e.length,s=n*8,o=512-(s+64)%512-1+s+65,a=new Tn(o/8),u=new at(a.buffer);a.set(e,0),a[n]=128,u[u.length-1]=kn(s);for(var f,E=0;E<o/32;E+=16){var g=t.slice();for(f=0;f<64;f++){var A;if(f<16)A=kn(u[E+f]);else{var w=ct[f-15],v=ct[f-2];A=ct[f-7]+ct[f-16]+(fe(w,7)^fe(w,18)^w>>>3)+(fe(v,17)^fe(v,19)^v>>>10)}ct[f]=A|=0;for(var R=(fe(g[4],6)^fe(g[4],11)^fe(g[4],25))+(g[4]&g[5]^~g[4]&g[6])+g[7]+A+Ps[f],T=(fe(g[0],2)^fe(g[0],13)^fe(g[0],22))+(g[0]&g[1]^g[2]&(g[0]^g[1])),_=7;_>0;_--)g[_]=g[_-1];g[0]=R+T|0,g[4]=g[4]+R|0}for(f=0;f<8;f++)t[f]=t[f]+g[f]|0}return new Tn(new at(t.map(function(N){return kn(N)})).buffer)}function Da(e,t){if(e.length>64&&(e=Vt(e)),e.length<64){let f=new Uint8Array(64);f.set(e,0),e=f}for(var n=new Uint8Array(64),s=new Uint8Array(64),o=0;o<64;o++)n[o]=54^e[o],s[o]=92^e[o];var a=new Uint8Array(t.length+64);a.set(n,0),a.set(t,64);var u=new Uint8Array(96);return u.set(s,0),u.set(Vt(a),64),Vt(u)}var Fa=class{constructor(){this.base64CharSet="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",this.hexCharSet="0123456789abcdef"}uint8ViewToBase64(e){let t="",n=this.base64CharSet,s=e.byteLength,o=s%3,a=s-o,u,f,E,g,A;for(let w=0;w<a;w=w+3)A=e[w]<<16|e[w+1]<<8|e[w+2],u=(A&16515072)>>18,f=(A&258048)>>12,E=(A&4032)>>6,g=A&63,t+=n[u]+n[f]+n[E]+n[g];return o==1?(A=e[a],u=(A&252)>>2,f=(A&3)<<4,t+=n[u]+n[f]+"=="):o==2&&(A=e[a]<<8|e[a+1],u=(A&64512)>>10,f=(A&1008)>>4,E=(A&15)<<2,t+=n[u]+n[f]+n[E]+"="),t}base64ToArrayBuffer(e){let t=atob?.(e),n=t.length,s=new Uint8Array(n);for(let o=0;o<n;o++){let a=t.charCodeAt(o);s[o]=a}return this.toArrayBuffer(s)}isBuffer(e){return e instanceof ArrayBuffer||ArrayBuffer.isView(e)}toBuffer(e){if(!ArrayBuffer)throw new Error("Can't convert to Buffer: browser does not support the necessary types");if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(this.toArrayBuffer(e));throw new Error("BufferUtils.toBuffer expected an ArrayBuffer or a view onto one")}toArrayBuffer(e){if(!ArrayBuffer)throw new Error("Can't convert to ArrayBuffer: browser does not support the necessary types");if(e instanceof ArrayBuffer)return e;if(ArrayBuffer.isView(e))return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength);throw new Error("BufferUtils.toArrayBuffer expected an ArrayBuffer or a view onto one")}base64Encode(e){return this.uint8ViewToBase64(this.toBuffer(e))}base64UrlEncode(e){return this.base64Encode(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}base64Decode(e){if(ArrayBuffer&&b.Config.atob)return this.base64ToArrayBuffer(e);throw new Error("Expected ArrayBuffer to exist and Platform.Config.atob to be configured")}hexEncode(e){return this.toBuffer(e).reduce((n,s)=>n+s.toString(16).padStart(2,"0"),"")}hexDecode(e){if(e.length%2!==0)throw new Error("Can't create a byte array from a hex string of odd length");let t=new Uint8Array(e.length/2);for(let n=0;n<t.length;n++)t[n]=parseInt(e.slice(2*n,2*(n+1)),16);return this.toArrayBuffer(t)}utf8Encode(e){if(b.Config.TextEncoder){let t=new b.Config.TextEncoder().encode(e);return this.toArrayBuffer(t)}else throw new Error("Expected TextEncoder to be configured")}utf8Decode(e){if(!this.isBuffer(e))throw new Error("Expected input of utf8decode to be an arraybuffer or typed array");if(TextDecoder)return new TextDecoder().decode(e);throw new Error("Expected TextDecoder to be configured")}areBuffersEqual(e,t){if(!e||!t)return!1;let n=this.toArrayBuffer(e),s=this.toArrayBuffer(t);if(n.byteLength!=s.byteLength)return!1;let o=new Uint8Array(n),a=new Uint8Array(s);for(var u=0;u<o.length;u++)if(o[u]!=a[u])return!1;return!0}byteLength(e){return e instanceof ArrayBuffer||ArrayBuffer.isView(e)?e.byteLength:-1}arrayBufferViewToBuffer(e){return this.toArrayBuffer(e)}concat(e){let t=e.reduce((o,a)=>o+a.byteLength,0),n=new Uint8Array(t),s=0;for(let o of e){let a=this.toBuffer(o);n.set(a,s),s+=a.byteLength}return n.buffer}sha256(e){let t=Vt(this.toBuffer(e));return this.toArrayBuffer(t)}hmacSha256(e,t){let n=Da(this.toBuffer(t),this.toBuffer(e));return this.toArrayBuffer(n)}},Ls=new Fa,Ga=function(e,t){var n="aes",s=256,o="cbc",a=16;function u(v){if(v.algorithm==="aes"&&v.mode==="cbc"){if(v.keyLength===128||v.keyLength===256)return;throw new Error("Unsupported key length "+v.keyLength+" for aes-cbc encryption. Encryption key must be 128 or 256 bits (16 or 32 ASCII characters)")}}function f(v){return v.replace("_","/").replace("-","+")}function E(v){return v instanceof g}class g{constructor(R,T,_,N){this.algorithm=R,this.keyLength=T,this.mode=_,this.key=N}}class A{static getDefaultParams(R){var T;if(!R.key)throw new Error("Crypto.getDefaultParams: a key is required");typeof R.key=="string"?T=t.toArrayBuffer(t.base64Decode(f(R.key))):R.key instanceof ArrayBuffer?T=R.key:T=t.toArrayBuffer(R.key);var _=R.algorithm||n,N=T.byteLength*8,D=R.mode||o,F=new g(_,N,D,T);if(R.keyLength&&R.keyLength!==F.keyLength)throw new Error("Crypto.getDefaultParams: a keyLength of "+R.keyLength+" was specified, but the key actually has length "+F.keyLength);return u(F),F}static async generateRandomKey(R){try{return e.getRandomArrayBuffer((R||s)/8)}catch(T){throw new C("Failed to generate random key: "+T.message,400,5e4,T)}}static getCipher(R,T){var _,N=E(R)?R:this.getDefaultParams(R);return{cipherParams:N,cipher:new w(N,(_=R.iv)!=null?_:null,T)}}}A.CipherParams=g;class w{constructor(R,T,_){if(this.logger=_,!crypto.subtle)throw isSecureContext?new Error("Crypto operations are not possible since the browser\u2019s SubtleCrypto class is unavailable (reason unknown)."):new Error("Crypto operations are is not possible since the current environment is a non-secure context and hence the browser\u2019s SubtleCrypto class is not available.");this.algorithm=R.algorithm+"-"+String(R.keyLength)+"-"+R.mode,this.webCryptoAlgorithm=R.algorithm+"-"+R.mode,this.key=t.toArrayBuffer(R.key),this.iv=T?t.toArrayBuffer(T):null}concat(R,T){let _=new ArrayBuffer(R.byteLength+T.byteLength),N=new DataView(_),D=new DataView(t.toArrayBuffer(R));for(let q=0;q<D.byteLength;q++)N.setInt8(q,D.getInt8(q));let F=new DataView(t.toArrayBuffer(T));for(let q=0;q<F.byteLength;q++)N.setInt8(D.byteLength+q,F.getInt8(q));return _}async encrypt(R){c.logAction(this.logger,c.LOG_MICRO,"CBCCipher.encrypt()","");let T=await this.getIv(),_=await crypto.subtle.importKey("raw",this.key,this.webCryptoAlgorithm,!1,["encrypt"]),N=await crypto.subtle.encrypt({name:this.webCryptoAlgorithm,iv:T},_,R);return this.concat(T,N)}async decrypt(R){c.logAction(this.logger,c.LOG_MICRO,"CBCCipher.decrypt()","");let T=t.toArrayBuffer(R),_=T.slice(0,a),N=T.slice(a),D=await crypto.subtle.importKey("raw",this.key,this.webCryptoAlgorithm,!1,["decrypt"]);return crypto.subtle.decrypt({name:this.webCryptoAlgorithm,iv:_},D,N)}async getIv(){if(this.iv){var R=this.iv;return this.iv=null,R}let T=await e.getRandomArrayBuffer(a);return t.toArrayBuffer(T)}}return A},xs=(e=>(e[e.REQ_SEND=0]="REQ_SEND",e[e.REQ_RECV=1]="REQ_RECV",e[e.REQ_RECV_POLL=2]="REQ_RECV_POLL",e[e.REQ_RECV_STREAM=3]="REQ_RECV_STREAM",e))(xs||{}),Ce=xs;function Us(){return new C("No HTTP request plugin provided. Provide at least one of the FetchRequest or XHRRequest plugins.",400,4e4)}var ut,Bs=(ut=class{constructor(e){this.checksInProgress=null,this.checkConnectivity=void 0,this.supportsAuthHeaders=!1,this.supportsLinkHeaders=!1;var t;this.client=e??null;let n=e?.options.connectivityCheckUrl||L.connectivityCheckUrl,s=(t=e?.options.connectivityCheckParams)!=null?t:null,o=!e?.options.connectivityCheckUrl,a=O(O({},Bs.bundledRequestImplementations),e?._additionalHTTPRequestImplementations),u=a.XHRRequest,f=a.FetchRequest,E=!!(u||f);if(!E)throw Us();b.Config.xhrSupported&&u?(this.supportsAuthHeaders=!0,this.Request=async function(g,A,w,v,R){return new Promise(T=>{var _;let N=u.createRequest(A,w,v,R,Ce.REQ_SEND,(_=e&&e.options.timeouts)!=null?_:null,this.logger,g);N.once("complete",(D,F,q,x,se)=>T({error:D,body:F,headers:q,unpacked:x,statusCode:se})),N.exec()})},e?.options.disableConnectivityCheck?this.checkConnectivity=async function(){return!0}:this.checkConnectivity=async function(){var g;c.logAction(this.logger,c.LOG_MICRO,"(XHRRequest)Http.checkConnectivity()","Sending; "+n);let A=await this.doUri(V.Get,n,null,null,s),w=!1;return o?w=!A.error&&((g=A.body)==null?void 0:g.replace(/\n/,""))=="yes":w=!A.error&&no(A.statusCode),c.logAction(this.logger,c.LOG_MICRO,"(XHRRequest)Http.checkConnectivity()","Result: "+w),w}):b.Config.fetchSupported&&f?(this.supportsAuthHeaders=!0,this.Request=async(g,A,w,v,R)=>f(g,e??null,A,w,v,R),e?.options.disableConnectivityCheck?this.checkConnectivity=async function(){return!0}:this.checkConnectivity=async function(){var g;c.logAction(this.logger,c.LOG_MICRO,"(Fetch)Http.checkConnectivity()","Sending; "+n);let A=await this.doUri(V.Get,n,null,null,null),w=!A.error&&((g=A.body)==null?void 0:g.replace(/\n/,""))=="yes";return c.logAction(this.logger,c.LOG_MICRO,"(Fetch)Http.checkConnectivity()","Result: "+w),w}):this.Request=async()=>({error:E?new J("no supported HTTP transports available",null,400):Us()})}get logger(){var e,t;return(t=(e=this.client)==null?void 0:e.logger)!=null?t:c.defaultLogger}async doUri(e,t,n,s,o){return this.Request?this.Request(e,t,n,o,s):{error:new J("Request invoked before assigned to",null,500)}}shouldFallback(e){let t=e.statusCode;return t===408&&!e.code||t===400&&!e.code||t>=500&&t<=504}},ut.methods=[V.Get,V.Delete,V.Post,V.Put,V.Patch],ut.methodsWithoutBody=[V.Get,V.Delete],ut.methodsWithBody=[V.Post,V.Put,V.Patch],ut),Ds=Bs,Ve="ablyjs-storage-test",je=typeof globalThis<"u"?globalThis:typeof window<"u"?window:self,qa=class{constructor(){try{je.sessionStorage.setItem(Ve,Ve),je.sessionStorage.removeItem(Ve),this.sessionSupported=!0}catch{this.sessionSupported=!1}try{je.localStorage.setItem(Ve,Ve),je.localStorage.removeItem(Ve),this.localSupported=!0}catch{this.localSupported=!1}}get(e){return this._get(e,!1)}getSession(e){return this._get(e,!0)}remove(e){return this._remove(e,!1)}removeSession(e){return this._remove(e,!0)}set(e,t,n){return this._set(e,t,n,!1)}setSession(e,t,n){return this._set(e,t,n,!0)}_set(e,t,n,s){let o={value:t};return n&&(o.expires=Date.now()+n),this.storageInterface(s).setItem(e,JSON.stringify(o))}_get(e,t){if(t&&!this.sessionSupported)throw new Error("Session Storage not supported");if(!t&&!this.localSupported)throw new Error("Local Storage not supported");let n=this.storageInterface(t).getItem(e);if(!n)return null;let s=JSON.parse(n);return s.expires&&s.expires<Date.now()?(this.storageInterface(t).removeItem(e),null):s.value}_remove(e,t){return this.storageInterface(t).removeItem(e)}storageInterface(e){return e?je.sessionStorage:je.localStorage}},Fs=new qa,j=rn(),Ha=typeof EdgeRuntime=="string";typeof Window>"u"&&typeof WorkerGlobalScope>"u"&&!Ha&&console.log("Warning: this distribution of Ably is intended for browsers. On nodejs, please use the 'ably' package on npm");function Va(){let e=j.location;return!j.WebSocket||!e||!e.origin||e.origin.indexOf("http")>-1}function ja(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}var Wa=j.navigator&&j.navigator.userAgent.toString(),Ka=j.location&&j.location.href,$a={agent:"browser",logTimestamps:!0,userAgent:Wa,currentUrl:Ka,binaryType:"arraybuffer",WebSocket:j.WebSocket,fetchSupported:!!j.fetch,xhrSupported:j.XMLHttpRequest&&"withCredentials"in new XMLHttpRequest,allowComet:Va(),useProtocolHeartbeats:!0,supportsBinary:!!j.TextDecoder,preferBinary:!1,ArrayBuffer:j.ArrayBuffer,atob:j.atob,nextTick:typeof j.setImmediate<"u"?j.setImmediate.bind(j):function(e){setTimeout(e,0)},addEventListener:j.addEventListener,inspect:JSON.stringify,stringByteSize:function(e){return j.TextDecoder&&new j.TextEncoder().encode(e).length||e.length},TextEncoder:j.TextEncoder,TextDecoder:j.TextDecoder,getRandomArrayBuffer:async function(e){let t=new Uint8Array(e);return j.crypto.getRandomValues(t),t.buffer},isWebworker:ja(),push:{platform:"browser",formFactor:"desktop",storage:Fs}},Gs=$a;function za(e){let t=[80015,80017,80030];return e.code?ye.isTokenErr(e)?!1:t.includes(e.code)?!0:e.code>=4e4&&e.code<5e4:!1}function Pn(e){return za(e)?[ie({action:P.ERROR,error:e})]:[ie({action:P.DISCONNECTED,error:e})]}var Ja=class extends He{constructor(e,t,n){super(e,t,n,!0),this.onAuthUpdated=s=>{this.authParams={access_token:s.token}},this.stream="stream"in n?n.stream:!0,this.sendRequest=null,this.recvRequest=null,this.pendingCallback=null,this.pendingItems=null}connect(){c.logAction(this.logger,c.LOG_MINOR,"CometTransport.connect()","starting"),He.prototype.connect.call(this);let e=this.params,t=e.options,n=e.host||t.primaryDomain,s=L.getPort(t),o=t.tls?"https://":"http://";this.baseUri=o+n+":"+s+"/comet/";let a=this.baseUri+"connect";c.logAction(this.logger,c.LOG_MINOR,"CometTransport.connect()","uri: "+a),X(this.auth.getAuthParams(),(u,f)=>{if(u){this.disconnect(u);return}if(this.isDisposed)return;this.authParams=f;let E=this.params.getConnectParams(f);"stream"in E&&(this.stream=E.stream),c.logAction(this.logger,c.LOG_MINOR,"CometTransport.connect()","connectParams:"+nt(E));let g=!1,A=this.recvRequest=this.createRequest(a,null,E,null,this.stream?Ce.REQ_RECV_STREAM:Ce.REQ_RECV);A.on("data",w=>{this.recvRequest&&(g||(g=!0,this.emit("preconnect")),this.onData(w))}),A.on("complete",w=>{if(this.recvRequest||(w=w||new C("Request cancelled",80003,400)),this.recvRequest=null,!g&&!w&&(g=!0,this.emit("preconnect")),this.onActivity(),w){w.code?this.onData(Pn(w)):this.disconnect(w);return}b.Config.nextTick(()=>{this.recv()})}),A.exec()})}requestClose(){c.logAction(this.logger,c.LOG_MINOR,"CometTransport.requestClose()"),this._requestCloseOrDisconnect(!0)}requestDisconnect(){c.logAction(this.logger,c.LOG_MINOR,"CometTransport.requestDisconnect()"),this._requestCloseOrDisconnect(!1)}_requestCloseOrDisconnect(e){let t=e?this.closeUri:this.disconnectUri;if(t){let n=this.createRequest(t,null,this.authParams,null,Ce.REQ_SEND);n.on("complete",s=>{s&&(c.logAction(this.logger,c.LOG_ERROR,"CometTransport.request"+(e?"Close()":"Disconnect()"),"request returned err = "+G(s)),this.finish("disconnected",s))}),n.exec()}}dispose(){c.logAction(this.logger,c.LOG_MINOR,"CometTransport.dispose()",""),this.isDisposed||(this.isDisposed=!0,this.recvRequest&&(c.logAction(this.logger,c.LOG_MINOR,"CometTransport.dispose()","aborting recv request"),this.recvRequest.abort(),this.recvRequest=null),this.finish("disconnected",Oe.disconnected()),b.Config.nextTick(()=>{this.emit("disposed")}))}onConnect(e){var t;if(this.isDisposed)return;let n=(t=e.connectionDetails)==null?void 0:t.connectionKey;He.prototype.onConnect.call(this,e);let s=this.baseUri+n;c.logAction(this.logger,c.LOG_MICRO,"CometTransport.onConnect()","baseUri = "+s),this.sendUri=s+"/send",this.recvUri=s+"/recv",this.closeUri=s+"/close",this.disconnectUri=s+"/disconnect"}send(e){if(this.sendRequest){this.pendingItems=this.pendingItems||[],this.pendingItems.push(e);return}let t=this.pendingItems||[];t.push(e),this.pendingItems=null,this.sendItems(t)}sendAnyPending(){let e=this.pendingItems;e&&(this.pendingItems=null,this.sendItems(e))}sendItems(e){let t=this.sendRequest=this.createRequest(this.sendUri,null,this.authParams,this.encodeRequest(e),Ce.REQ_SEND);t.on("complete",(n,s)=>{if(n&&c.logAction(this.logger,c.LOG_ERROR,"CometTransport.sendItems()","on complete: err = "+G(n)),this.sendRequest=null,n){n.code?this.onData(Pn(n)):this.disconnect(n);return}s&&this.onData(s),this.pendingItems&&b.Config.nextTick(()=>{this.sendRequest||this.sendAnyPending()})}),t.exec()}recv(){if(this.recvRequest||!this.isConnected)return;let e=this.recvRequest=this.createRequest(this.recvUri,null,this.authParams,null,this.stream?Ce.REQ_RECV_STREAM:Ce.REQ_RECV_POLL);e.on("data",t=>{this.onData(t)}),e.on("complete",t=>{if(this.recvRequest=null,this.onActivity(),t){t.code?this.onData(Pn(t)):this.disconnect(t);return}b.Config.nextTick(()=>{this.recv()})}),e.exec()}onData(e){try{let t=this.decodeResponse(e);if(t&&t.length)for(let n=0;n<t.length;n++)this.onProtocolMessage(mn(t[n],this.connectionManager.realtime._RealtimePresence,this.connectionManager.realtime._Annotations,this.connectionManager.realtime._objectsPlugin))}catch(t){c.logAction(this.logger,c.LOG_ERROR,"CometTransport.onData()","Unexpected exception handing channel event: "+t.stack)}}encodeRequest(e){return JSON.stringify(e)}decodeResponse(e){return typeof e=="string"?JSON.parse(e):e}},Qa=Ja;function Ya(e,t){return nn(tt(t)).includes("x-ably-errorcode")}function Xa(e,t){if(Ya(e,t))return e.error&&C.fromValues(e.error)}var Za=function(){},ec=0,qs={};function tc(e,t){return e.getResponseHeader&&e.getResponseHeader(t)}function nc(e){return e.getResponseHeader&&(e.getResponseHeader("transfer-encoding")||!e.getResponseHeader("content-length"))}function ic(e){let t=e.getAllResponseHeaders().trim().split(`\r
8
- `),n={};for(let s=0;s<t.length;s++){let o=t[s].split(":").map(a=>a.trim());n[o[0].toLowerCase()]=o[1]}return n}var sc=class Tr extends ${constructor(t,n,s,o,a,u,f,E){super(f),s=s||{},s.rnd=Mt(),this.uri=t+nt(s),this.headers=n||{},this.body=o,this.method=E?E.toUpperCase():ce(o)?"GET":"POST",this.requestMode=a,this.timeouts=u,this.timedOut=!1,this.requestComplete=!1,this.id=String(++ec),qs[this.id]=this}static createRequest(t,n,s,o,a,u,f,E){let g=u||L.TIMEOUTS;return new Tr(t,n,Le(s),o,a,g,f,E)}complete(t,n,s,o,a){this.requestComplete||(this.requestComplete=!0,!t&&n&&this.emit("data",n),this.emit("complete",t,n,s,o,a),this.dispose())}abort(){this.dispose()}exec(){let t=this.headers,n=this.requestMode==Ce.REQ_SEND?this.timeouts.httpRequestTimeout:this.timeouts.recvTimeout,s=this.timer=setTimeout(()=>{this.timedOut=!0,a.abort()},n),o=this.method,a=this.xhr=new XMLHttpRequest,u=t.accept,f=this.body,E="text";u?u.indexOf("application/x-msgpack")===0&&(E="arraybuffer"):t.accept="application/json",f&&(t["content-type"]||(t["content-type"]="application/json")).indexOf("application/json")>-1&&typeof f!="string"&&(f=JSON.stringify(f)),a.open(o,this.uri,!0),a.responseType=E,"authorization"in t&&(a.withCredentials=!0);for(let x in t)a.setRequestHeader(x,t[x]);let g=(x,se,Y,gt)=>{var We;let Un=se+" (event type: "+x.type+")";(We=this==null?void 0:this.xhr)!=null&&We.statusText&&(Un+=", current statusText is "+this.xhr.statusText),c.logAction(this.logger,c.LOG_ERROR,"Request.on"+x.type+"()",Un),this.complete(new J(Un,Y,gt))};a.onerror=x=>{g(x,"XHR error occurred",null,400)},a.onabort=x=>{this.timedOut?g(x,"Request aborted due to request timeout expiring",null,408):g(x,"Request cancelled",null,400)},a.ontimeout=x=>{g(x,"Request timed out",null,408)};let A,w,v,R=0,T=!1,_=()=>{if(clearTimeout(s),v=w<400,w==204){this.complete(null,null,null,null,w);return}A=this.requestMode==Ce.REQ_RECV_STREAM&&v&&nc(a)},N=()=>{let x;try{let Y=tc(a,"content-type");if(Y?Y.indexOf("application/json")>=0:a.responseType=="text"){let We=a.responseType==="arraybuffer"?b.BufferUtils.utf8Decode(a.response):String(a.responseText);We.length?x=JSON.parse(We):x=We,T=!0}else x=a.response;x.response!==void 0?(w=x.statusCode,v=w<400,t=x.headers,x=x.response):t=ic(a)}catch(Y){this.complete(new J("Malformed response body from server: "+Y.message,null,400));return}if(v||Array.isArray(x)){this.complete(null,x,t,T,w);return}let se=Xa(x,t);se||(se=new J("Error response received from server: "+w+" body was: "+b.Config.inspect(x),null,w)),this.complete(se,x,t,T,w)};function D(){let x=a.responseText,se=x.length-1,Y,gt;for(;R<se&&(Y=x.indexOf(`
9
- `,R))>-1;)gt=x.slice(R,Y),R=Y+1,F(gt)}let F=x=>{try{x=JSON.parse(x)}catch(se){this.complete(new J("Malformed response body from server: "+se.message,null,400));return}this.emit("data",x)},q=()=>{D(),this.streamComplete=!0,b.Config.nextTick(()=>{this.complete()})};a.onreadystatechange=()=>{let x=a.readyState;x<3||a.status!==0&&(w===void 0&&(w=a.status,_()),x==3&&A?D():x==4&&(A?q():N()))},a.send(f)}dispose(){let t=this.xhr;if(t){t.onreadystatechange=t.onerror=t.onabort=t.ontimeout=Za,this.xhr=null;let n=this.timer;n&&(clearTimeout(n),this.timer=null),this.requestComplete||t.abort()}delete qs[this.id]}},Hs=sc,Vs=ee.XhrPolling,rc=class extends Qa{constructor(e,t,n){super(e,t,n),this.shortName=Vs,n.stream=!1,this.shortName=Vs}static isAvailable(){return!!(b.Config.xhrSupported&&b.Config.allowComet)}toString(){return"XHRPollingTransport; uri="+this.baseUri+"; isConnected="+this.isConnected}createRequest(e,t,n,s,o){return Hs.createRequest(e,t,n,s,o,this.timeouts,this.logger)}},oc=rc,ac=["xhr_polling"],cc={order:ac,bundledImplementations:{web_socket:Ms,xhr_polling:oc}},lc=cc,hc={connectivityCheckUrl:"https://internet-up.ably-realtime.com/is-the-internet-up.txt",wsConnectivityCheckUrl:"wss://ws-up.ably-realtime.com",defaultTransports:[ee.XhrPolling,ee.WebSocket]},uc=hc;function dc(e){if(e===void 0)return"undefined";let t,n;if(e instanceof ArrayBuffer?(n="ArrayBuffer",t=new DataView(e)):e instanceof DataView&&(n="DataView",t=e),!t)return JSON.stringify(e);let s=[];for(let o=0;o<e.byteLength;o++){if(o>20){s.push("...");break}let a=t.getUint8(o).toString(16);a.length===1&&(a="0"+a),s.push(a)}return"<"+n+" "+s.join(" ")+">"}function dt(e,t,n){for(let s=0,o=n.length;s<o;s++){let a=n.charCodeAt(s);if(a<128){e.setUint8(t++,a>>>0&127|0);continue}if(a<2048){e.setUint8(t++,a>>>6&31|192),e.setUint8(t++,a>>>0&63|128);continue}if(a<65536){e.setUint8(t++,a>>>12&15|224),e.setUint8(t++,a>>>6&63|128),e.setUint8(t++,a>>>0&63|128);continue}if(a<1114112){e.setUint8(t++,a>>>18&7|240),e.setUint8(t++,a>>>12&63|128),e.setUint8(t++,a>>>6&63|128),e.setUint8(t++,a>>>0&63|128);continue}throw new Error("bad codepoint "+a)}}function js(e,t,n){let s="";for(let o=t,a=t+n;o<a;o++){let u=e.getUint8(o);if((u&128)===0){s+=String.fromCharCode(u);continue}if((u&224)===192){s+=String.fromCharCode((u&15)<<6|e.getUint8(++o)&63);continue}if((u&240)===224){s+=String.fromCharCode((u&15)<<12|(e.getUint8(++o)&63)<<6|(e.getUint8(++o)&63)<<0);continue}if((u&248)===240){s+=String.fromCharCode((u&7)<<18|(e.getUint8(++o)&63)<<12|(e.getUint8(++o)&63)<<6|(e.getUint8(++o)&63)<<0);continue}throw new Error("Invalid byte "+u.toString(16))}return s}function Nn(e){let t=0;for(let n=0,s=e.length;n<s;n++){let o=e.charCodeAt(n);if(o<128){t+=1;continue}if(o<2048){t+=2;continue}if(o<65536){t+=3;continue}if(o<1114112){t+=4;continue}throw new Error("bad codepoint "+o)}return t}function fc(e,t){let n=pt(e,t);if(n===0)return;let s=new ArrayBuffer(n),o=new DataView(s);return ft(e,o,0,t),s}var Ln=65536*65536,Ws=1/Ln;function pc(e,t){return t=t||0,e.getInt32(t)*Ln+e.getUint32(t+4)}function gc(e,t){return t=t||0,e.getUint32(t)*Ln+e.getUint32(t+4)}function mc(e,t,n){n<9223372036854776e3?(e.setInt32(t,Math.floor(n*Ws)),e.setInt32(t+4,n&-1)):(e.setUint32(t,2147483647),e.setUint32(t+4,2147483647))}function yc(e,t,n){n<18446744073709552e3?(e.setUint32(t,Math.floor(n*Ws)),e.setInt32(t+4,n&-1)):(e.setUint32(t,4294967295),e.setUint32(t+4,4294967295))}var Ec=class{constructor(e,t){this.map=n=>{let s={};for(let o=0;o<n;o++){let a=this.parse();s[a]=this.parse()}return s},this.bin=n=>{let s=new ArrayBuffer(n);return new Uint8Array(s).set(new Uint8Array(this.view.buffer,this.offset,n),0),this.offset+=n,s},this.buf=this.bin,this.str=n=>{let s=js(this.view,this.offset,n);return this.offset+=n,s},this.array=n=>{let s=new Array(n);for(let o=0;o<n;o++)s[o]=this.parse();return s},this.ext=n=>(this.offset+=n,{type:this.view.getInt8(this.offset),data:this.buf(n)}),this.parse=()=>{let n=this.view.getUint8(this.offset),s,o;if((n&128)===0)return this.offset++,n;if((n&240)===128)return o=n&15,this.offset++,this.map(o);if((n&240)===144)return o=n&15,this.offset++,this.array(o);if((n&224)===160)return o=n&31,this.offset++,this.str(o);if((n&224)===224)return s=this.view.getInt8(this.offset),this.offset++,s;switch(n){case 192:return this.offset++,null;case 193:this.offset++;return;case 194:return this.offset++,!1;case 195:return this.offset++,!0;case 196:return o=this.view.getUint8(this.offset+1),this.offset+=2,this.bin(o);case 197:return o=this.view.getUint16(this.offset+1),this.offset+=3,this.bin(o);case 198:return o=this.view.getUint32(this.offset+1),this.offset+=5,this.bin(o);case 199:return o=this.view.getUint8(this.offset+1),this.offset+=2,this.ext(o);case 200:return o=this.view.getUint16(this.offset+1),this.offset+=3,this.ext(o);case 201:return o=this.view.getUint32(this.offset+1),this.offset+=5,this.ext(o);case 202:return s=this.view.getFloat32(this.offset+1),this.offset+=5,s;case 203:return s=this.view.getFloat64(this.offset+1),this.offset+=9,s;case 204:return s=this.view.getUint8(this.offset+1),this.offset+=2,s;case 205:return s=this.view.getUint16(this.offset+1),this.offset+=3,s;case 206:return s=this.view.getUint32(this.offset+1),this.offset+=5,s;case 207:return s=gc(this.view,this.offset+1),this.offset+=9,s;case 208:return s=this.view.getInt8(this.offset+1),this.offset+=2,s;case 209:return s=this.view.getInt16(this.offset+1),this.offset+=3,s;case 210:return s=this.view.getInt32(this.offset+1),this.offset+=5,s;case 211:return s=pc(this.view,this.offset+1),this.offset+=9,s;case 212:return o=1,this.offset++,this.ext(o);case 213:return o=2,this.offset++,this.ext(o);case 214:return o=4,this.offset++,this.ext(o);case 215:return o=8,this.offset++,this.ext(o);case 216:return o=16,this.offset++,this.ext(o);case 217:return o=this.view.getUint8(this.offset+1),this.offset+=2,this.str(o);case 218:return o=this.view.getUint16(this.offset+1),this.offset+=3,this.str(o);case 219:return o=this.view.getUint32(this.offset+1),this.offset+=5,this.str(o);case 220:return o=this.view.getUint16(this.offset+1),this.offset+=3,this.array(o);case 221:return o=this.view.getUint32(this.offset+1),this.offset+=5,this.array(o);case 222:return o=this.view.getUint16(this.offset+1),this.offset+=3,this.map(o);case 223:return o=this.view.getUint32(this.offset+1),this.offset+=5,this.map(o)}throw new Error("Unknown type 0x"+n.toString(16))},this.offset=t||0,this.view=e}};function Cc(e){let t=new DataView(e),n=new Ec(t),s=n.parse();if(n.offset!==e.byteLength)throw new Error(e.byteLength-n.offset+" trailing bytes");return s}function Ks(e,t){return Object.keys(e).filter(function(n){let s=e[n],o=typeof s;return(!t||s!=null)&&(o!=="function"||!!s.toJSON)})}function ft(e,t,n,s){let o=typeof e;if(typeof e=="string"){let a=Nn(e);if(a<32)return t.setUint8(n,a|160),dt(t,n+1,e),1+a;if(a<256)return t.setUint8(n,217),t.setUint8(n+1,a),dt(t,n+2,e),2+a;if(a<65536)return t.setUint8(n,218),t.setUint16(n+1,a),dt(t,n+3,e),3+a;if(a<4294967296)return t.setUint8(n,219),t.setUint32(n+1,a),dt(t,n+5,e),5+a}if(ArrayBuffer.isView&&ArrayBuffer.isView(e)&&(e=e.buffer),e instanceof ArrayBuffer){let a=e.byteLength;if(a<256)return t.setUint8(n,196),t.setUint8(n+1,a),new Uint8Array(t.buffer).set(new Uint8Array(e),n+2),2+a;if(a<65536)return t.setUint8(n,197),t.setUint16(n+1,a),new Uint8Array(t.buffer).set(new Uint8Array(e),n+3),3+a;if(a<4294967296)return t.setUint8(n,198),t.setUint32(n+1,a),new Uint8Array(t.buffer).set(new Uint8Array(e),n+5),5+a}if(typeof e=="number"){if(Math.floor(e)!==e)return t.setUint8(n,203),t.setFloat64(n+1,e),9;if(e>=0){if(e<128)return t.setUint8(n,e),1;if(e<256)return t.setUint8(n,204),t.setUint8(n+1,e),2;if(e<65536)return t.setUint8(n,205),t.setUint16(n+1,e),3;if(e<4294967296)return t.setUint8(n,206),t.setUint32(n+1,e),5;if(e<18446744073709552e3)return t.setUint8(n,207),yc(t,n+1,e),9;throw new Error("Number too big 0x"+e.toString(16))}if(e>=-32)return t.setInt8(n,e),1;if(e>=-128)return t.setUint8(n,208),t.setInt8(n+1,e),2;if(e>=-32768)return t.setUint8(n,209),t.setInt16(n+1,e),3;if(e>=-2147483648)return t.setUint8(n,210),t.setInt32(n+1,e),5;if(e>=-9223372036854776e3)return t.setUint8(n,211),mc(t,n+1,e),9;throw new Error("Number too small -0x"+(-e).toString(16).substr(1))}if(o==="undefined")return s?0:(t.setUint8(n,212),t.setUint8(n+1,0),t.setUint8(n+2,0),3);if(e===null)return s?0:(t.setUint8(n,192),1);if(o==="boolean")return t.setUint8(n,e?195:194),1;if(typeof e.toJSON=="function")return ft(e.toJSON(),t,n,s);if(o==="object"){let a,u=0,f,E=Array.isArray(e);if(E?a=e.length:(f=Ks(e,s),a=f.length),a<16?(t.setUint8(n,a|(E?144:128)),u=1):a<65536?(t.setUint8(n,E?220:222),t.setUint16(n+1,a),u=3):a<4294967296&&(t.setUint8(n,E?221:223),t.setUint32(n+1,a),u=5),E)for(let g=0;g<a;g++)u+=ft(e[g],t,n+u,s);else if(f)for(let g=0;g<a;g++){let A=f[g];u+=ft(A,t,n+u),u+=ft(e[A],t,n+u,s)}return u}if(o==="function")return 0;throw new Error("Unknown type "+o)}function pt(e,t){let n=typeof e;if(n==="string"){let s=Nn(e);if(s<32)return 1+s;if(s<256)return 2+s;if(s<65536)return 3+s;if(s<4294967296)return 5+s}if(ArrayBuffer.isView&&ArrayBuffer.isView(e)&&(e=e.buffer),e instanceof ArrayBuffer){let s=e.byteLength;if(s<256)return 2+s;if(s<65536)return 3+s;if(s<4294967296)return 5+s}if(typeof e=="number"){if(Math.floor(e)!==e)return 9;if(e>=0){if(e<128)return 1;if(e<256)return 2;if(e<65536)return 3;if(e<4294967296)return 5;if(e<18446744073709552e3)return 9;throw new Error("Number too big 0x"+e.toString(16))}if(e>=-32)return 1;if(e>=-128)return 2;if(e>=-32768)return 3;if(e>=-2147483648)return 5;if(e>=-9223372036854776e3)return 9;throw new Error("Number too small -0x"+e.toString(16).substr(1))}if(n==="boolean")return 1;if(e===null)return t?0:1;if(e===void 0)return t?0:3;if(typeof e.toJSON=="function")return pt(e.toJSON(),t);if(n==="object"){let s,o=0;if(Array.isArray(e)){s=e.length;for(let a=0;a<s;a++)o+=pt(e[a],t)}else{let a=Ks(e,t);s=a.length;for(let u=0;u<s;u++){let f=a[u];o+=pt(f)+pt(e[f],t)}}if(s<16)return 1+o;if(s<65536)return 3+o;if(s<4294967296)return 5+o;throw new Error("Array or object too long 0x"+s.toString(16))}if(n==="function")return 0;throw new Error("Unknown type "+n)}var xn={encode:fc,decode:Cc,inspect:dc,utf8Write:dt,utf8Read:js,utf8ByteCount:Nn};function Sc(e,t){return!!t.get("x-ably-errorcode")}function Rc(e,t){if(Sc(e,t))return e.error&&C.fromValues(e.error)}function Ac(e){let t={};return e.forEach((n,s)=>{t[s]=n}),t}async function wc(e,t,n,s,o,a){let u=new Headers(s||{}),f=e?e.toUpperCase():ce(a)?"GET":"POST",E=new AbortController,g,A=new Promise(R=>{g=setTimeout(()=>{E.abort(),R({error:new J("Request timed out",null,408)})},t?t.options.timeouts.httpRequestTimeout:L.TIMEOUTS.httpRequestTimeout)}),w={method:f,headers:u,body:a,signal:E.signal};b.Config.isWebworker||(w.credentials=u.has("authorization")?"include":"same-origin");let v=(async()=>{try{let R=new URLSearchParams(o||{});R.set("rnd",Mt());let T=n+"?"+R,_=await rn().fetch(T,w);if(clearTimeout(g),_.status==204)return{error:null,statusCode:_.status};let N=_.headers.get("Content-Type"),D;N&&N.indexOf("application/x-msgpack")>-1?D=await _.arrayBuffer():N&&N.indexOf("application/json")>-1?D=await _.json():D=await _.text();let F=!!N&&N.indexOf("application/x-msgpack")===-1,q=Ac(_.headers);return _.ok?{error:null,body:D,headers:q,unpacked:F,statusCode:_.status}:{error:Rc(D,_.headers)||new J("Error response received from server: "+_.status+" body was: "+b.Config.inspect(D),null,_.status),body:D,headers:q,unpacked:F,statusCode:_.status}}catch(R){return clearTimeout(g),{error:R}}})();return Promise.race([A,v])}var bc={XHRRequest:Hs,FetchRequest:wc},$s=Ga(Gs,Ls);b.Crypto=$s,b.BufferUtils=Ls,b.Http=Ds,b.Config=Gs,b.Transports=lc,b.WebStorage=Fs;for(let e of[Rn,On])e.Crypto=$s,e._MsgPack=xn;Ds.bundledRequestImplementations=bc,c.initLogHandlers(),b.Defaults=eo(uc),b.Config.agent&&(b.Defaults.agent+=" "+b.Config.agent);var vc={ErrorInfo:C,Rest:Rn,Realtime:On,msgpack:xn,makeProtocolMessageFromDeserialized:As};if(typeof i.exports=="object"&&typeof l=="object"){var Ic=(e,t,n,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Object.getOwnPropertyNames(t))!Object.prototype.hasOwnProperty.call(e,o)&&o!==n&&Object.defineProperty(e,o,{get:()=>t[o],enumerable:!(s=Object.getOwnPropertyDescriptor(t,o))||s.enumerable});return e};i.exports=Ic(i.exports,l)}return i.exports})});M();M();var Nr=Js(mr());M();M();M();var yr="https://api.anam.ai",Er="/v1",zt={client:"js-sdk",version:"0.0.0-automated",supportsPubSubSignalling:!0};var $n="https://api.anam.ai",Jt="/v1";var Cr=$n,Sr=Jt,Rr=(l,i=Jt)=>{Cr=l,Sr=i},be={sessionId:null,organizationId:null,attemptCorrelationId:null},Me=l=>{be={...be,...l}},ue=async(l,i,r)=>{try{let h={...zt,...r};be.sessionId&&(h.sessionId=be.sessionId),be.organizationId&&(h.organizationId=be.organizationId),be.attemptCorrelationId&&(h.attemptCorrelationId=be.attemptCorrelationId),await fetch(`${Cr}${Sr}/metrics/client`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:l,value:i,tags:h})})}catch(h){console.error("Failed to send error metric:",h)}},Ar=(l,i="console")=>{let r={};l.forEach(y=>{r[y.type]||(r[y.type]=[]),r[y.type].push(y)});let h={issues:[]},d=r["inbound-rtp"]?.filter(y=>y.kind==="video")||[];d.length>0&&(h.personaVideoStream=[],d.forEach(y=>{let k={framesReceived:y.framesReceived??"unknown",framesDropped:y.framesDropped??"unknown",framesPerSecond:y.framesPerSecond??"unknown",packetsReceived:y.packetsReceived??"unknown",packetsLost:y.packetsLost??"unknown",resolution:y.frameWidth&&y.frameHeight?`${y.frameWidth}x${y.frameHeight}`:void 0,jitter:y.jitter!==void 0?y.jitter:void 0};h.personaVideoStream.push(k)}));let p=r["inbound-rtp"]?.filter(y=>y.kind==="audio")||[];p.length>0&&(h.personaAudioStream=[],p.forEach(y=>{let k={packetsReceived:y.packetsReceived??"unknown",packetsLost:y.packetsLost??"unknown",audioLevel:y.audioLevel??"unknown",jitter:y.jitter!==void 0?y.jitter:void 0,totalAudioEnergy:y.totalAudioEnergy!==void 0?y.totalAudioEnergy:void 0};h.personaAudioStream.push(k)}));let m=r["outbound-rtp"]?.filter(y=>y.kind==="audio")||[];m.length>0&&(h.userAudioInput=[],m.forEach(y=>{let k={packetsSent:y.packetsSent??"unknown",retransmittedPackets:y.retransmittedPacketsSent??void 0,avgPacketSendDelay:y.totalPacketSendDelay!==void 0?y.totalPacketSendDelay/(y.packetsSent||1)*1e3:void 0};h.userAudioInput.push(k)})),r.codec&&(h.codecs=[],r.codec.forEach(y=>{let k={status:y.payloadType?"Active":"Available",mimeType:y.mimeType||"Unknown",payloadType:y.payloadType||"N/A",clockRate:y.clockRate||void 0,channels:y.channels||void 0};h.codecs.push(k)})),r.transport&&(h.transportLayer=[],r.transport.forEach(y=>{let k={dtlsState:y.dtlsState||"unknown",iceState:y.iceState||"unknown",bytesSent:y.bytesSent||void 0,bytesReceived:y.bytesReceived||void 0};h.transportLayer.push(k)}));let I=[];if(d.forEach(y=>{typeof y.framesDropped=="number"&&y.framesDropped>0&&I.push(`Video: ${y.framesDropped} frames dropped`),typeof y.packetsLost=="number"&&y.packetsLost>0&&I.push(`Video: ${y.packetsLost} packets lost`),typeof y.framesPerSecond=="number"&&y.framesPerSecond<23&&I.push(`Video: Low frame rate (${y.framesPerSecond} fps)`)}),p.forEach(y=>{typeof y.packetsLost=="number"&&y.packetsLost>0&&I.push(`Audio: ${y.packetsLost} packets lost`),typeof y.jitter=="number"&&y.jitter>.1&&I.push(`Audio: High jitter (${(y.jitter*1e3).toFixed(1)}ms)`)}),h.issues=I,i==="json")return h;console.group("\u{1F4CA} WebRTC Session Statistics Report"),h.personaVideoStream&&h.personaVideoStream.length>0&&(console.group("\u{1F4F9} Persona Video Stream (Inbound)"),h.personaVideoStream.forEach(y=>{console.log(`Frames Received: ${y.framesReceived}`),console.log(`Frames Dropped: ${y.framesDropped}`),console.log(`Frames Per Second: ${y.framesPerSecond}`),console.log(`Packets Received: ${typeof y.packetsReceived=="number"?y.packetsReceived.toLocaleString():y.packetsReceived}`),console.log(`Packets Lost: ${y.packetsLost}`),y.resolution&&console.log(`Resolution: ${y.resolution}`),y.jitter!==void 0&&console.log(`Jitter: ${y.jitter.toFixed(5)}ms`)}),console.groupEnd()),h.personaAudioStream&&h.personaAudioStream.length>0&&(console.group("\u{1F50A} Persona Audio Stream (Inbound)"),h.personaAudioStream.forEach(y=>{console.log(`Packets Received: ${typeof y.packetsReceived=="number"?y.packetsReceived.toLocaleString():y.packetsReceived}`),console.log(`Packets Lost: ${y.packetsLost}`),console.log(`Audio Level: ${y.audioLevel}`),y.jitter!==void 0&&console.log(`Jitter: ${y.jitter.toFixed(5)}ms`),y.totalAudioEnergy!==void 0&&console.log(`Total Audio Energy: ${y.totalAudioEnergy.toFixed(6)}`)}),console.groupEnd()),h.userAudioInput&&h.userAudioInput.length>0&&(console.group("\u{1F3A4} User Audio Input (Outbound)"),h.userAudioInput.forEach(y=>{console.log(`Packets Sent: ${typeof y.packetsSent=="number"?y.packetsSent.toLocaleString():y.packetsSent}`),y.retransmittedPackets&&console.log(`Retransmitted Packets: ${y.retransmittedPackets}`),y.avgPacketSendDelay!==void 0&&console.log(`Avg Packet Send Delay: ${y.avgPacketSendDelay.toFixed(5)}ms`)}),console.groupEnd()),h.codecs&&h.codecs.length>0&&(console.group("\u{1F527} Codecs Used"),h.codecs.forEach(y=>{console.log(`${y.status} ${y.mimeType} - Payload Type: ${y.payloadType}`),y.clockRate&&console.log(` Clock Rate: ${y.clockRate}Hz`),y.channels&&console.log(` Channels: ${y.channels}`)}),console.groupEnd()),h.transportLayer&&h.transportLayer.length>0&&(console.group("\u{1F69A} Transport Layer"),h.transportLayer.forEach(y=>{console.log(`DTLS State: ${y.dtlsState}`),console.log(`ICE State: ${y.iceState}`),(y.bytesReceived||y.bytesSent)&&console.log(`Data Transfer (bytes) - Sent: ${(y.bytesSent||0).toLocaleString()}, Received: ${(y.bytesReceived||0).toLocaleString()}`)}),console.groupEnd()),h.issues.length>0?(console.group("\u26A0\uFE0F Potential Issues Detected"),h.issues.forEach(y=>console.warn(y)),console.groupEnd()):console.log("\u2705 No significant issues detected"),console.groupEnd()};var K=class l extends Error{constructor(i,r,h=500,d){super(i),this.name="ClientError",this.code=r,this.statusCode=h,this.details=d,Object.setPrototypeOf(this,l.prototype),ue("client_error",r,{details:d,statusCode:h})}};M();function Jn(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():Date.now().toString(36)+Math.random().toString(36).substr(2,9)}M();M();var kr=Js(_r());M();M();M();var Xe=(k=>(k.OFFER="offer",k.ANSWER="answer",k.ICE_CANDIDATE="icecandidate",k.END_SESSION="endsession",k.HEARTBEAT="heartbeat",k.WARNING="warning",k.TALK_STREAM_INTERRUPTED="talkinputstreaminterrupted",k.TALK_STREAM_INPUT="talkstream",k.SESSION_READY="sessionready",k))(Xe||{});function Mr(l){return l.payloadFormat==="json-string"?{...l,payload:JSON.parse(l.payload),payloadFormat:"unencoded"}:l}M();M();var Yt=(r=>(r.USER="user",r.PERSONA="persona",r))(Yt||{});M();M();var ve=(O=>(O.MESSAGE_HISTORY_UPDATED="MESSAGE_HISTORY_UPDATED",O.MESSAGE_STREAM_EVENT_RECEIVED="MESSAGE_STREAM_EVENT_RECEIVED",O.CONNECTION_ESTABLISHED="CONNECTION_ESTABLISHED",O.CONNECTION_CLOSED="CONNECTION_CLOSED",O.INPUT_AUDIO_STREAM_STARTED="INPUT_AUDIO_STREAM_STARTED",O.VIDEO_STREAM_STARTED="VIDEO_STREAM_STARTED",O.VIDEO_PLAY_STARTED="VIDEO_PLAY_STARTED",O.AUDIO_STREAM_STARTED="AUDIO_STREAM_STARTED",O.TALK_STREAM_INTERRUPTED="TALK_STREAM_INTERRUPTED",O.SESSION_READY="SESSION_READY",O.SERVER_WARNING="SERVER_WARNING",O))(ve||{});M();var ke=(h=>(h.WEB_SOCKET_OPEN="WEB_SOCKET_OPEN",h.SIGNAL_MESSAGE_RECEIVED="SIGNAL_MESSAGE_RECEIVED",h.WEBRTC_CHAT_MESSAGE_RECEIVED="WEBRTC_CHAT_MESSAGE_RECEIVED",h))(ke||{});M();var Ze=(p=>(p.NORMAL="CONNECTION_CLOSED_CODE_NORMAL",p.MICROPHONE_PERMISSION_DENIED="CONNECTION_CLOSED_CODE_MICROPHONE_PERMISSION_DENIED",p.SIGNALLING_CLIENT_CONNECTION_FAILURE="CONNECTION_CLOSED_CODE_SIGNALLING_CLIENT_CONNECTION_FAILURE",p.WEBRTC_FAILURE="CONNECTION_CLOSED_CODE_WEBRTC_FAILURE",p.SERVER_CLOSED_CONNECTION="CONNECTION_CLOSED_CODE_SERVER_CLOSED_CONNECTION",p))(Ze||{});var Rt=class{constructor(i,r,h,d){this.realtime=null;this.channel=null;this.stopSignal=!1;if(this.publicEventEmitter=h,this.internalEventEmitter=d,!i)throw new Error("Signalling Client: sessionId is required");this.sessionId=i;let{ablyToken:p,channelName:m}=r;if(!p)throw new Error("Signalling Client: ablyToken is required");if(!m)throw new Error("Signalling Client: channelName is required");this.ablyToken=p,this.channelName=m}stop(){this.stopSignal=!0,this.closeConnection()}connect(){if(this.realtime){console.warn("SignallingClient - connect: Already connected");return}this.realtime=new kr.Realtime({token:this.ablyToken,echoMessages:!1,autoConnect:typeof window<"u",disconnectedRetryTimeout:1e3,suspendedRetryTimeout:2e3,transportParams:{heartbeatInterval:5e3}}),this.channel=this.realtime.channels.get(this.channelName,{params:{rewind:"100"}}),this.channel.presence.enter(),this.realtime.connection.on("connected",()=>{this.onConnected()}),this.realtime.connection.on("failed",()=>{this.onConnectionFailed()}),this.channel.subscribe(i=>{this.onMessage(i)}),this.realtime.connect()}async sendOffer(i){if(!this.channel)throw new Error("SignallingClient - sendOffer: Not connected. Call connect() first.");let r={connectionDescription:i,userUid:this.sessionId},h={actionType:"offer",sessionId:this.sessionId,payload:r};this.sendSignalMessage(h)}async sendIceCandidate(i){if(!this.channel)throw new Error("SignallingClient - sendIceCandidate: Not connected. Call connect() first.");let r={actionType:"icecandidate",sessionId:this.sessionId,payload:i.toJSON()};this.sendSignalMessage(r)}sendSignalMessage(i){if(!this.channel)throw new Error("SignallingClient - sendSignalMessage: Cannot send message, not connected. Call connect() first.");try{this.channel.publish("signal",i)}catch(r){throw console.error("SignallingClient - sendSignalMessage: error sending message",r),r}}async sendTalkMessage(i){if(!this.channel)throw new Error("SignallingClient - sendTalkMessage: Not connected. Call connect() first.");let r={actionType:"talkstream",sessionId:this.sessionId,payload:i};this.sendSignalMessage(r)}closeConnection(){this.realtime&&(this.realtime.close(),this.realtime=null,this.channel=null)}onConnected(){try{this.internalEventEmitter.emit("WEB_SOCKET_OPEN")}catch(i){console.error("SignallingClient - onConnected: error",i),this.publicEventEmitter.emit("CONNECTION_CLOSED","CONNECTION_CLOSED_CODE_SIGNALLING_CLIENT_CONNECTION_FAILURE")}}onConnectionFailed(){this.stopSignal||this.publicEventEmitter.emit("CONNECTION_CLOSED","CONNECTION_CLOSED_CODE_SIGNALLING_CLIENT_CONNECTION_FAILURE")}onMessage(i){let r=i.data;r=Mr(r),this.internalEventEmitter.emit("SIGNAL_MESSAGE_RECEIVED",r)}};M();M();function Pr(l){return"brainType"in l||"llmId"in l}var At=class{constructor(i,r,h){if(!i&&!r)throw new Error("Either sessionToken or apiKey must be provided");this.sessionToken=i||null,this.apiKey=r||null,this.baseUrl=h?.baseUrl||yr,this.apiVersion=h?.apiVersion||Er}async startSession(i,r){if(!this.sessionToken){if(!i)throw new K("Persona configuration must be provided when using apiKey","CLIENT_ERROR_CODE_VALIDATION_ERROR",400);this.sessionToken=await this.unsafe_getSessionToken(i)}i&&"brainType"in i&&console.warn("Warning: brainType is deprecated and will be removed in a future version. Please use llmId instead.");try{let h=await fetch(`${this.getApiUrl()}/engine/session`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.sessionToken}`},body:JSON.stringify({personaConfig:i,sessionOptions:r,clientMetadata:zt})}),d=await h.json();switch(h.status){case 200:case 201:return d;case 400:throw new K("Invalid request to start session","CLIENT_ERROR_CODE_VALIDATION_ERROR",400,{cause:d.message});case 401:throw new K("Authentication failed when starting session","CLIENT_ERROR_CODE_AUTHENTICATION_ERROR",401,{cause:d.message});case 402:throw new K("Please sign up for a plan to start a session","CLIENT_ERROR_CODE_NO_PLAN_FOUND",402,{cause:d.message});case 403:throw new K("Authentication failed when starting session","CLIENT_ERROR_CODE_AUTHENTICATION_ERROR",403,{cause:d.message});case 429:throw new K("Usage limit reached, please upgrade your plan","CLIENT_ERROR_CODE_USAGE_LIMIT_REACHED",429,{cause:d.message});case 503:throw new K("There are no available personas, please try again later","CLIENT_ERROR_CODE_SERVICE_BUSY",503,{cause:d.message});default:throw new K("Unknown error when starting session","CLIENT_ERROR_CODE_SERVER_ERROR",500,{cause:d.message})}}catch(h){throw h instanceof K?h:new K("Failed to start session","CLIENT_ERROR_CODE_SERVER_ERROR",500,{cause:h instanceof Error?h.message:String(h)})}}async unsafe_getSessionToken(i){if(console.warn("Using unsecure method. This method should not be used in production."),!this.apiKey)throw new Error("No apiKey provided");i&&"brainType"in i&&console.warn("Warning: brainType is deprecated and will be removed in a future version. Please use llmId instead.");let r={clientLabel:"js-sdk-api-key"};Pr(i)&&(r={...r,personaConfig:i});try{return(await(await fetch(`${this.getApiUrl()}/auth/session-token`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify(r)})).json()).sessionToken}catch{throw new Error("Failed to get session token")}}getApiUrl(){return`${this.baseUrl}${this.apiVersion}`}};M();var wt=class{constructor(i,r){this.baseUrl=i,this.sessionId=r}async sendTalkCommand(i){try{let r=await fetch(`${this.baseUrl}/talk?session_id=${this.sessionId}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:i})});if(!r.ok)throw new Error(`Failed to send talk command: ${r.status} ${r.statusText}`)}catch(r){throw console.error(r),new Error("EngineApiRestClient - sendTalkCommand: Failed to send talk command")}}};M();var bt=class{constructor(){this.listeners={}}addListener(i,r){this.listeners[i]||(this.listeners[i]=new Set),this.listeners[i].add(r)}removeListener(i,r){this.listeners[i]&&this.listeners[i].delete(r)}emit(i,...r){this.listeners[i]&&this.listeners[i].forEach(h=>{h(...r)})}};M();var vt=class{constructor(i,r){this.messages=[];this.publicEventEmitter=i,this.internalEventEmitter=r,this.internalEventEmitter.addListener("WEBRTC_CHAT_MESSAGE_RECEIVED",this.processWebRtcTextMessageEvent.bind(this))}webRtcTextMessageEventToMessageStreamEvent(i){return{id:`${i.role}::${i.message_id}`,content:i.content,role:i.role,endOfSpeech:i.end_of_speech,interrupted:i.interrupted}}processUserMessage(i){let r={id:i.id,content:i.content,role:i.role};this.messages.push(r)}processPersonaMessage(i){let r={id:i.id,content:i.content,role:i.role,interrupted:i.interrupted},h=this.messages.findIndex(d=>d.id===r.id);if(h!==-1){let d=this.messages[h];this.messages[h]={...d,content:d.content+r.content,interrupted:d.interrupted||r.interrupted}}else this.messages.push(r)}processWebRtcTextMessageEvent(i){let r=this.webRtcTextMessageEventToMessageStreamEvent(i);switch(this.publicEventEmitter.emit("MESSAGE_STREAM_EVENT_RECEIVED",r),r.role){case"user":this.processUserMessage(r);break;case"persona":this.processPersonaMessage(r);break}r.endOfSpeech&&this.publicEventEmitter.emit("MESSAGE_HISTORY_UPDATED",this.messages)}};M();var It=class{constructor(){this.listeners={}}addListener(i,r){this.listeners[i]||(this.listeners[i]=new Set),this.listeners[i].add(r)}removeListener(i,r){this.listeners[i]&&this.listeners[i].delete(r)}emit(i,...r){if(i==="CONNECTION_ESTABLISHED"&&ue("client_connection_established","1"),i==="CONNECTION_CLOSED"){let[h,d]=r;ue("client_connection_closed",h,d?{details:d}:void 0)}this.listeners[i]&&this.listeners[i].forEach(h=>{h(...r)})}};M();M();M();var Xt=class{constructor(i,r,h){this.state=0;this.correlationId=i,this.internalEventEmitter=r,this.signallingClient=h,this.internalEventEmitter.addListener("SIGNAL_MESSAGE_RECEIVED",this.onSignalMessage.bind(this))}onDeactivate(){this.internalEventEmitter.removeListener("SIGNAL_MESSAGE_RECEIVED",this.onSignalMessage.bind(this))}async onSignalMessage(i){i.actionType==="talkinputstreaminterrupted"&&i.payload.correlationId===this.correlationId&&(this.state=2,this.onDeactivate())}async endMessage(){if(this.state===3){console.warn("Talk stream is already ended via end of speech. No need to call endMessage.");return}if(this.state!==1){console.warn("Talk stream is not active state: "+this.state);return}let i={content:"",startOfSpeech:!1,endOfSpeech:!0,correlationId:this.correlationId};await this.signallingClient.sendTalkMessage(i),this.state=3,this.onDeactivate()}async streamMessageChunk(i,r){if(this.state!==1&&this.state!==0)throw new Error("Talk stream is not in an active state: "+this.state);let h={content:i,startOfSpeech:this.state===0,endOfSpeech:r,correlationId:this.correlationId};this.state=r?3:1,this.state===3&&this.onDeactivate(),await this.signallingClient.sendTalkMessage(h)}getCorrelationId(){return this.correlationId}isActive(){return this.state===1||this.state===0}getState(){return this.state}};var fl=15e3,Ot=class{constructor(i,r,h,d){this.peerConnection=null;this.connectionReceivedAnswer=!1;this.remoteIceCandidateBuffer=[];this.inputAudioStream=null;this.dataChannel=null;this.videoElement=null;this.videoStream=null;this.audioStream=null;this.inputAudioState={isMuted:!1};this.successMetricPoller=null;this.successMetricFired=!1;this.showPeerConnectionStatsReport=!1;this.peerConnectionStatsReportOutputFormat="console";this.publicEventEmitter=h,this.internalEventEmitter=d;let{inputAudio:p}=r;this.inputAudioState=p.inputAudioState,r.inputAudio.userProvidedMediaStream&&(this.inputAudioStream=r.inputAudio.userProvidedMediaStream),this.disableInputAudio=r.inputAudio.disableInputAudio===!0,this.internalEventEmitter.addListener("WEB_SOCKET_OPEN",this.onSignallingClientConnected.bind(this)),this.internalEventEmitter.addListener("SIGNAL_MESSAGE_RECEIVED",this.onSignalMessage.bind(this)),this.iceServers=r.iceServers,this.signallingClient=new Rt(i,r.signalling,this.publicEventEmitter,this.internalEventEmitter),this.engineApiRestClient=new wt(r.engine.baseUrl,i),this.audioDeviceId=r.inputAudio.audioDeviceId,this.showPeerConnectionStatsReport=r.metrics?.showPeerConnectionStatsReport??!1,this.peerConnectionStatsReportOutputFormat=r.metrics?.peerConnectionStatsReportOutputFormat??"console"}onInputAudioStateChange(i,r){i.isMuted!==r.isMuted&&(r.isMuted?this.muteAllAudioTracks():this.unmuteAllAudioTracks())}muteAllAudioTracks(){this.inputAudioStream?.getAudioTracks().forEach(i=>{i.enabled=!1})}unmuteAllAudioTracks(){this.inputAudioStream?.getAudioTracks().forEach(i=>{i.enabled=!0})}startSuccessMetricPolling(){if(this.successMetricPoller||this.successMetricFired)return;let i=setTimeout(()=>{this.successMetricPoller&&(console.warn("No video frames received, there is a problem with the connection."),clearInterval(this.successMetricPoller),this.successMetricPoller=null)},fl);this.successMetricPoller=setInterval(async()=>{if(!this.peerConnection||this.successMetricFired){this.successMetricPoller&&clearInterval(this.successMetricPoller),clearTimeout(i);return}try{let r=await this.peerConnection.getStats(),h=!1,d=null;r.forEach(p=>{p.type==="inbound-rtp"&&p.kind==="video"&&(p.framesDecoded!==void 0&&p.framesDecoded>0?(h=!0,d="framesDecoded"):p.framesReceived!==void 0&&p.framesReceived>0?(h=!0,d="framesReceived"):p.bytesReceived>0&&p.packetsReceived>0&&p.bytesReceived>1e5&&(h=!0,d="bytesReceived"))}),h&&!this.successMetricFired&&(this.successMetricFired=!0,ue("client_session_success","1",d?{detectionMethod:d}:void 0),this.successMetricPoller&&clearInterval(this.successMetricPoller),clearTimeout(i),this.successMetricPoller=null)}catch{}},500)}muteInputAudio(){let i=this.inputAudioState,r={...this.inputAudioState,isMuted:!0};return this.inputAudioState=r,this.onInputAudioStateChange(i,r),this.inputAudioState}unmuteInputAudio(){let i=this.inputAudioState,r={...this.inputAudioState,isMuted:!1};return this.inputAudioState=r,this.onInputAudioStateChange(i,r),this.inputAudioState}getInputAudioState(){return this.inputAudioState}getPeerConnection(){return this.peerConnection}getInputAudioStream(){return this.inputAudioStream}getVideoStream(){return this.videoStream}getAudioStream(){return this.audioStream}sendDataMessage(i){this.dataChannel&&this.dataChannel.readyState==="open"&&this.dataChannel.send(i)}setMediaStreamTargetById(i){if(i){let r=document.getElementById(i);if(!r)throw new Error(`StreamingClient: video element with id ${i} not found`);this.videoElement=r}}startConnection(){try{if(this.peerConnection){console.error("StreamingClient - startConnection: peer connection already exists");return}this.signallingClient.connect()}catch(i){console.log("StreamingClient - startConnection: error",i),this.handleWebrtcFailure(i)}}async stopConnection(){await this.shutdown()}async sendTalkCommand(i){if(!this.peerConnection)throw new Error("StreamingClient - sendTalkCommand: peer connection is null");await this.engineApiRestClient.sendTalkCommand(i)}startTalkMessageStream(i){return i||(i=Math.random().toString(36).substring(2,15)),new Xt(i,this.internalEventEmitter,this.signallingClient)}async initPeerConnection(){this.peerConnection=new RTCPeerConnection({iceServers:this.iceServers}),this.peerConnection.onicecandidate=this.onIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onIceConnectionStateChange.bind(this),this.peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this),this.peerConnection.addEventListener("track",this.onTrackEventHandler.bind(this)),await this.setupDataChannels(),this.peerConnection.addTransceiver("video",{direction:"recvonly"}),this.disableInputAudio?this.peerConnection.addTransceiver("audio",{direction:"recvonly"}):this.peerConnection.addTransceiver("audio",{direction:"sendrecv"})}async onSignalMessage(i){if(!this.peerConnection){console.error("StreamingClient - onSignalMessage: peerConnection is not initialized");return}switch(i.actionType){case"answer":let r=i.payload;await this.peerConnection.setRemoteDescription(r),this.connectionReceivedAnswer=!0,this.flushRemoteIceCandidateBuffer();break;case"icecandidate":let h=i.payload,d=new RTCIceCandidate(h);this.connectionReceivedAnswer?await this.peerConnection.addIceCandidate(d):this.remoteIceCandidateBuffer.push(d);break;case"endsession":let p=i.payload;console.log("StreamingClient - onSignalMessage: reason",p),this.publicEventEmitter.emit("CONNECTION_CLOSED","CONNECTION_CLOSED_CODE_SERVER_CLOSED_CONNECTION",p),this.shutdown();break;case"warning":let m=i.payload;console.warn("Warning received from server: "+m),this.publicEventEmitter.emit("SERVER_WARNING",m);break;case"talkinputstreaminterrupted":let I=i.payload;this.publicEventEmitter.emit("TALK_STREAM_INTERRUPTED",I.correlationId);break;case"sessionready":let y=i.sessionId;this.publicEventEmitter.emit("SESSION_READY",y);break;default:console.error("StreamingClient - onSignalMessage: unknown signal message action type. Is your anam-sdk version up to date?",i)}}async onSignallingClientConnected(){if(!this.peerConnection)try{await this.initPeerConnectionAndSendOffer()}catch(i){console.error("StreamingClient - onSignallingClientConnected: Error initializing peer connection",i),this.handleWebrtcFailure(i)}}flushRemoteIceCandidateBuffer(){this.remoteIceCandidateBuffer.forEach(i=>{this.peerConnection?.addIceCandidate(i)}),this.remoteIceCandidateBuffer=[]}onIceCandidate(i){i.candidate&&this.signallingClient.sendIceCandidate(i.candidate)}onIceConnectionStateChange(){(this.peerConnection?.iceConnectionState==="connected"||this.peerConnection?.iceConnectionState==="completed")&&this.publicEventEmitter.emit("CONNECTION_ESTABLISHED")}onConnectionStateChange(){this.peerConnection?.connectionState==="closed"&&(console.error("StreamingClient - onConnectionStateChange: Connection closed"),this.handleWebrtcFailure("The connection to our servers was lost. Please try again."))}handleWebrtcFailure(i){console.error({message:"StreamingClient - handleWebrtcFailure: ",err:i}),i.name==="NotAllowedError"&&i.message==="Permission denied"?this.publicEventEmitter.emit("CONNECTION_CLOSED","CONNECTION_CLOSED_CODE_MICROPHONE_PERMISSION_DENIED"):this.publicEventEmitter.emit("CONNECTION_CLOSED","CONNECTION_CLOSED_CODE_WEBRTC_FAILURE");try{this.stopConnection()}catch(r){console.error("StreamingClient - handleWebrtcFailure: error stopping connection",r)}}onTrackEventHandler(i){if(i.track.kind==="video"){if(this.startSuccessMetricPolling(),this.videoStream=i.streams[0],this.publicEventEmitter.emit("VIDEO_STREAM_STARTED",this.videoStream),this.videoElement){this.videoElement.srcObject=this.videoStream;let r=this.videoElement.requestVideoFrameCallback(()=>{this.videoElement?.cancelVideoFrameCallback(r),this.publicEventEmitter.emit("VIDEO_PLAY_STARTED"),this.successMetricFired||(this.successMetricFired=!0,ue("client_session_success","1",{detectionMethod:"videoElement"}))})}}else i.track.kind==="audio"&&(this.audioStream=i.streams[0],this.publicEventEmitter.emit("AUDIO_STREAM_STARTED",this.audioStream))}async setupDataChannels(){if(!this.peerConnection){console.error("StreamingClient - setupDataChannels: peer connection is not initialized");return}if(!this.disableInputAudio){if(this.inputAudioStream){if(!this.inputAudioStream.getAudioTracks().length)throw new Error("StreamingClient - setupDataChannels: user provided stream does not have audio tracks")}else{let h={echoCancellation:!0};this.audioDeviceId&&(h.deviceId={exact:this.audioDeviceId}),this.inputAudioStream=await navigator.mediaDevices.getUserMedia({audio:h})}this.inputAudioState.isMuted&&this.muteAllAudioTracks();let r=this.inputAudioStream.getAudioTracks()[0];this.peerConnection.addTrack(r,this.inputAudioStream),this.publicEventEmitter.emit("INPUT_AUDIO_STREAM_STARTED",this.inputAudioStream)}let i=this.peerConnection.createDataChannel("chat",{ordered:!0});i.onopen=()=>{this.dataChannel=i??null},i.onclose=()=>{},i.onmessage=r=>{let h=JSON.parse(r.data);this.internalEventEmitter.emit("WEBRTC_CHAT_MESSAGE_RECEIVED",h)}}async initPeerConnectionAndSendOffer(){if(await this.initPeerConnection(),!this.peerConnection){console.error("StreamingClient - initPeerConnectionAndSendOffer: peer connection is not initialized");return}try{let i=await this.peerConnection.createOffer();await this.peerConnection.setLocalDescription(i)}catch(i){console.error("StreamingClient - initPeerConnectionAndSendOffer: error creating offer",i)}if(!this.peerConnection.localDescription)throw new Error("StreamingClient - initPeerConnectionAndSendOffer: local description is null");await this.signallingClient.sendOffer(this.peerConnection.localDescription)}async shutdown(){if(this.showPeerConnectionStatsReport){let i=await this.peerConnection?.getStats();if(i){let r=Ar(i,this.peerConnectionStatsReportOutputFormat);r&&console.log(r,void 0,2)}}this.successMetricPoller&&(clearInterval(this.successMetricPoller),this.successMetricPoller=null),this.successMetricFired=!1;try{this.inputAudioStream&&this.inputAudioStream.getTracks().forEach(i=>{i.stop()}),this.inputAudioStream=null}catch(i){console.error("StreamingClient - shutdown: error stopping input audio stream",i)}try{this.signallingClient.stop()}catch(i){console.error("StreamingClient - shutdown: error stopping signallilng",i)}try{this.peerConnection&&this.peerConnection.connectionState!=="closed"&&(this.peerConnection.onconnectionstatechange=null,this.peerConnection.close(),this.peerConnection=null)}catch(i){console.error("StreamingClient - shutdown: error closing peer connection",i)}}};var et=class{constructor(i,r,h){this.inputAudioState={isMuted:!1};this.sessionId=null;this.organizationId=null;this.streamingClient=null;this._isStreaming=!1;let d=this.validateClientConfig(i,r,h);if(d)throw new K(d,"CLIENT_ERROR_CODE_CONFIGURATION_ERROR",400);this.personaConfig=r,this.clientOptions=h,(h?.api?.baseUrl||h?.api?.apiVersion)&&Rr(h.api.baseUrl||$n,h.api.apiVersion||Jt),this.publicEventEmitter=new It,this.internalEventEmitter=new bt,this.apiClient=new At(i,h?.apiKey,h?.api),this.messageHistoryClient=new vt(this.publicEventEmitter,this.internalEventEmitter)}decodeJwt(i){try{let r=i.split(".")[1],h=Nr.Buffer.from(r,"base64").toString("utf8");return JSON.parse(h)}catch{throw new Error("Invalid session token format")}}validateClientConfig(i,r,h){if(!i&&!h?.apiKey)return"Either sessionToken or apiKey must be provided";if(h?.apiKey&&i)return"Only one of sessionToken or apiKey should be used";if(i){let d=this.decodeJwt(i);this.organizationId=d.accountId,Me({organizationId:this.organizationId});let p=d.type?.toLowerCase();if(p==="legacy")return"Legacy session tokens are no longer supported. Please define your persona when creating your session token. See https://docs.anam.ai/resources/migrating-legacy for more information.";if((p==="ephemeral"||p==="stateful")&&r)return"This session token already contains a persona configuration. Please remove the personaConfig parameter."}else if(!r)return"Missing persona config. Persona configuration must be provided when using apiKey";if(h?.voiceDetection){if(h.disableInputAudio)return"Voice detection is disabled because input audio is disabled. Please set disableInputAudio to false to enable voice detection.";if(h.voiceDetection.endOfSpeechSensitivity!==void 0){if(typeof h.voiceDetection.endOfSpeechSensitivity!="number")return"End of speech sensitivity must be a number";if(h.voiceDetection.endOfSpeechSensitivity<0||h.voiceDetection.endOfSpeechSensitivity>1)return"End of speech sensitivity must be between 0 and 1"}}}buildStartSessionOptionsForClient(){let i={};if(this.clientOptions?.voiceDetection&&(i.voiceDetection=this.clientOptions.voiceDetection),Object.keys(i).length!==0)return i}async startSession(i){let r=this.personaConfig,h=this.buildStartSessionOptionsForClient(),d=await this.apiClient.startSession(r,h),{sessionId:p,clientConfig:m,engineHost:I,engineProtocol:y}=d,{ablyToken:k,ablyChannel:U,iceServers:O}=m;this.sessionId=p,Me({sessionId:this.sessionId});try{this.streamingClient=new Ot(p,{engine:{baseUrl:`${y}://${I}`},signalling:{ablyToken:k,channelName:U},iceServers:O,inputAudio:{inputAudioState:this.inputAudioState,userProvidedMediaStream:this.clientOptions?.disableInputAudio?void 0:i,audioDeviceId:this.clientOptions?.audioDeviceId,disableInputAudio:this.clientOptions?.disableInputAudio},metrics:{showPeerConnectionStatsReport:this.clientOptions?.metrics?.showPeerConnectionStatsReport??!1,peerConnectionStatsReportOutputFormat:this.clientOptions?.metrics?.peerConnectionStatsReportOutputFormat??"console"}},this.publicEventEmitter,this.internalEventEmitter)}catch(H){throw Me({sessionId:null}),new K("Failed to initialize streaming client","CLIENT_ERROR_CODE_SERVER_ERROR",500,{cause:H instanceof Error?H.message:String(H),sessionId:p})}return p}async startSessionIfNeeded(i){if((!this.sessionId||!this.streamingClient)&&(await this.startSession(i),!this.sessionId||!this.streamingClient))throw new K("Session ID or streaming client is not available after starting session","CLIENT_ERROR_CODE_SERVER_ERROR",500,{cause:"Failed to initialize session properly"})}async stream(i){if(this._isStreaming)throw new Error("Already streaming");let r=Jn();return Me({attemptCorrelationId:r,sessionId:null}),ue("client_session_attempt","1"),this.clientOptions?.disableInputAudio&&i&&console.warn("AnamClient:Input audio is disabled. User provided audio stream will be ignored."),await this.startSessionIfNeeded(i),this._isStreaming=!0,new Promise(h=>{let d=[],p=!1,m=!1;this.publicEventEmitter.addListener("VIDEO_STREAM_STARTED",I=>{d.push(I),p=!0,m&&h(d)}),this.publicEventEmitter.addListener("AUDIO_STREAM_STARTED",I=>{d.push(I),m=!0,p&&h(d)}),this.streamingClient?.startConnection()})}async streamToVideoAndAudioElements(i,r,h){console.warn("AnamClient: streamToVideoAndAudioElements is deprecated. To avoid possible audio issues, please use streamToVideoElement instead."),await this.streamToVideoElement(i,h)}async streamToVideoElement(i,r){let h=Jn();Me({attemptCorrelationId:h,sessionId:null}),ue("client_session_attempt","1"),this.clientOptions?.disableInputAudio&&r&&console.warn("AnamClient:Input audio is disabled. User provided audio stream will be ignored.");try{await this.startSessionIfNeeded(r)}catch(d){throw d instanceof K?d:new K("Failed to start session","CLIENT_ERROR_CODE_SERVER_ERROR",500,{cause:d instanceof Error?d.message:String(d),sessionId:this.sessionId})}if(this._isStreaming)throw new Error("Already streaming");if(this._isStreaming=!0,!this.streamingClient)throw new Error("Failed to stream: streaming client is not available");this.streamingClient.setMediaStreamTargetById(i),this.streamingClient.startConnection()}async talk(i){if(!this.streamingClient)throw new Error("Failed to send talk command: session is not started. Have you called startSession?");if(!this._isStreaming)throw new Error("Failed to send talk command: not currently streaming. Have you called stream?");await this.streamingClient.sendTalkCommand(i)}sendDataMessage(i){if(this.streamingClient)this.streamingClient.sendDataMessage(i);else throw new Error("Failed to send message: session is not started.")}sendUserMessage(i){if(!this._isStreaming)throw console.warn("AnamClient: Not currently streaming. User message will not be sent."),new Error("Failed to send user message: not currently streaming");let r=this.getActiveSessionId();if(!r)throw new Error("Failed to send user message: no active session");let h=new Date().toISOString().replace("Z",""),d=JSON.stringify({content:i,timestamp:h,session_id:r,message_type:"speech"});this.sendDataMessage(d)}interruptPersona(){if(!this._isStreaming)throw new Error("Failed to send interrupt command: not currently streaming");let i=this.getActiveSessionId();if(!i)throw new Error("Failed to send interrupt command: no active session");let r=JSON.stringify({message_type:"interrupt",session_id:i,timestamp:new Date().toISOString()});this.sendDataMessage(r)}async stopStreaming(){this.streamingClient&&(this.publicEventEmitter.emit("CONNECTION_CLOSED","CONNECTION_CLOSED_CODE_NORMAL"),await this.streamingClient.stopConnection(),this.streamingClient=null,this.sessionId=null,Me({attemptCorrelationId:null,sessionId:null,organizationId:this.organizationId}),this._isStreaming=!1)}isStreaming(){return this._isStreaming}setPersonaConfig(i){this.personaConfig=i}getPersonaConfig(){return this.personaConfig}getInputAudioState(){return this.clientOptions?.disableInputAudio&&console.warn("AnamClient: Audio state will not be used because input audio is disabled."),this.streamingClient&&(this.inputAudioState=this.streamingClient.getInputAudioState()),this.inputAudioState}muteInputAudio(){return this.clientOptions?.disableInputAudio&&console.warn("AnamClient: Input audio is disabled. Muting input audio will have no effect."),this.streamingClient&&!this.clientOptions?.disableInputAudio?this.inputAudioState=this.streamingClient.muteInputAudio():this.inputAudioState={...this.inputAudioState,isMuted:!0},this.inputAudioState}unmuteInputAudio(){return this.clientOptions?.disableInputAudio&&console.warn("AnamClient: Input audio is disabled. Unmuting input audio will have no effect."),this.streamingClient&&!this.clientOptions?.disableInputAudio?this.inputAudioState=this.streamingClient.unmuteInputAudio():this.inputAudioState={...this.inputAudioState,isMuted:!1},this.inputAudioState}createTalkMessageStream(i){if(!this.streamingClient)throw new Error("Failed to start talk message stream: session is not started.");if(i&&i.trim()==="")throw new Error("Failed to start talk message stream: correlationId is empty");return this.streamingClient.startTalkMessageStream(i)}addListener(i,r){this.publicEventEmitter.addListener(i,r)}removeListener(i,r){this.publicEventEmitter.removeListener(i,r)}getActiveSessionId(){return this.sessionId}};var md=(l,i)=>new et(l,void 0,i),yd=(l,i,r)=>new et(void 0,i,{...r,apiKey:l});export{ve as AnamEvent,Ze as ConnectionClosedCode,ke as InternalEvent,Yt as MessageRole,Xe as SignalMessageAction,md as createClient,yd as unsafe_createClientWithApiKey};
10
- /*! Bundled license information:
11
-
12
- ieee754/index.js:
13
- (*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> *)
14
-
15
- buffer/index.js:
16
- (*!
17
- * The buffer module from node.js, for the browser.
18
- *
19
- * @author Feross Aboukhadijeh <https://feross.org>
20
- * @license MIT
21
- *)
22
-
23
- ably/build/ably.js:
24
- (*@license Copyright 2015-2022 Ably Real-time Ltd (ably.com)
25
-
26
- Ably JavaScript Library v2.10.1
27
- https://github.com/ably/ably-js
28
-
29
- Released under the Apache Licence v2.0*)
30
- */
31
- //# sourceMappingURL=index.esm.js.map