hs-admin-ui 15.1.6 → 15.1.7

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 (486) hide show
  1. package/dist/crypto-js-CDv3g9Fu.js +14 -0
  2. package/dist/crypto-js-YAPiafFo.js +5020 -0
  3. package/dist/element-plus-BDPBrlGs.js +47 -0
  4. package/dist/element-plus-DsYvsms7.js +33347 -0
  5. package/dist/element-plus.css +1 -0
  6. package/dist/index.css +1 -0
  7. package/dist/index.js +21 -1
  8. package/dist/index.mjs +21262 -169
  9. package/dist/lodash-Bz9d-A6a.js +27 -0
  10. package/dist/lodash-D8UdwBmx.js +3677 -0
  11. package/dist/mathjs-DUElwFnu.js +53 -0
  12. package/dist/mathjs-DriWWyuQ.js +28075 -0
  13. package/dist/trtc-sdk-v5-CQx2bVFN.js +131 -0
  14. package/dist/trtc-sdk-v5-D3p_Spei.js +13452 -0
  15. package/dist/types/index.d.ts +1 -1
  16. package/dist/vender-CW460RJ7.js +102 -0
  17. package/dist/vender-DsdbGbik.js +26205 -0
  18. package/dist/vxe-pc-ui-D9AWriGd.js +25535 -0
  19. package/dist/vxe-pc-ui-yKZybkNt.js +4 -0
  20. package/dist/vxe-pc-ui.css +1 -0
  21. package/dist/vxe-table-AZLI7TZY.js +3 -0
  22. package/dist/vxe-table-CDtN4_hB.js +14273 -0
  23. package/dist/vxe-table.css +1 -0
  24. package/package.json +13 -41
  25. package/LICENSE +0 -21
  26. package/dist/401-BePx5kSv.mjs +0 -56
  27. package/dist/401-BruOzyt3.js +0 -1
  28. package/dist/404-CVkD6ebs.js +0 -1
  29. package/dist/404-CVkD6ebs.js.gz +0 -0
  30. package/dist/404-jQN6KU5y.mjs +0 -61
  31. package/dist/404-jQN6KU5y.mjs.gz +0 -0
  32. package/dist/account-Bw7GuU2Y.js +0 -1
  33. package/dist/account-RbilIl5p.mjs +0 -215
  34. package/dist/aside-CO_TFnBP.js +0 -1
  35. package/dist/aside-DGbD7WXx.mjs +0 -164
  36. package/dist/baseBtnConfig-C6KLedE5.mjs +0 -273
  37. package/dist/baseBtnConfig-DRxjBT8Z.js +0 -1
  38. package/dist/baseFormConfig-B0LkZBRJ.mjs +0 -504
  39. package/dist/baseFormConfig-B0LkZBRJ.mjs.gz +0 -0
  40. package/dist/baseFormConfig-BaFbaMWd.mjs +0 -722
  41. package/dist/baseFormConfig-BaFbaMWd.mjs.gz +0 -0
  42. package/dist/baseFormConfig-D5Q35Bo3.js +0 -1
  43. package/dist/baseFormConfig-XAt1gry0.js +0 -1
  44. package/dist/baseTableConfig-BxkqNzZ1.js +0 -1
  45. package/dist/baseTableConfig-BxkqNzZ1.js.gz +0 -0
  46. package/dist/baseTableConfig-Dkvzwm5z.mjs +0 -2624
  47. package/dist/baseTableConfig-Dkvzwm5z.mjs.gz +0 -0
  48. package/dist/bcFormConfig-Bn-_XbCl.mjs +0 -234
  49. package/dist/bcFormConfig-DJPNhuTH.js +0 -1
  50. package/dist/bcPageTreeBySystem.vue_vue_type_script_setup_true_lang-BEzNBOmo.js +0 -1
  51. package/dist/bcPageTreeBySystem.vue_vue_type_script_setup_true_lang-DG93G9jP.mjs +0 -131
  52. package/dist/bcSwitchSystems.vue_vue_type_script_setup_true_lang-BkfUkxPL.js +0 -1
  53. package/dist/bcSwitchSystems.vue_vue_type_script_setup_true_lang-lFAXGB7Y.mjs +0 -101
  54. package/dist/btnIndex-BsZSZGd4.js +0 -1
  55. package/dist/btnIndex-CqbzIQXE.mjs +0 -287
  56. package/dist/btnIndex-CqbzIQXE.mjs.gz +0 -0
  57. package/dist/classic-Bt3HfZzY.js +0 -1
  58. package/dist/classic-Dec3i2x2.mjs +0 -81
  59. package/dist/cloneConfigDialog-CQusM1M9.mjs +0 -817
  60. package/dist/cloneConfigDialog-CQusM1M9.mjs.gz +0 -0
  61. package/dist/cloneConfigDialog-Cl6qXd5e.js +0 -1
  62. package/dist/cloneConfigDialog-Cl6qXd5e.js.gz +0 -0
  63. package/dist/columns-C-o5zY9j.mjs +0 -87
  64. package/dist/columns-CXvoLhJP.js +0 -1
  65. package/dist/columnsAside-DJy-pEoD.js +0 -1
  66. package/dist/columnsAside-DnSlEG-x.mjs +0 -220
  67. package/dist/contextmenu-9jqMr4VX.mjs +0 -125
  68. package/dist/contextmenu-BfPQqiXK.mjs +0 -125
  69. package/dist/contextmenu-BliNwJm0.js +0 -1
  70. package/dist/contextmenu-DhGzlYnv.js +0 -1
  71. package/dist/copyMenuConfig-Cy4a281w.mjs +0 -4
  72. package/dist/copyMenuConfig-wbduEbAX.js +0 -1
  73. package/dist/copyMenuConfig.vue_vue_type_script_setup_true_lang-DEoJr7E5.mjs +0 -85
  74. package/dist/copyMenuConfig.vue_vue_type_script_setup_true_lang-DhXeuYsn.js +0 -1
  75. package/dist/copySystem-BVvrKj55.mjs +0 -4
  76. package/dist/copySystem-CU8MODKF.js +0 -1
  77. package/dist/copySystem.vue_vue_type_script_setup_true_lang-CM18bPv-.mjs +0 -78
  78. package/dist/copySystem.vue_vue_type_script_setup_true_lang-DJsMAvqs.js +0 -1
  79. package/dist/defaults-CDLdvMzg.js +0 -1
  80. package/dist/defaults-SEDq-Yru.mjs +0 -86
  81. package/dist/dialog-B3OvnqAp.js +0 -1
  82. package/dist/dialog-BpY5TPcI.mjs +0 -365
  83. package/dist/dialog-BpY5TPcI.mjs.gz +0 -0
  84. package/dist/dialog-Cf7iMybE.mjs +0 -10
  85. package/dist/dialog-D-InTgwh.js +0 -1
  86. package/dist/dialog-DQP53khI.mjs +0 -359
  87. package/dist/dialog-DQP53khI.mjs.gz +0 -0
  88. package/dist/dialog-DmOMzR5s.mjs +0 -4
  89. package/dist/dialog-DxBOYlwo.js +0 -1
  90. package/dist/dialog-HstJ1U1U.mjs +0 -4
  91. package/dist/dialog-MbRBbo7-.js +0 -1
  92. package/dist/dialog-TFJ52Qpk.js +0 -1
  93. package/dist/dialog.vue_vue_type_script_setup_true_name_dataAuthDialog_lang-BgZXqNWa.mjs +0 -220
  94. package/dist/dialog.vue_vue_type_script_setup_true_name_dataAuthDialog_lang-mdGXAfNy.js +0 -1
  95. package/dist/dialog.vue_vue_type_script_setup_true_name_systemMenuDialog_lang-B11N-m1T.mjs +0 -694
  96. package/dist/dialog.vue_vue_type_script_setup_true_name_systemMenuDialog_lang-B11N-m1T.mjs.gz +0 -0
  97. package/dist/dialog.vue_vue_type_script_setup_true_name_systemMenuDialog_lang-Bfimmfr9.js +0 -1
  98. package/dist/dialog.vue_vue_type_script_setup_true_name_systemMenuDialog_lang-Bfimmfr9.js.gz +0 -0
  99. package/dist/dictDialog-9WB_PEq3.mjs +0 -4
  100. package/dist/dictDialog-ChYWOYnC.js +0 -1
  101. package/dist/dictDialog.vue_vue_type_script_setup_true_name_dictDialog_lang-BqUqa2MM.js +0 -1
  102. package/dist/dictDialog.vue_vue_type_script_setup_true_name_dictDialog_lang-Dwk-_Zrd.mjs +0 -154
  103. package/dist/dictItemDialog-BvpodlZn.mjs +0 -4
  104. package/dist/dictItemDialog-Cu3CA1Fy.js +0 -1
  105. package/dist/dictItemDialog.vue_vue_type_script_setup_true_lang-BAa91Osq.js +0 -1
  106. package/dist/dictItemDialog.vue_vue_type_script_setup_true_lang-PaRWBrbP.mjs +0 -231
  107. package/dist/favicon.ico +0 -0
  108. package/dist/formConfig-BL3rYhB2.js +0 -1
  109. package/dist/formConfig-BL3rYhB2.js.gz +0 -0
  110. package/dist/formConfig-DRBUT-We.mjs +0 -592
  111. package/dist/formConfig-DRBUT-We.mjs.gz +0 -0
  112. package/dist/header-BcV4n4bO.mjs +0 -28
  113. package/dist/header-DnpDVR9P.js +0 -1
  114. package/dist/horizontal-CEPNInY6.mjs +0 -151
  115. package/dist/horizontal-RTM7XxDH.js +0 -1
  116. package/dist/hsAttrBtn-CE3CMNek.js +0 -1
  117. package/dist/hsAttrBtn-CiL5ezh7.mjs +0 -4
  118. package/dist/hsAttrBtn.vue_vue_type_script_setup_true_lang-B7YMfMWs.js +0 -1
  119. package/dist/hsAttrBtn.vue_vue_type_script_setup_true_lang-BZPaXw7E.mjs +0 -128
  120. package/dist/hsAttrForm-BCH4VRLC.mjs +0 -4
  121. package/dist/hsAttrForm-BZhKSm2W.js +0 -1
  122. package/dist/hsAttrForm.vue_vue_type_script_setup_true_lang-C1447QGx.js +0 -1
  123. package/dist/hsAttrForm.vue_vue_type_script_setup_true_lang-YUO0lTkn.mjs +0 -439
  124. package/dist/hsAttrForm.vue_vue_type_script_setup_true_lang-YUO0lTkn.mjs.gz +0 -0
  125. package/dist/hsBtnConfigList-BMaD3HLT.js +0 -1
  126. package/dist/hsBtnConfigList-DqBJmwk8.mjs +0 -117
  127. package/dist/hsBtnItemConfig-C9BAyIc1.js +0 -1
  128. package/dist/hsBtnItemConfig-DL6-SFjB.mjs +0 -4
  129. package/dist/hsBtnItemConfig.vue_vue_type_script_setup_true_lang-D3iLEZwe.js +0 -1
  130. package/dist/hsBtnItemConfig.vue_vue_type_script_setup_true_lang-DT6EDcI6.mjs +0 -147
  131. package/dist/hsBtnPanel-BJFipPMX.js +0 -1
  132. package/dist/hsBtnPanel-lgdpbYZA.mjs +0 -4
  133. package/dist/hsBtnPanel.vue_vue_type_script_setup_true_name_formPanel_lang-BIyoHv9a.js +0 -1
  134. package/dist/hsBtnPanel.vue_vue_type_script_setup_true_name_formPanel_lang-BW7roS0J.mjs +0 -67
  135. package/dist/hsCheckbox-BKa_El3s.js +0 -1
  136. package/dist/hsCheckbox-CalDndlZ.mjs +0 -4
  137. package/dist/hsCheckbox.vue_vue_type_script_setup_true_lang-Dh-lqGjq.js +0 -1
  138. package/dist/hsCheckbox.vue_vue_type_script_setup_true_lang-XCUyHi8X.mjs +0 -28
  139. package/dist/hsExpand-Bhhk7Jdi.mjs +0 -4
  140. package/dist/hsExpand-CQ3vWcYy.js +0 -1
  141. package/dist/hsExpand.vue_vue_type_script_setup_true_lang-B-IyqJIq.js +0 -1
  142. package/dist/hsExpand.vue_vue_type_script_setup_true_lang-D49jBgyP.mjs +0 -285
  143. package/dist/hsFormConfig-BR2oHpJJ.mjs +0 -207
  144. package/dist/hsFormConfig-DGphH9M7.js +0 -1
  145. package/dist/hsFormConfigList-CDZM6LN4.mjs +0 -414
  146. package/dist/hsFormConfigList-CDZM6LN4.mjs.gz +0 -0
  147. package/dist/hsFormConfigList-DEFRUzgO.js +0 -1
  148. package/dist/hsFormPanel-9xVlKXrH.js +0 -1
  149. package/dist/hsFormPanel-B9bY0wM7.mjs +0 -238
  150. package/dist/hsFormPanel-B9bY0wM7.mjs.gz +0 -0
  151. package/dist/hsFormParse-B8x5v5jx.js +0 -1
  152. package/dist/hsFormParse-BOT-NNYG.mjs +0 -4
  153. package/dist/hsFormParse.vue_vue_type_script_setup_true_lang-6aqTlfjv.js +0 -1
  154. package/dist/hsFormParse.vue_vue_type_script_setup_true_lang-CmxWqdX1.mjs +0 -242
  155. package/dist/hsPanelItem-C-7xaCLg.js +0 -1
  156. package/dist/hsPanelItem-CPASHLbr.mjs +0 -4
  157. package/dist/hsPanelItem.vue_vue_type_script_setup_true_name_panelItem_lang-DJASpFoF.js +0 -1
  158. package/dist/hsPanelItem.vue_vue_type_script_setup_true_name_panelItem_lang-rqLDQa4b.mjs +0 -86
  159. package/dist/iframes-CWdXFiYU.mjs +0 -122
  160. package/dist/iframes-DnAW1ZV2.js +0 -1
  161. package/dist/index copy-B3S_Bhdn.js +0 -1
  162. package/dist/index copy-BJ6LFdF1.mjs +0 -69
  163. package/dist/index copy-CsOZzjt9.js +0 -1
  164. package/dist/index copy-K1YcPYr9.mjs +0 -134
  165. package/dist/index-3UJSM3kd.js +0 -1
  166. package/dist/index-4ncpQ4eO.js +0 -1
  167. package/dist/index-6iu8JZuY.mjs +0 -1009
  168. package/dist/index-6iu8JZuY.mjs.gz +0 -0
  169. package/dist/index-79ZRlR7H.js +0 -1
  170. package/dist/index-7dwtQ4S9.js +0 -1
  171. package/dist/index-82-8Z3I8.js +0 -1
  172. package/dist/index-B03eGOGy.mjs +0 -133
  173. package/dist/index-B4QJL1DA.mjs +0 -10
  174. package/dist/index-B7FeSk1m.mjs +0 -4
  175. package/dist/index-B7Ggcbmc.js +0 -1
  176. package/dist/index-B7Ggcbmc.js.gz +0 -0
  177. package/dist/index-B8nrdqc9.mjs +0 -47
  178. package/dist/index-BDozMyrz.mjs +0 -95
  179. package/dist/index-BFZ9P1dy.js +0 -1
  180. package/dist/index-BHEgh4cW.mjs +0 -4
  181. package/dist/index-BHHI4_CY.js +0 -1
  182. package/dist/index-BIgnSPCb.js +0 -1
  183. package/dist/index-BIyVJNgI.js +0 -1
  184. package/dist/index-BKOItnzJ.js +0 -111
  185. package/dist/index-BKOItnzJ.js.gz +0 -0
  186. package/dist/index-BLycUQgN.mjs +0 -119
  187. package/dist/index-BMpjRLM7.js +0 -1
  188. package/dist/index-BOkwyZP7.mjs +0 -213
  189. package/dist/index-BSBQtzjR.js +0 -1
  190. package/dist/index-BT1BhIbi.js +0 -1
  191. package/dist/index-BZr64ugI.js +0 -1
  192. package/dist/index-BaeZfYEj.mjs +0 -4
  193. package/dist/index-BbXbVv7K.mjs +0 -4
  194. package/dist/index-Bgwg31Qt.js +0 -1
  195. package/dist/index-BhMp70XH.mjs +0 -94
  196. package/dist/index-BkyRUnkO.js +0 -1
  197. package/dist/index-BrTAFhhs.mjs +0 -2208
  198. package/dist/index-BrTAFhhs.mjs.gz +0 -0
  199. package/dist/index-BwKrUIVd.mjs +0 -14
  200. package/dist/index-ByjtaERc.js +0 -1
  201. package/dist/index-BzaNS4eH.mjs +0 -67
  202. package/dist/index-C0D9zAa6.mjs +0 -5403
  203. package/dist/index-C0D9zAa6.mjs.gz +0 -0
  204. package/dist/index-C1uuTYqn.js +0 -1
  205. package/dist/index-C9nUkjy2.js +0 -1
  206. package/dist/index-CGROx9d2.mjs +0 -23
  207. package/dist/index-CGVLSa-Z.mjs +0 -89
  208. package/dist/index-CI88VXHh.js +0 -1
  209. package/dist/index-CIUdc0tl.js +0 -1
  210. package/dist/index-CLpyyily.mjs +0 -285
  211. package/dist/index-CM2QwHXA.js +0 -1
  212. package/dist/index-COp-mviH.js +0 -1
  213. package/dist/index-CUE6cOFE.mjs +0 -76
  214. package/dist/index-CXHit-vm.js +0 -1
  215. package/dist/index-CXHit-vm.js.gz +0 -0
  216. package/dist/index-CbCppT2z.js +0 -1
  217. package/dist/index-CbgKih92.js +0 -1
  218. package/dist/index-Cji7t1Jc.mjs +0 -173
  219. package/dist/index-CqIZ1k-x.mjs +0 -65
  220. package/dist/index-CrrapXlE.js +0 -1
  221. package/dist/index-CzWSMFPz.js +0 -1
  222. package/dist/index-CzWSMFPz.js.gz +0 -0
  223. package/dist/index-D6PuZeGA.mjs +0 -254
  224. package/dist/index-DBvCcs0m.js +0 -1
  225. package/dist/index-DEykAVeO.js +0 -1
  226. package/dist/index-DHHcO6BG.js +0 -1
  227. package/dist/index-DHsKIehs.js +0 -1
  228. package/dist/index-DNpYXPbH.mjs +0 -30
  229. package/dist/index-DOi1__i9.js +0 -1
  230. package/dist/index-DS3B-tKV.mjs +0 -254951
  231. package/dist/index-DS3B-tKV.mjs.gz +0 -0
  232. package/dist/index-DSWpyZ7C.mjs +0 -65
  233. package/dist/index-DSjqqbn0.js +0 -1
  234. package/dist/index-DT3c6iM1.mjs +0 -49
  235. package/dist/index-DYiTqLqC.mjs +0 -51
  236. package/dist/index-DYk60nb9.mjs +0 -50
  237. package/dist/index-DZ_UFJE2.mjs +0 -43
  238. package/dist/index-DfEspIWc.mjs +0 -262
  239. package/dist/index-Dfp17Bwa.mjs +0 -4
  240. package/dist/index-DgEXQL9C.mjs +0 -403
  241. package/dist/index-DgEXQL9C.mjs.gz +0 -0
  242. package/dist/index-DnUx8Zdo.mjs +0 -73
  243. package/dist/index-Dur4EUIu.mjs +0 -73
  244. package/dist/index-DzRR1RxG.js +0 -1
  245. package/dist/index-IAOLoA9b.js +0 -1
  246. package/dist/index-MScX3_tk.mjs +0 -10
  247. package/dist/index-NBXUgAw3.mjs +0 -331
  248. package/dist/index-NBXUgAw3.mjs.gz +0 -0
  249. package/dist/index-OcKc5oUD.js +0 -1
  250. package/dist/index-PCI3lWru.mjs +0 -38
  251. package/dist/index-P_kHpPhU.js +0 -1
  252. package/dist/index-QNrlL5fl.js +0 -1
  253. package/dist/index-W_IJV_8K.mjs +0 -22
  254. package/dist/index-Z83-84L3.js +0 -1
  255. package/dist/index-_-xa-98Q.mjs +0 -172
  256. package/dist/index-feq0FF6W.mjs +0 -23
  257. package/dist/index-g2ermQHl.mjs +0 -131
  258. package/dist/index-g_BDa62N.mjs +0 -19
  259. package/dist/index-hgZg0VtS.js +0 -1
  260. package/dist/index-k2-oxT3d.mjs +0 -200
  261. package/dist/index-sdudei9U.mjs +0 -152
  262. package/dist/index-tZQPmXty.js +0 -1
  263. package/dist/index-v7jFnqoB.js +0 -1
  264. package/dist/index-zhWfbpLN.js +0 -1
  265. package/dist/index.vue_vue_type_script_setup_true_lang-9yt_AqOo.mjs +0 -194
  266. package/dist/index.vue_vue_type_script_setup_true_lang-BBB1sJxx.mjs +0 -267
  267. package/dist/index.vue_vue_type_script_setup_true_lang-BBB1sJxx.mjs.gz +0 -0
  268. package/dist/index.vue_vue_type_script_setup_true_lang-CfrDnaDb.js +0 -1
  269. package/dist/index.vue_vue_type_script_setup_true_lang-Cmc_75Q9.mjs +0 -97
  270. package/dist/index.vue_vue_type_script_setup_true_lang-DC2YOBp8.mjs +0 -103
  271. package/dist/index.vue_vue_type_script_setup_true_lang-DkqCU_07.js +0 -1
  272. package/dist/index.vue_vue_type_script_setup_true_lang-DueNaQN9.js +0 -1
  273. package/dist/index.vue_vue_type_script_setup_true_lang-lub2RD3v.js +0 -1
  274. package/dist/index.vue_vue_type_script_setup_true_name_iconSelector_lang-DZPUQb3w.mjs +0 -288
  275. package/dist/index.vue_vue_type_script_setup_true_name_iconSelector_lang-DZPUQb3w.mjs.gz +0 -0
  276. package/dist/index.vue_vue_type_script_setup_true_name_iconSelector_lang-kCj43-0A.js +0 -1
  277. package/dist/lib-generate-test-usersig.min.js +0 -2
  278. package/dist/lib-generate-test-usersig.min.js.gz +0 -0
  279. package/dist/link-BgAziH_3.mjs +0 -63
  280. package/dist/link-Sqx3Q52p.js +0 -1
  281. package/dist/list-8FpcTs_2.js +0 -1
  282. package/dist/list-B67E-uei.mjs +0 -85
  283. package/dist/logo-mini-BQ9BrQ1U.mjs +0 -4
  284. package/dist/logo-mini-DwRdfcE7.js +0 -1
  285. package/dist/main-CmcbR12f.mjs +0 -72
  286. package/dist/main-DDPKI7Ni.js +0 -1
  287. package/dist/mobile-CBTICbJa.js +0 -1
  288. package/dist/mobile-Dcn_uE49.mjs +0 -115
  289. package/dist/parent-BP8X2kB8.js +0 -1
  290. package/dist/parent-BrVaTYeC.mjs +0 -131
  291. package/dist/popup-BEiDsECK.mjs +0 -4
  292. package/dist/popup-B_5FHg24.js +0 -1
  293. package/dist/popup.vue_vue_type_script_setup_true_name_replaceRules_lang-23ItHebo.mjs +0 -89
  294. package/dist/popup.vue_vue_type_script_setup_true_name_replaceRules_lang-GJCKGOLm.js +0 -1
  295. package/dist/roleItem-BQW8elI1.mjs +0 -103
  296. package/dist/roleItem-FUZgV9xL.js +0 -1
  297. package/dist/saveForm-BDrXtiIE.mjs +0 -160
  298. package/dist/saveForm-BxQmbdKc.js +0 -1
  299. package/dist/scan-BRU9Wew1.mjs +0 -945
  300. package/dist/scan-BRU9Wew1.mjs.gz +0 -0
  301. package/dist/scan-j7LW3Xdv.js +0 -1
  302. package/dist/scan-j7LW3Xdv.js.gz +0 -0
  303. package/dist/search-BdOGXXxf.js +0 -1
  304. package/dist/search-kPkciC8X.mjs +0 -114
  305. package/dist/selectConfig-Dj-vR1zX.mjs +0 -546
  306. package/dist/selectConfig-Dj-vR1zX.mjs.gz +0 -0
  307. package/dist/selectConfig-x1qMbzEi.js +0 -1
  308. package/dist/shortcutList-BXBGQdNn.mjs +0 -76
  309. package/dist/shortcutList-WSi4lUlm.js +0 -1
  310. package/dist/style.css +0 -1
  311. package/dist/style.css.gz +0 -0
  312. package/dist/subItem-DK1aBmBX.js +0 -1
  313. package/dist/subItem-LshS1tdW.mjs +0 -77
  314. package/dist/tagsView-BdC9SbGU.js +0 -8
  315. package/dist/tagsView-BdC9SbGU.js.gz +0 -0
  316. package/dist/tagsView-ByNvn7m7.mjs +0 -2695
  317. package/dist/tagsView-ByNvn7m7.mjs.gz +0 -0
  318. package/dist/transverse-Au31vuAN.mjs +0 -65
  319. package/dist/transverse-D2dpAzsD.js +0 -1
  320. package/dist/types/components/business/bcBox/bcBox.vue.d.ts +0 -66
  321. package/dist/types/components/business/bcBox/utils.d.ts +0 -68
  322. package/dist/types/components/business/bcBreadcrumb/bcBreadcrumb.vue.d.ts +0 -23
  323. package/dist/types/components/business/bcBreadcrumb/index.d.ts +0 -12
  324. package/dist/types/components/business/bcForm/baseForm.vue.d.ts +0 -273
  325. package/dist/types/components/business/bcForm/bcForm.vue.d.ts +0 -42
  326. package/dist/types/components/business/bcForm/type.d.ts +0 -138
  327. package/dist/types/components/business/bcForm/useGuide.d.ts +0 -564
  328. package/dist/types/components/business/bcSystemAuth/components/data.vue.d.ts +0 -3
  329. package/dist/types/components/business/bcSystemAuth/components/dict.vue.d.ts +0 -3
  330. package/dist/types/components/business/bcSystemAuth/components/fastSet/index.d.ts +0 -1
  331. package/dist/types/components/business/bcSystemAuth/components/fastSet/popup.vue.d.ts +0 -17
  332. package/dist/types/components/business/bcSystemAuth/components/field.vue.d.ts +0 -3
  333. package/dist/types/components/business/bcSystemAuth/components/form.vue.d.ts +0 -13
  334. package/dist/types/components/business/bcSystemAuth/components/index.d.ts +0 -5
  335. package/dist/types/components/business/bcSystemAuth/components/selectAll/index.d.ts +0 -24
  336. package/dist/types/components/business/bcSystemAuth/components/selectAll/index.vue.d.ts +0 -5
  337. package/dist/types/components/business/bcSystemAuth/components/table.vue.d.ts +0 -13
  338. package/dist/types/components/business/bcSystemAuth/components/widget/btns.vue.d.ts +0 -15
  339. package/dist/types/components/business/bcSystemAuth/components/widget/form.vue.d.ts +0 -15
  340. package/dist/types/components/business/bcSystemAuth/components/widget/index.d.ts +0 -3
  341. package/dist/types/components/business/bcSystemAuth/components/widget/tab.vue.d.ts +0 -45
  342. package/dist/types/components/business/bcSystemAuth/components/widget/tables.vue.d.ts +0 -15
  343. package/dist/types/components/business/bcSystemAuth/components/widget/tablesWraper.vue.d.ts +0 -15
  344. package/dist/types/components/business/bcSystemAuth/fastStore.d.ts +0 -512
  345. package/dist/types/components/business/bcSystemAuth/fastUtils.d.ts +0 -346
  346. package/dist/types/components/business/bcSystemAuth/index.d.ts +0 -3
  347. package/dist/types/components/business/bcSystemAuth/index.vue.d.ts +0 -26
  348. package/dist/types/components/business/bcSystemAuth/store.d.ts +0 -512
  349. package/dist/types/components/business/bcSystemAuth/type.d.ts +0 -42
  350. package/dist/types/components/business/bcSystemAuth/useAuth.d.ts +0 -28
  351. package/dist/types/components/business/bcSystemAuth/utils.d.ts +0 -346
  352. package/dist/types/components/business/bcSystemField/components/field.vue.d.ts +0 -3
  353. package/dist/types/components/business/bcSystemField/components/form.vue.d.ts +0 -13
  354. package/dist/types/components/business/bcSystemField/components/index.d.ts +0 -3
  355. package/dist/types/components/business/bcSystemField/components/selectAll/index.d.ts +0 -22
  356. package/dist/types/components/business/bcSystemField/components/selectAll/index.vue.d.ts +0 -5
  357. package/dist/types/components/business/bcSystemField/components/table.vue.d.ts +0 -13
  358. package/dist/types/components/business/bcSystemField/components/widget/form.vue.d.ts +0 -15
  359. package/dist/types/components/business/bcSystemField/components/widget/index.d.ts +0 -2
  360. package/dist/types/components/business/bcSystemField/components/widget/tab.vue.d.ts +0 -45
  361. package/dist/types/components/business/bcSystemField/components/widget/tables.vue.d.ts +0 -15
  362. package/dist/types/components/business/bcSystemField/components/widget/tablesWraper.vue.d.ts +0 -15
  363. package/dist/types/components/business/bcSystemField/index.d.ts +0 -3
  364. package/dist/types/components/business/bcSystemField/index.vue.d.ts +0 -16
  365. package/dist/types/components/business/bcSystemField/store.d.ts +0 -343
  366. package/dist/types/components/business/bcSystemField/useAuth.d.ts +0 -16
  367. package/dist/types/components/business/bcSystemField/utils.d.ts +0 -187
  368. package/dist/types/components/business/bcTable/bcFormTable.vue.d.ts +0 -142
  369. package/dist/types/components/business/bcTable/bcTable.vue.d.ts +0 -51
  370. package/dist/types/components/business/bcTable/components/btn/btn.vue.d.ts +0 -77
  371. package/dist/types/components/business/bcTable/components/index.d.ts +0 -4
  372. package/dist/types/components/business/bcTable/components/popup/index.d.ts +0 -3
  373. package/dist/types/components/business/bcTable/components/query/components/sortForm/index.d.ts +0 -2
  374. package/dist/types/components/business/bcTable/components/query/components/sortForm/sortForm.vue.d.ts +0 -23
  375. package/dist/types/components/business/bcTable/components/query/drag.vue.d.ts +0 -244
  376. package/dist/types/components/business/bcTable/components/query/query.vue.d.ts +0 -249
  377. package/dist/types/components/business/bcTable/components/query/useQuickSearch.d.ts +0 -8
  378. package/dist/types/components/business/bcTable/components/table/colgroup.vue.d.ts +0 -28
  379. package/dist/types/components/business/bcTable/components/table/column.vue.d.ts +0 -35
  380. package/dist/types/components/business/bcTable/components/table/components/sortColumn/index.d.ts +0 -2
  381. package/dist/types/components/business/bcTable/components/table/components/sortColumn/sortColumn.vue.d.ts +0 -25
  382. package/dist/types/components/business/bcTable/components/table/components/sortColumn/types.d.ts +0 -20
  383. package/dist/types/components/business/bcTable/components/table/table.vue.d.ts +0 -67
  384. package/dist/types/components/business/bcTable/components/table/useTable.d.ts +0 -36
  385. package/dist/types/components/business/bcTable/components/table/useTableHeight.d.ts +0 -25
  386. package/dist/types/components/business/bcTable/methods/cellDetailMethod.d.ts +0 -3
  387. package/dist/types/components/business/bcTable/methods/filterAgeMethod.d.ts +0 -3
  388. package/dist/types/components/business/bcTable/methods/footerMethod.d.ts +0 -4
  389. package/dist/types/components/business/bcTable/methods/formBtnMethod.d.ts +0 -8
  390. package/dist/types/components/business/bcTable/methods/index.d.ts +0 -4
  391. package/dist/types/components/business/bcTable/utils/authField.d.ts +0 -6
  392. package/dist/types/components/business/bcTable/utils/onFormKey.d.ts +0 -16
  393. package/dist/types/components/business/bcTable/utils/onTableKey.d.ts +0 -16
  394. package/dist/types/components/business/bcTable/utils/parseTable.d.ts +0 -117
  395. package/dist/types/components/business/bcTable/utils/type.d.ts +0 -463
  396. package/dist/types/components/business/bcTable/utils/useBcTable.d.ts +0 -12918
  397. package/dist/types/components/business/bcTable/utils/useButon.d.ts +0 -12
  398. package/dist/types/components/business/bcTable/utils/useFormTableHeight.d.ts +0 -20
  399. package/dist/types/components/business/bcTable/utils/useKeydownEvent.d.ts +0 -45
  400. package/dist/types/components/business/bcVisual/bcVisual.vue.d.ts +0 -57
  401. package/dist/types/components/business/bcVisual/components/setting/dragItem.vue.d.ts +0 -46
  402. package/dist/types/components/business/bcVisual/components/setting/extendItem.vue.d.ts +0 -13
  403. package/dist/types/components/business/bcVisual/components/setting/setting.vue.d.ts +0 -3
  404. package/dist/types/components/business/bcVisual/components/setting/useDrag.d.ts +0 -10
  405. package/dist/types/components/business/bcVisual/components/table/table.vue.d.ts +0 -6
  406. package/dist/types/components/business/bcVisual/components/updateName/index.d.ts +0 -1
  407. package/dist/types/components/business/bcVisual/components/updateName/popup.vue.d.ts +0 -17
  408. package/dist/types/components/business/bcVisual/components/updateSql/addCondition.vue.d.ts +0 -23
  409. package/dist/types/components/business/bcVisual/components/updateSql/index.d.ts +0 -4
  410. package/dist/types/components/business/bcVisual/components/updateSql/nodeTree/index.d.ts +0 -19
  411. package/dist/types/components/business/bcVisual/components/updateSql/nodeTree/index.vue.d.ts +0 -21
  412. package/dist/types/components/business/bcVisual/components/updateSql/nodeTree/nodeTree.vue.d.ts +0 -19
  413. package/dist/types/components/business/bcVisual/components/updateSql/popup.vue.d.ts +0 -17
  414. package/dist/types/components/business/bcVisual/type.d.ts +0 -186
  415. package/dist/types/components/business/bcVisual/useTableFormat.d.ts +0 -271
  416. package/dist/types/components/business/bcVisual/utils.d.ts +0 -134
  417. package/dist/types/plugins/index.d.ts +0 -33
  418. package/dist/types/types/auth.d.ts +0 -81
  419. package/dist/types/types/components.d.ts +0 -29
  420. package/dist/types/types/customData.d.ts +0 -309
  421. package/dist/types/types/form.d.ts +0 -100
  422. package/dist/types/types/formItem/autocomplete.d.ts +0 -45
  423. package/dist/types/types/formItem/button.d.ts +0 -39
  424. package/dist/types/types/formItem/checkbox.d.ts +0 -80
  425. package/dist/types/types/formItem/index.d.ts +0 -9
  426. package/dist/types/types/formItem/input.d.ts +0 -65
  427. package/dist/types/types/formItem/inputGroup.d.ts +0 -14
  428. package/dist/types/types/formItem/inputNumber.d.ts +0 -41
  429. package/dist/types/types/formItem/radio.d.ts +0 -58
  430. package/dist/types/types/formItem/selelct.d.ts +0 -56
  431. package/dist/types/types/formItem/treeSelect.d.ts +0 -41
  432. package/dist/types/types/index.d.ts +0 -6
  433. package/dist/types/types/system.d.ts +0 -14
  434. package/dist/types/utils/arrayOperation.d.ts +0 -21
  435. package/dist/types/utils/authFunction.d.ts +0 -18
  436. package/dist/types/utils/build.d.ts +0 -11
  437. package/dist/types/utils/cfprint.d.ts +0 -70
  438. package/dist/types/utils/common.d.ts +0 -15
  439. package/dist/types/utils/commonFunction.d.ts +0 -29
  440. package/dist/types/utils/crypto.d.ts +0 -5
  441. package/dist/types/utils/device_info.d.ts +0 -14
  442. package/dist/types/utils/download.d.ts +0 -73
  443. package/dist/types/utils/file.d.ts +0 -6
  444. package/dist/types/utils/formatTime.d.ts +0 -37
  445. package/dist/types/utils/getDataType.d.ts +0 -9
  446. package/dist/types/utils/getStyleSheets.d.ts +0 -11
  447. package/dist/types/utils/index.d.ts +0 -29
  448. package/dist/types/utils/loading.d.ts +0 -10
  449. package/dist/types/utils/lodash.d.ts +0 -3
  450. package/dist/types/utils/mitt.d.ts +0 -11
  451. package/dist/types/utils/number.d.ts +0 -82
  452. package/dist/types/utils/other.d.ts +0 -75
  453. package/dist/types/utils/request/index.d.ts +0 -6
  454. package/dist/types/utils/request/interceptors/request/authorization.interceptor.d.ts +0 -4
  455. package/dist/types/utils/request/interceptors/request/index.d.ts +0 -2
  456. package/dist/types/utils/request/interceptors/request/result.type.interceptor.d.ts +0 -4
  457. package/dist/types/utils/request/interceptors/request/undefined-params-handler.interceptor.d.ts +0 -13
  458. package/dist/types/utils/request/interceptors/response/error-handler.interceptor.d.ts +0 -4
  459. package/dist/types/utils/request/interceptors/response/index.d.ts +0 -2
  460. package/dist/types/utils/request/repeatRequest.d.ts +0 -4
  461. package/dist/types/utils/request/request.d.ts +0 -7
  462. package/dist/types/utils/setIconfont.d.ts +0 -11
  463. package/dist/types/utils/shortcutList.d.ts +0 -4
  464. package/dist/types/utils/showMessage.d.ts +0 -6
  465. package/dist/types/utils/showMessageBox.d.ts +0 -6
  466. package/dist/types/utils/showNotification.d.ts +0 -6
  467. package/dist/types/utils/showPopup/index.d.ts +0 -35
  468. package/dist/types/utils/storage.d.ts +0 -177
  469. package/dist/types/utils/theme.d.ts +0 -13
  470. package/dist/types/utils/toolsValidate.d.ts +0 -149
  471. package/dist/types/utils/tree.d.ts +0 -26
  472. package/dist/types/utils/update.d.ts +0 -1
  473. package/dist/types/utils/url.d.ts +0 -23
  474. package/dist/types/utils/watermark.d.ts +0 -9
  475. package/dist/useConfigInfo-2zEYLSSs.js +0 -1
  476. package/dist/useConfigInfo-PTkkdx-l.mjs +0 -19
  477. package/dist/user-DRbPksY1.js +0 -1
  478. package/dist/user-Ov9wSafP.mjs +0 -246
  479. package/dist/userNews-Cqxll0Ds.mjs +0 -72
  480. package/dist/userNews-DoDA3w2k.js +0 -1
  481. package/dist/userSelect-DSYUFA--.mjs +0 -4
  482. package/dist/userSelect-XDlpJz1X.js +0 -1
  483. package/dist/userSelect.vue_vue_type_script_setup_true_lang-CI2_r4Ah.mjs +0 -100
  484. package/dist/userSelect.vue_vue_type_script_setup_true_lang-Dyt80LKy.js +0 -1
  485. package/dist/vertical-CnMFrhxt.mjs +0 -133
  486. package/dist/vertical-ST7_xt19.js +0 -1
@@ -0,0 +1,131 @@
1
+ "use strict";const kc=require("./crypto-js-CDv3g9Fu.js");var AI={exports:{}};(function(RI,f1){(function(Rp,ca){RI.exports=ca()})(kc.commonjsGlobal,function(){function Rp(e,t){return t.forEach(function(i){i&&typeof i!="string"&&!Array.isArray(i)&&Object.keys(i).forEach(function(r){if(r!=="default"&&!(r in e)){var n=Object.getOwnPropertyDescriptor(i,r);Object.defineProperty(e,r,n.get?n:{enumerable:!0,get:function(){return i[r]}})}})}),Object.freeze(e)}var ca=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof kc.commonjsGlobal<"u"?kc.commonjsGlobal:typeof self<"u"?self:{},Z=function(e){try{return!!e()}catch{return!0}},la=!Z(function(){var e=(function(){}).bind();return typeof e!="function"||e.hasOwnProperty("prototype")}),Cp=la,bp=Function.prototype,Nc=bp.call,CI=Cp&&bp.bind.bind(Nc,Nc),ee=Cp?CI:function(e){return function(){return Nc.apply(e,arguments)}},kp=ee,bI=kp({}.toString),kI=kp("".slice),Pi=function(e){return kI(bI(e),8,-1)},NI=Z,DI=Pi,Dc=Object,wI=ee("".split),ua=NI(function(){return!Dc("z").propertyIsEnumerable(0)})?function(e){return DI(e)=="String"?wI(e,""):Dc(e)}:Dc,Er=function(e){return e==null},OI=Er,PI=TypeError,Xt=function(e){if(OI(e))throw PI("Can't call method on "+e);return e},LI=ua,MI=Xt,Rn=function(e){return LI(MI(e))},da=function(e){return e&&e.Math==Math&&e},te=da(typeof globalThis=="object"&&globalThis)||da(typeof window=="object"&&window)||da(typeof self=="object"&&self)||da(typeof ca=="object"&&ca)||function(){return this}()||Function("return this")(),Cn={},xI={get exports(){return Cn},set exports(e){Cn=e}},Np=te,VI=Object.defineProperty,wc=function(e,t){try{VI(Np,e,{value:t,configurable:!0,writable:!0})}catch{Np[e]=t}return t},UI=wc,Dp="__core-js_shared__",Oc=te[Dp]||UI(Dp,{}),wp=Oc;(xI.exports=function(e,t){return wp[e]||(wp[e]=t!==void 0?t:{})})("versions",[]).push({version:"3.30.0",mode:"global",copyright:"© 2014-2023 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.30.0/LICENSE",source:"https://github.com/zloirock/core-js"});var $t,ha,FI=Xt,BI=Object,nt=function(e){return BI(FI(e))},HI=nt,jI=ee({}.hasOwnProperty),ve=Object.hasOwn||function(e,t){return jI(HI(e),t)},GI=ee,WI=0,JI=Math.random(),zI=GI(1 .toString),Pc=function(e){return"Symbol("+(e===void 0?"":e)+")_"+zI(++WI+JI,36)},Zt=typeof navigator<"u"&&String(navigator.userAgent)||"",Op=te,Lc=Zt,Pp=Op.process,Lp=Op.Deno,Mp=Pp&&Pp.versions||Lp&&Lp.version,xp=Mp&&Mp.v8;xp&&(ha=($t=xp.split("."))[0]>0&&$t[0]<4?1:+($t[0]+$t[1])),!ha&&Lc&&(!($t=Lc.match(/Edge\/(\d+)/))||$t[1]>=74)&&($t=Lc.match(/Chrome\/(\d+)/))&&(ha=+$t[1]);var yr=ha,Vp=yr,KI=Z,Up=!!Object.getOwnPropertySymbols&&!KI(function(){var e=Symbol();return!String(e)||!(Object(e)instanceof Symbol)||!Symbol.sham&&Vp&&Vp<41}),Fp=Up&&!Symbol.sham&&typeof Symbol.iterator=="symbol",qI=Cn,Bp=ve,YI=Pc,QI=Up,XI=Fp,Sr=te.Symbol,Mc=qI("wks"),$I=XI?Sr.for||Sr:Sr&&Sr.withoutSetter||YI,ce=function(e){return Bp(Mc,e)||(Mc[e]=QI&&Bp(Sr,e)?Sr[e]:$I("Symbol."+e)),Mc[e]},xc=typeof document=="object"&&document.all,pa={all:xc,IS_HTMLDDA:xc===void 0&&xc!==void 0},ZI=pa.all,ie=pa.IS_HTMLDDA?function(e){return typeof e=="function"||e===ZI}:function(e){return typeof e=="function"},Hp=ie,eA=pa.all,De=pa.IS_HTMLDDA?function(e){return typeof e=="object"?e!==null:Hp(e)||e===eA}:function(e){return typeof e=="object"?e!==null:Hp(e)},tA=De,iA=String,rA=TypeError,Re=function(e){if(tA(e))return e;throw rA(iA(e)+" is not an object")},jp={},Ee=!Z(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7}),Gp=Ee&&Z(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42}),Ke={},Wp=De,Vc=te.document,nA=Wp(Vc)&&Wp(Vc.createElement),ma=function(e){return nA?Vc.createElement(e):{}},sA=ma,Jp=!Ee&&!Z(function(){return Object.defineProperty(sA("div"),"a",{get:function(){return 7}}).a!=7}),aA=la,_a=Function.prototype.call,le=aA?_a.bind(_a):function(){return _a.apply(_a,arguments)},Uc=te,oA=ie,ei=function(e,t){return arguments.length<2?(i=Uc[e],oA(i)?i:void 0):Uc[e]&&Uc[e][t];var i},ti=ee({}.isPrototypeOf),cA=ei,lA=ie,uA=ti,dA=Object,Fc=Fp?function(e){return typeof e=="symbol"}:function(e){var t=cA("Symbol");return lA(t)&&uA(t.prototype,dA(e))},hA=String,vr=function(e){try{return hA(e)}catch{return"Object"}},pA=ie,mA=vr,_A=TypeError,st=function(e){if(pA(e))return e;throw _A(mA(e)+" is not a function")},fA=st,gA=Er,bn=function(e,t){var i=e[t];return gA(i)?void 0:fA(i)},Bc=le,Hc=ie,jc=De,TA=TypeError,EA=le,zp=De,Kp=Fc,yA=bn,SA=function(e,t){var i,r;if(t==="string"&&Hc(i=e.toString)&&!jc(r=Bc(i,e))||Hc(i=e.valueOf)&&!jc(r=Bc(i,e))||t!=="string"&&Hc(i=e.toString)&&!jc(r=Bc(i,e)))return r;throw TA("Can't convert object to primitive value")},vA=TypeError,IA=ce("toPrimitive"),qp=function(e,t){if(!zp(e)||Kp(e))return e;var i,r=yA(e,IA);if(r){if(t===void 0&&(t="default"),i=EA(r,e,t),!zp(i)||Kp(i))return i;throw vA("Can't convert object to primitive value")}return t===void 0&&(t="number"),SA(e,t)},AA=qp,RA=Fc,fa=function(e){var t=AA(e,"string");return RA(t)?t:t+""},CA=Ee,bA=Jp,kA=Gp,ga=Re,Yp=fa,NA=TypeError,Gc=Object.defineProperty,DA=Object.getOwnPropertyDescriptor,Wc="enumerable",Jc="configurable",zc="writable";Ke.f=CA?kA?function(e,t,i){if(ga(e),t=Yp(t),ga(i),typeof e=="function"&&t==="prototype"&&"value"in i&&zc in i&&!i[zc]){var r=DA(e,t);r&&r[zc]&&(e[t]=i.value,i={configurable:Jc in i?i[Jc]:r[Jc],enumerable:Wc in i?i[Wc]:r[Wc],writable:!1})}return Gc(e,t,i)}:Gc:function(e,t,i){if(ga(e),t=Yp(t),ga(i),bA)try{return Gc(e,t,i)}catch{}if("get"in i||"set"in i)throw NA("Accessors not supported");return"value"in i&&(e[t]=i.value),e};var wA=Math.ceil,OA=Math.floor,PA=Math.trunc||function(e){var t=+e;return(t>0?OA:wA)(t)},LA=PA,ii=function(e){var t=+e;return t!=t||t===0?0:LA(t)},MA=ii,xA=Math.max,VA=Math.min,Ta=function(e,t){var i=MA(e);return i<0?xA(i+t,0):VA(i,t)},UA=ii,FA=Math.min,Li=function(e){return e>0?FA(UA(e),9007199254740991):0},BA=Li,_t=function(e){return BA(e.length)},HA=Rn,jA=Ta,GA=_t,Qp=function(e){return function(t,i,r){var n,s=HA(t),a=GA(s),c=jA(r,a);if(e&&i!=i){for(;a>c;)if((n=s[c++])!=n)return!0}else for(;a>c;c++)if((e||c in s)&&s[c]===i)return e||c||0;return!e&&-1}},Xp={includes:Qp(!0),indexOf:Qp(!1)},Kc={},qc=ve,WA=Rn,JA=Xp.indexOf,zA=Kc,$p=ee([].push),Zp=function(e,t){var i,r=WA(e),n=0,s=[];for(i in r)!qc(zA,i)&&qc(r,i)&&$p(s,i);for(;t.length>n;)qc(r,i=t[n++])&&(~JA(s,i)||$p(s,i));return s},Yc=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],KA=Zp,qA=Yc,em=Object.keys||function(e){return KA(e,qA)},YA=Ee,QA=Gp,XA=Ke,$A=Re,ZA=Rn,eR=em;jp.f=YA&&!QA?Object.defineProperties:function(e,t){$A(e);for(var i,r=ZA(t),n=eR(t),s=n.length,a=0;s>a;)XA.f(e,i=n[a++],r[i]);return e};var Ea,tm=ei("document","documentElement"),tR=Pc,im=Cn("keys"),Qc=function(e){return im[e]||(im[e]=tR(e))},iR=Re,rR=jp,rm=Yc,nR=Kc,sR=tm,aR=ma,Xc="prototype",$c="script",nm=Qc("IE_PROTO"),Zc=function(){},sm=function(e){return"<"+$c+">"+e+"</"+$c+">"},am=function(e){e.write(sm("")),e.close();var t=e.parentWindow.Object;return e=null,t},ya=function(){try{Ea=new ActiveXObject("htmlfile")}catch{}var e,t,i;ya=typeof document<"u"?document.domain&&Ea?am(Ea):(t=aR("iframe"),i="java"+$c+":",t.style.display="none",sR.appendChild(t),t.src=String(i),(e=t.contentWindow.document).open(),e.write(sm("document.F=Object")),e.close(),e.F):am(Ea);for(var r=rm.length;r--;)delete ya[Xc][rm[r]];return ya()};nR[nm]=!0;var kn=Object.create||function(e,t){var i;return e!==null?(Zc[Xc]=iR(e),i=new Zc,Zc[Xc]=null,i[nm]=e):i=ya(),t===void 0?i:rR.f(i,t)},oR=ce,cR=kn,lR=Ke.f,el=oR("unscopables"),tl=Array.prototype;tl[el]==null&&lR(tl,el,{configurable:!0,value:cR(null)});var Sa,Nn,va,om=function(e){tl[el][e]=!0},Dn={},uR=ie,cm=te.WeakMap,dR=uR(cm)&&/native code/.test(String(cm)),Ir=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}},hR=Ke,pR=Ir,Dt=Ee?function(e,t,i){return hR.f(e,t,pR(1,i))}:function(e,t,i){return e[t]=i,e},mR=dR,lm=te,_R=De,fR=Dt,il=ve,rl=Oc,gR=Qc,TR=Kc,um="Object already initialized",nl=lm.TypeError,ER=lm.WeakMap;if(mR||rl.state){var ft=rl.state||(rl.state=new ER);ft.get=ft.get,ft.has=ft.has,ft.set=ft.set,Sa=function(e,t){if(ft.has(e))throw nl(um);return t.facade=e,ft.set(e,t),t},Nn=function(e){return ft.get(e)||{}},va=function(e){return ft.has(e)}}else{var Ar=gR("state");TR[Ar]=!0,Sa=function(e,t){if(il(e,Ar))throw nl(um);return t.facade=e,fR(e,Ar,t),t},Nn=function(e){return il(e,Ar)?e[Ar]:{}},va=function(e){return il(e,Ar)}}var Me={set:Sa,get:Nn,has:va,enforce:function(e){return va(e)?Nn(e):Sa(e,{})},getterFor:function(e){return function(t){var i;if(!_R(t)||(i=Nn(t)).type!==e)throw nl("Incompatible receiver, "+e+" required");return i}}},wn={},sl={},dm={}.propertyIsEnumerable,hm=Object.getOwnPropertyDescriptor,yR=hm&&!dm.call({1:2},1);sl.f=yR?function(e){var t=hm(this,e);return!!t&&t.enumerable}:dm;var SR=Ee,vR=le,IR=sl,AR=Ir,RR=Rn,CR=fa,bR=ve,kR=Jp,pm=Object.getOwnPropertyDescriptor;wn.f=SR?pm:function(e,t){if(e=RR(e),t=CR(t),kR)try{return pm(e,t)}catch{}if(bR(e,t))return AR(!vR(IR.f,e,t),e[t])};var Ia={},NR={get exports(){return Ia},set exports(e){Ia=e}},al=Ee,DR=ve,mm=Function.prototype,wR=al&&Object.getOwnPropertyDescriptor,_m=DR(mm,"name"),On={PROPER:_m&&(function(){}).name==="something",CONFIGURABLE:_m&&(!al||al&&wR(mm,"name").configurable)},OR=ie,ol=Oc,PR=ee(Function.toString);OR(ol.inspectSource)||(ol.inspectSource=function(e){return PR(e)});var cl=ol.inspectSource,ll=ee,LR=Z,MR=ie,Aa=ve,ul=Ee,xR=On.CONFIGURABLE,VR=cl,UR=Me.enforce,FR=Me.get,fm=String,Ra=Object.defineProperty,BR=ll("".slice),HR=ll("".replace),jR=ll([].join),GR=ul&&!LR(function(){return Ra(function(){},"length",{value:8}).length!==8}),WR=String(String).split("String"),JR=NR.exports=function(e,t,i){BR(fm(t),0,7)==="Symbol("&&(t="["+HR(fm(t),/^Symbol\(([^)]*)\)/,"$1")+"]"),i&&i.getter&&(t="get "+t),i&&i.setter&&(t="set "+t),(!Aa(e,"name")||xR&&e.name!==t)&&(ul?Ra(e,"name",{value:t,configurable:!0}):e.name=t),GR&&i&&Aa(i,"arity")&&e.length!==i.arity&&Ra(e,"length",{value:i.arity});try{i&&Aa(i,"constructor")&&i.constructor?ul&&Ra(e,"prototype",{writable:!1}):e.prototype&&(e.prototype=void 0)}catch{}var r=UR(e);return Aa(r,"source")||(r.source=jR(WR,typeof t=="string"?t:"")),e};Function.prototype.toString=JR(function(){return MR(this)&&FR(this).source||VR(this)},"toString");var zR=ie,KR=Ke,qR=Ia,YR=wc,qe=function(e,t,i,r){r||(r={});var n=r.enumerable,s=r.name!==void 0?r.name:t;if(zR(i)&&qR(i,s,r),r.global)n?e[t]=i:YR(t,i);else{try{r.unsafe?e[t]&&(n=!0):delete e[t]}catch{}n?e[t]=i:KR.f(e,t,{value:i,enumerable:!1,configurable:!r.nonConfigurable,writable:!r.nonWritable})}return e},Pn={},QR=Zp,XR=Yc.concat("length","prototype");Pn.f=Object.getOwnPropertyNames||function(e){return QR(e,XR)};var dl={};dl.f=Object.getOwnPropertySymbols;var Mi,gm,Tm,$R=ei,ZR=Pn,eC=dl,tC=Re,iC=ee([].concat),rC=$R("Reflect","ownKeys")||function(e){var t=ZR.f(tC(e)),i=eC.f;return i?iC(t,i(e)):t},Em=ve,nC=rC,sC=wn,aC=Ke,ym=function(e,t,i){for(var r=nC(t),n=aC.f,s=sC.f,a=0;a<r.length;a++){var c=r[a];Em(e,c)||i&&Em(i,c)||n(e,c,s(t,c))}},oC=Z,cC=ie,lC=/#|\.prototype\./,Ln=function(e,t){var i=dC[uC(e)];return i==pC||i!=hC&&(cC(t)?oC(t):!!t)},uC=Ln.normalize=function(e){return String(e).replace(lC,".").toLowerCase()},dC=Ln.data={},hC=Ln.NATIVE="N",pC=Ln.POLYFILL="P",hl=Ln,pl=te,mC=wn.f,_C=Dt,fC=qe,gC=wc,TC=ym,EC=hl,pe=function(e,t){var i,r,n,s,a,c=e.target,o=e.global,l=e.stat;if(i=o?pl:l?pl[c]||gC(c,{}):(pl[c]||{}).prototype)for(r in t){if(s=t[r],n=e.dontCallGetSet?(a=mC(i,r))&&a.value:i[r],!EC(o?r:c+(l?".":"#")+r,e.forced)&&n!==void 0){if(typeof s==typeof n)continue;TC(s,n)}(e.sham||n&&n.sham)&&_C(s,"sham",!0),fC(i,r,s,e)}},yC=!Z(function(){function e(){}return e.prototype.constructor=null,Object.getPrototypeOf(new e)!==e.prototype}),SC=ve,vC=ie,IC=nt,AC=yC,Sm=Qc("IE_PROTO"),ml=Object,RC=ml.prototype,Ca=AC?ml.getPrototypeOf:function(e){var t=IC(e);if(SC(t,Sm))return t[Sm];var i=t.constructor;return vC(i)&&t instanceof i?i.prototype:t instanceof ml?RC:null},CC=Z,bC=ie,kC=De,vm=Ca,NC=qe,_l=ce("iterator"),Im=!1;[].keys&&("next"in(Tm=[].keys())?(gm=vm(vm(Tm)))!==Object.prototype&&(Mi=gm):Im=!0);var DC=!kC(Mi)||CC(function(){var e={};return Mi[_l].call(e)!==e});DC&&(Mi={}),bC(Mi[_l])||NC(Mi,_l,function(){return this});var fl={IteratorPrototype:Mi,BUGGY_SAFARI_ITERATORS:Im},wC=Ke.f,OC=ve,Am=ce("toStringTag"),Rr=function(e,t,i){e&&!i&&(e=e.prototype),e&&!OC(e,Am)&&wC(e,Am,{configurable:!0,value:t})},PC=fl.IteratorPrototype,LC=kn,MC=Ir,xC=Rr,VC=Dn,UC=function(){return this},Rm=function(e,t,i,r){var n=t+" Iterator";return e.prototype=LC(PC,{next:MC(+!r,i)}),xC(e,n,!1),VC[n]=UC,e},FC=ee,BC=st,HC=ie,jC=String,GC=TypeError,WC=function(e,t,i){try{return FC(BC(Object.getOwnPropertyDescriptor(e,t)[i]))}catch{}},JC=Re,zC=function(e){if(typeof e=="object"||HC(e))return e;throw GC("Can't set "+jC(e)+" as a prototype")},Cr=Object.setPrototypeOf||("__proto__"in{}?function(){var e,t=!1,i={};try{(e=WC(Object.prototype,"__proto__","set"))(i,[]),t=i instanceof Array}catch{}return function(r,n){return JC(r),zC(n),t?e(r,n):r.__proto__=n,r}}():void 0),KC=pe,qC=le,YC=ie,QC=Rm,Cm=Ca,bm=Cr,XC=Rr,$C=Dt,gl=qe,ZC=Dn,eb=On.PROPER,tb=On.CONFIGURABLE,km=fl.IteratorPrototype,ba=fl.BUGGY_SAFARI_ITERATORS,Mn=ce("iterator"),Nm="keys",xn="values",Dm="entries",ib=function(){return this},wm=function(e,t,i,r,n,s,a){QC(i,t,r);var c,o,l,d=function(y){if(y===n&&T)return T;if(!ba&&y in m)return m[y];switch(y){case Nm:case xn:case Dm:return function(){return new i(this,y)}}return function(){return new i(this)}},u=t+" Iterator",p=!1,m=e.prototype,f=m[Mn]||m["@@iterator"]||n&&m[n],T=!ba&&f||d(n),S=t=="Array"&&m.entries||f;if(S&&(c=Cm(S.call(new e)))!==Object.prototype&&c.next&&(Cm(c)!==km&&(bm?bm(c,km):YC(c[Mn])||gl(c,Mn,ib)),XC(c,u,!0)),eb&&n==xn&&f&&f.name!==xn&&(tb?$C(m,"name",xn):(p=!0,T=function(){return qC(f,this)})),n)if(o={values:d(xn),keys:s?T:d(Nm),entries:d(Dm)},a)for(l in o)(ba||p||!(l in m))&&gl(m,l,o[l]);else KC({target:t,proto:!0,forced:ba||p},o);return m[Mn]!==T&&gl(m,Mn,T,{name:n}),ZC[t]=T,o},Om=function(e,t){return{value:e,done:t}},rb=Rn,Tl=om,Pm=Dn,Lm=Me,nb=Ke.f,sb=wm,Mm=Om,ab=Ee,xm="Array Iterator",ob=Lm.set,cb=Lm.getterFor(xm),lb=sb(Array,"Array",function(e,t){ob(this,{type:xm,target:rb(e),index:0,kind:t})},function(){var e=cb(this),t=e.target,i=e.kind,r=e.index++;return!t||r>=t.length?(e.target=void 0,Mm(void 0,!0)):Mm(i=="keys"?r:i=="values"?t[r]:[r,t[r]],!1)},"values"),Vm=Pm.Arguments=Pm.Array;if(Tl("keys"),Tl("values"),Tl("entries"),ab&&Vm.name!=="values")try{nb(Vm,"name",{value:"values"})}catch{}var Um={CSSRuleList:0,CSSStyleDeclaration:0,CSSValueList:0,ClientRectList:0,DOMRectList:0,DOMStringList:0,DOMTokenList:1,DataTransferItemList:0,FileList:0,HTMLAllCollection:0,HTMLCollection:0,HTMLFormElement:0,HTMLSelectElement:0,MediaList:0,MimeTypeArray:0,NamedNodeMap:0,NodeList:1,PaintRequestList:0,Plugin:0,PluginArray:0,SVGLengthList:0,SVGNumberList:0,SVGPathSegList:0,SVGPointList:0,SVGStringList:0,SVGTransformList:0,SourceBufferList:0,StyleSheetList:0,TextTrackCueList:0,TextTrackList:0,TouchList:0},El=ma("span").classList,Fm=El&&El.constructor&&El.constructor.prototype,Bm=Fm===Object.prototype?void 0:Fm,Hm=te,jm=Um,ub=Bm,Vn=lb,yl=Dt,Gm=ce,Sl=Gm("iterator"),Wm=Gm("toStringTag"),vl=Vn.values,Jm=function(e,t){if(e){if(e[Sl]!==vl)try{yl(e,Sl,vl)}catch{e[Sl]=vl}if(e[Wm]||yl(e,Wm,t),jm[t]){for(var i in Vn)if(e[i]!==Vn[i])try{yl(e,i,Vn[i])}catch{e[i]=Vn[i]}}}};for(var Il in jm)Jm(Hm[Il]&&Hm[Il].prototype,Il);Jm(ub,"DOMTokenList");var Un=typeof process<"u"&&Pi(process)=="process",zm=Ia,db=Ke,xi=function(e,t,i){return i.get&&zm(i.get,t,{getter:!0}),i.set&&zm(i.set,t,{setter:!0}),db.f(e,t,i)},hb=ei,pb=xi,mb=Ee,Km=ce("species"),ka=function(e){var t=hb(e);mb&&t&&!t[Km]&&pb(t,Km,{configurable:!0,get:function(){return this}})},_b=ti,fb=TypeError,Fn=function(e,t){if(_b(t,e))return e;throw fb("Incorrect invocation")},qm={};qm[ce("toStringTag")]="z";var gb=String(qm)==="[object z]",Tb=ie,Na=Pi,Eb=ce("toStringTag"),yb=Object,Sb=Na(function(){return arguments}())=="Arguments",ri=gb?Na:function(e){var t,i,r;return e===void 0?"Undefined":e===null?"Null":typeof(i=function(n,s){try{return n[s]}catch{}}(t=yb(e),Eb))=="string"?i:Sb?Na(t):(r=Na(t))=="Object"&&Tb(t.callee)?"Arguments":r},vb=ee,Ib=Z,Ym=ie,Ab=ri,Rb=cl,Qm=function(){},Cb=[],Xm=ei("Reflect","construct"),Al=/^\s*(?:class|function)\b/,bb=vb(Al.exec),kb=!Al.exec(Qm),Bn=function(e){if(!Ym(e))return!1;try{return Xm(Qm,Cb,e),!0}catch{return!1}},$m=function(e){if(!Ym(e))return!1;switch(Ab(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return kb||!!bb(Al,Rb(e))}catch{return!0}};$m.sham=!0;var Hn,br,Zm,Rl,Cl=!Xm||Ib(function(){var e;return Bn(Bn.call)||!Bn(Object)||!Bn(function(){e=!0})||e})?$m:Bn,Nb=Cl,Db=vr,wb=TypeError,e_=function(e){if(Nb(e))return e;throw wb(Db(e)+" is not a constructor")},t_=Re,Ob=e_,Pb=Er,Lb=ce("species"),bl=function(e,t){var i,r=t_(e).constructor;return r===void 0||Pb(i=t_(r)[Lb])?t:Ob(i)},Mb=la,i_=Function.prototype,r_=i_.apply,n_=i_.call,s_=typeof Reflect=="object"&&Reflect.apply||(Mb?n_.bind(r_):function(){return n_.apply(r_,arguments)}),xb=Pi,Vb=ee,jn=function(e){if(xb(e)==="Function")return Vb(e)},Ub=st,Fb=la,Bb=jn(jn.bind),ni=function(e,t){return Ub(e),t===void 0?e:Fb?Bb(e,t):function(){return e.apply(t,arguments)}},Hb=ee([].slice),jb=TypeError,kl=function(e,t){if(e<t)throw jb("Not enough arguments");return e},a_=/(?:ipad|iphone|ipod).*applewebkit/i.test(Zt),Be=te,Gb=s_,Wb=ni,o_=ie,Jb=ve,c_=Z,l_=tm,zb=Hb,u_=ma,Kb=kl,qb=a_,Yb=Un,Nl=Be.setImmediate,d_=Be.clearImmediate,Qb=Be.process,Dl=Be.Dispatch,Xb=Be.Function,h_=Be.MessageChannel,$b=Be.String,wl=0,Gn={},p_="onreadystatechange";c_(function(){Hn=Be.location});var Ol=function(e){if(Jb(Gn,e)){var t=Gn[e];delete Gn[e],t()}},Pl=function(e){return function(){Ol(e)}},m_=function(e){Ol(e.data)},__=function(e){Be.postMessage($b(e),Hn.protocol+"//"+Hn.host)};Nl&&d_||(Nl=function(e){Kb(arguments.length,1);var t=o_(e)?e:Xb(e),i=zb(arguments,1);return Gn[++wl]=function(){Gb(t,void 0,i)},br(wl),wl},d_=function(e){delete Gn[e]},Yb?br=function(e){Qb.nextTick(Pl(e))}:Dl&&Dl.now?br=function(e){Dl.now(Pl(e))}:h_&&!qb?(Rl=(Zm=new h_).port2,Zm.port1.onmessage=m_,br=Wb(Rl.postMessage,Rl)):Be.addEventListener&&o_(Be.postMessage)&&!Be.importScripts&&Hn&&Hn.protocol!=="file:"&&!c_(__)?(br=__,Be.addEventListener("message",m_,!1)):br=p_ in u_("script")?function(e){l_.appendChild(u_("script"))[p_]=function(){l_.removeChild(this),Ol(e)}}:function(e){setTimeout(Pl(e),0)});var f_={set:Nl},g_=function(){this.head=null,this.tail=null};g_.prototype={add:function(e){var t={item:e,next:null},i=this.tail;i?i.next=t:this.head=t,this.tail=t},get:function(){var e=this.head;if(e)return(this.head=e.next)===null&&(this.tail=null),e.item}};var kr,Ll,Ml,xl,T_,E_=g_,Zb=/ipad|iphone|ipod/i.test(Zt)&&typeof Pebble<"u",ek=/web0s(?!.*chrome)/i.test(Zt),Vi=te,y_=ni,tk=wn.f,Vl=f_.set,ik=E_,rk=a_,nk=Zb,sk=ek,Ul=Un,S_=Vi.MutationObserver||Vi.WebKitMutationObserver,v_=Vi.document,I_=Vi.process,Da=Vi.Promise,A_=tk(Vi,"queueMicrotask"),Fl=A_&&A_.value;if(!Fl){var wa=new ik,Oa=function(){var e,t;for(Ul&&(e=I_.domain)&&e.exit();t=wa.get();)try{t()}catch(i){throw wa.head&&kr(),i}e&&e.enter()};rk||Ul||sk||!S_||!v_?!nk&&Da&&Da.resolve?((xl=Da.resolve(void 0)).constructor=Da,T_=y_(xl.then,xl),kr=function(){T_(Oa)}):Ul?kr=function(){I_.nextTick(Oa)}:(Vl=y_(Vl,Vi),kr=function(){Vl(Oa)}):(Ll=!0,Ml=v_.createTextNode(""),new S_(Oa).observe(Ml,{characterData:!0}),kr=function(){Ml.data=Ll=!Ll}),Fl=function(e){wa.head||kr(),wa.add(e)}}var ak=Fl,Bl=function(e){try{return{error:!1,value:e()}}catch(t){return{error:!0,value:t}}},Wn=te.Promise,R_=typeof Deno=="object"&&Deno&&typeof Deno.version=="object",ok=!R_&&!Un&&typeof window=="object"&&typeof document=="object",ck=te,Jn=Wn,lk=ie,uk=hl,dk=cl,hk=ce,pk=ok,mk=R_,Hl=yr;Jn&&Jn.prototype;var _k=hk("species"),C_=!1,b_=lk(ck.PromiseRejectionEvent),fk=uk("Promise",function(){var e=dk(Jn),t=e!==String(Jn);if(!t&&Hl===66)return!0;if(!Hl||Hl<51||!/native code/.test(e)){var i=new Jn(function(n){n(1)}),r=function(n){n(function(){},function(){})};if((i.constructor={})[_k]=r,!(C_=i.then(function(){})instanceof r))return!0}return!t&&(pk||mk)&&!b_}),Ui={CONSTRUCTOR:fk,REJECTION_EVENT:b_,SUBCLASSING:C_},Nr={},k_=st,gk=TypeError,Tk=function(e){var t,i;this.promise=new e(function(r,n){if(t!==void 0||i!==void 0)throw gk("Bad Promise constructor");t=r,i=n}),this.resolve=k_(t),this.reject=k_(i)};Nr.f=function(e){return new Tk(e)};var jl,N_,D_,Ek=pe,Pa=Un,si=te,Dr=le,w_=qe,O_=Cr,yk=Rr,Sk=ka,vk=st,La=ie,Ik=De,Ak=Fn,Rk=bl,P_=f_.set,Gl=ak,Ck=function(e,t){try{arguments.length==1?console.error(e):console.error(e,t)}catch{}},bk=Bl,kk=E_,L_=Me,Ma=Wn,M_=Nr,xa="Promise",x_=Ui.CONSTRUCTOR,Nk=Ui.REJECTION_EVENT,Dk=Ui.SUBCLASSING,Wl=L_.getterFor(xa),wk=L_.set,wr=Ma&&Ma.prototype,Or=Ma,Va=wr,V_=si.TypeError,Jl=si.document,zl=si.process,Kl=M_.f,Ok=Kl,Pk=!!(Jl&&Jl.createEvent&&si.dispatchEvent),U_="unhandledrejection",F_=function(e){var t;return!(!Ik(e)||!La(t=e.then))&&t},B_=function(e,t){var i,r,n,s=t.value,a=t.state==1,c=a?e.ok:e.fail,o=e.resolve,l=e.reject,d=e.domain;try{c?(a||(t.rejection===2&&Mk(t),t.rejection=1),c===!0?i=s:(d&&d.enter(),i=c(s),d&&(d.exit(),n=!0)),i===e.promise?l(V_("Promise-chain cycle")):(r=F_(i))?Dr(r,i,o,l):o(i)):l(s)}catch(u){d&&!n&&d.exit(),l(u)}},H_=function(e,t){e.notified||(e.notified=!0,Gl(function(){for(var i,r=e.reactions;i=r.get();)B_(i,e);e.notified=!1,t&&!e.rejection&&Lk(e)}))},j_=function(e,t,i){var r,n;Pk?((r=Jl.createEvent("Event")).promise=t,r.reason=i,r.initEvent(e,!1,!0),si.dispatchEvent(r)):r={promise:t,reason:i},!Nk&&(n=si["on"+e])?n(r):e===U_&&Ck("Unhandled promise rejection",i)},Lk=function(e){Dr(P_,si,function(){var t,i=e.facade,r=e.value;if(G_(e)&&(t=bk(function(){Pa?zl.emit("unhandledRejection",r,i):j_(U_,i,r)}),e.rejection=Pa||G_(e)?2:1,t.error))throw t.value})},G_=function(e){return e.rejection!==1&&!e.parent},Mk=function(e){Dr(P_,si,function(){var t=e.facade;Pa?zl.emit("rejectionHandled",t):j_("rejectionhandled",t,e.value)})},Pr=function(e,t,i){return function(r){e(t,r,i)}},Lr=function(e,t,i){e.done||(e.done=!0,i&&(e=i),e.value=t,e.state=2,H_(e,!0))},ql=function(e,t,i){if(!e.done){e.done=!0,i&&(e=i);try{if(e.facade===t)throw V_("Promise can't be resolved itself");var r=F_(t);r?Gl(function(){var n={done:!1};try{Dr(r,t,Pr(ql,n,e),Pr(Lr,n,e))}catch(s){Lr(n,s,e)}}):(e.value=t,e.state=1,H_(e,!1))}catch(n){Lr({done:!1},n,e)}}};if(x_&&(Va=(Or=function(e){Ak(this,Va),vk(e),Dr(jl,this);var t=Wl(this);try{e(Pr(ql,t),Pr(Lr,t))}catch(i){Lr(t,i)}}).prototype,(jl=function(e){wk(this,{type:xa,done:!1,notified:!1,parent:!1,reactions:new kk,rejection:!1,state:0,value:void 0})}).prototype=w_(Va,"then",function(e,t){var i=Wl(this),r=Kl(Rk(this,Or));return i.parent=!0,r.ok=!La(e)||e,r.fail=La(t)&&t,r.domain=Pa?zl.domain:void 0,i.state==0?i.reactions.add(r):Gl(function(){B_(r,i)}),r.promise}),N_=function(){var e=new jl,t=Wl(e);this.promise=e,this.resolve=Pr(ql,t),this.reject=Pr(Lr,t)},M_.f=Kl=function(e){return e===Or||e===void 0?new N_(e):Ok(e)},La(Ma)&&wr!==Object.prototype)){D_=wr.then,Dk||w_(wr,"then",function(e,t){var i=this;return new Or(function(r,n){Dr(D_,i,r,n)}).then(e,t)},{unsafe:!0});try{delete wr.constructor}catch{}O_&&O_(wr,Va)}Ek({global:!0,constructor:!0,wrap:!0,forced:x_},{Promise:Or}),yk(Or,xa,!1),Sk(xa);var xk=Dn,Vk=ce("iterator"),Uk=Array.prototype,Yl=function(e){return e!==void 0&&(xk.Array===e||Uk[Vk]===e)},Fk=ri,W_=bn,Bk=Er,Hk=Dn,jk=ce("iterator"),zn=function(e){if(!Bk(e))return W_(e,jk)||W_(e,"@@iterator")||Hk[Fk(e)]},Gk=le,Wk=st,Jk=Re,zk=vr,Kk=zn,qk=TypeError,Ua=function(e,t){var i=arguments.length<2?Kk(e):t;if(Wk(i))return Jk(Gk(i,e));throw qk(zk(e)+" is not iterable")},Yk=le,J_=Re,Qk=bn,z_=function(e,t,i){var r,n;J_(e);try{if(!(r=Qk(e,"return"))){if(t==="throw")throw i;return i}r=Yk(r,e)}catch(s){n=!0,r=s}if(t==="throw")throw i;if(n)throw r;return J_(r),i},Xk=ni,$k=le,Zk=Re,e0=vr,t0=Yl,i0=_t,K_=ti,r0=Ua,n0=zn,q_=z_,s0=TypeError,Fa=function(e,t){this.stopped=e,this.result=t},Y_=Fa.prototype,Q_=function(e,t,i){var r,n,s,a,c,o,l,d=i&&i.that,u=!(!i||!i.AS_ENTRIES),p=!(!i||!i.IS_RECORD),m=!(!i||!i.IS_ITERATOR),f=!(!i||!i.INTERRUPTED),T=Xk(t,d),S=function(E){return r&&q_(r,"normal",E),new Fa(!0,E)},y=function(E){return u?(Zk(E),f?T(E[0],E[1],S):T(E[0],E[1])):f?T(E,S):T(E)};if(p)r=e.iterator;else if(m)r=e;else{if(!(n=n0(e)))throw s0(e0(e)+" is not iterable");if(t0(n)){for(s=0,a=i0(e);a>s;s++)if((c=y(e[s]))&&K_(Y_,c))return c;return new Fa(!1)}r=r0(e,n)}for(o=p?e.next:r.next;!(l=$k(o,r)).done;){try{c=y(l.value)}catch(E){q_(r,"throw",E)}if(typeof c=="object"&&c&&K_(Y_,c))return c}return new Fa(!1)},X_=ce("iterator"),$_=!1;try{var a0=0,Z_={next:function(){return{done:!!a0++}},return:function(){$_=!0}};Z_[X_]=function(){return this},Array.from(Z_,function(){throw 2})}catch{}var ef=function(e,t){if(!t&&!$_)return!1;var i=!1;try{var r={};r[X_]=function(){return{next:function(){return{done:i=!0}}}},e(r)}catch{}return i},o0=Wn,tf=Ui.CONSTRUCTOR||!ef(function(e){o0.all(e).then(void 0,function(){})}),c0=le,l0=st,u0=Nr,d0=Bl,h0=Q_;pe({target:"Promise",stat:!0,forced:tf},{all:function(e){var t=this,i=u0.f(t),r=i.resolve,n=i.reject,s=d0(function(){var a=l0(t.resolve),c=[],o=0,l=1;h0(e,function(d){var u=o++,p=!1;l++,c0(a,t,d).then(function(m){p||(p=!0,c[u]=m,--l||r(c))},n)}),--l||r(c)});return s.error&&n(s.value),i.promise}});var p0=pe,m0=Ui.CONSTRUCTOR,Ql=Wn,_0=ei,f0=ie,g0=qe,rf=Ql&&Ql.prototype;if(p0({target:"Promise",proto:!0,forced:m0,real:!0},{catch:function(e){return this.then(void 0,e)}}),f0(Ql)){var nf=_0("Promise").prototype.catch;rf.catch!==nf&&g0(rf,"catch",nf,{unsafe:!0})}var T0=le,E0=st,y0=Nr,S0=Bl,v0=Q_;pe({target:"Promise",stat:!0,forced:tf},{race:function(e){var t=this,i=y0.f(t),r=i.reject,n=S0(function(){var s=E0(t.resolve);v0(e,function(a){T0(s,t,a).then(i.resolve,r)})});return n.error&&r(n.value),i.promise}});var I0=le,A0=Nr;pe({target:"Promise",stat:!0,forced:Ui.CONSTRUCTOR},{reject:function(e){var t=A0.f(this);return I0(t.reject,void 0,e),t.promise}});var R0=Re,C0=De,b0=Nr,sf=function(e,t){if(R0(e),C0(t)&&t.constructor===e)return t;var i=b0.f(e);return(0,i.resolve)(t),i.promise},k0=pe,N0=Ui.CONSTRUCTOR,D0=sf;ei("Promise"),k0({target:"Promise",stat:!0,forced:N0},{resolve:function(e){return D0(this,e)}});var w0=ie,O0=De,af=Cr,of=function(e,t,i){var r,n;return af&&w0(r=t.constructor)&&r!==i&&O0(n=r.prototype)&&n!==i.prototype&&af(e,n),e},P0=De,L0=Pi,M0=ce("match"),cf=function(e){var t;return P0(e)&&((t=e[M0])!==void 0?!!t:L0(e)=="RegExp")},x0=ri,V0=String,He=function(e){if(x0(e)==="Symbol")throw TypeError("Cannot convert a Symbol value to a string");return V0(e)},U0=Re,lf=function(){var e=U0(this),t="";return e.hasIndices&&(t+="d"),e.global&&(t+="g"),e.ignoreCase&&(t+="i"),e.multiline&&(t+="m"),e.dotAll&&(t+="s"),e.unicode&&(t+="u"),e.unicodeSets&&(t+="v"),e.sticky&&(t+="y"),t},F0=le,B0=ve,H0=ti,j0=lf,uf=RegExp.prototype,df=function(e){var t=e.flags;return t!==void 0||"flags"in uf||B0(e,"flags")||!H0(uf,e)?t:F0(j0,e)},Xl=Z,$l=te.RegExp,Zl=Xl(function(){var e=$l("a","y");return e.lastIndex=2,e.exec("abcd")!=null}),G0=Zl||Xl(function(){return!$l("a","y").sticky}),W0=Zl||Xl(function(){var e=$l("^r","gy");return e.lastIndex=2,e.exec("str")!=null}),hf={BROKEN_CARET:W0,MISSED_STICKY:G0,UNSUPPORTED_Y:Zl},J0=Ke.f,z0=Z,K0=te.RegExp,pf=z0(function(){var e=K0(".","s");return!(e.dotAll&&e.exec(`
2
+ `)&&e.flags==="s")}),q0=Z,Y0=te.RegExp,mf=q0(function(){var e=Y0("(?<a>b)","g");return e.exec("b").groups.a!=="b"||"b".replace(e,"$<a>c")!=="bc"}),Q0=Ee,eu=te,Kn=ee,X0=hl,$0=of,Z0=Dt,eN=Pn.f,_f=ti,tN=cf,ff=He,iN=df,gf=hf,rN=function(e,t,i){i in e||J0(e,i,{configurable:!0,get:function(){return t[i]},set:function(r){t[i]=r}})},nN=qe,sN=Z,aN=ve,oN=Me.enforce,cN=ka,Tf=pf,Ef=mf,lN=ce("match"),ai=eu.RegExp,Mr=ai.prototype,uN=eu.SyntaxError,dN=Kn(Mr.exec),Ba=Kn("".charAt),yf=Kn("".replace),Sf=Kn("".indexOf),hN=Kn("".slice),pN=/^\?<[^\s\d!#%&*+<=>@^][^\s!#%&*+<=>@^]*>/,Fi=/a/g,tu=/a/g,mN=new ai(Fi)!==Fi,vf=gf.MISSED_STICKY,_N=gf.UNSUPPORTED_Y,fN=Q0&&(!mN||vf||Tf||Ef||sN(function(){return tu[lN]=!1,ai(Fi)!=Fi||ai(tu)==tu||ai(Fi,"i")!="/a/i"}));if(X0("RegExp",fN)){for(var Bi=function(e,t){var i,r,n,s,a,c,o=_f(Mr,this),l=tN(e),d=t===void 0,u=[],p=e;if(!o&&l&&d&&e.constructor===Bi)return e;if((l||_f(Mr,e))&&(e=e.source,d&&(t=iN(p))),e=e===void 0?"":ff(e),t=t===void 0?"":ff(t),p=e,Tf&&"dotAll"in Fi&&(r=!!t&&Sf(t,"s")>-1)&&(t=yf(t,/s/g,"")),i=t,vf&&"sticky"in Fi&&(n=!!t&&Sf(t,"y")>-1)&&_N&&(t=yf(t,/y/g,"")),Ef&&(s=function(m){for(var f,T=m.length,S=0,y="",E=[],D={},P=!1,Q=!1,q=0,U="";S<=T;S++){if((f=Ba(m,S))==="\\")f+=Ba(m,++S);else if(f==="]")P=!1;else if(!P)switch(!0){case f==="[":P=!0;break;case f==="(":dN(pN,hN(m,S+1))&&(S+=2,Q=!0),y+=f,q++;continue;case(f===">"&&Q):if(U===""||aN(D,U))throw new uN("Invalid capture group name");D[U]=!0,E[E.length]=[U,q],Q=!1,U="";continue}Q?U+=f:y+=f}return[y,E]}(e),e=s[0],u=s[1]),a=$0(ai(e,t),o?this:Mr,Bi),(r||n||u.length)&&(c=oN(a),r&&(c.dotAll=!0,c.raw=Bi(function(m){for(var f,T=m.length,S=0,y="",E=!1;S<=T;S++)(f=Ba(m,S))!=="\\"?E||f!=="."?(f==="["?E=!0:f==="]"&&(E=!1),y+=f):y+="[\\s\\S]":y+=f+Ba(m,++S);return y}(e),i)),n&&(c.sticky=!0),u.length&&(c.groups=u)),e!==p)try{Z0(a,"source",p===""?"(?:)":p)}catch{}return a},If=eN(ai),Af=0;If.length>Af;)rN(Bi,ai,If[Af++]);Mr.constructor=Bi,Bi.prototype=Mr,nN(eu,"RegExp",Bi,{constructor:!0})}cN("RegExp");var xr=le,Ha=ee,gN=He,TN=lf,EN=hf,yN=kn,SN=Me.get,vN=pf,IN=mf,AN=Cn("native-string-replace",String.prototype.replace),ja=RegExp.prototype.exec,iu=ja,RN=Ha("".charAt),CN=Ha("".indexOf),bN=Ha("".replace),ru=Ha("".slice),nu=function(){var e=/a/,t=/b*/g;return xr(ja,e,"a"),xr(ja,t,"a"),e.lastIndex!==0||t.lastIndex!==0}(),Rf=EN.BROKEN_CARET,su=/()??/.exec("")[1]!==void 0;(nu||su||Rf||vN||IN)&&(iu=function(e){var t,i,r,n,s,a,c,o=this,l=SN(o),d=gN(e),u=l.raw;if(u)return u.lastIndex=o.lastIndex,t=xr(iu,u,d),o.lastIndex=u.lastIndex,t;var p=l.groups,m=Rf&&o.sticky,f=xr(TN,o),T=o.source,S=0,y=d;if(m&&(f=bN(f,"y",""),CN(f,"g")===-1&&(f+="g"),y=ru(d,o.lastIndex),o.lastIndex>0&&(!o.multiline||o.multiline&&RN(d,o.lastIndex-1)!==`
3
+ `)&&(T="(?: "+T+")",y=" "+y,S++),i=new RegExp("^(?:"+T+")",f)),su&&(i=new RegExp("^"+T+"$(?!\\s)",f)),nu&&(r=o.lastIndex),n=xr(ja,m?i:o,y),m?n?(n.input=ru(n.input,S),n[0]=ru(n[0],S),n.index=o.lastIndex,o.lastIndex+=n[0].length):o.lastIndex=0:nu&&n&&(o.lastIndex=o.global?n.index+n[0].length:r),su&&n&&n.length>1&&xr(AN,n[0],i,function(){for(s=1;s<arguments.length-2;s++)arguments[s]===void 0&&(n[s]=void 0)}),n&&p)for(n.groups=a=yN(null),s=0;s<p.length;s++)a[(c=p[s])[0]]=n[c[1]];return n});var Ga=iu;pe({target:"RegExp",proto:!0,forced:/./.exec!==Ga},{exec:Ga});var kN=Pi,Cf=Array.isArray||function(e){return kN(e)=="Array"},bf=Cf,NN=Cl,DN=De,wN=ce("species"),kf=Array,ON=function(e){var t;return bf(e)&&(t=e.constructor,(NN(t)&&(t===kf||bf(t.prototype))||DN(t)&&(t=t[wN])===null)&&(t=void 0)),t===void 0?kf:t},PN=ni,LN=ua,MN=nt,xN=_t,VN=function(e,t){return new(ON(e))(t===0?0:t)},Nf=ee([].push),UN=function(e){var t=e==1,i=e==2,r=e==3,n=e==4,s=e==6,a=e==7,c=e==5||s;return function(o,l,d,u){for(var p,m,f=MN(o),T=LN(f),S=PN(l,d),y=xN(T),E=0,D=u||VN,P=t?D(o,y):i||a?D(o,0):void 0;y>E;E++)if((c||E in T)&&(m=S(p=T[E],E,f),e))if(t)P[E]=m;else if(m)switch(e){case 3:return!0;case 5:return p;case 6:return E;case 2:Nf(P,p)}else switch(e){case 4:return!1;case 7:Nf(P,p)}return s?-1:r||n?n:P}},Df={forEach:UN(0)},FN=Z,au=function(e,t){var i=[][e];return!!i&&FN(function(){i.call(null,t||function(){return 1},1)})},BN=Df.forEach,HN=au("forEach")?[].forEach:function(e){return BN(this,e,arguments.length>1?arguments[1]:void 0)},wf=te,Of=Um,jN=Bm,ou=HN,GN=Dt,Pf=function(e){if(e&&e.forEach!==ou)try{GN(e,"forEach",ou)}catch{e.forEach=ou}};for(var cu in Of)Of[cu]&&Pf(wf[cu]&&wf[cu].prototype);Pf(jN);var WN=st,JN=nt,zN=ua,KN=_t,qN=TypeError,YN=function(e){return function(t,i,r,n){WN(i);var s=JN(t),a=zN(s),c=KN(s),o=e?c-1:0,l=e?-1:1;if(r<2)for(;;){if(o in a){n=a[o],o+=l;break}if(o+=l,e?o<0:c<=o)throw qN("Reduce of empty array with no initial value")}for(;e?o>=0:c>o;o+=l)o in a&&(n=i(n,a[o],o,s));return n}},QN={left:YN(!1)}.left;pe({target:"Array",proto:!0,forced:!Un&&yr>79&&yr<83||!au("reduce")},{reduce:function(e){var t=arguments.length;return QN(this,e,t,t>1?arguments[1]:void 0)}});var Lf=jn,Mf=qe,XN=Ga,xf=Z,Vf=ce,$N=Vf("species"),Uf=RegExp.prototype,lu=ee,ZN=ii,eD=He,tD=Xt,iD=lu("".charAt),Ff=lu("".charCodeAt),rD=lu("".slice),Bf=function(e){return function(t,i){var r,n,s=eD(tD(t)),a=ZN(i),c=s.length;return a<0||a>=c?e?"":void 0:(r=Ff(s,a))<55296||r>56319||a+1===c||(n=Ff(s,a+1))<56320||n>57343?e?iD(s,a):r:e?rD(s,a,a+2):n-56320+(r-55296<<10)+65536}},uu={codeAt:Bf(!1),charAt:Bf(!0)},nD=uu.charAt,du=ee,sD=nt,aD=Math.floor,hu=du("".charAt),oD=du("".replace),pu=du("".slice),cD=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,lD=/\$([$&'`]|\d{1,2})/g,Hf=function(e,t,i,r,n,s){var a=i+e.length,c=r.length,o=lD;return n!==void 0&&(n=sD(n),o=cD),oD(s,o,function(l,d){var u;switch(hu(d,0)){case"$":return"$";case"&":return e;case"`":return pu(t,0,i);case"'":return pu(t,a);case"<":u=n[pu(d,1,-1)];break;default:var p=+d;if(p===0)return l;if(p>c){var m=aD(p/10);return m===0?l:m<=c?r[m-1]===void 0?hu(d,1):r[m-1]+hu(d,1):l}u=r[p-1]}return u===void 0?"":u})},jf=le,uD=Re,dD=ie,hD=Pi,pD=Ga,mD=TypeError,_D=s_,Gf=le,Wa=ee,fD=function(e,t,i,r){var n=Vf(e),s=!xf(function(){var l={};return l[n]=function(){return 7},""[e](l)!=7}),a=s&&!xf(function(){var l=!1,d=/a/;return e==="split"&&((d={}).constructor={},d.constructor[$N]=function(){return d},d.flags="",d[n]=/./[n]),d.exec=function(){return l=!0,null},d[n](""),!l});if(!s||!a||i){var c=Lf(/./[n]),o=t(n,""[e],function(l,d,u,p,m){var f=Lf(l),T=d.exec;return T===XN||T===Uf.exec?s&&!m?{done:!0,value:c(d,u,p)}:{done:!0,value:f(u,d,p)}:{done:!1}});Mf(String.prototype,e,o[0]),Mf(Uf,n,o[1])}},gD=Z,TD=Re,ED=ie,yD=Er,SD=ii,vD=Li,Vr=He,ID=Xt,AD=function(e,t,i){return t+(i?nD(e,t).length:1)},RD=bn,CD=Hf,bD=function(e,t){var i=e.exec;if(dD(i)){var r=jf(i,e,t);return r!==null&&uD(r),r}if(hD(e)==="RegExp")return jf(pD,e,t);throw mD("RegExp#exec called on incompatible receiver")},mu=ce("replace"),kD=Math.max,ND=Math.min,DD=Wa([].concat),_u=Wa([].push),Wf=Wa("".indexOf),Jf=Wa("".slice),wD=function(e){return e===void 0?e:String(e)},OD="a".replace(/./,"$0")==="$0",zf=!!/./[mu]&&/./[mu]("a","$0")==="",PD=!gD(function(){var e=/./;return e.exec=function(){var t=[];return t.groups={a:"7"},t},"".replace(e,"$<a>")!=="7"});fD("replace",function(e,t,i){var r=zf?"$":"$0";return[function(n,s){var a=ID(this),c=yD(n)?void 0:RD(n,mu);return c?Gf(c,n,a,s):Gf(t,Vr(a),n,s)},function(n,s){var a=TD(this),c=Vr(n);if(typeof s=="string"&&Wf(s,r)===-1&&Wf(s,"$<")===-1){var o=i(t,a,c,s);if(o.done)return o.value}var l=ED(s);l||(s=Vr(s));var d=a.global;if(d){var u=a.unicode;a.lastIndex=0}for(var p=[];;){var m=bD(a,c);if(m===null||(_u(p,m),!d))break;Vr(m[0])===""&&(a.lastIndex=AD(c,vD(a.lastIndex),u))}for(var f="",T=0,S=0;S<p.length;S++){for(var y=Vr((m=p[S])[0]),E=kD(ND(SD(m.index),c.length),0),D=[],P=1;P<m.length;P++)_u(D,wD(m[P]));var Q=m.groups;if(l){var q=DD([y],D,E,c);Q!==void 0&&_u(q,Q);var U=Vr(_D(s,void 0,q))}else U=CD(y,c,E,D,Q,s);E>=T&&(f+=Jf(c,T,E)+U,T=E+y.length)}return f+Jf(c,T)}]},!PD||!OD||zf);var LD=Xp.includes,MD=om;pe({target:"Array",proto:!0,forced:Z(function(){return!Array(1).includes()})},{includes:function(e){return LD(this,e,arguments.length>1?arguments[1]:void 0)}}),MD("includes");var xD=ii,VD=He,UD=Xt,FD=RangeError,Kf=ee,BD=Li,qf=He,HD=function(e){var t=VD(UD(this)),i="",r=xD(e);if(r<0||r==1/0)throw FD("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))1&r&&(i+=t);return i},jD=Xt,GD=Kf(HD),WD=Kf("".slice),JD=Math.ceil,zD=function(e){return function(t,i,r){var n,s,a=qf(jD(t)),c=BD(i),o=a.length,l=r===void 0?" ":qf(r);return c<=o||l==""?a:((s=GD(l,JD((n=c-o)/l.length))).length>n&&(s=WD(s,0,n)),e?a+s:s+a)}},KD={start:zD(!1)},qD=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(Zt),YD=KD.start;pe({target:"String",proto:!0,forced:qD},{padStart:function(e){return YD(this,e,arguments.length>1?arguments[1]:void 0)}});var QD=Z,XD=Ee,$D=ce("iterator"),Yf=!QD(function(){var e=new URL("b?a=1&b=2&c=3","http://a"),t=e.searchParams,i="";return e.pathname="c%20d",t.forEach(function(r,n){t.delete("b"),i+=n+r}),!t.size&&!XD||!t.sort||e.href!=="http://a/c%20d?a=1&c=3"||t.get("c")!=="3"||String(new URLSearchParams("?a=1"))!=="a=1"||!t[$D]||new URL("https://a@b").username!=="a"||new URLSearchParams(new URLSearchParams("a=b")).get("a")!=="b"||new URL("http://тест").host!=="xn--e1aybc"||new URL("http://a#б").hash!=="#%D0%B1"||i!=="a1c3"||new URL("http://x",void 0).host!=="x"}),ZD=qe,Qf=function(e,t,i){for(var r in t)ZD(e,r,t[r],i);return e},ew=fa,tw=Ke,iw=Ir,Xf=function(e,t,i){var r=ew(t);r in e?tw.f(e,r,iw(0,i)):e[r]=i},$f=Ta,rw=_t,nw=Xf,sw=Array,aw=Math.max,fu=function(e,t,i){for(var r=rw(e),n=$f(t,r),s=$f(i===void 0?r:i,r),a=sw(aw(s-n,0)),c=0;n<s;n++,c++)nw(a,c,e[n]);return a.length=c,a},Zf=fu,ow=Math.floor,gu=function(e,t){var i=e.length,r=ow(i/2);return i<8?cw(e,t):lw(e,gu(Zf(e,0,r),t),gu(Zf(e,r),t),t)},cw=function(e,t){for(var i,r,n=e.length,s=1;s<n;){for(r=s,i=e[s];r&&t(e[r-1],i)>0;)e[r]=e[--r];r!==s++&&(e[r]=i)}return e},lw=function(e,t,i,r){for(var n=t.length,s=i.length,a=0,c=0;a<n||c<s;)e[a+c]=a<n&&c<s?r(t[a],i[c])<=0?t[a++]:i[c++]:a<n?t[a++]:i[c++];return e},Tu=gu,Eu=pe,Ur=te,Ja=le,gt=ee,Fr=Ee,eg=Yf,tg=qe,uw=xi,dw=Qf,hw=Rr,pw=Rm,yu=Me,ig=Fn,Su=ie,mw=ve,_w=ni,fw=ri,gw=Re,rg=De,je=He,Tw=kn,ng=Ir,vu=Ua,Ew=zn,Br=kl,yw=Tu,Sw=ce("iterator"),qn="URLSearchParams",sg=qn+"Iterator",ag=yu.set,Ye=yu.getterFor(qn),vw=yu.getterFor(sg),Iw=Object.getOwnPropertyDescriptor,Iu=function(e){if(!Fr)return Ur[e];var t=Iw(Ur,e);return t&&t.value},og=Iu("fetch"),za=Iu("Request"),Yn=Iu("Headers"),Au=za&&za.prototype,cg=Yn&&Yn.prototype,Aw=Ur.RegExp,Rw=Ur.TypeError,lg=Ur.decodeURIComponent,Cw=Ur.encodeURIComponent,bw=gt("".charAt),ug=gt([].join),Hi=gt([].push),Ru=gt("".replace),kw=gt([].shift),dg=gt([].splice),hg=gt("".split),Nw=gt("".slice),Dw=/\+/g,pg=Array(4),ww=function(e){return pg[e-1]||(pg[e-1]=Aw("((?:%[\\da-f]{2}){"+e+"})","gi"))},Ow=function(e){try{return lg(e)}catch{return e}},mg=function(e){var t=Ru(e,Dw," "),i=4;try{return lg(t)}catch{for(;i;)t=Ru(t,ww(i--),Ow);return t}},Pw=/[!'()~]|%20/g,Lw={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+"},Mw=function(e){return Lw[e]},_g=function(e){return Ru(Cw(e),Pw,Mw)},Cu=pw(function(e,t){ag(this,{type:sg,iterator:vu(Ye(e).entries),kind:t})},"Iterator",function(){var e=vw(this),t=e.kind,i=e.iterator.next(),r=i.value;return i.done||(i.value=t==="keys"?r.key:t==="values"?r.value:[r.key,r.value]),i},!0),fg=function(e){this.entries=[],this.url=null,e!==void 0&&(rg(e)?this.parseObject(e):this.parseQuery(typeof e=="string"?bw(e,0)==="?"?Nw(e,1):e:je(e)))};fg.prototype={type:qn,bindURL:function(e){this.url=e,this.update()},parseObject:function(e){var t,i,r,n,s,a,c,o=Ew(e);if(o)for(i=(t=vu(e,o)).next;!(r=Ja(i,t)).done;){if(s=(n=vu(gw(r.value))).next,(a=Ja(s,n)).done||(c=Ja(s,n)).done||!Ja(s,n).done)throw Rw("Expected sequence with length 2");Hi(this.entries,{key:je(a.value),value:je(c.value)})}else for(var l in e)mw(e,l)&&Hi(this.entries,{key:l,value:je(e[l])})},parseQuery:function(e){if(e)for(var t,i,r=hg(e,"&"),n=0;n<r.length;)(t=r[n++]).length&&(i=hg(t,"="),Hi(this.entries,{key:mg(kw(i)),value:mg(ug(i,"="))}))},serialize:function(){for(var e,t=this.entries,i=[],r=0;r<t.length;)e=t[r++],Hi(i,_g(e.key)+"="+_g(e.value));return ug(i,"&")},update:function(){this.entries.length=0,this.parseQuery(this.url.query)},updateURL:function(){this.url&&this.url.update()}};var Ka=function(){ig(this,Hr);var e=ag(this,new fg(arguments.length>0?arguments[0]:void 0));Fr||(this.length=e.entries.length)},Hr=Ka.prototype;if(dw(Hr,{append:function(e,t){Br(arguments.length,2);var i=Ye(this);Hi(i.entries,{key:je(e),value:je(t)}),Fr||this.length++,i.updateURL()},delete:function(e){Br(arguments.length,1);for(var t=Ye(this),i=t.entries,r=je(e),n=0;n<i.length;)i[n].key===r?dg(i,n,1):n++;Fr||(this.length=i.length),t.updateURL()},get:function(e){Br(arguments.length,1);for(var t=Ye(this).entries,i=je(e),r=0;r<t.length;r++)if(t[r].key===i)return t[r].value;return null},getAll:function(e){Br(arguments.length,1);for(var t=Ye(this).entries,i=je(e),r=[],n=0;n<t.length;n++)t[n].key===i&&Hi(r,t[n].value);return r},has:function(e){Br(arguments.length,1);for(var t=Ye(this).entries,i=je(e),r=0;r<t.length;)if(t[r++].key===i)return!0;return!1},set:function(e,t){Br(arguments.length,1);for(var i,r=Ye(this),n=r.entries,s=!1,a=je(e),c=je(t),o=0;o<n.length;o++)(i=n[o]).key===a&&(s?dg(n,o--,1):(s=!0,i.value=c));s||Hi(n,{key:a,value:c}),Fr||(this.length=n.length),r.updateURL()},sort:function(){var e=Ye(this);yw(e.entries,function(t,i){return t.key>i.key?1:-1}),e.updateURL()},forEach:function(e){for(var t,i=Ye(this).entries,r=_w(e,arguments.length>1?arguments[1]:void 0),n=0;n<i.length;)r((t=i[n++]).value,t.key,this)},keys:function(){return new Cu(this,"keys")},values:function(){return new Cu(this,"values")},entries:function(){return new Cu(this,"entries")}},{enumerable:!0}),tg(Hr,Sw,Hr.entries,{name:"entries"}),tg(Hr,"toString",function(){return Ye(this).serialize()},{enumerable:!0}),Fr&&uw(Hr,"size",{get:function(){return Ye(this).entries.length},configurable:!0,enumerable:!0}),hw(Ka,qn),Eu({global:!0,constructor:!0,forced:!eg},{URLSearchParams:Ka}),!eg&&Su(Yn)){var xw=gt(cg.has),Vw=gt(cg.set),gg=function(e){if(rg(e)){var t,i=e.body;if(fw(i)===qn)return t=e.headers?new Yn(e.headers):new Yn,xw(t,"content-type")||Vw(t,"content-type","application/x-www-form-urlencoded;charset=UTF-8"),Tw(e,{body:ng(0,je(i)),headers:ng(0,t)})}return e};if(Su(og)&&Eu({global:!0,enumerable:!0,dontCallGetSet:!0,forced:!0},{fetch:function(e){return og(e,arguments.length>1?gg(arguments[1]):{})}}),Su(za)){var bu=function(e){return ig(this,Au),new za(e,arguments.length>1?gg(arguments[1]):{})};Au.constructor=bu,bu.prototype=Au,Eu({global:!0,constructor:!0,dontCallGetSet:!0,forced:!0},{Request:bu})}}var Uw={URLSearchParams:Ka,getState:Ye},Fw=pe,qa=Wn,Bw=Z,Tg=ei,Eg=ie,Hw=bl,yg=sf,jw=qe,ku=qa&&qa.prototype;if(Fw({target:"Promise",proto:!0,real:!0,forced:!!qa&&Bw(function(){ku.finally.call({then:function(){}},function(){})})},{finally:function(e){var t=Hw(this,Tg("Promise")),i=Eg(e);return this.then(i?function(r){return yg(t,e()).then(function(){return r})}:e,i?function(r){return yg(t,e()).then(function(){throw r})}:e)}}),Eg(qa)){var Sg=Tg("Promise").prototype.finally;ku.finally!==Sg&&jw(ku,"finally",Sg,{unsafe:!0})}var vg=`
4
+ \v\f\r                 \u2028\u2029\uFEFF`,Gw=Xt,Ww=He,Nu=vg,Ig=ee("".replace),Jw=RegExp("^["+Nu+"]+"),zw=RegExp("(^|[^"+Nu+"])["+Nu+"]+$"),Kw=function(e){return function(t){var i=Ww(Gw(t));return 1&e&&(i=Ig(i,Jw,"")),2&e&&(i=Ig(i,zw,"$1")),i}},qw={trim:Kw(3)},Yw=On.PROPER,Qw=Z,Ag=vg,Xw=qw.trim;pe({target:"String",proto:!0,forced:function(e){return Qw(function(){return!!Ag[e]()||"​…᠎"[e]()!=="​…᠎"||Yw&&Ag[e].name!==e})}("trim")},{trim:function(){return Xw(this)}});var $w=pe,Zw=Ee,Ya=ee,eO=ve,tO=ie,iO=ti,rO=He,nO=xi,sO=ym,wt=te.Symbol,ji=wt&&wt.prototype;if(Zw&&tO(wt)&&(!("description"in ji)||wt().description!==void 0)){var Rg={},Qa=function(){var e=arguments.length<1||arguments[0]===void 0?void 0:rO(arguments[0]),t=iO(ji,this)?new wt(e):e===void 0?wt():wt(e);return e===""&&(Rg[t]=!0),t};sO(Qa,wt),Qa.prototype=ji,ji.constructor=Qa;var aO=String(wt("test"))=="Symbol(test)",oO=Ya(ji.valueOf),cO=Ya(ji.toString),lO=/^Symbol\((.*)\)[^)]+$/,uO=Ya("".replace),dO=Ya("".slice);nO(ji,"description",{configurable:!0,get:function(){var e=oO(this);if(eO(Rg,e))return"";var t=cO(e),i=aO?dO(t,7,-1):uO(t,lO,"$1");return i===""?void 0:i}}),$w({global:!0,constructor:!0,forced:!0},{Symbol:Qa})}var hO=uu.charAt,pO=He,Cg=Me,mO=wm,bg=Om,kg="String Iterator",_O=Cg.set,fO=Cg.getterFor(kg);mO(String,"String",function(e){_O(this,{type:kg,string:pO(e),index:0})},function(){var e,t=fO(this),i=t.string,r=t.index;return r>=i.length?bg(void 0,!0):(e=hO(i,r),t.index+=e.length,bg(e,!1))});var Qe,Ng=Ee,gO=ee,TO=le,EO=Z,Du=em,yO=dl,SO=sl,vO=nt,IO=ua,jr=Object.assign,Dg=Object.defineProperty,AO=gO([].concat),RO=!jr||EO(function(){if(Ng&&jr({b:1},jr(Dg({},"a",{enumerable:!0,get:function(){Dg(this,"b",{value:3,enumerable:!1})}}),{b:2})).b!==1)return!0;var e={},t={},i=Symbol(),r="abcdefghijklmnopqrst";return e[i]=7,r.split("").forEach(function(n){t[n]=n}),jr({},e)[i]!=7||Du(jr({},t)).join("")!=r})?function(e,t){for(var i=vO(e),r=arguments.length,n=1,s=yO.f,a=SO.f;r>n;)for(var c,o=IO(arguments[n++]),l=s?AO(Du(o),s(o)):Du(o),d=l.length,u=0;d>u;)c=l[u++],Ng&&!TO(a,o,c)||(i[c]=o[c]);return i}:jr,CO=Re,bO=z_,kO=ni,NO=le,DO=nt,wO=function(e,t,i,r){try{return r?t(CO(i)[0],i[1]):t(i)}catch(n){bO(e,"throw",n)}},OO=Yl,PO=Cl,LO=_t,wg=Xf,MO=Ua,xO=zn,Og=Array,Gi=ee,wu=2147483647,VO=/[^\0-\u007E]/,Pg=/[.\u3002\uFF0E\uFF61]/g,Lg="Overflow: input needs wider integers to process",Mg=RangeError,UO=Gi(Pg.exec),Gr=Math.floor,Ou=String.fromCharCode,xg=Gi("".charCodeAt),Vg=Gi([].join),oi=Gi([].push),FO=Gi("".replace),BO=Gi("".split),HO=Gi("".toLowerCase),Ug=function(e){return e+22+75*(e<26)},jO=function(e,t,i){var r=0;for(e=i?Gr(e/700):e>>1,e+=Gr(e/t);e>455;)e=Gr(e/35),r+=36;return Gr(r+36*e/(e+38))},GO=function(e){var t=[];e=function(y){for(var E=[],D=0,P=y.length;D<P;){var Q=xg(y,D++);if(Q>=55296&&Q<=56319&&D<P){var q=xg(y,D++);(64512&q)==56320?oi(E,((1023&Q)<<10)+(1023&q)+65536):(oi(E,Q),D--)}else oi(E,Q)}return E}(e);var i,r,n=e.length,s=128,a=0,c=72;for(i=0;i<e.length;i++)(r=e[i])<128&&oi(t,Ou(r));var o=t.length,l=o;for(o&&oi(t,"-");l<n;){var d=wu;for(i=0;i<e.length;i++)(r=e[i])>=s&&r<d&&(d=r);var u=l+1;if(d-s>Gr((wu-a)/u))throw Mg(Lg);for(a+=(d-s)*u,s=d,i=0;i<e.length;i++){if((r=e[i])<s&&++a>wu)throw Mg(Lg);if(r==s){for(var p=a,m=36;;){var f=m<=c?1:m>=c+26?26:m-c;if(p<f)break;var T=p-f,S=36-f;oi(t,Ou(Ug(f+T%S))),p=Gr(T/S),m+=36}oi(t,Ou(Ug(p))),c=jO(a,u,l==o),a=0,l++}}a++,s++}return Vg(t,"")},WO=pe,Pu=Ee,JO=Yf,Lu=te,Fg=ni,Xe=ee,Xa=qe,$e=xi,zO=Fn,Mu=ve,xu=RO,Wr=function(e){var t=DO(e),i=PO(this),r=arguments.length,n=r>1?arguments[1]:void 0,s=n!==void 0;s&&(n=kO(n,r>2?arguments[2]:void 0));var a,c,o,l,d,u,p=xO(t),m=0;if(!p||this===Og&&OO(p))for(a=LO(t),c=i?new this(a):Og(a);a>m;m++)u=s?n(t[m],m):t[m],wg(c,m,u);else for(d=(l=MO(t,p)).next,c=i?new this:[];!(o=NO(d,l)).done;m++)u=s?wO(l,n,[o.value,m],!0):o.value,wg(c,m,u);return c.length=m,c},at=fu,KO=uu.codeAt,qO=function(e){var t,i,r=[],n=BO(FO(HO(e),Pg,"."),".");for(t=0;t<n.length;t++)i=n[t],oi(r,UO(VO,i)?"xn--"+GO(i):i);return Vg(r,".")},Ot=He,YO=Rr,QO=kl,Bg=Uw,Hg=Me,XO=Hg.set,$a=Hg.getterFor("URL"),$O=Bg.URLSearchParams,ZO=Bg.getState,Qn=Lu.URL,Vu=Lu.TypeError,Za=Lu.parseInt,eP=Math.floor,jg=Math.pow,Ze=Xe("".charAt),ot=Xe(/./.exec),Xn=Xe([].join),tP=Xe(1 .toString),iP=Xe([].pop),Jr=Xe([].push),Uu=Xe("".replace),rP=Xe([].shift),nP=Xe("".split),$n=Xe("".slice),eo=Xe("".toLowerCase),sP=Xe([].unshift),Fu="Invalid scheme",Wi="Invalid host",Gg="Invalid port",Wg=/[a-z]/i,aP=/[\d+-.a-z]/i,Bu=/\d/,oP=/^0x/i,cP=/^[0-7]+$/,lP=/^\d+$/,Jg=/^[\da-f]+$/i,uP=/[\0\t\n\r #%/:<>?@[\\\]^|]/,dP=/[\0\t\n\r #/:<>?@[\\\]^|]/,hP=/^[\u0000-\u0020]+/,pP=/(^|[^\u0000-\u0020])[\u0000-\u0020]+$/,mP=/[\t\n\r]/g,Zn=function(e){var t,i,r,n;if(typeof e=="number"){for(t=[],i=0;i<4;i++)sP(t,e%256),e=eP(e/256);return Xn(t,".")}if(typeof e=="object"){for(t="",r=function(s){for(var a=null,c=1,o=null,l=0,d=0;d<8;d++)s[d]!==0?(l>c&&(a=o,c=l),o=null,l=0):(o===null&&(o=d),++l);return l>c&&(a=o,c=l),a}(e),i=0;i<8;i++)n&&e[i]===0||(n&&(n=!1),r===i?(t+=i?":":"::",n=!0):(t+=tP(e[i],16),i<7&&(t+=":")));return"["+t+"]"}return e},to={},zg=xu({},to,{" ":1,'"':1,"<":1,">":1,"`":1}),Kg=xu({},zg,{"#":1,"?":1,"{":1,"}":1}),Hu=xu({},Kg,{"/":1,":":1,";":1,"=":1,"@":1,"[":1,"\\":1,"]":1,"^":1,"|":1}),ci=function(e,t){var i=KO(e,0);return i>32&&i<127&&!Mu(t,e)?e:encodeURIComponent(e)},io={ftp:21,file:null,http:80,https:443,ws:80,wss:443},es=function(e,t){var i;return e.length==2&&ot(Wg,Ze(e,0))&&((i=Ze(e,1))==":"||!t&&i=="|")},qg=function(e){var t;return e.length>1&&es($n(e,0,2))&&(e.length==2||(t=Ze(e,2))==="/"||t==="\\"||t==="?"||t==="#")},_P=function(e){return e==="."||eo(e)==="%2e"},ju={},Yg={},Gu={},Qg={},Xg={},Wu={},$g={},Zg={},ro={},no={},Ju={},zu={},Ku={},qu={},eT={},Yu={},zr={},Tt={},tT={},Ji={},Pt={},Qu=function(e,t,i){var r,n,s,a=Ot(e);if(t){if(n=this.parse(a))throw Vu(n);this.searchParams=null}else{if(i!==void 0&&(r=new Qu(i,!0)),n=this.parse(a,null,r))throw Vu(n);(s=ZO(new $O)).bindURL(this),this.searchParams=s}};Qu.prototype={type:"URL",parse:function(e,t,i){var r,n,s,a,c,o=this,l=t||ju,d=0,u="",p=!1,m=!1,f=!1;for(e=Ot(e),t||(o.scheme="",o.username="",o.password="",o.host=null,o.port=null,o.path=[],o.query=null,o.fragment=null,o.cannotBeABaseURL=!1,e=Uu(e,hP,""),e=Uu(e,pP,"$1")),e=Uu(e,mP,""),r=Wr(e);d<=r.length;){switch(n=r[d],l){case ju:if(!n||!ot(Wg,n)){if(t)return Fu;l=Gu;continue}u+=eo(n),l=Yg;break;case Yg:if(n&&(ot(aP,n)||n=="+"||n=="-"||n=="."))u+=eo(n);else{if(n!=":"){if(t)return Fu;u="",l=Gu,d=0;continue}if(t&&(o.isSpecial()!=Mu(io,u)||u=="file"&&(o.includesCredentials()||o.port!==null)||o.scheme=="file"&&!o.host))return;if(o.scheme=u,t)return void(o.isSpecial()&&io[o.scheme]==o.port&&(o.port=null));u="",o.scheme=="file"?l=qu:o.isSpecial()&&i&&i.scheme==o.scheme?l=Qg:o.isSpecial()?l=Zg:r[d+1]=="/"?(l=Xg,d++):(o.cannotBeABaseURL=!0,Jr(o.path,""),l=tT)}break;case Gu:if(!i||i.cannotBeABaseURL&&n!="#")return Fu;if(i.cannotBeABaseURL&&n=="#"){o.scheme=i.scheme,o.path=at(i.path),o.query=i.query,o.fragment="",o.cannotBeABaseURL=!0,l=Pt;break}l=i.scheme=="file"?qu:Wu;continue;case Qg:if(n!="/"||r[d+1]!="/"){l=Wu;continue}l=ro,d++;break;case Xg:if(n=="/"){l=no;break}l=Tt;continue;case Wu:if(o.scheme=i.scheme,n==Qe)o.username=i.username,o.password=i.password,o.host=i.host,o.port=i.port,o.path=at(i.path),o.query=i.query;else if(n=="/"||n=="\\"&&o.isSpecial())l=$g;else if(n=="?")o.username=i.username,o.password=i.password,o.host=i.host,o.port=i.port,o.path=at(i.path),o.query="",l=Ji;else{if(n!="#"){o.username=i.username,o.password=i.password,o.host=i.host,o.port=i.port,o.path=at(i.path),o.path.length--,l=Tt;continue}o.username=i.username,o.password=i.password,o.host=i.host,o.port=i.port,o.path=at(i.path),o.query=i.query,o.fragment="",l=Pt}break;case $g:if(!o.isSpecial()||n!="/"&&n!="\\"){if(n!="/"){o.username=i.username,o.password=i.password,o.host=i.host,o.port=i.port,l=Tt;continue}l=no}else l=ro;break;case Zg:if(l=ro,n!="/"||Ze(u,d+1)!="/")continue;d++;break;case ro:if(n!="/"&&n!="\\"){l=no;continue}break;case no:if(n=="@"){p&&(u="%40"+u),p=!0,s=Wr(u);for(var T=0;T<s.length;T++){var S=s[T];if(S!=":"||f){var y=ci(S,Hu);f?o.password+=y:o.username+=y}else f=!0}u=""}else if(n==Qe||n=="/"||n=="?"||n=="#"||n=="\\"&&o.isSpecial()){if(p&&u=="")return"Invalid authority";d-=Wr(u).length+1,u="",l=Ju}else u+=n;break;case Ju:case zu:if(t&&o.scheme=="file"){l=Yu;continue}if(n!=":"||m){if(n==Qe||n=="/"||n=="?"||n=="#"||n=="\\"&&o.isSpecial()){if(o.isSpecial()&&u=="")return Wi;if(t&&u==""&&(o.includesCredentials()||o.port!==null))return;if(a=o.parseHost(u))return a;if(u="",l=zr,t)return;continue}n=="["?m=!0:n=="]"&&(m=!1),u+=n}else{if(u=="")return Wi;if(a=o.parseHost(u))return a;if(u="",l=Ku,t==zu)return}break;case Ku:if(!ot(Bu,n)){if(n==Qe||n=="/"||n=="?"||n=="#"||n=="\\"&&o.isSpecial()||t){if(u!=""){var E=Za(u,10);if(E>65535)return Gg;o.port=o.isSpecial()&&E===io[o.scheme]?null:E,u=""}if(t)return;l=zr;continue}return Gg}u+=n;break;case qu:if(o.scheme="file",n=="/"||n=="\\")l=eT;else{if(!i||i.scheme!="file"){l=Tt;continue}if(n==Qe)o.host=i.host,o.path=at(i.path),o.query=i.query;else if(n=="?")o.host=i.host,o.path=at(i.path),o.query="",l=Ji;else{if(n!="#"){qg(Xn(at(r,d),""))||(o.host=i.host,o.path=at(i.path),o.shortenPath()),l=Tt;continue}o.host=i.host,o.path=at(i.path),o.query=i.query,o.fragment="",l=Pt}}break;case eT:if(n=="/"||n=="\\"){l=Yu;break}i&&i.scheme=="file"&&!qg(Xn(at(r,d),""))&&(es(i.path[0],!0)?Jr(o.path,i.path[0]):o.host=i.host),l=Tt;continue;case Yu:if(n==Qe||n=="/"||n=="\\"||n=="?"||n=="#"){if(!t&&es(u))l=Tt;else if(u==""){if(o.host="",t)return;l=zr}else{if(a=o.parseHost(u))return a;if(o.host=="localhost"&&(o.host=""),t)return;u="",l=zr}continue}u+=n;break;case zr:if(o.isSpecial()){if(l=Tt,n!="/"&&n!="\\")continue}else if(t||n!="?")if(t||n!="#"){if(n!=Qe&&(l=Tt,n!="/"))continue}else o.fragment="",l=Pt;else o.query="",l=Ji;break;case Tt:if(n==Qe||n=="/"||n=="\\"&&o.isSpecial()||!t&&(n=="?"||n=="#")){if((c=eo(c=u))===".."||c==="%2e."||c===".%2e"||c==="%2e%2e"?(o.shortenPath(),n=="/"||n=="\\"&&o.isSpecial()||Jr(o.path,"")):_P(u)?n=="/"||n=="\\"&&o.isSpecial()||Jr(o.path,""):(o.scheme=="file"&&!o.path.length&&es(u)&&(o.host&&(o.host=""),u=Ze(u,0)+":"),Jr(o.path,u)),u="",o.scheme=="file"&&(n==Qe||n=="?"||n=="#"))for(;o.path.length>1&&o.path[0]==="";)rP(o.path);n=="?"?(o.query="",l=Ji):n=="#"&&(o.fragment="",l=Pt)}else u+=ci(n,Kg);break;case tT:n=="?"?(o.query="",l=Ji):n=="#"?(o.fragment="",l=Pt):n!=Qe&&(o.path[0]+=ci(n,to));break;case Ji:t||n!="#"?n!=Qe&&(n=="'"&&o.isSpecial()?o.query+="%27":o.query+=n=="#"?"%23":ci(n,to)):(o.fragment="",l=Pt);break;case Pt:n!=Qe&&(o.fragment+=ci(n,zg))}d++}},parseHost:function(e){var t,i,r;if(Ze(e,0)=="["){if(Ze(e,e.length-1)!="]"||(t=function(n){var s,a,c,o,l,d,u,p=[0,0,0,0,0,0,0,0],m=0,f=null,T=0,S=function(){return Ze(n,T)};if(S()==":"){if(Ze(n,1)!=":")return;T+=2,f=++m}for(;S();){if(m==8)return;if(S()!=":"){for(s=a=0;a<4&&ot(Jg,S());)s=16*s+Za(S(),16),T++,a++;if(S()=="."){if(a==0||(T-=a,m>6))return;for(c=0;S();){if(o=null,c>0){if(!(S()=="."&&c<4))return;T++}if(!ot(Bu,S()))return;for(;ot(Bu,S());){if(l=Za(S(),10),o===null)o=l;else{if(o==0)return;o=10*o+l}if(o>255)return;T++}p[m]=256*p[m]+o,++c!=2&&c!=4||m++}if(c!=4)return;break}if(S()==":"){if(T++,!S())return}else if(S())return;p[m++]=s}else{if(f!==null)return;T++,f=++m}}if(f!==null)for(d=m-f,m=7;m!=0&&d>0;)u=p[m],p[m--]=p[f+d-1],p[f+--d]=u;else if(m!=8)return;return p}($n(e,1,-1)),!t))return Wi;this.host=t}else if(this.isSpecial()){if(e=qO(e),ot(uP,e)||(t=function(n){var s,a,c,o,l,d,u,p=nP(n,".");if(p.length&&p[p.length-1]==""&&p.length--,(s=p.length)>4)return n;for(a=[],c=0;c<s;c++){if((o=p[c])=="")return n;if(l=10,o.length>1&&Ze(o,0)=="0"&&(l=ot(oP,o)?16:8,o=$n(o,l==8?1:2)),o==="")d=0;else{if(!ot(l==10?lP:l==8?cP:Jg,o))return n;d=Za(o,l)}Jr(a,d)}for(c=0;c<s;c++)if(d=a[c],c==s-1){if(d>=jg(256,5-s))return null}else if(d>255)return null;for(u=iP(a),c=0;c<a.length;c++)u+=a[c]*jg(256,3-c);return u}(e),t===null))return Wi;this.host=t}else{if(ot(dP,e))return Wi;for(t="",i=Wr(e),r=0;r<i.length;r++)t+=ci(i[r],to);this.host=t}},cannotHaveUsernamePasswordPort:function(){return!this.host||this.cannotBeABaseURL||this.scheme=="file"},includesCredentials:function(){return this.username!=""||this.password!=""},isSpecial:function(){return Mu(io,this.scheme)},shortenPath:function(){var e=this.path,t=e.length;!t||this.scheme=="file"&&t==1&&es(e[0],!0)||e.length--},serialize:function(){var e=this,t=e.scheme,i=e.username,r=e.password,n=e.host,s=e.port,a=e.path,c=e.query,o=e.fragment,l=t+":";return n!==null?(l+="//",e.includesCredentials()&&(l+=i+(r?":"+r:"")+"@"),l+=Zn(n),s!==null&&(l+=":"+s)):t=="file"&&(l+="//"),l+=e.cannotBeABaseURL?a[0]:a.length?"/"+Xn(a,"/"):"",c!==null&&(l+="?"+c),o!==null&&(l+="#"+o),l},setHref:function(e){var t=this.parse(e);if(t)throw Vu(t);this.searchParams.update()},getOrigin:function(){var e=this.scheme,t=this.port;if(e=="blob")try{return new Kr(e.path[0]).origin}catch{return"null"}return e!="file"&&this.isSpecial()?e+"://"+Zn(this.host)+(t!==null?":"+t:""):"null"},getProtocol:function(){return this.scheme+":"},setProtocol:function(e){this.parse(Ot(e)+":",ju)},getUsername:function(){return this.username},setUsername:function(e){var t=Wr(Ot(e));if(!this.cannotHaveUsernamePasswordPort()){this.username="";for(var i=0;i<t.length;i++)this.username+=ci(t[i],Hu)}},getPassword:function(){return this.password},setPassword:function(e){var t=Wr(Ot(e));if(!this.cannotHaveUsernamePasswordPort()){this.password="";for(var i=0;i<t.length;i++)this.password+=ci(t[i],Hu)}},getHost:function(){var e=this.host,t=this.port;return e===null?"":t===null?Zn(e):Zn(e)+":"+t},setHost:function(e){this.cannotBeABaseURL||this.parse(e,Ju)},getHostname:function(){var e=this.host;return e===null?"":Zn(e)},setHostname:function(e){this.cannotBeABaseURL||this.parse(e,zu)},getPort:function(){var e=this.port;return e===null?"":Ot(e)},setPort:function(e){this.cannotHaveUsernamePasswordPort()||((e=Ot(e))==""?this.port=null:this.parse(e,Ku))},getPathname:function(){var e=this.path;return this.cannotBeABaseURL?e[0]:e.length?"/"+Xn(e,"/"):""},setPathname:function(e){this.cannotBeABaseURL||(this.path=[],this.parse(e,zr))},getSearch:function(){var e=this.query;return e?"?"+e:""},setSearch:function(e){(e=Ot(e))==""?this.query=null:(Ze(e,0)=="?"&&(e=$n(e,1)),this.query="",this.parse(e,Ji)),this.searchParams.update()},getSearchParams:function(){return this.searchParams.facade},getHash:function(){var e=this.fragment;return e?"#"+e:""},setHash:function(e){(e=Ot(e))!=""?(Ze(e,0)=="#"&&(e=$n(e,1)),this.fragment="",this.parse(e,Pt)):this.fragment=null},update:function(){this.query=this.searchParams.serialize()||null}};var Kr=function(e){var t=zO(this,we),i=QO(arguments.length,1)>1?arguments[1]:void 0,r=XO(t,new Qu(e,!1,i));Pu||(t.href=r.serialize(),t.origin=r.getOrigin(),t.protocol=r.getProtocol(),t.username=r.getUsername(),t.password=r.getPassword(),t.host=r.getHost(),t.hostname=r.getHostname(),t.port=r.getPort(),t.pathname=r.getPathname(),t.search=r.getSearch(),t.searchParams=r.getSearchParams(),t.hash=r.getHash())},we=Kr.prototype,et=function(e,t){return{get:function(){return $a(this)[e]()},set:t&&function(i){return $a(this)[t](i)},configurable:!0,enumerable:!0}};if(Pu&&($e(we,"href",et("serialize","setHref")),$e(we,"origin",et("getOrigin")),$e(we,"protocol",et("getProtocol","setProtocol")),$e(we,"username",et("getUsername","setUsername")),$e(we,"password",et("getPassword","setPassword")),$e(we,"host",et("getHost","setHost")),$e(we,"hostname",et("getHostname","setHostname")),$e(we,"port",et("getPort","setPort")),$e(we,"pathname",et("getPathname","setPathname")),$e(we,"search",et("getSearch","setSearch")),$e(we,"searchParams",et("getSearchParams")),$e(we,"hash",et("getHash","setHash"))),Xa(we,"toJSON",function(){return $a(this).serialize()},{enumerable:!0}),Xa(we,"toString",function(){return $a(this).serialize()},{enumerable:!0}),Qn){var iT=Qn.createObjectURL,rT=Qn.revokeObjectURL;iT&&Xa(Kr,"createObjectURL",Fg(iT,Qn)),rT&&Xa(Kr,"revokeObjectURL",Fg(rT,Qn))}YO(Kr,"URL"),WO({global:!0,constructor:!0,forced:!JO,sham:!Pu},{URL:Kr});var nT=typeof ArrayBuffer<"u"&&typeof DataView<"u",fP=ii,gP=Li,TP=RangeError,sT=function(e){if(e===void 0)return 0;var t=fP(e),i=gP(t);if(t!==i)throw TP("Wrong length or index");return i},EP=Array,yP=Math.abs,Lt=Math.pow,SP=Math.floor,vP=Math.log,IP=Math.LN2,AP={pack:function(e,t,i){var r,n,s,a=EP(i),c=8*i-t-1,o=(1<<c)-1,l=o>>1,d=t===23?Lt(2,-24)-Lt(2,-77):0,u=e<0||e===0&&1/e<0?1:0,p=0;for((e=yP(e))!=e||e===1/0?(n=e!=e?1:0,r=o):(r=SP(vP(e)/IP),e*(s=Lt(2,-r))<1&&(r--,s*=2),(e+=r+l>=1?d/s:d*Lt(2,1-l))*s>=2&&(r++,s/=2),r+l>=o?(n=0,r=o):r+l>=1?(n=(e*s-1)*Lt(2,t),r+=l):(n=e*Lt(2,l-1)*Lt(2,t),r=0));t>=8;)a[p++]=255&n,n/=256,t-=8;for(r=r<<t|n,c+=t;c>0;)a[p++]=255&r,r/=256,c-=8;return a[--p]|=128*u,a},unpack:function(e,t){var i,r=e.length,n=8*r-t-1,s=(1<<n)-1,a=s>>1,c=n-7,o=r-1,l=e[o--],d=127&l;for(l>>=7;c>0;)d=256*d+e[o--],c-=8;for(i=d&(1<<-c)-1,d>>=-c,c+=t;c>0;)i=256*i+e[o--],c-=8;if(d===0)d=1-a;else{if(d===s)return i?NaN:l?-1/0:1/0;i+=Lt(2,t),d-=a}return(l?-1:1)*i*Lt(2,d-t)}},RP=nt,aT=Ta,CP=_t,oT=function(e){for(var t=RP(this),i=CP(t),r=arguments.length,n=aT(r>1?arguments[1]:void 0,i),s=r>2?arguments[2]:void 0,a=s===void 0?i:aT(s,i);a>n;)t[n++]=e;return t},so=te,Xu=ee,$u=Ee,bP=nT,cT=On,lT=Dt,kP=xi,uT=Qf,Zu=Z,ao=Fn,NP=ii,DP=Li,oo=sT,dT=AP,wP=Ca,hT=Cr,OP=Pn.f,PP=oT,LP=fu,pT=Rr,ed=Me,MP=cT.PROPER,mT=cT.CONFIGURABLE,qr="ArrayBuffer",co="DataView",Yr="prototype",_T="Wrong index",fT=ed.getterFor(qr),ts=ed.getterFor(co),gT=ed.set,tt=so[qr],ct=tt,Qr=ct&&ct[Yr],Mt=so[co],zi=Mt&&Mt[Yr],TT=Object.prototype,xP=so.Array,lo=so.RangeError,VP=Xu(PP),UP=Xu([].reverse),ET=dT.pack,yT=dT.unpack,ST=function(e){return[255&e]},vT=function(e){return[255&e,e>>8&255]},IT=function(e){return[255&e,e>>8&255,e>>16&255,e>>24&255]},AT=function(e){return e[3]<<24|e[2]<<16|e[1]<<8|e[0]},FP=function(e){return ET(e,23,4)},BP=function(e){return ET(e,52,8)},uo=function(e,t,i){kP(e[Yr],t,{configurable:!0,get:function(){return i(this)[t]}})},li=function(e,t,i,r){var n=oo(i),s=ts(e);if(n+t>s.byteLength)throw lo(_T);var a=s.bytes,c=n+s.byteOffset,o=LP(a,c,c+t);return r?o:UP(o)},ui=function(e,t,i,r,n,s){var a=oo(i),c=ts(e);if(a+t>c.byteLength)throw lo(_T);for(var o=c.bytes,l=a+c.byteOffset,d=r(+n),u=0;u<t;u++)o[l+u]=d[s?u:t-u-1]};if(bP){var RT=MP&&tt.name!==qr;if(Zu(function(){tt(1)})&&Zu(function(){new tt(-1)})&&!Zu(function(){return new tt,new tt(1.5),new tt(NaN),tt.length!=1||RT&&!mT}))RT&&mT&&lT(tt,"name",qr);else{(ct=function(e){return ao(this,Qr),new tt(oo(e))})[Yr]=Qr;for(var td,CT=OP(tt),bT=0;CT.length>bT;)(td=CT[bT++])in ct||lT(ct,td,tt[td]);Qr.constructor=ct}hT&&wP(zi)!==TT&&hT(zi,TT);var ho=new Mt(new ct(2)),kT=Xu(zi.setInt8);ho.setInt8(0,2147483648),ho.setInt8(1,2147483649),!ho.getInt8(0)&&ho.getInt8(1)||uT(zi,{setInt8:function(e,t){kT(this,e,t<<24>>24)},setUint8:function(e,t){kT(this,e,t<<24>>24)}},{unsafe:!0})}else Qr=(ct=function(e){ao(this,Qr);var t=oo(e);gT(this,{type:qr,bytes:VP(xP(t),0),byteLength:t}),$u||(this.byteLength=t,this.detached=!1)})[Yr],zi=(Mt=function(e,t,i){ao(this,zi),ao(e,Qr);var r=fT(e),n=r.byteLength,s=NP(t);if(s<0||s>n)throw lo("Wrong offset");if(s+(i=i===void 0?n-s:DP(i))>n)throw lo("Wrong length");gT(this,{type:co,buffer:e,byteLength:i,byteOffset:s,bytes:r.bytes}),$u||(this.buffer=e,this.byteLength=i,this.byteOffset=s)})[Yr],$u&&(uo(ct,"byteLength",fT),uo(Mt,"buffer",ts),uo(Mt,"byteLength",ts),uo(Mt,"byteOffset",ts)),uT(zi,{getInt8:function(e){return li(this,1,e)[0]<<24>>24},getUint8:function(e){return li(this,1,e)[0]},getInt16:function(e){var t=li(this,2,e,arguments.length>1?arguments[1]:void 0);return(t[1]<<8|t[0])<<16>>16},getUint16:function(e){var t=li(this,2,e,arguments.length>1?arguments[1]:void 0);return t[1]<<8|t[0]},getInt32:function(e){return AT(li(this,4,e,arguments.length>1?arguments[1]:void 0))},getUint32:function(e){return AT(li(this,4,e,arguments.length>1?arguments[1]:void 0))>>>0},getFloat32:function(e){return yT(li(this,4,e,arguments.length>1?arguments[1]:void 0),23)},getFloat64:function(e){return yT(li(this,8,e,arguments.length>1?arguments[1]:void 0),52)},setInt8:function(e,t){ui(this,1,e,ST,t)},setUint8:function(e,t){ui(this,1,e,ST,t)},setInt16:function(e,t){ui(this,2,e,vT,t,arguments.length>2?arguments[2]:void 0)},setUint16:function(e,t){ui(this,2,e,vT,t,arguments.length>2?arguments[2]:void 0)},setInt32:function(e,t){ui(this,4,e,IT,t,arguments.length>2?arguments[2]:void 0)},setUint32:function(e,t){ui(this,4,e,IT,t,arguments.length>2?arguments[2]:void 0)},setFloat32:function(e,t){ui(this,4,e,FP,t,arguments.length>2?arguments[2]:void 0)},setFloat64:function(e,t){ui(this,8,e,BP,t,arguments.length>2?arguments[2]:void 0)}});pT(ct,qr),pT(Mt,co);var po={ArrayBuffer:ct,DataView:Mt},HP=pe,id=jn,jP=Z,NT=Re,DT=Ta,GP=Li,WP=bl,rd=po.ArrayBuffer,nd=po.DataView,wT=nd.prototype,OT=id(rd.prototype.slice),JP=id(wT.getUint8),zP=id(wT.setUint8);HP({target:"ArrayBuffer",proto:!0,unsafe:!0,forced:jP(function(){return!new rd(2).slice(1,void 0).byteLength})},{slice:function(e,t){if(OT&&t===void 0)return OT(NT(this),e);for(var i=NT(this).byteLength,r=DT(e,i),n=DT(t===void 0?i:t,i),s=new(WP(this,rd))(GP(n-r)),a=new nd(this),c=new nd(s),o=0;r<n;)zP(c,o++,JP(a,r++));return s}});var xe,Xr,mo,_o={},PT={get exports(){return _o},set exports(e){_o=e}},KP=nT,sd=Ee,Oe=te,LT=ie,MT=De,is=ve,xT=ri,qP=vr,YP=Dt,ad=qe,QP=xi,XP=ti,od=Ca,$r=Cr,$P=ce,ZP=Pc,VT=Me.enforce,fo=Oe.Int8Array,cd=fo&&fo.prototype,UT=Oe.Uint8ClampedArray,FT=UT&&UT.prototype,Et=fo&&od(fo),lt=cd&&od(cd),eL=Object.prototype,ld=Oe.TypeError,BT=$P("toStringTag"),ud=ZP("TYPED_ARRAY_TAG"),HT="TypedArrayConstructor",xt=KP&&!!$r&&xT(Oe.opera)!=="Opera",jT=!1,di={Int8Array:1,Uint8Array:1,Uint8ClampedArray:1,Int16Array:2,Uint16Array:2,Int32Array:4,Uint32Array:4,Float32Array:4,Float64Array:8},GT={BigInt64Array:8,BigUint64Array:8},WT=function(e){if(!MT(e))return!1;var t=xT(e);return is(di,t)||is(GT,t)};for(xe in di)(mo=(Xr=Oe[xe])&&Xr.prototype)?VT(mo)[HT]=Xr:xt=!1;for(xe in GT)(mo=(Xr=Oe[xe])&&Xr.prototype)&&(VT(mo)[HT]=Xr);if((!xt||!LT(Et)||Et===Function.prototype)&&(Et=function(){throw ld("Incorrect invocation")},xt))for(xe in di)Oe[xe]&&$r(Oe[xe],Et);if((!xt||!lt||lt===eL)&&(lt=Et.prototype,xt))for(xe in di)Oe[xe]&&$r(Oe[xe].prototype,lt);if(xt&&od(FT)!==lt&&$r(FT,lt),sd&&!is(lt,BT))for(xe in jT=!0,QP(lt,BT,{configurable:!0,get:function(){return MT(this)?this[ud]:void 0}}),di)Oe[xe]&&YP(Oe[xe],ud,xe);var Vt={NATIVE_ARRAY_BUFFER_VIEWS:xt,TYPED_ARRAY_TAG:jT&&ud,aTypedArray:function(e){if(WT(e))return e;throw ld("Target is not a typed array")},aTypedArrayConstructor:function(e){if(LT(e)&&(!$r||XP(Et,e)))return e;throw ld(qP(e)+" is not a typed array constructor")},exportTypedArrayMethod:function(e,t,i,r){if(sd){if(i)for(var n in di){var s=Oe[n];if(s&&is(s.prototype,e))try{delete s.prototype[e]}catch{try{s.prototype[e]=t}catch{}}}lt[e]&&!i||ad(lt,e,i?t:xt&&cd[e]||t,r)}},exportTypedArrayStaticMethod:function(e,t,i){var r,n;if(sd){if($r){if(i){for(r in di)if((n=Oe[r])&&is(n,e))try{delete n[e]}catch{}}if(Et[e]&&!i)return;try{return ad(Et,e,i?t:xt&&Et[e]||t)}catch{}}for(r in di)!(n=Oe[r])||n[e]&&!i||ad(n,e,t)}},isTypedArray:WT,TypedArray:Et,TypedArrayPrototype:lt},JT=te,dd=Z,tL=ef,iL=Vt.NATIVE_ARRAY_BUFFER_VIEWS,rL=JT.ArrayBuffer,Ki=JT.Int8Array,zT=!iL||!dd(function(){Ki(1)})||!dd(function(){new Ki(-1)})||!tL(function(e){new Ki,new Ki(null),new Ki(1.5),new Ki(e)},!0)||dd(function(){return new Ki(new rL(2),1,void 0).length!==1}),nL=De,sL=Math.floor,aL=Number.isInteger||function(e){return!nL(e)&&isFinite(e)&&sL(e)===e},oL=ii,cL=RangeError,lL=function(e){var t=oL(e);if(t<0)throw cL("The argument can't be less than 0");return t},uL=RangeError,KT=function(e,t){var i=lL(e);if(i%t)throw uL("Wrong offset");return i},dL=ri,hL=qp,pL=TypeError,qT=function(e){var t=hL(e,"number");if(typeof t=="number")throw pL("Can't convert number to bigint");return BigInt(t)},mL=ni,_L=le,fL=e_,gL=nt,TL=_t,EL=Ua,yL=zn,SL=Yl,vL=function(e){var t=dL(e);return t=="BigInt64Array"||t=="BigUint64Array"},IL=Vt.aTypedArrayConstructor,AL=qT,YT=function(e){var t,i,r,n,s,a,c,o,l=fL(this),d=gL(e),u=arguments.length,p=u>1?arguments[1]:void 0,m=p!==void 0,f=yL(d);if(f&&!SL(f))for(o=(c=EL(d,f)).next,d=[];!(a=_L(o,c)).done;)d.push(a.value);for(m&&u>2&&(p=mL(p,arguments[2])),i=TL(d),r=new(IL(l))(i),n=vL(r),t=0;i>t;t++)s=m?p(d[t],t):d[t],r[t]=n?AL(s):+s;return r},QT=pe,XT=te,$T=le,RL=Ee,CL=zT,Zr=Vt,ZT=po,eE=Fn,bL=Ir,rs=Dt,kL=aL,NL=Li,tE=sT,hd=KT,iE=fa,ns=ve,DL=ri,pd=De,wL=Fc,OL=kn,PL=ti,go=Cr,LL=Pn.f,rE=YT,ML=Df.forEach,xL=ka,VL=xi,nE=Ke,sE=wn,UL=of,md=Me.get,FL=Me.set,BL=Me.enforce,aE=nE.f,HL=sE.f,jL=Math.round,_d=XT.RangeError,oE=ZT.ArrayBuffer,GL=oE.prototype,WL=ZT.DataView,To=Zr.NATIVE_ARRAY_BUFFER_VIEWS,cE=Zr.TYPED_ARRAY_TAG,lE=Zr.TypedArray,ss=Zr.TypedArrayPrototype,JL=Zr.aTypedArrayConstructor,fd=Zr.isTypedArray,Eo="BYTES_PER_ELEMENT",gd="Wrong length",uE=function(e,t){JL(e);for(var i=0,r=t.length,n=new e(r);r>i;)n[i]=t[i++];return n},yo=function(e,t){VL(e,t,{configurable:!0,get:function(){return md(this)[t]}})},dE=function(e){var t;return PL(GL,e)||(t=DL(e))=="ArrayBuffer"||t=="SharedArrayBuffer"},hE=function(e,t){return fd(e)&&!wL(t)&&t in e&&kL(+t)&&t>=0},pE=function(e,t){return t=iE(t),hE(e,t)?bL(2,e[t]):HL(e,t)},mE=function(e,t,i){return t=iE(t),!(hE(e,t)&&pd(i)&&ns(i,"value"))||ns(i,"get")||ns(i,"set")||i.configurable||ns(i,"writable")&&!i.writable||ns(i,"enumerable")&&!i.enumerable?aE(e,t,i):(e[t]=i.value,e)};RL?(To||(sE.f=pE,nE.f=mE,yo(ss,"buffer"),yo(ss,"byteOffset"),yo(ss,"byteLength"),yo(ss,"length")),QT({target:"Object",stat:!0,forced:!To},{getOwnPropertyDescriptor:pE,defineProperty:mE}),PT.exports=function(e,t,i){var r=e.match(/\d+/)[0]/8,n=e+(i?"Clamped":"")+"Array",s="get"+e,a="set"+e,c=XT[n],o=c,l=o&&o.prototype,d={},u=function(m,f){aE(m,f,{get:function(){return function(T,S){var y=md(T);return y.view[s](S*r+y.byteOffset,!0)}(this,f)},set:function(T){return function(S,y,E){var D=md(S);i&&(E=(E=jL(E))<0?0:E>255?255:255&E),D.view[a](y*r+D.byteOffset,E,!0)}(this,f,T)},enumerable:!0})};To?CL&&(o=t(function(m,f,T,S){return eE(m,l),UL(pd(f)?dE(f)?S!==void 0?new c(f,hd(T,r),S):T!==void 0?new c(f,hd(T,r)):new c(f):fd(f)?uE(o,f):$T(rE,o,f):new c(tE(f)),m,o)}),go&&go(o,lE),ML(LL(c),function(m){m in o||rs(o,m,c[m])}),o.prototype=l):(o=t(function(m,f,T,S){eE(m,l);var y,E,D,P=0,Q=0;if(pd(f)){if(!dE(f))return fd(f)?uE(o,f):$T(rE,o,f);y=f,Q=hd(T,r);var q=f.byteLength;if(S===void 0){if(q%r||(E=q-Q)<0)throw _d(gd)}else if((E=NL(S)*r)+Q>q)throw _d(gd);D=E/r}else D=tE(f),y=new oE(E=D*r);for(FL(m,{buffer:y,byteOffset:Q,byteLength:E,length:D,view:new WL(y)});P<D;)u(m,P++)}),go&&go(o,lE),l=o.prototype=OL(ss)),l.constructor!==o&&rs(l,"constructor",o),BL(l).TypedArrayConstructor=o,cE&&rs(l,cE,n);var p=o!=c;d[n]=o,QT({global:!0,constructor:!0,forced:p,sham:!To},d),Eo in o||rs(o,Eo,r),Eo in l||rs(l,Eo,r),xL(n)}):PT.exports=function(){},_o("Uint8",function(e){return function(t,i,r){return e(this,t,i,r)}});var zL=oT,KL=qT,qL=ri,YL=le,QL=Z,XL=Vt.aTypedArray,$L=Vt.exportTypedArrayMethod,ZL=ee("".slice);$L("fill",function(e){var t=arguments.length;XL(this);var i=ZL(qL(this),0,3)==="Big"?KL(e):+e;return YL(zL,this,i,t>1?arguments[1]:void 0,t>2?arguments[2]:void 0)},QL(function(){var e=0;return new Int8Array(2).fill({valueOf:function(){return e++}}),e!==1}));var _E=te,fE=le,Td=Vt,eM=_t,tM=KT,iM=nt,gE=Z,rM=_E.RangeError,Ed=_E.Int8Array,TE=Ed&&Ed.prototype,EE=TE&&TE.set,nM=Td.aTypedArray,sM=Td.exportTypedArrayMethod,yd=!gE(function(){var e=new Uint8ClampedArray(2);return fE(EE,e,{length:1,0:3},1),e[1]!==3}),aM=yd&&Td.NATIVE_ARRAY_BUFFER_VIEWS&&gE(function(){var e=new Ed(2);return e.set(1),e.set("2",1),e[0]!==0||e[1]!==2});sM("set",function(e){nM(this);var t=tM(arguments.length>1?arguments[1]:void 0,1),i=iM(e);if(yd)return fE(EE,this,i,t);var r=this.length,n=eM(i),s=0;if(n+t>r)throw rM("Wrong length");for(;s<n;)this[t+s]=i[s++]},!yd||aM);var yE=Zt.match(/firefox\/(\d+)/i),SE=!!yE&&+yE[1],vE=/MSIE|Trident/.test(Zt),IE=Zt.match(/AppleWebKit\/(\d+)\./),AE=!!IE&&+IE[1],oM=jn,Sd=Z,cM=st,lM=Tu,RE=SE,uM=vE,CE=yr,bE=AE,dM=Vt.aTypedArray,hM=Vt.exportTypedArrayMethod,as=te.Uint16Array,en=as&&oM(as.prototype.sort),pM=!(!en||Sd(function(){en(new as(2),null)})&&Sd(function(){en(new as(2),{})})),kE=!!en&&!Sd(function(){if(CE)return CE<74;if(RE)return RE<67;if(uM)return!0;if(bE)return bE<602;var e,t,i=new as(516),r=Array(516);for(e=0;e<516;e++)t=e%4,i[e]=515-e,r[e]=e-2*t+3;for(en(i,function(n,s){return(n/4|0)-(s/4|0)}),e=0;e<516;e++)if(i[e]!==r[e])return!0});hM("sort",function(e){return e!==void 0&&cM(e),kE?en(this,e):lM(dM(this),function(t){return function(i,r){return t!==void 0?+t(i,r)||0:r!=r?-1:i!=i?1:i===0&&r===0?1/i>0&&1/r<0?1:-1:i>r}}(e))},!kE||pM),_o("Float32",function(e){return function(t,i,r){return e(this,t,i,r)}});var mM=ka,vd="ArrayBuffer",NE=po[vd];pe({global:!0,constructor:!0,forced:te[vd]!==NE},{ArrayBuffer:NE}),mM(vd);var _M=pe,fM=Cf,gM=ee([].reverse),DE=[1,2];_M({target:"Array",proto:!0,forced:String(DE)===String(DE.reverse())},{reverse:function(){return fM(this)&&(this.length=this.length),gM(this)}});var wE=vr,TM=TypeError,EM=pe,OE=ee,yM=st,SM=nt,PE=_t,vM=function(e,t){if(!delete e[t])throw TM("Cannot delete property "+wE(t)+" of "+wE(e))},LE=He,Id=Z,IM=Tu,AM=au,ME=SE,RM=vE,xE=yr,VE=AE,hi=[],UE=OE(hi.sort),CM=OE(hi.push),bM=Id(function(){hi.sort(void 0)}),kM=Id(function(){hi.sort(null)}),NM=AM("sort"),FE=!Id(function(){if(xE)return xE<70;if(!(ME&&ME>3)){if(RM)return!0;if(VE)return VE<603;var e,t,i,r,n="";for(e=65;e<76;e++){switch(t=String.fromCharCode(e),e){case 66:case 69:case 70:case 72:i=3;break;case 68:case 71:i=4;break;default:i=2}for(r=0;r<47;r++)hi.push({k:t+r,v:i})}for(hi.sort(function(s,a){return a.v-s.v}),r=0;r<hi.length;r++)t=hi[r].k.charAt(0),n.charAt(n.length-1)!==t&&(n+=t);return n!=="DGBEFHACIJK"}});EM({target:"Array",proto:!0,forced:bM||!kM||!NM||!FE},{sort:function(e){e!==void 0&&yM(e);var t=SM(this);if(FE)return e===void 0?UE(t):UE(t,e);var i,r,n=[],s=PE(t);for(r=0;r<s;r++)r in t&&CM(n,t[r]);for(IM(n,function(a){return function(c,o){return o===void 0?-1:c===void 0?1:a!==void 0?+a(c,o)||0:LE(c)>LE(o)?1:-1}}(e)),i=PE(n),r=0;r<i;)t[r]=n[r++];for(;r<s;)vM(t,r++);return t}});var DM=pe,wM=le,Ad=ee,BE=Xt,OM=ie,PM=Er,LM=cf,os=He,MM=bn,xM=df,VM=Hf,UM=ce("replace"),FM=TypeError,HE=Ad("".indexOf);Ad("".replace);var jE=Ad("".slice),BM=Math.max,GE=function(e,t,i){return i>e.length?-1:t===""?i:HE(e,t,i)};DM({target:"String",proto:!0},{replaceAll:function(e,t){var i,r,n,s,a,c,o,l,d=BE(this),u=0,p=0,m="";if(!PM(e)){if(LM(e)&&(i=os(BE(xM(e))),!~HE(i,"g")))throw FM("`.replaceAll` does not allow non-global regexes");if(r=MM(e,UM))return wM(r,e,d,t)}for(n=os(d),s=os(e),(a=OM(t))||(t=os(t)),c=s.length,o=BM(1,c),u=GE(n,s,0);u!==-1;)l=a?os(t(s,u,n)):VM(s,n,u,[],void 0,t),m+=jE(n,p,u)+l,p=u+c,u=GE(n,s,u+o);return p<n.length&&(m+=jE(n,p)),m}}),(0,Vt.exportTypedArrayStaticMethod)("from",YT,zT);let WE=!0,JE=!0;function So(e,t,i){const r=e.match(t);return r&&r.length>=i&&parseInt(r[i],10)}function qi(e,t,i){if(!e.RTCPeerConnection)return;const r=e.RTCPeerConnection.prototype,n=r.addEventListener;r.addEventListener=function(a,c){if(a!==t)return n.apply(this,arguments);const o=l=>{const d=i(l);d&&(c.handleEvent?c.handleEvent(d):c(d))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(c,o),n.apply(this,[a,o])};const s=r.removeEventListener;r.removeEventListener=function(a,c){if(a!==t||!this._eventMap||!this._eventMap[t])return s.apply(this,arguments);if(!this._eventMap[t].has(c))return s.apply(this,arguments);const o=this._eventMap[t].get(c);return this._eventMap[t].delete(c),this._eventMap[t].size===0&&delete this._eventMap[t],Object.keys(this._eventMap).length===0&&delete this._eventMap,s.apply(this,[a,o])},Object.defineProperty(r,"on"+t,{get(){return this["_on"+t]},set(a){this["_on"+t]&&(this.removeEventListener(t,this["_on"+t]),delete this["_on"+t]),a&&this.addEventListener(t,this["_on"+t]=a)},enumerable:!0,configurable:!0})}function HM(e){return typeof e!="boolean"?new Error("Argument type: "+typeof e+". Please use a boolean."):(WE=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function jM(e){return typeof e!="boolean"?new Error("Argument type: "+typeof e+". Please use a boolean."):(JE=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function zE(){if(typeof window=="object"){if(WE)return;typeof console<"u"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function Rd(e,t){JE&&console.warn(e+" is deprecated, please use "+t+" instead.")}function KE(e){return Object.prototype.toString.call(e)==="[object Object]"}function qE(e){return KE(e)?Object.keys(e).reduce(function(t,i){const r=KE(e[i]),n=r?qE(e[i]):e[i],s=r&&!Object.keys(n).length;return n===void 0||s?t:Object.assign(t,{[i]:n})},{}):e}function Cd(e,t,i){t&&!i.has(t.id)&&(i.set(t.id,t),Object.keys(t).forEach(r=>{r.endsWith("Id")?Cd(e,e.get(t[r]),i):r.endsWith("Ids")&&t[r].forEach(n=>{Cd(e,e.get(n),i)})}))}function YE(e,t,i){const r=i?"outbound-rtp":"inbound-rtp",n=new Map;if(t===null)return n;const s=[];return e.forEach(a=>{a.type==="track"&&a.trackIdentifier===t.id&&s.push(a)}),s.forEach(a=>{e.forEach(c=>{c.type===r&&c.trackId===a.id&&Cd(e,c,n)})}),n}const QE=zE;function XE(e,t){const i=e&&e.navigator;if(!i.mediaDevices)return;const r=function(a){if(typeof a!="object"||a.mandatory||a.optional)return a;const c={};return Object.keys(a).forEach(o=>{if(o==="require"||o==="advanced"||o==="mediaSource")return;const l=typeof a[o]=="object"?a[o]:{ideal:a[o]};l.exact!==void 0&&typeof l.exact=="number"&&(l.min=l.max=l.exact);const d=function(u,p){return u?u+p.charAt(0).toUpperCase()+p.slice(1):p==="deviceId"?"sourceId":p};if(l.ideal!==void 0){c.optional=c.optional||[];let u={};typeof l.ideal=="number"?(u[d("min",o)]=l.ideal,c.optional.push(u),u={},u[d("max",o)]=l.ideal,c.optional.push(u)):(u[d("",o)]=l.ideal,c.optional.push(u))}l.exact!==void 0&&typeof l.exact!="number"?(c.mandatory=c.mandatory||{},c.mandatory[d("",o)]=l.exact):["min","max"].forEach(u=>{l[u]!==void 0&&(c.mandatory=c.mandatory||{},c.mandatory[d(u,o)]=l[u])})}),a.advanced&&(c.optional=(c.optional||[]).concat(a.advanced)),c},n=function(a,c){if(t.version>=61)return c(a);if((a=JSON.parse(JSON.stringify(a)))&&typeof a.audio=="object"){const o=function(l,d,u){d in l&&!(u in l)&&(l[u]=l[d],delete l[d])};o((a=JSON.parse(JSON.stringify(a))).audio,"autoGainControl","googAutoGainControl"),o(a.audio,"noiseSuppression","googNoiseSuppression"),a.audio=r(a.audio)}if(a&&typeof a.video=="object"){let o=a.video.facingMode;o=o&&(typeof o=="object"?o:{ideal:o});const l=t.version<66;if(o&&(o.exact==="user"||o.exact==="environment"||o.ideal==="user"||o.ideal==="environment")&&(!i.mediaDevices.getSupportedConstraints||!i.mediaDevices.getSupportedConstraints().facingMode||l)){let d;if(delete a.video.facingMode,o.exact==="environment"||o.ideal==="environment"?d=["back","rear"]:o.exact!=="user"&&o.ideal!=="user"||(d=["front"]),d)return i.mediaDevices.enumerateDevices().then(u=>{let p=(u=u.filter(m=>m.kind==="videoinput")).find(m=>d.some(f=>m.label.toLowerCase().includes(f)));return!p&&u.length&&d.includes("back")&&(p=u[u.length-1]),p&&(a.video.deviceId=o.exact?{exact:p.deviceId}:{ideal:p.deviceId}),a.video=r(a.video),QE("chrome: "+JSON.stringify(a)),c(a)})}a.video=r(a.video)}return QE("chrome: "+JSON.stringify(a)),c(a)},s=function(a){return t.version>=64?a:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[a.name]||a.name,message:a.message,constraint:a.constraint||a.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}};if(i.getUserMedia=(function(a,c,o){n(a,l=>{i.webkitGetUserMedia(l,c,d=>{o&&o(s(d))})})}).bind(i),i.mediaDevices.getUserMedia){const a=i.mediaDevices.getUserMedia.bind(i.mediaDevices);i.mediaDevices.getUserMedia=function(c){return n(c,o=>a(o).then(l=>{if(o.audio&&!l.getAudioTracks().length||o.video&&!l.getVideoTracks().length)throw l.getTracks().forEach(d=>{d.stop()}),new DOMException("","NotFoundError");return l},l=>Promise.reject(s(l))))}}}function $E(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function ZE(e){if(typeof e=="object"&&e.RTCPeerConnection&&!("ontrack"in e.RTCPeerConnection.prototype)){Object.defineProperty(e.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(i){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=i)},enumerable:!0,configurable:!0});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=i=>{i.stream.addEventListener("addtrack",r=>{let n;n=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find(a=>a.track&&a.track.id===r.track.id):{track:r.track};const s=new Event("track");s.track=r.track,s.receiver=n,s.transceiver={receiver:n},s.streams=[i.stream],this.dispatchEvent(s)}),i.stream.getTracks().forEach(r=>{let n;n=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find(a=>a.track&&a.track.id===r.id):{track:r};const s=new Event("track");s.track=r,s.receiver=n,s.transceiver={receiver:n},s.streams=[i.stream],this.dispatchEvent(s)})},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else qi(e,"track",t=>(t.transceiver||Object.defineProperty(t,"transceiver",{value:{receiver:t.receiver}}),t))}function ey(e){if(typeof e=="object"&&e.RTCPeerConnection&&!("getSenders"in e.RTCPeerConnection.prototype)&&"createDTMFSender"in e.RTCPeerConnection.prototype){const t=function(n,s){return{track:s,get dtmf(){return this._dtmf===void 0&&(s.kind==="audio"?this._dtmf=n.createDTMFSender(s):this._dtmf=null),this._dtmf},_pc:n}};if(!e.RTCPeerConnection.prototype.getSenders){e.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const n=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(a,c){let o=n.apply(this,arguments);return o||(o=t(this,a),this._senders.push(o)),o};const s=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(a){s.apply(this,arguments);const c=this._senders.indexOf(a);c!==-1&&this._senders.splice(c,1)}}const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(n){this._senders=this._senders||[],i.apply(this,[n]),n.getTracks().forEach(s=>{this._senders.push(t(this,s))})};const r=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(n){this._senders=this._senders||[],r.apply(this,[n]),n.getTracks().forEach(s=>{const a=this._senders.find(c=>c.track===s);a&&this._senders.splice(this._senders.indexOf(a),1)})}}else if(typeof e=="object"&&e.RTCPeerConnection&&"getSenders"in e.RTCPeerConnection.prototype&&"createDTMFSender"in e.RTCPeerConnection.prototype&&e.RTCRtpSender&&!("dtmf"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;e.RTCPeerConnection.prototype.getSenders=function(){const i=t.apply(this,[]);return i.forEach(r=>r._pc=this),i},Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get(){return this._dtmf===void 0&&(this.track.kind==="audio"?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function ty(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[i,r,n]=arguments;if(arguments.length>0&&typeof i=="function")return t.apply(this,arguments);if(t.length===0&&(arguments.length===0||typeof i!="function"))return t.apply(this,[]);const s=function(c){const o={};return c.result().forEach(l=>{const d={id:l.id,timestamp:l.timestamp,type:{localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[l.type]||l.type};l.names().forEach(u=>{d[u]=l.stat(u)}),o[d.id]=d}),o},a=function(c){return new Map(Object.keys(c).map(o=>[o,c[o]]))};if(arguments.length>=2){const c=function(o){r(a(s(o)))};return t.apply(this,[c,i])}return new Promise((c,o)=>{t.apply(this,[function(l){c(a(s(l)))},o])}).then(r,n)}}function iy(e){if(!(typeof e=="object"&&e.RTCPeerConnection&&e.RTCRtpSender&&e.RTCRtpReceiver))return;if(!("getStats"in e.RTCRtpSender.prototype)){const i=e.RTCPeerConnection.prototype.getSenders;i&&(e.RTCPeerConnection.prototype.getSenders=function(){const n=i.apply(this,[]);return n.forEach(s=>s._pc=this),n});const r=e.RTCPeerConnection.prototype.addTrack;r&&(e.RTCPeerConnection.prototype.addTrack=function(){const n=r.apply(this,arguments);return n._pc=this,n}),e.RTCRtpSender.prototype.getStats=function(){const n=this;return this._pc.getStats().then(s=>YE(s,n.track,!0))}}if(!("getStats"in e.RTCRtpReceiver.prototype)){const i=e.RTCPeerConnection.prototype.getReceivers;i&&(e.RTCPeerConnection.prototype.getReceivers=function(){const r=i.apply(this,[]);return r.forEach(n=>n._pc=this),r}),qi(e,"track",r=>(r.receiver._pc=r.srcElement,r)),e.RTCRtpReceiver.prototype.getStats=function(){const r=this;return this._pc.getStats().then(n=>YE(n,r.track,!1))}}if(!("getStats"in e.RTCRtpSender.prototype)||!("getStats"in e.RTCRtpReceiver.prototype))return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof e.MediaStreamTrack){const i=arguments[0];let r,n,s;return this.getSenders().forEach(a=>{a.track===i&&(r?s=!0:r=a)}),this.getReceivers().forEach(a=>(a.track===i&&(n?s=!0:n=a),a.track===i)),s||r&&n?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):r?r.getStats():n?n.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return t.apply(this,arguments)}}function ry(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(s=>this._shimmedLocalStreams[s][0])};const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(s,a){if(!a)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const c=t.apply(this,arguments);return this._shimmedLocalStreams[a.id]?this._shimmedLocalStreams[a.id].indexOf(c)===-1&&this._shimmedLocalStreams[a.id].push(c):this._shimmedLocalStreams[a.id]=[a,c],c};const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(s){this._shimmedLocalStreams=this._shimmedLocalStreams||{},s.getTracks().forEach(o=>{if(this.getSenders().find(l=>l.track===o))throw new DOMException("Track already exists.","InvalidAccessError")});const a=this.getSenders();i.apply(this,arguments);const c=this.getSenders().filter(o=>a.indexOf(o)===-1);this._shimmedLocalStreams[s.id]=[s].concat(c)};const r=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(s){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[s.id],r.apply(this,arguments)};const n=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(s){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},s&&Object.keys(this._shimmedLocalStreams).forEach(a=>{const c=this._shimmedLocalStreams[a].indexOf(s);c!==-1&&this._shimmedLocalStreams[a].splice(c,1),this._shimmedLocalStreams[a].length===1&&delete this._shimmedLocalStreams[a]}),n.apply(this,arguments)}}function ny(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return ry(e);const i=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){const o=i.apply(this);return this._reverseStreams=this._reverseStreams||{},o.map(l=>this._reverseStreams[l.id])};const r=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(o){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},o.getTracks().forEach(l=>{if(this.getSenders().find(d=>d.track===l))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[o.id]){const l=new e.MediaStream(o.getTracks());this._streams[o.id]=l,this._reverseStreams[l.id]=o,o=l}r.apply(this,[o])};const n=e.RTCPeerConnection.prototype.removeStream;function s(o,l){let d=l.sdp;return Object.keys(o._reverseStreams||[]).forEach(u=>{const p=o._reverseStreams[u],m=o._streams[p.id];d=d.replace(new RegExp(m.id,"g"),p.id)}),new RTCSessionDescription({type:l.type,sdp:d})}e.RTCPeerConnection.prototype.removeStream=function(o){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},n.apply(this,[this._streams[o.id]||o]),delete this._reverseStreams[this._streams[o.id]?this._streams[o.id].id:o.id],delete this._streams[o.id]},e.RTCPeerConnection.prototype.addTrack=function(o,l){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const d=[].slice.call(arguments,1);if(d.length!==1||!d[0].getTracks().find(p=>p===o))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");if(this.getSenders().find(p=>p.track===o))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const u=this._streams[l.id];if(u)u.addTrack(o),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{const p=new e.MediaStream([o]);this._streams[l.id]=p,this._reverseStreams[p.id]=l,this.addStream(p)}return this.getSenders().find(p=>p.track===o)},["createOffer","createAnswer"].forEach(function(o){const l=e.RTCPeerConnection.prototype[o],d={[o](){const u=arguments;return arguments.length&&typeof arguments[0]=="function"?l.apply(this,[p=>{const m=s(this,p);u[0].apply(null,[m])},p=>{u[1]&&u[1].apply(null,p)},arguments[2]]):l.apply(this,arguments).then(p=>s(this,p))}};e.RTCPeerConnection.prototype[o]=d[o]});const a=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=function(o,l){let d=l.sdp;return Object.keys(o._reverseStreams||[]).forEach(u=>{const p=o._reverseStreams[u],m=o._streams[p.id];d=d.replace(new RegExp(p.id,"g"),m.id)}),new RTCSessionDescription({type:l.type,sdp:d})}(this,arguments[0]),a.apply(this,arguments)):a.apply(this,arguments)};const c=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get(){const o=c.get.apply(this);return o.type===""?o:s(this,o)}}),e.RTCPeerConnection.prototype.removeTrack=function(o){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!o._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(o._pc!==this)throw new DOMException("Sender was not created by this connection.","InvalidAccessError");let l;this._streams=this._streams||{},Object.keys(this._streams).forEach(d=>{this._streams[d].getTracks().find(u=>o.track===u)&&(l=this._streams[d])}),l&&(l.getTracks().length===1?this.removeStream(this._reverseStreams[l.id]):l.removeTrack(o.track),this.dispatchEvent(new Event("negotiationneeded")))}}function bd(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(i){const r=e.RTCPeerConnection.prototype[i],n={[i](){return arguments[0]=new(i==="addIceCandidate"?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),r.apply(this,arguments)}};e.RTCPeerConnection.prototype[i]=n[i]})}function sy(e,t){qi(e,"negotiationneeded",i=>{const r=i.target;if(!(t.version<72||r.getConfiguration&&r.getConfiguration().sdpSemantics==="plan-b")||r.signalingState==="stable")return i})}var ay=Object.freeze({__proto__:null,shimMediaStream:$E,shimOnTrack:ZE,shimGetSendersWithDtmf:ey,shimGetStats:ty,shimSenderReceiverGetStats:iy,shimAddTrackRemoveTrackWithNative:ry,shimAddTrackRemoveTrack:ny,shimPeerConnection:bd,fixNegotiationNeeded:sy,shimGetUserMedia:XE,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&(typeof t=="function"?e.navigator.mediaDevices.getDisplayMedia=function(i){return t(i).then(r=>{const n=i.video&&i.video.width,s=i.video&&i.video.height,a=i.video&&i.video.frameRate;return i.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:r,maxFrameRate:a||3}},n&&(i.video.mandatory.maxWidth=n),s&&(i.video.mandatory.maxHeight=s),e.navigator.mediaDevices.getUserMedia(i)})}:console.error("shimGetDisplayMedia: getSourceId argument is not a function"))}});function oy(e,t){const i=e&&e.navigator,r=e&&e.MediaStreamTrack;if(i.getUserMedia=function(n,s,a){Rd("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),i.mediaDevices.getUserMedia(n).then(s,a)},!(t.version>55&&"autoGainControl"in i.mediaDevices.getSupportedConstraints())){const n=function(a,c,o){c in a&&!(o in a)&&(a[o]=a[c],delete a[c])},s=i.mediaDevices.getUserMedia.bind(i.mediaDevices);if(i.mediaDevices.getUserMedia=function(a){return typeof a=="object"&&typeof a.audio=="object"&&(a=JSON.parse(JSON.stringify(a)),n(a.audio,"autoGainControl","mozAutoGainControl"),n(a.audio,"noiseSuppression","mozNoiseSuppression")),s(a)},r&&r.prototype.getSettings){const a=r.prototype.getSettings;r.prototype.getSettings=function(){const c=a.apply(this,arguments);return n(c,"mozAutoGainControl","autoGainControl"),n(c,"mozNoiseSuppression","noiseSuppression"),c}}if(r&&r.prototype.applyConstraints){const a=r.prototype.applyConstraints;r.prototype.applyConstraints=function(c){return this.kind==="audio"&&typeof c=="object"&&(c=JSON.parse(JSON.stringify(c)),n(c,"autoGainControl","mozAutoGainControl"),n(c,"noiseSuppression","mozNoiseSuppression")),a.apply(this,[c])}}}}function cy(e){typeof e=="object"&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function kd(e,t){if(typeof e!="object"||!e.RTCPeerConnection&&!e.mozRTCPeerConnection)return;!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection),t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(n){const s=e.RTCPeerConnection.prototype[n],a={[n](){return arguments[0]=new(n==="addIceCandidate"?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),s.apply(this,arguments)}};e.RTCPeerConnection.prototype[n]=a[n]});const i={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},r=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[n,s,a]=arguments;return r.apply(this,[n||null]).then(c=>{if(t.version<53&&!s)try{c.forEach(o=>{o.type=i[o.type]||o.type})}catch(o){if(o.name!=="TypeError")throw o;c.forEach((l,d)=>{c.set(d,Object.assign({},l,{type:i[l.type]||l.type}))})}return c}).then(s,a)}}function ly(e){if(typeof e!="object"||!e.RTCPeerConnection||!e.RTCRtpSender||e.RTCRtpSender&&"getStats"in e.RTCRtpSender.prototype)return;const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const r=t.apply(this,[]);return r.forEach(n=>n._pc=this),r});const i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){const r=i.apply(this,arguments);return r._pc=this,r}),e.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function uy(e){if(typeof e!="object"||!e.RTCPeerConnection||!e.RTCRtpSender||e.RTCRtpSender&&"getStats"in e.RTCRtpReceiver.prototype)return;const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const i=t.apply(this,[]);return i.forEach(r=>r._pc=this),i}),qi(e,"track",i=>(i.receiver._pc=i.srcElement,i)),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function dy(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(t){Rd("removeStream","removeTrack"),this.getSenders().forEach(i=>{i.track&&t.getTracks().includes(i.track)&&this.removeTrack(i)})})}function hy(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function py(e){if(typeof e!="object"||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.addTransceiver;t&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let i=arguments[1]&&arguments[1].sendEncodings;i===void 0&&(i=[]),i=[...i];const r=i.length>0;r&&i.forEach(s=>{if("rid"in s&&!/^[a-z0-9]{0,16}$/i.test(s.rid))throw new TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in s&&!(parseFloat(s.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in s&&!(parseFloat(s.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});const n=t.apply(this,arguments);if(r){const{sender:s}=n,a=s.getParameters();(!("encodings"in a)||a.encodings.length===1&&Object.keys(a.encodings[0]).length===0)&&(a.encodings=i,s.sendEncodings=i,this.setParametersPromises.push(s.setParameters(a).then(()=>{delete s.sendEncodings}).catch(()=>{delete s.sendEncodings})))}return n})}function my(e){if(typeof e!="object"||!e.RTCRtpSender)return;const t=e.RTCRtpSender.prototype.getParameters;t&&(e.RTCRtpSender.prototype.getParameters=function(){const i=t.apply(this,arguments);return"encodings"in i||(i.encodings=[].concat(this.sendEncodings||[{}])),i})}function _y(e){if(typeof e!="object"||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>t.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):t.apply(this,arguments)}}function fy(e){if(typeof e!="object"||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createAnswer;e.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>t.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):t.apply(this,arguments)}}var gy=Object.freeze({__proto__:null,shimOnTrack:cy,shimPeerConnection:kd,shimSenderGetStats:ly,shimReceiverGetStats:uy,shimRemoveStream:dy,shimRTCDataChannel:hy,shimAddTransceiver:py,shimGetParameters:my,shimCreateOffer:_y,shimCreateAnswer:fy,shimGetUserMedia:oy,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&(e.navigator.mediaDevices.getDisplayMedia=function(i){if(!i||!i.video){const r=new DOMException("getDisplayMedia without video constraints is undefined");return r.name="NotFoundError",r.code=8,Promise.reject(r)}return i.video===!0?i.video={mediaSource:t}:i.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(i)})}});function Ty(e){if(typeof e=="object"&&e.RTCPeerConnection){if("getLocalStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in e.RTCPeerConnection.prototype)){const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addStream=function(i){this._localStreams||(this._localStreams=[]),this._localStreams.includes(i)||this._localStreams.push(i),i.getAudioTracks().forEach(r=>t.call(this,r,i)),i.getVideoTracks().forEach(r=>t.call(this,r,i))},e.RTCPeerConnection.prototype.addTrack=function(i,...r){return r&&r.forEach(n=>{this._localStreams?this._localStreams.includes(n)||this._localStreams.push(n):this._localStreams=[n]}),t.apply(this,arguments)}}"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(t){this._localStreams||(this._localStreams=[]);const i=this._localStreams.indexOf(t);if(i===-1)return;this._localStreams.splice(i,1);const r=t.getTracks();this.getSenders().forEach(n=>{r.includes(n.track)&&this.removeTrack(n)})})}}function Ey(e){if(typeof e=="object"&&e.RTCPeerConnection&&("getRemoteStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in e.RTCPeerConnection.prototype))){Object.defineProperty(e.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(i){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=i),this.addEventListener("track",this._onaddstreampoly=r=>{r.streams.forEach(n=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(n))return;this._remoteStreams.push(n);const s=new Event("addstream");s.stream=n,this.dispatchEvent(s)})})}});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){const i=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(r){r.streams.forEach(n=>{if(i._remoteStreams||(i._remoteStreams=[]),i._remoteStreams.indexOf(n)>=0)return;i._remoteStreams.push(n);const s=new Event("addstream");s.stream=n,i.dispatchEvent(s)})}),t.apply(i,arguments)}}}function yy(e){if(typeof e!="object"||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype,i=t.createOffer,r=t.createAnswer,n=t.setLocalDescription,s=t.setRemoteDescription,a=t.addIceCandidate;t.createOffer=function(o,l){const d=arguments.length>=2?arguments[2]:arguments[0],u=i.apply(this,[d]);return l?(u.then(o,l),Promise.resolve()):u},t.createAnswer=function(o,l){const d=arguments.length>=2?arguments[2]:arguments[0],u=r.apply(this,[d]);return l?(u.then(o,l),Promise.resolve()):u};let c=function(o,l,d){const u=n.apply(this,[o]);return d?(u.then(l,d),Promise.resolve()):u};t.setLocalDescription=c,c=function(o,l,d){const u=s.apply(this,[o]);return d?(u.then(l,d),Promise.resolve()):u},t.setRemoteDescription=c,c=function(o,l,d){const u=a.apply(this,[o]);return d?(u.then(l,d),Promise.resolve()):u},t.addIceCandidate=c}function Sy(e){const t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){const i=t.mediaDevices,r=i.getUserMedia.bind(i);t.mediaDevices.getUserMedia=n=>r(vy(n))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=(function(i,r,n){t.mediaDevices.getUserMedia(i).then(r,n)}).bind(t))}function vy(e){return e&&e.video!==void 0?Object.assign({},e,{video:qE(e.video)}):e}function Iy(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection;e.RTCPeerConnection=function(i,r){if(i&&i.iceServers){const n=[];for(let s=0;s<i.iceServers.length;s++){let a=i.iceServers[s];a.urls===void 0&&a.url?(Rd("RTCIceServer.url","RTCIceServer.urls"),a=JSON.parse(JSON.stringify(a)),a.urls=a.url,delete a.url,n.push(a)):n.push(i.iceServers[s])}i.iceServers=n}return new t(i,r)},e.RTCPeerConnection.prototype=t.prototype,"generateCertificate"in t&&Object.defineProperty(e.RTCPeerConnection,"generateCertificate",{get:()=>t.generateCertificate})}function Ay(e){typeof e=="object"&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function Ry(e){const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(i){if(i){i.offerToReceiveAudio!==void 0&&(i.offerToReceiveAudio=!!i.offerToReceiveAudio);const r=this.getTransceivers().find(s=>s.receiver.track.kind==="audio");i.offerToReceiveAudio===!1&&r?r.direction==="sendrecv"?r.setDirection?r.setDirection("sendonly"):r.direction="sendonly":r.direction==="recvonly"&&(r.setDirection?r.setDirection("inactive"):r.direction="inactive"):i.offerToReceiveAudio!==!0||r||this.addTransceiver("audio",{direction:"recvonly"}),i.offerToReceiveVideo!==void 0&&(i.offerToReceiveVideo=!!i.offerToReceiveVideo);const n=this.getTransceivers().find(s=>s.receiver.track.kind==="video");i.offerToReceiveVideo===!1&&n?n.direction==="sendrecv"?n.setDirection?n.setDirection("sendonly"):n.direction="sendonly":n.direction==="recvonly"&&(n.setDirection?n.setDirection("inactive"):n.direction="inactive"):i.offerToReceiveVideo!==!0||n||this.addTransceiver("video",{direction:"recvonly"})}return t.apply(this,arguments)}}function Cy(e){typeof e!="object"||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var by=Object.freeze({__proto__:null,shimLocalStreamsAPI:Ty,shimRemoteStreamsAPI:Ey,shimCallbacksAPI:yy,shimGetUserMedia:Sy,shimConstraints:vy,shimRTCIceServerUrls:Iy,shimTrackEventTransceiver:Ay,shimCreateOfferLegacy:Ry,shimAudioContext:Cy}),vo={};(function(e){const t={generateIdentifier:function(){return Math.random().toString(36).substring(2,12)}};t.localCName=t.generateIdentifier(),t.splitLines=function(i){return i.trim().split(`
5
+ `).map(r=>r.trim())},t.splitSections=function(i){return i.split(`
6
+ m=`).map((r,n)=>(n>0?"m="+r:r).trim()+`\r
7
+ `)},t.getDescription=function(i){const r=t.splitSections(i);return r&&r[0]},t.getMediaSections=function(i){const r=t.splitSections(i);return r.shift(),r},t.matchPrefix=function(i,r){return t.splitLines(i).filter(n=>n.indexOf(r)===0)},t.parseCandidate=function(i){let r;r=i.indexOf("a=candidate:")===0?i.substring(12).split(" "):i.substring(10).split(" ");const n={foundation:r[0],component:{1:"rtp",2:"rtcp"}[r[1]]||r[1],protocol:r[2].toLowerCase(),priority:parseInt(r[3],10),ip:r[4],address:r[4],port:parseInt(r[5],10),type:r[7]};for(let s=8;s<r.length;s+=2)switch(r[s]){case"raddr":n.relatedAddress=r[s+1];break;case"rport":n.relatedPort=parseInt(r[s+1],10);break;case"tcptype":n.tcpType=r[s+1];break;case"ufrag":n.ufrag=r[s+1],n.usernameFragment=r[s+1];break;default:n[r[s]]===void 0&&(n[r[s]]=r[s+1])}return n},t.writeCandidate=function(i){const r=[];r.push(i.foundation);const n=i.component;n==="rtp"?r.push(1):n==="rtcp"?r.push(2):r.push(n),r.push(i.protocol.toUpperCase()),r.push(i.priority),r.push(i.address||i.ip),r.push(i.port);const s=i.type;return r.push("typ"),r.push(s),s!=="host"&&i.relatedAddress&&i.relatedPort&&(r.push("raddr"),r.push(i.relatedAddress),r.push("rport"),r.push(i.relatedPort)),i.tcpType&&i.protocol.toLowerCase()==="tcp"&&(r.push("tcptype"),r.push(i.tcpType)),(i.usernameFragment||i.ufrag)&&(r.push("ufrag"),r.push(i.usernameFragment||i.ufrag)),"candidate:"+r.join(" ")},t.parseIceOptions=function(i){return i.substring(14).split(" ")},t.parseRtpMap=function(i){let r=i.substring(9).split(" ");const n={payloadType:parseInt(r.shift(),10)};return r=r[0].split("/"),n.name=r[0],n.clockRate=parseInt(r[1],10),n.channels=r.length===3?parseInt(r[2],10):1,n.numChannels=n.channels,n},t.writeRtpMap=function(i){let r=i.payloadType;i.preferredPayloadType!==void 0&&(r=i.preferredPayloadType);const n=i.channels||i.numChannels||1;return"a=rtpmap:"+r+" "+i.name+"/"+i.clockRate+(n!==1?"/"+n:"")+`\r
8
+ `},t.parseExtmap=function(i){const r=i.substring(9).split(" ");return{id:parseInt(r[0],10),direction:r[0].indexOf("/")>0?r[0].split("/")[1]:"sendrecv",uri:r[1],attributes:r.slice(2).join(" ")}},t.writeExtmap=function(i){return"a=extmap:"+(i.id||i.preferredId)+(i.direction&&i.direction!=="sendrecv"?"/"+i.direction:"")+" "+i.uri+(i.attributes?" "+i.attributes:"")+`\r
9
+ `},t.parseFmtp=function(i){const r={};let n;const s=i.substring(i.indexOf(" ")+1).split(";");for(let a=0;a<s.length;a++)n=s[a].trim().split("="),r[n[0].trim()]=n[1];return r},t.writeFmtp=function(i){let r="",n=i.payloadType;if(i.preferredPayloadType!==void 0&&(n=i.preferredPayloadType),i.parameters&&Object.keys(i.parameters).length){const s=[];Object.keys(i.parameters).forEach(a=>{i.parameters[a]!==void 0?s.push(a+"="+i.parameters[a]):s.push(a)}),r+="a=fmtp:"+n+" "+s.join(";")+`\r
10
+ `}return r},t.parseRtcpFb=function(i){const r=i.substring(i.indexOf(" ")+1).split(" ");return{type:r.shift(),parameter:r.join(" ")}},t.writeRtcpFb=function(i){let r="",n=i.payloadType;return i.preferredPayloadType!==void 0&&(n=i.preferredPayloadType),i.rtcpFeedback&&i.rtcpFeedback.length&&i.rtcpFeedback.forEach(s=>{r+="a=rtcp-fb:"+n+" "+s.type+(s.parameter&&s.parameter.length?" "+s.parameter:"")+`\r
11
+ `}),r},t.parseSsrcMedia=function(i){const r=i.indexOf(" "),n={ssrc:parseInt(i.substring(7,r),10)},s=i.indexOf(":",r);return s>-1?(n.attribute=i.substring(r+1,s),n.value=i.substring(s+1)):n.attribute=i.substring(r+1),n},t.parseSsrcGroup=function(i){const r=i.substring(13).split(" ");return{semantics:r.shift(),ssrcs:r.map(n=>parseInt(n,10))}},t.getMid=function(i){const r=t.matchPrefix(i,"a=mid:")[0];if(r)return r.substring(6)},t.parseFingerprint=function(i){const r=i.substring(14).split(" ");return{algorithm:r[0].toLowerCase(),value:r[1].toUpperCase()}},t.getDtlsParameters=function(i,r){return{role:"auto",fingerprints:t.matchPrefix(i+r,"a=fingerprint:").map(t.parseFingerprint)}},t.writeDtlsParameters=function(i,r){let n="a=setup:"+r+`\r
12
+ `;return i.fingerprints.forEach(s=>{n+="a=fingerprint:"+s.algorithm+" "+s.value+`\r
13
+ `}),n},t.parseCryptoLine=function(i){const r=i.substring(9).split(" ");return{tag:parseInt(r[0],10),cryptoSuite:r[1],keyParams:r[2],sessionParams:r.slice(3)}},t.writeCryptoLine=function(i){return"a=crypto:"+i.tag+" "+i.cryptoSuite+" "+(typeof i.keyParams=="object"?t.writeCryptoKeyParams(i.keyParams):i.keyParams)+(i.sessionParams?" "+i.sessionParams.join(" "):"")+`\r
14
+ `},t.parseCryptoKeyParams=function(i){if(i.indexOf("inline:")!==0)return null;const r=i.substring(7).split("|");return{keyMethod:"inline",keySalt:r[0],lifeTime:r[1],mkiValue:r[2]?r[2].split(":")[0]:void 0,mkiLength:r[2]?r[2].split(":")[1]:void 0}},t.writeCryptoKeyParams=function(i){return i.keyMethod+":"+i.keySalt+(i.lifeTime?"|"+i.lifeTime:"")+(i.mkiValue&&i.mkiLength?"|"+i.mkiValue+":"+i.mkiLength:"")},t.getCryptoParameters=function(i,r){return t.matchPrefix(i+r,"a=crypto:").map(t.parseCryptoLine)},t.getIceParameters=function(i,r){const n=t.matchPrefix(i+r,"a=ice-ufrag:")[0],s=t.matchPrefix(i+r,"a=ice-pwd:")[0];return n&&s?{usernameFragment:n.substring(12),password:s.substring(10)}:null},t.writeIceParameters=function(i){let r="a=ice-ufrag:"+i.usernameFragment+`\r
15
+ a=ice-pwd:`+i.password+`\r
16
+ `;return i.iceLite&&(r+=`a=ice-lite\r
17
+ `),r},t.parseRtpParameters=function(i){const r={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},n=t.splitLines(i)[0].split(" ");r.profile=n[2];for(let a=3;a<n.length;a++){const c=n[a],o=t.matchPrefix(i,"a=rtpmap:"+c+" ")[0];if(o){const l=t.parseRtpMap(o),d=t.matchPrefix(i,"a=fmtp:"+c+" ");switch(l.parameters=d.length?t.parseFmtp(d[0]):{},l.rtcpFeedback=t.matchPrefix(i,"a=rtcp-fb:"+c+" ").map(t.parseRtcpFb),r.codecs.push(l),l.name.toUpperCase()){case"RED":case"ULPFEC":r.fecMechanisms.push(l.name.toUpperCase())}}}t.matchPrefix(i,"a=extmap:").forEach(a=>{r.headerExtensions.push(t.parseExtmap(a))});const s=t.matchPrefix(i,"a=rtcp-fb:* ").map(t.parseRtcpFb);return r.codecs.forEach(a=>{s.forEach(c=>{a.rtcpFeedback.find(o=>o.type===c.type&&o.parameter===c.parameter)||a.rtcpFeedback.push(c)})}),r},t.writeRtpDescription=function(i,r){let n="";n+="m="+i+" ",n+=r.codecs.length>0?"9":"0",n+=" "+(r.profile||"UDP/TLS/RTP/SAVPF")+" ",n+=r.codecs.map(a=>a.preferredPayloadType!==void 0?a.preferredPayloadType:a.payloadType).join(" ")+`\r
18
+ `,n+=`c=IN IP4 0.0.0.0\r
19
+ `,n+=`a=rtcp:9 IN IP4 0.0.0.0\r
20
+ `,r.codecs.forEach(a=>{n+=t.writeRtpMap(a),n+=t.writeFmtp(a),n+=t.writeRtcpFb(a)});let s=0;return r.codecs.forEach(a=>{a.maxptime>s&&(s=a.maxptime)}),s>0&&(n+="a=maxptime:"+s+`\r
21
+ `),r.headerExtensions&&r.headerExtensions.forEach(a=>{n+=t.writeExtmap(a)}),n},t.parseRtpEncodingParameters=function(i){const r=[],n=t.parseRtpParameters(i),s=n.fecMechanisms.indexOf("RED")!==-1,a=n.fecMechanisms.indexOf("ULPFEC")!==-1,c=t.matchPrefix(i,"a=ssrc:").map(p=>t.parseSsrcMedia(p)).filter(p=>p.attribute==="cname"),o=c.length>0&&c[0].ssrc;let l;const d=t.matchPrefix(i,"a=ssrc-group:FID").map(p=>p.substring(17).split(" ").map(m=>parseInt(m,10)));d.length>0&&d[0].length>1&&d[0][0]===o&&(l=d[0][1]),n.codecs.forEach(p=>{if(p.name.toUpperCase()==="RTX"&&p.parameters.apt){let m={ssrc:o,codecPayloadType:parseInt(p.parameters.apt,10)};o&&l&&(m.rtx={ssrc:l}),r.push(m),s&&(m=JSON.parse(JSON.stringify(m)),m.fec={ssrc:o,mechanism:a?"red+ulpfec":"red"},r.push(m))}}),r.length===0&&o&&r.push({ssrc:o});let u=t.matchPrefix(i,"b=");return u.length&&(u=u[0].indexOf("b=TIAS:")===0?parseInt(u[0].substring(7),10):u[0].indexOf("b=AS:")===0?1e3*parseInt(u[0].substring(5),10)*.95-16e3:void 0,r.forEach(p=>{p.maxBitrate=u})),r},t.parseRtcpParameters=function(i){const r={},n=t.matchPrefix(i,"a=ssrc:").map(c=>t.parseSsrcMedia(c)).filter(c=>c.attribute==="cname")[0];n&&(r.cname=n.value,r.ssrc=n.ssrc);const s=t.matchPrefix(i,"a=rtcp-rsize");r.reducedSize=s.length>0,r.compound=s.length===0;const a=t.matchPrefix(i,"a=rtcp-mux");return r.mux=a.length>0,r},t.writeRtcpParameters=function(i){let r="";return i.reducedSize&&(r+=`a=rtcp-rsize\r
22
+ `),i.mux&&(r+=`a=rtcp-mux\r
23
+ `),i.ssrc!==void 0&&i.cname&&(r+="a=ssrc:"+i.ssrc+" cname:"+i.cname+`\r
24
+ `),r},t.parseMsid=function(i){let r;const n=t.matchPrefix(i,"a=msid:");if(n.length===1)return r=n[0].substring(7).split(" "),{stream:r[0],track:r[1]};const s=t.matchPrefix(i,"a=ssrc:").map(a=>t.parseSsrcMedia(a)).filter(a=>a.attribute==="msid");return s.length>0?(r=s[0].value.split(" "),{stream:r[0],track:r[1]}):void 0},t.parseSctpDescription=function(i){const r=t.parseMLine(i),n=t.matchPrefix(i,"a=max-message-size:");let s;n.length>0&&(s=parseInt(n[0].substring(19),10)),isNaN(s)&&(s=65536);const a=t.matchPrefix(i,"a=sctp-port:");if(a.length>0)return{port:parseInt(a[0].substring(12),10),protocol:r.fmt,maxMessageSize:s};const c=t.matchPrefix(i,"a=sctpmap:");if(c.length>0){const o=c[0].substring(10).split(" ");return{port:parseInt(o[0],10),protocol:o[1],maxMessageSize:s}}},t.writeSctpDescription=function(i,r){let n=[];return n=i.protocol!=="DTLS/SCTP"?["m="+i.kind+" 9 "+i.protocol+" "+r.protocol+`\r
25
+ `,`c=IN IP4 0.0.0.0\r
26
+ `,"a=sctp-port:"+r.port+`\r
27
+ `]:["m="+i.kind+" 9 "+i.protocol+" "+r.port+`\r
28
+ `,`c=IN IP4 0.0.0.0\r
29
+ `,"a=sctpmap:"+r.port+" "+r.protocol+` 65535\r
30
+ `],r.maxMessageSize!==void 0&&n.push("a=max-message-size:"+r.maxMessageSize+`\r
31
+ `),n.join("")},t.generateSessionId=function(){return Math.random().toString().substr(2,22)},t.writeSessionBoilerplate=function(i,r,n){let s;const a=r!==void 0?r:2;return s=i||t.generateSessionId(),`v=0\r
32
+ o=`+(n||"thisisadapterortc")+" "+s+" "+a+` IN IP4 127.0.0.1\r
33
+ s=-\r
34
+ t=0 0\r
35
+ `},t.getDirection=function(i,r){const n=t.splitLines(i);for(let s=0;s<n.length;s++)switch(n[s]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return n[s].substring(2)}return r?t.getDirection(r):"sendrecv"},t.getKind=function(i){return t.splitLines(i)[0].split(" ")[0].substring(2)},t.isRejected=function(i){return i.split(" ",2)[1]==="0"},t.parseMLine=function(i){const r=t.splitLines(i)[0].substring(2).split(" ");return{kind:r[0],port:parseInt(r[1],10),protocol:r[2],fmt:r.slice(3).join(" ")}},t.parseOLine=function(i){const r=t.matchPrefix(i,"o=")[0].substring(2).split(" ");return{username:r[0],sessionId:r[1],sessionVersion:parseInt(r[2],10),netType:r[3],addressType:r[4],address:r[5]}},t.isValidSDP=function(i){if(typeof i!="string"||i.length===0)return!1;const r=t.splitLines(i);for(let n=0;n<r.length;n++)if(r[n].length<2||r[n].charAt(1)!=="=")return!1;return!0},e.exports=t})({get exports(){return vo},set exports(e){vo=e}});var tn=vo,GM=Rp({__proto__:null,default:tn},[vo]);function Io(e){if(!e.RTCIceCandidate||e.RTCIceCandidate&&"foundation"in e.RTCIceCandidate.prototype)return;const t=e.RTCIceCandidate;e.RTCIceCandidate=function(i){if(typeof i=="object"&&i.candidate&&i.candidate.indexOf("a=")===0&&((i=JSON.parse(JSON.stringify(i))).candidate=i.candidate.substring(2)),i.candidate&&i.candidate.length){const r=new t(i),n=tn.parseCandidate(i.candidate);for(const s in n)s in r||Object.defineProperty(r,s,{value:n[s]});return r.toJSON=function(){return{candidate:r.candidate,sdpMid:r.sdpMid,sdpMLineIndex:r.sdpMLineIndex,usernameFragment:r.usernameFragment}},r}return new t(i)},e.RTCIceCandidate.prototype=t.prototype,qi(e,"icecandidate",i=>(i.candidate&&Object.defineProperty(i,"candidate",{value:new e.RTCIceCandidate(i.candidate),writable:"false"}),i))}function Nd(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||qi(e,"icecandidate",t=>{if(t.candidate){const i=tn.parseCandidate(t.candidate.candidate);i.type==="relay"&&(t.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[i.priority>>24])}return t})}function Ao(e,t){if(!e.RTCPeerConnection)return;"sctp"in e.RTCPeerConnection.prototype||Object.defineProperty(e.RTCPeerConnection.prototype,"sctp",{get(){return this._sctp===void 0?null:this._sctp}});const i=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,t.browser==="chrome"&&t.version>=76){const{sdpSemantics:r}=this.getConfiguration();r==="plan-b"&&Object.defineProperty(this,"sctp",{get(){return this._sctp===void 0?null:this._sctp},enumerable:!0,configurable:!0})}if(function(r){if(!r||!r.sdp)return!1;const n=tn.splitSections(r.sdp);return n.shift(),n.some(s=>{const a=tn.parseMLine(s);return a&&a.kind==="application"&&a.protocol.indexOf("SCTP")!==-1})}(arguments[0])){const r=function(o){const l=o.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(l===null||l.length<2)return-1;const d=parseInt(l[1],10);return d!=d?-1:d}(arguments[0]),n=function(o){let l=65536;return t.browser==="firefox"&&(l=t.version<57?o===-1?16384:2147483637:t.version<60?t.version===57?65535:65536:2147483637),l}(r),s=function(o,l){let d=65536;t.browser==="firefox"&&t.version===57&&(d=65535);const u=tn.matchPrefix(o.sdp,"a=max-message-size:");return u.length>0?d=parseInt(u[0].substring(19),10):t.browser==="firefox"&&l!==-1&&(d=2147483637),d}(arguments[0],r);let a;a=n===0&&s===0?Number.POSITIVE_INFINITY:n===0||s===0?Math.max(n,s):Math.min(n,s);const c={};Object.defineProperty(c,"maxMessageSize",{get:()=>a}),this._sctp=c}return i.apply(this,arguments)}}function Ro(e){if(!e.RTCPeerConnection||!("createDataChannel"in e.RTCPeerConnection.prototype))return;function t(r,n){const s=r.send;r.send=function(){const a=arguments[0],c=a.length||a.size||a.byteLength;if(r.readyState==="open"&&n.sctp&&c>n.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+n.sctp.maxMessageSize+" bytes)");return s.apply(r,arguments)}}const i=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){const r=i.apply(this,arguments);return t(r,this),r},qi(e,"datachannel",r=>(t(r.channel,r.target),r))}function Dd(e){if(!e.RTCPeerConnection||"connectionState"in e.RTCPeerConnection.prototype)return;const t=e.RTCPeerConnection.prototype;Object.defineProperty(t,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(t,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(i){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),i&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=i)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach(i=>{const r=t[i];t[i]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=n=>{const s=n.target;if(s._lastConnectionState!==s.connectionState){s._lastConnectionState=s.connectionState;const a=new Event("connectionstatechange",n);s.dispatchEvent(a)}return n},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),r.apply(this,arguments)}})}function wd(e,t){if(!e.RTCPeerConnection||t.browser==="chrome"&&t.version>=71||t.browser==="safari"&&t.version>=605)return;const i=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(r){if(r&&r.sdp&&r.sdp.indexOf(`
36
+ a=extmap-allow-mixed`)!==-1){const n=r.sdp.split(`
37
+ `).filter(s=>s.trim()!=="a=extmap-allow-mixed").join(`
38
+ `);e.RTCSessionDescription&&r instanceof e.RTCSessionDescription?arguments[0]=new e.RTCSessionDescription({type:r.type,sdp:n}):r.sdp=n}return i.apply(this,arguments)}}function Co(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const i=e.RTCPeerConnection.prototype.addIceCandidate;i&&i.length!==0&&(e.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?(t.browser==="chrome"&&t.version<78||t.browser==="firefox"&&t.version<68||t.browser==="safari")&&arguments[0]&&arguments[0].candidate===""?Promise.resolve():i.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function bo(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const i=e.RTCPeerConnection.prototype.setLocalDescription;i&&i.length!==0&&(e.RTCPeerConnection.prototype.setLocalDescription=function(){let r=arguments[0]||{};if(typeof r!="object"||r.type&&r.sdp)return i.apply(this,arguments);if(r={type:r.type,sdp:r.sdp},!r.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":r.type="offer";break;default:r.type="answer"}return r.sdp||r.type!=="offer"&&r.type!=="answer"?i.apply(this,[r]):(r.type==="offer"?this.createOffer:this.createAnswer).apply(this).then(n=>i.apply(this,[n]))})}var WM=Object.freeze({__proto__:null,shimRTCIceCandidate:Io,shimRTCIceCandidateRelayProtocol:Nd,shimMaxMessageSize:Ao,shimSendThrowTypeError:Ro,shimConnectionState:Dd,removeExtmapAllowMixed:wd,shimAddIceCandidateNullOrEmpty:Co,shimParameterlessSetLocalDescription:bo});(function({window:e}={},t={shimChrome:!0,shimFirefox:!0,shimSafari:!0}){const i=zE,r=function(s){const a={browser:null,version:null};if(s===void 0||!s.navigator||!s.navigator.userAgent)return a.browser="Not a browser.",a;const{navigator:c}=s;if(c.mozGetUserMedia)a.browser="firefox",a.version=So(c.userAgent,/Firefox\/(\d+)\./,1);else if(c.webkitGetUserMedia||s.isSecureContext===!1&&s.webkitRTCPeerConnection)a.browser="chrome",a.version=So(c.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else{if(!s.RTCPeerConnection||!c.userAgent.match(/AppleWebKit\/(\d+)\./))return a.browser="Not a supported browser.",a;a.browser="safari",a.version=So(c.userAgent,/AppleWebKit\/(\d+)\./,1),a.supportsUnifiedPlan=s.RTCRtpTransceiver&&"currentDirection"in s.RTCRtpTransceiver.prototype}return a}(e),n={browserDetails:r,commonShim:WM,extractVersion:So,disableLog:HM,disableWarnings:jM,sdp:GM};switch(r.browser){case"chrome":if(!ay||!bd||!t.shimChrome)return i("Chrome shim is not included in this adapter release."),n;if(r.version===null)return i("Chrome shim can not determine version, not shimming."),n;i("adapter.js shimming chrome."),n.browserShim=ay,Co(e,r),bo(e),XE(e,r),$E(e),bd(e,r),ZE(e),ny(e,r),ey(e),ty(e),iy(e),sy(e,r),Io(e),Nd(e),Dd(e),Ao(e,r),Ro(e),wd(e,r);break;case"firefox":if(!gy||!kd||!t.shimFirefox)return i("Firefox shim is not included in this adapter release."),n;i("adapter.js shimming firefox."),n.browserShim=gy,Co(e,r),bo(e),oy(e,r),kd(e,r),cy(e),dy(e),ly(e),uy(e),hy(e),py(e),my(e),_y(e),fy(e),Io(e),Dd(e),Ao(e,r),Ro(e);break;case"safari":if(!by||!t.shimSafari)return i("Safari shim is not included in this adapter release."),n;i("adapter.js shimming safari."),n.browserShim=by,Co(e,r),bo(e),Iy(e),Ry(e),yy(e),Ty(e),Ey(e),Ay(e),Sy(e),Cy(e),Io(e),Nd(e),Ao(e,r),Ro(e),wd(e,r);break;default:i("Unsupported browser!")}})({window:typeof window>"u"?void 0:window});var w,JM=Object.create,cs=Object.defineProperty,zM=Object.defineProperties,ky=Object.getOwnPropertyDescriptor,KM=Object.getOwnPropertyDescriptors,qM=Object.getOwnPropertyNames,ko=Object.getOwnPropertySymbols,Ny=Object.getPrototypeOf,Od=Object.prototype.hasOwnProperty,Dy=Object.prototype.propertyIsEnumerable,YM=Reflect.get,Pd=Math.pow,Ld=(e,t,i)=>t in e?cs(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,O=(e,t)=>{for(var i in t||(t={}))Od.call(t,i)&&Ld(e,i,t[i]);if(ko)for(var i of ko(t))Dy.call(t,i)&&Ld(e,i,t[i]);return e},J=(e,t)=>zM(e,KM(t)),Ut=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),ls=(e,t)=>{for(var i in t)cs(e,i,{get:t[i],enumerable:!0})},Ie=(e,t,i)=>(i=e!=null?JM(Ny(e)):{},((r,n,s,a)=>{if(n&&typeof n=="object"||typeof n=="function")for(let c of qM(n))!Od.call(r,c)&&c!==s&&cs(r,c,{get:()=>n[c],enumerable:!(a=ky(n,c))||a.enumerable});return r})(!t&&e&&e.__esModule?i:cs(i,"default",{value:e,enumerable:!0}),e)),k=(e,t,i,r)=>{for(var n,s=ky(t,i),a=e.length-1;a>=0;a--)(n=e[a])&&(s=n(t,i,s)||s);return s&&cs(t,i,s),s},h=(e,t,i)=>(Ld(e,typeof t!="symbol"?t+"":t,i),i),it=(e,t,i)=>YM(Ny(e),i,t),g=(e,t,i)=>new Promise((r,n)=>{var s=o=>{try{c(i.next(o))}catch(l){n(l)}},a=o=>{try{c(i.throw(o))}catch(l){n(l)}},c=o=>o.done?r(o.value):Promise.resolve(o.value).then(s,a);c((i=i.apply(e,t)).next())}),Ve=Ut((e,t)=>{var i=Object.prototype.hasOwnProperty,r="~";function n(){}function s(l,d,u){this.fn=l,this.context=d,this.once=u||!1}function a(l,d,u,p,m){if(typeof u!="function")throw new TypeError("The listener must be a function");var f=new s(u,p||l,m),T=r?r+d:d;return l._events[T]?l._events[T].fn?l._events[T]=[l._events[T],f]:l._events[T].push(f):(l._events[T]=f,l._eventsCount++),l}function c(l,d){--l._eventsCount==0?l._events=new n:delete l._events[d]}function o(){this._events=new n,this._eventsCount=0}Object.create&&(n.prototype=Object.create(null),new n().__proto__||(r=!1)),o.prototype.eventNames=function(){var l,d,u=[];if(this._eventsCount===0)return u;for(d in l=this._events)i.call(l,d)&&u.push(r?d.slice(1):d);return Object.getOwnPropertySymbols?u.concat(Object.getOwnPropertySymbols(l)):u},o.prototype.listeners=function(l){var d=r?r+l:l,u=this._events[d];if(!u)return[];if(u.fn)return[u.fn];for(var p=0,m=u.length,f=new Array(m);p<m;p++)f[p]=u[p].fn;return f},o.prototype.listenerCount=function(l){var d=r?r+l:l,u=this._events[d];return u?u.fn?1:u.length:0},o.prototype.emit=function(l,d,u,p,m,f){var T=r?r+l:l;if(!this._events[T])return!1;var S,y,E=this._events[T],D=arguments.length;if(E.fn){switch(E.once&&this.removeListener(l,E.fn,void 0,!0),D){case 1:return E.fn.call(E.context),!0;case 2:return E.fn.call(E.context,d),!0;case 3:return E.fn.call(E.context,d,u),!0;case 4:return E.fn.call(E.context,d,u,p),!0;case 5:return E.fn.call(E.context,d,u,p,m),!0;case 6:return E.fn.call(E.context,d,u,p,m,f),!0}for(y=1,S=new Array(D-1);y<D;y++)S[y-1]=arguments[y];E.fn.apply(E.context,S)}else{var P,Q=E.length;for(y=0;y<Q;y++)switch(E[y].once&&this.removeListener(l,E[y].fn,void 0,!0),D){case 1:E[y].fn.call(E[y].context);break;case 2:E[y].fn.call(E[y].context,d);break;case 3:E[y].fn.call(E[y].context,d,u);break;case 4:E[y].fn.call(E[y].context,d,u,p);break;default:if(!S)for(P=1,S=new Array(D-1);P<D;P++)S[P-1]=arguments[P];E[y].fn.apply(E[y].context,S)}}return!0},o.prototype.on=function(l,d,u){return a(this,l,d,u,!1)},o.prototype.once=function(l,d,u){return a(this,l,d,u,!0)},o.prototype.removeListener=function(l,d,u,p){var m=r?r+l:l;if(!this._events[m])return this;if(!d)return c(this,m),this;var f=this._events[m];if(f.fn)f.fn===d&&(!p||f.once)&&(!u||f.context===u)&&c(this,m);else{for(var T=0,S=[],y=f.length;T<y;T++)(f[T].fn!==d||p&&!f[T].once||u&&f[T].context!==u)&&S.push(f[T]);S.length?this._events[m]=S.length===1?S[0]:S:c(this,m)}return this},o.prototype.removeAllListeners=function(l){var d;return l?(d=r?r+l:l,this._events[d]&&c(this,d)):(this._events=new n,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=r,o.EventEmitter=o,t!==void 0&&(t.exports=o)}),wy=Ut((e,t)=>{var i=t.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(r){return r.encoding?"rtpmap:%d %s/%s/%s":r.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(r){return r.address!=null?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(r){return r.subtype!=null?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(r){return"extmap:%d"+(r.direction?"/%s":"%v")+(r["encrypt-uri"]?" %s":"%v")+" %s"+(r.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(r){return r.sessionConfig!=null?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(r){var n="candidate:%s %d %s %d %s %d typ %s";return n+=r.raddr!=null?" raddr %s rport %d":"%v%v",n+=r.tcptype!=null?" tcptype %s":"%v",r.generation!=null&&(n+=" generation %d"),n+=r["network-id"]!=null?" network-id %d":"%v",n+=r["network-cost"]!=null?" network-cost %d":"%v"}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(r){var n="ssrc:%d";return r.attribute!=null&&(n+=" %s",r.value!=null&&(n+=":%s")),n}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(r){return r.maxMessageSize!=null?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(r){return r.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(r){return"imageattr:%s %s %s"+(r.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(r){return"simulcast:%s %s"+(r.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(r){return"ts-refclk:%s"+(r.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(r){var n="mediaclk:";return n+=r.id!=null?"id=%s %s":"%v%s",n+=r.mediaClockValue!=null?"=%s":"",n+=r.rateNumerator!=null?" rate=%s":"",n+=r.rateDenominator!=null?"/%s":""}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};Object.keys(i).forEach(function(r){i[r].forEach(function(n){n.reg||(n.reg=/(.*)/),n.format||(n.format="%s")})})}),QM=Ut(e=>{var t=function(a){return String(Number(a))===a?Number(a):a},i=function(a,c,o){var l=a.name&&a.names;a.push&&!c[a.push]?c[a.push]=[]:l&&!c[a.name]&&(c[a.name]={});var d=a.push?{}:l?c[a.name]:c;(function(u,p,m,f){if(f&&!m)p[f]=t(u[1]);else for(var T=0;T<m.length;T+=1)u[T+1]!=null&&(p[m[T]]=t(u[T+1]))})(o.match(a.reg),d,a.names,a.name),a.push&&c[a.push].push(d)},r=wy(),n=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(a){var c={},o=[],l=c;return a.split(/(\r\n|\r|\n)/).filter(n).forEach(function(d){var u=d[0],p=d.slice(2);u==="m"&&(o.push({rtp:[],fmtp:[]}),l=o[o.length-1]);for(var m=0;m<(r[u]||[]).length;m+=1){var f=r[u][m];if(f.reg.test(p))return i(f,l,p)}}),c.media=o,c};var s=function(a,c){var o=c.split(/=(.+)/,2);return o.length===2?a[o[0]]=t(o[1]):o.length===1&&c.length>1&&(a[o[0]]=void 0),a};e.parseParams=function(a){return a.split(/;\s?/).reduce(s,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(a){return a.toString().split(" ").map(Number)},e.parseRemoteCandidates=function(a){for(var c=[],o=a.split(" ").map(t),l=0;l<o.length;l+=3)c.push({component:o[l],ip:o[l+1],port:o[l+2]});return c},e.parseImageAttributes=function(a){return a.split(" ").map(function(c){return c.substring(1,c.length-1).split(",").reduce(s,{})})},e.parseSimulcastStreamList=function(a){return a.split(";").map(function(c){return c.split(",").map(function(o){var l,d=!1;return o[0]!=="~"?l=t(o):(l=t(o.substring(1,o.length)),d=!0),{scid:l,paused:d}})})}}),XM=Ut((e,t)=>{var i=wy(),r=/%[sdv%]/g,n=function(o){var l=1,d=arguments,u=d.length;return o.replace(r,function(p){if(l>=u)return p;var m=d[l];switch(l+=1,p){case"%%":return"%";case"%s":return String(m);case"%d":return Number(m);case"%v":return""}})},s=function(o,l,d){var u=[o+"="+(l.format instanceof Function?l.format(l.push?d:d[l.name]):l.format)];if(l.names)for(var p=0;p<l.names.length;p+=1){var m=l.names[p];l.name?u.push(d[l.name][m]):u.push(d[l.names[p]])}else u.push(d[l.name]);return n.apply(null,u)},a=["v","o","s","i","u","e","p","c","b","t","r","z","a"],c=["i","c","b","a"];t.exports=function(o,l){l=l||{},o.version==null&&(o.version=0),o.name==null&&(o.name=" "),o.media.forEach(function(m){m.payloads==null&&(m.payloads="")});var d=l.outerOrder||a,u=l.innerOrder||c,p=[];return d.forEach(function(m){i[m].forEach(function(f){f.name in o&&o[f.name]!=null?p.push(s(m,f,o)):f.push in o&&o[f.push]!=null&&o[f.push].forEach(function(T){p.push(s(m,f,T))})})}),o.media.forEach(function(m){p.push(s("m",i.m[0],m)),u.forEach(function(f){i[f].forEach(function(T){T.name in m&&m[T.name]!=null?p.push(s(f,T,m)):T.push in m&&m[T.push]!=null&&m[T.push].forEach(function(S){p.push(s(f,T,S))})})})}),p.join(`\r
39
+ `)+`\r
40
+ `}}),$M=Ut(e=>{var t=QM(),i=XM();e.write=i,e.parse=t.parse,e.parseParams=t.parseParams,e.parseFmtpConfig=t.parseFmtpConfig,e.parsePayloads=t.parsePayloads,e.parseRemoteCandidates=t.parseRemoteCandidates,e.parseImageAttributes=t.parseImageAttributes,e.parseSimulcastStreamList=t.parseSimulcastStreamList}),Oy=Ut((e,t)=>{var i=t.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(r){return r.encoding?"rtpmap:%d %s/%s/%s":r.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(r){return r.address!=null?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(r){return r.subtype!=null?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(r){return"extmap:%d"+(r.direction?"/%s":"%v")+(r["encrypt-uri"]?" %s":"%v")+" %s"+(r.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(r){return r.sessionConfig!=null?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(r){var n="candidate:%s %d %s %d %s %d typ %s";return n+=r.raddr!=null?" raddr %s rport %d":"%v%v",n+=r.tcptype!=null?" tcptype %s":"%v",r.generation!=null&&(n+=" generation %d"),n+=r["network-id"]!=null?" network-id %d":"%v",n+=r["network-cost"]!=null?" network-cost %d":"%v"}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(r){var n="ssrc:%d";return r.attribute!=null&&(n+=" %s",r.value!=null&&(n+=":%s")),n}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(r){return r.maxMessageSize!=null?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(r){return r.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(r){return"imageattr:%s %s %s"+(r.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(r){return"simulcast:%s %s"+(r.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(r){return"ts-refclk:%s"+(r.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(r){var n="mediaclk:";return n+=r.id!=null?"id=%s %s":"%v%s",n+=r.mediaClockValue!=null?"=%s":"",n+=r.rateNumerator!=null?" rate=%s":"",n+=r.rateDenominator!=null?"/%s":""}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};Object.keys(i).forEach(function(r){i[r].forEach(function(n){n.reg||(n.reg=/(.*)/),n.format||(n.format="%s")})})}),ZM=Ut(e=>{var t=function(a){return String(Number(a))===a?Number(a):a},i=function(a,c,o){var l=a.name&&a.names;a.push&&!c[a.push]?c[a.push]=[]:l&&!c[a.name]&&(c[a.name]={});var d=a.push?{}:l?c[a.name]:c;(function(u,p,m,f){if(f&&!m)p[f]=t(u[1]);else for(var T=0;T<m.length;T+=1)u[T+1]!=null&&(p[m[T]]=t(u[T+1]))})(o.match(a.reg),d,a.names,a.name),a.push&&c[a.push].push(d)},r=Oy(),n=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(a){var c={},o=[],l=c;return a.split(/(\r\n|\r|\n)/).filter(n).forEach(function(d){var u=d[0],p=d.slice(2);u==="m"&&(o.push({rtp:[],fmtp:[]}),l=o[o.length-1]);for(var m=0;m<(r[u]||[]).length;m+=1){var f=r[u][m];if(f.reg.test(p))return i(f,l,p)}}),c.media=o,c};var s=function(a,c){var o=c.split(/=(.+)/,2);return o.length===2?a[o[0]]=t(o[1]):o.length===1&&c.length>1&&(a[o[0]]=void 0),a};e.parseParams=function(a){return a.split(/;\s?/).reduce(s,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(a){return a.toString().split(" ").map(Number)},e.parseRemoteCandidates=function(a){for(var c=[],o=a.split(" ").map(t),l=0;l<o.length;l+=3)c.push({component:o[l],ip:o[l+1],port:o[l+2]});return c},e.parseImageAttributes=function(a){return a.split(" ").map(function(c){return c.substring(1,c.length-1).split(",").reduce(s,{})})},e.parseSimulcastStreamList=function(a){return a.split(";").map(function(c){return c.split(",").map(function(o){var l,d=!1;return o[0]!=="~"?l=t(o):(l=t(o.substring(1,o.length)),d=!0),{scid:l,paused:d}})})}}),ex=Ut((e,t)=>{var i=Oy(),r=/%[sdv%]/g,n=function(o){var l=1,d=arguments,u=d.length;return o.replace(r,function(p){if(l>=u)return p;var m=d[l];switch(l+=1,p){case"%%":return"%";case"%s":return String(m);case"%d":return Number(m);case"%v":return""}})},s=function(o,l,d){var u=[o+"="+(l.format instanceof Function?l.format(l.push?d:d[l.name]):l.format)];if(l.names)for(var p=0;p<l.names.length;p+=1){var m=l.names[p];l.name?u.push(d[l.name][m]):u.push(d[l.names[p]])}else u.push(d[l.name]);return n.apply(null,u)},a=["v","o","s","i","u","e","p","c","b","t","r","z","a"],c=["i","c","b","a"];t.exports=function(o,l){l=l||{},o.version==null&&(o.version=0),o.name==null&&(o.name=" "),o.media.forEach(function(m){m.payloads==null&&(m.payloads="")});var d=l.outerOrder||a,u=l.innerOrder||c,p=[];return d.forEach(function(m){i[m].forEach(function(f){f.name in o&&o[f.name]!=null?p.push(s(m,f,o)):f.push in o&&o[f.push]!=null&&o[f.push].forEach(function(T){p.push(s(m,f,T))})})}),o.media.forEach(function(m){p.push(s("m",i.m[0],m)),u.forEach(function(f){i[f].forEach(function(T){T.name in m&&m[T.name]!=null?p.push(s(f,T,m)):T.push in m&&m[T.push]!=null&&m[T.push].forEach(function(S){p.push(s(f,T,S))})})})}),p.join(`\r
41
+ `)+`\r
42
+ `}}),Py=Ut(e=>{var t=ZM(),i=ex();e.write=i,e.parse=t.parse,e.parseParams=t.parseParams,e.parseFmtpConfig=t.parseFmtpConfig,e.parsePayloads=t.parsePayloads,e.parseRemoteCandidates=t.parseRemoteCandidates,e.parseImageAttributes=t.parseImageAttributes,e.parseSimulcastStreamList=t.parseSimulcastStreamList}),tx=Ie(Ve()),Ly=((w=Ly||{})[w.INVALID_PARAMETER=4096]="INVALID_PARAMETER",w[w.INVALID_OPERATION=4097]="INVALID_OPERATION",w[w.NOT_SUPPORTED=4098]="NOT_SUPPORTED",w[w.DEVICE_NOT_FOUND=4099]="DEVICE_NOT_FOUND",w[w.INITIALIZE_FAILED=4100]="INITIALIZE_FAILED",w[w.SIGNAL_CHANNEL_SETUP_FAILED=16385]="SIGNAL_CHANNEL_SETUP_FAILED",w[w.SIGNAL_CHANNEL_ERROR=16386]="SIGNAL_CHANNEL_ERROR",w[w.ICE_TRANSPORT_ERROR=16387]="ICE_TRANSPORT_ERROR",w[w.JOIN_ROOM_FAILED=16388]="JOIN_ROOM_FAILED",w[w.CREATE_OFFER_FAILED=16389]="CREATE_OFFER_FAILED",w[w.SIGNAL_CHANNEL_RECONNECTION_FAILED=16390]="SIGNAL_CHANNEL_RECONNECTION_FAILED",w[w.UPLINK_RECONNECTION_FAILED=16391]="UPLINK_RECONNECTION_FAILED",w[w.DOWNLINK_RECONNECTION_FAILED=16392]="DOWNLINK_RECONNECTION_FAILED",w[w.REMOTE_STREAM_NOT_EXIST=16400]="REMOTE_STREAM_NOT_EXIST",w[w.CLIENT_BANNED=16448]="CLIENT_BANNED",w[w.SERVER_TIMEOUT=16449]="SERVER_TIMEOUT",w[w.SUBSCRIPTION_TIMEOUT=16450]="SUBSCRIPTION_TIMEOUT",w[w.PLAY_NOT_ALLOWED=16451]="PLAY_NOT_ALLOWED",w[w.DEVICE_AUTO_RECOVER_FAILED=16452]="DEVICE_AUTO_RECOVER_FAILED",w[w.START_PUBLISH_CDN_FAILED=16453]="START_PUBLISH_CDN_FAILED",w[w.STOP_PUBLISH_CDN_FAILED=16454]="STOP_PUBLISH_CDN_FAILED",w[w.START_MIX_TRANSCODE_FAILED=16455]="START_MIX_TRANSCODE_FAILED",w[w.STOP_MIX_TRANSCODE_FAILED=16456]="STOP_MIX_TRANSCODE_FAILED",w[w.NOT_SUPPORTED_H264=16457]="NOT_SUPPORTED_H264",w[w.SWITCH_ROLE_FAILED=16458]="SWITCH_ROLE_FAILED",w[w.API_CALL_TIMEOUT=16459]="API_CALL_TIMEOUT",w[w.SCHEDULE_FAILED=16460]="SCHEDULE_FAILED",w[w.API_CALL_ABORTED=16461]="API_CALL_ABORTED",w[w.SPC_INITIALIZED_FAILED=16462]="SPC_INITIALIZED_FAILED",w[w.UNKNOWN=65535]="UNKNOWN",w),C=Ly,ix=class extends Error{constructor(e){let{name:t="RtcError",message:i,code:r=C.UNKNOWN,extraCode:n=0,constraint:s}=e,a="<".concat(function(o){for(let l in C)if(C[l]===o)return l;return"UNKNOWN"}(r)," 0x").concat(r.toString(16),">"),c="".concat(i).concat(s?" constraint: ".concat(s):"").concat(i!=null&&i.includes(a)?"":" ".concat(a));super(c),h(this,"code"),h(this,"extraCode"),h(this,"message"),h(this,"originMessage"),h(this,"name"),h(this,"constraint"),this.code=r,this.extraCode=n,this.name=t,this.message=c,this.constraint=s,this.originMessage=i}getCode(){return this.code}getExtraCode(){return this.extraCode}toString(){return this.originMessage}},N=ix,Md=(new Date().getTime(),0),xd=function(){return new Date().getTime()+Md},My=function(){let e=new Date;return e.setTime(xd()),e.toLocaleString()},yt={};ls(yt,{bytes2ms:()=>Gx,convertObjectNumberToInt:()=>kh,copyProperties:()=>jx,deepClone:()=>xs,deepMerge:()=>nr,delay:()=>Nh,fibonacci:()=>Ls,formatedTime:()=>Zx,getAbilityConfigUrl:()=>Fx,getConstructorName:()=>bS,getContainerFromElement:()=>Xx,getEnv:()=>Hx,getInternalVersion:()=>qx,getLoggerUrl:()=>Os,getMuteStateFromFlag:()=>Ms,getNetworkType:()=>vS,getNumNetworkType:()=>Qo,getReconnectionTimeout:()=>ln,getStringByteLength:()=>bh,getTurnServer:()=>Qx,getUint32Version:()=>OS,getValueType:()=>Fe,getViewListFromView:()=>$o,glog:()=>Jx,ipv4ToUint32:()=>Xo,isArray:()=>Ce,isAudioWorkletSupported:()=>Kx,isBoolean:()=>We,isConstructor:()=>Rh,isEmpty:()=>NS,isFunction:()=>ne,isLangChinese:()=>Ti,isMediaStreamTrack:()=>zx,isNumber:()=>ge,isObject:()=>Ei,isOverseaSdkAppId:()=>Yo,isPlainObject:()=>jt,isPortrait:()=>wS,isPromise:()=>Ah,isRemoteTrack:()=>yi,isString:()=>re,isUndefined:()=>I,loadImage:()=>Zo,ms2bytes:()=>Wx,ms2samples:()=>CS,performanceNow:()=>W,promiseAny:()=>Ch,samples2ms:()=>RS,setNetworkType:()=>AS,stringify:()=>Gt,stringifyIncludeValue:()=>DS,throttlePromise:()=>PS});var xy={};ls(xy,{AUDIO_MUTE_BIT:()=>zd,AUDIO_STAT_BIT:()=>ms,AUX_STAT_BIT:()=>Do,AUX_STREAM_MSID:()=>Jy,BACKEND_ENV:()=>Wd,BASE_DOC_URL:()=>Yi,BASE_HOST:()=>Uy,CAPABILITIES_KEYS:()=>Xd,CLASS_NAME:()=>Ix,CLOUD_CONSOLE_URL:()=>ax,DATA_FREEZE_TIMING:()=>qd,DOC_URL:()=>ox,DTLS_STATE_UNKNOWN:()=>mi,ENV_NAME:()=>Qi,EXCHANGE_SDP_TIMEOUT:()=>Xy,INTERVAL:()=>Mo,IS_WORKER:()=>No,IS_WORKLET:()=>Fd,KIBANA_EVENT:()=>Ft,LOCAL_STREAM_PUBLISH_STATE:()=>$y,LOGGER_CMD_TYPE:()=>hs,LOGGER_DOMAIN:()=>Fy,LOGGER_DOMAIN_OVERSEA:()=>By,LOG_LEVEL:()=>pi,LOG_LEVEL_NAME:()=>Rx,MAIN_STREAM_MSID:()=>wo,MICROPHONE_COMMUNICATIONS:()=>Ax,MICROPHONE_DEFAULT:()=>fs,NAME:()=>_,NETWORK_TYPE:()=>Hd,NOT_SUPPORTED_H264:()=>Po,PAUSED_RETRY_COUNT:()=>Zy,PEERCONNECTION_CONNECTING_TIMEOUT:()=>Yd,PEER_CONNECTION_STATE:()=>fe,PEER_LEAVE_REASON:()=>eS,RAF:()=>Qd,RECOVER_CAPTURE_INTERVAL:()=>Ts,REMOTE_STREAM_TYPE_AUX:()=>Ky,REMOTE_STREAM_TYPE_MAIN:()=>zy,RENDER_FREEZE_TIMING:()=>Ex,RIC:()=>Es,SCHEDULE_DOMAIN:()=>It,SCHEDULE_TIMEOUT:()=>vx,SDP_SEMANTICS_PLAN_B:()=>Oo,SDP_SEMANTICS_UNIFIED_PLAN:()=>_s,SECOND_HOST:()=>nx,SIGNAL_PING_PONG_INTERVAL:()=>lx,SIGNAL_PING_TIMEOUT:()=>cx,SIGNAL_RECONNECTION_COUNT:()=>gx,SMALL_STAT_BIT:()=>Jd,SPEAKER_DEFAULT:()=>Lo,STORAGE_EXPIRES_TIME:()=>jy,STREAM_TYPE_BIG:()=>yx,STREAM_TYPE_SMALL:()=>Sx,SUBSCRIBE_SMALL_RETRY_COUNT:()=>gs,SYNC_USER_LIST_INTERVAL:()=>Tx,Scene:()=>Wy,Switch:()=>Gy,THIRD_HOST:()=>sx,TIMEOUT:()=>ys,TRANSPORT_DIRECTION:()=>Y,TRTC_ERROR_ASSISTANCE:()=>Hy,TRTC_QUALITY_BAD:()=>mx,TRTC_QUALITY_DISCONNECTED:()=>fx,TRTC_QUALITY_EXCELLENT:()=>dx,TRTC_QUALITY_GOOD:()=>hx,TRTC_QUALITY_POOR:()=>px,TRTC_QUALITY_UNKNOWN:()=>ux,TRTC_QUALITY_VERY_BAD:()=>_x,UPDATE_OFFER_TIMEOUT:()=>Qy,VIDEO_MUTE_BIT:()=>Kd,VIDEO_STAT_BIT:()=>ps,audioProfileMap:()=>jd,getRetryCount:()=>rn,getScriptDir:()=>rx,innerVersion:()=>Vd,loggerProxy:()=>Bd,screenProfileMap:()=>Gd,setLoggerProxy:()=>ds,setRetryCount:()=>Yy,setVersion:()=>Vy,version:()=>St,videoProfileMap:()=>vt});var Vd="4.15.00.1600",St="5.0.0";function Vy(e){St=e;let[t,i,r]=e.split(".").map(n=>parseInt(n,10));Vd="".concat(t,".").concat(Math.min(15,i),".").concat(Math.min(15,r),".").concat(i.toString().padStart(2,"0")).concat(r.toString().padStart(2,"0"))}var Ud,us,Ge,No=typeof importScripts<"u",Fd=typeof registerProcessor<"u",rx=()=>{let e=No?self.location.href:document.currentScript.src;return e.substring(0,e.lastIndexOf("/")+1)},Bd="",ds=e=>Bd=e,Uy="web.sdk.qcloud.com",nx="web.sdk.tencent.cn",sx="web.sdk.cloud.tencent.cn",ax="https://console.cloud.tencent.com/trtc",Yi="https://".concat(Uy,"/trtc/webrtc/v5/doc"),ox="".concat(Yi,"/zh-cn/"),Fy="https://yun.tim.qq.com",By="https://apisgp.my-imcloud.com",Hy="trtc_error_assistance",hs={LOG:"jssdk_log",EVENT:"jssdk_event",KEY_POINT:"jssdk_new_endreport",KV_STAT:"jssdk_key_metrics_report"},Qi={QCLOUD:"qcloud",OLD_CLOUD_LADDER:"trtc",WEBRTC:"webrtc"},pi=((Ge=pi||{})[Ge.TRACE=0]="TRACE",Ge[Ge.DEBUG=1]="DEBUG",Ge[Ge.INFO=2]="INFO",Ge[Ge.WARN=3]="WARN",Ge[Ge.ERROR=4]="ERROR",Ge[Ge.NONE=5]="NONE",Ge),cx=18e3,lx=2e3,Hd={unknown:0,wifi:1,"3g":2,"2g":3,"4g":4,wired:5,"5g":6},jy=6048e5,Gy=((us=Gy||{}).USEAINS="useAINS",us.ENABLEDEBUG="enableDebug",us.USEV2="useV2",us.USEWT="useWt",us),jd={standard:{sampleRate:48e3,channelCount:1,bitrate:40},"standard-stereo":{sampleRate:48e3,channelCount:2,bitrate:64},high:{sampleRate:48e3,channelCount:1,bitrate:128},"high-stereo":{sampleRate:48e3,channelCount:2,bitrate:192}},vt={"120p":{width:160,height:120,frameRate:15,bitrate:200},"120p_2":{width:160,height:120,frameRate:15,bitrate:100},"180p":{width:320,height:180,frameRate:15,bitrate:350},"180p_2":{width:320,height:180,frameRate:15,bitrate:150},"240p":{width:320,height:240,frameRate:15,bitrate:400},"240p_2":{width:320,height:240,frameRate:15,bitrate:200},"360p":{width:640,height:360,frameRate:15,bitrate:800},"360p_2":{width:640,height:360,frameRate:15,bitrate:400},"480p":{width:640,height:480,frameRate:15,bitrate:900},"480p_2":{width:640,height:480,frameRate:15,bitrate:500},"720p":{width:1280,height:720,frameRate:15,bitrate:1500},"1080p":{width:1920,height:1080,frameRate:15,bitrate:2e3},"1440p":{width:2560,height:1440,frameRate:30,bitrate:4860},"4K":{width:3840,height:2160,frameRate:30,bitrate:9e3}},Gd={"480p":{width:640,height:480,frameRate:5,bitrate:900},"480p_2":{width:640,height:480,frameRate:30,bitrate:1e3},"720p":{width:1280,height:720,frameRate:5,bitrate:1200},"720p_2":{width:1280,height:720,frameRate:30,bitrate:3e3},"1080p":{width:1920,height:1080,frameRate:5,bitrate:1600},"1080p_2":{width:1920,height:1080,frameRate:30,bitrate:4e3}},_={CANVAS:"canvas",AUDIO:"audio",VIDEO:"video",SCREEN:"screen",SMALL:"small",BIG:"big",AUXILIARY:"auxiliary",SMALL_VIDEO:"smallVideo",FACING_MODE_USER:"user",FACING_MODE_ENVIRONMENT:"environment",MUTE:"mute",UNMUTE:"unmute",ENDED:"ended",PLAYING:"playing",PAUSE:"pause",ERROR:"error",LOADEDDATA:"loadeddata",AUDIO_INPUT:"audioinput",VIDEO_INPUT:"videoinput",DETAIL:"detail",TEXT:"text",MAIN:"main",BACKUP:"backup",BANNED:"banned",KICK:"kick",USER_TIME_OUT:"user_time_out",ROOM_DISBAND:"room_disband",SEI_MESSAGE:"sei-message",ADD:"add",REMOVE:"remove",REPLACE:"replace",TRACK:"track",SUBSCRIBE:"subscribe",UNSUBSCRIBE:"unsubscribe",TRANSCEIVER_DIRECTION_SENDONLY:"sendonly",TRANSCEIVER_DIRECTION_RECVONLY:"recvonly",ENTER_PICTURE_IN_PICTURE:"enterpictureinpicture",LEAVE_PICTURE_IN_PICTURE:"leavepictureinpicture"},Y={INACTIVE:"inactive",SENDONLY:"sendonly",RECVONLY:"recvonly"},Wd={OLD_CLOUD_LADDER:"wss://trtc.rtc.qq.com",WEBRTC:"wss://webrtc.qq.com"},Wy=((Ud=Wy||{}).LIVE="live",Ud.RTC="rtc",Ud),ps=1,Jd=2,Do=4,ms=8,zd=64,Kd=16,wo="5Y2wZK8nANNAoVw6dSAHVjNxrD1ObBM2kBPV",Jy="224d130c-7b5c-415b-aaa2-79c2eb5a6df2",zy=_.MAIN,Ky=_.AUXILIARY,ux=0,dx=1,hx=2,px=3,mx=4,_x=5,fx=6,mi="unknown",fe={NEW:"new",CONNECTING:"connecting",FAILED:"failed",CLOSED:"closed",DISCONNECTED:"disconnected",CONNECTED:"connected",COMPLETED:"completed"},qy=1/0;function Yy(e){qy=e}function rn(){return qy}var Xi,gx=30,Ft={JOIN:"join",DELTA_JOIN:"delta-join",REJOIN:"rejoin",LEAVE:"leave",DELTA_LEAVE:"delta-leave",PUBLISH:"publish",DELTA_PUBLISH:"delta-publish",UNPUBLISH:"unpublish",SUBSCRIBE:"subscribe",UNSUBSCRIBE:"unsubscribe",UPLINK_CONNECTION:"uplink-connection",UPLINK_RECONNECTION:"uplink-reconnection",DOWNLINK_CONNECTION:"downlink-connection",DOWNLINK_RECONNECTION:"downlink-reconnection",ON_TRACK:"ontrack",ICE_CONNECTION_STATE:"iceConnectionState",LOCAL_STREAM_INITIALIZE:"stream-initialize",SIGNAL_CONNECTION:"websocketConnectionState",SIGNAL_RECONNECTION:"websocketReconnectionState",UPDATE_STREAM:"update-stream",RECOVER_LOCAL_AUDIO_TRACK:"recover-local-audio-track",RECOVER_LOCAL_VIDEO_TRACK:"recover-local-video-track",RECOVER_SUBSCRIPTION:"recover-subscription",START_MIX_TRANSCODE:"start-mix-transcode",STOP_MIX_TRANSCODE:"stop-mix-transcode",PLAYER_ERROR:"player-error",SCHEDULE:"schedule",LOAD_WORKLET:"load-worklet",VIDEO_FROZEN_COUNT:"videoFrozenCount",GET_USER_MEDIA_RETRY:"getUserMedia-retry"},Tx=1e4,Qy=1e4,Xy=1e4,_s="unified-plan",Oo="plan-b",Po=1028,$y=((Xi=$y||{})[Xi.UNPUBLISH=-1]="UNPUBLISH",Xi[Xi.PUBLISHING=0]="PUBLISHING",Xi[Xi.PUBLISHED=1]="PUBLISHED",Xi),qd=500,Ex=1e3,yx=_.BIG,Sx=_.SMALL,Yd=1e4,It={MAIN:"schedule.cloud-rtc.com",BACKUP:"schedule.rtc.qcloud.com",MAIN_OVERSEA:"schedule.rtc-web.com",BACKUP_OVERSEA:"schedule.rtc-web.io",MAIN_OVERSEA_OLD:"schedule.rtc.tencentcloud.com",BACKUP_OVERSEA_OLD:"schedule-ecdn.rtc.tencentcloud.com"},vx=2e3,Ix={TRTC:"TRTC",CLIENT:"Client",LOCAL_STREAM:"LocalStream",REMOTE_STREAM:"RemoteStream",STREAM:"Stream"},Zy=5,fs="default",Lo=fs,Ax="communications",Rx=Object.keys(pi),eS=["normal leave","timeout leave","kick","role change"],gs=10,Ts=2e3,Es="ric",Qd="raf",Mo="interval",ys="timeout",Xd=["width","height","frameRate","facingMode","sampleRate","sampleSize","channelCount","deviceId","min","max"];function Ss(e){let{url:t,body:i,method:r,timeout:n}=e,s=new XMLHttpRequest;return new Promise((a,c)=>{s.onreadystatechange=()=>{if(s.readyState===4)if(s.status>=200&&s.status<300)try{let o=JSON.parse(s.response);a({data:o})}catch{a({data:s.response})}else c({status:s.status,statusText:s.statusText||"request failed!"})},s.timeout=n||5e3,s.open(r||"POST",t,!0),s.send(i)})}function tS(e){return g(this,null,function*(){let t=W(),i=JSON.stringify(e);try{if(!CompressionStream||i.length<=2800)return i;let r=new Blob([i],{type:"application/json"}).stream().pipeThrough(new CompressionStream("gzip")),n=yield(yield(yield new Response(r)).blob()).arrayBuffer();return b.debug("compressJSON ".concat(i.length," -> ").concat(n.byteLength," ").concat(W()-t,"ms")),n}catch{return i}})}var _i=1e8,B={AVOID_REPEATED_CALL:"AVOID_REPEATED_CALL",INVALID_PARAMETER_REQUIRED:"INVALID_PARAMETER_REQUIRED",INVALID_PARAMETER_TYPE:"INVALID_PARAMETER_TYPE",INVALID_PARAMETER_EMPTY:"INVALID_PARAMETER_EMPTY",INVALID_PARAMETER_INSTANCE:"INVALID_PARAMETER_INSTANCE",INVALID_PARAMETER_RANGE:"INVALID_PARAMETER_RANGE",INVALID_PARAMETER_MIN:"INVALID_PARAMETER_MIN",INVALID_PARAMETER_MAX:"INVALID_PARAMETER_MAX",INVALID_PARAMETER_STREAMTYPE:"INVALID_PARAMETER_STREAMTYPE",API_CALL_TIMEOUT:"API_CALL_TIMEOUT",SIGNAL_CHANNEL_RECONNECTION_FAILED:"SIGNAL_CHANNEL_RECONNECTION_FAILED",SIGNAL_CHANNEL_SETUP_FAILED:"SIGNAL_CHANNEL_SETUP_FAILED",ERROR_MESSAGE:"ERROR_MESSAGE",EXCHANGE_SDP_TIMEOUT:"EXCHANGE_SDP_TIMEOUT",DOWNLINK_RECONNECTION_FAILED:"DOWNLINK_RECONNECTION_FAILED",EXCHANGE_SDP_FAILED:"EXCHANGE_SDP_FAILED",UPDATE_OFFER_TIMEOUT:"UPDATE_OFFER_TIMEOUT",UPLINK_RECONNECTION_FAILED:"UPLINK_RECONNECTION_FAILED",INVALID_RECORDID:"INVALID_RECORDID",INVALID_PURE_AUDIO:"INVALID_PURE_AUDIO",INVALID_STREAMID:"INVALID_STREAMID",INVALID_USER_DEFINE_RECORDID:"INVALID_USER_DEFINE_RECORDID",INVALID_USER_DEFINE_PUSH_ARGS:"INVALID_USER_DEFINE_PUSH_ARGS",INVALID_PROXY:"INVALID_PROXY",INVALID_JOIN:"INVALID_JOIN",INVALID_ROOMID_STRING:"INVALID_ROOMID_STRING",INVALID_ROOMID_INTEGER:"INVALID_ROOMID_INTEGER",INVALID_SIGNAL_CHANNEL:"INVALID_SIGNAL_CHANNEL",JOIN_ROOM_TIMEOUT:"JOIN_ROOM_TIMEOUT",JOIN_ROOM_FAILED:"JOIN_ROOM_FAILED",REJOIN_ROOM_FAILED:"REJOIN_ROOM_FAILED",INVALID_DESTROY:"INVALID_DESTROY",INVALID_PUBLISH:"INVALID_PUBLISH",INVALID_UNPUBLISH:"INVALID_UNPUBLISH",INVALID_AUDIENCE:"INVALID_AUDIENCE",INVALID_INITIALIZE:"INVALID_INITIALIZE",INVALID_DUPLICATE_PUBLISHING:"INVALID_DUPLICATE_PUBLISHING",INVALID_SUBSCRIBE_UNDEFINED:"INVALID_SUBSCRIBE_UNDEFINED",INVALID_SUBSCRIBE_LOCAL:"INVALID_SUBSCRIBE_LOCAL",INVALID_REMOTE_STREAM:"INVALID_REMOTE_STREAM",SUBSCRIBE_FAILED:"SUBSCRIBE_FAILED",INVALID_ROLE:"INVALID_ROLE",INVALID_PARAMETER_SWITCH_ROLE:"INVALID_PARAMETER_SWITCH_ROLE",INVALID_OPERATION_SWITCH_ROLE:"INVALID_OPERATION_SWITCH_ROLE",SWITCH_ROLE_TIMEOUT:"SWITCH_ROLE_TIMEOUT",SWITCH_ROLE_FAILED:"SWITCH_ROLE_FAILED",CLIENT_BANNED:"CLIENT_BANNED",INVALID_OPERATION_START_PUBLISH_CDN:"INVALID_OPERATION_START_PUBLISH_CDN",INVALID_OPERATION_STOP_PUBLISH_CDN:"INVALID_OPERATION_STOP_PUBLISH_CDN",INVALID_STREAM_ID:"INVALID_STREAM_ID",START_PUBLISH_CDN_FAILED:"START_PUBLISH_CDN_FAILED",STOP_PUBLISH_CDN_FAILED:"STOP_PUBLISH_CDN_FAILED",START_MIX_TRANSCODE:"START_MIX_TRANSCODE",STOP_MIX_TRANSCODE:"STOP_MIX_TRANSCODE",INVALID_AUDIO_VOLUME:"INVALID_AUDIO_VOLUME",ENABLE_SMALL_STREAM_PUBLISHED:"ENABLE_SMALL_STREAM_PUBLISHED",DISABLE_SMALL_STREAM_PUBLISHED:"DISABLE_SMALL_STREAM_PUBLISHED",NOT_SUPPORTED_SMALL_STREAM:"NOT_SUPPORTED_SMALL_STREAM",INVALID_SMALL_STREAM_PROFILE:"INVALID_SMALL_STREAM_PROFILE",INVALID_PARAMETER_REMOTE_STREAM:"INVALID_PARAMETER_REMOTE_STREAM",INVALID_OPERATION_CHANGE_SMALL:"INVALID_OPERATION_CHANGE_SMALL",REMOTE_NOT_PUBLISH_SMALL_STREAM:"REMOTE_NOT_PUBLISH_SMALL_STREAM",INVALID_SWITCH_DEVICE:"INVALID_SWITCH_DEVICE",INVALID_SWITCH_DEVICE_PUBLISHING:"INVALID_SWITCH_DEVICE_PUBLISHING",INVALID_REPLACE_TRACK:"INVALID_REPLACE_TRACK",INVALID_INITIALIZE_LOCAL_STREAM:"INVALID_INITIALIZE_LOCAL_STREAM",INVALID_ADD_TRACK_REPETITIVE:"INVALID_ADD_TRACK_REPETITIVE",INVALID_ADD_TRACK_REMOVING:"INVALID_ADD_TRACK_REMOVING",INVALID_ADD_TRACK_PUBLISHING:"INVALID_ADD_TRACK_PUBLISHING",INVALID_STREAM_INITIALIZED:"INVALID_STREAM_INITIALIZED",INVALID_ADD_TRACK_NUMBER:"INVALID_ADD_TRACK_NUMBER",INVALID_REMOVE_AUDIO_TRACK:"INVALID_REMOVE_AUDIO_TRACK",INVALID_REMOVE_AUDIO_ADDING:"INVALID_REMOVE_AUDIO_ADDING",INVALID_REMOVE_AUDIO_ON:"INVALID_REMOVE_AUDIO_ON",INVALID_REMOVE_TRACK_PUBLISHING:"INVALID_REMOVE_TRACK_PUBLISHING",INVALID_REMOVE_TRACK_NOT_TRACK:"INVALID_REMOVE_TRACK_NOT_TRACK",INVALID_REMOVE_TRACK_NUMBER:"INVALID_REMOVE_TRACK_NUMBER",INVALID_REPLACE_TRACK_NO_TRACK:"INVALID_REPLACE_TRACK_NO_TRACK",REPEAT_JOIN:"REPEAT_JOIN",CLIENT_DESTROYED:"CLIENT_DESTROYED",NOT_BUG_PACKAGE:"NOT_BUG_PACKAGE",START_MIX_TRANSCODE_FAILED:"START_MIX_TRANSCODE_FAILED",STOP_MIX_TRANSCODE_FAILED:"STOP_MIX_TRANSCODE_FAILED",MIX_TRANSCODE_NOT_STARTED:"MIX_TRANSCODE_NOT_STARTED",CANNOT_LESS_THAN_ZERO:"CANNOT_LESS_THAN_ZERO",MIX_PARAMS_VIDEO_FRAMERATE:"MIX_PARAMS_VIDEO_FRAMERATE",MIX_PARAMS_VIDEO_GOP:"MIX_PARAMS_VIDEO_GOP",MIX_PARAMS_AUDIO_BITRATE:"MIX_PARAMS_AUDIO_BITRATE",MIX_PARAMS_USER_Z_ORDER:"MIX_PARAMS_USER_Z_ORDER",MIX_PARAMS_NOT_SELF:"MIX_PARAMS_NOT_SELF",MIX_PARAMS_USER_STREAM:"MIX_PARAMS_USER_STREAM",INVALID_PLAY:"INVALID_PLAY",INVALID_ELEMENT_ID:"INVALID_ELEMENT_ID",INVALID_ELEMENT_ID_TYPE:"INVALID_ELEMENT_ID_TYPE",PLAY_FAILED:"PLAY_FAILED",INVALID_USERID:"INVALID_USERID",INVALID_CREATE_STREAM_SOURCE:"INVALID_CREATE_STREAM_SOURCE",INVALID_CREATE_STREAM_SCREEN:"INVALID_CREATE_STREAM_SCREEN",INVALID_CREATE_STREAM_AUDIO:"INVALID_CREATE_STREAM_AUDIO",INVALID_CREATE_STREAM_SCREEN_AUDIO:"INVALID_CREATE_STREAM_SCREEN_AUDIO",NOT_SUPPORTED_HTTP:"NOT_SUPPORTED_HTTP",NOT_SUPPORTED_WEBRTC:"NOT_SUPPORTED_WEBRTC",NOT_SUPPORTED_PROFILE:"NOT_SUPPORTED_PROFILE",NOT_SUPPORTED_MEDIA:"NOT_SUPPORTED_MEDIA",NOT_SUPPORTED_H264ENCODE:"NOT_SUPPORTED_H264ENCODE",NOT_SUPPORTED_H264DECODE:"NOT_SUPPORTED_H264DECODE",NOT_SUPPORTED_TRACK:"NOT_SUPPORTED_TRACK",NOT_SUPPORTED_SWITCH_DEVICE:"NOT_SUPPORTED_SWITCH_DEVICE",NOT_SUPPORTED_CAPTURE:"NOT_SUPPORTED_CAPTURE",NOT_SUPPORTED_AUX:"NOT_SUPPORTED_AUX",MICROPHONE_NOT_FOUND:"MICROPHONE_NOT_FOUND",CAMERA_NOT_FOUND:"CAMERA_NOT_FOUND",SIGNAL_RESPONSE_FAILED:"SIGNAL_RESPONSE_FAILED",CATCH_HANDLER_ERROR:"CATCH_HANDLER_ERROR",API_NOT_EXIST:"API_NOT_EXIST",CONNECTION_CLOSED:"CONNECTION_CLOSED",SUBSCRIBE_ALL_FALSE:"SUBSCRIBE_ALL_FALSE",SEI_NOT_SUPPORT:"SEI_NOT_SUPPORT",SEI_DISABLED:"SEI_DISABLED",SEI_BEFORE_PUBLISH:"SEI_BEFORE_PUBLISH",SEI_NOT_VIDEO:"SEI_NOT_VIDEO",CALL_FREQUENCY_LIMIT:"CALL_FREQUENCY_LIMIT",CONNECTION_ABORTED:"CONNECTION_ABORTED",API_CALL_ABORTED:"API_CALL_ABORTED",DUPLICATE_AUX:"DUPLICATE_AUX"},ut={AVOID_REPEATED_CALL:e=>"previous ".concat(e.name,"() is ongoing, please avoid repeated calls."),INVALID_PARAMETER_REQUIRED(e){let{key:t,rule:i,fnName:r,value:n}=e;return"'".concat(t||i.name,"' is a required param when calling ").concat(r,"(), received: ").concat(n,".")},INVALID_PARAMETER_TYPE(e){let{key:t,rule:i,fnName:r,value:n}=e,s="".concat(t||i.name),a="";return a=Array.isArray(i.type)?i.type.join("|"):i.type,"'".concat(s,"' must be type of ").concat(a," when calling ").concat(r,"(), received type: ").concat(Fe(n),".")},INVALID_PARAMETER_EMPTY(e){let{key:t,rule:i,fnName:r,value:n}=e;return"'".concat(t||i.name,"' cannot be '").concat(n,"' when calling ").concat(r,"().")},INVALID_PARAMETER_INSTANCE(e){let{key:t,rule:i,fnName:r,value:n}=e,s="".concat(t||i.name),a="".concat(i.instanceOf.name||i.instanceOf);return"'".concat(s,"' must be instanceof ").concat(a," when calling ").concat(r,"(), received type: ").concat(Fe(n),".")},INVALID_PARAMETER_RANGE(e){let{key:t,rule:i,fnName:r,value:n}=e;return"'".concat(t||i.name,"' must be one of ").concat(i.values.join("|")," when calling ").concat(r,"(), received: ").concat(n,".")},INVALID_PARAMETER_MIN(e){let{key:t,rule:i,fnName:r,value:n}=e;return"the min value of ".concat(t||i.name," is ").concat(i.min,", received: ").concat(n,".")},INVALID_PARAMETER_MAX(e){let{key:t,rule:i,fnName:r,value:n}=e;return"the max value of ".concat(t||i.name," is ").concat(i.max,", received: ").concat(n,".")},API_CALL_TIMEOUT:e=>"".concat(e.commandDesc||e.command," timeout observed."),SIGNAL_CHANNEL_RECONNECTION_FAILED:"signal channel reconnection failed, please check your network.",SIGNAL_CHANNEL_SETUP_FAILED:e=>"SignalChannel setup failure: (errorCode: ".concat(e.errorCode,", errorMsg: ").concat(e.errorMsg," })."),ERROR_MESSAGE(e){let t="".concat(e.type," failed");return e.message&&(t="".concat(t,": ").concat(e.message,".")),t},EXCHANGE_SDP_TIMEOUT:"exchange sdp timeout.",DOWNLINK_RECONNECTION_FAILED:"downlink reconnection failed, please check your network and re-join room.",EXCHANGE_SDP_FAILED:e=>"exchange sdp failed ".concat(e.errMsg,"."),UPDATE_OFFER_TIMEOUT:"update offer timeout observed.",UPLINK_RECONNECTION_FAILED:"uplink reconnection failed, please check your network and publish again.",INVALID_RECORDID:"recordId must be an integer number.",INVALID_PURE_AUDIO:"pureAudioPushMode must be 1 or 2.",INVALID_STREAMID:"streamId must be a sting literal within 64 bytes, and not be empty.",INVALID_USER_DEFINE_RECORDID:"userDefineRecordId must be a sting literal contains (a-zA-Z),(0-9), underline and hyphen, within 64 bytes, and not be empty.",INVALID_USER_DEFINE_PUSH_ARGS:"userDefinePushArgs must be a sting literal within 256 bytes, and not be empty.",INVALID_PROXY:'proxy server url must start with "wss://".',INVALID_JOIN:"duplicate join() called.",INVALID_ROOMID_STRING:e=>"'".concat(e,"' must be validate string when useStringRoomId is true."),INVALID_ROOMID_INTEGER:e=>"'".concat(e,"' must be an integer between [1, 4294967294] when useStringRoomId is false."),INVALID_SIGNAL_CHANNEL:"SignalChannel is not ready yet.",JOIN_ROOM_TIMEOUT:"join room timeout.",JOIN_ROOM_FAILED(e){let{error:t,code:i}=e;return"Failed to join room - ".concat(t," code: ").concat(i)},REJOIN_ROOM_FAILED:e=>"reJoin room: ".concat(e.roomId," failed, please check your network."),INVALID_DESTROY:"please call leave() before destroy().",INVALID_PUBLISH:"please call join() before publish().",INVALID_UNPUBLISH:"stream has not been published yet.",INVALID_AUDIENCE:"no permission to publish() under live/".concat("audience",', please call switchRole("',"anchor",'") firstly before publish().'),INVALID_INITIALIZE:"cannot publish stream because stream is not initialized, is switching device, or has been closed.",INVALID_DUPLICATE_PUBLISHING:e=>"duplicate ".concat(e," stream publishing, please unpublish your prev ").concat(e," stream and then re-publish."),INVALID_SUBSCRIBE_UNDEFINED:"stream is undefined or null.",INVALID_SUBSCRIBE_LOCAL:"stream cannot be LocalStream.",INVALID_REMOTE_STREAM:"remoteStream does not exist because it has been unpublished by remote peer.",SUBSCRIBE_FAILED(e){let{message:t,userId:i,streamType:r}=e;return"failed to subscribe ".concat(i," ").concat(r," stream, reason: ").concat(t,".")},INVALID_ROLE:"switchRole can only be called in live mode.",INVALID_PARAMETER_SWITCH_ROLE:"role could only be set to a value as ".concat("anchor"," or ","audience","."),INVALID_OPERATION_SWITCH_ROLE:"please call join() before switchRole().",SWITCH_ROLE_TIMEOUT:"switchRole timeout.",SWITCH_ROLE_FAILED:e=>"switchRole failed, errCode: ".concat(e.code," errMsg: ").concat(e.message,"."),CLIENT_BANNED:e=>"client was banned because of ".concat(e.message,"."),INVALID_OPERATION_START_PUBLISH_CDN:"please call startPublishCDNStream() after join room and publish the local stream.",INVALID_OPERATION_STOP_PUBLISH_CDN:"please call startPublishCDNStream() before stopPublishCDNStream().",START_PUBLISH_CDN_FAILED:e=>"startPublishCDNStream failed, errMsg: ".concat(e.message,"."),STOP_PUBLISH_CDN_FAILED:e=>"stopPublishCDNStream failed, errMsg: ".concat(e.message,"."),INVALID_STREAM_ID:e=>"'".concat(e,"' can only consist of uppercase and lowercase english letters (a-zA-Z), numbers (0-9), hyphens and underscores."),START_MIX_TRANSCODE:"please call startMixTranscode() after join().",STOP_MIX_TRANSCODE:"please call stopMixTranscode() after startMixTranscode().",INVALID_AUDIO_VOLUME:"interval must be a number.",ENABLE_SMALL_STREAM_PUBLISHED:"Cannot enable small stream after localStream published.",DISABLE_SMALL_STREAM_PUBLISHED:"Cannot disable small stream after localStream published.",NOT_SUPPORTED_SMALL_STREAM:"your browser does not support opening small stream.",INVALID_SMALL_STREAM_PROFILE:"small stream profile is invalid.",INVALID_PARAMETER_REMOTE_STREAM:"remoteStream is invalid.",INVALID_OPERATION_CHANGE_SMALL:"cannot switch to the small stream without subscribing to the video of remoteStream.",REMOTE_NOT_PUBLISH_SMALL_STREAM:"remote peer does not publish small stream.",INVALID_SWITCH_DEVICE:"cannot switch device on current stream.",INVALID_SWITCH_DEVICE_PUBLISHING:"cannot switch device when publishing localStream.",INVALID_REPLACE_TRACK:"cannot replace track when publishing localStream.",INVALID_INITIALIZE_LOCAL_STREAM:"local stream has not initialized yet.",INVALID_ADD_TRACK_REPETITIVE:"previous addTrack is ongoing, please avoid repetitive execution.",INVALID_ADD_TRACK_REMOVING:"cannot add track when a track is removing.",INVALID_ADD_TRACK_PUBLISHING:"cannot add track when publishing localStream.",INVALID_STREAM_INITIALIZED:"your local stream haven't been initialized yet.",INVALID_ADD_TRACK_NUMBER:"a Stream has at most one audio track and one video track.",INVALID_REMOVE_AUDIO_TRACK:"remove audio track is not supported on your browser.",INVALID_REMOVE_AUDIO_ADDING:"cannot remove track when a track is adding.",INVALID_REMOVE_AUDIO_ON:"previous removeTrack is ongoing, please avoid repetitive execution.",INVALID_REMOVE_TRACK_PUBLISHING:"cannot remove track when publishing localStream.",INVALID_REMOVE_TRACK_NOT_TRACK:"localStream has not this track.",INVALID_REMOVE_TRACK_NUMBER:"remove the only video track is not supported, please use replaceTrack or muteVideo.",INVALID_REPLACE_TRACK_NO_TRACK:e=>"cannot replace ".concat(e.kind," track because stream has not ").concat(e.kind," track"),NOT_BUG_PACKAGE:"You need to buy packages, refer to tencent console.",START_MIX_TRANSCODE_FAILED:e=>"startMixTranscode failed, errMsg: ".concat(e.message,"."),STOP_MIX_TRANSCODE_FAILED:e=>"stopMixTranscode failed, errMsg: ".concat(e.message,"."),MIX_TRANSCODE_NOT_STARTED:"mixTranscode has not been started.",CANNOT_LESS_THAN_ZERO(e){let{key:t,rule:i,fnName:r,value:n}=e;return"'".concat(t||i.name,"' cannot be less than 0 when calling ").concat(r,"().")},MIX_PARAMS_VIDEO_FRAMERATE:"'config.videoFramerate' should be an integer between 0 and 30, excluding 0.",MIX_PARAMS_VIDEO_GOP:"'config.videoGOP' should be an integer between 1 and 8.",MIX_PARAMS_AUDIO_BITRATE:"'config.audioBitrate' should be an integer between 32 and 192.",MIX_PARAMS_USER_Z_ORDER:e=>"'".concat(e,"' is required and must be between 1 and 15."),MIX_PARAMS_NOT_SELF:"'config.mixUsers' must contain self.",MIX_PARAMS_USER_STREAM:"'config.videoWidth' and 'config.videoHeight' of output stream should be contain all mix stream.",INVALID_PLAY:"duplicate play() call observed, please stop() firstly.",INVALID_ELEMENT_ID:e=>{let{key:t,fnName:i}=e;return"'".concat(t,"' is not found in the document object when calling ").concat(i,"().")},INVALID_ELEMENT_ID_TYPE:e=>{let{key:t,fnName:i,type:r}=e;return"the element corresponding to '".concat(t,"' must be instanceof HTMLElement when calling ").concat(i,"(), received: ").concat(r,".")},PLAY_FAILED:e=>"".concat(e.media," play failed,browser exception: ").concat(e.error.toString()),INVALID_USERID:"userId cannot be all spaces.",INVALID_CREATE_STREAM_SOURCE:"LocalStream must be created by createStream() with either audio/video or audioSource/videoSource, but can not be mixed with audio/video and audioSource/videoSource.",INVALID_CREATE_STREAM_SCREEN:"screen/video cannot be both true.",INVALID_CREATE_STREAM_AUDIO:"audio/screenAudio cannot be both true.",INVALID_CREATE_STREAM_SCREEN_AUDIO:"when screen is true, screenAudio can be configured.",NOT_SUPPORTED_HTTP:"http protocol does not support the ability to capture microphone, camera and screen. please use https to deploy your page.",NOT_SUPPORTED_WEBRTC:"your browser or environment does not support full WebRTC capabilities.",NOT_SUPPORTED_PROFILE:"your browser does not support setVideoProfile.",NOT_SUPPORTED_MEDIA:"your browser or environment does not support navigator.mediaDevices.",NOT_SUPPORTED_H264ENCODE:"your device does not support H.264 encoding.",NOT_SUPPORTED_H264DECODE:"your device does not support H.264 decoding.",NOT_SUPPORTED_TRACK:e=>"".concat(e,"Track is not supported on your browser."),NOT_SUPPORTED_SWITCH_DEVICE:"switchDevice is not supported on your browser.",NOT_SUPPORTED_CAPTURE:"Your browser or environment does not support screen sharing, please check whether the browser version.",MICROPHONE_NOT_FOUND:"no microphone detected, please check your microphone.",CAMERA_NOT_FOUND:"no camera detected, please check your camera.",SIGNAL_RESPONSE_FAILED:e=>"".concat(e.signalResponse," failed, response code is ").concat(e.code," , errMsg: ").concat(e.message,"."),CATCH_HANDLER_ERROR(e){let{name:t,event:i}=e;return"an error was caught in ".concat(t,".on('").concat(i,"', handler), please check your code in 'handler'.")},API_NOT_EXIST(e){let{name:t}=e;return"experimental api ".concat(t," does not exist.")},REPEAT_JOIN:e=>"[".concat(e,"] is calling client.join api or has already joined room, please avoid repeated join."),CONNECTION_CLOSED:"remoteStream has been unsubscribed or unpublished by remote user.",SUBSCRIBE_ALL_FALSE:"cannot subscribe when both audio & video are false, use client.unsubscribe() instead",CLIENT_DESTROYED(e){let{funName:t}=e;return"failed to call ".concat(t,"() because client was destroyed.")},SEI_NOT_SUPPORT:e=>"not support to sendSEIMessage".concat(e===!1?" without using h264 codec":""),SEI_DISABLED:"SEI is disabled",SEI_BEFORE_PUBLISH:"please call sendSEIMessage() after publish() success",SEI_NOT_VIDEO:"cannot send sei when localStream has not video.",CALL_FREQUENCY_LIMIT:e=>{let{isSize:t,name:i,timesInSecond:r,maxSizeInSecond:n}=e;return"api ".concat(i," call ").concat(t?"size":"times"," is over ").concat(t?"".concat(n," bytes"):r," in a second.")},CONNECTION_ABORTED:e=>"connection aborted due to: ".concat(e),API_CALL_ABORTED(e){let t;return t=e.message.includes("REMOTE_STREAM_NOT_EXIST")?"Subscribe ".concat(e.userId," ").concat(e.streamType," stream aborted, reason: remote user ").concat(e.userId," unpublished stream."):"API aborted, reason: ".concat(e.message),t},DUPLICATE_AUX:"only one auxiliary stream can be published in a room.",NOT_SUPPORTED_AUX:"publish auxiliary stream is not supported on your browser.",INVALID_PARAMETER_STREAMTYPE:e=>"'streamType' is required when 'userId' is not '*', calling ".concat(e,"()")},iS={};ls(iS,{ANDROID_VERSION:()=>eh,CHROME_MAJOR_VERSION:()=>er,CHROME_VERSION:()=>gh,EDGE_VERSION:()=>ih,EDG_MAJOR_VERSION:()=>aS,EDG_VERSION:()=>rh,FIREFOX_MAJOR_VERSION:()=>sS,FIREFOX_VERSION:()=>th,HUAWEI_VERSION:()=>ph,IE_VERSION:()=>Dx,IOS_MAIN_VERSION:()=>Th,IOS_VERSION:()=>tr,IPADQQB_VERSION:()=>dh,IS_ANDROID:()=>Ue,IS_ANDROID_WEBVIEW:()=>Lx,IS_ANY_SAFARI:()=>an,IS_CHROME:()=>qo,IS_CHROME_OS:()=>cS,IS_CHROMIUM_BASE:()=>Zi,IS_EDG:()=>As,IS_EDGE:()=>Is,IS_ELECTRON:()=>Ox,IS_FIREFOX:()=>ue,IS_HEADLESS_CHROME:()=>uS,IS_HUAWEI:()=>Px,IS_HUAWEIBROWSER:()=>Wo,IS_IE:()=>oS,IS_IE8:()=>Nx,IS_IOS:()=>Bt,IS_IOS_13_OR_14:()=>hS,IS_IOS_15_1:()=>dS,IS_IPAD:()=>vs,IS_IPADQQB:()=>Ho,IS_IPAD_PRO:()=>Zd,IS_IPHONE:()=>nn,IS_IPOD:()=>nS,IS_LINUX:()=>jo,IS_LOCAL:()=>on,IS_MAC:()=>$i,IS_MACQQB:()=>Bo,IS_MIBROWSER:()=>Go,IS_MQQB:()=>bs,IS_NATIVE_ANDROID:()=>kx,IS_OLD_ANDROID:()=>bx,IS_OPPOBROWSER:()=>zo,IS_SAFARI:()=>Rt,IS_SAFARI_15_1:()=>Mx,IS_SAMSUNGBROWSER:()=>Jo,IS_SOGOU:()=>Vo,IS_SOGOUM:()=>xo,IS_TBS:()=>At,IS_UCBROWSER:()=>lS,IS_VIVOBROWSER:()=>Ko,IS_WECHAT:()=>Uo,IS_WIN:()=>sn,IS_WQQB:()=>Fo,IS_WX:()=>wx,IS_X5MQQB:()=>Cs,IS_XWEB:()=>Rs,MACQQB_VERSION:()=>uh,MI_VERSION:()=>hh,MQQB_VERSION:()=>ks,OPPO_VERSION:()=>_h,SAFARI_VERSION:()=>Ds,SAMSUNG_VERSION:()=>mh,SOGOUM_VERSION:()=>nh,SOGOU_VERSION:()=>sh,TBS_VERSION:()=>ah,UA_DATA_STRING:()=>Ht,USER_AGENT:()=>dt,VIVO_VERSION:()=>fh,WECHAT_VERSION:()=>ch,WQQB_VERSION:()=>lh,XWEB_VERSION:()=>oh,browserInfo:()=>fi,getBrowserInfo:()=>pS,getChromeMajorVersion:()=>Ns,getDeviceModel:()=>mS,getOSName:()=>yh,getOSString:()=>Sh,getOSType:()=>xx,getTerminalType:()=>fS,getUserAgentData:()=>Eh,isLocalStorageEnabled:()=>ir});var dt=typeof navigator>"u"?"":navigator.userAgent,G=e=>new RegExp(e,"i").test(dt),ye=e=>{if(G(e)){let t=new RegExp("".concat(e,"\\/([\\d.]+)")),i=dt.match(t);if(i&&i[1])return i[1]}return""},$d=e=>{if(G(e)){let t=new RegExp("".concat(e,"\\/(\\d+)")),i=dt.match(t);if(i&&i[1])return parseFloat(i[1])}return NaN},rS=/AppleWebKit\/([\d.]+)/i.exec(dt),Cx=rS?parseFloat(rS[1]):NaN,vs=G("iPad"),Zd=typeof navigator<"u"&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&G("Macintosh"),nn=G("iPhone")&&!vs,nS=G("iPod"),Bt=nn||vs||nS||Zd,Ue=G("Android"),eh=function(){if(Ue){let e=dt.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);if(e){let t=e[1]&&parseFloat(e[1]),i=e[2]&&parseFloat(e[2]);if(t&&i)return parseFloat("".concat(e[1],".").concat(e[2]));if(t)return t}}return NaN}(),bx=Ue&&G("webkit")&&eh<2.3,kx=Ue&&eh<5&&Cx<537,ue=G("Firefox"),th=ye("Firefox"),sS=$d("Firefox"),Is=G("Edge"),ih=ye("Edge"),As=G("Edg"),rh=ye("Edg"),aS=$d("Edg"),xo=G("SogouMobileBrowser"),nh=ye("SogouMobileBrowser"),Vo=G("MetaSr\\s"),sh=ye("MetaSr\\s"),At=G("TBS"),ah=ye("TBS"),Rs=G("XWEB"),oh=ye("XWEB"),Nx=G("MSIE\\s8\\.0"),oS=G("MSIE\\/\\d+"),Dx=function(){if(oS){let e=/MSIE\s(\d+)\.\d/.exec(dt),t=e&&parseFloat(e[1]);return!t&&/Trident\/7.0/i.test(dt)&&/rv:11.0/.test(dt)&&(t=11),t}return NaN}(),Uo=G("(micromessenger|webbrowser)"),ch=ye("MicroMessenger"),Cs=!At&&G("MQQBrowser")&&G("COVC"),bs=!At&&G("MQQBrowser")&&!G("COVC"),ks=bs||Cs?ye("MQQBrowser"):"",Fo=!At&&G(" QQBrowser"),lh=ye(" QQBrowser"),Bo=!At&&G("QQBrowserLite"),uh=ye("QQBrowserLite"),Ho=!At&&G("MQBHD"),dh=ye("MQBHD"),sn=G("Windows"),$i=!Bt&&G("MAC OS X"),jo=!Ue&&G("Linux"),cS=G("CrOS"),wx=G("MicroMessenger"),lS=G("UCBrowser"),Ox=G("Electron"),Go=G("MiuiBrowser"),hh=ye("MiuiBrowser"),Wo=G("HuaweiBrowser"),Px=G("Huawei"),ph=ye("HuaweiBrowser"),Jo=G("SamsungBrowser"),mh=ye("SamsungBrowser"),zo=G("HeyTapBrowser"),_h=ye("HeyTapBrowser"),Ko=G("VivoBrowser"),fh=ye("VivoBrowser"),Ns=()=>$d("Chrome"),Zi=G("Chrome"),qo=!Is&&!Vo&&!xo&&!At&&!Rs&&!As&&!Fo&&!Go&&!Wo&&!Jo&&!zo&&!Ko&&Zi,uS=G("HeadlessChrome"),er=Ns(),gh=ye("Chrome"),Rt=!Zi&&!bs&&!Cs&&!Bo&&!Ho&&G("Safari"),an=Rt||Bt,Ds=ye("Version"),Lx=/Android.*(wv|.0.0.0)/.test(dt),tr=(()=>{if(Zd)return Ds;if(Bt){let e=dt.match(/OS (\d+)_(\d+)/i);if(e&&e[1]){let t=e[1];return e[2]&&(t+=".".concat(e[2])),t}}return""})(),Th=Number(tr.split(".")[0]),Mx=Ds==="15.1",dS=tr==="15.1",hS=(()=>{let e=Number(tr.split(".")[0]);return e===14||e===13})(),on=typeof location<"u"&&(location.protocol==="file:"||location.hostname==="localhost"||location.hostname==="127.0.0.1"),ir=(()=>{let e;return()=>{if(I(e))try{e=!!window.localStorage}catch{e=!1}return e}})(),fi=pS();function pS(){let e=new Map([[ue,["Firefox",th]],[As,["Edg",rh]],[qo,["Chrome",gh]],[Rt,["Safari",Ds]],[At,["TBS",ah]],[Rs,["XWEB",oh]],[Uo&&nn,["WeChat",ch]],[Fo,["QQ(Win)",lh]],[bs,["QQ(Mobile)",ks]],[Cs,["QQ(Mobile X5)",ks]],[Bo,["QQ(Mac)",uh]],[Ho,["QQ(iPad)",dh]],[Go,["MI",hh]],[Wo,["HW",ph]],[Jo,["Samsung",mh]],[zo,["OPPO",_h]],[Ko,["VIVO",fh]],[Is,["EDGE",ih]],[xo,["SogouMobile",nh]],[Vo,["Sogou",sh]]]),t="unknown",i="unknown";return e.has(!0)&&([t,i]=e.get(!0)),{name:t,version:i}}var se=null,Ht="";function Eh(){return g(this,null,function*(){if(se)return se;if(!navigator.userAgentData||!ne(navigator.userAgentData.getHighEntropyValues))return null;try{return(se=yield navigator.userAgentData.getHighEntropyValues(["architecture","bitness","model","platformVersion","fullVersionList"]))&&!Ht&&(Ht="UAData: ".concat(se.platform,"/").concat(se.platformVersion),se.architecture&&se.bitness&&(Ht+=" ".concat(se.architecture,"/").concat(se.bitness)),se.mobile&&(Ht+=" mobile"),se.model&&(Ht+=" model: ".concat(se.model)),se.fullVersionList&&(Ht+=" ".concat(se.fullVersionList.filter(e=>e.brand!=="Not/A)Brand").map(e=>"".concat(e.brand,"/").concat(e.version)).join(",")))),se}catch{return null}})}function mS(){return(se==null?void 0:se.model)||""}var _S=new Map([[Ue,"Android"],[Bt,"iOS"],[sn,"Windows"],[$i,"MacOS"],[jo,"Linux"],[cS,"ChromeOS"]]),yh=function(){return _S.get(!0)?_S.get(!0):se?se.platform:"unknown"},Sh=()=>{let e=yh();return e+="/".concat(fi.name,"/").concat(Rt?fi.version:fi.version.split(".")[0]),se!=null&&se.platformVersion&&(e+="/".concat(se.platformVersion)),se!=null&&se.architecture&&(e+="/".concat(se.architecture)),e};function fS(){return Ue?4:nn?2:vs?3:$i?12:sn?5:jo?13:1}function xx(){return Ue?"Android":nn?"iPhone":vs?"iPad":$i?"Mac":sn?"Windows":jo?"Linux":"unknown"}var gS=(e,t)=>t?"".concat(Yi,"/").concat(e,"/").concat(t):"".concat(Yi,"/").concat(e,"/index.html"),Vx=()=>{if(window.TRTC_ERROR_INFO&&window.TRTC_ERROR_LINK)return{TRTC_ERROR_INFO:window.TRTC_ERROR_INFO,TRTC_ERROR_LINK:window.TRTC_ERROR_LINK};let e=localStorage==null?void 0:localStorage.getItem(Hy);if(e){e=JSON.parse(e);let t=document.createElement("script");t.type="text/javascript",t.text=e.message,document.body.appendChild(t);let i=window.TRTC_ERROR_INFO,r=window.TRTC_ERROR_LINK;return document.body.removeChild(t),{TRTC_ERROR_INFO:i,TRTC_ERROR_LINK:r}}return{}};function j(e){let{key:t,data:i,link:r,addDocLink:n=!0}=e,s="",a="",c="";ne(ut[t])?s=ut[t](i):re(ut[t])&&(s=ut[t]);let{TRTC_ERROR_INFO:o,TRTC_ERROR_LINK:l}=Vx();r?c="".concat(r.className,".html#").concat(r.fnName):l&&l[t]&&(ne(l[t])?c=l[t](i):re(l[t])&&(c=l[t]));let d=s;return Ti()&&(o&&o[t]&&(ne(o[t])?a=o[t](i):re(o[t])&&(a=o[t])),a&&(d=n?"".concat(a,`
43
+ 请查看文档: `).concat(gS("zh-cn",c),`
44
+
45
+ `):"".concat(a,`
46
+
47
+ `),d+=s)),n&&(d+=`
48
+ Refer to: `.concat(gS("en",c),`
49
+ `)),d}var x,ws=function(e){let{retryFunction:t,settings:i,onError:r,onRetrying:n,onRetryFailed:s,onRetrySuccess:a,context:c}=e;return function(){for(var o=arguments.length,l=new Array(o),d=0;d<o;d++)l[d]=arguments[d];let{retries:u=5,timeout:p=1e3}=i,m=0,f=-1,T=0,S=(y,E)=>g(this,null,function*(){let D=c||this;try{let P=yield t.apply(D,l);m>0&&a&&a.call(this,m),m=0,y(P)}catch(P){let Q=()=>{clearTimeout(f),m=0,T=2,E(P)},q=()=>{T!==2&&m<(ne(u)?u():u)?(m++,T=1,ne(n)&&n.call(this,m,Q),f=window.setTimeout(()=>{f=-1,S(y,E)},ne(p)?p(m):p)):(Q(),ne(s)&&s.call(this,P))};ne(r)?r.call(this,{error:P,retry:q,reject:E,retryFuncArgs:l,retriedCount:m}):q()}});return new Promise(S)}},R=new(Ie(Ve(),1)).default,TS=((x=TS||{}).ROOM_DESTROY="1",x.JOIN_START="21",x.JOIN_SCHEDULE_SUCCESS="22",x.JOIN_SIGNAL_CONNECTION_START="23",x.JOIN_SIGNAL_CONNECTION_END="24",x.JOIN_SEND_CMD="25",x.JOIN_RECEIVED_CMD_RES="26",x.JOIN_SUCCESS="27",x.JOIN_FAILED="28",x.LEAVE_START="51",x.LEAVE_SEND_CMD="52",x.LEAVE_SUCCESS="53",x.PUBLISH_START="61",x.SEND_FIRST_VIDEO_FRAME="62",x.PUBLISH_FAILED="63",x.SUBSCRIBE_START="81",x.SUBSCRIBE_SUCCESS="82",x.SUBSCRIBE_FAILED="84",x.UNSUBSCRIBE_SUCCESS="83",x.LOCAL_TRACK_CAPTURE_START="101",x.LOCAL_TRACK_CAPTURE_SUCCESS="102",x.LOCAL_TRACK_CAPTURE_FAILED="103",x.LOCAL_TRACK_PUBLISHED="104",x.LOCAL_TRACK_UNPUBLISHED="105",x.LOCAL_TRACK_REPLACED="106",x.SWITCH_DEVICE_SUCCESS="107",x.TRACK_MUTED="108",x.TRACK_UNMUTED="109",x.REMOTE_TRACK_SUBSCRIBED="110",x.REMOTE_TRACK_UNSUBSCRIBED="111",x.LOCAL_TRACK_RECAPTURE="112",x.PLAY_TRACK_START="151",x.PLAYER_STATE_CHANGED="152",x.VIDEO_LOADED_DATA="153",x.AUTOPLAY_DIALOG_CLICK_CONFIRM="154",x.SIGNAL_CONNECTION_STATE_CHANGED="201",x.PEER_CONNECTION_STATE_CHANGED="202",x.SINGLE_CONNECTION_STAT="203",x.SPC_RECONNECTED="204",x.HEARTBEAT_REPORT="251",x.RECEIVED_PUBLISHED_USER_LIST="252",x.REMOTE_PUBLISH_STATE_CHANGED="253",x.AUDIO_LEVEL_INTERVAL="260",x.NETWORK_QUALITY="261",x.VIDEO_CODEC_IMPLEMENTATION_CHANGED="262",x.QUALITY_LIMITATION_CHANGED="263",x),de=new class{constructor(){this._roomIdMap=new Map,typeof registerProcessor>"u"&&(this._configs={sdkAppId:"",userId:"",version:St,env:Qi.QCLOUD,browserVersion:fi.name+fi.version,ua:navigator.userAgent})}setConfig(e){let{sdkAppId:t,env:i,userId:r,roomId:n}=e;t!==this._configs.sdkAppId&&(this._configs.sdkAppId=String(t)),this._configs.env=i,this._configs.userId=r,this._roomIdMap.set(r,String(n))}logSuccessEvent(e){on||!b.isAbleToUpload||this._configs.env===Qi.QCLOUD&&this.uploadEventToKibana(J(O({},e),{result:"success"}))}logFailedEvent(e){if(on||!b.isAbleToUpload)return;let{eventType:t,code:i,error:r,userId:n}=e,s={roomId:this._roomIdMap.get(n||this._configs.userId),userId:n,eventType:t,result:"failed",code:i||(r==null?void 0:r.extraCode)||(r==null?void 0:r.code)||C.UNKNOWN};this._configs.env===Qi.QCLOUD&&this.uploadEventToKibana(J(O({},s),{error:r}))}uploadEventToKibana(e){let t="stat-".concat(e.eventType,"-").concat(e.result);(e.eventType==="delta-join"||e.eventType==="delta-leave"||e.eventType==="delta-publish")&&(t="".concat(e.eventType,":").concat(e.delta)),this.uploadEvent({log:t,userId:e.userId}),e.result==="failed"&&(t="stat-".concat(e.eventType,"-").concat(e.result,"-").concat(e.code),this.uploadEvent({log:t,userId:e.userId,error:e.error}))}uploadEvent(e){let{log:t,userId:i,error:r}=e,n={timestamp:My(),sdkAppId:this._configs.sdkAppId,userId:i||this._configs.userId,version:St,log:t};r&&(n.errorInfo=r.message,r.stack&&(n.errorInfo+=`
50
+ `.concat(r.stack))),this.sendRequest(Os(this._configs.sdkAppId,hs.LOG),n)}sendRequest(e,t){b.isAbleToUpload?Ss({url:e,body:JSON.stringify(t)}).catch(()=>{}):setTimeout(()=>{this.sendRequest(e,t)},1e3)}},vh=null,Ih=!0;function gi(e){We(e)&&e!==Ih&&(Ih=e,b.info("setIsNeedToSchedule ".concat(e)))}function Ux(e){return g(this,arguments,function(t){let{userId:i,sdkAppId:r,useStringRoomId:n,roomId:s,userSig:a,version:c,frameWorkType:o,role:l,latencyLevel:d}=t;return function*(){if(!Ih&&vh)return{isCached:!0,result:vh};let u={delta:0,count:[1,1],msg:[],detail:[]};try{let p=new FormData;p.append("userId",String(i)),p.append("sdkAppId",String(r)),p.append("isStrGroupId",String(n)),p.append("groupId",String(s)),p.append("sdkVersion",c),p.append("userSig",String(a)),l&&p.append("role",String(l)),d&&p.append("latencyLevel",String(d)),o&&p.append("frameWorkType",String(o));let m=W(),f=yield function(S,y,E){return new Promise((D,P)=>{let Q=null;Ch([SS(q=>y.count[0]=q+1,q=>{let{error:U,retry:Qt,retriedCount:Te,retryFuncArgs:Oi}=q;y.msg[0]=U.message,Q||(Te>=2&&(Oi[0]=cn(E,_.MAIN,!0)),Qt())})(cn(E,_.MAIN),S,{get timeout(){return 1e3*Ls(2+y.count[0])}}),SS(q=>y.count[1]=q+1,q=>{let{error:U,retry:Qt,retriedCount:Te,retryFuncArgs:Oi}=q;y.msg[1]=U.message,Q||(Te>=2&&(Oi[0]=cn(E,_.BACKUP,!0)),Qt())})(cn(E,_.BACKUP),S,{get timeout(){return 1e3*Ls(2+y.count[1])}})]).then(q=>{Q=q,D(Q)}).catch(P)})}(p,u,r);f.config&&(f.config.loggerDomain&&ds(f.config.loggerDomain),We(f.config.scheduleCache)&&gi(!f.config.scheduleCache)),u.delta=W()-m;let T=function(S,y,E){let D=performance.getEntriesByType("resource"),P=cn(S,_.MAIN),Q=cn(S,_.BACKUP),q={totalCost:0,local:0,dns:0,tcp:0,tls:0,request:0,response:0};for(let U of D)if(U.startTime>=E&&(U.name===P||U.name===Q)&&U.transferSize>0){let Qt=U.name===P?_.MAIN:_.BACKUP,Te=Math.round(U.duration),Oi=Math.round(U.domainLookupStart-U.startTime),Nt=Math.round(U.domainLookupEnd-U.domainLookupStart),yI=Math.round(U.requestStart-U.secureConnectionStart),SI=Math.round(U.secureConnectionStart-U.connectStart),vI=Math.round(U.responseStart-U.requestStart),II=Math.round(U.responseEnd-U.responseStart),p1=[Oi,Nt,yI,SI,vI,II];de.uploadEvent({log:"stat-schedule-net:".concat(Te,"(").concat(p1.join("->"),") ").concat(Qt),userId:y}),q=J(O({},q),{totalCost:Te,local:Oi,dns:Nt,tcp:SI,tls:yI,request:vI,response:II});break}return q}(Number(r),i,m);return vh=f,{isCached:!1,result:f,detailCost:T}}catch(p){let m=Ce(p)?p[0]:p,f=ge(m.code)?m.code:0,T="schedule failed".concat(m.message?": ".concat(m.message):""),S=new N({code:C.SCHEDULE_FAILED,extraCode:f,message:j({key:B.JOIN_ROOM_FAILED,data:{error:T,code:f}})});throw b.error(T,f),S}}()})}document&&document.head.insertAdjacentHTML("beforeend",Object.values(It).map(e=>'<link rel="dns-prefetch" href="https://'.concat(e,'">')).join(`\r
51
+ `)),R.on("28",()=>gi(!0)),R.on("63",()=>gi(!0)),R.on("84",()=>gi(!0)),R.on("201",e=>{e.state==="RECONNECTING"&&gi(!0)}),R.on("202",e=>{e.state==="RECONNECTING"&&gi(!0)});var rr={main:"",backup:""};function ES(e){Ce(e)?(rr.main=e[0],rr.backup=e[1]):rr.main=e}function cn(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:_.MAIN,i=arguments.length>2&&arguments[2]!==void 0&&arguments[2];return"https://".concat(rr[t]||yS(e,t,i),"/api/v1/config")}function Fx(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:_.MAIN;return"https://".concat(rr[t]||yS(e,t),"/api/v1/trtcAutoConf")}function yS(e){let t,i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:_.MAIN,r=arguments.length>2&&arguments[2]!==void 0&&arguments[2];return Yo(e)?i===_.MAIN?It.MAIN_OVERSEA:It.BACKUP_OVERSEA:(t=Yo(e)?r?i===_.MAIN?It.MAIN_OVERSEA_OLD:It.BACKUP_OVERSEA_OLD:i===_.MAIN?It.MAIN_OVERSEA:It.BACKUP_OVERSEA:i===_.MAIN?It.MAIN:It.BACKUP,t)}function Bx(e,t,i){return new Promise((r,n)=>{Ss({url:e,body:t,timeout:i.timeout}).then(s=>{s.data.code===0?r(s.data.data):n({code:s.data.code,message:s.data.msg})}).catch(n)})}var SS=(e,t)=>ws({retryFunction:Bx,settings:{retries:3,timeout:0},onError:t,onRetrying:e}),Hx=function(){return new URLSearchParams(location.search).get("trtc_env")||""},Yo=e=>Number(e)<14e8,Os=function(e,t){let i;i=Bd||(Yo(e)?By:Fy);let r=Math.floor(Math.random()*Pd(2,31));return"".concat(i,"/v5/AVQualityReportSvc/C2S?random=").concat(r,"&sdkappid=").concat(e,"&cmdtype=").concat(t)},Ps="unknown";function vS(){if(Ps!=="unknown")return Ps;let{userAgent:e,connection:t}=navigator,i=(e.match(/NetType\/\S+/)||[])[0]||"";i=i.toLowerCase().replace("nettype/",""),i==="3gnet"&&(i="3g");let r=t&&t.type&&t.type.toLowerCase(),n=t&&t.effectiveType&&t.effectiveType.toLowerCase();return n==="slow-2"&&(n="2g"),r&&(Ps=IS(r,n)),Ps}function IS(e,t){if(Hd[e])return e;switch(e){case"cellular":case"wimax":return t||"unknown";case"ethernet":return"wired";default:return"unknown"}}function AS(e){Ps=IS(e)}function Qo(){return Hd[vS()]}function jx(e,t){for(let i of Reflect.ownKeys(t))if(i!=="constructor"&&i!=="prototype"&&i!=="name"){let r=Object.getOwnPropertyDescriptor(t,i)||"";Object.defineProperty(e,i,r)}return e}function Gx(e){return RS(e/4,arguments.length>1&&arguments[1]!==void 0?arguments[1]:48e3)}function RS(e){return 1e3*e/(arguments.length>1&&arguments[1]!==void 0?arguments[1]:48e3)}function Wx(e){return 4*CS(e,arguments.length>1&&arguments[1]!==void 0?arguments[1]:48e3)}function CS(e){return e*(arguments.length>1&&arguments[1]!==void 0?arguments[1]:48e3)/1e3}var Jx=typeof window<"u"&&typeof window.glog=="function"?window.glog:()=>{},Ti=()=>{let e=navigator.language;return e=e.substring(0,2),e==="zh"},jt=function(e){if(!e||typeof e!="object"||Object.prototype.toString.call(e)!="[object Object]")return!1;let t=Object.getPrototypeOf(e);if(t===null)return!0;let i=Object.prototype.hasOwnProperty.call(t,"constructor")&&t.constructor;return typeof i=="function"&&i instanceof i&&Function.prototype.toString.call(i)===Function.prototype.toString.call(Object)};function Ls(e){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1;return e<=1?t:Ls(e-1,t,(arguments.length>1&&arguments[1]!==void 0?arguments[1]:1)+t)}function ln(e){return e>8?3e4:1e3*Ls(e)}function Fe(e){return Reflect.apply(Object.prototype.toString,e,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}var ne=e=>typeof e=="function",I=e=>e===void 0,re=e=>typeof e=="string",ge=e=>typeof e=="number",We=e=>typeof e=="boolean",Ei=e=>Fe(e)==="object",Ce=e=>Fe(e)==="array",zx=e=>Fe(e)==="MediaStreamTrack".toLowerCase(),yi=e=>e.isRemote,Ah=e=>Fe(e)==="promise",Rh=e=>ne(e)&&e.prototype.constructor===e,bS=e=>Rh(e)?e.prototype.constructor.name:"",Kx=typeof AudioWorkletNode<"u";function Ch(e){return new Promise((t,i)=>{let r=[];e.forEach(n=>{n.then(t).catch(s=>{r.push(s),r.length===e.length&&i(r)})})})}function W(){return performance&&performance.now?Math.floor(performance.now()):Date.now()}var kS=e=>+e<10?"0".concat(e):e,qx=e=>{let t=e.match(/^\d+\.\d+\.\d+/)[0];if(!t)return e;let i=t.split("."),r=kS(i[1])+kS(i[2]);return i[1]-15>0&&(i[1]="15"),i[2]-15>0&&(i[2]="15"),"".concat(i.join("."),".").concat(r)},Yx=Object.prototype.hasOwnProperty;function NS(e){if(e==null)return!0;if(typeof e=="boolean")return!1;if(typeof e=="number")return e===0;if(typeof e=="string"||typeof e=="function"||Array.isArray(e))return e.length===0;if(e instanceof Error)return e.message==="";if(jt(e))switch(Object.prototype.toString.call(e)){case"[object File]":case"[object Map]":case"[object Set]":return e.size===0;case"[object Object]":for(let t in e)if(Yx.call(e,t))return!1;return!0}return!1}function Ms(e,t){return{userId:t,hasAudio:!!(e&ms),hasVideo:!!(e&ps),hasAuxiliary:!!(e&Do),hasSmall:!!(e&Jd),audioMuted:!!(e&zd),videoMuted:!!(e&Kd),audioAvailable:!(!(e&ms)||e&zd),videoAvailable:!(!(e&ps)||e&Kd)}}function Qx(e){let t={urls:"turn:".concat(e.url)};return!I(e.username)&&!I(e.credential)&&(t.username=e.username,t.credential=e.credential,t.credentialType="password",I(e.credentialType)||(t.credentialType=e.credentialType)),t}function Xo(e){let t=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];if(!re(e))return 0;let i=e.split(".");return t?(Number(i[0])<<24|Number(i[1])<<16|Number(i[2])<<8|Number(i[3]))>>>0:(Number(i[3])<<24|Number(i[2])<<16|Number(i[1])<<8|Number(i[0]))>>>0}var nr=function(e,t,i,r){if(!Ei(e)||!Ei(t))return 0;let n,s=0,a=Object.keys(t);for(let c=0,o=a.length;c<o;c++)if(n=a[c],!(I(t[n])||i&&i.includes(n)))if(Ei(e[n])&&Ei(t[n]))s+=nr(e[n],t[n],i,r);else{if(r&&r.includes(t[n]))continue;e[n]!==t[n]&&(e[n]=xs(t[n]),s+=1)}return s};function xs(e){if(Ce(e)){let t=[];return e.forEach((i,r)=>{t[r]=xs(i)}),t}if(Ei(e)){let t={};return Object.keys(e).forEach(i=>{t[i]=xs(e[i])}),t}return e}var $o=e=>{let t=[];if(Ce(e))t=[...e];else if(re(e)){let i=document.getElementById(e);i&&t.push(i)}else e&&t.push(e);return t},Xx=e=>re(e)?document.getElementById(e):e,$x=new Intl.DateTimeFormat("zh-CN",{dateStyle:"short",timeStyle:"medium"}),Zx=()=>$x.format(new Date);function Gt(e,t){let{keysToInclude:i,keysToExclude:r}=t;try{if(Ce(e))return"[".concat(e.map(c=>Gt(c,{keysToInclude:i,keysToExclude:r})).join(","),"]");if(!jt(e)||!Ce(i)&&!Ce(r))return JSON.stringify(e);let n={},s=new Set(i),a=new Set(r);return Object.keys(e).forEach(c=>{(a.size===0&&s.has(c)||s.size===0&&!a.has(c))&&(n[c]=jt(e[c])||Ce(e[c])?JSON.parse(Gt(e[c],{keysToExclude:r,keysToInclude:i})):e[c])}),JSON.stringify(n)}catch{return"{}"}}function DS(e){let t=arguments.length>1&&arguments[1]!==void 0&&arguments[1],i=[];return Object.keys(e).forEach(r=>{t===e[r]&&i.push(r)}),Gt(e,{keysToInclude:i})}function bh(e){return e.replace(/[\u4e00-\u9fa5]/g,"aa").length}var wS=()=>{var e,t,i,r;return(e=window.screen)!=null&&e.orientation?!((r=(i=(t=window.screen)==null?void 0:t.orientation)==null?void 0:i.type)==null||!r.includes("portrait")):window.orientation===0||window.orientation===180},Zo=e=>g(void 0,null,function*(){return new Promise((t,i)=>{let r;if(re(e))r=new Image,r.crossOrigin="anonymous",r.src=e;else if(r=e,r.complete)return void t(r);r.onload=()=>t(r),r.onerror=i})}),OS=e=>{let t=e.split(".");return+t[0]<<24|+t[1]<<16|+t[2]<<8|+t[3]},kh=e=>(Object.keys(e).forEach(t=>{ge(e[t])&&(t.startsWith("uint")||t.startsWith("int"))?e[t]=Math.floor(e[t]):(jt(e[t])||Ce(e[t]))&&kh(e[t])}),e);function Nh(e){return new Promise(t=>setTimeout(t,e))}var PS=(e,t)=>{let i=null;return function(){for(var r=arguments.length,n=new Array(r),s=0;s<r;s++)n[s]=arguments[s];return i||(i=e.apply(t||this,n),i.finally(()=>i=null),i)}},eV=Object.prototype.hasOwnProperty,sr=e=>e===void 0;function tV(e){if(e==null)return!0;if(typeof e=="boolean")return!1;if(typeof e=="number")return e===0;if(typeof e=="string"||typeof e=="function"||Array.isArray(e))return e.length===0;if(e instanceof Error)return e.message==="";if(function(t){if(!t||typeof t!="object"||Object.prototype.toString.call(t)!="[object Object]")return!1;let i=Object.getPrototypeOf(t);if(i===null)return!0;let r=Object.prototype.hasOwnProperty.call(i,"constructor")&&i.constructor;return typeof r=="function"&&r instanceof r&&Function.prototype.toString.call(r)===Function.prototype.toString.call(Object)}(e))switch(Object.prototype.toString.call(e)){case"[object File]":case"[object Map]":case"[object Set]":return e.size===0;case"[object Object]":for(let t in e)if(eV.call(e,t))return!1;return!0}return!1}var iV=class{constructor(e){h(this,"userId"),h(this,"remoteUserId"),h(this,"id"),h(this,"sdkAppId"),h(this,"type"),h(this,"isLocal"),this.id=e.id,this.userId=e.userId,this.sdkAppId=e.sdkAppId,this.remoteUserId=e.remoteUserId,this.isLocal=typeof e.isLocal!="boolean"||e.isLocal,this.type=this.isLocal?"":e.type}createChild(e){return Object.setPrototypeOf(e,this)}setUserId(e){this.userId=e}setSdkAppId(e){this.sdkAppId=e}log(e,t){let i=this.isLocal?this.userId:this.remoteUserId;t.unshift("[".concat(this.isLocal?"↑":"↓").concat(this.type&&this.type!=="main"?"*":"").concat(this.id).concat(i?"|".concat(i):"","]")),b.log(e,t,sr(this.userId)||tV(this.userId),this.userId,this.sdkAppId)}info(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];this.log(2,t)}debug(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];this.log(1,t)}warn(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];this.log(3,t)}error(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];this.log(4,t)}},A=TS,rV=!(Bt||Ue||uS),b=new class{constructor(){h(this,"_isEnableUploadLog",!0),h(this,"_localJoinedUser",new Map),h(this,"_queue",[]),h(this,"_timeoutId",-1),h(this,"_logLevel",1),h(this,"_logLevelToUpload",2),!No&&!Fd&&(this.checkURLParam(),this.installEvents())}get isAbleToUpload(){return this._isEnableUploadLog&&this._timeoutId!==-1}installEvents(){R.on(A.JOIN_SCHEDULE_SUCCESS,e=>{let{schedule:t}=e;var i;(i=t==null?void 0:t.config)!=null&&i.logLevelToUpload&&pi[t.config.logLevelToUpload]&&(this._logLevelToUpload=t.config.logLevelToUpload)}),R.on(A.JOIN_SUCCESS,e=>{let{room:t}=e;this.addJoinedUser({userId:t.userId,sdkAppId:t.sdkAppId}),this.startUpload()}),R.once(A.JOIN_FAILED,()=>{this.startUpload()}),R.on(A.LEAVE_SUCCESS,e=>{let{room:t}=e;this.deleteJoinedUser(t.userId)})}startUpload(){this._timeoutId===-1&&this.uploadInterval()}addJoinedUser(e){this._localJoinedUser.set(e.userId,e),this.startUpload()}deleteJoinedUser(e){this._localJoinedUser.delete(e)}uploadInterval(){this.upload().catch(()=>{}),this._timeoutId=window.setTimeout(()=>this.uploadInterval(),2e3)}getLogsToUpload(){let e={map:new Map,splicedQueue:[]};if(this._queue[0].forAllJoinedClients&&this._localJoinedUser.size===0)return e;let t=0;for(;t<this._queue.length&&t!==50;t++){let i=this._queue[t];if(i.forAllJoinedClients)this._localJoinedUser.forEach(r=>{let{userId:n,sdkAppId:s}=r;e.map.has(n)?e.map.get(n).logs.push(i):e.map.set(n,{userId:n,sdkAppId:s,logs:[i]})});else if(re(i.userId)&&ge(i.sdkAppId)){let{userId:r,sdkAppId:n}=i;e.map.has(r)?e.map.get(r).logs.push(i):e.map.set(r,{userId:r,sdkAppId:n,logs:[i]})}}return e.map.size>0&&(e.splicedQueue=this._queue.splice(0,t)),e}upload(){return g(this,null,function*(){if(this._queue.length===0||!this._isEnableUploadLog)return;let{map:e,splicedQueue:t}=this.getLogsToUpload();if(e.size===0)return;try{let r=[...e.values()];for(let n=0;n<r.length;n++){let{userId:s,sdkAppId:a,logs:c}=r[n];yield this.uploadLogWithRetry(JSON.stringify({timestamp:My(),sdkAppId:String(a),userId:s,version:St,log:c.map(o=>o.log).join(`
52
+ `)}),a),c.forEach(o=>o.uploaded=!0)}}catch{}let i=t.filter(r=>!r.uploaded);i.length>0&&(this._queue=i.concat(this._queue))})}uploadLogWithRetry(e,t){return ws({retryFunction:()=>Ss({url:Os(t,hs.LOG),body:e,timeout:5e3}),settings:{retries:3,timeout:1e3},onError:i=>{let{retry:r}=i;r()}})()}getPrefix(e){let t=new Date;t.setTime(xd());let i=String(t.getMilliseconds());return"padStart"in String.prototype&&(i=i.toString().padStart(3,"0")),"[".concat(t.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/,"$1"),":").concat(i,"] <").concat(pi[e],">")}getLogLevel(){return this._logLevel}setLogLevel(e){I(pi[e])||(this._logLevel!==e&&this.info("setLogLevel",e),this._logLevel=e)}enableUploadLog(){this._isEnableUploadLog=!0}disableUploadLog(){this.warn("disableUploadLog"),this._isEnableUploadLog=!1}logChunkToString(e){if(re(e))return e;try{return e instanceof Error?e.toString():JSON.stringify(e)}catch{return""}}log(e,t){let i=!(arguments.length>2&&arguments[2]!==void 0)||arguments[2],r=arguments.length>3?arguments[3]:void 0,n=arguments.length>4?arguments[4]:void 0;var s;if(t.unshift(this.getPrefix(e)),this._isEnableUploadLog&&e>=this._logLevelToUpload&&this._queue.push({log:t.reduce((c,o)=>"".concat(c," ").concat(this.logChunkToString(o)).trim(),""),level:e,userId:r,sdkAppId:n,forAllJoinedClients:i}),e<this._logLevel)return;let a=((s=pi[e])==null?void 0:s.toLowerCase())||"info";rV?console[a]("%cTRTC%c%s","padding: 1px 4px;border-radius: 3px;color: #fff;background: #1E88E5;","display: inline",...t):console[a](...t)}debug(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];this.log(1,t)}info(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];this.log(2,t)}warn(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];this.log(3,t)}error(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];this.log(4,t)}createLogger(e){return new iV(e)}checkURLParam(){let e=new URLSearchParams(location.search).get("logLevelToUpload"),t=e?Number(e):-1;pi[t]&&(this._logLevelToUpload=t)}},LS=function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=16*Math.random()|0;return(e=="x"?t:3&t|8).toString(16)})},MS=new class{constructor(){h(this,"_prefix","TRTC"),h(this,"_queue",new Map),this.checkStorage()}getRealKey(e){return"".concat(this._prefix,"_").concat(e)}checkStorage(){ir()&&(setInterval(this.doFlush.bind(this),2e4),Object.keys(localStorage).filter(e=>{if(e.startsWith(this._prefix)){let t=localStorage.getItem(e);if(!t)return!1;let i=JSON.parse(t);if(i&&i.expiresIn<Date.now())return!0}return!1}).forEach(e=>localStorage.removeItem(e)))}doFlush(){if(ir())try{for(let[e,t]of this._queue)localStorage.setItem(e,JSON.stringify(t))}catch(e){b.warn(e)}}getItem(e){if(!ir())return null;try{let t=localStorage.getItem(this.getRealKey(e));if(!t)return null;let i=JSON.parse(t);return i&&i.expiresIn>=Date.now()?i.value:null}catch(t){b.warn(t)}}setItem(e,t){if(ir())try{let i={expiresIn:Date.now()+jy,value:t};this._queue.set(this.getRealKey(e),i)}catch(i){b.warn(i)}}deleteItem(e){if(!ir())return!1;try{return e=this.getRealKey(e),this._queue.delete(e),localStorage.removeItem(e),!0}catch(t){return b.warn(t),!1}}clear(){if(ir())try{localStorage.clear()}catch(e){b.warn(e)}}},Vs={};ls(Vs,{HTTPS_API:()=>cV,IS_GET_CAPABILITIES_SUPPORTED:()=>WS,IS_GET_SETTINGS_SUPPORTED:()=>un,IS_SEI_SUPPORTED:()=>or,IS_SPC_SUPPORTED:()=>Bs,basis:()=>dV,checkSystemRequirementsInternal:()=>Lh,decodeSupportStatus:()=>Ph,encodeSupportStatus:()=>Oh,getBrowserInfo:()=>sV,getDisplayResolution:()=>FS,isAddTransceiverSupported:()=>Wt,isBrowserSupported:()=>Dh,isGetReceiversSupported:()=>ic,isGetSendersSupported:()=>Fs,isGetTransceiversSupported:()=>Si,isGetUserMediaSupported:()=>BS,isMediaDevicesSupported:()=>wh,isMediaSessionSupported:()=>JS,isMediaStreamTrackProcessorSupported:()=>aV,isReplaceTrackSupported:()=>GS,isScreenCaptureApiAvailable:()=>ec,isSelectedCandidatePair:()=>Us,isSetParametersSupported:()=>xh,isSmallStreamAPISupported:()=>jS,isSmallStreamSupported:()=>tc,isStopTransceiverSupported:()=>uV,isTRTCSupported:()=>oV,isUnifiedPlanDefault:()=>lV,isUsedInHttpProtocol:()=>ar,isWebAudioSupported:()=>HS,isWebCodecSupported:()=>Uh,isWebCodecsSupported:()=>VS,isWebRTCSupported:()=>Vh,isWebTransportSupported:()=>zS});var xS=Ie($M(),1),$={result:!1,detail:{isBrowserSupported:!1,isWebRTCSupported:!1,isWebCodecsSupported:!1,isMediaDevicesSupported:!1,isScreenShareSupported:!1,isSmallStreamSupported:!1,isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH264DecodeSupported:!1,isVp8DecodeSupported:!1}},nV=new Map([[ue,["Firefox",th]],[As,["Edg",rh]],[qo,["Chrome",gh]],[Rt,["Safari",Ds]],[At,["TBS",ah]],[Rs,["XWEB",oh]],[Uo&&nn,["WeChat",ch]],[Fo,["QQ(Win)",lh]],[bs,["QQ(Mobile)",ks]],[Cs,["QQ(Mobile X5)",ks]],[Bo,["QQ(Mac)",uh]],[Ho,["QQ(iPad)",dh]],[Go,["MI",hh]],[Wo,["HW",ph]],[Jo,["Samsung",mh]],[zo,["OPPO",_h]],[Ko,["VIVO",fh]],[Is,["EDGE",ih]],[xo,["SogouMobile",nh]],[Vo,["Sogou",sh]]]);function sV(){let e=nV.get(!0);return{browserName:e?e[0]:"unknown",browserVersion:e?e[1]:"unknown"}}var Dh=function(){return!(lS||Is||As&&aS<80||ue&&sS<56)},VS=function(){return["VideoDecoder","VideoEncoder","AudioEncoder","AudioDecoder","MediaStreamTrackGenerator"].every(e=>e in window)},wh=function(){if(!navigator.mediaDevices)return ar()||b.error(ut.NOT_SUPPORTED_MEDIA),!1;let e=["getUserMedia","enumerateDevices"];return e.filter(t=>t in navigator.mediaDevices).length===e.length},US=!1;function ar(){return location.protocol==="http:"&&!on&&(US||b.error(j({key:B.NOT_SUPPORTED_HTTP})),US=!0,!0)}var aV=function(){return(window==null?void 0:window.OffscreenCanvas)&&(window==null?void 0:window.MediaStreamTrackProcessor)&&(window==null?void 0:window.MediaStreamTrackGenerator)},Oh=function(){return g(this,null,function*(){if($.detail.isH264EncodeSupported&&$.detail.isVp8EncodeSupported)return{isH264EncodeSupported:$.detail.isH264EncodeSupported,isVp8EncodeSupported:$.detail.isVp8EncodeSupported};let e,t=!1,i=!1;try{let r=new RTCPeerConnection,n=document.createElement(_.CANVAS);n.getContext("2d");let s=n.captureStream(0);return r.addTrack(s.getVideoTracks()[0],s),e=yield r.createOffer(),e.sdp.toLowerCase().indexOf("h264")!==-1&&(t=!0),e.sdp.toLowerCase().indexOf("vp8")!==-1&&(i=!0),r.close(),$.detail.isH264EncodeSupported=t,$.detail.isVp8EncodeSupported=i,{isH264EncodeSupported:$.detail.isH264EncodeSupported,isVp8EncodeSupported:$.detail.isVp8EncodeSupported}}catch{return{isH264EncodeSupported:!1,isVp8EncodeSupported:!1}}})},Ph=function(){return g(this,null,function*(){if($.detail.isH264DecodeSupported&&$.detail.isVp8DecodeSupported)return{isH264DecodeSupported:$.detail.isH264DecodeSupported,isVp8DecodeSupported:$.detail.isVp8DecodeSupported};let e,t=!1,i=!1;try{let r=new RTCPeerConnection;return e=yield r.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0}),e.sdp.toLowerCase().indexOf("h264")!==-1&&(t=!0),e.sdp.toLowerCase().indexOf("vp8")!==-1&&(i=!0),r.close(),{isH264DecodeSupported:t,isVp8DecodeSupported:i}}catch{return{isH264DecodeSupported:!1,isVp8DecodeSupported:!1}}})},Lh=PS(()=>g(void 0,null,function*(){if($.result&&$.detail.isH264EncodeSupported&&$.detail.isVp8EncodeSupported&&$.detail.isH264DecodeSupported&&$.detail.isVp8DecodeSupported)return $;let e=Dh(),t=Vh(),i=VS(),r=wh(),{isH264EncodeSupported:n,isVp8EncodeSupported:s}=yield Oh(),{isH264DecodeSupported:a,isVp8DecodeSupported:c}=yield Ph();if(!n||!s){let o=yield Oh();b.warn("detect encode again h264:".concat(n," vp8:").concat(s," result: ").concat(JSON.stringify(o))),n=o.isH264EncodeSupported,s=o.isVp8EncodeSupported}if(n&&a&&Ue&&Zi&&!Rs&&!At){let{encode:o,decode:l}=yield function(){return g(this,null,function*(){return Mh||(Mh=new Promise(d=>g(this,null,function*(){let u={encode:!1,decode:!1},p=()=>{};try{b.warn("detectH264Supported start");let m=document.createElement("canvas"),f=m.getContext("2d");m.width=320,m.height=240;let T=setInterval(()=>{f.fillText("test",Math.floor(320*Math.random()),Math.floor(240*Math.random()))},66),S=-1,y=-1;p=()=>{clearInterval(S),clearInterval(T),clearTimeout(y),D.close(),P.close(),E.getTracks().forEach(Te=>Te.stop())},y=setTimeout(()=>{p(),d(u)},2e3);let E=m.captureStream(),D=new RTCPeerConnection({}),P=new RTCPeerConnection({offerToReceiveAudio:!0,offerToReceiveVideo:!0});D.addEventListener("icecandidate",Te=>P.addIceCandidate(Te.candidate)),P.addEventListener("icecandidate",Te=>D.addIceCandidate(Te.candidate)),D.addTrack(E.getVideoTracks()[0],E);let Q=yield D.createOffer();yield D.setLocalDescription(Q),yield P.setRemoteDescription(Q);let q=yield P.createAnswer(),U=xS.default.parse(q.sdp),Qt=U.media[0].rtp.findIndex(Te=>Te.codec==="H264");U.media[0].rtp=[U.media[0].rtp[Qt]],U.media[0].fmtp=U.media[0].fmtp.filter(Te=>Te.payload===U.media[0].rtp[0].payload),U.media[0].rtcpFb&&(U.media[0].rtcpFb=U.media[0].rtcpFb.filter(Te=>Te.payload===U.media[0].rtp[0].payload)),q.sdp=xS.default.write(U),yield P.setLocalDescription(q),yield D.setRemoteDescription(q),S=setInterval(()=>g(this,null,function*(){u.encode&&u.decode&&(p(),d(u));let Te=yield D.getSenders()[0].getStats(),Oi=yield P.getReceivers()[0].getStats();u.encode||Te.forEach(Nt=>{Nt.type==="outbound-rtp"&&Nt.mediaType===_.VIDEO&&Nt.bytesSent>0&&(u.encode=!0)}),u.decode||Oi.forEach(Nt=>{Nt.type==="inbound-rtp"&&Nt.mediaType===_.VIDEO&&Nt.bytesReceived>0&&(u.decode=!0)})}),100)}catch(m){p(),b.warn(m),d(u)}})).then(d=>((!d.encode||!d.decode)&&b.warn("detectH264Supported encode: ".concat(d.encode," decode: ").concat(d.decode," ").concat(Ht)),d)),Mh)})}();n=o,o&&(a=l)}return $.result=e&&t&&r&&(n||s)&&(a||c),$.detail.isBrowserSupported=e,$.detail.isWebRTCSupported=t,$.detail.isWebCodecsSupported=i,$.detail.isMediaDevicesSupported=r,$.detail.isScreenShareSupported=ec(),$.detail.isSmallStreamSupported=tc(),$.detail.isH264EncodeSupported=n,$.detail.isVp8EncodeSupported=s,$.detail.isH264DecodeSupported=a,$.detail.isVp8DecodeSupported=c,$.result||b.error("".concat(navigator.userAgent," ").concat(DS($.detail,!1))),MS.setItem(KS,{ua:navigator.userAgent,checkResult:$}),$})),oV=function(){return $.result},ec=function(){return!(!navigator.mediaDevices||!navigator.mediaDevices.getDisplayMedia)},Mh=null,cV=(e,t,i)=>{location.protocol==="http:"&&!on&&(e[t]=()=>{throw new N({code:C.INVALID_OPERATION,message:ut.NOT_SUPPORTED_HTTP})})},Us=function(e){return!(e.type!=="candidate-pair"||!e.nominated||e.state!=="in-progress"&&e.state!=="succeeded")&&!(We(e.selected)&&!e.selected)};function FS(){let e="";if(screen.width){let t=screen.width?screen.width*window.devicePixelRatio:"",i=screen.height?screen.height*window.devicePixelRatio:"";e+="".concat(t," * ").concat(i)}return e}function BS(){return navigator.getUserMedia||navigator.mediaDevices&&navigator.mediaDevices.getUserMedia}function HS(){let e={isSupported:!1},t=["AudioContext","webkitAudioContext","mozAudioContext","msAudioContext"];for(let i=0;i<t.length;i++)if(t[i]in window){e.isSupported=!0;break}return e.isSupported}function jS(){return"captureStream"in HTMLCanvasElement.prototype}function tc(){return!(Uo||Bt||er&&er<63)&&!(!Dh()||!jS())}var lV=function(){if(I(window.RTCRtpTransceiver)||!("currentDirection"in RTCRtpTransceiver.prototype))return!1;let e=null,t=!1;try{e=new RTCPeerConnection({sdpSemantics:_s}),e.addTransceiver(_.AUDIO),t=!0}catch{}return e==null||e.close(),t};function ic(){return"RTCPeerConnection"in window&&"getReceivers"in window.RTCPeerConnection.prototype}function Fs(){return"RTCPeerConnection"in window&&"getSenders"in window.RTCPeerConnection.prototype}function Si(){return"RTCPeerConnection"in window&&"getTransceivers"in window.RTCPeerConnection.prototype}function Wt(){return Th!==11&&"RTCPeerConnection"in window&&"addTransceiver"in window.RTCPeerConnection.prototype}var Bs=!(!Wt()||Zi&&er<86);function uV(){return"RTCRtpTransceiver"in window&&"stop"in window.RTCRtpTransceiver.prototype}function GS(){return"RTCRtpSender"in window&&"replaceTrack"in window.RTCRtpSender.prototype}function xh(){return"RTCRtpSender"in window&&"setParameters"in window.RTCRtpSender.prototype&&Fs()}var un=window.MediaStreamTrack&&"getSettings"in MediaStreamTrack.prototype,WS=window.MediaStreamTrack&&"getCapabilities"in MediaStreamTrack.prototype,or="RTCRtpSender"in window&&"createEncodedStreams"in window.RTCRtpSender.prototype&&Ns()>=86,Vh=function(){return["RTCPeerConnection","webkitRTCPeerConnection","RTCIceGatherer"].filter(e=>e in window).length>0};function Uh(){let e={AudioDecoder:!1,AudioEncoder:!1,VideoDecoder:!1,VideoEncoder:!1,ImageDecoder:!1};return I(window.AudioDecoder)||(e.AudioDecoder=!0),I(window.AudioEncoder)||(e.AudioEncoder=!0),I(window.VideoDecoder)||(e.VideoDecoder=!0),I(window.VideoEncoder)||(e.VideoEncoder=!0),I(window.ImageDecoder)||(e.ImageDecoder=!0),e}function JS(){return"mediaSession"in navigator&&!I(navigator.mediaSession.setActionHandler)}function zS(){return!I(window.WebTransport)}function dV(){let e={browser:"".concat(fi.name,"/").concat(fi.version),os:yh(),displayResolution:FS(),isScreenShareSupported:ec(),isWebRTCSupported:Vh(),isGetUserMediaSupported:BS(),isWebAudioSupported:HS(),isWebSocketsSupported:"WebSocket"in window&&window.WebSocket.CLOSING===2,isWebCodecSupported:Uh(),isMediaSessionSupported:JS(),isWebTransportSupported:zS()};return navigator.userAgent.includes("miniProgram")&&(e.browser="mini/".concat(e.browser)),e}var KS="checkResult";(function(){ar();let e=MS.getItem(KS);e&&e.ua===navigator.userAgent&&($=e.checkResult),Lh()})();var hV=Ie(Ve(),1),qS=Symbol("instance"),rc=Symbol("cacheResult"),Fh=class{constructor(e,t,i){this.oldState=e,this.newState=t,this.action=i,this.aborted=!1}abort(e){this.aborted=!0,js.call(e,this.oldState,new Error("action '".concat(this.action,"' aborted")))}toString(){return"".concat(this.action,"ing")}},Bh=class extends Error{constructor(e,t,i){super(t),this.state=e,this.message=t,this.cause=i}},Hs=new Map;function be(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return(r,n,s)=>{let a=i.action||n;if(!i.context){let o=Hs.get(r)||[];Hs.has(r)||Hs.set(r,o),o.push({from:e,to:t,action:a})}let c=s.value;s.value=function(){let o=this;for(var l=arguments.length,d=new Array(l),u=0;u<l;u++)d[u]=arguments[u];if(i.context&&(o=X.get(typeof i.context=="function"?i.context.call(this,...d):i.context)),o.state===t)return i.sync?o[rc]:Promise.resolve(o[rc]);o.state instanceof Fh&&o.state.action==i.abortAction&&o.state.abort(o);let p=null;Array.isArray(e)?e.length==0?o.state instanceof Fh&&o.state.abort(o):(typeof o.state!="string"||!e.includes(o.state))&&(p=new Bh(o._state,"".concat(o.name," ").concat(a," to ").concat(t," failed: current state ").concat(o._state," not from ").concat(e.join("|")))):e!==o.state&&(p=new Bh(o._state,"".concat(o.name," ").concat(a," to ").concat(t," failed: current state ").concat(o._state," not from ").concat(e)));let m=E=>{if(i.fail&&i.fail.call(this,E),i.sync){if(i.ignoreError)return E;throw E}return i.ignoreError?Promise.resolve(E):Promise.reject(E)};if(p)return m(p);let f=o.state,T=new Fh(f,t,a);js.call(o,T);let S=E=>{var D;return o[rc]=E,T.aborted||(js.call(o,t),(D=i.success)===null||D===void 0||D.call(this,o[rc])),E},y=E=>{let D=E instanceof Error?E.message:String(E);return js.call(o,f,E),m(new Bh(o._state,"action '".concat(a,"' failed :").concat(D),E instanceof Error?E:new Error(D)))};try{let E=c.apply(this,d);return function(D){return typeof D=="object"&&D&&"then"in D}(E)?E.then(S).catch(y):i.sync?S(E):Promise.resolve(S(E))}catch(E){return y(E)}}}}var pV=typeof window<"u"&&window.__AFSM__?(e,t)=>{window.dispatchEvent(new CustomEvent(e,{detail:t}))}:typeof importScripts<"u"?(e,t)=>{postMessage({type:e,payload:t})}:()=>{};function js(e,t){let i=this._state;this._state=e;let r=e.toString();e&&this.emit(r,i),this.emit(X.STATECHANGED,e,i,t),this.updateDevTools({value:e,old:i,err:t instanceof Error?t.message:String(t)})}var X=class extends hV.default{constructor(e,t,i){super(),this.name=e,this.groupName=t,this._state=X.INIT,e||(e=Date.now().toString(36)),i?Object.setPrototypeOf(this,i):i=Object.getPrototypeOf(this),t||(this.groupName=this.constructor.name);let r=i[qS];r?this.name=r.name+"-"+r.count++:i[qS]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let e=Object.getPrototypeOf(this),t=Hs.get(e)||[],i=new Set,r=[],n=[],s=new Set,a=Object.getPrototypeOf(e);Hs.has(a)&&(a.stateDiagram.forEach(o=>i.add(o)),a.allStates.forEach(o=>s.add(o))),t.forEach(o=>{let{from:l,to:d,action:u}=o;typeof l=="string"?r.push({from:l,to:d,action:u}):l.length?l.forEach(p=>{r.push({from:p,to:d,action:u})}):n.push({to:d,action:u})}),r.forEach(o=>{let{from:l,to:d,action:u}=o;s.add(l),s.add(d),s.add(u+"ing"),i.add("".concat(l," --> ").concat(u,"ing : ").concat(u)),i.add("".concat(u,"ing --> ").concat(d," : ").concat(u," 🟢")),i.add("".concat(u,"ing --> ").concat(l," : ").concat(u," 🔴"))}),n.forEach(o=>{let{to:l,action:d}=o;i.add("".concat(d,"ing --> ").concat(l," : ").concat(d," 🟢")),s.forEach(u=>{u!==l&&i.add("".concat(u," --> ").concat(d,"ing : ").concat(d))})});let c=[...i];return Object.defineProperties(e,{stateDiagram:{value:c},allStates:{value:s}}),c}static get(e){let t;return typeof e=="string"?(t=X.instances.get(e),t||X.instances.set(e,t=new X(e,void 0,Object.create(X.prototype)))):(t=X.instances2.get(e),t||X.instances2.set(e,t=new X(e.constructor.name,void 0,Object.create(X.prototype)))),t}static getState(e){var t;return(t=X.get(e))===null||t===void 0?void 0:t.state}updateDevTools(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};pV(X.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},e))}get state(){return this._state}set state(e){js.call(this,e)}};X.STATECHANGED="stateChanged",X.UPDATEAFSM="updateAFSM",X.INIT="[*]",X.ON="on",X.OFF="off",X.instances=new Map,X.instances2=new WeakMap;var YS=(window==null?void 0:window.requestIdleCallback)||function(e){let t=Date.now();return setTimeout(()=>{e({didTimeout:!1,timeRemaining:()=>Math.max(0,50-(Date.now()-t))})},1e3)},mV=(window==null?void 0:window.cancelIdleCallback)||function(e){clearTimeout(e)},_V=(window==null?void 0:window.cancelAnimationFrame)||(window==null?void 0:window.mozCancelAnimationFrame),Hh=class{static generateTaskID(){return this.currentTaskID++}static run(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:ys,t=arguments.length>1?arguments[1]:void 0,i=arguments.length>2?arguments[2]:void 0;i=O(e===Mo?{delay:2e3,count:0,backgroundTask:!0}:e===Es?{delay:1e4,count:0}:e===Qd?{fps:60,delay:16.6,count:0,backgroundTask:!0}:{delay:2e3,count:0,backgroundTask:!0},i),Ei(t)&&(i=O(O({},i),t)),ne(e)&&(t=e,e=ys);let r=O({taskID:this.generateTaskID(),loopCount:0,intervalID:null,timeoutID:null,rafID:null,ricID:null,taskName:e,callback:t},i);return this.taskMap.set(r.taskID,r),this[e](r),r.taskID}static interval(e){return e.intervalID=setInterval(()=>{e.callback(),e.loopCount+=1,this.isBreakLoop(e)},e.delay)}static intervalInWorker(e){e.delay=(1e3/e.fps).toFixed(2);let t=new Worker(URL.createObjectURL(new Blob([`
53
+ let timerID = null;
54
+ self.onmessage = function (e) {
55
+ if (e.data === 'start') {
56
+ timerID = setInterval(() => {
57
+ self.postMessage('tick');
58
+ }, `.concat(e.delay,`);
59
+ } else if (e.data === 'stop') {
60
+ clearInterval(timerID);
61
+ }
62
+ };
63
+ `)],{type:"application/javascript"})));t.onmessage=i=>{i.data==="tick"&&(e.callback(),e.loopCount+=1,this.isBreakLoop(e)&&t.postMessage("stop"))},e.worker=t,t.postMessage("start")}static timeout(e){let t=()=>{if(e.callback(),e.loopCount+=1,!this.isBreakLoop(e))return e.timeoutID=setTimeout(t,e.delay)};return e.timeoutID=setTimeout(t,e.delay)}static ric(e){let t,i=W(),r=()=>{if(t=W()-i,t>=e.delay&&(i=W()-Math.floor(t%e.delay),e.callback(),e.loopCount+=1),!this.isBreakLoop(e))return e.ricID=YS(r,{timeout:e.delay})};return e.ricID=YS(r,{timeout:e.delay})}static raf(e){e.delay=(1e3/e.fps).toFixed(2);let t,i=W(),r=()=>document.hidden&&e.backgroundTask?(t=W()-i,i=W(),e.callback(),e.loopCount+=1,this.isBreakLoop(e)?void 0:e.timeoutID=setTimeout(r,e.delay-Math.floor(t%e.delay))):(t=W()-i,t>=e.delay&&(i=W()-Math.floor(t%e.delay),e.callback(),e.loopCount+=1),this.isBreakLoop(e)?void 0:e.rafID=requestAnimationFrame(r));if(e.rafID=requestAnimationFrame(r),e.backgroundTask){let n=()=>{if(document.hidden){let s=W()-i;s>=e.delay?r():e.timeoutID=setTimeout(r,e.delay-s)}};document.addEventListener("visibilitychange",n),e.onVisibilitychange=n,document.hidden&&n()}return e.taskID}static hasTask(e){return this.taskMap.has(e)}static clearTask(e){if(!this.taskMap.has(e))return!0;let{intervalID:t,timeoutID:i,rafID:r,ricID:n,onVisibilitychange:s,worker:a}=this.taskMap.get(e);return a&&a.terminate(),t&&clearInterval(t),i&&clearTimeout(i),r&&_V(r),n&&mV(n),s&&document.removeEventListener("visibilitychange",s),this.taskMap.delete(e),!0}static isBreakLoop(e){return!this.taskMap.has(e.taskID)||e.count!==0&&e.loopCount>=e.count&&(this.clearTask(e.taskID),!0)}};Hh.taskMap=new Map,Hh.currentTaskID=1;var _e=Hh,rt={LOADED_DATA:_.LOADEDDATA,MEDIA_TRACK_CHANGED:"media-track-changed",PLAYER_STATE_CHANGED:"player-state-changed",ERROR:"error"},jh={};ls(jh,{create:()=>ht,remove:()=>Pe});var Gs=new WeakMap;function ht(e,t){Gs.has(e)||Gs.set(e,[]);let i=Gs.get(e),r={add:(n,s)=>("addEventListener"in t?(i.push(t.removeEventListener.bind(t,n,s)),t.addEventListener(n,s)):(i.push(t.off.bind(t,n,s)),t.on(n,s)),r)};return r}function Pe(e){let t=Gs.get(e);t&&(t.forEach(i=>i()),Gs.delete(e))}var Ct=new WeakMap;function cr(e){let{settings:t={retries:5,timeout:2e3},onError:i,onRetrying:r,onRetryFailed:n}=e;return function(s,a,c){let o=ws({retryFunction:c.value,settings:t,onError(l){let{error:d,retry:u,reject:p,retryFuncArgs:m}=l;var f;i?i.call(this,d,()=>{var T;(T=Ct.get(s))!=null&&T.has(a)?u():p(d)},p,m):(f=Ct.get(s))!=null&&f.has(a)?u():p(d)},onRetrying(l,d){var u;ne(r)&&r.call(this,l,d),(u=Ct.get(s))!=null&&u.has(a)&&(Ct.get(s).get(a).stopRetry=d)},onRetryFailed:n});return c.value=function(){let l=Ct.get(s);for(var d=arguments.length,u=new Array(d),p=0;p<d;p++)u[p]=arguments[p];return l?l.set(a,{args:u}):Ct.set(s,new Map([[a,{args:u}]])),o.apply(this,u).finally(()=>{var m;return(m=Ct.get(s))==null?void 0:m.delete(a)})},c}}function nc(e){let{fnName:t,callback:i,validateArgs:r=!0}=e;return function(n,s,a){let c=a.value;return a.value=function(){for(var o,l,d=arguments.length,u=new Array(d),p=0;p<d;p++)u[p]=arguments[p];if((o=Ct.get(n))!=null&&o.has(t)){let{stopRetry:m,args:f}=Ct.get(n).get(t),T=!0;if(r){for(let S of f)if(!u.find(y=>y===S)){T=!1;break}}T&&(i&&i.apply(this,u),m&&m(),(l=Ct.get(n))==null||l.delete(t))}return c.apply(this,u)},a}}var pt,H,Gh,QS=class{constructor(){let e=!(arguments.length>0&&arguments[0]!==void 0)||arguments[0];this.countMap=new Map,this.distributionMap=new Map,this.log=b.createLogger({id:"kv"}),e&&(R.on("102",t=>{let{track:i,cost:r}=t;this.addSuccessEvent({key:i.kind===_.AUDIO?Wh.START_MICROPHONE:Jh.START_CAMERA,cost:r})}),R.on("103",t=>{let{track:i,error:r}=t;this.addFailedEvent({key:i.kind===_.AUDIO?Wh.START_MICROPHONE:Jh.START_CAMERA,error:r})}))}getReportData(){let e={msg_sdk_basic_info:{uint32_sdk_version:OS(this.version||St),uint32_terminal_type:15,bytes_device_name:"",bytes_os_version:"",uint32_framework:30,uint32_network_type:0},stats_count:[...this.countMap.entries()].map(t=>{let[i,r]=t;return{uint32_key:i,uint32_count:r}}),stats_distribution:[...this.distributionMap.entries()].map(t=>{let[i,r]=t;return{uint32_key:i,distribution_items:[...r.entries()].map(n=>{let[s,a]=n;return{uint32_item_key:s,uint32_item_value:a}})}})};return this.countMap.clear(),this.distributionMap.clear(),e}clear(){this.countMap.clear(),this.distributionMap.clear()}isEnumKey(e){let t=+String(e).slice(-3);return t>=700&&t<799}isErrorCodeKey(e){let t=+String(e).slice(-3);return t>=600&&t<699}isCountKey(e){let t=+String(e).slice(-3);return t>=0&&t<599}isNumberKey(e){let t=+String(e).slice(-3);return t>=800&&t<899}addCount(e){let{key:t,useUV:i=!1}=e;this.isCountKey(t)?i&&this.countMap.has(t)||this.countMap.set(t,(this.countMap.get(t)||0)+1):this.log.debug("".concat(t," is not count key, last 3 number should be 0~599"))}addEnum(e){let{key:t,value:i,useUV:r=!0}=e;var n;if(!this.isEnumKey(t))return this.log.debug("".concat(t," is not enum key, last 3 number should be 700~799"));if(r&&this.countMap.has(t))return;this.countMap.set(t,(this.countMap.get(t)||0)+1);let s=((n=this.distributionMap)==null?void 0:n.get(t))||new Map;s.set(i,(s.get(i)||0)+1),this.distributionMap.set(t,s)}addNumber(e){let{key:t,value:i,split:r=100,useUV:n=!1}=e;var s;if(!this.isNumberKey(t))return this.log.debug("".concat(t," is not number key, last 3 number should be 800~899"));if(n&&this.countMap.has(t))return;this.countMap.set(t,(this.countMap.get(t)||0)+1);let a=((s=this.distributionMap)==null?void 0:s.get(t))||new Map,c=0;if(ge(r))c=Math.floor(i/r);else for(let o=r.length-1;o>0;o--)if(i>r[o]){c=o;break}a.set(c,(a.get(c)||0)+1),this.distributionMap.set(t,a)}addSuccessEvent(e){let{key:t,cost:i,timeKey:r,split:n}=e;if(t&&(this.addEnum({key:t,value:1,useUV:!1}),i)){let s=+String(t).slice(-3);s<800&&s>=700?this.addNumber({key:r||t+100,value:i,split:n}):r||this.log.debug("time stat ignored, ".concat(t))}}addFailedEvent(e){let{key:t,error:i}=e;if(!t)return;let r=C.UNKNOWN;i&&(ge(i)?r=i:(!I(i.extraCode)||!I(i.code))&&(r=i.extraCode||i.code)),this.addEnum({key:t,value:0,useUV:!1}),this.addEnum({key:t,value:r,useUV:!1})}},XS=((H=XS||{})[H.enterRoom=500700]="enterRoom",H[H.exitRoom=500701]="exitRoom",H[H.switchRole=500702]="switchRole",H[H.destroy=500703]="destroy",H[H.startLocalAudio=500704]="startLocalAudio",H[H.updateLocalAudio=500705]="updateLocalAudio",H[H.stopLocalAudio=500706]="stopLocalAudio",H[H.startLocalVideo=500707]="startLocalVideo",H[H.updateLocalVideo=500708]="updateLocalVideo",H[H.stopLocalVideo=500709]="stopLocalVideo",H[H.startScreenShare=500710]="startScreenShare",H[H.updateScreenShare=500711]="updateScreenShare",H[H.stopScreenShare=500712]="stopScreenShare",H[H.startRemoteVideo=500713]="startRemoteVideo",H[H.updateRemoteVideo=500714]="updateRemoteVideo",H[H.stopRemoteVideo=500715]="stopRemoteVideo",H[H.muteRemoteAudio=500716]="muteRemoteAudio",H[H.setRemoteAudioVolume=500717]="setRemoteAudioVolume",H[H.use=500718]="use",H[H.sendSEIMessage=5e5]="sendSEIMessage",H[H.sendCustomMessage=500001]="sendCustomMessage",H),$S=((pt=$S||{})[pt.AudioMixer=550700]="AudioMixer",pt[pt.AIDenoiser=551700]="AIDenoiser",pt[pt.VirtualBackground=570700]="VirtualBackground",pt[pt.Beauty=571700]="Beauty",pt[pt.Watermark=572700]="Watermark",pt),ZS=(e=>(e[e.AudioMixer=550701]="AudioMixer",e[e.AIDenoiser=551701]="AIDenoiser",e[e.VirtualBackground=570701]="VirtualBackground",e[e.Beauty=571701]="Beauty",e[e.Watermark=572701]="Watermark",e))(ZS||{}),ev=(e=>(e[e.AudioMixer=550702]="AudioMixer",e[e.AIDenoiser=551702]="AIDenoiser",e[e.VirtualBackground=570702]="VirtualBackground",e[e.Beauty=571702]="Beauty",e[e.Watermark=572702]="Watermark",e))(ev||{}),Wh=(e=>(e[e.START_MICROPHONE=501700]="START_MICROPHONE",e[e.MICROPHONE_CAHNNELS=501701]="MICROPHONE_CAHNNELS",e[e.MICROPHONE_SAMPLERATE=501702]="MICROPHONE_SAMPLERATE",e))(Wh||{}),Jh=((Gh=Jh||{})[Gh.START_CAMERA=511700]="START_CAMERA",Gh),fV=new QS(!0),Ws=new QS(!1),L=fV,dn=class extends X{constructor(e,t){super(e.id,"".concat(t,"-player")),this.kind=t,h(this,"id"),h(this,"element",null),h(this,"track"),h(this,"url"),h(this,"attr"),h(this,"muted"),h(this,"_log"),h(this,"_pausedRetryCount"),h(this,"_isElementPlayingFired",!1),h(this,"_interval"),h(this,"_delayDestroyTimeoutId",0),h(this,"_isReplayByRecreateMediaStreamIng",!1),this.id=e.id,this._log=e.log,this.track=e.track,this.muted=e.muted,this._pausedRetryCount=Zy,this._state="STOPPED",this.bindTrackEvents(),this._log.info("create ".concat(t,"-player ").concat(this.id))}get isPlaying(){var e;return this._state==="PLAYING"&&((e=this.element)==null?void 0:e.paused)===!1}get isStopped(){return this._state==="STOPPED"}setAttr(e){this.attr=e}setUrl(e){this.track&&(this.unbindTrackEvents(),this.element&&(this.element.srcObject=null),this.track=null),e!==this.url&&(this.url=e,e!==null&&this.element&&(this.element.crossOrigin="anonymous",this.element.src=e))}play(){return g(this,null,function*(){if(!this.isPlaying)try{this._delayDestroyTimeoutId&&(clearTimeout(this._delayDestroyTimeoutId),this._delayDestroyTimeoutId=0,this.bindTrackEvents(),this.bindElementEvents()),this.bindAutoPlayEvent(),yield this.element.play()}catch(e){let t=j({key:B.PLAY_FAILED,data:{media:this.kind,error:e}});if(this.track&&!this.track.muted&&this._log.warn(e),t.includes("NotAllowedError"))throw new N({code:C.PLAY_NOT_ALLOWED,message:t})}})}stop(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0;this._isElementPlayingFired=!1,this.unbindEvents(),e>0?this._delayDestroyTimeoutId||(this._log.info("destroy element after 3 * ".concat(e)),this._delayDestroyTimeoutId=setTimeout(()=>this.destroyElement(),3*e)):this.destroyElement(),this.handleStopped(_.ENDED),this._interval>0&&_e.clearTask(this._interval)}destroyElement(){this.element&&(this._log.debug("destroy element"),this.element.remove(),this.element.srcObject=null,this.element=null),clearTimeout(this._delayDestroyTimeoutId),this._delayDestroyTimeoutId=0}pause(){var e;this.isPlaying&&((e=this.element)==null||e.pause())}resume(){return this._log.info("resume"),this.isPlaying?Promise.resolve():dS?this.replay():this.play().catch(()=>{})}setMuted(e){this.element&&(this.element.muted=e),this.muted=e}replay(){return this.stop(),this.play().catch(()=>{})}bindElementEvents(){if(this.element){let e=this.handleElementEvent.bind(this);return ht(this.element,this.element).add(_.PLAYING,e).add(_.ENDED,e).add(_.PAUSE,e).add(_.ERROR,e).add(_.LOADEDDATA,e)}}bindTrackEvents(){if(this.track){let e=this.handleTrackEvent.bind(this);jh==null||jh.create(this.track,this.track).add(_.ENDED,e).add(_.MUTE,e).add(_.UNMUTE,e),this.track.readyState===_.ENDED&&this.handleTrackEvent({type:_.ENDED}),this.track.muted&&this.handleTrackEvent({type:_.MUTE})}}bindAutoPlayEvent(){R.on(A.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}unbindTrackEvents(){this.track&&Pe(this.track)}unbindEvents(){this.element&&Pe(this.element),this.unbindTrackEvents(),R.off(A.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}handleElementEvent(e){switch(e.type){case _.PLAYING:this._isElementPlayingFired=!0,this._log.info("".concat(this.kind," player is playing")),this.handlePlaying(_.PLAYING),this._interval&&(_e.clearTask(this._interval),this._interval=-1);break;case _.ENDED:this._log.info("".concat(this.kind," player is ended")),this.handleStopped(_.ENDED);break;case _.PAUSE:this._log.info("".concat(this.kind," player is paused")),this.handlePaused(_.PAUSE),Bt&&(this._interval=_e.run(ys,()=>{this.element&&this._state==="PAUSED"&&this.resume()},{delay:3e3}));break;case _.ERROR:if(this.element&&this.element.error){this.handlePaused(_.ERROR);let{code:t,message:i}=this.element.error;this._log.error("".concat(this.kind," ").concat(this._log.isLocal?"local":"remote"," MediaError code: ").concat(t," message: ").concat(i," userAgent: ").concat(navigator.userAgent)),de.uploadEvent({log:"stat-".concat(this.kind,"-").concat(Ft.PLAYER_ERROR,"-").concat(t,"-").concat(navigator.userAgent),error:this.element.error}),this.replayByRecreateMediaStream()}break;case _.LOADEDDATA:this.kind===_.VIDEO&&this.emit(rt.LOADED_DATA)}}replayByRecreateMediaStream(){if(!this._isReplayByRecreateMediaStreamIng)return this._isReplayByRecreateMediaStreamIng=!0,this.doReplayByRecreateMediaStream(1e3).then(()=>{this._log.warn("replayByRecreateMediaStream success"),de.uploadEvent({log:"stat-replayByRecreateMediaStream-success"}),L.addSuccessEvent({key:this.kind===_.AUDIO?506700:516700})}).catch(()=>{var e,t;this._log.error("replayByRecreateMediaStream failed"),de.uploadEvent({log:"stat-replayByRecreateMediaStream-failed"}),L.addFailedEvent({key:this.kind===_.AUDIO?506700:516700,error:(e=this.element)==null?void 0:e.error}),(t=this.element)!=null&&t.error&&this.emit(rt.ERROR,this.element.error)}).finally(()=>{this._isReplayByRecreateMediaStreamIng=!1})}doReplayByRecreateMediaStream(e){return this._log.warn("delay ".concat(e,"ms to recreate mediaStream")),new Promise((t,i)=>{Nh(e).then(()=>{this.element&&(this.element.srcObject=null,this.element.srcObject=new MediaStream([this.track]),this._log.warn("recreated mediaStream"),this.element.onerror=()=>{var r,n,s;this._log.warn("element onerror ".concat((n=(r=this.element)==null?void 0:r.error)==null?void 0:n.code," fired after recreated mediaStream")),i((s=this.element)==null?void 0:s.error)}),Nh(5e3).then(()=>{var r,n;(!this.isPlaying||(r=this.element)!=null&&r.error)&&i((n=this.element)==null?void 0:n.error),t()})})}).finally(()=>{this.element&&(this.element.onerror=null)})}handleTrackEvent(e){switch(e.type){case _.ENDED:this.handleStopped(_.ENDED);break;case _.MUTE:this.handlePaused(_.MUTE);break;case _.UNMUTE:this._isElementPlayingFired&&this.handlePlaying(_.UNMUTE)}}handlePlaying(e){this.emit(rt.PLAYER_STATE_CHANGED,{type:this.kind,state:"PLAYING",reason:e})}handlePaused(e){this.emit(rt.PLAYER_STATE_CHANGED,{type:this.kind,state:"PAUSED",reason:e})}handleStopped(e){this.emit(rt.PLAYER_STATE_CHANGED,{type:this.kind,state:"STOPPED",reason:e})}getElement(){return this.element}};k([cr({settings:{retries:2,timeout:0},onError(e,t,i,r){r[0]=(r[0]||1e3)+1e3,t()}})],dn.prototype,"doReplayByRecreateMediaStream"),k([be([],"PLAYING",{sync:!0})],dn.prototype,"handlePlaying"),k([be("PLAYING","PAUSED",{ignoreError:!0,sync:!0})],dn.prototype,"handlePaused"),k([be([],"STOPPED",{sync:!0})],dn.prototype,"handleStopped");var Jt="trtc_autoplay",zh="".concat(Jt,"_mask"),hn="".concat(Jt,"_wrapper"),tv="".concat(Jt,"_header"),Kh="".concat(Jt,"_content"),sc="".concat(Jt,"_action_wrapper"),qh="".concat(Jt,"_question"),Yh="".concat(Jt,"_collapse"),ac="".concat(Jt,"_action_confirm"),iv="".concat(Jt,"_detail"),rv="#2473E8",Qh="dialog",gV="".concat(Qh,"-show"),TV="".concat(Qh,"-1"),EV="".concat(Qh,"-2"),nv=!1,sv=()=>!!document.querySelector(".".concat(hn)),av="".concat(Yi,"/").concat(Ti()?"zh-cn":"en","/tutorial-21-advanced-auto-play-policy.html"),ov="<br><a href='".concat(av,"' target='_blank'>").concat(Ti()?"其他方案?":"Any other solution?","</a>"),yV="".concat(Ti()?"浏览器自动播放策略:在用户与页面产生交互(点击、触摸)之前,浏览器禁止播放有声媒体。该弹窗用于帮助用户恢复音视频播放。".concat(ov):"Autoplay Policy: Before user interacts with the web page (clicking, touching), page will not be allowed to play media with sound. This Dialog is used to help users resume playback. ".concat(ov)),SV=class{constructor(){if(h(this,"content","音视频播放被浏览器拦截,请点击“恢复播放”。"),h(this,"_dialogNode",null),h(this,"_bodyPosition",""),h(this,"_showDetail",!1),h(this,"_isCollapseClicked",!1),h(this,"_isQuestionClicked",!1),Ti()||(this.content='Media playback failed. Click the "Resume" to resume playback.'),!nv){let e=document.createElement("style");e.innerHTML=".".concat(zh,"{position:fixed;top:0;left:0;right:0;bottom:0;width:100vw;height:100vh;display:flex;justify-content:center;align-items:center;background:rgba(0,0,0,0.5);z-index:1500;}.").concat(zh," div:not(.").concat(sc,"){display:block !important;}.").concat(hn,"{padding:14px;background:#fff;border-radius:3px;box-shadow:0px 3px 15px #434343;border:1px solid #d1cfcf;max-width:500px;}.").concat(hn," a{color:").concat(rv,";}.").concat(tv,"{overflow:hidden;text-overflow:ellipsis;font-size:16px;font-weight:600;}.").concat(Kh,"{margin:8px 0;}.").concat(sc,"{width:100%;display:flex !important;align-items:center;justify-content:right;float:right;}.").concat(Yh,"{margin-right:auto;cursor:pointer}.").concat(qh,"{height:100%;line-height:16px;cursor:pointer;}.").concat(ac,"{margin-left:8px;color:#fff;background:").concat(rv,";padding:4px 12px;outline:none;border:1px solid;border-radius:3px;font-weight:bold;}.").concat(ac,":hover{opacity:0.9;}.").concat(Yh,",.").concat(ac,",.").concat(Kh,",.").concat(qh,"{font-size:14px;}@media screen and (max-width:750px){.").concat(hn,"{width:80vw;}}"),document.head.appendChild(e),nv=!0}this.addDiaLog()}createDiaLog(){let e=document.createElement("template");e.innerHTML='<div class="'.concat(zh,`"><div class='`).concat(hn,"'><div class='").concat(tv,"'>").concat(location.host,"</div><div class='").concat(Kh,"'>").concat(this.content,"</div><div class='").concat(iv,`' style="visibility:hidden;width:100%;height:0;font-size:12px;color:gray;">`).concat(yV,"</div><div class='").concat(sc,"'></div></div></div>").trim();let t=document.createElement("button");t.className=ac,t.innerText=Ti()?"恢复播放":"Resume",t.onclick=this.onConfirm.bind(this);let i=document.createElement("div");i.className=qh,i.innerHTML=`<?xml version="1.0" encoding="UTF-8"?>
64
+ <svg class="icon" width="18" height="18" p-id="2030" t="1639646523624" version="1.1" viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg">
65
+ <path d="m464 784.35c0 26.51 21.49 48 48 48s48-21.49 48-48-21.49-48-48-48-48 21.49-48 48z" p-id="2031"/>
66
+ <path d="m512 960c-247.04 0-448-200.96-448-448s200.96-448 448-448 448 200.96 448 448-200.96 448-448 448zm0-831.71c-211.58 0-383.71 172.13-383.71 383.71 0 211.55 172.13 383.71 383.71 383.71 211.55 0 383.71-172.16 383.71-383.71 0-211.58-172.16-383.71-383.71-383.71z" p-id="2032"/>
67
+ <path d="m512 673.7c-17.665 0-32.001-14.336-32.001-31.999v-54.112c0-52.353 40-92.352 75.328-127.65 25.887-25.92 52.672-52.672 52.672-74.017 0-53.343-43.072-96.735-95.999-96.735-53.823 0-95.999 41.536-95.999 94.559 0 17.665-14.336 31.999-32.001 31.999s-32.001-14.336-32.001-31.999c0-87.424 71.775-158.56 160-158.56s160 72.095 160 160.74c0 47.904-36.32 84.192-71.424 119.3-27.84 27.776-56.576 56.512-56.576 82.336v54.112c0 17.665-14.336 32.032-32.001 32.032z" p-id="2033"/>
68
+ </svg>
69
+ `,i.onclick=this.onQuestionClick.bind(this);let r=document.createElement("div");r.className=Yh,r.innerText="".concat(Ti()?"详情 >":"Detail >"),r.onclick=this.onCollapseClick.bind(this);let n=e.content.firstChild,s=n.querySelector(".".concat(sc));return s.appendChild(r),s.appendChild(i),s.appendChild(t),n}addDiaLog(){sv()||(this._dialogNode=this.createDiaLog(),document.body.appendChild(this._dialogNode),this._dialogNode.onclick=this.onConfirm.bind(this),this._dialogNode.querySelector(".".concat(hn)).onclick=e=>e.stopPropagation(),this._bodyPosition=document.body.style.position,document.body.style.position="fixed",b.info("show autoplay dialog"),de.uploadEvent({log:gV}))}deleteDiaLog(){this._dialogNode&&(document.body.removeChild(this._dialogNode),document.body.style.position=this._bodyPosition,this._dialogNode=null)}onConfirm(){b.warn("confirm clicked, try resume stream"),R.emit(A.AUTOPLAY_DIALOG_CLICK_CONFIRM),this.deleteDiaLog()}onCollapseClick(){let e=this._dialogNode.querySelector(".".concat(iv));e.style.visibility="".concat(this._showDetail?"hidden":"visible"),e.style.height="".concat(this._showDetail?0:"fit-content"),this._showDetail=!this._showDetail,this._isCollapseClicked||de.uploadEvent({log:TV}),this._isCollapseClicked=!0}onQuestionClick(){window.open(av,"_blank"),this._isQuestionClicked||de.uploadEvent({log:EV}),this._isQuestionClicked=!0}},vi=class extends dn{constructor(e){super(e,_.VIDEO),h(this,"viewMirror",!1),h(this,"objectFit"),h(this,"container"),h(this,"canvas"),this.container=e.container,this.canvas=e.canvas,I(e.viewMirror)||(this.viewMirror=e.viewMirror),I(e.objectFit)||(this.objectFit=e.objectFit),this.initializeElement()}initializeElement(){var e;let t=document.createElement(_.VIDEO);this.track&&(t.srcObject=new MediaStream([this.track])),t.muted=!0,t.setAttribute("id","video_".concat(this.id)),t.setAttribute("style",this.styleAttribute),this.canvas&&this.canvas.setAttribute("style",this.styleAttribute),t.setAttribute("autoplay","autoplay"),t.setAttribute("playsinline","playsinline"),this.element=t,(e=this.container)==null||e.appendChild(this.elementToRender),this.bindElementEvents()}get styleAttribute(){let e="width: 100%; height: 100%; object-fit: ".concat(this.objectFit,";background-color: black;");return this.viewMirror&&(e+="transform: scaleX(-1);"),e}setContainer(e){var t;this.container=e,this.track&&this.elementToRender&&((t=this.container)==null||t.appendChild(this.elementToRender))}bindElementEvents(){let e=super.bindElementEvents();this.handleElementEvent=this.handleElementEvent.bind(this),e&&e.add(_.ENTER_PICTURE_IN_PICTURE,this.handleElementEvent).add(_.LEAVE_PICTURE_IN_PICTURE,this.handleElementEvent)}handleElementEvent(e){var t;super.handleElementEvent(e);let i=e.type;if(i===_.PAUSE&&(this.container&&document.getElementById(this.container.id)||this._log.warn("".concat(this.kind," player has been remove, element ID: ").concat((t=this.container)==null?void 0:t.id)),this._pausedRetryCount>0&&!sv()&&(this._log.info("".concat(this.kind," player auto resume when paused")),this.resume(),this._pausedRetryCount--)),this.viewMirror&&this.element){let r=this.element.style.transform;i===_.ENTER_PICTURE_IN_PICTURE?this.element.style.transform=r.replace("scaleX(-1)",""):i===_.LEAVE_PICTURE_IN_PICTURE&&!r.includes("scaleX")&&(this.element.style.transform="".concat(r," scaleX(-1)"))}}setCanvas(e){var t,i;this.canvas!==e&&((t=this.canvas)==null||t.remove(),e==null||e.setAttribute("style",this.styleAttribute),this.canvas=e,e&&((i=this.container)==null||i.appendChild(e)))}setAttr(e){let t=Object.assign({autoplay:"autoplay",playsinline:"playsinline",muted:!0},e);t.style=Object.assign({width:"100%",height:"100%"},t.style),super.setAttr(t)}get mirror(){return this.viewMirror}setRect(e,t){this.elementToRender&&(this.elementToRender.style.width="".concat(e,"px"),this.elementToRender.style.height="".concat(t,"px"))}setViewMirror(e){this.elementToRender&&(this.elementToRender.style.transform=e?"scaleX(-1)":""),this.viewMirror=e}setObjectFit(e){this.elementToRender&&(this.elementToRender.style.objectFit="".concat(e)),this.objectFit=e}stop(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0;var t;super.stop(e),(t=this.canvas)==null||t.remove()}play(){return this.element?this.elementToRender&&this.elementToRender.parentElement!==this.container&&this.container&&this.container.append(this.elementToRender):this.initializeElement(),super.play()}get elementToRender(){return this.canvas||this.element}setTrack(e){e!==this.track&&(this.unbindTrackEvents(),this.track=e,this.emit(rt.MEDIA_TRACK_CHANGED,e),e!==null&&(this.bindTrackEvents(),this.element&&(this.element.srcObject=new MediaStream([e]),this.element.remove()),this.elementToRender&&this.elementToRender.parentElement!==this.container&&this.container&&this.container.append(this.elementToRender)))}getVideoFrame(){if(this.canvas)return this.canvas.toDataURL("image/png");if(!this.element)return"";let e=document.createElement("canvas");return e.width=this.element.videoWidth,e.height=this.element.videoHeight,e.getContext("2d").drawImage(this.element,0,0),e.toDataURL("image/png")}getElement(){return this.element}};function Xh(e,t){return g(this,null,function*(){if(!e.audioWorklet)return Promise.reject("audioWorklet is not supported");try{yield e.audioWorklet.addModule(t),b.info("worklet addModule success")}catch(i){throw b.info("worklet addModule catch error. ".concat(i.message)),i}})}typeof window<"u"&&(window.AudioContext=window.AudioContext||window.webkitAudioContext||window.mozAudioContext);var lr=new window.AudioContext({sampleRate:48e3}),oc=()=>{lr.state==="suspended"?(lr.resume(),document.addEventListener("click",oc)):lr.state==="interrupted"?lr.resume():document.removeEventListener("click",oc)};document.addEventListener("click",oc),lr.onstatechange=()=>{b.info("context state: ".concat(lr.state)),oc()};var Ii=e=>lr,ur=class{constructor(){this.pre=new Set,this.next=new Set,this.connectedNodes=new Set,this._channelCount=1}get channelCount(){return this._channelCount}set channelCount(e){this._channelCount=e,this.node&&(this.node.channelCount=e),this.next.forEach(t=>t.channelCount=e)}setContext(e){this.context=e,this.node&&e.addMixWeight()}removeContext(){var e;this.node&&((e=this.context)==null||e.reduceMixWeight()),delete this.context}setNode(e){var t;if(!this.node)try{(t=this.context)==null||t.addMixWeight(),this.node=e,this.node.channelCountMode="explicit",this.node.channelCount=this._channelCount,this.preNodeReconnect(),this.reconnect(),L.addSuccessEvent({key:502701})}catch(i){b.error(i),L.addFailedEvent({key:502701,error:i})}}deleteNode(){var e;if(this.node)try{this._disconnect(),delete this.node,(e=this.context)==null||e.reduceMixWeight(),this.preNodeReconnect(),L.addSuccessEvent({key:502702})}catch(t){b.error(t),L.addFailedEvent({key:502702,error:t})}}preNodeReconnect(){this.pre.forEach(e=>{e.node?e.reconnect():e.preNodeReconnect()})}connectNext(e){this.next.forEach(t=>e._connect(t.node)||t.connectNext(e))}_connect(e){return!(!this.node||!e)&&(this.node.connect(e),this.connectedNodes.add(e),!0)}_disconnect(){this.connectedNodes.forEach(e=>{var t;return(t=this.node)==null?void 0:t.disconnect(e)}),this.connectedNodes.clear()}reconnect(){this._disconnect(),this.connectNext(this)}pipeTo(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return t.forEach(r=>{this.next.add(r),r.pre.add(this)}),this}},vV=class extends ur{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:256;super(),this.fftSize=e,this.dataArray=new Uint8Array(0)}setNode(e){e.fftSize=this.fftSize,this.dataArray=new Uint8Array(e.frequencyBinCount),super.setNode(e)}getByteTimeDomainData(){var e;return(e=this.node)==null||e.getByteTimeDomainData(this.dataArray),this.dataArray}get level(){var e;return(e=this.node)==null||e.getByteTimeDomainData(this.dataArray),Math.max(...this.dataArray)/128-1}get timeDomainPathData(){let e=this.getByteTimeDomainData(),t=0,i=0,r="M".concat(t,",").concat(i);for(let n=0;n<e.length;n++)i=e[n]/128*100/2,r+="L".concat(t,",").concat(i),t+=1;return r}},cv=class{constructor(){this.source=new ur,this.gain=new ur,this.destination=new ur}get volume(){var e;return((e=this.gain.node)==null?void 0:e.gain.value)||1}setVolume(e){e!==1?(this.gain.node||this.gain.setNode(this.source.node.context.createGain()),this.gain.node.gain.value=e):this.gain.node&&this.gain.deleteNode()}replaceSource(e){this.source.deleteNode(),this.source.setNode(function(t){let i=uv.get(t);if(i)return i;let r=Ii();if(t instanceof HTMLAudioElement)i=r.createMediaElementSource(t);else{if(!(t instanceof MediaStreamTrack))return t;i=r.createMediaStreamSource(new MediaStream([t]))}return uv.set(t,i),i}(e))}get track(){var e;return(e=this.stream)==null?void 0:e.getAudioTracks()[0]}get stream(){var e;return(e=this.destination.node)==null?void 0:e.stream}},lv=class extends cv{constructor(e){super(),this.context=e,this.denoiser=new ur,this.source.pipeTo(this.denoiser.pipeTo(this.gain.pipeTo(this.destination)))}connect(){this.context.inputs.has(this)||(this.destination.setNode(this.context.destination),this.source.setContext(this.context),this.denoiser.setContext(this.context),this.gain.setContext(this.context),this.context.inputs.add(this))}disconnect(){!this.context.inputs.has(this)||(this.destination.deleteNode(),this.source.removeContext(),this.denoiser.removeContext(),this.gain.removeContext(),this.context.inputs.delete(this))}remove(){this.gain.deleteNode(),this.denoiser.deleteNode(),this.source.deleteNode(),this.disconnect()}setVolume(e){e!==1?(this.gain.node||this.gain.setNode(this.context.audioContext.createGain()),this.gain.node.gain.value=e):this.gain.node&&this.gain.deleteNode()}},IV=class{constructor(){this.audioContext=Ii(),this.destination=this.audioContext.createMediaStreamDestination(),this.inputs=new Set,this.mixWeight=0}addMixWeight(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:1;this.mixWeight+=e,this.mixWeight-1==e+1>>1&&this.mixOnChange()}reduceMixWeight(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:1;this.addMixWeight(-e)}close(){this.inputs.forEach(e=>e.remove())}get mixTrack(){return this.destination.stream.getAudioTracks()[0]}},uv=new WeakMap,pn=class{constructor(e){h(this,"_volume",0),h(this,"_log"),h(this,"_scriptProcessorNode",null),h(this,"_audioWorkletNode",null),h(this,"_interval",200),h(this,"ready",this.preload());let{log:t}=e;this._log=t,R.on(A.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}get node(){return this._audioWorkletNode||this._scriptProcessorNode}preload(){return pn.workletReady||(pn.workletReady=Xh(pn.audioContext,URL.createObjectURL(new Blob([`
70
+ class VolumeMeter extends AudioWorkletProcessor{constructor(){super();this.volume=0;this.intervalTime=200;this.tick=this.intervalTime;this.isStop=false;this.cache=[];this.sentFirstInfo1=false;this.unmute=false;this.port.onmessage=(event)=>{const{data}=event;switch(data.name){case"chunk":this.cache.push.apply(this.cache,data.data);if(!this.sentFirstInfo1){this.port.postMessage({cl:data.data.length});this.sentFirstInfo1=true;}
71
+ break;case"setIntervalTime":this.intervalTime=data.intervalTime;break;case"unmute":this.unmute=true;break;case"stop":this.isStop=true;break;}};}
72
+ process(inputs,outputs){const input=inputs[0];const output=outputs[0];if(!input&&!output){return true;}
73
+ if(this.isStop){return false;}
74
+ const l=output?output[0].length:0;const cl=this.cache.length;if(cl>l){output[0].set(this.cache.slice(0,l));this.cache=this.cache.slice(l);}else if(this.unmute){output[0].set(input[0]);}
75
+ const firstChannel=cl>l?output[0]:input[0];if(!firstChannel){return true;}
76
+ let sum=0;let rms;for(let i=0;i<firstChannel.length;++i){sum+=firstChannel[i]*firstChannel[i];}
77
+ rms=Math.sqrt(sum/firstChannel.length);this.volume=Math.max(rms,this.volume*0.95);this.tick-=firstChannel.length;if(this.tick<0){this.tick+=(this.intervalTime/1000)*sampleRate;this.port.postMessage({volume:this.volume,cacheLen:cl,outputLen:l});}
78
+ return true;}}
79
+ registerProcessor("volume-meter",VolumeMeter);
80
+ `],{type:"application/javascript"})))),pn.workletReady.then(()=>this.initAudioWorklet()).catch(()=>this.initScriptProcessor())}initAudioWorklet(){if(!this._audioWorkletNode)try{this._audioWorkletNode=new AudioWorkletNode(pn.audioContext,"volume-meter");let e=!1;this._audioWorkletNode.port.onmessage=t=>{this._volume=t.data.volume||0,!e&&t.data.cacheLen&&t.data.outputLen&&(this._log.warn("worklet play success"),e=!0)},this.handleAudioLevelInterval({interval:this._interval})}catch(e){de.logFailedEvent({userId:this._log.userId,eventType:Ft.LOAD_WORKLET,error:e}),this.initScriptProcessor()}}initScriptProcessor(){if(!this._scriptProcessorNode)try{this._scriptProcessorNode=Ii().createScriptProcessor(2048,1,1),this._scriptProcessorNode.onaudioprocess=e=>{let t=e.inputBuffer.getChannelData(0),i=0;for(let r=0;r<t.length;++r)i+=t[r]*t[r];this._volume=Math.sqrt(i/t.length)||0}}catch(e){this._log.error("volumeMeter init script processor error: ".concat(e))}}destroy(){this._scriptProcessorNode&&(this._scriptProcessorNode.onaudioprocess=null),this._audioWorkletNode&&(this._audioWorkletNode.port.postMessage({name:"stop"}),this._audioWorkletNode.port.onmessage=null),this._audioWorkletNode=null,this._scriptProcessorNode=null,R.off(A.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}getInternalAudioLevel(){return this._volume}getCalculatedVolume(){return parseFloat(this._volume.toFixed(2))}handleAudioLevelInterval(e){var t;let{interval:i}=e;this._interval=i,(t=this._audioWorkletNode)==null||t.port.postMessage({name:"setIntervalTime",intervalTime:i})}},$h=pn;h($h,"audioContext",Ii()),h($h,"workletReady");var AV=class extends ur{constructor(e){super(),h(this,"_volumeMeter"),this._volumeMeter=new $h(e)}deleteNode(){super.deleteNode(),this._volumeMeter.destroy()}init(){return g(this,null,function*(){yield this._volumeMeter.preload(),this.setNode(this._volumeMeter.node)})}getCalculatedVolume(){return this._volumeMeter.getCalculatedVolume()}getInternalAudioLevel(){return this._volumeMeter.getInternalAudioLevel()}write(e){if(this.node){let t=e.allocationSize({planeIndex:0}),i=new Float32Array(t>>2);e.copyTo(i,{planeIndex:0}),this.node.port.postMessage({name:"chunk",data:i},[i.buffer]),e.close()}}},RV=Ie(Ve(),1),dv=e=>t=>t.deviceId===e,Zh=class{constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"Input";h(this,"kind"),h(this,"type"),h(this,"devices",[]),this.kind=e,this.type=t}update(e,t){let i=e.filter(r=>r.kind==="".concat(this.kind).concat(this.type.toLocaleLowerCase()));this.devices.length===1&&Js(this.devices[0])||t&&(i.forEach(r=>{if(r.deviceId&&!this.devices.find(dv(r.deviceId))){let n="".concat(this.kind).concat(this.type,"Added");b.warn("".concat(n,": ").concat(JSON.stringify(r))),t.emit(n,r)}}),this.devices.forEach(r=>{if(r.deviceId&&!i.find(dv(r.deviceId))){let n="".concat(this.kind).concat(this.type,"Removed");b.warn("".concat(n,": ").concat(JSON.stringify(r))),t.emit(n,r)}})),this.devices=i}hasDevice(e){return!!this.devices.find(t=>t.deviceId===e)}},CV=class extends RV.EventEmitter{constructor(){super(),h(this,"audioInputs",new Zh(_.AUDIO)),h(this,"videoInputs",new Zh(_.VIDEO)),h(this,"audioOutputs",new Zh(_.AUDIO,"Output")),this.init(),navigator.mediaDevices&&(navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",()=>this.update()),"ondevicechange"in navigator.mediaDevices||_e.run(Mo,()=>{this.update()},{delay:1e4}))}init(){ep().then(e=>{this.audioInputs.update(e),this.videoInputs.update(e),this.audioOutputs.update(e)})}update(){return g(this,arguments,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0;return function*(){let i=yield ep(t);return e.audioInputs.update(i,e),e.videoInputs.update(i,e),e.audioOutputs.update(i,e),e}()})}},ke=Fd||No?null:new CV;function Js(e){return e.deviceId===e.groupId&&e.groupId===""}function ep(){return g(this,arguments,function(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0;return function*(){if(ar()||!wh())return[];let t=yield navigator.mediaDevices.enumerateDevices();if(e!==0){let i={audio:!1,video:!1};if(t.forEach(r=>{Js(r)&&(r.kind===_.AUDIO_INPUT?i.audio=!0:r.kind===_.VIDEO_INPUT&&(i.video=!0))}),e===2&&(i.audio=!1),e===1&&(i.video=!1),i.audio||i.video){let r;try{r=yield navigator.mediaDevices.getUserMedia(i)}catch(n){b.debug("capture before getDevices failed: ",n)}t=yield navigator.mediaDevices.enumerateDevices(),r==null||r.getTracks().forEach(n=>n.stop())}}return t.map((i,r)=>{let n={kind:i.kind,deviceId:i.deviceId,groupId:i.groupId,label:i.label||"".concat(i.kind,"_").concat(r)};return i.deviceId.length>0&&tp.add("".concat(i.deviceId,"_").concat(i.kind)),i.getCapabilities&&(n.getCapabilities=()=>i.getCapabilities()),n})}()})}function zt(){let e=arguments.length>0&&arguments[0]!==void 0&&arguments[0];return ke.update(e?1:0).then(t=>t.audioInputs.devices)}function Ai(){let e=arguments.length>0&&arguments[0]!==void 0&&arguments[0];return ke.update(e?2:0).then(t=>t.videoInputs.devices)}var hv=!1;function mn(){let e=arguments.length>0&&arguments[0]!==void 0&&arguments[0];return g(this,null,function*(){return ke.update(e?1:0).then(t=>t.audioOutputs.devices)})}var tp=new Set;function pv(e,t){return g(this,null,function*(){let i=(yield zt()).find(r=>r.deviceId===fs);return(i==null?void 0:i.groupId)===e&&i.label===t})}var cc,bV=class extends cv{constructor(e){super(),this.log=e,h(this,"volumeMeter"),h(this,"volumeDestination"),h(this,"analyser",new vV),this.volumeMeter=new AV({log:this.log}),this.volumeDestination=new ur,this.volumeMeter.pipeTo(this.volumeDestination)}destory(){this.gain.deleteNode(),this.volumeMeter.deleteNode(),this.analyser.deleteNode(),this.source.deleteNode(),this.destination.deleteNode(),this.volumeDestination.deleteNode()}},ip=class extends dn{constructor(e){super(e,_.AUDIO),h(this,"_outputDeviceId"),h(this,"_volume",1),h(this,"_destination",Ii().createMediaStreamDestination()),h(this,"pipeline"),h(this,"volumeMeterMode","worklet"),this.pipeline=new bV(this._log)}getMediaStream(){return this.pipeline.stream||(this.track?new MediaStream([this.track]):null)}initializeElement(){if((tr==="15.2"||tr==="15.3"||tr==="15.4")&&this.muted)return void this._log.info("audioElement is muted.");let e=cc||new Audio;e.setAttribute("autoplay","autoplay"),e.srcObject=this.getMediaStream(),e.muted=this.muted,this.element=e,e===cc&&(cc=void 0),this.bindElementEvents()}play(){return g(this,null,function*(){if(this.track)return this.pipeline.source.node||this.pipeline.replaceSource(this.track),this.element||this.initializeElement(),this._outputDeviceId&&(yield this.setSinkId(this._outputDeviceId)),this.volumeMeterMode==="worklet"?this.pipeline.volumeMeter.init():this.volumeMeterMode==="analyser"&&this.pipeline.analyser.setNode(Ii().createAnalyser()),this.setVolume(this._volume),function(){g(this,null,function*(){try{hv||(hv=!0,b.info("speakers:".concat((yield mn()).map(e=>" ".concat(e.deviceId.slice(0,8),": ").concat(e.label)))))}catch{}})}(),it(ip.prototype,this,"play").call(this)})}stop(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0;this.pipeline.destory(),super.stop(e)}setSinkId(e){return g(this,null,function*(){var t,i;this._outputDeviceId!==e&&(this._outputDeviceId=e),this.element&&this.element.sinkId!==e&&(yield(i=(t=this.element).setSinkId)==null?void 0:i.call(t,e))})}get useDestination(){return!!this.pipeline.stream}setLoop(e){!this.element||(this.element.loop=e)}getAudioLevel(){return this.pipeline.volumeMeter.getCalculatedVolume()}getInternalAudioLevel(){return this.pipeline.volumeMeter.getInternalAudioLevel()}},kV=class extends ip{constructor(e){super(e),this.pipeline.source.pipeTo(this.pipeline.volumeMeter,this.pipeline.destination)}setTrack(e){var t;this.track!==e&&(this.unbindTrackEvents(),this.track=e,this.emit(rt.MEDIA_TRACK_CHANGED,e),e?(this.bindTrackEvents(),this.pipeline.source.channelCount=((t=e.getSettings())==null?void 0:t.channelCount)||1,this.pipeline.replaceSource(e),!this.useDestination&&this.element&&(this.element.srcObject=new MediaStream([e]))):this.pipeline.source.deleteNode())}setSourceNode(e){!e||this.pipeline.source.node===e||(this.pipeline.replaceSource(e),e instanceof MediaStreamAudioSourceNode?this.pipeline.destination.setNode(this._destination):this.pipeline.destination.deleteNode(),this.element&&(this.element.srcObject=this.getMediaStream(),this.element.play().catch(()=>{}),this.setVolume(this._volume)))}setVolume(e){this._volume=e,this.element&&(this.element.volume=e)}},NV=class extends ip{constructor(e){super(e),h(this,"_sourceElement"),this.pipeline.source.pipeTo(this.pipeline.gain.pipeTo(this.pipeline.volumeMeter,this.pipeline.destination))}write(e){this.pipeline.volumeMeter.write(e)}setTrack(e){var t,i,r;((i=(t=this.element)==null?void 0:t.error)==null?void 0:i.code)!==MediaError.MEDIA_ERR_DECODE&&this.track!==e&&(this.unbindTrackEvents(),this.track=e,this.emit(rt.MEDIA_TRACK_CHANGED,e),e?(this.bindTrackEvents(),this._sourceElement?this._sourceElement.srcObject=new MediaStream([e]):!this.useDestination&&this.element&&(this.element.srcObject=new MediaStream([e])),this.pipeline.source.channelCount=((r=e.getSettings())==null?void 0:r.channelCount)||1,this.pipeline.replaceSource(e)):this.pipeline.source.deleteNode())}setVolume(e){this._volume=e,this.useDestination?(this.pipeline.setVolume(e),this._log.info("set pipeline volume: ".concat(e))):e<=1?(this.element?this._log.info("set element volume: ".concat(e)):this._log.info("set element volume: no element"),this.element&&(this.element.volume=e)):(this._log.info("start set pipeline volume: ".concat(e)),this.pipeline.setVolume(e),this.element&&!this._sourceElement&&(this.pipeline.destination.setNode(this._destination),Pe(this.element),this._sourceElement=this.element,this._sourceElement.muted=!0,this.element=null,this.play()))}stop(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0;this.pipeline.destory();let t=this._sourceElement||this.element;t&&an&&(cc=t),this._sourceElement&&(this._sourceElement.srcObject=null,delete this._sourceElement),super.stop(e)}},rp=class extends X{constructor(e){let{userId:t,sdkAppId:i,mediaType:r,room:n,PlayerClass:s=r===1?NV:vi}=e;var a;super(),h(this,"id",LS()),h(this,"userId",""),h(this,"isRemote"),h(this,"mediaType"),h(this,"room"),h(this,"user"),h(this,"_log"),h(this,"_inputTrack"),h(this,"_outputTrack"),h(this,"isPlayCalled"),h(this,"container",null),h(this,"player"),h(this,"subVideoPlayerMap"),h(this,"muted",!1),h(this,"abortCtrl"),h(this,"objectFit","cover"),h(this,"mirror"),h(this,"isScreen",!1),h(this,"manager"),h(this,"trackSettings"),h(this,"onPlayerError"),this.userId=t||"",this.mediaType=r,this._log=b.createLogger({id:"".concat(this.kind[0],"t"),userId:(a=n||this.room)==null?void 0:a.userId,remoteUserId:this instanceof Ci?void 0:this.userId,sdkAppId:i,type:this.mediaType===2?"auxiliary":"main",isLocal:this instanceof Ci}),this.player=new s({id:this.userId||this.id,track:null,muted:!1,container:null,log:this._log}),this.player.on(rt.PLAYER_STATE_CHANGED,c=>{R.emit(A.PLAYER_STATE_CHANGED,O({track:this},c)),this.emit("player-state-changed",c)}),this.kind===_.VIDEO&&(this.player.on(rt.LOADED_DATA,()=>{R.emit(A.VIDEO_LOADED_DATA,{track:this})}),this.player.on(rt.MEDIA_TRACK_CHANGED,c=>{var o;(o=this.subVideoPlayerMap)==null||o.forEach(l=>l.setTrack(c))})),this.onTrackMuted=this.onTrackMuted.bind(this),this.onTrackUnmuted=this.onTrackUnmuted.bind(this),this.onTrackEnded=this.onTrackEnded.bind(this),this.onPlayerError&&this.player.on(rt.ERROR,this.onPlayerError.bind(this))}get log(){return this._log||b}get kind(){return this.mediaType===1?_.AUDIO:_.VIDEO}get strMediaType(){return this.mediaType===4?_.VIDEO:this.mediaType===2?_.SCREEN:_.AUDIO}get streamType(){return 2&this.mediaType?"auxiliary":"main"}play(e,t){return g(this,null,function*(){let i=Ce(e)?e[0]:e;if(this.isPlayCalled)return this.log.info("play update options: ".concat(JSON.stringify(t))),t&&!I(t.muted)&&this.setPlayerMute(t.muted),t&&!I(t.objectFit)&&(this.objectFit=t.objectFit),void(this.player instanceof vi&&(this.player.setObjectFit(this.objectFit),this.container!==i&&i&&(this.container=i,this.player.setContainer(i)),Ce(e)&&e.length>=1&&(yield this.playSubContainer(e.slice(1),t))));if(t&&!I(t.muted)?this.setPlayerMute(t.muted):(!this.isRemote||this.kind===_.VIDEO)&&this.setPlayerMute(!0),t&&!I(t.objectFit)&&(this.objectFit=t.objectFit),this.player instanceof vi&&this.player.setObjectFit(this.objectFit),this.isPlayCalled=!0,i&&(this.container=i,this.player instanceof vi&&this.player.setContainer(i)),R.emit(A.PLAY_TRACK_START,{track:this}),this._outputTrack){this._log.info("play with options: ".concat(JSON.stringify(t)));try{this.player.setTrack(this.playerMediaTrack),yield this.player.play(),Ce(e)&&e.length>1&&(yield this.playSubContainer(e.slice(1),t))}catch(r){throw this.handleAutoPlayFailed(),this.emit("error",r),r}}else this.log.info("play has not mediaTrack, abort")})}setMirror(e,t){if(this.isScreen||this.kind!==_.VIDEO||I(e)||e===this.mirror)return;this.mirror=e;let i=this.player;t&&(i=t);let r=this.manager;if(We(this.mirror))return i.setViewMirror(this.mirror),void(r&&(r.mirror=!1));switch(this.mirror){case"view":r&&(r.mirror=!1),i.setViewMirror(!0);break;case"publish":r&&(r.mirror=!0),i.setViewMirror(!0);break;case"both":r&&(r.mirror=!0),i.setViewMirror(!1)}}playSubContainer(e,t){return g(this,null,function*(){if(!this._outputTrack||this.kind===_.AUDIO)return;this.subVideoPlayerMap||(this.subVideoPlayerMap=new Map),this.subVideoPlayerMap.forEach((r,n)=>{var s;e.find(a=>n===a)||(r.stop(),(s=this.subVideoPlayerMap)==null||s.delete(n))});for(let[r,n]of e.entries()){let s=this.subVideoPlayerMap.get(n);s?t&&(I(t.objectFit)||s.setObjectFit(t.objectFit)):this.subVideoPlayerMap.set(n,new vi({id:this.userId||this.id,track:this.playerMediaTrack,container:n,muted:this.player.muted,objectFit:this.objectFit,log:this.log.createChild({id:"vp-sub".concat(r+1)})}))}let i=[...this.subVideoPlayerMap.values()];for(let r of i)r.setViewMirror(this.player.mirror),yield r.play()})}setAudioOutput(e){return this.player.setSinkId(e)}setAudioVolume(e){this.player.setVolume(e)}getAudioLevel(){return this.player.getAudioLevel()||0}getInternalAudioLevel(){var e;return((e=this.player)==null?void 0:e.getInternalAudioLevel())||0}stop(){!this.isPlayCalled||(this.isPlayCalled=!1,this.player&&(this.log.info("stop ".concat(this.kind," player")),this.player.stop(yi(this)?this.jitterBufferDelay:0)),this.subVideoPlayerMap&&this.subVideoPlayerMap.size>0&&this.subVideoPlayerMap.forEach(e=>{e.stop()}),this.container=null)}resume(){return g(this,null,function*(){var e;!this.isPlayCalled||(yield(e=this.player)==null?void 0:e.resume())})}close(){this.log.info("close"),this.isPlayCalled&&this.stop()}setMute(e){this.muted=e,this._inputTrack&&(this._inputTrack.enabled=!e),this._outputTrack&&(this._outputTrack.enabled=!e),this.emit(e?"mute":"unmute",this),R.emit(e?A.TRACK_MUTED:A.TRACK_UNMUTED,{track:this})}setPlayerMute(e){this.player.setMuted(e)}get mediaTrack(){return this._inputTrack||null}get outMediaTrack(){return this._outputTrack||null}get playerMediaTrack(){return this.outMediaTrack}installTrackEvent(e){ht(e,e).add(_.MUTE,this.onTrackMuted).add(_.UNMUTE,this.onTrackUnmuted).add(_.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===_.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){Pe(e)}setInputMediaStreamTrack(e){var t;let i=this._inputTrack;if(e!==i)return this._inputTrack=e,this.trackSettings=(t=e.getSettings)==null?void 0:t.call(e),e.enabled=!this.muted,i&&this.uninstallTrackEvent(i),this.installTrackEvent(e),this.emit("input-media-track-changed",e||null,i||null),this.manager?this.manager.changeInput(this):this.setOutputMediaStreamTrack(e)}setOutputMediaStreamTrack(e){var t;e!==this._outputTrack&&(this.isRemote?this.log.debug("setOutputMediaStreamTrack",e.label):this.log.info("setOutputMediaStreamTrack",(t=e.getSettings)==null?void 0:t.call(e).deviceId,e.label),this._outputTrack=e,this.updatePlayingState(!!e),this.emit("output-media-track-changed",e))}setMediaType(e){this.mediaType=e}updatePlayingState(e){if(this.isPlayCalled){if(e){if(this.player.setTrack(this.playerMediaTrack),this.player.isStopped)return this.player.play().catch(()=>this.handleAutoPlayFailed()),void this.log.info("playing state updated, play ".concat(this.kind))}else if(!this.player.isStopped)return this.player.stop(yi(this)?this.jitterBufferDelay:0),void this.log.info("playing state updated, stop ".concat(this.kind))}this.log.debug("updatePlayingState abort ".concat(this.isPlayCalled," ").concat(e," ").concat(this.player.isStopped))}handleAutoPlayFailed(){if(this.room&&this.room.enableAutoPlayDialog)new SV;else{let e=()=>{this.resume().then(()=>{document.removeEventListener("click",e,!0)})};document.addEventListener("click",e,!0)}}getVideoFrame(){return this.player instanceof vi?this.player.getVideoFrame():""}onTrackMuted(){this._log.warn("".concat(this.kind," track is unable to provide media output"))}onTrackUnmuted(){this._log.info("".concat(this.kind," track is able to provide media output"))}onTrackEnded(){this._log.warn("".concat(this.kind," track ended"))}};k([be([],X.INIT,{sync:!0})],rp.prototype,"close");var DV=Object.prototype.hasOwnProperty,Ri=function(e){if(e==null)return!0;if(typeof e=="boolean")return!1;if(typeof e=="number")return e===0;if(typeof e=="string"||typeof e=="function"||Array.isArray(e))return e.length===0;if(e instanceof Error)return e.message==="";if(jt(e))switch(Object.prototype.toString.call(e)){case"[object File]":case"[object Map]":case"[object Set]":return e.size===0;case"[object Object]":for(let t in e)if(DV.call(e,t))return!1;return!0}return!1},wV=ws({retryFunction:function(e){return g(this,null,function*(){let t=function(s){return{audio:OV(s),video:PV(s)}}(e);b.info("getUserMedia with constraints: ".concat(JSON.stringify(t)));let i=[],r=[],n=["label","deviceId"];t.audio&&(i=yield zt(),b.info("microphones: ".concat(Gt(i,{keysToInclude:n})))),t.video&&(r=yield Ai(),b.info("cameras: ".concat(Gt(r,{keysToInclude:n}))));try{let s=yield navigator.mediaDevices.getUserMedia(t);return WS&&s.getTracks().forEach(a=>{b.info("".concat(a.kind," capabilities: ").concat(Gt(a.getCapabilities(),{keysToInclude:Xd})))}),s}catch(s){let{message:a}=s;throw s.name==="NotFoundError"&&(e.video&&r&&r.length===0&&(a=j({key:B.CAMERA_NOT_FOUND})),e.audio&&i&&i.length===0&&(a=j({key:B.MICROPHONE_NOT_FOUND}))),new N({code:C.INITIALIZE_FAILED,name:s.name,message:a,constraint:s.constraint})}})},settings:{retries:3,timeout:500},onError:e=>{let{error:t,retry:i,reject:r,retryFuncArgs:n,retriedCount:s}=e,a=s+1;t.name==="NotReadableError"||t.name==="OverconstrainedError"?(a===1?n[0].video&&(n[0].maxResolution=!1,(!Rt||n[0].width*n[0].height<=2073600)&&n[0].frameRate&&(n[0].frameRate=n[0].frameRate>10?10:5)):a===2?n[0].useDeviceIdOnly=!0:a===3&&!n[0].useExactDeviceId&&(n[0].useTrueAsConstraint=!0),i()):r(t),n[0].microphoneId&&mv(n[0].microphoneId,!1),n[0].cameraId&&mv(n[0].cameraId,!0)},onRetrying:e=>{b.warn("getUserMedia NotReadableError observed, retrying [".concat(e,"/3]"))},onRetryFailed:e=>{de.logFailedEvent({eventType:Ft.GET_USER_MEDIA_RETRY,error:e})},onRetrySuccess:e=>{de.logSuccessEvent({eventType:Ft.GET_USER_MEDIA_RETRY}),de.uploadEvent({log:"stat-".concat(Ft.GET_USER_MEDIA_RETRY,"-success-").concat(e)})}});function mv(e,t){return g(this,null,function*(){let i=(t?yield Ai():yield zt()).find(r=>r.deviceId===e);i&&ne(i.getCapabilities)&&b.warn(Gt(i.getCapabilities(),{keysToInclude:Xd}))})}function OV(e){if(!e.audio)return!1;if(e.useTrueAsConstraint)return!0;let t={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:e.sampleRate};return!Ri(e.microphoneId)&&(t.deviceId=e.useExactDeviceId?{exact:e.microphoneId}:e.microphoneId,e.useDeviceIdOnly)?t:(ge(e.channelCount)&&(t.channelCount=e.channelCount),We(e.echoCancellation)&&!e.echoCancellation&&(t.echoCancellation=!1),We(e.noiseSuppression)&&!e.noiseSuppression&&(t.noiseSuppression=!1),We(e.autoGainControl)&&!e.autoGainControl&&(t.autoGainControl=!1),!!Ri(t)||t)}function PV(e){if(!e.video)return!1;if(e.useTrueAsConstraint)return!0;let{maxResolution:t=!0}=e,i={};return e.cameraId?i.deviceId=e.useExactDeviceId?{exact:e.cameraId}:e.cameraId:e.facingMode&&(i.facingMode=e.facingMode),e.useDeviceIdOnly&&!Ri(i)?i:(e.width&&(i.width={ideal:e.width},t&&!ue&&(i.width.max=e.width)),e.height&&(i.height={ideal:e.height},t&&!ue&&(i.height.max=e.height)),ue&&$i&&e.width&&e.height&&e.width*e.height<101376&&(i.width=e.width,i.height=e.height),e.frameRate&&(i.frameRate=e.frameRate),!!Ri(i)||i)}var LV=wV;function _v(e){return ae((t,i)=>function(){for(var r=arguments.length,n=new Array(r),s=0;s<r;s++)n[s]=arguments[s];return g(this,null,function*(){return yield e.apply(this,n),t.apply(this,n)})})}function np(e){return ae((t,i)=>function(){for(var r=arguments.length,n=new Array(r),s=0;s<r;s++)n[s]=arguments[s];return g(this,null,function*(){let a=yield t.apply(this,n);return yield e.call(this,...n),a})})}function ae(e){return function(t,i,r){return r.value=e(r.value,i),r}}var MV=(()=>{let e=!1,t=document.visibilityState;return()=>{document.visibilityState!==t&&b.info("visibility change: ".concat(document.visibilityState)),!e&&(document.addEventListener("visibilitychange",()=>{b.info("visibility change: ".concat(document.visibilityState)),t=document.visibilityState}),e=!0)}})(),xV=0,fv=class{constructor(){this.log=b.createLogger({id:"fq".concat(++xV)}),this.isRunning=!1,this.queue=[]}get length(){return this.queue.length}get lastQueueItem(){return this.length===0?null:this.queue[this.length-1]}push(e){let t=arguments.length>1&&arguments[1]!==void 0&&arguments[1];var i,r;let n=O({},e),s=new Promise((a,c)=>{n.resolve=a,n.reject=c});return n.promise=s,t?this.length<=1?this.queue.push(n):(r=(i=this.lastQueueItem)==null?void 0:i.promise)==null||r.then(n.resolve,n.reject):this.queue.push(n),this.log.debug("push ".concat(this.length)),this.isRunning||this.callNext(),s}shift(){let e=this.queue.shift();return this.log.debug("shift ".concat(this.length)),e}callNext(){if(this.isRunning||this.length===0)return;this.log.debug("callNext ",this.length);let{fn:e,args:t,context:i,resolve:r,reject:n}=this.queue[0];this.isRunning=!0,e.apply(i,t).then(r,n).finally(()=>{this.isRunning=!1,this.shift(),this.callNext()})}},zs=new WeakMap,lc=new WeakMap;function _n(){let e=arguments.length>0&&arguments[0]!==void 0&&arguments[0];return function(t,i,r){let n=r.value;return r.value=function(){let s=zs.get(this)||new fv;for(var a=arguments.length,c=new Array(a),o=0;o<a;o++)c[o]=arguments[o];return zs.set(this,s),s.push({fn:n,args:c,context:this},e)},r}}function gv(e){return function(t,i,r){let n=r.value;return r.value=function(){var s,a,c;let o=[];for(var l=arguments.length,d=new Array(l),u=0;u<l;u++)d[u]=arguments[u];return(a=(s=zs.get(this))==null?void 0:s.queue)==null||a.forEach(p=>o.push(p)),(c=lc.get(this))==null||c.forEach(p=>p==null?void 0:p.queue.forEach(m=>o.push(m))),o.forEach(p=>{p.reject(new N({code:C.API_CALL_ABORTED,message:e}))}),zs.delete(this),lc.delete(this),n.apply(this,d)},r}}function fn(e){return function(t,i,r){let n=r.value,s=a=>e(...a);return r.value=function(){for(var a=arguments.length,c=new Array(a),o=0;o<a;o++)c[o]=arguments[o];let l=lc.get(this)||new Map,d=l.get(s(c))||new fv;return l.set(s(c),d),lc.set(this,l),d.push({fn:n,args:c,context:this})},r}}var Tv=class extends rp{constructor(e,t){super({mediaType:e,PlayerClass:t}),h(this,"isRemote",!1),h(this,"deviceId"),h(this,"groupId",""),h(this,"label",""),h(this,"_isRecapturing",!1),h(this,"_lastRecaptureTime",0),h(this,"_onMuteTimeoutId",-1),h(this,"profile")}get enableEncodeFrame(){return!1}get isPublished(){return this.state==="publish"}encodeFrame(e,t){throw new Error("Method not implemented.")}installTrackEvent(e){ht(e,e).add(_.MUTE,this.onTrackMuted).add(_.UNMUTE,this.onTrackUnmuted).add(_.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===_.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){Pe(e)}setStateToCapture(){}capture(e){return g(this,null,function*(){var t;try{let i,r=W();R.emit(A.LOCAL_TRACK_CAPTURE_START,{track:this}),e.customSource?(i=new MediaStream,i.addTrack(e.customSource)):((t=this.mediaTrack)==null||t.stop(),i=yield LV(e));let n=i.getTracks()[0];return yield this.setInputMediaStreamTrack(n),e.customSource||(this.updateDeviceIdInUse(),this.listenDeviceChange()),R.emit(A.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this,cost:W()-r}),i}catch(i){throw R.emit(A.LOCAL_TRACK_CAPTURE_FAILED,{track:this,error:i}),this.log.error("getUserMedia error observed ".concat(i)),i}})}setInputMediaStreamTrack(e){return this.state===X.INIT&&this.setStateToCapture(),super.setInputMediaStreamTrack(e)}setOutputMediaStreamTrack(e){var t;return super.setOutputMediaStreamTrack(e),(t=this.room)==null?void 0:t.replaceTrack(this)}publish(e,t){return this.room=e,this.emit("4",{mediaType:this.strMediaType,state:"starting",prevState:"stopped"}),this.userId=e.userId,this._log.setUserId(e.userId),this._log.setSdkAppId(e.sdkAppId),t}unpublish(){this.room&&this.room.localTracks.delete(this),R.emit(A.LOCAL_TRACK_UNPUBLISHED,{track:this})}updateDeviceIdInUse(){return g(this,null,function*(){if(this.mediaTrack&&un){let{deviceId:e,groupId:t}=this.mediaTrack.getSettings(),{label:i}=this.mediaTrack;(yield function(r){return g(this,arguments,function(n){let{newDeviceId:s,oldDeviceId:a,oldGroupId:c,oldLabel:o,kind:l}=n;return function*(){return s===a&&(l!==_.AUDIO||s!==fs||(yield pv(c,o)))}()})}({newDeviceId:e,oldDeviceId:this.deviceId,oldGroupId:this.groupId,oldLabel:this.label,kind:this.kind}))||(this.deviceId=e,this.label=i,t&&(this.groupId=t),ep().then(r=>{let n=r.find(s=>s.deviceId===e);n&&this.emit("2",n)}))}})}setProfile(e){this.log.info("setProfile",e),Object.assign(this.profile,e)}isNeedToRecapture(){let e=arguments.length>0&&arguments[0]!==void 0&&arguments[0];return!(!this.deviceId||!this.mediaTrack||this.kind===_.AUDIO&&!function(t){if(t instanceof CanvasCaptureMediaStreamTrack||!(t instanceof MediaStreamTrack))return!1;let i=t.label.toLocaleLowerCase();if(i.includes("mic")||i.includes("麦克风"))return!0;let r="".concat(((t==null?void 0:t.getSettings())||{}).deviceId,"_").concat(_.AUDIO_INPUT);return!!tp.has(r)}(this.mediaTrack)||this.kind===_.VIDEO&&!function(t){if(t instanceof CanvasCaptureMediaStreamTrack||!(t instanceof MediaStreamTrack))return!1;let i=t.label.toLocaleLowerCase();if(i.includes("camera")||i.includes("webcam"))return!0;let r="".concat(((t==null?void 0:t.getSettings())||{}).deviceId,"_").concat(_.VIDEO_INPUT);return!!tp.has(r)}(this.mediaTrack)||this._isRecapturing||e&&$i&&Rt)}onTrackMuted(){if(super.onTrackMuted(),MV(),this.isNeedToRecapture(!0)){if(Date.now()-this._lastRecaptureTime<Ts)return void setTimeout(()=>this.onTrackMuted(),Ts);this._onMuteTimeoutId=setTimeout(()=>g(this,null,function*(){var e;if((e=this.mediaTrack)!=null&&e.muted){if((Bt||Ue)&&document.visibilityState!=="visible")return;this.recapture(yield this.getRecoverCaptureDeviceId())}}),5e3)}}onTrackUnmuted(){super.onTrackUnmuted(),this._onMuteTimeoutId>0&&clearTimeout(this._onMuteTimeoutId)}onTrackEnded(){return g(this,null,function*(){if(it(Tv.prototype,this,"onTrackEnded").call(this),this.isNeedToRecapture()){if(Date.now()-this._lastRecaptureTime<Ts)return void setTimeout(()=>this.onTrackEnded(),Ts);this.recapture(yield this.getRecoverCaptureDeviceId())}})}recapture(e){return g(this,null,function*(){var t;if(this._isRecapturing||!this._inputTrack)return;this.log.warn("recapture trying"),(t=this._inputTrack)==null||t.stop(),this._isRecapturing=!0,this._lastRecaptureTime=Date.now();let i={useExactDeviceId:!0};if(e==="user"||e==="environment")i.facingMode=e;else{let r;(this.kind==="audio"?yield zt():yield Ai()).find(n=>n.deviceId===e)&&(r=e),i.deviceId=r}return this.capture(i).then(()=>{this._isRecapturing=!1,this.log.warn("recapture success"),this.emit("1",{deviceId:this.deviceId}),R.emit(A.LOCAL_TRACK_RECAPTURE,{track:this})}).catch(r=>{this._isRecapturing=!1,this.log.warn("recapture failed ".concat(r.message)),this.emit("5",r),R.emit(A.LOCAL_TRACK_RECAPTURE,{track:this,error:r})})})}getRecoverCaptureDeviceId(){return g(this,null,function*(){let e=this instanceof Je;if(e&&this.facingMode)return this.facingMode;let{deviceId:t}=this;if(t){let i=(Ks.get(t)||0)+1;if(Ks.set(t,i),i>=3){let r=e?(yield Ai()).find(n=>!Ks.has(n.deviceId)):(yield zt()).find(n=>!Ks.has(n.deviceId));r&&(this.log.warn("".concat(t," capture fail ").concat(i," times, change new ").concat(r.deviceId)),t=r.deviceId)}}return t})}close(){var e;super.close(),this._inputTrack&&(this._inputTrack.stop(),this.uninstallTrackEvent(this._inputTrack)),(e=this.manager)==null||e.removeInput(this)}},Ci=Tv;k([be(X.INIT,"capture",{ignoreError:!0,sync:!0})],Ci.prototype,"setStateToCapture"),k([_n()],Ci.prototype,"capture"),k([be("capture","publish",{ignoreError:!0,success(){this.room.localTracks.add(this),R.emit(A.LOCAL_TRACK_PUBLISHED,{track:this}),this.emit("4",{mediaType:this.strMediaType,state:"started",prevState:"starting"})},fail(e){let t="error",i=e.cause;i.message.includes("timeout")?t="timeout":i.code===C.API_CALL_ABORTED&&(t="api-call"),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:"starting",reason:t,error:i})}})],Ci.prototype,"publish"),k([ae(e=>function(){return g(this,null,function*(){let t=this.state==="publish"?"started":"starting";e.call(this),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:t,reason:"api-call"})})}),be([],"capture",{sync:!0})],Ci.prototype,"unpublish");var Ks=new Map;R.on(A.SWITCH_DEVICE_SUCCESS,e=>{e.track.deviceId&&Ks.delete(e.track.deviceId)});var Kt=class extends Ci{constructor(e){super(1,kV),h(this,"mediaType",1),h(this,"volume",0),h(this,"profile",{echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0,sampleRate:48e3,channelCount:1,bitrate:40}),h(this,"playerMuted",!0),h(this,"pipeline"),this.manager=e,this.pipeline=new lv(e),this.handleMicrophoneAdded=this.handleMicrophoneAdded.bind(this),this.handleMicrophoneRemoved=this.handleMicrophoneRemoved.bind(this)}getAudioLevel(){let e=(this.volume||super.getAudioLevel())*this.captureVolume;return e>1?1:e}get playerMediaTrack(){return this.mediaTrack}setInputMediaStreamTrack(e){return g(this,null,function*(){yield it(Kt.prototype,this,"setInputMediaStreamTrack").call(this,e);let t=this.trackSettings||{};L.addEnum({key:501701,value:t.channelCount||0,useUV:!1}),L.addEnum({key:501702,value:t.sampleRate||0,useUV:!1}),L.addEnum({key:502700,value:0});let{sampleRate:i,channelCount:r}=t;this._log.info("local audio track input ".concat(JSON.stringify({sampleRate:i,channelCount:r}))),this.pipeline.source.channelCount=r||1,this.pipeline.replaceSource(e),this.updatePlayingState(!!e)})}capture(e){let{deviceId:t,customSource:i,useExactDeviceId:r=!1}=e;return super.capture({video:!1,audio:!0,microphoneId:t,echoCancellation:this.profile.echoCancellation,autoGainControl:this.profile.autoGainControl,noiseSuppression:this.profile.noiseSuppression,sampleRate:this.profile.sampleRate,channelCount:this.profile.channelCount,useExactDeviceId:r,customSource:i})}switchDevice(e){return g(this,null,function*(){if(this.mediaTrack){if(this.deviceId===e&&(e!==fs||(yield pv(this.groupId,this.label))))return;try{this.log.info("switchDevice audio to: ".concat(e)),this.mediaTrack&&this.mediaTrack.stop(),yield this.capture({deviceId:e,useExactDeviceId:!0}),this.room&&(yield this.room.replaceTrack(this)),R.emit(A.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch microphone success")}catch(t){throw this.log.error("switch microphone failed ".concat(t)),this.deviceId&&this.recapture(this.deviceId),t}}})}listenDeviceChange(){ke&&!ke.listeners("audioInputRemoved").includes(this.handleMicrophoneRemoved)&&ke.on("audioInputRemoved",this.handleMicrophoneRemoved,this)}handleMicrophoneRemoved(e){return g(this,null,function*(){if(e.deviceId===this.deviceId){this.log.warn("current microphone is lost: ".concat(JSON.stringify(e))),me(this.userId,{eventId:2003,param1:6,streamType:1});let t=yield zt();t[0]?this.recapture(t[0].deviceId):ke.on("audioInputAdded",this.handleMicrophoneAdded,this)}})}handleMicrophoneAdded(e){this.log.warn("microphone added: ".concat(JSON.stringify(e))),this.recapture(e.deviceId)}update3A(e){return g(this,arguments,function(t){var i=this;let{echoCancellation:r,noiseSuppression:n,autoGainControl:s}=t;return function*(){let a=!1;!I(r)&&r!==i.profile.echoCancellation&&(i.profile.echoCancellation=r,a=!0),!I(n)&&n!==i.profile.noiseSuppression&&(i.profile.noiseSuppression=n,a=!0),!I(s)&&s!==i.profile.autoGainControl&&(i.profile.autoGainControl=s,a=!0),a&&i.deviceId&&(yield i.recapture(i.deviceId))}()})}get captureVolume(){return this.pipeline.volume}setCaptureVolume(e){this.pipeline.setVolume(e/100),this.pipeline.gain.node&&L.addEnum({key:502700,value:2}),this.resetPlayerSource()}enableTrackANS(e){if(!this._inputTrack)return;let t=this._inputTrack.getConstraints();return t.noiseSuppression=e,this._inputTrack.applyConstraints(t).catch(i=>this._log.warn("".concat(e?"enable":"disable"," ANS failed "),i))}addDenoiser(e){var t;er<=92&&((t=this.trackSettings)==null?void 0:t.sampleRate)!==48e3?this._log.warn("denoiser only support sampleRate 48000 before chrome 93"):(L.addEnum({key:502700,value:1}),this.pipeline.denoiser.setNode(e),this.resetPlayerSource(),this.enableTrackANS(!1))}removeDenoiser(e){this.pipeline.denoiser.node===e&&(this.pipeline.denoiser.deleteNode(),this.resetPlayerSource(),this.enableTrackANS(!0))}resetPlayerSource(){this.player.setSourceNode(this.pipeline.gain.node||this.pipeline.denoiser.node||this.pipeline.source.node)}close(){this.pipeline.remove(),ke.off("audioInputAdded",this.handleMicrophoneAdded,this),ke.off("audioInputRemoved",this.handleMicrophoneRemoved,this),super.close()}recapture(e){return g(this,null,function*(){try{yield it(Kt.prototype,this,"recapture").call(this,e)}catch(t){let i=(yield zt()).find(r=>r.deviceId!==e);if(!i)throw t;yield it(Kt.prototype,this,"recapture").call(this,i.deviceId)}})}},Ev=class{constructor(e){let t=arguments.length>1&&arguments[1]!==void 0&&arguments[1];this.dataView=e,this.isSEI&&(t?this.addPreventionByte():this.removePreventionByte())}addPreventionByte(){let e=this.seiPayloadStartIndex,t=this.dataView.byteLength-2,i=[],r=0;for(let s=e;s<=t;s++){let a=this.dataView.getInt8(s);switch(a){case 0:case 1:case 2:case 3:r===2&&(i.push(3),r=0),a==0?r++:r=0,i.push(a);break;default:r=0,i.push(a)}}i.push(this.dataView.getInt8(this.dataView.byteLength-1));let n=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,e),...i]).buffer);this.dataView=n}removePreventionByte(){let e=this.seiPayloadStartIndex,t=this.dataView.byteLength-1,i=[],r=0;for(let s=e;s<=t;s++)switch(this.dataView.getInt8(s)){case 0:r++,i.push(this.dataView.getInt8(s));break;case 3:r!==2&&i.push(this.dataView.getInt8(s)),r=0;break;default:i.push(this.dataView.getInt8(s)),r=0}let n=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,e),...i]).buffer);this.dataView=n}get isSEI(){return this.dataView.getUint8(4)===6}get seiPayloadStartIndex(){let e=6;for(let t=6;t<this.dataView.buffer.byteLength&&(e++,this.dataView.getUint8(t)===255);t++);return e}get seiPayloadType(){return this.isSEI?this.dataView.getUint8(5):null}get seiPayload(){if(!this.isSEI)return null;let e=0,t=6;for(let n=6;n<this.dataView.buffer.byteLength;n++){let s=this.dataView.getUint8(n);if(t++,s!==255){e+=s;break}e+=255}let i=new ArrayBuffer(e),r=new DataView(i);for(let n=0;n<i.byteLength;n++,t++)r.setInt8(n,this.dataView.getInt8(t));return r}},VV=class{constructor(){h(this,"_seiMessageList",[]),h(this,"_smallSeiMessageList",[]),h(this,"_seiPayloadType",243)}encodeSEINalu(e){let t=e.byteLength,i=parseInt(String(t/255),10),r=t%255,n=[];n.push(0,0,0,1,6,this._seiPayloadType);for(let a=0;a<i;a++)n.push(255);n.push(r);let s=new DataView(e);return n.push(...new Uint8Array(s.buffer)),n.push(128),new Ev(new DataView(new Uint8Array(n).buffer),!0)}sendSEI(e,t){t!=null&&t.seiPayloadType&&(this._seiPayloadType=t.seiPayloadType),this._seiMessageList.push(e),t!=null&&t.small&&this._smallSeiMessageList.push(e)}getNaluCount(e){let t=0,i=0,r=new DataView(e);for(let n=0;n<e.byteLength;n++)switch(r.getUint8(n)){case 0:t++;break;case 1:(t===2||t===3)&&i++,t=0;break;default:t=0}return i}encode(e,t){let i=t?this._smallSeiMessageList:this._seiMessageList;if(i.length>0&&e.data.byteLength>0){let r=9-this.getNaluCount(e.data);if(r<=0)return 0;let n=i.splice(0,r).reverse().map(this.encodeSEINalu.bind(this)),s=n.reduce((d,u)=>d+u.dataView.byteLength,0),a=new ArrayBuffer(s+e.data.byteLength),c=new DataView(a),o=new DataView(e.data),l=0;for(let d=0;d<n.length;d++)for(let u=0;u<n[d].dataView.byteLength;u++)c.setInt8(l++,n[d].dataView.getInt8(u));for(let d=0;d<e.data.byteLength;d++)c.setInt8(l++,o.getInt8(d));return e.data=a,n.length}return 0}},Je=class extends Ci{constructor(e){super(arguments.length>1&&arguments[1]!==void 0?arguments[1]:4,vi),h(this,"profile",{width:640,height:480,frameRate:15,bitrate:500}),h(this,"states",{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0}),h(this,"small"),h(this,"isNeedToSetBandwidth"),h(this,"muteImage"),h(this,"manager"),h(this,"_seiCodec",new VV),this.manager=e;let t=()=>{this.isAllowed2k4k(this.profile)?this.room&&this.settings.height>=1440&&this.state==="publish"&&this.room.sendAbilityStatus({"2k4k":1}):(this.log.warn("Resolution is reset to 1080p, need to upgrade ability here https://cloud.tencent.com/document/product/647/85386"),this.setProfile(J(O({},this.profile),{width:1920,height:1080})),this.applyProfile())};this.on("input-media-track-changed",t),this.on("publish",t),this.handleCameraAdded=this.handleCameraAdded.bind(this),this.handleCameraRemoved=this.handleCameraRemoved.bind(this)}get facingMode(){if(un&&this.mediaTrack)return this.mediaTrack.getSettings().facingMode}get isQosClearFirst(){var e;return((e=this._inputTrack)==null?void 0:e.contentHint)==="detail"}setMute(e){return g(this,null,function*(){var t,i,r;if(re(e)){if(this.muteImage===e)return;yield(t=this.manager)==null?void 0:t.deleteWatermark("mute"),yield(i=this.manager)==null?void 0:i.setWatermark({x:0,y:0,width:this.settings.width,height:this.settings.height,type:"mute",zIndex:999,imageUrl:e}),this.muteImage=e,it(Je.prototype,this,"setMute").call(this,!1)}else yield(r=this.manager)==null?void 0:r.deleteWatermark("mute"),this.muteImage=void 0,it(Je.prototype,this,"setMute").call(this,e)})}capture(e){let{deviceId:t,facingMode:i,useExactDeviceId:r=!1,customSource:n}=e;return super.capture({audio:!1,video:!0,facingMode:i||this.facingMode,cameraId:t,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,useExactDeviceId:r,customSource:n})}setProfile(e){let t=O({},e),i=t.width>t.height;t.width*t.height<=19200&&Ue&&Zi&&(this.log.warn("resolution is ".concat(t.width,"*").concat(t.height,", fallback to 240*180")),t.width=i?240:180,t.height=i?180:240,t.bitrate=Math.max(t.bitrate,150)),t.width*t.height>921600&&hS&&(t.width=i?1280:720,t.height=i?720:1280,this.log.warn("reset to 1280 * 720 on iOS 13~14")),t.bitrate&&(this.isNeedToSetBandwidth=t.bitrate!==this.profile.bitrate),this.isAllowed2k4k(this.profile)?super.setProfile(t):(this.log.warn("Resolution is reset to 1080p, need to upgrade ability here https://cloud.tencent.com/document/product/647/85386"),super.setProfile(J(O({},this.profile),{width:1920,height:1080})))}applyProfile(){var e;if(!this.mediaTrack)return;let t=this.settings;return t.height!==this.profile.height||t.width!==this.profile.width||t.frameRate!==this.profile.frameRate?(e=this.mediaTrack)==null?void 0:e.applyConstraints({width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate}).then(()=>{if(this.manager&&this.manager.changeInput(this),this.room&&this.settings.height>=1440&&this.state==="publish"&&this.room.sendAbilityStatus({"2k4k":1}),this.isNeedToSetBandwidth&&this.room&&this.room.setBandWidth)return this.isNeedToSetBandwidth=!1,this.room.setBandWidth({bandwidth:this.profile.bitrate,type:_.VIDEO,videoType:_.BIG})}):void 0}get settings(){let e={width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate};return un&&this.mediaTrack&&Object.assign(e,this.mediaTrack.getSettings()),e}get scaleResolutionDownBy(){let{settings:e}=this;return e.width===this.profile.width&&e.height===this.profile.height?1:wS()&&this.profile.width>this.profile.height&&e.height>e.width?Math.max(e.width/this.profile.height,e.height/this.profile.width,1):Math.max(e.width/this.profile.width,e.height/this.profile.height,1)}isAllowed2k4k(e){var t;return!(this.room&&this.room.scheduleResult&&!this.isScreen&&!(e.height*e.width<3686400))||((t=this.room.scheduleResult.trtcAutoConf)==null?void 0:t["2k4k"])===1}isNeedToSwitchDevice(e){return!(!this.mediaTrack||this.deviceId===e||this.facingMode===e)}switchDevice(e){return g(this,null,function*(){try{if(!this.isNeedToSwitchDevice(e))return;let t={useExactDeviceId:!0};e==="user"||e==="environment"?t.facingMode=e:t.deviceId=e,this.mediaTrack.stop(),yield this.capture(t),R.emit(A.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch camera success")}catch(t){throw this.log.error("switch camera failed ".concat(t)),this.deviceId&&this.recapture(this.deviceId),t}})}listenDeviceChange(){ke&&!ke.listeners("videoInputRemoved").includes(this.handleCameraRemoved)&&ke.on("videoInputRemoved",this.handleCameraRemoved,this)}handleCameraRemoved(e){return g(this,null,function*(){if(e.deviceId===this.deviceId){this.log.warn("current camera is lost: ".concat(JSON.stringify(e))),me(this.userId,{eventId:2003,param1:7,streamType:2});let t=yield Ai();t[0]?this.recapture(t[0].deviceId):ke.on("videoInputAdded",this.handleCameraAdded,this)}})}handleCameraAdded(e){return g(this,null,function*(){this.log.warn("camera added: ".concat(JSON.stringify(e))),this.recapture(e.deviceId)})}encodeFrame(e,t){try{let i=this._seiCodec.encode(e,!!t);i&&this._log.debug("".concat(i," sei sent"))}catch(i){this._log.warn(i)}return e}get enableEncodeFrame(){var e;return!((e=this.room)==null||!e.enableSEI)&&or}sendSEI(e,t){this._seiCodec.sendSEI(e,Object.assign({small:!!this.small},t))}play(e,t){return g(this,null,function*(){return I(this.mirror)&&!this.isScreen&&this.setMirror("view"),it(Je.prototype,this,"play").call(this,e,t)})}close(){ke.off("videoInputAdded",this.handleCameraAdded,this),ke.off("videoInputRemoved",this.handleCameraRemoved,this),super.close()}recapture(e){return g(this,null,function*(){try{yield it(Je.prototype,this,"recapture").call(this,e)}catch(t){let i=(yield Ai()).find(r=>r.deviceId!==e);if(!i)throw t;yield it(Je.prototype,this,"recapture").call(this,i.deviceId)}})}},yv=LS();if(navigator.mediaDevices&&"setCaptureHandleConfig"in navigator.mediaDevices)try{navigator.mediaDevices.setCaptureHandleConfig({handle:yv,exposeOrigin:!0,permittedOrigins:["*"]})}catch{}var sp,UV=function(e){return g(this,null,function*(){let t=null,i=function(s){let a={preferCurrentTab:s.preferDisplaySurface==="current-tab"||!!s.captureElement,systemAudio:"include",selfBrowserSurface:"include",surfaceSwitching:"include"},c={width:Rt?{max:s.width}:{ideal:s.width,max:s.width},height:Rt?{max:s.height}:{ideal:s.height,max:s.height},frameRate:s.frameRate,displaySurface:s.preferDisplaySurface||"monitor"};if(a.video=c,s.systemAudio){let{echoCancellation:o=!0,noiseSuppression:l=!1,autoGainControl:d=!1}=s;a.audio={echoCancellation:o,noiseSuppression:l,autoGainControl:d,sampleRate:48e3}}return a}(e);b.info("getDisplayMedia with constraints: ".concat(JSON.stringify(i)));let r=yield navigator.mediaDevices.getDisplayMedia(i);e.systemAudio&&r.getAudioTracks().length===0&&(qo&&er<74||Rt||ue)&&b.warn("Your browser not support capture system audio");let n=r.getVideoTracks()[0];if(n){if(e.frameRate)try{yield n.applyConstraints({frameRate:{min:e.frameRate,ideal:e.frameRate},width:e.width,height:e.height})}catch(s){b.warn("screen applyConstraints failed: ".concat(s))}e.captureElement&&(yield function(s,a){return g(this,null,function*(){var c;if("CropTarget"in window&&"fromElement"in CropTarget&&ne(s.cropTo))try{if(((c=s.getCaptureHandle())==null?void 0:c.handle)!==yv)return;let o=yield CropTarget.fromElement(a);yield s.cropTo(o)}catch(o){b.warn("cropTo target failed ".concat(o))}})}(n,e.captureElement))}if(e.audio){let s=function(a){let c={echoCancellation:a.echoCancellation,autoGainControl:a.autoGainControl,noiseSuppression:a.noiseSuppression,sampleRate:a.sampleRate,channelCount:a.channelCount};return I(a.microphoneId)||(c.deviceId=a.microphoneId),{audio:c,video:!1}}(e);b.info("getUserMedia with constraints: ".concat(JSON.stringify(s))),t=yield navigator.mediaDevices.getUserMedia(s),r.addTrack(t.getAudioTracks()[0])}return r})},dr=class extends Je{constructor(e){super(e,2),h(this,"profile",{width:1920,height:1080,frameRate:5,bitrate:1600}),h(this,"objectFit","contain"),h(this,"isScreen",!0),this._log.id="s-".concat(this._log.id)}capture(e){return g(this,arguments,function(t){var i=this;let{systemAudio:r=!1,autoGainControl:n,echoCancellation:s,noiseSuppression:a,audioTrack:c,videoTrack:o,captureElement:l,preferDisplaySurface:d}=t;return function*(){try{let u;return o||c?(u=new MediaStream,o&&u.addTrack(o),c&&u.addTrack(c)):u=yield UV({audio:!1,systemAudio:r,width:i.profile.width,height:i.profile.height,frameRate:i.profile.frameRate,autoGainControl:n,echoCancellation:s,noiseSuppression:a,captureElement:l,preferDisplaySurface:d}),yield i.setInputMediaStreamTrack(u.getVideoTracks()[0]),u}catch(u){throw i.log.error("getDisplayMedia error observed ".concat(u)),u instanceof N?u:new N({code:C.INITIALIZE_FAILED,name:u.name,message:u.message})}}()})}switchDevice(e){return g(this,null,function*(){throw new Error("Method not implemented.")})}},qs=class extends Kt{constructor(e){super(e),this._log.id="s-".concat(this._log.id)}},FV=class extends IV{constructor(e){super(),this.room=e,h(this,"_localAudioTrack"),h(this,"_localScreenAudioTrack"),h(this,"log",b.createLogger({id:"am"})),h(this,"denoiser"),e&&(this.log.setUserId(e.userId),this.log.setSdkAppId(e.sdkAppId))}get _localAudioPipline(){var e;return(e=this._localAudioTrack)==null?void 0:e.pipeline}dump(e){var t,i;if(!this._localAudioTrack)return;let r=[],n=[];(t=this._localAudioPipline)!=null&&t.source.node&&(r.push(this._localAudioPipline.source.node),n.push("mic")),(i=this._localAudioPipline)!=null&&i.denoiser.node&&(r.push(this._localAudioPipline.denoiser.node),n.push("mic-processed")),this.mixWeight>1&&(r.push(this.audioContext.createMediaStreamSource(this._localAudioPipline.stream)),n.push("mix")),this.log.info("dump audio track ".concat(n,", duration: ").concat(e));let s=new AbortController,a=[],c=setTimeout(()=>{this.log.info('dump audio track complete please input "download()" to download.'),s.abort("timeout")},1e3*e),o=()=>{for(let d=0;d<n.length;d++){let u=URL.createObjectURL(new Blob(a[d])),p=document.createElement("a");p.href=u,p.download="".concat(n[d],".pcm"),p.style.display="none",document.body.appendChild(p),p.click(),URL.revokeObjectURL(u),p.remove()}clearTimeout(c),s.abort("download")},l=function(d){return g(this,null,function*(){let u=Ii();sp||(sp=Xh(u,URL.createObjectURL(new Blob(["registerProcessor('dumper', class extends AudioWorkletProcessor {process(inputs) {this.port.postMessage(inputs);return true;}});"],{type:"application/javascript"})))),yield sp;let p=new AudioWorkletNode(u,"dumper",{numberOfInputs:d.length,numberOfOutputs:0});return d.forEach((m,f)=>m.connect(p,0,f)),new ReadableStream({start(m){p.port.onmessage=f=>{m.enqueue(f.data)}},cancel(){d.forEach(m=>m.disconnect(p)),p.port.close()}})})}(r).then(d=>d.pipeTo(new WritableStream({write(u){u.forEach((p,m)=>a[m]=a[m]?a[m].concat(p[0]):[p[0]])}}),s).catch(u=>o));return{then:l.then.bind(l),download:o}}get hasScreenAudioTrack(){return this._localScreenAudioTrack!==null}get hasAudioTrack(){return this._localAudioTrack!==null}changeInput(e){if(e instanceof qs)this._localScreenAudioTrack=e,e.pipeline.connect(),this.mixOnChange();else if(e instanceof Kt)this._localAudioTrack=e,this.denoiser&&e.addDenoiser(this.denoiser),e.pipeline.connect(),this.mixOnChange();else if(e instanceof ap)return e.setOutputMediaStreamTrack(e.mediaTrack)}mixOnChange(){var e,t;(e=this._localAudioTrack)==null||e.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localAudioTrack.mediaTrack),(t=this._localScreenAudioTrack)==null||t.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localScreenAudioTrack.mediaTrack)}removeInput(e){e instanceof qs?delete this._localScreenAudioTrack:e instanceof Kt&&delete this._localAudioTrack}addDenoiser(e){var t;this.denoiser=e,(t=this._localAudioTrack)==null||t.addDenoiser(e)}removeDenoiser(e){var t;delete this.denoiser,(t=this._localAudioTrack)==null||t.removeDenoiser(e)}destroy(){this.close()}};function Sv(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:30,t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:2;return ae((i,r)=>function(){for(var n=arguments.length,s=new Array(n),a=0;a<n;a++)s[a]=arguments[a];return new Promise((c,o)=>{let l=setTimeout(()=>{let d=new N({code:C.API_CALL_TIMEOUT,message:"checkPendingPromise ".concat(r,"() timeout ").concat(e,"s")});b.warn(d),t===2?o(d):t===1&&c()},1e3*e);i.apply(this,s).then(c,o).finally(()=>{clearTimeout(l)})})})}var vv=class extends rp{constructor(e,t,i){super({userId:t.userId,sdkAppId:e.sdkAppId,mediaType:i,room:e}),this.room=e,this.user=t,h(this,"tinyId"),h(this,"isRemote",!0),h(this,"jitterBufferDelay",0),this.tinyId=t.tinyId}setMute(e){this.hasFlag&&super.setMute(e)}setInputMediaStreamTrack(e){super.setInputMediaStreamTrack(e),this.hasFlag&&this.isSubscribed&&this.player.setTrack(this.outMediaTrack)}waitHasMediaTrack(){return new Promise(e=>{this.mediaTrack?e():this.once("input-media-track-changed",e)})}get isSubscribing(){return this.state.toString()==="subscribeing"}get isSubscribed(){return this.state===vv.STATE_SUBSCRIBE}subscribe(e){return e}unsubscribe(){this.player.setTrack(null),this.streamType==="main"&&this.kind==="video"&&this.room.changeType(!1,this.user)}updatePlayingState(e){if(this.isPlayCalled&&this.player.isStopped===e){if(e&&(!this.isSubscribed||!this.hasFlag||!this.outMediaTrack))return void this.log.info("abort play, isSubscribed:".concat(this.isSubscribed," hasFlag:").concat(this.hasFlag," hasTrack:").concat(!!this.outMediaTrack));super.updatePlayingState(e)}}onFlagChanged(){this.updatePlayingState(this.hasFlag)}onTrackMuted(){this.hasFlag&&(this.isSubscribed||this.isSubscribing)&&this.isPlayCalled&&super.onTrackMuted()}onTrackUnmuted(){this.hasFlag&&(this.isSubscribed||this.isSubscribing)&&this.isPlayCalled&&super.onTrackUnmuted()}onTrackEnded(){this.hasFlag&&(this.isSubscribed||this.isSubscribing)&&this.isPlayCalled&&super.onTrackEnded()}},bi=vv;h(bi,"STATE_SUBSCRIBE","subscribe"),k([Sv(5,1)],bi.prototype,"waitHasMediaTrack"),k([be(X.INIT,bi.STATE_SUBSCRIBE,{success(){this.log.info("subscribed"),R.emit(A.REMOTE_TRACK_SUBSCRIBED,{track:this}),this.updatePlayingState(!0)},ignoreError:!0})],bi.prototype,"subscribe"),k([be(bi.STATE_SUBSCRIBE,X.INIT,{sync:!0,success(){this.log.info("unsubscribed"),this.updatePlayingState(!1),R.emit(A.REMOTE_TRACK_UNSUBSCRIBED,{track:this})}})],bi.prototype,"unsubscribe");var ap=class extends bi{constructor(e,t){super(e,t,1),h(this,"volume",0),h(this,"mediaType",1),h(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,end2EndDelay:0,jitterBufferDelay:0}),h(this,"audioDecoder"),this.manager=e.audioManager}onPlayerError(e){if(this.enableDecodeFrame){this.room.enableInsertableStreams();let t=new AudioDecoder({error:i=>this._log.error(i),output:i=>{this.player.write(i)}});t.configure({codec:"opus",sampleRate:48e3,numberOfChannels:1}),this._log.info("audioDecoder state:".concat(t.state)),this.audioDecoder=t}}get enableDecodeFrame(){var e,t;return((t=(e=this.player.element)==null?void 0:e.error)==null?void 0:t.code)===MediaError.MEDIA_ERR_DECODE&&or&&Uh().AudioDecoder}decodeFrame(e){var t;return((t=this.audioDecoder)==null?void 0:t.state)==="configured"&&this.audioDecoder.decode(new EncodedAudioChunk({data:e.data,timestamp:e.timestamp,type:"key"})),e}getAudioLevel(){let e=this.volume||super.getAudioLevel();return e>1?1:e}get hasFlag(){return this.user.muteState.hasAudio}isFlagChanged(e){let t=e.hasAudio&&!e.audioMuted;return this.hasFlag||(this.volume=0),this.hasFlag!==t}},BV=[-1,-1,1,-1,-1,1,1,1],HV=[0,0,1,0,0,1,1,1],hr=class extends X{constructor(e,t){if(super(),this.context=e,h(this,"name"),h(this,"input"),h(this,"output"),h(this,"texture"),h(this,"ctx2d",null),h(this,"fbo"),h(this,"width",0),h(this,"height",0),h(this,"x",0),h(this,"y",0),h(this,"program"),h(this,"vertexShader"),h(this,"fragmentShader"),h(this,"totalFrames",0),h(this,"dropFrames",0),h(this,"matchInputSize",!0),h(this,"texCoordBuffer"),h(this,"positionBuffer"),h(this,"lastInfo",{name:"",timestamp:0,totalFrames:0,x:0,y:0,width:0,height:0,fps:0}),h(this,"cost",0),h(this,"_canvas",null),h(this,"_image"),this.context.on("disconnect",this.close,this),this.name=t.name,this.matchInputSize=t.matchInputSize!==!1,this.width=t.width||e.width,this.height=t.height||e.height,this._image=t.image,e instanceof ki){if(e.ctx&&t.create2d){let i=document.createElement("canvas"),r=typeof i.transferControlToOffscreen=="function"?i.transferControlToOffscreen():i;r.width=this.width,r.height=this.height,this.ctx2d=r.getContext("2d"),this._image=r,this._canvas=r}}else try{let i=e.ctx;this.texCoordBuffer=this.createBuffer(HV),this.positionBuffer=this.createBuffer(BV),t.createTexture!==!1&&(this.texture=i.createTexture(),this.useTexture(),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MIN_FILTER,i.LINEAR),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MAG_FILTER,i.LINEAR),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_S,i.CLAMP_TO_EDGE),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_T,i.CLAMP_TO_EDGE),i.pixelStorei(i.PACK_ALIGNMENT,1),i.pixelStorei(i.UNPACK_ALIGNMENT,1)),t.useFbo&&(this.fbo=i.createFramebuffer(),this.useBufferFrame(),this.useTexture(),i.texImage2D(i.TEXTURE_2D,0,i.RGBA,this.width,this.height,0,i.RGBA,i.UNSIGNED_BYTE,null),i.framebufferTexture2D(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0,i.TEXTURE_2D,this.texture,0)),t.useDefaultProgram?this.program=e.defaultProgam:(t.vertexShaderSource||t.fragmentShaderSource)&&(this.vertexShader=t.vertexShaderSource?e.createShader(i.VERTEX_SHADER,t.vertexShaderSource):e.defaultVShader,this.fragmentShader=t.fragmentShaderSource?e.createShader(i.FRAGMENT_SHADER,t.fragmentShaderSource):e.defaultFShader,this.program=e.createProgram(this.vertexShader,this.fragmentShader))}catch(i){this.context.destroy(i)}}get image(){return this._image}set image(e){this._image=e}createFramebuffer(e){let t=this.context.ctx,i=t.createFramebuffer();return t.bindFramebuffer(t.FRAMEBUFFER,i),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,e,0),i}connect(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];return e.addInput(this,...i),this.output=e,e}addInput(e){this.input=e,this.matchInputSize&&e.width&&e.height&&this.resize(e.width,e.height)}requestFrame(e){let t=Date.now();return!!(this.context instanceof bt&&this.render(e)||this.context instanceof ki&&this.render2d(e))&&(this.totalFrames++,this.cost=Date.now()-t,!0)}render2d(e){var t;return!((t=this.input)==null||!t.requestFrame(e))&&this.draw2d(this.input.image,0,0,this.width,this.height)}disconnect(){for(var e,t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];(e=this.output)==null||e.removeInput(this,...i),delete this.output}removeInput(e){delete this.input}close(){var e,t;if(this.context.off("disconnect",this.close,this),(e=this.output)==null||e.removeInput(this),delete this.output,(t=this.input)==null||t.disconnect(),this.context instanceof bt){let i=this.context.ctx;i.deleteBuffer(this.texCoordBuffer),i.deleteBuffer(this.positionBuffer),this.fbo&&i.deleteFramebuffer(this.fbo),this.texture&&i.deleteTexture(this.texture),this.vertexShader&&this.vertexShader!==this.context.defaultVShader&&i.deleteShader(this.vertexShader),this.fragmentShader&&this.fragmentShader!==this.context.defaultFShader&&i.deleteShader(this.fragmentShader),this.program&&this.program!==this.context.defaultProgam&&i.deleteProgram(this.program)}this._canvas&&(this._canvas.width=0,this._canvas.height=0,this.ctx2d=null),this.removeAllListeners()}useTexture(){this.useTextures(this.texture)}useInputTexture(){var e;this.useTextures((e=this.input)==null?void 0:e.texture)}useTextures(){let e=this.context.ctx;for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];i.forEach((n,s)=>{n&&(e.activeTexture(e.TEXTURE0+s),e.bindTexture(e.TEXTURE_2D,n))})}useProgram(){this.context.ctx.useProgram(this.program)}useBufferFrame(){let e=this.context.ctx;e.bindFramebuffer(e.FRAMEBUFFER,this.fbo||null)}createBuffer(e){let t=this.context.ctx,i=t.createBuffer();return t.bindBuffer(t.ARRAY_BUFFER,i),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW),i}setTexBuffer(e){let t=this.context.ctx;t.bindBuffer(t.ARRAY_BUFFER,this.texCoordBuffer),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW)}setPosBuffer(e){let t=this.context.ctx;t.bindBuffer(t.ARRAY_BUFFER,this.positionBuffer),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW)}changeBufferData(e,t){let i=this.context.ctx;i.bindBuffer(i.ARRAY_BUFFER,e),i.bufferData(i.ARRAY_BUFFER,new Float32Array(t),i.STATIC_DRAW)}setAttributes(){let e=this.context.ctx;for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];i.forEach((n,s)=>{e.enableVertexAttribArray(s),e.bindBuffer(e.ARRAY_BUFFER,n),e.vertexAttribPointer(s,2,e.FLOAT,!1,0,0)})}getVertexPoint(e,t){return[e/this.width*2-1,t/this.height*2-1]}layout2texCoords(e){return[...this.getVertexPoint(e.x,e.y),...this.getVertexPoint(e.x+e.width,e.y),...this.getVertexPoint(e.x,e.y+e.height),...this.getVertexPoint(e.x+e.width,e.y+e.height)]}resize(e,t){if(this.width!==e||this.height!==t){if(this.width=e,this.height=t,this._canvas&&(this._canvas.width=e,this._canvas.height=t),this.texture&&this.fbo){this.useTexture();let i=this.context.ctx;i.texImage2D(i.TEXTURE_2D,0,i.RGBA,e,t,0,i.RGBA,i.UNSIGNED_BYTE,null)}this.output&&this.output.matchInputSize&&this.output.resize(e,t)}}draw(e,t){this.setAttributes(e||this.positionBuffer,t||this.texCoordBuffer);let i=this.context.ctx;i.drawArrays(i.TRIANGLE_STRIP,0,4)}draw2d(e,t,i,r,n){return!(!this.ctx2d||!e)&&(e instanceof ImageData?this.ctx2d.putImageData(e,t,i):this.ctx2d.drawImage(e,t,i,r,n),!0)}getInfo(){var e;let{totalFrames:t,x:i,y:r,width:n,height:s,name:a,cost:c}=this,o=Date.now(),l=(t-this.lastInfo.totalFrames)/((o-this.lastInfo.timestamp)/1e3)|0;return this.lastInfo={totalFrames:t,x:i,y:r,width:n,height:s,timestamp:o,fps:l,name:a,cost:c},O({parent:(e=this.input)==null?void 0:e.getInfo()},this.lastInfo)}createTexture(e){let t=this.context.ctx,i=t.createTexture();return this.useTextures(i),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.pixelStorei(t.PACK_ALIGNMENT,1),t.pixelStorei(t.UNPACK_ALIGNMENT,1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,e),i}};k([be(X.INIT,"connected",{sync:!0})],hr.prototype,"connect"),k([be("connected",X.INIT,{ignoreError:!0,sync:!0})],hr.prototype,"disconnect"),k([be([],"closed",{sync:!0})],hr.prototype,"close");var jV=[0,1,1,1,0,0,1,0],Iv=class extends hr{constructor(e,t){super(e,Object.assign({useDefaultProgram:!0,createTexture:!1,name:"destination"},t)),h(this,"_intervalId",0),h(this,"_sequence",0),h(this,"checkGLError",!1),e instanceof ki?this.ctx2d=e.ctx:e.available&&(t!=null&&t.mirrorUpAndDown)&&this.setTexBuffer(jV)}start(e){this._intervalId=_e.run("intervalInWorker",()=>{if(e!==this.context.frameRate&&(_e.clearTask(this._intervalId),this.start(this.context.frameRate)),this.requestFrame(this._sequence++),this.checkGLError&&this.context instanceof bt){let t=this.context.ctx.getError();t&&this.context.destroy(new Error("".concat(this.name," req ").concat(this._sequence," render ").concat(this.totalFrames," faild ").concat(t)))}},{fps:this.context.frameRate})}render(e){var t;return!((t=this.input)==null||!t.requestFrame(e))&&(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0)}addInput(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];super.addInput(e,...i),this.start(this.context.frameRate)}removeInput(e){super.removeInput(e),_e.clearTask(this._intervalId)}resize(e,t){super.resize(e,t),this.context.setSize(e,t)}},op=class extends Iv{constructor(e,t){super(e,t),h(this,"_videoTrack"),[this._videoTrack]=e._canvas.captureStream(e.frameRate).getVideoTracks();let i=r=>{var n;let s=()=>{var c;return(c=this._videoTrack)==null?void 0:c.removeEventListener(r,a)},a=()=>{s(),this.context.destroy(new Error("video track ".concat(r)))};this.once("closed",s),(n=this._videoTrack)==null||n.addEventListener(r,a)};e instanceof bt&&i("mute"),i("ended")}get videoTrack(){return this._videoTrack}close(){var e;super.close(),(e=this._videoTrack)==null||e.stop(),delete this._videoTrack}},GV=class extends op{render(e){var t;return!((t=this.input)==null||!t.requestFrame(e))}},WV=class extends op{constructor(e,t){super(e,{name:"smallDestination"}),this.resolution=t}resize(e,t){let i,r=e*t,n=this.resolution.width*this.resolution.height;b.info("big res: ".concat(e,"*").concat(t," small res: ").concat(this.resolution.width,"*").concat(this.resolution.height," ")),r>n?i=r/n:(b.warn("Small stream resolution is not smaller than big stream, which is invalid. big: ".concat(e," * ").concat(t," small: ").concat(this.resolution.width," * ").concat(this.resolution.height)),i=r/19200),super.resize(e/Math.sqrt(i),t/Math.sqrt(i))}},Av=class extends hr{constructor(e,t){super(e,O({name:"imageSource"},t)),h(this,"_lastImage"),h(this,"_totalFrames",0),h(this,"_autoResize",!1),this._autoResize=(t==null?void 0:t.autoResize)!==!1}_render(e,t){var i,r;let{width:n,height:s}=this;if(this.image instanceof HTMLVideoElement){if(ne(this.image.getVideoPlaybackQuality)&&!an){let a=this.image.getVideoPlaybackQuality().totalVideoFrames;if(((r=(i=this.image.srcObject)==null?void 0:i.getVideoTracks()[0])==null?void 0:r.muted)===!0||this._totalFrames===a)return!1;this._totalFrames=a,this.dropFrames=this._totalFrames-this.totalFrames}if({videoWidth:n,videoHeight:s}=this.image,!n||!s)return!1;this.image.width=n,this.image.height=s}else if(this.image instanceof HTMLImageElement||this.image instanceof ImageData||this.image instanceof ImageBitmap){if({width:n,height:s}=this.image,this.image!==this._lastImage)this._lastImage=this.image;else if(n===this.width&&s===this.height)return!1}else(this.image instanceof HTMLCanvasElement||this.image instanceof OffscreenCanvas)&&({width:n,height:s}=this.image,this._lastImage=this.image);if(!this._autoResize)return!0;if(this.width===n&&this.height===s&&this.totalFrames){if(t){this.useTexture();let a=this.context.ctx;a.texSubImage2D(a.TEXTURE_2D,0,0,0,a.RGBA,a.UNSIGNED_BYTE,this.image)}}else{if(t){this.useTexture();let a=this.context.ctx;a.texImage2D(a.TEXTURE_2D,0,a.RGBA,a.RGBA,a.UNSIGNED_BYTE,this.image)}this.resize(n,s)}return!0}render(e){return this._render(e,!0)}render2d(e){return this._render(e,!1)}},Rv=class extends Av{constructor(e,t,i){super(e,i),this._player=t,this.name="videoPlayerSource"}get image(){return this._player.element}},Cv=class extends Rv{constructor(e,t,i){super(e,new vi({id:i.name,track:t,muted:!0,container:null,objectFit:"contain",log:i.logger}),i),this.name="videoTrackSource",this._player.play()}get image(){return this._player.element}replaceTrack(e){this._player.setTrack(e),this._player.play()}close(){super.close(),this._player.stop()}},bv=class extends X{constructor(e){super(),h(this,"frameRate"),h(this,"_canvas"),h(this,"log"),h(this,"hasAlpha",!1),h(this,"name"),this.name=e.name,this.log=e.logger.createChild({id:"vc-".concat(this.name)}),this.frameRate=e.frameRate}set width(e){this._canvas&&(this._canvas.width=e)}get width(){var e;return((e=this._canvas)==null?void 0:e.width)||0}set height(e){this._canvas&&(this._canvas.height=e)}get height(){var e;return((e=this._canvas)==null?void 0:e.height)||0}setSize(e,t){this._canvas&&(this._canvas.width=e,this._canvas.height=t)}createVideoTrackSource(e,t){return new Cv(this,e,{logger:this.log,name:t})}createVideoTrackDestination(e){return new op(this,e)}createVideoImageSource(e,t){return new Av(this,t?Object.assign(t,{logger:this.log,image:e}):{logger:this.log,image:e})}createVideoPlayerSource(e,t){return new Rv(this,e,t?Object.assign(t,{logger:this.log}):{logger:this.log})}get available(){return this.state==="created"}disconnect(){this.emit("disconnect")}},JV={alpha:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0,powerPreference:"low-power"},bt=class extends bv{constructor(){super(...arguments),h(this,"defaultProgam"),h(this,"defaultVShader"),h(this,"defaultFShader"),h(this,"ctx")}create(){if(this._canvas||(this._canvas=document.createElement("canvas")),this.ctx=this._canvas.getContext("webgl2",JV),!this.ctx)throw new Error("webgl2 not supported");this.defaultVShader=this.createShader(this.ctx.VERTEX_SHADER,`
81
+ // 顶点着色器
82
+ attribute vec4 a_position;
83
+ attribute vec2 a_texCoord;
84
+ varying vec2 v_texCoord;
85
+
86
+ void main() {
87
+ gl_Position = a_position;
88
+ v_texCoord = a_texCoord;
89
+ }
90
+ `),this.defaultFShader=this.createShader(this.ctx.FRAGMENT_SHADER,`
91
+ // 片元着色器
92
+ precision mediump float;
93
+ varying vec2 v_texCoord;
94
+ uniform sampler2D u_texture;
95
+
96
+ void main() {
97
+ gl_FragColor = texture2D(u_texture, v_texCoord);
98
+ } `),this.defaultProgam=this.createProgram(this.defaultVShader,this.defaultFShader),this._canvas.addEventListener("webglcontextlost",()=>{this.destroy(new Error("webgl context lost"))}),this.log.info("video context created use webgl")}destroy(e){return this.disconnect(),this.log.info("video context destroy ".concat(e?": ".concat(e):"")),this.ctx&&(this.ctx.deleteShader(this.defaultVShader),this.ctx.deleteShader(this.defaultFShader),this.ctx.deleteProgram(this.defaultProgam),delete this.ctx),e}set width(e){var t;(t=this.ctx)==null||t.viewport(0,0,e,this.height),super.width=e}set height(e){var t;(t=this.ctx)==null||t.viewport(0,0,this.width,e),super.height=e}setSize(e,t){var i;(i=this.ctx)==null||i.viewport(0,0,e,t),super.setSize(e,t)}createShader(e,t){let i=this.ctx,r=i.createShader(e);return i.shaderSource(r,t),i.compileShader(r),r}createProgram(e,t){let i=this.ctx,r=i.createProgram();return i.attachShader(r,e),i.attachShader(r,t),i.linkProgram(r),i.getProgramParameter(r,i.LINK_STATUS)||this.log.error(i.getProgramInfoLog(r)),r}};k([be(X.INIT,"created",{sync:!0})],bt.prototype,"create"),k([be("created",X.INIT,{ignoreError:!0,sync:!0,success(e){e&&this.emit("unavailable",e),this.removeAllListeners()}})],bt.prototype,"destroy");var ki=class extends bv{constructor(){super(...arguments),h(this,"ctx")}create(e){if(this.hasAlpha=e.alpha,this._canvas=document.createElement("canvas"),this.ctx=this._canvas.getContext("2d",{alpha:e.alpha}),!this.ctx)throw new Error("2d context not supported");this.log.info("video context created use 2d")}destroy(e){this.disconnect(),this.log.info("video context destroy ".concat(e?": ".concat(e):"")),delete this.ctx,this._canvas&&(this._canvas.remove(),this._canvas.width=0,this._canvas.height=0,delete this._canvas),this.removeAllListeners()}};k([be(X.INIT,"created",{sync:!0})],ki.prototype,"create"),k([be("created",X.INIT,{ignoreError:!0,sync:!0})],ki.prototype,"destroy");var Ys=class extends bi{constructor(e,t){super(e,t,arguments.length>2&&arguments[2]!==void 0?arguments[2]:4),h(this,"mediaType",4),h(this,"source"),h(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,end2EndDelay:0,jitterBufferDelay:0}),this.manager=e.videoManager}play(e,t){return(Th===17||t!=null&&t.canvasRender)&&!this.source&&this.useCanvasPlayer(),super.play(e,t)}useCanvasPlayer(){if(this.log.info("useCanvasPlayer(), ".concat(!!this.player.element)),!this.player.element)return;let e=new ki({frameRate:15,logger:this.log,name:this.userId});e.create({alpha:!1});let t=e.createVideoPlayerSource(this.player);this.source=t;let i=new Iv(e);t.connect(i),this.player.setCanvas(e._canvas),this.updateCanvasPlayerFPS=this.updateCanvasPlayerFPS.bind(this,e),this.room.on("heartbeat-report",this.updateCanvasPlayerFPS,this)}updateCanvasPlayerFPS(e){let t=this.decodeFPS,i=(r=t,[15,30,45,60].reduce((n,s)=>Math.abs(s-r)<Math.abs(n-r)?s:n));var r;!ge(t)||t<=0?this.log.debug("updateCanvasPlayerFPS() ignore decoder: ".concat(t," ")):i!==e.frameRate?(this.log.info("updateCanvasPlayerFPS() decoder: ".concat(t,", closest: ").concat(i,", current: ").concat(e.frameRate)),e.frameRate=i):this.log.debug("updateCanvasPlayerFPS() ignore ClosestFPS ".concat(i," == ").concat(e.frameRate))}get decodeFPS(){var e;let{msg_video_status:t}=((e=this.room.heartbeatReport)==null?void 0:e.msg_down_stream_info.find(n=>n.msg_user_info.str_identifier===this.userId))||{},i=this.mediaType===2?7:this.isSmall?3:2;if(!t||t.length===0)return 0;let r=t.find(n=>n.uint32_video_stream_type===i);return(r==null?void 0:r.uint32_video_dec_fps)||0}stop(){return this.room.off("heartbeat-report",this.updateCanvasPlayerFPS,this),super.stop()}get enableDecodeFrame(){return!!this.room.enableSEI&&or}decodeFrame(e){try{if(e.type==="empty"||e.data.byteLength===0)return e;let t=new DataView(e.data);if(t.getInt32(0)!==1||t.getInt8(4)!==6)return e;let i=[],r=0,n=-1,s=-1;for(let a=0;a<e.data.byteLength;a++){let c=t.getUint8(a);if(c===0)r++;else if(c===1){if(r===2||r===3){let o=a-r;if(n===-1?n=o:s===-1&&(s=o,i.push(new Ev(new DataView(t.buffer.slice(n,s)))),n=o,s=-1),t.getUint8(a+1)!==6){e.data=t.buffer.slice(o);break}}r=0}else r=0}this._log.debug("".concat(i.length," sei received")),i.reverse().forEach(a=>{this.room.emit("sei-message",{seiPayloadType:a.seiPayloadType,data:a.seiPayload.buffer,userId:this.user.userId,streamType:this.mediaType===2?"auxiliary":"main"})})}catch(t){this._log.warn(t)}return e}get isBig(){return this.mediaType===4}get isSmall(){return this.mediaType===8}changeType(e){this.room.changeType(e,this.user)}get hasFlag(){return this.user.muteState.hasVideo&&!this.user.muteState.videoMuted}isFlagChanged(e){let t=e.hasVideo&&!e.videoMuted;return this.hasFlag!==t}setMirror(e){e==="publish"||e==="both"||super.setMirror(e)}},kv=class extends Ys{constructor(e,t){super(e,t,2),h(this,"mediaType",2),h(this,"objectFit","contain")}get hasFlag(){return this.user.muteState.hasAuxiliary}isFlagChanged(e){let t=e.hasAuxiliary;return this.hasFlag!==t}};function Qs(){}var zV=e=>e(),KV=()=>typeof __FASTRX_DEVTOOLS__<"u",qV=1,Xs=class extends Function{toString(){return"".concat(this.name,"(").concat(this.args.length?[...this.args].join(", "):"",")")}subscribe(e){let t=new YV(e,this,this.streamId++);return qt.subscribe({id:this.id,end:!1},{nodeId:t.sourceId,streamId:t.id}),this(t),t}},Nv=class{constructor(){this.defers=new Set,this.disposed=!1}next(e){}complete(){this.dispose()}error(e){this.dispose()}get bindDispose(){return()=>this.dispose()}dispose(){this.disposed=!0,this.complete=Qs,this.error=Qs,this.next=Qs,this.dispose=Qs,this.subscribe=Qs,this.doDefer()}subscribe(e){return e instanceof Xs?e.subscribe(this):e(this),this}get bindSubscribe(){return e=>this.subscribe(e)}doDefer(){this.defers.forEach(zV),this.defers.clear()}defer(e){this.defers.add(e)}removeDefer(e){this.defers.delete(e)}reset(){this.disposed=!1,delete this.complete,delete this.next,delete this.dispose,delete this.next,delete this.subscribe}resetNext(){delete this.next}resetComplete(){delete this.complete}resetError(){delete this.error}},Dv=class extends Nv{constructor(e){super(),this.sink=e,e.defer(this.bindDispose)}next(e){this.sink.next(e)}complete(){this.sink.complete()}error(e){this.sink.error(e)}};function uc(e,t,i){if(KV()){let r=Object.defineProperties(Object.setPrototypeOf(e,Xs.prototype),{streamId:{value:0,writable:!0,configurable:!0},name:{value:t,writable:!0,configurable:!0},args:{value:i,writable:!0,configurable:!0},id:{value:0,writable:!0,configurable:!0}});qt.create(r);for(let n=0;n<i.length;n++){let s=i[n];typeof s=="function"&&s instanceof Xs&&qt.addSource(r,s)}return r}return e}function Ni(e,t){window.postMessage({source:"fastrx-devtools-backend",payload:{event:e,payload:t}})}var YV=class extends Dv{constructor(e,t,i){super(e),this.source=t,this.id=i,this.sourceId=e.sourceId,this.defer(()=>{qt.defer(this.source,this.id)})}next(e){qt.next(this.source,this.id,e),this.sink.next(e)}complete(){qt.complete(this.source,this.id),this.sink.complete()}error(e){qt.complete(this.source,this.id,e),this.sink.error(e)}},qt={addSource(e,t){Ni("addSource",{id:e.id,name:e.toString(),source:{id:t.id,name:t.toString()}})},next(e,t,i){Ni("next",{id:e.id,streamId:t,data:i&&i.toString()})},subscribe(e,t){let{id:i,end:r}=e;Ni("subscribe",{id:i,end:r,sink:{nodeId:t&&t.nodeId,streamId:t&&t.streamId}})},complete(e,t,i){Ni("complete",{id:e.id,streamId:t,err:i?i.toString():null})},defer(e,t){Ni("defer",{id:e.id,streamId:t})},pipe(e){Ni("pipe",{name:e.toString(),id:e.id,source:{id:e.source.id,name:e.source.toString()}})},update(e){Ni("update",{id:e.id,name:e.toString()})},create(e){e.id||(e.id=qV++),Ni("create",{name:e.toString(),id:e.id})}},QV=class extends Nv{constructor(e){super(),this.source=e,this.sinks=new Set}add(e){e.defer(()=>this.remove(e)),this.sinks.add(e).size===1&&(this.reset(),this.subscribe(this.source))}remove(e){this.sinks.delete(e),this.sinks.size===0&&this.dispose()}next(e){this.sinks.forEach(t=>t.next(e))}complete(){this.sinks.forEach(e=>e.complete()),this.sinks.clear()}error(e){this.sinks.forEach(t=>t.error(e)),this.sinks.clear()}},XV=function(e,t){return function(){for(var i=arguments.length,r=new Array(i),n=0;n<i;n++)r[n]=arguments[n];return s=>{if(s instanceof Xs){let a=uc(c=>{let o=new e(c,...r);o.sourceId=a.id,o.subscribe(s)},t,arguments);return a.source=s,qt.pipe(a),a}return a=>s(new e(a,...r))}}}(class extends Dv{constructor(e,t,i){super(e),this.mapper=t,this.thisArg=i}next(e){super.next(this.mapper.call(this.thisArg,e))}},"map");(function(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];i.reduce((n,s)=>s(n),e)})(function(e){return uc(t=>{let i=0,r=setInterval(()=>t.next(i++),e);return t.defer(()=>{clearInterval(r)}),"interval"},"interval",arguments)}(250),XV(()=>performance.now()),function(){return e=>{let t=new QV(e);if(e instanceof Xs){let i=uc(r=>{t.add(r)},"share",arguments);return t.sourceId=i.id,i.source=e,qt.pipe(i),i}return uc(t.add.bind(t),"share",arguments)}}());var gn=new Map;function me(e,t){let i=J(O({},t),{timestamp:xd()});gn.has(e)?gn.get(e).push(i):gn.set(e,[i])}R.on(A.JOIN_SUCCESS,e=>{let{room:t}=e;me(t.userId,{eventId:32788})}),R.on(A.LEAVE_START,e=>{let{room:t}=e;me(t.userId,{eventId:32789})}),R.on(A.LOCAL_TRACK_PUBLISHED,e=>{let{track:t}=e;if(t.room){let i=32769;t.mediaType===4?i=32768:t.mediaType===2&&(i=32805),me(t.room.userId,{eventId:i})}}),R.on(A.LOCAL_TRACK_UNPUBLISHED,e=>{let{track:t}=e;if(t.room){let i=32771;t.mediaType===4?i=32770:t.mediaType===2&&(i=32806),me(t.room.userId,{eventId:i})}}),R.on(A.TRACK_MUTED,e=>{let{track:t}=e;t.room&&(t.kind===_.AUDIO?me(t.room.userId,{eventId:t.isRemote?32785:32772,remoteUserId:t.isRemote?t.userId:void 0}):me(t.room.userId,{eventId:t.isRemote?32784:32773,remoteUserId:t.isRemote?t.userId:void 0}))}),R.on(A.TRACK_UNMUTED,e=>{let{track:t}=e;t.room&&(t.kind===_.AUDIO?me(t.room.userId,{eventId:t.isRemote?32787:32774,remoteUserId:t.isRemote?t.userId:void 0}):me(t.room.userId,{eventId:t.isRemote?32786:32775,remoteUserId:t.isRemote?t.userId:void 0}))}),R.on(A.REMOTE_TRACK_SUBSCRIBED,e=>{let{track:t}=e;!t.room||(t.mediaType===1&&me(t.room.userId,{eventId:32777,remoteUserId:t.userId}),t.mediaType===4&&me(t.room.userId,{eventId:32776,remoteUserId:t.userId}),t.mediaType===8&&me(t.room.userId,{eventId:32803,remoteUserId:t.userId}))}),R.on(A.REMOTE_TRACK_UNSUBSCRIBED,e=>{let{track:t}=e;!t.room||(t.mediaType===1&&me(t.room.userId,{eventId:32779,remoteUserId:t.userId}),t.mediaType===4&&me(t.room.userId,{eventId:32778,remoteUserId:t.userId}),t.mediaType===8&&me(t.room.userId,{eventId:32804,remoteUserId:t.userId}))}),R.on(A.SWITCH_DEVICE_SUCCESS,e=>{let{track:t}=e;t.room&&me(t.room.userId,{eventId:t.kind===_.VIDEO?32780:32781})}),R.on(A.LOCAL_TRACK_REPLACED,e=>{let{track:t}=e;t.room&&me(t.room.userId,{eventId:t.kind===_.VIDEO?32782:32783})}),R.on(A.SIGNAL_CONNECTION_STATE_CHANGED,e=>{let t,{room:i,prevState:r,state:n}=e;switch(n){case"CONNECTED":t=r==="RECONNECTING"?32795:32791;break;case"DISCONNECTED":t=r==="RECONNECTING"?32796:32790;break;case"RECONNECTING":t=32794}t&&me(i.userId,{eventId:t})}),R.on(A.PEER_CONNECTION_STATE_CHANGED,e=>{let t,{room:i,prevState:r,state:n,remoteUserId:s}=e,a=!!s;switch(n){case"CONNECTED":t=r==="RECONNECTING"?a?32801:32798:a?32793:32792;break;case"DISCONNECTED":r==="RECONNECTING"&&(t=a?32802:32799);break;case"RECONNECTING":t=a?32800:32797}t&&me(i.userId,{eventId:t,remoteUserId:s})}),R.on(A.VIDEO_CODEC_IMPLEMENTATION_CHANGED,e=>{let{userId:t,remoteUserId:i,codec:r,isHWCodec:n,prevImplementation:s}=e,a=n?1:0;s||(a=n?3:2);let c={eventId:4004,param1:a,param2:r==="h264"?0:2,streamType:2};i&&(c.remoteUserId=i,c.eventId=4005),me(t,c)}),R.on(A.LOCAL_TRACK_RECAPTURE,e=>{let{track:t,error:i}=e;if(t.userId){let r={eventId:2003,param1:0};t.kind===_.AUDIO?(r.streamType=1,i&&(r.param1=2)):(r.streamType=t.streamType==="auxiliary"?7:2,i&&(r.param1=8)),me(t.userId,r)}});var $V=Ie(Ve(),1),ZV=class extends $V.EventEmitter{constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"userId";super(),this.mySelfId=e,this._log=t,this.key=i,h(this,"userMap",new Map),h(this,"remotePublishedUserMap",new Map)}getPublishedUser(e){return this.remotePublishedUserMap.get(e)}addUser(e){let t=e[this.key],{userId:i,tinyId:r,role:n}=e;if(this.userMap.has(t))return;let s={userId:i,tinyId:r,role:n===20?"anchor":"audience"};this.userMap.set(t,s),this.emit("1",s)}deleteUser(e,t){let i=this.userMap.get(e);if(!i)return;let r="peer leave [".concat(e,"]");I(t)||(r+=":".concat(eS[t])),this._log.info(r);let n=this.remotePublishedUserMap.get(e);if(n){let s=n.muteState;n.flag=0,this.emit("5",n.userId),this.deleteRemotePublishedUser(e),this.emit("6",{prevMuteState:s,muteState:n.muteState,flag:0})}this.userMap.delete(e),this.emit("2",i.userId)}setUserList(e){this.userMap.forEach(t=>{e.findIndex(i=>i[this.key]===t[this.key])<0&&this.deleteUser(t[this.key],0)}),e.forEach(t=>{!this.userMap.has(t[this.key])&&t[this.key]!==this.mySelfId&&this.addUser(t)})}addRemotePublishedUser(e){this.remotePublishedUserMap.has(e[this.key])||this.remotePublishedUserMap.set(e[this.key],e)}deleteRemotePublishedUser(e){!this.remotePublishedUserMap.has(e)||this.remotePublishedUserMap.delete(e)}setRemotePublishedUserList(e){this.remotePublishedUserMap.forEach(t=>{let i=t[this.key];if(e.findIndex(r=>r[this.key]===t[this.key])<0){this._log.info("remote [".concat(i,"] unpublish"));let r=t.muteState;t.flag=0,this.emit("5",t.userId),this.deleteRemotePublishedUser(i),this.emit("6",{prevMuteState:r,muteState:t.muteState,flag:0})}}),e.forEach(t=>{var i;let r=t[this.key];if(r===this.mySelfId)return;let{flag:n,userId:s,tinyId:a}=t,c=Ms(n,s),o=(i=this.remotePublishedUserMap.get(r))==null?void 0:i.muteState;if(o){let l=this.remotePublishedUserMap.get(r);l&&l.flag!==n&&(l.flag=n,this._log.info("remote publish updated: ".concat(JSON.stringify(l.muteState))),this.emit("6",{prevMuteState:o,muteState:c,flag:n}))}else this._log.info("remote publish. state: ".concat(JSON.stringify(c))),this.addUser({userId:s,tinyId:a,role:20}),this.emit("3",t),this.emit("6",{prevMuteState:Ms(0,s),muteState:c,flag:n})})}clear(){this.userMap.clear(),this.remotePublishedUserMap.clear()}};function wv(e){let{timesInSecond:t,maxSizeInSecond:i,getSize:r}=e;return ae((n,s)=>{let a=new Map;return R.on(A.ROOM_DESTROY,c=>{let{room:o}=c;return a.delete(o)}),function(){let c=a.get(this);for(var o=arguments.length,l=new Array(o),d=0;d<o;d++)l[d]=arguments[d];if(c||(c={callCountInSecond:0,timestamp:0,totalSizeInSecond:0},a.set(this,c)),c.timestamp===0?c.timestamp=Date.now():Date.now()-c.timestamp>1e3&&(c.timestamp=Date.now(),c.callCountInSecond=0,c.totalSizeInSecond=0),r&&(c.totalSizeInSecond+=r(...l)),c.timestamp!==0&&Date.now()-c.timestamp<1e3&&(c.callCountInSecond>=t||c.totalSizeInSecond>i))throw new N({code:C.INVALID_OPERATION,message:j({key:B.CALL_FREQUENCY_LIMIT,data:{isTimes:c.callCountInSecond>=t,isSize:c.totalSizeInSecond>i,name:s,timesInSecond:t,maxSizeInSecond:i}})});c.callCountInSecond++,n.call(this,...l)}})}var v,Ov=!0,Yt={SCENE_LIVE:"live",SCENE_RTC:"rtc",ROLE_ANCHOR:"anchor",ROLE_AUDIENCE:"audience",STREAM_TYPE_MAIN:"main",STREAM_TYPE_SUB:"sub",AUDIO_PROFILE_STANDARD:"standard",AUDIO_PROFILE_STANDARD_STEREO:"standard-stereo",AUDIO_PROFILE_HIGH:"high",AUDIO_PROFILE_HIGH_STEREO:"high-stereo",QOS_PREFERENCE_SMOOTH:"smooth",QOS_PREFERENCE_CLEAR:"clear"},V={INVALID_PARAMETER:5e3,INVALID_OPERATION:5100,ENV_NOT_SUPPORTED:5200,DEVICE_ERROR:5300,SERVER_ERROR:5400,OPERATION_FAILED:5500,OPERATION_ABORT:5998,UNKNOWN_ERROR:5999},dc=((v=dc||{})[v.INVALID_PARAMETER=5e3]="INVALID_PARAMETER",v[v.INVALID_PARAMETER_REQUIRED=5001]="INVALID_PARAMETER_REQUIRED",v[v.INVALID_PARAMETER_TYPE=5002]="INVALID_PARAMETER_TYPE",v[v.INVALID_PARAMETER_EMPTY=5003]="INVALID_PARAMETER_EMPTY",v[v.INVALID_PARAMETER_INSTANCE=5004]="INVALID_PARAMETER_INSTANCE",v[v.INVALID_PARAMETER_RANGE=5005]="INVALID_PARAMETER_RANGE",v[v.INVALID_PARAMETER_LESS_THAN_ZERO=5006]="INVALID_PARAMETER_LESS_THAN_ZERO",v[v.INVALID_PARAMETER_MIN=5007]="INVALID_PARAMETER_MIN",v[v.INVALID_PARAMETER_MAX=5008]="INVALID_PARAMETER_MAX",v[v.INVALID_ELEMENT_ID=5009]="INVALID_ELEMENT_ID",v[v.INVALID_ELEMENT_ID_TYPE=5010]="INVALID_ELEMENT_ID_TYPE",v[v.INVALID_STREAM_ID=5011]="INVALID_STREAM_ID",v[v.INVALID_ROOM_ID_STRING=5012]="INVALID_ROOM_ID_STRING",v[v.INVALID_ROOM_ID_INTEGER=5013]="INVALID_ROOM_ID_INTEGER",v[v.INVALID_STREAM_TYPE=5014]="INVALID_STREAM_TYPE",v[v.INVALID_ROOM_ID_REQUIED=5015]="INVALID_ROOM_ID_REQUIED",v[v.INVALID_ROOM_ID_INTEGER_STRING=5016]="INVALID_ROOM_ID_INTEGER_STRING",v[v.INVALID_BUFFER_EMPTY=5017]="INVALID_BUFFER_EMPTY",v[v.INVALID_BUFFER_OVERSIZE=5018]="INVALID_BUFFER_OVERSIZE",v[v.INVALID_OPERATION=5100]="INVALID_OPERATION",v[v.INVALID_OPERATION_NOT_JOINED=5101]="INVALID_OPERATION_NOT_JOINED",v[v.INVALID_OPERATION_REMOTE_USER_NOT_EXIST=5102]="INVALID_OPERATION_REMOTE_USER_NOT_EXIST",v[v.INVALID_OPERATION_STREAM_TYPE_NOT_EXIST=5103]="INVALID_OPERATION_STREAM_TYPE_NOT_EXIST",v[v.INVALID_OPERATION_REPEAT_CALL=5104]="INVALID_OPERATION_REPEAT_CALL",v[v.INVALID_OPERATION_NEED_VIDEO=5105]="INVALID_OPERATION_NEED_VIDEO",v[v.INVALID_OPERATION_NEED_AUDIO=5106]="INVALID_OPERATION_NEED_AUDIO",v[v.INVALID_ROLE_AUDIENCE=5107]="INVALID_ROLE_AUDIENCE",v[v.INVALID_NOT_ENABLE_SEI=5108]="INVALID_NOT_ENABLE_SEI",v[v.INVALID_NEED_CALL_PUBLISHED=5109]="INVALID_NEED_CALL_PUBLISHED",v[v.ENV_NOT_SUPPORTED=5200]="ENV_NOT_SUPPORTED",v[v.NOT_SUPPORTED_HTTP=5201]="NOT_SUPPORTED_HTTP",v[v.NOT_SUPPORTED_WEBRTC=5202]="NOT_SUPPORTED_WEBRTC",v[v.NOT_SUPPORTED_H264_ENCODE=5203]="NOT_SUPPORTED_H264_ENCODE",v[v.NOT_SUPPORTED_H264_DECODE=5204]="NOT_SUPPORTED_H264_DECODE",v[v.NOT_SUPPORTED_SCREEN_SHARE=5205]="NOT_SUPPORTED_SCREEN_SHARE",v[v.NOT_SUPPORTED_SMALL_VIDEO=5206]="NOT_SUPPORTED_SMALL_VIDEO",v[v.NOT_SUPPORTED_SEI=5207]="NOT_SUPPORTED_SEI",v[v.NOT_SUPPORTED_WEBGL=5208]="NOT_SUPPORTED_WEBGL",v[v.NOT_SUPPORTED_CHROME_VERSION=5209]="NOT_SUPPORTED_CHROME_VERSION",v[v.DEVICE_ERROR=5300]="DEVICE_ERROR",v[v.DEVICE_NOT_FOUND_ERROR=5301]="DEVICE_NOT_FOUND_ERROR",v[v.DEVICE_NOT_ALLOWED_ERROR=5302]="DEVICE_NOT_ALLOWED_ERROR",v[v.DEVICE_NOT_READABLE_ERROR=5303]="DEVICE_NOT_READABLE_ERROR",v[v.DEVICE_OVERCONSTRAINED_ERROR=5304]="DEVICE_OVERCONSTRAINED_ERROR",v[v.DEVICE_INVALID_STATE_ERROR=5305]="DEVICE_INVALID_STATE_ERROR",v[v.DEVICE_SECURITY_ERROR=5306]="DEVICE_SECURITY_ERROR",v[v.DEVICE_ABORT_ERROR=5307]="DEVICE_ABORT_ERROR",v[v.CAMERA_RECOVER_FAILED=5308]="CAMERA_RECOVER_FAILED",v[v.MICROPHONE_RECOVER_FAILED=5309]="MICROPHONE_RECOVER_FAILED",v[v.SERVER_ERROR=5400]="SERVER_ERROR",v[v.NEED_TO_BUY=5401]="NEED_TO_BUY",v[v.ACCOUNT_NO_MONEY=-100013]="ACCOUNT_NO_MONEY",v[v.OPERATION_FAILED=5500]="OPERATION_FAILED",v[v.FIREWALL_RESTRICTION=5501]="FIREWALL_RESTRICTION",v[v.REJOIN_FAILED=5502]="REJOIN_FAILED",v[v.EVENT_HANDLER_ERROR=5503]="EVENT_HANDLER_ERROR",v[v.VIDEO_CONTEXT_ERROR=5504]="VIDEO_CONTEXT_ERROR",v[v.OPERATION_ABORT=5998]="OPERATION_ABORT",v[v.UNKNOWN_ERROR=5999]="UNKNOWN_ERROR",v),Pv=J(O({},ut),{INVALID_PARAMETER(e){let{fnName:t}=e;return"the parameters of the '".concat(t,"' you called does not meet the requirements, please check the API documentation.")},INVALID_PARAMETER_REQUIRED(e){let{key:t,rule:i,fnName:r,value:n}=e;return"'".concat(t||i.name,"' is a required param when calling ").concat(r,"(), received: ").concat(n,".")},INVALID_PARAMETER_TYPE(e){let{key:t,rule:i,fnName:r,value:n}=e,s="".concat(t||i.name),a="";return a=Array.isArray(i.type)?i.type.join("|"):i.type,"'".concat(s,"' must be type of ").concat(a," when calling ").concat(r,"(), received type: ").concat(Fe(n),".")},INVALID_PARAMETER_EMPTY(e){let{key:t,rule:i,fnName:r,value:n}=e;return"'".concat(t||i.name,"' cannot be '").concat(n,"' when calling ").concat(r,"().")},INVALID_PARAMETER_INSTANCE(e){let{key:t,rule:i,fnName:r,value:n}=e,s="".concat(t||i.name),a="".concat(i.instanceOf.name||i.instanceOf);return"'".concat(s,"' must be instanceof ").concat(a," when calling ").concat(r,"(), received type: ").concat(Fe(n),".")},INVALID_PARAMETER_RANGE(e){let{key:t,rule:i,fnName:r,value:n}=e;return"'".concat(t||i.name,"' must be one of ").concat(i.values.join("|")," when calling ").concat(r,"(), received: ").concat(n,".")},INVALID_PARAMETER_LESS_THAN_ZERO(e){let{key:t,rule:i,fnName:r}=e;return"'".concat(t||i.name,"' cannot be less than 0 when calling ").concat(r,"().")},INVALID_PARAMETER_MIN(e){let{key:t,rule:i,value:r}=e;return"the min value of ".concat(t||i.name," is ").concat(i.min,", received: ").concat(r,".")},INVALID_PARAMETER_MAX(e){let{key:t,rule:i,value:r}=e;return"the max value of ".concat(t||i.name," is ").concat(i.max,", received: ").concat(r,".")},INVALID_ELEMENT_ID(e){let{key:t,fnName:i}=e;return"'".concat(t,"' is not found in the document object when calling ").concat(i,"().")},INVALID_ELEMENT_ID_TYPE(e){let{key:t,fnName:i,type:r}=e;return"the element corresponding to '".concat(t,"' must be instanceof HTMLElement when calling ").concat(i,"(), received: ").concat(r,".")},INVALID_STREAM_ID(e){let{key:t}=e;return"'".concat(t,"' can only consist of uppercase and lowercase english letters (a-zA-Z), numbers (0-9), hyphens and underscores.")},INVALID_ROOM_ID_STRING(e){let{key:t}=e;return"'".concat(t,"' must be a valid string.")},INVALID_ROOM_ID_INTEGER(e){let{key:t}=e;return"'".concat(t,"' must be an integer between [1, 4294967294].")},INVALID_ROOM_ID_INTEGER_STRING(e){let{key:t}=e;return"'".concat(t,"' must be an integer but go a string, use 'parseInt' to convert it or use 'strRoomId' instead.")},INVALID_ROOM_ID_REQUIED:()=>"at least one of 'roomId'(between [1, 4294967294]) and 'strRoomId'(not empty) is required.",INVALID_STREAM_TYPE:e=>{let{fnName:t}=e;return"'streamType' is required when 'userId' is not '*', calling ".concat(t,"()")},INVALID_IMAGE_URL:"The 'src' param must be filled in when the background type is image.",INVALID_OPERATION(e){let{fnName:t}=e;return"the API '".concat(t,"' you called does not meet the requirements, please check the API documentation.")},INVALID_OPERATION_NOT_JOINED(e){let{fnName:t}=e;return"cannot ".concat(t," because you are not enter room yet.")},INVALID_OPERATION_REMOTE_USER_NOT_EXIST(e){let{fnName:t,value:i}=e;return"cannot ".concat(t," because remote user(userId: ").concat(i.userId,") does not publishing stream.")},INVALID_OPERATION_STREAM_TYPE_NOT_EXIST(e){let{fnName:t,value:i}=e;return"cannot ".concat(t," because remote user(userId: ").concat(i.userId,") does not publishing ").concat(i.streamType," video.")},INVALID_OPERATION_REPEAT_CALL(e){let{fnName:t}=e;return"you are already ".concat(t,"(), cannot repeated call '").concat(t,"'.")},INVALID_OPERATION_NEED_VIDEO(e){let{fnName:t}=e;return"cannot call '".concat(t,"' because the camera is not turned on.")},INVALID_OPERATION_NEED_AUDIO(e){let{fnName:t}=e;return"cannot call '".concat(t,"' because the microphone is not turned on.")},INVALID_BUFFER_EMPTY:e=>{let{key:t}=e;return"the buffer size of paramerter '".concat(t,"' cannot be empty")},INVALID_BUFFER_OVERSIZE:()=>"buffer size is over 1000 Bytes",INVALID_ROLE_AUDIENCE:()=>"role: '".concat("audience","' cannot call this api."),INVALID_NOT_ENABLE_SEI:()=>"you need to enable SEI in TRTC.create({ enableSEI: true })",INVALID_NEED_CALL_PUBLISHED:e=>{let{fnName:t}=e;return"you need to call ".concat(t,"() after publish stream.")},ENV_NOT_SUPPORTED(e){let{fnName:t}=e;return"the current browser does not support the capability of the function '".concat(t,"' you are calling, please check the API documentation.")},NOT_SUPPORTED_WEBRTC:"the current browser does not support WebRTC capability, please check the SDK documentation.",NOT_SUPPORTED_H264_ENCODE:"this browser does not support H264 encode.",NOT_SUPPORTED_H264_DECODE:"this browser does not support H264 decode.",NOT_SUPPORTED_SCREEN_SHARE:"this browser does not support screen share, please check the browser version.",NOT_SUPPORTED_SMALL_VIDEO:"this browser does not support small video, please check the browser version.",NOT_SUPPORTED_SEI:"this browser does not support SEI, please check the browser version.",NOT_SUPPORTED_WEBGL:"this browser does not support WebGL, please check the browser version.",NOT_SUPPORTED_CHROME_VERSION(e){let{fnName:t}=e;return"cannot call ".concat(t," because the browser version is too low, please upgrade to the latest version")},DEVICE_ERROR(e){let{fnName:t,error:i}=e;return"'".concat(t,"' got device exception").concat(i?", error: ".concat(i.toString(),"."):".")},DEVICE_NOT_FOUND_ERROR(e){let{fnName:t,deviceType:i=pr(t),error:r}=e;return"NotFoundError, no ".concat(i," detected, please check your device and the configuration on '").concat(t,"'").concat(r?", error: ".concat(r.toString(),"."):".")},DEVICE_NOT_ALLOWED_ERROR(e){let{fnName:t,deviceType:i=pr(t),error:r}=e;return"NotAllowedError, you have disabled ".concat(i," access, please allow the current application to use the ").concat(i).concat(r?", error: ".concat(r.toString(),"."):".")},DEVICE_NOT_READABLE_ERROR(e){let{fnName:t,deviceType:i=pr(t),error:r}=e;return"NotReadableError, the ".concat(i," maybe in use by another APP, please check if the device is pre-occupied by another APP.")},DEVICE_OVERCONSTRAINED_ERROR(e){let{fnName:t,deviceType:i=pr(t),error:r}=e;return"OverconstrainedError, the device ID is incorrect, please check whether the device ID passed in is correct".concat(r?", error: ".concat(r.toString(),"."):".")},DEVICE_INVALID_STATE_ERROR(e){let{fnName:t,deviceType:i=pr(t),error:r}=e;return"InvalidStateError, after the user clicks and interacts with the page, turn on the ".concat(i).concat(r?", error: ".concat(r.toString(),"."):".")},DEVICE_SECURITY_ERROR(e){let{fnName:t,deviceType:i=pr(t),error:r}=e;return"SecurityError, check whether the system security policy restricts the use of the ".concat(i,", and it is recommended to turn on the ").concat(i," after the user interacts with the page").concat(r?", error: ".concat(r.toString(),"."):".")},DEVICE_ABORT_ERROR(e){let{fnName:t,deviceType:i=pr(t),error:r}=e;return"AbortError, an unknown exception in the system makes the device unusable, recommended to change the device or browser and re-check whether the device is normal".concat(r?" error: ".concat(r.toString(),"."):".")},CAMERA_RECOVER_FAILED(e){let{error:t}=e;return"camera recover capture failed ".concat((t==null?void 0:t.name)||"",": ").concat((t==null?void 0:t.originMessage)||(t==null?void 0:t.message))},MICROPHONE_RECOVER_FAILED(e){let{error:t}=e;return"microphone recover capture failed ".concat((t==null?void 0:t.name)||"",": ").concat((t==null?void 0:t.originMessage)||(t==null?void 0:t.message))},OPERATION_FAILED(e){let{fnName:t,error:i}=e;return"'".concat(t,"' failed, reason: ").concat(i==null?void 0:i.toString())},FIREWALL_RESTRICTION:()=>"media connection failure due to firewall restrictions, please try to change your network.",EVENT_HANDLER_ERROR(e){let{eventName:t}=e;return"an error was caught on trtc.on('".concat(t,"', handler), please check your code on 'handler'.")},VIDEO_CONTEXT_ERROR(e){let{reason:t,error:i}=e;return"video context error ".concat(t," ").concat((i==null?void 0:i.name)||""," ").concat((i==null?void 0:i.message)||"")},SERVER_ERROR(e){let{fnName:t,error:i}=e;return"'".concat(t,"' got server error: ").concat(i==null?void 0:i.toString(),", please check the SDK documentation.")},NEED_TO_BUY(e){let{value:t,url:i}=e;return"You need to buy packages for ".concat(t,". Refer to: ").concat(i)},ACCOUNT_NO_MONEY:e=>{let{fnParams:t}=e;return"your TRTC account run out of credit, please recharge.".concat(t.sdkAppId?" SDKAppId: ".concat(t.sdkAppId):"")},OPERATION_ABORT(e){let{fnName:t}=e;return"'".concat(t,"' abort")},UNKNOWN_ERROR(e){let{fnName:t,error:i}=e;return"'".concat(t,"' throw unknown exception").concat(i?", error: ".concat(i.toString(),"."):".")}});function pr(e){if(!e)return"camera";let t=e.toLowerCase();return t.includes("screen")?"screen share":t.includes("audio")?"microphone":"camera"}var hc=class extends Error{constructor(e){let{code:t,extraCode:i,message:r="",messageParams:n,fnName:s="",originError:a}=e;var c;let o;o=r||function(l){let d,{code:u,params:p,enableDocLink:m=!1}=l,f="",T=dc[u];try{d=Pv[T]}catch{d=Pv.UNKNOWN_ERROR}return ne(d)?f=d(p):re(d)&&(f=d),p.fnName&&!f.includes(p.fnName)&&(f[f.length-1]!=="."&&(f+="."),f+=" thrown from ".concat(p.fnName,"()")),m&&(f+=" doc:"),f}({code:i||t,params:O({fnName:s,error:a},n)}),super(o),h(this,"name","RtcError"),h(this,"code"),h(this,"extraCode"),h(this,"functionName"),h(this,"message"),h(this,"handler"),h(this,"originError"),this.name=dc[t],this.code=t,this.extraCode=i,this.functionName=s,this.originError=a,this.message=o,this.extraCode===5302&&((c=this.originError)!=null&&c.message.includes("system"))&&(this.handler=()=>{let l=document.createElement("a");sn?l.href="ms-settings:privacy-".concat({startLocalVideo:"webcam",startLocalAudio:"microphone"}[this.functionName]):$i&&(l.href="x-apple.systempreferences:com.apple.preference.security?Privacy_".concat({startLocalVideo:"Camera",startLocalAudio:"Microphone",startScreenShare:"ScreenCapture"}[this.functionName])),l.href.length>0&&l.click()})}static convertFrom(e,t,i){let r=e;if(e instanceof N){let{stack:n}=e,s={code:V.UNKNOWN_ERROR,fnName:t,originError:e};switch(e.getCode()){case C.INVALID_PARAMETER:s.code=V.INVALID_PARAMETER,s.message=e.message;break;case C.INVALID_OPERATION:s.code=V.INVALID_OPERATION;break;case C.NOT_SUPPORTED:case C.NOT_SUPPORTED_H264:s.code=V.ENV_NOT_SUPPORTED,e.getCode()===C.NOT_SUPPORTED_H264&&(s.extraCode=e.message.includes(ut.NOT_SUPPORTED_H264ENCODE)?5203:5204);break;case C.JOIN_ROOM_FAILED:s.messageParams={fnParams:i};case C.SERVER_TIMEOUT:case C.SWITCH_ROLE_FAILED:s.code=V.SERVER_ERROR,s.extraCode=e.getExtraCode();break;case C.API_CALL_ABORTED:s.code=V.OPERATION_ABORT;break;case C.DEVICE_NOT_FOUND:case C.DEVICE_AUTO_RECOVER_FAILED:case C.INITIALIZE_FAILED:s.code=5300,e.name&&(s.extraCode=function(a){let c;switch(a){case"NotFoundError":c=5301;break;case"NotAllowedError":c=5302;break;case"NotReadableError":c=5303;break;case"OverconstrainedError":c=5304;break;case"InvalidStateError":c=5305;break;case"SecurityError":c=5306;break;case"AbortError":c=5307;break;default:c=5300}return c}(e.name));break;case C.UNKNOWN:break;default:s.code=V.OPERATION_FAILED}r=new hc(s),n&&(r.stack+=n.substr(n.indexOf(`
99
+ `)))}else{if(e instanceof hc)return e;r=new hc({code:V.UNKNOWN_ERROR,fnName:t,originError:e})}return r}},M=hc,Lv={type:"object",properties:{cameraId:{type:"string"},useFrontCamera:{type:"boolean"},fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:["string","boolean"],values:[!0,!1,"view","publish","both"]},small:{properties:{width:{type:"number"},height:{type:"number"},frameRate:{type:"number"},bitrate:{type:"number"}}},videoTrack:{instanceOf:MediaStreamTrack}}},Mv={type:"object",properties:{systemAudio:{type:"boolean"},fillMode:{type:"string",values:["contain","cover","fill"]},profile:{type:["string","object"],properties:{width:{type:"number"},height:{type:"number"},frameRate:{type:"number"},bitrate:{type:"number"}}},videoTrack:{instanceOf:MediaStreamTrack},audioTrack:{instanceOf:MediaStreamTrack}}},Tn={type:["string",HTMLElement,null,"array"],arrayItem:{instanceOf:HTMLElement},validate(e,t,i){if(re(e)&&!document.getElementById(e))throw new M({code:V.INVALID_PARAMETER,extraCode:5009,fnName:i,messageParams:{key:t}})}},xv={name:"userId",required:!0,type:"string"},Vv={type:"object",properties:{microphoneId:{type:"string"},audioTrack:{instanceOf:MediaStreamTrack},captureVolume:{type:"number",min:0},earMonitorVolume:{type:"number",min:0,max:100},profile:{values:[Yt.AUDIO_PROFILE_STANDARD,Yt.AUDIO_PROFILE_STANDARD_STEREO,Yt.AUDIO_PROFILE_HIGH,Yt.AUDIO_PROFILE_HIGH_STEREO]},echoCancellation:{type:"boolean"},autoGainControl:{type:"boolean"},noiseSuppression:{type:"boolean"}}};function $s(e,t){if(!e)throw new M({code:V.INVALID_OPERATION,extraCode:5101,fnName:t})}function Uv(e,t,i){if(!e)throw new M({code:V.INVALID_OPERATION,extraCode:5102,fnName:t,messageParams:{value:i}})}var eU={create:[{name:"RoomConfig",instanceOf:Function},{name:"CreateConfig",type:"object",properties:{plugins:{type:"array",arrayItem:{instanceOf:Function}}}}],enterRoom:{name:"EnterRoomConfig",type:"object",required:!0,validate(e,t,i){if(this._room.isJoined)throw new M({code:V.INVALID_OPERATION,extraCode:5104,fnName:i});if(e.roomId){if(re(e.roomId))throw new M({code:V.INVALID_PARAMETER,extraCode:5016,fnName:i,messageParams:{key:t}});if(!(/^[1-9]\d*$/.test(String(e.roomId))&&e.roomId<4294967295))throw new M({code:V.INVALID_PARAMETER,extraCode:5013,fnName:i,messageParams:{key:t}})}else{if(!e.strRoomId)throw new M({code:V.INVALID_PARAMETER,extraCode:5015,fnName:i});if(!/^[A-Za-z\d\s!#$%&()+\-:;<=.>?@[\]^_{}|~,]{1,64}$/.test(e.strRoomId))throw new M({code:V.INVALID_PARAMETER,extraCode:5012,fnName:i,messageParams:{key:t}})}},properties:{sdkAppId:{required:!0,type:"number",allowEmpty:!1},userId:{required:!0,type:"string",allowEmpty:!1},userSig:{required:!0,type:"string",allowEmpty:!1},scene:{type:"string",values:["live","rtc"]},role:{type:"string",values:["audience","anchor"]},roomId:{type:["string","number"]},strRoomId:{type:"string"},proxy:{type:["object","string"],properties:{websocketProxy:{type:"string"},turnServer:{type:["object","array"],properties:{url:{required:!0,type:"string"},username:{type:"string"},credential:{type:"string"},credentialType:{type:"string",values:["password"]}}},loggerProxy:{type:"string"},webtransportProxy:{type:"string"}}},enableAutoPlayDialog:{type:"boolean"},userDefineRecordId:{type:"string"},latencyLevel:{type:"number"}}},startLocalVideo:{name:"LocalVideoConfig",type:"object",properties:{view:Tn,mute:{type:["boolean","string"]},publish:{type:"boolean"},option:Lv},validate(e){var t;if(((t=e==null?void 0:e.option)==null||!t.videoTrack)&&ar())throw new M({code:V.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalVideo:{name:"updateLocalVideoConfig",type:"object",required:!0,properties:{view:J(O({},Tn),{required:!1}),publish:{type:"boolean"},mute:{type:["boolean","string"]},option:Lv}},startLocalAudio:{name:"LocalAudioConfig",type:"object",properties:{publish:{type:"boolean"},option:Vv},validate(e){var t;if(((t=e==null?void 0:e.option)==null||!t.audioTrack)&&ar())throw new M({code:V.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalAudio:{name:"updateLocalAudioConfig",type:"object",required:!0,properties:{publish:{type:"boolean"},mute:{type:"boolean"},option:Vv}},startScreenShare:{name:"ScreenShareConfig",type:"object",properties:{view:Tn,publish:{type:"boolean"},option:Mv},validate(e,t,i,r,n){var s;if(((s=e==null?void 0:e.option)==null||!s.videoTrack)&&ar())throw new M({code:V.ENV_NOT_SUPPORTED,extraCode:5201});if(!ec())throw new M({code:V.ENV_NOT_SUPPORTED,fnName:i,extraCode:5205})}},updateScreenShare:{name:"updateScreenShareConfig",type:"object",required:!0,properties:{view:Tn,publish:{type:"boolean"},option:Mv}},muteRemoteAudio:[xv,{name:"mute",required:!0,type:"boolean"}],setRemoteAudioVolume:[xv,{name:"volume",required:!0,type:"number",min:0}],startRemoteVideo:{name:"startRemoteVideoConfig",type:"object",required:!0,properties:{view:Tn,userId:{type:"string",required:!0},streamType:{values:["main","sub"],required:!0},option:{type:"object",properties:{fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:"boolean"}}}},validate(e,t,i){$s(this._room.isJoined,i);let r=this._room.remotePublishedUserMap.get(e.userId);if(Uv(!!r,i,e),r&&(e.streamType==="main"&&!r.muteState.videoAvailable||e.streamType==="sub"&&!r.muteState.hasAuxiliary))throw new M({code:V.INVALID_OPERATION,extraCode:5103,fnName:i,messageParams:{value:e}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:"object",required:!0,properties:{view:J(O({},Tn),{required:!1}),userId:{type:"string",required:!0},streamType:{values:["main","sub"],required:!0},option:{type:"object",properties:{fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:"boolean"}}}},validate(e,t,i){$s(this._room.isJoined,i);let r=this._room.remotePublishedUserMap.get(e.userId);if(Uv(!!r,i,e),r&&(e.streamType==="main"&&!r.muteState.videoAvailable||e.streamType==="sub"&&!r.muteState.hasAuxiliary))throw new M({code:V.INVALID_OPERATION,extraCode:5103,fnName:i,messageParams:{value:e}})}},stopRemoteVideo:{name:"stopRemoteVideoConfig",type:"object",required:!0,properties:{userId:{type:"string",required:!0},streamType:{values:["main","sub"]}},validate(e,t,i){if(e.userId!=="*"&&I(e.streamType))throw new M({code:V.INVALID_PARAMETER,extraCode:5014,fnName:i})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(e,t,i){$s(this._room.isJoining||this._room.isJoined,i)}},enableAudioVolumeEvaluation:[{name:"interval",type:"number"},{name:"enableInBackground",type:"boolean"}],sendSEIMessage:[{name:"buffer",required:!0,instanceOf:ArrayBuffer,validate(e,t,i,r){if(!or)throw new M({code:V.ENV_NOT_SUPPORTED,fnName:i,extraCode:5207});if(!this._room.enableSEI)throw new M({code:V.INVALID_OPERATION,fnName:i,extraCode:5108});if(e.byteLength>1e3)throw new M({code:V.INVALID_PARAMETER,extraCode:5018,fnName:i});if(e.byteLength===0)throw new M({code:V.INVALID_PARAMETER,extraCode:5017,messageParams:{key:t},fnName:i});$s(this._room.isJoined,i)}},{name:"options",type:"object",properties:{seiPayloadType:{type:"number",values:[5,243]},toSubStream:{type:"boolean",validate(e,t,i){if(!e&&!this._room.isMainStreamPublished||e&&!this._room.isAuxStreamPublished)throw new M({code:V.INVALID_OPERATION,extraCode:5109,messageParams:{key:t},fnName:i})}}}}],sendCustomMessage:{name:"message",required:!0,type:"object",properties:{cmdId:{type:"number",required:!0,min:1,max:10},data:{instanceOf:ArrayBuffer,required:!0,validate(e,t,i,r){if(e.byteLength>1e3)throw new M({code:V.INVALID_PARAMETER,extraCode:5018,fnName:i});if(e.byteLength===0)throw new M({code:V.INVALID_PARAMETER,extraCode:5017,fnName:i,messageParams:{key:t}})}}},validate(e,t,i){if($s(this._room.isJoined,i),this._room.scene==="live"&&this._room.role==="audience")throw new M({code:V.INVALID_OPERATION,extraCode:5107,fnName:i,messageParams:{key:t}})}}},Ae={TRTC:eU},ze=class extends Error{};function tU(e,t){let i=xs(e);for(let r=0;r<t.length;r++)nr(i[r],t[r]);return i}function iU(e){this._resolve=Promise.resolve(e)}function rU(e){this._reject=Promise.reject(e)}var Zs=class{constructor(e,t){this.instance=e,this.group=t,this.started=!1,this.ops=[],this.startSame=()=>!0,this.mergeUpdate=tU;let i=Zs.instances.get(e);i?i.set(t,this):Zs.instances.set(e,new Map([[t,this]]))}static get(e,t){let i=Zs.instances.get(e);return i&&i.get(t)||new Zs(e,t)}action(e,t,i){let r=a=>{var c;return e===0?this.started=!0:e===3&&(this.started=!1),this.ops.shift(),(c=this.currentOp)==null||c.action(),a},n=a=>{var c,o;throw this.ops.shift(),e===0&&((c=this.currentOp)==null?void 0:c.type)===2&&this.ops.shift().reject(new ze("start failed")),(o=this.currentOp)==null||o.action(),a},s={type:e,action:()=>t(...s.args).then(r,n),args:i,resolve:iU,reject:rU};try{switch(this.state){case 1:if(e===0)throw new ze("already started");break;case 4:if(e===2)throw new ze("not started");break;default:return this.cacheOp(s)}}catch(a){return Promise.reject(a)}return this.ops.push(s),s.promise=t(...s.args).then(r,n)}cacheOp(e){if(this.ops.length===1)switch(this.state){case 0:case 2:if(e.type===0)throw new ze("already start");break;case 3:switch(e.type){case 2:throw new ze("update not allowed when stopping");case 3:return this.currentOp.promise}break;default:throw new ze("unknown state")}else switch(e.type){case 3:if(this.lastOpType===3)return this.lastOp.promise;{let i=new ze("keep stop");if(this.ops.slice(1).forEach(r=>r.reject(i)),this.ops=this.ops.slice(0,1),this.state===3)return this.currentOp.promise}break;case 2:switch(this.lastOpType){case 2:return this.lastOp.args=this.mergeUpdate(this.lastOp.args,e.args),this.lastOp.promise;case 3:throw new ze("update not allowed after stop")}break;case 0:switch(this.lastOpType){case 2:throw new ze("start not allowed after update");case 0:throw new ze("duplicate start");case 3:if(this.startSame(this.currentOp.args,e.args))throw this.ops.pop().reject(new ze("keep start")),new ze("already start")}}e.promise=new Promise((i,r)=>{e._resolve?e._resolve.then(i):e.resolve=i,e._reject?e._reject.catch(r):e.reject=r});let{action:t}=e;return e.action=()=>t().then(e.resolve,e.reject),this.ops.push(e),e.promise}get lastOp(){return this.ops[this.ops.length-1]}get lastOpType(){return this.lastOp.type}get currentOp(){return this.ops[0]}get state(){return this.currentOp?this.currentOp.type:this.started?1:4}},ea=Zs;ea.instances=new WeakMap;var pc=new WeakMap,mc=(e,t)=>{if(t instanceof ze){let{stack:i}=t;t=new M({code:V.OPERATION_ABORT,message:"".concat(e," abort: ").concat(t.message),fnName:e}),i&&(t.stack+=i.substr(i.indexOf(`
100
+ `)))}throw t};function mr(e,t){return ae((i,r)=>function(){for(var n=arguments.length,s=new Array(n),a=0;a<n;a++)s[a]=arguments[a];let c=ea.get(this,typeof e=="string"?e:e.call(this,...s));return t&&(c.startSame=t.bind(this)),c.action(0,i.bind(this),s).catch(mc.bind(null,r))})}function En(e,t){let{merge:i,debounce:r}=t||{};return ae((n,s)=>function(){for(var a=arguments.length,c=new Array(a),o=0;o<a;o++)c[o]=arguments[o];let l=ea.get(this,typeof e=="string"?e:e.call(this,...c));if(i&&(l.mergeUpdate=i.bind(this)),r&&r.isNeedToDebounce.apply(this,c)){let{delay:d,getKey:u}=r;return new Promise((p,m)=>{var f,T;let S=(f=pc.get(this))==null?void 0:f.get(u(...c));if(S){let{timeoutId:E,resolve:D}=S;clearTimeout(E),D()}let y=setTimeout(()=>{if(l.state===3||l.state===4)return p();l.action(2,n.bind(this),c).catch(mc.bind(null,s)).then(p,m)},d);pc.has(this)?(T=pc.get(this))==null||T.set(u(...c),{timeoutId:y,resolve:p}):pc.set(this,new Map([[u(...c),{timeoutId:y,resolve:p}]]))})}return l.action(2,n.bind(this),c).catch(mc.bind(null,s))})}function _r(e){return ae((t,i)=>function(){for(var r=arguments.length,n=new Array(r),s=0;s<r;s++)n[s]=arguments[s];return ea.get(this,typeof e=="string"?e:e.call(this,...n)).action(3,t.bind(this),n).catch(mc.bind(null,i))})}var F={ERROR:"error",AUTOPLAY_FAILED:"autoplay-failed",KICKED_OUT:"kicked-out",REMOTE_USER_ENTER:"remote-user-enter",REMOTE_USER_EXIT:"remote-user-exit",REMOTE_AUDIO_AVAILABLE:"remote-audio-available",REMOTE_AUDIO_UNAVAILABLE:"remote-audio-unavailable",REMOTE_VIDEO_AVAILABLE:"remote-video-available",REMOTE_VIDEO_UNAVAILABLE:"remote-video-unavailable",AUDIO_VOLUME:"audio-volume",NETWORK_QUALITY:"network-quality",CONNECTION_STATE_CHANGED:"connection-state-changed",AUDIO_PLAY_STATE_CHANGED:"audio-play-state-changed",VIDEO_PLAY_STATE_CHANGED:"video-play-state-changed",SCREEN_SHARE_STOPPED:"screen-share-stopped",DEVICE_CHANGED:"device-changed",PUBLISH_STATE_CHANGED:"publish-state-changed",TRACK:"track",STATISTICS:"statistics",SEI_MESSAGE:"sei-message",CUSTOM_MESSAGE:"custom-message"};function _c(e){return e==="sub"?"auxiliary":e==="auxiliary"?"sub":"main"}function yn(e){return e===Yt.QOS_PREFERENCE_CLEAR?"detail":e===Yt.QOS_PREFERENCE_SMOOTH?"motion":""}var Fv=class{constructor(){h(this,"_log"),this._log=b.createLogger({id:"fd"})}download(e,t){return g(this,null,function*(){let{type:i="blob"}=t||{};try{let r,n=W();if(r=ne(fetch)?yield this.downloadWithFetch(e,i):yield this.downloadWithXHR(e,i),!r||!r.data)throw new Error("data is empty");let s=W()-n;return this._log.info("downloaded: ".concat(e,", return type: ").concat(i,", cost: ").concat(s,"ms")),L.addSuccessEvent({key:522700,cost:W()-n}),r.data}catch(r){throw this._log.error("failed to download: ".concat(e,", error: ").concat(r)),L.addFailedEvent({key:522700,error:r}),r}})}downloadWithFetch(e,t){return g(this,null,function*(){this._log.info("download with fetch: ".concat(e,", return type: ").concat(t));try{let i,r=yield fetch(e);if(!r.ok)throw new Error("network response was not ok");return i=t==="arraybuffer"?yield r.arrayBuffer():yield r.blob(),{data:i}}catch(i){throw i}})}downloadWithXHR(e,t){return this._log.info("download with xhr: ".concat(e,", return type: ").concat(t)),new Promise((i,r)=>{let n=new XMLHttpRequest;n.open("GET",e,!0),n.responseType=t,n.onload=()=>{n.status===200||n.status===0&&n.response?i({data:n.response}):r(new Error("XHR failed"))},n.onerror=r,n.send(null)})}loadWasm(e,t){return g(this,null,function*(){this._log.info("loadWasm ".concat(e,", importObject: ").concat(JSON.stringify(t)));let i=W(),r=null,n=null;if(ne(WebAssembly.instantiateStreaming)&&!e.startsWith("data:application/octet-stream;base64,")&&!(s=>s.startsWith("file://"))(e)&&ne(fetch))try{let s=fetch(e);r=(yield WebAssembly.instantiateStreaming(s,t)).instance}catch(s){n=s}if(!r)try{let s=yield this.download(e,{type:"arraybuffer"});r=(yield WebAssembly.instantiate(s,t)).instance}catch(s){n=s}if(r){let s=W()-i;return this._log.info("loadedWasm ".concat(e,", cost: ").concat(s,"ms")),L.addSuccessEvent({key:522701,cost:s}),r}throw this._log.error("failed to loadWasm ".concat(e,", error: ").concat(n)),L.addFailedEvent({key:522701,error:n}),n})}};k([cr({settings:{timeout:0,retries:3},onRetrying(e){this._log.warn("download retrying: ".concat(e))}})],Fv.prototype,"download");var nU=new Fv,fc=new WeakMap;function Le(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return ae((r,n)=>function(){for(var s=arguments.length,a=new Array(s),c=0;c<s;c++)a[c]=arguments[c];try{cp.call(this,t,a,n,this._name)}catch(o){return Promise.reject(o)}return r.apply(this,a)})}function Bv(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return ae((r,n)=>function(){for(var s=arguments.length,a=new Array(s),c=0;c<s;c++)a[c]=arguments[c];try{cp.call(this,t,a,n,this._name)}catch(o){throw o}return r.apply(this,a)})}function cp(e,t,i,r){if(Ce(e))for(let n=0;n<e.length;n++)gc.call(this,{rule:e[n],value:t[n],key:e[n].name,fnName:i,className:r});else gc.call(this,{rule:e,value:t[0],key:e.name,fnName:i,className:r})}function gc(e){let{rule:t,value:i,key:r,fnName:n,className:s}=e;function a(l){return{code:V.INVALID_PARAMETER,extraCode:l,fnName:n,messageParams:{key:r,rule:t,value:i}}}if(I(i)){if(t.required)throw new M(a(5001));if(I(t.defaultValue))return void(ne(t.validate)&&t.validate.call(this,i,r,n,s,this));i=t.defaultValue}if(Array.isArray(t.type)){let l=!1;for(let d=0;d<t.type.length;d++)t.type[d]===null&&i===null&&(l=!0),ne(t.type[d])&&i instanceof t.type[d]&&(l=!0),re(t.type[d])&&Fe(i)===t.type[d].toLowerCase()&&(l=!0);if(!l)throw new M({code:V.INVALID_PARAMETER,extraCode:5002,fnName:n,messageParams:{key:r,rule:{type:t.type.map(d=>Rh(d)?bS(d):re(d)?d:Fe(d))},value:i}})}else if(!I(t.type)&&Fe(i)!==t.type)throw new M(a(5002));if(t.allowEmpty===!1){let l=ge(i)&&(i===0||Number.isNaN(i)),d=re(i)&&i.trim()==="";if(l||d)throw new M(a(5003))}if(t.notLessThanZero&&ge(i)&&i<0)throw new M(a(5006));if(!I(t.min)&&ge(i)&&i<t.min)throw new M(a(5007));if(!I(t.max)&&ge(i)&&i>t.max)throw new M(a(5008));if(re(t.instanceOf)){if(!i||i._name!==t.instanceOf)throw new M(a(5004))}else if(ne(t.instanceOf)&&!(i instanceof t.instanceOf))throw new M(a(5004));if(Array.isArray(t.values)&&!t.values.includes(i))throw new M(a(5005));let{properties:c}=t;jt(c)&&Ei(i)&&Object.keys(c).forEach(l=>{gc.call(this,{rule:c[l],value:i&&i[l],key:"".concat(l),fnName:n,className:s})});let{arrayItem:o}=t;jt(o)&&Ce(i)&&i.forEach((l,d)=>{gc.call(this,{rule:o,value:l,key:"".concat(r,"[").concat(d,"]"),fnName:n,className:s})}),ne(t.validate)&&t.validate.call(this,i,r,n,s,this)}function oe(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},{getRemoteId:t=()=>"",replaceArg:i,getKVReportKey:r}=e;return ae((n,s)=>function(){for(var a=arguments.length,c=new Array(a),o=0;o<a;o++)c[o]=arguments[o];function l(p,m,f){if(f&&f.includes(p))return"hided";if(i){let T=i(...c);if(c[T.argIndex]===m)return T.value}if(m===c||p in c)return m;try{return m instanceof HTMLElement?"id: ".concat(m.id," type:").concat(Fe(m)):(JSON.stringify(m),m)}catch{return"type:".concat(Fe(m))}}let d=this._log||b;c.length>0?d.info("".concat(s,"() ").concat(JSON.stringify(c,(p,m)=>l(p,m,["userSig","privateMapKey"])))):d.info("".concat(s,"()"));let u=r?r(...c):XS[s];try{let p=n.apply(this,c),m=W();return Ah(p)?p.then(f=>(d.info("".concat(s,"() success ").concat(t.call(this,...c))),L.addSuccessEvent({key:u,cost:W()-m}),f)).catch(f=>{throw f=M.convertFrom.call(this,f,s,c.length===1?c[0]:c),d.error("".concat(s,"() failed ").concat(t.call(this,...c)," ").concat(f," params: ").concat(JSON.stringify(c,l))),L.addFailedEvent({key:u,error:f}),f}):(L.addSuccessEvent({key:u}),p)}catch(p){throw p=M.convertFrom.call(this,p,s),d.error("".concat(s,"() failed ").concat(p," params: ").concat(JSON.stringify(c,l))),L.addFailedEvent({key:u,error:p}),p}})}var lp=e=>ae((t,i)=>function(r,n){return g(this,null,function*(){let s=this._plugins.get(r);if(!s)throw this._log.error("plugin ".concat(String(r)," is not found")),new M({code:V.OPERATION_ABORT,message:"plugin ".concat(String(r)," is not found"),fnName:i});return cp.call(this,s.getValidateRule(e),[n],i,"TRTC"),t.call(this,s,n)})}),up=0,sU=class{constructor(e,t){h(this,"player"),h(this,"publisher"),h(this,"mixInput"),this.mixInput=new lv(t),e.url?(this.player=new Audio(e.url),this.player.crossOrigin="anonymous",this.publisher=new Audio(e.url),this.publisher.crossOrigin="anonymous",this.mixInput.replaceSource(this.publisher)):this.mixInput.replaceSource(e.track),this.mixInput.connect()}updateSettings(e){!this.player||(I(e.volume)||(this.volume=e.volume),I(e.loop)||(this.loop=e.loop),I(e.playbackRate)||(this.playbackRate=e.playbackRate))}updateListener(e){if(this.player){if(e.onDurationChange){let{onDurationChange:t}=e;this.player.ondurationchange=i=>{t(i.target.duration)}}if(e.onTimeUpdate){let t=e.onTimeUpdate,{player:i}=this;i.ontimeupdate=()=>{t(i.currentTime,i.duration)}}e.onEnded&&(this.player.onended=e.onEnded)}}reset(){this.seek(0),this.mixInput.connect()}seek(e){!this.player||e<0&&e>this.player.duration||(this.player.currentTime=e,this.publisher.currentTime=e)}play(){var e,t;return(e=this.publisher)==null||e.play(),(t=this.player)==null?void 0:t.play()}pause(){var e,t;(e=this.player)==null||e.pause(),(t=this.publisher)==null||t.pause()}stop(){var e;(e=this.player)==null||e.pause(),this.mixInput.disconnect()}setOperation(e){e==="pause"&&this.pause(),e==="resume"&&(this.pause(),this.play()),e==="stop"&&(this.pause(),this.seek(0))}set volume(e){!this.player||!this.publisher||(this.player.volume=e,this.publisher.volume=e)}set loop(e){!this.player||!this.publisher||(this.player.loop=e,this.publisher.loop=e)}set playbackRate(e){!this.player||!this.publisher||(this.player.playbackRate=e,this.publisher.playbackRate=e)}};function Sn(e,t){if(t&&typeof t!="function")throw new M({code:V.INVALID_PARAMETER,message:"start audioMixer plugin: param ".concat(e," should be a function.")})}var ta=class{constructor(e){this.core=e,h(this,"log"),h(this,"mixedMusicMap",new Map),h(this,"cacheMusicMap",new Map),up+=1,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(up)}),this.log.info("[audioMixer] created id=".concat(this.getAlias()).concat(up)),this.core=e}getName(){return ta.Name}getAlias(){return"ax"}getGroup(e){return e==null?void 0:e.id}getValidateRule(e){switch(e){case"start":return ta.startValidateRule;case"update":return ta.updateValidateRule;case"stop":return ta.stopValidateRule}}start(e){return g(this,null,function*(){let{room:t}=this.core;this.log.info("add music source, id: ".concat(e.id," url: ").concat(e.url,", track: ").concat(e.track));let{id:i,url:r}=e;if(this.mixedMusicMap.has(i))return;let n=this.cacheMusicMap.get(i);n?e.url?n.reset():(n.mixInput.replaceSource(e.track),n.mixInput.connect()):(n=new sU(e,t.audioManager),this.cacheMusicMap.set(i,n)),n.updateListener(e),n.updateSettings(e),yield n.play(),this.mixedMusicMap.set(i,n),this.log.info("start mix audio track ".concat(i," success.")),L.addEnum({key:502700,value:3}),this.kvUpload(e)})}update(e){return g(this,null,function*(){let{id:t,operation:i,seekFrom:r,playbackRate:n}=e;this.log.info("update music source, ".concat(JSON.stringify(e)));let s=this.mixedMusicMap.get(t);s?(s.updateSettings(e),s.updateListener(e),I(i)||s.setOperation(i),I(r)||s.seek(r),this.kvUpload(e)):this.log.warn("update music source failed, music id: ".concat(t," not found."))})}stop(e){return g(this,arguments,function(t){var i=this;let{id:r}=t;return function*(){var n;i.mixedMusicMap.has(r)&&(i.log.info("remove music source, music id: ".concat(r)),(n=i.mixedMusicMap.get(r))==null||n.stop(),i.mixedMusicMap.delete(r)),r==="*"&&i.destroyAllMusic()}()})}kvUpload(e){let{track:t,loop:i,volume:r,playbackRate:n,operation:s,seekFrom:a,onTimeUpdate:c,onDurationChange:o,onEnded:l}=e;t&&L.addCount({key:502711}),i&&L.addCount({key:502703}),r&&L.addCount({key:502704}),n&&L.addCount({key:502705}),s&&L.addCount({key:502706}),a&&L.addCount({key:502707}),typeof c!="function"&&L.addCount({key:502709}),typeof l!="function"&&L.addCount({key:502710}),typeof o!="function"&&L.addCount({key:502708})}destroyAllMusic(){this.log.info("destroy all music source."),this.mixedMusicMap.forEach((e,t)=>this.stop({id:t}))}destroyAllCache(){this.log.info("destroy all music cache."),this.cacheMusicMap.clear()}destroy(){this.log.info("destroy audio mixer plugin."),this.destroyAllMusic(),this.destroyAllCache()}},ia=ta;h(ia,"startValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},url:{type:"string",required:!1},track:{required:!1},loop:{type:"boolean"},volume:{type:"number"}},validate(e,t,i){if(e.url&&e.url!=="*"){let r=e.url.split("?")[0],n=["mp3","ogg","wav","flac"],s=r.split(".").pop(),a=n.indexOf(s)>=0,c=r.startsWith("blob"),o=r.startsWith("data");if(!(a||c||o))throw new M({code:V.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:i})}if(!e.url&&!e.track)throw new M({code:V.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:i});Sn("onTimeUpdate",e.onTimeUpdate),Sn("onEnded",e.onEnded),Sn("onDurationChange",e.onDurationChange)}}),h(ia,"updateValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},loop:{type:"boolean"},volume:{type:"number"},seekFrom:{type:"number"},operation:{type:"string",values:["pause","resume","stop"]}},validate(e,t,i){Sn("onTimeUpdate",e.onTimeUpdate),Sn("onEnded",e.onEnded),Sn("onDurationChange",e.onDurationChange)}}),h(ia,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),h(ia,"Name","AudioMixer");var aU=e=>(e=Number(e))>0&&e<14e8,dp=0,ra=class{constructor(e){this.core=e,h(this,"log"),h(this,"preloadPromise"),h(this,"audioContext",Ii()),h(this,"workletNode"),dp+=1,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(dp)}),this.log.info("[audioDenoiser] created id=".concat(this.getAlias()).concat(dp)),e.assetsPath&&this.preload("".concat(e.assetsPath,"/denoiser-wasm.js"))}static startValidateRule(e){return{name:"options",required:!0,type:"object",properties:{sdkAppId:{type:"number",required:!0},userId:{type:"string",required:!0},userSig:{type:"string",required:!0}},validate(t,i,r,n){if(!e.room.audioManager.hasAudioTrack)throw new M({code:V.INVALID_OPERATION,extraCode:5106,fnName:r})}}}preload(e){return this.preloadPromise||(this.preloadPromise=this.doPreload(e)),this.preloadPromise}doPreload(e){return g(this,null,function*(){let t=yield this.core.fileDownloader.download(e,{type:"blob"}),i=URL.createObjectURL(t);try{yield Xh(this.audioContext,i)}finally{URL.revokeObjectURL(i)}})}getName(){return ra.Name}getAlias(){return"ad"}getGroup(){return"AIDenoiser_".concat(Date.now())}getValidateRule(e){switch(e){case"start":return ra.startValidateRule(this.core);case"update":return ra.updateValidateRule;case"stop":return ra.stopValidateRule}}start(e){return g(this,null,function*(){let{room:t}=this.core;if(yield this.preload("".concat(e.assetsPath,"/denoiser-wasm.js")),!this.workletNode){let i=String(Date.now()).slice(0,-3),{auth:r,sign:n,status:s,message:a}=yield function(c){return g(this,arguments,function(o){let{sdkAppId:l,userId:d,userSig:u,timestamp:p}=o;return function*(){let m="https://".concat(function(Q){let q;return q=aU(Q)?Hv.MAIN_OVERSEA:Hv.MAIN,q}(l),"/api/v1/audioAiAuth?sdkAppId=").concat(l,"&userId=").concat(d,"&userSig=").concat(u,"&timestamp=").concat(p),f=yield fetch(m),{data:{errCode:T,errMsg:S,sign:y,status:E}}=yield f.json();if(E==="1")return{auth:!0,sign:y,status:E,message:S};let D="Init RTCAIDenoiser failed.",P="";switch(T){case 1:P="Please check your params.";break;case 2:P="You need to buy packages. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 3:P="Server is invalid. Please contact our engineer. ";break;case 4:P="Your packages is not active. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 5:P="Your packages is expired. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 6:P="Your version is not supported."}return{auth:!1,status:E,message:S?"".concat(D," Reason: ").concat(S,". ").concat(P):"".concat(D,", ").concat(P)}}()})}(J(O({},e),{timestamp:i}));if(!r)throw this.log.info("RTCAIDenoiser: ".concat(e.userId," auth result: ").concat(r,". Message: ").concat(a)),new M({code:V.INVALID_PARAMETER,message:a});this.workletNode=new AudioWorkletNode(this.audioContext,"trtc-denoiser-processor",{numberOfInputs:1,numberOfOutputs:1}),this.workletNode.port.postMessage({type:"init",data:{sdkAppId:String(e.sdkAppId),userId:e.userId,timestamp:i,sign:n,status:s}}),this.workletNode.port.onmessage=c=>{let{data:o}=c;o.type==="cost"&&this.log.debug("[RTCAIDenoiser] ".concat(o.value))}}this.workletNode.port.postMessage({type:"enable"}),t.audioManager.addDenoiser(this.workletNode),t.sendAbilityStatus({ai_denoise:1})})}update(){return g(this,null,function*(){})}stop(){return g(this,null,function*(){if(!this.workletNode)return;let{room:e}=this.core;this.workletNode.port.postMessage({type:"disable"}),yield e.audioManager.removeDenoiser(this.workletNode)})}destroy(){}},Tc=ra;h(Tc,"updateValidateRule",{type:"object"}),h(Tc,"stopValidateRule",{type:"object"}),h(Tc,"Name","AIDenoiser");var Hv={MAIN:"schedule.cloud-rtc.com",MAIN_OVERSEA:"schedule.rtc.tencentcloud.com"},oU=Ie(Ve(),1),cU=class extends oU.EventEmitter{constructor(){super(),this.state="nominal",this.onPressureChange=this.onPressureChange.bind(this)}get stateNum(){switch(this.state){case"nominal":return 1;case"fair":return 2;case"serious":return 3;case"critical":return 4}}start(){return g(this,null,function*(){if(!this.observer)try{"PressureObserver"in window&&!Ue&&(this.observer=new PressureObserver(this.onPressureChange),yield this.observer.observe("cpu",{sampleInterval:2e3}))}catch(e){de.uploadEvent({log:"stat-pressure-detector-start-failed",error:e})}})}onPressureChange(e){let t=this.stateNum,i=e[e.length-1];this.state=i.state,(this.stateNum>3||t>3)&&b.info("".concat(i.source,": ").concat(i.state)),this.emit("state-changed",{type:i.source,state:this.state})}destroy(){var e;try{(e=this.observer)==null||e.disconnect(),this.observer=null}catch(t){de.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:t})}}},jv=new cU,Gv=0,Ec=new Set,Ne=null;Vy("5.7.1");var lU={RtcError:M,ErrorCode:V,ErrorCodeDictionary:dc},yc=class extends tx.EventEmitter{constructor(e,t){super(),h(this,"_room"),h(this,"_eventListened",new Set),h(this,"_localVideoTrack",null),h(this,"_localAudioTrack",null),h(this,"_localScreenTrack",null),h(this,"_localScreenAudioTrack",null),h(this,"_localVideoConfig",null),h(this,"_localScreenConfig",null),h(this,"_localAudioConfig",null),h(this,"_remoteVideoConfigMap",new Map),h(this,"_remoteAudioConfigMap",new Map),h(this,"_remoteAudioMuteMap",new Map),h(this,"_mediaTrackMap",new WeakMap),h(this,"_log",b.createLogger({id:"t".concat(++Gv)})),h(this,"_plugins",new Map),h(this,"_networkQuality",null),h(this,"_speakerId"),this._room=new e(O({logger:this._log,frameWorkType:yc.frameWorkType},t)),this._log.debug(JSON.stringify(t)),Object.defineProperties(this,{dumpAudio:{enumerable:!1,value(i){return this._room.audioManager.dump(i)}}}),t.plugins&&t.plugins.forEach(i=>{this._use(i,t.assetsPath)}),this._use(ia,t.assetsPath),this._use(Tc,t.assetsPath),this._room.on("audio-volume",i=>{!i.find(r=>r.userId==="")&&this._localAudioTrack&&i.push({userId:"",volume:Math.floor(100*this._localAudioTrack.getAudioLevel())}),this.emit(F.AUDIO_VOLUME,{result:i.sort((r,n)=>n.volume-r.volume)})}),this._room.videoManager.on("error",i=>{let{reason:r,error:n}=i;this._log.error(new M({code:V.OPERATION_FAILED,extraCode:5504,messageParams:{reason:r,error:n}}))}),this._listenEvents(),this._initActiveSpeaker(),((i,r)=>{let{emit:n}=i;i.emit=function(){for(var s=arguments.length,a=new Array(s),c=0;c<s;c++)a[c]=arguments[c];try{return n.apply(i,a)}catch(o){let l=j({key:B.CATCH_HANDLER_ERROR,data:{name:r,event:a[0]},addDocLink:!1});return b.warn("".concat(l,`
101
+
102
+ `).concat(o.stack)),!1}}})(this,"trtc")}static create(e){}static _create(e,t){var i;Ov&&(Ov=!1,b.getLogLevel()!==5&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info("* API Document: ".concat(Yi,"/en/index.html")),console.info("* Changelog: ".concat(Yi,"/en/tutorial-01-info-changelog.html")),console.info("* Report issues: https://github.com/LiteAVSDK/TRTC_Web/issues"),console.info("******************************************************************************")),b.info("TRTC Web SDK Version:",St),b.info("UA:",navigator.userAgent),b.info("URL: ".concat(location.href).concat(((i=self.frameElement)==null?void 0:i.tagName)==="IFRAME"?" in iframe":"")),Eh().then(n=>{n&&b.info(Ht)}));let r=new yc(e,t||{});return Ec.add(r),r}_listenEvents(){ht(this,this._room).add("peer-join",e=>{let{userId:t}=e;this.emit(F.REMOTE_USER_ENTER,{userId:t})}).add("peer-leave",e=>{this.emit(F.REMOTE_USER_EXIT,{userId:e})}).add("banned",e=>{this._exitRoom().then(()=>{this.emit(F.KICKED_OUT,{reason:e.reason})})}).add("error",e=>{this._exitRoom().then(()=>{this.emit(F.ERROR,M.convertFrom(e))})}).add("signal-connection-state-changed",e=>{this.emit(F.CONNECTION_STATE_CHANGED,e)}).add("network-quality",e=>{this._networkQuality=e,this.emit(F.NETWORK_QUALITY,e)}).add("remote-published",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(t=>{ht(t,t).add("player-state-changed",i=>{let r=J(O({},i),{userId:e.userId});t.kind===_.VIDEO&&(r.streamType=_c(t.streamType)),this.emit(t.kind===_.AUDIO?F.AUDIO_PLAY_STATE_CHANGED:F.VIDEO_PLAY_STATE_CHANGED,r)}).add("error",i=>{i.getCode()===C.PLAY_NOT_ALLOWED&&this.emit(F.AUTOPLAY_FAILED,{userId:t.userId})})})}).add("remote-unpublished",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(t=>{Pe(t)})}).add("remote-publish-state-changed",e=>{let{prevMuteState:t,muteState:i}=e,{userId:r}=i,n=t.audioAvailable,s=t.videoAvailable,{audioAvailable:a,videoAvailable:c}=i;a||this._remoteAudioConfigMap.delete(r),c||this._remoteVideoConfigMap.delete("".concat(r,"_","main")),i.hasAuxiliary||this._remoteVideoConfigMap.delete("".concat(r,"_","sub")),n!==a&&(this.emit(a?F.REMOTE_AUDIO_AVAILABLE:F.REMOTE_AUDIO_UNAVAILABLE,{userId:r}),a?this._onAudioAvailable({userId:r}):this._onAudioUnavailable({userId:r,muteState:i})),s!==c&&(this.emit(c?F.REMOTE_VIDEO_AVAILABLE:F.REMOTE_VIDEO_UNAVAILABLE,{userId:r,streamType:"main"}),c?this._onVideoAvailable({userId:r,streamType:"main"}):this._onVideoUnavailable({userId:r,streamType:"main"})),t.hasAuxiliary!==i.hasAuxiliary&&(this.emit(i.hasAuxiliary?F.REMOTE_VIDEO_AVAILABLE:F.REMOTE_VIDEO_UNAVAILABLE,{userId:r,streamType:"sub"}),i.hasAuxiliary?this._onVideoAvailable({userId:r,streamType:"sub"}):this._onVideoUnavailable({userId:r,streamType:"sub"}))}).add("firewall-restriction",()=>{this.emit(F.ERROR,new M({code:V.OPERATION_FAILED,extraCode:5501}))}).add("sei-message",e=>{this.emit(F.SEI_MESSAGE,J(O({},e),{streamType:_c(e.streamType)}))}).add("heartbeat-report",e=>{var t,i,r,n,s,a,c;let o={2:"big",3:"small",7:"sub"},l={rtt:e.msg_up_stream_info.msg_network_status.uint32_rtt||((t=e.msg_down_stream_info[0])==null?void 0:t.msg_network_status.uint32_rtt)||((i=this._networkQuality)==null?void 0:i.uplinkRTT)||((r=this._networkQuality)==null?void 0:r.downlinkRTT)||0,upLoss:((n=this._networkQuality)==null?void 0:n.uplinkLoss)||0,downLoss:((s=this._networkQuality)==null?void 0:s.downlinkLoss)||0,bytesSent:e.bytes_sent||0,bytesReceived:e.bytes_received||0,localStatistics:{audio:{bitrate:(((a=e.msg_up_stream_info.msg_audio_status)==null?void 0:a.uint32_audio_codec_bitrate)||0)/1e3,audioLevel:(((c=e.msg_up_stream_info.msg_audio_status)==null?void 0:c.uint32_audio_level)||0)/_i},video:e.msg_up_stream_info.msg_video_status.filter(d=>o[d.uint32_video_stream_type]).map(d=>({bitrate:(d.uint32_video_codec_bitrate||0)/1e3,width:d.uint32_video_width,height:d.uint32_video_height,frameRate:d.uint32_video_enc_fps,videoType:o[d.uint32_video_stream_type]}))},remoteStatistics:e.msg_down_stream_info.map(d=>({userId:d.msg_user_info.str_identifier,audio:{bitrate:(d.msg_audio_status.uint32_audio_codec_bitrate||0)/1e3,audioLevel:(d.msg_audio_status.uint32_audio_level||0)/_i},video:d.msg_video_status.map(u=>({bitrate:(u.uint32_video_codec_bitrate||0)/1e3,width:u.uint32_video_width,height:u.uint32_video_height,frameRate:u.uint32_video_dec_fps,videoType:o[u.uint32_video_stream_type]}))}))};this.emit(F.STATISTICS,l)}).add("custom-message",e=>{this.emit(F.CUSTOM_MESSAGE,e)}),ht(this,ke).add("audioInputAdded",e=>{this.emit(F.DEVICE_CHANGED,{type:"microphone",action:"add",device:e})}).add("audioInputRemoved",e=>{this.emit(F.DEVICE_CHANGED,{type:"microphone",action:"remove",device:e})}).add("videoInputAdded",e=>{this.emit(F.DEVICE_CHANGED,{type:"camera",action:"add",device:e})}).add("videoInputRemoved",e=>{this.emit(F.DEVICE_CHANGED,{type:"camera",action:"remove",device:e})}).add("audioOutputAdded",e=>g(this,null,function*(){if(this.emit(F.DEVICE_CHANGED,{type:"speaker",action:"add",device:e}),Ne&&Ne.deviceId===Lo){let t=(yield mn()).find(i=>i.deviceId===Lo);t&&Ne.groupId!==t.groupId&&(Ne=t,this.emit(F.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))}})).add("audioOutputRemoved",e=>g(this,null,function*(){this.emit(F.DEVICE_CHANGED,{type:"speaker",action:"remove",device:e});let t=(yield mn())[0];t&&Ne&&(Ne.deviceId===e.deviceId||Ne.deviceId===Lo&&Ne.groupId!==t.groupId)&&(Ne=t,this.emit(F.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))}))}use(e){let t,i;"plugin"in e?(t=e.plugin,i=e.assetsPath):t=e,this._use(t,i||"https://web.sdk.qcloud.com/trtc/webrtc/v5/assets/")}_use(e,t){if(this._plugins.get(e.Name))return void this._log.warn("duplicate install plugin",e.Name);let i=new e(function(r,n,s){return{room:r,assetsPath:s,fileDownloader:nU,innerEmitter:R,constants:xy,environment:iS,utils:yt,eventLogger:de,log:r.getLogger(),errorModule:n,kvStatManager:L,clearStarted(a,c){let o=a.getAlias(),l=ea.instances.get(r);if(l)if(c){let d=l.get(o+c);if(!d)return;d.started=!1}else l.forEach((d,u)=>{u.startsWith(o)&&(d.started=!1)})}}}(this._room,lU,t));this._plugins.set(e.Name,i)}enterRoom(e){return g(this,null,function*(){var t,i;let{scene:r="rtc",enableAutoPlayDialog:n=!0,autoReceiveAudio:s=!0,autoReceiveVideo:a=!1}=e;e.proxy&&(this._room.setProxyServer(e.proxy),!re(e.proxy)&&e.proxy.turnServer&&((i=(t=this._room).setTurnServer)==null||i.call(t,e.proxy.turnServer,e.proxy.iceTransportPolicy))),this._room.enableAutoPlayDialog=n,this._room.autoReceiveAudio=s,this._room.autoReceiveVideo=a,We(e.enableHWEncoder)&&(this._room.enableHWEncoder=e.enableHWEncoder);let c={sdkAppId:e.sdkAppId,userId:e.userId,userSig:e.userSig,privateMapKey:e.privateMapKey||null,latencyLevel:e.latencyLevel,role:e.role==="audience"?21:20,roomId:e.roomId||0,strRoomId:e.strRoomId||"",businessInfo:e.businessInfo||null,streamId:null,userDefineRecordId:e.userDefineRecordId||null,frameWorkType:e.frameWorkType,component:e.component,language:e.language};e.strRoomId&&!e.roomId?this._room.useStringRoomId=!0:this._room.useStringRoomId=!1,yield this._room.join(c,r,yc.frameWorkType),this._checkTrackToPublish(),jv.start()})}exitRoom(){return g(this,null,function*(){return yield this._exitRoom()})}switchRole(e,t){return g(this,null,function*(){t!=null&&t.privateMapKey&&(this._room.privateMapKey=t.privateMapKey),t!=null&&t.latencyLevel&&(this._room.latencyLevel=t.latencyLevel),yield this._room.switchRole(e),e==="anchor"&&this._checkTrackToPublish()})}destroy(){Pe(this),this.removeAllListeners(),this._room.destroy(),Ec.delete(this),Ec.size===0&&jv.destroy(),this._localAudioTrack&&this.stopLocalAudio(),this._localVideoTrack&&this.stopLocalVideo(),this._localScreenTrack&&this.stopScreenShare(),this._plugins.forEach(e=>{var t;return(t=e.destroy)==null?void 0:t.call(e)})}startLocalAudio(){return g(this,arguments,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{publish:!0};return function*(){if(e._localAudioTrack)return void e._log.warn("local audio is already started");let{publish:i=!0,mute:r,option:n}=t,s=new Kt(e._room.audioManager),a={},c={muted:!0};n&&(I(n.microphoneId)?I(n.audioTrack)||(a.customSource=n.audioTrack):a.deviceId=n.microphoneId,n&&ge(n.captureVolume)&&s.setCaptureVolume(n.captureVolume),I(n.profile)||(re(n.profile)?jd[n.profile]&&s.setProfile(jd[n.profile]):s.setProfile(n.profile)),ge(n.earMonitorVolume)&&(c.muted=!(n.earMonitorVolume>0),c.volume=n.earMonitorVolume),I(n.echoCancellation)||(s.profile.echoCancellation=n.echoCancellation),I(n.noiseSuppression)||(s.profile.noiseSuppression=n.noiseSuppression),I(n.autoGainControl)||(s.profile.autoGainControl=n.autoGainControl)),s.on("5",o=>{e.emit(F.ERROR,new M({code:V.DEVICE_ERROR,extraCode:5309,messageParams:{error:o}}))}),s.on("2",o=>{e.emit(F.DEVICE_CHANGED,{type:"microphone",action:"active",device:o})}),s.on("4",o=>{let l;o.error&&(l=M.convertFrom(o.error)),e.emit(F.PUBLISH_STATE_CHANGED,J(O({},o),{error:l}))}),e._listenOutputTrackChanged(s),e._speakerId&&s.setAudioOutput(e._speakerId),yield s.capture(a),I(r)||s.setMute(r),ht(s,s).add("player-state-changed",o=>{e.emit(F.AUDIO_PLAY_STATE_CHANGED,J(O({},o),{userId:""}))}),i&&e._room.isJoined&&e._room.publish(s).catch(()=>{}),e._localAudioTrack=s,e._localAudioConfig=J(O({},t),{publish:i}),yield e._updateAudioPlayOption({playOption:c,track:s})}()})}updateLocalAudio(e){return g(this,null,function*(){if(!this._localAudioTrack||!this._localAudioConfig)return;let{publish:t,mute:i,option:r}=e,n={};r&&(r.microphoneId?yield this._localAudioTrack.switchDevice(r.microphoneId):I(r.audioTrack)||(yield this._localAudioTrack.setInputMediaStreamTrack(r.audioTrack)),I(r.captureVolume)||this._localAudioTrack.setCaptureVolume(r.captureVolume),I(r.earMonitorVolume)||(n.muted=!(r.earMonitorVolume>0),n.volume=r.earMonitorVolume),yield this._localAudioTrack.update3A(r)),this._room.isJoined&&!I(t)&&(t&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch(()=>{}),this._localAudioConfig.publish&&!t&&this._room.unpublish(this._localAudioTrack).catch(()=>{})),I(i)||this._localAudioTrack.setMute(i),yield this._updateAudioPlayOption({playOption:n,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),nr(this._localAudioConfig,e)})}stopLocalAudio(){return g(this,null,function*(){!this._localAudioTrack||(this._room.isJoined&&(yield this._room.unpublish(this._localAudioTrack).catch(()=>{})),this._localAudioTrack.stop(),this._localAudioTrack.close(),this._room.audioManager.removeInput(this._localAudioTrack),Pe(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null)})}startLocalVideo(){return g(this,arguments,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{publish:!0,view:null};return function*(){if(e._localVideoTrack)return void e._log.warn("local video is already started");let{view:i,publish:r=!0,mute:n,option:s}=t,a=new Je(e._room.videoManager),c={},o={};if(s&&(s.cameraId?c.deviceId=s.cameraId:I(s.useFrontCamera)?I(s.videoTrack)||(c.customSource=s.videoTrack):c.facingMode=s.useFrontCamera?_.FACING_MODE_USER:_.FACING_MODE_ENVIRONMENT,I(s.profile)||(re(s.profile)?vt[s.profile]&&a.setProfile(vt[s.profile]):a.setProfile(s.profile)),I(s.fillMode)||(o.objectFit=s.fillMode),I(s.mirror)||(o.mirror=s.mirror),I(s.small)||(tc()?re(s.small)?a.small=vt[s.small]:s.small===!0?a.small=vt["120p"]:a.small=s.small:e._log.warn("small stream is not supported"))),a.on("5",l=>{e.emit(F.ERROR,new M({code:V.DEVICE_ERROR,extraCode:5308,messageParams:{error:l}}))}),a.on("2",l=>{e.emit(F.DEVICE_CHANGED,{type:"camera",action:"active",device:l})}),a.on("4",l=>{let d;l.error&&(d=M.convertFrom(l.error)),e.emit(F.PUBLISH_STATE_CHANGED,J(O({},l),{error:d}))}),e._listenOutputTrackChanged(a),yield a.capture(c),I(n)||(yield a.setMute(n)),a.mediaTrack)if(s!=null&&s.qosPreference){let l=yn(s.qosPreference);a.mediaTrack.contentHint=l}else s!=null&&s.videoTrack||(a.mediaTrack.contentHint=yn(Yt.QOS_PREFERENCE_SMOOTH));ht(a,a).add("player-state-changed",l=>{e.emit(F.VIDEO_PLAY_STATE_CHANGED,J(O({},l),{userId:"",streamType:"main"}))}),r&&e._room.isJoined&&e._room.publish(a).catch(()=>{}),e._localVideoTrack=a,e._localVideoConfig=J(O({},t),{view:i,publish:r}),yield e._updateVideoPlayOption({view:i,playOption:o,track:a})}()})}updateLocalVideo(e){return g(this,null,function*(){if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:t,publish:i,mute:r,option:n}=e,s={};if(n){if(I(n.profile)||(re(n.profile)?vt[n.profile]&&this._localVideoTrack.setProfile(vt[n.profile]):this._localVideoTrack.setProfile(n.profile),(!n.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(n.cameraId))&&I(n.useFrontCamera)&&this._localVideoTrack.applyProfile()),n.cameraId?yield this._localVideoTrack.switchDevice(n.cameraId):I(n.useFrontCamera)?I(n.videoTrack)||(yield this._localVideoTrack.setInputMediaStreamTrack(n.videoTrack)):yield this._localVideoTrack.switchDevice(n.useFrontCamera?_.FACING_MODE_USER:_.FACING_MODE_ENVIRONMENT),I(n.fillMode)||(s.objectFit=n.fillMode),I(n.mirror)||(s.mirror=n.mirror),n.qosPreference&&this._localVideoTrack.mediaTrack){let a=yn(n.qosPreference);this._localVideoTrack.mediaTrack.contentHint=a}if(n.small){let a=!this._localVideoTrack.small;tc()?(n.small===!0?this._localVideoTrack.small=vt["120p"]:re(n.small)?this._localVideoTrack.small=vt[n.small]:this._localVideoTrack.small=n.small,this._room.videoManager.update(),a&&this._room.enableSmall(!0)):this._log.warn("small stream is not supported")}else n.small===!1&&this._localVideoTrack.small&&(delete this._localVideoTrack.small,this._room.videoManager.update(),this._room.enableSmall(!1))}this._room.isJoined&&!I(i)&&(i&&!this._localVideoConfig.publish&&this._room.publish(this._localVideoTrack).catch(()=>{}),this._localVideoConfig.publish&&!i&&this._room.unpublish(this._localVideoTrack).catch(()=>{})),I(r)||(yield this._localVideoTrack.setMute(r)),yield this._updateVideoPlayOption({view:t,playOption:s,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),nr(this._localVideoConfig,e)})}stopLocalVideo(){return g(this,null,function*(){!this._localVideoTrack||(this._room.isJoined&&(yield this._room.unpublish(this._localVideoTrack).catch(()=>{})),this._localVideoTrack.stop(),this._localVideoTrack.close(),Pe(this._localVideoTrack),this._localVideoTrack=null,this._localVideoConfig=null)})}startScreenShare(){return g(this,arguments,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{publish:!0,view:null};return function*(){if(e._localScreenTrack)return void e._log.warn("screen share is already started");let{view:i=null,publish:r=!0,option:n}=t,s=new dr(e._room.videoManager);s.on("4",d=>{let u;d.error&&(u=M.convertFrom(d.error)),e.emit(F.PUBLISH_STATE_CHANGED,J(O({},d),{error:u}))}),e._listenOutputTrackChanged(s);let a=null,c={},o={};n&&(I(n.profile)||(re(n.profile)?Gd[n.profile]&&s.setProfile(Gd[n.profile]):s.setProfile(n.profile)),n.systemAudio&&(c.systemAudio=!0,c.echoCancellation=n.echoCancellation,c.noiseSuppression=n.noiseSuppression,c.autoGainControl=n.autoGainControl),I(n.fillMode)||(o.objectFit=n.fillMode),n.videoTrack&&(c.videoTrack=n.videoTrack),n.audioTrack&&(c.audioTrack=n.audioTrack),n.captureElement&&(c.captureElement=n.captureElement),n.preferDisplaySurface&&(c.preferDisplaySurface=n.preferDisplaySurface));let l=yield s.capture(c);if(n!=null&&n.qosPreference){let d=yn(n.qosPreference);s.mediaTrack.contentHint=d}else n!=null&&n.videoTrack||(s.mediaTrack.contentHint=yn(Yt.QOS_PREFERENCE_CLEAR));if(s.mediaTrack.addEventListener(_.ENDED,()=>{e._stopScreenShare(),e.emit(F.SCREEN_SHARE_STOPPED)}),l.getAudioTracks()[0]&&(a=new qs(e._room.audioManager),a.setInputMediaStreamTrack(l.getAudioTracks()[0]),e._speakerId&&a.setAudioOutput(e._speakerId)),ht(s,s).add("player-state-changed",d=>{e.emit(F.VIDEO_PLAY_STATE_CHANGED,J(O({},d),{userId:"",streamType:"sub"}))}),r&&e._room.isJoined){let d=[s];a&&d.push(a),e._room.publish(...d).catch(()=>{})}e._localScreenTrack=s,e._localScreenAudioTrack=a,e._localScreenConfig=J(O({},t),{view:i,publish:r}),yield e._updateVideoPlayOption({view:i,playOption:o,track:s})}()})}updateScreenShare(e){return g(this,null,function*(){if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:t,publish:i,option:r}=e,n={};if(r&&(I(r.fillMode)||(n.objectFit=r.fillMode),r.qosPreference)){let s=yn(r.qosPreference);this._localScreenTrack.mediaTrack.contentHint=s}this._room.isJoined&&!I(i)&&(i&&!this._localScreenConfig.publish&&(this._room.publish(this._localScreenTrack).catch(()=>{}),this._localScreenAudioTrack&&this._room.publish(this._localScreenAudioTrack).catch(()=>{})),this._localScreenConfig.publish&&!i&&(this._room.unpublish(this._localScreenTrack).catch(()=>{}),this._localScreenAudioTrack&&this._room.unpublish(this._localScreenAudioTrack).catch(()=>{}))),yield this._updateVideoPlayOption({view:t,playOption:n,track:this._localScreenTrack,prevConfig:this._localScreenConfig}),nr(this._localScreenConfig,e)})}stopScreenShare(){return g(this,null,function*(){return yield this._stopScreenShare()})}startRemoteVideo(e){return g(this,null,function*(){let{view:t,userId:i,streamType:r,option:n}=e,s="".concat(i,"_").concat(r);if(this._remoteVideoConfigMap.has(s))return void this._log.warn("remote video has already started. userId:".concat(i,", streamType:").concat(r));let a=this._room.remotePublishedUserMap.get(i);if(!a)return;let c={},o=r==="main"?a.remoteVideoTrack:a.remoteAuxiliaryTrack;this._listenOutputTrackChanged(o),n&&(I(n.fillMode)||(c.objectFit=n.fillMode),I(n.mirror)||(c.mirror=n.mirror),c.canvasRender=n.canvasRender,r==="main"&&!I(n.small)&&(a.remoteVideoTrack.setMediaType(n.small?8:4),this._room.changeType(n.small,o.user))),yield this._room.subscribe(o),yield this._updateVideoPlayOption({view:t,playOption:c,track:o}),this._emitTrackEvent(o),this._remoteVideoConfigMap.set(s,{config:e}),n&&!I(n.receiveWhenViewVisible)&&this._observeView({remoteTrack:o,view:t,receiveWhenViewVisible:n.receiveWhenViewVisible,viewRoot:n==null?void 0:n.viewRoot})})}updateRemoteVideo(e){return g(this,null,function*(){var t,i;let{view:r,userId:n,streamType:s,option:a}=e,c="".concat(n,"_").concat(s),o=this._remoteVideoConfigMap.get(c);if(!o||!this._room.remotePublishedUserMap.has(n))return;let l={};a&&(I(a.fillMode)||(l.objectFit=a.fillMode),I(a.mirror)||(l.mirror=a.mirror));let d=null,u=this._room.remotePublishedUserMap.get(n);if(s==="main"&&(u!=null&&u.muteState.hasVideo)&&(d=u.remoteVideoTrack),s==="sub"&&(u!=null&&u.muteState.hasAuxiliary)&&(d=u.remoteAuxiliaryTrack),!d)return;let{config:p}=o;s==="main"&&a&&!I(a.small)&&this._room.changeType(a.small,d.user),yield this._updateVideoPlayOption({view:r,playOption:l,track:d,prevConfig:p}),nr(p,e);let m=I(a==null?void 0:a.receiveWhenViewVisible)?(t=p.option)==null?void 0:t.receiveWhenViewVisible:a.receiveWhenViewVisible,f=I(r)?p.view:r,T=I(a==null?void 0:a.viewRoot)?(i=p.option)==null?void 0:i.viewRoot:a.viewRoot;this._observeView({remoteTrack:d,view:f,receiveWhenViewVisible:m,viewRoot:T})})}stopRemoteVideo(e){return g(this,null,function*(){return this._stopRemoteVideo(e)})}_stopRemoteVideo(e){let t=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];return g(this,null,function*(){let i=[],r=this._room.remotePublishedUserMap.get(e.userId);if(r){let{muteState:s,remoteVideoTrack:a,remoteAuxiliaryTrack:c}=r;e.streamType==="main"&&(a.stop(),s.hasVideo&&i.push(a)),e.streamType==="sub"&&(c.stop(),s.hasAuxiliary&&i.push(c))}for(let s of i)t&&(yield this._room.unsubscribe(s),this._mediaTrackMap.get(s.outMediaTrack)===s.userId&&this._mediaTrackMap.delete(s.outMediaTrack));let n=this._remoteVideoConfigMap.get("".concat(e.userId,"_").concat(e.streamType));n&&n.observer&&n.observer.disconnect(),this._remoteVideoConfigMap.delete("".concat(e.userId,"_").concat(e.streamType))})}muteRemoteAudio(e,t){return g(this,null,function*(){if(e==="*")if(t)yield this._stopRemoteAudio({userId:e});else{let i=[...this._room.remotePublishedUserMap.values()];for(let r of i)r.muteState.hasAudio&&!this._remoteAudioConfigMap.has(r.userId)&&(yield this._startRemoteAudio({userId:r.userId}))}else t?yield this._stopRemoteAudio({userId:e}):this._remoteAudioConfigMap.has(e)||(yield this._startRemoteAudio({userId:e}));this._remoteAudioMuteMap.set(e,t)})}setRemoteAudioVolume(e,t){if(e==="*"){let i=[...this._room.remotePublishedUserMap.values()];for(let r of i)this._updateAudioPlayOption({playOption:{volume:t},track:r.remoteAudioTrack})}else if(e){let i=this._room.remotePublishedUserMap.get(e);i&&this._updateAudioPlayOption({playOption:{volume:t},track:i.remoteAudioTrack})}}startPlugin(e,t){return g(this,null,function*(){return e.start(t)})}updatePlugin(e,t){return g(this,null,function*(){return e.update(t)})}stopPlugin(e,t){return g(this,null,function*(){return e.stop(t)})}enableAudioVolumeEvaluation(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:2e3,t=arguments.length>1&&arguments[1]!==void 0&&arguments[1];this._room.enableAudioVolumeEvaluation(e,t)}on(e,t,i){return this.listeners(e).includes(t)||(this._log.debug("on",e),super.on(e,t,i),this._eventListened.add(e)),this}off(e,t,i){return this._log.debug("off",e),e==="*"?(this._eventListened.clear(),this.removeAllListeners()):super.off(e,t,i),this}getAudioTrack(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{userId:"",streamType:"main"};var t,i;let r,n="main";if(re(e)?r=e:(r=e.userId,e.streamType&&(n=e.streamType)),!r)return n==="sub"?((t=this._localScreenAudioTrack)==null?void 0:t.mediaTrack)||null:((i=this._localAudioTrack)==null?void 0:i.mediaTrack)||null;{let s=this._room.remotePublishedUserMap.get(r);if(s)return s.remoteAudioTrack.mediaTrack}return null}getVideoTrack(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{userId:"",streamType:"main"},{userId:t="",streamType:i="main"}=e;if(t===""){if(i==="main"&&this._localVideoTrack)return this._localVideoTrack.mediaTrack;if(i==="sub"&&this._localScreenTrack)return this._localScreenTrack.mediaTrack}else{let r=this._room.remotePublishedUserMap.get(t);if(r)return i==="main"?r.remoteVideoTrack.mediaTrack:r.remoteAuxiliaryTrack.mediaTrack}return null}getVideoSnapshot(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},{userId:t,streamType:i="main"}=e;if(t){let r=this._room.remotePublishedUserMap.get(t);if(i==="main"&&(r!=null&&r.muteState.hasVideo))return r.remoteVideoTrack.getVideoFrame();if(i==="sub"&&(r!=null&&r.muteState.hasAuxiliary))return r.remoteAuxiliaryTrack.getVideoFrame()}else{if(i==="main"&&this._localVideoTrack)return this._localVideoTrack.getVideoFrame();if(i==="sub"&&this._localScreenTrack)return this._localScreenTrack.getVideoFrame()}return""}setCurrentSpeaker(e){var t,i;this._speakerId=e,(t=this._localAudioTrack)==null||t.setAudioOutput(e),(i=this._localScreenAudioTrack)==null||i.setAudioOutput(e),this._room.remotePublishedUserMap.forEach(r=>r.remoteAudioTrack.setAudioOutput(e))}_startRemoteAudio(e){return this._doStartRemoteAudio(e)}_doStartRemoteAudio(e){return g(this,null,function*(){let{userId:t,option:i}=e;if(this._remoteAudioConfigMap.has(t))return void this._log.warn("remote audio has already started. userId:".concat(t));let r=this._room.remotePublishedUserMap.get(t);if(!r)return;let n={};i&&(I(i.volume)||(n.volume=i.volume));let s=r.remoteAudioTrack;this._listenOutputTrackChanged(s),this._speakerId&&s.setAudioOutput(this._speakerId);try{this._remoteAudioConfigMap.set(t,e),yield this._room.subscribe(s),yield this._updateAudioPlayOption({playOption:n,track:s})}catch(a){throw this._remoteAudioConfigMap.delete(t),a}this._emitTrackEvent(s)})}_stopRemoteAudio(e){let t=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];return g(this,null,function*(){let i=this._room.remotePublishedUserMap.get(e.userId);i&&(i.remoteAudioTrack.stop(),i.muteState.hasAudio&&t&&(yield this._room.unsubscribe(i.remoteAudioTrack)),this._mediaTrackMap.get(i.remoteAudioTrack.outMediaTrack)===e.userId&&this._mediaTrackMap.delete(i.remoteAudioTrack.outMediaTrack)),this._remoteAudioConfigMap.delete("".concat(e.userId))})}_updateVideoPlayOption(e){return g(this,arguments,function(t){let{view:i,playOption:r,track:n,prevConfig:s}=t;return function*(){if(n.setMirror(r.mirror),I(i)&&s&&s.view&&!NS(r)){let a=$o(s.view);a.length>0&&(yield n.play(a,r))}if(!I(i)){let a=$o(i);a.length>0?yield n.play(a,r):n.stop()}}()})}_updateAudioPlayOption(e){return g(this,arguments,function(t){let{playOption:i={},track:r,prevConfig:n}=t;return function*(){if(!r.isPlayCalled)try{yield r.play(null,i)}catch{}I(i.muted)||r.setPlayerMute(i.muted),I(i.volume)||r.setAudioVolume(i.volume/100)}()})}_listenOutputTrackChanged(e){e.listeners("output-media-track-changed").length===0&&e.on("output-media-track-changed",()=>this._emitTrackEvent(e,!1))}_emitTrackEvent(e){let t=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1],i=e.isRemote?e.userId:"";!e.outMediaTrack||t&&this._mediaTrackMap.get(e.outMediaTrack)===i||(this._mediaTrackMap.set(e.outMediaTrack,i),this.emit(F.TRACK,{userId:i,streamType:_c(e.streamType),track:e.outMediaTrack}))}_checkTrackToPublish(){var e,t,i;let r=[];if((e=this._localAudioConfig)!=null&&e.publish&&this._localAudioTrack&&r.push(this._localAudioTrack),(t=this._localVideoConfig)!=null&&t.publish&&this._localVideoTrack&&r.push(this._localVideoTrack),(i=this._localScreenConfig)!=null&&i.publish&&(this._localScreenTrack&&r.push(this._localScreenTrack),this._localScreenAudioTrack&&r.push(this._localScreenAudioTrack)),r.length!==0)return this._room.publish(...r).catch(()=>{})}_observeView(e){let{remoteTrack:t,view:i,receiveWhenViewVisible:r=!1,viewRoot:n}=e;if(I(i))return;let s=this._remoteVideoConfigMap.get("".concat(t.userId,"_").concat(_c(t.streamType)));if(!s)return;let a=s.observer||void 0;if(i===null||Ce(i)&&i.length===0||!r)return a==null||a.disconnect(),void(t.isSubscribed||this._room.subscribe(t).catch(()=>{}));let c=s.visibleViewMap||new Map,o=-1;(!a||a.root!==n)&&(a==null||a.disconnect(),c.clear(),a=new IntersectionObserver(d=>{d.forEach(u=>{c.set(u.target,u.isIntersecting)}),clearTimeout(o),o=window.setTimeout(()=>{[...c.values()].find(u=>u)?t.isSubscribed||this._room.subscribe(t).catch(()=>{}):t.isSubscribed&&this._room.unsubscribe(t).catch(()=>{})},200)},{root:n}));let l=new Set($o(i));c.forEach((d,u)=>{l.has(u)||(a.unobserve(u),c.delete(u))}),l.forEach(d=>{c.set(d,!0),a.observe(d)}),a.takeRecords().forEach(d=>{c.set(d.target,d.isIntersecting)}),s.visibleViewMap=c,s.observer=a}_exitRoom(){return g(this,null,function*(){this._room.isJoined&&(yield this._room.leave()),new Set([...this._remoteAudioConfigMap.keys(),...this._remoteAudioMuteMap.keys()]).forEach(e=>{this._stopRemoteAudio({userId:e}).catch()}),[...this._remoteVideoConfigMap.keys()].forEach(e=>{let t=e.includes("main")?"main":"sub",i=e.split("_".concat(t))[0];i&&this._stopRemoteVideo({userId:i,streamType:t}).catch()}),this._remoteVideoConfigMap.clear(),this._remoteAudioConfigMap.clear(),this._remoteAudioMuteMap.clear(),this._room.remotePublishedUserMap.forEach(e=>{Pe(e.remoteAudioTrack),Pe(e.remoteVideoTrack),Pe(e.remoteAuxiliaryTrack)})})}_stopScreenShare(){return g(this,null,function*(){var e;if(this._localScreenTrack){if(this._room.isJoined){let t=[this._localScreenTrack];this._localScreenAudioTrack&&t.push(this._localScreenAudioTrack),yield(e=this._room)==null?void 0:e.unpublish(...t).catch(()=>{})}this._localScreenTrack.stop(),this._localScreenTrack.close(),this._localScreenAudioTrack&&(this._localScreenAudioTrack.stop(),this._localScreenAudioTrack.close(),this._room.audioManager.removeInput(this._localScreenAudioTrack),this._localScreenAudioTrack=null),Pe(this._localScreenTrack),this._localScreenTrack=null,this._localScreenConfig=null}})}_initActiveSpeaker(){return g(this,null,function*(){if(Ne&&!Js(Ne))this.emit(F.DEVICE_CHANGED,{type:"speaker",action:"active",device:Ne});else{let e=yield mn();if(e[0]&&!Js(e[0]))Ne=e[0],this.emit(F.DEVICE_CHANGED,{type:"speaker",action:"active",device:e[0]});else{let t=i=>{let{track:r}=i;r.kind==="audio"&&(!Ne||Js(Ne))&&(this._initActiveSpeaker(),R.off("102",this._initActiveSpeaker))};R.on("102",t)}}})}_onAudioAvailable(e){let{userId:t}=e,i=this._remoteAudioMuteMap.has(t)?this._remoteAudioMuteMap.get(t):this._remoteAudioMuteMap.get("*");(i===!1||this._room.autoReceiveAudio&&!i)&&this._doStartRemoteAudio({userId:t}).catch(()=>{})}_onVideoAvailable(e){let{userId:t,streamType:i}=e;if(!this._room.autoReceiveVideo)return;let r=this._room.remotePublishedUserMap.get(t);if(r){let n=i==="main"?r.remoteVideoTrack:r.remoteAuxiliaryTrack;this._room.subscribe(n).then(()=>{this._emitTrackEvent(n)}).catch(()=>{})}}_onAudioUnavailable(e){let{userId:t,muteState:i}=e;i.hasAudio&&i.audioMuted||this._stopRemoteAudio({userId:t},!1).catch(()=>{})}_onVideoUnavailable(e){let{userId:t,streamType:i}=e;this._stopRemoteVideo({userId:t,streamType:i},!1).catch(()=>{})}sendSEIMessage(e,t){this._room.sendSEI(e,t||{seiPayloadType:243}),L.addCount({key:5e5,useUV:!0})}sendCustomMessage(e){var t,i;(i=(t=this._room).sendCustomMessage)==null||i.call(t,e),L.addCount({key:500001,useUV:!0})}static setLogLevel(e,t){b.setLogLevel(e),I(t)||(t?b.enableUploadLog():b.disableUploadLog())}static isSupported(){return Lh()}static getCameraList(){return Ai(!(arguments.length>0&&arguments[0]!==void 0)||arguments[0])}static getMicrophoneList(){return zt(!(arguments.length>0&&arguments[0]!==void 0)||arguments[0])}static getSpeakerList(){return mn(!(arguments.length>0&&arguments[0]!==void 0)||arguments[0])}static setCurrentSpeaker(e){return g(this,null,function*(){(yield mn()).forEach(t=>{t.deviceId===e&&(Ec.forEach(i=>{i.setCurrentSpeaker(e),i.emit(F.DEVICE_CHANGED,{type:"speaker",action:"active",device:t})}),Ne=t)})})}static _addKVStat(e){let{type:t,key:i,value:r,base:n,useUV:s,version:a}=e;switch(a&&(Ws.version=a),t){case"count":Ws.addCount({key:i,useUV:s});break;case"enum":Ws.addEnum({key:i,value:r,useUV:s});break;case"number":Ws.addNumber({key:i,value:r,split:n})}}},z=yc;h(z,"_loggerManager",b),h(z,"EVENT",F),h(z,"ERROR_CODE",V),h(z,"TYPE",Yt),h(z,"frameWorkType",30),k([oe({replaceArg:e=>({argIndex:0,value:{name:"plugin"in e?e.plugin.Name:e.Name,assetsPath:"assetsPath"in e?e==null?void 0:e.assetsPath:"default"}})})],z.prototype,"use"),k([Le(Ae.TRTC.enterRoom),mr("room",(e,t)=>{let[i]=e,[r]=t;return(i.roomId||i.strRoomId)===(r.roomId||r.strRoomId)&&i.userId===r.userId&&i.sdkAppId===r.sdkAppId}),ae(e=>function(t){return this._log.setUserId(t.userId),this._log.setSdkAppId(t.sdkAppId),e.call(this,t)}),oe()],z.prototype,"enterRoom"),k([oe()],z.prototype,"exitRoom"),k([Le(Ae.TRTC.switchRole),En("room",{merge:(e,t)=>t}),oe()],z.prototype,"switchRole"),k([oe()],z.prototype,"destroy"),k([Le(Ae.TRTC.startLocalAudio),mr("audio",(e,t)=>{let[i]=e,[r]=t;var n,s;return((n=i==null?void 0:i.option)==null?void 0:n.microphoneId)===((s=r==null?void 0:r.option)==null?void 0:s.microphoneId)}),oe()],z.prototype,"startLocalAudio"),k([Le(Ae.TRTC.updateLocalAudio),En("audio",{debounce:{delay:200,getKey:()=>"".concat(Gv,"-localAudio"),isNeedToDebounce:e=>{var t;return!I((t=e.option)==null?void 0:t.captureVolume)}}}),oe()],z.prototype,"updateLocalAudio"),k([_r("audio"),oe()],z.prototype,"stopLocalAudio"),k([Le(Ae.TRTC.startLocalVideo),mr("video",(e,t)=>{let[i]=e,[r]=t;var n,s;return((n=i==null?void 0:i.option)==null?void 0:n.cameraId)===((s=r==null?void 0:r.option)==null?void 0:s.cameraId)}),oe()],z.prototype,"startLocalVideo"),k([Le(Ae.TRTC.updateLocalVideo),En("video"),oe()],z.prototype,"updateLocalVideo"),k([_r("video"),oe()],z.prototype,"stopLocalVideo"),k([Le(Ae.TRTC.startScreenShare),mr("screen",()=>!0),oe()],z.prototype,"startScreenShare"),k([Le(Ae.TRTC.updateScreenShare),En("screen"),oe()],z.prototype,"updateScreenShare"),k([oe()],z.prototype,"stopScreenShare"),k([Le(Ae.TRTC.startRemoteVideo),mr(e=>"v".concat(e.userId).concat(e.streamType),()=>!0),oe({getRemoteId:e=>"".concat(e.userId,"_").concat(e.streamType)})],z.prototype,"startRemoteVideo"),k([Le(Ae.TRTC.updateRemoteVideo),En(e=>"v".concat(e.userId).concat(e.streamType)),oe({getRemoteId:e=>"".concat(e.userId,"_").concat(e.streamType)})],z.prototype,"updateRemoteVideo"),k([Le(Ae.TRTC.stopRemoteVideo),ae(e=>function(t){return g(this,null,function*(){if(t.userId==="*"){let i=[];return this._room.remotePublishedUserMap.forEach(r=>{this._remoteVideoConfigMap.has("".concat(r.userId,"_","main"))&&i.push(this.stopRemoteVideo({streamType:"main",userId:r.userId}).catch(()=>{})),this._remoteVideoConfigMap.has("".concat(r.userId,"_","sub"))&&i.push(this.stopRemoteVideo({streamType:"sub",userId:r.userId}).catch(()=>{}))}),Promise.all(i)}return e.call(this,t)})}),oe({getRemoteId:e=>"".concat(e.userId,"_").concat(e.streamType)})],z.prototype,"stopRemoteVideo"),k([_r(e=>"v".concat(e.userId).concat(e.streamType))],z.prototype,"_stopRemoteVideo"),k([Le(...Ae.TRTC.muteRemoteAudio),oe({getRemoteId:e=>e})],z.prototype,"muteRemoteAudio"),k([Bv(...Ae.TRTC.setRemoteAudioVolume),function(e,t){return ae((i,r)=>function(){for(var n=arguments.length,s=new Array(n),a=0;a<n;a++)s[a]=arguments[a];var c,o;let l=(c=fc.get(this))==null?void 0:c.get(t(...s));l&&l>0&&clearTimeout(l);let d=window.setTimeout(()=>{i.apply(this,s)},e);fc.has(this)?(o=fc.get(this))==null||o.set(t(...s),d):fc.set(this,new Map([[t(...s),d]]))})}(200,e=>e),oe({getRemoteId:e=>e})],z.prototype,"setRemoteAudioVolume"),k([lp("start"),mr((e,t)=>e.getAlias()+e.getGroup(t)),oe({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>$S[e.getName()]})],z.prototype,"startPlugin"),k([lp("update"),En((e,t)=>e.getAlias()+e.getGroup(t)),oe({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>ZS[e.getName()]})],z.prototype,"updatePlugin"),k([lp("stop"),_r((e,t)=>e.getAlias()+e.getGroup(t)),oe({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>ev[e.getName()]})],z.prototype,"stopPlugin"),k([Bv(...Ae.TRTC.enableAudioVolumeEvaluation)],z.prototype,"enableAudioVolumeEvaluation"),k([oe()],z.prototype,"getVideoSnapshot"),k([oe()],z.prototype,"setCurrentSpeaker"),k([mr(e=>"a".concat(e.userId),()=>!0)],z.prototype,"_startRemoteAudio"),k([ae(e=>function(t){return g(this,null,function*(){return t.userId==="*"?Promise.all([...this._room.remotePublishedUserMap.values()].map(i=>this._stopRemoteAudio(J(O({},t),{userId:i.userId})).catch(()=>{}))):e.call(this,t)})}),_r(e=>"a".concat(e.userId))],z.prototype,"_stopRemoteAudio"),k([_r("room")],z.prototype,"_exitRoom"),k([_r("screen")],z.prototype,"_stopScreenShare"),k([Le(...Ae.TRTC.sendSEIMessage),wv({timesInSecond:30,maxSizeInSecond:8e3,getSize:function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return t[0].byteLength}})],z.prototype,"sendSEIMessage"),k([Le(Ae.TRTC.sendCustomMessage),wv({timesInSecond:30,maxSizeInSecond:8e3,getSize:e=>e.data.byteLength})],z.prototype,"sendCustomMessage"),k([Le(Ae.TRTC.create)],z,"_create");var Sc=z,uU=class{constructor(){this._set=new Set,R.on(A.LEAVE_SUCCESS,this.delete,this)}add(e){let{room:t,roomId:i}=e;if(t.scene==="rtc")return;let r=this.getKey(t.userId,i||t.roomId,t.sdkAppId,t.useStringRoomId);this._set.add(r)}delete(e){let{room:t,roomId:i}=e;if(t.scene==="rtc")return;let r=this.getKey(t.userId,t.roomId||i,t.sdkAppId,t.useStringRoomId);this._set.delete(r)}getKey(e,t,i,r){return"".concat(i,"_").concat(t,"_").concat(e,"_").concat(r)}isJoined(e){let{userId:t,roomId:i,sdkAppId:r,room:n}=e;return n.scene!=="rtc"&&this._set.has(this.getKey(t,i,r,n.useStringRoomId))}};function dU(){return g(this,null,function*(){let e,t;try{let u=yield zt();e=u&&u.length}catch{}try{let u=yield Ai();t=u&&u.length}catch{}let i={microphone:e,camera:t},{isH264EncodeSupported:r,isVp8EncodeSupported:n,isH264DecodeSupported:s,isVp8DecodeSupported:a}=this.checkSystemResult.detail,c=Vs.basis(),o={webRTC:c.isWebRTCSupported,getUserMedia:c.isGetUserMediaSupported,webSocket:c.isWebSocketsSupported,screenShare:c.isScreenShareSupported,webAudio:c.isWebAudioSupported,h264Encode:r,h264Decode:s,vp8Encode:n,vp8Decode:a},l={browser:c.browser,os:c.os,trtc:o,devices:i},d={isWebCodecSupported:c.isWebCodecSupported,isMediaSessionSupported:c.isMediaSessionSupported,isWebTransportSupported:c.isWebTransportSupported};de.uploadEvent({log:"trtcstats-".concat(JSON.stringify(l)),userId:this.userId}),this._log.info("TrtcStats-".concat(JSON.stringify(l))),de.uploadEvent({log:"trtcadvancedstats-".concat(JSON.stringify(d)),userId:this.userId})})}var hU=Ie(Ve(),1),Wv=Symbol("instance"),hp=Symbol("cacheResult"),vc=class{constructor(e,t,i){this.oldState=e,this.newState=t,this.action=i,this.aborted=!1}abort(e){this.aborted=!0,sa.call(e,this.oldState,new Error("action '".concat(this.action,"' aborted")))}toString(){return"".concat(this.action,"ing")}},pp=class extends Error{constructor(e,t,i){super(t),this.state=e,this.message=t,this.cause=i}},na=new Map;function Jv(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return(r,n,s)=>{let a=i.action||n;if(!i.context){let o=na.get(r)||[];na.has(r)||na.set(r,o),o.push({from:e,to:t,action:a})}let c=s.value;s.value=function(){let o=this;for(var l=arguments.length,d=new Array(l),u=0;u<l;u++)d[u]=arguments[u];if(i.context&&(o=he.get(typeof i.context=="function"?i.context.call(this,...d):i.context)),o.state===t)return o[hp];o.state instanceof vc&&o.state.action==i.abortAction&&o.state.abort(o);let p=null;if(Array.isArray(e)?e.length==0?o.state instanceof vc&&o.state.abort(o):(typeof o.state!="string"||!e.includes(o.state))&&(p=new pp(o._state,"".concat(o.name," ").concat(a," to ").concat(t," failed: current state ").concat(o._state," not in from config"))):e!==o.state&&(p=new pp(o._state,"".concat(o.name," ").concat(a," to ").concat(t," failed: current state ").concat(o._state," not from ").concat(e))),p){if(!i.fail){if(i.ignoreError)return p;throw p}i.fail.call(this,p)}let m=o.state,f=new vc(m,t,a);sa.call(o,f);let T=y=>{var E;return o[hp]=y,f.aborted||(sa.call(o,t),(E=i.success)===null||E===void 0||E.call(this,o[hp])),y},S=y=>{let E=y instanceof Error?y.message:String(y);if(sa.call(o,m,y),!i.fail){if(i.ignoreError)return y;throw y}i.fail.call(this,new pp(o._state,"action '".concat(a,"' failed :").concat(E),y instanceof Error?y:new Error(E)))};try{let y=c.apply(this,d);return function(E){return typeof E=="object"&&E&&"then"in E}(y)?y.then(T).catch(S):T(y)}catch(y){S(y)}}}}var pU=typeof window<"u"&&window.__AFSM__?(e,t)=>{window.dispatchEvent(new CustomEvent(e,{detail:t}))}:typeof importScripts<"u"?(e,t)=>{postMessage({type:e,payload:t})}:()=>{};function sa(e,t){let i=this._state;this._state=e;let r=e.toString();e&&this.emit(r,i),this.emit(he.STATECHANGED,e,i,t),this.updateDevTools({value:e,old:i,err:t instanceof Error?t.message:String(t)})}var he=class extends hU.default{constructor(e,t,i){super(),this.name=e,this.groupName=t,this._state=he.INIT,e||(e=Date.now().toString(36)),i?Object.setPrototypeOf(this,i):i=Object.getPrototypeOf(this),t||(this.groupName=this.constructor.name);let r=i[Wv];r?this.name=r.name+"-"+r.count++:i[Wv]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let e=Object.getPrototypeOf(this),t=na.get(e)||[],i=new Set,r=[],n=[],s=new Set,a=Object.getPrototypeOf(e);na.has(a)&&(a.stateDiagram.forEach(o=>i.add(o)),a.allStates.forEach(o=>s.add(o))),t.forEach(o=>{let{from:l,to:d,action:u}=o;typeof l=="string"?r.push({from:l,to:d,action:u}):l.length?l.forEach(p=>{r.push({from:p,to:d,action:u})}):n.push({to:d,action:u})}),r.forEach(o=>{let{from:l,to:d,action:u}=o;s.add(l),s.add(d),s.add(u+"ing"),i.add("".concat(l," --> ").concat(u,"ing : ").concat(u)),i.add("".concat(u,"ing --> ").concat(d," : ").concat(u," 🟢")),i.add("".concat(u,"ing --> ").concat(l," : ").concat(u," 🔴"))}),n.forEach(o=>{let{to:l,action:d}=o;i.add("".concat(d,"ing --> ").concat(l," : ").concat(d," 🟢")),s.forEach(u=>{u!==l&&i.add("".concat(u," --> ").concat(d,"ing : ").concat(d))})});let c=[...i];return Object.defineProperties(e,{stateDiagram:{value:c},allStates:{value:s}}),c}static get(e){let t;return typeof e=="string"?(t=he.instances.get(e),t||he.instances.set(e,t=new he(e,void 0,Object.create(he.prototype)))):(t=he.instances2.get(e),t||he.instances2.set(e,t=new he(e.constructor.name,void 0,Object.create(he.prototype)))),t}static getState(e){var t;return(t=he.get(e))===null||t===void 0?void 0:t.state}updateDevTools(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};pU(he.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},e))}get state(){return this._state}set state(e){sa.call(this,e)}};he.STATECHANGED="stateChanged",he.UPDATEAFSM="updateAFSM",he.INIT="[*]",he.ON="on",he.OFF="off",he.instances=new Map,he.instances2=new WeakMap;var mU=Ie(Ve()),zv="1",Kv="5",mp="2",vn="3",_U="5",fU="4",kt={CLIENT_BANNED:9,CHANNEL_SETUP_RESULT:19,CHANNEL_RECONNECT_RESULT:514,JOIN_ROOM_RESULT:20,PEER_JOIN:4134,PEER_LEAVE:4135,STREAM_ADDED:16,STREAM_REMOVED:18,UPLINK_NETWORK_STATS:22,UPDATE_REMOTE_MUTE_STAT:23,PUBLISH_RESULT:4098,PUBLISH_STATE_CHANGE_RESULT:4112,UNPUBLISH_RESULT:4100,SUBSCRIBE_RESULT:4102,UNSUBSCRIBE_RESULT:4104,SUBSCRIBE_CHANGE_RESULT:4106,MUTE_RESULT:4108,UPDATE_OFFER_RESULT:4128,START_PUBLISH_TENCENT_CDN_RES:1286,STOP_PUBLISH_TENCENT_CDN_RES:1288,START_PUBLISH_GIVEN_CDN_RES:777,STOP_PUBLISH_GIVEN_CDN_RES:779,START_MIX_TRANSCODE_RES:781,STOP_MIX_TRANSCODE_RES:783,USER_LIST_RES:4137,SWITCH_ROLE_RES:4110,UPDATE_CONSTRAINT_CONFIG_RES:772,REBUILD_PEER_CONNECTION_RES:4150,SPC_PUBLISH_RESULT:4146,SPC_SUBSCRIBE_RESULT:4156,ABILITY_STATUS_REPORT_RESULT:4158,SERVER_FIRST_PACKAGE_RECEIVED:5e3,RECEIVE_CUSTOM_MSG:4140},gU=[kt.UPDATE_REMOTE_MUTE_STAT,kt.UPLINK_NETWORK_STATS,kt.USER_LIST_RES,kt.MUTE_RESULT,kt.SERVER_FIRST_PACKAGE_RECEIVED,kt.RECEIVE_CUSTOM_MSG],K={CLIENT_BANNED:"client-banned",CHANNEL_SETUP_RESULT:"channel-setup-result",CHANNEL_RECONNECT_RESULT:"channel-reconnect-result",JOIN_ROOM_RESULT:"join-room-result",PEER_JOIN:"peer-join",PEER_LEAVE:"peer-leave",STREAM_ADDED:"stream-added",STREAM_REMOVED:"stream-removed",UPLINK_NETWORK_STATS:"uplink-network-stats",UPDATE_REMOTE_MUTE_STAT:"update-remote-mute-stat",PUBLISH_RESULT:"publish-result",PUBLISH_STATE_CHANGE_RESULT:"publish-state-change-result",UNPUBLISH_RESULT:"unpublish-result",SUBSCRIBE_RESULT:"subscribe-result",SUBSCRIBE_CHANGE_RESULT:"subscribe-change-result",UNSUBSCRIBE_RESULT:"unsubscribe-result",UPDATE_OFFER_RESULT:"update-offer-result",START_PUBLISH_TENCENT_CDN_RES:"start-publish-tencent-cdn-res",STOP_PUBLISH_TENCENT_CDN_RES:"stop-publish-tencent-cdn-res",START_PUBLISH_GIVEN_CDN_RES:"start-publish-given-cdn-res",STOP_PUBLISH_GIVEN_CDN_RES:"stop-publish-given-cdn-res",START_MIX_TRANSCODE_RES:"start-mix-transcode-res",STOP_MIX_TRANSCODE_RES:"stop-mix-transcode-res",USER_LIST_RES:"user-list-res",SWITCH_ROLE_RES:"switch_role_res",MUTE_RESULT:"mute-result",UPDATE_CONSTRAINT_CONFIG_RES:"update-contraint-config-res",REBUILD_PEER_CONNECTION_RES:"rebuild-pc-res",SPC_PUBLISH_RESULT:"spc-publish-result",SPC_SUBSCRIBE_RESULT:"spc-subscribe-result",ABILITY_STATUS_REPORT_RESULT:"ability-status-report",SERVER_FIRST_PACKAGE_RECEIVED:"first-pkg-received",RECEIVE_CUSTOM_MSG:"receive-custom-msg"},TU="publish_change",EU="join",yU="leave",SU="quality_report",qv="mute_uplink",vU="publish",Yv="publish_state_change",_p="unpublish",IU="subscribe",Qv="unsubscribe",Xv="subscribe_change",AU="start_publishing",RU="stop_publishing",CU="start_push_user_cdn",bU="stop_push_user_cdn",kU="start_mcu_mix",NU="stop_mcu_mix",DU="get_user_list",wU="change_role",$v="update_constraint_config",OU="rebuild_pc",PU="join/v2",LU="publish/v2",MU="subscribe/v3",xU="ability_status_report",VU="reconnect",UU="channel_msg",Ic=new Set,Zv=class extends mU.default{constructor(e){var t,i;super(),h(this,"room"),h(this,"url"),h(this,"backupUrl"),h(this,"race"),h(this,"destroyed",!1),h(this,"_socketInUse"),h(this,"_socket"),h(this,"_backupSocket"),h(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0}),h(this,"_currentState","DISCONNECTED"),h(this,"_isReconnecting",!1),h(this,"_seq",0),h(this,"_log"),h(this,"_lastMessageTime",-1),h(this,"_connnectStartTime",-1),h(this,"_stopConnectRetry"),h(this,"bytesSent",0),h(this,"bytesReceived",0),h(this,"keepAlive",!1),h(this,"signalDomainWhenUnifiedProxy"),this.room=e.room,this.race=!!I(e.race)||e.race,this.signalDomainWhenUnifiedProxy=e.signalDomainWhenUnifiedProxy,(((i=(t=this.room.scheduleResult)==null?void 0:t.config)==null?void 0:i.keepAliveClient)||0)-Ic.size>0&&this.room.enableSPC&&(this.keepAlive=!0,Ic.add(this)),this.url=e.url,this.backupUrl=e.backupUrl,this._seq=0,this._log=b.createLogger({id:"ws",userId:this.userId,sdkAppId:this.sdkAppId}),this.onmessage=this.onmessage.bind(this),this.onerror=this.onerror.bind(this),this.onclose=this.onclose.bind(this)}get urlParam(){let e="?sdkAppId=".concat(encodeURIComponent(this.sdkAppId),"&userId=").concat(encodeURIComponent(this.userId),"&userSig=").concat(encodeURIComponent(this.userSig),"&keepAlive=").concat(encodeURIComponent(Number(this.keepAlive)));return this.signalDomainWhenUnifiedProxy&&(e+="&signalDomain=".concat(encodeURIComponent(this.signalDomainWhenUnifiedProxy))),this.race?"".concat(e,"&race=1"):e}get _urlWithParam(){return"".concat(this.url).concat(this.race?"/v2/ws":"").concat(this.urlParam)}get _backupUrlWithParam(){return"".concat(this.backupUrl).concat(this.race?"/v2/ws":"").concat(this.urlParam)}get isConnected(){return this._currentState==="CONNECTED"}get isConnecting(){return this._currentState==="CONNECTING"}get sdkAppId(){return this.room.sdkAppId}get userId(){return this.room.userId}get userSig(){return this.room.userSig}get isOnline(){return this._currentState==="CONNECTED"&&Date.now()-this._lastMessageTime<12e3}connect(){return g(this,arguments,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:1e4;return function*(){if(e.isConnected)return Promise.resolve();e._log.info("connect to [".concat(e.url,", ").concat(e.backupUrl,"]").concat(t?" timeout: ".concat(t):""," keepAlive: ").concat(Number(e.keepAlive))),e.emitConnectionStateChanged("CONNECTING"),e._connnectStartTime=W();let i=[e.connectWS({url:e._urlWithParam,isMain:!0,timeout:t})];e.race&&e._backupUrlWithParam!==e._urlWithParam&&i.push(e.connectWS({url:e._backupUrlWithParam,isMain:!1,timeout:t})),e._socketInUse=yield Ch(i),e.unbindAndCloseSocket(e._socketInUse===e._socket?_.BACKUP:_.MAIN),e.emitConnectionStateChanged("CONNECTED")}()})}connectWS(e){let{url:t,timeout:i,isMain:r}=e,n=new WebSocket(t);this.bindSocket(n),r?this._socket=n:this._backupSocket=n;let s=-1;return new Promise((a,c)=>{n.onclose=c,n.onerror=c,n.onopen=()=>a(n),i&&(s=setTimeout(()=>{this.unbindAndCloseSocket(r?_.MAIN:_.BACKUP),c(new N({code:C.SIGNAL_CHANNEL_SETUP_FAILED,message:"ws connect timeout"}))},i))}).finally(()=>{n.onclose=null,n.onerror=null,n.onopen=null,clearTimeout(s)})}bindSocket(e){e.addEventListener("close",this.onclose),e.addEventListener("error",this.onerror),e.addEventListener("message",this.onmessage)}unbindSocket(e){e.removeEventListener("close",this.onclose),e.removeEventListener("error",this.onerror),e.removeEventListener("message",this.onmessage)}unbindAndCloseSocket(e){if(e===_.MAIN){if(this._socket){this.unbindSocket(this._socket);try{this._socket.close(1e3)}catch{}this._socket=null}}else if(this._backupSocket){this.unbindSocket(this._backupSocket);try{this._backupSocket.close(1e3)}catch{}this._backupSocket=null}}onclose(e){if(e.target===this._socketInUse&&(this._log.warn("".concat(e.target===this._socket?"main":"backup"," is closed code:").concat(e.code," ").concat(e.reason)),this.emitConnectionStateChanged("DISCONNECTED"),!e.wasClean||e.code!==1e3)){this._socketInUse.onclose=null,this._socketInUse.close(4011);let t=this._socketInUse===this._socket;this.unbindAndCloseSocket(t?_.MAIN:_.BACKUP),this._socketInUse=null,this.reconnect()}}onerror(e){this._log.error("".concat(e.target===this._socket?"main":"backup"," error observed")),this.emitConnectionStateChanged("DISCONNECTED"),e.target===this._socketInUse&&(this.unbindAndCloseSocket(_.MAIN),this.unbindAndCloseSocket(_.BACKUP),this._socketInUse=null,this.reconnect())}onmessage(e){if(!this.isConnected)return;this._lastMessageTime=Date.now(),this.bytesReceived+=bh(e.data);let t=JSON.parse(e.data),{cmd:i,data:r}=t,n=Object.values(kt),s=Object.keys(kt)[n.indexOf(i)],a=K[s];switch(gU.includes(i)||(this._log.debug("received ".concat(i," msg: ").concat(e.data)),a&&this._log.info("Received event: [ ".concat(a," ]"))),i){case kt.CHANNEL_SETUP_RESULT:if(t.code===0)this._signalInfo.clientIp=r.clientIp,this._signalInfo.signalIp=r.signalInnerIp,r.svrTime&&function(c){Md=c-new Date().getTime();let o=new Date;o.setTime(c),b.info("baseTime from server: ".concat(o," offset: ").concat(Md))}(r.svrTime),this._log.info("ChannelSetup Success"),L.addSuccessEvent({key:521701,cost:W()-this._connnectStartTime}),this._connnectStartTime=-1,this.emit(zv,{signalInfo:this._signalInfo});else{let c=new N({code:C.SIGNAL_CHANNEL_SETUP_FAILED,extraCode:t.code,message:j({key:B.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:t.code,errorMsg:t.message}})});this._log.error("".concat(t.code,", ").concat(t.message)),this.close(),L.addFailedEvent({key:521701,error:c}),this.emit(Kv,c)}break;case kt.JOIN_ROOM_RESULT:t.code===0&&(this._signalInfo.relayIp=r.relayOuterIp,this._signalInfo.relayInnerIp=r.relayInnerIp,this._signalInfo.relayPort=r.relayPort,this._signalInfo.tinyId=t.tinyId,this._log.info("signalIp:".concat(this._signalInfo.signalIp," clientIp:").concat(this._signalInfo.clientIp," relayIp: ").concat(this._signalInfo.relayIp))),this.emit(a,{data:t});break;default:this.emit(a,{data:t})}}reGetSignalChannelUrl(){return g(this,null,function*(){try{if(!this.room.joinParams)return;gi(!0),yield this.room.schedule(this.room.joinParams);let{mainUrl:e,backupUrl:t}=this.room.getSignalChannelUrl();this.url=e,this.backupUrl=t}catch{}})}reconnect(){return g(this,null,function*(){if(!this._isReconnecting){if(!this.room.isJoined&&this.keepAlive)return void this.close();this._isReconnecting=!0;try{this._log.warn("reconnect"),yield this.connect();let{roomId:e,useStringRoomId:t}=this.room,{relayIp:i,relayInnerIp:r,relayPort:n}=this._signalInfo,{data:s}=yield this.sendWaitForResponse({command:VU,data:{roomId:e,useStringRoomId:t,relayInnerIp:r,relayOuterIp:i,relayPort:n},responseCommand:K.CHANNEL_RECONNECT_RESULT});s.code===0?(this._log.warn("reconnect success"),this.stopReconnection(),L.addSuccessEvent({key:521702,cost:W()-this._connnectStartTime}),this._connnectStartTime=-1,this.room.syncUserList(),this.room.checkConnectionsToReconnect()):(L.addFailedEvent({key:521702,error:s.code}),this._log.warn("reconnect failed, ".concat(s.code," ").concat(s.message)),this.room.reJoin())}catch(e){this._log.error(e),this.room.reJoin()}}})}send(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(this.isConnected&&!this.room.isLeft){let i={cmd:e,data:t,userId:this.userId,tinyId:this._signalInfo.tinyId,seq:++this._seq},r=JSON.stringify(i);return this._socketInUse.send(r),this.bytesSent+=bh(r),i.seq}}sendWaitForResponse(e){let{command:t,data:i,timeout:r=5e3,responseCommand:n,commandDesc:s,enableLog:a=!0}=e;return new Promise((c,o)=>{let l=setTimeout(()=>{this.off(n,d);let p=new N({code:C.API_CALL_TIMEOUT,message:j({key:B.API_CALL_TIMEOUT,data:{commandDesc:s,command:t}})});a&&this._log.warn(p),o(p)},r),d=p=>{p.data.seq===u&&(clearTimeout(l),this.off(n,d),c(p))};this.on(n,d);let u=this.send(t,i)})}sendWaitForResponseWithRetry(e){let{commandDesc:t,command:i,retries:r=0,retryTimeout:n=0}=e;return ws({retryFunction:this.sendWaitForResponse,onError:s=>{let{retry:a}=s;this.isOnline?a():(this._log.warn("retry ".concat(i," when connected")),this.once(vn,a))},onRetrying:s=>{this._log.warn("".concat(t||i," timeout observed, retrying [").concat(s,"/").concat(r,"]"))},settings:{retries:r,timeout:n},context:this})(e)}getCurrentState(){return this._currentState}getSignalInfo(){return this._signalInfo}stopReconnection(){this._isReconnecting=!1,this._stopConnectRetry&&this._stopConnectRetry()}close(){this._log.info("closed"),Ic.delete(this),this.stopReconnection(),this._signalInfo={tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0},this._socketInUse=null,this.bytesSent=0,this.bytesReceived=0,this._stopConnectRetry&&this._stopConnectRetry(),this.unbindAndCloseSocket(_.MAIN),this.unbindAndCloseSocket(_.BACKUP),this.emitConnectionStateChanged("DISCONNECTED")}destroy(){this.close(),this.destroyed=!0}stopKeepAliveIn(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:3600;if(this.keepAlive){this._log.info("stopKeepAlive in ".concat(e,"s"));let t=setTimeout(()=>{this.keepAlive=!1,this._log.info("close due to not used ".concat(e,"s")),this.close()},1e3*e),i=r=>{r instanceof vc&&r.action==="join"&&(this._log.info("stopKeepAlive clear timeout"),clearTimeout(t),this.room.off(he.STATECHANGED,i))};this.room.on(he.STATECHANGED,i)}}emitConnectionStateChanged(e){e!==this._currentState&&(this._log.info("".concat(this._currentState," -> ").concat(e)),this.emit(mp,{prevState:this._currentState,state:e}),this._currentState=e,e==="CONNECTED"?this.emit(vn):e==="DISCONNECTED"&&this.emit(_U))}};k([cr({settings:{retries:1/0,timeout:2e3},onError(e,t){!this.room.isDestroyed&&!this.destroyed&&t()},onRetrying(e,t){this._log.warn("retrying to connect ".concat(e)),e>=3&&e%3==0&&this.reGetSignalChannelUrl(),t&&(this._stopConnectRetry=t,(this.room.isDestroyed||this.destroyed)&&t())}})],Zv.prototype,"connect");var FU=Ie(Ve()),fp=0,gp=!1,Ac=new Set,eI=!1,fr=class{constructor(e){h(this,"userId"),h(this,"tinyId"),h(this,"_sdpSemantics"),h(this,"_isUplink"),h(this,"_room"),h(this,"_log"),h(this,"_signalChannel"),h(this,"_isErrorObserved",!1),h(this,"_waitForPeerConnectionConnectedPromise"),h(this,"_waitForPeerConnectionConnectedPromiseReject",null),h(this,"_peerConnection",null),h(this,"_emitter",new FU.default),h(this,"_currentState","DISCONNECTED"),h(this,"_isReconnecting",!1),h(this,"_reconnectionCount",0),h(this,"_reconnectionTimer",-1),h(this,"_isFirstConnection",!0),h(this,"_prevTime",-1),h(this,"_enableSEI"),h(this,"_sei"),h(this,"_localAddress"),h(this,"_remoteAddress"),this.userId=e.userId,this.tinyId=e.tinyId,this._room=e.room,this._sdpSemantics=e.room.sdpSemantics,this._isUplink=e.isUplink,this._log=b.createLogger({id:"n-mpc",userId:this._room.userId,remoteUserId:this.userId,sdkAppId:this._room.sdkAppId,isLocal:this._isUplink}),this._signalChannel=e.signalChannel,this._enableSEI=e.enableSEI}beforeConnect(){this._prevTime<0&&(this._prevTime=W())}afterConnect(){try{this._isFirstConnection?(this._isFirstConnection=!1,L.addSuccessEvent({key:521705,cost:Math.min(W()-this._prevTime,3e4)})):this._isReconnecting&&L.addSuccessEvent({key:521706,cost:W()-this._prevTime}),this._prevTime=-1}catch(e){throw this._isFirstConnection?(this._isFirstConnection=!1,L.addFailedEvent({key:521705,error:e})):this._isReconnecting&&this._reconnectionCount>=3&&L.addFailedEvent({key:521706,error:e}),e}}initialize(){let e={encodedInsertableStreams:this._enableSEI&&or,iceServers:this._room.getIceServers(),iceTransportPolicy:this._room.getIceTransportPolicy(),sdpSemantics:this._sdpSemantics,bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"};this._peerConnection=new RTCPeerConnection(e),this._peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this)}close(e){this._log.info("close connection"),this._emitter.emit("closed",e),this._isReconnecting&&this.stopReconnection(),this.closePeerConnection(),this._sei&&(this._sei.destroy(),this._sei=null),Ac.delete(this)}closePeerConnection(){let e=arguments.length>0&&arguments[0]!==void 0&&arguments[0];this._peerConnection&&(this._log.info("close pc"),this._peerConnection.onconnectionstatechange=null,this._peerConnection.close(),this._peerConnection=null,e&&this.emitConnectionStateChangedEvent("DISCONNECTED")),this._waitForPeerConnectionConnectedPromiseReject&&this._waitForPeerConnectionConnectedPromiseReject(new N({code:C.API_CALL_ABORTED,message:"connection closed"}))}getDTLSTransportState(){if(!this._peerConnection)return mi;let e=null;if(this._isUplink){if(!Fs()||this._peerConnection.getSenders().length===0)return mi;e=this._peerConnection.getSenders()[0].transport}else{if(!ic()||this._peerConnection.getReceivers().length===0)return mi;e=this._peerConnection.getReceivers()[0].transport}return e?e.state:mi}onConnectionStateChange(e){let t=this._peerConnection.iceConnectionState,i=this.getDTLSTransportState();if(this._log.info("connectionState: ".concat(e.target.connectionState,", ICE: ").concat(t,", DTLS: ").concat(i)),e.target.connectionState===fe.CONNECTING&&this.emitConnectionStateChangedEvent("CONNECTING"),e.target.connectionState===fe.FAILED||e.target.connectionState===fe.CLOSED){let r="connection ".concat(e.target.connectionState,". ICE Transport state: ").concat(t,", DTLS Transport state: ").concat(i),n=new N({message:r,code:C.ICE_TRANSPORT_ERROR});this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection(),this._isErrorObserved||this._emitter.emit("error",n)}(e.target.connectionState===fe.CONNECTED||e.target.connectionState===fe.COMPLETED)&&(this.logSelectedCandidate(),de.logSuccessEvent({userId:this._room.userId,eventType:Ft.ICE_CONNECTION_STATE}),this.emitConnectionStateChangedEvent("CONNECTED"))}emitConnectionStateChangedEvent(e){return e!==this._currentState&&(e==="CONNECTED"?(fp=0,gp=!1,eI=!0,Ac.add(this)):Ac.delete(this),R.emit(A.PEER_CONNECTION_STATE_CHANGED,{room:this._room,prevState:this._currentState,state:e,remoteUserId:this._isUplink?void 0:this.userId}),this._emitter.emit("connection-state-changed",{prevState:this._currentState,state:e}),this._currentState=e,!0)}getPeerConnection(){return this._peerConnection}getRoom(){return this._room}getUserId(){return this.userId}getTinyId(){return this.tinyId}logSelectedCandidate(){return g(this,null,function*(){if(!this._peerConnection)return;let e=yield this._peerConnection.getStats();for(let[,t]of e)if(Us(t)){let i=e.get(t.localCandidateId),r=e.get(t.remoteCandidateId);i&&(this._log.info("local candidate: ".concat(i.candidateType," ").concat(i.protocol,":").concat(i.ip||i.address,":").concat(i.port," ").concat(i.networkType||""," ").concat(i.candidateType==="relay"?"relayProtocol:".concat(i.relayProtocol):"")),this._localAddress="".concat(i.ip||i.address,":").concat(i.port)),r&&(this._log.info("remote candidate: ".concat(r.candidateType," ").concat(r.protocol,":").concat(r.ip||r.address,":").concat(r.port)),this._remoteAddress="".concat(r.protocol,":").concat(r.ip||r.address));break}})}getCurrentState(){return this._currentState}waitForPeerConnectionConnected(){return this._waitForPeerConnectionConnectedPromise||(this._waitForPeerConnectionConnectedPromise=new Promise((e,t)=>{if(this._currentState==="CONNECTED")return e();this._waitForPeerConnectionConnectedPromiseReject=t;let i=a=>{a.state==="CONNECTED"&&(clearTimeout(s),n(),e())},r=a=>{let{room:c}=a;c===this._room&&(clearTimeout(s),n(),t(new N({code:C.API_CALL_ABORTED,message:j({key:B.CONNECTION_ABORTED,data:"leave room"})})))},n=()=>{R.off(A.LEAVE_SUCCESS,r,this),this._emitter.off("connection-state-changed",i,this)},s=setTimeout(()=>{n();let a=new N({code:C.API_CALL_TIMEOUT,message:"connection timeout"});var c;fp+=1,c=this._signalChannel.isConnected,fp>2&&!gp&&Ac.size===0&&c&&(this._log.warn("firewall restriction"),gp=!0,this._emitter.emit("firewall-restriction")),t(a)},Yd);R.on(A.LEAVE_SUCCESS,r,this),this._emitter.on("connection-state-changed",i,this)}),this._waitForPeerConnectionConnectedPromise=this._waitForPeerConnectionConnectedPromise.finally(()=>{this._waitForPeerConnectionConnectedPromise=null,this._waitForPeerConnectionConnectedPromiseReject=null})),this._waitForPeerConnectionConnectedPromise}getReconnectionCount(){return this._reconnectionCount}startReconnection(){this._isReconnecting=!0,this.reconnect()}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}stopReconnection(){this._log.info("stop reconnection"),this._isReconnecting=!1,this._reconnectionCount=0,this.clearReconnectionTimer(),this._signalChannel.off(vn,this.reconnect,this)}beforeReconnect(){if(this._reconnectionTimer!==-1)return this._log.warn("reconnect() is reconnecting, ignore"),-1;if(this._reconnectionCount>=rn()){this._log.warn("SDK has tried reconnect for ".concat(this._reconnectionCount," times, but all failed, please check your network")),this.stopReconnection();let e=new N({code:this._isUplink?C.UPLINK_RECONNECTION_FAILED:C.DOWNLINK_RECONNECTION_FAILED,message:j({key:this._isUplink?B.UPLINK_RECONNECTION_FAILED:B.DOWNLINK_RECONNECTION_FAILED})});return this.emitConnectionStateChangedEvent("DISCONNECTED"),this._emitter.emit("error",e),-1}return this._signalChannel.isConnected?(this._reconnectionCount+=1,this._log.warn("reconnect() trying [".concat(this._reconnectionCount,"]")),1):(this._log.warn("reconnect() signal channel is not connected, suspend reconnection until signal is connected"),this._signalChannel.once(vn,this.reconnect,this),-1)}on(e,t,i){this._emitter.on(e,t,i)}off(e,t,i){this._emitter.off(e,t,i)}getIsReconnecting(){return this._isReconnecting}get isH264(){var e,t;return!((t=(e=this._peerConnection)==null?void 0:e.remoteDescription)==null||!t.sdp.includes("H264"))}},tI=Ie(Py()),Se=function(e){return tI.default.parse(e)},Di=function(e){return tI.default.write(e)};function Tp(e){return Object.keys(e).filter(t=>e[t])}var iI=class extends fr{constructor(e){super(J(O({},e),{isUplink:!1})),h(this,"_flag",0),h(this,"role","anchor"),h(this,"remoteAudioTrack"),h(this,"remoteVideoTrack"),h(this,"remoteAuxiliaryTrack"),h(this,"ssrc",{audio:0,video:0,auxiliary:0}),h(this,"_isSDPExchanging",!1),this.flag=e.flag,this.remoteAudioTrack=e.remoteAudioTrack||new ap(this._room,this),this.remoteVideoTrack=e.remoteVideoTrack||new Ys(this._room,this),this.remoteAuxiliaryTrack=e.remoteAuxiliaryTrack||new kv(this._room,this)}get videoCodec(){var e,t;let i=(t=(e=this._peerConnection)==null?void 0:e.remoteDescription)==null?void 0:t.sdp;return i?i.includes("H264")?"h264":"vp8":"h264"}get subscribeState(){let e={audio:!1,video:!1,auxiliary:!1,smallVideo:!1};return this.remoteVideoTrack.isSubscribed&&(8&this.remoteVideoTrack.mediaType?e.smallVideo=!0:e.video=!0),this.remoteAudioTrack.isSubscribed&&(e.audio=!0),this.remoteAuxiliaryTrack.isSubscribed&&(e.auxiliary=!0),e}get muteState(){return Ms(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var t,i,r;e!==this._flag&&(this._flag=e,(t=this.remoteAudioTrack)==null||t.onFlagChanged(),(i=this.remoteVideoTrack)==null||i.onFlagChanged(),(r=this.remoteAuxiliaryTrack)==null||r.onFlagChanged())}get hasMainStream(){return this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall}get hasAuxStream(){return this.muteState.hasAuxiliary}get isMainStreamSubscribed(){return(this.subscribeState.audio||this.subscribeState.video||this.subscribeState.smallVideo)&&(this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall)}get isAuxStreamSubscribed(){return this.subscribeState.auxiliary&&this.muteState.hasAuxiliary}get isSmallStreamSubscribed(){return this.subscribeState.smallVideo&&this.muteState.hasSmall}get isBigStreamSubscribed(){return this.subscribeState.video&&this.muteState.hasVideo}isStreamUnpublished(e){return e===_.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){super.initialize(),this.installEvents(),this._peerConnection.ontrack=this.onTrack.bind(this)}close(e){super.close(e),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.uninstallEvents()}installEvents(){}uninstallEvents(){this._emitter.removeAllListeners()}emitConnectionStateChangedEvent(e){var t,i;let r=this._currentState,n=super.emitConnectionStateChangedEvent(e);return n&&r!==e&&((t=this.remoteVideoTrack)==null||t.emit("connection-state-changed",{prevState:r,state:e}),(i=this.remoteAuxiliaryTrack)==null||i.emit("connection-state-changed",{prevState:r,state:e})),n}onTrack(e){let t=e.streams[0],{track:i}=e,r=t.id===wo?_.MAIN:_.AUXILIARY;this._log.debug("ontrack ".concat(r," ").concat(i.kind));let n=_.AUDIO;i.kind===_.VIDEO&&(n=r===_.MAIN?_.VIDEO:_.AUXILIARY);let s=this.remoteAudioTrack;n===_.VIDEO?s=this.remoteVideoTrack:n===_.AUXILIARY&&(s=this.remoteAuxiliaryTrack),s.setInputMediaStreamTrack(i)}addRRTRLine(e){let t=e.split(`\r
103
+ `),i=new Map;t.forEach((n,s)=>{/^a=rtcp-fb:/.test(n)&&t[s+1]&&!/^a=rtcp-fb:/.test(t[s+1])&&i.set(s+1,"".concat(n.match(/^a=rtcp-fb:\d+/)[0]," rrtr"))});let r=[...i];for(let n=0;n<r.length;n++){let[s,a]=r[n];t.splice(s+n,0,a)}return t.join(`\r
104
+ `)}addSPSDescription(e){let t=Se(e);return t.media.forEach(i=>{i.type===_.VIDEO&&i.fmtp.forEach(r=>{r.config+=";sps-pps-idr-in-keyframe=1"})}),Di(t)}removeSDESDescription(e){let t=["urn:ietf:params:rtp-hdrext:sdes:mid","urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id","urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id"],i=Se(e);return i.media.forEach(r=>{!r.ext||(r.ext=r.ext.filter(n=>!t.includes(n.uri)))}),Di(i)}isSubscriptionStateNotChanged(e){return JSON.stringify(e)===JSON.stringify(this.subscribeState)}subscribe(e,t){return g(this,null,function*(){var i,r;try{if((((i=this._peerConnection)==null?void 0:i.connectionState)===fe.NEW||((r=this._peerConnection)==null?void 0:r.connectionState)===fe.CONNECTING)&&(yield this.waitForPeerConnectionConnected()),this.isSubscriptionStateNotChanged(e))return void(this._peerConnection||(this.initialize(),yield this.connect(e)));if(this._log.info("subscribe ".concat(t," ").concat(JSON.stringify(e))),this._peerConnection||this._isSDPExchanging){let n="subscribe_change";Object.values(e).find(s=>s===!0)||(n="unsubscribe"),yield this.sendSubscription(n,e)}else this.initialize(),yield this.connect(e)}catch(n){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn("".concat(n.message," ").concat(JSON.stringify(this.muteState))),new N({code:C.REMOTE_STREAM_NOT_EXIST,message:"remote user ".concat(this.userId," unpublished stream")})):n}})}unsubscribe(e){return g(this,arguments,function(t){var i=this;let{remoteTracks:r,streamType:n}=t;return function*(){if(i._currentState==="CONNECTED"&&(n==="main"&&!i.isMainStreamSubscribed||n==="auxiliary"&&!i.isAuxStreamSubscribed))return void i._log.info("".concat(n," stream already unsubscribed"));let s=O({},i.subscribeState);r.forEach(c=>{switch(c.mediaType){case 1:s.audio=!1;break;case 4:s.video=!1;break;case 8:s.smallVideo=!1;break;case 2:s.auxiliary=!1}});let a="subscribe_change";Object.values(s).find(c=>c===!0)||(a="unsubscribe"),i._log.info("".concat(a==="unsubscribe"?a:"subscribe"," ").concat(n," [").concat(Tp(s),"]")),yield i.sendSubscription(a,s),a==="unsubscribe"&&(i.closePeerConnection(),i.emitConnectionStateChangedEvent("DISCONNECTED"))}()})}sendSubscription(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.subscribeState,i={srcTinyId:this.tinyId,srcUserId:this.userId},r=Qv,n=K.UNSUBSCRIBE_RESULT;return e==="subscribe_change"&&(i={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},r=Xv,n=K.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponse({command:r,data:i,responseCommand:n,timeout:1e4}).then(s=>{let{data:a}=s;if(a.code!==0){let c=new N({code:a.code,message:j({key:B.ERROR_MESSAGE,data:{type:e,message:a.message}})});throw this._log.error(c),c}})}connect(){return g(this,arguments,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.subscribeState;return function*(){try{yield e.exchangeSDP(t),yield e.waitForPeerConnectionConnected()}catch(i){throw e.closePeerConnection(!0),i}}()})}exchangeSDP(e){return g(this,null,function*(){try{this._isSDPExchanging=!0,yield this.createOffer(),this._log.info("createOffer success, sending offer");let{type:t,sdp:i}=this._peerConnection.localDescription,r={type:t,sdp:i,srcUserId:this.userId,srcTinyId:this.tinyId,audio:e.audio,bigVideo:e.video,auxVideo:e.auxiliary,smallVideo:e.smallVideo},n=yield this._signalChannel.sendWaitForResponse({command:IU,commandDesc:"exchange sdp",data:r,responseCommand:K.SUBSCRIBE_RESULT,timeout:Xy});if(!this._peerConnection){let s=new N({code:C.INVALID_OPERATION,message:j({key:B.CONNECTION_CLOSED})});throw this._log.warn(s),s}yield this.onSubscribeResult(n),this._isSDPExchanging=!1}catch(t){throw this._isSDPExchanging=!1,t}})}createOffer(){return g(this,null,function*(){let e={voiceActivityDetection:!1};Wt()&&this._sdpSemantics===_s?(this._peerConnection.addTransceiver(_.AUDIO,{direction:Y.RECVONLY}),this._peerConnection.addTransceiver(_.VIDEO,{direction:Y.RECVONLY}),this._peerConnection.addTransceiver(_.VIDEO,{direction:Y.RECVONLY})):(e.offerToReceiveAudio=!0,e.offerToReceiveVideo=!0);let t=yield this._peerConnection.createOffer(e);if(t.sdp){let{isH264DecodeSupported:i}=yield Ph();i||(this._log.warn("remove h264 desc from sdp"),t.sdp=function(r){let n=Se(r);return n.media.forEach(s=>{var a,c;if(s.type===_.VIDEO){let o=new Set;s.rtp.forEach(d=>{let{payload:u,codec:p}=d;return p==="H264"&&o.add(u)}),s.fmtp.forEach(d=>{let{payload:u,config:p}=d,m=p.match(/apt=(\d+)/);m&&m[1]&&o.has(Number(m[1]))&&o.add(u)});let l=d=>{let{payload:u}=d;return!o.has(u)};s.rtp=s.rtp.filter(l),s.rtcpFb=(a=s.rtcpFb)==null?void 0:a.filter(l),s.fmtp=s.fmtp.filter(l),s.payloads=(c=s.payloads)==null?void 0:c.split(" ").filter(d=>!o.has(Number(d))).join(" ")}}),Di(n)}(t.sdp)),t.sdp=this.addRRTRLine(t.sdp),t.sdp=this.addSPSDescription(t.sdp),t.sdp=function(r){let n=Se(r);return n.media.forEach(s=>{s.type===_.AUDIO&&s.fmtp.forEach(a=>{a.config+=";sprop-stereo=1;stereo=1"})}),Di(n)}(t.sdp),this._sdpSemantics===_s&&(t.sdp=this.removeSDESDescription(t.sdp))}yield this._peerConnection.setLocalDescription(t)})}onSubscribeResult(e){return g(this,null,function*(){let{code:t,message:i=""}=e&&e.data||{},{type:r,sdp:n}=e&&e.data&&e.data.data||{};if(t===Po)throw new N({code:C.NOT_SUPPORTED_H264,message:j({key:B.NOT_SUPPORTED_H264DECODE})});try{if(t!==0)throw new N({code:t,message:j({key:B.EXCHANGE_SDP_FAILED,data:{errMsg:i}})});this._log.debug("accept remote answer: ".concat(n)),yield this._peerConnection.setRemoteDescription({type:r,sdp:n}),this._sei&&(this._sei.handleEncodedStreams(),this._sei.onSEIMessage=s=>{this._emitter.emit("sei-message",J(O({},s),{userId:this.userId}))}),this.updateSSRC(n)}catch(s){throw this._log.error(s),s}})}updateSSRC(e){try{Se(e).media.forEach(t=>{if(t.ssrcs)if(t.type===_.AUDIO){let i=t.ssrcs.find(r=>{var n;return(n=r.value)==null?void 0:n.includes(wo)});i&&(this.ssrc.audio=Number(i.id))}else{let i=t.ssrcs.find(n=>{var s;return(s=n.value)==null?void 0:s.includes(wo)}),r=t.ssrcs.find(n=>{var s;return(s=n.value)==null?void 0:s.includes(Jy)});i&&(this.ssrc.video=Number(i.id)),r&&(this.ssrc.auxiliary=Number(r.id))}})}catch{}}getMainStreamVideoTrackId(){return this.remoteVideoTrack&&this.remoteVideoTrack.mediaTrack?this.remoteVideoTrack.mediaTrack.id:""}getAuxStreamVideoTrackId(){return this.remoteAuxiliaryTrack&&this.remoteAuxiliaryTrack.mediaTrack?this.remoteAuxiliaryTrack.mediaTrack.id:""}reconnect(){return g(this,null,function*(){if(!(it(iI.prototype,this,"beforeReconnect").call(this)<0))try{this.closePeerConnection(),this.initialize(),yield this.connect(),this.stopReconnection(),this._log.warn("reconnect() success")}catch{let t=ln(this._reconnectionCount);this._log.warn("reconnect() timeout, try again after ".concat(t/1e3,"s")),this._reconnectionTimer=setTimeout(()=>{this.clearReconnectionTimer(),this.reconnect()},t)}})}getIsReconnecting(){return this._isReconnecting}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}getCurrentState(){return this._currentState}setDelay(e){let{audioDelay:t,videoDelay:i}=e;this.remoteAudioTrack.stat.end2EndDelay=t,this.remoteVideoTrack.stat.end2EndDelay=i}},Ep=iI;k([ae(e=>function(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];return new Promise((n,s)=>{let a=c=>{this._emitter.off("closed",a),s(new N({code:C.API_CALL_ABORTED,message:j({key:B.CONNECTION_ABORTED,data:c})}))};this._emitter.on("closed",a),e.apply(this,i).then(n,s).finally(()=>{this._emitter.off("closed",a)})})})],Ep.prototype,"subscribe"),k([np(fr.prototype.afterConnect),_v(fr.prototype.beforeConnect)],Ep.prototype,"connect");var rI=Ep,nI={voiceActivityDetection:!1},sI=class extends fr{constructor(e){super(J(O({},e),{isUplink:!0})),h(this,"localMainAudioTrack",null),h(this,"localMainVideoTrack",null),h(this,"localAuxAudioTrack",null),h(this,"localAuxVideoTrack",null),h(this,"ssrc",{audio:0,video:0,small:0,auxiliary:0}),h(this,"_isPublishingAux",!1),h(this,"_publishingLocalAudioTrack"),h(this,"_publishingLocalVideoTrack"),h(this,"_mediaSettings",{videoCodec:"",videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioCodec:"opus",audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0,auxVideoWidth:0,auxVideoHeight:0,auxVideoFps:0,auxVideoBps:0}),h(this,"flag",0)}get videoCodec(){return this._mediaSettings.videoCodec.toLowerCase()||"h264"}get isMainStreamPublished(){return!(!this.localMainAudioTrack&&!this.localMainVideoTrack)}get isAuxStreamPublished(){return!(!this.localAuxVideoTrack&&!this.localAuxAudioTrack)}get publishState(){var e,t,i,r;let n={audio:!1,bigVideo:!1,smallVideo:!1,auxVideo:!1};if(this._peerConnection){let s=this._peerConnection.getSenders();s&&(Si()?(n.audio=!((e=s[0])==null||!e.track),n.bigVideo=!((t=s[1])==null||!t.track),n.smallVideo=!((i=s[2])==null||!i.track),n.auxVideo=!((r=s[3])==null||!r.track)):s.forEach(a=>{a.track&&(a.track.kind===_.AUDIO?n.audio=!0:(n.bigVideo=!0,this._room.videoManager.hasSmall&&(n.smallVideo=!0)))}))}return n}initialize(){super.initialize(),this.installEvents()}reset(){this._isReconnecting&&this.stopReconnection(),this.closePeerConnection(),this.uninstallEvents()}close(e){super.close(e),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED")}installEvents(){this._emitter.listeners("connection-state-changed").includes(this.handleConnectionStateChange)||this._emitter.on("connection-state-changed",this.handleConnectionStateChange,this)}uninstallEvents(){this._emitter.off("connection-state-changed",this.handleConnectionStateChange,this)}emitConnectionStateChangedEvent(e,t){var i,r,n;let s=this._currentState,a=super.emitConnectionStateChangedEvent(e);return a&&s!==e&&(t?t.emit("connection-state-changed",{prevState:s,state:e}):((i=this.localMainVideoTrack)==null||i.emit("connection-state-changed",{prevState:s,state:e}),(r=this.localAuxVideoTrack)==null||r.emit("connection-state-changed",{prevState:s,state:e}),(n=this._publishingLocalVideoTrack)==null||n.emit("connection-state-changed",{prevState:s,state:e}))),a}publish(e){return g(this,arguments,function(t){var i=this;let{localAudioTrack:r,localVideoTrack:n,isAuxiliary:s}=t;return function*(){var a;let c;i._peerConnection||i.initialize(),r&&(i._publishingLocalAudioTrack=r),n&&(i._publishingLocalVideoTrack=n),i._isPublishingAux=s,n&&!s&&n.small&&(c=i._room.videoManager.smallTrack),i.sendMediaSettings(),Wt()?yield i.publishByTransceiver({localAudioTrack:r,localVideoTrack:n,smallTrack:c,isAuxiliary:s}):yield i.publishByAddTrack({localAudioTrack:r,localVideoTrack:n,smallTrack:c}),i._publishingLocalAudioTrack=null,i._publishingLocalVideoTrack=null,i._isPublishingAux=!1,s?(n&&(i.localAuxVideoTrack=n),r&&(i.localAuxAudioTrack=r)):(n&&(i.localMainVideoTrack=n),r&&(i.localMainAudioTrack=r)),(a=i._sei)==null||a.handleEncodedStreams(),i.installTrackMuteEvents(r,n),i.sendMutedFlag()}()})}publishByTransceiver(e){return g(this,arguments,function(t){var i=this;let{localAudioTrack:r,localVideoTrack:n,smallTrack:s,isAuxiliary:a}=t;return function*(){i._log.info("publish by transceiver");let c=new MediaStream,o=n==null?void 0:n.outMediaTrack,l=r==null?void 0:r.outMediaTrack;l&&c.addTrack(l),o&&c.addTrack(o);let d=i._peerConnection.getTransceivers();if(d.length===0)i._peerConnection.addTransceiver(l||_.AUDIO,{direction:Y.SENDONLY,streams:[c]}),i._peerConnection.addTransceiver(a?_.VIDEO:o||_.VIDEO,{direction:Y.SENDONLY,streams:[c]}),i._peerConnection.addTransceiver(s||_.VIDEO,{direction:Y.SENDONLY,streams:[c]}),i._peerConnection.addTransceiver(a&&o||_.VIDEO,{direction:Y.SENDONLY,streams:[c]}),yield i.connect();else{let u=[];if(l&&(d[0].sender.track||u.push(0),yield d[0].sender.replaceTrack(l),yield i.setBandwidth({bandwidth:(r==null?void 0:r.profile.bitrate)||40,type:_.AUDIO})),o){let p=a?3:1;yield d[p].sender.replaceTrack(o),yield i.setBandwidth({bandwidth:n.profile.bitrate,type:_.VIDEO,videoType:a?_.AUXILIARY:_.BIG}),u.push(p),s&&(yield d[2].sender.replaceTrack(s),yield i.setBandwidth({bandwidth:n.small.bitrate,type:_.VIDEO,videoType:_.SMALL}),u.push(2))}yield i.setTransceiverDirection(Y.SENDONLY,u),yield i.doPublishChange(),n==null||n.emit("connection-state-changed",{prevState:"DISCONNECTED",state:"CONNECTING"}),n==null||n.emit("connection-state-changed",{prevState:"CONNECTING",state:"CONNECTED"})}}()})}publishByAddTrack(e){return g(this,arguments,function(t){var i=this;let{localAudioTrack:r,localVideoTrack:n,smallTrack:s}=t;return function*(){i._log.info("publish by addtrack");let a=n==null?void 0:n.outMediaTrack,c=r==null?void 0:r.outMediaTrack;if(i._peerConnection&&i._peerConnection.connectionState!=="new")return r&&c&&(yield i.addTrack(r)),void(a&&(yield i.addTrack(n)));let o=new MediaStream;if(c&&o.addTrack(c),a&&o.addTrack(a),c&&i._peerConnection.addTrack(c,o),a&&(i._peerConnection.addTrack(a,o),s)){let l=new MediaStream;l.addTrack(s),i._peerConnection.addTrack(s,l)}yield i.connect()}()})}enableSmall(e){return g(this,null,function*(){let t=this._peerConnection.getTransceivers();e?this._room.videoManager.smallTrack&&(yield t[2].sender.replaceTrack(this._room.videoManager.smallTrack),yield this.setTransceiverDirection(Y.SENDONLY,[2])):(yield t[2].sender.replaceTrack(null),yield this.setTransceiverDirection(Y.INACTIVE,[2])),this.updateMediaSettings(),yield this.doPublishChange()})}installTrackMuteEvents(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];t.forEach(r=>{r&&(r==null||r.on("mute",this.sendMutedFlag,this),r==null||r.on("unmute",this.sendMutedFlag,this))})}uninstallTrackMuteEvents(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];t.forEach(r=>{r&&(r==null||r.off("mute",this.sendMutedFlag,this),r==null||r.off("unmute",this.sendMutedFlag,this))})}unpublish(e){return g(this,arguments,function(t){var i=this;let{localAudioTrack:r,localVideoTrack:n}=t;return function*(){if(!Si())return r&&r.outMediaTrack&&!n&&i.localMainVideoTrack?(yield i.removeTrack(r),void(i.localMainAudioTrack=null)):n&&n.outMediaTrack&&!r&&i.localMainAudioTrack?(yield i.removeTrack(n),void(i.localMainVideoTrack=null)):(yield i.doUnpublish(),i.uninstallTrackMuteEvents(r,n),void i.emitConnectionStateChangedEvent("DISCONNECTED",n));let s=n&&n===i.localAuxVideoTrack,a=n==null?void 0:n.outMediaTrack,c=i._peerConnection.getSenders(),o=[];r&&(yield c[0].replaceTrack(null),o.push(0),s?i.localAuxAudioTrack=null:i.localMainAudioTrack=null),a&&(s?(yield c[3].replaceTrack(null),i.localAuxVideoTrack=null,i._mediaSettings=J(O({},i._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),o.push(3)):(yield c[1].replaceTrack(null),yield c[2].replaceTrack(null),i.localMainVideoTrack=null,i._mediaSettings=J(O({},i._mediaSettings),{videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0}),o.push(1,2))),i.isMainStreamPublished||i.isAuxStreamPublished?(yield i.setTransceiverDirection(Y.INACTIVE,o),yield i.doPublishChange(!1)):yield i.doUnpublish(),i.uninstallTrackMuteEvents(r,n),n==null||n.emit("connection-state-changed",{prevState:i._currentState,state:"DISCONNECTED"})}()})}doPublishChange(){let e=!(arguments.length>0&&arguments[0]!==void 0)||arguments[0];return g(this,null,function*(){let t={state:this.publishState,constraintConfig:this._mediaSettings},i=yield this._signalChannel.sendWaitForResponse({command:Yv,data:t,responseCommand:K.PUBLISH_STATE_CHANGE_RESULT,enableLog:e});this.checkPublishResultCode(i.data.code,i.data.message)})}doUnpublish(){let e=arguments.length>0&&arguments[0]!==void 0&&arguments[0];return this._signalChannel.sendWaitForResponse({command:_p,commandDesc:"unpublish",responseCommand:K.UNPUBLISH_RESULT,enableLog:e}).catch(t=>{if(t.getCode()===C.API_CALL_TIMEOUT)return Promise.resolve();throw t})}updateMediaSettings(){let{detail:{isH264EncodeSupported:e,isVp8EncodeSupported:t}}=this._room.checkSystemResult;e?this._mediaSettings.videoCodec="H264":t&&(this._mediaSettings.videoCodec="VP8");let i=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:r,localAuxVideoTrack:n}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?n=this._publishingLocalVideoTrack:r=this._publishingLocalVideoTrack),un){if(i&&i.outMediaTrack){let s=i.outMediaTrack.getSettings();this._mediaSettings.audioChannel=s.channelCount||1,this._mediaSettings.audioBps=1e3*i.profile.bitrate,this._mediaSettings.audioFs=s.sampleRate||0}if(r&&r.outMediaTrack){let s=r.outMediaTrack.getSettings();this._mediaSettings.videoWidth=s.width||0,this._mediaSettings.videoHeight=s.height||0,this._mediaSettings.videoFps=s.frameRate||0,this._mediaSettings.videoBps=1e3*r.profile.bitrate,r.small&&(this._mediaSettings.smallVideoWidth=r.small.width,this._mediaSettings.smallVideoHeight=r.small.height,this._mediaSettings.smallVideoFps=r.small.frameRate,this._mediaSettings.smallVideoBps=1e3*r.small.bitrate)}if(n&&n.outMediaTrack){let s=n.outMediaTrack.getSettings();this._mediaSettings.auxVideoWidth=s.width||0,this._mediaSettings.auxVideoHeight=s.height||0,this._mediaSettings.auxVideoFps=s.frameRate||0,this._mediaSettings.auxVideoBps=1e3*n.profile.bitrate}}else i&&i.outMediaTrack&&(this._mediaSettings.audioChannel=i.profile.channelCount,this._mediaSettings.audioBps=1e3*i.profile.bitrate,this._mediaSettings.audioFs=i.profile.sampleRate),r&&r.outMediaTrack&&(this._mediaSettings.videoWidth=r.profile.width,this._mediaSettings.videoHeight=r.profile.height,this._mediaSettings.videoFps=r.profile.frameRate,this._mediaSettings.videoBps=1e3*r.profile.bitrate);this._log.info("updateMediaSettings: ".concat(JSON.stringify(this._mediaSettings)))}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:$v,data:this._mediaSettings,responseCommand:K.UPDATE_CONSTRAINT_CONFIG_RES}).then(e=>{e.data.code!==0&&this._log.warn(e.data.message)}).catch(()=>{})}addTrack(e){return g(this,null,function*(){var t;if(!this._peerConnection)return;let i=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info("is adding ".concat(e.kind," track to current published local ").concat(i?_.AUXILIARY:_.MAIN," stream")),(t=this._sei)==null||t.handleEncodedStreams(),Wt()?yield this.addTrackByTransceiver(e,i):yield this.addTrackBySender(e)})}addTrackByTransceiver(e,t){return g(this,null,function*(){var i;if(!e.mediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===_.AUDIO)yield r[0].sender.replaceTrack(e.outMediaTrack);else{let n=t?3:1;yield r[n].sender.replaceTrack(e.outMediaTrack),n===1&&((i=this.localMainVideoTrack)!=null&&i.small)&&(yield r[2].sender.replaceTrack(this._room.videoManager.smallTrack)),r[n].direction===Y.INACTIVE&&(yield this.setTransceiverDirection(Y.SENDONLY,[n]))}this.updateMediaSettings(),yield this.doPublishChange()})}addTrackBySender(e){return g(this,null,function*(){if(!e.outMediaTrack)return;let t=e.outMediaTrack;Si()&&this._peerConnection.getTransceivers().findIndex(r=>r.direction==="stopped")>=0&&(this._log.warn("transceiver is stopping, negotiate sdp first"),yield this.updateOffer("remove",t));let i=this._peerConnection.getSenders().find(r=>r.track&&r.track.kind===t.kind);if(i&&i.track){this._log.warn("sender already exists, remove sender first");let r=i.track;this.removeSender(i),yield this.updateOffer("remove",r)}if(t&&this._peerConnection.addTrack(t,new MediaStream([t])),t.kind===_.VIDEO&&e instanceof Je&&e.small){let r=new MediaStream,{smallTrack:n}=this._room.videoManager;r.addTrack(n),this._peerConnection.addTrack(n,r)}yield this.updateOffer("add",t)})}isNeedToResetOfferOrder(){if(this._sdpSemantics===Oo||!this._peerConnection||!this._peerConnection.localDescription)return!1;let{sdp:e}=this._peerConnection.localDescription,t=Se(e);for(let i=0;i<t.media.length;i++)if(Number(t.media[i].mid)===0&&t.media[i].type===_.VIDEO)return!0;return!1}removeSender(e){let t=null;Si()&&(t=this._peerConnection.getTransceivers().find(i=>i.sender&&i.sender.track===e.track)),this._peerConnection.removeTrack(e),t&&ne(t.stop)&&(this._log.info("stop transceiver"),t.stop())}removeTrack(e){return g(this,null,function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info("is removing ".concat(e.kind," track from current published local ").concat(t?_.AUXILIARY:_.MAIN," stream")),Wt()?yield this.removeTrackByTransceiver(e,t):yield this.removeTrackBySender(e)})}removeTrackByTransceiver(e,t){return g(this,null,function*(){if(!e.outMediaTrack)return;let i=this._peerConnection.getTransceivers();if(e.kind===_.AUDIO)yield i[0].sender.replaceTrack(null);else{let r=t?3:1;yield i[r].sender.replaceTrack(null),r===1&&e.small&&(yield i[2].sender.replaceTrack(null)),yield this.setTransceiverDirection(Y.INACTIVE,[r])}this.updateMediaSettings(),yield this.doPublishChange()})}setTransceiverDirection(e,t){return g(this,null,function*(){if(!ue)return;let i=!1,r=!1;this._log.info("setting transceiver ".concat(t.join(",")," direction to ").concat(e));let n=this._peerConnection.getTransceivers();if(t.forEach(c=>{n[c].direction!==e&&(n[c].direction=e,i=!0)}),i){this._log.info("updating offer");let c=yield this._peerConnection.createOffer();yield this._peerConnection.setLocalDescription(c)}let s=-1,a=this._peerConnection.remoteDescription.sdp.split(`\r
105
+ `).map(c=>{if(c.match(new RegExp("a=(".concat(Y.INACTIVE,"|").concat(Y.RECVONLY,"|").concat(Y.SENDONLY,")")))&&s++,t.includes(s)){if(e===Y.INACTIVE&&c.includes("a=".concat(Y.RECVONLY)))return r=!0,"a=".concat(e);if(e===Y.SENDONLY&&c.includes("a=".concat(Y.INACTIVE)))return r=!0,"a=".concat(Y.RECVONLY)}return c}).join(`\r
106
+ `);r&&(this._log.info("updating answer"),yield this._peerConnection.setRemoteDescription({type:"answer",sdp:a}))})}removeTrackBySender(e){return g(this,null,function*(){if(!e.outMediaTrack)return;if(e.kind===_.VIDEO&&this.isNeedToResetOfferOrder()&&this.localMainAudioTrack)return this.reset(),this.initialize(),void(yield this.publish({localAudioTrack:this.localMainAudioTrack,isAuxiliary:!1}));let t=this._peerConnection.getSenders().find(i=>i.track===e.outMediaTrack);t&&(this.removeSender(t),e.kind===_.VIDEO&&e.small&&this._peerConnection.getSenders().forEach(i=>{i.track&&i.track.kind===_.VIDEO&&this.removeSender(i)})),yield this.updateOffer("remove",e.outMediaTrack)})}replaceTrack(e){return g(this,null,function*(){var t;let i,r=(t=this._peerConnection)==null?void 0:t.getSenders();if(!r||r.length===0||!e.mediaTrack||(i=Wt()?e.kind===_.AUDIO?r[0]:r[1]:r.find(s=>s.track&&s.track.kind===e.kind),!i))return!1;let n=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;return this._log.info("is replacing ".concat(e.kind," track on ").concat(n?_.AUXILIARY:_.MAIN," stream")),e.kind===_.AUDIO?yield i.replaceTrack(e.outMediaTrack):e.kind===_.VIDEO&&(n?r[3]&&(yield r[3].replaceTrack(e.outMediaTrack)):yield i.replaceTrack(e.outMediaTrack)),!0})}updateOffer(e,t){return g(this,null,function*(){try{let i=yield this._peerConnection.createOffer(nI);ue&&i.sdp&&(i.sdp=this.setSDPDirection(i.sdp,"sendrecv")),yield this._peerConnection.setLocalDescription(i);let r=this.updateMediaSettings(),n={action:e,trackId:t.id,kind:t.kind===_.VIDEO?"bigVideo":t.kind,type:"offer",sdp:this._peerConnection.localDescription.sdp,constraintConfig:r,state:this.publishState};this._log.info("createOffer success, sending updated offer to remote server"),this._log.debug("updatedOffer: ".concat(n.sdp));let s=yield this._signalChannel.sendWaitForResponse({command:TU,data:n,responseCommand:K.UPDATE_OFFER_RESULT,timeout:Qy,commandDesc:"update offer"}),{code:a,message:c}=s.data;a!==0&&this.checkPublishResultCode(a,c),yield this.acceptAnswer(s.data.data),i.sdp&&this.updateSSRC(i.sdp)}catch(i){throw this._log.error(i),i}})}setBandwidth(e){return g(this,arguments,function(t){var i=this;let{bandwidth:r,type:n,videoType:s,sdp:a}=t;return function*(){if(!xh())return a?n===_.VIDEO?i.updateVideoBandwidthRestriction(a,r,s):i.updateAudioBandwidthRestriction(a,r):void 0;let c,o=i._peerConnection.getSenders();if(Wt()){let l=0;n===_.VIDEO&&(l=s===_.SMALL?2:s===_.AUXILIARY?3:1),c=o[l]}else c=o.find(l=>l.track&&l.track.kind===n);if(c){let l=c.getParameters();(!l.encodings||l.encodings.length===0)&&(l.encodings=[{}]),l.encodings[0].maxBitrate=1e3*r;try{return yield c.setParameters(l),i._log.info("".concat(s||"").concat(n," bandwidth ").concat(r," kbps")),a}catch(d){if(i._log.info("failed to set bandwidth by setting maxBitrate: ".concat(d)),a)return n===_.VIDEO?i.updateVideoBandwidthRestriction(a,r,s):i.updateAudioBandwidthRestriction(a,r)}}return a}()})}updateVideoBandwidthRestriction(e,t,i){let r="AS";ue&&(r="TIAS",t*=1e3);let n=0,s=-1;return i===_.SMALL?n=1:i===_.AUXILIARY&&(n=2),e=e.replace(/m=video (.*)\r\nc=IN (.*)\r\n/g,a=>(s+=1,s===n?"".concat(a,"b=").concat(r,":").concat(t,`\r
107
+ `):a))}updateAudioBandwidthRestriction(e,t){let i="AS";return ue&&(i="TIAS",t*=1e3),e=e.replace(/m=audio (.*)\r\nc=IN (.*)\r\n/,`m=audio $1\r
108
+ c=IN $2\r
109
+ b=`.concat(i,":").concat(t,`\r
110
+ `))}removeBandwidthRestriction(e){return e.replace(/b=AS:.*\r\n/,"").replace(/b=TIAS:.*\r\n/,"")}removeVideoOrientation(e){return e.replace(/urn:3gpp:video-orientation/,"")}connect(){return g(this,null,function*(){try{yield this.exchangeSDP(),yield this.waitForPeerConnectionConnected()}catch(e){throw this.closePeerConnection(!0),this.uninstallEvents(),e}})}exchangeSDP(){return g(this,null,function*(){try{yield this.createOffer(),this._log.info("createOffer success, sending offer to remote server"),yield this.doExchangeSDP()}catch(e){throw e}})}createOffer(){return g(this,null,function*(){try{let e=yield this._peerConnection.createOffer(nI);yield this._peerConnection.setLocalDescription(e),e.sdp&&this.updateSSRC(e.sdp)}catch(e){throw e}})}doExchangeSDP(){let e={command:vU,responseCommand:K.PUBLISH_RESULT,data:{type:this._peerConnection.localDescription.type,sdp:this.removeVideoOrientation(this._peerConnection.localDescription.sdp),screen:this.localMainVideoTrack instanceof dr||this.localAuxVideoTrack instanceof dr,state:this.publishState,constraintConfig:this._mediaSettings},enableLog:!1};return this._log.debug("sending sdp offer: ".concat(e.data.sdp)),this._signalChannel.sendWaitForResponse(e).then(t=>{let{code:i,message:r,data:n}=t.data;return i===0?this.acceptAnswer(n):this.checkPublishResultCode(i,r)})}setSDPDirection(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"all",r=Se(e);return r.media.forEach(n=>{(i==="all"||n.type===i)&&(n.direction=t)}),Di(r)}acceptAnswer(e){return g(this,null,function*(){var t,i,r,n,s;try{let a;if(this._publishingLocalAudioTrack||this._publishingLocalVideoTrack||this.isMainStreamPublished){let o=((t=this._publishingLocalVideoTrack)==null?void 0:t.profile.bitrate)||((i=this.localMainVideoTrack)==null?void 0:i.profile.bitrate),l=((r=this._publishingLocalAudioTrack)==null?void 0:r.profile.bitrate)||((n=this.localMainAudioTrack)==null?void 0:n.profile.bitrate);if(o){let d=this._isPublishingAux?_.AUXILIARY:_.BIG;a=yield this.setBandwidth({bandwidth:o,type:_.VIDEO,sdp:a,videoType:d})}l&&(a=yield this.setBandwidth({bandwidth:l,type:_.AUDIO,sdp:a}))}if(a=this.removeVideoOrientation(e.sdp),(s=this._publishingLocalVideoTrack)!=null&&s.small){let{smallStreamConfig:o}=this._room;a=yield this.setBandwidth({bandwidth:this._publishingLocalVideoTrack.small.bitrate||o.bitrate,type:_.VIDEO,videoType:_.SMALL,sdp:a})}let c={type:e.type,sdp:a};yield this._peerConnection.setRemoteDescription(c),this._log.debug("accepted answer: ".concat(a))}catch(a){throw this._log.error("failed to accept remote answer ".concat(a)),a}})}sendMutedFlag(e){var t,i,r;if(e===this.localAuxAudioTrack||e===this.localAuxVideoTrack)return;let n={audio:!((t=this.localMainAudioTrack)==null||!t.muted),bigVideo:!((i=this.localMainVideoTrack)==null||!i.muted),auxVideo:!((r=this.localAuxVideoTrack)==null||!r.muted)};this._log.info("send muted state: ".concat(JSON.stringify(n))),this._signalChannel.send(qv,n)}getIsReconnecting(){return this._isReconnecting}reconnect(){return g(this,null,function*(){if(!(it(sI.prototype,this,"beforeReconnect").call(this)<0))try{yield this._signalChannel.sendWaitForResponse({command:_p,responseCommand:K.UNPUBLISH_RESULT,enableLog:!1}),this.closePeerConnection(),this.initialize(),this.isMainStreamPublished&&(yield this.publish({localAudioTrack:this.localMainAudioTrack,localVideoTrack:this.localMainVideoTrack,isAuxiliary:!1})),this.isAuxStreamPublished&&(yield this.publish({localAudioTrack:this.localAuxAudioTrack,localVideoTrack:this.localAuxVideoTrack,isAuxiliary:!0})),this._log.warn("reconnect() uplink reconnect successfully"),this.stopReconnection()}catch{let t=ln(this._reconnectionCount);this._log.warn("reconnect() timeout, try again after ".concat(t/1e3,"s")),this._reconnectionTimer=setTimeout(()=>{this.clearReconnectionTimer(),this.reconnect()},t)}})}handleConnectionStateChange(e){e.state==="CONNECTED"&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&R.emit(A.SEND_FIRST_VIDEO_FRAME,{room:this._room})}updateSSRC(e){try{Se(e).media.forEach((t,i)=>{if(t.type===_.AUDIO){let r=t.ssrcs&&t.ssrcs[0];r&&(this.ssrc.audio=Number(r.id))}else{if(this._sdpSemantics===Oo&&t.ssrcGroups)return void t.ssrcGroups.forEach((n,s)=>{let a=Number(n.ssrcs.split(" ")[0]);s===0?this.ssrc.video=a:s===1&&(this.ssrc.small=a)});let r=t.ssrcs&&t.ssrcs[0];if(!r)return;switch(i){case 1:this.ssrc.video=Number(r.id);break;case 2:this.ssrc.small=Number(r.id);break;case 3:this.ssrc.auxiliary=Number(r.id)}}})}catch{}}getVideoTrackId(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:_.VIDEO;if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===_.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(e===_.VIDEO&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===_.VIDEO){let t=this.localMainVideoTrack.mediaTrack;if(t)return t.id}if(this.localAuxVideoTrack&&e===_.AUXILIARY){let t=this.localAuxVideoTrack.mediaTrack;if(t)return t.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,t){if(e!==0)throw e===Po?(this._log.error(ut.NOT_SUPPORTED_H264ENCODE),new N({code:C.NOT_SUPPORTED_H264,message:j({key:B.NOT_SUPPORTED_H264ENCODE})})):new N({code:C.UNKNOWN,message:j({key:B.SIGNAL_RESPONSE_FAILED,data:{signalResponse:K.PUBLISH_RESULT,code:e,message:t}})})}sendSEI(e,t){var i;(i=this._sei)==null||i.push(e,t)}},yp=sI;k([ae(e=>function(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];return new Promise((n,s)=>{let a=c=>{this._emitter.off("closed",a),s(new N({code:C.API_CALL_ABORTED,message:j({key:B.CONNECTION_ABORTED,data:c})}))};this._emitter.on("closed",a),e.apply(this,i).then(n,s).finally(()=>{this._emitter.off("closed",a)})})})],yp.prototype,"publish"),k([np(fr.prototype.afterConnect),_v(fr.prototype.beforeConnect)],yp.prototype,"connect");var Sp=yp,BU=class{constructor(e,t){this.room=e,h(this,"_log"),h(this,"_prevReportTime",0),h(this,"_prevReport",{}),h(this,"_prevStats",null),h(this,"_prevEncoderImplementation",""),h(this,"_prevQualityLimitationReason",""),h(this,"_prevAuxQualityLimitationReason",""),h(this,"_prevDecoderImplementationMap",new Map),h(this,"totalBytesSent",0),h(this,"totalBytesReceived",0),h(this,"_spcStats",null),this._log=t}get statInterval(){return this._prevReportTime===0?2:(Date.now()-this._prevReportTime)/1e3}getSenderStats(e){return g(this,null,function*(){let t={audio:{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0},video:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},small:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},auxiliary:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},rtt:0},i=e.getPeerConnection(),r=e.getSSRC();if(i)try{if((this._spcStats||(yield i.getStats())).forEach(n=>{var s,a,c;if(n.type==="outbound-rtp")if((n.mediaType||n.kind)===_.VIDEO){let o,l;if(n.ssrc===r.video?(o=_.VIDEO,l=e.localMainVideoTrack):n.ssrc===r.small?o=_.SMALL:n.ssrc===r.auxiliary&&(l=e.localAuxVideoTrack,o=_.AUXILIARY),!o)return;if(t[o].bytesSent=n.bytesSent,t[o].packetsSent=n.packetsSent,t[o].framesEncoded=n.framesEncoded,I(n.keyFramesEncoded)||(t[o].keyFramesEncoded=n.keyFramesEncoded),I(n.nackCount)||(t[o].nackCount=n.nackCount),I(n.pliCount)||(t[o].pliCount=n.pliCount),I(n.retransmittedPacketsSent)||(t[o].retransmittedPacketsSent=n.retransmittedPacketsSent),I(n.totalEncodeTime)||(t[o].totalEncodeTime=n.totalEncodeTime),I(n.totalPacketSendDelay)||(t[o].totalPacketSendDelay=n.totalPacketSendDelay),n.ssrc===r.video){if(!I(n.encoderImplementation)&&this._prevEncoderImplementation!==n.encoderImplementation){R.emit("262",{userId:e.userId,prevImplementation:this._prevEncoderImplementation,implementation:n.encoderImplementation,codec:e.videoCodec,isHWCodec:n.powerEfficientEncoder}),this._prevEncoderImplementation=n.encoderImplementation;let d="".concat(n.encoderImplementation,"(").concat(e.videoCodec,")");this._log.info("encoderImplementation change to ".concat(d," HWEncoder: ").concat(n.powerEfficientEncoder))}!I(n.qualityLimitationReason)&&n.bytesSent!==0&&this._prevQualityLimitationReason!==n.qualityLimitationReason&&(this._log.info("qualityLimitationReason change to ".concat(n.qualityLimitationReason)),R.emit("263",{userId:e.userId,reason:n.qualityLimitationReason,prevReason:this._prevQualityLimitationReason,streamType:2,isQosClearFirst:(s=e.localMainVideoTrack)==null?void 0:s.isQosClearFirst}),this._prevQualityLimitationReason=n.qualityLimitationReason)}else n.ssrc===r.auxiliary&&!I(n.qualityLimitationReason)&&n.bytesSent!==0&&this._prevAuxQualityLimitationReason!==n.qualityLimitationReason&&(this._log.info("aux qualityLimitationReason change to ".concat(n.qualityLimitationReason)),R.emit("263",{userId:e.userId,reason:n.qualityLimitationReason,prevReason:this._prevAuxQualityLimitationReason,streamType:7,isQosClearFirst:(a=e.localAuxVideoTrack)==null?void 0:a.isQosClearFirst}),this._prevAuxQualityLimitationReason=n.qualityLimitationReason)}else t.audio.bytesSent=n.bytesSent,t.audio.packetsSent=n.packetsSent;else n.type==="candidate-pair"?Us(n)&&ge(n.currentRoundTripTime)&&(t.rtt=Math.floor(1e3*n.currentRoundTripTime),this.totalBytesSent=n.bytesSent):n.type==="media-source"&&(n.kind===_.AUDIO?(t.audio.audioLevel=n.audioLevel||0,t.audio.totalAudioEnergy=n.totalAudioEnergy||0,n.echoReturnLoss,n.totalSamplesDuration&&(t.audio.totalSamplesDuration=n.totalSamplesDuration)):n.kind===_.VIDEO&&(n.trackIdentifier===e.getVideoTrackId(_.VIDEO)?t.video.fpsCapture=n.framesPerSecond:n.trackIdentifier===e.getVideoTrackId(_.AUXILIARY)?t.auxiliary.fpsCapture=n.framesPerSecond:t.small.fpsCapture=n.framesPerSecond));if(!I(n.audioLevel)&&((c=e.localMainAudioTrack)!=null&&c.mediaTrack)&&n.trackIdentifier===e.localMainAudioTrack.mediaTrack.id&&(t.audio.audioLevel=n.audioLevel||0),!I(n.frameWidth)){let o=_.SMALL;n.trackIdentifier===e.getVideoTrackId(_.VIDEO)||n.ssrc===r.video?o=_.VIDEO:(n.trackIdentifier===e.getVideoTrackId(_.AUXILIARY)||n.ssrc===r.auxiliary)&&(o=_.AUXILIARY),t[o].frameWidth=n.frameWidth,t[o].frameHeight=n.frameHeight,t[o].framesSent=n.framesSent}}),e.localMainAudioTrack){let n=e.localMainAudioTrack.getInternalAudioLevel();t.audio.micAudioLevel=n,t.audio.audioLevel===0&&(t.audio.audioLevel=n)}this.totalBytesSent||(this.totalBytesSent+=t.audio.bytesSent+t.video.bytesSent+t.auxiliary.bytesSent)}catch(n){this._log.warn("failed to getStats on sender connection ".concat(n))}return t})}getReceiverStats(e){return g(this,null,function*(){let t={tinyId:e.tinyId,userId:e.userId,rtt:0,hasAudio:!1,hasVideo:!1,hasAuxiliary:!1,isSmallSubscribed:!1,audio:{bytesReceived:0,packetsReceived:0,packetsLost:0,p2pDelay:0,totalJitter:0,totalJitterCount:0,audioLevel:0,totalAudioEnergy:0,insertedSamplesForDeceleration:0,removedSamplesForAcceleration:0},video:{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,fpsDecoded:0,freezeCount:0,totalFreezesDuration:0,totalJitter:0,totalJitterCount:0},auxiliary:{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,fpsDecoded:0,totalJitter:0,totalJitterCount:0}},i=e.getPeerConnection();if(i)try{let{ssrc:r}=e,{muteState:n,subscribeState:s}=e;(this._spcStats||(yield i.getStats())).forEach(a=>{if(a.type==="inbound-rtp"){let c=(a.mediaType||a.kind)===_.AUDIO;if(c){if(a.ssrc!==r.audio||!n.hasAudio)return;t.audio.packetsReceived=a.packetsReceived,t.audio.bytesReceived=a.bytesReceived,t.audio.packetsLost=a.packetsLost,a.insertedSamplesForDeceleration&&(t.audio.insertedSamplesForDeceleration=a.insertedSamplesForDeceleration),a.removedSamplesForAcceleration&&(t.audio.removedSamplesForAcceleration=a.removedSamplesForAcceleration),a.totalSamplesDuration&&(t.audio.totalSamplesDuration=a.totalSamplesDuration),a.totalSamplesReceived&&(t.audio.totalSamplesReceived=a.totalSamplesReceived),a.concealedSamples&&(t.audio.concealedSamples=a.concealedSamples);let{remoteAudioTrack:o}=e;o.stat.packetsReceived=a.packetsReceived,o.stat.bytesReceived=a.bytesReceived,o.stat.packetsLost=a.packetsLost,t.audio.p2pDelay=o.stat.end2EndDelay,t.hasAudio=!0}else{if(ue&&a.bytesReceived===0)return;let o;a.ssrc===r.video&&n.hasVideo&&(t.video.packetsReceived=a.packetsReceived,t.video.bytesReceived=a.bytesReceived,t.video.packetsLost=a.packetsLost,t.video.framesReceived=a.framesReceived,t.video.framesDecoded=a.framesDecoded,t.video.fpsDecoded=a.framesPerSecond,t.hasVideo=!0,o=e.remoteVideoTrack,n.hasSmall&&s.smallVideo&&(t.isSmallSubscribed=!0),a.decoderImplementation&&(!this._prevDecoderImplementationMap.has(t.userId)||this._prevDecoderImplementationMap.get(t.userId)!==a.decoderImplementation)&&(this._log.info("".concat(t.userId," decoderImplementation change to ").concat(a.decoderImplementation," HWDecoder: ").concat(a.powerEfficientDecoder)),R.emit("262",{userId:this.room.userId,remoteUserId:t.userId,prevImplementation:this._prevDecoderImplementationMap.get(t.userId),implementation:a.decoderImplementation,codec:e.videoCodec,isHWCodec:a.powerEfficientDecoder}),this._prevDecoderImplementationMap.set(t.userId,a.decoderImplementation))),a.ssrc===r.auxiliary&&n.hasAuxiliary&&(t.auxiliary.packetsReceived=a.packetsReceived,t.auxiliary.bytesReceived=a.bytesReceived,t.auxiliary.packetsLost=a.packetsLost,t.auxiliary.framesReceived=a.framesReceived,t.auxiliary.framesDecoded=a.framesDecoded,t.auxiliary.fpsDecoded=a.framesPerSecond,o=e.remoteAuxiliaryTrack,t.hasAuxiliary=!0),o&&(o.stat.packetsReceived=a.packetsReceived,o.stat.bytesReceived=a.bytesReceived,o.stat.packetsLost=a.packetsLost,o.stat.framesReceived=a.framesReceived,o.stat.framesDecoded=a.framesDecoded,a.jitterBufferDelay&&(o.stat.jitterBufferDelay=Math.floor(a.jitterBufferDelay/a.jitterBufferEmittedCount*1e3)))}a.jitterBufferDelay&&(c?(t.audio.totalJitter=a.jitterBufferDelay,t.audio.totalJitterCount=a.jitterBufferEmittedCount):a.ssrc===r.video&&n.hasVideo?(t.video.totalJitter=a.jitterBufferDelay,t.video.totalJitterCount=a.jitterBufferEmittedCount):a.ssrc===r.auxiliary&&n.hasAuxiliary&&(t.auxiliary.totalJitter=a.jitterBufferDelay,t.auxiliary.totalJitterCount=a.jitterBufferEmittedCount))}else a.type==="candidate-pair"&&Us(a)&&ge(a.currentRoundTripTime)&&(t.rtt=Math.floor(1e3*a.currentRoundTripTime),this.totalBytesReceived=a.bytesReceived);I(a.frameWidth)||((a.trackIdentifier===e.getMainStreamVideoTrackId()||a.ssrc===r.video)&&(t.video.frameWidth=a.frameWidth,t.video.frameHeight=a.frameHeight,e.remoteVideoTrack.stat.frameWidth=a.frameWidth,e.remoteVideoTrack.stat.frameHeight=a.frameHeight),(a.trackIdentifier===e.getAuxStreamVideoTrackId()||a.ssrc===r.auxiliary)&&(t.auxiliary.frameWidth=a.frameWidth,t.auxiliary.frameHeight=a.frameHeight,e.remoteAuxiliaryTrack.stat.frameWidth=a.frameWidth,e.remoteAuxiliaryTrack.stat.frameHeight=a.frameHeight)),!I(a.audioLevel)&&e.muteState.audioAvailable&&e.remoteAudioTrack.mediaTrack&&a.trackIdentifier===e.remoteAudioTrack.mediaTrack.id&&(t.audio.audioLevel=a.audioLevel||0,t.audio.totalAudioEnergy=a.totalAudioEnergy||0)}),t.audio.audioLevel===0&&e.muteState.audioAvailable&&(t.audio.audioLevel=e.remoteAudioTrack.getInternalAudioLevel()||0),this.totalBytesReceived||(this.totalBytesReceived+=t.audio.bytesReceived+t.video.bytesReceived+t.auxiliary.bytesReceived)}catch(r){this._log.warn("failed to getStats on receiver connection ".concat(r))}return t})}getStats(e,t){return g(this,null,function*(){let i={},r=[];if(this.room.singlePC){let n=this.room.singlePC.getPeerConnection();if(!n)return{senderStats:i,receiverStats:r};let s=W(),a=yield n.getStats(),c=W();c-s>2e3&&this._log.warn("getStats cost ".concat(c-s,"ms"));let o=[],l=new Set(["inbound-rtp","outbound-rtp","track","candidate-pair","media-source"]);a.forEach(d=>l.has(d.type)&&o.push(d)),this._spcStats=o}e&&(i=yield this.getSenderStats(e));for(let[n,s]of t){let a=yield this.getReceiverStats(s);r.push(a)}return{senderStats:i,receiverStats:r}})}getDifferenceValue(e,t){if(Ri(e))return t;let i=t-e;return i<0?0:i}prepareReport(e){let{stats:t,report:i,freezeMap:r}=e;var n;if(!Ri(t.senderStats)){let u={uint32_audio_level:t.senderStats.audio.audioLevel*_i,uint32_audio_energy:1e6*t.senderStats.audio.totalAudioEnergy,uint32_audio_codec_bitrate:t.senderStats.audio.bytesSent};t.senderStats.audio.micAudioLevel&&(u.uint32_mic_audio_level=t.senderStats.audio.micAudioLevel*_i),t.senderStats.audio.totalSamplesDuration&&(i.msg_device_info.uint32_audio_capture_cost=t.senderStats.audio.totalSamplesDuration);let p=[];if(t.senderStats.video.bytesSent){let f={uint32_video_stream_type:2,uint32_video_codec_fps:t.senderStats.video.framesSent,uint32_video_capture_fps:t.senderStats.video.fpsCapture,uint32_video_width:t.senderStats.video.frameWidth,uint32_video_height:t.senderStats.video.frameHeight,uint32_video_codec_bitrate:t.senderStats.video.bytesSent,uint32_video_enc_fps:t.senderStats.video.framesEncoded,uint32_key_frame_count:t.senderStats.video.keyFramesEncoded,uint32_nack_count:t.senderStats.video.nackCount,uint32_pli_count:t.senderStats.video.pliCount,uint32_encode_cost:1e3*(t.senderStats.video.totalEncodeTime||0),uint32_send_packet_cost:1e3*(t.senderStats.video.totalPacketSendDelay||0),uint32_video_arq_packets:t.senderStats.video.retransmittedPacketsSent};p.push(f)}if(t.senderStats.small.bytesSent){let f={uint32_video_stream_type:3,uint32_video_codec_fps:t.senderStats.small.framesSent||0,uint32_video_capture_fps:t.senderStats.small.fpsCapture||0,uint32_video_width:t.senderStats.small.frameWidth||0,uint32_video_height:t.senderStats.small.frameHeight||0,uint32_video_codec_bitrate:t.senderStats.small.bytesSent,uint32_video_enc_fps:t.senderStats.small.framesEncoded||0,uint32_key_frame_count:t.senderStats.small.keyFramesEncoded,uint32_nack_count:t.senderStats.small.nackCount,uint32_pli_count:t.senderStats.small.pliCount,uint32_encode_cost:1e3*(t.senderStats.small.totalEncodeTime||0),uint32_send_packet_cost:1e3*(t.senderStats.small.totalPacketSendDelay||0),uint32_video_arq_packets:t.senderStats.small.retransmittedPacketsSent};p.push(f)}if(t.senderStats.auxiliary.bytesSent){let f={uint32_video_stream_type:7,uint32_video_codec_fps:t.senderStats.auxiliary.framesSent||0,uint32_video_capture_fps:t.senderStats.auxiliary.fpsCapture||0,uint32_video_width:t.senderStats.auxiliary.frameWidth||0,uint32_video_height:t.senderStats.auxiliary.frameHeight||0,uint32_video_codec_bitrate:t.senderStats.auxiliary.bytesSent,uint32_video_enc_fps:t.senderStats.auxiliary.framesEncoded||0,uint32_key_frame_count:t.senderStats.auxiliary.keyFramesEncoded,uint32_nack_count:t.senderStats.auxiliary.nackCount,uint32_pli_count:t.senderStats.auxiliary.pliCount,uint32_encode_cost:1e3*(t.senderStats.auxiliary.totalEncodeTime||0),uint32_send_packet_cost:1e3*(t.senderStats.auxiliary.totalPacketSendDelay||0),uint32_video_arq_packets:t.senderStats.auxiliary.retransmittedPacketsSent};p.push(f)}let m={uint32_bitrate:0,uint32_lost:0,uint32_rtt:t.senderStats.rtt};i.msg_up_stream_info={msg_audio_status:u,msg_video_status:p,msg_network_status:m}}let{statInterval:s}=this;i.msg_down_stream_info=[],t.receiverStats.forEach(u=>{let p={msg_user_info:{str_identifier:u.userId,uint64_tinyid:u.tinyId},msg_network_status:{uint32_rtt:u.rtt,uint32_bitrate:0,uint32_lost:0},msg_audio_status:{},msg_video_status:[]};if(u.hasAudio){let m={uint32_audio_p2p_delay:u.audio.p2pDelay,uint32_audio_cache_ms:u.audio.totalJitter,uint32_audio_cache_ms_count:u.audio.totalJitterCount,uint32_audio_codec_bitrate:u.audio.bytesReceived,uint32_audio_total_bitrate:u.audio.bytesReceived,uint32_audio_level:1e8*u.audio.audioLevel,uint32_audio_energy:1e6*u.audio.totalAudioEnergy,uint32_audio_receive:u.audio.packetsReceived,uint32_audio_origin_lost:u.audio.packetsLost};p.msg_audio_status=m}if(u.hasVideo){let m=r.get("".concat(u.userId,"_").concat(zy)),f=m?m.duration:0,T={uint32_video_stream_type:u.isSmallSubscribed?3:2,uint32_video_receive_fps:u.video.framesReceived,uint32_video_width:u.video.frameWidth,uint32_video_height:u.video.frameHeight,uint32_video_codec_bitrate:u.video.bytesReceived,uint32_video_receive:u.video.packetsReceived,uint32_video_origin_lost:u.video.packetsLost,uint32_video_block_time:f,uint32_video_dec_fps:u.video.framesDecoded,uint32_video_cache_ms:u.video.totalJitter,uint32_video_cache_ms_count:u.video.totalJitterCount};p.msg_video_status.push(T)}if(u.hasAuxiliary){let m=r.get("".concat(u.userId,"_").concat(Ky)),f=m?m.duration:0,T={uint32_video_stream_type:7,uint32_video_receive_fps:u.auxiliary.framesReceived,uint32_video_width:u.auxiliary.frameWidth,uint32_video_height:u.auxiliary.frameHeight,uint32_video_codec_bitrate:u.auxiliary.bytesReceived,uint32_video_receive:u.auxiliary.packetsReceived+u.auxiliary.packetsLost,uint32_video_origin_lost:u.auxiliary.packetsLost,uint32_video_block_time:f,uint32_video_dec_fps:u.auxiliary.framesDecoded,uint32_video_cache_ms:u.auxiliary.totalJitter,uint32_video_cache_ms_count:u.auxiliary.totalJitterCount};p.msg_video_status.push(T)}i.msg_down_stream_info.push(p)});let a=this._prevReport,c=this._prevStats;if(this._prevReport=JSON.parse(JSON.stringify(i)),this._prevStats=JSON.parse(JSON.stringify(t)),i.msg_up_stream_info.msg_audio_status&&a.msg_up_stream_info.msg_audio_status){let u=a.msg_up_stream_info.msg_audio_status,p=i.msg_up_stream_info.msg_audio_status;if(u.uint32_audio_codec_bitrate===0)p.uint32_audio_codec_bitrate=0;else{let m=this.getDifferenceValue(u.uint32_audio_codec_bitrate,p.uint32_audio_codec_bitrate);p.uint32_audio_codec_bitrate=Math.round(8*m/s),i.msg_up_stream_info.msg_network_status.uint32_bitrate+=p.uint32_audio_codec_bitrate}(n=a.msg_device_info)!=null&&n.uint32_audio_capture_cost?i.msg_device_info.uint32_audio_capture_cost=2*Math.floor(1e3*this.getDifferenceValue(a.msg_device_info.uint32_audio_capture_cost,i.msg_device_info.uint32_audio_capture_cost)/s):delete i.msg_device_info.uint32_audio_capture_cost}let o=a.msg_up_stream_info.msg_video_status;i.msg_up_stream_info.msg_video_status.forEach(u=>{let p=o.find(y=>y.uint32_video_stream_type===u.uint32_video_stream_type);if(!p||p.uint32_video_codec_bitrate===0)return u.uint32_video_codec_bitrate=0,u.uint32_video_enc_fps=0,void(u.uint32_video_codec_fps=0);let m=0,f=0,T=0;p&&u.uint32_video_codec_bitrate>=p.uint32_video_codec_bitrate&&(m=p.uint32_video_codec_bitrate,f=p.uint32_video_enc_fps,T=p.uint32_video_codec_fps);let S=this.getDifferenceValue(m,u.uint32_video_codec_bitrate);u.uint32_video_codec_bitrate=Math.round(8*S/s),i.msg_up_stream_info.msg_network_status.uint32_bitrate+=u.uint32_video_codec_bitrate,u.uint32_video_enc_fps=Math.round(this.getDifferenceValue(f,u.uint32_video_enc_fps)/s),u.uint32_video_codec_fps=Math.round(this.getDifferenceValue(T,u.uint32_video_codec_fps)/s),sn&&Ns()===115&&p.uint32_video_width===0&&p.uint32_video_height===0&&p.uint32_video_codec_fps===0&&(u.uint32_video_codec_fps=u.uint32_video_enc_fps),I(p.uint32_key_frame_count)||(u.uint32_key_frame_count=Math.round(this.getDifferenceValue(p.uint32_key_frame_count,u.uint32_key_frame_count))),I(p.uint32_nack_count)||(u.uint32_nack_count=Math.round(this.getDifferenceValue(p.uint32_nack_count,u.uint32_nack_count))),I(p.uint32_pli_count)||(u.uint32_pli_count=Math.round(this.getDifferenceValue(p.uint32_pli_count,u.uint32_pli_count))),I(p.uint32_video_arq_packets)||(u.uint32_video_arq_packets=Math.round(this.getDifferenceValue(p.uint32_video_arq_packets,u.uint32_video_arq_packets))),I(p.uint32_encode_cost)||(u.uint32_encode_cost=Math.round(this.getDifferenceValue(p.uint32_encode_cost,u.uint32_encode_cost)/s)),I(p.uint32_send_packet_cost)||(u.uint32_send_packet_cost=Math.round(this.getDifferenceValue(p.uint32_send_packet_cost,u.uint32_send_packet_cost)/s))});let l=a.msg_down_stream_info;i.msg_down_stream_info=i.msg_down_stream_info.filter(u=>l.find(p=>p.msg_user_info.uint64_tinyid===u.msg_user_info.uint64_tinyid));let d=i.msg_down_stream_info;return d.forEach(u=>{let p=l.find(m=>m.msg_user_info.uint64_tinyid===u.msg_user_info.uint64_tinyid);if(Ri(u.msg_audio_status)||Ri(p.msg_audio_status))u.msg_audio_status={};else{let m=u.msg_audio_status,f=p.msg_audio_status,T=this.getDifferenceValue(f.uint32_audio_cache_ms_count,m.uint32_audio_cache_ms_count);delete m.uint32_audio_cache_ms_count,m.uint32_audio_cache_ms=Math.floor(1e3*this.getDifferenceValue(f.uint32_audio_cache_ms,m.uint32_audio_cache_ms)/T)||0;let S=this.room.remotePublishedUserMap.get(u.msg_user_info.str_identifier);S&&(S.remoteAudioTrack.stat.jitterBufferDelay=m.uint32_audio_cache_ms),m.uint32_audio_origin_lost=this.getDifferenceValue(f.uint32_audio_origin_lost,m.uint32_audio_origin_lost),m.uint32_audio_receive=this.getDifferenceValue(f.uint32_audio_receive,m.uint32_audio_receive),m.uint32_audio_receive+=m.uint32_audio_origin_lost;let y=this.getDifferenceValue(f.uint32_audio_codec_bitrate,m.uint32_audio_codec_bitrate);m.uint32_audio_codec_bitrate=Math.round(8*y/s),m.uint32_audio_total_bitrate=Math.round(8*y/s)}if(u.msg_video_status&&p.msg_video_status){let m=p.msg_video_status;u.msg_video_status=u.msg_video_status.filter(f=>m.find(T=>T.uint32_video_stream_type===f.uint32_video_stream_type)),u.msg_video_status.forEach(f=>{let T=m.find(Qt=>Qt.uint32_video_stream_type===f.uint32_video_stream_type),S=T.uint32_video_receive,y=T.uint32_video_origin_lost,E=T.uint32_video_codec_bitrate,D=T.uint32_video_receive_fps,P=T.uint32_video_dec_fps;f.uint32_video_origin_lost=this.getDifferenceValue(y,f.uint32_video_origin_lost),f.uint32_video_receive=this.getDifferenceValue(S,f.uint32_video_receive)+f.uint32_video_origin_lost;let Q=this.getDifferenceValue(E,f.uint32_video_codec_bitrate);f.uint32_video_codec_bitrate=Math.round(8*Q/s);let q=this.getDifferenceValue(D,f.uint32_video_receive_fps);f.uint32_video_receive_fps=Math.round(q/s),f.uint32_video_dec_fps=Math.round(this.getDifferenceValue(P,f.uint32_video_dec_fps)/s);let U=this.getDifferenceValue(T.uint32_video_cache_ms_count,f.uint32_video_cache_ms_count);delete f.uint32_video_cache_ms_count,f.uint32_video_cache_ms=Math.floor(1e3*this.getDifferenceValue(T.uint32_video_cache_ms,f.uint32_video_cache_ms)/U)||0})}}),c&&t.receiverStats.forEach(u=>{if(u.audio.concealedSamples&&u.audio.totalSamplesReceived){let p=c.receiverStats.find(m=>m.userId===u.userId);if(p&&p.audio.concealedSamples&&p.audio.totalSamplesReceived){let m=u.audio.concealedSamples-p.audio.concealedSamples,f=u.audio.totalSamplesReceived-p.audio.totalSamplesReceived,T=Math.floor(m/f*1e3*s);if(T>s/5){let S=d.find(y=>y.msg_user_info.str_identifier===u.userId);S&&(S.msg_audio_status.uint32_audio_block_time=T)}}}}),i}getStatsReport(e){return g(this,arguments,function(t){var i=this;let{uplinkConnection:r,downlinkConnections:n,freezeMap:s}=t;return function*(){let a={msg_device_info:{},msg_up_stream_info:{msg_audio_status:{uint32_audio_format:11,uint32_audio_sample_rate:0,uint32_audio_codec_bitrate:0,uint32_audio_receive:0,uint32_audio_origin_lost:0,uint32_audio_level:0,uint32_audio_energy:0},msg_video_status:[],msg_network_status:{uint32_bitrate:0,uint32_rtt:0,uint32_lost:0}},msg_down_stream_info:[{msg_user_info:{str_identifier:"",uint64_tinyid:0},msg_audio_status:{uint32_audio_cache_ms:0,uint32_audio_format:11,uint32_audio_sample_rate:0,uint32_audio_codec_bitrate:0,uint32_audio_total_bitrate:0,uint32_audio_level:0,uint32_audio_energy:0,uint32_audio_receive:0,uint32_audio_origin_lost:0,uint32_audio_final_lost:0},msg_video_status:[{uint32_video_cache_ms:0,uint32_video_stream_type:0,uint32_video_receive_fps:0,uint32_video_width:0,uint32_video_height:0,uint32_video_codec_bitrate:0,uint32_video_receive:0,uint32_video_origin_lost:0,uint32_video_block_time:0,uint32_video_dec_fps:0}],msg_network_status:{uint32_bitrate:0,uint32_rtt:0,uint32_lost:0}}]},c=yield i.getStats(r,n);return JSON.stringify(i._prevReport)==="{}"&&(i._prevReport=JSON.parse(JSON.stringify(a))),i.prepareReport({stats:c,report:a,freezeMap:s}),i._prevReportTime=Date.now(),a}()})}reset(){this._prevReportTime=0,this._prevReport={},this._prevEncoderImplementation="",this._prevQualityLimitationReason="",this._prevDecoderImplementationMap=new Map}},HU=Ie(Ve()),aI=class extends HU.default{constructor(e){let{signalChannel:t,room:i}=e;super(),h(this,"_room"),h(this,"_signalChannel"),h(this,"_log"),h(this,"_uplinkRTT",0),h(this,"_uplinkLoss",0),h(this,"_downlinkRTT",0),h(this,"_downlinkLoss",0),h(this,"_downlinkPrevStatMap",new Map),h(this,"_downlinkLossAndRTTMap",new Map),h(this,"_interval",-1),h(this,"_uplinkNetworkQuality",0),h(this,"_downlinkNetworkQuality",0),this._room=i,this._signalChannel=t,this._log=b.createLogger({id:"q",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),this.initialize()}get uplinkNetworkQuality(){return this._uplinkNetworkQuality}set uplinkNetworkQuality(e){e!==this._uplinkNetworkQuality&&this._log.info("uplink ".concat(this.uplinkNetworkQuality," -> ").concat(e,", rtt: ").concat(this._uplinkRTT,", loss: ").concat(this._uplinkLoss)),this._uplinkNetworkQuality=e}get downlinkNetworkQuality(){return this._downlinkNetworkQuality}set downlinkNetworkQuality(e){if(e!==this._downlinkNetworkQuality){let{rtt:t,loss:i}=this.getAverageLossAndRTT([...this._downlinkLossAndRTTMap.values()]);this._log.info("downlink ".concat(this.downlinkNetworkQuality," -> ").concat(e,", rtt: ").concat(t,", loss: ").concat(i))}this._downlinkNetworkQuality=e}initialize(){this._signalChannel.on(K.UPLINK_NETWORK_STATS,e=>{this.handleUplinkNetworkQuality(e)}),this._signalChannel.on(mp,this.handleSignalConnectionStateChange.bind(this)),this.start()}handleUplinkNetworkQuality(e){var t,i;if(e.data.code!==0)return;let r=e.data.data;if(r.delay&&this.updateDelay(r.delay),!this._room.uplinkConnection)return this.uplinkNetworkQuality=0,this._uplinkLoss=0,void(this._uplinkRTT=0);let n=(i=(t=this._room)==null?void 0:t.uplinkConnection)==null?void 0:i.getPeerConnection();if(n&&this.isPeerConnectionDisconnected(n))return this.uplinkNetworkQuality=6,this._uplinkLoss=0,void(this._uplinkRTT=0);let s=r.expectAudPkg+r.expectVidPkg,a=r.recvAudPkg+r.recvVidPkg,c=s-a;s===0&&a===0||(this._uplinkLoss=c<=0?0:Math.round(c/s*100),this._uplinkRTT=r.rtt,this.uplinkNetworkQuality=this.getNetworkQuality(this._uplinkLoss,this._uplinkRTT))}handleDownlinkNetworkQuality(){return g(this,null,function*(){if(this._room.remotePublishedUserMap.size===0)return void(this.downlinkNetworkQuality=0);let e=[...this._room.remotePublishedUserMap.values()],t=e.filter(n=>{var s;return((s=n.getPeerConnection())==null?void 0:s.connectionState)===fe.CONNECTED});if(e.filter(n=>this.isPeerConnectionDisconnected(n.getPeerConnection())).length===e.length)return void(this.downlinkNetworkQuality=6);for(let n=0;n<t.length;n++){let s=t[n].getPeerConnection();if(!s)return;let{rtt:a,totalPacketsLost:c,totalPacketsReceived:o}=yield this.getStat(s);if(!this._downlinkPrevStatMap.has(s)){this._downlinkPrevStatMap.set(s,{totalPacketsLost:c,totalPacketsReceived:o});continue}let l=0,d=this._downlinkPrevStatMap.get(s),u=c-d.totalPacketsLost,p=o-d.totalPacketsReceived;l=u<=0||p<0?0:Math.round(u/(u+p)*100),this._downlinkPrevStatMap.set(s,{totalPacketsLost:c,totalPacketsReceived:o}),this._downlinkLossAndRTTMap.set(s,{rtt:a,loss:l,userId:t[n].getUserId(),audioDelay:t[n].remoteAudioTrack.stat.end2EndDelay,videoDelay:t[n].remoteVideoTrack.stat.end2EndDelay})}if([...this._downlinkPrevStatMap.keys()].forEach(n=>{this.isPeerConnectionDisconnected(n)&&(this._downlinkPrevStatMap.delete(n),this._downlinkLossAndRTTMap.delete(n))}),this._downlinkLossAndRTTMap.size===0)return;let{rtt:i,loss:r}=this.getAverageLossAndRTT([...this._downlinkLossAndRTTMap.values()]);this._downlinkRTT=i,this._downlinkLoss=r,this.downlinkNetworkQuality=this.getNetworkQuality(r,i)})}getStat(e){return g(this,null,function*(){let t={rtt:0,totalPacketsLost:0,totalPacketsReceived:0};if(!e||!ic())return t;let i=e.getReceivers();try{for(let r=0;r<i.length;r++)(yield i[r].getStats()).forEach(n=>{n.type==="candidate-pair"&&ge(n.currentRoundTripTime)&&(t.rtt=Math.round(1e3*n.currentRoundTripTime)),n.type==="inbound-rtp"&&(n.mediaType===_.AUDIO||n.mediaType===_.VIDEO)&&(t.totalPacketsLost+=n.packetsLost,t.totalPacketsReceived+=n.packetsReceived)});return t}catch{return t}})}getAverageLossAndRTT(e){let t={rtt:0,loss:0};return Array.isArray(e)&&e.length>0&&(e.forEach(i=>{t.rtt+=i.rtt,t.loss+=i.loss}),Object.keys(t).forEach(i=>{t[i]=Math.round(t[i]/e.length)})),t}getNetworkQuality(e,t){return e>50||t>500?5:e>30||t>350?4:e>20||t>200?3:e>10||t>100?2:e>=0||t>=0?1:0}handleSignalConnectionStateChange(e){e.state==="DISCONNECTED"?(this._uplinkRTT=0,this._uplinkLoss=0,this.uplinkNetworkQuality=6):e.state==="CONNECTED"&&this.uplinkNetworkQuality===6&&(this.uplinkNetworkQuality=5)}handleUplinkConnectionStateChange(e){let{state:t}=e;t==="DISCONNECTED"?(this._uplinkLoss=0,this._uplinkRTT=0,this.uplinkNetworkQuality=6):t==="CONNECTED"&&this.uplinkNetworkQuality===6&&(this.uplinkNetworkQuality=5)}isPeerConnectionDisconnected(e){return!(!e||e.connectionState!==fe.DISCONNECTED&&e.connectionState!==fe.FAILED&&e.connectionState!==fe.CLOSED)}setUplinkConnection(e){this._room.uplinkConnection=e,this._room.uplinkConnection?this._room.uplinkConnection.on("connection-state-changed",this.handleUplinkConnectionStateChange.bind(this)):(this.uplinkNetworkQuality=0,this._uplinkRTT=0,this._uplinkLoss=0)}start(){this._interval===-1?(this._log.debug("start network quality calculating"),this._interval=_e.run(Es,()=>{this.handleDownlinkNetworkQuality();let e=[...this._downlinkLossAndRTTMap.values()];R.emit(A.NETWORK_QUALITY,{room:this._room,uplink:{rtt:this._uplinkRTT,loss:this._uplinkLoss},downlinks:e}),this.emit(aI.EVENT_NETWORK_QUALITY,{uplinkNetworkQuality:this.uplinkNetworkQuality,downlinkNetworkQuality:this.downlinkNetworkQuality,uplinkRTT:this._uplinkRTT,uplinkLoss:this._uplinkLoss,downlinkRTT:this._downlinkRTT,downlinkLoss:this._downlinkLoss,downlinkInfo:e})},{delay:2e3})):this._log.info("network quality calculating is already started")}stop(){this._log.debug("stopped"),this._interval!==-1&&(_e.clearTask(this._interval),this._interval=-1),this._downlinkLossAndRTTMap.clear(),this._downlinkPrevStatMap.clear()}updateDelay(e){let{tinyIdToUserIdMap:t}=this._room;e.forEach(i=>{let{srcTinyId:r,videoDelay:n,audioDelay:s}=i,a=t.get(r);if(a){let c=this._room.remotePublishedUserMap.get(a);c==null||c.setDelay({videoDelay:n,audioDelay:s})}})}},vp=aI;h(vp,"EVENT_NETWORK_QUALITY","0");var oI=class{constructor(e){this._signalInfo={tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0},this._eventMap=new Map,this._captureCostSum=0,this._captureCostCount=0,this._frameWorkType=e.frameWorkType||30,this._component=e.component||0,this.connectionType=e.connectionType||1,this._language=e.language||0,this._room=e.room,this._keyPrefix="key_point",this._log=b.createLogger({id:"kpm",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),Object.getOwnPropertyNames(this.__proto__).forEach(t=>{t.startsWith("handle")&&ne(this[t])&&(this[t]=function(i){let{fn:r,context:n}=i;return function(){try{for(var s=arguments.length,a=new Array(s),c=0;c<s;c++)a[c]=arguments[c];let o=r.apply(n,a);return Ah(o)?o.catch(l=>b.error("".concat(r.name,"() error observed ").concat(l))):o}catch(o){b.error("".concat(r.name,"() error observed ").concat(o))}}}({fn:this[t],context:this}))}),this.initData(),this.installEvents()}initData(){this._firstPublishedUserList=[],this._networkQuality={totalUplinkRTT:0,totalUplinkLoss:0,count:0,totalDownlinkRTTAndLossMap:new Map},this._basicInfo={string_sdk_version:St,uint32_os_type:15,string_device_name:"",string_http_user_agent:navigator.userAgent,string_os_version:"",uint32_avg_rtt:0,uint32_avg_up_loss:0,uint32_scene:this._room.scene==="live"?1:0,uint32_joining_duration:0,uint32_networkType:0,uint32_framework:this._frameWorkType,uint32_component:this._component,uint32_connection_type:this.connectionType,uint32_caller_coding_language:this._language,string_domain:location.hostname},this._pathJoinRoom={uint64_start_time:0,uint64_send_request_acc_ip_cmd_start_time:0,uint64_send_request_acc_ip_cmd_end_time:0,uint64_send_request_enter_room_cmd_start_time:0,uint64_send_request_enter_room_cmd_end_time:0,uint64_send_first_video_frame_time:0,uint64_recv_userlist_time:0,uint64_end_time:0,int32_send_request_acc_ip_cmd_ret:0,int32_send_request_enter_room_cmd_ret:0,int32_end_ret:0},this._pathLeaveRoom={uint64_start_time:0,uint64_send_request_exit_room_cmd_start_time:0,uint64_send_request_exit_room_cmd_end_time:0,uint64_end_time:0,int32_send_request_exit_room_cmd_ret:0,int32_end_ret:0},this._localStreamStat={totalVideoBitrate:0,totalVideoFPS:0,totalVideoHeight:0,totalVideoWidth:0,totalAudioLevel:0,videoCount:0,audioLevelCount:0,publishStartTime:0,statsToReport:{uint32_audio_capture_db:0,uint32_video_big_capture_fps:0,uint32_video_big_bitrate:0,uint32_video_big_resolution:0}},this._pathMainVideoMap=new Map,this._pathMainAudioMap=new Map,this._pathAuxiliaryMap=new Map,this._remoteStreamStatMap=new Map,Eh().then(e=>{this._basicInfo.string_os_version=Sh(),this._basicInfo.string_device_name=e&&e.mobile?e.model:this._basicInfo.string_os_version})}addEvent(e,t){return this._eventMap.set(e,t),R.on(e,t),this}installEvents(){this.handleUnload=this.handleUnload.bind(this),window.addEventListener("pagehide",this.handleUnload),this._room.once("banned",()=>this.handleLeaveSuccess({room:this._room,roomId:this._room.roomId})),this.addEvent(A.JOIN_START,this.handleJoinStart).addEvent(A.JOIN_SCHEDULE_SUCCESS,this.handleJoinScheduleSuccess).addEvent(A.JOIN_SIGNAL_CONNECTION_START,this.handleSignalConnectionStart).addEvent(A.JOIN_SIGNAL_CONNECTION_END,this.handleSignalConnectionEnd).addEvent(A.JOIN_SEND_CMD,this.handleJoinSendCMD).addEvent(A.JOIN_RECEIVED_CMD_RES,this.handleJoinReceivedCMDResponce).addEvent(A.JOIN_SUCCESS,this.handleJoinSuccess).addEvent(A.JOIN_FAILED,this.handleJoinFailed).addEvent(A.LEAVE_START,this.handleLeaveStart).addEvent(A.LEAVE_SUCCESS,this.handleLeaveSuccess).addEvent(A.LEAVE_SEND_CMD,this.handleLeaveSendCMD).addEvent(A.LOCAL_TRACK_CAPTURE_START,this.handleTrackCaptureStart).addEvent(A.LOCAL_TRACK_CAPTURE_SUCCESS,this.handleTrackCaptureSuccess).addEvent(A.LOCAL_TRACK_CAPTURE_FAILED,this.handleTrackCaptureFailed).addEvent(A.PUBLISH_START,this.handlePublishStart).addEvent(A.SEND_FIRST_VIDEO_FRAME,this.handleSendFirstVideoFrame).addEvent(A.SUBSCRIBE_START,this.handleSubscribeStart).addEvent(A.SUBSCRIBE_SUCCESS,this.handleSubscribed).addEvent(A.PLAY_TRACK_START,this.handlePlayStart).addEvent(A.VIDEO_LOADED_DATA,this.handleVideoLoadedData).addEvent(A.PLAYER_STATE_CHANGED,e=>{let{track:t,state:i,type:r}=e;!yi(t)||!this.hitTest(t.room)||i==="PLAYING"&&(r===_.AUDIO?this.handleAudioPlaying(t):this.handleVideoPlaying(t))}).addEvent(A.NETWORK_QUALITY,this.handleNetworkQuality).addEvent(A.HEARTBEAT_REPORT,this.handleHeartbeatStats).addEvent(A.RECEIVED_PUBLISHED_USER_LIST,this.handleReceivedPublishUserList).addEvent(A.REMOTE_PUBLISH_STATE_CHANGED,e=>{let{room:t,prevMuteState:i,muteState:r}=e;if(!this.hitTest(t))return;let n=i.hasAudio||i.hasVideo||i.hasSmall,s=i.hasAuxiliary,a=r.hasAudio||r.hasVideo||r.hasSmall,c=r.hasAuxiliary;!n&&a&&this.handleRemoteStreamAdded(r.userId,"main"),!s&&c&&this.handleRemoteStreamAdded(r.userId,"auxiliary")}).addEvent(A.SINGLE_CONNECTION_STAT,e=>{let{room:t,stat:i}=e;this.hitTest(t)&&(this._pathJoinRoom.int32_ice_cost=i.ice,this._pathJoinRoom.int32_dtls_cost=i.dtls,this._pathJoinRoom.int32_peer_connection_cost=i.peerConnection)})}uninstallEvents(){window.removeEventListener("unload",this.handleUnload),this._eventMap.forEach((e,t)=>R.off(t,e)),this._eventMap.clear()}destroy(){this.uninstallEvents(),_e.clearTask(this._intervalId)}handleUnload(){this._room.isJoined&&this.handleLeaveSuccess({room:this._room,roomId:this._room.roomId})}handleJoinStart(e){this.hitTest(e.room)&&(this._pathJoinRoom.uint64_start_time===0&&(this._pathJoinRoom.uint64_start_time=Date.now()),e.params&&(I(e.params.frameWorkType)||(this._frameWorkType=e.params.frameWorkType,this._basicInfo.uint32_framework=this._frameWorkType),I(e.params.component)||(this._component=e.params.component,this._basicInfo.uint32_component=this._component),I(e.params.language)||(this._language=e.params.language,this._basicInfo.uint32_caller_coding_language=this._language)))}handleJoinScheduleSuccess(e){let{room:t,detailCost:i}=e;if(this.hitTest(t)&&i){let{totalCost:r,local:n,dns:s,tcp:a,tls:c,request:o,response:l}=i;this._pathJoinRoom.int32_schedule_cost=r,this._pathJoinRoom.int32_schedule_local=n,this._pathJoinRoom.int32_schedule_dns=s,this._pathJoinRoom.int32_schedule_tcp=a,this._pathJoinRoom.int32_schedule_tls=c,this._pathJoinRoom.int32_schedule_request=o,this._pathJoinRoom.int32_schedule_response=l}}handleSignalConnectionStart(e){let{room:t}=e;this.hitTest(t)&&this._pathJoinRoom.uint64_send_request_acc_ip_cmd_start_time===0&&(this._pathJoinRoom.uint64_send_request_acc_ip_cmd_start_time=Date.now())}handleSignalConnectionEnd(e){let{room:t,error:i}=e;this.hitTest(t)&&this._pathJoinRoom.uint64_send_request_acc_ip_cmd_end_time===0&&(this._pathJoinRoom.uint64_send_request_acc_ip_cmd_end_time=Date.now(),i&&(this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret=i instanceof N?Number(i.getExtraCode()||i.getCode()):C.UNKNOWN,this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret))}handleJoinSendCMD(e){this.hitTest(e.room)&&this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time===0&&(this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time=Date.now())}handleJoinReceivedCMDResponce(e){this.hitTest(e.room)&&this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time===0&&(this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time=Date.now(),this._pathJoinRoom.int32_send_request_enter_room_cmd_ret=e.code,e.code!==0&&(this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_enter_room_cmd_ret))}handleJoinSuccess(e){this.hitTest(e.room)&&this._pathJoinRoom.uint64_end_time===0&&(this._pathJoinRoom.uint64_end_time=Date.now(),this._pathJoinRoom.int32_end_ret=0,this._signalInfo=e.room.getSignalInfo())}handleJoinFailed(e){let{room:t,error:i}=e;this.hitTest(t)&&(this._pathJoinRoom.uint64_end_time=Date.now(),this._pathJoinRoom.int32_end_ret===0&&(this._pathJoinRoom.int32_end_ret=i.code||this._pathJoinRoom.int32_send_request_enter_room_cmd_ret||this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret),setTimeout(()=>{this.report()}))}handleReceivedPublishUserList(e){this.hitTest(e.room)&&this._pathJoinRoom.uint64_recv_userlist_time===0&&(this._pathJoinRoom.uint64_recv_userlist_time=Date.now(),this._firstPublishedUserList=e.publishedUserList||[])}handleSendFirstVideoFrame(e){let{room:t}=e;!this.hitTest(t)||this._pathJoinRoom.uint64_send_first_video_frame_time===0&&this._pathJoinRoom.uint64_start_time!==0&&(this._pathJoinRoom.uint64_send_first_video_frame_time=Date.now())}handleLeaveStart(e){this.hitTest(e.room)&&(this._pathLeaveRoom.uint64_start_time=Date.now())}handleLeaveSuccess(e){this.hitTest(e.room)&&this._pathLeaveRoom.uint64_end_time===0&&(this._pathLeaveRoom.uint64_end_time=Date.now(),this._pathJoinRoom.uint64_end_time!==0?this._basicInfo.uint32_joining_duration=this._pathLeaveRoom.uint64_end_time-this._pathJoinRoom.uint64_end_time:this._log.warn("pathJoinRoom endTime is 0"),this.report())}handleLeaveSendCMD(e){this.hitTest(e.room)&&(this._pathLeaveRoom.uint64_send_request_exit_room_cmd_start_time=Date.now(),this._pathLeaveRoom.uint64_send_request_exit_room_cmd_end_time=Date.now())}handleRemoteStreamAdded(e,t){var i;let r="".concat(e,"_").concat(t);if(!this._remoteStreamStatMap.has(r)){let n={userId:e,totalVideoFPS:0,totalVideoBitrate:0,totalAudioLevel:0,totalAudioBitrate:0,totalLoss:0,audioCount:0,audioLevelCount:0,videoCount:0,networkQualityCount:0,streamAddedTime:Date.now(),subscribeStartTime:0,subscribedTime:0,playStreamTime:0,statsToReport:J(O({},jU),{msg_user_info:new Ip({userId:e,tinyId:(i=this._room.remotePublishedUserMap.get(e))==null?void 0:i.tinyId,role:20})})};n.statsToReport.uint32_stream_type=t==="main"?2:7,this._remoteStreamStatMap.set(r,n)}}handleSubscribeStart(e){let{room:t,remotePublishedUser:i,streamType:r,subscribeState:n}=e;if(!this.hitTest(t))return;let{userId:s,tinyId:a,role:c}=i,o=new Ip({userId:s,tinyId:a,role:c==="anchor"?20:21}),l=Date.now(),d="".concat(s,"_").concat(r),u=this._remoteStreamStatMap.get(d);u&&u.subscribeStartTime===0&&(u.subscribeStartTime=l),r==="main"?(i.muteState.hasVideo&&(n.video||n.smallVideo)&&!this._pathMainVideoMap.has(d)&&this._pathMainVideoMap.set(d,{statsToReport:{msg_user_info:o,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_render_first_frame_time:0,uint64_combine_first_frame_time:0},userId:s,sendSubscribeCMDTime:l}),i.muteState.hasAudio&&n.audio&&!this._pathMainAudioMap.has(d)&&this._pathMainAudioMap.set(d,{statsToReport:{msg_user_info:o,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_play_first_frame_time:0},userId:s,sendSubscribeCMDTime:l})):i.muteState.hasAuxiliary&&n.auxiliary&&!this._pathAuxiliaryMap.has(d)&&this._pathAuxiliaryMap.set(d,{sendSubscribeCMDTime:l})}handleSubscribed(e){let{room:t,remotePublishedUser:i,streamType:r}=e;if(this.hitTest(t)){let n="".concat(i.userId,"_").concat(r),s=this._remoteStreamStatMap.get(n);s&&s.subscribedTime===0&&(s.subscribedTime=Date.now())}}handlePlayStart(e){let{track:t}=e;if(!yi(t)||!this.hitTest(t.room))return;let i="".concat(t.userId,"_").concat(t.streamType),r=this._remoteStreamStatMap.get(i);(r==null?void 0:r.playStreamTime)===0&&(r.playStreamTime=Date.now())}handleVideoLoadedData(e){let{track:t}=e;if(!yi(t)||!this.hitTest(t.room))return;let i="".concat(t.userId,"_").concat(t.streamType),r=this._pathMainVideoMap.get(i);r&&r.statsToReport.uint64_combine_first_frame_time===0&&(r.statsToReport.uint64_combine_first_frame_time=Date.now())}handleVideoPlaying(e){let t="".concat(e.userId,"_").concat(e.streamType),i=Date.now(),r=this._pathMainVideoMap.get(t),n=this._remoteStreamStatMap.get(t);if(r&&(r.statsToReport.uint64_render_first_frame_time===0&&(r.statsToReport.uint64_render_first_frame_time=i),n)){let{statsToReport:a,playStreamTime:c,subscribedTime:o}=n;a.uint32_video_render_first===0&&c-o<=100&&(a.uint32_video_render_first=i-r.sendSubscribeCMDTime)}let s=this._pathAuxiliaryMap.get(t);if(s&&n){let{statsToReport:a,playStreamTime:c,subscribedTime:o}=n;a.uint32_video_render_first===0&&c-o<=100&&(a.uint32_video_render_first=i-s.sendSubscribeCMDTime)}}handleAudioPlaying(e){let t="".concat(e.userId,"_").concat(e.streamType),i=this._pathMainAudioMap.get(t);i&&i.statsToReport.uint64_play_first_frame_time===0&&(i.statsToReport.uint64_play_first_frame_time=Date.now())}handleNetworkQuality(e){this.hitTest(e.room)&&(this._networkQuality.totalUplinkLoss+=e.uplink.loss,this._networkQuality.totalUplinkRTT+=e.uplink.rtt,this._networkQuality.count++,e.downlinks.forEach(t=>{let{rtt:i,loss:r,userId:n,videoDelay:s,audioDelay:a}=t,c=this._networkQuality.totalDownlinkRTTAndLossMap.get(n);if(c)c.totalRTT+=i,c.totalLoss+=r,s&&(c.totalVideoDelay=(c.totalVideoDelay||0)+s,c.videoDelayCount=(c.videoDelayCount||0)+1),a&&(c.totalAudioDelay=(c.totalAudioDelay||0)+a,c.audioDelayCount=(c.audioDelayCount||0)+1),c.count++;else{let o,l,d,u;s&&(l=s,d=1),a&&(o=a,u=1),this._networkQuality.totalDownlinkRTTAndLossMap.set(n,{totalRTT:i,totalLoss:r,count:1,totalAudioDelay:o,totalVideoDelay:l,audioDelayCount:u,videoDelayCount:d})}}))}handleHeartbeatStats(e){if(this.hitTest(e.room)){let{msg_device_info:t,msg_up_stream_info:i,msg_down_stream_info:r}=e.report;if(i.msg_video_status[0]){let{uint32_video_codec_bitrate:n,uint32_video_enc_fps:s,uint32_video_width:a,uint32_video_height:c}=i.msg_video_status[0];this._localStreamStat.totalVideoBitrate+=n,this._localStreamStat.totalVideoFPS+=s,this._localStreamStat.totalVideoWidth+=a,this._localStreamStat.totalVideoHeight+=c,this._localStreamStat.videoCount++}if(i.msg_audio_status){let{uint32_audio_level:n}=i.msg_audio_status;Math.floor(n/_i*100)>0&&(this._localStreamStat.totalAudioLevel+=n/_i,this._localStreamStat.audioLevelCount++)}r.forEach(n=>{let{msg_user_info:s,msg_audio_status:a,msg_video_status:c}=n,o=s.str_identifier,l=this._room.remotePublishedUserMap.get(o);if(c.forEach(d=>{let u=d.uint32_video_stream_type===2,p=d.uint32_video_stream_type===7,m="".concat(o,"_").concat(u?"main":"auxiliary"),f=this._remoteStreamStatMap.get(m);if(f&&(u&&(l!=null&&l.remoteVideoTrack.isSubscribed)||p&&(l!=null&&l.remoteAuxiliaryTrack))){f.totalVideoFPS+=d.uint32_video_receive_fps,f.totalVideoBitrate+=d.uint32_video_codec_bitrate,f.videoCount++,f.statsToReport.uint32_video_width===0&&(f.statsToReport.uint32_video_width=d.uint32_video_width),f.statsToReport.uint32_video_height===0&&(f.statsToReport.uint32_video_height=d.uint32_video_height);let T=u?l.remoteVideoTrack:l.remoteAuxiliaryTrack;T.stat.jitterBufferDelay&&(f.videoJitterBufferDelay=T.stat.jitterBufferDelay),T.stat.framesReceived&&(f.statsToReport.uint32_video_consume_render_rate=Math.floor(T.stat.framesDecoded/T.stat.framesReceived*Pd(10,6)))}}),a){let d="".concat(o,"_","main"),u=this._remoteStreamStatMap.get(d);this._remoteStreamStatMap.has(d)&&u&&(l!=null&&l.remoteAudioTrack.isSubscribed)&&(u.totalAudioBitrate+=a.uint32_audio_codec_bitrate,u.audioCount++,l.remoteAudioTrack.stat.jitterBufferDelay&&(u.audioJitterBufferDelay=l.remoteAudioTrack.stat.jitterBufferDelay),Math.floor(a.uint32_audio_level/_i*100)>0&&(u.totalAudioLevel+=a.uint32_audio_level/_i,u.audioLevelCount++))}}),t.uint32_audio_capture_cost&&(this._captureCostSum+=t.uint32_audio_capture_cost,this._captureCostCount+=1,this._captureCostCount>=100&&(this._basicInfo.uint32_audio_capture_cost=Math.floor(this._captureCostSum/this._captureCostCount),this._captureCostSum=0,this._captureCostCount=0))}}handlePublishStart(e){let{room:t}=e;this.hitTest(t)&&this._localStreamStat.publishStartTime===0&&(this._localStreamStat.publishStartTime=Date.now())}handleTrackCaptureStart(e){let{track:t}=e;t.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_start_time&&(this._pathJoinRoom.uint64_init_audio_start_time=Date.now()),t.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_start_time&&(this._pathJoinRoom.uint64_init_camera_start_time=Date.now())}handleTrackCaptureSuccess(e){let{track:t}=e;t.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=0,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),t.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=0,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}handleTrackCaptureFailed(e){let{track:t,error:i}=e,r={NotFoundError:1,NotAllowedError:2,NotReadableError:3,OverConstrainedError:4,AbortError:5,InvalidStateError:6,SecurityError:7,TypeError:8}[i.name]||(i instanceof N?i.getExtraCode()||i.getCode():C.UNKNOWN);t.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=r,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),t.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=r,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}hasVideoFlag(e){return this._firstPublishedUserList.findIndex(t=>t.userId===e&&t.flag&ps)>=0}hasAudioFlag(e){return this._firstPublishedUserList.findIndex(t=>t.userId===e&&t.flag&ms)>=0}hasAuxFlag(e){return this._firstPublishedUserList.findIndex(t=>t.userId===e&&t.flag&Do)>=0}hitTest(e){return e===this._room}prepareReport(){if(this._captureCostCount>0&&!this._basicInfo.uint32_audio_capture_cost&&(this._basicInfo.uint32_audio_capture_cost=Math.floor(this._captureCostSum/this._captureCostCount),this._captureCostSum=0,this._captureCostCount=0),this._networkQuality.count>0&&(this._basicInfo.uint32_avg_rtt=Math.floor(this._networkQuality.totalUplinkRTT/this._networkQuality.count),this._basicInfo.uint32_avg_up_loss=Math.floor(this._networkQuality.totalUplinkLoss/this._networkQuality.count)),this._localStreamStat.videoCount>0){this._localStreamStat.statsToReport.uint32_video_big_capture_fps=Math.floor(this._localStreamStat.totalVideoFPS/this._localStreamStat.videoCount),this._localStreamStat.statsToReport.uint32_video_big_bitrate=Math.floor(this._localStreamStat.totalVideoBitrate/this._localStreamStat.videoCount);let e=Math.floor(this._localStreamStat.totalVideoWidth/this._localStreamStat.videoCount),t=Math.floor(this._localStreamStat.totalVideoHeight/this._localStreamStat.videoCount);this._localStreamStat.statsToReport.uint32_video_big_resolution=e<<16|t}this._localStreamStat.audioLevelCount>0&&(this._localStreamStat.statsToReport.uint32_audio_capture_db=Math.floor(this._localStreamStat.totalAudioLevel/this._localStreamStat.audioLevelCount*100)),this._remoteStreamStatMap.forEach((e,t)=>{let{userId:i}=e,r=this._networkQuality.totalDownlinkRTTAndLossMap.get(i);if(r){let{totalLoss:l,count:d,audioDelayCount:u,videoDelayCount:p,totalAudioDelay:m,totalVideoDelay:f}=r;e.statsToReport.uint32_avg_down_loss=Math.floor(l/d),u&&m&&(e.statsToReport.uint32_audio_network_p2p_delay=Math.floor(m/u),e.audioJitterBufferDelay&&(e.statsToReport.uint32_p2p_delay=Math.floor(e.statsToReport.uint32_audio_network_p2p_delay+e.audioJitterBufferDelay))),p&&f&&(e.statsToReport.uint32_video_network_p2p_delay=Math.floor(f/p))}e.videoCount>0&&(e.statsToReport.uint32_video_avg_fps=Math.floor(e.totalVideoFPS/e.videoCount),e.statsToReport.uint32_video_avg_bitrate=Math.floor(e.totalVideoBitrate/e.videoCount)),e.audioCount>0&&(e.statsToReport.uint32_audio_recv_bitrate=e.statsToReport.uint32_audio_bitrate=Math.floor(e.totalAudioBitrate/e.audioCount)),e.audioLevelCount>0&&(e.statsToReport.uint32_audio_play_db=Math.floor(e.totalAudioLevel/e.audioLevelCount*100));let{callDurationCalculator:n}=this._room;n&&(e.statsToReport.uint32_audio_play_time=n.getDuration(t,_.AUDIO),e.statsToReport.uint32_video_play_time=n.getDuration(t,_.VIDEO)),e.statsToReport.uint32_video_render_first=Math.min(e.statsToReport.uint32_video_render_first,gr);let{badCaseDetector:s}=this._room,{dataFreeze:a,count:c}=s.getDataFreezeDuration(t),{renderFreeze:o}=s.getRenderFreezeDuration(t);e.statsToReport.uint32_video_block_count=c,e.statsToReport.uint32_video_block_time=Math.min(a,e.statsToReport.uint32_video_play_time),e.statsToReport.uint32_video_external_block_time=Math.min(o,e.statsToReport.uint32_video_play_time),s.isBlackStream(t)&&e.statsToReport.uint32_video_avg_fps===0?e.statsToReport.uint32_video_black_screen_subjective=1:e.statsToReport.uint32_video_black_screen_subjective=0,(e.subscribeStartTime===0||e.subscribeStartTime-e.streamAddedTime>100||e.playStreamTime===0)&&(this._pathMainAudioMap.delete(t),this._pathMainVideoMap.delete(t),e.statsToReport.uint32_video_render_first=0)}),this._pathMainAudioMap.forEach((e,t)=>{this.hasAudioFlag(e.userId)?e.statsToReport.uint64_play_first_frame_time-e.statsToReport.uint64_start_enter_time>gr&&(e.statsToReport.uint64_play_first_frame_time=e.statsToReport.uint64_start_enter_time+gr):this._pathMainAudioMap.delete(t)}),this._pathMainVideoMap.forEach((e,t)=>{this.hasVideoFlag(e.userId)?e.statsToReport.uint64_render_first_frame_time-e.statsToReport.uint64_start_enter_time>gr&&(e.statsToReport.uint64_render_first_frame_time=e.statsToReport.uint64_start_enter_time+gr):this._pathMainVideoMap.delete(t)}),this._pathJoinRoom.uint64_end_time-this._pathJoinRoom.uint64_start_time>gr&&(this._pathJoinRoom.uint64_end_time=this._pathJoinRoom.uint64_start_time+gr)}getReportData(){this._basicInfo.uint32_networkType=Qo();let e={uint32_sdk_app_id:Number(this._room.sdkAppId),msg_user_info:new Ip({userId:this._room.userId,tinyId:this._room.tinyId,role:this._room.role==="anchor"?20:21}),msg_basic_info:this._basicInfo,uint32_acc_ip:Xo(this._signalInfo.relayIp),uint32_client_ip:Xo(this._signalInfo.clientIp,!1),uint32_acc_port:this._signalInfo.relayPort||0,uint64_timestamp:Date.now(),uint32_seq:Math.floor(Math.random()*Pd(2,31)),msg_path_enter_room:this._pathJoinRoom,msg_path_exit_room:this._pathLeaveRoom,msg_path_recv_video:[...this._pathMainVideoMap.values()].map(t=>t.statsToReport),msg_quality_statistics:[...this._remoteStreamStatMap.values()].map(t=>t.statsToReport),str_room_name:String(this._room.roomId||0),msg_path_recv_audio:[...this._pathMainAudioMap.values()].map(t=>t.statsToReport),uint32_info_client_ip:Xo(this._signalInfo.clientIp,!1),error_code:[],msg_local_statistics:this._localStreamStat.statsToReport};return kh(e),e}report(){return g(this,null,function*(){try{this.prepareReport();let e=this.getReportData();yield this.upload(e),this.initData()}catch(e){this._log.warn(e)}})}upload(e){return g(this,null,function*(){if(e.msg_path_enter_room.uint64_start_time===0)return;let t=Number(this._room.sdkAppId),i=yield tS(e),r=i instanceof ArrayBuffer,n="".concat(Os(t,hs.KEY_POINT),"&gzip=").concat(+r),s=!1;navigator.sendBeacon&&(s=navigator.sendBeacon(n,i)),s||Ss({url:n,body:i}),this.uploadKVStat(L),this.uploadKVStat(Ws)})}setConnectionType(e){this.connectionType=e,this._basicInfo.uint32_connection_type=e}uploadKVStat(e){return g(this,null,function*(){let t=e.getReportData();if(t.stats_count.length===0&&t.stats_distribution.length===0)return;t.msg_sdk_basic_info=J(O({},t.msg_sdk_basic_info),{bytes_device_name:this._basicInfo.string_device_name||"",bytes_os_version:this._basicInfo.string_os_version||"",uint32_framework:this._frameWorkType,uint32_network_type:this._basicInfo.uint32_networkType||0}),this._log.debug(t);let i=yield tS(t),r="".concat(Os(+this._room.sdkAppId,hs.KV_STAT),"&gzip=").concat(+(i instanceof ArrayBuffer)),n=!1;navigator.sendBeacon&&(n=navigator.sendBeacon(r,i)),n||Ss({url:r,body:i})})}};k([cr({settings:{timeout:500,retries:3}})],oI.prototype,"upload");var gr=5e3,jU={msg_user_info:null,uint32_video_avg_fps:0,uint32_video_width:0,uint32_video_height:0,uint32_video_avg_bitrate:0,uint32_video_block_time:0,uint32_video_play_time:0,uint32_audio_block_time:0,uint32_audio_play_time:0,uint32_audio_play_db:0,uint32_avg_down_loss:0,uint32_stream_type:0,uint32_video_render_first:0,uint32_video_block_count:0,uint32_audio_block_count:0,uint32_audio_bitrate:0,uint32_video_black_screen_subjective:0,uint32_audio_recv_bitrate:0,uint32_video_external_block_time:0,uint32_video_consume_render_rate:0},Ip=class{constructor(e){this.str_identifier=String(e.userId),this.str_tinyid=String(e.tinyId||0),this.uint32_role=e.role}},GU=oI,Rc=class{constructor(){h(this,"_startTime"),h(this,"_endTime"),this._startTime=0,this._endTime=0,this.start()}start(){this._startTime===0&&(this._startTime=W())}stop(){this._endTime===0&&(this._endTime=W())}getDuration(){return this._endTime===0?W()-this._startTime:this._endTime-this._startTime}get endTime(){return this._endTime}},WU=class{constructor(e){h(this,"_room",null),h(this,"_durationMap"),h(this,"_eventMap",new Map),this._room=e.room,this._durationMap=new Map,this.installEvents()}installEvents(){this._eventMap.set(A.SUBSCRIBE_SUCCESS,this.handleSubscribed).set(A.UNSUBSCRIBE_SUCCESS,this.handleStreamStopped).set(A.REMOTE_PUBLISH_STATE_CHANGED,e=>{let{room:t,prevMuteState:i,muteState:r}=e;var n;let{userId:s}=r;if(!this.hitTest(t))return;i.hasAudio&&!r.hasAudio&&this.stopDurationItem("".concat(s,"_","main"),_.AUDIO),i.hasVideo&&!r.hasVideo&&this.stopDurationItem("".concat(s,"_","main"),_.VIDEO),i.hasAuxiliary&&!r.hasAuxiliary&&this.stopDurationItem("".concat(s,"_","auxiliary"),_.VIDEO);let a=(n=this._room)==null?void 0:n.remotePublishedUserMap.get(s);!a||(!i.hasAudio&&r.hasAudio&&a.remoteAudioTrack.isSubscribed&&this.addDuractionItem(s,_.AUDIO,"main"),!i.hasVideo&&r.hasVideo&&a.remoteVideoTrack.isSubscribed&&this.addDuractionItem(s,_.VIDEO,"main"),!i.hasAuxiliary&&r.hasAuxiliary&&a.remoteAuxiliaryTrack.isSubscribed&&this.addDuractionItem(s,_.VIDEO,"auxiliary"))}),this._eventMap.forEach((e,t)=>R.on(t,e,this))}uninstallEvents(){this._eventMap.forEach((e,t)=>R.off(t,e,this)),this._eventMap.clear()}handleSubscribed(e){let{room:t,streamType:i,remotePublishedUser:r}=e;if(!this.hitTest(t))return;let{userId:n}=r,s="".concat(n,"_").concat(i);if(r.muteState.hasAudio&&i==="main")if(r.remoteAudioTrack.isSubscribed){let a=new Rc,c=this._durationMap.get(s);c?this.isRecording(c.audio)||c.audio.push(a):this._durationMap.set(s,{userId:n,type:i,audio:[a],video:[]})}else this.stopDurationItem(s,_.AUDIO);if(r.muteState.hasVideo||r.muteState.hasAuxiliary)if(r.remoteVideoTrack.isSubscribed||r.remoteAuxiliaryTrack.isSubscribed){let a=new Rc,c=this._durationMap.get(s);c?this.isRecording(c.video)||c.video.push(a):this._durationMap.set(s,{userId:n,type:i,audio:[],video:[a]})}else this.stopDurationItem(s,_.VIDEO)}handleStreamStopped(e){let{room:t,streamType:i,remotePublishedUser:r}=e;if(!this.hitTest(t))return;let{userId:n}=r,s="".concat(n,"_").concat(i);this.stopDurationItem(s,_.AUDIO),this.stopDurationItem(s,_.VIDEO)}isRecording(e){return e.findIndex(t=>t.endTime===0)>=0}addDuractionItem(e,t,i){let r="".concat(e,"_").concat(i),n=new Rc,s=this._durationMap.get(r);s?this.isRecording(s[t])||s[t].push(n):this._durationMap.set(r,{userId:e,type:i,audio:t===_.AUDIO?[n]:[],video:t===_.AUDIO?[]:[n]})}stopDurationItem(e,t){if(this._durationMap.has(e)){let i=this._durationMap.get(e)[t].find(r=>r.endTime===0);i&&i.stop()}}hitTest(e){return this._room===e}getDuration(e,t){return this._durationMap.has(e)?this._durationMap.get(e)[t].reduce((i,r)=>i+r.getDuration(),0):0}getDurationMap(){return this._durationMap}reset(){this._durationMap.clear()}destroy(){this._room=null,this.uninstallEvents()}},JU=class{constructor(e){h(this,"_room"),h(this,"_renderFreezeMap",new Map),h(this,"_isVideoPlayingEventFiredMap",new Map),h(this,"_dataFreezeMap",new Map),h(this,"_monitorFreezeData",new Map),h(this,"_eventMap",new Map),this._room=e.room,this.installEvents()}installEvents(){this._eventMap.set(A.LEAVE_SUCCESS,e=>{let{room:t}=e;this.hitTest(t)&&this.stop()}).set(A.PLAY_TRACK_START,this.onPlayTrackStart).set(A.UNSUBSCRIBE_SUCCESS,e=>{let{room:t,streamType:i,remotePublishedUser:r}=e;if(!this.hitTest(t))return;let{userId:n}=r,s="".concat(n,"_").concat(i);this.stopDataFreeze({key:s,userId:n,type:i})}).set(A.REMOTE_PUBLISH_STATE_CHANGED,e=>{let{room:t,prevMuteState:i,muteState:r}=e;if(!this.hitTest(t))return;let{userId:n}=r;if(i.hasVideo&&!r.hasVideo){let s="main",a="".concat(r.userId,"_").concat(s);this.stopDataFreeze({key:a,userId:n,type:s})}if(i.hasAuxiliary&&!r.hasAuxiliary){let s="auxiliary",a="".concat(r.userId,"_").concat(s);this.stopDataFreeze({key:a,userId:n,type:s})}}).set(A.PLAYER_STATE_CHANGED,e=>{let{track:t,state:i,reason:r,type:n}=e;if(yi(t)&&this.hitTest(t.room)&&n===_.VIDEO){if(i==="PLAYING"){let s="".concat(t.userId,"_").concat(t.streamType);this._isVideoPlayingEventFiredMap.set(s,!0)}r===_.MUTE?this.onVideoTrackMuted(t):r===_.UNMUTE&&this.onVideoTrackUnmuted(t)}}).set(A.HEARTBEAT_REPORT,this.onHearBeatReport),this._eventMap.forEach((e,t)=>R.on(t,e,this))}uninstallEvents(){this._eventMap.forEach((e,t)=>R.off(t,e,this)),this._eventMap.clear()}stop(){this._renderFreezeMap.clear(),this._dataFreezeMap.clear(),this._isVideoPlayingEventFiredMap.clear()}onVideoTrackMuted(e){if(!e.isSubscribed)return;let{userId:t,streamType:i}=e,r="".concat(t,"_").concat(i),n=this._dataFreezeMap.get(r),s=new Rc;n?n.durationItemList.push(s):this._dataFreezeMap.set(r,{userId:t,type:i,durationItemList:[s],isFreezing(){let a=this.durationItemList[this.durationItemList.length-1];return a&&a.endTime===0}})}onVideoTrackUnmuted(e){if(!e.isSubscribed)return;let{userId:t,streamType:i}=e,r="".concat(t,"_").concat(i);this.stopDataFreeze({key:r,userId:t,type:i})}onHearBeatReport(e){let{room:t,report:i}=e;!this.hitTest(t)||i.msg_down_stream_info.forEach(r=>{let n=this._room.remotePublishedUserMap.get(r.msg_user_info.str_identifier);if(!n)return;let{userId:s,muteState:a}=n;r.msg_video_status.forEach(c=>{c.uint32_video_stream_type===2&&a.hasVideo&&!a.videoMuted&&n.remoteVideoTrack.isSubscribed&&this.handleRenderFreeze({userId:s,fps:c.uint32_video_dec_fps,type:"main"}),c.uint32_video_stream_type===7&&a.hasAuxiliary&&n.remoteAuxiliaryTrack.isSubscribed&&this.handleRenderFreeze({userId:s,fps:c.uint32_video_dec_fps,type:"auxiliary"})})})}stopDataFreeze(e){let{key:t,userId:i,type:r}=e,n=this._dataFreezeMap.get(t);if(!n||!n.isFreezing())return;let s=n.durationItemList[n.durationItemList.length-1];s.stop();let a=s.getDuration();a>qd?this._monitorFreezeData.set(t,{userId:i,type:r,duration:a}):n.durationItemList.pop()}getTotalDuration(e){return e.reduce((t,i)=>{let r=i.getDuration();return t+Math.min(r,5e3)},0)}handleRenderFreeze(e){return g(this,arguments,function(t){var i=this;let{userId:r,fps:n,type:s}=t;return function*(){let a="".concat(r,"_").concat(s),c=i._renderFreezeMap.get(a);if(n<=2){let o=W();c&&!c.isFreeze&&(c.freezeTimeline.push({startTime:o,endTime:0}),c.isFreeze=!0),c||i._renderFreezeMap.set(a,{userId:r,type:s,isFreeze:!0,freezeTimeline:[{startTime:o,endTime:0}],renderFreezeTotal:0})}else if(c&&c.isFreeze){c.isFreeze=!1;let o=c.freezeTimeline.pop();if(o){o.endTime=W();let l=o.endTime-o.startTime;c.freezeTimeline.push(o),c.renderFreezeTotal+=Math.min(5e3,l)}}}()})}onPlayTrackStart(e){let{track:t}=e;if(!yi(t)||!this.hitTest(t.room)||t.kind!==_.VIDEO||t.hasFlag)return;let i="".concat(t.userId,"_").concat(t.streamType);this._isVideoPlayingEventFiredMap.has(i)||this._isVideoPlayingEventFiredMap.set(i,!1)}getDataFreezeDuration(e){let t={dataFreeze:0,count:0},i=this._dataFreezeMap.get(e);if(i){if(i.isFreezing()){let r=i.durationItemList[i.durationItemList.length-1];r.stop(),r.getDuration()<qd&&i.durationItemList.pop()}t.dataFreeze=this.getTotalDuration(i.durationItemList),t.count=i.durationItemList.length}return t}getRenderFreezeDuration(e){let t=this._renderFreezeMap.get(e),i=0,r=0;if(t)if(t.isFreeze){let n=W()-t.freezeTimeline[t.freezeTimeline.length-1].startTime;i=t.renderFreezeTotal+Math.min(n,5e3),r=t.freezeTimeline.length}else i=t.renderFreezeTotal;return{renderFreeze:i,count:r}}getMonitorFreeze(){return this._monitorFreezeData}isBlackStream(e){return!!this._isVideoPlayingEventFiredMap.has(e)&&!this._isVideoPlayingEventFiredMap.get(e)}resetMonitor(){this._monitorFreezeData.clear()}hitTest(e){return e===this._room}destroy(){this.uninstallEvents()}},zU=Ie(Ve(),1),KU=[1,0,0,0,1,1,0,1],qU=class extends hr{constructor(e){if(super(e,{useDefaultProgram:!0,useFbo:!0,create2d:!0,name:"mirror"}),e instanceof bt)try{this.setTexBuffer(KU)}catch(t){e.destroy(t)}}draw2d(e,t,i,r,n){if(this.ctx2d){this.ctx2d.save(),this.ctx2d.scale(-1,1),this.ctx2d.translate(-this.width,0);let s=super.draw2d(e,t,i,r,n);return this.ctx2d.restore(),s}return!1}render(e){var t;return!((t=this.input)==null||!t.requestFrame(e))&&(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0)}},YU=class{constructor(e,t){this.node=e,this.layout=t,h(this,"positionBuffer")}get x(){return this.layout.x||this.node.x}get y(){return this.layout.y||this.node.y}get width(){return this.layout.width||this.node.width}get height(){return this.layout.height||this.node.height}get right(){return this.x+this.width}get bottom(){return this.y+this.height}},QU=class extends hr{constructor(e){super(e,{useDefaultProgram:!0,useFbo:!0,name:"mix",create2d:!0}),h(this,"inputs",[])}addInput(e,t){if(this.inputs[t.zIndex])throw new Error("input already exists");let i=new YU(e,t);this.inputs[t.zIndex]=i}resize(e,t){let i=this.inputs.reduce((r,n)=>n?Object.assign(r,{width:Math.max(r.width,n.right),height:Math.max(r.height,n.bottom)}):r,{width:0,height:0});super.resize(i.width,i.height),this.context instanceof bt&&this.inputs.forEach(r=>{if(r){let n=this.layout2texCoords(r);r.positionBuffer?this.changeBufferData(r.positionBuffer,n):r.positionBuffer=this.createBuffer(n)}})}connect(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];return super.connect(e,...i),this.resize(0,0),e}removeInput(e){this.inputs[this.inputs.findIndex(t=>(t==null?void 0:t.node)===e)]=void 0}render(e){let t=this.context.ctx;if(t.clearColor(0,0,0,0),!this.inputs.reduce((i,r)=>(!r||!r.node.requestFrame(e))&&i,!0)&&t){this.useProgram(),t.enable(t.BLEND),t.blendFunc(t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA),this.useBufferFrame();for(let i=0;i<this.inputs.length;i++){let r=this.inputs[i];r&&(r.node.useTexture(),this.draw(r.positionBuffer))}return!0}return!1}render2d(e){if(!this.inputs.reduce((t,i)=>(!i||!i.node.requestFrame(e))&&t,!0)&&this.ctx2d){this.ctx2d.clearRect(0,0,this.width,this.height);for(let t=0;t<this.inputs.length;t++){let i=this.inputs[t];i&&this.draw2d(i.node.image,i.x,i.y,i.width,i.height)}return!0}return!1}getInfo(){let{totalFrames:e,x:t,y:i,width:r,height:n,name:s}=this,a=Date.now(),c=(e-this.lastInfo.totalFrames)/((a-this.lastInfo.timestamp)/1e3)|0;return this.lastInfo={totalFrames:e,x:t,y:i,width:r,height:n,timestamp:a,fps:c,name:s},O({parent:this.inputs.filter(o=>o).map(o=>o.node.getInfo())},this.lastInfo)}close(){super.close(),this.inputs.forEach(e=>{var t,i;if(e&&((t=e.node)==null||t.disconnect(),e.positionBuffer&&this.context instanceof bt))try{(i=this.context.ctx)==null||i.deleteBuffer(e.positionBuffer)}catch{}})}},XU=class extends Cv{constructor(e,t){super(e,t.input,{name:"vb",create2d:!1,useDefaultProgram:!1,useFbo:!1,createTexture:!0,logger:e.log}),h(this,"ready",!1),h(this,"_bgTexture"),h(this,"_waterMarkTexture"),h(this,"_lastMaskTexture"),h(this,"_lastMaskFbo"),h(this,"_textureValid",!1),h(this,"_selfieTextureValid",!1),h(this,"_selfieSegmentation"),h(this,"wasm"),h(this,"_prePrograme"),h(this,"_segmentationMask"),h(this,"_weixin",!1),t.selfieSegmentation&&(this._selfieSegmentation=t.selfieSegmentation,this._selfieSegmentation.onResults=this.onPredict.bind(this)),this.init(t).catch(()=>this.context.destroy(new Error("selfie_segmentation init faild")))}init(e){return g(this,null,function*(){var t,i;let r=e.Wasm,n=this.context.ctx;if(this.wasm=new r.AllIn1(n),this.wasm.blurRadius=e.blurRadius||3,this.wasm.mirror=!!e.mirror,this.wasm.vbMode=e.bg==="blur"?1:e.bg instanceof HTMLImageElement?2:e.bg==="green"?3:0,e.waterMark){let{x:s,y:a,width:c,height:o}=e.waterMark;this.wasm.setWaterMark(s,a,c,o)}if(e.beautyParams){let{beauty:s,brightness:a,ruddy:c}=e.beautyParams;this.wasm.setBeauty(s,a,c,(t=this.context._canvas)==null?void 0:t.width,(i=this.context._canvas)==null?void 0:i.height)}if(this.program=this.wasm.init(),this.useProgram(),this.setAttributes(this.positionBuffer,this.texCoordBuffer),n.uniform1i(n.getUniformLocation(this.program,"mask"),1),e.bg instanceof HTMLImageElement&&(n.uniform1i(n.getUniformLocation(this.program,"bg"),2),this._bgTexture=this.createTexture(e.bg)),e.waterMark&&(n.uniform1i(n.getUniformLocation(this.program,"waterMark"),3),this._waterMarkTexture=this.createTexture(e.waterMark.image)),n.uniform1i(n.getUniformLocation(this.program,"lastMask"),4),this._weixin){let s=this.context.createShader(n.FRAGMENT_SHADER,`#version 300 es
111
+ precision highp float;
112
+ uniform sampler2D u_texture;
113
+ uniform sampler2D mask;
114
+
115
+ in vec2 v_texCoord;
116
+ out vec4 outColor;
117
+ void main() {
118
+ outColor = vec4(texture(u_texture, v_texCoord).rgb, texture(mask, v_texCoord).a);
119
+ }`),a=this.context.createShader(n.VERTEX_SHADER,`#version 300 es
120
+ in vec2 a_position;
121
+ in vec2 a_texCoord;
122
+ out vec2 v_texCoord;
123
+ void main() {
124
+ gl_Position = vec4(a_position.x, a_position.y, 0, 1);
125
+ v_texCoord = a_texCoord;
126
+ }`);this._prePrograme=this.context.createProgram(a,s),n.useProgram(this._prePrograme),this.setAttributes(this.positionBuffer,this.texCoordBuffer),n.uniform1i(n.getUniformLocation(this._prePrograme,"mask"),1)}this.ready=!0})}onPredict(e){var t;let i=this.context.ctx;this._weixin&&(this._lastMaskTexture||(this._lastMaskTexture=this.createTexture(this.image),this._lastMaskFbo=this.createFramebuffer(this._lastMaskTexture))),this.useProgram(),this._weixin?this.useTexture():this==null||this._selfieSegmentation.bindTexture(),i.activeTexture(i.TEXTURE1),(t=this._selfieSegmentation)==null||t.bindTexture2d(e),i.activeTexture(i.TEXTURE2),i.bindTexture(i.TEXTURE_2D,this._bgTexture||null),i.activeTexture(i.TEXTURE3),i.bindTexture(i.TEXTURE_2D,this._waterMarkTexture||null),this.useBufferFrame(),i.drawArrays(i.TRIANGLE_STRIP,0,4),this._segmentationMask=e,this.totalFrames++}render(e){var t,i,r;let n=this.context.ctx;if(typeof this.image.getVideoPlaybackQuality=="function"&&!an){let o=this.image.getVideoPlaybackQuality().totalVideoFrames;if(this._totalFrames===o)return!1;this._totalFrames=o,this.dropFrames=this._totalFrames-this.totalFrames}let{videoWidth:s,videoHeight:a}=this.image;this.image.width=s,this.image.height=a;let c=!1;if(this.totalFrames)this._weixin?this.useTexture():this==null||this._selfieSegmentation.bindTexture(),c=this._selfieTextureValid,this._selfieTextureValid=!0;else{if(!this.program)return!1;this.useTexture(),c=this._textureValid,this._textureValid=!0}return this.width===s&&this.height===a&&c?n.texSubImage2D(n.TEXTURE_2D,0,0,0,n.RGBA,n.UNSIGNED_BYTE,this.image):(this.resize(s,a),n.texImage2D(n.TEXTURE_2D,0,n.RGBA,n.RGBA,n.UNSIGNED_BYTE,this.image)),this.ready&&(this._weixin&&(n.useProgram(this._prePrograme),this.useTexture(),this._segmentationMask&&(n.activeTexture(n.TEXTURE1),(t=this._selfieSegmentation)==null||t.bindTexture2d(this._segmentationMask),n.bindFramebuffer(n.FRAMEBUFFER,this._lastMaskFbo||null)),n.drawArrays(n.TRIANGLE_STRIP,0,4),(i=this._selfieSegmentation)==null||i.bindTexture(),this._segmentationMask?n.copyTexSubImage2D(n.TEXTURE_2D,0,0,0,0,0,s,a):n.copyTexImage2D(n.TEXTURE_2D,0,n.RGBA,0,0,s,a,0)),(r=this._selfieSegmentation)==null||r.send(s,a)),this.totalFrames||(n.activeTexture(n.TEXTURE2),n.bindTexture(n.TEXTURE_2D,this._bgTexture||null),n.activeTexture(n.TEXTURE3),n.bindTexture(n.TEXTURE_2D,this._waterMarkTexture||null),n.drawArrays(n.TRIANGLE_STRIP,0,4)),!1}close(){var e;super.close();let t=this.context.ctx;this._bgTexture&&t.deleteTexture(this._bgTexture),this._waterMarkTexture&&t.deleteTexture(this._waterMarkTexture),this._lastMaskTexture&&t.deleteTexture(this._lastMaskTexture),this._lastMaskFbo&&t.deleteFramebuffer(this._lastMaskFbo),this._prePrograme&&t.deleteProgram(this._prePrograme),(e=this.wasm)==null||e.close()}},$U=class extends zU.EventEmitter{constructor(e){super(),this.room=e,h(this,"videoContext"),h(this,"_glVideoContext"),h(this,"_2dVideoContext"),h(this,"destination"),h(this,"smallVideoContext"),h(this,"smallDestination"),h(this,"smallTrackSource"),h(this,"smallImageSource"),h(this,"_isMirror",!1),h(this,"cameraTrack"),h(this,"cameraNode"),h(this,"mirrorNode"),h(this,"mixNode"),h(this,"screenTrack"),h(this,"screenNode"),h(this,"selfModel",!1),h(this,"blurRadius",3),h(this,"arTrack"),h(this,"Wasm"),h(this,"waterMarkNode"),h(this,"_waterMarkOption"),h(this,"watermarkImageList",[]),h(this,"_beautyParams"),h(this,"isUsingArTrack",!1),h(this,"_isMixScreen",!1),h(this,"_virtualBackground"),h(this,"virtualBackgroundInstance"),h(this,"_bgAssetPath"),h(this,"log",b.createLogger({id:"vm"})),h(this,"_checkId",0),h(this,"_use2d",!1),h(this,"_autoSwitchRenderMode",!0),h(this,"_selfieSegmentation"),e&&(this.log.setUserId(e.userId),this.log.setSdkAppId(e.sdkAppId)),this.smallVideoContext=new ki({frameRate:15,logger:this.log,name:"s"}),this.enablePrintDetail()}get _hasVirtualBg(){return!!this._virtualBackground}get _hasWaterMark(){return this.watermarkImageList.length>0}get renderMode(){return this._autoSwitchRenderMode?"auto":this._use2d?"2d":"webgl"}set renderMode(e){if(this._autoSwitchRenderMode=e==="auto",this._autoSwitchRenderMode)return;let t=e==="2d";this._use2d!==t&&(this._use2d=t,this.clear(),this.videoContext=this._use2d?this.get2dVideoContext():this.getGlVideoContext(),this.update())}get2dVideoContext(){return this._2dVideoContext?this._2dVideoContext.destroy():this._2dVideoContext=new ki({frameRate:15,logger:this.log,name:"m"}),this._2dVideoContext.create({alpha:this._hasWaterMark||this._hasVirtualBg}),this.sendCreateResult("videoCtx2d",this._2dVideoContext.ctx?void 0:new Error("create 2d context failed")),this._2dVideoContext}getGlVideoContext(){if(this._glVideoContext){if(this._glVideoContext.available)return this._glVideoContext}else this._glVideoContext=new bt({frameRate:15,logger:this.log,name:"m"});try{this._glVideoContext.create(),this.sendCreateResult(),this._glVideoContext.on("unavailable",(e,t)=>{this.emit("error",{reason:e,error:t}),this.log.warn("video context unavailable",e,t),this.sendCreateResult("videoCtxGl",t||new Error(e)),this.update()})}catch(e){this.emit("error",{reason:"create",error:e}),this.sendCreateResult("videoCtxGl",e)}return this._glVideoContext}enablePrintDetail(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:2e3;this._checkId=_e.run(Mo,()=>{this.destination&&this.log.debug(this.destination.getInfo())},{delay:e})}destroy(){var e,t;(e=this._2dVideoContext)==null||e.destroy(),(t=this._glVideoContext)==null||t.destroy(),this.smallVideoContext.destroy(),_e.clearTask(this._checkId)}get needAlpha(){return this._hasWaterMark||this._hasVirtualBg}get active(){return(an||this._isMixScreen||this._isMirror||this._hasWaterMark||this._hasVirtualBg||this._beautyParams)&&this.checkOrCreateVideoContext()}sendCreateResult(){let e=arguments.length>1?arguments[1]:void 0,t=(arguments.length>0&&arguments[0]!==void 0?arguments[0]:"videoCtxGl")==="videoCtxGl"?512700:512701;e?L.addFailedEvent({key:t,error:e}):L.addSuccessEvent({key:t})}checkOrCreateVideoContext(){let e=this._use2d;if(this._autoSwitchRenderMode&&(this._use2d=!this._hasVirtualBg),this.videoContext)if(this.videoContext.available){let t=!this.videoContext.hasAlpha&&this.needAlpha;if(this._autoSwitchRenderMode&&e===this._hasVirtualBg)this.clear();else{if(!t||!this._use2d)return!0;this.clear()}}else this.clear(),this._use2d=!0;return this.videoContext=this._use2d?this.get2dVideoContext():this.getGlVideoContext(),this.videoContext.available}get smallTrack(){var e;return(e=this.smallDestination)==null?void 0:e.videoTrack}get hasSmall(){return!!this.smallTrack}get initialTrack(){var e;return(e=this.cameraTrack)==null?void 0:e.mediaTrack}initVirtualBackground(e){return this._selfieSegmentation=e,this._selfieSegmentation.changeModel()}_setMainOutput(e){var t;try{let i=this.cameraTrack,{small:r,settings:n,player:s}=i;r?(this.smallVideoContext.available||(this.smallVideoContext.create({alpha:!1}),this.smallDestination=new WV(this.smallVideoContext,r)),this.smallVideoContext.frameRate=r.frameRate,this.smallDestination.resolution=r,e?(this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource),this.smallImageSource?this.smallImageSource.image=e:(this.smallImageSource=this.smallVideoContext.createVideoImageSource(e),this.smallImageSource.connect(this.smallDestination))):(this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource?this.smallTrackSource.replaceTrack(this.initialTrack):(this.smallTrackSource=this.smallVideoContext.createVideoTrackSource(this.initialTrack,"smallTrackSource"),this.smallTrackSource.width=n.width,this.smallTrackSource.height=n.height,this.smallTrackSource.connect(this.smallDestination)))):this.smallVideoContext.available&&(this.smallVideoContext.destroy(),delete this.smallDestination,delete this.smallTrackSource,delete this.smallImageSource),an&&s.setCanvas(e);let a=e&&((t=this.destination)==null?void 0:t.videoTrack)||this.initialTrack;return this.isUsingArTrack&&this.arTrack&&(this.emit("output-track-changed"),a=this.arTrack),this._selfieSegmentation&&e&&!this._use2d&&(this._selfieSegmentation._glName||this._selfieSegmentation.setCanvas(e)),this.log.info("set main output ".concat(a?a.label:"no output track")),i.setOutputMediaStreamTrack(a)}catch(i){this.log.error("set main output failed",i)}}update(){return g(this,null,function*(){var e,t;if(!this.cameraTrack||!this.cameraTrack.mediaTrack)return;if(!this.active)return this.cameraNode&&this.clear(),this._setMainOutput();let{settings:i,profile:r}=this.cameraTrack;if(this._use2d||!this._virtualBackground&&!this._beautyParams?(this.destination||(this.destination=this.videoContext.createVideoTrackDestination({name:"mainDestination",logger:this.log})),this.cameraNode?this.cameraNode.replaceTrack(this.initialTrack):(this.cameraNode=this.videoContext.createVideoTrackSource(this.initialTrack,"cameraNodeSource"),this.cameraNode.resize(i.width,i.height))):(this.cameraNode&&this.cameraNode.close(),this.destination||(this.destination=new GV(this.videoContext,{name:"mainDestination",logger:this.log})),this.cameraNode=new XU(this.videoContext,{input:this.cameraTrack.mediaTrack,mirror:this._isMirror,bg:this._virtualBackground,selfModel:this.selfModel,waterMark:this._waterMarkOption,beautyParams:this._beautyParams,useTflite:!0,blurRadius:this.blurRadius,assetPath:this._bgAssetPath,selfieSegmentation:this._selfieSegmentation,Wasm:this.Wasm}),this.cameraNode.connect(this.destination)),this.videoContext.frameRate=r.frameRate,this._use2d){let n=this.cameraNode;n.disconnect(),this._isMirror&&(this.mirrorNode||(this.mirrorNode=new qU(this.videoContext)),n=n.connect(this.mirrorNode),n.disconnect(),this.log.info("start mirror")),this.mixNode&&this.mixNode.close(),delete this.mixNode,(this._isMixScreen||this._hasWaterMark)&&(this.mixNode=new QU(this.videoContext),n.connect(this.mixNode,{zIndex:1}),this._hasWaterMark&&!this.waterMarkNode&&this._waterMarkOption&&(this.waterMarkNode=this.videoContext.createVideoImageSource(this._waterMarkOption.image,{autoResize:!1,logger:this.log}),this.waterMarkNode.resize(this._waterMarkOption.width,this._waterMarkOption.height),this.waterMarkNode.x=this._waterMarkOption.x,this.waterMarkNode.y=this._waterMarkOption.y),(e=this.waterMarkNode)==null||e.connect(this.mixNode,{zIndex:2}),this._isMixScreen&&this.screenTrack&&!this.screenNode&&(this.screenNode=this.videoContext.createVideoTrackSource(this.screenTrack.mediaTrack,"screenNodeSource")),(t=this.screenNode)==null||t.connect(this.mixNode,{zIndex:0}),n=this.mixNode,this.log.info("start mix","".concat(this.mixNode.width,"x").concat(this.mixNode.height))),n.connect(this.destination)}return this.log.info("update ".concat(this._use2d?"2d":"webgl")),this._setMainOutput(this.videoContext._canvas)})}changeInput(e){var t,i,r,n;if(e instanceof dr)return this.log.info("change screen input",(t=e.mediaTrack)==null?void 0:t.label),this.setScreenTrack(e);if(e instanceof Je)return this.log.info("change video input",(i=e.mediaTrack)==null?void 0:i.label),this.setCameraTrack(e);if(e instanceof Ys){this.log.info("change remote input",(r=e.mediaTrack)==null?void 0:r.label);let s=e.mediaTrack;return e.setOutputMediaStreamTrack(s)}this.log.warn("change unknown input",(n=e.mediaTrack)==null?void 0:n.label)}removeInput(e){var t;e instanceof dr?((t=this.screenNode)==null||t.close(),delete this.screenNode,delete this.screenTrack,this.update()):e instanceof Je?(this.clear(),delete this.cameraTrack,this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource)):e instanceof Ys&&e.source&&e.source.context.destroy()}setCameraTrack(e){return g(this,null,function*(){this.cameraTrack=e,this.update()})}setScreenTrack(e){return this.screenTrack=e,this._isMixScreen&&(this.screenNode?this.screenNode.replaceTrack(e.mediaTrack):this.update()),e.setOutputMediaStreamTrack(e.mediaTrack)}getWatermarkImage(e,t){return g(this,null,function*(){let i=document.createElement("canvas");t&&e&&(i.height=t,i.width=e);let r=i.getContext("2d");if(!r)throw new N({code:C.NOT_SUPPORTED,message:"Make image failed because of canvas context is null"});return this.watermarkImageList.sort((n,s)=>n.zIndex-s.zIndex),this.watermarkImageList.forEach(n=>{let{image:s,x:a,y:c,width:o,height:l}=n;r.drawImage(s,a,c,o,l)}),Zo(i.toDataURL())})}pushWaterMarkImageList(e){let{type:t}=e;this.watermarkImageList.some(i=>i.imageUrl===e.imageUrl&&i.height===e.height&&i.width===e.width&&i.x===e.x&&i.y===e.y&&i.type===e.type&&i.zIndex===e.zIndex)||((t==="mute"||t==="watermark")&&(this.watermarkImageList=this.watermarkImageList.filter(i=>i.type!==t)),this.watermarkImageList.push(e))}setBeautyParams(e){return g(this,null,function*(){this._beautyParams=e,this.update()})}stopBeauty(){return g(this,null,function*(){this._beautyParams=void 0,this.update()})}setWatermark(e){return g(this,null,function*(){let t;try{t=yield Zo((e==null?void 0:e.imageElement)||e.imageUrl)}catch{throw new N({code:C.INVALID_PARAMETER,message:"load image failed, url: ".concat(e.imageUrl)})}let{x:i=0,y:r=0,width:n=t.width,height:s=t.height,type:a="watermark",zIndex:c=2}=e;this.pushWaterMarkImageList({x:i,y:r,width:n,height:s,image:t,zIndex:c,type:a,imageUrl:e.imageUrl}),yield this.freshWatermark(),this.log.info("set watermark",JSON.stringify(this.watermarkImageList))})}deleteWatermark(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"watermark";return g(this,null,function*(){this.watermarkImageList=this.watermarkImageList.filter(t=>t.type!==e),this.log.info("delete watermark",e,JSON.stringify(this.watermarkImageList)),yield this.freshWatermark()})}freshWatermark(){return g(this,null,function*(){var e,t,i;(e=this.waterMarkNode)==null||e.close(),delete this.waterMarkNode,delete this._waterMarkOption;let r=yield this.getWatermarkImage((t=this.cameraTrack)==null?void 0:t.settings.width,(i=this.cameraTrack)==null?void 0:i.settings.height);this._waterMarkOption={x:0,y:0,width:r.width,height:r.height,image:r},this.update()})}setVirtualBackground(e){return g(this,null,function*(){if(e){if(this._use2d&&!this._autoSwitchRenderMode)return Promise.reject(new Error("not support virtual background in 2d mode"));this._bgAssetPath=e.assetPath,e.type==="image"?this._virtualBackground=yield Zo(e.imageUrl):(this.blurRadius=e.blurLevel||this.blurRadius||3,this._virtualBackground=e.type)}else this._virtualBackground=void 0;this.log.info("".concat(this._virtualBackground?"start":"stop"," virtual background, ").concat((e==null?void 0:e.type)||"",", ").concat(this.blurRadius||"")),this.update()})}get mixScreen(){return this._isMixScreen}set mixScreen(e){var t;this._isMixScreen=e,this._isMixScreen||((t=this.screenNode)==null||t.close(),delete this.screenNode),this.update()}set mirror(e){var t;this._isMirror!==e&&(this._isMirror=e,this._isMirror||((t=this.mirrorNode)==null||t.close(),delete this.mirrorNode),this.update())}get mirror(){return this._isMirror}enableAr(e){this.arTrack=e,this.isUsingArTrack=!0,this.update()}updateAr(){return g(this,null,function*(){var e;(e=this.cameraTrack)==null||!e.mediaTrack||(yield this.virtualBackgroundInstance.ar.updateInputTrack(this.cameraTrack.mediaTrack.clone()))})}disableAr(){var e;this.isUsingArTrack=!1,(e=this.arTrack)==null||e.stop(),this.arTrack=void 0,this.update()}clear(){var e;(e=this.videoContext)==null||e.disconnect(),delete this.destination,delete this.cameraNode,delete this.mirrorNode,delete this.screenNode,delete this.waterMarkNode}},ZU=0,e1=class extends X{constructor(e){super("room"),this.seq=++ZU,this.role="anchor",this.joinParams=null,this.localTracks=new Set,this.enableAutoPlayDialog=!0,this.autoReceiveAudio=!0,this.autoReceiveVideo=!0,this.scheduleResult={domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null},this._isUsingCachedSchedule=!1,this._log=b.createLogger({id:"r".concat(this.seq)}),this._joinedTimestamp=0,this.isDestroyed=!1,this.useStringRoomId=!!e.useStringRoomId,We(e.autoReceiveAudio)&&(this.autoReceiveAudio=e.autoReceiveAudio),We(e.autoReceiveVideo)&&(this.autoReceiveVideo=e.autoReceiveVideo),We(e.enableAutoPlayDialog)&&(this.enableAutoPlayDialog=e.enableAutoPlayDialog),this._sdkType=e.sdkType,this.keyPointManager=new GU({room:this,frameWorkType:e.frameWorkType,component:e.component,language:e.language}),this.callDurationCalculator=new WU({room:this}),this.badCaseDetector=new JU({room:this}),this.audioManager=new FV(this),this.videoManager=new $U(this)}get isMainStreamPublished(){for(let e of this.localTracks)if(4&e.mediaType)return!0;return!1}get isAuxStreamPublished(){for(let e of this.localTracks)if(2&e.mediaType)return!0;return!1}get hasAuxStream(){for(let e of this.remotePublishedUserMap.values())if(e.muteState.hasAuxiliary)return!0;return this.isAuxStreamPublished}getLogger(){return this._log}get isJoining(){return this.state.toString()==="joining"}get isJoined(){return this.state==="joined"}get isLeft(){return this.state==="left"}addTrack(e){return g(this,null,function*(){return this.publish(e)})}removeTrack(e){return g(this,null,function*(){return this.unpublish(e)})}replaceTrack(e){return g(this,null,function*(){})}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAIVoice(e){throw new Error("Method not implemented.")}setProxyServer(e){if(re(e))e.startsWith("wss://")?this.proxy_ws=e:e.startsWith("https://")&&(this.proxy_wt=e);else if(jt(e)){let{websocketProxy:t,webtransportProxy:i,loggerProxy:r,scheduleProxy:n,unifiedProxy:s}=e;this.proxy_ws=t,this.proxy_wt=i,this.proxy_unified=s,s?(ES([s,s]),ds("https://".concat(s))):(r&&ds(r),n&&ES(n))}R.once(A.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({sched_domain:rr.main,sched_back_domain:rr.backup,signal_domain:this.proxy_ws||this.proxy_wt||""}))}getRemoteAudioStats(){return g(this,null,function*(){let e={};return this.remotePublishedUserMap.forEach(t=>{e[t.userId]=t.remoteAudioTrack.stat}),e})}getTransportStats(){return g(this,null,function*(){var e;let t={rtt:((e=this.quality)==null?void 0:e.uplinkRTT)||0,downlinksRTT:{}};if(this.quality)for(let i of this.quality.downlinkInfo)t.downlinksRTT[i.userId]=i.rtt;return t})}getRemoteVideoStats(){return g(this,arguments,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"main";return function*(){let i={};return e.remotePublishedUserMap.forEach(r=>{let n=t==="auxiliary"?r.remoteAuxiliaryTrack:r.remoteVideoTrack;i[r.userId]=n.stat}),i}()})}checkDestroy(){if(this.isDestroyed)throw new N({code:C.INVALID_OPERATION,message:j({key:B.CLIENT_DESTROYED,data:{funName:"join"}})})}destroy(){if(this.isJoined)throw this._log.warn(ut.INVALID_DESTROY),new N({code:C.INVALID_OPERATION,message:j({key:B.INVALID_DESTROY})});this._log.info("destroy room"),this.audioManager.destroy(),this.videoManager.destroy(),this.keyPointManager.destroy(),this.callDurationCalculator.destroy(),this.badCaseDetector.destroy(),this.isDestroyed=!0,R.emit(A.ROOM_DESTROY,{room:this})}schedule(e,t){return g(this,null,function*(){var i,r;let n=W();try{let{isCached:s,result:a,detailCost:c}=yield Ux({userId:this.userId,sdkAppId:this.sdkAppId,roomId:this.useStringRoomId?e.strRoomId:e.roomId,useStringRoomId:this.useStringRoomId,version:St,userSig:this.userSig,role:this.scene==="live"?e.role:void 0,frameWorkType:t,latencyLevel:e.latencyLevel});this._isUsingCachedSchedule=s,this._log.info("schedule cache:".concat(+s," ").concat(Gt(a,{keysToExclude:["username","credential"]}))),s&&R.once(A.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({scheduleCache:1})),this.scheduleResult=O(O({},this.scheduleResult),a),ge((i=a.config)==null?void 0:i.retryCount)&&Yy(a.config.retryCount),re((r=a.config)==null?void 0:r.loggerDomain)&&ds(a.config.loggerDomain),R.emit(A.JOIN_SCHEDULE_SUCCESS,{room:this,schedule:this.scheduleResult,detailCost:c}),L.addSuccessEvent({key:521700,cost:W()-n,split:50})}catch(s){throw L.addFailedEvent({key:521700,error:s}),s}})}},t1=Ie(Ve()),cI=Ie(Py());function lI(e){var t;let i=[];for(let r=0;r<e.rtp.length;r++){if(["rtx","red","ulpfec"].includes(e.rtp[r].codec))continue;let n=e.fmtp.filter(s=>s.payload===e.rtp[r].payload)[0];i.push({payload:e.rtp[r].payload,codec:e.rtp[r].codec,fmtp:n?n.config:"",rate:e.rtp[r].rate,rtx:((t=e.rtp[r+1])==null?void 0:t.codec)==="rtx"?e.rtp[r+1].payload:0,rtcpFb:((e==null?void 0:e.rtcpFb)||[]).filter(s=>s.payload===e.rtp[r].payload).map(s=>{let{type:a,subtype:c}=s;return{id:a,params:c?[c]:[]}})})}return i}var i1=(e,t)=>g(void 0,null,function*(){var i;let r=Se(e),n={ice:{ufrag:"",password:""},dtls:{hash:"",fingerprint:"",setup:""},audio:{codecs:[],extensions:[]},video:{codecs:[],decoders:[],extensions:[]},useDataChannel:!1};n.ice.ufrag=String(r.media[0].iceUfrag),n.ice.password=r.media[0].icePwd||"",r.fingerprint&&(n.dtls.hash=r.fingerprint.type,n.dtls.fingerprint=r.fingerprint.hash,n.dtls.setup=r.setup||""),r.media[0].fingerprint&&(n.dtls.hash=r.media[0].fingerprint.type,n.dtls.fingerprint=r.media[0].fingerprint.hash),n.dtls.setup=r.media[0].setup||"";let s=r.media[0],a=r.media[1];s.ext&&(n.audio.extensions=s.ext.map(l=>({id:l.value,uri:l.uri}))),a.ext&&(n.video.extensions=a.ext.map(l=>({id:l.value,uri:l.uri})));let c={codec:s.rtp[0].codec,fmtp:s.fmtp[0].config,payload:s.fmtp[0].payload,rate:s.rtp[0].rate,channel:s.rtp[0].encoding,rtcpFb:[],rtx:0};(i=s.rtcpFb)==null||i.forEach(l=>{let{payload:d,type:u,subtype:p}=l;if(d===c.payload){let m={id:u,params:[]};p&&m.params.push(p),c.rtcpFb.push(m)}}),n.audio.codecs.push(c);let o=["h264","vp8"];return t&&o.shift(),n.video.codecs=[...lI(a)].filter(l=>o.includes(l.codec.toLocaleLowerCase())),n.video.decoders=(yield function(){return g(this,null,function*(){let l=new RTCPeerConnection;l.addTransceiver(_.VIDEO,{direction:_.TRANSCEIVER_DIRECTION_RECVONLY});let d=yield l.createOffer();if(!d.sdp)return[];let u=lI(Se(d.sdp).media[0]);return l.close(),u})}()).filter(l=>["h264","vp8"].includes(l.codec.toLocaleLowerCase())),n}),r1=e=>{let{serverAbility:t,clientAbility:i,offerSDP:r,enableCustomMessage:n}=e,s=Se(r),a={extmapAllowMixed:"extmap-allow-mixed",groups:s.groups,icelite:"ice-lite",media:[],msidSemantic:{semantic:"",token:"WMS"},name:"-",origin:{address:"127.0.0.1",username:"-",sessionId:String(Date.now()),sessionVersion:1,netType:"IN",ipVer:4},timing:{start:0,stop:0},version:0},c={candidates:t.candidates.map(o=>({component:1,foundation:"1",generation:0,ip:o.ip,port:o.port,priority:o.priority,transport:o.foundation,type:o.type})),connection:{version:4,ip:"0.0.0.0"},direction:_.TRANSCEIVER_DIRECTION_RECVONLY,ext:t.audio.extensions.map(o=>({value:o.id,uri:o.uri})),fingerprint:{type:t.dtls.hash,hash:t.dtls.fingerprint},fmtp:[{payload:t.audio.codecs[0].payload,config:t.audio.codecs[0].fmtp}],icePwd:t.ice.password,iceUfrag:t.ice.ufrag,mid:"0",payloads:String(t.audio.codecs[0].payload),port:s.media[0].port,protocol:s.media[0].protocol,type:_.AUDIO,setup:t.dtls.setup,rtcpFb:t.audio.codecs[0].rtcpfb.map(o=>({payload:t.audio.codecs[0].payload,type:o.id,subtype:o.params[0]})),rtcpMux:"rtcp-mux",rtcpRsize:"rtcp-rsize",rtp:[{payload:t.audio.codecs[0].payload,codec:t.audio.codecs[0].codec,rate:t.audio.codecs[0].rate,encoding:t.audio.codecs[0].channels}]};return a.media.push(c),[1,2,3].forEach(o=>{a.media.push(uI({mid:o,serverAbility:t,clientAbility:i,parsedOffer:s}))}),n&&a.media.push(s.media.find(o=>o.mid==="dc")),Di(a)},uI=e=>{let{mid:t,serverAbility:i,clientAbility:r,parsedOffer:n,isDownlink:s=!1}=e,a={candidates:i.candidates.map(c=>({component:1,foundation:"1",generation:0,ip:c.ip,port:c.port,priority:c.priority,transport:c.foundation,type:c.type})),connection:{version:4,ip:"0.0.0.0"},direction:_.TRANSCEIVER_DIRECTION_RECVONLY,ext:i.video.extensions.map(c=>({value:c.id,uri:c.uri})),fingerprint:{type:i.dtls.hash,hash:i.dtls.fingerprint},fmtp:[],icePwd:i.ice.password,iceUfrag:i.ice.ufrag,mid:String(t),payloads:"",port:n.media[0].port,protocol:n.media[0].protocol,type:_.VIDEO,setup:i.dtls.setup,rtcpFb:[],rtcpMux:"rtcp-mux",rtcpRsize:"rtcp-rsize",rtp:[]};if(s)(i.video.decoders||i.video.codecs).forEach(c=>{Cc(a,c)});else{let c=i.video.codecs.findIndex(l=>l.codec.toLowerCase()===(i.useVp8?"vp8":"h264")),o=i.video.codecs[c]||r.video.codecs[0];Cc(a,o)}return a},Cc=(e,t)=>{e.payloads="".concat(e.payloads," ").concat(t.payload).trim(),e.fmtp.push({payload:t.payload,config:t.fmtp}),e.rtcpFb=[...e.rtcpFb||[],...(t.rtcpfb||t.rtcpFb).map(i=>({payload:t.payload,type:i.id,subtype:i.params[0]}))],e.rtp.push({payload:t.payload,codec:t.codec.toUpperCase(),rate:t.rate}),t.rtx&&(e.payloads="".concat(e.payloads," ").concat(t.rtx),e.fmtp.push({payload:t.rtx,config:"apt=".concat(t.payload)}),e.rtp.push({payload:t.rtx,codec:"rtx",rate:t.rate}))},mt,n1=(e,t,i)=>{let r=cI.default.parse(e);return r.media.forEach((n,s)=>{var a;(n.type===_.AUDIO||n.type===_.VIDEO)&&(function(c){if(!c.rtcpFb)return;let o=[];c.rtcpFb.forEach((l,d)=>{var u;o.push(l),c.rtcpFb&&((u=c.rtcpFb[d+1])==null?void 0:u.payload)!==l.payload&&l.type!=="rrtr"&&o.push({payload:l.payload,type:"rrtr"})}),c.rtcpFb=o}(n),function(c){c.type===_.VIDEO&&c.fmtp&&c.fmtp.forEach(o=>{o.config.includes("apt")||(o.config+=";sps-pps-idr-in-keyframe=1")})}(n),function(c){c.type===_.AUDIO&&c.fmtp&&c.fmtp.forEach(o=>{o.config+=";sprop-stereo=1;stereo=1"})}(n),function(c){let o=new Set(["urn:ietf:params:rtp-hdrext:sdes:mid","urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id","urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id"]);c.ext&&(c.ext=c.ext.filter(l=>!o.has(l.uri)))}(n),n.type===_.VIDEO&&(s<4?(n.payloads="",n.fmtp=[],n.rtp=[],n.rtcpFb=[],t.video.codecs.forEach(c=>Cc(n,c))):i&&(n.payloads="",n.fmtp=[],n.rtp=[],n.rtcpFb=[],(i.video.decoders||i.video.codecs).forEach(c=>Cc(n,c))))),(a=n.payloads)!=null&&a.includes("datachannel")&&r.groups&&n.mid&&(r.groups[0].mids=r.groups[0].mids.replace(n.mid,"dc"),n.mid="dc")}),cI.default.write(r)},Tr=((mt=Tr||{}).TRACK="track",mt.DATA_CHANNEL_MESSAGE="data_channel_msg",mt[mt.CONNECTION_STATE_CHANGED="connection-state-changed"]="CONNECTION_STATE_CHANGED",mt[mt.FIREWALL_RESTRICTION="firewall-restriction"]="FIREWALL_RESTRICTION",mt.RECONNECTED="spc-reconnected",mt.RECONNECT_FAILED="spc-reconnect-failed",mt.ERROR="error",mt.SEI_MESSAGE="sei-message",mt),dI=0,hI=!1,s1=new Set,a1=1,aa=class extends t1.default{constructor(e){let{signalChannel:t,room:i,enableCustomMessage:r}=e;super(),h(this,"stat",{iceStartTime:0,iceEndTime:0,dtlsStartTime:0,dtlsEndTime:0,peerConnectionStartTime:0,peerConnectionEndTime:0}),h(this,"currentState","DISCONNECTED"),h(this,"_room"),h(this,"_signalChannel"),h(this,"_peerConnection",null),h(this,"_datachannel",null),h(this,"_enableCustomMessage"),h(this,"_log"),h(this,"_downlinkMIDMap",new Map),h(this,"_downlinkMIDUserIDMap",new Map),h(this,"_reconnectionTimer",-1),h(this,"reconnectionCount",0),h(this,"clientAbility"),h(this,"_serverAbility",null),h(this,"addDownlinkQueue",new Set),h(this,"removeDownlinkQueue",new Set),h(this,"_parsedAnswer",null),h(this,"_updateSDPPromise",null),h(this,"_waitForPCConnectedPromise"),h(this,"_waitForPCConnectedPromiseReject",null),h(this,"_isSDPLogged",!1),h(this,"abortMap",new Map),h(this,"enableInsertableStreams",!1),this._room=i,this._enableCustomMessage=r,this._signalChannel=t,this._log=b.createLogger({id:"spc".concat(a1++),userId:this._room.userId,sdkAppId:this._room.sdkAppId}),this._room.enableSEI&&or&&(this.enableInsertableStreams=!0)}get isH264EncodeSupported(){let e=this._room.checkSystemResult.detail.isH264EncodeSupported;return this._serverAbility&&(e=e&&!!this._serverAbility.video.codecs.find(t=>t.codec.toLowerCase()==="h264")),e}addAbortController(e,t){var i;(i=this.abortMap.get(e))==null||i.abort("destory"),this.abortMap.set(e,t)}get isVP8EncodeSupported(){let e=this._room.checkSystemResult.detail.isVp8EncodeSupported;return this._serverAbility&&(e=e&&this._serverAbility.useVp8),e}get videoCodec(){var e;return(e=this._serverAbility)!=null&&e.useVp8?"vp8":"h264"}get downlinkVideoCodec(){var e;return(e=this._serverAbility)!=null&&e.video.codecs.find(t=>t.codec.toLowerCase()==="h264")?"h264":"vp8"}get isUsingH264(){return this.videoCodec==="h264"}get uplinkSSRC(){return this._peerConnection&&this._peerConnection.localDescription?(e=>{let t=Se(e),i={audioSsrc:0,audioRtxSsrc:0,bigVideoSsrc:0,bigVideoRtxSsrc:0,smallVideoSsrc:0,smallVideoRtxSsrc:0,auxVideoSsrc:0,auxVideoRtxSsrc:0};return t.media.forEach((r,n)=>{var s;if(r.ssrcs&&!I(r.ssrcs[0].id)){let a=Number(r.ssrcs[0].id),c=Number((s=r.ssrcs.filter(o=>o.attribute==="cname")[1])==null?void 0:s.id);switch(n){case 0:i.audioSsrc=a;break;case 1:i.bigVideoSsrc=a,i.bigVideoRtxSsrc=c;break;case 2:i.smallVideoSsrc=a,i.smallVideoRtxSsrc=c;break;case 3:i.auxVideoSsrc=a,i.auxVideoRtxSsrc=c}}}),i})(this._peerConnection.localDescription.sdp):{audioSsrc:0,audioRtxSsrc:0,bigVideoSsrc:0,bigVideoRtxSsrc:0,smallVideoSsrc:0,smallVideoRtxSsrc:0,auxVideoSsrc:0,auxVideoRtxSsrc:0}}get isReconnecting(){return this.currentState==="RECONNECTING"||this._reconnectionTimer>0||this.reconnectionCount>0}get dtlsTransport(){if(!this._peerConnection)return null;let e=this._peerConnection.getSenders();return e.length===0?null:e[0].transport}initialize(){return g(this,null,function*(){var e;let t;try{this._peerConnection=new RTCPeerConnection({encodedInsertableStreams:this.enableInsertableStreams,offerExtmapAllowMixed:!0,iceServers:this._room.getIceServers(),iceTransportPolicy:this._room.getIceTransportPolicy(),sdpSemantics:this._room.sdpSemantics,bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"}),this._peerConnection.oniceconnectionstatechange=()=>{if(!this._peerConnection)return;let r=this._peerConnection.iceConnectionState;this._log.debug("ice state: ".concat(r)),r==="checking"&&this.stat.iceStartTime===0?this.stat.iceStartTime=Date.now():r==="connected"&&this.stat.iceEndTime===0&&(this.stat.iceEndTime=Date.now())},this._peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this),this._peerConnection.ontrack=r=>this.emit("track",r),this._enableCustomMessage&&(this._datachannel=this._peerConnection.createDataChannel("".concat(this._room.userId,"dc")),this._datachannel.binaryType="arraybuffer",this._datachannel.onopen=()=>{this._log.info("datachannel open")},this._datachannel.onclose=()=>{this._log.warn("datachannel close")},this._datachannel.onmessage=r=>{let n=new c1(r.data);this.emit("data_channel_msg",{data:n})},this._datachannel.onerror=r=>{this._log.warn("datachannel error",r)}),this._peerConnection.addTransceiver(_.AUDIO,{direction:_.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(_.VIDEO,{direction:_.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(_.VIDEO,{direction:_.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(_.VIDEO,{direction:_.TRANSCEIVER_DIRECTION_SENDONLY}),t=yield this._peerConnection.createOffer();let i=!this.isH264EncodeSupported;return I((e=this._room.scheduleResult.config)==null?void 0:e.remove264FromSDP)||(i=i&&this._room.scheduleResult.config.remove264FromSDP),this.clientAbility=yield i1(t.sdp,i),yield this.setOffer(t),this.dtlsTransport&&(this.dtlsTransport.onstatechange=()=>{let{dtlsTransport:r}=this;!r||(this._log.debug("dtls state: ".concat(r.state)),r.state==="connecting"&&this.stat.dtlsStartTime===0?this.stat.dtlsStartTime=Date.now():r.state==="connected"&&this.stat.dtlsEndTime===0&&(this.stat.dtlsEndTime=Date.now()))}),L.addSuccessEvent({key:521707}),this.clientAbility}catch(i){throw L.addFailedEvent({key:521707,error:i}),this._log.error("initialize failed ".concat(i,`
127
+ offer: `).concat(t==null?void 0:t.sdp)),i}})}connect(e){let t=arguments.length>1&&arguments[1]!==void 0&&arguments[1];return g(this,null,function*(){try{if(this.currentState==="CONNECTED")return;let i=W(),r={type:"answer",sdp:r1({serverAbility:e,clientAbility:this.clientAbility,offerSDP:this._peerConnection.localDescription.sdp,enableCustomMessage:this._enableCustomMessage})};this._serverAbility=e,yield this.setAnswer(r),yield this.waitForPeerConnectionConnected(),t||L.addSuccessEvent({key:521703,cost:W()-i})}catch(i){let r=i instanceof N&&i.code===C.API_CALL_ABORTED;throw r||this._log.error("connect failed: ".concat(i),e),this.reset(),!r&&!this.isReconnecting&&(L.addFailedEvent({key:521703,error:i}),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection()),i}})}reconnect(){return g(this,null,function*(){if(this._reconnectionTimer===-1){if(!this._signalChannel.isConnected)return this._log.warn("reconnect() wait signal channel is connected"),void this._signalChannel.once(vn,this.reconnect,this);try{this.reconnectionCount++,this._log.warn("reconnect() trying [".concat(this.reconnectionCount,"]")),this.reset();let e=yield this.initialize(),t=yield this._signalChannel.sendWaitForResponse({command:OU,responseCommand:K.REBUILD_PEER_CONNECTION_RES,data:{ability:e},enableLog:!1});if(t.data.code!==0)throw new N({code:t.data.code,message:t.data.message});yield this.connect(t.data.data.ability,!0),L.addSuccessEvent({key:521704}),this._log.warn("reconnect() success"),this.stopReconnection(),R.emit(A.SPC_RECONNECTED,{room:this._room}),this.emit("spc-reconnected")}catch(e){if(!this.isReconnecting)return;if(e!=null&&e.message.includes("timeout")){let t=ln(this.reconnectionCount);this._log.warn("reconnect() timeout, try again after ".concat(t/1e3,"s")),this._reconnectionTimer=window.setTimeout(()=>{this.clearReconnectionTimer(),this.reconnect()},t)}else this._log.error("reconnect() failed ".concat(e==null?void 0:e.code," ").concat(e)),L.addFailedEvent({key:521704,error:e}),this.reconnectionCount>=rn()&&this._log.warn("SDK has tried reconnect for ".concat(rn()," times, but all failed, please check your network")),this.stopReconnection(),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.emit("error")}}else this._log.warn("reconnect() is reconnecting, ignore current reconnection")})}getPeerConnection(){return this._peerConnection}startReconnection(){return g(this,null,function*(){this._log.warn("start reconnect"),this._updateSDPPromise=null,this.emitConnectionStateChangedEvent("RECONNECTING"),yield this.reconnect()})}stopReconnection(){this.isReconnecting&&(this._log.info("stop reconnect"),this.reconnectionCount=0,this.clearReconnectionTimer(),this._signalChannel.off(vn,this.reconnect,this))}checkPeerConnectionToReconnect(){var e;!this.isReconnecting&&((e=this._peerConnection)==null?void 0:e.connectionState)===fe.CLOSED&&this.startReconnection()}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}onConnectionStateChange(e){let t=this._peerConnection.iceConnectionState,i=this.getDTLSTransportState();this._log.info("connectionState: ".concat(e.target.connectionState," ICE: ").concat(t," DTLS: ").concat(i)),e.target.connectionState===fe.CONNECTING&&(this.stat.peerConnectionStartTime===0&&(this.stat.peerConnectionStartTime=Date.now()),this.emitConnectionStateChangedEvent("CONNECTING")),(e.target.connectionState===fe.FAILED||e.target.connectionState===fe.CLOSED)&&(this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection()),(e.target.connectionState===fe.CONNECTED||e.target.connectionState===fe.COMPLETED)&&(this.stat.peerConnectionEndTime===0&&(this.stat.peerConnectionEndTime=Date.now()),R.emit(A.SINGLE_CONNECTION_STAT,{room:this._room,stat:{ice:this.stat.iceEndTime-this.stat.iceStartTime,dtls:this.stat.dtlsEndTime-this.stat.dtlsStartTime,peerConnection:this.stat.peerConnectionEndTime-this.stat.peerConnectionStartTime}}),this.logSelectedCandidate(),this.emitConnectionStateChangedEvent("CONNECTED"))}getDTLSTransportState(){if(!this._peerConnection)return mi;let e=null;return Fs()&&this._peerConnection.getSenders().length!==0?(e=this._peerConnection.getSenders()[0].transport,ic()&&this._peerConnection.getReceivers().length!==0&&e?e.state:mi):mi}emitConnectionStateChangedEvent(e){e!==this.currentState&&(this.currentState==="RECONNECTING"&&e==="CONNECTING"||(this.emit(Tr.CONNECTION_STATE_CHANGED,{prevState:this.currentState,state:e}),this.currentState=e))}logSelectedCandidate(){return g(this,null,function*(){if(!this._peerConnection)return;let e=yield this._peerConnection.getStats();for(let[t,i]of e)if(Us(i)){let r=e.get(i.localCandidateId),n=e.get(i.remoteCandidateId);r&&(this._log.info("local candidate: ".concat(r.candidateType," ").concat(r.protocol,":").concat(r.ip||r.address,":").concat(r.port," ").concat(r.networkType||""," ").concat(r.candidateType==="relay"?"relayProtocol:".concat(r.relayProtocol):"")),r.networkType&&AS(r.networkType)),n&&this._log.info("remote candidate: ".concat(n.candidateType," ").concat(n.protocol,":").concat(n.ip||n.address,":").concat(n.port));break}})}waitForPeerConnectionConnected(){return this._waitForPCConnectedPromise||(this._waitForPCConnectedPromise=new Promise((e,t)=>{if(this.currentState==="CONNECTED")return e();this._waitForPCConnectedPromiseReject=t;let i=a=>{a.state==="CONNECTED"&&(clearTimeout(s),n(),e())},r=a=>{let{room:c}=a;c===this._room&&(clearTimeout(s),n(),t(new N({code:C.API_CALL_ABORTED,message:j({key:B.CONNECTION_ABORTED,data:"leave room"})})))},n=()=>{R.off(A.LEAVE_SUCCESS,r,this),this.off(Tr.CONNECTION_STATE_CHANGED,i,this)},s=setTimeout(()=>{n();let a=new N({code:C.API_CALL_TIMEOUT,message:"connection timeout"});var c;dI+=1,c=this._signalChannel.isConnected,dI>2&&!hI&&s1.size===0&&c&&(this._log.warn("firewall restriction"),hI=!0,this.emit(Tr.FIREWALL_RESTRICTION)),t(a)},Yd);R.on(A.LEAVE_SUCCESS,r,this),this.on(Tr.CONNECTION_STATE_CHANGED,i,this)}),this._waitForPCConnectedPromise=this._waitForPCConnectedPromise.finally(()=>{this._waitForPCConnectedPromise=null,this._waitForPCConnectedPromiseReject=null})),this._waitForPCConnectedPromise}waitForReconnected(){return this.isReconnecting?new Promise((e,t)=>{this.once("spc-reconnected",e),this.once("error",t)}):Promise.resolve()}addDownlink(e){return g(this,null,function*(){if(this._log.info("addDownlink(".concat(e.userId,") trying")),this.isReconnecting&&(yield this.waitForReconnected()),this._updateSDPPromise&&(yield this._updateSDPPromise),this.updateLocalAndRemoteSDPConfig(e),this.addDownlinkQueue.size===0)try{yield this.updateSDP(),this._log.info("addDownlink(".concat(e.userId,") done"))}catch(t){this._log.error("addDownlink(".concat(e.userId,") failed ").concat(t)),yield this.startReconnection()}})}updateLocalAndRemoteSDPConfig(e){let{ssrc:t,userId:i,tinyId:r}=e;if(!this._peerConnection)return;this._log.info("updateLocalAndRemoteSDPConfig ".concat(i," ").concat(JSON.stringify(t)));let n=this._peerConnection.getTransceivers().filter(u=>u.direction==="inactive").slice(0,3).map(u=>(u.direction=_.TRANSCEIVER_DIRECTION_RECVONLY,Number(u.mid)));this._parsedAnswer||(this._parsedAnswer=Se(this._peerConnection.remoteDescription.sdp));let s,a,c,o=this._parsedAnswer.media.filter(u=>{var p;return(p=u.ssrcs)==null?void 0:p.find(m=>{var f;return(f=m.value)==null?void 0:f.includes(r)})});if(o.length===3)s=o[0],a=o[1],c=o[2];else if(n.length===3)s=this._parsedAnswer.media.find(u=>Number(u.mid)===Number(n[0])),a=this._parsedAnswer.media.find(u=>Number(u.mid)===Number(n[1])),c=this._parsedAnswer.media.find(u=>Number(u.mid)===Number(n[2]));else if(n.length===0){this._peerConnection.addTransceiver(_.AUDIO,{direction:_.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(_.VIDEO,{direction:_.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(_.VIDEO,{direction:_.TRANSCEIVER_DIRECTION_RECVONLY}),s=JSON.parse(JSON.stringify(this._parsedAnswer.media[0]));let u=uI({mid:1,serverAbility:this._serverAbility,clientAbility:this.clientAbility,parsedOffer:Se(this._peerConnection.localDescription.sdp),isDownlink:!0});a=JSON.parse(JSON.stringify(u)),c=JSON.parse(JSON.stringify(u)),s.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(s),a.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(a),c.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(c)}s.direction=_.TRANSCEIVER_DIRECTION_SENDONLY;let l="".concat(r,"-").concat(t.audio);s.ssrcs=[{id:t.audio,attribute:"cname",value:"".concat(l)},{id:t.audio,attribute:"msid",value:"".concat(l,"-").concat(_.MAIN," ").concat(l,"-audio")}],a.direction=_.TRANSCEIVER_DIRECTION_SENDONLY,a.ssrcs=[{id:t.video,attribute:"cname",value:"".concat(l)},{id:t.video,attribute:"msid",value:"".concat(l,"-").concat(_.MAIN," ").concat(l,"-bigvideo")},{id:t.videoRtx,attribute:"cname",value:"".concat(l)},{id:t.videoRtx,attribute:"msid",value:"".concat(l,"-").concat(_.MAIN," ").concat(l,"-bigvideo")}],a.ssrcGroups=[{semantics:"FID",ssrcs:"".concat(t.video," ").concat(t.videoRtx)}],c.direction=_.TRANSCEIVER_DIRECTION_SENDONLY;let d="".concat(l,"-aux");c.ssrcs=[{id:t.auxiliary,attribute:"cname",value:d},{id:t.auxiliary,attribute:"msid",value:"".concat(d," ").concat(l,"-aux").concat(_.VIDEO)},{id:t.auxiliaryRtx,attribute:"cname",value:"".concat(d," ").concat(l,"-aux").concat(_.VIDEO)},{id:t.auxiliaryRtx,attribute:"msid",value:"".concat(d," ").concat(l,"-aux").concat(_.VIDEO)}],c.ssrcGroups=[{semantics:"FID",ssrcs:"".concat(t.auxiliary," ").concat(t.auxiliaryRtx)}],this._parsedAnswer.groups&&(this._parsedAnswer.groups[0].mids=this._parsedAnswer.media.map(u=>u.mid).join(" ")),this._downlinkMIDMap.set(i,[s.mid,a.mid,c.mid]),this._downlinkMIDUserIDMap.set(s.mid,i),this._downlinkMIDUserIDMap.set(a.mid,i),this._downlinkMIDUserIDMap.set(c.mid,i)}removeDownlink(e){return g(this,null,function*(){if(!this._downlinkMIDMap.has(e)||!this._peerConnection)return;this._log.info("removeDownlink(".concat(e,") trying")),this.isReconnecting&&(yield this.waitForReconnected()),this._updateSDPPromise&&(yield this._updateSDPPromise);let t=this._downlinkMIDMap.get(e),i=!1;this._peerConnection.getTransceivers().forEach(r=>{t!=null&&t.includes(Number(r.mid))&&(i=!0,r.direction="inactive")}),this._parsedAnswer||(this._parsedAnswer=Se(this._peerConnection.remoteDescription.sdp)),this._parsedAnswer.media.forEach(r=>{t!=null&&t.includes(Number(r.mid))&&(i=!0,r.direction="inactive",r.ssrcs=[],r.ssrcGroups=[])}),this.removeDownlinkQueue.size===0&&i&&(yield this.updateSDP()),this._downlinkMIDMap.delete(e),t==null||t.forEach(r=>this._downlinkMIDUserIDMap.delete(r)),this._log.info("removeDownlink(".concat(e,") done"))})}setBandwidth(e){return g(this,null,function*(){if(!this._peerConnection)return;let{audio:t,bigVideo:i,smallVideo:r,auxVideo:n}=e;try{if(xh()){let s=this._peerConnection.getSenders().slice(0,4);for(let c=0;c<s.length;c++){let o,l=s[c];c===0&&t?o=t:c===1&&i?o=i:c===2&&r?o=r:c===3&&n&&(o=n),o&&(yield this.setSenderMaxBitrate(l,o))}let a=!1;i&&s[1].track&&(a=this.setStartBitrate(1,i)),n&&s[3].track&&(a=this.setStartBitrate(3,n)||a),a&&(yield this.updateSDP())}else yield this.setBandwidthBySDP(e);this._log.info("setBandwidth ".concat(JSON.stringify(e)))}catch(s){this._log.error("failed to set bandwidth: ".concat(s))}})}setStartBitrate(e,t){var i,r;return!((i=this._peerConnection)==null||!i.remoteDescription||(this._parsedAnswer||(this._parsedAnswer=Se(this._peerConnection.remoteDescription.sdp)),(r=this._parsedAnswer.media[e])==null||!r.fmtp[0]))&&(this._parsedAnswer.media[e].fmtp[0].config+=";x-google-start-bitrate=".concat(t>5e3?5e3:t),!0)}setSenderMaxBitrate(e,t){let i=e.getParameters();return(!i.encodings||i.encodings.length===0)&&(i.encodings=[{}]),t==="unlimited"?delete i.encodings[0].maxBitrate:i.encodings[0].maxBitrate=1e3*t,e.setParameters(i)}setBandwidthBySDP(e){let{audio:t,bigVideo:i,smallVideo:r,auxVideo:n}=e;if(!this._peerConnection||!this._peerConnection.localDescription)return;let s=Se(this._peerConnection.localDescription.sdp);this._parsedAnswer||(this._parsedAnswer=Se(this._peerConnection.remoteDescription.sdp));let a=ue?"TIAS":"AS";t&&(s.media[0].bandwidth=[{type:a,limit:ue?1e3*t:t}],this._parsedAnswer.media[0].bandwidth=[{type:a,limit:ue?1e3*t:t}]),i&&(s.media[1].bandwidth=[{type:a,limit:ue?1e3*i:i}],this._parsedAnswer.media[1].bandwidth=[{type:a,limit:ue?1e3*i:i}]),r&&(s.media[2].bandwidth=[{type:a,limit:ue?1e3*r:r}],this._parsedAnswer.media[2].bandwidth=[{type:a,limit:ue?1e3*r:r}]),n&&(s.media[3].bandwidth=[{type:a,limit:ue?1e3*n:n}],this._parsedAnswer.media[3].bandwidth=[{type:a,limit:ue?1e3*n:n}]);let c={type:"offer",sdp:Di(s)};return this.updateSDP({localDescription:c})}setScaleResolutionDownBy(e,t){if(t===1)return;let i=e.getParameters();return(!i.encodings||i.encodings.length===0)&&(i.encodings=[{}]),i.encodings[0].scaleResolutionDownBy=t,e.setParameters(i)}updateSDP(){let{localDescription:e}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!this._parsedAnswer)return Promise.resolve();let t=Di(this._parsedAnswer);return this._updateSDPPromise=new Promise((i,r)=>g(this,null,function*(){var n,s;try{!e&&this._peerConnection&&(this._log.info("creating offer"),e=yield this._peerConnection.createOffer()),e&&(yield this.setOffer(e)),yield this.setAnswer({type:"answer",sdp:t}),this._updateSDPPromise=null,i()}catch(a){this._log.error(a),!this._isSDPLogged&&this._peerConnection&&(this._log.warn("current offer: ".concat(this.filterSDPDirection((n=this._peerConnection.localDescription)==null?void 0:n.sdp),`
128
+ next offer: `).concat(this.filterSDPDirection(e==null?void 0:e.sdp))),this._log.warn("current answer: ".concat(this.filterSDPDirection((s=this._peerConnection.remoteDescription)==null?void 0:s.sdp),`
129
+ next answer: `).concat(this.filterSDPDirection(t))),this._log.warn("offer: ".concat(e==null?void 0:e.sdp)),this._log.warn("answer: ".concat(t)),this._log.warn("transceivers: ".concat(JSON.stringify(this._peerConnection.getTransceivers().map(c=>{let{mid:o,currentDirection:l,direction:d,stopped:u}=c;return{mid:o,currentDirection:l,direction:d,stopped:u}})))),this._log.warn("parsedAnswer: ".concat(JSON.stringify(this._parsedAnswer))),this._isSDPLogged=!0),this._updateSDPPromise=null,r(a)}})),this._updateSDPPromise}filterSDPDirection(){return Se(arguments.length>0&&arguments[0]!==void 0?arguments[0]:"").media.map(e=>e.direction)}setOffer(e){return this._log.info("setting offer"),this._log.debug(e.sdp),this._peerConnection.setLocalDescription({type:"offer",sdp:n1(e.sdp,this.clientAbility,this._serverAbility)})}setAnswer(e){return this._log.info("setting answer"),this._log.debug(e.sdp),this._room.enableHWEncoder&&e.sdp&&(e.sdp=e.sdp.replaceAll("42e01f","42001f")),this._peerConnection.setRemoteDescription(e)}sendDataChannelMessage(e){var t;(t=this._datachannel)==null||t.send(e)}reset(){var e;(e=this._peerConnection)==null||e.close(),this._waitForPCConnectedPromise=null,this._parsedAnswer=null}close(){this._log.info("close pc"),this.abortMap.forEach(e=>typeof e.abort=="function"&&e.abort("destroy")),this.abortMap.clear(),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED"),this._downlinkMIDMap.clear(),this.stopReconnection(),this.removeAllListeners()}getReceiversByUserId(e){if(!this._peerConnection)return[];let t=this._peerConnection.getReceivers();return(this._downlinkMIDMap.get(e)||[]).map(i=>t[i])}};k([gv("reconnect")],aa.prototype,"startReconnection"),k([fn(e=>e.userId)],aa.prototype,"addDownlink"),k([fn(e=>e)],aa.prototype,"removeDownlink"),k([_n(!0)],aa.prototype,"updateSDP");var o1=class{constructor(e){h(this,"tag"),h(this,"len"),h(this,"data");let t=new DataView(e);this.tag=t.getUint16(),this.len=t.getUint16(2),this.data=new Uint8Array(e).slice(4,4+this.len).buffer}},c1=class{constructor(e){h(this,"tinyId"),h(this,"data");let t=new DataView(e),i=0,r=[];for(;i<t.byteLength;){let n=t.getUint16(i+2),s=new o1(new Uint8Array(e).slice(i,i+2+2+n).buffer);r.push(s),i+=4+n}r.forEach(n=>{n.tag===1?this.tinyId=new TextDecoder().decode(n.data):n.tag===2&&(this.data=n.data)})}},pI=new Set;function In(){let e=Math.floor(4294967296*Math.random());return pI.has(e)?In():(pI.add(e),e)}var l1=Ie(Ve()),mI=class extends l1.default{constructor(e){super(),h(this,"userId"),h(this,"tinyId"),h(this,"_sdpSemantics"),h(this,"_isUplink"),h(this,"_room"),h(this,"_log"),h(this,"_signalChannel"),h(this,"_currentState","DISCONNECTED"),h(this,"_prevTime",-1),h(this,"_enableSEI"),this.userId=e.userId,this.tinyId=e.tinyId,this._room=e.room,this._sdpSemantics=e.room.sdpSemantics,this._isUplink=e.isUplink,this._log=b.createLogger({id:"n",userId:this._room.userId,remoteUserId:this._isUplink?void 0:this.userId,sdkAppId:this._room.sdkAppId,isLocal:this._isUplink}),this._signalChannel=e.signalChannel,this._enableSEI=e.enableSEI}get _peerConnection(){var e;return((e=this.singlePC)==null?void 0:e.getPeerConnection())||null}get singlePC(){return this._room.singlePC}close(e){this._log.info("close connection"),this.emit("closed",e)}emitConnectionStateChangedEvent(e){return e!==this._currentState&&(R.emit(A.PEER_CONNECTION_STATE_CHANGED,{room:this._room,prevState:this._currentState,state:e,remoteUserId:this._isUplink?void 0:this.userId}),this.emit("connection-state-changed",{prevState:this._currentState,state:e}),this._currentState=e,!0)}getPeerConnection(){return this._peerConnection}getRoom(){return this._room}getUserId(){return this.userId}getTinyId(){return this.tinyId}getCurrentState(){return this._currentState}get isH264(){var e,t;return!((t=(e=this._peerConnection)==null?void 0:e.remoteDescription)==null||!t.sdp.includes("H264"))}},Ap=class extends mI{constructor(e){super(J(O({},e),{isUplink:!0})),h(this,"localMainAudioTrack",null),h(this,"localMainVideoTrack",null),h(this,"localAuxAudioTrack",null),h(this,"localAuxVideoTrack",null),h(this,"_isPublishingAux",!1),h(this,"_publishingLocalAudioTrack"),h(this,"_publishingLocalVideoTrack"),h(this,"_mediaSettings",{videoCodec:"",videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioCodec:"opus",audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0,auxVideoWidth:0,auxVideoHeight:0,auxVideoFps:0,auxVideoBps:0}),h(this,"_flag",0),h(this,"_checkPublishStateTimeoutId",-1),this.initialize()}get videoCodec(){var e;return((e=this.singlePC)==null?void 0:e.videoCodec)||"h264"}get ssrc(){if(!this.singlePC)return{audio:0,video:0,videoRtx:0,small:0,smallRtx:0,auxiliary:0,auxiliaryRtx:0};let{audioSsrc:e,bigVideoSsrc:t,bigVideoRtxSsrc:i,smallVideoSsrc:r,smallVideoRtxSsrc:n,auxVideoSsrc:s,auxVideoRtxSsrc:a}=this.singlePC.uplinkSSRC;return{audio:e||0,video:t||0,videoRtx:i||0,small:r||0,smallRtx:n||0,auxiliary:s||0,auxiliaryRtx:a||0}}get flag(){return this._flag}set flag(e){this._flag!==e&&(this._flag=e,this.checkPublishState())}checkPublishState(){let e=arguments.length>0&&arguments[0]!==void 0&&arguments[0];if(!e&&this._checkPublishStateTimeoutId>0)return;let{publishState:t,serverPublishState:i}=this,r=Object.keys(t).find(n=>t[n]!==i[n]);if(r){if(!e)return void(this._checkPublishStateTimeoutId=_e.run(ys,()=>this.checkPublishState(!0),{delay:1e4,count:1}));this._log.warn("publish state not matched, ".concat(r," local:").concat(t[r]," server:").concat(i[r]," ").concat(Sh()," ").concat(mS())),L.addCount({key:521e3})}_e.clearTask(this._checkPublishStateTimeoutId),this._checkPublishStateTimeoutId=-1}get isMainStreamPublished(){return!(!this.localMainAudioTrack&&!this.localMainVideoTrack)}get isAuxStreamPublished(){return!(!this.localAuxVideoTrack&&!this.localAuxAudioTrack)}get publishState(){var e,t,i,r;let n={audio:!1,bigVideo:!1,smallVideo:!1,auxVideo:!1};if(this._peerConnection){let s=this._peerConnection.getSenders();s&&(Si()?(n.audio=!((e=s[0])==null||!e.track),n.bigVideo=!((t=s[1])==null||!t.track),n.smallVideo=!((i=s[2])==null||!i.track),n.auxVideo=!((r=s[3])==null||!r.track)):s.forEach(a=>{a.track&&(a.track.kind===_.AUDIO?n.audio=!0:(n.bigVideo=!0,this._room.videoManager.hasSmall&&(n.smallVideo=!0)))}))}return n}get serverPublishState(){return{audio:!!(this.flag&ms),bigVideo:!!(this.flag&ps),smallVideo:!!(this.flag&Jd),auxVideo:!!(this.flag&Do)}}get muteState(){var e,t,i;return{audio:!((e=this.localMainAudioTrack)==null||!e.muted),bigVideo:!((t=this.localMainVideoTrack)==null||!t.muted),auxVideo:!((i=this.localAuxVideoTrack)==null||!i.muted)}}initialize(){this.installEvents()}reset(){this.uninstallEvents(),this.uninstallTrackMuteEvents(this.localMainAudioTrack,this.localMainVideoTrack,this.localAuxVideoTrack)}close(e){var t;let i=((t=this._peerConnection)==null?void 0:t.getSenders())||[];for(let r of i)r.replaceTrack(null);super.close(e),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED")}installEvents(){var e,t;this.listeners("connection-state-changed").includes(this.handleConnectionStateChange)||this.on("connection-state-changed",this.handleConnectionStateChange,this),(e=this.singlePC)!=null&&e.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||(t=this.singlePC)==null||t.on("spc-reconnected",this.onSinglePCReconnected,this)}uninstallEvents(){var e;this.off("connection-state-changed",this.handleConnectionStateChange,this),(e=this.singlePC)==null||e.off("spc-reconnected",this.onSinglePCReconnected,this)}emitConnectionStateChangedEvent(e,t){var i,r,n;let s=this._currentState,a=super.emitConnectionStateChangedEvent(e);return a&&s!==e&&(t?t.emit("connection-state-changed",{prevState:s,state:e}):((i=this.localMainVideoTrack)==null||i.emit("connection-state-changed",{prevState:s,state:e}),(r=this.localAuxVideoTrack)==null||r.emit("connection-state-changed",{prevState:s,state:e}),(n=this._publishingLocalVideoTrack)==null||n.emit("connection-state-changed",{prevState:s,state:e}))),a}publish(e){return g(this,arguments,function(t){var i=this;let{localAudioTrack:r,localVideoTrack:n,isAuxiliary:s}=t;return function*(){var a,c,o,l,d,u;if(!i.singlePC)return;yield i.singlePC.waitForPeerConnectionConnected();let p,{publishState:m,muteState:f}=i;if(r&&(i._publishingLocalAudioTrack=r,m.audio=!0,f.audio=r.muted),n){if(!i.singlePC.isH264EncodeSupported&&!i.singlePC.isVP8EncodeSupported)throw new N({code:C.NOT_SUPPORTED_H264,message:j({key:B.NOT_SUPPORTED_H264ENCODE})});Ue&&Ns()===115&&n.profile.width*n.profile.height<=230400&&(i._log.warn("fallback video to 480p"),n.setProfile(vt["480p_2"]),yield n.applyProfile()),i._publishingLocalVideoTrack=n,s?(m.auxVideo=!0,f.auxVideo=n.muted):(m.bigVideo=!0,f.bigVideo=n.muted)}if(i._isPublishingAux=s,n&&!s&&n.small&&(p=i._room.videoManager.smallTrack,m.smallVideo=!0),yield i._signalChannel.sendWaitForResponseWithRetry({command:LU,responseCommand:K.SPC_PUBLISH_RESULT,data:J(O({},i.singlePC.uplinkSSRC),{state:m,muteState:f}),retries:3}),yield i.publishByTransceiver({localAudioTrack:r,localVideoTrack:n,smallTrack:p,isAuxiliary:s}),i._publishingLocalAudioTrack=null,i._publishingLocalVideoTrack=null,i._isPublishingAux=!1,s)n&&(i.localAuxVideoTrack=n),r&&(i.localAuxAudioTrack=r);else{if(n){i.localMainVideoTrack=n;let{scaleResolutionDownBy:T}=n;T>1&&(i._log.warn("setScaleResolutionDownBy main ".concat(T)),yield i.singlePC.setScaleResolutionDownBy(i._peerConnection.getSenders()[1],T))}r&&(i.localMainAudioTrack=r)}yield i.singlePC.setBandwidth({audio:((a=i.localMainAudioTrack)==null?void 0:a.profile.bitrate)||((c=i.localAuxAudioTrack)==null?void 0:c.profile.bitrate),bigVideo:(o=i.localMainVideoTrack)==null?void 0:o.profile.bitrate,smallVideo:(d=(l=i.localMainVideoTrack)==null?void 0:l.small)==null?void 0:d.bitrate,auxVideo:(u=i.localAuxVideoTrack)==null?void 0:u.profile.bitrate}),i.sendMediaSettings(),i.installTrackMuteEvents(r,n)}()})}publishByTransceiver(e){let{localAudioTrack:t,localVideoTrack:i,smallTrack:r,isAuxiliary:n}=e;if(!Wt())return;this._log.info("publish by transceiver");let s=i==null?void 0:i.outMediaTrack,a=t==null?void 0:t.outMediaTrack,c=this._peerConnection.getTransceivers(),o=[],l=[],d=(p,m,f)=>{var T;let S=c[m].sender.replaceTrack(f);l.push(m),(T=this.singlePC)!=null&&T.enableInsertableStreams&&S.then(()=>this.createEncodedStreams(c[m].sender,p)),o.push(S)};a&&d(t.mediaType,0,a),s&&d(i.mediaType,n?3:1,s),r&&d(8,2,r);let u=this.setTransceiverDirection(Y.SENDONLY,l);return o.push(u),Promise.all(o)}getTrackByMeidaType(e){switch(e){case 1:return this.localMainAudioTrack||this._publishingLocalAudioTrack;case 4:case 8:return this.localMainVideoTrack||this._publishingLocalVideoTrack;case 2:return this.localAuxVideoTrack||this._publishingLocalVideoTrack;default:throw new Error("mediaType error")}}createEncodedStreams(e,t){var i,r;if(this.singlePC.abortMap.has(e))return;let n=e.createEncodedStreams(),s=new AbortController;(i=this.singlePC)==null||i.addAbortController(e,s),((r=this.getTrackByMeidaType(t))!=null&&r.enableEncodeFrame?n.readable.pipeThrough(new TransformStream({transform:(a,c)=>{var o;return c.enqueue((o=this.singlePC)!=null&&o.isUsingH264?this.getTrackByMeidaType(t).encodeFrame(a,t===8):a)}}),s):n.readable).pipeTo(n.writable,s).catch(a=>{this._log.debug("encoded stream error",a),a!=="destory"&&this._log.warn(a)})}enableSmall(e){return g(this,null,function*(){if(!this.singlePC)return;let t=this._peerConnection.getTransceivers();e?this._room.videoManager.smallTrack&&(yield t[2].sender.replaceTrack(this._room.videoManager.smallTrack),yield this.setTransceiverDirection(Y.SENDONLY,[2])):(yield t[2].sender.replaceTrack(null),yield this.setTransceiverDirection(Y.INACTIVE,[2])),this.updateMediaSettings(),yield this.doPublishChange()})}installTrackMuteEvents(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];t.forEach(r=>{r&&(r==null||r.on("mute",this.sendMutedFlag,this),r==null||r.on("unmute",this.sendMutedFlag,this))})}uninstallTrackMuteEvents(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];t.forEach(r=>{r&&(r==null||r.off("mute",this.sendMutedFlag,this),r==null||r.off("unmute",this.sendMutedFlag,this))})}unpublish(e){return g(this,arguments,function(t){var i=this;let{localAudioTrack:r,localVideoTrack:n}=t;return function*(){let s=n&&n===i.localAuxVideoTrack,a=n==null?void 0:n.outMediaTrack,c=i._peerConnection.getSenders(),o=[];r&&(yield c[0].replaceTrack(null),o.push(0),s?i.localAuxAudioTrack=null:i.localMainAudioTrack=null),a&&(s?(yield c[3].replaceTrack(null),i.localAuxVideoTrack=null,i._mediaSettings=J(O({},i._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),o.push(3)):(yield c[1].replaceTrack(null),yield c[2].replaceTrack(null),i.localMainVideoTrack=null,i._mediaSettings=J(O({},i._mediaSettings),{videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0}),o.push(1,2))),i.isMainStreamPublished||i.isAuxStreamPublished?(yield i.setTransceiverDirection(Y.INACTIVE,o),yield i.doPublishChange(!1)):yield i.doUnpublish(),i.uninstallTrackMuteEvents(r,n),n==null||n.emit("connection-state-changed",{prevState:i._currentState,state:"DISCONNECTED"})}()})}doPublishChange(){let e=!(arguments.length>0&&arguments[0]!==void 0)||arguments[0];return g(this,null,function*(){let t={state:this.publishState,constraintConfig:this._mediaSettings},i=yield this._signalChannel.sendWaitForResponseWithRetry({command:Yv,data:t,responseCommand:K.PUBLISH_STATE_CHANGE_RESULT,enableLog:e,retries:3});this.checkPublishResultCode(i.data.code,i.data.message)})}doUnpublish(){let e=arguments.length>0&&arguments[0]!==void 0&&arguments[0];return this._signalChannel.sendWaitForResponse({command:_p,commandDesc:"unpublish",responseCommand:K.UNPUBLISH_RESULT,enableLog:e}).catch(t=>{if(t.getCode()===C.API_CALL_TIMEOUT)return Promise.resolve();throw t})}updateMediaSettings(){let{detail:{isH264EncodeSupported:e,isVp8EncodeSupported:t}}=this._room.checkSystemResult;e?this._mediaSettings.videoCodec="H264":t&&(this._mediaSettings.videoCodec="VP8");let i=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:r,localAuxVideoTrack:n}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?n=this._publishingLocalVideoTrack:r=this._publishingLocalVideoTrack),un){if(i&&i.outMediaTrack){let s=i.outMediaTrack.getSettings();this._mediaSettings.audioChannel=s.channelCount||1,this._mediaSettings.audioBps=1e3*i.profile.bitrate,this._mediaSettings.audioFs=s.sampleRate||0}if(r&&r.outMediaTrack){let s=r.outMediaTrack.getSettings();this._mediaSettings.videoWidth=s.width||0,this._mediaSettings.videoHeight=s.height||0,this._mediaSettings.videoFps=s.frameRate||0,this._mediaSettings.videoBps=1e3*r.profile.bitrate,r.small&&(this._mediaSettings.smallVideoWidth=r.small.width,this._mediaSettings.smallVideoHeight=r.small.height,this._mediaSettings.smallVideoFps=r.small.frameRate,this._mediaSettings.smallVideoBps=1e3*r.small.bitrate)}if(n&&n.outMediaTrack){let s=n.outMediaTrack.getSettings();this._mediaSettings.auxVideoWidth=s.width||0,this._mediaSettings.auxVideoHeight=s.height||0,this._mediaSettings.auxVideoFps=s.frameRate||0,this._mediaSettings.auxVideoBps=1e3*n.profile.bitrate}}else i&&i.outMediaTrack&&(this._mediaSettings.audioChannel=i.profile.channelCount,this._mediaSettings.audioBps=1e3*i.profile.bitrate,this._mediaSettings.audioFs=i.profile.sampleRate),r&&r.outMediaTrack&&(this._mediaSettings.videoWidth=r.profile.width,this._mediaSettings.videoHeight=r.profile.height,this._mediaSettings.videoFps=r.profile.frameRate,this._mediaSettings.videoBps=1e3*r.profile.bitrate);this._log.info("updateMediaSettings: ".concat(JSON.stringify(this._mediaSettings)))}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:$v,data:this._mediaSettings,responseCommand:K.UPDATE_CONSTRAINT_CONFIG_RES}).then(e=>{e.data.code!==0&&this._log.warn(e.data.message)}).catch(()=>{})}addTrack(e){return g(this,null,function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info("is adding ".concat(e.kind," track to current published local ").concat(t?_.AUXILIARY:_.MAIN," stream")),Si()&&(yield this.addTrackByTransceiver(e,t))})}addTrackByTransceiver(e,t){return g(this,null,function*(){var i;if(!e.mediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===_.AUDIO)yield r[0].sender.replaceTrack(e.outMediaTrack);else{let n=t?3:1;yield r[n].sender.replaceTrack(e.outMediaTrack),n===1&&((i=this.localMainVideoTrack)!=null&&i.small)&&(yield r[2].sender.replaceTrack(this._room.videoManager.smallTrack)),r[n].direction===Y.INACTIVE&&(yield this.setTransceiverDirection(Y.SENDONLY,[n]))}this.updateMediaSettings(),yield this.doPublishChange()})}removeTrack(e){return g(this,null,function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info("is removing ".concat(e.kind," track from current published local ").concat(t?_.AUXILIARY:_.MAIN," stream")),Si()&&(yield this.removeTrackByTransceiver(e,t))})}removeTrackByTransceiver(e,t){return g(this,null,function*(){if(!e.mediaTrack)return;let i=this._peerConnection.getTransceivers();if(e.kind===_.AUDIO)yield i[0].sender.replaceTrack(null);else{let r=t?3:1;yield i[r].sender.replaceTrack(null),r===1&&this._room.videoManager.hasSmall&&(yield i[2].sender.replaceTrack(null)),yield this.setTransceiverDirection(Y.INACTIVE,[r])}this.updateMediaSettings(),yield this.doPublishChange()})}setTransceiverDirection(e,t){return g(this,null,function*(){if(!ue)return;let i=!1,r=!1;this._log.info("setting transceiver ".concat(t.join(",")," direction to ").concat(e));let n=this._peerConnection.getTransceivers();if(t.forEach(c=>{n[c].direction!==e&&(n[c].direction=e,i=!0)}),i){this._log.info("updating offer");let c=yield this._peerConnection.createOffer();yield this._peerConnection.setLocalDescription(c)}let s=-1,a=this._peerConnection.remoteDescription.sdp.split(`\r
130
+ `).map(c=>{if(c.match(new RegExp("a=(".concat(Y.INACTIVE,"|").concat(Y.RECVONLY,"|").concat(Y.SENDONLY,")")))&&s++,t.includes(s)){if(e===Y.INACTIVE&&c.includes("a=".concat(Y.RECVONLY)))return r=!0,"a=".concat(e);if(e===Y.SENDONLY&&c.includes("a=".concat(Y.INACTIVE)))return r=!0,"a=".concat(Y.RECVONLY)}return c}).join(`\r
131
+ `);r&&(this._log.info("updating answer"),yield this._peerConnection.setRemoteDescription({type:"answer",sdp:a}))})}replaceTrack(e){return g(this,null,function*(){var t;let i=(t=this._peerConnection)==null?void 0:t.getSenders(),r=e.outMediaTrack||e.mediaTrack;if(!i||i.length===0||!r||i.find(s=>s.track===r))return!1;let n=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;return this._log.info("is replacing ".concat(r.kind," track ").concat(r.id," on ").concat(n?_.AUXILIARY:_.MAIN," stream")),r.kind===_.AUDIO&&i[0]&&(yield i[0].replaceTrack(r)),r.kind===_.VIDEO&&(!n&&i[1]&&(yield i[1].replaceTrack(r)),n&&i[3]&&(yield i[3].replaceTrack(r))),!0})}setBandwidth(e){return g(this,arguments,function(t){var i=this;let{bandwidth:r,type:n,videoType:s}=t;return function*(){if(i.singlePC){let a={};n===_.AUDIO?a.audio=r:s==="big"?a.bigVideo=r:s==="small"?a.smallVideo=r:a.auxVideo=r,yield i.singlePC.setBandwidth(a)}}()})}sendMutedFlag(e){e===this.localAuxAudioTrack||e===this.localAuxVideoTrack||(this._log.info("send muted state: ".concat(JSON.stringify(this.muteState))),this._signalChannel.sendWaitForResponseWithRetry({command:qv,responseCommand:K.MUTE_RESULT,data:this.muteState,retries:3}).catch(()=>{}))}handleConnectionStateChange(e){e.state==="CONNECTED"&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&R.emit(A.SEND_FIRST_VIDEO_FRAME,{room:this._room})}getVideoTrackId(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:_.VIDEO;if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===_.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(e===_.VIDEO&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===_.VIDEO){let t=this.localMainVideoTrack.mediaTrack;if(t)return t.id}if(this.localAuxVideoTrack&&e===_.AUXILIARY){let t=this.localAuxVideoTrack.mediaTrack;if(t)return t.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,t){if(e!==0)throw e===Po?(this._log.error(ut.NOT_SUPPORTED_H264ENCODE),new N({code:C.NOT_SUPPORTED_H264,message:j({key:B.NOT_SUPPORTED_H264ENCODE})})):new N({code:C.UNKNOWN,message:j({key:B.SIGNAL_RESPONSE_FAILED,data:{signalResponse:K.PUBLISH_RESULT,code:e,message:t}})})}onSinglePCReconnected(){return g(this,null,function*(){this.isMainStreamPublished&&(this._log.warn("republish main stream"),yield this.publish({localAudioTrack:this.localMainAudioTrack,localVideoTrack:this.localMainVideoTrack,isAuxiliary:!1})),this.isAuxStreamPublished&&(this._log.warn("republish aux stream"),yield this.publish({localAudioTrack:this.localAuxAudioTrack,localVideoTrack:this.localAuxVideoTrack,isAuxiliary:!0}))})}};function _I(e){return Object.keys(e).filter(t=>e[t])}var bc=class extends mI{constructor(e){super(J(O({},e),{isUplink:!1})),h(this,"_flag",0),h(this,"role","anchor"),h(this,"remoteAudioTrack"),h(this,"remoteVideoTrack"),h(this,"remoteAuxiliaryTrack"),h(this,"ssrc",{audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0}),this.flag=e.flag,this.remoteAudioTrack=new ap(this._room,this),this.remoteVideoTrack=new Ys(this._room,this),this.remoteAuxiliaryTrack=new kv(this._room,this),this.initialize()}get videoCodec(){var e;return((e=this.singlePC)==null?void 0:e.downlinkVideoCodec)||"h264"}get subscribeState(){return{audio:this.remoteAudioTrack.isSubscribed||this.remoteAudioTrack.isSubscribing,video:this.remoteVideoTrack.isBig&&(this.remoteVideoTrack.isSubscribed||this.remoteVideoTrack.isSubscribing),smallVideo:this.remoteVideoTrack.isSmall&&(this.remoteVideoTrack.isSubscribed||this.remoteVideoTrack.isSubscribing),auxiliary:this.remoteAuxiliaryTrack.isSubscribed||this.remoteAuxiliaryTrack.isSubscribing}}get muteState(){return Ms(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var t,i,r;e!==this._flag&&(this._flag=e,(t=this.remoteAudioTrack)==null||t.onFlagChanged(),(i=this.remoteVideoTrack)==null||i.onFlagChanged(),(r=this.remoteAuxiliaryTrack)==null||r.onFlagChanged())}get hasMainStream(){return this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall}get hasAuxStream(){return this.muteState.hasAuxiliary}get isMainStreamSubscribed(){return(this.subscribeState.audio||this.subscribeState.video||this.subscribeState.smallVideo)&&(this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall)}get isAuxStreamSubscribed(){return this.subscribeState.auxiliary&&this.muteState.hasAuxiliary}get isSmallStreamSubscribed(){return this.subscribeState.smallVideo&&this.muteState.hasSmall}get isBigStreamSubscribed(){return this.subscribeState.video&&this.muteState.hasVideo}isStreamUnpublished(e){return e===_.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){this.installEvents()}close(e){super.close(e),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.uninstallEvents(),this.removeDownlink()}installEvents(){!this.singlePC||(this.listeners("track").includes(this.onTrack)||this.singlePC.on("track",this.onTrack,this),this.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||this.singlePC.on("spc-reconnected",this.onSinglePCReconnected,this))}uninstallEvents(){!this.singlePC||(this.singlePC.off("track",this.onTrack,this),this.singlePC.off("spc-reconnected",this.onSinglePCReconnected,this))}emitConnectionStateChangedEvent(e){var t,i;let r=this._currentState,n=super.emitConnectionStateChangedEvent(e);return n&&r!==e&&((t=this.remoteVideoTrack)==null||t.emit("connection-state-changed",{prevState:r,state:e}),(i=this.remoteAuxiliaryTrack)==null||i.emit("connection-state-changed",{prevState:r,state:e})),n}onTrack(e){let t=e.streams[0],{track:i,receiver:r}=e;if(!t.id.includes(this.tinyId))return;let n=t.id.includes("aux")?"auxiliary":"main";this._log.debug("ontrack ".concat(n," ").concat(i.kind));let s=_.AUDIO;i.kind===_.VIDEO&&(s=n===_.MAIN?_.VIDEO:_.AUXILIARY);let a=this.remoteAudioTrack;s===_.VIDEO?a=this.remoteVideoTrack:s===_.AUXILIARY&&(a=this.remoteAuxiliaryTrack),this.singlePC.enableInsertableStreams&&this.createEncodedStreams(a,r),a.setInputMediaStreamTrack(i)}createEncodedStreams(e,t){if(!this.singlePC.abortMap.has(t)){let i=t.createEncodedStreams(),r=new AbortController,n={abortController:r,enqueue:s=>{var a;return(a=this.singlePC)!=null&&a.isUsingH264?e.decodeFrame(s):s}};(e.enableDecodeFrame?i.readable.pipeThrough(new TransformStream({transform:(s,a)=>a.enqueue(n.enqueue(s))})):i.readable).pipeTo(i.writable,r).catch(s=>{s!=="destory"&&this._log.warn(s)}),this.singlePC.addAbortController(t,r)}}subscribe(e,t){return g(this,null,function*(){try{if(this._log.info("subscribe ".concat(t," ").concat(_I(e))),this.hasSSRC){let i="subscribe_change";Object.values(e).find(r=>r===!0)||(i="unsubscribe"),yield this.sendSubscription(i,e)}else yield this.doSubscribe(e),this.checkTrackEnded(e)}catch(i){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn("".concat(i.message," ").concat(JSON.stringify(this.muteState))),new N({code:C.REMOTE_STREAM_NOT_EXIST,message:"remote user ".concat(this.userId," unpublished stream")})):i}})}checkTrackEnded(e){var t,i,r;if((e.audio&&((t=this.remoteAudioTrack.mediaTrack)==null?void 0:t.readyState)==="ended"||e.video&&((i=this.remoteVideoTrack.mediaTrack)==null?void 0:i.readyState)==="ended"||e.auxiliary&&((r=this.remoteAuxiliaryTrack.mediaTrack)==null?void 0:r.readState)==="ended")&&this.singlePC&&!this.singlePC.isReconnecting){if(this._log.warn("remote track ended start spc reconnect"),Zi&&er<92)return;this.singlePC.startReconnection()}}unsubscribe(e){return g(this,arguments,function(t){var i=this;let{remoteTracks:r,streamType:n}=t;return function*(){var s;if(n==="main"&&!i.isMainStreamSubscribed||n==="auxiliary"&&!i.isAuxStreamSubscribed)return void i._log.info("".concat(n," stream already unsubscribed"));let a=O({},i.subscribeState);r.forEach(o=>{switch(o.mediaType){case 1:a.audio=!1;break;case 4:a.video=!1;break;case 8:a.smallVideo=!1;break;case 2:a.auxiliary=!1}});let c="subscribe_change";Object.values(a).find(o=>o===!0)||(c="unsubscribe"),i._log.info("".concat(c==="unsubscribe"?c:"subscribe"," ").concat(n," [").concat(_I(a),"]")),c==="unsubscribe"&&((s=i.singlePC)==null||s.removeDownlinkQueue.add(i.tinyId)),yield i.sendSubscription(c,a),c==="unsubscribe"&&(yield i.removeDownlink())}()})}sendSubscription(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.subscribeState,i={srcTinyId:this.tinyId,srcUserId:this.userId},r=Qv,n=K.UNSUBSCRIBE_RESULT;return e==="subscribe_change"&&(i={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},r=Xv,n=K.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponseWithRetry({command:r,data:i,responseCommand:n,timeout:1e4,retries:3}).then(s=>{let{data:a}=s;if(a.code!==0){let c=new N({code:a.code,message:j({key:B.ERROR_MESSAGE,data:{type:e,message:a.message}})});throw this._log.error(c),c}})}getMainStreamVideoTrackId(){return this.remoteVideoTrack&&this.remoteVideoTrack.mediaTrack?this.remoteVideoTrack.mediaTrack.id:""}getAuxStreamVideoTrackId(){return this.remoteAuxiliaryTrack&&this.remoteAuxiliaryTrack.mediaTrack?this.remoteAuxiliaryTrack.mediaTrack.id:""}setDelay(e){let{audioDelay:t,videoDelay:i}=e;this.remoteAudioTrack.stat.end2EndDelay=t,this.remoteVideoTrack.stat.end2EndDelay=i}onSinglePCReconnected(){(this.ssrc.audio||this.ssrc.video||this.ssrc.auxiliary)&&(this._log.warn("resubscribe ".concat(JSON.stringify(this.subscribeState))),this.doSubscribe(this.subscribeState))}get hasSSRC(){return this.ssrc.audio&&this.ssrc.video&&this.ssrc.auxiliary}doSubscribe(){return g(this,arguments,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.subscribeState,i=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];return function*(){if(e.singlePC){e.singlePC.addDownlinkQueue.add(e.tinyId),yield e.singlePC.waitForPeerConnectionConnected();try{if(i||!e.hasSSRC){let r={audioSsrc:In(),bigVideoSsrc:In(),bigVideoRtxSsrc:In(),auxVideoSsrc:In(),auxVideoRtxSsrc:In()},{audioSsrc:n,bigVideoSsrc:s,bigVideoRtxSsrc:a,auxVideoSsrc:c,auxVideoRtxSsrc:o}=r;e.ssrc={audio:n,video:s,videoRtx:a,auxiliary:c,auxiliaryRtx:o},e.singlePC.addDownlinkQueue.delete(e.tinyId),yield e.singlePC.addDownlink({userId:e.userId,tinyId:e.tinyId,ssrc:e.ssrc});try{let l=yield e._signalChannel.sendWaitForResponseWithRetry({command:MU,responseCommand:K.SPC_SUBSCRIBE_RESULT,data:{srcUserId:e.userId,srcTinyId:e.tinyId,audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,customData:!1,ssrc:r},retries:3,retryTimeout:0});if(l.data.code!==0)throw new N({code:l.data.code,message:l.data.message})}catch(l){throw yield e.removeDownlink(),l}return}e.singlePC.addDownlinkQueue.delete(e.tinyId),yield e.singlePC.addDownlink({userId:e.userId,tinyId:e.tinyId,ssrc:e.ssrc})}finally{let r=e._room.scheduleResult.config;(r!=null&&r.jitterDelay||r!=null&&r.jitterDelayAux)&&e.setJitterBufferDelay({mainDelay:r.jitterDelay,auxDelay:r.jitterDelayAux})}}}()})}removeDownlink(){return g(this,null,function*(){if(!this.singlePC)return;this.ssrc={audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0},this.singlePC.removeDownlinkQueue.delete(this.tinyId);let e=this._room.scheduleResult.config;(e!=null&&e.jitterDelay||e!=null&&e.jitterDelayAux)&&this.setJitterBufferDelay({mainDelay:0,auxDelay:0}),yield this.singlePC.removeDownlink(this.userId)})}setJitterBufferDelay(e){let{mainDelay:t,auxDelay:i}=e;if(!this.singlePC||!this._peerConnection||sr(t)&&sr(i))return Promise.resolve();this._log.info("set jitterBuffer main: ".concat(t," aux: ").concat(i));let r=this.singlePC.getReceiversByUserId(this.userId);return ge(t)&&(this.remoteAudioTrack.jitterBufferDelay=t,this.remoteVideoTrack.jitterBufferDelay=t),ge(i)&&(this.remoteAuxiliaryTrack.jitterBufferDelay=i,sr(t)&&(this.remoteAudioTrack.jitterBufferDelay=i)),new Promise(n=>{this.doSetJitterBufferDelay({mainDelay:t,auxDelay:i,receivers:r,resolve:n})})}doSetJitterBufferDelay(e){let{mainDelay:t,auxDelay:i,receivers:r,resolve:n}=e,s=-1;try{if(t===0&&i===0)return r.forEach(a=>a.jitterBufferTarget=0),n();if(r.forEach(a=>{var c;let o=a.track===this.remoteAuxiliaryTrack.outMediaTrack||sr(t)&&a.track===this.remoteAudioTrack.outMediaTrack;if(o&&sr(i)||!o&&sr(t))return;let l=o?i||0:t,d=(a.jitterBufferTarget||0)+100;d>l||(a.jitterBufferTarget=d,this._log.debug("set ".concat(o?"aux ":"").concat((c=a==null?void 0:a.track)==null?void 0:c.kind," jitterBuffer delay ").concat(d," -> ").concat(l)))}),!r.find(a=>{let c=a.track===this.remoteAuxiliaryTrack.outMediaTrack?i||0:t;return a.jitterBufferTarget<c}))return this._log.info("set jitterBuffer main: ".concat(t," aux: ").concat(i," done")),n();s=setTimeout(()=>{this.doSetJitterBufferDelay({mainDelay:t,auxDelay:i,receivers:r,resolve:n})},1e3)}catch(a){this._log.warn("set jitterBuffer delay error: ".concat(a)),clearTimeout(s),n()}}};k([_n(),ae(e=>function(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];return new Promise((n,s)=>{let a=c=>{this.off("closed",a),s(new N({code:C.API_CALL_ABORTED,message:j({key:B.CONNECTION_ABORTED,data:c})}))};this.on("closed",a),e.apply(this,i).then(n,s).finally(()=>{this.off("closed",a)})})})],bc.prototype,"subscribe"),k([_n()],bc.prototype,"unsubscribe"),k([fn(()=>"jitter")],bc.prototype,"setJitterBufferDelay");var u1=bc,d1=Ie(Ve()),fI=class extends d1.EventEmitter{constructor(e,t){super(),this.room=e,this.signalChannel=t,h(this,"log"),h(this,"cmdIdSeqMap",new Map),h(this,"messageMap",new Map),this.log=b.createLogger({id:"cmm",userId:e.userId}),this.onReceiveMsg=this.onReceiveMsg.bind(this),t.on(K.RECEIVE_CUSTOM_MSG,this.onReceiveMsg)}send(e){let{cmdId:t,data:i}=e,r=this.cmdIdSeqMap.get(t)||Math.floor(16383*Math.random()),n={cmdId:t,msg:btoa(String.fromCharCode(...new Uint8Array(i))),ordered:!0,reliable:!0,streamSeq:r};this.cmdIdSeqMap.set(t,r+1),this.signalChannel.send(UU,n)}onReceiveMsg(e){let{data:t}=e.data,i=this.room.tinyIdToUserIdMap.get(t.srcTinyId);if(i){let r={userId:i,cmdId:t.cmdId,seq:t.streamSeq,data:Uint8Array.from(atob(t.msg),n=>n.charCodeAt(0)).buffer};if(t.ordered){let n="".concat(i,"_").concat(r.cmdId),s=this.messageMap.get(n);if(!s||Math.abs(s.lastSeq-r.seq)>fI.SEQ_INTERVAL)this.messageMap.set(n,{lastSeq:r.seq,cachedMessageMap:new Map}),this.emitMessage(r);else if(r.seq>s.lastSeq){if(r.seq===s.lastSeq+1)this.emitMessage(r);else if(!s.cachedMessageMap.has(r.seq)){let a=setTimeout(()=>this.emitMessage(r,!0),5e3);s.cachedMessageMap.set(r.seq,{message:r,timeoutId:a})}}else this.log.debug("drop message ".concat(r.userId,"-").concat(r.cmdId,"-").concat(r.seq))}else this.emit("message",r)}}emitMessage(e){let t=arguments.length>1&&arguments[1]!==void 0&&arguments[1];var i;let r=this.messageMap.get("".concat(e.userId,"_").concat(e.cmdId)),n=e;if(r){if(t){let a=[...r.cachedMessageMap.values()].sort((c,o)=>c.message.seq-o.message.seq);a[0]&&(n=a[0].message)}n.seq-r.lastSeq>1&&this.log.debug("msg lost userId: ".concat(n.userId," seq: ").concat(r.lastSeq," -> ").concat(n.seq)),r.lastSeq=n.seq,clearTimeout((i=r.cachedMessageMap.get(n.seq))==null?void 0:i.timeoutId),r.cachedMessageMap.delete(n.seq)}this.emit("message",n);let s=r==null?void 0:r.cachedMessageMap.get(n.seq+1);s&&this.emitMessage(s.message)}},gI=fI;h(gI,"SEQ_INTERVAL",300);var TI,{isString:EI,isUndefined:An,getNetworkType:h1,isEmpty:oa}=yt,wi=class extends e1{constructor(e){super(e),this._heartbeat=-1,this._lastHeartBeatTime=-1,this._joinTimeout=-1,this._firstPublishedList=null,this._joinReject=null,this._isRelayChanged=!1,this._signalChannel=null,this.uplinkConnection=null,this.singlePC=null,this.enableSPC=Bs,this._changeBigSmallRecords=new Map,this._networkQuality=null,this._turnServers=[],this._syncUserListInterval=-1,this._smallStreamConfig={bitrate:100,frameRate:15,height:120,width:160},this.enableSEI=!1,this._enableAudioVolumeEvaluation=!1,this._audioVolumeIntervalId=0,this._enableMultiAuxStream=!1,this._pureAudioPushMode=!1,this.enableHWEncoder=!1,this._stats=new BU(this,this._log),this.userManager=new ZV(this.userId,this._log),this._version=St,this.sdpSemantics=Oo,An(e.sdpSemantics)?Vs.isUnifiedPlanDefault()&&(this.sdpSemantics=_s):this.sdpSemantics=e.sdpSemantics,this._log.info("sdpSemantics: ".concat(this.sdpSemantics,", netType: ").concat(h1())),e.iceTransportPolicy&&(this._iceTransportPolicy=e.iceTransportPolicy),this._enableMultiAuxStream=!An(e.enableMultiAuxStream)&&e.enableMultiAuxStream,this.enableSEI=e.enableSEI&&Bs,!An(e.enableSPC)&&Bs&&(this.enableSPC=e.enableSPC),this.enableHWEncoder=e.enableHWEncoder||!1,this._initBusinessInfo(e)}get isMainStreamPublished(){var e;return!((e=this.uplinkConnection)==null||!e.isMainStreamPublished)}get isMainAudioPublished(){var e;return!((e=this.uplinkConnection)==null||!e.localMainAudioTrack)}get isAuxStreamPublished(){var e;return!((e=this.uplinkConnection)==null||!e.isAuxStreamPublished)}get hasAuxStream(){return[...this.remotePublishedUserMap.values()].findIndex(e=>e.muteState.hasAuxiliary)>=0}get userMap(){return this.userManager.userMap}get remotePublishedUserMap(){return this.userManager.remotePublishedUserMap}get tinyIdToUserIdMap(){return new Map([...this.userMap.values()].map(e=>[e.tinyId,e.userId]))}join(e,t,i){return g(this,null,function*(){return this.userManager.mySelfId=this.userId,this.userManager.on("1",r=>{this.emit("peer-join",r)}),this.userManager.on("2",r=>{this.closeDownLinkConnection(r,"remote user exitRoom"),this.emit("peer-leave",r)}),this.userManager.on("3",this.createDownlinkConnection,this),this.userManager.on("5",this.closeDownLinkConnection,this),this.userManager.on("6",r=>{var n=((s,a)=>{var c={};for(var o in s)Od.call(s,o)&&a.indexOf(o)<0&&(c[o]=s[o]);if(s!=null&&ko)for(var o of ko(s))a.indexOf(o)<0&&Dy.call(s,o)&&(c[o]=s[o]);return c})(r,[]);R.emit(A.REMOTE_PUBLISH_STATE_CHANGED,O({room:this},n)),this.emit("remote-publish-state-changed",O({},n))}),this.joinParams=e,new Promise((r,n)=>g(this,null,function*(){var s,a;this._joinReject=n;try{this.checkDestroy();try{yield Promise.all([this.initialize(),this.initSinglePC()])}catch(c){if(!(c instanceof N&&c.code===C.SPC_INITIALIZED_FAILED))return n(c);(s=this._signalChannel)==null||s.destroy(),yield this.initialize()}yield this.doJoin(e,(a=this.singlePC)==null?void 0:a.clientAbility),r(),this._firstPublishedList&&this.onPublishedUserList({data:{userList:this._firstPublishedList}})}catch(c){n(c)}this._joinReject=null}))})}initSinglePC(){return g(this,null,function*(){if(this.enableSPC&&!this.singlePC){this.singlePC=new aa({signalChannel:this._signalChannel,room:this,enableCustomMessage:!1}),this.singlePC.on("sei-message",e=>this.emit("sei-message",e)),this.singlePC.once("error",()=>this.fallbackToMPC());try{return yield this.singlePC.initialize()}catch(e){throw this.fallbackToMPC(),new N({code:C.SPC_INITIALIZED_FAILED,message:e==null?void 0:e.message})}}})}doJoin(e,t){return new Promise((i,r)=>g(this,null,function*(){var n,s,a;e.privateMapKey&&(this.privateMapKey=e.privateMapKey),e.latencyLevel&&(this.latencyLevel=e.latencyLevel),this._signalChannel.once(Kv,l=>{this.clearJoinTimeout(),R.emit(A.JOIN_SIGNAL_CONNECTION_END,{room:this,error:l}),r(l)}),We((s=(n=this.scheduleResult)==null?void 0:n.config)==null?void 0:s.singlePC)&&Bs&&(this.enableSPC=this.scheduleResult.config.singlePC),this.keyPointManager.setConnectionType(this.singlePC?1:2);let c={roomId:String(e.roomId||e.strRoomId),useStringRoomId:this.useStringRoomId,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel,trtcRole:e.role,trtcScene:this.scene==="live"?2:1,sdpSemantics:this.sdpSemantics,version:this._version,ua:navigator&&navigator.userAgent||"",terminalType:fS(),netType:Qo(),bussinessInfo:this._businessInfo,ability:t,sdkType:this._sdkType,userSig:this.userSig};this._log.debug("join room signal data: ".concat(JSON.stringify(c)));let o=5e3;(a=this.scheduleResult.config)!=null&&a.enterRoomTimeout&&this.scheduleResult.config.enterRoomTimeout>=1&&(o=1e3*this.scheduleResult.config.enterRoomTimeout),this._joinTimeout=window.setTimeout(()=>{r(new N({code:C.JOIN_ROOM_FAILED,message:j({key:B.JOIN_ROOM_TIMEOUT})}))},o),R.emit(A.JOIN_SEND_CMD,{room:this}),this._signalChannel.send(this.singlePC?PU:EU,c),this._signalChannel.once(K.JOIN_ROOM_RESULT,l=>{this.clearJoinTimeout();let{code:d,message:u,data:p,tinyId:m}=l.data;R.emit(A.JOIN_RECEIVED_CMD_RES,{room:this,code:d}),d===0?(this._log.info("Join room success, start heartbeat"),m&&(this.tinyId=m),this.startHeartbeat(),this.syncUserList(),this.startSyncUserListInterval(),this._firstPublishedList=p.publishers,this.singlePC&&this.singlePC.connect(p.ability).catch(()=>{}),i()):(this._log.error("Join room failed result: ".concat(d," error: ").concat(u)),r(new N({code:C.JOIN_ROOM_FAILED,extraCode:d,message:j({key:B.JOIN_ROOM_FAILED,data:{error:u,code:d}})})))})}))}reJoin(){let e=!(arguments.length>0&&arguments[0]!==void 0)||arguments[0];return g(this,null,function*(){if(this.isJoined)try{this._log.warn("reJoin pending: ".concat(this.joinParams.roomId));let t,i=[];if(this.singlePC&&(this.singlePC.close(),this.singlePC=null,i.push(this.initSinglePC().then(r=>(t=r,r)))),this._signalChannel&&(this._signalChannel.race=e,this._signalChannel.close(),i.push(this._signalChannel.connect())),yield Promise.all(i),yield this.doJoin(J(O({},this.joinParams),{role:this.role==="anchor"?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel}),t),this._log.warn("reJoin success"),de.logSuccessEvent({userId:this.userId,eventType:Ft.REJOIN}),this.singlePC){let r=n=>{var s;n.state==="CONNECTED"&&((s=this.singlePC)==null||s.off(Tr.CONNECTION_STATE_CHANGED,r),this.uplinkConnection instanceof Ap&&(this.uplinkConnection.installEvents(),this.uplinkConnection.onSinglePCReconnected()),this.remotePublishedUserMap.forEach(a=>{a.installEvents(),a.onSinglePCReconnected()}))};this.singlePC.on(Tr.CONNECTION_STATE_CHANGED,r),this.checkConnectionsToReconnect(),this.uplinkConnection instanceof Sp&&!this.uplinkConnection.getIsReconnecting()&&this.uplinkConnection.startReconnection()}}catch(t){this._log.warn("reJoin fail ".concat(t)),this.reset(),de.logFailedEvent({userId:this.userId,eventType:Ft.REJOIN,error:t}),this.emit("error",new N({code:C.JOIN_ROOM_FAILED,message:j({key:B.REJOIN_ROOM_FAILED,data:{roomId:this.joinParams.roomId}})}))}else this._log.warn("reJoin abort")})}initialize(){return g(this,null,function*(){let e,{mainUrl:t,backupUrl:i}=this.getSignalChannelUrl(),r=this._signalChannel||function(s){return[...Ic.values()].find(c=>c.room.userId===s&&!c.room.isJoined)||null}(this.userId),n=!!(r&&r.isConnected&&r.keepAlive);return Array.isArray(this.scheduleResult.domains)&&this.scheduleResult.domains.length>0&&(e=this.scheduleResult.domains[0]),this._log.info("".concat(n?"reuse":"setup"," signal channel")),n?(r.url=t,r.backupUrl=i,r.room=this,this._signalChannel=r):(this._signalChannel=new Zv({sdkAppId:this.sdkAppId,userId:this.userId,userSig:this.userSig,url:t,backupUrl:i,race:this.enableSPC&&!this.proxy_ws,room:this,signalDomainWhenUnifiedProxy:this.proxy_unified?e:void 0}),this._customMessageManager=new gI(this,this._signalChannel),this._customMessageManager.on("message",s=>{this.emit("custom-message",s)})),this._networkQuality||(this._networkQuality=new vp({signalChannel:this._signalChannel,room:this}),this._networkQuality.on(vp.EVENT_NETWORK_QUALITY,s=>{this.emit("network-quality",s)})),ht(this,this._signalChannel).add(mp,s=>{R.emit(A.SIGNAL_CONNECTION_STATE_CHANGED,O({room:this},s)),this.emit("signal-connection-state-changed",s)}).add(fU,s=>{this.reset(),this.emit("error",s)}).add(K.PEER_JOIN,s=>{let{srcTinyId:a,userId:c,role:o}=s.data.data;this.userManager.addUser({userId:c,tinyId:a,role:o})}).add(K.PEER_LEAVE,s=>{let{userId:a,reason:c=0}=s.data.data;this.userManager.deleteUser(a,c)}).add(K.UPDATE_REMOTE_MUTE_STAT,s=>{this._lastHeartBeatTime>0&&Date.now()-this._lastHeartBeatTime>=1e4&&this.doHeartbeat(),this.onPublishedUserList(s.data)}).add(K.CLIENT_BANNED,s=>{let a=s.data.data,{reason:c}=a;if(de.uploadEvent({log:"stat-banned:".concat(c),userId:this.userId}),c==="user_time_out")return this._log.warn("".concat(c," last heart beat time: ").concat(this._lastHeartBeatTime," interval: ").concat(Date.now()-this._lastHeartBeatTime,", visibility: ").concat(document.visibilityState)),void this.reJoin();this._log[c==="kick"?"error":"info"]("user was banned because of [".concat(c,"]")),this.reset(),this.emit("banned",{reason:c})}),this._signalChannel.once(zv,s=>{this.tinyId=s.signalInfo.tinyId,R.emit(A.JOIN_SIGNAL_CONNECTION_END,{room:this})}),R.emit(A.JOIN_SIGNAL_CONNECTION_START,{room:this}),yield this._signalChannel.connect(),n&&R.emit(A.JOIN_SIGNAL_CONNECTION_END,{room:this}),n})}setSignalChannel(e){this._signalChannel=e,e||Pe(this)}leave(){return g(this,null,function*(){var e;try{yield this.doHeartbeat()}catch{}this._log.info("leave() => leaving room"),R.emit(A.LEAVE_SEND_CMD,{room:this}),(e=this._signalChannel)==null||e.send(yU)})}clearNetworkQuality(){this._networkQuality&&(this._networkQuality.stop(),this._networkQuality=null)}closeConnections(){this.remotePublishedUserMap.forEach(e=>{this.closeDownLinkConnection(e.userId,"you exitRoom")})}clearJoinTimeout(){clearTimeout(this._joinTimeout),this._joinTimeout=-1}startHeartbeat(){this._heartbeat===-1&&(this._heartbeat=_e.run(Es,this.doHeartbeat.bind(this),{delay:2e3}))}stopHeartbeat(){this._heartbeat!==-1&&(this._log.info("stopHeartbeat"),_e.clearTask(this._heartbeat),this._heartbeat=-1,this._lastHeartBeatTime=-1)}doHeartbeat(){return g(this,null,function*(){var e;let t=this.badCaseDetector.getMonitorFreeze(),i=yield this._stats.getStatsReport({uplinkConnection:this.uplinkConnection,downlinkConnections:this.remotePublishedUserMap,freezeMap:t});if(this.badCaseDetector.resetMonitor(),(e=this._signalChannel)==null||!e.isConnected)return;let r=this._signalChannel.isConnected?function(a){if(gn.has(a)){let c=gn.get(a).map(o=>({uint32_event_id:o.eventId,uint64_date:o.timestamp,str_userid:o.remoteUserId,uint32_param1:o.param1,uint32_param2:o.param2,uint32_video_stream_type:o.streamType}));return gn.delete(a),c}return[]}(this.userId):[],n=J(O({str_sdk_version:Vd,uint64_datetime:new Date().getTime(),msg_user_info:{str_identifier:this.userId,uint64_tinyid:this.tinyId},msg_event_msg:r,str_acc_ip:this.getSignalInfo().relayIp,str_client_ip:this.getSignalInfo().clientIp},i),{msg_device_info:O({uint32_terminal_type:15,str_device_name:navigator.platform,str_os_version:"",uint32_net_type:Qo()},i.msg_device_info)});this.heartbeatReport=n,R.emit(A.HEARTBEAT_REPORT,{room:this,report:n}),this._signalChannel.send(SU,n),this.emit("heartbeat-report",J(O({},n),{bytes_sent:this._stats.totalBytesSent+this._signalChannel.bytesSent,bytes_received:this._stats.totalBytesReceived+this._signalChannel.bytesReceived}));let s=Date.now();this._lastHeartBeatTime>0&&s-this._lastHeartBeatTime>1e4&&this._log.warn("heartbeat took ".concat(s-this._lastHeartBeatTime)),this._signalChannel.isConnected&&(this._lastHeartBeatTime=s),!this._isRelayChanged&&this.isRelayMaybeFailed()&&(this.reJoin(),this._isRelayChanged=!0)})}onPublishedUserList(e){if(!this.isJoined)return;let t=e.data.userList.map(i=>{let{userId:r,srcTinyId:n,flag:s}=i;r===this.userId&&this.uplinkConnection&&(this.uplinkConnection.flag=s);let a=this.remotePublishedUserMap.get(r);return a&&this.checkSubscribeBigSmallVideo(a),{userId:r,tinyId:n,flag:s}});R.emit(A.RECEIVED_PUBLISHED_USER_LIST,{room:this,publishedUserList:t}),this.userManager.setRemotePublishedUserList(t)}closeUplink(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"you unpublished";this.uplinkConnection&&(this.localTracks.size>0&&this.uplinkConnection.doUnpublish(),this.uplinkConnection.close(e),this.uplinkConnection=null),this.localTracks.forEach(t=>t.unpublish()),this.localTracks.clear()}createDownlinkConnection(e){let{userId:t,tinyId:i,flag:r}=e,n=new(this.singlePC?u1:rI)({userId:t,tinyId:i,room:this,signalChannel:this._signalChannel,enableSEI:this.enableSEI,flag:r});this.userManager.addRemotePublishedUser(n),this.installDownlinkEvents(n,t),this.emit("remote-published",n)}closeDownLinkConnection(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"remote user unpublished",i=this.remotePublishedUserMap.get(e);i&&(i.close(t),this.emit("remote-unpublished",i))}installDownlinkEvents(e,t){e.on("error",i=>{let r=i.getCode();r!==C.ICE_TRANSPORT_ERROR&&(r===C.DOWNLINK_RECONNECTION_FAILED&&this.closeDownLinkConnection(t),this.emit("error",i))}),e.on("connection-state-changed",i=>{this.emit("media-connection-state-changed",J(O({},i),{userId:e.userId}))}),e.on("firewall-restriction",()=>{this.emit("firewall-restriction")})}startSyncUserListInterval(){this._syncUserListInterval===-1&&(this._syncUserListInterval=_e.run(Es,this.syncUserList.bind(this)))}stopSyncUserListInterval(){_e.clearTask(this._syncUserListInterval),this._syncUserListInterval=-1}syncUserList(){return this.getUserList().then(e=>{this.userManager.setUserList(e)}).catch(e=>{this._log.debug("sync user list failed: ".concat(e))})}getUserList(){var e;return(e=this._signalChannel)!=null&&e.isConnected?this._signalChannel.sendWaitForResponse({command:DU,responseCommand:K.USER_LIST_RES,enableLog:!1,timeout:2e3}).then(t=>{let{data:i}=t,{code:r,message:n}=i;if(r===0)return(i.data&&i.data.userList||[]).map(s=>{let{userId:a,srcTinyId:c,role:o}=s;return{userId:a,tinyId:c,role:o}});throw j({key:B.SIGNAL_RESPONSE_FAILED,data:{signalResponse:K.USER_LIST_RES,code:r,message:n}})}):Promise.reject("not connected")}getAllConnections(){let e=[...this.remotePublishedUserMap.values()];return this.uplinkConnection&&e.push(this.uplinkConnection),e}isRelayMaybeFailed(){if(this._signalChannel&&!this._signalChannel.isOnline||!eI)return!1;if(this.singlePC)return this.singlePC.reconnectionCount>6;let e=this.getAllConnections();if(e.length===0)return!1;for(let t=0;t<e.length;t++)if(e[t].getReconnectionCount()<6)return!1;return!0}checkConnectionsToReconnect(){var e;this.singlePC?((e=this.singlePC.getPeerConnection())==null?void 0:e.connectionState)===fe.CLOSED&&!this.singlePC.isReconnecting&&(this._log.warn("spc pc is closed but not reconnect"),this.singlePC.startReconnection()):this.getAllConnections().forEach(t=>{if(t instanceof fr&&!t.getIsReconnecting()){let i=t.getPeerConnection();i&&i.connectionState===fe.CLOSED&&(this._log.warn("[".concat(t.getUserId(),"] pc is closed but not reconnect")),t.startReconnection())}})}fallbackToMPC(){return g(this,null,function*(){var e;if(this._log.warn("fallback to multi pc"),de.uploadEvent({log:"stat-fallback",userId:this.userId}),this.enableSPC=!1,(e=this.singlePC)==null||e.close(),this.singlePC=null,this.isJoined&&(yield this.reJoin(!1)),this.uplinkConnection){let t=this.uplinkConnection;this.uplinkConnection=new Sp({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this._signalChannel,enableSEI:this.enableSEI,audioManager:this.audioManager}),t.isMainStreamPublished&&(yield this.uplinkConnection.publish({localAudioTrack:t.localMainAudioTrack,localVideoTrack:t.localMainVideoTrack,isAuxiliary:!1})),t.isAuxStreamPublished&&(yield this.uplinkConnection.publish({localAudioTrack:t.localAuxAudioTrack,localVideoTrack:t.localAuxVideoTrack,isAuxiliary:!0})),t.close()}this.remotePublishedUserMap.forEach(t=>{let i=new rI({userId:t.userId,tinyId:t.tinyId,room:this,signalChannel:this._signalChannel,enableSEI:this.enableSEI,flag:t.flag,remoteAudioTrack:t.remoteAudioTrack,remoteVideoTrack:t.remoteVideoTrack,remoteAuxiliaryTrack:t.remoteAuxiliaryTrack});this.installDownlinkEvents(i,t.userId),this.remotePublishedUserMap.set(t.userId,i),t.isMainStreamSubscribed&&i.subscribe(t.subscribeState,"main"),t.isAuxStreamSubscribed&&i.subscribe(t.subscribeState,"auxiliary")})})}destroy(){this.isDestroyed||(this._signalChannel&&(this._log.info("destroying SignalChannel"),this._signalChannel.close(),this._signalChannel=null),super.destroy(),this._joinReject&&(this._joinReject(new N({code:C.INVALID_OPERATION,message:j({key:B.CLIENT_DESTROYED,data:{funName:"join"}})})),this.clearJoinTimeout(),this.reset()),this.removeAllListeners())}switchRole(e){return g(this,null,function*(){this.role!==e&&(e==="audience"&&this.uplinkConnection&&this.closeUplink("you switch role to audience"),yield this.doSwitchRole(e))})}doSwitchRole(e){let t={command:wU,data:{role:e==="anchor"?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel},responseCommand:K.SWITCH_ROLE_RES,retries:1};return this._log.info("switchRole signal data: ".concat(JSON.stringify(t.data))),this._signalChannel.sendWaitForResponseWithRetry(t).then(i=>{let{code:r,message:n}=i.data;if(r!==0)throw new N({code:C.SWITCH_ROLE_FAILED,message:j({key:B.SWITCH_ROLE_FAILED,data:{message:n,code:r}})});this.role=e}).catch(i=>{throw i instanceof N&&i.getCode()===C.API_CALL_TIMEOUT&&(i=new N({code:C.SWITCH_ROLE_FAILED,message:j({key:B.SWITCH_ROLE_TIMEOUT})})),this._log.error(i),i})}publish(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return g(this,null,function*(){let r={},n={};t.forEach(o=>{o instanceof Kt&&(o instanceof qs?n.audio=o:r.audio=o),o instanceof Je&&(o instanceof dr&&o.mediaType===2?n.video=o:r.video=o)});let s=oa(r),a=oa(n);(!s||!a)&&!this.uplinkConnection&&(this.singlePC?this.uplinkConnection=new Ap({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this._signalChannel,enableSEI:this.enableSEI,audioManager:this.audioManager}):this.uplinkConnection=new Sp({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this._signalChannel,enableSEI:this.enableSEI,audioManager:this.audioManager}),this.uplinkConnection.on("connection-state-changed",o=>{this.emit("media-connection-state-changed",J(O({},o),{userId:this.userId}))}),this.uplinkConnection.on("firewall-restriction",()=>{this.emit("firewall-restriction")}),this.uplinkConnection.on("error",o=>{let l=o.getCode();l!==C.ICE_TRANSPORT_ERROR&&(l===C.UPLINK_RECONNECTION_FAILED&&this.closeUplink(),this.emit("error",o))}));let c=t.map(o=>o.kind).join(",");s||(this._log.info("publish() => main ".concat(c)),yield this.uplinkConnection.publish({localAudioTrack:r.audio,localVideoTrack:r.video,isAuxiliary:!1}),this._log.info("main is published")),a||(this._log.info("publish() => aux ".concat(c)),yield this.uplinkConnection.publish({localAudioTrack:n.audio,localVideoTrack:n.video,isAuxiliary:!0}),this._log.info("aux is published"))})}unpublish(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return g(this,null,function*(){if(this.scene==="live"&&this.role!=="anchor"||!this.isMainStreamPublished&&!this.isAuxStreamPublished||!this.uplinkConnection)return;let r={},n={};t.forEach(s=>{!s.mediaTrack||!s.isPublished||(s instanceof Kt&&(s instanceof qs?n.audio=s:r.audio=s),s instanceof Je&&(s instanceof dr&&s.mediaType===2?n.video=s:r.video=s))});try{let s=t.map(a=>a.kind).join(",");oa(r)||(this._log.info("unpublish() => main ".concat(s)),yield this.uplinkConnection.unpublish({localAudioTrack:r.audio,localVideoTrack:r.video})),oa(n)||(this._log.info("unpublish() => aux ".concat(s)),yield this.uplinkConnection.unpublish({localAudioTrack:n.audio,localVideoTrack:n.video}))}catch{}this.localTracks.size===0&&this.closeUplink("you unpublished")})}addTrack(e){if(!this.uplinkConnection||!e.mediaTrack)return Promise.resolve();let t=this.uplinkConnection.addTrack(e);return e.publish(this,t),t}removeTrack(e){return this.uplinkConnection&&e.mediaTrack?this.uplinkConnection.removeTrack(e).then(t=>(e.unpublish(),t)):Promise.resolve()}replaceTrack(e){return this.uplinkConnection&&e.mediaTrack&&GS()?this.uplinkConnection.replaceTrack(e).then(t=>{t&&R.emit(A.LOCAL_TRACK_REPLACED,{track:e})}):Promise.resolve()}setBandWidth(e){return g(this,null,function*(){!this.uplinkConnection||(yield this.uplinkConnection.setBandwidth(e),yield this.uplinkConnection.sendMediaSettings())})}enableSmall(e){return g(this,null,function*(){if(!this.uplinkConnection||!this.uplinkConnection.localMainVideoTrack)return Promise.resolve();e&&this.uplinkConnection.localMainVideoTrack.small&&(yield this.setBandWidth({type:_.VIDEO,videoType:_.SMALL,bandwidth:this.uplinkConnection.localMainVideoTrack.small.bitrate})),yield this.uplinkConnection.enableSmall(e)})}subscribe(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return g(this,null,function*(){if(t=t.filter(a=>!a.isSubscribed),t.length===0)return;let{userId:r}=t[0],n=this.remotePublishedUserMap.get(r);if(!n)return;let s=t.find(a=>a.mediaType===2)?"auxiliary":"main";try{let a=O({},n.subscribeState);t.forEach(o=>{switch(o.mediaType){case 1:a.audio=!0;break;case 4:a.video=!0;break;case 8:a.smallVideo=!0;break;case 2:a.auxiliary=!0}});let c=this._changeBigSmallRecords.get(r);c&&c.options.smallVideo&&n.muteState.hasSmall&&a.video&&(a.video=!1,a.smallVideo=!0),R.emit(A.SUBSCRIBE_START,{room:this,streamType:s,remotePublishedUser:n,subscribeState:a}),this._log.info("subscribe() => ".concat(r," ").concat(s," [").concat(Tp(a),"] prev: [").concat(Tp(n.subscribeState),"]")),yield n.subscribe(a,s),this._log.info("subscribe ".concat(r," ").concat(s," done"));for(let o of t)o.mediaTrack||(yield o.waitHasMediaTrack());R.emit(A.SUBSCRIBE_SUCCESS,{room:this,streamType:s,remotePublishedUser:n})}catch(a){let c=a instanceof N?a.getCode():C.UNKNOWN,o=a;throw a instanceof N?c===C.REMOTE_STREAM_NOT_EXIST&&(o=new N({code:C.API_CALL_ABORTED,message:j({key:B.API_CALL_ABORTED,data:{message:a.message,userId:r,streamType:s}})}),this._log.warn(o)):(o=new N({code:c,message:j({key:B.SUBSCRIBE_FAILED,data:{message:a.message,userId:r,streamType:s}})}),this._log.error(o)),o}})}unsubscribe(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return g(this,null,function*(){let{userId:r}=t[0],n=this.remotePublishedUserMap.get(r);if(!n)return;let s=t.find(a=>a.mediaType===2)?"auxiliary":"main";this._log.info("unsubscribe() => ".concat(r," ").concat(s));try{yield n.unsubscribe({remoteTracks:t,streamType:s})}catch(a){this._log.warn("unsubscribe() => failed ".concat(a))}t.forEach(a=>{a.unsubscribe(),a.mediaType===8&&a.setMediaType(4)}),R.emit(A.UNSUBSCRIBE_SUCCESS,{room:this,streamType:s,remotePublishedUser:n})})}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAudioVolumeEvaluation(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:2e3,t=arguments.length>1?arguments[1]:void 0;if(e<=0)return this._enableAudioVolumeEvaluation=!1,void _e.clearTask(this._audioVolumeIntervalId);e=Math.floor(Math.max(e,100)),R.emit(A.AUDIO_LEVEL_INTERVAL,{interval:e}),this._audioVolumeIntervalId&&_e.clearTask(this._audioVolumeIntervalId),this._enableAudioVolumeEvaluation=!0,this._audioVolumeIntervalId=_e.run(Qd,()=>{var i;let r=[];(i=this.remotePublishedUserMap)==null||i.forEach(n=>{if(n.muteState.hasAudio){let s=Math.floor(100*n.remoteAudioTrack.getAudioLevel());r.push({userId:n.userId,volume:s})}}),this.emit("audio-volume",r)},{fps:1e3/e,backgroundTask:t})}getLocalAudioStats(){return g(this,null,function*(){let e={};if(e[this.userId]={bytesSent:0,packetsSent:0},this.uplinkConnection){let t=yield this._stats.getSenderStats(this.uplinkConnection);e[this.userId]={bytesSent:t.audio.bytesSent,packetsSent:t.audio.packetsSent}}return e})}getLocalVideoStats(){return g(this,null,function*(){let e={};if(e[this.userId]={bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0},this.uplinkConnection){let{video:{bytesSent:t,packetsSent:i,framesEncoded:r,framesSent:n,frameWidth:s,frameHeight:a}}=yield this._stats.getSenderStats(this.uplinkConnection);e[this.userId]={bytesSent:t,packetsSent:i,framesEncoded:r,framesSent:n,frameWidth:s,frameHeight:a}}return e})}getTransportStats(){return g(this,null,function*(){let e={rtt:0,downlinksRTT:{}};if(this.uplinkConnection){let t=yield this._stats.getSenderStats(this.uplinkConnection);e.rtt=t.rtt}for(let[,t]of this.remotePublishedUserMap){let i=yield this._stats.getReceiverStats(t);e.downlinksRTT[i.userId]=i.rtt}return e})}getRemoteVideoStats(e){return g(this,null,function*(){let t={};for(let[i,r]of this.remotePublishedUserMap)e==="main"&&r.muteState.hasVideo&&(t[i]=r.remoteVideoTrack.stat),e==="auxiliary"&&r.muteState.hasAuxiliary&&(t[i]=r.remoteAuxiliaryTrack.stat);return t})}getRemoteAudioStats(){return g(this,null,function*(){let e={};for(let[t,i]of this.remotePublishedUserMap)i.muteState.hasAudio&&(e[t]=i.remoteAudioTrack.stat);return e})}setTurnServer(e,t){this._log.info("set turn server: ".concat(JSON.stringify(e)," ").concat(t||""));let i=[];Array.isArray(e)?e.forEach(r=>i.push(yt.getTurnServer(r))):yt.isPlainObject(e)&&i.push(yt.getTurnServer(e)),this._turnServers=i,t&&(this._iceTransportPolicy=t)}sendStartMixTranscode(e){return this._signalChannel.sendWaitForResponse({command:kU,data:e,timeout:5e3,responseCommand:K.START_MIX_TRANSCODE_RES,commandDesc:"startMixTranscode"})}sendStopMixTranscode(e){return this._signalChannel.sendWaitForResponse({command:NU,data:e,timeout:5e3,responseCommand:K.STOP_MIX_TRANSCODE_RES,commandDesc:"stopMixTranscode"})}sendStartPublishCDN(e){let t=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];return this._signalChannel.sendWaitForResponse({command:t?AU:CU,data:e,timeout:5e3,responseCommand:t?K.START_PUBLISH_TENCENT_CDN_RES:K.START_PUBLISH_GIVEN_CDN_RES,commandDesc:"startPublishCDN"})}sendStopPublishCDN(e){let t=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];return this._signalChannel.sendWaitForResponse({command:t?RU:bU,data:e,timeout:5e3,responseCommand:t?K.STOP_PUBLISH_TENCENT_CDN_RES:K.STOP_PUBLISH_GIVEN_CDN_RES,commandDesc:"stopPublishCDN"})}sendAbilityStatus(e){var t;(t=this._signalChannel)==null||t.sendWaitForResponse({command:xU,data:e,timeout:5e3,responseCommand:K.ABILITY_STATUS_REPORT_RESULT,commandDesc:"ability status report"}).catch(i=>{})}getIceServers(){return this._turnServers.length===0&&this.scheduleResult.iceServers?this.scheduleResult.iceServers:this._turnServers}getIceTransportPolicy(){return this._iceTransportPolicy||this.scheduleResult.iceTransportPolicy||"all"}getLogger(){return this._log}enableAIVoice(){throw new Error("Method not implemented.")}getSignalChannelUrl(){let e={mainUrl:"",backupUrl:""},t=yt.getEnv();return t?(e.mainUrl="wss://".concat(t,".rtc.qq.com"),e.backupUrl=e.mainUrl):this.proxy_ws?(e.mainUrl=this.proxy_ws,e.backupUrl=e.mainUrl):this.proxy_unified?(e.mainUrl="wss://".concat(this.proxy_unified),e.backupUrl=e.mainUrl):Array.isArray(this.scheduleResult.domains)&&this.scheduleResult.domains.length>0&&(e.mainUrl="wss://".concat(this.scheduleResult.domains[0]),e.backupUrl=e.mainUrl,this.scheduleResult.domains[1]&&(e.backupUrl="wss://".concat(this.scheduleResult.domains[1]))),e}getSignalInfo(){var e;return((e=this._signalChannel)==null?void 0:e.getSignalInfo())||{clientIp:"",relayIp:""}}reset(){let e=arguments.length>0&&arguments[0]!==void 0&&arguments[0];this.stopSyncUserListInterval(),this.stopHeartbeat(),this.closeConnections(),this.clearNetworkQuality(),this.closeUplink("you exitRoom"),this._signalChannel&&(e&&this._signalChannel.keepAlive&&this._signalChannel.isConnected?this._signalChannel.stopKeepAliveIn(3600):this._signalChannel.close(),this.setSignalChannel(null)),this._stats.reset(),this.userManager.clear(),this.userManager.removeAllListeners(),this.singlePC&&(this.singlePC.close(),this.singlePC=null),this.scheduleResult={domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null}}checkSubscribeBigSmallVideo(e){return g(this,null,function*(){let{subscribeState:t,userId:i,muteState:{hasSmall:r,hasVideo:n}}=e;if(!r&&!n||!t.video&&!t.smallVideo)return;let s=this._changeBigSmallRecords.get(i);if(!s||s.isSubscribing||s.reSubscribeCount<=0)return;let{options:a,reSubscribeCount:c}=s;if(a.video&&t.video||a.smallVideo&&t.smallVideo&&r)return;let o={audio:e.remoteAudioTrack.isSubscribed||e.remoteAudioTrack.isSubscribing,auxiliary:e.remoteAuxiliaryTrack.isSubscribed||e.remoteAuxiliaryTrack.isSubscribing,video:a.video,smallVideo:a.smallVideo};try{if(!r&&o.smallVideo&&(o.video=!0,o.smallVideo=!1),o.smallVideo===t.smallVideo&&o.video===t.video)return;s.isSubscribing=!0,s.reSubscribeCount=c-1,yield e.subscribe(o,"main"),e.remoteVideoTrack.setMediaType(o.smallVideo?8:4),this._log.info("change [".concat(i,"] to ").concat(o.smallVideo?"small":"big"," video successfully. count ").concat(gs-s.reSubscribeCount,".")),s.isSubscribing=!1,s.reSubscribeCount=gs}catch{this._log.info("change [".concat(i,"] to ").concat(o.smallVideo?"small":"big"," video failed. count ").concat(gs-s.reSubscribeCount,".")),s.isSubscribing=!1,s.reSubscribeCount===0&&this._changeBigSmallRecords.delete(i)}})}changeType(e,t){let i={options:{video:!e,smallVideo:e},isSubscribing:!1,reSubscribeCount:gs};this._changeBigSmallRecords.set(t.userId,i),this._log.info("set [".concat(t.userId,"] video prefer type: ").concat(e?"small":"big"))}get smallStreamConfig(){return this._smallStreamConfig}_initBusinessInfo(e){this._businessInfo=e.businessInfo;let t={};if(EI(e.businessInfo)&&(t=JSON.parse(e.businessInfo)),!An(e.pureAudioPushMode)){if(!Number.isInteger(Number(e.pureAudioPushMode)))throw new N({code:C.INVALID_PARAMETER,message:j({key:B.INVALID_PURE_AUDIO})});this._pureAudioPushMode=e.pureAudioPushMode,t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.pure_audio_push_mod=this._pureAudioPushMode}if(!An(e.userDefineRecordId)){let i=/^[A-Za-z0-9_-]{1,64}$/gi;if(e.userDefineRecordId.match(i)===null)throw new N({code:C.INVALID_PARAMETER,message:j({key:B.INVALID_USER_DEFINE_RECORDID})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_record_id=e.userDefineRecordId}if(!An(e.userDefinePushArgs)){if(!(EI(e.userDefinePushArgs)&&String(e.userDefinePushArgs)&&String(e.userDefinePushArgs).length<=256))throw new N({code:C.INVALID_PARAMETER,message:j({key:B.INVALID_USER_DEFINE_PUSH_ARGS})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_push_args=e.userDefinePushArgs}oa(t)||(this._businessInfo=JSON.stringify(t))}sendSEI(e,t){var i,r;this.uplinkConnection instanceof Ap&&(t!=null&&t.toSubStream?(i=this.uplinkConnection.localAuxVideoTrack)==null||i.sendSEI(e,t):(r=this.uplinkConnection.localMainVideoTrack)==null||r.sendSEI(e,t))}sendCustomMessage(e){var t;(t=this._customMessageManager)==null||t.send(e)}enableInsertableStreams(){if(this.singlePC&&!this.singlePC.enableInsertableStreams)return this.singlePC.enableInsertableStreams=!0,this.singlePC.startReconnection()}};return k([Jv(["left",he.INIT],"joined"),cr({settings:{retries:1,timeout:0},onError(e,t,i){this._isUsingCachedSchedule&&!this.isDestroyed?(this._log.warn("is using cached schedule, retry join"),gi(!0),this.reset(),t()):this._signalChannel&&this._signalChannel.isConnected&&this._signalChannel.keepAlive?(this._log.warn("is using keepAlive ws, retry join"),this._signalChannel.close(),this.reset(),t()):(this.reset(),this._log.error(e),i(e))}}),ae(e=>{let t=new uU;return function(i,r,n){return g(this,null,function*(){let s=String(i.roomId||i.strRoomId);if(this.userId=i.userId,this.sdkAppId=i.sdkAppId,this.userSig=i.userSig,this._log.setSdkAppId(this.sdkAppId),this._log.setUserId(this.userId),this.scene=r,i.privateMapKey=i.privateMapKey||"",this.isJoined)throw new N({code:C.INVALID_OPERATION,message:j({key:B.INVALID_JOIN})});if(this.checkDestroy(),t.isJoined({userId:this.userId,roomId:s,sdkAppId:this.sdkAppId,room:this}))throw new N({code:C.INVALID_OPERATION,message:j({key:B.REPEAT_JOIN,data:this.userId})});t.add({room:this,roomId:s}),this.role=i.role===21?"audience":"anchor",this._log.info("Join() => joining room: ".concat(s," useStringRoomId: ").concat(this.useStringRoomId," scene: ").concat(this.scene," role: ").concat(this.role)),R.emit(A.JOIN_START,{room:this,roomId:s,params:i}),this.checkSystemResult=yield Vs.checkSystemRequirementsInternal(),this.checkDestroy();let a=yt.getEnv();a||(a=Qi.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(Wd.OLD_CLOUD_LADDER)?a=Qi.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(Wd.WEBRTC)&&(a=Qi.WEBRTC))),de.setConfig({env:a,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:s}),dU.call(this);let{isH264EncodeSupported:c,isVp8EncodeSupported:o}=this.checkSystemResult.detail;if(!Vs.isWebRTCSupported()||!c&&!o)throw new N({code:C.NOT_SUPPORTED,message:j({key:B.NOT_SUPPORTED_WEBRTC})});try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!yt.getEnv()&&(yield this.schedule(i,n));let l=yield e.call(this,i,r,n);return this.roomId=s,this._joinedTimestamp=yt.performanceNow(),R.emit(A.JOIN_SUCCESS,{room:this}),n===30&&!i.component&&de.uploadEvent({log:"stat-conv-".concat(Number(on),"-").concat(location.hostname),userId:this.userId}),l}catch(l){throw t.delete({room:this,roomId:s}),R.emit(A.JOIN_FAILED,{room:this,error:l}),l}})}})],wi.prototype,"join"),k([Jv("joined","left",{ignoreError:!0,success(){this.reset(!0)}}),ae(e=>function(){return g(this,null,function*(){R.emit(A.LEAVE_START,{room:this}),yield e.call(this),R.emit(A.LEAVE_SUCCESS,{room:this,roomId:this.roomId})})}),gv("leave room"),nc({fnName:"publish",validateArgs:!1}),nc({fnName:"unsubscribe",validateArgs:!1})],wi.prototype,"leave"),k([_n(),ae(e=>function(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];return g(this,null,function*(){if(this.scene==="live"&&this.role!=="anchor"||(i=i.filter(s=>s.outMediaTrack&&s.state==="capture"),!i.length))return;R.emit("61",{room:this});let n=e.apply(this,i);return i.forEach(s=>s.publish(this,n)),n})}),cr({settings:{retries:rn,timeout:e=>ln(e)},onError(e,t,i){var r;(r=e.message)!=null&&r.includes("timeout")?(this._log.warn("publish timeout"),t()):(this._log.error("publish failed: ".concat(e)),i(e),R.emit(A.PUBLISH_FAILED,{room:this}))}})],wi.prototype,"publish"),k([nc({fnName:"publish"}),(TI="api-call",function(e,t,i){let r=i.value;return i.value=function(){for(var n=arguments.length,s=new Array(n),a=0;a<n;a++)s[a]=arguments[a];let c=zs.get(this);if(c){let o=c.queue.filter((l,d)=>{if(d===0)return!0;let u=!0;return l.args.forEach(p=>{s.find(m=>m===p)||(u=!1)}),!u||(l.reject(new N({code:C.API_CALL_ABORTED,message:TI})),!1)});c.queue=o}return r.apply(this,s)},i}),_n(),ae(e=>function(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];let n=e.apply(this,i);return i.forEach(s=>s.unpublish()),n}),np(function(){var e,t;!this.uplinkConnection&&Fs()&&((t=(e=this.singlePC)==null?void 0:e.getPeerConnection())==null||t.getSenders().forEach(i=>i.track&&i.replaceTrack(null)))})],wi.prototype,"unpublish"),k([fn(e=>e.userId)],wi.prototype,"replaceTrack"),k([fn(function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return t[0].userId}),Sv(),ae(e=>function(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];let n=e.apply(this,i);return i.forEach(s=>!s.isSubscribed&&s.subscribe(n)),n}),cr({settings:{retries:rn,timeout:e=>ln(e)},onError(e,t,i,r){e.message.includes("timeout")?(this._log.warn("subscribe timeout"),t()):(this._log.error("subscribe failed: ".concat(e)),i(e),R.emit(A.SUBSCRIBE_FAILED,{room:this,remoteTracks:r}))}})],wi.prototype,"subscribe"),k([nc({fnName:"subscribe",callback(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];this.singlePC||t.forEach(r=>{let n=this.remotePublishedUserMap.get(r.userId);n&&!n.isMainStreamSubscribed&&!n.isAuxStreamSubscribed&&n.close("you unsubscribed")})}}),fn(function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return t[0].userId})],wi.prototype,"unsubscribe"),Sc.create=Sc._create.bind(Sc,wi),Sc})})(AI);var m1=AI.exports;const _1=kc.getDefaultExportFromCjs(m1);exports.TRTC=_1;