@kaeawc/auto-mobile 0.0.91 → 0.0.93

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 (272) hide show
  1. package/dist/build-info.json +12 -12
  2. package/dist/schemas/README.md +16 -0
  3. package/dist/schemas/prototype-icon-names.json +302 -0
  4. package/dist/schemas/test-plan.schema.json +370 -52
  5. package/dist/src/chunk-00167wan.js +55 -0
  6. package/dist/src/chunk-0jrrsnc9.js +6 -0
  7. package/dist/src/chunk-0n6swkwg.js +5 -0
  8. package/dist/src/chunk-0qsy1qsx.js +57 -0
  9. package/dist/src/chunk-11m8wj8j.js +237 -0
  10. package/dist/src/chunk-1p7xf5kb.js +5 -0
  11. package/dist/src/chunk-23p5f095.js +4 -0
  12. package/dist/src/chunk-26k317v5.js +5 -0
  13. package/dist/src/chunk-284ptqa4.js +7 -0
  14. package/dist/src/chunk-28re4xrg.js +4 -0
  15. package/dist/src/chunk-2f9rkmhx.js +5 -0
  16. package/dist/src/chunk-2fxdh48t.js +4 -0
  17. package/dist/src/chunk-2tbdrbt6.js +4 -0
  18. package/dist/src/chunk-2tqzq5qh.js +971 -0
  19. package/dist/src/chunk-32gvv9b4.js +21 -0
  20. package/dist/src/chunk-3f3t1x97.js +8 -0
  21. package/dist/src/chunk-3fspkbc7.js +4 -0
  22. package/dist/src/chunk-3qwrzxh0.js +11 -0
  23. package/dist/src/chunk-3sy6ahhz.js +26 -0
  24. package/dist/src/chunk-3vg455e6.js +4 -0
  25. package/dist/src/chunk-3xkpk44w.js +5 -0
  26. package/dist/src/chunk-3y6eykz9.js +4 -0
  27. package/dist/src/chunk-49bsqdx3.js +4 -0
  28. package/dist/src/chunk-4hw3665t.js +42 -0
  29. package/dist/src/chunk-58wzr3mt.js +5 -0
  30. package/dist/src/chunk-5d2hft6c.js +5 -0
  31. package/dist/src/chunk-5s645vr4.js +4 -0
  32. package/dist/src/chunk-5snsn9cf.js +4 -0
  33. package/dist/src/chunk-5tm9mn47.js +54 -0
  34. package/dist/src/chunk-5zc77a5t.js +4 -0
  35. package/dist/src/chunk-64j0majr.js +19 -0
  36. package/dist/src/chunk-65y8v4td.js +17 -0
  37. package/dist/src/chunk-6awz7vhq.js +5 -0
  38. package/dist/src/chunk-6bznss4t.js +8 -0
  39. package/dist/src/chunk-6ep7f5ge.js +4 -0
  40. package/dist/src/chunk-6pg7bqck.js +4 -0
  41. package/dist/src/chunk-6wt9rgjf.js +5 -0
  42. package/dist/src/chunk-6xmss8er.js +8 -0
  43. package/dist/src/chunk-710rxz9y.js +5 -0
  44. package/dist/src/chunk-7cs2da62.js +5 -0
  45. package/dist/src/chunk-7g103b54.js +4 -0
  46. package/dist/src/chunk-7j5vj4pa.js +4 -0
  47. package/dist/src/chunk-7rz9898k.js +5 -0
  48. package/dist/src/chunk-7tw8x05v.js +4 -0
  49. package/dist/src/chunk-7zy586cb.js +4 -0
  50. package/dist/src/chunk-8037tzzj.js +5 -0
  51. package/dist/src/chunk-84nanf8s.js +5 -0
  52. package/dist/src/chunk-8g1922rp.js +10 -0
  53. package/dist/src/chunk-8gvwcv2p.js +4 -0
  54. package/dist/src/chunk-8ph29g99.js +4 -0
  55. package/dist/src/chunk-8thrmfat.js +4 -0
  56. package/dist/src/chunk-8zgzzs7k.js +78 -0
  57. package/dist/src/chunk-97b1zmaq.js +4 -0
  58. package/dist/src/chunk-9fth9ayh.js +4 -0
  59. package/dist/src/chunk-9j6anhjr.js +4 -0
  60. package/dist/src/chunk-aabchzxk.js +9 -0
  61. package/dist/src/chunk-ayp07wbb.js +4 -0
  62. package/dist/src/chunk-bfjwqk8q.js +4 -0
  63. package/dist/src/chunk-bfw6125s.js +5 -0
  64. package/dist/src/chunk-bnhscm2n.js +4 -0
  65. package/dist/src/chunk-bxmsax22.js +5 -0
  66. package/dist/src/chunk-c1vs4g1n.js +4 -0
  67. package/dist/src/chunk-ct3e7yng.js +4 -0
  68. package/dist/src/chunk-cyy71ggq.js +5 -0
  69. package/dist/src/chunk-ddzkz92z.js +4 -0
  70. package/dist/src/chunk-dgrbdpb7.js +9 -0
  71. package/dist/src/chunk-drdz8hee.js +5 -0
  72. package/dist/src/chunk-e98dqnc9.js +145 -0
  73. package/dist/src/chunk-eersndy7.js +5 -0
  74. package/dist/src/chunk-eggq53ks.js +4 -0
  75. package/dist/src/chunk-f2dya7cs.js +4 -0
  76. package/dist/src/chunk-fbakd6cw.js +4 -0
  77. package/dist/src/chunk-fgb98zjj.js +5 -0
  78. package/dist/src/chunk-fmpad823.js +5 -0
  79. package/dist/src/chunk-g04bwyj3.js +4 -0
  80. package/dist/src/chunk-g0xr8zw0.js +4 -0
  81. package/dist/src/chunk-g3rjs80x.js +4 -0
  82. package/dist/src/chunk-g78rtrfv.js +4 -0
  83. package/dist/src/chunk-g7tmjbkt.js +5 -0
  84. package/dist/src/chunk-gabgv3y5.js +4 -0
  85. package/dist/src/chunk-gmr45m8f.js +4 -0
  86. package/dist/src/chunk-gsyfebqj.js +4 -0
  87. package/dist/src/chunk-h5rpn9wr.js +247 -0
  88. package/dist/src/chunk-hb1x7v55.js +4 -0
  89. package/dist/src/chunk-hrfytkxh.js +168 -0
  90. package/dist/src/chunk-j4yjzbak.js +4 -0
  91. package/dist/src/chunk-jd6a5v6p.js +5 -0
  92. package/dist/src/chunk-jh6vhqzx.js +5 -0
  93. package/dist/src/chunk-kn5spq15.js +4 -0
  94. package/dist/src/chunk-m94qs0f0.js +4 -0
  95. package/dist/src/chunk-mjrps0ac.js +7 -0
  96. package/dist/src/chunk-n03dmn5q.js +5 -0
  97. package/dist/src/chunk-n72qhwd9.js +4 -0
  98. package/dist/src/chunk-ndt1ccxm.js +71 -0
  99. package/dist/src/chunk-nr6y0n4y.js +5 -0
  100. package/dist/src/chunk-pcsen2vs.js +4 -0
  101. package/dist/src/chunk-ppfr0b8h.js +4 -0
  102. package/dist/src/chunk-q10bdnat.js +4 -0
  103. package/dist/src/chunk-q9xmq595.js +4 -0
  104. package/dist/src/chunk-qcxzr2my.js +5 -0
  105. package/dist/src/chunk-qf6nynk6.js +7 -0
  106. package/dist/src/chunk-qyqypn28.js +5 -0
  107. package/dist/src/chunk-r2epb56s.js +4 -0
  108. package/dist/src/chunk-r5bxavdx.js +311 -0
  109. package/dist/src/chunk-r6z1eztj.js +18 -0
  110. package/dist/src/chunk-r7bpkgff.js +4 -0
  111. package/dist/src/chunk-r8jf3d92.js +4 -0
  112. package/dist/src/chunk-rbpdk7m0.js +5 -0
  113. package/dist/src/chunk-rc0dbypm.js +4 -0
  114. package/dist/src/chunk-rhcty4ms.js +4 -0
  115. package/dist/src/chunk-rpvckv3p.js +4 -0
  116. package/dist/src/chunk-rqc9ap3x.js +4 -0
  117. package/dist/src/chunk-rvvy1bte.js +7 -0
  118. package/dist/src/chunk-ry0mz41y.js +4 -0
  119. package/dist/src/chunk-s3jc6cwp.js +5 -0
  120. package/dist/src/chunk-sfv61xjb.js +6 -0
  121. package/dist/src/chunk-t6bfvfkg.js +4 -0
  122. package/dist/src/chunk-t6c8akcm.js +5 -0
  123. package/dist/src/chunk-t7w8rctc.js +4 -0
  124. package/dist/src/chunk-thbh3jew.js +5 -0
  125. package/dist/src/chunk-v2wd4n3e.js +5 -0
  126. package/dist/src/chunk-v6pya0dm.js +5 -0
  127. package/dist/src/chunk-vy3bwm1d.js +17 -0
  128. package/dist/src/chunk-w3vs79ex.js +27 -0
  129. package/dist/src/chunk-w4zga19f.js +4 -0
  130. package/dist/src/chunk-w5b2jwk3.js +14 -0
  131. package/dist/src/chunk-w7hkv422.js +5 -0
  132. package/dist/src/chunk-waqwcjyn.js +4 -0
  133. package/dist/src/chunk-wbh8spm5.js +20 -0
  134. package/dist/src/chunk-wyrkw6hw.js +5 -0
  135. package/dist/src/chunk-xa73x2cx.js +5 -0
  136. package/dist/src/chunk-xgan0qqp.js +4 -0
  137. package/dist/src/chunk-y2vs6jwg.js +4 -0
  138. package/dist/src/chunk-yattm52s.js +4 -0
  139. package/dist/src/chunk-yb97j25b.js +6 -0
  140. package/dist/src/chunk-ybbtagbt.js +5 -0
  141. package/dist/src/chunk-ycaj2sgf.js +9 -0
  142. package/dist/src/chunk-yf7ympyz.js +325 -0
  143. package/dist/src/chunk-yjawdzk8.js +4 -0
  144. package/dist/src/chunk-z637nqg8.js +11 -0
  145. package/dist/src/chunk-zgja5f3p.js +6 -0
  146. package/dist/src/chunk-zs1sghs9.js +4 -0
  147. package/dist/src/daemon/processEntry.js +4 -0
  148. package/dist/src/index.js +4 -2843
  149. package/dist/src/runtime/bunRuntimeGuard.js +4 -0
  150. package/dist/src/utils/workers/iosBundleExtractWorker.js +2 -3
  151. package/ios/CameraPosterInjection/Injection/CameraPosterInjection.m +466 -0
  152. package/package.json +7 -6
  153. package/schemas/README.md +16 -0
  154. package/schemas/prototype-icon-names.json +302 -0
  155. package/schemas/test-plan.schema.json +370 -52
  156. package/node_modules/@borewit/text-codec/README.md +0 -87
  157. package/node_modules/@jimp/diff/node_modules/pixelmatch/README.md +0 -110
  158. package/node_modules/@jimp/diff/node_modules/pixelmatch/node_modules/pngjs/README.md +0 -433
  159. package/node_modules/@jimp/file-ops/dist/browser/index.js +0 -8
  160. package/node_modules/@jimp/js-png/README.md +0 -35
  161. package/node_modules/@jimp/js-png/src/__image_snapshots__/index-node-test-ts-png-should-use-png-options-1-snap.png +0 -0
  162. package/node_modules/@jimp/js-png/src/output.png +0 -0
  163. package/node_modules/@jimp/js-png/vitest.config.browser.mjs +0 -3
  164. package/node_modules/@jimp/plugin-resize/README.md +0 -12
  165. package/node_modules/@jimp/plugin-resize/vitest.config.browser.mjs +0 -3
  166. package/node_modules/@tokenizer/inflate/README.md +0 -114
  167. package/node_modules/@tokenizer/token/README.md +0 -19
  168. package/node_modules/await-to-js/README.md +0 -82
  169. package/node_modules/debug/README.md +0 -481
  170. package/node_modules/exif-parser/README.md +0 -83
  171. package/node_modules/file-type/readme.md +0 -667
  172. package/node_modules/ieee754/README.md +0 -51
  173. package/node_modules/mime/README.md +0 -178
  174. package/node_modules/ms/readme.md +0 -59
  175. package/node_modules/parse-bmfont-xml/README.md +0 -74
  176. package/node_modules/parse-bmfont-xml/lib/browser.js +0 -85
  177. package/node_modules/parse-bmfont-xml/node_modules/xml2js/README.md +0 -507
  178. package/node_modules/pngjs/README.md +0 -287
  179. package/node_modules/sax/README.md +0 -228
  180. package/node_modules/strtok3/README.md +0 -795
  181. package/node_modules/tinycolor2/README.md +0 -492
  182. package/node_modules/tinycolor2/cjs/test.js +0 -2191
  183. package/node_modules/tinycolor2/cjs/test_template.js +0 -26
  184. package/node_modules/tinycolor2/deno_asserts@0.168.0.mjs +0 -807
  185. package/node_modules/tinycolor2/esm/test.js +0 -2189
  186. package/node_modules/tinycolor2/esm/test_template.js +0 -24
  187. package/node_modules/tinycolor2/tinycolor.js +0 -1191
  188. package/node_modules/token-types/README.md +0 -160
  189. package/node_modules/uint8array-extras/readme.md +0 -318
  190. package/node_modules/xml-parse-from-string/README.md +0 -35
  191. package/node_modules/xmlbuilder/README.md +0 -86
  192. package/node_modules/zod/README.md +0 -208
  193. package/node_modules/zod/v4/locales/ar.d.cts +0 -4
  194. package/node_modules/zod/v4/locales/ar.d.ts +0 -4
  195. package/node_modules/zod/v4/locales/az.d.cts +0 -4
  196. package/node_modules/zod/v4/locales/az.d.ts +0 -4
  197. package/node_modules/zod/v4/locales/be.d.cts +0 -4
  198. package/node_modules/zod/v4/locales/be.d.ts +0 -4
  199. package/node_modules/zod/v4/locales/ca.d.cts +0 -4
  200. package/node_modules/zod/v4/locales/ca.d.ts +0 -4
  201. package/node_modules/zod/v4/locales/cs.d.cts +0 -4
  202. package/node_modules/zod/v4/locales/cs.d.ts +0 -4
  203. package/node_modules/zod/v4/locales/de.d.cts +0 -4
  204. package/node_modules/zod/v4/locales/de.d.ts +0 -4
  205. package/node_modules/zod/v4/locales/en.d.cts +0 -5
  206. package/node_modules/zod/v4/locales/en.d.ts +0 -5
  207. package/node_modules/zod/v4/locales/eo.d.cts +0 -5
  208. package/node_modules/zod/v4/locales/eo.d.ts +0 -5
  209. package/node_modules/zod/v4/locales/es.d.cts +0 -4
  210. package/node_modules/zod/v4/locales/es.d.ts +0 -4
  211. package/node_modules/zod/v4/locales/fa.d.cts +0 -4
  212. package/node_modules/zod/v4/locales/fa.d.ts +0 -4
  213. package/node_modules/zod/v4/locales/fi.d.cts +0 -4
  214. package/node_modules/zod/v4/locales/fi.d.ts +0 -4
  215. package/node_modules/zod/v4/locales/fr-CA.d.cts +0 -4
  216. package/node_modules/zod/v4/locales/fr-CA.d.ts +0 -4
  217. package/node_modules/zod/v4/locales/fr.d.cts +0 -4
  218. package/node_modules/zod/v4/locales/fr.d.ts +0 -4
  219. package/node_modules/zod/v4/locales/he.d.cts +0 -4
  220. package/node_modules/zod/v4/locales/he.d.ts +0 -4
  221. package/node_modules/zod/v4/locales/hu.d.cts +0 -4
  222. package/node_modules/zod/v4/locales/hu.d.ts +0 -4
  223. package/node_modules/zod/v4/locales/id.d.cts +0 -4
  224. package/node_modules/zod/v4/locales/id.d.ts +0 -4
  225. package/node_modules/zod/v4/locales/index.d.cts +0 -39
  226. package/node_modules/zod/v4/locales/index.d.ts +0 -39
  227. package/node_modules/zod/v4/locales/it.d.cts +0 -4
  228. package/node_modules/zod/v4/locales/it.d.ts +0 -4
  229. package/node_modules/zod/v4/locales/ja.d.cts +0 -4
  230. package/node_modules/zod/v4/locales/ja.d.ts +0 -4
  231. package/node_modules/zod/v4/locales/kh.d.cts +0 -4
  232. package/node_modules/zod/v4/locales/kh.d.ts +0 -4
  233. package/node_modules/zod/v4/locales/ko.d.cts +0 -4
  234. package/node_modules/zod/v4/locales/ko.d.ts +0 -4
  235. package/node_modules/zod/v4/locales/mk.d.cts +0 -4
  236. package/node_modules/zod/v4/locales/mk.d.ts +0 -4
  237. package/node_modules/zod/v4/locales/ms.d.cts +0 -4
  238. package/node_modules/zod/v4/locales/ms.d.ts +0 -4
  239. package/node_modules/zod/v4/locales/nl.d.cts +0 -4
  240. package/node_modules/zod/v4/locales/nl.d.ts +0 -4
  241. package/node_modules/zod/v4/locales/no.d.cts +0 -4
  242. package/node_modules/zod/v4/locales/no.d.ts +0 -4
  243. package/node_modules/zod/v4/locales/ota.d.cts +0 -4
  244. package/node_modules/zod/v4/locales/ota.d.ts +0 -4
  245. package/node_modules/zod/v4/locales/pl.d.cts +0 -4
  246. package/node_modules/zod/v4/locales/pl.d.ts +0 -4
  247. package/node_modules/zod/v4/locales/ps.d.cts +0 -4
  248. package/node_modules/zod/v4/locales/ps.d.ts +0 -4
  249. package/node_modules/zod/v4/locales/pt.d.cts +0 -4
  250. package/node_modules/zod/v4/locales/pt.d.ts +0 -4
  251. package/node_modules/zod/v4/locales/ru.d.cts +0 -4
  252. package/node_modules/zod/v4/locales/ru.d.ts +0 -4
  253. package/node_modules/zod/v4/locales/sl.d.cts +0 -4
  254. package/node_modules/zod/v4/locales/sl.d.ts +0 -4
  255. package/node_modules/zod/v4/locales/sv.d.cts +0 -4
  256. package/node_modules/zod/v4/locales/sv.d.ts +0 -4
  257. package/node_modules/zod/v4/locales/ta.d.cts +0 -4
  258. package/node_modules/zod/v4/locales/ta.d.ts +0 -4
  259. package/node_modules/zod/v4/locales/th.d.cts +0 -4
  260. package/node_modules/zod/v4/locales/th.d.ts +0 -4
  261. package/node_modules/zod/v4/locales/tr.d.cts +0 -5
  262. package/node_modules/zod/v4/locales/tr.d.ts +0 -5
  263. package/node_modules/zod/v4/locales/ua.d.cts +0 -4
  264. package/node_modules/zod/v4/locales/ua.d.ts +0 -4
  265. package/node_modules/zod/v4/locales/ur.d.cts +0 -4
  266. package/node_modules/zod/v4/locales/ur.d.ts +0 -4
  267. package/node_modules/zod/v4/locales/vi.d.cts +0 -4
  268. package/node_modules/zod/v4/locales/vi.d.ts +0 -4
  269. package/node_modules/zod/v4/locales/zh-CN.d.cts +0 -4
  270. package/node_modules/zod/v4/locales/zh-CN.d.ts +0 -4
  271. package/node_modules/zod/v4/locales/zh-TW.d.cts +0 -4
  272. package/node_modules/zod/v4/locales/zh-TW.d.ts +0 -4
@@ -0,0 +1,20 @@
1
+ // @bun
2
+ import{i,Q,No,l,e}from"./chunk-z637nqg8.js";import"./chunk-58wzr3mt.js";import{B}from"./chunk-yf7ympyz.js";import{Md,Nd,Is,_f,iy,bE,VK,tc,AJ,ZO,QO}from"./chunk-t6c8akcm.js";import{R}from"./chunk-r5bxavdx.js";import"./chunk-5d2hft6c.js";import"./chunk-4hw3665t.js";import{SQ,F4,wQ,RQ,L4,Kq,_0}from"./chunk-hrfytkxh.js";import"./chunk-v2wd4n3e.js";import{QZ}from"./chunk-ybbtagbt.js";import{jO,KO,GO}from"./chunk-8037tzzj.js";import"./chunk-284ptqa4.js";import{r,t}from"./chunk-rbpdk7m0.js";import{Nt,M,wt}from"./chunk-qcxzr2my.js";var ha=M(function(kl){kl.toString=function(s){switch(s){case 1:return"A";case 10:return"NULL";case 28:return"AAAA";case 18:return"AFSDB";case 42:return"APL";case 257:return"CAA";case 60:return"CDNSKEY";case 59:return"CDS";case 37:return"CERT";case 5:return"CNAME";case 49:return"DHCID";case 32769:return"DLV";case 39:return"DNAME";case 48:return"DNSKEY";case 43:return"DS";case 55:return"HIP";case 13:return"HINFO";case 45:return"IPSECKEY";case 25:return"KEY";case 36:return"KX";case 29:return"LOC";case 15:return"MX";case 35:return"NAPTR";case 2:return"NS";case 47:return"NSEC";case 50:return"NSEC3";case 51:return"NSEC3PARAM";case 12:return"PTR";case 46:return"RRSIG";case 17:return"RP";case 24:return"SIG";case 6:return"SOA";case 99:return"SPF";case 33:return"SRV";case 44:return"SSHFP";case 32768:return"TA";case 249:return"TKEY";case 52:return"TLSA";case 250:return"TSIG";case 16:return"TXT";case 252:return"AXFR";case 251:return"IXFR";case 41:return"OPT";case 255:return"ANY"}return"UNKNOWN_"+s};kl.toType=function(s){switch(s.toUpperCase()){case"A":return 1;case"NULL":return 10;case"AAAA":return 28;case"AFSDB":return 18;case"APL":return 42;case"CAA":return 257;case"CDNSKEY":return 60;case"CDS":return 59;case"CERT":return 37;case"CNAME":return 5;case"DHCID":return 49;case"DLV":return 32769;case"DNAME":return 39;case"DNSKEY":return 48;case"DS":return 43;case"HIP":return 55;case"HINFO":return 13;case"IPSECKEY":return 45;case"KEY":return 25;case"KX":return 36;case"LOC":return 29;case"MX":return 15;case"NAPTR":return 35;case"NS":return 2;case"NSEC":return 47;case"NSEC3":return 50;case"NSEC3PARAM":return 51;case"PTR":return 12;case"RRSIG":return 46;case"RP":return 17;case"SIG":return 24;case"SOA":return 6;case"SPF":return 99;case"SRV":return 33;case"SSHFP":return 44;case"TA":return 32768;case"TKEY":return 249;case"TLSA":return 52;case"TSIG":return 250;case"TXT":return 16;case"AXFR":return 252;case"IXFR":return 251;case"OPT":return 41;case"ANY":return 255;case"*":return 255}if(s.toUpperCase().startsWith("UNKNOWN_"))return parseInt(s.slice(8));return 0}});var la=M(function(xl){xl.toString=function(s){switch(s){case 0:return"NOERROR";case 1:return"FORMERR";case 2:return"SERVFAIL";case 3:return"NXDOMAIN";case 4:return"NOTIMP";case 5:return"REFUSED";case 6:return"YXDOMAIN";case 7:return"YXRRSET";case 8:return"NXRRSET";case 9:return"NOTAUTH";case 10:return"NOTZONE";case 11:return"RCODE_11";case 12:return"RCODE_12";case 13:return"RCODE_13";case 14:return"RCODE_14";case 15:return"RCODE_15"}return"RCODE_"+s};xl.toRcode=function(s){switch(s.toUpperCase()){case"NOERROR":return 0;case"FORMERR":return 1;case"SERVFAIL":return 2;case"NXDOMAIN":return 3;case"NOTIMP":return 4;case"REFUSED":return 5;case"YXDOMAIN":return 6;case"YXRRSET":return 7;case"NXRRSET":return 8;case"NOTAUTH":return 9;case"NOTZONE":return 10;case"RCODE_11":return 11;case"RCODE_12":return 12;case"RCODE_13":return 13;case"RCODE_14":return 14;case"RCODE_15":return 15}return 0}});var ua=M(function(Bl){Bl.toString=function(s){switch(s){case 0:return"QUERY";case 1:return"IQUERY";case 2:return"STATUS";case 3:return"OPCODE_3";case 4:return"NOTIFY";case 5:return"UPDATE";case 6:return"OPCODE_6";case 7:return"OPCODE_7";case 8:return"OPCODE_8";case 9:return"OPCODE_9";case 10:return"OPCODE_10";case 11:return"OPCODE_11";case 12:return"OPCODE_12";case 13:return"OPCODE_13";case 14:return"OPCODE_14";case 15:return"OPCODE_15"}return"OPCODE_"+s};Bl.toOpcode=function(s){switch(s.toUpperCase()){case"QUERY":return 0;case"IQUERY":return 1;case"STATUS":return 2;case"OPCODE_3":return 3;case"NOTIFY":return 4;case"UPDATE":return 5;case"OPCODE_6":return 6;case"OPCODE_7":return 7;case"OPCODE_8":return 8;case"OPCODE_9":return 9;case"OPCODE_10":return 10;case"OPCODE_11":return 11;case"OPCODE_12":return 12;case"OPCODE_13":return 13;case"OPCODE_14":return 14;case"OPCODE_15":return 15}return 0}});var pa=M(function(Ul){Ul.toString=function(s){switch(s){case 1:return"IN";case 2:return"CS";case 3:return"CH";case 4:return"HS";case 255:return"ANY"}return"UNKNOWN_"+s};Ul.toClass=function(s){switch(s.toUpperCase()){case"IN":return 1;case"CS":return 2;case"CH":return 3;case"HS":return 4;case"ANY":return 255}return 0}});var fa=M(function(Hl){Hl.toString=function(s){switch(s){case 1:return"LLQ";case 2:return"UL";case 3:return"NSID";case 5:return"DAU";case 6:return"DHU";case 7:return"N3U";case 8:return"CLIENT_SUBNET";case 9:return"EXPIRE";case 10:return"COOKIE";case 11:return"TCP_KEEPALIVE";case 12:return"PADDING";case 13:return"CHAIN";case 14:return"KEY_TAG";case 26946:return"DEVICEID"}if(s<0)return null;return`OPTION_${s}`};Hl.toCode=function(s){if(typeof s==="number")return s;if(!s)return-1;switch(s.toUpperCase()){case"OPTION_0":return 0;case"LLQ":return 1;case"UL":return 2;case"NSID":return 3;case"OPTION_4":return 4;case"DAU":return 5;case"DHU":return 6;case"N3U":return 7;case"CLIENT_SUBNET":return 8;case"EXPIRE":return 9;case"COOKIE":return 10;case"TCP_KEEPALIVE":return 11;case"PADDING":return 12;case"CHAIN":return 13;case"KEY_TAG":return 14;case"DEVICEID":return 26946;case"OPTION_65535":return 65535}let n=s.match(/_(\d+)$/);if(n)return parseInt(n[1],10);return-1}});var ya=M(function(ga,mi){var ma=function(s){Object.defineProperty(s,"__esModule",{value:!0}),s.decode=y,s.encode=m,s.familyOf=f,s.name=void 0,s.sizeOf=p,s.v6=s.v4=void 0;let n=/^(\d{1,3}\.){3,3}\d{1,3}$/,a=4,o=/^(::)?(((\d{1,3}\.){3}(\d{1,3}){1})?([0-9a-f]){0,4}:{0,2}){1,8}(::)?$/i,c=16,d={name:"v4",size:a,isFormat:(S)=>n.test(S),encode(S,v,g){g=~~g,v=v||new Uint8Array(g+a);let w=S.length,T=0;for(let b=0;b<w;){let C=S.charCodeAt(b++);if(C===46)v[g++]=T,T=0;else T=T*10+(C-48)}return v[g]=T,v},decode(S,v){return v=~~v,`${S[v++]}.${S[v++]}.${S[v++]}.${S[v]}`}};s.v4=d;let h={name:"v6",size:c,isFormat:(S)=>S.length>0&&o.test(S),encode(S,v,g){g=~~g;let w=g+c,T=-1,b=0,C=0,P=!0,x=!1;v=v||new Uint8Array(g+c);for(let H=0;H<S.length;H++){let O=S.charCodeAt(H);if(O===58){if(P){if(T!==-1){if(g<w)v[g]=0;if(g<w-1)v[g+1]=0;g+=2}else if(g<w)T=g}else{if(x===!0){if(g<w)v[g]=C;g++}else{if(g<w)v[g]=b>>8;if(g<w-1)v[g+1]=b&255;g+=2}b=0,C=0}P=!0,x=!1}else if(O===46){if(g<w)v[g]=C;g++,C=0,b=0,P=!1,x=!0}else{if(P=!1,O>=97)O-=87;else if(O>=65)O-=55;else O-=48,C=C*10+O;b=(b<<4)+O}}if(P===!1)if(x===!0){if(g<w)v[g]=C;g++}else{if(g<w)v[g]=b>>8;if(g<w-1)v[g+1]=b&255;g+=2}else if(T===0){if(g<w)v[g]=0;if(g<w-1)v[g+1]=0;g+=2}else if(T!==-1){g+=2;for(let H=Math.min(g-1,w-1);H>=T+2;H--)v[H]=v[H-2];v[T]=0,v[T+1]=0,T=g}if(T!==g&&T!==-1){if(g>w-2)g=w-2;while(w>T)v[--w]=g<w&&g>T?v[--g]:0}else while(g<w)v[g++]=0;return v},decode(S,v){v=~~v;let g="";for(let w=0;w<c;w+=2){if(w!==0)g+=":";g+=(S[v+w]<<8|S[v+w+1]).toString(16)}return g.replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}};s.v6=h;let u="ip";s.name=u;function p(S){if(d.isFormat(S))return d.size;if(h.isFormat(S))return h.size;throw Error(`Invalid ip address: ${S}`)}function f(S){return p(S)===d.size?1:2}function m(S,v,g){g=~~g;let w=p(S);if(typeof v==="function")v=v(g+w);if(w===d.size)return d.encode(S,v,g);return h.encode(S,v,g)}function y(S,v,g){if(v=~~v,g=g||S.length-v,g===d.size)return d.decode(S,v,g);if(g===h.size)return h.decode(S,v,g);throw Error(`Invalid buffer size needs to be ${d.size} for v4 or ${h.size} for v6.`)}return"default"in s?s.default:s}({});if(typeof define==="function"&&define.amd)define([],function(){return ma});else if(typeof mi==="object"&&typeof ga==="object")mi.exports=ma});var wa=M(function(sr){var k=wt("buffer").Buffer,Y=ha(),Sa=la(),va=ua(),nt=pa(),xt=fa(),ie=ya(),I=sr.name={};I.encode=function(s,n,a,{mail:o=!1}={}){if(!n)n=k.alloc(I.encodingLength(s));if(!a)a=0;let c=a,d=s.replace(/^\.|\.$/gm,"");if(d.length){let h=[];if(o){let u="";d.split(".").forEach((p)=>{if(p.endsWith("\\"))u+=(u.length?".":"")+p.slice(0,-1);else if(h.length===0&&u.length)h.push(u+"."+p);else h.push(p)})}else h=d.split(".");for(let u=0;u<h.length;u++){let p=n.write(h[u],a+1);n[a]=p,a+=p+1}}return n[a++]=0,I.encode.bytes=a-c,n};I.encode.bytes=0;I.decode=function(s,n,{mail:a=!1}={}){if(!n)n=0;let o=[],c=n,d=0,h=0,u=!1;while(!0){if(n>=s.length)throw Error("Cannot decode name (buffer overflow)");let p=s[n++];if(h+=u?0:1,p===0)break;else if((p&192)===0){if(n+p>s.length)throw Error("Cannot decode name (buffer overflow)");if(d+=p+1,d>254)throw Error("Cannot decode name (name too long)");let f=s.toString("utf-8",n,n+p);if(a)f=f.replace(/\./g,"\\.");o.push(f),n+=p,h+=u?0:p}else if((p&192)===192){if(n+1>s.length)throw Error("Cannot decode name (buffer overflow)");let f=s.readUInt16BE(n-1)-49152;if(f>=c)throw Error("Cannot decode name (bad pointer)");n=f,c=f,h+=u?0:1,u=!0}else throw Error("Cannot decode name (bad label)")}return I.decode.bytes=h,o.length===0?".":o.join(".")};I.decode.bytes=0;I.encodingLength=function(s){if(s==="."||s==="..")return 1;return k.byteLength(s.replace(/^\.|\.$/gm,""))+2};var L={};L.encode=function(s,n,a){if(!n)n=k.alloc(L.encodingLength(s));if(!a)a=0;let o=n.write(s,a+1);return n[a]=o,L.encode.bytes=o+1,n};L.encode.bytes=0;L.decode=function(s,n){if(!n)n=0;let a=s[n],o=s.toString("utf-8",n+1,n+1+a);return L.decode.bytes=a+1,o};L.decode.bytes=0;L.encodingLength=function(s){return k.byteLength(s)+1};var ve={};ve.encode=function(s,n,a){if(!n)n=ve.encodingLength(s);if(!a)a=0;let o=(s.flags||0)&32767,c=s.type==="response"?32768:0;return n.writeUInt16BE(s.id||0,a),n.writeUInt16BE(o|c,a+2),n.writeUInt16BE(s.questions.length,a+4),n.writeUInt16BE(s.answers.length,a+6),n.writeUInt16BE(s.authorities.length,a+8),n.writeUInt16BE(s.additionals.length,a+10),n};ve.encode.bytes=12;ve.decode=function(s,n){if(!n)n=0;if(s.length<12)throw Error("Header must be 12 bytes");let a=s.readUInt16BE(n+2);return{id:s.readUInt16BE(n),type:a&32768?"response":"query",flags:a&32767,flag_qr:(a>>15&1)===1,opcode:va.toString(a>>11&15),flag_aa:(a>>10&1)===1,flag_tc:(a>>9&1)===1,flag_rd:(a>>8&1)===1,flag_ra:(a>>7&1)===1,flag_z:(a>>6&1)===1,flag_ad:(a>>5&1)===1,flag_cd:(a>>4&1)===1,rcode:Sa.toString(a&15),questions:Array(s.readUInt16BE(n+4)),answers:Array(s.readUInt16BE(n+6)),authorities:Array(s.readUInt16BE(n+8)),additionals:Array(s.readUInt16BE(n+10))}};ve.decode.bytes=12;ve.encodingLength=function(){return 12};var Fe=sr.unknown={};Fe.encode=function(s,n,a){if(!n)n=k.alloc(Fe.encodingLength(s));if(!a)a=0;return n.writeUInt16BE(s.length,a),s.copy(n,a+2),Fe.encode.bytes=s.length+2,n};Fe.encode.bytes=0;Fe.decode=function(s,n){if(!n)n=0;let a=s.readUInt16BE(n),o=s.slice(n+2,n+2+a);return Fe.decode.bytes=a+2,o};Fe.decode.bytes=0;Fe.encodingLength=function(s){return s.length+2};var ze=sr.ns={};ze.encode=function(s,n,a){if(!n)n=k.alloc(ze.encodingLength(s));if(!a)a=0;return I.encode(s,n,a+2),n.writeUInt16BE(I.encode.bytes,a),ze.encode.bytes=I.encode.bytes+2,n};ze.encode.bytes=0;ze.decode=function(s,n){if(!n)n=0;let a=s.readUInt16BE(n),o=I.decode(s,n+2);return ze.decode.bytes=a+2,o};ze.decode.bytes=0;ze.encodingLength=function(s){return I.encodingLength(s)+2};var qe=sr.soa={};qe.encode=function(s,n,a){if(!n)n=k.alloc(qe.encodingLength(s));if(!a)a=0;let o=a;return a+=2,I.encode(s.mname,n,a),a+=I.encode.bytes,I.encode(s.rname,n,a,{mail:!0}),a+=I.encode.bytes,n.writeUInt32BE(s.serial||0,a),a+=4,n.writeUInt32BE(s.refresh||0,a),a+=4,n.writeUInt32BE(s.retry||0,a),a+=4,n.writeUInt32BE(s.expire||0,a),a+=4,n.writeUInt32BE(s.minimum||0,a),a+=4,n.writeUInt16BE(a-o-2,o),qe.encode.bytes=a-o,n};qe.encode.bytes=0;qe.decode=function(s,n){if(!n)n=0;let a=n,o={};return n+=2,o.mname=I.decode(s,n),n+=I.decode.bytes,o.rname=I.decode(s,n,{mail:!0}),n+=I.decode.bytes,o.serial=s.readUInt32BE(n),n+=4,o.refresh=s.readUInt32BE(n),n+=4,o.retry=s.readUInt32BE(n),n+=4,o.expire=s.readUInt32BE(n),n+=4,o.minimum=s.readUInt32BE(n),n+=4,qe.decode.bytes=n-a,o};qe.decode.bytes=0;qe.encodingLength=function(s){return 22+I.encodingLength(s.mname)+I.encodingLength(s.rname)};var We=sr.txt={};We.encode=function(s,n,a){if(!Array.isArray(s))s=[s];for(let c=0;c<s.length;c++){if(typeof s[c]==="string")s[c]=k.from(s[c]);if(!k.isBuffer(s[c]))throw Error("Must be a Buffer")}if(!n)n=k.alloc(We.encodingLength(s));if(!a)a=0;let o=a;return a+=2,s.forEach(function(c){n[a++]=c.length,c.copy(n,a,0,c.length),a+=c.length}),n.writeUInt16BE(a-o-2,o),We.encode.bytes=a-o,n};We.encode.bytes=0;We.decode=function(s,n){if(!n)n=0;let a=n,o=s.readUInt16BE(n);n+=2;let c=[];while(o>0){let d=s[n++];if(--o,o<d)throw Error("Buffer overflow");c.push(s.slice(n,n+d)),n+=d,o-=d}return We.decode.bytes=n-a,c};We.decode.bytes=0;We.encodingLength=function(s){if(!Array.isArray(s))s=[s];let n=2;return s.forEach(function(a){if(typeof a==="string")n+=k.byteLength(a)+1;else n+=a.length+1}),n};var Ke=sr.null={};Ke.encode=function(s,n,a){if(!n)n=k.alloc(Ke.encodingLength(s));if(!a)a=0;if(typeof s==="string")s=k.from(s);if(!s)s=k.alloc(0);let o=a;a+=2;let c=s.length;return s.copy(n,a,0,c),a+=c,n.writeUInt16BE(a-o-2,o),Ke.encode.bytes=a-o,n};Ke.encode.bytes=0;Ke.decode=function(s,n){if(!n)n=0;let a=n,o=s.readUInt16BE(n);n+=2;let c=s.slice(n,n+o);return n+=o,Ke.decode.bytes=n-a,c};Ke.decode.bytes=0;Ke.encodingLength=function(s){if(!s)return 2;return(k.isBuffer(s)?s.length:k.byteLength(s))+2};var $e=sr.hinfo={};$e.encode=function(s,n,a){if(!n)n=k.alloc($e.encodingLength(s));if(!a)a=0;let o=a;return a+=2,L.encode(s.cpu,n,a),a+=L.encode.bytes,L.encode(s.os,n,a),a+=L.encode.bytes,n.writeUInt16BE(a-o-2,o),$e.encode.bytes=a-o,n};$e.encode.bytes=0;$e.decode=function(s,n){if(!n)n=0;let a=n,o={};return n+=2,o.cpu=L.decode(s,n),n+=L.decode.bytes,o.os=L.decode(s,n),n+=L.decode.bytes,$e.decode.bytes=n-a,o};$e.decode.bytes=0;$e.encodingLength=function(s){return L.encodingLength(s.cpu)+L.encodingLength(s.os)+2};var ye=sr.ptr={},ql=sr.cname=ye,Wl=sr.dname=ye;ye.encode=function(s,n,a){if(!n)n=k.alloc(ye.encodingLength(s));if(!a)a=0;return I.encode(s,n,a+2),n.writeUInt16BE(I.encode.bytes,a),ye.encode.bytes=I.encode.bytes+2,n};ye.encode.bytes=0;ye.decode=function(s,n){if(!n)n=0;let a=I.decode(s,n+2);return ye.decode.bytes=I.decode.bytes+2,a};ye.decode.bytes=0;ye.encodingLength=function(s){return I.encodingLength(s)+2};var Ge=sr.srv={};Ge.encode=function(s,n,a){if(!n)n=k.alloc(Ge.encodingLength(s));if(!a)a=0;n.writeUInt16BE(s.priority||0,a+2),n.writeUInt16BE(s.weight||0,a+4),n.writeUInt16BE(s.port||0,a+6),I.encode(s.target,n,a+8);let o=I.encode.bytes+6;return n.writeUInt16BE(o,a),Ge.encode.bytes=o+2,n};Ge.encode.bytes=0;Ge.decode=function(s,n){if(!n)n=0;let a=s.readUInt16BE(n),o={};return o.priority=s.readUInt16BE(n+2),o.weight=s.readUInt16BE(n+4),o.port=s.readUInt16BE(n+6),o.target=I.decode(s,n+8),Ge.decode.bytes=a+2,o};Ge.decode.bytes=0;Ge.encodingLength=function(s){return 8+I.encodingLength(s.target)};var ce=sr.caa={};ce.ISSUER_CRITICAL=128;ce.encode=function(s,n,a){let o=ce.encodingLength(s);if(!n)n=k.alloc(ce.encodingLength(s));if(!a)a=0;if(s.issuerCritical)s.flags=ce.ISSUER_CRITICAL;return n.writeUInt16BE(o-2,a),a+=2,n.writeUInt8(s.flags||0,a),a+=1,L.encode(s.tag,n,a),a+=L.encode.bytes,n.write(s.value,a),a+=k.byteLength(s.value),ce.encode.bytes=o,n};ce.encode.bytes=0;ce.decode=function(s,n){if(!n)n=0;let a=s.readUInt16BE(n);n+=2;let o=n,c={};return c.flags=s.readUInt8(n),n+=1,c.tag=L.decode(s,n),n+=L.decode.bytes,c.value=s.toString("utf-8",n,o+a),c.issuerCritical=!!(c.flags&ce.ISSUER_CRITICAL),ce.decode.bytes=a+2,c};ce.decode.bytes=0;ce.encodingLength=function(s){return L.encodingLength(s.tag)+L.encodingLength(s.value)+2};var it=sr.mx={};it.encode=function(s,n,a){if(!n)n=k.alloc(it.encodingLength(s));if(!a)a=0;let o=a;return a+=2,n.writeUInt16BE(s.preference||0,a),a+=2,I.encode(s.exchange,n,a),a+=I.encode.bytes,n.writeUInt16BE(a-o-2,o),it.encode.bytes=a-o,n};it.encode.bytes=0;it.decode=function(s,n){if(!n)n=0;let a=n,o={};return n+=2,o.preference=s.readUInt16BE(n),n+=2,o.exchange=I.decode(s,n),n+=I.decode.bytes,it.decode.bytes=n-a,o};it.encodingLength=function(s){return 4+I.encodingLength(s.exchange)};var je=sr.a={};je.encode=function(s,n,a){if(!n)n=k.alloc(je.encodingLength(s));if(!a)a=0;return n.writeUInt16BE(4,a),a+=2,ie.v4.encode(s,n,a),je.encode.bytes=6,n};je.encode.bytes=0;je.decode=function(s,n){if(!n)n=0;n+=2;let a=ie.v4.decode(s,n);return je.decode.bytes=6,a};je.decode.bytes=0;je.encodingLength=function(){return 6};var Ve=sr.aaaa={};Ve.encode=function(s,n,a){if(!n)n=k.alloc(Ve.encodingLength(s));if(!a)a=0;return n.writeUInt16BE(16,a),a+=2,ie.v6.encode(s,n,a),Ve.encode.bytes=18,n};Ve.encode.bytes=0;Ve.decode=function(s,n){if(!n)n=0;n+=2;let a=ie.v6.decode(s,n);return Ve.decode.bytes=18,a};Ve.decode.bytes=0;Ve.encodingLength=function(){return 18};var re=sr.option={};re.encode=function(s,n,a){if(!n)n=k.alloc(re.encodingLength(s));if(!a)a=0;let o=a,c=xt.toCode(s.code);if(n.writeUInt16BE(c,a),a+=2,s.data)n.writeUInt16BE(s.data.length,a),a+=2,s.data.copy(n,a),a+=s.data.length;else switch(c){case 8:let d=s.sourcePrefixLength||0,h=s.family||ie.familyOf(s.ip),u=ie.encode(s.ip,k.alloc),p=Math.ceil(d/8);n.writeUInt16BE(p+4,a),a+=2,n.writeUInt16BE(h,a),a+=2,n.writeUInt8(d,a++),n.writeUInt8(s.scopePrefixLength||0,a++),u.copy(n,a,0,p),a+=p;break;case 11:if(s.timeout)n.writeUInt16BE(2,a),a+=2,n.writeUInt16BE(s.timeout,a),a+=2;else n.writeUInt16BE(0,a),a+=2;break;case 12:let f=s.length||0;n.writeUInt16BE(f,a),a+=2,n.fill(0,a,a+f),a+=f;break;case 14:let m=s.tags.length*2;n.writeUInt16BE(m,a),a+=2;for(let y of s.tags)n.writeUInt16BE(y,a),a+=2;break;default:throw Error(`Unknown roption code: ${s.code}`)}return re.encode.bytes=a-o,n};re.encode.bytes=0;re.decode=function(s,n){if(!n)n=0;let a={};a.code=s.readUInt16BE(n),a.type=xt.toString(a.code),n+=2;let o=s.readUInt16BE(n);switch(n+=2,a.data=s.slice(n,n+o),a.code){case 8:a.family=s.readUInt16BE(n),n+=2,a.sourcePrefixLength=s.readUInt8(n++),a.scopePrefixLength=s.readUInt8(n++);let c=k.alloc(a.family===1?4:16);s.copy(c,0,n,n+o-4),a.ip=ie.decode(c);break;case 11:if(o>0)a.timeout=s.readUInt16BE(n),n+=2;break;case 14:a.tags=[];for(let d=0;d<o;d+=2)a.tags.push(s.readUInt16BE(n)),n+=2}return re.decode.bytes=o+4,a};re.decode.bytes=0;re.encodingLength=function(s){if(s.data)return s.data.length+4;switch(xt.toCode(s.code)){case 8:let a=s.sourcePrefixLength||0;return Math.ceil(a/8)+8;case 11:return typeof s.timeout==="number"?6:4;case 12:return s.length+4;case 14:return 4+s.tags.length*2}throw Error(`Unknown roption code: ${s.code}`)};var he=sr.opt={};he.encode=function(s,n,a){if(!n)n=k.alloc(he.encodingLength(s));if(!a)a=0;let o=a,c=Pt(s,re);return n.writeUInt16BE(c,a),a=os(s,re,n,a+2),he.encode.bytes=a-o,n};he.encode.bytes=0;he.decode=function(s,n){if(!n)n=0;let a=n,o=[],c=s.readUInt16BE(n);n+=2;let d=0;while(c>0)o[d++]=re.decode(s,n),n+=re.decode.bytes,c-=re.decode.bytes;return he.decode.bytes=n-a,o};he.decode.bytes=0;he.encodingLength=function(s){return 2+Pt(s||[],re)};var te=sr.dnskey={};te.PROTOCOL_DNSSEC=3;te.ZONE_KEY=128;te.SECURE_ENTRYPOINT=32768;te.encode=function(s,n,a){if(!n)n=k.alloc(te.encodingLength(s));if(!a)a=0;let o=a,c=s.key;if(!k.isBuffer(c))throw Error("Key must be a Buffer");return a+=2,n.writeUInt16BE(s.flags,a),a+=2,n.writeUInt8(te.PROTOCOL_DNSSEC,a),a+=1,n.writeUInt8(s.algorithm,a),a+=1,c.copy(n,a,0,c.length),a+=c.length,te.encode.bytes=a-o,n.writeUInt16BE(te.encode.bytes-2,o),n};te.encode.bytes=0;te.decode=function(s,n){if(!n)n=0;let a=n;var o={},c=s.readUInt16BE(n);if(n+=2,o.flags=s.readUInt16BE(n),n+=2,s.readUInt8(n)!==te.PROTOCOL_DNSSEC)throw Error("Protocol must be 3");return n+=1,o.algorithm=s.readUInt8(n),n+=1,o.key=s.slice(n,a+c+2),n+=o.key.length,te.decode.bytes=n-a,o};te.decode.bytes=0;te.encodingLength=function(s){return 6+k.byteLength(s.key)};var Ee=sr.rrsig={};Ee.encode=function(s,n,a){if(!n)n=k.alloc(Ee.encodingLength(s));if(!a)a=0;let o=a,c=s.signature;if(!k.isBuffer(c))throw Error("Signature must be a Buffer");return a+=2,n.writeUInt16BE(Y.toType(s.typeCovered),a),a+=2,n.writeUInt8(s.algorithm,a),a+=1,n.writeUInt8(s.labels,a),a+=1,n.writeUInt32BE(s.originalTTL,a),a+=4,n.writeUInt32BE(s.expiration,a),a+=4,n.writeUInt32BE(s.inception,a),a+=4,n.writeUInt16BE(s.keyTag,a),a+=2,I.encode(s.signersName,n,a),a+=I.encode.bytes,c.copy(n,a,0,c.length),a+=c.length,Ee.encode.bytes=a-o,n.writeUInt16BE(Ee.encode.bytes-2,o),n};Ee.encode.bytes=0;Ee.decode=function(s,n){if(!n)n=0;let a=n;var o={},c=s.readUInt16BE(n);return n+=2,o.typeCovered=Y.toString(s.readUInt16BE(n)),n+=2,o.algorithm=s.readUInt8(n),n+=1,o.labels=s.readUInt8(n),n+=1,o.originalTTL=s.readUInt32BE(n),n+=4,o.expiration=s.readUInt32BE(n),n+=4,o.inception=s.readUInt32BE(n),n+=4,o.keyTag=s.readUInt16BE(n),n+=2,o.signersName=I.decode(s,n),n+=I.decode.bytes,o.signature=s.slice(n,a+c+2),n+=o.signature.length,Ee.decode.bytes=n-a,o};Ee.decode.bytes=0;Ee.encodingLength=function(s){return 20+I.encodingLength(s.signersName)+k.byteLength(s.signature)};var Ie=sr.rp={};Ie.encode=function(s,n,a){if(!n)n=k.alloc(Ie.encodingLength(s));if(!a)a=0;let o=a;return a+=2,I.encode(s.mbox||".",n,a,{mail:!0}),a+=I.encode.bytes,I.encode(s.txt||".",n,a),a+=I.encode.bytes,Ie.encode.bytes=a-o,n.writeUInt16BE(Ie.encode.bytes-2,o),n};Ie.encode.bytes=0;Ie.decode=function(s,n){if(!n)n=0;let a=n,o={};return n+=2,o.mbox=I.decode(s,n,{mail:!0})||".",n+=I.decode.bytes,o.txt=I.decode(s,n)||".",n+=I.decode.bytes,Ie.decode.bytes=n-a,o};Ie.decode.bytes=0;Ie.encodingLength=function(s){return 2+I.encodingLength(s.mbox||".")+I.encodingLength(s.txt||".")};var V={};V.encode=function(s,n,a){if(!n)n=k.alloc(V.encodingLength(s));if(!a)a=0;let o=a;var c=[];for(var d=0;d<s.length;d++){var h=Y.toType(s[d]);if(c[h>>8]===void 0)c[h>>8]=[];c[h>>8][h>>3&31]|=1<<7-(h&7)}for(d=0;d<c.length;d++)if(c[d]!==void 0){var u=k.from(c[d]);n.writeUInt8(d,a),a+=1,n.writeUInt8(u.length,a),a+=1,u.copy(n,a),a+=u.length}return V.encode.bytes=a-o,n};V.encode.bytes=0;V.decode=function(s,n,a){if(!n)n=0;let o=n;var c=[];while(n-o<a){var d=s.readUInt8(n);n+=1;var h=s.readUInt8(n);n+=1;for(var u=0;u<h;u++){var p=s.readUInt8(n+u);for(var f=0;f<8;f++)if(p&1<<7-f){var m=Y.toString(d<<8|u<<3|f);c.push(m)}}n+=h}return V.decode.bytes=n-o,c};V.decode.bytes=0;V.encodingLength=function(s){var n=[];for(var a=0;a<s.length;a++){var o=Y.toType(s[a]);n[o>>8]=Math.max(n[o>>8]||0,o&255)}var c=0;for(a=0;a<n.length;a++)if(n[a]!==void 0)c+=2+Math.ceil((n[a]+1)/8);return c};var ke=sr.nsec={};ke.encode=function(s,n,a){if(!n)n=k.alloc(ke.encodingLength(s));if(!a)a=0;let o=a;return a+=2,I.encode(s.nextDomain,n,a),a+=I.encode.bytes,V.encode(s.rrtypes,n,a),a+=V.encode.bytes,ke.encode.bytes=a-o,n.writeUInt16BE(ke.encode.bytes-2,o),n};ke.encode.bytes=0;ke.decode=function(s,n){if(!n)n=0;let a=n;var o={},c=s.readUInt16BE(n);return n+=2,o.nextDomain=I.decode(s,n),n+=I.decode.bytes,o.rrtypes=V.decode(s,n,c-(n-a)),n+=V.decode.bytes,ke.decode.bytes=n-a,o};ke.decode.bytes=0;ke.encodingLength=function(s){return 2+I.encodingLength(s.nextDomain)+V.encodingLength(s.rrtypes)};var Pe=sr.nsec3={};Pe.encode=function(s,n,a){if(!n)n=k.alloc(Pe.encodingLength(s));if(!a)a=0;let o=a,c=s.salt;if(!k.isBuffer(c))throw Error("salt must be a Buffer");let d=s.nextDomain;if(!k.isBuffer(d))throw Error("nextDomain must be a Buffer");return a+=2,n.writeUInt8(s.algorithm,a),a+=1,n.writeUInt8(s.flags,a),a+=1,n.writeUInt16BE(s.iterations,a),a+=2,n.writeUInt8(c.length,a),a+=1,c.copy(n,a,0,c.length),a+=c.length,n.writeUInt8(d.length,a),a+=1,d.copy(n,a,0,d.length),a+=d.length,V.encode(s.rrtypes,n,a),a+=V.encode.bytes,Pe.encode.bytes=a-o,n.writeUInt16BE(Pe.encode.bytes-2,o),n};Pe.encode.bytes=0;Pe.decode=function(s,n){if(!n)n=0;let a=n;var o={},c=s.readUInt16BE(n);n+=2,o.algorithm=s.readUInt8(n),n+=1,o.flags=s.readUInt8(n),n+=1,o.iterations=s.readUInt16BE(n),n+=2;let d=s.readUInt8(n);n+=1,o.salt=s.slice(n,n+d),n+=d;let h=s.readUInt8(n);return n+=1,o.nextDomain=s.slice(n,n+h),n+=h,o.rrtypes=V.decode(s,n,c-(n-a)),n+=V.decode.bytes,Pe.decode.bytes=n-a,o};Pe.decode.bytes=0;Pe.encodingLength=function(s){return 8+s.salt.length+s.nextDomain.length+V.encodingLength(s.rrtypes)};var Ae=sr.ds={};Ae.encode=function(s,n,a){if(!n)n=k.alloc(Ae.encodingLength(s));if(!a)a=0;let o=a,c=s.digest;if(!k.isBuffer(c))throw Error("Digest must be a Buffer");return a+=2,n.writeUInt16BE(s.keyTag,a),a+=2,n.writeUInt8(s.algorithm,a),a+=1,n.writeUInt8(s.digestType,a),a+=1,c.copy(n,a,0,c.length),a+=c.length,Ae.encode.bytes=a-o,n.writeUInt16BE(Ae.encode.bytes-2,o),n};Ae.encode.bytes=0;Ae.decode=function(s,n){if(!n)n=0;let a=n;var o={},c=s.readUInt16BE(n);return n+=2,o.keyTag=s.readUInt16BE(n),n+=2,o.algorithm=s.readUInt8(n),n+=1,o.digestType=s.readUInt8(n),n+=1,o.digest=s.slice(n,a+c+2),n+=o.digest.length,Ae.decode.bytes=n-a,o};Ae.decode.bytes=0;Ae.encodingLength=function(s){return 6+k.byteLength(s.digest)};var de=sr.sshfp={};de.getFingerprintLengthForHashType=function(n){switch(n){case 1:return 20;case 2:return 32}};de.encode=function(n,a,o){if(!a)a=k.alloc(de.encodingLength(n));if(!o)o=0;let c=o;o+=2,a[o]=n.algorithm,o+=1,a[o]=n.hash,o+=1;let d=k.from(n.fingerprint.toUpperCase(),"hex");if(d.length!==de.getFingerprintLengthForHashType(n.hash))throw Error("Invalid fingerprint length");return d.copy(a,o),o+=d.byteLength,de.encode.bytes=o-c,a.writeUInt16BE(de.encode.bytes-2,c),a};de.encode.bytes=0;de.decode=function(n,a){if(!a)a=0;let o=a,c={};a+=2,c.algorithm=n[a],a+=1,c.hash=n[a],a+=1;let d=de.getFingerprintLengthForHashType(c.hash);return c.fingerprint=n.slice(a,a+d).toString("hex").toUpperCase(),a+=d,de.decode.bytes=a-o,c};de.decode.bytes=0;de.encodingLength=function(s){return 4+k.from(s.fingerprint,"hex").byteLength};var xe=sr.naptr={};xe.encode=function(s,n,a){if(!n)n=k.alloc(xe.encodingLength(s));if(!a)a=0;let o=a;return a+=2,n.writeUInt16BE(s.order||0,a),a+=2,n.writeUInt16BE(s.preference||0,a),a+=2,L.encode(s.flags,n,a),a+=L.encode.bytes,L.encode(s.services,n,a),a+=L.encode.bytes,L.encode(s.regexp,n,a),a+=L.encode.bytes,I.encode(s.replacement,n,a),a+=I.encode.bytes,xe.encode.bytes=a-o,n.writeUInt16BE(xe.encode.bytes-2,o),n};xe.encode.bytes=0;xe.decode=function(s,n){if(!n)n=0;let a=n,o={};return n+=2,o.order=s.readUInt16BE(n),n+=2,o.preference=s.readUInt16BE(n),n+=2,o.flags=L.decode(s,n),n+=L.decode.bytes,o.services=L.decode(s,n),n+=L.decode.bytes,o.regexp=L.decode(s,n),n+=L.decode.bytes,o.replacement=I.decode(s,n),n+=I.decode.bytes,xe.decode.bytes=n-a,o};xe.decode.bytes=0;xe.encodingLength=function(s){return L.encodingLength(s.flags)+L.encodingLength(s.services)+L.encodingLength(s.regexp)+I.encodingLength(s.replacement)+6};var _e=sr.tlsa={};_e.encode=function(s,n,a){if(!n)n=k.alloc(_e.encodingLength(s));if(!a)a=0;let o=a,c=s.certificate;if(!k.isBuffer(c))throw Error("Certificate must be a Buffer");return a+=2,n.writeUInt8(s.usage,a),a+=1,n.writeUInt8(s.selector,a),a+=1,n.writeUInt8(s.matchingType,a),a+=1,c.copy(n,a,0,c.length),a+=c.length,_e.encode.bytes=a-o,n.writeUInt16BE(_e.encode.bytes-2,o),n};_e.encode.bytes=0;_e.decode=function(s,n){if(!n)n=0;let a=n,o={},c=s.readUInt16BE(n);return n+=2,o.usage=s.readUInt8(n),n+=1,o.selector=s.readUInt8(n),n+=1,o.matchingType=s.readUInt8(n),n+=1,o.certificate=s.slice(n,a+c+2),n+=o.certificate.length,_e.decode.bytes=n-a,o};_e.decode.bytes=0;_e.encodingLength=function(s){return 5+k.byteLength(s.certificate)};var Si=sr.record=function(s){switch(s.toUpperCase()){case"A":return je;case"PTR":return ye;case"CNAME":return ql;case"DNAME":return Wl;case"TXT":return We;case"NULL":return Ke;case"AAAA":return Ve;case"SRV":return Ge;case"HINFO":return $e;case"CAA":return ce;case"NS":return ze;case"SOA":return qe;case"MX":return it;case"OPT":return he;case"DNSKEY":return te;case"RRSIG":return Ee;case"RP":return Ie;case"NSEC":return ke;case"NSEC3":return Pe;case"SSHFP":return de;case"DS":return Ae;case"NAPTR":return xe;case"TLSA":return _e}return Fe},X=sr.answer={};X.encode=function(s,n,a){if(!n)n=k.alloc(X.encodingLength(s));if(!a)a=0;let o=a;if(I.encode(s.name,n,a),a+=I.encode.bytes,n.writeUInt16BE(Y.toType(s.type),a),s.type.toUpperCase()==="OPT"){if(s.name!==".")throw Error("OPT name must be root.");n.writeUInt16BE(s.udpPayloadSize||4096,a+2),n.writeUInt8(s.extendedRcode||0,a+4),n.writeUInt8(s.ednsVersion||0,a+5),n.writeUInt16BE(s.flags||0,a+6),a+=8,he.encode(s.options||[],n,a),a+=he.encode.bytes}else{let c=nt.toClass(s.class===void 0?"IN":s.class);if(s.flush)c|=32768;n.writeUInt16BE(c,a+2),n.writeUInt32BE(s.ttl||0,a+4),a+=8;let d=Si(s.type);d.encode(s.data,n,a),a+=d.encode.bytes}return X.encode.bytes=a-o,n};X.encode.bytes=0;X.decode=function(s,n){if(!n)n=0;let a={},o=n;if(a.name=I.decode(s,n),n+=I.decode.bytes,a.type=Y.toString(s.readUInt16BE(n)),a.type==="OPT")a.udpPayloadSize=s.readUInt16BE(n+2),a.extendedRcode=s.readUInt8(n+4),a.ednsVersion=s.readUInt8(n+5),a.flags=s.readUInt16BE(n+6),a.flag_do=(a.flags>>15&1)===1,a.options=he.decode(s,n+8),n+=8+he.decode.bytes;else{let c=s.readUInt16BE(n+2);a.ttl=s.readUInt32BE(n+4),a.class=nt.toString(c&-32769),a.flush=!!(c&32768);let d=Si(a.type);a.data=d.decode(s,n+8),n+=8+d.decode.bytes}return X.decode.bytes=n-o,a};X.decode.bytes=0;X.encodingLength=function(s){let n=s.data!==null&&s.data!==void 0?s.data:s.options;return I.encodingLength(s.name)+8+Si(s.type).encodingLength(n)};var Se=sr.question={};Se.encode=function(s,n,a){if(!n)n=k.alloc(Se.encodingLength(s));if(!a)a=0;let o=a;return I.encode(s.name,n,a),a+=I.encode.bytes,n.writeUInt16BE(Y.toType(s.type),a),a+=2,n.writeUInt16BE(nt.toClass(s.class===void 0?"IN":s.class),a),a+=2,Se.encode.bytes=a-o,s};Se.encode.bytes=0;Se.decode=function(s,n){if(!n)n=0;let a=n,o={};if(o.name=I.decode(s,n),n+=I.decode.bytes,o.type=Y.toString(s.readUInt16BE(n)),n+=2,o.class=nt.toString(s.readUInt16BE(n)),n+=2,!!(o.class&32768))o.class&=-32769;return Se.decode.bytes=n-a,o};Se.decode.bytes=0;Se.encodingLength=function(s){return I.encodingLength(s.name)+4};sr.AUTHORITATIVE_ANSWER=1024;sr.TRUNCATED_RESPONSE=512;sr.RECURSION_DESIRED=256;sr.RECURSION_AVAILABLE=128;sr.AUTHENTIC_DATA=32;sr.CHECKING_DISABLED=16;sr.DNSSEC_OK=32768;sr.encode=function(s,n,a){let o=!n;if(o)n=k.alloc(sr.encodingLength(s));if(!a)a=0;let c=a;if(!s.questions)s.questions=[];if(!s.answers)s.answers=[];if(!s.authorities)s.authorities=[];if(!s.additionals)s.additionals=[];if(ve.encode(s,n,a),a+=ve.encode.bytes,a=os(s.questions,Se,n,a),a=os(s.answers,X,n,a),a=os(s.authorities,X,n,a),a=os(s.additionals,X,n,a),sr.encode.bytes=a-c,o&&sr.encode.bytes!==n.length)return n.slice(0,sr.encode.bytes);return n};sr.encode.bytes=0;sr.decode=function(s,n){if(!n)n=0;let a=n,o=ve.decode(s,n);return n+=ve.decode.bytes,n=tr(o.questions,Se,s,n),n=tr(o.answers,X,s,n),n=tr(o.authorities,X,s,n),n=tr(o.additionals,X,s,n),sr.decode.bytes=n-a,o};sr.decode.bytes=0;sr.encodingLength=function(s){return ve.encodingLength(s)+Pt(s.questions||[],Se)+Pt(s.answers||[],X)+Pt(s.authorities||[],X)+Pt(s.additionals||[],X)};sr.streamEncode=function(s){let n=sr.encode(s),a=k.alloc(2);a.writeUInt16BE(n.byteLength);let o=k.concat([a,n]);return sr.streamEncode.bytes=o.byteLength,o};sr.streamEncode.bytes=0;sr.streamDecode=function(s){let n=s.readUInt16BE(0);if(s.byteLength<n+2)return null;let a=sr.decode(s.slice(2));return sr.streamDecode.bytes=sr.decode.bytes,a};sr.streamDecode.bytes=0;function Pt(s,n){let a=0;for(let o=0;o<s.length;o++)a+=n.encodingLength(s[o]);return a}function os(s,n,a,o){for(let c=0;c<s.length;c++)n.encode(s[c],a,o),o+=n.encode.bytes;return o}function tr(s,n,a,o){for(let c=0;c<s.length;c++)s[c]=n.decode(a,o),o+=n.decode.bytes;return o}});var Ra=M(function(rT,ba){var Ta=ru;process.nextTick(su,42);ba.exports=Jl;function Jl(s){var n=o;return a;function a(c){n(c||eu)}function o(c){var d=[c];n=h,s(u);function h(p){d.push(p)}function u(p){var f=arguments;n=Zl(p)?o:m;while(d.length)m(d.shift());function m(y){Ta(tu,y,f)}}}}function Zl(s){return Object.prototype.toString.call(s)==="[object Error]"}function eu(){}function tu(s,n){s.apply(null,n)}function su(s){if(s===42)Ta=process.nextTick}function ru(s,n,a){process.nextTick(function(){s(n,a)})}});var Ia=M(function(iT,Ea){var vi=wa(),iu=wt("dgram"),nu=Ra(),au=wt("events"),Ti=wt("os"),wi=function(){};Ea.exports=function(s){if(!s)s={};var n=new au.EventEmitter,a=typeof s.port==="number"?s.port:5353,o=s.type||"udp4",c=s.ip||s.host||(o==="udp4"?"224.0.0.251":null),d={address:c,port:a},h={},u=!1,p=null;if(o==="udp6"&&(!c||!s.interface))throw Error("For IPv6 multicast you must specify `ip` and `interface`");var f=s.socket||iu.createSocket({type:o,reuseAddr:s.reuseAddr!==!1,toString:function(){return o}});f.on("error",function(y){if(y.code==="EACCES"||y.code==="EADDRINUSE")n.emit("error",y);else n.emit("warning",y)}),f.on("message",function(y,S){try{y=vi.decode(y)}catch(v){n.emit("warning",v);return}if(n.emit("packet",y,S),y.type==="query")n.emit("query",y,S);if(y.type==="response")n.emit("response",y,S)}),f.on("listening",function(){if(!a)a=d.port=f.address().port;if(s.multicast!==!1)n.update(),p=setInterval(n.update,5000),f.setMulticastTTL(s.ttl||255),f.setMulticastLoopback(s.loopback!==!1)});var m=nu(function(y){if(!a||s.bind===!1)return y(null);f.once("error",y),f.bind(a,s.bind||s.interface,function(){f.removeListener("error",y),y(null)})});return m(function(y){if(y)return n.emit("error",y);n.emit("ready")}),n.send=function(y,S,v){if(typeof S==="function")return n.send(y,null,S);if(!v)v=wi;if(!S)S=d;else if(!S.host&&!S.address)S.address=d.address;m(g);function g(w){if(u)return v();if(w)return v(w);var T=vi.encode(y);f.send(T,0,T.length,S.port,S.address||S.host,v)}},n.response=n.respond=function(y,S,v){if(Array.isArray(y))y={answers:y};y.type="response",y.flags=(y.flags||0)|vi.AUTHORITATIVE_ANSWER,n.send(y,S,v)},n.query=function(y,S,v,g){if(typeof S==="function")return n.query(y,null,null,S);if(typeof S==="object"&&S&&S.port)return n.query(y,null,S,v);if(typeof v==="function")return n.query(y,S,null,v);if(!g)g=wi;if(typeof y==="string")y=[{name:y,type:S||"ANY"}];if(Array.isArray(y))y={type:"query",questions:y};y.type="query",n.send(y,v,g)},n.destroy=function(y){if(!y)y=wi;if(u)return process.nextTick(y);u=!0,clearInterval(p);for(var S in h)try{f.dropMembership(c,S)}catch(v){}h={},f.close(y)},n.update=function(){var y=s.interface?[].concat(s.interface):cu(),S=!1;for(var v=0;v<y.length;v++){var g=y[v];if(h[g])continue;try{f.addMembership(c,g),h[g]=!0,S=!0}catch(w){n.emit("warning",w)}}if(S){if(f.setMulticastInterface)try{f.setMulticastInterface(s.interface||ou())}catch(w){n.emit("warning",w)}n.emit("networkInterface")}},n};function ou(){var s=Ti.networkInterfaces(),n=Object.keys(s);for(var a=0;a<n.length;a++){var o=s[n[a]];for(var c=0;c<o.length;c++){var d=o[c];if(Ca(d.family)&&!d.internal){if(Ti.platform()==="darwin"&&n[a]==="en0")return d.address;return"0.0.0.0"}}}return"127.0.0.1"}function cu(){var s=Ti.networkInterfaces(),n=Object.keys(s),a=[];for(var o=0;o<n.length;o++){var c=s[n[o]];for(var d=0;d<c.length;d++){var h=c[d];if(Ca(h.family)){a.push(h.address);break}}}return a}function Ca(s){return s===4||s==="IPv4"}});import{randomUUID as lu}from"crypto";import{EventEmitter as uu}from"events";import{randomBytes as $c}from"crypto";import{createSocket as Lu}from"dgram";import*as ld from"net";import{connect as Uu}from"net";import*as ud from"tls";import{createSocket as Nu}from"dgram";import{randomBytes as cp}from"crypto";import{setTimeout as pp}from"timers/promises";import{createCipheriv as Ip,createDecipheriv as kp}from"crypto";import{createHash as Pp,createHmac as Ap,createPrivateKey as xp,createPublicKey as _p,diffieHellman as Lp}from"crypto";import{createECDH as Ed}from"crypto";import{generateKeyPairSync as Kp}from"crypto";var nh=Nt(Ia(),1);import{createCipheriv as Vf,createHmac as Ei}from"crypto";import{createCipheriv as to,createDecipheriv as so,createHmac as ro,timingSafeEqual as Yf}from"crypto";import{createCipheriv as oo,createDecipheriv as co}from"crypto";import{setTimeout as hm}from"timers/promises";import{createPrivateKey as lm,createSign as fo,generateKeyPair as um,X509Certificate as pm}from"crypto";import{promisify as fm}from"util";import{randomBytes as mm,sign as gm}from"crypto";import{randomBytes as Lm}from"crypto";import{createHash as Nm,randomUUID as Eo}from"crypto";import{isIPv4 as Io}from"net";import*as ih from"timers/promises";import{randomBytes as $m}from"crypto";import{isIPv4 as Gt}from"net";import{randomBytes as ah}from"crypto";import{randomUUID as Vm}from"crypto";import{createHmac as hh,randomBytes as tg}from"crypto";import{isIPv4 as on,isIPv6 as sg}from"net";import{isIPv4 as Cg}from"net";import{promises as Ig}from"dns";import{isIP as gh,SocketAddress as kg}from"net";import{connect as Pg,createServer as Ag}from"net";import{isIP as wh}from"net";import*as Th from"tls";import{setTimeout as Dg}from"timers/promises";import{createHash as Ug}from"crypto";import*as bh from"os";import{createHmac as Ko,randomBytes as gy}from"crypto";import{randomBytes as Hy}from"crypto";import{isIPv4 as Fy}from"net";import{createPrivateKey as Xy,randomUUID as Jy,X509Certificate as hc}from"crypto";import{setTimeout as Zy}from"timers/promises";import{createHash as tS}from"crypto";import{performance as uc}from"perf_hooks";import{randomUUID as sS}from"crypto";import{randomUUID as qh}from"crypto";import{randomBytes as yc,randomUUID as _S}from"crypto";import{isIPv4 as LS,isIPv6 as BS}from"net";import{randomUUID as FS}from"crypto";import{randomUUID as VS}from"crypto";import{setTimeout as Oi}from"timers/promises";import{setTimeout as XS}from"timers/promises";import{randomBytes as _c,randomUUID as pv}from"crypto";import{setTimeout as Lc}from"timers/promises";import{randomUUID as Uc}from"crypto";var du=Object.defineProperty,hu=(s,n)=>{for(var a in n)du(s,a,{get:n[a],enumerable:!0})};function Kc(s){return s.map((n,a)=>[a,n])}function Je(s,n){let a=s.split(n);return[a[0],a.slice(1).join(n)]}var Fs=class extends uu{emit(s,...n){if(typeof s!=="string")return super.emit(s,...n);if(n.length===0)return super.emit(s,new Event(s));let[a,...o]=n;if(a&&typeof a==="object"&&!("type"in a))try{Object.defineProperty(a,"type",{configurable:!0,enumerable:!0,value:s})}catch{return super.emit(s,{type:s,...a},...o)}return super.emit(s,a,...o)}addEventListener=(s,n,a)=>{if(typeof a==="object"&&a?.once){this.once(s,n);return}this.addListener(s,n)};removeEventListener=(s,n)=>{this.removeListener(s,n)};dispatchEvent=(s)=>this.emit(s.type,s)};function pu(){return $c(2).readUInt16BE(0)}function ka(){return $c(4).readUInt32BE(0)}var Br=class{constructor(s){this.bitLength=s}bitLength;value=0;set(s,n,a){return a&=(1<<s)-1,this.value|=a<<this.bitLength-s-n,this}get buffer(){let s=Math.ceil(this.bitLength/8),n=Buffer.alloc(s);return n.writeUIntBE(this.value,0,s),n}},Gc=class{constructor(s){if(this.bitLength=s,s>32)throw Error()}bitLength;_value=0n;offset=0n;set(s,n=1){let a=BigInt(s),o=BigInt(n);return a&=(1n<<o)-1n,this._value|=a<<BigInt(this.bitLength)-o-this.offset,this.offset+=o,this}get value(){return Number(this._value)}get buffer(){let s=Math.ceil(this.bitLength/8),n=Buffer.alloc(s);return n.writeUIntBE(this.value,0,s),n}};function j(s,n,a=1){let o=s.toString(2).split("");o=[...Array(8-o.length).fill("0"),...o];let c=o.slice(n,n+a).join("");return Number.parseInt(c,2)}function W(s,n){return vr(s)(n)}function vr(s,n){let a=s.reduce((c,d)=>c+d,0),o=n?Buffer.alloc(a):void 0;return(c)=>{let d=o||Buffer.alloc(a),h=0;return c.forEach((u,p)=>{let f=s[p];if(f===8)d.writeBigUInt64BE(u,h);else d.writeUIntBE(u,h,f);h+=f}),d}}function oe(s,n){let a=0;return n.map((o)=>{let c;if(o===8)c=s.readBigUInt64BE(a);else c=s.readUIntBE(a,o);return a+=o,c})}var Rs=class{constructor(s){this.uint8Array=s}uint8Array;position=0;bitsPending=0;writeBits(s,n){if(s==0)return this;n&=4294967295>>>32-s;let a;if(this.bitsPending>0)if(this.bitsPending>s)this.uint8Array[this.position-1]|=n<<this.bitsPending-s,a=s,this.bitsPending-=s;else if(this.bitsPending==s)this.uint8Array[this.position-1]|=n,a=s,this.bitsPending=0;else this.uint8Array[this.position-1]|=n>>s-this.bitsPending,a=this.bitsPending,this.bitsPending=0;else a=Math.min(8,s),this.bitsPending=8-a,this.uint8Array[this.position++]=n>>s-a<<this.bitsPending;if(s-=a,s>0)this.writeBits(s,n);return this}readBits(s){return this._readBits(s)}_readBits(s,n){if(typeof n>"u")n=0;if(s==0)return n;let a,o;if(this.bitsPending>0){let c=this.uint8Array[this.position-1]&255>>8-this.bitsPending;o=Math.min(this.bitsPending,s),this.bitsPending-=o,a=c>>this.bitsPending}else o=Math.min(8,s),this.bitsPending=8-o,a=this.uint8Array[this.position++]>>this.bitsPending;return s-=o,n=n<<o|a,s>0?this._readBits(s,n):n}seekTo(s){if(this.position=s/8|0,this.bitsPending=s%8,this.bitsPending>0)this.bitsPending=8-this.bitsPending,this.position++}},z={};hu(z,{BinaryReader:()=>Vc,BinaryWriter:()=>_n,NotEnoughDataError:()=>jc,decode:()=>mu,encode:()=>fu,types:()=>vu});var jc=class extends Error{constructor(s,n){super(`requested ${s} bytes but only ${n} available`);this.name="NotEnoughDataError"}},Vc=class{constructor(s){this.buf=s}buf;offset=0;get length(){return this.buf.length-this.offset}get bytes(){return this.offset}readBuffer(s){this.assertSize(s);let n=this.buf.subarray(this.offset,this.offset+s);return this.offset+=s,n}readUIntBE(s){this.assertSize(s);let n=this.buf.readUIntBE(this.offset,s);return this.offset+=s,n}assertSize(s){if(s>this.length)throw new jc(s,this.length)}},_n=class{chunks=[];written=0;get bytes(){return this.written}writeBuffer(s){this.chunks.push(s),this.written+=s.length}writeUIntBE(s,n){let a=Buffer.allocUnsafe(n);switch(n){case 1:a.writeUInt8(s,0);break;case 2:a.writeUInt16BE(s,0);break;case 4:a.writeUInt32BE(s,0);break;default:a.writeUIntBE(s,0,n)}this.writeBuffer(a)}toBuffer(){return Buffer.concat(this.chunks,this.written)}},Yc=(s)=>typeof s==="object"&&s!==null,ne=(s)=>Yc(s)&&typeof s.encode==="function"&&typeof s.decode==="function",Qc=(s)=>{if(!Yc(s))return!1;let n=Object.getPrototypeOf(s);return n===Object.prototype||n===null},Xc=()=>({node:void 0,current:void 0}),Pa=(s)=>({node:s.node,current:s.current}),Jc=(s,n)=>{if(!Qc(s))throw TypeError(n)},Zc=(s,n,a,o)=>{if(ne(n))n.encode(s,a,o);else ed(s,n,a,o)},ed=(s,n,a,o)=>{if(Jc(n,"Argument `schema` should be a plain object."),o.node===void 0)o.node=s;o.current=s;for(let c of Object.keys(n)){let d=n[c],h=s[c];if(ne(d))d.encode(h,a,o);else ed(h,d,a,o),o.current=s}},Ki=(s,n,a)=>{if(ne(n))return n.decode(s,a);return td(s,n,a)},td=(s,n,a)=>{Jc(n,"Argument #2 should be a plain object.");let o=Object.create(null);if(a.node===void 0)a.node=o;a.current=o;for(let c of Object.keys(n)){let d=n[c];if(ne(d))o[c]=d.decode(s,a);else o[c]=td(s,d,a),a.current=o}return o};function fu(s,n){let a=new _n;return Zc(s,n,a,Xc()),a.toBuffer()}function mu(s,n){return Ki(new Vc(s),n,Xc())}var ds=(s)=>({encode:(n,a)=>a.writeUIntBE(n,s),decode:(n)=>n.readUIntBE(s)}),Ln=(s)=>{if(typeof s!=="number"&&!ne(s)&&typeof s!=="function")throw TypeError("Unknown type of argument #1.")},As=(s,n,a)=>{if(s!==n)throw Error(`${a} required length ${s} instead of ${n}`)},Ct=(s,n)=>{if(typeof s!=="number")throw TypeError(n)};function gu(s){Ln(s);let n="Length of a buffer should be a number.";return{encode(a,o,c){if(!Buffer.isBuffer(a))throw TypeError("Argument 1 should be a Buffer or a BinaryStream.");if(typeof s==="number")As(s,a.length,"Buffer");else if(ne(s))s.encode(a.length,o,c);else{let d=s(c);Ct(d,n),As(d,a.length,"Buffer")}o.writeBuffer(a)},decode(a,o){let c;if(typeof s==="number")c=s;else if(ne(s))c=s.decode(a,o);else c=s(o);return Ct(c,n),a.readBuffer(c)}}}function yu(s,n,a="count"){if(!ne(s)&&!Qc(s))throw TypeError("Argument #1 should be a valid type.");Ln(n);let o=a==="bytes",c="Length of an array should be a number.";return{encode(d,h,u){if(!Array.isArray(d))throw TypeError("Argument #1 should be an Array.");let p=Pa(u),f=0;if(typeof n==="number")f=n;else if(ne(n))f=d.length;else f=n(p),Ct(f,c);let m=new _n;for(let y of d)Zc(y,s,m,p);if(o){if(ne(n))f=m.bytes;As(m.bytes,f,"Argument #1")}else As(f,d.length,"Argument #1");if(ne(n))n.encode(f,h,p);h.writeBuffer(m.toBuffer())},decode(d,h){let u=Pa(h),p;if(typeof n==="number")p=n;else if(ne(n))p=n.decode(d,u);else p=n(u);Ct(p,c);let f=[];if(o){let m=d.bytes,y=0;while(y<p)f.push(Ki(d,s,u)),y=d.bytes-m;if(y>p)throw Error("Incorrect length of an array.")}else for(let m=0;m<p;m++)f.push(Ki(d,s,u));return f}}}function Su(s,n="ascii"){if(!Buffer.isEncoding(n))throw Error("Argument #2 should be an encoding name.");Ln(s);let a="Length of a buffer should be a number.";return{encode(o,c,d){let h=Buffer.from(o.toString(),n);if(typeof s==="number"){if(h.length!==s)throw Error(`Size of string should be ${s} in bytes.`)}else if(ne(s))s.encode(h.length,c,d);else{let u=s(d);Ct(u,a),As(u,h.length,"Buffer")}c.writeBuffer(h)},decode(o,c){let d;if(typeof s==="number")d=s;else if(ne(s))d=s.decode(o,c),Ct(d,"Size of a string should be a number.");else d=s(c),Ct(d,a);return o.readBuffer(d).toString(n)}}}var vu={uint8:ds(1),uint16be:ds(2),uint24be:ds(3),uint32be:ds(4),uint48be:ds(6),buffer:gu,array:yu,string:Su},wu=3988292384,Tu=2197175160;function sd(s){return typeof s!=="string"}function rd(s){let n=Array(256),a=0;for(let o=0;o<256;++o)a=o,a=a&1?s^a>>>1:a>>>1,a=a&1?s^a>>>1:a>>>1,a=a&1?s^a>>>1:a>>>1,a=a&1?s^a>>>1:a>>>1,a=a&1?s^a>>>1:a>>>1,a=a&1?s^a>>>1:a>>>1,a=a&1?s^a>>>1:a>>>1,a=a&1?s^a>>>1:a>>>1,n[o]=a;return new Int32Array(n)}function id(s){let n=new Int32Array(4096),a=0,o=0,c=0;for(c=0;c<256;++c)n[c]=s[c];for(c=0;c<256;++c){o=s[c];for(a=256+c;a<4096;a+=256)o=n[a]=o>>>8^s[o&255]}let d=[];for(c=1;c<16;++c)d[c-1]=n.subarray(c*256,c*256+256);return d}function nd(s,n,a){let o=n^-1,c=0,d=s.length,h=0,u=0;while(c<d)if(h=s.charCodeAt(c++),h<128)o=o>>>8^a[(o^h)&255];else if(h<2048)o=o>>>8^a[(o^(192|h>>6&31))&255],o=o>>>8^a[(o^(128|h&63))&255];else if(h>=55296&&h<57344)h=(h&1023)+64,u=s.charCodeAt(c++)&1023,o=o>>>8^a[(o^(240|h>>8&7))&255],o=o>>>8^a[(o^(128|h>>2&63))&255],o=o>>>8^a[(o^(128|u>>6&15|(h&3)<<4))&255],o=o>>>8^a[(o^(128|u&63))&255];else o=o>>>8^a[(o^(224|h>>12&15))&255],o=o>>>8^a[(o^(128|h>>6&63))&255],o=o>>>8^a[(o^(128|h&63))&255];return~o>>>0}function ad(s,n,a,o){let[c,d,h,u,p,f,m,y,S,v,g,w,T,b,C]=o,P=n^-1,x=0,H=s.length-15;while(x<H)P=C[s[x++]^P&255]^b[s[x++]^P>>>8&255]^T[s[x++]^P>>>16&255]^w[s[x++]^P>>>24]^g[s[x++]]^v[s[x++]]^S[s[x++]]^y[s[x++]]^m[s[x++]]^f[s[x++]]^p[s[x++]]^u[s[x++]]^h[s[x++]]^d[s[x++]]^c[s[x++]]^a[s[x++]];for(H+=15;x<H;)P=P>>>8^a[(P^s[x++])&255];return~P>>>0}var $i=rd(wu),bu=id($i),Gi=rd(Tu),Ru=id(Gi);function Cu(s,n=0){if(sd(s))return ad(s,n,$i,bu);return nd(s,n,$i)}function od(s,n=0){if(sd(s))return ad(s,n,Gi,Ru);return nd(s,n,Gi)}var E=class{event={stack:[],promiseStack:[],eventId:0};ended=!1;onended;onerror=(s)=>{};execute=(...s)=>{if(this.ended)return;for(let n of this.event.stack)n.execute(...s);(async()=>{for(let n of this.event.promiseStack)await n.execute(...s)})().catch((n)=>{this.onerror(n)})};complete=()=>{if(this.ended)return;for(let s of this.event.stack)if(s.complete)s.complete();if(this.allUnsubscribe(),this.ended=!0,this.onended)this.onended(),this.onended=void 0};error=(s)=>{if(this.ended)return;for(let n of this.event.stack)if(n.error)n.error(s);this.allUnsubscribe()};allUnsubscribe=()=>{if(this.ended)return;this.event={stack:[],promiseStack:[],eventId:0}};subscribe=(s,n,a)=>{let o=this.event.eventId;this.event.stack.push({execute:s,id:o,complete:n,error:a}),this.event.eventId++;let c=()=>{this.event.stack=this.event.stack.filter((h)=>h.id!==o&&h)};return{unSubscribe:c,disposer:(h)=>{h.push(c)}}};pipe(s){this.subscribe((...n)=>{s.execute(...n)})}queuingSubscribe=(s,n,a)=>{if(this.ended)throw Error("event completed");let o=this.event.eventId;this.event.promiseStack.push({execute:s,id:o,complete:n,error:a}),this.event.eventId++;let c=()=>{this.event.stack=this.event.stack.filter((h)=>h.id!==o&&h)};return{unSubscribe:c,disposer:(h)=>{h.push(c)}}};once=(s,n,a)=>{let o=this.subscribe((...c)=>{o.unSubscribe(),s(...c)},n,a)};watch=(s,n)=>new Promise((a,o)=>{let c=n&&setTimeout(()=>{o("Event watch timeout")},n),{unSubscribe:d}=this.subscribe((...h)=>{if(s(...h)){if(c)clearTimeout(c);d(),a(h)}})});asPromise=(s)=>new Promise((n,a)=>{let o=s&&setTimeout(()=>{a("Event asPromise timeout")},s);this.once((...c)=>{if(o)clearTimeout(o);n(c)},()=>{if(o)clearTimeout(o);n([])},(c)=>{if(o)clearTimeout(o);a(c)})});get returnTrigger(){let{execute:s,error:n,complete:a}=this;return{execute:s,error:n,complete:a}}get returnListener(){let{subscribe:s,once:n,asPromise:a}=this;return{subscribe:s,once:n,asPromise:a}}get length(){return this.event.stack.length}},Eu=class{_disposer=[];push(s){this._disposer.push(s)}dispose(){this._disposer.forEach((s)=>s()),this._disposer=[]}};var Aa=[31,32,33,34,35,36],Iu=Symbol.for("werift-common.log.state"),Z=globalThis[Iu]??={namespaceSetting:ku(),generation:0,includePatterns:[],excludePatterns:[],lastTime:Date.now(),debugWriter:(...s)=>xu(...s)};if(Z.generation===0&&Z.includePatterns.length===0)cd(Z.namespaceSetting);function Bn(){return globalThis.process}function Mn(){return Boolean(Bn()?.versions?.node)}function ku(){if(Mn())return Bn()?.env?.DEBUG??"";try{return globalThis.localStorage?.getItem("debug")??""}catch{return""}}function xa(s){return new RegExp(`^${s.split("*").map(Pu).join(".*?")}$`)}function Pu(s){return s.replace(/[|\\{}()[\]^$+?.]/g,"\\$&")}function cd(s){let n=s.split(/[\s,]+/).filter(Boolean);Z.includePatterns=n.filter((a)=>!a.startsWith("-")).map(xa),Z.excludePatterns=n.filter((a)=>a.startsWith("-")).map((a)=>xa(a.slice(1)))}function dd(s){return!Z.excludePatterns.some((n)=>n.test(s))&&Z.includePatterns.some((n)=>n.test(s))}function Au(s){let n=0;for(let a=0;a<s.length;a++)n=(n<<5)-n+s.charCodeAt(a);return Aa[Math.abs(n)%Aa.length]}function _a(s){if(s?.env?.NO_COLOR!==void 0)return!1;let n=s?.env?.DEBUG_COLORS;if(n!==void 0)return!["no","false","0","disabled"].includes(n.toLowerCase());return Boolean(s?.stderr?.isTTY)}function xu(...s){if(Mn())console.error(...s);else console.debug(...s)}function _u(s,n){let a=Bn(),o=Date.now(),c=o-Z.lastTime;if(Z.lastTime=o,Mn()){let h=_a(a)?`\x1B[${Au(s)}m${s}\x1B[0m`:`${new Date().toISOString()} ${s}`,u=_a(a)?` +${c}ms`:"",p=[...n];if(typeof p[0]==="string")p[0]=`${h} ${p[0]}${u}`;else p.unshift(`${h}${u}`);Z.debugWriter(...p);return}let d=[...n];if(typeof d[0]==="string")d[0]=`${s} ${d[0]}`;else d.unshift(s);Z.debugWriter(...d)}var xs=(s)=>{let n=-1,a=!1,o,c=()=>{if(o!==void 0)return o;if(n!==Z.generation)a=dd(s),n=Z.generation;return a},d=(...h)=>{if(c())_u(s,h)};return Object.defineProperties(d,{enabled:{get:c,set:(h)=>{o=Boolean(h)},enumerable:!0},namespace:{value:s,enumerable:!0}}),d};xs.enable=(s)=>{Z.namespaceSetting=s,cd(s),Z.generation++};xs.disable=()=>{let s=Z.namespaceSetting;return xs.enable(""),s};xs.enabled=(s)=>dd(s);var _=xs,Mr=(s,n)=>n?n[s]:void 0;async function Bu(s,n,a="udp4",o){let c;for(let d=s;d<=n;d++){let h=Lu(a);if(setImmediate(()=>h.bind({port:d,address:Mr(a,o)})),await new Promise((p)=>{h.once("error",(f)=>p(f)),h.once("listening",()=>p())})){await new Promise((p)=>h.close(()=>p()));continue}if(c=h.address()?.port,await new Promise((p)=>h.close(()=>p())),s<=c&&c<=n)break}if(!c)throw Error("port not found");return c}function Dr(s){if(s==="IPv4")return 4;if(s==="IPv6")return 6;return s}function Mu(s,n){return s+n&255}function ae(s,n){return s+n&65535}function Xt(s,n){return Number(BigInt(s)+BigInt(n)&0xffffffffn)}function Du(s){return s&16777215}function hd(s,n){return s<n&&n-s>32768||s>n&&s-n<32768}function Ze(s,n){return s<n&&n-s>2147483648||s>n&&s-n<2147483648}function Ss(s,n){return s===n||Ze(s,n)}var Cs=(s)=>Number.parseInt(s,10);var Vt=class s{items=[];head=0;removed=0;constructor(n){if(n)for(let a of n)this.items.push(a)}get length(){return this.items.length-this.head}push(...n){for(let a of n)this.items.push(a);return this.length}shift(){if(this.head>=this.items.length)return;let n=this.items[this.head];return this.items[this.head]=void 0,this.head++,this.removed++,this.compact(),n}unshift(n){if(this.removed--,this.head>0)this.head--,this.items[this.head]=n;else this.items.unshift(n);return this.length}peek(){return this.head<this.items.length?this.items[this.head]:void 0}last(){return this.length>0?this.items[this.items.length-1]:void 0}at(n){let a=this.length,o=n<0?a+n:n;if(o<0||o>=a)return;return this.items[this.head+o]}findIndex(n){for(let a=this.head;a<this.items.length;a++)if(n(this.items[a],a-this.head))return a-this.head;return-1}filter(n){let a=new s;for(let o=this.head;o<this.items.length;o++){let c=this.items[o];if(n(c,o-this.head))a.items.push(c)}return a}forEach(n){for(let a=this.head;a<this.items.length;a++)n(this.items[a],a-this.head)}clear(){this.removed+=this.length,this.reset()}toArray(){return this.items.slice(this.head)}*[Symbol.iterator](){let n=this.removed;while(!0){let a=Math.max(0,n-this.removed);if(a>=this.length)return;n=this.removed+a+1,yield this.items[this.head+a]}}reset(){this.items=[],this.head=0}compact(){if(this.head===this.items.length)this.reset();else if(this.head>=1024&&this.head*2>=this.items.length)this.items=this.items.slice(this.head),this.head=0}},Kt=_("werift-ice:packages/ice/src/transport.ts"),Ou=8000,ji=class s{constructor(n,a={}){this.socketType=n,this.options=a,this.socket=Nu(n),this.socket.on("message",(o,c)=>{if(Dr(c.family)===6)[c.address]=c.address.split("%");this.rinfo=c;try{this.onData(o,[c.address,c.port])}catch(d){Kt("onData error",d)}}),this.socket.on("error",(o)=>{if(Kt("udp socket error",o),this.closed||!this.listening)return;try{this.onError.execute(o)}catch(c){Kt("onError handler error",c)}})}socketType;options;type="udp";socket;rinfo;onData=()=>{};onError=new E;closed=!1;listening=!1;static async init(n,a={}){let o=new s(n,a);try{return await o.init(),o}catch(c){throw await o.close(),c}}async init(){let n=Mr(this.socketType,this.options.interfaceAddresses),a=this.options.port?this.options.port:this.options.portRange?await Bu(this.options.portRange[0],this.options.portRange[1],this.socketType,this.options.interfaceAddresses):void 0;if(this.closed)throw Error("udp transport closed");await new Promise((o,c)=>{let d=!1,h=(m)=>{if(d)return;d=!0,this.socket.off("listening",u),this.socket.off("error",p),this.socket.off("close",f),m?c(m):o()},u=()=>{this.listening=!0,h()},p=(m)=>{h(m)},f=()=>{h(Error("udp transport closed"))};this.socket.once("listening",u),this.socket.once("error",p),this.socket.once("close",f);try{if(a===void 0)this.socket.bind({address:n});else this.socket.bind({port:a,address:n})}catch(m){h(m)}})}send=async(n,a)=>{if(a&&!ld.isIP(a[0]))return new Promise((o,c)=>{this.socket.send(n,a[1],a[0],(d)=>{if(d)Kt("send error",a,n),c(d);else o()})});else a=a??[this.rinfo?.address,this.rinfo?.port],this.socket.send(n,a[1],a[0])};get address(){return this.socket.address()}get addressFamily(){return this.socketType==="udp6"?6:4}get host(){return this.socket.address().address}get port(){return this.socket.address().port}close=()=>new Promise((n)=>{if(this.closed){n();return}this.closed=!0,this.socket.once("close",n);try{this.onError.complete()}catch(a){Kt("onError complete error",a)}try{this.socket.close()}catch(a){n()}})},Vi=class s{type="tcp";stream;constructor(n,a={}){this.stream=new pd("tcp",()=>Uu({port:n[1],host:n[0]}),void 0,a.connectTimeoutMs)}static async init(n,a={}){let o=new s(n,a);try{return await o.init(),o}catch(c){throw await o.close(),c}}async init(){await this.stream.waitForConnect()}get address(){return this.stream.address}get remoteAddress(){return this.stream.remoteAddress}get closed(){return this.stream.closed}get onData(){return this.stream.onData}set onData(n){this.stream.onData=n}send=async(n,a)=>{await this.stream.send(n,a)};close=async()=>{await this.stream.close()}},Yi=class s{type="tls";stream;constructor(n,a={},o={}){this.stream=new pd("tls",()=>ud.connect({...a,host:n[0],port:n[1]}),void 0,o.connectTimeoutMs)}static async init(n,a={},o={}){let c=new s(n,a,o);try{return await c.init(),c}catch(d){throw await c.close(),d}}async init(){await this.stream.waitForConnect()}get address(){return this.stream.address}get remoteAddress(){return this.stream.remoteAddress}get closed(){return this.stream.closed}get onData(){return this.stream.onData}set onData(n){this.stream.onData=n}send=async(n,a)=>{await this.stream.send(n,a)};close=async()=>{await this.stream.close()}},pd=class{constructor(s,n,a=s==="tls"?"secureConnect":"connect",o=Ou){this.createClient=n,this.connectEvent=a,this.connectTimeoutMs=o,this.type=s,this.connect()}createClient;connectEvent;connectTimeoutMs;type;connecting;client;onData=()=>{};closed=!1;rejectConnecting;connect(){if(this.closed)return;if(this.client)this.client.destroy();let s=this.createClient();this.client=s,this.connecting=new Promise((n,a)=>{let o=!1,c=(p)=>{if(o)return;o=!0,clearTimeout(u),s.off(this.connectEvent,d),s.off("error",h),this.rejectConnecting=void 0,p?a(p):n()},d=()=>{c()},h=(p)=>{this.closed=!0,c(p),s.destroy()},u=setTimeout(()=>{this.closed=!0,c(Error(`${this.type} connect timed out after ${this.connectTimeoutMs}ms`)),s.destroy()},this.connectTimeoutMs);this.rejectConnecting=(p)=>c(p),s.once(this.connectEvent,d),s.once("error",h)}),s.on("data",(n)=>{this.onData(n,this.remoteAddress)}),s.on("error",(n)=>{Kt(`${this.type} transport error`,n)})}async waitForConnect(){await this.connecting}get address(){return{}}get remoteAddress(){let{remoteAddress:s,remotePort:n}=this.client;if(!s||!n)return;return[Hu(s),n]}send=async(s,n)=>{await this.connecting,await new Promise((a,o)=>{this.client.write(s,(c)=>{if(c){o(c);return}a()})})};close=async()=>{this.closed=!0,this.rejectConnecting?.(Error(`${this.type} transport closed`)),this.client?.destroy()}};function Hu(s){return s.split("%")[0]}var Fu=_("werift:packages/webrtc/src/dataChannel.ts");function zu(s){return Buffer.isBuffer(s)?s.length:Buffer.byteLength(s)}var fd=class extends Fs{constructor(s,n,a=!0){super();if(this.sctp=s,this.parameters=n,this.sendOpen=a,this.id=this.parameters.id,n.negotiated){if(this.id==null||this.id<0||this.id>65534)throw Error("ID must be in range 0-65534 if data channel is negotiated out-of-band");this.sctp.dataChannelAddNegotiated(this)}else if(a)this.sendOpen=!1,this.sctp.dataChannelOpen(this)}sctp;parameters;sendOpen;statsId=lu().toString();stateChange=new E;stateChanged=new E;onMessage=new E;error=new E;bufferedAmountLow=new E;onopen;onclose;onclosing;onmessage;onerror;isCreatedByRemote=!1;id;readyState="connecting";bufferedAmount=0;_bufferedAmountLowThreshold=0;messagesSent=0;bytesSent=0;messagesReceived=0;bytesReceived=0;get ordered(){return this.parameters.ordered}get maxRetransmits(){return this.parameters.maxRetransmits??null}get maxPacketLifeTime(){return this.parameters.maxPacketLifeTime??null}get label(){return this.parameters.label}get protocol(){return this.parameters.protocol}get negotiated(){return this.parameters.negotiated}get bufferedAmountLowThreshold(){return this._bufferedAmountLowThreshold}set bufferedAmountLowThreshold(s){if(s<0||s>4294967295)throw Error("bufferedAmountLowThreshold must be in range 0 - 4294967295");this._bufferedAmountLowThreshold=s}setId(s){this.id=s}setReadyState(s){if(s!==this.readyState){switch(this.readyState=s,this.stateChange.execute(s),this.stateChanged.execute(s),s){case"open":if(this.onopen)this.onopen();this.emit("open");break;case"closed":if(this.onclose)this.onclose();this.emit("close");break;case"closing":if(this.onclosing)this.onclosing();break}Fu("change state",s)}}addBufferedAmount(s){let n=this.bufferedAmount>this.bufferedAmountLowThreshold&&this.bufferedAmount+s<=this.bufferedAmountLowThreshold;if(this.bufferedAmount+=s,n)this.bufferedAmountLow.execute(),this.emit("bufferedamountlow")}send(s){let n=this.sctp.datachannelSend(this,s);this.messagesSent++,this.bytesSent+=n}close(){this.sctp.dataChannelClose(this)}},md=class{label="";maxPacketLifeTime;maxRetransmits;ordered=!0;protocol="";negotiated=!1;id;constructor(s={}){Object.assign(this,s)}},Ue={rsa_1:1,ecdsa_3:3},Ur={sha256_4:4},Qi={TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256_49195:49195,TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256_49199:49199},qu=Object.values(Qi),Jt={x25519_29:29,secp256r1_23:23},gd=Object.values(Jt),yd={named_curve_3:3},La={rsa_pkcs1_sha256:1025,ecdsa_secp256r1_sha256:1027},Wu=[1,64],Sd=[{hash:Ur.sha256_4,signature:Ue.rsa_1},{hash:Ur.sha256_4,signature:Ue.ecdsa_3}],et={CLIENT:1,SERVER:2},Ku=class{id=0;name;hashAlgorithm;verifyDataLength=12;blockAlgorithm;kx;init(...s){throw Error("not implemented")}encrypt(...s){throw Error("not implemented")}decrypt(...s){throw Error("not implemented")}toString(){return this.name}},be={integer:2,bitString:3,octetString:4,null:5,objectIdentifier:6,utf8String:12,printableString:19,utcTime:23,generalizedTime:24,sequence:48,set:49};function Re(s,n){if(n.length<128)return Buffer.concat([Buffer.from([s,n.length]),n]);let a=[];for(let o=n.length;o>0;o=Math.floor(o/256))a.unshift(o&255);return Buffer.concat([Buffer.from([s,128|a.length,...a]),n])}function Ne(...s){return Re(be.sequence,Buffer.concat(s))}function $u(...s){return Re(be.set,Buffer.concat([...s].sort(Buffer.compare)))}function Gu(s,n){if(s<0||s>30)throw RangeError(`unsupported context-specific tag: ${s}`);return Re(160|s,n)}function ju(){return Buffer.from([be.null,0])}function Xi(s){let n;if(typeof s==="number"){if(!Number.isSafeInteger(s)||s<0)throw RangeError(`unsupported integer: ${s}`);let o=[];for(let c=s;c>0;c=Math.floor(c/256))o.unshift(c&255);n=Buffer.from(o)}else n=s;let a=0;while(a<n.length-1&&n[a]===0)a++;if(n=n.subarray(a),n.length===0)n=Buffer.from([0]);if(n[0]&128)n=Buffer.concat([Buffer.from([0]),n]);return Re(be.integer,n)}function Nr(s){if(!/^[0-2](\.\d+)+$/.test(s))throw TypeError(`invalid object identifier: ${s}`);let n=s.split(".").map(Number);if(n[0]<2&&n[1]>=40)throw TypeError(`invalid object identifier: ${s}`);let a=[];for(let o of[n[0]*40+n[1],...n.slice(2)]){if(!Number.isSafeInteger(o))throw TypeError(`invalid object identifier: ${s}`);let c=[o&127];for(let d=Math.floor(o/128);d>0;d=Math.floor(d/128))c.unshift(d&127|128);a.push(...c)}return Re(be.objectIdentifier,Buffer.from(a))}function vd(s){return Re(be.bitString,Buffer.concat([Buffer.from([0]),s]))}function Ba(s){return Re(be.octetString,s)}function Vu(s){return Re(be.utf8String,Buffer.from(s,"utf8"))}function Yu(s){if(!/^[A-Za-z0-9 '()+,\-./:=?]*$/.test(s))throw TypeError(`invalid PrintableString: ${s}`);return Re(be.printableString,Buffer.from(s,"ascii"))}function Ma(s){let n=s.getUTCFullYear(),a=(c)=>c.toString().padStart(2,"0"),o=a(s.getUTCMonth()+1)+a(s.getUTCDate())+a(s.getUTCHours())+a(s.getUTCMinutes())+a(s.getUTCSeconds())+"Z";if(n>=1950&&n<2050)return Re(be.utcTime,Buffer.from(a(n%100)+o,"ascii"));if(n<0||n>9999)throw RangeError(`unsupported year: ${n}`);return Re(be.generalizedTime,Buffer.from(n.toString().padStart(4,"0")+o,"ascii"))}function Qu(s,n){let a=n.toString("base64"),o=[];for(let c=0;c<a.length;c+=64)o.push(a.slice(c,c+64));return`-----BEGIN ${s}-----
3
+ ${o.join(`
4
+ `)}
5
+ -----END ${s}-----
6
+ `}var Dn=(s)=>"0x"+s.toString("hex").replace(/(.)(.)/g,"$1$2 ").split(" ").filter((n)=>n!=null&&n.length>0).join(",0x"),wd=(s)=>Object.entries({...s}).reduce((n,[a,o])=>{if(typeof o==="number"||typeof o==="string")n[a]=o;if(Buffer.isBuffer(o))n[a]=Dn(o);return n},{}),{decode:Xu,encode:Ju,types:_t}=z,ge=class s{constructor(n,a,o,c,d,h){this.msg_type=n,this.length=a,this.message_seq=o,this.fragment_offset=c,this.fragment_length=d,this.fragment=h}msg_type;length;message_seq;fragment_offset;fragment_length;fragment;static spec={msg_type:_t.uint8,length:_t.uint24be,message_seq:_t.uint16be,fragment_offset:_t.uint24be,fragment_length:_t.uint24be,fragment:_t.buffer((n)=>n.current.fragment_length)};get summary(){return wd(this)}static createEmpty(){return new s(void 0,void 0,void 0,void 0,void 0,void 0)}static deSerialize(n){return new s(...Object.values(Xu(n,s.spec)))}serialize(){return Ju(this,s.spec)}chunk(n){let a=0,o=this.fragment.length;if(o===0)return[new s(this.msg_type,o,this.message_seq,a,0,this.fragment)];let c=[];if(!n)n=1240;while(a<o){let d=Math.min(n,o-a),h=Buffer.from(this.fragment.slice(a,a+d));if(h.length<=0)throw Error("Zero or less bytes processed while fragmenting handshake message.");c.push(new s(this.msg_type,o,this.message_seq,a,h.length,h)),a+=h.length}return c}static assemble(n){if(!n?.length)throw Error("cannot reassemble handshake from empty array");n=n.sort((o,c)=>o.fragment_offset-c.fragment_offset);let a=Buffer.alloc(n[0].length);for(let o of n)o.fragment.copy(a,o.fragment_offset);return new s(n[0].msg_type,n[0].length,n[0].message_seq,0,a.length,a)}static findAllFragments(n,a){let o=n.find((c)=>c.msg_type===a);if(!o)return[];if(!n?.length)return[];return n.filter((c)=>c.msg_type===o.msg_type&&c.message_seq===o.message_seq&&c.length===o.length)}},{types:Zu}=z,{uint16be:Or,uint24be:ep,buffer:Td,array:tp,uint8:_s,string:sp}=Zu,rp={type:Or,data:Td(Or)},Ji=tp(rp,Or,"bytes"),ip=Td(ep),np=_s,ap=sp(Or),op={hash:_s,signature:_s},Un={major:_s,minor:_s},{decode:dp,encode:hp,types:Da}=z,dt=class s{constructor(n=Math.floor(Date.now()/1000),a=cp(28)){this.gmt_unix_time=n,this.random_bytes=a}gmt_unix_time;random_bytes;static spec={gmt_unix_time:Da.uint32be,random_bytes:Da.buffer(28)};static deSerialize(n){return new s(...Object.values(dp(n,s.spec)))}static from(n){return new s(...Object.values(n))}serialize(){return hp(this,s.spec)}},{decode:lp,encode:up,types:ue}=z,bd=class s{constructor(n,a,o,c,d,h,u){this.clientVersion=n,this.random=a,this.sessionId=o,this.cookie=c,this.cipherSuites=d,this.compressionMethods=h,this.extensions=u}clientVersion;random;sessionId;cookie;cipherSuites;compressionMethods;extensions;msgType=1;messageSeq=0;static spec={clientVersion:{major:ue.uint8,minor:ue.uint8},random:dt.spec,sessionId:ue.buffer(ue.uint8),cookie:ue.buffer(ue.uint8),cipherSuites:ue.array(ue.uint16be,ue.uint16be,"bytes"),compressionMethods:ue.array(ue.uint8,ue.uint8,"bytes"),extensions:Ji};static createEmpty(){return new s(void 0,void 0,void 0,void 0,void 0,void 0,void 0)}static deSerialize(n){return new s(...Object.values(lp(n,s.spec)))}serialize(){return up(this,s.spec)}toFragment(){let n=this.serialize();return new ge(this.msgType,n.length,this.messageSeq,0,n.length,n)}},{decode:fp,encode:mp,types:rr}=z,gp=class s{constructor(n,a,o,c,d){this.epoch=n,this.sequenceNumber=a,this.contentType=o,this.protocolVersion=c,this.contentLen=d}epoch;sequenceNumber;contentType;protocolVersion;contentLen;static spec={epoch:rr.uint16be,sequenceNumber:rr.uint48be,contentType:rr.uint8,protocolVersion:Un,contentLen:rr.uint16be};static createEmpty(){return new s(void 0,void 0,void 0,void 0,void 0)}static deSerialize(n){return new s(...Object.values(fp(n,s.spec)))}serialize(){return mp(this,s.spec)}},Rd=class s{constructor(n,a){this.recordLayerHeader=n,this.fragment=a}recordLayerHeader;fragment;get summary(){return{header:this.recordLayerHeader,fragment:Dn(this.fragment)}}static createEmpty(){return new s(void 0,void 0)}static deSerialize(n){if(n.length<13)throw Error("Invalid DTLS record: buffer is too short");let a=n.readUInt8(0),o=n.readUInt8(1),c=n.readUInt8(2),d=n.readUInt16BE(3),h=n.slice(5,11).readUIntBE(0,6),u=n.readUInt16BE(11);if(n.length<13+u)throw Error("Invalid DTLS record: fragment length exceeds buffer");let p=n.slice(13,13+u);return new s({contentType:a,protocolVersion:{major:o,minor:c},epoch:d,sequenceNumber:h,contentLen:u},p)}serialize(){let n=this.fragment.length,a=13+n,o=Buffer.alloc(a);return o.writeUInt8(this.recordLayerHeader.contentType,0),o.writeUInt8(this.recordLayerHeader.protocolVersion.major,1),o.writeUInt8(this.recordLayerHeader.protocolVersion.minor,2),o.writeUInt16BE(this.recordLayerHeader.epoch,3),o.writeUIntBE(this.recordLayerHeader.sequenceNumber,5,6),o.writeUInt16BE(n,11),this.fragment.copy(o,13),o}computeMACHeader(){return new gp(this.recordLayerHeader.epoch,this.recordLayerHeader.sequenceNumber,this.recordLayerHeader.contentType,this.recordLayerHeader.protocolVersion,this.recordLayerHeader.contentLen).serialize()}},Cd=(s)=>(n)=>(s.lastFlight=n,n.flatMap((a)=>(a.messageSeq=s.sequenceNumber++,a.toFragment().chunk()))),zs=(s)=>(n,a)=>n.map((o)=>new Rd({contentType:o.type,protocolVersion:s.version,epoch:s.epoch,sequenceNumber:a,contentLen:o.fragment.length},o.fragment)),Zi=((s)=>(s[s.CloseNotify=0]="CloseNotify",s[s.UnexpectedMessage=10]="UnexpectedMessage",s[s.BadRecordMac=20]="BadRecordMac",s[s.DecryptionFailed=21]="DecryptionFailed",s[s.RecordOverflow=22]="RecordOverflow",s[s.DecompressionFailure=30]="DecompressionFailure",s[s.HandshakeFailure=40]="HandshakeFailure",s[s.NoCertificate=41]="NoCertificate",s[s.BadCertificate=42]="BadCertificate",s[s.UnsupportedCertificate=43]="UnsupportedCertificate",s[s.CertificateRevoked=44]="CertificateRevoked",s[s.CertificateExpired=45]="CertificateExpired",s[s.CertificateUnknown=46]="CertificateUnknown",s[s.IllegalParameter=47]="IllegalParameter",s[s.UnknownCa=48]="UnknownCa",s[s.AccessDenied=49]="AccessDenied",s[s.DecodeError=50]="DecodeError",s[s.DecryptError=51]="DecryptError",s[s.ExportRestriction=60]="ExportRestriction",s[s.ProtocolVersion=70]="ProtocolVersion",s[s.InsufficientSecurity=71]="InsufficientSecurity",s[s.InternalError=80]="InternalError",s[s.UserCanceled=90]="UserCanceled",s[s.NoRenegotiation=100]="NoRenegotiation",s[s.UnsupportedExtension=110]="UnsupportedExtension",s))(Zi||{}),yp=_("werift-dtls : packages/dtls/src/flight/flight.ts : warn"),bi=_("werift-dtls : packages/dtls/src/flight/flight.ts : err"),qs=class s{constructor(n,a,o,c){this.transport=n,this.dtls=a,this.flight=o,this.nextFlight=c}transport;dtls;flight;nextFlight;state="PREPARING";static RetransmitCount=10;createPacket(n){let a=Cd(this.dtls)(n);return this.dtls.bufferHandshakeCache(a,!0,this.flight),zs(this.dtls)(a.map((c)=>({type:22,fragment:c.serialize()})),++this.dtls.recordSequenceNumber)}async transmit(n){let a=0,o=this.transport.closedSignal;for(;a<=s.RetransmitCount;a++){if(o.aborted)return;if(this.setState("SENDING"),this.send(n).catch((d)=>{bi("fail to send",bi)}),this.setState("WAITING"),this.nextFlight===void 0){this.setState("FINISHED");break}if(!await pp(1000*((a+1)/2),!0,{signal:o}).catch(()=>!1))return;if(this.dtls.flight>=this.nextFlight){this.setState("FINISHED");break}else yp(this.dtls.sessionId,"retransmit",a,this.dtls.flight)}if(a>s.RetransmitCount)throw bi(this.dtls.sessionId,"retransmit failed",a),Error(`over retransmitCount : ${this.flight} ${this.nextFlight}`)}send=(n)=>Promise.all(n.map((a)=>this.transport.send(a)));setState(n){this.state=n}},Sp=class extends qs{constructor(s,n,a){super(s,n,1,3);this.cipher=a}cipher;async exec(s){if(this.dtls.flight===1)throw Error();this.dtls.flight=1;let n=new bd({major:254,minor:253},new dt,Buffer.from([]),Buffer.from([]),qu,[0],s);this.dtls.version=n.clientVersion,this.cipher.localRandom=dt.from(n.random);let a=this.createPacket([n]),o=Buffer.concat(a.map((c)=>c.serialize()));await this.transmit([o])}},vp=_("werift-dtls : packages/dtls/src/flight/client/flight3.ts : log"),wp=class extends qs{constructor(s,n){super(s,n,3,5)}async exec(s){if(this.dtls.flight===3)throw Error();this.dtls.flight=3,this.dtls.handshakeCache=[];let[n]=this.dtls.lastFlight;vp("dtls version",n.clientVersion),n.cookie=s.cookie,this.dtls.cookie=s.cookie;let a=this.createPacket([n]),o=Buffer.concat(a.map((c)=>c.serialize()));await this.transmit([o])}},ii={NULL:0,ECDHE:1},Ws={NULL:0,RSA:1,ECDSA:2,PSK:3},Ks={NULL:0,RSA:1,ECDHE_RSA:2,ECDHE_ECDSA:3,PSK:4,ECDHE_PSK:5},$s=class{id=0;name;signType;keyType;toString(){return this.name}};function Tp(){let s=new $s;return s.id=Ks.RSA,s.name="RSA",s.keyType=Ws.RSA,s}function bp(){let s=new $s;return s.id=Ks.ECDHE_RSA,s.name="ECDHE_RSA",s.signType=ii.ECDHE,s.keyType=Ws.RSA,s}function Rp(){let s=new $s;return s.id=Ks.ECDHE_ECDSA,s.name="ECDHE_ECDSA",s.signType=ii.ECDHE,s.keyType=Ws.ECDSA,s}function Cp(){let s=new $s;return s.id=Ks.PSK,s.name="PSK",s.signType=ii.NULL,s.keyType=Ws.PSK,s}function Ep(){let s=new $s;return s.id=Ks.ECDHE_PSK,s.name="ECDHE_PSK",s.signType=ii.ECDHE,s.keyType=Ws.PSK,s}var Bp=()=>{let s=Ed("prime256v1");s.generateKeys();let n=s.getPrivateKey(),a=s.getPublicKey();return{privateKey:n,publicKey:a}},Mp=({publicKey:s,privateKey:n})=>{let a=Ed("prime256v1");return a.setPrivateKey(n),a.computeSecret(s)},Dp="1.3.101.110",Ls=32,Id=Ne(Nr(Dp)),kd=Buffer.alloc(Ls),Up=Ne(Xi(0),Id,Ba(Ba(kd))).subarray(0,-Ls),Np=Ne(Id,vd(kd)).subarray(0,-Ls);function Pd(s,n,a){switch(a){case Jt.secp256r1_23:return Mp({publicKey:s,privateKey:n});case Jt.x25519_29:if(n.length!==Ls)throw Error(`invalid X25519 private key length: ${n.length}`);if(s.length!==Ls)throw Error(`invalid X25519 public key length: ${s.length}`);return Lp({privateKey:xp({key:Buffer.concat([Up,n]),format:"der",type:"pkcs8"}),publicKey:_p({key:Buffer.concat([Np,s]),format:"der",type:"spki"})});default:throw Error()}}function Ua(s,n,a){let o=Ap(s,n);return o.update(a),o.digest()}function Gs(s,n,a,o="sha256"){let c=a,d=[],h=n;do{h=Ua(o,s,h);let u=Ua(o,s,Buffer.concat([h,n]));d.push(u),a-=u.length}while(a>0);return Buffer.concat(d,c)}function Ad(s,n,a){let o=Buffer.concat([Buffer.from("master secret"),n,a]);return Gs(s,o,48)}function xd(s,n){let a=_d("sha256",n),o="extended master secret";return Gs(s,Buffer.concat([Buffer.from("extended master secret"),a]),48)}function Op(s,n,a,o,c,d){let h=d?o:c,u=d?c:o,p=Buffer.concat([Buffer.from(s),h,u]);return Gs(a,p,n)}function _d(s,n){return Pp(s).update(n).digest()}function Ld(s,n,a,o=12){let c=_d("sha256",n);return Gs(s,Buffer.concat([Buffer.from(a),c]),o)}function Hp(s,n){return Ld(s,n,"client finished")}function Fp(s,n){return Ld(s,n,"server finished")}function zp(s,n,a,o,c,d,h="sha256"){let u=o*2+c*2,p=s,f=Buffer.concat([a,n]),m=Gs(p,Buffer.concat([Buffer.from("key expansion"),f]),u,h),y=new z.BinaryReader(m),S=y.readBuffer(o),v=y.readBuffer(o),g=y.readBuffer(c),w=y.readBuffer(c),T=Buffer.alloc(d,0),b=Buffer.alloc(d,0);return g.copy(T,0),w.copy(b,0),{clientWriteKey:S,serverWriteKey:v,clientNonce:T,serverNonce:b}}var qp=_("werift-dtls : packages/dtls/src/cipher/suites/aead.ts : err"),Wp=class extends Ku{keyLength=0;nonceLength=0;ivLength=0;authTagLength=0;nonceImplicitLength=0;nonceExplicitLength=0;clientWriteKey;serverWriteKey;clientNonce;serverNonce;constructor(){super()}get summary(){return wd(this)}init(s,n,a){let o=zp(s,a,n,this.keyLength,this.ivLength,this.nonceLength,this.hashAlgorithm);this.clientWriteKey=o.clientWriteKey,this.serverWriteKey=o.serverWriteKey,this.clientNonce=o.clientNonce,this.serverNonce=o.serverNonce}encrypt(s,n,a){let o=s===et.CLIENT,c=o?this.clientNonce:this.serverNonce,d=o?this.clientWriteKey:this.serverWriteKey;if(!c||!d)throw Error();c.writeUInt16BE(a.epoch,this.nonceImplicitLength),c.writeUIntBE(a.sequenceNumber,this.nonceImplicitLength+2,6);let h=c.slice(this.nonceImplicitLength),u=this.encodeAdditionalBuffer(a,n.length),p=Ip(this.blockAlgorithm,d,c,{authTagLength:this.authTagLength});p.setAAD(u,{plaintextLength:n.length});let f=p.update(n),m=p.final(),y=p.getAuthTag();return Buffer.concat([h,f,m,y])}encodeAdditionalBuffer(s,n){let a=Buffer.alloc(13);return a.writeUInt16BE(s.epoch,0),a.writeUintBE(s.sequenceNumber,2,6),a.writeUInt8(s.type,8),a.writeUInt16BE(s.version,9),a.writeUInt16BE(n,11),a}decrypt(s,n,a){let o=s===et.CLIENT,c=o?this.serverNonce:this.clientNonce,d=o?this.serverWriteKey:this.clientWriteKey;if(!c||!d)throw Error();n.subarray(0,this.nonceExplicitLength).copy(c,this.nonceImplicitLength);let u=n.subarray(this.nonceExplicitLength,n.length-this.authTagLength),p=n.subarray(n.length-this.authTagLength),f=this.encodeAdditionalBuffer(a,u.length),m=kp(this.blockAlgorithm,d,c,{authTagLength:this.authTagLength});m.setAuthTag(p),m.setAAD(f,{plaintextLength:u.length});let y=m.update(u);try{let S=m.final();return S.length>0?Buffer.concat([y,S]):y}catch(S){throw qp("decrypt failed",S,s,Dn(n),a,this.summary),S}}},K={TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:49195,TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:49196,TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:49199,TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:49200,TLS_RSA_WITH_AES_128_GCM_SHA256:156,TLS_RSA_WITH_AES_256_GCM_SHA384:157,TLS_PSK_WITH_AES_128_GCM_SHA256:168,TLS_PSK_WITH_AES_256_GCM_SHA384:169,TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256:53249,TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384:53250,TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256:52396,TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256:52393,TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256:52392,TLS_PSK_WITH_CHACHA20_POLY1305_SHA256:52395},hs={K_LEN:16,N_MIN:12,N_MAX:12,P_MAX:68719476705,A_MAX:9007199254740991,C_MAX:68719476721},ls={K_LEN:32,N_MIN:12,N_MAX:12,P_MAX:68719476705,A_MAX:9007199254740991,C_MAX:68719476721},Na=Tp(),Oa=bp(),Ha=Rp(),Fa=Cp(),za=Ep();function Bd(s){switch(s){case K.TLS_RSA_WITH_AES_128_GCM_SHA256:return Le(K.TLS_RSA_WITH_AES_128_GCM_SHA256,"TLS_RSA_WITH_AES_128_GCM_SHA256","aes-128-gcm",Na,hs);case K.TLS_RSA_WITH_AES_256_GCM_SHA384:return Le(K.TLS_RSA_WITH_AES_256_GCM_SHA384,"TLS_RSA_WITH_AES_256_GCM_SHA384","aes-256-gcm",Na,ls,"sha384");case K.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:return Le(K.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,"TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256","aes-128-gcm",Oa,hs);case K.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:return Le(K.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,"TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384","aes-256-gcm",Oa,ls,"sha384");case K.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:return Le(K.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,"TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256","aes-128-gcm",Ha,hs);case K.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:return Le(K.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,"TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384","aes-256-gcm",Ha,ls,"sha384");case K.TLS_PSK_WITH_AES_128_GCM_SHA256:return Le(K.TLS_PSK_WITH_AES_128_GCM_SHA256,"TLS_PSK_WITH_AES_128_GCM_SHA256","aes-128-gcm",Fa,hs,"sha256");case K.TLS_PSK_WITH_AES_256_GCM_SHA384:return Le(K.TLS_PSK_WITH_AES_256_GCM_SHA384,"TLS_PSK_WITH_AES_256_GCM_SHA384","aes-256-gcm",Fa,ls,"sha384");case K.TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256:return Le(K.TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256,"TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256","aes-128-gcm",za,hs,"sha256");case K.TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384:return Le(K.TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384,"TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384","aes-256-gcm",za,ls,"sha384");default:break}return null}function Le(s,n,a,o,c,d="sha256"){let h=new Wp;return h.id=s,h.name=n,h.blockAlgorithm=a,h.kx=o,h.hashAlgorithm=d,h.keyLength=c.K_LEN,h.nonceLength=c.N_MAX,h.nonceImplicitLength=4,h.nonceExplicitLength=8,h.ivLength=h.nonceImplicitLength,h.authTagLength=16,h}function Dd(s){switch(s){case Jt.secp256r1_23:{let{privateKey:n,publicKey:a}=Bp();return{curve:s,privateKey:n,publicKey:a}}case Jt.x25519_29:{let n=Kp("x25519"),a=n.privateKey.export({format:"jwk"}),o=n.publicKey.export({format:"jwk"});return{curve:s,privateKey:Buffer.from(a.d,"base64url"),publicKey:Buffer.from(o.x,"base64url")}}default:throw Error()}}var Hr=class{srtpProfile;static findMatchingSRTPProfile(s,n){for(let a of n)if(s.includes(a))return a}},ni=class{static type=23},{decode:$p,encode:Gp,types:qa}=z,ai=class s{static type=65281;static spec={type:qa.uint16be,data:qa.uint8};type=s.type;data=0;constructor(n={}){Object.assign(this,n)}static createEmpty(){return new s}static deSerialize(n){return new s($p(n,s.spec))}serialize(){return Gp(this,s.spec)}get extension(){return{type:this.type,data:this.serialize().slice(2)}}},{decode:jp,encode:Vp,types:Ri}=z,Zt=class s{static type=14;static spec={type:Ri.uint16be,data:Ri.buffer(Ri.uint16be)};type=s.type;data=Buffer.from([]);profiles=[];mki=Buffer.from([0]);constructor(n={}){Object.assign(this,n)}static create(n,a){return new s({profiles:n,mki:a})}static deSerialize(n){let a=new s(jp(n,s.spec)),o=a.data.readUInt16BE(),c=Array(o/2);for(let d=0;d<c.length;d++)c[d]=a.data.readUInt16BE(d*2+2);return a.profiles=c,a.mki=a.data.slice(o+2),a}serialize(){let n=Buffer.alloc(2);n.writeUInt16BE(this.profiles.length*2);let a=Buffer.concat([n,...this.profiles.map((o)=>{let c=Buffer.alloc(2);return c.writeUInt16BE(o),c}),this.mki]);return this.data=a,Vp(this,s.spec)}static fromData(n){let a=Buffer.alloc(4);return a.writeUInt16BE(s.type),a.writeUInt16BE(n.length,2),s.deSerialize(Buffer.concat([a,n]))}get extension(){return{type:this.type,data:this.serialize().slice(4)}}},{decode:Yp,encode:Qp,types:Wa}=z,Fr=class s{constructor(n){this.certificateList=n}certificateList;msgType=11;messageSeq;static spec={certificateList:Wa.array(ip,Wa.uint24be,"bytes")};static createEmpty(){return new s(void 0)}static deSerialize(n){return new s(...Object.values(Yp(n,s.spec)))}serialize(){return Qp(this,s.spec)}toFragment(){let n=this.serialize();return new ge(this.msgType,n.length,this.messageSeq,0,n.length,n)}},{decode:Xp,encode:Jp,types:Zp}=z,Ud=class s{constructor(n=1){this.type=n}type;static spec={type:Zp.uint8};static createEmpty(){return new s}static deSerialize(n){let{type:a}=Xp(n,s.spec);return new s(a)}serialize(){return Jp(this,s.spec)}},{decode:ef,encode:tf,types:Ci}=z,Od=class s{constructor(n,a){this.algorithm=n,this.signature=a}algorithm;signature;msgType=15;messageSeq;static spec={algorithm:Ci.uint16be,signature:Ci.buffer(Ci.uint16be)};static createEmpty(){return new s(void 0,void 0)}static deSerialize(n){let a=ef(n,s.spec);return new s(...Object.values(a))}serialize(){return tf(this,s.spec)}toFragment(){let n=this.serialize();return new ge(this.msgType,n.length,this.messageSeq,0,n.length,n)}},{decode:sf,encode:rf,types:Ka}=z,Hd=class s{constructor(n){this.publicKey=n}publicKey;msgType=16;messageSeq;static spec={publicKey:Ka.buffer(Ka.uint8)};static createEmpty(){return new s(void 0)}static deSerialize(n){let a=sf(n,s.spec);return new s(...Object.values(a))}serialize(){return rf(this,s.spec)}toFragment(){let n=this.serialize();return new ge(this.msgType,n.length,this.messageSeq,0,n.length,n)}},en=class s{constructor(n){this.verifyData=n}verifyData;msgType=20;messageSeq;static createEmpty(){return new s(void 0)}static deSerialize(n){return new s(n)}serialize(){return this.verifyData}toFragment(){let n=this.serialize();return new ge(this.msgType,n.length,this.messageSeq,0,n.length,n)}},{decode:nf,encode:af,types:Lt}=z,Fd=class s{constructor(n,a,o){this.certificateTypes=n,this.signatures=a,this.authorities=o}certificateTypes;signatures;authorities;msgType=13;messageSeq;static spec={certificateTypes:Lt.array(np,Lt.uint8,"bytes"),signatures:Lt.array(op,Lt.uint16be,"bytes"),authorities:Lt.array(ap,Lt.uint16be,"bytes")};static createEmpty(){return new s(void 0,void 0,void 0)}static deSerialize(n){return new s(...Object.values(nf(n,s.spec)))}serialize(){return af(this,s.spec)}toFragment(){let n=this.serialize();return new ge(this.msgType,n.length,this.messageSeq,0,n.length,n)}},{decode:$a,encode:Ga,types:ir}=z,zd=class s{constructor(n,a,o,c,d,h){this.serverVersion=n,this.random=a,this.sessionId=o,this.cipherSuite=c,this.compressionMethod=d,this.extensions=h}serverVersion;random;sessionId;cipherSuite;compressionMethod;extensions;msgType=2;messageSeq;static spec={serverVersion:Un,random:dt.spec,sessionId:ir.buffer(ir.uint8),cipherSuite:ir.uint16be,compressionMethod:ir.uint8};static createEmpty(){return new s(void 0,void 0,void 0,void 0,void 0,void 0)}static deSerialize(n){let a=$a(n,s.spec),o=new s(...Object.values(a));if(o.serialize().length<n.length)return new s(...Object.values($a(n,{...s.spec,extensions:Ji})));return o}serialize(){return this.extensions===void 0?Ga(this,s.spec):Ga(this,{...s.spec,extensions:Ji})}toFragment(){let n=this.serialize();return new ge(this.msgType,n.length,this.messageSeq,0,n.length,n)}},{decode:of,encode:cf}=z,qd=class s{msgType=14;messageSeq;static spec={};static createEmpty(){return new s}static deSerialize(n){return new s(...Object.values(of(n,s.spec)))}serialize(){return cf(this,s.spec)}toFragment(){let n=this.serialize();return new ge(this.msgType,n.length,this.messageSeq,0,n.length,n)}},{encode:df}=z;function hf(s,n){return df(s,n)}var{decode:lf,types:at}=z,Wd=class s{constructor(n,a,o,c,d,h,u,p){this.ellipticCurveType=n,this.namedCurve=a,this.publicKeyLength=o,this.publicKey=c,this.hashAlgorithm=d,this.signatureAlgorithm=h,this.signatureLength=u,this.signature=p}ellipticCurveType;namedCurve;publicKeyLength;publicKey;hashAlgorithm;signatureAlgorithm;signatureLength;signature;msgType=12;messageSeq;static spec={ellipticCurveType:at.uint8,namedCurve:at.uint16be,publicKeyLength:at.uint8,publicKey:at.buffer((n)=>n.current.publicKeyLength),hashAlgorithm:at.uint8,signatureAlgorithm:at.uint8,signatureLength:at.uint16be,signature:at.buffer((n)=>n.current.signatureLength)};static createEmpty(){return new s(void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0)}static deSerialize(n){let a=lf(n,s.spec);return new s(...Object.values(a))}serialize(){return hf(this,s.spec)}toFragment(){let n=this.serialize();return new ge(this.msgType,n.length,this.messageSeq,0,n.length,n)}};var ft={OneByte:48862,TwoByte:4096},ja=2,Va=4,Ya=8,Qa=12,Xa=4,Ce=class s{version=2;padding=!1;paddingSize=0;extension=!1;marker=!1;payloadOffset=0;payloadType=0;sequenceNumber=0;timestamp=0;ssrc=0;csrcLength=0;csrc=[];extensionProfile=ft.OneByte;extensionLength;extensions=[];constructor(n={}){Object.assign(this,n)}static deSerialize(n){let a=new s,o=0,c=n[o++];a.version=j(c,0,2),a.padding=j(c,2)>0,a.extension=j(c,3)>0,a.csrcLength=j(c,4,4),a.csrc=[...Array(a.csrcLength)].map(()=>{let h=n.readUInt32BE(o);return o+=4,h}),o+=Qa-1;let d=n[1];a.marker=j(d,0)>0,a.payloadType=j(d,1,7),a.sequenceNumber=n.readUInt16BE(ja),a.timestamp=n.readUInt32BE(Va),a.ssrc=n.readUInt32BE(Ya);for(let h=0;h<a.csrc.length;h++){let u=Qa+h*Xa;a.csrc[h]=n.subarray(u).readUInt32BE()}if(a.extension){a.extensionProfile=n.subarray(o).readUInt16BE(),o+=2;let h=n.subarray(o).readUInt16BE()*4;switch(a.extensionLength=h,o+=2,a.extensionProfile){case ft.OneByte:{let u=o+h;while(o<u){if(n[o]===0){o++;continue}let p=n[o]>>4,f=(n[o]&(n[o]^240))+1;if(o++,p===15)break;let m={id:p,payload:n.subarray(o,o+f)};a.extensions=[...a.extensions,m],o+=f}}break;case ft.TwoByte:{let u=o+h;while(o<u){if(n[o]===0){o++;continue}let p=n[o];o++;let f=n[o];o++;let m={id:p,payload:n.subarray(o,o+f)};a.extensions=[...a.extensions,m],o+=f}}break;default:{let u={id:0,payload:n.subarray(o,o+h)};a.extensions=[...a.extensions,u],o+=a.extensions[0].payload.length}break}}if(a.payloadOffset=o,a.padding)a.paddingSize=n[n.length-1];return a}get serializeSize(){let{csrc:n,extensionProfile:a,extensions:o}=this,c=12+n.length*Xa;if(o.length>0||this.extension===!0){let d=4;switch(a){case ft.OneByte:for(let h of o)d+=1+h.payload.length;break;case ft.TwoByte:for(let h of o)d+=2+h.payload.length;break;default:d+=o[0].payload.length}c+=Math.floor((d+3)/4)*4}return c}serialize(n){let a=Buffer.alloc(n),o=0,c=new Br(8);if(c.set(2,0,this.version),this.padding)c.set(1,2,1);if(this.extensions.length>0)this.extension=!0;if(this.extension)c.set(1,3,1);c.set(4,4,this.csrc.length),a.writeUInt8(c.value,o++);let d=new Br(8);if(this.marker)d.set(1,0,1);d.set(7,1,this.payloadType),a.writeUInt8(d.value,o++),a.writeUInt16BE(this.sequenceNumber,ja),o+=2,a.writeUInt32BE(this.timestamp,Va),o+=4,a.writeUInt32BE(this.ssrc,Ya),o+=4;for(let h of this.csrc)a.writeUInt32BE(h,o),o+=4;if(this.extension){let h=o;a.writeUInt16BE(this.extensionProfile,o),o+=4;let u=o;switch(this.extensionProfile){case ft.OneByte:for(let m of this.extensions)a.writeUInt8(m.id<<4|m.payload.length-1,o++),m.payload.copy(a,o),o+=m.payload.length;break;case ft.TwoByte:for(let m of this.extensions)a.writeUInt8(m.id,o++),a.writeUInt8(m.payload.length,o++),m.payload.copy(a,o),o+=m.payload.length;break;default:{let m=this.extensions[0].payload.length;if(m%4!=0)throw Error();this.extensions[0].payload.copy(a,o),o+=m}}let p=o-u,f=Math.trunc((p+3)/4)*4;a.writeUInt16BE(Math.trunc(f/4),h+2);for(let m=0;m<f-p;m++)a.writeUInt8(0,o),o++}return this.payloadOffset=o,a}},fe=class s{constructor(n,a){this.header=n,this.payload=a}header;payload;get serializeSize(){return this.header.serializeSize+this.payload.length}clone(){return new s(new Ce({...this.header}),this.payload)}serialize(){let n=this.header.serialize(this.header.serializeSize+this.payload.length),{payloadOffset:a}=this.header;if(this.payload.copy(n,a),this.header.padding){let o=Buffer.alloc(this.header.paddingSize);o.writeUInt8(this.header.paddingSize,this.header.paddingSize-1),n=Buffer.concat([n,o])}return n}static deSerialize(n){let a=Ce.deSerialize(n);return new s(a,n.subarray(a.payloadOffset,n.length-a.paddingSize))}clear(){this.payload=null}};var yT=_("werift-rtp : packages/rtp/src/codec/av1.ts");var uf={0:"Reserved",1:"OBU_SEQUENCE_HEADER",2:"OBU_TEMPORAL_DELIMITER",3:"OBU_FRAME_HEADER",4:"OBU_TILE_GROUP",5:"OBU_METADATA",6:"OBU_FRAME",7:"OBU_REDUNDANT_FRAME_HEADER",8:"OBU_TILE_LIST",15:"OBU_PADDING"},ST=Object.entries(uf).reduce((s,[n,a])=>(s[a]=Number(n),s),{});var pf=48,ff=49;var mf={BLA_W_LP:16,BLA_W_RADL:17,BLA_N_LP:18,IDR_W_RADL:19,IDR_N_LP:20,CRA_NUT:21},vT={VPS:32,SPS:33,PPS:34,AUD:35,...mf,AP:pf,FU:ff},wT=Buffer.from([0,0,0,1]);var TT=Buffer.from([0,0,0,1]);var gf=13,yf=3;var bT=gf+yf;function Ja(s,n){let a=Buffer.alloc(n);return s.copy(a),a}function zr(s){return Number.parseInt(s.toString(),10)}function Sf(s){let n=s[0];return n>127&&n<192}var tn=4,ut=class s{version=2;padding=!1;count=0;type=0;length=0;constructor(n={}){Object.assign(this,n)}static serialize(n,a,o,c){let h=new s({type:n,count:a,version:2,length:c}).serialize();return Buffer.concat([h,o])}serialize(){let n=new Br(8);if(n.set(2,0,this.version),this.padding)n.set(1,2,1);return n.set(5,3,this.count),W([1,1,2],[n.value,this.type,this.length])}static deSerialize(n){let[a,o,c]=oe(n,[1,1,2]),d=j(a,0,2),h=j(a,2,1)>0,u=j(a,3,5);return new s({version:d,padding:h,count:u,type:o,length:c})}},qr=class s{static count=4;count=s.count;senderSsrc;mediaSsrc;fir=[];constructor(n={}){Object.assign(this,n)}get length(){return this.serialize().length/4}static deSerialize(n){let[a,o]=oe(n,[4,4]),c=[];for(let d=8;d<n.length;d+=8)c.push({ssrc:n.readUInt32BE(d),sequenceNumber:n[d+4]});return new s({senderSsrc:a,mediaSsrc:o,fir:c})}serialize(){let n=W([4,4],[this.senderSsrc,this.mediaSsrc]),a=Buffer.alloc(this.fir.length*8);return this.fir.forEach(({ssrc:o,sequenceNumber:c},d)=>{a.writeUInt32BE(o,d*8),a[d*8+4]=c}),Buffer.concat([n,a])}},Bs=class s{static count=1;count=s.count;length=2;senderSsrc;mediaSsrc;constructor(n={}){Object.assign(this,n)}static deSerialize(n){let[a,o]=oe(n,[4,4]);return new s({senderSsrc:a,mediaSsrc:o})}serialize(){return W([4,4],[this.senderSsrc,this.mediaSsrc])}},Wr=class s{static count=15;length;count=s.count;senderSsrc;mediaSsrc;uniqueID="REMB";ssrcNum=0;brExp;brMantissa;bitrate;ssrcFeedbacks=[];constructor(n={}){Object.assign(this,n)}static deSerialize(n){let[a,o,c,d,h]=oe(n,[4,4,4,1,1]),u=j(h,0,6),p=(j(h,6,2)<<16)+(n[14]<<8)+n[15],f=u>46?18446744073709551615n:BigInt(p)<<BigInt(u),m=[];for(let y=16;y<n.length;y+=4){let S=n.slice(y).readUIntBE(0,4);m.push(S)}return new s({senderSsrc:a,mediaSsrc:o,uniqueID:W([4],[c]).toString(),ssrcNum:d,brExp:u,brMantissa:p,ssrcFeedbacks:m,bitrate:f})}serialize(){let n=Buffer.concat([W([4,4],[this.senderSsrc,this.mediaSsrc]),Buffer.from(this.uniqueID),W([1],[this.ssrcNum])]),a=new Br(24);a.set(6,0,this.brExp).set(18,6,this.brMantissa);let o=Buffer.concat(this.ssrcFeedbacks.map((d)=>W([4],[d]))),c=Buffer.concat([n,W([3],[a.value]),o]);return this.length=c.length/4,c}},vf=_("werift-rtp: /rtcp/psfb/index"),Ms=class s{static type=206;type=s.type;feedback;constructor(n={}){Object.assign(this,n)}serialize(){let n=this.feedback.serialize();return ut.serialize(this.type,this.feedback.count,n,this.feedback.length)}static deSerialize(n,a){let o;switch(a.count){case qr.count:o=qr.deSerialize(n);break;case Bs.count:o=Bs.deSerialize(n);break;case Wr.count:o=Wr.deSerialize(n);break;default:vf("unknown psfb packet",a.count);break}return new s({feedback:o})}},Ds=class s{ssrc=0;reports=[];static type=201;type=s.type;constructor(n={}){Object.assign(this,n)}serialize(){let n=W([4],[this.ssrc]);return n=Buffer.concat([n,...this.reports.map((a)=>a.serialize())]),ut.serialize(s.type,this.reports.length,n,Math.floor(n.length/4))}static deSerialize(n,a){let[o]=oe(n,[4]),c=4,d=[];for(let h=0;h<a;h++)d.push(Nn.deSerialize(n.slice(c,c+24))),c+=24;return new s({ssrc:o,reports:d})}},Nn=class s{ssrc;fractionLost;packetsLost;highestSequence;jitter;lsr;dlsr;constructor(n={}){Object.assign(this,n)}toJSON(){return{ssrc:this.ssrc,fractionLost:this.fractionLost,packetsLost:this.packetsLost,highestSequence:this.highestSequence,jitter:this.jitter,lsr:this.lsr,dlsr:this.dlsr}}serialize(){return W([4,1,3,4,4,4,4],[this.ssrc,this.fractionLost,this.packetsLost,this.highestSequence,this.jitter,this.lsr,this.dlsr])}static deSerialize(n){let[a,o,c,d,h,u,p]=oe(n,[4,1,3,4,4,4,4]);return new s({ssrc:a,fractionLost:o,packetsLost:c,highestSequence:d,jitter:h,lsr:u,dlsr:p})}},Kd=205,Kr=class s{static count=1;count=s.count;header;senderSsrc;mediaSourceSsrc;lost=[];toJSON(){return{lost:this.lost,senderSsrc:this.senderSsrc,mediaSourceSsrc:this.mediaSourceSsrc}}constructor(n={}){if(Object.assign(this,n),!this.header)this.header=new ut({type:Kd,count:this.count,version:2})}static deSerialize(n,a){let[o,c]=oe(n,[4,4]),d=[];for(let h=8;h<n.length;h+=4){let[u,p]=oe(n.subarray(h),[2,2]);d.push(u);for(let f=0;f<16;f++)if(p>>f&1)d.push(u+f+1)}return new s({header:a,senderSsrc:o,mediaSourceSsrc:c,lost:d})}serialize(){let n=W([4,4],[this.senderSsrc,this.mediaSourceSsrc]),a=[];if(this.lost.length>0){let c=this.lost[0],d=0;this.lost.slice(1).forEach((h)=>{let u=h-c-1;if(u>=0&&u<16)d|=1<<u;else a.push(W([2,2],[c,d])),c=h,d=0}),a.push(W([2,2],[c,d]))}let o=Buffer.concat([n,Buffer.concat(a)]);return this.header.length=o.length/4,Buffer.concat([this.header.serialize(),o])}},wf=_("werift/rtp/rtcp/rtpfb/twcc"),$r=class s{static count=15;count=s.count;length=2;senderSsrc;mediaSourceSsrc;baseSequenceNumber;packetStatusCount;referenceTime;fbPktCount;packetChunks=[];recvDeltas=[];header;constructor(n={}){if(Object.assign(this,n),!this.header)this.header=new ut({type:205,count:this.count,version:2})}static deSerialize(n,a){let[o,c,d,h,u,p]=oe(n,[4,4,2,2,3,1]),f=[],m=[],y=16;for(let v=0;v<h;){let g=j(n.slice(y,y+1)[0],0,1),w;switch(g){case 0:{let T=Es.deSerialize(n.slice(y,y+2));w=T;let b=Math.min(h-v,T.runLength);if(T.packetStatus===1||T.packetStatus===2)for(let C=0;C<b;C++)m.push(new wr({type:T.packetStatus}));v+=b}break;case 1:{let T=Tf.deSerialize(n.slice(y,y+2));if(w=T,T.symbolSize===0)T.symbolList.forEach((b)=>{if(b===1)m.push(new wr({type:1}))});if(T.symbolSize===1)T.symbolList.forEach((b)=>{if(b===1||b===2)m.push(new wr({type:b}))});v+=T.symbolList.length}break}if(!w)throw Error();y+=2,f.push(w)}let S=y;return m.forEach((v)=>{if(v.type===1)v.deSerialize(n.slice(S,S+1)),S++;if(v.type===2)v.deSerialize(n.slice(S,S+2)),S+=2}),new s({senderSsrc:o,mediaSourceSsrc:c,baseSequenceNumber:d,packetStatusCount:h,referenceTime:u,fbPktCount:p,recvDeltas:m,packetChunks:f,header:a})}serialize(){let n=W([4,4,2,2,3,1],[this.senderSsrc,this.mediaSourceSsrc,this.baseSequenceNumber,this.packetStatusCount,this.referenceTime,this.fbPktCount]),a=Buffer.concat(this.packetChunks.map((d)=>d.serialize())),o=Buffer.concat(this.recvDeltas.map((d)=>{try{return d.serialize()}catch(h){wf(h?.message);return}}).filter((d)=>d)),c=Buffer.concat([n,a,o]);if(this.header.padding&&c.length%4!==0){let d=4-c.length%4,h=Buffer.alloc(d);return h[h.length-1]=h.length,this.header.length=Math.floor((c.length+h.length)/4),Buffer.concat([this.header.serialize(),c,h])}return this.header.length=Math.floor(c.length/4),Buffer.concat([this.header.serialize(),c])}get packetResults(){let n=this.baseSequenceNumber-1,a=this.packetChunks.filter((h)=>h instanceof Es).flatMap((h)=>h.results(n)),o=0,d=BigInt(this.referenceTime)*64n;for(let h of a){let u=this.recvDeltas[o];if(!h.received||!u)continue;d+=BigInt(u.delta)/1000n,h.delta=u.delta,h.receivedAtMs=Number(d),o++}return a}},Es=class s{type;packetStatus;runLength;constructor(n={}){Object.assign(this,n),this.type=0}static deSerialize(n){let a=j(n[0],1,2),o=(j(n[0],3,5)<<8)+n[1];return new s({type:0,packetStatus:a,runLength:o})}serialize(){return new Gc(16).set(0).set(this.packetStatus,2).set(this.runLength,13).buffer}results(n){let a=this.packetStatus===1||this.packetStatus===2,o=[];for(let c=0;c<=this.runLength;++c)o.push(new bf({sequenceNumber:++n,received:a}));return o}},Tf=class s{type;symbolSize;symbolList=[];constructor(n={}){Object.assign(this,n)}static deSerialize(n){let o=j(n[0],1,1),c=[];function d(h,u){for(let p=0;p<h;p++)u(p)}switch(o){case 0:d(6,(h)=>c.push(j(n[0],2+h,1))),d(8,(h)=>c.push(j(n[1],h,1)));break;case 1:d(3,(h)=>c.push(j(n[0],2+h*2,2))),d(4,(h)=>c.push(j(n[1],h*2,2)));break;default:o=(j(n[0],2,6)<<8)+n[1]}return new s({type:1,symbolSize:o,symbolList:c})}serialize(){let n=Buffer.alloc(2),a=new Gc(16).set(1).set(this.symbolSize),o=this.symbolSize===0?1:2;return this.symbolList.forEach((c)=>{a.set(c,o)}),n.writeUInt16BE(a.value),n}},wr=class s{type;delta;constructor(n={}){Object.assign(this,n)}static deSerialize(n){let a,o;if(n.length===1)a=1,o=250*n[0];else if(n.length===2)a=2,o=250*n.readInt16BE();if(a===void 0||o===void 0)throw Error();return new s({type:a,delta:o})}deSerialize(n){let a=s.deSerialize(n);this.delta=a.delta}parsed=!1;parseDelta(){if(this.delta=Math.floor(this.delta/250),this.delta<0||this.delta>255){if(this.delta>32767)this.delta=32767;if(this.delta<-32768)this.delta=-32768;if(!this.type)this.type=2}else if(!this.type)this.type=1;this.parsed=!0}serialize(){if(!this.parsed)this.parseDelta();if(this.type===1){let n=Buffer.alloc(1);return n.writeUInt8(this.delta),n}else if(this.type===2){let n=Buffer.alloc(2);return n.writeInt16BE(this.delta),n}throw Error("errDeltaExceedLimit "+this.delta+" "+this.type)}};var bf=class{sequenceNumber=0;delta=0;received=!1;receivedAtMs=0;constructor(s){Object.assign(this,s)}},Rf=_("werift-rtp:packages/rtp/rtcp/rtpfb/index"),es=class s{static type=Kd;type=s.type;feedback;header;constructor(n={}){Object.assign(this,n)}serialize(){return this.feedback.serialize()}static deSerialize(n,a){let o;switch(a.count){case Kr.count:o=Kr.deSerialize(n,a);break;case $r.count:o=$r.deSerialize(n,a);break;default:Rf("unknown rtpfb packet",a.count);break}return new s({feedback:o,header:a})}},Gr=class s{static type=202;type=s.type;chunks=[];constructor(n){Object.assign(this,n)}get length(){let n=0;return this.chunks.forEach((a)=>n+=a.length),n}serialize(){let n=Buffer.concat(this.chunks.map((a)=>a.serialize()));while(n.length%4)n=Buffer.concat([n,Buffer.from([0])]);return ut.serialize(this.type,this.chunks.length,n,n.length/4)}static deSerialize(n,a){let o=[];for(let c=0;c<n.length;){let d=$d.deSerialize(n.slice(c));o.push(d),c+=d.length}return new s({chunks:o})}},$d=class s{source;items=[];constructor(n={}){Object.assign(this,n)}get length(){let n=4;return this.items.forEach((a)=>n+=a.length),n+=1,n+=Za(n),n}serialize(){let n=Buffer.concat([W([4],[this.source]),Buffer.concat(this.items.map((o)=>o.serialize()))]);return Buffer.concat([n,Buffer.alloc(Za(n.length))])}static deSerialize(n){let a=n.readUInt32BE(),o=[];for(let c=4;c<n.length;){if(n[c]===0)break;let h=Gd.deSerialize(n.slice(c));o.push(h),c+=h.length}return new s({source:a,items:o})}},Gd=class s{type;text;constructor(n){Object.assign(this,n)}get length(){return 2+Buffer.from(this.text).length}serialize(){let n=Buffer.from(this.text);return Buffer.concat([W([1,1],[this.type,n.length]),n])}static deSerialize(n){let a=n[0],o=n[1],c=n.slice(2,2+o).toString();return new s({type:a,text:c})}};function Za(s){if(s%4==0)return 0;return 4-s%4}var ts=class s{ssrc=0;senderInfo;reports=[];static type=200;type=s.type;constructor(n){Object.assign(this,n)}toJSON(){return{ssrc:this.ssrc,senderInfo:this.senderInfo.toJSON(),reports:this.reports.map((n)=>n.toJSON())}}serialize(){let n=Buffer.alloc(4);return n.writeUInt32BE(this.ssrc),n=Buffer.concat([n,this.senderInfo.serialize()]),n=Buffer.concat([n,...this.reports.map((a)=>a.serialize())]),ut.serialize(s.type,this.reports.length,n,Math.floor(n.length/4))}static deSerialize(n,a){let o=n.readUInt32BE(),c=jd.deSerialize(n.subarray(4,24)),d=24,h=[];for(let p=0;p<a;p++)h.push(Nn.deSerialize(n.subarray(d,d+24))),d+=24;return new s({ssrc:o,senderInfo:c,reports:h})}},jd=class s{ntpTimestamp;rtpTimestamp;packetCount;octetCount;constructor(n={}){Object.assign(this,n)}toJSON(){return{ntpTimestamp:Cf(this.ntpTimestamp),rtpTimestamp:this.rtpTimestamp}}serialize(){return W([8,4,4,4],[this.ntpTimestamp,this.rtpTimestamp,this.packetCount,this.octetCount])}static deSerialize(n){let[a,o,c,d]=oe(n,[8,4,4,4]);return new s({ntpTimestamp:a,rtpTimestamp:o,packetCount:c,octetCount:d})}},Cf=(s)=>{let[n,a]=oe(W([8],[s]),[4,4]);return n+a/4294967296},Ef=_("werift-rtp:packages/rtp/src/rtcp/rtcp.ts"),If=class{static deSerialize(s){let n=0,a=[];while(n<s.length){let o=ut.deSerialize(s.subarray(n,n+tn));n+=tn;let c=s.subarray(n,n+o.length*4);if(n+=o.length*4,o.padding)c=c.subarray(0,c.length-c.subarray(-1)[0]);try{switch(o.type){case ts.type:a.push(ts.deSerialize(c,o.count));break;case Ds.type:a.push(Ds.deSerialize(c,o.count));break;case Gr.type:a.push(Gr.deSerialize(c,o));break;case es.type:a.push(es.deSerialize(c,o));break;case Ms.type:a.push(Ms.deSerialize(c,o));break;default:break}}catch(d){Ef("deSerialize RTCP",d)}}return a}};function kf(s){return s.length>=2&&s[1]>=192&&s[1]<=208}var J={sdesMid:"urn:ietf:params:rtp-hdrext:sdes:mid",sdesRTPStreamID:"urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id",repairedRtpStreamId:"urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id",transportWideCC:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",absSendTime:"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time",dependencyDescriptor:"https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension",audioLevelIndication:"urn:ietf:params:rtp-hdrext:ssrc-audio-level",videoOrientation:"urn:3gpp:video-orientation"};function Pf(s,n){return s.map((a)=>{let o=n[a.id];if(!o)return{uri:"unknown",value:a.payload};switch(o){case J.sdesMid:case J.sdesRTPStreamID:case J.repairedRtpStreamId:return{uri:o,value:Df(a.payload)};case J.transportWideCC:return{uri:o,value:Uf(a.payload)};case J.absSendTime:return{uri:o,value:Nf(a.payload)};case J.audioLevelIndication:return{uri:o,value:Of(a.payload)};case J.videoOrientation:return{uri:o,value:Hf(a.payload)};default:return{uri:o,value:a.payload}}}).reduce((a,o)=>{if(o)a[o.uri]=o.value;return a},{})}function Af(s){return Buffer.from(s)}function xf(s){return Buffer.from(s)}function Lf(s){return Buffer.from(s)}function Bf(s){return W([2],[s])}function Mf(s){let n=Buffer.alloc(3),a=s>>14n&0x00ffffffn;return n.writeUIntBE(Number(a),0,3),n}function Df(s){return s.toString()}function Uf(s){return s.readUInt16BE()}function Nf(s){return oe(s,[3])[0]}function Of(s){let n=new Rs(s);return{v:n.readBits(1)===1,level:n.readBits(7)}}function Hf(s){let n=new Rs(s);return n.readBits(4),{c:n.readBits(1),f:n.readBits(1),r1:n.readBits(1),r0:n.readBits(1)}}var Ff=_("packages/rtp/src/rtp/red/packet.ts"),Vd=class s{header;blocks=[];static deSerialize(n){let a=n instanceof ArrayBuffer?Buffer.from(n):n,o=new s,c=0;return[o.header,c]=eo.deSerialize(a),o.header.fields.forEach(({blockLength:d,timestampOffset:h,blockPT:u})=>{if(d&&h){let p=a.subarray(c,c+d);o.blocks.push({block:p,blockPT:u,timestampOffset:h}),c+=d}else{let p=a.subarray(c);o.blocks.push({block:p,blockPT:u})}}),o}serialize(){this.header=new eo;for(let{timestampOffset:a,blockPT:o,block:c}of this.blocks)if(a)this.header.fields.push({fBit:1,blockPT:o,blockLength:c.length,timestampOffset:a});else this.header.fields.push({fBit:0,blockPT:o});let n=this.header.serialize();for(let{block:a}of this.blocks)n=Buffer.concat([n,a]);return n}},eo=class s{fields=[];static deSerialize(n){let a=0,o=new s;for(;;){let c={};o.fields.push(c);let d=new Rs(n.subarray(a));if(c.fBit=d.readBits(1),c.blockPT=d.readBits(7),a++,c.fBit===0)break;c.timestampOffset=d.readBits(14),c.blockLength=d.readBits(10),a+=3}return[o,a]}serialize(){let n=Buffer.alloc(0);for(let a of this.fields)try{if(a.timestampOffset&&a.blockLength){let o=new Rs(Buffer.alloc(4)).writeBits(1,a.fBit).writeBits(7,a.blockPT).writeBits(14,a.timestampOffset).writeBits(10,a.blockLength);n=Buffer.concat([n,o.uint8Array])}else{let o=new Rs(Buffer.alloc(1)).writeBits(1,0).writeBits(7,a.blockPT);n=Buffer.concat([n,o.uint8Array])}}catch(o){Ff(o?.message)}return n}},zf=class{constructor(s=1){this.distance=s}distance;cache=[];cacheSize=10;push(s){if(this.cache.push(s),this.cache.length>this.cacheSize)this.cache.shift()}build(){let s=new Vd,n=this.cache.slice(-(this.distance+1)),a=n.pop();if(!a)return s;return n.forEach((o)=>{let c=Xt(a.timestamp,-o.timestamp);if(c>qf)return;s.blocks.push({block:o.block,blockPT:o.blockPT,timestampOffset:c})}),s.blocks.push({block:a.block,blockPT:a.blockPT}),s}},qf=16383,Wf=class{size=150;sequenceNumbers=[];push(s,n){let a=[];return s.blocks.forEach(({blockPT:c,timestampOffset:d,block:h},u)=>{let p=ae(n.header.sequenceNumber,-(s.blocks.length-(u+1)));if(d)a.push(new fe(new Ce({timestamp:Xt(n.header.timestamp,-d),payloadType:c,ssrc:n.header.ssrc,sequenceNumber:p,marker:!0}),h));else a.push(new fe(new Ce({timestamp:n.header.timestamp,payloadType:c,ssrc:n.header.ssrc,sequenceNumber:p,marker:!0}),h))}),a.filter((c)=>{if(this.sequenceNumbers.includes(c.header.sequenceNumber))return!1;else{if(this.sequenceNumbers.length>this.size)this.sequenceNumbers.shift();return this.sequenceNumbers.push(c.header.sequenceNumber),!0}})}};function Kf(s,n,a){return new fe(new Ce({payloadType:n,marker:s.header.marker,sequenceNumber:s.payload.readUInt16BE(0),timestamp:s.header.timestamp,ssrc:a}),s.payload.subarray(2))}function $f(s,n,a,o){let c=Buffer.allocUnsafe(2);return c.writeUInt16BE(s.header.sequenceNumber,0),new fe(new Ce({payloadType:n,marker:s.header.marker,sequenceNumber:a,timestamp:s.header.timestamp,ssrc:o,csrc:s.header.csrc,extensions:s.header.extensions}),Buffer.concat([c,s.payload]))}var oi=1,js=7;var Gf=(s)=>{switch(s){case oi:case js:return 16}},jf=(s)=>{switch(s){case oi:return 14;case js:return 12}},Et=class extends Error{constructor(s){super(s);this.name="SrtpAuthenticationError"}},io=12,Qf=8;function On(s,n,a="Failed to authenticate SRTP packet"){let o=s.length-n;Us(s.length>=io+n,a);let c=Qd(()=>Ce.deSerialize(s.subarray(0,o)),a);return c.paddingSize=0,Us(c.payloadOffset>=io&&c.payloadOffset<=o,a),c}function Yd(s,n,a,o="Failed to authenticate SRTCP packet"){return Us(s.length>=Qf+n+a,o),Qd(()=>ut.deSerialize(s.subarray(0,tn)),o)}function Us(s,n){if(!s)throw new Et(n)}function Qd(s,n){try{return s()}catch{throw new Et(n)}}function Xd(s,n,a="Failed to authenticate SRTP packet"){if(!s.padding)return s.paddingSize=0,s;Us(n.length>s.payloadOffset,a);let o=n[n.length-1];return Us(o>0&&o<=n.length-s.payloadOffset,a),s.paddingSize=o,s}var Jd=class{constructor(s,n,a,o){this.srtpSessionKey=s,this.srtpSessionSalt=n,this.srtcpSessionKey=a,this.srtcpSessionSalt=o}srtpSessionKey;srtpSessionSalt;srtcpSessionKey;srtcpSessionSalt;encryptRtp(s,n,a){return Buffer.from([])}decryptRtp(s,n,a){return[]}encryptRTCP(s,n){return Buffer.from([])}decryptRTCP(s){return[]}},Xf=class extends Jd{constructor(s,n,a,o,c,d){super(s,n,a,o);this.srtpSessionAuthTag=c,this.srtcpSessionAuthTag=d}srtpSessionAuthTag;srtcpSessionAuthTag;authTagLength=10;encryptRtp(s,n,a){let o=s.serialize(s.serializeSize),c=this.generateCounter(s.sequenceNumber,a,s.ssrc,this.srtpSessionSalt),h=to("aes-128-ctr",this.srtpSessionKey,c).update(n),u=this.generateSrtpAuthTag(a,o,h);return Buffer.concat([o,h,u])}decryptRtp(s,n,a=On(s,this.authTagLength)){let o=s.length-this.authTagLength,c=s.subarray(0,o),d=s.subarray(o),h=this.generateSrtpAuthTag(n,c.subarray(0,a.payloadOffset),c.subarray(a.payloadOffset));ao(d,h,"Failed to authenticate SRTP packet");let u=this.generateCounter(a.sequenceNumber,n,a.ssrc,this.srtpSessionSalt),p=so("aes-128-ctr",this.srtpSessionKey,u),f=c.subarray(a.payloadOffset),m=p.update(f),y=Buffer.concat([c.subarray(0,a.payloadOffset),m]);return[y,Xd(a,y,"Failed to authenticate SRTP packet")]}encryptRTCP(s,n){let a=Buffer.from(s),o=a.readUInt32BE(4),c=this.generateCounter(n&65535,n>>16,o,this.srtcpSessionSalt);to("aes-128-ctr",this.srtcpSessionKey,c).update(a.slice(8)).copy(a,8),a=Buffer.concat([a,Buffer.alloc(4)]),a.writeUInt32BE(n,a.length-4),a[a.length-4]|=128;let u=this.generateSrtcpAuthTag(a);return a=Buffer.concat([a,u]),a}decryptRTCP(s){let n=Yd(s,this.authTagLength,no),a=s.length-(this.authTagLength+no),o=s.subarray(0,s.length-this.authTagLength),c=s.subarray(s.length-this.authTagLength),d=this.generateSrtcpAuthTag(o);ao(c,d,"Failed to authenticate SRTCP packet");let h=Buffer.from(s).slice(0,a);if(s[a]>>>7===0)return[h,n];let p=s.readUInt32BE(a);p&=2147483647;let f=s.readUInt32BE(4),m=this.generateCounter(p&65535,p>>16,f,this.srtcpSessionSalt);return so("aes-128-ctr",this.srtcpSessionKey,m).update(h.subarray(8)).copy(h,8),[h,n]}generateSrtcpAuthTag(s){return ro("sha1",this.srtcpSessionAuthTag).update(s).digest().slice(0,10)}generateCounter(s,n,a,o){let c=Buffer.alloc(16);c.writeUInt32BE(a,4),c.writeUInt32BE(n,8),c.writeUInt32BE(Number(BigInt(s)<<16n),12);for(let d=0;d<o.length;d++)c[d]^=o[d];return c}generateSrtpAuthTag(s,...n){let a=ro("sha1",this.srtpSessionAuthTag),o=Buffer.alloc(4);o.writeUInt32BE(s);for(let c of n)a.update(c);return a.update(o).digest().subarray(0,10)}},no=4;function ao(s,n,a){if(s.length!==n.length||!Yf(s,n))throw new Et(a)}var Jf=class extends Jd{aeadAuthTagLen=16;rtpIvWriter=vr([2,4,4,2],!0);rtcpIvWriter=vr([2,4,2,4],!0);aadWriter=vr([4],!0);constructor(s,n,a,o){super(s,n,a,o)}encryptRtp(s,n,a){let o=s.serialize(s.serializeSize),c=this.rtpInitializationVector(s,a),d=oo("aes-128-gcm",this.srtpSessionKey,c);d.setAAD(o);let h=d.update(n);d.final();let u=d.getAuthTag();return Buffer.concat([o,h,u])}decryptRtp(s,n,a=On(s,this.aeadAuthTagLen)){let o=s.subarray(0,a.payloadOffset),c=s.length-this.aeadAuthTagLen,d=s.subarray(c),h=Buffer.from([]);h=Ja(h,s.length-this.aeadAuthTagLen),o.copy(h);let u=this.rtpInitializationVector(a,n),p=s.slice(a.payloadOffset,c),f=co("aes-128-gcm",this.srtpSessionKey,u);f.setAAD(o),f.setAuthTag(d);let m=f.update(p);return lo(f,"SRTP"),m.copy(h,a.payloadOffset),[h,Xd(a,h,"Failed to authenticate SRTP packet")]}encryptRTCP(s,n){let a=s.readUInt32BE(4),o=s.length+this.aeadAuthTagLen,c=Buffer.from([]);c=Ja(c,o+Ii),s.slice(0,8).copy(c);let d=this.rtcpInitializationVector(a,n),h=this.rtcpAdditionalAuthenticatedData(s,n),u=oo("aes-128-gcm",this.srtcpSessionKey,d);u.setAAD(h);let p=u.update(s.slice(8));return u.final(),p.copy(c,8),u.getAuthTag().copy(c,8+p.length),h.slice(8,12).copy(c,o),c}decryptRTCP(s){let n=Yd(s,this.aeadAuthTagLen,Ii),a=s.length-Ii,o=a-this.aeadAuthTagLen,c=s.readUInt32BE(4),d=s.readUInt32BE(a),h=d>>>31===1,u=d&~(ho<<24),p=this.rtcpInitializationVector(c,u),f=h?Buffer.concat([s.subarray(0,8),s.subarray(a)]):Buffer.concat([s.subarray(0,o),s.subarray(a)]),m=h?s.slice(8,o):Buffer.alloc(0),y=h?Buffer.alloc(o):Buffer.from(s.subarray(0,o));if(h)s.slice(0,8).copy(y);let S=co("aes-128-gcm",this.srtcpSessionKey,p);S.setAAD(f),S.setAuthTag(s.subarray(o,a));let v=S.update(m);if(lo(S,"SRTCP"),h)v.copy(y,8);return[y,n]}rtpInitializationVector(s,n){let a=this.rtpIvWriter([0,s.ssrc,n,s.sequenceNumber]);for(let o=0;o<a.length;o++)a[o]^=this.srtpSessionSalt[o];return a}rtcpInitializationVector(s,n){let a=this.rtcpIvWriter([0,s,0,n]);for(let o=0;o<a.length;o++)a[o]^=this.srtcpSessionSalt[o];return a}rtcpAdditionalAuthenticatedData(s,n){let a=Buffer.concat([s.subarray(0,8),this.aadWriter([n])]);return a[8]|=ho,a}},Ii=4,ho=128;function lo(s,n){try{s.final()}catch{throw new Et(`Failed to authenticate ${n} packet`)}}function nr(s,n){let a=Vf("aes-128-ecb",s,Buffer.alloc(0));return a.setAutoPadding(!1),Buffer.concat([a.update(n),a.final()])}var Zd=class{constructor(s,n,a){this.masterKey=s,this.masterSalt=n,this.profile=a;{let o=14-n.length;if(o>0)this.masterSalt=Buffer.concat([n,Buffer.alloc(o)])}switch(this.srtpSessionKey=this.generateSessionKey(0),this.srtpSessionSalt=this.generateSessionSalt(2),this.srtpSessionAuthTag=this.generateSessionAuthTag(1),this.srtpSessionAuth=Ei("sha1",this.srtpSessionAuthTag),this.srtcpSessionKey=this.generateSessionKey(3),this.srtcpSessionSalt=this.generateSessionSalt(5),this.srtcpSessionAuthTag=this.generateSessionAuthTag(4),this.srtcpSessionAuth=Ei("sha1",this.srtcpSessionAuthTag),a){case oi:this.cipher=new Xf(this.srtpSessionKey,this.srtpSessionSalt,this.srtcpSessionKey,this.srtcpSessionSalt,this.srtpSessionAuthTag,this.srtcpSessionAuthTag);break;case js:this.cipher=new Jf(this.srtpSessionKey,this.srtpSessionSalt,this.srtcpSessionKey,this.srtcpSessionSalt);break}}masterKey;masterSalt;profile;srtpSSRCStates={};srtpSessionKey;srtpSessionSalt;srtpSessionAuthTag;srtpSessionAuth;srtcpSSRCStates={};srtcpSessionKey;srtcpSessionSalt;srtcpSessionAuthTag;srtcpSessionAuth;cipher;generateSessionKey(s){let n=Buffer.from(this.masterSalt),a=Buffer.from([s,0,0,0,0,0,0]);for(let o=a.length-1,c=n.length-1;o>=0;o--,c--)n[c]=n[c]^a[o];return n=Buffer.concat([n,Buffer.from([0,0])]),nr(this.masterKey,n)}generateSessionSalt(s){let n=Buffer.from(this.masterSalt),a=Buffer.from([s,0,0,0,0,0,0]);for(let o=a.length-1,c=n.length-1;o>=0;o--,c--)n[c]=n[c]^a[o];return n=Buffer.concat([n,Buffer.from([0,0])]),n=nr(this.masterKey,n),n.subarray(0,14)}generateSessionAuthTag(s){let n=Buffer.from(this.masterSalt),a=Buffer.from([s,0,0,0,0,0,0]);for(let d=a.length-1,h=n.length-1;d>=0;d--,h--)n[h]=n[h]^a[d];let o=Buffer.concat([n,Buffer.from([0,0])]),c=Buffer.concat([n,Buffer.from([0,1])]);return o=nr(this.masterKey,o),c=nr(this.masterKey,c),Buffer.concat([o,c.subarray(0,4)])}getSrtpSsrcState(s){let n=this.srtpSSRCStates[s];if(n)return n;return n={ssrc:s,rolloverCounter:0,lastSequenceNumber:0},this.srtpSSRCStates[s]=n,n}getSrtcpSsrcState(s){let n=this.srtcpSSRCStates[s];if(n)return n;return n={srtcpIndex:0,ssrc:s},this.srtcpSSRCStates[s]=n,n}estimateRolloverCounter(s,n){let a=tm(s,n);if(a<0)return 0;if(a>em)throw new eh(n.ssrc);return a}commitPacketIndex(s,n,a){if(!a.rolloverHasProcessed){a.rolloverHasProcessed=!0,a.rolloverCounter=n,a.lastSequenceNumber=s;return}let o=uo(n,s)-uo(a.rolloverCounter,a.lastSequenceNumber);if(o>0&&o<=Tr)a.rolloverCounter=n,a.lastSequenceNumber=s}updateRolloverCount(s,n){let a=this.estimateRolloverCounter(s,n);return this.commitPacketIndex(s,a,n),a}generateSrtpAuthTag(s,n){this.srtpSessionAuth=Ei("sha1",this.srtpSessionAuthTag);let a=Buffer.alloc(4);return a.writeUInt32BE(n),this.srtpSessionAuth.update(s).update(a).digest().slice(0,10)}index(s){let n=this.srtcpSSRCStates[s];if(!n)return 0;return n.srtcpIndex}setIndex(s,n){let a=this.getSrtcpSsrcState(s);a.srtcpIndex=n%2147483647}},eh=class extends Error{constructor(s){super(`SRTP rollover counter exhausted for ssrc ${s}, re-keying required`);this.name="SrtpRolloverCounterOverflowError"}},Zf=65536,Tr=32768,em=4294967295,uo=(s,n)=>s*Zf+n,tm=(s,n)=>{if(!n.rolloverHasProcessed)return 0;let{rolloverCounter:a,lastSequenceNumber:o}=n;if(o<Tr)return s-o>Tr?a-1:a;return o-Tr>s?a+1:a},sm=class extends Zd{constructor(s,n,a){super(s,n,a)}encryptRTCP(s){let n=s.readUInt32BE(4),a=this.getSrtcpSsrcState(n);if(a.srtcpIndex++,a.srtcpIndex>>rm)a.srtcpIndex=0;return this.cipher.encryptRTCP(s,a.srtcpIndex)}decryptRTCP(s){return this.cipher.decryptRTCP(s)}},rm=2147483647,th=class{constructor(s){this.ContextCls=s}ContextCls;localContext;remoteContext;onData;start(s,n,a,o,c){this.localContext=new this.ContextCls(s,n,c),this.remoteContext=new this.ContextCls(a,o,c)}},im=class extends th{constructor(s){super(sm);this.config=s,this.start(s.keys.localMasterKey,s.keys.localMasterSalt,s.keys.remoteMasterKey,s.keys.remoteMasterSalt,s.profile)}config;decrypt=(s)=>{let[n]=this.remoteContext.decryptRTCP(s);return n};encrypt(s){return this.localContext.encryptRTCP(s)}},nm=class extends Zd{constructor(s,n,a){super(s,n,a)}encryptRtp(s,n){let a=this.getSrtpSsrcState(n.ssrc),o=this.estimateRolloverCounter(n.sequenceNumber,a),c=this.cipher.encryptRtp(n,s,o);return this.commitPacketIndex(n.sequenceNumber,o,a),c}decryptRtp(s){let n=On(s,this.rtpAuthTagLength),a=this.srtpSSRCStates[n.ssrc],o=a??{ssrc:n.ssrc,rolloverCounter:0,lastSequenceNumber:0},c;try{c=this.estimateRolloverCounter(n.sequenceNumber,o)}catch(h){if(h instanceof eh)throw new Et(h.message);throw h}let d=this.cipher.decryptRtp(s,c,n);if(!a)this.srtpSSRCStates[n.ssrc]=o;return this.commitPacketIndex(n.sequenceNumber,c,o),d}get rtpAuthTagLength(){return this.profile===js?16:10}},am=class extends th{constructor(s){super(nm);this.config=s,this.start(s.keys.localMasterKey,s.keys.localMasterSalt,s.keys.remoteMasterKey,s.keys.remoteMasterSalt,s.profile)}config;decrypt=(s)=>{let[n]=this.remoteContext.decryptRtp(s);return n};encrypt(s,n){return this.localContext.encryptRtp(s,n)}};var se=_("werift-dtls : packages/dtls/src/flight/client/flight5.ts : log"),om=class extends qs{constructor(s,n,a,o){super(s,n,5,7);this.cipher=a,this.srtp=o}cipher;srtp;handleHandshake(s){this.dtls.bufferHandshakeCache([s],!1,4);let n=(()=>{switch(s.msg_type){case 2:return zd.deSerialize(s.fragment);case 11:return Fr.deSerialize(s.fragment);case 12:return Wd.deSerialize(s.fragment);case 13:return Fd.deSerialize(s.fragment);case 14:return qd.deSerialize(s.fragment)}})();if(n)is[n.msgType]({dtls:this.dtls,cipher:this.cipher,srtp:this.srtp})(n)}async exec(){if(this.dtls.flight===5){se(this.dtls.sessionId,"flight5 twice"),this.send(this.dtls.lastMessage);return}this.dtls.flight=5;let s=this.dtls.requestedCertificateTypes.length>0;se(this.dtls.sessionId,"send flight5",s);let n=[s&&this.sendCertificate(),this.sendClientKeyExchange(),s&&this.sendCertificateVerify(),this.sendChangeCipherSpec(),this.sendFinished()].filter((a)=>a);this.dtls.lastMessage=n,await this.transmit(n)}sendCertificate(){let s=new Fr([Buffer.from(this.cipher.localCert)]),n=this.createPacket([s]);return Buffer.concat(n.map((o)=>o.serialize()))}sendClientKeyExchange(){if(!this.cipher.localKeyPair)throw Error();let s=new Hd(this.cipher.localKeyPair.publicKey),n=this.createPacket([s]),a=Buffer.concat(n.map((u)=>u.serialize())),o=this.cipher.localKeyPair,c=this.cipher.remoteKeyPair;if(!c.publicKey)throw Error("not exist");let d=Pd(c.publicKey,o.privateKey,o.curve);se(this.dtls.sessionId,"extendedMasterSecret",this.dtls.options.extendedMasterSecret,this.dtls.remoteExtendedMasterSecret);let h=Buffer.concat(this.dtls.sortedHandshakeCache.map((u)=>u.serialize()));return this.cipher.masterSecret=this.dtls.options.extendedMasterSecret&&this.dtls.remoteExtendedMasterSecret?xd(d,h):Ad(d,this.cipher.localRandom.serialize(),this.cipher.remoteRandom.serialize()),this.cipher.cipher=Bd(this.cipher.cipherSuite),this.cipher.cipher.init(this.cipher.masterSecret,this.cipher.remoteRandom.serialize(),this.cipher.localRandom.serialize()),se(this.dtls.sessionId,"cipher",this.cipher.cipher.summary),a}sendCertificateVerify(){let s=Buffer.concat(this.dtls.sortedHandshakeCache.map((h)=>h.serialize())),n=this.cipher.signatureData(s,"sha256"),a=(()=>{switch(this.cipher.signatureHashAlgorithm?.signature){case Ue.ecdsa_3:return La.ecdsa_secp256r1_sha256;case Ue.rsa_1:return La.rsa_pkcs1_sha256}})();if(!a)throw Error();se(this.dtls.sessionId,"signatureScheme",this.cipher.signatureHashAlgorithm?.signature,a);let o=new Od(a,n),c=this.createPacket([o]);return Buffer.concat(c.map((h)=>h.serialize()))}sendChangeCipherSpec(){let s=Ud.createEmpty().serialize(),n=zs(this.dtls)([{type:20,fragment:s}],++this.dtls.recordSequenceNumber);return Buffer.concat(n.map((o)=>o.serialize()))}sendFinished(){let s=Buffer.concat(this.dtls.sortedHandshakeCache.map((d)=>d.serialize())),n=this.cipher.verifyData(s),a=new en(n);this.dtls.epoch=1;let[o]=this.createPacket([a]);this.dtls.recordSequenceNumber=0;let c=this.cipher.encryptPacket(o).serialize();return se(this.dtls.sessionId,"finished",this.cipher.cipher.summary),c}},is={};is[2]=({cipher:s,srtp:n,dtls:a})=>(o)=>{if(se(a.sessionId,"serverHello",o.cipherSuite),s.remoteRandom=dt.from(o.random),s.cipherSuite=o.cipherSuite,se(a.sessionId,"selected cipherSuite",s.cipherSuite),o.extensions)o.extensions.forEach((c)=>{switch(c.type){case Zt.type:{let d=Zt.fromData(c.data),h=Hr.findMatchingSRTPProfile(d.profiles,a.options.srtpProfiles||[]);if(se(a.sessionId,"selected srtp profile",h),h==null)return;n.srtpProfile=h}break;case ni.type:a.remoteExtendedMasterSecret=!0;break;case ai.type:se(a.sessionId,"RenegotiationIndication");break}})};is[11]=({cipher:s,dtls:n})=>(a)=>{se(n.sessionId,"handshake certificate",a),s.remoteCertificate=a.certificateList[0]};is[12]=({cipher:s,dtls:n})=>(a)=>{if(!s.localRandom||!s.remoteRandom)throw Error();se(n.sessionId,"ServerKeyExchange",a),se(n.sessionId,"selected curve",a.namedCurve),s.remoteKeyPair={curve:a.namedCurve,publicKey:a.publicKey},s.localKeyPair=Dd(a.namedCurve)};is[13]=({dtls:s})=>(n)=>{se(s.sessionId,"certificate_request",n),s.requestedCertificateTypes=n.certificateTypes,s.requestedSignatureAlgorithms=n.signatures};is[14]=({dtls:s})=>(n)=>{se(s.sessionId,"server_hello_done",n)};var{decode:cm,encode:dm,types:po}=z,sh=class s{constructor(n,a){this.serverVersion=n,this.cookie=a}serverVersion;cookie;msgType=3;messageSeq;static spec={serverVersion:Un,cookie:po.buffer(po.uint8)};static createEmpty(){return new s(void 0,void 0)}static deSerialize(n){return new s(...Object.values(cm(n,s.spec)))}serialize(){return dm(this,s.spec)}get version(){return{major:255-this.serverVersion.major,minor:255-this.serverVersion.minor}}toFragment(){let n=this.serialize();return new ge(this.msgType,n.length,this.messageSeq,0,n.length,n)}},ym={"ecdsa-sha256":{identifier:Ne(Nr("1.2.840.10045.4.3.2")),hash:"sha256"},"rsa-sha256":{identifier:Ne(Nr("1.2.840.113549.1.1.11"),ju()),hash:"sha256"}},Sm={C:"2.5.4.6",ST:"2.5.4.8",L:"2.5.4.7",O:"2.5.4.10",OU:"2.5.4.11",CN:"2.5.4.3"};function vm(s){return Ne(...s.map(([n,a])=>$u(Ne(Nr(Sm[n]),n==="C"?Yu(a):Vu(a)))))}function wm({publicKey:s,privateKey:n,signatureAlgorithm:a,name:o,notBefore:c,notAfter:d,serialNumber:h=mm(8)}){let{identifier:u,hash:p}=ym[a],f=vm(o),m=Ne(Gu(0,Xi(2)),Xi(h),u,f,Ne(Ma(c),Ma(d)),f,s.export({type:"spki",format:"der"})),y=gm(p,m,n),S=Ne(m,u,vd(y));return Qu("CERTIFICATE",S)}var{encode:Tm,types:ki}=z,mo=fm(um),jr=class{constructor(s,n,a,o){if(this.sessionType=s,this.certPem=n,this.keyPem=a,n&&a&&o)this.parseX509(n,a,o)}sessionType;certPem;keyPem;localRandom;remoteRandom;cipherSuite;remoteCertificate;remoteKeyPair;localKeyPair;masterSecret;cipher;namedCurve;signatureHashAlgorithm;localCert;localPrivateKey;static createSelfSignedCertificateWithKey=async(s,n)=>{if(s.hash!==Ur.sha256_4)throw Error(`unsupported hash algorithm: ${s.hash}`);let{publicKey:a,privateKey:o}=await(()=>{switch(s.signature){case Ue.rsa_1:return mo("rsa",{modulusLength:2048,publicExponent:65537});case Ue.ecdsa_3:return mo("ec",{namedCurve:"P-256"});default:throw Error(`unsupported signature algorithm: ${s.signature}`)}})(),c=new Date,d=wm({publicKey:a,privateKey:o,signatureAlgorithm:s.signature===Ue.ecdsa_3?"ecdsa-sha256":"rsa-sha256",name:[["C","AU"],["ST","Some-State"],["O","Internet Widgits Pty Ltd"]],notBefore:c,notAfter:new Date(c.getTime()+315360000000)}),h=o.export({type:"pkcs8",format:"pem"});return{certPem:d,keyPem:h,signatureHash:s}};encryptPacket(s){let n=s.recordLayerHeader,a=n.protocolVersion.major<<8|n.protocolVersion.minor,o=this.cipher.encrypt(this.sessionType,s.fragment,{type:n.contentType,version:a,epoch:n.epoch,sequenceNumber:n.sequenceNumber});return s.fragment=o,s.recordLayerHeader.contentLen=o.length,s}decryptPacket(s){let n=s.recordLayerHeader,a=n.protocolVersion.major<<8|n.protocolVersion.minor;return this.cipher.decrypt(this.sessionType,s.fragment,{type:n.contentType,version:a,epoch:n.epoch,sequenceNumber:n.sequenceNumber})}verifyData(s){if(this.sessionType===et.CLIENT)return Hp(this.masterSecret,s);else return Fp(this.masterSecret,s)}signatureData(s,n){return fo(n).update(s).sign(this.localPrivateKey)}generateKeySignature(s){let n=this.sessionType===et.CLIENT?this.localRandom:this.remoteRandom,a=this.sessionType===et.SERVER?this.localRandom:this.remoteRandom,o=this.valueKeySignature(n.serialize(),a.serialize(),this.localKeyPair.publicKey,this.namedCurve);return fo(s).update(o).sign(this.localPrivateKey)}parseX509(s,n,a){this.localCert=new pm(Vr(s)).raw,this.localPrivateKey=lm(Vr(n)),this.signatureHashAlgorithm=a}valueKeySignature(s,n,a,o){let c=Tm({type:yd.named_curve_3,curve:o,len:a.length},{type:ki.uint8,curve:ki.uint16be,len:ki.uint8});return Buffer.concat([s,n,c,a])}};function Vr(s){return`${s.split(/\r?\n/).map((n)=>n.trim()).filter((n)=>n.length>0).join(`
7
+ `)}
8
+ `}var bm=_("werift-dtls : packages/dtls/src/context/dtls.ts : log"),go=class{constructor(s,n){this.options=s,this.sessionType=n}options;sessionType;version={major:254,minor:253};lastFlight=[];lastMessage=[];recordSequenceNumber=0;sequenceNumber=0;epoch=0;flight=0;handshakeCache={};cookie;requestedCertificateTypes=[];requestedSignatureAlgorithms=[];remoteExtendedMasterSecret=!1;get sessionId(){return this.cookie?this.cookie.toString("hex").slice(0,10):""}get sortedHandshakeCache(){return Object.entries(this.handshakeCache).sort(([s],[n])=>Number(s)-Number(n)).flatMap(([,{data:s}])=>s.sort((n,a)=>n.message_seq-a.message_seq))}checkHandshakesExist=(s)=>!s.find((n)=>this.sortedHandshakeCache.find((a)=>a.msg_type===n)==null);bufferHandshakeCache(s,n,a){if(!this.handshakeCache[a])this.handshakeCache[a]={data:[],isLocal:n,flight:a};let o=s.filter((c)=>{let d=this.handshakeCache[a].data.find((h)=>h.msg_type===c.msg_type);if(d)return bm(this.sessionId,"exist",d.summary,n,a),!1;return!0});this.handshakeCache[a].data=[...this.handshakeCache[a].data,...o]}},Rm=class{constructor(s){this.socket=s}socket;closing=new AbortController;send=(s,n)=>this.socket.send(s,n);get closedSignal(){return this.closing.signal}close(){return this.closing.abort(),this.socket.close()}},{decode:yo,encode:Cm,types:ar}=z,sn=class s{static type=10;static spec={type:ar.uint16be,data:ar.array(ar.uint16be,ar.uint16be,"bytes")};type=s.type;data=[];constructor(n={}){Object.assign(this,n)}static createEmpty(){return new s}static fromData(n){return new s({type:s.type,data:yo(n,s.spec.data)})}static deSerialize(n){return new s(yo(n,s.spec))}serialize(){return Cm(this,s.spec)}get extension(){return{type:this.type,data:this.serialize().slice(2)}}},{decode:Em,encode:Im,types:us}=z,rn=class s{static type=13;static spec={type:us.uint16be,data:us.array({hash:us.uint8,signature:us.uint8},us.uint16be,"bytes")};type=s.type;data=[];constructor(n={}){Object.assign(this,n)}static createEmpty(){return new s}static deSerialize(n){return new s(Em(n,s.spec))}serialize(){return Im(this,s.spec)}static fromData(n){let a=Buffer.alloc(2);return a.writeUInt16BE(s.type),s.deSerialize(Buffer.concat([a,n]))}get extension(){return{type:this.type,data:this.serialize().slice(2)}}},{decode:km,encode:Pm,types:So}=z,vo=class s{constructor(n,a){this.level=n,this.description=a}level;description;static spec={level:So.uint8,description:So.uint8};static deSerialize(n){return new s(...Object.values(km(n,s.spec)))}serialize(){return Pm(this,s.spec)}},wo=_("werift-dtls : packages/dtls/record/receive.ts : log"),Pi=_("werift-dtls : packages/dtls/record/receive.ts : err"),Am=(s)=>{let n=0,a=[];while(s.length>n){let o=s.readUInt16BE(n+11);if(s.length<n+(12+o))break;let c=Rd.deSerialize(s.subarray(n));a.push(c),n+=13+o}return a},xm=(s,n)=>(a)=>{switch(a.recordLayerHeader.contentType){case 20:return wo(s.sessionId,"change cipher spec"),[{type:20,data:void 0}];case 22:{let c=a.fragment;try{if(a.recordLayerHeader.epoch>0)wo(s.sessionId,"decrypt handshake"),c=n.decryptPacket(a)}catch(d){throw Pi(s.sessionId,"decrypt failed",d),d}try{let d=0,h=[];while(c.length>d){let u=ge.deSerialize(c.subarray(d));h.push({type:22,data:u}),d+=u.fragment_length+12}return h}catch(d){throw Pi(s.sessionId,"decSerialize failed",d,c),d}}case 23:return[{type:23,data:n.decryptPacket(a)}];case 21:{let c=vo.deSerialize(a.fragment);if(Zi[c.description]==null){let d=n.decryptPacket(a);c=vo.deSerialize(d)}if(Pi(s.sessionId,"ContentType.alert",c,Zi[c.description],"flight",s.flight,"lastFlight",s.lastFlight),c.level>1)throw Error("alert fatal error");return[{type:21,data:void 0}]}default:return[{type:21,data:void 0}]}},{decode:_m,types:or}=z,To=_("werift-dtls : packages/dtls/src/socket.ts : log"),bo=_("werift-dtls : packages/dtls/src/socket.ts : err"),rh=class{constructor(s,n){this.options=s,this.sessionType=n,this.dtls=new go(this.options,this.sessionType),this.cipher=new jr(this.sessionType,this.options.cert,this.options.key,this.options.signatureHash),this.transport=new Rm(this.options.transport),this.setupExtensions(),this.transport.socket.onData=this.udpOnMessage}options;sessionType;onConnect=new E;onData=new E;onError=new E;onClose=new E;transport;cipher;dtls;srtp=new Hr;connected=!1;extensions=[];onHandleHandshakes;bufferFragmentedHandshakes=[];renegotiation(){To("renegotiation",this.sessionType),this.connected=!1,this.cipher=new jr(this.sessionType,this.options.cert,this.options.key,this.options.signatureHash),this.dtls=new go(this.options,this.sessionType),this.srtp=new Hr,this.extensions=[],this.bufferFragmentedHandshakes=[]}udpOnMessage=(s)=>{let n=Am(s);for(let a of n)try{let o=xm(this.dtls,this.cipher)(a);for(let c of o)switch(c.type){case 22:{let d=c.data,h=this.handleFragmentHandshake([d]),u=Object.values(h.reduce((p,f)=>{if(!p[f.msg_type])p[f.msg_type]=[];return p[f.msg_type].push(f),p},{})).map((p)=>ge.assemble(p)).sort((p,f)=>p.msg_type-f.msg_type);this.onHandleHandshakes(u).catch((p)=>{bo(this.dtls.sessionId,"onHandleHandshakes error",p),this.onError.execute(p)})}break;case 23:this.onData.execute(c.data);break;case 21:this.onClose.execute();break}}catch(o){bo(this.dtls.sessionId,"catch udpOnMessage error",o)}};setupExtensions(){if(To(this.dtls.sessionId,"support srtpProfiles",this.options.srtpProfiles),this.options.srtpProfiles&&this.options.srtpProfiles.length>0){let s=Zt.create(this.options.srtpProfiles,Buffer.from([0]));this.extensions.push(s.extension)}{let s=sn.createEmpty();s.data=gd,this.extensions.push(s.extension)}{let s=rn.createEmpty();s.data=Sd,this.extensions.push(s.extension)}if(this.options.extendedMasterSecret)this.extensions.push({type:ni.type,data:Buffer.alloc(0)});{let s=ai.createEmpty();this.extensions.push(s.extension)}}waitForReady=(s)=>new Promise(async(n,a)=>{for(let o=0;o<10;o++)if(s()){n();break}else await hm(100*o);a("waitForReady timeout")});handleFragmentHandshake(s){let n=s.filter((a)=>{if(a.fragment_length!==a.length)return this.bufferFragmentedHandshakes.push(a),!1;return!0});if(this.bufferFragmentedHandshakes.length>1){let[a]=this.bufferFragmentedHandshakes.slice(-1);if(a.fragment_offset+a.fragment_length===a.length)n=[...this.bufferFragmentedHandshakes,...n],this.bufferFragmentedHandshakes=[]}return n}send=async(s,n)=>{let a=zs(this.dtls)([{type:23,fragment:s}],++this.dtls.recordSequenceNumber)[0];await this.transport.send(this.cipher.encryptPacket(a).serialize(),n)};close(){this.transport.close()}extractSessionKeys(s,n){let a=this.exportKeyingMaterial("EXTRACTOR-dtls_srtp",s*2+n*2),{clientKey:o,serverKey:c,clientSalt:d,serverSalt:h}=_m(a,{clientKey:or.buffer(s),serverKey:or.buffer(s),clientSalt:or.buffer(n),serverSalt:or.buffer(n)});if(this.sessionType===et.CLIENT)return{localKey:o,localSalt:d,remoteKey:c,remoteSalt:h};else return{localKey:c,localSalt:h,remoteKey:o,remoteSalt:d}}exportKeyingMaterial(s,n){return Op(s,n,this.cipher.masterSecret,this.cipher.localRandom.serialize(),this.cipher.remoteRandom.serialize(),this.sessionType===et.CLIENT)}get remoteCertificate(){return this.cipher.remoteCertificate}},Ai=_("werift-dtls : packages/dtls/src/client.ts : log"),Ro=class extends rh{constructor(s){super(s,et.CLIENT);this.onHandleHandshakes=this.handleHandshakes,Ai(this.dtls.sessionId,"start client")}async connect(){await new Sp(this.transport,this.dtls,this.cipher).exec(this.extensions)}flight5;handleHandshakes=async(s)=>{Ai(this.dtls.sessionId,"handleHandshakes",s.map((n)=>n.msg_type));for(let n of s)switch(n.msg_type){case 3:{let a=sh.deSerialize(n.fragment);await new wp(this.transport,this.dtls).exec(a)}break;case 2:{if(this.connected)return;this.flight5=new om(this.transport,this.dtls,this.cipher,this.srtp),this.flight5.handleHandshake(n)}break;case 11:case 12:case 13:await this.waitForReady(()=>!!this.flight5),this.flight5?.handleHandshake(n);break;case 14:{await this.waitForReady(()=>!!this.flight5),this.flight5?.handleHandshake(n);let a=[11,12,this.options.certificateRequest&&13].filter((o)=>typeof o==="number");await this.waitForReady(()=>this.dtls.checkHandshakesExist(a)),await this.flight5?.exec()}break;case 20:this.dtls.flight=7,this.connected=!0,this.onConnect.execute(),Ai(this.dtls.sessionId,"dtls connected");break}}},Be=_("werift-dtls : packages/dtls/flight/server/flight2.ts : log"),Bm=(s,n,a,o)=>(c)=>{Be("dtls version",c.clientVersion),n.flight=2,n.recordSequenceNumber=0,n.sequenceNumber=0,c.extensions.forEach((y)=>{switch(y.type){case sn.type:{let S=sn.fromData(y.data).data;Be(n.sessionId,"curves",S);let v=S.filter((g)=>gd.includes(g))[0];a.namedCurve=v,Be(n.sessionId,"curve selected",a.namedCurve)}break;case rn.type:{if(!a.signatureHashAlgorithm)throw Error("need to set certificate");let S=rn.fromData(y.data).data;Be(n.sessionId,"hash,signature",S);let v=S.find((w)=>w.signature===a.signatureHashAlgorithm?.signature)?.signature,g=S.find((w)=>w.hash===a.signatureHashAlgorithm?.hash)?.hash;if(v==null||g==null)throw Error("invalid signatureHash")}break;case Zt.type:{if(!n.options?.srtpProfiles)return;if(n.options.srtpProfiles.length===0)return;let S=Zt.fromData(y.data);Be(n.sessionId,"srtp profiles",S.profiles);let v=Hr.findMatchingSRTPProfile(S.profiles,n.options?.srtpProfiles);if(!v)throw Error();o.srtpProfile=v,Be(n.sessionId,"srtp profile selected",o.srtpProfile)}break;case ni.type:n.remoteExtendedMasterSecret=!0;break;case ai.type:Be(n.sessionId,"RenegotiationIndication",y.data);break;case 43:{let v=[...y.data.subarray(1)].map((g)=>g.toString(10));Be("dtls supported version",v)}break}}),a.localRandom=new dt,a.remoteRandom=dt.from(c.random);let d=c.cipherSuites;Be(n.sessionId,"cipher suites",d);let h=(()=>{switch(a.signatureHashAlgorithm?.signature){case Ue.ecdsa_3:return Qi.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256_49195;case Ue.rsa_1:return Qi.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256_49199}})();if(h===void 0||!d.includes(h))throw Error("dtls cipher suite negotiation failed");a.cipherSuite=h,Be(n.sessionId,"selected cipherSuite",a.cipherSuite),a.localKeyPair=Dd(a.namedCurve),n.cookie||=Lm(20);let u=new sh({major:254,minor:253},n.cookie),p=Cd(n)([u]),m=zs(n)(p.map((y)=>({type:22,fragment:y.serialize()})),++n.recordSequenceNumber).map((y)=>y.serialize());for(let y of m)s.send(y)},Co=_("werift-dtls : packages/dtls/flight/server/flight4.ts : log"),Mm=class extends qs{constructor(s,n,a,o){super(s,n,4,6);this.cipher=a,this.srtp=o}cipher;srtp;async exec(s,n,a=!1){if(this.dtls.flight===4){Co(this.dtls.sessionId,"flight4 twice"),this.send(this.dtls.lastMessage);return}this.cipher.remoteRandom=dt.from(n.random),this.dtls.flight=4,this.dtls.sequenceNumber=1,this.dtls.bufferHandshakeCache([s],!1,4);let o=[this.sendServerHello(),this.sendCertificate(),this.sendServerKeyExchange(),a&&this.sendCertificateRequest(),this.sendServerHelloDone()].filter((c)=>c);this.dtls.lastMessage=o,await this.transmit(o)}sendServerHello(){let s=[];if(this.srtp.srtpProfile)s.push(Zt.create([this.srtp.srtpProfile],Buffer.from([0])).extension);if(this.dtls.options.extendedMasterSecret)s.push({type:ni.type,data:Buffer.alloc(0)});let n=ai.createEmpty();s.push(n.extension);let a=new zd(this.dtls.version,this.cipher.localRandom,Buffer.from([0]),this.cipher.cipherSuite,0,s),o=this.createPacket([a]);return Buffer.concat(o.map((c)=>c.serialize()))}sendCertificate(){let s=new Fr([Buffer.from(this.cipher.localCert)]),n=this.createPacket([s]);return Buffer.concat(n.map((a)=>a.serialize()))}sendServerKeyExchange(){let s=this.cipher.generateKeySignature("sha256");if(!this.cipher.signatureHashAlgorithm)throw Error("not exist");let n=new Wd(yd.named_curve_3,this.cipher.namedCurve,this.cipher.localKeyPair.publicKey.length,this.cipher.localKeyPair.publicKey,this.cipher.signatureHashAlgorithm.hash,this.cipher.signatureHashAlgorithm.signature,s.length,s),a=this.createPacket([n]);return Buffer.concat(a.map((o)=>o.serialize()))}sendCertificateRequest(){let s=new Fd(Wu,Sd,[]);Co(this.dtls.sessionId,"sendCertificateRequest",s);let n=this.createPacket([s]);return Buffer.concat(n.map((a)=>a.serialize()))}sendServerHelloDone(){let s=new qd,n=this.createPacket([s]);return Buffer.concat(n.map((a)=>a.serialize()))}},ss=_("werift-dtls : packages/dtls/flight/server/flight6.ts"),Dm=class extends qs{constructor(s,n,a){super(s,n,6);this.cipher=a}cipher;handleHandshake(s){this.dtls.bufferHandshakeCache([s],!1,5);let n=(()=>{switch(s.msg_type){case 11:return Fr.deSerialize(s.fragment);case 15:return Od.deSerialize(s.fragment);case 16:return Hd.deSerialize(s.fragment);case 20:return en.deSerialize(s.fragment)}})();if(n){let a=Vs[n.msgType];if(!a)return;a({dtls:this.dtls,cipher:this.cipher})(n)}}async exec(){if(this.dtls.flight===6){ss(this.dtls.sessionId,"flight6 twice"),this.send(this.dtls.lastMessage);return}this.dtls.flight=6;let s=[this.sendChangeCipherSpec(),this.sendFinished()];this.dtls.lastMessage=s,await this.transmit(s)}sendChangeCipherSpec(){let s=Ud.createEmpty().serialize(),n=zs(this.dtls)([{type:20,fragment:s}],++this.dtls.recordSequenceNumber);return Buffer.concat(n.map((o)=>o.serialize()))}sendFinished(){let s=Buffer.concat(this.dtls.sortedHandshakeCache.map((d)=>d.serialize())),n=this.cipher.verifyData(s),a=new en(n);this.dtls.epoch=1;let[o]=this.createPacket([a]);return this.dtls.recordSequenceNumber=0,this.cipher.encryptPacket(o).serialize()}},Vs={};Vs[16]=({cipher:s,dtls:n})=>(a)=>{if(s.remoteKeyPair={curve:s.namedCurve,publicKey:a.publicKey},!s.remoteKeyPair.publicKey||!s.localKeyPair||!s.remoteRandom||!s.localRandom)throw Error("not exist");let o=Pd(s.remoteKeyPair.publicKey,s.localKeyPair.privateKey,s.localKeyPair.curve);ss(n.sessionId,"extendedMasterSecret",n.options.extendedMasterSecret,n.remoteExtendedMasterSecret);let c=Buffer.concat(n.sortedHandshakeCache.map((d)=>d.serialize()));s.masterSecret=n.options.extendedMasterSecret&&n.remoteExtendedMasterSecret?xd(o,c):Ad(o,s.remoteRandom.serialize(),s.localRandom.serialize()),s.cipher=Bd(s.cipherSuite),s.cipher.init(s.masterSecret,s.localRandom.serialize(),s.remoteRandom.serialize()),ss(n.sessionId,"setup cipher",s.cipher.summary)};Vs[11]=({cipher:s,dtls:n})=>(a)=>{ss(n.sessionId,"handshake certificate",a),s.remoteCertificate=a.certificateList[0]};Vs[15]=({cipher:s,dtls:n})=>(a)=>{if(!s.remoteCertificate)throw Error("client certificate missing before certificate verify");ss(n.sessionId,"certificate_verify",a.algorithm)};Vs[20]=({dtls:s})=>(n)=>{ss(s.sessionId,"finished",n)};var Bt=_("werift-dtls : packages/dtls/src/server.ts : log"),Um=class extends rh{constructor(s){super(s,et.SERVER);this.onHandleHandshakes=this.handleHandshakes,Bt(this.dtls.sessionId,"start server")}flight6;handleHandshakes=async(s)=>{Bt(this.dtls.sessionId,"handleHandshakes",s.map((n)=>n.msg_type));for(let n of s)switch(n.msg_type){case 1:{if(this.connected)this.renegotiation();let a=bd.deSerialize(n.fragment);if(a.cookie.length===0)Bt(this.dtls.sessionId,"send flight2"),Bm(this.transport,this.dtls,this.cipher,this.srtp)(a);else if(this.dtls.cookie&&a.cookie.equals(this.dtls.cookie))Bt(this.dtls.sessionId,"send flight4"),await new Mm(this.transport,this.dtls,this.cipher,this.srtp).exec(n,a,this.options.certificateRequest);else Bt("wrong state",{dtlsCookie:this.dtls.cookie?.toString("hex").slice(10),helloCookie:a.cookie.toString("hex").slice(10)})}break;case 11:case 15:case 16:{if(this.connected)return;this.flight6=new Dm(this.transport,this.dtls,this.cipher),this.flight6.handleHandshake(n)}break;case 20:{await this.waitForReady(()=>!!this.flight6),this.flight6?.handleHandshake(n);let a=[16,this.options.certificateRequest&&11,this.options.certificateRequest&&15].filter((o)=>typeof o==="number");await this.waitForReady(()=>this.dtls.checkHandshakesExist(a)),await this.flight6?.exec(),this.connected=!0,this.onConnect.execute(),Bt(this.dtls.sessionId,"dtls connected")}break}}},Me=class s{constructor(n,a,o,c,d,h,u,p,f,m,y,S){this.foundation=n,this.component=a,this.transport=o,this.priority=c,this.host=d,this.port=h,this.type=u,this.relatedAddress=p,this.relatedPort=f,this.tcptype=m,this.generation=y,this.ufrag=S}foundation;component;transport;priority;host;port;type;relatedAddress;relatedPort;tcptype;generation;ufrag;id=Eo().toString();refreshId(){this.id=Eo().toString()}static fromSdp(n){let a=n.split(" ");if(a.length<8)throw Error("SDP does not have enough properties");let o={foundation:a[0],component:Number(a[1]),transport:a[2],priority:Number(a[3]),host:a[4],port:Number(a[5]),type:a[7]};for(let y=8,S=a.length-1;y<S;y+=2)if(a[y]==="raddr")o.related_address=a[y+1];else if(a[y]==="rport")o.related_port=Number(a[y+1]);else if(a[y]==="tcptype")o.tcptype=a[y+1];else if(a[y]==="generation")o.generation=Number(a[y+1]);else if(a[y]==="ufrag")o.ufrag=a[y+1];let{foundation:c,component:d,transport:h,priority:u,host:p,port:f,type:m}=o;return new s(c,d,h,u,p,f,m,o.related_address,o.related_port,o.tcptype,o.generation,o.ufrag)}canPairWith(n){let a=Io(this.host),o=Io(n.host);return this.component===n.component&&this.transport.toLowerCase()===n.transport.toLowerCase()&&qm(this,n)&&a===o}toSdp(){let n=`${this.foundation} ${this.component} ${this.transport} ${this.priority} ${this.host} ${this.port} typ ${this.type}`;if(this.relatedAddress)n+=` raddr ${this.relatedAddress}`;if(this.relatedPort!=null)n+=` rport ${this.relatedPort}`;if(this.tcptype)n+=` tcptype ${this.tcptype}`;if(this.generation!=null)n+=` generation ${this.generation}`;if(this.ufrag!=null)n+=` ufrag ${this.ufrag}`;return n}},Om={host:126,prflx:110,srflx:100,relay:0},Hm={host:105,prflx:90,srflx:80,relay:0},Fm={active:6,passive:4,so:2},zm={active:4,passive:2,so:6};function ci(s){return s?.toLowerCase()??"udp"}function nn(s){switch(s){case"active":case"passive":case"so":return s;default:return}}function qm(s,n){if(ci(s.transport)!=="tcp")return!0;let a=nn(s.tcptype),o=nn(n.tcptype);if(!a||!o)return!1;return a==="active"&&o==="passive"||a==="passive"&&o==="active"||a==="so"&&o==="so"}function Wm({candidateType:s,transport:n="udp",tcptype:a,otherPreference:o=8191}){if(ci(n)!=="tcp")return o;let c=nn(a)??"active";return 8192*(s==="srflx"||s==="prflx"?zm[c]:Fm[c])+o}function Km(s,n="udp"){return(ci(n)==="tcp"?Hm:Om)[s]??0}function vs(s,n,a){let o=`${s}|${n}|${a}`;return Nm("md5").update(o,"ascii").digest("hex").slice(7)}function $t(s,n=65535){let o=typeof n==="number"?"udp":ci(n.transport),c=typeof n==="number"?n:n.localPreference??Wm({candidateType:s,transport:o,tcptype:n.tcptype,otherPreference:n.otherPreference});return 16777216*Km(s,o)+256*c+255}function ko(s){switch(s){case"passive":return"active";case"active":return"passive";default:return"so"}}var Po=class{cache=new Map;mdnsInstance=nh.default();constructor(){this.mdnsInstance.setMaxListeners(50)}lookup(s){return new Promise((n,a)=>{let o=()=>{this.mdnsInstance.removeListener("response",d),clearTimeout(c)},c=setTimeout(()=>{o(),a(Error("No mDNS response"))},1e4),d=(h)=>{let u=h.answers?.[0];if(u?.type!=="A")return;if(u.name!==s)return;o(),n(u.data)};this.mdnsInstance.on("response",d),this.mdnsInstance.query(s,"A")})}close(){this.mdnsInstance.destroy()}},Hn=class extends Error{response;addr},Fn=class extends Hn{constructor(s,n){super();this.response=s,this.addr=n}response;addr;get str(){let s="STUN transaction failed",n=this.response.getAttributeValue("ERROR-CODE");if(n){let[a,o]=n;s+=` (${a} - ${o})`}return s}},Ao=class extends Hn{get str(){return"STUN transaction timed out"}},Oe=class extends Hn{get str(){return"STUN transaction cancelled"}},Gm=class extends Error{constructor(s,n){super(`cannot reach ${s[0]}:${s[1]} from an IPv${n} socket`);this.addr=s,this.socketFamily=n}addr;socketFamily},xo=class extends Error{constructor(s,n,a,o){super(`TURN Allocate to ${n[0]}:${n[1]} returned 300 (Try Alternate)`+(a?` to ${a[0]}:${a[1]}`:"")+`; redirect not followed: ${s}`,{cause:o});this.reason=s,this.server=n,this.alternate=a}reason;server;alternate};function Mt(s){return ah(s).toString("hex").substring(0,s)}function jm(){return ah(12)}var xi=class{queue=[];wait=new E;put(s){if(this.queue.push(s),this.queue.length===1)this.wait.execute(s)}get(){let s=this.queue.shift();if(!s)return new Promise((n)=>{this.wait.subscribe((a)=>{this.queue.shift(),n(a)})});return s}},an=(s)=>{let n,a,o=new Promise((d,h)=>{n=d,a=h});o.then(()=>{c.execute(void 0),c.complete()}).catch((d)=>{c.execute(d??Error()),c.complete()});let c=new E;return s(n,a,c).catch(()=>{}),{awaitable:o,resolve:n,reject:a}},di=554869826,Ym=8,Qm=1398035790,ot=20,oh=24,ch=1,dh=2,Xm=6,Jm=50;function Zm(s){if(s.length<ot)return!1;if((s[0]&192)!==0)return!1;if(s.readUInt32BE(4)!==di)return!1;let n=s.readUInt16BE(2);if(n%4!==0)return!1;return s.length===ot+n}var eg=3000;function lh(s){if(on(s)){let c=Buffer.allocUnsafe(4),d=s.split(".");for(let h=0;h<4;h++)c[h]=Number(d[h])&255;return c}if(!sg(s))throw Error(`Invalid ip address: ${s}`);let n=s.split(":",8);for(let c=0;c<n.length;c++){let d;if(on(n[c]))d=lh(n[c]),n[c]=d.subarray(0,2).toString("hex");if(d&&++c<8)n.splice(c,0,d.subarray(2,4).toString("hex"))}if(n[0]==="")while(n.length<8)n.unshift("0");else if(n[n.length-1]==="")while(n.length<8)n.push("0");else if(n.length<8){let c=0;for(;c<n.length&&n[c]!=="";c++);let d=[];for(let h=9-n.length;h>0;h--)d.push("0");n.splice(c,1,...d)}let a=Buffer.allocUnsafe(16),o=0;for(let c of n){let d=Number.parseInt(c,16)||0;a[o++]=d>>8&255,a[o++]=d&255}return a}function _o(s){if(s.length===4)return`${s[0]}.${s[1]}.${s[2]}.${s[3]}`;if(s.length!==16)throw Error(`Invalid ip address buffer length: ${s.length}`);let n=[];for(let o=0;o<16;o+=2)n.push(s.readUInt16BE(o).toString(16));let a=n.join(":");return a=a.replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3"),a=a.replace(/:{3,4}/,"::"),a}function rg(s){return on(s)}function St(s){let[n]=s,a=rg(n)?ch:dh,o=Buffer.alloc(4);return o.writeUInt8(0,0),o.writeUInt8(a,1),o.writeUInt16BE(s[1],2),Buffer.concat([o,lh(n)])}function ig(s){if(s.length<4)throw Error("STUN error code is less than 4 bytes");let n=s.readUInt8(2),a=s.readUInt8(3),o=s.slice(4).toString("utf8");return[n*100+a,o]}function vt(s){if(s.length<4)throw Error("STUN address length is less than 4 bytes");let n=s.readUInt8(1),a=s.readUInt16BE(2),o=s.slice(4);switch(n){case ch:if(o.length!==4)throw Error("STUN address has invalid length for IPv4");return[_o(o),a];case dh:if(o.length!==16)throw Error("STUN address has invalid length for IPv6");return[_o(o),a];default:throw Error("STUN address has unknown protocol")}}var zn=Buffer.alloc(6);zn.writeUInt16BE(di>>16,0);zn.writeUInt32BE(di,2);function uh(s,n){let a=[...zn,...n],o=s.slice(0,2);for(let c=2;c<s.length;c++){let d=s[c]^a[c-2],h=Buffer.alloc(1);h.writeUIntBE(d,0,1),o=Buffer.concat([o,h])}return o}function br(s,n){return vt(uh(s,n))}function ng(s){let n=Buffer.alloc(4);n.writeUInt16BE(0,0),n.writeUInt8(Math.floor(s[0]/100),2),n.writeUInt8(s[0]%100,3);let a=Buffer.from(s[1],"utf8");return Buffer.concat([n,a])}function ag(s){let n=Buffer.alloc(s.length*2);return s.forEach((a,o)=>{n.writeUInt16BE(a,o*2)}),n}function og(s){if(s.length%2!==0)throw Error("UNKNOWN-ATTRIBUTES must have an even length");let n=[];for(let a=0;a<s.length;a+=2)n.push(s.readUInt16BE(a));return n}function Rr(s,n){return uh(St(s),n)}var Dt=(s)=>{let n=Buffer.alloc(4);return n.writeUInt32BE(s,0),n},Ut=(s)=>s.readUInt32BE(0),cg=(s)=>{let n=Buffer.alloc(4);return n.writeUInt16BE(s,0),n},dg=(s)=>s.readUInt16BE(0),Lo=(s)=>{let n=Buffer.allocUnsafe(8);return n.writeBigUInt64BE(s,0),n},Bo=(s)=>s.readBigUInt64BE(0),Cr=(s)=>Buffer.from(s,"utf8"),cr=(s)=>s.toString("utf8"),hg=(s)=>{if([...s].length>=128)throw Error("SOFTWARE must be shorter than 128 characters");return Cr(s)},Ye=(s)=>s,Qe=(s)=>s,lg=()=>Buffer.alloc(0),ug=()=>null,ph=[[1,"MAPPED-ADDRESS",St,vt],[3,"CHANGE-REQUEST",Dt,Ut],[4,"SOURCE-ADDRESS",St,vt],[5,"CHANGED-ADDRESS",St,vt],[6,"USERNAME",Cr,cr],[8,"MESSAGE-INTEGRITY",Ye,Qe],[9,"ERROR-CODE",ng,ig],[10,"UNKNOWN-ATTRIBUTES",ag,og],[12,"CHANNEL-NUMBER",cg,dg],[13,"LIFETIME",Dt,Ut],[18,"XOR-PEER-ADDRESS",Rr,br],[19,"DATA",Ye,Qe],[20,"REALM",Cr,cr],[21,"NONCE",Ye,Qe],[22,"XOR-RELAYED-ADDRESS",Rr,br],[23,"REQUESTED-ADDRESS-FAMILY",Dt,Ut],[24,"EVEN-PORT",Ye,Qe],[25,"REQUESTED-TRANSPORT",Dt,Ut],[28,"MESSAGE-INTEGRITY-SHA256",Ye,Qe],[29,"PASSWORD-ALGORITHM",Ye,Qe],[30,"USERHASH",Ye,Qe],[32,"XOR-MAPPED-ADDRESS",Rr,br],[34,"RESERVATION-TOKEN",Ye,Qe],[36,"PRIORITY",Dt,Ut],[37,"USE-CANDIDATE",lg,ug],[32770,"PASSWORD-ALGORITHMS",Ye,Qe],[32771,"ALTERNATE-DOMAIN",Cr,cr],[32802,"SOFTWARE",hg,cr],[32803,"ALTERNATE-SERVER",St,vt],[32808,"FINGERPRINT",Dt,Ut],[32809,"ICE-CONTROLLED",Lo,Bo],[32810,"ICE-CONTROLLING",Lo,Bo],[32811,"RESPONSE-ORIGIN",St,vt],[32812,"OTHER-ADDRESS",St,vt]],fh=class{constructor(s=[]){this.attributes=s}attributes;getAttributes(){return this.attributes}setAttribute(s,n){let a=this.attributes.find((o)=>o[0]===s);if(a)a[1]=n;else this.attributes.push([s,n]);return this}getAttributeValue(s){return this.attributes.find((a)=>a[0]===s)?.[1]}get attributesKeys(){return this.attributes.map((s)=>s[0])}clear(){this.attributes=[]}},Mo=ph.reduce((s,n)=>(s[n[0]]=n,s),{}),pg=ph.reduce((s,n)=>(s[n[1]]=n,s),{});function ht(s,n){if(!Zm(s))return;let a=s.readUInt16BE(0),o=Buffer.from(s.slice(ot-12,ot)),c=new fh,d=[],h=[],u=!1,p=!1,f=!1;for(let m=ot;m<s.length;){if(m+4>s.length)return;let y=s.readUInt16BE(m),S=s.readUInt16BE(m+2),v=m+4,g=v+S;if(g>s.length)return;let w=s.slice(v,g),T=Ns(S);if(g+T>s.length)return;let b=Mo[y]?.[1];if(f&&b!=="FINGERPRINT"||p&&b!=="FINGERPRINT"&&b!=="MESSAGE-INTEGRITY-SHA256"){m=g+T;continue}if(b==="MESSAGE-INTEGRITY")p=!0;if(b==="MESSAGE-INTEGRITY-SHA256")f=!0;let C=Mo[y];if(C){let[,P,,x]=C,H;try{H=x.name===br.name?x(w,o):x(w)}catch{return}if(c.setAttribute(P,H),P==="ALTERNATE-SERVER")h.push(H);if(P==="FINGERPRINT"){let O=mh(s.slice(0,m));if(c.getAttributeValue("FINGERPRINT")!==O)return}else if(P==="MESSAGE-INTEGRITY"&&n){let O=mg(s.slice(0,m),n),ee=c.getAttributeValue("MESSAGE-INTEGRITY");if(!O.equals(ee))return;u=!0}}else d.push({type:y,length:S,value:Buffer.from(w)});m=g+T}if(n&&!u)return;return new De(a&16111,a&272,o,c.getAttributes(),d,h)}var De=class extends fh{constructor(s,n,a=tg(12),o=[],c=[],d=[]){super(o);this.messageMethod=s,this.messageClass=n,this.transactionId=a,this.rawAttributes=c,this.alternateServers=d}messageMethod;messageClass;transactionId;rawAttributes;alternateServers;toJSON(){return this.json}get json(){return{messageMethod:this.messageMethod,messageClass:this.messageClass,attributes:this.attributes,rawAttributes:this.rawAttributes.map((s)=>({type:s.type,length:s.value.length}))}}get transactionIdHex(){return this.transactionId.toString("hex")}appendRawAttribute(s,n){return this.rawAttributes.push({type:s,value:Buffer.from(n)}),this}get unknownAttributeTypes(){return this.rawAttributes.map((s)=>s.type)}get bytes(){let s=Buffer.concat(this.serializedAttributes.map((a)=>fg(a.type,a.value))),n=Buffer.alloc(8);return n.writeUInt16BE(this.messageMethod|this.messageClass,0),n.writeUInt16BE(s.length,2),n.writeUInt32BE(di,4),Buffer.concat([n,this.transactionId,s])}addMessageIntegrity(s){return this.setAttribute("MESSAGE-INTEGRITY",this.messageIntegrity(s)),this}messageIntegrity(s){let n=qn(this.bytes,this.bytes.length-ot+oh);return Buffer.from(hh("sha1",s).update(n).digest("hex"),"hex")}addFingerprint(){return this.setAttribute("FINGERPRINT",mh(this.bytes)),this}get serializedAttributes(){let s=[];for(let n of this.attributesKeys){let a=this.getAttributeValue(n),[o,,c]=pg[n],d=c.name===Rr.name?c(a,this.transactionId):c(a);s.push({type:o,value:d})}return s.push(...this.rawAttributes.map((n)=>({type:n.type,value:Buffer.from(n.value)}))),s}};function fg(s,n){let a=n.length,o=Ns(a),c=Buffer.alloc(4);return c.writeUInt16BE(s,0),c.writeUInt16BE(a,2),Buffer.concat([c,n,Buffer.alloc(o)])}var qn=(s,n)=>{let a=Buffer.alloc(s.length);return s.copy(a,0,0,2),a.writeUInt16BE(n,2),s.copy(a,4,4),a};function mh(s){let n=qn(s,s.length-ot+Ym);return(Cu(n)^Qm)>>>0}function mg(s,n){let a=qn(s,s.length-ot+oh);return Buffer.from(hh("sha1",n).update(a).digest("hex"),"hex")}function Ns(s){let n=s%4;return n===0?0:4-n}var gg=_("werift-ice : packages/ice/src/ice.ts : log"),dr=class{constructor(s,n,a){this.protocol=s,this.remoteCandidate=n,this.iceControlling=a}protocol;remoteCandidate;iceControlling;id=Vm().toString();handle;nominated=!1;remoteNominated=!1;_state=0;get state(){return this._state}packetsSent=0;packetsReceived=0;bytesSent=0;bytesReceived=0;rtt;totalRoundTripTime=0;roundTripTimeMeasurements=0;requestsReceived=0;requestsSent=0;responsesReceived=0;responsesSent=0;retransmissionsReceived=0;retransmissionsSent=0;consentRequestsSent=0;requestTransactionIds=new Set;toJSON(){return this.json}get json(){return{protocol:this.protocol.type,localCandidate:this.localCandidate.toSdp(),remoteCandidate:this.remoteCandidate.toSdp()}}updateState(s){this._state=s}get localCandidate(){if(!this.protocol.localCandidate)throw Error("localCandidate not exist");return this.protocol.localCandidate}get remoteAddr(){return[this.remoteCandidate.host,this.remoteCandidate.port]}get component(){return this.localCandidate.component}get priority(){return cn(this.localCandidate,this.remoteCandidate,this.iceControlling)}get foundation(){return this.localCandidate.foundation}noteIncomingRequest(s){if(!this.requestTransactionIds.has(s))return this.requestTransactionIds.add(s),!1;return this.retransmissionsReceived++,!0}},hr=1,ps=2,yg=5;var Sg=30,vg=1000,wg=500;function Tg(s){if(s===void 0||!Number.isFinite(s)||s<=0)return vg;return Math.max(wg,Math.round(s*1000*2+200))}var bg={iceLite:!1,useTcp:!1,useIpv4:!0,useIpv6:!0};function _i(s){if(!["host","relay","srflx"].includes(s.type))throw Error(`Unexpected candidate type "${s.type}"`);return s}function Rg(s,n){return s.sort((a,o)=>cn(a.localCandidate,a.remoteCandidate,n)-cn(o.localCandidate,o.remoteCandidate,n)).reverse()}function cn(s,n,a){let o=a&&s.priority||n.priority,c=a&&n.priority||s.priority;return 1*Math.min(o,c)+2*Math.max(o,c)+(o>c?1:0)}async function Do(s,n){let a=new De(1,0);try{let[o]=await s.request(a,n),c=s.localCandidate;if(!c)throw Error("not exist");return new Me(vs("srflx",c.transport,c.host),c.component,c.transport,$t("srflx",{transport:c.transport,tcptype:c.tcptype}),o.getAttributeValue("XOR-MAPPED-ADDRESS")[0],o.getAttributeValue("XOR-MAPPED-ADDRESS")[1],"srflx",c.host,c.port,c.tcptype)}catch(o){gg("error serverReflexiveCandidate",o)}}function Uo(s){if(s&&Number.isNaN(s[1]))return[s[0],443];return s}function Eg({enumerated:s,interfaceAddresses:n,additionalHostAddresses:a=[],useIpv4:o,useIpv6:c,log:d=()=>{}}){let h=n?.udp4,u=n?.udp6;if(!h&&!u)return Array.from(new Set([...a,...s]));let p=[];if(h&&o)p.push(h);if(u&&c)p.push(u);let f=a.filter((m)=>{let y=Cg(m)?h:u;if(!y)return!0;if(m===y)return!0;return d("ignore additionalHostAddress; its family is bound to interfaceAddress",m,y),!1});return Array.from(new Set([...p,...f]))}var fs=_("werift-ice:packages/ice/src/stun/transaction.ts");async function bt(s,n=0){let a=gh(s[0]);if(a){if(n!==0&&a!==n)throw new Gm(s,n);return s}return[(await Ig.lookup(s[0],{family:n})).address,s[1]]}function yh(s,n){if(s!==null&&typeof s==="object")return s;return{retransmissions:typeof s==="number"?s:void 0,onRequestSent:n}}function dn(s,n){return s[1]===n[1]&&Oo(s[0])===Oo(n[0])}function Oo(s){return gh(s)===6?new kg({address:s,family:"ipv6"}).address:s}var hi=class{constructor(s,n,a,o,c){this.request=s,this.addr=n,this.protocol=a;let d=yh(o,c);this.triesMax=1+(d.retransmissions??Xm),this.timeoutDelay=d.responseTimeout??Jm,this.onRequestSent=d.onRequestSent,this.signal=d.signal,this.failOnSendError=d.failOnSendError??!1,this.expectedAddr=n,this.integrityKey=d.integrityKey}request;addr;protocol;timeoutDelay;ended=!1;tries=0;triesMax;onResponse=new E;onRequestSent;signal;failOnSendError;expectedAddr;integrityKey;waitTimer;waitResolve;onAbort;responseReceived=(s,n)=>{if(this.ended||this.onResponse.length===0)return;if(!dn(this.expectedAddr,n)){fs("ignore STUN response from unexpected address",n,"expected",this.expectedAddr);return}if(this.integrityKey){if(!(s.attributesKeys.includes("MESSAGE-INTEGRITY")||s.attributesKeys.includes("MESSAGE-INTEGRITY-SHA256"))){fs("ignore unauthenticated STUN response (MESSAGE-INTEGRITY required)");return}}if(s.messageClass===256)this.onResponse.execute(s,n),this.onResponse.complete();else this.onResponse.error(new Fn(s,n))};run=async()=>{try{if(this.signal?.aborted)throw new Ao;return this.attachAbortListener(),this.retry().catch((n)=>{fs("retry failed",n)}),await this.onResponse.asPromise()}catch(s){throw s}finally{this.cancel()}};attachAbortListener(){if(!this.signal)return;this.onAbort=()=>{this.failWithTimeout()},this.signal.addEventListener("abort",this.onAbort,{once:!0})}failWithTimeout(){this.fail(new Ao)}fail(s){if(this.ended)return;if(this.ended=!0,this.clearWait(),this.onResponse.length>0)this.onResponse.error(s)}clearWait(){if(this.waitTimer!==void 0)clearTimeout(this.waitTimer),this.waitTimer=void 0;let s=this.waitResolve;this.waitResolve=void 0,s?.()}wait(s){return new Promise((n)=>{if(this.ended||this.signal?.aborted){n();return}this.waitResolve=n,this.waitTimer=setTimeout(()=>{this.waitTimer=void 0,this.waitResolve=void 0,n()},s)})}retry=async()=>{while(this.tries<this.triesMax&&!this.ended){if(this.onRequestSent?.(this.tries),this.protocol.sendStun(this.request,this.addr).catch((s)=>{if(fs("send stun failed",s),this.failOnSendError)this.fail(s)}),await this.wait(this.timeoutDelay),this.ended)break;this.timeoutDelay*=2,this.tries++}if(this.tries>=this.triesMax&&!this.ended)fs(`retry failed times:${this.tries} maxLimit:${this.triesMax}`),this.failWithTimeout()};cancel(){if(this.fail(new Oe),this.ended=!0,this.clearWait(),this.signal&&this.onAbort)this.signal.removeEventListener("abort",this.onAbort),this.onAbort=void 0}};function li(s,n,a){let o=yh(n,a);if(s&&!o.integrityKey)o.integrityKey=s;return o}var lr=_("werift-ice : packages/ice/src/stun/protocol.ts"),ur=class s{static type="stun";type=s.type;transport;transactions={};get transactionsKeys(){return Object.keys(this.transactions)}localCandidate;sentMessage;localIp;closed=!1;onRequestReceived=new E;onDataReceived=new E;constructor(){}connectionMade=async(n,a,o)=>{if(n)this.transport=await ji.init("udp4",{portRange:a,interfaceAddresses:o});else this.transport=await ji.init("udp6",{portRange:a,interfaceAddresses:o});this.transport.onData=(c,d)=>{this.datagramReceived(c,d)},this.transport.onError.subscribe((c)=>{lr("transport error",c)})};datagramReceived(n,a){try{let o=ht(n);if(!o){if(this.localCandidate)this.onDataReceived.execute(n);return}if((o.messageClass===256||o.messageClass===272)&&this.transactionsKeys.includes(o.transactionIdHex)){let c=this.transactions[o.transactionIdHex],d=c.integrityKey?ht(n,c.integrityKey):o;if(!d){lr("STUN response failed MESSAGE-INTEGRITY check");return}c.responseReceived(d,a)}else if(o.messageClass===0)this.onRequestReceived.execute(o,a,n)}catch(o){lr("datagramReceived error",o)}}getExtraInfo(){let{address:n,port:a}=this.transport.address;return[n,a]}async sendStun(n,a){if(this.transport.closed)return;let o=n.bytes;await this.transport.send(o,a).catch(()=>{lr("sendStun failed",a,n)})}async sendData(n,a){if(this.transport.closed)return;await this.transport.send(n,a)}async request(n,a,o,c,d){if(this.transactionsKeys.includes(n.transactionIdHex))throw Error("already request ed");if(o)n.addMessageIntegrity(o),n.addFingerprint();let h=await bt(a,this.transport.addressFamily);if(this.closed)throw new Oe;let u=li(o,c,d),p=new hi(n,h,this,u);this.transactions[n.transactionIdHex]=p;try{return await p.run()}catch(f){throw f}finally{delete this.transactions[n.transactionIdHex]}}async close(){this.closed=!0,Object.values(this.transactions).forEach((n)=>{n.cancel()}),await this.transport.close(),this.onRequestReceived.complete(),this.onDataReceived.complete()}};function xg(s){let n=Buffer.alloc(2);return n.writeUInt16BE(s.length,0),Buffer.concat([n,s])}function _g(s){let n=[],a=0;while(s.length-a>=2){let o=s.readUInt16BE(a);if(s.length-a<o+2)break;n.push(s.subarray(a+2,a+2+o)),a+=2+o}return{frames:n,rest:s.subarray(a)}}var pr=_("werift-ice:packages/ice/src/stun/tcpProtocol.ts");function ws(s){return`${s[0]}:${s[1]}`}function Lg(s){return s.destroyed||s.writableEnded}function Sh(s){if(!s.remoteAddress||!s.remotePort)return;return[s.remoteAddress,s.remotePort]}async function Ho(s,n,a){return await new Promise((o,c)=>{let d=(u)=>{s.off("listening",h),c(u)},h=()=>{s.off("error",d),o()};s.once("error",d),s.once("listening",h),s.listen({host:n,port:a??0,exclusive:!0})})}var vh=class s{static type="tcp";type=s.type;transactions={};localCandidate;sentMessage;localIp;onRequestReceived=new E;onDataReceived=new E;onConnectionClosed=new E;closed=!1;sockets=new Map;rememberSocket(n){let a=n.remoteAddr;if(!a)return;this.sockets.set(ws(a),n)}forgetSocket(n){let a=n.remoteAddr;if(!a)return!1;let o=ws(a);if(this.sockets.get(o)!==n)return!1;return this.sockets.delete(o),!0}getOpenSocket(n){let a=this.sockets.get(ws(n));if(!a)return;if(Lg(a.socket)){this.dropSocket(a);return}return a}dropSocket(n){if(n.socket.destroy(),this.forgetSocket(n)&&n.remoteAddr)this.onConnectionClosed.execute(n.remoteAddr)}registerSocket(n,a){let o={socket:n,buffer:Buffer.alloc(0),remoteAddr:a};if(a)this.rememberSocket(o);return n.on("data",(c)=>{o.buffer=Buffer.concat([o.buffer,typeof c==="string"?Buffer.from(c):c]);let{frames:d,rest:h}=_g(o.buffer);o.buffer=h;let u=o.remoteAddr??Sh(n);if(!o.remoteAddr&&u)o.remoteAddr=u,this.rememberSocket(o);if(!u)return;for(let p of d){if(p.length===0)continue;this.handleFrame(p,u)}}),n.on("close",()=>{if(this.forgetSocket(o)&&o.remoteAddr)this.onConnectionClosed.execute(o.remoteAddr)}),n.on("error",(c)=>{pr("tcp socket error",c)}),o}handleFrame(n,a){try{let o=ht(n);if(!o){this.onDataReceived.execute(n);return}if((o.messageClass===256||o.messageClass===272)&&this.transactions[o.transactionIdHex]){let c=this.transactions[o.transactionIdHex],d=c.integrityKey?ht(n,c.integrityKey):o;if(!d){pr("STUN response failed MESSAGE-INTEGRITY check");return}c.responseReceived(d,a)}else if(o.messageClass===0)this.onRequestReceived.execute(o,a,n)}catch(o){pr("tcp frame parse error",o)}}async sendFrame(n,a){let o=await this.getSocket(a);try{await new Promise((c,d)=>{o.socket.write(xg(n),(h)=>{if(h){d(h);return}c()})})}catch(c){throw pr("tcp write failed",a,c),this.dropSocket(o),c}}async sendStun(n,a){await this.sendFrame(n.bytes,a)}async sendData(n,a){await this.sendFrame(n,a)}async request(n,a,o,c,d){if(this.transactions[n.transactionIdHex])throw Error("already requested");if(o)n.addMessageIntegrity(o),n.addFingerprint();let h=await bt(a);if(this.closed)throw new Oe;let u={failOnSendError:!0,...li(o,c,d)},p=new hi(n,h,this,u);this.transactions[n.transactionIdHex]=p;try{return await p.run()}finally{delete this.transactions[n.transactionIdHex]}}async pruneForSelection(n){for(let[a,o]of this.sockets.entries()){if(n&&a===ws(n))continue;o.socket.destroy(),this.sockets.delete(a)}}get activeSocketCount(){return this.sockets.size}get address(){return{}}async close(){this.closed=!0,Object.values(this.transactions).forEach((n)=>{n.cancel()}),await this.pruneForSelection(),this.onRequestReceived.complete(),this.onDataReceived.complete(),this.onConnectionClosed.complete()}},Bg=class extends vh{pendingSockets=new Map;async connectionMade(s){this.localIp=s}async getSocket(s){let n=ws(s),a=this.getOpenSocket(s);if(a)return a;let o=this.pendingSockets.get(n);if(o)return await o;let c=new Promise((d,h)=>{let u=Pg({host:s[0],port:s[1],localAddress:this.localIp}),p=this.registerSocket(u,s),f=(y)=>{u.off("connect",m),h(y)},m=()=>{u.off("error",f),d(p)};u.once("error",f),u.once("connect",m)});this.pendingSockets.set(n,c);try{return await c}finally{this.pendingSockets.delete(n)}}},Mg=class extends vh{server=Ag((s)=>{this.registerSocket(s,Sh(s))});async connectionMade(s,n){if(this.localIp=s,n){let a;for(let o=n[0];o<=n[1];o++)try{await Ho(this.server,s,o);return}catch(c){a=c}throw a??Error("tcp port not found")}await Ho(this.server,s)}async getSocket(s){let n=this.getOpenSocket(s);if(!n)throw Error("tcp passive connection not established");return n}get listeningPort(){let s=this.server.address();if(!s||typeof s==="string")throw Error("tcp passive protocol is not listening");return s.port}async close(){await super.close(),await new Promise((s)=>{this.server.close(()=>s())})}};function Ng(s,n,a){return Ug("md5").update(Buffer.from([s,n,a].join(":"))).digest()}function Wn(s){return s.length>=4&&(s[0]&192)===64}function Og(s,n){let a=Buffer.alloc(4);return a.writeUInt16BE(s,0),a.writeUInt16BE(n.length,2),Buffer.concat([a,n])}function Hg(s){if(!Wn(s)||s.length<4)return;let n=s.readUInt16BE(0),a=s.readUInt16BE(2);if(s.length<4+a)return;return{channelNumber:n,data:s.subarray(4,4+a)}}function Fg(s){let n=Ns(s.length);return n>0?Buffer.concat([s,Buffer.alloc(n)]):s}function zg(s){let n=[],a=0,o=!1;while(s.length-a>=4){let c;if(Wn(s.subarray(a))){let d=s.readUInt16BE(a+2);c=4+d+Ns(d)}else if((s[a]&192)===0){if(s.length-a<20)break;let d=s.readUInt16BE(a+2);c=20+d+Ns(d)}else{o=!0;break}if(s.length-a<c)break;n.push(s.subarray(a,a+c)),a+=c}return{frames:n,malformed:o,rest:s.subarray(a)}}var G=_("werift-ice:packages/ice/src/turn/protocol.ts"),qg=500,Wg=600,Kg=285212672,$g=3;function Ot(s){return s.type==="tcp"||s.type==="tls"}function Gg(s){return s[0]}function Fo(s){return JSON.stringify(s)}var jg=class s{constructor(n){this.turn=n,n.onData.subscribe((a,o)=>{this.handleStunMessage(a,o)}).disposer(this.disposer)}turn;static type="turn";type=s.type;localCandidate;disposer=new Eu;onRequestReceived=new E;onDataReceived=new E;handleStunMessage=(n,a)=>{try{let o=ht(n);if(!o){this.onDataReceived.execute(n);return}if(o.messageClass===256||o.messageClass===272){let c=this.turn.transactions[o.transactionIdHex];if(c){let d=c.integrityKey?ht(n,c.integrityKey):o;if(!d){G("STUN over TURN response failed MESSAGE-INTEGRITY check");return}c.responseReceived(d,a)}}else if(o.messageClass===0)this.onRequestReceived.execute(o,a,n)}catch(o){G("datagramReceived error",o)}};async request(n,a,o,c,d){if(this.turn.transactions[n.transactionIdHex])throw Error("exist");if(o)n.addMessageIntegrity(o),n.addFingerprint();let h=await bt(a),u=li(o,c,d),p=new hi(n,h,this,u);this.turn.transactions[n.transactionIdHex]=p;try{return await p.run()}catch(f){throw f}finally{delete this.turn.transactions[n.transactionIdHex]}}async connectionMade(){}async sendData(n,a){await this.turn.sendData(n,a)}async sendStun(n,a){await this.turn.sendData(n.bytes,a)}async close(){return this.disposer.dispose(),this.turn.close()}},Vg=class s{constructor(n,a,o,c,d,h={}){this.server=n,this.username=a,this.password=o,this.lifetime=c,this.transport=d,this.options=h,this.configuredServer=n,this.channelRefreshTime=this.options.channelRefreshTime??qg}server;username;password;lifetime;transport;options;static type="turn";type=s.type;onData=new E;onRequestReceived=new E;onDataReceived=new E;integrityKey;nonce;realm;relayedAddress;mappedAddress;localCandidate;transactions={};closed=!1;refreshHandle;channelNumber=16384;channelByAddr={};addrByChannel={};channelRefreshTime;channelBindQueue=Promise.resolve();channelBindingByAddr=new Map;tcpBuffer=Buffer.alloc(0);permissionByAddr={};permissionQueue=Promise.resolve();creatingPermissionByAddr=new Map;pinnedServerEndpoint;serverEndpointSelection;configuredServer;async connectionMade(){this.attachTransport();let[n]=await this.allocate().catch((o)=>{throw G("connect error",o),o});this.relayedAddress=n.getAttributeValue("XOR-RELAYED-ADDRESS"),this.mappedAddress=n.getAttributeValue("XOR-MAPPED-ADDRESS");let a=n.getAttributeValue("LIFETIME");if(G("connect",this.relayedAddress,this.mappedAddress,{exp:a}),this.closed)throw new Oe;this.refresh(a)}attachTransport(){this.transport.onData=(n,a)=>{this.dataReceived(n,a)},this.transport.onError?.subscribe((n)=>{G("transport error",n)})}async allocate(){let n=this.options.maxAllocateRedirects??$g,a=[];for(let o=0;;o++){let c=new De(3,0).setAttribute("LIFETIME",this.lifetime).setAttribute("REQUESTED-TRANSPORT",Kg);try{return await this.requestWithRetry(c,this.server)}catch(d){let h=Jg(d,this.transport.addressFamily);if(!h)throw d;if(a.push(this.server),this.pinnedServerEndpoint)a.push(this.pinnedServerEndpoint);let u=d,p=(f)=>new xo(f,this.server,h.server,u);if(!h.server)throw new xo("missing-alternate",this.server,void 0,u);if(a.some((f)=>dn(f,h.server)))throw p("loop");if(o>=n)throw p("too-many-redirects");if(Ot(this.transport)&&!this.options.reconnect)throw p("unsupported-transport");G("allocate redirected",this.server,"->",h),await this.switchServer(h)}}}async switchServer({server:n,domain:a}){let o;if(Ot(this.transport)){let c=this.transport;c.onData=()=>{},await c.close();let d=await this.options.reconnect(n,a);if(this.closed)throw d.onData=()=>{},await d.close(),new Oe;this.transport=d,this.tcpBuffer=Buffer.alloc(0),this.attachTransport(),o=this.transport.remoteAddress??n}else o=await bt(n,this.transport.addressFamily??0);this.server=n,this.pinnedServerEndpoint=o,this.serverEndpointSelection=Promise.resolve(o),this.nonce=void 0,this.realm=void 0,this.integrityKey=void 0}handleChannelData(n){let a=Hg(n),o=a&&this.addrByChannel[a.channelNumber];if(o&&a)this.onData.execute(a.data,o)}handleSTUNMessage(n,a){try{let o=ht(n);if(!o)throw Error("not stun message");if(o.messageClass===256||o.messageClass===272){let c=this.transactions[o.transactionIdHex];if(c){let d=c.integrityKey?ht(n,c.integrityKey):o;if(!d){G("TURN STUN response failed MESSAGE-INTEGRITY check");return}c.responseReceived(d,a)}}else if(o.messageClass===0)this.onData.execute(n,a);if(o.getAttributeValue("DATA")){let c=o.getAttributeValue("DATA"),d=o.getAttributeValue("XOR-PEER-ADDRESS")??a;this.onData.execute(c,d)}}catch(o){G("parse error",n.toString())}}dataReceived(n,a){let o=(c,d)=>{if(c.length>=4&&Wn(c))this.handleChannelData(c);else this.handleSTUNMessage(c,d)};if(Ot(this.transport)){this.tcpBuffer=Buffer.concat([this.tcpBuffer,n]);let{frames:c,rest:d}=zg(this.tcpBuffer);this.tcpBuffer=d;for(let h of c)o(h,a)}else o(n,a)}async send(n,a){if(this.transport.closed)return;await this.transport.send(Ot(this.transport)?Fg(n):n,a)}async createPermission(n){let a=new De(8,0);a.setAttribute("XOR-PEER-ADDRESS",n).setAttribute("USERNAME",this.username).setAttribute("REALM",this.realm).setAttribute("NONCE",this.nonce),await this.requestWithRetry(a,this.server)}refresh=(n)=>{this.refreshHandle=an(async(a,o,c)=>{let d=new AbortController;c.once(()=>{d.abort()});while(!d.signal.aborted){let h=0.8333333333333334*n*1000;G("refresh delay",h,{exp:n});try{await Dg(h,void 0,{signal:d.signal})}catch(p){if(d.signal.aborted)return;throw p}if(d.signal.aborted)return;let u=new De(4,0);u.setAttribute("LIFETIME",n);try{let[p]=await this.requestWithRetry(u,this.server,d.signal);n=p.getAttributeValue("LIFETIME"),G("refresh",{exp:n})}catch(p){if(d.signal.aborted)return;G("refresh error",p)}}})};async request(n,a,o,c,d){if(this.transactions[n.transactionIdHex])throw Error("exist");if(this.integrityKey)n.setAttribute("USERNAME",this.username).setAttribute("REALM",this.realm).setAttribute("NONCE",this.nonce).addMessageIntegrity(this.integrityKey).addFingerprint();let h=await this.resolveRequestTarget(a);if(this.closed)throw new Oe;let u=li(this.integrityKey,c,d),p=new hi(n,h,this,u);this.transactions[n.transactionIdHex]=p;try{return await p.run()}catch(f){throw f}finally{delete this.transactions[n.transactionIdHex]}}get serverEndpoint(){return this.pinnedServerEndpoint}async resolveRequestTarget(n){if(Ot(this.transport)||dn(n,this.server))return this.selectServerEndpoint();return bt(n,this.transport.addressFamily??0)}async serverDestination(){return this.pinnedServerEndpoint??this.selectServerEndpoint()}selectServerEndpoint(){return this.serverEndpointSelection??=this.resolveServerEndpoint().then((n)=>(this.pinnedServerEndpoint=n,n),(n)=>{throw this.serverEndpointSelection=void 0,n}),this.serverEndpointSelection}async resolveServerEndpoint(){let n=this.transport;if(!Ot(n))return bt(this.server,n.addressFamily??0);if(n.remoteAddress)return n.remoteAddress;if(n instanceof Vi||n instanceof Yi)throw Error(`${n.type} transport has no remote address`);return bt(this.server)}async requestWithRetry(n,a,o){let c,d;try{[c,d]=await this.request(n,a,void 0,{signal:o})}catch(h){if(h instanceof Fn==!1)throw G("requestWithRetry error",h),h;let[u]=h.response.getAttributeValue("ERROR-CODE"),p=h.response.getAttributeValue("NONCE"),f=h.response.getAttributeValue("REALM");if((u===401&&f||u===438&&this.realm)&&p){if(G("retry with nonce",u),this.nonce=p,u===401)this.realm=f;this.integrityKey=ey(this.username,this.realm,this.password),n.transactionId=jm(),[c,d]=await this.request(n,this.server,void 0,{signal:o})}else throw h}return[c,d]}async sendData(n,a){let o;try{o=await this.getChannel(a)}catch(c){G("channelBind error; falling back to Send Indication",c)}if(!o){await this.getPermission(a);let c=new De(6,16).setAttribute("DATA",n).setAttribute("XOR-PEER-ADDRESS",a);await this.sendStun(c,await this.serverDestination());return}await this.send(Og(o.number,n),await this.serverDestination())}async getPermission(n){let a=Gg(n);if(this.permissionByAddr[a])return;let o=this.creatingPermissionByAddr.get(a);if(o)return o;let c=this.permissionQueue.then(async()=>{if(this.permissionByAddr[a])return;await this.createPermission(n),this.permissionByAddr[a]=!0});this.permissionQueue=c.then(()=>{return},()=>{return}),this.creatingPermissionByAddr.set(a,c);try{await c}catch(d){throw G("createPermission error",d),d}finally{if(this.creatingPermissionByAddr.get(a)===c)this.creatingPermissionByAddr.delete(a)}}async getChannel(n){let a=Fo(n),o=this.channelBindingByAddr.get(a);if(o)return o;let c=this.channelByAddr[a],d=Cs(Date.now()/1000);if(c&&c.refreshAt>d)return c;let h=this.channelBindQueue.then(()=>this.ensureChannel(n));this.channelBindQueue=h.then(()=>{return},()=>{return}),this.channelBindingByAddr.set(a,h);try{return await h}catch(u){throw G("channelBind error",u),u}finally{if(this.channelBindingByAddr.get(a)===h)this.channelBindingByAddr.delete(a)}}async ensureChannel(n){let a=Fo(n),o=Cs(Date.now()/1000),c=this.channelByAddr[a];if(c&&c.refreshAt>o)return c;let d=!c;if(!c)c={number:this.channelNumber++,address:n,refreshAt:0},this.channelByAddr[a]=c,this.addrByChannel[c.number]=n;try{return await this.channelBind(c.number,n),c.refreshAt=Cs(Date.now()/1000)+this.channelRefreshTime,G(d?"channelBind":"channelBind refresh",c),c}catch(h){if(d)delete this.channelByAddr[a],delete this.addrByChannel[c.number];throw h}}async channelBind(n,a){let o=new De(9,0);o.setAttribute("CHANNEL-NUMBER",n).setAttribute("XOR-PEER-ADDRESS",a);let[c]=await this.requestWithRetry(o,this.server);if(c.messageMethod!==9)throw Error("should be CHANNEL_BIND")}async sendStun(n,a){await this.send(n.bytes,a)}async close(){if(this.closed)return;this.closed=!0;for(let n of Object.values(this.transactions))n.cancel();this.refreshHandle?.resolve?.(),await this.transport.close()}};function Yg(s,n){let a=wh(s[0]);if(a===4||a===6){if(n&&n!==a)G("udpFamily ignored for IP literal TURN server",{address:s,udpFamily:n,literalFamily:a});return a===6?"udp6":"udp4"}return(n??4)===6?"udp6":"udp4"}async function Qg({address:s,username:n,password:a},{lifetime:o,portRange:c,interfaceAddresses:d,ssl:h,tlsOptions:u,transport:p,connectTimeoutMs:f,udpFamily:m,signal:y}={}){o??=Wg,p??=h?"tls":"udp";let S=p==="udp"?await ji.init(Yg(s,m),{portRange:c,interfaceAddresses:d}):p==="tcp"?await Vi.init(s,{connectTimeoutMs:f}):await Yi.init(s,u,{connectTimeoutMs:f}),v=new Vg(s,n,a,o,S,{reconnect:p==="udp"?void 0:(w,T)=>p==="tcp"?Vi.init(w,{connectTimeoutMs:f}):Yi.init(w,Xg(s,T,u),{connectTimeoutMs:f})}),g=()=>{v.close().catch((w)=>G("failed to close aborted TURN client",w))};if(y?.aborted)g();y?.addEventListener("abort",g,{once:!0});try{if(y?.aborted)throw new Oe;if(await v.connectionMade(),y?.aborted)throw new Oe}catch(w){try{await v.close()}catch(T){G("failed to close TURN client after allocation failure",T)}throw w}finally{y?.removeEventListener("abort",g)}return v}async function zo(s,n={}){let a=await Qg(s,n);return new jg(a)}function Xg(s,n,a={}){let o=n??a.servername??s[0],c=a.checkServerIdentity??Th.checkServerIdentity;return{...a,servername:wh(o)?void 0:o,checkServerIdentity:(d,h)=>c(o,h)}}function Jg(s,n){if(!(s instanceof Fn))return;let[a]=s.response.getAttributeValue("ERROR-CODE")??[];if(a!==300)return;let o=s.response.alternateServers;return{server:o.find(([d])=>n===void 0||Zg(d)===n)??o[0],domain:s.response.getAttributeValue("ALTERNATE-DOMAIN")}}function Zg(s){return s.includes(":")?6:4}function ey(s,n,a){return Ng(s,n,a)}function ty(s,n,a={},o){let c=["ipsec","tun","utun","tap"],d=["vmnet","veth"],{useLinkLocalAddress:h}=a,u=Object.keys(s).map((p)=>{for(let m of[...c,...d])if(p.startsWith(m))return{nic:p,addresses:[]};let f=(s[p]??[]).filter((m)=>Dr(m.family)===n&&!m.internal&&(h?!0:!o(m)));return{nic:p,addresses:f.map((m)=>m.address)}}).filter((p)=>!!p);return u.sort((p,f)=>p.nic.localeCompare(f.nic)),Object.values(u).flatMap((p)=>p.addresses)}var sy=_("werift-ice : packages/ice/src/utils.ts");function ry(s){return Dr(s.family)===4&&s.address?.startsWith("169.254.")||Dr(s.family)===6&&s.address?.startsWith("fe80::")}function qo(s,{useLinkLocalAddress:n}={}){let a=bh.networkInterfaces();return sy(a),ty(a,s,{useLinkLocalAddress:n},ry)}function ny(s,n,a={}){let o=[];if(s)o.push(...qo(4,a));if(n)o.push(...qo(6,a));return o}var D=_("werift-ice : packages/ice/src/ice.ts : log"),ay=["stun.l.google.com",19302],oy=class{constructor(s,n){if(this._iceControlling=s,this.closedSignal=new Promise((a)=>{this.signalClosed=a}),this.options={...bg,...n},this.iceLite)this._iceControlling=!1;this.applyStunTurnServersFromOptions(),this.restart(),D("new Connection",this.options)}_iceControlling;localUsername=Mt(4);localPassword=Mt(22);remoteIsLite=!1;remotePassword="";remoteUsername="";checkList=[];localCandidates=[];stunServer;turnServer;options;remoteCandidatesEnd=!1;remoteCandidatesEndRequested=!1;remoteResolutions=new Set;localCandidatesEnd=!1;checksBegun=!1;generation=-1;remoteGeneration=0;userHistory={};restarted=!1;tieBreaker=$m(8).readBigUInt64BE(0);state="new";lookup;_remoteCandidates=[];nominated;nominating=!1;remoteChecks=new AbortController;checkListDone=!1;closedSignal;signalClosed;closing=new AbortController;checkListState=new xi;earlyChecks=[];earlyChecksDone=!1;localCandidatesStart=!1;protocols=[];queryConsentHandle;consentFresh=!1;consentSessionId=0;consentExpiryTimer;consentRequestAbort;provisional;reflexiveBySocket=new WeakMap;onData=new E;stateChanged=new E;onIceCandidate=new E;setIceServers(s){if(this.options={...this.options,stunServer:s.stunServer,turnServer:s.turnServer,turnUsername:s.turnUsername,turnPassword:s.turnPassword,turnTransport:s.turnTransport},s.forceTurn!==void 0)this.options.forceTurn=s.forceTurn;if(s.useTcp!==void 0)this.options.useTcp=s.useTcp;if(s.turnTlsOptions!==void 0)this.options.turnTlsOptions=s.turnTlsOptions;if(s.turnUdpFamily!==void 0)this.options.turnUdpFamily=s.turnUdpFamily;this.applyStunTurnServersFromOptions(),D("Connection ice servers updated",this.options)}applyStunTurnServersFromOptions(){this.stunServer=Uo(this.options.stunServer)??ay,this.turnServer=Uo(this.options.turnServer)}get iceControlling(){return this._iceControlling}set iceControlling(s){if(this.iceLite)s=!1;if(this.nominated)return;this.applyIceControlling(s)}get iceLite(){return this.options.iceLite}async restart(){this.generation++,this.remoteGeneration++;let s=this.restarted?{[this.localUsername]:this.localPassword}:{};if(this.localUsername=Mt(4),this.localPassword=Mt(22),this.options.localPasswordPrefix)this.localPassword=this.options.localPasswordPrefix+this.localPassword.slice(this.options.localPasswordPrefix.length);this.userHistory={...s,[this.localUsername]:this.localPassword},this.restarted=!0,this.remoteUsername="",this.remotePassword="",this.localCandidates=[],this._remoteCandidates=[],this.remoteCandidatesEnd=!1,this.remoteCandidatesEndRequested=!1,this.remoteResolutions.clear(),this.localCandidatesEnd=!1,this.checksBegun=!1,this.state="new",this.lookup?.close?.(),this.lookup=void 0,this.nominated=void 0,this.nominating=!1,this.cancelChecks(),this.checkList=[],this.checkListDone=!1,this.checkListState=new xi,this.earlyChecks=[],this.earlyChecksDone=!1,this.localCandidatesStart=!1;for(let n of this.protocols)if(n.localCandidate)n.localCandidate.refreshId(),n.localCandidate.generation=this.generation,n.localCandidate.ufrag=this.localUsername;this.stopConsentLifecycle(),this.endProvisional()}restartRemote(){this.remoteGeneration++,this.remoteUsername="",this.remotePassword="",this._remoteCandidates=[],this.remoteCandidatesEnd=!1,this.remoteCandidatesEndRequested=!1,this.remoteResolutions.clear(),this.checksBegun=!1,this.state="new",this.nominated=void 0,this.nominating=!1,this.cancelChecks(),this.checkList=[],this.checkListDone=!1,this.checkListState=new xi,this.earlyChecks=[],this.earlyChecksDone=!1,this.stopConsentLifecycle(),this.endProvisional()}cancelChecks(){this.remoteChecks.abort(),this.remoteChecks=new AbortController;for(let s of this.checkList)s.handle?.resolve?.()}endProvisional(){this.provisional?.checks.abort(),this.provisional=void 0}stageLocalCredentials(s,n){this.userHistory[s]=n,this.endProvisional(),this.provisional={localUsername:s,localPassword:n,remoteCandidates:[],remoteCandidatesEnd:!1,remoteCandidatesEndRequested:!1,resolutions:new Set,revision:0,pairs:[],started:!1,checks:new AbortController}}discardStagedLocalCredentials(s){if(this.provisional?.localUsername===s)this.endProvisional();if(s!==this.localUsername)delete this.userHistory[s]}setProvisionalRemoteParams({usernameFragment:s,password:n}){let a=this.provisional;if(!a)return;if(a.remoteUsername===s&&a.remotePassword===n)return;a.remoteUsername=s,a.remotePassword=n,a.remoteCandidates=[],a.remoteCandidatesEnd=!1,a.remoteCandidatesEndRequested=!1,a.resolutions.clear(),a.revision++,a.checks.abort(),a.checks=new AbortController,a.pairs=[],a.nominated=void 0,a.nominating=!1}async addProvisionalRemoteCandidate(s){let n=this.provisional;if(!n)return;let a=n.revision,o=()=>this.provisional===n&&n.revision===a;if(!s){if(n.remoteCandidatesEnd||n.remoteCandidatesEndRequested)return;if(n.remoteCandidatesEndRequested=!0,n.resolutions.size>0){if(await Promise.allSettled([...n.resolutions]),!o())return}n.remoteCandidatesEnd=!0;return}if(n.remoteCandidatesEnd||n.remoteCandidatesEndRequested)return;if(s.host.includes(".local")){try{if(!this.lookup)this.lookup=new Po;let c=this.lookup.lookup(s.host);n.resolutions.add(c);try{s.host=await c}finally{n.resolutions.delete(c)}}catch(c){return}if(!o()||n.remoteCandidatesEnd)return}try{_i(s)}catch(c){return}if(!o()||n.remoteCandidates.some((c)=>c.host===s.host&&c.port===s.port&&c.transport.toLowerCase()===s.transport.toLowerCase()))return;n.remoteCandidates.push(s);for(let c of this.protocols)this.tryProvisionalPair(n,c,s)}startProvisionalChecks(){let s=this.provisional;if(!s||s.started)return;s.started=!0;for(let n of s.remoteCandidates)for(let a of this.protocols)this.tryProvisionalPair(s,a,n);for(let n of s.pairs)this.checkProvisional(s,n)}get provisionalNominated(){return this.provisional?.nominated}tryProvisionalPair(s,n,a){if(!n.localCandidate?.canPairWith(a)||n.localCandidate.transport.toLowerCase()==="tcp"&&n.localCandidate.tcptype==="passive"&&a.type!=="prflx"||s.pairs.some((c)=>c.protocol===n&&c.remoteCandidate===a))return;let o=new dr(n,a,this.iceControlling);if(this.options.filterCandidatePair&&!this.options.filterCandidatePair(o))return;if(o.updateState(1),s.pairs.push(o),s.started)this.checkProvisional(s,o)}async checkProvisional(s,n,a=!0){let o=s.revision,c=()=>this.provisional===s&&s.revision===o&&s.pairs.includes(n);if(this.iceLite||!c()||!s.started||!s.remoteUsername||!s.remotePassword||[2,3].includes(n.state))return;n.updateState(2);let d=this.iceControlling&&!this.remoteIsLite,h=this.buildRequest({nominate:d,localUsername:s.localUsername,remoteUsername:s.remoteUsername,iceControlling:this.iceControlling,localCandidate:n.localCandidate});try{n.requestsSent++;let[,u]=await n.protocol.request(h,n.remoteAddr,Buffer.from(s.remotePassword,"utf8"),{retransmissions:n.localCandidate.transport.toLowerCase()==="tcp"?0:4,signal:s.checks.signal});if(n.responsesReceived++,!c())return;if(u[0]!==n.remoteAddr[0]||u[1]!==n.remoteAddr[1]){n.updateState(4);return}}catch(u){if(!c())return;let p=u.response?.getAttributeValue("ERROR-CODE")?.[0];if(n.updateState(4),p===487&&a)return this.switchRole(h.attributesKeys.includes("ICE-CONTROLLED")),n.updateState(1),this.checkProvisional(s,n,!1);return}if(d||n.remoteNominated)n.nominated=!0;if(n.updateState(3),!n.nominated&&this.iceControlling&&!s.nominated&&!s.nominating)await this.nominateProvisional(s,n,c);if(n.nominated&&!s.nominated)D("provisional nominated",n.toJSON()),s.nominated=n}async nominateProvisional(s,n,a){s.nominating=!0;let o=this.buildRequest({nominate:!0,localUsername:s.localUsername,remoteUsername:s.remoteUsername,iceControlling:this.iceControlling,localCandidate:n.localCandidate});try{if(n.requestsSent++,await n.protocol.request(o,n.remoteAddr,Buffer.from(s.remotePassword,"utf8"),{retransmissions:n.localCandidate.transport.toLowerCase()==="tcp"?0:4,signal:s.checks.signal}),n.responsesReceived++,a())n.nominated=!0}catch(c){D("provisional regular nomination failed",c)}finally{if(a())s.nominating=!1}}checkIncomingProvisional(s,n,a,o){let c=n.getAttributeValue("USERNAME"),d=typeof c==="string"?Li(c).localUsername:void 0;if(s.remoteUsername&&d!==s.remoteUsername)return;let[h,u]=a,p=s.remoteCandidates.find((m)=>m.host===h&&m.port===u);if(!p)p=new Me(Mt(10),1,o.localCandidate?.transport??"udp",n.getAttributeValue("PRIORITY"),h,u,"prflx",void 0,void 0,o.localCandidate?.transport==="tcp"?ko(o.localCandidate.tcptype):void 0,void 0,void 0),s.remoteCandidates.push(p);let f=s.pairs.find((m)=>m.protocol===o&&m.remoteCandidate===p);if(!f)f=new dr(o,p,this.iceControlling),f.updateState(1),s.pairs.push(f);if(f.noteIncomingRequest(n.transactionIdHex),f.requestsReceived++,f.responsesSent++,n.attributesKeys.includes("USE-CANDIDATE")&&!this.iceControlling){if(f.remoteNominated=!0,this.iceLite||f.state===3)f.nominated=!0,f.updateState(3),s.nominated??=f}if(!this.iceLite&&[1,4].includes(f.state))this.checkProvisional(s,f)}commitLocalCredentials(s,n){if(this.localUsername!==s)delete this.userHistory[this.localUsername];this.localUsername=s,this.localPassword=n,this.userHistory[s]=n;for(let a of this.protocols)if(a.localCandidate)a.localCandidate.ufrag=s}dropOtherRemoteGenerations(s){let n=(a)=>!!a.ufrag&&a.ufrag!==s;this._remoteCandidates=this._remoteCandidates.filter((a)=>!n(a));for(let a of this.checkList)if(n(a.remoteCandidate))a.handle?.resolve?.();this.checkList=this.checkList.filter((a)=>!n(a.remoteCandidate))}resetNominatedPair(){D("resetNominatedPair"),this.nominated=void 0,this.nominating=!1,this.stopConsentLifecycle()}setRemoteParams({iceLite:s,usernameFragment:n,password:a}){D("setRemoteParams",{iceLite:s,usernameFragment:n,password:a}),this.remoteIsLite=s,this.remoteUsername=n,this.remotePassword=a}async gatherCandidates(){if(!this.localCandidatesStart){this.localCandidatesStart=!0;let s=this.generation,n=this.protocols.filter((c)=>c.localCandidate?.type==="relay");this.protocols=this.protocols.filter((c)=>!n.includes(c)),Promise.allSettled(n.map((c)=>c.close()));for(let c of this.protocols)if(c.localCandidate){c.localCandidate.generation=this.generation,c.localCandidate.ufrag=this.localUsername,this.appendLocalCandidate(c.localCandidate);let d=this.reflexiveBySocket.get(c);if(d)this.appendLocalCandidate(this.withGeneration(d))}let a=Eg({enumerated:ny(this.options.useIpv4,this.options.useIpv6,{useLinkLocalAddress:this.options.useLinkLocalAddress}),interfaceAddresses:this.options.interfaceAddresses,additionalHostAddresses:this.options.additionalHostAddresses,useIpv4:this.options.useIpv4,useIpv6:this.options.useIpv6,log:D}),o=this.getCandidatePromises(a,this.options.stunGatherTimeout,s);if(await Promise.race([Promise.allSettled(o),this.closedSignal]),!this.isGathering(s))return;this.localCandidatesEnd=!0}if(this.state==="new"&&!this.checksBegun)this.setState("completed")}isGathering(s){return this.generation===s&&this.state!=="closed"}withGeneration(s){return new Me(s.foundation,s.component,s.transport,s.priority,s.host,s.port,s.type,s.relatedAddress,s.relatedPort,s.tcptype,this.generation,this.localUsername)}get gathersFromServers(){return!!this.stunServer||!!this.turnServer}appendLocalCandidate(s){this.localCandidates.push(s),this.onIceCandidate.execute(s)}ensureProtocol(s){s.onRequestReceived.subscribe((n,a,o)=>{if(n.messageMethod!==1){this.respondError(n,a,s,[400,"Bad Request"]);return}let c=n.getAttributeValue("USERNAME"),{remoteUsername:d}=Li(c),h=this.userHistory[d]??this.localPassword,{iceControlling:u}=this;if(u&&n.attributesKeys.includes("ICE-CONTROLLING"))if(this.tieBreaker>=n.getAttributeValue("ICE-CONTROLLING")){this.respondError(n,a,s,[487,"Role Conflict"],h);return}else this.switchRole(!1);else if(!u&&n.attributesKeys.includes("ICE-CONTROLLED"))if(this.iceLite||this.tieBreaker<n.getAttributeValue("ICE-CONTROLLED")){this.respondError(n,a,s,[487,"Role Conflict"],h);return}else{this.switchRole(!0);return}if(this.options.filterStunResponse&&!this.options.filterStunResponse(n,a,s))return;let p=new De(1,256,n.transactionId);p.setAttribute("XOR-MAPPED-ADDRESS",a).addMessageIntegrity(Buffer.from(h,"utf8")).addFingerprint(),s.sendStun(p,a).catch((m)=>{D("sendStun error",m)});let f=this.provisional;if(f&&d===f.localUsername&&d!==this.localUsername){this.checkIncomingProvisional(f,n,a,s);return}if(this.checkList.length===0&&!this.earlyChecksDone)this.earlyChecks.push([n,a,s]);else this.checkIncoming(n,a,s)}),s.onDataReceived.subscribe((n)=>{try{let a=this.nominated;if(a&&a.protocol===s)a.packetsReceived++,a.bytesReceived+=n.length;this.onData.execute(n)}catch(a){D("dataReceived",a)}}),s.onConnectionClosed?.subscribe((n)=>{this.handleConnectionClosed(s,n)})}handleConnectionClosed(s,n){let a=this.nominated;if(!a||a.protocol!==s||a.remoteAddr[0]!==n[0]||a.remoteAddr[1]!==n[1])return;if(this.state==="closed"||this.state==="failed")return;D("selected tcp connection closed",a.toJSON()),this.stopConsentLifecycle(),this.setState("failed")}getCandidatePromises(s,n=5,a=this.generation){let o=[],c=()=>!this.isGathering(a),{stunServer:d,turnServer:h}=this,{turnUsername:u,turnPassword:p,interfaceAddresses:f}=this.options,m=this.iceLite,y=!m&&this.options.forceTurn&&h&&u&&p;s=s.filter((g)=>{if(this.protocols.find((w)=>w.localIp===g))return!1;if(Mr(Wo(g),f)===g&&this.protocols.some((w)=>w instanceof ur&&w.localCandidate?.type==="host"&&Gt(w.localCandidate.host)===Gt(g)))return!1;return!0});let S=this.protocols.filter((g)=>g instanceof ur&&g.localCandidate?.type==="host"&&g.localCandidate.transport==="udp"),v=y?[]:s.map(async(g)=>{let w=new ur;this.ensureProtocol(w);let T=Mr(Wo(g),f);try{if(await w.connectionMade(Gt(g),this.options.portRange,f),c()){await w.close();return}let[b,C]=w.getExtraInfo(),P=g;if(T){if(P=dy(b),P!==g)D("host address differs from the bound interface address; advertise the bound one",g,P)}let x=[P,C];return w.localIp=P,this.protocols.push(w),D("protocol",w.localIp),w.localCandidate=new Me(vs("host","udp",x[0]),1,"udp",$t("host",{transport:"udp"}),x[0],x[1],"host",void 0,void 0,void 0,this.generation,this.localUsername),this.pairLocalProtocol(w),this.appendLocalCandidate(w.localCandidate),w}catch(b){if(T)D("failed to bind UDP socket to interface address",T,b);else D("error protocol STUN",b)}});if(!y)o.push(...v.map((g)=>g.then((w)=>w?.localCandidate)));if(!y&&this.options.useTcp){let g=s.map(async(w)=>{if(this.options.tcpPassive!==!1){let T=new Mg;if(this.ensureProtocol(T),await T.connectionMade(w,this.options.portRange),c()){await T.close();return}T.localIp=w,T.localCandidate=new Me(vs("host","tcp",w),1,"tcp",$t("host",{transport:"tcp",tcptype:"passive"}),w,T.listeningPort,"host",void 0,void 0,"passive",this.generation,this.localUsername),this.protocols.push(T),this.appendLocalCandidate(T.localCandidate)}if(!m){let T=new Bg;if(this.ensureProtocol(T),await T.connectionMade(w),c()){await T.close();return}T.localIp=w,T.localCandidate=new Me(vs("host","tcp",w),1,"tcp",$t("host",{transport:"tcp",tcptype:"active"}),w,9,"host",void 0,void 0,"active",this.generation,this.localUsername),this.protocols.push(T),this.pairLocalProtocol(T),this.appendLocalCandidate(T.localCandidate)}});o.push(...g)}if(!m&&!y&&d){let g=S.filter((T)=>Gt(T.localCandidate.host)).map(async(T)=>{let b,C=await Promise.race([Do(T,d).catch(()=>{return}),new Promise((x)=>{b=setTimeout(()=>x(void 0),n*1000)})]);if(clearTimeout(b),c())return;let P=this.reflexiveBySocket.get(T);if(C&&(C.host!==P?.host||C.port!==P?.port))this.reflexiveBySocket.set(T,C),this.appendLocalCandidate(C);return C??P});o.push(...g);let w=v.map(async(T)=>{let b=await T;if(!b)return;return new Promise(async(P,x)=>{let H=setTimeout(x,n*1000);if(b.localCandidate?.host&&Gt(b.localCandidate?.host)){let O=await Do(b,d).catch((ee)=>{D("error",ee)});if(O&&!c())this.reflexiveBySocket.set(b,O),this.appendLocalCandidate(O);clearTimeout(H),P(O)}else clearTimeout(H),P()}).catch((P)=>{D("query STUN server",P)})});o.push(...w)}if(!m&&h&&u&&p){let g=(async()=>{let w=this.options.turnTransport??"udp",T=await zo({address:h,username:u,password:p},{portRange:this.options.portRange,interfaceAddresses:this.options.interfaceAddresses,transport:w,tlsOptions:this.options.turnTlsOptions,connectTimeoutMs:(this.options.turnConnectTimeout??8)*1000,udpFamily:this.options.turnUdpFamily,signal:this.closing.signal}).catch(async(P)=>{if(w==="udp"&&!this.closing.signal.aborted)return await zo({address:h,username:u,password:p},{portRange:this.options.portRange,interfaceAddresses:this.options.interfaceAddresses,transport:"tcp",connectTimeoutMs:(this.options.turnConnectTimeout??8)*1000,signal:this.closing.signal});else throw P});if(c()){await T.close();return}this.ensureProtocol(T),this.protocols.push(T);let b=T.turn.relayedAddress,C=T.turn.mappedAddress;return D("turn candidateAddress",b),T.localCandidate=new Me(vs("relay","udp",b[0]),1,"udp",$t("relay"),b[0],b[1],"relay",C[0],C[1],void 0,this.generation,this.localUsername),this.pairLocalProtocol(T),this.appendLocalCandidate(T.localCandidate),T.localCandidate})().catch((w)=>{D("query TURN server",w)});o.push(g)}return o}async connect(){if(D("start connect ice"),!this.localCandidatesEnd){if(!this.localCandidatesStart)throw Error("Local candidates gathering was not performed")}if(!this.remoteUsername||!this.remotePassword)throw Error("Remote username or password is missing");this.checksBegun=!0;for(let n of this.remoteCandidates)this.pairRemoteCandidate(n);if(this.sortCheckList(),!this.iceLite)this.unfreezeInitial();D("earlyChecks",this.localPassword,this.earlyChecks.length);for(let n of this.earlyChecks)this.checkIncoming(...n);if(this.earlyChecks=[],this.earlyChecksDone=!0,this.iceLite){if(!this.nominated){let n=ps;while(!this.checkListDone&&this.state!=="closed")if(n=await this.checkListState.get(),D("checkListState",n),n===hr)break;if(n!==hr&&!this.nominated)throw Error("ICE negotiation failed")}this.setState("connected");return}for(;;){if(this.state==="closed")break;if(!this.schedulingChecks())break;await ih.setTimeout(20)}let s=ps;while(this.checkList.length>0&&s===ps)s=await this.checkListState.get(),D("checkListState",s);for(let n of this.checkList)n.handle?.resolve?.();if(s!==hr)throw Error("ICE negotiation failed");this.queryConsent(),this.setState("connected")}unfreezeInitial(){let[s]=this.checkList;if(!s)return;if(s.state===0)s.updateState(1);let n=new Set(s.localCandidate.foundation);for(let a of this.checkList)if(a.component===s.component&&!n.has(a.localCandidate.foundation)&&a.state===0)a.updateState(1),n.add(a.localCandidate.foundation)}schedulingChecks(){{let s=this.checkList.filter((n)=>{if(this.options.forceTurn&&n.protocol.type===ur.type)return!1;return!0}).find((n)=>n.state===1);if(s)return s.handle=this.checkStart(s),!0}{let s=this.checkList.find((n)=>n.state===0);if(s)return s.handle=this.checkStart(s),!0}if(!this.remoteCandidatesEnd||!this.localCandidatesEnd)return!this.checkListDone;return!1}stopConsentLifecycle(){if(this.consentSessionId++,this.consentFresh=!1,this.consentExpiryTimer!==void 0)clearTimeout(this.consentExpiryTimer),this.consentExpiryTimer=void 0;this.consentRequestAbort?.abort(),this.consentRequestAbort=void 0;let s=this.queryConsentHandle;this.queryConsentHandle=void 0,s?.resolve?.()}shouldNominateConsentRequest(s){return this.iceControlling&&this.remoteIsLite&&this.nominated?.id===s.id}canSendApplicationData(){if(!this.nominated)return!1;if(this.state==="closed"||this.state==="failed")return!1;if(this.iceLite)return!0;return this.consentFresh}abortableDelay(s,n){return new Promise((a,o)=>{if(n.aborted){o(new DOMException("The operation was aborted","AbortError"));return}let c=setTimeout(()=>{n.removeEventListener("abort",d),a()},s),d=()=>{clearTimeout(c),o(new DOMException("The operation was aborted","AbortError"))};n.addEventListener("abort",d,{once:!0})})}queryConsent=()=>{if(this.iceLite)return;this.stopConsentLifecycle();let s=this.consentSessionId;this.consentFresh=!0;let n=an(async(a,o,c)=>{let d=!1,h=new AbortController,u=()=>{if(this.consentExpiryTimer===void 0)return;clearTimeout(this.consentExpiryTimer),this.consentExpiryTimer=void 0},p=()=>{if(d||s!==this.consentSessionId)return;u(),this.consentExpiryTimer=setTimeout(()=>{if(this.consentExpiryTimer=void 0,d||s!==this.consentSessionId)return;if(this.state==="closed"||this.state==="failed")return;if(D("Consent to send expired"),this.consentFresh=!1,this.consentSessionId++,this.consentRequestAbort?.abort(),this.consentRequestAbort=void 0,this.queryConsentHandle===n)this.queryConsentHandle=void 0;d=!0,h.abort(),this.setState("failed")},Sg*1000)};c.once(()=>{if(d=!0,s===this.consentSessionId)u(),this.consentRequestAbort?.abort(),this.consentRequestAbort=void 0;if(h.abort(),this.queryConsentHandle===n)this.queryConsentHandle=void 0}),p();let f=()=>yg*(0.8+0.4*Math.random())*1000,m=Date.now()+f(),y=()=>this.state==="closed"||this.state==="failed";try{while(!y()&&!d&&s===this.consentSessionId){if(await this.abortableDelay(Math.max(0,m-Date.now()),h.signal),d||y()||s!==this.consentSessionId)break;m=Date.now()+f();let S=this.nominated;if(!S)break;let v=S.id,g=this.remoteGeneration,w=this.remotePassword,{localUsername:T,remoteUsername:b,iceControlling:C}=this,P=this.buildRequest({nominate:this.shouldNominateConsentRequest(S),localUsername:T,remoteUsername:b,iceControlling:C,localCandidate:S.localCandidate});this.consentRequestAbort?.abort();let x=new AbortController;this.consentRequestAbort=x,S.consentRequestsSent++,S.requestsSent++;let H=Tg(S.rtt),O=performance.now();S.protocol.request(P,S.remoteAddr,Buffer.from(w,"utf8"),{retransmissions:0,responseTimeout:H,signal:x.signal,onRequestSent:(ee)=>{if(ee>0)S.retransmissionsSent++}}).then(()=>{if(s!==this.consentSessionId||d)return;let ee=this.state;if(ee==="closed"||ee==="failed")return;if(this.nominated?.id!==v)return;if(this.remoteGeneration!==g)return;if(this.remotePassword!==w)return;let da=(performance.now()-O)/1000;if(S.rtt=da,S.totalRoundTripTime+=da,S.roundTripTimeMeasurements++,S.responsesReceived++,this.consentFresh=!0,p(),ee==="disconnected")this.setState("connected")}).catch((ee)=>{if(s===this.consentSessionId&&this.nominated?.id===v)D("no stun response",ee)})}}catch(S){}finally{if(s===this.consentSessionId)u()}});this.queryConsentHandle=n};async close(){if(this.setState("closed"),this.signalClosed(),this.closing.abort(),this.cancelChecks(),this.endProvisional(),this.stopConsentLifecycle(),this.checkList&&!this.checkListDone)this.checkListState.put(new Promise((s)=>{s(ps)}));this.nominated=void 0;for(let s of this.protocols)if(s.close)await s.close();this.protocols=[],this.localCandidates=[],this.lookup?.close?.(),this.lookup=void 0}setState(s){this.state=s,this.stateChanged.execute(s)}async addRemoteCandidate(s){if(!s){if(this.remoteCandidatesEnd||this.remoteCandidatesEndRequested)return;if(this.remoteCandidatesEndRequested=!0,this.remoteResolutions.size>0){let n=this.remoteGeneration;if(await Promise.allSettled([...this.remoteResolutions]),this.remoteGeneration!==n)return}this.remoteCandidatesEnd=!0;return}if(this.remoteCandidatesEnd||this.remoteCandidatesEndRequested)return;if(s.host.includes(".local")){let n=this.remoteGeneration;try{if(!this.lookup)this.lookup=new Po;let a=this.lookup.lookup(s.host);this.remoteResolutions.add(a);try{s.host=await a}finally{this.remoteResolutions.delete(a)}}catch(a){return}if(this.remoteGeneration!==n||this.remoteCandidatesEnd)return}try{_i(s)}catch(n){return}D("addRemoteCandidate",s),this._remoteCandidates.push(s),this.pairRemoteCandidate(s),this.sortCheckList()}send=async(s)=>{if(!this.canSendApplicationData())return;let n=this.nominated;await n.protocol.sendData(s,n.remoteAddr),n.packetsSent++,n.bytesSent+=s.length};getDefaultCandidate(){let s=this.localCandidates.sort((a,o)=>a.priority-o.priority),[n]=s;return n}set remoteCandidates(s){if(this.remoteCandidatesEnd)throw Error("Cannot set remote candidates after end-of-candidates.");this._remoteCandidates=[];for(let n of s){try{_i(n)}catch(a){continue}this._remoteCandidates.push(n)}this.remoteCandidatesEnd=!0}get remoteCandidates(){return this._remoteCandidates}get candidatePairs(){return this.checkList}sortCheckList(){Rg(this.checkList,this.iceControlling)}findPair(s,n){return this.checkList.find((o)=>o.protocol===s&&o.remoteCandidate===n)}applyIceControlling(s){this._iceControlling=s;for(let n of this.checkList)n.iceControlling=s}switchRole(s){if(D("switch role",s),this.iceLite)s=!1;this.applyIceControlling(s),this.sortCheckList()}checkComplete(s){if(s.handle=void 0,s.state===3){if(s.nominated&&this.checkList.includes(s)&&(s.remoteCandidate.ufrag==null||s.remoteCandidate.ufrag===this.remoteUsername)&&this.nominated==null){if(D("nominated",s.toJSON()),this.nominated=s,this.nominating=!1,this.consentFresh=!0,this.pruneTcpConnections(s),!this.iceLite&&(this.state==="connected"||this.state==="completed"))this.queryConsent();for(let n of this.checkList)if(n.component===s.component&&[1,0].includes(n.state))n.updateState(4)}if(this.nominated){if(!this.checkListDone)D("ICE completed"),this.checkListState.put(new Promise((n)=>n(hr))),this.checkListDone=!0;return}D("not completed",s.toJSON());for(let n of this.checkList)if(n.localCandidate.foundation===s.localCandidate.foundation&&n.state===0)n.updateState(1)}if(this.nominateTcpPairIfReady(),this.nominating)return;{let n=[3,4];if(this.checkList.find(({state:a})=>!n.includes(a)))return}if(!this.iceControlling){if(this.checkList.find(({state:a})=>a===3))return}if(!this.checkListDone&&this.localCandidatesEnd&&this.remoteCandidatesEnd)D("ICE failed"),this.checkListState.put(new Promise((n)=>{n(ps)}))}checkStart=(s)=>an(async(n,a,o)=>{D("check start",s.toJSON());let c=new AbortController;o.once(()=>c.abort());let d=AbortSignal.any([c.signal,this.remoteChecks.signal]),h=this.remoteGeneration;s.updateState(2);let u={},{remotePassword:p,remoteUsername:f,generation:m}=this,y=s.localCandidate.ufrag??this.localUsername,S=this.iceControlling&&!this.remoteIsLite&&!this.isTcpPair(s),v=this.buildRequest({nominate:S,localUsername:y,remoteUsername:f,iceControlling:this.iceControlling,localCandidate:s.localCandidate}),g=performance.now();try{s.requestsSent++;let[w,T]=await s.protocol.request(v,s.remoteAddr,Buffer.from(p,"utf8"),{...this.checkRequestOptions(s),signal:d});s.responsesReceived++;let C=(performance.now()-g)/1000;s.rtt=C,s.totalRoundTripTime+=C,s.roundTripTimeMeasurements++,D("response received",v.toJSON(),w.toJSON(),T,{localUsername:y,remoteUsername:f,remotePassword:p,generation:m,rtt:C}),u.response=w,u.addr=T}catch(w){if(d.aborted||w instanceof Oe){n();return}let T=w;if(D("failure case",v.toJSON(),T.response?JSON.stringify(T.response.toJSON(),null,2):w,{localUsername:y,remoteUsername:f,remotePassword:p,generation:m},s.remoteAddr),T.response?.getAttributeValue("ERROR-CODE")[0]===487){if(v.attributesKeys.includes("ICE-CONTROLLED"))this.switchRole(!0);else if(v.attributesKeys.includes("ICE-CONTROLLING"))this.switchRole(!1);await this.retryCheck(s,o),n();return}if(T.response?.getAttributeValue("ERROR-CODE")[0]===401){D("retry 401",s.toJSON()),await this.retryCheck(s,o),n();return}else{D("checkStart CandidatePairState.FAILED",s.toJSON()),s.updateState(4),this.checkComplete(s),n();return}}if(u.addr[0]!==s.remoteAddr[0]||u.addr[1]!==s.remoteAddr[1]){s.updateState(4),this.checkComplete(s),n();return}if(S||s.remoteNominated)s.nominated=!0;else if(this.usesTcpRegularNomination(s));else if(this.iceControlling&&!this.nominating){this.nominating=!0;let w=this.buildRequest({nominate:!0,localUsername:y,remoteUsername:f,iceControlling:this.iceControlling,localCandidate:s.localCandidate});try{s.requestsSent++,await s.protocol.request(w,s.remoteAddr,Buffer.from(this.remotePassword,"utf8"),{...this.checkRequestOptions(s),signal:d}),s.responsesReceived++}catch(T){if(d.aborted||T instanceof Oe||this.isStaleNomination(s,h)){n();return}this.nominating=!1,s.updateState(4),this.checkComplete(s),n();return}if(this.isStaleNomination(s,h)){n();return}s.nominated=!0}s.updateState(3),this.checkComplete(s),n()});async retryCheck(s,n){let a=this.checkStart(s);n.once(()=>a.resolve()),await a.awaitable}isTcpPair(s){return s.localCandidate.transport.toLowerCase()==="tcp"}usesTcpRegularNomination(s){return this.iceControlling&&!this.remoteIsLite&&this.isTcpPair(s)}checkRequestOptions(s){let n=(a)=>{if(a>0)s.retransmissionsSent++};if(this.isTcpPair(s))return{retransmissions:0,responseTimeout:eg,onRequestSent:n};return{retransmissions:4,onRequestSent:n}}nominateTcpPairIfReady(){if(!this.iceControlling||this.remoteIsLite||this.nominated||this.nominating)return;for(let s of this.checkList){if(!this.isTcpPair(s))continue;if(s.state===3){this.nominateTcpPair(s);return}if(s.state!==4)return}}nominateTcpPair(s){this.nominating=!0;let n=this.remoteGeneration,a=this.buildRequest({nominate:!0,localUsername:s.localCandidate.ufrag??this.localUsername,remoteUsername:this.remoteUsername,iceControlling:this.iceControlling,localCandidate:s.localCandidate});s.requestsSent++,s.protocol.request(a,s.remoteAddr,Buffer.from(this.remotePassword,"utf8"),{...this.checkRequestOptions(s),signal:this.remoteChecks.signal}).then(()=>{if(this.isStaleNomination(s,n))return;s.responsesReceived++,s.nominated=!0,this.nominating=!1,this.checkComplete(s)},(o)=>{if(this.isStaleNomination(s,n))return;D("tcp nomination failed",s.toJSON(),o),this.nominating=!1,s.updateState(4),this.checkComplete(s)})}isStaleNomination(s,n){return this.state==="closed"||this.remoteGeneration!==n||!this.checkList.includes(s)}addPair(s){this.checkList.push(s),this.sortCheckList()}checkIncoming(s,n,a){let o=s.getAttributeValue("USERNAME"),{remoteUsername:c}=Li(o),d,[h,u]=n;for(let f of this.remoteCandidates)if(f.host===h&&f.port===u){d=f;break}if(!d)d=new Me(Mt(10),1,a.localCandidate?.transport??"udp",s.getAttributeValue("PRIORITY"),h,u,"prflx",void 0,void 0,a.localCandidate?.transport==="tcp"?ko(a.localCandidate.tcptype):void 0,void 0,void 0),this._remoteCandidates.push(d);let p=this.findPair(a,d);if(!p)p=new dr(a,d,this.iceControlling),p.updateState(1),this.addPair(p);if(p.noteIncomingRequest(s.transactionIdHex),p.requestsReceived++,p.responsesSent++,D("Triggered Checks",s.toJSON(),p.toJSON(),{localUsername:this.localUsername,remoteUsername:this.remoteUsername,localPassword:this.localPassword,remotePassword:this.remotePassword,generation:this.generation}),this.iceLite){if(s.attributesKeys.includes("USE-CANDIDATE")&&!this.iceControlling)p.remoteNominated=!0,p.nominated=!0,p.updateState(3),this.checkComplete(p);return}if([1,4].includes(p.state))p.handle=this.checkStart(p);if(s.attributesKeys.includes("USE-CANDIDATE")&&!this.iceControlling){if(p.remoteNominated=!0,p.state===3)p.nominated=!0,this.checkComplete(p)}}tryPair(s,n){if(s.localCandidate?.canPairWith(n)&&!(s.localCandidate.transport.toLowerCase()==="tcp"&&s.localCandidate.tcptype==="passive"&&n.type!=="prflx")&&!this.findPair(s,n)){let a=new dr(s,n,this.iceControlling);if(this.options.filterCandidatePair&&!this.options.filterCandidatePair(a))return;a.updateState(1),this.addPair(a)}}pairLocalProtocol(s){if(this.nominated||this.checkListDone||this.state==="closed")return;for(let n of this.remoteCandidates)this.tryPair(s,n)}pairRemoteCandidate=(s)=>{for(let n of this.protocols)this.tryPair(n,s)};buildRequest({nominate:s,remoteUsername:n,localUsername:a,iceControlling:o,localCandidate:c}){let d=cy({remoteUsername:n,localUsername:a}),h=new De(1,0);if(h.setAttribute("USERNAME",d).setAttribute("PRIORITY",$t("prflx",{transport:c?.transport,tcptype:c?.tcptype})),o){if(h.setAttribute("ICE-CONTROLLING",this.tieBreaker),s)h.setAttribute("USE-CANDIDATE",null)}else h.setAttribute("ICE-CONTROLLED",this.tieBreaker);return h}pruneTcpConnections(s){for(let n of this.protocols){if(n.localCandidate?.transport.toLowerCase()!=="tcp")continue;if("pruneForSelection"in n&&typeof n.pruneForSelection==="function")n.pruneForSelection(n===s.protocol?s.remoteAddr:void 0)}}respondError(s,n,a,o,c=this.localPassword){let d=new De(s.messageMethod,272,s.transactionId);d.setAttribute("ERROR-CODE",o).addMessageIntegrity(Buffer.from(c,"utf8")).addFingerprint(),a.sendStun(d,n).catch((h)=>{D("sendStun error",h)})}},cy=({remoteUsername:s,localUsername:n})=>`${s}:${n}`,Li=(s)=>{let[n,a]=s.split(":");return{remoteUsername:n,localUsername:a}},Wo=(s)=>Gt(s)?"udp4":"udp6",dy=(s)=>s.split("%")[0],hn=4,ks=12,ln=4,hy=12,un=ln+hy,He=class s{constructor(n=0,a=Buffer.from("")){this.flags=n,this._body=a}flags;_body;get body(){return this._body}set body(n){this._body=n}static type=-1;get type(){return s.type}get bytes(){if(!this.body)throw Error();let n=Buffer.alloc(ln);return n.writeUInt8(this.type,0),n.writeUInt8(this.flags,1),n.writeUInt16BE(this.body.length+ln,2),Buffer.concat([n,this.body,...[...Array(Qs(this.body.length))].map(()=>Buffer.from("\x00"))])}},Kn=class extends He{constructor(s=0,n){super(s,n);if(this.flags=s,n)this.initiateTag=n.readUInt32BE(0),this.advertisedRwnd=n.readUInt32BE(4),this.outboundStreams=n.readUInt16BE(8),this.inboundStreams=n.readUInt16BE(10),this.initialTsn=n.readUInt32BE(12),this.params=Ph(n.slice(16));else this.initiateTag=0,this.advertisedRwnd=0,this.outboundStreams=0,this.inboundStreams=0,this.initialTsn=0,this.params=[]}flags;initiateTag;advertisedRwnd;outboundStreams;inboundStreams;initialTsn;params;get body(){let s=Buffer.alloc(16);return s.writeUInt32BE(this.initiateTag,0),s.writeUInt32BE(this.advertisedRwnd,4),s.writeUInt16BE(this.outboundStreams,8),s.writeUInt16BE(this.inboundStreams,10),s.writeUInt32BE(this.initialTsn,12),Buffer.concat([s,kh(this.params)])}},Er=class s extends Kn{static type=1;get type(){return s.type}},pn=class s extends Kn{static type=2;get type(){return s.type}},ly=class s extends Kn{static type=130;get type(){return s.type}},Ir=class s extends He{constructor(n=0,a){super(n,a);if(this.flags=n,a){this.cumulativeTsn=a.readUInt32BE(0);let o=4;while(o<a.length)this.streams.push([a.readUInt16BE(o),a.readUInt16BE(o+2)]),o+=4}else this.cumulativeTsn=0}flags;static type=192;streams=[];cumulativeTsn;get type(){return s.type}set body(n){}get body(){let n=Buffer.alloc(4);return n.writeUInt32BE(this.cumulativeTsn,0),Buffer.concat([n,...this.streams.map(([a,o])=>{let c=Buffer.alloc(4);return c.writeUInt16BE(a,0),c.writeUInt16BE(o,2),c})])}},kr=class s extends He{constructor(n=0,a){super(n,a);if(this.flags=n,a)this.tsn=a.readUInt32BE(0),this.streamId=a.readUInt16BE(4),this.streamSeqNum=a.readUInt16BE(6),this.protocol=a.readUInt32BE(8),this.userData=a.slice(12)}flags;static type=0;get type(){return s.type}tsn=0;streamId=0;streamSeqNum=0;protocol=0;userData=Buffer.from("");abandoned=!1;acked=!1;misses=0;retransmit=!1;sentCount=0;bookSize=0;expiry;maxRetransmits;sentTime;get bytes(){let n=un+this.userData.length,a=Buffer.alloc(un);a.writeUInt8(this.type,0),a.writeUInt8(this.flags,1),a.writeUInt16BE(n,2),a.writeUInt32BE(this.tsn,4),a.writeUInt16BE(this.streamId,8),a.writeUInt16BE(this.streamSeqNum,10),a.writeUInt32BE(this.protocol,12);let o=Buffer.concat([a,this.userData]);if(n%4)o=Buffer.concat([o,...[...Array(Qs(n))].map(()=>Buffer.from("\x00"))]);return o}},fn=class s extends He{static type=10;get type(){return s.type}},mn=class s extends He{static type=11;get type(){return s.type}},Ys=class extends He{constructor(s=0,n=void 0){super(s,n);if(this.flags=s,n)this.params=Ph(n)}flags;params=[];get body(){return kh(this.params)}},gn=class s extends Ys{static type=6;get type(){return s.type}},Pr=class s extends Ys{static type=9;static CODE={InvalidStreamIdentifier:1,MissingMandatoryParameter:2,StaleCookieError:3,OutofResource:4,UnresolvableAddress:5,UnrecognizedChunkType:6,InvalidMandatoryParameter:7,UnrecognizedParameters:8,NoUserData:9,CookieReceivedWhileShuttingDown:10,RestartofanAssociationwithNewAddresses:11,UserInitiatedAbort:12,ProtocolViolation:13};get type(){return s.type}get descriptions(){return this.params.map(([n,a])=>({name:(Object.entries(s.CODE).find(([,c])=>c===n)||[])[0],body:a}))}},yn=class s extends Ys{static type=4;get type(){return s.type}},Rh=class s extends Ys{static type=5;get type(){return s.type}},Sn=class s extends Ys{static type=130;get type(){return s.type}},vn=class s extends He{constructor(n=0,a){super(n,a);if(this.flags=n,a){this.cumulativeTsn=a.readUInt32BE(0),this.advertisedRwnd=a.readUInt32BE(4);let o=a.readUInt16BE(8),c=a.readUInt16BE(10),d=12;[...Array(o)].forEach(()=>{this.gaps.push([a.readUInt16BE(d),a.readUInt16BE(d+2)]),d+=4}),[...Array(c)].forEach(()=>{this.duplicates.push(a.readUInt32BE(d)),d+=4})}}flags;static type=3;get type(){return s.type}gaps=[];duplicates=[];cumulativeTsn=0;advertisedRwnd=0;get bytes(){let n=16+4*(this.gaps.length+this.duplicates.length),a=Buffer.alloc(16);a.writeUInt8(this.type,0),a.writeUInt8(this.flags,1),a.writeUInt16BE(n,2),a.writeUInt32BE(this.cumulativeTsn,4),a.writeUInt32BE(this.advertisedRwnd,8),a.writeUInt16BE(this.gaps.length,12),a.writeUInt16BE(this.duplicates.length,14);let o=Buffer.concat([a,...this.gaps.map((c)=>{let d=Buffer.alloc(4);return d.writeUInt16BE(c[0],0),d.writeUInt16BE(c[1],2),d})]);return o=Buffer.concat([o,...this.duplicates.map((c)=>{let d=Buffer.alloc(4);return d.writeUInt32BE(c,0),d})]),o}},Ch=class s extends He{constructor(n=0,a){super(n,a);if(this.flags=n,a)this.cumulativeTsn=a.readUInt32BE(0)}flags;static type=7;get type(){return s.type}cumulativeTsn=0;get body(){let n=Buffer.alloc(4);return n.writeUInt32BE(this.cumulativeTsn,0),n}},Eh=class s extends He{static type=8;get type(){return s.type}},Ih=class s extends He{static type=14;get type(){return s.type}},uy=[kr,Er,pn,vn,yn,Rh,gn,Ch,Eh,Pr,fn,mn,Ih,Sn,Ir],py=uy.reduce((s,n)=>(s[n.type]=n,s),{});function Qs(s){let n=s%hn;return n?hn-n:0}function kh(s){let n=Buffer.from(""),a=Buffer.from("");return s.forEach(([o,c])=>{let d=c.length+4,h=Buffer.alloc(4);h.writeUInt16BE(o,0),h.writeUInt16BE(d,2),n=Buffer.concat([n,a,h,c]),a=Buffer.concat([...Array(Qs(d))].map(()=>Buffer.from("\x00")))}),n}function Ph(s){let n=[],a=0;while(a<=s.length-4){let o=s.readUInt16BE(a),c=s.readUInt16BE(a+2);n.push([o,s.slice(a+4,a+c)]),a+=c+Qs(c)}return n}function fy(s){if(s.length<ks)throw Error("SCTP packet length is less than 12 bytes");let n=s.readUInt16BE(0),a=s.readUInt16BE(2),o=s.readUInt32BE(4),c=s.readUInt32LE(8),d=od(Buffer.concat([s.slice(0,8),Buffer.from("\x00\x00\x00\x00"),s.slice(ks)]));if(c!==d)throw Error("SCTP packet has invalid checksum");let h=[],u=ks;while(u+4<=s.length){let p=s.readUInt8(u),f=s.readUInt8(u+1),m=s.readUInt16BE(u+2),y=s.slice(u+4,u+m),S=py[p.toString()];if(S)h.push(new S(f,y));else throw Error("unknown");u+=m+Qs(m)}return[n,a,o,h]}function my(s,n,a,o){let c=Buffer.alloc(ks-4);c.writeUInt16BE(s,0),c.writeUInt16BE(n,2),c.writeUInt32BE(a,4);let d=o.bytes,h=od(Buffer.concat([c,Buffer.from("\x00\x00\x00\x00"),d])),u=Buffer.alloc(4);return u.writeUInt32LE(h,0),Buffer.concat([c,u,d])}function yy(s){return s.map((n,a)=>[a,n])}function Sy(s){return s.reduce((n,a)=>(n[a]=new E,n),{})}var wn=class s{constructor(n,a,o,c){this.requestSequence=n,this.responseSequence=a,this.lastTsn=o,this.streams=c}requestSequence;responseSequence;lastTsn;streams;static type=13;get type(){return s.type}get bytes(){let n=Buffer.allocUnsafe(12);return n.writeUInt32BE(this.requestSequence,0),n.writeUInt32BE(this.responseSequence,4),n.writeUInt32BE(this.lastTsn,8),Buffer.concat([n,...this.streams.map((a)=>{let o=Buffer.allocUnsafe(2);return o.writeUInt16BE(a,0),o})])}static parse(n){let a=n.readUInt32BE(0),o=n.readUInt32BE(4),c=n.readUInt32BE(8),d=[];for(let h=12;h<n.length;h+=2)d.push(n.readUInt16BE(h));return new s(a,o,c,d)}},Ah=class s{constructor(n,a){this.requestSequence=n,this.newStreams=a}requestSequence;newStreams;static type=17;get type(){return s.type}get bytes(){let n=Buffer.allocUnsafe(8);return n.writeUInt32BE(this.requestSequence,0),n.writeUInt16BE(this.newStreams,4),n.writeUInt16BE(0,6),n}static parse(n){let a=n.readUInt32BE(0),o=n.readUInt16BE(4);return new s(a,o)}},fr={ReconfigResultSuccessPerformed:1,BadSequenceNumber:5},Ar=class s{constructor(n,a){this.responseSequence=n,this.result=a}responseSequence;result;static type=16;get type(){return s.type}get bytes(){let n=Buffer.allocUnsafe(8);return n.writeUInt32BE(this.responseSequence,0),n.writeUInt32BE(this.result,4),n}static parse(n){let a=n.readUInt32BE(0),o=n.readUInt32BE(4);return new s(a,o)}},$o={13:wn,16:Ar,17:Ah},U=_("werift/sctp/sctp"),vy=24,wy=60,Go=65535,Yr=1191;function xh(s,n=un){let a=ks+n;if(s<=a)return 0;let o=s-a;return o-o%hn}function _h(s){if(!Number.isSafeInteger(s)||s<=0)throw Error("SCTP MTU must be a positive integer");if(xh(s)===0)throw Error("SCTP MTU is too small for a DATA chunk")}var Ts=1,Lh=2,Tn=4,jo=10,Ty=8,Vo=0.125,Yo=0.25,Qo=3,by=1,Ry=60,Qr=4294967296,Cy=200,Ey=30,Xo=135,Jo=7,Zo=32776,ec=49152,Iy=["new","closed","connected","connecting"],ky=class s{constructor(n,a=5000,o={}){this.transport=n,this.port=a,this.mtu=o.mtu??Yr,_h(this.mtu),this.maxPayloadSize=xh(this.mtu),this.cwnd=3*this.maxPayloadSize,this.localPort=this.port,this.transport.onData=(c)=>{this.handleData(c)}}transport;port;flush=new E;stateChanged=Sy(Iy);onReconfigStreams=new E;onReceive=new E;onSackReceived=async()=>{};associationState=1;started=!1;state="new";isServer=!0;isStopping=!1;isClosed=!1;hmacKey=gy(16);localPartialReliability=!0;localPort;localVerificationTag=ka();remoteExtensions=[];remotePartialReliability=!0;remotePort;remoteVerificationTag=0;advertisedRwnd=1048576;peerAdvertisedRwnd=this.advertisedRwnd;get peerRwnd(){return Math.max(0,this.peerAdvertisedRwnd-this.flightSize)}inboundStreams={};_inboundStreamsCount=0;_inboundStreamsMax=Go;lastReceivedTsn;sackDuplicates=[];sackMisOrdered=new Set;sackNeeded=!1;sackPacketCount=0;sackHasNewDataInPacket=!1;sackImmediate=!1;sackTimeout;cwnd;mtu;maxPayloadSize;fastRecoveryExit;fastRecoveryTransmit=!1;forwardTsnChunk;flightSize=0;outboundQueue=new Vt;sendWaiters=new Vt;outboundStreamSeq={};_outboundStreamsCount=Go;localTsn=Number(ka());lastSackedTsn=mt(this.localTsn);advancedPeerAckTsn=mt(this.localTsn);partialBytesAcked=0;sentQueue=new Vt;transmitting=!1;transmitRequested=!1;reconfigRequestSeq=this.localTsn;reconfigResponseSeq=0;reconfigRequest;reconfigQueue=[];srtt;rttvar;rto=Qo;timer1Handle;timer1Chunk;timer1Failures=0;timer2Handle;timer2Chunk;timer2Failures=0;timer3Handle;timerReconfigHandle;timerReconfigFailures=0;timerHeartbeatHandle;heartbeatInterval=Ey;ssthresh;get isStopped(){return this.isStopping||this.isClosed}get maxChannels(){if(this._inboundStreamsCount>0)return Math.min(this._inboundStreamsCount,this._outboundStreamsCount);return}static client(n,a=5000,o={}){let c=new s(n,a,o);return c.isServer=!1,c}static server(n,a=5000,o={}){let c=new s(n,a,o);return c.isServer=!0,c}async handleData(n){if(this.isStopped)return;let a,[,,o,c]=fy(n);if(c.filter((h)=>h.type===Er.type).length>0){if(c.length!=1)throw Error();a=0}else a=this.localVerificationTag;if(o!==a)return;this.sackHasNewDataInPacket=!1;for(let h of c)await this.receiveChunk(h);if(this.sackNeeded){if(this.sackHasNewDataInPacket)this.sackPacketCount++;if(this.sackPacketCount>=2)this.sackImmediate=!0;await this.scheduleSack()}}async scheduleSack(){if(this.isStopped)return;if(!this.sackNeeded)return;if(this.sackImmediate){if(this.sackTimeout)clearTimeout(this.sackTimeout),this.sackTimeout=void 0;await this.sendSack();return}if(this.sackTimeout)return;this.sackTimeout=setTimeout(()=>{this.sackTimeout=void 0,this.sendSack().catch((n)=>{U("send delayed sack failed",n.message)})},Cy)}async sendSack(){if(this.isStopped)return;if(!this.sackNeeded)return;let n=[],a;[...this.sackMisOrdered].sort().forEach((c)=>{let d=(c-this.lastReceivedTsn)%Qr;if(c===a)n[n.length-1][1]=d;else n.push([d,d]);a=jt(c)});let o=new vn(0,void 0);o.cumulativeTsn=this.lastReceivedTsn,o.advertisedRwnd=Math.max(0,this.advertisedRwnd),o.duplicates=[...this.sackDuplicates],o.gaps=n,await this.sendChunk(o).catch((c)=>{U("send sack failed",c.message)}),this.sackDuplicates=[],this.sackNeeded=!1,this.sackPacketCount=0,this.sackImmediate=!1}async receiveChunk(n){switch(n.type){case kr.type:this.receiveDataChunk(n);break;case Er.type:{if(!this.isServer)return;let a=n;U("receive init",a),this.lastReceivedTsn=mt(a.initialTsn),this.reconfigResponseSeq=mt(a.initialTsn),this.remoteVerificationTag=a.initiateTag,this.ssthresh=a.advertisedRwnd,this.peerAdvertisedRwnd=a.advertisedRwnd,this.getExtensions(a.params),this._inboundStreamsCount=Math.min(a.outboundStreams,this._inboundStreamsMax),this._outboundStreamsCount=Math.min(this._outboundStreamsCount,a.inboundStreams);let o=new pn;o.initiateTag=this.localVerificationTag,o.advertisedRwnd=this.advertisedRwnd,o.outboundStreams=this._outboundStreamsCount,o.inboundStreams=this._inboundStreamsCount,o.initialTsn=this.localTsn,this.setExtensions(o.params);let c=Math.floor(Date.now()/1000),d=Buffer.allocUnsafe(4);d.writeUInt32BE(c,0);let h=d;h=Buffer.concat([h,Ko("sha1",this.hmacKey).update(h).digest()]),o.params.push([Jo,h]),U("send initAck",o),await this.sendChunk(o).catch((u)=>{U("send initAck failed",u.message)})}break;case pn.type:{if(this.associationState!=2)return;let a=n;this.timer1Cancel(),this.lastReceivedTsn=mt(a.initialTsn),this.reconfigResponseSeq=mt(a.initialTsn),this.remoteVerificationTag=a.initiateTag,this.ssthresh=a.advertisedRwnd,this.peerAdvertisedRwnd=a.advertisedRwnd,this.getExtensions(a.params),this._inboundStreamsCount=Math.min(a.outboundStreams,this._inboundStreamsMax),this._outboundStreamsCount=Math.min(this._outboundStreamsCount,a.inboundStreams);let o=new fn;for(let[c,d]of a.params)if(c===Jo){o.body=d;break}await this.sendChunk(o).catch((c)=>{U("send echo failed",c.message)}),this.timer1Start(o),this.setState(3)}break;case vn.type:await this.receiveSackChunk(n);break;case yn.type:{let a=new Rh;a.params=n.params,await this.sendChunk(a).catch((o)=>{U("send heartbeat ack failed",o.message)})}break;case gn.type:this.setState(1);break;case Ch.type:{this.timer2Cancel(),this.setState(7);let a=new Eh;await this.sendChunk(a).catch((o)=>{U("send shutdown ack failed",o.message)}),this.t2Start(a),this.setState(6)}break;case Pr.type:U("ErrorChunk",n.descriptions);break;case fn.type:{if(!this.isServer)return;let o=n.body,c=Ko("sha1",this.hmacKey).update(o.slice(0,4)).digest();if(o?.length!=vy||!o.slice(4).equals(c)){U("x State cookie is invalid");return}let d=Math.floor(Date.now()/1000),h=o.readUInt32BE(0);if(h<d-wy||h>d){let p=new Pr(0,void 0);p.params.push([Pr.CODE.StaleCookieError,Buffer.concat([...Array(8)].map(()=>Buffer.from("\x00")))]),await this.sendChunk(p).catch((f)=>{U("send errorChunk failed",f.message)});return}let u=new mn;await this.sendChunk(u).catch((p)=>{U("send cookieAck failed",p.message)}),this.setState(4)}break;case mn.type:{if(this.associationState!=3)return;this.timer1Cancel(),this.setState(4)}break;case Ih.type:{if(this.associationState!=8)return;this.timer2Cancel(),this.setState(1)}break;case Sn.type:{if(this.associationState!=4)return;let a=n;for(let[o,c]of a.params){let d=$o[o];if(d)await this.receiveReconfigParam(d.parse(c))}}break;case Ir.type:this.receiveForwardTsnChunk(n);break}}getExtensions(n){for(let[a,o]of n)if(a===ec)this.remotePartialReliability=!0;else if(a===Zo)this.remoteExtensions=[...o]}async receiveReconfigParam(n){switch(U("receiveReconfigParam",$o[n.type]),n.type){case wn.type:{let a=n,o=new Ar(a.requestSequence,fr.ReconfigResultSuccessPerformed);this.reconfigResponseSeq=a.requestSequence,await this.sendReconfigParam(o),await Promise.all(a.streams.map(async(c)=>{if(delete this.inboundStreams[c],this.outboundStreamSeq[c]){if(!this.reconfigQueue.includes(c))this.reconfigQueue.push(c)}})),await this.transmitReconfigRequest(),this.onReconfigStreams.execute(a.streams)}break;case Ar.type:{let a=n;if(a.result!==fr.ReconfigResultSuccessPerformed)U("OutgoingSSNResetRequestParam failed",Object.keys(fr).find((o)=>fr[o]===a.result));else if(a.responseSequence===this.reconfigRequest?.requestSequence){let o=this.reconfigRequest.streams.map((c)=>(delete this.outboundStreamSeq[c],c));if(this.onReconfigStreams.execute(o),this.reconfigRequest=void 0,this.timerReconfigCancel(),this.rto=Qo,this.timerReconfigFailures=0,this.reconfigQueue.length>0)await this.transmitReconfigRequest()}}break;case Ah.type:{let a=n;this._inboundStreamsCount+=a.newStreams;let o=new Ar(a.requestSequence,1);this.reconfigResponseSeq=a.requestSequence,await this.sendReconfigParam(o)}break}}receiveDataChunk(n){if(this.sackNeeded=!0,this.markReceived(n.tsn)){this.sackImmediate=!0;return}if(this.sackHasNewDataInPacket=!0,this.sackImmediate=!0,(n.flags&Ts)===0)this.sackImmediate=!0;if(this.sackMisOrdered.size>0)this.sackImmediate=!0;let a=this.getInboundStream(n.streamId);a.addChunk(n),this.advertisedRwnd-=n.userData.length;for(let o of a.popMessages())this.advertisedRwnd+=o[2].length,this.receive(...o)}async receiveSackChunk(n){if(Ze(this.lastSackedTsn,n.cumulativeTsn))return;let a=Date.now()/1000;this.lastSackedTsn=n.cumulativeTsn;let o=this.flightSize>=this.cwnd,c=0,d=0;while(this.sentQueue.length>0&&Ss(this.lastSackedTsn,this.sentQueue.peek().tsn)){let u=this.sentQueue.shift();if(c++,!u?.acked)d+=u.bookSize,this.flightSizeDecrease(u);if(c===1&&u.sentCount===1)this.updateRto(a-u.sentTime)}let h=!1;if(n.gaps.length>0){let u=new Set,p;n.gaps.forEach((m)=>{for(let y=m[0];y<m[1]+1;y++)p=(n.cumulativeTsn+y)%Qr,u.add(p)});let f=n.cumulativeTsn;for(let m of this.sentQueue){if(Ze(m.tsn,p))break;if(u.has(m.tsn)&&!m.acked)d+=m.bookSize,m.acked=!0,this.flightSizeDecrease(m),f=m.tsn}for(let m of this.sentQueue){if(Ze(m.tsn,f))break;if(!u.has(m.tsn)){if(m.misses++,m.misses===3){if(m.misses=0,!this.maybeAbandon(m))m.retransmit=!0;m.acked=!1,this.flightSizeDecrease(m),h=!0}}}}if(this.fastRecoveryExit===void 0){if(c&&o){if(this.cwnd<=this.ssthresh)this.cwnd+=Math.min(d,this.maxPayloadSize);else if(this.partialBytesAcked+=d,this.partialBytesAcked>=this.cwnd)this.partialBytesAcked-=this.cwnd,this.cwnd+=this.maxPayloadSize}if(h)this.ssthresh=Math.max(Math.floor(this.cwnd/2),4*this.maxPayloadSize),this.cwnd=this.ssthresh,this.partialBytesAcked=0,this.fastRecoveryExit=this.sentQueue.last().tsn,this.fastRecoveryTransmit=!0}else if(Ss(n.cumulativeTsn,this.fastRecoveryExit))this.fastRecoveryExit=void 0;if(this.sentQueue.length===0)this.timer3Cancel();else if(c>0)this.timer3Restart();this.peerAdvertisedRwnd=n.advertisedRwnd,this.updateAdvancedPeerAckPoint(),await this.onSackReceived(),await this.transmit()}receiveForwardTsnChunk(n){if(this.sackNeeded=!0,this.sackImmediate=!0,Ss(this.lastReceivedTsn,n.cumulativeTsn))return;let a=(o)=>Ze(o,this.lastReceivedTsn);this.lastReceivedTsn=n.cumulativeTsn,this.sackMisOrdered=new Set([...this.sackMisOrdered].filter(a));for(let o of[...this.sackMisOrdered].sort())if(o===jt(this.lastReceivedTsn))this.lastReceivedTsn=o;else break;this.sackDuplicates=this.sackDuplicates.filter(a),this.sackMisOrdered=new Set([...this.sackMisOrdered].filter(a));for(let[o,c]of n.streams){let d=this.getInboundStream(o);d.streamSequenceNumber=ae(c,1);for(let h of d.popMessages())this.advertisedRwnd+=h[2].length,this.receive(...h)}Object.values(this.inboundStreams).forEach((o)=>{this.advertisedRwnd+=o.pruneChunks(this.lastReceivedTsn)})}updateRto(n){if(!this.srtt)this.rttvar=n/2,this.srtt=n;else this.rttvar=(1-Yo)*this.rttvar+Yo*Math.abs(this.srtt-n),this.srtt=(1-Vo)*this.srtt+Vo*n;this.rto=Math.max(by,Math.min(this.srtt+4*this.rttvar,Ry))}receive(n,a,o){this.onReceive.execute(n,a,o)}getInboundStream(n){if(!this.inboundStreams[n])this.inboundStreams[n]=new Py;return this.inboundStreams[n]}markReceived(n){if(Ss(this.lastReceivedTsn,n)||this.sackMisOrdered.has(n))return this.sackDuplicates.push(n),!0;this.sackMisOrdered.add(n);for(let o of[...this.sackMisOrdered].sort())if(o===jt(this.lastReceivedTsn))this.lastReceivedTsn=o;else break;let a=(o)=>Ze(o,this.lastReceivedTsn);return this.sackDuplicates=this.sackDuplicates.filter(a),this.sackMisOrdered=new Set([...this.sackMisOrdered].filter(a)),!1}send=async(n,a,o,{expiry:c,maxRetransmits:d,ordered:h}={expiry:void 0,maxRetransmits:void 0,ordered:!0})=>{let u=h?this.outboundStreamSeq[n]||0:0,p=Math.ceil(o.length/this.maxPayloadSize),f=0,m=[];for(let v=0;v<p;v++){let g=new kr(0,void 0);if(g.flags=0,!h)g.flags=Tn;if(v===0)g.flags|=Lh;if(v===p-1)g.flags|=Ts;g.tsn=this.localTsn,g.streamId=n,g.streamSeqNum=u,g.protocol=a,g.userData=o.slice(f,f+this.maxPayloadSize),g.bookSize=g.userData.length,g.expiry=c,g.maxRetransmits=d,f+=this.maxPayloadSize,this.localTsn=jt(this.localTsn),m.push(g)}for(let v of m)this.outboundQueue.push(v);if(h)this.outboundStreamSeq[n]=ae(u,1);let y=m[m.length-1],S=y&&!this.isStopped?new Promise((v)=>{this.sendWaiters.push({chunk:y,resolve:v})}):void 0;await this.transmit(),await S};resolveSendWaiters(n){if(this.sendWaiters.peek()?.chunk===n)this.sendWaiters.shift().resolve()}releaseSendWaiters(){let n=this.sendWaiters;this.sendWaiters=new Vt;for(let a of n)a.resolve()}async transmit(){if(this.isStopped)return;if(this.transmitting){this.transmitRequested=!0;return}this.transmitting=!0;try{do this.transmitRequested=!1,await this.transmitOnce();while(this.transmitRequested)}finally{this.transmitting=!1}}async transmitOnce(){if(this.isStopped)return;if(this.forwardTsnChunk){if(await this.sendChunk(this.forwardTsnChunk).catch((c)=>{U("send forwardTsn failed",c.message)}),this.forwardTsnChunk=void 0,!this.timer3Handle)this.timer3Start()}let n=this.fastRecoveryExit!=null?2*this.maxPayloadSize:4*this.maxPayloadSize,a=Math.min(this.flightSize+n,this.cwnd),o=!0;for(let c of this.sentQueue){if(c.retransmit){if(this.fastRecoveryTransmit)this.fastRecoveryTransmit=!1;else if(this.flightSize>=a)break;if(this.flightSizeIncrease(c),c.misses=0,c.retransmit=!1,c.sentCount++,await this.sendChunk(c).catch((d)=>{U("send data failed",d.message)}),o)this.timer3Restart()}o=!1}while(this.outboundQueue.length>0&&this.flightSize<a&&this.peerRwnd>0){let c=this.outboundQueue.peek();if(c.bookSize>this.peerRwnd&&this.flightSize>0)break;if(this.outboundQueue.shift(),this.sentQueue.push(c),this.resolveSendWaiters(c),this.flightSizeIncrease(c),c.sentCount++,c.sentTime=Date.now()/1000,await this.sendChunk(c).catch((d)=>{U("send data outboundQueue failed",d.message)}),!this.timer3Handle)this.timer3Start()}this.flush.execute()}async transmitReconfigRequest(){if(this.reconfigQueue.length>0&&this.associationState===4&&!this.reconfigRequest){let n=[...new Set(this.reconfigQueue)],a=n.slice(0,Xo);this.reconfigQueue=n.slice(Xo);let o=new wn(this.reconfigRequestSeq,this.reconfigResponseSeq,mt(this.localTsn),a);this.reconfigRequestSeq=jt(this.reconfigRequestSeq),this.reconfigRequest=o,await this.sendReconfigParam(o),this.timerReconfigHandleStart()}}async sendReconfigParam(n){U("sendReconfigParam",n);let a=new Sn;a.params.push([n.type,n.bytes]),await this.sendChunk(a).catch((o)=>{U("send reconfig failed",o.message)})}async sendResetRequest(n){U("sendResetRequest",n);let a=new kr(0,void 0);if(a.streamId=n,this.outboundQueue.push(a),!this.timer3Handle)await this.transmit()}flightSizeIncrease(n){this.flightSize+=n.bookSize}flightSizeDecrease(n){this.flightSize=Math.max(0,this.flightSize-n.bookSize)}timer1Start(n){if(this.timer1Handle)throw Error();this.timer1Chunk=n,this.timer1Failures=0,this.timer1Handle=setTimeout(this.timer1Expired,this.rto*1000)}timer1Expired=()=>{if(this.isStopped)return;if(this.timer1Failures++,this.timer1Handle=void 0,this.timer1Failures>Ty)this.setState(1);else{if(setImmediate(()=>{if(this.isStopped)return;this.sendChunk(this.timer1Chunk).catch((n)=>{U("send timer1 chunk failed",n.message)})}),this.isStopped)return;this.timer1Handle=setTimeout(this.timer1Expired,this.rto*1000)}};timer1Cancel(){if(this.timer1Handle)clearTimeout(this.timer1Handle),this.timer1Handle=void 0,this.timer1Chunk=void 0}t2Start(n){if(this.timer2Handle)throw Error();this.timer2Chunk=n,this.timer2Failures=0,this.timer2Handle=setTimeout(this.timer2Expired,this.rto*1000)}timer2Expired=()=>{if(this.isStopped)return;if(this.timer2Failures++,this.timer2Handle=void 0,this.timer2Failures>jo)this.setState(1);else{if(setImmediate(()=>{if(this.isStopped)return;this.sendChunk(this.timer2Chunk).catch((n)=>{U("send timer2Chunk failed",n.message)})}),this.isStopped)return;this.timer2Handle=setTimeout(this.timer2Expired,this.rto*1000)}};timer2Cancel(){if(this.timer2Handle)clearTimeout(this.timer2Handle),this.timer2Handle=void 0,this.timer2Chunk=void 0}timer3Start(){if(this.isStopped)return;if(this.timer3Handle)throw Error();this.timer3Handle=setTimeout(this.timer3Expired,this.rto*1000)}timer3Restart(){if(this.isStopped)return;this.timer3Cancel(),this.timer3Handle=setTimeout(this.timer3Expired,this.rto*1000)}timer3Expired=()=>{if(this.isStopped)return;this.timer3Handle=void 0,this.sentQueue.forEach((n)=>{if(!this.maybeAbandon(n))n.retransmit=!0}),this.updateAdvancedPeerAckPoint(),this.fastRecoveryExit=void 0,this.flightSize=0,this.partialBytesAcked=0,this.ssthresh=Math.max(Math.floor(this.cwnd/2),4*this.maxPayloadSize),this.cwnd=this.maxPayloadSize,this.transmit()};timer3Cancel(){if(this.timer3Handle)clearTimeout(this.timer3Handle),this.timer3Handle=void 0}timerReconfigHandleStart(){if(this.isStopped)return;if(this.timerReconfigHandle)return;U("timerReconfigHandleStart",{rto:this.rto}),this.timerReconfigFailures=0,this.timerReconfigHandle=setTimeout(this.timerReconfigHandleExpired,this.rto*1000)}timerReconfigHandleExpired=async()=>{if(this.isStopped)return;if(this.timerReconfigFailures++,this.rto=Math.ceil(this.rto*1.5),this.timerReconfigFailures>jo)U("timerReconfigFailures",this.timerReconfigFailures),this.setState(1),this.timerReconfigHandle=void 0;else if(this.reconfigRequest){if(U("timerReconfigHandleExpired",this.timerReconfigFailures,this.rto),await this.sendReconfigParam(this.reconfigRequest),this.isStopped)return;this.timerReconfigHandle=setTimeout(this.timerReconfigHandleExpired,this.rto*1000)}};timerReconfigCancel(){if(this.timerReconfigHandle)U("timerReconfigCancel"),clearTimeout(this.timerReconfigHandle),this.timerReconfigHandle=void 0,this.timerReconfigFailures=0}heartbeatStart(){if(this.timerHeartbeatHandle||this.associationState!==4)return;this.timerHeartbeatHandle=setTimeout(this.timerHeartbeatExpired,(this.rto+this.heartbeatInterval)*1000)}heartbeatRestart(){this.heartbeatCancel(),this.heartbeatStart()}heartbeatCancel(){if(this.timerHeartbeatHandle)clearTimeout(this.timerHeartbeatHandle),this.timerHeartbeatHandle=void 0}timerHeartbeatExpired=async()=>{if(this.timerHeartbeatHandle=void 0,this.associationState!==4)return;if(this.flightSize===0&&this.outboundQueue.length===0){let n=new yn,a=Buffer.allocUnsafe(4);a.writeUInt32BE(Math.floor(Date.now()/1000),0),n.params.push([1,a]),await this.sendChunk(n).catch((o)=>{U("send heartbeat failed",o.message)})}this.heartbeatStart()};setHeartbeatInterval(n){if(n<=0)throw Error("heartbeat interval must be > 0");this.heartbeatInterval=n,this.heartbeatRestart()}updateAdvancedPeerAckPoint(){if(Ze(this.lastSackedTsn,this.advancedPeerAckTsn))this.advancedPeerAckTsn=this.lastSackedTsn;let n=0,a={};while(this.sentQueue.length>0&&this.sentQueue.peek().abandoned){let o=this.sentQueue.shift();if(this.advancedPeerAckTsn=o.tsn,n++,!(o.flags&Tn))a[o.streamId]=o.streamSeqNum}if(n)this.forwardTsnChunk=new Ir(0,void 0),this.forwardTsnChunk.cumulativeTsn=this.advancedPeerAckTsn,this.forwardTsnChunk.streams=Object.entries(a).map(([o,c])=>[Number(o),c])}maybeAbandon(n){if(n.abandoned)return!0;if(!(!!n.maxRetransmits&&n.maxRetransmits<n.sentCount||!!n.expiry&&n.expiry<Date.now()/1000))return!1;let o=this.sentQueue.findIndex((c)=>c.type===n.type);for(let c=o;c>=0;c--){let d=this.sentQueue.at(c);if(d.abandoned=!0,d.retransmit=!1,d.flags&Ts)break}for(let c=o;c<this.sentQueue.length;c++){let d=this.sentQueue.at(c);if(d.abandoned=!0,d.retransmit=!1,d.flags&Ts)break}return!0}static getCapabilities(){return new Ay(65536)}setRemotePort(n){this.remotePort=n}async start(n){if(!this.started){if(this.started=!0,this.setConnectionState("connecting"),n)this.setRemotePort(n);if(!this.isServer)await this.init()}}async init(){let n=new Er;n.initiateTag=this.localVerificationTag,n.advertisedRwnd=this.advertisedRwnd,n.outboundStreams=this._outboundStreamsCount,n.inboundStreams=this._inboundStreamsMax,n.initialTsn=this.localTsn,this.setExtensions(n.params),U("send init",n);try{await this.sendChunk(n),this.timer1Start(n),this.setState(2)}catch(a){U("send init failed",a.message)}}setExtensions(n){let a=[];if(this.localPartialReliability)n.push([ec,Buffer.from("")]),a.push(Ir.type);a.push(ly.type),n.push([Zo,Buffer.from(a)])}async sendChunk(n){if(this.state==="closed")return;if(this.remotePort===void 0)throw Error("invalid remote port");let a=my(this.localPort,this.remotePort,this.remoteVerificationTag,n);await this.transport.send(a)}setState(n){if(n!=this.associationState)this.associationState=n;if(n===4)this.isStopping=!1,this.isClosed=!1,this.setConnectionState("connected"),this.heartbeatStart();else if(n===1){if(this.isClosed=!0,this.timer1Cancel(),this.timer2Cancel(),this.timer3Cancel(),this.timerReconfigCancel(),this.heartbeatCancel(),this.sackTimeout)clearTimeout(this.sackTimeout),this.sackTimeout=void 0;this.setConnectionState("closed"),this.removeAllListeners(),this.releaseSendWaiters()}}setConnectionState(n){this.state=n,U("setConnectionState",n),this.stateChanged[n].execute()}async stop(){if(this.isStopped){this.setState(1);return}if(this.isStopping=!0,this.transport.onData=void 0,this.sackTimeout)clearTimeout(this.sackTimeout),this.sackTimeout=void 0;if(this.associationState!==1)await this.abort();this.setState(1),clearTimeout(this.timer1Handle),clearTimeout(this.timer2Handle),clearTimeout(this.timer3Handle),clearTimeout(this.timerReconfigHandle),clearTimeout(this.timerHeartbeatHandle),clearTimeout(this.sackTimeout)}async abort(){let n=new gn;await this.sendChunk(n).catch((a)=>{U("send abort failed",a.message)})}removeAllListeners(){Object.values(this.stateChanged).forEach((n)=>n.allUnsubscribe())}},Py=class{reassembly=[];streamSequenceNumber=0;constructor(){}addChunk(s){if(this.reassembly.length===0||Ze(s.tsn,this.reassembly[this.reassembly.length-1].tsn)){this.reassembly.push(s);return}for(let[n,a]of yy(this.reassembly)){if(a.tsn===s.tsn)throw Error("duplicate chunk in reassembly");if(Ze(a.tsn,s.tsn)){this.reassembly.splice(n,0,s);break}}}*popMessages(){let s=0,n,a,o;while(s<this.reassembly.length){let c=this.reassembly[s];if(n===void 0){if(o=!(c.flags&Tn),!(c.flags&Lh))if(o)break;else{s++;continue}if(o&&hd(c.streamSeqNum,this.streamSequenceNumber))break;a=c.tsn,n=s}else if(c.tsn!==a)if(o)break;else{n=void 0,s++;continue}if(c.flags&Ts){let d=this.reassembly.slice(n,s+1).map((u)=>u.userData).reduce((u,p)=>(u.push(p),u.push(Buffer.from("")),u),[]);d.pop();let h=Buffer.concat(d);if(this.reassembly=[...this.reassembly.slice(0,n),...this.reassembly.slice(s+1)],o&&c.streamSeqNum===this.streamSequenceNumber)this.streamSequenceNumber=ae(this.streamSequenceNumber,1);s=n,yield[c.streamId,c.protocol,h]}else s++;a=jt(a)}}pruneChunks(s){let n=-1,a=0;for(let[o,c]of this.reassembly.entries())if(Ss(s,c.tsn))n=o,a+=c.userData.length;else break;return this.reassembly=this.reassembly.slice(n+1),a}},Ay=class{constructor(s){this.maxMessageSize=s}maxMessageSize};function mt(s){return(s-1)%Qr}function jt(s){return(s+1)%Qr}function A(s,n=s){return new DOMException(n,s)}function lt(s){return TypeError(s)}var Xs=()=>({type:"nack"}),ct=()=>({type:"nack",parameter:"pli"}),Js=()=>({type:"goog-remb"}),sc=()=>({type:"transport-cc"}),st=class{payloadType;mimeType;clockRate;channels;rtcpFeedback=[];parameters;direction="all";constructor(s){Object.assign(this,s)}get name(){return this.mimeType.split("/")[1]}get contentType(){return this.mimeType.split("/")[0]}get str(){let s=`${this.name}/${this.clockRate}`;if(this.channels===2)s+="/2";return s}},xy=class{id;uri;constructor(s){Object.assign(this,s)}};var _y=class{type;parameter;constructor(s={}){Object.assign(this,s)}},Ly=class{ssrc;constructor(s={}){Object.assign(this,s)}},By=class{ssrc;payloadType;rtx;constructor(s){Object.assign(this,s)}},Bh=class{rid;direction;constructor(s){Object.assign(this,s)}},$n=(s={})=>new st({mimeType:"video/H264",clockRate:90000,rtcpFeedback:[Xs(),ct(),Js()],parameters:"profile-level-id=42e01f;packetization-mode=1;level-asymmetry-allowed=1",...s}),Mh=(s={})=>new st({mimeType:"video/VP8",clockRate:90000,rtcpFeedback:[Xs(),ct(),Js()],...s}),My=(s={})=>new st({mimeType:"video/VP9",clockRate:90000,rtcpFeedback:[Xs(),ct(),Js()],...s}),Dy=(s={})=>new st({mimeType:"video/AV1",clockRate:90000,rtcpFeedback:[Xs(),ct(),Js()],...s}),Uy=(s={})=>new st({mimeType:"video/AV1X",clockRate:90000,rtcpFeedback:[Xs(),ct(),Js()],...s}),Dh=(s={})=>new st({mimeType:"audio/OPUS",clockRate:48000,channels:2,...s}),ui=(s={})=>new st({mimeType:"audio/PCMU",clockRate:8000,channels:1,payloadType:0,...s});function Ny(){return{audio:[Dh(),ui()],video:[Mh()]}}function Oy(s){return new st({mimeType:s.mimeType,clockRate:s.clockRate,...s.channels!=null?{channels:s.channels}:{},...s.payloadType!=null?{payloadType:s.payloadType}:{},rtcpFeedback:s.rtcpFeedback.map((n)=>({...n})),...s.parameters!=null?{parameters:s.parameters}:{},direction:s.direction})}var Uh=[Dy(),Uy(),My(),Mh(),$n(),Dh(),ui()].map((s)=>s.mimeType),jT=Uh.filter((s)=>s.toLowerCase().startsWith("video/")),VT=Uh.filter((s)=>s.toLowerCase().startsWith("audio/")),rc=2,Bi=3,zy=0,qy=1,Wy=2,Ky=128,$y=129,Gy=130,Ht=50,ic=51,nc=53,jy=56,Vy=57,ac="0.0.0.0",oc=9,bn={auto:"actpass",client:"active",server:"passive"},cc=Object.keys(bn).reduce((s,n)=>{let a=bn[n];return s[a]=n,s},{}),Yy=["apt","max-fr","max-fs","maxplaybackrate","minptime","packetization-mode","level-asymmetry-allowed","stereo","useinbandfec"],Nh=["cname","msid","mslabel","label"],dc={SRTP_AES128_CM_HMAC_SHA1_80:oi,SRTP_AEAD_AES_128_GCM:js},Qt=["sendonly","sendrecv"],Qy=["sendrecv","recvonly"],lc=class extends Map{constructor(s){super();if(s)for(let n of s)this.set(n.id,n)}};function q(s,...n){let a=n.filter((o)=>o!==void 0);return`${s}_${a.join("_")}`}function Gn(s,n,a){return q("codec",s,n,a)}function pt(){return performance.timeOrigin+performance.now()}function eS(s){let n=[];for(let[a,o]of Object.entries(s)){if(a==="id")continue;if(a.endsWith("Id")){if(typeof o==="string")n.push(o);continue}if(a.endsWith("Ids")&&Array.isArray(o)){for(let c of o)if(typeof c==="string")n.push(c)}}return n}function Xr(s,n){let a=new Map;for(let d of s)a.set(d.id,d);if(!n)return new lc([...a.values()]);let o=new Set,c=[...new Set(Array.from(n))];while(c.length>0){let d=c.shift();if(!d||o.has(d))continue;let h=a.get(d);if(!h)continue;o.add(d),c.push(...eS(h))}return new lc([...o].map((d)=>a.get(d)).filter((d)=>!!d))}var pc=(s,n)=>`${s}\x00${n}`,Oh=new WeakMap;function Rn(s){return Oh.get(s)??0}function rS(s){Oh.set(s,Rn(s)+1)}var iS=class{constructor(s,n,a,o,c){if(this.kind=s,this.receiver=a,this.sender=o,this._direction=c,n)this.setDtlsTransport(n)}kind;receiver;sender;_direction;id=sS().toString();onTrack=new E;mid=null;mLineIndex;usedForSender=!1;_currentDirection;offerDirection;_codecs=[];set codecs(s){this._codecs=s}get codecs(){return this._codecs}headerExtensions=[];_codecPreferences;onCodecPreferencesChanged=new E;pendingLocalOfferCodecs;codecPreferencesNeedResolution=!1;codecChangeRevision=0;get codecPreferences(){return this._codecPreferences}setCodecPreferences(s){if(!Array.isArray(s))throw lt("codecs must be an array");let n=s.length===0?void 0:s.map(Oy);if(nS(this._codecPreferences,n))return;this._codecPreferences=n,this.codecPreferencesNeedResolution=!0,this.markCodecsForResolution(),this.onCodecPreferencesChanged.execute()}markCodecsForResolution(){this.codecChangeRevision++,this._codecs=[]}options={};stopping=!1;stopped=!1;rejected=!1;pendingRejection=!1;firedReceiving=!1;onStopRequested=new E;onRelease=new E;createdNegotiationState;get dtlsTransport(){return this.receiver.dtlsTransport}get direction(){return this._direction}set direction(s){this.setDirection(s)}setDirection(s){if(this._direction=s,this._currentDirection&&this._currentDirection!=="stopped"&&Qt.includes(this._currentDirection))this.usedForSender=!0}get currentDirection(){return this._currentDirection??null}setCurrentDirection(s){if(this._currentDirection=s,this.sender.setSendSuppressed(!!s&&s!=="stopped"&&!Qt.includes(s)),s&&s!=="stopped"&&Qt.includes(s)&&this.sender.track)this.usedForSender=!0}setDtlsTransport(s){this.receiver.setDtlsTransport(s),this.sender.setDtlsTransport(s)}snapshotNegotiationState(){return{mid:this.mid,mLineIndex:this.mLineIndex,codecs:this.codecs,pendingLocalOfferCodecs:this.pendingLocalOfferCodecs&&[...this.pendingLocalOfferCodecs],codecPreferencesNeedResolution:this.codecPreferencesNeedResolution,codecChangeRevision:this.codecChangeRevision,headerExtensions:this.headerExtensions,offerDirection:this.offerDirection,currentDirection:this.currentDirection,stopping:this.stopping,stopped:this.stopped,rejected:this.rejected,pendingRejection:this.pendingRejection,firedReceiving:this.firedReceiving,applicationStopRevision:Rn(this),dtlsTransport:this.dtlsTransport,sender:this.sender.snapshotSendParams(),receiver:this.receiver.snapshotNegotiationState()}}restoreNegotiationState(s){if(this.mid=s.mid,this.mLineIndex=s.mLineIndex,this.pendingLocalOfferCodecs=s.pendingLocalOfferCodecs&&[...s.pendingLocalOfferCodecs],this.codecChangeRevision===s.codecChangeRevision)this.codecs=s.codecs,this.codecPreferencesNeedResolution=s.codecPreferencesNeedResolution;else this.codecs=[],this.codecPreferencesNeedResolution=!0;this.headerExtensions=s.headerExtensions,this.offerDirection=s.offerDirection,this.setCurrentDirection(s.currentDirection??void 0),this.stopping=s.stopping||Rn(this)!==s.applicationStopRevision,this.stopped=s.stopped,this.rejected=s.rejected,this.pendingRejection=s.pendingRejection,this.firedReceiving=s.firedReceiving,this.setDtlsTransport(s.dtlsTransport),this.sender.restoreSendParams(s.sender),this.receiver.restoreNegotiationState(s.receiver)}get heldByApplication(){return!!this.sender.track}get msid(){return this.msids[0]}get msids(){return this.sender.streamIds.map((s)=>`${s} ${this.sender.trackId}`)}addTrack(s){if(this.receiver.addTrack(s))this.onTrack.execute(s,this)}get associated(){return this.mid!=null&&this.mLineIndex!=null}stop(){if(rS(this),this.stopping)return;if(this.stopping=!0,this.releaseMedia(),!this.associated)this.markStopped();this.onStopRequested.execute()}commitStopped({rejected:s}){if(s&&!this.stopping)this.rejected=!0;this.pendingRejection=!1,this.stopping=!0,this.releaseMedia(),this.markStopped()}markStopped(){this.stopped=!0,this.setCurrentDirection("stopped")}releaseMedia(){this.sender.stop({keepTrack:!0}),this.receiver.stop(),this.receiver.endTracks(),this.onRelease.execute()}forceStop(){if(this.stopped&&this.sender.stopped&&this.receiver.stopped)return;this.stopping=!0,this.stopped=!0,this.setCurrentDirection("stopped"),this.receiver.stop(),this.sender.stop(),this.onRelease.execute()}getPayloadType(s){return this.codecs.find((n)=>n.mimeType.toLowerCase().includes(s.toLowerCase()))?.payloadType}getCodecStats(){let s=pt();return this.collectCodecStats(s)}collectCodecStats(s){let n=[];if(!this.dtlsTransport)return n;let a=q("transport",this.dtlsTransport.id);for(let o of this.codecs){let c={type:"codec",id:Gn(a,o.payloadType,this.id),timestamp:s,payloadType:o.payloadType,transportId:a,mimeType:o.mimeType,clockRate:o.clockRate,channels:o.channels,sdpFmtpLine:o.parameters};n.push(c)}return n}};function nS(s,n){if(s===n)return!0;if(s==null||n==null||s.length!==n.length)return!1;return Jr(s)===Jr(n)}function Jr(s){if(Array.isArray(s))return`[${s.map(Jr).join(",")}]`;if(s!=null&&typeof s==="object")return`{${Object.entries(s).filter(([,a])=>a!==void 0).sort(([a],[o])=>a.localeCompare(o)).map(([a,o])=>`${JSON.stringify(a)}:${Jr(o)}`).join(",")}}`;return JSON.stringify(s)??"undefined"}var aS="inactive",Hh="sendonly",Fh="recvonly",zh="sendrecv",Mi=[aS,Hh,Fh,zh],Zr=new WeakMap,ei=new WeakSet;function oS(s,n){if(ei.add(s),n==null)Zr.delete(s);else Zr.set(s,n)}function Tt(s){return s==null?void 0:Zr.get(s)}function Os(s){if(ei.has(s))return;if(ei.add(s),s.codec!=null)Zr.set(s,[s.codec])}var cS=class{tracks=new Set;upstreamStops=new Set;attach(s){this.tracks.add(s)}detach(s){if(this.tracks.delete(s),this.tracks.size>0)return;for(let n of[...this.upstreamStops])n();this.upstreamStops.clear()}addUpstreamStop(s){let n=()=>{this.upstreamStops.delete(n),s()};this.upstreamStops.add(n)}deliverRtp(s,n){let a=[...this.tracks].filter((o)=>!o.stopped);for(let o of a)o.applyIncomingRtp(s.clone(),n)}deliverRtcp(s){for(let n of this.tracks)if(!n.stopped)n.onReceiveRtcp.execute(s)}deliverSourceChanged(s){for(let n of this.tracks)if(!n.stopped)n.onSourceChanged.execute(s)}stopAllTracks(){for(let s of[...this.tracks])s.stop()}},rs=class s extends Fs{uuid=qh().toString();streamId;remote=!1;label;kind;id;ssrc;rid;header;codec;enabled=!0;onReceiveRtp=new E;onReceiveRtcp=new E;onSourceChanged=new E;stopped=!1;muted=!0;broadcastSource;constructor(n){super();let a=n.broadcastSource;if(Object.assign(this,n),this.id??=this.uuid,this.broadcastSource=a??new cS,!this.stopped)this.broadcastSource.attach(this);this.onReceiveRtp.subscribe((o)=>{this.muted=!1,this.header=o.header}),this.label=`${this.remote?"remote":"local"} ${this.kind}`}get readyState(){return this.stopped?"ended":"live"}stop=()=>{if(this.stopped)return;this.stopped=!0,this.muted=!0,this.onReceiveRtp.complete(),this.emit("ended"),this.broadcastSource.detach(this)};writeRtp=(n)=>{if(this.remote)throw Error("this is remoteTrack");let a=Buffer.isBuffer(n)?fe.deSerialize(n):n.clone();a.header.payloadType=this.codec?.payloadType??a.header.payloadType,this.broadcastSource.deliverRtp(a)};writeRtcp=(n)=>{this.broadcastSource.deliverRtcp(n)};notifySourceChanged(n){this.broadcastSource.deliverSourceChanged(n)}applyIncomingRtp(n,a){if(this.stopped)return;this.onReceiveRtp.execute(n,a)}bindUpstreamStop(n){this.broadcastSource.addUpstreamStop(n)}stopMediaSource(){this.broadcastSource.stopAllTracks()}clone(){let n=new s({kind:this.kind,remote:this.remote,enabled:this.enabled,muted:this.muted,stopped:this.stopped,codec:this.codec,ssrc:this.ssrc,rid:this.rid,header:this.header,broadcastSource:this.broadcastSource});if(ei.has(this))oS(n,Tt(this));else Os(n);return n}},dS=class s{id;tracks=[];constructor(n={}){if(Array.isArray(n))this.tracks=n;else Object.assign(this,n);this.id??=qh().toString()}addTrack(n){n.streamId=this.id,this.tracks.push(n)}removeTrack(n){if(this.tracks=this.tracks.filter((a)=>a!==n),n.streamId===this.id)n.streamId=void 0}getTracks(){return this.tracks}getAudioTracks(){return this.tracks.filter((n)=>n.kind==="audio")}getVideoTracks(){return this.tracks.filter((n)=>n.kind==="video")}getTrackById(n){return this.tracks.find((a)=>a.id===n)}get active(){return this.tracks.some((n)=>!n.stopped)}clone(){let n=new s;for(let a of this.tracks)n.addTrack(a.clone());return n}},hS=_("werift:packages/webrtc/src/utils.ts");function Wh(s,n){let a=(d)=>d.toUpperCase(),o=(d)=>d.match(/(.{2})/g).join(":"),c=tS(n).update(s).digest("hex");return o(a(c))}var lS={sha1:"sha1","sha-1":"sha1",sha224:"sha224","sha-224":"sha224",sha256:"sha256","sha-256":"sha256",sha384:"sha384","sha-384":"sha384",sha512:"sha512","sha-512":"sha512"};function Kh(s){return lS[s.trim().toLowerCase()]}function Cn(s){return s.replace(/[^0-9a-f]/gi,"").toLowerCase()}function uS(s){let n=s[0];return n>19&&n<64}var $h=(s,n)=>Mi[Mi.indexOf(s)&Mi.indexOf(n)];function pS(s){if(s==="sendonly")return"recvonly";if(s==="recvonly")return"sendonly";return s}var Gh=Date.now,fS=BigInt(Date.now())*1000n-process.hrtime.bigint()/1000n,mS=()=>fS+process.hrtime.bigint()/1000n,ti=()=>Date.now()/1000,gS=()=>{let n=(uc.timeOrigin+uc.now()-Date.UTC(1900,0,1))/1000,[a,o]=n.toString().split(".").map(Number);return W([4,4],[a,o]).readBigUInt64BE()},yS=(s)=>{let[n,a]=oe(W([8],[s]),[4,4]);return n*1000+a+Date.UTC(1900,0,1)},jh=(s)=>{let n=W([8],[s]),[,a,o]=oe(n,[2,2,2,2]);return W([2,2],[a,o]).readUInt32BE()};function SS(s){let n={};for(let a of s){let o=Array.isArray(a.urls)?a.urls:[a.urls];for(let c of o){let d=wS(c);if(!d)continue;if(!n.stunServer&&d.kind==="stun")n.stunServer=d.address;if(!n.turnServer&&d.kind==="turn")n.turnServer=d.address,n.turnTransport=d.transport,n.turnUsername=a.username,n.turnPassword=a.credential}}return hS("iceOptions",n),n}function vS({configuredTurnTransport:s,forceTurnTCP:n,parsedTurnTransport:a}){if(a)return a;if(s)return s;if(n)return"tcp";return}function wS(s){let n=/^(stun|stuns|turn|turns):(.+)$/i.exec(s.trim());if(!n)return;let[,a,o]=n,c=a.toLowerCase(),[d]=o.split("?",1),[,h=""]=o.split("?"),u=RS(d,bS(c));if(!u)return;if(c==="stun"||c==="stuns")return{kind:"stun",address:u};let f=new URLSearchParams(h).get("transport"),m=TS({scheme:c,transportParam:f});if(m==="invalid")return;return{kind:"turn",address:u,transport:m}}function TS({scheme:s,transportParam:n}){if(n==null)return s==="turns"?"tls":void 0;if(n==="udp")return s==="turns"?"invalid":"udp";if(n==="tcp")return s==="turns"?"tls":"tcp";return"invalid"}function bS(s){if(s==="stuns"||s==="turns")return 5349;return 3478}function RS(s,n){let a=s.startsWith("//")?s.slice(2):s;if(!a)return;if(a.startsWith("[")){let d=a.indexOf("]");if(d===-1)return;let h=a.slice(1,d),u=fc(a.slice(d+1),n);return[h,u]}let o=a.indexOf(":"),c=a.lastIndexOf(":");if(o!==-1&&o===c)return[a.slice(0,o),fc(a.slice(o+1),n)];return[a,n]}function fc(s,n){let a=s.startsWith(":")?s.slice(1):s,o=Number.parseInt(a,10);return Number.isFinite(o)?o:n}var rb=jr.createSelfSignedCertificateWithKey;var CS=(s,n)=>{if(!s||typeof s!=="object")if(n!==null&&typeof n==="object")return n;else return s;if(!n||typeof n!=="object"){if(n==null)return s;return n}for(let a in n)if(Object.hasOwn(n,a)){let o=n[a];if(o!=null)s[a]=o}return s},we=_("werift:packages/webrtc/src/transport/dtls.ts");function ES(s){if(!s)return;if(s.major===254&&s.minor===253)return"DTLS 1.2";if(s.major===254&&s.minor===255)return"DTLS 1.0"}function IS(s){switch(s){case 1:return"AES_CM_128_HMAC_SHA1_80";case 7:return"AEAD_AES_128_GCM";default:return}}var mc=class s{constructor(n,a,o,c=[]){this.config=n,this.iceTransport=a,this.localCertificate=o,this.srtpProfiles=c,this.localCertificate??=s.localCertificate}config;iceTransport;localCertificate;srtpProfiles;id=Jy().toString();state="new";role="auto";iceRoleAtStart;srtpStarted=!1;transportSequenceNumber=0;bytesSent=0;bytesReceived=0;packetsSent=0;packetsReceived=0;dataReceiver=()=>{};dtls;srtp;srtcp;onStateChange=new E;onRtcp=new E;onRtp=new E;events=new Fs;onstatechange;static localCertificate;static localCertificatePromise;remoteParameters;addEventListener=(n,a,o)=>{this.events.addEventListener(n,a,o)};removeEventListener=(n,a)=>{this.events.removeEventListener(n,a)};dispatchEvent=(n)=>this.events.dispatchEvent(n);get localParameters(){return new In(this.localCertificate?this.localCertificate.getFingerprints():[],this.role)}static async SetupCertificate(){if(this.localCertificate)return this.localCertificate;if(this.localCertificatePromise)return this.localCertificatePromise;return this.localCertificatePromise=(async()=>{let{certPem:n,keyPem:a,signatureHash:o}=await jr.createSelfSignedCertificateWithKey({signature:Ue.ecdsa_3,hash:Ur.sha256_4},Jt.secp256r1_23);return this.localCertificate=new Vh(a,n,o),this.localCertificate})(),this.localCertificatePromise}setRemoteParams(n){let a=kS(n.fingerprints),o=n.role==="auto"&&this.remoteParameters?.role?this.remoteParameters.role:n.role;this.remoteParameters=new In(a,o)}get hasRemoteParameters(){return(this.remoteParameters?.fingerprints.length??0)>0}async start(){if(this.state!=="new")throw Error("state must be new");if(!this.remoteParameters||this.remoteParameters.fingerprints.length===0)throw Error("remote fingerprint not exist");if(this.iceRoleAtStart=this.iceTransport.role,this.role==="auto")if(this.iceTransport.role==="controlling")this.role="server";else this.role="client";this.setState("connecting"),await new Promise(async(n,a)=>{if(this.role==="server")this.dtls=new Um({cert:this.localCertificate?.certPem,key:this.localCertificate?.privateKey,signatureHash:this.localCertificate?.signatureHash,transport:gc(this.iceTransport.connection),srtpProfiles:this.srtpProfiles,extendedMasterSecret:!0,certificateRequest:!0});else this.dtls=new Ro({cert:this.localCertificate?.certPem,key:this.localCertificate?.privateKey,signatureHash:this.localCertificate?.signatureHash,transport:gc(this.iceTransport.connection),srtpProfiles:this.srtpProfiles,extendedMasterSecret:!0});if(this.dtls.onData.subscribe((o)=>{if(this.config.debug?.inboundPacketLoss&&this.config.debug?.inboundPacketLoss/100<Math.random())return;this.dataReceiver(o)}),this.dtls.onClose.subscribe(()=>{if(this.state!=="failed")this.setState("closed")}),this.dtls.onConnect.once(n),this.dtls.onError.once((o)=>{this.setState("failed"),we("dtls failed",o),a(o)}),this.dtls instanceof Ro)await Zy(100),this.dtls.connect().catch((o)=>{this.setState("failed"),we("dtls connect failed",o),a(o)})});try{this.verifyRemoteCertificateFingerprint()}catch(n){throw this.setState("failed"),this.dtls?.close(),n}if(this.srtpProfiles.length>0)this.startSrtp();this.setState("connected"),we("dtls connected")}verifyRemoteCertificateFingerprint(){if(!this.remoteParameters||this.remoteParameters.fingerprints.length===0)throw Error("remote fingerprint not exist");let n=this.dtls?.remoteCertificate;if(!n)throw Error("remote certificate not available");let a=this.remoteParameters.fingerprints.flatMap(({algorithm:u,value:p})=>{let f=Kh(u);if(!f)return[];let m=Cn(p);if(!m)throw Error("remote fingerprint value is empty");return[{normalizedAlgorithm:f,normalizedValue:m}]});if(a.length===0)throw Error("no supported remote fingerprint algorithms");let o=AS(a),c=a.filter(({normalizedAlgorithm:u})=>u===o),d=c.reduce((u,{normalizedAlgorithm:p})=>{if(!u.has(p))u.set(p,Cn(Wh(n,p)));return u},new Map);if(!c.some(({normalizedAlgorithm:u,normalizedValue:p})=>d.get(u)===p))throw Error("remote certificate fingerprint mismatch")}updateSrtpSession(){if(!this.dtls)throw Error();let n=this.dtls.srtp.srtpProfile;if(!n)throw Error("need srtpProfile");we("selected SRTP Profile",n);let{localKey:a,localSalt:o,remoteKey:c,remoteSalt:d}=this.dtls.extractSessionKeys(Gf(n),jf(n)),h={keys:{localMasterKey:a,localMasterSalt:o,remoteMasterKey:c,remoteMasterSalt:d},profile:n};this.srtp=new am(h),this.srtcp=new im(h)}startSrtp(){if(this.srtpStarted)return;this.srtpStarted=!0,this.updateSrtpSession(),this.iceTransport.connection.onData.subscribe((n)=>{if(this.config.debug?.inboundPacketLoss&&this.config.debug?.inboundPacketLoss/100<Math.random())return;if(!Sf(n))return;if(this.bytesReceived+=n.length,this.packetsReceived++,kf(n)){let a;try{a=this.srtcp.decrypt(n)}catch(c){if(c instanceof Et){we("dropping invalid SRTCP packet",c);return}throw c}let o;try{o=If.deSerialize(a)}catch(c){we("dropping malformed SRTCP packet",c);return}for(let c of o)try{this.onRtcp.execute(c)}catch(d){we("RTCP error",d)}}else{let a;try{a=this.srtp.decrypt(n)}catch(c){if(c instanceof Et){we("dropping invalid SRTP packet",c);return}throw c}let o;try{o=fe.deSerialize(a)}catch(c){we("dropping malformed SRTP packet",c);return}try{this.onRtp.execute(o)}catch(c){we("RTP error",c)}}})}sendData=async(n)=>{if(this.config.debug?.outboundPacketLoss&&this.config.debug?.outboundPacketLoss/100<Math.random())return;if(!this.dtls)throw Error("dtls not established");await this.dtls.send(n)};async sendRtp(n,a){try{let o=this.srtp.encrypt(n,a);if(this.config.debug?.outboundPacketLoss&&this.config.debug?.outboundPacketLoss/100<Math.random())return o.length;return this.bytesSent+=o.length,this.packetsSent++,await this.iceTransport.connection.send(o).catch(()=>{}),o.length}catch(o){return we("failed to send",o),0}}async sendRtcp(n){let a=Buffer.concat(n.map((c)=>c.serialize())),o=this.srtcp.encrypt(a);if(this.config.debug?.outboundPacketLoss&&this.config.debug?.outboundPacketLoss/100<Math.random())return o.length;this.bytesSent+=o.length,this.packetsSent++,await this.iceTransport.connection.send(o).catch(()=>{})}setState(n,a=!0){if(n!=this.state){if(this.state=n,this.onStateChange.execute(n),a)this.onstatechange?.(),this.events.emit("statechange")}}async stop(){this.setState("closed",!1),await this.iceTransport.stop(),this.dtls?.close()}async getStats(n=pt()){let a=[],o=q("transport",this.id),c={type:"transport",id:o,timestamp:n,bytesSent:this.bytesSent,bytesReceived:this.bytesReceived,packetsSent:this.packetsSent,packetsReceived:this.packetsReceived,dtlsState:this.state,iceState:this.iceTransport.state,iceRole:this.iceTransport.role==="unknown"?void 0:this.iceTransport.role,iceLocalUsernameFragment:this.iceTransport.localParameters.usernameFragment,selectedCandidatePairId:this.iceTransport.connection.nominated?q("candidate-pair",this.iceTransport.connection.nominated.id):void 0,localCertificateId:this.localCertificate?q("certificate",this.id,"local"):void 0,remoteCertificateId:this.dtls?.remoteCertificate?q("certificate",this.id,"remote"):void 0,dtlsRole:this.role==="auto"?void 0:this.role,tlsVersion:ES(this.dtls?.dtls.version),dtlsCipher:this.dtls?.cipher.cipher?.name,srtpCipher:IS(this.dtls?.srtp.srtpProfile),iceRestarts:this.iceTransport.iceRestarts};if(a.push(c),this.localCertificate){let h=this.localCertificate.getFingerprints();if(h.length>0){let u={type:"certificate",id:q("certificate",this.id,"local"),timestamp:n,fingerprint:h[0].value,fingerprintAlgorithm:h[0].algorithm,base64Certificate:Buffer.from(this.localCertificate.certPem).toString("base64")};a.push(u)}}if(this.remoteParameters&&this.remoteParameters.fingerprints.length>0&&this.dtls?.remoteCertificate){let h={type:"certificate",id:q("certificate",this.id,"remote"),timestamp:n,fingerprint:this.remoteParameters.fingerprints[0].value,fingerprintAlgorithm:this.remoteParameters.fingerprints[0].algorithm,base64Certificate:Buffer.from(this.dtls.remoteCertificate).toString("base64")};a.push(h)}let d=await this.iceTransport.getStats(n,o);return a.push(...d),a}};var Vh=class{constructor(s,n,a){this.certPem=n,this.signatureHash=a,this.certPem=Vr(n);let o=new hc(this.certPem);this.publicKey=o.publicKey.export({type:"spki",format:"pem"}).toString(),this.privateKey=Xy(Vr(s)).export({type:"pkcs8",format:"pem"}).toString()}certPem;signatureHash;publicKey;privateKey;getFingerprints(){return[new En("sha-256",Wh(new hc(this.certPem).raw,"sha256"))]}},En=class{constructor(s,n){this.algorithm=s,this.value=n}algorithm;value},In=class{constructor(s=[],n){this.fingerprints=s,this.role=n}fingerprints;role},kS=(s)=>{let n=new Set;return s.filter(({algorithm:a,value:o})=>{let c=`${Kh(a)??a.trim().toLowerCase()}:${Cn(o)}`;if(n.has(c))return!1;return n.add(c),!0})},PS=["sha512","sha384","sha256","sha224","sha1"],AS=(s)=>PS.find((n)=>s.some(({normalizedAlgorithm:a})=>a===n))??s[0].normalizedAlgorithm,xS=class{constructor(s){this.ice=s,s.onData.subscribe((n)=>{if(uS(n)){if(this.onData)this.onData(n)}})}ice;closed=!1;onData=()=>{};get address(){return{}}type="ice";send=(s)=>this.ice.send(s);async close(){if(this.closed)return;if(this.closed=!0,this.ice.state!=="closed")this.ice.close()}},gc=(s)=>new xS(s),Sc=Object.freeze({foundation:null,component:null,priority:null,address:null,protocol:null,port:null,type:null,tcpType:null,relatedAddress:null,relatedPort:null}),MS=["host","srflx","prflx","relay"],Yh=["active","passive","so"],si=(s)=>typeof s==="string"&&/^\S+$/.test(s),mr=(s,n,a)=>typeof s==="number"&&Number.isInteger(s)&&s>=n&&s<=a,vc="[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?",DS=new RegExp(`^(?=.{1,253}\\.?$)${vc}(?:\\.${vc})*\\.?$`),Te={foundation:(s)=>typeof s==="string"&&/^[A-Za-z0-9+/]{1,32}$/.test(s),component:(s)=>mr(s,1,256),protocol:si,priority:(s)=>mr(s,1,2147483647),address:(s)=>typeof s==="string"&&(LS(s)||BS(s)||!/^[\d.]+$/.test(s)&&DS.test(s)),port:(s)=>mr(s,0,65535),type:si,tcpType:(s)=>Yh.includes(s),generation:(s)=>mr(s,0,Number.MAX_SAFE_INTEGER)};function Qh(s){return Te.foundation(s.foundation)&&Te.component(s.component)&&Te.protocol(s.protocol)&&Te.priority(s.priority)&&Te.address(s.ip)&&Te.port(s.port)&&Te.type(s.type)&&(s.relatedAddress===void 0||Te.address(s.relatedAddress))&&(s.relatedPort===void 0||Te.port(s.relatedPort))&&(s.tcpType===void 0||Te.tcpType(s.tcpType))&&(s.generation===void 0||Te.generation(s.generation))&&(s.ufrag===void 0||si(s.ufrag))}var ms=(s)=>/^\d{1,16}$/.test(s)?Number(s):Number.NaN;function kn(s){if(typeof s!=="string")return;let a=(s.startsWith("candidate:")?s.slice(10):s).split(" ");if(a.length<8||a.length%2!==0)return;if(!a.every(si)||a[6]!=="typ")return;let[o,c,d,h,u,p,,f]=a,m={foundation:o,component:ms(c),protocol:d,priority:ms(h),ip:u,port:ms(p),type:f};for(let y=8;y<a.length;y+=2){let[S,v]=[a[y],a[y+1]];if(S==="raddr")m.relatedAddress=v;else if(S==="rport")m.relatedPort=ms(v);else if(S==="tcptype")m.tcpType=v;else if(S==="generation")m.generation=ms(v);else if(S==="ufrag")m.ufrag=v}return Qh(m)?m:void 0}function Pn(s){if(!s||!Qh(s))return{...Sc};let n=s.component===1?"rtp":s.component===2?"rtcp":void 0,a=s.protocol.toLowerCase(),o=MS.find((c)=>c===s.type);if(!n||a!=="udp"&&a!=="tcp"||!o)return{...Sc};return{foundation:s.foundation,component:n,priority:s.priority,address:s.ip,protocol:a,port:s.port,type:o,tcpType:a==="tcp"?Yh.find((c)=>c===s.tcpType)??null:null,relatedAddress:s.relatedAddress??null,relatedPort:s.relatedPort??null}}var Ft=_("werift:packages/webrtc/src/transport/ice.ts");function US(s){switch(s){case 0:return"frozen";case 1:return"waiting";case 2:return"in-progress";case 3:return"succeeded";case 4:return"failed";default:return"failed"}}var NS=class{constructor(s){this.iceGather=s,this.connection=this.iceGather.connection,this.connection.stateChanged.subscribe((n)=>{this.setState(n)}),this.iceGather.onIceCandidate=(n)=>{if(this.heldCandidateEvents)this.heldCandidateEvents.push(n);else this.onIceCandidate.execute(n)},this.iceGather.onGatheringStateChange.subscribe(()=>{this.ongatheringstatechange?.(),this.events.emit("gatheringstatechange")})}iceGather;id=_S().toString();connection;state="new";component="rtp";iceRestarts=0;waitStart;checksStarted=!1;renominating=!1;stagedLocalRestart;localGenerations=new Map;appliedLocalRestart;heldCandidateEvents;nextGatherIceServers;events=new Fs;onstatechange;ongatheringstatechange;onStateChange=new E;onIceCandidate=new E;onNegotiationNeeded=new E;addEventListener=(s,n,a)=>{this.events.addEventListener(s,n,a)};removeEventListener=(s,n)=>{this.events.removeEventListener(s,n)};dispatchEvent=(s)=>this.events.dispatchEvent(s);get role(){if(!this.connection.remoteUsername||!this.connection.remotePassword)return"unknown";if(this.connection.iceControlling)return"controlling";else return"controlled"}get gatheringState(){return this.iceGather.gatheringState}get localCandidates(){return this.describedLocalGeneration().candidates}get localCandidatesComplete(){return this.describedLocalGeneration().complete}describedLocalGeneration({applied:s=!1}={}){let n=this.stagedLocalRestart;if(!n||s&&n!==this.appliedLocalRestart)return{parameters:this.iceGather.localParameters,candidates:this.iceGather.localCandidates,complete:this.gatheringState==="complete"||this.connection.localCandidatesEnd};let a=this.stagedGatherPending();return{parameters:new ri({iceLite:this.connection.iceLite,usernameFragment:n.usernameFragment,password:n.password}),candidates:a?n.candidates.filter((o)=>o.type!=="relay"):n.candidates,complete:this.gatheringState==="complete"&&!a}}stagedGatherPending(){let s=this.stagedLocalRestart;if(!s)return!1;if(s.emitted)return!!s.endDeferred;return!!this.nextGatherIceServers||!!this.connection.gathersFromServers}get localParameters(){return this.describedLocalGeneration().parameters}stageLocalRestart({answering:s,replacing:n}={}){let a=this.appliedLocalRestart,o=s?[...this.localGenerations.values()].find((m)=>m.answering===s):a&&!n?.has(a.usernameFragment)?a:void 0;if(o){this.selectGeneration(o);return}this.unselectLocalRestart();let c=yc(6).toString("base64url"),d=yc(24).toString("base64url"),h=this.connection.options.localPasswordPrefix??"",u=h+d.slice(h.length),p=this.iceGather.localCandidates.map((m)=>Object.assign(new jn(m.component,m.foundation,m.ip,m.port,m.priority,m.protocol,m.type,this.connection.generation+1,c),{relatedAddress:m.relatedAddress,relatedPort:m.relatedPort,tcpType:m.tcpType})),f={usernameFragment:c,password:u,candidates:p,emitted:!1,answering:s,createdBy:s?"answer":"offer"};for(let[m,y]of this.localGenerations)if(y.createdBy===f.createdBy&&y!==this.appliedLocalRestart)this.localGenerations.delete(m);this.localGenerations.set(c,f),this.stagedLocalRestart=f,this.connection.stageLocalCredentials?.(c,u)}localGenerationFor(s,n){let a=this.iceGather.localParameters;if(a.usernameFragment===s&&a.password===n)return"live";let o=this.localGenerations.get(s);if(o?.password===n)return o;return}selectLocalGeneration(s,n){let a=this.localGenerationFor(s,n);if(!a)return!1;if(a==="live")return this.unselectLocalRestart(),!0;return this.selectGeneration(a),!0}selectGeneration(s){if(this.stagedLocalRestart===s)return;this.unselectLocalRestart(),this.stagedLocalRestart=s,this.connection.stageLocalCredentials?.(s.usernameFragment,s.password)}unselectLocalRestart(){let s=this.stagedLocalRestart;if(!s)return;this.connection.discardStagedLocalCredentials?.(s.usernameFragment),this.stagedLocalRestart=void 0}get hasStagedRestart(){return!!this.stagedLocalRestart}setProvisionalRemoteParams(s){if(!this.stagedLocalRestart)return;this.connection.setProvisionalRemoteParams?.(s)}addProvisionalRemoteCandidate(s){if(!this.stagedLocalRestart)return;return this.connection.addProvisionalRemoteCandidate?.(s?wc(s):void 0)}deliverRemoteCandidate(s){Promise.resolve(this.addRemoteCandidate(s)).catch((n)=>Ft("addRemoteCandidate failed",n))}deliverProvisionalRemoteCandidate(s){Promise.resolve(this.addProvisionalRemoteCandidate(s)).catch((n)=>Ft("addProvisionalRemoteCandidate failed",n))}startProvisionalChecks(){if(!this.stagedLocalRestart)return;this.connection.startProvisionalChecks?.()}emitStagedCandidates(){let s=this.stagedLocalRestart;if(!s||s.emitted)return;let n=this.localCandidates;s.endDeferred=this.stagedGatherPending(),s.emitted=!0;for(let a of n)this.onIceCandidate.execute(Object.assign(Object.create(Object.getPrototypeOf(a)),a));if(!s.endDeferred)this.onIceCandidate.execute(void 0)}rollbackLocalRestart(){if(this.appliedLocalRestart=void 0,this.stagedLocalRestart)this.stagedLocalRestart.emitted=!1;this.unselectLocalRestart()}markLocalRestartApplied(){this.appliedLocalRestart=this.stagedLocalRestart}discardUnappliedLocalRestart(){let s=this.stagedLocalRestart,n=this.appliedLocalRestart;if(!s||s===n)return;if(this.unselectLocalRestart(),n)this.stagedLocalRestart=n,this.connection.stageLocalCredentials?.(n.usernameFragment,n.password)}async commitLocalRestartIfStaged(){let s=this.stagedLocalRestart;if(!s)return;let n=this.stagedGatherPending();if(this.restart(!1,n),this.connection.commitLocalCredentials)this.connection.commitLocalCredentials(s.usernameFragment,s.password);else this.connection.localUsername=s.usernameFragment,this.connection.localPassword=s.password;if(this.stagedLocalRestart=void 0,this.appliedLocalRestart=void 0,!s.emitted)this.heldCandidateEvents=[];s.emitted=!1,s.endDeferred=void 0;let a=this.gather();if(n)a.catch((o)=>Ft("restart gathering failed",o));else await a}emitCommittedCandidates(){let s=this.heldCandidateEvents;if(!s)return;this.heldCandidateEvents=void 0;for(let n of s)this.onIceCandidate.execute(n)}getRemoteCandidates(){return this.connection.remoteCandidates.filter((s)=>s.type!=="prflx").map((s)=>Rt(s).toJSON())}getLocalCandidates(){return this.connection.localCandidates.map((s)=>Rt(s).toJSON())}getSelectedCandidatePair(){let s=this.connection.candidatePairs.find((n)=>n.nominated)??this.connection.candidatePairs.find((n)=>n.state===3);if(!s)return null;return{local:Rt(s.localCandidate).toJSON(),remote:Rt(s.remoteCandidate).toJSON()}}getLocalParameters(){return this.localParameters??null}getRemoteParameters(){if(!this.connection.remoteUsername||!this.connection.remotePassword)return null;return new ri({iceLite:this.connection.remoteIsLite,password:this.connection.remotePassword,usernameFragment:this.connection.remoteUsername})}setState(s,n=!0){if(this.state==="closed")return;if(s!==this.state){if(this.state=s,this.onStateChange.execute(s),n)this.onstatechange?.(),this.events.emit("statechange")}}gather(){return this.iceGather.gather()}setIceServers(s){this.nextGatherIceServers=void 0,this.iceGather.setIceServers(s)}deferIceServers(s){this.nextGatherIceServers=s}addRemoteCandidate=(s)=>{if(!this.connection.remoteCandidatesEnd)return!s?this.connection.addRemoteCandidate(void 0):this.connection.addRemoteCandidate(wc(s))};setRemoteParams(s,n=!1,{keepLocalCredentials:a=!1}={}){if(n)this.renominating=!0;if(this.connection.remoteUsername&&this.connection.remotePassword&&(this.connection.remoteUsername!==s.usernameFragment||this.connection.remotePassword!==s.password))if(this.renominating)Ft("renomination",s),this.connection.resetNominatedPair(),this.connection.dropOtherRemoteGenerations?.(s.usernameFragment),this.renominating=!1;else if(a&&this.connection.restartRemote)Ft("remote restart",s),this.resetRemoteGeneration();else Ft("restart",s),this.restart();this.connection.setRemoteParams(s)}resetRemoteGeneration(){if(!this.connection.restartRemote)return;this.connection.restartRemote(),this.setState("new"),this.waitStart=void 0,this.checksStarted=!1}restart(s=!0,n=!0){this.iceRestarts++,this.connection.restart();let a=this.nextGatherIceServers;if(a&&n)this.setIceServers(a);if(this.setState("new"),this.iceGather.setGatheringState("new"),this.waitStart=void 0,this.checksStarted=!1,s)this.onNegotiationNeeded.execute()}async start(){if(this.state==="closed")throw Error("RTCIceTransport is closed");if(!this.connection.remotePassword||!this.connection.remoteUsername)throw Error("remoteParams missing");if(this.waitStart)await this.waitStart.asPromise();let s=new E;this.waitStart=s,this.checksStarted=!0,this.setState("checking");try{await this.connection.connect()}catch(n){throw this.setState("failed"),n}finally{if(!s.ended)s.execute(),s.complete();if(this.waitStart===s)this.waitStart=void 0}}async checksSettled(){let s=this.waitStart;if(s)await s.asPromise()}async stop(){this.localGenerations.clear();let s=this.waitStart;if(this.waitStart=void 0,s&&!s.ended)s.execute(),s.complete();if(this.state!=="closed")this.setState("closed",!1),await this.connection.close();this.onStateChange.complete(),this.onIceCandidate.complete(),this.onNegotiationNeeded.complete()}async getStats(s=pt(),n=q("transport",this.id)){let a=[];for(let c of this.connection.localCandidates){let d={type:"local-candidate",id:q("local-candidate",c.id),timestamp:s,transportId:n,address:c.host,port:c.port,protocol:c.transport,candidateType:c.type,priority:c.priority,foundation:c.foundation,relatedAddress:c.relatedAddress,relatedPort:c.relatedPort,usernameFragment:c.ufrag,tcpType:c.tcptype};a.push(d)}for(let c of this.connection.remoteCandidates){let d={type:"remote-candidate",id:q("remote-candidate",c.id),timestamp:s,transportId:n,address:c.host,port:c.port,protocol:c.transport,candidateType:c.type,priority:c.priority,foundation:c.foundation,relatedAddress:c.relatedAddress,relatedPort:c.relatedPort,usernameFragment:c.ufrag,tcpType:c.tcptype};a.push(d)}let o=this.connection?.candidatePairs?[...this.connection.candidatePairs.filter((c)=>c.nominated),...this.connection.candidatePairs.filter((c)=>!c.nominated)]:[];for(let c of o){let d={type:"candidate-pair",id:q("candidate-pair",c.id),timestamp:s,transportId:n,localCandidateId:q("local-candidate",c.localCandidate.id),remoteCandidateId:q("remote-candidate",c.remoteCandidate.id),state:US(c.state),nominated:c.nominated,packetsSent:c.packetsSent,packetsReceived:c.packetsReceived,bytesSent:c.bytesSent,bytesReceived:c.bytesReceived,currentRoundTripTime:c.rtt,totalRoundTripTime:c.totalRoundTripTime,roundTripTimeMeasurements:c.roundTripTimeMeasurements,requestsReceived:c.requestsReceived,requestsSent:c.requestsSent,responsesReceived:c.responsesReceived,responsesSent:c.responsesSent,retransmissionsReceived:c.retransmissionsReceived,retransmissionsSent:c.retransmissionsSent,consentRequestsSent:c.consentRequestsSent};a.push(d)}return a}};var OS=class{constructor(s={}){this.options=s,this.connection=new oy(!1,this.options),this.connection.onIceCandidate.subscribe((n)=>{this.onIceCandidate(Rt(n))})}options;onIceCandidate=()=>{};gatheringState="new";connection;onGatheringStateChange=new E;async gather(){if(this.gatheringState==="new"){this.setState("gathering");let s=this.connection.generation;if(await this.connection.gatherCandidates(),this.connection.generation!==s||this.connection.state==="closed")return;this.onIceCandidate(void 0),this.setState("complete")}}setIceServers(s){this.connection.setIceServers(s)}setGatheringState(s){this.setState(s)}get localCandidates(){return this.connection.localCandidates.map(Rt)}get localParameters(){return new ri({iceLite:this.connection.iceLite,usernameFragment:this.connection.localUsername,password:this.connection.localPassword})}setState(s){if(s!==this.gatheringState)this.gatheringState=s,this.onGatheringStateChange.execute(s)}};function Rt(s){let n=new jn(s.component,s.foundation,s.host,s.port,s.priority,s.transport,s.type,s.generation,s.ufrag);return n.relatedAddress=s.relatedAddress,n.relatedPort=s.relatedPort,n.tcpType=s.tcptype,n}function wc(s){return new Me(s.foundation,s.component,s.protocol,s.priority,s.ip,s.port,s.type,s.relatedAddress,s.relatedPort,s.tcpType,s.generation,s.ufrag)}var Xh=Symbol("RTCIceCandidate.parsedFields");function Jh(s,n){return new HS({...s,[Xh]:n})}var HS=class{candidate="";sdpMid;sdpMLineIndex;usernameFragment;foundation;component;priority;address;protocol;port;type;tcpType;relatedAddress;relatedPort;constructor(s={}){let{sdpMid:n,sdpMLineIndex:a,usernameFragment:o}=s,c=s.candidate??"",d=s[Xh]??Pn(kn(c));Object.assign(this,d,{candidate:c,sdpMid:n,sdpMLineIndex:a,usernameFragment:o})}static fromSdp(s){let n=kn(s);return Jh({candidate:s,usernameFragment:n?.ufrag},Pn(n))}static isThis(s){if(typeof s?.candidate==="string")return!0}toJSON(){return{candidate:this.candidate,sdpMid:this.sdpMid,sdpMLineIndex:this.sdpMLineIndex,usernameFragment:this.usernameFragment}}},jn=class s{constructor(n,a,o,c,d,h,u,p,f){this.component=n,this.foundation=a,this.ip=o,this.port=c,this.priority=d,this.protocol=h,this.type=u,this.generation=p,this.ufrag=f}component;foundation;ip;port;priority;protocol;type;generation;ufrag;relatedAddress;relatedPort;sdpMid;sdpMLineIndex;tcpType;toJSON(){return Jh({candidate:el(this),sdpMLineIndex:this.sdpMLineIndex,sdpMid:this.sdpMid,usernameFragment:this.ufrag},Pn(this))}static fromJSON(n){let a=kn(n.candidate??"");if(!a)return;let o=new s(a.component,a.foundation,a.ip,a.port,a.priority,a.protocol,a.type,a.generation,a.ufrag);return o.relatedAddress=a.relatedAddress,o.relatedPort=a.relatedPort,o.tcpType=a.tcpType,o.sdpMLineIndex=n.sdpMLineIndex??void 0,o.sdpMid=n.sdpMid??void 0,o}},ri=class{iceLite=!1;usernameFragment;password;constructor(s={}){Object.assign(this,s)}},Xe=_("werift:packages/webrtc/src/transport/sctp.ts"),Yt=65536,zS=class s{constructor(n=5000,a=Yt,o={}){this.port=n,this.maxMessageSize=a,this.sctpOptions=o}port;maxMessageSize;sctpOptions;dtlsTransport;sctp;onDataChannel=new E;id=FS().toString();mid;mLineIndex;bundled=!1;dataChannels={};stopped=!1;remoteMaxMessageSize=Yt;dataChannelQueue=new Vt;dataChannelId;eventDisposer=[];get transport(){return this.dtlsTransport}setDtlsTransport(n){if(this.dtlsTransport&&this.dtlsTransport.id===n.id)return;this.eventDisposer.forEach((a)=>a()),this.dtlsTransport=n,this.stopped=!1,this.sctp=new ky(new qS(this.dtlsTransport),this.port,this.sctpOptions),this.eventDisposer=[...[this.sctp.onReceive.subscribe(this.datachannelReceive),this.sctp.onReconfigStreams.subscribe((a)=>{a.forEach((o)=>{let c=this.dataChannels[o];if(!c)return;c.setReadyState("closing"),c.setReadyState("closed"),delete this.dataChannels[o]})}),this.sctp.stateChanged.connected.subscribe(()=>{Object.values(this.dataChannels).forEach((a)=>{if(a.negotiated&&a.readyState!=="open")a.setReadyState("open")}),this.dataChannelFlush()}),this.sctp.stateChanged.closed.subscribe(()=>{Object.values(this.dataChannels).forEach((a)=>{a.setReadyState("closed")}),this.dataChannels={}}),this.dtlsTransport.onStateChange.subscribe((a)=>{if(a==="closed")this.sctp.setState(1)})].map((a)=>a.unSubscribe),()=>this.sctp.onSackReceived=async()=>{}],this.sctp.onSackReceived=async()=>{this.dataChannelFlush()}}get isServer(){return(this.dtlsTransport.iceRoleAtStart??this.dtlsTransport.iceTransport.role)!=="controlling"}channelByLabel(n){return Object.values(this.dataChannels).find((a)=>a.label===n)}datachannelReceive=async(n,a,o)=>{if(this.stopped)return;if(a===Ht&&o.length>0)switch(Xe("DCEP",n,a,o),o[0]){case Bi:{if(o.length<12){Xe("DATA_CHANNEL_OPEN data.length not enough");return}if(!Object.keys(this.dataChannels).includes(n.toString())){let h=o.readUInt8(1),u=o.readUInt32BE(4),p=o.readUInt16BE(8),f=o.readUInt16BE(10),m=12,y=o.slice(m,m+p).toString("utf8");m+=p;let S=o.slice(m,m+f).toString("utf8");Xe("DATA_CHANNEL_OPEN",{channelType:h,reliability:u,streamId:n,label:y,protocol:S});let v=(h&3)===1?u:void 0,g=(h&3)===2?u:void 0,w=new md({label:y,ordered:(h&128)===0,maxPacketLifeTime:g,maxRetransmits:v,protocol:S,id:n}),T=new fd(this,w,!1);T.isCreatedByRemote=!0,this.dataChannels[n]=T,this.onDataChannel.execute(T),T.setReadyState("open")}else Xe("datachannel already opened","retransmit ack");let c=this.dataChannels[n],d=Buffer.allocUnsafe(1);d.writeUInt8(rc,0),this.dataChannelQueue.push([c,Ht,d]),this.dataChannelFlush()}break;case rc:{Xe("DATA_CHANNEL_ACK",n,a);let c=this.dataChannels[n];if(!c)throw Error("channel not found");c.setReadyState("open")}break}else{let c=this.dataChannels[n];if(c){let d=(()=>{switch(a){case ic:return o.toString("utf8");case jy:return"";case nc:return o;case Vy:return Buffer.from([]);default:throw Error()}})();if(c.messagesReceived++,c.bytesReceived+=o.length,c.onMessage.execute(d),c.emit("message",{data:d}),c.onmessage)c.onmessage({data:d})}}};dataChannelAddNegotiated(n){if(n.id==null)throw Error();if(this.dataChannels[n.id])throw Error();if(this.dataChannels[n.id]=n,this.sctp.associationState===4)n.setReadyState("open")}dataChannelOpen(n){if(n.id!==void 0){if(this.dataChannels[n.id])throw Error(`Data channel with ID ${n.id} already registered`);this.dataChannels[n.id]=n}let a=0,o,c=0;if(n.maxRetransmits!==null)o=n.ordered?qy:$y,c=n.maxRetransmits;else if(n.maxPacketLifeTime!==null)o=n.ordered?Wy:Gy,c=n.maxPacketLifeTime;else o=n.ordered?zy:Ky;let d=Buffer.allocUnsafe(12);d.writeUInt8(Bi,0),d.writeUInt8(o,1),d.writeUInt16BE(a,2),d.writeUInt32BE(c,4),d.writeUInt16BE(n.label.length,8),d.writeUInt16BE(n.protocol.length,10);let h=Buffer.concat([d,Buffer.from(n.label,"utf8"),Buffer.from(n.protocol,"utf8")]);this.dataChannelQueue.push([n,Ht,h]),this.dataChannelFlush()}dataChannelFlush(){if(this.sctp.associationState!=4)return;this.dataChannelId??=this.isServer?0:1;while(this.dataChannelQueue.length>0){let[n,a,o]=this.dataChannelQueue.shift();if(n.readyState==="closed"||n.readyState==="closing"){if(a!==Ht)n.addBufferedAmount(-o.length);continue}let c=n.id;if(c===void 0){c=this.dataChannelId;while(Object.keys(this.dataChannels).includes(c.toString()))c+=2;this.dataChannels[c]=n,n.setId(c)}if(a===Ht)this.sctp.send(c,a,o,{ordered:!0}).catch((d)=>{Xe("send DCEP failed",d.message)});else{let d=n.maxPacketLifeTime!==null?Date.now()+n.maxPacketLifeTime/1000:void 0;this.sctp.send(c,a,o,{expiry:d,maxRetransmits:n.maxRetransmits??void 0,ordered:n.ordered}).catch((h)=>{Xe("send data failed",h.message)}).then(()=>n.addBufferedAmount(-o.length)).catch((h)=>{Xe("update bufferedAmount failed",h.message)})}}}assertSendableMessageSize(n){if(this.remoteMaxMessageSize!==0&&n>this.remoteMaxMessageSize)throw Error(`max-message-size exceeded: ${n} > ${this.remoteMaxMessageSize}`)}datachannelSend=(n,a)=>{let o=Buffer.isBuffer(a)?a:Buffer.from(a),c=zu(a);if(this.assertSendableMessageSize(c),n.addBufferedAmount(c),this.dataChannelQueue.push(typeof a==="string"?[n,ic,o]:[n,nc,o]),this.sctp.associationState!==4)Xe("sctp not established",this.sctp.associationState);return this.dataChannelFlush(),c};getCapabilities(){return s.getCapabilities(this.maxMessageSize)}static getCapabilities(n=Yt){return new Zh(n)}setRemoteMaxMessageSize(n){this.remoteMaxMessageSize=n??Yt}setRemotePort(n){this.sctp.setRemotePort(n)}async start(n){if(this.isServer)this.dataChannelId=0;else this.dataChannelId=1;this.sctp.isServer=this.isServer,await this.sctp.start(n)}async stop(){this.stopped=!0,this.dtlsTransport.dataReceiver=()=>{},this.discardUnsentMessages(),await this.sctp.stop()}discardUnsentMessages(){let n=new Vt;for(let a of this.dataChannelQueue.toArray()){let[o,c,d]=a;if(c!==Ht)o.addBufferedAmount(-d.length);else if(d[0]===Bi&&o.readyState!=="closed"&&o.readyState!=="closing")n.push(a)}this.dataChannelQueue=n}dataChannelClose(n){if(!["closing","closed"].includes(n.readyState))if(n.setReadyState("closing"),this.sctp.associationState===4){if(!this.sctp.reconfigQueue.includes(n.id))this.sctp.reconfigQueue.push(n.id);if(this.sctp.reconfigQueue.length===1)this.sctp.transmitReconfigRequest()}else{if(this.dataChannelQueue=this.dataChannelQueue.filter((a)=>a[0].id!==n.id),this.sctp.reconfigQueue=this.sctp.reconfigQueue.filter((a)=>a!==n.id),n.id!==void 0)delete this.dataChannels[n.id];n.setReadyState("closed")}}},Zh=class{constructor(s){this.maxMessageSize=s}maxMessageSize},qS=class{constructor(s){this.dtls=s}dtls;set onData(s){this.dtls.dataReceiver=s}send=(s)=>this.dtls.sendData(s);close(){}},xr=class s{version=0;origin;name="-";time="0 0";host;group=[];extMapAllowMixed=!0;msidSemantic=[];media=[];type;dtlsRole;iceOptions;iceLite;icePassword;iceUsernameFragment;dtlsFingerprints=[];cachedJson;static parse(n){let[a,o]=WS(n),c=new s;a.forEach((h)=>{if(h.startsWith("v="))c.version=Number.parseInt(h.slice(2),10);else if(h.startsWith("o="))c.origin=h.slice(2);else if(h.startsWith("s="))c.name=h.slice(2);else if(h.startsWith("c="))c.host=Di(h.slice(2));else if(h.startsWith("t="))c.time=h.slice(2);else if(h.startsWith("a=")){let[u,p]=Ui(h);switch(u){case"fingerprint":{let[f,m]=p?.split(" ")||[];c.dtlsFingerprints.push(new En(f,m))}break;case"ice-lite":c.iceLite=!0;break;case"ice-options":c.iceOptions=p;break;case"ice-pwd":c.icePassword=p;break;case"ice-ufrag":c.iceUsernameFragment=p;break;case"group":Ni(c.group,p);break;case"msid-semantic":Ni(c.msidSemantic,p);break;case"setup":c.dtlsRole=cc[p];break;case"extmap-allow-mixed":c.extMapAllowMixed=!0;break}}});let d=c.group.find((h)=>h.semantic==="BUNDLE");return o.forEach((h)=>{let p=h[0].match(/^m=([^ ]+) ([0-9]+) ([A-Z/]+) (.+)/);if(!p)throw Error("m line not found");let f=p[1],m=p[4].split(" "),y=["audio","video"].includes(f)?m.map((g)=>Number(g)):void 0,S=new bs(f,Number.parseInt(p[2]),p[3],y||m);if(S.dtlsParams=new In([...c.dtlsFingerprints],c.dtlsRole),S.iceParams=new ri({iceLite:c.iceLite,usernameFragment:c.iceUsernameFragment,password:c.icePassword}),S.iceOptions=c.iceOptions,c.media.push(S),h.slice(1).forEach((g)=>{if(g.startsWith("c="))S.host=Di(g.slice(2));else if(g.startsWith("a=")){let[w,T]=Ui(g);switch(w){case"candidate":if(!T)throw Error();S.iceCandidates.push(KS(T));break;case"end-of-candidates":S.iceCandidatesComplete=!0;break;case"extmap":{let[b,C]=T.split(" ");if(b.includes("/"))[b]=b.split("/");S.rtp.headerExtensions.push(new xy({id:Number.parseInt(b),uri:C}))}break;case"fingerprint":{if(!T)throw Error();let[b,C]=T.split(" ");S.dtlsParams?.fingerprints.push(new En(b,C))}break;case"ice-options":S.iceOptions=T;break;case"ice-pwd":S.iceParams.password=T;break;case"ice-ufrag":S.iceParams.usernameFragment=T;break;case"ice-lite":S.iceParams.iceLite=!0;break;case"max-message-size":S.sctpCapabilities=new Zh(Number.parseInt(T,10));break;case"mid":S.rtp.muxId=T;break;case"msid":S.msids.push(T);break;case"rtcp":{let[b,C]=Je(T," ");S.rtcpPort=Number.parseInt(b),S.rtcpHost=Di(C)}break;case"rtcp-mux":S.rtcpMux=!0;break;case"setup":S.dtlsParams.role=cc[T];break;case"recvonly":case"sendonly":case"sendrecv":case"inactive":S.direction=w;break;case"rtpmap":{let[b,C]=Je(T," "),[P,x,H]=C.split("/"),O;if(S.kind==="audio")O=H?Number.parseInt(H):1;let ee=new st({mimeType:S.kind+"/"+P,channels:O,clockRate:Number.parseInt(x),payloadType:Number.parseInt(b)});S.rtp.codecs.push(ee)}break;case"sctpmap":{if(!T)throw Error();let[b,C]=Je(T," ");S.sctpMap[Number.parseInt(b)]=C,S.sctpPort=Number.parseInt(b)}break;case"sctp-port":if(!T)throw Error();S.sctpPort=Number.parseInt(T);break;case"ssrc":{let[b,C]=Je(T," "),P=Number.parseInt(b),[x,H]=Je(C,":"),O=S.ssrc.find((ee)=>ee.ssrc===P);if(!O)O=new xn({ssrc:P}),S.ssrc.push(O);if(Nh.includes(x))O[x]=H}break;case"ssrc-group":Ni(S.ssrcGroup,T);break;case"rid":{let[b,C]=Je(T," ");S.simulcastParameters.push(new Bh({rid:b,direction:C}))}break}}}),!S.iceParams.usernameFragment||!S.iceParams.password){if(S.rtp.muxId&&d&&d.items.includes(S.rtp.muxId))for(let g=0;g<d.items.length;g++){if(!d.items.includes(g.toString()))continue;let w=c.media[g];if(w.iceParams?.usernameFragment&&w.iceParams.password){S.iceParams={...w.iceParams};break}}}if(!S.dtlsParams.role)S.dtlsParams=void 0;let v=(g)=>S.rtp.codecs.find((w)=>w.payloadType===g);h.slice(1).forEach((g)=>{if(g.startsWith("a=")){let[w,T]=Ui(g);if(w==="fmtp"){let[b,C]=Je(T," "),P=v(Number(b));P.parameters=C}else if(w==="rtcp-fb"){let[b,C,P]=T.split(" ");S.rtp.codecs.forEach((x)=>{if(["*",x.payloadType.toString()].includes(b))x.rtcpFeedback.push(new _y({type:C,parameter:P}))})}}})}),c}webrtcTrackId(n){if(n.msid?.includes(" ")){let a=n.msid.split(" ");for(let o of this.msidSemantic)if(o.semantic==="WMS"&&(o.items.includes(a[0])||o.items.includes("*")))return a[1]}return}get string(){let n=[`v=${this.version}`,`o=${this.origin}`,`s=${this.name}`];if(this.host)n.push(`c=${An(this.host)}`);if(n.push(`t=${this.time}`),this.group.forEach((c)=>n.push(`a=group:${c.str}`)),this.extMapAllowMixed)n.push("a=extmap-allow-mixed");this.msidSemantic.forEach((c)=>n.push(`a=msid-semantic:${c.str}`));let a=this.media.map((c)=>c.toString()).join("");return n.join(`\r
9
+ `)+`\r
10
+ `+a}toJSON(){let n=this.string;if(!this.cachedJson||this.cachedJson.sdp!==n||this.cachedJson.type!==this.type)this.cachedJson=new $S(n,this.type);return this.cachedJson}toSdp(){return{type:this.type,sdp:this.string}}},bs=class{constructor(s,n,a,o){this.kind=s,this.port=n,this.profile=a,this.fmt=o}kind;port;profile;fmt;host;direction;msids=[];rtcpPort;rtcpHost;rtcpMux=!1;ssrc=[];ssrcGroup=[];rtp={codecs:[],headerExtensions:[]};sctpCapabilities;sctpMap={};sctpPort;dtlsParams;iceParams;iceCandidates=[];iceCandidatesComplete=!1;iceOptions;simulcastParameters=[];get msid(){return this.msids[0]}set msid(s){this.msids=s?[s]:[]}toString(){let s=[];if(s.push(`m=${this.kind} ${this.port} ${this.profile} ${this.fmt.map((n)=>n.toString()).join(" ")}`),this.host)s.push(`c=${An(this.host)}`);if(this.iceCandidates.forEach((n)=>{s.push(`a=candidate:${el(n)}`)}),this.iceCandidatesComplete)s.push("a=end-of-candidates");if(this.iceParams?.usernameFragment)s.push(`a=ice-ufrag:${this.iceParams.usernameFragment}`);if(this.iceParams?.password)s.push(`a=ice-pwd:${this.iceParams.password}`);if(this.iceParams?.iceLite)s.push("a=ice-lite");if(this.iceOptions)s.push(`a=ice-options:${this.iceOptions}`);if(this.dtlsParams)this.dtlsParams.fingerprints.forEach((n)=>{s.push(`a=fingerprint:${n.algorithm} ${n.value}`)}),s.push(`a=setup:${bn[this.dtlsParams.role]}`);if(this.direction)s.push(`a=${this.direction}`);if(this.rtp.muxId)s.push(`a=mid:${this.rtp.muxId}`);if(this.msids.forEach((n)=>s.push(`a=msid:${n}`)),this.rtcpPort&&this.rtcpHost){if(s.push(`a=rtcp:${this.rtcpPort} ${An(this.rtcpHost)}`),this.rtcpMux)s.push("a=rtcp-mux")}if(this.ssrcGroup.forEach((n)=>{s.push(`a=ssrc-group:${n.str}`)}),this.ssrc.forEach((n)=>{Nh.forEach((a)=>{let o=n[a];if(o!==void 0)s.push(`a=ssrc:${n.ssrc} ${a}:${o}`)})}),this.rtp.codecs.forEach((n)=>{if(s.push(`a=rtpmap:${n.payloadType} ${n.str}`),n.rtcpFeedback.forEach((a)=>{let o=a.type;if(a.parameter)o+=` ${a.parameter}`;s.push(`a=rtcp-fb:${n.payloadType} ${o}`)}),n.parameters)s.push(`a=fmtp:${n.payloadType} ${n.parameters}`)}),Object.keys(this.sctpMap).forEach((n)=>{let a=this.sctpMap[Number(n)];s.push(`a=sctpmap:${n} ${a}`)}),this.sctpPort)s.push(`a=sctp-port:${this.sctpPort}`);if(this.sctpCapabilities)s.push(`a=max-message-size:${this.sctpCapabilities.maxMessageSize}`);if(this.rtp.headerExtensions.forEach((n)=>s.push(`a=extmap:${n.id} ${n.uri}`)),this.simulcastParameters.length){this.simulcastParameters.forEach((c)=>{s.push(`a=rid:${c.rid} ${c.direction}`)});let n="a=simulcast:",a=this.simulcastParameters.filter((c)=>c.direction==="recv");if(a.length)n+=`recv ${a.map((c)=>c.rid).join(";")} `;let o=this.simulcastParameters.filter((c)=>c.direction==="send");if(o.length)n+=`send ${o.map((c)=>c.rid).join(";")}`;s.push(n)}return s.join(`\r
11
+ `)+`\r
12
+ `}},Ps=class{constructor(s,n){this.semantic=s,this.items=n}semantic;items;get str(){return`${this.semantic} ${this.items.join(" ")}`}};function Di(s){let n=s.match(/^IN (IP4|IP6) ([^ ]+)$/);if(!n)throw Error("exception");return n[2]}function An(s){return`IN IP${Fy(s)?4:6} ${s}`}function el(s){let n=`${s.foundation} ${s.component} ${s.protocol} ${s.priority} ${s.ip} ${s.port} typ ${s.type}`;if(s.relatedAddress!=null)n+=` raddr ${s.relatedAddress}`;if(s.relatedPort!=null)n+=` rport ${s.relatedPort}`;if(s.tcpType!=null)n+=` tcptype ${s.tcpType}`;if(s.generation!=null)n+=` generation ${s.generation}`;if(s.ufrag!=null)n+=` ufrag ${s.ufrag}`;return n}function WS(s){let n=[],a=[],o=s.split(`\r
13
+ `);if(o.length===1)o=s.split(`
14
+ `);return o.forEach((c)=>{if(c.startsWith("m="))a.push([c]);else if(a.length>0)a[a.length-1].push(c);else n.push(c)}),[n,a]}function Ui(s){if(s.includes(":")){let n=Je(s.slice(2),":");return[n[0],n[1]]}else return[s.slice(2),void 0]}function Ni(s,n,a=(o)=>o.toString()){let o=n.split(" ");if(o.length>0)s.push(new Ps(o[0],o.slice(1).map(a)))}function KS(s){let n=Me.fromSdp(s);return Rt(n)}var $S=class{sdp;type;constructor(s,n){Object.defineProperties(this,{sdp:{configurable:!0,enumerable:!0,value:s,writable:!1},type:{configurable:!0,enumerable:!0,value:n,writable:!1}})}static isThis(s){if(typeof s?.sdp==="string")return!0}toSdp(){return{sdp:this.sdp,type:this.type}}};function Tc(s,n){let o=Hy(8).readBigUInt64BE(0).toString().slice(0,8),c=0;n.origin=`- ${o} 0 IN IP4 0.0.0.0`,n.msidSemantic.push(new Ps("WMS",["*"])),n.type=s}function tt(s){let n={};return s.split(";").forEach((a)=>{if(a.length===0)return;if(a.includes("=")){let[o,c]=Je(a,"=");if(Yy.includes(o))n[o]=Number(c);else n[o]=c}else if(a.includes(":")){let[o,c]=a.split(":");n[o]=Number.isNaN(Number(c))?c:Number(c)}else n[a]=void 0}),n}var xn=class{ssrc;cname;msid;msLabel;label;constructor(s){Object.assign(this,s)}};function me(s){let n=s.toLowerCase();return n==="video/av1x"?"video/av1":n}function Hs(s){return s.name.toLowerCase()}function _r(s,n){return s==null||n==null||s===n}function bc(s){let n=tt(s.parameters??"");return{packetizationMode:n["packetization-mode"],profileLevelId:n["profile-level-id"]?.toString().toLowerCase()}}function Vn(s,n){if(me(s.mimeType)!==me(n.mimeType))return!1;if(s.clockRate!==n.clockRate)return!1;if(!_r(s.channels,n.channels))return!1;if(Hs(s)!=="h264")return!0;let a=bc(s),o=bc(n);if(!_r(a.packetizationMode,o.packetizationMode))return!1;return _r(a.profileLevelId,o.profileLevelId)}function It(s){return["rtx","red"].includes(Hs(s))}function tl(s,n,a){if(s!=="audio"||n==null||Hs(n)!=="red")return n;let[o]=Yn(n);return a.find((c)=>!It(c)&&c.payloadType===o)??a.find((c)=>!It(c))??n}function GS(s,n){return s.some((a)=>!It(a)&&n.some((o)=>me(o.mimeType)===me(a.mimeType)))}function Yn(s){let n=s.parameters??"";if(Hs(s)==="rtx"){let a=Number(tt(n).apt);return Number.isNaN(a)?[]:[a]}if(Hs(s)==="red")return n.split("/").map(Number).filter((a)=>!Number.isNaN(a));return[]}function sl(s,n){let a=new Set(n.map((c)=>c.payloadType)),o=s.filter((c)=>{if(!It(c))return!1;let d=Yn(c);return d.length>0&&d.every((h)=>a.has(h))});return s.filter((c)=>n.includes(c)||o.includes(c))}function rl(s,n){let a=s.filter((o)=>!It(o)&&n.some((c)=>Vn(c,o)));return sl(s,a)}function jS(s,n){return me(s.mimeType)===me(n.mimeType)&&_r(s.clockRate,n.clockRate)}function il(s,n){if(n==null)return s;let a=n.flatMap((u)=>{let p=s.find((f)=>jS(f,u));return p?[p]:[]}),o=[...new Set(a)],c=new Set(o.filter(It).flatMap(Yn)),d=s.filter((u)=>!It(u)&&(o.includes(u)||c.has(u.payloadType))),h=sl(s,d);return[...o.filter((u)=>h.includes(u)),...h.filter((u)=>!o.includes(u))]}function Rc(s,n,a){return il(n==null?s:rl(s,n),a)}function gs(s){return s?.map((n)=>n.mimeType).join(", ")||"(none)"}function zt(s){let{kind:n,configured:a,source:o,preferences:c}=s,d=o==null?a:rl(a,o);if(o!=null&&d.length===0)throw A("NotSupportedError",`Track codec ${gs(o)} is not supported by this RTCPeerConnection. Configured ${n} codecs: ${gs(a)}`);let h=il(d,c);if(h.length===0)throw A("NotSupportedError",`No codec remains after applying codec preferences. Source codecs: ${gs(o)} Configured codecs: ${gs(a)} Preferred codecs: ${gs(c)}`);return h}var YS=_("werift:packages/webrtc/src/media/receiver/nack.ts"),Cc=150,QS=class{constructor(s){this.receiver=s}receiver;newEstSeqNum=0;_lost={};nackLoop;onPacketLost=new E;mediaSourceSsrc;retryCount=10;closed=!1;get lostSeqNumbers(){return Object.keys(this._lost).map(Number).sort()}getLost(s){return this._lost[s]}setLost(s,n){if(this._lost[s]=n,this.nackLoop||this.closed)return;this.nackLoop=setInterval(async()=>{try{if(await this.sendNack(),!Object.keys(this._lost).length)clearInterval(this.nackLoop),this.nackLoop=void 0}catch(a){YS("failed to send nack",a)}},5)}removeLost(s){delete this._lost[s]}addPacket(s){let{sequenceNumber:n,ssrc:a}=s.header;if(this.mediaSourceSsrc=a,this.newEstSeqNum===0){this.newEstSeqNum=n;return}if(this.getLost(n)){this.removeLost(n);return}if(n===ae(this.newEstSeqNum,1))this.newEstSeqNum=n;else if(n>ae(this.newEstSeqNum,1)){for(let o=ae(this.newEstSeqNum,1);o<n;o=ae(o,1))this.setLost(o,1);this.newEstSeqNum=n,this.pruneLost()}}pruneLost(){if(this.lostSeqNumbers.length>Cc)this._lost=Object.entries(this._lost).slice(-Cc).reduce((s,[n,a])=>(s[n]=a,s),{})}close(){this.closed=!0,clearInterval(this.nackLoop),this._lost={}}updateRetryCount(){this.lostSeqNumbers.forEach((s)=>{if(this._lost[s]++>this.retryCount)return this.removeLost(s),s})}sendNack=()=>new Promise((s,n)=>{if(this.lostSeqNumbers.length>0&&this.mediaSourceSsrc){let a=new Kr({senderSsrc:this.receiver.rtcpSsrc,mediaSourceSsrc:this.mediaSourceSsrc,lost:this.lostSeqNumbers}),o=new es({feedback:a});this.receiver.dtlsTransport.sendRtcp([o]).then(s).catch(n),this.updateRetryCount(),this.onPacketLost.execute(a)}})},JS=_("werift:packages/webrtc/media/receiver/receiverTwcc"),ZS=class{constructor(s,n,a){this.dtlsTransport=s,this.rtcpSsrc=n,this.mediaSourceSsrc=a,this.runTWCC()}dtlsTransport;rtcpSsrc;mediaSourceSsrc;extensionInfo={};twccRunning=!1;fbPktCount=0;lastTimestamp;handleTWCC(s){if(this.extensionInfo[s]={tsn:s,timestamp:mS()},Object.keys(this.extensionInfo).length>10)this.sendTWCC()}async runTWCC(){while(this.twccRunning)this.sendTWCC(),await XS(100)}sendTWCC(){if(Object.keys(this.extensionInfo).length===0)return;let s=Object.values(this.extensionInfo).sort((m,y)=>m.tsn-y.tsn),n=s[0].tsn,a=s.slice(-1)[0].tsn,o=[],c=s[0].tsn,d=ae(a-n,1),h,u,p=[];for(let m=n;m<=a;m++){let y=this.extensionInfo[m]?.timestamp;if(y){if(!this.lastTimestamp)this.lastTimestamp=y;if(!h)h=this.lastTimestamp;let S=y-this.lastTimestamp;this.lastTimestamp=y;let v=new wr({delta:Number(S)});if(v.parseDelta(),p.push(v),u!=null&&u.status!==v.type)o.push(new Es({packetStatus:u.status,runLength:m-u.minTSN})),u={minTSN:m,status:v.type};if(m===a)if(u!=null)o.push(new Es({packetStatus:u.status,runLength:m-u.minTSN+1}));else o.push(new Es({packetStatus:v.type,runLength:1}));if(u==null)u={minTSN:m,status:v.type}}}if(!h)return;let f=new es({feedback:new $r({senderSsrc:this.rtcpSsrc,mediaSourceSsrc:this.mediaSourceSsrc,baseSequenceNumber:c,packetStatusCount:d,referenceTime:Du(Math.floor(Number(h/1000n/64n))),fbPktCount:this.fbPktCount,recvDeltas:p,packetChunks:o})});this.dtlsTransport.sendRtcp([f]).catch((m)=>{JS(m)}),this.extensionInfo={},this.fbPktCount=Mu(this.fbPktCount,1)}},ev=class{base_seq;max_seq;cycles=0;packets_received=0;bytesReceived=0;headerBytesReceived=0;lastPacketReceivedTimestamp;clockRate;jitter_q4=0;last_arrival;last_timestamp;expected_prior=0;received_prior=0;constructor(s){this.clockRate=s}add(s,n=Date.now()/1000){let a=this.max_seq==null||hd(s.header.sequenceNumber,this.max_seq);if(this.packets_received++,this.bytesReceived+=s.payload.length,this.headerBytesReceived+=s.header.serializeSize,this.lastPacketReceivedTimestamp=pt(),this.base_seq==null)this.base_seq=s.header.sequenceNumber;if(a){let o=Cs(n*this.clockRate);if(this.max_seq!=null&&s.header.sequenceNumber<this.max_seq)this.cycles+=65536;if(this.max_seq=s.header.sequenceNumber,s.header.timestamp!==this.last_timestamp&&this.packets_received>1){let c=Math.abs(o-(this.last_arrival??0)-(s.header.timestamp-(this.last_timestamp??0)));this.jitter_q4+=c-(this.jitter_q4+8>>4)}this.last_arrival=o,this.last_timestamp=s.header.timestamp}}get fraction_lost(){let s=this.packets_expected-this.expected_prior;this.expected_prior=this.packets_expected;let n=this.packets_received-this.received_prior;this.received_prior=this.packets_received;let a=s-n;if(s==0||a<=0)return 0;else return Math.floor((a<<8)/s)}get jitter(){return this.jitter_q4>>4}get packets_expected(){return this.cycles+(this.max_seq??0)-(this.base_seq??0)+1}get packets_lost(){let s=this.packets_expected-this.packets_received;return s<0?0:s}},gr=_("werift:packages/webrtc/src/media/rtpReceiver.ts"),Lr=class{constructor(s,n,a){this.config=s,this.kind=n,this.rtcpSsrc=a,this.defaultTrack=new rs({kind:n,remote:!0}),this.onPacketLost.subscribe((o)=>{this.nackCountBySsrc[o.mediaSourceSsrc]=(this.nackCountBySsrc[o.mediaSourceSsrc]??0)+1})}config;kind;rtcpSsrc;codecs={};defaultTrack;get codecArray(){return Object.values(this.codecs).sort((s,n)=>s.payloadType-n.payloadType)}ssrcByRtx={};stagedCodecs={};stagedSsrcByRtx={};learnedTrackSsrcs=new Set;nack=new QS(this);audioRedHandler=new Wf;type="receiver";uuid=VS().toString();tracks=[];trackBySSRC={};trackByRID={};unboundTracks=[];lastSRtimestamp={};receiveLastSRTimestamp={};onPacketLost=this.nack.onPacketLost;onRtcp=new E;dtlsTransport;sdesMid;latestRid;latestRepairedRid;receiverTWCC;stopped=!1;remoteStreamId;remoteStreamIds=[];remoteTrackId;rtcpRunning=!1;rtcpCancel=new AbortController;remoteStreams={};senderReportsReceivedBySsrc={};remoteTimestampsBySsrc={};remotePacketCountBySsrc={};remoteOctetCountBySsrc={};nackCountBySsrc={};pliCountBySsrc={};payloadTypeBySsrc={};get transport(){return this.dtlsTransport??null}setDtlsTransport(s){this.dtlsTransport=s}get track(){return this.tracks[0]??this.defaultTrack}get nackEnabled(){return this.codecArray[0]?.rtcpFeedback.find((s)=>s.type==="nack")}get twccEnabled(){return this.codecArray[0]?.rtcpFeedback.find((s)=>s.type===sc().type)}get pliEnabled(){let s=ct();return this.codecArray[0]?.rtcpFeedback.find((n)=>n.type===s.type&&n.parameter===s.parameter)}prepareReceive(s,{deferConflicts:n=!1}={}){s.codecs.forEach((a)=>{let o=this.codecs[a.payloadType];if(n&&o&&!tv(o,a))this.stagedCodecs[a.payloadType]=a;else delete this.stagedCodecs[a.payloadType],this.codecs[a.payloadType]=a}),s.encodings.forEach((a)=>{if(!a.rtx)return;let o=this.ssrcByRtx[a.rtx.ssrc];if(n&&o!==void 0&&o!==a.ssrc)this.stagedSsrcByRtx[a.rtx.ssrc]=a.ssrc;else delete this.stagedSsrcByRtx[a.rtx.ssrc],this.ssrcByRtx[a.rtx.ssrc]=a.ssrc})}discardStagedReceive(){gt(this.stagedCodecs),gt(this.stagedSsrcByRtx)}commitStagedReceive(){Object.assign(this.codecs,this.stagedCodecs),Object.assign(this.ssrcByRtx,this.stagedSsrcByRtx),gt(this.stagedCodecs),gt(this.stagedSsrcByRtx)}snapshotReceiveTables(){return{codecs:{...this.codecs},ssrcByRtx:{...this.ssrcByRtx},stagedCodecs:{...this.stagedCodecs},stagedSsrcByRtx:{...this.stagedSsrcByRtx}}}restoreReceiveTables(s){for(let[n,a]of[[this.codecs,s.codecs],[this.ssrcByRtx,s.ssrcByRtx],[this.stagedCodecs,s.stagedCodecs],[this.stagedSsrcByRtx,s.stagedSsrcByRtx]])gt(n),Object.assign(n,a)}snapshotNegotiationState(){return{receiverTWCC:this.receiverTWCC,remoteStreamIds:[...this.remoteStreamIds],remoteStreamId:this.remoteStreamId,remoteTrackId:this.remoteTrackId,tracks:[...this.tracks],trackBySSRC:{...this.trackBySSRC},trackByRID:{...this.trackByRID},unboundTracks:[...this.unboundTracks],receiveTables:this.snapshotReceiveTables()}}restoreNegotiationState(s){if(this.receiverTWCC!==s.receiverTWCC){if(this.receiverTWCC)this.receiverTWCC.twccRunning=!1;this.receiverTWCC=s.receiverTWCC}this.remoteStreamIds=s.remoteStreamIds,this.remoteStreamId=s.remoteStreamId,this.remoteTrackId=s.remoteTrackId,this.tracks.splice(0,this.tracks.length,...s.tracks);let n=Object.entries(this.trackBySSRC).filter(([a,o])=>this.learnedTrackSsrcs.has(Number(a))&&!(a in s.trackBySSRC)&&s.tracks.includes(o));Ec(this.trackBySSRC,s.trackBySSRC);for(let[a,o]of n)this.trackBySSRC[a]=o;Ec(this.trackByRID,s.trackByRID),this.unboundTracks=[...s.unboundTracks];for(let[a,o]of Object.entries(s.trackBySSRC))if(!o.rid)o.ssrc=Number(a);this.restoreReceiveTables(s.receiveTables)}resyncCodecs(s,n){this.discardStagedReceive(),gt(this.codecs),gt(this.ssrcByRtx),this.prepareReceive(s);let a=tl(this.kind,s.codecs[0],s.codecs);if(a)for(let o of this.tracks)o.codec=a;if(this.receiverTWCC=void 0,n!=null)this.setupTWCC(n)}setupTWCC(s,n=!!this.twccEnabled){if(n&&!this.receiverTWCC)this.receiverTWCC=new ZS(this.dtlsTransport,this.rtcpSsrc,s)}keepUnboundTracks(s){for(let n of s){if(n.rid||this.tracks.includes(n))continue;this.tracks.push(n),this.unboundTracks.push(n)}}releaseProvisionalSsrc(s){let n=this.trackBySSRC[s];if(!n||n.rid)return;delete this.trackBySSRC[s],this.unboundTracks.push(n)}addTrack(s){if(s.ssrc&&!s.rid&&!this.trackBySSRC[s.ssrc]&&this.unboundTracks.length>0){let a=this.unboundTracks.find((o)=>o.ssrc===s.ssrc)??this.unboundTracks[0];return this.unboundTracks=this.unboundTracks.filter((o)=>o!==a),a.ssrc=s.ssrc,a.codec=s.codec??a.codec,this.trackBySSRC[s.ssrc]=a,this.learnedTrackSsrcs.delete(s.ssrc),!1}if(this.tracks.find((a)=>{if(this.unboundTracks.includes(a))return!1;if(a.rid)return a.rid===s.rid;if(a.ssrc)return a.ssrc===s.ssrc}))return!1;if(this.tracks.push(s),s.ssrc)this.trackBySSRC[s.ssrc]=s,this.learnedTrackSsrcs.delete(s.ssrc);if(s.rid)this.trackByRID[s.rid]=s;return!0}stop(){if(this.stopped=!0,this.rtcpRunning=!1,this.rtcpCancel.abort(),this.receiverTWCC)this.receiverTWCC.twccRunning=!1;this.nack.close()}endTracks(){for(let s of[...this.tracks,this.defaultTrack])s.stop()}async runRtcp(){if(this.rtcpRunning||this.stopped)return;this.rtcpRunning=!0;try{while(this.rtcpRunning){await Oi(500+Math.random()*1000,void 0,{signal:this.rtcpCancel.signal});let s=Object.entries(this.remoteStreams).map(([a,o])=>{let c=0,d=0;if(this.lastSRtimestamp[a]){c=this.lastSRtimestamp[a];let h=ti()-this.receiveLastSRTimestamp[a];if(h>0&&h<65536)d=Cs(h*65536)}return new Nn({ssrc:Number(a),fractionLost:o.fraction_lost,packetsLost:o.packets_lost,highestSequence:o.max_seq,jitter:o.jitter,lsr:c,dlsr:d})}),n=new Ds({ssrc:this.rtcpSsrc,reports:s});try{if(this.config.debug.receiverReportDelay)await Oi(this.config.debug.receiverReportDelay);await this.dtlsTransport.sendRtcp([n])}catch(a){gr("sendRtcp failed",a),await Oi(500+Math.random()*1000)}}}catch(s){}}getInboundRtpStatsId(s){return q("inbound-rtp",s.id??s.uuid)}getRemoteOutboundRtpStatsId(s){return q("remote-outbound-rtp",s.id??s.uuid)}getStatsRootIds(s){return this.tracks.filter((n)=>!s?!0:n===s).filter((n)=>n.ssrc).map((n)=>this.getInboundRtpStatsId(n))}collectStats(s){let n=[],a=this.dtlsTransport?q("transport",this.dtlsTransport.id):void 0,o=this.codecArray[0],c=new Set;for(let d of this.tracks){if(!d.ssrc)continue;let h=this.remoteStreams[d.ssrc],u=this.remoteTimestampsBySsrc[d.ssrc]!==void 0,p=this.lastSRtimestamp[d.ssrc]!==void 0||u?this.getRemoteOutboundRtpStatsId(d):void 0,f=o&&a?Gn(a,o.payloadType,d.id??d.uuid):void 0;if(o&&a&&f&&!c.has(f)){c.add(f);let y={type:"codec",id:f,timestamp:s,payloadType:o.payloadType,transportId:a,mimeType:o.mimeType,clockRate:o.clockRate,channels:o.channels,sdpFmtpLine:o.parameters};n.push(y)}let m={type:"inbound-rtp",id:this.getInboundRtpStatsId(d),timestamp:s,ssrc:d.ssrc,kind:this.kind,transportId:a,codecId:f,mid:this.sdesMid,trackIdentifier:d.id??d.uuid,packetsReceived:h?.packets_received??0,bytesReceived:h?.bytesReceived??0,headerBytesReceived:h?.headerBytesReceived??0,packetsLost:h?.packets_lost??0,jitter:h?.clockRate?h.jitter/h.clockRate:void 0,lastPacketReceivedTimestamp:h?.lastPacketReceivedTimestamp,remoteId:p,nackCount:this.nackCountBySsrc[d.ssrc]||void 0,pliCount:this.pliCountBySsrc[d.ssrc]||void 0};if(n.push(m),p){let y={type:"remote-outbound-rtp",id:this.getRemoteOutboundRtpStatsId(d),timestamp:s,ssrc:d.ssrc,kind:this.kind,transportId:a,codecId:m.codecId,localId:m.id,remoteTimestamp:this.remoteTimestampsBySsrc[d.ssrc],reportsSent:this.senderReportsReceivedBySsrc[d.ssrc]??0,packetsSent:this.remotePacketCountBySsrc[d.ssrc],bytesSent:this.remoteOctetCountBySsrc[d.ssrc]};n.push(y)}}return n}async getStats(){let s=pt(),n=this.collectStats(s);if(this.dtlsTransport)n.push(...await this.dtlsTransport.getStats(s));return Xr(n,this.getStatsRootIds())}pliNegotiation(s){let n=this.payloadTypeBySsrc[s]??this.trackBySSRC[s]?.codec?.payloadType,a=n!=null?this.codecs[n]:void 0;return{payloadType:a?n:void 0,allowed:a?Hi(a,ct().type,ct().parameter):!!this.pliEnabled}}async sendRtcpPLI(s){if(!this.pliNegotiation(s).allowed){gr("pli not supported",{mediaSsrc:s});return}if(this.stopped)return;gr("sendRtcpPLI",{mediaSsrc:s});let n=new Ms({feedback:new Bs({senderSsrc:this.rtcpSsrc,mediaSsrc:s})});try{this.pliCountBySsrc[s]=(this.pliCountBySsrc[s]??0)+1,await this.dtlsTransport.sendRtcp([n])}catch(a){gr(a)}}handleRtcpPacket(s){switch(s.type){case ts.type:{let n=s;this.lastSRtimestamp[n.ssrc]=jh(n.senderInfo.ntpTimestamp),this.receiveLastSRTimestamp[n.ssrc]=ti(),this.senderReportsReceivedBySsrc[n.ssrc]=(this.senderReportsReceivedBySsrc[n.ssrc]??0)+1,this.remoteTimestampsBySsrc[n.ssrc]=yS(n.senderInfo.ntpTimestamp),this.remotePacketCountBySsrc[n.ssrc]=n.senderInfo.packetCount,this.remoteOctetCountBySsrc[n.ssrc]=n.senderInfo.octetCount;let a=this.trackBySSRC[s.ssrc];if(a)a.onReceiveRtcp.execute(s)}break}this.onRtcp.execute(s)}handleRtpBySsrc=(s,n)=>{let a=this.trackBySSRC[s.header.ssrc];this.handleRTP(s,n,a)};handleRtpByRid=(s,n,a)=>{let o=this.trackByRID[n];if(!this.trackBySSRC[s.header.ssrc])this.trackBySSRC[s.header.ssrc]=o,this.learnedTrackSsrcs.add(s.header.ssrc);this.handleRTP(s,a,o)};handleRTP(s,n,a){if(this.stopped)return;let o=this.codecs[s.header.payloadType];if(!o)return;if(this.remoteStreams[s.header.ssrc]=this.remoteStreams[s.header.ssrc]??new ev(o.clockRate),this.remoteStreams[s.header.ssrc].add(s),this.receiverTWCC){let h=n[J.transportWideCC];if(!h==null)throw Error("undefined");this.receiverTWCC.handleTWCC(h)}else if(Hi(o,sc().type))this.setupTWCC(s.header.ssrc,!0);let c=o;if(o.name.toLowerCase()==="rtx"){let h=this.ssrcByRtx[s.header.ssrc],u=tt(o.parameters??""),p=this.codecs[u.apt];if(s.payload.length<2)return;s=Kf(s,p.payloadType,h),a=this.trackBySSRC[h],c=p}let d;if(o.name.toLowerCase()==="red"){if(d=Vd.deSerialize(s.payload),!Object.keys(this.codecs).includes(d.header.fields[0].blockPT.toString()))return}if(this.payloadTypeBySsrc[s.header.ssrc]=c.payloadType,a?.kind==="video"&&Hi(c,"nack"))this.nack.addPacket(s);if(a)if(d){if(a.kind==="audio"){let h=this.audioRedHandler.push(d,s);for(let u of h)a.onReceiveRtp.execute(u.clone(),n)}}else a.onReceiveRtp.execute(s.clone(),n);this.runRtcp()}};function gt(s){for(let n of Object.keys(s))delete s[Number(n)]}function Ec(s,n){for(let a of Object.keys(s))delete s[a];Object.assign(s,n)}var Ic=(s)=>s.rtcpFeedback.map((n)=>`${n.type} ${n.parameter??""}`).sort().join(",");function tv(s,n){return s.mimeType.toLowerCase()===n.mimeType.toLowerCase()&&s.clockRate===n.clockRate&&(s.channels??1)===(n.channels??1)&&(s.parameters??"")===(n.parameters??"")&&Ic(s)===Ic(n)}function Hi(s,n,a){return!!s?.rtcpFeedback.some((o)=>o.type===n&&(a===void 0||o.parameter===a))}var qt=_("werift:packages/webrtc/src/media/router.ts"),kc=["compatible","strict"],sv=(s)=>s.slice(s.indexOf("\x00")+1),rv=class{ssrcTable={};ridTable={};stagedSsrc=new Map;stagedRid=new Map;provisionalSsrc=new Map;extIdUriMap={};learnedSsrcs=new Set;keyFrameRequestRouting="compatible";constructor(){}registerRtpSender(s){this.ssrcTable[s.ssrc]=s,this.learnedSsrcs.delete(s.ssrc)}commitStaged(){for(let[s,n]of this.stagedSsrc)this.ssrcTable[s]=n,this.learnedSsrcs.delete(s);for(let[s,n]of this.stagedRid)this.ridTable[s]=n;this.stagedSsrc.clear(),this.stagedRid.clear(),this.provisionalSsrc.clear()}discardProvisional(){for(let[s,n]of this.provisionalSsrc)if(this.ssrcTable[s]===n&&!this.learnedSsrcs.has(s))delete this.ssrcTable[s],n.releaseProvisionalSsrc(s);this.provisionalSsrc.clear()}snapshotStaged(){return{ssrc:[...this.stagedSsrc],rid:[...this.stagedRid],provisional:[...this.provisionalSsrc]}}restoreStaged(s){this.stagedSsrc=new Map(s.ssrc),this.stagedRid=new Map(s.rid),this.provisionalSsrc=new Map(s.provisional)}snapshotRoutes(){return{ssrcTable:{...this.ssrcTable},ridTable:{...this.ridTable},extIdUriMap:{...this.extIdUriMap},staged:this.snapshotStaged()}}restoreRoutes(s,{endpoints:n,liveSenders:a}){let o=Object.entries(this.ssrcTable).filter(([c,d])=>this.learnedSsrcs.has(Number(c))&&!(c in s.ssrcTable)&&n.has(d));this.ssrcTable={...s.ssrcTable};for(let[c,d]of o)this.ssrcTable[Number(c)]=d;for(let c of a)if(!(c.ssrc in this.ssrcTable))this.registerRtpSender(c);this.ridTable={...s.ridTable},this.extIdUriMap={...s.extIdUriMap},this.restoreStaged(s.staged)}get staged(){return this.snapshotStaged()}unregisterTransceiver(s){for(let[n,a]of this.stagedSsrc)if(a===s.receiver)this.stagedSsrc.delete(n);for(let[n,a]of this.stagedRid)if(a===s.receiver)this.stagedRid.delete(n);for(let[n,a]of Object.entries(this.ssrcTable))if(a===s.sender||a===s.receiver)delete this.ssrcTable[Number(n)];for(let[n,a]of Object.entries(this.ridTable))if(a===s.sender||a===s.receiver)delete this.ridTable[n]}registerRtpReceiver(s,n,a=!1){qt("registerRtpReceiver",n);let o=this.ssrcTable[n];if(a&&o&&o!==s){this.stagedSsrc.set(n,s);return}if(a&&!o)this.provisionalSsrc.set(n,s);if(!a)this.provisionalSsrc.delete(n);this.stagedSsrc.delete(n),this.ssrcTable[n]=s,this.learnedSsrcs.delete(n)}registerRtpReceiverBySsrc(s,n,{deferConflicts:a=!1}={}){qt("registerRtpReceiverBySsrc",n),n.encodings.filter((o)=>o.ssrc!=null).forEach((o,c)=>{if(this.registerRtpReceiver(s.receiver,o.ssrc,a),s.addTrack(new rs({ssrc:o.ssrc,kind:s.kind,id:s.sender.trackId,remote:!0,codec:tl(s.kind,n.codecs[c],n.codecs)})),o.rtx)this.registerRtpReceiver(s.receiver,o.rtx.ssrc,a)}),n.headerExtensions.forEach((o)=>{this.extIdUriMap[o.id]=o.uri})}registerRtpReceiverByRid(s,n,a,{deferConflicts:o=!1}={}){let[c]=a.codecs;qt("registerRtpReceiverByRid",n),s.addTrack(new rs({rid:n.rid,kind:s.kind,id:s.sender.trackId,remote:!0,codec:c}));let d=pc(s.mid??"",n.rid),h=this.ridTable[d];if(o&&h&&h!==s.receiver){this.stagedRid.set(d,s.receiver);return}this.stagedRid.delete(d),this.ridTable[d]=s.receiver}receiverByRid(s,n){if(typeof n==="string"){let o=this.ridTable[pc(n,s)];if(o)return o}let a=Object.keys(this.ridTable).find((o)=>sv(o)===s);return a?this.ridTable[a]:void 0}routeRtp=(s)=>{let n=Pf(s.header.extensions,this.extIdUriMap),a=this.ssrcTable[s.header.ssrc],o=n[J.sdesRTPStreamID];if(typeof o==="string"){if(a=this.receiverByRid(o,n[J.sdesMid]),!a){qt("rid receiver not found",o);return}a.latestRid=o,a.handleRtpByRid(s,o,n)}else if(a)a.handleRtpBySsrc(s,n);else if(a=Object.values(this.ridTable).filter((h)=>h instanceof Lr).find((h)=>h.trackBySSRC[s.header.ssrc]),a)qt("simulcast register receiver by ssrc",s.header.ssrc),this.ssrcTable[s.header.ssrc]=a,this.learnedSsrcs.add(s.header.ssrc),a.handleRtpBySsrc(s,n);if(!a){qt("ssrcReceiver not found");return}let c=n[J.sdesMid];if(typeof c==="string")a.sdesMid=c;let d=n[J.repairedRtpStreamId];if(typeof d==="string")a.latestRepairedRid=d};routeRtcp=(s)=>{let n=[];switch(s.type){case ts.type:s=s,n.push(this.ssrcTable[s.ssrc]);break;case Ds.type:s=s,s.reports.forEach((a)=>{n.push(this.ssrcTable[a.ssrc])});break;case Gr.type:{let a=s}break;case es.type:{let a=s;if(a.feedback)n.push(this.ssrcTable[a.feedback.mediaSourceSsrc])}break;case Ms.type:{let a=s;if(!a.feedback)break;switch(a.feedback.count){case Wr.count:{let o=a.feedback;n.push(this.ssrcTable[o.ssrcFeedbacks[0]])}break;case Bs.count:{let o=this.keyFrameRequestTarget(a.feedback.mediaSsrc);if(o)n.push(o)}break;case qr.count:{let o=a.feedback;if(o.fir.length===0){if(o.mediaSsrc)n.push(this.ssrcTable[o.mediaSsrc]);break}let c=new Map;for(let d of o.fir){let h=this.keyFrameRequestTarget(d.ssrc);if(h)c.set(h,[...c.get(h)??[],d])}c.forEach((d,h)=>{if(h instanceof Lr)h.handleRtcpPacket(s);else h.handleRtcpPacket(s,d)})}break;default:n.push(this.ssrcTable[a.feedback.mediaSsrc])}}break}n.filter((a)=>a).forEach((a)=>a.handleRtcpPacket(s))};keyFrameRequestTarget(s){let n=this.ssrcTable[s];if(n||this.keyFrameRequestRouting==="strict")return n;let a=new Set(Object.values(this.ssrcTable).filter((d)=>!(d instanceof Lr)&&!d.stopped)),o=[...a].find((d)=>d.rtxSsrc===s);if(o)return o;let c=[...a].filter((d)=>d.kind==="video");return c.length===1?c[0]:void 0}},Pc=["compatible","aggressive"],Ac=(s,n)=>s.find((a)=>me(a.mimeType)===me(n.mimeType))?n:void 0;function iv(s){for(let[n,a]of Kc([...s.codecs.audio||[],...s.codecs.video||[]])){if(a.payloadType!=null)continue;switch(a.payloadType=96+n,a.name.toLowerCase()){case"rtx":a.parameters=`apt=${a.payloadType-1}`;break;case"red":if(a.contentType==="audio"){let o=a.payloadType+1;a.parameters=`${o}/${o}`,a.payloadType=63}break}}}function nl(){return{codecs:Ny(),headerExtensions:{audio:[],video:[]},iceTransportPolicy:"all",iceLite:!1,iceServers:[{urls:"stun:stun.l.google.com:19302"}],icePortRange:void 0,iceInterfaceAddresses:void 0,iceAdditionalHostAddresses:void 0,iceUseIpv4:!0,iceUseIpv6:!0,iceUseTcp:!1,iceTcpPassive:!0,iceStunGatherTimeout:void 0,iceTurnConnectTimeout:void 0,turnTransport:void 0,turnTlsOptions:void 0,turnUdpFamily:void 0,iceFilterStunResponse:void 0,iceFilterCandidatePair:void 0,icePasswordPrefix:void 0,iceUseLinkLocalAddress:void 0,dtls:{},bundlePolicy:"max-compat",rtcpMuxPolicy:"require",iceCandidatePoolSize:0,certificates:[],debug:{},midSuffix:!1,forceTurnTCP:!1,maxMessageSize:Yt,sctp:{mtu:Yr},pendingRtp:!1,mLineReuse:"compatible",keyFrameRequestRouting:"compatible"}}var hb=nl();function nv(s){let n=Object(s??{}),a={...n};if(n.sctp!==void 0)a.sctp={...n.sctp};if(n.bundlePolicy==="balanced")a.bundlePolicy="max-compat";if("certificates"in n)if(n.certificates===void 0)a.certificates=void 0;else if(!Array.isArray(n.certificates)||n.certificates.some((o)=>o==null))throw lt("certificates must be an array of RTCCertificate");else a.certificates=[...n.certificates];if("iceCandidatePoolSize"in n)a.iceCandidatePoolSize=av(n.iceCandidatePoolSize,"iceCandidatePoolSize");return a}function av(s,n){let a=Number(s);if(!Number.isFinite(a)||!Number.isInteger(a)||a<0||a>65535)throw lt(`${n} must be an unsigned short`);return a}function ov(s,n){return s.length===n.length&&s.every((a,o)=>a===n[o])}function cv(s){return{...s,codecs:{audio:s.codecs.audio?[...s.codecs.audio]:void 0,video:s.codecs.video?[...s.codecs.video]:void 0},headerExtensions:{audio:s.headerExtensions.audio?[...s.headerExtensions.audio]:void 0,video:s.headerExtensions.video?[...s.headerExtensions.video]:void 0},iceServers:s.iceServers.map((n)=>({...n,urls:Array.isArray(n.urls)?[...n.urls]:n.urls})),icePortRange:s.icePortRange?[...s.icePortRange]:void 0,iceAdditionalHostAddresses:s.iceAdditionalHostAddresses?[...s.iceAdditionalHostAddresses]:void 0,dtls:{...s.dtls},certificates:[...s.certificates],debug:{...s.debug},sctp:{...s.sctp},pendingRtp:typeof s.pendingRtp==="object"&&s.pendingRtp!=null?{...s.pendingRtp}:s.pendingRtp}}function dv(s,n,{isReconfiguration:a,hasLocalDescription:o,hasSctpTransport:c}){let d=nv(n);if(d.rtcpMuxPolicy&&d.rtcpMuxPolicy!=="require")throw Error("rtcpMuxPolicy must be require");if(d.iceCandidatePoolSize!==void 0&&(!Number.isInteger(d.iceCandidatePoolSize)||d.iceCandidatePoolSize<0))throw Error("iceCandidatePoolSize must be a non-negative integer");if(a&&d.bundlePolicy!==void 0&&d.bundlePolicy!==s.bundlePolicy)throw Error("bundlePolicy cannot be changed");if(d.mLineReuse!==void 0&&!Pc.includes(d.mLineReuse))throw lt(`mLineReuse must be one of ${Pc.join(", ")}`);if(d.keyFrameRequestRouting!==void 0&&!kc.includes(d.keyFrameRequestRouting))throw lt(`keyFrameRequestRouting must be one of ${kc.join(", ")}`);if(a&&d.mLineReuse!==void 0&&d.mLineReuse!==s.mLineReuse)throw A("InvalidModificationError","mLineReuse cannot be changed");if(a&&d.rtcpMuxPolicy!==void 0&&d.rtcpMuxPolicy!==s.rtcpMuxPolicy)throw Error("rtcpMuxPolicy cannot be changed");if(a&&d.certificates!==void 0&&!ov(d.certificates,s.certificates))throw Error("certificates cannot be changed");if(a&&d.iceCandidatePoolSize!==void 0&&o&&d.iceCandidatePoolSize!==s.iceCandidatePoolSize)throw Error("iceCandidatePoolSize cannot be changed after setLocalDescription");if((d.iceCandidatePoolSize??0)>0)throw Error("iceCandidatePoolSize > 0 is not supported");if(d.sctp!==void 0){let h=d.sctp.mtu??Yr;if(_h(h),c&&h!==s.sctp.mtu)throw Error("sctp.mtu cannot be changed after SCTP transport creation")}if(CS(s,d),s.sctp={mtu:s.sctp?.mtu??Yr},s.icePortRange){let[h,u]=s.icePortRange;if(h===u)throw Error("should not be same value");if(h>=u)throw Error("The min must be less than max")}if(!Number.isInteger(s.maxMessageSize)||s.maxMessageSize<0)throw Error("maxMessageSize must be a non-negative integer");return iv(s),[...s.headerExtensions.audio||[],...s.headerExtensions.video||[]].forEach((h,u)=>{h.id=1+u}),d}var xc=_("werift:packages/webrtc/src/media/rtpTransceiverManager.ts");function hv(s,n){return n.rtp.codecs.filter((a)=>{let o=Ac(s,a);if(!o)return!1;if(o?.name.toLowerCase()==="rtx"){let d=tt(o.parameters??"").apt,h=n.rtp.codecs.find((u)=>u.payloadType===d);if(!h)return!1;return!!Ac(s,h)}return!0})}function lv(s){if(!s||s.length<2)return;let n=s.map((a)=>a.rid).filter((a)=>typeof a==="string"&&a.length>0);if(n.length<2)return;return n.map((a)=>({rid:a,direction:"send"}))}var uv=class{constructor(s,n,a){this.cname=s,this.config=n,this.router=a}cname;config;router;transceivers=[];notifiedRemoteTrack=new WeakMap;watched=new WeakSet;getNotifiedRemoteTrack(s){let n=this.notifiedRemoteTrack.get(s);return n&&{track:n.track,streams:[...n.streams]}}restoreNotifiedRemoteTrack(s,n){if(n)this.notifiedRemoteTrack.set(s,n);else this.notifiedRemoteTrack.delete(s)}snapshotNegotiationState(){return{order:[...this.transceivers],states:new Map(this.transceivers.map((s)=>[s,{transceiver:s.snapshotNegotiationState(),notifiedRemoteTrack:this.getNotifiedRemoteTrack(s)}]))}}restoreNegotiationState(s,n,a=()=>{return},o=new Set,c=new Set){for(let[u,p]of s.states){let{firedReceiving:f}=u.snapshotNegotiationState(),m=[...u.receiver.tracks];if(u.restoreNegotiationState(p.transceiver),c.has(u)){u.receiver.keepUnboundTracks(m),u.firedReceiving=f;continue}this.restoreNotifiedRemoteTrack(u,p.notifiedRemoteTrack)}let d=[];for(let u of n){if(o.has(u)){let p=[...u.receiver.tracks],f=a(u);if(f)u.restoreNegotiationState(f);u.receiver.keepUnboundTracks(p);continue}if(u.heldByApplication){let p=a(u);if(p)u.restoreNegotiationState(p);this.notifiedRemoteTrack.delete(u),u.mid=null,u.mLineIndex=void 0;continue}d.push(u.dtlsTransport),this.removeRemoteTransceiver(u)}let h=new Set([...s.states.values()].map(({transceiver:u})=>u.mLineIndex));for(let u of this.transceivers){if(s.states.has(u))continue;if(!u.stopped){let p=u.createdNegotiationState;if(p){let f=[...u.receiver.tracks],{firedReceiving:m}=u.snapshotNegotiationState();u.restoreNegotiationState({...p,firedReceiving:m}),u.receiver.keepUnboundTracks(f)}u.mid=null,u.mLineIndex=void 0,u.setCurrentDirection(void 0);continue}if(u.mLineIndex!=null&&h.has(u.mLineIndex))u.mLineIndex=void 0}return this.restoreTransceiverOrder(s.order),d}revertUnappliedAssociations(s){for(let[n,{transceiver:a}]of s.states){if(n.currentDirection||n.stopped)continue;n.mid=a.mid,n.mLineIndex=a.mLineIndex}}onTransceiverAdded=new E;onRemoteTransceiverAdded=new E;onTrack=new E;onNegotiationNeeded=new E;getTransceivers(){return this.transceivers}getSenders(){return this.getTransceivers().map((s)=>s.sender)}getReceivers(){return this.getTransceivers().map((s)=>s.receiver)}getTransceiverByMLineIndex(s){return this.transceivers.find((n)=>n.mLineIndex===s&&!n.stopped)??this.transceivers.find((n)=>n.mLineIndex===s)}restoreTransceiverOrder(s){let n=this.transceivers.filter((a)=>!s.includes(a));this.transceivers.splice(0,this.transceivers.length,...s,...n),s.forEach((a)=>this.watchTransceiver(a))}pushTransceiver(s){this.watchTransceiver(s),this.transceivers.push(s)}removeRemoteTransceiver(s){let n=this.transceivers.indexOf(s);if(n<0)return;s.forceStop(),s.mid=null,s.mLineIndex=void 0,this.transceivers.splice(n,1)}replaceTransceiver(s,n){this.watchTransceiver(s),this.transceivers[n]=s}unwatchTransceiver(s){this.watched.delete(s),s.onRelease.allUnsubscribe(),s.onStopRequested.allUnsubscribe()}watchTransceiver(s){if(this.watched.has(s))return;this.watched.add(s),s.onRelease.subscribe(()=>{this.router.unregisterTransceiver(s)}),s.onStopRequested.subscribe(()=>{if(!s.stopped)this.onNegotiationNeeded.execute()})}findReusableTransceiver(s){return this.transceivers.find((n)=>n.stopped&&n.kind===s&&n.mLineIndex!=null&&!this.transceivers.some((a)=>a!==n&&a.mLineIndex===n.mLineIndex))}takeOverMLine(s,n){let a=this.transceivers.indexOf(s);n.mLineIndex=s.mLineIndex,s.mid=null,s.mLineIndex=void 0,this.unwatchTransceiver(s),this.replaceTransceiver(n,a)}associateMLine(s,n){let a=this.transceivers.find((o)=>o!==s&&o.stopped&&o.mLineIndex===n);if(!a)return;this.transceivers.splice(this.transceivers.indexOf(s),1),this.takeOverMLine(a,s)}releaseUnassociatedReservations(s,n){for(let a of this.transceivers)if(!s.has(a)&&a.mid==null&&a.mLineIndex!=null&&a.mLineIndex<n)a.mLineIndex=void 0}addTransceiver(s,n,a={},{remoteMLineIndex:o}={}){let c=typeof s==="string"?s:s.kind,d=a.direction||"sendrecv";if(typeof s!=="string")Os(s),zt({kind:c,configured:this.filterCodecsByDirection(c,d),source:Tt(s),preferences:void 0});let h=new Tv(s,{pendingRtp:this.config.pendingRtp}),u=new Lr(this.config,c,h.ssrc),p=new iS(c,n,u,h,d);p.onCodecPreferencesChanged.subscribe(()=>{this.onNegotiationNeeded.execute()}),p.options={...a,simulcast:a.simulcast??lv(a.sendEncodings)},p.sender.setStreams(a.streams??[]),p.sender.setSendEncodings((a.sendEncodings??[]).map((m)=>({...m}))),this.router.registerRtpSender(p.sender),p.createdNegotiationState=p.snapshotNegotiationState();let f=o==null?this.findReusableTransceiver(c):this.transceivers.find((m)=>m.stopped&&m.mLineIndex===o);if(f)this.takeOverMLine(f,p);else this.pushTransceiver(p);return this.onTransceiverAdded.execute(p),p}addTrack(s,n=[]){if(this.getSenders().find((d)=>d.track?.uuid===s.uuid))throw A("InvalidAccessError","Track already added");let a=(d)=>d.sender.track==null&&d.kind===s.kind&&!d.usedForSender&&!d.stopping&&!d.stopped&&!d.rejected&&!d.pendingRejection,o=this.transceivers.find((d)=>a(d)&&Qt.includes(d.direction));if(o){this.validateTrackForTransceiver(s,o);let d=o.sender;return d.setStreams(n),d.registerTrack(s),o.options={...o.options,streams:n},o.markCodecsForResolution(),o}let c=this.transceivers.find((d)=>a(d)&&!Qt.includes(d.direction));if(c){let d=c.direction==="recvonly"?"sendrecv":c.direction==="inactive"?"sendonly":c.direction;this.validateTrackForTransceiver(s,c,d);let h=c.sender;switch(h.setStreams(n),h.registerTrack(s),c.options={...c.options,streams:n},c.direction){case"recvonly":c.setDirection("sendrecv");break;case"inactive":c.setDirection("sendonly");break}return c.markCodecsForResolution(),c}else return this.addTransceiver(s,void 0,{direction:"sendrecv",streams:n})}removeTrack(s){if(!this.getSenders().find(({ssrc:a})=>s.ssrc===a))throw A("InvalidAccessError","Sender does not exist");let n=this.transceivers.find(({sender:{ssrc:a}})=>s.ssrc===a);if(!n)throw Error("No matching transceiver found");if(n.stopping||n.stopped)return!1;if(s.track==null)return!1;if(s.detachTrack(),n.direction==="sendrecv")n.setDirection("recvonly");else if(n.direction==="sendonly")n.setDirection("inactive");return!0}assignTransceiverCodecs(s){let n=this.filterCodecsByDirection(s.kind,s.direction);s.codecs=zt({kind:s.kind,configured:n,source:Tt(s.sender.track),preferences:s.codecPreferences}),s.codecPreferencesNeedResolution=!1}filterCodecsByDirection(s,n){return this.config.codecs[s].filter((a)=>{switch(a.direction){case"recvonly":{if(Qy.includes(n))return!0;return!1}case"sendonly":{if(Qt.includes(n))return!0;return!1}case"sendrecv":{if([zh,Fh,Hh].includes(n))return!0;return!1}case"all":return!0;default:return!1}})}validateTrackForTransceiver(s,n,a=n.direction){Os(s),zt({kind:s.kind,configured:this.filterCodecsByDirection(s.kind,a),source:Tt(s),preferences:n.codecPreferences})}getLocalRtpParams(s){if(s.mid==null)throw Error("mid not assigned");return{codecs:s.codecs,muxId:s.mid,headerExtensions:s.headerExtensions,rtcp:{cname:this.cname,ssrc:s.sender.ssrc,mux:!0}}}getRemoteRtpParams(s,n){return{muxId:s.rtp.muxId,rtcp:s.rtp.rtcp,codecs:n.codecs,headerExtensions:n.headerExtensions,encodings:Object.values([...n.codecs].sort((o,c)=>Number(o.name.toLowerCase()==="rtx")-Number(c.name.toLowerCase()==="rtx")).reduce((o,c)=>{if(c.name.toLowerCase()==="rtx"){let d=tt(c.parameters??""),h=o[d.apt];if(h&&s.ssrc.length===2)h.rtx=new Ly({ssrc:s.ssrc[1].ssrc});return o}return o[c.payloadType]=new By({ssrc:s.ssrc[0]?.ssrc,payloadType:c.payloadType}),o},{}))}}resolveRemoteCodecSet(s,n,a,o){let c=(f)=>f.name.toLowerCase(),d=(f)=>(f.parameters??"").split("/").map(Number).filter((m)=>!Number.isNaN(m)),h=new Map,u=new Set;for(let f of s){if(["red","rtx"].includes(c(f)))continue;let m=n.rtp.codecs.find((y)=>!u.has(y)&&me(y.mimeType)===me(f.mimeType)&&(o==null||o.some((S)=>Vn(S,y))));if(m)h.set(f,m),u.add(m)}let p=s.flatMap((f)=>{if(c(f)==="red"){let g=d(f).flatMap((T)=>{let b=s.find((P)=>P.payloadType===T),C=b?h.get(b):void 0;return C?[C.payloadType]:[]}),w=n.rtp.codecs.find((T)=>{if(c(T)!=="red"||u.has(T))return!1;let b=d(T);return b.length===g.length&&b.every((C,P)=>C===g[P])});if(!w)return[];return u.add(w),[w]}if(c(f)!=="rtx"){let g=h.get(f);return g?[g]:[]}let m=tt(f.parameters??"").apt,y=s.find((g)=>g.payloadType===m);if(!y)return[];let S=h.get(y);if(!S)return[];let v=n.rtp.codecs.find((g)=>{if(c(g)!=="rtx"||u.has(g))return!1;return tt(g.parameters??"").apt===S.payloadType});if(!v)return[];return u.add(v),[v]});if(a==="remote"){let f=new Map(n.rtp.codecs.map((m,y)=>[m,y]));p.sort((m,y)=>f.get(m)-f.get(y))}if(p.length===0)throw A("NotSupportedError","No compatible codec remains after remote negotiation.");return p}refreshAnswerCodecs(s,n){let a=this.config.codecs[n.kind]||[],o=Tt(s.sender.track);zt({kind:n.kind,configured:a,source:o,preferences:s.codecPreferences});let c=Rc(a,o,s.codecPreferences);s.codecs=this.resolveRemoteCodecSet(c,n,"local",o),s.sender.proposeSend(s.codecs),xc("negotiated codecs",s.codecs)}commitAnswerCodecs(s,n){if(s.sender.prepareSend(this.getLocalRtpParams(s)),["recvonly","sendrecv"].includes(s.direction)){let a=this.getRemoteRtpParams(n,s);for(let o of n.simulcastParameters)this.router.registerRtpReceiverByRid(s,o,a);s.receiver.resyncCodecs(a,n.ssrc[0]?.ssrc),this.router.registerRtpReceiverBySsrc(s,a)}s.codecPreferencesNeedResolution=!1}planRemoteRtpCodecs(s,n){let a=new Map,o=s.type==="offer";for(let[c,d]of s.media.entries()){if(!["audio","video"].includes(d.kind))continue;let h=n(d,c);if(d.port===0||h?.stopped||h?.stopping){a.set(c,[]);continue}let u=Tt(h?.sender.track),p=this.config.codecs[d.kind]||[],f=o?p:h?.pendingLocalOfferCodecs||[];if(!GS(f,d.rtp.codecs)){a.set(c,[]);continue}if(o)zt({kind:d.kind,configured:p,source:u,preferences:h?.codecPreferences});let m=this.resolveRemoteCodecSet(o?Rc(p,u,h?.codecPreferences):f,d,o?"local":"remote",u);if(u!=null)zt({kind:d.kind,configured:m,source:u,preferences:void 0});a.set(c,m)}return a}setRemoteRTP(s,n,a,o,c){if(!s.mid)s.mid=n.rtp.muxId??null;if(s.mLineIndex=o,a==="answer")s.pendingLocalOfferCodecs=void 0;if(s.stopped)return!1;if(s.stopping){if(a==="answer"&&n.port===0)s.commitStopped({rejected:!1});return!1}if(xc("negotiated codecs",c),n.port===0||c.length===0){if(a==="answer")s.commitStopped({rejected:!0});else s.pendingRejection=!0;return!1}s.pendingRejection=!1,s.codecs=c,s.headerExtensions=n.rtp.headerExtensions.filter((p)=>(this.config.headerExtensions[n.kind]||[]).find((f)=>f.uri===p.uri));let d=n.direction??"inactive",h=pS(d);if(["answer","pranswer"].includes(a))s.setCurrentDirection(h);else s.offerDirection=h;let u=this.getLocalRtpParams(s);if(a!=="offer"||!s.currentDirection)s.sender.prepareSend(u);else s.sender.proposeSend(u.codecs);if(["recvonly","sendrecv"].includes(s.direction)){let p=this.getRemoteRtpParams(n,s),f={deferConflicts:a!=="answer"};for(let m of n.simulcastParameters)this.router.registerRtpReceiverByRid(s,m,p,f);if(a==="answer")s.receiver.resyncCodecs(p,n.ssrc[0]?.ssrc);else s.receiver.prepareReceive(p,f);this.router.registerRtpReceiverBySsrc(s,p,f)}if(["sendonly","sendrecv"].includes(d)){let p=[...new Set(n.msids.map((S)=>S.split(" ")[0]))],f=n.msids[0]?.split(" ")[1];s.receiver.remoteStreamId=p[0],s.receiver.remoteStreamIds=p,s.receiver.remoteTrackId=f;let m=s.receiver.track,y=this.notifiedRemoteTrack.get(s);if(y?.track!==m||y.streams.join("\x00")!==p.join("\x00"))this.notifiedRemoteTrack.set(s,{track:m,streams:p}),this.onTrack.execute({track:m,transceiver:s,streams:p.map((S)=>new dS({id:S,tracks:[m]}))});s.firedReceiving=!0}else this.notifiedRemoteTrack.delete(s),s.firedReceiving=!1;if((a==="answer"||!s.currentDirection)&&n.ssrc[0]?.ssrc)s.receiver.setupTWCC(n.ssrc[0].ssrc);return!0}commitRemoteOffer(){for(let s of this.transceivers)if(s.pendingRejection)s.commitStopped({rejected:!0})}settleStoppingTransceivers(s){for(let n of this.transceivers){if(!n.stopping||n.stopped)continue;if(n.mid==null||!s.has(n.mid))n.commitStopped({rejected:!1})}return this.transceivers.some((n)=>n.stopping&&!n.stopped)}collectStats(s){let n=[];for(let a of this.transceivers){if(a.sender)n.push(...a.sender.collectStats(s));if(a.receiver)n.push(...a.receiver.collectStats(s));let o=a.collectCodecStats(s);if(o)n.push(...o)}return n}getStatsRootIds(s){if(!s)return[];let n=[];for(let a of this.transceivers){if(a.sender.track===s)n.push(...a.sender.getStatsRootIds());if(a.receiver.tracks.includes(s))n.push(...a.receiver.getStatsRootIds(s))}return n}close(){for(let s of this.transceivers)s.forceStop(),this.unwatchTransceiver(s);this.onTransceiverAdded.allUnsubscribe(),this.onRemoteTransceiverAdded.allUnsubscribe(),this.onTrack.allUnsubscribe(),this.onNegotiationNeeded.allUnsubscribe()}};var fv=class{numPackets=0;totalSize=0;firstPacketSentAtMs=0;lastPacketSentAtMs=0;firstPacketReceivedAtMs=0;lastPacketReceivedAtMs=0;addPacket(s,n,a){if(this.numPackets===0)this.firstPacketSentAtMs=n,this.firstPacketReceivedAtMs=a,this.lastPacketSentAtMs=n,this.lastPacketReceivedAtMs=a;else{if(n<this.firstPacketSentAtMs)this.firstPacketSentAtMs=n;if(a<this.firstPacketReceivedAtMs)this.firstPacketReceivedAtMs=a;if(n>this.lastPacketSentAtMs)this.lastPacketSentAtMs=n;if(a>this.lastPacketReceivedAtMs)this.lastPacketReceivedAtMs=a}this.numPackets++,this.totalSize+=s}reset(){this.numPackets=0,this.totalSize=0,this.firstPacketSentAtMs=0,this.lastPacketSentAtMs=0,this.firstPacketReceivedAtMs=0,this.lastPacketReceivedAtMs=0}get receiveBitrate(){let s=this.lastPacketReceivedAtMs-this.firstPacketReceivedAtMs,n=this.totalSize/s*8*1000;return zr(n)}get sendBitrate(){let s=this.lastPacketSentAtMs-this.firstPacketSentAtMs,n=this.totalSize/s*8*1000;return zr(n)}},Wt=20,mv=10,gv=5000,yv=32768,Sv=class{congestion=!1;onAvailableBitrate=new E;onCongestion=new E;onCongestionScore=new E;congestionCounter=0;cumulativeResult=new fv;sentInfos=new Map;_congestionScore=1;get congestionScore(){return this._congestionScore}set congestionScore(s){this._congestionScore=s,this.onCongestionScore.execute(s)}_availableBitrate=0;get availableBitrate(){return this._availableBitrate}set availableBitrate(s){this._availableBitrate=s,this.onAvailableBitrate.execute(s)}constructor(){}receiveTWCC(s){let a=Gh()-this.cumulativeResult.firstPacketSentAtMs;if(a>1000){if(this.cumulativeResult.reset(),this.congestionCounter<Wt)this.congestionCounter++;else if(this.congestionScore<mv)this.congestionScore++;if(this.congestionCounter>=Wt&&!this.congestion)this.congestion=!0,this.onCongestion.execute(this.congestion)}for(let o of s.packetResults){if(!o.received)continue;let c=o.sequenceNumber,d=this.sentInfos.get(c);if(!d)continue;if(!o.receivedAtMs)continue;this.cumulativeResult.addPacket(d.size,d.sendingAtMs,o.receivedAtMs)}if(a>=100&&this.cumulativeResult.numPackets>=20){if(this.availableBitrate=Math.min(this.cumulativeResult.sendBitrate,this.cumulativeResult.receiveBitrate),this.cumulativeResult.reset(),this.congestionCounter>-Wt){let o=zr(Wt/2)+1,c=zr(Wt/4)+1,d=o-(o-c)/10*this.congestionScore;this.congestionCounter=this.congestionCounter-d}if(this.congestionCounter<=-Wt){if(this.congestionScore>1)this.congestionScore--,this.onCongestion.execute(!1);this.congestionCounter=0}if(this.congestionCounter<=0&&this.congestion)this.congestion=!1,this.onCongestion.execute(this.congestion)}}rtpPacketSent(s){this.sentInfos.delete(s.wideSeq),this.sentInfos.set(s.wideSeq,s);for(let[n,a]of this.sentInfos){if(this.sentInfos.size<=yv&&s.sentAtMs-a.sentAtMs<=gv)break;this.sentInfos.delete(n)}}},Fi=_("werift:packages/webrtc/src/media/rtpSender.ts"),Bc=128,zi=256,Mc=0.85;function vv(s){if(s===!0)return{enabled:!0,maxLength:zi};if(s==null||s===!1)return{enabled:!1,maxLength:zi};let n=typeof s.maxLength==="number"&&Number.isFinite(s.maxLength)&&s.maxLength>=1?Math.floor(s.maxLength):zi;return{enabled:s.enabled??!0,maxLength:n}}function wv(s,n,a,o,c){return{seqOffset:ae(ae(s,1),-a),timestampOffset:Xt(Xt(n,c),-o)}}var Tv=class{constructor(s,n={}){this.trackOrKind=s;let a=vv(n.pendingRtp);if(this.pendingRtpEnabled=a.enabled,this.pendingRtpMaxLength=a.maxLength,this.kind=typeof this.trackOrKind==="string"?this.trackOrKind:this.trackOrKind.kind,typeof s!=="string")this.registerTrack(s)}trackOrKind;type="sender";kind;ssrc=_c(4).readUInt32BE(0);rtxSsrc=_c(4).readUInt32BE(0);trackId=pv().toString();onReady=new E;onRtcp=new E;onPictureLossIndication=new E;onGenericNack=new E;onFullIntraRequest=new E;onKeyFrameRequest=new E;senderBWE=new Sv;cname;mid;rtpStreamId;repairedRtpStreamId;rtxPayloadType;rtxSequenceNumber=pu();redRedundantPayloadType;_redDistance=2;redEncoder=new zf(this._redDistance);headerExtensions=[];disposeTrack;sendEncodings=[{}];lastSRtimestamp;lastSentSRTimestamp;ntpTimestamp=0n;rtpTimestamp=0;octetCount=0;packetCount=0;headerBytesSent=0;rtt;totalRoundTripTime=0;roundTripTimeMeasurements=0;retransmittedPacketsSent=0;retransmittedBytesSent=0;nackCount=0;pliCount=0;firCount=0;lastFirSequenceNumbers=new Map;remotePacketsLost;remoteFractionLost;receiverEstimatedMaxBitrate=0n;sequenceNumber;timestamp;timestampOffset=0;seqOffset=0;rtpContinuityPending=!1;pendingTimestampStep=1;rtpCache=[];pendingRtp=[];drainingPendingRtp=!1;pendingRtpEnabled;pendingRtpMaxLength;codec;negotiatedCodecs=[];sendPrimaryCodec;proposedPrimaryCodec;dtlsTransport;dtlsDisposer=[];track=null;streamIds=[];stopped=!1;rtcpRunning=!1;rtcpCancel=new AbortController;get transport(){return this.dtlsTransport??null}get streamId(){return this.streamIds[0]}set streamId(s){this.streamIds=s?[s]:[]}setDtlsTransport(s){if(this.dtlsTransport)this.dtlsDisposer.forEach((n)=>n());if(this.dtlsTransport=s,this.stopped){this.dtlsDisposer=[];return}this.dtlsDisposer=[this.dtlsTransport.onStateChange.subscribe((n)=>{if(n==="connected")this.onReady.execute(),this.drainPendingRtp()}).unSubscribe]}get redDistance(){return this._redDistance}set redDistance(s){this._redDistance=s,this.redEncoder.distance=s}snapshotSendParams(){return{cname:this.cname,mid:this.mid,headerExtensions:[...this.headerExtensions],rtpStreamId:this.rtpStreamId,repairedRtpStreamId:this.repairedRtpStreamId,codec:this.codec,negotiatedCodecs:[...this.negotiatedCodecs],sendPrimaryCodec:this.sendPrimaryCodec,proposedPrimaryCodec:this.proposedPrimaryCodec,track:this.track,trackCodec:this.track?.codec,rtxPayloadType:this.rtxPayloadType,redRedundantPayloadType:this.redRedundantPayloadType}}proposeSend(s){this.proposedPrimaryCodec=Dc(s)}restoreSendParams(s){if(this.cname=s.cname,this.mid=s.mid,this.headerExtensions=[...s.headerExtensions],this.rtpStreamId=s.rtpStreamId,this.repairedRtpStreamId=s.repairedRtpStreamId,this.codec=s.codec,this.negotiatedCodecs=[...s.negotiatedCodecs],this.sendPrimaryCodec=s.sendPrimaryCodec,this.proposedPrimaryCodec=s.proposedPrimaryCodec,this.track)this.track.codec=this.track===s.track?s.trackCodec:this.codec;this.rtxPayloadType=s.rtxPayloadType,this.redRedundantPayloadType=s.redRedundantPayloadType}prepareSend(s){if(this.cname=s.rtcp?.cname,this.mid=s.muxId,this.headerExtensions=s.headerExtensions,this.rtpStreamId=s.rtpStreamId??this.rtpStreamId,this.repairedRtpStreamId=s.repairedRtpStreamId,this.negotiatedCodecs=[...s.codecs],this.proposedPrimaryCodec=void 0,this.codec=al(s.codecs),this.sendPrimaryCodec=Dc(s.codecs),this.track)this.track.codec=this.codec;if(this.rtxPayloadType=void 0,this.redRedundantPayloadType=void 0,s.codecs.forEach((n)=>{let a=tt(n.parameters??"");if(n.name.toLowerCase()==="rtx"&&this.sendPrimaryCodec?.payloadType===a.apt)this.rtxPayloadType=n.payloadType}),this.codec?.name.toLowerCase()==="red"&&this.sendPrimaryCodec!=null)this.redRedundantPayloadType=this.sendPrimaryCodec.payloadType;this.drainPendingRtp()}sendSuppressed=!1;setSendSuppressed(s){if(this.sendSuppressed===s)return;if(this.sendSuppressed=s,s)this.discardPendingRtp();else this.drainPendingRtp()}canSendRtp(){return!this.stopped&&!this.sendSuppressed&&this.dtlsTransport?.state==="connected"&&!!this.codec}settlePendingRtp(s,n){if(n==null){s.resolve();return}s.reject(n)}discardPendingRtp(){let s=this.pendingRtp.splice(0);for(let n of s)this.settlePendingRtp(n)}enqueuePendingRtp(s,n,a){let o=Buffer.isBuffer(s)?fe.deSerialize(s):s.clone();this.pendingRtp.push({packet:o,resolve:n,reject:a});while(this.pendingRtp.length>this.pendingRtpMaxLength){let c=this.pendingRtp.shift();if(c)this.settlePendingRtp(c)}}async drainPendingRtp(){if(this.drainingPendingRtp)return;this.drainingPendingRtp=!0;try{while(this.pendingRtp.length>0&&this.canSendRtp()){let s=this.pendingRtp.shift();if(!this.canSendRtp()){this.settlePendingRtp(s);continue}try{await this.dispatchRtp(s.packet),this.settlePendingRtp(s)}catch(n){this.settlePendingRtp(s,n)}}}finally{this.drainingPendingRtp=!1}if(this.pendingRtp.length>0&&this.canSendRtp())await this.drainPendingRtp()}registerTrack(s){if(s.stopped)throw Error("track is ended");if(Os(s),this.disposeTrack)this.disposeTrack();s.id=this.trackId;let{unSubscribe:n}=s.onReceiveRtp.subscribe(async(o)=>{await this.sendRtp(o)}),{unSubscribe:a}=s.onSourceChanged.subscribe((o)=>{this.replaceRTP(o)});if(this.track=s,this.disposeTrack=()=>{n(),a()},this.codec)s.codec=this.codec}setStreams(s=[]){this.streamIds=[...new Set(s.map((n)=>n.id))]}setSendEncodings(s=[]){this.sendEncodings=s.length>0?s.map((a)=>({...a})):[{}];let n=this.sendEncodings.find((a)=>typeof a.rid==="string")?.rid;if(typeof n==="string")this.rtpStreamId=n}async replaceTrack(s){if(s===null){this.detachTrack();return}if(s.stopped)throw Error("track is ended");Os(s);let n=Tt(s),a=[this.sendPrimaryCodec,this.proposedPrimaryCodec].find((o)=>o!=null&&n!=null&&!n.some((c)=>Vn(c,o)));if(a)throw A("InvalidModificationError",`Track codec ${n.map((o)=>o.mimeType).join(", ")} is incompatible with negotiated codec ${a.mimeType}`);if(this.sequenceNumber!=null)this.scheduleRtpContinuity();this.registerTrack(s),Fi("replaceTrack","ssrc",s.ssrc,"rid",s.rid)}detachTrack(){if(this.rtpContinuityPending=!1,this.discardPendingRtp(),this.disposeTrack)this.disposeTrack(),this.disposeTrack=void 0;this.track=null}stop({keepTrack:s=!1}={}){this.stopped=!0;for(let n of this.dtlsDisposer)n();if(this.dtlsDisposer=[],this.rtpContinuityPending=!1,this.discardPendingRtp(),this.rtcpRunning=!1,this.rtcpCancel.abort(),this.disposeTrack)this.disposeTrack(),this.disposeTrack=void 0;if(!s)this.track=null}async runRtcp(){if(this.rtcpRunning||this.stopped)return;this.rtcpRunning=!0;try{while(this.rtcpRunning){await Lc(500+Math.random()*1000,void 0,{signal:this.rtcpCancel.signal});let s=[new ts({ssrc:this.ssrc,senderInfo:new jd({ntpTimestamp:this.ntpTimestamp,rtpTimestamp:this.rtpTimestamp,packetCount:this.packetCount,octetCount:this.octetCount})})];if(this.lastSRtimestamp=jh(this.ntpTimestamp),this.lastSentSRTimestamp=ti(),this.cname)s.push(new Gr({chunks:[new $d({source:this.ssrc,items:[new Gd({type:1,text:this.cname})]})]}));try{await this.dtlsTransport.sendRtcp(s)}catch(n){Fi("sendRtcp failed",n),await Lc(500+Math.random()*1000)}}}catch(s){}}async sendRtp(s){if(this.stopped||this.sendSuppressed)return;if(!this.pendingRtpEnabled){if(!this.canSendRtp())return;await this.dispatchRtp(s);return}await new Promise((n,a)=>{this.enqueuePendingRtp(s,n,a),this.drainPendingRtp()})}replaceRTP(s,n=!1,a=1){this.scheduleRtpContinuity(a),Fi("replaceRTP",this.sequenceNumber,s.sequenceNumber,n,a)}scheduleRtpContinuity(s=1){this.rtpContinuityPending=!0,this.pendingTimestampStep=s,this.rtpCache=[]}async dispatchRtp(s){if(!this.canSendRtp())return;let n=this.codec;if(!n)return;s=Buffer.isBuffer(s)?fe.deSerialize(s):s.clone();let{header:a,payload:o}=s,{sequenceNumber:c,timestamp:d}=a;if(this.rtpContinuityPending){if(this.sequenceNumber!=null&&this.timestamp!=null){let S=wv(this.sequenceNumber,this.timestamp,c,d,this.pendingTimestampStep);this.seqOffset=S.seqOffset,this.timestampOffset=S.timestampOffset}this.rtpContinuityPending=!1,this.pendingTimestampStep=1}a.ssrc=this.ssrc,a.payloadType=n.payloadType,a.timestamp=Xt(a.timestamp,this.timestampOffset),a.sequenceNumber=ae(a.sequenceNumber,this.seqOffset),this.timestamp=a.timestamp,this.sequenceNumber=a.sequenceNumber;let h=gS(),u=[...a.extensions];a.extensions=this.headerExtensions.map((S)=>{let v=(()=>{switch(S.uri){case J.sdesMid:if(this.mid)return Af(this.mid);return;case J.sdesRTPStreamID:if(this.rtpStreamId)return xf(this.rtpStreamId);return;case J.repairedRtpStreamId:if(this.repairedRtpStreamId)return Lf(this.repairedRtpStreamId);return;case J.transportWideCC:return this.dtlsTransport.transportSequenceNumber=ae(this.dtlsTransport.transportSequenceNumber,1),Bf(this.dtlsTransport.transportSequenceNumber);case J.absSendTime:return Mf(h)}})();if(v)return{id:S.id,payload:v}}).filter((S)=>S);for(let S of u){let v=a.extensions.find((g)=>g.id===S.id);if(v)v.payload=S.payload;else a.extensions.push(S)}a.extensions=a.extensions.sort((S,v)=>S.id-v.id),this.ntpTimestamp=h,this.rtpTimestamp=a.timestamp,this.octetCount+=o.length,this.headerBytesSent+=a.serializeSize,this.packetCount=Xt(this.packetCount,1),this.rtpCache[a.sequenceNumber%Bc]=s;let p=o;if(this.redRedundantPayloadType)this.redEncoder.push({block:p,timestamp:a.timestamp,blockPT:this.redRedundantPayloadType}),p=this.redEncoder.build().serialize();let f=await this.dtlsTransport.sendRtp(p,a);this.runRtcp();let m=Gh(),y={wideSeq:this.dtlsTransport.transportSequenceNumber,size:f,sendingAtMs:m,sentAtMs:m};this.senderBWE.rtpPacketSent(y)}handleRtcpPacket(s,n){switch(s.type){case ts.type:case Ds.type:s.reports.filter((o)=>o.ssrc===this.ssrc).forEach((o)=>{if(this.remotePacketsLost=o.packetsLost,this.remoteFractionLost=o.fractionLost/256,this.lastSRtimestamp===o.lsr&&o.dlsr){if(this.lastSentSRTimestamp){let c=ti()-this.lastSentSRTimestamp-o.dlsr/65536;if(this.totalRoundTripTime+=c,this.roundTripTimeMeasurements++,this.rtt===void 0)this.rtt=c;else this.rtt=Mc*this.rtt+(1-Mc)*c}}});break;case es.type:{let a=s;switch(a.feedback.count){case $r.count:{let o=a.feedback;this.senderBWE.receiveTWCC(o)}break;case Kr.count:{let o=a.feedback;this.nackCount++,o.lost.forEach(async(c)=>{let d=this.rtpCache[c%Bc];if(d&&d.header.sequenceNumber!==c)d=void 0;if(d){if(this.rtxPayloadType!=null)d=$f(d,this.rtxPayloadType,this.rtxSequenceNumber,this.rtxSsrc),this.rtxSequenceNumber=ae(this.rtxSequenceNumber,1);this.retransmittedPacketsSent++,this.retransmittedBytesSent+=d.payload.length,this.headerBytesSent+=d.header.serializeSize,await this.dtlsTransport.sendRtp(d.payload,d.header)}}),this.onGenericNack.execute(o)}break}}break;case Ms.type:{let a=s;switch(a.feedback?.count){case Wr.count:{let o=a.feedback;this.receiverEstimatedMaxBitrate=o.bitrate}break;case Bs.count:this.pliCount++,this.onPictureLossIndication.execute(),this.onKeyFrameRequest.execute("pli");break;case qr.count:{let o=a.feedback,c=n??o.fir.filter(({ssrc:h})=>h===this.ssrc);if(c.length===0)break;this.firCount++;let d=!1;for(let{ssrc:h,sequenceNumber:u}of c){let p=`${o.senderSsrc}:${h}`;if(this.lastFirSequenceNumbers.get(p)!==u)d=!0;this.lastFirSequenceNumbers.set(p,u)}if(d)this.onFullIntraRequest.execute(o),this.onKeyFrameRequest.execute("fir")}break}}break}this.onRtcp.execute(s)}getParameters(){return{encodings:this.sendEncodings.map((s)=>({...s}))}}setParameters(s){if(s.encodings)this.setSendEncodings(s.encodings)}get outboundRtpStatsId(){return q("outbound-rtp",this.trackId)}get mediaSourceStatsId(){return q("media-source",this.trackId)}get remoteInboundRtpStatsId(){return q("remote-inbound-rtp",this.trackId)}getStatsRootIds(){return[this.outboundRtpStatsId]}collectStats(s){let n=[],a=this.dtlsTransport?q("transport",this.dtlsTransport.id):void 0,o=this.codec&&a?Gn(a,this.codec.payloadType,this.trackId):void 0,c={type:"outbound-rtp",id:this.outboundRtpStatsId,timestamp:s,ssrc:this.ssrc,kind:this.kind,transportId:a,codecId:o,mid:this.mid,packetsSent:this.packetCount,bytesSent:this.octetCount,headerBytesSent:this.headerBytesSent,retransmittedPacketsSent:this.retransmittedPacketsSent||void 0,retransmittedBytesSent:this.retransmittedBytesSent||void 0,rtxSsrc:this.rtxPayloadType?this.rtxSsrc:void 0,mediaSourceId:this.track?this.mediaSourceStatsId:void 0,remoteId:this.rtt!==void 0||this.remotePacketsLost!==void 0||this.remoteFractionLost!==void 0?this.remoteInboundRtpStatsId:void 0,nackCount:this.nackCount||void 0,pliCount:this.pliCount||void 0,firCount:this.firCount||void 0};if(n.push(c),this.track){let d={type:"media-source",id:this.mediaSourceStatsId,timestamp:s,trackIdentifier:this.track.id??this.trackId,kind:this.kind};n.push(d)}if(this.codec&&a){let d={type:"codec",id:o,timestamp:s,payloadType:this.codec.payloadType,transportId:a,mimeType:this.codec.mimeType,clockRate:this.codec.clockRate,channels:this.codec.channels,sdpFmtpLine:this.codec.parameters};n.push(d)}if(this.rtt!==void 0||this.remotePacketsLost!==void 0||this.remoteFractionLost!==void 0){let d={type:"remote-inbound-rtp",id:this.remoteInboundRtpStatsId,timestamp:s,ssrc:this.ssrc,kind:this.kind,transportId:a,codecId:c.codecId,localId:c.id,roundTripTime:this.rtt,totalRoundTripTime:this.totalRoundTripTime,roundTripTimeMeasurements:this.roundTripTimeMeasurements,packetsLost:this.remotePacketsLost,fractionLost:this.remoteFractionLost};n.push(d)}return n}async getStats(){let s=pt(),n=this.collectStats(s);if(this.dtlsTransport)n.push(...await this.dtlsTransport.getStats(s));return Xr(n,this.getStatsRootIds())}};function al(s){return s.find((n)=>n.name.toLowerCase()!=="rtx")??s[0]}function Dc(s){let n=al(s);if(n?.name.toLowerCase()!=="red")return n;let a=Number((n.parameters??"").split("/")[0]);return s.find((o)=>!["red","rtx"].includes(o.name.toLowerCase())&&o.payloadType===a)}var bv=class{type="track";track;streams;transceiver;receiver;constructor(s){this.track=s.track,this.streams=[...s.streams],this.transceiver=s.transceiver,this.receiver=s.receiver}},Rv=class{constructor(s,n,a,o,c,d=()=>!1){this.sdp=s,this.transceivers=n,this.sctp=a,this.negotiation=o,this.createTransport=c,this.isClosed=d}sdp;transceivers;sctp;negotiation;createTransport;isClosed;async assertOpen(s){if(!this.isClosed())return;throw await Promise.allSettled(s.map((n)=>n.stop())),A("InvalidStateError","RTCPeerConnection is closed")}bundleTagOf(s,n){if(this.sdp.bundlePolicy==="disable"||n==null)return;return s.group.find((a)=>a.semantic==="BUNDLE"&&a.items.includes(n))?.items[0]}isBundledNonTag(s,n){let a=this.bundleTagOf(s,n);return a!==void 0&&a!==n}currentTransportForMid(s){return this.negotiation.transportByMid.get(s)??this.transceivers.getTransceivers().find((n)=>n.mid===s)?.dtlsTransport??(this.sctp.sctpTransport?.mid===s?this.sctp.sctpTransport.dtlsTransport:void 0)}transportsOf(s){let n=new Set;for(let a of s.media){let o=a.rtp.muxId;if(a.port===0||!o)continue;let c=this.bundleTagOf(s,o)??o,d=this.negotiation.transportByMid.get(c)??this.liveTransportForMid(c);if(d)n.add(d)}return n}liveTransportForMid(s){return this.liveTransportByMid().get(s)}liveTransportByMid(){let s=new Map;for(let a of this.transceivers.getTransceivers())if(a.mid)s.set(a.mid,a.dtlsTransport);let n=this.sctp.sctpTransport;if(n?.mid)s.set(n.mid,n.dtlsTransport);return s}async stageLocalOffer(s,n=new Map){let a=this.liveTransportByMid();for(let[p,f]of n)if(!a.has(p))a.set(p,f);let o=!!this.sdp.currentRemoteDescription?.group.some((p)=>p.semantic==="BUNDLE"),c=new Map;for(let p of s.media){let f=p.rtp.muxId;if(p.port===0||!f)continue;let m=this.bundleTagOf(s,f)??f,y=a.get(f),S=m===f||this.sdp.bundlePolicy==="max-bundle"||o||!y||y===a.get(m);c.set(f,S?m:f)}let d=new Map,h=new Set,u=[];try{for(let p of new Set(c.values())){let f=a.get(p),m=!1;if(!f||h.has(f))f=this.createTransport(),u.push(f),m=!0,await f.iceTransport.gather(),await this.assertOpen(u);h.add(f),d.set(p,{transport:f,pendingOnly:m})}}catch(p){throw await Promise.allSettled(u.map((f)=>f.stop())),p}return[...c].map(([p,f])=>({mid:p,owner:f,...d.get(f)}))}installLocalOffer(s,n){let a=this.liveTransportByMid();for(let{mid:o,owner:c,transport:d,pendingOnly:h}of n){if(h){this.negotiation.prepareTransport(s,o,d,!0),this.negotiation.prepareTransport(s,o,d);continue}let u=a.get(c)??d;this.negotiation.prepareTransport(s,o,u)}}planPending(s){let n=new Map;for(let d of s.media){if(d.port===0||!d.rtp.muxId)continue;if((d.kind==="audio"||d.kind==="video")&&this.transceivers.getTransceivers().find((h)=>h.mid===d.rtp.muxId)?.codecs.length===0)continue;n.set(d.rtp.muxId,this.bundleTagOf(s,d.rtp.muxId)??d.rtp.muxId)}let a=this.liveTransportByMid(),o=new Map,c=new Set;for(let d of new Set(n.values())){let h=a.get(d);if(!h||c.has(h))o.set(d,{});else o.set(d,{reuse:h}),c.add(h)}return{ownerByMid:n,owners:o}}assertPendingSctpBinding(s){let n=this.sctp.sctpTransport;if(!this.sdp.currentRemoteDescription||!n?.mid||n.sctp?.associationState!==4)return;let{ownerByMid:a,owners:o}=this.planPending(s),c=a.get(n.mid);if(c===void 0)return;if(o.get(c)?.reuse!==n.dtlsTransport)throw A("InvalidModificationError","Moving a connected SCTP association to another DTLS transport is unsupported")}async preparePending(){let s=this.sdp.pendingRemoteDescription;if(!s||s.type!=="offer"||this.negotiation.preparedDescription===s)return;if(!this.sdp.currentRemoteDescription)return;this.assertPendingSctpBinding(s);let{ownerByMid:n,owners:a}=this.planPending(s),o=[];try{let c=new Map;for(let[d,h]of a){let u=h.reuse;if(!u)u=this.createTransport(),o.push(u),this.negotiation.prepareTransport(s,d,u,!0),await u.iceTransport.gather(),await this.assertOpen(o);c.set(d,u)}for(let[d,h]of n)this.negotiation.prepareTransport(s,d,c.get(h))}catch(c){throw await this.negotiation.discardPreparedTransports(),c}}applyPending(s){let n=this.negotiation.transportByMid;if(n.size===0)return;for(let c of this.transceivers.getTransceivers()){let d=c.mid&&n.get(c.mid);if(d)c.setDtlsTransport(d)}let a=this.sctp.sctpTransport,o=!!s&&s.media.find((c)=>c.rtp.muxId===a?.mid)?.port===0;if(a?.mid&&!o){let c=(s&&this.bundleTagOf(s,a.mid))??a.mid,d=n.get(c)??(c!==a.mid?this.transceivers.getTransceivers().find((h)=>h.mid===c)?.dtlsTransport:void 0);if(d)a.setDtlsTransport(d)}}assertAnswerKeepsSharedTransports(s,n){if(!["answer","pranswer"].includes(s.type)||!["have-local-offer","have-remote-pranswer"].includes(n)||this.sdp.bundlePolicy==="disable")return;let a=s.group.filter((d)=>d.semantic==="BUNDLE"),o=new Map,c=this.sctp.sctpTransport;for(let d of s.media){let h=d.rtp.muxId;if(d.port===0||h==null)continue;let u=d.kind==="application"?c?.mid===h?c:void 0:this.transceivers.getTransceivers().find((S)=>S.mid===h&&!S.stopped),p=this.negotiation.transportByMid.get(h)??u?.dtlsTransport;if(!p)continue;let f={group:a.find((S)=>S.items.includes(h)),credentials:`${d.iceParams?.usernameFragment}:${d.iceParams?.password}`},m=o.get(p);if(!m){o.set(p,f);continue}if(!(!!f.group&&f.group===m.group)&&f.credentials!==m.credentials)throw A("InvalidAccessError",`mid=${h} shares a transport in the local offer but the remote ${s.type} moves it out of that BUNDLE group`)}}};function yr(s){return s.fingerprints.map(({algorithm:n,value:a})=>`${n.toLowerCase()}:${a.replaceAll(":","").toLowerCase()}`).sort().join("|")}var Cv=class{constructor(s,n,a,o,c,d){this.config=s,this.sdp=n,this.transceivers=a,this.sctp=o,this.negotiation=c,this.topology=d}config;sdp;transceivers;sctp;negotiation;topology;validateLocal(s,n=()=>{return}){for(let a of s.media){if(a.port===0||!a.iceParams)continue;let o=a.rtp.muxId&&this.negotiation.transportByMid.get(a.rtp.muxId),c=(a.kind==="application"?this.sctp.sctpTransport?.dtlsTransport:this.transceivers.getTransceivers().find((f)=>f.mid===a.rtp.muxId)?.dtlsTransport)??n(a.rtp.muxId??""),d=(f)=>!!f?.iceTransport.localGenerationFor(a.iceParams.usernameFragment,a.iceParams.password),h=s.type==="offer"?[o,c].filter(Boolean):[o||c].filter(Boolean);if(h.length>0&&!h.some((f)=>d(f||void 0)))throw A("InvalidModificationError","Local SDP must use prepared ICE credentials");let u=this.topology.isBundledNonTag(s,a.rtp.muxId),p=a.dtlsParams?.role;if(s.type!=="offer"&&!u&&p&&p!=="auto"&&c&&(!o||o===c)&&["connecting","connected"].includes(c.state)&&c.role!=="auto"&&c.role!==p)throw A("InvalidModificationError","Changing the DTLS role of a connected association is unsupported")}}assertRecyclesOnlyStoppedMLines(s){let n=this.sdp.currentRemoteDescription;if(s.type!=="offer"||!n)return;for(let[a,o]of s.media.entries()){let c=n.media[a],d=this.sdp.currentLocalDescription?.media[a];if(!c?.rtp.muxId||o.rtp.muxId===c.rtp.muxId||c.port===0||d?.port===0)continue;let h=this.transceivers.getTransceivers().find((u)=>u.mid===c.rtp.muxId);if(h&&!h.stopped&&!h.stopping)throw A("InvalidModificationError","An m-line of a transceiver that is not stopped cannot be recycled")}}validateRemote(s,n){this.sdp.validateRemoteDescription(s),this.topology.assertAnswerKeepsSharedTransports(s,n),this.assertRecyclesOnlyStoppedMLines(s);for(let[a,o]of s.media.entries()){if(!["audio","video","application"].includes(o.kind))throw A("OperationError","Unsupported media kind");if(o.kind==="application"&&o.port!==0){if(!o.sctpPort||o.sctpPort<1||o.sctpPort>65535)throw A("OperationError","Invalid SCTP port");if(this.sctp.sctpRemotePort&&this.sctp.sctpRemotePort!==o.sctpPort)throw A("InvalidModificationError","Changing the port of an existing SCTP association is unsupported")}if(s.type!=="offer"&&o.port!==0&&o.kind!=="application"&&hv(this.transceivers.getTransceivers().find((c)=>c.mid===o.rtp.muxId)?.pendingLocalOfferCodecs??this.localCodecsFor(o),o).length===0)throw A("InvalidAccessError","No supported codec in answer");if(o.port!==0&&this.sdp.currentRemoteDescription){let c=this.sdp.currentRemoteDescription.media[a];if((o.kind==="application"?this.sctp.sctpTransport?.dtlsTransport:this.transceivers.getTransceivers().find((h)=>h.mid===o.rtp.muxId)?.dtlsTransport)?.state==="connected"&&c?.dtlsParams&&o.dtlsParams){if(yr(c.dtlsParams)!==yr(o.dtlsParams))throw A("InvalidModificationError","Changing the fingerprint of a connected DTLS association is unsupported")}}if(o.port!==0&&s.type!=="offer"){let c=o.kind==="application"?this.sctp.sctpTransport?.dtlsTransport:this.transceivers.getTransceivers().find((p)=>p.mid===o.rtp.muxId)?.dtlsTransport,d=this.negotiation.transportByMid.get(o.rtp.muxId??""),h=this.topology.isBundledNonTag(s,o.rtp.muxId),u=o.dtlsParams?.role;if(!h&&u&&u!=="auto"&&c&&["connecting","connected"].includes(c.state)&&c.role!=="auto"&&(!d||d===c)&&(u==="client"?"server":"client")!==c.role)throw A("InvalidModificationError","Changing the DTLS role of a connected association is unsupported")}if(o.port!==0&&this.sdp.pendingRemoteDescription?.type==="pranswer"&&!this.sdp.currentRemoteDescription){let c=this.sdp.pendingRemoteDescription.media[a];if((o.kind==="application"?this.sctp.sctpTransport?.dtlsTransport:this.transceivers.getTransceivers().find((h)=>h.mid===o.rtp.muxId)?.dtlsTransport)?.state==="connected"&&c?.dtlsParams&&o.dtlsParams&&yr(c.dtlsParams)!==yr(o.dtlsParams))throw A("InvalidModificationError","Changing the fingerprint of a provisional DTLS association is unsupported")}}if(s.type==="answer"&&this.sctp.sctpTransport?.sctp?.associationState===4){let a=s.media.find((o)=>o.kind==="application"&&o.port!==0);if(a?.rtp.muxId){let c=s.group.find((h)=>h.semantic==="BUNDLE"&&h.items.includes(a.rtp.muxId))?.items[0]??a.rtp.muxId,d=this.negotiation.transportByMid.get(c)??this.transceivers.getTransceivers().find((h)=>h.mid===c)?.dtlsTransport??(this.sctp.sctpTransport.mid===c?this.sctp.sctpTransport.dtlsTransport:void 0);if(d&&d!==this.sctp.sctpTransport.dtlsTransport)throw A("InvalidModificationError","Moving a connected SCTP association to another DTLS transport is unsupported")}}if(s.type==="offer")this.topology.assertPendingSctpBinding(s)}localCodecsFor(s){return this.config.codecs[s.kind]??[]}};function qi(s){return(s?.media??[]).filter((n)=>n.port!==0).map((n)=>n.iceParams?.usernameFragment).filter((n)=>!!n)}var Ev=class{requested=!1;toReplace=new Set;request(s,n){this.requested=!0,this.toReplace=new Set([...qi(s),...qi(n)])}get replacing(){return this.toReplace}clear(){this.requested=!1,this.toReplace.clear()}settle(s){if(!this.requested)return;if(qi(s).some((n)=>this.toReplace.has(n)))return;this.clear()}},Iv=class{constructor(s){this.host=s}host;flag=!1;recheck=!1;scheduled=!1;changeSeq=0;negotiatedSeq=0;pendingOfferSeq;change(){this.changeSeq++,this.schedule()}schedule(){if(this.host.invalidate(),this.recheck=!0,this.flag||this.scheduled||this.host.signalingState()!=="stable")return;this.recheck=!1,this.scheduled=!0,setImmediate(()=>{if(this.scheduled=!1,this.host.isClosed())return;if(this.negotiatedSeq>=this.changeSeq)return;if(this.host.signalingState()!=="stable"){this.recheck=!0;return}this.flag=!0,this.host.fire()})}noteCreatedOffer(){return this.changeSeq}noteAppliedOffer(s){this.pendingOfferSeq=s}discardPendingOffer(){this.pendingOfferSeq=void 0}commitPendingOffer(){if(this.pendingOfferSeq==null)return;this.negotiatedSeq=Math.max(this.negotiatedSeq,this.pendingOfferSeq),this.pendingOfferSeq=void 0}};function kv(s){if(!s)return s;let n=s.candidate?.match(/\bufrag\s+(\S+)/)?.[1],a=s.usernameFragment??void 0;if(n&&a&&n!==a)throw A("OperationError","Candidate ufrag does not match usernameFragment");if(!n||a)return s;return{..."toJSON"in s?s.toJSON():{...s},usernameFragment:n}}var Pv=class{constructor(s,n,a,o,c){this.sdp=s,this.secure=n,this.negotiation=a,this.topology=o,this.host=c}sdp;secure;negotiation;topology;host;queued=[];async apply(s){let n=this.sdp.currentRemoteDescription,a=this.sdp.pendingRemoteDescription,o=s?.usernameFragment,c=s?.sdpMid,d=s?.sdpMLineIndex,h=(S)=>typeof c==="string"?S.media.filter((v)=>v.rtp.muxId===c):typeof d==="number"?S.media.slice(d,d+1):S.media,u=(S)=>h(S).some((v)=>v.iceParams?.usernameFragment===o),p=o&&n&&u(n)&&(!a||!u(a))?n:a??n;if(!p)return;let f=p===a&&!!n&&(a?.type==="offer"||a?.type==="pranswer"),m=await this.secure.addIceCandidate(p,s,!f),y=p;if(!y||!m)return;if(f){let S=new Set(m.mediaIndices.map((v)=>this.negotiation.transportByMid.get(y.media[v]?.rtp.muxId??"")).filter((v)=>!!v&&this.negotiation.isPendingOnlyTransport(v.iceTransport.id)));for(let v of S)v.iceTransport.deliverRemoteCandidate(m.kind==="end-of-candidates"?void 0:m.candidate);if(n)await this.deliverSameGenerationCandidate(y,n,m);if(this.host.signalingState()==="have-local-pranswer"||this.host.signalingState()==="have-remote-pranswer"){let v=new Set(m.mediaIndices.map((g)=>this.topology.currentTransportForMid(y.media[g]?.rtp.muxId??"")?.iceTransport).filter((g)=>!!g?.hasStagedRestart&&!this.negotiation.isPendingOnlyTransport(g.id)));for(let g of v)g.deliverProvisionalRemoteCandidate(m.kind==="end-of-candidates"?void 0:m.candidate)}}if(m.kind==="end-of-candidates"){for(let S of m.mediaIndices){let v=y.media[S];if(v)v.iceCandidatesComplete=!0}this.completeSharedTransportMedia(y,m.mediaIndices);return}for(let S of m.mediaIndices){let v=y.media[S];if(!v)continue;v.iceCandidates.push(m.candidate)}}async deliverSameGenerationDescription(s){let n=this.sdp.currentRemoteDescription;if(!n)return;let a=[...s.media.entries()].filter(([,o])=>{if(o.port===0)return!1;let c=this.negotiation.transportByMid.get(o.rtp.muxId??"");return!(c&&this.negotiation.isPendingOnlyTransport(c.iceTransport.id))});for(let[o,c]of a){if(this.topology.isBundledNonTag(s,c.rtp.muxId))continue;for(let d of c.iceCandidates)await this.deliverSameGenerationCandidate(s,n,{kind:"candidate",candidate:d,mediaIndices:[o]})}for(let[o,c]of a){if(!c.iceCandidatesComplete)continue;await this.deliverSameGenerationCandidate(s,n,{kind:"end-of-candidates",mediaIndices:[o]})}}completeSharedTransportMedia(s,n){let a=this.sdp.currentRemoteDescription;if(s===a){let h=(p)=>this.topology.liveTransportForMid(p)?.iceTransport,u=n.flatMap((p)=>{let f=s.media[p],m=h(f?.rtp.muxId??""),y=f?.iceParams?.usernameFragment;return m?.connection.remoteCandidatesEnd&&m.connection.remoteUsername===y?[{transport:m,ufrag:y}]:[]});for(let p of s.media){let f=h(p.rtp.muxId??"");if(u.some((m)=>m.transport===f&&m.ufrag===p.iceParams?.usernameFragment))p.iceCandidatesComplete=!0}return}let o=(h,u)=>this.topology.bundleTagOf(h,u)??u,c=(h)=>`${o(s,h.rtp.muxId??"")}\x00${h.iceParams?.usernameFragment??""}`,d=new Set;for(let h of n){let u=s.media[h],p=u?.rtp.muxId,f=u?.iceParams?.usernameFragment;if(!u||!p||!f)continue;let m=this.topology.liveTransportForMid(p)?.iceTransport,y=!!a&&o(a,p)===o(s,p)&&!!m?.connection.remoteCandidatesEnd&&m.connection.remoteUsername===f;if(u.iceCandidatesComplete||y)d.add(c(u))}for(let h of s.media)if(d.has(c(h)))h.iceCandidatesComplete=!0}async deliverSameGenerationCandidate(s,n,a){for(let o of a.mediaIndices){let c=s.media[o]?.rtp.muxId,d=s.media[o]?.iceParams?.usernameFragment,h=n.media.find((f)=>f.rtp.muxId===c),u=c?this.topology.currentTransportForMid(c)?.iceTransport:void 0;if(!d||!h||h.iceParams?.usernameFragment!==d||!u||this.negotiation.isPendingOnlyTransport(u.id)||u.connection.remoteUsername!==d||h.iceCandidatesComplete||u.connection.remoteCandidatesEnd)continue;if(a.kind==="end-of-candidates"){h.iceCandidatesComplete=!0,u.deliverRemoteCandidate(void 0),this.completeSharedTransportMedia(n,[n.media.indexOf(h)]);continue}let p=a.candidate.toJSON().candidate;if(h.iceCandidates.some((f)=>f.toJSON().candidate===p))continue;h.iceCandidates.push(a.candidate),u.deliverRemoteCandidate(a.candidate)}}async validateQueued(s){let n;for(let a of[...this.queued])try{await this.secure.addIceCandidate(s,a??null,!1)}catch(o){n??=o,this.queued.splice(this.queued.indexOf(a),1)}if(n)throw n}async flushQueued(){while(this.queued.length>0&&this.host.hasRemoteDescription()){let s=this.queued.shift();await this.apply(s??null)}}},Av=class{constructor(s,n,a,o,c,d){this.sdp=s,this.transceivers=n,this.sctp=a,this.router=o,this.negotiation=c,this.host=d}sdp;transceivers;sctp;router;negotiation;host;planCodecs(s){let n=new Set;return this.transceivers.planRemoteRtpCodecs(s,(a,o)=>{let c=this.findTransceiver(a,o,n);if(c)n.add(c);return c})}apply(s,n=new Map){let a=this.sdp.bundlePolicy==="disable"?[]:s.group.filter((u)=>u.semantic==="BUNDLE"),o=(s.type==="offer"||s.type==="pranswer")&&!!this.sdp.currentRemoteDescription,c={preserveCurrentTransport:o,transportUpdates:[],endOfCandidates:[],provisionalIce:[],associated:new Set},d=this.associate(s,c.associated);this.assignTransports(s,d,a,o);let h=this.accept(s,d,c,n);return this.planTransportUpdates(s,d,a,h,c),c}associate(s,n){let a=s.media.map((o,c)=>{if(o.kind==="application"){if(o.port===0)return{remoteMedia:o,index:c};let h=this.sctp.sctpTransport;if(!h)h=this.host.createSctpTransport(),h.mid=o.rtp.muxId;else if(h.mid!==void 0&&h.mid!==o.rtp.muxId&&(this.rejectedInCurrent(h.mid)||s.type==="offer"&&!this.inCurrent(h.mid)))h.mid=o.rtp.muxId;return{remoteMedia:o,index:c,sctpTransport:h}}if(!["audio","video"].includes(o.kind))throw Error("invalid media kind");let d=this.findTransceiver(o,c,n);if(!d){if(o.port===0)return{remoteMedia:o,index:c};let h=this.transceivers.getTransceivers().find((u)=>!u.stopped&&u.mLineIndex===c&&!!u.mid&&u.mid!==o.rtp.muxId&&this.sdp.currentRemoteDescription?.media[c]?.rtp.muxId===u.mid);if(h)h.stopping=!0,h.stopped=!0,this.router.unregisterTransceiver(h),this.negotiation.rememberDisplacedTransceiver(h);d=this.transceivers.addTransceiver(o.kind,this.host.createTransport(),{direction:"recvonly"},{remoteMLineIndex:c}),d.mid=o.rtp.muxId??null,this.negotiation.rememberRemoteTransceiver(d),this.host.onRemoteTransceiverAdded(d)}else if(d.mid==null)this.transceivers.associateMLine(d,c);return n.add(d),{remoteMedia:o,index:c,transceiver:d}});if(s.type==="offer")this.transceivers.releaseUnassociatedReservations(n,s.media.length);return a}inCurrent(s){return[this.sdp.currentLocalDescription,this.sdp.currentRemoteDescription].some((n)=>n?.media.some((a)=>a.rtp.muxId===s))}rejectedInCurrent(s){return[this.sdp.currentLocalDescription,this.sdp.currentRemoteDescription].some((n)=>n?.media.find((a)=>a.rtp.muxId===s)?.port===0)}findTransceiver(s,n,a){let o=this.transceivers.getTransceivers().filter((u)=>!a.has(u)&&u.kind===s.kind),c=s.rtp.muxId,d=c!=null?o.find((u)=>u.mid===c):void 0;if(d)return d;if(s.port===0)return;let h=o.filter((u)=>u.mid==null&&!u.stopping&&!u.stopped);return h.find((u)=>u.mLineIndex===n)??h[0]}assignTransports(s,n,a,o){let c=s.type==="offer",d=(m)=>o&&(m.transceiver?!!m.transceiver.currentDirection:!!this.sctp.sctpRemotePort),h=(m)=>n.filter((y)=>!!yt(y)&&y.remoteMedia.port!==0&&m.items.includes(y.remoteMedia.rtp.muxId));if(o){for(let m of a){let y=h(m),S=y.find((g)=>g.remoteMedia.rtp.muxId===m.items[0])??y[0],v=S&&yt(S).dtlsTransport;for(let g of y){let w=yt(g);if(v&&!d(g)&&w.dtlsTransport!==v)w.setDtlsTransport(v)}}return}let u=new Set,p=(m)=>m.iceTransport.localParameters.usernameFragment,f=(m)=>u.has(m)||[...u].some((y)=>p(y)===p(m));for(let m of a){let y=h(m);if(y.length===0)continue;let v=[...y.filter((g)=>g.remoteMedia.rtp.muxId===m.items[0]),...y].map((g)=>yt(g).dtlsTransport).find((g)=>Wi(g)&&(!c||!f(g)));if(!v)v=this.host.createOwnerTransport();u.add(v);for(let g of y){let w=yt(g);if(w.dtlsTransport!==v)w.setDtlsTransport(v)}}if(c)for(let m of n){let y=yt(m);if(!y||m.remoteMedia.port===0||Nc(a,m.remoteMedia.rtp.muxId))continue;if(!Wi(y.dtlsTransport)||f(y.dtlsTransport))y.setDtlsTransport(this.host.createOwnerTransport());u.add(y.dtlsTransport)}}accept(s,n,a,o){let c=new Set;for(let d of n){let{remoteMedia:h,index:u,transceiver:p}=d;if(p){if(h.port!==0){if(this.transceivers.setRemoteRTP(p,h,s.type,u,o.get(u)??[]))c.add(d);continue}if(p.mLineIndex=u,p.stopped)continue;if(s.type==="answer")a.transportUpdates.push(()=>p.commitStopped({rejected:!p.stopping}));else if(!p.stopping)p.pendingRejection=!0}else if(d.sctpTransport){if(!a.preserveCurrentTransport||!this.sctp.sctpRemotePort)this.sctp.setRemoteSCTP(h,u);else if(s.type==="pranswer")this.sctp.updateRemoteMaxMessageSize(h);c.add(d)}}return c}planTransportUpdates(s,n,a,o,c){let{preserveCurrentTransport:d}=c,h=new Map;for(let u of a)for(let p of u.items){let f=n.find((m)=>m.remoteMedia.rtp.muxId===p&&m.remoteMedia.port!==0&&o.has(m));if(f){h.set(u,f);break}}for(let u of n){let{remoteMedia:p}=u,f=yt(u),m=Nc(a,p.rtp.muxId);if(!f||p.port===0||!o.has(u)&&!m)continue;let y=p.rtp.muxId?this.negotiation.transportByMid.get(p.rtp.muxId):void 0,S=y&&this.negotiation.isPendingOnlyTransport(y.iceTransport.id)?y:void 0,v=d&&S?S:f.dtlsTransport;if(!Wi(v))continue;let g=v.iceTransport,w=!!m&&h.get(m)!==u,T=!d||!!S;c.transportUpdates.push(()=>{if(p.iceParams&&T&&!w){let C=s.media.some((P)=>P.port!==0&&P.direction==="inactive");if(g.setRemoteParams(p.iceParams,C,{keepLocalCredentials:s.type!=="offer"}),p.iceParams.iceLite&&!g.connection.iceLite)g.connection.iceControlling=!0}if(p.dtlsParams&&T&&!w)v.setRemoteParams(p.dtlsParams);if(T&&!w)p.iceCandidates.forEach(g.addRemoteCandidate);if(p.iceCandidatesComplete&&T)c.endOfCandidates.push(g);if(s.type==="pranswer"&&d&&!S&&!w&&g.hasStagedRestart)c.provisionalIce.push([g,p]);let b=p.dtlsParams?.role==="auto"&&["connecting","connected"].includes(v.state);if((s.type==="answer"||s.type==="pranswer")&&p.dtlsParams?.role&&!w&&!b)v.role=p.dtlsParams.role==="client"?"server":"client"})}}},yt=(s)=>s.transceiver??s.sctpTransport,Wi=(s)=>!!s&&s.state!=="closed",Nc=(s,n)=>n==null?void 0:s.find((a)=>a.items.includes(n)),Sr=_("werift:packages/webrtc/src/negotiation/transportActivation.ts"),xv=class{constructor(s,n,a,o,c,d,h){this.sdp=s,this.secure=n,this.transceivers=a,this.sctp=o,this.negotiation=c,this.topology=d,this.host=h}sdp;secure;transceivers;sctp;negotiation;topology;host;connectEpoch=0;async cleanupInitialProvisional(){if(this.sdp.currentLocalDescription||this.sdp.currentRemoteDescription)return;this.connectEpoch++;let s=[...this.secure.dtlsTransports];if(s.some((n)=>n.state!=="new"||!["new","closed"].includes(n.iceTransport.state)||!!n.iceTransport.getRemoteParameters())){if(this.sctp.sctpTransport)await this.sctp.sctpTransport.stop(),this.sctp.sctpRemotePort=void 0;await Promise.all(s.map((n)=>n.stop()));for(let n of this.transceivers.getTransceivers())n.setDtlsTransport(this.host.createTransport());if(this.sctp.sctpTransport)this.sctp.sctpTransport.setDtlsTransport(this.host.createTransport())}this.secure.updateIceConnectionState(),this.secure.setConnectionState("new")}async activatePendingRemote(s=!1){let n=this.sdp.pendingRemoteDescription;if(!n||n.type!=="offer")return;let a=new Map;for(let[o,c]of n.media.entries()){if(c.port===0)continue;let d=c.rtp.muxId&&this.negotiation.transportByMid.get(c.rtp.muxId)||(c.kind==="application"?this.sctp.sctpTransport?.dtlsTransport:this.transceivers.getTransceivers().find((f)=>f.mid===c.rtp.muxId)?.dtlsTransport);if(!d)continue;let h=this.topology.isBundledNonTag(n,c.rtp.muxId),u=s&&!this.negotiation.isPendingOnlyTransport(d.iceTransport.id);if(c.kind==="application")if(u)this.sctp.updateRemoteMaxMessageSize(c);else this.sctp.setRemoteSCTP(c,o);let p=a.get(d.iceTransport)??{provisional:u,candidates:new Map,eoc:!1,members:[]};if(a.set(d.iceTransport,p),p.members.push(c),!h){if(p.tag=c,!u){if(c.iceParams)d.iceTransport.setRemoteParams(c.iceParams);if(c.dtlsParams)d.setRemoteParams(c.dtlsParams)}}for(let f of c.iceCandidates)p.candidates.set(f.toJSON().candidate,f);if(c.iceCandidatesComplete)p.eoc=!0}for(let[o,c]of a){let d=c.tag?.iceParams?.usernameFragment;for(let[h,u]of c.candidates)if(d&&u.ufrag&&u.ufrag!==d)c.candidates.delete(h);if(c.provisional){if(c.tag)await this.applyProvisionalIce(o,c.tag,[...c.candidates.values()],c.eoc);continue}for(let h of c.candidates.values())o.deliverRemoteCandidate(h);if(c.eoc)o.deliverRemoteCandidate(void 0)}for(let o of a.values()){if(!o.eoc)continue;for(let c of o.members)c.iceCandidatesComplete=!0}}async applyProvisionalIce(s,n,a=n.iceCandidates,o=n.iceCandidatesComplete){if(!s.hasStagedRestart||!n.iceParams)return;s.setProvisionalRemoteParams(n.iceParams);for(let c of a)s.deliverProvisionalRemoteCandidate(c);if(o)s.deliverProvisionalRemoteCandidate(void 0)}async connect(){Sr("start connect");let s=this.connectEpoch,n=await Promise.allSettled(this.secure.dtlsTransports.map(async(a)=>{let{iceTransport:o}=a,c=!1,d=["connected","completed"].includes(o.state);if(!o.checksStarted&&!o.getRemoteParameters())return c;if(!o.checksStarted)c=!0,this.secure.setConnectionState("connecting"),await o.start().catch((h)=>{throw Sr("iceTransport.start failed",h),h}),d=!0;else if(o.state==="checking"){if(c=!0,await o.checksSettled(),d=["connected","completed"].includes(o.state),!d)throw Error(`ICE transport ${o.state}`)}if(a.state==="connecting"){let h=await Oc(a.onStateChange,()=>a.state,(u)=>u!=="connecting");if(h!=="connected")throw Error(`DTLS transport ${h}`);return this.startJoinedSctp(a),!0}if(a.state==="connected")this.startJoinedSctp(a);if(a.state!=="new"||!d||!a.hasRemoteParameters)return c;if(this.secure.setConnectionState("connecting"),await a.start().catch((h)=>{throw Sr("dtlsTransport.start failed",h),h}),this.sctp.sctpTransport&&this.sctp.sctpTransport.dtlsTransport.id===a.id)await this.sctp.connectSctp();return!0}));if(s!==this.connectEpoch)return;if(n.find((a)=>a.status==="rejected"))this.secure.setConnectionState("failed");else if(n.some((a)=>a.status==="fulfilled"&&a.value))this.secure.setConnectionState("connected")}startJoinedSctp(s){let n=this.sctp.sctpTransport;if(!n||n.dtlsTransport!==s||n.sctp.started||n.sctp.associationState!==1)return;this.sctp.connectSctp().catch((a)=>{Sr("sctp start failed",a)})}async connectPending(){let s=[...new Set(this.negotiation.transportByMid.values())].filter((n)=>this.negotiation.isPendingOnlyTransport(n.iceTransport.id));for(let n of this.secure.iceTransports)if(!this.negotiation.isPendingOnlyTransport(n.id))n.startProvisionalChecks();await Promise.all(s.map(async(n)=>{let{iceTransport:a}=n;if(!a.checksStarted){if(!a.getRemoteParameters())return;a.connection.iceControlling=this.host.signalingState()==="have-remote-pranswer",await a.start()}else if(a.state==="checking")await a.checksSettled();if(!["connected","completed"].includes(a.state))return;if(n.state==="connecting"){await Oc(n.onStateChange,()=>n.state,(o)=>o!=="connecting");return}if(n.state==="new"&&n.hasRemoteParameters)await n.start()}))}};function Oc(s,n,a){return new Promise((o)=>{if(a(n())||s.ended){o(n());return}let{unSubscribe:c}=s.subscribe((d)=>{if(!a(d))return;c(),o(d)},()=>o(n()))})}var _v=class s{remoteCreated=new Set;displaced=new Set;prepared=new Map;pendingOnly=new Set;owners=new Set;emittedCandidates=new Set;preparedFor;get speculativeTransports(){return[...this.pendingOnly,...this.owners]}clear(){this.assign(new s)}copy(){let n=new s;return n.assign(this),n}assign(n){ys(this.remoteCreated,n.remoteCreated),ys(this.displaced,n.displaced),ys(this.pendingOnly,n.pendingOnly),ys(this.owners,n.owners),ys(this.emittedCandidates,n.emittedCandidates),this.prepared.clear();for(let[a,o]of n.prepared)this.prepared.set(a,o);this.preparedFor=n.preparedFor}};function Hc(s){if(!s)return[];return[...[...s.transceivers.states.values()].map(({transceiver:n})=>n.dtlsTransport),s.sctp.dtlsTransport].filter((n)=>!!n)}function ys(s,n){let a=[...n];s.clear();for(let o of a)s.add(o)}var Lv=64,Bv=class{constructor(s,n,a,o){this.sdp=s,this.transceivers=n,this.router=a,this.sctp=o}sdp;transceivers;router;sctp;baseline;offerSnapshot;resources=new _v;retiredRemoteUfrags=new Set;createdTransports=new Set;createdStates=new WeakMap;revision=0;phase="idle";snapshotForOffer(){if(this.baseline)return;let s=this.capture();if(!this.offerSnapshot){this.offerSnapshot=s;return}let{order:n,states:a}=this.offerSnapshot.transceivers;for(let[o,c]of s.transceivers.states)if(!a.has(o))a.set(o,c),n.push(o)}begin({fromCreatedOffer:s=!1}={}){if(!this.baseline&&!s&&this.offerSnapshot)this.transceivers.revertUnappliedAssociations(this.offerSnapshot.transceivers),this.sctp.revertUnappliedAssociation(this.offerSnapshot.sctp);if(!this.baseline)this.baseline=(s?this.offerSnapshot:void 0)??this.capture();return this.offerSnapshot=void 0,this.revision++,this.phase="pending",this.revision}settle(){if(this.baseline)this.phase="pending"}validate(){this.phase="validating"}prepare(){this.phase="preparing"}async commit(){this.phase="committing",this.router.commitStaged();for(let a of this.transceivers.getTransceivers())a.receiver.commitStagedReceive();for(let a of this.resources.displaced){if(!a.stopped)continue;a.setCurrentDirection("stopped"),a.receiver.stop(),a.sender.stop()}let s=new Set(this.createdTransports);for(let{transceiver:a}of this.baseline?.transceivers.states.values()??[])s.add(a.dtlsTransport);if(this.baseline?.sctp.dtlsTransport)s.add(this.baseline.sctp.dtlsTransport);this.createdTransports.clear(),this.cleanup();let n=this.transportsInUse({includeStopped:!1});await Promise.all([...s].filter((a)=>!n.has(a)).map((a)=>a.stop()))}stopUnusedProposalChecks(s){let n=this.transportsInUse({includeStopped:!1});for(let a of s)n.add(a);for(let a of new Set([...this.createdTransports,...this.resources.speculativeTransports])){if(n.has(a))continue;if(["new","closed"].includes(a.iceTransport.state))continue;a.iceTransport.resetRemoteGeneration()}}async replace(s){if(!this.baseline)return;let n=(c)=>!!s?.media.some((d)=>d.port!==0&&d.kind===c.kind&&d.rtp.muxId===c.mid),a=new Set([...this.resources.remoteCreated].filter(n)),o=new Set(this.transceivers.getTransceivers().filter((c)=>!this.resources.remoteCreated.has(c)&&n(c)));await this.restoreState(this.baseline,this.resources.remoteCreated,this.resources.speculativeTransports,a,o),this.resources.clear();for(let c of a)this.resources.remoteCreated.add(c);this.revision++,this.phase="pending"}async rollback(){if(!this.baseline)return;await this.restoreState(this.baseline,this.resources.remoteCreated,this.resources.speculativeTransports),this.cleanup()}checkpoint(){return{state:this.capture(),resources:this.resources.copy()}}async restoreCheckpoint(s){let n=s.resources,a=new Set(n.speculativeTransports);await this.restoreState(s.state,[...this.resources.remoteCreated].filter((o)=>!n.remoteCreated.has(o)),this.resources.speculativeTransports.filter((o)=>!a.has(o))),this.resources.assign(n),this.phase="pending"}async dispose(){let s=new Set([...this.createdTransports,...this.resources.speculativeTransports,...this.resources.prepared.values(),...Hc(this.baseline),...Hc(this.offerSnapshot)]);this.createdTransports.clear(),this.offerSnapshot=void 0,this.cleanup(),await Promise.allSettled([...s].map((n)=>n.stop()))}noteCreatedTransport(s){this.createdTransports.add(s),s.onStateChange.subscribe((n)=>{if(n==="closed")this.createdTransports.delete(s)})}rememberRemoteTransceiver(s){this.resources.remoteCreated.add(s),this.createdStates.set(s,s.snapshotNegotiationState())}rememberOwnerTransport(s){this.resources.owners.add(s)}rememberDisplacedTransceiver(s){this.resources.displaced.add(s)}get preparedDescription(){return this.resources.preparedFor}get transportByMid(){return this.resources.prepared}isPendingOnlyTransport(s){return[...this.resources.pendingOnly].some((n)=>n.iceTransport.id===s)}takePreparedCandidateTransports(){let{pendingOnly:s,emittedCandidates:n}=this.resources,a=[...s].filter((o)=>!n.has(o.id));for(let o of a)n.add(o.id);return a}prepareTransport(s,n,a,o=!1){if(this.resources.preparedFor=s,this.resources.prepared.set(n,a),o)this.resources.pendingOnly.add(a)}async discardPreparedTransports(){let{prepared:s,pendingOnly:n,emittedCandidates:a}=this.resources,o=[...n];s.clear(),n.clear(),a.clear(),this.resources.preparedFor=void 0,await Promise.allSettled(o.map((c)=>c.stop()))}discardStagedRemoteAnswer(){this.router.discardProvisional(),this.router.restoreStaged({ssrc:[],rid:[]});for(let s of this.transceivers.getTransceivers())s.receiver.discardStagedReceive()}retireRemoteGeneration(s){for(let n of s?.media??[]){let a=n.iceParams?.usernameFragment;if(a)this.retiredRemoteUfrags.add(a)}while(this.retiredRemoteUfrags.size>Lv)this.retiredRemoteUfrags.delete(this.retiredRemoteUfrags.values().next().value)}isRetiredRemoteUfrag(s){return!!s&&this.retiredRemoteUfrags.has(s)}capture(){return{transceivers:this.transceivers.snapshotNegotiationState(),routes:this.router.snapshotRoutes(),sctp:this.sctp.snapshotNegotiationState()}}async restoreState(s,n,a,o=new Set,c=new Set){let d=this.transceivers.restoreNegotiationState(s.transceivers,n,(f)=>this.createdStates.get(f),o,c),h=this.transceivers.getTransceivers();this.router.restoreRoutes(s.routes,{endpoints:new Set(h.flatMap((f)=>[f.sender,f.receiver])),liveSenders:h.filter((f)=>!f.stopped&&!f.stopping).map((f)=>f.sender)});let u=this.sctp.sctpTransport?.dtlsTransport;await this.sctp.restoreNegotiationState(s.sctp);let p=this.transportsInUse({includeStopped:!0});for(let f of new Set([...a,...d,...u?[u]:[]]))if(!p.has(f))await f.stop()}transportsInUse({includeStopped:s}){let n=new Set(this.transceivers.getTransceivers().filter((o)=>s||!o.stopped).map((o)=>o.dtlsTransport)),a=this.sctp.sctpTransport?.dtlsTransport;if(a)n.add(a);return n}cleanup(){this.baseline=void 0,this.resources.clear(),this.phase="idle"}inspect(){return{phase:this.phase,revision:this.revision,currentLocal:this.sdp.currentLocalDescription,currentRemote:this.sdp.currentRemoteDescription,pendingLocal:this.sdp.pendingLocalDescription,pendingRemote:this.sdp.pendingRemoteDescription,baselineTransceivers:this.baseline?.transceivers.states.size??0,remoteCreated:this.resources.remoteCreated.size,pendingTransports:this.resources.pendingOnly.size,createdTransports:[...this.createdTransports],hasOfferSnapshot:!!this.offerSnapshot}}},Mv=_("werift:packages/webrtc/src/transport/sctpManager.ts"),Dv=class{sctpTransport;sctpRemotePort;dataChannelsOpened=0;dataChannelsClosed=0;dataChannels=[];applicationOwned=new WeakSet;onDataChannel=new E;constructor(){}createSctpTransport(s,n){let a=new zS(5000,s,n);return a.mid=void 0,a.onDataChannel.subscribe((o)=>{this.track(o),this.onDataChannel.execute(o)}),this.sctpTransport=a,a}createDataChannel(s,n={}){let a=Fc(n.maxPacketLifeTime,"maxPacketLifeTime"),o=Fc(n.maxRetransmits,"maxRetransmits"),d={...{protocol:"",ordered:!0,negotiated:!1},...n,maxPacketLifeTime:a,maxRetransmits:o};if(d.maxPacketLifeTime!=null&&d.maxRetransmits!=null)throw lt("maxPacketLifeTime and maxRetransmits cannot both be set");if(!this.sctpTransport)this.sctpTransport=this.createSctpTransport();this.applicationOwned.add(this.sctpTransport);let h=new md({id:d.id,label:s,maxPacketLifeTime:d.maxPacketLifeTime,maxRetransmits:d.maxRetransmits,negotiated:d.negotiated,ordered:d.ordered,protocol:d.protocol}),u=new fd(this.sctpTransport,h);return this.track(u),u}track(s){this.dataChannelsOpened++,this.dataChannels.push(s);let{unSubscribe:n}=s.stateChange.subscribe((a)=>{if(a==="closed"){n(),this.dataChannelsClosed++;let o=this.dataChannels.indexOf(s);if(o!==-1)this.dataChannels.splice(o,1)}})}isApplicationOwned(s){return this.applicationOwned.has(s)}snapshotNegotiationState(){let s=this.sctpTransport;return{transport:s,dtlsTransport:s?.dtlsTransport,remotePort:this.sctpRemotePort,mid:s?.mid,mLineIndex:s?.mLineIndex,remoteMaxMessageSize:s?.remoteMaxMessageSize}}async restoreNegotiationState(s){let n=this.sctpTransport!==s.transport?this.sctpTransport:void 0,a=!!n&&this.isApplicationOwned(n)&&n.sctp.associationState===1;if(n&&!a)await n.stop();if(this.sctpTransport=a?n:s.transport,s.transport&&s.dtlsTransport&&s.transport.dtlsTransport!==s.dtlsTransport)s.transport.setDtlsTransport(s.dtlsTransport);if(n&&a)this.detachFromDescription(n);if(this.sctpRemotePort=s.remotePort,s.transport){if(s.transport.mid=s.mid,s.transport.mLineIndex=s.mLineIndex,s.remoteMaxMessageSize!==void 0)s.transport.remoteMaxMessageSize=s.remoteMaxMessageSize}}revertUnappliedAssociation(s){let n=this.sctpTransport;if(n&&n===s.transport&&this.sctpRemotePort===void 0)n.mid=s.mid,n.mLineIndex=s.mLineIndex}detachFromDescription(s){s.mid=void 0,s.mLineIndex=void 0,s.remoteMaxMessageSize=Yt}async connectSctp(){if(!this.sctpTransport||!this.sctpRemotePort)return;await this.sctpTransport.start(this.sctpRemotePort),await this.sctpTransport.sctp.stateChanged.connected.asPromise(),Mv("sctp connected")}updateRemoteMaxMessageSize(s){this.sctpTransport?.setRemoteMaxMessageSize(s.sctpCapabilities?.maxMessageSize)}setRemoteSCTP(s,n){if(!this.sctpTransport)return;if(this.sctpTransport.setRemoteMaxMessageSize(s.sctpCapabilities?.maxMessageSize),this.sctpRemotePort=s.sctpPort,!this.sctpRemotePort)throw Error("sctpRemotePort not exist");if(this.sctpTransport.setRemotePort(this.sctpRemotePort),this.sctpTransport.mLineIndex=n,!this.sctpTransport.mid)this.sctpTransport.mid=s.rtp.muxId}async close(){if(this.sctpTransport)await this.sctpTransport.stop(),await new Promise((s)=>setImmediate(s));this.onDataChannel.allUnsubscribe()}async getStats(s=pt()){let n=[];for(let a of this.dataChannels){let o={type:"data-channel",id:q("data-channel",a.id??a.statsId),timestamp:s,label:a.label,protocol:a.protocol,dataChannelIdentifier:a.id??void 0,state:a.readyState,messagesSent:a.messagesSent||0,bytesSent:a.bytesSent||0,messagesReceived:a.messagesReceived||0,bytesReceived:a.bytesReceived||0};n.push(o)}return n}};function Fc(s,n){if(s===void 0)return;let a=Number(s);if(!Number.isFinite(a)||!Number.isInteger(a)||a<0||a>65535)throw lt(`${n} must be an unsigned short`);return a}var Uv=class{currentLocalDescription;currentRemoteDescription;pendingLocalDescription;pendingRemoteDescription;cname;midSuffix;bundlePolicy;mLineReuse;seenMid=new Set;constructor({cname:s,midSuffix:n,bundlePolicy:a,mLineReuse:o}){this.cname=s,this.midSuffix=n??!1,this.bundlePolicy=a,this.mLineReuse=o??"compatible"}get localDescription(){if(!this._localDescription)return;return this._localDescription.toJSON()}get remoteDescription(){if(!this._remoteDescription)return;return this._remoteDescription.toJSON()}get _localDescription(){return this.pendingLocalDescription||this.currentLocalDescription}get _remoteDescription(){return this.pendingRemoteDescription||this.currentRemoteDescription}get inactiveRemoteMedia(){return this._remoteDescription?.media?.find?.((s)=>s.direction==="inactive")}createMediaDescriptionForTransceiver(s,n){let a=new bs(s.kind,9,"UDP/TLS/RTP/SAVPF",s.codecs.map((o)=>o.payloadType));if(a.direction=n,a.msids=s.msids,a.rtp={codecs:s.codecs,headerExtensions:s.headerExtensions,muxId:s.mid??void 0},a.rtcpHost="0.0.0.0",a.rtcpPort=9,a.rtcpMux=!0,a.ssrc=[new xn({ssrc:s.sender.ssrc,cname:this.cname})],s.options.simulcast)a.simulcastParameters=s.options.simulcast.map((o)=>new Bh(o));if(a.rtp.codecs.find((o)=>o.name.toLowerCase()==="rtx"))a.ssrc.push(new xn({ssrc:s.sender.rtxSsrc,cname:this.cname})),a.ssrcGroup=[new Ps("FID",[s.sender.ssrc.toString(),s.sender.rtxSsrc.toString()])];return this.addTransportDescription(a,s.dtlsTransport),a}createRejectedMediaDescription(s,n){let a=s.fmt[0]??s.codecs[0]?.payloadType??0,o=new bs(s.kind,0,s.profile,[a]);if(o.host=ac,o.direction="inactive",o.rtp={codecs:s.codecs.filter((c)=>c.payloadType?.toString()===a.toString()),headerExtensions:[],muxId:s.mid},o.rtcpMux=!0,n)o.iceParams=n.iceTransport.localParameters,o.dtlsParams=n.localParameters;return o}createMediaDescriptionForSctp(s){let n=new bs("application",oc,"UDP/DTLS/SCTP",["webrtc-datachannel"]);return n.sctpPort=s.port,n.rtp.muxId=s.mid,n.sctpCapabilities=s.getCapabilities(),this.addTransportDescription(n,s.dtlsTransport),n}addTransportDescription(s,n,{applied:a=!1}={}){let o=n.iceTransport.describedLocalGeneration({applied:a});if(a&&s.iceParams&&s.iceParams.usernameFragment!==o.parameters?.usernameFragment)return;if(s.iceCandidates=o.candidates,s.iceCandidatesComplete=o.complete,s.iceParams=o.parameters,s.iceOptions="trickle",s.host=ac,s.port=oc,s.direction==="inactive"){if(this.mLineReuse==="aggressive")s.port=0;s.msids=[]}if(!s.dtlsParams){if(s.dtlsParams=n.localParameters,!s.dtlsParams.fingerprints)s.dtlsParams.fingerprints=n.localParameters.fingerprints}}allocateMid(s=""){let n="";for(let a=0;;)if(n=(a++).toString()+s,!this.seenMid.has(n))break;return this.seenMid.add(n),n}parseSdp({sdp:s,isLocal:n,signalingState:a,type:o}){let c=xr.parse(s);if(this.validateDescription({description:c,isLocal:n,signalingState:a,type:o}),!n&&o!=="offer")this.alignInitialAnswerMids(c);return this.validateSections(c,o,n),c.type=o,c}alignInitialAnswerMids(s){let n=this.pendingLocalDescription;if(this.currentLocalDescription||this.currentRemoteDescription||!n||n.media.length!==s.media.length)return;let a=new Set(n.media.map((c)=>c.rtp.muxId)),o=new Map;for(let[c,d]of s.media.entries()){let h=n.media[c],u=d.rtp.muxId,p=h.rtp.muxId;if(!u||!p||u===p||a.has(u)||d.kind!==h.kind||s.media.some((f)=>f.rtp.muxId===p))continue;o.set(u,p),d.rtp.muxId=p}for(let c of s.group)c.items=c.items.map((d)=>o.get(d)??d)}validateSections(s,n,a){let c=s.media.map((p)=>p.rtp.muxId).filter((p)=>!!p);if(new Set(c).size!==c.length)throw A("OperationError","Duplicate MID in SDP");for(let p of s.group.filter((f)=>f.semantic==="BUNDLE"))if(new Set(p.items).size!==p.items.length||p.items.some((f)=>!c.includes(f)))throw A("OperationError","Invalid BUNDLE group in SDP");let d=a?this.currentLocalDescription:this.currentRemoteDescription;if(d){for(let[p,f]of d.media.entries()){let m=s.media[p],y=a?this.currentRemoteDescription:this.currentLocalDescription,S=f.port===0||y?.media[p]?.port===0||f.direction==="inactive";if(!m||m.kind!==f.kind&&f.port!==0||f.rtp.muxId&&m.rtp.muxId!==f.rtp.muxId&&!S)throw A("InvalidModificationError","Existing m-lines must retain their order, kind and MID");if(!a&&!S&&m.port!==0)this.assertStablePayloadTypes(this.negotiatedCodecs(p),m)}if(!a)this.assertStableHeaderExtensionIds(s)}if(n==="offer")return;let h=a?this.pendingRemoteDescription:this.pendingLocalDescription,u=!a&&!!h&&s.media.length<h.media.length;if(!h||s.media.length!==h.media.length&&!u)throw A("InvalidModificationError","Answer m-lines must match the offer");for(let[p,f]of s.media.entries()){let m=h.media[p];if(f.kind!==m.kind||m.rtp.muxId&&f.rtp.muxId!==m.rtp.muxId)throw A("InvalidModificationError","Answer m-lines must match the offer");if(f.port!==0&&m.port===0)throw A("InvalidModificationError","Answer cannot accept a rejected m-line")}}negotiatedMedia(s){let n=this.currentRemoteDescription?.media[s],a=this.currentLocalDescription?.media[s];if(!n||!a||n.port===0||a.port===0)return;return{remote:n,local:a}}negotiatedCodecs(s){let n=this.negotiatedMedia(s);if(!n)return[];return n.remote.rtp.codecs.filter((a)=>n.local.rtp.codecs.some((o)=>o.payloadType===a.payloadType))}negotiatedHeaderExtensions(s){let n=this.negotiatedMedia(s);if(!n)return[];return n.remote.rtp.headerExtensions.filter((a)=>n.local.rtp.headerExtensions.some((o)=>o.id===a.id&&o.uri===a.uri))}assertStableHeaderExtensionIds(s){let n=new Map;for(let a of this.currentRemoteDescription?.media.keys()??[])for(let o of this.negotiatedHeaderExtensions(a))n.set(o.id,o.uri);for(let a of s.media){if(a.port===0)continue;for(let o of a.rtp.headerExtensions){let c=n.get(o.id);if(c!==void 0&&c!==o.uri)throw A("InvalidModificationError",`RTP header extension id ${o.id} cannot be remapped within a session`)}}}assertStablePayloadTypes(s,n){for(let a of n.rtp.codecs){let o=s.find((d)=>d.payloadType===a.payloadType);if(!o)continue;let c=(d)=>tt(d.parameters??"").apt;if(o.mimeType.toLowerCase()!==a.mimeType.toLowerCase()||o.clockRate!==a.clockRate||(o.channels??1)!==(a.channels??1)||o.name.toLowerCase()==="rtx"&&c(o)!==c(a))throw A("InvalidModificationError",`Payload type ${a.payloadType} cannot be remapped within a session`)}}validateDescription({description:s,isLocal:n,signalingState:a,type:o}){if(n){if(o==="offer"){if(!["stable","have-local-offer","have-remote-pranswer"].includes(a))throw A("InvalidStateError","Cannot handle offer in signaling state")}else if(["answer","pranswer"].includes(o)){if(!["have-remote-offer","have-local-pranswer"].includes(a))throw A("InvalidStateError","Cannot handle answer in signaling state")}}else if(o==="offer"){if(!["stable","have-remote-offer","have-local-offer","have-local-pranswer"].includes(a))throw A("InvalidStateError","Cannot handle offer in signaling state")}else if(["answer","pranswer"].includes(o)){if(!["have-local-offer","have-remote-pranswer"].includes(a))throw A("InvalidStateError","Cannot handle answer in signaling state")}}buildOfferSdp(s,n){let a=new xr;Tc("offer",a);let o=this.findLiveDtlsTransport(s,n),c=this.currentLocalDescription?.media??[],d=s.filter((u)=>u.mid==null&&u.mLineIndex===void 0&&!u.stopping&&!u.stopped),h=new Set;c.forEach((u,p)=>{let f=s.find((g)=>!!u.rtp.muxId&&g.mid===u.rtp.muxId),y=u.kind!=="application"&&(!f||f.stopped)&&(u.port===0||this.currentRemoteDescription?.media[p]?.port===0)?d.findIndex((g)=>g.kind===u.kind):-1,S=y>=0?d.splice(y,1)[0]:void 0;if(S){S.mid=this.allocateMid(this.midSuffix?"av":""),S.mLineIndex=p,a.media.push(this.createMediaDescriptionForTransceiver(S,S.direction));return}let v=u.rtp.muxId;if(!v)return;if(u.kind==="application"){let g=u.port===0||this.currentRemoteDescription?.media[p]?.port===0,w=n?.mid===v;if(n&&n.mid==null)n.mid=g?this.allocateMid(this.midSuffix?"dc":""):v,w=!0;if(n&&w){n.mLineIndex=p,a.media.push(this.createMediaDescriptionForSctp(n));return}a.media.push(this.createRejectedMediaDescription({kind:u.kind,profile:u.profile,fmt:u.fmt,codecs:[],mid:v},o))}else{let g=s.find((w)=>w.mid===v);if(!g){h.add(p),a.media.push(this.createRejectedMediaDescription({kind:u.kind,profile:u.profile,fmt:u.fmt,codecs:u.rtp.codecs,mid:v},o));return}if(g.mLineIndex=p,g.stopping||g.stopped){a.media.push(this.createRejectedMediaDescription({kind:u.kind,profile:u.profile,fmt:u.fmt,codecs:u.rtp.codecs,mid:v},this.liveTransportOr(g.dtlsTransport,o)));return}a.media.push(this.createMediaDescriptionForTransceiver(g,g.stopping||g.stopped?"inactive":g.direction))}});for(let u of s.filter((p)=>!p.stopping&&!p.stopped&&!a.media.find((f)=>f.rtp.muxId===p.mid))){if(u.mid==null)u.mid=this.allocateMid(this.midSuffix?"av":"");let p=this.createMediaDescriptionForTransceiver(u,u.direction),f=u.mLineIndex;if(f!=null&&h.has(f)&&a.media[f]?.kind===u.kind)h.delete(f),a.media[f]=p;else u.mLineIndex=a.media.length,a.media.push(p)}if(n&&!a.media.find((u)=>u.kind==="application"&&u.port!==0&&u.rtp.muxId===n.mid)){if(n.mLineIndex=a.media.length,n.mid==null)n.mid=this.allocateMid(this.midSuffix?"dc":"");a.media.push(this.createMediaDescriptionForSctp(n))}if(this.bundlePolicy!=="disable"){let u=a.media.filter((p)=>p.port!==0).map((p)=>p.rtp.muxId).filter((p)=>p);if(u.length){let p=new Ps("BUNDLE",zc(u,this.negotiatedBundleTags.find((f)=>u.includes(f))));a.group.push(p)}}return a}liveTransportOr(s,n){return s&&s.state!=="closed"?s:n}findLiveDtlsTransport(s,n){return[...s.filter((a)=>!a.stopped&&!a.pendingRejection).map((a)=>a.dtlsTransport),n?.dtlsTransport,...s.map((a)=>a.dtlsTransport)].find((a)=>!!a&&a.state!=="closed")}get negotiatedBundleTags(){return([this.currentLocalDescription,this.currentRemoteDescription].find((n)=>n?.type==="answer")?.group??[]).filter((n)=>n.semantic==="BUNDLE").map((n)=>n.items[0])}buildAnswerSdp({transceivers:s,sctpTransport:n,signalingState:a,transportByMid:o}){if(!["have-remote-offer","have-local-pranswer"].includes(a))throw Error("createAnswer failed");if(!this._remoteDescription)throw Error("wrong state");let c=new xr;Tc("answer",c);let d=this._remoteDescription,h=this.findLiveDtlsTransport(s,n),u=new Set;for(let p of d.media){let f,m,y=!0;if(p.port===0){if(p.rtp.muxId)u.add(p.rtp.muxId);m=new bs(p.kind,0,p.profile,p.fmt),m.rtp.muxId=p.rtp.muxId,m.direction="inactive",c.media.push(m);continue}if(["audio","video"].includes(p.kind)){let v=s.find((w)=>w.mid!=null&&w.mid===p.rtp.muxId);if(!v&&p.port!==0)throw Error(`Transceiver with mid=${p.rtp.muxId} not found`);let g=v&&p.port!==0&&!v.stopped&&!v.pendingRejection?this.createMediaDescriptionForTransceiver(v,v.stopping?"inactive":$h(v.direction,v.offerDirection)):void 0;if(!v||!g||g.rtp.codecs.length===0){if(y=!1,p.rtp.muxId)u.add(p.rtp.muxId);f=this.liveTransportOr(v?.dtlsTransport,h),m=this.createRejectedMediaDescription({kind:p.kind,profile:p.profile,fmt:p.fmt,codecs:p.rtp.codecs,mid:p.rtp.muxId},f)}else m=g,f=v.dtlsTransport}else if(p.kind==="application"){if(!n||!n.mid)throw Error("sctpTransport not found");m=this.createMediaDescriptionForSctp(n),f=n.dtlsTransport}else throw Error("invalid kind");let S=p.rtp.muxId&&o?.get(p.rtp.muxId);if(S&&y)f=S,this.addTransportDescription(m,S);if(m.dtlsParams&&f)if(f.role==="auto")m.dtlsParams.role=p.dtlsParams?.role==="client"?"server":"client";else m.dtlsParams.role=f.role;if(y&&p.simulcastParameters&&p.simulcastParameters.length>0)m.simulcastParameters=p.simulcastParameters.map((v)=>({...v,direction:v.direction==="send"?"recv":"send"}));c.media.push(m)}if(this.bundlePolicy!=="disable")c.group.push(...this.buildAnswerBundleGroups(d,c));return c}buildAnswerBundleGroups(s,n){let a=new Set(n.media.filter((c)=>c.port!==0&&c.rtp.muxId).map((c)=>c.rtp.muxId)),o=this.negotiatedBundleTags;return s.group.filter((c)=>c.semantic==="BUNDLE").map((c)=>c.items.filter((d,h,u)=>a.has(d)&&u.indexOf(d)===h)).filter((c)=>c.length>0).map((c)=>new Ps("BUNDLE",zc(c,o.find((d)=>c.includes(d)))))}assertRemoteAnswerCodecs(s){if(!["answer","pranswer"].includes(s.type))return;let n=this.pendingLocalDescription;if(!n)return;s.media.forEach((a,o)=>{if(!["audio","video"].includes(a.kind)||a.port===0)return;let c=n.media[o];if(!c||c.port===0||c.kind!==a.kind)return;if(!a.rtp.codecs.some((h)=>h.name.toLowerCase()!=="rtx"&&c.rtp.codecs.some((u)=>me(u.mimeType)===me(h.mimeType))))throw A("InvalidAccessError",`No common codec for m-line ${o} (mid=${a.rtp.muxId}) in remote ${s.type}`)})}setLocalDescription(s){if(s.type==="offer"||s.type==="pranswer"){this.pendingLocalDescription=s;return}if(this.currentLocalDescription=s,this.pendingRemoteDescription)this.currentRemoteDescription=this.pendingRemoteDescription;this.pendingLocalDescription=void 0,this.pendingRemoteDescription=void 0}setRemoteDescription(s,n){if(!s.type)throw Error("invalid sessionDescription");if(s.type==="rollback"){if(!["have-remote-offer","have-local-pranswer","have-remote-pranswer"].includes(n))throw A("InvalidStateError","Cannot rollback remote description in signaling state");this.pendingLocalDescription=void 0,this.pendingRemoteDescription=void 0;return}if(!s.sdp)throw Error("invalid sessionDescription");let a=this.parseSdp({sdp:s.sdp,isLocal:!1,signalingState:n,type:s.type});return this.validateRemoteDescription(a),this.applyRemoteDescription(a),a}validateRemoteDescription(s){this.assertRemoteAnswerCodecs(s)}applyRemoteDescription(s){if(s.type==="offer"||s.type==="pranswer")this.pendingRemoteDescription=s;else{if(this.pendingLocalDescription)this.currentLocalDescription=this.pendingLocalDescription;this.currentRemoteDescription=s,this.pendingRemoteDescription=void 0,this.pendingLocalDescription=void 0}}rollbackLocalDescription(s){if(!["have-local-offer","have-local-pranswer","have-remote-pranswer"].includes(s))throw A("InvalidStateError","Cannot rollback local description in signaling state");this.pendingLocalDescription=void 0,this.pendingRemoteDescription=void 0}registerMid(s){this.seenMid.add(s)}get remoteIsBundled(){let s=this._remoteDescription;if(!s)return;return s.group.find((a)=>a.semantic==="BUNDLE"&&this.bundlePolicy!=="disable")}offerNewAssociation(s,n,a,o){if(s.type==="offer"&&n.dtlsParams&&a.state==="new"&&o?.get(n.rtp.muxId??"")===a)n.dtlsParams.role="auto"}setLocal(s,n,a,o){let c=new Map(n.map((p)=>[p?.mLineIndex,p])),d=n.find((p)=>p?.dtlsTransport)?.dtlsTransport??a?.dtlsTransport,h=s===this.currentLocalDescription||s===this.pendingLocalDescription;s.media.forEach((p,f)=>{if(!["audio","video"].includes(p.kind))return;let m=n.find((g)=>g?.mid!=null&&g.mid===p.rtp.muxId)??c.get(f),y=m&&!m.stopping&&!m.stopped&&!m.pendingRejection;if(p.port===0&&!y)return;let S=p.rtp.muxId&&o?.get(p.rtp.muxId)||m?.dtlsTransport||d;if(!S)throw Error(`dtls transport not found for media index ${f}`);let v=p.port;if(this.addTransportDescription(p,S,{applied:h}),this.offerNewAssociation(s,p,S,o),v===0)p.port=0});let u=s.media.find((p)=>p.kind==="application"&&p.port!==0);if(a&&u){let p=u.rtp.muxId&&o?.get(u.rtp.muxId)||a.dtlsTransport;this.addTransportDescription(u,p,{applied:h}),this.offerNewAssociation(s,u,p,o)}if(s===this.currentLocalDescription)return;this.setLocalDescription(s)}};function zc(s,n){if(!n||!s.includes(n))return s;return[n,...s.filter((a)=>a!==n)]}var qc=_("werift:packages/webrtc/src/transport/secureTransportManager.ts"),Nv=class{connectionState="new";iceConnectionState="new";iceGatheringState="new";certificate;iceGatheringStateChange=new E;iceConnectionStateChange=new E;onIceCandidate=new E;connectionStateChange=new E;config;lastLocalCredentials;transceiverManager;sctpManager;constructor({config:s,transceiverManager:n,sctpManager:a}){if(this.config=s,this.transceiverManager=n,this.sctpManager=a,this.config.dtls){let{keys:o}=this.config.dtls;if(this.config.certificates[0])this.certificate=this.config.certificates[0];else if(o)this.setupCertificate(o)}}get dtlsTransports(){return Wc([...this.transceiverManager.getTransceivers().filter((s)=>!s.stopped).map((s)=>s.dtlsTransport),this.sctpManager.sctpTransport?.dtlsTransport])}get allDtlsTransports(){return Wc([...this.transceiverManager.getTransceivers().map((s)=>s?.dtlsTransport),this.sctpManager.sctpTransport?.dtlsTransport])}get iceTransports(){return this.dtlsTransports.map((s)=>s.iceTransport)}setupCertificate(s){this.certificate=new Vh(s.keyPem,s.certPem,s.signatureHash)}resolveIceServerOptions(){let s=SS(this.config.iceServers),n=vS({parsedTurnTransport:s.turnTransport,configuredTurnTransport:this.config.turnTransport,forceTurnTCP:this.config.forceTurnTCP});return{stunServer:s.stunServer,turnServer:s.turnServer,turnUsername:s.turnUsername,turnPassword:s.turnPassword,turnTransport:n}}updateIceServers(){let s={...this.resolveIceServerOptions(),forceTurn:this.config.iceTransportPolicy==="relay",useTcp:this.config.iceUseTcp,turnUdpFamily:this.config.turnUdpFamily};for(let n of this.iceTransports)if(n.gatheringState==="new")n.setIceServers(s);else n.deferIceServers(s)}createTransport(s=!0){let n=typeof s==="boolean"?!s:s.inheritCredentials!==!1,a=!n,o=n?this.iceTransports.find((p)=>p.state!=="closed"):void 0,c=new OS({...this.resolveIceServerOptions(),iceLite:this.config.iceLite,forceTurn:this.config.iceTransportPolicy==="relay",portRange:this.config.icePortRange,interfaceAddresses:this.config.iceInterfaceAddresses,additionalHostAddresses:this.config.iceAdditionalHostAddresses,filterStunResponse:this.config.iceFilterStunResponse,filterCandidatePair:this.config.iceFilterCandidatePair,localPasswordPrefix:this.config.icePasswordPrefix,useIpv4:this.config.iceUseIpv4,useIpv6:this.config.iceUseIpv6,useTcp:this.config.iceUseTcp,tcpPassive:this.config.iceTcpPassive,stunGatherTimeout:this.config.iceStunGatherTimeout,turnConnectTimeout:this.config.iceTurnConnectTimeout,turnTlsOptions:this.config.turnTlsOptions,turnUdpFamily:this.config.turnUdpFamily,useLinkLocalAddress:this.config.iceUseLinkLocalAddress}),d=o?{usernameFragment:o.connection.localUsername,password:o.connection.localPassword}:!a?this.lastLocalCredentials:void 0;if(d)c.connection.localUsername=d.usernameFragment,c.connection.localPassword=d.password;if(!a)this.lastLocalCredentials={usernameFragment:c.connection.localUsername,password:c.connection.localPassword};c.onGatheringStateChange.subscribe(()=>{this.updateIceGatheringState()}),this.updateIceGatheringState();let h=new NS(c);return h.onStateChange.subscribe(()=>{this.updateIceConnectionState()}),new mc(this.config,h,this.certificate,Ov)}handleNewIceCandidate({candidate:s,sdpMid:n,sdpMLineIndex:a}){if(s.sdpMid=n,s.sdpMLineIndex=a,s.foundation&&!s.foundation.startsWith("candidate:"))s.foundation="candidate:"+s.foundation;return this.onIceCandidate.execute(s),s}async addIceCandidate(s,n,a=!0){let o=n?.candidate,c=n?.sdpMid,d=n?.sdpMLineIndex,h=n?.usernameFragment,u=n==null||o==null||o==="",p=this.resolveCandidateMediaIndices({sdp:s,isEndOfCandidates:u,sdpMid:c,sdpMLineIndex:d,usernameFragment:h});if(u){let v=p.filter((w)=>!s.media[w]?.iceCandidatesComplete);if(v.length===0)return;let g=v.map((w)=>this.getTransportByMLineIndex(s,w)).filter((w)=>!!w).reduce((w,T)=>{if(!w.find(({id:b})=>b===T.id))w.push(T);return w},[]);if(a)for(let w of g)w.deliverRemoteCandidate(void 0);return{kind:"end-of-candidates",mediaIndices:v}}let f=jn.fromJSON(n);if(!f)throw A("OperationError","Failed to parse ICE candidate");let m=p[0],y=s.media[m];if(!y)throw A("OperationError","ICE media section not found");if(f.sdpMid=y.rtp.muxId??void 0,f.sdpMLineIndex=m,y.iceCandidates.some((v)=>v.toJSON().candidate===f.toJSON().candidate))return;if(y.iceCandidatesComplete)return;let S=this.getTransportByMLineIndex(s,m);if(!S&&a){if(this.isRejectedMedia(y))return{kind:"candidate",candidate:f,mediaIndices:[m]};throw A("OperationError","ICE transport not found for candidate")}if(a)S?.deliverRemoteCandidate(f);return{kind:"candidate",candidate:f,mediaIndices:[m]}}resolveCandidateMediaIndices({sdp:s,isEndOfCandidates:n,sdpMid:a,sdpMLineIndex:o,usernameFragment:c}){let d;if(typeof a==="string"){let h=s.media.findIndex((u)=>u.rtp.muxId===a);if(h<0)throw A("OperationError","Media section for sdpMid was not found");d=[h]}else if(typeof o==="number"){if(o<0||o>=s.media.length)throw A("OperationError","Media section for sdpMLineIndex was not found");d=[o]}else if(n)d=s.media.map((h,u)=>u);else throw lt("sdpMid or sdpMLineIndex must be provided with a candidate");if(typeof c==="string"){let h=d.filter((u)=>s.media[u]?.iceParams?.usernameFragment===c);if(h.length===0)throw A("OperationError","No media section matched the ICE usernameFragment");d=h}return d}isRejectedMedia(s){if(s.port===0)return!0;if(!["audio","video"].includes(s.kind))return!1;let n=this.transceiverManager.getTransceivers().find((a)=>a.mid!=null&&a.mid===s.rtp.muxId);return!n||n.stopped||n.stopping||n.pendingRejection}getTransportByMid(s){if(!s)return;let n,a=this.transceiverManager.getTransceivers().find((o)=>o.mid===s);if(a)n=a.dtlsTransport?.iceTransport;else if(!n&&this.sctpManager.sctpTransport?.mid===s)n=this.sctpManager.sctpTransport.dtlsTransport.iceTransport;if(n?.state==="closed")return;return n}getTransportByMLineIndex(s,n){let a=s.media[n];if(!a)return;return this.getTransportByMid(a.rtp.muxId)}restartIce(){for(let n of this.iceTransports)n.restart();let[s]=this.iceTransports;if(s)this.lastLocalCredentials=s.localParameters;this.updateIceGatheringState()}stageIceRestart(s,{answering:n,replacing:a}={}){for(let o of this.iceTransports){let c=o.gatheringState!=="new"&&!!o.getRemoteParameters();if((!s||s.has(o))&&c)o.stageLocalRestart({answering:n,replacing:a});else o.rollbackLocalRestart()}}rollbackStagedIceRestart(){for(let s of this.iceTransports)s.rollbackLocalRestart()}markStagedIceRestartApplied(){for(let s of this.iceTransports)s.markLocalRestartApplied()}discardUnappliedIceRestart(){for(let s of this.iceTransports)s.discardUnappliedLocalRestart()}emitStagedIceCandidates(){for(let s of this.iceTransports)s.emitStagedCandidates()}emitCommittedIceCandidates(){for(let s of this.iceTransports)s.emitCommittedCandidates()}async commitIceRestartIfAnyStaged(){await Promise.all(this.iceTransports.map((n)=>n.commitLocalRestartIfStaged()));let[s]=this.iceTransports;if(s)this.lastLocalCredentials=s.localParameters;this.updateIceGatheringState()}setLocalRole({type:s,role:n}){for(let a of this.dtlsTransports){let o=a.iceTransport;if(o.connection.iceLite)o.connection.iceControlling=!1;else if(o.connection.remoteIsLite)o.connection.iceControlling=!0;else if(s==="offer")o.connection.iceControlling=!0;else o.connection.iceControlling=!1;if(s==="answer"){let c=n(a);if(c)a.role=c}}}updateIceGatheringState(){let s=this.iceTransports;function n(...o){return s.filter((c)=>o.includes(c.gatheringState)).length===s.length}let a;if(s.length&&n("complete"))a="complete";else if(!s.length||n("new","complete"))a="new";else if(s.map((o)=>o.gatheringState).includes("gathering"))a="gathering";else a="new";if(this.iceGatheringState===a)return;this.iceGatheringState=a,this.iceGatheringStateChange.execute(a)}updateIceConnectionState(){let s=this.iceTransports,n;function a(...c){return s.filter((d)=>c.includes(d.state)).length===s.length}function o(...c){return s.some((d)=>c.includes(d.state))}if(this.connectionState==="closed")n="closed";else if(o("failed"))n="failed";else if(o("disconnected"))n="disconnected";else if(a("new","closed"))n="new";else if(o("new","checking"))n="checking";else if(a("completed","closed"))n="completed";else if(a("connected","completed","closed"))n="connected";else n="new";if(this.iceConnectionState===n)return;if(qc("iceConnectionStateChange",n),this.iceConnectionState=n,this.iceConnectionStateChange.execute(n),n==="failed"&&this.connectionState!=="closed")this.setConnectionState("failed");else if(n==="disconnected"&&this.connectionState==="connected")this.setConnectionState("disconnected")}async gatherCandidates(){await Promise.allSettled(this.iceTransports.filter((s)=>s.state!=="closed"&&s.gatheringState==="new").map((s)=>s.gather()))}setConnectionState(s){if(this.connectionState===s)return;qc("connectionStateChange",s),this.connectionState=s,this.connectionStateChange.execute(s)}async getStats(s){let n=[];for(let a of this.dtlsTransports){let o=await a.getStats(s);if(o)n.push(...o)}return n}async ensureCerts(){if(!this.certificate)this.certificate=await mc.SetupCertificate();for(let s of this.dtlsTransports)s.localCertificate=this.certificate}async close(){this.setConnectionState("closed"),await Promise.allSettled([...this.allDtlsTransports.map((s)=>s.stop())]),this.iceGatheringStateChange.allUnsubscribe(),this.iceConnectionStateChange.allUnsubscribe(),this.onIceCandidate.allUnsubscribe(),this.connectionStateChange.allUnsubscribe()}};function Wc(s){return s.reduce((n,a)=>{if(a&&!n.map((o)=>o.id).includes(a.id))n.push(a);return n},[])}var Ov=[dc.SRTP_AEAD_AES_128_GCM,dc.SRTP_AES128_CM_HMAC_SHA1_80],pe=_("werift:packages/webrtc/src/peerConnection.ts"),ol=class extends Fs{id=Uc().toString();cname=Uc().toString();config=nl();signalingState="stable";negotiationNeed=new Iv({signalingState:()=>this.signalingState,isClosed:()=>this.isClosed,invalidate:()=>this.invalidateLastCreatedDescriptions(),fire:()=>{if(this.onNegotiationneeded.execute(),this.onnegotiationneeded)this.onnegotiationneeded(new globalThis.Event("negotiationneeded"));this.emit("negotiationneeded")}});iceRestartRequest=new Ev;get negotiationneeded(){return this.negotiationNeed.flag}set negotiationneeded(s){this.negotiationNeed.flag=s}get needRestart(){return this.iceRestartRequest.requested}set needRestart(s){if(s)this.iceRestartRequest.requested=!0;else this.iceRestartRequest.clear()}router=new rv;sdpManager;transceiverManager;sctpManager;secureManager;negotiation;topology;remoteCandidates;validator;remoteMedia;activation;isClosed=!1;applyingIceRestart=!1;descriptionTail={done:Promise.resolve(),applied:Promise.resolve()};markDescriptionApplied=()=>{};lastCreatedAnswer;lastCreatedOffer;createdOffer;iceGatheringStateChange=new E;iceConnectionStateChange=new E;signalingStateChange=new E;connectionStateChange=new E;onDataChannel=new E;onRemoteTransceiverAdded=new E;onTransceiverAdded=new E;onIceCandidate=new E;onNegotiationneeded=new E;onTrack=new E;eventHandlers={};get ondatachannel(){return this.eventHandlers.ondatachannel??null}set ondatachannel(s){this.eventHandlers.ondatachannel=s??void 0}get onicecandidate(){return this.eventHandlers.onicecandidate??null}set onicecandidate(s){this.eventHandlers.onicecandidate=s??void 0}get onicecandidateerror(){return this.eventHandlers.onicecandidateerror??null}set onicecandidateerror(s){this.eventHandlers.onicecandidateerror=s??void 0}get onicegatheringstatechange(){return this.eventHandlers.onicegatheringstatechange??null}set onicegatheringstatechange(s){this.eventHandlers.onicegatheringstatechange=s??void 0}get onnegotiationneeded(){return this.eventHandlers.onnegotiationneeded??null}set onnegotiationneeded(s){this.eventHandlers.onnegotiationneeded=s??void 0}get onsignalingstatechange(){return this.eventHandlers.onsignalingstatechange??null}set onsignalingstatechange(s){this.eventHandlers.onsignalingstatechange=s??void 0}get ontrack(){return this.eventHandlers.ontrack??null}set ontrack(s){this.eventHandlers.ontrack=s??void 0}get onconnectionstatechange(){return this.eventHandlers.onconnectionstatechange??null}set onconnectionstatechange(s){this.eventHandlers.onconnectionstatechange=s??void 0}get oniceconnectionstatechange(){return this.eventHandlers.oniceconnectionstatechange??null}set oniceconnectionstatechange(s){this.eventHandlers.oniceconnectionstatechange=s??void 0}constructor(s={}){super();this.setConfiguration(s),this.sdpManager=new Uv({cname:this.cname,bundlePolicy:this.config.bundlePolicy,mLineReuse:this.config.mLineReuse}),this.transceiverManager=new uv(this.cname,this.config,this.router),this.transceiverManager.onTransceiverAdded.pipe(this.onTransceiverAdded),this.transceiverManager.onRemoteTransceiverAdded.pipe(this.onRemoteTransceiverAdded),this.transceiverManager.onTrack.subscribe(({track:n,streams:a,transceiver:o})=>{let c=new bv({track:n,streams:a,transceiver:o,receiver:o.receiver});if(this.onTrack.execute(n),this.emit("track",c),this.ontrack)this.ontrack(c)}),this.transceiverManager.onNegotiationNeeded.subscribe(()=>this.needNegotiation()),this.sctpManager=new Dv,this.negotiation=new Bv(this.sdpManager,this.transceiverManager,this.router,this.sctpManager),this.topology=new Rv(this.sdpManager,this.transceiverManager,this.sctpManager,this.negotiation,()=>this.findOrCreateTransport(!0),()=>this.isClosed),this.remoteMedia=new Av(this.sdpManager,this.transceiverManager,this.sctpManager,this.router,this.negotiation,{createSctpTransport:()=>this.createSctpTransport(),createTransport:()=>this.findOrCreateTransport(),createOwnerTransport:()=>this.createOwnerTransport(),onRemoteTransceiverAdded:(n)=>this.onRemoteTransceiverAdded.execute(n)}),this.validator=new Cv(this.config,this.sdpManager,this.transceiverManager,this.sctpManager,this.negotiation,this.topology),this.sctpManager.onDataChannel.subscribe((n)=>{this.onDataChannel.execute(n);let a={type:"datachannel",channel:n};this.ondatachannel?.(a),this.emit("datachannel",a)}),this.secureManager=new Nv({config:this.config,sctpManager:this.sctpManager,transceiverManager:this.transceiverManager}),this.remoteCandidates=new Pv(this.sdpManager,this.secureManager,this.negotiation,this.topology,{signalingState:()=>this.signalingState,hasRemoteDescription:()=>!!this.remoteDescription&&!!this.sdpManager._remoteDescription}),this.activation=new xv(this.sdpManager,this.secureManager,this.transceiverManager,this.sctpManager,this.negotiation,this.topology,{signalingState:()=>this.signalingState,createTransport:()=>this.findOrCreateTransport()}),this.secureManager.iceGatheringStateChange.subscribe((n)=>{this.iceGatheringStateChange.execute(n),this.onicegatheringstatechange?.(new globalThis.Event("icegatheringstatechange")),this.emit("icegatheringstatechange")}),this.secureManager.iceConnectionStateChange.subscribe((n)=>{if(n==="closed")this.close();this.iceConnectionStateChange.execute(n),this.oniceconnectionstatechange?.(),this.emit("iceconnectionstatechange")}),this.secureManager.connectionStateChange.subscribe((n)=>{this.connectionStateChange.execute(n),this.onconnectionstatechange?.(),this.emit("connectionstatechange")}),this.secureManager.onIceCandidate.subscribe((n)=>{let a=n?n.toJSON():void 0;this.onIceCandidate.execute(a);let o={type:"icecandidate",candidate:a};this.onicecandidate?.(o),this.emit("icecandidate",o)})}get connectionState(){return this.secureManager.connectionState}get iceConnectionState(){return this.secureManager.iceConnectionState}get iceGathererState(){return this.secureManager.iceGatheringState}get iceGatheringState(){return this.secureManager.iceGatheringState}get dtlsTransports(){return this.secureManager.dtlsTransports}get sctpTransport(){return this.sctpManager.sctpTransport}get sctp(){return this.sctpTransport??null}get sctpRemotePort(){return this.sctpManager.sctpRemotePort}get iceTransports(){return this.secureManager.iceTransports}get extIdUriMap(){return this.router.extIdUriMap}get iceGeneration(){return this.iceTransports[0].connection.generation}get localDescription(){return this.sdpManager.localDescription??null}get currentLocalDescription(){return this.sdpManager.currentLocalDescription?.toJSON()??null}get pendingLocalDescription(){return this.sdpManager.pendingLocalDescription?.toJSON()??null}get remoteDescription(){return this.sdpManager.remoteDescription??null}get currentRemoteDescription(){return this.sdpManager.currentRemoteDescription?.toJSON()??null}get pendingRemoteDescription(){return this.sdpManager.pendingRemoteDescription?.toJSON()??null}get canTrickleIceCandidates(){let s=this.sdpManager._remoteDescription;if(!s)return null;return[s.iceOptions,...s.media.map((a)=>a.iceOptions)].filter((a)=>!!a).join(" ").split(/\s+/).includes("trickle")}get remoteIsBundled(){return this.sdpManager.remoteIsBundled}get _localDescription(){return this.sdpManager._localDescription}get _remoteDescription(){return this.sdpManager._remoteDescription}getTransceivers(){return this.transceiverManager.getTransceivers()}getSenders(){return this.transceiverManager.getSenders()}getReceivers(){return this.transceiverManager.getReceivers()}setConfiguration(s){let n=!!this.sdpManager,a=dv(this.config,s,{isReconfiguration:n,hasLocalDescription:n&&!!this.localDescription,hasSctpTransport:!!this.sctpManager?.sctpTransport});if(this.router.keyFrameRequestRouting=this.config.keyFrameRequestRouting,this.sctpManager?.sctpTransport)this.sctpManager.sctpTransport.maxMessageSize=this.config.maxMessageSize;if(n&&this.secureManager&&(a.iceServers!==void 0||a.turnUdpFamily!==void 0))this.secureManager.updateIceServers()}getConfiguration(){return cv(this.config)}createOffer(s={}){return this.enqueueDescriptionOperation(()=>this.createOfferNow(s))}async createOfferNow({iceRestart:s}={}){if(this.signalingState==="stable")this.negotiation.snapshotForOffer();if(!!s||this.needRestart)if(this.sdpManager.currentLocalDescription&&this.sdpManager.currentRemoteDescription)this.secureManager.stageIceRestart(void 0,{replacing:this.iceRestartRequest.replacing});else this.iceRestartRequest.clear(),this.secureManager.restartIce();else if(["stable","have-local-offer","have-remote-pranswer"].includes(this.signalingState))this.secureManager.discardUnappliedIceRestart();await this.secureManager.ensureCerts();for(let m of this.transceiverManager.getTransceivers()){if(m.codecs.length===0||m.codecPreferencesNeedResolution)this.transceiverManager.assignTransceiverCodecs(m);if(m.headerExtensions.length===0)m.headerExtensions=this.config.headerExtensions[m.kind]??[]}let a=["have-remote-offer","have-local-pranswer"].includes(this.signalingState),o=this.transceiverManager.getTransceivers(),c=o.map((m)=>[m.mid,m.mLineIndex]),d=this.sctpTransport,h=d&&[d.mid,d.mLineIndex],u=this.sdpManager.buildOfferSdp(o,this.sctpTransport),p=new Map(o.filter((m)=>m.mid!=null).map((m)=>[m.mid,m]));if(a){if(o.forEach((m,y)=>{[m.mid,m.mLineIndex]=c[y]}),d&&h)[d.mid,d.mLineIndex]=h}let f=u.toJSON();return this.lastCreatedOffer=f,this.createdOffer={sdp:f.sdp,transceiverByMid:p,changeSeq:this.negotiationNeed.noteCreatedOffer()},f}createSctpTransport(){let s=this.sctpManager.createSctpTransport(this.config.maxMessageSize,this.config.sctp),n=this.findOrCreateTransport();return s.setDtlsTransport(n),s}createDataChannel(s,n={}){if(!this.sctpTransport)this.createSctpTransport(),this.needNegotiation();let a=this.sctpManager.createDataChannel(s,n);if(!a.sctp.dtlsTransport){let o=this.findOrCreateTransport();a.sctp.setDtlsTransport(o)}return a}removeTrack(s){if(this.isClosed)throw A("InvalidStateError","peer closed");if(this.transceiverManager.removeTrack(s))this.needNegotiation()}needNegotiation=()=>{this.negotiationNeed.change()};planOfferAssignments(s,n){let a=this.transceiverManager.getTransceivers(),o=this.createdOffer?.sdp===n?this.createdOffer:void 0,c=[];for(let[d,h]of s.media.entries()){let u=h.rtp.muxId;if(!u||!["audio","video"].includes(h.kind))continue;let p=a.find((f)=>f.mid===u);if(!p){let f=o?.transceiverByMid.get(u);if(f&&f.mid==null&&!f.stopped&&a.includes(f))p=f}if(p)c.push({transceiver:p,mid:u,index:d})}return c}selectDescribedIceGenerations(s){for(let n of s.media){if(n.port===0||!n.iceParams||!n.rtp.muxId)continue;(this.negotiation.transportByMid.get(n.rtp.muxId)??this.topology.currentTransportForMid(n.rtp.muxId))?.iceTransport.selectLocalGeneration(n.iceParams.usernameFragment,n.iceParams.password)}}invalidateLastCreatedDescriptions(){this.lastCreatedAnswer=void 0,this.lastCreatedOffer=void 0}async waitForPendingDescriptionTask(){await Promise.resolve(),this.assertOpenAfterYield()}async enqueueDescriptionOperation(s,{afterApplied:n=!1}={}){this.assertNotClosed();let a=this.descriptionTail,o,c,d=new Promise((u)=>{o=u}),h=new Promise((u)=>{c=u});this.descriptionTail=n?{done:Promise.all([a.done,d]).then(()=>{return}),applied:Promise.all([a.applied,d]).then(()=>{return})}:{done:d,applied:h};try{if(await(n?a.applied:a.done),this.assertOpenAfterYield(),!n)this.markDescriptionApplied=c;let u;try{u=await s()}catch(p){throw this.assertOpenAfterYield(),p}return this.assertOpenAfterYield(),u}finally{c(),o()}}findOrCreateTransport(s=!1){this.assertNotClosed();let n=this.dtlsTransports.find((d)=>d.state!=="closed"),a=n?.iceTransport;if(!s&&(this.sdpManager.bundlePolicy==="max-bundle"||this.sdpManager.bundlePolicy!=="disable"&&this.remoteIsBundled)){if(n)return n}let o=this.secureManager.createTransport(s);o.onRtp.subscribe((d)=>{this.router.routeRtp(d)}),o.onRtcp.subscribe((d)=>{this.router.routeRtcp(d)}),this.negotiation.noteCreatedTransport(o);let c=o.iceTransport;return c.onNegotiationNeeded.subscribe(()=>{this.needNegotiation()}),c.onIceCandidate.subscribe((d)=>{if(this.applyingIceRestart||this.negotiation.isPendingOnlyTransport(c.id))return;if(!this.localDescription){pe("localDescription not found when ice candidate was gathered");return}if(!d){if(this.sdpManager.setLocal(this._localDescription,this.transceiverManager.getTransceivers(),this.sctpTransport,this.negotiation.transportByMid),this.onIceCandidate.execute(void 0),this.onicecandidate)this.onicecandidate({candidate:void 0});this.emit("icecandidate",{candidate:void 0});return}if(!this._localDescription){pe("localDescription not found when ice candidate was gathered");return}let h=this.resolveLocalCandidateOwner(c);if(!h){pe("no accepted m-line owns the ice transport",c.id);return}this.secureManager.handleNewIceCandidate({candidate:d,sdpMid:h.mid,sdpMLineIndex:h.index})}),o}resolveLocalCandidateOwner(s){let n=this._localDescription;if(!n)return;let a=n.media.map((d,h)=>({media:d,index:h})).filter(({media:d})=>{if(d.port===0)return!1;let h=d.rtp.muxId;if(d.kind==="application")return!!this.sctpTransport&&this.sctpTransport.mid===h&&this.sctpTransport.dtlsTransport?.iceTransport.id===s.id;return this.transceiverManager.getTransceivers().find((p)=>p.mid===h&&!p.stopped)?.dtlsTransport?.iceTransport.id===s.id}),o=n.group.filter((d)=>d.semantic==="BUNDLE").map((d)=>d.items[0]),c=a.find(({media:d})=>o.includes(d.rtp.muxId))??a[0];if(!c)return;return{mid:c.media.rtp.muxId,index:c.index}}settleStoppingTransceivers(){let s=new Set((this.sdpManager.currentLocalDescription?.media??[]).filter((a)=>a.port!==0&&a.rtp.muxId).map((a)=>a.rtp.muxId)),n=this.transceiverManager.settleStoppingTransceivers(s);return this.closeIdleTransports(),n}closeIdleTransports(s=this.transceiverManager.getTransceivers().filter((n)=>n.stopped).map((n)=>n.dtlsTransport)){let n=new Set(this.dtlsTransports.map((a)=>a.id));for(let a of this.negotiation.transportByMid.values())n.add(a.id);for(let a of new Set(s)){if(!a||a.state==="closed"||n.has(a.id))continue;a.stop().catch((o)=>{pe("failed to close idle transport",o)})}}async setLocalDescription(s){return this.enqueueDescriptionOperation(async()=>{let n=["stable","have-local-offer","have-remote-pranswer"];if(await this.waitForPendingDescriptionTask(),s?.type==="rollback"){if(this.negotiation.retireRemoteGeneration(this.sdpManager.pendingRemoteDescription),this.sdpManager.rollbackLocalDescription(this.signalingState),this.secureManager.rollbackStagedIceRestart(),await this.negotiation.rollback(),this.assertOpenAfterYield(),await this.activation.cleanupInitialProvisional(),this.assertOpenAfterYield(),this.setSignalingState("stable"),this.negotiationNeed.discardPendingOffer(),this.negotiationNeed.recheck||this.needRestart)this.negotiationNeed.schedule();this.invalidateLastCreatedDescriptions();return}let o=!s?.type||!s.sdp||s.sdp.length===0?s?.type==="offer"?this.lastCreatedOffer??await this.createOfferNow():s?.type==="answer"||s?.type==="pranswer"?this.lastCreatedAnswer??await this.createAnswerNow():n.includes(this.signalingState)?this.lastCreatedOffer??await this.createOfferNow():this.lastCreatedAnswer??await this.createAnswerNow():void 0;if(this.assertOpenAfterYield(),s={type:s?.type??o.type,sdp:s?.sdp&&s.sdp.length>0?s.sdp:o.sdp},s.type==="offer"&&s.sdp!==this.createdOffer?.sdp)throw A("InvalidModificationError","setLocalDescription must use the latest created offer");let c=s.type,d=this.sdpManager.parseSdp({sdp:s.sdp,isLocal:!0,signalingState:this.signalingState,type:c}),h=d.type==="offer"?this.planOfferAssignments(d,s.sdp):[],u=d.type==="offer"&&this.sctpTransport?d.media.map((g,w)=>({media:g,index:w})).find(({media:g})=>g.kind==="application"&&g.port!==0&&!!g.rtp.muxId&&(this.sctpTransport.mid==null||this.sctpTransport.mid===g.rtp.muxId)):void 0,p=new Map(h.map(({mid:g,transceiver:w})=>[g,w.dtlsTransport]));if(u&&this.sctpTransport)p.set(u.media.rtp.muxId,this.sctpTransport.dtlsTransport);this.validator.validateLocal(d,(g)=>p.get(g));let f=d.type==="offer"?await this.topology.stageLocalOffer(d,p):void 0;this.assertOpenAfterYield();try{if(d.type==="offer"&&this.signalingState==="have-remote-pranswer")this.negotiation.retireRemoteGeneration(this.sdpManager.pendingRemoteDescription),this.sdpManager.setRemoteDescription({type:"rollback"},this.signalingState),this.secureManager.rollbackStagedIceRestart(),await this.negotiation.rollback(),this.assertOpenAfterYield(),await this.activation.cleanupInitialProvisional(),this.assertOpenAfterYield(),this.setSignalingState("stable"),this.assertOpenAfterYield();if(d.type==="offer"){if(this.signalingState==="have-local-offer")await this.negotiation.replace(),this.assertOpenAfterYield(),this.sdpManager.pendingLocalDescription=void 0;else this.negotiation.begin({fromCreatedOffer:!0});for(let{transceiver:g,mid:w,index:T}of h)g.mid=w,g.mLineIndex=T,g.pendingLocalOfferCodecs=[...d.media[T].rtp.codecs];if(u&&this.sctpTransport)this.sctpTransport.mid=u.media.rtp.muxId,this.sctpTransport.mLineIndex=u.index}if(this.selectDescribedIceGenerations(d),this.negotiation.validate(),this.negotiation.prepare(),f)this.topology.installLocalOffer(d,f)}catch(g){throw await Promise.allSettled((f??[]).filter(({transport:w,pendingOnly:T})=>T&&!this.negotiation.isPendingOnlyTransport(w.iceTransport.id)).map(({transport:w})=>w.stop())),g}let m=[];if(d.type==="answer"||d.type==="pranswer")for(let g of this.transceiverManager.getTransceivers()){if(!g.mid||g.stopping||g.stopped)continue;let w=d.media.find((b)=>b.rtp.muxId===g.mid&&b.kind===g.kind&&b.port!==0);if(!w||w.rtp.codecs.length===0)continue;let T=g.codecs;if(g.codecs=[...w.rtp.codecs],!Hv(T,g.codecs))m.push(g)}if(d.type==="answer"&&this.sdpManager.currentRemoteDescription){this.topology.applyPending(d),await this.commitIceRestartIfAnyStaged(),this.assertOpenAfterYield(),await this.activation.activatePendingRemote(),this.assertOpenAfterYield();for(let g of this.transceiverManager.getTransceivers())if(g.mid&&g.codecs.length>0)g.sender.prepareSend(this.transceiverManager.getLocalRtpParams(g));this.commitAnsweredCodecs()}if(d.type==="pranswer"&&this.sdpManager.currentRemoteDescription){await this.activation.activatePendingRemote(!0),this.assertOpenAfterYield();for(let g of this.transceiverManager.getTransceivers())if(g.mid&&g.codecs.length>0)g.sender.prepareSend(this.transceiverManager.getLocalRtpParams(g))}if((d.type==="answer"||d.type==="pranswer")&&!this.sdpManager.currentRemoteDescription)this.commitAnsweredCodecs();for(let g of m)g.codecPreferencesNeedResolution=!0;for(let[g,w]of Kc(d.media)){let T=w.rtp.muxId;if(this.sdpManager.registerMid(T),["audio","video"].includes(w.kind)&&w.port!==0){let b=this.transceiverManager.getTransceivers().find((C)=>C.mLineIndex===g&&!C.stopped&&C.kind===w.kind&&(C.mid==null||C.mid===T));if(b)b.mid=T}if(w.kind==="application"&&w.port!==0&&this.sctpTransport)this.sctpTransport.mid=T}let y=d.media.find((g)=>g.dtlsParams)?.dtlsParams?.role,S=new Map;for(let g of d.media){let w=this.topology.currentTransportForMid(g.rtp.muxId??""),T=g.dtlsParams?.role;if(w&&T&&!S.has(w))S.set(w,T)}if(this.secureManager.setLocalRole({type:d.type==="offer"?"offer":"answer",role:(g)=>S.get(g)??(g.role==="auto"?y:void 0)}),["answer","pranswer"].includes(d.type)){let g=new Set(d.media.map((w)=>w.rtp.muxId));for(let w of this.transceiverManager.getTransceivers()){if(!w.mid||!g.has(w.mid))continue;if(w.stopped||w.pendingRejection)continue;let T=d.media.find((C)=>C.rtp.muxId===w.mid&&C.port!==0)?.direction,b=w.stopping?"inactive":T??$h(w.direction,w.offerDirection);w.setCurrentDirection(b)}}if(d.type==="answer"){this.transceiverManager.commitRemoteOffer();for(let g of d.media){if(!["audio","video"].includes(g.kind)||g.port!==0)continue;this.transceiverManager.getTransceivers().find((T)=>T.mid===g.rtp.muxId&&!T.stopped)?.commitStopped({rejected:!0})}}if(this.sdpManager.setLocal(d,this.transceiverManager.getTransceivers(),this.sctpTransport,this.negotiation.transportByMid),d.type==="offer")this.secureManager.markStagedIceRestartApplied(),this.negotiation.settle(),this.negotiationNeed.noteAppliedOffer(this.createdOffer.changeSeq),this.setSignalingState("have-local-offer");else if(d.type==="answer")this.setSignalingState("stable");else if(d.type==="pranswer")this.secureManager.markStagedIceRestartApplied(),this.negotiation.stopUnusedProposalChecks(this.topology.transportsOf(d)),this.negotiation.settle(),this.setSignalingState("have-local-pranswer");if(this.assertOpenAfterYield(),d.type==="offer")this.secureManager.emitStagedIceCandidates();else if(d.type==="answer")this.secureManager.emitCommittedIceCandidates();if(["offer","answer","pranswer"].includes(d.type)){let g=this.negotiation.takePreparedCandidateTransports();for(let w of g){let T=d.media.findIndex((b)=>this.negotiation.transportByMid.get(b.rtp.muxId??"")===w);if(T<0)continue;for(let b of w.iceTransport.localCandidates){let C=Object.assign(Object.create(Object.getPrototypeOf(b)),b,{sdpMid:d.media[T].rtp.muxId,sdpMLineIndex:T});if(C.foundation&&!C.foundation.startsWith("candidate:"))C.foundation=`candidate:${C.foundation}`;this.secureManager.onIceCandidate.execute(C)}}if(g.length>0)this.secureManager.onIceCandidate.execute(void 0)}if(d.type==="answer")await this.negotiation.commit(),this.assertOpenAfterYield(),this.completeEndedCurrentGenerations();if(this.markDescriptionApplied(),await this.gatherCandidates().catch((g)=>{pe("gatherCandidates failed",g)}),this.assertOpenAfterYield(),d.type==="answer"||d.type==="pranswer"){if(d.type==="pranswer")this.activation.connectPending().catch((g)=>pe("pending connect failed",g));this.activation.connect().catch((g)=>{pe("connect failed",g),this.secureManager.setConnectionState("failed")})}if(this.sdpManager.setLocal(d,this.transceiverManager.getTransceivers(),this.sctpTransport,this.negotiation.transportByMid),d.type==="answer")this.iceRestartRequest.settle(this.sdpManager.currentLocalDescription);let v=d.type==="answer"&&this.settleStoppingTransceivers();if(this.negotiationNeed.recheck||v)this.negotiationNeed.schedule();return this.invalidateLastCreatedDescriptions(),d})}async gatherCandidates(){await this.secureManager.gatherCandidates()}commitAnsweredCodecs(){for(let s of this.transceiverManager.getTransceivers()){if(!s.mid||s.codecs.length===0||s.stopping||s.stopped||s.pendingRejection)continue;let n=this.sdpManager.pendingRemoteDescription?.media.find((a)=>a.rtp.muxId===s.mid&&a.port!==0);if(n&&["audio","video"].includes(n.kind))this.transceiverManager.commitAnswerCodecs(s,n)}}async commitIceRestartIfAnyStaged(){this.applyingIceRestart=!0;try{await this.secureManager.commitIceRestartIfAnyStaged()}finally{this.applyingIceRestart=!1}}async addIceCandidate(s={}){return this.enqueueDescriptionOperation(async()=>{if(this.isClosed)throw A("InvalidStateError","is closed");if(s=kv(s),!this.remoteDescription||!this.sdpManager._remoteDescription){let n=s?.usernameFragment;if(this.negotiation.isRetiredRemoteUfrag(n))throw A("OperationError","ICE generation was rolled back or replaced");this.remoteCandidates.queued.push(s);return}await this.remoteCandidates.apply(s)},{afterApplied:!0})}restartIce(){this.iceRestartRequest.request(this.sdpManager.currentLocalDescription,this.sdpManager.pendingLocalDescription),this.needNegotiation()}async setRemoteDescription(s){return this.enqueueDescriptionOperation(async()=>{if(s instanceof xr)s=s.toSdp();if(await this.waitForPendingDescriptionTask(),s.type==="rollback"){if(this.negotiation.retireRemoteGeneration(this.sdpManager.pendingRemoteDescription),this.sdpManager.setRemoteDescription(s,this.signalingState),this.secureManager.rollbackStagedIceRestart(),await this.negotiation.rollback(),this.assertOpenAfterYield(),await this.activation.cleanupInitialProvisional(),this.assertOpenAfterYield(),this.setSignalingState("stable"),this.negotiationNeed.discardPendingOffer(),this.negotiationNeed.recheck||this.needRestart)this.negotiationNeed.schedule();this.invalidateLastCreatedDescriptions();return}if(!s.type||!s.sdp)throw A("OperationError","Invalid remote description");let n=this.sdpManager.pendingRemoteDescription;if(n?.type===s.type&&n.toJSON().sdp===s.sdp)return;let a=this.sdpManager.parseSdp({sdp:s.sdp,isLocal:!1,signalingState:this.signalingState,type:s.type});this.validator.validateRemote(a,this.signalingState);let o=this.remoteMedia.planCodecs(a);if(this.remoteCandidates.queued.length>0)await this.remoteCandidates.validateQueued(a),this.assertOpenAfterYield();if(s.type==="offer"&&["have-local-offer","have-local-pranswer"].includes(this.signalingState))this.negotiation.retireRemoteGeneration(this.sdpManager.pendingRemoteDescription),this.sdpManager.rollbackLocalDescription(this.signalingState),this.secureManager.rollbackStagedIceRestart(),await this.negotiation.rollback(),this.assertOpenAfterYield(),await this.activation.cleanupInitialProvisional(),this.assertOpenAfterYield(),this.negotiationNeed.discardPendingOffer(),this.negotiationNeed.recheck=!0,this.setSignalingState("stable"),await new Promise((p)=>setImmediate(p)),this.assertOpenAfterYield();if(a.type==="offer"&&this.signalingState==="have-remote-offer")this.negotiation.retireRemoteGeneration(this.sdpManager.pendingRemoteDescription),await this.negotiation.replace(a),this.assertOpenAfterYield(),this.secureManager.rollbackStagedIceRestart(),this.sdpManager.pendingRemoteDescription=void 0;if(a.type==="offer"&&this.signalingState!=="have-remote-offer")this.negotiation.begin();this.negotiation.validate(),this.negotiation.prepare();let d=a.type==="offer",h=this.negotiation.checkpoint();try{if(a.type==="answer"||a.type==="pranswer")this.negotiation.discardStagedRemoteAnswer();if(a.type==="answer")this.topology.applyPending(a);let{preserveCurrentTransport:p,transportUpdates:f,endOfCandidates:m,provisionalIce:y,associated:S}=this.remoteMedia.apply(a,o);if(a.type==="answer")this.secureManager.discardUnappliedIceRestart(),await this.commitIceRestartIfAnyStaged(),this.assertOpenAfterYield();for(let v of f)v();for(let v of new Set(m))v.deliverRemoteCandidate(void 0);if(p)await this.remoteCandidates.deliverSameGenerationDescription(a),this.assertOpenAfterYield();this.remoteCandidates.completeSharedTransportMedia(a,a.media.map((v,g)=>g));for(let[v,g]of y)await this.activation.applyProvisionalIce(v,g),this.assertOpenAfterYield();if(a.type==="answer"){let v=new Set([this.sdpManager.pendingLocalDescription,this.sdpManager.currentLocalDescription].flatMap((w)=>w?.media.map((T)=>T.rtp.muxId)??[]));for(let w of this.transceiverManager.getTransceivers()){if(S.has(w)||w.mid==null||w.stopped)continue;if(v.has(w.mid))w.commitStopped({rejected:!0});else w.mid=null,w.mLineIndex=void 0}let g=this.sctpTransport;if(g?.mid!=null&&!v.has(g.mid))g.mid=void 0,g.mLineIndex=void 0}}catch(p){if(this.isClosed)throw p;if(d){if(this.secureManager.rollbackStagedIceRestart(),await this.negotiation.rollback(),await this.activation.cleanupInitialProvisional(),this.signalingState!=="stable")this.setSignalingState("stable")}else await this.negotiation.restoreCheckpoint(h);throw p}if(a.type==="offer")this.sdpManager.applyRemoteDescription(a),this.negotiation.settle(),this.setSignalingState("have-remote-offer");else if(a.type==="answer")this.sdpManager.applyRemoteDescription(a),await this.negotiation.commit(),this.assertOpenAfterYield(),this.completeEndedCurrentGenerations(),this.setSignalingState("stable"),this.secureManager.emitCommittedIceCandidates();else if(a.type==="pranswer")this.sdpManager.applyRemoteDescription(a),this.negotiation.stopUnusedProposalChecks(this.topology.transportsOf(a)),this.negotiation.settle(),this.setSignalingState("have-remote-pranswer");if(await this.remoteCandidates.flushQueued(),this.assertOpenAfterYield(),a.type==="answer"||a.type==="pranswer"){if(pe("caller start connect"),a.type==="pranswer")this.activation.connectPending().catch((p)=>pe("pending connect failed",p));this.activation.connect().catch((p)=>{pe("connect failed",p),this.secureManager.setConnectionState("failed")})}if(this.negotiationneeded=!1,a.type==="answer")this.negotiationNeed.commitPendingOffer();if(a.type==="answer")this.iceRestartRequest.settle(this.sdpManager.currentLocalDescription);let u=a.type==="answer"&&this.settleStoppingTransceivers();if(this.negotiationNeed.recheck||u)this.negotiationNeed.schedule();this.invalidateLastCreatedDescriptions()})}completeEndedCurrentGenerations(){let s=this.sdpManager.currentRemoteDescription;if(!s)return;this.remoteCandidates.completeSharedTransportMedia(s,s.media.map((n,a)=>a))}createOwnerTransport(){let s=this.findOrCreateTransport(!0);return this.negotiation.rememberOwnerTransport(s),s}addTransceiver(s,n={}){let a=this.findOrCreateTransport(),o=this.transceiverManager.addTransceiver(s,a,n);return this.secureManager.updateIceConnectionState(),this.needNegotiation(),o}addTrack(s,...n){if(this.isClosed)throw A("InvalidStateError","is closed");let a=this.transceiverManager.addTrack(s,n);if(!a.dtlsTransport){let o=this.findOrCreateTransport();a.setDtlsTransport(o)}return this.needNegotiation(),a.sender}createAnswer(){return this.enqueueDescriptionOperation(()=>this.createAnswerNow())}async createAnswerNow(){this.assertNotClosed(),await this.secureManager.ensureCerts();let s=this.sdpManager.currentRemoteDescription,n=this.sdpManager.pendingRemoteDescription;if(s&&n?.type==="offer"){let c=new Set;for(let[d,h]of this.topology.planPending(n).owners){let u=h.reuse?.iceTransport,p=n.media.find((m)=>m.rtp.muxId===d)?.iceParams?.usernameFragment,f=u?.getRemoteParameters()?.usernameFragment;if(u&&p&&f&&p!==f)c.add(u)}this.secureManager.stageIceRestart(c,{answering:n})}await this.topology.preparePending();for(let c of this.transceiverManager.getTransceivers()){if(c.codecs.length!==0&&!c.codecPreferencesNeedResolution)continue;if(c.pendingRejection||c.stopping||c.stopped)continue;let d=this.sdpManager.pendingRemoteDescription,h=d?.media.find((u)=>u.rtp.muxId!=null&&u.rtp.muxId===c.mid&&u.kind===c.kind)??(c.mLineIndex!=null?d?.media[c.mLineIndex]:void 0);if(h&&["audio","video"].includes(h.kind))this.transceiverManager.refreshAnswerCodecs(c,h);else this.transceiverManager.assignTransceiverCodecs(c);if(c.headerExtensions.length===0)c.headerExtensions=this.config.headerExtensions[c.kind]??[]}let o=this.sdpManager.buildAnswerSdp({transceivers:this.transceiverManager.getTransceivers(),sctpTransport:this.sctpTransport,signalingState:this.signalingState,transportByMid:this.negotiation.transportByMid}).toJSON();return this.lastCreatedAnswer=o,o}assertOpenAfterYield(){this.assertNotClosed()}assertNotClosed(){if(this.isClosed)throw A("InvalidStateError","RTCPeerConnection is closed")}setSignalingState(s){if(this.signalingState===s||this.signalingState==="closed")return;if(pe("signalingStateChange",s),this.signalingState=s,this.signalingStateChange.execute(s),this.onsignalingstatechange)this.onsignalingstatechange(new globalThis.Event("signalingstatechange"));this.emit("signalingstatechange")}createPeerConnectionStats(s){return{type:"peer-connection",id:q("peer-connection",this.id),timestamp:s,dataChannelsOpened:this.sctpManager.dataChannelsOpened,dataChannelsClosed:this.sctpManager.dataChannelsClosed}}async getStats(s){let n=pt(),a=[];if(!s)a.push(this.createPeerConnectionStats(n));a.push(...this.transceiverManager.collectStats(n));let o=await this.secureManager.getStats(n);if(a.push(...o),!s&&this.sctpTransport){let c=await this.sctpManager.getStats(n);if(c)a.push(...c)}if(!s)return Xr(a);return Xr(a,this.transceiverManager.getStatsRootIds(s))}async close(){if(this.isClosed)return;this.isClosed=!0,this.remoteCandidates.queued.length=0,this.setSignalingState("closed"),this.transceiverManager.close(),await this.sctpManager.close(),await this.negotiation.dispose(),await this.secureManager.close(),this.completePeerEvents(),pe("peerConnection closed")}completePeerEvents(){let s=[this.onDataChannel,this.iceGatheringStateChange,this.iceConnectionStateChange,this.signalingStateChange,this.connectionStateChange,this.onTransceiverAdded,this.onRemoteTransceiverAdded,this.onIceCandidate,this.onNegotiationneeded];for(let n of s)if(!n.ended)n.complete()}};function Hv(s,n){return s.length===n.length&&s.every((a,o)=>a.payloadType===n[o].payloadType&&a.mimeType.toLowerCase()===n[o].mimeType.toLowerCase()&&(a.parameters??"")===(n[o].parameters??""))}var Fv=90000;class Qn{sink;ssrc;payloadType;mtu;timer;onSps;onAccessUnit;parser=new tc;assembler=new _f;sequenceNumber;baseTimeMs=null;accessUnitStartMs=null;framesWritten=0;packetsWritten=0;sawKeyFrame=!1;cachedSps=null;cachedPps=null;constructor(s){if(this.sink=s.sink,this.ssrc=s.ssrc>>>0,this.payloadType=s.payloadType??102,this.mtu=s.mtu??bE,!Number.isSafeInteger(this.mtu)||this.mtu<3)throw Error("H.264 RTP MTU must be an integer of at least 3 bytes.");this.timer=s.timer??i,this.onSps=s.onSps,this.onAccessUnit=s.onAccessUnit,this.sequenceNumber=(s.initialSequenceNumber??0)&65535}writeChunk(s){for(let n of this.parser.push(s))this.consumeNal(n)}primeParameterSets(s,n){if(s)this.cachedSps=Buffer.from(s),this.onSps?.(s);if(n)this.cachedPps=Buffer.from(n)}endOfPacket(){for(let s of this.parser.flush())this.consumeNal(s);for(let s of this.assembler.flushPicture())this.writeAccessUnit(s,this.accessUnitStartMs??this.timer.now()),this.accessUnitStartMs=null}flush(){for(let s of this.parser.flush())this.consumeNal(s);for(let s of this.assembler.flush())this.writeAccessUnit(s,this.accessUnitStartMs??this.timer.now()),this.accessUnitStartMs=null}get stats(){return{framesWritten:this.framesWritten,packetsWritten:this.packetsWritten,sawKeyFrame:this.sawKeyFrame}}consumeNal(s){let n=Is(s);if(n===Md)this.cachedSps=Buffer.from(s),this.onSps?.(s);else if(n===Nd)this.cachedPps=Buffer.from(s);if(VK(s))this.sawKeyFrame=!0;let a=this.assembler.push(s);for(let o of a)this.writeAccessUnit(o,this.accessUnitStartMs??this.timer.now()),this.accessUnitStartMs=null;if(this.accessUnitStartMs===null)this.accessUnitStartMs=this.timer.now()}writeAccessUnit(s,n){let a=this.rtpTimestamp(n),o=s.some(VK),c=AJ(this.withParameterSets(s),this.mtu);if(c.length===0)return;for(let d of c){let h=new Ce({version:2,payloadType:this.payloadType,marker:d.marker,sequenceNumber:this.sequenceNumber,timestamp:a,ssrc:this.ssrc});this.sink.writeRtp(new fe(h,d.payload)),this.sequenceNumber=this.sequenceNumber+1&65535,this.packetsWritten++}this.framesWritten++,this.onAccessUnit?.({timestampMs:n,isIdr:o,rtpPacketCount:c.length})}withParameterSets(s){let n=zv(s);if(!n.hasIdr||n.hasSps&&n.hasPps)return s;let a=[];if(!n.hasSps&&this.cachedSps)a.push(this.cachedSps);if(!n.hasPps&&this.cachedPps)a.push(this.cachedPps);return a.length===0?s:[...a,...s]}rtpTimestamp(s){if(this.baseTimeMs===null)this.baseTimeMs=s;let n=Math.max(0,s-this.baseTimeMs);return Math.round(n*(Fv/1000))>>>0}}function zv(s){let n=!1,a=!1,o=!1;for(let c of s){let d=Is(c);if(d===iy)n=!0;else if(d===Md)a=!0;else if(d===Nd)o=!0}return{hasIdr:n,hasSps:a,hasPps:o}}var qv=0,Wv=1200;class Xn{sink;ssrc;payloadType;mtu;sequenceNumber;timestamp=0;packetsWritten=0;samplesWritten=0;remainder=null;constructor(s){if(this.sink=s.sink,this.ssrc=s.ssrc>>>0,this.payloadType=s.payloadType??qv,this.mtu=s.mtu??Wv,!Number.isFinite(this.mtu)||this.mtu<=0)throw new t(`PCMU RTP MTU must be a positive number of bytes; got ${this.mtu}.`);this.sequenceNumber=(s.initialSequenceNumber??0)&65535}writePcm16Chunk(s){let n=this.remainder?Buffer.concat([this.remainder,s]):s,a=Math.floor(n.length/2);if(this.remainder=n.length%2===0?null:Buffer.from(n.subarray(-1)),a===0)return;let o=Buffer.alloc(a);for(let c=0;c<a;c++)o[c]=Kv(n.readInt16LE(c*2));for(let c=0;c<o.length;c+=this.mtu){let d=o.subarray(c,Math.min(c+this.mtu,o.length)),h=new Ce({version:2,payloadType:this.payloadType,marker:!1,sequenceNumber:this.sequenceNumber,timestamp:this.timestamp,ssrc:this.ssrc});this.sink.writeRtp(new fe(h,Buffer.from(d))),this.sequenceNumber=this.sequenceNumber+1&65535,this.timestamp=this.timestamp+d.length>>>0,this.packetsWritten++}this.samplesWritten+=a}get stats(){return{packetsWritten:this.packetsWritten,samplesWritten:this.samplesWritten}}}function Kv(s){let o=0,c=s;if(c<0)c=-c,o=128;c=Math.min(c,32635)+132;let d=7;for(let u=16384;d>0&&(c&u)===0;u>>=1)d--;let h=c>>d+3&15;return~(o|d<<4|h)&255}var $v=15000;class Jn{endpoint;bearerToken;fetchImpl;requestTimeoutMs;timer;constructor(s){if(!s.endpoint)throw new t("WHIP endpoint URL is required.");this.endpoint=s.endpoint,this.bearerToken=s.bearerToken;let n=s.fetchImpl??(typeof globalThis.fetch==="function"?(a,o)=>globalThis.fetch(a,o):void 0);if(!n)throw new t("No fetch implementation available for WHIP client.");if(this.fetchImpl=n,this.requestTimeoutMs=s.requestTimeoutMs??$v,!Number.isFinite(this.requestTimeoutMs)||this.requestTimeoutMs<=0)throw new t("WHIP request timeout must be a positive number of milliseconds.");this.timer=s.timer??i}async publish(s,n){let a=await this.fetchWithTimeout(this.endpoint,{method:"POST",headers:this.headers({"Content-Type":"application/sdp"}),body:s,signal:n});if(a.status!==201){let u=await this.safeText(a);throw new t(`WHIP ingest failed: expected 201 Created, got ${a.status}${u?` \u2014 ${u}`:""}`)}let o=await this.readTextWithTimeout(a,"POST");if(!o.trim())throw new t("WHIP ingest returned an empty SDP answer.");let c=a.headers.get("location");if(!c)throw new t("WHIP ingest response omitted the required Location header.");let d=this.resolveLocation(c),h=a.headers.get("etag");return{answerSdp:o,resourceUrl:d,etag:h}}async patchCandidate(s,n,a,o){let c=await this.fetchWithTimeout(s,{method:"PATCH",headers:this.headers({"Content-Type":"application/trickle-ice-sdpfrag","If-Match":n}),body:a,signal:o});if(c.status!==204&&c.status!==200)e.debug(`[WHIP] trickle PATCH ${s} returned ${c.status}`)}async delete(s,n){let a=await this.fetchWithTimeout(s,{method:"DELETE",headers:this.headers(),signal:n});if(!a.ok&&a.status!==404)e.warn(`[WHIP] DELETE ${s} returned ${a.status}`)}headers(s={}){let n={...s};if(this.bearerToken)n.Authorization=`Bearer ${this.bearerToken}`;return n}async fetchWithTimeout(s,n){let a=new AbortController,o=()=>a.abort();if(n.signal?.aborted)a.abort();else n.signal?.addEventListener("abort",o,{once:!0});let c=this.timer.setTimeout(()=>a.abort(),this.requestTimeoutMs);try{return await this.fetchImpl(s,{...n,signal:a.signal})}catch(d){if(a.signal.aborted&&!n.signal?.aborted)throw new t(`WHIP ${n.method} request timed out after ${this.requestTimeoutMs}ms.`);throw d}finally{this.timer.clearTimeout(c),n.signal?.removeEventListener("abort",o)}}resolveLocation(s){try{return new URL(s,this.endpoint).toString()}catch{return e.warn(`[WHIP] Could not resolve Location header "${s}" against ${this.endpoint}`),s}}async safeText(s){try{return(await this.readTextWithTimeout(s,"response")).slice(0,300)}catch(n){return e.debug(`[WHIP] failed to read error response body: ${n}`),""}}async readTextWithTimeout(s,n){let a,o=new AbortController;try{let c=s.text();return a=this.timer.setTimeout(()=>o.abort(new t(`WHIP ${n} response body timed out after ${this.requestTimeoutMs}ms.`)),this.requestTimeoutMs),await l(c,{timer:this.timer,signal:o.signal,label:`WHIP ${n} response body`})}finally{if(a)this.timer.clearTimeout(a)}}}function Gv(s){let n=s.trim();return n.startsWith("candidate:")?n:`candidate:${n}`}function jv(s,n){let a=[n.mLine,`a=mid:${s.sdpMid??n.mid}`,`a=ice-ufrag:${n.ice.ufrag}`,`a=ice-pwd:${n.ice.pwd}`];return a.push(`a=${Gv(s.candidate)}`),`${a.join(`\r
15
+ `)}\r
16
+ `}function Vv(s){return[s.mLine,`a=mid:${s.mid}`,`a=ice-ufrag:${s.ice.ufrag}`,`a=ice-pwd:${s.ice.pwd}`,"a=end-of-candidates",""].join(`\r
17
+ `)}class Zn{send;contexts;resourceUrl=null;buffered=[];stopped=!1;constructor(s,n){this.send=s;this.contexts=n}addCandidate(s){if(this.stopped)return;let n=this.contextFor(s.sdpMid);if(!n)return;let a=jv(s,n);if(this.resourceUrl===null)this.buffered.push(a);else this.send(this.resourceUrl,a)}completeGathering(s){if(this.stopped)return;let n=this.contextFor(s);if(!n)return;let a=Vv(n);if(this.resourceUrl===null)this.buffered.push(a);else this.send(this.resourceUrl,a)}setResource(s){if(this.stopped)return;if(this.resourceUrl=s,s===null)return;let n=this.buffered;this.buffered=[];for(let a of n)this.send(s,a)}stop(){this.stopped=!0,this.buffered=[]}contextFor(s){return s===void 0?this.contexts.values().next().value:this.contexts.get(s)}}function dl(s){let n=cl(s.split(/\r?\n(?=m=)/)[0]),a=new Map;for(let o of s.split(/\r?\n(?=m=)/).slice(1)){let c=o.split(/\r?\n/).filter(Boolean),d=c[0],h=c.find((p)=>p.startsWith("a=mid:"))?.slice(6),u={...n,...cl(o)};if(d&&h&&u.ufrag&&u.pwd)a.set(h,{mLine:d,mid:h,ice:{ufrag:u.ufrag,pwd:u.pwd}})}return a}function cl(s){let n=s.match(/^a=ice-ufrag:(.+)$/m)?.[1]?.trim(),a=s.match(/^a=ice-pwd:(.+)$/m)?.[1]?.trim();return{ufrag:n,pwd:a}}class ea{attempt;backoff;maxAttempts;timer;onStateChange;state="idle";stopped=!1;cycleActive=!1;pendingHandle=null;attemptsThisCycle=0;pendingReconnect=!1;constructor(s){this.attempt=s.attempt,this.backoff=No(s.backoff??Q({initialDelayMs:1000,multiplier:2,maxDelayMs:30000})),this.maxAttempts=s.maxAttempts??0,this.timer=s.timer??i,this.onStateChange=s.onStateChange}getState(){return this.state}async start(){if(this.stopped)throw Error("ReconnectController already stopped.");this.cycleActive=!0,this.attemptsThisCycle=1,this.setState("connecting");try{await this.attempt()}catch(s){if(this.cycleActive=!1,this.stopped)return;throw this.setState("failed"),s}if(this.cycleActive=!1,this.stopped)return;this.setState("connected"),this.drainPendingReconnect()}notifyConnectionLost(){if(this.stopped)return;if(this.cycleActive||this.state==="connecting"||this.state==="reconnecting"){this.pendingReconnect=!0;return}this.runReconnectCycle()}stop(){this.stopped=!0,this.pendingReconnect=!1,this.clearPending(),this.setState("stopped")}drainPendingReconnect(){if(this.pendingReconnect&&!this.stopped)this.pendingReconnect=!1,this.runReconnectCycle()}async runReconnectCycle(){if(this.stopped||this.cycleActive)return;this.cycleActive=!0,this.attemptsThisCycle=0,this.setState("reconnecting"),await this.tryOnce()}async tryOnce(){if(this.stopped){this.cycleActive=!1;return}this.attemptsThisCycle++;try{if(await this.attempt(),this.cycleActive=!1,this.stopped)return;this.setState("connected"),this.drainPendingReconnect()}catch(s){e.warn(`[WebRTC] reconnect attempt ${this.attemptsThisCycle} failed: ${r(s)}`),this.scheduleRetryOrFail()}}scheduleRetryOrFail(){if(this.stopped){this.cycleActive=!1;return}if(this.maxAttempts>0&&this.attemptsThisCycle>=this.maxAttempts){this.cycleActive=!1,this.setState("failed");return}let s=this.backoff.delayForAttempt(this.attemptsThisCycle);this.setState("reconnecting"),this.clearPending(),this.pendingHandle=this.timer.setTimeout(()=>{this.pendingHandle=null,this.tryOnce()},s)}clearPending(){if(this.pendingHandle)this.timer.clearTimeout(this.pendingHandle),this.pendingHandle=null}setState(s){if(this.state===s)return;this.state=s,this.onStateChange?.(s)}}function ta(s,n,a,o){let c=Yv(s,n);if(!c)throw Error(`WHIP answer did not include a ${n} m-line.`);let{mediaLine:d,attributeLines:h,sessionDirection:u}=c,p=d.split(/\s+/),f=Number(p[1]),m=new Set(p.slice(3));if(!Number.isFinite(f)||f===0)throw Error(`WHIP answer rejected the requested ${n} m-line.`);let y=h.map((g)=>g.match(/^a=(sendrecv|sendonly|recvonly|inactive)$/)?.[1]).find((g)=>g!==void 0)??u??"sendrecv";if(y!=="recvonly")throw Error(`WHIP answer did not accept receiving ${n} (direction=${y}).`);let S=a==="pcmu"?"0":void 0;if(!(S!==void 0&&m.has(S)||h.some((g)=>Qv(g,m,a,{attributeLines:h,profile:o}))))throw Error(`WHIP answer did not accept ${a.toUpperCase()} ${n}.`)}function Yv(s,n){let a=s.split(/\r?\n/).map((d)=>d.trim()).filter(Boolean),o=a.findIndex((d)=>d.startsWith("m=")),c=a.slice(0,o<0?a.length:o).map((d)=>d.match(/^a=(sendrecv|sendonly|recvonly|inactive)$/)?.[1]).find((d)=>d!==void 0);for(let d=0;d<a.length;d++){if(!a[d].startsWith(`m=${n} `))continue;let h=[];for(let u=d+1;u<a.length;u++){if(a[u].startsWith("m="))break;h.push(a[u])}return{mediaLine:a[d],attributeLines:h,sessionDirection:c}}return null}function Qv(s,n,a,{attributeLines:o,profile:c}){let d=s.match(/^a=rtpmap:(\S+)\s+([^/\s]+)\/(\d+)/i);if(!d||!n.has(d[1])||d[2].toLowerCase()!==a)return!1;if(a!=="h264")return!0;return d[3]==="90000"&&o.some((h)=>{if(!h.startsWith(`a=fmtp:${d[1]} `))return!1;let u=h.slice(h.indexOf(" ")+1),p=/(?:^|;)\s*packetization-mode\s*=\s*1(?:;|$)/i.test(u),f=/(?:^|;)\s*profile-level-id\s*=\s*([0-9a-f]{6})(?:;|$)/i.exec(u)?.[1];return p&&f!==void 0&&Xv(u,f,c)})}function hl(s){return`profile-level-id=${wQ(s)};packetization-mode=1;level-asymmetry-allowed=1`}function Xv(s,n,a){if(!L4(n,a))return!1;if(Number.parseInt(n.slice(4,6),16)>=F4)return!0;let c=/(?:^|;)\s*level-asymmetry-allowed\s*=\s*1(?:;|$)/i.test(s),d=/(?:^|;)\s*max-recv-level\s*=\s*([0-9a-f]{4})(?:;|$)/i.exec(s)?.[1],h=d?Number.parseInt(d.slice(2),16):Number.NaN;return c&&h>=F4}function ll(s){return s.replace(/a=rtcp-mux\r?\n/g,(n)=>`${n}a=rtcp-mux-only\r
18
+ `)}async function ul(s,n,a){if(a)await n.delete(a).catch((o)=>{e.warn(`[WebRtcPublisher] Cancelled WHIP session cleanup failed: ${r(o)}`)});throw await s.close().catch((o)=>{e.warn(`[WebRtcPublisher] Cancelled peer cleanup rejected: ${r(o)}`)}),Error("Publisher closed during establish.")}var pl=5000,Jv=1000;class sa{config;createPeerConnection;whip;timer;onBeforeEstablish;onConnected;onKeyFrameRequest;onSourceFailure;onLifecycleEvent;controller;trickleIce;audioEnabled;h264Profile;pc=null;writer=null;audioWriter=null;resourceUrl=null;activeWhipEtag=null;state="idle";closed=!1;establishing=!1;connectedFired=!1;trickle=null;candidateSub=null;lastKeyFrameRequestMs=Number.NEGATIVE_INFINITY;frameWatchdogHandle=null;frameWatchdogLastFrames=0;frameWatchdogLastAdvanceMs=0;mediaTelemetryInitialized=!1;lastEncodedFrameTimestampUs=null;lastIdrTimestampUs=null;idrRequestCount=0;idrCompletionCount=0;pendingIdrRequests=0;encodedAccessUnitCount=0;publisherRtpPacketCount=0;firstRtpSent=!1;constructor(s,n={}){this.config=s,this.trickleIce=s.trickleIce??!1,this.audioEnabled=s.audioEnabled??!1,this.h264Profile=s.h264Profile??SQ,this.timer=n.timer??i,this.onBeforeEstablish=n.onBeforeEstablish,this.onConnected=n.onConnected,this.onKeyFrameRequest=n.onKeyFrameRequest,this.onSourceFailure=n.onSourceFailure,this.onLifecycleEvent=n.onLifecycleEvent,this.createPeerConnection=n.createPeerConnection??((o)=>new ol({iceServers:o,bundlePolicy:"max-bundle",codecs:{video:[$n({parameters:hl(this.h264Profile)})],...this.audioEnabled?{audio:[ui()]}:{}}}));let a=n.createWhipClient??((o)=>new Jn(o));this.whip=a({endpoint:Zv(s.whipEndpoint,s.streamId),bearerToken:s.bearerToken}),this.controller=new ea({attempt:()=>this.establish(),backoff:s.reconnectBackoff,maxAttempts:s.maxReconnectAttempts,timer:this.timer,onStateChange:(o)=>{this.state=o,n.onStateChange?.(o)}})}async start(){if(this.closed)throw Error("Publisher already closed.");await this.controller.start()}writeH264Chunk(s){this.withH264Writer((n)=>n.writeChunk(s))}endOfH264Packet(){this.withH264Writer((s)=>s.endOfPacket())}withH264Writer(s){try{let n=this.writer?.stats.framesWritten??0;if(this.writer)s(this.writer);this.recordFirstRtpIfConnected(n)}catch(n){let a=n instanceof Error?n:Error(String(n));e.warn(`[WebRTC] stream ${this.config.streamId} emitted an H.264 stream outside its negotiated capability: ${a.message}`),this.notifySourceFailed(a)}}recordFirstRtpIfConnected(s){if(this.firstRtpSent||this.pc?.connectionState!=="connected")return;if((this.writer?.stats.framesWritten??0)<=s)return;this.firstRtpSent=!0,this.onLifecycleEvent?.("first_rtp_sent")}primeH264ParameterSets(s,n){this.writer?.primeParameterSets(s,n)}writePcmAudioChunk(s){this.audioWriter?.writePcm16Chunk(s)}notifySourceFailed(s){if(this.closed)return;let n=s?`: ${s.message}`:"";e.warn(`[WebRTC] stream ${this.config.streamId} capture source failed${n}; reconnecting`),this.onSourceFailure?.(s??Error("Capture source stopped producing media.")),this.controller.notifyConnectionLost()}handleKeyFrameRequest(s){if(this.closed||this.pc!==s||!this.onKeyFrameRequest)return;let n=this.timer.now();if(n-this.lastKeyFrameRequestMs<Jv)return;this.lastKeyFrameRequestMs=n,e.debug(`[WebRTC] stream ${this.config.streamId} received PLI; requesting keyframe`);try{if(this.onKeyFrameRequest())this.noteKeyFrameRequest(),this.resetFrameWatchdogDeadline(s)}catch(a){e.debug(`[WebRTC] keyframe request failed for ${this.config.streamId}: ${a}`)}}getState(){return this.state}getDescriptor(){let s=this.writer?.stats,n=this.audioWriter?.stats;return{streamId:this.config.streamId,state:this.state,whipEndpoint:this.config.whipEndpoint,resourceUrl:this.resourceUrl,iceServers:this.config.iceServers??[],framesSent:s?.framesWritten??0,packetsSent:s?.packetsWritten??0,audioPacketsSent:n?.packetsWritten??0,audioSamplesSent:n?.samplesWritten??0,readiness:this.getReadiness()}}async stop(){this.closed=!0,this.controller.stop(),await this.teardownActiveSession()}async establish(){if(this.closed)throw Error("Publisher closed.");if(this.establishing=!0,this.connectedFired=!1,await this.teardownActiveSession(),await this.onBeforeEstablish?.(),this.closed)throw Error("Publisher closed during pre-establish.");let s=this.createPeerConnection(this.config.iceServers??[]);this.pc=s;try{this.initializeTracks(s);let n=await this.publishOffer(s);if(await this.acceptAnswer(s,n),this.establishing=!1,this.watchConnectionState(s),s.connectionState==="connected")this.fireConnected(s);e.info(`[WebRTC] stream ${this.config.streamId} published to ${this.config.whipEndpoint}`+(n.resourceUrl?` (resource ${n.resourceUrl})`:""))}catch(n){throw await this.cleanupFailedEstablish(s),n}}watchConnectionState(s){if(s.connectionStateChange.subscribe((n)=>{if(this.closed||this.pc!==s)return;if(n==="connected"){this.fireConnected(s);return}if(this.establishing)return;if(n==="failed"||n==="disconnected")e.warn(`[WebRTC] stream ${this.config.streamId} connection ${n}; reconnecting`),this.controller.notifyConnectionLost()}),s.connectionState==="failed"||s.connectionState==="disconnected")this.controller.notifyConnectionLost()}fireConnected(s){if(this.connectedFired||this.pc!==s||this.closed)return;this.connectedFired=!0,this.onLifecycleEvent?.("ice_connected"),Promise.resolve().then(()=>this.onConnected?.()).then(()=>{if(!this.closed&&this.pc===s)this.startFrameWatchdog(s)}).catch((n)=>{e.warn(`[WebRTC] capture start failed for ${this.config.streamId}: ${n}; reconnecting`),this.notifySourceFailed()})}startFrameWatchdog(s){let n=this.config.frameStallTimeoutMs;if(!n||n<=0)return;this.stopFrameWatchdog(),this.frameWatchdogLastFrames=this.writer?.stats.framesWritten??0,this.frameWatchdogLastAdvanceMs=this.timer.now();let a=Math.max(500,Math.min(n,2000));this.frameWatchdogHandle=this.timer.setInterval(()=>this.checkFrameProgress(s,n),a)}resetFrameWatchdogDeadline(s){if(!this.frameWatchdogHandle||this.closed||this.pc!==s||s.connectionState!=="connected")return;this.frameWatchdogLastFrames=this.writer?.stats.framesWritten??0,this.frameWatchdogLastAdvanceMs=this.timer.now()}checkFrameProgress(s,n){if(this.closed||this.establishing||this.pc!==s||s.connectionState!=="connected")return;let a=this.writer?.stats.framesWritten??0;if(a>this.frameWatchdogLastFrames){this.frameWatchdogLastFrames=a,this.frameWatchdogLastAdvanceMs=this.timer.now();return}if(this.timer.now()-this.frameWatchdogLastAdvanceMs>=n)e.warn(`[WebRTC] stream ${this.config.streamId} produced no frames for ${n}ms while connected (framesSent=${a}); treating capture as stalled and reconnecting`),this.stopFrameWatchdog(),this.notifySourceFailed()}stopFrameWatchdog(){if(this.frameWatchdogHandle)this.timer.clearInterval(this.frameWatchdogHandle),this.frameWatchdogHandle=null}noteKeyFrameRequest(){this.mediaTelemetryInitialized=!0,this.idrRequestCount++,this.pendingIdrRequests++}getReadiness(){if(!this.mediaTelemetryInitialized)return{lastEncodedFrameTimestampUs:null,lastIdrTimestampUs:null,idrRequestCount:null,idrCompletionCount:null,encodedAccessUnitCount:null,publisherRtpPacketCount:null,captureSourceState:"not_initialized",lastSourceError:null};return{lastEncodedFrameTimestampUs:this.lastEncodedFrameTimestampUs,lastIdrTimestampUs:this.lastIdrTimestampUs,idrRequestCount:this.idrRequestCount,idrCompletionCount:this.idrCompletionCount,encodedAccessUnitCount:this.encodedAccessUnitCount,publisherRtpPacketCount:this.publisherRtpPacketCount,captureSourceState:"not_initialized",lastSourceError:null}}recordAccessUnit(s){if(this.mediaTelemetryInitialized=!0,this.lastEncodedFrameTimestampUs=s.timestampMs*1000,this.encodedAccessUnitCount++,this.publisherRtpPacketCount+=s.rtpPacketCount,!s.isIdr)return;if(this.lastIdrTimestampUs=s.timestampMs*1000,this.pendingIdrRequests>0)this.pendingIdrRequests--,this.idrCompletionCount++}subscribeTrickle(s){let n=[],a=null,o=(c)=>{if(!a){n.push(c);return}if(c)a.addCandidate({candidate:c.candidate,sdpMid:c.sdpMid,sdpMLineIndex:c.sdpMLineIndex});else a.completeGathering()};return this.candidateSub=s.onIceCandidate.subscribe((c)=>{if(this.pc===s)o(c)}),()=>{if(this.pc!==s||a)return;let c=dl(s.localDescription?.sdp??"");a=new Zn((d,h)=>{let u=this.activeWhipEtag;if(!u)return;this.whip.patchCandidate(d,u,h).catch((p)=>{e.debug(`[WebRTC] trickle candidate PATCH failed: ${p}`)})},c),this.trickle=a;for(let d of n)o(d);n.length=0}}async waitForIceGathering(s){if(s.iceGatheringState==="complete"){this.onLifecycleEvent?.("ice_gathering_complete");return}this.onLifecycleEvent?.("ice_gathering_started");try{await s.iceGatheringStateChange.watch((n)=>n==="complete",pl),this.onLifecycleEvent?.("ice_gathering_complete")}catch{e.warn(`[WebRTC] ICE gathering did not complete within ${pl}ms; publishing partial offer`),this.onLifecycleEvent?.("ice_gathering_timeout")}}async teardownActiveSession(){this.stopFrameWatchdog();let s=this.pc,n=this.resourceUrl;if(this.pc=null,this.writer=null,this.audioWriter=null,this.resourceUrl=null,this.activeWhipEtag=null,this.trickle?.stop(),this.trickle=null,this.candidateSub?.unSubscribe(),this.candidateSub=null,n)try{await this.whip.delete(n)}catch(a){e.debug(`[WebRTC] WHIP delete failed during teardown: ${a}`)}if(s)try{await s.close()}catch(a){e.debug(`[WebRTC] peer close failed during teardown: ${a}`)}}initializeTracks(s){let n=new rs({kind:"video",streamId:this.config.streamId}),a=s.addTransceiver(n,{direction:"sendonly"});if(a.sender.onPictureLossIndication.subscribe(()=>this.handleKeyFrameRequest(s)),this.writer=new Qn({sink:n,ssrc:a.sender.ssrc,mtu:this.config.mtu??bE,timer:this.timer,onSps:(o)=>{let c=RQ(o,this.h264Profile);if(!c.compatible)throw Error(c.reason)},onAccessUnit:(o)=>this.recordAccessUnit(o)}),this.mediaTelemetryInitialized=!0,this.firstRtpSent=!1,this.audioEnabled){let o=new rs({kind:"audio",streamId:this.config.streamId}),c=s.addTransceiver(o,{direction:"sendonly"});this.audioWriter=new Xn({sink:o,ssrc:c.sender.ssrc})}}async publishOffer(s){let n=this.trickleIce?this.subscribeTrickle(s):void 0,a=await s.createOffer();if(await s.setLocalDescription(a),this.onLifecycleEvent?.("sdp_offer_created"),n)n();else await this.waitForIceGathering(s);let o=s.localDescription?.sdp;if(!o)throw Error("Failed to produce a local SDP offer.");let c=await this.whip.publish(ll(o));return this.onLifecycleEvent?.("whip_answer_received"),c}async cleanupFailedEstablish(s){if(this.pc===s){let n=this.resourceUrl;if(this.resourceUrl=null,this.activeWhipEtag=null,this.pc=null,this.writer=null,this.audioWriter=null,this.trickle?.stop(),this.trickle=null,this.candidateSub?.unSubscribe(),this.candidateSub=null,n)await this.whip.delete(n).catch((a)=>{e.warn(`[WebRtcPublisher] Failed WHIP session cleanup: ${r(a)}`)});await s.close().catch((a)=>{e.warn(`[WebRtcPublisher] Failed peer cleanup rejected: ${r(a)}`)})}}async acceptAnswer(s,n){if(this.closed||this.pc!==s)await ul(s,this.whip,n.resourceUrl);if(this.resourceUrl=n.resourceUrl,this.activeWhipEtag=n.etag,this.trickleIce&&!n.etag)throw Error("WHIP server did not return the ETag required for Trickle ICE.");if(this.trickle?.setResource(n.resourceUrl),await s.setRemoteDescription({type:"answer",sdp:n.answerSdp}),ta(n.answerSdp,"video","h264",this.h264Profile),this.audioEnabled)ta(n.answerSdp,"audio","pcmu",this.h264Profile)}}function Zv(s,n){try{let a=new URL(s);if(!a.searchParams.has("streamId"))a.searchParams.set("streamId",n);return a.toString()}catch(a){return e.debug(`[WebRTC] could not append streamId to WHIP endpoint ${s}: ${a}`),s}}import{isDeepStrictEqual as ew}from"util";class ra{context;constructor(s){this.context=s}unaddressedStreamCandidates=()=>{let s=[...this.context.streams.values()],n=s.filter((a)=>!a.initialStartFailed);return n.length>0?n:s};addressedStreamRecord=(s)=>{if(s!==void 0)return this.context.streams.get(s);let n=this.unaddressedStreamCandidates();return n.length===1?n[0]:void 0};leaseStreamRecord=(s)=>{if(s.leaseId===void 0)return;if(s.streamId!==void 0)return this.context.streams.get(s.streamId);let n=s.leaseId;return[...this.context.streams.values()].find((a)=>a.leases.has(n))};callerSubscriptionKind=(s)=>{if(s.allowEndedLease&&s.leaseId&&this.context.endedLeases.has(s.leaseId))return"owner";let a=[...this.addressedStreamRecord(s.streamId)?.leases.values()??[]].filter((o)=>o.sessionUuid===s.sessionUuid);return a.length>0&&a.every((o)=>o.kind==="viewer")?"viewer":"owner"};getWebRtcSubscriptionKind=(s)=>{if(this.context.pruneEndedLeases(),!s.allowEndedLease)this.context.assertLeaseNotEnded(s);let n=this.leaseStreamRecord(s),a=s.leaseId,o=a?n?.leases.get(a):void 0;if(n&&a&&o)return this.context.assertLeaseAccess(n,a,o.sessionUuid,s.sessionUuid),o.kind;return s.existingLeaseOnly?void 0:this.callerSubscriptionKind(s)};getWebRtcStreamControlContext=(s)=>{let n=s.deviceId!==void 0?this.activeStreamForDevice(s.deviceId):this.leaseStreamRecord(s)??this.addressedStreamRecord(s.streamId);if(!n)return;let a=[...n.leases].some(([o,c])=>c.sessionUuid===s.sessionUuid&&c.expiresAt>this.context.dependencies.timer.now()&&(s.leaseId===void 0||o===s.leaseId));return{streamId:n.streamId,deviceId:n.device.deviceId,holdsLease:a,parametersMatch:!s.compareParameters||this.differingConfigKeys(n,s.overrides).length===0}};differingConfigKeys=(s,n)=>{let a=Kq(n);return Object.keys(s.config).filter((c)=>!ew(s.config[c],a[c]))};getWebRtcStreamDeviceIds=()=>[...new Set([...this.context.streams.values()].map((s)=>s.device.deviceId))];isReadinessSatisfied=(s,n)=>{if(n==="publishing")return s.lifecycleState==="publishing";return s.sourceStarted&&(s.lifecycleState==="capture_ready"||s.lifecycleState==="publishing")};stoppedReadinessDescriptor=(s,n,a,o)=>({...this.describeRecord(s,o),state:"stopped",failure:{code:"stopped",message:`WebRTC stream ${n} was stopped while waiting for ${a}.`,at:this.context.dependencies.now().toISOString()},fallback:null});readinessWaitDuration=(s,n)=>n?Math.min(s,this.context.WEBRTC_STREAM_LEASE_TTL_MS/2):s;waitForRecordStateChange=(s,n)=>new Promise((a)=>{let o=this.context.dependencies.timer.setTimeout(()=>{s.stateWaiters.delete(c),a()},n),c=()=>{this.context.dependencies.timer.clearTimeout(o),a()};s.stateWaiters.add(c)});resolveReadinessRecord=(s,n,a,o)=>{let c=this.context.streams.get(s);if(c)return{type:"active",record:c};if(o?.lifecycleState==="stopping")return{type:"stopped",descriptor:this.stoppedReadinessDescriptor(o,s,n,a)};throw new t(`No active WebRTC stream with id ${s}.`)};waitForWebRtcStreamReadiness=async(s,n,a=this.context.DEFAULT_STREAM_READY_TIMEOUT_MS,{leaseId:o,sessionUuid:c}={})=>{if(!Number.isFinite(a)||a<=0)throw new t("WebRTC stream readiness timeout must be a positive number of milliseconds.");let d=this.context.dependencies.timer.now()+a,h=o,u;for(;;){this.context.assertLeaseNotEnded({streamId:s,leaseId:h});let p=this.resolveReadinessRecord(s,n,h,u);if(p.type==="stopped")return p.descriptor;let f=p.record;if(u=f,h!==void 0)h=this.context.acquireLease(f,{requestedLeaseId:h,sessionUuid:c});if(this.isReadinessSatisfied(f,n))return this.describeRecord(f,h);if(f.lifecycleState==="degraded"||f.lifecycleState==="failed")return this.describeRecord(f,h);let m=d-this.context.dependencies.timer.now();if(m<=0)return this.readinessTimeoutDescriptor(f,n,h);await this.waitForRecordStateChange(f,this.readinessWaitDuration(m,Boolean(h)))}};readinessTimeoutDescriptor=(s,n,a)=>{let o=n==="capture_ready"?"capture_ready_timeout":"publishing_timeout";return{...this.describeRecord(s,a),failure:{code:o,message:`Timed out waiting for WebRTC stream ${s.streamId} to reach ${n}.`,at:this.context.dependencies.now().toISOString()},fallback:null}};resolveStreamRecord=(s)=>{if(s){let a=this.context.streams.get(s);if(!a)throw new t(`No active WebRTC stream with id ${s}.`);return a}let n=this.unaddressedStreamCandidates();if(n.length===0)throw new t("No active WebRTC streams. Provide a streamId.");if(n.length>1)throw new t("Multiple active WebRTC streams. Provide a streamId.");return n[0]};activeStreamForDevice=(s)=>{for(let n of this.context.streams.values())if(n.device.deviceId===s&&!n.initialStartFailed)return n;return};leaseExpiryAt=(s,n)=>{let a=s.leases.get(n);if(!a)return;return new Date(this.context.dependencies.now().getTime()+Math.max(0,a.expiresAt-this.context.dependencies.timer.now())).toISOString()};describeRecord=(s,n)=>{let a=s.publisher.getDescriptor(),o=s.source?.getTelemetry?.()??s.sourceTelemetry,c=n?this.leaseExpiryAt(s,n):void 0;return{...a,sourceStarted:s.sourceStarted,readiness:{...a.readiness,...o,captureSourceState:s.sourceState,lastSourceError:s.lastSourceError},frameMetrics:s.frameMetrics,lifecycleState:s.lifecycleState,failure:s.failure,telemetry:s.telemetry,fallback:s.lifecycleState==="degraded"||s.lifecycleState==="failed"?{mode:"screenshots",reason:s.failure?.code??"capture_unavailable"}:null,lease:n&&c?{id:n,expiresAt:c}:null,consumerCount:s.leases.size}};publisherTimestampField=(s)=>({sdp_offer_created:"sdpOffer",ice_gathering_started:"sdpOffer",whip_answer_received:"sdpAnswer",ice_connected:"iceConnected",first_rtp_sent:"firstRtpSent"})[s]}function tw(s){let n=R.sessionManager();return n?Boolean(n.getSession(s)):!1}var ml={idGenerator:B,createPublisher:(s,n)=>new sa(s,n),createSource:(s,n)=>ZO(s,n),resolveVideoJar:(s)=>s.platform==="android"?_0():Promise.resolve(null),now:()=>new Date,timer:i,isSessionLive:tw},N={...ml},F=new Map,rt=new Map,sw=256;function na(){let s=N.timer.now();for(let[n,a]of rt)if(a.expiresAt<=s)rt.delete(n)}function Zs(s){na();let n=s.leaseId?rt.get(s.leaseId):void 0;if(n&&(s.streamId===void 0||n.streamId===s.streamId))throw new GO({reason:n.reason,subscriptionKind:n.kind})}function gl({record:s,leaseId:n,kind:a}){return`deviceId=${s.device.deviceId} streamId=${s.streamId} leaseId=${n} kind=${a}`}function aa(s){let{record:n,leaseId:a,reason:o,cause:c}=s,d=n.leases.get(a);if(!d)return;if(n.leases.delete(a),na(),rt.set(a,{streamId:n.streamId,reason:o,kind:d.kind,expiresAt:N.timer.now()+pi}),rt.size>sw){let u=rt.keys().next().value;if(u!==void 0)rt.delete(u)}let h=`[WebRtcStream] ending subscription: ${gl({record:n,leaseId:a,kind:d.kind})} reason=${o}${c?` cause=${c}`:""}`;if(!c&&(o==="device_removed"||o==="identity_quarantined"))e.warn(h);else e.info(h);vl(n)}var rw=1e4,iw=30000,pi=60000,nw=5000;function yl(s){if(F.get(s.streamId)!==s)return!1;return ca(s),!0}async function as(s,n){await Promise.all(s.filter(yl).map(async(a)=>{try{await l(()=>Tl(a),{timer:N.timer,timeoutMs:nw,label:`WebRTC stream ${a.streamId} cleanup (${n})`})}catch(o){e.warn(`[WebRtcStream] cleanup failed (${n}): ${r(o)}`,o)}}))}function Sl({record:s,...n}){for(let[a,o]of s.leases){let c=KO({kind:o.kind,event:n.reason});aa({record:s,leaseId:a,reason:c.reason,cause:n.cause})}}function aw(s){let n=[...F.values()].filter((a)=>a.device.deviceId===s.deviceId);for(let a of n)Sl({record:a,...s});return as(n,s.reason)}function B0(s,n){let a=[];for(let o of F.values()){if(o.device.deviceId!==s)continue;for(let[c,d]of o.leases)if(d.sessionUuid!==void 0)ow({record:o,leaseId:c,lease:d,resolveIdentity:n});if(o.leases.size===0)a.push(o);else kt(o)}return as(a,"device ownership changed")}function ow(s){let{record:n,leaseId:a,lease:o,resolveIdentity:c}=s,d=jO({...c(o.sessionUuid),kind:o.kind});if(d.action==="end")aa({record:n,leaseId:a,reason:d.reason});else if(d.action==="downgrade")o.kind="viewer",e.info(`[WebRtcStream] downgraded subscription: ${gl({record:n,leaseId:a,kind:o.kind})}`)}function M0(s){let n=[...F.values()];for(let a of n)Sl({record:a,reason:s});return as(n,s)}QZ({stopStreamsForDevice:aw});function D0(s){N={...N,...s}}function U0(){for(let s of F.values())if(s.leaseExpiryHandle)N.timer.clearTimeout(s.leaseExpiryHandle);F.clear(),rt.clear(),N={...ml}}async function cw(s,n){let a=F.get(s);if(a)await n(a)}function kt(s){if(s.leaseExpiryHandle)N.timer.clearTimeout(s.leaseExpiryHandle),s.leaseExpiryHandle=null;let n=Math.min(...Array.from(s.leases.values(),(a)=>a.expiresAt));if(!Number.isFinite(n))return;s.leaseExpiryHandle=N.timer.setTimeout(()=>{if(F.get(s.streamId)!==s)return;let a=N.timer.now();for(let[o,c]of s.leases)if(c.expiresAt<=a)s.leases.delete(o);if(s.leases.size>0){kt(s);return}as([s],"lease expired")},Math.max(0,n-N.timer.now()))}function oa(s,n,a,o){if(a&&o&&a!==o&&N.isSessionLive?.(a))throw new t(`WebRTC lease ${n} for stream ${s.streamId} belongs to another active session.`)}function fi(s,n){let{requestedLeaseId:a,sessionUuid:o,mintIfUnknown:c=!1}=n;if(!c)Zs({streamId:s.streamId,leaseId:a});let d=a===void 0?void 0:s.leases.get(a);if(a!==void 0&&!d&&!c)throw new t(`No active WebRTC lease ${a} for stream ${s.streamId}; call start to resume.`);if(d&&a!==void 0)return oa(s,a,d.sessionUuid,o),d.sessionUuid=o??d.sessionUuid,d.expiresAt=N.timer.now()+pi,kt(s),a;let h=`lease_${N.idGenerator.next()}`;return s.leases.set(h,{expiresAt:N.timer.now()+pi,sessionUuid:o,kind:n.subscriptionKind??"owner"}),kt(s),h}function dw(s,n,a){let o=s.leases.get(n);if(o)oa(s,n,o.sessionUuid,a);let c=s.leases.delete(n);if(c)kt(s);return c}function vl(s){for(let n of s.stateWaiters)n();s.stateWaiters.clear()}function er(s,n){s.lifecycleState=n,vl(s)}function ns(s,n,a,o="failed"){s.failure={code:n,message:r(a),at:N.now().toISOString()},er(s,o)}function hw(s,n){let a=N.now().toISOString(),o=ww(n);if(o)s.telemetry[o]??=a;if(n==="ice_gathering_complete"||n==="ice_gathering_timeout"){let c=Date.parse(s.telemetry.sdpOffer??a);s.telemetry.nonTrickleIceGatheringDelayMs??=Math.max(0,N.now().getTime()-c)}if(n==="ice_connected"&&!s.sourceFailed)er(s,"publishing")}function lw(s,n,a,{jarPath:o,bitrateBps:c,requestReceived:d}){let h={},u=!1,p=N.createPublisher({streamId:s,whipEndpoint:a.whipEndpoint,bearerToken:a.bearerToken,iceServers:a.iceServers,bitrateBps:c,trickleIce:a.trickleIce,audioEnabled:a.audioEnabled,h264Profile:n.platform==="android"?"main":"constrained-baseline",frameStallTimeoutMs:rw},{onBeforeEstablish:async()=>{let y=F.get(s);if(u&&y?.sourceFailed||!y?.sourceStarted)await cw(s,async(S)=>{await wl(S)})},onKeyFrameRequest:()=>F.get(s)?.source?.requestKeyFrame?.()??!1,onConnected:()=>{let y=F.get(s);if(y&&y.publisher===h.current&&!y.sourceFailed)er(y,"publishing"),y.publisher.primeH264ParameterSets(y.cachedSps,y.cachedPps),y.source?.requestKeyFrame?.()},onSourceFailure:(y)=>{let S=F.get(s);if(S&&S.publisher===h.current&&!S.sourceFailed)S.sourceFailed=!0,ns(S,"capture_runtime_failed",y,"degraded")},onLifecycleEvent:(y)=>{let S=F.get(s);if(S&&S.publisher===h.current)hw(S,y)}});h.current=p;let f={config:structuredClone(a),streamId:s,device:n,publisher:p,source:null,jarPath:o,bitrateBps:c,size:a.size,fps:n.platform==="android"?a.androidFps:a.iosSimulatorFps,audioEnabled:a.audioEnabled,startedAt:d,sourceStarted:!1,lifecycleState:"preparing",failure:null,telemetry:{requestReceived:d},sourceFailed:!1,initialStartFailed:!1,mediaParser:new tc,cachedSps:null,cachedPps:null,stateWaiters:new Set,leases:new Map,leaseExpiryHandle:null,sourceState:"not_initialized",lastSourceError:null,sourceTelemetry:null},m=p.start.bind(p);return p.start=async()=>{await m(),u=!0},f}function uw(){return N.captureRegistry??QO()}async function ia(s){if(s.sourceStarted=!1,s.frameMetrics=void 0,s.source){let n=s.source;s.sourceTelemetry=n.getTelemetry?.()??s.sourceTelemetry,s.source=null,s.sourceState="stopped",await n.stop().catch((a)=>{e.warn(`[WebRtcStream] source stop failed: ${r(a)}`,a)})}}function fl(s,n){for(let a of n){let o=Is(a);if(o===Md)s.cachedSps=Buffer.from(a);else if(o===Nd)s.cachedPps=Buffer.from(a);if(o===iy&&!s.telemetry.firstIdr)s.telemetry.firstIdr=N.now().toISOString()}}async function wl(s){if(await ia(s),F.get(s.streamId)!==s)return!1;s.sourceState="starting";let n={current:null};s.sourceFailed=!1,s.mediaParser=new tc;let a=null,o=(c,d)=>{if(s.source!==a)return;if(d&&!s.telemetry.firstMediaFrame)s.telemetry.firstMediaFrame=N.now().toISOString();let h;try{h=s.mediaParser.push(c)}catch(u){s.sourceFailed=!0,ns(s,"capture_runtime_failed",u,"degraded"),s.publisher.notifySourceFailed(u instanceof Error?u:Error(String(u)));return}fl(s,h),s.publisher.writeH264Chunk(c)};a=uw().acquire({device:s.device,create:(c)=>N.createSource(c,s.jarPath),options:{device:s.device,onData:(c)=>o(c,!0),onReplayData:(c)=>o(c,!1),onEncodedAccessUnit:()=>{if(s.source!==a)return;fl(s,s.mediaParser.flush()),s.publisher.endOfH264Packet()},onAudioData:(c)=>{if(s.source===a)s.publisher.writePcmAudioChunk(c)},onError:(c)=>{if(s.source!==a)return;s.sourceState="failed",s.lastSourceError=c.message,s.sourceTelemetry=a?.getTelemetry?.()??s.sourceTelemetry,s.sourceFailed=!0,ns(s,"capture_runtime_failed",c,"degraded"),s.publisher.notifySourceFailed(c)},bitrateBps:s.bitrateBps,size:s.size,fps:s.fps,audioEnabled:s.audioEnabled,onFrameMetrics:(c)=>{if(s.source===n.current)s.frameMetrics=c}}}),n.current=a,s.source=a;try{await a.start()}catch(c){throw s.sourceState="failed",s.lastSourceError=r(c),s.sourceTelemetry=a.getTelemetry?.()??s.sourceTelemetry,s.sourceFailed=!0,ns(s,"capture_start_failed",c,"degraded"),s.publisher.notifySourceFailed(c instanceof Error?c:Error(String(c))),c}if(F.get(s.streamId)!==s){if(s.source===a)await ia(s);return!1}if(s.sourceStarted=!0,s.sourceState="running",s.sourceTelemetry=a.getTelemetry?.()??s.sourceTelemetry,s.telemetry.captureSourcePrepared??=N.now().toISOString(),!s.sourceFailed)s.failure=null,er(s,"capture_ready");return!0}function pw(s){let n=F.get(s);if(!n)return;if(!n.initialStartFailed)throw new t(`WebRTC stream ${s} already active. Stop it first.`);ca(n)}function ca(s){if(F.get(s.streamId)===s)F.delete(s.streamId);if(s.leaseExpiryHandle)N.timer.clearTimeout(s.leaseExpiryHandle),s.leaseExpiryHandle=null}async function Tl(s){er(s,"stopping"),await bl(s)}async function bl(s){await Promise.all([ia(s),s.publisher.stop().catch((n)=>{e.warn(`[WebRtcStream] publisher stop failed: ${r(n)}`,n)})])}async function Rl(s,n){s.initialStartFailed=!0;try{await bl(s)}catch(a){e.warn(`[WebRtcStream] cleanup of failed initial start ${s.streamId} failed: ${r(a)}`,a)}finally{if(s.leases.size<=n)ca(s)}}async function fw(s){try{if(await s.publisher.start(),F.get(s.streamId)!==s)throw Error(`WebRTC stream ${s.streamId} was stopped before startup completed.`)}catch(n){if(F.get(s.streamId)!==s)return;ns(s,s.failure?.code??"whip_publish_failed",n,s.failure?"degraded":"failed"),await Rl(s,0)}}async function mw(s,n){if(n.ownsDevice&&Tw(s,n.overrides).length>0)return await yw({streamId:s.streamId,sessionUuid:n.sessionUuid}),gw({...n,leaseId:void 0,subscriptionKind:"owner"});return le(s,fi(s,{requestedLeaseId:n.leaseId,sessionUuid:n.sessionUuid,subscriptionKind:n.subscriptionKind,mintIfUnknown:!0}))}async function gw(s){let n=N.now().toISOString(),a=vw(s.device.deviceId);if(a)return mw(a,s);let o=Kq(s.overrides),c=s.streamId??`webrtc_${N.idGenerator.next()}`;pw(c);let d=o.bitrateKbps?o.bitrateKbps*1000:void 0,h=lw(c,s.device,o,{jarPath:null,bitrateBps:d,requestReceived:n}),u=fi(h,{requestedLeaseId:s.leaseId,sessionUuid:s.sessionUuid,subscriptionKind:s.subscriptionKind,mintIfUnknown:!0});F.set(c,h);try{if(h.jarPath=await N.resolveVideoJar(s.device),F.get(c)!==h)return{...le(h,u),state:"stopped"};if(!await wl(h))return{...le(h,u),state:"stopped"};return fw(h),le(h,u)}catch(p){if(e.warn(`[WebRtcStream] initial start failed for ${c}: ${r(p)}`,p),F.get(c)===h)ns(h,h.failure?.code??"capture_start_failed",p,"degraded"),await Rl(h,1);return{...le(h,u),state:"stopped"}}}async function N0(s,n,a){Zs({streamId:s,leaseId:n});let o=Il(s);if(n!==void 0&&!dw(o,n,a))throw new t(`No active WebRTC lease ${n} for stream ${o.streamId}.`);if(n!==void 0&&o.leases.size>0)return le(o);if(n===void 0){for(let[c,d]of o.leases)if(d.sessionUuid===void 0||d.sessionUuid===a)o.leases.delete(c);if(Array.from(o.leases.values()).some((c)=>c.sessionUuid&&N.isSessionLive?.(c.sessionUuid)))return kt(o),le(o)}return yl(o),await Tl(o),{...le(o),state:"stopped"}}function Cl(s){return Zs(s),Sw(s)??Il(s.streamId)}async function O0(s){let n=Cl(s),a=[...n.leases].filter(([o,c])=>c.sessionUuid===s.sessionUuid&&(s.leaseId===void 0||o===s.leaseId));if(a.length===0)throw new t("No caller-owned WebRTC leases on the addressed stream.");for(let[o]of a)n.leases.delete(o);if(n.leases.size>0)return kt(n),le(n);return await as([n],"own leases released"),{...le(n),state:"stopped"}}async function yw(s){let n=Cl(s);for(let[a,o]of n.leases)if(o.sessionUuid===s.sessionUuid)n.leases.delete(a);else aa({record:n,leaseId:a,reason:"stopped_by_owner"});return await as([n],"stopped_by_owner"),{...le(n),state:"stopped"}}function H0(){return Array.from(F.values()).map((s)=>le(s))}function F0(s,n,a){Zs({streamId:s,leaseId:n});let o=F.get(s);if(!o)return null;let c=n!==void 0?fi(o,{requestedLeaseId:n,sessionUuid:a}):void 0;return le(o,c)}var El=new ra({get dependencies(){return N},get streams(){return F},get endedLeases(){return rt},pruneEndedLeases:na,assertLeaseNotEnded:Zs,assertLeaseAccess:oa,acquireLease:fi,get DEFAULT_STREAM_READY_TIMEOUT_MS(){return iw},get WEBRTC_STREAM_LEASE_TTL_MS(){return pi}}),{getWebRtcStreamControlContext:z0,getWebRtcStreamDeviceIds:q0,getWebRtcSubscriptionKind:W0,waitForWebRtcStreamReadiness:K0}=El,{leaseStreamRecord:Sw,resolveStreamRecord:Il,describeRecord:le,activeStreamForDevice:vw,publisherTimestampField:ww,differingConfigKeys:Tw}=El;export{iw as DEFAULT_STREAM_READY_TIMEOUT_MS,pi as WEBRTC_STREAM_LEASE_TTL_MS,nw as WEBRTC_STREAM_STOP_TIMEOUT_MS,aw as endWebRtcStreamsForDevice,z0 as getWebRtcStreamControlContext,F0 as getWebRtcStreamDescriptor,q0 as getWebRtcStreamDeviceIds,W0 as getWebRtcSubscriptionKind,H0 as listWebRtcStreams,B0 as reconcileWebRtcStreamsForDeviceOwnership,O0 as releaseWebRtcStreamOwnLeases,U0 as resetWebRtcStreamManager,D0 as setWebRtcStreamManagerDependencies,gw as startWebRtcStream,M0 as stopAllWebRtcStreams,N0 as stopWebRtcStream,yw as stopWebRtcStreamAsOwner,K0 as waitForWebRtcStreamReadiness};
19
+
20
+ //# debugId=5286E6BC0A83340364756E2164756E21