livekit-client 2.18.9 → 2.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (217) hide show
  1. package/dist/livekit-client.e2ee.worker.js +1 -1
  2. package/dist/livekit-client.e2ee.worker.js.map +1 -1
  3. package/dist/livekit-client.e2ee.worker.mjs +5609 -644
  4. package/dist/livekit-client.e2ee.worker.mjs.map +1 -1
  5. package/dist/livekit-client.esm.mjs +3553 -2813
  6. package/dist/livekit-client.esm.mjs.map +1 -1
  7. package/dist/livekit-client.pt.worker.js +2 -0
  8. package/dist/livekit-client.pt.worker.js.map +1 -0
  9. package/dist/livekit-client.pt.worker.mjs +5834 -0
  10. package/dist/livekit-client.pt.worker.mjs.map +1 -0
  11. package/dist/livekit-client.umd.js +1 -1
  12. package/dist/livekit-client.umd.js.map +1 -1
  13. package/dist/src/api/SignalClient.d.ts +2 -1
  14. package/dist/src/api/SignalClient.d.ts.map +1 -1
  15. package/dist/src/e2ee/E2eeManager.d.ts +8 -7
  16. package/dist/src/e2ee/E2eeManager.d.ts.map +1 -1
  17. package/dist/src/e2ee/types.d.ts +35 -8
  18. package/dist/src/e2ee/types.d.ts.map +1 -1
  19. package/dist/src/e2ee/utils.d.ts +5 -5
  20. package/dist/src/e2ee/utils.d.ts.map +1 -1
  21. package/dist/src/e2ee/worker/DataCryptor.d.ts +5 -5
  22. package/dist/src/e2ee/worker/DataCryptor.d.ts.map +1 -1
  23. package/dist/src/e2ee/worker/FrameCryptor.d.ts +21 -4
  24. package/dist/src/e2ee/worker/FrameCryptor.d.ts.map +1 -1
  25. package/dist/src/e2ee/worker/naluUtils.d.ts +1 -1
  26. package/dist/src/e2ee/worker/naluUtils.d.ts.map +1 -1
  27. package/dist/src/e2ee/worker/sifPayload.d.ts +7 -7
  28. package/dist/src/e2ee/worker/sifPayload.d.ts.map +1 -1
  29. package/dist/src/index.d.ts +4 -1
  30. package/dist/src/index.d.ts.map +1 -1
  31. package/dist/src/options.d.ts +7 -0
  32. package/dist/src/options.d.ts.map +1 -1
  33. package/dist/src/packetTrailer/PacketTrailerManager.d.ts +49 -0
  34. package/dist/src/packetTrailer/PacketTrailerManager.d.ts.map +1 -0
  35. package/dist/src/packetTrailer/packetTrailer.d.ts +32 -0
  36. package/dist/src/packetTrailer/packetTrailer.d.ts.map +1 -0
  37. package/dist/src/packetTrailer/types.d.ts +57 -0
  38. package/dist/src/packetTrailer/types.d.ts.map +1 -0
  39. package/dist/src/packetTrailer/utils.d.ts +9 -0
  40. package/dist/src/packetTrailer/utils.d.ts.map +1 -0
  41. package/dist/src/packetTrailer/worker/packetTrailer.worker.d.ts +2 -0
  42. package/dist/src/packetTrailer/worker/packetTrailer.worker.d.ts.map +1 -0
  43. package/dist/src/room/RTCEngine.d.ts +2 -4
  44. package/dist/src/room/RTCEngine.d.ts.map +1 -1
  45. package/dist/src/room/Room.d.ts +7 -3
  46. package/dist/src/room/Room.d.ts.map +1 -1
  47. package/dist/src/room/data-track/RemoteDataTrack.d.ts +5 -1
  48. package/dist/src/room/data-track/RemoteDataTrack.d.ts.map +1 -1
  49. package/dist/src/room/data-track/depacketizer.d.ts +12 -4
  50. package/dist/src/room/data-track/depacketizer.d.ts.map +1 -1
  51. package/dist/src/room/data-track/frame.d.ts +3 -3
  52. package/dist/src/room/data-track/frame.d.ts.map +1 -1
  53. package/dist/src/room/data-track/incoming/IncomingDataTrackManager.d.ts +3 -1
  54. package/dist/src/room/data-track/incoming/IncomingDataTrackManager.d.ts.map +1 -1
  55. package/dist/src/room/data-track/incoming/pipeline.d.ts +4 -1
  56. package/dist/src/room/data-track/incoming/pipeline.d.ts.map +1 -1
  57. package/dist/src/room/data-track/outgoing/types.d.ts +2 -2
  58. package/dist/src/room/data-track/outgoing/types.d.ts.map +1 -1
  59. package/dist/src/room/data-track/packet/extensions.d.ts +4 -4
  60. package/dist/src/room/data-track/packet/extensions.d.ts.map +1 -1
  61. package/dist/src/room/data-track/packet/index.d.ts +5 -5
  62. package/dist/src/room/data-track/packet/index.d.ts.map +1 -1
  63. package/dist/src/room/data-track/packet/serializable.d.ts +1 -1
  64. package/dist/src/room/data-track/packet/serializable.d.ts.map +1 -1
  65. package/dist/src/room/data-track/types.d.ts +7 -0
  66. package/dist/src/room/data-track/types.d.ts.map +1 -1
  67. package/dist/src/room/events.d.ts +2 -2
  68. package/dist/src/room/participant/LocalParticipant.d.ts +8 -14
  69. package/dist/src/room/participant/LocalParticipant.d.ts.map +1 -1
  70. package/dist/src/room/participant/Participant.d.ts +1 -1
  71. package/dist/src/room/participant/Participant.d.ts.map +1 -1
  72. package/dist/src/room/participant/RemoteParticipant.d.ts +5 -1
  73. package/dist/src/room/participant/RemoteParticipant.d.ts.map +1 -1
  74. package/dist/src/room/rpc/client/RpcClientManager.d.ts +39 -0
  75. package/dist/src/room/rpc/client/RpcClientManager.d.ts.map +1 -0
  76. package/dist/src/room/rpc/client/events.d.ts +8 -0
  77. package/dist/src/room/rpc/client/events.d.ts.map +1 -0
  78. package/dist/src/room/rpc/index.d.ts +6 -0
  79. package/dist/src/room/rpc/index.d.ts.map +1 -0
  80. package/dist/src/room/rpc/server/RpcServerManager.d.ts +44 -0
  81. package/dist/src/room/rpc/server/RpcServerManager.d.ts.map +1 -0
  82. package/dist/src/room/rpc/server/events.d.ts +8 -0
  83. package/dist/src/room/rpc/server/events.d.ts.map +1 -0
  84. package/dist/src/room/{rpc.d.ts → rpc/utils.d.ts} +34 -4
  85. package/dist/src/room/rpc/utils.d.ts.map +1 -0
  86. package/dist/src/room/track/PacketTrailerExtractor.d.ts +19 -0
  87. package/dist/src/room/track/PacketTrailerExtractor.d.ts.map +1 -0
  88. package/dist/src/room/track/RemoteVideoTrack.d.ts +16 -0
  89. package/dist/src/room/track/RemoteVideoTrack.d.ts.map +1 -1
  90. package/dist/src/room/track/Track.d.ts +1 -1
  91. package/dist/src/room/track/Track.d.ts.map +1 -1
  92. package/dist/src/room/track/create.d.ts.map +1 -1
  93. package/dist/src/room/track/options.d.ts +10 -0
  94. package/dist/src/room/track/options.d.ts.map +1 -1
  95. package/dist/src/room/track/utils.d.ts.map +1 -1
  96. package/dist/src/room/utils.d.ts +4 -3
  97. package/dist/src/room/utils.d.ts.map +1 -1
  98. package/dist/src/test/MockMediaStreamTrack.d.ts.map +1 -1
  99. package/dist/src/utils/dataPacketBuffer.d.ts +1 -1
  100. package/dist/src/utils/dataPacketBuffer.d.ts.map +1 -1
  101. package/dist/src/version.d.ts +9 -1
  102. package/dist/src/version.d.ts.map +1 -1
  103. package/dist/ts4.2/api/SignalClient.d.ts +2 -1
  104. package/dist/ts4.2/e2ee/E2eeManager.d.ts +8 -7
  105. package/dist/ts4.2/e2ee/types.d.ts +35 -8
  106. package/dist/ts4.2/e2ee/utils.d.ts +5 -5
  107. package/dist/ts4.2/e2ee/worker/DataCryptor.d.ts +5 -5
  108. package/dist/ts4.2/e2ee/worker/FrameCryptor.d.ts +21 -4
  109. package/dist/ts4.2/e2ee/worker/naluUtils.d.ts +1 -1
  110. package/dist/ts4.2/e2ee/worker/sifPayload.d.ts +7 -7
  111. package/dist/ts4.2/index.d.ts +5 -1
  112. package/dist/ts4.2/options.d.ts +7 -0
  113. package/dist/ts4.2/packetTrailer/PacketTrailerManager.d.ts +49 -0
  114. package/dist/ts4.2/packetTrailer/packetTrailer.d.ts +32 -0
  115. package/dist/ts4.2/packetTrailer/types.d.ts +57 -0
  116. package/dist/ts4.2/packetTrailer/utils.d.ts +9 -0
  117. package/dist/ts4.2/packetTrailer/worker/packetTrailer.worker.d.ts +2 -0
  118. package/dist/ts4.2/room/RTCEngine.d.ts +2 -4
  119. package/dist/ts4.2/room/Room.d.ts +7 -3
  120. package/dist/ts4.2/room/data-track/RemoteDataTrack.d.ts +5 -1
  121. package/dist/ts4.2/room/data-track/depacketizer.d.ts +12 -4
  122. package/dist/ts4.2/room/data-track/frame.d.ts +3 -3
  123. package/dist/ts4.2/room/data-track/incoming/IncomingDataTrackManager.d.ts +3 -1
  124. package/dist/ts4.2/room/data-track/incoming/pipeline.d.ts +4 -1
  125. package/dist/ts4.2/room/data-track/outgoing/types.d.ts +2 -2
  126. package/dist/ts4.2/room/data-track/packet/extensions.d.ts +4 -4
  127. package/dist/ts4.2/room/data-track/packet/index.d.ts +5 -5
  128. package/dist/ts4.2/room/data-track/packet/serializable.d.ts +1 -1
  129. package/dist/ts4.2/room/data-track/types.d.ts +7 -0
  130. package/dist/ts4.2/room/events.d.ts +2 -2
  131. package/dist/ts4.2/room/participant/LocalParticipant.d.ts +8 -14
  132. package/dist/ts4.2/room/participant/Participant.d.ts +1 -1
  133. package/dist/ts4.2/room/participant/RemoteParticipant.d.ts +5 -1
  134. package/dist/ts4.2/room/rpc/client/RpcClientManager.d.ts +43 -0
  135. package/dist/ts4.2/room/rpc/client/events.d.ts +8 -0
  136. package/dist/ts4.2/room/rpc/index.d.ts +7 -0
  137. package/dist/ts4.2/room/rpc/server/RpcServerManager.d.ts +44 -0
  138. package/dist/ts4.2/room/rpc/server/events.d.ts +8 -0
  139. package/dist/ts4.2/room/{rpc.d.ts → rpc/utils.d.ts} +34 -4
  140. package/dist/ts4.2/room/track/PacketTrailerExtractor.d.ts +19 -0
  141. package/dist/ts4.2/room/track/RemoteVideoTrack.d.ts +16 -0
  142. package/dist/ts4.2/room/track/Track.d.ts +1 -1
  143. package/dist/ts4.2/room/track/options.d.ts +10 -0
  144. package/dist/ts4.2/room/utils.d.ts +4 -3
  145. package/dist/ts4.2/utils/dataPacketBuffer.d.ts +1 -1
  146. package/dist/ts4.2/version.d.ts +9 -1
  147. package/package.json +24 -16
  148. package/src/api/SignalClient.test.ts +102 -10
  149. package/src/api/SignalClient.ts +4 -2
  150. package/src/api/WebSocketStream.test.ts +0 -1
  151. package/src/e2ee/E2eeManager.ts +82 -30
  152. package/src/e2ee/types.ts +37 -8
  153. package/src/e2ee/utils.ts +7 -6
  154. package/src/e2ee/worker/DataCryptor.ts +6 -6
  155. package/src/e2ee/worker/FrameCryptor.test.ts +177 -4
  156. package/src/e2ee/worker/FrameCryptor.ts +94 -14
  157. package/src/e2ee/worker/ParticipantKeyHandler.test.ts +4 -4
  158. package/src/e2ee/worker/e2ee.worker.ts +13 -5
  159. package/src/e2ee/worker/naluUtils.ts +4 -4
  160. package/src/e2ee/worker/sifPayload.ts +10 -8
  161. package/src/index.ts +7 -0
  162. package/src/options.ts +8 -0
  163. package/src/packetTrailer/PacketTrailerManager.test.ts +172 -0
  164. package/src/packetTrailer/PacketTrailerManager.ts +250 -0
  165. package/src/packetTrailer/packetTrailer.test.ts +174 -0
  166. package/src/packetTrailer/packetTrailer.ts +276 -0
  167. package/src/packetTrailer/types.ts +75 -0
  168. package/src/packetTrailer/utils.test.ts +105 -0
  169. package/src/packetTrailer/utils.ts +50 -0
  170. package/src/packetTrailer/worker/packetTrailer.worker.ts +155 -0
  171. package/src/packetTrailer/worker/tsconfig.json +14 -0
  172. package/src/room/BackOffStrategy.test.ts +1 -1
  173. package/src/room/RTCEngine.test.ts +219 -0
  174. package/src/room/RTCEngine.ts +86 -46
  175. package/src/room/Room.test.ts +62 -1
  176. package/src/room/Room.ts +111 -86
  177. package/src/room/data-track/RemoteDataTrack.ts +8 -1
  178. package/src/room/data-track/depacketizer.test.ts +433 -1
  179. package/src/room/data-track/depacketizer.ts +79 -61
  180. package/src/room/data-track/frame.ts +2 -2
  181. package/src/room/data-track/incoming/IncomingDataTrackManager.test.ts +194 -0
  182. package/src/room/data-track/incoming/IncomingDataTrackManager.ts +21 -1
  183. package/src/room/data-track/incoming/pipeline.ts +13 -2
  184. package/src/room/data-track/outgoing/types.ts +3 -2
  185. package/src/room/data-track/packet/extensions.ts +2 -2
  186. package/src/room/data-track/packet/index.ts +6 -6
  187. package/src/room/data-track/packet/serializable.ts +1 -1
  188. package/src/room/data-track/types.ts +8 -0
  189. package/src/room/events.ts +2 -2
  190. package/src/room/participant/LocalParticipant.test.ts +81 -0
  191. package/src/room/participant/LocalParticipant.ts +64 -187
  192. package/src/room/participant/Participant.ts +1 -1
  193. package/src/room/participant/RemoteParticipant.ts +9 -0
  194. package/src/room/participant/publishUtils.ts +1 -1
  195. package/src/room/rpc/client/RpcClientManager.test.ts +430 -0
  196. package/src/room/rpc/client/RpcClientManager.ts +269 -0
  197. package/src/room/rpc/client/events.ts +9 -0
  198. package/src/room/rpc/index.ts +14 -0
  199. package/src/room/rpc/server/RpcServerManager.test.ts +471 -0
  200. package/src/room/rpc/server/RpcServerManager.ts +293 -0
  201. package/src/room/rpc/server/events.ts +9 -0
  202. package/src/room/{rpc.ts → rpc/utils.ts} +49 -8
  203. package/src/room/track/PacketTrailerExtractor.ts +43 -0
  204. package/src/room/track/RemoteVideoTrack.ts +23 -2
  205. package/src/room/track/Track.ts +1 -1
  206. package/src/room/track/create.ts +0 -4
  207. package/src/room/track/options.ts +11 -0
  208. package/src/room/track/record.ts +1 -1
  209. package/src/room/track/utils.ts +4 -1
  210. package/src/room/utils.test.ts +14 -1
  211. package/src/room/utils.ts +19 -4
  212. package/src/test/MockMediaStreamTrack.ts +0 -1
  213. package/src/type-polyfills/non-shared-typed-arrays.d.ts +6 -0
  214. package/src/utils/dataPacketBuffer.ts +1 -1
  215. package/src/version.ts +11 -1
  216. package/dist/src/room/rpc.d.ts.map +0 -1
  217. package/src/room/rpc.test.ts +0 -301
@@ -1,2 +1,2 @@
1
- !function(e){"function"==typeof define&&define.amd?define(e):e()}((function(){"use strict";function e(e,t,n,r){return new(n||(n=Promise))((function(i,o){function a(e){try{c(r.next(e))}catch(e){o(e)}}function s(e){try{c(r.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(a,s)}c((r=r.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;var t,n={exports:{}};var r,i,o,a,s,c=(t||(t=1,i=n.exports,o=function(){var e=function(){},t="undefined",n=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),r=["trace","debug","info","warn","error"],i={},o=null;function a(e,t){var n=e[t];if("function"==typeof n.bind)return n.bind(e);try{return Function.prototype.bind.call(n,e)}catch(t){return function(){return Function.prototype.apply.apply(n,[e,arguments])}}}function s(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function c(){for(var n=this.getLevel(),i=0;i<r.length;i++){var o=r[i];this[o]=i<n?e:this.methodFactory(o,n,this.name)}if(this.log=this.debug,typeof console===t&&n<this.levels.SILENT)return"No console available for logging"}function d(e){return function(){typeof console!==t&&(c.call(this),this[e].apply(this,arguments))}}function u(r,i,o){return function(r){return"debug"===r&&(r="log"),typeof console!==t&&("trace"===r&&n?s:void 0!==console[r]?a(console,r):void 0!==console.log?a(console,"log"):e)}(r)||d.apply(this,arguments)}function l(e,n){var a,s,d,l=this,y="loglevel";function p(){var e;if(typeof window!==t&&y){try{e=window.localStorage[y]}catch(e){}if(typeof e===t)try{var n=window.document.cookie,r=encodeURIComponent(y),i=n.indexOf(r+"=");-1!==i&&(e=/^([^;]+)/.exec(n.slice(i+r.length+1))[1])}catch(e){}return void 0===l.levels[e]&&(e=void 0),e}}function h(e){var t=e;if("string"==typeof t&&void 0!==l.levels[t.toUpperCase()]&&(t=l.levels[t.toUpperCase()]),"number"==typeof t&&t>=0&&t<=l.levels.SILENT)return t;throw new TypeError("log.setLevel() called with invalid level: "+e)}"string"==typeof e?y+=":"+e:"symbol"==typeof e&&(y=void 0),l.name=e,l.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},l.methodFactory=n||u,l.getLevel=function(){return null!=d?d:null!=s?s:a},l.setLevel=function(e,n){return d=h(e),!1!==n&&function(e){var n=(r[e]||"silent").toUpperCase();if(typeof window!==t&&y){try{return void(window.localStorage[y]=n)}catch(e){}try{window.document.cookie=encodeURIComponent(y)+"="+n+";"}catch(e){}}}(d),c.call(l)},l.setDefaultLevel=function(e){s=h(e),p()||l.setLevel(e,!1)},l.resetLevel=function(){d=null,function(){if(typeof window!==t&&y){try{window.localStorage.removeItem(y)}catch(e){}try{window.document.cookie=encodeURIComponent(y)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch(e){}}}(),c.call(l)},l.enableAll=function(e){l.setLevel(l.levels.TRACE,e)},l.disableAll=function(e){l.setLevel(l.levels.SILENT,e)},l.rebuild=function(){if(o!==l&&(a=h(o.getLevel())),c.call(l),o===l)for(var e in i)i[e].rebuild()},a=h(o?o.getLevel():"WARN");var f=p();null!=f&&(d=h(f)),c.call(l)}(o=new l).getLogger=function(e){if("symbol"!=typeof e&&"string"!=typeof e||""===e)throw new TypeError("You must supply a name when creating a logger.");var t=i[e];return t||(t=i[e]=new l(e,o.methodFactory)),t};var y=typeof window!==t?window.log:void 0;return o.noConflict=function(){return typeof window!==t&&window.log===o&&(window.log=y),o},o.getLoggers=function(){return i},o.default=o,o},(r=n).exports?r.exports=o():i.log=o()),n.exports);!function(e){e[e.trace=0]="trace",e[e.debug=1]="debug",e[e.info=2]="info",e[e.warn=3]="warn",e[e.error=4]="error",e[e.silent=5]="silent"}(a||(a={})),function(e){e.Default="livekit",e.Room="livekit-room",e.TokenSource="livekit-token-source",e.Participant="livekit-participant",e.Track="livekit-track",e.Publication="livekit-track-publication",e.Engine="livekit-engine",e.Signal="livekit-signal",e.PCManager="livekit-pc-manager",e.PCTransport="livekit-pc-transport",e.E2EE="lk-e2ee",e.DataTracks="livekit-data-tracks"}(s||(s={}));let d=c.getLogger(s.Default);Object.values(s).map((e=>c.getLogger(e))),d.setDefaultLevel(a.info);const u=c.getLogger(s.E2EE);var l,y=Object.defineProperty,p=(e,t,n)=>((e,t,n)=>t in e?y(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n)(e,"symbol"!=typeof t?t+"":t,n);class h{constructor(){p(this,"_locking"),p(this,"_locks"),this._locking=Promise.resolve(),this._locks=0}isLocked(){return this._locks>0}lock(){let e;this._locks+=1;const t=new Promise((t=>e=()=>{this._locks-=1,t()})),n=this._locking.then((()=>e));return this._locking=this._locking.then((()=>t)),n}}!function(e){e[e.WAITING=0]="WAITING",e[e.RUNNING=1]="RUNNING",e[e.COMPLETED=2]="COMPLETED"}(l||(l={}));const f="AES-GCM",g={key:10,delta:3,audio:1,empty:0},v={sharedKey:!1,ratchetSalt:"LKFrameEncryptionKey",ratchetWindowSize:8,failureTolerance:10,keyringSize:16,keySize:128};class m extends Error{constructor(e,t,n){super(t||"an error has occurred"),this.name="LiveKitError",this.code=e,void 0!==(null==n?void 0:n.cause)&&(this.cause=null==n?void 0:n.cause)}}var I,w,b,k,L,_,E,S;!function(e){e[e.NotAllowed=0]="NotAllowed",e[e.ServerUnreachable=1]="ServerUnreachable",e[e.InternalError=2]="InternalError",e[e.Cancelled=3]="Cancelled",e[e.LeaveRequest=4]="LeaveRequest",e[e.Timeout=5]="Timeout",e[e.WebSocket=6]="WebSocket",e[e.ServiceNotFound=7]="ServiceNotFound"}(I||(I={})),function(e){e[e.AlreadyOpened=0]="AlreadyOpened",e[e.AbnormalEnd=1]="AbnormalEnd",e[e.DecodeFailed=2]="DecodeFailed",e[e.LengthExceeded=3]="LengthExceeded",e[e.Incomplete=4]="Incomplete",e[e.HandlerAlreadyRegistered=7]="HandlerAlreadyRegistered",e[e.EncryptionTypeMismatch=8]="EncryptionTypeMismatch"}(w||(w={})),function(e){e.PermissionDenied="PermissionDenied",e.NotFound="NotFound",e.DeviceInUse="DeviceInUse",e.Other="Other"}(b||(b={})),function(e){e.getFailure=function(t){if(t&&"name"in t)return"NotFoundError"===t.name||"DevicesNotFoundError"===t.name?e.NotFound:"NotAllowedError"===t.name||"PermissionDeniedError"===t.name?e.PermissionDenied:"NotReadableError"===t.name||"TrackStartError"===t.name?e.DeviceInUse:e.Other}}(b||(b={})),function(e){e[e.InvalidKey=0]="InvalidKey",e[e.MissingKey=1]="MissingKey",e[e.InternalError=2]="InternalError"}(k||(k={}));class T extends m{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:k.InternalError,n=arguments.length>2?arguments[2]:void 0;super(40,e),this.reason=t,this.participantIdentity=n}}function A(e,t){const n=(new TextEncoder).encode(t);switch(e){case"HKDF":return{name:"HKDF",salt:n,hash:"SHA-256",info:new ArrayBuffer(128)};case"PBKDF2":return{name:"PBKDF2",salt:n,hash:"SHA-256",iterations:1e5};default:throw new Error("algorithm ".concat(e," is currently unsupported"))}}function R(t,n){return e(this,void 0,void 0,(function*(){const e=A(t.algorithm.name,n.ratchetSalt),r=yield crypto.subtle.deriveKey(e,t,{name:f,length:n.keySize},!1,["encrypt","decrypt"]);return{material:t,encryptionKey:r}}))}!function(e){e.SetKey="setKey",e.RatchetRequest="ratchetRequest",e.KeyRatcheted="keyRatcheted"}(L||(L={})),function(e){e.KeyRatcheted="keyRatcheted"}(_||(_={})),function(e){e.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",e.EncryptionError="encryptionError"}(E||(E={})),function(e){e.Error="cryptorError"}(S||(S={}));class C{static makeIV(e){const t=new ArrayBuffer(12),n=new DataView(t),r=crypto.getRandomValues(new Uint32Array(1));return n.setUint32(0,r[0]),n.setUint32(4,e),n.setUint32(8,e-C.sendCount%65535),C.sendCount++,t}static encrypt(t,n){return e(this,void 0,void 0,(function*(){const e=C.makeIV(performance.now()),r=yield n.getKeySet();if(!r)throw new Error("No key set found");const i=yield crypto.subtle.encrypt({name:f,iv:e},r.encryptionKey,new Uint8Array(t));return{payload:new Uint8Array(i),iv:new Uint8Array(e),keyIndex:n.getCurrentKeyIndex()}}))}static decrypt(t,n,r){return e(this,arguments,void 0,(function(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,i=arguments.length>4?arguments[4]:void 0,o=arguments.length>5&&void 0!==arguments[5]?arguments[5]:{ratchetCount:0};return function*(){const a=yield n.getKeySet(r);if(!a)throw new Error("No key set found");try{const n=yield crypto.subtle.decrypt({name:f,iv:t},a.encryptionKey,new Uint8Array(e));return{payload:new Uint8Array(n)}}catch(s){if(n.keyProviderOptions.ratchetWindowSize>0){if(o.ratchetCount<n.keyProviderOptions.ratchetWindowSize){let s,c;u.debug("DataCryptor: ratcheting key attempt ".concat(o.ratchetCount," of ").concat(n.keyProviderOptions.ratchetWindowSize,", for data packet")),(null!=i?i:a)===n.getKeySet(r)&&(c=yield n.ratchetKey(r,!1),s=yield R(c.cryptoKey,n.keyProviderOptions));const d=yield C.decrypt(e,t,n,r,i,{ratchetCount:o.ratchetCount+1,encryptionKey:null==s?void 0:s.encryptionKey});return d&&s&&(null!=i?i:a)===n.getKeySet(r)&&(n.setKeySet(s,r,c),n.setCurrentKeyIndex(r)),d}throw u.warn("DataCryptor: maximum ratchet attempts exceeded"),new T("DataCryptor: valid key missing for participant ".concat(n.participantIdentity),k.InvalidKey,n.participantIdentity)}throw new T("DataCryptor: Decryption failed: ".concat(s.message),k.InvalidKey,n.participantIdentity)}}()}))}}C.sendCount=0;var P,N={exports:{}};var K=function(){if(P)return N.exports;P=1;var e,t="object"==typeof Reflect?Reflect:null,n=t&&"function"==typeof t.apply?t.apply:function(e,t,n){return Function.prototype.apply.call(e,t,n)};e=t&&"function"==typeof t.ownKeys?t.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var r=Number.isNaN||function(e){return e!=e};function i(){i.init.call(this)}N.exports=i,N.exports.once=function(e,t){return new Promise((function(n,r){function i(n){e.removeListener(t,o),r(n)}function o(){"function"==typeof e.removeListener&&e.removeListener("error",i),n([].slice.call(arguments))}h(e,t,o,{once:!0}),"error"!==t&&function(e,t,n){"function"==typeof e.on&&h(e,"error",t,n)}(e,i,{once:!0})}))},i.EventEmitter=i,i.prototype._events=void 0,i.prototype._eventsCount=0,i.prototype._maxListeners=void 0;var o=10;function a(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function s(e){return void 0===e._maxListeners?i.defaultMaxListeners:e._maxListeners}function c(e,t,n,r){var i,o,c,d;if(a(n),void 0===(o=e._events)?(o=e._events=Object.create(null),e._eventsCount=0):(void 0!==o.newListener&&(e.emit("newListener",t,n.listener?n.listener:n),o=e._events),c=o[t]),void 0===c)c=o[t]=n,++e._eventsCount;else if("function"==typeof c?c=o[t]=r?[n,c]:[c,n]:r?c.unshift(n):c.push(n),(i=s(e))>0&&c.length>i&&!c.warned){c.warned=!0;var u=new Error("Possible EventEmitter memory leak detected. "+c.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");u.name="MaxListenersExceededWarning",u.emitter=e,u.type=t,u.count=c.length,d=u,console&&console.warn&&console.warn(d)}return e}function d(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function u(e,t,n){var r={fired:!1,wrapFn:void 0,target:e,type:t,listener:n},i=d.bind(r);return i.listener=n,r.wrapFn=i,i}function l(e,t,n){var r=e._events;if(void 0===r)return[];var i=r[t];return void 0===i?[]:"function"==typeof i?n?[i.listener||i]:[i]:n?function(e){for(var t=new Array(e.length),n=0;n<t.length;++n)t[n]=e[n].listener||e[n];return t}(i):p(i,i.length)}function y(e){var t=this._events;if(void 0!==t){var n=t[e];if("function"==typeof n)return 1;if(void 0!==n)return n.length}return 0}function p(e,t){for(var n=new Array(t),r=0;r<t;++r)n[r]=e[r];return n}function h(e,t,n,r){if("function"==typeof e.on)r.once?e.once(t,n):e.on(t,n);else{if("function"!=typeof e.addEventListener)throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof e);e.addEventListener(t,(function i(o){r.once&&e.removeEventListener(t,i),n(o)}))}}return Object.defineProperty(i,"defaultMaxListeners",{enumerable:!0,get:function(){return o},set:function(e){if("number"!=typeof e||e<0||r(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");o=e}}),i.init=function(){void 0!==this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},i.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||r(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this},i.prototype.getMaxListeners=function(){return s(this)},i.prototype.emit=function(e){for(var t=[],r=1;r<arguments.length;r++)t.push(arguments[r]);var i="error"===e,o=this._events;if(void 0!==o)i=i&&void 0===o.error;else if(!i)return!1;if(i){var a;if(t.length>0&&(a=t[0]),a instanceof Error)throw a;var s=new Error("Unhandled error."+(a?" ("+a.message+")":""));throw s.context=a,s}var c=o[e];if(void 0===c)return!1;if("function"==typeof c)n(c,this,t);else{var d=c.length,u=p(c,d);for(r=0;r<d;++r)n(u[r],this,t)}return!0},i.prototype.addListener=function(e,t){return c(this,e,t,!1)},i.prototype.on=i.prototype.addListener,i.prototype.prependListener=function(e,t){return c(this,e,t,!0)},i.prototype.once=function(e,t){return a(t),this.on(e,u(this,e,t)),this},i.prototype.prependOnceListener=function(e,t){return a(t),this.prependListener(e,u(this,e,t)),this},i.prototype.removeListener=function(e,t){var n,r,i,o,s;if(a(t),void 0===(r=this._events))return this;if(void 0===(n=r[e]))return this;if(n===t||n.listener===t)0==--this._eventsCount?this._events=Object.create(null):(delete r[e],r.removeListener&&this.emit("removeListener",e,n.listener||t));else if("function"!=typeof n){for(i=-1,o=n.length-1;o>=0;o--)if(n[o]===t||n[o].listener===t){s=n[o].listener,i=o;break}if(i<0)return this;0===i?n.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(n,i),1===n.length&&(r[e]=n[0]),void 0!==r.removeListener&&this.emit("removeListener",e,s||t)}return this},i.prototype.off=i.prototype.removeListener,i.prototype.removeAllListeners=function(e){var t,n,r;if(void 0===(n=this._events))return this;if(void 0===n.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==n[e]&&(0==--this._eventsCount?this._events=Object.create(null):delete n[e]),this;if(0===arguments.length){var i,o=Object.keys(n);for(r=0;r<o.length;++r)"removeListener"!==(i=o[r])&&this.removeAllListeners(i);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=n[e]))this.removeListener(e,t);else if(void 0!==t)for(r=t.length-1;r>=0;r--)this.removeListener(e,t[r]);return this},i.prototype.listeners=function(e){return l(this,e,!0)},i.prototype.rawListeners=function(e){return l(this,e,!1)},i.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):y.call(e,t)},i.prototype.listenerCount=y,i.prototype.eventNames=function(){return this._eventsCount>0?e(this._events):[]},N.exports}();const U=31;var x,O;function D(e){return e&U}function M(e){return e>>1&63}function F(e){return e===x.SLICE_IDR||e===x.SLICE_NON_IDR}function B(e){return e===O.TRAIL_N||e===O.TRAIL_R||e===O.TSA_N||e===O.TSA_R||e===O.STSA_N||e===O.STSA_R||e===O.RADL_N||e===O.RADL_R||e===O.RASL_N||e===O.RASL_R||e===O.BLA_W_LP||e===O.BLA_W_RADL||e===O.BLA_N_LP||e===O.IDR_W_RADL||e===O.IDR_N_LP||e===O.CRA_NUT}function j(e,t){const n=function(e){const t=[];let n=0,r=0,i=e.length-3;for(;r<i;){for(;r<i&&!(r<i-1&&0===e[r]&&0===e[r+1]&&0===e[r+2]&&1===e[r+3])&&(0!==e[r]||0!==e[r+1]||1!==e[r+2]);)r++;r>=i&&(r=e.length);let o=r;for(;o>n&&0===e[o-1];)o--;if(0===n){if(o!==n)throw TypeError("byte stream contains leading data")}else t.push(n);let a=3;r<e.length-3&&0===e[r]&&0===e[r+1]&&0===e[r+2]&&1===e[r+3]&&(a=4),n=r+=a}return t}(e),r=null!=t?t:function(e,t){for(const n of t){if(F(D(e[n])))return"h264";if(B(M(e[n])))return"h265"}return"unknown"}(e,n);if("unknown"===r)return{unencryptedBytes:0,detectedCodec:r,requiresNALUProcessing:!1};const i=function(e,t,n){for(const r of t)if("h265"===n){if(B(M(e[r])))return r+2}else if(F(D(e[r])))return r+2;return null}(e,n,r);if(null===i)throw new TypeError("Could not find NALU");return{unencryptedBytes:i,detectedCodec:r,requiresNALUProcessing:!0}}!function(e){e[e.SLICE_NON_IDR=1]="SLICE_NON_IDR",e[e.SLICE_PARTITION_A=2]="SLICE_PARTITION_A",e[e.SLICE_PARTITION_B=3]="SLICE_PARTITION_B",e[e.SLICE_PARTITION_C=4]="SLICE_PARTITION_C",e[e.SLICE_IDR=5]="SLICE_IDR",e[e.SEI=6]="SEI",e[e.SPS=7]="SPS",e[e.PPS=8]="PPS",e[e.AUD=9]="AUD",e[e.END_SEQ=10]="END_SEQ",e[e.END_STREAM=11]="END_STREAM",e[e.FILLER_DATA=12]="FILLER_DATA",e[e.SPS_EXT=13]="SPS_EXT",e[e.PREFIX_NALU=14]="PREFIX_NALU",e[e.SUBSET_SPS=15]="SUBSET_SPS",e[e.DPS=16]="DPS",e[e.SLICE_AUX=19]="SLICE_AUX",e[e.SLICE_EXT=20]="SLICE_EXT",e[e.SLICE_LAYER_EXT=21]="SLICE_LAYER_EXT"}(x||(x={})),function(e){e[e.TRAIL_N=0]="TRAIL_N",e[e.TRAIL_R=1]="TRAIL_R",e[e.TSA_N=2]="TSA_N",e[e.TSA_R=3]="TSA_R",e[e.STSA_N=4]="STSA_N",e[e.STSA_R=5]="STSA_R",e[e.RADL_N=6]="RADL_N",e[e.RADL_R=7]="RADL_R",e[e.RASL_N=8]="RASL_N",e[e.RASL_R=9]="RASL_R",e[e.BLA_W_LP=16]="BLA_W_LP",e[e.BLA_W_RADL=17]="BLA_W_RADL",e[e.BLA_N_LP=18]="BLA_N_LP",e[e.IDR_W_RADL=19]="IDR_W_RADL",e[e.IDR_N_LP=20]="IDR_N_LP",e[e.CRA_NUT=21]="CRA_NUT",e[e.VPS_NUT=32]="VPS_NUT",e[e.SPS_NUT=33]="SPS_NUT",e[e.PPS_NUT=34]="PPS_NUT",e[e.AUD_NUT=35]="AUD_NUT",e[e.EOS_NUT=36]="EOS_NUT",e[e.EOB_NUT=37]="EOB_NUT",e[e.FD_NUT=38]="FD_NUT",e[e.PREFIX_SEI_NUT=39]="PREFIX_SEI_NUT",e[e.SUFFIX_SEI_NUT=40]="SUFFIX_SEI_NUT"}(O||(O={}));const W="ef0161653d8b2b23aad46624b420af1d03ce48950e9fc85718028f91b50f9219",q="f0a0e09647d891d6d50aa898bce7108090375d0d55e50a2bb21147afee558e44",z="61d9665eed71b6d424ae9539330a3bdd5cb386d4d781c808219a6e36750493a7",X="faffc26b68a2fc09096fa20f3351e706398b6f838a7500c8063472c2e476e90d",V="aad8d31fc56b2802ca500e58c2fb9d0b29ad71bb7cb52cd6530251eade188988";function H(t){return e(this,void 0,void 0,(function*(){const n=yield function(t){return e(this,void 0,void 0,(function*(){const e=yield crypto.subtle.digest("SHA-256",t),n=new Uint8Array(e);return Array.from(n).map((e=>e.toString(16).padStart(2,"0"))).join("")}))}(t);switch(n){case W:return"vp8";case q:case z:case X:return"h264";case V:return"opus";default:return null}}))}const G=new Map;class Y extends K.EventEmitter{encodeFunction(e,t){throw Error("not implemented for subclass")}decodeFunction(e,t){throw Error("not implemented for subclass")}}class Q extends Y{constructor(e){var t;super(),this.lastErrorTimestamp=new Map,this.errorCounts=new Map,this.ERROR_THROTTLE_MS=1e3,this.MAX_ERRORS_PER_MINUTE=5,this.ERROR_WINDOW_MS=6e4,this.sendCounts=new Map,this.keys=e.keys,this.participantIdentity=e.participantIdentity,this.rtpMap=new Map,this.keyProviderOptions=e.keyProviderOptions,this.sifTrailer=null!==(t=e.sifTrailer)&&void 0!==t?t:Uint8Array.from([])}get logContext(){return{participant:this.participantIdentity,mediaTrackId:this.trackId,fallbackCodec:this.videoCodec}}setParticipant(e,t){u.debug("setting new participant on cryptor",Object.assign(Object.assign({},this.logContext),{newParticipant:e,hadPreviousParticipant:!!this.participantIdentity})),this.participantIdentity&&this.participantIdentity!==e&&(u.warn("cryptor has already a participant set, cleaning up before switching",{oldParticipant:this.participantIdentity,newParticipant:e,trackId:this.trackId}),this.unsetParticipant()),this.participantIdentity=e,this.keys=t}unsetParticipant(){u.debug("unsetting participant",this.logContext),this.currentTransform&&(this.currentTransform=void 0),this.participantIdentity=void 0,this.lastErrorTimestamp=new Map,this.errorCounts=new Map}isEnabled(){return this.participantIdentity?G.get(this.participantIdentity):void 0}getParticipantIdentity(){return this.participantIdentity}getTrackId(){return this.trackId}setVideoCodec(e){this.videoCodec=e}setRtpMap(e){this.rtpMap=e}setupTransform(e,t,n,r,i,o){if(o&&(u.info("setting codec on cryptor to",{codec:o}),this.videoCodec=o),u.debug("Setting up frame cryptor transform",Object.assign({operation:e,passedTrackId:r,codec:o,isReuse:i,hasCurrentTransform:!!this.currentTransform},this.logContext)),this.trackId=r,i&&this.currentTransform&&t===this.currentTransform.readable&&n===this.currentTransform.writable)return void u.debug("reusing existing transform",Object.assign(Object.assign({},this.logContext),{trackId:r}));const a=Symbol("transform"),s="encode"===e?this.encodeFunction:this.decodeFunction,c=new TransformStream({transform:s.bind(this)});this.currentTransform={readable:t,writable:n,transformer:c,trackId:r,symbol:a},t.pipeThrough(c).pipeTo(n).catch((e=>{e instanceof TypeError&&"Destination stream closed"===e.message?u.debug("destination stream closed"):(u.warn("transform error",Object.assign({error:e},this.logContext)),this.emit(S.Error,e instanceof T?e:new T(e.message,void 0,this.participantIdentity)))})).finally((()=>{var e;(null===(e=this.currentTransform)||void 0===e?void 0:e.symbol)===a&&(u.debug("transform completed",Object.assign(Object.assign({},this.logContext),{trackId:r})),this.currentTransform=void 0)}))}setSifTrailer(e){u.debug("setting SIF trailer",Object.assign(Object.assign({},this.logContext),{trailer:e})),this.sifTrailer=e}shouldEmitError(e){var t,n;const r=Date.now(),i=null!==(t=this.lastErrorTimestamp.get(e))&&void 0!==t?t:0,o=null!==(n=this.errorCounts.get(e))&&void 0!==n?n:0;return r-i>this.ERROR_WINDOW_MS?(this.errorCounts.set(e,0),this.lastErrorTimestamp.set(e,r),!0):!(r-i<this.ERROR_THROTTLE_MS)&&(o>=this.MAX_ERRORS_PER_MINUTE?(o===this.MAX_ERRORS_PER_MINUTE&&(u.warn("Suppressing further decryption errors for ".concat(this.participantIdentity),Object.assign(Object.assign({},this.logContext),{errorKey:e})),this.errorCounts.set(e,o+1)),!1):(this.lastErrorTimestamp.set(e,r),this.errorCounts.set(e,o+1),!0))}emitThrottledError(e){var t;const n="".concat(this.participantIdentity,"-").concat(e.reason,"-decrypt");if(this.shouldEmitError(n)){const r=null!==(t=this.errorCounts.get(n))&&void 0!==t?t:0;r>1&&u.debug("Decryption error (".concat(r," occurrences in window)"),Object.assign(Object.assign({},this.logContext),{reason:k[e.reason]})),this.emit(S.Error,e)}}encodeFunction(t,n){return e(this,void 0,void 0,(function*(){var e;if(!this.isEnabled()||0===t.data.byteLength)return n.enqueue(t);const r=this.keys.getKeySet();if(!r)return void this.emitThrottledError(new T("key set not found for ".concat(this.participantIdentity," at index ").concat(this.keys.getCurrentKeyIndex()),k.MissingKey,this.participantIdentity));const{encryptionKey:i}=r,o=this.keys.getCurrentKeyIndex();if(i){const r=this.makeIV(null!==(e=t.getMetadata().synchronizationSource)&&void 0!==e?e:-1,t.timestamp);let s=this.getUnencryptedBytes(t);const c=new Uint8Array(t.data,0,s.unencryptedBytes),d=new Uint8Array(2);d[0]=12,d[1]=o;try{const e=yield crypto.subtle.encrypt({name:f,iv:r,additionalData:new Uint8Array(t.data,0,c.byteLength)},i,new Uint8Array(t.data,s.unencryptedBytes));let o=new Uint8Array(e.byteLength+r.byteLength+d.byteLength);o.set(new Uint8Array(e)),o.set(new Uint8Array(r),e.byteLength),o.set(d,e.byteLength+r.byteLength),s.requiresNALUProcessing&&(o=function(e){const t=[];for(var n=0,r=0;r<e.length;++r){var i=e[r];i<=3&&n>=2&&(t.push(3),n=0),t.push(i),0==i?++n:n=0}return new Uint8Array(t)}(o));var a=new Uint8Array(c.byteLength+o.byteLength);return a.set(c),a.set(o,c.byteLength),t.data=a.buffer,n.enqueue(t)}catch(e){u.error(e)}}else u.debug("failed to encrypt, emitting error",this.logContext),this.emitThrottledError(new T("encryption key missing for encoding",k.MissingKey,this.participantIdentity))}))}decodeFunction(t,n){return e(this,void 0,void 0,(function*(){if(!this.isEnabled()||0===t.data.byteLength)return n.enqueue(t);if(function(e,t){if(0===t.byteLength)return!1;const n=new Uint8Array(e.slice(e.byteLength-t.byteLength));return t.every(((e,t)=>e===n[t]))}(t.data,this.sifTrailer))return t.data=t.data.slice(0,t.data.byteLength-this.sifTrailer.byteLength),(yield H(t.data))?(u.debug("enqueue SIF",this.logContext),n.enqueue(t)):void u.warn("Unexpected SIF frame payload, dropping frame",this.logContext);const e=new Uint8Array(t.data)[t.data.byteLength-1];if(!this.keys.hasInvalidKeyAtIndex(e))if(this.keys.getKeySet(e))try{const r=yield this.decryptFrame(t,e);if(this.keys.decryptionSuccess(e),r)return n.enqueue(r)}catch(t){t instanceof T&&t.reason===k.InvalidKey?this.keys.hasValidKey&&(this.emitThrottledError(t),this.keys.decryptionFailure(e)):u.warn("decoding frame failed",{error:t})}else u.warn("skipping decryption due to missing key at index ".concat(e)),this.emitThrottledError(new T("missing key at index ".concat(e," for participant ").concat(this.participantIdentity),k.MissingKey,this.participantIdentity)),this.keys.decryptionFailure(e)}))}decryptFrame(t,n){return e(this,arguments,void 0,(function(e,t){var n=this;let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:void 0,i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{ratchetCount:0};return function*(){var o;const a=n.keys.getKeySet(t);if(!i.encryptionKey&&!a)throw new TypeError("no encryption key found for decryption of ".concat(n.participantIdentity));let s=n.getUnencryptedBytes(e);try{const t=new Uint8Array(e.data,0,s.unencryptedBytes);var c=new Uint8Array(e.data,t.length,e.data.byteLength-t.length);if(s.requiresNALUProcessing&&function(e){for(var t=0;t<e.length-3;t++)if(0==e[t]&&0==e[t+1]&&3==e[t+2])return!0;return!1}(c)){c=function(e){const t=[];for(var n=e.length,r=0;r<e.length;)n-r>=3&&!e[r]&&!e[r+1]&&3==e[r+2]?(t.push(e[r++]),t.push(e[r++]),r++):t.push(e[r++]);return new Uint8Array(t)}(c);const n=new Uint8Array(t.byteLength+c.byteLength);n.set(t),n.set(c,t.byteLength),e.data=n.buffer}const n=new Uint8Array(e.data,e.data.byteLength-2,2),r=n[0],d=new Uint8Array(e.data,e.data.byteLength-r-n.byteLength,r),u=t.byteLength,l=e.data.byteLength-(t.byteLength+r+n.byteLength),y=yield crypto.subtle.decrypt({name:f,iv:d,additionalData:new Uint8Array(e.data,0,t.byteLength)},null!==(o=i.encryptionKey)&&void 0!==o?o:a.encryptionKey,new Uint8Array(e.data,u,l)),p=new ArrayBuffer(t.byteLength+y.byteLength),h=new Uint8Array(p);return h.set(new Uint8Array(e.data,0,t.byteLength)),h.set(new Uint8Array(y),t.byteLength),e.data=p,e}catch(o){if(n.keyProviderOptions.ratchetWindowSize>0){if(i.ratchetCount<n.keyProviderOptions.ratchetWindowSize){let o,s;u.debug("ratcheting key attempt ".concat(i.ratchetCount," of ").concat(n.keyProviderOptions.ratchetWindowSize,", for kind ").concat(e instanceof RTCEncodedAudioFrame?"audio":"video")),(null!=r?r:a)===n.keys.getKeySet(t)&&(s=yield n.keys.ratchetKey(t,!1),o=yield R(s.cryptoKey,n.keyProviderOptions));const c=yield n.decryptFrame(e,t,r||a,{ratchetCount:i.ratchetCount+1,encryptionKey:null==o?void 0:o.encryptionKey});return c&&o&&(null!=r?r:a)===n.keys.getKeySet(t)&&(n.keys.setKeySet(o,t,s),n.keys.setCurrentKeyIndex(t)),c}throw u.warn("maximum ratchet attempts exceeded"),new T("valid key missing for participant ".concat(n.participantIdentity),k.InvalidKey,n.participantIdentity)}throw new T("Decryption failed: ".concat(o.message),k.InvalidKey,n.participantIdentity)}}()}))}makeIV(e,t){var n;const r=new ArrayBuffer(12),i=new DataView(r);this.sendCounts.has(e)||this.sendCounts.set(e,Math.floor(65535*Math.random()));const o=null!==(n=this.sendCounts.get(e))&&void 0!==n?n:0;return i.setUint32(0,e),i.setUint32(4,t),i.setUint32(8,t-o%65535),this.sendCounts.set(e,o+1),r}getUnencryptedBytes(e){var t;if(!function(e){return"type"in e}(e))return{unencryptedBytes:g.audio,requiresNALUProcessing:!1};const n=null!==(t=this.getVideoCodec(e))&&void 0!==t?t:this.videoCodec;if(n!==this.detectedCodec&&(u.debug("detected different codec",Object.assign({detectedCodec:n,oldCodec:this.detectedCodec},this.logContext)),this.detectedCodec=n),"av1"===n)throw new Error("".concat(n," is not yet supported for end to end encryption"));if("vp8"===n)return{unencryptedBytes:g[e.type],requiresNALUProcessing:!1};if("vp9"===n)return{unencryptedBytes:0,requiresNALUProcessing:!1};try{const t="h264"===n||"h265"===n?n:void 0,r=j(new Uint8Array(e.data),t);if(r.requiresNALUProcessing)return{unencryptedBytes:r.unencryptedBytes,requiresNALUProcessing:!0}}catch(e){u.debug("NALU processing failed, falling back to VP8 handling",Object.assign({error:e},this.logContext))}return{unencryptedBytes:g[e.type],requiresNALUProcessing:!1}}getVideoCodec(e){if(0===this.rtpMap.size)return;const t=e.getMetadata().payloadType;return t?this.rtpMap.get(t):void 0}}class J extends K.EventEmitter{get hasValidKey(){return!this.hasInvalidKeyAtIndex(this.currentKeyIndex)}constructor(e,t){if(super(),this.currentKeyIndex=0,t.keyringSize<1||t.keyringSize>256)throw new TypeError("Keyring size needs to be between 1 and 256");this.cryptoKeyRing=new Array(t.keyringSize).fill(void 0),this.decryptionFailureCounts=new Array(t.keyringSize).fill(0),this.keyProviderOptions=t,this.ratchetPromiseMap=new Map,this.participantIdentity=e}hasInvalidKeyAtIndex(e){return this.keyProviderOptions.failureTolerance>=0&&this.decryptionFailureCounts[e]>this.keyProviderOptions.failureTolerance}decryptionFailure(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.currentKeyIndex;this.keyProviderOptions.failureTolerance<0||(this.decryptionFailureCounts[e]+=1,this.decryptionFailureCounts[e]>this.keyProviderOptions.failureTolerance&&u.warn("key for ".concat(this.participantIdentity," at index ").concat(e," is being marked as invalid")))}decryptionSuccess(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.currentKeyIndex;this.resetKeyStatus(e)}resetKeyStatus(e){void 0===e?this.decryptionFailureCounts.fill(0):this.decryptionFailureCounts[e]=0}ratchetKey(t){let n=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];const r=null!=t?t:this.getCurrentKeyIndex(),i=this.ratchetPromiseMap.get(r);if(void 0!==i)return i;const o=new Promise(((t,i)=>e(this,void 0,void 0,(function*(){try{const i=this.getKeySet(r);if(!i)throw new TypeError("Cannot ratchet key without a valid keyset of participant ".concat(this.participantIdentity));const o=i.material,a=yield function(t,n){return e(this,void 0,void 0,(function*(){const e=A(t.algorithm.name,n);return crypto.subtle.deriveBits(e,t,256)}))}(o,this.keyProviderOptions.ratchetSalt),s=yield function(t){return e(this,arguments,void 0,(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{name:f},n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"encrypt";return function*(){return crypto.subtle.importKey("raw",e,t,!1,"derive"===n?["deriveBits","deriveKey"]:["encrypt","decrypt"])}()}))}(a,o.algorithm.name,"derive"),c={chainKey:a,cryptoKey:s};n&&(yield this.setKeyFromMaterial(s,r,c)),t(c)}catch(e){i(e)}finally{this.ratchetPromiseMap.delete(r)}}))));return this.ratchetPromiseMap.set(r,o),o}setKey(t){return e(this,arguments,void 0,(function(e){var t=this;let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];return function*(){yield t.setKeyFromMaterial(e,n,null,r),r&&t.resetKeyStatus(n)}()}))}setKeyFromMaterial(t,n){return e(this,arguments,void 0,(function(e,t){var n=this;let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,i=!(arguments.length>3&&void 0!==arguments[3])||arguments[3];return function*(){const o=yield R(e,n.keyProviderOptions),a=t>=0?t%n.cryptoKeyRing.length:n.currentKeyIndex;u.debug("setting new key with index ".concat(t),{usage:e.usages,algorithm:e.algorithm,ratchetSalt:n.keyProviderOptions.ratchetSalt}),n.setKeySet(o,a,r),a>=0&&i&&(n.currentKeyIndex=a)}()}))}setKeySet(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null;this.cryptoKeyRing[t%this.cryptoKeyRing.length]=e,n&&this.emit(_.KeyRatcheted,n,this.participantIdentity,t)}setCurrentKeyIndex(t){return e(this,void 0,void 0,(function*(){this.currentKeyIndex=t%this.cryptoKeyRing.length,this.resetKeyStatus(t)}))}getCurrentKeyIndex(){return this.currentKeyIndex}getKeySet(e){return this.cryptoKeyRing[null!=e?e:this.currentKeyIndex]}}const Z=[],$=new Map;let ee,te,ne=new class{constructor(){this.pendingTasks=new Map,this.taskMutex=new h,this.nextTaskIndex=0}run(t){return e(this,void 0,void 0,(function*(){const e={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:l.WAITING};this.pendingTasks.set(e.id,e);const n=yield this.taskMutex.lock();try{return e.executedAt=Date.now(),e.status=l.RUNNING,yield t()}finally{e.status=l.COMPLETED,this.pendingTasks.delete(e.id),n()}}))}flush(){return e(this,void 0,void 0,(function*(){return this.run((()=>e(this,void 0,void 0,(function*(){}))))}))}snapshot(){return Array.from(this.pendingTasks.values())}},re=!1,ie=v,oe=new Map;function ae(e,t){let n=Z.filter((e=>e.getTrackId()===t));if(n.length>1){const r=n.map((e=>({participant:e.getParticipantIdentity()}))).join(",");u.error("Found multiple cryptors for the same trackID ".concat(t,". target participant: ").concat(e," "),{participants:r})}let r=n[0];if(r)e!==r.getParticipantIdentity()&&r.setParticipant(e,se(e));else{if(u.info("creating new cryptor for",{participantIdentity:e,trackId:t}),!ie)throw Error("Missing keyProvider options");r=new Q({participantIdentity:e,keys:se(e),keyProviderOptions:ie,sifTrailer:te}),r.setRtpMap(oe),function(e){e.on(S.Error,(e=>{const t={kind:"error",data:{error:new Error("".concat(k[e.reason],": ").concat(e.message)),participantIdentity:e.participantIdentity}};postMessage(t)}))}(r),Z.push(r)}return r}function se(e){if(re)return ce();let t=$.get(e);return t||(t=new J(e,ie),t.on(_.KeyRatcheted,de),$.set(e,t)),t}function ce(){return ee||(u.debug("creating new shared key handler"),ee=new J("shared-key",ie)),ee}function de(e,t,n){postMessage({kind:"ratchetKey",data:{participantIdentity:t,keyIndex:n,ratchetResult:e}})}u.setDefaultLevel("info"),onmessage=t=>{ne.run((()=>e(void 0,void 0,void 0,(function*(){const{kind:n,data:r}=t.data;switch(n){case"init":u.setLevel(r.loglevel),u.info("worker initialized"),ie=r.keyProviderOptions,re=!!r.keyProviderOptions.sharedKey;postMessage({kind:"initAck",data:{enabled:false}});break;case"enable":o=r.enabled,a=r.participantIdentity,u.debug("setting encryption enabled for all tracks of ".concat(a),{enable:o}),G.set(a,o),u.info("updated e2ee enabled status for ".concat(r.participantIdentity," to ").concat(r.enabled)),postMessage(t.data);break;case"decode":ae(r.participantIdentity,r.trackId).setupTransform(n,r.readableStream,r.writableStream,r.trackId,r.isReuse,r.codec);break;case"encode":ae(r.participantIdentity,r.trackId).setupTransform(n,r.readableStream,r.writableStream,r.trackId,r.isReuse,r.codec);break;case"encryptDataRequest":const{payload:s,iv:c,keyIndex:d}=yield C.encrypt(r.payload,se(r.participantIdentity));console.log("encrypted payload",{original:r.payload,encrypted:s,iv:c}),postMessage({kind:"encryptDataResponse",data:{payload:s,iv:c,keyIndex:d,uuid:r.uuid}});break;case"decryptDataRequest":try{const{payload:e}=yield C.decrypt(r.payload,r.iv,se(r.participantIdentity),r.keyIndex);postMessage({kind:"decryptDataResponse",data:{payload:e,uuid:r.uuid}})}catch(e){u.error("DataCryptor decryption failed",{error:e,participantIdentity:r.participantIdentity,uuid:r.uuid}),postMessage({kind:"error",data:{error:e instanceof Error?e:new Error(String(e)),uuid:r.uuid}})}break;case"setKey":re?yield function(t,n,r){return e(this,void 0,void 0,(function*(){u.info("set shared key",{index:n}),yield ce().setKey(t,n,r)}))}(r.key,r.keyIndex,r.updateCurrentKeyIndex):r.participantIdentity?(u.info("set participant sender key ".concat(r.participantIdentity," index ").concat(r.keyIndex)),yield se(r.participantIdentity).setKey(r.key,r.keyIndex,r.updateCurrentKeyIndex)):u.error("no participant Id was provided and shared key usage is disabled");break;case"removeTransform":!function(e,t){const n=Z.filter((n=>n.getParticipantIdentity()===t&&n.getTrackId()===e));n.length>1&&u.error("Found multiple cryptors for the same participant and trackID combination",{trackId:e,participantIdentity:t});const r=n[0];r?r.unsetParticipant():u.warn("Could not unset participant on cryptor",{trackId:e,participantIdentity:t})}(r.trackId,r.participantIdentity);break;case"updateCodec":ae(r.participantIdentity,r.trackId).setVideoCodec(r.codec),u.info("updated codec",{participantIdentity:r.participantIdentity,trackId:r.trackId,codec:r.codec});break;case"setRTPMap":oe=r.map,Z.forEach((e=>{e.getParticipantIdentity()===r.participantIdentity&&e.setRtpMap(r.map)}));break;case"ratchetRequest":!function(t){e(this,void 0,void 0,(function*(){if(re){const e=ce();yield e.ratchetKey(t.keyIndex),e.resetKeyStatus()}else if(t.participantIdentity){const e=se(t.participantIdentity);yield e.ratchetKey(t.keyIndex),e.resetKeyStatus()}else u.error("no participant Id was provided for ratchet request and shared key usage is disabled")}))}(r);break;case"setSifTrailer":i=r.trailer,te=i,Z.forEach((e=>{e.setSifTrailer(i)}))}var i,o,a}))))},self.RTCTransformEvent&&(self.onrtctransform=t=>{const n=t.transformer,{kind:r,participantIdentity:i,trackId:o,codec:a}=n.options;ne.run((()=>e(void 0,void 0,void 0,(function*(){const e=ae(i,o);u.debug("onrtctransform setup",{participantIdentity:i,trackId:o,codec:a}),e.setupTransform(r,n.readable,n.writable,o,!1,a)}))))})}));
1
+ !function(e){"function"==typeof define&&define.amd?define(e):e()}((function(){"use strict";function e(e,t,n,r){return new(n||(n=Promise))((function(i,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((r=r.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;var t,n={exports:{}};var r,i,a,o,s,c=(t||(t=1,i=n.exports,a=function(){var e=function(){},t="undefined",n=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),r=["trace","debug","info","warn","error"],i={},a=null;function o(e,t){var n=e[t];if("function"==typeof n.bind)return n.bind(e);try{return Function.prototype.bind.call(n,e)}catch(t){return function(){return Function.prototype.apply.apply(n,[e,arguments])}}}function s(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function c(){for(var n=this.getLevel(),i=0;i<r.length;i++){var a=r[i];this[a]=i<n?e:this.methodFactory(a,n,this.name)}if(this.log=this.debug,typeof console===t&&n<this.levels.SILENT)return"No console available for logging"}function d(e){return function(){typeof console!==t&&(c.call(this),this[e].apply(this,arguments))}}function u(r,i,a){return function(r){return"debug"===r&&(r="log"),typeof console!==t&&("trace"===r&&n?s:void 0!==console[r]?o(console,r):void 0!==console.log?o(console,"log"):e)}(r)||d.apply(this,arguments)}function l(e,n){var o,s,d,l=this,h="loglevel";function f(){var e;if(typeof window!==t&&h){try{e=window.localStorage[h]}catch(e){}if(typeof e===t)try{var n=window.document.cookie,r=encodeURIComponent(h),i=n.indexOf(r+"=");-1!==i&&(e=/^([^;]+)/.exec(n.slice(i+r.length+1))[1])}catch(e){}return void 0===l.levels[e]&&(e=void 0),e}}function p(e){var t=e;if("string"==typeof t&&void 0!==l.levels[t.toUpperCase()]&&(t=l.levels[t.toUpperCase()]),"number"==typeof t&&t>=0&&t<=l.levels.SILENT)return t;throw new TypeError("log.setLevel() called with invalid level: "+e)}"string"==typeof e?h+=":"+e:"symbol"==typeof e&&(h=void 0),l.name=e,l.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},l.methodFactory=n||u,l.getLevel=function(){return null!=d?d:null!=s?s:o},l.setLevel=function(e,n){return d=p(e),!1!==n&&function(e){var n=(r[e]||"silent").toUpperCase();if(typeof window!==t&&h){try{return void(window.localStorage[h]=n)}catch(e){}try{window.document.cookie=encodeURIComponent(h)+"="+n+";"}catch(e){}}}(d),c.call(l)},l.setDefaultLevel=function(e){s=p(e),f()||l.setLevel(e,!1)},l.resetLevel=function(){d=null,function(){if(typeof window!==t&&h){try{window.localStorage.removeItem(h)}catch(e){}try{window.document.cookie=encodeURIComponent(h)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch(e){}}}(),c.call(l)},l.enableAll=function(e){l.setLevel(l.levels.TRACE,e)},l.disableAll=function(e){l.setLevel(l.levels.SILENT,e)},l.rebuild=function(){if(a!==l&&(o=p(a.getLevel())),c.call(l),a===l)for(var e in i)i[e].rebuild()},o=p(a?a.getLevel():"WARN");var y=f();null!=y&&(d=p(y)),c.call(l)}(a=new l).getLogger=function(e){if("symbol"!=typeof e&&"string"!=typeof e||""===e)throw new TypeError("You must supply a name when creating a logger.");var t=i[e];return t||(t=i[e]=new l(e,a.methodFactory)),t};var h=typeof window!==t?window.log:void 0;return a.noConflict=function(){return typeof window!==t&&window.log===a&&(window.log=h),a},a.getLoggers=function(){return i},a.default=a,a},(r=n).exports?r.exports=a():i.log=a()),n.exports);!function(e){e[e.trace=0]="trace",e[e.debug=1]="debug",e[e.info=2]="info",e[e.warn=3]="warn",e[e.error=4]="error",e[e.silent=5]="silent"}(o||(o={})),function(e){e.Default="livekit",e.Room="livekit-room",e.TokenSource="livekit-token-source",e.Participant="livekit-participant",e.Track="livekit-track",e.Publication="livekit-track-publication",e.Engine="livekit-engine",e.Signal="livekit-signal",e.PCManager="livekit-pc-manager",e.PCTransport="livekit-pc-transport",e.E2EE="lk-e2ee",e.DataTracks="livekit-data-tracks"}(s||(s={}));let d=c.getLogger(s.Default);function u(e,t){const n=c.getLogger(e);return n.setDefaultLevel(d.getLevel()),n}Object.values(s).map((e=>c.getLogger(e))),d.setDefaultLevel(o.info);const l=c.getLogger(s.E2EE);var h,f=Object.defineProperty,p=(e,t,n)=>((e,t,n)=>t in e?f(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n)(e,"symbol"!=typeof t?t+"":t,n);class y{constructor(){p(this,"_locking"),p(this,"_locks"),this._locking=Promise.resolve(),this._locks=0}isLocked(){return this._locks>0}lock(){let e;this._locks+=1;const t=new Promise((t=>e=()=>{this._locks-=1,t()})),n=this._locking.then((()=>e));return this._locking=this._locking.then((()=>t)),n}}!function(e){e[e.WAITING=0]="WAITING",e[e.RUNNING=1]="RUNNING",e[e.COMPLETED=2]="COMPLETED"}(h||(h={}));const m="AES-GCM",g={key:10,delta:3,audio:1,empty:0},b={sharedKey:!1,ratchetSalt:"LKFrameEncryptionKey",ratchetWindowSize:8,failureTolerance:10,keyringSize:16,keySize:128};function v(e,t){if(!e)throw new Error(t)}const k=34028234663852886e22,w=-34028234663852886e22,T=4294967295,S=2147483647,I=-2147483648;function E(e){if("number"!=typeof e)throw new Error("invalid int 32: "+typeof e);if(!Number.isInteger(e)||e>S||e<I)throw new Error("invalid int 32: "+e)}function N(e){if("number"!=typeof e)throw new Error("invalid uint 32: "+typeof e);if(!Number.isInteger(e)||e>T||e<0)throw new Error("invalid uint 32: "+e)}function A(e){if("number"!=typeof e)throw new Error("invalid float 32: "+typeof e);if(Number.isFinite(e)&&(e>k||e<w))throw new Error("invalid float 32: "+e)}const C=Symbol("@bufbuild/protobuf/enum-type");function L(e){const t=e[C];return v(t,"missing enum type on enum object"),t}function R(e,t,n,r){e[C]=U(t,n.map((t=>({no:t.no,name:t.name,localName:e[t.no]}))))}function U(e,t,n){const r=Object.create(null),i=Object.create(null),a=[];for(const e of t){const t=P(e);a.push(t),r[e.name]=t,i[e.no]=t}return{typeName:e,values:a,findName:e=>r[e],findNumber:e=>i[e]}}function O(e,t,n){const r={};for(const e of t){const t=P(e);r[t.localName]=t.no,r[t.no]=t.localName}return R(r,e,t),r}function P(e){return"localName"in e?e:Object.assign(Object.assign({},e),{localName:e.name})}class _{equals(e){return this.getType().runtime.util.equals(this.getType(),this,e)}clone(){return this.getType().runtime.util.clone(this)}fromBinary(e,t){const n=this.getType().runtime.bin,r=n.makeReadOptions(t);return n.readMessage(this,r.readerFactory(e),e.byteLength,r),this}fromJson(e,t){const n=this.getType(),r=n.runtime.json,i=r.makeReadOptions(t);return r.readMessage(n,e,i,this),this}fromJsonString(e,t){let n;try{n=JSON.parse(e)}catch(e){throw new Error("cannot decode ".concat(this.getType().typeName," from JSON: ").concat(e instanceof Error?e.message:String(e)))}return this.fromJson(n,t)}toBinary(e){const t=this.getType().runtime.bin,n=t.makeWriteOptions(e),r=n.writerFactory();return t.writeMessage(this,r,n),r.finish()}toJson(e){const t=this.getType().runtime.json,n=t.makeWriteOptions(e);return t.writeMessage(this,n)}toJsonString(e){var t;const n=this.toJson(e);return JSON.stringify(n,null,null!==(t=null==e?void 0:e.prettySpaces)&&void 0!==t?t:0)}toJSON(){return this.toJson({emitDefaultValues:!0})}getType(){return Object.getPrototypeOf(this).constructor}}function D(){let e=0,t=0;for(let n=0;n<28;n+=7){let r=this.buf[this.pos++];if(e|=(127&r)<<n,0==(128&r))return this.assertBounds(),[e,t]}let n=this.buf[this.pos++];if(e|=(15&n)<<28,t=(112&n)>>4,0==(128&n))return this.assertBounds(),[e,t];for(let n=3;n<=31;n+=7){let r=this.buf[this.pos++];if(t|=(127&r)<<n,0==(128&r))return this.assertBounds(),[e,t]}throw new Error("invalid varint")}function F(e,t,n){for(let r=0;r<28;r+=7){const i=e>>>r,a=!(i>>>7==0&&0==t),o=255&(a?128|i:i);if(n.push(o),!a)return}const r=e>>>28&15|(7&t)<<4,i=!(t>>3==0);if(n.push(255&(i?128|r:r)),i){for(let e=3;e<31;e+=7){const r=t>>>e,i=!(r>>>7==0),a=255&(i?128|r:r);if(n.push(a),!i)return}n.push(t>>>31&1)}}const x=4294967296;function B(e){const t="-"===e[0];t&&(e=e.slice(1));const n=1e6;let r=0,i=0;function a(t,a){const o=Number(e.slice(t,a));i*=n,r=r*n+o,r>=x&&(i+=r/x|0,r%=x)}return a(-24,-18),a(-18,-12),a(-12,-6),a(-6),t?j(r,i):K(r,i)}function M(e,t){if(({lo:e,hi:t}=function(e,t){return{lo:e>>>0,hi:t>>>0}}(e,t)),t<=2097151)return String(x*t+e);const n=16777215&(e>>>24|t<<8),r=t>>16&65535;let i=(16777215&e)+6777216*n+6710656*r,a=n+8147497*r,o=2*r;const s=1e7;return i>=s&&(a+=Math.floor(i/s),i%=s),a>=s&&(o+=Math.floor(a/s),a%=s),o.toString()+V(a)+V(i)}function K(e,t){return{lo:0|e,hi:0|t}}function j(e,t){return t=~t,e?e=1+~e:t+=1,K(e,t)}const V=e=>{const t=String(e);return"0000000".slice(t.length)+t};function W(e,t){if(e>=0){for(;e>127;)t.push(127&e|128),e>>>=7;t.push(e)}else{for(let n=0;n<9;n++)t.push(127&e|128),e>>=7;t.push(1)}}function q(){let e=this.buf[this.pos++],t=127&e;if(0==(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<7,0==(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<14,0==(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<21,0==(128&e))return this.assertBounds(),t;e=this.buf[this.pos++],t|=(15&e)<<28;for(let t=5;0!=(128&e)&&t<10;t++)e=this.buf[this.pos++];if(0!=(128&e))throw new Error("invalid varint");return this.assertBounds(),t>>>0}const G=function(){const e=new DataView(new ArrayBuffer(8));if("function"==typeof BigInt&&"function"==typeof e.getBigInt64&&"function"==typeof e.getBigUint64&&"function"==typeof e.setBigInt64&&"function"==typeof e.setBigUint64&&("object"!=typeof process||"object"!=typeof process.env||"1"!==process.env.BUF_BIGINT_DISABLE)){const t=BigInt("-9223372036854775808"),n=BigInt("9223372036854775807"),r=BigInt("0"),i=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(e){const r="bigint"==typeof e?e:BigInt(e);if(r>n||r<t)throw new Error("int64 invalid: ".concat(e));return r},uParse(e){const t="bigint"==typeof e?e:BigInt(e);if(t>i||t<r)throw new Error("uint64 invalid: ".concat(e));return t},enc(t){return e.setBigInt64(0,this.parse(t),!0),{lo:e.getInt32(0,!0),hi:e.getInt32(4,!0)}},uEnc(t){return e.setBigInt64(0,this.uParse(t),!0),{lo:e.getInt32(0,!0),hi:e.getInt32(4,!0)}},dec:(t,n)=>(e.setInt32(0,t,!0),e.setInt32(4,n,!0),e.getBigInt64(0,!0)),uDec:(t,n)=>(e.setInt32(0,t,!0),e.setInt32(4,n,!0),e.getBigUint64(0,!0))}}const t=e=>v(/^-?[0-9]+$/.test(e),"int64 invalid: ".concat(e)),n=e=>v(/^[0-9]+$/.test(e),"uint64 invalid: ".concat(e));return{zero:"0",supported:!1,parse:e=>("string"!=typeof e&&(e=e.toString()),t(e),e),uParse:e=>("string"!=typeof e&&(e=e.toString()),n(e),e),enc:e=>("string"!=typeof e&&(e=e.toString()),t(e),B(e)),uEnc:e=>("string"!=typeof e&&(e=e.toString()),n(e),B(e)),dec:(e,t)=>function(e,t){let n=K(e,t);const r=2147483648&n.hi;r&&(n=j(n.lo,n.hi));const i=M(n.lo,n.hi);return r?"-"+i:i}(e,t),uDec:(e,t)=>M(e,t)}}();var X,J,H;function z(e,t,n){if(t===n)return!0;if(e==X.BYTES){if(!(t instanceof Uint8Array&&n instanceof Uint8Array))return!1;if(t.length!==n.length)return!1;for(let e=0;e<t.length;e++)if(t[e]!==n[e])return!1;return!0}switch(e){case X.UINT64:case X.FIXED64:case X.INT64:case X.SFIXED64:case X.SINT64:return t==n}return!1}function Y(e,t){switch(e){case X.BOOL:return!1;case X.UINT64:case X.FIXED64:case X.INT64:case X.SFIXED64:case X.SINT64:return 0==t?G.zero:"0";case X.DOUBLE:case X.FLOAT:return 0;case X.BYTES:return new Uint8Array(0);case X.STRING:return"";default:return 0}}function Q(e,t){switch(e){case X.BOOL:return!1===t;case X.STRING:return""===t;case X.BYTES:return t instanceof Uint8Array&&!t.byteLength;default:return 0==t}}!function(e){e[e.DOUBLE=1]="DOUBLE",e[e.FLOAT=2]="FLOAT",e[e.INT64=3]="INT64",e[e.UINT64=4]="UINT64",e[e.INT32=5]="INT32",e[e.FIXED64=6]="FIXED64",e[e.FIXED32=7]="FIXED32",e[e.BOOL=8]="BOOL",e[e.STRING=9]="STRING",e[e.BYTES=12]="BYTES",e[e.UINT32=13]="UINT32",e[e.SFIXED32=15]="SFIXED32",e[e.SFIXED64=16]="SFIXED64",e[e.SINT32=17]="SINT32",e[e.SINT64=18]="SINT64"}(X||(X={})),function(e){e[e.BIGINT=0]="BIGINT",e[e.STRING=1]="STRING"}(J||(J={})),function(e){e[e.Varint=0]="Varint",e[e.Bit64=1]="Bit64",e[e.LengthDelimited=2]="LengthDelimited",e[e.StartGroup=3]="StartGroup",e[e.EndGroup=4]="EndGroup",e[e.Bit32=5]="Bit32"}(H||(H={}));class ${constructor(e){this.stack=[],this.textEncoder=null!=e?e:new TextEncoder,this.chunks=[],this.buf=[]}finish(){this.chunks.push(new Uint8Array(this.buf));let e=0;for(let t=0;t<this.chunks.length;t++)e+=this.chunks[t].length;let t=new Uint8Array(e),n=0;for(let e=0;e<this.chunks.length;e++)t.set(this.chunks[e],n),n+=this.chunks[e].length;return this.chunks=[],t}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let e=this.finish(),t=this.stack.pop();if(!t)throw new Error("invalid state, fork stack empty");return this.chunks=t.chunks,this.buf=t.buf,this.uint32(e.byteLength),this.raw(e)}tag(e,t){return this.uint32((e<<3|t)>>>0)}raw(e){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(e),this}uint32(e){for(N(e);e>127;)this.buf.push(127&e|128),e>>>=7;return this.buf.push(e),this}int32(e){return E(e),W(e,this.buf),this}bool(e){return this.buf.push(e?1:0),this}bytes(e){return this.uint32(e.byteLength),this.raw(e)}string(e){let t=this.textEncoder.encode(e);return this.uint32(t.byteLength),this.raw(t)}float(e){A(e);let t=new Uint8Array(4);return new DataView(t.buffer).setFloat32(0,e,!0),this.raw(t)}double(e){let t=new Uint8Array(8);return new DataView(t.buffer).setFloat64(0,e,!0),this.raw(t)}fixed32(e){N(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){E(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return E(e),W(e=(e<<1^e>>31)>>>0,this.buf),this}sfixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),r=G.enc(e);return n.setInt32(0,r.lo,!0),n.setInt32(4,r.hi,!0),this.raw(t)}fixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),r=G.uEnc(e);return n.setInt32(0,r.lo,!0),n.setInt32(4,r.hi,!0),this.raw(t)}int64(e){let t=G.enc(e);return F(t.lo,t.hi,this.buf),this}sint64(e){let t=G.enc(e),n=t.hi>>31;return F(t.lo<<1^n,(t.hi<<1|t.lo>>>31)^n,this.buf),this}uint64(e){let t=G.uEnc(e);return F(t.lo,t.hi,this.buf),this}}class Z{constructor(e,t){this.varint64=D,this.uint32=q,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength),this.textDecoder=null!=t?t:new TextDecoder}tag(){let e=this.uint32(),t=e>>>3,n=7&e;if(t<=0||n<0||n>5)throw new Error("illegal tag: field no "+t+" wire type "+n);return[t,n]}skip(e,t){let n=this.pos;switch(e){case H.Varint:for(;128&this.buf[this.pos++];);break;case H.Bit64:this.pos+=4;case H.Bit32:this.pos+=4;break;case H.LengthDelimited:let n=this.uint32();this.pos+=n;break;case H.StartGroup:for(;;){const[e,n]=this.tag();if(n===H.EndGroup){if(void 0!==t&&e!==t)throw new Error("invalid end group tag");break}this.skip(n,e)}break;default:throw new Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(n,this.pos)}assertBounds(){if(this.pos>this.len)throw new RangeError("premature EOF")}int32(){return 0|this.uint32()}sint32(){let e=this.uint32();return e>>>1^-(1&e)}int64(){return G.dec(...this.varint64())}uint64(){return G.uDec(...this.varint64())}sint64(){let[e,t]=this.varint64(),n=-(1&e);return e=(e>>>1|(1&t)<<31)^n,t=t>>>1^n,G.dec(e,t)}bool(){let[e,t]=this.varint64();return 0!==e||0!==t}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return G.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return G.dec(this.sfixed32(),this.sfixed32())}float(){return this.view.getFloat32((this.pos+=4)-4,!0)}double(){return this.view.getFloat64((this.pos+=8)-8,!0)}bytes(){let e=this.uint32(),t=this.pos;return this.pos+=e,this.assertBounds(),this.buf.subarray(t,t+e)}string(){return this.textDecoder.decode(this.bytes())}}function ee(e){const t=e.field.localName,n=Object.create(null);return n[t]=function(e){const t=e.field;if(t.repeated)return[];if(void 0!==t.default)return t.default;switch(t.kind){case"enum":return t.T.values[0].no;case"scalar":return Y(t.T,t.L);case"message":const e=t.T,n=new e;return e.fieldWrapper?e.fieldWrapper.unwrapField(n):n;case"map":throw"map fields are not allowed to be extensions"}}(e),[n,()=>n[t]]}let te="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),ne=[];for(let e=0;e<te.length;e++)ne[te[e].charCodeAt(0)]=e;ne["-".charCodeAt(0)]=te.indexOf("+"),ne["_".charCodeAt(0)]=te.indexOf("/");const re={dec(e){let t=3*e.length/4;"="==e[e.length-2]?t-=2:"="==e[e.length-1]&&(t-=1);let n,r=new Uint8Array(t),i=0,a=0,o=0;for(let t=0;t<e.length;t++){if(n=ne[e.charCodeAt(t)],void 0===n)switch(e[t]){case"=":a=0;case"\n":case"\r":case"\t":case" ":continue;default:throw Error("invalid base64 string.")}switch(a){case 0:o=n,a=1;break;case 1:r[i++]=o<<2|(48&n)>>4,o=n,a=2;break;case 2:r[i++]=(15&o)<<4|(60&n)>>2,o=n,a=3;break;case 3:r[i++]=(3&o)<<6|n,a=0}}if(1==a)throw Error("invalid base64 string.");return r.subarray(0,i)},enc(e){let t,n="",r=0,i=0;for(let a=0;a<e.length;a++)switch(t=e[a],r){case 0:n+=te[t>>2],i=(3&t)<<4,r=1;break;case 1:n+=te[i|t>>4],i=(15&t)<<2,r=2;break;case 2:n+=te[i|t>>6],n+=te[63&t],r=0}return r&&(n+=te[i],n+="=",1==r&&(n+="=")),n}};function ie(e,t,n){se(t,e);const r=t.runtime.bin.makeReadOptions(n),i=function(e,t){if(!t.repeated&&("enum"==t.kind||"scalar"==t.kind)){for(let n=e.length-1;n>=0;--n)if(e[n].no==t.no)return[e[n]];return[]}return e.filter((e=>e.no===t.no))}(e.getType().runtime.bin.listUnknownFields(e),t.field),[a,o]=ee(t);for(const e of i)t.runtime.bin.readField(a,r.readerFactory(e.data),t.field,e.wireType,r);return o()}function ae(e,t,n,r){se(t,e);const i=t.runtime.bin.makeReadOptions(r),a=t.runtime.bin.makeWriteOptions(r);if(oe(e,t)){const n=e.getType().runtime.bin.listUnknownFields(e).filter((e=>e.no!=t.field.no));e.getType().runtime.bin.discardUnknownFields(e);for(const t of n)e.getType().runtime.bin.onUnknownField(e,t.no,t.wireType,t.data)}const o=a.writerFactory();let s=t.field;s.opt||s.repeated||"enum"!=s.kind&&"scalar"!=s.kind||(s=Object.assign(Object.assign({},t.field),{opt:!0})),t.runtime.bin.writeField(s,n,o,a);const c=i.readerFactory(o.finish());for(;c.pos<c.len;){const[t,n]=c.tag(),r=c.skip(n,t);e.getType().runtime.bin.onUnknownField(e,t,n,r)}}function oe(e,t){const n=e.getType();return t.extendee.typeName===n.typeName&&!!n.runtime.bin.listUnknownFields(e).find((e=>e.no==t.field.no))}function se(e,t){v(e.extendee.typeName==t.getType().typeName,"extension ".concat(e.typeName," can only be applied to message ").concat(e.extendee.typeName))}function ce(e,t){const n=e.localName;if(e.repeated)return t[n].length>0;if(e.oneof)return t[e.oneof.localName].case===n;switch(e.kind){case"enum":case"scalar":return e.opt||e.req?void 0!==t[n]:"enum"==e.kind?t[n]!==e.T.values[0].no:!Q(e.T,t[n]);case"message":return void 0!==t[n];case"map":return Object.keys(t[n]).length>0}}function de(e,t){const n=e.localName,r=!e.opt&&!e.req;if(e.repeated)t[n]=[];else if(e.oneof)t[e.oneof.localName]={case:void 0};else switch(e.kind){case"map":t[n]={};break;case"enum":t[n]=r?e.T.values[0].no:void 0;break;case"scalar":t[n]=r?Y(e.T,e.L):void 0;break;case"message":t[n]=void 0}}function ue(e,t){if(null===e||"object"!=typeof e)return!1;if(!Object.getOwnPropertyNames(_.prototype).every((t=>t in e&&"function"==typeof e[t])))return!1;const n=e.getType();return null!==n&&"function"==typeof n&&"typeName"in n&&"string"==typeof n.typeName&&(void 0===t||n.typeName==t.typeName)}function le(e,t){return ue(t)||!e.fieldWrapper?t:e.fieldWrapper.wrapField(t)}X.DOUBLE,X.FLOAT,X.INT64,X.UINT64,X.INT32,X.UINT32,X.BOOL,X.STRING,X.BYTES;const he={ignoreUnknownFields:!1},fe={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};function pe(e){return e?Object.assign(Object.assign({},he),e):he}function ye(e){return e?Object.assign(Object.assign({},fe),e):fe}const me=Symbol(),ge=Symbol();function be(e){if(null===e)return"null";switch(typeof e){case"object":return Array.isArray(e)?"array":"object";case"string":return e.length>100?"string":'"'.concat(e.split('"').join('\\"'),'"');default:return String(e)}}function ve(e,t,n,r,i){let a=n.localName;if(n.repeated){if(v("map"!=n.kind),null===t)return;if(!Array.isArray(t))throw new Error("cannot decode field ".concat(i.typeName,".").concat(n.name," from JSON: ").concat(be(t)));const o=e[a];for(const e of t){if(null===e)throw new Error("cannot decode field ".concat(i.typeName,".").concat(n.name," from JSON: ").concat(be(e)));switch(n.kind){case"message":o.push(n.T.fromJson(e,r));break;case"enum":const t=Te(n.T,e,r.ignoreUnknownFields,!0);t!==ge&&o.push(t);break;case"scalar":try{o.push(we(n.T,e,n.L,!0))}catch(t){let r="cannot decode field ".concat(i.typeName,".").concat(n.name," from JSON: ").concat(be(e));throw t instanceof Error&&t.message.length>0&&(r+=": ".concat(t.message)),new Error(r)}}}}else if("map"==n.kind){if(null===t)return;if("object"!=typeof t||Array.isArray(t))throw new Error("cannot decode field ".concat(i.typeName,".").concat(n.name," from JSON: ").concat(be(t)));const o=e[a];for(const[e,a]of Object.entries(t)){if(null===a)throw new Error("cannot decode field ".concat(i.typeName,".").concat(n.name," from JSON: map value null"));let s;try{s=ke(n.K,e)}catch(e){let r="cannot decode map key for field ".concat(i.typeName,".").concat(n.name," from JSON: ").concat(be(t));throw e instanceof Error&&e.message.length>0&&(r+=": ".concat(e.message)),new Error(r)}switch(n.V.kind){case"message":o[s]=n.V.T.fromJson(a,r);break;case"enum":const e=Te(n.V.T,a,r.ignoreUnknownFields,!0);e!==ge&&(o[s]=e);break;case"scalar":try{o[s]=we(n.V.T,a,J.BIGINT,!0)}catch(e){let r="cannot decode map value for field ".concat(i.typeName,".").concat(n.name," from JSON: ").concat(be(t));throw e instanceof Error&&e.message.length>0&&(r+=": ".concat(e.message)),new Error(r)}}}}else switch(n.oneof&&(e=e[n.oneof.localName]={case:a},a="value"),n.kind){case"message":const o=n.T;if(null===t&&"google.protobuf.Value"!=o.typeName)return;let s=e[a];ue(s)?s.fromJson(t,r):(e[a]=s=o.fromJson(t,r),o.fieldWrapper&&!n.oneof&&(e[a]=o.fieldWrapper.unwrapField(s)));break;case"enum":const c=Te(n.T,t,r.ignoreUnknownFields,!1);switch(c){case me:de(n,e);break;case ge:break;default:e[a]=c}break;case"scalar":try{const r=we(n.T,t,n.L,!1);if(r===me)de(n,e);else e[a]=r}catch(e){let r="cannot decode field ".concat(i.typeName,".").concat(n.name," from JSON: ").concat(be(t));throw e instanceof Error&&e.message.length>0&&(r+=": ".concat(e.message)),new Error(r)}}}function ke(e,t){if(e===X.BOOL)switch(t){case"true":t=!0;break;case"false":t=!1}return we(e,t,J.BIGINT,!0).toString()}function we(e,t,n,r){if(null===t)return r?Y(e,n):me;switch(e){case X.DOUBLE:case X.FLOAT:if("NaN"===t)return Number.NaN;if("Infinity"===t)return Number.POSITIVE_INFINITY;if("-Infinity"===t)return Number.NEGATIVE_INFINITY;if(""===t)break;if("string"==typeof t&&t.trim().length!==t.length)break;if("string"!=typeof t&&"number"!=typeof t)break;const r=Number(t);if(Number.isNaN(r))break;if(!Number.isFinite(r))break;return e==X.FLOAT&&A(r),r;case X.INT32:case X.FIXED32:case X.SFIXED32:case X.SINT32:case X.UINT32:let i;if("number"==typeof t?i=t:"string"==typeof t&&t.length>0&&t.trim().length===t.length&&(i=Number(t)),void 0===i)break;return e==X.UINT32||e==X.FIXED32?N(i):E(i),i;case X.INT64:case X.SFIXED64:case X.SINT64:if("number"!=typeof t&&"string"!=typeof t)break;const a=G.parse(t);return n?a.toString():a;case X.FIXED64:case X.UINT64:if("number"!=typeof t&&"string"!=typeof t)break;const o=G.uParse(t);return n?o.toString():o;case X.BOOL:if("boolean"!=typeof t)break;return t;case X.STRING:if("string"!=typeof t)break;try{encodeURIComponent(t)}catch(e){throw new Error("invalid UTF8")}return t;case X.BYTES:if(""===t)return new Uint8Array(0);if("string"!=typeof t)break;return re.dec(t)}throw new Error}function Te(e,t,n,r){if(null===t)return"google.protobuf.NullValue"==e.typeName?0:r?e.values[0].no:me;switch(typeof t){case"number":if(Number.isInteger(t))return t;break;case"string":const r=e.findName(t);if(void 0!==r)return r.no;if(n)return ge}throw new Error("cannot decode enum ".concat(e.typeName," from JSON: ").concat(be(t)))}function Se(e){return!(!e.repeated&&"map"!=e.kind)||!e.oneof&&("message"!=e.kind&&(!e.opt&&!e.req))}function Ie(e,t,n){if("map"==e.kind){v("object"==typeof t&&null!=t);const r={},i=Object.entries(t);switch(e.V.kind){case"scalar":for(const[t,n]of i)r[t.toString()]=Ne(e.V.T,n);break;case"message":for(const[e,t]of i)r[e.toString()]=t.toJson(n);break;case"enum":const t=e.V.T;for(const[e,a]of i)r[e.toString()]=Ee(t,a,n.enumAsInteger)}return n.emitDefaultValues||i.length>0?r:void 0}if(e.repeated){v(Array.isArray(t));const r=[];switch(e.kind){case"scalar":for(let n=0;n<t.length;n++)r.push(Ne(e.T,t[n]));break;case"enum":for(let i=0;i<t.length;i++)r.push(Ee(e.T,t[i],n.enumAsInteger));break;case"message":for(let e=0;e<t.length;e++)r.push(t[e].toJson(n))}return n.emitDefaultValues||r.length>0?r:void 0}switch(e.kind){case"scalar":return Ne(e.T,t);case"enum":return Ee(e.T,t,n.enumAsInteger);case"message":return le(e.T,t).toJson(n)}}function Ee(e,t,n){var r;if(v("number"==typeof t),"google.protobuf.NullValue"==e.typeName)return null;if(n)return t;const i=e.findNumber(t);return null!==(r=null==i?void 0:i.name)&&void 0!==r?r:t}function Ne(e,t){switch(e){case X.INT32:case X.SFIXED32:case X.SINT32:case X.FIXED32:case X.UINT32:return v("number"==typeof t),t;case X.FLOAT:case X.DOUBLE:return v("number"==typeof t),Number.isNaN(t)?"NaN":t===Number.POSITIVE_INFINITY?"Infinity":t===Number.NEGATIVE_INFINITY?"-Infinity":t;case X.STRING:return v("string"==typeof t),t;case X.BOOL:return v("boolean"==typeof t),t;case X.UINT64:case X.FIXED64:case X.INT64:case X.SFIXED64:case X.SINT64:return v("bigint"==typeof t||"string"==typeof t||"number"==typeof t),t.toString();case X.BYTES:return v(t instanceof Uint8Array),re.enc(t)}}const Ae=Symbol("@bufbuild/protobuf/unknown-fields"),Ce={readUnknownFields:!0,readerFactory:e=>new Z(e)},Le={writeUnknownFields:!0,writerFactory:()=>new $};function Re(e){return e?Object.assign(Object.assign({},Ce),e):Ce}function Ue(e){return e?Object.assign(Object.assign({},Le),e):Le}function Oe(e,t,n,r,i){let{repeated:a,localName:o}=n;switch(n.oneof&&((e=e[n.oneof.localName]).case!=o&&delete e.value,e.case=o,o="value"),n.kind){case"scalar":case"enum":const s="enum"==n.kind?X.INT32:n.T;let c=De;if("scalar"==n.kind&&n.L>0&&(c=_e),a){let n=e[o];if(r==H.LengthDelimited&&s!=X.STRING&&s!=X.BYTES){let e=t.uint32()+t.pos;for(;t.pos<e;)n.push(c(t,s))}else n.push(c(t,s))}else e[o]=c(t,s);break;case"message":const d=n.T;a?e[o].push(Pe(t,new d,i,n)):ue(e[o])?Pe(t,e[o],i,n):(e[o]=Pe(t,new d,i,n),!d.fieldWrapper||n.oneof||n.repeated||(e[o]=d.fieldWrapper.unwrapField(e[o])));break;case"map":let[u,l]=function(e,t,n){const r=t.uint32(),i=t.pos+r;let a,o;for(;t.pos<i;){const[r]=t.tag();switch(r){case 1:a=De(t,e.K);break;case 2:switch(e.V.kind){case"scalar":o=De(t,e.V.T);break;case"enum":o=t.int32();break;case"message":o=Pe(t,new e.V.T,n,void 0)}}}void 0===a&&(a=Y(e.K,J.BIGINT));"string"!=typeof a&&"number"!=typeof a&&(a=a.toString());if(void 0===o)switch(e.V.kind){case"scalar":o=Y(e.V.T,J.BIGINT);break;case"enum":o=e.V.T.values[0].no;break;case"message":o=new e.V.T}return[a,o]}(n,t,i);e[o][u]=l}}function Pe(e,t,n,r){const i=t.getType().runtime.bin,a=null==r?void 0:r.delimited;return i.readMessage(t,e,a?r.no:e.uint32(),n,a),t}function _e(e,t){const n=De(e,t);return"bigint"==typeof n?n.toString():n}function De(e,t){switch(t){case X.STRING:return e.string();case X.BOOL:return e.bool();case X.DOUBLE:return e.double();case X.FLOAT:return e.float();case X.INT32:return e.int32();case X.INT64:return e.int64();case X.UINT64:return e.uint64();case X.FIXED64:return e.fixed64();case X.BYTES:return e.bytes();case X.FIXED32:return e.fixed32();case X.SFIXED32:return e.sfixed32();case X.SFIXED64:return e.sfixed64();case X.SINT64:return e.sint64();case X.UINT32:return e.uint32();case X.SINT32:return e.sint32()}}function Fe(e,t,n,r){v(void 0!==t);const i=e.repeated;switch(e.kind){case"scalar":case"enum":let a="enum"==e.kind?X.INT32:e.T;if(i)if(v(Array.isArray(t)),e.packed)!function(e,t,n,r){if(!r.length)return;e.tag(n,H.LengthDelimited).fork();let[,i]=Ke(t);for(let t=0;t<r.length;t++)e[i](r[t]);e.join()}(n,a,e.no,t);else for(const r of t)Me(n,a,e.no,r);else Me(n,a,e.no,t);break;case"message":if(i){v(Array.isArray(t));for(const i of t)Be(n,r,e,i)}else Be(n,r,e,t);break;case"map":v("object"==typeof t&&null!=t);for(const[i,a]of Object.entries(t))xe(n,r,e,i,a)}}function xe(e,t,n,r,i){e.tag(n.no,H.LengthDelimited),e.fork();let a=r;switch(n.K){case X.INT32:case X.FIXED32:case X.UINT32:case X.SFIXED32:case X.SINT32:a=Number.parseInt(r);break;case X.BOOL:v("true"==r||"false"==r),a="true"==r}switch(Me(e,n.K,1,a),n.V.kind){case"scalar":Me(e,n.V.T,2,i);break;case"enum":Me(e,X.INT32,2,i);break;case"message":v(void 0!==i),e.tag(2,H.LengthDelimited).bytes(i.toBinary(t))}e.join()}function Be(e,t,n,r){const i=le(n.T,r);n.delimited?e.tag(n.no,H.StartGroup).raw(i.toBinary(t)).tag(n.no,H.EndGroup):e.tag(n.no,H.LengthDelimited).bytes(i.toBinary(t))}function Me(e,t,n,r){v(void 0!==r);let[i,a]=Ke(t);e.tag(n,i)[a](r)}function Ke(e){let t=H.Varint;switch(e){case X.BYTES:case X.STRING:t=H.LengthDelimited;break;case X.DOUBLE:case X.FIXED64:case X.SFIXED64:t=H.Bit64;break;case X.FIXED32:case X.SFIXED32:case X.FLOAT:t=H.Bit32}return[t,X[e].toLowerCase()]}function je(e){if(void 0===e)return e;if(ue(e))return e.clone();if(e instanceof Uint8Array){const t=new Uint8Array(e.byteLength);return t.set(e),t}return e}function Ve(e){return e instanceof Uint8Array?e:new Uint8Array(e)}class We{constructor(e,t){this._fields=e,this._normalizer=t}findJsonName(e){if(!this.jsonNames){const e={};for(const t of this.list())e[t.jsonName]=e[t.name]=t;this.jsonNames=e}return this.jsonNames[e]}find(e){if(!this.numbers){const e={};for(const t of this.list())e[t.no]=t;this.numbers=e}return this.numbers[e]}list(){return this.all||(this.all=this._normalizer(this._fields)),this.all}byNumber(){return this.numbersAsc||(this.numbersAsc=this.list().concat().sort(((e,t)=>e.no-t.no))),this.numbersAsc}byMember(){if(!this.members){this.members=[];const e=this.members;let t;for(const n of this.list())n.oneof?n.oneof!==t&&(t=n.oneof,e.push(t)):e.push(n)}return this.members}}function qe(e,t){const n=Xe(e);return t?n:Qe(Ye(n))}const Ge=Xe;function Xe(e){let t=!1;const n=[];for(let r=0;r<e.length;r++){let i=e.charAt(r);switch(i){case"_":t=!0;break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":n.push(i),t=!1;break;default:t&&(t=!1,i=i.toUpperCase()),n.push(i)}}return n.join("")}const Je=new Set(["constructor","toString","toJSON","valueOf"]),He=new Set(["getType","clone","equals","fromBinary","fromJson","fromJsonString","toBinary","toJson","toJsonString","toObject"]),ze=e=>"".concat(e,"$"),Ye=e=>He.has(e)?ze(e):e,Qe=e=>Je.has(e)?ze(e):e;class $e{constructor(e){this.kind="oneof",this.repeated=!1,this.packed=!1,this.opt=!1,this.req=!1,this.default=void 0,this.fields=[],this.name=e,this.localName=qe(e,!1)}addField(e){v(e.oneof===this,"field ".concat(e.name," not one of ").concat(this.name)),this.fields.push(e)}findField(e){if(!this._lookup){this._lookup=Object.create(null);for(let e=0;e<this.fields.length;e++)this._lookup[this.fields[e].localName]=this.fields[e]}return this._lookup[e]}}const Ze=(et=e=>new We(e,(e=>function(e,t){var n,r,i,a,o,s;const c=[];let d;for(const t of"function"==typeof e?e():e){const e=t;if(e.localName=qe(t.name,void 0!==t.oneof),e.jsonName=null!==(n=t.jsonName)&&void 0!==n?n:Ge(t.name),e.repeated=null!==(r=t.repeated)&&void 0!==r&&r,"scalar"==t.kind&&(e.L=null!==(i=t.L)&&void 0!==i?i:J.BIGINT),e.delimited=null!==(a=t.delimited)&&void 0!==a&&a,e.req=null!==(o=t.req)&&void 0!==o&&o,e.opt=null!==(s=t.opt)&&void 0!==s&&s,void 0===t.packed&&(e.packed="enum"==t.kind||"scalar"==t.kind&&t.T!=X.BYTES&&t.T!=X.STRING),void 0!==t.oneof){const n="string"==typeof t.oneof?t.oneof:t.oneof.name;d&&d.name==n||(d=new $e(n)),e.oneof=d,d.addField(e)}c.push(e)}return c}(e))),tt=e=>{for(const t of e.getType().fields.byMember()){if(t.opt)continue;const n=t.localName,r=e;if(t.repeated)r[n]=[];else switch(t.kind){case"oneof":r[n]={case:void 0};break;case"enum":r[n]=0;break;case"map":r[n]={};break;case"scalar":r[n]=Y(t.T,t.L)}}},{syntax:"proto3",json:{makeReadOptions:pe,makeWriteOptions:ye,readMessage(e,t,n,r){if(null==t||Array.isArray(t)||"object"!=typeof t)throw new Error("cannot decode message ".concat(e.typeName," from JSON: ").concat(be(t)));r=null!=r?r:new e;const i=new Map,a=n.typeRegistry;for(const[o,s]of Object.entries(t)){const t=e.fields.findJsonName(o);if(t){if(t.oneof){if(null===s&&"scalar"==t.kind)continue;const n=i.get(t.oneof);if(void 0!==n)throw new Error("cannot decode message ".concat(e.typeName,' from JSON: multiple keys for oneof "').concat(t.oneof.name,'" present: "').concat(n,'", "').concat(o,'"'));i.set(t.oneof,o)}ve(r,s,t,n,e)}else{let t=!1;if((null==a?void 0:a.findExtension)&&o.startsWith("[")&&o.endsWith("]")){const i=a.findExtension(o.substring(1,o.length-1));if(i&&i.extendee.typeName==e.typeName){t=!0;const[e,a]=ee(i);ve(e,s,i.field,n,i),ae(r,i,a(),n)}}if(!t&&!n.ignoreUnknownFields)throw new Error("cannot decode message ".concat(e.typeName,' from JSON: key "').concat(o,'" is unknown'))}}return r},writeMessage(e,t){const n=e.getType(),r={};let i;try{for(i of n.fields.byNumber()){if(!ce(i,e)){if(i.req)throw"required field not set";if(!t.emitDefaultValues)continue;if(!Se(i))continue}const n=Ie(i,i.oneof?e[i.oneof.localName].value:e[i.localName],t);void 0!==n&&(r[t.useProtoFieldName?i.name:i.jsonName]=n)}const a=t.typeRegistry;if(null==a?void 0:a.findExtensionFor)for(const i of n.runtime.bin.listUnknownFields(e)){const o=a.findExtensionFor(n.typeName,i.no);if(o&&oe(e,o)){const n=ie(e,o,t),i=Ie(o.field,n,t);void 0!==i&&(r[o.field.jsonName]=i)}}}catch(e){const t=i?"cannot encode field ".concat(n.typeName,".").concat(i.name," to JSON"):"cannot encode message ".concat(n.typeName," to JSON"),r=e instanceof Error?e.message:String(e);throw new Error(t+(r.length>0?": ".concat(r):""))}return r},readScalar:(e,t,n)=>we(e,t,null!=n?n:J.BIGINT,!0),writeScalar(e,t,n){if(void 0!==t)return n||Q(e,t)?Ne(e,t):void 0},debug:be},bin:{makeReadOptions:Re,makeWriteOptions:Ue,listUnknownFields(e){var t;return null!==(t=e[Ae])&&void 0!==t?t:[]},discardUnknownFields(e){delete e[Ae]},writeUnknownFields(e,t){const n=e[Ae];if(n)for(const e of n)t.tag(e.no,e.wireType).raw(e.data)},onUnknownField(e,t,n,r){const i=e;Array.isArray(i[Ae])||(i[Ae]=[]),i[Ae].push({no:t,wireType:n,data:r})},readMessage(e,t,n,r,i){const a=e.getType(),o=i?t.len:t.pos+n;let s,c;for(;t.pos<o&&([s,c]=t.tag(),!0!==i||c!=H.EndGroup);){const n=a.fields.find(s);if(n)Oe(e,t,n,c,r);else{const n=t.skip(c,s);r.readUnknownFields&&this.onUnknownField(e,s,c,n)}}if(i&&(c!=H.EndGroup||s!==n))throw new Error("invalid end group tag")},readField:Oe,writeMessage(e,t,n){const r=e.getType();for(const i of r.fields.byNumber())if(ce(i,e))Fe(i,i.oneof?e[i.oneof.localName].value:e[i.localName],t,n);else if(i.req)throw new Error("cannot encode field ".concat(r.typeName,".").concat(i.name," to binary: required field not set"));return n.writeUnknownFields&&this.writeUnknownFields(e,t),t},writeField(e,t,n,r){void 0!==t&&Fe(e,t,n,r)}},util:Object.assign(Object.assign({},{setEnumType:R,initPartial(e,t){if(void 0===e)return;const n=t.getType();for(const r of n.fields.byMember()){const n=r.localName,i=t,a=e;if(null!=a[n])switch(r.kind){case"oneof":const e=a[n].case;if(void 0===e)continue;const t=r.findField(e);let o=a[n].value;t&&"message"==t.kind&&!ue(o,t.T)?o=new t.T(o):t&&"scalar"===t.kind&&t.T===X.BYTES&&(o=Ve(o)),i[n]={case:e,value:o};break;case"scalar":case"enum":let s=a[n];r.T===X.BYTES&&(s=r.repeated?s.map(Ve):Ve(s)),i[n]=s;break;case"map":switch(r.V.kind){case"scalar":case"enum":if(r.V.T===X.BYTES)for(const[e,t]of Object.entries(a[n]))i[n][e]=Ve(t);else Object.assign(i[n],a[n]);break;case"message":const e=r.V.T;for(const t of Object.keys(a[n])){let r=a[n][t];e.fieldWrapper||(r=new e(r)),i[n][t]=r}}break;case"message":const c=r.T;if(r.repeated)i[n]=a[n].map((e=>ue(e,c)?e:new c(e)));else{const e=a[n];c.fieldWrapper?"google.protobuf.BytesValue"===c.typeName?i[n]=Ve(e):i[n]=e:i[n]=ue(e,c)?e:new c(e)}}}},equals:(e,t,n)=>t===n||!(!t||!n)&&e.fields.byMember().every((e=>{const r=t[e.localName],i=n[e.localName];if(e.repeated){if(r.length!==i.length)return!1;switch(e.kind){case"message":return r.every(((t,n)=>e.T.equals(t,i[n])));case"scalar":return r.every(((t,n)=>z(e.T,t,i[n])));case"enum":return r.every(((e,t)=>z(X.INT32,e,i[t])))}throw new Error("repeated cannot contain ".concat(e.kind))}switch(e.kind){case"message":let t=r,n=i;return e.T.fieldWrapper&&(void 0===t||ue(t)||(t=e.T.fieldWrapper.wrapField(t)),void 0===n||ue(n)||(n=e.T.fieldWrapper.wrapField(n))),e.T.equals(t,n);case"enum":return z(X.INT32,r,i);case"scalar":return z(e.T,r,i);case"oneof":if(r.case!==i.case)return!1;const a=e.findField(r.case);if(void 0===a)return!0;switch(a.kind){case"message":return a.T.equals(r.value,i.value);case"enum":return z(X.INT32,r.value,i.value);case"scalar":return z(a.T,r.value,i.value)}throw new Error("oneof cannot contain ".concat(a.kind));case"map":const o=Object.keys(r).concat(Object.keys(i));switch(e.V.kind){case"message":const t=e.V.T;return o.every((e=>t.equals(r[e],i[e])));case"enum":return o.every((e=>z(X.INT32,r[e],i[e])));case"scalar":const n=e.V.T;return o.every((e=>z(n,r[e],i[e])))}}})),clone(e){const t=e.getType(),n=new t,r=n;for(const n of t.fields.byMember()){const t=e[n.localName];let i;if(n.repeated)i=t.map(je);else if("map"==n.kind){i=r[n.localName];for(const[e,n]of Object.entries(t))i[e]=je(n)}else i="oneof"==n.kind?n.findField(t.case)?{case:t.case,value:je(t.value)}:{case:void 0}:je(t);r[n.localName]=i}for(const n of t.runtime.bin.listUnknownFields(e))t.runtime.bin.onUnknownField(r,n.no,n.wireType,n.data);return n}}),{newFieldList:et,initFields:tt}),makeMessageType(e,t,n){return function(e,t,n,r){var i;const a=null!==(i=null==r?void 0:r.localName)&&void 0!==i?i:t.substring(t.lastIndexOf(".")+1),o={[a]:function(t){e.util.initFields(this),e.util.initPartial(t,this)}}[a];return Object.setPrototypeOf(o.prototype,new _),Object.assign(o,{runtime:e,typeName:t,fields:e.util.newFieldList(n),fromBinary:(e,t)=>(new o).fromBinary(e,t),fromJson:(e,t)=>(new o).fromJson(e,t),fromJsonString:(e,t)=>(new o).fromJsonString(e,t),equals:(t,n)=>e.util.equals(o,t,n)}),o}(this,e,t,n)},makeEnum:O,makeEnumType:U,getEnumType:L,makeExtension(e,t,n){return function(e,t,n,r){let i;return{typeName:t,extendee:n,get field(){if(!i){const n="function"==typeof r?r():r;n.name=t.split(".").pop(),n.jsonName="[".concat(t,"]"),i=e.util.newFieldList([n]).list()[0]}return i},runtime:e}}(this,e,t,n)}});var et,tt;const nt=Ze.makeEnum("livekit.TrackType",[{no:0,name:"AUDIO"},{no:1,name:"VIDEO"},{no:2,name:"DATA"}]),rt=Ze.makeEnum("livekit.TrackSource",[{no:0,name:"UNKNOWN"},{no:1,name:"CAMERA"},{no:2,name:"MICROPHONE"},{no:3,name:"SCREEN_SHARE"},{no:4,name:"SCREEN_SHARE_AUDIO"}]),it=Ze.makeEnum("livekit.StreamState",[{no:0,name:"ACTIVE"},{no:1,name:"PAUSED"}]);class at extends Error{constructor(e,t,n){super(t||"an error has occurred"),this.name="LiveKitError",this.code=e,void 0!==(null==n?void 0:n.cause)&&(this.cause=null==n?void 0:n.cause)}}var ot,st,ct,dt,ut,lt,ht,ft;!function(e){e[e.NotAllowed=0]="NotAllowed",e[e.ServerUnreachable=1]="ServerUnreachable",e[e.InternalError=2]="InternalError",e[e.Cancelled=3]="Cancelled",e[e.LeaveRequest=4]="LeaveRequest",e[e.Timeout=5]="Timeout",e[e.WebSocket=6]="WebSocket",e[e.ServiceNotFound=7]="ServiceNotFound"}(ot||(ot={})),function(e){e[e.AlreadyOpened=0]="AlreadyOpened",e[e.AbnormalEnd=1]="AbnormalEnd",e[e.DecodeFailed=2]="DecodeFailed",e[e.LengthExceeded=3]="LengthExceeded",e[e.Incomplete=4]="Incomplete",e[e.HandlerAlreadyRegistered=7]="HandlerAlreadyRegistered",e[e.EncryptionTypeMismatch=8]="EncryptionTypeMismatch"}(st||(st={})),function(e){e.PermissionDenied="PermissionDenied",e.NotFound="NotFound",e.DeviceInUse="DeviceInUse",e.Other="Other"}(ct||(ct={})),function(e){e.getFailure=function(t){if(t&&"name"in t)return"NotFoundError"===t.name||"DevicesNotFoundError"===t.name?e.NotFound:"NotAllowedError"===t.name||"PermissionDeniedError"===t.name?e.PermissionDenied:"NotReadableError"===t.name||"TrackStartError"===t.name?e.DeviceInUse:e.Other}}(ct||(ct={})),function(e){e[e.InvalidKey=0]="InvalidKey",e[e.MissingKey=1]="MissingKey",e[e.InternalError=2]="InternalError"}(dt||(dt={}));class pt extends at{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:dt.InternalError,n=arguments.length>2?arguments[2]:void 0;super(40,e),this.reason=t,this.participantIdentity=n}}function yt(e){return"type"in e}function mt(e,t){const n=(new TextEncoder).encode(t);switch(e){case"HKDF":return{name:"HKDF",salt:n,hash:"SHA-256",info:new ArrayBuffer(128)};case"PBKDF2":return{name:"PBKDF2",salt:n,hash:"SHA-256",iterations:1e5};default:throw new Error("algorithm ".concat(e," is currently unsupported"))}}function gt(t,n){return e(this,void 0,void 0,(function*(){const e=mt(t.algorithm.name,n.ratchetSalt),r=yield crypto.subtle.deriveKey(e,t,{name:m,length:n.keySize},!1,["encrypt","decrypt"]);return{material:t,encryptionKey:r}}))}!function(e){e.SetKey="setKey",e.RatchetRequest="ratchetRequest",e.KeyRatcheted="keyRatcheted"}(ut||(ut={})),function(e){e.KeyRatcheted="keyRatcheted"}(lt||(lt={})),function(e){e.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",e.EncryptionError="encryptionError"}(ht||(ht={})),function(e){e.Error="cryptorError"}(ft||(ft={}));class bt{static makeIV(e){const t=new ArrayBuffer(12),n=new DataView(t),r=crypto.getRandomValues(new Uint32Array(1));return n.setUint32(0,r[0]),n.setUint32(4,e),n.setUint32(8,e-bt.sendCount%65535),bt.sendCount++,t}static encrypt(t,n){return e(this,void 0,void 0,(function*(){const e=bt.makeIV(performance.now()),r=yield n.getKeySet();if(!r)throw new Error("No key set found");const i=yield crypto.subtle.encrypt({name:m,iv:e},r.encryptionKey,new Uint8Array(t));return{payload:new Uint8Array(i),iv:new Uint8Array(e),keyIndex:n.getCurrentKeyIndex()}}))}static decrypt(t,n,r){return e(this,arguments,void 0,(function(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,i=arguments.length>4?arguments[4]:void 0,a=arguments.length>5&&void 0!==arguments[5]?arguments[5]:{ratchetCount:0};return function*(){const o=yield n.getKeySet(r);if(!o)throw new Error("No key set found");try{const n=yield crypto.subtle.decrypt({name:m,iv:t},o.encryptionKey,new Uint8Array(e));return{payload:new Uint8Array(n)}}catch(s){if(n.keyProviderOptions.ratchetWindowSize>0){if(a.ratchetCount<n.keyProviderOptions.ratchetWindowSize){let s,c;l.debug("DataCryptor: ratcheting key attempt ".concat(a.ratchetCount," of ").concat(n.keyProviderOptions.ratchetWindowSize,", for data packet")),(null!=i?i:o)===n.getKeySet(r)&&(c=yield n.ratchetKey(r,!1),s=yield gt(c.cryptoKey,n.keyProviderOptions));const d=yield bt.decrypt(e,t,n,r,i,{ratchetCount:a.ratchetCount+1,encryptionKey:null==s?void 0:s.encryptionKey});return d&&s&&(null!=i?i:o)===n.getKeySet(r)&&(n.setKeySet(s,r,c),n.setCurrentKeyIndex(r)),d}throw l.warn("DataCryptor: maximum ratchet attempts exceeded"),new pt("DataCryptor: valid key missing for participant ".concat(n.participantIdentity),dt.InvalidKey,n.participantIdentity)}throw new pt("DataCryptor: Decryption failed: ".concat(s.message),dt.InvalidKey,n.participantIdentity)}}()}))}}bt.sendCount=0;var vt,kt={exports:{}};var wt,Tt,St=function(){if(vt)return kt.exports;vt=1;var e,t="object"==typeof Reflect?Reflect:null,n=t&&"function"==typeof t.apply?t.apply:function(e,t,n){return Function.prototype.apply.call(e,t,n)};e=t&&"function"==typeof t.ownKeys?t.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var r=Number.isNaN||function(e){return e!=e};function i(){i.init.call(this)}kt.exports=i,kt.exports.once=function(e,t){return new Promise((function(n,r){function i(n){e.removeListener(t,a),r(n)}function a(){"function"==typeof e.removeListener&&e.removeListener("error",i),n([].slice.call(arguments))}p(e,t,a,{once:!0}),"error"!==t&&function(e,t,n){"function"==typeof e.on&&p(e,"error",t,n)}(e,i,{once:!0})}))},i.EventEmitter=i,i.prototype._events=void 0,i.prototype._eventsCount=0,i.prototype._maxListeners=void 0;var a=10;function o(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function s(e){return void 0===e._maxListeners?i.defaultMaxListeners:e._maxListeners}function c(e,t,n,r){var i,a,c,d;if(o(n),void 0===(a=e._events)?(a=e._events=Object.create(null),e._eventsCount=0):(void 0!==a.newListener&&(e.emit("newListener",t,n.listener?n.listener:n),a=e._events),c=a[t]),void 0===c)c=a[t]=n,++e._eventsCount;else if("function"==typeof c?c=a[t]=r?[n,c]:[c,n]:r?c.unshift(n):c.push(n),(i=s(e))>0&&c.length>i&&!c.warned){c.warned=!0;var u=new Error("Possible EventEmitter memory leak detected. "+c.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");u.name="MaxListenersExceededWarning",u.emitter=e,u.type=t,u.count=c.length,d=u,console&&console.warn&&console.warn(d)}return e}function d(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function u(e,t,n){var r={fired:!1,wrapFn:void 0,target:e,type:t,listener:n},i=d.bind(r);return i.listener=n,r.wrapFn=i,i}function l(e,t,n){var r=e._events;if(void 0===r)return[];var i=r[t];return void 0===i?[]:"function"==typeof i?n?[i.listener||i]:[i]:n?function(e){for(var t=new Array(e.length),n=0;n<t.length;++n)t[n]=e[n].listener||e[n];return t}(i):f(i,i.length)}function h(e){var t=this._events;if(void 0!==t){var n=t[e];if("function"==typeof n)return 1;if(void 0!==n)return n.length}return 0}function f(e,t){for(var n=new Array(t),r=0;r<t;++r)n[r]=e[r];return n}function p(e,t,n,r){if("function"==typeof e.on)r.once?e.once(t,n):e.on(t,n);else{if("function"!=typeof e.addEventListener)throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof e);e.addEventListener(t,(function i(a){r.once&&e.removeEventListener(t,i),n(a)}))}}return Object.defineProperty(i,"defaultMaxListeners",{enumerable:!0,get:function(){return a},set:function(e){if("number"!=typeof e||e<0||r(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");a=e}}),i.init=function(){void 0!==this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},i.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||r(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this},i.prototype.getMaxListeners=function(){return s(this)},i.prototype.emit=function(e){for(var t=[],r=1;r<arguments.length;r++)t.push(arguments[r]);var i="error"===e,a=this._events;if(void 0!==a)i=i&&void 0===a.error;else if(!i)return!1;if(i){var o;if(t.length>0&&(o=t[0]),o instanceof Error)throw o;var s=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw s.context=o,s}var c=a[e];if(void 0===c)return!1;if("function"==typeof c)n(c,this,t);else{var d=c.length,u=f(c,d);for(r=0;r<d;++r)n(u[r],this,t)}return!0},i.prototype.addListener=function(e,t){return c(this,e,t,!1)},i.prototype.on=i.prototype.addListener,i.prototype.prependListener=function(e,t){return c(this,e,t,!0)},i.prototype.once=function(e,t){return o(t),this.on(e,u(this,e,t)),this},i.prototype.prependOnceListener=function(e,t){return o(t),this.prependListener(e,u(this,e,t)),this},i.prototype.removeListener=function(e,t){var n,r,i,a,s;if(o(t),void 0===(r=this._events))return this;if(void 0===(n=r[e]))return this;if(n===t||n.listener===t)0==--this._eventsCount?this._events=Object.create(null):(delete r[e],r.removeListener&&this.emit("removeListener",e,n.listener||t));else if("function"!=typeof n){for(i=-1,a=n.length-1;a>=0;a--)if(n[a]===t||n[a].listener===t){s=n[a].listener,i=a;break}if(i<0)return this;0===i?n.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(n,i),1===n.length&&(r[e]=n[0]),void 0!==r.removeListener&&this.emit("removeListener",e,s||t)}return this},i.prototype.off=i.prototype.removeListener,i.prototype.removeAllListeners=function(e){var t,n,r;if(void 0===(n=this._events))return this;if(void 0===n.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==n[e]&&(0==--this._eventsCount?this._events=Object.create(null):delete n[e]),this;if(0===arguments.length){var i,a=Object.keys(n);for(r=0;r<a.length;++r)"removeListener"!==(i=a[r])&&this.removeAllListeners(i);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=n[e]))this.removeListener(e,t);else if(void 0!==t)for(r=t.length-1;r>=0;r--)this.removeListener(e,t[r]);return this},i.prototype.listeners=function(e){return l(this,e,!0)},i.prototype.rawListeners=function(e){return l(this,e,!1)},i.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):h.call(e,t)},i.prototype.listenerCount=h,i.prototype.eventNames=function(){return this._eventsCount>0?e(this._events):[]},kt.exports}();class It extends(Tt=Promise){constructor(e){super(e)}catch(e){return super.catch(e)}static reject(e){return super.reject(e)}static all(e){return super.all(e)}static race(e){return super.race(e)}}wt=It,It.resolve=e=>Reflect.get(Tt,"resolve",wt).call(wt,e);const Et=/version\/(\d+(\.?_?\d+)+)/i;let Nt;function At(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if("undefined"==typeof navigator)return;const n=navigator.userAgent.toLowerCase();if(void 0===Nt||t){const e=Ct.find((e=>{let{test:t}=e;return t.test(n)}));Nt=null==e?void 0:e.describe(n)}return Nt}const Ct=[{test:/firefox|iceweasel|fxios/i,describe:e=>({name:"Firefox",version:Lt(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:Rt(e)})},{test:/chrom|crios|crmo/i,describe:e=>({name:"Chrome",version:Lt(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("crios")?"iOS":void 0,osVersion:Rt(e)})},{test:/safari|applewebkit/i,describe:e=>({name:"Safari",version:Lt(Et,e),os:e.includes("mobile/")?"iOS":"macOS",osVersion:Rt(e)})}];function Lt(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;const r=t.match(e);return r&&r.length>=n&&r[n]||""}function Rt(e){return e.includes("mac os")?Lt(/\(.+?(\d+_\d+(:?_\d+)?)/,e,1).replace(/_/g,"."):void 0}var Ut,Ot,Pt,_t,Dt,Ft;!function(e){e.Connected="connected",e.Reconnecting="reconnecting",e.SignalReconnecting="signalReconnecting",e.Reconnected="reconnected",e.Disconnected="disconnected",e.ConnectionStateChanged="connectionStateChanged",e.Moved="moved",e.MediaDevicesChanged="mediaDevicesChanged",e.ParticipantConnected="participantConnected",e.ParticipantDisconnected="participantDisconnected",e.TrackPublished="trackPublished",e.TrackSubscribed="trackSubscribed",e.TrackSubscriptionFailed="trackSubscriptionFailed",e.TrackUnpublished="trackUnpublished",e.TrackUnsubscribed="trackUnsubscribed",e.TrackMuted="trackMuted",e.TrackUnmuted="trackUnmuted",e.LocalTrackPublished="localTrackPublished",e.LocalTrackUnpublished="localTrackUnpublished",e.LocalAudioSilenceDetected="localAudioSilenceDetected",e.ActiveSpeakersChanged="activeSpeakersChanged",e.ParticipantMetadataChanged="participantMetadataChanged",e.ParticipantNameChanged="participantNameChanged",e.ParticipantAttributesChanged="participantAttributesChanged",e.ParticipantActive="participantActive",e.RoomMetadataChanged="roomMetadataChanged",e.DataReceived="dataReceived",e.SipDTMFReceived="sipDTMFReceived",e.TranscriptionReceived="transcriptionReceived",e.ConnectionQualityChanged="connectionQualityChanged",e.TrackStreamStateChanged="trackStreamStateChanged",e.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",e.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",e.AudioPlaybackStatusChanged="audioPlaybackChanged",e.VideoPlaybackStatusChanged="videoPlaybackChanged",e.MediaDevicesError="mediaDevicesError",e.ParticipantPermissionsChanged="participantPermissionsChanged",e.SignalConnected="signalConnected",e.RecordingStatusChanged="recordingStatusChanged",e.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",e.EncryptionError="encryptionError",e.DCBufferStatusChanged="dcBufferStatusChanged",e.ActiveDeviceChanged="activeDeviceChanged",e.ChatMessage="chatMessage",e.LocalTrackSubscribed="localTrackSubscribed",e.MetricsReceived="metricsReceived",e.DataTrackPublished="dataTrackPublished",e.DataTrackUnpublished="dataTrackUnpublished",e.LocalDataTrackPublished="localDataTrackPublished",e.LocalDataTrackUnpublished="localDataTrackUnpublished"}(Ut||(Ut={})),function(e){e.TrackPublished="trackPublished",e.TrackSubscribed="trackSubscribed",e.TrackSubscriptionFailed="trackSubscriptionFailed",e.TrackUnpublished="trackUnpublished",e.TrackUnsubscribed="trackUnsubscribed",e.TrackMuted="trackMuted",e.TrackUnmuted="trackUnmuted",e.LocalTrackPublished="localTrackPublished",e.LocalTrackUnpublished="localTrackUnpublished",e.LocalTrackCpuConstrained="localTrackCpuConstrained",e.LocalSenderCreated="localSenderCreated",e.ParticipantMetadataChanged="participantMetadataChanged",e.ParticipantNameChanged="participantNameChanged",e.DataReceived="dataReceived",e.SipDTMFReceived="sipDTMFReceived",e.TranscriptionReceived="transcriptionReceived",e.IsSpeakingChanged="isSpeakingChanged",e.ConnectionQualityChanged="connectionQualityChanged",e.TrackStreamStateChanged="trackStreamStateChanged",e.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",e.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",e.TrackCpuConstrained="trackCpuConstrained",e.MediaDevicesError="mediaDevicesError",e.AudioStreamAcquired="audioStreamAcquired",e.ParticipantPermissionsChanged="participantPermissionsChanged",e.PCTrackAdded="pcTrackAdded",e.AttributesChanged="attributesChanged",e.LocalTrackSubscribed="localTrackSubscribed",e.ChatMessage="chatMessage",e.Active="active"}(Ot||(Ot={})),function(e){e.TransportsCreated="transportsCreated",e.Connected="connected",e.Disconnected="disconnected",e.Resuming="resuming",e.Resumed="resumed",e.Restarting="restarting",e.Restarted="restarted",e.SignalResumed="signalResumed",e.SignalRestarted="signalRestarted",e.Closing="closing",e.MediaTrackAdded="mediaTrackAdded",e.ActiveSpeakersUpdate="activeSpeakersUpdate",e.DataPacketReceived="dataPacketReceived",e.RTPVideoMapUpdate="rtpVideoMapUpdate",e.DCBufferStatusChanged="dcBufferStatusChanged",e.ParticipantUpdate="participantUpdate",e.RoomUpdate="roomUpdate",e.SpeakersChanged="speakersChanged",e.StreamStateChanged="streamStateChanged",e.ConnectionQualityUpdate="connectionQualityUpdate",e.SubscriptionError="subscriptionError",e.SubscriptionPermissionUpdate="subscriptionPermissionUpdate",e.RemoteMute="remoteMute",e.SubscribedQualityUpdate="subscribedQualityUpdate",e.LocalTrackUnpublished="localTrackUnpublished",e.LocalTrackSubscribed="localTrackSubscribed",e.Offline="offline",e.SignalRequestResponse="signalRequestResponse",e.SignalConnected="signalConnected",e.RoomMoved="roomMoved",e.PublishDataTrackResponse="publishDataTrackResponse",e.UnPublishDataTrackResponse="unPublishDataTrackResponse",e.DataTrackSubscriberHandles="dataTrackSubscriberHandles",e.DataTrackPacketReceived="dataTrackPacketReceived",e.Joined="joined",e.TokenRefreshed="tokenRefreshed",e.ServerRegionsReported="serverRegionsReported"}(Pt||(Pt={})),function(e){e.Message="message",e.Muted="muted",e.Unmuted="unmuted",e.Restarted="restarted",e.Ended="ended",e.Subscribed="subscribed",e.Unsubscribed="unsubscribed",e.CpuConstrained="cpuConstrained",e.UpdateSettings="updateSettings",e.UpdateSubscription="updateSubscription",e.AudioPlaybackStarted="audioPlaybackStarted",e.AudioPlaybackFailed="audioPlaybackFailed",e.AudioSilenceDetected="audioSilenceDetected",e.VisibilityChanged="visibilityChanged",e.VideoDimensionsChanged="videoDimensionsChanged",e.VideoPlaybackStarted="videoPlaybackStarted",e.VideoPlaybackFailed="videoPlaybackFailed",e.ElementAttached="elementAttached",e.ElementDetached="elementDetached",e.UpstreamPaused="upstreamPaused",e.UpstreamResumed="upstreamResumed",e.SubscriptionPermissionChanged="subscriptionPermissionChanged",e.SubscriptionStatusChanged="subscriptionStatusChanged",e.SubscriptionFailed="subscriptionFailed",e.TrackProcessorUpdate="trackProcessorUpdate",e.AudioTrackFeatureUpdate="audioTrackFeatureUpdate",e.TranscriptionReceived="transcriptionReceived",e.TimeSyncUpdate="timeSyncUpdate",e.PreConnectBufferFlushed="preConnectBufferFlushed"}(_t||(_t={}));class xt{constructor(e,t,n,r,i){if("object"==typeof e)this.width=e.width,this.height=e.height,this.aspectRatio=e.aspectRatio,this.encoding={maxBitrate:e.maxBitrate,maxFramerate:e.maxFramerate,priority:e.priority};else{if(void 0===t||void 0===n)throw new TypeError("Unsupported options: provide at least width, height and maxBitrate");this.width=e,this.height=t,this.aspectRatio=e/t,this.encoding={maxBitrate:n,maxFramerate:r,priority:i}}}get resolution(){return{width:this.width,height:this.height,frameRate:this.encoding.maxFramerate,aspectRatio:this.aspectRatio}}}function Bt(e){return"mediaStreamTrack"in e?{trackID:e.sid,source:e.source,muted:e.isMuted,enabled:e.mediaStreamTrack.enabled,kind:e.kind,streamID:e.mediaStreamID,streamTrackID:e.mediaStreamTrack.id}:{trackID:e.trackSid,enabled:e.isEnabled,muted:e.isMuted,trackInfo:Object.assign({mimeType:e.mimeType,name:e.trackName,encrypted:e.isEncrypted,kind:e.kind,source:e.source},e.track?Bt(e.track):{})}}!function(e){e[e.PREFER_REGRESSION=0]="PREFER_REGRESSION",e[e.SIMULCAST=1]="SIMULCAST",e[e.REGRESSION=2]="REGRESSION"}(Dt||(Dt={})),function(e){e.telephone={maxBitrate:12e3},e.speech={maxBitrate:24e3},e.music={maxBitrate:48e3},e.musicStereo={maxBitrate:64e3},e.musicHighQuality={maxBitrate:96e3},e.musicHighQualityStereo={maxBitrate:128e3}}(Ft||(Ft={})),new xt(160,90,9e4,20),new xt(320,180,16e4,20),new xt(384,216,18e4,20),new xt(640,360,45e4,20),new xt(960,540,8e5,25),new xt(1280,720,17e5,30),new xt(1920,1080,3e6,30),new xt(2560,1440,5e6,30),new xt(3840,2160,8e6,30),new xt(160,120,7e4,20),new xt(240,180,125e3,20),new xt(320,240,14e4,20),new xt(480,360,33e4,20),new xt(640,480,5e5,20),new xt(720,540,6e5,25),new xt(960,720,13e5,30),new xt(1440,1080,23e5,30),new xt(1920,1440,38e5,30),new xt(640,360,2e5,3,"medium"),new xt(640,360,4e5,15,"medium"),new xt(1280,720,8e5,5,"medium"),new xt(1280,720,15e5,15,"medium"),new xt(1280,720,2e6,30,"medium"),new xt(1920,1080,25e5,15,"medium"),new xt(1920,1080,5e6,30,"medium"),new xt(0,0,7e6,30,"medium");const Mt=[];var Kt;!function(e){e[e.LOW=0]="LOW",e[e.MEDIUM=1]="MEDIUM",e[e.HIGH=2]="HIGH"}(Kt||(Kt={}));class jt extends St.EventEmitter{get streamState(){return this._streamState}setStreamState(e){this._streamState=e}constructor(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};var r;super(),this.attachedElements=[],this.isMuted=!1,this._streamState=jt.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.log=d,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),"hidden"===document.visibilityState?this.backgroundTimeout=setTimeout((()=>this.handleAppVisibilityChanged()),5e3):this.handleAppVisibilityChanged()},this.log=u(null!==(r=n.loggerName)&&void 0!==r?r:s.Track),this.loggerContextCb=n.loggerContextCb,this.setMaxListeners(100),this.kind=t,this._mediaStreamTrack=e,this._mediaStreamID=e.id,this.source=jt.Source.Unknown}get logContext(){var e;return Object.assign(Object.assign({},null===(e=this.loggerContextCb)||void 0===e?void 0:e.call(this)),Bt(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(e){let t="audio";this.kind===jt.Kind.Video&&(t="video"),0===this.attachedElements.length&&this.kind===jt.Kind.Video&&this.addAppVisibilityListener(),e||("audio"===t&&(Mt.forEach((t=>{null!==t.parentElement||e||(e=t)})),e&&Mt.splice(Mt.indexOf(e),1)),e||(e=document.createElement(t))),this.attachedElements.includes(e)||this.attachedElements.push(e),function(e,t){let n,r;n=t.srcObject instanceof MediaStream?t.srcObject:new MediaStream;r="audio"===e.kind?n.getAudioTracks():n.getVideoTracks();r.includes(e)||(r.forEach((e=>{n.removeTrack(e)})),n.addTrack(e));Wt()&&t instanceof HTMLVideoElement||(t.autoplay=!0);t.muted=0===n.getAudioTracks().length,t instanceof HTMLVideoElement&&(t.playsInline=!0);t.srcObject!==n&&(t.srcObject=n,(Wt()||function(){var e;return"Firefox"===(null===(e=At())||void 0===e?void 0:e.name)}())&&t instanceof HTMLVideoElement&&setTimeout((()=>{t.srcObject=n,t.play().catch((()=>{}))}),0))}(this.mediaStreamTrack,e);const n=e.srcObject.getTracks(),r=n.some((e=>"audio"===e.kind));return e.play().then((()=>{this.emit(r?_t.AudioPlaybackStarted:_t.VideoPlaybackStarted)})).catch((t=>{"NotAllowedError"===t.name?this.emit(r?_t.AudioPlaybackFailed:_t.VideoPlaybackFailed,t):"AbortError"===t.name?d.debug("".concat(r?"audio":"video"," playback aborted, likely due to new play request")):d.warn("could not playback ".concat(r?"audio":"video"),t),r&&e&&n.some((e=>"video"===e.kind))&&"NotAllowedError"===t.name&&(e.muted=!0,e.play().catch((()=>{})))})),this.emit(_t.ElementAttached,e),e}detach(e){try{if(e){Vt(this.mediaStreamTrack,e);const t=this.attachedElements.indexOf(e);return t>=0&&(this.attachedElements.splice(t,1),this.recycleElement(e),this.emit(_t.ElementDetached,e)),e}const t=[];return this.attachedElements.forEach((e=>{Vt(this.mediaStreamTrack,e),t.push(e),this.recycleElement(e),this.emit(_t.ElementDetached,e)})),this.attachedElements=[],t}finally{0===this.attachedElements.length&&this.removeAppVisibilityListener()}}stop(){this.stopMonitor(),this._mediaStreamTrack.stop()}enable(){this._mediaStreamTrack.enabled=!0}disable(){this._mediaStreamTrack.enabled=!1}stopMonitor(){this.monitorInterval&&clearInterval(this.monitorInterval),this.timeSyncHandle&&cancelAnimationFrame(this.timeSyncHandle)}updateLoggerOptions(e){e.loggerName&&(this.log=u(e.loggerName)),e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb)}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),Mt.forEach((e=>{e.parentElement||(t=!1)})),t&&Mt.push(e)}}handleAppVisibilityChanged(){return e(this,void 0,void 0,(function*(){this.isInBackground="hidden"===document.visibilityState,this.isInBackground||this.kind!==jt.Kind.Video||setTimeout((()=>this.attachedElements.forEach((e=>e.play().catch((()=>{}))))),0)}))}addAppVisibilityListener(){qt()?(this.isInBackground="hidden"===document.visibilityState,document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){qt()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function Vt(e,t){if(t.srcObject instanceof MediaStream){const n=t.srcObject;n.removeTrack(e),n.getTracks().length>0?t.srcObject=n:t.srcObject=null}}function Wt(){var e;return"Safari"===(null===(e=At())||void 0===e?void 0:e.name)}function qt(){return"undefined"!=typeof document}function Gt(e){return!(!(null==e?void 0:e.timestamp)&&!(null==e?void 0:e.frameId))}!function(e){let t,n,r;!function(e){e.Audio="audio",e.Video="video",e.Unknown="unknown"}(t=e.Kind||(e.Kind={})),function(e){e.Camera="camera",e.Microphone="microphone",e.ScreenShare="screen_share",e.ScreenShareAudio="screen_share_audio",e.Unknown="unknown"}(n=e.Source||(e.Source={})),function(e){e.Active="active",e.Paused="paused",e.Unknown="unknown"}(r=e.StreamState||(e.StreamState={})),e.kindToProto=function(e){switch(e){case t.Audio:return nt.AUDIO;case t.Video:return nt.VIDEO;default:return nt.DATA}},e.kindFromProto=function(e){switch(e){case nt.AUDIO:return t.Audio;case nt.VIDEO:return t.Video;default:return t.Unknown}},e.sourceToProto=function(e){switch(e){case n.Camera:return rt.CAMERA;case n.Microphone:return rt.MICROPHONE;case n.ScreenShare:return rt.SCREEN_SHARE;case n.ScreenShareAudio:return rt.SCREEN_SHARE_AUDIO;default:return rt.UNKNOWN}},e.sourceFromProto=function(e){switch(e){case rt.CAMERA:return n.Camera;case rt.MICROPHONE:return n.Microphone;case rt.SCREEN_SHARE:return n.ScreenShare;case rt.SCREEN_SHARE_AUDIO:return n.ScreenShareAudio;default:return n.Unknown}},e.streamStateFromProto=function(e){switch(e){case it.ACTIVE:return r.Active;case it.PAUSED:return r.Paused;default:return r.Unknown}}}(jt||(jt={}));const Xt=Uint8Array.from(["L".charCodeAt(0),"K".charCodeAt(0),"T".charCodeAt(0),"S".charCodeAt(0)]),Jt=1,Ht=2,zt=5,Yt=10,Qt=6;function $t(e,t,n){const r=t!==BigInt(0),i=0!==n;if(!r&&!i)return e;const a=(r?Yt:0)+(i?Qt:0)+zt,o=new Uint8Array(e.length+a);let s=0;return o.set(e,s),s+=e.length,r&&(o[s++]=255^Jt,o[s++]=247,function(e,t,n){const r=Number(n>>BigInt(32)&BigInt(4294967295)),i=Number(n&BigInt(4294967295));e[t]=r>>>24^255,e[t+1]=r>>>16&255^255,e[t+2]=r>>>8&255^255,e[t+3]=255&r^255,e[t+4]=i>>>24^255,e[t+5]=i>>>16&255^255,e[t+6]=i>>>8&255^255,e[t+7]=255&i^255}(o,s,t),s+=8),i&&(o[s++]=255^Ht,o[s++]=251,function(e,t,n){for(let r=3;r>=0;r-=1)e[t+(3-r)]=n>>8*r&255^255}(o,s,n),s+=4),o[s++]=255^a,o.set(Xt,s),o}function Zt(e){const t=e instanceof Uint8Array?e:new Uint8Array(e);if(t.length<zt)return{data:t};if(!function(e,t){for(let n=0;n<Xt.length;n+=1)if(e[t+n]!==Xt[n])return!1;return!0}(t,t.length-Xt.length))return{data:t};const n=255^t[t.length-zt];if(n<zt||n>t.length)return{data:t};const r=t.length-n,i=t.length-zt,a=t.subarray(0,r);let o=r,s=!1;const c={userTimestamp:BigInt(0),frameId:0};for(;o+2<=i;){const e=255^t[o++],n=255^t[o++];if(o+n>i)break;e===Jt&&8===n?(c.userTimestamp=en(t,o),s=!0):e===Ht&&4===n&&(c.frameId=tn(t,o,n),s=!0),o+=n}return s?{data:a,metadata:c}:{data:t}}function en(e,t){const n=BigInt(((255^e[t])<<24|(255^e[t+1])<<16|(255^e[t+2])<<8|255^e[t+3])>>>0),r=BigInt(((255^e[t+4])<<24|(255^e[t+5])<<16|(255^e[t+6])<<8|255^e[t+7])>>>0);return n<<BigInt(32)|r}function tn(e,t,n){let r=0;for(let i=0;i<n;i+=1)r=r<<8|255^e[t+i];return r>>>0}function nn(e){try{const t=e.getMetadata();if("number"==typeof t.synchronizationSource)return t.synchronizationSource}catch(e){}return 0}const rn=31;var an,on;function sn(e){return e&rn}function cn(e){return e>>1&63}function dn(e){return e===an.SLICE_IDR||e===an.SLICE_NON_IDR}function un(e){return e===on.TRAIL_N||e===on.TRAIL_R||e===on.TSA_N||e===on.TSA_R||e===on.STSA_N||e===on.STSA_R||e===on.RADL_N||e===on.RADL_R||e===on.RASL_N||e===on.RASL_R||e===on.BLA_W_LP||e===on.BLA_W_RADL||e===on.BLA_N_LP||e===on.IDR_W_RADL||e===on.IDR_N_LP||e===on.CRA_NUT}function ln(e,t){const n=function(e){const t=[];let n=0,r=0,i=e.length-3;for(;r<i;){for(;r<i&&!(r<i-1&&0===e[r]&&0===e[r+1]&&0===e[r+2]&&1===e[r+3])&&(0!==e[r]||0!==e[r+1]||1!==e[r+2]);)r++;r>=i&&(r=e.length);let a=r;for(;a>n&&0===e[a-1];)a--;if(0===n){if(a!==n)throw TypeError("byte stream contains leading data")}else t.push(n);let o=3;r<e.length-3&&0===e[r]&&0===e[r+1]&&0===e[r+2]&&1===e[r+3]&&(o=4),n=r+=o}return t}(e),r=null!=t?t:function(e,t){for(const n of t){if(dn(sn(e[n])))return"h264";if(un(cn(e[n])))return"h265"}return"unknown"}(e,n);if("unknown"===r)return{unencryptedBytes:0,detectedCodec:r,requiresNALUProcessing:!1};const i=function(e,t,n){for(const r of t)if("h265"===n){if(un(cn(e[r])))return r+2}else if(dn(sn(e[r])))return r+2;return null}(e,n,r);if(null===i)throw new TypeError("Could not find NALU");return{unencryptedBytes:i,detectedCodec:r,requiresNALUProcessing:!0}}!function(e){e[e.SLICE_NON_IDR=1]="SLICE_NON_IDR",e[e.SLICE_PARTITION_A=2]="SLICE_PARTITION_A",e[e.SLICE_PARTITION_B=3]="SLICE_PARTITION_B",e[e.SLICE_PARTITION_C=4]="SLICE_PARTITION_C",e[e.SLICE_IDR=5]="SLICE_IDR",e[e.SEI=6]="SEI",e[e.SPS=7]="SPS",e[e.PPS=8]="PPS",e[e.AUD=9]="AUD",e[e.END_SEQ=10]="END_SEQ",e[e.END_STREAM=11]="END_STREAM",e[e.FILLER_DATA=12]="FILLER_DATA",e[e.SPS_EXT=13]="SPS_EXT",e[e.PREFIX_NALU=14]="PREFIX_NALU",e[e.SUBSET_SPS=15]="SUBSET_SPS",e[e.DPS=16]="DPS",e[e.SLICE_AUX=19]="SLICE_AUX",e[e.SLICE_EXT=20]="SLICE_EXT",e[e.SLICE_LAYER_EXT=21]="SLICE_LAYER_EXT"}(an||(an={})),function(e){e[e.TRAIL_N=0]="TRAIL_N",e[e.TRAIL_R=1]="TRAIL_R",e[e.TSA_N=2]="TSA_N",e[e.TSA_R=3]="TSA_R",e[e.STSA_N=4]="STSA_N",e[e.STSA_R=5]="STSA_R",e[e.RADL_N=6]="RADL_N",e[e.RADL_R=7]="RADL_R",e[e.RASL_N=8]="RASL_N",e[e.RASL_R=9]="RASL_R",e[e.BLA_W_LP=16]="BLA_W_LP",e[e.BLA_W_RADL=17]="BLA_W_RADL",e[e.BLA_N_LP=18]="BLA_N_LP",e[e.IDR_W_RADL=19]="IDR_W_RADL",e[e.IDR_N_LP=20]="IDR_N_LP",e[e.CRA_NUT=21]="CRA_NUT",e[e.VPS_NUT=32]="VPS_NUT",e[e.SPS_NUT=33]="SPS_NUT",e[e.PPS_NUT=34]="PPS_NUT",e[e.AUD_NUT=35]="AUD_NUT",e[e.EOS_NUT=36]="EOS_NUT",e[e.EOB_NUT=37]="EOB_NUT",e[e.FD_NUT=38]="FD_NUT",e[e.PREFIX_SEI_NUT=39]="PREFIX_SEI_NUT",e[e.SUFFIX_SEI_NUT=40]="SUFFIX_SEI_NUT"}(on||(on={}));const hn="ef0161653d8b2b23aad46624b420af1d03ce48950e9fc85718028f91b50f9219",fn="f0a0e09647d891d6d50aa898bce7108090375d0d55e50a2bb21147afee558e44",pn="61d9665eed71b6d424ae9539330a3bdd5cb386d4d781c808219a6e36750493a7",yn="faffc26b68a2fc09096fa20f3351e706398b6f838a7500c8063472c2e476e90d",mn="aad8d31fc56b2802ca500e58c2fb9d0b29ad71bb7cb52cd6530251eade188988";function gn(t){return e(this,void 0,void 0,(function*(){const n=yield function(t){return e(this,void 0,void 0,(function*(){const e=yield crypto.subtle.digest("SHA-256",t),n=new Uint8Array(e);return Array.from(n).map((e=>e.toString(16).padStart(2,"0"))).join("")}))}(t);switch(n){case hn:return"vp8";case fn:case pn:case yn:return"h264";case mn:return"opus";default:return null}}))}const bn=new Map;class vn extends St.EventEmitter{encodeFunction(e,t){throw Error("not implemented for subclass")}decodeFunction(e,t){throw Error("not implemented for subclass")}}class kn extends vn{constructor(e){var t;super(),this.hasPacketTrailer=!1,this.packetTrailerFrameId=0,this.lastErrorTimestamp=new Map,this.errorCounts=new Map,this.ERROR_THROTTLE_MS=1e3,this.MAX_ERRORS_PER_MINUTE=5,this.ERROR_WINDOW_MS=6e4,this.sendCounts=new Map,this.keys=e.keys,this.participantIdentity=e.participantIdentity,this.rtpMap=new Map,this.keyProviderOptions=e.keyProviderOptions,this.sifTrailer=null!==(t=e.sifTrailer)&&void 0!==t?t:Uint8Array.from([])}get logContext(){return{participant:this.participantIdentity,mediaTrackId:this.trackId,fallbackCodec:this.videoCodec}}setParticipant(e,t){l.debug("setting new participant on cryptor",Object.assign(Object.assign({},this.logContext),{newParticipant:e,hadPreviousParticipant:!!this.participantIdentity})),this.participantIdentity&&this.participantIdentity!==e&&(l.warn("cryptor has already a participant set, cleaning up before switching",{oldParticipant:this.participantIdentity,newParticipant:e,trackId:this.trackId}),this.unsetParticipant()),this.participantIdentity=e,this.keys=t}unsetParticipant(){l.debug("unsetting participant",this.logContext),this.currentTransform&&(this.currentTransform=void 0),this.participantIdentity=void 0,this.lastErrorTimestamp=new Map,this.errorCounts=new Map}isEnabled(){return this.participantIdentity?bn.get(this.participantIdentity):void 0}getParticipantIdentity(){return this.participantIdentity}getTrackId(){return this.trackId}setVideoCodec(e){this.videoCodec=e}setRtpMap(e){this.rtpMap=e}setHasPacketTrailer(e){this.hasPacketTrailer=e}setPacketTrailer(e){this.packetTrailer=e,this.packetTrailerFrameId=0}setupTransform(e,t,n,r,i,a,o){if(a&&(l.info("setting codec on cryptor to",{codec:a}),this.videoCodec=a),"encode"===e&&this.setPacketTrailer(o),l.debug("Setting up frame cryptor transform",Object.assign({operation:e,passedTrackId:r,codec:a,isReuse:i,hasCurrentTransform:!!this.currentTransform},this.logContext)),this.trackId=r,i&&this.currentTransform&&t===this.currentTransform.readable&&n===this.currentTransform.writable)return void l.debug("reusing existing transform",Object.assign(Object.assign({},this.logContext),{trackId:r}));const s=Symbol("transform"),c="encode"===e?this.encodeFunction:this.decodeFunction,d=new TransformStream({transform:c.bind(this)});this.currentTransform={readable:t,writable:n,transformer:d,trackId:r,symbol:s},t.pipeThrough(d).pipeTo(n).catch((e=>{e instanceof TypeError&&"Destination stream closed"===e.message?l.debug("destination stream closed"):(l.warn("transform error",Object.assign({error:e},this.logContext)),this.emit(ft.Error,e instanceof pt?e:new pt(e.message,void 0,this.participantIdentity)))})).finally((()=>{var e;(null===(e=this.currentTransform)||void 0===e?void 0:e.symbol)===s&&(l.debug("transform completed",Object.assign(Object.assign({},this.logContext),{trackId:r})),this.currentTransform=void 0)}))}setSifTrailer(e){l.debug("setting SIF trailer",Object.assign(Object.assign({},this.logContext),{trailer:e})),this.sifTrailer=e}shouldEmitError(e){var t,n;const r=Date.now(),i=null!==(t=this.lastErrorTimestamp.get(e))&&void 0!==t?t:0,a=null!==(n=this.errorCounts.get(e))&&void 0!==n?n:0;return r-i>this.ERROR_WINDOW_MS?(this.errorCounts.set(e,0),this.lastErrorTimestamp.set(e,r),!0):!(r-i<this.ERROR_THROTTLE_MS)&&(a>=this.MAX_ERRORS_PER_MINUTE?(a===this.MAX_ERRORS_PER_MINUTE&&(l.warn("Suppressing further decryption errors for ".concat(this.participantIdentity),Object.assign(Object.assign({},this.logContext),{errorKey:e})),this.errorCounts.set(e,a+1)),!1):(this.lastErrorTimestamp.set(e,r),this.errorCounts.set(e,a+1),!0))}emitThrottledError(e){var t;const n="".concat(this.participantIdentity,"-").concat(e.reason,"-decrypt");if(this.shouldEmitError(n)){const r=null!==(t=this.errorCounts.get(n))&&void 0!==t?t:0;r>1&&l.debug("Decryption error (".concat(r," occurrences in window)"),Object.assign(Object.assign({},this.logContext),{reason:dt[e.reason]})),this.emit(ft.Error,e)}}encodeFunction(t,n){return e(this,void 0,void 0,(function*(){var e;if(0===t.data.byteLength)return n.enqueue(t);if(!this.isEnabled())return this.appendPacketTrailer(t),n.enqueue(t);const r=this.keys.getKeySet();if(!r)return void this.emitThrottledError(new pt("key set not found for ".concat(this.participantIdentity," at index ").concat(this.keys.getCurrentKeyIndex()),dt.MissingKey,this.participantIdentity));const{encryptionKey:i}=r,a=this.keys.getCurrentKeyIndex();if(i){const r=this.makeIV(null!==(e=t.getMetadata().synchronizationSource)&&void 0!==e?e:-1,t.timestamp);let s=this.getUnencryptedBytes(t);const c=new Uint8Array(t.data,0,s.unencryptedBytes),d=new Uint8Array(2);d[0]=12,d[1]=a;try{const e=yield crypto.subtle.encrypt({name:m,iv:r,additionalData:new Uint8Array(t.data,0,c.byteLength)},i,new Uint8Array(t.data,s.unencryptedBytes));let a=new Uint8Array(e.byteLength+r.byteLength+d.byteLength);a.set(new Uint8Array(e)),a.set(new Uint8Array(r),e.byteLength),a.set(d,e.byteLength+r.byteLength),s.requiresNALUProcessing&&(a=function(e){const t=[];for(var n=0,r=0;r<e.length;++r){var i=e[r];i<=3&&n>=2&&(t.push(3),n=0),t.push(i),0==i?++n:n=0}return new Uint8Array(t)}(a));var o=new Uint8Array(c.byteLength+a.byteLength);return o.set(c),o.set(a,c.byteLength),t.data=o.buffer,this.appendPacketTrailer(t),n.enqueue(t)}catch(e){l.error(e)}}else l.debug("failed to encrypt, emitting error",this.logContext),this.emitThrottledError(new pt("encryption key missing for encoding",dt.MissingKey,this.participantIdentity))}))}appendPacketTrailer(e){var t;Gt(this.packetTrailer)&&yt(e)&&((null===(t=this.packetTrailer)||void 0===t?void 0:t.frameId)&&(this.packetTrailerFrameId=4294967295===this.packetTrailerFrameId?1:this.packetTrailerFrameId+1),function(e,t,n){if(!Gt(t)||0===e.data.byteLength)return!1;const r=(null==t?void 0:t.timestamp)?BigInt(Date.now())*BigInt(1e3):BigInt(0),i=(null==t?void 0:t.frameId)?n:0,a=new Uint8Array(e.data),o=$t(a,r,i);o.byteLength!==a.byteLength&&(e.data=o.buffer.slice(o.byteOffset,o.byteOffset+o.byteLength))}(e,this.packetTrailer,this.packetTrailerFrameId))}decodeFunction(t,n){return e(this,void 0,void 0,(function*(){if(this.hasPacketTrailer&&yt(t))try{const e=function(e,t){if(0===e.data.byteLength)return{};const n=Zt(e.data);if(!n.metadata)return{};const r=n.data.buffer.slice(n.data.byteOffset,n.data.byteOffset+n.data.byteLength),i=function(e){try{const t=e.getMetadata();if("number"==typeof t.rtpTimestamp)return t.rtpTimestamp;if("number"==typeof t.timestamp)return t.timestamp}catch(e){}if("number"==typeof e.timestamp)return e.timestamp}(e);return void 0!==i&&t?{data:r,payload:{trackId:t,rtpTimestamp:i,ssrc:nn(e),metadata:n.metadata}}:{data:r}}(t,this.trackId);if(e.data&&(t.data=e.data),e.payload&&this.participantIdentity){const t={kind:"packetTrailerMetadata",data:e.payload};postMessage(t)}}catch(e){}if(!this.isEnabled()||0===t.data.byteLength)return n.enqueue(t);if(function(e,t){if(0===t.byteLength)return!1;const n=new Uint8Array(e.slice(e.byteLength-t.byteLength));return t.every(((e,t)=>e===n[t]))}(t.data,this.sifTrailer))return t.data=t.data.slice(0,t.data.byteLength-this.sifTrailer.byteLength),(yield gn(t.data))?(l.debug("enqueue SIF",this.logContext),n.enqueue(t)):void l.warn("Unexpected SIF frame payload, dropping frame",this.logContext);const e=new Uint8Array(t.data)[t.data.byteLength-1];if(!this.keys.hasInvalidKeyAtIndex(e))if(this.keys.getKeySet(e))try{const r=yield this.decryptFrame(t,e);if(this.keys.decryptionSuccess(e),r)return n.enqueue(r)}catch(t){t instanceof pt&&t.reason===dt.InvalidKey?this.keys.hasValidKey&&(this.emitThrottledError(t),this.keys.decryptionFailure(e)):l.warn("decoding frame failed",{error:t})}else l.warn("skipping decryption due to missing key at index ".concat(e)),this.emitThrottledError(new pt("missing key at index ".concat(e," for participant ").concat(this.participantIdentity),dt.MissingKey,this.participantIdentity)),this.keys.decryptionFailure(e)}))}decryptFrame(t,n){return e(this,arguments,void 0,(function(e,t){var n=this;let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:void 0,i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{ratchetCount:0};return function*(){var a;const o=n.keys.getKeySet(t);if(!i.encryptionKey&&!o)throw new TypeError("no encryption key found for decryption of ".concat(n.participantIdentity));let s=n.getUnencryptedBytes(e);try{const t=new Uint8Array(e.data,0,s.unencryptedBytes);var c=new Uint8Array(e.data,t.length,e.data.byteLength-t.length);if(s.requiresNALUProcessing&&function(e){for(var t=0;t<e.length-3;t++)if(0==e[t]&&0==e[t+1]&&3==e[t+2])return!0;return!1}(c)){c=function(e){const t=[];for(var n=e.length,r=0;r<e.length;)n-r>=3&&!e[r]&&!e[r+1]&&3==e[r+2]?(t.push(e[r++]),t.push(e[r++]),r++):t.push(e[r++]);return new Uint8Array(t)}(c);const n=new Uint8Array(t.byteLength+c.byteLength);n.set(t),n.set(c,t.byteLength),e.data=n.buffer}const n=new Uint8Array(e.data,e.data.byteLength-2,2),r=n[0],d=new Uint8Array(e.data,e.data.byteLength-r-n.byteLength,r),u=t.byteLength,l=e.data.byteLength-(t.byteLength+r+n.byteLength),h=yield crypto.subtle.decrypt({name:m,iv:d,additionalData:new Uint8Array(e.data,0,t.byteLength)},null!==(a=i.encryptionKey)&&void 0!==a?a:o.encryptionKey,new Uint8Array(e.data,u,l)),f=new ArrayBuffer(t.byteLength+h.byteLength),p=new Uint8Array(f);return p.set(new Uint8Array(e.data,0,t.byteLength)),p.set(new Uint8Array(h),t.byteLength),e.data=f,e}catch(a){if(n.keyProviderOptions.ratchetWindowSize>0){if(i.ratchetCount<n.keyProviderOptions.ratchetWindowSize){let a,s;l.debug("ratcheting key attempt ".concat(i.ratchetCount," of ").concat(n.keyProviderOptions.ratchetWindowSize,", for kind ").concat(e instanceof RTCEncodedAudioFrame?"audio":"video")),(null!=r?r:o)===n.keys.getKeySet(t)&&(s=yield n.keys.ratchetKey(t,!1),a=yield gt(s.cryptoKey,n.keyProviderOptions));const c=yield n.decryptFrame(e,t,r||o,{ratchetCount:i.ratchetCount+1,encryptionKey:null==a?void 0:a.encryptionKey});return c&&a&&(null!=r?r:o)===n.keys.getKeySet(t)&&(n.keys.setKeySet(a,t,s),n.keys.setCurrentKeyIndex(t)),c}throw l.warn("maximum ratchet attempts exceeded"),new pt("valid key missing for participant ".concat(n.participantIdentity),dt.InvalidKey,n.participantIdentity)}throw new pt("Decryption failed: ".concat(a.message),dt.InvalidKey,n.participantIdentity)}}()}))}makeIV(e,t){var n;const r=new ArrayBuffer(12),i=new DataView(r);this.sendCounts.has(e)||this.sendCounts.set(e,Math.floor(65535*Math.random()));const a=null!==(n=this.sendCounts.get(e))&&void 0!==n?n:0;return i.setUint32(0,e),i.setUint32(4,t),i.setUint32(8,t-a%65535),this.sendCounts.set(e,a+1),r}getUnencryptedBytes(e){var t;if(!yt(e))return{unencryptedBytes:g.audio,requiresNALUProcessing:!1};const n=null!==(t=this.getVideoCodec(e))&&void 0!==t?t:this.videoCodec;if(n!==this.detectedCodec&&(l.debug("detected different codec",Object.assign({detectedCodec:n,oldCodec:this.detectedCodec},this.logContext)),this.detectedCodec=n),"av1"===n)throw new Error("".concat(n," is not yet supported for end to end encryption"));if("vp8"===n)return{unencryptedBytes:g[e.type],requiresNALUProcessing:!1};if("vp9"===n)return{unencryptedBytes:0,requiresNALUProcessing:!1};try{const t="h264"===n||"h265"===n?n:void 0,r=ln(new Uint8Array(e.data),t);if(r.requiresNALUProcessing)return{unencryptedBytes:r.unencryptedBytes,requiresNALUProcessing:!0}}catch(e){l.debug("NALU processing failed, falling back to VP8 handling",Object.assign({error:e},this.logContext))}return{unencryptedBytes:g[e.type],requiresNALUProcessing:!1}}getVideoCodec(e){if(0===this.rtpMap.size)return;const t=e.getMetadata().payloadType;return t?this.rtpMap.get(t):void 0}}class wn extends St.EventEmitter{get hasValidKey(){return!this.hasInvalidKeyAtIndex(this.currentKeyIndex)}constructor(e,t){if(super(),this.currentKeyIndex=0,t.keyringSize<1||t.keyringSize>256)throw new TypeError("Keyring size needs to be between 1 and 256");this.cryptoKeyRing=new Array(t.keyringSize).fill(void 0),this.decryptionFailureCounts=new Array(t.keyringSize).fill(0),this.keyProviderOptions=t,this.ratchetPromiseMap=new Map,this.participantIdentity=e}hasInvalidKeyAtIndex(e){return this.keyProviderOptions.failureTolerance>=0&&this.decryptionFailureCounts[e]>this.keyProviderOptions.failureTolerance}decryptionFailure(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.currentKeyIndex;this.keyProviderOptions.failureTolerance<0||(this.decryptionFailureCounts[e]+=1,this.decryptionFailureCounts[e]>this.keyProviderOptions.failureTolerance&&l.warn("key for ".concat(this.participantIdentity," at index ").concat(e," is being marked as invalid")))}decryptionSuccess(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.currentKeyIndex;this.resetKeyStatus(e)}resetKeyStatus(e){void 0===e?this.decryptionFailureCounts.fill(0):this.decryptionFailureCounts[e]=0}ratchetKey(t){let n=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];const r=null!=t?t:this.getCurrentKeyIndex(),i=this.ratchetPromiseMap.get(r);if(void 0!==i)return i;const a=new Promise(((t,i)=>e(this,void 0,void 0,(function*(){try{const i=this.getKeySet(r);if(!i)throw new TypeError("Cannot ratchet key without a valid keyset of participant ".concat(this.participantIdentity));const a=i.material,o=yield function(t,n){return e(this,void 0,void 0,(function*(){const e=mt(t.algorithm.name,n);return crypto.subtle.deriveBits(e,t,256)}))}(a,this.keyProviderOptions.ratchetSalt),s=yield function(t){return e(this,arguments,void 0,(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{name:m},n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"encrypt";return function*(){return crypto.subtle.importKey("raw",e,t,!1,"derive"===n?["deriveBits","deriveKey"]:["encrypt","decrypt"])}()}))}(o,a.algorithm.name,"derive"),c={chainKey:o,cryptoKey:s};n&&(yield this.setKeyFromMaterial(s,r,c)),t(c)}catch(e){i(e)}finally{this.ratchetPromiseMap.delete(r)}}))));return this.ratchetPromiseMap.set(r,a),a}setKey(t){return e(this,arguments,void 0,(function(e){var t=this;let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];return function*(){yield t.setKeyFromMaterial(e,n,null,r),r&&t.resetKeyStatus(n)}()}))}setKeyFromMaterial(t,n){return e(this,arguments,void 0,(function(e,t){var n=this;let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,i=!(arguments.length>3&&void 0!==arguments[3])||arguments[3];return function*(){const a=yield gt(e,n.keyProviderOptions),o=t>=0?t%n.cryptoKeyRing.length:n.currentKeyIndex;l.debug("setting new key with index ".concat(t),{usage:e.usages,algorithm:e.algorithm,ratchetSalt:n.keyProviderOptions.ratchetSalt}),n.setKeySet(a,o,r),o>=0&&i&&(n.currentKeyIndex=o)}()}))}setKeySet(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null;this.cryptoKeyRing[t%this.cryptoKeyRing.length]=e,n&&this.emit(lt.KeyRatcheted,n,this.participantIdentity,t)}setCurrentKeyIndex(t){return e(this,void 0,void 0,(function*(){this.currentKeyIndex=t%this.cryptoKeyRing.length,this.resetKeyStatus(t)}))}getCurrentKeyIndex(){return this.currentKeyIndex}getKeySet(e){return this.cryptoKeyRing[null!=e?e:this.currentKeyIndex]}}const Tn=[],Sn=new Map;let In,En,Nn=new class{constructor(){this.pendingTasks=new Map,this.taskMutex=new y,this.nextTaskIndex=0}run(t){return e(this,void 0,void 0,(function*(){const e={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:h.WAITING};this.pendingTasks.set(e.id,e);const n=yield this.taskMutex.lock();try{return e.executedAt=Date.now(),e.status=h.RUNNING,yield t()}finally{e.status=h.COMPLETED,this.pendingTasks.delete(e.id),n()}}))}flush(){return e(this,void 0,void 0,(function*(){return this.run((()=>e(this,void 0,void 0,(function*(){}))))}))}snapshot(){return Array.from(this.pendingTasks.values())}},An=!1,Cn=b,Ln=new Map;function Rn(e,t){let n=Tn.filter((e=>e.getTrackId()===t));if(n.length>1){const r=n.map((e=>({participant:e.getParticipantIdentity()}))).join(",");l.error("Found multiple cryptors for the same trackID ".concat(t,". target participant: ").concat(e," "),{participants:r})}let r=n[0];if(r)e!==r.getParticipantIdentity()&&r.setParticipant(e,Un(e));else{if(l.info("creating new cryptor for",{participantIdentity:e,trackId:t}),!Cn)throw Error("Missing keyProvider options");r=new kn({participantIdentity:e,keys:Un(e),keyProviderOptions:Cn,sifTrailer:En}),r.setRtpMap(Ln),function(e){e.on(ft.Error,(e=>{const t={kind:"error",data:{error:new Error("".concat(dt[e.reason],": ").concat(e.message)),participantIdentity:e.participantIdentity}};postMessage(t)}))}(r),Tn.push(r)}return r}function Un(e){if(An)return On();let t=Sn.get(e);return t||(t=new wn(e,Cn),t.on(lt.KeyRatcheted,Pn),Sn.set(e,t)),t}function On(){return In||(l.debug("creating new shared key handler"),In=new wn("shared-key",Cn)),In}function Pn(e,t,n){postMessage({kind:"ratchetKey",data:{participantIdentity:t,keyIndex:n,ratchetResult:e}})}l.setDefaultLevel("info"),onmessage=t=>{Nn.run((()=>e(void 0,void 0,void 0,(function*(){const{kind:n,data:r}=t.data;switch(n){case"init":l.setLevel(r.loglevel),l.info("worker initialized"),Cn=r.keyProviderOptions,An=!!r.keyProviderOptions.sharedKey;postMessage({kind:"initAck",data:{enabled:false}});break;case"enable":a=r.enabled,o=r.participantIdentity,l.debug("setting encryption enabled for all tracks of ".concat(o),{enable:a}),bn.set(o,a),l.info("updated e2ee enabled status for ".concat(r.participantIdentity," to ").concat(r.enabled)),postMessage(t.data);break;case"decode":let s=Rn(r.participantIdentity,r.trackId);s.setHasPacketTrailer(r.hasPacketTrailer),s.setupTransform(n,r.readableStream,r.writableStream,r.trackId,r.isReuse,r.codec);break;case"encode":let c=Rn(r.participantIdentity,r.trackId);c.setHasPacketTrailer(r.hasPacketTrailer),c.setupTransform(n,r.readableStream,r.writableStream,r.trackId,r.isReuse,r.codec,r.packetTrailer);break;case"encryptDataRequest":const{payload:d,iv:u,keyIndex:h}=yield bt.encrypt(r.payload,Un(r.participantIdentity));console.log("encrypted payload",{original:r.payload,encrypted:d,iv:u}),postMessage({kind:"encryptDataResponse",data:{payload:d,iv:u,keyIndex:h,uuid:r.uuid}});break;case"decryptDataRequest":try{const{payload:e}=yield bt.decrypt(r.payload,r.iv,Un(r.participantIdentity),r.keyIndex);postMessage({kind:"decryptDataResponse",data:{payload:e,uuid:r.uuid}})}catch(e){l.error("DataCryptor decryption failed",{error:e,participantIdentity:r.participantIdentity,uuid:r.uuid}),postMessage({kind:"error",data:{error:e instanceof Error?e:new Error(String(e)),uuid:r.uuid}})}break;case"setKey":An?yield function(t,n,r){return e(this,void 0,void 0,(function*(){l.info("set shared key",{index:n}),yield On().setKey(t,n,r)}))}(r.key,r.keyIndex,r.updateCurrentKeyIndex):r.participantIdentity?(l.info("set participant sender key ".concat(r.participantIdentity," index ").concat(r.keyIndex)),yield Un(r.participantIdentity).setKey(r.key,r.keyIndex,r.updateCurrentKeyIndex)):l.error("no participant Id was provided and shared key usage is disabled");break;case"removeTransform":!function(e,t){const n=Tn.filter((n=>n.getParticipantIdentity()===t&&n.getTrackId()===e));n.length>1&&l.error("Found multiple cryptors for the same participant and trackID combination",{trackId:e,participantIdentity:t});const r=n[0];r?r.unsetParticipant():l.warn("Could not unset participant on cryptor",{trackId:e,participantIdentity:t})}(r.trackId,r.participantIdentity);break;case"updateCodec":const f=Rn(r.participantIdentity,r.trackId);f.setVideoCodec(r.codec),f.setHasPacketTrailer(r.hasPacketTrailer),l.info("updated codec",{participantIdentity:r.participantIdentity,trackId:r.trackId,codec:r.codec,hasPacketTrailer:r.hasPacketTrailer});break;case"setRTPMap":Ln=r.map,Tn.forEach((e=>{e.getParticipantIdentity()===r.participantIdentity&&e.setRtpMap(r.map)}));break;case"ratchetRequest":!function(t){e(this,void 0,void 0,(function*(){if(An){const e=On();yield e.ratchetKey(t.keyIndex),e.resetKeyStatus()}else if(t.participantIdentity){const e=Un(t.participantIdentity);yield e.ratchetKey(t.keyIndex),e.resetKeyStatus()}else l.error("no participant Id was provided for ratchet request and shared key usage is disabled")}))}(r);break;case"setSifTrailer":i=r.trailer,En=i,Tn.forEach((e=>{e.setSifTrailer(i)}))}var i,a,o}))))},self.RTCTransformEvent&&(self.onrtctransform=t=>{const n=t.transformer,r=n.options,{kind:i,participantIdentity:a,trackId:o,codec:s,hasPacketTrailer:c}=r;Nn.run((()=>e(void 0,void 0,void 0,(function*(){const e=Rn(a,o);e.setHasPacketTrailer(c),l.debug("onrtctransform setup",{participantIdentity:a,trackId:o,codec:s}),e.setupTransform(i,n.readable,n.writable,o,!1,s,"encode"===i?r.packetTrailer:void 0)}))))})}));
2
2
  //# sourceMappingURL=livekit-client.e2ee.worker.js.map