@whereby.com/browser-sdk 3.12.1 → 3.12.3
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.
- package/dist/cdn/v3-react.js +2 -2
- package/dist/react/index.cjs +1 -1
- package/dist/react/index.esm.js +1 -1
- package/package.json +2 -2
package/dist/cdn/v3-react.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
this.whereby=this.whereby||{},this.whereby.react=function(e,t,r){"use strict";function i(e){var t=Object.create(null);return e&&Object.keys(e).forEach((function(r){if("default"!==r){var i=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,i.get?i:{enumerable:!0,get:function(){return e[r]}})}})),t.default=e,Object.freeze(t)}function n(e,t){return t.forEach((function(t){t&&"string"!=typeof t&&!Array.isArray(t)&&Object.keys(t).forEach((function(r){if("default"!==r&&!(r in e)){var i=Object.getOwnPropertyDescriptor(t,r);Object.defineProperty(e,r,i.get?i:{enumerable:!0,get:function(){return t[r]}})}}))})),Object.freeze(e)}var s=i(t),o=i(r),a="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function c(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var d,l={exports:{}},u={};l.exports=(d||(d=1,function(){"undefined"!=typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error);var e=t,r="function"==typeof Object.is?Object.is:function(e,t){return e===t&&(0!==e||1/e==1/t)||e!=e&&t!=t},i=e.useSyncExternalStore,n=e.useRef,s=e.useEffect,o=e.useMemo,a=e.useDebugValue;u.useSyncExternalStoreWithSelector=function(e,t,c,d,l){var u,p=n(null);null===p.current?(u={hasValue:!1,value:null},p.current=u):u=p.current;var h=o((function(){var e,i,n=!1,s=function(t){if(!n){n=!0,e=t;var s=d(t);if(void 0!==l&&u.hasValue){var o=u.value;if(l(o,s))return i=o,o}return i=s,s}var a=i;if(r(e,t))return a;var c=d(t);return void 0!==l&&l(a,c)?a:(e=t,i=c,c)},o=void 0===c?null:c;return[function(){return s(t())},null===o?void 0:function(){return s(o())}]}),[t,c,d,l]),f=h[0],m=h[1],g=i(e,f,m);return s((function(){u.hasValue=!0,u.value=g}),[g]),a(g),g},"undefined"!=typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error)}()),u);var p=l.exports,h="default"in s?s.default:s,f=Symbol.for("react-redux-context"),m="undefined"!=typeof globalThis?globalThis:{};function g(){if(!h.createContext)return{};const e=m[f]??(m[f]=new Map);let t=e.get(h.createContext);return t||(t=h.createContext(null),t.displayName="ReactRedux",e.set(h.createContext,t)),t}var v=g();function b(e=v){return function(){const t=h.useContext(e);if(!t)throw new Error("could not find react-redux context value; please ensure the component is wrapped in a <Provider>");return t}}var y=b(),w=()=>{throw new Error("uSES not initialized!")},_=(e,t)=>e===t;var S={notify(){},get:()=>[]};var C=!("undefined"==typeof window||void 0===window.document||void 0===window.document.createElement),R="undefined"!=typeof navigator&&"ReactNative"===navigator.product,k=C||R?h.useLayoutEffect:h.useEffect;var T=function({store:e,context:t,children:r,serverState:i,stabilityCheck:n="once",identityFunctionCheck:s="once"}){const o=h.useMemo((()=>{const t=function(e,t){let r,i=S,n=0,s=!1;function o(){d.onStateChange&&d.onStateChange()}function a(){n++,r||(r=t?t.addNestedSub(o):e.subscribe(o),i=function(){let e=null,t=null;return{clear(){e=null,t=null},notify(){var t;t=()=>{let t=e;for(;t;)t.callback(),t=t.next},t()},get(){const t=[];let r=e;for(;r;)t.push(r),r=r.next;return t},subscribe(r){let i=!0;const n=t={callback:r,next:null,prev:t};return n.prev?n.prev.next=n:e=n,function(){i&&null!==e&&(i=!1,n.next?n.next.prev=n.prev:t=n.prev,n.prev?n.prev.next=n.next:e=n.next)}}}}())}function c(){n--,r&&0===n&&(r(),r=void 0,i.clear(),i=S)}const d={addNestedSub:function(e){a();const t=i.subscribe(e);let r=!1;return()=>{r||(r=!0,t(),c())}},notifyNestedSubs:function(){i.notify()},handleChangeWrapper:o,isSubscribed:function(){return s},trySubscribe:function(){s||(s=!0,a())},tryUnsubscribe:function(){s&&(s=!1,c())},getListeners:()=>i};return d}(e);return{store:e,subscription:t,getServerState:i?()=>i:void 0,stabilityCheck:n,identityFunctionCheck:s}}),[e,i,n,s]),a=h.useMemo((()=>e.getState()),[e]);k((()=>{const{subscription:t}=o;return t.onStateChange=t.notifyNestedSubs,t.trySubscribe(),a!==e.getState()&&t.notifyNestedSubs(),()=>{t.tryUnsubscribe(),t.onStateChange=void 0}}),[o,a]);const c=t||v;return h.createElement(c.Provider,{value:o},r)};function P(e=v){const t=e===v?y:b(e),r=()=>{const{store:e}=t();return e};return Object.assign(r,{withTypes:()=>r}),r}var E,O=P();E=p.useSyncExternalStoreWithSelector,w=E;var D=(()=>"function"==typeof Symbol&&Symbol.observable||"@@observable")(),I=()=>Math.random().toString(36).substring(7).split("").join("."),x={INIT:`@@redux/INIT${I()}`,REPLACE:`@@redux/REPLACE${I()}`,PROBE_UNKNOWN_ACTION:()=>`@@redux/PROBE_UNKNOWN_ACTION${I()}`};function M(e){if("object"!=typeof e||null===e)return!1;let t=e;for(;null!==Object.getPrototypeOf(t);)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t||null===Object.getPrototypeOf(e)}function L(e){if(void 0===e)return"undefined";if(null===e)return"null";const t=typeof e;switch(t){case"boolean":case"string":case"number":case"symbol":case"function":return t}if(Array.isArray(e))return"array";if(function(e){return e instanceof Date||"function"==typeof e.toDateString&&"function"==typeof e.getDate&&"function"==typeof e.setDate}(e))return"date";if(function(e){return e instanceof Error||"string"==typeof e.message&&e.constructor&&"number"==typeof e.constructor.stackTraceLimit}(e))return"error";const r=function(e){return"function"==typeof e.constructor?e.constructor.name:null}(e);switch(r){case"Symbol":case"Promise":case"WeakMap":case"WeakSet":case"Map":case"Set":return r}return Object.prototype.toString.call(e).slice(8,-1).toLowerCase().replace(/\s/g,"")}function j(e){let t=typeof e;return t=L(e),t}function A(e,t,r){if("function"!=typeof e)throw new Error(`Expected the root reducer to be a function. Instead, received: '${j(e)}'`);if("function"==typeof t&&"function"==typeof r||"function"==typeof r&&"function"==typeof arguments[3])throw new Error("It looks like you are passing several store enhancers to createStore(). This is not supported. Instead, compose them together to a single function. See https://redux.js.org/tutorials/fundamentals/part-4-store#creating-a-store-with-enhancers for an example.");if("function"==typeof t&&void 0===r&&(r=t,t=void 0),void 0!==r){if("function"!=typeof r)throw new Error(`Expected the enhancer to be a function. Instead, received: '${j(r)}'`);return r(A)(e,t)}let i=e,n=t,s=new Map,o=s,a=0,c=!1;function d(){o===s&&(o=new Map,s.forEach(((e,t)=>{o.set(t,e)})))}function l(){if(c)throw new Error("You may not call store.getState() while the reducer is executing. The reducer has already received the state as an argument. Pass it down from the top reducer instead of reading it from the store.");return n}function u(e){if("function"!=typeof e)throw new Error(`Expected the listener to be a function. Instead, received: '${j(e)}'`);if(c)throw new Error("You may not call store.subscribe() while the reducer is executing. If you would like to be notified after the store has been updated, subscribe from a component and invoke store.getState() in the callback to access the latest state. See https://redux.js.org/api/store#subscribelistener for more details.");let t=!0;d();const r=a++;return o.set(r,e),function(){if(t){if(c)throw new Error("You may not unsubscribe from a store listener while the reducer is executing. See https://redux.js.org/api/store#subscribelistener for more details.");t=!1,d(),o.delete(r),s=null}}}function p(e){if(!M(e))throw new Error(`Actions must be plain objects. Instead, the actual type was: '${j(e)}'. You may need to add middleware to your store setup to handle dispatching other values, such as 'redux-thunk' to handle dispatching functions. See https://redux.js.org/tutorials/fundamentals/part-4-store#middleware and https://redux.js.org/tutorials/fundamentals/part-6-async-logic#using-the-redux-thunk-middleware for examples.`);if(void 0===e.type)throw new Error('Actions may not have an undefined "type" property. You may have misspelled an action type string constant.');if("string"!=typeof e.type)throw new Error(`Action "type" property must be a string. Instead, the actual type was: '${j(e.type)}'. Value was: '${e.type}' (stringified)`);if(c)throw new Error("Reducers may not dispatch actions.");try{c=!0,n=i(n,e)}finally{c=!1}return(s=o).forEach((e=>{e()})),e}p({type:x.INIT});return{dispatch:p,subscribe:u,getState:l,replaceReducer:function(e){if("function"!=typeof e)throw new Error(`Expected the nextReducer to be a function. Instead, received: '${j(e)}`);i=e,p({type:x.REPLACE})},[D]:function(){const e=u;return{subscribe(t){if("object"!=typeof t||null===t)throw new Error(`Expected the observer to be an object. Instead, received: '${j(t)}'`);function r(){const e=t;e.next&&e.next(l())}r();return{unsubscribe:e(r)}},[D](){return this}}}}}function N(e){"undefined"!=typeof console&&"function"==typeof console.error&&console.error(e);try{throw new Error(e)}catch(e){}}function B(e){const t=Object.keys(e),r={};for(let i=0;i<t.length;i++){const n=t[i];void 0===e[n]&&N(`No reducer provided for key "${n}"`),"function"==typeof e[n]&&(r[n]=e[n])}const i=Object.keys(r);let n,s;n={};try{!function(e){Object.keys(e).forEach((t=>{const r=e[t];if(void 0===r(void 0,{type:x.INIT}))throw new Error(`The slice reducer for key "${t}" returned undefined during initialization. If the state passed to the reducer is undefined, you must explicitly return the initial state. The initial state may not be undefined. If you don't want to set a value for this reducer, you can use null instead of undefined.`);if(void 0===r(void 0,{type:x.PROBE_UNKNOWN_ACTION()}))throw new Error(`The slice reducer for key "${t}" returned undefined when probed with a random type. Don't try to handle '${x.INIT}' or other actions in "redux/*" namespace. They are considered private. Instead, you must return the current state for any unknown actions, unless it is undefined, in which case you must return the initial state, regardless of the action type. The initial state may not be undefined, but can be null.`)}))}(r)}catch(e){s=e}return function(e={},t){if(s)throw s;{const i=function(e,t,r,i){const n=Object.keys(t),s=r&&r.type===x.INIT?"preloadedState argument passed to createStore":"previous state received by the reducer";if(0===n.length)return"Store does not have a valid reducer. Make sure the argument passed to combineReducers is an object whose values are reducers.";if(!M(e))return`The ${s} has unexpected type of "${j(e)}". Expected argument to be an object with the following keys: "${n.join('", "')}"`;const o=Object.keys(e).filter((e=>!t.hasOwnProperty(e)&&!i[e]));return o.forEach((e=>{i[e]=!0})),r&&r.type===x.REPLACE?void 0:o.length>0?`Unexpected ${o.length>1?"keys":"key"} "${o.join('", "')}" found in ${s}. Expected to find one of the known reducer keys instead: "${n.join('", "')}". Unexpected keys will be ignored.`:void 0}(e,r,t,n);i&&N(i)}let o=!1;const a={};for(let n=0;n<i.length;n++){const s=i[n],c=r[s],d=e[s],l=c(d,t);if(void 0===l){const e=t&&t.type;throw new Error(`When called with an action of type ${e?`"${String(e)}"`:"(unknown type)"}, the slice reducer for key "${s}" returned undefined. To ignore an action, you must explicitly return the previous state. If you want this reducer to hold no value, you can return null instead of undefined.`)}a[s]=l,o=o||l!==d}return o=o||i.length!==Object.keys(e).length,o?a:e}}function F(...e){return 0===e.length?e=>e:1===e.length?e[0]:e.reduce(((e,t)=>(...r)=>e(t(...r))))}function z(e){return M(e)&&"type"in e&&"string"==typeof e.type}var V=Symbol.for("immer-nothing"),U=Symbol.for("immer-draftable"),$=Symbol.for("immer-state"),G=[function(e){return`The plugin for '${e}' has not been loaded into Immer. To enable the plugin, import and call \`enable${e}()\` when initializing your application.`},function(e){return`produce can only be called on things that are draftable: plain objects, arrays, Map, Set or classes that are marked with '[immerable]: true'. Got '${e}'`},"This object has been frozen and should not be mutated",function(e){return"Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? "+e},"An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.","Immer forbids circular references","The first or second argument to `produce` must be a function","The third argument to `produce` must be a function or undefined","First argument to `createDraft` must be a plain object, an array, or an immerable object","First argument to `finishDraft` must be a draft returned by `createDraft`",function(e){return`'current' expects a draft, got: ${e}`},"Object.defineProperty() cannot be used on an Immer draft","Object.setPrototypeOf() cannot be used on an Immer draft","Immer only supports deleting array indices","Immer only supports setting array indices and the 'length' property",function(e){return`'original' expects a draft, got: ${e}`}];function q(e,...t){{const r=G[e],i="function"==typeof r?r.apply(null,t):r;throw new Error(`[Immer] ${i}`)}}var H=Object.getPrototypeOf;function W(e){return!!e&&!!e[$]}function K(e){return!!e&&(X(e)||Array.isArray(e)||!!e[U]||!!e.constructor?.[U]||te(e)||re(e))}var J=Object.prototype.constructor.toString();function X(e){if(!e||"object"!=typeof e)return!1;const t=H(e);if(null===t)return!0;const r=Object.hasOwnProperty.call(t,"constructor")&&t.constructor;return r===Object||"function"==typeof r&&Function.toString.call(r)===J}function Q(e,t){0===Z(e)?Object.entries(e).forEach((([r,i])=>{t(r,i,e)})):e.forEach(((r,i)=>t(i,r,e)))}function Z(e){const t=e[$];return t?t.type_:Array.isArray(e)?1:te(e)?2:re(e)?3:0}function Y(e,t){return 2===Z(e)?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function ee(e,t,r){const i=Z(e);2===i?e.set(t,r):3===i?e.add(r):e[t]=r}function te(e){return e instanceof Map}function re(e){return e instanceof Set}function ie(e){return e.copy_||e.base_}function ne(e,t){if(te(e))return new Map(e);if(re(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);if(!t&&X(e)){if(!H(e)){const t=Object.create(null);return Object.assign(t,e)}return{...e}}const r=Object.getOwnPropertyDescriptors(e);delete r[$];let i=Reflect.ownKeys(r);for(let t=0;t<i.length;t++){const n=i[t],s=r[n];!1===s.writable&&(s.writable=!0,s.configurable=!0),(s.get||s.set)&&(r[n]={configurable:!0,writable:!0,enumerable:s.enumerable,value:e[n]})}return Object.create(H(e),r)}function se(e,t=!1){return ae(e)||W(e)||!K(e)||(Z(e)>1&&(e.set=e.add=e.clear=e.delete=oe),Object.freeze(e),t&&Q(e,((e,t)=>se(t,!0)))),e}function oe(){q(2)}function ae(e){return Object.isFrozen(e)}var ce,de={};function le(e){const t=de[e];return t||q(0,e),t}function ue(){return ce}function pe(e,t){t&&(le("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function he(e){fe(e),e.drafts_.forEach(ge),e.drafts_=null}function fe(e){e===ce&&(ce=e.parent_)}function me(e){return ce={drafts_:[],parent_:ce,immer_:e,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function ge(e){const t=e[$];0===t.type_||1===t.type_?t.revoke_():t.revoked_=!0}function ve(e,t){t.unfinalizedDrafts_=t.drafts_.length;const r=t.drafts_[0];return void 0!==e&&e!==r?(r[$].modified_&&(he(t),q(4)),K(e)&&(e=be(t,e),t.parent_||we(t,e)),t.patches_&&le("Patches").generateReplacementPatches_(r[$].base_,e,t.patches_,t.inversePatches_)):e=be(t,r,[]),he(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==V?e:void 0}function be(e,t,r){if(ae(t))return t;const i=t[$];if(!i)return Q(t,((n,s)=>ye(e,i,t,n,s,r))),t;if(i.scope_!==e)return t;if(!i.modified_)return we(e,i.base_,!0),i.base_;if(!i.finalized_){i.finalized_=!0,i.scope_.unfinalizedDrafts_--;const t=i.copy_;let n=t,s=!1;3===i.type_&&(n=new Set(t),t.clear(),s=!0),Q(n,((n,o)=>ye(e,i,t,n,o,r,s))),we(e,t,!1),r&&e.patches_&&le("Patches").generatePatches_(i,r,e.patches_,e.inversePatches_)}return i.copy_}function ye(e,t,r,i,n,s,o){if(n===r&&q(5),W(n)){const o=be(e,n,s&&t&&3!==t.type_&&!Y(t.assigned_,i)?s.concat(i):void 0);if(ee(r,i,o),!W(o))return;e.canAutoFreeze_=!1}else o&&r.add(n);if(K(n)&&!ae(n)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;be(e,n),t&&t.scope_.parent_||we(e,n)}}function we(e,t,r=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&se(t,r)}var _e={get(e,t){if(t===$)return e;const r=ie(e);if(!Y(r,t))return function(e,t,r){const i=Re(t,r);return i?"value"in i?i.value:i.get?.call(e.draft_):void 0}(e,r,t);const i=r[t];return e.finalized_||!K(i)?i:i===Ce(e.base_,t)?(Te(e),e.copy_[t]=Pe(i,e)):i},has:(e,t)=>t in ie(e),ownKeys:e=>Reflect.ownKeys(ie(e)),set(e,t,r){const i=Re(ie(e),t);if(i?.set)return i.set.call(e.draft_,r),!0;if(!e.modified_){const i=Ce(ie(e),t),o=i?.[$];if(o&&o.base_===r)return e.copy_[t]=r,e.assigned_[t]=!1,!0;if(((n=r)===(s=i)?0!==n||1/n==1/s:n!=n&&s!=s)&&(void 0!==r||Y(e.base_,t)))return!0;Te(e),ke(e)}var n,s;return e.copy_[t]===r&&(void 0!==r||t in e.copy_)||Number.isNaN(r)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=r,e.assigned_[t]=!0),!0},deleteProperty:(e,t)=>(void 0!==Ce(e.base_,t)||t in e.base_?(e.assigned_[t]=!1,Te(e),ke(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0),getOwnPropertyDescriptor(e,t){const r=ie(e),i=Reflect.getOwnPropertyDescriptor(r,t);return i?{writable:!0,configurable:1!==e.type_||"length"!==t,enumerable:i.enumerable,value:r[t]}:i},defineProperty(){q(11)},getPrototypeOf:e=>H(e.base_),setPrototypeOf(){q(12)}},Se={};function Ce(e,t){const r=e[$];return(r?ie(r):e)[t]}function Re(e,t){if(!(t in e))return;let r=H(e);for(;r;){const e=Object.getOwnPropertyDescriptor(r,t);if(e)return e;r=H(r)}}function ke(e){e.modified_||(e.modified_=!0,e.parent_&&ke(e.parent_))}function Te(e){e.copy_||(e.copy_=ne(e.base_,e.scope_.immer_.useStrictShallowCopy_))}Q(_e,((e,t)=>{Se[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}})),Se.deleteProperty=function(e,t){return isNaN(parseInt(t))&&q(13),Se.set.call(this,e,t,void 0)},Se.set=function(e,t,r){return"length"!==t&&isNaN(parseInt(t))&&q(14),_e.set.call(this,e[0],t,r,e[0])};function Pe(e,t){const r=te(e)?le("MapSet").proxyMap_(e,t):re(e)?le("MapSet").proxySet_(e,t):function(e,t){const r=Array.isArray(e),i={type_:r?1:0,scope_:t?t.scope_:ue(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1};let n=i,s=_e;r&&(n=[i],s=Se);const{revoke:o,proxy:a}=Proxy.revocable(n,s);return i.draft_=a,i.revoke_=o,a}(e,t);return(t?t.scope_:ue()).drafts_.push(r),r}function Ee(e){return W(e)||q(10,e),Oe(e)}function Oe(e){if(!K(e)||ae(e))return e;const t=e[$];let r;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,r=ne(e,t.scope_.immer_.useStrictShallowCopy_)}else r=ne(e,!0);return Q(r,((e,t)=>{ee(r,e,Oe(t))})),t&&(t.finalized_=!1),r}var De=new class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.produce=(e,t,r)=>{if("function"==typeof e&&"function"!=typeof t){const r=t;t=e;const i=this;return function(e=r,...n){return i.produce(e,(e=>t.call(this,e,...n)))}}let i;if("function"!=typeof t&&q(6),void 0!==r&&"function"!=typeof r&&q(7),K(e)){const n=me(this),s=Pe(e,void 0);let o=!0;try{i=t(s),o=!1}finally{o?he(n):fe(n)}return pe(n,r),ve(i,n)}if(!e||"object"!=typeof e){if(i=t(e),void 0===i&&(i=e),i===V&&(i=void 0),this.autoFreeze_&&se(i,!0),r){const t=[],n=[];le("Patches").generateReplacementPatches_(e,i,t,n),r(t,n)}return i}q(1,e)},this.produceWithPatches=(e,t)=>{if("function"==typeof e)return(t,...r)=>this.produceWithPatches(t,(t=>e(t,...r)));let r,i;return[this.produce(e,t,((e,t)=>{r=e,i=t})),r,i]},"boolean"==typeof e?.autoFreeze&&this.setAutoFreeze(e.autoFreeze),"boolean"==typeof e?.useStrictShallowCopy&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){K(e)||q(8),W(e)&&(e=Ee(e));const t=me(this),r=Pe(e,void 0);return r[$].isManual_=!0,fe(t),r}finishDraft(e,t){const r=e&&e[$];r&&r.isManual_||q(9);const{scope_:i}=r;return pe(i,t),ve(void 0,i)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}applyPatches(e,t){let r;for(r=t.length-1;r>=0;r--){const i=t[r];if(0===i.path.length&&"replace"===i.op){e=i.value;break}}r>-1&&(t=t.slice(r+1));const i=le("Patches").applyPatches_;return W(e)?i(e,t):this.produce(e,(e=>i(e,t)))}},Ie=De.produce;De.produceWithPatches.bind(De),De.setAutoFreeze.bind(De),De.setUseStrictShallowCopy.bind(De),De.applyPatches.bind(De),De.createDraft.bind(De),De.finishDraft.bind(De);var xe=(e,t,r)=>{if(1===t.length&&t[0]===r){let t=!1;try{const r={};e(r)===r&&(t=!0)}catch{}if(t){let e;try{throw new Error}catch(t){({stack:e}=t)}console.warn("The result function returned its own inputs without modification. e.g\n`createSelector([state => state.todos], todos => todos)`\nThis could lead to inefficient memoization and unnecessary re-renders.\nEnsure transformation logic is in the result function, and extraction logic is in the input selectors.",{stack:e})}}},Me=(e,t,r)=>{const{memoize:i,memoizeOptions:n}=t,{inputSelectorResults:s,inputSelectorResultsCopy:o}=e,a=i((()=>({})),...n);if(!(a.apply(null,s)===a.apply(null,o))){let e;try{throw new Error}catch(t){({stack:e}=t)}console.warn("An input selector returned a different result when passed same arguments.\nThis means your output selector will likely run more frequently than intended.\nAvoid returning a new reference inside your input selector, e.g.\n`createSelector([state => state.todos.map(todo => todo.id)], todoIds => todoIds.length)`",{arguments:r,firstInputs:s,secondInputs:o,stack:e})}},Le={inputStabilityCheck:"once",identityFunctionCheck:"once"};var je=e=>Array.isArray(e)?e:[e];function Ae(e){const t=Array.isArray(e[0])?e[0]:e;return function(e,t="expected all items to be functions, instead received the following types: "){if(!e.every((e=>"function"==typeof e))){const r=e.map((e=>"function"==typeof e?`function ${e.name||"unnamed"}()`:typeof e)).join(", ");throw new TypeError(`${t}[${r}]`)}}(t,"createSelector expects all input-selectors to be functions, but received the following types: "),t}function Ne(e,t){const r=[],{length:i}=e;for(let n=0;n<i;n++)r.push(e[n].apply(null,t));return r}var Be="undefined"!=typeof WeakRef?WeakRef:class{constructor(e){this.value=e}deref(){return this.value}},Fe=0,ze=1;function Ve(){return{s:Fe,v:void 0,o:null,p:null}}function Ue(e,t={}){let r=Ve();const{resultEqualityCheck:i}=t;let n,s=0;function o(){let t=r;const{length:o}=arguments;for(let e=0,r=o;e<r;e++){const r=arguments[e];if("function"==typeof r||"object"==typeof r&&null!==r){let e=t.o;null===e&&(t.o=e=new WeakMap);const i=e.get(r);void 0===i?(t=Ve(),e.set(r,t)):t=i}else{let e=t.p;null===e&&(t.p=e=new Map);const i=e.get(r);void 0===i?(t=Ve(),e.set(r,t)):t=i}}const a=t;let c;if(t.s===ze?c=t.v:(c=e.apply(null,arguments),s++),a.s=ze,i){const e=n?.deref?.()??n;null!=e&&i(e,c)&&(c=e,0!==s&&s--);n="object"==typeof c&&null!==c||"function"==typeof c?new Be(c):c}return a.v=c,c}return o.clearCache=()=>{r=Ve(),o.resetResultsCount()},o.resultsCount=()=>s,o.resetResultsCount=()=>{s=0},o}function $e(e,...t){const r="function"==typeof e?{memoize:e,memoizeOptions:t}:e,i=(...e)=>{let t,i=0,n=0,s={},o=e.pop();"object"==typeof o&&(s=o,o=e.pop()),function(e,t="expected a function, instead received "+typeof e){if("function"!=typeof e)throw new TypeError(t)}(o,`createSelector expects an output function after the inputs, but received: [${typeof o}]`);const a={...r,...s},{memoize:c,memoizeOptions:d=[],argsMemoize:l=Ue,argsMemoizeOptions:u=[],devModeChecks:p={}}=a,h=je(d),f=je(u),m=Ae(e),g=c((function(){return i++,o.apply(null,arguments)}),...h);let v=!0;const b=l((function(){n++;const e=Ne(m,arguments);t=g.apply(null,e);{const{identityFunctionCheck:r,inputStabilityCheck:i}=((e,t)=>{const{identityFunctionCheck:r,inputStabilityCheck:i}={...Le,...t};return{identityFunctionCheck:{shouldRun:"always"===r||"once"===r&&e,run:xe},inputStabilityCheck:{shouldRun:"always"===i||"once"===i&&e,run:Me}}})(v,p);if(r.shouldRun&&r.run(o,e,t),i.shouldRun){const t=Ne(m,arguments);i.run({inputSelectorResults:e,inputSelectorResultsCopy:t},{memoize:c,memoizeOptions:h},arguments)}v&&(v=!1)}return t}),...f);return Object.assign(b,{resultFunc:o,memoizedResultFunc:g,dependencies:m,dependencyRecomputations:()=>n,resetDependencyRecomputations:()=>{n=0},lastResult:()=>t,recomputations:()=>i,resetRecomputations:()=>{i=0},memoize:c,argsMemoize:l})};return Object.assign(i,{withTypes:()=>i}),i}var Ge=$e(Ue),qe=Object.assign(((e,t=Ge)=>{!function(e,t="expected an object, instead received "+typeof e){if("object"!=typeof e)throw new TypeError(t)}(e,"createStructuredSelector expects first argument to be an object where each property is a selector, instead received a "+typeof e);const r=Object.keys(e),i=t(r.map((t=>e[t])),((...e)=>e.reduce(((e,t,i)=>(e[r[i]]=t,e)),{})));return i}),{withTypes:()=>qe});function He(e){return({dispatch:t,getState:r})=>i=>n=>"function"==typeof n?n(t,r,e):i(n)}var We=He(),Ke=He;((...e)=>{const t=$e(...e),r=Object.assign(((...e)=>{const r=t(...e),i=(e,...t)=>r(W(e)?Ee(e):e,...t);return Object.assign(i,r),i}),{withTypes:()=>r})})(Ue);var Je="undefined"!=typeof window&&window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__?window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__:function(){if(0!==arguments.length)return"object"==typeof arguments[0]?F:F.apply(null,arguments)},Xe=e=>e&&"function"==typeof e.match;function Qe(e,t){function r(...r){if(t){let i=t(...r);if(!i)throw new Error("prepareAction did not return an object");return{type:e,payload:i.payload,..."meta"in i&&{meta:i.meta},..."error"in i&&{error:i.error}}}return{type:e,payload:r[0]}}return r.toString=()=>`${e}`,r.type=e,r.match=t=>z(t)&&t.type===e,r}function Ze(e){return"function"==typeof e&&"type"in e&&Xe(e)}function Ye(e,t){let r=0;return{measureTime(e){const t=Date.now();try{return e()}finally{const e=Date.now();r+=e-t}},warnIfExceeded(){r>e&&console.warn(`${t} took ${r}ms, which is more than the warning threshold of ${e}ms. \nIf your state or actions are very large, you may want to disable the middleware as it might cause too much of a slowdown in development mode. See https://redux-toolkit.js.org/api/getDefaultMiddleware for instructions.\nIt is disabled in production builds, so you don't need to worry about that.`)}}}function et(e,t){for(const r of e)if(t(r))return r}var tt=class e extends Array{constructor(...t){super(...t),Object.setPrototypeOf(this,e.prototype)}static get[Symbol.species](){return e}concat(...e){return super.concat.apply(this,e)}prepend(...t){return 1===t.length&&Array.isArray(t[0])?new e(...t[0].concat(this)):new e(...t.concat(this))}};function rt(e){return K(e)?Ie(e,(()=>{})):e}function it(e,t,r){if(e.has(t)){let i=e.get(t);return r.update&&(i=r.update(i,t,e),e.set(t,i)),i}if(!r.insert)throw new Error("No insert provided for key not already in map");const i=r.insert(t,e);return e.set(t,i),i}function nt(e){return"object"!=typeof e||null==e||Object.isFrozen(e)}function st(e,t,r){const i=ot(e,t,r);return{detectMutations:()=>at(e,t,i,r)}}function ot(e,t=[],r,i="",n=new Set){const s={value:r};if(!e(r)&&!n.has(r)){n.add(r),s.children={};for(const n in r){const o=i?i+"."+n:n;t.length&&-1!==t.indexOf(o)||(s.children[n]=ot(e,t,r[n],o))}}return s}function at(e,t=[],r,i,n=!1,s=""){const o=r?r.value:void 0,a=o===i;if(n&&!a&&!Number.isNaN(i))return{wasMutated:!0,path:s};if(e(o)||e(i))return{wasMutated:!1};const c={};for(let e in r.children)c[e]=!0;for(let e in i)c[e]=!0;const d=t.length>0;for(let n in c){const o=s?s+"."+n:n;if(d){if(t.some((e=>e instanceof RegExp?e.test(o):o===e)))continue}const c=at(e,t,r.children[n],i[n],a,o);if(c.wasMutated)return c}return{wasMutated:!1}}function ct(e){const t=typeof e;return null==e||"string"===t||"boolean"===t||"number"===t||Array.isArray(e)||M(e)}function dt(e,t="",r=ct,i,n=[],s){let o;if(!r(e))return{keyPath:t||"<root>",value:e};if("object"!=typeof e||null===e)return!1;if(s?.has(e))return!1;const a=null!=i?i(e):Object.entries(e),c=n.length>0;for(const[e,d]of a){const a=t?t+"."+e:e;if(c){if(n.some((e=>e instanceof RegExp?e.test(a):a===e)))continue}if(!r(d))return{keyPath:a,value:d};if("object"==typeof d&&(o=dt(d,a,r,i,n,s),o))return o}return s&<(e)&&s.add(e),!1}function lt(e){if(!Object.isFrozen(e))return!1;for(const t of Object.values(e))if("object"==typeof t&&null!==t&&!lt(t))return!1;return!0}function ut(e){return"boolean"==typeof e}var pt=()=>function(e){const{thunk:t=!0,immutableCheck:r=!0,serializableCheck:i=!0,actionCreatorCheck:n=!0}=e??{};let s=new tt;if(t&&(ut(t)?s.push(We):s.push(Ke(t.extraArgument))),r){let e={};ut(r)||(e=r),s.unshift(function(e={}){{let t=function(e,t,i,n){return JSON.stringify(e,r(t,n),i)},r=function(e,t){let r=[],i=[];return t||(t=function(e,t){return r[0]===t?"[Circular ~]":"[Circular ~."+i.slice(0,r.indexOf(t)).join(".")+"]"}),function(n,s){if(r.length>0){var o=r.indexOf(this);~o?r.splice(o+1):r.push(this),~o?i.splice(o,1/0,n):i.push(n),~r.indexOf(s)&&(s=t.call(this,n,s))}else r.push(s);return null==e?s:e.call(this,n,s)}},{isImmutable:i=nt,ignoredPaths:n,warnAfter:s=32}=e;const o=st.bind(null,i,n);return({getState:e})=>{let r,i=e(),n=o(i);return a=>c=>{const d=Ye(s,"ImmutableStateInvariantMiddleware");d.measureTime((()=>{if(i=e(),r=n.detectMutations(),n=o(i),r.wasMutated)throw new Error(`A state mutation was detected between dispatches, in the path '${r.path||""}'. This may cause incorrect behavior. (https://redux.js.org/style-guide/style-guide#do-not-mutate-state)`)}));const l=a(c);return d.measureTime((()=>{if(i=e(),r=n.detectMutations(),n=o(i),r.wasMutated)throw new Error(`A state mutation was detected inside a dispatch, in the path: ${r.path||""}. Take a look at the reducer(s) handling the action ${t(c)}. (https://redux.js.org/style-guide/style-guide#do-not-mutate-state)`)})),d.warnIfExceeded(),l}}}}(e))}if(i){let e={};ut(i)||(e=i),s.push(function(e={}){{const{isSerializable:t=ct,getEntries:r,ignoredActions:i=[],ignoredActionPaths:n=["meta.arg","meta.baseQueryMeta"],ignoredPaths:s=[],warnAfter:o=32,ignoreState:a=!1,ignoreActions:c=!1,disableCache:d=!1}=e,l=!d&&WeakSet?new WeakSet:void 0;return e=>d=>u=>{if(!z(u))return d(u);const p=d(u),h=Ye(o,"SerializableStateInvariantMiddleware");return c||i.length&&-1!==i.indexOf(u.type)||h.measureTime((()=>{const e=dt(u,"",t,r,n,l);if(e){const{keyPath:t,value:r}=e;console.error(`A non-serializable value was detected in an action, in the path: \`${t}\`. Value:`,r,"\nTake a look at the logic that dispatched this action: ",u,"\n(See https://redux.js.org/faq/actions#why-should-type-be-a-string-or-at-least-serializable-why-should-my-action-types-be-constants)","\n(To allow non-serializable values see: https://redux-toolkit.js.org/usage/usage-guide#working-with-non-serializable-data)")}})),a||(h.measureTime((()=>{const i=dt(e.getState(),"",t,r,s,l);if(i){const{keyPath:e,value:t}=i;console.error(`A non-serializable value was detected in the state, in the path: \`${e}\`. Value:`,t,`\nTake a look at the reducer(s) handling this action type: ${u.type}.\n(See https://redux.js.org/faq/organizing-state#can-i-put-functions-promises-or-other-non-serializable-items-in-my-store-state)`)}})),h.warnIfExceeded()),p}}}(e))}if(n){let e={};ut(n)||(e=n),s.unshift(function(e={}){const{isActionCreator:t=Ze}=e;return()=>e=>r=>(t(r)&&console.warn(function(e){const t=e?`${e}`.split("/"):[],r=t[t.length-1]||"actionCreator";return`Detected an action creator with type "${e||"unknown"}" being dispatched. \nMake sure you're calling the action creator before dispatching, i.e. \`dispatch(${r}())\` instead of \`dispatch(${r})\`. This is necessary even if the action has no payload.`}(r.type)),e(r))}(e))}return s},ht=e=>t=>{setTimeout(t,e)},ft="undefined"!=typeof window&&window.requestAnimationFrame?window.requestAnimationFrame:ht(10),mt=e=>function(t){const{autoBatch:r=!0}=t??{};let i=new tt(e);return r&&i.push(((e={type:"raf"})=>t=>(...r)=>{const i=t(...r);let n=!0,s=!1,o=!1;const a=new Set,c="tick"===e.type?queueMicrotask:"raf"===e.type?ft:"callback"===e.type?e.queueNotification:ht(e.timeout),d=()=>{o=!1,s&&(s=!1,a.forEach((e=>e())))};return Object.assign({},i,{subscribe(e){const t=i.subscribe((()=>n&&e()));return a.add(e),()=>{t(),a.delete(e)}},dispatch(e){try{return n=!e?.meta?.RTK_autoBatch,s=!n,s&&(o||(o=!0,c(d))),i.dispatch(e)}finally{n=!0}}})})("object"==typeof r?r:void 0)),i};function gt(e){const t=pt(),{reducer:r,middleware:i,devTools:n=!0,preloadedState:s,enhancers:o}=e||{};let a,c;if("function"==typeof r)a=r;else{if(!M(r))throw new Error("`reducer` is a required argument, and must be a function or an object of functions that can be passed to combineReducers");a=B(r)}if(i&&"function"!=typeof i)throw new Error("`middleware` field must be a callback");if("function"==typeof i){if(c=i(t),!Array.isArray(c))throw new Error("when using a middleware builder function, an array of middleware must be returned")}else c=t();if(c.some((e=>"function"!=typeof e)))throw new Error("each middleware provided to configureStore must be a function");let d=F;n&&(d=Je({trace:!0,..."object"==typeof n&&n}));const l=function(...e){return t=>(r,i)=>{const n=t(r,i);let s=()=>{throw new Error("Dispatching while constructing your middleware is not allowed. Other middleware would not be applied to this dispatch.")};const o={getState:n.getState,dispatch:(e,...t)=>s(e,...t)},a=e.map((e=>e(o)));return s=F(...a)(n.dispatch),{...n,dispatch:s}}}(...c),u=mt(l);if(o&&"function"!=typeof o)throw new Error("`enhancers` field must be a callback");let p="function"==typeof o?o(u):u();if(!Array.isArray(p))throw new Error("`enhancers` callback must return an array");if(p.some((e=>"function"!=typeof e)))throw new Error("each enhancer provided to configureStore must be a function");c.length&&!p.includes(l)&&console.error("middlewares were provided, but middleware enhancer was not included in final enhancers - make sure to call `getDefaultEnhancers`");return A(a,s,d(...p))}function vt(e){const t={},r=[];let i;const n={addCase(e,s){if(r.length>0)throw new Error("`builder.addCase` should only be called before calling `builder.addMatcher`");if(i)throw new Error("`builder.addCase` should only be called before calling `builder.addDefaultCase`");const o="string"==typeof e?e:e.type;if(!o)throw new Error("`builder.addCase` cannot be called with an empty action type");if(o in t)throw new Error(`\`builder.addCase\` cannot be called with two reducers for the same action type '${o}'`);return t[o]=s,n},addMatcher(e,t){if(i)throw new Error("`builder.addMatcher` should only be called before calling `builder.addDefaultCase`");return r.push({matcher:e,reducer:t}),n},addDefaultCase(e){if(i)throw new Error("`builder.addDefaultCase` can only be called once");return i=e,n}};return e(n),[t,r,i]}var bt=(e=21)=>{let t="",r=e;for(;r--;)t+="ModuleSymbhasOwnPr-0123456789ABCDEFGHNRVfgctiUvz_KqYTJkLxpZXIjQW"[64*Math.random()|0];return t};function yt(...e){return t=>e.some((e=>((e,t)=>Xe(e)?e.match(t):e(t))(e,t)))}var wt=["name","message","stack","code"],_t=class{constructor(e,t){this.payload=e,this.meta=t}_type},St=class{constructor(e,t){this.payload=e,this.meta=t}_type},Ct=e=>{if("object"==typeof e&&null!==e){const t={};for(const r of wt)"string"==typeof e[r]&&(t[r]=e[r]);return t}return{message:String(e)}},Rt=(()=>{function e(e,t,r){const i=Qe(e+"/fulfilled",((e,t,r,i)=>({payload:e,meta:{...i||{},arg:r,requestId:t,requestStatus:"fulfilled"}}))),n=Qe(e+"/pending",((e,t,r)=>({payload:void 0,meta:{...r||{},arg:t,requestId:e,requestStatus:"pending"}}))),s=Qe(e+"/rejected",((e,t,i,n,s)=>({payload:n,error:(r&&r.serializeError||Ct)(e||"Rejected"),meta:{...s||{},arg:i,requestId:t,rejectedWithValue:!!n,requestStatus:"rejected",aborted:"AbortError"===e?.name,condition:"ConditionError"===e?.name}})));return Object.assign((function(e){return(o,a,c)=>{const d=r?.idGenerator?r.idGenerator(e):bt(),l=new AbortController;let u,p;function h(e){p=e,l.abort()}const f=async function(){let f;try{let s=r?.condition?.(e,{getState:a,extra:c});if(function(e){return null!==e&&"object"==typeof e&&"function"==typeof e.then}(s)&&(s=await s),!1===s||l.signal.aborted)throw{name:"ConditionError",message:"Aborted due to condition callback returning false."};const m=new Promise(((e,t)=>{u=()=>{t({name:"AbortError",message:p||"Aborted"})},l.signal.addEventListener("abort",u)}));o(n(d,e,r?.getPendingMeta?.({requestId:d,arg:e},{getState:a,extra:c}))),f=await Promise.race([m,Promise.resolve(t(e,{dispatch:o,getState:a,extra:c,requestId:d,signal:l.signal,abort:h,rejectWithValue:(e,t)=>new _t(e,t),fulfillWithValue:(e,t)=>new St(e,t)})).then((t=>{if(t instanceof _t)throw t;return t instanceof St?i(t.payload,d,e,t.meta):i(t,d,e)}))])}catch(t){f=t instanceof _t?s(null,d,e,t.payload,t.meta):s(t,d,e)}finally{u&&l.signal.removeEventListener("abort",u)}return r&&!r.dispatchConditionRejection&&s.match(f)&&f.meta.condition||o(f),f}();return Object.assign(f,{abort:h,requestId:d,arg:e,unwrap:()=>f.then(kt)})}}),{pending:n,rejected:s,fulfilled:i,settled:yt(s,i),typePrefix:e})}return e.withTypes=()=>e,e})();function kt(e){if(e.meta&&e.meta.rejectedWithValue)throw e.payload;if(e.error)throw e.error;return e.payload}var Tt=Symbol.for("rtk-slice-createasyncthunk");function Pt(e,t){return`${e}/${t}`}function Et({creators:e}={}){const t=e?.asyncThunk?.[Tt];return function(e){const{name:r,reducerPath:i=r}=e;if(!r)throw new Error("`name` is a required option for createSlice");const n=("function"==typeof e.reducers?e.reducers(function(){function e(e,t){return{_reducerDefinitionType:"asyncThunk",payloadCreator:e,...t}}return e.withTypes=()=>e,{reducer:e=>Object.assign({[e.name]:(...t)=>e(...t)}[e.name],{_reducerDefinitionType:"reducer"}),preparedReducer:(e,t)=>({_reducerDefinitionType:"reducerWithPrepare",prepare:e,reducer:t}),asyncThunk:e}}()):e.reducers)||{},s=Object.keys(n),o={sliceCaseReducersByName:{},sliceCaseReducersByType:{},actionCreators:{},sliceMatchers:[]},a={addCase(e,t){const r="string"==typeof e?e:e.type;if(!r)throw new Error("`context.addCase` cannot be called with an empty action type");if(r in o.sliceCaseReducersByType)throw new Error("`context.addCase` cannot be called with two reducers for the same action type: "+r);return o.sliceCaseReducersByType[r]=t,a},addMatcher:(e,t)=>(o.sliceMatchers.push({matcher:e,reducer:t}),a),exposeAction:(e,t)=>(o.actionCreators[e]=t,a),exposeCaseReducer:(e,t)=>(o.sliceCaseReducersByName[e]=t,a)};function c(){if("object"==typeof e.extraReducers)throw new Error("The object notation for `createSlice.extraReducers` has been removed. Please use the 'builder callback' notation instead: https://redux-toolkit.js.org/api/createSlice");const[t={},r=[],i]="function"==typeof e.extraReducers?vt(e.extraReducers):[e.extraReducers],n={...t,...o.sliceCaseReducersByType};return function(e,t){if("object"==typeof t)throw new Error("The object notation for `createReducer` has been removed. Please use the 'builder callback' notation instead: https://redux-toolkit.js.org/api/createReducer");let r,[i,n,s]=vt(t);if("function"==typeof e)r=()=>rt(e());else{const t=rt(e);r=()=>t}function o(e=r(),t){let o=[i[t.type],...n.filter((({matcher:e})=>e(t))).map((({reducer:e})=>e))];return 0===o.filter((e=>!!e)).length&&(o=[s]),o.reduce(((e,r)=>{if(r){if(W(e)){const i=r(e,t);return void 0===i?e:i}if(K(e))return Ie(e,(e=>r(e,t)));{const i=r(e,t);if(void 0===i){if(null===e)return e;throw new Error("A case reducer on a non-draftable value must not return undefined")}return i}}return e}),e)}return o.getInitialState=r,o}(e.initialState,(e=>{for(let t in n)e.addCase(t,n[t]);for(let t of o.sliceMatchers)e.addMatcher(t.matcher,t.reducer);for(let t of r)e.addMatcher(t.matcher,t.reducer);i&&e.addDefaultCase(i)}))}s.forEach((i=>{const s=n[i],o={reducerName:i,type:Pt(r,i),createNotation:"function"==typeof e.reducers};!function(e){return"asyncThunk"===e._reducerDefinitionType}(s)?function({type:e,reducerName:t,createNotation:r},i,n){let s,o;if("reducer"in i){if(r&&!function(e){return"reducerWithPrepare"===e._reducerDefinitionType}(i))throw new Error("Please use the `create.preparedReducer` notation for prepared action creators with the `create` notation.");s=i.reducer,o=i.prepare}else s=i;n.addCase(e,s).exposeCaseReducer(t,s).exposeAction(t,o?Qe(e,o):Qe(e))}(o,s,a):function({type:e,reducerName:t},r,i,n){if(!n)throw new Error("Cannot use `create.asyncThunk` in the built-in `createSlice`. Use `buildCreateSlice({ creators: { asyncThunk: asyncThunkCreator } })` to create a customised version of `createSlice`.");const{payloadCreator:s,fulfilled:o,pending:a,rejected:c,settled:d,options:l}=r,u=n(e,s,l);i.exposeAction(t,u),o&&i.addCase(u.fulfilled,o);a&&i.addCase(u.pending,a);c&&i.addCase(u.rejected,c);d&&i.addMatcher(u.settled,d);i.exposeCaseReducer(t,{fulfilled:o||It,pending:a||It,rejected:c||It,settled:d||It})}(o,s,a,t)}));const d=e=>e,l=new Map;let u;function p(e,t){return u||(u=c()),u(e,t)}function h(){return u||(u=c()),u.getInitialState()}function f(t,r=!1){function i(e){let i=e[t];if(void 0===i){if(!r)throw new Error("selectSlice returned undefined for an uninjected slice reducer");i=h()}return i}function n(t=d){const i=it(l,r,{insert:()=>new WeakMap});return it(i,t,{insert:()=>{const i={};for(const[n,s]of Object.entries(e.selectors??{}))i[n]=Ot(s,t,h,r);return i}})}return{reducerPath:t,getSelectors:n,get selectors(){return n(i)},selectSlice:i}}const m={name:r,reducer:p,actions:o.actionCreators,caseReducers:o.sliceCaseReducersByName,getInitialState:h,...f(i),injectInto(e,{reducerPath:t,...r}={}){const n=t??i;return e.inject({reducerPath:n,reducer:p},r),{...m,...f(n,!0)}}};return m}}function Ot(e,t,r,i){function n(n,...s){let o=t(n);if(void 0===o){if(!i)throw new Error("selectState returned undefined for an uninjected slice reducer");o=r()}return e(o,...s)}return n.unwrapped=e,n}var Dt=Et();function It(){}var xt="listener",Mt="completed",Lt="cancelled",jt=`task-${Lt}`,At=`task-${Mt}`,Nt=`${xt}-${Lt}`,Bt=`${xt}-${Mt}`,Ft=class{constructor(e){this.code=e,this.message=`task ${Lt} (reason: ${e})`}name="TaskAbortError";message},zt=(e,t)=>{if("function"!=typeof e)throw new Error(`${t} is not a function`)},Vt=()=>{},Ut=(e,t=Vt)=>(e.catch(t),e),$t=(e,t)=>(e.addEventListener("abort",t,{once:!0}),()=>e.removeEventListener("abort",t)),Gt=(e,t)=>{const r=e.signal;r.aborted||("reason"in r||Object.defineProperty(r,"reason",{enumerable:!0,value:t,configurable:!0,writable:!0}),e.abort(t))},qt=e=>{if(e.aborted){const{reason:t}=e;throw new Ft(t)}};function Ht(e,t){let r=Vt;return new Promise(((i,n)=>{const s=()=>n(new Ft(e.reason));e.aborted?s():(r=$t(e,s),t.finally((()=>r())).then(i,n))})).finally((()=>{r=Vt}))}var Wt=e=>t=>Ut(Ht(e,t).then((t=>(qt(e),t)))),Kt=e=>{const t=Wt(e);return e=>t(new Promise((t=>setTimeout(t,e))))},{assign:Jt}=Object,Xt={},Qt="listenerMiddleware",Zt=(e,t)=>(r,i)=>{zt(r,"taskExecutor");const n=new AbortController;var s;s=n,$t(e,(()=>Gt(s,e.reason)));const o=(async(e,t)=>{try{return await Promise.resolve(),{status:"ok",value:await e()}}catch(e){return{status:e instanceof Ft?"cancelled":"rejected",error:e}}finally{t?.()}})((async()=>{qt(e),qt(n.signal);const t=await r({pause:Wt(n.signal),delay:Kt(n.signal),signal:n.signal});return qt(n.signal),t}),(()=>Gt(n,At)));return i?.autoJoin&&t.push(o.catch(Vt)),{result:Wt(e)(o),cancel(){Gt(n,jt)}}},Yt=(e,t)=>(r,i)=>Ut((async(r,i)=>{qt(t);let n=()=>{};const s=[new Promise(((t,i)=>{let s=e({predicate:r,effect:(e,r)=>{r.unsubscribe(),t([e,r.getState(),r.getOriginalState()])}});n=()=>{s(),i()}}))];null!=i&&s.push(new Promise((e=>setTimeout(e,i,null))));try{const e=await Ht(t,Promise.race(s));return qt(t),e}finally{n()}})(r,i)),er=e=>{let{type:t,actionCreator:r,matcher:i,predicate:n,effect:s}=e;if(t)n=Qe(t).match;else if(r)t=r.type,n=r.match;else if(i)n=i;else if(!n)throw new Error("Creating or removing a listener requires one of the known fields for matching an action");return zt(s,"options.listener"),{predicate:n,type:t,effect:s}},tr=Object.assign((e=>{const{type:t,predicate:r,effect:i}=er(e);return{id:bt(),effect:i,type:t,predicate:r,pending:new Set,unsubscribe:()=>{throw new Error("Unsubscribe not initialized")}}}),{withTypes:()=>tr}),rr=e=>{e.pending.forEach((e=>{Gt(e,Nt)}))},ir=(e,t,r)=>{try{e(t,r)}catch(e){setTimeout((()=>{throw e}),0)}},nr=Object.assign(Qe(`${Qt}/add`),{withTypes:()=>nr}),sr=Qe(`${Qt}/removeAll`),or=Object.assign(Qe(`${Qt}/remove`),{withTypes:()=>or}),ar=(...e)=>{console.error(`${Qt}/error`,...e)};let cr=!0,dr=!0;function lr(e,t,r){const i=e.match(t);return i&&i.length>=r&&parseInt(i[r],10)}function ur(e,t,r){if(!e.RTCPeerConnection)return;const i=e.RTCPeerConnection.prototype,n=i.addEventListener;i.addEventListener=function(e,i){if(e!==t)return n.apply(this,arguments);const s=e=>{const t=r(e);t&&(i.handleEvent?i.handleEvent(t):i(t))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(i,s),n.apply(this,[e,s])};const s=i.removeEventListener;i.removeEventListener=function(e,r){if(e!==t||!this._eventMap||!this._eventMap[t])return s.apply(this,arguments);if(!this._eventMap[t].has(r))return s.apply(this,arguments);const i=this._eventMap[t].get(r);return this._eventMap[t].delete(r),0===this._eventMap[t].size&&delete this._eventMap[t],0===Object.keys(this._eventMap).length&&delete this._eventMap,s.apply(this,[e,i])},Object.defineProperty(i,"on"+t,{get(){return this["_on"+t]},set(e){this["_on"+t]&&(this.removeEventListener(t,this["_on"+t]),delete this["_on"+t]),e&&this.addEventListener(t,this["_on"+t]=e)},enumerable:!0,configurable:!0})}function pr(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(cr=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function hr(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(dr=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function fr(){if("object"==typeof window){if(cr)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function mr(e,t){dr&&console.warn(e+" is deprecated, please use "+t+" instead.")}function gr(e){return"[object Object]"===Object.prototype.toString.call(e)}function vr(e){return gr(e)?Object.keys(e).reduce((function(t,r){const i=gr(e[r]),n=i?vr(e[r]):e[r],s=i&&!Object.keys(n).length;return void 0===n||s?t:Object.assign(t,{[r]:n})}),{}):e}function br(e,t,r){t&&!r.has(t.id)&&(r.set(t.id,t),Object.keys(t).forEach((i=>{i.endsWith("Id")?br(e,e.get(t[i]),r):i.endsWith("Ids")&&t[i].forEach((t=>{br(e,e.get(t),r)}))})))}function yr(e,t,r){const i=r?"outbound-rtp":"inbound-rtp",n=new Map;if(null===t)return n;const s=[];return e.forEach((e=>{"track"===e.type&&e.trackIdentifier===t.id&&s.push(e)})),s.forEach((t=>{e.forEach((r=>{r.type===i&&r.trackId===t.id&&br(e,r,n)}))})),n}const wr=fr;function _r(e,t){const r=e&&e.navigator;if(!r.mediaDevices)return;const i=function(e){if("object"!=typeof e||e.mandatory||e.optional)return e;const t={};return Object.keys(e).forEach((r=>{if("require"===r||"advanced"===r||"mediaSource"===r)return;const i="object"==typeof e[r]?e[r]:{ideal:e[r]};void 0!==i.exact&&"number"==typeof i.exact&&(i.min=i.max=i.exact);const n=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):"deviceId"===t?"sourceId":t};if(void 0!==i.ideal){t.optional=t.optional||[];let e={};"number"==typeof i.ideal?(e[n("min",r)]=i.ideal,t.optional.push(e),e={},e[n("max",r)]=i.ideal,t.optional.push(e)):(e[n("",r)]=i.ideal,t.optional.push(e))}void 0!==i.exact&&"number"!=typeof i.exact?(t.mandatory=t.mandatory||{},t.mandatory[n("",r)]=i.exact):["min","max"].forEach((e=>{void 0!==i[e]&&(t.mandatory=t.mandatory||{},t.mandatory[n(e,r)]=i[e])}))})),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},n=function(e,n){if(t.version>=61)return n(e);if((e=JSON.parse(JSON.stringify(e)))&&"object"==typeof e.audio){const t=function(e,t,r){t in e&&!(r in e)&&(e[r]=e[t],delete e[t])};t((e=JSON.parse(JSON.stringify(e))).audio,"autoGainControl","googAutoGainControl"),t(e.audio,"noiseSuppression","googNoiseSuppression"),e.audio=i(e.audio)}if(e&&"object"==typeof e.video){let s=e.video.facingMode;s=s&&("object"==typeof s?s:{ideal:s});const o=t.version<66;if(s&&("user"===s.exact||"environment"===s.exact||"user"===s.ideal||"environment"===s.ideal)&&(!r.mediaDevices.getSupportedConstraints||!r.mediaDevices.getSupportedConstraints().facingMode||o)){let t;if(delete e.video.facingMode,"environment"===s.exact||"environment"===s.ideal?t=["back","rear"]:"user"!==s.exact&&"user"!==s.ideal||(t=["front"]),t)return r.mediaDevices.enumerateDevices().then((r=>{let o=(r=r.filter((e=>"videoinput"===e.kind))).find((e=>t.some((t=>e.label.toLowerCase().includes(t)))));return!o&&r.length&&t.includes("back")&&(o=r[r.length-1]),o&&(e.video.deviceId=s.exact?{exact:o.deviceId}:{ideal:o.deviceId}),e.video=i(e.video),wr("chrome: "+JSON.stringify(e)),n(e)}))}e.video=i(e.video)}return wr("chrome: "+JSON.stringify(e)),n(e)},s=function(e){return t.version>=64?e:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[e.name]||e.name,message:e.message,constraint:e.constraint||e.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}};if(r.getUserMedia=function(e,t,i){n(e,(e=>{r.webkitGetUserMedia(e,t,(e=>{i&&i(s(e))}))}))}.bind(r),r.mediaDevices.getUserMedia){const e=r.mediaDevices.getUserMedia.bind(r.mediaDevices);r.mediaDevices.getUserMedia=function(t){return n(t,(t=>e(t).then((e=>{if(t.audio&&!e.getAudioTracks().length||t.video&&!e.getVideoTracks().length)throw e.getTracks().forEach((e=>{e.stop()})),new DOMException("","NotFoundError");return e}),(e=>Promise.reject(s(e))))))}}}function Sr(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function Cr(e){if("object"==typeof e&&e.RTCPeerConnection&&!("ontrack"in e.RTCPeerConnection.prototype)){Object.defineProperty(e.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(e){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=e)},enumerable:!0,configurable:!0});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=t=>{t.stream.addEventListener("addtrack",(r=>{let i;i=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===r.track.id)):{track:r.track};const n=new Event("track");n.track=r.track,n.receiver=i,n.transceiver={receiver:i},n.streams=[t.stream],this.dispatchEvent(n)})),t.stream.getTracks().forEach((r=>{let i;i=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===r.id)):{track:r};const n=new Event("track");n.track=r,n.receiver=i,n.transceiver={receiver:i},n.streams=[t.stream],this.dispatchEvent(n)}))},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else ur(e,"track",(e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e)))}function Rr(e){if("object"==typeof e&&e.RTCPeerConnection&&!("getSenders"in e.RTCPeerConnection.prototype)&&"createDTMFSender"in e.RTCPeerConnection.prototype){const t=function(e,t){return{track:t,get dtmf(){return void 0===this._dtmf&&("audio"===t.kind?this._dtmf=e.createDTMFSender(t):this._dtmf=null),this._dtmf},_pc:e}};if(!e.RTCPeerConnection.prototype.getSenders){e.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const r=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,i){let n=r.apply(this,arguments);return n||(n=t(this,e),this._senders.push(n)),n};const i=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){i.apply(this,arguments);const t=this._senders.indexOf(e);-1!==t&&this._senders.splice(t,1)}}const r=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._senders=this._senders||[],r.apply(this,[e]),e.getTracks().forEach((e=>{this._senders.push(t(this,e))}))};const i=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._senders=this._senders||[],i.apply(this,[e]),e.getTracks().forEach((e=>{const t=this._senders.find((t=>t.track===e));t&&this._senders.splice(this._senders.indexOf(t),1)}))}}else if("object"==typeof e&&e.RTCPeerConnection&&"getSenders"in e.RTCPeerConnection.prototype&&"createDTMFSender"in e.RTCPeerConnection.prototype&&e.RTCRtpSender&&!("dtmf"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e},Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function kr(e){if(!("object"==typeof e&&e.RTCPeerConnection&&e.RTCRtpSender&&e.RTCRtpReceiver))return;if(!("getStats"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e});const r=e.RTCPeerConnection.prototype.addTrack;r&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=r.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>yr(t,e.track,!0)))}}if(!("getStats"in e.RTCRtpReceiver.prototype)){const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e}),ur(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>yr(t,e.track,!1)))}}if(!("getStats"in e.RTCRtpSender.prototype)||!("getStats"in e.RTCRtpReceiver.prototype))return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof e.MediaStreamTrack){const e=arguments[0];let t,r,i;return this.getSenders().forEach((r=>{r.track===e&&(t?i=!0:t=r)})),this.getReceivers().forEach((t=>(t.track===e&&(r?i=!0:r=t),t.track===e))),i||t&&r?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):t?t.getStats():r?r.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return t.apply(this,arguments)}}function Tr(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map((e=>this._shimmedLocalStreams[e][0]))};const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,r){if(!r)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const i=t.apply(this,arguments);return this._shimmedLocalStreams[r.id]?-1===this._shimmedLocalStreams[r.id].indexOf(i)&&this._shimmedLocalStreams[r.id].push(i):this._shimmedLocalStreams[r.id]=[r,i],i};const r=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._shimmedLocalStreams=this._shimmedLocalStreams||{},e.getTracks().forEach((e=>{if(this.getSenders().find((t=>t.track===e)))throw new DOMException("Track already exists.","InvalidAccessError")}));const t=this.getSenders();r.apply(this,arguments);const i=this.getSenders().filter((e=>-1===t.indexOf(e)));this._shimmedLocalStreams[e.id]=[e].concat(i)};const i=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],i.apply(this,arguments)};const n=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach((t=>{const r=this._shimmedLocalStreams[t].indexOf(e);-1!==r&&this._shimmedLocalStreams[t].splice(r,1),1===this._shimmedLocalStreams[t].length&&delete this._shimmedLocalStreams[t]})),n.apply(this,arguments)}}function Pr(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return Tr(e);const r=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){const e=r.apply(this);return this._reverseStreams=this._reverseStreams||{},e.map((e=>this._reverseStreams[e.id]))};const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(t){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},t.getTracks().forEach((e=>{if(this.getSenders().find((t=>t.track===e)))throw new DOMException("Track already exists.","InvalidAccessError")})),!this._reverseStreams[t.id]){const r=new e.MediaStream(t.getTracks());this._streams[t.id]=r,this._reverseStreams[r.id]=t,t=r}i.apply(this,[t])};const n=e.RTCPeerConnection.prototype.removeStream;function s(e,t){let r=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const i=e._reverseStreams[t],n=e._streams[i.id];r=r.replace(new RegExp(n.id,"g"),i.id)})),new RTCSessionDescription({type:t.type,sdp:r})}e.RTCPeerConnection.prototype.removeStream=function(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},n.apply(this,[this._streams[e.id]||e]),delete this._reverseStreams[this._streams[e.id]?this._streams[e.id].id:e.id],delete this._streams[e.id]},e.RTCPeerConnection.prototype.addTrack=function(t,r){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const i=[].slice.call(arguments,1);if(1!==i.length||!i[0].getTracks().find((e=>e===t)))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");if(this.getSenders().find((e=>e.track===t)))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const n=this._streams[r.id];if(n)n.addTrack(t),Promise.resolve().then((()=>{this.dispatchEvent(new Event("negotiationneeded"))}));else{const i=new e.MediaStream([t]);this._streams[r.id]=i,this._reverseStreams[i.id]=r,this.addStream(i)}return this.getSenders().find((e=>e.track===t))},["createOffer","createAnswer"].forEach((function(t){const r=e.RTCPeerConnection.prototype[t],i={[t](){const e=arguments;return arguments.length&&"function"==typeof arguments[0]?r.apply(this,[t=>{const r=s(this,t);e[0].apply(null,[r])},t=>{e[1]&&e[1].apply(null,t)},arguments[2]]):r.apply(this,arguments).then((e=>s(this,e)))}};e.RTCPeerConnection.prototype[t]=i[t]}));const o=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=function(e,t){let r=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const i=e._reverseStreams[t],n=e._streams[i.id];r=r.replace(new RegExp(i.id,"g"),n.id)})),new RTCSessionDescription({type:t.type,sdp:r})}(this,arguments[0]),o.apply(this,arguments)):o.apply(this,arguments)};const a=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get(){const e=a.get.apply(this);return""===e.type?e:s(this,e)}}),e.RTCPeerConnection.prototype.removeTrack=function(e){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!e._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(e._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");let t;this._streams=this._streams||{},Object.keys(this._streams).forEach((r=>{this._streams[r].getTracks().find((t=>e.track===t))&&(t=this._streams[r])})),t&&(1===t.getTracks().length?this.removeStream(this._reverseStreams[t.id]):t.removeTrack(e.track),this.dispatchEvent(new Event("negotiationneeded")))}}function Er(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const r=e.RTCPeerConnection.prototype[t],i={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),r.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=i[t]}))}function Or(e,t){ur(e,"negotiationneeded",(e=>{const r=e.target;if(!(t.version<72||r.getConfiguration&&"plan-b"===r.getConfiguration().sdpSemantics)||"stable"===r.signalingState)return e}))}var Dr=Object.freeze({__proto__:null,fixNegotiationNeeded:Or,shimAddTrackRemoveTrack:Pr,shimAddTrackRemoveTrackWithNative:Tr,shimGetSendersWithDtmf:Rr,shimGetUserMedia:_r,shimMediaStream:Sr,shimOnTrack:Cr,shimPeerConnection:Er,shimSenderReceiverGetStats:kr});function Ir(e,t){const r=e&&e.navigator,i=e&&e.MediaStreamTrack;if(r.getUserMedia=function(e,t,i){mr("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),r.mediaDevices.getUserMedia(e).then(t,i)},!(t.version>55&&"autoGainControl"in r.mediaDevices.getSupportedConstraints())){const e=function(e,t,r){t in e&&!(r in e)&&(e[r]=e[t],delete e[t])},t=r.mediaDevices.getUserMedia.bind(r.mediaDevices);if(r.mediaDevices.getUserMedia=function(r){return"object"==typeof r&&"object"==typeof r.audio&&(r=JSON.parse(JSON.stringify(r)),e(r.audio,"autoGainControl","mozAutoGainControl"),e(r.audio,"noiseSuppression","mozNoiseSuppression")),t(r)},i&&i.prototype.getSettings){const t=i.prototype.getSettings;i.prototype.getSettings=function(){const r=t.apply(this,arguments);return e(r,"mozAutoGainControl","autoGainControl"),e(r,"mozNoiseSuppression","noiseSuppression"),r}}if(i&&i.prototype.applyConstraints){const t=i.prototype.applyConstraints;i.prototype.applyConstraints=function(r){return"audio"===this.kind&&"object"==typeof r&&(r=JSON.parse(JSON.stringify(r)),e(r,"autoGainControl","mozAutoGainControl"),e(r,"noiseSuppression","mozNoiseSuppression")),t.apply(this,[r])}}}}function xr(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function Mr(e,t){if("object"!=typeof e||!e.RTCPeerConnection&&!e.mozRTCPeerConnection)return;!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection),t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const r=e.RTCPeerConnection.prototype[t],i={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),r.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=i[t]}));const r={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},i=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,n,s]=arguments;return i.apply(this,[e||null]).then((e=>{if(t.version<53&&!n)try{e.forEach((e=>{e.type=r[e.type]||e.type}))}catch(t){if("TypeError"!==t.name)throw t;e.forEach(((t,i)=>{e.set(i,Object.assign({},t,{type:r[t.type]||t.type}))}))}return e})).then(n,s)}}function Lr(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpSender.prototype)return;const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e});const r=e.RTCPeerConnection.prototype.addTrack;r&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=r.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function jr(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpReceiver.prototype)return;const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e}),ur(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function Ar(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){mr("removeStream","removeTrack"),this.getSenders().forEach((t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)}))})}function Nr(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function Br(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.addTransceiver;t&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let e=arguments[1]&&arguments[1].sendEncodings;void 0===e&&(e=[]),e=[...e];const r=e.length>0;r&&e.forEach((e=>{if("rid"in e){if(!/^[a-z0-9]{0,16}$/i.test(e.rid))throw new TypeError("Invalid RID value provided.")}if("scaleResolutionDownBy"in e&&!(parseFloat(e.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in e&&!(parseFloat(e.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")}));const i=t.apply(this,arguments);if(r){const{sender:t}=i,r=t.getParameters();(!("encodings"in r)||1===r.encodings.length&&0===Object.keys(r.encodings[0]).length)&&(r.encodings=e,t.sendEncodings=e,this.setParametersPromises.push(t.setParameters(r).then((()=>{delete t.sendEncodings})).catch((()=>{delete t.sendEncodings}))))}return i})}function Fr(e){if("object"!=typeof e||!e.RTCRtpSender)return;const t=e.RTCRtpSender.prototype.getParameters;t&&(e.RTCRtpSender.prototype.getParameters=function(){const e=t.apply(this,arguments);return"encodings"in e||(e.encodings=[].concat(this.sendEncodings||[{}])),e})}function zr(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((()=>t.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):t.apply(this,arguments)}}function Vr(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createAnswer;e.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((()=>t.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):t.apply(this,arguments)}}var Ur=Object.freeze({__proto__:null,shimAddTransceiver:Br,shimCreateAnswer:Vr,shimCreateOffer:zr,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&(e.navigator.mediaDevices.getDisplayMedia=function(r){if(!r||!r.video){const e=new DOMException("getDisplayMedia without video constraints is undefined");return e.name="NotFoundError",e.code=8,Promise.reject(e)}return!0===r.video?r.video={mediaSource:t}:r.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(r)})},shimGetParameters:Fr,shimGetUserMedia:Ir,shimOnTrack:xr,shimPeerConnection:Mr,shimRTCDataChannel:Nr,shimReceiverGetStats:jr,shimRemoveStream:Ar,shimSenderGetStats:Lr});function $r(e){if("object"==typeof e&&e.RTCPeerConnection){if("getLocalStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in e.RTCPeerConnection.prototype)){const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addStream=function(e){this._localStreams||(this._localStreams=[]),this._localStreams.includes(e)||this._localStreams.push(e),e.getAudioTracks().forEach((r=>t.call(this,r,e))),e.getVideoTracks().forEach((r=>t.call(this,r,e)))},e.RTCPeerConnection.prototype.addTrack=function(e,...r){return r&&r.forEach((e=>{this._localStreams?this._localStreams.includes(e)||this._localStreams.push(e):this._localStreams=[e]})),t.apply(this,arguments)}}"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){this._localStreams||(this._localStreams=[]);const t=this._localStreams.indexOf(e);if(-1===t)return;this._localStreams.splice(t,1);const r=e.getTracks();this.getSenders().forEach((e=>{r.includes(e.track)&&this.removeTrack(e)}))})}}function Gr(e){if("object"==typeof e&&e.RTCPeerConnection&&("getRemoteStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in e.RTCPeerConnection.prototype))){Object.defineProperty(e.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(e){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=e),this.addEventListener("track",this._onaddstreampoly=e=>{e.streams.forEach((e=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(e))return;this._remoteStreams.push(e);const t=new Event("addstream");t.stream=e,this.dispatchEvent(t)}))})}});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){const e=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(t){t.streams.forEach((t=>{if(e._remoteStreams||(e._remoteStreams=[]),e._remoteStreams.indexOf(t)>=0)return;e._remoteStreams.push(t);const r=new Event("addstream");r.stream=t,e.dispatchEvent(r)}))}),t.apply(e,arguments)}}}function qr(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype,r=t.createOffer,i=t.createAnswer,n=t.setLocalDescription,s=t.setRemoteDescription,o=t.addIceCandidate;t.createOffer=function(e,t){const i=arguments.length>=2?arguments[2]:arguments[0],n=r.apply(this,[i]);return t?(n.then(e,t),Promise.resolve()):n},t.createAnswer=function(e,t){const r=arguments.length>=2?arguments[2]:arguments[0],n=i.apply(this,[r]);return t?(n.then(e,t),Promise.resolve()):n};let a=function(e,t,r){const i=n.apply(this,[e]);return r?(i.then(t,r),Promise.resolve()):i};t.setLocalDescription=a,a=function(e,t,r){const i=s.apply(this,[e]);return r?(i.then(t,r),Promise.resolve()):i},t.setRemoteDescription=a,a=function(e,t,r){const i=o.apply(this,[e]);return r?(i.then(t,r),Promise.resolve()):i},t.addIceCandidate=a}function Hr(e){const t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){const e=t.mediaDevices,r=e.getUserMedia.bind(e);t.mediaDevices.getUserMedia=e=>r(Wr(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,r,i){t.mediaDevices.getUserMedia(e).then(r,i)}.bind(t))}function Wr(e){return e&&void 0!==e.video?Object.assign({},e,{video:vr(e.video)}):e}function Kr(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection;e.RTCPeerConnection=function(e,r){if(e&&e.iceServers){const t=[];for(let r=0;r<e.iceServers.length;r++){let i=e.iceServers[r];void 0===i.urls&&i.url?(mr("RTCIceServer.url","RTCIceServer.urls"),i=JSON.parse(JSON.stringify(i)),i.urls=i.url,delete i.url,t.push(i)):t.push(e.iceServers[r])}e.iceServers=t}return new t(e,r)},e.RTCPeerConnection.prototype=t.prototype,"generateCertificate"in t&&Object.defineProperty(e.RTCPeerConnection,"generateCertificate",{get:()=>t.generateCertificate})}function Jr(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function Xr(e){const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(e){if(e){void 0!==e.offerToReceiveAudio&&(e.offerToReceiveAudio=!!e.offerToReceiveAudio);const t=this.getTransceivers().find((e=>"audio"===e.receiver.track.kind));!1===e.offerToReceiveAudio&&t?"sendrecv"===t.direction?t.setDirection?t.setDirection("sendonly"):t.direction="sendonly":"recvonly"===t.direction&&(t.setDirection?t.setDirection("inactive"):t.direction="inactive"):!0!==e.offerToReceiveAudio||t||this.addTransceiver("audio",{direction:"recvonly"}),void 0!==e.offerToReceiveVideo&&(e.offerToReceiveVideo=!!e.offerToReceiveVideo);const r=this.getTransceivers().find((e=>"video"===e.receiver.track.kind));!1===e.offerToReceiveVideo&&r?"sendrecv"===r.direction?r.setDirection?r.setDirection("sendonly"):r.direction="sendonly":"recvonly"===r.direction&&(r.setDirection?r.setDirection("inactive"):r.direction="inactive"):!0!==e.offerToReceiveVideo||r||this.addTransceiver("video",{direction:"recvonly"})}return t.apply(this,arguments)}}function Qr(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var Zr=Object.freeze({__proto__:null,shimAudioContext:Qr,shimCallbacksAPI:qr,shimConstraints:Wr,shimCreateOfferLegacy:Xr,shimGetUserMedia:Hr,shimLocalStreamsAPI:$r,shimRTCIceServerUrls:Kr,shimRemoteStreamsAPI:Gr,shimTrackEventTransceiver:Jr}),Yr={exports:{}};!function(e){const t={generateIdentifier:function(){return Math.random().toString(36).substring(2,12)}};t.localCName=t.generateIdentifier(),t.splitLines=function(e){return e.trim().split("\n").map((e=>e.trim()))},t.splitSections=function(e){return e.split("\nm=").map(((e,t)=>(t>0?"m="+e:e).trim()+"\r\n"))},t.getDescription=function(e){const r=t.splitSections(e);return r&&r[0]},t.getMediaSections=function(e){const r=t.splitSections(e);return r.shift(),r},t.matchPrefix=function(e,r){return t.splitLines(e).filter((e=>0===e.indexOf(r)))},t.parseCandidate=function(e){let t;t=0===e.indexOf("a=candidate:")?e.substring(12).split(" "):e.substring(10).split(" ");const r={foundation:t[0],component:{1:"rtp",2:"rtcp"}[t[1]]||t[1],protocol:t[2].toLowerCase(),priority:parseInt(t[3],10),ip:t[4],address:t[4],port:parseInt(t[5],10),type:t[7]};for(let e=8;e<t.length;e+=2)switch(t[e]){case"raddr":r.relatedAddress=t[e+1];break;case"rport":r.relatedPort=parseInt(t[e+1],10);break;case"tcptype":r.tcpType=t[e+1];break;case"ufrag":r.ufrag=t[e+1],r.usernameFragment=t[e+1];break;default:void 0===r[t[e]]&&(r[t[e]]=t[e+1])}return r},t.writeCandidate=function(e){const t=[];t.push(e.foundation);const r=e.component;"rtp"===r?t.push(1):"rtcp"===r?t.push(2):t.push(r),t.push(e.protocol.toUpperCase()),t.push(e.priority),t.push(e.address||e.ip),t.push(e.port);const i=e.type;return t.push("typ"),t.push(i),"host"!==i&&e.relatedAddress&&e.relatedPort&&(t.push("raddr"),t.push(e.relatedAddress),t.push("rport"),t.push(e.relatedPort)),e.tcpType&&"tcp"===e.protocol.toLowerCase()&&(t.push("tcptype"),t.push(e.tcpType)),(e.usernameFragment||e.ufrag)&&(t.push("ufrag"),t.push(e.usernameFragment||e.ufrag)),"candidate:"+t.join(" ")},t.parseIceOptions=function(e){return e.substring(14).split(" ")},t.parseRtpMap=function(e){let t=e.substring(9).split(" ");const r={payloadType:parseInt(t.shift(),10)};return t=t[0].split("/"),r.name=t[0],r.clockRate=parseInt(t[1],10),r.channels=3===t.length?parseInt(t[2],10):1,r.numChannels=r.channels,r},t.writeRtpMap=function(e){let t=e.payloadType;void 0!==e.preferredPayloadType&&(t=e.preferredPayloadType);const r=e.channels||e.numChannels||1;return"a=rtpmap:"+t+" "+e.name+"/"+e.clockRate+(1!==r?"/"+r:"")+"\r\n"},t.parseExtmap=function(e){const t=e.substring(9).split(" ");return{id:parseInt(t[0],10),direction:t[0].indexOf("/")>0?t[0].split("/")[1]:"sendrecv",uri:t[1],attributes:t.slice(2).join(" ")}},t.writeExtmap=function(e){return"a=extmap:"+(e.id||e.preferredId)+(e.direction&&"sendrecv"!==e.direction?"/"+e.direction:"")+" "+e.uri+(e.attributes?" "+e.attributes:"")+"\r\n"},t.parseFmtp=function(e){const t={};let r;const i=e.substring(e.indexOf(" ")+1).split(";");for(let e=0;e<i.length;e++)r=i[e].trim().split("="),t[r[0].trim()]=r[1];return t},t.writeFmtp=function(e){let t="",r=e.payloadType;if(void 0!==e.preferredPayloadType&&(r=e.preferredPayloadType),e.parameters&&Object.keys(e.parameters).length){const i=[];Object.keys(e.parameters).forEach((t=>{void 0!==e.parameters[t]?i.push(t+"="+e.parameters[t]):i.push(t)})),t+="a=fmtp:"+r+" "+i.join(";")+"\r\n"}return t},t.parseRtcpFb=function(e){const t=e.substring(e.indexOf(" ")+1).split(" ");return{type:t.shift(),parameter:t.join(" ")}},t.writeRtcpFb=function(e){let t="",r=e.payloadType;return void 0!==e.preferredPayloadType&&(r=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach((e=>{t+="a=rtcp-fb:"+r+" "+e.type+(e.parameter&&e.parameter.length?" "+e.parameter:"")+"\r\n"})),t},t.parseSsrcMedia=function(e){const t=e.indexOf(" "),r={ssrc:parseInt(e.substring(7,t),10)},i=e.indexOf(":",t);return i>-1?(r.attribute=e.substring(t+1,i),r.value=e.substring(i+1)):r.attribute=e.substring(t+1),r},t.parseSsrcGroup=function(e){const t=e.substring(13).split(" ");return{semantics:t.shift(),ssrcs:t.map((e=>parseInt(e,10)))}},t.getMid=function(e){const r=t.matchPrefix(e,"a=mid:")[0];if(r)return r.substring(6)},t.parseFingerprint=function(e){const t=e.substring(14).split(" ");return{algorithm:t[0].toLowerCase(),value:t[1].toUpperCase()}},t.getDtlsParameters=function(e,r){return{role:"auto",fingerprints:t.matchPrefix(e+r,"a=fingerprint:").map(t.parseFingerprint)}},t.writeDtlsParameters=function(e,t){let r="a=setup:"+t+"\r\n";return e.fingerprints.forEach((e=>{r+="a=fingerprint:"+e.algorithm+" "+e.value+"\r\n"})),r},t.parseCryptoLine=function(e){const t=e.substring(9).split(" ");return{tag:parseInt(t[0],10),cryptoSuite:t[1],keyParams:t[2],sessionParams:t.slice(3)}},t.writeCryptoLine=function(e){return"a=crypto:"+e.tag+" "+e.cryptoSuite+" "+("object"==typeof e.keyParams?t.writeCryptoKeyParams(e.keyParams):e.keyParams)+(e.sessionParams?" "+e.sessionParams.join(" "):"")+"\r\n"},t.parseCryptoKeyParams=function(e){if(0!==e.indexOf("inline:"))return null;const t=e.substring(7).split("|");return{keyMethod:"inline",keySalt:t[0],lifeTime:t[1],mkiValue:t[2]?t[2].split(":")[0]:void 0,mkiLength:t[2]?t[2].split(":")[1]:void 0}},t.writeCryptoKeyParams=function(e){return e.keyMethod+":"+e.keySalt+(e.lifeTime?"|"+e.lifeTime:"")+(e.mkiValue&&e.mkiLength?"|"+e.mkiValue+":"+e.mkiLength:"")},t.getCryptoParameters=function(e,r){return t.matchPrefix(e+r,"a=crypto:").map(t.parseCryptoLine)},t.getIceParameters=function(e,r){const i=t.matchPrefix(e+r,"a=ice-ufrag:")[0],n=t.matchPrefix(e+r,"a=ice-pwd:")[0];return i&&n?{usernameFragment:i.substring(12),password:n.substring(10)}:null},t.writeIceParameters=function(e){let t="a=ice-ufrag:"+e.usernameFragment+"\r\na=ice-pwd:"+e.password+"\r\n";return e.iceLite&&(t+="a=ice-lite\r\n"),t},t.parseRtpParameters=function(e){const r={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},i=t.splitLines(e)[0].split(" ");r.profile=i[2];for(let n=3;n<i.length;n++){const s=i[n],o=t.matchPrefix(e,"a=rtpmap:"+s+" ")[0];if(o){const i=t.parseRtpMap(o),n=t.matchPrefix(e,"a=fmtp:"+s+" ");switch(i.parameters=n.length?t.parseFmtp(n[0]):{},i.rtcpFeedback=t.matchPrefix(e,"a=rtcp-fb:"+s+" ").map(t.parseRtcpFb),r.codecs.push(i),i.name.toUpperCase()){case"RED":case"ULPFEC":r.fecMechanisms.push(i.name.toUpperCase())}}}t.matchPrefix(e,"a=extmap:").forEach((e=>{r.headerExtensions.push(t.parseExtmap(e))}));const n=t.matchPrefix(e,"a=rtcp-fb:* ").map(t.parseRtcpFb);return r.codecs.forEach((e=>{n.forEach((t=>{e.rtcpFeedback.find((e=>e.type===t.type&&e.parameter===t.parameter))||e.rtcpFeedback.push(t)}))})),r},t.writeRtpDescription=function(e,r){let i="";i+="m="+e+" ",i+=r.codecs.length>0?"9":"0",i+=" "+(r.profile||"UDP/TLS/RTP/SAVPF")+" ",i+=r.codecs.map((e=>void 0!==e.preferredPayloadType?e.preferredPayloadType:e.payloadType)).join(" ")+"\r\n",i+="c=IN IP4 0.0.0.0\r\n",i+="a=rtcp:9 IN IP4 0.0.0.0\r\n",r.codecs.forEach((e=>{i+=t.writeRtpMap(e),i+=t.writeFmtp(e),i+=t.writeRtcpFb(e)}));let n=0;return r.codecs.forEach((e=>{e.maxptime>n&&(n=e.maxptime)})),n>0&&(i+="a=maxptime:"+n+"\r\n"),r.headerExtensions&&r.headerExtensions.forEach((e=>{i+=t.writeExtmap(e)})),i},t.parseRtpEncodingParameters=function(e){const r=[],i=t.parseRtpParameters(e),n=-1!==i.fecMechanisms.indexOf("RED"),s=-1!==i.fecMechanisms.indexOf("ULPFEC"),o=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute)),a=o.length>0&&o[0].ssrc;let c;const d=t.matchPrefix(e,"a=ssrc-group:FID").map((e=>e.substring(17).split(" ").map((e=>parseInt(e,10)))));d.length>0&&d[0].length>1&&d[0][0]===a&&(c=d[0][1]),i.codecs.forEach((e=>{if("RTX"===e.name.toUpperCase()&&e.parameters.apt){let t={ssrc:a,codecPayloadType:parseInt(e.parameters.apt,10)};a&&c&&(t.rtx={ssrc:c}),r.push(t),n&&(t=JSON.parse(JSON.stringify(t)),t.fec={ssrc:a,mechanism:s?"red+ulpfec":"red"},r.push(t))}})),0===r.length&&a&&r.push({ssrc:a});let l=t.matchPrefix(e,"b=");return l.length&&(l=0===l[0].indexOf("b=TIAS:")?parseInt(l[0].substring(7),10):0===l[0].indexOf("b=AS:")?1e3*parseInt(l[0].substring(5),10)*.95-16e3:void 0,r.forEach((e=>{e.maxBitrate=l}))),r},t.parseRtcpParameters=function(e){const r={},i=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute))[0];i&&(r.cname=i.value,r.ssrc=i.ssrc);const n=t.matchPrefix(e,"a=rtcp-rsize");r.reducedSize=n.length>0,r.compound=0===n.length;const s=t.matchPrefix(e,"a=rtcp-mux");return r.mux=s.length>0,r},t.writeRtcpParameters=function(e){let t="";return e.reducedSize&&(t+="a=rtcp-rsize\r\n"),e.mux&&(t+="a=rtcp-mux\r\n"),void 0!==e.ssrc&&e.cname&&(t+="a=ssrc:"+e.ssrc+" cname:"+e.cname+"\r\n"),t},t.parseMsid=function(e){let r;const i=t.matchPrefix(e,"a=msid:");if(1===i.length)return r=i[0].substring(7).split(" "),{stream:r[0],track:r[1]};const n=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"msid"===e.attribute));return n.length>0?(r=n[0].value.split(" "),{stream:r[0],track:r[1]}):void 0},t.parseSctpDescription=function(e){const r=t.parseMLine(e),i=t.matchPrefix(e,"a=max-message-size:");let n;i.length>0&&(n=parseInt(i[0].substring(19),10)),isNaN(n)&&(n=65536);const s=t.matchPrefix(e,"a=sctp-port:");if(s.length>0)return{port:parseInt(s[0].substring(12),10),protocol:r.fmt,maxMessageSize:n};const o=t.matchPrefix(e,"a=sctpmap:");if(o.length>0){const e=o[0].substring(10).split(" ");return{port:parseInt(e[0],10),protocol:e[1],maxMessageSize:n}}},t.writeSctpDescription=function(e,t){let r=[];return r="DTLS/SCTP"!==e.protocol?["m="+e.kind+" 9 "+e.protocol+" "+t.protocol+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctp-port:"+t.port+"\r\n"]:["m="+e.kind+" 9 "+e.protocol+" "+t.port+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctpmap:"+t.port+" "+t.protocol+" 65535\r\n"],void 0!==t.maxMessageSize&&r.push("a=max-message-size:"+t.maxMessageSize+"\r\n"),r.join("")},t.generateSessionId=function(){return Math.random().toString().substr(2,22)},t.writeSessionBoilerplate=function(e,r,i){let n;const s=void 0!==r?r:2;n=e||t.generateSessionId();return"v=0\r\no="+(i||"thisisadapterortc")+" "+n+" "+s+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},t.getDirection=function(e,r){const i=t.splitLines(e);for(let e=0;e<i.length;e++)switch(i[e]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return i[e].substring(2)}return r?t.getDirection(r):"sendrecv"},t.getKind=function(e){return t.splitLines(e)[0].split(" ")[0].substring(2)},t.isRejected=function(e){return"0"===e.split(" ",2)[1]},t.parseMLine=function(e){const r=t.splitLines(e)[0].substring(2).split(" ");return{kind:r[0],port:parseInt(r[1],10),protocol:r[2],fmt:r.slice(3).join(" ")}},t.parseOLine=function(e){const r=t.matchPrefix(e,"o=")[0].substring(2).split(" ");return{username:r[0],sessionId:r[1],sessionVersion:parseInt(r[2],10),netType:r[3],addressType:r[4],address:r[5]}},t.isValidSDP=function(e){if("string"!=typeof e||0===e.length)return!1;const r=t.splitLines(e);for(let e=0;e<r.length;e++)if(r[e].length<2||"="!==r[e].charAt(1))return!1;return!0},e.exports=t}(Yr);var ei=Yr.exports,ti=c(ei),ri=n({__proto__:null,default:ti},[ei]);function ii(e){if(!e.RTCIceCandidate||e.RTCIceCandidate&&"foundation"in e.RTCIceCandidate.prototype)return;const t=e.RTCIceCandidate;e.RTCIceCandidate=function(e){if("object"==typeof e&&e.candidate&&0===e.candidate.indexOf("a=")&&((e=JSON.parse(JSON.stringify(e))).candidate=e.candidate.substring(2)),e.candidate&&e.candidate.length){const r=new t(e),i=ti.parseCandidate(e.candidate);for(const e in i)e in r||Object.defineProperty(r,e,{value:i[e]});return r.toJSON=function(){return{candidate:r.candidate,sdpMid:r.sdpMid,sdpMLineIndex:r.sdpMLineIndex,usernameFragment:r.usernameFragment}},r}return new t(e)},e.RTCIceCandidate.prototype=t.prototype,ur(e,"icecandidate",(t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t)))}function ni(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||ur(e,"icecandidate",(e=>{if(e.candidate){const t=ti.parseCandidate(e.candidate.candidate);"relay"===t.type&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e}))}function si(e,t){if(!e.RTCPeerConnection)return;"sctp"in e.RTCPeerConnection.prototype||Object.defineProperty(e.RTCPeerConnection.prototype,"sctp",{get(){return void 0===this._sctp?null:this._sctp}});const r=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,"chrome"===t.browser&&t.version>=76){const{sdpSemantics:e}=this.getConfiguration();"plan-b"===e&&Object.defineProperty(this,"sctp",{get(){return void 0===this._sctp?null:this._sctp},enumerable:!0,configurable:!0})}if(function(e){if(!e||!e.sdp)return!1;const t=ti.splitSections(e.sdp);return t.shift(),t.some((e=>{const t=ti.parseMLine(e);return t&&"application"===t.kind&&-1!==t.protocol.indexOf("SCTP")}))}(arguments[0])){const e=function(e){const t=e.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(null===t||t.length<2)return-1;const r=parseInt(t[1],10);return r!=r?-1:r}(arguments[0]),r=function(e){let r=65536;return"firefox"===t.browser&&(r=t.version<57?-1===e?16384:2147483637:t.version<60?57===t.version?65535:65536:2147483637),r}(e),i=function(e,r){let i=65536;"firefox"===t.browser&&57===t.version&&(i=65535);const n=ti.matchPrefix(e.sdp,"a=max-message-size:");return n.length>0?i=parseInt(n[0].substring(19),10):"firefox"===t.browser&&-1!==r&&(i=2147483637),i}(arguments[0],e);let n;n=0===r&&0===i?Number.POSITIVE_INFINITY:0===r||0===i?Math.max(r,i):Math.min(r,i);const s={};Object.defineProperty(s,"maxMessageSize",{get:()=>n}),this._sctp=s}return r.apply(this,arguments)}}function oi(e){if(!e.RTCPeerConnection||!("createDataChannel"in e.RTCPeerConnection.prototype))return;function t(e,t){const r=e.send;e.send=function(){const i=arguments[0],n=i.length||i.size||i.byteLength;if("open"===e.readyState&&t.sctp&&n>t.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+t.sctp.maxMessageSize+" bytes)");return r.apply(e,arguments)}}const r=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){const e=r.apply(this,arguments);return t(e,this),e},ur(e,"datachannel",(e=>(t(e.channel,e.target),e)))}function ai(e){if(!e.RTCPeerConnection||"connectionState"in e.RTCPeerConnection.prototype)return;const t=e.RTCPeerConnection.prototype;Object.defineProperty(t,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(t,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(e){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),e&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=e)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach((e=>{const r=t[e];t[e]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=e=>{const t=e.target;if(t._lastConnectionState!==t.connectionState){t._lastConnectionState=t.connectionState;const r=new Event("connectionstatechange",e);t.dispatchEvent(r)}return e},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),r.apply(this,arguments)}}))}function ci(e,t){if(!e.RTCPeerConnection)return;if("chrome"===t.browser&&t.version>=71)return;if("safari"===t.browser&&t.version>=605)return;const r=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(t){if(t&&t.sdp&&-1!==t.sdp.indexOf("\na=extmap-allow-mixed")){const r=t.sdp.split("\n").filter((e=>"a=extmap-allow-mixed"!==e.trim())).join("\n");e.RTCSessionDescription&&t instanceof e.RTCSessionDescription?arguments[0]=new e.RTCSessionDescription({type:t.type,sdp:r}):t.sdp=r}return r.apply(this,arguments)}}function di(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const r=e.RTCPeerConnection.prototype.addIceCandidate;r&&0!==r.length&&(e.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?("chrome"===t.browser&&t.version<78||"firefox"===t.browser&&t.version<68||"safari"===t.browser)&&arguments[0]&&""===arguments[0].candidate?Promise.resolve():r.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function li(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const r=e.RTCPeerConnection.prototype.setLocalDescription;r&&0!==r.length&&(e.RTCPeerConnection.prototype.setLocalDescription=function(){let e=arguments[0]||{};if("object"!=typeof e||e.type&&e.sdp)return r.apply(this,arguments);if(e={type:e.type,sdp:e.sdp},!e.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":e.type="offer";break;default:e.type="answer"}if(e.sdp||"offer"!==e.type&&"answer"!==e.type)return r.apply(this,[e]);return("offer"===e.type?this.createOffer:this.createAnswer).apply(this).then((e=>r.apply(this,[e])))})}var ui=Object.freeze({__proto__:null,removeExtmapAllowMixed:ci,shimAddIceCandidateNullOrEmpty:di,shimConnectionState:ai,shimMaxMessageSize:si,shimParameterlessSetLocalDescription:li,shimRTCIceCandidate:ii,shimRTCIceCandidateRelayProtocol:ni,shimSendThrowTypeError:oi});const pi=function({window:e}={},t={shimChrome:!0,shimFirefox:!0,shimSafari:!0}){const r=fr,i=function(e){const t={browser:null,version:null};if(void 0===e||!e.navigator||!e.navigator.userAgent)return t.browser="Not a browser.",t;const{navigator:r}=e;if(r.userAgentData&&r.userAgentData.brands){const e=r.userAgentData.brands.find((e=>"Chromium"===e.brand));if(e)return{browser:"chrome",version:parseInt(e.version,10)}}if(r.mozGetUserMedia)t.browser="firefox",t.version=lr(r.userAgent,/Firefox\/(\d+)\./,1);else if(r.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection)t.browser="chrome",t.version=lr(r.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else{if(!e.RTCPeerConnection||!r.userAgent.match(/AppleWebKit\/(\d+)\./))return t.browser="Not a supported browser.",t;t.browser="safari",t.version=lr(r.userAgent,/AppleWebKit\/(\d+)\./,1),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype}return t}(e),n={browserDetails:i,commonShim:ui,extractVersion:lr,disableLog:pr,disableWarnings:hr,sdp:ri};switch(i.browser){case"chrome":if(!Dr||!Er||!t.shimChrome)return r("Chrome shim is not included in this adapter release."),n;if(null===i.version)return r("Chrome shim can not determine version, not shimming."),n;r("adapter.js shimming chrome."),n.browserShim=Dr,di(e,i),li(e),_r(e,i),Sr(e),Er(e,i),Cr(e),Pr(e,i),Rr(e),kr(e),Or(e,i),ii(e),ni(e),ai(e),si(e,i),oi(e),ci(e,i);break;case"firefox":if(!Ur||!Mr||!t.shimFirefox)return r("Firefox shim is not included in this adapter release."),n;r("adapter.js shimming firefox."),n.browserShim=Ur,di(e,i),li(e),Ir(e,i),Mr(e,i),xr(e),Ar(e),Lr(e),jr(e),Nr(e),Br(e),Fr(e),zr(e),Vr(e),ii(e),ai(e),si(e,i),oi(e);break;case"safari":if(!Zr||!t.shimSafari)return r("Safari shim is not included in this adapter release."),n;r("adapter.js shimming safari."),n.browserShim=Zr,di(e,i),li(e),Kr(e),Xr(e),qr(e),$r(e),Gr(e),Jr(e),Hr(e),Qr(e),ii(e),ni(e),si(e,i),oi(e),ci(e,i);break;default:r("Unsupported browser!")}return n}({window:"undefined"==typeof window?void 0:window});function hi(e){return{id:e.id,tracks:e.getTracks().map((function(e){return{id:e.id,kind:e.kind,label:e.label,enabled:e.enabled,muted:e.muted,readyState:e.readyState}}))}}var fi=function(e,t,r){var i=0,n=!!window.mozRTCPeerConnection,s=!!window.RTCIceGatherer,o={};if(r.forEach((function(r){if(window[r+"RTCPeerConnection"]&&("webkit"!==r||!s)){var a=window[r+"RTCPeerConnection"],c=function(r,c){var d=new a(r,c),l="PC_"+i++;d.__rtcStatsId=l,r||(r={nullConfig:!0}),((r=JSON.parse(JSON.stringify(r)))&&r.iceServers||[]).forEach((function(e){delete e.credential})),r.browserType=n?"moz":s?"edge":"webkit",e("create",l,r),c&&e("constraints",l,c),d.addEventListener("icecandidate",(function(t){e("onicecandidate",l,t.candidate)})),d.addEventListener("addstream",(function(t){e("onaddstream",l,t.stream.id+" "+t.stream.getTracks().map((function(e){return e.kind+":"+e.id})))})),d.addEventListener("track",(function(t){e("ontrack",l,t.track.kind+":"+t.track.id+" "+t.streams.map((function(e){return"stream:"+e.id})))})),d.addEventListener("removestream",(function(t){e("onremovestream",l,t.stream.id+" "+t.stream.getTracks().map((function(e){return e.kind+":"+e.id})))})),d.addEventListener("signalingstatechange",(function(){e("onsignalingstatechange",l,d.signalingState)})),d.addEventListener("iceconnectionstatechange",(function(){e("oniceconnectionstatechange",l,d.iceConnectionState)})),d.addEventListener("icegatheringstatechange",(function(){e("onicegatheringstatechange",l,d.iceGatheringState)})),d.addEventListener("connectionstatechange",(function(){e("onconnectionstatechange",l,d.connectionState)})),d.addEventListener("negotiationneeded",(function(){e("onnegotiationneeded",l,void 0)})),d.addEventListener("datachannel",(function(t){e("ondatachannel",l,[t.channel.id,t.channel.label])}));var u=function(){d.getStats(null).then((function(t){var r=function(e){if(!e.entries)return e;var t={};return e.forEach((function(e,r){t[r]=e})),t}(t),i=JSON.parse(JSON.stringify(r));e("getstats",l,function(e,t){t=JSON.parse(JSON.stringify(t)),Object.keys(t).forEach((function(r){var i=t[r];delete i.id,e[r]&&Object.keys(i).forEach((function(n){i[n]===e[r][n]&&delete t[r][n],(0===Object.keys(i).length||1===Object.keys(i).length&&i.timestamp)&&delete t[r]}))}));var r=-1/0;return Object.keys(t).forEach((function(e){var i=t[e];i.timestamp>r&&(r=i.timestamp)})),Object.keys(t).forEach((function(e){var i=t[e];i.timestamp===r&&(i.timestamp=0)})),t.timestamp=r,t}(o[l]||{},r)),o[l]=i}))};if(!s&&t)var p=window.setInterval((function(){"closed"!==d.signalingState?u():window.clearInterval(p)}),t);return s||d.addEventListener("connectionstatechange",(function(){"connected"!==d.connectionState&&"failed"!==d.connectionState||u()})),d};["createDataChannel","close"].forEach((function(t){var r=a.prototype[t];r&&(a.prototype[t]=function(){return e(t,this.__rtcStatsId,arguments),r.apply(this,arguments)})})),["addStream","removeStream"].forEach((function(t){var r=a.prototype[t];r&&(a.prototype[t]=function(){var i=arguments[0],n=i.getTracks().map((function(e){return e.kind+":"+e.id})).join(",");return e(t,this.__rtcStatsId,i.id+" "+n),r.apply(this,arguments)})})),["addTrack"].forEach((function(t){var r=a.prototype[t];r&&(a.prototype[t]=function(){var i=arguments[0],n=[].slice.call(arguments,1);return e(t,this.__rtcStatsId,i.kind+":"+i.id+" "+(n.map((function(e){return"stream:"+e.id})).join(";")||"-")),r.apply(this,arguments)})})),["removeTrack"].forEach((function(t){var r=a.prototype[t];r&&(a.prototype[t]=function(){var i=arguments[0].track;return e(t,this.__rtcStatsId,i?i.kind+":"+i.id:"null"),r.apply(this,arguments)})})),["createOffer","createAnswer"].forEach((function(t){var r=a.prototype[t];r&&(a.prototype[t]=function(){var i,n=this.__rtcStatsId,s=arguments;return 1===arguments.length&&"object"==typeof arguments[0]?i=arguments[0]:3===arguments.length&&"object"==typeof arguments[2]&&(i=arguments[2]),e(t,this.__rtcStatsId,i),r.apply(this,i?[i]:void 0).then((function(r){if(e(t+"OnSuccess",n,r),!(s.length>0&&"function"==typeof s[0]))return r;s[0].apply(null,[r])}),(function(r){if(e(t+"OnFailure",n,r.toString()),!(s.length>1&&"function"==typeof s[1]))throw r;s[1].apply(null,[r])}))})})),["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){var r=a.prototype[t];r&&(a.prototype[t]=function(){var i=this.__rtcStatsId,n=arguments;return e(t,this.__rtcStatsId,n[0]),r.apply(this,[n[0]]).then((function(){e(t+"OnSuccess",i,void 0),n.length>=2&&"function"==typeof n[1]&&n[1].apply(null,[])}),(function(r){if(e(t+"OnFailure",i,r.toString()),!(n.length>=3&&"function"==typeof n[2]))throw r;n[2].apply(null,[r])}))})})),a.generateCertificate&&Object.defineProperty(c,"generateCertificate",{get:function(){return arguments.length?a.generateCertificate.apply(null,arguments):a.generateCertificate}}),window[r+"RTCPeerConnection"]=c,window[r+"RTCPeerConnection"].prototype=a.prototype}})),r.forEach((function(t){var r=t+(t.length?"GetUserMedia":"getUserMedia");if(navigator[r]){var i=navigator[r].bind(navigator);navigator[r]=function(){e("getUserMedia",null,arguments[0]);var t=arguments[1],r=arguments[2];i(arguments[0],(function(r){e("getUserMediaOnSuccess",null,hi(r)),t&&t(r)}),(function(t){e("getUserMediaOnFailure",null,t.name),r&&r(t)}))}.bind(navigator)}})),navigator.mediaDevices&&navigator.mediaDevices.getUserMedia){var a=navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);navigator.mediaDevices.getUserMedia=function(){return e("navigator.mediaDevices.getUserMedia",null,arguments[0]),a.apply(navigator.mediaDevices,arguments).then((function(t){return e("navigator.mediaDevices.getUserMediaOnSuccess",null,hi(t)),t}),(function(t){return e("navigator.mediaDevices.getUserMediaOnFailure",null,t.name),Promise.reject(t)}))}.bind(navigator.mediaDevices)}if(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia){var c=navigator.mediaDevices.getDisplayMedia.bind(navigator.mediaDevices);navigator.mediaDevices.getDisplayMedia=function(){return e("navigator.mediaDevices.getDisplayMedia",null,arguments[0]),c.apply(navigator.mediaDevices,arguments).then((function(t){return e("navigator.mediaDevices.getDisplayMediaOnSuccess",null,hi(t)),t}),(function(t){return e("navigator.mediaDevices.getDisplayMediaOnFailure",null,t.name),Promise.reject(t)}))}.bind(navigator.mediaDevices)}return{resetDelta(){o={}}}},mi=c(fi);let gi;const vi=new Uint8Array(16);function bi(){if(!gi&&(gi="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!gi))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return gi(vi)}const yi=[];for(let FO=0;FO<256;++FO)yi.push((FO+256).toString(16).slice(1));var wi={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function _i(e,t,r){if(wi.randomUUID&&!t&&!e)return wi.randomUUID();const i=(e=e||{}).random||(e.rng||bi)();if(i[6]=15&i[6]|64,i[8]=63&i[8]|128,t){r=r||0;for(let e=0;e<16;++e)t[r+e]=i[e];return t}return function(e,t=0){return yi[e[t+0]]+yi[e[t+1]]+yi[e[t+2]]+yi[e[t+3]]+"-"+yi[e[t+4]]+yi[e[t+5]]+"-"+yi[e[t+6]]+yi[e[t+7]]+"-"+yi[e[t+8]]+yi[e[t+9]]+"-"+yi[e[t+10]]+yi[e[t+11]]+yi[e[t+12]]+yi[e[t+13]]+yi[e[t+14]]+yi[e[t+15]]}(i)}var Si={},Ci={exports:{}},Ri=Ci.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(e){return e.encoding?"rtpmap:%d %s/%s/%s":e.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(e){return null!=e.address?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(e){return null!=e.subtype?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(e){return"extmap:%d"+(e.direction?"/%s":"%v")+(e["encrypt-uri"]?" %s":"%v")+" %s"+(e.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(e){return null!=e.sessionConfig?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(e){var t="candidate:%s %d %s %d %s %d typ %s";return t+=null!=e.raddr?" raddr %s rport %d":"%v%v",t+=null!=e.tcptype?" tcptype %s":"%v",null!=e.generation&&(t+=" generation %d"),t+=null!=e["network-id"]?" network-id %d":"%v",t+=null!=e["network-cost"]?" network-cost %d":"%v"}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(e){var t="ssrc:%d";return null!=e.attribute&&(t+=" %s",null!=e.value&&(t+=":%s")),t}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(e){return null!=e.maxMessageSize?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(e){return e.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(e){return"imageattr:%s %s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(e){return"simulcast:%s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(e){return"ts-refclk:%s"+(null!=e.clksrcExt?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(e){var t="mediaclk:";return t+=null!=e.id?"id=%s %s":"%v%s",t+=null!=e.mediaClockValue?"=%s":"",t+=null!=e.rateNumerator?" rate=%s":"",t+=null!=e.rateDenominator?"/%s":""}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};Object.keys(Ri).forEach((function(e){Ri[e].forEach((function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")}))}));var ki=Ci.exports;!function(e){var t=function(e){return String(Number(e))===e?Number(e):e},r=function(e,r,i){var n=e.name&&e.names;e.push&&!r[e.push]?r[e.push]=[]:n&&!r[e.name]&&(r[e.name]={});var s=e.push?{}:n?r[e.name]:r;!function(e,r,i,n){if(n&&!i)r[n]=t(e[1]);else for(var s=0;s<i.length;s+=1)null!=e[s+1]&&(r[i[s]]=t(e[s+1]))}(i.match(e.reg),s,e.names,e.name),e.push&&r[e.push].push(s)},i=ki,n=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},s=[],o=t;return e.split(/(\r\n|\r|\n)/).filter(n).forEach((function(e){var t=e[0],n=e.slice(2);"m"===t&&(s.push({rtp:[],fmtp:[]}),o=s[s.length-1]);for(var a=0;a<(i[t]||[]).length;a+=1){var c=i[t][a];if(c.reg.test(n))return r(c,o,n)}})),t.media=s,t};var s=function(e,r){var i=r.split(/=(.+)/,2);return 2===i.length?e[i[0]]=t(i[1]):1===i.length&&r.length>1&&(e[i[0]]=void 0),e};e.parseParams=function(e){return e.split(/;\s?/).reduce(s,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(e){return e.toString().split(" ").map(Number)},e.parseRemoteCandidates=function(e){for(var r=[],i=e.split(" ").map(t),n=0;n<i.length;n+=3)r.push({component:i[n],ip:i[n+1],port:i[n+2]});return r},e.parseImageAttributes=function(e){return e.split(" ").map((function(e){return e.substring(1,e.length-1).split(",").reduce(s,{})}))},e.parseSimulcastStreamList=function(e){return e.split(";").map((function(e){return e.split(",").map((function(e){var r,i=!1;return"~"!==e[0]?r=t(e):(r=t(e.substring(1,e.length)),i=!0),{scid:r,paused:i}}))}))}}(Si);var Ti=ki,Pi=/%[sdv%]/g,Ei=function(e){var t=1,r=arguments,i=r.length;return e.replace(Pi,(function(e){if(t>=i)return e;var n=r[t];switch(t+=1,e){case"%%":return"%";case"%s":return String(n);case"%d":return Number(n);case"%v":return""}}))},Oi=function(e,t,r){var i=[e+"="+(t.format instanceof Function?t.format(t.push?r:r[t.name]):t.format)];if(t.names)for(var n=0;n<t.names.length;n+=1){var s=t.names[n];t.name?i.push(r[t.name][s]):i.push(r[t.names[n]])}else i.push(r[t.name]);return Ei.apply(null,i)},Di=["v","o","s","i","u","e","p","c","b","t","r","z","a"],Ii=["i","c","b","a"],xi=Si,Mi=function(e,t){t=t||{},null==e.version&&(e.version=0),null==e.name&&(e.name=" "),e.media.forEach((function(e){null==e.payloads&&(e.payloads="")}));var r=t.outerOrder||Di,i=t.innerOrder||Ii,n=[];return r.forEach((function(t){Ti[t].forEach((function(r){r.name in e&&null!=e[r.name]?n.push(Oi(t,r,e)):r.push in e&&null!=e[r.push]&&e[r.push].forEach((function(e){n.push(Oi(t,r,e))}))}))})),e.media.forEach((function(e){n.push(Oi("m",Ti.m[0],e)),i.forEach((function(t){Ti[t].forEach((function(r){r.name in e&&null!=e[r.name]?n.push(Oi(t,r,e)):r.push in e&&null!=e[r.push]&&e[r.push].forEach((function(e){n.push(Oi(t,r,e))}))}))}))})),n.join("\r\n")+"\r\n"},Li=Mi,ji=xi.parse,Ai={},Ni={},Bi={};Object.defineProperty(Bi,"__esModule",{value:!0}),Bi.isCorrect=Bi.isInSubnet=void 0,Bi.isInSubnet=function(e){return!(this.subnetMask<e.subnetMask)&&this.mask(e.subnetMask)===e.mask()},Bi.isCorrect=function(e){return function(){return this.addressMinusSuffix===this.correctForm()&&(this.subnetMask===e&&!this.parsedSubnet||this.parsedSubnet===String(this.subnetMask))}};var Fi={};Object.defineProperty(Fi,"__esModule",{value:!0}),Fi.RE_SUBNET_STRING=Fi.RE_ADDRESS=Fi.GROUPS=Fi.BITS=void 0,Fi.BITS=32,Fi.GROUPS=4,Fi.RE_ADDRESS=/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/g,Fi.RE_SUBNET_STRING=/\/\d{1,2}$/;var zi={};Object.defineProperty(zi,"__esModule",{value:!0}),zi.AddressError=void 0;class Vi extends Error{constructor(e,t){super(e),this.name="AddressError",null!==t&&(this.parseMessage=t)}}zi.AddressError=Vi;var Ui,$i={exports:{}};Ui=$i,function(){var e;function t(e,t,r){null!=e&&("number"==typeof e?this.fromNumber(e,t,r):null==t&&"string"!=typeof e?this.fromString(e,256):this.fromString(e,t))}function r(){return new t(null)}var i="undefined"!=typeof navigator;i&&"Microsoft Internet Explorer"==navigator.appName?(t.prototype.am=function(e,t,r,i,n,s){for(var o=32767&t,a=t>>15;--s>=0;){var c=32767&this[e],d=this[e++]>>15,l=a*c+d*o;n=((c=o*c+((32767&l)<<15)+r[i]+(1073741823&n))>>>30)+(l>>>15)+a*d+(n>>>30),r[i++]=1073741823&c}return n},e=30):i&&"Netscape"!=navigator.appName?(t.prototype.am=function(e,t,r,i,n,s){for(;--s>=0;){var o=t*this[e++]+r[i]+n;n=Math.floor(o/67108864),r[i++]=67108863&o}return n},e=26):(t.prototype.am=function(e,t,r,i,n,s){for(var o=16383&t,a=t>>14;--s>=0;){var c=16383&this[e],d=this[e++]>>14,l=a*c+d*o;n=((c=o*c+((16383&l)<<14)+r[i]+n)>>28)+(l>>14)+a*d,r[i++]=268435455&c}return n},e=28),t.prototype.DB=e,t.prototype.DM=(1<<e)-1,t.prototype.DV=1<<e,t.prototype.FV=Math.pow(2,52),t.prototype.F1=52-e,t.prototype.F2=2*e-52;var n,s,o="0123456789abcdefghijklmnopqrstuvwxyz",a=new Array;for(n="0".charCodeAt(0),s=0;s<=9;++s)a[n++]=s;for(n="a".charCodeAt(0),s=10;s<36;++s)a[n++]=s;for(n="A".charCodeAt(0),s=10;s<36;++s)a[n++]=s;function c(e){return o.charAt(e)}function d(e,t){var r=a[e.charCodeAt(t)];return null==r?-1:r}function l(e){var t=r();return t.fromInt(e),t}function u(e){var t,r=1;return 0!=(t=e>>>16)&&(e=t,r+=16),0!=(t=e>>8)&&(e=t,r+=8),0!=(t=e>>4)&&(e=t,r+=4),0!=(t=e>>2)&&(e=t,r+=2),0!=(t=e>>1)&&(e=t,r+=1),r}function p(e){this.m=e}function h(e){this.m=e,this.mp=e.invDigit(),this.mpl=32767&this.mp,this.mph=this.mp>>15,this.um=(1<<e.DB-15)-1,this.mt2=2*e.t}function f(e,t){return e&t}function m(e,t){return e|t}function g(e,t){return e^t}function v(e,t){return e&~t}function b(e){if(0==e)return-1;var t=0;return 0==(65535&e)&&(e>>=16,t+=16),0==(255&e)&&(e>>=8,t+=8),0==(15&e)&&(e>>=4,t+=4),0==(3&e)&&(e>>=2,t+=2),0==(1&e)&&++t,t}function y(e){for(var t=0;0!=e;)e&=e-1,++t;return t}function w(){}function _(e){return e}function S(e){this.r2=r(),this.q3=r(),t.ONE.dlShiftTo(2*e.t,this.r2),this.mu=this.r2.divide(e),this.m=e}p.prototype.convert=function(e){return e.s<0||e.compareTo(this.m)>=0?e.mod(this.m):e},p.prototype.revert=function(e){return e},p.prototype.reduce=function(e){e.divRemTo(this.m,null,e)},p.prototype.mulTo=function(e,t,r){e.multiplyTo(t,r),this.reduce(r)},p.prototype.sqrTo=function(e,t){e.squareTo(t),this.reduce(t)},h.prototype.convert=function(e){var i=r();return e.abs().dlShiftTo(this.m.t,i),i.divRemTo(this.m,null,i),e.s<0&&i.compareTo(t.ZERO)>0&&this.m.subTo(i,i),i},h.prototype.revert=function(e){var t=r();return e.copyTo(t),this.reduce(t),t},h.prototype.reduce=function(e){for(;e.t<=this.mt2;)e[e.t++]=0;for(var t=0;t<this.m.t;++t){var r=32767&e[t],i=r*this.mpl+((r*this.mph+(e[t]>>15)*this.mpl&this.um)<<15)&e.DM;for(e[r=t+this.m.t]+=this.m.am(0,i,e,t,0,this.m.t);e[r]>=e.DV;)e[r]-=e.DV,e[++r]++}e.clamp(),e.drShiftTo(this.m.t,e),e.compareTo(this.m)>=0&&e.subTo(this.m,e)},h.prototype.mulTo=function(e,t,r){e.multiplyTo(t,r),this.reduce(r)},h.prototype.sqrTo=function(e,t){e.squareTo(t),this.reduce(t)},t.prototype.copyTo=function(e){for(var t=this.t-1;t>=0;--t)e[t]=this[t];e.t=this.t,e.s=this.s},t.prototype.fromInt=function(e){this.t=1,this.s=e<0?-1:0,e>0?this[0]=e:e<-1?this[0]=e+this.DV:this.t=0},t.prototype.fromString=function(e,r){var i;if(16==r)i=4;else if(8==r)i=3;else if(256==r)i=8;else if(2==r)i=1;else if(32==r)i=5;else{if(4!=r)return void this.fromRadix(e,r);i=2}this.t=0,this.s=0;for(var n=e.length,s=!1,o=0;--n>=0;){var a=8==i?255&e[n]:d(e,n);a<0?"-"==e.charAt(n)&&(s=!0):(s=!1,0==o?this[this.t++]=a:o+i>this.DB?(this[this.t-1]|=(a&(1<<this.DB-o)-1)<<o,this[this.t++]=a>>this.DB-o):this[this.t-1]|=a<<o,(o+=i)>=this.DB&&(o-=this.DB))}8==i&&0!=(128&e[0])&&(this.s=-1,o>0&&(this[this.t-1]|=(1<<this.DB-o)-1<<o)),this.clamp(),s&&t.ZERO.subTo(this,this)},t.prototype.clamp=function(){for(var e=this.s&this.DM;this.t>0&&this[this.t-1]==e;)--this.t},t.prototype.dlShiftTo=function(e,t){var r;for(r=this.t-1;r>=0;--r)t[r+e]=this[r];for(r=e-1;r>=0;--r)t[r]=0;t.t=this.t+e,t.s=this.s},t.prototype.drShiftTo=function(e,t){for(var r=e;r<this.t;++r)t[r-e]=this[r];t.t=Math.max(this.t-e,0),t.s=this.s},t.prototype.lShiftTo=function(e,t){var r,i=e%this.DB,n=this.DB-i,s=(1<<n)-1,o=Math.floor(e/this.DB),a=this.s<<i&this.DM;for(r=this.t-1;r>=0;--r)t[r+o+1]=this[r]>>n|a,a=(this[r]&s)<<i;for(r=o-1;r>=0;--r)t[r]=0;t[o]=a,t.t=this.t+o+1,t.s=this.s,t.clamp()},t.prototype.rShiftTo=function(e,t){t.s=this.s;var r=Math.floor(e/this.DB);if(r>=this.t)t.t=0;else{var i=e%this.DB,n=this.DB-i,s=(1<<i)-1;t[0]=this[r]>>i;for(var o=r+1;o<this.t;++o)t[o-r-1]|=(this[o]&s)<<n,t[o-r]=this[o]>>i;i>0&&(t[this.t-r-1]|=(this.s&s)<<n),t.t=this.t-r,t.clamp()}},t.prototype.subTo=function(e,t){for(var r=0,i=0,n=Math.min(e.t,this.t);r<n;)i+=this[r]-e[r],t[r++]=i&this.DM,i>>=this.DB;if(e.t<this.t){for(i-=e.s;r<this.t;)i+=this[r],t[r++]=i&this.DM,i>>=this.DB;i+=this.s}else{for(i+=this.s;r<e.t;)i-=e[r],t[r++]=i&this.DM,i>>=this.DB;i-=e.s}t.s=i<0?-1:0,i<-1?t[r++]=this.DV+i:i>0&&(t[r++]=i),t.t=r,t.clamp()},t.prototype.multiplyTo=function(e,r){var i=this.abs(),n=e.abs(),s=i.t;for(r.t=s+n.t;--s>=0;)r[s]=0;for(s=0;s<n.t;++s)r[s+i.t]=i.am(0,n[s],r,s,0,i.t);r.s=0,r.clamp(),this.s!=e.s&&t.ZERO.subTo(r,r)},t.prototype.squareTo=function(e){for(var t=this.abs(),r=e.t=2*t.t;--r>=0;)e[r]=0;for(r=0;r<t.t-1;++r){var i=t.am(r,t[r],e,2*r,0,1);(e[r+t.t]+=t.am(r+1,2*t[r],e,2*r+1,i,t.t-r-1))>=t.DV&&(e[r+t.t]-=t.DV,e[r+t.t+1]=1)}e.t>0&&(e[e.t-1]+=t.am(r,t[r],e,2*r,0,1)),e.s=0,e.clamp()},t.prototype.divRemTo=function(e,i,n){var s=e.abs();if(!(s.t<=0)){var o=this.abs();if(o.t<s.t)return null!=i&&i.fromInt(0),void(null!=n&&this.copyTo(n));null==n&&(n=r());var a=r(),c=this.s,d=e.s,l=this.DB-u(s[s.t-1]);l>0?(s.lShiftTo(l,a),o.lShiftTo(l,n)):(s.copyTo(a),o.copyTo(n));var p=a.t,h=a[p-1];if(0!=h){var f=h*(1<<this.F1)+(p>1?a[p-2]>>this.F2:0),m=this.FV/f,g=(1<<this.F1)/f,v=1<<this.F2,b=n.t,y=b-p,w=null==i?r():i;for(a.dlShiftTo(y,w),n.compareTo(w)>=0&&(n[n.t++]=1,n.subTo(w,n)),t.ONE.dlShiftTo(p,w),w.subTo(a,a);a.t<p;)a[a.t++]=0;for(;--y>=0;){var _=n[--b]==h?this.DM:Math.floor(n[b]*m+(n[b-1]+v)*g);if((n[b]+=a.am(0,_,n,y,0,p))<_)for(a.dlShiftTo(y,w),n.subTo(w,n);n[b]<--_;)n.subTo(w,n)}null!=i&&(n.drShiftTo(p,i),c!=d&&t.ZERO.subTo(i,i)),n.t=p,n.clamp(),l>0&&n.rShiftTo(l,n),c<0&&t.ZERO.subTo(n,n)}}},t.prototype.invDigit=function(){if(this.t<1)return 0;var e=this[0];if(0==(1&e))return 0;var t=3&e;return(t=(t=(t=(t=t*(2-(15&e)*t)&15)*(2-(255&e)*t)&255)*(2-((65535&e)*t&65535))&65535)*(2-e*t%this.DV)%this.DV)>0?this.DV-t:-t},t.prototype.isEven=function(){return 0==(this.t>0?1&this[0]:this.s)},t.prototype.exp=function(e,i){if(e>4294967295||e<1)return t.ONE;var n=r(),s=r(),o=i.convert(this),a=u(e)-1;for(o.copyTo(n);--a>=0;)if(i.sqrTo(n,s),(e&1<<a)>0)i.mulTo(s,o,n);else{var c=n;n=s,s=c}return i.revert(n)},t.prototype.toString=function(e){if(this.s<0)return"-"+this.negate().toString(e);var t;if(16==e)t=4;else if(8==e)t=3;else if(2==e)t=1;else if(32==e)t=5;else{if(4!=e)return this.toRadix(e);t=2}var r,i=(1<<t)-1,n=!1,s="",o=this.t,a=this.DB-o*this.DB%t;if(o-- >0)for(a<this.DB&&(r=this[o]>>a)>0&&(n=!0,s=c(r));o>=0;)a<t?(r=(this[o]&(1<<a)-1)<<t-a,r|=this[--o]>>(a+=this.DB-t)):(r=this[o]>>(a-=t)&i,a<=0&&(a+=this.DB,--o)),r>0&&(n=!0),n&&(s+=c(r));return n?s:"0"},t.prototype.negate=function(){var e=r();return t.ZERO.subTo(this,e),e},t.prototype.abs=function(){return this.s<0?this.negate():this},t.prototype.compareTo=function(e){var t=this.s-e.s;if(0!=t)return t;var r=this.t;if(0!=(t=r-e.t))return this.s<0?-t:t;for(;--r>=0;)if(0!=(t=this[r]-e[r]))return t;return 0},t.prototype.bitLength=function(){return this.t<=0?0:this.DB*(this.t-1)+u(this[this.t-1]^this.s&this.DM)},t.prototype.mod=function(e){var i=r();return this.abs().divRemTo(e,null,i),this.s<0&&i.compareTo(t.ZERO)>0&&e.subTo(i,i),i},t.prototype.modPowInt=function(e,t){var r;return r=e<256||t.isEven()?new p(t):new h(t),this.exp(e,r)},t.ZERO=l(0),t.ONE=l(1),w.prototype.convert=_,w.prototype.revert=_,w.prototype.mulTo=function(e,t,r){e.multiplyTo(t,r)},w.prototype.sqrTo=function(e,t){e.squareTo(t)},S.prototype.convert=function(e){if(e.s<0||e.t>2*this.m.t)return e.mod(this.m);if(e.compareTo(this.m)<0)return e;var t=r();return e.copyTo(t),this.reduce(t),t},S.prototype.revert=function(e){return e},S.prototype.reduce=function(e){for(e.drShiftTo(this.m.t-1,this.r2),e.t>this.m.t+1&&(e.t=this.m.t+1,e.clamp()),this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3),this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2);e.compareTo(this.r2)<0;)e.dAddOffset(1,this.m.t+1);for(e.subTo(this.r2,e);e.compareTo(this.m)>=0;)e.subTo(this.m,e)},S.prototype.mulTo=function(e,t,r){e.multiplyTo(t,r),this.reduce(r)},S.prototype.sqrTo=function(e,t){e.squareTo(t),this.reduce(t)};var C,R,k,T=[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509,521,523,541,547,557,563,569,571,577,587,593,599,601,607,613,617,619,631,641,643,647,653,659,661,673,677,683,691,701,709,719,727,733,739,743,751,757,761,769,773,787,797,809,811,821,823,827,829,839,853,857,859,863,877,881,883,887,907,911,919,929,937,941,947,953,967,971,977,983,991,997],P=(1<<26)/T[T.length-1];function E(){var e;e=(new Date).getTime(),R[k++]^=255&e,R[k++]^=e>>8&255,R[k++]^=e>>16&255,R[k++]^=e>>24&255,k>=j&&(k-=j)}if(t.prototype.chunkSize=function(e){return Math.floor(Math.LN2*this.DB/Math.log(e))},t.prototype.toRadix=function(e){if(null==e&&(e=10),0==this.signum()||e<2||e>36)return"0";var t=this.chunkSize(e),i=Math.pow(e,t),n=l(i),s=r(),o=r(),a="";for(this.divRemTo(n,s,o);s.signum()>0;)a=(i+o.intValue()).toString(e).substr(1)+a,s.divRemTo(n,s,o);return o.intValue().toString(e)+a},t.prototype.fromRadix=function(e,r){this.fromInt(0),null==r&&(r=10);for(var i=this.chunkSize(r),n=Math.pow(r,i),s=!1,o=0,a=0,c=0;c<e.length;++c){var l=d(e,c);l<0?"-"==e.charAt(c)&&0==this.signum()&&(s=!0):(a=r*a+l,++o>=i&&(this.dMultiply(n),this.dAddOffset(a,0),o=0,a=0))}o>0&&(this.dMultiply(Math.pow(r,o)),this.dAddOffset(a,0)),s&&t.ZERO.subTo(this,this)},t.prototype.fromNumber=function(e,r,i){if("number"==typeof r)if(e<2)this.fromInt(1);else for(this.fromNumber(e,i),this.testBit(e-1)||this.bitwiseTo(t.ONE.shiftLeft(e-1),m,this),this.isEven()&&this.dAddOffset(1,0);!this.isProbablePrime(r);)this.dAddOffset(2,0),this.bitLength()>e&&this.subTo(t.ONE.shiftLeft(e-1),this);else{var n=new Array,s=7&e;n.length=1+(e>>3),r.nextBytes(n),s>0?n[0]&=(1<<s)-1:n[0]=0,this.fromString(n,256)}},t.prototype.bitwiseTo=function(e,t,r){var i,n,s=Math.min(e.t,this.t);for(i=0;i<s;++i)r[i]=t(this[i],e[i]);if(e.t<this.t){for(n=e.s&this.DM,i=s;i<this.t;++i)r[i]=t(this[i],n);r.t=this.t}else{for(n=this.s&this.DM,i=s;i<e.t;++i)r[i]=t(n,e[i]);r.t=e.t}r.s=t(this.s,e.s),r.clamp()},t.prototype.changeBit=function(e,r){var i=t.ONE.shiftLeft(e);return this.bitwiseTo(i,r,i),i},t.prototype.addTo=function(e,t){for(var r=0,i=0,n=Math.min(e.t,this.t);r<n;)i+=this[r]+e[r],t[r++]=i&this.DM,i>>=this.DB;if(e.t<this.t){for(i+=e.s;r<this.t;)i+=this[r],t[r++]=i&this.DM,i>>=this.DB;i+=this.s}else{for(i+=this.s;r<e.t;)i+=e[r],t[r++]=i&this.DM,i>>=this.DB;i+=e.s}t.s=i<0?-1:0,i>0?t[r++]=i:i<-1&&(t[r++]=this.DV+i),t.t=r,t.clamp()},t.prototype.dMultiply=function(e){this[this.t]=this.am(0,e-1,this,0,0,this.t),++this.t,this.clamp()},t.prototype.dAddOffset=function(e,t){if(0!=e){for(;this.t<=t;)this[this.t++]=0;for(this[t]+=e;this[t]>=this.DV;)this[t]-=this.DV,++t>=this.t&&(this[this.t++]=0),++this[t]}},t.prototype.multiplyLowerTo=function(e,t,r){var i,n=Math.min(this.t+e.t,t);for(r.s=0,r.t=n;n>0;)r[--n]=0;for(i=r.t-this.t;n<i;++n)r[n+this.t]=this.am(0,e[n],r,n,0,this.t);for(i=Math.min(e.t,t);n<i;++n)this.am(0,e[n],r,n,0,t-n);r.clamp()},t.prototype.multiplyUpperTo=function(e,t,r){--t;var i=r.t=this.t+e.t-t;for(r.s=0;--i>=0;)r[i]=0;for(i=Math.max(t-this.t,0);i<e.t;++i)r[this.t+i-t]=this.am(t-i,e[i],r,0,0,this.t+i-t);r.clamp(),r.drShiftTo(1,r)},t.prototype.modInt=function(e){if(e<=0)return 0;var t=this.DV%e,r=this.s<0?e-1:0;if(this.t>0)if(0==t)r=this[0]%e;else for(var i=this.t-1;i>=0;--i)r=(t*r+this[i])%e;return r},t.prototype.millerRabin=function(e){var i=this.subtract(t.ONE),n=i.getLowestSetBit();if(n<=0)return!1;var s=i.shiftRight(n);(e=e+1>>1)>T.length&&(e=T.length);for(var o=r(),a=0;a<e;++a){o.fromInt(T[Math.floor(Math.random()*T.length)]);var c=o.modPow(s,this);if(0!=c.compareTo(t.ONE)&&0!=c.compareTo(i)){for(var d=1;d++<n&&0!=c.compareTo(i);)if(0==(c=c.modPowInt(2,this)).compareTo(t.ONE))return!1;if(0!=c.compareTo(i))return!1}}return!0},t.prototype.clone=function(){var e=r();return this.copyTo(e),e},t.prototype.intValue=function(){if(this.s<0){if(1==this.t)return this[0]-this.DV;if(0==this.t)return-1}else{if(1==this.t)return this[0];if(0==this.t)return 0}return(this[1]&(1<<32-this.DB)-1)<<this.DB|this[0]},t.prototype.byteValue=function(){return 0==this.t?this.s:this[0]<<24>>24},t.prototype.shortValue=function(){return 0==this.t?this.s:this[0]<<16>>16},t.prototype.signum=function(){return this.s<0?-1:this.t<=0||1==this.t&&this[0]<=0?0:1},t.prototype.toByteArray=function(){var e=this.t,t=new Array;t[0]=this.s;var r,i=this.DB-e*this.DB%8,n=0;if(e-- >0)for(i<this.DB&&(r=this[e]>>i)!=(this.s&this.DM)>>i&&(t[n++]=r|this.s<<this.DB-i);e>=0;)i<8?(r=(this[e]&(1<<i)-1)<<8-i,r|=this[--e]>>(i+=this.DB-8)):(r=this[e]>>(i-=8)&255,i<=0&&(i+=this.DB,--e)),0!=(128&r)&&(r|=-256),0==n&&(128&this.s)!=(128&r)&&++n,(n>0||r!=this.s)&&(t[n++]=r);return t},t.prototype.equals=function(e){return 0==this.compareTo(e)},t.prototype.min=function(e){return this.compareTo(e)<0?this:e},t.prototype.max=function(e){return this.compareTo(e)>0?this:e},t.prototype.and=function(e){var t=r();return this.bitwiseTo(e,f,t),t},t.prototype.or=function(e){var t=r();return this.bitwiseTo(e,m,t),t},t.prototype.xor=function(e){var t=r();return this.bitwiseTo(e,g,t),t},t.prototype.andNot=function(e){var t=r();return this.bitwiseTo(e,v,t),t},t.prototype.not=function(){for(var e=r(),t=0;t<this.t;++t)e[t]=this.DM&~this[t];return e.t=this.t,e.s=~this.s,e},t.prototype.shiftLeft=function(e){var t=r();return e<0?this.rShiftTo(-e,t):this.lShiftTo(e,t),t},t.prototype.shiftRight=function(e){var t=r();return e<0?this.lShiftTo(-e,t):this.rShiftTo(e,t),t},t.prototype.getLowestSetBit=function(){for(var e=0;e<this.t;++e)if(0!=this[e])return e*this.DB+b(this[e]);return this.s<0?this.t*this.DB:-1},t.prototype.bitCount=function(){for(var e=0,t=this.s&this.DM,r=0;r<this.t;++r)e+=y(this[r]^t);return e},t.prototype.testBit=function(e){var t=Math.floor(e/this.DB);return t>=this.t?0!=this.s:0!=(this[t]&1<<e%this.DB)},t.prototype.setBit=function(e){return this.changeBit(e,m)},t.prototype.clearBit=function(e){return this.changeBit(e,v)},t.prototype.flipBit=function(e){return this.changeBit(e,g)},t.prototype.add=function(e){var t=r();return this.addTo(e,t),t},t.prototype.subtract=function(e){var t=r();return this.subTo(e,t),t},t.prototype.multiply=function(e){var t=r();return this.multiplyTo(e,t),t},t.prototype.divide=function(e){var t=r();return this.divRemTo(e,t,null),t},t.prototype.remainder=function(e){var t=r();return this.divRemTo(e,null,t),t},t.prototype.divideAndRemainder=function(e){var t=r(),i=r();return this.divRemTo(e,t,i),new Array(t,i)},t.prototype.modPow=function(e,t){var i,n,s=e.bitLength(),o=l(1);if(s<=0)return o;i=s<18?1:s<48?3:s<144?4:s<768?5:6,n=s<8?new p(t):t.isEven()?new S(t):new h(t);var a=new Array,c=3,d=i-1,f=(1<<i)-1;if(a[1]=n.convert(this),i>1){var m=r();for(n.sqrTo(a[1],m);c<=f;)a[c]=r(),n.mulTo(m,a[c-2],a[c]),c+=2}var g,v,b=e.t-1,y=!0,w=r();for(s=u(e[b])-1;b>=0;){for(s>=d?g=e[b]>>s-d&f:(g=(e[b]&(1<<s+1)-1)<<d-s,b>0&&(g|=e[b-1]>>this.DB+s-d)),c=i;0==(1&g);)g>>=1,--c;if((s-=c)<0&&(s+=this.DB,--b),y)a[g].copyTo(o),y=!1;else{for(;c>1;)n.sqrTo(o,w),n.sqrTo(w,o),c-=2;c>0?n.sqrTo(o,w):(v=o,o=w,w=v),n.mulTo(w,a[g],o)}for(;b>=0&&0==(e[b]&1<<s);)n.sqrTo(o,w),v=o,o=w,w=v,--s<0&&(s=this.DB-1,--b)}return n.revert(o)},t.prototype.modInverse=function(e){var r=e.isEven();if(this.isEven()&&r||0==e.signum())return t.ZERO;for(var i=e.clone(),n=this.clone(),s=l(1),o=l(0),a=l(0),c=l(1);0!=i.signum();){for(;i.isEven();)i.rShiftTo(1,i),r?(s.isEven()&&o.isEven()||(s.addTo(this,s),o.subTo(e,o)),s.rShiftTo(1,s)):o.isEven()||o.subTo(e,o),o.rShiftTo(1,o);for(;n.isEven();)n.rShiftTo(1,n),r?(a.isEven()&&c.isEven()||(a.addTo(this,a),c.subTo(e,c)),a.rShiftTo(1,a)):c.isEven()||c.subTo(e,c),c.rShiftTo(1,c);i.compareTo(n)>=0?(i.subTo(n,i),r&&s.subTo(a,s),o.subTo(c,o)):(n.subTo(i,n),r&&a.subTo(s,a),c.subTo(o,c))}return 0!=n.compareTo(t.ONE)?t.ZERO:c.compareTo(e)>=0?c.subtract(e):c.signum()<0?(c.addTo(e,c),c.signum()<0?c.add(e):c):c},t.prototype.pow=function(e){return this.exp(e,new w)},t.prototype.gcd=function(e){var t=this.s<0?this.negate():this.clone(),r=e.s<0?e.negate():e.clone();if(t.compareTo(r)<0){var i=t;t=r,r=i}var n=t.getLowestSetBit(),s=r.getLowestSetBit();if(s<0)return t;for(n<s&&(s=n),s>0&&(t.rShiftTo(s,t),r.rShiftTo(s,r));t.signum()>0;)(n=t.getLowestSetBit())>0&&t.rShiftTo(n,t),(n=r.getLowestSetBit())>0&&r.rShiftTo(n,r),t.compareTo(r)>=0?(t.subTo(r,t),t.rShiftTo(1,t)):(r.subTo(t,r),r.rShiftTo(1,r));return s>0&&r.lShiftTo(s,r),r},t.prototype.isProbablePrime=function(e){var t,r=this.abs();if(1==r.t&&r[0]<=T[T.length-1]){for(t=0;t<T.length;++t)if(r[0]==T[t])return!0;return!1}if(r.isEven())return!1;for(t=1;t<T.length;){for(var i=T[t],n=t+1;n<T.length&&i<P;)i*=T[n++];for(i=r.modInt(i);t<n;)if(i%T[t++]==0)return!1}return r.millerRabin(e)},t.prototype.square=function(){var e=r();return this.squareTo(e),e},t.prototype.Barrett=S,null==R){var O;if(R=new Array,k=0,"undefined"!=typeof window&&window.crypto)if(window.crypto.getRandomValues){var D=new Uint8Array(32);for(window.crypto.getRandomValues(D),O=0;O<32;++O)R[k++]=D[O]}else if("Netscape"==navigator.appName&&navigator.appVersion<"5"){var I=window.crypto.random(32);for(O=0;O<I.length;++O)R[k++]=255&I.charCodeAt(O)}for(;k<j;)O=Math.floor(65536*Math.random()),R[k++]=O>>>8,R[k++]=255&O;k=0,E()}function x(){if(null==C){for(E(),(C=new L).init(R),k=0;k<R.length;++k)R[k]=0;k=0}return C.next()}function M(){}function L(){this.i=0,this.j=0,this.S=new Array}M.prototype.nextBytes=function(e){var t;for(t=0;t<e.length;++t)e[t]=x()},L.prototype.init=function(e){var t,r,i;for(t=0;t<256;++t)this.S[t]=t;for(r=0,t=0;t<256;++t)r=r+this.S[t]+e[t%e.length]&255,i=this.S[t],this.S[t]=this.S[r],this.S[r]=i;this.i=0,this.j=0},L.prototype.next=function(){var e;return this.i=this.i+1&255,this.j=this.j+this.S[this.i]&255,e=this.S[this.i],this.S[this.i]=this.S[this.j],this.S[this.j]=e,this.S[e+this.S[this.i]&255]};var j=256;Ui.exports={default:t,BigInteger:t,SecureRandom:M}}.call(a);var Gi=$i.exports,qi={};!function(e){!function(){var t={not_string:/[^s]/,not_bool:/[^t]/,not_type:/[^T]/,not_primitive:/[^v]/,number:/[diefg]/,numeric_arg:/[bcdiefguxX]/,json:/[j]/,not_json:/[^j]/,text:/^[^\x25]+/,modulo:/^\x25{2}/,placeholder:/^\x25(?:([1-9]\d*)\$|\(([^)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijostTuvxX])/,key:/^([a-z_][a-z_\d]*)/i,key_access:/^\.([a-z_][a-z_\d]*)/i,index_access:/^\[(\d+)\]/,sign:/^[+-]/};function r(e){return function(e,i){var n,s,o,a,c,d,l,u,p,h=1,f=e.length,m="";for(s=0;s<f;s++)if("string"==typeof e[s])m+=e[s];else if("object"==typeof e[s]){if((a=e[s]).keys)for(n=i[h],o=0;o<a.keys.length;o++){if(null==n)throw new Error(r('[sprintf] Cannot access property "%s" of undefined value "%s"',a.keys[o],a.keys[o-1]));n=n[a.keys[o]]}else n=a.param_no?i[a.param_no]:i[h++];if(t.not_type.test(a.type)&&t.not_primitive.test(a.type)&&n instanceof Function&&(n=n()),t.numeric_arg.test(a.type)&&"number"!=typeof n&&isNaN(n))throw new TypeError(r("[sprintf] expecting number but found %T",n));switch(t.number.test(a.type)&&(u=n>=0),a.type){case"b":n=parseInt(n,10).toString(2);break;case"c":n=String.fromCharCode(parseInt(n,10));break;case"d":case"i":n=parseInt(n,10);break;case"j":n=JSON.stringify(n,null,a.width?parseInt(a.width):0);break;case"e":n=a.precision?parseFloat(n).toExponential(a.precision):parseFloat(n).toExponential();break;case"f":n=a.precision?parseFloat(n).toFixed(a.precision):parseFloat(n);break;case"g":n=a.precision?String(Number(n.toPrecision(a.precision))):parseFloat(n);break;case"o":n=(parseInt(n,10)>>>0).toString(8);break;case"s":n=String(n),n=a.precision?n.substring(0,a.precision):n;break;case"t":n=String(!!n),n=a.precision?n.substring(0,a.precision):n;break;case"T":n=Object.prototype.toString.call(n).slice(8,-1).toLowerCase(),n=a.precision?n.substring(0,a.precision):n;break;case"u":n=parseInt(n,10)>>>0;break;case"v":n=n.valueOf(),n=a.precision?n.substring(0,a.precision):n;break;case"x":n=(parseInt(n,10)>>>0).toString(16);break;case"X":n=(parseInt(n,10)>>>0).toString(16).toUpperCase()}t.json.test(a.type)?m+=n:(!t.number.test(a.type)||u&&!a.sign?p="":(p=u?"+":"-",n=n.toString().replace(t.sign,"")),d=a.pad_char?"0"===a.pad_char?"0":a.pad_char.charAt(1):" ",l=a.width-(p+n).length,c=a.width&&l>0?d.repeat(l):"",m+=a.align?p+n+c:"0"===d?p+c+n:c+p+n)}return m}(function(e){if(n[e])return n[e];var r,i=e,s=[],o=0;for(;i;){if(null!==(r=t.text.exec(i)))s.push(r[0]);else if(null!==(r=t.modulo.exec(i)))s.push("%");else{if(null===(r=t.placeholder.exec(i)))throw new SyntaxError("[sprintf] unexpected placeholder");if(r[2]){o|=1;var a=[],c=r[2],d=[];if(null===(d=t.key.exec(c)))throw new SyntaxError("[sprintf] failed to parse named argument key");for(a.push(d[1]);""!==(c=c.substring(d[0].length));)if(null!==(d=t.key_access.exec(c)))a.push(d[1]);else{if(null===(d=t.index_access.exec(c)))throw new SyntaxError("[sprintf] failed to parse named argument key");a.push(d[1])}r[2]=a}else o|=2;if(3===o)throw new Error("[sprintf] mixing positional and named placeholders is not (yet) supported");s.push({placeholder:r[0],param_no:r[1],keys:r[2],sign:r[3],pad_char:r[4],align:r[5],width:r[6],precision:r[7],type:r[8]})}i=i.substring(r[0].length)}return n[e]=s}(e),arguments)}function i(e,t){return r.apply(null,[e].concat(t||[]))}var n=Object.create(null);e.sprintf=r,e.vsprintf=i,"undefined"!=typeof window&&(window.sprintf=r,window.vsprintf=i)}()}(qi);var Hi=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),Wi=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Ki=a&&a.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)"default"!==r&&Object.prototype.hasOwnProperty.call(e,r)&&Hi(t,e,r);return Wi(t,e),t};Object.defineProperty(Ni,"__esModule",{value:!0}),Ni.Address4=void 0;const Ji=Ki(Bi),Xi=Ki(Fi),Qi=zi,Zi=Gi,Yi=qi;class en{constructor(e){this.groups=Xi.GROUPS,this.parsedAddress=[],this.parsedSubnet="",this.subnet="/32",this.subnetMask=32,this.v4=!0,this.isCorrect=Ji.isCorrect(Xi.BITS),this.isInSubnet=Ji.isInSubnet,this.address=e;const t=Xi.RE_SUBNET_STRING.exec(e);if(t){if(this.parsedSubnet=t[0].replace("/",""),this.subnetMask=parseInt(this.parsedSubnet,10),this.subnet=`/${this.subnetMask}`,this.subnetMask<0||this.subnetMask>Xi.BITS)throw new Qi.AddressError("Invalid subnet mask.");e=e.replace(Xi.RE_SUBNET_STRING,"")}this.addressMinusSuffix=e,this.parsedAddress=this.parse(e)}static isValid(e){try{return new en(e),!0}catch(e){return!1}}parse(e){const t=e.split(".");if(!e.match(Xi.RE_ADDRESS))throw new Qi.AddressError("Invalid IPv4 address.");return t}correctForm(){return this.parsedAddress.map((e=>parseInt(e,10))).join(".")}static fromHex(e){const t=e.replace(/:/g,"").padStart(8,"0"),r=[];let i;for(i=0;i<8;i+=2){const e=t.slice(i,i+2);r.push(parseInt(e,16))}return new en(r.join("."))}static fromInteger(e){return en.fromHex(e.toString(16))}static fromArpa(e){const t=e.replace(/(\.in-addr\.arpa)?\.$/,"").split(".").reverse().join(".");return new en(t)}toHex(){return this.parsedAddress.map((e=>(0,Yi.sprintf)("%02x",parseInt(e,10)))).join(":")}toArray(){return this.parsedAddress.map((e=>parseInt(e,10)))}toGroup6(){const e=[];let t;for(t=0;t<Xi.GROUPS;t+=2){const r=(0,Yi.sprintf)("%02x%02x",parseInt(this.parsedAddress[t],10),parseInt(this.parsedAddress[t+1],10));e.push((0,Yi.sprintf)("%x",parseInt(r,16)))}return e.join(":")}bigInteger(){return new Zi.BigInteger(this.parsedAddress.map((e=>(0,Yi.sprintf)("%02x",parseInt(e,10)))).join(""),16)}_startAddress(){return new Zi.BigInteger(this.mask()+"0".repeat(Xi.BITS-this.subnetMask),2)}startAddress(){return en.fromBigInteger(this._startAddress())}startAddressExclusive(){const e=new Zi.BigInteger("1");return en.fromBigInteger(this._startAddress().add(e))}_endAddress(){return new Zi.BigInteger(this.mask()+"1".repeat(Xi.BITS-this.subnetMask),2)}endAddress(){return en.fromBigInteger(this._endAddress())}endAddressExclusive(){const e=new Zi.BigInteger("1");return en.fromBigInteger(this._endAddress().subtract(e))}static fromBigInteger(e){return en.fromInteger(parseInt(e.toString(),10))}mask(e){return void 0===e&&(e=this.subnetMask),this.getBitsBase2(0,e)}getBitsBase2(e,t){return this.binaryZeroPad().slice(e,t)}reverseForm(e){e||(e={});const t=this.correctForm().split(".").reverse().join(".");return e.omitSuffix?t:(0,Yi.sprintf)("%s.in-addr.arpa.",t)}isMulticast(){return this.isInSubnet(new en("224.0.0.0/4"))}binaryZeroPad(){return this.bigInteger().toString(2).padStart(Xi.BITS,"0")}groupForV6(){const e=this.parsedAddress;return this.address.replace(Xi.RE_ADDRESS,(0,Yi.sprintf)('<span class="hover-group group-v4 group-6">%s</span>.<span class="hover-group group-v4 group-7">%s</span>',e.slice(0,2).join("."),e.slice(2,4).join(".")))}}Ni.Address4=en;var tn={},rn={};Object.defineProperty(rn,"__esModule",{value:!0}),rn.RE_URL_WITH_PORT=rn.RE_URL=rn.RE_ZONE_STRING=rn.RE_SUBNET_STRING=rn.RE_BAD_ADDRESS=rn.RE_BAD_CHARACTERS=rn.TYPES=rn.SCOPES=rn.GROUPS=rn.BITS=void 0,rn.BITS=128,rn.GROUPS=8,rn.SCOPES={0:"Reserved",1:"Interface local",2:"Link local",4:"Admin local",5:"Site local",8:"Organization local",14:"Global",15:"Reserved"},rn.TYPES={"ff01::1/128":"Multicast (All nodes on this interface)","ff01::2/128":"Multicast (All routers on this interface)","ff02::1/128":"Multicast (All nodes on this link)","ff02::2/128":"Multicast (All routers on this link)","ff05::2/128":"Multicast (All routers in this site)","ff02::5/128":"Multicast (OSPFv3 AllSPF routers)","ff02::6/128":"Multicast (OSPFv3 AllDR routers)","ff02::9/128":"Multicast (RIP routers)","ff02::a/128":"Multicast (EIGRP routers)","ff02::d/128":"Multicast (PIM routers)","ff02::16/128":"Multicast (MLDv2 reports)","ff01::fb/128":"Multicast (mDNSv6)","ff02::fb/128":"Multicast (mDNSv6)","ff05::fb/128":"Multicast (mDNSv6)","ff02::1:2/128":"Multicast (All DHCP servers and relay agents on this link)","ff05::1:2/128":"Multicast (All DHCP servers and relay agents in this site)","ff02::1:3/128":"Multicast (All DHCP servers on this link)","ff05::1:3/128":"Multicast (All DHCP servers in this site)","::/128":"Unspecified","::1/128":"Loopback","ff00::/8":"Multicast","fe80::/10":"Link-local unicast"},rn.RE_BAD_CHARACTERS=/([^0-9a-f:/%])/gi,rn.RE_BAD_ADDRESS=/([0-9a-f]{5,}|:{3,}|[^:]:$|^:[^:]|\/$)/gi,rn.RE_SUBNET_STRING=/\/\d{1,3}(?=%|$)/,rn.RE_ZONE_STRING=/%.*$/,rn.RE_URL=new RegExp(/^\[{0,1}([0-9a-f:]+)\]{0,1}/),rn.RE_URL_WITH_PORT=new RegExp(/\[([0-9a-f:]+)\]:([0-9]{1,5})/);var nn={};Object.defineProperty(nn,"__esModule",{value:!0}),nn.simpleGroup=nn.spanLeadingZeroes=nn.spanAll=nn.spanAllZeroes=void 0;const sn=qi;function on(e){return e.replace(/(0+)/g,'<span class="zero">$1</span>')}function an(e){return e.replace(/^(0+)/,'<span class="zero">$1</span>')}nn.spanAllZeroes=on,nn.spanAll=function(e,t=0){return e.split("").map(((e,r)=>(0,sn.sprintf)('<span class="digit value-%s position-%d">%s</span>',e,r+t,on(e)))).join("")},nn.spanLeadingZeroes=function(e){return e.split(":").map((e=>an(e))).join(":")},nn.simpleGroup=function(e,t=0){return e.split(":").map(((e,r)=>/group-v4/.test(e)?e:(0,sn.sprintf)('<span class="hover-group group-%d">%s</span>',r+t,an(e))))};var cn={},dn=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),ln=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),un=a&&a.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)"default"!==r&&Object.prototype.hasOwnProperty.call(e,r)&&dn(t,e,r);return ln(t,e),t};Object.defineProperty(cn,"__esModule",{value:!0}),cn.possibleElisions=cn.simpleRegularExpression=cn.ADDRESS_BOUNDARY=cn.padGroup=cn.groupPossibilities=void 0;const pn=un(rn),hn=qi;function fn(e){return(0,hn.sprintf)("(%s)",e.join("|"))}function mn(e){return e.length<4?(0,hn.sprintf)("0{0,%d}%s",4-e.length,e):e}cn.groupPossibilities=fn,cn.padGroup=mn,cn.ADDRESS_BOUNDARY="[^A-Fa-f0-9:]",cn.simpleRegularExpression=function(e){const t=[];e.forEach(((e,r)=>{0===parseInt(e,16)&&t.push(r)}));const r=t.map((t=>e.map(((e,r)=>{if(r===t){const t=0===r||r===pn.GROUPS-1?":":"";return fn([mn(e),t])}return mn(e)})).join(":")));return r.push(e.map(mn).join(":")),fn(r)},cn.possibleElisions=function(e,t,r){const i=t?"":":",n=r?"":":",s=[];t||r||s.push("::"),t&&r&&s.push(""),(r&&!t||!r&&t)&&s.push(":"),s.push((0,hn.sprintf)("%s(:0{1,4}){1,%d}",i,e-1)),s.push((0,hn.sprintf)("(0{1,4}:){1,%d}%s",e-1,n)),s.push((0,hn.sprintf)("(0{1,4}:){%d}0{1,4}",e-1));for(let t=1;t<e-1;t++)for(let r=1;r<e-t;r++)s.push((0,hn.sprintf)("(0{1,4}:){%d}:(0{1,4}:){%d}0{1,4}",r,e-r-t-1));return fn(s)};var gn=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),vn=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),bn=a&&a.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)"default"!==r&&Object.prototype.hasOwnProperty.call(e,r)&&gn(t,e,r);return vn(t,e),t};Object.defineProperty(tn,"__esModule",{value:!0}),tn.Address6=void 0;const yn=bn(Bi),wn=bn(Fi),_n=bn(rn),Sn=bn(nn),Cn=Ni,Rn=cn,kn=zi,Tn=Gi,Pn=qi;function En(e){if(!e)throw new Error("Assertion failed.")}function On(e){return e=(e=e.replace(/^(0{1,})([1-9]+)$/,'<span class="parse-error">$1</span>$2')).replace(/^(0{1,})(0)$/,'<span class="parse-error">$1</span>$2')}function Dn(e){return(0,Pn.sprintf)("%04x",parseInt(e,16))}function In(e){return 255&e}class xn{constructor(e,t){this.addressMinusSuffix="",this.parsedSubnet="",this.subnet="/128",this.subnetMask=128,this.v4=!1,this.zone="",this.isInSubnet=yn.isInSubnet,this.isCorrect=yn.isCorrect(_n.BITS),this.groups=void 0===t?_n.GROUPS:t,this.address=e;const r=_n.RE_SUBNET_STRING.exec(e);if(r){if(this.parsedSubnet=r[0].replace("/",""),this.subnetMask=parseInt(this.parsedSubnet,10),this.subnet=`/${this.subnetMask}`,Number.isNaN(this.subnetMask)||this.subnetMask<0||this.subnetMask>_n.BITS)throw new kn.AddressError("Invalid subnet mask.");e=e.replace(_n.RE_SUBNET_STRING,"")}else if(/\//.test(e))throw new kn.AddressError("Invalid subnet mask.");const i=_n.RE_ZONE_STRING.exec(e);i&&(this.zone=i[0],e=e.replace(_n.RE_ZONE_STRING,"")),this.addressMinusSuffix=e,this.parsedAddress=this.parse(this.addressMinusSuffix)}static isValid(e){try{return new xn(e),!0}catch(e){return!1}}static fromBigInteger(e){const t=e.toString(16).padStart(32,"0"),r=[];let i;for(i=0;i<_n.GROUPS;i++)r.push(t.slice(4*i,4*(i+1)));return new xn(r.join(":"))}static fromURL(e){let t,r,i=null;if(-1!==e.indexOf("[")&&-1!==e.indexOf("]:")){if(r=_n.RE_URL_WITH_PORT.exec(e),null===r)return{error:"failed to parse address with port",address:null,port:null};t=r[1],i=r[2]}else if(-1!==e.indexOf("/")){if(e=e.replace(/^[a-z0-9]+:\/\//,""),r=_n.RE_URL.exec(e),null===r)return{error:"failed to parse address from URL",address:null,port:null};t=r[1]}else t=e;return i?(i=parseInt(i,10),(i<0||i>65536)&&(i=null)):i=null,{address:new xn(t),port:i}}static fromAddress4(e){const t=new Cn.Address4(e),r=_n.BITS-(wn.BITS-t.subnetMask);return new xn(`::ffff:${t.correctForm()}/${r}`)}static fromArpa(e){let t=e.replace(/(\.ip6\.arpa)?\.$/,"");if(63!==t.length)throw new kn.AddressError("Invalid 'ip6.arpa' form.");const r=t.split(".").reverse();for(let e=7;e>0;e--){const t=4*e;r.splice(t,0,":")}return t=r.join(""),new xn(t)}microsoftTranscription(){return(0,Pn.sprintf)("%s.ipv6-literal.net",this.correctForm().replace(/:/g,"-"))}mask(e=this.subnetMask){return this.getBitsBase2(0,e)}possibleSubnets(e=128){const t=_n.BITS-this.subnetMask-Math.abs(e-_n.BITS);return t<0?"0":function(e){const t=/(\d+)(\d{3})/;for(;t.test(e);)e=e.replace(t,"$1,$2");return e}(new Tn.BigInteger("2",10).pow(t).toString(10))}_startAddress(){return new Tn.BigInteger(this.mask()+"0".repeat(_n.BITS-this.subnetMask),2)}startAddress(){return xn.fromBigInteger(this._startAddress())}startAddressExclusive(){const e=new Tn.BigInteger("1");return xn.fromBigInteger(this._startAddress().add(e))}_endAddress(){return new Tn.BigInteger(this.mask()+"1".repeat(_n.BITS-this.subnetMask),2)}endAddress(){return xn.fromBigInteger(this._endAddress())}endAddressExclusive(){const e=new Tn.BigInteger("1");return xn.fromBigInteger(this._endAddress().subtract(e))}getScope(){let e=_n.SCOPES[this.getBits(12,16).intValue()];return"Global unicast"===this.getType()&&"Link local"!==e&&(e="Global"),e||"Unknown"}getType(){for(const e of Object.keys(_n.TYPES))if(this.isInSubnet(new xn(e)))return _n.TYPES[e];return"Global unicast"}getBits(e,t){return new Tn.BigInteger(this.getBitsBase2(e,t),2)}getBitsBase2(e,t){return this.binaryZeroPad().slice(e,t)}getBitsBase16(e,t){const r=t-e;if(r%4!=0)throw new Error("Length of bits to retrieve must be divisible by four");return this.getBits(e,t).toString(16).padStart(r/4,"0")}getBitsPastSubnet(){return this.getBitsBase2(this.subnetMask,_n.BITS)}reverseForm(e){e||(e={});const t=Math.floor(this.subnetMask/4),r=this.canonicalForm().replace(/:/g,"").split("").slice(0,t).reverse().join(".");return t>0?e.omitSuffix?r:(0,Pn.sprintf)("%s.ip6.arpa.",r):e.omitSuffix?"":"ip6.arpa."}correctForm(){let e,t=[],r=0;const i=[];for(e=0;e<this.parsedAddress.length;e++){const t=parseInt(this.parsedAddress[e],16);0===t&&r++,0!==t&&r>0&&(r>1&&i.push([e-r,e-1]),r=0)}r>1&&i.push([this.parsedAddress.length-r,this.parsedAddress.length-1]);const n=i.map((e=>e[1]-e[0]+1));if(i.length>0){const e=n.indexOf(Math.max(...n));t=function(e,t){const r=[],i=[];let n;for(n=0;n<e.length;n++)n<t[0]?r.push(e[n]):n>t[1]&&i.push(e[n]);return r.concat(["compact"]).concat(i)}(this.parsedAddress,i[e])}else t=this.parsedAddress;for(e=0;e<t.length;e++)"compact"!==t[e]&&(t[e]=parseInt(t[e],16).toString(16));let s=t.join(":");return s=s.replace(/^compact$/,"::"),s=s.replace(/^compact|compact$/,":"),s=s.replace(/compact/,""),s}binaryZeroPad(){return this.bigInteger().toString(2).padStart(_n.BITS,"0")}parse4in6(e){const t=e.split(":"),r=t.slice(-1)[0].match(wn.RE_ADDRESS);if(r){this.parsedAddress4=r[0],this.address4=new Cn.Address4(this.parsedAddress4);for(let t=0;t<this.address4.groups;t++)if(/^0[0-9]+/.test(this.address4.parsedAddress[t]))throw new kn.AddressError("IPv4 addresses can't have leading zeroes.",e.replace(wn.RE_ADDRESS,this.address4.parsedAddress.map(On).join(".")));this.v4=!0,t[t.length-1]=this.address4.toGroup6(),e=t.join(":")}return e}parse(e){const t=(e=this.parse4in6(e)).match(_n.RE_BAD_CHARACTERS);if(t)throw new kn.AddressError((0,Pn.sprintf)("Bad character%s detected in address: %s",t.length>1?"s":"",t.join("")),e.replace(_n.RE_BAD_CHARACTERS,'<span class="parse-error">$1</span>'));const r=e.match(_n.RE_BAD_ADDRESS);if(r)throw new kn.AddressError((0,Pn.sprintf)("Address failed regex: %s",r.join("")),e.replace(_n.RE_BAD_ADDRESS,'<span class="parse-error">$1</span>'));let i=[];const n=e.split("::");if(2===n.length){let e=n[0].split(":"),t=n[1].split(":");1===e.length&&""===e[0]&&(e=[]),1===t.length&&""===t[0]&&(t=[]);const r=this.groups-(e.length+t.length);if(!r)throw new kn.AddressError("Error parsing groups");this.elidedGroups=r,this.elisionBegin=e.length,this.elisionEnd=e.length+this.elidedGroups,i=i.concat(e);for(let e=0;e<r;e++)i.push("0");i=i.concat(t)}else{if(1!==n.length)throw new kn.AddressError("Too many :: groups found");i=e.split(":"),this.elidedGroups=0}if(i=i.map((e=>(0,Pn.sprintf)("%x",parseInt(e,16)))),i.length!==this.groups)throw new kn.AddressError("Incorrect number of groups found");return i}canonicalForm(){return this.parsedAddress.map(Dn).join(":")}decimal(){return this.parsedAddress.map((e=>(0,Pn.sprintf)("%05d",parseInt(e,16)))).join(":")}bigInteger(){return new Tn.BigInteger(this.parsedAddress.map(Dn).join(""),16)}to4(){const e=this.binaryZeroPad().split("");return Cn.Address4.fromHex(new Tn.BigInteger(e.slice(96,128).join(""),2).toString(16))}to4in6(){const e=this.to4(),t=new xn(this.parsedAddress.slice(0,6).join(":"),6).correctForm();let r="";return/:$/.test(t)||(r=":"),t+r+e.address}inspectTeredo(){const e=this.getBitsBase16(0,32),t=this.getBits(80,96).xor(new Tn.BigInteger("ffff",16)).toString(),r=Cn.Address4.fromHex(this.getBitsBase16(32,64)),i=Cn.Address4.fromHex(this.getBits(96,128).xor(new Tn.BigInteger("ffffffff",16)).toString(16)),n=this.getBits(64,80),s=this.getBitsBase2(64,80),o=n.testBit(15),a=n.testBit(14),c=n.testBit(8),d=n.testBit(9),l=new Tn.BigInteger(s.slice(2,6)+s.slice(8,16),2).toString(10);return{prefix:(0,Pn.sprintf)("%s:%s",e.slice(0,4),e.slice(4,8)),server4:r.address,client4:i.address,flags:s,coneNat:o,microsoft:{reserved:a,universalLocal:d,groupIndividual:c,nonce:l},udpPort:t}}inspect6to4(){const e=this.getBitsBase16(0,16),t=Cn.Address4.fromHex(this.getBitsBase16(16,48));return{prefix:(0,Pn.sprintf)("%s",e.slice(0,4)),gateway:t.address}}to6to4(){if(!this.is4())return null;const e=["2002",this.getBitsBase16(96,112),this.getBitsBase16(112,128),"","/16"].join(":");return new xn(e)}toByteArray(){const e=this.bigInteger().toByteArray();return 17===e.length&&0===e[0]?e.slice(1):e}toUnsignedByteArray(){return this.toByteArray().map(In)}static fromByteArray(e){return this.fromUnsignedByteArray(e.map(In))}static fromUnsignedByteArray(e){const t=new Tn.BigInteger("256",10);let r=new Tn.BigInteger("0",10),i=new Tn.BigInteger("1",10);for(let n=e.length-1;n>=0;n--)r=r.add(i.multiply(new Tn.BigInteger(e[n].toString(10),10))),i=i.multiply(t);return xn.fromBigInteger(r)}isCanonical(){return this.addressMinusSuffix===this.canonicalForm()}isLinkLocal(){return"1111111010000000000000000000000000000000000000000000000000000000"===this.getBitsBase2(0,64)}isMulticast(){return"Multicast"===this.getType()}is4(){return this.v4}isTeredo(){return this.isInSubnet(new xn("2001::/32"))}is6to4(){return this.isInSubnet(new xn("2002::/16"))}isLoopback(){return"Loopback"===this.getType()}href(e){return e=void 0===e?"":(0,Pn.sprintf)(":%s",e),(0,Pn.sprintf)("http://[%s]%s/",this.correctForm(),e)}link(e){e||(e={}),void 0===e.className&&(e.className=""),void 0===e.prefix&&(e.prefix="/#address="),void 0===e.v4&&(e.v4=!1);let t=this.correctForm;return e.v4&&(t=this.to4in6),e.className?(0,Pn.sprintf)('<a href="%1$s%2$s" class="%3$s">%2$s</a>',e.prefix,t.call(this),e.className):(0,Pn.sprintf)('<a href="%1$s%2$s">%2$s</a>',e.prefix,t.call(this))}group(){if(0===this.elidedGroups)return Sn.simpleGroup(this.address).join(":");En("number"==typeof this.elidedGroups),En("number"==typeof this.elisionBegin);const e=[],[t,r]=this.address.split("::");t.length?e.push(...Sn.simpleGroup(t)):e.push("");const i=["hover-group"];for(let e=this.elisionBegin;e<this.elisionBegin+this.elidedGroups;e++)i.push((0,Pn.sprintf)("group-%d",e));return e.push((0,Pn.sprintf)('<span class="%s"></span>',i.join(" "))),r.length?e.push(...Sn.simpleGroup(r,this.elisionEnd)):e.push(""),this.is4()&&(En(this.address4 instanceof Cn.Address4),e.pop(),e.push(this.address4.groupForV6())),e.join(":")}regularExpressionString(e=!1){let t=[];const r=new xn(this.correctForm());if(0===r.elidedGroups)t.push((0,Rn.simpleRegularExpression)(r.parsedAddress));else if(r.elidedGroups===_n.GROUPS)t.push((0,Rn.possibleElisions)(_n.GROUPS));else{const e=r.address.split("::");e[0].length&&t.push((0,Rn.simpleRegularExpression)(e[0].split(":"))),En("number"==typeof r.elidedGroups),t.push((0,Rn.possibleElisions)(r.elidedGroups,0!==e[0].length,0!==e[1].length)),e[1].length&&t.push((0,Rn.simpleRegularExpression)(e[1].split(":"))),t=[t.join(":")]}return e||(t=["(?=^|",Rn.ADDRESS_BOUNDARY,"|[^\\w\\:])(",...t,")(?=[^\\w\\:]|",Rn.ADDRESS_BOUNDARY,"|$)"]),t.join("")}regularExpression(e=!1){return new RegExp(this.regularExpressionString(e),"i")}}tn.Address6=xn,function(e){var t=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),r=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),i=a&&a.__importStar||function(e){if(e&&e.__esModule)return e;var i={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&t(i,e,n);return r(i,e),i};Object.defineProperty(e,"__esModule",{value:!0}),e.v6=e.AddressError=e.Address6=e.Address4=void 0;const n=Ni;Object.defineProperty(e,"Address4",{enumerable:!0,get:function(){return n.Address4}});const s=tn;Object.defineProperty(e,"Address6",{enumerable:!0,get:function(){return s.Address6}});const o=zi;Object.defineProperty(e,"AddressError",{enumerable:!0,get:function(){return o.AddressError}});const c=i(nn);e.v6={helpers:c}}(Ai);var Mn={exports:{}};!function(e){(function(){var t,r,i,n,s,o,a,c;r={},null!==e&&e.exports?e.exports=r:this.ipaddr=r,a=function(e,t,r,i){var n,s;if(e.length!==t.length)throw new Error("ipaddr: cannot match CIDR for objects with different lengths");for(n=0;i>0;){if((s=r-i)<0&&(s=0),e[n]>>s!=t[n]>>s)return!1;i-=r,n+=1}return!0},r.subnetMatch=function(e,t,r){var i,n,s,o,a;for(s in null==r&&(r="unicast"),t)for(!(o=t[s])[0]||o[0]instanceof Array||(o=[o]),i=0,n=o.length;i<n;i++)if(a=o[i],e.kind()===a[0].kind()&&e.match.apply(e,a))return s;return r},r.IPv4=function(){function e(e){var t,r,i;if(4!==e.length)throw new Error("ipaddr: ipv4 octet count should be 4");for(t=0,r=e.length;t<r;t++)if(!(0<=(i=e[t])&&i<=255))throw new Error("ipaddr: ipv4 octet should fit in 8 bits");this.octets=e}return e.prototype.kind=function(){return"ipv4"},e.prototype.toString=function(){return this.octets.join(".")},e.prototype.toNormalizedString=function(){return this.toString()},e.prototype.toByteArray=function(){return this.octets.slice(0)},e.prototype.match=function(e,t){var r;if(void 0===t&&(e=(r=e)[0],t=r[1]),"ipv4"!==e.kind())throw new Error("ipaddr: cannot match ipv4 address with non-ipv4 one");return a(this.octets,e.octets,8,t)},e.prototype.SpecialRanges={unspecified:[[new e([0,0,0,0]),8]],broadcast:[[new e([255,255,255,255]),32]],multicast:[[new e([224,0,0,0]),4]],linkLocal:[[new e([169,254,0,0]),16]],loopback:[[new e([127,0,0,0]),8]],carrierGradeNat:[[new e([100,64,0,0]),10]],private:[[new e([10,0,0,0]),8],[new e([172,16,0,0]),12],[new e([192,168,0,0]),16]],reserved:[[new e([192,0,0,0]),24],[new e([192,0,2,0]),24],[new e([192,88,99,0]),24],[new e([198,51,100,0]),24],[new e([203,0,113,0]),24],[new e([240,0,0,0]),4]]},e.prototype.range=function(){return r.subnetMatch(this,this.SpecialRanges)},e.prototype.toIPv4MappedAddress=function(){return r.IPv6.parse("::ffff:"+this.toString())},e.prototype.prefixLengthFromSubnetMask=function(){var e,t,r,i,n,s,o;for(o={0:8,128:7,192:6,224:5,240:4,248:3,252:2,254:1,255:0},e=0,n=!1,t=r=3;r>=0;t=r+=-1){if(!((i=this.octets[t])in o))return null;if(s=o[i],n&&0!==s)return null;8!==s&&(n=!0),e+=s}return 32-e},e}(),i="(0?\\d+|0x[a-f0-9]+)",n={fourOctet:new RegExp("^"+i+"\\."+i+"\\."+i+"\\."+i+"$","i"),longValue:new RegExp("^"+i+"$","i")},r.IPv4.parser=function(e){var t,r,i,s,o;if(r=function(e){return"0"===e[0]&&"x"!==e[1]?parseInt(e,8):parseInt(e)},t=e.match(n.fourOctet))return function(){var e,n,s,o;for(o=[],e=0,n=(s=t.slice(1,6)).length;e<n;e++)i=s[e],o.push(r(i));return o}();if(t=e.match(n.longValue)){if((o=r(t[1]))>4294967295||o<0)throw new Error("ipaddr: address outside defined range");return function(){var e,t;for(t=[],s=e=0;e<=24;s=e+=8)t.push(o>>s&255);return t}().reverse()}return null},r.IPv6=function(){function e(e,t){var r,i,n,s,o,a;if(16===e.length)for(this.parts=[],r=i=0;i<=14;r=i+=2)this.parts.push(e[r]<<8|e[r+1]);else{if(8!==e.length)throw new Error("ipaddr: ipv6 part count should be 8 or 16");this.parts=e}for(n=0,s=(a=this.parts).length;n<s;n++)if(!(0<=(o=a[n])&&o<=65535))throw new Error("ipaddr: ipv6 part should fit in 16 bits");t&&(this.zoneId=t)}return e.prototype.kind=function(){return"ipv6"},e.prototype.toString=function(){return this.toNormalizedString().replace(/((^|:)(0(:|$))+)/,"::")},e.prototype.toRFC5952String=function(){var e,t,r,i,n;for(i=/((^|:)(0(:|$)){2,})/g,n=this.toNormalizedString(),e=0,t=-1;r=i.exec(n);)r[0].length>t&&(e=r.index,t=r[0].length);return t<0?n:n.substring(0,e)+"::"+n.substring(e+t)},e.prototype.toByteArray=function(){var e,t,r,i,n;for(e=[],t=0,r=(n=this.parts).length;t<r;t++)i=n[t],e.push(i>>8),e.push(255&i);return e},e.prototype.toNormalizedString=function(){var e,t,r;return e=function(){var e,r,i,n;for(n=[],e=0,r=(i=this.parts).length;e<r;e++)t=i[e],n.push(t.toString(16));return n}.call(this).join(":"),r="",this.zoneId&&(r="%"+this.zoneId),e+r},e.prototype.toFixedLengthString=function(){var e,t,r;return e=function(){var e,r,i,n;for(n=[],e=0,r=(i=this.parts).length;e<r;e++)t=i[e],n.push(t.toString(16).padStart(4,"0"));return n}.call(this).join(":"),r="",this.zoneId&&(r="%"+this.zoneId),e+r},e.prototype.match=function(e,t){var r;if(void 0===t&&(e=(r=e)[0],t=r[1]),"ipv6"!==e.kind())throw new Error("ipaddr: cannot match ipv6 address with non-ipv6 one");return a(this.parts,e.parts,16,t)},e.prototype.SpecialRanges={unspecified:[new e([0,0,0,0,0,0,0,0]),128],linkLocal:[new e([65152,0,0,0,0,0,0,0]),10],multicast:[new e([65280,0,0,0,0,0,0,0]),8],loopback:[new e([0,0,0,0,0,0,0,1]),128],uniqueLocal:[new e([64512,0,0,0,0,0,0,0]),7],ipv4Mapped:[new e([0,0,0,0,0,65535,0,0]),96],rfc6145:[new e([0,0,0,0,65535,0,0,0]),96],rfc6052:[new e([100,65435,0,0,0,0,0,0]),96],"6to4":[new e([8194,0,0,0,0,0,0,0]),16],teredo:[new e([8193,0,0,0,0,0,0,0]),32],reserved:[[new e([8193,3512,0,0,0,0,0,0]),32]]},e.prototype.range=function(){return r.subnetMatch(this,this.SpecialRanges)},e.prototype.isIPv4MappedAddress=function(){return"ipv4Mapped"===this.range()},e.prototype.toIPv4Address=function(){var e,t,i;if(!this.isIPv4MappedAddress())throw new Error("ipaddr: trying to convert a generic ipv6 address to ipv4");return e=(i=this.parts.slice(-2))[0],t=i[1],new r.IPv4([e>>8,255&e,t>>8,255&t])},e.prototype.prefixLengthFromSubnetMask=function(){var e,t,r,i,n,s,o;for(o={0:16,32768:15,49152:14,57344:13,61440:12,63488:11,64512:10,65024:9,65280:8,65408:7,65472:6,65504:5,65520:4,65528:3,65532:2,65534:1,65535:0},e=0,n=!1,t=r=7;r>=0;t=r+=-1){if(!((i=this.parts[t])in o))return null;if(s=o[i],n&&0!==s)return null;16!==s&&(n=!0),e+=s}return 128-e},e}(),s="(?:[0-9a-f]+::?)+",c="%[0-9a-z]{1,}",o={zoneIndex:new RegExp(c,"i"),native:new RegExp("^(::)?("+s+")?([0-9a-f]+)?(::)?("+c+")?$","i"),transitional:new RegExp("^((?:"+s+")|(?:::)(?:"+s+")?)"+i+"\\."+i+"\\."+i+"\\."+i+"("+c+")?$","i")},t=function(e,t){var r,i,n,s,a,c;if(e.indexOf("::")!==e.lastIndexOf("::"))return null;for((c=(e.match(o.zoneIndex)||[])[0])&&(c=c.substring(1),e=e.replace(/%.+$/,"")),r=0,i=-1;(i=e.indexOf(":",i+1))>=0;)r++;if("::"===e.substr(0,2)&&r--,"::"===e.substr(-2,2)&&r--,r>t)return null;for(a=t-r,s=":";a--;)s+="0:";return":"===(e=e.replace("::",s))[0]&&(e=e.slice(1)),":"===e[e.length-1]&&(e=e.slice(0,-1)),{parts:t=function(){var t,r,i,s;for(s=[],t=0,r=(i=e.split(":")).length;t<r;t++)n=i[t],s.push(parseInt(n,16));return s}(),zoneId:c}},r.IPv6.parser=function(e){var r,i,n,s,a,c,d;if(o.native.test(e))return t(e,8);if((s=e.match(o.transitional))&&(d=s[6]||"",(r=t(s[1].slice(0,-1)+d,6)).parts)){for(i=0,n=(c=[parseInt(s[2]),parseInt(s[3]),parseInt(s[4]),parseInt(s[5])]).length;i<n;i++)if(!(0<=(a=c[i])&&a<=255))return null;return r.parts.push(c[0]<<8|c[1]),r.parts.push(c[2]<<8|c[3]),{parts:r.parts,zoneId:r.zoneId}}return null},r.IPv4.isIPv4=r.IPv6.isIPv6=function(e){return null!==this.parser(e)},r.IPv4.isValid=function(e){try{return new this(this.parser(e)),!0}catch(e){return!1}},r.IPv4.isValidFourPartDecimal=function(e){return!(!r.IPv4.isValid(e)||!e.match(/^(0|[1-9]\d*)(\.(0|[1-9]\d*)){3}$/))},r.IPv6.isValid=function(e){var t;if("string"==typeof e&&-1===e.indexOf(":"))return!1;try{return new this((t=this.parser(e)).parts,t.zoneId),!0}catch(e){return!1}},r.IPv4.parse=function(e){var t;if(null===(t=this.parser(e)))throw new Error("ipaddr: string is not formatted like ip address");return new this(t)},r.IPv6.parse=function(e){var t;if(null===(t=this.parser(e)).parts)throw new Error("ipaddr: string is not formatted like ip address");return new this(t.parts,t.zoneId)},r.IPv4.parseCIDR=function(e){var t,r,i;if((r=e.match(/^(.+)\/(\d+)$/))&&(t=parseInt(r[2]))>=0&&t<=32)return i=[this.parse(r[1]),t],Object.defineProperty(i,"toString",{value:function(){return this.join("/")}}),i;throw new Error("ipaddr: string is not formatted like an IPv4 CIDR range")},r.IPv4.subnetMaskFromPrefixLength=function(e){var t,r,i;if((e=parseInt(e))<0||e>32)throw new Error("ipaddr: invalid IPv4 prefix length");for(i=[0,0,0,0],r=0,t=Math.floor(e/8);r<t;)i[r]=255,r++;return t<4&&(i[t]=Math.pow(2,e%8)-1<<8-e%8),new this(i)},r.IPv4.broadcastAddressFromCIDR=function(e){var t,r,i,n,s;try{for(i=(t=this.parseCIDR(e))[0].toByteArray(),s=this.subnetMaskFromPrefixLength(t[1]).toByteArray(),n=[],r=0;r<4;)n.push(parseInt(i[r],10)|255^parseInt(s[r],10)),r++;return new this(n)}catch(e){throw new Error("ipaddr: the address does not have IPv4 CIDR format")}},r.IPv4.networkAddressFromCIDR=function(e){var t,r,i,n,s;try{for(i=(t=this.parseCIDR(e))[0].toByteArray(),s=this.subnetMaskFromPrefixLength(t[1]).toByteArray(),n=[],r=0;r<4;)n.push(parseInt(i[r],10)&parseInt(s[r],10)),r++;return new this(n)}catch(e){throw new Error("ipaddr: the address does not have IPv4 CIDR format")}},r.IPv6.parseCIDR=function(e){var t,r,i;if((r=e.match(/^(.+)\/(\d+)$/))&&(t=parseInt(r[2]))>=0&&t<=128)return i=[this.parse(r[1]),t],Object.defineProperty(i,"toString",{value:function(){return this.join("/")}}),i;throw new Error("ipaddr: string is not formatted like an IPv6 CIDR range")},r.isValid=function(e){return r.IPv6.isValid(e)||r.IPv4.isValid(e)},r.parse=function(e){if(r.IPv6.isValid(e))return r.IPv6.parse(e);if(r.IPv4.isValid(e))return r.IPv4.parse(e);throw new Error("ipaddr: the address has neither IPv6 nor IPv4 format")},r.parseCIDR=function(e){try{return r.IPv6.parseCIDR(e)}catch(t){try{return r.IPv4.parseCIDR(e)}catch(e){throw new Error("ipaddr: the address has neither IPv6 nor IPv4 CIDR format")}}},r.fromByteArray=function(e){var t;if(4===(t=e.length))return new r.IPv4(e);if(16===t)return new r.IPv6(e);throw new Error("ipaddr: the binary input is neither an IPv6 nor IPv4 address")},r.process=function(e){var t;return"ipv6"===(t=this.parse(e)).kind()&&t.isIPv4MappedAddress()?t.toIPv4Address():t}}).call(a)}(Mn);var Ln=Mn.exports,jn=function(e,t){if("string"==typeof t)return An(e,t);if("object"==typeof t){for(var r=!1,i=0;i<t.length;i++)if(An(e,t[i])){r=!0;break}return r}};function An(e,t){try{var r=Ln.process(e);if(-1===t.indexOf("/")){var i=Ln.process(t);return"ipv6"===r.kind()&&"ipv6"===i.kind()?r.toNormalizedString()===i.toNormalizedString():r.toString()==i.toString()}var n=Ln.parseCIDR(t);return r.match(n)}catch(e){return!1}}var Nn=jn,Bn=/^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/,Fn=["0.0.0.0/8","10.0.0.0/8","100.64.0.0/10","127.0.0.0/8","169.254.0.0/16","172.16.0.0/12","192.0.0.0/24","192.0.2.0/24","192.168.0.0/16","198.18.0.0/15","198.51.100.0/24","203.0.113.0/24","224.0.0.0/3"],zn=["10.0.0.0/8","172.16.0.0/12","192.168.0.0/16"];for(var Vn=function(e){var t=[],r={originalIp:e,boiledIp:!1,isValid:!1,isBogon:!1,isApipa:!1,isMulticast:!1,isRfc1918:!1,isPublicIp:!1};if(Bn.test(e)){r.isValid=!0;for(var i=e.split("."),n=0;n<4;n++)t.push(parseInt(i[n],10));r.boiledIp=t.join("."),Nn(r.boiledIp,Fn)&&(r.isBogon=!0),Nn(r.boiledIp,"169.254.0.0/16")&&(r.isApipa=!0),Nn(r.boiledIp,"224.0.0.0/4")&&(r.isMulticast=!0),Nn(r.boiledIp,zn)?r.isRfc1918=!0:!1===r.isBogon&&(r.isPublicIp=!0)}return r},Un=c(Vn),$n={exports:{}},Gn=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[0-9a-f]{4}-[0-9a-f]{12}$/i,qn=[],Hn=0;Hn<256;Hn++)qn[Hn]=(Hn+256).toString(16).substr(1);$n.exports=function(e,t){var r;if(Buffer.isBuffer(e))r=function(e,t){var r=t||0,i=qn;return i[e[r++]]+i[e[r++]]+i[e[r++]]+i[e[r++]]+"-"+i[e[r++]]+i[e[r++]]+"-"+i[e[r++]]+i[e[r++]]+"-"+i[e[r++]]+i[e[r++]]+"-"+i[e[r++]]+i[e[r++]]+i[e[r++]]+i[e[r++]]+i[e[r++]]+i[e[r++]]}(e);else{if("[object String]"!==Object.prototype.toString.call(e))return!1;r=e}if(r=r.toLowerCase(),!Gn.test(r))return!1;if(void 0===t)t=Jn(r);else if(Jn(r)!==t)return!1;switch(t){case 1:case 2:return!0;case 3:case 4:case 5:return-1!==["8","9","a","b"].indexOf(r.charAt(19));default:throw new Error("Invalid version provided.")}};var Wn,Kn,Jn=$n.exports.version=function(e){return 0|e.charAt(14)},Xn=c($n.exports),Qn={},Zn={exports:{}};function Yn(){if(Kn)return Wn;Kn=1;var e=1e3,t=60*e,r=60*t,i=24*r,n=7*i,s=365.25*i;function o(e,t,r,i){var n=t>=1.5*r;return Math.round(e/r)+" "+i+(n?"s":"")}return Wn=function(a,c){c=c||{};var d=typeof a;if("string"===d&&a.length>0)return function(o){if((o=String(o)).length>100)return;var a=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(o);if(!a)return;var c=parseFloat(a[1]);switch((a[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return c*s;case"weeks":case"week":case"w":return c*n;case"days":case"day":case"d":return c*i;case"hours":case"hour":case"hrs":case"hr":case"h":return c*r;case"minutes":case"minute":case"mins":case"min":case"m":return c*t;case"seconds":case"second":case"secs":case"sec":case"s":return c*e;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return c;default:return}}(a);if("number"===d&&isFinite(a))return c.long?function(n){var s=Math.abs(n);if(s>=i)return o(n,s,i,"day");if(s>=r)return o(n,s,r,"hour");if(s>=t)return o(n,s,t,"minute");if(s>=e)return o(n,s,e,"second");return n+" ms"}(a):function(n){var s=Math.abs(n);if(s>=i)return Math.round(n/i)+"d";if(s>=r)return Math.round(n/r)+"h";if(s>=t)return Math.round(n/t)+"m";if(s>=e)return Math.round(n/e)+"s";return n+"ms"}(a);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(a))},Wn}var es=function(e){function t(e){let i,n,s,o=null;function a(...e){if(!a.enabled)return;const r=a,n=Number(new Date),s=n-(i||n);r.diff=s,r.prev=i,r.curr=n,i=n,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let o=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,((i,n)=>{if("%%"===i)return"%";o++;const s=t.formatters[n];if("function"==typeof s){const t=e[o];i=s.call(r,t),e.splice(o,1),o--}return i})),t.formatArgs.call(r,e);(r.log||t.log).apply(r,e)}return a.namespace=e,a.useColors=t.useColors(),a.color=t.selectColor(e),a.extend=r,a.destroy=t.destroy,Object.defineProperty(a,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==o?o:(n!==t.namespaces&&(n=t.namespaces,s=t.enabled(e)),s),set:e=>{o=e}}),"function"==typeof t.init&&t.init(a),a}function r(e,r){const i=t(this.namespace+(void 0===r?":":r)+e);return i.log=this.log,i}function i(e){return e.toString().substring(2,e.toString().length-2).replace(/\.\*\?$/,"*")}return t.debug=t,t.default=t,t.coerce=function(e){if(e instanceof Error)return e.stack||e.message;return e},t.disable=function(){const e=[...t.names.map(i),...t.skips.map(i).map((e=>"-"+e))].join(",");return t.enable(""),e},t.enable=function(e){let r;t.save(e),t.namespaces=e,t.names=[],t.skips=[];const i=("string"==typeof e?e:"").split(/[\s,]+/),n=i.length;for(r=0;r<n;r++)i[r]&&("-"===(e=i[r].replace(/\*/g,".*?"))[0]?t.skips.push(new RegExp("^"+e.slice(1)+"$")):t.names.push(new RegExp("^"+e+"$")))},t.enabled=function(e){if("*"===e[e.length-1])return!0;let r,i;for(r=0,i=t.skips.length;r<i;r++)if(t.skips[r].test(e))return!1;for(r=0,i=t.names.length;r<i;r++)if(t.names[r].test(e))return!0;return!1},t.humanize=Yn(),t.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(e).forEach((r=>{t[r]=e[r]})),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let r=0;for(let t=0;t<e.length;t++)r=(r<<5)-r+e.charCodeAt(t),r|=0;return t.colors[Math.abs(r)%t.colors.length]},t.enable(t.load()),t};!function(e,t){t.formatArgs=function(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;const r="color: "+this.color;t.splice(1,0,r,"color: inherit");let i=0,n=0;t[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(i++,"%c"===e&&(n=i))})),t.splice(n,0,r)},t.save=function(e){try{e?t.storage.setItem("debug",e):t.storage.removeItem("debug")}catch(e){}},t.load=function(){let e;try{e=t.storage.getItem("debug")}catch(e){}!e&&"undefined"!=typeof process&&"env"in process&&(e=process.env.DEBUG);return e},t.useColors=function(){if("undefined"!=typeof window&&window.process&&("renderer"===window.process.type||window.process.__nwjs))return!0;if("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let e;return"undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&(e=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(e[1],10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},t.storage=function(){try{return localStorage}catch(e){}}(),t.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],t.log=console.debug||console.log||(()=>{}),e.exports=es(t);const{formatters:r}=e.exports;r.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}(Zn,Zn.exports);var ts=Zn.exports,rs={},is={exports:{}};!function(e,t){!function(r,i){var n,s="",o="function",a="undefined",c="object",d="string",l="major",u="model",p="name",h="type",f="vendor",m="version",g="architecture",v="console",b="mobile",y="tablet",w="smarttv",_="wearable",S="xr",C="embedded",R="inapp",k="user-agent",T="brands",P="formFactors",E="fullVersionList",O="platform",D="platformVersion",I="bitness",x="sec-ch-ua",M=x+"-full-version-list",L=x+"-arch",j=x+"-"+I,A=x+"-form-factors",N=x+"-"+b,B=x+"-"+u,F=x+"-"+O,z=F+"-version",V=[T,E,b,u,O,D,g,P,I],U="browser",$="cpu",G="device",q="engine",H="os",W="result",K="Amazon",J="Apple",X="ASUS",Q="BlackBerry",Z="Google",Y="Huawei",ee="Lenovo",te="LG",re="Microsoft",ie="Motorola",ne="Samsung",se="Sharp",oe="Sony",ae="Xiaomi",ce="Zebra",de="Mobile ",le=" Browser",ue="Chrome",pe="Chromecast",he="Firefox",fe="Opera",me="Facebook",ge="Sogou",ve="Windows",be=typeof r!==a,ye=be&&r.navigator?r.navigator:i,we=ye&&ye.userAgentData?ye.userAgentData:i,_e=function(e){for(var t={},r=0;r<e.length;r++)t[e[r].toUpperCase()]=e[r];return t},Se=function(e,t){if(typeof e===c&&e.length>0){for(var r in e)if(Te(e[r])==Te(t))return!0;return!1}return!!Re(e)&&-1!==Te(t).indexOf(Te(e))},Ce=function(e,t){for(var r in e)return/^(browser|cpu|device|engine|os)$/.test(r)||!!t&&Ce(e[r])},Re=function(e){return typeof e===d},ke=function(e){if(!e)return i;for(var t=[],r=Oe(/\\?\"/g,e).split(","),n=0;n<r.length;n++)if(r[n].indexOf(";")>-1){var s=Ie(r[n]).split(";v=");t[n]={brand:s[0],version:s[1]}}else t[n]=Ie(r[n]);return t},Te=function(e){return Re(e)?e.toLowerCase():e},Pe=function(e){return Re(e)?Oe(/[^\d\.]/g,e).split(".")[0]:i},Ee=function(e){for(var t in e){var r=e[t];typeof r==c&&2==r.length?this[r[0]]=r[1]:this[r]=i}return this},Oe=function(e,t){return Re(t)?t.replace(e,s):t},De=function(e){return Oe(/\\?\"/g,e)},Ie=function(e,t){if(Re(e))return e=Oe(/^\s\s*/,e),typeof t===a?e:e.substring(0,500)},xe=function(e,t){if(e&&t)for(var r,n,s,a,d,l,u=0;u<t.length&&!d;){var p=t[u],h=t[u+1];for(r=n=0;r<p.length&&!d&&p[r];)if(d=p[r++].exec(e))for(s=0;s<h.length;s++)l=d[++n],typeof(a=h[s])===c&&a.length>0?2===a.length?typeof a[1]==o?this[a[0]]=a[1].call(this,l):this[a[0]]=a[1]:3===a.length?typeof a[1]!==o||a[1].exec&&a[1].test?this[a[0]]=l?l.replace(a[1],a[2]):i:this[a[0]]=l?a[1].call(this,l,a[2]):i:4===a.length&&(this[a[0]]=l?a[3].call(this,l.replace(a[1],a[2])):i):this[a]=l||i;u+=2}},Me=function(e,t){for(var r in t)if(typeof t[r]===c&&t[r].length>0){for(var n=0;n<t[r].length;n++)if(Se(t[r][n],e))return"?"===r?i:r}else if(Se(t[r],e))return"?"===r?i:r;return t.hasOwnProperty("*")?t["*"]:e},Le={ME:"4.90","NT 3.11":"NT3.51","NT 4.0":"NT4.0",2e3:"NT 5.0",XP:["NT 5.1","NT 5.2"],Vista:"NT 6.0",7:"NT 6.1",8:"NT 6.2",8.1:"NT 6.3",10:["NT 6.4","NT 10.0"],RT:"ARM"},je={embedded:"Automotive",mobile:"Mobile",tablet:["Tablet","EInk"],smarttv:"TV",wearable:"Watch",xr:["VR","XR"],"?":["Desktop","Unknown"],"*":i},Ae={browser:[[/\b(?:crmo|crios)\/([\w\.]+)/i],[m,[p,de+"Chrome"]],[/edg(?:e|ios|a)?\/([\w\.]+)/i],[m,[p,"Edge"]],[/(opera mini)\/([-\w\.]+)/i,/(opera [mobiletab]{3,6})\b.+version\/([-\w\.]+)/i,/(opera)(?:.+version\/|[\/ ]+)([\w\.]+)/i],[p,m],[/opios[\/ ]+([\w\.]+)/i],[m,[p,fe+" Mini"]],[/\bop(?:rg)?x\/([\w\.]+)/i],[m,[p,fe+" GX"]],[/\bopr\/([\w\.]+)/i],[m,[p,fe]],[/\bb[ai]*d(?:uhd|[ub]*[aekoprswx]{5,6})[\/ ]?([\w\.]+)/i],[m,[p,"Baidu"]],[/\b(?:mxbrowser|mxios|myie2)\/?([-\w\.]*)\b/i],[m,[p,"Maxthon"]],[/(kindle)\/([\w\.]+)/i,/(lunascape|maxthon|netfront|jasmine|blazer|sleipnir)[\/ ]?([\w\.]*)/i,/(avant|iemobile|slim(?:browser|boat|jet))[\/ ]?([\d\.]*)/i,/(?:ms|\()(ie) ([\w\.]+)/i,/(flock|rockmelt|midori|epiphany|silk|skyfire|ovibrowser|bolt|iron|vivaldi|iridium|phantomjs|bowser|qupzilla|falkon|rekonq|puffin|brave|whale(?!.+naver)|qqbrowserlite|duckduckgo|klar|helio|(?=comodo_)?dragon)\/([-\w\.]+)/i,/(heytap|ovi|115)browser\/([\d\.]+)/i,/(weibo)__([\d\.]+)/i],[p,m],[/quark(?:pc)?\/([-\w\.]+)/i],[m,[p,"Quark"]],[/\bddg\/([\w\.]+)/i],[m,[p,"DuckDuckGo"]],[/(?:\buc? ?browser|(?:juc.+)ucweb)[\/ ]?([\w\.]+)/i],[m,[p,"UCBrowser"]],[/microm.+\bqbcore\/([\w\.]+)/i,/\bqbcore\/([\w\.]+).+microm/i,/micromessenger\/([\w\.]+)/i],[m,[p,"WeChat"]],[/konqueror\/([\w\.]+)/i],[m,[p,"Konqueror"]],[/trident.+rv[: ]([\w\.]{1,9})\b.+like gecko/i],[m,[p,"IE"]],[/ya(?:search)?browser\/([\w\.]+)/i],[m,[p,"Yandex"]],[/slbrowser\/([\w\.]+)/i],[m,[p,"Smart "+ee+le]],[/(avast|avg)\/([\w\.]+)/i],[[p,/(.+)/,"$1 Secure"+le],m],[/\bfocus\/([\w\.]+)/i],[m,[p,he+" Focus"]],[/\bopt\/([\w\.]+)/i],[m,[p,fe+" Touch"]],[/coc_coc\w+\/([\w\.]+)/i],[m,[p,"Coc Coc"]],[/dolfin\/([\w\.]+)/i],[m,[p,"Dolphin"]],[/coast\/([\w\.]+)/i],[m,[p,fe+" Coast"]],[/miuibrowser\/([\w\.]+)/i],[m,[p,"MIUI"+le]],[/fxios\/([\w\.-]+)/i],[m,[p,de+he]],[/\bqihoobrowser\/?([\w\.]*)/i],[m,[p,"360"]],[/\b(qq)\/([\w\.]+)/i],[[p,/(.+)/,"$1Browser"],m],[/(oculus|sailfish|huawei|vivo|pico)browser\/([\w\.]+)/i],[[p,/(.+)/,"$1"+le],m],[/samsungbrowser\/([\w\.]+)/i],[m,[p,ne+" Internet"]],[/metasr[\/ ]?([\d\.]+)/i],[m,[p,ge+" Explorer"]],[/(sogou)mo\w+\/([\d\.]+)/i],[[p,ge+" Mobile"],m],[/(electron)\/([\w\.]+) safari/i,/(tesla)(?: qtcarbrowser|\/(20\d\d\.[-\w\.]+))/i,/m?(qqbrowser|2345(?=browser|chrome|explorer))\w*[\/ ]?v?([\w\.]+)/i],[p,m],[/(lbbrowser|rekonq)/i],[p],[/ome\/([\w\.]+) \w* ?(iron) saf/i,/ome\/([\w\.]+).+qihu (360)[es]e/i],[m,p],[/((?:fban\/fbios|fb_iab\/fb4a)(?!.+fbav)|;fbav\/([\w\.]+);)/i],[[p,me],m,[h,R]],[/(Klarna)\/([\w\.]+)/i,/(kakao(?:talk|story))[\/ ]([\w\.]+)/i,/(naver)\(.*?(\d+\.[\w\.]+).*\)/i,/safari (line)\/([\w\.]+)/i,/\b(line)\/([\w\.]+)\/iab/i,/(alipay)client\/([\w\.]+)/i,/(twitter)(?:and| f.+e\/([\w\.]+))/i,/(instagram|snapchat)[\/ ]([-\w\.]+)/i],[p,m,[h,R]],[/\bgsa\/([\w\.]+) .*safari\//i],[m,[p,"GSA"],[h,R]],[/musical_ly(?:.+app_?version\/|_)([\w\.]+)/i],[m,[p,"TikTok"],[h,R]],[/\[(linkedin)app\]/i],[p,[h,R]],[/(chromium)[\/ ]([-\w\.]+)/i],[p,m],[/headlesschrome(?:\/([\w\.]+)| )/i],[m,[p,ue+" Headless"]],[/ wv\).+(chrome)\/([\w\.]+)/i],[[p,ue+" WebView"],m],[/droid.+ version\/([\w\.]+)\b.+(?:mobile safari|safari)/i],[m,[p,"Android"+le]],[/chrome\/([\w\.]+) mobile/i],[m,[p,de+"Chrome"]],[/(chrome|omniweb|arora|[tizenoka]{5} ?browser)\/v?([\w\.]+)/i],[p,m],[/version\/([\w\.\,]+) .*mobile(?:\/\w+ | ?)safari/i],[m,[p,de+"Safari"]],[/iphone .*mobile(?:\/\w+ | ?)safari/i],[[p,de+"Safari"]],[/version\/([\w\.\,]+) .*(safari)/i],[m,p],[/webkit.+?(mobile ?safari|safari)(\/[\w\.]+)/i],[p,[m,"1"]],[/(webkit|khtml)\/([\w\.]+)/i],[p,m],[/(?:mobile|tablet);.*(firefox)\/([\w\.-]+)/i],[[p,de+he],m],[/(navigator|netscape\d?)\/([-\w\.]+)/i],[[p,"Netscape"],m],[/(wolvic|librewolf)\/([\w\.]+)/i],[p,m],[/mobile vr; rv:([\w\.]+)\).+firefox/i],[m,[p,he+" Reality"]],[/ekiohf.+(flow)\/([\w\.]+)/i,/(swiftfox)/i,/(icedragon|iceweasel|camino|chimera|fennec|maemo browser|minimo|conkeror)[\/ ]?([\w\.\+]+)/i,/(seamonkey|k-meleon|icecat|iceape|firebird|phoenix|palemoon|basilisk|waterfox)\/([-\w\.]+)$/i,/(firefox)\/([\w\.]+)/i,/(mozilla)\/([\w\.]+) .+rv\:.+gecko\/\d+/i,/(polaris|lynx|dillo|icab|doris|amaya|w3m|netsurf|obigo|mosaic|(?:go|ice|up)[\. ]?browser)[-\/ ]?v?([\w\.]+)/i,/\b(links) \(([\w\.]+)/i],[p,[m,/_/g,"."]],[/(cobalt)\/([\w\.]+)/i],[p,[m,/[^\d\.]+./,s]]],cpu:[[/\b(?:(amd|x|x86[-_]?|wow|win)64)\b/i],[[g,"amd64"]],[/(ia32(?=;))/i,/((?:i[346]|x)86)[;\)]/i],[[g,"ia32"]],[/\b(aarch64|arm(v?8e?l?|_?64))\b/i],[[g,"arm64"]],[/\b(arm(?:v[67])?ht?n?[fl]p?)\b/i],[[g,"armhf"]],[/windows (ce|mobile); ppc;/i],[[g,"arm"]],[/((?:ppc|powerpc)(?:64)?)(?: mac|;|\))/i],[[g,/ower/,s,Te]],[/(sun4\w)[;\)]/i],[[g,"sparc"]],[/((?:avr32|ia64(?=;))|68k(?=\))|\barm(?=v(?:[1-7]|[5-7]1)l?|;|eabi)|(?=atmel )avr|(?:irix|mips|sparc)(?:64)?\b|pa-risc)/i],[[g,Te]]],device:[[/\b(sch-i[89]0\d|shw-m380s|sm-[ptx]\w{2,4}|gt-[pn]\d{2,4}|sgh-t8[56]9|nexus 10)/i],[u,[f,ne],[h,y]],[/\b((?:s[cgp]h|gt|sm)-(?![lr])\w+|sc[g-]?[\d]+a?|galaxy nexus)/i,/samsung[- ]((?!sm-[lr])[-\w]+)/i,/sec-(sgh\w+)/i],[u,[f,ne],[h,b]],[/(?:\/|\()(ip(?:hone|od)[\w, ]*)(?:\/|;)/i],[u,[f,J],[h,b]],[/\((ipad);[-\w\),; ]+apple/i,/applecoremedia\/[\w\.]+ \((ipad)/i,/\b(ipad)\d\d?,\d\d?[;\]].+ios/i],[u,[f,J],[h,y]],[/(macintosh);/i],[u,[f,J]],[/\b(sh-?[altvz]?\d\d[a-ekm]?)/i],[u,[f,se],[h,b]],[/(?:honor)([-\w ]+)[;\)]/i],[u,[f,"Honor"],[h,b]],[/\b((?:ag[rs][23]?|bah2?|sht?|btv)-a?[lw]\d{2})\b(?!.+d\/s)/i],[u,[f,Y],[h,y]],[/(?:huawei)([-\w ]+)[;\)]/i,/\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][012359c][adn]?)\b(?!.+d\/s)/i],[u,[f,Y],[h,b]],[/\b(poco[\w ]+|m2\d{3}j\d\d[a-z]{2})(?: bui|\))/i,/\b; (\w+) build\/hm\1/i,/\b(hm[-_ ]?note?[_ ]?(?:\d\w)?) bui/i,/\b(redmi[\-_ ]?(?:note|k)?[\w_ ]+)(?: bui|\))/i,/oid[^\)]+; (m?[12][0-389][01]\w{3,6}[c-y])( bui|; wv|\))/i,/\b(mi[-_ ]?(?:a\d|one|one[_ ]plus|note lte|max|cc)?[_ ]?(?:\d?\w?)[_ ]?(?:plus|se|lite|pro)?)(?: bui|\))/i],[[u,/_/g," "],[f,ae],[h,b]],[/oid[^\)]+; (2\d{4}(283|rpbf)[cgl])( bui|\))/i,/\b(mi[-_ ]?(?:pad)(?:[\w_ ]+))(?: bui|\))/i],[[u,/_/g," "],[f,ae],[h,y]],[/; (\w+) bui.+ oppo/i,/\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i],[u,[f,"OPPO"],[h,b]],[/\b(opd2\d{3}a?) bui/i],[u,[f,"OPPO"],[h,y]],[/vivo (\w+)(?: bui|\))/i,/\b(v[12]\d{3}\w?[at])(?: bui|;)/i],[u,[f,"Vivo"],[h,b]],[/\b(rmx[1-3]\d{3})(?: bui|;|\))/i],[u,[f,"Realme"],[h,b]],[/\b(milestone|droid(?:[2-4x]| (?:bionic|x2|pro|razr))?:?( 4g)?)\b[\w ]+build\//i,/\bmot(?:orola)?[- ](\w*)/i,/((?:moto[\w\(\) ]+|xt\d{3,4}|nexus 6)(?= bui|\)))/i],[u,[f,ie],[h,b]],[/\b(mz60\d|xoom[2 ]{0,2}) build\//i],[u,[f,ie],[h,y]],[/((?=lg)?[vl]k\-?\d{3}) bui| 3\.[-\w; ]{10}lg?-([06cv9]{3,4})/i],[u,[f,te],[h,y]],[/(lm(?:-?f100[nv]?|-[\w\.]+)(?= bui|\))|nexus [45])/i,/\blg[-e;\/ ]+((?!browser|netcast|android tv)\w+)/i,/\blg-?([\d\w]+) bui/i],[u,[f,te],[h,b]],[/(ideatab[-\w ]+)/i,/lenovo ?(s[56]000[-\w]+|tab(?:[\w ]+)|yt[-\d\w]{6}|tb[-\d\w]{6})/i],[u,[f,ee],[h,y]],[/(?:maemo|nokia).*(n900|lumia \d+)/i,/nokia[-_ ]?([-\w\.]*)/i],[[u,/_/g," "],[f,"Nokia"],[h,b]],[/(pixel c)\b/i],[u,[f,Z],[h,y]],[/droid.+; (pixel[\daxl ]{0,6})(?: bui|\))/i],[u,[f,Z],[h,b]],[/droid.+; (a?\d[0-2]{2}so|[c-g]\d{4}|so[-gl]\w+|xq-a\w[4-7][12])(?= bui|\).+chrome\/(?![1-6]{0,1}\d\.))/i],[u,[f,oe],[h,b]],[/sony tablet [ps]/i,/\b(?:sony)?sgp\w+(?: bui|\))/i],[[u,"Xperia Tablet"],[f,oe],[h,y]],[/ (kb2005|in20[12]5|be20[12][59])\b/i,/(?:one)?(?:plus)? (a\d0\d\d)(?: b|\))/i],[u,[f,"OnePlus"],[h,b]],[/(alexa)webm/i,/(kf[a-z]{2}wi|aeo(?!bc)\w\w)( bui|\))/i,/(kf[a-z]+)( bui|\)).+silk\//i],[u,[f,K],[h,y]],[/((?:sd|kf)[0349hijorstuw]+)( bui|\)).+silk\//i],[[u,/(.+)/g,"Fire Phone $1"],[f,K],[h,b]],[/(playbook);[-\w\),; ]+(rim)/i],[u,f,[h,y]],[/\b((?:bb[a-f]|st[hv])100-\d)/i,/\(bb10; (\w+)/i],[u,[f,Q],[h,b]],[/(?:\b|asus_)(transfo[prime ]{4,10} \w+|eeepc|slider \w+|nexus 7|padfone|p00[cj])/i],[u,[f,X],[h,y]],[/ (z[bes]6[027][012][km][ls]|zenfone \d\w?)\b/i],[u,[f,X],[h,b]],[/(nexus 9)/i],[u,[f,"HTC"],[h,y]],[/(htc)[-;_ ]{1,2}([\w ]+(?=\)| bui)|\w+)/i,/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,/(alcatel|geeksphone|nexian|panasonic(?!(?:;|\.))|sony(?!-bra))[-_ ]?([-\w]*)/i],[f,[u,/_/g," "],[h,b]],[/tcl (xess p17aa)/i,/droid [\w\.]+; ((?:8[14]9[16]|9(?:0(?:48|60|8[01])|1(?:3[27]|66)|2(?:6[69]|9[56])|466))[gqswx])(_\w(\w|\w\w))?(\)| bui)/i],[u,[f,"TCL"],[h,y]],[/droid [\w\.]+; (418(?:7d|8v)|5087z|5102l|61(?:02[dh]|25[adfh]|27[ai]|56[dh]|59k|65[ah])|a509dl|t(?:43(?:0w|1[adepqu])|50(?:6d|7[adju])|6(?:09dl|10k|12b|71[efho]|76[hjk])|7(?:66[ahju]|67[hw]|7[045][bh]|71[hk]|73o|76[ho]|79w|81[hks]?|82h|90[bhsy]|99b)|810[hs]))(_\w(\w|\w\w))?(\)| bui)/i],[u,[f,"TCL"],[h,b]],[/(itel) ((\w+))/i],[[f,Te],u,[h,Me,{tablet:["p10001l","w7001"],"*":"mobile"}]],[/droid.+; ([ab][1-7]-?[0178a]\d\d?)/i],[u,[f,"Acer"],[h,y]],[/droid.+; (m[1-5] note) bui/i,/\bmz-([-\w]{2,})/i],[u,[f,"Meizu"],[h,b]],[/; ((?:power )?armor(?:[\w ]{0,8}))(?: bui|\))/i],[u,[f,"Ulefone"],[h,b]],[/; (energy ?\w+)(?: bui|\))/i,/; energizer ([\w ]+)(?: bui|\))/i],[u,[f,"Energizer"],[h,b]],[/; cat (b35);/i,/; (b15q?|s22 flip|s48c|s62 pro)(?: bui|\))/i],[u,[f,"Cat"],[h,b]],[/((?:new )?andromax[\w- ]+)(?: bui|\))/i],[u,[f,"Smartfren"],[h,b]],[/droid.+; (a(?:015|06[35]|142p?))/i],[u,[f,"Nothing"],[h,b]],[/(blackberry|benq|palm(?=\-)|sonyericsson|acer|asus|dell|meizu|motorola|polytron|infinix|tecno|micromax|advan)[-_ ]?([-\w]*)/i,/; (imo) ((?!tab)[\w ]+?)(?: bui|\))/i,/(hp) ([\w ]+\w)/i,/(asus)-?(\w+)/i,/(microsoft); (lumia[\w ]+)/i,/(lenovo)[-_ ]?([-\w]+)/i,/(jolla)/i,/(oppo) ?([\w ]+) bui/i],[f,u,[h,b]],[/(imo) (tab \w+)/i,/(kobo)\s(ereader|touch)/i,/(archos) (gamepad2?)/i,/(hp).+(touchpad(?!.+tablet)|tablet)/i,/(kindle)\/([\w\.]+)/i],[f,u,[h,y]],[/(surface duo)/i],[u,[f,re],[h,y]],[/droid [\d\.]+; (fp\du?)(?: b|\))/i],[u,[f,"Fairphone"],[h,b]],[/(shield[\w ]+) b/i],[u,[f,"Nvidia"],[h,y]],[/(sprint) (\w+)/i],[f,u,[h,b]],[/(kin\.[onetw]{3})/i],[[u,/\./g," "],[f,re],[h,b]],[/droid.+; ([c6]+|et5[16]|mc[239][23]x?|vc8[03]x?)\)/i],[u,[f,ce],[h,y]],[/droid.+; (ec30|ps20|tc[2-8]\d[kx])\)/i],[u,[f,ce],[h,b]],[/smart-tv.+(samsung)/i],[f,[h,w]],[/hbbtv.+maple;(\d+)/i],[[u,/^/,"SmartTV"],[f,ne],[h,w]],[/(nux; netcast.+smarttv|lg (netcast\.tv-201\d|android tv))/i],[[f,te],[h,w]],[/(apple) ?tv/i],[f,[u,J+" TV"],[h,w]],[/crkey.*devicetype\/chromecast/i],[[u,pe+" Third Generation"],[f,Z],[h,w]],[/crkey.*devicetype\/([^/]*)/i],[[u,/^/,"Chromecast "],[f,Z],[h,w]],[/fuchsia.*crkey/i],[[u,pe+" Nest Hub"],[f,Z],[h,w]],[/crkey/i],[[u,pe],[f,Z],[h,w]],[/droid.+aft(\w+)( bui|\))/i],[u,[f,K],[h,w]],[/\(dtv[\);].+(aquos)/i,/(aquos-tv[\w ]+)\)/i],[u,[f,se],[h,w]],[/(bravia[\w ]+)( bui|\))/i],[u,[f,oe],[h,w]],[/(mitv-\w{5}) bui/i],[u,[f,ae],[h,w]],[/Hbbtv.*(technisat) (.*);/i],[f,u,[h,w]],[/\b(roku)[\dx]*[\)\/]((?:dvp-)?[\d\.]*)/i,/hbbtv\/\d+\.\d+\.\d+ +\([\w\+ ]*; *([\w\d][^;]*);([^;]*)/i],[[f,Ie],[u,Ie],[h,w]],[/\b(android tv|smart[- ]?tv|opera tv|tv; rv:)\b/i],[[h,w]],[/(ouya)/i,/(nintendo) (\w+)/i],[f,u,[h,v]],[/droid.+; (shield) bui/i],[u,[f,"Nvidia"],[h,v]],[/(playstation \w+)/i],[u,[f,oe],[h,v]],[/\b(xbox(?: one)?(?!; xbox))[\); ]/i],[u,[f,re],[h,v]],[/\b(sm-[lr]\d\d[05][fnuw]?s?)\b/i],[u,[f,ne],[h,_]],[/((pebble))app/i],[f,u,[h,_]],[/(watch)(?: ?os[,\/]|\d,\d\/)[\d\.]+/i],[u,[f,J],[h,_]],[/droid.+; (wt63?0{2,3})\)/i],[u,[f,ce],[h,_]],[/droid.+; (glass) \d/i],[u,[f,Z],[h,S]],[/(pico) (4|neo3(?: link|pro)?)/i],[f,u,[h,S]],[/; (quest( \d| pro)?)/i],[u,[f,me],[h,S]],[/(tesla)(?: qtcarbrowser|\/[-\w\.]+)/i],[f,[h,C]],[/(aeobc)\b/i],[u,[f,K],[h,C]],[/droid .+?; ([^;]+?)(?: bui|; wv\)|\) applew).+? mobile safari/i],[u,[h,b]],[/droid .+?; ([^;]+?)(?: bui|\) applew).+?(?! mobile) safari/i],[u,[h,y]],[/\b((tablet|tab)[;\/]|focus\/\d(?!.+mobile))/i],[[h,y]],[/(phone|mobile(?:[;\/]| [ \w\/\.]*safari)|pda(?=.+windows ce))/i],[[h,b]],[/(android[-\w\. ]{0,9});.+buil/i],[u,[f,"Generic"]]],engine:[[/windows.+ edge\/([\w\.]+)/i],[m,[p,"EdgeHTML"]],[/(arkweb)\/([\w\.]+)/i],[p,m],[/webkit\/537\.36.+chrome\/(?!27)([\w\.]+)/i],[m,[p,"Blink"]],[/(presto)\/([\w\.]+)/i,/(webkit|trident|netfront|netsurf|amaya|lynx|w3m|goanna|servo)\/([\w\.]+)/i,/ekioh(flow)\/([\w\.]+)/i,/(khtml|tasman|links)[\/ ]\(?([\w\.]+)/i,/(icab)[\/ ]([23]\.[\d\.]+)/i,/\b(libweb)/i],[p,m],[/rv\:([\w\.]{1,9})\b.+(gecko)/i],[m,p]],os:[[/microsoft (windows) (vista|xp)/i],[p,m],[/(windows (?:phone(?: os)?|mobile))[\/ ]?([\d\.\w ]*)/i],[p,[m,Me,Le]],[/windows nt 6\.2; (arm)/i,/windows[\/ ]?([ntce\d\. ]+\w)(?!.+xbox)/i,/(?:win(?=3|9|n)|win 9x )([nt\d\.]+)/i],[[m,Me,Le],[p,ve]],[/ip[honead]{2,4}\b(?:.*os ([\w]+) like mac|; opera)/i,/(?:ios;fbsv\/|iphone.+ios[\/ ])([\d\.]+)/i,/cfnetwork\/.+darwin/i],[[m,/_/g,"."],[p,"iOS"]],[/(mac os x) ?([\w\. ]*)/i,/(macintosh|mac_powerpc\b)(?!.+haiku)/i],[[p,"macOS"],[m,/_/g,"."]],[/android ([\d\.]+).*crkey/i],[m,[p,pe+" Android"]],[/fuchsia.*crkey\/([\d\.]+)/i],[m,[p,pe+" Fuchsia"]],[/crkey\/([\d\.]+).*devicetype\/smartspeaker/i],[m,[p,pe+" SmartSpeaker"]],[/linux.*crkey\/([\d\.]+)/i],[m,[p,pe+" Linux"]],[/crkey\/([\d\.]+)/i],[m,[p,pe]],[/droid ([\w\.]+)\b.+(android[- ]x86|harmonyos)/i],[m,p],[/(android|webos|qnx|bada|rim tablet os|maemo|meego|sailfish|openharmony)[-\/ ]?([\w\.]*)/i,/(blackberry)\w*\/([\w\.]*)/i,/(tizen|kaios)[\/ ]([\w\.]+)/i,/\((series40);/i],[p,m],[/\(bb(10);/i],[m,[p,Q]],[/(?:symbian ?os|symbos|s60(?=;)|series60)[-\/ ]?([\w\.]*)/i],[m,[p,"Symbian"]],[/mozilla\/[\d\.]+ \((?:mobile|tablet|tv|mobile; [\w ]+); rv:.+ gecko\/([\w\.]+)/i],[m,[p,he+" OS"]],[/web0s;.+rt(tv)/i,/\b(?:hp)?wos(?:browser)?\/([\w\.]+)/i],[m,[p,"webOS"]],[/watch(?: ?os[,\/]|\d,\d\/)([\d\.]+)/i],[m,[p,"watchOS"]],[/(cros) [\w]+(?:\)| ([\w\.]+)\b)/i],[[p,"Chrome OS"],m],[/panasonic;(viera)/i,/(netrange)mmh/i,/(nettv)\/(\d+\.[\w\.]+)/i,/(nintendo|playstation) (\w+)/i,/(xbox); +xbox ([^\);]+)/i,/(pico) .+os([\w\.]+)/i,/\b(joli|palm)\b ?(?:os)?\/?([\w\.]*)/i,/(mint)[\/\(\) ]?(\w*)/i,/(mageia|vectorlinux)[; ]/i,/([kxln]?ubuntu|debian|suse|opensuse|gentoo|arch(?= linux)|slackware|fedora|mandriva|centos|pclinuxos|red ?hat|zenwalk|linpus|raspbian|plan 9|minix|risc os|contiki|deepin|manjaro|elementary os|sabayon|linspire)(?: gnu\/linux)?(?: enterprise)?(?:[- ]linux)?(?:-gnu)?[-\/ ]?(?!chrom|package)([-\w\.]*)/i,/(hurd|linux) ?([\w\.]*)/i,/(gnu) ?([\w\.]*)/i,/\b([-frentopcghs]{0,5}bsd|dragonfly)[\/ ]?(?!amd|[ix346]{1,2}86)([\w\.]*)/i,/(haiku) (\w+)/i],[p,m],[/(sunos) ?([\w\.\d]*)/i],[[p,"Solaris"],m],[/((?:open)?solaris)[-\/ ]?([\w\.]*)/i,/(aix) ((\d)(?=\.|\)| )[\w\.])*/i,/\b(beos|os\/2|amigaos|morphos|openvms|fuchsia|hp-ux|serenityos)/i,/(unix) ?([\w\.]*)/i],[p,m]]},Ne=(n={init:{},isIgnore:{},isIgnoreRgx:{},toString:{}},Ee.call(n.init,[[U,[p,m,l,h]],[$,[g]],[G,[h,u,f]],[q,[p,m]],[H,[p,m]]]),Ee.call(n.isIgnore,[[U,[m,l]],[q,[m]],[H,[m]]]),Ee.call(n.isIgnoreRgx,[[U,/ ?browser$/i],[H,/ ?os$/i]]),Ee.call(n.toString,[[U,[p,m]],[$,[g]],[G,[f,u]],[q,[p,m]],[H,[p,m]]]),n),Be=function(e,t){var r=Ne.init[t],i=Ne.isIgnore[t]||0,n=Ne.isIgnoreRgx[t]||0,o=Ne.toString[t]||0;function c(){Ee.call(this,r)}return c.prototype.getItem=function(){return e},c.prototype.withClientHints=function(){return we?we.getHighEntropyValues(V).then((function(t){return e.setCH(new Fe(t,!1)).parseCH().get()})):e.parseCH().get()},c.prototype.withFeatureCheck=function(){return e.detectFeature().get()},t!=W&&(c.prototype.is=function(e){var t=!1;for(var r in this)if(this.hasOwnProperty(r)&&!Se(i,r)&&Te(n?Oe(n,this[r]):this[r])==Te(n?Oe(n,e):e)){if(t=!0,e!=a)break}else if(e==a&&t){t=!t;break}return t},c.prototype.toString=function(){var e=s;for(var t in o)typeof this[o[t]]!==a&&(e+=(e?" ":s)+this[o[t]]);return e||a}),we||(c.prototype.then=function(e){var t=this,r=function(){for(var e in t)t.hasOwnProperty(e)&&(this[e]=t[e])};r.prototype={is:c.prototype.is,toString:c.prototype.toString};var i=new r;return e(i),i}),new c};function Fe(e,t){if(e=e||{},Ee.call(this,V),t)Ee.call(this,[[T,ke(e[x])],[E,ke(e[M])],[b,/\?1/.test(e[N])],[u,De(e[B])],[O,De(e[F])],[D,De(e[z])],[g,De(e[L])],[P,ke(e[A])],[I,De(e[j])]]);else for(var r in e)this.hasOwnProperty(r)&&typeof e[r]!==a&&(this[r]=e[r])}function ze(e,t,r,n){return this.get=function(e){return e?this.data.hasOwnProperty(e)?this.data[e]:i:this.data},this.set=function(e,t){return this.data[e]=t,this},this.setCH=function(e){return this.uaCH=e,this},this.detectFeature=function(){if(ye&&ye.userAgent==this.ua)switch(this.itemType){case U:ye.brave&&typeof ye.brave.isBrave==o&&this.set(p,"Brave");break;case G:!this.get(h)&&we&&we[b]&&this.set(h,b),"Macintosh"==this.get(u)&&ye&&typeof ye.standalone!==a&&ye.maxTouchPoints&&ye.maxTouchPoints>2&&this.set(u,"iPad").set(h,y);break;case H:!this.get(p)&&we&&we[O]&&this.set(p,we[O]);break;case W:var e=this.data,t=function(t){return e[t].getItem().detectFeature().get()};this.set(U,t(U)).set($,t($)).set(G,t(G)).set(q,t(q)).set(H,t(H))}return this},this.parseUA=function(){return this.itemType!=W&&xe.call(this.data,this.ua,this.rgxMap),this.itemType==U&&this.set(l,Pe(this.get(m))),this},this.parseCH=function(){var e=this.uaCH,t=this.rgxMap;switch(this.itemType){case U:var r,n=e[E]||e[T];if(n)for(var s in n){var o=Oe(/(Google|Microsoft) /,n[s].brand||n[s]),a=n[s].version;/not.a.brand/i.test(o)||r&&(!/chrom/i.test(r)||/chromi/i.test(o))||(this.set(p,o).set(m,a).set(l,Pe(a)),r=o)}break;case $:var c=e[g];c&&(c&&"64"==e[I]&&(c+="64"),xe.call(this.data,c+";",t));break;case G:if(e[b]&&this.set(h,b),e[u]&&this.set(u,e[u]),"Xbox"==e[u]&&this.set(h,v).set(f,re),e[P]){var d;if("string"!=typeof e[P])for(var y=0;!d&&y<e[P].length;)d=Me(e[P][y++],je);else d=Me(e[P],je);this.set(h,d)}break;case H:var w=e[O];if(w){var _=e[D];w==ve&&(_=parseInt(Pe(_),10)>=13?"11":"10"),this.set(p,w).set(m,_)}this.get(p)==ve&&"Xbox"==e[u]&&this.set(p,"Xbox").set(m,i);break;case W:var S=this.data,C=function(t){return S[t].getItem().setCH(e).parseCH().get()};this.set(U,C(U)).set($,C($)).set(G,C(G)).set(q,C(q)).set(H,C(H))}return this},Ee.call(this,[["itemType",e],["ua",t],["uaCH",n],["rgxMap",r],["data",Be(this,e)]]),this}function Ve(e,t,r){if(typeof e===c?(Ce(e,!0)?(typeof t===c&&(r=t),t=e):(r=e,t=i),e=i):typeof e!==d||Ce(t,!0)||(r=t,t=i),r&&typeof r.append===o){var n={};r.forEach((function(e,t){n[t]=e})),r=n}if(!(this instanceof Ve))return new Ve(e,t,r).getResult();var a=typeof e===d?e:r&&r[k]?r[k]:ye&&ye.userAgent?ye.userAgent:s,l=new Fe(r,!0),u=t?function(e,t){var r={},i=t;if(!Ce(t))for(var n in i={},t)for(var s in t[n])i[s]=t[n][s].concat(i[s]?i[s]:[]);for(var o in e)r[o]=i[o]&&i[o].length%2==0?i[o].concat(e[o]):e[o];return r}(Ae,t):Ae,p=function(e){return e==W?function(){return new ze(e,a,u,l).set("ua",a).set(U,this.getBrowser()).set($,this.getCPU()).set(G,this.getDevice()).set(q,this.getEngine()).set(H,this.getOS()).get()}:function(){return new ze(e,a,u[e],l).parseUA().get()}};return Ee.call(this,[["getBrowser",p(U)],["getCPU",p($)],["getDevice",p(G)],["getEngine",p(q)],["getOS",p(H)],["getResult",p(W)],["getUA",function(){return a}],["setUA",function(e){return Re(e)&&(a=e.length>500?Ie(e,500):e),this}]]).setUA(a),this}Ve.VERSION="2.0.0",Ve.BROWSER=_e([p,m,l,h]),Ve.CPU=_e([g]),Ve.DEVICE=_e([u,f,h,v,b,w,y,_,C]),Ve.ENGINE=Ve.OS=_e([p,m]),e.exports&&(t=e.exports=Ve),t.UAParser=Ve;var Ue=be&&(r.jQuery||r.Zepto);if(Ue&&!Ue.ua){var $e=new Ve;Ue.ua=$e.getResult(),Ue.ua.get=function(){return $e.getUA()},Ue.ua.set=function(e){$e.setUA(e);var t=$e.getResult();for(var r in t)Ue.ua[r]=t[r]}}}("object"==typeof window?window:a)}(is,is.exports);var ns=is.exports,ss={},os=a&&a.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(ss,"__esModule",{value:!0});var as=ss.Logger=void 0;const cs=os(ts),ds="mediasoup-client";as=ss.Logger=class{constructor(e){e?(this._debug=(0,cs.default)(`${ds}:${e}`),this._warn=(0,cs.default)(`${ds}:WARN:${e}`),this._error=(0,cs.default)(`${ds}:ERROR:${e}`)):(this._debug=(0,cs.default)(ds),this._warn=(0,cs.default)(`${ds}:WARN`),this._error=(0,cs.default)(`${ds}:ERROR`)),this._debug.log=console.info.bind(console),this._warn.log=console.warn.bind(console),this._error.log=console.error.bind(console)}get debug(){return this._debug}get warn(){return this._warn}get error(){return this._error}};var ls,us={},ps={exports:{}},hs="object"==typeof Reflect?Reflect:null,fs=hs&&"function"==typeof hs.apply?hs.apply:function(e,t,r){return Function.prototype.apply.call(e,t,r)};ls=hs&&"function"==typeof hs.ownKeys?hs.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var ms=Number.isNaN||function(e){return e!=e};function gs(){gs.init.call(this)}ps.exports=gs,ps.exports.once=function(e,t){return new Promise((function(r,i){function n(r){e.removeListener(t,s),i(r)}function s(){"function"==typeof e.removeListener&&e.removeListener("error",n),r([].slice.call(arguments))}Ts(e,t,s,{once:!0}),"error"!==t&&function(e,t,r){"function"==typeof e.on&&Ts(e,"error",t,r)}(e,n,{once:!0})}))},gs.EventEmitter=gs,gs.prototype._events=void 0,gs.prototype._eventsCount=0,gs.prototype._maxListeners=void 0;var vs=10;function bs(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function ys(e){return void 0===e._maxListeners?gs.defaultMaxListeners:e._maxListeners}function ws(e,t,r,i){var n,s,o;if(bs(r),void 0===(s=e._events)?(s=e._events=Object.create(null),e._eventsCount=0):(void 0!==s.newListener&&(e.emit("newListener",t,r.listener?r.listener:r),s=e._events),o=s[t]),void 0===o)o=s[t]=r,++e._eventsCount;else if("function"==typeof o?o=s[t]=i?[r,o]:[o,r]:i?o.unshift(r):o.push(r),(n=ys(e))>0&&o.length>n&&!o.warned){o.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");a.name="MaxListenersExceededWarning",a.emitter=e,a.type=t,a.count=o.length,function(e){console&&console.warn&&console.warn(e)}(a)}return e}function _s(){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 Ss(e,t,r){var i={fired:!1,wrapFn:void 0,target:e,type:t,listener:r},n=_s.bind(i);return n.listener=r,i.wrapFn=n,n}function Cs(e,t,r){var i=e._events;if(void 0===i)return[];var n=i[t];return void 0===n?[]:"function"==typeof n?r?[n.listener||n]:[n]:r?function(e){for(var t=new Array(e.length),r=0;r<t.length;++r)t[r]=e[r].listener||e[r];return t}(n):ks(n,n.length)}function Rs(e){var t=this._events;if(void 0!==t){var r=t[e];if("function"==typeof r)return 1;if(void 0!==r)return r.length}return 0}function ks(e,t){for(var r=new Array(t),i=0;i<t;++i)r[i]=e[i];return r}function Ts(e,t,r,i){if("function"==typeof e.on)i.once?e.once(t,r):e.on(t,r);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 n(s){i.once&&e.removeEventListener(t,n),r(s)}))}}Object.defineProperty(gs,"defaultMaxListeners",{enumerable:!0,get:function(){return vs},set:function(e){if("number"!=typeof e||e<0||ms(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");vs=e}}),gs.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},gs.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||ms(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},gs.prototype.getMaxListeners=function(){return ys(this)},gs.prototype.emit=function(e){for(var t=[],r=1;r<arguments.length;r++)t.push(arguments[r]);var i="error"===e,n=this._events;if(void 0!==n)i=i&&void 0===n.error;else if(!i)return!1;if(i){var s;if(t.length>0&&(s=t[0]),s instanceof Error)throw s;var o=new Error("Unhandled error."+(s?" ("+s.message+")":""));throw o.context=s,o}var a=n[e];if(void 0===a)return!1;if("function"==typeof a)fs(a,this,t);else{var c=a.length,d=ks(a,c);for(r=0;r<c;++r)fs(d[r],this,t)}return!0},gs.prototype.addListener=function(e,t){return ws(this,e,t,!1)},gs.prototype.on=gs.prototype.addListener,gs.prototype.prependListener=function(e,t){return ws(this,e,t,!0)},gs.prototype.once=function(e,t){return bs(t),this.on(e,Ss(this,e,t)),this},gs.prototype.prependOnceListener=function(e,t){return bs(t),this.prependListener(e,Ss(this,e,t)),this},gs.prototype.removeListener=function(e,t){var r,i,n,s,o;if(bs(t),void 0===(i=this._events))return this;if(void 0===(r=i[e]))return this;if(r===t||r.listener===t)0==--this._eventsCount?this._events=Object.create(null):(delete i[e],i.removeListener&&this.emit("removeListener",e,r.listener||t));else if("function"!=typeof r){for(n=-1,s=r.length-1;s>=0;s--)if(r[s]===t||r[s].listener===t){o=r[s].listener,n=s;break}if(n<0)return this;0===n?r.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(r,n),1===r.length&&(i[e]=r[0]),void 0!==i.removeListener&&this.emit("removeListener",e,o||t)}return this},gs.prototype.off=gs.prototype.removeListener,gs.prototype.removeAllListeners=function(e){var t,r,i;if(void 0===(r=this._events))return this;if(void 0===r.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==r[e]&&(0==--this._eventsCount?this._events=Object.create(null):delete r[e]),this;if(0===arguments.length){var n,s=Object.keys(r);for(i=0;i<s.length;++i)"removeListener"!==(n=s[i])&&this.removeAllListeners(n);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=r[e]))this.removeListener(e,t);else if(void 0!==t)for(i=t.length-1;i>=0;i--)this.removeListener(e,t[i]);return this},gs.prototype.listeners=function(e){return Cs(this,e,!0)},gs.prototype.rawListeners=function(e){return Cs(this,e,!1)},gs.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):Rs.call(e,t)},gs.prototype.listenerCount=Rs,gs.prototype.eventNames=function(){return this._eventsCount>0?ls(this._events):[]};var Ps=ps.exports;Object.defineProperty(us,"__esModule",{value:!0}),us.EnhancedEventEmitter=void 0;const Es=Ps,Os=new ss.Logger("EnhancedEventEmitter");class Ds extends Es.EventEmitter{constructor(){super(),this.setMaxListeners(1/0)}emit(e,...t){return super.emit(e,...t)}safeEmit(e,...t){try{return super.emit(e,...t)}catch(t){Os.error("safeEmit() | event listener threw an error [eventName:%s]:%o",e,t);try{super.emit("listenererror",e,t)}catch(e){}return Boolean(super.listenerCount(e))}}on(e,t){return super.on(e,t),this}off(e,t){return super.off(e,t),this}addListener(e,t){return super.on(e,t),this}prependListener(e,t){return super.prependListener(e,t),this}once(e,t){return super.once(e,t),this}prependOnceListener(e,t){return super.prependOnceListener(e,t),this}removeListener(e,t){return super.off(e,t),this}removeAllListeners(e){return super.removeAllListeners(e),this}listenerCount(e){return super.listenerCount(e)}listeners(e){return super.listeners(e)}rawListeners(e){return super.rawListeners(e)}}us.EnhancedEventEmitter=Ds;var Is={};Object.defineProperty(Is,"__esModule",{value:!0});var xs=Is.InvalidStateError=Is.UnsupportedError=void 0;class Ms extends Error{constructor(e){super(e),this.name="UnsupportedError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,Ms):this.stack=new Error(e).stack}}Is.UnsupportedError=Ms;class Ls extends Error{constructor(e){super(e),this.name="InvalidStateError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,Ls):this.stack=new Error(e).stack}}xs=Is.InvalidStateError=Ls;var js={};Object.defineProperty(js,"__esModule",{value:!0});var As=js.clone=function(e){return void 0===e?void 0:Number.isNaN(e)?NaN:"function"==typeof structuredClone?structuredClone(e):JSON.parse(JSON.stringify(e))};js.generateRandomNumber=function(){return Math.round(1e7*Math.random())},js.deepFreeze=function e(t){const r=Reflect.ownKeys(t);for(const i of r){const r=t[i];(r&&"object"==typeof r||"function"==typeof r)&&e(r)}return Object.freeze(t)};var Ns,Bs,Fs={},zs={},Vs={},Us={exports:{}};function $s(){if(Bs)return Ns;Bs=1;var e=1e3,t=60*e,r=60*t,i=24*r,n=7*i,s=365.25*i;function o(e,t,r,i){var n=t>=1.5*r;return Math.round(e/r)+" "+i+(n?"s":"")}return Ns=function(a,c){c=c||{};var d=typeof a;if("string"===d&&a.length>0)return function(o){if((o=String(o)).length>100)return;var a=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(o);if(!a)return;var c=parseFloat(a[1]);switch((a[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return c*s;case"weeks":case"week":case"w":return c*n;case"days":case"day":case"d":return c*i;case"hours":case"hour":case"hrs":case"hr":case"h":return c*r;case"minutes":case"minute":case"mins":case"min":case"m":return c*t;case"seconds":case"second":case"secs":case"sec":case"s":return c*e;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return c;default:return}}(a);if("number"===d&&isFinite(a))return c.long?function(n){var s=Math.abs(n);if(s>=i)return o(n,s,i,"day");if(s>=r)return o(n,s,r,"hour");if(s>=t)return o(n,s,t,"minute");if(s>=e)return o(n,s,e,"second");return n+" ms"}(a):function(n){var s=Math.abs(n);if(s>=i)return Math.round(n/i)+"d";if(s>=r)return Math.round(n/r)+"h";if(s>=t)return Math.round(n/t)+"m";if(s>=e)return Math.round(n/e)+"s";return n+"ms"}(a);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(a))},Ns}var Gs=function(e){function t(e){let i,n,s,o=null;function a(...e){if(!a.enabled)return;const r=a,n=Number(new Date),s=n-(i||n);r.diff=s,r.prev=i,r.curr=n,i=n,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let o=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,((i,n)=>{if("%%"===i)return"%";o++;const s=t.formatters[n];if("function"==typeof s){const t=e[o];i=s.call(r,t),e.splice(o,1),o--}return i})),t.formatArgs.call(r,e);(r.log||t.log).apply(r,e)}return a.namespace=e,a.useColors=t.useColors(),a.color=t.selectColor(e),a.extend=r,a.destroy=t.destroy,Object.defineProperty(a,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==o?o:(n!==t.namespaces&&(n=t.namespaces,s=t.enabled(e)),s),set:e=>{o=e}}),"function"==typeof t.init&&t.init(a),a}function r(e,r){const i=t(this.namespace+(void 0===r?":":r)+e);return i.log=this.log,i}function i(e){return e.toString().substring(2,e.toString().length-2).replace(/\.\*\?$/,"*")}return t.debug=t,t.default=t,t.coerce=function(e){if(e instanceof Error)return e.stack||e.message;return e},t.disable=function(){const e=[...t.names.map(i),...t.skips.map(i).map((e=>"-"+e))].join(",");return t.enable(""),e},t.enable=function(e){let r;t.save(e),t.namespaces=e,t.names=[],t.skips=[];const i=("string"==typeof e?e:"").split(/[\s,]+/),n=i.length;for(r=0;r<n;r++)i[r]&&("-"===(e=i[r].replace(/\*/g,".*?"))[0]?t.skips.push(new RegExp("^"+e.slice(1)+"$")):t.names.push(new RegExp("^"+e+"$")))},t.enabled=function(e){if("*"===e[e.length-1])return!0;let r,i;for(r=0,i=t.skips.length;r<i;r++)if(t.skips[r].test(e))return!1;for(r=0,i=t.names.length;r<i;r++)if(t.names[r].test(e))return!0;return!1},t.humanize=$s(),t.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(e).forEach((r=>{t[r]=e[r]})),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let r=0;for(let t=0;t<e.length;t++)r=(r<<5)-r+e.charCodeAt(t),r|=0;return t.colors[Math.abs(r)%t.colors.length]},t.enable(t.load()),t};!function(e,t){t.formatArgs=function(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;const r="color: "+this.color;t.splice(1,0,r,"color: inherit");let i=0,n=0;t[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(i++,"%c"===e&&(n=i))})),t.splice(n,0,r)},t.save=function(e){try{e?t.storage.setItem("debug",e):t.storage.removeItem("debug")}catch(e){}},t.load=function(){let e;try{e=t.storage.getItem("debug")}catch(e){}!e&&"undefined"!=typeof process&&"env"in process&&(e=process.env.DEBUG);return e},t.useColors=function(){if("undefined"!=typeof window&&window.process&&("renderer"===window.process.type||window.process.__nwjs))return!0;if("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;return"undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},t.storage=function(){try{return localStorage}catch(e){}}(),t.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],t.log=console.debug||console.log||(()=>{}),e.exports=Gs(t);const{formatters:r}=e.exports;r.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}(Us,Us.exports);var qs=Us.exports,Hs=a&&a.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Vs,"__esModule",{value:!0}),Vs.Logger=void 0;const Ws=Hs(qs),Ks="h264-profile-level-id";Vs.Logger=class{constructor(e){e?(this._debug=(0,Ws.default)(`${Ks}:${e}`),this._warn=(0,Ws.default)(`${Ks}:WARN:${e}`),this._error=(0,Ws.default)(`${Ks}:ERROR:${e}`)):(this._debug=(0,Ws.default)(Ks),this._warn=(0,Ws.default)(`${Ks}:WARN`),this._error=(0,Ws.default)(`${Ks}:ERROR`)),this._debug.log=console.info.bind(console),this._warn.log=console.warn.bind(console),this._error.log=console.error.bind(console)}get debug(){return this._debug}get warn(){return this._warn}get error(){return this._error}},Object.defineProperty(zs,"__esModule",{value:!0}),zs.generateProfileLevelIdStringForAnswer=zs.isSameProfile=zs.parseSdpProfileLevelId=zs.levelToString=zs.profileToString=zs.profileLevelIdToString=zs.parseProfileLevelId=zs.ProfileLevelId=zs.Level=zs.Profile=void 0;const Js=new Vs.Logger;var Xs,Qs;!function(e){e[e.ConstrainedBaseline=1]="ConstrainedBaseline",e[e.Baseline=2]="Baseline",e[e.Main=3]="Main",e[e.ConstrainedHigh=4]="ConstrainedHigh",e[e.High=5]="High",e[e.PredictiveHigh444=6]="PredictiveHigh444"}(Xs||(zs.Profile=Xs={})),function(e){e[e.L1_b=0]="L1_b",e[e.L1=10]="L1",e[e.L1_1=11]="L1_1",e[e.L1_2=12]="L1_2",e[e.L1_3=13]="L1_3",e[e.L2=20]="L2",e[e.L2_1=21]="L2_1",e[e.L2_2=22]="L2_2",e[e.L3=30]="L3",e[e.L3_1=31]="L3_1",e[e.L3_2=32]="L3_2",e[e.L4=40]="L4",e[e.L4_1=41]="L4_1",e[e.L4_2=42]="L4_2",e[e.L5=50]="L5",e[e.L5_1=51]="L5_1",e[e.L5_2=52]="L5_2"}(Qs||(zs.Level=Qs={}));class Zs{constructor(e,t){this.profile=e,this.level=t}}zs.ProfileLevelId=Zs;const Ys=new Zs(Xs.ConstrainedBaseline,Qs.L3_1);class eo{constructor(e){this.mask=~oo("x",e),this.masked_value=oo("1",e)}isMatch(e){return this.masked_value===(e&this.mask)}}class to{constructor(e,t,r){this.profile_idc=e,this.profile_iop=t,this.profile=r}}const ro=[new to(66,new eo("x1xx0000"),Xs.ConstrainedBaseline),new to(77,new eo("1xxx0000"),Xs.ConstrainedBaseline),new to(88,new eo("11xx0000"),Xs.ConstrainedBaseline),new to(66,new eo("x0xx0000"),Xs.Baseline),new to(88,new eo("10xx0000"),Xs.Baseline),new to(77,new eo("0x0x0000"),Xs.Main),new to(100,new eo("00000000"),Xs.High),new to(100,new eo("00001100"),Xs.ConstrainedHigh),new to(244,new eo("00000000"),Xs.PredictiveHigh444)];function io(e){if("string"!=typeof e||6!==e.length)return;const t=parseInt(e,16);if(0===t)return;const r=255&t,i=t>>8&255,n=t>>16&255;let s;switch(r){case Qs.L1_1:s=0!=(16&i)?Qs.L1_b:Qs.L1_1;break;case Qs.L1:case Qs.L1_2:case Qs.L1_3:case Qs.L2:case Qs.L2_1:case Qs.L2_2:case Qs.L3:case Qs.L3_1:case Qs.L3_2:case Qs.L4:case Qs.L4_1:case Qs.L4_2:case Qs.L5:case Qs.L5_1:case Qs.L5_2:s=r;break;default:return void Js.warn(`parseProfileLevelId() | unrecognized level_idc [str:${e}, level_idc:${r}]`)}for(const e of ro)if(n===e.profile_idc&&e.profile_iop.isMatch(i))return new Zs(e.profile,s);Js.warn(`parseProfileLevelId() | unrecognized profile_idc/profile_iop combination [str:${e}, profile_idc:${n}, profile_iop:${i}]`)}function no(e){if(e.level==Qs.L1_b)switch(e.profile){case Xs.ConstrainedBaseline:return"42f00b";case Xs.Baseline:return"42100b";case Xs.Main:return"4d100b";default:return void Js.warn(`profileLevelIdToString() | Level 1_b not is allowed for profile ${e.profile}`)}let t;switch(e.profile){case Xs.ConstrainedBaseline:t="42e0";break;case Xs.Baseline:t="4200";break;case Xs.Main:t="4d00";break;case Xs.ConstrainedHigh:t="640c";break;case Xs.High:t="6400";break;case Xs.PredictiveHigh444:t="f400";break;default:return void Js.warn(`profileLevelIdToString() | unrecognized profile ${e.profile}`)}let r=e.level.toString(16);return 1===r.length&&(r=`0${r}`),`${t}${r}`}function so(e={}){const t=e["profile-level-id"];return t?io(t):Ys}function oo(e,t){return Number(t[0]===e)<<7|Number(t[1]===e)<<6|Number(t[2]===e)<<5|Number(t[3]===e)<<4|Number(t[4]===e)<<3|Number(t[5]===e)<<2|Number(t[6]===e)<<1|Number(t[7]===e)<<0}function ao(e={}){const t=e["level-asymmetry-allowed"];return!0===t||1===t||"1"===t}zs.parseProfileLevelId=io,zs.profileLevelIdToString=no,zs.profileToString=function(e){switch(e){case Xs.ConstrainedBaseline:return"ConstrainedBaseline";case Xs.Baseline:return"Baseline";case Xs.Main:return"Main";case Xs.ConstrainedHigh:return"ConstrainedHigh";case Xs.High:return"High";case Xs.PredictiveHigh444:return"PredictiveHigh444";default:return void Js.warn(`profileToString() | unrecognized profile ${e}`)}},zs.levelToString=function(e){switch(e){case Qs.L1_b:return"1b";case Qs.L1:return"1";case Qs.L1_1:return"1.1";case Qs.L1_2:return"1.2";case Qs.L1_3:return"1.3";case Qs.L2:return"2";case Qs.L2_1:return"2.1";case Qs.L2_2:return"2.2";case Qs.L3:return"3";case Qs.L3_1:return"3.1";case Qs.L3_2:return"3.2";case Qs.L4:return"4";case Qs.L4_1:return"4.1";case Qs.L4_2:return"4.2";case Qs.L5:return"5";case Qs.L5_1:return"5.1";case Qs.L5_2:return"5.2";default:return void Js.warn(`levelToString() | unrecognized level ${e}`)}},zs.parseSdpProfileLevelId=so,zs.isSameProfile=function(e={},t={}){const r=so(e),i=so(t);return Boolean(r&&i&&r.profile===i.profile)},zs.generateProfileLevelIdStringForAnswer=function(e={},t={}){if(!e["profile-level-id"]&&!t["profile-level-id"])return void Js.warn("generateProfileLevelIdStringForAnswer() | profile-level-id missing in local and remote params");const r=so(e),i=so(t);if(!r)throw new TypeError("invalid local_profile_level_id");if(!i)throw new TypeError("invalid remote_profile_level_id");if(r.profile!==i.profile)throw new TypeError("H264 Profile mismatch");const n=ao(e)&&ao(t),s=r.level,o=i.level,a=function(e,t){return e===Qs.L1_b?t!==Qs.L1&&t!==Qs.L1_b:t===Qs.L1_b?e!==Qs.L1:e<t}(c=s,d=o)?c:d;var c,d;const l=n?s:a;return Js.debug(`generateProfileLevelIdStringForAnswer() | result [profile:${r.profile}, level:${l}]`),no(new Zs(r.profile,l))};var co,lo=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),uo=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),po=a&&a.__importStar||(co=function(e){return co=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},co(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r=co(e),i=0;i<r.length;i++)"default"!==r[i]&&lo(t,e,r[i]);return uo(t,e),t});Object.defineProperty(Fs,"__esModule",{value:!0}),Fs.validateRtpCapabilities=function(e){if("object"!=typeof e)throw new TypeError("caps is not an object");if(e.codecs&&!Array.isArray(e.codecs))throw new TypeError("caps.codecs is not an array");e.codecs||(e.codecs=[]);for(const t of e.codecs)So(t);if(e.headerExtensions&&!Array.isArray(e.headerExtensions))throw new TypeError("caps.headerExtensions is not an array");e.headerExtensions||(e.headerExtensions=[]);for(const t of e.headerExtensions)Ro(t)},Fs.validateRtpParameters=_o,Fs.validateSctpStreamParameters=function(e){if("object"!=typeof e)throw new TypeError("params is not an object");if("number"!=typeof e.streamId)throw new TypeError("missing params.streamId");let t=!1;"boolean"==typeof e.ordered?t=!0:e.ordered=!0;if(e.maxPacketLifeTime&&"number"!=typeof e.maxPacketLifeTime)throw new TypeError("invalid params.maxPacketLifeTime");if(e.maxRetransmits&&"number"!=typeof e.maxRetransmits)throw new TypeError("invalid params.maxRetransmits");if(e.maxPacketLifeTime&&e.maxRetransmits)throw new TypeError("cannot provide both maxPacketLifeTime and maxRetransmits");if(t&&e.ordered&&(e.maxPacketLifeTime||e.maxRetransmits))throw new TypeError("cannot be ordered with maxPacketLifeTime or maxRetransmits");t||!e.maxPacketLifeTime&&!e.maxRetransmits||(e.ordered=!1);if(e.label&&"string"!=typeof e.label)throw new TypeError("invalid params.label");if(e.protocol&&"string"!=typeof e.protocol)throw new TypeError("invalid params.protocol")},Fs.validateSctpCapabilities=function(e){if("object"!=typeof e)throw new TypeError("caps is not an object");if(!e.numStreams||"object"!=typeof e.numStreams)throw new TypeError("missing caps.numStreams");!function(e){if("object"!=typeof e)throw new TypeError("numStreams is not an object");if("number"!=typeof e.OS)throw new TypeError("missing numStreams.OS");if("number"!=typeof e.MIS)throw new TypeError("missing numStreams.MIS")}(e.numStreams)},Fs.getExtendedRtpCapabilities=function(e,t){const r={codecs:[],headerExtensions:[]};for(const i of t.codecs??[]){if(Eo(i))continue;const t=(e.codecs??[]).find((e=>Oo(e,i,{strict:!0,modify:!0})));if(!t)continue;const n={mimeType:t.mimeType,kind:t.kind,clockRate:t.clockRate,channels:t.channels,localPayloadType:t.preferredPayloadType,localRtxPayloadType:void 0,remotePayloadType:i.preferredPayloadType,remoteRtxPayloadType:void 0,localParameters:t.parameters,remoteParameters:i.parameters,rtcpFeedback:Io(t,i)};r.codecs.push(n)}for(const i of r.codecs){const r=e.codecs.find((e=>Eo(e)&&e.parameters.apt===i.localPayloadType)),n=t.codecs.find((e=>Eo(e)&&e.parameters.apt===i.remotePayloadType));r&&n&&(i.localRtxPayloadType=r.preferredPayloadType,i.remoteRtxPayloadType=n.preferredPayloadType)}for(const i of t.headerExtensions){const t=e.headerExtensions.find((e=>Do(e,i)));if(!t)continue;const n={kind:i.kind,uri:i.uri,sendId:t.preferredId,recvId:i.preferredId,encrypt:t.preferredEncrypt,direction:"sendrecv"};switch(i.direction){case"sendrecv":n.direction="sendrecv";break;case"recvonly":n.direction="sendonly";break;case"sendonly":n.direction="recvonly";break;case"inactive":n.direction="inactive"}r.headerExtensions.push(n)}return r},Fs.getRecvRtpCapabilities=function(e){const t={codecs:[],headerExtensions:[]};for(const r of e.codecs){const e={mimeType:r.mimeType,kind:r.kind,preferredPayloadType:r.remotePayloadType,clockRate:r.clockRate,channels:r.channels,parameters:r.localParameters,rtcpFeedback:r.rtcpFeedback};if(t.codecs.push(e),!r.remoteRtxPayloadType)continue;const i={mimeType:`${r.kind}/rtx`,kind:r.kind,preferredPayloadType:r.remoteRtxPayloadType,clockRate:r.clockRate,parameters:{apt:r.remotePayloadType},rtcpFeedback:[]};t.codecs.push(i)}for(const r of e.headerExtensions){if("sendrecv"!==r.direction&&"recvonly"!==r.direction)continue;const e={kind:r.kind,uri:r.uri,preferredId:r.recvId,preferredEncrypt:r.encrypt,direction:r.direction};t.headerExtensions.push(e)}return t};var ho=Fs.getSendingRtpParameters=function(e,t){const r={mid:void 0,codecs:[],headerExtensions:[],encodings:[],rtcp:{}};for(const i of t.codecs){if(i.kind!==e)continue;const t={mimeType:i.mimeType,payloadType:i.localPayloadType,clockRate:i.clockRate,channels:i.channels,parameters:i.localParameters,rtcpFeedback:i.rtcpFeedback};if(r.codecs.push(t),i.localRtxPayloadType){const e={mimeType:`${i.kind}/rtx`,payloadType:i.localRtxPayloadType,clockRate:i.clockRate,parameters:{apt:i.localPayloadType},rtcpFeedback:[]};r.codecs.push(e)}}for(const i of t.headerExtensions){if(i.kind&&i.kind!==e||"sendrecv"!==i.direction&&"sendonly"!==i.direction)continue;const t={uri:i.uri,id:i.sendId,encrypt:i.encrypt,parameters:{}};r.headerExtensions.push(t)}return r},fo=Fs.getSendingRemoteRtpParameters=function(e,t){const r={mid:void 0,codecs:[],headerExtensions:[],encodings:[],rtcp:{}};for(const i of t.codecs){if(i.kind!==e)continue;const t={mimeType:i.mimeType,payloadType:i.localPayloadType,clockRate:i.clockRate,channels:i.channels,parameters:i.remoteParameters,rtcpFeedback:i.rtcpFeedback};if(r.codecs.push(t),i.localRtxPayloadType){const e={mimeType:`${i.kind}/rtx`,payloadType:i.localRtxPayloadType,clockRate:i.clockRate,parameters:{apt:i.localPayloadType},rtcpFeedback:[]};r.codecs.push(e)}}for(const i of t.headerExtensions){if(i.kind&&i.kind!==e||"sendrecv"!==i.direction&&"sendonly"!==i.direction)continue;const t={uri:i.uri,id:i.sendId,encrypt:i.encrypt,parameters:{}};r.headerExtensions.push(t)}if(r.headerExtensions.some((e=>"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01"===e.uri)))for(const e of r.codecs)e.rtcpFeedback=(e.rtcpFeedback??[]).filter((e=>"goog-remb"!==e.type));else if(r.headerExtensions.some((e=>"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time"===e.uri)))for(const e of r.codecs)e.rtcpFeedback=(e.rtcpFeedback??[]).filter((e=>"transport-cc"!==e.type));else for(const e of r.codecs)e.rtcpFeedback=(e.rtcpFeedback??[]).filter((e=>"transport-cc"!==e.type&&"goog-remb"!==e.type));return r},mo=Fs.reduceCodecs=function(e,t){const r=[];if(t){for(let i=0;i<e.length;++i)if(Oo(e[i],t,{strict:!0})){r.push(e[i]),Eo(e[i+1])&&r.push(e[i+1]);break}if(0===r.length)throw new TypeError("no matching codec found")}else r.push(e[0]),Eo(e[1])&&r.push(e[1]);return r};Fs.generateProbatorRtpParameters=function(e){_o(e=vo.clone(e));const t={mid:bo,codecs:[],headerExtensions:[],encodings:[{ssrc:yo}],rtcp:{cname:"probator"}};return t.codecs.push(e.codecs[0]),t.codecs[0].payloadType=wo,t.headerExtensions=e.headerExtensions,t},Fs.canSend=function(e,t){return t.codecs.some((t=>t.kind===e))},Fs.canReceive=function(e,t){if(_o(e),0===e.codecs.length)return!1;const r=e.codecs[0];return t.codecs.some((e=>e.remotePayloadType===r.payloadType))};const go=po(zs),vo=po(js),bo="probator",yo=1234,wo=127;function _o(e){if("object"!=typeof e)throw new TypeError("params is not an object");if(e.mid&&"string"!=typeof e.mid)throw new TypeError("params.mid is not a string");if(!Array.isArray(e.codecs))throw new TypeError("missing params.codecs");for(const t of e.codecs)ko(t);if(e.headerExtensions&&!Array.isArray(e.headerExtensions))throw new TypeError("params.headerExtensions is not an array");e.headerExtensions||(e.headerExtensions=[]);for(const t of e.headerExtensions)To(t);if(e.encodings&&!Array.isArray(e.encodings))throw new TypeError("params.encodings is not an array");e.encodings||(e.encodings=[]);for(const t of e.encodings)Po(t);if(e.rtcp&&"object"!=typeof e.rtcp)throw new TypeError("params.rtcp is not an object");e.rtcp||(e.rtcp={}),function(e){if("object"!=typeof e)throw new TypeError("rtcp is not an object");if(e.cname&&"string"!=typeof e.cname)throw new TypeError("invalid rtcp.cname");e.reducedSize&&"boolean"==typeof e.reducedSize||(e.reducedSize=!0)}(e.rtcp)}function So(e){const t=new RegExp("^(audio|video)/(.+)","i");if("object"!=typeof e)throw new TypeError("codec is not an object");if(!e.mimeType||"string"!=typeof e.mimeType)throw new TypeError("missing codec.mimeType");const r=t.exec(e.mimeType);if(!r)throw new TypeError("invalid codec.mimeType");if(e.kind=r[1].toLowerCase(),e.preferredPayloadType&&"number"!=typeof e.preferredPayloadType)throw new TypeError("invalid codec.preferredPayloadType");if("number"!=typeof e.clockRate)throw new TypeError("missing codec.clockRate");"audio"===e.kind?"number"!=typeof e.channels&&(e.channels=1):delete e.channels,e.parameters&&"object"==typeof e.parameters||(e.parameters={});for(const t of Object.keys(e.parameters)){let r=e.parameters[t];if(void 0===r&&(e.parameters[t]="",r=""),"string"!=typeof r&&"number"!=typeof r)throw new TypeError(`invalid codec parameter [key:${t}s, value:${r}]`);if("apt"===t&&"number"!=typeof r)throw new TypeError("invalid codec apt parameter")}e.rtcpFeedback&&Array.isArray(e.rtcpFeedback)||(e.rtcpFeedback=[]);for(const t of e.rtcpFeedback)Co(t)}function Co(e){if("object"!=typeof e)throw new TypeError("fb is not an object");if(!e.type||"string"!=typeof e.type)throw new TypeError("missing fb.type");e.parameter&&"string"==typeof e.parameter||(e.parameter="")}function Ro(e){if("object"!=typeof e)throw new TypeError("ext is not an object");if("audio"!==e.kind&&"video"!==e.kind)throw new TypeError("invalid ext.kind");if(!e.uri||"string"!=typeof e.uri)throw new TypeError("missing ext.uri");if("number"!=typeof e.preferredId)throw new TypeError("missing ext.preferredId");if(e.preferredEncrypt&&"boolean"!=typeof e.preferredEncrypt)throw new TypeError("invalid ext.preferredEncrypt");if(e.preferredEncrypt||(e.preferredEncrypt=!1),e.direction&&"string"!=typeof e.direction)throw new TypeError("invalid ext.direction");e.direction||(e.direction="sendrecv")}function ko(e){const t=new RegExp("^(audio|video)/(.+)","i");if("object"!=typeof e)throw new TypeError("codec is not an object");if(!e.mimeType||"string"!=typeof e.mimeType)throw new TypeError("missing codec.mimeType");const r=t.exec(e.mimeType);if(!r)throw new TypeError("invalid codec.mimeType");if("number"!=typeof e.payloadType)throw new TypeError("missing codec.payloadType");if("number"!=typeof e.clockRate)throw new TypeError("missing codec.clockRate");"audio"===r[1].toLowerCase()?"number"!=typeof e.channels&&(e.channels=1):delete e.channels,e.parameters&&"object"==typeof e.parameters||(e.parameters={});for(const t of Object.keys(e.parameters)){let r=e.parameters[t];if(void 0===r&&(e.parameters[t]="",r=""),"string"!=typeof r&&"number"!=typeof r)throw new TypeError(`invalid codec parameter [key:${t}s, value:${r}]`);if("apt"===t&&"number"!=typeof r)throw new TypeError("invalid codec apt parameter")}e.rtcpFeedback&&Array.isArray(e.rtcpFeedback)||(e.rtcpFeedback=[]);for(const t of e.rtcpFeedback)Co(t)}function To(e){if("object"!=typeof e)throw new TypeError("ext is not an object");if(!e.uri||"string"!=typeof e.uri)throw new TypeError("missing ext.uri");if("number"!=typeof e.id)throw new TypeError("missing ext.id");if(e.encrypt&&"boolean"!=typeof e.encrypt)throw new TypeError("invalid ext.encrypt");e.encrypt||(e.encrypt=!1),e.parameters&&"object"==typeof e.parameters||(e.parameters={});for(const t of Object.keys(e.parameters)){let r=e.parameters[t];if(void 0===r&&(e.parameters[t]="",r=""),"string"!=typeof r&&"number"!=typeof r)throw new TypeError("invalid header extension parameter")}}function Po(e){if("object"!=typeof e)throw new TypeError("encoding is not an object");if(e.ssrc&&"number"!=typeof e.ssrc)throw new TypeError("invalid encoding.ssrc");if(e.rid&&"string"!=typeof e.rid)throw new TypeError("invalid encoding.rid");if(e.rtx&&"object"!=typeof e.rtx)throw new TypeError("invalid encoding.rtx");if(e.rtx&&"number"!=typeof e.rtx.ssrc)throw new TypeError("missing encoding.rtx.ssrc");if(e.dtx&&"boolean"==typeof e.dtx||(e.dtx=!1),e.scalabilityMode&&"string"!=typeof e.scalabilityMode)throw new TypeError("invalid encoding.scalabilityMode")}function Eo(e){return!!e&&/.+\/rtx$/i.test(e.mimeType)}function Oo(e,t,{strict:r=!1,modify:i=!1}={}){const n=e.mimeType.toLowerCase();if(n!==t.mimeType.toLowerCase())return!1;if(e.clockRate!==t.clockRate)return!1;if(e.channels!==t.channels)return!1;switch(n){case"video/h264":if(r){if((e.parameters["packetization-mode"]||0)!==(t.parameters["packetization-mode"]||0))return!1;if(!go.isSameProfile(e.parameters,t.parameters))return!1;let r;try{r=go.generateProfileLevelIdStringForAnswer(e.parameters,t.parameters)}catch(e){return!1}i&&(r?(e.parameters["profile-level-id"]=r,t.parameters["profile-level-id"]=r):(delete e.parameters["profile-level-id"],delete t.parameters["profile-level-id"]))}break;case"video/vp9":if(r){if((e.parameters["profile-id"]||0)!==(t.parameters["profile-id"]||0))return!1}}return!0}function Do(e,t){return(!e.kind||!t.kind||e.kind===t.kind)&&e.uri===t.uri}function Io(e,t){const r=[];for(const i of e.rtcpFeedback??[]){const e=(t.rtcpFeedback??[]).find((e=>e.type===i.type&&(e.parameter===i.parameter||!e.parameter&&!i.parameter)));e&&r.push(e)}return r}var xo={},Mo={},Lo={};Object.defineProperty(Lo,"__esModule",{value:!0}),Lo.Logger=void 0;const jo=qs,Ao="awaitqueue";Lo.Logger=class{constructor(e){e?(this._debug=(0,jo.default)(`${Ao}:${e}`),this._warn=(0,jo.default)(`${Ao}:WARN:${e}`),this._error=(0,jo.default)(`${Ao}:ERROR:${e}`)):(this._debug=(0,jo.default)(Ao),this._warn=(0,jo.default)(`${Ao}:WARN`),this._error=(0,jo.default)(`${Ao}:ERROR`)),this._debug.log=console.info.bind(console),this._warn.log=console.warn.bind(console),this._error.log=console.error.bind(console)}get debug(){return this._debug}get warn(){return this._warn}get error(){return this._error}},Object.defineProperty(Mo,"__esModule",{value:!0}),Mo.AwaitQueue=Mo.AwaitQueueRemovedTaskError=Mo.AwaitQueueStoppedError=void 0;const No=new Lo.Logger;class Bo extends Error{constructor(e){super(e??"AwaitQueue stopped"),this.name="AwaitQueueStoppedError","function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,Bo)}}Mo.AwaitQueueStoppedError=Bo;class Fo extends Error{constructor(e){super(e??"AwaitQueue task removed"),this.name="AwaitQueueRemovedTaskError","function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,Fo)}}Mo.AwaitQueueRemovedTaskError=Fo;
|
|
1
|
+
this.whereby=this.whereby||{},this.whereby.react=function(e,t,r){"use strict";function i(e){var t=Object.create(null);return e&&Object.keys(e).forEach((function(r){if("default"!==r){var i=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,i.get?i:{enumerable:!0,get:function(){return e[r]}})}})),t.default=e,Object.freeze(t)}function n(e,t){return t.forEach((function(t){t&&"string"!=typeof t&&!Array.isArray(t)&&Object.keys(t).forEach((function(r){if("default"!==r&&!(r in e)){var i=Object.getOwnPropertyDescriptor(t,r);Object.defineProperty(e,r,i.get?i:{enumerable:!0,get:function(){return t[r]}})}}))})),Object.freeze(e)}var s=i(t),o=i(r),a="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function c(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var d,l={exports:{}},u={};l.exports=(d||(d=1,function(){"undefined"!=typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error);var e=t,r="function"==typeof Object.is?Object.is:function(e,t){return e===t&&(0!==e||1/e==1/t)||e!=e&&t!=t},i=e.useSyncExternalStore,n=e.useRef,s=e.useEffect,o=e.useMemo,a=e.useDebugValue;u.useSyncExternalStoreWithSelector=function(e,t,c,d,l){var u,p=n(null);null===p.current?(u={hasValue:!1,value:null},p.current=u):u=p.current;var h=o((function(){var e,i,n=!1,s=function(t){if(!n){n=!0,e=t;var s=d(t);if(void 0!==l&&u.hasValue){var o=u.value;if(l(o,s))return i=o,o}return i=s,s}var a=i;if(r(e,t))return a;var c=d(t);return void 0!==l&&l(a,c)?a:(e=t,i=c,c)},o=void 0===c?null:c;return[function(){return s(t())},null===o?void 0:function(){return s(o())}]}),[t,c,d,l]),f=h[0],m=h[1],g=i(e,f,m);return s((function(){u.hasValue=!0,u.value=g}),[g]),a(g),g},"undefined"!=typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error)}()),u);var p=l.exports,h="default"in s?s.default:s,f=Symbol.for("react-redux-context"),m="undefined"!=typeof globalThis?globalThis:{};function g(){if(!h.createContext)return{};const e=m[f]??(m[f]=new Map);let t=e.get(h.createContext);return t||(t=h.createContext(null),t.displayName="ReactRedux",e.set(h.createContext,t)),t}var v=g();function b(e=v){return function(){const t=h.useContext(e);if(!t)throw new Error("could not find react-redux context value; please ensure the component is wrapped in a <Provider>");return t}}var y=b(),w=()=>{throw new Error("uSES not initialized!")},_=(e,t)=>e===t;var S={notify(){},get:()=>[]};var C=!("undefined"==typeof window||void 0===window.document||void 0===window.document.createElement),R="undefined"!=typeof navigator&&"ReactNative"===navigator.product,k=C||R?h.useLayoutEffect:h.useEffect;var T=function({store:e,context:t,children:r,serverState:i,stabilityCheck:n="once",identityFunctionCheck:s="once"}){const o=h.useMemo((()=>{const t=function(e,t){let r,i=S,n=0,s=!1;function o(){d.onStateChange&&d.onStateChange()}function a(){n++,r||(r=t?t.addNestedSub(o):e.subscribe(o),i=function(){let e=null,t=null;return{clear(){e=null,t=null},notify(){var t;t=()=>{let t=e;for(;t;)t.callback(),t=t.next},t()},get(){const t=[];let r=e;for(;r;)t.push(r),r=r.next;return t},subscribe(r){let i=!0;const n=t={callback:r,next:null,prev:t};return n.prev?n.prev.next=n:e=n,function(){i&&null!==e&&(i=!1,n.next?n.next.prev=n.prev:t=n.prev,n.prev?n.prev.next=n.next:e=n.next)}}}}())}function c(){n--,r&&0===n&&(r(),r=void 0,i.clear(),i=S)}const d={addNestedSub:function(e){a();const t=i.subscribe(e);let r=!1;return()=>{r||(r=!0,t(),c())}},notifyNestedSubs:function(){i.notify()},handleChangeWrapper:o,isSubscribed:function(){return s},trySubscribe:function(){s||(s=!0,a())},tryUnsubscribe:function(){s&&(s=!1,c())},getListeners:()=>i};return d}(e);return{store:e,subscription:t,getServerState:i?()=>i:void 0,stabilityCheck:n,identityFunctionCheck:s}}),[e,i,n,s]),a=h.useMemo((()=>e.getState()),[e]);k((()=>{const{subscription:t}=o;return t.onStateChange=t.notifyNestedSubs,t.trySubscribe(),a!==e.getState()&&t.notifyNestedSubs(),()=>{t.tryUnsubscribe(),t.onStateChange=void 0}}),[o,a]);const c=t||v;return h.createElement(c.Provider,{value:o},r)};function P(e=v){const t=e===v?y:b(e),r=()=>{const{store:e}=t();return e};return Object.assign(r,{withTypes:()=>r}),r}var O,E=P();O=p.useSyncExternalStoreWithSelector,w=O;var D=(()=>"function"==typeof Symbol&&Symbol.observable||"@@observable")(),I=()=>Math.random().toString(36).substring(7).split("").join("."),x={INIT:`@@redux/INIT${I()}`,REPLACE:`@@redux/REPLACE${I()}`,PROBE_UNKNOWN_ACTION:()=>`@@redux/PROBE_UNKNOWN_ACTION${I()}`};function M(e){if("object"!=typeof e||null===e)return!1;let t=e;for(;null!==Object.getPrototypeOf(t);)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t||null===Object.getPrototypeOf(e)}function j(e){if(void 0===e)return"undefined";if(null===e)return"null";const t=typeof e;switch(t){case"boolean":case"string":case"number":case"symbol":case"function":return t}if(Array.isArray(e))return"array";if(function(e){return e instanceof Date||"function"==typeof e.toDateString&&"function"==typeof e.getDate&&"function"==typeof e.setDate}(e))return"date";if(function(e){return e instanceof Error||"string"==typeof e.message&&e.constructor&&"number"==typeof e.constructor.stackTraceLimit}(e))return"error";const r=function(e){return"function"==typeof e.constructor?e.constructor.name:null}(e);switch(r){case"Symbol":case"Promise":case"WeakMap":case"WeakSet":case"Map":case"Set":return r}return Object.prototype.toString.call(e).slice(8,-1).toLowerCase().replace(/\s/g,"")}function L(e){let t=typeof e;return t=j(e),t}function A(e,t,r){if("function"!=typeof e)throw new Error(`Expected the root reducer to be a function. Instead, received: '${L(e)}'`);if("function"==typeof t&&"function"==typeof r||"function"==typeof r&&"function"==typeof arguments[3])throw new Error("It looks like you are passing several store enhancers to createStore(). This is not supported. Instead, compose them together to a single function. See https://redux.js.org/tutorials/fundamentals/part-4-store#creating-a-store-with-enhancers for an example.");if("function"==typeof t&&void 0===r&&(r=t,t=void 0),void 0!==r){if("function"!=typeof r)throw new Error(`Expected the enhancer to be a function. Instead, received: '${L(r)}'`);return r(A)(e,t)}let i=e,n=t,s=new Map,o=s,a=0,c=!1;function d(){o===s&&(o=new Map,s.forEach(((e,t)=>{o.set(t,e)})))}function l(){if(c)throw new Error("You may not call store.getState() while the reducer is executing. The reducer has already received the state as an argument. Pass it down from the top reducer instead of reading it from the store.");return n}function u(e){if("function"!=typeof e)throw new Error(`Expected the listener to be a function. Instead, received: '${L(e)}'`);if(c)throw new Error("You may not call store.subscribe() while the reducer is executing. If you would like to be notified after the store has been updated, subscribe from a component and invoke store.getState() in the callback to access the latest state. See https://redux.js.org/api/store#subscribelistener for more details.");let t=!0;d();const r=a++;return o.set(r,e),function(){if(t){if(c)throw new Error("You may not unsubscribe from a store listener while the reducer is executing. See https://redux.js.org/api/store#subscribelistener for more details.");t=!1,d(),o.delete(r),s=null}}}function p(e){if(!M(e))throw new Error(`Actions must be plain objects. Instead, the actual type was: '${L(e)}'. You may need to add middleware to your store setup to handle dispatching other values, such as 'redux-thunk' to handle dispatching functions. See https://redux.js.org/tutorials/fundamentals/part-4-store#middleware and https://redux.js.org/tutorials/fundamentals/part-6-async-logic#using-the-redux-thunk-middleware for examples.`);if(void 0===e.type)throw new Error('Actions may not have an undefined "type" property. You may have misspelled an action type string constant.');if("string"!=typeof e.type)throw new Error(`Action "type" property must be a string. Instead, the actual type was: '${L(e.type)}'. Value was: '${e.type}' (stringified)`);if(c)throw new Error("Reducers may not dispatch actions.");try{c=!0,n=i(n,e)}finally{c=!1}return(s=o).forEach((e=>{e()})),e}p({type:x.INIT});return{dispatch:p,subscribe:u,getState:l,replaceReducer:function(e){if("function"!=typeof e)throw new Error(`Expected the nextReducer to be a function. Instead, received: '${L(e)}`);i=e,p({type:x.REPLACE})},[D]:function(){const e=u;return{subscribe(t){if("object"!=typeof t||null===t)throw new Error(`Expected the observer to be an object. Instead, received: '${L(t)}'`);function r(){const e=t;e.next&&e.next(l())}r();return{unsubscribe:e(r)}},[D](){return this}}}}}function N(e){"undefined"!=typeof console&&"function"==typeof console.error&&console.error(e);try{throw new Error(e)}catch(e){}}function B(e){const t=Object.keys(e),r={};for(let i=0;i<t.length;i++){const n=t[i];void 0===e[n]&&N(`No reducer provided for key "${n}"`),"function"==typeof e[n]&&(r[n]=e[n])}const i=Object.keys(r);let n,s;n={};try{!function(e){Object.keys(e).forEach((t=>{const r=e[t];if(void 0===r(void 0,{type:x.INIT}))throw new Error(`The slice reducer for key "${t}" returned undefined during initialization. If the state passed to the reducer is undefined, you must explicitly return the initial state. The initial state may not be undefined. If you don't want to set a value for this reducer, you can use null instead of undefined.`);if(void 0===r(void 0,{type:x.PROBE_UNKNOWN_ACTION()}))throw new Error(`The slice reducer for key "${t}" returned undefined when probed with a random type. Don't try to handle '${x.INIT}' or other actions in "redux/*" namespace. They are considered private. Instead, you must return the current state for any unknown actions, unless it is undefined, in which case you must return the initial state, regardless of the action type. The initial state may not be undefined, but can be null.`)}))}(r)}catch(e){s=e}return function(e={},t){if(s)throw s;{const i=function(e,t,r,i){const n=Object.keys(t),s=r&&r.type===x.INIT?"preloadedState argument passed to createStore":"previous state received by the reducer";if(0===n.length)return"Store does not have a valid reducer. Make sure the argument passed to combineReducers is an object whose values are reducers.";if(!M(e))return`The ${s} has unexpected type of "${L(e)}". Expected argument to be an object with the following keys: "${n.join('", "')}"`;const o=Object.keys(e).filter((e=>!t.hasOwnProperty(e)&&!i[e]));return o.forEach((e=>{i[e]=!0})),r&&r.type===x.REPLACE?void 0:o.length>0?`Unexpected ${o.length>1?"keys":"key"} "${o.join('", "')}" found in ${s}. Expected to find one of the known reducer keys instead: "${n.join('", "')}". Unexpected keys will be ignored.`:void 0}(e,r,t,n);i&&N(i)}let o=!1;const a={};for(let n=0;n<i.length;n++){const s=i[n],c=r[s],d=e[s],l=c(d,t);if(void 0===l){const e=t&&t.type;throw new Error(`When called with an action of type ${e?`"${String(e)}"`:"(unknown type)"}, the slice reducer for key "${s}" returned undefined. To ignore an action, you must explicitly return the previous state. If you want this reducer to hold no value, you can return null instead of undefined.`)}a[s]=l,o=o||l!==d}return o=o||i.length!==Object.keys(e).length,o?a:e}}function F(...e){return 0===e.length?e=>e:1===e.length?e[0]:e.reduce(((e,t)=>(...r)=>e(t(...r))))}function z(e){return M(e)&&"type"in e&&"string"==typeof e.type}var V=Symbol.for("immer-nothing"),U=Symbol.for("immer-draftable"),$=Symbol.for("immer-state"),G=[function(e){return`The plugin for '${e}' has not been loaded into Immer. To enable the plugin, import and call \`enable${e}()\` when initializing your application.`},function(e){return`produce can only be called on things that are draftable: plain objects, arrays, Map, Set or classes that are marked with '[immerable]: true'. Got '${e}'`},"This object has been frozen and should not be mutated",function(e){return"Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? "+e},"An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.","Immer forbids circular references","The first or second argument to `produce` must be a function","The third argument to `produce` must be a function or undefined","First argument to `createDraft` must be a plain object, an array, or an immerable object","First argument to `finishDraft` must be a draft returned by `createDraft`",function(e){return`'current' expects a draft, got: ${e}`},"Object.defineProperty() cannot be used on an Immer draft","Object.setPrototypeOf() cannot be used on an Immer draft","Immer only supports deleting array indices","Immer only supports setting array indices and the 'length' property",function(e){return`'original' expects a draft, got: ${e}`}];function q(e,...t){{const r=G[e],i="function"==typeof r?r.apply(null,t):r;throw new Error(`[Immer] ${i}`)}}var H=Object.getPrototypeOf;function W(e){return!!e&&!!e[$]}function K(e){return!!e&&(X(e)||Array.isArray(e)||!!e[U]||!!e.constructor?.[U]||te(e)||re(e))}var J=Object.prototype.constructor.toString();function X(e){if(!e||"object"!=typeof e)return!1;const t=H(e);if(null===t)return!0;const r=Object.hasOwnProperty.call(t,"constructor")&&t.constructor;return r===Object||"function"==typeof r&&Function.toString.call(r)===J}function Q(e,t){0===Z(e)?Object.entries(e).forEach((([r,i])=>{t(r,i,e)})):e.forEach(((r,i)=>t(i,r,e)))}function Z(e){const t=e[$];return t?t.type_:Array.isArray(e)?1:te(e)?2:re(e)?3:0}function Y(e,t){return 2===Z(e)?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function ee(e,t,r){const i=Z(e);2===i?e.set(t,r):3===i?e.add(r):e[t]=r}function te(e){return e instanceof Map}function re(e){return e instanceof Set}function ie(e){return e.copy_||e.base_}function ne(e,t){if(te(e))return new Map(e);if(re(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);if(!t&&X(e)){if(!H(e)){const t=Object.create(null);return Object.assign(t,e)}return{...e}}const r=Object.getOwnPropertyDescriptors(e);delete r[$];let i=Reflect.ownKeys(r);for(let t=0;t<i.length;t++){const n=i[t],s=r[n];!1===s.writable&&(s.writable=!0,s.configurable=!0),(s.get||s.set)&&(r[n]={configurable:!0,writable:!0,enumerable:s.enumerable,value:e[n]})}return Object.create(H(e),r)}function se(e,t=!1){return ae(e)||W(e)||!K(e)||(Z(e)>1&&(e.set=e.add=e.clear=e.delete=oe),Object.freeze(e),t&&Q(e,((e,t)=>se(t,!0)))),e}function oe(){q(2)}function ae(e){return Object.isFrozen(e)}var ce,de={};function le(e){const t=de[e];return t||q(0,e),t}function ue(){return ce}function pe(e,t){t&&(le("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function he(e){fe(e),e.drafts_.forEach(ge),e.drafts_=null}function fe(e){e===ce&&(ce=e.parent_)}function me(e){return ce={drafts_:[],parent_:ce,immer_:e,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function ge(e){const t=e[$];0===t.type_||1===t.type_?t.revoke_():t.revoked_=!0}function ve(e,t){t.unfinalizedDrafts_=t.drafts_.length;const r=t.drafts_[0];return void 0!==e&&e!==r?(r[$].modified_&&(he(t),q(4)),K(e)&&(e=be(t,e),t.parent_||we(t,e)),t.patches_&&le("Patches").generateReplacementPatches_(r[$].base_,e,t.patches_,t.inversePatches_)):e=be(t,r,[]),he(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==V?e:void 0}function be(e,t,r){if(ae(t))return t;const i=t[$];if(!i)return Q(t,((n,s)=>ye(e,i,t,n,s,r))),t;if(i.scope_!==e)return t;if(!i.modified_)return we(e,i.base_,!0),i.base_;if(!i.finalized_){i.finalized_=!0,i.scope_.unfinalizedDrafts_--;const t=i.copy_;let n=t,s=!1;3===i.type_&&(n=new Set(t),t.clear(),s=!0),Q(n,((n,o)=>ye(e,i,t,n,o,r,s))),we(e,t,!1),r&&e.patches_&&le("Patches").generatePatches_(i,r,e.patches_,e.inversePatches_)}return i.copy_}function ye(e,t,r,i,n,s,o){if(n===r&&q(5),W(n)){const o=be(e,n,s&&t&&3!==t.type_&&!Y(t.assigned_,i)?s.concat(i):void 0);if(ee(r,i,o),!W(o))return;e.canAutoFreeze_=!1}else o&&r.add(n);if(K(n)&&!ae(n)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;be(e,n),t&&t.scope_.parent_||we(e,n)}}function we(e,t,r=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&se(t,r)}var _e={get(e,t){if(t===$)return e;const r=ie(e);if(!Y(r,t))return function(e,t,r){const i=Re(t,r);return i?"value"in i?i.value:i.get?.call(e.draft_):void 0}(e,r,t);const i=r[t];return e.finalized_||!K(i)?i:i===Ce(e.base_,t)?(Te(e),e.copy_[t]=Pe(i,e)):i},has:(e,t)=>t in ie(e),ownKeys:e=>Reflect.ownKeys(ie(e)),set(e,t,r){const i=Re(ie(e),t);if(i?.set)return i.set.call(e.draft_,r),!0;if(!e.modified_){const i=Ce(ie(e),t),o=i?.[$];if(o&&o.base_===r)return e.copy_[t]=r,e.assigned_[t]=!1,!0;if(((n=r)===(s=i)?0!==n||1/n==1/s:n!=n&&s!=s)&&(void 0!==r||Y(e.base_,t)))return!0;Te(e),ke(e)}var n,s;return e.copy_[t]===r&&(void 0!==r||t in e.copy_)||Number.isNaN(r)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=r,e.assigned_[t]=!0),!0},deleteProperty:(e,t)=>(void 0!==Ce(e.base_,t)||t in e.base_?(e.assigned_[t]=!1,Te(e),ke(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0),getOwnPropertyDescriptor(e,t){const r=ie(e),i=Reflect.getOwnPropertyDescriptor(r,t);return i?{writable:!0,configurable:1!==e.type_||"length"!==t,enumerable:i.enumerable,value:r[t]}:i},defineProperty(){q(11)},getPrototypeOf:e=>H(e.base_),setPrototypeOf(){q(12)}},Se={};function Ce(e,t){const r=e[$];return(r?ie(r):e)[t]}function Re(e,t){if(!(t in e))return;let r=H(e);for(;r;){const e=Object.getOwnPropertyDescriptor(r,t);if(e)return e;r=H(r)}}function ke(e){e.modified_||(e.modified_=!0,e.parent_&&ke(e.parent_))}function Te(e){e.copy_||(e.copy_=ne(e.base_,e.scope_.immer_.useStrictShallowCopy_))}Q(_e,((e,t)=>{Se[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}})),Se.deleteProperty=function(e,t){return isNaN(parseInt(t))&&q(13),Se.set.call(this,e,t,void 0)},Se.set=function(e,t,r){return"length"!==t&&isNaN(parseInt(t))&&q(14),_e.set.call(this,e[0],t,r,e[0])};function Pe(e,t){const r=te(e)?le("MapSet").proxyMap_(e,t):re(e)?le("MapSet").proxySet_(e,t):function(e,t){const r=Array.isArray(e),i={type_:r?1:0,scope_:t?t.scope_:ue(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1};let n=i,s=_e;r&&(n=[i],s=Se);const{revoke:o,proxy:a}=Proxy.revocable(n,s);return i.draft_=a,i.revoke_=o,a}(e,t);return(t?t.scope_:ue()).drafts_.push(r),r}function Oe(e){return W(e)||q(10,e),Ee(e)}function Ee(e){if(!K(e)||ae(e))return e;const t=e[$];let r;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,r=ne(e,t.scope_.immer_.useStrictShallowCopy_)}else r=ne(e,!0);return Q(r,((e,t)=>{ee(r,e,Ee(t))})),t&&(t.finalized_=!1),r}var De=new class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.produce=(e,t,r)=>{if("function"==typeof e&&"function"!=typeof t){const r=t;t=e;const i=this;return function(e=r,...n){return i.produce(e,(e=>t.call(this,e,...n)))}}let i;if("function"!=typeof t&&q(6),void 0!==r&&"function"!=typeof r&&q(7),K(e)){const n=me(this),s=Pe(e,void 0);let o=!0;try{i=t(s),o=!1}finally{o?he(n):fe(n)}return pe(n,r),ve(i,n)}if(!e||"object"!=typeof e){if(i=t(e),void 0===i&&(i=e),i===V&&(i=void 0),this.autoFreeze_&&se(i,!0),r){const t=[],n=[];le("Patches").generateReplacementPatches_(e,i,t,n),r(t,n)}return i}q(1,e)},this.produceWithPatches=(e,t)=>{if("function"==typeof e)return(t,...r)=>this.produceWithPatches(t,(t=>e(t,...r)));let r,i;return[this.produce(e,t,((e,t)=>{r=e,i=t})),r,i]},"boolean"==typeof e?.autoFreeze&&this.setAutoFreeze(e.autoFreeze),"boolean"==typeof e?.useStrictShallowCopy&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){K(e)||q(8),W(e)&&(e=Oe(e));const t=me(this),r=Pe(e,void 0);return r[$].isManual_=!0,fe(t),r}finishDraft(e,t){const r=e&&e[$];r&&r.isManual_||q(9);const{scope_:i}=r;return pe(i,t),ve(void 0,i)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}applyPatches(e,t){let r;for(r=t.length-1;r>=0;r--){const i=t[r];if(0===i.path.length&&"replace"===i.op){e=i.value;break}}r>-1&&(t=t.slice(r+1));const i=le("Patches").applyPatches_;return W(e)?i(e,t):this.produce(e,(e=>i(e,t)))}},Ie=De.produce;De.produceWithPatches.bind(De),De.setAutoFreeze.bind(De),De.setUseStrictShallowCopy.bind(De),De.applyPatches.bind(De),De.createDraft.bind(De),De.finishDraft.bind(De);var xe=(e,t,r)=>{if(1===t.length&&t[0]===r){let t=!1;try{const r={};e(r)===r&&(t=!0)}catch{}if(t){let e;try{throw new Error}catch(t){({stack:e}=t)}console.warn("The result function returned its own inputs without modification. e.g\n`createSelector([state => state.todos], todos => todos)`\nThis could lead to inefficient memoization and unnecessary re-renders.\nEnsure transformation logic is in the result function, and extraction logic is in the input selectors.",{stack:e})}}},Me=(e,t,r)=>{const{memoize:i,memoizeOptions:n}=t,{inputSelectorResults:s,inputSelectorResultsCopy:o}=e,a=i((()=>({})),...n);if(!(a.apply(null,s)===a.apply(null,o))){let e;try{throw new Error}catch(t){({stack:e}=t)}console.warn("An input selector returned a different result when passed same arguments.\nThis means your output selector will likely run more frequently than intended.\nAvoid returning a new reference inside your input selector, e.g.\n`createSelector([state => state.todos.map(todo => todo.id)], todoIds => todoIds.length)`",{arguments:r,firstInputs:s,secondInputs:o,stack:e})}},je={inputStabilityCheck:"once",identityFunctionCheck:"once"};var Le=e=>Array.isArray(e)?e:[e];function Ae(e){const t=Array.isArray(e[0])?e[0]:e;return function(e,t="expected all items to be functions, instead received the following types: "){if(!e.every((e=>"function"==typeof e))){const r=e.map((e=>"function"==typeof e?`function ${e.name||"unnamed"}()`:typeof e)).join(", ");throw new TypeError(`${t}[${r}]`)}}(t,"createSelector expects all input-selectors to be functions, but received the following types: "),t}function Ne(e,t){const r=[],{length:i}=e;for(let n=0;n<i;n++)r.push(e[n].apply(null,t));return r}var Be="undefined"!=typeof WeakRef?WeakRef:class{constructor(e){this.value=e}deref(){return this.value}},Fe=0,ze=1;function Ve(){return{s:Fe,v:void 0,o:null,p:null}}function Ue(e,t={}){let r=Ve();const{resultEqualityCheck:i}=t;let n,s=0;function o(){let t=r;const{length:o}=arguments;for(let e=0,r=o;e<r;e++){const r=arguments[e];if("function"==typeof r||"object"==typeof r&&null!==r){let e=t.o;null===e&&(t.o=e=new WeakMap);const i=e.get(r);void 0===i?(t=Ve(),e.set(r,t)):t=i}else{let e=t.p;null===e&&(t.p=e=new Map);const i=e.get(r);void 0===i?(t=Ve(),e.set(r,t)):t=i}}const a=t;let c;if(t.s===ze?c=t.v:(c=e.apply(null,arguments),s++),a.s=ze,i){const e=n?.deref?.()??n;null!=e&&i(e,c)&&(c=e,0!==s&&s--);n="object"==typeof c&&null!==c||"function"==typeof c?new Be(c):c}return a.v=c,c}return o.clearCache=()=>{r=Ve(),o.resetResultsCount()},o.resultsCount=()=>s,o.resetResultsCount=()=>{s=0},o}function $e(e,...t){const r="function"==typeof e?{memoize:e,memoizeOptions:t}:e,i=(...e)=>{let t,i=0,n=0,s={},o=e.pop();"object"==typeof o&&(s=o,o=e.pop()),function(e,t="expected a function, instead received "+typeof e){if("function"!=typeof e)throw new TypeError(t)}(o,`createSelector expects an output function after the inputs, but received: [${typeof o}]`);const a={...r,...s},{memoize:c,memoizeOptions:d=[],argsMemoize:l=Ue,argsMemoizeOptions:u=[],devModeChecks:p={}}=a,h=Le(d),f=Le(u),m=Ae(e),g=c((function(){return i++,o.apply(null,arguments)}),...h);let v=!0;const b=l((function(){n++;const e=Ne(m,arguments);t=g.apply(null,e);{const{identityFunctionCheck:r,inputStabilityCheck:i}=((e,t)=>{const{identityFunctionCheck:r,inputStabilityCheck:i}={...je,...t};return{identityFunctionCheck:{shouldRun:"always"===r||"once"===r&&e,run:xe},inputStabilityCheck:{shouldRun:"always"===i||"once"===i&&e,run:Me}}})(v,p);if(r.shouldRun&&r.run(o,e,t),i.shouldRun){const t=Ne(m,arguments);i.run({inputSelectorResults:e,inputSelectorResultsCopy:t},{memoize:c,memoizeOptions:h},arguments)}v&&(v=!1)}return t}),...f);return Object.assign(b,{resultFunc:o,memoizedResultFunc:g,dependencies:m,dependencyRecomputations:()=>n,resetDependencyRecomputations:()=>{n=0},lastResult:()=>t,recomputations:()=>i,resetRecomputations:()=>{i=0},memoize:c,argsMemoize:l})};return Object.assign(i,{withTypes:()=>i}),i}var Ge=$e(Ue),qe=Object.assign(((e,t=Ge)=>{!function(e,t="expected an object, instead received "+typeof e){if("object"!=typeof e)throw new TypeError(t)}(e,"createStructuredSelector expects first argument to be an object where each property is a selector, instead received a "+typeof e);const r=Object.keys(e),i=t(r.map((t=>e[t])),((...e)=>e.reduce(((e,t,i)=>(e[r[i]]=t,e)),{})));return i}),{withTypes:()=>qe});function He(e){return({dispatch:t,getState:r})=>i=>n=>"function"==typeof n?n(t,r,e):i(n)}var We=He(),Ke=He;((...e)=>{const t=$e(...e),r=Object.assign(((...e)=>{const r=t(...e),i=(e,...t)=>r(W(e)?Oe(e):e,...t);return Object.assign(i,r),i}),{withTypes:()=>r})})(Ue);var Je="undefined"!=typeof window&&window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__?window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__:function(){if(0!==arguments.length)return"object"==typeof arguments[0]?F:F.apply(null,arguments)},Xe=e=>e&&"function"==typeof e.match;function Qe(e,t){function r(...r){if(t){let i=t(...r);if(!i)throw new Error("prepareAction did not return an object");return{type:e,payload:i.payload,..."meta"in i&&{meta:i.meta},..."error"in i&&{error:i.error}}}return{type:e,payload:r[0]}}return r.toString=()=>`${e}`,r.type=e,r.match=t=>z(t)&&t.type===e,r}function Ze(e){return"function"==typeof e&&"type"in e&&Xe(e)}function Ye(e,t){let r=0;return{measureTime(e){const t=Date.now();try{return e()}finally{const e=Date.now();r+=e-t}},warnIfExceeded(){r>e&&console.warn(`${t} took ${r}ms, which is more than the warning threshold of ${e}ms. \nIf your state or actions are very large, you may want to disable the middleware as it might cause too much of a slowdown in development mode. See https://redux-toolkit.js.org/api/getDefaultMiddleware for instructions.\nIt is disabled in production builds, so you don't need to worry about that.`)}}}function et(e,t){for(const r of e)if(t(r))return r}var tt=class e extends Array{constructor(...t){super(...t),Object.setPrototypeOf(this,e.prototype)}static get[Symbol.species](){return e}concat(...e){return super.concat.apply(this,e)}prepend(...t){return 1===t.length&&Array.isArray(t[0])?new e(...t[0].concat(this)):new e(...t.concat(this))}};function rt(e){return K(e)?Ie(e,(()=>{})):e}function it(e,t,r){if(e.has(t)){let i=e.get(t);return r.update&&(i=r.update(i,t,e),e.set(t,i)),i}if(!r.insert)throw new Error("No insert provided for key not already in map");const i=r.insert(t,e);return e.set(t,i),i}function nt(e){return"object"!=typeof e||null==e||Object.isFrozen(e)}function st(e,t,r){const i=ot(e,t,r);return{detectMutations:()=>at(e,t,i,r)}}function ot(e,t=[],r,i="",n=new Set){const s={value:r};if(!e(r)&&!n.has(r)){n.add(r),s.children={};for(const n in r){const o=i?i+"."+n:n;t.length&&-1!==t.indexOf(o)||(s.children[n]=ot(e,t,r[n],o))}}return s}function at(e,t=[],r,i,n=!1,s=""){const o=r?r.value:void 0,a=o===i;if(n&&!a&&!Number.isNaN(i))return{wasMutated:!0,path:s};if(e(o)||e(i))return{wasMutated:!1};const c={};for(let e in r.children)c[e]=!0;for(let e in i)c[e]=!0;const d=t.length>0;for(let n in c){const o=s?s+"."+n:n;if(d){if(t.some((e=>e instanceof RegExp?e.test(o):o===e)))continue}const c=at(e,t,r.children[n],i[n],a,o);if(c.wasMutated)return c}return{wasMutated:!1}}function ct(e){const t=typeof e;return null==e||"string"===t||"boolean"===t||"number"===t||Array.isArray(e)||M(e)}function dt(e,t="",r=ct,i,n=[],s){let o;if(!r(e))return{keyPath:t||"<root>",value:e};if("object"!=typeof e||null===e)return!1;if(s?.has(e))return!1;const a=null!=i?i(e):Object.entries(e),c=n.length>0;for(const[e,d]of a){const a=t?t+"."+e:e;if(c){if(n.some((e=>e instanceof RegExp?e.test(a):a===e)))continue}if(!r(d))return{keyPath:a,value:d};if("object"==typeof d&&(o=dt(d,a,r,i,n,s),o))return o}return s&<(e)&&s.add(e),!1}function lt(e){if(!Object.isFrozen(e))return!1;for(const t of Object.values(e))if("object"==typeof t&&null!==t&&!lt(t))return!1;return!0}function ut(e){return"boolean"==typeof e}var pt=()=>function(e){const{thunk:t=!0,immutableCheck:r=!0,serializableCheck:i=!0,actionCreatorCheck:n=!0}=e??{};let s=new tt;if(t&&(ut(t)?s.push(We):s.push(Ke(t.extraArgument))),r){let e={};ut(r)||(e=r),s.unshift(function(e={}){{let t=function(e,t,i,n){return JSON.stringify(e,r(t,n),i)},r=function(e,t){let r=[],i=[];return t||(t=function(e,t){return r[0]===t?"[Circular ~]":"[Circular ~."+i.slice(0,r.indexOf(t)).join(".")+"]"}),function(n,s){if(r.length>0){var o=r.indexOf(this);~o?r.splice(o+1):r.push(this),~o?i.splice(o,1/0,n):i.push(n),~r.indexOf(s)&&(s=t.call(this,n,s))}else r.push(s);return null==e?s:e.call(this,n,s)}},{isImmutable:i=nt,ignoredPaths:n,warnAfter:s=32}=e;const o=st.bind(null,i,n);return({getState:e})=>{let r,i=e(),n=o(i);return a=>c=>{const d=Ye(s,"ImmutableStateInvariantMiddleware");d.measureTime((()=>{if(i=e(),r=n.detectMutations(),n=o(i),r.wasMutated)throw new Error(`A state mutation was detected between dispatches, in the path '${r.path||""}'. This may cause incorrect behavior. (https://redux.js.org/style-guide/style-guide#do-not-mutate-state)`)}));const l=a(c);return d.measureTime((()=>{if(i=e(),r=n.detectMutations(),n=o(i),r.wasMutated)throw new Error(`A state mutation was detected inside a dispatch, in the path: ${r.path||""}. Take a look at the reducer(s) handling the action ${t(c)}. (https://redux.js.org/style-guide/style-guide#do-not-mutate-state)`)})),d.warnIfExceeded(),l}}}}(e))}if(i){let e={};ut(i)||(e=i),s.push(function(e={}){{const{isSerializable:t=ct,getEntries:r,ignoredActions:i=[],ignoredActionPaths:n=["meta.arg","meta.baseQueryMeta"],ignoredPaths:s=[],warnAfter:o=32,ignoreState:a=!1,ignoreActions:c=!1,disableCache:d=!1}=e,l=!d&&WeakSet?new WeakSet:void 0;return e=>d=>u=>{if(!z(u))return d(u);const p=d(u),h=Ye(o,"SerializableStateInvariantMiddleware");return c||i.length&&-1!==i.indexOf(u.type)||h.measureTime((()=>{const e=dt(u,"",t,r,n,l);if(e){const{keyPath:t,value:r}=e;console.error(`A non-serializable value was detected in an action, in the path: \`${t}\`. Value:`,r,"\nTake a look at the logic that dispatched this action: ",u,"\n(See https://redux.js.org/faq/actions#why-should-type-be-a-string-or-at-least-serializable-why-should-my-action-types-be-constants)","\n(To allow non-serializable values see: https://redux-toolkit.js.org/usage/usage-guide#working-with-non-serializable-data)")}})),a||(h.measureTime((()=>{const i=dt(e.getState(),"",t,r,s,l);if(i){const{keyPath:e,value:t}=i;console.error(`A non-serializable value was detected in the state, in the path: \`${e}\`. Value:`,t,`\nTake a look at the reducer(s) handling this action type: ${u.type}.\n(See https://redux.js.org/faq/organizing-state#can-i-put-functions-promises-or-other-non-serializable-items-in-my-store-state)`)}})),h.warnIfExceeded()),p}}}(e))}if(n){let e={};ut(n)||(e=n),s.unshift(function(e={}){const{isActionCreator:t=Ze}=e;return()=>e=>r=>(t(r)&&console.warn(function(e){const t=e?`${e}`.split("/"):[],r=t[t.length-1]||"actionCreator";return`Detected an action creator with type "${e||"unknown"}" being dispatched. \nMake sure you're calling the action creator before dispatching, i.e. \`dispatch(${r}())\` instead of \`dispatch(${r})\`. This is necessary even if the action has no payload.`}(r.type)),e(r))}(e))}return s},ht=e=>t=>{setTimeout(t,e)},ft="undefined"!=typeof window&&window.requestAnimationFrame?window.requestAnimationFrame:ht(10),mt=e=>function(t){const{autoBatch:r=!0}=t??{};let i=new tt(e);return r&&i.push(((e={type:"raf"})=>t=>(...r)=>{const i=t(...r);let n=!0,s=!1,o=!1;const a=new Set,c="tick"===e.type?queueMicrotask:"raf"===e.type?ft:"callback"===e.type?e.queueNotification:ht(e.timeout),d=()=>{o=!1,s&&(s=!1,a.forEach((e=>e())))};return Object.assign({},i,{subscribe(e){const t=i.subscribe((()=>n&&e()));return a.add(e),()=>{t(),a.delete(e)}},dispatch(e){try{return n=!e?.meta?.RTK_autoBatch,s=!n,s&&(o||(o=!0,c(d))),i.dispatch(e)}finally{n=!0}}})})("object"==typeof r?r:void 0)),i};function gt(e){const t=pt(),{reducer:r,middleware:i,devTools:n=!0,preloadedState:s,enhancers:o}=e||{};let a,c;if("function"==typeof r)a=r;else{if(!M(r))throw new Error("`reducer` is a required argument, and must be a function or an object of functions that can be passed to combineReducers");a=B(r)}if(i&&"function"!=typeof i)throw new Error("`middleware` field must be a callback");if("function"==typeof i){if(c=i(t),!Array.isArray(c))throw new Error("when using a middleware builder function, an array of middleware must be returned")}else c=t();if(c.some((e=>"function"!=typeof e)))throw new Error("each middleware provided to configureStore must be a function");let d=F;n&&(d=Je({trace:!0,..."object"==typeof n&&n}));const l=function(...e){return t=>(r,i)=>{const n=t(r,i);let s=()=>{throw new Error("Dispatching while constructing your middleware is not allowed. Other middleware would not be applied to this dispatch.")};const o={getState:n.getState,dispatch:(e,...t)=>s(e,...t)},a=e.map((e=>e(o)));return s=F(...a)(n.dispatch),{...n,dispatch:s}}}(...c),u=mt(l);if(o&&"function"!=typeof o)throw new Error("`enhancers` field must be a callback");let p="function"==typeof o?o(u):u();if(!Array.isArray(p))throw new Error("`enhancers` callback must return an array");if(p.some((e=>"function"!=typeof e)))throw new Error("each enhancer provided to configureStore must be a function");c.length&&!p.includes(l)&&console.error("middlewares were provided, but middleware enhancer was not included in final enhancers - make sure to call `getDefaultEnhancers`");return A(a,s,d(...p))}function vt(e){const t={},r=[];let i;const n={addCase(e,s){if(r.length>0)throw new Error("`builder.addCase` should only be called before calling `builder.addMatcher`");if(i)throw new Error("`builder.addCase` should only be called before calling `builder.addDefaultCase`");const o="string"==typeof e?e:e.type;if(!o)throw new Error("`builder.addCase` cannot be called with an empty action type");if(o in t)throw new Error(`\`builder.addCase\` cannot be called with two reducers for the same action type '${o}'`);return t[o]=s,n},addMatcher(e,t){if(i)throw new Error("`builder.addMatcher` should only be called before calling `builder.addDefaultCase`");return r.push({matcher:e,reducer:t}),n},addDefaultCase(e){if(i)throw new Error("`builder.addDefaultCase` can only be called once");return i=e,n}};return e(n),[t,r,i]}var bt=(e=21)=>{let t="",r=e;for(;r--;)t+="ModuleSymbhasOwnPr-0123456789ABCDEFGHNRVfgctiUvz_KqYTJkLxpZXIjQW"[64*Math.random()|0];return t};function yt(...e){return t=>e.some((e=>((e,t)=>Xe(e)?e.match(t):e(t))(e,t)))}var wt=["name","message","stack","code"],_t=class{constructor(e,t){this.payload=e,this.meta=t}_type},St=class{constructor(e,t){this.payload=e,this.meta=t}_type},Ct=e=>{if("object"==typeof e&&null!==e){const t={};for(const r of wt)"string"==typeof e[r]&&(t[r]=e[r]);return t}return{message:String(e)}},Rt=(()=>{function e(e,t,r){const i=Qe(e+"/fulfilled",((e,t,r,i)=>({payload:e,meta:{...i||{},arg:r,requestId:t,requestStatus:"fulfilled"}}))),n=Qe(e+"/pending",((e,t,r)=>({payload:void 0,meta:{...r||{},arg:t,requestId:e,requestStatus:"pending"}}))),s=Qe(e+"/rejected",((e,t,i,n,s)=>({payload:n,error:(r&&r.serializeError||Ct)(e||"Rejected"),meta:{...s||{},arg:i,requestId:t,rejectedWithValue:!!n,requestStatus:"rejected",aborted:"AbortError"===e?.name,condition:"ConditionError"===e?.name}})));return Object.assign((function(e){return(o,a,c)=>{const d=r?.idGenerator?r.idGenerator(e):bt(),l=new AbortController;let u,p;function h(e){p=e,l.abort()}const f=async function(){let f;try{let s=r?.condition?.(e,{getState:a,extra:c});if(function(e){return null!==e&&"object"==typeof e&&"function"==typeof e.then}(s)&&(s=await s),!1===s||l.signal.aborted)throw{name:"ConditionError",message:"Aborted due to condition callback returning false."};const m=new Promise(((e,t)=>{u=()=>{t({name:"AbortError",message:p||"Aborted"})},l.signal.addEventListener("abort",u)}));o(n(d,e,r?.getPendingMeta?.({requestId:d,arg:e},{getState:a,extra:c}))),f=await Promise.race([m,Promise.resolve(t(e,{dispatch:o,getState:a,extra:c,requestId:d,signal:l.signal,abort:h,rejectWithValue:(e,t)=>new _t(e,t),fulfillWithValue:(e,t)=>new St(e,t)})).then((t=>{if(t instanceof _t)throw t;return t instanceof St?i(t.payload,d,e,t.meta):i(t,d,e)}))])}catch(t){f=t instanceof _t?s(null,d,e,t.payload,t.meta):s(t,d,e)}finally{u&&l.signal.removeEventListener("abort",u)}return r&&!r.dispatchConditionRejection&&s.match(f)&&f.meta.condition||o(f),f}();return Object.assign(f,{abort:h,requestId:d,arg:e,unwrap:()=>f.then(kt)})}}),{pending:n,rejected:s,fulfilled:i,settled:yt(s,i),typePrefix:e})}return e.withTypes=()=>e,e})();function kt(e){if(e.meta&&e.meta.rejectedWithValue)throw e.payload;if(e.error)throw e.error;return e.payload}var Tt=Symbol.for("rtk-slice-createasyncthunk");function Pt(e,t){return`${e}/${t}`}function Ot({creators:e}={}){const t=e?.asyncThunk?.[Tt];return function(e){const{name:r,reducerPath:i=r}=e;if(!r)throw new Error("`name` is a required option for createSlice");const n=("function"==typeof e.reducers?e.reducers(function(){function e(e,t){return{_reducerDefinitionType:"asyncThunk",payloadCreator:e,...t}}return e.withTypes=()=>e,{reducer:e=>Object.assign({[e.name]:(...t)=>e(...t)}[e.name],{_reducerDefinitionType:"reducer"}),preparedReducer:(e,t)=>({_reducerDefinitionType:"reducerWithPrepare",prepare:e,reducer:t}),asyncThunk:e}}()):e.reducers)||{},s=Object.keys(n),o={sliceCaseReducersByName:{},sliceCaseReducersByType:{},actionCreators:{},sliceMatchers:[]},a={addCase(e,t){const r="string"==typeof e?e:e.type;if(!r)throw new Error("`context.addCase` cannot be called with an empty action type");if(r in o.sliceCaseReducersByType)throw new Error("`context.addCase` cannot be called with two reducers for the same action type: "+r);return o.sliceCaseReducersByType[r]=t,a},addMatcher:(e,t)=>(o.sliceMatchers.push({matcher:e,reducer:t}),a),exposeAction:(e,t)=>(o.actionCreators[e]=t,a),exposeCaseReducer:(e,t)=>(o.sliceCaseReducersByName[e]=t,a)};function c(){if("object"==typeof e.extraReducers)throw new Error("The object notation for `createSlice.extraReducers` has been removed. Please use the 'builder callback' notation instead: https://redux-toolkit.js.org/api/createSlice");const[t={},r=[],i]="function"==typeof e.extraReducers?vt(e.extraReducers):[e.extraReducers],n={...t,...o.sliceCaseReducersByType};return function(e,t){if("object"==typeof t)throw new Error("The object notation for `createReducer` has been removed. Please use the 'builder callback' notation instead: https://redux-toolkit.js.org/api/createReducer");let r,[i,n,s]=vt(t);if("function"==typeof e)r=()=>rt(e());else{const t=rt(e);r=()=>t}function o(e=r(),t){let o=[i[t.type],...n.filter((({matcher:e})=>e(t))).map((({reducer:e})=>e))];return 0===o.filter((e=>!!e)).length&&(o=[s]),o.reduce(((e,r)=>{if(r){if(W(e)){const i=r(e,t);return void 0===i?e:i}if(K(e))return Ie(e,(e=>r(e,t)));{const i=r(e,t);if(void 0===i){if(null===e)return e;throw new Error("A case reducer on a non-draftable value must not return undefined")}return i}}return e}),e)}return o.getInitialState=r,o}(e.initialState,(e=>{for(let t in n)e.addCase(t,n[t]);for(let t of o.sliceMatchers)e.addMatcher(t.matcher,t.reducer);for(let t of r)e.addMatcher(t.matcher,t.reducer);i&&e.addDefaultCase(i)}))}s.forEach((i=>{const s=n[i],o={reducerName:i,type:Pt(r,i),createNotation:"function"==typeof e.reducers};!function(e){return"asyncThunk"===e._reducerDefinitionType}(s)?function({type:e,reducerName:t,createNotation:r},i,n){let s,o;if("reducer"in i){if(r&&!function(e){return"reducerWithPrepare"===e._reducerDefinitionType}(i))throw new Error("Please use the `create.preparedReducer` notation for prepared action creators with the `create` notation.");s=i.reducer,o=i.prepare}else s=i;n.addCase(e,s).exposeCaseReducer(t,s).exposeAction(t,o?Qe(e,o):Qe(e))}(o,s,a):function({type:e,reducerName:t},r,i,n){if(!n)throw new Error("Cannot use `create.asyncThunk` in the built-in `createSlice`. Use `buildCreateSlice({ creators: { asyncThunk: asyncThunkCreator } })` to create a customised version of `createSlice`.");const{payloadCreator:s,fulfilled:o,pending:a,rejected:c,settled:d,options:l}=r,u=n(e,s,l);i.exposeAction(t,u),o&&i.addCase(u.fulfilled,o);a&&i.addCase(u.pending,a);c&&i.addCase(u.rejected,c);d&&i.addMatcher(u.settled,d);i.exposeCaseReducer(t,{fulfilled:o||It,pending:a||It,rejected:c||It,settled:d||It})}(o,s,a,t)}));const d=e=>e,l=new Map;let u;function p(e,t){return u||(u=c()),u(e,t)}function h(){return u||(u=c()),u.getInitialState()}function f(t,r=!1){function i(e){let i=e[t];if(void 0===i){if(!r)throw new Error("selectSlice returned undefined for an uninjected slice reducer");i=h()}return i}function n(t=d){const i=it(l,r,{insert:()=>new WeakMap});return it(i,t,{insert:()=>{const i={};for(const[n,s]of Object.entries(e.selectors??{}))i[n]=Et(s,t,h,r);return i}})}return{reducerPath:t,getSelectors:n,get selectors(){return n(i)},selectSlice:i}}const m={name:r,reducer:p,actions:o.actionCreators,caseReducers:o.sliceCaseReducersByName,getInitialState:h,...f(i),injectInto(e,{reducerPath:t,...r}={}){const n=t??i;return e.inject({reducerPath:n,reducer:p},r),{...m,...f(n,!0)}}};return m}}function Et(e,t,r,i){function n(n,...s){let o=t(n);if(void 0===o){if(!i)throw new Error("selectState returned undefined for an uninjected slice reducer");o=r()}return e(o,...s)}return n.unwrapped=e,n}var Dt=Ot();function It(){}var xt="listener",Mt="completed",jt="cancelled",Lt=`task-${jt}`,At=`task-${Mt}`,Nt=`${xt}-${jt}`,Bt=`${xt}-${Mt}`,Ft=class{constructor(e){this.code=e,this.message=`task ${jt} (reason: ${e})`}name="TaskAbortError";message},zt=(e,t)=>{if("function"!=typeof e)throw new Error(`${t} is not a function`)},Vt=()=>{},Ut=(e,t=Vt)=>(e.catch(t),e),$t=(e,t)=>(e.addEventListener("abort",t,{once:!0}),()=>e.removeEventListener("abort",t)),Gt=(e,t)=>{const r=e.signal;r.aborted||("reason"in r||Object.defineProperty(r,"reason",{enumerable:!0,value:t,configurable:!0,writable:!0}),e.abort(t))},qt=e=>{if(e.aborted){const{reason:t}=e;throw new Ft(t)}};function Ht(e,t){let r=Vt;return new Promise(((i,n)=>{const s=()=>n(new Ft(e.reason));e.aborted?s():(r=$t(e,s),t.finally((()=>r())).then(i,n))})).finally((()=>{r=Vt}))}var Wt=e=>t=>Ut(Ht(e,t).then((t=>(qt(e),t)))),Kt=e=>{const t=Wt(e);return e=>t(new Promise((t=>setTimeout(t,e))))},{assign:Jt}=Object,Xt={},Qt="listenerMiddleware",Zt=(e,t)=>(r,i)=>{zt(r,"taskExecutor");const n=new AbortController;var s;s=n,$t(e,(()=>Gt(s,e.reason)));const o=(async(e,t)=>{try{return await Promise.resolve(),{status:"ok",value:await e()}}catch(e){return{status:e instanceof Ft?"cancelled":"rejected",error:e}}finally{t?.()}})((async()=>{qt(e),qt(n.signal);const t=await r({pause:Wt(n.signal),delay:Kt(n.signal),signal:n.signal});return qt(n.signal),t}),(()=>Gt(n,At)));return i?.autoJoin&&t.push(o.catch(Vt)),{result:Wt(e)(o),cancel(){Gt(n,Lt)}}},Yt=(e,t)=>(r,i)=>Ut((async(r,i)=>{qt(t);let n=()=>{};const s=[new Promise(((t,i)=>{let s=e({predicate:r,effect:(e,r)=>{r.unsubscribe(),t([e,r.getState(),r.getOriginalState()])}});n=()=>{s(),i()}}))];null!=i&&s.push(new Promise((e=>setTimeout(e,i,null))));try{const e=await Ht(t,Promise.race(s));return qt(t),e}finally{n()}})(r,i)),er=e=>{let{type:t,actionCreator:r,matcher:i,predicate:n,effect:s}=e;if(t)n=Qe(t).match;else if(r)t=r.type,n=r.match;else if(i)n=i;else if(!n)throw new Error("Creating or removing a listener requires one of the known fields for matching an action");return zt(s,"options.listener"),{predicate:n,type:t,effect:s}},tr=Object.assign((e=>{const{type:t,predicate:r,effect:i}=er(e);return{id:bt(),effect:i,type:t,predicate:r,pending:new Set,unsubscribe:()=>{throw new Error("Unsubscribe not initialized")}}}),{withTypes:()=>tr}),rr=e=>{e.pending.forEach((e=>{Gt(e,Nt)}))},ir=(e,t,r)=>{try{e(t,r)}catch(e){setTimeout((()=>{throw e}),0)}},nr=Object.assign(Qe(`${Qt}/add`),{withTypes:()=>nr}),sr=Qe(`${Qt}/removeAll`),or=Object.assign(Qe(`${Qt}/remove`),{withTypes:()=>or}),ar=(...e)=>{console.error(`${Qt}/error`,...e)};let cr=!0,dr=!0;function lr(e,t,r){const i=e.match(t);return i&&i.length>=r&&parseInt(i[r],10)}function ur(e,t,r){if(!e.RTCPeerConnection)return;const i=e.RTCPeerConnection.prototype,n=i.addEventListener;i.addEventListener=function(e,i){if(e!==t)return n.apply(this,arguments);const s=e=>{const t=r(e);t&&(i.handleEvent?i.handleEvent(t):i(t))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(i,s),n.apply(this,[e,s])};const s=i.removeEventListener;i.removeEventListener=function(e,r){if(e!==t||!this._eventMap||!this._eventMap[t])return s.apply(this,arguments);if(!this._eventMap[t].has(r))return s.apply(this,arguments);const i=this._eventMap[t].get(r);return this._eventMap[t].delete(r),0===this._eventMap[t].size&&delete this._eventMap[t],0===Object.keys(this._eventMap).length&&delete this._eventMap,s.apply(this,[e,i])},Object.defineProperty(i,"on"+t,{get(){return this["_on"+t]},set(e){this["_on"+t]&&(this.removeEventListener(t,this["_on"+t]),delete this["_on"+t]),e&&this.addEventListener(t,this["_on"+t]=e)},enumerable:!0,configurable:!0})}function pr(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(cr=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function hr(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(dr=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function fr(){if("object"==typeof window){if(cr)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function mr(e,t){dr&&console.warn(e+" is deprecated, please use "+t+" instead.")}function gr(e){return"[object Object]"===Object.prototype.toString.call(e)}function vr(e){return gr(e)?Object.keys(e).reduce((function(t,r){const i=gr(e[r]),n=i?vr(e[r]):e[r],s=i&&!Object.keys(n).length;return void 0===n||s?t:Object.assign(t,{[r]:n})}),{}):e}function br(e,t,r){t&&!r.has(t.id)&&(r.set(t.id,t),Object.keys(t).forEach((i=>{i.endsWith("Id")?br(e,e.get(t[i]),r):i.endsWith("Ids")&&t[i].forEach((t=>{br(e,e.get(t),r)}))})))}function yr(e,t,r){const i=r?"outbound-rtp":"inbound-rtp",n=new Map;if(null===t)return n;const s=[];return e.forEach((e=>{"track"===e.type&&e.trackIdentifier===t.id&&s.push(e)})),s.forEach((t=>{e.forEach((r=>{r.type===i&&r.trackId===t.id&&br(e,r,n)}))})),n}const wr=fr;function _r(e,t){const r=e&&e.navigator;if(!r.mediaDevices)return;const i=function(e){if("object"!=typeof e||e.mandatory||e.optional)return e;const t={};return Object.keys(e).forEach((r=>{if("require"===r||"advanced"===r||"mediaSource"===r)return;const i="object"==typeof e[r]?e[r]:{ideal:e[r]};void 0!==i.exact&&"number"==typeof i.exact&&(i.min=i.max=i.exact);const n=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):"deviceId"===t?"sourceId":t};if(void 0!==i.ideal){t.optional=t.optional||[];let e={};"number"==typeof i.ideal?(e[n("min",r)]=i.ideal,t.optional.push(e),e={},e[n("max",r)]=i.ideal,t.optional.push(e)):(e[n("",r)]=i.ideal,t.optional.push(e))}void 0!==i.exact&&"number"!=typeof i.exact?(t.mandatory=t.mandatory||{},t.mandatory[n("",r)]=i.exact):["min","max"].forEach((e=>{void 0!==i[e]&&(t.mandatory=t.mandatory||{},t.mandatory[n(e,r)]=i[e])}))})),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},n=function(e,n){if(t.version>=61)return n(e);if((e=JSON.parse(JSON.stringify(e)))&&"object"==typeof e.audio){const t=function(e,t,r){t in e&&!(r in e)&&(e[r]=e[t],delete e[t])};t((e=JSON.parse(JSON.stringify(e))).audio,"autoGainControl","googAutoGainControl"),t(e.audio,"noiseSuppression","googNoiseSuppression"),e.audio=i(e.audio)}if(e&&"object"==typeof e.video){let s=e.video.facingMode;s=s&&("object"==typeof s?s:{ideal:s});const o=t.version<66;if(s&&("user"===s.exact||"environment"===s.exact||"user"===s.ideal||"environment"===s.ideal)&&(!r.mediaDevices.getSupportedConstraints||!r.mediaDevices.getSupportedConstraints().facingMode||o)){let t;if(delete e.video.facingMode,"environment"===s.exact||"environment"===s.ideal?t=["back","rear"]:"user"!==s.exact&&"user"!==s.ideal||(t=["front"]),t)return r.mediaDevices.enumerateDevices().then((r=>{let o=(r=r.filter((e=>"videoinput"===e.kind))).find((e=>t.some((t=>e.label.toLowerCase().includes(t)))));return!o&&r.length&&t.includes("back")&&(o=r[r.length-1]),o&&(e.video.deviceId=s.exact?{exact:o.deviceId}:{ideal:o.deviceId}),e.video=i(e.video),wr("chrome: "+JSON.stringify(e)),n(e)}))}e.video=i(e.video)}return wr("chrome: "+JSON.stringify(e)),n(e)},s=function(e){return t.version>=64?e:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[e.name]||e.name,message:e.message,constraint:e.constraint||e.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}};if(r.getUserMedia=function(e,t,i){n(e,(e=>{r.webkitGetUserMedia(e,t,(e=>{i&&i(s(e))}))}))}.bind(r),r.mediaDevices.getUserMedia){const e=r.mediaDevices.getUserMedia.bind(r.mediaDevices);r.mediaDevices.getUserMedia=function(t){return n(t,(t=>e(t).then((e=>{if(t.audio&&!e.getAudioTracks().length||t.video&&!e.getVideoTracks().length)throw e.getTracks().forEach((e=>{e.stop()})),new DOMException("","NotFoundError");return e}),(e=>Promise.reject(s(e))))))}}}function Sr(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function Cr(e){if("object"==typeof e&&e.RTCPeerConnection&&!("ontrack"in e.RTCPeerConnection.prototype)){Object.defineProperty(e.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(e){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=e)},enumerable:!0,configurable:!0});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=t=>{t.stream.addEventListener("addtrack",(r=>{let i;i=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===r.track.id)):{track:r.track};const n=new Event("track");n.track=r.track,n.receiver=i,n.transceiver={receiver:i},n.streams=[t.stream],this.dispatchEvent(n)})),t.stream.getTracks().forEach((r=>{let i;i=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===r.id)):{track:r};const n=new Event("track");n.track=r,n.receiver=i,n.transceiver={receiver:i},n.streams=[t.stream],this.dispatchEvent(n)}))},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else ur(e,"track",(e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e)))}function Rr(e){if("object"==typeof e&&e.RTCPeerConnection&&!("getSenders"in e.RTCPeerConnection.prototype)&&"createDTMFSender"in e.RTCPeerConnection.prototype){const t=function(e,t){return{track:t,get dtmf(){return void 0===this._dtmf&&("audio"===t.kind?this._dtmf=e.createDTMFSender(t):this._dtmf=null),this._dtmf},_pc:e}};if(!e.RTCPeerConnection.prototype.getSenders){e.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const r=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,i){let n=r.apply(this,arguments);return n||(n=t(this,e),this._senders.push(n)),n};const i=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){i.apply(this,arguments);const t=this._senders.indexOf(e);-1!==t&&this._senders.splice(t,1)}}const r=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._senders=this._senders||[],r.apply(this,[e]),e.getTracks().forEach((e=>{this._senders.push(t(this,e))}))};const i=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._senders=this._senders||[],i.apply(this,[e]),e.getTracks().forEach((e=>{const t=this._senders.find((t=>t.track===e));t&&this._senders.splice(this._senders.indexOf(t),1)}))}}else if("object"==typeof e&&e.RTCPeerConnection&&"getSenders"in e.RTCPeerConnection.prototype&&"createDTMFSender"in e.RTCPeerConnection.prototype&&e.RTCRtpSender&&!("dtmf"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e},Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function kr(e){if(!("object"==typeof e&&e.RTCPeerConnection&&e.RTCRtpSender&&e.RTCRtpReceiver))return;if(!("getStats"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e});const r=e.RTCPeerConnection.prototype.addTrack;r&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=r.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>yr(t,e.track,!0)))}}if(!("getStats"in e.RTCRtpReceiver.prototype)){const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e}),ur(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>yr(t,e.track,!1)))}}if(!("getStats"in e.RTCRtpSender.prototype)||!("getStats"in e.RTCRtpReceiver.prototype))return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof e.MediaStreamTrack){const e=arguments[0];let t,r,i;return this.getSenders().forEach((r=>{r.track===e&&(t?i=!0:t=r)})),this.getReceivers().forEach((t=>(t.track===e&&(r?i=!0:r=t),t.track===e))),i||t&&r?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):t?t.getStats():r?r.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return t.apply(this,arguments)}}function Tr(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map((e=>this._shimmedLocalStreams[e][0]))};const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,r){if(!r)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const i=t.apply(this,arguments);return this._shimmedLocalStreams[r.id]?-1===this._shimmedLocalStreams[r.id].indexOf(i)&&this._shimmedLocalStreams[r.id].push(i):this._shimmedLocalStreams[r.id]=[r,i],i};const r=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._shimmedLocalStreams=this._shimmedLocalStreams||{},e.getTracks().forEach((e=>{if(this.getSenders().find((t=>t.track===e)))throw new DOMException("Track already exists.","InvalidAccessError")}));const t=this.getSenders();r.apply(this,arguments);const i=this.getSenders().filter((e=>-1===t.indexOf(e)));this._shimmedLocalStreams[e.id]=[e].concat(i)};const i=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],i.apply(this,arguments)};const n=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach((t=>{const r=this._shimmedLocalStreams[t].indexOf(e);-1!==r&&this._shimmedLocalStreams[t].splice(r,1),1===this._shimmedLocalStreams[t].length&&delete this._shimmedLocalStreams[t]})),n.apply(this,arguments)}}function Pr(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return Tr(e);const r=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){const e=r.apply(this);return this._reverseStreams=this._reverseStreams||{},e.map((e=>this._reverseStreams[e.id]))};const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(t){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},t.getTracks().forEach((e=>{if(this.getSenders().find((t=>t.track===e)))throw new DOMException("Track already exists.","InvalidAccessError")})),!this._reverseStreams[t.id]){const r=new e.MediaStream(t.getTracks());this._streams[t.id]=r,this._reverseStreams[r.id]=t,t=r}i.apply(this,[t])};const n=e.RTCPeerConnection.prototype.removeStream;function s(e,t){let r=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const i=e._reverseStreams[t],n=e._streams[i.id];r=r.replace(new RegExp(n.id,"g"),i.id)})),new RTCSessionDescription({type:t.type,sdp:r})}e.RTCPeerConnection.prototype.removeStream=function(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},n.apply(this,[this._streams[e.id]||e]),delete this._reverseStreams[this._streams[e.id]?this._streams[e.id].id:e.id],delete this._streams[e.id]},e.RTCPeerConnection.prototype.addTrack=function(t,r){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const i=[].slice.call(arguments,1);if(1!==i.length||!i[0].getTracks().find((e=>e===t)))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");if(this.getSenders().find((e=>e.track===t)))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const n=this._streams[r.id];if(n)n.addTrack(t),Promise.resolve().then((()=>{this.dispatchEvent(new Event("negotiationneeded"))}));else{const i=new e.MediaStream([t]);this._streams[r.id]=i,this._reverseStreams[i.id]=r,this.addStream(i)}return this.getSenders().find((e=>e.track===t))},["createOffer","createAnswer"].forEach((function(t){const r=e.RTCPeerConnection.prototype[t],i={[t](){const e=arguments;return arguments.length&&"function"==typeof arguments[0]?r.apply(this,[t=>{const r=s(this,t);e[0].apply(null,[r])},t=>{e[1]&&e[1].apply(null,t)},arguments[2]]):r.apply(this,arguments).then((e=>s(this,e)))}};e.RTCPeerConnection.prototype[t]=i[t]}));const o=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=function(e,t){let r=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const i=e._reverseStreams[t],n=e._streams[i.id];r=r.replace(new RegExp(i.id,"g"),n.id)})),new RTCSessionDescription({type:t.type,sdp:r})}(this,arguments[0]),o.apply(this,arguments)):o.apply(this,arguments)};const a=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get(){const e=a.get.apply(this);return""===e.type?e:s(this,e)}}),e.RTCPeerConnection.prototype.removeTrack=function(e){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!e._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(e._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");let t;this._streams=this._streams||{},Object.keys(this._streams).forEach((r=>{this._streams[r].getTracks().find((t=>e.track===t))&&(t=this._streams[r])})),t&&(1===t.getTracks().length?this.removeStream(this._reverseStreams[t.id]):t.removeTrack(e.track),this.dispatchEvent(new Event("negotiationneeded")))}}function Or(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const r=e.RTCPeerConnection.prototype[t],i={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),r.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=i[t]}))}function Er(e,t){ur(e,"negotiationneeded",(e=>{const r=e.target;if(!(t.version<72||r.getConfiguration&&"plan-b"===r.getConfiguration().sdpSemantics)||"stable"===r.signalingState)return e}))}var Dr=Object.freeze({__proto__:null,fixNegotiationNeeded:Er,shimAddTrackRemoveTrack:Pr,shimAddTrackRemoveTrackWithNative:Tr,shimGetSendersWithDtmf:Rr,shimGetUserMedia:_r,shimMediaStream:Sr,shimOnTrack:Cr,shimPeerConnection:Or,shimSenderReceiverGetStats:kr});function Ir(e,t){const r=e&&e.navigator,i=e&&e.MediaStreamTrack;if(r.getUserMedia=function(e,t,i){mr("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),r.mediaDevices.getUserMedia(e).then(t,i)},!(t.version>55&&"autoGainControl"in r.mediaDevices.getSupportedConstraints())){const e=function(e,t,r){t in e&&!(r in e)&&(e[r]=e[t],delete e[t])},t=r.mediaDevices.getUserMedia.bind(r.mediaDevices);if(r.mediaDevices.getUserMedia=function(r){return"object"==typeof r&&"object"==typeof r.audio&&(r=JSON.parse(JSON.stringify(r)),e(r.audio,"autoGainControl","mozAutoGainControl"),e(r.audio,"noiseSuppression","mozNoiseSuppression")),t(r)},i&&i.prototype.getSettings){const t=i.prototype.getSettings;i.prototype.getSettings=function(){const r=t.apply(this,arguments);return e(r,"mozAutoGainControl","autoGainControl"),e(r,"mozNoiseSuppression","noiseSuppression"),r}}if(i&&i.prototype.applyConstraints){const t=i.prototype.applyConstraints;i.prototype.applyConstraints=function(r){return"audio"===this.kind&&"object"==typeof r&&(r=JSON.parse(JSON.stringify(r)),e(r,"autoGainControl","mozAutoGainControl"),e(r,"noiseSuppression","mozNoiseSuppression")),t.apply(this,[r])}}}}function xr(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function Mr(e,t){if("object"!=typeof e||!e.RTCPeerConnection&&!e.mozRTCPeerConnection)return;!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection),t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const r=e.RTCPeerConnection.prototype[t],i={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),r.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=i[t]}));const r={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},i=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,n,s]=arguments;return i.apply(this,[e||null]).then((e=>{if(t.version<53&&!n)try{e.forEach((e=>{e.type=r[e.type]||e.type}))}catch(t){if("TypeError"!==t.name)throw t;e.forEach(((t,i)=>{e.set(i,Object.assign({},t,{type:r[t.type]||t.type}))}))}return e})).then(n,s)}}function jr(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpSender.prototype)return;const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e});const r=e.RTCPeerConnection.prototype.addTrack;r&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=r.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function Lr(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpReceiver.prototype)return;const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e}),ur(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function Ar(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){mr("removeStream","removeTrack"),this.getSenders().forEach((t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)}))})}function Nr(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function Br(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.addTransceiver;t&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let e=arguments[1]&&arguments[1].sendEncodings;void 0===e&&(e=[]),e=[...e];const r=e.length>0;r&&e.forEach((e=>{if("rid"in e){if(!/^[a-z0-9]{0,16}$/i.test(e.rid))throw new TypeError("Invalid RID value provided.")}if("scaleResolutionDownBy"in e&&!(parseFloat(e.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in e&&!(parseFloat(e.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")}));const i=t.apply(this,arguments);if(r){const{sender:t}=i,r=t.getParameters();(!("encodings"in r)||1===r.encodings.length&&0===Object.keys(r.encodings[0]).length)&&(r.encodings=e,t.sendEncodings=e,this.setParametersPromises.push(t.setParameters(r).then((()=>{delete t.sendEncodings})).catch((()=>{delete t.sendEncodings}))))}return i})}function Fr(e){if("object"!=typeof e||!e.RTCRtpSender)return;const t=e.RTCRtpSender.prototype.getParameters;t&&(e.RTCRtpSender.prototype.getParameters=function(){const e=t.apply(this,arguments);return"encodings"in e||(e.encodings=[].concat(this.sendEncodings||[{}])),e})}function zr(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((()=>t.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):t.apply(this,arguments)}}function Vr(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createAnswer;e.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((()=>t.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):t.apply(this,arguments)}}var Ur=Object.freeze({__proto__:null,shimAddTransceiver:Br,shimCreateAnswer:Vr,shimCreateOffer:zr,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&(e.navigator.mediaDevices.getDisplayMedia=function(r){if(!r||!r.video){const e=new DOMException("getDisplayMedia without video constraints is undefined");return e.name="NotFoundError",e.code=8,Promise.reject(e)}return!0===r.video?r.video={mediaSource:t}:r.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(r)})},shimGetParameters:Fr,shimGetUserMedia:Ir,shimOnTrack:xr,shimPeerConnection:Mr,shimRTCDataChannel:Nr,shimReceiverGetStats:Lr,shimRemoveStream:Ar,shimSenderGetStats:jr});function $r(e){if("object"==typeof e&&e.RTCPeerConnection){if("getLocalStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in e.RTCPeerConnection.prototype)){const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addStream=function(e){this._localStreams||(this._localStreams=[]),this._localStreams.includes(e)||this._localStreams.push(e),e.getAudioTracks().forEach((r=>t.call(this,r,e))),e.getVideoTracks().forEach((r=>t.call(this,r,e)))},e.RTCPeerConnection.prototype.addTrack=function(e,...r){return r&&r.forEach((e=>{this._localStreams?this._localStreams.includes(e)||this._localStreams.push(e):this._localStreams=[e]})),t.apply(this,arguments)}}"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){this._localStreams||(this._localStreams=[]);const t=this._localStreams.indexOf(e);if(-1===t)return;this._localStreams.splice(t,1);const r=e.getTracks();this.getSenders().forEach((e=>{r.includes(e.track)&&this.removeTrack(e)}))})}}function Gr(e){if("object"==typeof e&&e.RTCPeerConnection&&("getRemoteStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in e.RTCPeerConnection.prototype))){Object.defineProperty(e.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(e){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=e),this.addEventListener("track",this._onaddstreampoly=e=>{e.streams.forEach((e=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(e))return;this._remoteStreams.push(e);const t=new Event("addstream");t.stream=e,this.dispatchEvent(t)}))})}});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){const e=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(t){t.streams.forEach((t=>{if(e._remoteStreams||(e._remoteStreams=[]),e._remoteStreams.indexOf(t)>=0)return;e._remoteStreams.push(t);const r=new Event("addstream");r.stream=t,e.dispatchEvent(r)}))}),t.apply(e,arguments)}}}function qr(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype,r=t.createOffer,i=t.createAnswer,n=t.setLocalDescription,s=t.setRemoteDescription,o=t.addIceCandidate;t.createOffer=function(e,t){const i=arguments.length>=2?arguments[2]:arguments[0],n=r.apply(this,[i]);return t?(n.then(e,t),Promise.resolve()):n},t.createAnswer=function(e,t){const r=arguments.length>=2?arguments[2]:arguments[0],n=i.apply(this,[r]);return t?(n.then(e,t),Promise.resolve()):n};let a=function(e,t,r){const i=n.apply(this,[e]);return r?(i.then(t,r),Promise.resolve()):i};t.setLocalDescription=a,a=function(e,t,r){const i=s.apply(this,[e]);return r?(i.then(t,r),Promise.resolve()):i},t.setRemoteDescription=a,a=function(e,t,r){const i=o.apply(this,[e]);return r?(i.then(t,r),Promise.resolve()):i},t.addIceCandidate=a}function Hr(e){const t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){const e=t.mediaDevices,r=e.getUserMedia.bind(e);t.mediaDevices.getUserMedia=e=>r(Wr(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,r,i){t.mediaDevices.getUserMedia(e).then(r,i)}.bind(t))}function Wr(e){return e&&void 0!==e.video?Object.assign({},e,{video:vr(e.video)}):e}function Kr(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection;e.RTCPeerConnection=function(e,r){if(e&&e.iceServers){const t=[];for(let r=0;r<e.iceServers.length;r++){let i=e.iceServers[r];void 0===i.urls&&i.url?(mr("RTCIceServer.url","RTCIceServer.urls"),i=JSON.parse(JSON.stringify(i)),i.urls=i.url,delete i.url,t.push(i)):t.push(e.iceServers[r])}e.iceServers=t}return new t(e,r)},e.RTCPeerConnection.prototype=t.prototype,"generateCertificate"in t&&Object.defineProperty(e.RTCPeerConnection,"generateCertificate",{get:()=>t.generateCertificate})}function Jr(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function Xr(e){const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(e){if(e){void 0!==e.offerToReceiveAudio&&(e.offerToReceiveAudio=!!e.offerToReceiveAudio);const t=this.getTransceivers().find((e=>"audio"===e.receiver.track.kind));!1===e.offerToReceiveAudio&&t?"sendrecv"===t.direction?t.setDirection?t.setDirection("sendonly"):t.direction="sendonly":"recvonly"===t.direction&&(t.setDirection?t.setDirection("inactive"):t.direction="inactive"):!0!==e.offerToReceiveAudio||t||this.addTransceiver("audio",{direction:"recvonly"}),void 0!==e.offerToReceiveVideo&&(e.offerToReceiveVideo=!!e.offerToReceiveVideo);const r=this.getTransceivers().find((e=>"video"===e.receiver.track.kind));!1===e.offerToReceiveVideo&&r?"sendrecv"===r.direction?r.setDirection?r.setDirection("sendonly"):r.direction="sendonly":"recvonly"===r.direction&&(r.setDirection?r.setDirection("inactive"):r.direction="inactive"):!0!==e.offerToReceiveVideo||r||this.addTransceiver("video",{direction:"recvonly"})}return t.apply(this,arguments)}}function Qr(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var Zr=Object.freeze({__proto__:null,shimAudioContext:Qr,shimCallbacksAPI:qr,shimConstraints:Wr,shimCreateOfferLegacy:Xr,shimGetUserMedia:Hr,shimLocalStreamsAPI:$r,shimRTCIceServerUrls:Kr,shimRemoteStreamsAPI:Gr,shimTrackEventTransceiver:Jr}),Yr={exports:{}};!function(e){const t={generateIdentifier:function(){return Math.random().toString(36).substring(2,12)}};t.localCName=t.generateIdentifier(),t.splitLines=function(e){return e.trim().split("\n").map((e=>e.trim()))},t.splitSections=function(e){return e.split("\nm=").map(((e,t)=>(t>0?"m="+e:e).trim()+"\r\n"))},t.getDescription=function(e){const r=t.splitSections(e);return r&&r[0]},t.getMediaSections=function(e){const r=t.splitSections(e);return r.shift(),r},t.matchPrefix=function(e,r){return t.splitLines(e).filter((e=>0===e.indexOf(r)))},t.parseCandidate=function(e){let t;t=0===e.indexOf("a=candidate:")?e.substring(12).split(" "):e.substring(10).split(" ");const r={foundation:t[0],component:{1:"rtp",2:"rtcp"}[t[1]]||t[1],protocol:t[2].toLowerCase(),priority:parseInt(t[3],10),ip:t[4],address:t[4],port:parseInt(t[5],10),type:t[7]};for(let e=8;e<t.length;e+=2)switch(t[e]){case"raddr":r.relatedAddress=t[e+1];break;case"rport":r.relatedPort=parseInt(t[e+1],10);break;case"tcptype":r.tcpType=t[e+1];break;case"ufrag":r.ufrag=t[e+1],r.usernameFragment=t[e+1];break;default:void 0===r[t[e]]&&(r[t[e]]=t[e+1])}return r},t.writeCandidate=function(e){const t=[];t.push(e.foundation);const r=e.component;"rtp"===r?t.push(1):"rtcp"===r?t.push(2):t.push(r),t.push(e.protocol.toUpperCase()),t.push(e.priority),t.push(e.address||e.ip),t.push(e.port);const i=e.type;return t.push("typ"),t.push(i),"host"!==i&&e.relatedAddress&&e.relatedPort&&(t.push("raddr"),t.push(e.relatedAddress),t.push("rport"),t.push(e.relatedPort)),e.tcpType&&"tcp"===e.protocol.toLowerCase()&&(t.push("tcptype"),t.push(e.tcpType)),(e.usernameFragment||e.ufrag)&&(t.push("ufrag"),t.push(e.usernameFragment||e.ufrag)),"candidate:"+t.join(" ")},t.parseIceOptions=function(e){return e.substring(14).split(" ")},t.parseRtpMap=function(e){let t=e.substring(9).split(" ");const r={payloadType:parseInt(t.shift(),10)};return t=t[0].split("/"),r.name=t[0],r.clockRate=parseInt(t[1],10),r.channels=3===t.length?parseInt(t[2],10):1,r.numChannels=r.channels,r},t.writeRtpMap=function(e){let t=e.payloadType;void 0!==e.preferredPayloadType&&(t=e.preferredPayloadType);const r=e.channels||e.numChannels||1;return"a=rtpmap:"+t+" "+e.name+"/"+e.clockRate+(1!==r?"/"+r:"")+"\r\n"},t.parseExtmap=function(e){const t=e.substring(9).split(" ");return{id:parseInt(t[0],10),direction:t[0].indexOf("/")>0?t[0].split("/")[1]:"sendrecv",uri:t[1],attributes:t.slice(2).join(" ")}},t.writeExtmap=function(e){return"a=extmap:"+(e.id||e.preferredId)+(e.direction&&"sendrecv"!==e.direction?"/"+e.direction:"")+" "+e.uri+(e.attributes?" "+e.attributes:"")+"\r\n"},t.parseFmtp=function(e){const t={};let r;const i=e.substring(e.indexOf(" ")+1).split(";");for(let e=0;e<i.length;e++)r=i[e].trim().split("="),t[r[0].trim()]=r[1];return t},t.writeFmtp=function(e){let t="",r=e.payloadType;if(void 0!==e.preferredPayloadType&&(r=e.preferredPayloadType),e.parameters&&Object.keys(e.parameters).length){const i=[];Object.keys(e.parameters).forEach((t=>{void 0!==e.parameters[t]?i.push(t+"="+e.parameters[t]):i.push(t)})),t+="a=fmtp:"+r+" "+i.join(";")+"\r\n"}return t},t.parseRtcpFb=function(e){const t=e.substring(e.indexOf(" ")+1).split(" ");return{type:t.shift(),parameter:t.join(" ")}},t.writeRtcpFb=function(e){let t="",r=e.payloadType;return void 0!==e.preferredPayloadType&&(r=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach((e=>{t+="a=rtcp-fb:"+r+" "+e.type+(e.parameter&&e.parameter.length?" "+e.parameter:"")+"\r\n"})),t},t.parseSsrcMedia=function(e){const t=e.indexOf(" "),r={ssrc:parseInt(e.substring(7,t),10)},i=e.indexOf(":",t);return i>-1?(r.attribute=e.substring(t+1,i),r.value=e.substring(i+1)):r.attribute=e.substring(t+1),r},t.parseSsrcGroup=function(e){const t=e.substring(13).split(" ");return{semantics:t.shift(),ssrcs:t.map((e=>parseInt(e,10)))}},t.getMid=function(e){const r=t.matchPrefix(e,"a=mid:")[0];if(r)return r.substring(6)},t.parseFingerprint=function(e){const t=e.substring(14).split(" ");return{algorithm:t[0].toLowerCase(),value:t[1].toUpperCase()}},t.getDtlsParameters=function(e,r){return{role:"auto",fingerprints:t.matchPrefix(e+r,"a=fingerprint:").map(t.parseFingerprint)}},t.writeDtlsParameters=function(e,t){let r="a=setup:"+t+"\r\n";return e.fingerprints.forEach((e=>{r+="a=fingerprint:"+e.algorithm+" "+e.value+"\r\n"})),r},t.parseCryptoLine=function(e){const t=e.substring(9).split(" ");return{tag:parseInt(t[0],10),cryptoSuite:t[1],keyParams:t[2],sessionParams:t.slice(3)}},t.writeCryptoLine=function(e){return"a=crypto:"+e.tag+" "+e.cryptoSuite+" "+("object"==typeof e.keyParams?t.writeCryptoKeyParams(e.keyParams):e.keyParams)+(e.sessionParams?" "+e.sessionParams.join(" "):"")+"\r\n"},t.parseCryptoKeyParams=function(e){if(0!==e.indexOf("inline:"))return null;const t=e.substring(7).split("|");return{keyMethod:"inline",keySalt:t[0],lifeTime:t[1],mkiValue:t[2]?t[2].split(":")[0]:void 0,mkiLength:t[2]?t[2].split(":")[1]:void 0}},t.writeCryptoKeyParams=function(e){return e.keyMethod+":"+e.keySalt+(e.lifeTime?"|"+e.lifeTime:"")+(e.mkiValue&&e.mkiLength?"|"+e.mkiValue+":"+e.mkiLength:"")},t.getCryptoParameters=function(e,r){return t.matchPrefix(e+r,"a=crypto:").map(t.parseCryptoLine)},t.getIceParameters=function(e,r){const i=t.matchPrefix(e+r,"a=ice-ufrag:")[0],n=t.matchPrefix(e+r,"a=ice-pwd:")[0];return i&&n?{usernameFragment:i.substring(12),password:n.substring(10)}:null},t.writeIceParameters=function(e){let t="a=ice-ufrag:"+e.usernameFragment+"\r\na=ice-pwd:"+e.password+"\r\n";return e.iceLite&&(t+="a=ice-lite\r\n"),t},t.parseRtpParameters=function(e){const r={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},i=t.splitLines(e)[0].split(" ");r.profile=i[2];for(let n=3;n<i.length;n++){const s=i[n],o=t.matchPrefix(e,"a=rtpmap:"+s+" ")[0];if(o){const i=t.parseRtpMap(o),n=t.matchPrefix(e,"a=fmtp:"+s+" ");switch(i.parameters=n.length?t.parseFmtp(n[0]):{},i.rtcpFeedback=t.matchPrefix(e,"a=rtcp-fb:"+s+" ").map(t.parseRtcpFb),r.codecs.push(i),i.name.toUpperCase()){case"RED":case"ULPFEC":r.fecMechanisms.push(i.name.toUpperCase())}}}t.matchPrefix(e,"a=extmap:").forEach((e=>{r.headerExtensions.push(t.parseExtmap(e))}));const n=t.matchPrefix(e,"a=rtcp-fb:* ").map(t.parseRtcpFb);return r.codecs.forEach((e=>{n.forEach((t=>{e.rtcpFeedback.find((e=>e.type===t.type&&e.parameter===t.parameter))||e.rtcpFeedback.push(t)}))})),r},t.writeRtpDescription=function(e,r){let i="";i+="m="+e+" ",i+=r.codecs.length>0?"9":"0",i+=" "+(r.profile||"UDP/TLS/RTP/SAVPF")+" ",i+=r.codecs.map((e=>void 0!==e.preferredPayloadType?e.preferredPayloadType:e.payloadType)).join(" ")+"\r\n",i+="c=IN IP4 0.0.0.0\r\n",i+="a=rtcp:9 IN IP4 0.0.0.0\r\n",r.codecs.forEach((e=>{i+=t.writeRtpMap(e),i+=t.writeFmtp(e),i+=t.writeRtcpFb(e)}));let n=0;return r.codecs.forEach((e=>{e.maxptime>n&&(n=e.maxptime)})),n>0&&(i+="a=maxptime:"+n+"\r\n"),r.headerExtensions&&r.headerExtensions.forEach((e=>{i+=t.writeExtmap(e)})),i},t.parseRtpEncodingParameters=function(e){const r=[],i=t.parseRtpParameters(e),n=-1!==i.fecMechanisms.indexOf("RED"),s=-1!==i.fecMechanisms.indexOf("ULPFEC"),o=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute)),a=o.length>0&&o[0].ssrc;let c;const d=t.matchPrefix(e,"a=ssrc-group:FID").map((e=>e.substring(17).split(" ").map((e=>parseInt(e,10)))));d.length>0&&d[0].length>1&&d[0][0]===a&&(c=d[0][1]),i.codecs.forEach((e=>{if("RTX"===e.name.toUpperCase()&&e.parameters.apt){let t={ssrc:a,codecPayloadType:parseInt(e.parameters.apt,10)};a&&c&&(t.rtx={ssrc:c}),r.push(t),n&&(t=JSON.parse(JSON.stringify(t)),t.fec={ssrc:a,mechanism:s?"red+ulpfec":"red"},r.push(t))}})),0===r.length&&a&&r.push({ssrc:a});let l=t.matchPrefix(e,"b=");return l.length&&(l=0===l[0].indexOf("b=TIAS:")?parseInt(l[0].substring(7),10):0===l[0].indexOf("b=AS:")?1e3*parseInt(l[0].substring(5),10)*.95-16e3:void 0,r.forEach((e=>{e.maxBitrate=l}))),r},t.parseRtcpParameters=function(e){const r={},i=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute))[0];i&&(r.cname=i.value,r.ssrc=i.ssrc);const n=t.matchPrefix(e,"a=rtcp-rsize");r.reducedSize=n.length>0,r.compound=0===n.length;const s=t.matchPrefix(e,"a=rtcp-mux");return r.mux=s.length>0,r},t.writeRtcpParameters=function(e){let t="";return e.reducedSize&&(t+="a=rtcp-rsize\r\n"),e.mux&&(t+="a=rtcp-mux\r\n"),void 0!==e.ssrc&&e.cname&&(t+="a=ssrc:"+e.ssrc+" cname:"+e.cname+"\r\n"),t},t.parseMsid=function(e){let r;const i=t.matchPrefix(e,"a=msid:");if(1===i.length)return r=i[0].substring(7).split(" "),{stream:r[0],track:r[1]};const n=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"msid"===e.attribute));return n.length>0?(r=n[0].value.split(" "),{stream:r[0],track:r[1]}):void 0},t.parseSctpDescription=function(e){const r=t.parseMLine(e),i=t.matchPrefix(e,"a=max-message-size:");let n;i.length>0&&(n=parseInt(i[0].substring(19),10)),isNaN(n)&&(n=65536);const s=t.matchPrefix(e,"a=sctp-port:");if(s.length>0)return{port:parseInt(s[0].substring(12),10),protocol:r.fmt,maxMessageSize:n};const o=t.matchPrefix(e,"a=sctpmap:");if(o.length>0){const e=o[0].substring(10).split(" ");return{port:parseInt(e[0],10),protocol:e[1],maxMessageSize:n}}},t.writeSctpDescription=function(e,t){let r=[];return r="DTLS/SCTP"!==e.protocol?["m="+e.kind+" 9 "+e.protocol+" "+t.protocol+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctp-port:"+t.port+"\r\n"]:["m="+e.kind+" 9 "+e.protocol+" "+t.port+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctpmap:"+t.port+" "+t.protocol+" 65535\r\n"],void 0!==t.maxMessageSize&&r.push("a=max-message-size:"+t.maxMessageSize+"\r\n"),r.join("")},t.generateSessionId=function(){return Math.random().toString().substr(2,22)},t.writeSessionBoilerplate=function(e,r,i){let n;const s=void 0!==r?r:2;n=e||t.generateSessionId();return"v=0\r\no="+(i||"thisisadapterortc")+" "+n+" "+s+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},t.getDirection=function(e,r){const i=t.splitLines(e);for(let e=0;e<i.length;e++)switch(i[e]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return i[e].substring(2)}return r?t.getDirection(r):"sendrecv"},t.getKind=function(e){return t.splitLines(e)[0].split(" ")[0].substring(2)},t.isRejected=function(e){return"0"===e.split(" ",2)[1]},t.parseMLine=function(e){const r=t.splitLines(e)[0].substring(2).split(" ");return{kind:r[0],port:parseInt(r[1],10),protocol:r[2],fmt:r.slice(3).join(" ")}},t.parseOLine=function(e){const r=t.matchPrefix(e,"o=")[0].substring(2).split(" ");return{username:r[0],sessionId:r[1],sessionVersion:parseInt(r[2],10),netType:r[3],addressType:r[4],address:r[5]}},t.isValidSDP=function(e){if("string"!=typeof e||0===e.length)return!1;const r=t.splitLines(e);for(let e=0;e<r.length;e++)if(r[e].length<2||"="!==r[e].charAt(1))return!1;return!0},e.exports=t}(Yr);var ei=Yr.exports,ti=c(ei),ri=n({__proto__:null,default:ti},[ei]);function ii(e){if(!e.RTCIceCandidate||e.RTCIceCandidate&&"foundation"in e.RTCIceCandidate.prototype)return;const t=e.RTCIceCandidate;e.RTCIceCandidate=function(e){if("object"==typeof e&&e.candidate&&0===e.candidate.indexOf("a=")&&((e=JSON.parse(JSON.stringify(e))).candidate=e.candidate.substring(2)),e.candidate&&e.candidate.length){const r=new t(e),i=ti.parseCandidate(e.candidate);for(const e in i)e in r||Object.defineProperty(r,e,{value:i[e]});return r.toJSON=function(){return{candidate:r.candidate,sdpMid:r.sdpMid,sdpMLineIndex:r.sdpMLineIndex,usernameFragment:r.usernameFragment}},r}return new t(e)},e.RTCIceCandidate.prototype=t.prototype,ur(e,"icecandidate",(t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t)))}function ni(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||ur(e,"icecandidate",(e=>{if(e.candidate){const t=ti.parseCandidate(e.candidate.candidate);"relay"===t.type&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e}))}function si(e,t){if(!e.RTCPeerConnection)return;"sctp"in e.RTCPeerConnection.prototype||Object.defineProperty(e.RTCPeerConnection.prototype,"sctp",{get(){return void 0===this._sctp?null:this._sctp}});const r=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,"chrome"===t.browser&&t.version>=76){const{sdpSemantics:e}=this.getConfiguration();"plan-b"===e&&Object.defineProperty(this,"sctp",{get(){return void 0===this._sctp?null:this._sctp},enumerable:!0,configurable:!0})}if(function(e){if(!e||!e.sdp)return!1;const t=ti.splitSections(e.sdp);return t.shift(),t.some((e=>{const t=ti.parseMLine(e);return t&&"application"===t.kind&&-1!==t.protocol.indexOf("SCTP")}))}(arguments[0])){const e=function(e){const t=e.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(null===t||t.length<2)return-1;const r=parseInt(t[1],10);return r!=r?-1:r}(arguments[0]),r=function(e){let r=65536;return"firefox"===t.browser&&(r=t.version<57?-1===e?16384:2147483637:t.version<60?57===t.version?65535:65536:2147483637),r}(e),i=function(e,r){let i=65536;"firefox"===t.browser&&57===t.version&&(i=65535);const n=ti.matchPrefix(e.sdp,"a=max-message-size:");return n.length>0?i=parseInt(n[0].substring(19),10):"firefox"===t.browser&&-1!==r&&(i=2147483637),i}(arguments[0],e);let n;n=0===r&&0===i?Number.POSITIVE_INFINITY:0===r||0===i?Math.max(r,i):Math.min(r,i);const s={};Object.defineProperty(s,"maxMessageSize",{get:()=>n}),this._sctp=s}return r.apply(this,arguments)}}function oi(e){if(!e.RTCPeerConnection||!("createDataChannel"in e.RTCPeerConnection.prototype))return;function t(e,t){const r=e.send;e.send=function(){const i=arguments[0],n=i.length||i.size||i.byteLength;if("open"===e.readyState&&t.sctp&&n>t.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+t.sctp.maxMessageSize+" bytes)");return r.apply(e,arguments)}}const r=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){const e=r.apply(this,arguments);return t(e,this),e},ur(e,"datachannel",(e=>(t(e.channel,e.target),e)))}function ai(e){if(!e.RTCPeerConnection||"connectionState"in e.RTCPeerConnection.prototype)return;const t=e.RTCPeerConnection.prototype;Object.defineProperty(t,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(t,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(e){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),e&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=e)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach((e=>{const r=t[e];t[e]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=e=>{const t=e.target;if(t._lastConnectionState!==t.connectionState){t._lastConnectionState=t.connectionState;const r=new Event("connectionstatechange",e);t.dispatchEvent(r)}return e},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),r.apply(this,arguments)}}))}function ci(e,t){if(!e.RTCPeerConnection)return;if("chrome"===t.browser&&t.version>=71)return;if("safari"===t.browser&&t.version>=605)return;const r=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(t){if(t&&t.sdp&&-1!==t.sdp.indexOf("\na=extmap-allow-mixed")){const r=t.sdp.split("\n").filter((e=>"a=extmap-allow-mixed"!==e.trim())).join("\n");e.RTCSessionDescription&&t instanceof e.RTCSessionDescription?arguments[0]=new e.RTCSessionDescription({type:t.type,sdp:r}):t.sdp=r}return r.apply(this,arguments)}}function di(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const r=e.RTCPeerConnection.prototype.addIceCandidate;r&&0!==r.length&&(e.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?("chrome"===t.browser&&t.version<78||"firefox"===t.browser&&t.version<68||"safari"===t.browser)&&arguments[0]&&""===arguments[0].candidate?Promise.resolve():r.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function li(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const r=e.RTCPeerConnection.prototype.setLocalDescription;r&&0!==r.length&&(e.RTCPeerConnection.prototype.setLocalDescription=function(){let e=arguments[0]||{};if("object"!=typeof e||e.type&&e.sdp)return r.apply(this,arguments);if(e={type:e.type,sdp:e.sdp},!e.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":e.type="offer";break;default:e.type="answer"}if(e.sdp||"offer"!==e.type&&"answer"!==e.type)return r.apply(this,[e]);return("offer"===e.type?this.createOffer:this.createAnswer).apply(this).then((e=>r.apply(this,[e])))})}var ui=Object.freeze({__proto__:null,removeExtmapAllowMixed:ci,shimAddIceCandidateNullOrEmpty:di,shimConnectionState:ai,shimMaxMessageSize:si,shimParameterlessSetLocalDescription:li,shimRTCIceCandidate:ii,shimRTCIceCandidateRelayProtocol:ni,shimSendThrowTypeError:oi});const pi=function({window:e}={},t={shimChrome:!0,shimFirefox:!0,shimSafari:!0}){const r=fr,i=function(e){const t={browser:null,version:null};if(void 0===e||!e.navigator||!e.navigator.userAgent)return t.browser="Not a browser.",t;const{navigator:r}=e;if(r.userAgentData&&r.userAgentData.brands){const e=r.userAgentData.brands.find((e=>"Chromium"===e.brand));if(e)return{browser:"chrome",version:parseInt(e.version,10)}}if(r.mozGetUserMedia)t.browser="firefox",t.version=lr(r.userAgent,/Firefox\/(\d+)\./,1);else if(r.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection)t.browser="chrome",t.version=lr(r.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else{if(!e.RTCPeerConnection||!r.userAgent.match(/AppleWebKit\/(\d+)\./))return t.browser="Not a supported browser.",t;t.browser="safari",t.version=lr(r.userAgent,/AppleWebKit\/(\d+)\./,1),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype}return t}(e),n={browserDetails:i,commonShim:ui,extractVersion:lr,disableLog:pr,disableWarnings:hr,sdp:ri};switch(i.browser){case"chrome":if(!Dr||!Or||!t.shimChrome)return r("Chrome shim is not included in this adapter release."),n;if(null===i.version)return r("Chrome shim can not determine version, not shimming."),n;r("adapter.js shimming chrome."),n.browserShim=Dr,di(e,i),li(e),_r(e,i),Sr(e),Or(e,i),Cr(e),Pr(e,i),Rr(e),kr(e),Er(e,i),ii(e),ni(e),ai(e),si(e,i),oi(e),ci(e,i);break;case"firefox":if(!Ur||!Mr||!t.shimFirefox)return r("Firefox shim is not included in this adapter release."),n;r("adapter.js shimming firefox."),n.browserShim=Ur,di(e,i),li(e),Ir(e,i),Mr(e,i),xr(e),Ar(e),jr(e),Lr(e),Nr(e),Br(e),Fr(e),zr(e),Vr(e),ii(e),ai(e),si(e,i),oi(e);break;case"safari":if(!Zr||!t.shimSafari)return r("Safari shim is not included in this adapter release."),n;r("adapter.js shimming safari."),n.browserShim=Zr,di(e,i),li(e),Kr(e),Xr(e),qr(e),$r(e),Gr(e),Jr(e),Hr(e),Qr(e),ii(e),ni(e),si(e,i),oi(e),ci(e,i);break;default:r("Unsupported browser!")}return n}({window:"undefined"==typeof window?void 0:window});function hi(e){return{id:e.id,tracks:e.getTracks().map((function(e){return{id:e.id,kind:e.kind,label:e.label,enabled:e.enabled,muted:e.muted,readyState:e.readyState}}))}}var fi=function(e,t,r){var i=0,n=!!window.mozRTCPeerConnection,s=!!window.RTCIceGatherer,o={};if(r.forEach((function(r){if(window[r+"RTCPeerConnection"]&&("webkit"!==r||!s)){var a=window[r+"RTCPeerConnection"],c=function(r,c){var d=new a(r,c),l="PC_"+i++;d.__rtcStatsId=l,r||(r={nullConfig:!0}),((r=JSON.parse(JSON.stringify(r)))&&r.iceServers||[]).forEach((function(e){delete e.credential})),r.browserType=n?"moz":s?"edge":"webkit",e("create",l,r),c&&e("constraints",l,c),d.addEventListener("icecandidate",(function(t){e("onicecandidate",l,t.candidate)})),d.addEventListener("addstream",(function(t){e("onaddstream",l,t.stream.id+" "+t.stream.getTracks().map((function(e){return e.kind+":"+e.id})))})),d.addEventListener("track",(function(t){e("ontrack",l,t.track.kind+":"+t.track.id+" "+t.streams.map((function(e){return"stream:"+e.id})))})),d.addEventListener("removestream",(function(t){e("onremovestream",l,t.stream.id+" "+t.stream.getTracks().map((function(e){return e.kind+":"+e.id})))})),d.addEventListener("signalingstatechange",(function(){e("onsignalingstatechange",l,d.signalingState)})),d.addEventListener("iceconnectionstatechange",(function(){e("oniceconnectionstatechange",l,d.iceConnectionState)})),d.addEventListener("icegatheringstatechange",(function(){e("onicegatheringstatechange",l,d.iceGatheringState)})),d.addEventListener("connectionstatechange",(function(){e("onconnectionstatechange",l,d.connectionState)})),d.addEventListener("negotiationneeded",(function(){e("onnegotiationneeded",l,void 0)})),d.addEventListener("datachannel",(function(t){e("ondatachannel",l,[t.channel.id,t.channel.label])}));var u=function(){d.getStats(null).then((function(t){var r=function(e){if(!e.entries)return e;var t={};return e.forEach((function(e,r){t[r]=e})),t}(t),i=JSON.parse(JSON.stringify(r));e("getstats",l,function(e,t){t=JSON.parse(JSON.stringify(t)),Object.keys(t).forEach((function(r){var i=t[r];delete i.id,e[r]&&Object.keys(i).forEach((function(n){i[n]===e[r][n]&&delete t[r][n],(0===Object.keys(i).length||1===Object.keys(i).length&&i.timestamp)&&delete t[r]}))}));var r=-1/0;return Object.keys(t).forEach((function(e){var i=t[e];i.timestamp>r&&(r=i.timestamp)})),Object.keys(t).forEach((function(e){var i=t[e];i.timestamp===r&&(i.timestamp=0)})),t.timestamp=r,t}(o[l]||{},r)),o[l]=i}))};if(!s&&t)var p=window.setInterval((function(){"closed"!==d.signalingState?u():window.clearInterval(p)}),t);return s||d.addEventListener("connectionstatechange",(function(){"connected"!==d.connectionState&&"failed"!==d.connectionState||u()})),d};["createDataChannel","close"].forEach((function(t){var r=a.prototype[t];r&&(a.prototype[t]=function(){return e(t,this.__rtcStatsId,arguments),r.apply(this,arguments)})})),["addStream","removeStream"].forEach((function(t){var r=a.prototype[t];r&&(a.prototype[t]=function(){var i=arguments[0],n=i.getTracks().map((function(e){return e.kind+":"+e.id})).join(",");return e(t,this.__rtcStatsId,i.id+" "+n),r.apply(this,arguments)})})),["addTrack"].forEach((function(t){var r=a.prototype[t];r&&(a.prototype[t]=function(){var i=arguments[0],n=[].slice.call(arguments,1);return e(t,this.__rtcStatsId,i.kind+":"+i.id+" "+(n.map((function(e){return"stream:"+e.id})).join(";")||"-")),r.apply(this,arguments)})})),["removeTrack"].forEach((function(t){var r=a.prototype[t];r&&(a.prototype[t]=function(){var i=arguments[0].track;return e(t,this.__rtcStatsId,i?i.kind+":"+i.id:"null"),r.apply(this,arguments)})})),["createOffer","createAnswer"].forEach((function(t){var r=a.prototype[t];r&&(a.prototype[t]=function(){var i,n=this.__rtcStatsId,s=arguments;return 1===arguments.length&&"object"==typeof arguments[0]?i=arguments[0]:3===arguments.length&&"object"==typeof arguments[2]&&(i=arguments[2]),e(t,this.__rtcStatsId,i),r.apply(this,i?[i]:void 0).then((function(r){if(e(t+"OnSuccess",n,r),!(s.length>0&&"function"==typeof s[0]))return r;s[0].apply(null,[r])}),(function(r){if(e(t+"OnFailure",n,r.toString()),!(s.length>1&&"function"==typeof s[1]))throw r;s[1].apply(null,[r])}))})})),["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){var r=a.prototype[t];r&&(a.prototype[t]=function(){var i=this.__rtcStatsId,n=arguments;return e(t,this.__rtcStatsId,n[0]),r.apply(this,[n[0]]).then((function(){e(t+"OnSuccess",i,void 0),n.length>=2&&"function"==typeof n[1]&&n[1].apply(null,[])}),(function(r){if(e(t+"OnFailure",i,r.toString()),!(n.length>=3&&"function"==typeof n[2]))throw r;n[2].apply(null,[r])}))})})),a.generateCertificate&&Object.defineProperty(c,"generateCertificate",{get:function(){return arguments.length?a.generateCertificate.apply(null,arguments):a.generateCertificate}}),window[r+"RTCPeerConnection"]=c,window[r+"RTCPeerConnection"].prototype=a.prototype}})),r.forEach((function(t){var r=t+(t.length?"GetUserMedia":"getUserMedia");if(navigator[r]){var i=navigator[r].bind(navigator);navigator[r]=function(){e("getUserMedia",null,arguments[0]);var t=arguments[1],r=arguments[2];i(arguments[0],(function(r){e("getUserMediaOnSuccess",null,hi(r)),t&&t(r)}),(function(t){e("getUserMediaOnFailure",null,t.name),r&&r(t)}))}.bind(navigator)}})),navigator.mediaDevices&&navigator.mediaDevices.getUserMedia){var a=navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);navigator.mediaDevices.getUserMedia=function(){return e("navigator.mediaDevices.getUserMedia",null,arguments[0]),a.apply(navigator.mediaDevices,arguments).then((function(t){return e("navigator.mediaDevices.getUserMediaOnSuccess",null,hi(t)),t}),(function(t){return e("navigator.mediaDevices.getUserMediaOnFailure",null,t.name),Promise.reject(t)}))}.bind(navigator.mediaDevices)}if(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia){var c=navigator.mediaDevices.getDisplayMedia.bind(navigator.mediaDevices);navigator.mediaDevices.getDisplayMedia=function(){return e("navigator.mediaDevices.getDisplayMedia",null,arguments[0]),c.apply(navigator.mediaDevices,arguments).then((function(t){return e("navigator.mediaDevices.getDisplayMediaOnSuccess",null,hi(t)),t}),(function(t){return e("navigator.mediaDevices.getDisplayMediaOnFailure",null,t.name),Promise.reject(t)}))}.bind(navigator.mediaDevices)}return{resetDelta(){o={}}}},mi=c(fi);let gi;const vi=new Uint8Array(16);function bi(){if(!gi&&(gi="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!gi))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return gi(vi)}const yi=[];for(let VE=0;VE<256;++VE)yi.push((VE+256).toString(16).slice(1));var wi={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function _i(e,t,r){if(wi.randomUUID&&!t&&!e)return wi.randomUUID();const i=(e=e||{}).random||(e.rng||bi)();if(i[6]=15&i[6]|64,i[8]=63&i[8]|128,t){r=r||0;for(let e=0;e<16;++e)t[r+e]=i[e];return t}return function(e,t=0){return yi[e[t+0]]+yi[e[t+1]]+yi[e[t+2]]+yi[e[t+3]]+"-"+yi[e[t+4]]+yi[e[t+5]]+"-"+yi[e[t+6]]+yi[e[t+7]]+"-"+yi[e[t+8]]+yi[e[t+9]]+"-"+yi[e[t+10]]+yi[e[t+11]]+yi[e[t+12]]+yi[e[t+13]]+yi[e[t+14]]+yi[e[t+15]]}(i)}var Si={},Ci={exports:{}},Ri=Ci.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(e){return e.encoding?"rtpmap:%d %s/%s/%s":e.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(e){return null!=e.address?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(e){return null!=e.subtype?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(e){return"extmap:%d"+(e.direction?"/%s":"%v")+(e["encrypt-uri"]?" %s":"%v")+" %s"+(e.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(e){return null!=e.sessionConfig?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(e){var t="candidate:%s %d %s %d %s %d typ %s";return t+=null!=e.raddr?" raddr %s rport %d":"%v%v",t+=null!=e.tcptype?" tcptype %s":"%v",null!=e.generation&&(t+=" generation %d"),t+=null!=e["network-id"]?" network-id %d":"%v",t+=null!=e["network-cost"]?" network-cost %d":"%v"}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(e){var t="ssrc:%d";return null!=e.attribute&&(t+=" %s",null!=e.value&&(t+=":%s")),t}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(e){return null!=e.maxMessageSize?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(e){return e.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(e){return"imageattr:%s %s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(e){return"simulcast:%s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(e){return"ts-refclk:%s"+(null!=e.clksrcExt?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(e){var t="mediaclk:";return t+=null!=e.id?"id=%s %s":"%v%s",t+=null!=e.mediaClockValue?"=%s":"",t+=null!=e.rateNumerator?" rate=%s":"",t+=null!=e.rateDenominator?"/%s":""}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};Object.keys(Ri).forEach((function(e){Ri[e].forEach((function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")}))}));var ki=Ci.exports;!function(e){var t=function(e){return String(Number(e))===e?Number(e):e},r=function(e,r,i){var n=e.name&&e.names;e.push&&!r[e.push]?r[e.push]=[]:n&&!r[e.name]&&(r[e.name]={});var s=e.push?{}:n?r[e.name]:r;!function(e,r,i,n){if(n&&!i)r[n]=t(e[1]);else for(var s=0;s<i.length;s+=1)null!=e[s+1]&&(r[i[s]]=t(e[s+1]))}(i.match(e.reg),s,e.names,e.name),e.push&&r[e.push].push(s)},i=ki,n=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},s=[],o=t;return e.split(/(\r\n|\r|\n)/).filter(n).forEach((function(e){var t=e[0],n=e.slice(2);"m"===t&&(s.push({rtp:[],fmtp:[]}),o=s[s.length-1]);for(var a=0;a<(i[t]||[]).length;a+=1){var c=i[t][a];if(c.reg.test(n))return r(c,o,n)}})),t.media=s,t};var s=function(e,r){var i=r.split(/=(.+)/,2);return 2===i.length?e[i[0]]=t(i[1]):1===i.length&&r.length>1&&(e[i[0]]=void 0),e};e.parseParams=function(e){return e.split(/;\s?/).reduce(s,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(e){return e.toString().split(" ").map(Number)},e.parseRemoteCandidates=function(e){for(var r=[],i=e.split(" ").map(t),n=0;n<i.length;n+=3)r.push({component:i[n],ip:i[n+1],port:i[n+2]});return r},e.parseImageAttributes=function(e){return e.split(" ").map((function(e){return e.substring(1,e.length-1).split(",").reduce(s,{})}))},e.parseSimulcastStreamList=function(e){return e.split(";").map((function(e){return e.split(",").map((function(e){var r,i=!1;return"~"!==e[0]?r=t(e):(r=t(e.substring(1,e.length)),i=!0),{scid:r,paused:i}}))}))}}(Si);var Ti=ki,Pi=/%[sdv%]/g,Oi=function(e){var t=1,r=arguments,i=r.length;return e.replace(Pi,(function(e){if(t>=i)return e;var n=r[t];switch(t+=1,e){case"%%":return"%";case"%s":return String(n);case"%d":return Number(n);case"%v":return""}}))},Ei=function(e,t,r){var i=[e+"="+(t.format instanceof Function?t.format(t.push?r:r[t.name]):t.format)];if(t.names)for(var n=0;n<t.names.length;n+=1){var s=t.names[n];t.name?i.push(r[t.name][s]):i.push(r[t.names[n]])}else i.push(r[t.name]);return Oi.apply(null,i)},Di=["v","o","s","i","u","e","p","c","b","t","r","z","a"],Ii=["i","c","b","a"],xi=Si,Mi=function(e,t){t=t||{},null==e.version&&(e.version=0),null==e.name&&(e.name=" "),e.media.forEach((function(e){null==e.payloads&&(e.payloads="")}));var r=t.outerOrder||Di,i=t.innerOrder||Ii,n=[];return r.forEach((function(t){Ti[t].forEach((function(r){r.name in e&&null!=e[r.name]?n.push(Ei(t,r,e)):r.push in e&&null!=e[r.push]&&e[r.push].forEach((function(e){n.push(Ei(t,r,e))}))}))})),e.media.forEach((function(e){n.push(Ei("m",Ti.m[0],e)),i.forEach((function(t){Ti[t].forEach((function(r){r.name in e&&null!=e[r.name]?n.push(Ei(t,r,e)):r.push in e&&null!=e[r.push]&&e[r.push].forEach((function(e){n.push(Ei(t,r,e))}))}))}))})),n.join("\r\n")+"\r\n"},ji=Mi,Li=xi.parse,Ai={},Ni={},Bi={};Object.defineProperty(Bi,"__esModule",{value:!0}),Bi.isCorrect=Bi.isInSubnet=void 0,Bi.isInSubnet=function(e){return!(this.subnetMask<e.subnetMask)&&this.mask(e.subnetMask)===e.mask()},Bi.isCorrect=function(e){return function(){return this.addressMinusSuffix===this.correctForm()&&(this.subnetMask===e&&!this.parsedSubnet||this.parsedSubnet===String(this.subnetMask))}};var Fi={};Object.defineProperty(Fi,"__esModule",{value:!0}),Fi.RE_SUBNET_STRING=Fi.RE_ADDRESS=Fi.GROUPS=Fi.BITS=void 0,Fi.BITS=32,Fi.GROUPS=4,Fi.RE_ADDRESS=/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/g,Fi.RE_SUBNET_STRING=/\/\d{1,2}$/;var zi={};Object.defineProperty(zi,"__esModule",{value:!0}),zi.AddressError=void 0;class Vi extends Error{constructor(e,t){super(e),this.name="AddressError",null!==t&&(this.parseMessage=t)}}zi.AddressError=Vi;var Ui,$i={exports:{}};Ui=$i,function(){var e;function t(e,t,r){null!=e&&("number"==typeof e?this.fromNumber(e,t,r):null==t&&"string"!=typeof e?this.fromString(e,256):this.fromString(e,t))}function r(){return new t(null)}var i="undefined"!=typeof navigator;i&&"Microsoft Internet Explorer"==navigator.appName?(t.prototype.am=function(e,t,r,i,n,s){for(var o=32767&t,a=t>>15;--s>=0;){var c=32767&this[e],d=this[e++]>>15,l=a*c+d*o;n=((c=o*c+((32767&l)<<15)+r[i]+(1073741823&n))>>>30)+(l>>>15)+a*d+(n>>>30),r[i++]=1073741823&c}return n},e=30):i&&"Netscape"!=navigator.appName?(t.prototype.am=function(e,t,r,i,n,s){for(;--s>=0;){var o=t*this[e++]+r[i]+n;n=Math.floor(o/67108864),r[i++]=67108863&o}return n},e=26):(t.prototype.am=function(e,t,r,i,n,s){for(var o=16383&t,a=t>>14;--s>=0;){var c=16383&this[e],d=this[e++]>>14,l=a*c+d*o;n=((c=o*c+((16383&l)<<14)+r[i]+n)>>28)+(l>>14)+a*d,r[i++]=268435455&c}return n},e=28),t.prototype.DB=e,t.prototype.DM=(1<<e)-1,t.prototype.DV=1<<e,t.prototype.FV=Math.pow(2,52),t.prototype.F1=52-e,t.prototype.F2=2*e-52;var n,s,o="0123456789abcdefghijklmnopqrstuvwxyz",a=new Array;for(n="0".charCodeAt(0),s=0;s<=9;++s)a[n++]=s;for(n="a".charCodeAt(0),s=10;s<36;++s)a[n++]=s;for(n="A".charCodeAt(0),s=10;s<36;++s)a[n++]=s;function c(e){return o.charAt(e)}function d(e,t){var r=a[e.charCodeAt(t)];return null==r?-1:r}function l(e){var t=r();return t.fromInt(e),t}function u(e){var t,r=1;return 0!=(t=e>>>16)&&(e=t,r+=16),0!=(t=e>>8)&&(e=t,r+=8),0!=(t=e>>4)&&(e=t,r+=4),0!=(t=e>>2)&&(e=t,r+=2),0!=(t=e>>1)&&(e=t,r+=1),r}function p(e){this.m=e}function h(e){this.m=e,this.mp=e.invDigit(),this.mpl=32767&this.mp,this.mph=this.mp>>15,this.um=(1<<e.DB-15)-1,this.mt2=2*e.t}function f(e,t){return e&t}function m(e,t){return e|t}function g(e,t){return e^t}function v(e,t){return e&~t}function b(e){if(0==e)return-1;var t=0;return 0==(65535&e)&&(e>>=16,t+=16),0==(255&e)&&(e>>=8,t+=8),0==(15&e)&&(e>>=4,t+=4),0==(3&e)&&(e>>=2,t+=2),0==(1&e)&&++t,t}function y(e){for(var t=0;0!=e;)e&=e-1,++t;return t}function w(){}function _(e){return e}function S(e){this.r2=r(),this.q3=r(),t.ONE.dlShiftTo(2*e.t,this.r2),this.mu=this.r2.divide(e),this.m=e}p.prototype.convert=function(e){return e.s<0||e.compareTo(this.m)>=0?e.mod(this.m):e},p.prototype.revert=function(e){return e},p.prototype.reduce=function(e){e.divRemTo(this.m,null,e)},p.prototype.mulTo=function(e,t,r){e.multiplyTo(t,r),this.reduce(r)},p.prototype.sqrTo=function(e,t){e.squareTo(t),this.reduce(t)},h.prototype.convert=function(e){var i=r();return e.abs().dlShiftTo(this.m.t,i),i.divRemTo(this.m,null,i),e.s<0&&i.compareTo(t.ZERO)>0&&this.m.subTo(i,i),i},h.prototype.revert=function(e){var t=r();return e.copyTo(t),this.reduce(t),t},h.prototype.reduce=function(e){for(;e.t<=this.mt2;)e[e.t++]=0;for(var t=0;t<this.m.t;++t){var r=32767&e[t],i=r*this.mpl+((r*this.mph+(e[t]>>15)*this.mpl&this.um)<<15)&e.DM;for(e[r=t+this.m.t]+=this.m.am(0,i,e,t,0,this.m.t);e[r]>=e.DV;)e[r]-=e.DV,e[++r]++}e.clamp(),e.drShiftTo(this.m.t,e),e.compareTo(this.m)>=0&&e.subTo(this.m,e)},h.prototype.mulTo=function(e,t,r){e.multiplyTo(t,r),this.reduce(r)},h.prototype.sqrTo=function(e,t){e.squareTo(t),this.reduce(t)},t.prototype.copyTo=function(e){for(var t=this.t-1;t>=0;--t)e[t]=this[t];e.t=this.t,e.s=this.s},t.prototype.fromInt=function(e){this.t=1,this.s=e<0?-1:0,e>0?this[0]=e:e<-1?this[0]=e+this.DV:this.t=0},t.prototype.fromString=function(e,r){var i;if(16==r)i=4;else if(8==r)i=3;else if(256==r)i=8;else if(2==r)i=1;else if(32==r)i=5;else{if(4!=r)return void this.fromRadix(e,r);i=2}this.t=0,this.s=0;for(var n=e.length,s=!1,o=0;--n>=0;){var a=8==i?255&e[n]:d(e,n);a<0?"-"==e.charAt(n)&&(s=!0):(s=!1,0==o?this[this.t++]=a:o+i>this.DB?(this[this.t-1]|=(a&(1<<this.DB-o)-1)<<o,this[this.t++]=a>>this.DB-o):this[this.t-1]|=a<<o,(o+=i)>=this.DB&&(o-=this.DB))}8==i&&0!=(128&e[0])&&(this.s=-1,o>0&&(this[this.t-1]|=(1<<this.DB-o)-1<<o)),this.clamp(),s&&t.ZERO.subTo(this,this)},t.prototype.clamp=function(){for(var e=this.s&this.DM;this.t>0&&this[this.t-1]==e;)--this.t},t.prototype.dlShiftTo=function(e,t){var r;for(r=this.t-1;r>=0;--r)t[r+e]=this[r];for(r=e-1;r>=0;--r)t[r]=0;t.t=this.t+e,t.s=this.s},t.prototype.drShiftTo=function(e,t){for(var r=e;r<this.t;++r)t[r-e]=this[r];t.t=Math.max(this.t-e,0),t.s=this.s},t.prototype.lShiftTo=function(e,t){var r,i=e%this.DB,n=this.DB-i,s=(1<<n)-1,o=Math.floor(e/this.DB),a=this.s<<i&this.DM;for(r=this.t-1;r>=0;--r)t[r+o+1]=this[r]>>n|a,a=(this[r]&s)<<i;for(r=o-1;r>=0;--r)t[r]=0;t[o]=a,t.t=this.t+o+1,t.s=this.s,t.clamp()},t.prototype.rShiftTo=function(e,t){t.s=this.s;var r=Math.floor(e/this.DB);if(r>=this.t)t.t=0;else{var i=e%this.DB,n=this.DB-i,s=(1<<i)-1;t[0]=this[r]>>i;for(var o=r+1;o<this.t;++o)t[o-r-1]|=(this[o]&s)<<n,t[o-r]=this[o]>>i;i>0&&(t[this.t-r-1]|=(this.s&s)<<n),t.t=this.t-r,t.clamp()}},t.prototype.subTo=function(e,t){for(var r=0,i=0,n=Math.min(e.t,this.t);r<n;)i+=this[r]-e[r],t[r++]=i&this.DM,i>>=this.DB;if(e.t<this.t){for(i-=e.s;r<this.t;)i+=this[r],t[r++]=i&this.DM,i>>=this.DB;i+=this.s}else{for(i+=this.s;r<e.t;)i-=e[r],t[r++]=i&this.DM,i>>=this.DB;i-=e.s}t.s=i<0?-1:0,i<-1?t[r++]=this.DV+i:i>0&&(t[r++]=i),t.t=r,t.clamp()},t.prototype.multiplyTo=function(e,r){var i=this.abs(),n=e.abs(),s=i.t;for(r.t=s+n.t;--s>=0;)r[s]=0;for(s=0;s<n.t;++s)r[s+i.t]=i.am(0,n[s],r,s,0,i.t);r.s=0,r.clamp(),this.s!=e.s&&t.ZERO.subTo(r,r)},t.prototype.squareTo=function(e){for(var t=this.abs(),r=e.t=2*t.t;--r>=0;)e[r]=0;for(r=0;r<t.t-1;++r){var i=t.am(r,t[r],e,2*r,0,1);(e[r+t.t]+=t.am(r+1,2*t[r],e,2*r+1,i,t.t-r-1))>=t.DV&&(e[r+t.t]-=t.DV,e[r+t.t+1]=1)}e.t>0&&(e[e.t-1]+=t.am(r,t[r],e,2*r,0,1)),e.s=0,e.clamp()},t.prototype.divRemTo=function(e,i,n){var s=e.abs();if(!(s.t<=0)){var o=this.abs();if(o.t<s.t)return null!=i&&i.fromInt(0),void(null!=n&&this.copyTo(n));null==n&&(n=r());var a=r(),c=this.s,d=e.s,l=this.DB-u(s[s.t-1]);l>0?(s.lShiftTo(l,a),o.lShiftTo(l,n)):(s.copyTo(a),o.copyTo(n));var p=a.t,h=a[p-1];if(0!=h){var f=h*(1<<this.F1)+(p>1?a[p-2]>>this.F2:0),m=this.FV/f,g=(1<<this.F1)/f,v=1<<this.F2,b=n.t,y=b-p,w=null==i?r():i;for(a.dlShiftTo(y,w),n.compareTo(w)>=0&&(n[n.t++]=1,n.subTo(w,n)),t.ONE.dlShiftTo(p,w),w.subTo(a,a);a.t<p;)a[a.t++]=0;for(;--y>=0;){var _=n[--b]==h?this.DM:Math.floor(n[b]*m+(n[b-1]+v)*g);if((n[b]+=a.am(0,_,n,y,0,p))<_)for(a.dlShiftTo(y,w),n.subTo(w,n);n[b]<--_;)n.subTo(w,n)}null!=i&&(n.drShiftTo(p,i),c!=d&&t.ZERO.subTo(i,i)),n.t=p,n.clamp(),l>0&&n.rShiftTo(l,n),c<0&&t.ZERO.subTo(n,n)}}},t.prototype.invDigit=function(){if(this.t<1)return 0;var e=this[0];if(0==(1&e))return 0;var t=3&e;return(t=(t=(t=(t=t*(2-(15&e)*t)&15)*(2-(255&e)*t)&255)*(2-((65535&e)*t&65535))&65535)*(2-e*t%this.DV)%this.DV)>0?this.DV-t:-t},t.prototype.isEven=function(){return 0==(this.t>0?1&this[0]:this.s)},t.prototype.exp=function(e,i){if(e>4294967295||e<1)return t.ONE;var n=r(),s=r(),o=i.convert(this),a=u(e)-1;for(o.copyTo(n);--a>=0;)if(i.sqrTo(n,s),(e&1<<a)>0)i.mulTo(s,o,n);else{var c=n;n=s,s=c}return i.revert(n)},t.prototype.toString=function(e){if(this.s<0)return"-"+this.negate().toString(e);var t;if(16==e)t=4;else if(8==e)t=3;else if(2==e)t=1;else if(32==e)t=5;else{if(4!=e)return this.toRadix(e);t=2}var r,i=(1<<t)-1,n=!1,s="",o=this.t,a=this.DB-o*this.DB%t;if(o-- >0)for(a<this.DB&&(r=this[o]>>a)>0&&(n=!0,s=c(r));o>=0;)a<t?(r=(this[o]&(1<<a)-1)<<t-a,r|=this[--o]>>(a+=this.DB-t)):(r=this[o]>>(a-=t)&i,a<=0&&(a+=this.DB,--o)),r>0&&(n=!0),n&&(s+=c(r));return n?s:"0"},t.prototype.negate=function(){var e=r();return t.ZERO.subTo(this,e),e},t.prototype.abs=function(){return this.s<0?this.negate():this},t.prototype.compareTo=function(e){var t=this.s-e.s;if(0!=t)return t;var r=this.t;if(0!=(t=r-e.t))return this.s<0?-t:t;for(;--r>=0;)if(0!=(t=this[r]-e[r]))return t;return 0},t.prototype.bitLength=function(){return this.t<=0?0:this.DB*(this.t-1)+u(this[this.t-1]^this.s&this.DM)},t.prototype.mod=function(e){var i=r();return this.abs().divRemTo(e,null,i),this.s<0&&i.compareTo(t.ZERO)>0&&e.subTo(i,i),i},t.prototype.modPowInt=function(e,t){var r;return r=e<256||t.isEven()?new p(t):new h(t),this.exp(e,r)},t.ZERO=l(0),t.ONE=l(1),w.prototype.convert=_,w.prototype.revert=_,w.prototype.mulTo=function(e,t,r){e.multiplyTo(t,r)},w.prototype.sqrTo=function(e,t){e.squareTo(t)},S.prototype.convert=function(e){if(e.s<0||e.t>2*this.m.t)return e.mod(this.m);if(e.compareTo(this.m)<0)return e;var t=r();return e.copyTo(t),this.reduce(t),t},S.prototype.revert=function(e){return e},S.prototype.reduce=function(e){for(e.drShiftTo(this.m.t-1,this.r2),e.t>this.m.t+1&&(e.t=this.m.t+1,e.clamp()),this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3),this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2);e.compareTo(this.r2)<0;)e.dAddOffset(1,this.m.t+1);for(e.subTo(this.r2,e);e.compareTo(this.m)>=0;)e.subTo(this.m,e)},S.prototype.mulTo=function(e,t,r){e.multiplyTo(t,r),this.reduce(r)},S.prototype.sqrTo=function(e,t){e.squareTo(t),this.reduce(t)};var C,R,k,T=[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509,521,523,541,547,557,563,569,571,577,587,593,599,601,607,613,617,619,631,641,643,647,653,659,661,673,677,683,691,701,709,719,727,733,739,743,751,757,761,769,773,787,797,809,811,821,823,827,829,839,853,857,859,863,877,881,883,887,907,911,919,929,937,941,947,953,967,971,977,983,991,997],P=(1<<26)/T[T.length-1];function O(){var e;e=(new Date).getTime(),R[k++]^=255&e,R[k++]^=e>>8&255,R[k++]^=e>>16&255,R[k++]^=e>>24&255,k>=L&&(k-=L)}if(t.prototype.chunkSize=function(e){return Math.floor(Math.LN2*this.DB/Math.log(e))},t.prototype.toRadix=function(e){if(null==e&&(e=10),0==this.signum()||e<2||e>36)return"0";var t=this.chunkSize(e),i=Math.pow(e,t),n=l(i),s=r(),o=r(),a="";for(this.divRemTo(n,s,o);s.signum()>0;)a=(i+o.intValue()).toString(e).substr(1)+a,s.divRemTo(n,s,o);return o.intValue().toString(e)+a},t.prototype.fromRadix=function(e,r){this.fromInt(0),null==r&&(r=10);for(var i=this.chunkSize(r),n=Math.pow(r,i),s=!1,o=0,a=0,c=0;c<e.length;++c){var l=d(e,c);l<0?"-"==e.charAt(c)&&0==this.signum()&&(s=!0):(a=r*a+l,++o>=i&&(this.dMultiply(n),this.dAddOffset(a,0),o=0,a=0))}o>0&&(this.dMultiply(Math.pow(r,o)),this.dAddOffset(a,0)),s&&t.ZERO.subTo(this,this)},t.prototype.fromNumber=function(e,r,i){if("number"==typeof r)if(e<2)this.fromInt(1);else for(this.fromNumber(e,i),this.testBit(e-1)||this.bitwiseTo(t.ONE.shiftLeft(e-1),m,this),this.isEven()&&this.dAddOffset(1,0);!this.isProbablePrime(r);)this.dAddOffset(2,0),this.bitLength()>e&&this.subTo(t.ONE.shiftLeft(e-1),this);else{var n=new Array,s=7&e;n.length=1+(e>>3),r.nextBytes(n),s>0?n[0]&=(1<<s)-1:n[0]=0,this.fromString(n,256)}},t.prototype.bitwiseTo=function(e,t,r){var i,n,s=Math.min(e.t,this.t);for(i=0;i<s;++i)r[i]=t(this[i],e[i]);if(e.t<this.t){for(n=e.s&this.DM,i=s;i<this.t;++i)r[i]=t(this[i],n);r.t=this.t}else{for(n=this.s&this.DM,i=s;i<e.t;++i)r[i]=t(n,e[i]);r.t=e.t}r.s=t(this.s,e.s),r.clamp()},t.prototype.changeBit=function(e,r){var i=t.ONE.shiftLeft(e);return this.bitwiseTo(i,r,i),i},t.prototype.addTo=function(e,t){for(var r=0,i=0,n=Math.min(e.t,this.t);r<n;)i+=this[r]+e[r],t[r++]=i&this.DM,i>>=this.DB;if(e.t<this.t){for(i+=e.s;r<this.t;)i+=this[r],t[r++]=i&this.DM,i>>=this.DB;i+=this.s}else{for(i+=this.s;r<e.t;)i+=e[r],t[r++]=i&this.DM,i>>=this.DB;i+=e.s}t.s=i<0?-1:0,i>0?t[r++]=i:i<-1&&(t[r++]=this.DV+i),t.t=r,t.clamp()},t.prototype.dMultiply=function(e){this[this.t]=this.am(0,e-1,this,0,0,this.t),++this.t,this.clamp()},t.prototype.dAddOffset=function(e,t){if(0!=e){for(;this.t<=t;)this[this.t++]=0;for(this[t]+=e;this[t]>=this.DV;)this[t]-=this.DV,++t>=this.t&&(this[this.t++]=0),++this[t]}},t.prototype.multiplyLowerTo=function(e,t,r){var i,n=Math.min(this.t+e.t,t);for(r.s=0,r.t=n;n>0;)r[--n]=0;for(i=r.t-this.t;n<i;++n)r[n+this.t]=this.am(0,e[n],r,n,0,this.t);for(i=Math.min(e.t,t);n<i;++n)this.am(0,e[n],r,n,0,t-n);r.clamp()},t.prototype.multiplyUpperTo=function(e,t,r){--t;var i=r.t=this.t+e.t-t;for(r.s=0;--i>=0;)r[i]=0;for(i=Math.max(t-this.t,0);i<e.t;++i)r[this.t+i-t]=this.am(t-i,e[i],r,0,0,this.t+i-t);r.clamp(),r.drShiftTo(1,r)},t.prototype.modInt=function(e){if(e<=0)return 0;var t=this.DV%e,r=this.s<0?e-1:0;if(this.t>0)if(0==t)r=this[0]%e;else for(var i=this.t-1;i>=0;--i)r=(t*r+this[i])%e;return r},t.prototype.millerRabin=function(e){var i=this.subtract(t.ONE),n=i.getLowestSetBit();if(n<=0)return!1;var s=i.shiftRight(n);(e=e+1>>1)>T.length&&(e=T.length);for(var o=r(),a=0;a<e;++a){o.fromInt(T[Math.floor(Math.random()*T.length)]);var c=o.modPow(s,this);if(0!=c.compareTo(t.ONE)&&0!=c.compareTo(i)){for(var d=1;d++<n&&0!=c.compareTo(i);)if(0==(c=c.modPowInt(2,this)).compareTo(t.ONE))return!1;if(0!=c.compareTo(i))return!1}}return!0},t.prototype.clone=function(){var e=r();return this.copyTo(e),e},t.prototype.intValue=function(){if(this.s<0){if(1==this.t)return this[0]-this.DV;if(0==this.t)return-1}else{if(1==this.t)return this[0];if(0==this.t)return 0}return(this[1]&(1<<32-this.DB)-1)<<this.DB|this[0]},t.prototype.byteValue=function(){return 0==this.t?this.s:this[0]<<24>>24},t.prototype.shortValue=function(){return 0==this.t?this.s:this[0]<<16>>16},t.prototype.signum=function(){return this.s<0?-1:this.t<=0||1==this.t&&this[0]<=0?0:1},t.prototype.toByteArray=function(){var e=this.t,t=new Array;t[0]=this.s;var r,i=this.DB-e*this.DB%8,n=0;if(e-- >0)for(i<this.DB&&(r=this[e]>>i)!=(this.s&this.DM)>>i&&(t[n++]=r|this.s<<this.DB-i);e>=0;)i<8?(r=(this[e]&(1<<i)-1)<<8-i,r|=this[--e]>>(i+=this.DB-8)):(r=this[e]>>(i-=8)&255,i<=0&&(i+=this.DB,--e)),0!=(128&r)&&(r|=-256),0==n&&(128&this.s)!=(128&r)&&++n,(n>0||r!=this.s)&&(t[n++]=r);return t},t.prototype.equals=function(e){return 0==this.compareTo(e)},t.prototype.min=function(e){return this.compareTo(e)<0?this:e},t.prototype.max=function(e){return this.compareTo(e)>0?this:e},t.prototype.and=function(e){var t=r();return this.bitwiseTo(e,f,t),t},t.prototype.or=function(e){var t=r();return this.bitwiseTo(e,m,t),t},t.prototype.xor=function(e){var t=r();return this.bitwiseTo(e,g,t),t},t.prototype.andNot=function(e){var t=r();return this.bitwiseTo(e,v,t),t},t.prototype.not=function(){for(var e=r(),t=0;t<this.t;++t)e[t]=this.DM&~this[t];return e.t=this.t,e.s=~this.s,e},t.prototype.shiftLeft=function(e){var t=r();return e<0?this.rShiftTo(-e,t):this.lShiftTo(e,t),t},t.prototype.shiftRight=function(e){var t=r();return e<0?this.lShiftTo(-e,t):this.rShiftTo(e,t),t},t.prototype.getLowestSetBit=function(){for(var e=0;e<this.t;++e)if(0!=this[e])return e*this.DB+b(this[e]);return this.s<0?this.t*this.DB:-1},t.prototype.bitCount=function(){for(var e=0,t=this.s&this.DM,r=0;r<this.t;++r)e+=y(this[r]^t);return e},t.prototype.testBit=function(e){var t=Math.floor(e/this.DB);return t>=this.t?0!=this.s:0!=(this[t]&1<<e%this.DB)},t.prototype.setBit=function(e){return this.changeBit(e,m)},t.prototype.clearBit=function(e){return this.changeBit(e,v)},t.prototype.flipBit=function(e){return this.changeBit(e,g)},t.prototype.add=function(e){var t=r();return this.addTo(e,t),t},t.prototype.subtract=function(e){var t=r();return this.subTo(e,t),t},t.prototype.multiply=function(e){var t=r();return this.multiplyTo(e,t),t},t.prototype.divide=function(e){var t=r();return this.divRemTo(e,t,null),t},t.prototype.remainder=function(e){var t=r();return this.divRemTo(e,null,t),t},t.prototype.divideAndRemainder=function(e){var t=r(),i=r();return this.divRemTo(e,t,i),new Array(t,i)},t.prototype.modPow=function(e,t){var i,n,s=e.bitLength(),o=l(1);if(s<=0)return o;i=s<18?1:s<48?3:s<144?4:s<768?5:6,n=s<8?new p(t):t.isEven()?new S(t):new h(t);var a=new Array,c=3,d=i-1,f=(1<<i)-1;if(a[1]=n.convert(this),i>1){var m=r();for(n.sqrTo(a[1],m);c<=f;)a[c]=r(),n.mulTo(m,a[c-2],a[c]),c+=2}var g,v,b=e.t-1,y=!0,w=r();for(s=u(e[b])-1;b>=0;){for(s>=d?g=e[b]>>s-d&f:(g=(e[b]&(1<<s+1)-1)<<d-s,b>0&&(g|=e[b-1]>>this.DB+s-d)),c=i;0==(1&g);)g>>=1,--c;if((s-=c)<0&&(s+=this.DB,--b),y)a[g].copyTo(o),y=!1;else{for(;c>1;)n.sqrTo(o,w),n.sqrTo(w,o),c-=2;c>0?n.sqrTo(o,w):(v=o,o=w,w=v),n.mulTo(w,a[g],o)}for(;b>=0&&0==(e[b]&1<<s);)n.sqrTo(o,w),v=o,o=w,w=v,--s<0&&(s=this.DB-1,--b)}return n.revert(o)},t.prototype.modInverse=function(e){var r=e.isEven();if(this.isEven()&&r||0==e.signum())return t.ZERO;for(var i=e.clone(),n=this.clone(),s=l(1),o=l(0),a=l(0),c=l(1);0!=i.signum();){for(;i.isEven();)i.rShiftTo(1,i),r?(s.isEven()&&o.isEven()||(s.addTo(this,s),o.subTo(e,o)),s.rShiftTo(1,s)):o.isEven()||o.subTo(e,o),o.rShiftTo(1,o);for(;n.isEven();)n.rShiftTo(1,n),r?(a.isEven()&&c.isEven()||(a.addTo(this,a),c.subTo(e,c)),a.rShiftTo(1,a)):c.isEven()||c.subTo(e,c),c.rShiftTo(1,c);i.compareTo(n)>=0?(i.subTo(n,i),r&&s.subTo(a,s),o.subTo(c,o)):(n.subTo(i,n),r&&a.subTo(s,a),c.subTo(o,c))}return 0!=n.compareTo(t.ONE)?t.ZERO:c.compareTo(e)>=0?c.subtract(e):c.signum()<0?(c.addTo(e,c),c.signum()<0?c.add(e):c):c},t.prototype.pow=function(e){return this.exp(e,new w)},t.prototype.gcd=function(e){var t=this.s<0?this.negate():this.clone(),r=e.s<0?e.negate():e.clone();if(t.compareTo(r)<0){var i=t;t=r,r=i}var n=t.getLowestSetBit(),s=r.getLowestSetBit();if(s<0)return t;for(n<s&&(s=n),s>0&&(t.rShiftTo(s,t),r.rShiftTo(s,r));t.signum()>0;)(n=t.getLowestSetBit())>0&&t.rShiftTo(n,t),(n=r.getLowestSetBit())>0&&r.rShiftTo(n,r),t.compareTo(r)>=0?(t.subTo(r,t),t.rShiftTo(1,t)):(r.subTo(t,r),r.rShiftTo(1,r));return s>0&&r.lShiftTo(s,r),r},t.prototype.isProbablePrime=function(e){var t,r=this.abs();if(1==r.t&&r[0]<=T[T.length-1]){for(t=0;t<T.length;++t)if(r[0]==T[t])return!0;return!1}if(r.isEven())return!1;for(t=1;t<T.length;){for(var i=T[t],n=t+1;n<T.length&&i<P;)i*=T[n++];for(i=r.modInt(i);t<n;)if(i%T[t++]==0)return!1}return r.millerRabin(e)},t.prototype.square=function(){var e=r();return this.squareTo(e),e},t.prototype.Barrett=S,null==R){var E;if(R=new Array,k=0,"undefined"!=typeof window&&window.crypto)if(window.crypto.getRandomValues){var D=new Uint8Array(32);for(window.crypto.getRandomValues(D),E=0;E<32;++E)R[k++]=D[E]}else if("Netscape"==navigator.appName&&navigator.appVersion<"5"){var I=window.crypto.random(32);for(E=0;E<I.length;++E)R[k++]=255&I.charCodeAt(E)}for(;k<L;)E=Math.floor(65536*Math.random()),R[k++]=E>>>8,R[k++]=255&E;k=0,O()}function x(){if(null==C){for(O(),(C=new j).init(R),k=0;k<R.length;++k)R[k]=0;k=0}return C.next()}function M(){}function j(){this.i=0,this.j=0,this.S=new Array}M.prototype.nextBytes=function(e){var t;for(t=0;t<e.length;++t)e[t]=x()},j.prototype.init=function(e){var t,r,i;for(t=0;t<256;++t)this.S[t]=t;for(r=0,t=0;t<256;++t)r=r+this.S[t]+e[t%e.length]&255,i=this.S[t],this.S[t]=this.S[r],this.S[r]=i;this.i=0,this.j=0},j.prototype.next=function(){var e;return this.i=this.i+1&255,this.j=this.j+this.S[this.i]&255,e=this.S[this.i],this.S[this.i]=this.S[this.j],this.S[this.j]=e,this.S[e+this.S[this.i]&255]};var L=256;Ui.exports={default:t,BigInteger:t,SecureRandom:M}}.call(a);var Gi=$i.exports,qi={};!function(e){!function(){var t={not_string:/[^s]/,not_bool:/[^t]/,not_type:/[^T]/,not_primitive:/[^v]/,number:/[diefg]/,numeric_arg:/[bcdiefguxX]/,json:/[j]/,not_json:/[^j]/,text:/^[^\x25]+/,modulo:/^\x25{2}/,placeholder:/^\x25(?:([1-9]\d*)\$|\(([^)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijostTuvxX])/,key:/^([a-z_][a-z_\d]*)/i,key_access:/^\.([a-z_][a-z_\d]*)/i,index_access:/^\[(\d+)\]/,sign:/^[+-]/};function r(e){return function(e,i){var n,s,o,a,c,d,l,u,p,h=1,f=e.length,m="";for(s=0;s<f;s++)if("string"==typeof e[s])m+=e[s];else if("object"==typeof e[s]){if((a=e[s]).keys)for(n=i[h],o=0;o<a.keys.length;o++){if(null==n)throw new Error(r('[sprintf] Cannot access property "%s" of undefined value "%s"',a.keys[o],a.keys[o-1]));n=n[a.keys[o]]}else n=a.param_no?i[a.param_no]:i[h++];if(t.not_type.test(a.type)&&t.not_primitive.test(a.type)&&n instanceof Function&&(n=n()),t.numeric_arg.test(a.type)&&"number"!=typeof n&&isNaN(n))throw new TypeError(r("[sprintf] expecting number but found %T",n));switch(t.number.test(a.type)&&(u=n>=0),a.type){case"b":n=parseInt(n,10).toString(2);break;case"c":n=String.fromCharCode(parseInt(n,10));break;case"d":case"i":n=parseInt(n,10);break;case"j":n=JSON.stringify(n,null,a.width?parseInt(a.width):0);break;case"e":n=a.precision?parseFloat(n).toExponential(a.precision):parseFloat(n).toExponential();break;case"f":n=a.precision?parseFloat(n).toFixed(a.precision):parseFloat(n);break;case"g":n=a.precision?String(Number(n.toPrecision(a.precision))):parseFloat(n);break;case"o":n=(parseInt(n,10)>>>0).toString(8);break;case"s":n=String(n),n=a.precision?n.substring(0,a.precision):n;break;case"t":n=String(!!n),n=a.precision?n.substring(0,a.precision):n;break;case"T":n=Object.prototype.toString.call(n).slice(8,-1).toLowerCase(),n=a.precision?n.substring(0,a.precision):n;break;case"u":n=parseInt(n,10)>>>0;break;case"v":n=n.valueOf(),n=a.precision?n.substring(0,a.precision):n;break;case"x":n=(parseInt(n,10)>>>0).toString(16);break;case"X":n=(parseInt(n,10)>>>0).toString(16).toUpperCase()}t.json.test(a.type)?m+=n:(!t.number.test(a.type)||u&&!a.sign?p="":(p=u?"+":"-",n=n.toString().replace(t.sign,"")),d=a.pad_char?"0"===a.pad_char?"0":a.pad_char.charAt(1):" ",l=a.width-(p+n).length,c=a.width&&l>0?d.repeat(l):"",m+=a.align?p+n+c:"0"===d?p+c+n:c+p+n)}return m}(function(e){if(n[e])return n[e];var r,i=e,s=[],o=0;for(;i;){if(null!==(r=t.text.exec(i)))s.push(r[0]);else if(null!==(r=t.modulo.exec(i)))s.push("%");else{if(null===(r=t.placeholder.exec(i)))throw new SyntaxError("[sprintf] unexpected placeholder");if(r[2]){o|=1;var a=[],c=r[2],d=[];if(null===(d=t.key.exec(c)))throw new SyntaxError("[sprintf] failed to parse named argument key");for(a.push(d[1]);""!==(c=c.substring(d[0].length));)if(null!==(d=t.key_access.exec(c)))a.push(d[1]);else{if(null===(d=t.index_access.exec(c)))throw new SyntaxError("[sprintf] failed to parse named argument key");a.push(d[1])}r[2]=a}else o|=2;if(3===o)throw new Error("[sprintf] mixing positional and named placeholders is not (yet) supported");s.push({placeholder:r[0],param_no:r[1],keys:r[2],sign:r[3],pad_char:r[4],align:r[5],width:r[6],precision:r[7],type:r[8]})}i=i.substring(r[0].length)}return n[e]=s}(e),arguments)}function i(e,t){return r.apply(null,[e].concat(t||[]))}var n=Object.create(null);e.sprintf=r,e.vsprintf=i,"undefined"!=typeof window&&(window.sprintf=r,window.vsprintf=i)}()}(qi);var Hi=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),Wi=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Ki=a&&a.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)"default"!==r&&Object.prototype.hasOwnProperty.call(e,r)&&Hi(t,e,r);return Wi(t,e),t};Object.defineProperty(Ni,"__esModule",{value:!0}),Ni.Address4=void 0;const Ji=Ki(Bi),Xi=Ki(Fi),Qi=zi,Zi=Gi,Yi=qi;class en{constructor(e){this.groups=Xi.GROUPS,this.parsedAddress=[],this.parsedSubnet="",this.subnet="/32",this.subnetMask=32,this.v4=!0,this.isCorrect=Ji.isCorrect(Xi.BITS),this.isInSubnet=Ji.isInSubnet,this.address=e;const t=Xi.RE_SUBNET_STRING.exec(e);if(t){if(this.parsedSubnet=t[0].replace("/",""),this.subnetMask=parseInt(this.parsedSubnet,10),this.subnet=`/${this.subnetMask}`,this.subnetMask<0||this.subnetMask>Xi.BITS)throw new Qi.AddressError("Invalid subnet mask.");e=e.replace(Xi.RE_SUBNET_STRING,"")}this.addressMinusSuffix=e,this.parsedAddress=this.parse(e)}static isValid(e){try{return new en(e),!0}catch(e){return!1}}parse(e){const t=e.split(".");if(!e.match(Xi.RE_ADDRESS))throw new Qi.AddressError("Invalid IPv4 address.");return t}correctForm(){return this.parsedAddress.map((e=>parseInt(e,10))).join(".")}static fromHex(e){const t=e.replace(/:/g,"").padStart(8,"0"),r=[];let i;for(i=0;i<8;i+=2){const e=t.slice(i,i+2);r.push(parseInt(e,16))}return new en(r.join("."))}static fromInteger(e){return en.fromHex(e.toString(16))}static fromArpa(e){const t=e.replace(/(\.in-addr\.arpa)?\.$/,"").split(".").reverse().join(".");return new en(t)}toHex(){return this.parsedAddress.map((e=>(0,Yi.sprintf)("%02x",parseInt(e,10)))).join(":")}toArray(){return this.parsedAddress.map((e=>parseInt(e,10)))}toGroup6(){const e=[];let t;for(t=0;t<Xi.GROUPS;t+=2){const r=(0,Yi.sprintf)("%02x%02x",parseInt(this.parsedAddress[t],10),parseInt(this.parsedAddress[t+1],10));e.push((0,Yi.sprintf)("%x",parseInt(r,16)))}return e.join(":")}bigInteger(){return new Zi.BigInteger(this.parsedAddress.map((e=>(0,Yi.sprintf)("%02x",parseInt(e,10)))).join(""),16)}_startAddress(){return new Zi.BigInteger(this.mask()+"0".repeat(Xi.BITS-this.subnetMask),2)}startAddress(){return en.fromBigInteger(this._startAddress())}startAddressExclusive(){const e=new Zi.BigInteger("1");return en.fromBigInteger(this._startAddress().add(e))}_endAddress(){return new Zi.BigInteger(this.mask()+"1".repeat(Xi.BITS-this.subnetMask),2)}endAddress(){return en.fromBigInteger(this._endAddress())}endAddressExclusive(){const e=new Zi.BigInteger("1");return en.fromBigInteger(this._endAddress().subtract(e))}static fromBigInteger(e){return en.fromInteger(parseInt(e.toString(),10))}mask(e){return void 0===e&&(e=this.subnetMask),this.getBitsBase2(0,e)}getBitsBase2(e,t){return this.binaryZeroPad().slice(e,t)}reverseForm(e){e||(e={});const t=this.correctForm().split(".").reverse().join(".");return e.omitSuffix?t:(0,Yi.sprintf)("%s.in-addr.arpa.",t)}isMulticast(){return this.isInSubnet(new en("224.0.0.0/4"))}binaryZeroPad(){return this.bigInteger().toString(2).padStart(Xi.BITS,"0")}groupForV6(){const e=this.parsedAddress;return this.address.replace(Xi.RE_ADDRESS,(0,Yi.sprintf)('<span class="hover-group group-v4 group-6">%s</span>.<span class="hover-group group-v4 group-7">%s</span>',e.slice(0,2).join("."),e.slice(2,4).join(".")))}}Ni.Address4=en;var tn={},rn={};Object.defineProperty(rn,"__esModule",{value:!0}),rn.RE_URL_WITH_PORT=rn.RE_URL=rn.RE_ZONE_STRING=rn.RE_SUBNET_STRING=rn.RE_BAD_ADDRESS=rn.RE_BAD_CHARACTERS=rn.TYPES=rn.SCOPES=rn.GROUPS=rn.BITS=void 0,rn.BITS=128,rn.GROUPS=8,rn.SCOPES={0:"Reserved",1:"Interface local",2:"Link local",4:"Admin local",5:"Site local",8:"Organization local",14:"Global",15:"Reserved"},rn.TYPES={"ff01::1/128":"Multicast (All nodes on this interface)","ff01::2/128":"Multicast (All routers on this interface)","ff02::1/128":"Multicast (All nodes on this link)","ff02::2/128":"Multicast (All routers on this link)","ff05::2/128":"Multicast (All routers in this site)","ff02::5/128":"Multicast (OSPFv3 AllSPF routers)","ff02::6/128":"Multicast (OSPFv3 AllDR routers)","ff02::9/128":"Multicast (RIP routers)","ff02::a/128":"Multicast (EIGRP routers)","ff02::d/128":"Multicast (PIM routers)","ff02::16/128":"Multicast (MLDv2 reports)","ff01::fb/128":"Multicast (mDNSv6)","ff02::fb/128":"Multicast (mDNSv6)","ff05::fb/128":"Multicast (mDNSv6)","ff02::1:2/128":"Multicast (All DHCP servers and relay agents on this link)","ff05::1:2/128":"Multicast (All DHCP servers and relay agents in this site)","ff02::1:3/128":"Multicast (All DHCP servers on this link)","ff05::1:3/128":"Multicast (All DHCP servers in this site)","::/128":"Unspecified","::1/128":"Loopback","ff00::/8":"Multicast","fe80::/10":"Link-local unicast"},rn.RE_BAD_CHARACTERS=/([^0-9a-f:/%])/gi,rn.RE_BAD_ADDRESS=/([0-9a-f]{5,}|:{3,}|[^:]:$|^:[^:]|\/$)/gi,rn.RE_SUBNET_STRING=/\/\d{1,3}(?=%|$)/,rn.RE_ZONE_STRING=/%.*$/,rn.RE_URL=new RegExp(/^\[{0,1}([0-9a-f:]+)\]{0,1}/),rn.RE_URL_WITH_PORT=new RegExp(/\[([0-9a-f:]+)\]:([0-9]{1,5})/);var nn={};Object.defineProperty(nn,"__esModule",{value:!0}),nn.simpleGroup=nn.spanLeadingZeroes=nn.spanAll=nn.spanAllZeroes=void 0;const sn=qi;function on(e){return e.replace(/(0+)/g,'<span class="zero">$1</span>')}function an(e){return e.replace(/^(0+)/,'<span class="zero">$1</span>')}nn.spanAllZeroes=on,nn.spanAll=function(e,t=0){return e.split("").map(((e,r)=>(0,sn.sprintf)('<span class="digit value-%s position-%d">%s</span>',e,r+t,on(e)))).join("")},nn.spanLeadingZeroes=function(e){return e.split(":").map((e=>an(e))).join(":")},nn.simpleGroup=function(e,t=0){return e.split(":").map(((e,r)=>/group-v4/.test(e)?e:(0,sn.sprintf)('<span class="hover-group group-%d">%s</span>',r+t,an(e))))};var cn={},dn=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),ln=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),un=a&&a.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)"default"!==r&&Object.prototype.hasOwnProperty.call(e,r)&&dn(t,e,r);return ln(t,e),t};Object.defineProperty(cn,"__esModule",{value:!0}),cn.possibleElisions=cn.simpleRegularExpression=cn.ADDRESS_BOUNDARY=cn.padGroup=cn.groupPossibilities=void 0;const pn=un(rn),hn=qi;function fn(e){return(0,hn.sprintf)("(%s)",e.join("|"))}function mn(e){return e.length<4?(0,hn.sprintf)("0{0,%d}%s",4-e.length,e):e}cn.groupPossibilities=fn,cn.padGroup=mn,cn.ADDRESS_BOUNDARY="[^A-Fa-f0-9:]",cn.simpleRegularExpression=function(e){const t=[];e.forEach(((e,r)=>{0===parseInt(e,16)&&t.push(r)}));const r=t.map((t=>e.map(((e,r)=>{if(r===t){const t=0===r||r===pn.GROUPS-1?":":"";return fn([mn(e),t])}return mn(e)})).join(":")));return r.push(e.map(mn).join(":")),fn(r)},cn.possibleElisions=function(e,t,r){const i=t?"":":",n=r?"":":",s=[];t||r||s.push("::"),t&&r&&s.push(""),(r&&!t||!r&&t)&&s.push(":"),s.push((0,hn.sprintf)("%s(:0{1,4}){1,%d}",i,e-1)),s.push((0,hn.sprintf)("(0{1,4}:){1,%d}%s",e-1,n)),s.push((0,hn.sprintf)("(0{1,4}:){%d}0{1,4}",e-1));for(let t=1;t<e-1;t++)for(let r=1;r<e-t;r++)s.push((0,hn.sprintf)("(0{1,4}:){%d}:(0{1,4}:){%d}0{1,4}",r,e-r-t-1));return fn(s)};var gn=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),vn=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),bn=a&&a.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)"default"!==r&&Object.prototype.hasOwnProperty.call(e,r)&&gn(t,e,r);return vn(t,e),t};Object.defineProperty(tn,"__esModule",{value:!0}),tn.Address6=void 0;const yn=bn(Bi),wn=bn(Fi),_n=bn(rn),Sn=bn(nn),Cn=Ni,Rn=cn,kn=zi,Tn=Gi,Pn=qi;function On(e){if(!e)throw new Error("Assertion failed.")}function En(e){return e=(e=e.replace(/^(0{1,})([1-9]+)$/,'<span class="parse-error">$1</span>$2')).replace(/^(0{1,})(0)$/,'<span class="parse-error">$1</span>$2')}function Dn(e){return(0,Pn.sprintf)("%04x",parseInt(e,16))}function In(e){return 255&e}class xn{constructor(e,t){this.addressMinusSuffix="",this.parsedSubnet="",this.subnet="/128",this.subnetMask=128,this.v4=!1,this.zone="",this.isInSubnet=yn.isInSubnet,this.isCorrect=yn.isCorrect(_n.BITS),this.groups=void 0===t?_n.GROUPS:t,this.address=e;const r=_n.RE_SUBNET_STRING.exec(e);if(r){if(this.parsedSubnet=r[0].replace("/",""),this.subnetMask=parseInt(this.parsedSubnet,10),this.subnet=`/${this.subnetMask}`,Number.isNaN(this.subnetMask)||this.subnetMask<0||this.subnetMask>_n.BITS)throw new kn.AddressError("Invalid subnet mask.");e=e.replace(_n.RE_SUBNET_STRING,"")}else if(/\//.test(e))throw new kn.AddressError("Invalid subnet mask.");const i=_n.RE_ZONE_STRING.exec(e);i&&(this.zone=i[0],e=e.replace(_n.RE_ZONE_STRING,"")),this.addressMinusSuffix=e,this.parsedAddress=this.parse(this.addressMinusSuffix)}static isValid(e){try{return new xn(e),!0}catch(e){return!1}}static fromBigInteger(e){const t=e.toString(16).padStart(32,"0"),r=[];let i;for(i=0;i<_n.GROUPS;i++)r.push(t.slice(4*i,4*(i+1)));return new xn(r.join(":"))}static fromURL(e){let t,r,i=null;if(-1!==e.indexOf("[")&&-1!==e.indexOf("]:")){if(r=_n.RE_URL_WITH_PORT.exec(e),null===r)return{error:"failed to parse address with port",address:null,port:null};t=r[1],i=r[2]}else if(-1!==e.indexOf("/")){if(e=e.replace(/^[a-z0-9]+:\/\//,""),r=_n.RE_URL.exec(e),null===r)return{error:"failed to parse address from URL",address:null,port:null};t=r[1]}else t=e;return i?(i=parseInt(i,10),(i<0||i>65536)&&(i=null)):i=null,{address:new xn(t),port:i}}static fromAddress4(e){const t=new Cn.Address4(e),r=_n.BITS-(wn.BITS-t.subnetMask);return new xn(`::ffff:${t.correctForm()}/${r}`)}static fromArpa(e){let t=e.replace(/(\.ip6\.arpa)?\.$/,"");if(63!==t.length)throw new kn.AddressError("Invalid 'ip6.arpa' form.");const r=t.split(".").reverse();for(let e=7;e>0;e--){const t=4*e;r.splice(t,0,":")}return t=r.join(""),new xn(t)}microsoftTranscription(){return(0,Pn.sprintf)("%s.ipv6-literal.net",this.correctForm().replace(/:/g,"-"))}mask(e=this.subnetMask){return this.getBitsBase2(0,e)}possibleSubnets(e=128){const t=_n.BITS-this.subnetMask-Math.abs(e-_n.BITS);return t<0?"0":function(e){const t=/(\d+)(\d{3})/;for(;t.test(e);)e=e.replace(t,"$1,$2");return e}(new Tn.BigInteger("2",10).pow(t).toString(10))}_startAddress(){return new Tn.BigInteger(this.mask()+"0".repeat(_n.BITS-this.subnetMask),2)}startAddress(){return xn.fromBigInteger(this._startAddress())}startAddressExclusive(){const e=new Tn.BigInteger("1");return xn.fromBigInteger(this._startAddress().add(e))}_endAddress(){return new Tn.BigInteger(this.mask()+"1".repeat(_n.BITS-this.subnetMask),2)}endAddress(){return xn.fromBigInteger(this._endAddress())}endAddressExclusive(){const e=new Tn.BigInteger("1");return xn.fromBigInteger(this._endAddress().subtract(e))}getScope(){let e=_n.SCOPES[this.getBits(12,16).intValue()];return"Global unicast"===this.getType()&&"Link local"!==e&&(e="Global"),e||"Unknown"}getType(){for(const e of Object.keys(_n.TYPES))if(this.isInSubnet(new xn(e)))return _n.TYPES[e];return"Global unicast"}getBits(e,t){return new Tn.BigInteger(this.getBitsBase2(e,t),2)}getBitsBase2(e,t){return this.binaryZeroPad().slice(e,t)}getBitsBase16(e,t){const r=t-e;if(r%4!=0)throw new Error("Length of bits to retrieve must be divisible by four");return this.getBits(e,t).toString(16).padStart(r/4,"0")}getBitsPastSubnet(){return this.getBitsBase2(this.subnetMask,_n.BITS)}reverseForm(e){e||(e={});const t=Math.floor(this.subnetMask/4),r=this.canonicalForm().replace(/:/g,"").split("").slice(0,t).reverse().join(".");return t>0?e.omitSuffix?r:(0,Pn.sprintf)("%s.ip6.arpa.",r):e.omitSuffix?"":"ip6.arpa."}correctForm(){let e,t=[],r=0;const i=[];for(e=0;e<this.parsedAddress.length;e++){const t=parseInt(this.parsedAddress[e],16);0===t&&r++,0!==t&&r>0&&(r>1&&i.push([e-r,e-1]),r=0)}r>1&&i.push([this.parsedAddress.length-r,this.parsedAddress.length-1]);const n=i.map((e=>e[1]-e[0]+1));if(i.length>0){const e=n.indexOf(Math.max(...n));t=function(e,t){const r=[],i=[];let n;for(n=0;n<e.length;n++)n<t[0]?r.push(e[n]):n>t[1]&&i.push(e[n]);return r.concat(["compact"]).concat(i)}(this.parsedAddress,i[e])}else t=this.parsedAddress;for(e=0;e<t.length;e++)"compact"!==t[e]&&(t[e]=parseInt(t[e],16).toString(16));let s=t.join(":");return s=s.replace(/^compact$/,"::"),s=s.replace(/^compact|compact$/,":"),s=s.replace(/compact/,""),s}binaryZeroPad(){return this.bigInteger().toString(2).padStart(_n.BITS,"0")}parse4in6(e){const t=e.split(":"),r=t.slice(-1)[0].match(wn.RE_ADDRESS);if(r){this.parsedAddress4=r[0],this.address4=new Cn.Address4(this.parsedAddress4);for(let t=0;t<this.address4.groups;t++)if(/^0[0-9]+/.test(this.address4.parsedAddress[t]))throw new kn.AddressError("IPv4 addresses can't have leading zeroes.",e.replace(wn.RE_ADDRESS,this.address4.parsedAddress.map(En).join(".")));this.v4=!0,t[t.length-1]=this.address4.toGroup6(),e=t.join(":")}return e}parse(e){const t=(e=this.parse4in6(e)).match(_n.RE_BAD_CHARACTERS);if(t)throw new kn.AddressError((0,Pn.sprintf)("Bad character%s detected in address: %s",t.length>1?"s":"",t.join("")),e.replace(_n.RE_BAD_CHARACTERS,'<span class="parse-error">$1</span>'));const r=e.match(_n.RE_BAD_ADDRESS);if(r)throw new kn.AddressError((0,Pn.sprintf)("Address failed regex: %s",r.join("")),e.replace(_n.RE_BAD_ADDRESS,'<span class="parse-error">$1</span>'));let i=[];const n=e.split("::");if(2===n.length){let e=n[0].split(":"),t=n[1].split(":");1===e.length&&""===e[0]&&(e=[]),1===t.length&&""===t[0]&&(t=[]);const r=this.groups-(e.length+t.length);if(!r)throw new kn.AddressError("Error parsing groups");this.elidedGroups=r,this.elisionBegin=e.length,this.elisionEnd=e.length+this.elidedGroups,i=i.concat(e);for(let e=0;e<r;e++)i.push("0");i=i.concat(t)}else{if(1!==n.length)throw new kn.AddressError("Too many :: groups found");i=e.split(":"),this.elidedGroups=0}if(i=i.map((e=>(0,Pn.sprintf)("%x",parseInt(e,16)))),i.length!==this.groups)throw new kn.AddressError("Incorrect number of groups found");return i}canonicalForm(){return this.parsedAddress.map(Dn).join(":")}decimal(){return this.parsedAddress.map((e=>(0,Pn.sprintf)("%05d",parseInt(e,16)))).join(":")}bigInteger(){return new Tn.BigInteger(this.parsedAddress.map(Dn).join(""),16)}to4(){const e=this.binaryZeroPad().split("");return Cn.Address4.fromHex(new Tn.BigInteger(e.slice(96,128).join(""),2).toString(16))}to4in6(){const e=this.to4(),t=new xn(this.parsedAddress.slice(0,6).join(":"),6).correctForm();let r="";return/:$/.test(t)||(r=":"),t+r+e.address}inspectTeredo(){const e=this.getBitsBase16(0,32),t=this.getBits(80,96).xor(new Tn.BigInteger("ffff",16)).toString(),r=Cn.Address4.fromHex(this.getBitsBase16(32,64)),i=Cn.Address4.fromHex(this.getBits(96,128).xor(new Tn.BigInteger("ffffffff",16)).toString(16)),n=this.getBits(64,80),s=this.getBitsBase2(64,80),o=n.testBit(15),a=n.testBit(14),c=n.testBit(8),d=n.testBit(9),l=new Tn.BigInteger(s.slice(2,6)+s.slice(8,16),2).toString(10);return{prefix:(0,Pn.sprintf)("%s:%s",e.slice(0,4),e.slice(4,8)),server4:r.address,client4:i.address,flags:s,coneNat:o,microsoft:{reserved:a,universalLocal:d,groupIndividual:c,nonce:l},udpPort:t}}inspect6to4(){const e=this.getBitsBase16(0,16),t=Cn.Address4.fromHex(this.getBitsBase16(16,48));return{prefix:(0,Pn.sprintf)("%s",e.slice(0,4)),gateway:t.address}}to6to4(){if(!this.is4())return null;const e=["2002",this.getBitsBase16(96,112),this.getBitsBase16(112,128),"","/16"].join(":");return new xn(e)}toByteArray(){const e=this.bigInteger().toByteArray();return 17===e.length&&0===e[0]?e.slice(1):e}toUnsignedByteArray(){return this.toByteArray().map(In)}static fromByteArray(e){return this.fromUnsignedByteArray(e.map(In))}static fromUnsignedByteArray(e){const t=new Tn.BigInteger("256",10);let r=new Tn.BigInteger("0",10),i=new Tn.BigInteger("1",10);for(let n=e.length-1;n>=0;n--)r=r.add(i.multiply(new Tn.BigInteger(e[n].toString(10),10))),i=i.multiply(t);return xn.fromBigInteger(r)}isCanonical(){return this.addressMinusSuffix===this.canonicalForm()}isLinkLocal(){return"1111111010000000000000000000000000000000000000000000000000000000"===this.getBitsBase2(0,64)}isMulticast(){return"Multicast"===this.getType()}is4(){return this.v4}isTeredo(){return this.isInSubnet(new xn("2001::/32"))}is6to4(){return this.isInSubnet(new xn("2002::/16"))}isLoopback(){return"Loopback"===this.getType()}href(e){return e=void 0===e?"":(0,Pn.sprintf)(":%s",e),(0,Pn.sprintf)("http://[%s]%s/",this.correctForm(),e)}link(e){e||(e={}),void 0===e.className&&(e.className=""),void 0===e.prefix&&(e.prefix="/#address="),void 0===e.v4&&(e.v4=!1);let t=this.correctForm;return e.v4&&(t=this.to4in6),e.className?(0,Pn.sprintf)('<a href="%1$s%2$s" class="%3$s">%2$s</a>',e.prefix,t.call(this),e.className):(0,Pn.sprintf)('<a href="%1$s%2$s">%2$s</a>',e.prefix,t.call(this))}group(){if(0===this.elidedGroups)return Sn.simpleGroup(this.address).join(":");On("number"==typeof this.elidedGroups),On("number"==typeof this.elisionBegin);const e=[],[t,r]=this.address.split("::");t.length?e.push(...Sn.simpleGroup(t)):e.push("");const i=["hover-group"];for(let e=this.elisionBegin;e<this.elisionBegin+this.elidedGroups;e++)i.push((0,Pn.sprintf)("group-%d",e));return e.push((0,Pn.sprintf)('<span class="%s"></span>',i.join(" "))),r.length?e.push(...Sn.simpleGroup(r,this.elisionEnd)):e.push(""),this.is4()&&(On(this.address4 instanceof Cn.Address4),e.pop(),e.push(this.address4.groupForV6())),e.join(":")}regularExpressionString(e=!1){let t=[];const r=new xn(this.correctForm());if(0===r.elidedGroups)t.push((0,Rn.simpleRegularExpression)(r.parsedAddress));else if(r.elidedGroups===_n.GROUPS)t.push((0,Rn.possibleElisions)(_n.GROUPS));else{const e=r.address.split("::");e[0].length&&t.push((0,Rn.simpleRegularExpression)(e[0].split(":"))),On("number"==typeof r.elidedGroups),t.push((0,Rn.possibleElisions)(r.elidedGroups,0!==e[0].length,0!==e[1].length)),e[1].length&&t.push((0,Rn.simpleRegularExpression)(e[1].split(":"))),t=[t.join(":")]}return e||(t=["(?=^|",Rn.ADDRESS_BOUNDARY,"|[^\\w\\:])(",...t,")(?=[^\\w\\:]|",Rn.ADDRESS_BOUNDARY,"|$)"]),t.join("")}regularExpression(e=!1){return new RegExp(this.regularExpressionString(e),"i")}}tn.Address6=xn,function(e){var t=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),r=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),i=a&&a.__importStar||function(e){if(e&&e.__esModule)return e;var i={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&t(i,e,n);return r(i,e),i};Object.defineProperty(e,"__esModule",{value:!0}),e.v6=e.AddressError=e.Address6=e.Address4=void 0;const n=Ni;Object.defineProperty(e,"Address4",{enumerable:!0,get:function(){return n.Address4}});const s=tn;Object.defineProperty(e,"Address6",{enumerable:!0,get:function(){return s.Address6}});const o=zi;Object.defineProperty(e,"AddressError",{enumerable:!0,get:function(){return o.AddressError}});const c=i(nn);e.v6={helpers:c}}(Ai);var Mn={exports:{}};!function(e){(function(){var t,r,i,n,s,o,a,c;r={},null!==e&&e.exports?e.exports=r:this.ipaddr=r,a=function(e,t,r,i){var n,s;if(e.length!==t.length)throw new Error("ipaddr: cannot match CIDR for objects with different lengths");for(n=0;i>0;){if((s=r-i)<0&&(s=0),e[n]>>s!=t[n]>>s)return!1;i-=r,n+=1}return!0},r.subnetMatch=function(e,t,r){var i,n,s,o,a;for(s in null==r&&(r="unicast"),t)for(!(o=t[s])[0]||o[0]instanceof Array||(o=[o]),i=0,n=o.length;i<n;i++)if(a=o[i],e.kind()===a[0].kind()&&e.match.apply(e,a))return s;return r},r.IPv4=function(){function e(e){var t,r,i;if(4!==e.length)throw new Error("ipaddr: ipv4 octet count should be 4");for(t=0,r=e.length;t<r;t++)if(!(0<=(i=e[t])&&i<=255))throw new Error("ipaddr: ipv4 octet should fit in 8 bits");this.octets=e}return e.prototype.kind=function(){return"ipv4"},e.prototype.toString=function(){return this.octets.join(".")},e.prototype.toNormalizedString=function(){return this.toString()},e.prototype.toByteArray=function(){return this.octets.slice(0)},e.prototype.match=function(e,t){var r;if(void 0===t&&(e=(r=e)[0],t=r[1]),"ipv4"!==e.kind())throw new Error("ipaddr: cannot match ipv4 address with non-ipv4 one");return a(this.octets,e.octets,8,t)},e.prototype.SpecialRanges={unspecified:[[new e([0,0,0,0]),8]],broadcast:[[new e([255,255,255,255]),32]],multicast:[[new e([224,0,0,0]),4]],linkLocal:[[new e([169,254,0,0]),16]],loopback:[[new e([127,0,0,0]),8]],carrierGradeNat:[[new e([100,64,0,0]),10]],private:[[new e([10,0,0,0]),8],[new e([172,16,0,0]),12],[new e([192,168,0,0]),16]],reserved:[[new e([192,0,0,0]),24],[new e([192,0,2,0]),24],[new e([192,88,99,0]),24],[new e([198,51,100,0]),24],[new e([203,0,113,0]),24],[new e([240,0,0,0]),4]]},e.prototype.range=function(){return r.subnetMatch(this,this.SpecialRanges)},e.prototype.toIPv4MappedAddress=function(){return r.IPv6.parse("::ffff:"+this.toString())},e.prototype.prefixLengthFromSubnetMask=function(){var e,t,r,i,n,s,o;for(o={0:8,128:7,192:6,224:5,240:4,248:3,252:2,254:1,255:0},e=0,n=!1,t=r=3;r>=0;t=r+=-1){if(!((i=this.octets[t])in o))return null;if(s=o[i],n&&0!==s)return null;8!==s&&(n=!0),e+=s}return 32-e},e}(),i="(0?\\d+|0x[a-f0-9]+)",n={fourOctet:new RegExp("^"+i+"\\."+i+"\\."+i+"\\."+i+"$","i"),longValue:new RegExp("^"+i+"$","i")},r.IPv4.parser=function(e){var t,r,i,s,o;if(r=function(e){return"0"===e[0]&&"x"!==e[1]?parseInt(e,8):parseInt(e)},t=e.match(n.fourOctet))return function(){var e,n,s,o;for(o=[],e=0,n=(s=t.slice(1,6)).length;e<n;e++)i=s[e],o.push(r(i));return o}();if(t=e.match(n.longValue)){if((o=r(t[1]))>4294967295||o<0)throw new Error("ipaddr: address outside defined range");return function(){var e,t;for(t=[],s=e=0;e<=24;s=e+=8)t.push(o>>s&255);return t}().reverse()}return null},r.IPv6=function(){function e(e,t){var r,i,n,s,o,a;if(16===e.length)for(this.parts=[],r=i=0;i<=14;r=i+=2)this.parts.push(e[r]<<8|e[r+1]);else{if(8!==e.length)throw new Error("ipaddr: ipv6 part count should be 8 or 16");this.parts=e}for(n=0,s=(a=this.parts).length;n<s;n++)if(!(0<=(o=a[n])&&o<=65535))throw new Error("ipaddr: ipv6 part should fit in 16 bits");t&&(this.zoneId=t)}return e.prototype.kind=function(){return"ipv6"},e.prototype.toString=function(){return this.toNormalizedString().replace(/((^|:)(0(:|$))+)/,"::")},e.prototype.toRFC5952String=function(){var e,t,r,i,n;for(i=/((^|:)(0(:|$)){2,})/g,n=this.toNormalizedString(),e=0,t=-1;r=i.exec(n);)r[0].length>t&&(e=r.index,t=r[0].length);return t<0?n:n.substring(0,e)+"::"+n.substring(e+t)},e.prototype.toByteArray=function(){var e,t,r,i,n;for(e=[],t=0,r=(n=this.parts).length;t<r;t++)i=n[t],e.push(i>>8),e.push(255&i);return e},e.prototype.toNormalizedString=function(){var e,t,r;return e=function(){var e,r,i,n;for(n=[],e=0,r=(i=this.parts).length;e<r;e++)t=i[e],n.push(t.toString(16));return n}.call(this).join(":"),r="",this.zoneId&&(r="%"+this.zoneId),e+r},e.prototype.toFixedLengthString=function(){var e,t,r;return e=function(){var e,r,i,n;for(n=[],e=0,r=(i=this.parts).length;e<r;e++)t=i[e],n.push(t.toString(16).padStart(4,"0"));return n}.call(this).join(":"),r="",this.zoneId&&(r="%"+this.zoneId),e+r},e.prototype.match=function(e,t){var r;if(void 0===t&&(e=(r=e)[0],t=r[1]),"ipv6"!==e.kind())throw new Error("ipaddr: cannot match ipv6 address with non-ipv6 one");return a(this.parts,e.parts,16,t)},e.prototype.SpecialRanges={unspecified:[new e([0,0,0,0,0,0,0,0]),128],linkLocal:[new e([65152,0,0,0,0,0,0,0]),10],multicast:[new e([65280,0,0,0,0,0,0,0]),8],loopback:[new e([0,0,0,0,0,0,0,1]),128],uniqueLocal:[new e([64512,0,0,0,0,0,0,0]),7],ipv4Mapped:[new e([0,0,0,0,0,65535,0,0]),96],rfc6145:[new e([0,0,0,0,65535,0,0,0]),96],rfc6052:[new e([100,65435,0,0,0,0,0,0]),96],"6to4":[new e([8194,0,0,0,0,0,0,0]),16],teredo:[new e([8193,0,0,0,0,0,0,0]),32],reserved:[[new e([8193,3512,0,0,0,0,0,0]),32]]},e.prototype.range=function(){return r.subnetMatch(this,this.SpecialRanges)},e.prototype.isIPv4MappedAddress=function(){return"ipv4Mapped"===this.range()},e.prototype.toIPv4Address=function(){var e,t,i;if(!this.isIPv4MappedAddress())throw new Error("ipaddr: trying to convert a generic ipv6 address to ipv4");return e=(i=this.parts.slice(-2))[0],t=i[1],new r.IPv4([e>>8,255&e,t>>8,255&t])},e.prototype.prefixLengthFromSubnetMask=function(){var e,t,r,i,n,s,o;for(o={0:16,32768:15,49152:14,57344:13,61440:12,63488:11,64512:10,65024:9,65280:8,65408:7,65472:6,65504:5,65520:4,65528:3,65532:2,65534:1,65535:0},e=0,n=!1,t=r=7;r>=0;t=r+=-1){if(!((i=this.parts[t])in o))return null;if(s=o[i],n&&0!==s)return null;16!==s&&(n=!0),e+=s}return 128-e},e}(),s="(?:[0-9a-f]+::?)+",c="%[0-9a-z]{1,}",o={zoneIndex:new RegExp(c,"i"),native:new RegExp("^(::)?("+s+")?([0-9a-f]+)?(::)?("+c+")?$","i"),transitional:new RegExp("^((?:"+s+")|(?:::)(?:"+s+")?)"+i+"\\."+i+"\\."+i+"\\."+i+"("+c+")?$","i")},t=function(e,t){var r,i,n,s,a,c;if(e.indexOf("::")!==e.lastIndexOf("::"))return null;for((c=(e.match(o.zoneIndex)||[])[0])&&(c=c.substring(1),e=e.replace(/%.+$/,"")),r=0,i=-1;(i=e.indexOf(":",i+1))>=0;)r++;if("::"===e.substr(0,2)&&r--,"::"===e.substr(-2,2)&&r--,r>t)return null;for(a=t-r,s=":";a--;)s+="0:";return":"===(e=e.replace("::",s))[0]&&(e=e.slice(1)),":"===e[e.length-1]&&(e=e.slice(0,-1)),{parts:t=function(){var t,r,i,s;for(s=[],t=0,r=(i=e.split(":")).length;t<r;t++)n=i[t],s.push(parseInt(n,16));return s}(),zoneId:c}},r.IPv6.parser=function(e){var r,i,n,s,a,c,d;if(o.native.test(e))return t(e,8);if((s=e.match(o.transitional))&&(d=s[6]||"",(r=t(s[1].slice(0,-1)+d,6)).parts)){for(i=0,n=(c=[parseInt(s[2]),parseInt(s[3]),parseInt(s[4]),parseInt(s[5])]).length;i<n;i++)if(!(0<=(a=c[i])&&a<=255))return null;return r.parts.push(c[0]<<8|c[1]),r.parts.push(c[2]<<8|c[3]),{parts:r.parts,zoneId:r.zoneId}}return null},r.IPv4.isIPv4=r.IPv6.isIPv6=function(e){return null!==this.parser(e)},r.IPv4.isValid=function(e){try{return new this(this.parser(e)),!0}catch(e){return!1}},r.IPv4.isValidFourPartDecimal=function(e){return!(!r.IPv4.isValid(e)||!e.match(/^(0|[1-9]\d*)(\.(0|[1-9]\d*)){3}$/))},r.IPv6.isValid=function(e){var t;if("string"==typeof e&&-1===e.indexOf(":"))return!1;try{return new this((t=this.parser(e)).parts,t.zoneId),!0}catch(e){return!1}},r.IPv4.parse=function(e){var t;if(null===(t=this.parser(e)))throw new Error("ipaddr: string is not formatted like ip address");return new this(t)},r.IPv6.parse=function(e){var t;if(null===(t=this.parser(e)).parts)throw new Error("ipaddr: string is not formatted like ip address");return new this(t.parts,t.zoneId)},r.IPv4.parseCIDR=function(e){var t,r,i;if((r=e.match(/^(.+)\/(\d+)$/))&&(t=parseInt(r[2]))>=0&&t<=32)return i=[this.parse(r[1]),t],Object.defineProperty(i,"toString",{value:function(){return this.join("/")}}),i;throw new Error("ipaddr: string is not formatted like an IPv4 CIDR range")},r.IPv4.subnetMaskFromPrefixLength=function(e){var t,r,i;if((e=parseInt(e))<0||e>32)throw new Error("ipaddr: invalid IPv4 prefix length");for(i=[0,0,0,0],r=0,t=Math.floor(e/8);r<t;)i[r]=255,r++;return t<4&&(i[t]=Math.pow(2,e%8)-1<<8-e%8),new this(i)},r.IPv4.broadcastAddressFromCIDR=function(e){var t,r,i,n,s;try{for(i=(t=this.parseCIDR(e))[0].toByteArray(),s=this.subnetMaskFromPrefixLength(t[1]).toByteArray(),n=[],r=0;r<4;)n.push(parseInt(i[r],10)|255^parseInt(s[r],10)),r++;return new this(n)}catch(e){throw new Error("ipaddr: the address does not have IPv4 CIDR format")}},r.IPv4.networkAddressFromCIDR=function(e){var t,r,i,n,s;try{for(i=(t=this.parseCIDR(e))[0].toByteArray(),s=this.subnetMaskFromPrefixLength(t[1]).toByteArray(),n=[],r=0;r<4;)n.push(parseInt(i[r],10)&parseInt(s[r],10)),r++;return new this(n)}catch(e){throw new Error("ipaddr: the address does not have IPv4 CIDR format")}},r.IPv6.parseCIDR=function(e){var t,r,i;if((r=e.match(/^(.+)\/(\d+)$/))&&(t=parseInt(r[2]))>=0&&t<=128)return i=[this.parse(r[1]),t],Object.defineProperty(i,"toString",{value:function(){return this.join("/")}}),i;throw new Error("ipaddr: string is not formatted like an IPv6 CIDR range")},r.isValid=function(e){return r.IPv6.isValid(e)||r.IPv4.isValid(e)},r.parse=function(e){if(r.IPv6.isValid(e))return r.IPv6.parse(e);if(r.IPv4.isValid(e))return r.IPv4.parse(e);throw new Error("ipaddr: the address has neither IPv6 nor IPv4 format")},r.parseCIDR=function(e){try{return r.IPv6.parseCIDR(e)}catch(t){try{return r.IPv4.parseCIDR(e)}catch(e){throw new Error("ipaddr: the address has neither IPv6 nor IPv4 CIDR format")}}},r.fromByteArray=function(e){var t;if(4===(t=e.length))return new r.IPv4(e);if(16===t)return new r.IPv6(e);throw new Error("ipaddr: the binary input is neither an IPv6 nor IPv4 address")},r.process=function(e){var t;return"ipv6"===(t=this.parse(e)).kind()&&t.isIPv4MappedAddress()?t.toIPv4Address():t}}).call(a)}(Mn);var jn=Mn.exports,Ln=function(e,t){if("string"==typeof t)return An(e,t);if("object"==typeof t){for(var r=!1,i=0;i<t.length;i++)if(An(e,t[i])){r=!0;break}return r}};function An(e,t){try{var r=jn.process(e);if(-1===t.indexOf("/")){var i=jn.process(t);return"ipv6"===r.kind()&&"ipv6"===i.kind()?r.toNormalizedString()===i.toNormalizedString():r.toString()==i.toString()}var n=jn.parseCIDR(t);return r.match(n)}catch(e){return!1}}var Nn=Ln,Bn=/^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/,Fn=["0.0.0.0/8","10.0.0.0/8","100.64.0.0/10","127.0.0.0/8","169.254.0.0/16","172.16.0.0/12","192.0.0.0/24","192.0.2.0/24","192.168.0.0/16","198.18.0.0/15","198.51.100.0/24","203.0.113.0/24","224.0.0.0/3"],zn=["10.0.0.0/8","172.16.0.0/12","192.168.0.0/16"];for(var Vn=function(e){var t=[],r={originalIp:e,boiledIp:!1,isValid:!1,isBogon:!1,isApipa:!1,isMulticast:!1,isRfc1918:!1,isPublicIp:!1};if(Bn.test(e)){r.isValid=!0;for(var i=e.split("."),n=0;n<4;n++)t.push(parseInt(i[n],10));r.boiledIp=t.join("."),Nn(r.boiledIp,Fn)&&(r.isBogon=!0),Nn(r.boiledIp,"169.254.0.0/16")&&(r.isApipa=!0),Nn(r.boiledIp,"224.0.0.0/4")&&(r.isMulticast=!0),Nn(r.boiledIp,zn)?r.isRfc1918=!0:!1===r.isBogon&&(r.isPublicIp=!0)}return r},Un=c(Vn),$n={exports:{}},Gn=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[0-9a-f]{4}-[0-9a-f]{12}$/i,qn=[],Hn=0;Hn<256;Hn++)qn[Hn]=(Hn+256).toString(16).substr(1);$n.exports=function(e,t){var r;if(Buffer.isBuffer(e))r=function(e,t){var r=t||0,i=qn;return i[e[r++]]+i[e[r++]]+i[e[r++]]+i[e[r++]]+"-"+i[e[r++]]+i[e[r++]]+"-"+i[e[r++]]+i[e[r++]]+"-"+i[e[r++]]+i[e[r++]]+"-"+i[e[r++]]+i[e[r++]]+i[e[r++]]+i[e[r++]]+i[e[r++]]+i[e[r++]]}(e);else{if("[object String]"!==Object.prototype.toString.call(e))return!1;r=e}if(r=r.toLowerCase(),!Gn.test(r))return!1;if(void 0===t)t=Jn(r);else if(Jn(r)!==t)return!1;switch(t){case 1:case 2:return!0;case 3:case 4:case 5:return-1!==["8","9","a","b"].indexOf(r.charAt(19));default:throw new Error("Invalid version provided.")}};var Wn,Kn,Jn=$n.exports.version=function(e){return 0|e.charAt(14)},Xn=c($n.exports),Qn={},Zn={exports:{}};function Yn(){if(Kn)return Wn;Kn=1;var e=1e3,t=60*e,r=60*t,i=24*r,n=7*i,s=365.25*i;function o(e,t,r,i){var n=t>=1.5*r;return Math.round(e/r)+" "+i+(n?"s":"")}return Wn=function(a,c){c=c||{};var d=typeof a;if("string"===d&&a.length>0)return function(o){if((o=String(o)).length>100)return;var a=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(o);if(!a)return;var c=parseFloat(a[1]);switch((a[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return c*s;case"weeks":case"week":case"w":return c*n;case"days":case"day":case"d":return c*i;case"hours":case"hour":case"hrs":case"hr":case"h":return c*r;case"minutes":case"minute":case"mins":case"min":case"m":return c*t;case"seconds":case"second":case"secs":case"sec":case"s":return c*e;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return c;default:return}}(a);if("number"===d&&isFinite(a))return c.long?function(n){var s=Math.abs(n);if(s>=i)return o(n,s,i,"day");if(s>=r)return o(n,s,r,"hour");if(s>=t)return o(n,s,t,"minute");if(s>=e)return o(n,s,e,"second");return n+" ms"}(a):function(n){var s=Math.abs(n);if(s>=i)return Math.round(n/i)+"d";if(s>=r)return Math.round(n/r)+"h";if(s>=t)return Math.round(n/t)+"m";if(s>=e)return Math.round(n/e)+"s";return n+"ms"}(a);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(a))},Wn}var es=function(e){function t(e){let i,n,s,o=null;function a(...e){if(!a.enabled)return;const r=a,n=Number(new Date),s=n-(i||n);r.diff=s,r.prev=i,r.curr=n,i=n,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let o=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,((i,n)=>{if("%%"===i)return"%";o++;const s=t.formatters[n];if("function"==typeof s){const t=e[o];i=s.call(r,t),e.splice(o,1),o--}return i})),t.formatArgs.call(r,e);(r.log||t.log).apply(r,e)}return a.namespace=e,a.useColors=t.useColors(),a.color=t.selectColor(e),a.extend=r,a.destroy=t.destroy,Object.defineProperty(a,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==o?o:(n!==t.namespaces&&(n=t.namespaces,s=t.enabled(e)),s),set:e=>{o=e}}),"function"==typeof t.init&&t.init(a),a}function r(e,r){const i=t(this.namespace+(void 0===r?":":r)+e);return i.log=this.log,i}function i(e){return e.toString().substring(2,e.toString().length-2).replace(/\.\*\?$/,"*")}return t.debug=t,t.default=t,t.coerce=function(e){if(e instanceof Error)return e.stack||e.message;return e},t.disable=function(){const e=[...t.names.map(i),...t.skips.map(i).map((e=>"-"+e))].join(",");return t.enable(""),e},t.enable=function(e){let r;t.save(e),t.namespaces=e,t.names=[],t.skips=[];const i=("string"==typeof e?e:"").split(/[\s,]+/),n=i.length;for(r=0;r<n;r++)i[r]&&("-"===(e=i[r].replace(/\*/g,".*?"))[0]?t.skips.push(new RegExp("^"+e.slice(1)+"$")):t.names.push(new RegExp("^"+e+"$")))},t.enabled=function(e){if("*"===e[e.length-1])return!0;let r,i;for(r=0,i=t.skips.length;r<i;r++)if(t.skips[r].test(e))return!1;for(r=0,i=t.names.length;r<i;r++)if(t.names[r].test(e))return!0;return!1},t.humanize=Yn(),t.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(e).forEach((r=>{t[r]=e[r]})),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let r=0;for(let t=0;t<e.length;t++)r=(r<<5)-r+e.charCodeAt(t),r|=0;return t.colors[Math.abs(r)%t.colors.length]},t.enable(t.load()),t};!function(e,t){t.formatArgs=function(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;const r="color: "+this.color;t.splice(1,0,r,"color: inherit");let i=0,n=0;t[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(i++,"%c"===e&&(n=i))})),t.splice(n,0,r)},t.save=function(e){try{e?t.storage.setItem("debug",e):t.storage.removeItem("debug")}catch(e){}},t.load=function(){let e;try{e=t.storage.getItem("debug")}catch(e){}!e&&"undefined"!=typeof process&&"env"in process&&(e=process.env.DEBUG);return e},t.useColors=function(){if("undefined"!=typeof window&&window.process&&("renderer"===window.process.type||window.process.__nwjs))return!0;if("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let e;return"undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&(e=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(e[1],10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},t.storage=function(){try{return localStorage}catch(e){}}(),t.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],t.log=console.debug||console.log||(()=>{}),e.exports=es(t);const{formatters:r}=e.exports;r.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}(Zn,Zn.exports);var ts=Zn.exports,rs={},is={exports:{}};!function(e,t){!function(r,i){var n,s="",o="function",a="undefined",c="object",d="string",l="major",u="model",p="name",h="type",f="vendor",m="version",g="architecture",v="console",b="mobile",y="tablet",w="smarttv",_="wearable",S="xr",C="embedded",R="inapp",k="user-agent",T="brands",P="formFactors",O="fullVersionList",E="platform",D="platformVersion",I="bitness",x="sec-ch-ua",M=x+"-full-version-list",j=x+"-arch",L=x+"-"+I,A=x+"-form-factors",N=x+"-"+b,B=x+"-"+u,F=x+"-"+E,z=F+"-version",V=[T,O,b,u,E,D,g,P,I],U="browser",$="cpu",G="device",q="engine",H="os",W="result",K="Amazon",J="Apple",X="ASUS",Q="BlackBerry",Z="Google",Y="Huawei",ee="Lenovo",te="LG",re="Microsoft",ie="Motorola",ne="Samsung",se="Sharp",oe="Sony",ae="Xiaomi",ce="Zebra",de="Mobile ",le=" Browser",ue="Chrome",pe="Chromecast",he="Firefox",fe="Opera",me="Facebook",ge="Sogou",ve="Windows",be=typeof r!==a,ye=be&&r.navigator?r.navigator:i,we=ye&&ye.userAgentData?ye.userAgentData:i,_e=function(e){for(var t={},r=0;r<e.length;r++)t[e[r].toUpperCase()]=e[r];return t},Se=function(e,t){if(typeof e===c&&e.length>0){for(var r in e)if(Te(e[r])==Te(t))return!0;return!1}return!!Re(e)&&-1!==Te(t).indexOf(Te(e))},Ce=function(e,t){for(var r in e)return/^(browser|cpu|device|engine|os)$/.test(r)||!!t&&Ce(e[r])},Re=function(e){return typeof e===d},ke=function(e){if(!e)return i;for(var t=[],r=Ee(/\\?\"/g,e).split(","),n=0;n<r.length;n++)if(r[n].indexOf(";")>-1){var s=Ie(r[n]).split(";v=");t[n]={brand:s[0],version:s[1]}}else t[n]=Ie(r[n]);return t},Te=function(e){return Re(e)?e.toLowerCase():e},Pe=function(e){return Re(e)?Ee(/[^\d\.]/g,e).split(".")[0]:i},Oe=function(e){for(var t in e){var r=e[t];typeof r==c&&2==r.length?this[r[0]]=r[1]:this[r]=i}return this},Ee=function(e,t){return Re(t)?t.replace(e,s):t},De=function(e){return Ee(/\\?\"/g,e)},Ie=function(e,t){if(Re(e))return e=Ee(/^\s\s*/,e),typeof t===a?e:e.substring(0,500)},xe=function(e,t){if(e&&t)for(var r,n,s,a,d,l,u=0;u<t.length&&!d;){var p=t[u],h=t[u+1];for(r=n=0;r<p.length&&!d&&p[r];)if(d=p[r++].exec(e))for(s=0;s<h.length;s++)l=d[++n],typeof(a=h[s])===c&&a.length>0?2===a.length?typeof a[1]==o?this[a[0]]=a[1].call(this,l):this[a[0]]=a[1]:3===a.length?typeof a[1]!==o||a[1].exec&&a[1].test?this[a[0]]=l?l.replace(a[1],a[2]):i:this[a[0]]=l?a[1].call(this,l,a[2]):i:4===a.length&&(this[a[0]]=l?a[3].call(this,l.replace(a[1],a[2])):i):this[a]=l||i;u+=2}},Me=function(e,t){for(var r in t)if(typeof t[r]===c&&t[r].length>0){for(var n=0;n<t[r].length;n++)if(Se(t[r][n],e))return"?"===r?i:r}else if(Se(t[r],e))return"?"===r?i:r;return t.hasOwnProperty("*")?t["*"]:e},je={ME:"4.90","NT 3.11":"NT3.51","NT 4.0":"NT4.0",2e3:"NT 5.0",XP:["NT 5.1","NT 5.2"],Vista:"NT 6.0",7:"NT 6.1",8:"NT 6.2",8.1:"NT 6.3",10:["NT 6.4","NT 10.0"],RT:"ARM"},Le={embedded:"Automotive",mobile:"Mobile",tablet:["Tablet","EInk"],smarttv:"TV",wearable:"Watch",xr:["VR","XR"],"?":["Desktop","Unknown"],"*":i},Ae={browser:[[/\b(?:crmo|crios)\/([\w\.]+)/i],[m,[p,de+"Chrome"]],[/edg(?:e|ios|a)?\/([\w\.]+)/i],[m,[p,"Edge"]],[/(opera mini)\/([-\w\.]+)/i,/(opera [mobiletab]{3,6})\b.+version\/([-\w\.]+)/i,/(opera)(?:.+version\/|[\/ ]+)([\w\.]+)/i],[p,m],[/opios[\/ ]+([\w\.]+)/i],[m,[p,fe+" Mini"]],[/\bop(?:rg)?x\/([\w\.]+)/i],[m,[p,fe+" GX"]],[/\bopr\/([\w\.]+)/i],[m,[p,fe]],[/\bb[ai]*d(?:uhd|[ub]*[aekoprswx]{5,6})[\/ ]?([\w\.]+)/i],[m,[p,"Baidu"]],[/\b(?:mxbrowser|mxios|myie2)\/?([-\w\.]*)\b/i],[m,[p,"Maxthon"]],[/(kindle)\/([\w\.]+)/i,/(lunascape|maxthon|netfront|jasmine|blazer|sleipnir)[\/ ]?([\w\.]*)/i,/(avant|iemobile|slim(?:browser|boat|jet))[\/ ]?([\d\.]*)/i,/(?:ms|\()(ie) ([\w\.]+)/i,/(flock|rockmelt|midori|epiphany|silk|skyfire|ovibrowser|bolt|iron|vivaldi|iridium|phantomjs|bowser|qupzilla|falkon|rekonq|puffin|brave|whale(?!.+naver)|qqbrowserlite|duckduckgo|klar|helio|(?=comodo_)?dragon)\/([-\w\.]+)/i,/(heytap|ovi|115)browser\/([\d\.]+)/i,/(weibo)__([\d\.]+)/i],[p,m],[/quark(?:pc)?\/([-\w\.]+)/i],[m,[p,"Quark"]],[/\bddg\/([\w\.]+)/i],[m,[p,"DuckDuckGo"]],[/(?:\buc? ?browser|(?:juc.+)ucweb)[\/ ]?([\w\.]+)/i],[m,[p,"UCBrowser"]],[/microm.+\bqbcore\/([\w\.]+)/i,/\bqbcore\/([\w\.]+).+microm/i,/micromessenger\/([\w\.]+)/i],[m,[p,"WeChat"]],[/konqueror\/([\w\.]+)/i],[m,[p,"Konqueror"]],[/trident.+rv[: ]([\w\.]{1,9})\b.+like gecko/i],[m,[p,"IE"]],[/ya(?:search)?browser\/([\w\.]+)/i],[m,[p,"Yandex"]],[/slbrowser\/([\w\.]+)/i],[m,[p,"Smart "+ee+le]],[/(avast|avg)\/([\w\.]+)/i],[[p,/(.+)/,"$1 Secure"+le],m],[/\bfocus\/([\w\.]+)/i],[m,[p,he+" Focus"]],[/\bopt\/([\w\.]+)/i],[m,[p,fe+" Touch"]],[/coc_coc\w+\/([\w\.]+)/i],[m,[p,"Coc Coc"]],[/dolfin\/([\w\.]+)/i],[m,[p,"Dolphin"]],[/coast\/([\w\.]+)/i],[m,[p,fe+" Coast"]],[/miuibrowser\/([\w\.]+)/i],[m,[p,"MIUI"+le]],[/fxios\/([\w\.-]+)/i],[m,[p,de+he]],[/\bqihoobrowser\/?([\w\.]*)/i],[m,[p,"360"]],[/\b(qq)\/([\w\.]+)/i],[[p,/(.+)/,"$1Browser"],m],[/(oculus|sailfish|huawei|vivo|pico)browser\/([\w\.]+)/i],[[p,/(.+)/,"$1"+le],m],[/samsungbrowser\/([\w\.]+)/i],[m,[p,ne+" Internet"]],[/metasr[\/ ]?([\d\.]+)/i],[m,[p,ge+" Explorer"]],[/(sogou)mo\w+\/([\d\.]+)/i],[[p,ge+" Mobile"],m],[/(electron)\/([\w\.]+) safari/i,/(tesla)(?: qtcarbrowser|\/(20\d\d\.[-\w\.]+))/i,/m?(qqbrowser|2345(?=browser|chrome|explorer))\w*[\/ ]?v?([\w\.]+)/i],[p,m],[/(lbbrowser|rekonq)/i],[p],[/ome\/([\w\.]+) \w* ?(iron) saf/i,/ome\/([\w\.]+).+qihu (360)[es]e/i],[m,p],[/((?:fban\/fbios|fb_iab\/fb4a)(?!.+fbav)|;fbav\/([\w\.]+);)/i],[[p,me],m,[h,R]],[/(Klarna)\/([\w\.]+)/i,/(kakao(?:talk|story))[\/ ]([\w\.]+)/i,/(naver)\(.*?(\d+\.[\w\.]+).*\)/i,/safari (line)\/([\w\.]+)/i,/\b(line)\/([\w\.]+)\/iab/i,/(alipay)client\/([\w\.]+)/i,/(twitter)(?:and| f.+e\/([\w\.]+))/i,/(instagram|snapchat)[\/ ]([-\w\.]+)/i],[p,m,[h,R]],[/\bgsa\/([\w\.]+) .*safari\//i],[m,[p,"GSA"],[h,R]],[/musical_ly(?:.+app_?version\/|_)([\w\.]+)/i],[m,[p,"TikTok"],[h,R]],[/\[(linkedin)app\]/i],[p,[h,R]],[/(chromium)[\/ ]([-\w\.]+)/i],[p,m],[/headlesschrome(?:\/([\w\.]+)| )/i],[m,[p,ue+" Headless"]],[/ wv\).+(chrome)\/([\w\.]+)/i],[[p,ue+" WebView"],m],[/droid.+ version\/([\w\.]+)\b.+(?:mobile safari|safari)/i],[m,[p,"Android"+le]],[/chrome\/([\w\.]+) mobile/i],[m,[p,de+"Chrome"]],[/(chrome|omniweb|arora|[tizenoka]{5} ?browser)\/v?([\w\.]+)/i],[p,m],[/version\/([\w\.\,]+) .*mobile(?:\/\w+ | ?)safari/i],[m,[p,de+"Safari"]],[/iphone .*mobile(?:\/\w+ | ?)safari/i],[[p,de+"Safari"]],[/version\/([\w\.\,]+) .*(safari)/i],[m,p],[/webkit.+?(mobile ?safari|safari)(\/[\w\.]+)/i],[p,[m,"1"]],[/(webkit|khtml)\/([\w\.]+)/i],[p,m],[/(?:mobile|tablet);.*(firefox)\/([\w\.-]+)/i],[[p,de+he],m],[/(navigator|netscape\d?)\/([-\w\.]+)/i],[[p,"Netscape"],m],[/(wolvic|librewolf)\/([\w\.]+)/i],[p,m],[/mobile vr; rv:([\w\.]+)\).+firefox/i],[m,[p,he+" Reality"]],[/ekiohf.+(flow)\/([\w\.]+)/i,/(swiftfox)/i,/(icedragon|iceweasel|camino|chimera|fennec|maemo browser|minimo|conkeror)[\/ ]?([\w\.\+]+)/i,/(seamonkey|k-meleon|icecat|iceape|firebird|phoenix|palemoon|basilisk|waterfox)\/([-\w\.]+)$/i,/(firefox)\/([\w\.]+)/i,/(mozilla)\/([\w\.]+) .+rv\:.+gecko\/\d+/i,/(polaris|lynx|dillo|icab|doris|amaya|w3m|netsurf|obigo|mosaic|(?:go|ice|up)[\. ]?browser)[-\/ ]?v?([\w\.]+)/i,/\b(links) \(([\w\.]+)/i],[p,[m,/_/g,"."]],[/(cobalt)\/([\w\.]+)/i],[p,[m,/[^\d\.]+./,s]]],cpu:[[/\b(?:(amd|x|x86[-_]?|wow|win)64)\b/i],[[g,"amd64"]],[/(ia32(?=;))/i,/((?:i[346]|x)86)[;\)]/i],[[g,"ia32"]],[/\b(aarch64|arm(v?8e?l?|_?64))\b/i],[[g,"arm64"]],[/\b(arm(?:v[67])?ht?n?[fl]p?)\b/i],[[g,"armhf"]],[/windows (ce|mobile); ppc;/i],[[g,"arm"]],[/((?:ppc|powerpc)(?:64)?)(?: mac|;|\))/i],[[g,/ower/,s,Te]],[/(sun4\w)[;\)]/i],[[g,"sparc"]],[/((?:avr32|ia64(?=;))|68k(?=\))|\barm(?=v(?:[1-7]|[5-7]1)l?|;|eabi)|(?=atmel )avr|(?:irix|mips|sparc)(?:64)?\b|pa-risc)/i],[[g,Te]]],device:[[/\b(sch-i[89]0\d|shw-m380s|sm-[ptx]\w{2,4}|gt-[pn]\d{2,4}|sgh-t8[56]9|nexus 10)/i],[u,[f,ne],[h,y]],[/\b((?:s[cgp]h|gt|sm)-(?![lr])\w+|sc[g-]?[\d]+a?|galaxy nexus)/i,/samsung[- ]((?!sm-[lr])[-\w]+)/i,/sec-(sgh\w+)/i],[u,[f,ne],[h,b]],[/(?:\/|\()(ip(?:hone|od)[\w, ]*)(?:\/|;)/i],[u,[f,J],[h,b]],[/\((ipad);[-\w\),; ]+apple/i,/applecoremedia\/[\w\.]+ \((ipad)/i,/\b(ipad)\d\d?,\d\d?[;\]].+ios/i],[u,[f,J],[h,y]],[/(macintosh);/i],[u,[f,J]],[/\b(sh-?[altvz]?\d\d[a-ekm]?)/i],[u,[f,se],[h,b]],[/(?:honor)([-\w ]+)[;\)]/i],[u,[f,"Honor"],[h,b]],[/\b((?:ag[rs][23]?|bah2?|sht?|btv)-a?[lw]\d{2})\b(?!.+d\/s)/i],[u,[f,Y],[h,y]],[/(?:huawei)([-\w ]+)[;\)]/i,/\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][012359c][adn]?)\b(?!.+d\/s)/i],[u,[f,Y],[h,b]],[/\b(poco[\w ]+|m2\d{3}j\d\d[a-z]{2})(?: bui|\))/i,/\b; (\w+) build\/hm\1/i,/\b(hm[-_ ]?note?[_ ]?(?:\d\w)?) bui/i,/\b(redmi[\-_ ]?(?:note|k)?[\w_ ]+)(?: bui|\))/i,/oid[^\)]+; (m?[12][0-389][01]\w{3,6}[c-y])( bui|; wv|\))/i,/\b(mi[-_ ]?(?:a\d|one|one[_ ]plus|note lte|max|cc)?[_ ]?(?:\d?\w?)[_ ]?(?:plus|se|lite|pro)?)(?: bui|\))/i],[[u,/_/g," "],[f,ae],[h,b]],[/oid[^\)]+; (2\d{4}(283|rpbf)[cgl])( bui|\))/i,/\b(mi[-_ ]?(?:pad)(?:[\w_ ]+))(?: bui|\))/i],[[u,/_/g," "],[f,ae],[h,y]],[/; (\w+) bui.+ oppo/i,/\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i],[u,[f,"OPPO"],[h,b]],[/\b(opd2\d{3}a?) bui/i],[u,[f,"OPPO"],[h,y]],[/vivo (\w+)(?: bui|\))/i,/\b(v[12]\d{3}\w?[at])(?: bui|;)/i],[u,[f,"Vivo"],[h,b]],[/\b(rmx[1-3]\d{3})(?: bui|;|\))/i],[u,[f,"Realme"],[h,b]],[/\b(milestone|droid(?:[2-4x]| (?:bionic|x2|pro|razr))?:?( 4g)?)\b[\w ]+build\//i,/\bmot(?:orola)?[- ](\w*)/i,/((?:moto[\w\(\) ]+|xt\d{3,4}|nexus 6)(?= bui|\)))/i],[u,[f,ie],[h,b]],[/\b(mz60\d|xoom[2 ]{0,2}) build\//i],[u,[f,ie],[h,y]],[/((?=lg)?[vl]k\-?\d{3}) bui| 3\.[-\w; ]{10}lg?-([06cv9]{3,4})/i],[u,[f,te],[h,y]],[/(lm(?:-?f100[nv]?|-[\w\.]+)(?= bui|\))|nexus [45])/i,/\blg[-e;\/ ]+((?!browser|netcast|android tv)\w+)/i,/\blg-?([\d\w]+) bui/i],[u,[f,te],[h,b]],[/(ideatab[-\w ]+)/i,/lenovo ?(s[56]000[-\w]+|tab(?:[\w ]+)|yt[-\d\w]{6}|tb[-\d\w]{6})/i],[u,[f,ee],[h,y]],[/(?:maemo|nokia).*(n900|lumia \d+)/i,/nokia[-_ ]?([-\w\.]*)/i],[[u,/_/g," "],[f,"Nokia"],[h,b]],[/(pixel c)\b/i],[u,[f,Z],[h,y]],[/droid.+; (pixel[\daxl ]{0,6})(?: bui|\))/i],[u,[f,Z],[h,b]],[/droid.+; (a?\d[0-2]{2}so|[c-g]\d{4}|so[-gl]\w+|xq-a\w[4-7][12])(?= bui|\).+chrome\/(?![1-6]{0,1}\d\.))/i],[u,[f,oe],[h,b]],[/sony tablet [ps]/i,/\b(?:sony)?sgp\w+(?: bui|\))/i],[[u,"Xperia Tablet"],[f,oe],[h,y]],[/ (kb2005|in20[12]5|be20[12][59])\b/i,/(?:one)?(?:plus)? (a\d0\d\d)(?: b|\))/i],[u,[f,"OnePlus"],[h,b]],[/(alexa)webm/i,/(kf[a-z]{2}wi|aeo(?!bc)\w\w)( bui|\))/i,/(kf[a-z]+)( bui|\)).+silk\//i],[u,[f,K],[h,y]],[/((?:sd|kf)[0349hijorstuw]+)( bui|\)).+silk\//i],[[u,/(.+)/g,"Fire Phone $1"],[f,K],[h,b]],[/(playbook);[-\w\),; ]+(rim)/i],[u,f,[h,y]],[/\b((?:bb[a-f]|st[hv])100-\d)/i,/\(bb10; (\w+)/i],[u,[f,Q],[h,b]],[/(?:\b|asus_)(transfo[prime ]{4,10} \w+|eeepc|slider \w+|nexus 7|padfone|p00[cj])/i],[u,[f,X],[h,y]],[/ (z[bes]6[027][012][km][ls]|zenfone \d\w?)\b/i],[u,[f,X],[h,b]],[/(nexus 9)/i],[u,[f,"HTC"],[h,y]],[/(htc)[-;_ ]{1,2}([\w ]+(?=\)| bui)|\w+)/i,/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,/(alcatel|geeksphone|nexian|panasonic(?!(?:;|\.))|sony(?!-bra))[-_ ]?([-\w]*)/i],[f,[u,/_/g," "],[h,b]],[/tcl (xess p17aa)/i,/droid [\w\.]+; ((?:8[14]9[16]|9(?:0(?:48|60|8[01])|1(?:3[27]|66)|2(?:6[69]|9[56])|466))[gqswx])(_\w(\w|\w\w))?(\)| bui)/i],[u,[f,"TCL"],[h,y]],[/droid [\w\.]+; (418(?:7d|8v)|5087z|5102l|61(?:02[dh]|25[adfh]|27[ai]|56[dh]|59k|65[ah])|a509dl|t(?:43(?:0w|1[adepqu])|50(?:6d|7[adju])|6(?:09dl|10k|12b|71[efho]|76[hjk])|7(?:66[ahju]|67[hw]|7[045][bh]|71[hk]|73o|76[ho]|79w|81[hks]?|82h|90[bhsy]|99b)|810[hs]))(_\w(\w|\w\w))?(\)| bui)/i],[u,[f,"TCL"],[h,b]],[/(itel) ((\w+))/i],[[f,Te],u,[h,Me,{tablet:["p10001l","w7001"],"*":"mobile"}]],[/droid.+; ([ab][1-7]-?[0178a]\d\d?)/i],[u,[f,"Acer"],[h,y]],[/droid.+; (m[1-5] note) bui/i,/\bmz-([-\w]{2,})/i],[u,[f,"Meizu"],[h,b]],[/; ((?:power )?armor(?:[\w ]{0,8}))(?: bui|\))/i],[u,[f,"Ulefone"],[h,b]],[/; (energy ?\w+)(?: bui|\))/i,/; energizer ([\w ]+)(?: bui|\))/i],[u,[f,"Energizer"],[h,b]],[/; cat (b35);/i,/; (b15q?|s22 flip|s48c|s62 pro)(?: bui|\))/i],[u,[f,"Cat"],[h,b]],[/((?:new )?andromax[\w- ]+)(?: bui|\))/i],[u,[f,"Smartfren"],[h,b]],[/droid.+; (a(?:015|06[35]|142p?))/i],[u,[f,"Nothing"],[h,b]],[/(blackberry|benq|palm(?=\-)|sonyericsson|acer|asus|dell|meizu|motorola|polytron|infinix|tecno|micromax|advan)[-_ ]?([-\w]*)/i,/; (imo) ((?!tab)[\w ]+?)(?: bui|\))/i,/(hp) ([\w ]+\w)/i,/(asus)-?(\w+)/i,/(microsoft); (lumia[\w ]+)/i,/(lenovo)[-_ ]?([-\w]+)/i,/(jolla)/i,/(oppo) ?([\w ]+) bui/i],[f,u,[h,b]],[/(imo) (tab \w+)/i,/(kobo)\s(ereader|touch)/i,/(archos) (gamepad2?)/i,/(hp).+(touchpad(?!.+tablet)|tablet)/i,/(kindle)\/([\w\.]+)/i],[f,u,[h,y]],[/(surface duo)/i],[u,[f,re],[h,y]],[/droid [\d\.]+; (fp\du?)(?: b|\))/i],[u,[f,"Fairphone"],[h,b]],[/(shield[\w ]+) b/i],[u,[f,"Nvidia"],[h,y]],[/(sprint) (\w+)/i],[f,u,[h,b]],[/(kin\.[onetw]{3})/i],[[u,/\./g," "],[f,re],[h,b]],[/droid.+; ([c6]+|et5[16]|mc[239][23]x?|vc8[03]x?)\)/i],[u,[f,ce],[h,y]],[/droid.+; (ec30|ps20|tc[2-8]\d[kx])\)/i],[u,[f,ce],[h,b]],[/smart-tv.+(samsung)/i],[f,[h,w]],[/hbbtv.+maple;(\d+)/i],[[u,/^/,"SmartTV"],[f,ne],[h,w]],[/(nux; netcast.+smarttv|lg (netcast\.tv-201\d|android tv))/i],[[f,te],[h,w]],[/(apple) ?tv/i],[f,[u,J+" TV"],[h,w]],[/crkey.*devicetype\/chromecast/i],[[u,pe+" Third Generation"],[f,Z],[h,w]],[/crkey.*devicetype\/([^/]*)/i],[[u,/^/,"Chromecast "],[f,Z],[h,w]],[/fuchsia.*crkey/i],[[u,pe+" Nest Hub"],[f,Z],[h,w]],[/crkey/i],[[u,pe],[f,Z],[h,w]],[/droid.+aft(\w+)( bui|\))/i],[u,[f,K],[h,w]],[/\(dtv[\);].+(aquos)/i,/(aquos-tv[\w ]+)\)/i],[u,[f,se],[h,w]],[/(bravia[\w ]+)( bui|\))/i],[u,[f,oe],[h,w]],[/(mitv-\w{5}) bui/i],[u,[f,ae],[h,w]],[/Hbbtv.*(technisat) (.*);/i],[f,u,[h,w]],[/\b(roku)[\dx]*[\)\/]((?:dvp-)?[\d\.]*)/i,/hbbtv\/\d+\.\d+\.\d+ +\([\w\+ ]*; *([\w\d][^;]*);([^;]*)/i],[[f,Ie],[u,Ie],[h,w]],[/\b(android tv|smart[- ]?tv|opera tv|tv; rv:)\b/i],[[h,w]],[/(ouya)/i,/(nintendo) (\w+)/i],[f,u,[h,v]],[/droid.+; (shield) bui/i],[u,[f,"Nvidia"],[h,v]],[/(playstation \w+)/i],[u,[f,oe],[h,v]],[/\b(xbox(?: one)?(?!; xbox))[\); ]/i],[u,[f,re],[h,v]],[/\b(sm-[lr]\d\d[05][fnuw]?s?)\b/i],[u,[f,ne],[h,_]],[/((pebble))app/i],[f,u,[h,_]],[/(watch)(?: ?os[,\/]|\d,\d\/)[\d\.]+/i],[u,[f,J],[h,_]],[/droid.+; (wt63?0{2,3})\)/i],[u,[f,ce],[h,_]],[/droid.+; (glass) \d/i],[u,[f,Z],[h,S]],[/(pico) (4|neo3(?: link|pro)?)/i],[f,u,[h,S]],[/; (quest( \d| pro)?)/i],[u,[f,me],[h,S]],[/(tesla)(?: qtcarbrowser|\/[-\w\.]+)/i],[f,[h,C]],[/(aeobc)\b/i],[u,[f,K],[h,C]],[/droid .+?; ([^;]+?)(?: bui|; wv\)|\) applew).+? mobile safari/i],[u,[h,b]],[/droid .+?; ([^;]+?)(?: bui|\) applew).+?(?! mobile) safari/i],[u,[h,y]],[/\b((tablet|tab)[;\/]|focus\/\d(?!.+mobile))/i],[[h,y]],[/(phone|mobile(?:[;\/]| [ \w\/\.]*safari)|pda(?=.+windows ce))/i],[[h,b]],[/(android[-\w\. ]{0,9});.+buil/i],[u,[f,"Generic"]]],engine:[[/windows.+ edge\/([\w\.]+)/i],[m,[p,"EdgeHTML"]],[/(arkweb)\/([\w\.]+)/i],[p,m],[/webkit\/537\.36.+chrome\/(?!27)([\w\.]+)/i],[m,[p,"Blink"]],[/(presto)\/([\w\.]+)/i,/(webkit|trident|netfront|netsurf|amaya|lynx|w3m|goanna|servo)\/([\w\.]+)/i,/ekioh(flow)\/([\w\.]+)/i,/(khtml|tasman|links)[\/ ]\(?([\w\.]+)/i,/(icab)[\/ ]([23]\.[\d\.]+)/i,/\b(libweb)/i],[p,m],[/rv\:([\w\.]{1,9})\b.+(gecko)/i],[m,p]],os:[[/microsoft (windows) (vista|xp)/i],[p,m],[/(windows (?:phone(?: os)?|mobile))[\/ ]?([\d\.\w ]*)/i],[p,[m,Me,je]],[/windows nt 6\.2; (arm)/i,/windows[\/ ]?([ntce\d\. ]+\w)(?!.+xbox)/i,/(?:win(?=3|9|n)|win 9x )([nt\d\.]+)/i],[[m,Me,je],[p,ve]],[/ip[honead]{2,4}\b(?:.*os ([\w]+) like mac|; opera)/i,/(?:ios;fbsv\/|iphone.+ios[\/ ])([\d\.]+)/i,/cfnetwork\/.+darwin/i],[[m,/_/g,"."],[p,"iOS"]],[/(mac os x) ?([\w\. ]*)/i,/(macintosh|mac_powerpc\b)(?!.+haiku)/i],[[p,"macOS"],[m,/_/g,"."]],[/android ([\d\.]+).*crkey/i],[m,[p,pe+" Android"]],[/fuchsia.*crkey\/([\d\.]+)/i],[m,[p,pe+" Fuchsia"]],[/crkey\/([\d\.]+).*devicetype\/smartspeaker/i],[m,[p,pe+" SmartSpeaker"]],[/linux.*crkey\/([\d\.]+)/i],[m,[p,pe+" Linux"]],[/crkey\/([\d\.]+)/i],[m,[p,pe]],[/droid ([\w\.]+)\b.+(android[- ]x86|harmonyos)/i],[m,p],[/(android|webos|qnx|bada|rim tablet os|maemo|meego|sailfish|openharmony)[-\/ ]?([\w\.]*)/i,/(blackberry)\w*\/([\w\.]*)/i,/(tizen|kaios)[\/ ]([\w\.]+)/i,/\((series40);/i],[p,m],[/\(bb(10);/i],[m,[p,Q]],[/(?:symbian ?os|symbos|s60(?=;)|series60)[-\/ ]?([\w\.]*)/i],[m,[p,"Symbian"]],[/mozilla\/[\d\.]+ \((?:mobile|tablet|tv|mobile; [\w ]+); rv:.+ gecko\/([\w\.]+)/i],[m,[p,he+" OS"]],[/web0s;.+rt(tv)/i,/\b(?:hp)?wos(?:browser)?\/([\w\.]+)/i],[m,[p,"webOS"]],[/watch(?: ?os[,\/]|\d,\d\/)([\d\.]+)/i],[m,[p,"watchOS"]],[/(cros) [\w]+(?:\)| ([\w\.]+)\b)/i],[[p,"Chrome OS"],m],[/panasonic;(viera)/i,/(netrange)mmh/i,/(nettv)\/(\d+\.[\w\.]+)/i,/(nintendo|playstation) (\w+)/i,/(xbox); +xbox ([^\);]+)/i,/(pico) .+os([\w\.]+)/i,/\b(joli|palm)\b ?(?:os)?\/?([\w\.]*)/i,/(mint)[\/\(\) ]?(\w*)/i,/(mageia|vectorlinux)[; ]/i,/([kxln]?ubuntu|debian|suse|opensuse|gentoo|arch(?= linux)|slackware|fedora|mandriva|centos|pclinuxos|red ?hat|zenwalk|linpus|raspbian|plan 9|minix|risc os|contiki|deepin|manjaro|elementary os|sabayon|linspire)(?: gnu\/linux)?(?: enterprise)?(?:[- ]linux)?(?:-gnu)?[-\/ ]?(?!chrom|package)([-\w\.]*)/i,/(hurd|linux) ?([\w\.]*)/i,/(gnu) ?([\w\.]*)/i,/\b([-frentopcghs]{0,5}bsd|dragonfly)[\/ ]?(?!amd|[ix346]{1,2}86)([\w\.]*)/i,/(haiku) (\w+)/i],[p,m],[/(sunos) ?([\w\.\d]*)/i],[[p,"Solaris"],m],[/((?:open)?solaris)[-\/ ]?([\w\.]*)/i,/(aix) ((\d)(?=\.|\)| )[\w\.])*/i,/\b(beos|os\/2|amigaos|morphos|openvms|fuchsia|hp-ux|serenityos)/i,/(unix) ?([\w\.]*)/i],[p,m]]},Ne=(n={init:{},isIgnore:{},isIgnoreRgx:{},toString:{}},Oe.call(n.init,[[U,[p,m,l,h]],[$,[g]],[G,[h,u,f]],[q,[p,m]],[H,[p,m]]]),Oe.call(n.isIgnore,[[U,[m,l]],[q,[m]],[H,[m]]]),Oe.call(n.isIgnoreRgx,[[U,/ ?browser$/i],[H,/ ?os$/i]]),Oe.call(n.toString,[[U,[p,m]],[$,[g]],[G,[f,u]],[q,[p,m]],[H,[p,m]]]),n),Be=function(e,t){var r=Ne.init[t],i=Ne.isIgnore[t]||0,n=Ne.isIgnoreRgx[t]||0,o=Ne.toString[t]||0;function c(){Oe.call(this,r)}return c.prototype.getItem=function(){return e},c.prototype.withClientHints=function(){return we?we.getHighEntropyValues(V).then((function(t){return e.setCH(new Fe(t,!1)).parseCH().get()})):e.parseCH().get()},c.prototype.withFeatureCheck=function(){return e.detectFeature().get()},t!=W&&(c.prototype.is=function(e){var t=!1;for(var r in this)if(this.hasOwnProperty(r)&&!Se(i,r)&&Te(n?Ee(n,this[r]):this[r])==Te(n?Ee(n,e):e)){if(t=!0,e!=a)break}else if(e==a&&t){t=!t;break}return t},c.prototype.toString=function(){var e=s;for(var t in o)typeof this[o[t]]!==a&&(e+=(e?" ":s)+this[o[t]]);return e||a}),we||(c.prototype.then=function(e){var t=this,r=function(){for(var e in t)t.hasOwnProperty(e)&&(this[e]=t[e])};r.prototype={is:c.prototype.is,toString:c.prototype.toString};var i=new r;return e(i),i}),new c};function Fe(e,t){if(e=e||{},Oe.call(this,V),t)Oe.call(this,[[T,ke(e[x])],[O,ke(e[M])],[b,/\?1/.test(e[N])],[u,De(e[B])],[E,De(e[F])],[D,De(e[z])],[g,De(e[j])],[P,ke(e[A])],[I,De(e[L])]]);else for(var r in e)this.hasOwnProperty(r)&&typeof e[r]!==a&&(this[r]=e[r])}function ze(e,t,r,n){return this.get=function(e){return e?this.data.hasOwnProperty(e)?this.data[e]:i:this.data},this.set=function(e,t){return this.data[e]=t,this},this.setCH=function(e){return this.uaCH=e,this},this.detectFeature=function(){if(ye&&ye.userAgent==this.ua)switch(this.itemType){case U:ye.brave&&typeof ye.brave.isBrave==o&&this.set(p,"Brave");break;case G:!this.get(h)&&we&&we[b]&&this.set(h,b),"Macintosh"==this.get(u)&&ye&&typeof ye.standalone!==a&&ye.maxTouchPoints&&ye.maxTouchPoints>2&&this.set(u,"iPad").set(h,y);break;case H:!this.get(p)&&we&&we[E]&&this.set(p,we[E]);break;case W:var e=this.data,t=function(t){return e[t].getItem().detectFeature().get()};this.set(U,t(U)).set($,t($)).set(G,t(G)).set(q,t(q)).set(H,t(H))}return this},this.parseUA=function(){return this.itemType!=W&&xe.call(this.data,this.ua,this.rgxMap),this.itemType==U&&this.set(l,Pe(this.get(m))),this},this.parseCH=function(){var e=this.uaCH,t=this.rgxMap;switch(this.itemType){case U:var r,n=e[O]||e[T];if(n)for(var s in n){var o=Ee(/(Google|Microsoft) /,n[s].brand||n[s]),a=n[s].version;/not.a.brand/i.test(o)||r&&(!/chrom/i.test(r)||/chromi/i.test(o))||(this.set(p,o).set(m,a).set(l,Pe(a)),r=o)}break;case $:var c=e[g];c&&(c&&"64"==e[I]&&(c+="64"),xe.call(this.data,c+";",t));break;case G:if(e[b]&&this.set(h,b),e[u]&&this.set(u,e[u]),"Xbox"==e[u]&&this.set(h,v).set(f,re),e[P]){var d;if("string"!=typeof e[P])for(var y=0;!d&&y<e[P].length;)d=Me(e[P][y++],Le);else d=Me(e[P],Le);this.set(h,d)}break;case H:var w=e[E];if(w){var _=e[D];w==ve&&(_=parseInt(Pe(_),10)>=13?"11":"10"),this.set(p,w).set(m,_)}this.get(p)==ve&&"Xbox"==e[u]&&this.set(p,"Xbox").set(m,i);break;case W:var S=this.data,C=function(t){return S[t].getItem().setCH(e).parseCH().get()};this.set(U,C(U)).set($,C($)).set(G,C(G)).set(q,C(q)).set(H,C(H))}return this},Oe.call(this,[["itemType",e],["ua",t],["uaCH",n],["rgxMap",r],["data",Be(this,e)]]),this}function Ve(e,t,r){if(typeof e===c?(Ce(e,!0)?(typeof t===c&&(r=t),t=e):(r=e,t=i),e=i):typeof e!==d||Ce(t,!0)||(r=t,t=i),r&&typeof r.append===o){var n={};r.forEach((function(e,t){n[t]=e})),r=n}if(!(this instanceof Ve))return new Ve(e,t,r).getResult();var a=typeof e===d?e:r&&r[k]?r[k]:ye&&ye.userAgent?ye.userAgent:s,l=new Fe(r,!0),u=t?function(e,t){var r={},i=t;if(!Ce(t))for(var n in i={},t)for(var s in t[n])i[s]=t[n][s].concat(i[s]?i[s]:[]);for(var o in e)r[o]=i[o]&&i[o].length%2==0?i[o].concat(e[o]):e[o];return r}(Ae,t):Ae,p=function(e){return e==W?function(){return new ze(e,a,u,l).set("ua",a).set(U,this.getBrowser()).set($,this.getCPU()).set(G,this.getDevice()).set(q,this.getEngine()).set(H,this.getOS()).get()}:function(){return new ze(e,a,u[e],l).parseUA().get()}};return Oe.call(this,[["getBrowser",p(U)],["getCPU",p($)],["getDevice",p(G)],["getEngine",p(q)],["getOS",p(H)],["getResult",p(W)],["getUA",function(){return a}],["setUA",function(e){return Re(e)&&(a=e.length>500?Ie(e,500):e),this}]]).setUA(a),this}Ve.VERSION="2.0.0",Ve.BROWSER=_e([p,m,l,h]),Ve.CPU=_e([g]),Ve.DEVICE=_e([u,f,h,v,b,w,y,_,C]),Ve.ENGINE=Ve.OS=_e([p,m]),e.exports&&(t=e.exports=Ve),t.UAParser=Ve;var Ue=be&&(r.jQuery||r.Zepto);if(Ue&&!Ue.ua){var $e=new Ve;Ue.ua=$e.getResult(),Ue.ua.get=function(){return $e.getUA()},Ue.ua.set=function(e){$e.setUA(e);var t=$e.getResult();for(var r in t)Ue.ua[r]=t[r]}}}("object"==typeof window?window:a)}(is,is.exports);var ns=is.exports,ss={},os=a&&a.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(ss,"__esModule",{value:!0});var as=ss.Logger=void 0;const cs=os(ts),ds="mediasoup-client";as=ss.Logger=class{constructor(e){e?(this._debug=(0,cs.default)(`${ds}:${e}`),this._warn=(0,cs.default)(`${ds}:WARN:${e}`),this._error=(0,cs.default)(`${ds}:ERROR:${e}`)):(this._debug=(0,cs.default)(ds),this._warn=(0,cs.default)(`${ds}:WARN`),this._error=(0,cs.default)(`${ds}:ERROR`)),this._debug.log=console.info.bind(console),this._warn.log=console.warn.bind(console),this._error.log=console.error.bind(console)}get debug(){return this._debug}get warn(){return this._warn}get error(){return this._error}};var ls,us={},ps={exports:{}},hs="object"==typeof Reflect?Reflect:null,fs=hs&&"function"==typeof hs.apply?hs.apply:function(e,t,r){return Function.prototype.apply.call(e,t,r)};ls=hs&&"function"==typeof hs.ownKeys?hs.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var ms=Number.isNaN||function(e){return e!=e};function gs(){gs.init.call(this)}ps.exports=gs,ps.exports.once=function(e,t){return new Promise((function(r,i){function n(r){e.removeListener(t,s),i(r)}function s(){"function"==typeof e.removeListener&&e.removeListener("error",n),r([].slice.call(arguments))}Ts(e,t,s,{once:!0}),"error"!==t&&function(e,t,r){"function"==typeof e.on&&Ts(e,"error",t,r)}(e,n,{once:!0})}))},gs.EventEmitter=gs,gs.prototype._events=void 0,gs.prototype._eventsCount=0,gs.prototype._maxListeners=void 0;var vs=10;function bs(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function ys(e){return void 0===e._maxListeners?gs.defaultMaxListeners:e._maxListeners}function ws(e,t,r,i){var n,s,o;if(bs(r),void 0===(s=e._events)?(s=e._events=Object.create(null),e._eventsCount=0):(void 0!==s.newListener&&(e.emit("newListener",t,r.listener?r.listener:r),s=e._events),o=s[t]),void 0===o)o=s[t]=r,++e._eventsCount;else if("function"==typeof o?o=s[t]=i?[r,o]:[o,r]:i?o.unshift(r):o.push(r),(n=ys(e))>0&&o.length>n&&!o.warned){o.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");a.name="MaxListenersExceededWarning",a.emitter=e,a.type=t,a.count=o.length,function(e){console&&console.warn&&console.warn(e)}(a)}return e}function _s(){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 Ss(e,t,r){var i={fired:!1,wrapFn:void 0,target:e,type:t,listener:r},n=_s.bind(i);return n.listener=r,i.wrapFn=n,n}function Cs(e,t,r){var i=e._events;if(void 0===i)return[];var n=i[t];return void 0===n?[]:"function"==typeof n?r?[n.listener||n]:[n]:r?function(e){for(var t=new Array(e.length),r=0;r<t.length;++r)t[r]=e[r].listener||e[r];return t}(n):ks(n,n.length)}function Rs(e){var t=this._events;if(void 0!==t){var r=t[e];if("function"==typeof r)return 1;if(void 0!==r)return r.length}return 0}function ks(e,t){for(var r=new Array(t),i=0;i<t;++i)r[i]=e[i];return r}function Ts(e,t,r,i){if("function"==typeof e.on)i.once?e.once(t,r):e.on(t,r);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 n(s){i.once&&e.removeEventListener(t,n),r(s)}))}}Object.defineProperty(gs,"defaultMaxListeners",{enumerable:!0,get:function(){return vs},set:function(e){if("number"!=typeof e||e<0||ms(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");vs=e}}),gs.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},gs.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||ms(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},gs.prototype.getMaxListeners=function(){return ys(this)},gs.prototype.emit=function(e){for(var t=[],r=1;r<arguments.length;r++)t.push(arguments[r]);var i="error"===e,n=this._events;if(void 0!==n)i=i&&void 0===n.error;else if(!i)return!1;if(i){var s;if(t.length>0&&(s=t[0]),s instanceof Error)throw s;var o=new Error("Unhandled error."+(s?" ("+s.message+")":""));throw o.context=s,o}var a=n[e];if(void 0===a)return!1;if("function"==typeof a)fs(a,this,t);else{var c=a.length,d=ks(a,c);for(r=0;r<c;++r)fs(d[r],this,t)}return!0},gs.prototype.addListener=function(e,t){return ws(this,e,t,!1)},gs.prototype.on=gs.prototype.addListener,gs.prototype.prependListener=function(e,t){return ws(this,e,t,!0)},gs.prototype.once=function(e,t){return bs(t),this.on(e,Ss(this,e,t)),this},gs.prototype.prependOnceListener=function(e,t){return bs(t),this.prependListener(e,Ss(this,e,t)),this},gs.prototype.removeListener=function(e,t){var r,i,n,s,o;if(bs(t),void 0===(i=this._events))return this;if(void 0===(r=i[e]))return this;if(r===t||r.listener===t)0==--this._eventsCount?this._events=Object.create(null):(delete i[e],i.removeListener&&this.emit("removeListener",e,r.listener||t));else if("function"!=typeof r){for(n=-1,s=r.length-1;s>=0;s--)if(r[s]===t||r[s].listener===t){o=r[s].listener,n=s;break}if(n<0)return this;0===n?r.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(r,n),1===r.length&&(i[e]=r[0]),void 0!==i.removeListener&&this.emit("removeListener",e,o||t)}return this},gs.prototype.off=gs.prototype.removeListener,gs.prototype.removeAllListeners=function(e){var t,r,i;if(void 0===(r=this._events))return this;if(void 0===r.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==r[e]&&(0==--this._eventsCount?this._events=Object.create(null):delete r[e]),this;if(0===arguments.length){var n,s=Object.keys(r);for(i=0;i<s.length;++i)"removeListener"!==(n=s[i])&&this.removeAllListeners(n);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=r[e]))this.removeListener(e,t);else if(void 0!==t)for(i=t.length-1;i>=0;i--)this.removeListener(e,t[i]);return this},gs.prototype.listeners=function(e){return Cs(this,e,!0)},gs.prototype.rawListeners=function(e){return Cs(this,e,!1)},gs.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):Rs.call(e,t)},gs.prototype.listenerCount=Rs,gs.prototype.eventNames=function(){return this._eventsCount>0?ls(this._events):[]};var Ps=ps.exports;Object.defineProperty(us,"__esModule",{value:!0}),us.EnhancedEventEmitter=void 0;const Os=Ps,Es=new ss.Logger("EnhancedEventEmitter");class Ds extends Os.EventEmitter{constructor(){super(),this.setMaxListeners(1/0)}emit(e,...t){return super.emit(e,...t)}safeEmit(e,...t){try{return super.emit(e,...t)}catch(t){Es.error("safeEmit() | event listener threw an error [eventName:%s]:%o",e,t);try{super.emit("listenererror",e,t)}catch(e){}return Boolean(super.listenerCount(e))}}on(e,t){return super.on(e,t),this}off(e,t){return super.off(e,t),this}addListener(e,t){return super.on(e,t),this}prependListener(e,t){return super.prependListener(e,t),this}once(e,t){return super.once(e,t),this}prependOnceListener(e,t){return super.prependOnceListener(e,t),this}removeListener(e,t){return super.off(e,t),this}removeAllListeners(e){return super.removeAllListeners(e),this}listenerCount(e){return super.listenerCount(e)}listeners(e){return super.listeners(e)}rawListeners(e){return super.rawListeners(e)}}us.EnhancedEventEmitter=Ds;var Is={};Object.defineProperty(Is,"__esModule",{value:!0});var xs=Is.InvalidStateError=Is.UnsupportedError=void 0;class Ms extends Error{constructor(e){super(e),this.name="UnsupportedError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,Ms):this.stack=new Error(e).stack}}Is.UnsupportedError=Ms;class js extends Error{constructor(e){super(e),this.name="InvalidStateError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,js):this.stack=new Error(e).stack}}xs=Is.InvalidStateError=js;var Ls={};Object.defineProperty(Ls,"__esModule",{value:!0});var As=Ls.clone=function(e){return void 0===e?void 0:Number.isNaN(e)?NaN:"function"==typeof structuredClone?structuredClone(e):JSON.parse(JSON.stringify(e))};Ls.generateRandomNumber=function(){return Math.round(1e7*Math.random())},Ls.deepFreeze=function e(t){const r=Reflect.ownKeys(t);for(const i of r){const r=t[i];(r&&"object"==typeof r||"function"==typeof r)&&e(r)}return Object.freeze(t)};var Ns,Bs,Fs={},zs={},Vs={},Us={exports:{}};function $s(){if(Bs)return Ns;Bs=1;var e=1e3,t=60*e,r=60*t,i=24*r,n=7*i,s=365.25*i;function o(e,t,r,i){var n=t>=1.5*r;return Math.round(e/r)+" "+i+(n?"s":"")}return Ns=function(a,c){c=c||{};var d=typeof a;if("string"===d&&a.length>0)return function(o){if((o=String(o)).length>100)return;var a=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(o);if(!a)return;var c=parseFloat(a[1]);switch((a[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return c*s;case"weeks":case"week":case"w":return c*n;case"days":case"day":case"d":return c*i;case"hours":case"hour":case"hrs":case"hr":case"h":return c*r;case"minutes":case"minute":case"mins":case"min":case"m":return c*t;case"seconds":case"second":case"secs":case"sec":case"s":return c*e;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return c;default:return}}(a);if("number"===d&&isFinite(a))return c.long?function(n){var s=Math.abs(n);if(s>=i)return o(n,s,i,"day");if(s>=r)return o(n,s,r,"hour");if(s>=t)return o(n,s,t,"minute");if(s>=e)return o(n,s,e,"second");return n+" ms"}(a):function(n){var s=Math.abs(n);if(s>=i)return Math.round(n/i)+"d";if(s>=r)return Math.round(n/r)+"h";if(s>=t)return Math.round(n/t)+"m";if(s>=e)return Math.round(n/e)+"s";return n+"ms"}(a);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(a))},Ns}var Gs=function(e){function t(e){let i,n,s,o=null;function a(...e){if(!a.enabled)return;const r=a,n=Number(new Date),s=n-(i||n);r.diff=s,r.prev=i,r.curr=n,i=n,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let o=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,((i,n)=>{if("%%"===i)return"%";o++;const s=t.formatters[n];if("function"==typeof s){const t=e[o];i=s.call(r,t),e.splice(o,1),o--}return i})),t.formatArgs.call(r,e);(r.log||t.log).apply(r,e)}return a.namespace=e,a.useColors=t.useColors(),a.color=t.selectColor(e),a.extend=r,a.destroy=t.destroy,Object.defineProperty(a,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==o?o:(n!==t.namespaces&&(n=t.namespaces,s=t.enabled(e)),s),set:e=>{o=e}}),"function"==typeof t.init&&t.init(a),a}function r(e,r){const i=t(this.namespace+(void 0===r?":":r)+e);return i.log=this.log,i}function i(e){return e.toString().substring(2,e.toString().length-2).replace(/\.\*\?$/,"*")}return t.debug=t,t.default=t,t.coerce=function(e){if(e instanceof Error)return e.stack||e.message;return e},t.disable=function(){const e=[...t.names.map(i),...t.skips.map(i).map((e=>"-"+e))].join(",");return t.enable(""),e},t.enable=function(e){let r;t.save(e),t.namespaces=e,t.names=[],t.skips=[];const i=("string"==typeof e?e:"").split(/[\s,]+/),n=i.length;for(r=0;r<n;r++)i[r]&&("-"===(e=i[r].replace(/\*/g,".*?"))[0]?t.skips.push(new RegExp("^"+e.slice(1)+"$")):t.names.push(new RegExp("^"+e+"$")))},t.enabled=function(e){if("*"===e[e.length-1])return!0;let r,i;for(r=0,i=t.skips.length;r<i;r++)if(t.skips[r].test(e))return!1;for(r=0,i=t.names.length;r<i;r++)if(t.names[r].test(e))return!0;return!1},t.humanize=$s(),t.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(e).forEach((r=>{t[r]=e[r]})),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let r=0;for(let t=0;t<e.length;t++)r=(r<<5)-r+e.charCodeAt(t),r|=0;return t.colors[Math.abs(r)%t.colors.length]},t.enable(t.load()),t};!function(e,t){t.formatArgs=function(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;const r="color: "+this.color;t.splice(1,0,r,"color: inherit");let i=0,n=0;t[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(i++,"%c"===e&&(n=i))})),t.splice(n,0,r)},t.save=function(e){try{e?t.storage.setItem("debug",e):t.storage.removeItem("debug")}catch(e){}},t.load=function(){let e;try{e=t.storage.getItem("debug")}catch(e){}!e&&"undefined"!=typeof process&&"env"in process&&(e=process.env.DEBUG);return e},t.useColors=function(){if("undefined"!=typeof window&&window.process&&("renderer"===window.process.type||window.process.__nwjs))return!0;if("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;return"undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},t.storage=function(){try{return localStorage}catch(e){}}(),t.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],t.log=console.debug||console.log||(()=>{}),e.exports=Gs(t);const{formatters:r}=e.exports;r.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}(Us,Us.exports);var qs=Us.exports,Hs=a&&a.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Vs,"__esModule",{value:!0}),Vs.Logger=void 0;const Ws=Hs(qs),Ks="h264-profile-level-id";Vs.Logger=class{constructor(e){e?(this._debug=(0,Ws.default)(`${Ks}:${e}`),this._warn=(0,Ws.default)(`${Ks}:WARN:${e}`),this._error=(0,Ws.default)(`${Ks}:ERROR:${e}`)):(this._debug=(0,Ws.default)(Ks),this._warn=(0,Ws.default)(`${Ks}:WARN`),this._error=(0,Ws.default)(`${Ks}:ERROR`)),this._debug.log=console.info.bind(console),this._warn.log=console.warn.bind(console),this._error.log=console.error.bind(console)}get debug(){return this._debug}get warn(){return this._warn}get error(){return this._error}},Object.defineProperty(zs,"__esModule",{value:!0}),zs.generateProfileLevelIdStringForAnswer=zs.isSameProfile=zs.parseSdpProfileLevelId=zs.levelToString=zs.profileToString=zs.profileLevelIdToString=zs.parseProfileLevelId=zs.ProfileLevelId=zs.Level=zs.Profile=void 0;const Js=new Vs.Logger;var Xs,Qs;!function(e){e[e.ConstrainedBaseline=1]="ConstrainedBaseline",e[e.Baseline=2]="Baseline",e[e.Main=3]="Main",e[e.ConstrainedHigh=4]="ConstrainedHigh",e[e.High=5]="High",e[e.PredictiveHigh444=6]="PredictiveHigh444"}(Xs||(zs.Profile=Xs={})),function(e){e[e.L1_b=0]="L1_b",e[e.L1=10]="L1",e[e.L1_1=11]="L1_1",e[e.L1_2=12]="L1_2",e[e.L1_3=13]="L1_3",e[e.L2=20]="L2",e[e.L2_1=21]="L2_1",e[e.L2_2=22]="L2_2",e[e.L3=30]="L3",e[e.L3_1=31]="L3_1",e[e.L3_2=32]="L3_2",e[e.L4=40]="L4",e[e.L4_1=41]="L4_1",e[e.L4_2=42]="L4_2",e[e.L5=50]="L5",e[e.L5_1=51]="L5_1",e[e.L5_2=52]="L5_2"}(Qs||(zs.Level=Qs={}));class Zs{constructor(e,t){this.profile=e,this.level=t}}zs.ProfileLevelId=Zs;const Ys=new Zs(Xs.ConstrainedBaseline,Qs.L3_1);class eo{constructor(e){this.mask=~oo("x",e),this.masked_value=oo("1",e)}isMatch(e){return this.masked_value===(e&this.mask)}}class to{constructor(e,t,r){this.profile_idc=e,this.profile_iop=t,this.profile=r}}const ro=[new to(66,new eo("x1xx0000"),Xs.ConstrainedBaseline),new to(77,new eo("1xxx0000"),Xs.ConstrainedBaseline),new to(88,new eo("11xx0000"),Xs.ConstrainedBaseline),new to(66,new eo("x0xx0000"),Xs.Baseline),new to(88,new eo("10xx0000"),Xs.Baseline),new to(77,new eo("0x0x0000"),Xs.Main),new to(100,new eo("00000000"),Xs.High),new to(100,new eo("00001100"),Xs.ConstrainedHigh),new to(244,new eo("00000000"),Xs.PredictiveHigh444)];function io(e){if("string"!=typeof e||6!==e.length)return;const t=parseInt(e,16);if(0===t)return;const r=255&t,i=t>>8&255,n=t>>16&255;let s;switch(r){case Qs.L1_1:s=0!=(16&i)?Qs.L1_b:Qs.L1_1;break;case Qs.L1:case Qs.L1_2:case Qs.L1_3:case Qs.L2:case Qs.L2_1:case Qs.L2_2:case Qs.L3:case Qs.L3_1:case Qs.L3_2:case Qs.L4:case Qs.L4_1:case Qs.L4_2:case Qs.L5:case Qs.L5_1:case Qs.L5_2:s=r;break;default:return void Js.warn(`parseProfileLevelId() | unrecognized level_idc [str:${e}, level_idc:${r}]`)}for(const e of ro)if(n===e.profile_idc&&e.profile_iop.isMatch(i))return new Zs(e.profile,s);Js.warn(`parseProfileLevelId() | unrecognized profile_idc/profile_iop combination [str:${e}, profile_idc:${n}, profile_iop:${i}]`)}function no(e){if(e.level==Qs.L1_b)switch(e.profile){case Xs.ConstrainedBaseline:return"42f00b";case Xs.Baseline:return"42100b";case Xs.Main:return"4d100b";default:return void Js.warn(`profileLevelIdToString() | Level 1_b not is allowed for profile ${e.profile}`)}let t;switch(e.profile){case Xs.ConstrainedBaseline:t="42e0";break;case Xs.Baseline:t="4200";break;case Xs.Main:t="4d00";break;case Xs.ConstrainedHigh:t="640c";break;case Xs.High:t="6400";break;case Xs.PredictiveHigh444:t="f400";break;default:return void Js.warn(`profileLevelIdToString() | unrecognized profile ${e.profile}`)}let r=e.level.toString(16);return 1===r.length&&(r=`0${r}`),`${t}${r}`}function so(e={}){const t=e["profile-level-id"];return t?io(t):Ys}function oo(e,t){return Number(t[0]===e)<<7|Number(t[1]===e)<<6|Number(t[2]===e)<<5|Number(t[3]===e)<<4|Number(t[4]===e)<<3|Number(t[5]===e)<<2|Number(t[6]===e)<<1|Number(t[7]===e)<<0}function ao(e={}){const t=e["level-asymmetry-allowed"];return!0===t||1===t||"1"===t}zs.parseProfileLevelId=io,zs.profileLevelIdToString=no,zs.profileToString=function(e){switch(e){case Xs.ConstrainedBaseline:return"ConstrainedBaseline";case Xs.Baseline:return"Baseline";case Xs.Main:return"Main";case Xs.ConstrainedHigh:return"ConstrainedHigh";case Xs.High:return"High";case Xs.PredictiveHigh444:return"PredictiveHigh444";default:return void Js.warn(`profileToString() | unrecognized profile ${e}`)}},zs.levelToString=function(e){switch(e){case Qs.L1_b:return"1b";case Qs.L1:return"1";case Qs.L1_1:return"1.1";case Qs.L1_2:return"1.2";case Qs.L1_3:return"1.3";case Qs.L2:return"2";case Qs.L2_1:return"2.1";case Qs.L2_2:return"2.2";case Qs.L3:return"3";case Qs.L3_1:return"3.1";case Qs.L3_2:return"3.2";case Qs.L4:return"4";case Qs.L4_1:return"4.1";case Qs.L4_2:return"4.2";case Qs.L5:return"5";case Qs.L5_1:return"5.1";case Qs.L5_2:return"5.2";default:return void Js.warn(`levelToString() | unrecognized level ${e}`)}},zs.parseSdpProfileLevelId=so,zs.isSameProfile=function(e={},t={}){const r=so(e),i=so(t);return Boolean(r&&i&&r.profile===i.profile)},zs.generateProfileLevelIdStringForAnswer=function(e={},t={}){if(!e["profile-level-id"]&&!t["profile-level-id"])return void Js.warn("generateProfileLevelIdStringForAnswer() | profile-level-id missing in local and remote params");const r=so(e),i=so(t);if(!r)throw new TypeError("invalid local_profile_level_id");if(!i)throw new TypeError("invalid remote_profile_level_id");if(r.profile!==i.profile)throw new TypeError("H264 Profile mismatch");const n=ao(e)&&ao(t),s=r.level,o=i.level,a=function(e,t){return e===Qs.L1_b?t!==Qs.L1&&t!==Qs.L1_b:t===Qs.L1_b?e!==Qs.L1:e<t}(c=s,d=o)?c:d;var c,d;const l=n?s:a;return Js.debug(`generateProfileLevelIdStringForAnswer() | result [profile:${r.profile}, level:${l}]`),no(new Zs(r.profile,l))};var co,lo=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),uo=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),po=a&&a.__importStar||(co=function(e){return co=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},co(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r=co(e),i=0;i<r.length;i++)"default"!==r[i]&&lo(t,e,r[i]);return uo(t,e),t});Object.defineProperty(Fs,"__esModule",{value:!0}),Fs.validateRtpCapabilities=function(e){if("object"!=typeof e)throw new TypeError("caps is not an object");if(e.codecs&&!Array.isArray(e.codecs))throw new TypeError("caps.codecs is not an array");e.codecs||(e.codecs=[]);for(const t of e.codecs)So(t);if(e.headerExtensions&&!Array.isArray(e.headerExtensions))throw new TypeError("caps.headerExtensions is not an array");e.headerExtensions||(e.headerExtensions=[]);for(const t of e.headerExtensions)Ro(t)},Fs.validateRtpParameters=_o,Fs.validateSctpStreamParameters=function(e){if("object"!=typeof e)throw new TypeError("params is not an object");if("number"!=typeof e.streamId)throw new TypeError("missing params.streamId");let t=!1;"boolean"==typeof e.ordered?t=!0:e.ordered=!0;if(e.maxPacketLifeTime&&"number"!=typeof e.maxPacketLifeTime)throw new TypeError("invalid params.maxPacketLifeTime");if(e.maxRetransmits&&"number"!=typeof e.maxRetransmits)throw new TypeError("invalid params.maxRetransmits");if(e.maxPacketLifeTime&&e.maxRetransmits)throw new TypeError("cannot provide both maxPacketLifeTime and maxRetransmits");if(t&&e.ordered&&(e.maxPacketLifeTime||e.maxRetransmits))throw new TypeError("cannot be ordered with maxPacketLifeTime or maxRetransmits");t||!e.maxPacketLifeTime&&!e.maxRetransmits||(e.ordered=!1);if(e.label&&"string"!=typeof e.label)throw new TypeError("invalid params.label");if(e.protocol&&"string"!=typeof e.protocol)throw new TypeError("invalid params.protocol")},Fs.validateSctpCapabilities=function(e){if("object"!=typeof e)throw new TypeError("caps is not an object");if(!e.numStreams||"object"!=typeof e.numStreams)throw new TypeError("missing caps.numStreams");!function(e){if("object"!=typeof e)throw new TypeError("numStreams is not an object");if("number"!=typeof e.OS)throw new TypeError("missing numStreams.OS");if("number"!=typeof e.MIS)throw new TypeError("missing numStreams.MIS")}(e.numStreams)},Fs.getExtendedRtpCapabilities=function(e,t){const r={codecs:[],headerExtensions:[]};for(const i of t.codecs??[]){if(Oo(i))continue;const t=(e.codecs??[]).find((e=>Eo(e,i,{strict:!0,modify:!0})));if(!t)continue;const n={mimeType:t.mimeType,kind:t.kind,clockRate:t.clockRate,channels:t.channels,localPayloadType:t.preferredPayloadType,localRtxPayloadType:void 0,remotePayloadType:i.preferredPayloadType,remoteRtxPayloadType:void 0,localParameters:t.parameters,remoteParameters:i.parameters,rtcpFeedback:Io(t,i)};r.codecs.push(n)}for(const i of r.codecs){const r=e.codecs.find((e=>Oo(e)&&e.parameters.apt===i.localPayloadType)),n=t.codecs.find((e=>Oo(e)&&e.parameters.apt===i.remotePayloadType));r&&n&&(i.localRtxPayloadType=r.preferredPayloadType,i.remoteRtxPayloadType=n.preferredPayloadType)}for(const i of t.headerExtensions){const t=e.headerExtensions.find((e=>Do(e,i)));if(!t)continue;const n={kind:i.kind,uri:i.uri,sendId:t.preferredId,recvId:i.preferredId,encrypt:t.preferredEncrypt,direction:"sendrecv"};switch(i.direction){case"sendrecv":n.direction="sendrecv";break;case"recvonly":n.direction="sendonly";break;case"sendonly":n.direction="recvonly";break;case"inactive":n.direction="inactive"}r.headerExtensions.push(n)}return r},Fs.getRecvRtpCapabilities=function(e){const t={codecs:[],headerExtensions:[]};for(const r of e.codecs){const e={mimeType:r.mimeType,kind:r.kind,preferredPayloadType:r.remotePayloadType,clockRate:r.clockRate,channels:r.channels,parameters:r.localParameters,rtcpFeedback:r.rtcpFeedback};if(t.codecs.push(e),!r.remoteRtxPayloadType)continue;const i={mimeType:`${r.kind}/rtx`,kind:r.kind,preferredPayloadType:r.remoteRtxPayloadType,clockRate:r.clockRate,parameters:{apt:r.remotePayloadType},rtcpFeedback:[]};t.codecs.push(i)}for(const r of e.headerExtensions){if("sendrecv"!==r.direction&&"recvonly"!==r.direction)continue;const e={kind:r.kind,uri:r.uri,preferredId:r.recvId,preferredEncrypt:r.encrypt,direction:r.direction};t.headerExtensions.push(e)}return t};var ho=Fs.getSendingRtpParameters=function(e,t){const r={mid:void 0,codecs:[],headerExtensions:[],encodings:[],rtcp:{}};for(const i of t.codecs){if(i.kind!==e)continue;const t={mimeType:i.mimeType,payloadType:i.localPayloadType,clockRate:i.clockRate,channels:i.channels,parameters:i.localParameters,rtcpFeedback:i.rtcpFeedback};if(r.codecs.push(t),i.localRtxPayloadType){const e={mimeType:`${i.kind}/rtx`,payloadType:i.localRtxPayloadType,clockRate:i.clockRate,parameters:{apt:i.localPayloadType},rtcpFeedback:[]};r.codecs.push(e)}}for(const i of t.headerExtensions){if(i.kind&&i.kind!==e||"sendrecv"!==i.direction&&"sendonly"!==i.direction)continue;const t={uri:i.uri,id:i.sendId,encrypt:i.encrypt,parameters:{}};r.headerExtensions.push(t)}return r},fo=Fs.getSendingRemoteRtpParameters=function(e,t){const r={mid:void 0,codecs:[],headerExtensions:[],encodings:[],rtcp:{}};for(const i of t.codecs){if(i.kind!==e)continue;const t={mimeType:i.mimeType,payloadType:i.localPayloadType,clockRate:i.clockRate,channels:i.channels,parameters:i.remoteParameters,rtcpFeedback:i.rtcpFeedback};if(r.codecs.push(t),i.localRtxPayloadType){const e={mimeType:`${i.kind}/rtx`,payloadType:i.localRtxPayloadType,clockRate:i.clockRate,parameters:{apt:i.localPayloadType},rtcpFeedback:[]};r.codecs.push(e)}}for(const i of t.headerExtensions){if(i.kind&&i.kind!==e||"sendrecv"!==i.direction&&"sendonly"!==i.direction)continue;const t={uri:i.uri,id:i.sendId,encrypt:i.encrypt,parameters:{}};r.headerExtensions.push(t)}if(r.headerExtensions.some((e=>"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01"===e.uri)))for(const e of r.codecs)e.rtcpFeedback=(e.rtcpFeedback??[]).filter((e=>"goog-remb"!==e.type));else if(r.headerExtensions.some((e=>"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time"===e.uri)))for(const e of r.codecs)e.rtcpFeedback=(e.rtcpFeedback??[]).filter((e=>"transport-cc"!==e.type));else for(const e of r.codecs)e.rtcpFeedback=(e.rtcpFeedback??[]).filter((e=>"transport-cc"!==e.type&&"goog-remb"!==e.type));return r},mo=Fs.reduceCodecs=function(e,t){const r=[];if(t){for(let i=0;i<e.length;++i)if(Eo(e[i],t,{strict:!0})){r.push(e[i]),Oo(e[i+1])&&r.push(e[i+1]);break}if(0===r.length)throw new TypeError("no matching codec found")}else r.push(e[0]),Oo(e[1])&&r.push(e[1]);return r};Fs.generateProbatorRtpParameters=function(e){_o(e=vo.clone(e));const t={mid:bo,codecs:[],headerExtensions:[],encodings:[{ssrc:yo}],rtcp:{cname:"probator"}};return t.codecs.push(e.codecs[0]),t.codecs[0].payloadType=wo,t.headerExtensions=e.headerExtensions,t},Fs.canSend=function(e,t){return t.codecs.some((t=>t.kind===e))},Fs.canReceive=function(e,t){if(_o(e),0===e.codecs.length)return!1;const r=e.codecs[0];return t.codecs.some((e=>e.remotePayloadType===r.payloadType))};const go=po(zs),vo=po(Ls),bo="probator",yo=1234,wo=127;function _o(e){if("object"!=typeof e)throw new TypeError("params is not an object");if(e.mid&&"string"!=typeof e.mid)throw new TypeError("params.mid is not a string");if(!Array.isArray(e.codecs))throw new TypeError("missing params.codecs");for(const t of e.codecs)ko(t);if(e.headerExtensions&&!Array.isArray(e.headerExtensions))throw new TypeError("params.headerExtensions is not an array");e.headerExtensions||(e.headerExtensions=[]);for(const t of e.headerExtensions)To(t);if(e.encodings&&!Array.isArray(e.encodings))throw new TypeError("params.encodings is not an array");e.encodings||(e.encodings=[]);for(const t of e.encodings)Po(t);if(e.rtcp&&"object"!=typeof e.rtcp)throw new TypeError("params.rtcp is not an object");e.rtcp||(e.rtcp={}),function(e){if("object"!=typeof e)throw new TypeError("rtcp is not an object");if(e.cname&&"string"!=typeof e.cname)throw new TypeError("invalid rtcp.cname");e.reducedSize&&"boolean"==typeof e.reducedSize||(e.reducedSize=!0)}(e.rtcp)}function So(e){const t=new RegExp("^(audio|video)/(.+)","i");if("object"!=typeof e)throw new TypeError("codec is not an object");if(!e.mimeType||"string"!=typeof e.mimeType)throw new TypeError("missing codec.mimeType");const r=t.exec(e.mimeType);if(!r)throw new TypeError("invalid codec.mimeType");if(e.kind=r[1].toLowerCase(),e.preferredPayloadType&&"number"!=typeof e.preferredPayloadType)throw new TypeError("invalid codec.preferredPayloadType");if("number"!=typeof e.clockRate)throw new TypeError("missing codec.clockRate");"audio"===e.kind?"number"!=typeof e.channels&&(e.channels=1):delete e.channels,e.parameters&&"object"==typeof e.parameters||(e.parameters={});for(const t of Object.keys(e.parameters)){let r=e.parameters[t];if(void 0===r&&(e.parameters[t]="",r=""),"string"!=typeof r&&"number"!=typeof r)throw new TypeError(`invalid codec parameter [key:${t}s, value:${r}]`);if("apt"===t&&"number"!=typeof r)throw new TypeError("invalid codec apt parameter")}e.rtcpFeedback&&Array.isArray(e.rtcpFeedback)||(e.rtcpFeedback=[]);for(const t of e.rtcpFeedback)Co(t)}function Co(e){if("object"!=typeof e)throw new TypeError("fb is not an object");if(!e.type||"string"!=typeof e.type)throw new TypeError("missing fb.type");e.parameter&&"string"==typeof e.parameter||(e.parameter="")}function Ro(e){if("object"!=typeof e)throw new TypeError("ext is not an object");if("audio"!==e.kind&&"video"!==e.kind)throw new TypeError("invalid ext.kind");if(!e.uri||"string"!=typeof e.uri)throw new TypeError("missing ext.uri");if("number"!=typeof e.preferredId)throw new TypeError("missing ext.preferredId");if(e.preferredEncrypt&&"boolean"!=typeof e.preferredEncrypt)throw new TypeError("invalid ext.preferredEncrypt");if(e.preferredEncrypt||(e.preferredEncrypt=!1),e.direction&&"string"!=typeof e.direction)throw new TypeError("invalid ext.direction");e.direction||(e.direction="sendrecv")}function ko(e){const t=new RegExp("^(audio|video)/(.+)","i");if("object"!=typeof e)throw new TypeError("codec is not an object");if(!e.mimeType||"string"!=typeof e.mimeType)throw new TypeError("missing codec.mimeType");const r=t.exec(e.mimeType);if(!r)throw new TypeError("invalid codec.mimeType");if("number"!=typeof e.payloadType)throw new TypeError("missing codec.payloadType");if("number"!=typeof e.clockRate)throw new TypeError("missing codec.clockRate");"audio"===r[1].toLowerCase()?"number"!=typeof e.channels&&(e.channels=1):delete e.channels,e.parameters&&"object"==typeof e.parameters||(e.parameters={});for(const t of Object.keys(e.parameters)){let r=e.parameters[t];if(void 0===r&&(e.parameters[t]="",r=""),"string"!=typeof r&&"number"!=typeof r)throw new TypeError(`invalid codec parameter [key:${t}s, value:${r}]`);if("apt"===t&&"number"!=typeof r)throw new TypeError("invalid codec apt parameter")}e.rtcpFeedback&&Array.isArray(e.rtcpFeedback)||(e.rtcpFeedback=[]);for(const t of e.rtcpFeedback)Co(t)}function To(e){if("object"!=typeof e)throw new TypeError("ext is not an object");if(!e.uri||"string"!=typeof e.uri)throw new TypeError("missing ext.uri");if("number"!=typeof e.id)throw new TypeError("missing ext.id");if(e.encrypt&&"boolean"!=typeof e.encrypt)throw new TypeError("invalid ext.encrypt");e.encrypt||(e.encrypt=!1),e.parameters&&"object"==typeof e.parameters||(e.parameters={});for(const t of Object.keys(e.parameters)){let r=e.parameters[t];if(void 0===r&&(e.parameters[t]="",r=""),"string"!=typeof r&&"number"!=typeof r)throw new TypeError("invalid header extension parameter")}}function Po(e){if("object"!=typeof e)throw new TypeError("encoding is not an object");if(e.ssrc&&"number"!=typeof e.ssrc)throw new TypeError("invalid encoding.ssrc");if(e.rid&&"string"!=typeof e.rid)throw new TypeError("invalid encoding.rid");if(e.rtx&&"object"!=typeof e.rtx)throw new TypeError("invalid encoding.rtx");if(e.rtx&&"number"!=typeof e.rtx.ssrc)throw new TypeError("missing encoding.rtx.ssrc");if(e.dtx&&"boolean"==typeof e.dtx||(e.dtx=!1),e.scalabilityMode&&"string"!=typeof e.scalabilityMode)throw new TypeError("invalid encoding.scalabilityMode")}function Oo(e){return!!e&&/.+\/rtx$/i.test(e.mimeType)}function Eo(e,t,{strict:r=!1,modify:i=!1}={}){const n=e.mimeType.toLowerCase();if(n!==t.mimeType.toLowerCase())return!1;if(e.clockRate!==t.clockRate)return!1;if(e.channels!==t.channels)return!1;switch(n){case"video/h264":if(r){if((e.parameters["packetization-mode"]||0)!==(t.parameters["packetization-mode"]||0))return!1;if(!go.isSameProfile(e.parameters,t.parameters))return!1;let r;try{r=go.generateProfileLevelIdStringForAnswer(e.parameters,t.parameters)}catch(e){return!1}i&&(r?(e.parameters["profile-level-id"]=r,t.parameters["profile-level-id"]=r):(delete e.parameters["profile-level-id"],delete t.parameters["profile-level-id"]))}break;case"video/vp9":if(r){if((e.parameters["profile-id"]||0)!==(t.parameters["profile-id"]||0))return!1}}return!0}function Do(e,t){return(!e.kind||!t.kind||e.kind===t.kind)&&e.uri===t.uri}function Io(e,t){const r=[];for(const i of e.rtcpFeedback??[]){const e=(t.rtcpFeedback??[]).find((e=>e.type===i.type&&(e.parameter===i.parameter||!e.parameter&&!i.parameter)));e&&r.push(e)}return r}var xo={},Mo={},jo={};Object.defineProperty(jo,"__esModule",{value:!0}),jo.Logger=void 0;const Lo=qs,Ao="awaitqueue";jo.Logger=class{constructor(e){e?(this._debug=(0,Lo.default)(`${Ao}:${e}`),this._warn=(0,Lo.default)(`${Ao}:WARN:${e}`),this._error=(0,Lo.default)(`${Ao}:ERROR:${e}`)):(this._debug=(0,Lo.default)(Ao),this._warn=(0,Lo.default)(`${Ao}:WARN`),this._error=(0,Lo.default)(`${Ao}:ERROR`)),this._debug.log=console.info.bind(console),this._warn.log=console.warn.bind(console),this._error.log=console.error.bind(console)}get debug(){return this._debug}get warn(){return this._warn}get error(){return this._error}},Object.defineProperty(Mo,"__esModule",{value:!0}),Mo.AwaitQueue=Mo.AwaitQueueRemovedTaskError=Mo.AwaitQueueStoppedError=void 0;const No=new jo.Logger;class Bo extends Error{constructor(e){super(e??"AwaitQueue stopped"),this.name="AwaitQueueStoppedError","function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,Bo)}}Mo.AwaitQueueStoppedError=Bo;class Fo extends Error{constructor(e){super(e??"AwaitQueue task removed"),this.name="AwaitQueueRemovedTaskError","function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,Fo)}}Mo.AwaitQueueRemovedTaskError=Fo;
|
|
2
2
|
/*! queue-microtask. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
|
|
3
|
-
let zo;Mo.AwaitQueue=class{constructor(){this.pendingTasks=new Map,this.nextTaskId=0,this.stopping=!1}get size(){return this.pendingTasks.size}async push(e,t){if(t=t??e.name,No.debug(`push() [name:${t}]`),"function"!=typeof e)throw new TypeError("given task is not a function");if(t)try{Object.defineProperty(e,"name",{value:t})}catch(e){}return new Promise(((r,i)=>{const n={id:this.nextTaskId++,task:e,name:t,enqueuedAt:Date.now(),executedAt:void 0,completed:!1,resolve:e=>{if(n.completed)return;n.completed=!0,this.pendingTasks.delete(n.id),No.debug(`resolving task [name:${n.name}]`),r(e);const[t]=this.pendingTasks.values();t&&!t.executedAt&&this.execute(t)},reject:e=>{if(!n.completed&&(n.completed=!0,this.pendingTasks.delete(n.id),No.debug(`rejecting task [name:${n.name}]: %s`,String(e)),i(e),!this.stopping)){const[e]=this.pendingTasks.values();e&&!e.executedAt&&this.execute(e)}}};this.pendingTasks.set(n.id,n),1===this.pendingTasks.size&&this.execute(n)}))}stop(){No.debug("stop()"),this.stopping=!0;for(const e of this.pendingTasks.values())No.debug(`stop() | stopping task [name:${e.name}]`),e.reject(new Bo);this.stopping=!1}remove(e){No.debug(`remove() [taskIdx:${e}]`);const t=Array.from(this.pendingTasks.values())[e];t?t.reject(new Fo):No.debug(`stop() | no task with given idx [taskIdx:${e}]`)}dump(){const e=Date.now();let t=0;return Array.from(this.pendingTasks.values()).map((r=>({idx:t++,task:r.task,name:r.name,enqueuedTime:r.executedAt?r.executedAt-r.enqueuedAt:e-r.enqueuedAt,executionTime:r.executedAt?e-r.executedAt:0})))}async execute(e){if(No.debug(`execute() [name:${e.name}]`),e.executedAt)throw new Error("task already being executed");e.executedAt=Date.now();try{const t=await e.task();e.resolve(t)}catch(t){e.reject(t)}}};var Vo="function"==typeof queueMicrotask?queueMicrotask.bind("undefined"!=typeof window?window:a):e=>(zo||(zo=Promise.resolve())).then(e).catch((e=>setTimeout((()=>{throw e}),0))),Uo={};Object.defineProperty(Uo,"__esModule",{value:!0}),Uo.Producer=void 0;const $o=us,Go=Is,qo=new ss.Logger("Producer");class Ho extends $o.EnhancedEventEmitter{constructor({id:e,localId:t,rtpSender:r,track:i,rtpParameters:n,stopTracks:s,disableTrackOnPause:o,zeroRtpOnPause:a,appData:c}){super(),this._closed=!1,this._observer=new $o.EnhancedEventEmitter,qo.debug("constructor()"),this._id=e,this._localId=t,this._rtpSender=r,this._track=i,this._kind=i.kind,this._rtpParameters=n,this._paused=!!o&&!i.enabled,this._maxSpatialLayer=void 0,this._stopTracks=s,this._disableTrackOnPause=o,this._zeroRtpOnPause=a,this._appData=c??{},this.onTrackEnded=this.onTrackEnded.bind(this),this.handleTrack()}get id(){return this._id}get localId(){return this._localId}get closed(){return this._closed}get kind(){return this._kind}get rtpSender(){return this._rtpSender}get track(){return this._track}get rtpParameters(){return this._rtpParameters}get paused(){return this._paused}get maxSpatialLayer(){return this._maxSpatialLayer}get appData(){return this._appData}set appData(e){this._appData=e}get observer(){return this._observer}close(){this._closed||(qo.debug("close()"),this._closed=!0,this.destroyTrack(),this.emit("@close"),this._observer.safeEmit("close"))}transportClosed(){this._closed||(qo.debug("transportClosed()"),this._closed=!0,this.destroyTrack(),this.safeEmit("transportclose"),this._observer.safeEmit("close"))}async getStats(){if(this._closed)throw new Go.InvalidStateError("closed");return new Promise(((e,t)=>{this.safeEmit("@getstats",e,t)}))}pause(){qo.debug("pause()"),this._closed?qo.error("pause() | Producer closed"):(this._paused=!0,this._track&&this._disableTrackOnPause&&(this._track.enabled=!1),this._zeroRtpOnPause&&new Promise(((e,t)=>{this.safeEmit("@pause",e,t)})).catch((()=>{})),this._observer.safeEmit("pause"))}resume(){qo.debug("resume()"),this._closed?qo.error("resume() | Producer closed"):(this._paused=!1,this._track&&this._disableTrackOnPause&&(this._track.enabled=!0),this._zeroRtpOnPause&&new Promise(((e,t)=>{this.safeEmit("@resume",e,t)})).catch((()=>{})),this._observer.safeEmit("resume"))}async replaceTrack({track:e}){if(qo.debug("replaceTrack() [track:%o]",e),this._closed){if(e&&this._stopTracks)try{e.stop()}catch(e){}throw new Go.InvalidStateError("closed")}if(e&&"ended"===e.readyState)throw new Go.InvalidStateError("track ended");e!==this._track?(await new Promise(((t,r)=>{this.safeEmit("@replacetrack",e,t,r)})),this.destroyTrack(),this._track=e,this._track&&this._disableTrackOnPause&&(this._paused?this._paused&&(this._track.enabled=!1):this._track.enabled=!0),this.handleTrack()):qo.debug("replaceTrack() | same track, ignored")}async setMaxSpatialLayer(e){if(this._closed)throw new Go.InvalidStateError("closed");if("video"!==this._kind)throw new Go.UnsupportedError("not a video Producer");if("number"!=typeof e)throw new TypeError("invalid spatialLayer");e!==this._maxSpatialLayer&&(await new Promise(((t,r)=>{this.safeEmit("@setmaxspatiallayer",e,t,r)})).catch((()=>{})),this._maxSpatialLayer=e)}async setRtpEncodingParameters(e){if(this._closed)throw new Go.InvalidStateError("closed");if("object"!=typeof e)throw new TypeError("invalid params");await new Promise(((t,r)=>{this.safeEmit("@setrtpencodingparameters",e,t,r)}))}onTrackEnded(){qo.debug('track "ended" event'),this.safeEmit("trackended"),this._observer.safeEmit("trackended")}handleTrack(){this._track&&this._track.addEventListener("ended",this.onTrackEnded)}destroyTrack(){if(this._track)try{this._track.removeEventListener("ended",this.onTrackEnded),this._stopTracks&&this._track.stop()}catch(e){}}}Uo.Producer=Ho;var Wo={};Object.defineProperty(Wo,"__esModule",{value:!0}),Wo.Consumer=void 0;const Ko=us,Jo=Is,Xo=new ss.Logger("Consumer");class Qo extends Ko.EnhancedEventEmitter{constructor({id:e,localId:t,producerId:r,rtpReceiver:i,track:n,rtpParameters:s,appData:o}){super(),this._closed=!1,this._observer=new Ko.EnhancedEventEmitter,Xo.debug("constructor()"),this._id=e,this._localId=t,this._producerId=r,this._rtpReceiver=i,this._track=n,this._rtpParameters=s,this._paused=!n.enabled,this._appData=o??{},this.onTrackEnded=this.onTrackEnded.bind(this),this.handleTrack()}get id(){return this._id}get localId(){return this._localId}get producerId(){return this._producerId}get closed(){return this._closed}get kind(){return this._track.kind}get rtpReceiver(){return this._rtpReceiver}get track(){return this._track}get rtpParameters(){return this._rtpParameters}get paused(){return this._paused}get appData(){return this._appData}set appData(e){this._appData=e}get observer(){return this._observer}close(){this._closed||(Xo.debug("close()"),this._closed=!0,this.destroyTrack(),this.emit("@close"),this._observer.safeEmit("close"))}transportClosed(){this._closed||(Xo.debug("transportClosed()"),this._closed=!0,this.destroyTrack(),this.safeEmit("transportclose"),this._observer.safeEmit("close"))}async getStats(){if(this._closed)throw new Jo.InvalidStateError("closed");return new Promise(((e,t)=>{this.safeEmit("@getstats",e,t)}))}pause(){Xo.debug("pause()"),this._closed?Xo.error("pause() | Consumer closed"):this._paused?Xo.debug("pause() | Consumer is already paused"):(this._paused=!0,this._track.enabled=!1,this.emit("@pause"),this._observer.safeEmit("pause"))}resume(){Xo.debug("resume()"),this._closed?Xo.error("resume() | Consumer closed"):this._paused?(this._paused=!1,this._track.enabled=!0,this.emit("@resume"),this._observer.safeEmit("resume")):Xo.debug("resume() | Consumer is already resumed")}onTrackEnded(){Xo.debug('track "ended" event'),this.safeEmit("trackended"),this._observer.safeEmit("trackended")}handleTrack(){this._track.addEventListener("ended",this.onTrackEnded)}destroyTrack(){try{this._track.removeEventListener("ended",this.onTrackEnded),this._track.stop()}catch(e){}}}Wo.Consumer=Qo;var Zo={};Object.defineProperty(Zo,"__esModule",{value:!0}),Zo.DataProducer=void 0;const Yo=us,ea=Is,ta=new ss.Logger("DataProducer");class ra extends Yo.EnhancedEventEmitter{constructor({id:e,dataChannel:t,sctpStreamParameters:r,appData:i}){super(),this._closed=!1,this._observer=new Yo.EnhancedEventEmitter,ta.debug("constructor()"),this._id=e,this._dataChannel=t,this._sctpStreamParameters=r,this._appData=i??{},this.handleDataChannel()}get id(){return this._id}get closed(){return this._closed}get sctpStreamParameters(){return this._sctpStreamParameters}get readyState(){return this._dataChannel.readyState}get label(){return this._dataChannel.label}get protocol(){return this._dataChannel.protocol}get bufferedAmount(){return this._dataChannel.bufferedAmount}get bufferedAmountLowThreshold(){return this._dataChannel.bufferedAmountLowThreshold}set bufferedAmountLowThreshold(e){this._dataChannel.bufferedAmountLowThreshold=e}get appData(){return this._appData}set appData(e){this._appData=e}get observer(){return this._observer}close(){this._closed||(ta.debug("close()"),this._closed=!0,this._dataChannel.close(),this.emit("@close"),this._observer.safeEmit("close"))}transportClosed(){this._closed||(ta.debug("transportClosed()"),this._closed=!0,this._dataChannel.close(),this.safeEmit("transportclose"),this._observer.safeEmit("close"))}send(e){if(ta.debug("send()"),this._closed)throw new ea.InvalidStateError("closed");this._dataChannel.send(e)}handleDataChannel(){this._dataChannel.addEventListener("open",(()=>{this._closed||(ta.debug('DataChannel "open" event'),this.safeEmit("open"))})),this._dataChannel.addEventListener("error",(e=>{if(this._closed)return;let{error:t}=e;t||(t=new Error("unknown DataChannel error")),"sctp-failure"===t.errorDetail?ta.error("DataChannel SCTP error [sctpCauseCode:%s]: %s",t.sctpCauseCode,t.message):ta.error('DataChannel "error" event: %o',t),this.safeEmit("error",t)})),this._dataChannel.addEventListener("close",(()=>{this._closed||(ta.warn('DataChannel "close" event'),this._closed=!0,this.emit("@close"),this.safeEmit("close"),this._observer.safeEmit("close"))})),this._dataChannel.addEventListener("message",(()=>{this._closed||ta.warn('DataChannel "message" event in a DataProducer, message discarded')})),this._dataChannel.addEventListener("bufferedamountlow",(()=>{this._closed||this.safeEmit("bufferedamountlow")}))}}Zo.DataProducer=ra;var ia={};Object.defineProperty(ia,"__esModule",{value:!0}),ia.DataConsumer=void 0;const na=us,sa=new ss.Logger("DataConsumer");class oa extends na.EnhancedEventEmitter{constructor({id:e,dataProducerId:t,dataChannel:r,sctpStreamParameters:i,appData:n}){super(),this._closed=!1,this._observer=new na.EnhancedEventEmitter,sa.debug("constructor()"),this._id=e,this._dataProducerId=t,this._dataChannel=r,this._sctpStreamParameters=i,this._appData=n??{},this.handleDataChannel()}get id(){return this._id}get dataProducerId(){return this._dataProducerId}get closed(){return this._closed}get sctpStreamParameters(){return this._sctpStreamParameters}get readyState(){return this._dataChannel.readyState}get label(){return this._dataChannel.label}get protocol(){return this._dataChannel.protocol}get binaryType(){return this._dataChannel.binaryType}set binaryType(e){this._dataChannel.binaryType=e}get appData(){return this._appData}set appData(e){this._appData=e}get observer(){return this._observer}close(){this._closed||(sa.debug("close()"),this._closed=!0,this._dataChannel.close(),this.emit("@close"),this._observer.safeEmit("close"))}transportClosed(){this._closed||(sa.debug("transportClosed()"),this._closed=!0,this._dataChannel.close(),this.safeEmit("transportclose"),this._observer.safeEmit("close"))}handleDataChannel(){this._dataChannel.addEventListener("open",(()=>{this._closed||(sa.debug('DataChannel "open" event'),this.safeEmit("open"))})),this._dataChannel.addEventListener("error",(e=>{if(this._closed)return;let{error:t}=e;t||(t=new Error("unknown DataChannel error")),"sctp-failure"===t.errorDetail?sa.error("DataChannel SCTP error [sctpCauseCode:%s]: %s",t.sctpCauseCode,t.message):sa.error('DataChannel "error" event: %o',t),this.safeEmit("error",t)})),this._dataChannel.addEventListener("close",(()=>{this._closed||(sa.warn('DataChannel "close" event'),this._closed=!0,this.emit("@close"),this.safeEmit("close"),this._observer.safeEmit("close"))})),this._dataChannel.addEventListener("message",(e=>{this._closed||this.safeEmit("message",e.data)}))}}ia.DataConsumer=oa;var aa=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),ca=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),da=a&&a.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(null!=t)for(var i=e(t),n=0;n<i.length;n++)"default"!==i[n]&&aa(r,t,i[n]);return ca(r,t),r}}(),la=a&&a.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(xo,"__esModule",{value:!0}),xo.Transport=void 0;const ua=Mo,pa=la(Vo),ha=ss,fa=us,ma=Is,ga=da(js),va=da(Fs),ba=Uo,ya=Wo,wa=Zo,_a=ia,Sa=new ha.Logger("Transport");class Ca{constructor(e){this.consumerOptions=e,this.promise=new Promise(((e,t)=>{this.resolve=e,this.reject=t}))}}let Ra=class extends fa.EnhancedEventEmitter{constructor({direction:e,id:t,iceParameters:r,iceCandidates:i,dtlsParameters:n,sctpParameters:s,iceServers:o,iceTransportPolicy:a,additionalSettings:c,proprietaryConstraints:d,appData:l,handlerFactory:u,extendedRtpCapabilities:p,canProduceByKind:h}){super(),this._closed=!1,this._iceGatheringState="new",this._connectionState="new",this._producers=new Map,this._consumers=new Map,this._dataProducers=new Map,this._dataConsumers=new Map,this._probatorConsumerCreated=!1,this._awaitQueue=new ua.AwaitQueue,this._pendingConsumerTasks=[],this._consumerCreationInProgress=!1,this._pendingPauseConsumers=new Map,this._consumerPauseInProgress=!1,this._pendingResumeConsumers=new Map,this._consumerResumeInProgress=!1,this._pendingCloseConsumers=new Map,this._consumerCloseInProgress=!1,this._observer=new fa.EnhancedEventEmitter,Sa.debug("constructor() [id:%s, direction:%s]",t,e),this._id=t,this._direction=e,this._extendedRtpCapabilities=p,this._canProduceByKind=h,this._maxSctpMessageSize=s?s.maxMessageSize:null;const f=ga.clone(c)??{};delete f.iceServers,delete f.iceTransportPolicy,delete f.bundlePolicy,delete f.rtcpMuxPolicy,delete f.sdpSemantics,this._handler=u(),this._handler.run({direction:e,iceParameters:r,iceCandidates:i,dtlsParameters:n,sctpParameters:s,iceServers:o,iceTransportPolicy:a,additionalSettings:f,proprietaryConstraints:d,extendedRtpCapabilities:p}),this._appData=l??{},this.handleHandler()}get id(){return this._id}get closed(){return this._closed}get direction(){return this._direction}get handler(){return this._handler}get iceGatheringState(){return this._iceGatheringState}get connectionState(){return this._connectionState}get appData(){return this._appData}set appData(e){this._appData=e}get observer(){return this._observer}close(){if(!this._closed){Sa.debug("close()"),this._closed=!0,this._awaitQueue.stop(),this._handler.close(),this._connectionState="closed";for(const e of this._producers.values())e.transportClosed();this._producers.clear();for(const e of this._consumers.values())e.transportClosed();this._consumers.clear();for(const e of this._dataProducers.values())e.transportClosed();this._dataProducers.clear();for(const e of this._dataConsumers.values())e.transportClosed();this._dataConsumers.clear(),this._observer.safeEmit("close")}}async getStats(){if(this._closed)throw new ma.InvalidStateError("closed");return this._handler.getTransportStats()}async restartIce({iceParameters:e}){if(Sa.debug("restartIce()"),this._closed)throw new ma.InvalidStateError("closed");if(!e)throw new TypeError("missing iceParameters");return this._awaitQueue.push((async()=>await this._handler.restartIce(e)),"transport.restartIce()")}async updateIceServers({iceServers:e}={}){if(Sa.debug("updateIceServers()"),this._closed)throw new ma.InvalidStateError("closed");if(!Array.isArray(e))throw new TypeError("missing iceServers");return this._awaitQueue.push((async()=>this._handler.updateIceServers(e)),"transport.updateIceServers()")}async produce({track:e,encodings:t,codecOptions:r,codec:i,stopTracks:n=!0,disableTrackOnPause:s=!0,zeroRtpOnPause:o=!1,onRtpSender:a,appData:c={}}={}){if(Sa.debug("produce() [track:%o]",e),this._closed)throw new ma.InvalidStateError("closed");if(!e)throw new TypeError("missing track");if("send"!==this._direction)throw new ma.UnsupportedError("not a sending Transport");if(!this._canProduceByKind[e.kind])throw new ma.UnsupportedError(`cannot produce ${e.kind}`);if("ended"===e.readyState)throw new ma.InvalidStateError("track ended");if(0===this.listenerCount("connect")&&"new"===this._connectionState)throw new TypeError('no "connect" listener set into this transport');if(0===this.listenerCount("produce"))throw new TypeError('no "produce" listener set into this transport');if(c&&"object"!=typeof c)throw new TypeError("if given, appData must be an object");return this._awaitQueue.push((async()=>{let d;if(t&&!Array.isArray(t))throw TypeError("encodings must be an array");t&&0===t.length?d=void 0:t&&(d=t.map((e=>{const t={active:!0};return!1===e.active&&(t.active=!1),"boolean"==typeof e.dtx&&(t.dtx=e.dtx),"string"==typeof e.scalabilityMode&&(t.scalabilityMode=e.scalabilityMode),"number"==typeof e.scaleResolutionDownBy&&(t.scaleResolutionDownBy=e.scaleResolutionDownBy),"number"==typeof e.maxBitrate&&(t.maxBitrate=e.maxBitrate),"number"==typeof e.maxFramerate&&(t.maxFramerate=e.maxFramerate),"boolean"==typeof e.adaptivePtime&&(t.adaptivePtime=e.adaptivePtime),"string"==typeof e.priority&&(t.priority=e.priority),"string"==typeof e.networkPriority&&(t.networkPriority=e.networkPriority),t})));const{localId:l,rtpParameters:u,rtpSender:p}=await this._handler.send({track:e,encodings:d,codecOptions:r,codec:i,onRtpSender:a});try{va.validateRtpParameters(u);const{id:t}=await new Promise(((t,r)=>{this.safeEmit("produce",{kind:e.kind,rtpParameters:u,appData:c},t,r)})),r=new ba.Producer({id:t,localId:l,rtpSender:p,track:e,rtpParameters:u,stopTracks:n,disableTrackOnPause:s,zeroRtpOnPause:o,appData:c});return this._producers.set(r.id,r),this.handleProducer(r),this._observer.safeEmit("newproducer",r),r}catch(e){throw this._handler.stopSending(l).catch((()=>{})),e}}),"transport.produce()").catch((t=>{if(n)try{e.stop()}catch(e){}throw t}))}async consume({id:e,producerId:t,kind:r,rtpParameters:i,streamId:n,onRtpReceiver:s,appData:o={}}){if(Sa.debug("consume()"),this._closed)throw new ma.InvalidStateError("closed");if("recv"!==this._direction)throw new ma.UnsupportedError("not a receiving Transport");if("string"!=typeof e)throw new TypeError("missing id");if("string"!=typeof t)throw new TypeError("missing producerId");if("audio"!==r&&"video"!==r)throw new TypeError(`invalid kind '${r}'`);if(0===this.listenerCount("connect")&&"new"===this._connectionState)throw new TypeError('no "connect" listener set into this transport');if(o&&"object"!=typeof o)throw new TypeError("if given, appData must be an object");const a=ga.clone(i);if(!va.canReceive(a,this._extendedRtpCapabilities))throw new ma.UnsupportedError("cannot consume this Producer");const c=new Ca({id:e,producerId:t,kind:r,rtpParameters:a,streamId:n,onRtpReceiver:s,appData:o});return this._pendingConsumerTasks.push(c),(0,pa.default)((()=>{this._closed||!1===this._consumerCreationInProgress&&this.createPendingConsumers()})),c.promise}async produceData({ordered:e=!0,maxPacketLifeTime:t,maxRetransmits:r,label:i="",protocol:n="",appData:s={}}={}){if(Sa.debug("produceData()"),this._closed)throw new ma.InvalidStateError("closed");if("send"!==this._direction)throw new ma.UnsupportedError("not a sending Transport");if(!this._maxSctpMessageSize)throw new ma.UnsupportedError("SCTP not enabled by remote Transport");if(0===this.listenerCount("connect")&&"new"===this._connectionState)throw new TypeError('no "connect" listener set into this transport');if(0===this.listenerCount("producedata"))throw new TypeError('no "producedata" listener set into this transport');if(s&&"object"!=typeof s)throw new TypeError("if given, appData must be an object");return(t||r)&&(e=!1),this._awaitQueue.push((async()=>{const{dataChannel:o,sctpStreamParameters:a}=await this._handler.sendDataChannel({ordered:e,maxPacketLifeTime:t,maxRetransmits:r,label:i,protocol:n});va.validateSctpStreamParameters(a);const{id:c}=await new Promise(((e,t)=>{this.safeEmit("producedata",{sctpStreamParameters:a,label:i,protocol:n,appData:s},e,t)})),d=new wa.DataProducer({id:c,dataChannel:o,sctpStreamParameters:a,appData:s});return this._dataProducers.set(d.id,d),this.handleDataProducer(d),this._observer.safeEmit("newdataproducer",d),d}),"transport.produceData()")}async consumeData({id:e,dataProducerId:t,sctpStreamParameters:r,label:i="",protocol:n="",appData:s={}}){if(Sa.debug("consumeData()"),this._closed)throw new ma.InvalidStateError("closed");if("recv"!==this._direction)throw new ma.UnsupportedError("not a receiving Transport");if(!this._maxSctpMessageSize)throw new ma.UnsupportedError("SCTP not enabled by remote Transport");if("string"!=typeof e)throw new TypeError("missing id");if("string"!=typeof t)throw new TypeError("missing dataProducerId");if(0===this.listenerCount("connect")&&"new"===this._connectionState)throw new TypeError('no "connect" listener set into this transport');if(s&&"object"!=typeof s)throw new TypeError("if given, appData must be an object");const o=ga.clone(r);return va.validateSctpStreamParameters(o),this._awaitQueue.push((async()=>{const{dataChannel:r}=await this._handler.receiveDataChannel({sctpStreamParameters:o,label:i,protocol:n}),a=new _a.DataConsumer({id:e,dataProducerId:t,dataChannel:r,sctpStreamParameters:o,appData:s});return this._dataConsumers.set(a.id,a),this.handleDataConsumer(a),this._observer.safeEmit("newdataconsumer",a),a}),"transport.consumeData()")}async createPendingConsumers(){this._consumerCreationInProgress=!0,this._awaitQueue.push((async()=>{if(0===this._pendingConsumerTasks.length)return void Sa.debug("createPendingConsumers() | there is no Consumer to be created");const e=[...this._pendingConsumerTasks];let t;this._pendingConsumerTasks=[];const r=[];for(const t of e){const{id:e,kind:i,rtpParameters:n,streamId:s,onRtpReceiver:o}=t.consumerOptions;r.push({trackId:e,kind:i,rtpParameters:n,streamId:s,onRtpReceiver:o})}try{const i=await this._handler.receive(r);for(let r=0;r<i.length;++r){const n=e[r],s=i[r],{id:o,producerId:a,kind:c,rtpParameters:d,appData:l}=n.consumerOptions,{localId:u,rtpReceiver:p,track:h}=s,f=new ya.Consumer({id:o,localId:u,producerId:a,rtpReceiver:p,track:h,rtpParameters:d,appData:l});this._consumers.set(f.id,f),this.handleConsumer(f),this._probatorConsumerCreated||t||"video"!==c||(t=f),this._observer.safeEmit("newconsumer",f),n.resolve(f)}}catch(t){for(const r of e)r.reject(t)}if(t)try{const e=va.generateProbatorRtpParameters(t.rtpParameters);await this._handler.receive([{trackId:"probator",kind:"video",rtpParameters:e}]),Sa.debug("createPendingConsumers() | Consumer for RTP probation created"),this._probatorConsumerCreated=!0}catch(e){Sa.error("createPendingConsumers() | failed to create Consumer for RTP probation:%o",e)}}),"transport.createPendingConsumers()").then((()=>{this._consumerCreationInProgress=!1,this._pendingConsumerTasks.length>0&&this.createPendingConsumers()})).catch((()=>{}))}pausePendingConsumers(){this._consumerPauseInProgress=!0,this._awaitQueue.push((async()=>{if(0===this._pendingPauseConsumers.size)return void Sa.debug("pausePendingConsumers() | there is no Consumer to be paused");const e=Array.from(this._pendingPauseConsumers.values());this._pendingPauseConsumers.clear();try{const t=e.map((e=>e.localId));await this._handler.pauseReceiving(t)}catch(e){Sa.error("pausePendingConsumers() | failed to pause Consumers:",e)}}),"transport.pausePendingConsumers").then((()=>{this._consumerPauseInProgress=!1,this._pendingPauseConsumers.size>0&&this.pausePendingConsumers()})).catch((()=>{}))}resumePendingConsumers(){this._consumerResumeInProgress=!0,this._awaitQueue.push((async()=>{if(0===this._pendingResumeConsumers.size)return void Sa.debug("resumePendingConsumers() | there is no Consumer to be resumed");const e=Array.from(this._pendingResumeConsumers.values());this._pendingResumeConsumers.clear();try{const t=e.map((e=>e.localId));await this._handler.resumeReceiving(t)}catch(e){Sa.error("resumePendingConsumers() | failed to resume Consumers:",e)}}),"transport.resumePendingConsumers").then((()=>{this._consumerResumeInProgress=!1,this._pendingResumeConsumers.size>0&&this.resumePendingConsumers()})).catch((()=>{}))}closePendingConsumers(){this._consumerCloseInProgress=!0,this._awaitQueue.push((async()=>{if(0===this._pendingCloseConsumers.size)return void Sa.debug("closePendingConsumers() | there is no Consumer to be closed");const e=Array.from(this._pendingCloseConsumers.values());this._pendingCloseConsumers.clear();try{await this._handler.stopReceiving(e.map((e=>e.localId)))}catch(e){Sa.error("closePendingConsumers() | failed to close Consumers:",e)}}),"transport.closePendingConsumers").then((()=>{this._consumerCloseInProgress=!1,this._pendingCloseConsumers.size>0&&this.closePendingConsumers()})).catch((()=>{}))}handleHandler(){const e=this._handler;e.on("@connect",(({dtlsParameters:e},t,r)=>{this._closed?r(new ma.InvalidStateError("closed")):this.safeEmit("connect",{dtlsParameters:e},t,r)})),e.on("@icegatheringstatechange",(e=>{e!==this._iceGatheringState&&(Sa.debug("ICE gathering state changed to %s",e),this._iceGatheringState=e,this._closed||this.safeEmit("icegatheringstatechange",e))})),e.on("@connectionstatechange",(e=>{e!==this._connectionState&&(Sa.debug("connection state changed to %s",e),this._connectionState=e,this._closed||this.safeEmit("connectionstatechange",e))}))}handleProducer(e){e.on("@close",(()=>{this._producers.delete(e.id),this._closed||this._awaitQueue.push((async()=>await this._handler.stopSending(e.localId)),"producer @close event").catch((e=>Sa.warn("producer.close() failed:%o",e)))})),e.on("@pause",((t,r)=>{this._awaitQueue.push((async()=>await this._handler.pauseSending(e.localId)),"producer @pause event").then(t).catch(r)})),e.on("@resume",((t,r)=>{this._awaitQueue.push((async()=>await this._handler.resumeSending(e.localId)),"producer @resume event").then(t).catch(r)})),e.on("@replacetrack",((t,r,i)=>{this._awaitQueue.push((async()=>await this._handler.replaceTrack(e.localId,t)),"producer @replacetrack event").then(r).catch(i)})),e.on("@setmaxspatiallayer",((t,r,i)=>{this._awaitQueue.push((async()=>await this._handler.setMaxSpatialLayer(e.localId,t)),"producer @setmaxspatiallayer event").then(r).catch(i)})),e.on("@setrtpencodingparameters",((t,r,i)=>{this._awaitQueue.push((async()=>await this._handler.setRtpEncodingParameters(e.localId,t)),"producer @setrtpencodingparameters event").then(r).catch(i)})),e.on("@getstats",((t,r)=>{if(this._closed)return r(new ma.InvalidStateError("closed"));this._handler.getSenderStats(e.localId).then(t).catch(r)}))}handleConsumer(e){e.on("@close",(()=>{this._consumers.delete(e.id),this._pendingPauseConsumers.delete(e.id),this._pendingResumeConsumers.delete(e.id),this._closed||(this._pendingCloseConsumers.set(e.id,e),!1===this._consumerCloseInProgress&&this.closePendingConsumers())})),e.on("@pause",(()=>{this._pendingResumeConsumers.has(e.id)&&this._pendingResumeConsumers.delete(e.id),this._pendingPauseConsumers.set(e.id,e),(0,pa.default)((()=>{this._closed||!1===this._consumerPauseInProgress&&this.pausePendingConsumers()}))})),e.on("@resume",(()=>{this._pendingPauseConsumers.has(e.id)&&this._pendingPauseConsumers.delete(e.id),this._pendingResumeConsumers.set(e.id,e),(0,pa.default)((()=>{this._closed||!1===this._consumerResumeInProgress&&this.resumePendingConsumers()}))})),e.on("@getstats",((t,r)=>{if(this._closed)return r(new ma.InvalidStateError("closed"));this._handler.getReceiverStats(e.localId).then(t).catch(r)}))}handleDataProducer(e){e.on("@close",(()=>{this._dataProducers.delete(e.id)}))}handleDataConsumer(e){e.on("@close",(()=>{this._dataConsumers.delete(e.id)}))}};xo.Transport=Ra;var ka={},Ta={},Pa={},Ea={exports:{}},Oa=Ea.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(e){return e.encoding?"rtpmap:%d %s/%s/%s":e.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(e){return null!=e.address?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(e){return null!=e.subtype?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(e){return"extmap:%d"+(e.direction?"/%s":"%v")+(e["encrypt-uri"]?" %s":"%v")+" %s"+(e.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(e){return null!=e.sessionConfig?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(e){var t="candidate:%s %d %s %d %s %d typ %s";return t+=null!=e.raddr?" raddr %s rport %d":"%v%v",t+=null!=e.tcptype?" tcptype %s":"%v",null!=e.generation&&(t+=" generation %d"),t+=null!=e["network-id"]?" network-id %d":"%v",t+=null!=e["network-cost"]?" network-cost %d":"%v"}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(e){var t="ssrc:%d";return null!=e.attribute&&(t+=" %s",null!=e.value&&(t+=":%s")),t}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(e){return null!=e.maxMessageSize?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(e){return e.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(e){return"imageattr:%s %s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(e){return"simulcast:%s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(e){return"ts-refclk:%s"+(null!=e.clksrcExt?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(e){var t="mediaclk:";return t+=null!=e.id?"id=%s %s":"%v%s",t+=null!=e.mediaClockValue?"=%s":"",t+=null!=e.rateNumerator?" rate=%s":"",t+=null!=e.rateDenominator?"/%s":""}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};Object.keys(Oa).forEach((function(e){Oa[e].forEach((function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")}))}));var Da=Ea.exports;!function(e){var t=function(e){return String(Number(e))===e?Number(e):e},r=function(e,r,i){var n=e.name&&e.names;e.push&&!r[e.push]?r[e.push]=[]:n&&!r[e.name]&&(r[e.name]={});var s=e.push?{}:n?r[e.name]:r;!function(e,r,i,n){if(n&&!i)r[n]=t(e[1]);else for(var s=0;s<i.length;s+=1)null!=e[s+1]&&(r[i[s]]=t(e[s+1]))}(i.match(e.reg),s,e.names,e.name),e.push&&r[e.push].push(s)},i=Da,n=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},s=[],o=t;return e.split(/(\r\n|\r|\n)/).filter(n).forEach((function(e){var t=e[0],n=e.slice(2);"m"===t&&(s.push({rtp:[],fmtp:[]}),o=s[s.length-1]);for(var a=0;a<(i[t]||[]).length;a+=1){var c=i[t][a];if(c.reg.test(n))return r(c,o,n)}})),t.media=s,t};var s=function(e,r){var i=r.split(/=(.+)/,2);return 2===i.length?e[i[0]]=t(i[1]):1===i.length&&r.length>1&&(e[i[0]]=void 0),e};e.parseParams=function(e){return e.split(/;\s?/).reduce(s,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(e){return e.toString().split(" ").map(Number)},e.parseRemoteCandidates=function(e){for(var r=[],i=e.split(" ").map(t),n=0;n<i.length;n+=3)r.push({component:i[n],ip:i[n+1],port:i[n+2]});return r},e.parseImageAttributes=function(e){return e.split(" ").map((function(e){return e.substring(1,e.length-1).split(",").reduce(s,{})}))},e.parseSimulcastStreamList=function(e){return e.split(";").map((function(e){return e.split(",").map((function(e){var r,i=!1;return"~"!==e[0]?r=t(e):(r=t(e.substring(1,e.length)),i=!0),{scid:r,paused:i}}))}))}}(Pa);var Ia=Da,xa=/%[sdv%]/g,Ma=function(e){var t=1,r=arguments,i=r.length;return e.replace(xa,(function(e){if(t>=i)return e;var n=r[t];switch(t+=1,e){case"%%":return"%";case"%s":return String(n);case"%d":return Number(n);case"%v":return""}}))},La=function(e,t,r){var i=[e+"="+(t.format instanceof Function?t.format(t.push?r:r[t.name]):t.format)];if(t.names)for(var n=0;n<t.names.length;n+=1){var s=t.names[n];t.name?i.push(r[t.name][s]):i.push(r[t.names[n]])}else i.push(r[t.name]);return Ma.apply(null,i)},ja=["v","o","s","i","u","e","p","c","b","t","r","z","a"],Aa=["i","c","b","a"],Na=Pa,Ba=function(e,t){t=t||{},null==e.version&&(e.version=0),null==e.name&&(e.name=" "),e.media.forEach((function(e){null==e.payloads&&(e.payloads="")}));var r=t.outerOrder||ja,i=t.innerOrder||Aa,n=[];return r.forEach((function(t){Ia[t].forEach((function(r){r.name in e&&null!=e[r.name]?n.push(La(t,r,e)):r.push in e&&null!=e[r.push]&&e[r.push].forEach((function(e){n.push(La(t,r,e))}))}))})),e.media.forEach((function(e){n.push(La("m",Ia.m[0],e)),i.forEach((function(t){Ia[t].forEach((function(r){r.name in e&&null!=e[r.name]?n.push(La(t,r,e)):r.push in e&&null!=e[r.push]&&e[r.push].forEach((function(e){n.push(La(t,r,e))}))}))}))})),n.join("\r\n")+"\r\n"},Fa=Da;Ta.grammar=Fa,Ta.write=Ba,Ta.parse=Na.parse,Ta.parseParams=Na.parseParams,Ta.parseFmtpConfig=Na.parseFmtpConfig,Ta.parsePayloads=Na.parsePayloads,Ta.parseRemoteCandidates=Na.parseRemoteCandidates,Ta.parseImageAttributes=Na.parseImageAttributes,Ta.parseSimulcastStreamList=Na.parseSimulcastStreamList;var za={},Va=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),Ua=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),$a=a&&a.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(null!=t)for(var i=e(t),n=0;n<i.length;n++)"default"!==i[n]&&Va(r,t,i[n]);return Ua(r,t),r}}();Object.defineProperty(za,"__esModule",{value:!0});var Ga=za.extractRtpCapabilities=function({sdpObject:e}){const t=new Map,r=[];let i=!1,n=!1;for(const s of e.media){const e=s.type;switch(e){case"audio":if(i)continue;i=!0;break;case"video":if(n)continue;n=!0;break;default:continue}for(const r of s.rtp){const i={kind:e,mimeType:`${e}/${r.codec}`,preferredPayloadType:r.payload,clockRate:r.rate,channels:r.encoding,parameters:{},rtcpFeedback:[]};t.set(i.preferredPayloadType,i)}for(const e of s.fmtp||[]){const r=Ka.parseParams(e.config),i=t.get(e.payload);i&&(r?.hasOwnProperty("profile-level-id")&&(r["profile-level-id"]=String(r["profile-level-id"])),i.parameters=r)}for(const r of s.rtcpFb||[]){const i={type:r.type,parameter:r.subtype};if(i.parameter||delete i.parameter,"*"!==r.payload){const e=t.get(r.payload);if(!e)continue;e.rtcpFeedback.push(i)}else for(const r of t.values())r.kind!==e||/.+\/rtx$/i.test(r.mimeType)||r.rtcpFeedback.push(i)}for(const t of s.ext||[]){if(t["encrypt-uri"])continue;const i={kind:e,uri:t.uri,preferredId:t.value};r.push(i)}}return{codecs:Array.from(t.values()),headerExtensions:r}},qa=za.extractDtlsParameters=function({sdpObject:e}){let t,r=e.setup,i=e.fingerprint;if(!r||!i){const t=(e.media||[]).find((e=>0!==e.port));t&&(r??(r=t.setup),i??(i=t.fingerprint))}if(!r)throw new Error("no a=setup found at SDP session or media level");if(!i)throw new Error("no a=fingerprint found at SDP session or media level");switch(r){case"active":t="client";break;case"passive":t="server";break;case"actpass":t="auto"}return{role:t,fingerprints:[{algorithm:i.type,value:i.hash}]}},Ha=za.getCname=function({offerMediaObject:e}){const t=(e.ssrcs||[]).find((e=>"cname"===e.attribute));if(!t)return"";return t.value},Wa=za.applyCodecParameters=function({offerRtpParameters:e,answerMediaObject:t}){for(const r of e.codecs){const e=r.mimeType.toLowerCase();if("audio/opus"!==e)continue;if(!(t.rtp||[]).find((e=>e.payload===r.payloadType)))continue;t.fmtp=t.fmtp||[];let i=t.fmtp.find((e=>e.payload===r.payloadType));i||(i={payload:r.payloadType,config:""},t.fmtp.push(i));const n=Ka.parseParams(i.config);switch(e){case"audio/opus":{const e=r.parameters["sprop-stereo"];void 0!==e&&(n.stereo=Number(e)?1:0);break}}i.config="";for(const e of Object.keys(n))i.config&&(i.config+=";"),i.config+=`${e}=${n[e]}`}};const Ka=$a(Ta);var Ja={};Object.defineProperty(Ja,"__esModule",{value:!0}),Ja.getRtpEncodings=function({offerMediaObject:e}){const t=new Set;for(const r of e.ssrcs||[]){const e=r.id;t.add(e)}if(0===t.size)throw new Error("no a=ssrc lines found");const r=new Map;for(const i of e.ssrcGroups||[]){if("FID"!==i.semantics)continue;let[e,n]=i.ssrcs.split(/\s+/);e=Number(e),n=Number(n),t.has(e)&&(t.delete(e),t.delete(n),r.set(e,n))}for(const e of t)r.set(e,null);const i=[];for(const[e,t]of r){const r={ssrc:e};t&&(r.rtx={ssrc:t}),i.push(r)}return i},Ja.addLegacySimulcast=function({offerMediaObject:e,numStreams:t}){if(t<=1)throw new TypeError("numStreams must be greater than 1");const r=(e.ssrcs||[]).find((e=>"msid"===e.attribute));if(!r)throw new Error("a=ssrc line with msid information not found");const[i,n]=r.value.split(" "),s=Number(r.id);let o;(e.ssrcGroups||[]).some((e=>{if("FID"!==e.semantics)return!1;const t=e.ssrcs.split(/\s+/);return Number(t[0])===s&&(o=Number(t[1]),!0)}));const a=e.ssrcs.find((e=>"cname"===e.attribute));if(!a)throw new Error("a=ssrc line with cname information not found");const c=a.value,d=[],l=[];for(let e=0;e<t;++e)d.push(s+e),o&&l.push(o+e);e.ssrcGroups=[],e.ssrcs=[],e.ssrcGroups.push({semantics:"SIM",ssrcs:d.join(" ")});for(const t of d)e.ssrcs.push({id:t,attribute:"cname",value:c}),e.ssrcs.push({id:t,attribute:"msid",value:`${i} ${n}`});for(let t=0;t<l.length;++t){const r=d[t],s=l[t];e.ssrcs.push({id:s,attribute:"cname",value:c}),e.ssrcs.push({id:s,attribute:"msid",value:`${i} ${n}`}),e.ssrcGroups.push({semantics:"FID",ssrcs:`${r} ${s}`})}};var Xa={};Object.defineProperty(Xa,"__esModule",{value:!0});var Qa=Xa.addNackSuppportForOpus=function(e){for(const t of e.codecs??[])"audio/opus"!==t.mimeType.toLowerCase()&&"audio/multiopus"!==t.mimeType.toLowerCase()||t.rtcpFeedback?.some((e=>"nack"===e.type&&!e.parameter))||(t.rtcpFeedback||(t.rtcpFeedback=[]),t.rtcpFeedback.push({type:"nack"}))};var Za={};Object.defineProperty(Za,"__esModule",{value:!0});var Ya=Za.HandlerInterface=void 0;const ec=us;class tc extends ec.EnhancedEventEmitter{constructor(){super()}}Ya=Za.HandlerInterface=tc;var rc={},ic={},nc=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),sc=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),oc=a&&a.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(null!=t)for(var i=e(t),n=0;n<i.length;n++)"default"!==i[n]&&nc(r,t,i[n]);return sc(r,t),r}}();Object.defineProperty(ic,"__esModule",{value:!0}),ic.OfferMediaSection=ic.AnswerMediaSection=ic.MediaSection=void 0;const ac=oc(Ta),cc=oc(js);class dc{constructor({iceParameters:e,iceCandidates:t,dtlsParameters:r,planB:i=!1}){if(this._mediaObject={},this._planB=i,e&&this.setIceParameters(e),t){this._mediaObject.candidates=[];for(const e of t){const t={component:1};t.foundation=e.foundation,t.ip=e.address??e.ip,t.port=e.port,t.priority=e.priority,t.transport=e.protocol,t.type=e.type,e.tcpType&&(t.tcptype=e.tcpType),this._mediaObject.candidates.push(t)}this._mediaObject.endOfCandidates="end-of-candidates",this._mediaObject.iceOptions="renomination"}r&&this.setDtlsRole(r.role)}get mid(){return String(this._mediaObject.mid)}get closed(){return 0===this._mediaObject.port}getObject(){return this._mediaObject}setIceParameters(e){this._mediaObject.iceUfrag=e.usernameFragment,this._mediaObject.icePwd=e.password}pause(){this._mediaObject.direction="inactive"}disable(){this.pause(),delete this._mediaObject.ext,delete this._mediaObject.ssrcs,delete this._mediaObject.ssrcGroups,delete this._mediaObject.simulcast,delete this._mediaObject.simulcast_03,delete this._mediaObject.rids,delete this._mediaObject.extmapAllowMixed}close(){this.disable(),this._mediaObject.port=0}}ic.MediaSection=dc;ic.AnswerMediaSection=class extends dc{constructor({iceParameters:e,iceCandidates:t,dtlsParameters:r,sctpParameters:i,plainRtpParameters:n,planB:s=!1,offerMediaObject:o,offerRtpParameters:a,answerRtpParameters:c,codecOptions:d,extmapAllowMixed:l=!1}){switch(super({iceParameters:e,iceCandidates:t,dtlsParameters:r,planB:s}),this._mediaObject.mid=String(o.mid),this._mediaObject.type=o.type,this._mediaObject.protocol=o.protocol,n?(this._mediaObject.connection={ip:n.ip,version:n.ipVersion},this._mediaObject.port=n.port):(this._mediaObject.connection={ip:"127.0.0.1",version:4},this._mediaObject.port=7),o.type){case"audio":case"video":this._mediaObject.direction="recvonly",this._mediaObject.rtp=[],this._mediaObject.rtcpFb=[],this._mediaObject.fmtp=[];for(const e of c.codecs){const t={payload:e.payloadType,codec:lc(e),rate:e.clockRate};e.channels>1&&(t.encoding=e.channels),this._mediaObject.rtp.push(t);const r=cc.clone(e.parameters)??{};let i=cc.clone(e.rtcpFeedback)??[];if(d){const{opusStereo:t,opusFec:n,opusDtx:s,opusMaxPlaybackRate:o,opusMaxAverageBitrate:c,opusPtime:l,opusNack:u,videoGoogleStartBitrate:p,videoGoogleMaxBitrate:h,videoGoogleMinBitrate:f}=d,m=a.codecs.find((t=>t.payloadType===e.payloadType));switch(e.mimeType.toLowerCase()){case"audio/opus":case"audio/multiopus":void 0!==t&&(m.parameters["sprop-stereo"]=t?1:0,r.stereo=t?1:0),void 0!==n&&(m.parameters.useinbandfec=n?1:0,r.useinbandfec=n?1:0),void 0!==s&&(m.parameters.usedtx=s?1:0,r.usedtx=s?1:0),void 0!==o&&(r.maxplaybackrate=o),void 0!==c&&(r.maxaveragebitrate=c),void 0!==l&&(m.parameters.ptime=l,r.ptime=l),u||(m.rtcpFeedback=m.rtcpFeedback.filter((e=>"nack"!==e.type||e.parameter)),i=i.filter((e=>"nack"!==e.type||e.parameter)));break;case"video/vp8":case"video/vp9":case"video/h264":case"video/h265":void 0!==p&&(r["x-google-start-bitrate"]=p),void 0!==h&&(r["x-google-max-bitrate"]=h),void 0!==f&&(r["x-google-min-bitrate"]=f)}}const n={payload:e.payloadType,config:""};for(const e of Object.keys(r))n.config&&(n.config+=";"),n.config+=`${e}=${r[e]}`;n.config&&this._mediaObject.fmtp.push(n);for(const t of i)this._mediaObject.rtcpFb.push({payload:e.payloadType,type:t.type,subtype:t.parameter})}this._mediaObject.payloads=c.codecs.map((e=>e.payloadType)).join(" "),this._mediaObject.ext=[];for(const e of c.headerExtensions){(o.ext??[]).some((t=>t.uri===e.uri))&&this._mediaObject.ext.push({uri:e.uri,value:e.id})}if(l&&"extmap-allow-mixed"===o.extmapAllowMixed&&(this._mediaObject.extmapAllowMixed="extmap-allow-mixed"),o.simulcast){this._mediaObject.simulcast={dir1:"recv",list1:o.simulcast.list1},this._mediaObject.rids=[];for(const e of o.rids??[])"send"===e.direction&&this._mediaObject.rids.push({id:e.id,direction:"recv"})}else if(o.simulcast_03){this._mediaObject.simulcast_03={value:o.simulcast_03.value.replace(/send/g,"recv")},this._mediaObject.rids=[];for(const e of o.rids??[])"send"===e.direction&&this._mediaObject.rids.push({id:e.id,direction:"recv"})}this._mediaObject.rtcpMux="rtcp-mux",this._mediaObject.rtcpRsize="rtcp-rsize",this._planB&&"video"===this._mediaObject.type&&(this._mediaObject.xGoogleFlag="conference");break;case"application":"number"==typeof o.sctpPort?(this._mediaObject.payloads="webrtc-datachannel",this._mediaObject.sctpPort=i.port,this._mediaObject.maxMessageSize=i.maxMessageSize):o.sctpmap&&(this._mediaObject.payloads=i.port,this._mediaObject.sctpmap={app:"webrtc-datachannel",sctpmapNumber:i.port,maxMessageSize:i.maxMessageSize})}}setDtlsRole(e){switch(e){case"client":this._mediaObject.setup="active";break;case"server":this._mediaObject.setup="passive";break;case"auto":this._mediaObject.setup="actpass"}}resume(){this._mediaObject.direction="recvonly"}muxSimulcastStreams(e){if(!this._mediaObject.simulcast?.list1)return;const t={};for(const r of e)r.rid&&(t[r.rid]=r);const r=this._mediaObject.simulcast.list1,i=ac.parseSimulcastStreamList(r);for(const e of i)for(const r of e)r.paused=!t[r.scid]?.active;this._mediaObject.simulcast.list1=i.map((e=>e.map((e=>`${e.paused?"~":""}${e.scid}`)).join(","))).join(";")}};function lc(e){const t=new RegExp("^(audio|video)/(.+)","i").exec(e.mimeType);if(!t)throw new TypeError("invalid codec.mimeType");return t[2]}ic.OfferMediaSection=class extends dc{constructor({iceParameters:e,iceCandidates:t,dtlsParameters:r,sctpParameters:i,plainRtpParameters:n,planB:s=!1,mid:o,kind:a,offerRtpParameters:c,streamId:d,trackId:l,oldDataChannelSpec:u=!1}){switch(super({iceParameters:e,iceCandidates:t,dtlsParameters:r,planB:s}),this._mediaObject.mid=String(o),this._mediaObject.type=a,n?(this._mediaObject.connection={ip:n.ip,version:n.ipVersion},this._mediaObject.protocol="RTP/AVP",this._mediaObject.port=n.port):(this._mediaObject.connection={ip:"127.0.0.1",version:4},this._mediaObject.protocol=i?"UDP/DTLS/SCTP":"UDP/TLS/RTP/SAVPF",this._mediaObject.port=7),a){case"audio":case"video":{this._mediaObject.direction="sendonly",this._mediaObject.rtp=[],this._mediaObject.rtcpFb=[],this._mediaObject.fmtp=[],this._planB||(this._mediaObject.msid=`${d??"-"} ${l}`);for(const e of c.codecs){const t={payload:e.payloadType,codec:lc(e),rate:e.clockRate};e.channels>1&&(t.encoding=e.channels),this._mediaObject.rtp.push(t);const r={payload:e.payloadType,config:""};for(const t of Object.keys(e.parameters))r.config&&(r.config+=";"),r.config+=`${t}=${e.parameters[t]}`;r.config&&this._mediaObject.fmtp.push(r);for(const t of e.rtcpFeedback)this._mediaObject.rtcpFb.push({payload:e.payloadType,type:t.type,subtype:t.parameter})}this._mediaObject.payloads=c.codecs.map((e=>e.payloadType)).join(" "),this._mediaObject.ext=[];for(const e of c.headerExtensions)this._mediaObject.ext.push({uri:e.uri,value:e.id});this._mediaObject.rtcpMux="rtcp-mux",this._mediaObject.rtcpRsize="rtcp-rsize";const e=c.encodings[0],t=e.ssrc,r=e.rtx?.ssrc;this._mediaObject.ssrcs=[],this._mediaObject.ssrcGroups=[],c.rtcp.cname&&this._mediaObject.ssrcs.push({id:t,attribute:"cname",value:c.rtcp.cname}),this._planB&&this._mediaObject.ssrcs.push({id:t,attribute:"msid",value:`${d??"-"} ${l}`}),r&&(c.rtcp.cname&&this._mediaObject.ssrcs.push({id:r,attribute:"cname",value:c.rtcp.cname}),this._planB&&this._mediaObject.ssrcs.push({id:r,attribute:"msid",value:`${d??"-"} ${l}`}),this._mediaObject.ssrcGroups.push({semantics:"FID",ssrcs:`${t} ${r}`}));break}case"application":u?(this._mediaObject.payloads=i.port,this._mediaObject.sctpmap={app:"webrtc-datachannel",sctpmapNumber:i.port,maxMessageSize:i.maxMessageSize}):(this._mediaObject.payloads="webrtc-datachannel",this._mediaObject.sctpPort=i.port,this._mediaObject.maxMessageSize=i.maxMessageSize)}}setDtlsRole(e){this._mediaObject.setup="actpass"}resume(){this._mediaObject.direction="sendonly"}planBReceive({offerRtpParameters:e,streamId:t,trackId:r}){const i=e.encodings[0],n=i.ssrc,s=i.rtx?.ssrc,o=this._mediaObject.payloads.split(" ");for(const t of e.codecs){if(o.includes(String(t.payloadType)))continue;const e={payload:t.payloadType,codec:lc(t),rate:t.clockRate};t.channels>1&&(e.encoding=t.channels),this._mediaObject.rtp.push(e);const r={payload:t.payloadType,config:""};for(const e of Object.keys(t.parameters))r.config&&(r.config+=";"),r.config+=`${e}=${t.parameters[e]}`;r.config&&this._mediaObject.fmtp.push(r);for(const e of t.rtcpFeedback)this._mediaObject.rtcpFb.push({payload:t.payloadType,type:e.type,subtype:e.parameter})}this._mediaObject.payloads+=` ${e.codecs.filter((e=>!this._mediaObject.payloads.includes(e.payloadType))).map((e=>e.payloadType)).join(" ")}`,this._mediaObject.payloads=this._mediaObject.payloads.trim(),e.rtcp.cname&&this._mediaObject.ssrcs.push({id:n,attribute:"cname",value:e.rtcp.cname}),this._mediaObject.ssrcs.push({id:n,attribute:"msid",value:`${t??"-"} ${r}`}),s&&(e.rtcp.cname&&this._mediaObject.ssrcs.push({id:s,attribute:"cname",value:e.rtcp.cname}),this._mediaObject.ssrcs.push({id:s,attribute:"msid",value:`${t??"-"} ${r}`}),this._mediaObject.ssrcGroups.push({semantics:"FID",ssrcs:`${n} ${s}`}))}planBStopReceiving({offerRtpParameters:e}){const t=e.encodings[0],r=t.ssrc,i=t.rtx?.ssrc;this._mediaObject.ssrcs=this._mediaObject.ssrcs.filter((e=>e.id!==r&&e.id!==i)),i&&(this._mediaObject.ssrcGroups=this._mediaObject.ssrcGroups.filter((e=>e.ssrcs!==`${r} ${i}`)))}};var uc=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),pc=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),hc=a&&a.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(null!=t)for(var i=e(t),n=0;n<i.length;n++)"default"!==i[n]&&uc(r,t,i[n]);return pc(r,t),r}}();Object.defineProperty(rc,"__esModule",{value:!0});var fc=rc.RemoteSdp=void 0;const mc=hc(Ta),gc=ic,vc=new ss.Logger("RemoteSdp");fc=rc.RemoteSdp=class{constructor({iceParameters:e,iceCandidates:t,dtlsParameters:r,sctpParameters:i,plainRtpParameters:n,planB:s=!1}){if(this._mediaSections=[],this._midToIndex=new Map,this._iceParameters=e,this._iceCandidates=t,this._dtlsParameters=r,this._sctpParameters=i,this._plainRtpParameters=n,this._planB=s,this._sdpObject={version:0,origin:{address:"0.0.0.0",ipVer:4,netType:"IN",sessionId:1e4,sessionVersion:0,username:"mediasoup-client"},name:"-",timing:{start:0,stop:0},media:[]},e?.iceLite&&(this._sdpObject.icelite="ice-lite"),r){this._sdpObject.msidSemantic={semantic:"WMS",token:"*"};const e=this._dtlsParameters.fingerprints.length;this._sdpObject.fingerprint={type:r.fingerprints[e-1].algorithm,hash:r.fingerprints[e-1].value},this._sdpObject.groups=[{type:"BUNDLE",mids:""}]}n&&(this._sdpObject.origin.address=n.ip,this._sdpObject.origin.ipVer=n.ipVersion)}updateIceParameters(e){vc.debug("updateIceParameters() [iceParameters:%o]",e),this._iceParameters=e,this._sdpObject.icelite=e.iceLite?"ice-lite":void 0;for(const t of this._mediaSections)t.setIceParameters(e)}updateDtlsRole(e){vc.debug("updateDtlsRole() [role:%s]",e),this._dtlsParameters.role=e;for(const t of this._mediaSections)t.setDtlsRole(e)}getNextMediaSectionIdx(){for(let e=0;e<this._mediaSections.length;++e){const t=this._mediaSections[e];if(t.closed)return{idx:e,reuseMid:t.mid}}return{idx:this._mediaSections.length}}send({offerMediaObject:e,reuseMid:t,offerRtpParameters:r,answerRtpParameters:i,codecOptions:n,extmapAllowMixed:s=!1}){const o=new gc.AnswerMediaSection({iceParameters:this._iceParameters,iceCandidates:this._iceCandidates,dtlsParameters:this._dtlsParameters,plainRtpParameters:this._plainRtpParameters,planB:this._planB,offerMediaObject:e,offerRtpParameters:r,answerRtpParameters:i,codecOptions:n,extmapAllowMixed:s});t?this._replaceMediaSection(o,t):this._midToIndex.has(o.mid)?this._replaceMediaSection(o):this._addMediaSection(o)}receive({mid:e,kind:t,offerRtpParameters:r,streamId:i,trackId:n}){const s=this._midToIndex.get(e);let o;if(void 0!==s&&(o=this._mediaSections[s]),o)o.planBReceive({offerRtpParameters:r,streamId:i,trackId:n}),this._replaceMediaSection(o);else{o=new gc.OfferMediaSection({iceParameters:this._iceParameters,iceCandidates:this._iceCandidates,dtlsParameters:this._dtlsParameters,plainRtpParameters:this._plainRtpParameters,planB:this._planB,mid:e,kind:t,offerRtpParameters:r,streamId:i,trackId:n});const s=this._mediaSections.find((e=>e.closed));s?this._replaceMediaSection(o,s.mid):this._addMediaSection(o)}}pauseMediaSection(e){this._findMediaSection(e).pause()}resumeSendingMediaSection(e){this._findMediaSection(e).resume()}resumeReceivingMediaSection(e){this._findMediaSection(e).resume()}disableMediaSection(e){this._findMediaSection(e).disable()}closeMediaSection(e){const t=this._findMediaSection(e);return e===this._firstMid?(vc.debug("closeMediaSection() | cannot close first media section, disabling it instead [mid:%s]",e),this.disableMediaSection(e),!1):(t.close(),this._regenerateBundleMids(),!0)}muxMediaSectionSimulcast(e,t){const r=this._findMediaSection(e);r.muxSimulcastStreams(t),this._replaceMediaSection(r)}planBStopReceiving({mid:e,offerRtpParameters:t}){const r=this._findMediaSection(e);r.planBStopReceiving({offerRtpParameters:t}),this._replaceMediaSection(r)}sendSctpAssociation({offerMediaObject:e}){const t=new gc.AnswerMediaSection({iceParameters:this._iceParameters,iceCandidates:this._iceCandidates,dtlsParameters:this._dtlsParameters,sctpParameters:this._sctpParameters,plainRtpParameters:this._plainRtpParameters,offerMediaObject:e});this._addMediaSection(t)}receiveSctpAssociation({oldDataChannelSpec:e=!1}={}){const t=new gc.OfferMediaSection({iceParameters:this._iceParameters,iceCandidates:this._iceCandidates,dtlsParameters:this._dtlsParameters,sctpParameters:this._sctpParameters,plainRtpParameters:this._plainRtpParameters,mid:"datachannel",kind:"application",oldDataChannelSpec:e});this._addMediaSection(t)}getSdp(){return this._sdpObject.origin.sessionVersion++,mc.write(this._sdpObject)}_addMediaSection(e){this._firstMid||(this._firstMid=e.mid),this._mediaSections.push(e),this._midToIndex.set(e.mid,this._mediaSections.length-1),this._sdpObject.media.push(e.getObject()),this._regenerateBundleMids()}_replaceMediaSection(e,t){if("string"==typeof t){const r=this._midToIndex.get(t);if(void 0===r)throw new Error(`no media section found for reuseMid '${t}'`);const i=this._mediaSections[r];this._mediaSections[r]=e,this._midToIndex.delete(i.mid),this._midToIndex.set(e.mid,r),this._sdpObject.media[r]=e.getObject(),this._regenerateBundleMids()}else{const t=this._midToIndex.get(e.mid);if(void 0===t)throw new Error(`no media section found with mid '${e.mid}'`);this._mediaSections[t]=e,this._sdpObject.media[t]=e.getObject()}}_findMediaSection(e){const t=this._midToIndex.get(e);if(void 0===t)throw new Error(`no media section found with mid '${e}'`);return this._mediaSections[t]}_regenerateBundleMids(){this._dtlsParameters&&(this._sdpObject.groups[0].mids=this._mediaSections.filter((e=>!e.closed)).map((e=>e.mid)).join(" "))}};var bc={};Object.defineProperty(bc,"__esModule",{value:!0});var yc=bc.parse=function(e){const t=wc.exec(e??"");return t?{spatialLayers:Number(t[1]),temporalLayers:Number(t[2])}:{spatialLayers:1,temporalLayers:1}};const wc=new RegExp("^[LS]([1-9]\\d{0,1})T([1-9]\\d{0,1})");var _c=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),Sc=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Cc=a&&a.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(null!=t)for(var i=e(t),n=0;n<i.length;n++)"default"!==i[n]&&_c(r,t,i[n]);return Sc(r,t),r}}();Object.defineProperty(ka,"__esModule",{value:!0}),ka.Chrome111=void 0;const Rc=Cc(Ta),kc=ss,Tc=Cc(js),Pc=Cc(Fs),Ec=Cc(za),Oc=Cc(Ja),Dc=Cc(Xa),Ic=Is,xc=Za,Mc=rc,Lc=bc,jc=new kc.Logger("Chrome111"),Ac={OS:1024,MIS:1024};class Nc extends xc.HandlerInterface{static createFactory(){return()=>new Nc}constructor(){super(),this._closed=!1,this._mapMidTransceiver=new Map,this._sendStream=new MediaStream,this._hasDataChannelMediaSection=!1,this._nextSendSctpStreamId=0,this._transportReady=!1}get name(){return"Chrome111"}close(){if(jc.debug("close()"),!this._closed){if(this._closed=!0,this._pc)try{this._pc.close()}catch(e){}this.emit("@close")}}async getNativeRtpCapabilities(){jc.debug("getNativeRtpCapabilities()");const e=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"unified-plan"});try{e.addTransceiver("audio"),e.addTransceiver("video");const t=await e.createOffer();try{e.close()}catch(e){}const r=Rc.parse(t.sdp),i=Ec.extractRtpCapabilities({sdpObject:r});return Dc.addNackSuppportForOpus(i),i}catch(t){try{e.close()}catch(e){}throw t}}async getNativeSctpCapabilities(){return jc.debug("getNativeSctpCapabilities()"),{numStreams:Ac}}run({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,extendedRtpCapabilities:d}){this.assertNotClosed(),jc.debug("run()"),this._direction=e,this._remoteSdp=new Mc.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n}),this._sendingRtpParametersByKind={audio:Pc.getSendingRtpParameters("audio",d),video:Pc.getSendingRtpParameters("video",d)},this._sendingRemoteRtpParametersByKind={audio:Pc.getSendingRemoteRtpParameters("audio",d),video:Pc.getSendingRemoteRtpParameters("video",d)},i.role&&"auto"!==i.role&&(this._forcedLocalDtlsRole="server"===i.role?"client":"server"),this._pc=new RTCPeerConnection({iceServers:s??[],iceTransportPolicy:o??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"unified-plan",...a},c),this._pc.addEventListener("icegatheringstatechange",(()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)})),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",(()=>{this.emit("@connectionstatechange",this._pc.connectionState)})):(jc.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",(()=>{switch(this._pc.iceConnectionState){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected");break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed")}})))}async updateIceServers(e){this.assertNotClosed(),jc.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(this.assertNotClosed(),jc.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});jc.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};jc.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};jc.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();jc.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",t),await this._pc.setLocalDescription(t)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:e,encodings:t,codecOptions:r,codec:i,onRtpSender:n}){if(this.assertNotClosed(),this.assertSendDirection(),jc.debug("send() [kind:%s, track.id:%s]",e.kind,e.id),t&&t.length>1){let e=1;for(const r of t){const t=r.scalabilityMode?(0,Lc.parse)(r.scalabilityMode).temporalLayers:3;t>e&&(e=t)}t.forEach(((t,r)=>{t.rid=`r${r}`,t.scalabilityMode=`L1T${e}`}))}const s=Tc.clone(this._sendingRtpParametersByKind[e.kind]);s.codecs=Pc.reduceCodecs(s.codecs,i);const o=Tc.clone(this._sendingRemoteRtpParametersByKind[e.kind]);o.codecs=Pc.reduceCodecs(o.codecs,i);const a=this._remoteSdp.getNextMediaSectionIdx(),c=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream],sendEncodings:t});n&&n(c.sender);const d=await this._pc.createOffer();let l=Rc.parse(d.sdp);this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:l}),jc.debug("send() | calling pc.setLocalDescription() [offer:%o]",d),await this._pc.setLocalDescription(d);const u=c.mid;s.mid=u,l=Rc.parse(this._pc.localDescription.sdp);const p=l.media[a.idx];if(s.rtcp.cname=Ec.getCname({offerMediaObject:p}),t)if(1===t.length){const e=Oc.getRtpEncodings({offerMediaObject:p});Object.assign(e[0],t[0]),s.encodings=e}else s.encodings=t;else s.encodings=Oc.getRtpEncodings({offerMediaObject:p});this._remoteSdp.send({offerMediaObject:p,reuseMid:a.reuseMid,offerRtpParameters:s,answerRtpParameters:o,codecOptions:r,extmapAllowMixed:!0});const h={type:"answer",sdp:this._remoteSdp.getSdp()};return jc.debug("send() | calling pc.setRemoteDescription() [answer:%o]",h),await this._pc.setRemoteDescription(h),this._mapMidTransceiver.set(u,c),{localId:u,rtpParameters:s,rtpSender:c.sender}}async stopSending(e){if(this.assertSendDirection(),jc.debug("stopSending() [localId:%s]",e),this._closed)return;const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.sender.replaceTrack(null),this._pc.removeTrack(t.sender);if(this._remoteSdp.closeMediaSection(t.mid))try{t.stop()}catch(e){}const r=await this._pc.createOffer();jc.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const i={type:"answer",sdp:this._remoteSdp.getSdp()};jc.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),jc.debug("pauseSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="inactive",this._remoteSdp.pauseMediaSection(e);const r=await this._pc.createOffer();jc.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const i={type:"answer",sdp:this._remoteSdp.getSdp()};jc.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),jc.debug("resumeSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(this._remoteSdp.resumeSendingMediaSection(e),!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="sendonly";const r=await this._pc.createOffer();jc.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const i={type:"answer",sdp:this._remoteSdp.getSdp()};jc.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?jc.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):jc.debug("replaceTrack() [localId:%s, no track]",e);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");await r.sender.replaceTrack(t)}async setMaxSpatialLayer(e,t){this.assertNotClosed(),this.assertSendDirection(),jc.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const i=r.sender.getParameters();i.encodings.forEach(((e,r)=>{e.active=r<=t})),await r.sender.setParameters(i),this._remoteSdp.muxMediaSectionSimulcast(e,i.encodings);const n=await this._pc.createOffer();jc.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);const s={type:"answer",sdp:this._remoteSdp.getSdp()};jc.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),jc.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const i=r.sender.getParameters();i.encodings.forEach(((e,r)=>{i.encodings[r]={...e,...t}})),await r.sender.setParameters(i),this._remoteSdp.muxMediaSectionSimulcast(e,i.encodings);const n=await this._pc.createOffer();jc.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);const s={type:"answer",sdp:this._remoteSdp.getSdp()};jc.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async getSenderStats(e){this.assertNotClosed(),this.assertSendDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.sender.getStats()}async sendDataChannel({ordered:e,maxPacketLifeTime:t,maxRetransmits:r,label:i,protocol:n}){this.assertNotClosed(),this.assertSendDirection();const s={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmits:r,protocol:n};jc.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(i,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%Ac.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=Rc.parse(e.sdp),r=t.media.find((e=>"application"===e.type));this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:t}),jc.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:r});const i={type:"answer",sdp:this._remoteSdp.getSdp()};jc.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._hasDataChannelMediaSection=!0}return{dataChannel:o,sctpStreamParameters:{streamId:s.id,ordered:s.ordered,maxPacketLifeTime:s.maxPacketLifeTime,maxRetransmits:s.maxRetransmits}}}async receive(e){this.assertNotClosed(),this.assertRecvDirection();const t=[],r=new Map;for(const t of e){const{trackId:e,kind:i,rtpParameters:n,streamId:s}=t;jc.debug("receive() [trackId:%s, kind:%s]",e,i);const o=n.mid??String(this._mapMidTransceiver.size);r.set(e,o),this._remoteSdp.receive({mid:o,kind:i,offerRtpParameters:n,streamId:s??n.rtcp.cname,trackId:e})}const i={type:"offer",sdp:this._remoteSdp.getSdp()};jc.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",i),await this._pc.setRemoteDescription(i);for(const t of e){const{trackId:e,onRtpReceiver:i}=t;if(i){const t=r.get(e),n=this._pc.getTransceivers().find((e=>e.mid===t));if(!n)throw new Error("transceiver not found");i(n.receiver)}}let n=await this._pc.createAnswer();const s=Rc.parse(n.sdp);for(const t of e){const{trackId:e,rtpParameters:i}=t,n=r.get(e),o=s.media.find((e=>String(e.mid)===n));Ec.applyCodecParameters({offerRtpParameters:i,answerMediaObject:o})}n={type:"answer",sdp:Rc.write(s)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:s}),jc.debug("receive() | calling pc.setLocalDescription() [answer:%o]",n),await this._pc.setLocalDescription(n);for(const i of e){const{trackId:e}=i,n=r.get(e),s=this._pc.getTransceivers().find((e=>e.mid===n));if(!s)throw new Error("new RTCRtpTransceiver not found");this._mapMidTransceiver.set(n,s),t.push({localId:n,track:s.receiver.track,rtpReceiver:s.receiver})}return t}async stopReceiving(e){if(this.assertRecvDirection(),this._closed)return;for(const t of e){jc.debug("stopReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(e.mid)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};jc.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();jc.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r);for(const t of e)this._mapMidTransceiver.delete(t)}async pauseReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(const t of e){jc.debug("pauseReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="inactive",this._remoteSdp.pauseMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};jc.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();jc.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async resumeReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(const t of e){jc.debug("resumeReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};jc.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();jc.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async getReceiverStats(e){this.assertNotClosed(),this.assertRecvDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.receiver.getStats()}async receiveDataChannel({sctpStreamParameters:e,label:t,protocol:r}){this.assertNotClosed(),this.assertRecvDirection();const{streamId:i,ordered:n,maxPacketLifeTime:s,maxRetransmits:o}=e,a={negotiated:!0,id:i,ordered:n,maxPacketLifeTime:s,maxRetransmits:o,protocol:r};jc.debug("receiveDataChannel() [options:%o]",a);const c=this._pc.createDataChannel(t,a);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();const e={type:"offer",sdp:this._remoteSdp.getSdp()};jc.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=Rc.parse(t.sdp);await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:e})}jc.debug("receiveDataChannel() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setLocalDescription(t),this._hasDataChannelMediaSection=!0}return{dataChannel:c}}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=Rc.parse(this._pc.localDescription.sdp));const r=Ec.extractDtlsParameters({sdpObject:t});r.role=e,this._remoteSdp.updateDtlsRole("client"===e?"server":"client"),await new Promise(((e,t)=>{this.safeEmit("@connect",{dtlsParameters:r},e,t)})),this._transportReady=!0}assertNotClosed(){if(this._closed)throw new Ic.InvalidStateError("method called in a closed handler")}assertSendDirection(){if("send"!==this._direction)throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if("recv"!==this._direction)throw new Error('method can just be called for handlers with "recv" direction')}}ka.Chrome111=Nc;var Bc={},Fc=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),zc=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Vc=a&&a.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(null!=t)for(var i=e(t),n=0;n<i.length;n++)"default"!==i[n]&&Fc(r,t,i[n]);return zc(r,t),r}}();Object.defineProperty(Bc,"__esModule",{value:!0}),Bc.Chrome74=void 0;const Uc=Vc(Ta),$c=ss,Gc=Vc(js),qc=Vc(Fs),Hc=Vc(za),Wc=Vc(Ja),Kc=Vc(Xa),Jc=Is,Xc=Za,Qc=rc,Zc=bc,Yc=new $c.Logger("Chrome74"),ed={OS:1024,MIS:1024};class td extends Xc.HandlerInterface{static createFactory(){return()=>new td}constructor(){super(),this._closed=!1,this._mapMidTransceiver=new Map,this._sendStream=new MediaStream,this._hasDataChannelMediaSection=!1,this._nextSendSctpStreamId=0,this._transportReady=!1}get name(){return"Chrome74"}close(){if(Yc.debug("close()"),!this._closed){if(this._closed=!0,this._pc)try{this._pc.close()}catch(e){}this.emit("@close")}}async getNativeRtpCapabilities(){Yc.debug("getNativeRtpCapabilities()");const e=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"unified-plan"});try{e.addTransceiver("audio"),e.addTransceiver("video");const t=await e.createOffer();try{e.close()}catch(e){}const r=Uc.parse(t.sdp),i=Hc.extractRtpCapabilities({sdpObject:r});return Kc.addNackSuppportForOpus(i),i}catch(t){try{e.close()}catch(e){}throw t}}async getNativeSctpCapabilities(){return Yc.debug("getNativeSctpCapabilities()"),{numStreams:ed}}run({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,extendedRtpCapabilities:d}){Yc.debug("run()"),this._direction=e,this._remoteSdp=new Qc.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n}),this._sendingRtpParametersByKind={audio:qc.getSendingRtpParameters("audio",d),video:qc.getSendingRtpParameters("video",d)},this._sendingRemoteRtpParametersByKind={audio:qc.getSendingRemoteRtpParameters("audio",d),video:qc.getSendingRemoteRtpParameters("video",d)},i.role&&"auto"!==i.role&&(this._forcedLocalDtlsRole="server"===i.role?"client":"server"),this._pc=new RTCPeerConnection({iceServers:s??[],iceTransportPolicy:o??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"unified-plan",...a},c),this._pc.addEventListener("icegatheringstatechange",(()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)})),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",(()=>{this.emit("@connectionstatechange",this._pc.connectionState)})):(Yc.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",(()=>{switch(this._pc.iceConnectionState){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected");break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed")}})))}async updateIceServers(e){this.assertNotClosed(),Yc.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(this.assertNotClosed(),Yc.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});Yc.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};Yc.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};Yc.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();Yc.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",t),await this._pc.setLocalDescription(t)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:e,encodings:t,codecOptions:r,codec:i}){this.assertNotClosed(),this.assertSendDirection(),Yc.debug("send() [kind:%s, track.id:%s]",e.kind,e.id),t&&t.length>1&&t.forEach(((e,t)=>{e.rid=`r${t}`}));const n=Gc.clone(this._sendingRtpParametersByKind[e.kind]);n.codecs=qc.reduceCodecs(n.codecs,i);const s=Gc.clone(this._sendingRemoteRtpParametersByKind[e.kind]);s.codecs=qc.reduceCodecs(s.codecs,i);const o=this._remoteSdp.getNextMediaSectionIdx(),a=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream],sendEncodings:t});let c,d=await this._pc.createOffer(),l=Uc.parse(d.sdp);this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:l});let u=!1;const p=(0,Zc.parse)((t??[{}])[0].scalabilityMode);t&&1===t.length&&p.spatialLayers>1&&"video/vp9"===n.codecs[0].mimeType.toLowerCase()&&(Yc.debug("send() | enabling legacy simulcast for VP9 SVC"),u=!0,l=Uc.parse(d.sdp),c=l.media[o.idx],Wc.addLegacySimulcast({offerMediaObject:c,numStreams:p.spatialLayers}),d={type:"offer",sdp:Uc.write(l)}),Yc.debug("send() | calling pc.setLocalDescription() [offer:%o]",d),await this._pc.setLocalDescription(d);const h=a.mid;if(n.mid=h,l=Uc.parse(this._pc.localDescription.sdp),c=l.media[o.idx],n.rtcp.cname=Hc.getCname({offerMediaObject:c}),t)if(1===t.length){let e=Wc.getRtpEncodings({offerMediaObject:c});Object.assign(e[0],t[0]),u&&(e=[e[0]]),n.encodings=e}else n.encodings=t;else n.encodings=Wc.getRtpEncodings({offerMediaObject:c});if(n.encodings.length>1&&("video/vp8"===n.codecs[0].mimeType.toLowerCase()||"video/h264"===n.codecs[0].mimeType.toLowerCase()))for(const e of n.encodings)e.scalabilityMode?e.scalabilityMode=`L1T${p.temporalLayers}`:e.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:c,reuseMid:o.reuseMid,offerRtpParameters:n,answerRtpParameters:s,codecOptions:r,extmapAllowMixed:!0});const f={type:"answer",sdp:this._remoteSdp.getSdp()};return Yc.debug("send() | calling pc.setRemoteDescription() [answer:%o]",f),await this._pc.setRemoteDescription(f),this._mapMidTransceiver.set(h,a),{localId:h,rtpParameters:n,rtpSender:a.sender}}async stopSending(e){if(this.assertSendDirection(),Yc.debug("stopSending() [localId:%s]",e),this._closed)return;const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.sender.replaceTrack(null),this._pc.removeTrack(t.sender);if(this._remoteSdp.closeMediaSection(t.mid))try{t.stop()}catch(e){}const r=await this._pc.createOffer();Yc.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const i={type:"answer",sdp:this._remoteSdp.getSdp()};Yc.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),Yc.debug("pauseSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="inactive",this._remoteSdp.pauseMediaSection(e);const r=await this._pc.createOffer();Yc.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const i={type:"answer",sdp:this._remoteSdp.getSdp()};Yc.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),Yc.debug("resumeSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(this._remoteSdp.resumeSendingMediaSection(e),!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="sendonly";const r=await this._pc.createOffer();Yc.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const i={type:"answer",sdp:this._remoteSdp.getSdp()};Yc.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?Yc.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):Yc.debug("replaceTrack() [localId:%s, no track]",e);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");await r.sender.replaceTrack(t)}async setMaxSpatialLayer(e,t){this.assertNotClosed(),this.assertSendDirection(),Yc.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const i=r.sender.getParameters();i.encodings.forEach(((e,r)=>{e.active=r<=t})),await r.sender.setParameters(i),this._remoteSdp.muxMediaSectionSimulcast(e,i.encodings);const n=await this._pc.createOffer();Yc.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);const s={type:"answer",sdp:this._remoteSdp.getSdp()};Yc.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),Yc.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const i=r.sender.getParameters();i.encodings.forEach(((e,r)=>{i.encodings[r]={...e,...t}})),await r.sender.setParameters(i),this._remoteSdp.muxMediaSectionSimulcast(e,i.encodings);const n=await this._pc.createOffer();Yc.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);const s={type:"answer",sdp:this._remoteSdp.getSdp()};Yc.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async getSenderStats(e){this.assertNotClosed(),this.assertSendDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.sender.getStats()}async sendDataChannel({ordered:e,maxPacketLifeTime:t,maxRetransmits:r,label:i,protocol:n}){this.assertNotClosed(),this.assertSendDirection();const s={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmits:r,protocol:n};Yc.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(i,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%ed.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=Uc.parse(e.sdp),r=t.media.find((e=>"application"===e.type));this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:t}),Yc.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:r});const i={type:"answer",sdp:this._remoteSdp.getSdp()};Yc.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._hasDataChannelMediaSection=!0}return{dataChannel:o,sctpStreamParameters:{streamId:s.id,ordered:s.ordered,maxPacketLifeTime:s.maxPacketLifeTime,maxRetransmits:s.maxRetransmits}}}async receive(e){this.assertNotClosed(),this.assertRecvDirection();const t=[],r=new Map;for(const t of e){const{trackId:e,kind:i,rtpParameters:n,streamId:s}=t;Yc.debug("receive() [trackId:%s, kind:%s]",e,i);const o=n.mid??String(this._mapMidTransceiver.size);r.set(e,o),this._remoteSdp.receive({mid:o,kind:i,offerRtpParameters:n,streamId:s??n.rtcp.cname,trackId:e})}const i={type:"offer",sdp:this._remoteSdp.getSdp()};Yc.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",i),await this._pc.setRemoteDescription(i);let n=await this._pc.createAnswer();const s=Uc.parse(n.sdp);for(const t of e){const{trackId:e,rtpParameters:i}=t,n=r.get(e),o=s.media.find((e=>String(e.mid)===n));Hc.applyCodecParameters({offerRtpParameters:i,answerMediaObject:o})}n={type:"answer",sdp:Uc.write(s)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:s}),Yc.debug("receive() | calling pc.setLocalDescription() [answer:%o]",n),await this._pc.setLocalDescription(n);for(const i of e){const{trackId:e}=i,n=r.get(e),s=this._pc.getTransceivers().find((e=>e.mid===n));if(!s)throw new Error("new RTCRtpTransceiver not found");this._mapMidTransceiver.set(n,s),t.push({localId:n,track:s.receiver.track,rtpReceiver:s.receiver})}return t}async stopReceiving(e){if(this.assertRecvDirection(),this._closed)return;for(const t of e){Yc.debug("stopReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(e.mid)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};Yc.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Yc.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r);for(const t of e)this._mapMidTransceiver.delete(t)}async pauseReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(const t of e){Yc.debug("pauseReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="inactive",this._remoteSdp.pauseMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};Yc.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Yc.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async resumeReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(const t of e){Yc.debug("resumeReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};Yc.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Yc.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async getReceiverStats(e){this.assertNotClosed(),this.assertRecvDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.receiver.getStats()}async receiveDataChannel({sctpStreamParameters:e,label:t,protocol:r}){this.assertNotClosed(),this.assertRecvDirection();const{streamId:i,ordered:n,maxPacketLifeTime:s,maxRetransmits:o}=e,a={negotiated:!0,id:i,ordered:n,maxPacketLifeTime:s,maxRetransmits:o,protocol:r};Yc.debug("receiveDataChannel() [options:%o]",a);const c=this._pc.createDataChannel(t,a);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();const e={type:"offer",sdp:this._remoteSdp.getSdp()};Yc.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=Uc.parse(t.sdp);await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:e})}Yc.debug("receiveDataChannel() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setLocalDescription(t),this._hasDataChannelMediaSection=!0}return{dataChannel:c}}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=Uc.parse(this._pc.localDescription.sdp));const r=Hc.extractDtlsParameters({sdpObject:t});r.role=e,this._remoteSdp.updateDtlsRole("client"===e?"server":"client"),await new Promise(((e,t)=>{this.safeEmit("@connect",{dtlsParameters:r},e,t)})),this._transportReady=!0}assertNotClosed(){if(this._closed)throw new Jc.InvalidStateError("method called in a closed handler")}assertSendDirection(){if("send"!==this._direction)throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if("recv"!==this._direction)throw new Error('method can just be called for handlers with "recv" direction')}}Bc.Chrome74=td;var rd={},id=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),nd=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),sd=a&&a.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(null!=t)for(var i=e(t),n=0;n<i.length;n++)"default"!==i[n]&&id(r,t,i[n]);return nd(r,t),r}}();Object.defineProperty(rd,"__esModule",{value:!0}),rd.Chrome70=void 0;const od=sd(Ta),ad=ss,cd=sd(js),dd=sd(Fs),ld=sd(za),ud=sd(Ja),pd=Za,hd=rc,fd=bc,md=new ad.Logger("Chrome70"),gd={OS:1024,MIS:1024};class vd extends pd.HandlerInterface{static createFactory(){return()=>new vd}constructor(){super(),this._mapMidTransceiver=new Map,this._sendStream=new MediaStream,this._hasDataChannelMediaSection=!1,this._nextSendSctpStreamId=0,this._transportReady=!1}get name(){return"Chrome70"}close(){if(md.debug("close()"),this._pc)try{this._pc.close()}catch(e){}this.emit("@close")}async getNativeRtpCapabilities(){md.debug("getNativeRtpCapabilities()");const e=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"unified-plan"});try{e.addTransceiver("audio"),e.addTransceiver("video");const t=await e.createOffer();try{e.close()}catch(e){}const r=od.parse(t.sdp);return ld.extractRtpCapabilities({sdpObject:r})}catch(t){try{e.close()}catch(e){}throw t}}async getNativeSctpCapabilities(){return md.debug("getNativeSctpCapabilities()"),{numStreams:gd}}run({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,extendedRtpCapabilities:d}){md.debug("run()"),this._direction=e,this._remoteSdp=new hd.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n}),this._sendingRtpParametersByKind={audio:dd.getSendingRtpParameters("audio",d),video:dd.getSendingRtpParameters("video",d)},this._sendingRemoteRtpParametersByKind={audio:dd.getSendingRemoteRtpParameters("audio",d),video:dd.getSendingRemoteRtpParameters("video",d)},i.role&&"auto"!==i.role&&(this._forcedLocalDtlsRole="server"===i.role?"client":"server"),this._pc=new RTCPeerConnection({iceServers:s??[],iceTransportPolicy:o??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"unified-plan",...a},c),this._pc.addEventListener("icegatheringstatechange",(()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)})),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",(()=>{this.emit("@connectionstatechange",this._pc.connectionState)})):this._pc.addEventListener("iceconnectionstatechange",(()=>{switch(md.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.iceConnectionState){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected");break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed")}}))}async updateIceServers(e){md.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(md.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});md.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};md.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};md.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();md.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",t),await this._pc.setLocalDescription(t)}}async getTransportStats(){return this._pc.getStats()}async send({track:e,encodings:t,codecOptions:r,codec:i}){this.assertSendDirection(),md.debug("send() [kind:%s, track.id:%s]",e.kind,e.id);const n=cd.clone(this._sendingRtpParametersByKind[e.kind]);n.codecs=dd.reduceCodecs(n.codecs,i);const s=cd.clone(this._sendingRemoteRtpParametersByKind[e.kind]);s.codecs=dd.reduceCodecs(s.codecs,i);const o=this._remoteSdp.getNextMediaSectionIdx(),a=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream]});let c,d=await this._pc.createOffer(),l=od.parse(d.sdp);this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:l}),t&&t.length>1&&(md.debug("send() | enabling legacy simulcast"),l=od.parse(d.sdp),c=l.media[o.idx],ud.addLegacySimulcast({offerMediaObject:c,numStreams:t.length}),d={type:"offer",sdp:od.write(l)});let u=!1;const p=(0,fd.parse)((t??[{}])[0].scalabilityMode);if(t&&1===t.length&&p.spatialLayers>1&&"video/vp9"===n.codecs[0].mimeType.toLowerCase()&&(md.debug("send() | enabling legacy simulcast for VP9 SVC"),u=!0,l=od.parse(d.sdp),c=l.media[o.idx],ud.addLegacySimulcast({offerMediaObject:c,numStreams:p.spatialLayers}),d={type:"offer",sdp:od.write(l)}),md.debug("send() | calling pc.setLocalDescription() [offer:%o]",d),await this._pc.setLocalDescription(d),t){md.debug("send() | applying given encodings");const e=a.sender.getParameters();for(let r=0;r<(e.encodings??[]).length;++r){const i=e.encodings[r],n=t[r];if(!n)break;e.encodings[r]=Object.assign(i,n)}await a.sender.setParameters(e)}const h=a.mid;if(n.mid=h,l=od.parse(this._pc.localDescription.sdp),c=l.media[o.idx],n.rtcp.cname=ld.getCname({offerMediaObject:c}),n.encodings=ud.getRtpEncodings({offerMediaObject:c}),t)for(let e=0;e<n.encodings.length;++e)t[e]&&Object.assign(n.encodings[e],t[e]);if(u&&(n.encodings=[n.encodings[0]]),n.encodings.length>1&&("video/vp8"===n.codecs[0].mimeType.toLowerCase()||"video/h264"===n.codecs[0].mimeType.toLowerCase()))for(const e of n.encodings)e.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:c,reuseMid:o.reuseMid,offerRtpParameters:n,answerRtpParameters:s,codecOptions:r});const f={type:"answer",sdp:this._remoteSdp.getSdp()};return md.debug("send() | calling pc.setRemoteDescription() [answer:%o]",f),await this._pc.setRemoteDescription(f),this._mapMidTransceiver.set(h,a),{localId:h,rtpParameters:n,rtpSender:a.sender}}async stopSending(e){this.assertSendDirection(),md.debug("stopSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.sender.replaceTrack(null),this._pc.removeTrack(t.sender);if(this._remoteSdp.closeMediaSection(t.mid))try{t.stop()}catch(e){}const r=await this._pc.createOffer();md.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const i={type:"answer",sdp:this._remoteSdp.getSdp()};md.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._mapMidTransceiver.delete(e)}async pauseSending(e){}async resumeSending(e){}async replaceTrack(e,t){this.assertSendDirection(),t?md.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):md.debug("replaceTrack() [localId:%s, no track]",e);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");await r.sender.replaceTrack(t)}async setMaxSpatialLayer(e,t){this.assertSendDirection(),md.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const i=r.sender.getParameters();i.encodings.forEach(((e,r)=>{e.active=r<=t})),await r.sender.setParameters(i),this._remoteSdp.muxMediaSectionSimulcast(e,i.encodings);const n=await this._pc.createOffer();md.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);const s={type:"answer",sdp:this._remoteSdp.getSdp()};md.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async setRtpEncodingParameters(e,t){this.assertSendDirection(),md.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const i=r.sender.getParameters();i.encodings.forEach(((e,r)=>{i.encodings[r]={...e,...t}})),await r.sender.setParameters(i),this._remoteSdp.muxMediaSectionSimulcast(e,i.encodings);const n=await this._pc.createOffer();md.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);const s={type:"answer",sdp:this._remoteSdp.getSdp()};md.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async getSenderStats(e){this.assertSendDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.sender.getStats()}async sendDataChannel({ordered:e,maxPacketLifeTime:t,maxRetransmits:r,label:i,protocol:n}){this.assertSendDirection();const s={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmitTime:t,maxRetransmits:r,protocol:n};md.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(i,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%gd.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=od.parse(e.sdp),r=t.media.find((e=>"application"===e.type));this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:t}),md.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:r});const i={type:"answer",sdp:this._remoteSdp.getSdp()};md.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._hasDataChannelMediaSection=!0}return{dataChannel:o,sctpStreamParameters:{streamId:s.id,ordered:s.ordered,maxPacketLifeTime:s.maxPacketLifeTime,maxRetransmits:s.maxRetransmits}}}async receive(e){this.assertRecvDirection();const t=[],r=new Map;for(const t of e){const{trackId:e,kind:i,rtpParameters:n,streamId:s}=t;md.debug("receive() [trackId:%s, kind:%s]",e,i);const o=n.mid??String(this._mapMidTransceiver.size);r.set(e,o),this._remoteSdp.receive({mid:o,kind:i,offerRtpParameters:n,streamId:s??n.rtcp.cname,trackId:e})}const i={type:"offer",sdp:this._remoteSdp.getSdp()};md.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",i),await this._pc.setRemoteDescription(i);let n=await this._pc.createAnswer();const s=od.parse(n.sdp);for(const t of e){const{trackId:e,rtpParameters:i}=t,n=r.get(e),o=s.media.find((e=>String(e.mid)===n));ld.applyCodecParameters({offerRtpParameters:i,answerMediaObject:o})}n={type:"answer",sdp:od.write(s)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:s}),md.debug("receive() | calling pc.setLocalDescription() [answer:%o]",n),await this._pc.setLocalDescription(n);for(const i of e){const{trackId:e}=i,n=r.get(e),s=this._pc.getTransceivers().find((e=>e.mid===n));if(!s)throw new Error("new RTCRtpTransceiver not found");this._mapMidTransceiver.set(n,s),t.push({localId:n,track:s.receiver.track,rtpReceiver:s.receiver})}return t}async stopReceiving(e){this.assertRecvDirection();for(const t of e){md.debug("stopReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(e.mid)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};md.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();md.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r);for(const t of e)this._mapMidTransceiver.delete(t)}async pauseReceiving(e){}async resumeReceiving(e){}async getReceiverStats(e){this.assertRecvDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.receiver.getStats()}async receiveDataChannel({sctpStreamParameters:e,label:t,protocol:r}){this.assertRecvDirection();const{streamId:i,ordered:n,maxPacketLifeTime:s,maxRetransmits:o}=e,a={negotiated:!0,id:i,ordered:n,maxPacketLifeTime:s,maxRetransmitTime:s,maxRetransmits:o,protocol:r};md.debug("receiveDataChannel() [options:%o]",a);const c=this._pc.createDataChannel(t,a);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();const e={type:"offer",sdp:this._remoteSdp.getSdp()};md.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=od.parse(t.sdp);await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:e})}md.debug("receiveDataChannel() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setLocalDescription(t),this._hasDataChannelMediaSection=!0}return{dataChannel:c}}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=od.parse(this._pc.localDescription.sdp));const r=ld.extractDtlsParameters({sdpObject:t});r.role=e,this._remoteSdp.updateDtlsRole("client"===e?"server":"client"),await new Promise(((e,t)=>{this.safeEmit("@connect",{dtlsParameters:r},e,t)})),this._transportReady=!0}assertSendDirection(){if("send"!==this._direction)throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if("recv"!==this._direction)throw new Error('method can just be called for handlers with "recv" direction')}}rd.Chrome70=vd;var bd={},yd={};Object.defineProperty(yd,"__esModule",{value:!0}),yd.getRtpEncodings=function({offerMediaObject:e,track:t}){const r=new Set;for(const i of e.ssrcs||[]){if("msid"!==i.attribute)continue;if(i.value.split(" ")[1]===t.id){const e=i.id;r.add(e)}}if(0===r.size)throw new Error(`a=ssrc line with msid information not found [track.id:${t.id}]`);const i=new Map;for(const t of e.ssrcGroups||[]){if("FID"!==t.semantics)continue;let[e,n]=t.ssrcs.split(/\s+/);e=Number(e),n=Number(n),r.has(e)&&(r.delete(e),r.delete(n),i.set(e,n))}for(const e of r)i.set(e,null);const n=[];for(const[e,t]of i){const r={ssrc:e};t&&(r.rtx={ssrc:t}),n.push(r)}return n},yd.addLegacySimulcast=function({offerMediaObject:e,track:t,numStreams:r}){if(r<=1)throw new TypeError("numStreams must be greater than 1");let i,n,s;if(!(e.ssrcs||[]).find((e=>{if("msid"!==e.attribute)return!1;return e.value.split(" ")[1]===t.id&&(i=e.id,s=e.value.split(" ")[0],!0)})))throw new Error(`a=ssrc line with msid information not found [track.id:${t.id}]`);(e.ssrcGroups||[]).some((e=>{if("FID"!==e.semantics)return!1;const t=e.ssrcs.split(/\s+/);return Number(t[0])===i&&(n=Number(t[1]),!0)}));const o=e.ssrcs.find((e=>"cname"===e.attribute&&e.id===i));if(!o)throw new Error(`a=ssrc line with cname information not found [track.id:${t.id}]`);const a=o.value,c=[],d=[];for(let e=0;e<r;++e)c.push(i+e),n&&d.push(n+e);e.ssrcGroups=e.ssrcGroups||[],e.ssrcs=e.ssrcs||[],e.ssrcGroups.push({semantics:"SIM",ssrcs:c.join(" ")});for(const r of c)e.ssrcs.push({id:r,attribute:"cname",value:a}),e.ssrcs.push({id:r,attribute:"msid",value:`${s} ${t.id}`});for(let r=0;r<d.length;++r){const i=c[r],n=d[r];e.ssrcs.push({id:n,attribute:"cname",value:a}),e.ssrcs.push({id:n,attribute:"msid",value:`${s} ${t.id}`}),e.ssrcGroups.push({semantics:"FID",ssrcs:`${i} ${n}`})}};var wd=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),_d=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Sd=a&&a.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(null!=t)for(var i=e(t),n=0;n<i.length;n++)"default"!==i[n]&&wd(r,t,i[n]);return _d(r,t),r}}();Object.defineProperty(bd,"__esModule",{value:!0}),bd.Chrome67=void 0;const Cd=Sd(Ta),Rd=ss,kd=Sd(js),Td=Sd(Fs),Pd=Sd(za),Ed=Sd(yd),Od=Za,Dd=rc,Id=new Rd.Logger("Chrome67"),xd={OS:1024,MIS:1024};class Md extends Od.HandlerInterface{static createFactory(){return()=>new Md}constructor(){super(),this._sendStream=new MediaStream,this._mapSendLocalIdRtpSender=new Map,this._nextSendLocalId=0,this._mapRecvLocalIdInfo=new Map,this._hasDataChannelMediaSection=!1,this._nextSendSctpStreamId=0,this._transportReady=!1}get name(){return"Chrome67"}close(){if(Id.debug("close()"),this._pc)try{this._pc.close()}catch(e){}this.emit("@close")}async getNativeRtpCapabilities(){Id.debug("getNativeRtpCapabilities()");const e=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"plan-b"});try{const t=await e.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0});try{e.close()}catch(e){}const r=Cd.parse(t.sdp);return Pd.extractRtpCapabilities({sdpObject:r})}catch(t){try{e.close()}catch(e){}throw t}}async getNativeSctpCapabilities(){return Id.debug("getNativeSctpCapabilities()"),{numStreams:xd}}run({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,extendedRtpCapabilities:d}){Id.debug("run()"),this._direction=e,this._remoteSdp=new Dd.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n,planB:!0}),this._sendingRtpParametersByKind={audio:Td.getSendingRtpParameters("audio",d),video:Td.getSendingRtpParameters("video",d)},this._sendingRemoteRtpParametersByKind={audio:Td.getSendingRemoteRtpParameters("audio",d),video:Td.getSendingRemoteRtpParameters("video",d)},i.role&&"auto"!==i.role&&(this._forcedLocalDtlsRole="server"===i.role?"client":"server"),this._pc=new RTCPeerConnection({iceServers:s??[],iceTransportPolicy:o??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"plan-b",...a},c),this._pc.addEventListener("icegatheringstatechange",(()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)})),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",(()=>{this.emit("@connectionstatechange",this._pc.connectionState)})):this._pc.addEventListener("iceconnectionstatechange",(()=>{switch(Id.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.iceConnectionState){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected");break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed")}}))}async updateIceServers(e){Id.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(Id.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});Id.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};Id.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};Id.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();Id.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",t),await this._pc.setLocalDescription(t)}}async getTransportStats(){return this._pc.getStats()}async send({track:e,encodings:t,codecOptions:r,codec:i}){this.assertSendDirection(),Id.debug("send() [kind:%s, track.id:%s]",e.kind,e.id),i&&Id.warn("send() | codec selection is not available in %s handler",this.name),this._sendStream.addTrack(e),this._pc.addTrack(e,this._sendStream);let n,s=await this._pc.createOffer(),o=Cd.parse(s.sdp);const a=kd.clone(this._sendingRtpParametersByKind[e.kind]);a.codecs=Td.reduceCodecs(a.codecs);const c=kd.clone(this._sendingRemoteRtpParametersByKind[e.kind]);if(c.codecs=Td.reduceCodecs(c.codecs),this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:o}),"video"===e.kind&&t&&t.length>1&&(Id.debug("send() | enabling simulcast"),o=Cd.parse(s.sdp),n=o.media.find((e=>"video"===e.type)),Ed.addLegacySimulcast({offerMediaObject:n,track:e,numStreams:t.length}),s={type:"offer",sdp:Cd.write(o)}),Id.debug("send() | calling pc.setLocalDescription() [offer:%o]",s),await this._pc.setLocalDescription(s),o=Cd.parse(this._pc.localDescription.sdp),n=o.media.find((t=>t.type===e.kind)),a.rtcp.cname=Pd.getCname({offerMediaObject:n}),a.encodings=Ed.getRtpEncodings({offerMediaObject:n,track:e}),t)for(let e=0;e<a.encodings.length;++e)t[e]&&Object.assign(a.encodings[e],t[e]);if(a.encodings.length>1&&"video/vp8"===a.codecs[0].mimeType.toLowerCase())for(const e of a.encodings)e.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:n,offerRtpParameters:a,answerRtpParameters:c,codecOptions:r});const d={type:"answer",sdp:this._remoteSdp.getSdp()};Id.debug("send() | calling pc.setRemoteDescription() [answer:%o]",d),await this._pc.setRemoteDescription(d);const l=String(this._nextSendLocalId);this._nextSendLocalId++;const u=this._pc.getSenders().find((t=>t.track===e));return this._mapSendLocalIdRtpSender.set(l,u),{localId:l,rtpParameters:a,rtpSender:u}}async stopSending(e){this.assertSendDirection(),Id.debug("stopSending() [localId:%s]",e);const t=this._mapSendLocalIdRtpSender.get(e);if(!t)throw new Error("associated RTCRtpSender not found");this._pc.removeTrack(t),t.track&&this._sendStream.removeTrack(t.track),this._mapSendLocalIdRtpSender.delete(e);const r=await this._pc.createOffer();Id.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r);try{await this._pc.setLocalDescription(r)}catch(e){if(0===this._sendStream.getTracks().length)return void Id.warn("stopSending() | ignoring expected error due no sending tracks: %s",e.toString());throw e}if("stable"===this._pc.signalingState)return;const i={type:"answer",sdp:this._remoteSdp.getSdp()};Id.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i)}async pauseSending(e){}async resumeSending(e){}async replaceTrack(e,t){this.assertSendDirection(),t?Id.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):Id.debug("replaceTrack() [localId:%s, no track]",e);const r=this._mapSendLocalIdRtpSender.get(e);if(!r)throw new Error("associated RTCRtpSender not found");const i=r.track;await r.replaceTrack(t),i&&this._sendStream.removeTrack(i),t&&this._sendStream.addTrack(t)}async setMaxSpatialLayer(e,t){this.assertSendDirection(),Id.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);const r=this._mapSendLocalIdRtpSender.get(e);if(!r)throw new Error("associated RTCRtpSender not found");const i=r.getParameters();i.encodings.forEach(((e,r)=>{e.active=r<=t})),await r.setParameters(i)}async setRtpEncodingParameters(e,t){this.assertSendDirection(),Id.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);const r=this._mapSendLocalIdRtpSender.get(e);if(!r)throw new Error("associated RTCRtpSender not found");const i=r.getParameters();i.encodings.forEach(((e,r)=>{i.encodings[r]={...e,...t}})),await r.setParameters(i)}async getSenderStats(e){this.assertSendDirection();const t=this._mapSendLocalIdRtpSender.get(e);if(!t)throw new Error("associated RTCRtpSender not found");return t.getStats()}async sendDataChannel({ordered:e,maxPacketLifeTime:t,maxRetransmits:r,label:i,protocol:n}){this.assertSendDirection();const s={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmitTime:t,maxRetransmits:r,protocol:n};Id.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(i,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%xd.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=Cd.parse(e.sdp),r=t.media.find((e=>"application"===e.type));this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:t}),Id.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:r});const i={type:"answer",sdp:this._remoteSdp.getSdp()};Id.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._hasDataChannelMediaSection=!0}return{dataChannel:o,sctpStreamParameters:{streamId:s.id,ordered:s.ordered,maxPacketLifeTime:s.maxPacketLifeTime,maxRetransmits:s.maxRetransmits}}}async receive(e){this.assertRecvDirection();const t=[];for(const t of e){const{trackId:e,kind:r,rtpParameters:i,streamId:n}=t;Id.debug("receive() [trackId:%s, kind:%s]",e,r);const s=r;this._remoteSdp.receive({mid:s,kind:r,offerRtpParameters:i,streamId:n??i.rtcp.cname,trackId:e})}const r={type:"offer",sdp:this._remoteSdp.getSdp()};Id.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",r),await this._pc.setRemoteDescription(r);let i=await this._pc.createAnswer();const n=Cd.parse(i.sdp);for(const t of e){const{kind:e,rtpParameters:r}=t,i=e,s=n.media.find((e=>String(e.mid)===i));Pd.applyCodecParameters({offerRtpParameters:r,answerMediaObject:s})}i={type:"answer",sdp:Cd.write(n)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:n}),Id.debug("receive() | calling pc.setLocalDescription() [answer:%o]",i),await this._pc.setLocalDescription(i);for(const r of e){const{kind:e,trackId:i,rtpParameters:n}=r,s=i,o=e,a=this._pc.getReceivers().find((e=>e.track&&e.track.id===s));if(!a)throw new Error("new RTCRtpReceiver not");this._mapRecvLocalIdInfo.set(s,{mid:o,rtpParameters:n,rtpReceiver:a}),t.push({localId:s,track:a.track,rtpReceiver:a})}return t}async stopReceiving(e){this.assertRecvDirection();for(const t of e){Id.debug("stopReceiving() [localId:%s]",t);const{mid:e,rtpParameters:r}=this._mapRecvLocalIdInfo.get(t)??{};this._mapRecvLocalIdInfo.delete(t),this._remoteSdp.planBStopReceiving({mid:e,offerRtpParameters:r})}const t={type:"offer",sdp:this._remoteSdp.getSdp()};Id.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Id.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async pauseReceiving(e){}async resumeReceiving(e){}async getReceiverStats(e){this.assertRecvDirection();const{rtpReceiver:t}=this._mapRecvLocalIdInfo.get(e)??{};if(!t)throw new Error("associated RTCRtpReceiver not found");return t.getStats()}async receiveDataChannel({sctpStreamParameters:e,label:t,protocol:r}){this.assertRecvDirection();const{streamId:i,ordered:n,maxPacketLifeTime:s,maxRetransmits:o}=e,a={negotiated:!0,id:i,ordered:n,maxPacketLifeTime:s,maxRetransmitTime:s,maxRetransmits:o,protocol:r};Id.debug("receiveDataChannel() [options:%o]",a);const c=this._pc.createDataChannel(t,a);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation({oldDataChannelSpec:!0});const e={type:"offer",sdp:this._remoteSdp.getSdp()};Id.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=Cd.parse(t.sdp);await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:e})}Id.debug("receiveDataChannel() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setLocalDescription(t),this._hasDataChannelMediaSection=!0}return{dataChannel:c}}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=Cd.parse(this._pc.localDescription.sdp));const r=Pd.extractDtlsParameters({sdpObject:t});r.role=e,this._remoteSdp.updateDtlsRole("client"===e?"server":"client"),await new Promise(((e,t)=>{this.safeEmit("@connect",{dtlsParameters:r},e,t)})),this._transportReady=!0}assertSendDirection(){if("send"!==this._direction)throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if("recv"!==this._direction)throw new Error('method can just be called for handlers with "recv" direction')}}bd.Chrome67=Md;var Ld={},jd=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),Ad=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Nd=a&&a.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(null!=t)for(var i=e(t),n=0;n<i.length;n++)"default"!==i[n]&&jd(r,t,i[n]);return Ad(r,t),r}}();Object.defineProperty(Ld,"__esModule",{value:!0}),Ld.Chrome55=void 0;const Bd=Nd(Ta),Fd=ss,zd=Is,Vd=Nd(js),Ud=Nd(Fs),$d=Nd(za),Gd=Nd(yd),qd=Za,Hd=rc,Wd=new Fd.Logger("Chrome55"),Kd={OS:1024,MIS:1024};class Jd extends qd.HandlerInterface{static createFactory(){return()=>new Jd}constructor(){super(),this._sendStream=new MediaStream,this._mapSendLocalIdTrack=new Map,this._nextSendLocalId=0,this._mapRecvLocalIdInfo=new Map,this._hasDataChannelMediaSection=!1,this._nextSendSctpStreamId=0,this._transportReady=!1}get name(){return"Chrome55"}close(){if(Wd.debug("close()"),this._pc)try{this._pc.close()}catch(e){}this.emit("@close")}async getNativeRtpCapabilities(){Wd.debug("getNativeRtpCapabilities()");const e=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"plan-b"});try{const t=await e.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0});try{e.close()}catch(e){}const r=Bd.parse(t.sdp);return $d.extractRtpCapabilities({sdpObject:r})}catch(t){try{e.close()}catch(e){}throw t}}async getNativeSctpCapabilities(){return Wd.debug("getNativeSctpCapabilities()"),{numStreams:Kd}}run({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,extendedRtpCapabilities:d}){Wd.debug("run()"),this._direction=e,this._remoteSdp=new Hd.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n,planB:!0}),this._sendingRtpParametersByKind={audio:Ud.getSendingRtpParameters("audio",d),video:Ud.getSendingRtpParameters("video",d)},this._sendingRemoteRtpParametersByKind={audio:Ud.getSendingRemoteRtpParameters("audio",d),video:Ud.getSendingRemoteRtpParameters("video",d)},i.role&&"auto"!==i.role&&(this._forcedLocalDtlsRole="server"===i.role?"client":"server"),this._pc=new RTCPeerConnection({iceServers:s??[],iceTransportPolicy:o??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"plan-b",...a},c),this._pc.addEventListener("icegatheringstatechange",(()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)})),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",(()=>{this.emit("@connectionstatechange",this._pc.connectionState)})):this._pc.addEventListener("iceconnectionstatechange",(()=>{switch(Wd.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.iceConnectionState){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected");break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed")}}))}async updateIceServers(e){Wd.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(Wd.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});Wd.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};Wd.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};Wd.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();Wd.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",t),await this._pc.setLocalDescription(t)}}async getTransportStats(){return this._pc.getStats()}async send({track:e,encodings:t,codecOptions:r,codec:i}){this.assertSendDirection(),Wd.debug("send() [kind:%s, track.id:%s]",e.kind,e.id),i&&Wd.warn("send() | codec selection is not available in %s handler",this.name),this._sendStream.addTrack(e),this._pc.addStream(this._sendStream);let n,s=await this._pc.createOffer(),o=Bd.parse(s.sdp);const a=Vd.clone(this._sendingRtpParametersByKind[e.kind]);a.codecs=Ud.reduceCodecs(a.codecs);const c=Vd.clone(this._sendingRemoteRtpParametersByKind[e.kind]);if(c.codecs=Ud.reduceCodecs(c.codecs),this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:o}),"video"===e.kind&&t&&t.length>1&&(Wd.debug("send() | enabling simulcast"),o=Bd.parse(s.sdp),n=o.media.find((e=>"video"===e.type)),Gd.addLegacySimulcast({offerMediaObject:n,track:e,numStreams:t.length}),s={type:"offer",sdp:Bd.write(o)}),Wd.debug("send() | calling pc.setLocalDescription() [offer:%o]",s),await this._pc.setLocalDescription(s),o=Bd.parse(this._pc.localDescription.sdp),n=o.media.find((t=>t.type===e.kind)),a.rtcp.cname=$d.getCname({offerMediaObject:n}),a.encodings=Gd.getRtpEncodings({offerMediaObject:n,track:e}),t)for(let e=0;e<a.encodings.length;++e)t[e]&&Object.assign(a.encodings[e],t[e]);if(a.encodings.length>1&&"video/vp8"===a.codecs[0].mimeType.toLowerCase())for(const e of a.encodings)e.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:n,offerRtpParameters:a,answerRtpParameters:c,codecOptions:r});const d={type:"answer",sdp:this._remoteSdp.getSdp()};Wd.debug("send() | calling pc.setRemoteDescription() [answer:%o]",d),await this._pc.setRemoteDescription(d);const l=String(this._nextSendLocalId);return this._nextSendLocalId++,this._mapSendLocalIdTrack.set(l,e),{localId:l,rtpParameters:a}}async stopSending(e){this.assertSendDirection(),Wd.debug("stopSending() [localId:%s]",e);const t=this._mapSendLocalIdTrack.get(e);if(!t)throw new Error("track not found");this._mapSendLocalIdTrack.delete(e),this._sendStream.removeTrack(t),this._pc.addStream(this._sendStream);const r=await this._pc.createOffer();Wd.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r);try{await this._pc.setLocalDescription(r)}catch(e){if(0===this._sendStream.getTracks().length)return void Wd.warn("stopSending() | ignoring expected error due no sending tracks: %s",e.toString());throw e}if("stable"===this._pc.signalingState)return;const i={type:"answer",sdp:this._remoteSdp.getSdp()};Wd.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i)}async pauseSending(e){}async resumeSending(e){}async replaceTrack(e,t){throw new zd.UnsupportedError("not implemented")}async setMaxSpatialLayer(e,t){throw new zd.UnsupportedError(" not implemented")}async setRtpEncodingParameters(e,t){throw new zd.UnsupportedError("not supported")}async getSenderStats(e){throw new zd.UnsupportedError("not implemented")}async sendDataChannel({ordered:e,maxPacketLifeTime:t,maxRetransmits:r,label:i,protocol:n}){this.assertSendDirection();const s={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmitTime:t,maxRetransmits:r,protocol:n};Wd.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(i,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%Kd.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=Bd.parse(e.sdp),r=t.media.find((e=>"application"===e.type));this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:t}),Wd.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:r});const i={type:"answer",sdp:this._remoteSdp.getSdp()};Wd.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._hasDataChannelMediaSection=!0}return{dataChannel:o,sctpStreamParameters:{streamId:s.id,ordered:s.ordered,maxPacketLifeTime:s.maxPacketLifeTime,maxRetransmits:s.maxRetransmits}}}async receive(e){this.assertRecvDirection();const t=[];for(const t of e){const{trackId:e,kind:r,rtpParameters:i,streamId:n}=t;Wd.debug("receive() [trackId:%s, kind:%s]",e,r);const s=r;this._remoteSdp.receive({mid:s,kind:r,offerRtpParameters:i,streamId:n??i.rtcp.cname,trackId:e})}const r={type:"offer",sdp:this._remoteSdp.getSdp()};Wd.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",r),await this._pc.setRemoteDescription(r);let i=await this._pc.createAnswer();const n=Bd.parse(i.sdp);for(const t of e){const{kind:e,rtpParameters:r}=t,i=e,s=n.media.find((e=>String(e.mid)===i));$d.applyCodecParameters({offerRtpParameters:r,answerMediaObject:s})}i={type:"answer",sdp:Bd.write(n)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:n}),Wd.debug("receive() | calling pc.setLocalDescription() [answer:%o]",i),await this._pc.setLocalDescription(i);for(const r of e){const{kind:e,trackId:i,rtpParameters:n}=r,s=e,o=i,a=r.streamId??n.rtcp.cname,c=this._pc.getRemoteStreams().find((e=>e.id===a)).getTrackById(o);if(!c)throw new Error("remote track not found");this._mapRecvLocalIdInfo.set(o,{mid:s,rtpParameters:n}),t.push({localId:o,track:c})}return t}async stopReceiving(e){this.assertRecvDirection();for(const t of e){Wd.debug("stopReceiving() [localId:%s]",t);const{mid:e,rtpParameters:r}=this._mapRecvLocalIdInfo.get(t)??{};this._mapRecvLocalIdInfo.delete(t),this._remoteSdp.planBStopReceiving({mid:e,offerRtpParameters:r})}const t={type:"offer",sdp:this._remoteSdp.getSdp()};Wd.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Wd.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async pauseReceiving(e){}async resumeReceiving(e){}async getReceiverStats(e){throw new zd.UnsupportedError("not implemented")}async receiveDataChannel({sctpStreamParameters:e,label:t,protocol:r}){this.assertRecvDirection();const{streamId:i,ordered:n,maxPacketLifeTime:s,maxRetransmits:o}=e,a={negotiated:!0,id:i,ordered:n,maxPacketLifeTime:s,maxRetransmitTime:s,maxRetransmits:o,protocol:r};Wd.debug("receiveDataChannel() [options:%o]",a);const c=this._pc.createDataChannel(t,a);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation({oldDataChannelSpec:!0});const e={type:"offer",sdp:this._remoteSdp.getSdp()};Wd.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=Bd.parse(t.sdp);await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:e})}Wd.debug("receiveDataChannel() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setLocalDescription(t),this._hasDataChannelMediaSection=!0}return{dataChannel:c}}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=Bd.parse(this._pc.localDescription.sdp));const r=$d.extractDtlsParameters({sdpObject:t});r.role=e,this._remoteSdp.updateDtlsRole("client"===e?"server":"client"),await new Promise(((e,t)=>{this.safeEmit("@connect",{dtlsParameters:r},e,t)})),this._transportReady=!0}assertSendDirection(){if("send"!==this._direction)throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if("recv"!==this._direction)throw new Error('method can just be called for handlers with "recv" direction')}}Ld.Chrome55=Jd;var Xd={},Qd=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),Zd=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Yd=a&&a.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(null!=t)for(var i=e(t),n=0;n<i.length;n++)"default"!==i[n]&&Qd(r,t,i[n]);return Zd(r,t),r}}();Object.defineProperty(Xd,"__esModule",{value:!0}),Xd.Firefox120=void 0;const el=Yd(Ta),tl=ss,rl=Is,il=Yd(js),nl=Yd(Fs),sl=Yd(za),ol=Yd(Ja),al=Za,cl=rc,dl=bc,ll=new tl.Logger("Firefox120"),ul={OS:16,MIS:2048};class pl extends al.HandlerInterface{static createFactory(){return()=>new pl}constructor(){super(),this._closed=!1,this._mapMidTransceiver=new Map,this._sendStream=new MediaStream,this._hasDataChannelMediaSection=!1,this._nextSendSctpStreamId=0,this._transportReady=!1}get name(){return"Firefox120"}close(){if(ll.debug("close()"),!this._closed){if(this._closed=!0,this._pc)try{this._pc.close()}catch(e){}this.emit("@close")}}async getNativeRtpCapabilities(){ll.debug("getNativeRtpCapabilities()");const e=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"}),t=document.createElement("canvas");t.getContext("2d");const r=t.captureStream().getVideoTracks()[0];try{e.addTransceiver("audio",{direction:"sendrecv"}),e.addTransceiver(r,{direction:"sendrecv",sendEncodings:[{rid:"r0",maxBitrate:1e5},{rid:"r1",maxBitrate:5e5}]});const i=await e.createOffer();try{t.remove()}catch(e){}try{r.stop()}catch(e){}try{e.close()}catch(e){}const n=el.parse(i.sdp);return sl.extractRtpCapabilities({sdpObject:n})}catch(i){try{t.remove()}catch(e){}try{r.stop()}catch(e){}try{e.close()}catch(e){}throw i}}async getNativeSctpCapabilities(){return ll.debug("getNativeSctpCapabilities()"),{numStreams:ul}}run({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,extendedRtpCapabilities:d}){this.assertNotClosed(),ll.debug("run()"),this._direction=e,this._remoteSdp=new cl.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n}),this._sendingRtpParametersByKind={audio:nl.getSendingRtpParameters("audio",d),video:nl.getSendingRtpParameters("video",d)},this._sendingRemoteRtpParametersByKind={audio:nl.getSendingRemoteRtpParameters("audio",d),video:nl.getSendingRemoteRtpParameters("video",d)},this._pc=new RTCPeerConnection({iceServers:s??[],iceTransportPolicy:o??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...a},c),this._pc.addEventListener("icegatheringstatechange",(()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)})),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",(()=>{this.emit("@connectionstatechange",this._pc.connectionState)})):this._pc.addEventListener("iceconnectionstatechange",(()=>{switch(ll.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.iceConnectionState){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected");break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed")}}))}async updateIceServers(e){throw this.assertNotClosed(),new rl.UnsupportedError("not supported")}async restartIce(e){if(this.assertNotClosed(),ll.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});ll.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};ll.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};ll.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();ll.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",t),await this._pc.setLocalDescription(t)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:e,encodings:t,codecOptions:r,codec:i,onRtpSender:n}){this.assertNotClosed(),this.assertSendDirection(),ll.debug("send() [kind:%s, track.id:%s]",e.kind,e.id),t&&t.length>1&&t.forEach(((e,t)=>{e.rid=`r${t}`}));const s=il.clone(this._sendingRtpParametersByKind[e.kind]);s.codecs=nl.reduceCodecs(s.codecs,i);const o=il.clone(this._sendingRemoteRtpParametersByKind[e.kind]);o.codecs=nl.reduceCodecs(o.codecs,i);const a=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream],sendEncodings:t});n&&n(a.sender);const c=await this._pc.createOffer();let d=el.parse(c.sdp);this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:d});const l=(0,dl.parse)((t??[{}])[0].scalabilityMode);ll.debug("send() | calling pc.setLocalDescription() [offer:%o]",c),await this._pc.setLocalDescription(c);const u=a.mid;s.mid=u,d=el.parse(this._pc.localDescription.sdp);const p=d.media[d.media.length-1];if(s.rtcp.cname=sl.getCname({offerMediaObject:p}),t)if(1===t.length){const e=ol.getRtpEncodings({offerMediaObject:p});Object.assign(e[0],t[0]),s.encodings=e}else s.encodings=t;else s.encodings=ol.getRtpEncodings({offerMediaObject:p});if(s.encodings.length>1&&("video/vp8"===s.codecs[0].mimeType.toLowerCase()||"video/h264"===s.codecs[0].mimeType.toLowerCase()))for(const e of s.encodings)e.scalabilityMode?e.scalabilityMode=`L1T${l.temporalLayers}`:e.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:p,offerRtpParameters:s,answerRtpParameters:o,codecOptions:r,extmapAllowMixed:!0});const h={type:"answer",sdp:this._remoteSdp.getSdp()};return ll.debug("send() | calling pc.setRemoteDescription() [answer:%o]",h),await this._pc.setRemoteDescription(h),this._mapMidTransceiver.set(u,a),{localId:u,rtpParameters:s,rtpSender:a.sender}}async stopSending(e){if(this.assertSendDirection(),ll.debug("stopSending() [localId:%s]",e),this._closed)return;const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated transceiver not found");t.sender.replaceTrack(null),this._pc.removeTrack(t.sender),this._remoteSdp.disableMediaSection(t.mid);const r=await this._pc.createOffer();ll.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const i={type:"answer",sdp:this._remoteSdp.getSdp()};ll.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),ll.debug("pauseSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="inactive",this._remoteSdp.pauseMediaSection(e);const r=await this._pc.createOffer();ll.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const i={type:"answer",sdp:this._remoteSdp.getSdp()};ll.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),ll.debug("resumeSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="sendonly",this._remoteSdp.resumeSendingMediaSection(e);const r=await this._pc.createOffer();ll.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const i={type:"answer",sdp:this._remoteSdp.getSdp()};ll.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?ll.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):ll.debug("replaceTrack() [localId:%s, no track]",e);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");await r.sender.replaceTrack(t)}async setMaxSpatialLayer(e,t){this.assertNotClosed(),this.assertSendDirection(),ll.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated transceiver not found");const i=r.sender.getParameters();i.encodings.forEach(((e,r)=>{e.active=r<=t})),await r.sender.setParameters(i),this._remoteSdp.muxMediaSectionSimulcast(e,i.encodings);const n=await this._pc.createOffer();ll.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);const s={type:"answer",sdp:this._remoteSdp.getSdp()};ll.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),ll.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const i=r.sender.getParameters();i.encodings.forEach(((e,r)=>{i.encodings[r]={...e,...t}})),await r.sender.setParameters(i),this._remoteSdp.muxMediaSectionSimulcast(e,i.encodings);const n=await this._pc.createOffer();ll.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);const s={type:"answer",sdp:this._remoteSdp.getSdp()};ll.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async getSenderStats(e){this.assertNotClosed(),this.assertSendDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.sender.getStats()}async sendDataChannel({ordered:e,maxPacketLifeTime:t,maxRetransmits:r,label:i,protocol:n}){this.assertNotClosed(),this.assertSendDirection();const s={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmits:r,protocol:n};ll.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(i,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%ul.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=el.parse(e.sdp),r=t.media.find((e=>"application"===e.type));this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:t}),ll.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:r});const i={type:"answer",sdp:this._remoteSdp.getSdp()};ll.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._hasDataChannelMediaSection=!0}return{dataChannel:o,sctpStreamParameters:{streamId:s.id,ordered:s.ordered,maxPacketLifeTime:s.maxPacketLifeTime,maxRetransmits:s.maxRetransmits}}}async receive(e){this.assertNotClosed(),this.assertRecvDirection();const t=[],r=new Map;for(const t of e){const{trackId:e,kind:i,rtpParameters:n,streamId:s}=t;ll.debug("receive() [trackId:%s, kind:%s]",e,i);const o=n.mid??String(this._mapMidTransceiver.size);r.set(e,o),this._remoteSdp.receive({mid:o,kind:i,offerRtpParameters:n,streamId:s??n.rtcp.cname,trackId:e})}const i={type:"offer",sdp:this._remoteSdp.getSdp()};ll.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",i),await this._pc.setRemoteDescription(i);for(const t of e){const{trackId:e,onRtpReceiver:i}=t;if(i){const t=r.get(e),n=this._pc.getTransceivers().find((e=>e.mid===t));if(!n)throw new Error("transceiver not found");i(n.receiver)}}let n=await this._pc.createAnswer();const s=el.parse(n.sdp);for(const t of e){const{trackId:e,rtpParameters:i}=t,o=r.get(e),a=s.media.find((e=>String(e.mid)===o));sl.applyCodecParameters({offerRtpParameters:i,answerMediaObject:a}),n={type:"answer",sdp:el.write(s)}}this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:s}),ll.debug("receive() | calling pc.setLocalDescription() [answer:%o]",n),await this._pc.setLocalDescription(n);for(const i of e){const{trackId:e}=i,n=r.get(e),s=this._pc.getTransceivers().find((e=>e.mid===n));if(!s)throw new Error("new RTCRtpTransceiver not found");this._mapMidTransceiver.set(n,s),t.push({localId:n,track:s.receiver.track,rtpReceiver:s.receiver})}return t}async stopReceiving(e){if(this.assertRecvDirection(),this._closed)return;for(const t of e){ll.debug("stopReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(e.mid)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};ll.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();ll.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r);for(const t of e)this._mapMidTransceiver.delete(t)}async pauseReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(const t of e){ll.debug("pauseReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="inactive",this._remoteSdp.pauseMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};ll.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();ll.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async resumeReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(const t of e){ll.debug("resumeReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};ll.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();ll.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async getReceiverStats(e){this.assertRecvDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.receiver.getStats()}async receiveDataChannel({sctpStreamParameters:e,label:t,protocol:r}){this.assertNotClosed(),this.assertRecvDirection();const{streamId:i,ordered:n,maxPacketLifeTime:s,maxRetransmits:o}=e,a={negotiated:!0,id:i,ordered:n,maxPacketLifeTime:s,maxRetransmits:o,protocol:r};ll.debug("receiveDataChannel() [options:%o]",a);const c=this._pc.createDataChannel(t,a);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();const e={type:"offer",sdp:this._remoteSdp.getSdp()};ll.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=el.parse(t.sdp);await this.setupTransport({localDtlsRole:"client",localSdpObject:e})}ll.debug("receiveDataChannel() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setLocalDescription(t),this._hasDataChannelMediaSection=!0}return{dataChannel:c}}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=el.parse(this._pc.localDescription.sdp));const r=sl.extractDtlsParameters({sdpObject:t});r.role=e,this._remoteSdp.updateDtlsRole("client"===e?"server":"client"),await new Promise(((e,t)=>{this.safeEmit("@connect",{dtlsParameters:r},e,t)})),this._transportReady=!0}assertNotClosed(){if(this._closed)throw new rl.InvalidStateError("method called in a closed handler")}assertSendDirection(){if("send"!==this._direction)throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if("recv"!==this._direction)throw new Error('method can just be called for handlers with "recv" direction')}}Xd.Firefox120=pl;var hl={},fl=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),ml=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),gl=a&&a.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(null!=t)for(var i=e(t),n=0;n<i.length;n++)"default"!==i[n]&&fl(r,t,i[n]);return ml(r,t),r}}();Object.defineProperty(hl,"__esModule",{value:!0}),hl.Firefox60=void 0;const vl=gl(Ta),bl=ss,yl=Is,wl=gl(js),_l=gl(Fs),Sl=gl(za),Cl=gl(Ja),Rl=Za,kl=rc,Tl=bc,Pl=new bl.Logger("Firefox60"),El={OS:16,MIS:2048};class Ol extends Rl.HandlerInterface{static createFactory(){return()=>new Ol}constructor(){super(),this._closed=!1,this._mapMidTransceiver=new Map,this._sendStream=new MediaStream,this._hasDataChannelMediaSection=!1,this._nextSendSctpStreamId=0,this._transportReady=!1}get name(){return"Firefox60"}close(){if(Pl.debug("close()"),!this._closed){if(this._closed=!0,this._pc)try{this._pc.close()}catch(e){}this.emit("@close")}}async getNativeRtpCapabilities(){Pl.debug("getNativeRtpCapabilities()");const e=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"}),t=document.createElement("canvas");t.getContext("2d");const r=t.captureStream().getVideoTracks()[0];try{e.addTransceiver("audio",{direction:"sendrecv"});const i=e.addTransceiver(r,{direction:"sendrecv"}),n=i.sender.getParameters(),s=[{rid:"r0",maxBitrate:1e5},{rid:"r1",maxBitrate:5e5}];n.encodings=s,await i.sender.setParameters(n);const o=await e.createOffer();try{t.remove()}catch(e){}try{r.stop()}catch(e){}try{e.close()}catch(e){}const a=vl.parse(o.sdp);return Sl.extractRtpCapabilities({sdpObject:a})}catch(i){try{t.remove()}catch(e){}try{r.stop()}catch(e){}try{e.close()}catch(e){}throw i}}async getNativeSctpCapabilities(){return Pl.debug("getNativeSctpCapabilities()"),{numStreams:El}}run({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,extendedRtpCapabilities:d}){this.assertNotClosed(),Pl.debug("run()"),this._direction=e,this._remoteSdp=new kl.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n}),this._sendingRtpParametersByKind={audio:_l.getSendingRtpParameters("audio",d),video:_l.getSendingRtpParameters("video",d)},this._sendingRemoteRtpParametersByKind={audio:_l.getSendingRemoteRtpParameters("audio",d),video:_l.getSendingRemoteRtpParameters("video",d)},this._pc=new RTCPeerConnection({iceServers:s??[],iceTransportPolicy:o??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...a},c),this._pc.addEventListener("icegatheringstatechange",(()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)})),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",(()=>{this.emit("@connectionstatechange",this._pc.connectionState)})):this._pc.addEventListener("iceconnectionstatechange",(()=>{switch(Pl.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.iceConnectionState){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected");break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed")}}))}async updateIceServers(e){throw this.assertNotClosed(),new yl.UnsupportedError("not supported")}async restartIce(e){if(this.assertNotClosed(),Pl.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});Pl.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};Pl.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};Pl.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();Pl.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",t),await this._pc.setLocalDescription(t)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:e,encodings:t,codecOptions:r,codec:i}){this.assertNotClosed(),this.assertSendDirection(),Pl.debug("send() [kind:%s, track.id:%s]",e.kind,e.id),t&&((t=wl.clone(t)).forEach(((e,t)=>{e.rid=`r${t}`})),t.reverse());const n=wl.clone(this._sendingRtpParametersByKind[e.kind]);n.codecs=_l.reduceCodecs(n.codecs,i);const s=wl.clone(this._sendingRemoteRtpParametersByKind[e.kind]);s.codecs=_l.reduceCodecs(s.codecs,i);const o=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream]});if(t){const e=o.sender.getParameters();e.encodings=t,await o.sender.setParameters(e)}const a=await this._pc.createOffer();let c=vl.parse(a.sdp);this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:c});const d=(0,Tl.parse)((t??[{}])[0].scalabilityMode);Pl.debug("send() | calling pc.setLocalDescription() [offer:%o]",a),await this._pc.setLocalDescription(a);const l=o.mid;n.mid=l,c=vl.parse(this._pc.localDescription.sdp);const u=c.media[c.media.length-1];if(n.rtcp.cname=Sl.getCname({offerMediaObject:u}),t)if(1===t.length){const e=Cl.getRtpEncodings({offerMediaObject:u});Object.assign(e[0],t[0]),n.encodings=e}else n.encodings=t.reverse();else n.encodings=Cl.getRtpEncodings({offerMediaObject:u});if(n.encodings.length>1&&("video/vp8"===n.codecs[0].mimeType.toLowerCase()||"video/h264"===n.codecs[0].mimeType.toLowerCase()))for(const e of n.encodings)e.scalabilityMode?e.scalabilityMode=`L1T${d.temporalLayers}`:e.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:u,offerRtpParameters:n,answerRtpParameters:s,codecOptions:r,extmapAllowMixed:!0});const p={type:"answer",sdp:this._remoteSdp.getSdp()};return Pl.debug("send() | calling pc.setRemoteDescription() [answer:%o]",p),await this._pc.setRemoteDescription(p),this._mapMidTransceiver.set(l,o),{localId:l,rtpParameters:n,rtpSender:o.sender}}async stopSending(e){if(this.assertSendDirection(),Pl.debug("stopSending() [localId:%s]",e),this._closed)return;const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated transceiver not found");t.sender.replaceTrack(null),this._pc.removeTrack(t.sender),this._remoteSdp.disableMediaSection(t.mid);const r=await this._pc.createOffer();Pl.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const i={type:"answer",sdp:this._remoteSdp.getSdp()};Pl.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),Pl.debug("pauseSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="inactive",this._remoteSdp.pauseMediaSection(e);const r=await this._pc.createOffer();Pl.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const i={type:"answer",sdp:this._remoteSdp.getSdp()};Pl.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),Pl.debug("resumeSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="sendonly",this._remoteSdp.resumeSendingMediaSection(e);const r=await this._pc.createOffer();Pl.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const i={type:"answer",sdp:this._remoteSdp.getSdp()};Pl.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?Pl.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):Pl.debug("replaceTrack() [localId:%s, no track]",e);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");await r.sender.replaceTrack(t)}async setMaxSpatialLayer(e,t){this.assertNotClosed(),this.assertSendDirection(),Pl.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated transceiver not found");const i=r.sender.getParameters();t=i.encodings.length-1-t,i.encodings.forEach(((e,r)=>{e.active=r>=t})),await r.sender.setParameters(i),this._remoteSdp.muxMediaSectionSimulcast(e,i.encodings);const n=await this._pc.createOffer();Pl.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);const s={type:"answer",sdp:this._remoteSdp.getSdp()};Pl.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),Pl.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const i=r.sender.getParameters();i.encodings.forEach(((e,r)=>{i.encodings[r]={...e,...t}})),await r.sender.setParameters(i),this._remoteSdp.muxMediaSectionSimulcast(e,i.encodings);const n=await this._pc.createOffer();Pl.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);const s={type:"answer",sdp:this._remoteSdp.getSdp()};Pl.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async getSenderStats(e){this.assertNotClosed(),this.assertSendDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.sender.getStats()}async sendDataChannel({ordered:e,maxPacketLifeTime:t,maxRetransmits:r,label:i,protocol:n}){this.assertNotClosed(),this.assertSendDirection();const s={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmits:r,protocol:n};Pl.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(i,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%El.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=vl.parse(e.sdp),r=t.media.find((e=>"application"===e.type));this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:t}),Pl.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:r});const i={type:"answer",sdp:this._remoteSdp.getSdp()};Pl.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._hasDataChannelMediaSection=!0}return{dataChannel:o,sctpStreamParameters:{streamId:s.id,ordered:s.ordered,maxPacketLifeTime:s.maxPacketLifeTime,maxRetransmits:s.maxRetransmits}}}async receive(e){this.assertNotClosed(),this.assertRecvDirection();const t=[],r=new Map;for(const t of e){const{trackId:e,kind:i,rtpParameters:n,streamId:s}=t;Pl.debug("receive() [trackId:%s, kind:%s]",e,i);const o=n.mid??String(this._mapMidTransceiver.size);r.set(e,o),this._remoteSdp.receive({mid:o,kind:i,offerRtpParameters:n,streamId:s??n.rtcp.cname,trackId:e})}const i={type:"offer",sdp:this._remoteSdp.getSdp()};Pl.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",i),await this._pc.setRemoteDescription(i);let n=await this._pc.createAnswer();const s=vl.parse(n.sdp);for(const t of e){const{trackId:e,rtpParameters:i}=t,o=r.get(e),a=s.media.find((e=>String(e.mid)===o));Sl.applyCodecParameters({offerRtpParameters:i,answerMediaObject:a}),n={type:"answer",sdp:vl.write(s)}}this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:s}),Pl.debug("receive() | calling pc.setLocalDescription() [answer:%o]",n),await this._pc.setLocalDescription(n);for(const i of e){const{trackId:e}=i,n=r.get(e),s=this._pc.getTransceivers().find((e=>e.mid===n));if(!s)throw new Error("new RTCRtpTransceiver not found");this._mapMidTransceiver.set(n,s),t.push({localId:n,track:s.receiver.track,rtpReceiver:s.receiver})}return t}async stopReceiving(e){if(this.assertRecvDirection(),this._closed)return;for(const t of e){Pl.debug("stopReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(e.mid)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};Pl.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Pl.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r);for(const t of e)this._mapMidTransceiver.delete(t)}async pauseReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(const t of e){Pl.debug("pauseReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="inactive",this._remoteSdp.pauseMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};Pl.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Pl.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async resumeReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(const t of e){Pl.debug("resumeReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};Pl.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Pl.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async getReceiverStats(e){this.assertRecvDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.receiver.getStats()}async receiveDataChannel({sctpStreamParameters:e,label:t,protocol:r}){this.assertNotClosed(),this.assertRecvDirection();const{streamId:i,ordered:n,maxPacketLifeTime:s,maxRetransmits:o}=e,a={negotiated:!0,id:i,ordered:n,maxPacketLifeTime:s,maxRetransmits:o,protocol:r};Pl.debug("receiveDataChannel() [options:%o]",a);const c=this._pc.createDataChannel(t,a);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();const e={type:"offer",sdp:this._remoteSdp.getSdp()};Pl.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=vl.parse(t.sdp);await this.setupTransport({localDtlsRole:"client",localSdpObject:e})}Pl.debug("receiveDataChannel() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setLocalDescription(t),this._hasDataChannelMediaSection=!0}return{dataChannel:c}}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=vl.parse(this._pc.localDescription.sdp));const r=Sl.extractDtlsParameters({sdpObject:t});r.role=e,this._remoteSdp.updateDtlsRole("client"===e?"server":"client"),await new Promise(((e,t)=>{this.safeEmit("@connect",{dtlsParameters:r},e,t)})),this._transportReady=!0}assertNotClosed(){if(this._closed)throw new yl.InvalidStateError("method called in a closed handler")}assertSendDirection(){if("send"!==this._direction)throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if("recv"!==this._direction)throw new Error('method can just be called for handlers with "recv" direction')}}hl.Firefox60=Ol;var Dl={},Il=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),xl=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Ml=a&&a.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(null!=t)for(var i=e(t),n=0;n<i.length;n++)"default"!==i[n]&&Il(r,t,i[n]);return xl(r,t),r}}();Object.defineProperty(Dl,"__esModule",{value:!0});var Ll=Dl.Safari12=void 0;const jl=Ml(Ta),Al=ss,Nl=Ml(js),Bl=Ml(Fs),Fl=Ml(za),zl=Ml(Ja),Vl=Ml(Xa),Ul=Is,$l=Za,Gl=rc,ql=bc,Hl=new Al.Logger("Safari12"),Wl={OS:1024,MIS:1024};class Kl extends $l.HandlerInterface{static createFactory(){return()=>new Kl}constructor(){super(),this._closed=!1,this._mapMidTransceiver=new Map,this._sendStream=new MediaStream,this._hasDataChannelMediaSection=!1,this._nextSendSctpStreamId=0,this._transportReady=!1}get name(){return"Safari12"}close(){if(Hl.debug("close()"),!this._closed){if(this._closed=!0,this._pc)try{this._pc.close()}catch(e){}this.emit("@close")}}async getNativeRtpCapabilities(){Hl.debug("getNativeRtpCapabilities()");const e=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"});try{e.addTransceiver("audio"),e.addTransceiver("video");const t=await e.createOffer();try{e.close()}catch(e){}const r=jl.parse(t.sdp),i=Fl.extractRtpCapabilities({sdpObject:r});return Vl.addNackSuppportForOpus(i),i}catch(t){try{e.close()}catch(e){}throw t}}async getNativeSctpCapabilities(){return Hl.debug("getNativeSctpCapabilities()"),{numStreams:Wl}}run({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,extendedRtpCapabilities:d}){this.assertNotClosed(),Hl.debug("run()"),this._direction=e,this._remoteSdp=new Gl.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n}),this._sendingRtpParametersByKind={audio:Bl.getSendingRtpParameters("audio",d),video:Bl.getSendingRtpParameters("video",d)},this._sendingRemoteRtpParametersByKind={audio:Bl.getSendingRemoteRtpParameters("audio",d),video:Bl.getSendingRemoteRtpParameters("video",d)},i.role&&"auto"!==i.role&&(this._forcedLocalDtlsRole="server"===i.role?"client":"server"),this._pc=new RTCPeerConnection({iceServers:s??[],iceTransportPolicy:o??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...a},c),this._pc.addEventListener("icegatheringstatechange",(()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)})),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",(()=>{this.emit("@connectionstatechange",this._pc.connectionState)})):this._pc.addEventListener("iceconnectionstatechange",(()=>{switch(Hl.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.iceConnectionState){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected");break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed")}}))}async updateIceServers(e){this.assertNotClosed(),Hl.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(this.assertNotClosed(),Hl.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});Hl.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};Hl.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};Hl.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();Hl.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",t),await this._pc.setLocalDescription(t)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:e,encodings:t,codecOptions:r,codec:i,onRtpSender:n}){this.assertNotClosed(),this.assertSendDirection(),Hl.debug("send() [kind:%s, track.id:%s]",e.kind,e.id);const s=Nl.clone(this._sendingRtpParametersByKind[e.kind]);s.codecs=Bl.reduceCodecs(s.codecs,i);const o=Nl.clone(this._sendingRemoteRtpParametersByKind[e.kind]);o.codecs=Bl.reduceCodecs(o.codecs,i);const a=this._remoteSdp.getNextMediaSectionIdx(),c=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream]});n&&n(c.sender);let d,l=await this._pc.createOffer(),u=jl.parse(l.sdp);this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:u});const p=(0,ql.parse)((t??[{}])[0].scalabilityMode);t&&t.length>1&&(Hl.debug("send() | enabling legacy simulcast"),u=jl.parse(l.sdp),d=u.media[a.idx],zl.addLegacySimulcast({offerMediaObject:d,numStreams:t.length}),l={type:"offer",sdp:jl.write(u)}),Hl.debug("send() | calling pc.setLocalDescription() [offer:%o]",l),await this._pc.setLocalDescription(l);const h=c.mid;if(s.mid=h,u=jl.parse(this._pc.localDescription.sdp),d=u.media[a.idx],s.rtcp.cname=Fl.getCname({offerMediaObject:d}),s.encodings=zl.getRtpEncodings({offerMediaObject:d}),t)for(let e=0;e<s.encodings.length;++e)t[e]&&Object.assign(s.encodings[e],t[e]);if(s.encodings.length>1&&("video/vp8"===s.codecs[0].mimeType.toLowerCase()||"video/h264"===s.codecs[0].mimeType.toLowerCase()))for(const e of s.encodings)e.scalabilityMode?e.scalabilityMode=`L1T${p.temporalLayers}`:e.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:d,reuseMid:a.reuseMid,offerRtpParameters:s,answerRtpParameters:o,codecOptions:r});const f={type:"answer",sdp:this._remoteSdp.getSdp()};return Hl.debug("send() | calling pc.setRemoteDescription() [answer:%o]",f),await this._pc.setRemoteDescription(f),this._mapMidTransceiver.set(h,c),{localId:h,rtpParameters:s,rtpSender:c.sender}}async stopSending(e){if(this.assertSendDirection(),this._closed)return;Hl.debug("stopSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.sender.replaceTrack(null),this._pc.removeTrack(t.sender);if(this._remoteSdp.closeMediaSection(t.mid))try{t.stop()}catch(e){}const r=await this._pc.createOffer();Hl.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const i={type:"answer",sdp:this._remoteSdp.getSdp()};Hl.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),Hl.debug("pauseSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="inactive",this._remoteSdp.pauseMediaSection(e);const r=await this._pc.createOffer();Hl.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const i={type:"answer",sdp:this._remoteSdp.getSdp()};Hl.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),Hl.debug("resumeSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="sendonly",this._remoteSdp.resumeSendingMediaSection(e);const r=await this._pc.createOffer();Hl.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const i={type:"answer",sdp:this._remoteSdp.getSdp()};Hl.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?Hl.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):Hl.debug("replaceTrack() [localId:%s, no track]",e);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");await r.sender.replaceTrack(t)}async setMaxSpatialLayer(e,t){this.assertNotClosed(),this.assertSendDirection(),Hl.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const i=r.sender.getParameters();i.encodings.forEach(((e,r)=>{e.active=r<=t})),await r.sender.setParameters(i),this._remoteSdp.muxMediaSectionSimulcast(e,i.encodings);const n=await this._pc.createOffer();Hl.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);const s={type:"answer",sdp:this._remoteSdp.getSdp()};Hl.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),Hl.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const i=r.sender.getParameters();i.encodings.forEach(((e,r)=>{i.encodings[r]={...e,...t}})),await r.sender.setParameters(i),this._remoteSdp.muxMediaSectionSimulcast(e,i.encodings);const n=await this._pc.createOffer();Hl.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);const s={type:"answer",sdp:this._remoteSdp.getSdp()};Hl.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async getSenderStats(e){this.assertNotClosed(),this.assertSendDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.sender.getStats()}async sendDataChannel({ordered:e,maxPacketLifeTime:t,maxRetransmits:r,label:i,protocol:n}){this.assertNotClosed(),this.assertSendDirection();const s={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmits:r,protocol:n};Hl.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(i,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%Wl.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=jl.parse(e.sdp),r=t.media.find((e=>"application"===e.type));this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:t}),Hl.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:r});const i={type:"answer",sdp:this._remoteSdp.getSdp()};Hl.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._hasDataChannelMediaSection=!0}return{dataChannel:o,sctpStreamParameters:{streamId:s.id,ordered:s.ordered,maxPacketLifeTime:s.maxPacketLifeTime,maxRetransmits:s.maxRetransmits}}}async receive(e){this.assertNotClosed(),this.assertRecvDirection();const t=[],r=new Map;for(const t of e){const{trackId:e,kind:i,rtpParameters:n,streamId:s}=t;Hl.debug("receive() [trackId:%s, kind:%s]",e,i);const o=n.mid??String(this._mapMidTransceiver.size);r.set(e,o),this._remoteSdp.receive({mid:o,kind:i,offerRtpParameters:n,streamId:s??n.rtcp.cname,trackId:e})}const i={type:"offer",sdp:this._remoteSdp.getSdp()};Hl.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",i),await this._pc.setRemoteDescription(i);for(const t of e){const{trackId:e,onRtpReceiver:i}=t;if(i){const t=r.get(e),n=this._pc.getTransceivers().find((e=>e.mid===t));if(!n)throw new Error("transceiver not found");i(n.receiver)}}let n=await this._pc.createAnswer();const s=jl.parse(n.sdp);for(const t of e){const{trackId:e,rtpParameters:i}=t,n=r.get(e),o=s.media.find((e=>String(e.mid)===n));Fl.applyCodecParameters({offerRtpParameters:i,answerMediaObject:o})}n={type:"answer",sdp:jl.write(s)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:s}),Hl.debug("receive() | calling pc.setLocalDescription() [answer:%o]",n),await this._pc.setLocalDescription(n);for(const i of e){const{trackId:e}=i,n=r.get(e),s=this._pc.getTransceivers().find((e=>e.mid===n));if(!s)throw new Error("new RTCRtpTransceiver not found");this._mapMidTransceiver.set(n,s),t.push({localId:n,track:s.receiver.track,rtpReceiver:s.receiver})}return t}async stopReceiving(e){if(this.assertRecvDirection(),this._closed)return;for(const t of e){Hl.debug("stopReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(e.mid)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};Hl.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Hl.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r);for(const t of e)this._mapMidTransceiver.delete(t)}async pauseReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(const t of e){Hl.debug("pauseReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="inactive",this._remoteSdp.pauseMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};Hl.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Hl.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async resumeReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(const t of e){Hl.debug("resumeReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};Hl.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Hl.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async getReceiverStats(e){this.assertNotClosed(),this.assertRecvDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.receiver.getStats()}async receiveDataChannel({sctpStreamParameters:e,label:t,protocol:r}){this.assertNotClosed(),this.assertRecvDirection();const{streamId:i,ordered:n,maxPacketLifeTime:s,maxRetransmits:o}=e,a={negotiated:!0,id:i,ordered:n,maxPacketLifeTime:s,maxRetransmits:o,protocol:r};Hl.debug("receiveDataChannel() [options:%o]",a);const c=this._pc.createDataChannel(t,a);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();const e={type:"offer",sdp:this._remoteSdp.getSdp()};Hl.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=jl.parse(t.sdp);await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:e})}Hl.debug("receiveDataChannel() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setLocalDescription(t),this._hasDataChannelMediaSection=!0}return{dataChannel:c}}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=jl.parse(this._pc.localDescription.sdp));const r=Fl.extractDtlsParameters({sdpObject:t});r.role=e,this._remoteSdp.updateDtlsRole("client"===e?"server":"client"),await new Promise(((e,t)=>{this.safeEmit("@connect",{dtlsParameters:r},e,t)})),this._transportReady=!0}assertNotClosed(){if(this._closed)throw new Ul.InvalidStateError("method called in a closed handler")}assertSendDirection(){if("send"!==this._direction)throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if("recv"!==this._direction)throw new Error('method can just be called for handlers with "recv" direction')}}Ll=Dl.Safari12=Kl;var Jl={},Xl=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),Ql=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Zl=a&&a.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(null!=t)for(var i=e(t),n=0;n<i.length;n++)"default"!==i[n]&&Xl(r,t,i[n]);return Ql(r,t),r}}();Object.defineProperty(Jl,"__esModule",{value:!0}),Jl.Safari11=void 0;const Yl=Zl(Ta),eu=ss,tu=Zl(js),ru=Zl(Fs),iu=Zl(za),nu=Zl(yd),su=Za,ou=rc,au=new eu.Logger("Safari11"),cu={OS:1024,MIS:1024};class du extends su.HandlerInterface{static createFactory(){return()=>new du}constructor(){super(),this._sendStream=new MediaStream,this._mapSendLocalIdRtpSender=new Map,this._nextSendLocalId=0,this._mapRecvLocalIdInfo=new Map,this._hasDataChannelMediaSection=!1,this._nextSendSctpStreamId=0,this._transportReady=!1}get name(){return"Safari11"}close(){if(au.debug("close()"),this._pc)try{this._pc.close()}catch(e){}this.emit("@close")}async getNativeRtpCapabilities(){au.debug("getNativeRtpCapabilities()");const e=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"plan-b"});try{const t=await e.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0});try{e.close()}catch(e){}const r=Yl.parse(t.sdp);return iu.extractRtpCapabilities({sdpObject:r})}catch(t){try{e.close()}catch(e){}throw t}}async getNativeSctpCapabilities(){return au.debug("getNativeSctpCapabilities()"),{numStreams:cu}}run({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,extendedRtpCapabilities:d}){au.debug("run()"),this._direction=e,this._remoteSdp=new ou.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n,planB:!0}),this._sendingRtpParametersByKind={audio:ru.getSendingRtpParameters("audio",d),video:ru.getSendingRtpParameters("video",d)},this._sendingRemoteRtpParametersByKind={audio:ru.getSendingRemoteRtpParameters("audio",d),video:ru.getSendingRemoteRtpParameters("video",d)},i.role&&"auto"!==i.role&&(this._forcedLocalDtlsRole="server"===i.role?"client":"server"),this._pc=new RTCPeerConnection({iceServers:s??[],iceTransportPolicy:o??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...a},c),this._pc.addEventListener("icegatheringstatechange",(()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)})),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",(()=>{this.emit("@connectionstatechange",this._pc.connectionState)})):this._pc.addEventListener("iceconnectionstatechange",(()=>{switch(au.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.iceConnectionState){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected");break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed")}}))}async updateIceServers(e){au.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(au.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});au.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};au.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};au.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();au.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",t),await this._pc.setLocalDescription(t)}}async getTransportStats(){return this._pc.getStats()}async send({track:e,encodings:t,codecOptions:r,codec:i}){this.assertSendDirection(),au.debug("send() [kind:%s, track.id:%s]",e.kind,e.id),i&&au.warn("send() | codec selection is not available in %s handler",this.name),this._sendStream.addTrack(e),this._pc.addTrack(e,this._sendStream);let n,s=await this._pc.createOffer(),o=Yl.parse(s.sdp);const a=tu.clone(this._sendingRtpParametersByKind[e.kind]);a.codecs=ru.reduceCodecs(a.codecs);const c=tu.clone(this._sendingRemoteRtpParametersByKind[e.kind]);if(c.codecs=ru.reduceCodecs(c.codecs),this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:o}),"video"===e.kind&&t&&t.length>1&&(au.debug("send() | enabling simulcast"),o=Yl.parse(s.sdp),n=o.media.find((e=>"video"===e.type)),nu.addLegacySimulcast({offerMediaObject:n,track:e,numStreams:t.length}),s={type:"offer",sdp:Yl.write(o)}),au.debug("send() | calling pc.setLocalDescription() [offer:%o]",s),await this._pc.setLocalDescription(s),o=Yl.parse(this._pc.localDescription.sdp),n=o.media.find((t=>t.type===e.kind)),a.rtcp.cname=iu.getCname({offerMediaObject:n}),a.encodings=nu.getRtpEncodings({offerMediaObject:n,track:e}),t)for(let e=0;e<a.encodings.length;++e)t[e]&&Object.assign(a.encodings[e],t[e]);if(a.encodings.length>1&&"video/vp8"===a.codecs[0].mimeType.toLowerCase())for(const e of a.encodings)e.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:n,offerRtpParameters:a,answerRtpParameters:c,codecOptions:r});const d={type:"answer",sdp:this._remoteSdp.getSdp()};au.debug("send() | calling pc.setRemoteDescription() [answer:%o]",d),await this._pc.setRemoteDescription(d);const l=String(this._nextSendLocalId);this._nextSendLocalId++;const u=this._pc.getSenders().find((t=>t.track===e));return this._mapSendLocalIdRtpSender.set(l,u),{localId:l,rtpParameters:a,rtpSender:u}}async stopSending(e){this.assertSendDirection();const t=this._mapSendLocalIdRtpSender.get(e);if(!t)throw new Error("associated RTCRtpSender not found");t.track&&this._sendStream.removeTrack(t.track),this._mapSendLocalIdRtpSender.delete(e);const r=await this._pc.createOffer();au.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r);try{await this._pc.setLocalDescription(r)}catch(e){if(0===this._sendStream.getTracks().length)return void au.warn("stopSending() | ignoring expected error due no sending tracks: %s",e.toString());throw e}if("stable"===this._pc.signalingState)return;const i={type:"answer",sdp:this._remoteSdp.getSdp()};au.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i)}async pauseSending(e){}async resumeSending(e){}async replaceTrack(e,t){this.assertSendDirection(),t?au.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):au.debug("replaceTrack() [localId:%s, no track]",e);const r=this._mapSendLocalIdRtpSender.get(e);if(!r)throw new Error("associated RTCRtpSender not found");const i=r.track;await r.replaceTrack(t),i&&this._sendStream.removeTrack(i),t&&this._sendStream.addTrack(t)}async setMaxSpatialLayer(e,t){this.assertSendDirection(),au.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);const r=this._mapSendLocalIdRtpSender.get(e);if(!r)throw new Error("associated RTCRtpSender not found");const i=r.getParameters();i.encodings.forEach(((e,r)=>{e.active=r<=t})),await r.setParameters(i)}async setRtpEncodingParameters(e,t){this.assertSendDirection(),au.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);const r=this._mapSendLocalIdRtpSender.get(e);if(!r)throw new Error("associated RTCRtpSender not found");const i=r.getParameters();i.encodings.forEach(((e,r)=>{i.encodings[r]={...e,...t}})),await r.setParameters(i)}async getSenderStats(e){this.assertSendDirection();const t=this._mapSendLocalIdRtpSender.get(e);if(!t)throw new Error("associated RTCRtpSender not found");return t.getStats()}async sendDataChannel({ordered:e,maxPacketLifeTime:t,maxRetransmits:r,label:i,protocol:n}){this.assertSendDirection();const s={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmits:r,protocol:n};au.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(i,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%cu.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=Yl.parse(e.sdp),r=t.media.find((e=>"application"===e.type));this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:t}),au.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:r});const i={type:"answer",sdp:this._remoteSdp.getSdp()};au.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._hasDataChannelMediaSection=!0}return{dataChannel:o,sctpStreamParameters:{streamId:s.id,ordered:s.ordered,maxPacketLifeTime:s.maxPacketLifeTime,maxRetransmits:s.maxRetransmits}}}async receive(e){this.assertRecvDirection();const t=[];for(const t of e){const{trackId:e,kind:r,rtpParameters:i,streamId:n}=t;au.debug("receive() [trackId:%s, kind:%s]",e,r);const s=r;this._remoteSdp.receive({mid:s,kind:r,offerRtpParameters:i,streamId:n??i.rtcp.cname,trackId:e})}const r={type:"offer",sdp:this._remoteSdp.getSdp()};au.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",r),await this._pc.setRemoteDescription(r);let i=await this._pc.createAnswer();const n=Yl.parse(i.sdp);for(const t of e){const{kind:e,rtpParameters:r}=t,i=e,s=n.media.find((e=>String(e.mid)===i));iu.applyCodecParameters({offerRtpParameters:r,answerMediaObject:s})}i={type:"answer",sdp:Yl.write(n)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:n}),au.debug("receive() | calling pc.setLocalDescription() [answer:%o]",i),await this._pc.setLocalDescription(i);for(const r of e){const{kind:e,trackId:i,rtpParameters:n}=r,s=e,o=i,a=this._pc.getReceivers().find((e=>e.track&&e.track.id===o));if(!a)throw new Error("new RTCRtpReceiver not");this._mapRecvLocalIdInfo.set(o,{mid:s,rtpParameters:n,rtpReceiver:a}),t.push({localId:o,track:a.track,rtpReceiver:a})}return t}async stopReceiving(e){this.assertRecvDirection();for(const t of e){au.debug("stopReceiving() [localId:%s]",t);const{mid:e,rtpParameters:r}=this._mapRecvLocalIdInfo.get(t)??{};this._mapRecvLocalIdInfo.delete(t),this._remoteSdp.planBStopReceiving({mid:e,offerRtpParameters:r})}const t={type:"offer",sdp:this._remoteSdp.getSdp()};au.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();au.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async getReceiverStats(e){this.assertRecvDirection();const{rtpReceiver:t}=this._mapRecvLocalIdInfo.get(e)??{};if(!t)throw new Error("associated RTCRtpReceiver not found");return t.getStats()}async pauseReceiving(e){}async resumeReceiving(e){}async receiveDataChannel({sctpStreamParameters:e,label:t,protocol:r}){this.assertRecvDirection();const{streamId:i,ordered:n,maxPacketLifeTime:s,maxRetransmits:o}=e,a={negotiated:!0,id:i,ordered:n,maxPacketLifeTime:s,maxRetransmits:o,protocol:r};au.debug("receiveDataChannel() [options:%o]",a);const c=this._pc.createDataChannel(t,a);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation({oldDataChannelSpec:!0});const e={type:"offer",sdp:this._remoteSdp.getSdp()};au.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=Yl.parse(t.sdp);await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:e})}au.debug("receiveDataChannel() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setLocalDescription(t),this._hasDataChannelMediaSection=!0}return{dataChannel:c}}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=Yl.parse(this._pc.localDescription.sdp));const r=iu.extractDtlsParameters({sdpObject:t});r.role=e,this._remoteSdp.updateDtlsRole("client"===e?"server":"client"),await new Promise(((e,t)=>{this.safeEmit("@connect",{dtlsParameters:r},e,t)})),this._transportReady=!0}assertSendDirection(){if("send"!==this._direction)throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if("recv"!==this._direction)throw new Error('method can just be called for handlers with "recv" direction')}}Jl.Safari11=du;var lu={},uu={},pu=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),hu=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),fu=a&&a.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(null!=t)for(var i=e(t),n=0;n<i.length;n++)"default"!==i[n]&&pu(r,t,i[n]);return hu(r,t),r}}();Object.defineProperty(uu,"__esModule",{value:!0}),uu.getCapabilities=function(){const e=RTCRtpReceiver.getCapabilities(),t=mu.clone(e);for(const e of t.codecs??[]){if(e.channels=e.numChannels,delete e.numChannels,e.mimeType=e.mimeType??`${e.kind}/${e.name}`,e.parameters){const t=e.parameters;t.apt&&(t.apt=Number(t.apt)),t["packetization-mode"]&&(t["packetization-mode"]=Number(t["packetization-mode"]))}for(const t of e.rtcpFeedback??[])t.parameter||(t.parameter="")}return t},uu.mangleRtpParameters=function(e){const t=mu.clone(e);t.mid&&(t.muxId=t.mid,delete t.mid);for(const e of t.codecs)e.channels&&(e.numChannels=e.channels,delete e.channels),e.mimeType&&!e.name&&(e.name=e.mimeType.split("/")[1]),delete e.mimeType;return t};const mu=fu(js);var gu=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),vu=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),bu=a&&a.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(null!=t)for(var i=e(t),n=0;n<i.length;n++)"default"!==i[n]&&gu(r,t,i[n]);return vu(r,t),r}}();Object.defineProperty(lu,"__esModule",{value:!0}),lu.Edge11=void 0;const yu=ss,wu=Is,_u=bu(js),Su=bu(Fs),Cu=bu(uu),Ru=Za,ku=new yu.Logger("Edge11");class Tu extends Ru.HandlerInterface{static createFactory(){return()=>new Tu}constructor(){super(),this._rtpSenders=new Map,this._rtpReceivers=new Map,this._nextSendLocalId=0,this._transportReady=!1}get name(){return"Edge11"}close(){ku.debug("close()");try{this._iceGatherer.close()}catch(e){}try{this._iceTransport.stop()}catch(e){}try{this._dtlsTransport.stop()}catch(e){}for(const e of this._rtpSenders.values())try{e.stop()}catch(e){}for(const e of this._rtpReceivers.values())try{e.stop()}catch(e){}this.emit("@close")}async getNativeRtpCapabilities(){return ku.debug("getNativeRtpCapabilities()"),Cu.getCapabilities()}async getNativeSctpCapabilities(){return ku.debug("getNativeSctpCapabilities()"),{numStreams:{OS:0,MIS:0}}}run({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,extendedRtpCapabilities:d}){ku.debug("run()"),this._sendingRtpParametersByKind={audio:Su.getSendingRtpParameters("audio",d),video:Su.getSendingRtpParameters("video",d)},this._remoteIceParameters=t,this._remoteIceCandidates=r,this._remoteDtlsParameters=i,this._cname=`CNAME-${_u.generateRandomNumber()}`,this.setIceGatherer({iceServers:s,iceTransportPolicy:o}),this.setIceTransport(),this.setDtlsTransport()}async updateIceServers(e){throw new wu.UnsupportedError("not supported")}async restartIce(e){if(ku.debug("restartIce()"),this._remoteIceParameters=e,this._transportReady){ku.debug("restartIce() | calling iceTransport.start()"),this._iceTransport.start(this._iceGatherer,e,"controlling");for(const e of this._remoteIceCandidates)this._iceTransport.addRemoteCandidate(e);this._iceTransport.addRemoteCandidate({})}}async getTransportStats(){return this._iceTransport.getStats()}async send({track:e,encodings:t,codecOptions:r,codec:i}){ku.debug("send() [kind:%s, track.id:%s]",e.kind,e.id),this._transportReady||await this.setupTransport({localDtlsRole:"server"}),ku.debug("send() | calling new RTCRtpSender()");const n=new RTCRtpSender(e,this._dtlsTransport),s=_u.clone(this._sendingRtpParametersByKind[e.kind]);s.codecs=Su.reduceCodecs(s.codecs,i);const o=s.codecs.some((e=>/.+\/rtx$/i.test(e.mimeType)));t||(t=[{}]);for(const e of t)e.ssrc=_u.generateRandomNumber(),o&&(e.rtx={ssrc:_u.generateRandomNumber()});s.encodings=t,s.rtcp={cname:this._cname,reducedSize:!0,mux:!0};const a=Cu.mangleRtpParameters(s);ku.debug("send() | calling rtpSender.send() [params:%o]",a),await n.send(a);const c=String(this._nextSendLocalId);return this._nextSendLocalId++,this._rtpSenders.set(c,n),{localId:c,rtpParameters:s,rtpSender:n}}async stopSending(e){ku.debug("stopSending() [localId:%s]",e);const t=this._rtpSenders.get(e);if(!t)throw new Error("RTCRtpSender not found");this._rtpSenders.delete(e);try{ku.debug("stopSending() | calling rtpSender.stop()"),t.stop()}catch(e){throw ku.warn("stopSending() | rtpSender.stop() failed:%o",e),e}}async pauseSending(e){}async resumeSending(e){}async replaceTrack(e,t){t?ku.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):ku.debug("replaceTrack() [localId:%s, no track]",e);const r=this._rtpSenders.get(e);if(!r)throw new Error("RTCRtpSender not found");r.setTrack(t)}async setMaxSpatialLayer(e,t){ku.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);const r=this._rtpSenders.get(e);if(!r)throw new Error("RTCRtpSender not found");const i=r.getParameters();i.encodings.forEach(((e,r)=>{e.active=r<=t})),await r.setParameters(i)}async setRtpEncodingParameters(e,t){ku.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);const r=this._rtpSenders.get(e);if(!r)throw new Error("RTCRtpSender not found");const i=r.getParameters();i.encodings.forEach(((e,r)=>{i.encodings[r]={...e,...t}})),await r.setParameters(i)}async getSenderStats(e){const t=this._rtpSenders.get(e);if(!t)throw new Error("RTCRtpSender not found");return t.getStats()}async sendDataChannel(e){throw new wu.UnsupportedError("not implemented")}async receive(e){const t=[];for(const t of e){const{trackId:e,kind:r}=t;ku.debug("receive() [trackId:%s, kind:%s]",e,r)}this._transportReady||await this.setupTransport({localDtlsRole:"server"});for(const r of e){const{trackId:e,kind:i,rtpParameters:n}=r;ku.debug("receive() | calling new RTCRtpReceiver()");const s=new RTCRtpReceiver(this._dtlsTransport,i);s.addEventListener("error",(e=>{ku.error('rtpReceiver "error" event [event:%o]',e)}));const o=Cu.mangleRtpParameters(n);ku.debug("receive() | calling rtpReceiver.receive() [params:%o]",o),await s.receive(o);const a=e;this._rtpReceivers.set(a,s),t.push({localId:a,track:s.track,rtpReceiver:s})}return t}async stopReceiving(e){for(const t of e){ku.debug("stopReceiving() [localId:%s]",t);const e=this._rtpReceivers.get(t);if(!e)throw new Error("RTCRtpReceiver not found");this._rtpReceivers.delete(t);try{ku.debug("stopReceiving() | calling rtpReceiver.stop()"),e.stop()}catch(e){ku.warn("stopReceiving() | rtpReceiver.stop() failed:%o",e)}}}async pauseReceiving(e){}async resumeReceiving(e){}async getReceiverStats(e){const t=this._rtpReceivers.get(e);if(!t)throw new Error("RTCRtpReceiver not found");return t.getStats()}async receiveDataChannel(e){throw new wu.UnsupportedError("not implemented")}setIceGatherer({iceServers:e,iceTransportPolicy:t}){const r=new RTCIceGatherer({iceServers:e??[],gatherPolicy:t??"all"});r.addEventListener("error",(e=>{ku.error('iceGatherer "error" event [event:%o]',e)}));try{r.gather()}catch(e){ku.debug("setIceGatherer() | iceGatherer.gather() failed: %s",e.toString())}this._iceGatherer=r}setIceTransport(){const e=new RTCIceTransport(this._iceGatherer);e.addEventListener("statechange",(()=>{switch(e.state){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected");break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed")}})),e.addEventListener("icestatechange",(()=>{switch(e.state){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected");break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed")}})),e.addEventListener("candidatepairchange",(e=>{ku.debug('iceTransport "candidatepairchange" event [pair:%o]',e.pair)})),this._iceTransport=e}setDtlsTransport(){const e=new RTCDtlsTransport(this._iceTransport);e.addEventListener("statechange",(()=>{ku.debug('dtlsTransport "statechange" event [state:%s]',e.state)})),e.addEventListener("dtlsstatechange",(()=>{ku.debug('dtlsTransport "dtlsstatechange" event [state:%s]',e.state),"closed"===e.state&&this.emit("@connectionstatechange","closed")})),e.addEventListener("error",(e=>{ku.error('dtlsTransport "error" event [event:%o]',e)})),this._dtlsTransport=e}async setupTransport({localDtlsRole:e}){ku.debug("setupTransport()");const t=this._dtlsTransport.getLocalParameters();t.role=e,await new Promise(((e,r)=>{this.safeEmit("@connect",{dtlsParameters:t},e,r)})),this._iceTransport.start(this._iceGatherer,this._remoteIceParameters,"controlling");for(const e of this._remoteIceCandidates)this._iceTransport.addRemoteCandidate(e);this._iceTransport.addRemoteCandidate({}),this._remoteDtlsParameters.fingerprints=this._remoteDtlsParameters.fingerprints.filter((e=>"sha-256"===e.algorithm||"sha-384"===e.algorithm||"sha-512"===e.algorithm)),this._dtlsTransport.start(this._remoteDtlsParameters),this._transportReady=!0}}lu.Edge11=Tu;var Pu={},Eu=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),Ou=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Du=a&&a.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(null!=t)for(var i=e(t),n=0;n<i.length;n++)"default"!==i[n]&&Eu(r,t,i[n]);return Ou(r,t),r}}();Object.defineProperty(Pu,"__esModule",{value:!0}),Pu.ReactNativeUnifiedPlan=void 0;const Iu=Du(Ta),xu=ss,Mu=Du(js),Lu=Du(Fs),ju=Du(za),Au=Du(Ja),Nu=Du(Xa),Bu=Is,Fu=Za,zu=rc,Vu=bc,Uu=new xu.Logger("ReactNativeUnifiedPlan"),$u={OS:1024,MIS:1024};class Gu extends Fu.HandlerInterface{static createFactory(){return()=>new Gu}constructor(){super(),this._closed=!1,this._mapMidTransceiver=new Map,this._sendStream=new MediaStream,this._hasDataChannelMediaSection=!1,this._nextSendSctpStreamId=0,this._transportReady=!1}get name(){return"ReactNativeUnifiedPlan"}close(){if(Uu.debug("close()"),!this._closed){if(this._closed=!0,this._sendStream.release(!1),this._pc)try{this._pc.close()}catch(e){}this.emit("@close")}}async getNativeRtpCapabilities(){Uu.debug("getNativeRtpCapabilities()");const e=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"unified-plan"});try{e.addTransceiver("audio"),e.addTransceiver("video");const t=await e.createOffer();try{e.close()}catch(e){}const r=Iu.parse(t.sdp),i=ju.extractRtpCapabilities({sdpObject:r});return Nu.addNackSuppportForOpus(i),i}catch(t){try{e.close()}catch(e){}throw t}}async getNativeSctpCapabilities(){return Uu.debug("getNativeSctpCapabilities()"),{numStreams:$u}}run({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,extendedRtpCapabilities:d}){this.assertNotClosed(),Uu.debug("run()"),this._direction=e,this._remoteSdp=new zu.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n}),this._sendingRtpParametersByKind={audio:Lu.getSendingRtpParameters("audio",d),video:Lu.getSendingRtpParameters("video",d)},this._sendingRemoteRtpParametersByKind={audio:Lu.getSendingRemoteRtpParameters("audio",d),video:Lu.getSendingRemoteRtpParameters("video",d)},i.role&&"auto"!==i.role&&(this._forcedLocalDtlsRole="server"===i.role?"client":"server"),this._pc=new RTCPeerConnection({iceServers:s??[],iceTransportPolicy:o??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"unified-plan",...a},c),this._pc.addEventListener("icegatheringstatechange",(()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)})),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",(()=>{this.emit("@connectionstatechange",this._pc.connectionState)})):this._pc.addEventListener("iceconnectionstatechange",(()=>{switch(Uu.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.iceConnectionState){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected");break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed")}}))}async updateIceServers(e){this.assertNotClosed(),Uu.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(this.assertNotClosed(),Uu.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});Uu.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};Uu.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};Uu.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();Uu.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",t),await this._pc.setLocalDescription(t)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:e,encodings:t,codecOptions:r,codec:i,onRtpSender:n}){this.assertNotClosed(),this.assertSendDirection(),Uu.debug("send() [kind:%s, track.id:%s]",e.kind,e.id),t&&t.length>1&&t.forEach(((e,t)=>{e.rid=`r${t}`}));const s=Mu.clone(this._sendingRtpParametersByKind[e.kind]);s.codecs=Lu.reduceCodecs(s.codecs,i);const o=Mu.clone(this._sendingRemoteRtpParametersByKind[e.kind]);o.codecs=Lu.reduceCodecs(o.codecs,i);const a=this._remoteSdp.getNextMediaSectionIdx(),c=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream],sendEncodings:t});n&&n(c.sender);let d,l=await this._pc.createOffer(),u=Iu.parse(l.sdp);this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:u});let p=!1;const h=(0,Vu.parse)((t??[{}])[0].scalabilityMode);t&&1===t.length&&h.spatialLayers>1&&"video/vp9"===s.codecs[0].mimeType.toLowerCase()&&(Uu.debug("send() | enabling legacy simulcast for VP9 SVC"),p=!0,u=Iu.parse(l.sdp),d=u.media[a.idx],Au.addLegacySimulcast({offerMediaObject:d,numStreams:h.spatialLayers}),l={type:"offer",sdp:Iu.write(u)}),Uu.debug("send() | calling pc.setLocalDescription() [offer:%o]",l),await this._pc.setLocalDescription(l);let f=c.mid??void 0;if(f||Uu.warn("send() | missing transceiver.mid (bug in react-native-webrtc, using a workaround"),s.mid=f,u=Iu.parse(this._pc.localDescription.sdp),d=u.media[a.idx],s.rtcp.cname=ju.getCname({offerMediaObject:d}),t)if(1===t.length){let e=Au.getRtpEncodings({offerMediaObject:d});Object.assign(e[0],t[0]),p&&(e=[e[0]]),s.encodings=e}else s.encodings=t;else s.encodings=Au.getRtpEncodings({offerMediaObject:d});if(s.encodings.length>1&&("video/vp8"===s.codecs[0].mimeType.toLowerCase()||"video/h264"===s.codecs[0].mimeType.toLowerCase()))for(const e of s.encodings)e.scalabilityMode?e.scalabilityMode=`L1T${h.temporalLayers}`:e.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:d,reuseMid:a.reuseMid,offerRtpParameters:s,answerRtpParameters:o,codecOptions:r,extmapAllowMixed:!0});const m={type:"answer",sdp:this._remoteSdp.getSdp()};return Uu.debug("send() | calling pc.setRemoteDescription() [answer:%o]",m),await this._pc.setRemoteDescription(m),f||(f=c.mid,s.mid=f),this._mapMidTransceiver.set(f,c),{localId:f,rtpParameters:s,rtpSender:c.sender}}async stopSending(e){if(this.assertSendDirection(),this._closed)return;Uu.debug("stopSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.sender.replaceTrack(null),this._pc.removeTrack(t.sender);if(this._remoteSdp.closeMediaSection(t.mid))try{t.stop()}catch(e){}const r=await this._pc.createOffer();Uu.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const i={type:"answer",sdp:this._remoteSdp.getSdp()};Uu.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),Uu.debug("pauseSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="inactive",this._remoteSdp.pauseMediaSection(e);const r=await this._pc.createOffer();Uu.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const i={type:"answer",sdp:this._remoteSdp.getSdp()};Uu.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),Uu.debug("resumeSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(this._remoteSdp.resumeSendingMediaSection(e),!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="sendonly";const r=await this._pc.createOffer();Uu.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const i={type:"answer",sdp:this._remoteSdp.getSdp()};Uu.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?Uu.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):Uu.debug("replaceTrack() [localId:%s, no track]",e);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");await r.sender.replaceTrack(t)}async setMaxSpatialLayer(e,t){this.assertNotClosed(),this.assertSendDirection(),Uu.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const i=r.sender.getParameters();i.encodings.forEach(((e,r)=>{e.active=r<=t})),await r.sender.setParameters(i),this._remoteSdp.muxMediaSectionSimulcast(e,i.encodings);const n=await this._pc.createOffer();Uu.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);const s={type:"answer",sdp:this._remoteSdp.getSdp()};Uu.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),Uu.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const i=r.sender.getParameters();i.encodings.forEach(((e,r)=>{i.encodings[r]={...e,...t}})),await r.sender.setParameters(i),this._remoteSdp.muxMediaSectionSimulcast(e,i.encodings);const n=await this._pc.createOffer();Uu.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);const s={type:"answer",sdp:this._remoteSdp.getSdp()};Uu.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async getSenderStats(e){this.assertNotClosed(),this.assertSendDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.sender.getStats()}async sendDataChannel({ordered:e,maxPacketLifeTime:t,maxRetransmits:r,label:i,protocol:n}){this.assertNotClosed(),this.assertSendDirection();const s={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmits:r,protocol:n};Uu.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(i,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%$u.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=Iu.parse(e.sdp),r=t.media.find((e=>"application"===e.type));this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:t}),Uu.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:r});const i={type:"answer",sdp:this._remoteSdp.getSdp()};Uu.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._hasDataChannelMediaSection=!0}return{dataChannel:o,sctpStreamParameters:{streamId:s.id,ordered:s.ordered,maxPacketLifeTime:s.maxPacketLifeTime,maxRetransmits:s.maxRetransmits}}}async receive(e){this.assertNotClosed(),this.assertRecvDirection();const t=[],r=new Map;for(const t of e){const{trackId:e,kind:i,rtpParameters:n,streamId:s}=t;Uu.debug("receive() [trackId:%s, kind:%s]",e,i);const o=n.mid??String(this._mapMidTransceiver.size);r.set(e,o),this._remoteSdp.receive({mid:o,kind:i,offerRtpParameters:n,streamId:s??n.rtcp.cname,trackId:e})}const i={type:"offer",sdp:this._remoteSdp.getSdp()};Uu.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",i),await this._pc.setRemoteDescription(i);for(const t of e){const{trackId:e,onRtpReceiver:i}=t;if(i){const t=r.get(e),n=this._pc.getTransceivers().find((e=>e.mid===t));if(!n)throw new Error("transceiver not found");i(n.receiver)}}let n=await this._pc.createAnswer();const s=Iu.parse(n.sdp);for(const t of e){const{trackId:e,rtpParameters:i}=t,n=r.get(e),o=s.media.find((e=>String(e.mid)===n));ju.applyCodecParameters({offerRtpParameters:i,answerMediaObject:o})}n={type:"answer",sdp:Iu.write(s)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:s}),Uu.debug("receive() | calling pc.setLocalDescription() [answer:%o]",n),await this._pc.setLocalDescription(n);for(const i of e){const{trackId:e}=i,n=r.get(e),s=this._pc.getTransceivers().find((e=>e.mid===n));if(!s)throw new Error("new RTCRtpTransceiver not found");this._mapMidTransceiver.set(n,s),t.push({localId:n,track:s.receiver.track,rtpReceiver:s.receiver})}return t}async stopReceiving(e){if(this.assertRecvDirection(),this._closed)return;for(const t of e){Uu.debug("stopReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(e.mid)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};Uu.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Uu.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r);for(const t of e)this._mapMidTransceiver.delete(t)}async pauseReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(const t of e){Uu.debug("pauseReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="inactive",this._remoteSdp.pauseMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};Uu.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Uu.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async resumeReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(const t of e){Uu.debug("resumeReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};Uu.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Uu.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async getReceiverStats(e){this.assertNotClosed(),this.assertRecvDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.receiver.getStats()}async receiveDataChannel({sctpStreamParameters:e,label:t,protocol:r}){this.assertNotClosed(),this.assertRecvDirection();const{streamId:i,ordered:n,maxPacketLifeTime:s,maxRetransmits:o}=e,a={negotiated:!0,id:i,ordered:n,maxPacketLifeTime:s,maxRetransmits:o,protocol:r};Uu.debug("receiveDataChannel() [options:%o]",a);const c=this._pc.createDataChannel(t,a);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();const e={type:"offer",sdp:this._remoteSdp.getSdp()};Uu.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=Iu.parse(t.sdp);await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:e})}Uu.debug("receiveDataChannel() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setLocalDescription(t),this._hasDataChannelMediaSection=!0}return{dataChannel:c}}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=Iu.parse(this._pc.localDescription.sdp));const r=ju.extractDtlsParameters({sdpObject:t});r.role=e,this._remoteSdp.updateDtlsRole("client"===e?"server":"client"),await new Promise(((e,t)=>{this.safeEmit("@connect",{dtlsParameters:r},e,t)})),this._transportReady=!0}assertNotClosed(){if(this._closed)throw new Bu.InvalidStateError("method called in a closed handler")}assertSendDirection(){if("send"!==this._direction)throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if("recv"!==this._direction)throw new Error('method can just be called for handlers with "recv" direction')}}Pu.ReactNativeUnifiedPlan=Gu;var qu={},Hu=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),Wu=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Ku=a&&a.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(null!=t)for(var i=e(t),n=0;n<i.length;n++)"default"!==i[n]&&Hu(r,t,i[n]);return Wu(r,t),r}}();Object.defineProperty(qu,"__esModule",{value:!0}),qu.ReactNative=void 0;const Ju=Ku(Ta),Xu=ss,Qu=Is,Zu=Ku(js),Yu=Ku(Fs),ep=Ku(za),tp=Ku(yd),rp=Za,ip=rc,np=new Xu.Logger("ReactNative"),sp={OS:1024,MIS:1024};class op extends rp.HandlerInterface{static createFactory(){return()=>new op}constructor(){super(),this._sendStream=new MediaStream,this._mapSendLocalIdTrack=new Map,this._nextSendLocalId=0,this._mapRecvLocalIdInfo=new Map,this._hasDataChannelMediaSection=!1,this._nextSendSctpStreamId=0,this._transportReady=!1}get name(){return"ReactNative"}close(){if(np.debug("close()"),this._sendStream.release(!1),this._pc)try{this._pc.close()}catch(e){}this.emit("@close")}async getNativeRtpCapabilities(){np.debug("getNativeRtpCapabilities()");const e=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"plan-b"});try{const t=await e.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0});try{e.close()}catch(e){}const r=Ju.parse(t.sdp);return ep.extractRtpCapabilities({sdpObject:r})}catch(t){try{e.close()}catch(e){}throw t}}async getNativeSctpCapabilities(){return np.debug("getNativeSctpCapabilities()"),{numStreams:sp}}run({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,extendedRtpCapabilities:d}){np.debug("run()"),this._direction=e,this._remoteSdp=new ip.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n,planB:!0}),this._sendingRtpParametersByKind={audio:Yu.getSendingRtpParameters("audio",d),video:Yu.getSendingRtpParameters("video",d)},this._sendingRemoteRtpParametersByKind={audio:Yu.getSendingRemoteRtpParameters("audio",d),video:Yu.getSendingRemoteRtpParameters("video",d)},i.role&&"auto"!==i.role&&(this._forcedLocalDtlsRole="server"===i.role?"client":"server"),this._pc=new RTCPeerConnection({iceServers:s??[],iceTransportPolicy:o??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"plan-b",...a},c),this._pc.addEventListener("icegatheringstatechange",(()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)})),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",(()=>{this.emit("@connectionstatechange",this._pc.connectionState)})):this._pc.addEventListener("iceconnectionstatechange",(()=>{switch(np.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.iceConnectionState){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected");break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed")}}))}async updateIceServers(e){np.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(np.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});np.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};np.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};np.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();np.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",t),await this._pc.setLocalDescription(t)}}async getTransportStats(){return this._pc.getStats()}async send({track:e,encodings:t,codecOptions:r,codec:i}){this.assertSendDirection(),np.debug("send() [kind:%s, track.id:%s]",e.kind,e.id),i&&np.warn("send() | codec selection is not available in %s handler",this.name),this._sendStream.addTrack(e),this._pc.addStream(this._sendStream);let n,s=await this._pc.createOffer(),o=Ju.parse(s.sdp);const a=Zu.clone(this._sendingRtpParametersByKind[e.kind]);a.codecs=Yu.reduceCodecs(a.codecs);const c=Zu.clone(this._sendingRemoteRtpParametersByKind[e.kind]);if(c.codecs=Yu.reduceCodecs(c.codecs),this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:o}),"video"===e.kind&&t&&t.length>1&&(np.debug("send() | enabling simulcast"),o=Ju.parse(s.sdp),n=o.media.find((e=>"video"===e.type)),tp.addLegacySimulcast({offerMediaObject:n,track:e,numStreams:t.length}),s={type:"offer",sdp:Ju.write(o)}),np.debug("send() | calling pc.setLocalDescription() [offer:%o]",s),await this._pc.setLocalDescription(s),o=Ju.parse(this._pc.localDescription.sdp),n=o.media.find((t=>t.type===e.kind)),a.rtcp.cname=ep.getCname({offerMediaObject:n}),a.encodings=tp.getRtpEncodings({offerMediaObject:n,track:e}),t)for(let e=0;e<a.encodings.length;++e)t[e]&&Object.assign(a.encodings[e],t[e]);if(a.encodings.length>1&&("video/vp8"===a.codecs[0].mimeType.toLowerCase()||"video/h264"===a.codecs[0].mimeType.toLowerCase()))for(const e of a.encodings)e.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:n,offerRtpParameters:a,answerRtpParameters:c,codecOptions:r});const d={type:"answer",sdp:this._remoteSdp.getSdp()};np.debug("send() | calling pc.setRemoteDescription() [answer:%o]",d),await this._pc.setRemoteDescription(d);const l=String(this._nextSendLocalId);return this._nextSendLocalId++,this._mapSendLocalIdTrack.set(l,e),{localId:l,rtpParameters:a}}async stopSending(e){this.assertSendDirection(),np.debug("stopSending() [localId:%s]",e);const t=this._mapSendLocalIdTrack.get(e);if(!t)throw new Error("track not found");this._mapSendLocalIdTrack.delete(e),this._sendStream.removeTrack(t),this._pc.addStream(this._sendStream);const r=await this._pc.createOffer();np.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r);try{await this._pc.setLocalDescription(r)}catch(e){if(0===this._sendStream.getTracks().length)return void np.warn("stopSending() | ignoring expected error due no sending tracks: %s",e.toString());throw e}if("stable"===this._pc.signalingState)return;const i={type:"answer",sdp:this._remoteSdp.getSdp()};np.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i)}async pauseSending(e){}async resumeSending(e){}async replaceTrack(e,t){throw new Qu.UnsupportedError("not implemented")}async setMaxSpatialLayer(e,t){throw new Qu.UnsupportedError("not implemented")}async setRtpEncodingParameters(e,t){throw new Qu.UnsupportedError("not implemented")}async getSenderStats(e){throw new Qu.UnsupportedError("not implemented")}async sendDataChannel({ordered:e,maxPacketLifeTime:t,maxRetransmits:r,label:i,protocol:n}){this.assertSendDirection();const s={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmitTime:t,maxRetransmits:r,protocol:n};np.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(i,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%sp.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=Ju.parse(e.sdp),r=t.media.find((e=>"application"===e.type));this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:t}),np.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:r});const i={type:"answer",sdp:this._remoteSdp.getSdp()};np.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._hasDataChannelMediaSection=!0}return{dataChannel:o,sctpStreamParameters:{streamId:s.id,ordered:s.ordered,maxPacketLifeTime:s.maxPacketLifeTime,maxRetransmits:s.maxRetransmits}}}async receive(e){this.assertRecvDirection();const t=[],r=new Map;for(const t of e){const{trackId:e,kind:i,rtpParameters:n}=t;np.debug("receive() [trackId:%s, kind:%s]",e,i);const s=i;let o=t.streamId??n.rtcp.cname;np.debug("receive() | forcing a random remote streamId to avoid well known bug in react-native-webrtc"),o+=`-hack-${Zu.generateRandomNumber()}`,r.set(e,o),this._remoteSdp.receive({mid:s,kind:i,offerRtpParameters:n,streamId:o,trackId:e})}const i={type:"offer",sdp:this._remoteSdp.getSdp()};np.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",i),await this._pc.setRemoteDescription(i);let n=await this._pc.createAnswer();const s=Ju.parse(n.sdp);for(const t of e){const{kind:e,rtpParameters:r}=t,i=e,n=s.media.find((e=>String(e.mid)===i));ep.applyCodecParameters({offerRtpParameters:r,answerMediaObject:n})}n={type:"answer",sdp:Ju.write(s)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:s}),np.debug("receive() | calling pc.setLocalDescription() [answer:%o]",n),await this._pc.setLocalDescription(n);for(const i of e){const{kind:e,trackId:n,rtpParameters:s}=i,o=n,a=e,c=r.get(n),d=this._pc.getRemoteStreams().find((e=>e.id===c)).getTrackById(o);if(!d)throw new Error("remote track not found");this._mapRecvLocalIdInfo.set(o,{mid:a,rtpParameters:s}),t.push({localId:o,track:d})}return t}async stopReceiving(e){this.assertRecvDirection();for(const t of e){np.debug("stopReceiving() [localId:%s]",t);const{mid:e,rtpParameters:r}=this._mapRecvLocalIdInfo.get(t)??{};this._mapRecvLocalIdInfo.delete(t),this._remoteSdp.planBStopReceiving({mid:e,offerRtpParameters:r})}const t={type:"offer",sdp:this._remoteSdp.getSdp()};np.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();np.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async pauseReceiving(e){}async resumeReceiving(e){}async getReceiverStats(e){throw new Qu.UnsupportedError("not implemented")}async receiveDataChannel({sctpStreamParameters:e,label:t,protocol:r}){this.assertRecvDirection();const{streamId:i,ordered:n,maxPacketLifeTime:s,maxRetransmits:o}=e,a={negotiated:!0,id:i,ordered:n,maxPacketLifeTime:s,maxRetransmitTime:s,maxRetransmits:o,protocol:r};np.debug("receiveDataChannel() [options:%o]",a);const c=this._pc.createDataChannel(t,a);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation({oldDataChannelSpec:!0});const e={type:"offer",sdp:this._remoteSdp.getSdp()};np.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=Ju.parse(t.sdp);await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:e})}np.debug("receiveDataChannel() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setLocalDescription(t),this._hasDataChannelMediaSection=!0}return{dataChannel:c}}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=Ju.parse(this._pc.localDescription.sdp));const r=ep.extractDtlsParameters({sdpObject:t});r.role=e,this._remoteSdp.updateDtlsRole("client"===e?"server":"client"),await new Promise(((e,t)=>{this.safeEmit("@connect",{dtlsParameters:r},e,t)})),this._transportReady=!0}assertSendDirection(){if("send"!==this._direction)throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if("recv"!==this._direction)throw new Error('method can just be called for handlers with "recv" direction')}}qu.ReactNative=op;var ap=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),cp=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),dp=a&&a.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(null!=t)for(var i=e(t),n=0;n<i.length;n++)"default"!==i[n]&&ap(r,t,i[n]);return cp(r,t),r}}();Object.defineProperty(rs,"__esModule",{value:!0}),rs.Device=void 0,rs.detectDevice=Dp;const lp=ns,up=ss,pp=us,hp=Is,fp=dp(js),mp=dp(Fs),gp=xo,vp=ka,bp=Bc,yp=rd,wp=bd,_p=Ld,Sp=Xd,Cp=hl,Rp=Dl,kp=Jl,Tp=lu,Pp=Pu,Ep=qu,Op=new up.Logger("Device");function Dp(e){if(!e&&"object"==typeof navigator&&"ReactNative"===navigator.product)return Op.debug("detectDevice() | React-Native detected"),"undefined"==typeof RTCPeerConnection?void Op.warn("detectDevice() | unsupported react-native-webrtc without RTCPeerConnection, forgot to call registerGlobals()?"):"undefined"!=typeof RTCRtpTransceiver?(Op.debug("detectDevice() | ReactNative UnifiedPlan handler chosen"),"ReactNativeUnifiedPlan"):(Op.debug("detectDevice() | ReactNative PlanB handler chosen"),"ReactNative");if(e||"object"==typeof navigator&&"string"==typeof navigator.userAgent){e??(e=navigator.userAgent);const t=new lp.UAParser(e);Op.debug("detectDevice() | browser detected [userAgent:%s, parsed:%o]",e,t.getResult());const r=t.getBrowser(),i=r.name?.toLowerCase(),n=parseInt(r.major??"0"),s=t.getEngine(),o=s.name?.toLowerCase(),a=t.getOS(),c=a.name?.toLowerCase(),d=parseFloat(a.version??"0"),l=t.getDevice(),u=l.model?.toLowerCase(),p="ios"===c||"ipad"===u,h=i&&["chrome","chromium","mobile chrome","chrome webview","chrome headless"].includes(i),f=i&&["firefox","mobile firefox","mobile focus"].includes(i),m=i&&["safari","mobile safari"].includes(i),g=i&&["edge"].includes(i);if((h||g)&&!p&&n>=111)return"Chrome111";if(h&&!p&&n>=74||g&&!p&&n>=88)return"Chrome74";if(h&&!p&&n>=70)return"Chrome70";if(h&&!p&&n>=67)return"Chrome67";if(h&&!p&&n>=55)return"Chrome55";if(f&&!p&&n>=120)return"Firefox120";if(f&&!p&&n>=60)return"Firefox60";if(f&&p&&d>=14.3)return"Safari12";if(m&&n>=12&&"undefined"!=typeof RTCRtpTransceiver&&RTCRtpTransceiver.prototype.hasOwnProperty("currentDirection"))return"Safari12";if(m&&n>=11)return"Safari11";if(g&&!p&&n>=11&&n<=18)return"Edge11";if("webkit"===o&&p&&"undefined"!=typeof RTCRtpTransceiver&&RTCRtpTransceiver.prototype.hasOwnProperty("currentDirection"))return"Safari12";if("blink"===o){const t=e.match(/(?:(?:Chrome|Chromium))[ /](\w+)/i);if(t){const e=Number(t[1]);return e>=111?"Chrome111":e>=74?"Chrome74":e>=70?"Chrome70":e>=67?"Chrome67":"Chrome55"}return"Chrome111"}Op.warn("detectDevice() | browser not supported [name:%s, version:%s]",i,n)}else Op.warn("detectDevice() | unknown device")}rs.Device=class{constructor({handlerName:e,handlerFactory:t}={}){if(this._loaded=!1,this._observer=new pp.EnhancedEventEmitter,Op.debug("constructor()"),e&&t)throw new TypeError("just one of handlerName or handlerInterface can be given");if(t)this._handlerFactory=t;else{if(e)Op.debug("constructor() | handler given: %s",e);else{if(!(e=Dp()))throw new hp.UnsupportedError("device not supported");Op.debug("constructor() | detected handler: %s",e)}switch(e){case"Chrome111":this._handlerFactory=vp.Chrome111.createFactory();break;case"Chrome74":this._handlerFactory=bp.Chrome74.createFactory();break;case"Chrome70":this._handlerFactory=yp.Chrome70.createFactory();break;case"Chrome67":this._handlerFactory=wp.Chrome67.createFactory();break;case"Chrome55":this._handlerFactory=_p.Chrome55.createFactory();break;case"Firefox120":this._handlerFactory=Sp.Firefox120.createFactory();break;case"Firefox60":this._handlerFactory=Cp.Firefox60.createFactory();break;case"Safari12":this._handlerFactory=Rp.Safari12.createFactory();break;case"Safari11":this._handlerFactory=kp.Safari11.createFactory();break;case"Edge11":this._handlerFactory=Tp.Edge11.createFactory();break;case"ReactNativeUnifiedPlan":this._handlerFactory=Pp.ReactNativeUnifiedPlan.createFactory();break;case"ReactNative":this._handlerFactory=Ep.ReactNative.createFactory();break;default:throw new TypeError(`unknown handlerName "${e}"`)}}const r=this._handlerFactory();this._handlerName=r.name,r.close(),this._extendedRtpCapabilities=void 0,this._recvRtpCapabilities=void 0,this._canProduceByKind={audio:!1,video:!1},this._sctpCapabilities=void 0}get handlerName(){return this._handlerName}get loaded(){return this._loaded}get rtpCapabilities(){if(!this._loaded)throw new hp.InvalidStateError("not loaded");return this._recvRtpCapabilities}get sctpCapabilities(){if(!this._loaded)throw new hp.InvalidStateError("not loaded");return this._sctpCapabilities}get observer(){return this._observer}async load({routerRtpCapabilities:e}){let t;Op.debug("load() [routerRtpCapabilities:%o]",e);try{if(this._loaded)throw new hp.InvalidStateError("already loaded");const r=fp.clone(e);mp.validateRtpCapabilities(r),t=this._handlerFactory();const i=await t.getNativeRtpCapabilities();Op.debug("load() | got native RTP capabilities:%o",i);const n=fp.clone(i);mp.validateRtpCapabilities(n),this._extendedRtpCapabilities=mp.getExtendedRtpCapabilities(n,r),Op.debug("load() | got extended RTP capabilities:%o",this._extendedRtpCapabilities),this._canProduceByKind.audio=mp.canSend("audio",this._extendedRtpCapabilities),this._canProduceByKind.video=mp.canSend("video",this._extendedRtpCapabilities),this._recvRtpCapabilities=mp.getRecvRtpCapabilities(this._extendedRtpCapabilities),mp.validateRtpCapabilities(this._recvRtpCapabilities),Op.debug("load() | got receiving RTP capabilities:%o",this._recvRtpCapabilities),this._sctpCapabilities=await t.getNativeSctpCapabilities(),Op.debug("load() | got native SCTP capabilities:%o",this._sctpCapabilities),mp.validateSctpCapabilities(this._sctpCapabilities),Op.debug("load() succeeded"),this._loaded=!0,t.close()}catch(e){throw t&&t.close(),e}}canProduce(e){if(!this._loaded)throw new hp.InvalidStateError("not loaded");if("audio"!==e&&"video"!==e)throw new TypeError(`invalid kind "${e}"`);return this._canProduceByKind[e]}createSendTransport({id:e,iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,appData:d}){return Op.debug("createSendTransport()"),this.createTransport({direction:"send",id:e,iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,appData:d})}createRecvTransport({id:e,iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,appData:d}){return Op.debug("createRecvTransport()"),this.createTransport({direction:"recv",id:e,iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,appData:d})}createTransport({direction:e,id:t,iceParameters:r,iceCandidates:i,dtlsParameters:n,sctpParameters:s,iceServers:o,iceTransportPolicy:a,additionalSettings:c,proprietaryConstraints:d,appData:l}){if(!this._loaded)throw new hp.InvalidStateError("not loaded");if("string"!=typeof t)throw new TypeError("missing id");if("object"!=typeof r)throw new TypeError("missing iceParameters");if(!Array.isArray(i))throw new TypeError("missing iceCandidates");if("object"!=typeof n)throw new TypeError("missing dtlsParameters");if(s&&"object"!=typeof s)throw new TypeError("wrong sctpParameters");if(l&&"object"!=typeof l)throw new TypeError("if given, appData must be an object");const u=new gp.Transport({direction:e,id:t,iceParameters:r,iceCandidates:i,dtlsParameters:n,sctpParameters:s,iceServers:o,iceTransportPolicy:a,additionalSettings:c,proprietaryConstraints:d,appData:l,handlerFactory:this._handlerFactory,extendedRtpCapabilities:this._extendedRtpCapabilities,canProduceByKind:this._canProduceByKind});return this._observer.safeEmit("newtransport",u),u}};var Ip={},xp={};Object.defineProperty(xp,"__esModule",{value:!0});var Mp={};Object.defineProperty(Mp,"__esModule",{value:!0}),function(e){var t=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),r=a&&a.__exportStar||function(e,r){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(r,i)||t(r,e,i)};Object.defineProperty(e,"__esModule",{value:!0}),r(rs,e),r(xo,e),r(Uo,e),r(Wo,e),r(Zo,e),r(ia,e),r(xp,e),r(Mp,e),r(Za,e),r(Is,e)}(Ip),function(e){var t=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),r=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),i=a&&a.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},e(t)};return function(i){if(i&&i.__esModule)return i;var n={};if(null!=i)for(var s=e(i),o=0;o<s.length;o++)"default"!==s[o]&&t(n,i,s[o]);return r(n,i),n}}(),n=a&&a.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(e,"__esModule",{value:!0}),e.debug=e.parseScalabilityMode=e.detectDevice=e.Device=e.version=e.types=void 0;const s=n(ts);e.debug=s.default;const o=rs;Object.defineProperty(e,"Device",{enumerable:!0,get:function(){return o.Device}}),Object.defineProperty(e,"detectDevice",{enumerable:!0,get:function(){return o.detectDevice}});const c=i(Ip);e.types=c,e.version="3.7.18";var d=bc;Object.defineProperty(e,"parseScalabilityMode",{enumerable:!0,get:function(){return d.parse}})}(Qn);var Lp={exports:{}};!function(e,t){!function(r,i){var n="function",s="undefined",o="object",a="string",c="major",d="model",l="name",u="type",p="vendor",h="version",f="architecture",m="console",g="mobile",v="tablet",b="smarttv",y="wearable",w="embedded",_="Amazon",S="Apple",C="ASUS",R="BlackBerry",k="Browser",T="Chrome",P="Firefox",E="Google",O="Huawei",D="LG",I="Microsoft",x="Motorola",M="Opera",L="Samsung",j="Sharp",A="Sony",N="Xiaomi",B="Zebra",F="Facebook",z="Chromium OS",V="Mac OS",U=" Browser",$=function(e){for(var t={},r=0;r<e.length;r++)t[e[r].toUpperCase()]=e[r];return t},G=function(e,t){return typeof e===a&&-1!==q(t).indexOf(q(e))},q=function(e){return e.toLowerCase()},H=function(e,t){if(typeof e===a)return e=e.replace(/^\s\s*/,""),typeof t===s?e:e.substring(0,500)},W=function(e,t){for(var r,s,a,c,d,l,u=0;u<t.length&&!d;){var p=t[u],h=t[u+1];for(r=s=0;r<p.length&&!d&&p[r];)if(d=p[r++].exec(e))for(a=0;a<h.length;a++)l=d[++s],typeof(c=h[a])===o&&c.length>0?2===c.length?typeof c[1]==n?this[c[0]]=c[1].call(this,l):this[c[0]]=c[1]:3===c.length?typeof c[1]!==n||c[1].exec&&c[1].test?this[c[0]]=l?l.replace(c[1],c[2]):i:this[c[0]]=l?c[1].call(this,l,c[2]):i:4===c.length&&(this[c[0]]=l?c[3].call(this,l.replace(c[1],c[2])):i):this[c]=l||i;u+=2}},K=function(e,t){for(var r in t)if(typeof t[r]===o&&t[r].length>0){for(var n=0;n<t[r].length;n++)if(G(t[r][n],e))return"?"===r?i:r}else if(G(t[r],e))return"?"===r?i:r;return t.hasOwnProperty("*")?t["*"]:e},J={ME:"4.90","NT 3.11":"NT3.51","NT 4.0":"NT4.0",2e3:"NT 5.0",XP:["NT 5.1","NT 5.2"],Vista:"NT 6.0",7:"NT 6.1",8:"NT 6.2",8.1:"NT 6.3",10:["NT 6.4","NT 10.0"],RT:"ARM"},X={browser:[[/\b(?:crmo|crios)\/([\w\.]+)/i],[h,[l,"Chrome"]],[/edg(?:e|ios|a)?\/([\w\.]+)/i],[h,[l,"Edge"]],[/(opera mini)\/([-\w\.]+)/i,/(opera [mobiletab]{3,6})\b.+version\/([-\w\.]+)/i,/(opera)(?:.+version\/|[\/ ]+)([\w\.]+)/i],[l,h],[/opios[\/ ]+([\w\.]+)/i],[h,[l,M+" Mini"]],[/\bop(?:rg)?x\/([\w\.]+)/i],[h,[l,M+" GX"]],[/\bopr\/([\w\.]+)/i],[h,[l,M]],[/\bb[ai]*d(?:uhd|[ub]*[aekoprswx]{5,6})[\/ ]?([\w\.]+)/i],[h,[l,"Baidu"]],[/\b(?:mxbrowser|mxios|myie2)\/?([-\w\.]*)\b/i],[h,[l,"Maxthon"]],[/(kindle)\/([\w\.]+)/i,/(lunascape|maxthon|netfront|jasmine|blazer|sleipnir)[\/ ]?([\w\.]*)/i,/(avant|iemobile|slim(?:browser|boat|jet))[\/ ]?([\d\.]*)/i,/(?:ms|\()(ie) ([\w\.]+)/i,/(flock|rockmelt|midori|epiphany|silk|skyfire|ovibrowser|bolt|iron|vivaldi|iridium|phantomjs|bowser|qupzilla|falkon|rekonq|puffin|brave|whale(?!.+naver)|qqbrowserlite|duckduckgo|klar|helio|(?=comodo_)?dragon)\/([-\w\.]+)/i,/(heytap|ovi|115)browser\/([\d\.]+)/i,/(weibo)__([\d\.]+)/i],[l,h],[/quark(?:pc)?\/([-\w\.]+)/i],[h,[l,"Quark"]],[/\bddg\/([\w\.]+)/i],[h,[l,"DuckDuckGo"]],[/(?:\buc? ?browser|(?:juc.+)ucweb)[\/ ]?([\w\.]+)/i],[h,[l,"UC"+k]],[/microm.+\bqbcore\/([\w\.]+)/i,/\bqbcore\/([\w\.]+).+microm/i,/micromessenger\/([\w\.]+)/i],[h,[l,"WeChat"]],[/konqueror\/([\w\.]+)/i],[h,[l,"Konqueror"]],[/trident.+rv[: ]([\w\.]{1,9})\b.+like gecko/i],[h,[l,"IE"]],[/ya(?:search)?browser\/([\w\.]+)/i],[h,[l,"Yandex"]],[/slbrowser\/([\w\.]+)/i],[h,[l,"Smart Lenovo "+k]],[/(avast|avg)\/([\w\.]+)/i],[[l,/(.+)/,"$1 Secure "+k],h],[/\bfocus\/([\w\.]+)/i],[h,[l,P+" Focus"]],[/\bopt\/([\w\.]+)/i],[h,[l,M+" Touch"]],[/coc_coc\w+\/([\w\.]+)/i],[h,[l,"Coc Coc"]],[/dolfin\/([\w\.]+)/i],[h,[l,"Dolphin"]],[/coast\/([\w\.]+)/i],[h,[l,M+" Coast"]],[/miuibrowser\/([\w\.]+)/i],[h,[l,"MIUI"+U]],[/fxios\/([\w\.-]+)/i],[h,[l,P]],[/\bqihoobrowser\/?([\w\.]*)/i],[h,[l,"360"]],[/\b(qq)\/([\w\.]+)/i],[[l,/(.+)/,"$1Browser"],h],[/(oculus|sailfish|huawei|vivo|pico)browser\/([\w\.]+)/i],[[l,/(.+)/,"$1"+U],h],[/samsungbrowser\/([\w\.]+)/i],[h,[l,L+" Internet"]],[/metasr[\/ ]?([\d\.]+)/i],[h,[l,"Sogou Explorer"]],[/(sogou)mo\w+\/([\d\.]+)/i],[[l,"Sogou Mobile"],h],[/(electron)\/([\w\.]+) safari/i,/(tesla)(?: qtcarbrowser|\/(20\d\d\.[-\w\.]+))/i,/m?(qqbrowser|2345(?=browser|chrome|explorer))\w*[\/ ]?v?([\w\.]+)/i],[l,h],[/(lbbrowser|rekonq)/i,/\[(linkedin)app\]/i],[l],[/ome\/([\w\.]+) \w* ?(iron) saf/i,/ome\/([\w\.]+).+qihu (360)[es]e/i],[h,l],[/((?:fban\/fbios|fb_iab\/fb4a)(?!.+fbav)|;fbav\/([\w\.]+);)/i],[[l,F],h],[/(Klarna)\/([\w\.]+)/i,/(kakao(?:talk|story))[\/ ]([\w\.]+)/i,/(naver)\(.*?(\d+\.[\w\.]+).*\)/i,/safari (line)\/([\w\.]+)/i,/\b(line)\/([\w\.]+)\/iab/i,/(alipay)client\/([\w\.]+)/i,/(twitter)(?:and| f.+e\/([\w\.]+))/i,/(chromium|instagram|snapchat)[\/ ]([-\w\.]+)/i],[l,h],[/\bgsa\/([\w\.]+) .*safari\//i],[h,[l,"GSA"]],[/musical_ly(?:.+app_?version\/|_)([\w\.]+)/i],[h,[l,"TikTok"]],[/headlesschrome(?:\/([\w\.]+)| )/i],[h,[l,T+" Headless"]],[/ wv\).+(chrome)\/([\w\.]+)/i],[[l,T+" WebView"],h],[/droid.+ version\/([\w\.]+)\b.+(?:mobile safari|safari)/i],[h,[l,"Android "+k]],[/(chrome|omniweb|arora|[tizenoka]{5} ?browser)\/v?([\w\.]+)/i],[l,h],[/version\/([\w\.\,]+) .*mobile\/\w+ (safari)/i],[h,[l,"Mobile Safari"]],[/version\/([\w(\.|\,)]+) .*(mobile ?safari|safari)/i],[h,l],[/webkit.+?(mobile ?safari|safari)(\/[\w\.]+)/i],[l,[h,K,{"1.0":"/8",1.2:"/1",1.3:"/3","2.0":"/412","2.0.2":"/416","2.0.3":"/417","2.0.4":"/419","?":"/"}]],[/(webkit|khtml)\/([\w\.]+)/i],[l,h],[/(navigator|netscape\d?)\/([-\w\.]+)/i],[[l,"Netscape"],h],[/(wolvic|librewolf)\/([\w\.]+)/i],[l,h],[/mobile vr; rv:([\w\.]+)\).+firefox/i],[h,[l,P+" Reality"]],[/ekiohf.+(flow)\/([\w\.]+)/i,/(swiftfox)/i,/(icedragon|iceweasel|camino|chimera|fennec|maemo browser|minimo|conkeror)[\/ ]?([\w\.\+]+)/i,/(seamonkey|k-meleon|icecat|iceape|firebird|phoenix|palemoon|basilisk|waterfox)\/([-\w\.]+)$/i,/(firefox)\/([\w\.]+)/i,/(mozilla)\/([\w\.]+) .+rv\:.+gecko\/\d+/i,/(polaris|lynx|dillo|icab|doris|amaya|w3m|netsurf|obigo|mosaic|(?:go|ice|up)[\. ]?browser)[-\/ ]?v?([\w\.]+)/i,/(links) \(([\w\.]+)/i],[l,[h,/_/g,"."]],[/(cobalt)\/([\w\.]+)/i],[l,[h,/master.|lts./,""]]],cpu:[[/(?:(amd|x(?:(?:86|64)[-_])?|wow|win)64)[;\)]/i],[[f,"amd64"]],[/(ia32(?=;))/i],[[f,q]],[/((?:i[346]|x)86)[;\)]/i],[[f,"ia32"]],[/\b(aarch64|arm(v?8e?l?|_?64))\b/i],[[f,"arm64"]],[/\b(arm(?:v[67])?ht?n?[fl]p?)\b/i],[[f,"armhf"]],[/windows (ce|mobile); ppc;/i],[[f,"arm"]],[/((?:ppc|powerpc)(?:64)?)(?: mac|;|\))/i],[[f,/ower/,"",q]],[/(sun4\w)[;\)]/i],[[f,"sparc"]],[/((?:avr32|ia64(?=;))|68k(?=\))|\barm(?=v(?:[1-7]|[5-7]1)l?|;|eabi)|(?=atmel )avr|(?:irix|mips|sparc)(?:64)?\b|pa-risc)/i],[[f,q]]],device:[[/\b(sch-i[89]0\d|shw-m380s|sm-[ptx]\w{2,4}|gt-[pn]\d{2,4}|sgh-t8[56]9|nexus 10)/i],[d,[p,L],[u,v]],[/\b((?:s[cgp]h|gt|sm)-(?![lr])\w+|sc[g-]?[\d]+a?|galaxy nexus)/i,/samsung[- ]((?!sm-[lr])[-\w]+)/i,/sec-(sgh\w+)/i],[d,[p,L],[u,g]],[/(?:\/|\()(ip(?:hone|od)[\w, ]*)(?:\/|;)/i],[d,[p,S],[u,g]],[/\((ipad);[-\w\),; ]+apple/i,/applecoremedia\/[\w\.]+ \((ipad)/i,/\b(ipad)\d\d?,\d\d?[;\]].+ios/i],[d,[p,S],[u,v]],[/(macintosh);/i],[d,[p,S]],[/\b(sh-?[altvz]?\d\d[a-ekm]?)/i],[d,[p,j],[u,g]],[/(?:honor)([-\w ]+)[;\)]/i],[d,[p,"Honor"],[u,g]],[/\b((?:ag[rs][23]?|bah2?|sht?|btv)-a?[lw]\d{2})\b(?!.+d\/s)/i],[d,[p,O],[u,v]],[/(?:huawei)([-\w ]+)[;\)]/i,/\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][012359c][adn]?)\b(?!.+d\/s)/i],[d,[p,O],[u,g]],[/\b(poco[\w ]+|m2\d{3}j\d\d[a-z]{2})(?: bui|\))/i,/\b; (\w+) build\/hm\1/i,/\b(hm[-_ ]?note?[_ ]?(?:\d\w)?) bui/i,/\b(redmi[\-_ ]?(?:note|k)?[\w_ ]+)(?: bui|\))/i,/oid[^\)]+; (m?[12][0-389][01]\w{3,6}[c-y])( bui|; wv|\))/i,/\b(mi[-_ ]?(?:a\d|one|one[_ ]plus|note lte|max|cc)?[_ ]?(?:\d?\w?)[_ ]?(?:plus|se|lite|pro)?)(?: bui|\))/i],[[d,/_/g," "],[p,N],[u,g]],[/oid[^\)]+; (2\d{4}(283|rpbf)[cgl])( bui|\))/i,/\b(mi[-_ ]?(?:pad)(?:[\w_ ]+))(?: bui|\))/i],[[d,/_/g," "],[p,N],[u,v]],[/; (\w+) bui.+ oppo/i,/\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i],[d,[p,"OPPO"],[u,g]],[/\b(opd2\d{3}a?) bui/i],[d,[p,"OPPO"],[u,v]],[/vivo (\w+)(?: bui|\))/i,/\b(v[12]\d{3}\w?[at])(?: bui|;)/i],[d,[p,"Vivo"],[u,g]],[/\b(rmx[1-3]\d{3})(?: bui|;|\))/i],[d,[p,"Realme"],[u,g]],[/\b(milestone|droid(?:[2-4x]| (?:bionic|x2|pro|razr))?:?( 4g)?)\b[\w ]+build\//i,/\bmot(?:orola)?[- ](\w*)/i,/((?:moto[\w\(\) ]+|xt\d{3,4}|nexus 6)(?= bui|\)))/i],[d,[p,x],[u,g]],[/\b(mz60\d|xoom[2 ]{0,2}) build\//i],[d,[p,x],[u,v]],[/((?=lg)?[vl]k\-?\d{3}) bui| 3\.[-\w; ]{10}lg?-([06cv9]{3,4})/i],[d,[p,D],[u,v]],[/(lm(?:-?f100[nv]?|-[\w\.]+)(?= bui|\))|nexus [45])/i,/\blg[-e;\/ ]+((?!browser|netcast|android tv)\w+)/i,/\blg-?([\d\w]+) bui/i],[d,[p,D],[u,g]],[/(ideatab[-\w ]+)/i,/lenovo ?(s[56]000[-\w]+|tab(?:[\w ]+)|yt[-\d\w]{6}|tb[-\d\w]{6})/i],[d,[p,"Lenovo"],[u,v]],[/(?:maemo|nokia).*(n900|lumia \d+)/i,/nokia[-_ ]?([-\w\.]*)/i],[[d,/_/g," "],[p,"Nokia"],[u,g]],[/(pixel c)\b/i],[d,[p,E],[u,v]],[/droid.+; (pixel[\daxl ]{0,6})(?: bui|\))/i],[d,[p,E],[u,g]],[/droid.+; (a?\d[0-2]{2}so|[c-g]\d{4}|so[-gl]\w+|xq-a\w[4-7][12])(?= bui|\).+chrome\/(?![1-6]{0,1}\d\.))/i],[d,[p,A],[u,g]],[/sony tablet [ps]/i,/\b(?:sony)?sgp\w+(?: bui|\))/i],[[d,"Xperia Tablet"],[p,A],[u,v]],[/ (kb2005|in20[12]5|be20[12][59])\b/i,/(?:one)?(?:plus)? (a\d0\d\d)(?: b|\))/i],[d,[p,"OnePlus"],[u,g]],[/(alexa)webm/i,/(kf[a-z]{2}wi|aeo(?!bc)\w\w)( bui|\))/i,/(kf[a-z]+)( bui|\)).+silk\//i],[d,[p,_],[u,v]],[/((?:sd|kf)[0349hijorstuw]+)( bui|\)).+silk\//i],[[d,/(.+)/g,"Fire Phone $1"],[p,_],[u,g]],[/(playbook);[-\w\),; ]+(rim)/i],[d,p,[u,v]],[/\b((?:bb[a-f]|st[hv])100-\d)/i,/\(bb10; (\w+)/i],[d,[p,R],[u,g]],[/(?:\b|asus_)(transfo[prime ]{4,10} \w+|eeepc|slider \w+|nexus 7|padfone|p00[cj])/i],[d,[p,C],[u,v]],[/ (z[bes]6[027][012][km][ls]|zenfone \d\w?)\b/i],[d,[p,C],[u,g]],[/(nexus 9)/i],[d,[p,"HTC"],[u,v]],[/(htc)[-;_ ]{1,2}([\w ]+(?=\)| bui)|\w+)/i,/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,/(alcatel|geeksphone|nexian|panasonic(?!(?:;|\.))|sony(?!-bra))[-_ ]?([-\w]*)/i],[p,[d,/_/g," "],[u,g]],[/droid [\w\.]+; ((?:8[14]9[16]|9(?:0(?:48|60|8[01])|1(?:3[27]|66)|2(?:6[69]|9[56])|466))[gqswx])\w*(\)| bui)/i],[d,[p,"TCL"],[u,v]],[/(itel) ((\w+))/i],[[p,q],d,[u,K,{tablet:["p10001l","w7001"],"*":"mobile"}]],[/droid.+; ([ab][1-7]-?[0178a]\d\d?)/i],[d,[p,"Acer"],[u,v]],[/droid.+; (m[1-5] note) bui/i,/\bmz-([-\w]{2,})/i],[d,[p,"Meizu"],[u,g]],[/; ((?:power )?armor(?:[\w ]{0,8}))(?: bui|\))/i],[d,[p,"Ulefone"],[u,g]],[/; (energy ?\w+)(?: bui|\))/i,/; energizer ([\w ]+)(?: bui|\))/i],[d,[p,"Energizer"],[u,g]],[/; cat (b35);/i,/; (b15q?|s22 flip|s48c|s62 pro)(?: bui|\))/i],[d,[p,"Cat"],[u,g]],[/((?:new )?andromax[\w- ]+)(?: bui|\))/i],[d,[p,"Smartfren"],[u,g]],[/droid.+; (a(?:015|06[35]|142p?))/i],[d,[p,"Nothing"],[u,g]],[/(blackberry|benq|palm(?=\-)|sonyericsson|acer|asus|dell|meizu|motorola|polytron|infinix|tecno|micromax|advan)[-_ ]?([-\w]*)/i,/; (imo) ((?!tab)[\w ]+?)(?: bui|\))/i,/(hp) ([\w ]+\w)/i,/(asus)-?(\w+)/i,/(microsoft); (lumia[\w ]+)/i,/(lenovo)[-_ ]?([-\w]+)/i,/(jolla)/i,/(oppo) ?([\w ]+) bui/i],[p,d,[u,g]],[/(imo) (tab \w+)/i,/(kobo)\s(ereader|touch)/i,/(archos) (gamepad2?)/i,/(hp).+(touchpad(?!.+tablet)|tablet)/i,/(kindle)\/([\w\.]+)/i,/(nook)[\w ]+build\/(\w+)/i,/(dell) (strea[kpr\d ]*[\dko])/i,/(le[- ]+pan)[- ]+(\w{1,9}) bui/i,/(trinity)[- ]*(t\d{3}) bui/i,/(gigaset)[- ]+(q\w{1,9}) bui/i,/(vodafone) ([\w ]+)(?:\)| bui)/i],[p,d,[u,v]],[/(surface duo)/i],[d,[p,I],[u,v]],[/droid [\d\.]+; (fp\du?)(?: b|\))/i],[d,[p,"Fairphone"],[u,g]],[/(u304aa)/i],[d,[p,"AT&T"],[u,g]],[/\bsie-(\w*)/i],[d,[p,"Siemens"],[u,g]],[/\b(rct\w+) b/i],[d,[p,"RCA"],[u,v]],[/\b(venue[\d ]{2,7}) b/i],[d,[p,"Dell"],[u,v]],[/\b(q(?:mv|ta)\w+) b/i],[d,[p,"Verizon"],[u,v]],[/\b(?:barnes[& ]+noble |bn[rt])([\w\+ ]*) b/i],[d,[p,"Barnes & Noble"],[u,v]],[/\b(tm\d{3}\w+) b/i],[d,[p,"NuVision"],[u,v]],[/\b(k88) b/i],[d,[p,"ZTE"],[u,v]],[/\b(nx\d{3}j) b/i],[d,[p,"ZTE"],[u,g]],[/\b(gen\d{3}) b.+49h/i],[d,[p,"Swiss"],[u,g]],[/\b(zur\d{3}) b/i],[d,[p,"Swiss"],[u,v]],[/\b((zeki)?tb.*\b) b/i],[d,[p,"Zeki"],[u,v]],[/\b([yr]\d{2}) b/i,/\b(dragon[- ]+touch |dt)(\w{5}) b/i],[[p,"Dragon Touch"],d,[u,v]],[/\b(ns-?\w{0,9}) b/i],[d,[p,"Insignia"],[u,v]],[/\b((nxa|next)-?\w{0,9}) b/i],[d,[p,"NextBook"],[u,v]],[/\b(xtreme\_)?(v(1[045]|2[015]|[3469]0|7[05])) b/i],[[p,"Voice"],d,[u,g]],[/\b(lvtel\-)?(v1[12]) b/i],[[p,"LvTel"],d,[u,g]],[/\b(ph-1) /i],[d,[p,"Essential"],[u,g]],[/\b(v(100md|700na|7011|917g).*\b) b/i],[d,[p,"Envizen"],[u,v]],[/\b(trio[-\w\. ]+) b/i],[d,[p,"MachSpeed"],[u,v]],[/\btu_(1491) b/i],[d,[p,"Rotor"],[u,v]],[/(shield[\w ]+) b/i],[d,[p,"Nvidia"],[u,v]],[/(sprint) (\w+)/i],[p,d,[u,g]],[/(kin\.[onetw]{3})/i],[[d,/\./g," "],[p,I],[u,g]],[/droid.+; (cc6666?|et5[16]|mc[239][23]x?|vc8[03]x?)\)/i],[d,[p,B],[u,v]],[/droid.+; (ec30|ps20|tc[2-8]\d[kx])\)/i],[d,[p,B],[u,g]],[/smart-tv.+(samsung)/i],[p,[u,b]],[/hbbtv.+maple;(\d+)/i],[[d,/^/,"SmartTV"],[p,L],[u,b]],[/(nux; netcast.+smarttv|lg (netcast\.tv-201\d|android tv))/i],[[p,D],[u,b]],[/(apple) ?tv/i],[p,[d,S+" TV"],[u,b]],[/crkey/i],[[d,T+"cast"],[p,E],[u,b]],[/droid.+aft(\w+)( bui|\))/i],[d,[p,_],[u,b]],[/\(dtv[\);].+(aquos)/i,/(aquos-tv[\w ]+)\)/i],[d,[p,j],[u,b]],[/(bravia[\w ]+)( bui|\))/i],[d,[p,A],[u,b]],[/(mitv-\w{5}) bui/i],[d,[p,N],[u,b]],[/Hbbtv.*(technisat) (.*);/i],[p,d,[u,b]],[/\b(roku)[\dx]*[\)\/]((?:dvp-)?[\d\.]*)/i,/hbbtv\/\d+\.\d+\.\d+ +\([\w\+ ]*; *([\w\d][^;]*);([^;]*)/i],[[p,H],[d,H],[u,b]],[/\b(android tv|smart[- ]?tv|opera tv|tv; rv:)\b/i],[[u,b]],[/(ouya)/i,/(nintendo) ([wids3utch]+)/i],[p,d,[u,m]],[/droid.+; (shield) bui/i],[d,[p,"Nvidia"],[u,m]],[/(playstation [345portablevi]+)/i],[d,[p,A],[u,m]],[/\b(xbox(?: one)?(?!; xbox))[\); ]/i],[d,[p,I],[u,m]],[/\b(sm-[lr]\d\d[05][fnuw]?s?)\b/i],[d,[p,L],[u,y]],[/((pebble))app/i],[p,d,[u,y]],[/(watch)(?: ?os[,\/]|\d,\d\/)[\d\.]+/i],[d,[p,S],[u,y]],[/droid.+; (glass) \d/i],[d,[p,E],[u,y]],[/droid.+; (wt63?0{2,3})\)/i],[d,[p,B],[u,y]],[/droid.+; (glass) \d/i],[d,[p,E],[u,y]],[/(pico) (4|neo3(?: link|pro)?)/i],[p,d,[u,y]],[/; (quest( \d| pro)?)/i],[d,[p,F],[u,y]],[/(tesla)(?: qtcarbrowser|\/[-\w\.]+)/i],[p,[u,w]],[/(aeobc)\b/i],[d,[p,_],[u,w]],[/droid .+?; ([^;]+?)(?: bui|; wv\)|\) applew).+? mobile safari/i],[d,[u,g]],[/droid .+?; ([^;]+?)(?: bui|\) applew).+?(?! mobile) safari/i],[d,[u,v]],[/\b((tablet|tab)[;\/]|focus\/\d(?!.+mobile))/i],[[u,v]],[/(phone|mobile(?:[;\/]| [ \w\/\.]*safari)|pda(?=.+windows ce))/i],[[u,g]],[/(android[-\w\. ]{0,9});.+buil/i],[d,[p,"Generic"]]],engine:[[/windows.+ edge\/([\w\.]+)/i],[h,[l,"EdgeHTML"]],[/(arkweb)\/([\w\.]+)/i],[l,h],[/webkit\/537\.36.+chrome\/(?!27)([\w\.]+)/i],[h,[l,"Blink"]],[/(presto)\/([\w\.]+)/i,/(webkit|trident|netfront|netsurf|amaya|lynx|w3m|goanna|servo)\/([\w\.]+)/i,/ekioh(flow)\/([\w\.]+)/i,/(khtml|tasman|links)[\/ ]\(?([\w\.]+)/i,/(icab)[\/ ]([23]\.[\d\.]+)/i,/\b(libweb)/i],[l,h],[/rv\:([\w\.]{1,9})\b.+(gecko)/i],[h,l]],os:[[/microsoft (windows) (vista|xp)/i],[l,h],[/(windows (?:phone(?: os)?|mobile))[\/ ]?([\d\.\w ]*)/i],[l,[h,K,J]],[/windows nt 6\.2; (arm)/i,/windows[\/ ]?([ntce\d\. ]+\w)(?!.+xbox)/i,/(?:win(?=3|9|n)|win 9x )([nt\d\.]+)/i],[[h,K,J],[l,"Windows"]],[/ip[honead]{2,4}\b(?:.*os ([\w]+) like mac|; opera)/i,/(?:ios;fbsv\/|iphone.+ios[\/ ])([\d\.]+)/i,/cfnetwork\/.+darwin/i],[[h,/_/g,"."],[l,"iOS"]],[/(mac os x) ?([\w\. ]*)/i,/(macintosh|mac_powerpc\b)(?!.+haiku)/i],[[l,V],[h,/_/g,"."]],[/droid ([\w\.]+)\b.+(android[- ]x86|harmonyos)/i],[h,l],[/(android|webos|qnx|bada|rim tablet os|maemo|meego|sailfish|openharmony)[-\/ ]?([\w\.]*)/i,/(blackberry)\w*\/([\w\.]*)/i,/(tizen|kaios)[\/ ]([\w\.]+)/i,/\((series40);/i],[l,h],[/\(bb(10);/i],[h,[l,R]],[/(?:symbian ?os|symbos|s60(?=;)|series60)[-\/ ]?([\w\.]*)/i],[h,[l,"Symbian"]],[/mozilla\/[\d\.]+ \((?:mobile|tablet|tv|mobile; [\w ]+); rv:.+ gecko\/([\w\.]+)/i],[h,[l,P+" OS"]],[/web0s;.+rt(tv)/i,/\b(?:hp)?wos(?:browser)?\/([\w\.]+)/i],[h,[l,"webOS"]],[/watch(?: ?os[,\/]|\d,\d\/)([\d\.]+)/i],[h,[l,"watchOS"]],[/crkey\/([\d\.]+)/i],[h,[l,T+"cast"]],[/(cros) [\w]+(?:\)| ([\w\.]+)\b)/i],[[l,z],h],[/panasonic;(viera)/i,/(netrange)mmh/i,/(nettv)\/(\d+\.[\w\.]+)/i,/(nintendo|playstation) ([wids345portablevuch]+)/i,/(xbox); +xbox ([^\);]+)/i,/\b(joli|palm)\b ?(?:os)?\/?([\w\.]*)/i,/(mint)[\/\(\) ]?(\w*)/i,/(mageia|vectorlinux)[; ]/i,/([kxln]?ubuntu|debian|suse|opensuse|gentoo|arch(?= linux)|slackware|fedora|mandriva|centos|pclinuxos|red ?hat|zenwalk|linpus|raspbian|plan 9|minix|risc os|contiki|deepin|manjaro|elementary os|sabayon|linspire)(?: gnu\/linux)?(?: enterprise)?(?:[- ]linux)?(?:-gnu)?[-\/ ]?(?!chrom|package)([-\w\.]*)/i,/(hurd|linux) ?([\w\.]*)/i,/(gnu) ?([\w\.]*)/i,/\b([-frentopcghs]{0,5}bsd|dragonfly)[\/ ]?(?!amd|[ix346]{1,2}86)([\w\.]*)/i,/(haiku) (\w+)/i],[l,h],[/(sunos) ?([\w\.\d]*)/i],[[l,"Solaris"],h],[/((?:open)?solaris)[-\/ ]?([\w\.]*)/i,/(aix) ((\d)(?=\.|\)| )[\w\.])*/i,/\b(beos|os\/2|amigaos|morphos|openvms|fuchsia|hp-ux|serenityos)/i,/(unix) ?([\w\.]*)/i],[l,h]]},Q=function(e,t){if(typeof e===o&&(t=e,e=i),!(this instanceof Q))return new Q(e,t).getResult();var m=typeof r!==s&&r.navigator?r.navigator:i,b=e||(m&&m.userAgent?m.userAgent:""),y=m&&m.userAgentData?m.userAgentData:i,w=t?function(e,t){var r={};for(var i in e)t[i]&&t[i].length%2==0?r[i]=t[i].concat(e[i]):r[i]=e[i];return r}(X,t):X,_=m&&m.userAgent==b;return this.getBrowser=function(){var e,t={};return t[l]=i,t[h]=i,W.call(t,b,w.browser),t[c]=typeof(e=t[h])===a?e.replace(/[^\d\.]/g,"").split(".")[0]:i,_&&m&&m.brave&&typeof m.brave.isBrave==n&&(t[l]="Brave"),t},this.getCPU=function(){var e={};return e[f]=i,W.call(e,b,w.cpu),e},this.getDevice=function(){var e={};return e[p]=i,e[d]=i,e[u]=i,W.call(e,b,w.device),_&&!e[u]&&y&&y.mobile&&(e[u]=g),_&&"Macintosh"==e[d]&&m&&typeof m.standalone!==s&&m.maxTouchPoints&&m.maxTouchPoints>2&&(e[d]="iPad",e[u]=v),e},this.getEngine=function(){var e={};return e[l]=i,e[h]=i,W.call(e,b,w.engine),e},this.getOS=function(){var e={};return e[l]=i,e[h]=i,W.call(e,b,w.os),_&&!e[l]&&y&&y.platform&&"Unknown"!=y.platform&&(e[l]=y.platform.replace(/chrome os/i,z).replace(/macos/i,V)),e},this.getResult=function(){return{ua:this.getUA(),browser:this.getBrowser(),engine:this.getEngine(),os:this.getOS(),device:this.getDevice(),cpu:this.getCPU()}},this.getUA=function(){return b},this.setUA=function(e){return b=typeof e===a&&e.length>500?H(e,500):e,this},this.setUA(b),this};Q.VERSION="1.0.40",Q.BROWSER=$([l,h,c]),Q.CPU=$([f]),Q.DEVICE=$([d,p,u,m,g,b,v,y,w]),Q.ENGINE=Q.OS=$([l,h]),e.exports&&(t=e.exports=Q),t.UAParser=Q;var Z=typeof r!==s&&(r.jQuery||r.Zepto);if(Z&&!Z.ua){var Y=new Q;Z.ua=Y.getResult(),Z.ua.get=function(){return Y.getUA()},Z.ua.set=function(e){Y.setUA(e);var t=Y.getResult();for(var r in t)Z.ua[r]=t[r]}}}("object"==typeof window?window:a)}(Lp,Lp.exports);var jp=Lp.exports;function Ap(){}function Np(){Np.init.call(this)}function Bp(e){return void 0===e._maxListeners?Np.defaultMaxListeners:e._maxListeners}function Fp(e,t,r,i){var n,s,o,a;if("function"!=typeof r)throw new TypeError('"listener" argument must be a function');if((s=e._events)?(s.newListener&&(e.emit("newListener",t,r.listener?r.listener:r),s=e._events),o=s[t]):(s=e._events=new Ap,e._eventsCount=0),o){if("function"==typeof o?o=s[t]=i?[r,o]:[o,r]:i?o.unshift(r):o.push(r),!o.warned&&(n=Bp(e))&&n>0&&o.length>n){o.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+t+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=e,c.type=t,c.count=o.length,a=c,"function"==typeof console.warn?console.warn(a):console.log(a)}}else o=s[t]=r,++e._eventsCount;return e}function zp(e,t,r){var i=!1;function n(){e.removeListener(t,n),i||(i=!0,r.apply(e,arguments))}return n.listener=r,n}function Vp(e){var t=this._events;if(t){var r=t[e];if("function"==typeof r)return 1;if(r)return r.length}return 0}function Up(e,t){for(var r=new Array(t);t--;)r[t]=e[t];return r}Ap.prototype=Object.create(null),Np.EventEmitter=Np,Np.usingDomains=!1,Np.prototype.domain=void 0,Np.prototype._events=void 0,Np.prototype._maxListeners=void 0,Np.defaultMaxListeners=10,Np.init=function(){this.domain=null,Np.usingDomains&&undefined.active,this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new Ap,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},Np.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||isNaN(e))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=e,this},Np.prototype.getMaxListeners=function(){return Bp(this)},Np.prototype.emit=function(e){var t,r,i,n,s,o,a,c="error"===e;if(o=this._events)c=c&&null==o.error;else if(!c)return!1;if(a=this.domain,c){if(t=arguments[1],!a){if(t instanceof Error)throw t;var d=new Error('Uncaught, unspecified "error" event. ('+t+")");throw d.context=t,d}return t||(t=new Error('Uncaught, unspecified "error" event')),t.domainEmitter=this,t.domain=a,t.domainThrown=!1,a.emit("error",t),!1}if(!(r=o[e]))return!1;var l="function"==typeof r;switch(i=arguments.length){case 1:!function(e,t,r){if(t)e.call(r);else for(var i=e.length,n=Up(e,i),s=0;s<i;++s)n[s].call(r)}(r,l,this);break;case 2:!function(e,t,r,i){if(t)e.call(r,i);else for(var n=e.length,s=Up(e,n),o=0;o<n;++o)s[o].call(r,i)}(r,l,this,arguments[1]);break;case 3:!function(e,t,r,i,n){if(t)e.call(r,i,n);else for(var s=e.length,o=Up(e,s),a=0;a<s;++a)o[a].call(r,i,n)}(r,l,this,arguments[1],arguments[2]);break;case 4:!function(e,t,r,i,n,s){if(t)e.call(r,i,n,s);else for(var o=e.length,a=Up(e,o),c=0;c<o;++c)a[c].call(r,i,n,s)}(r,l,this,arguments[1],arguments[2],arguments[3]);break;default:for(n=new Array(i-1),s=1;s<i;s++)n[s-1]=arguments[s];!function(e,t,r,i){if(t)e.apply(r,i);else for(var n=e.length,s=Up(e,n),o=0;o<n;++o)s[o].apply(r,i)}(r,l,this,n)}return!0},Np.prototype.addListener=function(e,t){return Fp(this,e,t,!1)},Np.prototype.on=Np.prototype.addListener,Np.prototype.prependListener=function(e,t){return Fp(this,e,t,!0)},Np.prototype.once=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.on(e,zp(this,e,t)),this},Np.prototype.prependOnceListener=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.prependListener(e,zp(this,e,t)),this},Np.prototype.removeListener=function(e,t){var r,i,n,s,o;if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');if(!(i=this._events))return this;if(!(r=i[e]))return this;if(r===t||r.listener&&r.listener===t)0==--this._eventsCount?this._events=new Ap:(delete i[e],i.removeListener&&this.emit("removeListener",e,r.listener||t));else if("function"!=typeof r){for(n=-1,s=r.length;s-- >0;)if(r[s]===t||r[s].listener&&r[s].listener===t){o=r[s].listener,n=s;break}if(n<0)return this;if(1===r.length){if(r[0]=void 0,0==--this._eventsCount)return this._events=new Ap,this;delete i[e]}else!function(e,t){for(var r=t,i=r+1,n=e.length;i<n;r+=1,i+=1)e[r]=e[i];e.pop()}(r,n);i.removeListener&&this.emit("removeListener",e,o||t)}return this},Np.prototype.off=function(e,t){return this.removeListener(e,t)},Np.prototype.removeAllListeners=function(e){var t,r;if(!(r=this._events))return this;if(!r.removeListener)return 0===arguments.length?(this._events=new Ap,this._eventsCount=0):r[e]&&(0==--this._eventsCount?this._events=new Ap:delete r[e]),this;if(0===arguments.length){for(var i,n=Object.keys(r),s=0;s<n.length;++s)"removeListener"!==(i=n[s])&&this.removeAllListeners(i);return this.removeAllListeners("removeListener"),this._events=new Ap,this._eventsCount=0,this}if("function"==typeof(t=r[e]))this.removeListener(e,t);else if(t)do{this.removeListener(e,t[t.length-1])}while(t[0]);return this},Np.prototype.listeners=function(e){var t,r,i=this._events;return r=i&&(t=i[e])?"function"==typeof t?[t.listener||t]:function(e){for(var t=new Array(e.length),r=0;r<t.length;++r)t[r]=e[r].listener||e[r];return t}(t):[],r},Np.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):Vp.call(e,t)},Np.prototype.listenerCount=Vp,Np.prototype.eventNames=function(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]};const $p=Object.create(null);$p.open="0",$p.close="1",$p.ping="2",$p.pong="3",$p.message="4",$p.upgrade="5",$p.noop="6";const Gp=Object.create(null);Object.keys($p).forEach((e=>{Gp[$p[e]]=e}));const qp={type:"error",data:"parser error"},Hp="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),Wp="function"==typeof ArrayBuffer,Kp=e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,Jp=({type:e,data:t},r,i)=>Hp&&t instanceof Blob?r?i(t):Xp(t,i):Wp&&(t instanceof ArrayBuffer||Kp(t))?r?i(t):Xp(new Blob([t]),i):i($p[e]+(t||"")),Xp=(e,t)=>{const r=new FileReader;return r.onload=function(){const e=r.result.split(",")[1];t("b"+(e||""))},r.readAsDataURL(e)};function Qp(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let Zp;const Yp="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",eh="undefined"==typeof Uint8Array?[]:new Uint8Array(256);for(let zO=0;zO<64;zO++)eh[Yp.charCodeAt(zO)]=zO;const th="function"==typeof ArrayBuffer,rh=(e,t)=>{if("string"!=typeof e)return{type:"message",data:nh(e,t)};const r=e.charAt(0);if("b"===r)return{type:"message",data:ih(e.substring(1),t)};return Gp[r]?e.length>1?{type:Gp[r],data:e.substring(1)}:{type:Gp[r]}:qp},ih=(e,t)=>{if(th){const r=(e=>{let t,r,i,n,s,o=.75*e.length,a=e.length,c=0;"="===e[e.length-1]&&(o--,"="===e[e.length-2]&&o--);const d=new ArrayBuffer(o),l=new Uint8Array(d);for(t=0;t<a;t+=4)r=eh[e.charCodeAt(t)],i=eh[e.charCodeAt(t+1)],n=eh[e.charCodeAt(t+2)],s=eh[e.charCodeAt(t+3)],l[c++]=r<<2|i>>4,l[c++]=(15&i)<<4|n>>2,l[c++]=(3&n)<<6|63&s;return d})(e);return nh(r,t)}return{base64:!0,data:e}},nh=(e,t)=>"blob"===t?e instanceof Blob?e:new Blob([e]):e instanceof ArrayBuffer?e:e.buffer,sh=String.fromCharCode(30);function oh(){return new TransformStream({transform(e,t){!function(e,t){Hp&&e.data instanceof Blob?e.data.arrayBuffer().then(Qp).then(t):Wp&&(e.data instanceof ArrayBuffer||Kp(e.data))?t(Qp(e.data)):Jp(e,!1,(e=>{Zp||(Zp=new TextEncoder),t(Zp.encode(e))}))}(e,(r=>{const i=r.length;let n;if(i<126)n=new Uint8Array(1),new DataView(n.buffer).setUint8(0,i);else if(i<65536){n=new Uint8Array(3);const e=new DataView(n.buffer);e.setUint8(0,126),e.setUint16(1,i)}else{n=new Uint8Array(9);const e=new DataView(n.buffer);e.setUint8(0,127),e.setBigUint64(1,BigInt(i))}e.data&&"string"!=typeof e.data&&(n[0]|=128),t.enqueue(n),t.enqueue(r)}))}})}let ah;function ch(e){return e.reduce(((e,t)=>e+t.length),0)}function dh(e,t){if(e[0].length===t)return e.shift();const r=new Uint8Array(t);let i=0;for(let n=0;n<t;n++)r[n]=e[0][i++],i===e[0].length&&(e.shift(),i=0);return e.length&&i<e[0].length&&(e[0]=e[0].slice(i)),r}function lh(e){if(e)return function(e){for(var t in lh.prototype)e[t]=lh.prototype[t];return e}(e)}lh.prototype.on=lh.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this},lh.prototype.once=function(e,t){function r(){this.off(e,r),t.apply(this,arguments)}return r.fn=t,this.on(e,r),this},lh.prototype.off=lh.prototype.removeListener=lh.prototype.removeAllListeners=lh.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var r,i=this._callbacks["$"+e];if(!i)return this;if(1==arguments.length)return delete this._callbacks["$"+e],this;for(var n=0;n<i.length;n++)if((r=i[n])===t||r.fn===t){i.splice(n,1);break}return 0===i.length&&delete this._callbacks["$"+e],this},lh.prototype.emit=function(e){this._callbacks=this._callbacks||{};for(var t=new Array(arguments.length-1),r=this._callbacks["$"+e],i=1;i<arguments.length;i++)t[i-1]=arguments[i];if(r){i=0;for(var n=(r=r.slice(0)).length;i<n;++i)r[i].apply(this,t)}return this},lh.prototype.emitReserved=lh.prototype.emit,lh.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]},lh.prototype.hasListeners=function(e){return!!this.listeners(e).length};const uh="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")();function ph(e,...t){return t.reduce(((t,r)=>(e.hasOwnProperty(r)&&(t[r]=e[r]),t)),{})}const hh=uh.setTimeout,fh=uh.clearTimeout;function mh(e,t){t.useNativeTimers?(e.setTimeoutFn=hh.bind(uh),e.clearTimeoutFn=fh.bind(uh)):(e.setTimeoutFn=uh.setTimeout.bind(uh),e.clearTimeoutFn=uh.clearTimeout.bind(uh))}class gh extends Error{constructor(e,t,r){super(e),this.description=t,this.context=r,this.type="TransportError"}}class vh extends lh{constructor(e){super(),this.writable=!1,mh(this,e),this.opts=e,this.query=e.query,this.socket=e.socket}onError(e,t,r){return super.emitReserved("error",new gh(e,t,r)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return"opening"!==this.readyState&&"open"!==this.readyState||(this.doClose(),this.onClose()),this}send(e){"open"===this.readyState&&this.write(e)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){const t=rh(e,this.socket.binaryType);this.onPacket(t)}onPacket(e){super.emitReserved("packet",e)}onClose(e){this.readyState="closed",super.emitReserved("close",e)}pause(e){}createUri(e,t={}){return e+"://"+this._hostname()+this._port()+this.opts.path+this._query(t)}_hostname(){const e=this.opts.hostname;return-1===e.indexOf(":")?e:"["+e+"]"}_port(){return this.opts.port&&(this.opts.secure&&Number(443!==this.opts.port)||!this.opts.secure&&80!==Number(this.opts.port))?":"+this.opts.port:""}_query(e){const t=function(e){let t="";for(let r in e)e.hasOwnProperty(r)&&(t.length&&(t+="&"),t+=encodeURIComponent(r)+"="+encodeURIComponent(e[r]));return t}(e);return t.length?"?"+t:""}}const bh="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_".split(""),yh=64,wh={};let _h,Sh=0,Ch=0;function Rh(e){let t="";do{t=bh[e%yh]+t,e=Math.floor(e/yh)}while(e>0);return t}function kh(){const e=Rh(+new Date);return e!==_h?(Sh=0,_h=e):e+"."+Rh(Sh++)}for(;Ch<yh;Ch++)wh[bh[Ch]]=Ch;let Th=!1;try{Th="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(VO){}const Ph=Th;function Eh(e){const t=e.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!t||Ph))return new XMLHttpRequest}catch(e){}if(!t)try{return new(uh[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(e){}}function Oh(){}const Dh=null!=new Eh({xdomain:!1}).responseType;class Ih extends lh{constructor(e,t){super(),mh(this,t),this.opts=t,this.method=t.method||"GET",this.uri=e,this.data=void 0!==t.data?t.data:null,this.create()}create(){var e;const t=ph(this.opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");t.xdomain=!!this.opts.xd;const r=this.xhr=new Eh(t);try{r.open(this.method,this.uri,!0);try{if(this.opts.extraHeaders){r.setDisableHeaderCheck&&r.setDisableHeaderCheck(!0);for(let e in this.opts.extraHeaders)this.opts.extraHeaders.hasOwnProperty(e)&&r.setRequestHeader(e,this.opts.extraHeaders[e])}}catch(e){}if("POST"===this.method)try{r.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(e){}try{r.setRequestHeader("Accept","*/*")}catch(e){}null===(e=this.opts.cookieJar)||void 0===e||e.addCookies(r),"withCredentials"in r&&(r.withCredentials=this.opts.withCredentials),this.opts.requestTimeout&&(r.timeout=this.opts.requestTimeout),r.onreadystatechange=()=>{var e;3===r.readyState&&(null===(e=this.opts.cookieJar)||void 0===e||e.parseCookies(r)),4===r.readyState&&(200===r.status||1223===r.status?this.onLoad():this.setTimeoutFn((()=>{this.onError("number"==typeof r.status?r.status:0)}),0))},r.send(this.data)}catch(e){return void this.setTimeoutFn((()=>{this.onError(e)}),0)}"undefined"!=typeof document&&(this.index=Ih.requestsCount++,Ih.requests[this.index]=this)}onError(e){this.emitReserved("error",e,this.xhr),this.cleanup(!0)}cleanup(e){if(void 0!==this.xhr&&null!==this.xhr){if(this.xhr.onreadystatechange=Oh,e)try{this.xhr.abort()}catch(e){}"undefined"!=typeof document&&delete Ih.requests[this.index],this.xhr=null}}onLoad(){const e=this.xhr.responseText;null!==e&&(this.emitReserved("data",e),this.emitReserved("success"),this.cleanup())}abort(){this.cleanup()}}if(Ih.requestsCount=0,Ih.requests={},"undefined"!=typeof document)if("function"==typeof attachEvent)attachEvent("onunload",xh);else if("function"==typeof addEventListener){addEventListener("onpagehide"in uh?"pagehide":"unload",xh,!1)}function xh(){for(let e in Ih.requests)Ih.requests.hasOwnProperty(e)&&Ih.requests[e].abort()}const Mh="function"==typeof Promise&&"function"==typeof Promise.resolve?e=>Promise.resolve().then(e):(e,t)=>t(e,0),Lh=uh.WebSocket||uh.MozWebSocket,jh="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();const Ah={websocket:class extends vh{constructor(e){super(e),this.supportsBinary=!e.forceBase64}get name(){return"websocket"}doOpen(){if(!this.check())return;const e=this.uri(),t=this.opts.protocols,r=jh?{}:ph(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(r.headers=this.opts.extraHeaders);try{this.ws=jh?new Lh(e,t,r):t?new Lh(e,t):new Lh(e)}catch(e){return this.emitReserved("error",e)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const r=e[t],i=t===e.length-1;Jp(r,this.supportsBinary,(e=>{try{this.ws.send(e)}catch(e){}i&&Mh((()=>{this.writable=!0,this.emitReserved("drain")}),this.setTimeoutFn)}))}}doClose(){void 0!==this.ws&&(this.ws.close(),this.ws=null)}uri(){const e=this.opts.secure?"wss":"ws",t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=kh()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}check(){return!!Lh}},webtransport:class extends vh{get name(){return"webtransport"}doOpen(){"function"==typeof WebTransport&&(this.transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name]),this.transport.closed.then((()=>{this.onClose()})).catch((e=>{this.onError("webtransport error",e)})),this.transport.ready.then((()=>{this.transport.createBidirectionalStream().then((e=>{const t=function(e,t){ah||(ah=new TextDecoder);const r=[];let i=0,n=-1,s=!1;return new TransformStream({transform(o,a){for(r.push(o);;){if(0===i){if(ch(r)<1)break;const e=dh(r,1);s=128==(128&e[0]),n=127&e[0],i=n<126?3:126===n?1:2}else if(1===i){if(ch(r)<2)break;const e=dh(r,2);n=new DataView(e.buffer,e.byteOffset,e.length).getUint16(0),i=3}else if(2===i){if(ch(r)<8)break;const e=dh(r,8),t=new DataView(e.buffer,e.byteOffset,e.length),s=t.getUint32(0);if(s>Math.pow(2,21)-1){a.enqueue(qp);break}n=s*Math.pow(2,32)+t.getUint32(4),i=3}else{if(ch(r)<n)break;const e=dh(r,n);a.enqueue(rh(s?e:ah.decode(e),t)),i=0}if(0===n||n>e){a.enqueue(qp);break}}}})}(Number.MAX_SAFE_INTEGER,this.socket.binaryType),r=e.readable.pipeThrough(t).getReader(),i=oh();i.readable.pipeTo(e.writable),this.writer=i.writable.getWriter();const n=()=>{r.read().then((({done:e,value:t})=>{e||(this.onPacket(t),n())})).catch((e=>{}))};n();const s={type:"open"};this.query.sid&&(s.data=`{"sid":"${this.query.sid}"}`),this.writer.write(s).then((()=>this.onOpen()))}))})))}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const r=e[t],i=t===e.length-1;this.writer.write(r).then((()=>{i&&Mh((()=>{this.writable=!0,this.emitReserved("drain")}),this.setTimeoutFn)}))}}doClose(){var e;null===(e=this.transport)||void 0===e||e.close()}},polling:class extends vh{constructor(e){if(super(e),this.polling=!1,"undefined"!=typeof location){const t="https:"===location.protocol;let r=location.port;r||(r=t?"443":"80"),this.xd="undefined"!=typeof location&&e.hostname!==location.hostname||r!==e.port}const t=e&&e.forceBase64;this.supportsBinary=Dh&&!t,this.opts.withCredentials&&(this.cookieJar=void 0)}get name(){return"polling"}doOpen(){this.poll()}pause(e){this.readyState="pausing";const t=()=>{this.readyState="paused",e()};if(this.polling||!this.writable){let e=0;this.polling&&(e++,this.once("pollComplete",(function(){--e||t()}))),this.writable||(e++,this.once("drain",(function(){--e||t()})))}else t()}poll(){this.polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){((e,t)=>{const r=e.split(sh),i=[];for(let e=0;e<r.length;e++){const n=rh(r[e],t);if(i.push(n),"error"===n.type)break}return i})(e,this.socket.binaryType).forEach((e=>{if("opening"===this.readyState&&"open"===e.type&&this.onOpen(),"close"===e.type)return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(e)})),"closed"!==this.readyState&&(this.polling=!1,this.emitReserved("pollComplete"),"open"===this.readyState&&this.poll())}doClose(){const e=()=>{this.write([{type:"close"}])};"open"===this.readyState?e():this.once("open",e)}write(e){this.writable=!1,((e,t)=>{const r=e.length,i=new Array(r);let n=0;e.forEach(((e,s)=>{Jp(e,!1,(e=>{i[s]=e,++n===r&&t(i.join(sh))}))}))})(e,(e=>{this.doWrite(e,(()=>{this.writable=!0,this.emitReserved("drain")}))}))}uri(){const e=this.opts.secure?"https":"http",t=this.query||{};return!1!==this.opts.timestampRequests&&(t[this.opts.timestampParam]=kh()),this.supportsBinary||t.sid||(t.b64=1),this.createUri(e,t)}request(e={}){return Object.assign(e,{xd:this.xd,cookieJar:this.cookieJar},this.opts),new Ih(this.uri(),e)}doWrite(e,t){const r=this.request({method:"POST",data:e});r.on("success",t),r.on("error",((e,t)=>{this.onError("xhr post error",e,t)}))}doPoll(){const e=this.request();e.on("data",this.onData.bind(this)),e.on("error",((e,t)=>{this.onError("xhr poll error",e,t)})),this.pollXhr=e}}},Nh=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,Bh=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function Fh(e){if(e.length>2e3)throw"URI too long";const t=e,r=e.indexOf("["),i=e.indexOf("]");-1!=r&&-1!=i&&(e=e.substring(0,r)+e.substring(r,i).replace(/:/g,";")+e.substring(i,e.length));let n=Nh.exec(e||""),s={},o=14;for(;o--;)s[Bh[o]]=n[o]||"";return-1!=r&&-1!=i&&(s.source=t,s.host=s.host.substring(1,s.host.length-1).replace(/;/g,":"),s.authority=s.authority.replace("[","").replace("]","").replace(/;/g,":"),s.ipv6uri=!0),s.pathNames=function(e,t){const r=/\/{2,9}/g,i=t.replace(r,"/").split("/");"/"!=t.slice(0,1)&&0!==t.length||i.splice(0,1);"/"==t.slice(-1)&&i.splice(i.length-1,1);return i}(0,s.path),s.queryKey=function(e,t){const r={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,(function(e,t,i){t&&(r[t]=i)})),r}(0,s.query),s}let zh=class e extends lh{constructor(e,t={}){super(),this.binaryType="arraybuffer",this.writeBuffer=[],e&&"object"==typeof e&&(t=e,e=null),e?(e=Fh(e),t.hostname=e.host,t.secure="https"===e.protocol||"wss"===e.protocol,t.port=e.port,e.query&&(t.query=e.query)):t.host&&(t.hostname=Fh(t.host).host),mh(this,t),this.secure=null!=t.secure?t.secure:"undefined"!=typeof location&&"https:"===location.protocol,t.hostname&&!t.port&&(t.port=this.secure?"443":"80"),this.hostname=t.hostname||("undefined"!=typeof location?location.hostname:"localhost"),this.port=t.port||("undefined"!=typeof location&&location.port?location.port:this.secure?"443":"80"),this.transports=t.transports||["polling","websocket","webtransport"],this.writeBuffer=[],this.prevBufferLen=0,this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},t),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),"string"==typeof this.opts.query&&(this.opts.query=function(e){let t={},r=e.split("&");for(let e=0,i=r.length;e<i;e++){let i=r[e].split("=");t[decodeURIComponent(i[0])]=decodeURIComponent(i[1])}return t}(this.opts.query)),this.id=null,this.upgrades=null,this.pingInterval=null,this.pingTimeout=null,this.pingTimeoutTimer=null,"function"==typeof addEventListener&&(this.opts.closeOnBeforeunload&&(this.beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this.beforeunloadEventListener,!1)),"localhost"!==this.hostname&&(this.offlineEventListener=()=>{this.onClose("transport close",{description:"network connection lost"})},addEventListener("offline",this.offlineEventListener,!1))),this.open()}createTransport(e){const t=Object.assign({},this.opts.query);t.EIO=4,t.transport=e,this.id&&(t.sid=this.id);const r=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return new Ah[e](r)}open(){let t;if(this.opts.rememberUpgrade&&e.priorWebsocketSuccess&&-1!==this.transports.indexOf("websocket"))t="websocket";else{if(0===this.transports.length)return void this.setTimeoutFn((()=>{this.emitReserved("error","No transports available")}),0);t=this.transports[0]}this.readyState="opening";try{t=this.createTransport(t)}catch(e){return this.transports.shift(),void this.open()}t.open(),this.setTransport(t)}setTransport(e){this.transport&&this.transport.removeAllListeners(),this.transport=e,e.on("drain",this.onDrain.bind(this)).on("packet",this.onPacket.bind(this)).on("error",this.onError.bind(this)).on("close",(e=>this.onClose("transport close",e)))}probe(t){let r=this.createTransport(t),i=!1;e.priorWebsocketSuccess=!1;const n=()=>{i||(r.send([{type:"ping",data:"probe"}]),r.once("packet",(t=>{if(!i)if("pong"===t.type&&"probe"===t.data){if(this.upgrading=!0,this.emitReserved("upgrading",r),!r)return;e.priorWebsocketSuccess="websocket"===r.name,this.transport.pause((()=>{i||"closed"!==this.readyState&&(l(),this.setTransport(r),r.send([{type:"upgrade"}]),this.emitReserved("upgrade",r),r=null,this.upgrading=!1,this.flush())}))}else{const e=new Error("probe error");e.transport=r.name,this.emitReserved("upgradeError",e)}})))};function s(){i||(i=!0,l(),r.close(),r=null)}const o=e=>{const t=new Error("probe error: "+e);t.transport=r.name,s(),this.emitReserved("upgradeError",t)};function a(){o("transport closed")}function c(){o("socket closed")}function d(e){r&&e.name!==r.name&&s()}const l=()=>{r.removeListener("open",n),r.removeListener("error",o),r.removeListener("close",a),this.off("close",c),this.off("upgrading",d)};r.once("open",n),r.once("error",o),r.once("close",a),this.once("close",c),this.once("upgrading",d),-1!==this.upgrades.indexOf("webtransport")&&"webtransport"!==t?this.setTimeoutFn((()=>{i||r.open()}),200):r.open()}onOpen(){if(this.readyState="open",e.priorWebsocketSuccess="websocket"===this.transport.name,this.emitReserved("open"),this.flush(),"open"===this.readyState&&this.opts.upgrade){let e=0;const t=this.upgrades.length;for(;e<t;e++)this.probe(this.upgrades[e])}}onPacket(e){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState)switch(this.emitReserved("packet",e),this.emitReserved("heartbeat"),this.resetPingTimeout(),e.type){case"open":this.onHandshake(JSON.parse(e.data));break;case"ping":this.sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong");break;case"error":const t=new Error("server error");t.code=e.data,this.onError(t);break;case"message":this.emitReserved("data",e.data),this.emitReserved("message",e.data)}}onHandshake(e){this.emitReserved("handshake",e),this.id=e.sid,this.transport.query.sid=e.sid,this.upgrades=this.filterUpgrades(e.upgrades),this.pingInterval=e.pingInterval,this.pingTimeout=e.pingTimeout,this.maxPayload=e.maxPayload,this.onOpen(),"closed"!==this.readyState&&this.resetPingTimeout()}resetPingTimeout(){this.clearTimeoutFn(this.pingTimeoutTimer),this.pingTimeoutTimer=this.setTimeoutFn((()=>{this.onClose("ping timeout")}),this.pingInterval+this.pingTimeout),this.opts.autoUnref&&this.pingTimeoutTimer.unref()}onDrain(){this.writeBuffer.splice(0,this.prevBufferLen),this.prevBufferLen=0,0===this.writeBuffer.length?this.emitReserved("drain"):this.flush()}flush(){if("closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const e=this.getWritablePackets();this.transport.send(e),this.prevBufferLen=e.length,this.emitReserved("flush")}}getWritablePackets(){if(!(this.maxPayload&&"polling"===this.transport.name&&this.writeBuffer.length>1))return this.writeBuffer;let e=1;for(let r=0;r<this.writeBuffer.length;r++){const i=this.writeBuffer[r].data;if(i&&(e+="string"==typeof(t=i)?function(e){let t=0,r=0;for(let i=0,n=e.length;i<n;i++)t=e.charCodeAt(i),t<128?r+=1:t<2048?r+=2:t<55296||t>=57344?r+=3:(i++,r+=4);return r}(t):Math.ceil(1.33*(t.byteLength||t.size))),r>0&&e>this.maxPayload)return this.writeBuffer.slice(0,r);e+=2}var t;return this.writeBuffer}write(e,t,r){return this.sendPacket("message",e,t,r),this}send(e,t,r){return this.sendPacket("message",e,t,r),this}sendPacket(e,t,r,i){if("function"==typeof t&&(i=t,t=void 0),"function"==typeof r&&(i=r,r=null),"closing"===this.readyState||"closed"===this.readyState)return;(r=r||{}).compress=!1!==r.compress;const n={type:e,data:t,options:r};this.emitReserved("packetCreate",n),this.writeBuffer.push(n),i&&this.once("flush",i),this.flush()}close(){const e=()=>{this.onClose("forced close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),e()},r=()=>{this.once("upgrade",t),this.once("upgradeError",t)};return"opening"!==this.readyState&&"open"!==this.readyState||(this.readyState="closing",this.writeBuffer.length?this.once("drain",(()=>{this.upgrading?r():e()})):this.upgrading?r():e()),this}onError(t){e.priorWebsocketSuccess=!1,this.emitReserved("error",t),this.onClose("transport error",t)}onClose(e,t){"opening"!==this.readyState&&"open"!==this.readyState&&"closing"!==this.readyState||(this.clearTimeoutFn(this.pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),"function"==typeof removeEventListener&&(removeEventListener("beforeunload",this.beforeunloadEventListener,!1),removeEventListener("offline",this.offlineEventListener,!1)),this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this.prevBufferLen=0)}filterUpgrades(e){const t=[];let r=0;const i=e.length;for(;r<i;r++)~this.transports.indexOf(e[r])&&t.push(e[r]);return t}};zh.protocol=4;const Vh="function"==typeof ArrayBuffer,Uh=e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer,$h=Object.prototype.toString,Gh="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===$h.call(Blob),qh="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===$h.call(File);function Hh(e){return Vh&&(e instanceof ArrayBuffer||Uh(e))||Gh&&e instanceof Blob||qh&&e instanceof File}function Wh(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e)){for(let t=0,r=e.length;t<r;t++)if(Wh(e[t]))return!0;return!1}if(Hh(e))return!0;if(e.toJSON&&"function"==typeof e.toJSON&&1===arguments.length)return Wh(e.toJSON(),!0);for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t)&&Wh(e[t]))return!0;return!1}function Kh(e){const t=[],r=e.data,i=e;return i.data=Jh(r,t),i.attachments=t.length,{packet:i,buffers:t}}function Jh(e,t){if(!e)return e;if(Hh(e)){const r={_placeholder:!0,num:t.length};return t.push(e),r}if(Array.isArray(e)){const r=new Array(e.length);for(let i=0;i<e.length;i++)r[i]=Jh(e[i],t);return r}if("object"==typeof e&&!(e instanceof Date)){const r={};for(const i in e)Object.prototype.hasOwnProperty.call(e,i)&&(r[i]=Jh(e[i],t));return r}return e}function Xh(e,t){return e.data=Qh(e.data,t),delete e.attachments,e}function Qh(e,t){if(!e)return e;if(e&&!0===e._placeholder){if("number"==typeof e.num&&e.num>=0&&e.num<t.length)return t[e.num];throw new Error("illegal attachments")}if(Array.isArray(e))for(let r=0;r<e.length;r++)e[r]=Qh(e[r],t);else if("object"==typeof e)for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&(e[r]=Qh(e[r],t));return e}const Zh=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var Yh;!function(e){e[e.CONNECT=0]="CONNECT",e[e.DISCONNECT=1]="DISCONNECT",e[e.EVENT=2]="EVENT",e[e.ACK=3]="ACK",e[e.CONNECT_ERROR=4]="CONNECT_ERROR",e[e.BINARY_EVENT=5]="BINARY_EVENT",e[e.BINARY_ACK=6]="BINARY_ACK"}(Yh||(Yh={}));function ef(e){return"[object Object]"===Object.prototype.toString.call(e)}class tf extends lh{constructor(e){super(),this.reviver=e}add(e){let t;if("string"==typeof e){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");t=this.decodeString(e);const r=t.type===Yh.BINARY_EVENT;r||t.type===Yh.BINARY_ACK?(t.type=r?Yh.EVENT:Yh.ACK,this.reconstructor=new rf(t),0===t.attachments&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else{if(!Hh(e)&&!e.base64)throw new Error("Unknown type: "+e);if(!this.reconstructor)throw new Error("got binary data when not reconstructing a packet");t=this.reconstructor.takeBinaryData(e),t&&(this.reconstructor=null,super.emitReserved("decoded",t))}}decodeString(e){let t=0;const r={type:Number(e.charAt(0))};if(void 0===Yh[r.type])throw new Error("unknown packet type "+r.type);if(r.type===Yh.BINARY_EVENT||r.type===Yh.BINARY_ACK){const i=t+1;for(;"-"!==e.charAt(++t)&&t!=e.length;);const n=e.substring(i,t);if(n!=Number(n)||"-"!==e.charAt(t))throw new Error("Illegal attachments");r.attachments=Number(n)}if("/"===e.charAt(t+1)){const i=t+1;for(;++t;){if(","===e.charAt(t))break;if(t===e.length)break}r.nsp=e.substring(i,t)}else r.nsp="/";const i=e.charAt(t+1);if(""!==i&&Number(i)==i){const i=t+1;for(;++t;){const r=e.charAt(t);if(null==r||Number(r)!=r){--t;break}if(t===e.length)break}r.id=Number(e.substring(i,t+1))}if(e.charAt(++t)){const i=this.tryParse(e.substr(t));if(!tf.isPayloadValid(r.type,i))throw new Error("invalid payload");r.data=i}return r}tryParse(e){try{return JSON.parse(e,this.reviver)}catch(e){return!1}}static isPayloadValid(e,t){switch(e){case Yh.CONNECT:return ef(t);case Yh.DISCONNECT:return void 0===t;case Yh.CONNECT_ERROR:return"string"==typeof t||ef(t);case Yh.EVENT:case Yh.BINARY_EVENT:return Array.isArray(t)&&("number"==typeof t[0]||"string"==typeof t[0]&&-1===Zh.indexOf(t[0]));case Yh.ACK:case Yh.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class rf{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){const e=Xh(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}var nf=Object.freeze({__proto__:null,Decoder:tf,Encoder:class{constructor(e){this.replacer=e}encode(e){return e.type!==Yh.EVENT&&e.type!==Yh.ACK||!Wh(e)?[this.encodeAsString(e)]:this.encodeAsBinary({type:e.type===Yh.EVENT?Yh.BINARY_EVENT:Yh.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id})}encodeAsString(e){let t=""+e.type;return e.type!==Yh.BINARY_EVENT&&e.type!==Yh.BINARY_ACK||(t+=e.attachments+"-"),e.nsp&&"/"!==e.nsp&&(t+=e.nsp+","),null!=e.id&&(t+=e.id),null!=e.data&&(t+=JSON.stringify(e.data,this.replacer)),t}encodeAsBinary(e){const t=Kh(e),r=this.encodeAsString(t.packet),i=t.buffers;return i.unshift(r),i}},get PacketType(){return Yh},protocol:5});function sf(e,t,r){return e.on(t,r),function(){e.off(t,r)}}const of=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class af extends lh{constructor(e,t,r){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,r&&r.auth&&(this.auth=r.auth),this._opts=Object.assign({},r),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const e=this.io;this.subs=[sf(e,"open",this.onopen.bind(this)),sf(e,"packet",this.onpacket.bind(this)),sf(e,"error",this.onerror.bind(this)),sf(e,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected||(this.subEvents(),this.io._reconnecting||this.io.open(),"open"===this.io._readyState&&this.onopen()),this}open(){return this.connect()}send(...e){return e.unshift("message"),this.emit.apply(this,e),this}emit(e,...t){if(of.hasOwnProperty(e))throw new Error('"'+e.toString()+'" is a reserved event name');if(t.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;const r={type:Yh.EVENT,data:t,options:{}};if(r.options.compress=!1!==this.flags.compress,"function"==typeof t[t.length-1]){const e=this.ids++,i=t.pop();this._registerAckCallback(e,i),r.id=e}const i=this.io.engine&&this.io.engine.transport&&this.io.engine.transport.writable;return this.flags.volatile&&(!i||!this.connected)||(this.connected?(this.notifyOutgoingListeners(r),this.packet(r)):this.sendBuffer.push(r)),this.flags={},this}_registerAckCallback(e,t){var r;const i=null!==(r=this.flags.timeout)&&void 0!==r?r:this._opts.ackTimeout;if(void 0===i)return void(this.acks[e]=t);const n=this.io.setTimeoutFn((()=>{delete this.acks[e];for(let t=0;t<this.sendBuffer.length;t++)this.sendBuffer[t].id===e&&this.sendBuffer.splice(t,1);t.call(this,new Error("operation has timed out"))}),i);this.acks[e]=(...e)=>{this.io.clearTimeoutFn(n),t.apply(this,[null,...e])}}emitWithAck(e,...t){const r=void 0!==this.flags.timeout||void 0!==this._opts.ackTimeout;return new Promise(((i,n)=>{t.push(((e,t)=>r?e?n(e):i(t):i(e))),this.emit(e,...t)}))}_addToQueue(e){let t;"function"==typeof e[e.length-1]&&(t=e.pop());const r={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push(((e,...i)=>{if(r!==this._queue[0])return;return null!==e?r.tryCount>this._opts.retries&&(this._queue.shift(),t&&t(e)):(this._queue.shift(),t&&t(null,...i)),r.pending=!1,this._drainQueue()})),this._queue.push(r),this._drainQueue()}_drainQueue(e=!1){if(!this.connected||0===this._queue.length)return;const t=this._queue[0];t.pending&&!e||(t.pending=!0,t.tryCount++,this.flags=t.flags,this.emit.apply(this,t.args))}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){"function"==typeof this.auth?this.auth((e=>{this._sendConnectPacket(e)})):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:Yh.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved("connect_error",e)}onclose(e,t){this.connected=!1,delete this.id,this.emitReserved("disconnect",e,t)}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case Yh.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case Yh.EVENT:case Yh.BINARY_EVENT:this.onevent(e);break;case Yh.ACK:case Yh.BINARY_ACK:this.onack(e);break;case Yh.DISCONNECT:this.ondisconnect();break;case Yh.CONNECT_ERROR:this.destroy();const t=new Error(e.data.message);t.data=e.data.data,this.emitReserved("connect_error",t)}}onevent(e){const t=e.data||[];null!=e.id&&t.push(this.ack(e.id)),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){const t=this._anyListeners.slice();for(const r of t)r.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&"string"==typeof e[e.length-1]&&(this._lastOffset=e[e.length-1])}ack(e){const t=this;let r=!1;return function(...i){r||(r=!0,t.packet({type:Yh.ACK,id:e,data:i}))}}onack(e){const t=this.acks[e.id];"function"==typeof t&&(t.apply(this,e.data),delete this.acks[e.id])}onconnect(e,t){this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach((e=>this.emitEvent(e))),this.receiveBuffer=[],this.sendBuffer.forEach((e=>{this.notifyOutgoingListeners(e),this.packet(e)})),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach((e=>e())),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:Yh.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){const t=this._anyListeners;for(let r=0;r<t.length;r++)if(e===t[r])return t.splice(r,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){const t=this._anyOutgoingListeners;for(let r=0;r<t.length;r++)if(e===t[r])return t.splice(r,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const t=this._anyOutgoingListeners.slice();for(const r of t)r.apply(this,e.data)}}}function cf(e){e=e||{},this.ms=e.min||100,this.max=e.max||1e4,this.factor=e.factor||2,this.jitter=e.jitter>0&&e.jitter<=1?e.jitter:0,this.attempts=0}cf.prototype.duration=function(){var e=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),r=Math.floor(t*this.jitter*e);e=0==(1&Math.floor(10*t))?e-r:e+r}return 0|Math.min(e,this.max)},cf.prototype.reset=function(){this.attempts=0},cf.prototype.setMin=function(e){this.ms=e},cf.prototype.setMax=function(e){this.max=e},cf.prototype.setJitter=function(e){this.jitter=e};class df extends lh{constructor(e,t){var r;super(),this.nsps={},this.subs=[],e&&"object"==typeof e&&(t=e,e=void 0),(t=t||{}).path=t.path||"/socket.io",this.opts=t,mh(this,t),this.reconnection(!1!==t.reconnection),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor(null!==(r=t.randomizationFactor)&&void 0!==r?r:.5),this.backoff=new cf({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==t.timeout?2e4:t.timeout),this._readyState="closed",this.uri=e;const i=t.parser||nf;this.encoder=new i.Encoder,this.decoder=new i.Decoder,this._autoConnect=!1!==t.autoConnect,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,this):this._reconnection}reconnectionAttempts(e){return void 0===e?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return void 0===e?this._reconnectionDelay:(this._reconnectionDelay=e,null===(t=this.backoff)||void 0===t||t.setMin(e),this)}randomizationFactor(e){var t;return void 0===e?this._randomizationFactor:(this._randomizationFactor=e,null===(t=this.backoff)||void 0===t||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return void 0===e?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,null===(t=this.backoff)||void 0===t||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&0===this.backoff.attempts&&this.reconnect()}open(e){if(~this._readyState.indexOf("open"))return this;this.engine=new zh(this.uri,this.opts);const t=this.engine,r=this;this._readyState="opening",this.skipReconnect=!1;const i=sf(t,"open",(function(){r.onopen(),e&&e()})),n=t=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",t),e?e(t):this.maybeReconnectOnOpen()},s=sf(t,"error",n);if(!1!==this._timeout){const e=this._timeout,r=this.setTimeoutFn((()=>{i(),n(new Error("timeout")),t.close()}),e);this.opts.autoUnref&&r.unref(),this.subs.push((()=>{this.clearTimeoutFn(r)}))}return this.subs.push(i),this.subs.push(s),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const e=this.engine;this.subs.push(sf(e,"ping",this.onping.bind(this)),sf(e,"data",this.ondata.bind(this)),sf(e,"error",this.onerror.bind(this)),sf(e,"close",this.onclose.bind(this)),sf(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(e){this.onclose("parse error",e)}}ondecoded(e){Mh((()=>{this.emitReserved("packet",e)}),this.setTimeoutFn)}onerror(e){this.emitReserved("error",e)}socket(e,t){let r=this.nsps[e];return r?this._autoConnect&&!r.active&&r.connect():(r=new af(this,e,t),this.nsps[e]=r),r}_destroy(e){const t=Object.keys(this.nsps);for(const e of t){if(this.nsps[e].active)return}this._close()}_packet(e){const t=this.encoder.encode(e);for(let r=0;r<t.length;r++)this.engine.write(t[r],e.options)}cleanup(){this.subs.forEach((e=>e())),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close"),this.engine&&this.engine.close()}disconnect(){return this._close()}onclose(e,t){this.cleanup(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const e=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const t=this.backoff.duration();this._reconnecting=!0;const r=this.setTimeoutFn((()=>{e.skipReconnect||(this.emitReserved("reconnect_attempt",e.backoff.attempts),e.skipReconnect||e.open((t=>{t?(e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",t)):e.onreconnect()})))}),t);this.opts.autoUnref&&r.unref(),this.subs.push((()=>{this.clearTimeoutFn(r)}))}}onreconnect(){const e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}}const lf={};function uf(e,t){"object"==typeof e&&(t=e,e=void 0);const r=function(e,t="",r){let i=e;r=r||"undefined"!=typeof location&&location,null==e&&(e=r.protocol+"//"+r.host),"string"==typeof e&&("/"===e.charAt(0)&&(e="/"===e.charAt(1)?r.protocol+e:r.host+e),/^(https?|wss?):\/\//.test(e)||(e=void 0!==r?r.protocol+"//"+e:"https://"+e),i=Fh(e)),i.port||(/^(http|ws)$/.test(i.protocol)?i.port="80":/^(http|ws)s$/.test(i.protocol)&&(i.port="443")),i.path=i.path||"/";const n=-1!==i.host.indexOf(":")?"["+i.host+"]":i.host;return i.id=i.protocol+"://"+n+":"+i.port+t,i.href=i.protocol+"://"+n+(r&&r.port===i.port?"":":"+i.port),i}(e,(t=t||{}).path||"/socket.io"),i=r.source,n=r.id,s=r.path,o=lf[n]&&s in lf[n].nsps;let a;return t.forceNew||t["force new connection"]||!1===t.multiplex||o?a=new df(i,t):(lf[n]||(lf[n]=new df(i,t)),a=lf[n]),r.query&&!t.query&&(t.query=r.queryKey),a.socket(r.path,t)}Object.assign(uf,{Manager:df,Socket:af,io:uf,connect:uf});const pf=new URLSearchParams(window.location.search).has("debug");class hf{constructor(){this._isEnabled=!1,this._isEnabled=pf}isEnabled(){return this._isEnabled}enable(){this._isEnabled=!0}disable(){this._isEnabled=!1}info(...e){if(this._isEnabled)return console.info(...e)}warn(...e){if(this._isEnabled)return console.warn(...e)}error(...e){if(this._isEnabled)return console.error(...e)}withDebugLogger(e){return this._debugger=e,this}debug(...e){if(!this._isEnabled||!this._debugger)return;const t=[];e.forEach((e=>{if("function"==typeof e){const r=e();t.push(r)}else t.push(e)})),this._debugger.print(...t)}}function ff(e,t,r,i){return new(r||(r=Promise))((function(n,s){function o(e){try{c(i.next(e))}catch(e){s(e)}}function a(e){try{c(i.throw(e))}catch(e){s(e)}}function c(e){e.done?n(e.value):function(e){return e instanceof r?e:new r((function(t){t(e)}))}(e.value).then(o,a)}c((i=i.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError,pi.default;const mf={id:_i(),connectionNumber:0},gf=()=>{};let vf=gf;const bf=function(e,t=console){const r=[];let i,n,s,o,a,c,d,l,u,p,h,f,m=0,g=!1,v=0;const b={connected:!1,trace:(...e)=>{if(e.push(Date.now()),"customEvent"===e[0]&&"roomSessionId"===e[2].type){const t=c&&c[2].value.roomSessionId,r=e[2].value.roomSessionId;c=e,g&&r&&r!==t&&(null==i||i.close()),r&&(g=!0)}else"customEvent"===e[0]&&"clientId"===e[2].type?s=e:"customEvent"===e[0]&&"organizationId"===e[2].type?n=e:"customEvent"===e[0]&&"displayName"===e[2].type?o=e:"customEvent"===e[0]&&"userRole"===e[2].type?a=e:"customEvent"===e[0]&&"deviceId"===e[2].type?l=e:"customEvent"===e[0]&&"roomProduct"===e[2].type?u=e:"customEvent"===e[0]&&"roomMode"===e[2].type?p=e:"customEvent"===e[0]&&"sfuServer"===e[2].type?h=e:"customEvent"===e[0]&&"featureFlags"===e[2].type&&(f=e);(null==i?void 0:i.readyState)===WebSocket.OPEN?(m=0,i.send(JSON.stringify(e))):"getstats"===e[0]?v<20&&(v++,r.push(e)):"customEvent"===e[0]&&"insightsStats"===e[2].type||r.push(e),(null==i?void 0:i.readyState)===WebSocket.CLOSED&&d&&setTimeout((()=>{i.readyState===WebSocket.CLOSED&&d&&b.connect()}),1e3*m)},close:()=>{d=!1,null==i||i.close()},connect:()=>{d=!0,m+=1,null==i||i.close(),b.connected=!0,i=new WebSocket(e+window.location.pathname,"1.0"),i.onerror=e=>{b.connected=!1,t.warn("[RTCSTATS] WebSocket error",e)},i.onclose=e=>{b.connected=!1,t.info(`[RTCSTATS] Closed ${e.code}`),vf()},i.onopen=()=>{for(mf.connectionNumber++,i.send(JSON.stringify(["clientInfo",null,mf])),n&&i.send(JSON.stringify(n)),s&&i.send(JSON.stringify(s)),c&&i.send(JSON.stringify(c)),o&&i.send(JSON.stringify(o)),a&&i.send(JSON.stringify(a)),l&&i.send(JSON.stringify(l)),p&&i.send(JSON.stringify(p)),u&&i.send(JSON.stringify(u)),h&&i.send(JSON.stringify(h)),f&&i.send(JSON.stringify(f));r.length;)i.send(JSON.stringify(r.shift()));v=0}}};return b}("wss://rtcstats.srv.whereby.com"),yf=mi(bf.trace,1e4,[""]);vf=(null==yf?void 0:yf.resetDelta)||gf;const wf={sendEvent:(e,t)=>{bf.trace("customEvent",null,{type:e,value:t})},sendAudioMuted:e=>{wf.sendEvent("audio_muted",{muted:e})},sendVideoMuted:e=>{wf.sendEvent("video_muted",{muted:e})},server:bf};let _f=[],Sf=0;const Cf=new WeakMap,Rf=e=>{_f=_f.filter((t=>t!==e))};if(window.RTCPeerConnection){const UO=window.RTCPeerConnection;function $O(e){const t=new UO(e);_f.push(t),Cf.set(t,{index:Sf++});const r=()=>{"closed"===t.connectionState&&(Rf(t),t.removeEventListener("connectionstatechange",r))};return t.addEventListener("connectionstatechange",r),t}$O.prototype=UO.prototype,window.RTCPeerConnection=$O}const kf=e=>{var t;return null===(t=Cf.get(e))||void 0===t?void 0:t.index},Tf=new WeakMap;const Pf=()=>Promise.all(_f.map((e=>ff(void 0,void 0,void 0,(function*(){let t=Tf.get(e);t||(t={ssrcToTrackId:{}},Tf.set(e,t));try{const r=yield e.getStats();let i=null;if(r.forEach((e=>{if(!("inbound-rtp"!==e.type&&"outbound-rtp"!==e.type||e.trackIdentifier||t.ssrcToTrackId[e.ssrc])){if(e.mediaSourceId){const i=r.get(e.mediaSourceId);i&&i.trackIdentifier&&(t.ssrcToTrackId[e.ssrc]=i.trackIdentifier)}if(!t.ssrcToTrackId[e.ssrc]&&e.trackId){const i=r.get(e.trackId);i&&i.trackIdentifier&&(t.ssrcToTrackId[e.ssrc]=i.trackIdentifier)}t.ssrcToTrackId[e.ssrc]||(i||(i=[]),i.push(e.ssrc))}})),i){const r=[...e.getSenders(),...e.getReceivers()];(yield Promise.all(r.map((e=>e.getStats())))).forEach(((e,i)=>{e.forEach((e=>{"inbound-rtp"!==e.type&&"outbound-rtp"!==e.type||(t.ssrcToTrackId[e.ssrc]=r[i].track.id)}))})),i.forEach((e=>{t.ssrcToTrackId[e]||(t.ssrcToTrackId[e]="?"+e)}))}return[e,r,t]}catch(r){return wf.sendEvent("trackSsrcLookupFailed",{name:null==r?void 0:r.name,cause:null==r?void 0:r.cause,message:null==r?void 0:r.message}),[e,[],t]}}))))),Ef=(e,t,r,i,n,s)=>{let o=e[i];o||(o={tracks:{},startTime:t,updated:t},e[i]=o),o.updated=t;let a=o.tracks[n];a||(a={ssrcs:{},startTime:t,updated:t},o.tracks[n]=a),a.updated=t;let c=a.ssrcs[s];return c||(c={startTime:t,updated:t,pcIndex:r},a.ssrcs[s]=c),c.updated=t,c},Of=(e,t)=>{Object.entries(e).forEach((([r,i])=>{i.updated<t?delete e[r]:Object.entries(i.tracks).forEach((([e,r])=>{r.updated<t?delete i.tracks[e]:Object.entries(r.ssrcs).forEach((([e,i])=>{i.updated<t&&delete r.ssrcs[e]}))}))}))};function Df(e,{logger:t,interval:r},i){return ff(this,void 0,void 0,(function*(){const n=Df.bind(null,e,{interval:r,logger:t});try{const t=e.getClients(),s=t.find((e=>e.isLocalClient&&!e.isPresentation))||{id:"unknown"};let o=e.statsByView[s.id];o||(o={tracks:{},candidatePairs:{},pressure:null},e.statsByView[s.id]=o),o.pressure=e.lastPressureObserverRecord;if(Date.now()-e.lastUpdateTime<400)return i?e.statsByView:(e.subscriptions.forEach((r=>{var i;return null===(i=r.onUpdatedStats)||void 0===i?void 0:i.call(r,e.statsByView,t)})),void(e.nextTimeout=setTimeout(n,r)));if(e.lastUpdateTime=Date.now(),(yield Pf()).forEach((([i,n,a])=>{const c=kf(i);"closed"===i.connectionState&&(n=new Map,Rf(i)),a.previousSSRCs=a.currentSSRCs||{},a.currentSSRCs={},n.forEach((i=>{var d,l,u;if("candidate-pair"===i.type&&/inprogress|succeeded/.test(i.state)){const t=null===(d=a._oldReport)||void 0===d?void 0:d.get(i.id),s=t?i.timestamp-t.timestamp:r,l=c+":"+i.id;let u=o.candidatePairs[l];u||(u={startTime:e.lastUpdateTime,id:l},o.candidatePairs[l]=u),function(e,t,r,i,n){const s=t.bytesReceived-((null==r?void 0:r.bytesReceived)||0),o=t.bytesSent-((null==r?void 0:r.bytesSent)||0);e.bitrateIn=8e3*s/i,e.bitrateOut=8e3*o/i,e.state=t.state,e.roundTripTime=t.currentRoundTripTime,e.requestsSent=t.requestsSent,e.responsesReceived=t.responsesReceived,e.requestsReceived=t.requestsReceived,e.responsesSent=t.responsesSent,e.availableOutgoingBitrate=t.availableOutgoingBitrate,e.availableIncomingBitrate=t.availableIncomingBitrate;const a=n.get(t.remoteCandidateId),c=n.get(t.localCandidateId);e.usingTurn=!1,c&&/relay/i.test(c.candidateType||"")&&(e.usingTurn=!0,e.turnProtocol=c.relayProtocol),a&&c&&(e.localEp=`${c.protocol}:${c.address||c.ip}:${c.port} ${c.candidateType} (${c.networkType})`,e.remoteEp=`${a.protocol}:${a.address||a.ip}:${a.port} ${a.candidateType}`)}(u,i,t,s,n),u.lastRtcStatsTime=e.lastUpdateTime}if("inbound-rtp"===i.type||"outbound-rtp"===i.type){const o=i.mediaType||i.kind,d=i.ssrc;let p=i.trackIdentifier||a.ssrcToTrackId[d],h=null===(l=a._oldReport)||void 0===l?void 0:l.get(i.id);if(h&&h.mediaSourceId!==i.mediaSourceId){const e=n.get(i.mediaSourceId);e&&e.trackIdentifier&&(p=e.trackIdentifier,a.ssrcToTrackId[d]=p)}const f=t.find((e=>{var t;return(null===(t=e[o].track)||void 0===t?void 0:t.id)===p}))||s;if(!i.trackIdentifier&&a.ssrcToTrackId[d]&&(null===(u=f[o].track)||void 0===u?void 0:u.id)&&f[o].track.id!==a.ssrcToTrackId[d]&&(p=f[o].track.id,a.ssrcToTrackId[d]=f[o].track.id),a.currentSSRCs[d]=f.id,h){const e=n.get(i.transportId),t=a._oldReport.get(h.transportId);(t&&(null==e?void 0:e.selectedCandidatePairId)!==t.selectedCandidatePairId||i.bytesReceived<h.bytesReceived||i.bytesSent<h.bytesSent)&&(h=null)}const m=h?i.timestamp-h.timestamp:r,g=Ef(e.statsByView,e.lastUpdateTime,c,f.id,p,d);!function(e,t,r,i,n){if(e.codec)return;e.kind=t.kind||t.mediaType,e.ssrc=t.ssrc,e.direction="inbound-rtp"===t.type?"in":"out";const s=t.codecId&&n.get(t.codecId);e.codec=s&&[s.mimeType,s.channels&&`${s.channels}ch`,s.clockRate,s.payloadType,t.encoderImplementation||t.decoderImplementation,s.sdpFmtpLine].filter(Boolean).join(" "),e.mid=t.mid,e.rid=t.rid}(g,i,0,0,n),function(e,t,r,i,n){const s=(t.nackCount||0)-((null==r?void 0:r.nackCount)||0);if(e.nackCount=(e.nackCount||0)+s,e.nackRate=1e3*s/i,"in"===e.direction){const n=t.packetsReceived-((null==r?void 0:r.packetsReceived)||0);e.packetCount=(e.packetCount||0)+n,e.packetRate=1e3*n/i;const s=t.packetsLost-((null==r?void 0:r.packetsLost)||0);e.packetLossCount=(e.packetLossCount||0)+s,e.packetLossRate=1e3*s/i,e.lossRatio=s/(s+n)*1e3/i;const o=t.bytesReceived-((null==r?void 0:r.bytesReceived)||0);e.byteCount=(e.byteCount||0)+o;let a=0;t.headerBytesReceived&&(a=t.headerBytesReceived-((null==r?void 0:r.headerBytesReceived)||0),e.headerByteCount=(e.headerByteCount||0)+a);const c=o+a;if(e.bitrate=8e3*c/i,e.mediaRatio=o/c,"audio"===t.kind){const i=(t.fecBytesReceived||0)-((null==r?void 0:r.fecBytesReceived)||0);e.fecRatio=i/o}const d=(t.jitterBufferDelay||0)-((null==r?void 0:r.jitterBufferDelay)||0),l=(t.jitterBufferEmittedCount||0)-((null==r?void 0:r.jitterBufferEmittedCount)||0);e.jitter=l?d/l:0}else{const s=t.packetsSent-((null==r?void 0:r.packetsSent)||0);e.packetCount=(e.packetCount||0)+s,e.packetRate=1e3*s/i;const o=t.bytesSent-((null==r?void 0:r.bytesSent)||0);e.byteCount=(e.byteCount||0)+o;let a=0;t.headerBytesSent&&(a=t.headerBytesSent-((null==r?void 0:r.headerBytesSent)||0),e.headerByteCount=(e.headerByteCount||0)+a);const c=o+a;e.bitrate=8e3*c/i,e.mediaRatio=o/c;const d=t.totalPacketSendDelay-((null==r?void 0:r.totalPacketSendDelay)||0);e.sendDelay=d/s;const l=t.retransmittedPacketsSent-((null==r?void 0:r.retransmittedPacketsSent)||0);if(e.retransRatio=l/s*1e3/i,t.remoteId){const r=n.get(t.remoteId);r&&(e.roundTripTime=r.roundTripTime||0,e.jitter=r.jitter||0,e.fractionLost=r.fractionLost||0)}}}(g,i,h,m,n),"video"===o&&function(e,t,r,i,n){e.width=t.frameWidth,e.height=t.frameHeight,e.qualityLimitationReason=t.qualityLimitationReason||"";const s=t.pliCount-((null==r?void 0:r.pliCount)||0);e.pliCount=(e.pliCount||0)+s,e.pliRate=1e3*s/i;const o=t.firCount-((null==r?void 0:r.firCount)||0);if(e.firCount=(e.firCount||0)+o,e.firRate=1e3*o/i,"in"===e.direction){const n=t.keyFramesDecoded-((null==r?void 0:r.keyFramesDecoded)||0);e.kfCount=(e.kfCount||0)+n,e.kfRate=1e3*n/i;const s=t.framesDecoded-((null==r?void 0:r.framesDecoded)||0);e.frameCount=(e.frameCount||0)+s;const o=t.qpSum-((null==r?void 0:r.qpSum)||0);e.qpf=o/s,e.fps=1e3*s/i}else{const s=t.keyFramesEncoded-((null==r?void 0:r.keyFramesEncoded)||0);e.kfCount=(e.kfCount||0)+s,e.kfRate=1e3*s/i;const o=t.framesEncoded-((null==r?void 0:r.framesEncoded)||0);e.frameCount=(e.frameCount||0)+o;const a=t.qpSum-((null==r?void 0:r.qpSum)||0);e.qpf=a/o,e.fps=1e3*o/i;const c=t.totalEncodeTime-((null==r?void 0:r.totalEncodeTime)||0);if(e.encodeTime=c/o,t.mediaSourceId){const r=n.get(t.mediaSourceId);r&&(e.sourceWidth=r.width||0,e.sourceHeight=r.height||0,e.sourceFps=r.framesPerSecond||0)}}}(g,i,h,m,n),"audio"===o&&function(e,t,r,i,n){const s=t.packetsDiscarded-((null==r?void 0:r.packetsDiscarded)||0);if(e.packetsDiscarded=(e.packetsDiscarded||0)+s,"in"===e.direction){const i=t.totalAudioEnergy-((null==r?void 0:r.totalAudioEnergy)||0),n=t.totalSamplesDuration-((null==r?void 0:r.totalSamplesDuration)||0);e.audioLevel=Math.sqrt(i/n);const s=t.totalSamplesReceived||0,o=t.concealmentEvents||0,a=s-((null==r?void 0:r.totalSamplesReceived)||0),c=t.concealedSamples||0,d=c-((null==r?void 0:r.concealedSamples)||0),l=(t.silentConcealedSamples||0)-((null==r?void 0:r.silentConcealedSamples)||0),u=(t.insertedSamplesForDeceleration||0)-((null==r?void 0:r.insertedSamplesForDeceleration)||0),p=(t.removedSamplesForAcceleration||0)-((null==r?void 0:r.removedSamplesForAcceleration)||0);e.audioSamples=s,e.audioConcealmentEvents=o,e.audioConcealedSamples=c,e.audioConcealment=d?d/a:0,e.audioSilentConcealment=l?l/a:0,e.audioAcceleration=p?p/a:0,e.audioDeceleration=u?u/a:0}}(g,i,h)}})),a._oldReport=n,Object.keys(a.previousSSRCs).filter((e=>!a.currentSSRCs[e])).forEach((t=>{const r=a.previousSSRCs[t];if(r){const i=e.statsByView[r];i&&Object.values(i.tracks).forEach((e=>{e.ssrcs[t]&&delete e.ssrcs[t]}))}}))})),Of(e.statsByView,e.lastUpdateTime),Object.entries((null==o?void 0:o.candidatePairs)||{}).forEach((([t,r])=>{const i=r.lastRtcStatsTime===e.lastUpdateTime;r.active=i,i||(r.state="old/inactive",r.inactiveFromTime?e.lastUpdateTime-r.inactiveFromTime>4e3&&delete o.candidatePairs[t]:r.inactiveFromTime=e.lastUpdateTime)})),i)return e.statsByView;e.subscriptions.forEach((r=>{var i;return null===(i=r.onUpdatedStats)||void 0===i?void 0:i.call(r,e.statsByView,t)}))}catch(r){t.warn(r),e.numFailedStatsReports++,wf.sendEvent("collectStatsFailed",{name:null==r?void 0:r.name,cause:null==r?void 0:r.cause,message:null==r?void 0:r.message})}e.nextTimeout=setTimeout(n,r)}))}const If={};function xf(e,t=If,r=window.document){e.forEach((({hostnamePattern:e,token:i})=>{const n=`${e}-${i}`;if(!t[n]&&e.test(r.location.hostname)){const e=r.createElement("meta");e.httpEquiv="origin-trial",e.content=i,r.head.append(e),t[n]=!0}}))}const Mf={sampleRate:1,originTrials:[{hostnamePattern:/hereby\.dev/,token:"AkSNPHJw6EK08X0QU7kORnK9NABzRLAC7dqfXOwk5JwFAQG4Ey7WxLXxsnhieCgC1QHUdevE2EFICy7uBGDANwUAAABqeyJvcmlnaW4iOiJodHRwczovL2hlcmVieS5kZXY6NDQ0MyIsImZlYXR1cmUiOiJDb21wdXRlUHJlc3N1cmVfdjIiLCJleHBpcnkiOjE3MTY5NDA3OTksImlzU3ViZG9tYWluIjp0cnVlfQ=="},{hostnamePattern:/whereby\.com/,token:"Asc2wu8KpSx648i932NICteQDFcB05yl2QUUSHD7AQo8JGP2Fp6FF91TvYVJBsKGzLMH349rysPw5q9tqPC/PAUAAABqeyJvcmlnaW4iOiJodHRwczovL3doZXJlYnkuY29tOjQ0MyIsImZlYXR1cmUiOiJDb21wdXRlUHJlc3N1cmVfdjIiLCJleHBpcnkiOjE3MTY5NDA3OTksImlzU3ViZG9tYWluIjp0cnVlfQ=="}]};const Lf={currentMonitor:null,getClients:()=>[],lastUpdateTime:0,statsByView:{},subscriptions:[],numFailedStatsReports:0},jf={interval:2e3,logger:new hf},Af=()=>{var e;return null===(e=Lf.currentMonitor)||void 0===e?void 0:e.getUpdatedStats()};function Nf(e,{interval:t,logger:r}){const i=Df.bind(null,e,{interval:t,logger:r});let n;try{n=function(e,{sampleRate:t,originTrials:r}=Mf,i=globalThis.window){let n;if(xf(r),"PressureObserver"in i)return n=new i.PressureObserver(e,{sampleRate:t}),n.observe("cpu",{sampleInterval:1e3*t}),{stop:()=>{n.unobserve("cpu")}}}((t=>e.lastPressureObserverRecord=t.pop()))}catch(e){r.warn("Failed to observe CPU pressure",e)}return setTimeout(i,t),{getUpdatedStats:()=>i(!0),stop:()=>{clearTimeout(e.nextTimeout),n&&n.stop()}}}var Bf;const Ff=null!==(Bf=pi.default)&&void 0!==Bf?Bf:pi,zf=new hf,Vf=Ff.browserDetails.browser,Uf=Ff.browserDetails.version;function $f(e,t){let r=e.match(/a=ssrc-group:FID (\d+) (\d+)\r\n/),i=t.match(/a=ssrc-group:FID (\d+) (\d+)\r\n/);r||(r=e.match(/a=ssrc:(\d+) cname:(.*)\r\n/g)[1].match(/a=ssrc:(\d+)/),i=t.match(/a=ssrc:(\d+) cname:(.*)\r\n/g)[1].match(/a=ssrc:(\d+)/));for(let e=1;e<r.length;e++)t=t.replace(new RegExp(i[e],"g"),r[e]);return t}function Gf(e){return"firefox"!==Vf?e:ti.splitLines(e.trim()).map((e=>e.startsWith("a=msid-semantic:")?"a=msid-semantic: WMS *":e)).join("\r\n")+"\r\n"}function qf(e){return function(e,t,r=!1,i=!1){var n,s;try{const o=ji(e);if((null===(n=null==o?void 0:o.ext)||void 0===n?void 0:n.length)&&o.ext.length>0)return e;if((null==o?void 0:o.media.length)<1)return e;const a=null==o?void 0:o.media.flatMap((e=>e.ext||[])),c=(null===(s=a.find((e=>e.uri===t)))||void 0===s?void 0:s.value)||[...new Set([0,15,...a.map((e=>e.value))])].sort(((e,t)=>e-t)).find(((e,t,r)=>e+1!==r[t+1]))+1;return o.media.forEach((e=>{var n;(r&&"audio"===e.type||i&&"video"===e.type)&&((null===(n=e.ext)||void 0===n?void 0:n.find((e=>e.uri===t)))||(Array.isArray(e.ext)?e.ext.push({value:c,uri:t}):e.ext=[{value:c,uri:t}]))})),Li(o)}catch(e){console.error("Error during addAbsCaptureTimeExtMap: ",e)}return e}(e,"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",!0,!0)}function Hf(e,t,r=console){const i=e.getSenders().find((e=>e.track&&"video"===e.track.kind));if(!i)return Promise.resolve();const n=i.getParameters();return n.encodings&&0===n.encodings.length?Promise.resolve():(n.encodings||(n.encodings=[{}]),0===t?delete n.encodings[0].maxBitrate:n.encodings[0].maxBitrate=1e3*t,i.setParameters(n).catch((e=>{r.error("setParameters err: ",e)})))}const Wf=400;var Kf;const Jf=null!==(Kf=pi.default)&&void 0!==Kf?Kf:pi,Xf=new hf;class Qf{constructor({peerConnectionId:e,bandwidth:t,maximumTurnBandwidth:r,deprioritizeH264Encoding:i}){this.peerConnectionId=e,this.relayCandidateSeen=!1,this.serverReflexiveCandidateSeen=!1,this.publicHostCandidateSeen=!1,this.ipv6HostCandidateSeen=!1,this.ipv6HostCandidateTeredoSeen=!1,this.ipv6HostCandidate6to4Seen=!1,this.mdnsHostCandidateSeen=!1,this.pc=null,this.wasEverConnected=!1,this.connectionStatus=null,this.stats={totalSent:0,totalRecv:0},this.bandwidth=t||0,this.maximumTurnBandwidth=r,this.pending=[],this.isOperationPending=!1,this.streamIds=[],this.streams=[],this.earlyIceCandidates=[],this.afterConnected=new Promise((e=>{this.registerConnected=e})),this.offerOptions={offerToReceiveAudio:!0,offerToReceiveVideo:!0},this._deprioritizeH264Encoding=i}setAndGetPeerConnection({clientId:e,constraints:t,peerConnectionConfig:r,shouldAddLocalVideo:i}){return this.peerConnectionConfig=r,this.shouldAddLocalVideo=i,this.clientId=e,this.pc=new RTCPeerConnection(r),this.signalingState=this.pc.signalingState,this.pc.addEventListener("signalingstatechange",(()=>{if(this.signalingState!==this.pc.signalingState&&(this.signalingState=this.pc.signalingState,"stable"===this.pc.signalingState)){this.isOperationPending=!1;const e=this.pending.shift();e&&e.apply()}})),this.pc}addStream(e){this.streamIds.push(e.id),this.streams.push(e),RTCPeerConnection.prototype.addTrack?(e.getAudioTracks().forEach((t=>{this.pc.addTrack(t,e)})),e.getVideoTracks().forEach((t=>{this.pc.addTrack(t,e)}))):this.pc.addStream(e)}addTrack(e,t){t||(t=this.streams[0]),null==t||t.addTrack(e),this.pc.addTrack(e,t)}removeTrack(e){this.streams[0].removeTrack(e);const t=this.pc.getSenders().find((t=>t.track===e));t&&this.pc.removeTrack(t)}removeStream(e){for(let t=0;t<this.streamIds.length;t++)this.streamIds[t]===e.id&&(this.streamIds.splice(t,1),this.streams.splice(t,1));this.pc&&(this.pc.removeTrack?e.getTracks().forEach((e=>{const t=this.pc.getSenders().find((t=>t.track===e));t&&this.pc.removeTrack(t)})):this.pc.removeStream&&this.pc.removeStream(e))}_setRemoteDescription(e){return this._deprioritizeH264Encoding&&(e.sdp=function(e){return ti.splitSections(e).map((e=>{if("video"!==ti.getKind(e))return e;const t=ti.matchPrefix(e,"a=rtpmap:").map((e=>ti.parseRtpMap(e))).filter((e=>/h264/i.test(e.name))).map((e=>""+e.payloadType));if(!t.length)return e;const r=ti.matchPrefix(e,"m=video")[0],i=/(\s\d+)+$/i.exec(r),n=i?i[0]:"",s=[...n.split(" ").filter((e=>e&&!t.includes(e))),...t].join(" "),o=r.replace(n," "+s);return e.replace(r,o)})).join("")}(e.sdp)),this.srdComplete=this.pc.setRemoteDescription(e),this.srdComplete.then((()=>{this.earlyIceCandidates.forEach((e=>this.pc.addIceCandidate(e))),this.earlyIceCandidates=[]}))}handleOffer(e){if(!this.canModifyPeerConnection())return new Promise((t=>{this.pending.push((()=>this.handleOffer(e).then(t)))}));this.isOperationPending=!0;let t=e.sdp;t=function(e){return"safari"!==Vf&&("firefox"!==Vf||Uf&&Uf>=63||60===Uf)?e:ti.splitLines(e.trim()).filter((e=>!e.startsWith("a=extmap:")||"urn:ietf:params:rtp-hdrext:sdes:mid"!==ti.parseExtmap(e).uri)).join("\r\n")+"\r\n"}(t),t=Gf(t);const r={type:e.type,sdp:t};let i;return this._setRemoteDescription(r).then((()=>this.pc.createAnswer())).then((e=>(i=e,this.pc.setLocalDescription(e)))).then((()=>Hf(this.pc,this.bandwidth))).then((()=>i))}handleAnswer(e){const t=Gf(e.sdp),r={type:e.type,sdp:t};return this._setRemoteDescription(r).then((()=>Hf(this.pc,this.bandwidth)),(e=>{Xf.warn("Could not set remote description from remote answer: ",e)}))}addIceCandidate(e){this.srdComplete?this.srdComplete.then((()=>{"closed"!==this.pc.signalingState&&("safari"===Jf.browserDetails.browser&&e&&""===e.candidate||this.pc.addIceCandidate(e).catch((t=>{Xf.warn("Failed to add ICE candidate ('%s'): %s",e?e.candidate:null,t)})))})):this.earlyIceCandidates.push(e)}canModifyPeerConnection(){return"stable"===this.pc.signalingState&&!this.isOperationPending}close(){const e=this.pc;if(e){e.oniceconnectionstatechange=null,e.onicecandidate=null,e.ontrack=null;try{e.close()}catch(e){Xf.warn("failures during close of session",e)}}}hasConnectedPeerConnection(){return this.pc&&"connected"===this.pc.connectionState}replaceTrack(e,t){const r=this.pc;if(!r)return!1;const i=r.getSenders();if(e||(e=(i.find((e=>e.track&&e.track.kind===t.kind))||{}).track),window.RTCRtpSender&&window.RTCRtpSender.prototype.replaceTrack){if(e){const r=()=>{for(let r=0;r<i.length;r++){const n=i[r].track;if((null==n?void 0:n.id)===t.id)return Promise.resolve(t);if((null==n?void 0:n.id)===e.id)return i[r].replaceTrack(t)}return null};let n=r();if(n)return n;let s=null,o=null;n=new Promise(((e,t)=>{s=e,o=t}));let a=0,c=setInterval((()=>ff(this,void 0,void 0,(function*(){const e=r();if(!e)return void(3<++a&&(clearInterval(c),c=null,o("No sender track to replace")));clearInterval(c),c=null;const t=yield e;s(t)}))),1e3);return n}const n=this.streams.find((e=>e.getTracks().find((e=>e.id===t.id))))||this.streams[0];return n?r.addTrack(t,n):Promise.reject(new Error("replaceTrack: No stream?"))}if(!this.canModifyPeerConnection())return void this.pending.push((()=>{this.replaceTrack(e,t)}));this.isOperationPending=!0;const n=r.onnegotiationneeded;return r.onnegotiationneeded=null,this.removeTrack(e),this.addTrack(t),setTimeout((()=>{r.onnegotiationneeded=n}),0),"offer"===r.localDescription.type?r.createOffer().then((e=>(e.sdp=$f(r.localDescription.sdp,e.sdp),r.setLocalDescription(e)))).then((()=>this._setRemoteDescription(r.remoteDescription))):this._setRemoteDescription(r.remoteDescription).then((()=>r.createAnswer())).then((e=>(e.sdp=$f(r.localDescription.sdp,e.sdp),r.setLocalDescription(e))))}maybeRestrictRelayBandwidth(){var e;-1!==this.maximumTurnBandwidth&&(this.pc.getStats&&(e=this.pc,e.getStats(null).then((e=>{let t,r;return e.forEach((i=>{if("transport"===i.type&&i.selectedCandidatePairId){const n=e.get(i.selectedCandidatePairId);if(!n)return;return t=e.get(n.localCandidateId).candidateType,void(r=e.get(n.remoteCandidateId).candidateType)}"candidate-pair"===i.type&&i.selected&&(t=e.get(i.localCandidateId).candidateType,r=e.get(i.remoteCandidateId).candidateType)})),"relay"===t||"relayed"===t||"relay"===r||"relayed"===r}))).then((e=>{e&&0===this.bandwidth&&this.changeBandwidth(this.maximumTurnBandwidth)})))}changeBandwidth(e){e!==this.bandwidth&&(this.canModifyPeerConnection()?(this.bandwidth=e,this.pc.localDescription&&""!==this.pc.localDescription.type&&Hf(this.pc,this.bandwidth)):this.pending.push((()=>this.changeBandwidth(e))))}setAudioOnly(e,t=[]){this.pc.getTransceivers().filter((e=>{var r,i,n,s,o,a;return"recvonly"!==(null==e?void 0:e.direction)&&"video"===(null===(i=null===(r=null==e?void 0:e.receiver)||void 0===r?void 0:r.track)||void 0===i?void 0:i.kind)&&!t.includes(null===(s=null===(n=null==e?void 0:e.receiver)||void 0===n?void 0:n.track)||void 0===s?void 0:s.id)&&!t.includes(null===(a=null===(o=null==e?void 0:e.sender)||void 0===o?void 0:o.track)||void 0===a?void 0:a.id)})).forEach((t=>{t.direction=e?"sendonly":"sendrecv"}))}}var Zf;const Yf=null!==(Zf=pi.default)&&void 0!==Zf?Zf:pi;const em="fetch_mediaserver_config",tm="start_screenshare",rm="stop_screenshare",im="audio_enabled",nm="client_left",sm="mediaserver_config",om="new_client",am="screenshare_started",cm="screenshare_stopped",dm="room_joined",lm="video_enabled",um="ice_candidate",pm="ice_endofcandidates",hm="ready_to_receive_offer",fm="sdp_answer",mm="sdp_offer",gm="pending_client_left",vm="media_quality_changed",bm="client_connection_status_changed",ym="stream_added",wm="rtc_manager_created",_m="rtc_manager_destroyed",Sm="local_stream_track_added",Cm="local_stream_track_removed",Rm="connecting",km="connection_failed",Tm="connection_successful",Pm="connection_disconnected",Em="camera",Om="screen_share";const Dm=57600,Im=2.6041666666666665,xm=921600,Mm=1.0850694444444444;const Lm="[a-fA-F\\d:]",jm=e=>e&&e.includeBoundaries?`(?:(?<=\\s|^)(?=${Lm})|(?<=${Lm})(?=\\s|$))`:"",Am="(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}",Nm="[a-fA-F\\d]{1,4}",Bm=`\n(?:\n(?:${Nm}:){7}(?:${Nm}|:)| // 1:2:3:4:5:6:7:: 1:2:3:4:5:6:7:8\n(?:${Nm}:){6}(?:${Am}|:${Nm}|:)| // 1:2:3:4:5:6:: 1:2:3:4:5:6::8 1:2:3:4:5:6::8 1:2:3:4:5:6::1.2.3.4\n(?:${Nm}:){5}(?::${Am}|(?::${Nm}){1,2}|:)| // 1:2:3:4:5:: 1:2:3:4:5::7:8 1:2:3:4:5::8 1:2:3:4:5::7:1.2.3.4\n(?:${Nm}:){4}(?:(?::${Nm}){0,1}:${Am}|(?::${Nm}){1,3}|:)| // 1:2:3:4:: 1:2:3:4::6:7:8 1:2:3:4::8 1:2:3:4::6:7:1.2.3.4\n(?:${Nm}:){3}(?:(?::${Nm}){0,2}:${Am}|(?::${Nm}){1,4}|:)| // 1:2:3:: 1:2:3::5:6:7:8 1:2:3::8 1:2:3::5:6:7:1.2.3.4\n(?:${Nm}:){2}(?:(?::${Nm}){0,3}:${Am}|(?::${Nm}){1,5}|:)| // 1:2:: 1:2::4:5:6:7:8 1:2::8 1:2::4:5:6:7:1.2.3.4\n(?:${Nm}:){1}(?:(?::${Nm}){0,4}:${Am}|(?::${Nm}){1,6}|:)| // 1:: 1::3:4:5:6:7:8 1::8 1::3:4:5:6:7:1.2.3.4\n(?::(?:(?::${Nm}){0,5}:${Am}|(?::${Nm}){1,7}|:)) // ::2:3:4:5:6:7:8 ::2:3:4:5:6:7:8 ::8 ::1.2.3.4\n)(?:%[0-9a-zA-Z]{1,})? // %eth0 %1\n`.replace(/\s*\/\/.*$/gm,"").replace(/\n/g,"").trim(),Fm=new RegExp(`(?:^${Am}$)|(?:^${Bm}$)`),zm=new RegExp(`^${Am}$`),Vm=new RegExp(`^${Bm}$`),Um=e=>e&&e.exact?Fm:new RegExp(`(?:${jm(e)}${Am}${jm(e)})|(?:${jm(e)}${Bm}${jm(e)})`,"g");Um.v4=e=>e&&e.exact?zm:new RegExp(`${jm(e)}${Am}${jm(e)}`,"g"),Um.v6=e=>e&&e.exact?Vm:new RegExp(`${jm(e)}${Bm}${jm(e)}`,"g");var $m="connection_blocked_by_network",Gm="ice_ipv6_seen",qm="ice_mdns_seen",Hm="ice_no_public_ip_gathered",Wm="ice_no_public_ip_gathered_3sec",Km="ice_restart",Jm="microphone_not_working",Xm="microphone_stopped_working",Qm="camera_stopped_working",Zm="new_pc",Ym="sfu_connection_open",eg="sfu_connection_closed",tg="sfu_connection_info",rg="dominant_speaker",ig="pc_sld_failure",ng="pc_on_answer_failure",sg="pc_on_offer_failure";class og extends Error{constructor(e){super(e.message),this.name="AssertionError",this.code="ERR_ASSERTION",this.actual=e.actual,this.expected=e.expected,this.operator=e.operator,Error.captureStackTrace&&Error.captureStackTrace(this,e.stackStartFn)}}function ag(e){if(e.message instanceof Error)throw e.message;throw new og(e)}function cg(...e){!function(e,t,r,i){if(!r){let n=!1;if(0===t)n=!0,i="No value argument passed to `assert.ok()`";else if(i instanceof Error)throw i;const s=new og({actual:r,expected:!0,message:i,operator:"==",stackStartFn:e});throw s.generatedMessage=n,s}}(cg,e.length,...e)}const dg={fail:e=>{ag({actual:"fail()",expected:"fail() should not be called",message:e,operator:"fail",stackStartFn:dg.fail})},ok:cg,notEqual:function e(t,r,i){if(arguments.length<2)throw new Error("'actual' and 'expected' arguments are required");t==r&&ag({actual:t,expected:r,message:i,operator:"!=",stackStartFn:e})}};dg.ok=cg;const lg=new as("Safari17"),ug={OS:1024,MIS:1024};class pg extends Ya{static createFactory(){return()=>new pg}constructor(){super(),this._closed=!1,this._mapMidTransceiver=new Map,this._sendStream=new MediaStream,this._hasDataChannelMediaSection=!1,this._nextSendSctpStreamId=0,this._transportReady=!1}get name(){return"Safari17"}close(){if(lg.debug("close()"),!this._closed){if(this._closed=!0,this._pc)try{this._pc.close()}catch(e){}this.emit("@close")}}getNativeRtpCapabilities(){return ff(this,void 0,void 0,(function*(){lg.debug("getNativeRtpCapabilities()");const e=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"});try{e.addTransceiver("audio"),e.addTransceiver("video");const t=yield e.createOffer();try{e.close()}catch(e){}const r=ji(t.sdp),i=Ga({sdpObject:r});return Qa(i),i}catch(t){try{e.close()}catch(e){}throw t}}))}getNativeSctpCapabilities(){return ff(this,void 0,void 0,(function*(){return lg.debug("getNativeSctpCapabilities()"),{numStreams:ug}}))}run({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,extendedRtpCapabilities:d}){this.assertNotClosed(),lg.debug("run()"),this._direction=e,this._remoteSdp=new fc({iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n}),this._sendingRtpParametersByKind={audio:ho("audio",d),video:ho("video",d)},this._sendingRemoteRtpParametersByKind={audio:fo("audio",d),video:fo("video",d)},i.role&&"auto"!==i.role&&(this._forcedLocalDtlsRole="server"===i.role?"client":"server"),this._pc=new RTCPeerConnection(Object.assign({iceServers:null!=s?s:[],iceTransportPolicy:null!=o?o:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"},a),c),this._pc.addEventListener("icegatheringstatechange",(()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)})),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",(()=>{this.emit("@connectionstatechange",this._pc.connectionState)})):this._pc.addEventListener("iceconnectionstatechange",(()=>{switch(lg.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.iceConnectionState){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected");break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed")}}))}updateIceServers(e){return ff(this,void 0,void 0,(function*(){this.assertNotClosed(),lg.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}))}restartIce(e){return ff(this,void 0,void 0,(function*(){if(this.assertNotClosed(),lg.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=yield this._pc.createOffer({iceRestart:!0});lg.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),yield this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};lg.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),yield this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};lg.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),yield this._pc.setRemoteDescription(e);const t=yield this._pc.createAnswer();lg.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",t),yield this._pc.setLocalDescription(t)}}))}getTransportStats(){return ff(this,void 0,void 0,(function*(){return this.assertNotClosed(),this._pc.getStats()}))}send({track:e,encodings:t,codecOptions:r,codec:i,onRtpSender:n}){var s;return ff(this,void 0,void 0,(function*(){this.assertNotClosed(),this.assertSendDirection(),lg.debug("send() [kind:%s, track.id:%s]",e.kind,e.id);const o=As(this._sendingRtpParametersByKind[e.kind]);o.codecs=mo(o.codecs,i),t&&t.length>1&&t.every((({rid:e})=>!e))&&(t=t.map(((e,t)=>(e.rid=`r${t}`,e)))),t&&(o.encodings||(o.encodings=[]),Object.assign(o.encodings,t));const a=yc((null!=t?t:[{}])[0].scalabilityMode);if(o.encodings&&o.encodings.length>1&&("video/vp8"===o.codecs[0].mimeType.toLowerCase()||"video/h264"===o.codecs[0].mimeType.toLowerCase()))for(const e of o.encodings)e.scalabilityMode?e.scalabilityMode=`L1T${a.temporalLayers}`:e.scalabilityMode="L1T3";const c=As(this._sendingRemoteRtpParametersByKind[e.kind]);c.codecs=mo(c.codecs,i);const d=this._remoteSdp.getNextMediaSectionIdx(),l=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream],sendEncodings:"video"===e.kind?t:void 0});n&&n(l.sender);const u=yield this._pc.createOffer(),p=ji(u.sdp);let h=p.media[d.idx];this._transportReady||(yield this.setupTransport({localDtlsRole:null!==(s=this._forcedLocalDtlsRole)&&void 0!==s?s:"client",localSdpObject:p})),lg.debug("send() | calling pc.setLocalDescription() [offer:%o]",u),yield this._pc.setLocalDescription(u);const f=l.mid;o.mid=f,h=p.media[d.idx],o.rtcp.cname=Ha({offerMediaObject:h}),this._remoteSdp.send({offerMediaObject:h,reuseMid:d.reuseMid,offerRtpParameters:o,answerRtpParameters:c,codecOptions:r});const m={type:"answer",sdp:this._remoteSdp.getSdp()};return lg.debug("send() | calling pc.setRemoteDescription() [answer:%o]",m),yield this._pc.setRemoteDescription(m),this._mapMidTransceiver.set(f,l),{localId:f,rtpParameters:o,rtpSender:l.sender}}))}stopSending(e){return ff(this,void 0,void 0,(function*(){if(this.assertSendDirection(),this._closed)return;lg.debug("stopSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.sender.replaceTrack(null),this._pc.removeTrack(t.sender);if(this._remoteSdp.closeMediaSection(t.mid))try{t.stop()}catch(e){}const r=yield this._pc.createOffer();lg.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r),yield this._pc.setLocalDescription(r);const i={type:"answer",sdp:this._remoteSdp.getSdp()};lg.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",i),yield this._pc.setRemoteDescription(i),this._mapMidTransceiver.delete(e)}))}pauseSending(e){return ff(this,void 0,void 0,(function*(){this.assertNotClosed(),this.assertSendDirection(),lg.debug("pauseSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="inactive",this._remoteSdp.pauseMediaSection(e);const r=yield this._pc.createOffer();lg.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),yield this._pc.setLocalDescription(r);const i={type:"answer",sdp:this._remoteSdp.getSdp()};lg.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",i),yield this._pc.setRemoteDescription(i)}))}resumeSending(e){return ff(this,void 0,void 0,(function*(){this.assertNotClosed(),this.assertSendDirection(),lg.debug("resumeSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="sendonly",this._remoteSdp.resumeSendingMediaSection(e);const r=yield this._pc.createOffer();lg.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),yield this._pc.setLocalDescription(r);const i={type:"answer",sdp:this._remoteSdp.getSdp()};lg.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",i),yield this._pc.setRemoteDescription(i)}))}replaceTrack(e,t){return ff(this,void 0,void 0,(function*(){this.assertNotClosed(),this.assertSendDirection(),t?lg.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):lg.debug("replaceTrack() [localId:%s, no track]",e);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");yield r.sender.replaceTrack(t)}))}setMaxSpatialLayer(e,t){return ff(this,void 0,void 0,(function*(){this.assertNotClosed(),this.assertSendDirection(),lg.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const i=r.sender.getParameters();i.encodings.forEach(((e,r)=>{e.active=r<=t})),yield r.sender.setParameters(i),this._remoteSdp.muxMediaSectionSimulcast(e,i.encodings);const n=yield this._pc.createOffer();lg.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",n),yield this._pc.setLocalDescription(n);const s={type:"answer",sdp:this._remoteSdp.getSdp()};lg.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",s),yield this._pc.setRemoteDescription(s)}))}setRtpEncodingParameters(e,t){return ff(this,void 0,void 0,(function*(){this.assertNotClosed(),this.assertSendDirection(),lg.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const i=r.sender.getParameters();i.encodings.forEach(((e,r)=>{i.encodings[r]=Object.assign(Object.assign({},e),t)})),yield r.sender.setParameters(i),this._remoteSdp.muxMediaSectionSimulcast(e,i.encodings);const n=yield this._pc.createOffer();lg.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",n),yield this._pc.setLocalDescription(n);const s={type:"answer",sdp:this._remoteSdp.getSdp()};lg.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",s),yield this._pc.setRemoteDescription(s)}))}getSenderStats(e){return ff(this,void 0,void 0,(function*(){this.assertNotClosed(),this.assertSendDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.sender.getStats()}))}sendDataChannel({ordered:e,maxPacketLifeTime:t,maxRetransmits:r,label:i,protocol:n}){var s;return ff(this,void 0,void 0,(function*(){this.assertNotClosed(),this.assertSendDirection();const o={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmits:r,protocol:n};lg.debug("sendDataChannel() [options:%o]",o);const a=this._pc.createDataChannel(i,o);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%ug.MIS,!this._hasDataChannelMediaSection){const e=yield this._pc.createOffer(),t=ji(e.sdp),r=t.media.find((e=>"application"===e.type));this._transportReady||(yield this.setupTransport({localDtlsRole:null!==(s=this._forcedLocalDtlsRole)&&void 0!==s?s:"client",localSdpObject:t})),lg.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),yield this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:r});const i={type:"answer",sdp:this._remoteSdp.getSdp()};lg.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",i),yield this._pc.setRemoteDescription(i),this._hasDataChannelMediaSection=!0}return{dataChannel:a,sctpStreamParameters:{streamId:o.id,ordered:o.ordered,maxPacketLifeTime:o.maxPacketLifeTime,maxRetransmits:o.maxRetransmits}}}))}receive(e){var t,r;return ff(this,void 0,void 0,(function*(){this.assertNotClosed(),this.assertRecvDirection();const i=[],n=new Map;for(const r of e){const{trackId:e,kind:i,rtpParameters:s,streamId:o}=r;lg.debug("receive() [trackId:%s, kind:%s]",e,i);const a=null!==(t=s.mid)&&void 0!==t?t:String(this._mapMidTransceiver.size);n.set(e,a),this._remoteSdp.receive({mid:a,kind:i,offerRtpParameters:s,streamId:null!=o?o:s.rtcp.cname,trackId:e})}const s={type:"offer",sdp:this._remoteSdp.getSdp()};lg.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",s),yield this._pc.setRemoteDescription(s);for(const t of e){const{trackId:e,onRtpReceiver:r}=t;if(r){const t=n.get(e),i=this._pc.getTransceivers().find((e=>e.mid===t));if(!i)throw new Error("transceiver not found");r(i.receiver)}}let o=yield this._pc.createAnswer();const a=ji(o.sdp);for(const t of e){const{trackId:e,rtpParameters:r}=t,i=n.get(e),s=a.media.find((e=>String(e.mid)===i));Wa({offerRtpParameters:r,answerMediaObject:s})}o={type:"answer",sdp:Li(a)},this._transportReady||(yield this.setupTransport({localDtlsRole:null!==(r=this._forcedLocalDtlsRole)&&void 0!==r?r:"client",localSdpObject:a})),lg.debug("receive() | calling pc.setLocalDescription() [answer:%o]",o),yield this._pc.setLocalDescription(o);for(const t of e){const{trackId:e}=t,r=n.get(e),s=this._pc.getTransceivers().find((e=>e.mid===r));if(!s)throw new Error("new RTCRtpTransceiver not found");this._mapMidTransceiver.set(r,s),i.push({localId:r,track:s.receiver.track,rtpReceiver:s.receiver})}return i}))}stopReceiving(e){return ff(this,void 0,void 0,(function*(){if(this.assertRecvDirection(),this._closed)return;for(const t of e){lg.debug("stopReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(e.mid)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};lg.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),yield this._pc.setRemoteDescription(t);const r=yield this._pc.createAnswer();lg.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",r),yield this._pc.setLocalDescription(r);for(const t of e)this._mapMidTransceiver.delete(t)}))}pauseReceiving(e){return ff(this,void 0,void 0,(function*(){this.assertNotClosed(),this.assertRecvDirection();for(const t of e){lg.debug("pauseReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="inactive",this._remoteSdp.pauseMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};lg.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),yield this._pc.setRemoteDescription(t);const r=yield this._pc.createAnswer();lg.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",r),yield this._pc.setLocalDescription(r)}))}resumeReceiving(e){return ff(this,void 0,void 0,(function*(){this.assertNotClosed(),this.assertRecvDirection();for(const t of e){lg.debug("resumeReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};lg.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),yield this._pc.setRemoteDescription(t);const r=yield this._pc.createAnswer();lg.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",r),yield this._pc.setLocalDescription(r)}))}getReceiverStats(e){return ff(this,void 0,void 0,(function*(){this.assertNotClosed(),this.assertRecvDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.receiver.getStats()}))}receiveDataChannel({sctpStreamParameters:e,label:t,protocol:r}){var i;return ff(this,void 0,void 0,(function*(){this.assertNotClosed(),this.assertRecvDirection();const{streamId:n,ordered:s,maxPacketLifeTime:o,maxRetransmits:a}=e,c={negotiated:!0,id:n,ordered:s,maxPacketLifeTime:o,maxRetransmits:a,protocol:r};lg.debug("receiveDataChannel() [options:%o]",c);const d=this._pc.createDataChannel(t,c);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();const e={type:"offer",sdp:this._remoteSdp.getSdp()};lg.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),yield this._pc.setRemoteDescription(e);const t=yield this._pc.createAnswer();if(!this._transportReady){const e=ji(t.sdp);yield this.setupTransport({localDtlsRole:null!==(i=this._forcedLocalDtlsRole)&&void 0!==i?i:"client",localSdpObject:e})}lg.debug("receiveDataChannel() | calling pc.setRemoteDescription() [answer:%o]",t),yield this._pc.setLocalDescription(t),this._hasDataChannelMediaSection=!0}return{dataChannel:d}}))}setupTransport({localDtlsRole:e,localSdpObject:t}){return ff(this,void 0,void 0,(function*(){t||(t=ji(this._pc.localDescription.sdp));const r=qa({sdpObject:t});r.role=e,this._remoteSdp.updateDtlsRole("client"===e?"server":"client"),yield new Promise(((e,t)=>{this.safeEmit("@connect",{dtlsParameters:r},e,t)})),this._transportReady=!0}))}assertNotClosed(){if(this._closed)throw new xs("method called in a closed handler")}assertSendDirection(){if("send"!==this._direction)throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if("recv"!==this._direction)throw new Error('method can just be called for handlers with "recv" direction')}}const hg={codecOptions:{opusDtx:!0,opusFec:!0},encodings:[{dtx:!0}]},fg={codecOptions:{videoGoogleStartBitrate:500},encodings:[{scaleResolutionDownBy:4,maxBitrate:15e4},{scaleResolutionDownBy:2,maxBitrate:5e5},{scaleResolutionDownBy:1,maxBitrate:1e6}]},mg={codecOptions:{videoGoogleStartBitrate:500},encodings:[{scaleResolutionDownBy:2,maxBitrate:15e4},{scaleResolutionDownBy:1,maxBitrate:5e5}]},gg={codecOptions:{videoGoogleStartBitrate:500},encodings:[{scalabilityMode:"L3T2_KEY"}]},vg={codecOptions:{videoGoogleStartBitrate:500},encodings:[{scalabilityMode:"L2T2_KEY",maxBitrate:8e5}]},bg={encodings:[{}]},yg={encodings:[{maxBitrate:6e5,maxFramerate:2}]},wg={encodings:[{scaleResolutionDownBy:2,dtx:!0,maxBitrate:5e5},{scaleResolutionDownBy:1,dtx:!0,maxBitrate:15e5}]},_g={encodings:[{dtx:!0}]},Sg=(e,t,r)=>{const{lowDataModeEnabled:i,simulcastScreenshareOn:n,vp9On:s,lowBandwidth:o}=r;return"audio"===e?hg:t?o&&!s?yg:s?_g:n?wg:bg:o?s?vg:mg:s?gg:i?mg:fg};const Cg=new hf;class Rg extends Np{constructor(e){super(),this.reconnectThresholdInMs=0,this._socket=e,this._clients={},this._signalDisconnectTime=void 0,this.rtcManager=void 0,this.metrics={roomJoinedLate:0,pendingClientCanceled:0,evaluationFailed:0,roomJoined:0},e.on("disconnect",(()=>{this._signalDisconnectTime=Date.now()})),e.on(dm,(e=>this._onRoomJoined(e))),e.on(om,(e=>this._onNewClient(e))),e.on(nm,(e=>this._onClientLeft(e))),e.on(gm,(e=>this._onPendingClientLeft(e))),e.on(im,(e=>this._onAudioEnabled(e))),e.on(lm,(e=>this._onVideoEnabled(e))),e.on(am,(e=>this._onScreenshareChanged(e,!0))),e.on(cm,(e=>this._onScreenshareChanged(e,!1)))}_onRoomJoined(e){var t,r;return ff(this,void 0,void 0,(function*(){if(this.reconnectThresholdInMs=.8*(e.disconnectTimeout||0),!(null===(t=e.room)||void 0===t?void 0:t.clients))return void this.emit(dm,e);if(!e.selfId)return void this.emit(dm,e);const i=null===(r=e.room.clients.find((t=>e.selfId===t.id)))||void 0===r?void 0:r.deviceId;if(!i)return void this.emit(dm,e);if(!this._signalDisconnectTime)return this._resetClientState(e),e.room.clients=e.room.clients.filter((e=>!(e.deviceId===i&&e.isPendingToLeave))),void this.emit(dm,e);const n=.8*e.disconnectTimeout;if(Date.now()-this._signalDisconnectTime>n)return this._resetClientState(e),this.emit(dm,e),void this.metrics.roomJoinedLate++;e.room.clients=e.room.clients.filter((e=>!(e.deviceId===i&&e.isPendingToLeave)));const s=yield Af();e.room.clients.forEach((t=>{var r;try{if(t.id===e.selfId)return;if(!this._clients[t.id])return void this._addClientToState(t);if(!(null===(r=this.rtcManager)||void 0===r?void 0:r.hasClient(t.id)))return;if(this._hasClientStateChanged({clientId:t.id,webcam:t.isVideoEnabled,mic:t.isAudioEnabled,screenShare:t.streams.length>1}))return;if(this._wasClientSendingMedia(t.id)&&!this._isClientMediaActive(s,t.id))return;t.mergeWithOldClientState=!0}catch(e){Cg.error("Failed to evaluate if we should merge client state %o",e),this.metrics.evaluationFailed++}})),e.room.clients.forEach((e=>{e.isPendingToLeave&&this._onPendingClientLeft({clientId:e.id})})),this.metrics.roomJoined++,this.emit(dm,e)}))}_onClientLeft(e){var t;const{clientId:r}=e,i=this._clients[r];i&&(clearTimeout(i.timeout),delete this._clients[r]),null===(t=this.rtcManager)||void 0===t||t.disconnect(r,null,e.eventClaim),this.emit(nm,e)}_onPendingClientLeft(e){const{clientId:t}=e,r=this._clients[t];r?r.isPendingToLeave||(r.isPendingToLeave=!0,this._wasClientSendingMedia(t)&&(r.checkActiveMediaAttempts=0,this._abortIfNotActive(e))):Cg.warn(`client ${t} not found`)}_onNewClient(e){const{client:{id:t,deviceId:r}}=e,i=this._clients[t];if(i&&i.isPendingToLeave)return clearTimeout(i.timeoutHandler),i.isPendingToLeave=!1,void this.metrics.pendingClientCanceled++;this._getPendingClientsByDeviceId(r).forEach((e=>{clearTimeout(e.timeoutHandler),e.isPendingToLeave=void 0,this.emit(nm,{clientId:e.clientId})})),this._addClientToState(e.client),this.emit(om,e)}_abortIfNotActive(e){return ff(this,void 0,void 0,(function*(){const{clientId:t}=e;let r=this._clients[t];if(!(null==r?void 0:r.isPendingToLeave))return;if(r.checkActiveMediaAttempts++,r.checkActiveMediaAttempts>3)return;(yield this._checkIsActive(t))?r.timeoutHandler=setTimeout((()=>this._abortIfNotActive(e)),500):(r=this._clients[t],(null==r?void 0:r.isPendingToLeave)&&(clearTimeout(r.timeoutHandler),delete this._clients[t],this.emit(nm,e)))}))}_checkIsActive(e){return ff(this,void 0,void 0,(function*(){const t=yield Af();return this._isClientMediaActive(t,e)}))}_isClientMediaActive(e,t){const r=null==e?void 0:e[t];let i=!1;return r&&Object.entries(r.tracks).forEach((([e,t])=>{"probator"!==e&&Object.values(t.ssrcs).forEach((e=>{(e.bitrate||0)>0&&(i=!0)}))})),i}_onAudioEnabled(e){const{clientId:t,isAudioEnabled:r}=e;this._clients[t]=Object.assign(Object.assign({},this._clients[t]||{}),{isAudioEnabled:r})}_onVideoEnabled(e){const{clientId:t,isVideoEnabled:r}=e;this._clients[t]=Object.assign(Object.assign({},this._clients[t]||{}),{isVideoEnabled:r})}_onScreenshareChanged(e,t){const{clientId:r}=e;this._clients[r]=Object.assign(Object.assign({},this._clients[r]||{}),{isScreenshareEnabled:t})}_hasClientStateChanged({clientId:e,webcam:t,mic:r,screenShare:i}){const n=this._clients[e];if(!n)throw new Error(`Client ${e} not found in ReconnectManager state`);return t!==n.isVideoEnabled||(r!==n.isAudioEnabled||i!==n.isScreenshareEnabled)}_addClientToState(e){this._clients[e.id]=Object.assign(Object.assign({},this._clients[e.id]||{}),{isAudioEnabled:e.isAudioEnabled,isVideoEnabled:e.isVideoEnabled,isScreenshareEnabled:e.streams.length>1,deviceId:e.deviceId,isPendingToLeave:e.isPendingToLeave,clientId:e.id})}_wasClientSendingMedia(e){const t=this._clients[e];if(!t)throw new Error(`Client ${e} not found in ReconnectManager state`);return t.isAudioEnabled||t.isVideoEnabled||t.isScreenshareEnabled}_getPendingClientsByDeviceId(e){return Object.values(this._clients).filter((t=>t.deviceId===e&&t.isPendingToLeave))}_resetClientState(e){this._clients={},e.room.clients.forEach((t=>{t.id!==e.selfId&&this._addClientToState(t)}))}}var kg;const Tg=null!==(kg=pi.default)&&void 0!==kg?kg:pi;class Pg{constructor(e,t,r=!1){this._wasConnectedUsingWebsocket=!1,this._reconnectManager=null,this._socket=uf(e,Object.assign({path:"/protocol/socket.io/v4",randomizationFactor:.5,reconnectionDelay:250,reconnectionDelayMax:5e3,timeout:5e3,transports:["websocket"],withCredentials:!0},t)),this._socket.io.on("reconnect",(()=>{this._socket.sendBuffer=[]})),this._socket.io.on("reconnect_attempt",(()=>{this._wasConnectedUsingWebsocket?(this._socket.io.opts.transports=["websocket"],"safari"!==Tg.browserDetails.browser&&delete this._wasConnectedUsingWebsocket):this._socket.io.opts.transports=["websocket","polling"]})),r&&(this._reconnectManager=new Rg(this._socket)),this._socket.on("connect",(()=>{"websocket"===this.getTransport()&&(this._wasConnectedUsingWebsocket=!0,this.noopKeepaliveInterval||(this.noopKeepaliveInterval=setInterval((()=>{try{this._socket.connected&&this._socket.io.engine.sendPacket("noop")}catch(e){}}),2e3)))})),this._socket.on("disconnect",(()=>{this.disconnectTimestamp=Date.now(),this.noopKeepaliveInterval&&(clearInterval(this.noopKeepaliveInterval),this.noopKeepaliveInterval=null)}))}setRtcManager(e){this._reconnectManager&&(this._reconnectManager.rtcManager=e)}connect(){this.isConnected()||this.isConnecting()||this._socket.open()}disconnect(){this._socket.disconnect()}disconnectOnConnect(){this._socket.once("connect",(()=>{this._socket.disconnect()}))}emit(e,...t){this._socket.emit.apply(this._socket,arguments)}emitIfConnected(e,t){this.isConnected()&&this.emit(e,t)}getTransport(){return this._socket&&this._socket.io&&this._socket.io.engine&&this._socket.io.engine.transport&&this._socket.io.engine.transport.name}getManager(){return this._socket.io}isConnecting(){return this._socket&&this._socket.connecting}isConnected(){return this._socket&&this._socket.connected}on(e,t){const r=[dm,nm,om];return this._reconnectManager&&r.includes(e)?this._interceptEvent(e,t):(this._socket.on(e,t),()=>{this._socket.off(e,t)})}onEngineEvent(e,t){var r;return null===(r=this._socket.io)||void 0===r||r.on(e,t),()=>{var r;null===(r=this._socket.io)||void 0===r||r.off(e,t)}}once(e,t){this._socket.once(e,t)}off(e,t){this._socket.off(e,t)}_interceptEvent(e,t){return this._reconnectManager&&this._reconnectManager.on(e,t),()=>{this._reconnectManager&&this._reconnectManager.removeListener(e,t)}}getGlitchFreeMetrics(){var e;return null===(e=this._reconnectManager)||void 0===e?void 0:e.metrics}getReconnectThreshold(){var e;return null===(e=this._reconnectManager)||void 0===e?void 0:e.reconnectThresholdInMs}}const Eg=[{pattern:/^(?:([^.]+)[.])?(server:?\d*)/,separator:"."},{pattern:/^(?:([^.]+)[.])?(localhost:?\d*)/,separator:"."},{pattern:/^(?:([^.]+)[.])?((\d+[.]){3}:?\d*)$/,separator:"."},{pattern:/^(?:([^.]+)-)?(ip-[^.]*[.](?:hereby[.]dev|rfc1918[.]disappear[.]at)(?::\d+|))$/,separator:"-"},{pattern:/^(?:([^.]+)[.])?((:?[^.]+[.]){1,}[^.]+)$/,separator:"."}];function Og({host:e="whereby.com",protocol:t="https:"}={}){let r="",i=e,n=".";for(const{separator:t,pattern:s}of Eg){const o=s.exec(e);if(o){r=o[1]||"",i=o[2],n=t;break}}const s=r?`${r}${n}${i}`:i;return{domain:i,domainWithSeparator:`${n}${i}`,organizationDomain:s,organization:`${t}//${s}`,service:`${t}//${i}`,subdomain:r}}var Dg,Ig;Og(window&&window.location);const xg=null!==(Dg=pi.default)&&void 0!==Dg?Dg:pi,Mg=new hf,Lg=class{constructor(e,t){this.id=""+e,this.type=t,this.isEnabled=!0,this.hasSupportForAutoSuperSize=!1,this.isAudioEnabled=!0,this.isVideoEnabled=!0,this.status=Rm,this.stream=null,this.streamId=null}setup(e){return this.stream=e,this.streamId=e.id,this.setVideoEnabled(this.isVideoEnabled&&e.getVideoTracks().length>0),this.setAudioEnabled(this.isAudioEnabled&&e.getAudioTracks().length>0),this}setStatus(e){return this.status=e,this}setVideoEnabled(e){this.isVideoEnabled=e,this.stream&&this.stream.getVideoTracks().forEach((t=>{t.enabled=e}))}setAudioEnabled(e){this.isAudioEnabled=e,this.stream&&this.stream.getAudioTracks().forEach((t=>{t.enabled=e}))}static getCameraId(){return"0"}static getTypeFromId(e){return"0"===""+e?Em:Om}}.getCameraId(),jg=xg.browserDetails.browser,Ag=xg.browserDetails.version;"firefox"===jg&&xg.browserShim&&"shimGetDisplayMedia"in xg.browserShim&&(null===(Ig=xg.browserShim)||void 0===Ig||Ig.shimGetDisplayMedia(window,"screen"));let Ng=!1;"chrome"===jg&&window.document.addEventListener("beforeunload",(()=>{Ng=!0}));class Bg{constructor({selfId:e,room:t,emitter:r,serverSocket:i,webrtcProvider:n,features:s}){const{name:o,session:a,iceServers:c,sfuServer:d,mediaserverConfigTtlSeconds:l}=t;this._selfId=e,this._roomName=o,this._roomSessionId=a&&a.id,this.peerConnections={},this.localStreams={},this.enabledLocalStreamIds=[],this._screenshareVideoTrackIds=[],this._socketListenerDeregisterFunctions=[],this._localStreamDeregisterFunction=null,this._emitter=r,this._serverSocket=i,this._webrtcProvider=n,this._features=s||{},this._isAudioOnlyMode=!1,this.offerOptions={offerToReceiveAudio:!0,offerToReceiveVideo:!0},this._pendingActionsForConnectedPeerConnections=[],this._audioTrackOnEnded=()=>{wf.sendEvent("audio_ended",{unloading:Ng}),this._emit(Xm,{})},this._videoTrackOnEnded=()=>{wf.sendEvent("video_ended",{unloading:Ng}),this._emit(Qm,{})},this._updateAndScheduleMediaServersRefresh({sfuServer:d,iceServers:c.iceServers||[],mediaserverConfigTtlSeconds:l}),this.totalSessionsCreated=0}numberOfPeerconnections(){return Object.keys(this.peerConnections).length}isInitializedWith({selfId:e,roomName:t,isSfu:r}){return this._selfId===e&&this._roomName===t&&r===!!this._sfuServer}supportsScreenShareAudio(){return!0}maybeRestrictRelayBandwidth(e){e.maybeRestrictRelayBandwidth()}addNewStream(e,t,r,i,n=[]){if(t!==this.localStreams[e]){if(this._addLocalStream(e,t),e===Lg){this._addStreamToPeerConnections(t);const e=t.getAudioTracks()[0],r=t.getVideoTracks()[0];if(e){e.effectTrack||this._monitorAudioTrack(e);const t=n.find((e=>"audio"===e.kind));t&&this._monitorAudioTrack(t)}if(r){r.effectTrack||this._monitorVideoTrack(r);const e=n.find((e=>"video"===e.kind));e&&this._monitorVideoTrack(e)}this._localStreamDeregisterFunction&&(this._localStreamDeregisterFunction(),this._localStreamDeregisterFunction=null);const i=e=>{const{enable:t,track:r}=e.detail;this._handleStopOrResumeVideo({enable:t,track:r})};return t.addEventListener("stopresumevideo",i),void(this._localStreamDeregisterFunction=()=>{t.removeEventListener("stopresumevideo",i)})}this._screenshareVideoTrackIds.push(t.getVideoTracks()[0].id),this._shareScreen(e,t)}}replaceTrack(e,t){return"audio"!==t.kind||t.effectTrack||this._monitorAudioTrack(t),"video"!==t.kind||t.effectTrack||this._monitorVideoTrack(t),this._replaceTrackToPeerConnections(e,t)}disconnectAll(){Object.keys(this.peerConnections).forEach((e=>{this.disconnect(e)})),this.peerConnections={},this._socketListenerDeregisterFunctions.forEach((e=>{e()})),this._socketListenerDeregisterFunctions=[],this._localStreamDeregisterFunction&&(this._localStreamDeregisterFunction(),this._localStreamDeregisterFunction=null)}fixChromeAudio(e){if("chrome"!==jg)return;const t=this._getLocalCameraStream(),r=t.getAudioTracks()[0];return r&&"ended"===r.readyState?navigator.mediaDevices.getUserMedia({audio:e}).then((e=>{const i=e.getAudioTracks()[0];return i.enabled=r.enabled,t.removeTrack(r),t.addTrack(i),this.replaceTrack(r,i)})):void 0}setupSocketListeners(){this._socketListenerDeregisterFunctions=[()=>this._clearMediaServersRefresh(),this._serverSocket.on(sm,(e=>{e.error?Mg.warn("FETCH_MEDIASERVER_CONFIG failed:",e.error):this._updateAndScheduleMediaServersRefresh(e)})),this._serverSocket.on(hm,(e=>{this._connect(e.clientId)})),this._serverSocket.on(um,(e=>{const t=this._getSession(e.clientId);t?t.addIceCandidate(e.message):Mg.warn("No RTCPeerConnection on ICE_CANDIDATE",e)})),this._serverSocket.on(pm,(e=>{const t=this._getSession(e.clientId);t?t.addIceCandidate(null):Mg.warn("No RTCPeerConnection on ICE_END_OF_CANDIDATES",e)})),this._serverSocket.on(mm,(e=>{var t,r;const i=this._getSession(e.clientId);if(!i)return void Mg.warn("No RTCPeerConnection on SDP_OFFER",e);const n=this._transformIncomingSdp(e.message,i.pc);null===(r=(t=i.handleOffer(n).then((t=>{this._emitServerEvent(fm,{receiverId:e.clientId,message:this._transformOutgoingSdp(t)})}))).catch)||void 0===r||r.call(t,(e=>{this._emit(sg,e)}))})),this._serverSocket.on(fm,(e=>{var t,r;const i=this._getSession(e.clientId);if(!i)return void Mg.warn("No RTCPeerConnection on SDP_ANSWER",e);const n=this._transformIncomingSdp(e.message,i.pc);null===(r=null===(t=i.handleAnswer(n))||void 0===t?void 0:t.catch)||void 0===r||r.call(t,(e=>{this._emit(ng,e)}))})),this._serverSocket.on(dm,(({room:{sfuServer:e}})=>{if(e||!this._wasScreenSharing)return;const t=Object.keys(this.localStreams).find((e=>e!==Lg));if(!t)return;const r=this.localStreams[t];if(!r)return void Mg.warn("screenshare stream %s not found",t);const i=r.getAudioTracks().length>0;this._emitServerEvent(tm,{streamId:t,hasAudioTrack:i})}))]}sendAudioMutedStats(e){wf.sendEvent("audio_muted",{muted:e})}sendVideoMutedStats(e){wf.sendEvent("video_muted",{muted:e})}sendStatsCustomEvent(e,t){wf.sendEvent(e,t)}rtcStatsDisconnect(){wf.server.close()}rtcStatsReconnect(){wf.server.connected||wf.server.connect()}setAudioOnly(e){this._isAudioOnlyMode=e,this._forEachPeerConnection((e=>{e.hasConnectedPeerConnection()&&this._withForcedRenegotiation(e,(()=>e.setAudioOnly(this._isAudioOnlyMode,this._screenshareVideoTrackIds)))}))}setRemoteScreenshareVideoTrackIds(e=[]){const t=this._getFirstLocalNonCameraStream();this._screenshareVideoTrackIds=[...(null==t?void 0:t.track)?[t.track.id]:[],...e]}setRoomSessionId(e){this._roomSessionId=e}_setConnectionStatus(e,t,r){const i=e.connectionStatus;i!==t&&e.peerConnectionId!==this._selfId&&(i===Pm&&t===Rm||(e.connectionStatus=t,setTimeout((()=>{this._emit(bm,{streamIds:e.streamIds,clientId:r,status:t,previous:i})}),0)))}_setJitterBufferTarget(e){try{e.getReceivers().forEach((e=>{e.jitterBufferTarget=Wf,e.playoutDelayHint=.4}))}catch(e){Mg.error("Error during setting jitter buffer target:",e)}}_emitServerEvent(e,t,r){this._serverSocket.emit(e,t,r)}_emit(e,t){this._emitter.emit(e,t)}_addEnabledLocalStreamId(e){this.enabledLocalStreamIds.push(e)}_deleteEnabledLocalStreamId(e){const t=this.enabledLocalStreamIds.indexOf(e);-1!==t&&this.enabledLocalStreamIds.splice(t,1)}_getSession(e){return e in this.peerConnections?this.peerConnections[e]:null}_getOrCreateSession(e,t){let r=this.peerConnections[e];if(void 0===r){const i="safari"===jg&&Ag&&Ag>=14&&this._features.deprioritizeH264OnSafari;this.peerConnections[e]=r=new Qf({peerConnectionId:e,bandwidth:t,maximumTurnBandwidth:this._features.unlimitedBandwidthWhenUsingRelayP2POn?-1:1280,deprioritizeH264Encoding:i}),this.totalSessionsCreated++}return r}_getLocalCameraStream(){return this.localStreams[Lg]}_getNonLocalCameraStreamIds(){return Object.keys(this.localStreams).filter((e=>e!==Lg))}_isScreensharingLocally(){return this._getNonLocalCameraStreamIds().length>0}_getFirstLocalNonCameraStream(){const e=this._getNonLocalCameraStreamIds();return 0===e.length?null:this.localStreams[e[0]]}_transformIncomingSdp(e,t){return{type:e.type,sdp:e.sdpU}}_transformOutgoingSdp(e){return{type:e.type,sdpU:e.sdp}}_createSession({clientId:e,initialBandwidth:t,isOfferer:r,peerConnectionId:i,shouldAddLocalVideo:n}){if(!i)throw new Error("peerConnectionId is missing");if(!e)throw new Error("clientId is missing");const s=this._getOrCreateSession(i,t),o={optional:[]};"chrome"===jg&&o.optional.push({googCpuOveruseDetection:!0}),o.optional.push({rtcStatsRoomSessionId:this._roomSessionId}),o.optional.push({rtcStatsClientId:this._selfId}),o.optional.push({rtcStatsPeerId:i}),o.optional.push({rtcStatsConferenceId:this._roomName});const a={iceServers:this._iceServers};if(this._features.turnServerOverrideHost){const e=this._features.turnServerOverrideHost,t=e.indexOf(":")>0?"":":443",r=":"+e+t;a.iceServers=a.iceServers.map((e=>{const t=Object.assign({},e);return t.url&&(t.url=t.url.replace(/:[^?]*/,r)),t.urls&&(t.urls=t.urls.map((e=>e.replace(/:[^?]*/,r)))),t}))}if(this._features.addGoogleStunServers&&(a.iceServers=[...a.iceServers,{urls:"stun:stun.l.google.com:19302"},{urls:"stun:stun2.l.google.com:19302"}]),this._features.addCloudflareStunServers&&(a.iceServers=[...a.iceServers,{urls:"stun:stun.cloudflare.com:3478"},{urls:"stun:stun.cloudflare.com:53"}]),this._features.useOnlyTURN){a.iceTransportPolicy="relay";const e={onlyudp:/^turn:.*transport=udp$/,onlytcp:/^turn:.*transport=tcp$/,onlytls:/^turns:.*transport=tcp$/}[this._features.useOnlyTURN];e&&(a.iceServers=a.iceServers.filter((t=>t.url&&t.url.match(e))))}"chrome"===jg&&(a.sdpSemantics="unified-plan");const c=s.setAndGetPeerConnection({constraints:o,peerConnectionConfig:a,shouldAddLocalVideo:n,clientId:e});setTimeout((()=>this._emit(Zm)),0),c.ontrack=t=>{const r=t.streams[0];"default"===r.id&&0===r.getAudioTracks().length||-1===s.streamIds.indexOf(r.id)&&(s.streamIds.push(r.id),this._emit(ym,{clientId:e,stream:r}),s.connectionStatus===Tm&&setTimeout((()=>{this._emit(bm,{streamIds:s.streamIds,clientId:e,status:s.connectionStatus,previous:Rm})}),0))},c.oniceconnectionstatechange=()=>{let t;const r=s.connectionStatus;switch(c.iceConnectionState){case"checking":t=Rm;break;case"connected":case"completed":t=Tm,s.wasEverConnected||(this._pendingActionsForConnectedPeerConnections.forEach((e=>{"function"==typeof e&&e()})),this._pendingActionsForConnectedPeerConnections=[]),!s.wasEverConnected&&(c.iceConnectionState.match(/connected|completed/)||"chrome"===jg&&c.localDescription&&"answer"===c.localDescription.type)&&(s.wasEverConnected=!0,"false"!==this._features.bandwidth&&this.maybeRestrictRelayBandwidth(s)),this._isAudioOnlyMode&&s.setAudioOnly(!0,this._screenshareVideoTrackIds),s.registerConnected();break;case"disconnected":t=Pm,setTimeout((()=>{"disconnected"===c.iceConnectionState&&this._maybeRestartIce(e,s)}),2e3);break;case"failed":t=km,r!==t&&this._maybeRestartIce(e,s),null!==s.relayCandidateSeen||s.wasEverConnected||this._emit($m);break;default:return}this._setConnectionStatus(s,t,e)},c.onconnectionstate=()=>{switch(c.connectionState){case"connected":setTimeout((()=>{(function(e){if("chrome"!==Yf.browserDetails.browser||Yf.browserDetails.browser<58||"closed"===e.signalingState)return Promise.resolve(!1);const t=e.getSenders().some((e=>e.track&&"audio"===e.track.kind)),r=e.getReceivers().some((e=>e.track&&"audio"===e.track.kind));return e.getStats(null).then((e=>{let i=!1;return e.forEach((e=>{"outbound-rtp"!==e.type||"audio"!==e.kind&&"audio"!==e.mediaType||!t?"inbound-rtp"!==e.type||"audio"!==e.kind&&"audio"!==e.mediaType||!r||0===e.bytesReceived&&(i="inbound"):0===e.bytesSent&&(i="outbound")})),i}))})(s.pc).then((t=>{!1!==t&&this._emit(Jm,{failureDirection:t,clientId:e})}))}),3e3),s.registerConnected();break;case"failed":const t=km;null!==s.relayCandidateSeen||s.wasEverConnected||this._emit($m),this._setConnectionStatus(s,t,e)}};const d=this.localStreams[Lg];return n&&d&&s.addStream(d),n&&Object.keys(this.localStreams).forEach((e=>{if(e===Lg)return;const t=this.localStreams[e];r?s.addStream(t):s.afterConnected.then((()=>{this._emitServerEvent(tm,{receiverId:s.clientId,streamId:t.id,hasAudioTrack:!!t.getAudioTracks().length}),this._withForcedRenegotiation(s,(()=>s.addStream(t)))}))})),s}_cleanup(e){const t=this._getSession(e);t?(t.close(),delete this.peerConnections[e]):Mg.warn("No RTCPeerConnection in RTCManager.disconnect()",e)}_forEachPeerConnection(e){Object.values(this.peerConnections).forEach((t=>{e(t)}))}_addStreamToPeerConnections(e){this._forEachPeerConnection((t=>{this._withForcedRenegotiation(t,(()=>t.addStream(e)))}))}_addTrackToPeerConnections(e,t){this._forEachPeerConnection((r=>{this._withForcedRenegotiation(r,(()=>r.addTrack(e,t)))}))}_replaceTrackToPeerConnections(e,t){const r=[];return this._forEachPeerConnection((i=>{if(!i.hasConnectedPeerConnection()){Mg.info("Session doesn't have a connected PeerConnection, adding pending action!");const n=this._pendingActionsForConnectedPeerConnections;if(!n)return void Mg.warn("No pending action is created to replace track, because the pending actions array is null");const s=new Promise(((r,s)=>{n.push((()=>{const n=i.replaceTrack(e,t);if(!n)return Mg.error("replaceTrack returned false!"),void s("ReplaceTrack returned false");n.then((e=>r(e))).catch((e=>s(e)))}))}));return void r.push(s)}const n=i.replaceTrack(e,t);n?r.push(n):Mg.error("replaceTrack returned false!")})),Promise.all(r)}_removeStreamFromPeerConnections(e){this._forEachPeerConnection((t=>{this._withForcedRenegotiation(t,(()=>t.removeStream(e)))}))}_removeTrackFromPeerConnections(e){this._forEachPeerConnection((t=>{this._withForcedRenegotiation(t,(()=>t.removeTrack(e)))}))}_addLocalStream(e,t){this._addEnabledLocalStreamId(e),this.localStreams[e]=t}_removeLocalStream(e){delete this.localStreams[e],this._deleteEnabledLocalStreamId(e)}_updateAndScheduleMediaServersRefresh({iceServers:e,sfuServer:t,mediaserverConfigTtlSeconds:r}){this._iceServers=e,this._sfuServer=t,this._mediaserverConfigTtlSeconds=r,this._clearMediaServersRefresh(),r&&(this._fetchMediaServersTimer=setTimeout((()=>this._emitServerEvent(em)),1e3*r))}_clearMediaServersRefresh(){this._fetchMediaServersTimer&&(clearTimeout(this._fetchMediaServersTimer),this._fetchMediaServersTimer=null)}_monitorAudioTrack(e){var t,r;(null===(t=this._audioTrackBeingMonitored)||void 0===t?void 0:t.id)!==e.id&&(null===(r=this._audioTrackBeingMonitored)||void 0===r||r.removeEventListener("ended",this._audioTrackOnEnded),e.addEventListener("ended",this._audioTrackOnEnded),this._audioTrackBeingMonitored=e)}_monitorVideoTrack(e){var t,r;(null===(t=this._videoTrackBeingMonitored)||void 0===t?void 0:t.id)!==e.id&&(null===(r=this._videoTrackBeingMonitored)||void 0===r||r.removeEventListener("ended",this._videoTrackOnEnded),e.addEventListener("ended",this._videoTrackOnEnded),this._videoTrackBeingMonitored=e)}_connect(e){let t=this._getSession(e),r=t&&t.bandwidth||0;return t?(Mg.warn("Replacing peer session",e),this._cleanup(e)):r=this._changeBandwidthForAllClients(!0),t=this._createP2pSession({clientId:e,initialBandwidth:r,shouldAddLocalVideo:!0,isOfferer:!0}),this._negotiatePeerConnection(e,t),Promise.resolve(t)}_maybeRestartIce(e,t){const r=t.pc;"disconnected"!==r.iceConnectionState&&"failed"!==r.iceConnectionState||"offer"===r.localDescription.type&&(t.wasEverConnected=!1,t.relayCandidateSeen=!1,t.serverReflexiveCandidateSeen=!1,t.publicHostCandidateSeen=!1,t.ipv6HostCandidateSeen=!1,this.ipv6HostCandidateTeredoSeen=!1,this.ipv6HostCandidate6to4Seen=!1,this.mdnsHostCandidateSeen=!1,this._emit(Km),this._negotiatePeerConnection(e,t,Object.assign({},this.offerOptions,{iceRestart:!0})))}_setCodecPreferences(e,{vp9On:t,av1On:r,redOn:i}){try{const n=e.getTransceivers().filter((e=>{var t,r;return"audio"===(null===(r=null===(t=null==e?void 0:e.sender)||void 0===t?void 0:t.track)||void 0===r?void 0:r.kind)}));n.forEach((e=>{if(void 0===RTCRtpSender.getCapabilities)return;const t=RTCRtpSender.getCapabilities("audio");for(let e=0;e<t.codecs.length;e++)if(i&&"audio/red"===t.codecs[e].mimeType.toLowerCase()){t.codecs.unshift(t.codecs.splice(e,1)[0]);break}void 0!==e.setCodecPreferences&&e.setCodecPreferences(t.codecs)}));const s=e.getTransceivers().filter((e=>{var t,r;return"video"===(null===(r=null===(t=null==e?void 0:e.sender)||void 0===t?void 0:t.track)||void 0===r?void 0:r.kind)}));s.forEach((e=>{if(void 0===RTCRtpReceiver.getCapabilities)return;const i=RTCRtpReceiver.getCapabilities("video");(t||r)&&(i.codecs=function(e,t){const r=e.map((({mimeType:e})=>e)).filter(((e,t,r)=>r.indexOf(e)===t)),i=function(e,{vp9On:t,av1On:r}){return t&&e.unshift("video/vp9"),r&&e.unshift("video/av1"),e}(r,t);return e.sort(((e,t)=>{const r=i.indexOf(e.mimeType.toLowerCase()),n=i.indexOf(t.mimeType.toLowerCase());return(r>=0?r:Number.MAX_VALUE)-(n>=0?n:Number.MAX_VALUE)}))}(i.codecs,{vp9On:t,av1On:r})),void 0!==e.setCodecPreferences&&e.setCodecPreferences(i.codecs)}))}catch(e){Mg.error("Error during setting setCodecPreferences:",e)}}_negotiatePeerConnection(e,t,r){if(!t)return void Mg.warn("No RTCPeerConnection in negotiatePeerConnection()",e);const i=t.pc;if(!t.canModifyPeerConnection())return void t.pending.push((()=>{this._negotiatePeerConnection(e,t,r)}));t.isOperationPending=!0;const{vp9On:n,av1On:s,redOn:o,rtpAbsCaptureTimeOn:a,cleanSdpOn:c}=this._features;(n||s||o)&&this._setCodecPreferences(i,{vp9On:n,av1On:s,redOn:o}),i.createOffer(r||this.offerOptions).then((t=>{a&&(t.sdp=qf(t.sdp)),(n||o)&&"firefox"===jg&&(t.sdp=function(e,t,r){var i,n;try{const s=ji(e);if(Array.isArray(null==s?void 0:s.media)){const e=s.media.find((e=>"audio"===e.type));if(Array.isArray(null==e?void 0:e.rtp)){const t=e.rtp;for(let n=0;n<t.length;n++)if(r&&"red"===t[n].codec){const r=null===(i=e.payloads)||void 0===i?void 0:i.split(" "),s=null==r?void 0:r.indexOf(""+t[n].payload);s&&-1!==s&&s>=0&&(null==r||r.unshift(r.splice(s,1)[0]),e.payloads=null==r?void 0:r.join(" "))}}const o=s.media.find((e=>"video"===e.type));if(Array.isArray(null==o?void 0:o.rtp)){const e=o.rtp;for(let r=0;r<e.length;r++)if(t&&"VP9"===e[r].codec){const t=null===(n=o.payloads)||void 0===n?void 0:n.split(" "),i=null==t?void 0:t.indexOf(""+e[r].payload);i&&-1!==i&&i>=0&&(null==t||t.unshift(t.splice(i,1)[0]),o.payloads=null==t?void 0:t.join(" "))}}}return Li(s)}catch(e){zf.error("setCodecPreferenceSDP error:",e)}}(t.sdp,n,o)),c&&(t.sdp=function(e){try{const t=ji(e);return t.media.forEach((e=>{const t={};e.payloads&&(e.payloads=(""+e.payloads).split(" ").filter((e=>!t[e]&&(t[e]=!0))).join(" "));const r={};e.rtp=e.rtp.filter((e=>!e.payload||t[e.payload]&&!r[e.payload]&&(r[e.payload]=!0)));const i={};e.fmtp&&(e.fmtp=e.fmtp.filter((e=>!e.payload||t[e.payload]&&!i[e.payload]&&(i[e.payload]=!0))));const n={};e.rtcpFb&&(e.rtcpFb=e.rtcpFb.filter((e=>!e.payload||t[e.payload]&&!n[e.payload+e.type+e.subtype]&&(n[e.payload+e.type+e.subtype]=!0))))})),Li(t)}catch(e){}return e}(t.sdp)),i.setLocalDescription(t).catch((e=>{throw Mg.warn("RTCPeerConnection.setLocalDescription() failed with local offer",e),this._emit(ig,e),e})).then((()=>{this._emitServerEvent(mm,{receiverId:e,message:this._transformOutgoingSdp(t)})}))})).catch((e=>{Mg.warn("RTCPeerConnection.createOffer() failed to create local offer",e)}))}_withForcedRenegotiation(e,t){const r=e.pc,i=r.onnegotationneeded;r.onnegotiationneeded=null,t(),this._negotiatePeerConnection(e.clientId,e),setTimeout((()=>r.onnegotiationneeded=i),0)}_changeBandwidthForAllClients(e){let t=this.numberOfPeerconnections();if(e&&(t+=1),0===t)return 0;t>7&&(t=7);let r=this._features.bandwidth?parseInt(this._features.bandwidth,10):{1:this._features.lowBandwidth?768:0,2:this._features.highP2PBandwidth&&!this._features.lowBandwidth?768:384,3:this._features.highP2PBandwidth&&!this._features.lowBandwidth?512:256,4:192,5:128,6:128,7:64}[t];if(void 0===r)return 0;if(this._features.adjustBitratesFromResolution){const e=this._getLocalCameraStream();if(e){const t=e&&e.getVideoTracks()[0];if(t){const{width:e,height:i,frameRate:n}=t.getSettings();if(e&&i&&n){const t=Math.round(function(e,t,r){let i=e*t;i<Dm&&(i=Dm),i>xm&&(i=xm);let n=Im;i>xm?n=Mm:i>Dm&&(n+=-17582143775720163e-22*(i-Dm));let s=e*t*n;return r<=15?s*=.7:r<=24&&(s*=.9),s}(e,i,n)/1e3);r=Math.min(t,r||t)}}}}return this._features.higherP2PBitrates&&!this._features.lowBandwidth&&(r*=1.5),this._forEachPeerConnection((e=>{e.changeBandwidth(r)})),r}_createP2pSession({clientId:e,initialBandwidth:t,shouldAddLocalVideo:r=!1,isOfferer:i=!1}){const n=this._createSession({peerConnectionId:e,clientId:e,initialBandwidth:t,shouldAddLocalVideo:r,isOfferer:i}),s=n.pc;this._features.increaseIncomingMediaBufferOn&&this._setJitterBufferTarget(s);const o=this.localStreams[Lg];return r&&o&&!o.getVideoTracks().length&&this._stoppedVideoTrack&&s.addTrack(this._stoppedVideoTrack,o),s.onicegatheringstatechange=e=>{switch(e.target.iceGatheringState){case"gathering":this.icePublicIPGatheringTimeoutID&&clearTimeout(this.icePublicIPGatheringTimeoutID),this.icePublicIPGatheringTimeoutID=setTimeout((()=>{n.publicHostCandidateSeen||n.relayCandidateSeen||n.serverReflexiveCandidateSeen||"connected"===s.iceConnectionState&&"completed"===s.iceConnectionState||this._emit(Wm)}),3e3);break;case"complete":this.icePublicIPGatheringTimeoutID&&clearTimeout(this.icePublicIPGatheringTimeoutID),this.icePublicIPGatheringTimeoutID=void 0}},s.onicecandidate=t=>{var r,i;if(t.candidate){switch(null===(r=t.candidate)||void 0===r?void 0:r.type){case"host":const e=null===(i=null==t?void 0:t.candidate)||void 0===i?void 0:i.address;try{if(Um.v4({exact:!0}).test(e)){Un(e).isPublicIp&&(n.publicHostCandidateSeen=!0)}else if(Um.v6({exact:!0}).test(e.replace(/^\[(.*)\]/,"$1"))){const t=new Ai.Address6(e.replace(/^\[(.*)\]/,"$1"));n.ipv6HostCandidateSeen=!0,"Global"===t.getScope()&&(n.publicHostCandidateSeen=!0),t.isTeredo()&&(n.ipv6HostCandidateTeredoSeen=!0),t.is6to4()&&(n.ipv6HostCandidate6to4Seen=!0)}else{const t=e.replace(/.local/,"");t&&Xn(t,4)&&(n.mdnsHostCandidateSeen=!0)}}catch(e){Mg.info("Error during parsing candidates! Error: ",{error:e})}break;case"srflx":n.serverReflexiveCandidateSeen||(n.serverReflexiveCandidateSeen=!0);break;case"relay":case"relayed":n.relayCandidateSeen||(n.relayCandidateSeen=!0)}this._emitServerEvent(um,{receiverId:e,message:t.candidate})}else this._emitServerEvent(pm,{receiverId:e}),n.publicHostCandidateSeen||n.relayCandidateSeen||n.serverReflexiveCandidateSeen||"connected"===s.iceConnectionState||"completed"===s.iceConnectionState||this._emit(Hm),n.ipv6HostCandidateSeen&&this._emit(Gm,{teredoSeen:n.ipv6HostCandidateTeredoSeen,sixtofourSeen:n.ipv6HostCandidate6to4Seen}),n.mdnsHostCandidateSeen&&this._emit(qm)},s.onnegotiationneeded=()=>{"new"!==s.iceConnectionState&&n.connectionStatus&&this._negotiatePeerConnection(e,n)},n}acceptNewStream({streamId:e,clientId:t,shouldAddLocalVideo:r}){let i=this._getSession(t);if(i&&e!==t)return i;let n=i&&i.bandwidth||0;return i?(Mg.warn("Replacing peer session",t),this._cleanup(t)):n=this._changeBandwidthForAllClients(!0),i=this._createP2pSession({clientId:t,initialBandwidth:n,shouldAddLocalVideo:!!r,isOfferer:!1}),this._emitServerEvent(hm,{receiverId:t}),i}disconnect(e){this._cleanup(e),this._changeBandwidthForAllClients(!1);0===this.numberOfPeerconnections()&&setTimeout((()=>{0===this.numberOfPeerconnections()&&this.rtcStatsDisconnect()}),6e4)}updateStreamResolution(){}stopOrResumeAudio(){}_handleStopOrResumeVideo({enable:e,track:t}){e?this._stoppedVideoTrack?(this._replaceTrackToPeerConnections(this._stoppedVideoTrack,t),delete this._stoppedVideoTrack):this._addTrackToPeerConnections(t):this._stoppedVideoTrack=t}stopOrResumeVideo(e,t){var r;if(["chrome","safari"].includes(jg))if(!1===t){const i="ended"===(null===(r=e.getVideoTracks().find((e=>!e.enabled)))||void 0===r?void 0:r.readyState)?0:5e3;setTimeout((()=>{e.getVideoTracks().forEach((r=>{!1===r.enabled&&(r.stop(),e.removeTrack(r),this._emit(Cm,{stream:e,track:r}),this._handleStopOrResumeVideo({enable:t,track:r}))}))}),i)}else if(0===e.getVideoTracks().length){const r=this._webrtcProvider.getMediaConstraints().video;if(!r)return;navigator.mediaDevices.getUserMedia({video:r}).then((r=>{const i=r.getVideoTracks()[0];e.addTrack(i),this._monitorVideoTrack(i),this._emit(Sm,{streamId:e.id,tracks:[i],screenShare:!1}),this._handleStopOrResumeVideo({enable:t,track:i})}))}}_shareScreen(e,t){this._emitServerEvent(tm,{streamId:e,hasAudioTrack:!!t.getAudioTracks().length}),this._wasScreenSharing=!0,this._addStreamToPeerConnections(t)}removeStream(e,t,r){this._removeLocalStream(e),this._removeStreamFromPeerConnections(t),this._wasScreenSharing=!1,this._emitServerEvent(rm,{streamId:e,requestedByClientId:r})}hasClient(e){return Object.keys(this.peerConnections).includes(e)}}class Fg{static parse(e){let t;try{t=JSON.parse(e)}catch(e){return}if("object"==typeof t&&!Array.isArray(t))return t.request?Fg._handleRequest(t):t.response?Fg._handleResponse(t):t.message?Fg._handleMessage(t):void 0}static _handleRequest(e){const t={request:!0};if("string"==typeof e.method&&"number"==typeof e.id)return t.id=e.id,t.method=e.method,t.data=e.data||{},t}static _handleResponse(e){const t={response:!0};if("number"==typeof e.id)return t.id=e.id,e.ok?(t.ok=!0,t.data=e.data||{}):(t.ok=!1,t.errorCode=e.errorCode,t.errorReason=e.errorReason),t}static _handleMessage(e){const t={message:!0};if("string"==typeof e.method)return t.method=e.method,t.data=e.data||{},t}static createRequest(e,t){return{request:!0,id:Math.round(1e7*Math.random()),method:e,data:t||{}}}static createSuccessResponse(e,t){return{response:!0,id:e.id,ok:!0,data:t||{}}}static createErrorResponse(e,t,r){return{response:!0,id:e.id,errorCode:t,errorReason:r}}static createMessage(e,t){return{message:!0,method:e,data:t||{}}}}const zg=new hf;class Vg extends Np{constructor(e,t="whereby-sfu#v4"){super(),this.socket=null,this.wsUrl=e,this.protocol=t,this.sents=new Map,this._setupSocket()}_setupSocket(){this.socket=new WebSocket(this.wsUrl,this.protocol),this.socket.onopen=this._onOpen.bind(this),this.socket.onmessage=this._onMessage.bind(this),this.socket.onclose=this._onClose.bind(this),this.socket.onerror=this._onError.bind(this)}_tearDown(){null!==this.socket&&(this.socket.onopen=null,this.socket.onmessage=null,this.socket.onclose=null,this.socket.onerror=null,this.socket=null,this.sents.forEach((e=>e.close())),this.emit("close"))}close(){var e;null===(e=this.socket)||void 0===e||e.close()}_onOpen(){zg.info("Connected"),this.emit("open")}_onMessage(e){const t=Fg.parse(e.data);zg.info("Received message",t),(null==t?void 0:t.response)?this._handleResponse(t):(null==t?void 0:t.message)&&this.emit("message",t)}_onClose(){zg.info("Disconnected"),this._tearDown()}_onError(e){zg.info("Error",e)}_handleResponse(e){const t=this.sents.get(e.id);if(e.ok)t.resolve(e.data);else{const r=new Error(e.errorReason);t.reject(r)}}send(e){try{this.socket&&this.socket.send(JSON.stringify(e))}catch(e){}}message(e,t={}){const r=Fg.createMessage(e,t);this.send(r)}request(e,t={},r=1500*(15+.1*this.sents.size)){const i=Fg.createRequest(e,t);return this.send(i),new Promise(((e,t)=>{const n={id:i.id,method:i.method,resolve:t=>{this.sents.delete(i.id)&&(clearTimeout(n.timer),e(t))},reject:e=>{this.sents.delete(i.id)&&(clearTimeout(n.timer),t(e))},timer:setTimeout((()=>{this.sents.delete(i.id)&&t(new Error("request timeout"))}),r),close:()=>{clearTimeout(n.timer),t(new Error("transport closed"))}};this.sents.set(i.id,n)}))}}var Ug=Object.freeze({__proto__:null,KalmanFilter:class{constructor({R:e=.01,Q:t=2,A:r=1.1,B:i=1,C:n=1.2}={R:.01,Q:2,A:1.1,B:1,C:1.2}){this.R=e,this.Q=t,this.A=r,this.C=n,this.B=i,this.cov=NaN,this.x=NaN}filter(e,t=0){if(isNaN(this.x))this.x=1/this.C*e,this.cov=1/this.C*this.Q*(1/this.C);else{const r=this.predict(t),i=this.uncertainty(),n=i*this.C*(1/(this.C*i*this.C+this.Q));this.x=r+n*(e-this.C*r),this.cov=i-n*this.C*i}return this.x}predict(e=0){return this.A*this.x+this.B*e}uncertainty(){return this.A*this.cov*this.A+this.R}lastMeasurement(){return this.x}setMeasurementNoise(e){this.Q=e}setProcessNoise(e){this.R=e}},calculateStd:e=>{const t=e.reduce(((e,t)=>e+t),0)/e.length;return e.reduce(((e,r)=>e.concat(Math.pow(r-t,2))),[]).reduce(((e,t)=>e+t),0)/e.length},createACFCalculator:()=>{let e=-1,t=0,r=0;return i=>{const n=i.reduce(((e,t)=>e+t),0)/i.length;if(e=e<0?n:.95*e+.05*n,++r<2)return t=n,0;const s=(n-e)*(t-e);return t=n,s}},standardDeviation:e=>{const t=e.reduce(((e,t)=>e+t),0)/e.length;return{mean:t,SD:Math.sqrt(e.reduce(((e,r)=>e+Math.pow(r-t,2)),0)/e.length)}},variance:(e,t=!1)=>{const r=e.reduce(((e,t)=>e+t),0)/e.length;return e.reduce(((e,t)=>e.concat(Math.pow(t-r,2))),[]).reduce(((e,t)=>e+t),0)/(e.length-(t?0:1))}});const $g={minDecibels:-80,maxDecibels:-10,smoothingTimeConstant:.8,aggSize:1,sampleRate:10,reportRate:2,bins:32,bands:[[0,1,2,3],[4,5,6,7]],separateTrack:{autoGainControl:!1,noiseSupression:!1},binFormula:"bin",scoreFormula:"300 * bands[1].avg / Math.max(bands[1].avg + bands[0].avg, 0.01)",outFormula:"score"},Gg=new hf;const qg=new hf,Hg=Object.freeze({ok:"ok",warning:"warning",critical:"critical"});class Wg extends Np{constructor(){super(),this._clients={},this._producers={},this._startMonitor()}close(){clearInterval(this._intervalHandle),delete this._intervalHandle,this._producers={},this._clients={}}_startMonitor(){this._intervalHandle=setInterval((()=>{Object.entries(this._producers).forEach((([e,t])=>{this._evaluateClient(e,t)}))}),600)}_evaluateClient(e,t){this._clients[e]||(this._clients[e]={audio:{currentQuality:Hg.ok,trend:[]},video:{currentQuality:Hg.ok,trend:[]}}),this._evaluateProducer(e,Object.values(t).filter((e=>"audio"===e.kind)),"audio"),this._evaluateProducer(e,Object.values(t).filter((e=>"video"===e.kind)),"video")}_evaluateProducer(e,t,r){if(0===t.length)return;const i=t.reduce(((e,t)=>e+t.score),0)/t.length,n=this._evaluateScore(i);this._updateTrend(n,this._clients[e][r])&&this.emit(vm,{clientId:e,kind:r,quality:n})}_updateTrend(e,t){return t.trend.push(e),t.trend.length>3&&t.trend.shift(),!(e===t.currentQuality||!t.trend.every((e=>e!==t.currentQuality)))&&(t.currentQuality=e,!0)}addProducer(e,t){e&&t&&"string"==typeof e&&"string"==typeof t?(this._producers[e]||(this._producers[e]={}),this._producers[e][t]={}):qg.warn("Missing clientId or producerId")}removeProducer(e,t){delete this._producers[e][t],0===Object.keys(this._producers[e]).length&&delete this._producers[e]}addConsumer(e,t){e&&t?(this._producers[e]||(this._producers[e]={}),this._producers[e][t]={}):qg.warn("Missing clientId or consumerId")}removeConsumer(e,t){delete this._producers[e][t],0===Object.keys(this._producers[e]).length&&delete this._producers[e]}addProducerScore(e,t,r,i){Array.isArray(i)&&0!==i.length&&!i.some((e=>!e||!e.hasOwnProperty("score")||"number"!=typeof e.score||isNaN(e.score)))?this._producers[e][t]={kind:r,score:this._calcAvgProducerScore(i.map((e=>e.score)))}:qg.warn("Unexpected producer score format")}addConsumerScore(e,t,r,i){i&&i.hasOwnProperty("producerScores")&&Array.isArray(i.producerScores)?this._producers[e][t]={kind:r,score:this._calcAvgProducerScore(i.producerScores)}:qg.warn("Unexpected consumer score format")}_evaluateScore(e){return e<=9&&e>7?Hg.warning:e<=7&&e>0?Hg.critical:Hg.ok}_calcAvgProducerScore(e){try{if(!Array.isArray(e)||0===e.length)return 0;let t=0,r=0;return e.forEach((e=>{e>0&&(t+=e,r++)})),0===t||0===r?0:t/r}catch(e){return qg.error(e),0}}}function Kg(e){let t,r,i,n,s=[];const o=e=>{s=function(e){return"string"==typeof e?e.split(",").filter(Boolean).map((e=>{const[t,r]=/\|/.test(e)?e.split("|"):["",e];return{host:r,dc:t}})):e.filter((e=>e.host)).map((e=>({host:e.host,dc:e.dc||""})))}(e)};let a=!1,c=!1;const d=()=>{if(a)return void(c=!0);a=!0,c=!1;let o=s;if(t){const e=Date.now();e-3e3>(r||0)&&((!n||(i||0)>n)&&e-3e3>(i||0))||(o=[{host:t.host,dc:t.dc}])}const l={};let u=0;o.forEach((({dc:e})=>{void 0===l[e]&&(l[e]=u++)}));let p=0;const h={};let f,m=o.length,g=!1,v=!1;o.forEach((({host:i,dc:n},s)=>{if(s>0){p+=500;const e=(h[n]||0)+2e3;p=Math.max(p,e)}h[n]=p,setTimeout((()=>{var u;if(v)return;const p=new Vg((null===(u=e.getUrlForHost)||void 0===u?void 0:u.call(e,i))||i);let h=!1;p.on("open",(()=>{setTimeout((()=>{var r;if(!h)if(f||v)p.close();else{f=p,v=!0;const d=[...new Set(o.slice(0,s).filter((e=>e.host!==i)).map((e=>e.host)))],u=[...new Set(o.slice(0,s).filter((e=>e.dc!==n)).map((e=>e.dc)))];t=t?Object.assign(Object.assign({},t),{host:i,dc:n,failedHosts:[...new Set([...d,...t.failedHosts])].filter((e=>e!==i&&!t.usedHosts.includes(e))),failedDCs:[...new Set([...u,...t.failedDCs])].filter((e=>e!==n&&!t.usedDCs.includes(e))),usedHosts:[...new Set([...t.usedHosts,i])],usedDCs:[...new Set([...t.usedDCs,n])],numConnections:t.numConnections+1}):{host:i,dc:n,initialHost:i,initialDC:n,initialHostIndex:s,initialDCIndex:l[n],failedHosts:d,failedDCs:u,usedHosts:[i],usedDCs:[n],numConnections:1,numUsedDCs:1,numUsedHosts:1,numFailedDCs:0,numFailedHosts:0},t.numUsedDCs=t.usedDCs.length,t.numUsedHosts=t.usedHosts.length,t.numFailedDCs=t.failedDCs.length,t.numFailedHosts=t.failedHosts.length,c=!1,a=!1,null===(r=e.onConnected)||void 0===r||r.call(e,p,t)}}),100)})),p.on("close",(()=>{var t,i;h=!0,p===f&&(f=void 0,r=Date.now(),g=!0,null===(t=e.onDisconnected)||void 0===t||t.call(e)),m--,0!==m||g||(a=!1,c?setTimeout(d,0):null===(i=e.onFailed)||void 0===i||i.call(e))}))}),p)}))};o(e.initialHostList);return{connect:d,updateHostList:o,networkIsUp:()=>{i=Math.max(Date.now(),i||0)},networkIsPossiblyDown:()=>{n=Date.now()}}}var Jg;const Xg=null!==(Jg=pi.default)&&void 0!==Jg?Jg:pi,Qg=new hf,Zg=Xg.browserDetails.browser;let Yg=!1;const ev=_i(),tv=_i();"chrome"===Zg&&window.document.addEventListener("beforeunload",(()=>Yg=!0));class rv{constructor({selfId:e,room:t,emitter:r,serverSocket:i,webrtcProvider:n,features:s,eventClaim:o}){const{session:a,iceServers:c,sfuServer:d,sfuServers:l,mediaserverConfigTtlSeconds:u}=t;this._selfId=e,this._room=t,this._roomSessionId=null==a?void 0:a.id,this._emitter=r,this._serverSocket=i,this._webrtcProvider=n,this._features=s||{},this._eventClaim=o,this._vegaConnection=null,this._micAnalyser=null,this._micAnalyserDebugger=null,this._mediasoupDevice=(e=>{var t;if(e.isNodeSdk)return new Qn.Device({handlerFactory:Ll.createFactory()});let r=Qn.detectDevice()||(/applecoremedia|applewebkit|safari/i.test(navigator.userAgent)?"Safari12":void 0);if("Safari12"===r&&"object"==typeof navigator&&"string"==typeof navigator.userAgent){const i=new jp.UAParser(navigator.userAgent).getBrowser();parseInt(null!==(t=i.major)&&void 0!==t?t:"0")>=17&&e.safari17HandlerOn&&(r="Safari17")}return/iphone|ipad/i.test(navigator.userAgent)&&(r=e.safari17HandlerOn?"Safari17":"Safari12"),"Safari17"===r?new Qn.Device({handlerFactory:pg.createFactory()}):new Qn.Device({handlerName:r})})(s),this._routerRtpCapabilities=null,this._sendTransport=null,this._receiveTransport=null,this._clientStates=new Map,this._streamIdToVideoConsumerId=new Map,this._streamIdToVideoResolution=new Map,this._consumers=new Map,this._dataConsumers=new Map,this._localStreamDeregisterFunction=null,this._micTrack=null,this._webcamTrack=null,this._screenVideoTrack=null,this._screenAudioTrack=null,this._micProducer=null,this._micProducerPromise=null,this._micPaused=!1,this._micScoreProducer=null,this._micScoreProducerPromise=null,this._webcamProducer=null,this._webcamProducerPromise=null,this._webcamPaused=!1,this._screenVideoProducer=null,this._screenVideoProducerPromise=null,this._screenAudioProducer=null,this._screenAudioProducerPromise=null,this._sndTransportIceRestartPromise=null,this._rcvTransportIceRestartPromise=null,this._colocation=null,this._stopCameraTimeout=null,this._audioTrackOnEnded=()=>{wf.sendEvent("audio_ended",{unloading:Yg}),this._emitToPWA(Xm,{})},this._videoTrackOnEnded=()=>{wf.sendEvent("video_ended",{unloading:Yg}),this._emitToPWA(Qm,{})},this._updateAndScheduleMediaServersRefresh({sfuServer:d,sfuServers:l,iceServers:c.iceServers||[],mediaserverConfigTtlSeconds:u}),this._socketListenerDeregisterFunctions=[],this._reconnect=!0,this._reconnectTimeOut=null,this._hasVegaConnection=!1,this._isConnectingOrConnected=!1,this._qualityMonitor=new Wg,this._qualityMonitor.on(vm,(e=>{this._emitToPWA(vm,e)})),this._networkIsDetectedUpBySignal=!1}_updateAndScheduleMediaServersRefresh({iceServers:e,sfuServer:t,sfuServers:r,mediaserverConfigTtlSeconds:i}){var n,s,o;this._iceServers=e,this._sfuServer=t,this._sfuServers=r,!r&&(null==t?void 0:t.fallbackServers)&&(this._sfuServers=t.fallbackServers.map((e=>({host:e.host||e.fqdn,dc:e.dc})))),this._mediaserverConfigTtlSeconds=i,null===(n=this._vegaConnectionManager)||void 0===n||n.updateHostList(this._features.sfuServersOverride||this._sfuServers||this._features.sfuServerOverrideHost||t.url),null===(s=this._sendTransport)||void 0===s||s.updateIceServers({iceServers:this._iceServers}),null===(o=this._receiveTransport)||void 0===o||o.updateIceServers({iceServers:this._iceServers}),this._clearMediaServersRefresh(),i&&(this._fetchMediaServersTimer=setTimeout((()=>this._emitToSignal(em)),1e3*i))}_clearMediaServersRefresh(){this._fetchMediaServersTimer&&(clearTimeout(this._fetchMediaServersTimer),this._fetchMediaServersTimer=null)}_onNetworkIsDetectedUpBySignal(){var e;this._networkIsDetectedUpBySignal||(this._networkIsDetectedUpBySignal=!0,null===(e=this._vegaConnectionManager)||void 0===e||e.networkIsUp())}_onNetworkIsDetectedPossiblyDownBySignal(){var e;this._networkIsDetectedUpBySignal&&(this._networkIsDetectedUpBySignal=!1,null===(e=this._vegaConnectionManager)||void 0===e||e.networkIsPossiblyDown())}setupSocketListeners(){this._socketListenerDeregisterFunctions.push((()=>this._clearMediaServersRefresh()),this._serverSocket.on(sm,(e=>{e.error?Qg.warn("FETCH_MEDIASERVER_CONFIG failed:",e.error):this._updateAndScheduleMediaServersRefresh(e)})),this._serverSocket.on(dm,(()=>{this._screenVideoTrack&&this._emitScreenshareStarted(),this._features.sfuReconnectV2On&&!this._hasVegaConnection&&this._reconnect&&this._connect()})),this._serverSocket.on("connect",(()=>this._onNetworkIsDetectedUpBySignal())),this._serverSocket.onEngineEvent("packet",(()=>this._onNetworkIsDetectedUpBySignal())),this._serverSocket.on("disconnect",(()=>this._onNetworkIsDetectedPossiblyDownBySignal()))),this._connect()}_emitScreenshareStarted(){this._emitToSignal(tm,{streamId:tv,hasAudioTrack:Boolean(this._screenAudioTrack)})}_connect(){if(this._features.sfuConnectionManagerOn)return this._connect_v2();if(this._features.sfuReconnectV2On){if(this._hasVegaConnection)return;if(!this._serverSocket.isConnected()){const e=this._serverSocket.getReconnectThreshold();if(!e)return;if(Date.now()>(this._serverSocket.disconnectTimestamp||0)+e)return}this._reconnectTimeOut&&clearTimeout(this._reconnectTimeOut)}const e=this._features.sfuServerOverrideHost||[this._sfuServer.url],t=new URLSearchParams(Object.assign({clientId:this._selfId,organizationId:this._room.organizationId,roomName:this._room.name,eventClaim:this._room.isClaimed?this._eventClaim:null,lowBw:"true"},Object.keys(this._features||{}).filter((e=>this._features[e]&&/^sfu/.test(e))).reduce(((e,t)=>Object.assign(Object.assign({},e),{[t]:this._features[t]})),{}))),r=`wss://${e}?${t.toString()}`;this._vegaConnection=new Vg(r),this._hasVegaConnection=!0,this._vegaConnection.on("open",(()=>this._join())),this._vegaConnection.on("close",(()=>this._onClose())),this._vegaConnection.on("message",(e=>this._onMessage(e)))}_connect_v2(){if(this._features.sfuReconnectV2On){if(this._isConnectingOrConnected)return;if(!this._serverSocket.isConnected()){const e=this._serverSocket.getReconnectThreshold();if(!e)return;if(Date.now()>(this._serverSocket.disconnectTimestamp||0)+e)return}this._reconnectTimeOut&&clearTimeout(this._reconnectTimeOut)}if(!this._vegaConnectionManager){const e=this._features.sfuServersOverride||this._sfuServers||this._features.sfuServerOverrideHost||this._sfuServer.url;this._vegaConnectionManager=Kg({initialHostList:e,getUrlForHost:e=>{const t=new URLSearchParams(Object.assign({clientId:this._selfId,organizationId:this._room.organizationId,roomName:this._room.name,eventClaim:this._room.isClaimed?this._eventClaim:null,lowBw:"true"},Object.keys(this._features||{}).filter((e=>this._features[e]&&/^sfu/.test(e))).reduce(((e,t)=>Object.assign(Object.assign({},e),{[t]:this._features[t]})),{})));return`wss://${e}?${t.toString()}`},onConnected:(e,t)=>{this._vegaConnection=e,this._vegaConnection.on("message",(e=>this._onMessage(e))),this._emitToPWA(tg,t),this._join()},onDisconnected:()=>{this._vegaConnection=null,this._isConnectingOrConnected=!1,this._onClose()},onFailed:()=>{this._vegaConnection=null,this._isConnectingOrConnected=!1,this._onClose()}})}this._vegaConnectionManager.connect(),this._isConnectingOrConnected=!0}_onClose(){var e,t;Qg.info("_onClose()"),this._hasVegaConnection=!1,null===(e=this._sendTransport)||void 0===e||e.close(),null===(t=this._receiveTransport)||void 0===t||t.close(),this._sendTransport=null,this._receiveTransport=null,this._streamIdToVideoConsumerId.clear(),this._streamIdToVideoResolution.clear(),this._reconnect&&(this._reconnectTimeOut=setTimeout((()=>this._connect()),1e3)),this._qualityMonitor.close(),this._emitToPWA(eg)}_join(){var e,t;return ff(this,void 0,void 0,(function*(){Qg.info("join()"),this._emitToPWA(Ym);try{const{routerRtpCapabilities:r}=yield this._vegaConnection.request("getCapabilities");this._routerRtpCapabilities||(((e,t)=>{const{vp9On:r,h264On:i}=t;if(r){const{preferredPayloadType:t}=e.codecs.find((e=>"video/vp9"===e.mimeType.toLowerCase())),{preferredPayloadType:r}=e.codecs.find((e=>"video/rtx"===e.mimeType.toLowerCase()&&e.parameters.apt===t));e.codecs=e.codecs.filter((e=>"audio"===e.kind||e.preferredPayloadType===t||e.preferredPayloadType===r))}else if(i){const{preferredPayloadType:t}=e.codecs.find((e=>"video/h264"===e.mimeType.toLowerCase())),{preferredPayloadType:r}=e.codecs.find((e=>"video/rtx"===e.mimeType.toLowerCase()&&e.parameters.apt===t));e.codecs=e.codecs.filter((e=>"audio"===e.kind||e.preferredPayloadType===t||e.preferredPayloadType===r))}})(r,this._features),this._routerRtpCapabilities=r,yield null===(e=this._mediasoupDevice)||void 0===e?void 0:e.load({routerRtpCapabilities:r})),this._vegaConnection.message("setCapabilities",{rtpCapabilities:null===(t=this._mediasoupDevice)||void 0===t?void 0:t.rtpCapabilities}),this._colocation&&this._vegaConnection.message("setColocation",{colocation:this._colocation}),yield Promise.all([this._createTransport(!0),this._createTransport(!1)]);const i=[];!this._micTrack||this._micProducer||this._micProducerPromise||i.push(this._internalSendMic()),!this._webcamTrack||this._webcamProducer||this._webcamProducerPromise||i.push(this._internalSendWebcam()),!this._screenVideoTrack||this._screenVideoProducer||this._screenVideoProducerPromise||i.push(this._internalSendScreenVideo()),!this._screenAudioTrack||this._screenAudioProducer||this._screenAudioProducerPromise||i.push(this._internalSendScreenAudio()),yield Promise.all(i)}catch(e){Qg.error("_join() [error:%o]",e)}}))}_createTransport(e){var t;return ff(this,void 0,void 0,(function*(){const r=e?"createSendTransport":"createRecvTransport",i=yield this._vegaConnection.request("createTransport",{producing:e,consuming:!e,enableTcp:!0,enableUdp:!0,preferUdp:!0,sctpParameters:{enableSctp:!0,numSctpStreams:{OS:1024,MIS:1024},maxSctpMessageSize:262144,sctpSendBufferSize:262144}});i.iceServers=this._iceServers,((e,t)=>{if(!t.useOnlyTURN)return;e.iceTransportPolicy="relay";const r={onlyudp:/^turn:.*transport=udp$/,onlytcp:/^turn:.*transport=tcp$/,onlytls:/^turns:.*transport=tcp$/}[t.useOnlyTURN];r&&(e.iceServers=e.iceServers.filter((e=>e.url&&e.url.match(r))))})(i,this._features);const n=null===(t=this._mediasoupDevice)||void 0===t?void 0:t[r](i),s=t=>ff(this,void 0,void 0,(function*(){if(Qg.info(`Transport ConnectionStateChanged ${t}`),"disconnected"===t||"failed"===t)if(e){if(this._sndTransportIceRestartPromise)return;this._sndTransportIceRestartPromise=this._restartIce(n).finally((()=>{this._sndTransportIceRestartPromise=null}))}else{if(this._rcvTransportIceRestartPromise)return;this._rcvTransportIceRestartPromise=this._restartIce(n).finally((()=>{this._rcvTransportIceRestartPromise=null}))}}));null==n||n.on("connect",(({dtlsParameters:e},t)=>{var r;null===(r=this._vegaConnection)||void 0===r||r.message("connectTransport",{transportId:n.id,dtlsParameters:e}),t()})).on("connectionstatechange",s),null==n||n.observer.once("close",(()=>{n.removeListener("connectionstatechange",s)})),e?(null==n||n.on("produce",(({kind:e,rtpParameters:t,appData:r},i,s)=>ff(this,void 0,void 0,(function*(){var o;try{const{paused:s}=r,{id:a}=yield null===(o=this._vegaConnection)||void 0===o?void 0:o.request("produce",{transportId:n.id,kind:e,rtpParameters:t,paused:s,appData:r});i({id:a})}catch(e){s(e)}})))),null==n||n.on("producedata",(({appData:e,sctpStreamParameters:t},r,i)=>ff(this,void 0,void 0,(function*(){var s;try{const{id:i}=yield null===(s=this._vegaConnection)||void 0===s?void 0:s.request("produceData",{transportId:n.id,sctpStreamParameters:t,appData:e});r({id:i})}catch(e){i(e)}})))),this._sendTransport=n):this._receiveTransport=n}))}_restartIce(e,t=0){return ff(this,void 0,void 0,(function*(){if(!e||!("closed"in e)||!("connectionState"in e))return void Qg.info("_restartIce: No transport or property closed or connectionState!");if(e.closed)return void Qg.info("_restartIce: Transport is closed!");if("disconnected"!==e.connectionState&&"failed"!==e.connectionState)return void Qg.info("_restartIce: Connection is healthy ICE restart no loneger needed!");const{iceRestartStarted:r}=e.appData,i=Date.now();if(Number.isFinite(r)&&i-r<3500)return;if(e.appData.iceRestartStarted=i,5<=t)return void Qg.info("_restartIce: Reached restart ICE maximum retry count!");if(!this._vegaConnection)return void Qg.info("_restartIce: Connection is undefined");const{iceParameters:n}=yield this._vegaConnection.request("restartIce",{transportId:e.id});Qg.info("_restartIce: ICE restart iceParameters received from SFU: ",n);const s=yield e.restartIce({iceParameters:n}).then((()=>null)).catch((e=>e));if(s)switch(Qg.error(`_restartIce: ICE restart failed: ${s}`),s.message){case"missing transportId":case"no such transport":break;default:yield new Promise((e=>{setTimeout((()=>{e(void 0)}),Math.min(3500*Math.pow(2,t),6e4))})),yield this._restartIce(e,t+1)}else yield new Promise((e=>{setTimeout((()=>{e(void 0)}),6e4*Math.min(8,t+1))})),"failed"!==e.connectionState&&"disconnected"!==e.connectionState||(yield this._restartIce(e,t+1))}))}_internalSendMic(){return ff(this,void 0,void 0,(function*(){Qg.info("_internalSendMic()"),this._micProducerPromise=(()=>ff(this,void 0,void 0,(function*(){try{if(!this._micTrack||!this._sendTransport||this._micProducer)return void(this._micProducerPromise=null);const e=this._micPaused,t=yield this._sendTransport.produce(Object.assign(Object.assign({track:this._micTrack,disableTrackOnPause:!1,stopTracks:!1},Sg("audio",!1,this._features)),{appData:{streamId:ev,sourceClientId:this._selfId,screenShare:!1,source:"mic",paused:e}}));e?t.pause():t.resume(),this._micProducer=t,this._qualityMonitor.addProducer(this._selfId,t.id),t.observer.once("close",(()=>{var e;Qg.info('micProducer "close" event'),t.appData.localClosed&&(null===(e=this._vegaConnection)||void 0===e||e.message("closeProducers",{producerIds:[t.id]})),this._micProducer=null,this._micProducerPromise=null,this._qualityMonitor.removeProducer(this._selfId,t.id)})),this._micTrack!==this._micProducer.track&&(yield this._replaceMicTrack()),this._micPaused!==this._micProducer.paused&&this._pauseResumeMic()}catch(e){Qg.error("micProducer failed:%o",e)}finally{this._micProducerPromise=null,this._micTrack||(this._stopProducer(this._micProducer),this._micProducer=null)}})))()}))}_internalSetupMicScore(){return ff(this,void 0,void 0,(function*(){Qg.info("_internalSetupMicScore()"),this._micScoreProducerPromise=(()=>ff(this,void 0,void 0,(function*(){try{if(!this._micProducer||!this._colocation||this._micScoreProducer)return void(this._micScoreProducerPromise=null);const e=yield this._sendTransport.produceData({ordered:!1,maxPacketLifeTime:3e3,label:"micscore",appData:{producerId:this._micProducer.id,clientId:this._selfId}});this._micScoreProducer=e,e.observer.once("close",(()=>{var t;Qg.info('micScoreProducer "close" event'),e.appData.localClosed&&(null===(t=this._vegaConnection)||void 0===t||t.message("closeDataProducers",{dataProducerIds:[e.id]})),this._micScoreProducer=null,this._micScoreProducerPromise=null}))}catch(e){Qg.error("micScoreProducer failed:%o",e)}finally{this._micScoreProducerPromise=null,this._micProducer&&this._colocation||this._stopMicScoreProducer()}})))()}))}_stopMicScoreProducer(){this._stopProducer(this._micScoreProducer),this._micScoreProducer=null}_replaceMicTrack(){var e;return ff(this,void 0,void 0,(function*(){Qg.info("_replaceMicTrack()"),this._micTrack&&this._micProducer&&!this._micProducer.closed&&this._micProducer.track!==this._micTrack&&(yield this._micProducer.replaceTrack({track:this._micTrack}),null===(e=this._micAnalyser)||void 0===e||e.setTrack(this._micTrack),yield this._replaceMicTrack())}))}_pauseResumeMic(){var e,t;Qg.info("_pauseResumeMic()"),this._micProducer&&!this._micProducer.closed&&this._micPaused!==this._micProducer.paused&&(this._micPaused?(this._micProducer.pause(),null===(e=this._vegaConnection)||void 0===e||e.message("pauseProducers",{producerIds:[this._micProducer.id]})):(this._micProducer.resume(),null===(t=this._vegaConnection)||void 0===t||t.message("resumeProducers",{producerIds:[this._micProducer.id]})),this._pauseResumeMic())}_sendMic(e){return ff(this,void 0,void 0,(function*(){return Qg.info("_sendMic() [track:%o]",e),this._micTrack=e,this._micProducer?yield this._replaceMicTrack():this._micProducerPromise?void 0:this._sendTransport?yield this._internalSendMic():void 0}))}_sendMicScore(e){if(!isNaN(e)&&isFinite(e))if(this._micScoreProducer){if(this._micScoreProducer.closed)return void this._stopMicScoreProducer();try{this._micScoreProducer.send(JSON.stringify({score:e}))}catch(e){Qg.error("_sendMicScore failed [error:%o]",e)}}else!this._micScoreProducerPromise&&this._micProducer&&this._colocation&&0!==e&&this._internalSetupMicScore()}_internalSendWebcam(){var e;return ff(this,void 0,void 0,(function*(){Qg.info("_internalSendWebcam()"),!this._sendTransport||this._webcamProducer||this._webcamProducerPromise||"live"!==(null===(e=this._webcamTrack)||void 0===e?void 0:e.readyState)||(this._webcamProducerPromise=(()=>ff(this,void 0,void 0,(function*(){var e,t;try{const t=this._webcamPaused,r=yield this._sendTransport.produce(Object.assign(Object.assign({track:this._webcamTrack,disableTrackOnPause:!1,stopTracks:!1},Sg("video",!1,this._features)),{appData:{streamId:ev,sourceClientId:this._selfId,screenShare:!1,source:"webcam",paused:t}}));t?r.pause():r.resume(),this._webcamProducer=r,this._qualityMonitor.addProducer(this._selfId,r.id),r.observer.once("close",(()=>{var e;Qg.info('webcamProducer "close" event'),r.appData.localClosed&&(null===(e=this._vegaConnection)||void 0===e||e.message("closeProducers",{producerIds:[r.id]})),this._webcamProducer=null,this._webcamProducerPromise=null,this._qualityMonitor.removeProducer(this._selfId,r.id)})),this._webcamTrack&&this._webcamTrack!==(null===(e=this._webcamProducer)||void 0===e?void 0:e.track)&&(this._webcamProducerPromise=null,this._replaceWebcamTrack()),this._webcamPaused!==this._webcamProducer.paused&&this._pauseResumeWebcam()}catch(e){Qg.error("webcamProducer failed:%o",e)}finally{this._webcamProducerPromise=null,this._webcamTrack||(this._stopProducer(this._webcamProducer),this._webcamProducer=null),this._features.lowBandwidth&&this._screenVideoTrack&&(null===(t=this._webcamProducer)||void 0===t||t.setMaxSpatialLayer(0))}})))())}))}_replaceWebcamTrack(){return ff(this,void 0,void 0,(function*(){Qg.info("_replaceWebcamTrack()"),this._sendTransport&&this._webcamTrack&&!this._webcamProducerPromise&&(this._webcamProducer||!this._webcamTrack.enabled?this._webcamProducer.track!==this._webcamTrack&&(yield this._webcamProducer.replaceTrack({track:this._webcamTrack}),yield this._replaceWebcamTrack()):yield this._internalSendWebcam())}))}_pauseResumeWebcam(){var e,t;Qg.info("_pauseResumeWebcam()"),this._webcamProducer&&!this._webcamProducer.closed&&this._webcamPaused!==this._webcamProducer.paused&&(this._webcamPaused?(this._webcamProducer.pause(),null===(e=this._vegaConnection)||void 0===e||e.message("pauseProducers",{producerIds:[this._webcamProducer.id]})):(this._webcamProducer.resume(),null===(t=this._vegaConnection)||void 0===t||t.message("resumeProducers",{producerIds:[this._webcamProducer.id]})),this._pauseResumeWebcam())}_sendWebcam(e){return ff(this,void 0,void 0,(function*(){return Qg.info("_sendWebcam() [track:%o]",e),this._webcamTrack=e,this._webcamProducer?yield this._replaceWebcamTrack():this._webcamProducerPromise?void 0:this._sendTransport?yield this._internalSendWebcam():void 0}))}_internalSendScreenVideo(){return ff(this,void 0,void 0,(function*(){Qg.info("_internalSendScreenVideo()"),this._screenVideoProducerPromise=(()=>ff(this,void 0,void 0,(function*(){var e,t;try{if(!this._screenVideoTrack||!this._sendTransport||this._screenVideoProducer)return void(this._screenVideoProducerPromise=null);const t=yield this._sendTransport.produce(Object.assign(Object.assign({track:this._screenVideoTrack,disableTrackOnPause:!1,stopTracks:!1},Sg("video",!0,this._features)),{appData:{streamId:tv,sourceClientId:this._selfId,screenShare:!0,source:"screenvideo",paused:!1}}));this._screenVideoProducer=t,this._qualityMonitor.addProducer(this._selfId,t.id),t.observer.once("close",(()=>{var e;Qg.info('screenVideoProducer "close" event'),t.appData.localClosed&&(null===(e=this._vegaConnection)||void 0===e||e.message("closeProducers",{producerIds:[t.id]})),this._screenVideoProducer=null,this._screenVideoProducerPromise=null,this._qualityMonitor.removeProducer(this._selfId,t.id)})),this._screenVideoTrack!==this._screenVideoProducer.track&&(yield this._replaceScreenVideoTrack()),this._features.lowBandwidth&&(null===(e=this._webcamProducer)||void 0===e||e.setMaxSpatialLayer(0))}catch(e){Qg.error("screenVideoProducer failed:%o",e)}finally{this._screenVideoProducerPromise=null,this._screenVideoTrack||(yield this._stopProducer(this._screenVideoProducer),this._screenVideoProducer=null,this._features.lowBandwidth&&(null===(t=this._webcamProducer)||void 0===t||t.setMaxSpatialLayer(Number.MAX_VALUE)))}})))()}))}_replaceScreenVideoTrack(){return ff(this,void 0,void 0,(function*(){Qg.info("_replaceScreenVideoTrack()"),this._screenVideoTrack&&this._screenVideoProducer&&!this._screenVideoProducer.closed&&this._screenVideoProducer.track!==this._screenVideoTrack&&(yield this._screenVideoProducer.replaceTrack({track:this._screenVideoTrack}),yield this._replaceScreenVideoTrack())}))}_sendScreenVideo(e){return ff(this,void 0,void 0,(function*(){return Qg.info("_sendScreenVideo() [track:%o]",e),this._screenVideoTrack=e,this._screenVideoProducer?yield this._replaceScreenVideoTrack():this._screenVideoProducerPromise?void 0:this._sendTransport?yield this._internalSendScreenVideo():void 0}))}_internalSendScreenAudio(){return ff(this,void 0,void 0,(function*(){Qg.info("_internalSendScreenAudio()"),this._screenAudioProducerPromise=(()=>ff(this,void 0,void 0,(function*(){try{if(!this._screenAudioTrack||!this._sendTransport||this._screenAudioProducer)return void(this._screenAudioProducerPromise=null);const e=yield this._sendTransport.produce(Object.assign(Object.assign({track:this._screenAudioTrack,disableTrackOnPause:!1,stopTracks:!1},Sg("audio",!0,this._features)),{appData:{streamId:tv,sourceClientId:this._selfId,screenShare:!0,source:"screenaudio",paused:!1}}));this._screenAudioProducer=e,this._qualityMonitor.addProducer(this._selfId,e.id),e.observer.once("close",(()=>{var t;Qg.info('screenAudioProducer "close" event'),e.appData.localClosed&&(null===(t=this._vegaConnection)||void 0===t||t.message("closeProducers",{producerIds:[e.id]})),this._screenAudioProducer=null,this._screenAudioProducerPromise=null,this._qualityMonitor.removeProducer(this._selfId,e.id)})),this._screenAudioTrack!==this._screenAudioProducer.track&&(yield this._replaceScreenAudioTrack())}catch(e){Qg.error("screenAudioProducer failed:%o",e)}finally{this._screenAudioProducerPromise=null,this._screenAudioTrack||(yield this._stopProducer(this._screenAudioProducer),this._screenAudioProducer=null)}})))()}))}_replaceScreenAudioTrack(){return ff(this,void 0,void 0,(function*(){Qg.info("_replaceScreenAudioTrack()"),this._screenAudioTrack&&this._screenAudioProducer&&!this._screenAudioProducer.closed&&this._screenAudioProducer.track!==this._screenAudioTrack&&(yield this._screenAudioProducer.replaceTrack({track:this._screenAudioTrack}),yield this._replaceScreenAudioTrack())}))}_sendScreenAudio(e){return ff(this,void 0,void 0,(function*(){return Qg.info("_sendScreenAudio() [track:%o]",e),this._screenAudioTrack=e,this._screenAudioProducer?yield this._replaceScreenAudioTrack():this._screenAudioProducerPromise?void 0:this._sendTransport?yield this._internalSendScreenAudio():void 0}))}_stopProducer(e){Qg.info("_stopProducer()"),e&&!e.closed&&(e.appData.localClosed=!0,e.close())}isInitializedWith({selfId:e,roomName:t,isSfu:r}){return this._selfId===e&&this._room.name===t&&Boolean(r)}setEventClaim(e){var t;this._eventClaim=e,null===(t=this._vegaConnection)||void 0===t||t.message("eventClaim",{eventClaim:e})}setColocation(e){var t;this._colocation=e,null===(t=this._vegaConnection)||void 0===t||t.message("setColocation",{colocation:e}),e||!this._micScoreProducer||this._micScoreProducerPromise||this._stopMicScoreProducer(),this._syncMicAnalyser(),wf.sendEvent("colocation_changed",{colocation:e})}setAudioOnly(e){var t;null===(t=this._vegaConnection)||void 0===t||t.message(e?"enableAudioOnly":"disableAudioOnly")}setRemoteScreenshareVideoTrackIds(){}setRoomSessionId(e){this._roomSessionId=e}disconnect(e,t,r){var i;if(Qg.info("disconnect() [clientIdOrStreamId:%s, eventClaim:%s]",e,r),this._clientStates.has(e)){const t=this._clientStates.get(e);t.hasAcceptedWebcamStream=!1,t.hasAcceptedScreenStream=!1,this._syncIncomingStreamsWithPWA(e)}r&&(this._eventClaim=r,null===(i=this._vegaConnection)||void 0===i||i.message("eventClaim",{eventClaim:r}))}replaceTrack(e,t){"audio"===t.kind&&(t.effectTrack||this._monitorAudioTrack(t),this._micTrack=t,this._replaceMicTrack()),"video"===t.kind&&(t.effectTrack||this._monitorVideoTrack(t),this._webcamTrack=t,this._replaceWebcamTrack())}removeStream(e,t,r){var i;Qg.info("removeStream() [streamId:%s, requestedByClientId:%s]",e,r),this._emitToSignal(rm,{streamId:tv,requestedByClientId:r}),this._stopProducer(this._screenVideoProducer),this._screenVideoProducer=null,this._screenVideoTrack=null,this._stopProducer(this._screenAudioProducer),this._screenAudioProducer=null,this._screenAudioTrack=null,this._features.lowBandwidth&&(null===(i=this._webcamProducer)||void 0===i||i.setMaxSpatialLayer(Number.MAX_VALUE))}_onMicAnalyserScoreUpdated(e){var t,r;null===(r=null===(t=this._micAnalyserDebugger)||void 0===t?void 0:t.onScoreUpdated)||void 0===r||r.call(t,e),this._sendMicScore(this._micPaused?0:e.out)}addNewStream(e,t,r,i,n=[]){if("0"===e){this._micPaused=r,this._webcamPaused=i;const e=t.getVideoTracks()[0],s=t.getAudioTracks()[0];if(e){this._sendWebcam(e),e.effectTrack||this._monitorVideoTrack(e);const t=n.find((e=>"video"===e.kind));t&&this._monitorVideoTrack(t)}if(s){this._sendMic(s),this._syncMicAnalyser(),s.effectTrack||this._monitorAudioTrack(s);const e=n.find((e=>"audio"===e.kind));e&&this._monitorAudioTrack(e)}this._localStreamDeregisterFunction&&(this._localStreamDeregisterFunction(),this._localStreamDeregisterFunction=null);const o=e=>{const{enable:t,track:r}=e.detail;this._webcamPaused=!t,this._pauseResumeWebcam(),this._handleStopOrResumeVideo({enable:t,track:r})};t.addEventListener("stopresumevideo",o),this._localStreamDeregisterFunction=()=>{t.removeEventListener("stopresumevideo",o)}}else{const e=t.getVideoTracks()[0],r=t.getAudioTracks()[0];e&&this._sendScreenVideo(e),r&&this._sendScreenAudio(r),this._emitScreenshareStarted()}}_syncMicAnalyser(){if(!this._micTrack||!this._colocation||this._micAnalyser)return this._micAnalyser&&!this._colocation?(this._micAnalyser.close(),void(this._micAnalyser=null)):void 0;this._micAnalyser=function({micTrack:e,params:t,onScoreUpdated:r}){const i=new AudioContext;let n=null,s=null,o=null,a=!1;const c=e=>ff(this,void 0,void 0,(function*(){if(o&&a&&o.stop(),a=!1,e&&t.separateTrack)try{const r=yield navigator.mediaDevices.getUserMedia({audio:Object.assign({deviceId:null==o?void 0:o.getSettings().deviceId},t.separateTrack),video:!1});e=r.getAudioTracks()[0],a=!0}catch(e){Gg.warn("unable to fetch new track for colocation speaker analysis, using current",e)}if(o=e,s&&(s.disconnect(),s=null),e){const t=new MediaStream([e]);s=i.createMediaStreamSource(t),s.connect(n)}}));let d;const l=e=>{if(clearInterval(d),t=Object.assign(Object.assign({},$g),e),!n||n.fftSize!==2*t.bins){let e=null;n&&(e=o,c(null)),n=i.createAnalyser(),n.fftSize=2*t.bins,e&&c(e)}const s=new Uint8Array(n.frequencyBinCount),a=[];n.minDecibels=t.minDecibels,n.maxDecibels=t.maxDecibels,n.smoothingTimeConstant=t.smoothingTimeConstant;const l=t.initScript&&new Function("f","setTrack","lastTrack",t.initScript.join("\n")),u=t.scoreScript&&new Function("bins","g","f",t.scoreScript.join("\n")),p=t.scoreFormula&&new Function("bands",`return ${t.scoreFormula}`),h=t.outFormula&&new Function("score","avg","max","scores",`return ${t.outFormula}`),f=t.binFormula&&new Function("bin","index",`return ${t.binFormula}`);let m=0;const g=l&&l(Ug,c,o);d=setInterval((()=>{n.getByteFrequencyData(s);let e=0;if(p){const r=t.bands.map((e=>{const t=e.map((e=>f(s[e]/255,e)));return{avg:t.reduce(((e,t)=>e+t),0)/e.length,min:t.reduce(((e,t)=>Math.min(e,t/255)),Number.MAX_VALUE),max:t.reduce(((e,t)=>Math.max(e,t/255)),0)}}));e=p(r)||0}else u&&(e=u(s,g,Ug),isNaN(e)&&(e=0));if(a.push(e),a.length>t.aggSize&&a.shift(),m++,m>=t.reportRate){m=0;const t=a.reduce(((e,t)=>Math.max(e,t)),0),i=a.reduce(((e,t)=>e+t),0)/a.length,n=h(e,i,t,a);r({bins:s,score:e,max:t,avg:i,out:n})}}),1e3/t.sampleRate)};return l(t),c(e),{setParams:l,setTrack:c,close(){c(null),clearInterval(d),i.close()}}}({micTrack:this._micTrack,onScoreUpdated:this._onMicAnalyserScoreUpdated.bind(this)})}stopOrResumeAudio(e,t){Qg.info("stopOrResumeAudio() [enabled:%s]",t),this._micPaused=!t,this._pauseResumeMic()}_handleStopOrResumeVideo({enable:e,track:t}){e?this._sendWebcam(t):this._webcamProducer&&!this._webcamProducer.closed&&this._webcamProducer.track===t&&(this._stopProducer(this._webcamProducer),this._webcamProducer=null,this._webcamTrack=null)}stopOrResumeVideo(e,t){var r;if(Qg.info("stopOrResumeVideo() [enable:%s]",t),this._webcamPaused=!t,this._pauseResumeWebcam(),["chrome","safari"].includes(Zg))if(t){if(0===e.getVideoTracks().length){const r=this._webrtcProvider.getMediaConstraints().video;navigator.mediaDevices.getUserMedia({video:r}).then((r=>{const i=r.getVideoTracks()[0];e.addTrack(i),this._monitorVideoTrack(i),this._emitToPWA(Sm,{streamId:e.id,tracks:[i],screenShare:!1}),this._handleStopOrResumeVideo({enable:t,track:i})}))}}else{clearTimeout(this._stopCameraTimeout);const i="ended"===(null===(r=e.getVideoTracks().find((e=>!e.enabled)))||void 0===r?void 0:r.readyState)?0:5e3;this._stopCameraTimeout=setTimeout((()=>{e.getVideoTracks().forEach((r=>{!1===r.enabled&&(r.stop(),e.removeTrack(r),this._emitToPWA(Cm,{stream:e,track:r}),this._handleStopOrResumeVideo({enable:t,track:r}))}))}),i)}}supportsScreenShareAudio(){return!0}acceptNewStream({streamId:e,clientId:t}){Qg.info("acceptNewStream()",{streamId:e,clientId:t});const r=this._getOrCreateClientState(t);e!==t?(r.hasAcceptedScreenStream=!0,r.hasEmittedScreenStream=!1):(r.hasAcceptedWebcamStream=!0,r.hasEmittedWebcamStream=!1),this._syncIncomingStreamsWithPWA(t)}updateStreamResolution(e,t,{width:r,height:i}){var n,s;Qg.info("updateStreamResolution()",{streamId:e,width:r,height:i});const o=this._streamIdToVideoConsumerId.get(e),a=this._consumers.get(o);if(!a)return void this._streamIdToVideoResolution.set(e,{width:r,height:i});const c=function(e){let t=0;return e.forEach((e=>{var r,i;e._closed||e._paused||"webcam"!==(null===(r=e._appData)||void 0===r?void 0:r.source)&&"screenvideo"!==(null===(i=e._appData)||void 0===i?void 0:i.source)||t++})),t}(this._consumers),d=function(e){var t,r,i;return/T3/.test((null===(i=null===(r=null===(t=e._rtpParameters)||void 0===t?void 0:t.encodings)||void 0===r?void 0:r[0])||void 0===i?void 0:i.scalabilityMode)||"")?3:2}(a),{spatialLayer:l,temporalLayer:u}=function({width:e,height:t},{numberOfActiveVideos:r,numberOfTemporalLayers:i,uncappedSingleRemoteVideoOn:n}){const s=Math.max(e,t);let o=s>=480?s>=960?2:1:0,a=i-1;return s<100&&(a=Math.max(i-2,0)),r>8&&0===o&&(a=Math.max(i-2,0)),r<4&&s>300&&0===o&&(o=1),n&&1===r&&(o=2,a=i-1),{spatialLayer:o,temporalLayer:a}}({width:r,height:i},{numberOfActiveVideos:c,numberOfTemporalLayers:d,uncappedSingleRemoteVideoOn:null===(n=this._features)||void 0===n?void 0:n.uncappedSingleRemoteVideoOn});a.appData.spatialLayer===l&&a.appData.temporalLayer===u||(a.appData.spatialLayer=l,a.appData.temporalLayer=u,null===(s=this._vegaConnection)||void 0===s||s.message("setConsumersPreferredLayers",{consumerIds:[o],spatialLayer:l,temporalLayer:u}))}disconnectAll(){var e,t,r,i;this._reconnect=!1,this._reconnectTimeOut&&(clearTimeout(this._reconnectTimeOut),this._reconnectTimeOut=null),this._socketListenerDeregisterFunctions.forEach((e=>{e()})),this._localStreamDeregisterFunction&&(this._localStreamDeregisterFunction(),this._localStreamDeregisterFunction=null),this._socketListenerDeregisterFunctions=[],null===(e=this._vegaConnection)||void 0===e||e.removeAllListeners(),null===(t=this._vegaConnection)||void 0===t||t.close(),null===(r=this._sendTransport)||void 0===r||r.close(),null===(i=this._receiveTransport)||void 0===i||i.close(),this._micTrack=null,this._webcamTrack=null,this._screenVideoTrack=null,this._screenAudioTrack=null,this._streamIdToVideoConsumerId.clear(),this._mediasoupDevice=null}sendAudioMutedStats(e){wf.sendEvent("audio_muted",{muted:e})}sendVideoMutedStats(e){wf.sendEvent("video_muted",{muted:e})}sendStatsCustomEvent(e,t){wf.sendEvent(e,t)}rtcStatsDisconnect(){wf.server.close()}rtcStatsReconnect(){wf.server.connected||wf.server.connect()}_monitorAudioTrack(e){var t,r;(null===(t=this._audioTrackBeingMonitored)||void 0===t?void 0:t.id)!==e.id&&(null===(r=this._audioTrackBeingMonitored)||void 0===r||r.removeEventListener("ended",this._audioTrackOnEnded),e.addEventListener("ended",this._audioTrackOnEnded),this._audioTrackBeingMonitored=e)}_monitorVideoTrack(e){var t,r;(null===(t=this._videoTrackBeingMonitored)||void 0===t?void 0:t.id)!==e.id&&(null===(r=this._videoTrackBeingMonitored)||void 0===r||r.removeEventListener("ended",this._videoTrackOnEnded),e.addEventListener("ended",this._videoTrackOnEnded),this._videoTrackBeingMonitored=e)}_onMessage(e){return ff(this,void 0,void 0,(function*(){const{method:t,data:r}=e;return Promise.resolve().then((()=>{switch(t){case"consumerReady":return this._onConsumerReady(r);case"consumerClosed":return this._onConsumerClosed(r);case"consumerPaused":return this._onConsumerPaused(r);case"consumerResumed":return this._onConsumerResumed(r);case"dataConsumerReady":return this._onDataConsumerReady(r);case"dataConsumerClosed":return this._onDataConsumerClosed(r);case"dominantSpeaker":return this._onDominantSpeaker(r);case"consumerScore":return this._onConsumerScore(r);case"producerScore":return this._onProducerScore(r);default:return void Qg.info(`unknown message method "${t}"`)}})).catch((e=>{Qg.error('"message" failed [error:%o]',e)}))}))}_onConsumerReady(e){return ff(this,void 0,void 0,(function*(){Qg.info("_onConsumerReady()",{id:e.id,producerId:e.producerId});const t=yield this._receiveTransport.consume(e);if(t.pause(),t.appData.localPaused=!0,t.appData.spatialLayer=2,this._consumers.set(t.id,t),this._qualityMonitor.addConsumer(t.appData.sourceClientId,t.id),t.observer.once("close",(()=>{this._consumers.delete(t.id),this._qualityMonitor.removeConsumer(t.appData.sourceClientId,t.id),this._consumerClosedCleanup(t)})),this._features.increaseIncomingMediaBufferOn&&t.rtpReceiver)try{t.rtpReceiver.jitterBufferTarget=Wf,t.rtpReceiver.playoutDelayHint=.4}catch(e){Qg.error("Error during setting jitter buffer target:",e)}const{sourceClientId:r,screenShare:i,streamId:n}=t.appData,s=this._getOrCreateClientState(r);i?(s.hasEmittedScreenStream=!1,s.screenShareStreamId=n):(s.hasEmittedWebcamStream=!1,s.camStreamId=n);let o=i?s.screenStream:s.webcamStream;o&&o.inboundId===n||(o=new MediaStream,o.inboundId=n,i?s.screenStream=o:s.webcamStream=o),"video"===t.kind&&this._streamIdToVideoConsumerId.set(o.id,t.id),o.addTrack(t.track),this._syncIncomingStreamsWithPWA(r);const a=this._streamIdToVideoResolution.get(o.id);a&&(this.updateStreamResolution(o.id,null,a),this._streamIdToVideoResolution.delete(o.id))}))}_onConsumerClosed({consumerId:e,reason:t}){var r;return ff(this,void 0,void 0,(function*(){Qg.info("_onConsumerClosed()",{consumerId:e,reason:t}),null===(r=this._consumers.get(e))||void 0===r||r.close()}))}_onConsumerPaused({consumerId:e}){Qg.info("_onConsumerPaused()",{consumerId:e});const t=this._consumers.get(e);t&&(t.appData.remotePaused=!0,t.pause())}_onConsumerResumed({consumerId:e}){Qg.info("_onConsumerResumed()",{consumerId:e});const t=this._consumers.get(e);t&&(t.appData.remotePaused=!1,t.appData.localPaused||t.resume())}_onConsumerScore({consumerId:e,kind:t,score:r}){Qg.info("_onConsumerScore()",{consumerId:e,kind:t,score:r});const{appData:{sourceClientId:i}}=this._consumers.get(e)||{appData:{}};i&&this._qualityMonitor.addConsumerScore(i,e,t,r)}_onProducerScore({producerId:e,kind:t,score:r}){Qg.info("_onProducerScore()",{producerId:e,kind:t,score:r}),[this._micProducer,this._webcamProducer,this._screenVideoProducer,this._screenAudioProducer].forEach((i=>{(null==i?void 0:i.id)===e&&this._qualityMonitor.addProducerScore(this._selfId,e,t,r)}))}_onDataConsumerReady(e){return ff(this,void 0,void 0,(function*(){Qg.info("_onDataConsumerReady()",{id:e.id,producerId:e.producerId});const t=yield this._receiveTransport.consumeData(e);this._dataConsumers.set(t.id,t),t.once("close",(()=>{this._dataConsumers.delete(t.id)}));const{clientId:r}=t.appData;t.on("message",(e=>{var r;if(!this._micAnalyserDebugger)return;if("string"!=typeof e)return;const{score:i}=JSON.parse(e);i&&(null===(r=this._micAnalyserDebugger)||void 0===r||r.onConsumerScore(t.appData.clientId,i))})),this._syncIncomingStreamsWithPWA(r)}))}_onDataConsumerClosed({dataConsumerId:e,reason:t}){return ff(this,void 0,void 0,(function*(){Qg.info("_onDataConsumerClosed()",{dataConsumerId:e,reason:t});const r=this._dataConsumers.get(e);null==r||r.close()}))}_onDominantSpeaker({consumerId:e}){const t=this._consumers.get(e);if(!t)return;const{sourceClientId:r}=t.appData;this._emitToPWA(rg,{clientId:r})}_consumerClosedCleanup(e){const{sourceClientId:t,screenShare:r}=e.appData,i=this._getOrCreateClientState(t),n=r?i.screenStream:i.webcamStream;n&&(n.removeTrack(e.track),0===n.getTracks().length&&(this._streamIdToVideoConsumerId.delete(n.id),this._streamIdToVideoResolution.delete(n.id),r?(i.screenStream=null,i.hasEmittedScreenStream=!1,i.screenShareStreamId=null):(i.hasEmittedWebcamStream=!1,i.camStreamId=null)))}_syncIncomingStreamsWithPWA(e){var t,r;const i=this._getOrCreateClientState(e),{webcamStream:n,screenStream:s,hasEmittedWebcamStream:o,hasEmittedScreenStream:a,hasAcceptedWebcamStream:c,hasAcceptedScreenStream:d,screenShareStreamId:l,camStreamId:u}=i,p=[],h=[];this._consumers.forEach((t=>{if(t.appData.sourceClientId!==e)return;const r=t.appData.screenShare?d:c;!t.appData.localPaused!==r&&(r?(t.appData.remotePaused||t.resume(),t.appData.localPaused=!1,h.push(t.id)):(t.pause(),t.appData.localPaused=!0,p.push(t.id)))})),p.length>0&&(null===(t=this._vegaConnection)||void 0===t||t.message("pauseConsumers",{consumerIds:p})),h.length>0&&(null===(r=this._vegaConnection)||void 0===r||r.message("resumeConsumers",{consumerIds:h})),n&&!o&&c&&(this._emitToPWA(ym,{clientId:e,stream:n,streamId:u,streamType:"webcam"}),i.hasEmittedWebcamStream=!0),s&&!a&&d&&(this._emitToPWA(ym,{clientId:e,stream:s,streamId:l,streamType:"screenshare"}),i.hasEmittedScreenStream=!0)}_getOrCreateClientState(e){let t=this._clientStates.get(e);return t||(t={hasAcceptedWebcamStream:!1,hasAcceptedScreenStream:!1,hasEmittedWebcamStream:!1,hasEmittedScreenStream:!1,webcamStream:null,screenStream:null,screenShareStreamId:null,camStreamId:null},this._clientStates.set(e,t)),t}_emitToPWA(e,t){this._emitter.emit(e,t)}_emitToSignal(e,t,r){this._serverSocket.emit(e,t,r)}shouldAcceptStreamsFromBothSides(){return!0}setMicAnalyserDebugger(e){this._micAnalyserDebugger=e}setMicAnalyserParams(e){var t;null===(t=this._micAnalyser)||void 0===t||t.setParams(e)}hasClient(e){return this._clientStates.has(e)}}class iv{constructor({emitter:e,serverSocket:t,webrtcProvider:r,features:i}){this.emitter=e,this.currentManager=null,t.on(dm,(({room:n,selfId:s,error:o,eventClaim:a})=>{if(o)return;const c={selfId:s,room:n,emitter:e,serverSocket:t,webrtcProvider:r,features:i,eventClaim:a},d=!!n.sfuServer;if(nv=d?"group":"normal",this.currentManager){if(this.currentManager.isInitializedWith({selfId:s,roomName:n.name,isSfu:d}))return void(this.currentManager.setEventClaim&&a&&this.currentManager.setEventClaim(a));this.currentManager.disconnectAll(),e.emit(_m)}let l=null;l=d?new rv(c):new Bg(c),l.rtcStatsReconnect(),l.setupSocketListeners(),e.emit(wm,{rtcManager:l}),this.currentManager=l,t.setRtcManager(l)}))}stopRtcManager(){this.currentManager&&(this.currentManager.disconnectAll(),this.emitter.emit(_m))}}let nv="";const sv=()=>nv,ov=new hf,av={print:(...e)=>console.debug(e[0],...e.slice(1))};ov.withDebugLogger(av);const cv=new class{constructor(){this.BEGIN_PACKET_LOSS_PERIOD_THRESHOLD=.04,this.END_PACKET_LOSS_PERIOD_THRESHOLD=.005,this.INTERVAL_DIFF_THRESHOLD_MS=4e3,this.STALE_MEASUREMENT_TIMEOUT_MS=1e4,this.MINIMUM_INTERVAL_MS=3e4,this.ssrcsHistory=new Map,this.staleMeasurementTimeouts=new Map}addPacketLossMeasurement(e,t,r){this.handleStaleMeasurements(e);const i=t>this.BEGIN_PACKET_LOSS_PERIOD_THRESHOLD;let n=this.ssrcsHistory.get(e);if(!n)return n={id:e,hasActivePacketLoss:i,currPeriod:i?{begin:r}:void 0,hasPeriodicPacketLoss:!1},void this.ssrcsHistory.set(e,n);n.hasActivePacketLoss?t<this.END_PACKET_LOSS_PERIOD_THRESHOLD&&(this.endPacketLossPeriod(n,r),n.prevIntervalInMs&&n.prevIntervalInMs<this.MINIMUM_INTERVAL_MS&&this.ssrcsHistory.delete(e)):i&&(n.hasActivePacketLoss=!0,n.currPeriod={begin:r})}hasPeriodicPacketLoss(e,t){const r=this.ssrcsHistory.get(e);return r&&this.prevIntervalExceeded(r,t)?(this.ssrcsHistory.delete(r.id),!1):(null==r?void 0:r.hasPeriodicPacketLoss)||!1}prevIntervalExceeded(e,t){if(e.prevPeriod&&e.prevIntervalInMs){return t>this.calculatePeriodCenterTimestamp(e.prevPeriod)+e.prevIntervalInMs+this.INTERVAL_DIFF_THRESHOLD_MS}return!1}handleStaleMeasurements(e){const t=this.staleMeasurementTimeouts.get(e);t&&clearTimeout(t),this.staleMeasurementTimeouts.set(e,setTimeout((()=>{ov.debug("handleStaleMeasurements() [measurements invalid for ssrc: %s]",e),this.ssrcsHistory.delete(e)}),this.STALE_MEASUREMENT_TIMEOUT_MS))}endPacketLossPeriod(e,t){if(ov.debug("endPacketLossPeriod() [ssrcId: %s, timestamp: %s]",e.id,t),!e.currPeriod)throw new Error("No packet loss period for "+e.id);e.prevPeriod?(e.currPeriod.end=t,this.addNewPacketLossInterval(e)):e.prevPeriod=Object.assign(Object.assign({},e.currPeriod),{end:t}),delete e.currPeriod,e.hasActivePacketLoss=!1}addNewPacketLossInterval(e){if(ov.debug("addNewPacketLossInterval() [ssrcId: %s, prevIntervalInMs: %s]",e.id,e.prevIntervalInMs),!e.currPeriod||!e.prevPeriod)throw new Error("missing period timestamps");const t=this.calculatePeriodCenterTimestamp(e.prevPeriod),r=this.calculatePeriodCenterTimestamp(e.currPeriod)-t;if(e.prevIntervalInMs){const t=Math.abs(e.prevIntervalInMs-r);e.hasPeriodicPacketLoss=t<this.INTERVAL_DIFF_THRESHOLD_MS,ov.debug("addNewPacketLossInterval() [hasPeriodicPacketLoss: %s, intervalDiffInMs: %s]",t<this.INTERVAL_DIFF_THRESHOLD_MS,t)}e.prevIntervalInMs=r,e.prevPeriod=e.currPeriod}calculatePeriodCenterTimestamp(e){if(!e.end)throw new Error("Missing period end timestamp");return e.begin+(e.end-e.begin)/2}},dv=[{id:"desync",enabled:({client:e,track:t,stats:r})=>!e.isLocalClient&&"audio"===(null==t?void 0:t.kind)&&"object"==typeof(null==r?void 0:r.tracks)&&Object.keys(r.tracks).length>1,check:({stats:e})=>{if(!e)return!1;const t={audio:0,video:0};Object.values(e.tracks).flatMap((e=>Object.values(e.ssrcs))).forEach((e=>{"audio"===e.kind&&e.jitter&&e.jitter>t.audio&&(t.audio=e.jitter),"video"===e.kind&&e.jitter&&e.jitter>t.video&&(t.video=e.jitter)}));return Math.abs(1e3*t.audio-1e3*t.video)>500}},{id:"no-track",enabled:()=>!0,check:({client:e,clients:t,kind:r,track:i})=>{if(!i&&!e.isLocalClient&&"video"===r){const e=t.find((e=>e.isLocalClient));if(e)return!e.isAudioOnlyModeEnabled}return!i}},{id:"ended-track",enabled:({track:e})=>!!e,check:({track:e})=>"ended"===(null==e?void 0:e.readyState)},{id:"no-track-stats",enabled:({hasLiveTrack:e})=>e,check:({client:e,clients:t,kind:r,ssrcs:i})=>{if(0===i.length&&!e.isLocalClient&&"video"===r){const e=t.find((e=>e.isLocalClient));if(e)return!e.isAudioOnlyModeEnabled}return 0===i.length}},{id:"dry-track",enabled:({hasLiveTrack:e,ssrcs:t})=>!(!e||!t),check:({client:e,clients:t,ssrcs:r})=>{let i=!1;if(r.forEach((e=>{i=i||((null==e?void 0:e.bitrate)||0)>0})),!i&&e.isLocalClient){const e=t.filter((e=>!e.isLocalClient));if(e.length>0)return!e.every((e=>e.isAudioOnlyModeEnabled))}return!i}},{id:"low-layer0-bitrate",enabled:({hasLiveTrack:e,ssrc0:t,kind:r,client:i})=>e&&"video"===r&&!!t&&!!(null==t?void 0:t.height)&&!i.isPresentation,check:({ssrc0:e})=>!!(null==e?void 0:e.bitrate)&&(((null==e?void 0:e.height)||0)<200&&e.bitrate<3e4)},{id:"quality-limitation-bw",enabled:({hasLiveTrack:e,stats:t,client:r,clients:i,kind:n})=>{if("normal"===sv()){if(i.filter((e=>!e.isLocalClient)).some((e=>e.isAudioOnlyModeEnabled)))return!1}return e&&r.isLocalClient&&"video"===n&&!!t},check:({stats:e})=>!!e&&!!Object.values(e.tracks).find((e=>Object.values(e.ssrcs).find((e=>"bandwidth"===e.qualityLimitationReason))))},{id:"quality-limitation-cpu",enabled:({hasLiveTrack:e,stats:t,client:r,kind:i})=>e&&r.isLocalClient&&"video"===i&&!!t,check:({stats:e})=>!!e&&!!Object.values(e.tracks).find((e=>Object.values(e.ssrcs).find((e=>"cpu"===e.qualityLimitationReason))))},{id:"high-plirate",enabled:({hasLiveTrack:e,ssrc0:t})=>e&&!!t&&!!t.height,check:({ssrc0:e})=>((null==e?void 0:e.pliRate)||0)>2},{id:"extreme-plirate",enabled:({hasLiveTrack:e,ssrc0:t})=>e&&!!t&&!!t.height,check:({ssrc0:e})=>((null==e?void 0:e.pliRate)||0)>5},{id:"high-packetloss",enabled:({hasLiveTrack:e,ssrc0:t})=>e&&!!t&&"in"===t.direction,check:({ssrc0:e})=>((null==e?void 0:e.lossRatio)||0)>.02},{id:"extreme-packetloss",enabled:({hasLiveTrack:e,ssrc0:t})=>e&&!!t&&"in"===t.direction,check:({ssrc0:e})=>((null==e?void 0:e.lossRatio)||0)>.1},{id:"high-packetloss",enabled:({hasLiveTrack:e,ssrc0:t})=>e&&!!t&&"out"===t.direction,check:({ssrc0:e})=>((null==e?void 0:e.fractionLost)||0)>.02},{id:"extreme-packetloss",enabled:({hasLiveTrack:e,ssrc0:t})=>e&&!!t&&"out"===t.direction,check:({ssrc0:e})=>((null==e?void 0:e.fractionLost)||0)>.1},{id:"fps-below-20",enabled:({hasLiveTrack:e,ssrc0:t,kind:r,client:i})=>e&&!!t&&!!t.height&&"video"===r&&!i.isPresentation,check:({ssrc0:e})=>((null==e?void 0:e.height)||0)>180&&((null==e?void 0:e.fps)||0)<20},{id:"fps-below-10",enabled:({hasLiveTrack:e,ssrc0:t,kind:r,client:i})=>e&&!!t&&!!t.height&&"video"===r&&!i.isPresentation,check:({ssrc0:e})=>((null==e?void 0:e.fps)||0)<10},{id:"bad-network",enabled:({hasLiveTrack:e,ssrcs:t})=>e&&t.length>0,check:({client:e,clients:t,kind:r,ssrcs:i})=>{if(!i.some((e=>((null==e?void 0:e.bitrate)||0)>0))&&e.isLocalClient&&"video"===r){const e=t.filter((e=>!e.isLocalClient));if(e.length>0)return!e.every((e=>e.isAudioOnlyModeEnabled))}const n=i[0];return!!n&&(0===n.bitrate||(n.lossRatio||0)>.03||(n.fractionLost||0)>.03||!e.isPresentation&&"video"===r&&!!(null==n?void 0:n.bitrate)&&n.bitrate<3e4||"in"===n.direction&&!!n.pliRate&&n.pliRate>2)}},{id:"periodic-packet-loss",enabled:({client:e,hasLiveTrack:t,ssrc0:r})=>e.isLocalClient&&t&&!!(null==r?void 0:r.ssrc)&&"out"===(null==r?void 0:r.direction)&&((null==r?void 0:r.bitrate)||0)>0,check:({ssrc0:e})=>!(!e||!e.ssrc)&&(cv.addPacketLossMeasurement(e.ssrc,e.fractionLost||0,Date.now()),cv.hasPeriodicPacketLoss(e.ssrc,Date.now()))},{id:"cpu-pressure-serious",global:!0,enabled:({stats:e})=>{var t;return"cpu"===(null===(t=null==e?void 0:e.pressure)||void 0===t?void 0:t.source)},check:({stats:e})=>{var t;return"serious"===(null===(t=null==e?void 0:e.pressure)||void 0===t?void 0:t.state)}},{id:"cpu-pressure-critical",global:!0,enabled:({stats:e})=>{var t;return"cpu"===(null===(t=null==e?void 0:e.pressure)||void 0===t?void 0:t.source)},check:({stats:e})=>{var t;return"critical"===(null===(t=null==e?void 0:e.pressure)||void 0===t?void 0:t.state)}},{id:"concealed",enabled:({hasLiveTrack:e,ssrc0:t,kind:r})=>e&&!!t&&"audio"===r,check:({ssrc0:e})=>!!(null==e?void 0:e.bitrate)&&"in"===(null==e?void 0:e.direction)&&((null==e?void 0:e.audioLevel)||0)>=.001&&((null==e?void 0:e.audioConcealment)||0)>=.1},{id:"decelerated",enabled:({hasLiveTrack:e,ssrc0:t,kind:r})=>e&&!!t&&"audio"===r,check:({ssrc0:e})=>!!(null==e?void 0:e.bitrate)&&"in"===e.direction&&(e.audioLevel||0)>=.001&&((null==e?void 0:e.audioDeceleration)||0)>=.1},{id:"accelerated",enabled:({hasLiveTrack:e,ssrc0:t,kind:r})=>e&&!!t&&"audio"===r,check:({ssrc0:e})=>!!(null==e?void 0:e.bitrate)&&"in"===e.direction&&(e.audioLevel||0)>=.001&&(e.audioAcceleration||0)>=.1}];let lv=[],uv=null;const pv=[{id:"bitrate",enabled:({hasLiveTrack:e,track:t,ssrc0:r})=>e&&!!t&&!!r,value:({trackStats:e})=>Object.values((null==e?void 0:e.ssrcs)||{}).reduce(((e,t)=>e+((null==t?void 0:t.bitrate)||0)),0)},{id:"pixelrate",enabled:({hasLiveTrack:e,track:t,ssrc0:r,kind:i})=>e&&"video"===i&&!!t&&!!r&&!!r.height,value:({trackStats:e})=>Object.values((null==e?void 0:e.ssrcs)||{}).reduce(((e,t)=>e+(t.fps||0)*(t.width||0)*(t.height||0)),0)},{id:"height",enabled:({hasLiveTrack:e,track:t,trackStats:r,ssrc0:i,kind:n})=>e&&"video"===n&&!!r&&!!t&&!!i&&!!i.height,value:({trackStats:e})=>Object.values((null==e?void 0:e.ssrcs)||{}).reduce(((e,t)=>Math.max(e,t.fps>0?t.height:0)),0)},{id:"sourceHeight",enabled:({hasLiveTrack:e,track:t,ssrc0:r,kind:i})=>e&&"video"===i&&!!t&&!!r&&!!r.sourceHeight&&"out"===r.direction,value:({ssrc0:e})=>null==e?void 0:e.sourceHeight},{id:"packetloss",enabled:({hasLiveTrack:e,ssrc0:t})=>e&&!!t&&!!t.bitrate,value:({ssrc0:e})=>("in"===(null==e?void 0:e.direction)?e.lossRatio:null==e?void 0:e.fractionLost)||0},{id:"jitter",enabled:({hasLiveTrack:e,ssrc0:t})=>e&&!!t&&!!t.bitrate&&"in"===t.direction,value:({ssrc0:e})=>null==e?void 0:e.jitter},{id:"mos",enabled:({hasLiveTrack:e,ssrc0:t})=>e&&!!t&&!!t.bitrate&&"out"===t.direction,value:({ssrc0:e})=>{const t=((null==e?void 0:e.roundTripTime)||0)+2*((null==e?void 0:e.jitter)||0)+10;let r=t<160?93.2-t/40:93.2-(t-120)/10;r-=2.5*(100*((null==e?void 0:e.fractionLost)||0));return 1+.035*r+7e-6*r*(r-60)*(100-r)}},{id:"rendered",value:()=>1},{id:"active",value:({hasLiveTrack:e,track:t,ssrc0:r})=>e&&t&&r?1:0},{id:"cpu-pressure",global:!0,enabled:({stats:e})=>{var t;return"cpu"===(null===(t=null==e?void 0:e.pressure)||void 0===t?void 0:t.source)},value:({stats:e})=>{var t;return{nominal:.25,fair:.5,serious:.75,critical:1}[(null===(t=null==e?void 0:e.pressure)||void 0===t?void 0:t.state)||""]||0}},{id:"turn-usage",global:!0,enabled:({stats:e})=>!!Object.values((null==e?void 0:e.candidatePairs)||{}).length,value:({stats:e})=>Object.values((null==e?void 0:e.candidatePairs)||{}).some((e=>e.usingTurn))},{id:"turn-tls-usage",global:!0,enabled:({stats:e})=>!!Object.values((null==e?void 0:e.candidatePairs)||{}).length,value:({stats:e})=>Object.values((null==e?void 0:e.candidatePairs)||{}).some((e=>"tls"===e.turnProtocol))},{id:"concealment",enabled:({hasLiveTrack:e,ssrc0:t,kind:r})=>e&&!!t&&!!t.bitrate&&"in"===t.direction&&"audio"===r&&(t.audioLevel||0)>=.001,value:({ssrc0:e})=>null==e?void 0:e.audioConcealment},{id:"deceleration",enabled:({hasLiveTrack:e,ssrc0:t,kind:r})=>e&&!!t&&!!t.bitrate&&"in"===t.direction&&"audio"===r&&(t.audioLevel||0)>=.001,value:({ssrc0:e})=>null==e?void 0:e.audioDeceleration},{id:"acceleration",enabled:({hasLiveTrack:e,ssrc0:t,kind:r})=>e&&!!t&&!!t.bitrate&&"in"===t.direction&&"audio"===r&&(t.audioLevel||0)>=.001,value:({ssrc0:e})=>null==e?void 0:e.audioAcceleration},{id:"qpf",enabled:({hasLiveTrack:e,track:t,ssrc0:r,kind:i})=>e&&"video"===i&&!!t&&!!r&&!!r.height,value:({trackStats:e})=>Object.values((null==e?void 0:e.ssrcs)||{}).reduce(((e,t)=>e+(t.qpf||0)),0)}];let hv,fv,mv;const gv=()=>{hv={},fv={},mv={aggregated:{issues:fv,metrics:hv}}};function vv(e,t){Object.values(hv).forEach((e=>{e.curTicks=0,e.curSum=0,e.curMax=0,e.curMin=0,e.curAvg=0})),Object.values(fv).forEach((e=>{e.curTicks=0,e.curRegistered=0,e.active=!1})),t.find((e=>!e.isLocalClient))&&(t.forEach((r=>{const i=e[r.id];["video","audio","global"].forEach((e=>{var n,s;if(("global"!==e||r.isPresentation)&&!(null===(n=r[e])||void 0===n?void 0:n.enabled))return;if("global"===e&&!r.isLocalClient)return;let o=mv[r.id];o||(o={issues:{},metrics:{}},mv[r.id]=o);const a=null===(s=r[e])||void 0===s?void 0:s.track,c=!!a&&"ended"!==a.readyState,d=a&&i&&i.tracks[a.id],l=d?Object.values(d.ssrcs).sort(((e,t)=>(e.height||Number.MAX_SAFE_INTEGER)-(t.height||Number.MAX_SAFE_INTEGER))):[],u=l[0],p={client:r,clients:t,kind:e,track:a,trackStats:d,stats:i,hasLiveTrack:c,ssrc0:u,ssrcs:l,issues:o.issues,metrics:o.metrics},h="global"===e?"global":`${r.isLocalClient?"loc":"rem"}-${r.isPresentation?"pres":"cam"}-${e}`;pv.forEach((t=>{if(t.global&&"global"!==e)return;if(!t.global&&"global"===e)return;if(!t.enabled||t.enabled(p)){const e=`${h}-${t.id}`;let r=o.metrics[e];const i=t.value(p);r||(r={ticks:0,sum:0,avg:0,min:i,max:i},o.metrics[e]=r),r.ticks++,r.sum+=i,r.min=Math.min(r.min,i),r.max=Math.max(r.max,i),r.avg=r.sum/r.ticks;let n=hv[e];n||(n={ticks:0,sum:0,min:i,max:i,avg:0,curTicks:0,curMin:0,curMax:0,curAvg:0,curSum:0,totTicks:0,totMin:0,totMax:0,totAvg:0,totSum:0},hv[e]=n),n.ticks++,n.sum+=i,n.min=Math.min(n.min,i),n.max=Math.max(n.max,i),n.avg=n.sum/n.ticks,0===n.curTicks?(n.curMax=i,n.curMin=i,n.curSum=i):(n.curMax=Math.max(n.curMax,i),n.curMin=Math.min(n.curMin,i),n.curSum+=i),n.curTicks++}})),dv.forEach((t=>{if(t.global&&"global"!==e)return;if(!t.global&&"global"===e)return;const r=`${h}-${t.id}`,i=t.enabled(p);let n=o.issues[r],s=fv[r];if(i){n||(n={active:!1,ticks:0,registered:0,initial:0,periods:0,current:0,longest:0},o.issues[r]=n),n.ticks++,s||(s={active:!1,ticks:0,registered:0,initial:0,curTicks:0,curRegistered:0},fv[r]=s),s.ticks++,s.curTicks++;t.check(p)?(n.registered++,n.current++,n.active||(n.active=!0,n.periods++),n.ticks===n.initial+1&&(n.initial++,s.initial++),n.current>n.longest&&(n.longest=n.current),s.active=!0,s.registered++,s.curRegistered++):(n.active=!1,n.current=0)}else n&&(n.active=!1,n.current=0)}))}))})),Object.values(hv).forEach((e=>{e.curTicks&&(e.curAvg=e.curSum/e.curTicks,0===e.totTicks&&(e.totMin=e.curSum,e.totMax=e.curSum),e.totTicks++,e.totSum+=e.curSum,e.totMin=Math.min(e.totMin,e.curSum),e.totMax=Math.max(e.totMax,e.curSum),e.totAvg=e.totSum/e.totTicks)})),Object.values(fv).forEach((e=>{e.curTicks})),lv.forEach((r=>{var i;return null===(i=r.onUpdatedIssues)||void 0===i?void 0:i.call(r,mv,e,t)})))}function bv(e){return lv.push(e),uv||(uv=function(e,t=jf,r=Lf){return r.subscriptions.push(e),r.currentMonitor||(r.currentMonitor=Nf(r,t)),{stop(){var t;r.subscriptions=r.subscriptions.filter((t=>t!==e)),r.subscriptions.length||(null===(t=r.currentMonitor)||void 0===t||t.stop(),r.currentMonitor=null)}}}({onUpdatedStats:vv}).stop),{stop(){lv=lv.filter((t=>t!==e)),lv.length||(null==uv||uv(),uv=null,gv())}}}var yv;gv();const wv="safari"===(null!==(yv=pi.default)&&void 0!==yv?yv:pi).browserDetails.browser,_v=e=>e.split(/[^\d]/g).map((e=>parseInt(e,10)));function Sv({devices:e,videoId:t,audioId:r,options:i,type:n="ideal"}){const s=e.filter((e=>"audioinput"===e.kind)),o=e.filter((e=>"videoinput"===e.kind)),a=!r||!s.some((e=>e.deviceId===r)),c=!t||!o.some((e=>e.deviceId===t)),d=function({disableAEC:e,disableAGC:t,hd:r,lax:i,lowDataMode:n,preferredDeviceIds:s,resolution:o,simulcast:a,widescreen:c}){var d,l;let u=480,p=240;r&&(u=i||wv?720:{min:360,ideal:720}),a&&(!1===r?(u=360,p=270):p=360);const h={audio:Object.assign({},s.audioId&&{deviceId:s.audioId}),video:Object.assign(Object.assign({},s.videoId?{deviceId:s.videoId}:{facingMode:"user"}),{height:n?p:u,frameRate:n&&!a?15:24})};if(i)return(null===(d=h.audio)||void 0===d?void 0:d.deviceId)||(h.audio=!0),null===(l=h.video)||void 0===l||delete l.facingMode,h;if(o){const[e,t,r]=_v(o);e&&(h.video.width={exact:e}),t&&(h.video.height={exact:t}),r&&(h.video.frameRate={exact:r}),delete h.video.facingMode}else h.video.aspectRatio=c?16/9:4/3;return t&&(h.audio.autoGainControl=!1),e&&(h.audio.echoCancellation=!1),h}(Object.assign({preferredDeviceIds:{audioId:a?null:{[n]:r},videoId:c?null:{[n]:t}}},i));return!1!==r&&s.length||delete d.audio,!1!==t&&o.length||delete d.video,d}const Cv=new hf,Rv=/mobi/i.test(navigator.userAgent);class kv extends Error{constructor(...e){super(...e),this.name="nodevices"}}function Tv(e){return e.audio||e.video?navigator.mediaDevices.getUserMedia(e).catch((t=>{const r=`${t}, ${JSON.stringify(e,null,2)}`;throw Cv.error(`getUserMedia ${r}`),t})):Promise.reject(new kv("No provided devices"))}function Pv(e,t,r,i){var n,s,o;let a={deviceId:null};return t?(a.label=t.label,t.getSettings&&(a=Object.assign(Object.assign({},a),t.getSettings())),a.deviceId?a:(t.getCapabilities&&(a.deviceId=t.getCapabilities().deviceId),a.deviceId?a:(t.label&&r&&(a.deviceId=null===(s=r.find((r=>t.label===r.label&&r.kind===e)))||void 0===s?void 0:s.deviceId),a.deviceId||(a.deviceId=null===(o=t.getConstraints())||void 0===o?void 0:o.deviceId,a.broken=1),a))):(i&&r&&(a.deviceId=null===(n=r.find((t=>t.deviceId===i&&t.kind===e)))||void 0===n?void 0:n.deviceId),a)}function Ev(e,t){t&&"audio"!==t||e.getAudioTracks().forEach((e=>e.stop())),t&&"video"!==t||e.getVideoTracks().forEach((e=>e.stop()))}function Ov(e,{replaceStream:t,fallback:r=!0}={}){var i;return ff(this,void 0,void 0,(function*(){let n,s,o,a=null;const c=!1===e.audioId?"video":!1===e.videoId&&"audio",d=Rv||"video"!==c,l=Sv(e),u=(e,t)=>(e.details=Object.assign({constraints:l,constraint:e.constraint||(null==t?void 0:t.constraint),newConstraints:s,fallback:r,stopTracks:d},e!==n&&{error:String(n)}),e),p=t=>ff(this,void 0,void 0,(function*(){if(l.audio&&l.video){try{a=yield Tv(Sv(Object.assign(Object.assign({},e),{audioId:!1})))}catch(e){"NotFoundError"!==e.name&&u(e,t)}try{a||(a=yield Tv(Sv(Object.assign(Object.assign({},e),{videoId:!1}))))}catch(e){u(e,t)}}}));d&&t&&Ev(t,c);try{a=yield Tv(l)}catch(s){if(n=s,!r)throw u(s);if("OverconstrainedError"===s.name){o={deviceId:{videoId:null,audioId:null},width:{lax:!0},height:{lax:!0},"":{audioId:null,videoId:null,lax:!0}}[s.constraint||""]}else if("NotFoundError"===s.name)yield p(s);else if("NotAllowedError"===s.name||"NotReadableError"===s.name||"AbortError"===s.name)if(t&&!d&&(Ev(t,c),o=e),"NotAllowedError"===s.name)yield p(s);else if("NotAllowedError"!==s.name){try{a=yield Tv(Sv(Object.assign(Object.assign({},e),{options:Object.assign(Object.assign({},e.options),{lax:!0})})))}catch(e){Cv.warn("Tried getting stream again with laxer constraints, but failed: "+(""+e))}const t=(""+s).toLowerCase(),r={audio:"audioId",video:"videoId"}[(null===(i=/(video|audio)/.exec(t))||void 0===i?void 0:i[0])||c||""];if(!a&&r)try{a=yield Tv(Sv(Object.assign(Object.assign({},e),{[r]:null})))}catch(e){Cv.warn(`Re-tried ${r} with no constraints, but failed: ${""+e}`)}if(!a){const t=r?[r]:["videoId","audioId"];for(const r of t){try{a=yield Tv(Sv(Object.assign(Object.assign({},e),{[r]:!1})))}catch(e){Cv.warn(`Re-tried without ${r}, but failed: ${""+e}`)}if(a)break}}}}if(o){const t=c?{audio:{videoId:!1},video:{audioId:!1}}[c]:{};s=Sv(Object.assign(Object.assign(Object.assign(Object.assign({},e),o),{options:Object.assign(Object.assign({},e.options),{lax:o.lax})}),t));try{a=yield Tv(s)}catch(e){throw u(e,n)}}if(!a)throw u(n);let h;return t&&(d||Ev(t,c),h=function(e,t,r){const i=[];return r&&"audio"!==r||(i.push(...e.getAudioTracks()),t.getAudioTracks().forEach((t=>{t.replacement=!0,e.addTrack(t)}))),r&&"video"!==r||(i.push(...e.getVideoTracks()),t.getVideoTracks().forEach((t=>{t.replacement=!0,e.addTrack(t)}))),i.forEach((t=>{t.replaced=!0,e.removeTrack(t)})),i}(t,a,c),a=t),{error:n&&u(n),stream:a,replacedTracks:h}}))}function Dv({oldDevices:e,newDevices:t,currentAudioId:r,currentVideoId:i,currentSpeakerId:n}){const s=function(e,t){const[r,i]=[e,t].map((e=>e.filter((e=>e.kind&&e.deviceId)).reduce(((e,t)=>Object.assign(Object.assign({},e),{[t.kind]:Object.assign(Object.assign({},e[t.kind]),{[t.deviceId]:t})})),{}))),n={};return e.forEach((e=>{e.kind&&e.deviceId&&(n[e.kind]||(n[e.kind]={added:{},removed:{},changed:{}}),i[e.kind]&&i[e.kind][e.deviceId]||(n[e.kind].removed[e.deviceId]=e))})),t.forEach((e=>{e.kind&&e.deviceId&&(n[e.kind]||(n[e.kind]={added:{},removed:{},changed:{}}),r[e.kind]&&r[e.kind][e.deviceId]?r[e.kind][e.deviceId].label&&r[e.kind][e.deviceId].label!==e.label&&(n[e.kind].changed[e.deviceId]=e):n[e.kind].added[e.deviceId]=e)})),n}(e,t),o={},a={},c={};return[["audioinput",r],["videoinput",i],["audiooutput",n]].forEach((([e,r])=>{const i=s[e];if(i){if(r){if(i.removed[r]&&(a[e]={deviceId:null},"audiooutput"===e)){const r=t.find((e=>"audiooutput"===e.kind));a[e]={deviceId:null==r?void 0:r.deviceId}}i.changed[r]&&(a[e]={deviceId:r})}if(Object.keys(i.added).length>0){const[t]=Object.keys(i.added).slice(0,1),r=i.added[t];c[e]={deviceId:r.deviceId,label:r.label,kind:r.kind}}if(Object.keys(i.removed).length>0){const[t]=Object.keys(i.removed).slice(0,1);o[e]=i.removed[t]}}})),{addedDevices:c,changedDevices:a,removedDevices:o}}var Iv;!function(e){e.rtc_manager_created="rtc_manager_created",e.stream_added="stream_added"}(Iv||(Iv={}));var xv={exports:{}};xv.exports=function(e){return(e instanceof Buffer?e:Buffer.from(e.toString(),"binary")).toString("base64")};var Mv=c(xv.exports);function Lv(e,t){return function(){return e.apply(t,arguments)}}const{toString:jv}=Object.prototype,{getPrototypeOf:Av}=Object,Nv=(e=>t=>{const r=jv.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),Bv=e=>(e=e.toLowerCase(),t=>Nv(t)===e),Fv=e=>t=>typeof t===e,{isArray:zv}=Array,Vv=Fv("undefined");const Uv=Bv("ArrayBuffer");const $v=Fv("string"),Gv=Fv("function"),qv=Fv("number"),Hv=e=>null!==e&&"object"==typeof e,Wv=e=>{if("object"!==Nv(e))return!1;const t=Av(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||Symbol.toStringTag in e||Symbol.iterator in e)},Kv=Bv("Date"),Jv=Bv("File"),Xv=Bv("Blob"),Qv=Bv("FileList"),Zv=Bv("URLSearchParams");function Yv(e,t,{allOwnKeys:r=!1}={}){if(null==e)return;let i,n;if("object"!=typeof e&&(e=[e]),zv(e))for(i=0,n=e.length;i<n;i++)t.call(null,e[i],i,e);else{const n=r?Object.getOwnPropertyNames(e):Object.keys(e),s=n.length;let o;for(i=0;i<s;i++)o=n[i],t.call(null,e[o],o,e)}}function eb(e,t){t=t.toLowerCase();const r=Object.keys(e);let i,n=r.length;for(;n-- >0;)if(i=r[n],t===i.toLowerCase())return i;return null}const tb="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:global,rb=e=>!Vv(e)&&e!==tb;const ib=(nb="undefined"!=typeof Uint8Array&&Av(Uint8Array),e=>nb&&e instanceof nb);var nb;const sb=Bv("HTMLFormElement"),ob=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),ab=Bv("RegExp"),cb=(e,t)=>{const r=Object.getOwnPropertyDescriptors(e),i={};Yv(r,((r,n)=>{let s;!1!==(s=t(r,n,e))&&(i[n]=s||r)})),Object.defineProperties(e,i)},db="abcdefghijklmnopqrstuvwxyz",lb="0123456789",ub={DIGIT:lb,ALPHA:db,ALPHA_DIGIT:db+db.toUpperCase()+lb};const pb=Bv("AsyncFunction");var hb={isArray:zv,isArrayBuffer:Uv,isBuffer:function(e){return null!==e&&!Vv(e)&&null!==e.constructor&&!Vv(e.constructor)&&Gv(e.constructor.isBuffer)&&e.constructor.isBuffer(e)},isFormData:e=>{let t;return e&&("function"==typeof FormData&&e instanceof FormData||Gv(e.append)&&("formdata"===(t=Nv(e))||"object"===t&&Gv(e.toString)&&"[object FormData]"===e.toString()))},isArrayBufferView:function(e){let t;return t="undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&Uv(e.buffer),t},isString:$v,isNumber:qv,isBoolean:e=>!0===e||!1===e,isObject:Hv,isPlainObject:Wv,isUndefined:Vv,isDate:Kv,isFile:Jv,isBlob:Xv,isRegExp:ab,isFunction:Gv,isStream:e=>Hv(e)&&Gv(e.pipe),isURLSearchParams:Zv,isTypedArray:ib,isFileList:Qv,forEach:Yv,merge:function e(){const{caseless:t}=rb(this)&&this||{},r={},i=(i,n)=>{const s=t&&eb(r,n)||n;Wv(r[s])&&Wv(i)?r[s]=e(r[s],i):Wv(i)?r[s]=e({},i):zv(i)?r[s]=i.slice():r[s]=i};for(let e=0,t=arguments.length;e<t;e++)arguments[e]&&Yv(arguments[e],i);return r},extend:(e,t,r,{allOwnKeys:i}={})=>(Yv(t,((t,i)=>{r&&Gv(t)?e[i]=Lv(t,r):e[i]=t}),{allOwnKeys:i}),e),trim:e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,""),stripBOM:e=>(65279===e.charCodeAt(0)&&(e=e.slice(1)),e),inherits:(e,t,r,i)=>{e.prototype=Object.create(t.prototype,i),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),r&&Object.assign(e.prototype,r)},toFlatObject:(e,t,r,i)=>{let n,s,o;const a={};if(t=t||{},null==e)return t;do{for(n=Object.getOwnPropertyNames(e),s=n.length;s-- >0;)o=n[s],i&&!i(o,e,t)||a[o]||(t[o]=e[o],a[o]=!0);e=!1!==r&&Av(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},kindOf:Nv,kindOfTest:Bv,endsWith:(e,t,r)=>{e=String(e),(void 0===r||r>e.length)&&(r=e.length),r-=t.length;const i=e.indexOf(t,r);return-1!==i&&i===r},toArray:e=>{if(!e)return null;if(zv(e))return e;let t=e.length;if(!qv(t))return null;const r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},forEachEntry:(e,t)=>{const r=(e&&e[Symbol.iterator]).call(e);let i;for(;(i=r.next())&&!i.done;){const r=i.value;t.call(e,r[0],r[1])}},matchAll:(e,t)=>{let r;const i=[];for(;null!==(r=e.exec(t));)i.push(r);return i},isHTMLForm:sb,hasOwnProperty:ob,hasOwnProp:ob,reduceDescriptors:cb,freezeMethods:e=>{cb(e,((t,r)=>{if(Gv(e)&&-1!==["arguments","caller","callee"].indexOf(r))return!1;const i=e[r];Gv(i)&&(t.enumerable=!1,"writable"in t?t.writable=!1:t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+r+"'")}))}))},toObjectSet:(e,t)=>{const r={},i=e=>{e.forEach((e=>{r[e]=!0}))};return zv(e)?i(e):i(String(e).split(t)),r},toCamelCase:e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,(function(e,t,r){return t.toUpperCase()+r})),noop:()=>{},toFiniteNumber:(e,t)=>(e=+e,Number.isFinite(e)?e:t),findKey:eb,global:tb,isContextDefined:rb,ALPHABET:ub,generateString:(e=16,t=ub.ALPHA_DIGIT)=>{let r="";const{length:i}=t;for(;e--;)r+=t[Math.random()*i|0];return r},isSpecCompliantForm:function(e){return!!(e&&Gv(e.append)&&"FormData"===e[Symbol.toStringTag]&&e[Symbol.iterator])},toJSONObject:e=>{const t=new Array(10),r=(e,i)=>{if(Hv(e)){if(t.indexOf(e)>=0)return;if(!("toJSON"in e)){t[i]=e;const n=zv(e)?[]:{};return Yv(e,((e,t)=>{const s=r(e,i+1);!Vv(s)&&(n[t]=s)})),t[i]=void 0,n}}return e};return r(e,0)},isAsyncFn:pb,isThenable:e=>e&&(Hv(e)||Gv(e))&&Gv(e.then)&&Gv(e.catch)};function fb(e,t,r,i,n){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=(new Error).stack,this.message=e,this.name="AxiosError",t&&(this.code=t),r&&(this.config=r),i&&(this.request=i),n&&(this.response=n)}hb.inherits(fb,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:hb.toJSONObject(this.config),code:this.code,status:this.response&&this.response.status?this.response.status:null}}});const mb=fb.prototype,gb={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach((e=>{gb[e]={value:e}})),Object.defineProperties(fb,gb),Object.defineProperty(mb,"isAxiosError",{value:!0}),fb.from=(e,t,r,i,n,s)=>{const o=Object.create(mb);return hb.toFlatObject(e,o,(function(e){return e!==Error.prototype}),(e=>"isAxiosError"!==e)),fb.call(o,e.message,t,r,i,n),o.cause=e,o.name=e.name,s&&Object.assign(o,s),o};function vb(e){return hb.isPlainObject(e)||hb.isArray(e)}function bb(e){return hb.endsWith(e,"[]")?e.slice(0,-2):e}function yb(e,t,r){return e?e.concat(t).map((function(e,t){return e=bb(e),!r&&t?"["+e+"]":e})).join(r?".":""):t}const wb=hb.toFlatObject(hb,{},null,(function(e){return/^is[A-Z]/.test(e)}));function _b(e,t,r){if(!hb.isObject(e))throw new TypeError("target must be an object");t=t||new FormData;const i=(r=hb.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,(function(e,t){return!hb.isUndefined(t[e])}))).metaTokens,n=r.visitor||d,s=r.dots,o=r.indexes,a=(r.Blob||"undefined"!=typeof Blob&&Blob)&&hb.isSpecCompliantForm(t);if(!hb.isFunction(n))throw new TypeError("visitor must be a function");function c(e){if(null===e)return"";if(hb.isDate(e))return e.toISOString();if(!a&&hb.isBlob(e))throw new fb("Blob is not supported. Use a Buffer instead.");return hb.isArrayBuffer(e)||hb.isTypedArray(e)?a&&"function"==typeof Blob?new Blob([e]):Buffer.from(e):e}function d(e,r,n){let a=e;if(e&&!n&&"object"==typeof e)if(hb.endsWith(r,"{}"))r=i?r:r.slice(0,-2),e=JSON.stringify(e);else if(hb.isArray(e)&&function(e){return hb.isArray(e)&&!e.some(vb)}(e)||(hb.isFileList(e)||hb.endsWith(r,"[]"))&&(a=hb.toArray(e)))return r=bb(r),a.forEach((function(e,i){!hb.isUndefined(e)&&null!==e&&t.append(!0===o?yb([r],i,s):null===o?r:r+"[]",c(e))})),!1;return!!vb(e)||(t.append(yb(n,r,s),c(e)),!1)}const l=[],u=Object.assign(wb,{defaultVisitor:d,convertValue:c,isVisitable:vb});if(!hb.isObject(e))throw new TypeError("data must be an object");return function e(r,i){if(!hb.isUndefined(r)){if(-1!==l.indexOf(r))throw Error("Circular reference detected in "+i.join("."));l.push(r),hb.forEach(r,(function(r,s){!0===(!(hb.isUndefined(r)||null===r)&&n.call(t,r,hb.isString(s)?s.trim():s,i,u))&&e(r,i?i.concat(s):[s])})),l.pop()}}(e),t}function Sb(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,(function(e){return t[e]}))}function Cb(e,t){this._pairs=[],e&&_b(e,this,t)}const Rb=Cb.prototype;function kb(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function Tb(e,t,r){if(!t)return e;const i=r&&r.encode||kb,n=r&&r.serialize;let s;if(s=n?n(t,r):hb.isURLSearchParams(t)?t.toString():new Cb(t,r).toString(i),s){const t=e.indexOf("#");-1!==t&&(e=e.slice(0,t)),e+=(-1===e.indexOf("?")?"?":"&")+s}return e}Rb.append=function(e,t){this._pairs.push([e,t])},Rb.toString=function(e){const t=e?function(t){return e.call(this,t,Sb)}:Sb;return this._pairs.map((function(e){return t(e[0])+"="+t(e[1])}),"").join("&")};class Pb{constructor(){this.handlers=[]}use(e,t,r){return this.handlers.push({fulfilled:e,rejected:t,synchronous:!!r&&r.synchronous,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){hb.forEach(this.handlers,(function(t){null!==t&&e(t)}))}}var Eb={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},Ob={isBrowser:!0,classes:{URLSearchParams:"undefined"!=typeof URLSearchParams?URLSearchParams:Cb,FormData:"undefined"!=typeof FormData?FormData:null,Blob:"undefined"!=typeof Blob?Blob:null},protocols:["http","https","file","blob","url","data"]};const Db="undefined"!=typeof window&&"undefined"!=typeof document,Ib=(xb="undefined"!=typeof navigator&&navigator.product,Db&&["ReactNative","NativeScript","NS"].indexOf(xb)<0);var xb;const Mb="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&"function"==typeof self.importScripts;var Lb={...Object.freeze({__proto__:null,hasBrowserEnv:Db,hasStandardBrowserEnv:Ib,hasStandardBrowserWebWorkerEnv:Mb}),...Ob};function jb(e){function t(e,r,i,n){let s=e[n++];if("__proto__"===s)return!0;const o=Number.isFinite(+s),a=n>=e.length;if(s=!s&&hb.isArray(i)?i.length:s,a)return hb.hasOwnProp(i,s)?i[s]=[i[s],r]:i[s]=r,!o;i[s]&&hb.isObject(i[s])||(i[s]=[]);return t(e,r,i[s],n)&&hb.isArray(i[s])&&(i[s]=function(e){const t={},r=Object.keys(e);let i;const n=r.length;let s;for(i=0;i<n;i++)s=r[i],t[s]=e[s];return t}(i[s])),!o}if(hb.isFormData(e)&&hb.isFunction(e.entries)){const r={};return hb.forEachEntry(e,((e,i)=>{t(function(e){return hb.matchAll(/\w+|\[(\w*)]/g,e).map((e=>"[]"===e[0]?"":e[1]||e[0]))}(e),i,r,0)})),r}return null}const Ab={transitional:Eb,adapter:["xhr","http"],transformRequest:[function(e,t){const r=t.getContentType()||"",i=r.indexOf("application/json")>-1,n=hb.isObject(e);n&&hb.isHTMLForm(e)&&(e=new FormData(e));if(hb.isFormData(e))return i?JSON.stringify(jb(e)):e;if(hb.isArrayBuffer(e)||hb.isBuffer(e)||hb.isStream(e)||hb.isFile(e)||hb.isBlob(e))return e;if(hb.isArrayBufferView(e))return e.buffer;if(hb.isURLSearchParams(e))return t.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let s;if(n){if(r.indexOf("application/x-www-form-urlencoded")>-1)return function(e,t){return _b(e,new Lb.classes.URLSearchParams,Object.assign({visitor:function(e,t,r,i){return Lb.isNode&&hb.isBuffer(e)?(this.append(t,e.toString("base64")),!1):i.defaultVisitor.apply(this,arguments)}},t))}(e,this.formSerializer).toString();if((s=hb.isFileList(e))||r.indexOf("multipart/form-data")>-1){const t=this.env&&this.env.FormData;return _b(s?{"files[]":e}:e,t&&new t,this.formSerializer)}}return n||i?(t.setContentType("application/json",!1),function(e,t,r){if(hb.isString(e))try{return(t||JSON.parse)(e),hb.trim(e)}catch(e){if("SyntaxError"!==e.name)throw e}return(r||JSON.stringify)(e)}(e)):e}],transformResponse:[function(e){const t=this.transitional||Ab.transitional,r=t&&t.forcedJSONParsing,i="json"===this.responseType;if(e&&hb.isString(e)&&(r&&!this.responseType||i)){const r=!(t&&t.silentJSONParsing)&&i;try{return JSON.parse(e)}catch(e){if(r){if("SyntaxError"===e.name)throw fb.from(e,fb.ERR_BAD_RESPONSE,this,null,this.response);throw e}}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:Lb.classes.FormData,Blob:Lb.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};hb.forEach(["delete","get","head","post","put","patch"],(e=>{Ab.headers[e]={}}));var Nb=Ab;const Bb=hb.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]);const Fb=Symbol("internals");function zb(e){return e&&String(e).trim().toLowerCase()}function Vb(e){return!1===e||null==e?e:hb.isArray(e)?e.map(Vb):String(e)}function Ub(e,t,r,i,n){return hb.isFunction(i)?i.call(this,t,r):(n&&(t=r),hb.isString(t)?hb.isString(i)?-1!==t.indexOf(i):hb.isRegExp(i)?i.test(t):void 0:void 0)}class $b{constructor(e){e&&this.set(e)}set(e,t,r){const i=this;function n(e,t,r){const n=zb(t);if(!n)throw new Error("header name must be a non-empty string");const s=hb.findKey(i,n);(!s||void 0===i[s]||!0===r||void 0===r&&!1!==i[s])&&(i[s||t]=Vb(e))}const s=(e,t)=>hb.forEach(e,((e,r)=>n(e,r,t)));return hb.isPlainObject(e)||e instanceof this.constructor?s(e,t):hb.isString(e)&&(e=e.trim())&&!/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim())?s((e=>{const t={};let r,i,n;return e&&e.split("\n").forEach((function(e){n=e.indexOf(":"),r=e.substring(0,n).trim().toLowerCase(),i=e.substring(n+1).trim(),!r||t[r]&&Bb[r]||("set-cookie"===r?t[r]?t[r].push(i):t[r]=[i]:t[r]=t[r]?t[r]+", "+i:i)})),t})(e),t):null!=e&&n(t,e,r),this}get(e,t){if(e=zb(e)){const r=hb.findKey(this,e);if(r){const e=this[r];if(!t)return e;if(!0===t)return function(e){const t=Object.create(null),r=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let i;for(;i=r.exec(e);)t[i[1]]=i[2];return t}(e);if(hb.isFunction(t))return t.call(this,e,r);if(hb.isRegExp(t))return t.exec(e);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,t){if(e=zb(e)){const r=hb.findKey(this,e);return!(!r||void 0===this[r]||t&&!Ub(0,this[r],r,t))}return!1}delete(e,t){const r=this;let i=!1;function n(e){if(e=zb(e)){const n=hb.findKey(r,e);!n||t&&!Ub(0,r[n],n,t)||(delete r[n],i=!0)}}return hb.isArray(e)?e.forEach(n):n(e),i}clear(e){const t=Object.keys(this);let r=t.length,i=!1;for(;r--;){const n=t[r];e&&!Ub(0,this[n],n,e,!0)||(delete this[n],i=!0)}return i}normalize(e){const t=this,r={};return hb.forEach(this,((i,n)=>{const s=hb.findKey(r,n);if(s)return t[s]=Vb(i),void delete t[n];const o=e?function(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,((e,t,r)=>t.toUpperCase()+r))}(n):String(n).trim();o!==n&&delete t[n],t[o]=Vb(i),r[o]=!0})),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const t=Object.create(null);return hb.forEach(this,((r,i)=>{null!=r&&!1!==r&&(t[i]=e&&hb.isArray(r)?r.join(", "):r)})),t}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map((([e,t])=>e+": "+t)).join("\n")}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...t){const r=new this(e);return t.forEach((e=>r.set(e))),r}static accessor(e){const t=(this[Fb]=this[Fb]={accessors:{}}).accessors,r=this.prototype;function i(e){const i=zb(e);t[i]||(!function(e,t){const r=hb.toCamelCase(" "+t);["get","set","has"].forEach((i=>{Object.defineProperty(e,i+r,{value:function(e,r,n){return this[i].call(this,t,e,r,n)},configurable:!0})}))}(r,e),t[i]=!0)}return hb.isArray(e)?e.forEach(i):i(e),this}}$b.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),hb.reduceDescriptors($b.prototype,(({value:e},t)=>{let r=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(e){this[r]=e}}})),hb.freezeMethods($b);var Gb=$b;function qb(e,t){const r=this||Nb,i=t||r,n=Gb.from(i.headers);let s=i.data;return hb.forEach(e,(function(e){s=e.call(r,s,n.normalize(),t?t.status:void 0)})),n.normalize(),s}function Hb(e){return!(!e||!e.__CANCEL__)}function Wb(e,t,r){fb.call(this,null==e?"canceled":e,fb.ERR_CANCELED,t,r),this.name="CanceledError"}hb.inherits(Wb,fb,{__CANCEL__:!0});var Kb=Lb.hasStandardBrowserEnv?{write(e,t,r,i,n,s){const o=[e+"="+encodeURIComponent(t)];hb.isNumber(r)&&o.push("expires="+new Date(r).toGMTString()),hb.isString(i)&&o.push("path="+i),hb.isString(n)&&o.push("domain="+n),!0===s&&o.push("secure"),document.cookie=o.join("; ")},read(e){const t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read:()=>null,remove(){}};function Jb(e,t){return e&&!function(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}(t)?function(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}(e,t):t}var Xb=Lb.hasStandardBrowserEnv?function(){const e=/(msie|trident)/i.test(navigator.userAgent),t=document.createElement("a");let r;function i(r){let i=r;return e&&(t.setAttribute("href",i),i=t.href),t.setAttribute("href",i),{href:t.href,protocol:t.protocol?t.protocol.replace(/:$/,""):"",host:t.host,search:t.search?t.search.replace(/^\?/,""):"",hash:t.hash?t.hash.replace(/^#/,""):"",hostname:t.hostname,port:t.port,pathname:"/"===t.pathname.charAt(0)?t.pathname:"/"+t.pathname}}return r=i(window.location.href),function(e){const t=hb.isString(e)?i(e):e;return t.protocol===r.protocol&&t.host===r.host}}():function(){return!0};function Qb(e,t){let r=0;const i=function(e,t){e=e||10;const r=new Array(e),i=new Array(e);let n,s=0,o=0;return t=void 0!==t?t:1e3,function(a){const c=Date.now(),d=i[o];n||(n=c),r[s]=a,i[s]=c;let l=o,u=0;for(;l!==s;)u+=r[l++],l%=e;if(s=(s+1)%e,s===o&&(o=(o+1)%e),c-n<t)return;const p=d&&c-d;return p?Math.round(1e3*u/p):void 0}}(50,250);return n=>{const s=n.loaded,o=n.lengthComputable?n.total:void 0,a=s-r,c=i(a);r=s;const d={loaded:s,total:o,progress:o?s/o:void 0,bytes:a,rate:c||void 0,estimated:c&&o&&s<=o?(o-s)/c:void 0,event:n};d[t?"download":"upload"]=!0,e(d)}}var Zb="undefined"!=typeof XMLHttpRequest&&function(e){return new Promise((function(t,r){let i=e.data;const n=Gb.from(e.headers).normalize();let s,o,{responseType:a,withXSRFToken:c}=e;function d(){e.cancelToken&&e.cancelToken.unsubscribe(s),e.signal&&e.signal.removeEventListener("abort",s)}if(hb.isFormData(i))if(Lb.hasStandardBrowserEnv||Lb.hasStandardBrowserWebWorkerEnv)n.setContentType(!1);else if(!1!==(o=n.getContentType())){const[e,...t]=o?o.split(";").map((e=>e.trim())).filter(Boolean):[];n.setContentType([e||"multipart/form-data",...t].join("; "))}let l=new XMLHttpRequest;if(e.auth){const t=e.auth.username||"",r=e.auth.password?unescape(encodeURIComponent(e.auth.password)):"";n.set("Authorization","Basic "+btoa(t+":"+r))}const u=Jb(e.baseURL,e.url);function p(){if(!l)return;const i=Gb.from("getAllResponseHeaders"in l&&l.getAllResponseHeaders());!function(e,t,r){const i=r.config.validateStatus;r.status&&i&&!i(r.status)?t(new fb("Request failed with status code "+r.status,[fb.ERR_BAD_REQUEST,fb.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r)):e(r)}((function(e){t(e),d()}),(function(e){r(e),d()}),{data:a&&"text"!==a&&"json"!==a?l.response:l.responseText,status:l.status,statusText:l.statusText,headers:i,config:e,request:l}),l=null}if(l.open(e.method.toUpperCase(),Tb(u,e.params,e.paramsSerializer),!0),l.timeout=e.timeout,"onloadend"in l?l.onloadend=p:l.onreadystatechange=function(){l&&4===l.readyState&&(0!==l.status||l.responseURL&&0===l.responseURL.indexOf("file:"))&&setTimeout(p)},l.onabort=function(){l&&(r(new fb("Request aborted",fb.ECONNABORTED,e,l)),l=null)},l.onerror=function(){r(new fb("Network Error",fb.ERR_NETWORK,e,l)),l=null},l.ontimeout=function(){let t=e.timeout?"timeout of "+e.timeout+"ms exceeded":"timeout exceeded";const i=e.transitional||Eb;e.timeoutErrorMessage&&(t=e.timeoutErrorMessage),r(new fb(t,i.clarifyTimeoutError?fb.ETIMEDOUT:fb.ECONNABORTED,e,l)),l=null},Lb.hasStandardBrowserEnv&&(c&&hb.isFunction(c)&&(c=c(e)),c||!1!==c&&Xb(u))){const t=e.xsrfHeaderName&&e.xsrfCookieName&&Kb.read(e.xsrfCookieName);t&&n.set(e.xsrfHeaderName,t)}void 0===i&&n.setContentType(null),"setRequestHeader"in l&&hb.forEach(n.toJSON(),(function(e,t){l.setRequestHeader(t,e)})),hb.isUndefined(e.withCredentials)||(l.withCredentials=!!e.withCredentials),a&&"json"!==a&&(l.responseType=e.responseType),"function"==typeof e.onDownloadProgress&&l.addEventListener("progress",Qb(e.onDownloadProgress,!0)),"function"==typeof e.onUploadProgress&&l.upload&&l.upload.addEventListener("progress",Qb(e.onUploadProgress)),(e.cancelToken||e.signal)&&(s=t=>{l&&(r(!t||t.type?new Wb(null,e,l):t),l.abort(),l=null)},e.cancelToken&&e.cancelToken.subscribe(s),e.signal&&(e.signal.aborted?s():e.signal.addEventListener("abort",s)));const h=function(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}(u);h&&-1===Lb.protocols.indexOf(h)?r(new fb("Unsupported protocol "+h+":",fb.ERR_BAD_REQUEST,e)):l.send(i||null)}))};const Yb={http:null,xhr:Zb};hb.forEach(Yb,((e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch(e){}Object.defineProperty(e,"adapterName",{value:t})}}));const ey=e=>`- ${e}`,ty=e=>hb.isFunction(e)||null===e||!1===e;var ry=e=>{e=hb.isArray(e)?e:[e];const{length:t}=e;let r,i;const n={};for(let s=0;s<t;s++){let t;if(r=e[s],i=r,!ty(r)&&(i=Yb[(t=String(r)).toLowerCase()],void 0===i))throw new fb(`Unknown adapter '${t}'`);if(i)break;n[t||"#"+s]=i}if(!i){const e=Object.entries(n).map((([e,t])=>`adapter ${e} `+(!1===t?"is not supported by the environment":"is not available in the build")));throw new fb("There is no suitable adapter to dispatch the request "+(t?e.length>1?"since :\n"+e.map(ey).join("\n"):" "+ey(e[0]):"as no adapter specified"),"ERR_NOT_SUPPORT")}return i};function iy(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new Wb(null,e)}function ny(e){iy(e),e.headers=Gb.from(e.headers),e.data=qb.call(e,e.transformRequest),-1!==["post","put","patch"].indexOf(e.method)&&e.headers.setContentType("application/x-www-form-urlencoded",!1);return ry(e.adapter||Nb.adapter)(e).then((function(t){return iy(e),t.data=qb.call(e,e.transformResponse,t),t.headers=Gb.from(t.headers),t}),(function(t){return Hb(t)||(iy(e),t&&t.response&&(t.response.data=qb.call(e,e.transformResponse,t.response),t.response.headers=Gb.from(t.response.headers))),Promise.reject(t)}))}const sy=e=>e instanceof Gb?e.toJSON():e;function oy(e,t){t=t||{};const r={};function i(e,t,r){return hb.isPlainObject(e)&&hb.isPlainObject(t)?hb.merge.call({caseless:r},e,t):hb.isPlainObject(t)?hb.merge({},t):hb.isArray(t)?t.slice():t}function n(e,t,r){return hb.isUndefined(t)?hb.isUndefined(e)?void 0:i(void 0,e,r):i(e,t,r)}function s(e,t){if(!hb.isUndefined(t))return i(void 0,t)}function o(e,t){return hb.isUndefined(t)?hb.isUndefined(e)?void 0:i(void 0,e):i(void 0,t)}function a(r,n,s){return s in t?i(r,n):s in e?i(void 0,r):void 0}const c={url:s,method:s,data:s,baseURL:o,transformRequest:o,transformResponse:o,paramsSerializer:o,timeout:o,timeoutMessage:o,withCredentials:o,withXSRFToken:o,adapter:o,responseType:o,xsrfCookieName:o,xsrfHeaderName:o,onUploadProgress:o,onDownloadProgress:o,decompress:o,maxContentLength:o,maxBodyLength:o,beforeRedirect:o,transport:o,httpAgent:o,httpsAgent:o,cancelToken:o,socketPath:o,responseEncoding:o,validateStatus:a,headers:(e,t)=>n(sy(e),sy(t),!0)};return hb.forEach(Object.keys(Object.assign({},e,t)),(function(i){const s=c[i]||n,o=s(e[i],t[i],i);hb.isUndefined(o)&&s!==a||(r[i]=o)})),r}const ay="1.6.7",cy={};["object","boolean","number","function","string","symbol"].forEach(((e,t)=>{cy[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}}));const dy={};cy.transitional=function(e,t,r){function i(e,t){return"[Axios v1.6.7] Transitional option '"+e+"'"+t+(r?". "+r:"")}return(r,n,s)=>{if(!1===e)throw new fb(i(n," has been removed"+(t?" in "+t:"")),fb.ERR_DEPRECATED);return t&&!dy[n]&&(dy[n]=!0,console.warn(i(n," has been deprecated since v"+t+" and will be removed in the near future"))),!e||e(r,n,s)}};var ly={assertOptions:function(e,t,r){if("object"!=typeof e)throw new fb("options must be an object",fb.ERR_BAD_OPTION_VALUE);const i=Object.keys(e);let n=i.length;for(;n-- >0;){const s=i[n],o=t[s];if(o){const t=e[s],r=void 0===t||o(t,s,e);if(!0!==r)throw new fb("option "+s+" must be "+r,fb.ERR_BAD_OPTION_VALUE)}else if(!0!==r)throw new fb("Unknown option "+s,fb.ERR_BAD_OPTION)}},validators:cy};const uy=ly.validators;class py{constructor(e){this.defaults=e,this.interceptors={request:new Pb,response:new Pb}}async request(e,t){try{return await this._request(e,t)}catch(e){if(e instanceof Error){let t;Error.captureStackTrace?Error.captureStackTrace(t={}):t=new Error;const r=t.stack?t.stack.replace(/^.+\n/,""):"";e.stack?r&&!String(e.stack).endsWith(r.replace(/^.+\n.+\n/,""))&&(e.stack+="\n"+r):e.stack=r}throw e}}_request(e,t){"string"==typeof e?(t=t||{}).url=e:t=e||{},t=oy(this.defaults,t);const{transitional:r,paramsSerializer:i,headers:n}=t;void 0!==r&&ly.assertOptions(r,{silentJSONParsing:uy.transitional(uy.boolean),forcedJSONParsing:uy.transitional(uy.boolean),clarifyTimeoutError:uy.transitional(uy.boolean)},!1),null!=i&&(hb.isFunction(i)?t.paramsSerializer={serialize:i}:ly.assertOptions(i,{encode:uy.function,serialize:uy.function},!0)),t.method=(t.method||this.defaults.method||"get").toLowerCase();let s=n&&hb.merge(n.common,n[t.method]);n&&hb.forEach(["delete","get","head","post","put","patch","common"],(e=>{delete n[e]})),t.headers=Gb.concat(s,n);const o=[];let a=!0;this.interceptors.request.forEach((function(e){"function"==typeof e.runWhen&&!1===e.runWhen(t)||(a=a&&e.synchronous,o.unshift(e.fulfilled,e.rejected))}));const c=[];let d;this.interceptors.response.forEach((function(e){c.push(e.fulfilled,e.rejected)}));let l,u=0;if(!a){const e=[ny.bind(this),void 0];for(e.unshift.apply(e,o),e.push.apply(e,c),l=e.length,d=Promise.resolve(t);u<l;)d=d.then(e[u++],e[u++]);return d}l=o.length;let p=t;for(u=0;u<l;){const e=o[u++],t=o[u++];try{p=e(p)}catch(e){t.call(this,e);break}}try{d=ny.call(this,p)}catch(e){return Promise.reject(e)}for(u=0,l=c.length;u<l;)d=d.then(c[u++],c[u++]);return d}getUri(e){return Tb(Jb((e=oy(this.defaults,e)).baseURL,e.url),e.params,e.paramsSerializer)}}hb.forEach(["delete","get","head","options"],(function(e){py.prototype[e]=function(t,r){return this.request(oy(r||{},{method:e,url:t,data:(r||{}).data}))}})),hb.forEach(["post","put","patch"],(function(e){function t(t){return function(r,i,n){return this.request(oy(n||{},{method:e,headers:t?{"Content-Type":"multipart/form-data"}:{},url:r,data:i}))}}py.prototype[e]=t(),py.prototype[e+"Form"]=t(!0)}));var hy=py;class fy{constructor(e){if("function"!=typeof e)throw new TypeError("executor must be a function.");let t;this.promise=new Promise((function(e){t=e}));const r=this;this.promise.then((e=>{if(!r._listeners)return;let t=r._listeners.length;for(;t-- >0;)r._listeners[t](e);r._listeners=null})),this.promise.then=e=>{let t;const i=new Promise((e=>{r.subscribe(e),t=e})).then(e);return i.cancel=function(){r.unsubscribe(t)},i},e((function(e,i,n){r.reason||(r.reason=new Wb(e,i,n),t(r.reason))}))}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){this.reason?e(this.reason):this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const t=this._listeners.indexOf(e);-1!==t&&this._listeners.splice(t,1)}static source(){let e;return{token:new fy((function(t){e=t})),cancel:e}}}var my=fy;const gy={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(gy).forEach((([e,t])=>{gy[t]=e}));var vy=gy;const by=function e(t){const r=new hy(t),i=Lv(hy.prototype.request,r);return hb.extend(i,hy.prototype,r,{allOwnKeys:!0}),hb.extend(i,r,null,{allOwnKeys:!0}),i.create=function(r){return e(oy(t,r))},i}(Nb);function yy(e,t){return Rt(e,t)}function wy(e,t){return r=>(i,n,s)=>e(n())?t(r)(i,n,s):(console.warn("Not authorized to perform this action"),!1)}function _y(e){return t=>(r,i,n)=>"connected"!==i().roomConnection.status?(console.warn("Action cannot be performed outside of a connected room"),!1):e(t)(r,i,n)}function Sy(e,t){return yy(e,((e,r)=>{const{getState:i}=r;return"connected"!==i().roomConnection.status?(console.warn("Action cannot be performed outside of a connected room"),Promise.reject("Action cannot be performed outside of a connected room")):t(e,r)}))}function Cy(e,t){return r=>(i,n,s)=>"connected"!==n().roomConnection.status?(console.warn("Action cannot be performed outside of a connected room"),!1):wy(e,t)(r)(i,n,s)}by.Axios=hy,by.CanceledError=Wb,by.CancelToken=my,by.isCancel=Hb,by.VERSION=ay,by.toFormData=_b,by.AxiosError=fb,by.Cancel=by.CanceledError,by.all=function(e){return Promise.all(e)},by.spread=function(e){return function(t){return e.apply(null,t)}},by.isAxiosError=function(e){return hb.isObject(e)&&!0===e.isAxiosError},by.mergeConfig=oy,by.AxiosHeaders=Gb,by.formToJSON=e=>jb(hb.isHTMLForm(e)?new FormData(e):e),by.getAdapter=ry,by.HttpStatusCode=vy,by.default=by;const Ry=((e={})=>{const t=new Map,{extra:r,onError:i=ar}=e;zt(i,"onError");const n=e=>{let r=et(Array.from(t.values()),(t=>t.effect===e.effect));return r||(r=tr(e)),(e=>(e.unsubscribe=()=>t.delete(e.id),t.set(e.id,e),t=>{e.unsubscribe(),t?.cancelActive&&rr(e)}))(r)};Object.assign(n,{withTypes:()=>n});const s=e=>{const{type:r,effect:i,predicate:n}=er(e),s=et(Array.from(t.values()),(e=>("string"==typeof r?e.type===r:e.predicate===n)&&e.effect===i));return s&&(s.unsubscribe(),e.cancelActive&&rr(s)),!!s};Object.assign(s,{withTypes:()=>s});const o=async(e,s,o,a)=>{const c=new AbortController,d=Yt(n,c.signal),l=[];try{e.pending.add(c),await Promise.resolve(e.effect(s,Jt({},o,{getOriginalState:a,condition:(e,t)=>d(e,t).then(Boolean),take:d,delay:Kt(c.signal),pause:Wt(c.signal),extra:r,signal:c.signal,fork:Zt(c.signal,l),unsubscribe:e.unsubscribe,subscribe:()=>{t.set(e.id,e)},cancelActiveListeners:()=>{e.pending.forEach(((e,t,r)=>{e!==c&&(Gt(e,Nt),r.delete(e))}))},cancel:()=>{Gt(c,Nt),e.pending.delete(c)},throwIfCancelled:()=>{qt(c.signal)}})))}catch(e){e instanceof Ft||ir(i,e,{raisedBy:"effect"})}finally{await Promise.all(l),Gt(c,Bt),e.pending.delete(c)}},a=(e=>()=>{e.forEach(rr),e.clear()})(t);return{middleware:e=>r=>c=>{if(!z(c))return r(c);if(nr.match(c))return n(c.payload);if(sr.match(c))return void a();if(or.match(c))return s(c.payload);let d=e.getState();const l=()=>{if(d===Xt)throw new Error(`${Qt}: getOriginalState can only be called synchronously`);return d};let u;try{if(u=r(c),t.size>0){const r=e.getState(),n=Array.from(t.values());for(const t of n){let n=!1;try{n=t.predicate(c,r,d)}catch(e){n=!1,ir(i,e,{raisedBy:"predicate"})}n&&o(t,c,e,l)}}}finally{d=Xt}return u},startListening:n,stopListening:s,clearListeners:a}})(),ky=Ry.startListening,Ty=(e,t)=>ky({predicate:(t,r,i)=>{const n=e.map((e=>e(i))),s=e.map((e=>e(r)));return n.some(((e,t)=>e!==s[t]))},effect:(r,{dispatch:i,getState:n,extra:s})=>{const o=e.map((e=>e(n())));t({dispatch:i,getState:n,extra:s},...o)}}),Py=Dt({name:"app",initialState:{isNodeSdk:!1,isActive:!1,isDialIn:!1,ignoreBreakoutGroups:!1,roomName:null,roomUrl:null,displayName:null,userAgent:"core:0.32.8",externalId:null},reducers:{doAppStart:(e,t)=>{const r=new URL(t.payload.roomUrl);return Object.assign(Object.assign(Object.assign({},e),t.payload),{roomName:r.pathname,initialConfig:Object.assign({},t.payload),isActive:!0})},doAppStop:e=>Object.assign(Object.assign({},e),{isActive:!1})}}),{doAppStop:Ey,doAppStart:Oy}=Py.actions,Dy=e=>e.app.isActive,Iy=e=>e.app.isDialIn,xy=e=>e.app.roomName,My=e=>e.app.displayName,Ly=e=>e.app.userAgent,jy=e=>e.app.externalId;function Ay(e){return Qe(`signalConnection/event/${e}`)}const Ny={audioEnabled:Ay("audioEnabled"),audioEnableRequested:Ay("audioEnableRequested"),breakoutGroupJoined:Ay("breakoutGroupJoined"),breakoutMoveToGroup:Ay("breakoutMoveToGroup"),breakoutMoveToMain:Ay("breakoutMoveToMain"),breakoutSessionUpdated:Ay("breakoutSessionUpdated"),chatMessage:Ay("chatMessage"),clientLeft:Ay("clientLeft"),clientKicked:Ay("clientKicked"),clientMetadataReceived:Ay("clientMetadataReceived"),clientUnableToJoin:Ay("clientUnableToJoin"),cloudRecordingStarted:Ay("cloudRecordingStarted"),cloudRecordingStopped:Ay("cloudRecordingStopped"),disconnect:Ay("disconnect"),knockerLeft:Ay("knockerLeft"),knockHandled:Ay("knockHandled"),newClient:Ay("newClient"),roomJoined:Ay("roomJoined"),roomKnocked:Ay("roomKnocked"),roomLeft:Ay("roomLeft"),roomLocked:Ay("roomLocked"),roomSessionEnded:Ay("roomSessionEnded"),screenshareStarted:Ay("screenshareStarted"),screenshareStopped:Ay("screenshareStopped"),spotlightAdded:Ay("spotlightAdded"),spotlightRemoved:Ay("spotlightRemoved"),streamingStopped:Ay("streamingStopped"),videoEnabled:Ay("videoEnabled"),videoEnableRequested:Ay("videoEnableRequested"),liveTranscriptionStarted:Ay("liveTranscriptionStarted"),liveTranscriptionStopped:Ay("liveTranscriptionStopped")},By={canLockRoom:["host"],canRequestAudioEnable:["host"],canRequestVideoEnable:["host"],canKickClient:["host"],canEndMeeting:["host"],canAskToSpeak:["host"],canSpotlight:["host"]},Fy=Dt({name:"authorization",initialState:{roomKey:null,roleName:"none"},reducers:{setRoomKey:(e,t)=>Object.assign(Object.assign({},e),{roomKey:t.payload})},extraReducers:e=>{e.addCase(Oy,((e,t)=>Object.assign(Object.assign({},e),{roomKey:t.payload.roomKey}))),e.addCase(Ny.roomJoined,((e,t)=>{var r,i;const n=null===(i=null===(r=t.payload)||void 0===r?void 0:r.room)||void 0===i?void 0:i.clients.find((e=>{var r;return e.id===(null===(r=t.payload)||void 0===r?void 0:r.selfId)}));return Object.assign(Object.assign({},e),{roleName:(null==n?void 0:n.role.roleName)||"none"})}))}}),{setRoomKey:zy}=Fy.actions,Vy=e=>e.authorization.roomKey,Uy=e=>e.authorization.roleName,$y=Ge(Uy,(e=>By.canLockRoom.includes(e))),Gy=Ge(Uy,(e=>By.canRequestAudioEnable.includes(e))),qy=Ge(Uy,(e=>By.canRequestVideoEnable.includes(e))),Hy=Ge(Uy,(e=>By.canKickClient.includes(e))),Wy=Ge(Uy,(e=>By.canEndMeeting.includes(e))),Ky=Ge(Uy,(e=>By.canAskToSpeak.includes(e))),Jy=Ge(Uy,(e=>By.canSpotlight.includes(e)));function Xy(e,t){var r={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(r[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(i=Object.getOwnPropertySymbols(e);n<i.length;n++)t.indexOf(i[n])<0&&Object.prototype.propertyIsEnumerable.call(e,i[n])&&(r[i[n]]=e[i[n]])}return r}function Qy(e,t,r,i){return new(r||(r=Promise))((function(n,s){function o(e){try{c(i.next(e))}catch(e){s(e)}}function a(e){try{c(i.throw(e))}catch(e){s(e)}}function c(e){e.done?n(e.value):function(e){return e instanceof r?e:new r((function(t){t(e)}))}(e.value).then(o,a)}c((i=i.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;const Zy=Dt({name:"deviceCredentials",initialState:{isFetching:!1,data:null},reducers:{},extraReducers:e=>{e.addCase(Yy.pending,(e=>Object.assign(Object.assign({},e),{isFetching:!0}))),e.addCase(Yy.fulfilled,((e,t)=>Object.assign(Object.assign({},e),{isFetching:!1,data:t.payload}))),e.addCase(Yy.rejected,(e=>Object.assign(Object.assign({},e),{isFetching:!0})))}}),Yy=yy("deviceCredentials/doGetDeviceCredentials",((e,{extra:t})=>Qy(void 0,void 0,void 0,(function*(){try{return yield t.services.credentialsService.getCredentials()}catch(e){console.error(e)}})))),ew=e=>e.deviceCredentials,tw=e=>{var t,r;return null===(r=null===(t=e.deviceCredentials.data)||void 0===t?void 0:t.credentials)||void 0===r?void 0:r.uuid};Ty([Ge(Dy,ew,((e,t)=>!(!e||t.isFetching||t.data)))],(({dispatch:e},t)=>{t&&e(Yy())}));const rw=Dt({name:"signalConnection",initialState:{deviceIdentified:!1,isIdentifyingDevice:!1,status:"ready",socket:null},reducers:{socketConnecting:e=>Object.assign(Object.assign({},e),{status:"connecting"}),socketConnected:(e,t)=>Object.assign(Object.assign({},e),{socket:t.payload,status:"connected"}),socketDisconnected:e=>Object.assign(Object.assign({},e),{socket:null,deviceIdentified:!1,status:"disconnected"}),socketReconnecting:e=>Object.assign(Object.assign({},e),{status:"reconnecting"}),deviceIdentifying:e=>Object.assign(Object.assign({},e),{isIdentifyingDevice:!0}),deviceIdentified:e=>Object.assign(Object.assign({},e),{deviceIdentified:!0,isIdentifyingDevice:!1})},extraReducers:e=>{e.addCase(Ny.disconnect,(e=>Object.assign(Object.assign({},e),{deviceIdentified:!1,status:"disconnected"})))}}),{deviceIdentifying:iw,deviceIdentified:nw,socketConnected:sw,socketConnecting:ow,socketDisconnected:aw,socketReconnecting:cw}=rw.actions,dw=()=>(e,t)=>{if(mw(t()))return;e(ow());const r=function(){const e=new URL("wss://signal.appearin.net").origin;return new Pg(e,{autoConnect:!1})}();r.on("connect",(()=>e(sw(r)))),r.on("device_identified",(()=>e(nw()))),r.getManager().on("reconnect",(()=>e(cw()))),function(e,t){e.on("room_joined",(e=>t(Ny.roomJoined(e)))),e.on("new_client",(e=>t(Ny.newClient(e)))),e.on("client_left",(e=>t(Ny.clientLeft(e)))),e.on("client_kicked",(e=>t(Ny.clientKicked(e)))),e.on("client_unable_to_join",(e=>t(Ny.clientUnableToJoin(e)))),e.on("audio_enabled",(e=>t(Ny.audioEnabled(e)))),e.on("video_enabled",(e=>t(Ny.videoEnabled(e)))),e.on("audio_enable_requested",(e=>t(Ny.audioEnableRequested(e)))),e.on("client_metadata_received",(e=>t(Ny.clientMetadataReceived(e)))),e.on("chat_message",(e=>t(Ny.chatMessage(e)))),e.on("disconnect",(()=>t(Ny.disconnect()))),e.on("room_knocked",(e=>t(Ny.roomKnocked(e)))),e.on("room_left",(()=>t(Ny.roomLeft()))),e.on("room_locked",(e=>t(Ny.roomLocked(e)))),e.on("room_session_ended",(e=>t(Ny.roomSessionEnded(e)))),e.on("knocker_left",(e=>t(Ny.knockerLeft(e)))),e.on("knock_handled",(e=>t(Ny.knockHandled(e)))),e.on("screenshare_started",(e=>t(Ny.screenshareStarted(e)))),e.on("screenshare_stopped",(e=>t(Ny.screenshareStopped(e)))),e.on("cloud_recording_started",(e=>t(Ny.cloudRecordingStarted(e)))),e.on("cloud_recording_stopped",(()=>t(Ny.cloudRecordingStopped()))),e.on("streaming_stopped",(()=>t(Ny.streamingStopped()))),e.on("spotlight_added",(e=>t(Ny.spotlightAdded(e)))),e.on("spotlight_removed",(e=>t(Ny.spotlightRemoved(e)))),e.on("live_transcription_started",(e=>t(Ny.liveTranscriptionStarted(e)))),e.on("live_transcription_stopped",(e=>t(Ny.liveTranscriptionStopped(e)))),e.on("video_enable_requested",(e=>t(Ny.videoEnableRequested(e)))),e.on("breakout_group_joined",(e=>t(Ny.breakoutGroupJoined(e)))),e.on("breakout_session_updated",(e=>t(Ny.breakoutSessionUpdated(e)))),e.on("breakout_move_to_group",(()=>t(Ny.breakoutMoveToGroup()))),e.on("breakout_move_to_main",(()=>t(Ny.breakoutMoveToMain())))}(r,e),r.connect()},lw=({deviceCredentials:e})=>(t,r)=>{const i=r(),n=mw(i),s=hw(i);n&&(s||(n.emit("identify_device",{deviceCredentials:e}),t(iw())))},uw=()=>(e,t)=>{const r=t();if("connected"===fw(r)){const t=pw(r).socket;null==t||t.disconnect(),e(aw())}},pw=e=>e.signalConnection,hw=e=>e.signalConnection.deviceIdentified,fw=e=>e.signalConnection.status,mw=e=>e.signalConnection.socket;Ty([Ge(Dy,fw,((e,t)=>!(!e||!["ready","reconnecting"].includes(t))))],(({dispatch:e},t)=>{t&&e(dw())}));const gw=Ge(ew,fw,hw,(e=>e.signalConnection.isIdentifyingDevice),((e,t,r,i)=>!(!e.data||"connected"!==t||r||i)));function vw(e,{delay:t=500,edges:r}={}){let i,n=0;return(...s)=>{n+=1,r&&1===n&&e(...s),clearTimeout(i),i=setTimeout((()=>{(!r||n>1)&&e(...s),i=void 0,n=0}),t)}}Ty([gw,ew],(({dispatch:e},t,r)=>{t&&r.data&&e(lw({deviceCredentials:r.data}))})),ky({actionCreator:Ny.roomLeft,effect:(e,{dispatch:t})=>{t(uw())}}),ky({actionCreator:Ny.clientKicked,effect:(e,{dispatch:t})=>{t(uw())}});const bw=Dt({name:"localMedia",initialState:{busyDeviceIds:[],cameraEnabled:!1,currentSpeakerDeviceId:"default",devices:[],isSettingCameraDevice:!1,isSettingMicrophoneDevice:!1,isSettingSpeakerDevice:!1,isTogglingCamera:!1,lowDataMode:!1,microphoneEnabled:!1,status:"inactive",stream:void 0,isSwitchingStream:!1},reducers:{deviceBusy:(e,t)=>e.busyDeviceIds.includes(t.payload.deviceId)?e:Object.assign(Object.assign({},e),{busyDeviceIds:[...e.busyDeviceIds,t.payload.deviceId]}),toggleCameraEnabled(e,t){var r;return Object.assign(Object.assign({},e),{cameraEnabled:null!==(r=t.payload.enabled)&&void 0!==r?r:!e.cameraEnabled})},setCurrentCameraDeviceId:(e,t)=>Object.assign(Object.assign({},e),{currentCameraDeviceId:t.payload.deviceId}),toggleMicrophoneEnabled(e,t){var r;return Object.assign(Object.assign({},e),{microphoneEnabled:null!==(r=t.payload.enabled)&&void 0!==r?r:!e.microphoneEnabled})},setCurrentMicrophoneDeviceId:(e,t)=>Object.assign(Object.assign({},e),{currentMicrophoneDeviceId:t.payload.deviceId}),setCurrentSpeakerDeviceId(e,t){var r;return Object.assign(Object.assign({},e),{currentSpeakerDeviceId:null!==(r=t.payload.deviceId)&&void 0!==r?r:"default"})},toggleLowDataModeEnabled(e,t){var r;return Object.assign(Object.assign({},e),{lowDataMode:null!==(r=t.payload.enabled)&&void 0!==r?r:!e.lowDataMode})},setDevices:(e,t)=>Object.assign(Object.assign({},e),{devices:t.payload.devices}),setLocalMediaStream:(e,t)=>Object.assign(Object.assign({},e),{stream:t.payload.stream}),setLocalMediaOptions:(e,t)=>Object.assign(Object.assign({},e),{options:t.payload.options}),localMediaStopped:e=>Object.assign(Object.assign({},e),{status:"stopped",stream:void 0}),localStreamMetadataUpdated(e,t){const{audio:r,video:i}=t.payload;return Object.assign(Object.assign({},e),{currentCameraDeviceId:i.deviceId,currentMicrophoneDeviceId:r.deviceId,busyDeviceIds:e.busyDeviceIds.filter((e=>e!==r.deviceId&&e!==i.deviceId))})}},extraReducers:e=>{e.addCase(Oy,((e,t)=>Object.assign(Object.assign({},e),{options:t.payload.localMediaOptions}))),e.addCase(Mw.pending,((e,t)=>{const{audio:r,video:i}=t.meta.arg;return Object.assign(Object.assign({},e),{isSettingCameraDevice:i,isSettingMicrophoneDevice:r})})),e.addCase(Mw.fulfilled,((e,t)=>{const{audio:r,video:i}=t.meta.arg;return Object.assign(Object.assign({},e),{isSettingCameraDevice:!i&&e.isSettingCameraDevice,isSettingMicrophoneDevice:!r&&e.isSettingMicrophoneDevice})})),e.addCase(Mw.rejected,((e,t)=>{const{audio:r,video:i}=t.meta.arg;return Object.assign(Object.assign({},e),{isSettingCameraDevice:!i&&e.isSettingCameraDevice,isSettingMicrophoneDevice:!r&&e.isSettingMicrophoneDevice,cameraDeviceError:i?t.error:e.cameraDeviceError,microphoneDeviceError:r?t.error:e.microphoneDeviceError})})),e.addCase(Dw.pending,(e=>Object.assign(Object.assign({},e),{isTogglingCamera:!0}))),e.addCase(Dw.fulfilled,(e=>Object.assign(Object.assign({},e),{isTogglingCamera:!1}))),e.addCase(Lw.fulfilled,((e,t)=>Object.assign(Object.assign({},e),{devices:t.payload.devices}))),e.addCase(Aw.pending,(e=>Object.assign(Object.assign({},e),{status:"starting"}))),e.addCase(Aw.fulfilled,((e,{payload:{stream:t,onDeviceChange:r}})=>{let i,n,s=!1,o=!1;const a=t.getAudioTracks()[0],c=t.getVideoTracks()[0];return a&&(n=a.getSettings().deviceId,o=a.enabled),c&&(s=c.enabled,i=c.getSettings().deviceId),Object.assign(Object.assign({},e),{stream:t,status:"started",currentCameraDeviceId:i,currentMicrophoneDeviceId:n,cameraEnabled:s,microphoneEnabled:o,onDeviceChange:r})})),e.addCase(Aw.rejected,((e,t)=>Object.assign(Object.assign({},e),{status:"error",startError:t.error}))),e.addCase(jw.pending,(e=>Object.assign(Object.assign({},e),{isSwitchingStream:!0}))),e.addCase(jw.fulfilled,(e=>Object.assign(Object.assign({},e),{isSwitchingStream:!1}))),e.addCase(jw.rejected,(e=>Object.assign(Object.assign({},e),{isSwitchingStream:!1})))}}),{deviceBusy:yw,setCurrentCameraDeviceId:ww,setCurrentMicrophoneDeviceId:_w,setCurrentSpeakerDeviceId:Sw,toggleCameraEnabled:Cw,toggleMicrophoneEnabled:Rw,toggleLowDataModeEnabled:kw,setLocalMediaOptions:Tw,setLocalMediaStream:Pw,localMediaStopped:Ew,localStreamMetadataUpdated:Ow}=bw.actions,Dw=yy("localMedia/doToggleCamera",((e,{getState:t,rejectWithValue:r})=>Qy(void 0,void 0,void 0,(function*(){const e=t(),i=Jw(e);if(!i)return;let n=i.getVideoTracks()[0];const s=Uw(e);try{if(s)if(n)n.enabled=!0;else{const t=Qw(e),r=Fw(e);yield Ov(Object.assign(Object.assign({},t),{audioId:!1,videoId:r,type:"exact"}),{replaceStream:i}),n=i.getVideoTracks()[0]}else{if(!n)return;n.enabled=!1,n.stop(),i.removeTrack(n)}i.dispatchEvent(new CustomEvent("stopresumevideo",{detail:{track:n,enable:s}}))}catch(e){return r(e)}})))),Iw=yy("localMedia/doToggleMicrophone",((e,{getState:t})=>{var r;const i=t(),n=Jw(i);if(!n)return;const s=$w(i),o=null===(r=n.getAudioTracks())||void 0===r?void 0:r[0];o&&(o.enabled=s)})),xw=()=>(e,t)=>{const r=t();if(!Jw(r))return;const i=Fw(r),n=zw(r);e(jw({audioId:n,videoId:i}))},Mw=yy("localMedia/reactSetDevice",(({audio:e,video:t},{getState:r,rejectWithValue:i})=>Qy(void 0,void 0,void 0,(function*(){try{const i=r(),n=Jw(i);if(!n)throw new Error("No stream");const s=!!e&&zw(i),o=!!t&&Fw(i),a=Qw(i),{replacedTracks:c}=yield Ov(Object.assign(Object.assign({},a),{audioId:s,videoId:o,type:"exact"}),{replaceStream:n}),d=$w(i);n.getAudioTracks().forEach((e=>e.enabled=d));const l=Uw(i);return n.getVideoTracks().forEach((e=>e.enabled=l)),{replacedTracks:c}}catch(e){return i(e)}})))),Lw=yy("localMedia/doUpdateDeviceList",((e,{getState:t,dispatch:r,rejectWithValue:i})=>Qy(void 0,void 0,void 0,(function*(){var e,n,s,o;const a=t();let c=[],d=[];const l=Jw(a);try{c=yield navigator.mediaDevices.enumerateDevices(),d=qw(a);if(!(l&&!Xw(a)&&c&&d&&d.find((e=>e.deviceId))))return{devices:c};const{changedDevices:t,addedDevices:i}=Dv({oldDevices:d,newDevices:c});let u=null===(e=t.audioinput)||void 0===e?void 0:e.deviceId,p=null===(n=t.videoinput)||void 0===n?void 0:n.deviceId;return void 0===u&&(u=null===(s=i.audioinput)||void 0===s?void 0:s.deviceId),void 0===p&&(p=null===(o=i.videoinput)||void 0===o?void 0:o.deviceId),void 0===u&&void 0===p||r(jw({audioId:u,videoId:p})),{devices:c}}catch(e){return i(e)}})))),jw=yy("localMedia/doSwitchLocalStream",(({audioId:e,videoId:t},{dispatch:r,getState:i,rejectWithValue:n})=>Qy(void 0,void 0,void 0,(function*(){const s=i(),o=Jw(s),a=Qw(s),c=!(!t||e)||!(t||!e);if(o)try{const{replacedTracks:i}=yield Ov(Object.assign(Object.assign({},a),{audioId:void 0!==e&&e,videoId:void 0!==t&&t,type:"exact"}),{replaceStream:o}),n=e||t;return c&&n&&r(yw({deviceId:n})),{replacedTracks:i}}catch(i){console.error(i);const s=e||t;return c&&s&&r(yw({deviceId:s})),n(i)}})))),Aw=yy("localMedia/doStartLocalMedia",((e,{getState:t,dispatch:r,rejectWithValue:i})=>Qy(void 0,void 0,void 0,(function*(){const n=vw((()=>{r(Lw())}),{delay:500});if(navigator.mediaDevices&&navigator.mediaDevices.addEventListener("devicechange",n),"getTracks"in e)return Promise.resolve({stream:e,onDeviceChange:n});if(!e.audio&&!e.video)return{stream:new MediaStream,onDeviceChange:n};r(Tw({options:e}));try{yield r(Lw());const i=t(),s=Qw(i),{stream:o}=yield Ov(Object.assign(Object.assign({},s),{audioId:e.audio,videoId:e.video}));return{stream:o,onDeviceChange:n}}catch(e){return i(e)}})))),Nw=()=>(e,t)=>{const r=Jw(t()),i=Ww(t()).onDeviceChange;null==r||r.getTracks().forEach((e=>{e.stop()})),navigator.mediaDevices&&i&&navigator.mediaDevices.removeEventListener("devicechange",i),e(Ew())},Bw=e=>e.localMedia.busyDeviceIds,Fw=e=>e.localMedia.currentCameraDeviceId,zw=e=>e.localMedia.currentMicrophoneDeviceId,Vw=e=>e.localMedia.currentSpeakerDeviceId,Uw=e=>e.localMedia.cameraEnabled,$w=e=>e.localMedia.microphoneEnabled,Gw=e=>e.localMedia.lowDataMode,qw=e=>e.localMedia.devices,Hw=e=>e.localMedia.options;Ge(Hw,(e=>!!e));const Ww=e=>e.localMedia,Kw=e=>e.localMedia.status,Jw=e=>e.localMedia.stream,Xw=e=>e.localMedia.isSwitchingStream,Qw=Ge(qw,Fw,zw,Gw,((e,t,r,i)=>({devices:e,videoId:t,audioId:r,options:{disableAEC:!1,disableAGC:!1,hd:!0,lax:!1,lowDataMode:i,simulcast:!0,widescreen:!0}}))),Zw=Ge(Kw,(e=>"starting"===e)),Yw=Ge(qw,Bw,((e,t)=>e.filter((e=>"videoinput"===e.kind)).filter((e=>!t.includes(e.deviceId))))),e_=Ge(qw,Bw,((e,t)=>e.filter((e=>"audioinput"===e.kind)).filter((e=>!t.includes(e.deviceId))))),t_=Ge(qw,(e=>e.filter((e=>"audiooutput"===e.kind))));Ty([Ge(Dy,Kw,Hw,((e,t,r)=>{if(e&&["inactive","stopped"].includes(t)&&r)return r}))],(({dispatch:e},t)=>{t&&e(Aw(t))}));Ty([Ge(Dy,Kw,Hw,((e,t,r)=>!e&&"inactive"!==t&&!!r))],(({dispatch:e},t)=>{t&&e(Nw())})),ky({predicate:(e,t,r)=>{const i=$w(r),n=$w(t);return"started"===Kw(r)&&i!==n},effect:(e,{dispatch:t})=>{t(Iw())}}),ky({predicate:(e,t,r)=>{const i=Gw(r),n=Gw(t);return"started"===Kw(r)&&i!==n},effect:(e,{dispatch:t})=>{t(xw())}}),ky({predicate:(e,t,r)=>{if(t.localMedia.isTogglingCamera)return!1;const i=Uw(r),n=Uw(t);return"started"===Kw(r)&&i!==n},effect:(e,{dispatch:t})=>{t(Dw())}}),ky({predicate:(e,t,r)=>{const i=Fw(r),n=Fw(t);return"started"===Kw(r)&&i!==n},effect:(e,{dispatch:t})=>{t(Mw({audio:!1,video:!0}))}}),ky({predicate:(e,t,r)=>{const i=zw(r),n=zw(t);return"started"===Kw(r)&&i!==n},effect:(e,{dispatch:t})=>{t(Mw({audio:!0,video:!1}))}}),ky({matcher:yt(Aw.fulfilled,Lw.fulfilled,jw.fulfilled,jw.rejected),effect:(e,{dispatch:t,getState:r})=>{const i=r(),n=Jw(i),s=qw(i);if(!n)return;const o=function({audioTrack:e,videoTrack:t,devices:r,stoppedVideoTrack:i,lastAudioId:n,lastVideoId:s}){const o=e=>"live"===(null==e?void 0:e.readyState)?e:null;return t=o(t)||i,e=o(e),{video:Pv("videoinput",t,r,s),audio:Pv("audioinput",e,r,n)}}({audioTrack:n.getAudioTracks()[0],videoTrack:n.getVideoTracks()[0],devices:s});t(Ow(o))}}),ky({actionCreator:Ny.audioEnableRequested,effect:({payload:e},{dispatch:t})=>{const{enable:r}=e;r||t(Rw({enabled:!1}))}}),ky({actionCreator:Ny.videoEnableRequested,effect:({payload:e},{dispatch:t})=>{const{enable:r}=e;r||t(Cw({enabled:!1}))}}),ky({actionCreator:Ny.breakoutSessionUpdated,effect:({payload:e},{dispatch:t})=>{var r;!1===(null===(r=e.initiatedBy)||void 0===r?void 0:r.active)&&t(Rw({enabled:!1}))}});const r_=["recorder","streamer"],i_=e=>e.localParticipant,n_=e=>e.localParticipant.id,s_=e=>e.localParticipant.displayName,o_=e=>e.localParticipant.stickyReaction,a_=Ge(i_,Jw,((e,t)=>{const r={id:e.id,clientId:e.id,breakoutGroup:e.breakoutGroup,displayName:e.displayName,stream:t,isLocalClient:!0,isAudioEnabled:e.isAudioEnabled,isVideoEnabled:e.isVideoEnabled};return r_.includes(e.roleName)?null:r}));function c_({assignments:e,groups:t,startedAt:r,initiatedBy:i,breakoutStartedAt:n,breakoutEndedAt:s,breakoutNotification:o,breakoutTimerDuration:a,autoMoveToGroup:c,moveToGroupGracePeriod:d,autoMoveToMain:l,moveToMainGracePeriod:u,enforceAssignment:p,breakoutTimerSetting:h}={}){return{assignments:e||null,groups:t||null,startedAt:r?new Date(r):null,initiatedBy:i,breakoutStartedAt:n||null,breakoutEndedAt:s||null,breakoutNotification:o||null,breakoutTimerDuration:a||1800,autoMoveToGroup:c||!1,moveToGroupGracePeriod:d||10,autoMoveToMain:l||!1,moveToMainGracePeriod:u||30,enforceAssignment:p||!1,breakoutTimerSetting:h||!1}}const d_=Dt({name:"breakout",initialState:Object.assign(Object.assign({},c_()),{groupId:null}),reducers:{},extraReducers:e=>{e.addCase(Ny.roomJoined,((e,t)=>t.payload.breakout?Object.assign(Object.assign({},e),c_(t.payload.breakout)):e)),e.addCase(Ny.breakoutSessionUpdated,((e,t)=>Object.assign(Object.assign({},e),c_(t.payload)))),e.addCase(Ny.breakoutGroupJoined,((e,t)=>{var r;return(null===(r=t.meta)||void 0===r?void 0:r.localParticipantId)!==t.payload.clientId?e:Object.assign(Object.assign({},e),{groupId:t.payload.group})}))}}),l_=e=>(t,r)=>{const i=r(),{socket:n}=pw(i);null==n||n.emit("join_breakout_group",{group:e.group})},u_=e=>e.breakout,p_=e=>!!e.breakout.startedAt,h_=e=>e.breakout.assignments,f_=Ge(u_,(e=>e.localParticipant.breakoutGroup),((e,t)=>e.groupId||t||"")),m_=Ge(u_,f_,((e,t)=>{var r;const i=null===(r=e.groups)||void 0===r?void 0:r[t];return i?{id:t,name:i}:null}));ky({actionCreator:Ny.breakoutMoveToGroup,effect:(e,{dispatch:t,getState:r})=>{const i=r(),n=i_(i).breakoutGroupAssigned;n&&t(l_({group:n}))}}),ky({actionCreator:Ny.breakoutMoveToMain,effect:(e,{dispatch:t})=>{t(l_({group:""}))}}),ky({actionCreator:Ny.breakoutSessionUpdated,effect:({payload:e},{dispatch:t,getState:r})=>{var i;const n=r(),s=u_(n).autoMoveToMain;!1===(null===(i=e.initiatedBy)||void 0===i?void 0:i.active)&&(s||t(l_({group:""})))}});const g_=Dt({name:"chat",initialState:{chatMessages:[]},reducers:{},extraReducers(e){e.addCase(Ny.chatMessage,((e,t)=>{const r={senderId:t.payload.senderId,timestamp:t.payload.timestamp,text:t.payload.text};return Object.assign(Object.assign({},e),{chatMessages:[...e.chatMessages,r]})}))}}),v_=_y((e=>(t,r)=>{const i=r(),n=pw(i).socket,s=f_(i);null==n||n.emit("chat_message",Object.assign(Object.assign({text:e.text},s&&{breakoutGroup:s}),e.isBroadcast&&{broadcast:!0}))})),b_=Dt({name:"cloudRecording",initialState:{isRecording:!1,error:null,startedAt:void 0},reducers:{recordingRequestStarted:e=>Object.assign(Object.assign({},e),{status:"requested"})},extraReducers:e=>{e.addCase(Ny.cloudRecordingStopped,(e=>Object.assign(Object.assign({},e),{isRecording:!1,status:void 0}))),e.addCase(Ny.cloudRecordingStarted,((e,t)=>{const{payload:r}=t;return r.error?Object.assign(Object.assign({},e),{isRecording:!1,status:"error",error:r.error}):e})),e.addCase(Ny.newClient,((e,{payload:t})=>{var r;const{client:i}=t;return"recorder"===(null===(r=i.role)||void 0===r?void 0:r.roleName)?Object.assign(Object.assign({},e),{isRecording:!0,status:"recording",startedAt:i.startedCloudRecordingAt?new Date(i.startedCloudRecordingAt).getTime():(new Date).getTime()}):e}))}}),{recordingRequestStarted:y_}=b_.actions,w_=_y((()=>(e,t)=>{const r=t(),i=pw(r).socket,n=S_(r);n&&["recording","requested"].includes(n)||(null==i||i.emit("start_recording",{recording:"cloud"}),e(y_()))})),__=_y((()=>(e,t)=>{const r=t(),i=pw(r).socket;null==i||i.emit("stop_recording")})),S_=e=>e.cloudRecording.status,C_=e=>e.roomConnection.status;function R_(e){return Qe(`rtcConnection/event/${e}`)}const k_={rtcManagerCreated:R_("rtcManagerCreated"),rtcManagerDestroyed:R_("rtcManagerDestroyed"),streamAdded:R_("streamAdded"),clientConnectionStatusChanged:R_("clientConnectionStatusChanged")};function T_(e,t=!1){const{streams:r,role:i,breakoutGroup:n}=e,s=Xy(e,["streams","role","breakoutGroup"]);return Object.assign(Object.assign({},s),{stream:null,streams:r.map((e=>({id:e,state:t?"new_accept":"to_accept"}))),isLocalParticipant:!1,roleName:(null==i?void 0:i.roleName)||"none",presentationStream:null,breakoutGroup:n||null,newJoiner:t})}function P_(e,t){const r=e.remoteParticipants.findIndex((e=>e.id===t));return{index:r,participant:e.remoteParticipants[r]}}function E_(e,t,r){const{participant:i,index:n}=P_(e,t);return i?Object.assign(Object.assign({},e),{remoteParticipants:[...e.remoteParticipants.slice(0,n),Object.assign(Object.assign({},i),r),...e.remoteParticipants.slice(n+1)]}):(console.error(`Did not find client for update ${t}`),e)}function O_(e,t,r,i){const{participant:n}=P_(e,t);if(!n)return console.error(`No client ${t} found to update stream ${r} ${i}`),e;const s=n.streams.findIndex((e=>e.id===r)),o=[...n.streams];return o[s]=Object.assign(Object.assign({},o[s]),{state:i}),E_(e,t,{streams:o})}function D_(e,t,r){const{participant:i}=P_(e,t);return!i||i.streams.find((e=>e.id===r))?(console.warn(`No participant ${t} or stream ${r} already exists`),e):E_(e,t,{streams:[...i.streams,{id:r,state:"to_accept"}]})}const I_=Dt({name:"remoteParticipants",initialState:{remoteParticipants:[]},reducers:{streamStatusUpdated:(e,t)=>{let r=e;for(const{clientId:e,streamId:i,state:n}of t.payload)r=O_(r,e,i,n);return r},participantStreamAdded:(e,t)=>{const{clientId:r,stream:i}=t.payload;return E_(e,r,{stream:i})},participantStreamIdAdded:(e,t)=>{const{clientId:r,streamId:i}=t.payload;return D_(e,r,i)}},extraReducers:e=>{e.addCase(Ny.roomJoined,((e,t)=>{var r;if(!(null===(r=t.payload)||void 0===r?void 0:r.room))return e;const i=t.payload.selfId,{clients:n}=t.payload.room;return Object.assign(Object.assign({},e),{remoteParticipants:n.filter((e=>e.id!==i)).map((e=>T_(e)))})})),e.addCase(k_.streamAdded,((e,t)=>function(e,t){const{clientId:r,stream:i,streamType:n}=t;let{streamId:s}=t;const{participant:o}=P_(e,r);if(!o)return console.error(`Did not find client ${r} for adding stream`),e;const a=e.remoteParticipants;s||(s=i.id);const c=a.find((e=>e.id===r));if(!c)return e;const d=c.streams.find((e=>e.id===s));return c.stream&&(c.stream.id===s||c.stream.inboundId===s)||!c.stream&&"webcam"===n||!c.stream&&!n&&!d?E_(e,r,{stream:i}):E_(e,r,{presentationStream:i})}(e,t.payload))),e.addCase(Ny.newClient,((e,t)=>{const{client:r}=t.payload;return function(e,t){const{participant:r}=P_(e,t.id);return r?(console.warn(`Client already existing ${t.id}. Ignoring`),e):Object.assign(Object.assign({},e),{remoteParticipants:[...e.remoteParticipants,t]})}(e,T_(r,!0))})),e.addCase(Ny.clientLeft,((e,t)=>{const{clientId:r}=t.payload;return function(e,t){return Object.assign(Object.assign({},e),{remoteParticipants:e.remoteParticipants.filter((e=>e.id!==t))})}(e,r)})),e.addCase(Ny.audioEnabled,((e,t)=>{const{clientId:r,isAudioEnabled:i}=t.payload;return E_(e,r,{isAudioEnabled:i})})),e.addCase(Ny.videoEnabled,((e,t)=>{const{clientId:r,isVideoEnabled:i}=t.payload;return E_(e,r,{isVideoEnabled:i})})),e.addCase(Ny.clientMetadataReceived,((e,t)=>{const{error:r,payload:i}=t.payload;if(r||!i)return console.warn(r||"Client metadata error received"),e;const{clientId:n,displayName:s,stickyReaction:o}=i;return E_(e,n,{displayName:s,stickyReaction:o})})),e.addCase(Ny.breakoutGroupJoined,((e,t)=>{const{clientId:r,group:i}=t.payload;return E_(e,r,{breakoutGroup:i||null})})),e.addCase(Ny.screenshareStarted,((e,t)=>{const{clientId:r,streamId:i}=t.payload;return D_(e,r,i)})),e.addCase(Ny.screenshareStopped,((e,t)=>{const{clientId:r,streamId:i}=t.payload;return function(e,t,r){var i,n;const{participant:s}=P_(e,t);if(!s)return console.error(`No participant ${t} found to remove stream ${r}`),e;const o=s.stream&&s.stream.id,a=(null===(i=s.presentationStream)||void 0===i?void 0:i.inboundId)||(null===(n=s.presentationStream)||void 0===n?void 0:n.id),c=s.streams.findIndex((e=>e.id===r));return E_(e,t,Object.assign(Object.assign({streams:s.streams.filter(((e,t)=>t!==c))},o===r&&{stream:null}),a===r&&{presentationStream:null}))}(e,r,i)}))}}),{participantStreamAdded:x_,participantStreamIdAdded:M_,streamStatusUpdated:L_}=I_.actions,j_=Cy((e=>Gy(e)),(e=>(t,r)=>{const i=r(),n=Ky(i);if(e.enable&&!n)return void console.warn("Not authorized to perform this action");const s=pw(i).socket;null==s||s.emit("request_audio_enable",e)})),A_=Cy((e=>qy(e)),(e=>(t,r)=>{const i=r(),n=pw(i).socket;null==n||n.emit("request_video_enable",e)})),N_=e=>e.remoteParticipants.remoteParticipants,B_=Ge(N_,(e=>e.filter((e=>!r_.includes(e.roleName)))));Ge(N_,(e=>e.length+1));const F_=Ge(B_,i_,((e,t)=>r_.includes(t.roleName)?e.length:e.length+1)),z_=Dt({name:"localScreenshare",initialState:{status:"inactive",stream:null,error:null},reducers:{stopScreenshare:(e,t)=>Object.assign(Object.assign({},e),{status:"inactive",stream:null})},extraReducers:e=>{e.addCase(U_.pending,(e=>Object.assign(Object.assign({},e),{status:"starting"}))),e.addCase(U_.fulfilled,((e,{payload:{stream:t}})=>Object.assign(Object.assign({},e),{status:"active",stream:t}))),e.addCase(U_.rejected,((e,{payload:t})=>Object.assign(Object.assign({},e),{error:t,status:"inactive",stream:null})))}}),{stopScreenshare:V_}=z_.actions,U_=Sy("localScreenshare/doStartScreenshare",((e,{dispatch:t,getState:r,rejectWithValue:i})=>Qy(void 0,void 0,void 0,(function*(){var e;try{const i=r(),n=G_(i);if(n)return{stream:n};const s=yield navigator.mediaDevices.getDisplayMedia(),o=()=>{t($_())};return"oninactive"in s?s.addEventListener("inactive",o):null===(e=s.getVideoTracks()[0])||void 0===e||e.addEventListener("ended",o),{stream:s}}catch(e){return i(e)}})))),$_=_y((()=>(e,t)=>{const r=t(),i=G_(r);i&&(i.getTracks().forEach((e=>e.stop())),e(V_({stream:i})))})),G_=e=>e.localScreenshare.stream;function q_(e){return"recorder"===e.roleName}ky({actionCreator:Ew,effect:(e,{getState:t})=>{const r=t(),i=G_(r);i&&(null==i||i.getTracks().forEach((e=>{e.stop()})))}});const H_=Dt({name:"room",initialState:{isLocked:!1},reducers:{},extraReducers:e=>{e.addCase(Ny.roomJoined,((e,t)=>{const{error:r,isLocked:i}=t.payload;return r?e:Object.assign(Object.assign({},e),{isLocked:Boolean(i)})})),e.addCase(Ny.roomLocked,((e,t)=>{const{isLocked:r}=t.payload;return Object.assign(Object.assign({},e),{isLocked:Boolean(r)})}))}}),W_=wy((e=>$y(e)),(e=>(t,r)=>{const i=r(),{socket:n}=pw(i);null==n||n.emit("set_lock",{locked:e.locked})})),K_=wy((e=>Hy(e)),(e=>(t,r)=>{const i=r(),{socket:n}=pw(i);null==n||n.emit("kick_client",{clientId:e.clientId,reasonId:"kick"})})),J_=wy((e=>Wy(e)),(e=>(t,r)=>{const i=r(),n=N_(i).map((e=>e.id));if(n.length){const{socket:e}=pw(i);null==e||e.emit("kick_client",{clientIds:n,reasonId:"end-meeting"})}e.stayBehind||t(Ey())})),X_=Ge(G_,i_,B_,((e,t,r)=>{const i=[];e&&i.push({id:e.id||"local-screenshare",participantId:"local",hasAudioTrack:e.getTracks().some((e=>"audio"===e.kind)),breakoutGroup:t.breakoutGroup,stream:e,isLocal:!0});for(const e of r)e.presentationStream&&i.push({id:e.presentationStream.id||`pres-${e.id}`,participantId:e.id,hasAudioTrack:e.presentationStream.getTracks().some((e=>"audio"===e.kind)),breakoutGroup:e.breakoutGroup,stream:e.presentationStream,isLocal:!1});return i})),Q_=Ge(G_,i_,B_,f_,h_,((e,t,r,i,n)=>{const s=[];if(e){const r=!!e.getAudioTracks().length;s.push({clientId:t.id,displayName:"Your screenshare",id:"local-screenshare",isAudioEnabled:r,isLocalClient:!0,isPresentation:!0,isVideoEnabled:!0,stream:e,breakoutGroup:i||""})}for(const e of r){if("streamer"===e.roleName||q_(e))continue;const{presentationStream:t}=e,r=Xy(e,["presentationStream"]),i=e.displayName||"Guest",o=t&&t.active,a="pres-"+e.id,c=e.stream&&e.stream.active,d=e.isVideoEnabled;s.push(Object.assign(Object.assign(Object.assign({},r),{breakoutGroupAssigned:(null==n?void 0:n[e.deviceId])||"",clientId:e.id,displayName:i,hasActivePresentation:!!o}),e.isVideoEnabled?{isVideoEnabled:d}:{})),o&&s.push(Object.assign(Object.assign(Object.assign({},r),{clientId:e.id,stream:e.presentationStream,displayName:`Screenshare (${i})`,id:a,isPresentation:!0,isVideoEnabled:!0}),c&&{isRecording:null}))}return s})),Z_=Ge(a_,Q_,((e,t)=>[...e?[e]:[],...t])),Y_=Ge(Z_,p_,f_,((e,t,r)=>t&&r?e.filter((e=>e.isLocalClient||e.breakoutGroup===(r||"")||e.breakoutGroupAssigned&&e.breakoutGroupAssigned===r)):e)),eS=Ge(Z_,p_,(e=>e.breakout.groups),((e,t,r)=>{if(!t||!r)return[];return[{clients:e.filter((e=>!e.breakoutGroup||""===e.breakoutGroup)),group:{id:"",name:""}},...Object.entries(r).map((([t,r])=>({clients:e.filter((e=>!e.isPresentation&&e.breakoutGroup===t)),group:{id:t,name:r}})))]}));function tS({isPresentation:e,stream:t}){var r,i;return e?null!==(i=null!==(r=null==t?void 0:t.outboundId)&&void 0!==r?r:null==t?void 0:t.inboundId)&&void 0!==i?i:null==t?void 0:t.id:"0"}function rS(e,t){return e.find((e=>e.clientId===t.clientId&&e.streamId===t.streamId))?e:e.concat(t)}const iS=Dt({name:"spotlights",initialState:{sorted:[]},reducers:{addSpotlight(e,t){const{clientId:r,streamId:i}=t.payload;return Object.assign(Object.assign({},e),{sorted:rS(e.sorted,{clientId:r,streamId:i})})},removeSpotlight(e,t){const{clientId:r,streamId:i}=t.payload;return Object.assign(Object.assign({},e),{sorted:e.sorted.filter((e=>!(e.clientId===r&&e.streamId===i)))})}},extraReducers:e=>{e.addCase(Ny.roomJoined,((e,t)=>{if(!t.payload.room)return e;const{spotlights:r}=t.payload.room;return Object.assign(Object.assign({},e),{sorted:r})})),e.addCase(Ny.spotlightAdded,((e,t)=>{const{clientId:r,streamId:i}=t.payload;return Object.assign(Object.assign({},e),{sorted:rS(e.sorted,{clientId:r,streamId:i})})})),e.addCase(Ny.spotlightRemoved,((e,t)=>{const{clientId:r,streamId:i}=t.payload;return Object.assign(Object.assign({},e),{sorted:e.sorted.filter((e=>!(e.clientId===r&&e.streamId===i)))})})),e.addMatcher(yt(Ny.clientKicked,Ny.clientLeft),((e,t)=>{const{clientId:r}=t.payload;return Object.assign(Object.assign({},e),{sorted:e.sorted.filter((e=>e.clientId!==r))})}))}}),{addSpotlight:nS,removeSpotlight:sS}=iS.actions,oS=wy((e=>Jy(e)),(({id:e})=>(t,r)=>{const i=r(),n=Z_(i).find((t=>t.clientId===e));if(!n)return;const{socket:s}=pw(i),o=tS(n),a={clientId:n.id,streamId:null!=o?o:"0"};null==s||s.emit("add_spotlight",a)})),aS=wy((e=>Jy(e)),(({id:e})=>(t,r)=>{const i=r(),n=Z_(i).find((t=>t.clientId===e));if(!n)return;const{socket:s}=pw(i),o=tS(n),a={clientId:n.id,streamId:null!=o?o:"0"};null==s||s.emit("remove_spotlight",a)})),cS=e=>e.spotlights.sorted;Ge(i_,cS,((e,t)=>function({spotlights:e,isPresentation:t,clientId:r,stream:i}){return!!e.find((e=>{const n=tS({isPresentation:t,stream:i});return e.clientId===r&&e.streamId===n}))}({clientId:e.id,stream:e.stream,spotlights:t})));const dS=Ge(Z_,cS,((e,t)=>function(e,t){return e.reduce(((e,r)=>{const i=t.find((e=>r.clientId===e.clientId&&r.streamId===tS(e)));return i&&!e.includes(i)&&e.push(i),e}),[])}(t,e)));ky({actionCreator:U_.fulfilled,effect:({payload:e},{getState:t,dispatch:r})=>{const{stream:i}=e,n=t(),s=i_(n);s&&r(nS({clientId:s.id,streamId:i.id}))}}),ky({actionCreator:V_,effect:({payload:e},{getState:t,dispatch:r})=>{const{stream:i}=e,n=t(),s=i_(n);s&&r(sS({clientId:s.id,streamId:i.id}))}});const lS=e=>({emit:(t,r)=>{"rtc_manager_created"===t?e(kS(r)):"stream_added"===t?e(k_.streamAdded(r)):"rtc_manager_destroyed"===t?e(vS()):"client_connection_status_changed"===t&&e(k_.clientConnectionStatusChanged(r))}}),uS={dispatcherCreated:!1,error:null,isCreatingDispatcher:!1,reportedStreamResolutions:{},rtcManager:null,rtcManagerDispatcher:null,rtcManagerInitialized:!1,status:"inactive",isAcceptingStreams:!1},pS=Dt({name:"rtcConnection",initialState:uS,reducers:{isAcceptingStreams:(e,t)=>Object.assign(Object.assign({},e),{isAcceptingStreams:t.payload}),resolutionReported:(e,t)=>{const{streamId:r,width:i,height:n}=t.payload;return Object.assign(Object.assign({},e),{reportedStreamResolutions:Object.assign(Object.assign({},e.reportedStreamResolutions),{[r]:{width:i,height:n}})})},rtcDisconnected:()=>Object.assign({},uS),rtcDispatcherCreated:(e,t)=>Object.assign(Object.assign({},e),{dispatcherCreated:!0,rtcManagerDispatcher:t.payload}),rtcManagerCreated:(e,t)=>Object.assign(Object.assign({},e),{rtcManager:t.payload,status:"ready"}),rtcManagerDestroyed:e=>Object.assign(Object.assign({},e),{rtcManager:null}),rtcManagerInitialized:e=>Object.assign(Object.assign({},e),{rtcManagerInitialized:!0}),rtcClientConnectionStatusChanged:{reducer:e=>e,prepare:e=>({payload:{},meta:{localParticipantId:e.localParticipantId}})}},extraReducers:e=>{e.addCase(cw,(e=>Object.assign(Object.assign({},e),{status:"reconnecting"}))),e.addCase(Ny.roomJoined,(e=>Object.assign(Object.assign({},e),{status:"reconnecting"===e.status?"ready":e.status})))}}),{resolutionReported:hS,rtcDispatcherCreated:fS,rtcDisconnected:mS,rtcManagerCreated:gS,rtcManagerDestroyed:vS,rtcManagerInitialized:bS,isAcceptingStreams:yS,rtcClientConnectionStatusChanged:wS}=pS.actions,_S=()=>(e,t)=>{const r=t(),i=pw(r).socket,n=PS(r).rtcManagerDispatcher,s=Uw(r),o=$w(r),a=(e=>e.app.isNodeSdk)(r);if(n||!i)return;const c={getMediaConstraints:()=>({audio:o,video:s}),deferrable:e=>function({client:e,breakoutCurrentId:t}){return!(!e||(t||!e.breakoutGroup)&&(e.isAudioEnabled||e.isVideoEnabled))}({client:B_(t()).find((t=>t.id===e)),breakoutCurrentId:f_(t())||""})},d=new iv({emitter:lS(e),serverSocket:i,webrtcProvider:c,features:{isNodeSdk:a,lowDataModeEnabled:!1,sfuServerOverrideHost:void 0,turnServerOverrideHost:void 0,useOnlyTURN:void 0,vp9On:!1,h264On:!1,simulcastScreenshareOn:!1}});e(fS(d))},SS=()=>(e,t)=>{const{rtcManager:r}=PS(t());r&&r.disconnectAll(),e(mS())},CS=e=>(t,r)=>{var i;t(yS(!0));const n=r(),s=PS(n).rtcManager,o=N_(n);if(!s)throw new Error("No rtc manager");const a=p_(n),c=null===(i=s.shouldAcceptStreamsFromBothSides)||void 0===i?void 0:i.call(s),d=[];for(const{clientId:t,streamId:r,state:i}of e){if(o.find((e=>e.id===t))){if("to_accept"===i||"new_accept"===i&&c||"old_accept"===i&&!c)s.acceptNewStream({streamId:"0"===r?t:r,clientId:t,shouldAddLocalVideo:"0"===r,activeBreakout:a});else if("new_accept"===i||"old_accept"===i);else if("to_unaccept"===i)null==s||s.disconnect("0"===r?t:r,a);else if("done_accept"!==i)continue;d.push({clientId:t,streamId:r,state:i.replace(/to_|new_|old_/,"done_")})}}t(L_(d)),t(yS(!1))},RS=({streamId:e,width:t,height:r})=>(i,n)=>{const{reportedStreamResolutions:s,rtcManager:o}=PS(n()),a=Jw(n());if(!o||(null==a?void 0:a.id)===e)return;const c=s[e];c&&c.width===t&&c.height===r||o.updateStreamResolution(e,null,{width:t||1,height:r||1}),i(hS({streamId:e,width:t,height:r}))},kS=e=>t=>{const{rtcManager:r}=e;t(gS(r))},TS=()=>(e,t)=>{const r=Jw(t()),i=PS(t()).rtcManager,n=Uw(t()),s=$w(t());r&&i&&i.addNewStream("0",r,!s,!n),e(bS())},PS=e=>e.rtcConnection,ES=e=>e.rtcConnection.rtcManagerInitialized,OS=e=>e.rtcConnection.rtcManager,DS=e=>e.rtcConnection.status;ky({actionCreator:Mw.fulfilled,effect:({payload:e},{getState:t})=>{const{replacedTracks:r}=e,{rtcManager:i}=PS(t()),n=Jw(t());null==r||r.forEach((e=>{((e,t)=>{const r=null==n?void 0:n.getTracks().find((t=>t.kind===e));r&&(null==i||i.replaceTrack(t,r))})(e.kind,e)}))}}),ky({actionCreator:U_.fulfilled,effect:({payload:e},{getState:t})=>{const{stream:r}=e,{rtcManager:i}=PS(t());null==i||i.addNewStream(r.id,r,!1,!0)}}),ky({actionCreator:Ey,effect:(e,{getState:t})=>{const r=OS(t());null==r||r.rtcStatsDisconnect()}}),ky({actionCreator:V_,effect:({payload:e},{getState:t})=>{const{stream:r}=e,{rtcManager:i}=PS(t());null==i||i.removeStream(r.id,r,null)}}),ky({actionCreator:jw.fulfilled,effect:({payload:e},{getState:t})=>{var r;const i=Jw(t()),{rtcManager:n}=PS(t());if(i&&n){const t=(e,t)=>{const r=i.getTracks().find((t=>t.kind===e));return r&&n.replaceTrack(t,r)};null===(r=null==e?void 0:e.replacedTracks)||void 0===r||r.forEach((e=>{t(e.kind,e)}))}}}),ky({actionCreator:k_.clientConnectionStatusChanged,effect:(e,{dispatch:t,getState:r})=>{const i=i_(r());t(wS({localParticipantId:i.id}))}});Ty([Ge(DS,Dy,(e=>e.rtcConnection.dispatcherCreated),(e=>e.rtcConnection.isCreatingDispatcher),mw,((e,t,r,i,n)=>!(!t||"inactive"!==e||r||i||!n)))],(({dispatch:e},t)=>{t&&e(_S())}));const IS=Ge(OS,ES,Kw,((e,t,r)=>!("started"!==r||!e||t)));Ty([IS],(({dispatch:e},t)=>{t&&e(TS())}));Ty([Ge(DS,Dy,((e,t)=>!t&&!["inactive","disconnected"].includes(e)))],(({dispatch:e},t)=>{t&&e(SS())}));const xS=Ge(DS,N_,f_,cS,(e=>e.app.ignoreBreakoutGroups),((e,t,r,i,n)=>{if("ready"!==e)return[];const s=[];for(const e of t){const{streams:t,id:o,newJoiner:a}=e,c=i.find((t=>t.clientId===e.id&&"0"===t.streamId));for(let i=0;i<t.length;i++){let d=t[i].id,l=t[i].state;if((null==t?void 0:t.length)>1&&"0"===t[1].id&&(0===i?(d=t[1].id,l=t[1].state):1===i&&(d=t[0].id,l=t[0].state)),!e.breakoutGroup&&!r||e.breakoutGroup===r||""===e.breakoutGroup&&c||n){if("done_accept"===l)continue;s.push({clientId:o,streamId:d,state:(a&&"0"===d?"new":"to")+"_accept"})}else{if("done_unaccept"===l)continue;s.push({clientId:o,streamId:d,state:"to_unaccept"})}}}return s}));Ty([xS,e=>e.rtcConnection.isAcceptingStreams],(({dispatch:e},t,r)=>{0<t.length&&!r&&e(CS(t))}));const MS={running:!1},LS=Dt({name:"connectionMonitor",initialState:MS,reducers:{connectionMonitorStarted:(e,t)=>Object.assign(Object.assign({},e),{running:!0,stopCallbackFunction:t.payload.stopIssueSubscription}),connectionMonitorStopped:()=>Object.assign({},MS)}}),{connectionMonitorStarted:jS,connectionMonitorStopped:AS}=LS.actions,NS=()=>(e,t)=>{var r;r=()=>{const e=t(),r=Z_(e).map((e=>{var t,r;return{id:e.id,clientId:e.clientId,isLocalClient:e.isLocalClient,audio:{enabled:e.isAudioEnabled,track:null===(t=e.stream)||void 0===t?void 0:t.getAudioTracks()[0]},video:{enabled:e.isVideoEnabled,track:null===(r=e.stream)||void 0===r?void 0:r.getVideoTracks()[0]},isPresentation:e.isPresentation}}));return r},Lf.getClients=r;const i=bv({onUpdatedIssues:e=>{var r;const i=t(),n=OS(i);if(!n)return;let s=0,o=0,a=0,c=0;Object.entries(e.aggregated.metrics).forEach((([e,t])=>{/loc.*packetloss/.test(e)&&(s=Math.max(s,t.curMax)),/rem.*packetloss/.test(e)&&(o=Math.max(o,t.curMax)),/loc.*bitrate/.test(e)&&(a+=t.curSum),/rem.*bitrate/.test(e)&&(c+=t.curSum)})),n.sendStatsCustomEvent("insightsStats",{ls:Math.round(1e3*s)/1e3,lr:Math.round(1e3*o)/1e3,bs:Math.round(a),br:Math.round(c),cpu:null===(r=e.aggregated.metrics["global-cpu-pressure"])||void 0===r?void 0:r.curSum,_time:Date.now()})}});e(jS({stopIssueSubscription:i.stop}))},BS=()=>(e,t)=>{const r=t(),i=zS(r);i&&i(),e(AS())},FS=e=>e.connectionMonitor.running,zS=e=>e.connectionMonitor.stopCallbackFunction,VS=Ge(C_,FS,((e,t)=>!t&&"connected"===e)),US=Ge(C_,FS,((e,t)=>!(!t||!["kicked","left"].includes(e))));Ty([VS],(({dispatch:e},t)=>{t&&e(NS())})),Ty([US],(({dispatch:e},t)=>{t&&e(BS())}));const $S=Dt({name:"localParticipant",initialState:{displayName:"",id:"",breakoutGroup:null,breakoutGroupAssigned:"",isAudioEnabled:!0,isVideoEnabled:!0,isLocalParticipant:!0,stream:void 0,isScreenSharing:!1,roleName:"none",clientClaim:void 0,stickyReaction:void 0,isDialIn:!1},reducers:{setDisplayName:(e,t)=>Object.assign(Object.assign({},e),{displayName:t.payload.displayName}),setBreakoutGroupAssigned:(e,t)=>Object.assign(Object.assign({},e),{breakoutGroupAssigned:t.payload.breakoutGroupAssigned})},extraReducers:e=>{e.addCase(Oy,((e,t)=>Object.assign(Object.assign({},e),{displayName:t.payload.displayName}))),e.addCase(WS.fulfilled,((e,t)=>Object.assign(Object.assign({},e),{isAudioEnabled:t.payload}))),e.addCase(KS.fulfilled,((e,t)=>Object.assign(Object.assign({},e),{isVideoEnabled:t.payload}))),e.addCase(JS.fulfilled,((e,t)=>Object.assign(Object.assign({},e),{stickyReaction:t.payload}))),e.addCase(Ny.roomJoined,((e,t)=>{var r,i;const n=null===(i=null===(r=t.payload)||void 0===r?void 0:r.room)||void 0===i?void 0:i.clients.find((e=>{var r;return e.id===(null===(r=t.payload)||void 0===r?void 0:r.selfId)}));return Object.assign(Object.assign({},e),{id:t.payload.selfId,roleName:(null==n?void 0:n.role.roleName)||"none",clientClaim:t.payload.clientClaim,breakoutGroup:(null==n?void 0:n.breakoutGroup)||null})})),e.addCase(Ny.breakoutGroupJoined,((e,t)=>{var r,i;return(null===(r=t.payload)||void 0===r?void 0:r.clientId)!==e.id?e:Object.assign(Object.assign({},e),{breakoutGroup:null===(i=t.payload)||void 0===i?void 0:i.group})}))}}),{setDisplayName:GS,setBreakoutGroupAssigned:qS}=$S.actions,HS=_y((e=>(t,r)=>{const i=r(),n=pw(i).socket;null==n||n.emit("send_client_metadata",{type:"UserData",payload:{displayName:e.displayName}}),t(GS({displayName:e.displayName}))})),WS=Sy("localParticipant/doEnableAudio",((e,{dispatch:t,getState:r})=>Qy(void 0,void 0,void 0,(function*(){const i=r(),n=pw(i).socket;return null==n||n.emit("enable_audio",{enabled:e.enabled}),e.enabled&&t(JS({enabled:!1})),e.enabled})))),KS=Sy("localParticipant/doEnableVideo",((e,{getState:t})=>Qy(void 0,void 0,void 0,(function*(){const r=t(),i=pw(r).socket;return null==i||i.emit("enable_video",{enabled:e.enabled}),e.enabled})))),JS=Sy("localParticipant/doSetLocalStickyReaction",((e,{getState:t,rejectWithValue:r})=>Qy(void 0,void 0,void 0,(function*(){var i;const n=t(),s=o_(n),o=Boolean(s),a=null!==(i=e.enabled)&&void 0!==i?i:!o;if(a===o)return r(s);return a?{reaction:"✋",timestamp:(new Date).toISOString()}:null})))),XS=_y((()=>(e,t)=>{const r=t(),i=pw(r).socket,n={displayName:s_(r),stickyReaction:o_(r)};null==i||i.emit("send_client_metadata",{type:"UserData",payload:n})}));ky({actionCreator:Cw,effect:({payload:e},{dispatch:t,getState:r})=>{const{enabled:i}=e,{isVideoEnabled:n}=i_(r());"connected"===C_(r())&&t(KS({enabled:i||!n}))}}),ky({actionCreator:Rw,effect:({payload:e},{dispatch:t,getState:r})=>{const{enabled:i}=e,{isAudioEnabled:n}=i_(r());"connected"===C_(r())&&t(WS({enabled:i||!n}))}}),Ty([s_,o_,C_],(({dispatch:e},t,r,i)=>{"connected"===i&&e(XS())})),Ty([h_,tw,i_],(({dispatch:e},t,r,i)=>{const n=(null==t?void 0:t[r||""])||"";i.breakoutGroupAssigned!==n&&e(qS({breakoutGroupAssigned:n}))}));function QS(e){return Object.assign(Object.assign({},e),{timestamp:Date.now()})}const ZS=Dt({name:"notifications",initialState:{emitter:new Np,events:[]},reducers:{addNotification:(e,t)=>Object.assign(Object.assign({},e),{events:[...e.events,Object.assign({},t.payload)]}),doClearNotifications:e=>Object.assign(Object.assign({},e),{events:[]})}});ZS.actions;const YS=e=>(t,r)=>{t(ZS.actions.addNotification(e));const i=r(),n=eC(i);n.emit(e.type,e),n.emit("*",e)},eC=e=>e.notifications.emitter;ky({actionCreator:Ny.chatMessage,effect:({payload:e},{dispatch:t,getState:r})=>{const i=r(),n=B_(i).find((({id:t})=>t===e.senderId));n?t(YS(QS({type:"chatMessageReceived",message:`${n.displayName} says: ${e.text}`,props:{client:n,chatMessage:{senderId:e.senderId,timestamp:e.timestamp,text:e.text}}}))):console.warn("Could not find remote client that sent chat message")}}),ky({actionCreator:Ny.audioEnableRequested,effect:({payload:e},{dispatch:t,getState:r})=>{const{enable:i,requestedByClientId:n}=e,s=r(),o=B_(s).find((({id:e})=>e===n));o?t(YS(QS({type:i?"requestAudioEnable":"requestAudioDisable",message:i?`${o.displayName} has requested for you to speak`:`${o.displayName} has muted your microphone`,props:{client:o,enable:i}}))):console.warn("Could not find remote client that requested a local audio change")}}),ky({actionCreator:Ny.videoEnableRequested,effect:({payload:e},{dispatch:t,getState:r})=>{const{enable:i,requestedByClientId:n}=e,s=r(),o=B_(s).find((({id:e})=>e===n));o?t(YS(QS({type:i?"requestVideoEnable":"requestVideoDisable",message:i?`${o.displayName} has requested for you to start video`:`${o.displayName} has stopped your video`,props:{client:o,enable:i}}))):console.warn("Could not find remote client that requested a local video change")}}),ky({actionCreator:Ny.clientMetadataReceived,effect:(e,{dispatch:t,getOriginalState:r,getState:i})=>{var n;const{error:s,payload:o}=e.payload;if(s||!o)return;const{clientId:a,stickyReaction:c}=o,d=i();if(!Ky(d))return;const l=B_(d).find((({id:e})=>e===a));if(!l)return void console.warn("Could not find remote client that provided updated metadata");const u=r(),p=B_(u).find((({id:e})=>e===a));(c||(null==p?void 0:p.stickyReaction))&&(null==c?void 0:c.timestamp)!==(null===(n=null==p?void 0:p.stickyReaction)||void 0===n?void 0:n.timestamp)&&t(YS(QS({type:c?"remoteHandRaised":"remoteHandLowered",message:`${l.displayName} ${c?"raised":"lowered"} their hand`,props:{client:l,stickyReaction:c}})))}}),Ty([fw],(({dispatch:e,getState:t},r)=>{const i=t(),n=C_(i);["left","kicked"].includes(n)||("disconnected"===r?e(YS(QS({type:"signalTrouble",message:"Network connection lost. Trying to reconnect you...",props:{}}))):"connected"===r&&e(YS(QS({type:"signalOk",message:"Network connection available",props:{}}))))})),ky({actionCreator:Ny.clientUnableToJoin,effect:(e,{dispatch:t})=>{var r;"room_full"===(null===(r=e.payload)||void 0===r?void 0:r.error)&&t(YS(QS({type:"clientUnableToJoinFullRoom",message:"Someone tried to join but the room is full and at capacity.",props:{}})))}});const tC=Dt({initialState:{data:null,isFetching:!1,error:null},name:"organization",reducers:{},extraReducers:e=>{e.addCase(rC.pending,(e=>Object.assign(Object.assign({},e),{isFetching:!0}))),e.addCase(rC.fulfilled,((e,t)=>t.payload?Object.assign(Object.assign({},e),{isFetching:!1,data:t.payload}):Object.assign(Object.assign({},e),{isFetching:!0}))),e.addCase(rC.rejected,(e=>Object.assign(Object.assign({},e),{isFetching:!1,error:!0})))}}),rC=yy("organization/doOrganizationFetch",((e,{extra:t,getState:r})=>Qy(void 0,void 0,void 0,(function*(){try{const e=r().app.roomUrl,i=yield t.services.fetchOrganizationFromRoomUrl(e||"");if(!i)throw new Error("Invalid room url");return i}catch(e){console.error(e)}})))),iC=e=>{var t;return null===(t=e.organization.data)||void 0===t?void 0:t.organizationId};Ty([Ge(Dy,(e=>e.organization),ew,((e,t,r)=>!(!e||t.data||t.isFetching||t.error||r.isFetching)))],(({dispatch:e},t)=>{t&&e(rC())}));const nC=Dt({initialState:{session:null,status:"ready",error:null},name:"roomConnection",reducers:{connectionStatusChanged:(e,t)=>Object.assign(Object.assign({},e),{status:t.payload})},extraReducers:e=>{e.addCase(Ny.roomJoined,((e,t)=>{var r,i;const{error:n,isLocked:s}=t.payload;return"room_locked"===n&&s?Object.assign(Object.assign({},e),{status:"room_locked"}):n?Object.assign(Object.assign({},e),{status:"disconnected",error:n}):Object.assign(Object.assign({},e),{status:"connected",session:null!==(i=null===(r=t.payload.room)||void 0===r?void 0:r.session)&&void 0!==i?i:null})})),e.addCase(Ny.disconnect,(e=>["kicked","left"].includes(e.status)?Object.assign({},e):Object.assign(Object.assign({},e),{status:"disconnected"}))),e.addCase(Ny.newClient,((e,t)=>{var r,i;return Object.assign(Object.assign({},e),{session:null!==(i=null===(r=t.payload.room)||void 0===r?void 0:r.session)&&void 0!==i?i:null})})),e.addCase(Ny.roomSessionEnded,((e,t)=>{var r;return(null===(r=e.session)||void 0===r?void 0:r.id)!==t.payload.roomSessionId?e:Object.assign(Object.assign({},e),{session:null})})),e.addCase(Ny.clientKicked,(e=>Object.assign(Object.assign({},e),{status:"kicked"}))),e.addCase(Ny.roomLeft,(e=>Object.assign(Object.assign({},e),{status:"left"}))),e.addCase(cw,(e=>Object.assign(Object.assign({},e),{status:"reconnecting"})))}}),{connectionStatusChanged:sC}=nC.actions,oC=()=>(e,t)=>{const r=t(),i=pw(r).socket,n=xy(r),s=Vy(r),o=My(r),a=Iy(r),c=Ly(r),d=jy(r),l=iC(r);"room_locked"===C_(r)?(null==i||i.emit("knock_room",{avatarUrl:null,config:{isAudioEnabled:!0,isVideoEnabled:!0},deviceCapabilities:{canScreenshare:!0},displayName:o,isCoLocated:!1,isDialIn:a,isDevicePermissionDenied:!1,kickFromOtherRooms:!1,organizationId:l,roomKey:s,roomName:n,userAgent:c,externalId:d}),e(sC("knocking"))):console.warn("Room is not locked, knock aborted")},aC=()=>(e,t)=>{const r=t(),i=pw(r).socket,n=xy(r),s=Vy(r),o=My(r),a=Ly(r),c=jy(r),d=Iy(r),l=iC(r),u=Uw(t()),p=$w(t()),h=(e=>e.localParticipant.clientClaim)(t());null==i||i.emit("join_room",Object.assign({avatarUrl:null,config:{isAudioEnabled:p,isVideoEnabled:u},deviceCapabilities:{canScreenshare:!0},displayName:o,isCoLocated:!1,isDialIn:d,isDevicePermissionDenied:!1,kickFromOtherRooms:!1,organizationId:l,roomKey:s,roomName:n,userAgent:a,externalId:c},h&&{clientClaim:h})),e(sC("connecting"))};Ty([Ge([Dy,iC,C_,hw,Kw,e=>e.roomConnection.error],((e,t,r,i,n,s)=>!(!(e&&"started"===n&&i&&t&&["ready","reconnecting","disconnected"].includes(r))||s)))],(({dispatch:e},t)=>{t&&e(aC())})),ky({actionCreator:Ny.knockHandled,effect:({payload:e},{dispatch:t,getState:r})=>{const{clientId:i,resolution:n}=e,s=r();i===n_(s)&&("accepted"===n?(t(zy(e.metadata.roomKey)),t(aC())):"rejected"===n&&t(sC("knock_rejected")))}}),ky({actionCreator:Ey,effect:(e,{dispatch:t,getState:r})=>{const i=r();if("connected"===C_(i)){const e=pw(i).socket;null==e||e.emit("leave_room"),t(sC("leaving"))}else uw()}});const cC={audioEnabled:{actions:[WS.fulfilled],rtcEventName:"audioEnabled",getValue:e=>$w(e),getOutput:e=>({enabled:e})},videoEnabled:{actions:[KS.fulfilled],rtcEventName:"videoEnabled",getValue:e=>Uw(e),getOutput:e=>({enabled:e})},localStream:{actions:[Mw.fulfilled],rtcEventName:"localStream",getValue:e=>{var t;return null===(t=Jw(e))||void 0===t?void 0:t.getTracks().map((e=>({id:e.id,kind:e.kind,label:e.label})))},getOutput:e=>({stream:e})},localScreenshareStream:{actions:[U_.fulfilled],rtcEventName:"localScreenshareStream",getValue:e=>{var t;return null===(t=G_(e))||void 0===t?void 0:t.getTracks().map((e=>({id:e.id,kind:e.kind,label:e.label})))},getOutput:e=>({tracks:e})},localScreenshareStreamStopped:{actions:[V_],rtcEventName:"localScreenshareStream",getValue:()=>()=>null,getOutput:()=>({})},displayName:{actions:[GS],rtcEventName:"displayName",getValue:e=>My(e),getOutput:e=>({displayName:e})},clientId:{actions:null,rtcEventName:"clientId",getValue:e=>n_(e),getOutput:e=>({clientId:e})},deviceId:{actions:null,rtcEventName:"deviceId",getValue:e=>tw(e),getOutput:e=>({deviceId:e})},externalId:{actions:null,rtcEventName:"externalId",getValue:e=>jy(e),getOutput:e=>({externalId:e})},organizationId:{actions:null,rtcEventName:"organizationId",getValue:e=>iC(e),getOutput:e=>({organizationId:e})},signalConnectionStatus:{actions:null,rtcEventName:"signalConnectionStatus",getValue:e=>fw(e),getOutput:e=>({status:e})},roomSessionId:{actions:[Ny.newClient,Ny.roomJoined,Ny.roomSessionEnded,Ny.clientLeft],rtcEventName:"roomSessionId",getValue:e=>(e=>{var t;return null===(t=e.roomConnection.session)||void 0===t?void 0:t.id})(e),getOutput:e=>({roomSessionId:e})},rtcConnectionStatus:{actions:null,rtcEventName:"rtcConnectionStatus",getValue:e=>DS(e),getOutput:e=>({status:e})},userRole:{actions:null,rtcEventName:"userRole",getValue:e=>Uy(e),getOutput:e=>({userRole:e})}},dC=Object.values(cC).flatMap((({actions:e})=>{var t;return null!==(t=null==e?void 0:e.map((e=>e)))&&void 0!==t?t:null})).filter((e=>null!==e)),lC=e=>"object"==typeof e?JSON.stringify(e):e,uC=Dt({initialState:{reportedValues:{}},name:"rtcAnalytics",reducers:{updateReportedValues:(e,t)=>Object.assign(Object.assign({},e),{reportedValues:Object.assign(Object.assign({},e.reportedValues),{[t.payload.rtcEventName]:t.payload.value})})}}),pC=()=>(e,t)=>{const r=t(),i=PS(r).rtcManager;i&&(i.sendStatsCustomEvent("insightsStats",{_time:Date.now(),ls:0,lr:0,bs:0,br:0,cpu:0}),Object.values(cC).forEach((({rtcEventName:t,getValue:n,getOutput:s})=>{var o;const a=n(r),c=Object.assign(Object.assign({},s(a)),{_time:Date.now()}),d=lC(a);(null===(o=r.rtcAnalytics.reportedValues)||void 0===o?void 0:o[t])!==d&&(i.sendStatsCustomEvent(t,c),e(hC({rtcEventName:t,value:a})))})))},{updateReportedValues:hC}=uC.actions;ky({matcher:yt(...dC),effect:({type:e},{getState:t,dispatch:r})=>{var i;const n=t(),s=PS(n).rtcManager;if(!s)return;const o=Object.values(cC).find((({actions:t})=>null==t?void 0:t.map((e=>e.type)).includes(e)));if(!o)return;const{getValue:a,getOutput:c,rtcEventName:d}=o,l=a(n),u=lC(l),p=Object.assign(Object.assign({},c(l)),{_time:Date.now()});(null===(i=n.rtcAnalytics.reportedValues)||void 0===i?void 0:i[d])!==u&&(s.sendStatsCustomEvent(d,p),r(hC({rtcEventName:d,value:l})))}}),Ty([ES],(({dispatch:e},t)=>{t&&e(pC())}));const fC=Dt({name:"streaming",initialState:{isStreaming:!1,error:null,startedAt:void 0},reducers:{doHandleStreamingStarted:e=>Object.assign(Object.assign({},e),{isStreaming:!0,error:null,startedAt:(new Date).getTime()}),doHandleStreamingStopped:e=>Object.assign(Object.assign({},e),{isStreaming:!1})}});fC.actions;const mC=Dt({name:"waitingParticipants",initialState:{waitingParticipants:[]},reducers:{},extraReducers:e=>{e.addCase(Ny.roomJoined,((e,{payload:t})=>{var r;return(null===(r=t.room)||void 0===r?void 0:r.knockers.length)?Object.assign(Object.assign({},e),{waitingParticipants:t.room.knockers.map((e=>({id:e.clientId,displayName:e.displayName})))}):e})),e.addCase(Ny.roomKnocked,((e,t)=>{const{clientId:r,displayName:i}=t.payload;return Object.assign(Object.assign({},e),{waitingParticipants:[...e.waitingParticipants,{id:r,displayName:i}]})})),e.addCase(Ny.knockerLeft,((e,t)=>{const{clientId:r}=t.payload;return Object.assign(Object.assign({},e),{waitingParticipants:e.waitingParticipants.filter((e=>e.id!==r))})}))}}),gC=_y((e=>(t,r)=>{const{participantId:i}=e,n=r(),s=mw(n);null==s||s.emit("handle_knock",{action:"accept",clientId:i,response:{}})})),vC=_y((e=>(t,r)=>{const{participantId:i}=e,n=r(),s=mw(n);null==s||s.emit("handle_knock",{action:"reject",clientId:i,response:{}})}));const bC=null===!1&&!1,yC=B({app:Py.reducer,authorization:Fy.reducer,breakout:d_.reducer,chat:g_.reducer,cloudRecording:b_.reducer,connectionMonitor:LS.reducer,deviceCredentials:Zy.reducer,localMedia:bw.reducer,localParticipant:$S.reducer,localScreenshare:z_.reducer,notifications:ZS.reducer,organization:tC.reducer,remoteParticipants:I_.reducer,room:H_.reducer,roomConnection:nC.reducer,rtcAnalytics:uC.reducer,rtcConnection:pS.reducer,signalConnection:rw.reducer,spotlights:iS.reducer,streaming:fC.reducer,waitingParticipants:mC.reducer}),wC=(e,t)=>{var r;if(Oy.match(t)){const i={app:Object.assign(Object.assign({},Py.getInitialState()),{initialConfig:null===(r=null==e?void 0:e.app)||void 0===r?void 0:r.initialConfig}),localMedia:Object.assign(Object.assign({},bw.getInitialState()),null==e?void 0:e.localMedia)};return yC(i,t)}return yC(e,t)};class _C{constructor(e={}){this.data=void 0===e.data?{}:e.data,this.headers=e.headers||{},this.status=e.status||200,this.statusText=e.statusText||"OK",this.url=e.url||null}}function SC(e,t){return dg.ok(e,`${t} is required`),e}function CC(e,t){return dg.ok("boolean"==typeof e,`${t}<boolean> is required`),e}function RC(e,t){return dg.ok("number"==typeof e,`${t}<number> is required`),e}function kC(e,t){return dg.ok("string"==typeof e,`${t}<string> is required`),e}function TC(e,t,r){const i=r||t.name[0].toLowerCase()+t.name.substring(1);return dg.ok(e instanceof t,`${i}<${t.name}> is required`),e}function PC(e,t){return dg.ok(Array.isArray(e),`${t}<array> is required`),e}function EC(e,t){if(null==e||"object"!=typeof e||Array.isArray(e))throw new Error(`${t} must be a record. ${JSON.stringify(e)}`);return e}function OC(e,t,r){kC(t,"name"),function(e,t,r,i){kC(r,"name");const n=i||`${r} must be null or of type ${t}`;dg.ok(null===e||typeof e===t,n)}(e,"string",t,r)}function DC({baseUrl:e,url:t}){return e?e+t:t}class IC{constructor({baseUrl:e}){kC(e,"baseUrl"),this._baseUrl=e}_requestAxios(e,t){const r=Object.assign({},t,{url:e,baseURL:this._baseUrl});return by.request(r)}request(e,t){return kC(e,"url"),dg.ok("/"===e[0],'url<String> only accepts relative URLs beginning with "/".'),dg.ok(t,"options are required"),this._requestAxios(e,t).then((e=>{const{data:t,headers:r,status:i,statusText:n,config:s}=e,o=s&&s.url?DC({baseUrl:s.baseURL,url:s.url}):null;return new _C({data:t,headers:r,status:i,statusText:n,url:o})})).catch((e=>{const t=e.response;if(!t)throw new Error("Could not make the request.");const{data:r,headers:i,status:n,statusText:s,config:o}=t,a=o&&o.url?DC({baseUrl:o.baseURL,url:o.url}):null;return Promise.reject(new _C({data:r,headers:i,status:n,statusText:s,url:a}))}))}}class xC{constructor({httpClient:e}){dg.ok(e,"httpClient is required"),this._httpClient=e}static dataToFormData(e){dg.ok(e,"data is required");const t=new FormData;return Object.keys(e).forEach((r=>{const i=e[r];t.append(r,i)})),t}request(e,t={}){const r=Object.assign(t.headers||{},{"Content-Type":void 0});return this._httpClient.request(e,Object.assign(t,{headers:r,transformRequest:xC.dataToFormData}))}}let MC;MC="object"==typeof window?window.btoa||Mv:"object"==typeof global&&global.btoa||Mv;const LC=()=>Promise.resolve(null);class jC{constructor({httpClient:e,fetchDeviceCredentials:t}){this._httpClient=e,this._fetchDeviceCredentials=t}request(e,t){return this._fetchDeviceCredentials().then((r=>{const i=Object.assign({},t.headers,function(e){if(e&&e.credentials){const t=`${e.credentials.uuid}:${e.hmac}`;return{Authorization:`Basic ${MC(t)}`}}return{}}(r),{"X-Appearin-Device-Platform":"web"}),n=Object.assign({},t,{headers:i});return this._httpClient.request(e,n)}))}}class AC{constructor({baseUrl:e="https://api.appearin.net",fetchDeviceCredentials:t=LC}={}){this.authenticatedHttpClient=new jC({httpClient:new IC({baseUrl:e}),fetchDeviceCredentials:t}),this.authenticatedFormDataHttpClient=new xC({httpClient:this.authenticatedHttpClient})}request(e,t){return kC(e,"url"),dg.ok("/"===e[0],'url<String> only accepts relative URLs beginning with "/".'),dg.ok(t,"options are required"),this.authenticatedHttpClient.request(e,t)}requestMultipart(e,t){return kC(e,"url"),dg.ok("/"===e[0],'url<String> only accepts relative URLs beginning with "/".'),dg.ok(t,"options are required"),this.authenticatedFormDataHttpClient.request(e,t)}}function NC(e,t){return kC(EC(e,"data")[t],t)}const BC=(FC=NC,(e,t)=>{const r=EC(e,"data")[t];return null==r?null:FC(e,t)});var FC;function zC(e,t,r){return function(e,t){return PC(EC(e,"data")[t],t)}(e,t).map((e=>r(e)))}class VC{constructor(e,t,r=void 0){this.credentials={uuid:e},this.hmac=t,this.userId=r}toJson(){return Object.assign({credentials:this.credentials,hmac:this.hmac},this.userId&&{userId:this.userId})}static fromJson(e){return new VC(NC(function(e,t){const r=EC(e,"data")[t];return void 0===r?null:r}(e,"credentials"),"uuid"),NC(e,"hmac"),BC(e,"userId")||void 0)}}class UC{constructor({apiClient:e}){this._apiClient=e}getCredentials(){return this._apiClient.request("/devices",{method:"post"}).then((({data:e})=>VC.fromJson(e))).catch((e=>{if(e.response&&404===e.response.status)return null;throw e}))}}class $C{constructor(e,t){this._key=e,this._chromeStorage=t}loadOrDefault(e){return new Promise((t=>{this._chromeStorage.get(this._key,(r=>{t(r[this._key]||e)}))}))}save(e){return new Promise((t=>{this._chromeStorage.set({[this._key]:e},(()=>{t()}))}))}}class GC{constructor(e,t){SC(t,"localStorage"),this._key=kC(e,"key"),this._localStorage=t}loadOrDefault(e){try{const t=this._localStorage.getItem(this._key);if(t)try{return Promise.resolve(JSON.parse(t))}catch(e){}return Promise.resolve(e)}catch(t){return console.warn("Error getting access to storage. Are cookies blocked?",t),Promise.resolve(e)}}save(e){try{return this._localStorage.setItem(this._key,JSON.stringify(e)),Promise.resolve()}catch(e){return console.warn("Error getting access to storage. Are cookies blocked?",e),Promise.reject(e)}}}let qC;try{qC=self.localStorage}catch(GO){qC={getItem:()=>{},key:()=>{},setItem:()=>{},removeItem:()=>{},hasOwnProperty:()=>{},length:0}}var HC=qC;const WC="credentials_saved";class KC extends Np{constructor({deviceService:e,credentialsStore:t}){super(),this._deviceService=e,this._credentialsStore=t}static create({baseUrl:e,storeName:t="CredentialsStorage",storeType:r="localStorage"}){const i=new UC({apiClient:new AC({baseUrl:e})});let n=null;if("localStorage"===r)n=new GC(t,HC);else{if("chromeStorage"!==r)throw new Error(`Unknown store type: ${r}`);n=new $C(t,window.chrome.storage.local)}return new KC({deviceService:i,credentialsStore:n})}_fetchNewCredentialsFromApi(){const e=this._credentialsStore;return new Promise((t=>{const r=()=>{this._deviceService.getCredentials().then((r=>e.save(r?r.toJson():null).then((()=>t(r))))).catch((()=>{setTimeout(r,2e3)}))};r()}))}getCurrentCredentials(){return this._credentialsStore.loadOrDefault(null).then((e=>e?VC.fromJson(e):null))}getCredentials(){return this.credentialsPromise||(this.credentialsPromise=this.getCurrentCredentials().then((e=>e||this._fetchNewCredentialsFromApi()))),this.credentialsPromise}saveCredentials(e){return this.credentialsPromise=void 0,this._credentialsStore.save(e.toJson()).then((()=>(this.emit(WC,e),e)))}setUserId(e){return this.getCurrentCredentials().then((t=>{t||console.error("Illegal state: no credentials to set user id for.");if(null===t||t.userId!==e)return this._credentialsStore.save(Object.assign({},null==t?void 0:t.toJson(),{userId:e}))})).then((()=>{}))}}class JC{constructor({isExhausted:e,renewsAt:t,totalMinutesLimit:r,totalMinutesUsed:i}){this.isExhausted=e,this.renewsAt=t,this.totalMinutesLimit=r,this.totalMinutesUsed=i}static fromJson(e){return new JC({isExhausted:CC(e.isExhausted,"isExhausted"),renewsAt:new Date(kC(e.renewsAt,"renewsAt")),totalMinutesLimit:RC(e.totalMinutesLimit,"totalMinutesLimit"),totalMinutesUsed:RC(e.totalMinutesUsed,"totalMinutesUsed")})}}class XC{constructor({basePlanId:e,embeddedFreeTierStatus:t,isDeactivated:r,isOnTrial:i,onTrialUntil:n,trialStatus:s}){this.basePlanId=e,this.isDeactivated=r,this.isOnTrial=i,this.onTrialUntil=n||null,this.trialStatus=s||null,this.embeddedFreeTierStatus=t||null}static fromJson(e){return new XC({basePlanId:"string"==typeof e.basePlanId?e.basePlanId:null,isDeactivated:CC(e.isDeactivated,"isDeactivated"),isOnTrial:CC(e.isOnTrial,"isOnTrial"),onTrialUntil:"string"==typeof e.onTrialUntil?new Date(e.onTrialUntil):null,trialStatus:"string"==typeof e.trialStatus?e.trialStatus:null,embeddedFreeTierStatus:e.embeddedFreeTierStatus?JC.fromJson(e.embeddedFreeTierStatus):null})}}function QC(e){return null!=e}function ZC(e={}){return{maxNumberOfInvitationsAndUsers:QC(null==e?void 0:e.maxNumberOfInvitationsAndUsers)?Number(null==e?void 0:e.maxNumberOfInvitationsAndUsers):null,maxNumberOfClaimedRooms:QC(null==e?void 0:e.maxNumberOfClaimedRooms)?Number(null==e?void 0:e.maxNumberOfClaimedRooms):null,maxRoomLimitPerOrganization:QC(null==e?void 0:e.maxRoomLimitPerOrganization)?Number(null==e?void 0:e.maxRoomLimitPerOrganization):null,trialMinutesLimit:QC(null==e?void 0:e.trialMinutesLimit)?Number(null==e?void 0:e.trialMinutesLimit):null,includedUnits:QC(null==e?void 0:e.includedUnits)?Number(null==e?void 0:e.includedUnits):null}}class YC{constructor(e){this.logoImageUrl=null,this.roomBackgroundImageUrl=null,this.roomBackgroundThumbnailUrl=null,this.roomKnockPageBackgroundImageUrl=null,this.roomKnockPageBackgroundThumbnailUrl=null,this.preferences=null,this.onboardingSurvey=null,this.type=null,TC(e,Object,"properties"),kC(e.organizationId,"organizationId"),kC(e.organizationName,"organizationName"),kC(e.subdomain,"subdomain"),TC(e.permissions,Object,"permissions"),TC(e.limits,Object,"limits"),this.organizationId=e.organizationId,this.organizationName=e.organizationName,this.subdomain=e.subdomain,this.permissions=e.permissions,this.limits=e.limits,this.account=e.account?new XC(e.account):null,this.logoImageUrl=e.logoImageUrl,this.roomBackgroundImageUrl=e.roomBackgroundImageUrl,this.roomBackgroundThumbnailUrl=e.roomBackgroundThumbnailUrl,this.roomKnockPageBackgroundImageUrl=e.roomKnockPageBackgroundImageUrl,this.roomKnockPageBackgroundThumbnailUrl=e.roomKnockPageBackgroundThumbnailUrl,this.preferences=e.preferences,this.onboardingSurvey=e.onboardingSurvey,this.type=e.type}static fromJson(e){const t=TC(e,Object,"data"),r=(null==t?void 0:t.preferences)||{},i=(null==t?void 0:t.onboardingSurvey)||null,n=TC(t.permissions,Object,"permissions");return new YC({organizationId:kC(t.organizationId,"organizationId"),organizationName:kC(t.organizationName,"organizationName"),subdomain:kC(t.subdomain,"subdomain"),permissions:n,limits:ZC(TC(t.limits,Object,"limits")),account:t.account?XC.fromJson(t.account):null,logoImageUrl:"string"==typeof t.logoImageUrl?t.logoImageUrl:null,roomBackgroundImageUrl:"string"==typeof t.roomBackgroundImageUrl?t.roomBackgroundImageUrl:null,roomBackgroundThumbnailUrl:"string"==typeof t.roomBackgroundThumbnailUrl?t.roomBackgroundThumbnailUrl:null,roomKnockPageBackgroundImageUrl:"string"==typeof t.roomKnockPageBackgroundImageUrl?t.roomKnockPageBackgroundImageUrl:null,roomKnockPageBackgroundThumbnailUrl:"string"==typeof t.roomKnockPageBackgroundThumbnailUrl?t.roomKnockPageBackgroundThumbnailUrl:null,preferences:r,onboardingSurvey:i,type:"string"==typeof t.type?t.type:null})}}YC.GLOBAL_ORGANIZATION_ID="1";class eR{constructor({apiClient:e}){this._apiClient=e}createOrganization({organizationName:e,subdomain:t,owner:r}){const{displayName:i,consents:n}=r||{},s="email"in r?{value:r.email,verificationCode:kC(r.verificationCode,"owner.verificationCode")}:null,o="idToken"in r?r.idToken:null;if(kC(t,"subdomain"),kC(e,"organizationName"),kC(i,"owner.displayName"),dg.ok(s||o,"owner.email or owner.idToken is required"),n){PC(n,"consents");for(const{consentRevisionId:e,action:t}of n)kC(e,"consentRevisionId"),OC(t,"action")}return this._apiClient.request("/organizations",{method:"POST",data:{organizationName:e,type:"private",subdomain:t,owner:Object.assign(Object.assign(Object.assign(Object.assign({},s&&{email:s}),o&&{idToken:o}),n&&{consents:n}),{displayName:i})}}).then((({data:e})=>NC(e,"organizationId")))}getOrganizationBySubdomain(e){return kC(e,"subdomain"),this._apiClient.request(`/organization-subdomains/${encodeURIComponent(e)}/?fields=permissions,account,onboardingSurvey`,{method:"GET"}).then((({data:e})=>YC.fromJson(e))).catch((e=>{if(e instanceof _C){if(404===e.status)return null;throw new Error(e.statusText)}throw e}))}getOrganizationByOrganizationId(e){return kC(e,"organizationId"),this._apiClient.request(`/organizations/${encodeURIComponent(e)}?fields=permissions,account`,{method:"GET"}).then((({data:e})=>YC.fromJson(e))).catch((e=>{if(e instanceof _C){if(404===e.status)return null;throw new Error(e.statusText)}throw e}))}getOrganizationsByContactPoint(e){const{code:t}=e,r="email"in e?e.email:null,i="phoneNumber"in e?e.phoneNumber:null;dg.ok((r||i)&&!(r&&i),"either email or phoneNumber is required"),kC(t,"code");const n=r?{type:"email",value:r}:{type:"phoneNumber",value:i};return this._apiClient.request("/organization-queries",{method:"POST",data:{contactPoint:n,code:t}}).then((({data:e})=>zC(e,"organizations",(e=>YC.fromJson(e)))))}getOrganizationsByIdToken({idToken:e}){return kC(e,"idToken"),this._apiClient.request("/organization-queries",{method:"POST",data:{idToken:e}}).then((({data:e})=>zC(e,"organizations",(e=>YC.fromJson(Object.assign({permissions:{},limits:{}},EC(e,"organization")))))))}getOrganizationsByLoggedInUser(){return this._apiClient.request("/user/organizations",{method:"GET"}).then((({data:e})=>zC(e,"organizations",(e=>YC.fromJson(Object.assign({permissions:{},limits:{}},EC(e,"organization")))))))}getSubdomainAvailability(e){return kC(e,"subdomain"),this._apiClient.request(`/organization-subdomains/${encodeURIComponent(e)}/availability`,{method:"GET"}).then((({data:e})=>(TC(e,Object,"data"),{status:NC(e,"status")})))}updatePreferences({organizationId:e,preferences:t}){return SC(e,"organizationId"),SC(t,"preferences"),this._apiClient.request(`/organizations/${encodeURIComponent(e)}/preferences`,{method:"PATCH",data:t}).then((()=>{}))}deleteOrganization({organizationId:e}){return SC(e,"organizationId"),this._apiClient.request(`/organizations/${encodeURIComponent(e)}`,{method:"DELETE"}).then((()=>{}))}}class tR{constructor({organizationService:e,subdomain:t}){this._organizationService=e,this._subdomain=t,this._organizationPromise=null}initOrganization(){return this.fetchOrganization().then((()=>{}))}fetchOrganization(){return this._organizationPromise||(this._organizationPromise=this._organizationService.getOrganizationBySubdomain(this._subdomain)),this._organizationPromise}}const rR="https://api.whereby.dev";const iR=s.createContext(null);P(iR);const nR=function(e=v){const t=e===v?O:P(e),r=()=>t().dispatch;return Object.assign(r,{withTypes:()=>r}),r}(iR),sR=function(e=v){const t=e===v?y:b(e),r=(e,r={})=>{const{equalityFn:i=_,devModeChecks:n={}}="function"==typeof r?{equalityFn:r}:r;if(!e)throw new Error("You must pass a selector to useSelector");if("function"!=typeof e)throw new Error("You must pass a function as a selector to useSelector");if("function"!=typeof i)throw new Error("You must pass a function as an equality function to useSelector");const{store:s,subscription:o,getServerState:a,stabilityCheck:c,identityFunctionCheck:d}=t(),l=h.useRef(!0),u=h.useCallback({[e.name](t){const r=e(t);{const{identityFunctionCheck:s,stabilityCheck:o}={stabilityCheck:c,identityFunctionCheck:d,...n};if("always"===o||"once"===o&&l.current){const n=e(t);if(!i(r,n)){let i;try{throw new Error}catch(e){({stack:i}=e)}console.warn("Selector "+(e.name||"unknown")+" returned a different result when called with the same parameters. This can lead to unnecessary rerenders.\nSelectors that return a new reference (such as an object or an array) should be memoized: https://redux.js.org/usage/deriving-data-selectors#optimizing-selectors-with-memoization",{state:t,selected:r,selected2:n,stack:i})}}if(("always"===s||"once"===s&&l.current)&&r===t){let t;try{throw new Error}catch(e){({stack:t}=e)}console.warn("Selector "+(e.name||"unknown")+" returned the root state when called. This can lead to unnecessary rerenders.\nSelectors that return the entire state are almost certainly a mistake, as they will cause a rerender whenever *anything* in state changes.",{stack:t})}l.current&&(l.current=!1)}return r}}[e.name],[e,c,n.stabilityCheck]),p=w(o.addNestedSub,s.getState,a||s.getState,u,i);return h.useDebugValue(p),p};return Object.assign(r,{withTypes:()=>r}),r}(iR);var oR=function(){return oR=Object.assign||function(e){for(var t,r=1,i=arguments.length;r<i;r++)for(var n in t=arguments[r])Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e},oR.apply(this,arguments)};function aR(e,t){var r={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(r[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(i=Object.getOwnPropertySymbols(e);n<i.length;n++)t.indexOf(i[n])<0&&Object.prototype.propertyIsEnumerable.call(e,i[n])&&(r[i[n]]=e[i[n]])}return r}"function"==typeof SuppressedError&&SuppressedError;const cR=nR.withTypes(),dR=sR.withTypes(),lR=s.forwardRef(((e,t)=>{var{muted:r,mirror:i=!1,stream:n,onVideoResize:o}=e,a=aR(e,["muted","mirror","stream","onVideoResize"]);const c=cR(),d=dR(Vw),l=s.useRef(null),u=s.useRef(null);return s.useImperativeHandle(t,(()=>Object.assign(l.current,{captureAspectRatio:()=>{if(!l.current)return null;const e=l.current.videoHeight,t=l.current.videoWidth;return t&&e&&t+e>20?t/e:null}}))),s.useEffect((()=>{if(!l.current)return;const e=new ResizeObserver(vw((()=>{if(l.current&&(null==n?void 0:n.id)){const e=l.current.clientWidth,t=l.current.clientHeight;c(RS({streamId:n.id,width:e,height:t})),o&&o({width:e,height:t,stream:n})}}),{delay:1e3,edges:!0}));return e.observe(l.current),()=>{e.disconnect()}}),[n]),s.useEffect((()=>{l.current&&(l.current.srcObject!==n&&(l.current.srcObject=n),l.current.muted!==r&&(l.current.muted=Boolean(r)))}),[r,n,l]),s.useEffect((()=>{u.current&&!r&&n&&d&&(u.current.srcObject!==n&&(u.current.srcObject=n),u.current.setSinkId&&u.current.setSinkId(d))}),[n,u,d,r]),s.createElement(s.Fragment,null,s.createElement("video",Object.assign({ref:l,autoPlay:!0,playsInline:!0},a,{style:Object.assign({transform:i?"scaleX(-1)":"none",width:"100%",height:"100%"},a.style)})),s.createElement("audio",{ref:u,autoPlay:!0,playsInline:!0}))}));lR.displayName="VideoView";const uR=Ge((e=>e.chat.chatMessages),(e=>e.cloudRecording),m_,p_,eS,Y_,i_,Jw,B_,X_,C_,(e=>e.streaming),(e=>e.waitingParticipants.waitingParticipants),eC,dS,((e,t,r,i,n,s,o,a,c,d,l,u,p,h,f)=>({chatMessages:e,cloudRecording:t.isRecording?{status:"recording"}:void 0,breakout:{isActive:i,currentGroup:r,groupedParticipants:n,participantsInCurrentGroup:s},connectionStatus:l,events:h,liveStream:u.isStreaming?{status:"streaming",startedAt:u.startedAt}:void 0,localScreenshareStatus:o.isScreenSharing?"active":void 0,localParticipant:Object.assign(Object.assign({},o),{stream:a}),remoteParticipants:c,screenshares:d,waitingParticipants:p,spotlightedParticipants:f}))),pR={localMediaOptions:{audio:!0,video:!0}};const hR=Ge((e=>e.localMedia.cameraDeviceError),Yw,Fw,zw,Vw,(e=>e.localMedia.isSettingCameraDevice),(e=>e.localMedia.isSettingMicrophoneDevice),Zw,Jw,(e=>e.localMedia.microphoneDeviceError),e_,t_,(e=>e.localMedia.startError),((e,t,r,i,n,s,o,a,c,d,l,u,p)=>({cameraDeviceError:e,cameraDevices:t,currentCameraDeviceId:r,currentMicrophoneDeviceId:i,currentSpeakerDeviceId:n,isSettingCameraDevice:s,isSettingMicrophoneDevice:o,isStarting:a,localStream:c,microphoneDeviceError:d,microphoneDevices:l,speakerDevices:u,startError:p})));var fR={MIN_WINDOW_HEIGHT:320,MIN_WINDOW_WIDTH:320,DESKTOP_BREAKPOINT:1025,TABLET_BREAKPOINT:750,PHONE_BREAKPOINT:500,TOP_TOOLBAR_HEIGHT:56,BOTTOM_TOOLBAR_HEIGHT:82,SIDEBAR_WIDTH:375,VIDEO_CONTROLS_MIN_WIDTH:420,ROOM_FOOTER_MIN_WIDTH:600,FLOATING_VIDEO_CONTROLS_BOTTOM_MARGIN:20,WATERMARK_BAR_HEIGHT:32,BREAKOUT_STAGE_BACKDROP_HEADER_HEIGHT:28,BREAKOUT_STAGE_BACKDROP_FOOTER_HEIGHT:56,SUBGRID_EMPTY_STAGE_MAX_WIDTH:800,GROUPS_CELL_MARGIN:8,GROUPS_CELL_PADDING:12,GROUPS_CELL_NAV_HEIGHT:56,GROUPS_CELL_AVATAR_WRAPPER_BOTTOM_MARGIN:8,GROUPS_CELL_AVATAR_GRID_GAP:8,GROUPS_CELL_MIN_WIDTH:360,GROUPS_CELL_MAX_WIDTH:600,GROUPS_ROW_HEIGHT:72,GROUPS_ROW_GAP:1,FOLDABLE_SCREEN_STAGE_PADDING:8};function mR({top:e=0,left:t=0}={}){return{top:e,left:t}}function gR({width:e=0,height:t=0}={}){return{width:Math.max(e,0),height:Math.max(t,0)}}function vR({top:e=0,left:t=0,width:r=0,height:i=0}={}){return{bounds:gR({width:r,height:i}),origin:mR({top:e,left:t})}}function bR({top:e=0,left:t=0,bottom:r=0,right:i=0}={}){return{top:e,left:t,bottom:r,right:i}}function yR(e){return!!e&&!(e.width<=0||e.height<=0)}function wR(e,t){const{width:r,height:i}=t,n=i,s=n*e,o=Math.min(r/s,i/n);return{width:s*o,height:n*o}}const _R=({vertical:e,width:t,height:r,count:i,aspectRatio:n})=>{const s=[1,2,3].map((s=>(({width:e,height:t,rows:r,cols:i,aspectRatio:n})=>{const s=wR(n,{width:e/i,height:t/r});return Math.round(s.width*s.height)})({width:t,height:r,rows:e?Math.ceil(i/s):s,cols:e?s:Math.ceil(i/s),aspectRatio:n}))),o=Math.max(...s);return{splits:s.indexOf(o)+1,weight:o}},SR=({width:e,height:t,count:r,aspectRatio:i})=>{const n=_R({vertical:!0,width:e,height:t,count:r,aspectRatio:i}),s=_R({vertical:!1,width:e,height:t,count:r,aspectRatio:i});return n.weight>s.weight?{splits:n.splits,vertical:!0}:{splits:s.splits,vertical:!1}};function CR(e){var{aspectRatio:t,children:r,className:i,height:n,style:o,width:a,withRoundedCorners:c=!1,withShadow:d=!0}=e,l=aR(e,["aspectRatio","children","className","height","style","width","withRoundedCorners","withShadow"]);let u=a,p=n,h=0,f=0;t&&(({width:u,height:p}=wR(t,{width:a,height:n})),h=(a-u)/2,f=(n-p)/2);const m=Object.assign({width:`${Math.round(u)}px`,height:`${Math.round(p)}px`},h||f?{transform:`translate3d(${Math.round(h)}px, ${Math.round(f)}px, 0)`}:{});return s.createElement("div",{className:i,style:Object.assign({position:"absolute",top:0,left:0},o)},s.createElement("div",Object.assign({style:m},l),s.cloneElement(r,{contentWidth:u,contentHeight:p,withRoundedCorners:c,withShadow:d})))}function RR({origin:e,bounds:t}){return{top:Math.round(e.top),left:Math.round(e.left),height:Math.round(t.height),width:Math.round(t.width)}}function kR({cell:e,child:t,clientId:r,style:i={},withRoundedCorners:n=!1,withShadow:o=!1}){const a=!yR(e.bounds);return s.createElement(CR,{width:e.bounds.width,height:e.bounds.height,aspectRatio:e.aspectRatio,style:a?{width:0,height:0}:i,withRoundedCorners:n,withShadow:o,key:r},t)}function TR({containerFrame:e,debug:t=!1,featureRoundedCornersOff:r=!1,floatingContent:i,gridContent:n=[],isConstrained:o=!1,layoutOverflowBackdropFrame:a=vR(),layoutVideoStage:c,presentationGridContent:d=[],subgridContent:l=[]}){const u=!r&&!o,p=[];return n.length&&p.push(...function({content:e,isConstrained:t,stageLayout:r,withRoundedCorners:i,withShadow:n}){var o;const a=(null===(o=r.videoGrid)||void 0===o?void 0:o.cells)||[],c=e.map(((e,o)=>{var c,d;if(!r.videoGrid)return null;const l=a[o],u={top:r.videoGrid.origin.top+r.videoGrid.paddings.top+l.origin.top,left:r.videoGrid.origin.left+r.videoGrid.paddings.left+l.origin.left},p={width:Math.round(l.bounds.width),height:Math.round(l.bounds.height),transform:`translate3d(${Math.round(u.left)}px, ${Math.round(u.top)}px, 0)`},h=null===(d=null===(c=null==e?void 0:e.props)||void 0===c?void 0:c.participant)||void 0===d?void 0:d.id;return kR({cell:l,child:s.cloneElement(e,{isSmallCell:l.isSmallCell,isZoomedByDefault:!!t&&!(null==e?void 0:e.props.participant.isPresentation),canZoom:!!t,key:h||`video-${o}`}),clientId:h||`video-${o}`,withRoundedCorners:i,style:p,withShadow:n})}));return c}({content:n,isConstrained:o,stageLayout:c,withRoundedCorners:u,withShadow:!o})),d.length&&p.push(...function({content:e,isConstrained:t,stageLayout:r,withRoundedCorners:i,withShadow:n}){var o;const a=(null===(o=r.presentationGrid)||void 0===o?void 0:o.cells)||[];return e.map(((e,o)=>{var c,d;if(!r.presentationGrid)return null;const l=a[o],u={top:r.presentationGrid.origin.top+r.presentationGrid.paddings.top+l.origin.top,left:r.presentationGrid.origin.left+r.presentationGrid.paddings.left+l.origin.left},p={width:Math.round(l.bounds.width),height:Math.round(l.bounds.height),transform:`translate3d(${Math.round(u.left)}px, ${Math.round(u.top)}px, 0)`},h=null===(d=null===(c=null==e?void 0:e.props)||void 0===c?void 0:c.participant)||void 0===d?void 0:d.id;return kR({cell:l,child:s.cloneElement(e,{isSmallCell:l.isSmallCell,isZoomedByDefault:!!t&&!(null==e?void 0:e.props.participant.isPresentation),canZoom:!!t,key:h||`presentation-${o}`}),clientId:h||`presentation-${o}`,style:p,withRoundedCorners:i,withShadow:n})}))}({content:d,isConstrained:o,stageLayout:c,withRoundedCorners:u,withShadow:!o})),i&&p.push(function({content:e,containerFrame:t,stageLayout:r,withRoundedCorners:i}){var n;if(!r.floatingContent)return null;const o=r.floatingContent,a=o.origin.top,c=o.origin.left,d={width:Math.round(o.bounds.width),height:Math.round(o.bounds.height),transform:`translate3d(${Math.round(t.origin.left+c)}px, ${Math.round(t.origin.top+a)}px, 0)`,position:"fixed",top:o.bounds.height/2,left:0,zIndex:40},l=(null===(n=e.props.client)||void 0===n?void 0:n.id)||"floating";return kR({cell:o,child:s.cloneElement(e,{isSmallCell:o.isSmallCell,isZoomedByDefault:!1,canZoom:!1,key:l,isDraggable:!1}),clientId:l,style:d,withRoundedCorners:i,withShadow:!1})}({content:i,containerFrame:e,stageLayout:c,withRoundedCorners:!r})),l.length&&p.push(...function({content:e,stageLayout:t,withRoundedCorners:r,withShadow:i}){const n=t.subgrid.cells;return e.map(((e,o)=>{var a,c,d,l;const u=n[o],p={height:Math.round(u.bounds.height),width:Math.round(u.bounds.width),transform:""},h={top:t.subgrid.origin.top+u.origin.top,left:t.subgrid.origin.left+u.origin.left};p.transform=`translate3d(${Math.round(h.left)}px, ${Math.round(h.top)}px, 0)`;const f=null===(c=null===(a=null==e?void 0:e.props)||void 0===a?void 0:a.participant)||void 0===c?void 0:c.id,m=(null===(d=u.paddings)||void 0===d?void 0:d.left)||0,g=(null===(l=u.paddings)||void 0===l?void 0:l.right)||0;return kR({cell:u,child:s.cloneElement(e,{avatarSize:u.bounds.width-m-g,canZoom:!1,cellPaddings:u.paddings,isSmallCell:u.isSmallCell,isZoomedByDefault:!1,key:f||`subgrid-${o}`,style:p}),clientId:f||`subgrid-${o}`,style:p,withRoundedCorners:r,withShadow:i})}))}({content:l,stageLayout:c,withRoundedCorners:!r,withShadow:!0})),s.createElement("div",{key:"video-stage-layout",style:{width:"100%",height:"100%",position:"relative"}},yR(a.bounds)&&s.createElement("div",{style:RR(a)}),p,t&&s.createElement(s.Fragment,null))}const PR=16/9,ER=4/3,OR=({value:e,min:t,max:r})=>Math.min(Math.max(e,t),r);function DR({choices:e=[]}){const t=Math.min(...e),r=Math.max(...e);let i=null;if(t===r)i=t;else{const t=function(...e){return new Set(e).size!==e.length}(e)?(n=e).sort(((e,t)=>n.filter((t=>t===e)).length-n.filter((e=>e===t)).length)).pop():r;i=OR({value:t||r,min:ER,max:PR})}var n;return{minAr:t,maxAr:r,chosenAr:i}}function IR({width:e,height:t,cellCount:r,gridGap:i,cellAspectRatios:n=[ER],paddings:s=bR()}){if(!r)return{cellCount:r,cellHeight:0,cellWidth:0,cols:0,rows:0,extraHorizontalPadding:0,extraVerticalPadding:0,gridGap:i,paddings:s};const o=e-(s.left+s.right),a=t-(s.top+s.bottom),c=DR({choices:n});let d=c.chosenAr;const{rows:l,cols:u}=function({count:e,width:t,height:r,aspectRatio:i}){if(e<=1)return{rows:1,cols:1};const{splits:n,vertical:s}=SR({width:t,height:r,count:e,aspectRatio:i});return s?{rows:Math.ceil(e/n),cols:n}:{rows:n,cols:Math.ceil(e/n)}}({count:r,width:o,height:a,aspectRatio:d});1===l?d=OR({value:o/u/a,min:Math.min(c.chosenAr,c.maxAr),max:Math.max(c.chosenAr,c.maxAr)}):1===u&&(d=OR({value:o/(a/l),min:Math.min(c.chosenAr,c.maxAr),max:Math.max(c.chosenAr,c.maxAr)}));const{cellWidth:p,cellHeight:h,extraHorizontalPadding:f,extraVerticalPadding:m}=function({width:e,height:t,rows:r,cols:i,gridGap:n,aspectRatio:s}){const o=(e-(i-1)*n)/i,a=(t-(r-1)*n)/r,c=o/a;let d=0,l=0;return s<c?d=o-a*s:s>c&&(l=a-o/s),{cellWidth:o-d,cellHeight:a-l,extraHorizontalPadding:d*i/2,extraVerticalPadding:l*r/2}}({width:o,height:a,rows:l,cols:u,gridGap:i,aspectRatio:d});return{cellCount:r,cellHeight:h,cellWidth:p,cols:u,rows:l,extraHorizontalPadding:f,extraVerticalPadding:m,gridGap:i,paddings:s}}const xR="rows",MR="columns";function LR({layoutGrid:e,dim:t,secDim:r,index:i,count:n,gridGap:s}){const o=(t-s*(n-1))*(e.fractions?e.fractions[i]:1/n),a=e.lines[i];return[o,(r-s*(a-1))/a]}function jR({isHorizontal:e,layoutGrid:t,width:r,height:i,gridGap:n}){const s=[],o=0,a=0,c={x:0,y:0},d=t.lines.length,l=e?i:r,u=e?r:i;for(let r=0;r<d;r++){const i=LR({layoutGrid:t,dim:l,secDim:u,index:r,count:d,gridGap:n}),p={width:e?i[1]:i[0],height:e?i[0]:i[1]},h=t.lines[r];for(let t=0;t<h;t++)s.push({origin:Object.assign({},c),bounds:p}),e?c.x+=p.width+n:c.y+=p.height+n;e?(c.y+=p.height+n,c.x=o):(c.x+=p.width+n,c.y=a)}return s}function AR({layoutGrid:e,width:t,height:r,gridGap:i}){switch(e.type){case xR:return function({layoutGrid:e,width:t,height:r,gridGap:i}){return jR({isHorizontal:!0,layoutGrid:e,width:t,height:r,gridGap:i})}({layoutGrid:e,width:t,height:r,gridGap:i});case MR:return function({layoutGrid:e,width:t,height:r,gridGap:i}){return jR({isHorizontal:!1,layoutGrid:e,width:t,height:r,gridGap:i})}({layoutGrid:e,width:t,height:r,gridGap:i})}}function NR({width:e,height:t,cellCount:r,gridGap:i=0,paddings:n=bR()}){const s=e-(n.left+n.right),o=t-(n.top+n.bottom);return{cellRects:AR({layoutGrid:Math.round(s/o*10)/10<=1?{1:{type:xR,lines:[1]},2:{type:xR,lines:[1,1]},3:{type:xR,lines:[2,1]},4:{type:xR,lines:[2,2]},5:{type:xR,lines:[2,2,1]},6:{type:xR,lines:[2,2,2]},7:{type:xR,lines:[3,2,2]},8:{type:xR,lines:[2,2,2,2]},9:{type:xR,lines:[3,2,2,2]},10:{type:xR,lines:[3,3,2,2]},11:{type:xR,lines:[3,3,3,2]},12:{type:xR,lines:[3,3,3,3]},13:{type:xR,lines:[2,2,3,3,3]},14:{type:xR,lines:[2,3,3,3,3]},15:{type:xR,lines:[3,3,3,3,3]},16:{type:xR,lines:[2,2,3,3,3,3]},17:{type:xR,lines:[2,3,3,3,3,3]},18:{type:xR,lines:[3,3,3,3,3,3]},19:{type:xR,lines:[2,2,3,3,3,3,3]},20:{type:xR,lines:[2,3,3,3,3,3,3]},21:{type:xR,lines:[3,3,3,3,3,3,3]},22:{type:xR,lines:[2,2,3,3,3,3,3,3]},23:{type:xR,lines:[2,3,3,3,3,3,3,3]},24:{type:xR,lines:[3,3,3,3,3,3,3,3]}}[r]||{type:xR,lines:[3,3,3,3,3,3,3,3]}:function(e){return{1:{type:MR,lines:[1]},2:{type:MR,lines:[1,1]},3:{type:MR,lines:[2,1]},4:{type:MR,lines:[2,2]},5:{type:xR,lines:[3,2],fractions:[.45,.55]},6:{type:MR,lines:[2,2,2]},7:{type:xR,lines:[4,3],fractions:[.45,.55]},8:{type:MR,lines:[2,2,2,2]},9:{type:MR,lines:[3,2,2,2]},10:{type:MR,lines:[3,3,2,2]},11:{type:MR,lines:[3,3,3,2]},12:{type:MR,lines:[3,3,3,3]},13:{type:MR,lines:[4,3,3,3]},14:{type:MR,lines:[4,4,3,3]},15:{type:MR,lines:[3,3,3,3,3]},16:{type:MR,lines:[4,3,3,3,3]},17:{type:MR,lines:[4,4,3,3,3]},18:{type:MR,lines:[4,4,4,3,3]},19:{type:MR,lines:[4,4,4,4,3]},20:{type:MR,lines:[4,4,4,4,4]},21:{type:MR,lines:[5,4,4,4,4]},22:{type:MR,lines:[5,5,4,4,4]},23:{type:MR,lines:[5,5,5,4,4]},24:{type:MR,lines:[5,5,5,5,4]}}[e]||{type:MR,lines:[5,5,5,5,5]}}(r),width:s,height:o,gridGap:i})||[],cellCount:r,gridGap:i,extraHorizontalPadding:0,extraVerticalPadding:0,paddings:n}}function BR({containerBounds:e,isPortrait:t,cellCount:r,cellBounds:i,paddings:n=bR()}){let s=0,o=0,a=0,c=0,d=0,l=0;const u=e.width-n.left-n.right,p=e.height-n.top-n.bottom;return r&&(t?(c=Math.floor(u/i.width),a=Math.ceil(r/c),s=u,o=a*i.height,d=(u-c*i.width)/2):(a=Math.floor(p/i.height),c=Math.ceil(r/a),s=c*i.width,o=p,l=(p-a*i.height)/2)),{isPortrait:t,width:s+n.left+n.right,height:o+n.top+n.bottom,cellBounds:i,cellCount:r,rows:a,cols:c,extraHorizontalPadding:d,extraVerticalPadding:l,paddings:n}}const{BOTTOM_TOOLBAR_HEIGHT:FR,VIDEO_CONTROLS_MIN_WIDTH:zR,TABLET_BREAKPOINT:VR,SUBGRID_EMPTY_STAGE_MAX_WIDTH:UR}=fR,$R=200,GR=300,qR=200,HR=20,WR=12,KR=bR({top:4,bottom:28,left:8,right:8});function JR({hasOverflow:e,hasStage:t}){return e&&t?[80]:[80,60]}function XR({cellCount:e}){const t=e<=6;return gR({width:t?GR-50:GR,height:t?$R-50:$R})}function QR({containerBounds:e,isPortrait:t,cellCount:r,cellSizeOptions:i,cellPaddings:n,paddings:s}){const o=function({containerBounds:e,isPortrait:t,cellCount:r,cellSizeOptions:i,cellPaddings:n,paddings:s}){let o;for(let a=0;a<i.length;a++){const c=i[a];if(o=BR({containerBounds:e,isPortrait:t,cellCount:r,cellBounds:gR({width:c+n.left+n.right,height:c+n.top+n.bottom}),paddings:s}),o.width<=e.width&&o.height<=e.height)return o}return o}({containerBounds:e,isPortrait:t,cellCount:r,cellSizeOptions:i,cellPaddings:n,paddings:s}),a=o.cellBounds.width-n.left-n.right===i[i.length-1],c=gR({width:Math.min(o.width,e.width),height:Math.min(o.height,e.height)}),d=gR({width:o.width,height:o.height});return 0===r?{bounds:c,contentBounds:d,videoCells:[]}:{bounds:c,contentBounds:d,videoCells:[...Array(r)].map(((e,t)=>{const{top:r,left:i,width:s,height:c}=function({index:e,layout:t}){const{isPortrait:r,rows:i,cols:n,cellCount:s,cellBounds:o,extraHorizontalPadding:a,extraVerticalPadding:c,paddings:d}=t,l=r?Math.floor(e/n):Math.floor(e%i),u=r?Math.floor(e%n):Math.floor(e/i),p=function({index:e,isPortrait:t,rows:r,cols:i,cellBounds:n,cellCount:s}){const o=r*i,a=o-s;if(!a)return 0;const c=o-a-1;return e<c-((t?i:r)-a)+1||e>c?0:a*(t?n.width:n.height)/2}({index:e,isPortrait:r,rows:i,cols:n,cellBounds:o,cellCount:s});return{top:d.top+c+l*o.height+(r?0:p),left:d.left+a+u*o.width+(r?p:0),width:o.width,height:o.height}}({index:t,layout:o});return{origin:mR({top:r,left:i}),bounds:gR({width:s,height:c}),paddings:n,isSmallCell:a}}))}}function ZR({cellPaddings:e,cellSizeOptions:t,containerBounds:r,containerOrigin:i,gridGap:n,hasConstrainedOverflow:s,hasPresentationContent:o,hasVideoContent:a,isConstrained:c,isMaximizeMode:d,isPortrait:l,isSmallScreen:u,maxGridWidth:p,shouldOverflowSubgrid:h,subgridVideos:f}){const{width:m,height:g}=r,v=o||a,b=f.length>0;if(!b&&!v)return{isPortrait:l,videosContainer:vR(),subgrid:Object.assign(Object.assign({},vR()),{contentBounds:gR(),cells:[]}),hasOverflow:!1};if(!b)return{isPortrait:l,videosContainer:vR(Object.assign(Object.assign({},r),i)),subgrid:Object.assign(Object.assign({},vR()),{contentBounds:gR(),cells:[]}),hasOverflow:s};const y=h?HR:0;let w=null;if(v)if(h){const i=t[0];let n=d?FR:FR+e.top+(c||u?i/2:i)+e.bottom;r.height-n<$R&&(n=0),w=gR({width:r.width,height:n})}else w=gR(d?{width:r.width,height:t[0]+e.top+e.bottom}:l?{width:r.width,height:r.height/2}:{width:r.width/2,height:r.height});else w=gR({width:Math.min(UR,r.width),height:r.height});let _=0;w.width>p&&(_=(w.width-p)/2);const S=QR({containerBounds:w,isPortrait:l,cellCount:f.length,cellSizeOptions:t,cellPaddings:e,paddings:bR({top:y,left:_,right:_})}),C=gR({width:S.contentBounds.width-w.width,height:S.contentBounds.height-w.height}),R=C.width>0||C.height>0;let k,T=null;T=!v||h||R?S.contentBounds:S.bounds;let P=T;v?(P=gR(h?{width:0,height:w.height+y+n}:l?{width:0,height:S.bounds.height+n}:{width:S.bounds.width+n,height:0}),k=function({bounds:e,fromBounds:t}){return{width:Math.max(t.width-e.width,0),height:Math.max(t.height-e.height,0)}}({bounds:P,fromBounds:r})):k=gR();const E=Object.assign({},i);let O;return O=mR(v?{top:l?Math.max(i.top+g-P.height+n,0):i.top,left:l?i.left:Math.max(i.left+m-T.width,0)}:{top:i.top+Math.max(0,(g-T.height)/2),left:i.left+Math.max(0,(m-T.width)/2)}),{isPortrait:l,videosContainer:vR(Object.assign(Object.assign({},k),E)),subgrid:Object.assign(Object.assign({},vR(Object.assign(Object.assign({},T),O))),{cells:S.videoCells.map(((e,t)=>{var r,i;return Object.assign({aspectRatio:(null===(r=f[t])||void 0===r?void 0:r.aspectRatio)||1,type:"video",clientId:null===(i=f[t])||void 0===i?void 0:i.clientId},e)})),contentBounds:S.contentBounds}),hasOverflow:R||h||s,overflowNeedBounds:h?gR():C}}function YR({containerBounds:e,containerOrigin:t,gridGap:r,supersizedContentAspectRatio:i,hasPresentationContent:n,hasPresentationGrid:s,hasVideoContent:o,minGridBounds:a}){const{width:c,height:d}=e;let l=c<=d,u=gR(),p=mR(),h=o?Object.assign({},e):gR(),f=o?Object.assign({},t):mR();if(n){const n=function({bounds:e,aspectRatio:t,minGridContainerBounds:r,hasPresentationGrid:i}){const{width:n,height:s}=e;if(!(r.width>0))return{isPortrait:n<=s,supersizedContentBounds:e};const o=Math.round(n/2),a=Math.round(s/2),c=Math.max(n-r.width,0),d=Math.max(s-r.height,0);let l=c<=d,u=0,p=0;if(t){const e=wR(t,{width:c,height:s}),r=wR(t,{width:n,height:d});if(l=t<=1?r.height>e.height:r.width>e.width,l){const e=d-Math.max(r.height,a);p=Math.max(e,0)}else{const t=c-Math.max(e.width,o);u=Math.max(t,0)}}else i&&(l=c/d>=5);return{isPortrait:l,supersizedContentBounds:{width:l?n:c-u,height:l?d-p:s}}}({bounds:e,aspectRatio:i||1,minGridContainerBounds:gR({width:o?a.width+r:0,height:o?a.height+r:0}),hasPresentationGrid:s});l=n.isPortrait,u=n.supersizedContentBounds,p=Object.assign({},t),o&&(h=gR({width:l?e.width:e.width-u.width-r,height:l?e.height-u.height-r:e.height}),f=mR({top:l?t.top+u.height+r:t.top,left:l?t.left:t.left+u.width+r}))}return{isPortrait:l,presentationGrid:Object.assign({},vR(Object.assign(Object.assign({},u),p))),videoGrid:vR(Object.assign(Object.assign({},h),f))}}function ek({containerBounds:e,paddings:t=bR(),videos:r,isConstrained:i,maxGridWidth:n,gridGap:s}){const{width:o,height:a}=e,c=n?Math.min(o,n):o,d=r.length;let l=null,u=null;if(i){const e=NR({width:o,height:a,cellCount:d,gridGap:s,paddings:t}),i=d>4;u=r.map(((t,r)=>{const n=function({index:e,layout:t}){const{cellRects:r}=t,i=r[e]||vR();return{top:i.origin.y,left:i.origin.x,width:i.bounds.width,height:i.bounds.height}}({index:r,layout:e});return{clientId:t.clientId,isDraggable:t.isDraggable,origin:mR({top:n.top,left:n.left}),bounds:gR({width:n.width,height:n.height}),aspectRatio:n.width/n.height,isSmallCell:i,type:"video"}})),l=e}else{const e=r.map((e=>e.aspectRatio||1)),n=XR({cellCount:d}),o=IR({width:c,height:a,cellCount:d,gridGap:s,cellAspectRatios:e,paddings:t});u=r.map(((e,t)=>{const r=function({index:e,layout:t}){const{cellWidth:r,cellHeight:i,rows:n,cols:s,cellCount:o,gridGap:a}=t,c=Math.floor(e/s),d=Math.floor(e%s),l=function({rows:e,cols:t,cellWidth:r,index:i,cellCount:n,gridGap:s}){const o=e*t,a=o-n;if(!a)return 0;const c=o-a-1;return i>=c-(t-a)+1&&i<=c?a*r/2+s:0}({rows:n,cols:s,cellWidth:r,index:e,cellCount:o,gridGap:a});return{top:c*i+c*a,left:d*r+d*a+l,width:r,height:i}}({index:t,layout:o}),s=o.cellWidth<n.width,a=i||s?o.cellWidth/o.cellHeight:e.aspectRatio||1;return{clientId:e.clientId,isDraggable:e.isDraggable,origin:mR({top:r.top,left:r.left}),bounds:gR({width:r.width,height:r.height}),aspectRatio:a,isSmallCell:s,type:"video"}})),l=o}return{videoCells:u,extraHorizontalPadding:o!==c?l.extraHorizontalPadding+(o-c)/2:l.extraHorizontalPadding,extraVerticalPadding:l.extraVerticalPadding,paddings:l.paddings,gridGap:s}}function tk({a:e,b:t,gridGap:r,isPortrait:i}){const n=i?e.vertical:e.horizontal,s=i?t.vertical:t.horizontal;if(n===s)return{a:0,b:0};const o=n<s?e:t,a=i?o.vertical:o.horizontal,c=(r+(n+s)+a)/2-a;return{a:o===e?c:0,b:o===t?c:0}}function rk({gridGap:e,isConstrained:t,presentationVideos:r,videos:i,videosContainerLayout:n,gridLayoutPaddings:s=bR(),presentationGridLayoutPaddings:o=bR(),maxGridWidth:a}){return{gridLayout:ek({containerBounds:n.videoGrid.bounds,gridGap:e,isConstrained:t,maxGridWidth:a,paddings:s,videos:i}),presentationGridLayout:ek({containerBounds:n.presentationGrid.bounds,gridGap:e,isConstrained:t,maxGridWidth:a,paddings:o,videos:r})}}function ik({floatingVideo:e,frame:t,gridGap:r,isConstrained:i,isMaximizeMode:n=!1,isXLMeetingSize:s=!1,paddings:o=bR(),presentationVideos:a=[],rebalanceLayout:c=!1,roomBounds:d,roomLayoutHasOverlow:l=!1,subgridCellPaddings:u=KR,subgridVideos:p=[],videoControlsHeight:h=0,videos:f=[],videoGridGap:m}){let g=s&&(!screen||screen.width<=2048);const v=!!a.length,b=a.length>1,y=v&&!b?a[0].aspectRatio:null,w=!!f.length,_=t.bounds.width-o.left-o.right;let S=t.bounds.height-o.top-o.bottom;const C=Math.max(2200,.8*_),R=i&&f.length>WR,k=S/4,T=Math.ceil((f.length-WR)/3);S=R?S+k*T:S;const P=gR({width:_,height:S}),E=mR({top:o.top,left:o.left}),O=XR({cellCount:f.length}),D=d.width<VR||d.height<VR,I=n||g||!(v||w)||P.width<=P.height,x={cellPaddings:u,containerBounds:P,containerOrigin:E,gridGap:r,hasPresentationContent:v,hasVideoContent:w,isConstrained:i,isMaximizeMode:n,isSmallScreen:D,subgridVideos:p,maxGridWidth:C};let M=ZR(Object.assign(Object.assign({},x),{cellSizeOptions:JR({hasOverflow:g,hasStage:v||w}),isPortrait:I,shouldOverflowSubgrid:g,hasConstrainedOverflow:R})),L=!1;if(!g&&l&&!M.hasOverflow){ZR(Object.assign(Object.assign({},x),{containerBounds:gR({width:P.width,height:P.height-FR}),cellSizeOptions:JR({hasOverflow:g,hasStage:v||w}),isPortrait:I,shouldOverflowSubgrid:g,hasConstrainedOverflow:R})).hasOverflow&&(L=!0)}(L||M.hasOverflow&&!g)&&(g=!0,M=ZR(Object.assign(Object.assign({},x),{cellSizeOptions:JR({hasOverflow:!0,hasStage:v||w}),isPortrait:!0,shouldOverflowSubgrid:g,hasConstrainedOverflow:R})));const j=YR({containerBounds:M.videosContainer.bounds,containerOrigin:M.videosContainer.origin,gridGap:r,supersizedContentAspectRatio:y||1,hasPresentationContent:v,hasPresentationGrid:b,hasVideoContent:w,minGridBounds:O});let{gridLayout:A,presentationGridLayout:N}=rk({gridGap:m||r,isConstrained:i,presentationVideos:a,videos:f,videosContainerLayout:j,maxGridWidth:C});if(M.hasOverflow&&!g){const{vPaddings:e,hPaddings:t}=function({need:e,stageLayout:t,gridLayout:r,presentationGridLayout:i,videosContainerLayout:n}){let s={presentationGrid:0,grid:0},o={presentationGrid:0,grid:0};if(t.isPortrait){const t=Math.min(r.extraVerticalPadding,i.extraVerticalPadding);s={presentationGrid:Math.min(n.isPortrait?i.extraVerticalPadding:t,e.height),grid:Math.min(n.isPortrait?r.extraVerticalPadding:t,e.height)}}else{const t=Math.min(r.extraHorizontalPadding,i.extraHorizontalPadding);o={presentationGrid:Math.min(n.isPortrait?t:i.extraHorizontalPadding,e.width),grid:Math.min(n.isPortrait?t:r.extraHorizontalPadding,e.width)}}return{vPaddings:s,hPaddings:o}}({need:M.overflowNeedBounds||gR(),stageLayout:M,gridLayout:A,presentationGridLayout:N,videosContainerLayout:j});(e.presentationGrid||e.grid||t.presentationGrid||t.grid)&&(!function({vPaddings:e,hPaddings:t,stageLayout:r,videosContainerLayout:i}){if(r.isPortrait&&(e.presentationGrid||e.grid)){const t=i.isPortrait?2*e.presentationGrid+2*e.grid:e.presentationGrid+e.grid;r.videosContainer.bounds.height-=t,r.subgrid.origin.top-=t,r.subgrid.bounds.height+=t,i.presentationGrid.bounds.height-=2*e.presentationGrid,i.videoGrid.bounds.height-=2*e.grid,i.isPortrait&&(i.videoGrid.origin.top-=e.presentationGrid)}if(!r.isPortrait&&(t.presentationGrid||t.grid)){const e=i.isPortrait?t.presentationGrid+t.grid:2*t.presentationGrid+2*t.grid;r.videosContainer.bounds.width-=e,r.subgrid.origin.left-=e,r.subgrid.bounds.width+=e,i.presentationGrid.bounds.width-=2*t.presentationGrid,i.videoGrid.bounds.width-=2*t.grid,i.isPortrait||(i.videoGrid.origin.left-=t.grid)}}({vPaddings:e,hPaddings:t,stageLayout:M,videosContainerLayout:j}),({gridLayout:A,presentationGridLayout:N}=rk({gridGap:m||r,isConstrained:i,presentationVideos:a,videos:f,videosContainerLayout:j,maxGridWidth:C})))}const B=function({roomBounds:e,containerFrame:t,floatingVideo:r,videoControlsHeight:i,margin:n=8}){if(!r)return null;const s=wR(r.aspectRatio||0,{width:qR,height:qR}),o=!(e.height-t.bounds.height-t.origin.top),a=t.bounds.width-2*(s.width+n)<zR;let c=0;o&&a?c=-1*i:o||a||(c=i);const d=mR({top:t.origin.top+(t.bounds.height-s.height-n)+c,left:t.origin.left+(t.bounds.width-s.width-n)});return{clientId:r.clientId,isDraggable:r.isDraggable,origin:d,bounds:s,aspectRatio:r.aspectRatio,isSmallCell:!0}}({roomBounds:d,containerFrame:t,floatingVideo:e||null,videoControlsHeight:h});c&&function({videosContainerLayout:e,gridLayout:t,presentationGridLayout:r,stageLayout:i,gridGap:n,shouldOverflowSubgrid:s}){const o=e.presentationGrid.bounds.width>0,a=e.videoGrid.bounds.width>0,c=i.subgrid.bounds.width>0,d={vertical:0,horizontal:0};if(o&&a){const i=tk({a:{horizontal:r.extraHorizontalPadding,vertical:r.extraVerticalPadding},b:{horizontal:t.extraHorizontalPadding,vertical:t.extraVerticalPadding},gridGap:n,isPortrait:e.isPortrait});e.isPortrait?(e.presentationGrid.origin.top+=i.a,e.videoGrid.origin.top-=i.b,d.vertical=i.b):(e.presentationGrid.origin.left+=i.a,e.videoGrid.origin.left-=i.b,d.horizontal=i.b)}if(c&&(o||a)&&!s){const s={horizontal:r.extraHorizontalPadding,vertical:r.extraVerticalPadding},c={horizontal:t.extraHorizontalPadding+d.horizontal,vertical:t.extraVerticalPadding+d.vertical};let l;const u=o&&a;l=u&&e.isPortrait&&!i.isPortrait?s.horizontal<c.horizontal?s:c:u&&!e.isPortrait&&i.isPortrait?s.vertical<c.vertical?s:c:a?c:s;const p=tk({a:l,b:{horizontal:0,vertical:0},gridGap:n,isPortrait:i.isPortrait});i.isPortrait?i.subgrid.origin.top-=p.b:i.subgrid.origin.left-=p.b}}({videosContainerLayout:j,gridLayout:A,presentationGridLayout:N,stageLayout:M,gridGap:r,shouldOverflowSubgrid:g});let F=o.top+M.videosContainer.bounds.height+M.subgrid.bounds.height+o.bottom;return(v||w)&&(F+=r),{isPortrait:M.isPortrait,hasOverflow:M.hasOverflow,videosContainer:Object.assign(Object.assign({},j),{bounds:gR({width:M.videosContainer.bounds.width,height:M.videosContainer.bounds.height}),origin:mR({top:M.videosContainer.origin.top,left:M.videosContainer.origin.left})}),bounds:gR({height:g?F:t.bounds.height,width:t.bounds.width}),gridGap:r,presentationGrid:Object.assign(Object.assign({},j.presentationGrid),{cells:N.videoCells,paddings:bR({top:N.paddings.top+N.extraVerticalPadding,bottom:N.paddings.bottom+N.extraVerticalPadding,left:N.paddings.left+N.extraHorizontalPadding,right:N.paddings.right+N.extraHorizontalPadding})}),videoGrid:Object.assign(Object.assign({},j.videoGrid),{cells:A.videoCells,paddings:bR({top:A.paddings.top+A.extraVerticalPadding,bottom:A.paddings.bottom+A.extraVerticalPadding,left:A.paddings.left+A.extraHorizontalPadding,right:A.paddings.right+A.extraHorizontalPadding})}),subgrid:M.subgrid,floatingContent:Object.assign(Object.assign(Object.assign({},B),e),{origin:(null==B?void 0:B.origin)||mR(),bounds:(null==B?void 0:B.bounds)||gR(),aspectRatio:(null==e?void 0:e.aspectRatio)||1})}}function nk({aspectRatio:e,avatarSize:t,cellPaddings:r,client:i,isDraggable:n=!0,isPlaceholder:s=!1,isSubgrid:o=!1}){return{aspectRatio:e||16/9,avatarSize:t,cellPaddings:r,client:i,clientId:(null==i?void 0:i.id)||"",isDraggable:n,isPlaceholder:s,isSubgrid:o,type:"video"}}const sk=12,ok=12,ak=24;function ck({activeVideosSubgridTrigger:e=ok,stageParticipantLimit:t=sk,forceSubgrid:r=!0,enableSubgrid:i=!0,maximizedParticipant:n,floatingParticipant:o,isConstrained:a=!1}={}){const c=dR(Z_),d=dR(dS),l=dR(F_),u=s.useMemo((()=>o),[o]),p=s.useMemo((()=>u?c.filter((e=>e.id!==u.id)):c),[c,u]),h=s.useMemo((()=>!!i&&(!!r||l>t)),[r,l,t,i]),f=s.useMemo((()=>function({clientViews:e,activeVideosSubgridTrigger:t,shouldShowSubgrid:r,spotlightedParticipants:i,maximizedParticipant:n,isPhoneResolution:s}){if(!r)return[];const o=i.length>0,a=(n?e.filter((e=>e.id!==n.id)):e).filter((e=>!e.isPresentation&&!i.includes(e))),c=a.filter((e=>!e.isVideoEnabled)),d=a.filter((e=>e.isVideoEnabled)).length>t,l=a.filter((e=>!c.includes(e)&&e.isAudioEnabled)),u=a.filter((e=>!c.includes(e)&&!e.isAudioEnabled));if(c.length&&o)return[...u,...c];if(s&&a.length>ak){const e=[...l,...u],t=e.slice(0,ak);return t.length<=ak?[...e.filter((e=>!t.includes(e))),...c]:[...u,...c]}if(d&&u.length){const e=[...l,...u].slice(0,t);return e.length<=t?[...u.filter((t=>!e.includes(t))),...c]:[...u,...c]}return c}({clientViews:p,activeVideosSubgridTrigger:e,shouldShowSubgrid:h,spotlightedParticipants:d,maximizedParticipant:n,isPhoneResolution:a})),[p,h,e,d,a]),m=s.useMemo((()=>p.filter((e=>!f.includes(e)))),[p,f]),g=s.useMemo((()=>n?[n]:d),[d,n]),v=s.useMemo((()=>m.filter((e=>!g.includes(e)))),[m,g]);return{floatingClientView:u,clientViewsInGrid:v,clientViewsInPresentationGrid:g,clientViewsInSubgrid:f}}var dk={exports:{}};const lk=55296,uk=56319,pk=56320,hk=127462,fk=127487,mk=127995,gk=127999,vk=65024,bk=65039,yk=8400,wk=8447,_k=8205,Sk=[776,2359,2359,2367,2367,2984,3007,3021,3633,3635,3648,3657,4352,4449,4520];function Ck(e){if("string"!=typeof e)throw new Error("string cannot be undefined or null");const t=[];let r=0,i=0;for(;r<e.length;)i+=Rk(r+i,e),Ek(e[r+i])&&i++,Tk(e[r+i])&&i++,Pk(e[r+i])&&i++,Ok(e[r+i])?i++:(t.push(e.substring(r,r+i)),r+=i,i=0);return t}function Rk(e,t){const r=t[e];if(!function(e){return e&&Ik(e[0].charCodeAt(0),lk,uk)}(r)||e===t.length-1)return 1;const i=r+t[e+1];let n=t.substring(e+2,e+5);return kk(i)&&kk(n)||function(e){return Ik(Dk(e),mk,gk)}(n)?4:2}function kk(e){return Ik(Dk(e),hk,fk)}function Tk(e){return"string"==typeof e&&Ik(e.charCodeAt(0),vk,bk)}function Pk(e){return"string"==typeof e&&Ik(e.charCodeAt(0),yk,wk)}function Ek(e){return"string"==typeof e&&-1!==Sk.indexOf(e.charCodeAt(0))}function Ok(e){return"string"==typeof e&&e.charCodeAt(0)===_k}function Dk(e){return(e.charCodeAt(0)-lk<<10)+(e.charCodeAt(1)-pk)+65536}function Ik(e,t,r){return e>=t&&e<=r}dk.exports=Ck,dk.exports.substr=function(e,t,r){const i=Ck(e);if(void 0===t)return e;if(t>=i.length)return"";const n=i.length-t;let s=t+(void 0===r?n:r);return s>t+n&&(s=void 0),i.slice(t,s).join("")};var xk=c(dk.exports);const Mk=({name:e})=>{const t=((e="")=>{if(e=e.trim())return e.split(/-| /).map((e=>xk(e)[0])).slice(0,3);return[]})(e),r=[0,56,48,40][t.length]||32,i=t.join("").toUpperCase();return s.createElement("svg",{viewBox:"-60 -60 120 120","aria-hidden":"true",style:{height:"100%",pointerEvents:"none",width:"100%"}},s.createElement("text",{x:0,y:0,textAnchor:"middle",dominantBaseline:"central",fontSize:r},i))};function Lk(e){var{avatarUrl:t,className:r,size:i=40,name:n,variant:o="round"}=e,a=aR(e,["avatarUrl","className","size","name","variant"]);return s.createElement("div",Object.assign({style:{height:`${i}px`,width:`${i}px`,userSelect:"none",overflow:"hidden",borderRadius:"round"===o?"50%":"4px",backgroundColor:"#f8e3c8"},className:r,title:n},a),!t&&n?s.createElement(Mk,{name:n}):s.createElement("img",{src:t||"",alt:"",style:{height:"100%",width:"100%",objectFit:"cover",maxWidth:"initial"}}))}function jk({avatarUrl:e,displayName:t,isSmallCell:r,withRoundedCorners:i}){return s.createElement("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",position:"absolute",top:0,left:0,height:"100%",width:"100%",borderRadius:i?"8px":"0"}},s.createElement("div",{style:{height:r?60:80,width:r?60:80,pointerEvents:"none",position:"relative"}},s.createElement(Lk,{variant:"square",avatarUrl:e,name:t,size:r?60:80})))}function Ak(){return Ak=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var i in r)Object.prototype.hasOwnProperty.call(r,i)&&(e[i]=r[i])}return e},Ak.apply(this,arguments)}function Nk(e,t,{checkForDefaultPrevented:r=!0}={}){return function(i){if(null==e||e(i),!1===r||!i.defaultPrevented)return null==t?void 0:t(i)}}function Bk(...e){return t=>e.forEach((e=>function(e,t){"function"==typeof e?e(t):null!=e&&(e.current=t)}(e,t)))}function Fk(...e){return t.useCallback(Bk(...e),e)}function zk(e,r=[]){let i=[];const n=()=>{const r=i.map((e=>t.createContext(e)));return function(i){const n=(null==i?void 0:i[e])||r;return t.useMemo((()=>({[`__scope${e}`]:{...i,[e]:n}})),[i,n])}};return n.scopeName=e,[function(r,n){const s=t.createContext(n),o=i.length;function a(r){const{scope:i,children:n,...a}=r,c=(null==i?void 0:i[e][o])||s,d=t.useMemo((()=>a),Object.values(a));return t.createElement(c.Provider,{value:d},n)}return i=[...i,n],a.displayName=r+"Provider",[a,function(i,a){const c=(null==a?void 0:a[e][o])||s,d=t.useContext(c);if(d)return d;if(void 0!==n)return n;throw new Error(`\`${i}\` must be used within \`${r}\``)}]},Vk(n,...r)]}function Vk(...e){const r=e[0];if(1===e.length)return r;const i=()=>{const i=e.map((e=>({useScope:e(),scopeName:e.scopeName})));return function(e){const n=i.reduce(((t,{useScope:r,scopeName:i})=>({...t,...r(e)[`__scope${i}`]})),{});return t.useMemo((()=>({[`__scope${r.scopeName}`]:n})),[n])}};return i.scopeName=r.scopeName,i}const Uk=t.forwardRef(((e,r)=>{const{children:i,...n}=e,s=t.Children.toArray(i),o=s.find(qk);if(o){const e=o.props.children,i=s.map((r=>r===o?t.Children.count(e)>1?t.Children.only(null):t.isValidElement(e)?e.props.children:null:r));return t.createElement($k,Ak({},n,{ref:r}),t.isValidElement(e)?t.cloneElement(e,void 0,i):null)}return t.createElement($k,Ak({},n,{ref:r}),i)}));Uk.displayName="Slot";const $k=t.forwardRef(((e,r)=>{const{children:i,...n}=e;return t.isValidElement(i)?t.cloneElement(i,{...Hk(n,i.props),ref:r?Bk(r,i.ref):i.ref}):t.Children.count(i)>1?t.Children.only(null):null}));$k.displayName="SlotClone";const Gk=({children:e})=>t.createElement(t.Fragment,null,e);function qk(e){return t.isValidElement(e)&&e.type===Gk}function Hk(e,t){const r={...t};for(const i in t){const n=e[i],s=t[i];/^on[A-Z]/.test(i)?n&&s?r[i]=(...e)=>{s(...e),n(...e)}:n&&(r[i]=n):"style"===i?r[i]={...n,...s}:"className"===i&&(r[i]=[n,s].filter(Boolean).join(" "))}return{...e,...r}}const Wk=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","span","svg","ul"].reduce(((e,r)=>{const i=t.forwardRef(((e,i)=>{const{asChild:n,...s}=e,o=n?Uk:r;return t.useEffect((()=>{window[Symbol.for("radix-ui")]=!0}),[]),t.createElement(o,Ak({},s,{ref:i}))}));return i.displayName=`Primitive.${r}`,{...e,[r]:i}}),{});function Kk(e){const r=t.useRef(e);return t.useEffect((()=>{r.current=e})),t.useMemo((()=>(...e)=>{var t;return null===(t=r.current)||void 0===t?void 0:t.call(r,...e)}),[])}const Jk="dismissableLayer.update",Xk="dismissableLayer.pointerDownOutside",Qk="dismissableLayer.focusOutside";let Zk;const Yk=t.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),eT=t.forwardRef(((e,r)=>{var i;const{disableOutsidePointerEvents:n=!1,onEscapeKeyDown:s,onPointerDownOutside:o,onFocusOutside:a,onInteractOutside:c,onDismiss:d,...l}=e,u=t.useContext(Yk),[p,h]=t.useState(null),f=null!==(i=null==p?void 0:p.ownerDocument)&&void 0!==i?i:null===globalThis||void 0===globalThis?void 0:globalThis.document,[,m]=t.useState({}),g=Fk(r,(e=>h(e))),v=Array.from(u.layers),[b]=[...u.layersWithOutsidePointerEventsDisabled].slice(-1),y=v.indexOf(b),w=p?v.indexOf(p):-1,_=u.layersWithOutsidePointerEventsDisabled.size>0,S=w>=y,C=function(e,r=(null===globalThis||void 0===globalThis?void 0:globalThis.document)){const i=Kk(e),n=t.useRef(!1),s=t.useRef((()=>{}));return t.useEffect((()=>{const e=e=>{if(e.target&&!n.current){const t={originalEvent:e};function o(){rT(Xk,i,t,{discrete:!0})}"touch"===e.pointerType?(r.removeEventListener("click",s.current),s.current=o,r.addEventListener("click",s.current,{once:!0})):o()}else r.removeEventListener("click",s.current);n.current=!1},t=window.setTimeout((()=>{r.addEventListener("pointerdown",e)}),0);return()=>{window.clearTimeout(t),r.removeEventListener("pointerdown",e),r.removeEventListener("click",s.current)}}),[r,i]),{onPointerDownCapture:()=>n.current=!0}}((e=>{const t=e.target,r=[...u.branches].some((e=>e.contains(t)));S&&!r&&(null==o||o(e),null==c||c(e),e.defaultPrevented||null==d||d())}),f),R=function(e,r=(null===globalThis||void 0===globalThis?void 0:globalThis.document)){const i=Kk(e),n=t.useRef(!1);return t.useEffect((()=>{const e=e=>{if(e.target&&!n.current){rT(Qk,i,{originalEvent:e},{discrete:!1})}};return r.addEventListener("focusin",e),()=>r.removeEventListener("focusin",e)}),[r,i]),{onFocusCapture:()=>n.current=!0,onBlurCapture:()=>n.current=!1}}((e=>{const t=e.target;[...u.branches].some((e=>e.contains(t)))||(null==a||a(e),null==c||c(e),e.defaultPrevented||null==d||d())}),f);return function(e,r=(null===globalThis||void 0===globalThis?void 0:globalThis.document)){const i=Kk(e);t.useEffect((()=>{const e=e=>{"Escape"===e.key&&i(e)};return r.addEventListener("keydown",e),()=>r.removeEventListener("keydown",e)}),[i,r])}((e=>{w===u.layers.size-1&&(null==s||s(e),!e.defaultPrevented&&d&&(e.preventDefault(),d()))}),f),t.useEffect((()=>{if(p)return n&&(0===u.layersWithOutsidePointerEventsDisabled.size&&(Zk=f.body.style.pointerEvents,f.body.style.pointerEvents="none"),u.layersWithOutsidePointerEventsDisabled.add(p)),u.layers.add(p),tT(),()=>{n&&1===u.layersWithOutsidePointerEventsDisabled.size&&(f.body.style.pointerEvents=Zk)}}),[p,f,n,u]),t.useEffect((()=>()=>{p&&(u.layers.delete(p),u.layersWithOutsidePointerEventsDisabled.delete(p),tT())}),[p,u]),t.useEffect((()=>{const e=()=>m({});return document.addEventListener(Jk,e),()=>document.removeEventListener(Jk,e)}),[]),t.createElement(Wk.div,Ak({},l,{ref:g,style:{pointerEvents:_?S?"auto":"none":void 0,...e.style},onFocusCapture:Nk(e.onFocusCapture,R.onFocusCapture),onBlurCapture:Nk(e.onBlurCapture,R.onBlurCapture),onPointerDownCapture:Nk(e.onPointerDownCapture,C.onPointerDownCapture)}))}));function tT(){const e=new CustomEvent(Jk);document.dispatchEvent(e)}function rT(e,t,i,{discrete:n}){const s=i.originalEvent.target,o=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:i});t&&s.addEventListener(e,t,{once:!0}),n?function(e,t){e&&r.flushSync((()=>e.dispatchEvent(t)))}(s,o):s.dispatchEvent(o)}let iT=0;function nT(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.cssText="outline: none; opacity: 0; position: fixed; pointer-events: none",e}const sT="focusScope.autoFocusOnMount",oT="focusScope.autoFocusOnUnmount",aT={bubbles:!1,cancelable:!0},cT=t.forwardRef(((e,r)=>{const{loop:i=!1,trapped:n=!1,onMountAutoFocus:s,onUnmountAutoFocus:o,...a}=e,[c,d]=t.useState(null),l=Kk(s),u=Kk(o),p=t.useRef(null),h=Fk(r,(e=>d(e))),f=t.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;t.useEffect((()=>{if(n){function e(e){if(f.paused||!c)return;const t=e.target;c.contains(t)?p.current=t:pT(p.current,{select:!0})}function t(e){if(f.paused||!c)return;const t=e.relatedTarget;null!==t&&(c.contains(t)||pT(p.current,{select:!0}))}function r(e){if(document.activeElement===document.body)for(const t of e)t.removedNodes.length>0&&pT(c)}document.addEventListener("focusin",e),document.addEventListener("focusout",t);const i=new MutationObserver(r);return c&&i.observe(c,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",e),document.removeEventListener("focusout",t),i.disconnect()}}}),[n,c,f.paused]),t.useEffect((()=>{if(c){hT.add(f);const t=document.activeElement;if(!c.contains(t)){const r=new CustomEvent(sT,aT);c.addEventListener(sT,l),c.dispatchEvent(r),r.defaultPrevented||(!function(e,{select:t=!1}={}){const r=document.activeElement;for(const i of e)if(pT(i,{select:t}),document.activeElement!==r)return}((e=dT(c),e.filter((e=>"A"!==e.tagName))),{select:!0}),document.activeElement===t&&pT(c))}return()=>{c.removeEventListener(sT,l),setTimeout((()=>{const e=new CustomEvent(oT,aT);c.addEventListener(oT,u),c.dispatchEvent(e),e.defaultPrevented||pT(null!=t?t:document.body,{select:!0}),c.removeEventListener(oT,u),hT.remove(f)}),0)}}var e}),[c,l,u,f]);const m=t.useCallback((e=>{if(!i&&!n)return;if(f.paused)return;const t="Tab"===e.key&&!e.altKey&&!e.ctrlKey&&!e.metaKey,r=document.activeElement;if(t&&r){const t=e.currentTarget,[n,s]=function(e){const t=dT(e),r=lT(t,e),i=lT(t.reverse(),e);return[r,i]}(t);n&&s?e.shiftKey||r!==s?e.shiftKey&&r===n&&(e.preventDefault(),i&&pT(s,{select:!0})):(e.preventDefault(),i&&pT(n,{select:!0})):r===t&&e.preventDefault()}}),[i,n,f.paused]);return t.createElement(Wk.div,Ak({tabIndex:-1},a,{ref:h,onKeyDown:m}))}));function dT(e){const t=[],r=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:e=>{const t="INPUT"===e.tagName&&"hidden"===e.type;return e.disabled||e.hidden||t?NodeFilter.FILTER_SKIP:e.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;r.nextNode();)t.push(r.currentNode);return t}function lT(e,t){for(const r of e)if(!uT(r,{upTo:t}))return r}function uT(e,{upTo:t}){if("hidden"===getComputedStyle(e).visibility)return!0;for(;e;){if(void 0!==t&&e===t)return!1;if("none"===getComputedStyle(e).display)return!0;e=e.parentElement}return!1}function pT(e,{select:t=!1}={}){if(e&&e.focus){const r=document.activeElement;e.focus({preventScroll:!0}),e!==r&&function(e){return e instanceof HTMLInputElement&&"select"in e}(e)&&t&&e.select()}}const hT=function(){let e=[];return{add(t){const r=e[0];t!==r&&(null==r||r.pause()),e=fT(e,t),e.unshift(t)},remove(t){var r;e=fT(e,t),null===(r=e[0])||void 0===r||r.resume()}}}();function fT(e,t){const r=[...e],i=r.indexOf(t);return-1!==i&&r.splice(i,1),r}const mT=Boolean(null===globalThis||void 0===globalThis?void 0:globalThis.document)?t.useLayoutEffect:()=>{},gT=s["useId".toString()]||(()=>{});let vT=0;function bT(e){const[t,r]=s.useState(gT());return mT((()=>{e||r((e=>null!=e?e:String(vT++)))}),[e]),e||(t?`radix-${t}`:"")}const yT=["top","right","bottom","left"],wT=Math.min,_T=Math.max,ST=Math.round,CT=Math.floor,RT=e=>({x:e,y:e}),kT={left:"right",right:"left",bottom:"top",top:"bottom"},TT={start:"end",end:"start"};function PT(e,t,r){return _T(e,wT(t,r))}function ET(e,t){return"function"==typeof e?e(t):e}function OT(e){return e.split("-")[0]}function DT(e){return e.split("-")[1]}function IT(e){return"x"===e?"y":"x"}function xT(e){return"y"===e?"height":"width"}function MT(e){return["top","bottom"].includes(OT(e))?"y":"x"}function LT(e){return IT(MT(e))}function jT(e){return e.replace(/start|end/g,(e=>TT[e]))}function AT(e){return e.replace(/left|right|bottom|top/g,(e=>kT[e]))}function NT(e){return"number"!=typeof e?function(e){return{top:0,right:0,bottom:0,left:0,...e}}(e):{top:e,right:e,bottom:e,left:e}}function BT(e){const{x:t,y:r,width:i,height:n}=e;return{width:i,height:n,top:r,left:t,right:t+i,bottom:r+n,x:t,y:r}}function FT(e,t,r){let{reference:i,floating:n}=e;const s=MT(t),o=LT(t),a=xT(o),c=OT(t),d="y"===s,l=i.x+i.width/2-n.width/2,u=i.y+i.height/2-n.height/2,p=i[a]/2-n[a]/2;let h;switch(c){case"top":h={x:l,y:i.y-n.height};break;case"bottom":h={x:l,y:i.y+i.height};break;case"right":h={x:i.x+i.width,y:u};break;case"left":h={x:i.x-n.width,y:u};break;default:h={x:i.x,y:i.y}}switch(DT(t)){case"start":h[o]-=p*(r&&d?-1:1);break;case"end":h[o]+=p*(r&&d?-1:1)}return h}async function zT(e,t){var r;void 0===t&&(t={});const{x:i,y:n,platform:s,rects:o,elements:a,strategy:c}=e,{boundary:d="clippingAncestors",rootBoundary:l="viewport",elementContext:u="floating",altBoundary:p=!1,padding:h=0}=ET(t,e),f=NT(h),m=a[p?"floating"===u?"reference":"floating":u],g=BT(await s.getClippingRect({element:null==(r=await(null==s.isElement?void 0:s.isElement(m)))||r?m:m.contextElement||await(null==s.getDocumentElement?void 0:s.getDocumentElement(a.floating)),boundary:d,rootBoundary:l,strategy:c})),v="floating"===u?{x:i,y:n,width:o.floating.width,height:o.floating.height}:o.reference,b=await(null==s.getOffsetParent?void 0:s.getOffsetParent(a.floating)),y=await(null==s.isElement?void 0:s.isElement(b))&&await(null==s.getScale?void 0:s.getScale(b))||{x:1,y:1},w=BT(s.convertOffsetParentRelativeRectToViewportRelativeRect?await s.convertOffsetParentRelativeRectToViewportRelativeRect({elements:a,rect:v,offsetParent:b,strategy:c}):v);return{top:(g.top-w.top+f.top)/y.y,bottom:(w.bottom-g.bottom+f.bottom)/y.y,left:(g.left-w.left+f.left)/y.x,right:(w.right-g.right+f.right)/y.x}}function VT(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function UT(e){return yT.some((t=>e[t]>=0))}function $T(e){return HT(e)?(e.nodeName||"").toLowerCase():"#document"}function GT(e){var t;return(null==e||null==(t=e.ownerDocument)?void 0:t.defaultView)||window}function qT(e){var t;return null==(t=(HT(e)?e.ownerDocument:e.document)||window.document)?void 0:t.documentElement}function HT(e){return e instanceof Node||e instanceof GT(e).Node}function WT(e){return e instanceof Element||e instanceof GT(e).Element}function KT(e){return e instanceof HTMLElement||e instanceof GT(e).HTMLElement}function JT(e){return"undefined"!=typeof ShadowRoot&&(e instanceof ShadowRoot||e instanceof GT(e).ShadowRoot)}function XT(e){const{overflow:t,overflowX:r,overflowY:i,display:n}=tP(e);return/auto|scroll|overlay|hidden|clip/.test(t+i+r)&&!["inline","contents"].includes(n)}function QT(e){return["table","td","th"].includes($T(e))}function ZT(e){const t=YT(),r=tP(e);return"none"!==r.transform||"none"!==r.perspective||!!r.containerType&&"normal"!==r.containerType||!t&&!!r.backdropFilter&&"none"!==r.backdropFilter||!t&&!!r.filter&&"none"!==r.filter||["transform","perspective","filter"].some((e=>(r.willChange||"").includes(e)))||["paint","layout","strict","content"].some((e=>(r.contain||"").includes(e)))}function YT(){return!("undefined"==typeof CSS||!CSS.supports)&&CSS.supports("-webkit-backdrop-filter","none")}function eP(e){return["html","body","#document"].includes($T(e))}function tP(e){return GT(e).getComputedStyle(e)}function rP(e){return WT(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.pageXOffset,scrollTop:e.pageYOffset}}function iP(e){if("html"===$T(e))return e;const t=e.assignedSlot||e.parentNode||JT(e)&&e.host||qT(e);return JT(t)?t.host:t}function nP(e){const t=iP(e);return eP(t)?e.ownerDocument?e.ownerDocument.body:e.body:KT(t)&&XT(t)?t:nP(t)}function sP(e,t,r){var i;void 0===t&&(t=[]),void 0===r&&(r=!0);const n=nP(e),s=n===(null==(i=e.ownerDocument)?void 0:i.body),o=GT(n);return s?t.concat(o,o.visualViewport||[],XT(n)?n:[],o.frameElement&&r?sP(o.frameElement):[]):t.concat(n,sP(n,[],r))}function oP(e){const t=tP(e);let r=parseFloat(t.width)||0,i=parseFloat(t.height)||0;const n=KT(e),s=n?e.offsetWidth:r,o=n?e.offsetHeight:i,a=ST(r)!==s||ST(i)!==o;return a&&(r=s,i=o),{width:r,height:i,$:a}}function aP(e){return WT(e)?e:e.contextElement}function cP(e){const t=aP(e);if(!KT(t))return RT(1);const r=t.getBoundingClientRect(),{width:i,height:n,$:s}=oP(t);let o=(s?ST(r.width):r.width)/i,a=(s?ST(r.height):r.height)/n;return o&&Number.isFinite(o)||(o=1),a&&Number.isFinite(a)||(a=1),{x:o,y:a}}const dP=RT(0);function lP(e){const t=GT(e);return YT()&&t.visualViewport?{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}:dP}function uP(e,t,r,i){void 0===t&&(t=!1),void 0===r&&(r=!1);const n=e.getBoundingClientRect(),s=aP(e);let o=RT(1);t&&(i?WT(i)&&(o=cP(i)):o=cP(e));const a=function(e,t,r){return void 0===t&&(t=!1),!(!r||t&&r!==GT(e))&&t}(s,r,i)?lP(s):RT(0);let c=(n.left+a.x)/o.x,d=(n.top+a.y)/o.y,l=n.width/o.x,u=n.height/o.y;if(s){const e=GT(s),t=i&&WT(i)?GT(i):i;let r=e,n=r.frameElement;for(;n&&i&&t!==r;){const e=cP(n),t=n.getBoundingClientRect(),i=tP(n),s=t.left+(n.clientLeft+parseFloat(i.paddingLeft))*e.x,o=t.top+(n.clientTop+parseFloat(i.paddingTop))*e.y;c*=e.x,d*=e.y,l*=e.x,u*=e.y,c+=s,d+=o,r=GT(n),n=r.frameElement}}return BT({width:l,height:u,x:c,y:d})}const pP=[":popover-open",":modal"];function hP(e){return pP.some((t=>{try{return e.matches(t)}catch(e){return!1}}))}function fP(e){return uP(qT(e)).left+rP(e).scrollLeft}function mP(e,t,r){let i;if("viewport"===t)i=function(e,t){const r=GT(e),i=qT(e),n=r.visualViewport;let s=i.clientWidth,o=i.clientHeight,a=0,c=0;if(n){s=n.width,o=n.height;const e=YT();(!e||e&&"fixed"===t)&&(a=n.offsetLeft,c=n.offsetTop)}return{width:s,height:o,x:a,y:c}}(e,r);else if("document"===t)i=function(e){const t=qT(e),r=rP(e),i=e.ownerDocument.body,n=_T(t.scrollWidth,t.clientWidth,i.scrollWidth,i.clientWidth),s=_T(t.scrollHeight,t.clientHeight,i.scrollHeight,i.clientHeight);let o=-r.scrollLeft+fP(e);const a=-r.scrollTop;return"rtl"===tP(i).direction&&(o+=_T(t.clientWidth,i.clientWidth)-n),{width:n,height:s,x:o,y:a}}(qT(e));else if(WT(t))i=function(e,t){const r=uP(e,!0,"fixed"===t),i=r.top+e.clientTop,n=r.left+e.clientLeft,s=KT(e)?cP(e):RT(1);return{width:e.clientWidth*s.x,height:e.clientHeight*s.y,x:n*s.x,y:i*s.y}}(t,r);else{const r=lP(e);i={...t,x:t.x-r.x,y:t.y-r.y}}return BT(i)}function gP(e,t){const r=iP(e);return!(r===t||!WT(r)||eP(r))&&("fixed"===tP(r).position||gP(r,t))}function vP(e,t,r){const i=KT(t),n=qT(t),s="fixed"===r,o=uP(e,!0,s,t);let a={scrollLeft:0,scrollTop:0};const c=RT(0);if(i||!i&&!s)if(("body"!==$T(t)||XT(n))&&(a=rP(t)),i){const e=uP(t,!0,s,t);c.x=e.x+t.clientLeft,c.y=e.y+t.clientTop}else n&&(c.x=fP(n));return{x:o.left+a.scrollLeft-c.x,y:o.top+a.scrollTop-c.y,width:o.width,height:o.height}}function bP(e){return"static"===tP(e).position}function yP(e,t){return KT(e)&&"fixed"!==tP(e).position?t?t(e):e.offsetParent:null}function wP(e,t){const r=GT(e);if(hP(e))return r;if(!KT(e)){let t=iP(e);for(;t&&!eP(t);){if(WT(t)&&!bP(t))return t;t=iP(t)}return r}let i=yP(e,t);for(;i&&QT(i)&&bP(i);)i=yP(i,t);return i&&eP(i)&&bP(i)&&!ZT(i)?r:i||function(e){let t=iP(e);for(;KT(t)&&!eP(t);){if(ZT(t))return t;t=iP(t)}return null}(e)||r}const _P={convertOffsetParentRelativeRectToViewportRelativeRect:function(e){let{elements:t,rect:r,offsetParent:i,strategy:n}=e;const s="fixed"===n,o=qT(i),a=!!t&&hP(t.floating);if(i===o||a&&s)return r;let c={scrollLeft:0,scrollTop:0},d=RT(1);const l=RT(0),u=KT(i);if((u||!u&&!s)&&(("body"!==$T(i)||XT(o))&&(c=rP(i)),KT(i))){const e=uP(i);d=cP(i),l.x=e.x+i.clientLeft,l.y=e.y+i.clientTop}return{width:r.width*d.x,height:r.height*d.y,x:r.x*d.x-c.scrollLeft*d.x+l.x,y:r.y*d.y-c.scrollTop*d.y+l.y}},getDocumentElement:qT,getClippingRect:function(e){let{element:t,boundary:r,rootBoundary:i,strategy:n}=e;const s="clippingAncestors"===r?hP(t)?[]:function(e,t){const r=t.get(e);if(r)return r;let i=sP(e,[],!1).filter((e=>WT(e)&&"body"!==$T(e))),n=null;const s="fixed"===tP(e).position;let o=s?iP(e):e;for(;WT(o)&&!eP(o);){const t=tP(o),r=ZT(o);r||"fixed"!==t.position||(n=null),(s?!r&&!n:!r&&"static"===t.position&&n&&["absolute","fixed"].includes(n.position)||XT(o)&&!r&&gP(e,o))?i=i.filter((e=>e!==o)):n=t,o=iP(o)}return t.set(e,i),i}(t,this._c):[].concat(r),o=[...s,i],a=o[0],c=o.reduce(((e,r)=>{const i=mP(t,r,n);return e.top=_T(i.top,e.top),e.right=wT(i.right,e.right),e.bottom=wT(i.bottom,e.bottom),e.left=_T(i.left,e.left),e}),mP(t,a,n));return{width:c.right-c.left,height:c.bottom-c.top,x:c.left,y:c.top}},getOffsetParent:wP,getElementRects:async function(e){const t=this.getOffsetParent||wP,r=this.getDimensions,i=await r(e.floating);return{reference:vP(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:i.width,height:i.height}}},getClientRects:function(e){return Array.from(e.getClientRects())},getDimensions:function(e){const{width:t,height:r}=oP(e);return{width:t,height:r}},getScale:cP,isElement:WT,isRTL:function(e){return"rtl"===tP(e).direction}};function SP(e,t,r,i){void 0===i&&(i={});const{ancestorScroll:n=!0,ancestorResize:s=!0,elementResize:o="function"==typeof ResizeObserver,layoutShift:a="function"==typeof IntersectionObserver,animationFrame:c=!1}=i,d=aP(e),l=n||s?[...d?sP(d):[],...sP(t)]:[];l.forEach((e=>{n&&e.addEventListener("scroll",r,{passive:!0}),s&&e.addEventListener("resize",r)}));const u=d&&a?function(e,t){let r,i=null;const n=qT(e);function s(){var e;clearTimeout(r),null==(e=i)||e.disconnect(),i=null}return function o(a,c){void 0===a&&(a=!1),void 0===c&&(c=1),s();const{left:d,top:l,width:u,height:p}=e.getBoundingClientRect();if(a||t(),!u||!p)return;const h={rootMargin:-CT(l)+"px "+-CT(n.clientWidth-(d+u))+"px "+-CT(n.clientHeight-(l+p))+"px "+-CT(d)+"px",threshold:_T(0,wT(1,c))||1};let f=!0;function m(e){const t=e[0].intersectionRatio;if(t!==c){if(!f)return o();t?o(!1,t):r=setTimeout((()=>{o(!1,1e-7)}),1e3)}f=!1}try{i=new IntersectionObserver(m,{...h,root:n.ownerDocument})}catch(e){i=new IntersectionObserver(m,h)}i.observe(e)}(!0),s}(d,r):null;let p,h=-1,f=null;o&&(f=new ResizeObserver((e=>{let[i]=e;i&&i.target===d&&f&&(f.unobserve(t),cancelAnimationFrame(h),h=requestAnimationFrame((()=>{var e;null==(e=f)||e.observe(t)}))),r()})),d&&!c&&f.observe(d),f.observe(t));let m=c?uP(e):null;return c&&function t(){const i=uP(e);!m||i.x===m.x&&i.y===m.y&&i.width===m.width&&i.height===m.height||r();m=i,p=requestAnimationFrame(t)}(),r(),()=>{var e;l.forEach((e=>{n&&e.removeEventListener("scroll",r),s&&e.removeEventListener("resize",r)})),null==u||u(),null==(e=f)||e.disconnect(),f=null,c&&cancelAnimationFrame(p)}}const CP=function(e){return void 0===e&&(e=0),{name:"offset",options:e,async fn(t){var r,i;const{x:n,y:s,placement:o,middlewareData:a}=t,c=await async function(e,t){const{placement:r,platform:i,elements:n}=e,s=await(null==i.isRTL?void 0:i.isRTL(n.floating)),o=OT(r),a=DT(r),c="y"===MT(r),d=["left","top"].includes(o)?-1:1,l=s&&c?-1:1,u=ET(t,e);let{mainAxis:p,crossAxis:h,alignmentAxis:f}="number"==typeof u?{mainAxis:u,crossAxis:0,alignmentAxis:null}:{mainAxis:0,crossAxis:0,alignmentAxis:null,...u};return a&&"number"==typeof f&&(h="end"===a?-1*f:f),c?{x:h*l,y:p*d}:{x:p*d,y:h*l}}(t,e);return o===(null==(r=a.offset)?void 0:r.placement)&&null!=(i=a.arrow)&&i.alignmentOffset?{}:{x:n+c.x,y:s+c.y,data:{...c,placement:o}}}}},RP=function(e){return void 0===e&&(e={}),{name:"shift",options:e,async fn(t){const{x:r,y:i,placement:n}=t,{mainAxis:s=!0,crossAxis:o=!1,limiter:a={fn:e=>{let{x:t,y:r}=e;return{x:t,y:r}}},...c}=ET(e,t),d={x:r,y:i},l=await zT(t,c),u=MT(OT(n)),p=IT(u);let h=d[p],f=d[u];if(s){const e="y"===p?"bottom":"right";h=PT(h+l["y"===p?"top":"left"],h,h-l[e])}if(o){const e="y"===u?"bottom":"right";f=PT(f+l["y"===u?"top":"left"],f,f-l[e])}const m=a.fn({...t,[p]:h,[u]:f});return{...m,data:{x:m.x-r,y:m.y-i}}}}},kP=function(e){return void 0===e&&(e={}),{name:"flip",options:e,async fn(t){var r,i;const{placement:n,middlewareData:s,rects:o,initialPlacement:a,platform:c,elements:d}=t,{mainAxis:l=!0,crossAxis:u=!0,fallbackPlacements:p,fallbackStrategy:h="bestFit",fallbackAxisSideDirection:f="none",flipAlignment:m=!0,...g}=ET(e,t);if(null!=(r=s.arrow)&&r.alignmentOffset)return{};const v=OT(n),b=OT(a)===a,y=await(null==c.isRTL?void 0:c.isRTL(d.floating)),w=p||(b||!m?[AT(a)]:function(e){const t=AT(e);return[jT(e),t,jT(t)]}(a));p||"none"===f||w.push(...function(e,t,r,i){const n=DT(e);let s=function(e,t,r){const i=["left","right"],n=["right","left"],s=["top","bottom"],o=["bottom","top"];switch(e){case"top":case"bottom":return r?t?n:i:t?i:n;case"left":case"right":return t?s:o;default:return[]}}(OT(e),"start"===r,i);return n&&(s=s.map((e=>e+"-"+n)),t&&(s=s.concat(s.map(jT)))),s}(a,m,f,y));const _=[a,...w],S=await zT(t,g),C=[];let R=(null==(i=s.flip)?void 0:i.overflows)||[];if(l&&C.push(S[v]),u){const e=function(e,t,r){void 0===r&&(r=!1);const i=DT(e),n=LT(e),s=xT(n);let o="x"===n?i===(r?"end":"start")?"right":"left":"start"===i?"bottom":"top";return t.reference[s]>t.floating[s]&&(o=AT(o)),[o,AT(o)]}(n,o,y);C.push(S[e[0]],S[e[1]])}if(R=[...R,{placement:n,overflows:C}],!C.every((e=>e<=0))){var k,T;const e=((null==(k=s.flip)?void 0:k.index)||0)+1,t=_[e];if(t)return{data:{index:e,overflows:R},reset:{placement:t}};let r=null==(T=R.filter((e=>e.overflows[0]<=0)).sort(((e,t)=>e.overflows[1]-t.overflows[1]))[0])?void 0:T.placement;if(!r)switch(h){case"bestFit":{var P;const e=null==(P=R.map((e=>[e.placement,e.overflows.filter((e=>e>0)).reduce(((e,t)=>e+t),0)])).sort(((e,t)=>e[1]-t[1]))[0])?void 0:P[0];e&&(r=e);break}case"initialPlacement":r=a}if(n!==r)return{reset:{placement:r}}}return{}}}},TP=function(e){return void 0===e&&(e={}),{name:"size",options:e,async fn(t){const{placement:r,rects:i,platform:n,elements:s}=t,{apply:o=(()=>{}),...a}=ET(e,t),c=await zT(t,a),d=OT(r),l=DT(r),u="y"===MT(r),{width:p,height:h}=i.floating;let f,m;"top"===d||"bottom"===d?(f=d,m=l===(await(null==n.isRTL?void 0:n.isRTL(s.floating))?"start":"end")?"left":"right"):(m=d,f="end"===l?"top":"bottom");const g=h-c.top-c.bottom,v=p-c.left-c.right,b=wT(h-c[f],g),y=wT(p-c[m],v),w=!t.middlewareData.shift;let _=b,S=y;if(u?S=l||w?wT(y,v):v:_=l||w?wT(b,g):g,w&&!l){const e=_T(c.left,0),t=_T(c.right,0),r=_T(c.top,0),i=_T(c.bottom,0);u?S=p-2*(0!==e||0!==t?e+t:_T(c.left,c.right)):_=h-2*(0!==r||0!==i?r+i:_T(c.top,c.bottom))}await o({...t,availableWidth:S,availableHeight:_});const C=await n.getDimensions(s.floating);return p!==C.width||h!==C.height?{reset:{rects:!0}}:{}}}},PP=function(e){return void 0===e&&(e={}),{name:"hide",options:e,async fn(t){const{rects:r}=t,{strategy:i="referenceHidden",...n}=ET(e,t);switch(i){case"referenceHidden":{const e=VT(await zT(t,{...n,elementContext:"reference"}),r.reference);return{data:{referenceHiddenOffsets:e,referenceHidden:UT(e)}}}case"escaped":{const e=VT(await zT(t,{...n,altBoundary:!0}),r.floating);return{data:{escapedOffsets:e,escaped:UT(e)}}}default:return{}}}}},EP=e=>({name:"arrow",options:e,async fn(t){const{x:r,y:i,placement:n,rects:s,platform:o,elements:a,middlewareData:c}=t,{element:d,padding:l=0}=ET(e,t)||{};if(null==d)return{};const u=NT(l),p={x:r,y:i},h=LT(n),f=xT(h),m=await o.getDimensions(d),g="y"===h,v=g?"top":"left",b=g?"bottom":"right",y=g?"clientHeight":"clientWidth",w=s.reference[f]+s.reference[h]-p[h]-s.floating[f],_=p[h]-s.reference[h],S=await(null==o.getOffsetParent?void 0:o.getOffsetParent(d));let C=S?S[y]:0;C&&await(null==o.isElement?void 0:o.isElement(S))||(C=a.floating[y]||s.floating[f]);const R=w/2-_/2,k=C/2-m[f]/2-1,T=wT(u[v],k),P=wT(u[b],k),E=T,O=C-m[f]-P,D=C/2-m[f]/2+R,I=PT(E,D,O),x=!c.arrow&&null!=DT(n)&&D!==I&&s.reference[f]/2-(D<E?T:P)-m[f]/2<0,M=x?D<E?D-E:D-O:0;return{[h]:p[h]+M,data:{[h]:I,centerOffset:D-I-M,...x&&{alignmentOffset:M}},reset:x}}}),OP=function(e){return void 0===e&&(e={}),{options:e,fn(t){const{x:r,y:i,placement:n,rects:s,middlewareData:o}=t,{offset:a=0,mainAxis:c=!0,crossAxis:d=!0}=ET(e,t),l={x:r,y:i},u=MT(n),p=IT(u);let h=l[p],f=l[u];const m=ET(a,t),g="number"==typeof m?{mainAxis:m,crossAxis:0}:{mainAxis:0,crossAxis:0,...m};if(c){const e="y"===p?"height":"width",t=s.reference[p]-s.floating[e]+g.mainAxis,r=s.reference[p]+s.reference[e]-g.mainAxis;h<t?h=t:h>r&&(h=r)}if(d){var v,b;const e="y"===p?"width":"height",t=["top","left"].includes(OT(n)),r=s.reference[u]-s.floating[e]+(t&&(null==(v=o.offset)?void 0:v[u])||0)+(t?0:g.crossAxis),i=s.reference[u]+s.reference[e]+(t?0:(null==(b=o.offset)?void 0:b[u])||0)-(t?g.crossAxis:0);f<r?f=r:f>i&&(f=i)}return{[p]:h,[u]:f}}}},DP=(e,t,r)=>{const i=new Map,n={platform:_P,...r},s={...n.platform,_c:i};return(async(e,t,r)=>{const{placement:i="bottom",strategy:n="absolute",middleware:s=[],platform:o}=r,a=s.filter(Boolean),c=await(null==o.isRTL?void 0:o.isRTL(t));let d=await o.getElementRects({reference:e,floating:t,strategy:n}),{x:l,y:u}=FT(d,i,c),p=i,h={},f=0;for(let r=0;r<a.length;r++){const{name:s,fn:m}=a[r],{x:g,y:v,data:b,reset:y}=await m({x:l,y:u,initialPlacement:i,placement:p,strategy:n,middlewareData:h,rects:d,platform:o,elements:{reference:e,floating:t}});l=null!=g?g:l,u=null!=v?v:u,h={...h,[s]:{...h[s],...b}},y&&f<=50&&(f++,"object"==typeof y&&(y.placement&&(p=y.placement),y.rects&&(d=!0===y.rects?await o.getElementRects({reference:e,floating:t,strategy:n}):y.rects),({x:l,y:u}=FT(d,p,c))),r=-1)}return{x:l,y:u,placement:p,strategy:n,middlewareData:h}})(e,t,{...n,platform:s})};var IP="undefined"!=typeof document?t.useLayoutEffect:t.useEffect;function xP(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if("function"==typeof e&&e.toString()===t.toString())return!0;let r,i,n;if(e&&t&&"object"==typeof e){if(Array.isArray(e)){if(r=e.length,r!==t.length)return!1;for(i=r;0!=i--;)if(!xP(e[i],t[i]))return!1;return!0}if(n=Object.keys(e),r=n.length,r!==Object.keys(t).length)return!1;for(i=r;0!=i--;)if(!{}.hasOwnProperty.call(t,n[i]))return!1;for(i=r;0!=i--;){const r=n[i];if(("_owner"!==r||!e.$$typeof)&&!xP(e[r],t[r]))return!1}return!0}return e!=e&&t!=t}function MP(e){if("undefined"==typeof window)return 1;return(e.ownerDocument.defaultView||window).devicePixelRatio||1}function LP(e,t){const r=MP(e);return Math.round(t*r)/r}function jP(e){const t=s.useRef(e);return IP((()=>{t.current=e})),t}const AP=e=>({name:"arrow",options:e,fn(t){const{element:r,padding:i}="function"==typeof e?e(t):e;return r&&function(e){return{}.hasOwnProperty.call(e,"current")}(r)?null!=r.current?EP({element:r.current,padding:i}).fn(t):{}:r?EP({element:r,padding:i}).fn(t):{}}}),NP=(e,t)=>({...CP(e),options:[e,t]}),BP=(e,t)=>({...RP(e),options:[e,t]}),FP=(e,t)=>({...OP(e),options:[e,t]}),zP=(e,t)=>({...kP(e),options:[e,t]}),VP=(e,t)=>({...TP(e),options:[e,t]}),UP=(e,t)=>({...PP(e),options:[e,t]}),$P=(e,t)=>({...AP(e),options:[e,t]});const GP="Popper",[qP,HP]=zk(GP),[WP,KP]=qP(GP),JP=t.forwardRef(((e,r)=>{const{__scopePopper:i,virtualRef:n,...s}=e,o=KP("PopperAnchor",i),a=t.useRef(null),c=Fk(r,a);return t.useEffect((()=>{o.onAnchorChange((null==n?void 0:n.current)||a.current)})),n?null:t.createElement(Wk.div,Ak({},s,{ref:c}))})),XP="PopperContent",[QP,ZP]=qP(XP),YP=t.forwardRef(((e,r)=>{var i,n,a,c,d,l,u,p;const{__scopePopper:h,side:f="bottom",sideOffset:m=0,align:g="center",alignOffset:v=0,arrowPadding:b=0,avoidCollisions:y=!0,collisionBoundary:w=[],collisionPadding:_=0,sticky:S="partial",hideWhenDetached:C=!1,updatePositionStrategy:R="optimized",onPlaced:k,...T}=e,P=KP(XP,h),[E,O]=t.useState(null),D=Fk(r,(e=>O(e))),[I,x]=t.useState(null),M=function(e){const[r,i]=t.useState(void 0);return mT((()=>{if(e){i({width:e.offsetWidth,height:e.offsetHeight});const t=new ResizeObserver((t=>{if(!Array.isArray(t))return;if(!t.length)return;const r=t[0];let n,s;if("borderBoxSize"in r){const e=r.borderBoxSize,t=Array.isArray(e)?e[0]:e;n=t.inlineSize,s=t.blockSize}else n=e.offsetWidth,s=e.offsetHeight;i({width:n,height:s})}));return t.observe(e,{box:"border-box"}),()=>t.unobserve(e)}i(void 0)}),[e]),r}(I),L=null!==(i=null==M?void 0:M.width)&&void 0!==i?i:0,j=null!==(n=null==M?void 0:M.height)&&void 0!==n?n:0,A=f+("center"!==g?"-"+g:""),N="number"==typeof _?_:{top:0,right:0,bottom:0,left:0,..._},B=Array.isArray(w)?w:[w],F=B.length>0,z={padding:N,boundary:B.filter(eE),altBoundary:F},{refs:V,floatingStyles:U,placement:$,isPositioned:G,middlewareData:q}=function(e){void 0===e&&(e={});const{placement:t="bottom",strategy:r="absolute",middleware:i=[],platform:n,elements:{reference:a,floating:c}={},transform:d=!0,whileElementsMounted:l,open:u}=e,[p,h]=s.useState({x:0,y:0,strategy:r,placement:t,middlewareData:{},isPositioned:!1}),[f,m]=s.useState(i);xP(f,i)||m(i);const[g,v]=s.useState(null),[b,y]=s.useState(null),w=s.useCallback((e=>{e!==R.current&&(R.current=e,v(e))}),[]),_=s.useCallback((e=>{e!==k.current&&(k.current=e,y(e))}),[]),S=a||g,C=c||b,R=s.useRef(null),k=s.useRef(null),T=s.useRef(p),P=null!=l,E=jP(l),O=jP(n),D=s.useCallback((()=>{if(!R.current||!k.current)return;const e={placement:t,strategy:r,middleware:f};O.current&&(e.platform=O.current),DP(R.current,k.current,e).then((e=>{const t={...e,isPositioned:!0};I.current&&!xP(T.current,t)&&(T.current=t,o.flushSync((()=>{h(t)})))}))}),[f,t,r,O]);IP((()=>{!1===u&&T.current.isPositioned&&(T.current.isPositioned=!1,h((e=>({...e,isPositioned:!1}))))}),[u]);const I=s.useRef(!1);IP((()=>(I.current=!0,()=>{I.current=!1})),[]),IP((()=>{if(S&&(R.current=S),C&&(k.current=C),S&&C){if(E.current)return E.current(S,C,D);D()}}),[S,C,D,E,P]);const x=s.useMemo((()=>({reference:R,floating:k,setReference:w,setFloating:_})),[w,_]),M=s.useMemo((()=>({reference:S,floating:C})),[S,C]),L=s.useMemo((()=>{const e={position:r,left:0,top:0};if(!M.floating)return e;const t=LP(M.floating,p.x),i=LP(M.floating,p.y);return d?{...e,transform:"translate("+t+"px, "+i+"px)",...MP(M.floating)>=1.5&&{willChange:"transform"}}:{position:r,left:t,top:i}}),[r,d,M.floating,p.x,p.y]);return s.useMemo((()=>({...p,update:D,refs:x,elements:M,floatingStyles:L})),[p,D,x,M,L])}({strategy:"fixed",placement:A,whileElementsMounted:(...e)=>SP(...e,{animationFrame:"always"===R}),elements:{reference:P.anchor},middleware:[NP({mainAxis:m+j,alignmentAxis:v}),y&&BP({mainAxis:!0,crossAxis:!1,limiter:"partial"===S?FP():void 0,...z}),y&&zP({...z}),VP({...z,apply:({elements:e,rects:t,availableWidth:r,availableHeight:i})=>{const{width:n,height:s}=t.reference,o=e.floating.style;o.setProperty("--radix-popper-available-width",`${r}px`),o.setProperty("--radix-popper-available-height",`${i}px`),o.setProperty("--radix-popper-anchor-width",`${n}px`),o.setProperty("--radix-popper-anchor-height",`${s}px`)}}),I&&$P({element:I,padding:b}),tE({arrowWidth:L,arrowHeight:j}),C&&UP({strategy:"referenceHidden",...z})]}),[H,W]=rE($),K=Kk(k);mT((()=>{G&&(null==K||K())}),[G,K]);const J=null===(a=q.arrow)||void 0===a?void 0:a.x,X=null===(c=q.arrow)||void 0===c?void 0:c.y,Q=0!==(null===(d=q.arrow)||void 0===d?void 0:d.centerOffset),[Z,Y]=t.useState();return mT((()=>{E&&Y(window.getComputedStyle(E).zIndex)}),[E]),t.createElement("div",{ref:V.setFloating,"data-radix-popper-content-wrapper":"",style:{...U,transform:G?U.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:Z,"--radix-popper-transform-origin":[null===(l=q.transformOrigin)||void 0===l?void 0:l.x,null===(u=q.transformOrigin)||void 0===u?void 0:u.y].join(" ")},dir:e.dir},t.createElement(QP,{scope:h,placedSide:H,onArrowChange:x,arrowX:J,arrowY:X,shouldHideArrow:Q},t.createElement(Wk.div,Ak({"data-side":H,"data-align":W},T,{ref:D,style:{...T.style,animation:G?void 0:"none",opacity:null!==(p=q.hide)&&void 0!==p&&p.referenceHidden?0:void 0}}))))}));function eE(e){return null!==e}const tE=e=>({name:"transformOrigin",options:e,fn(t){var r,i,n,s,o;const{placement:a,rects:c,middlewareData:d}=t,l=0!==(null===(r=d.arrow)||void 0===r?void 0:r.centerOffset),u=l?0:e.arrowWidth,p=l?0:e.arrowHeight,[h,f]=rE(a),m={start:"0%",center:"50%",end:"100%"}[f],g=(null!==(i=null===(n=d.arrow)||void 0===n?void 0:n.x)&&void 0!==i?i:0)+u/2,v=(null!==(s=null===(o=d.arrow)||void 0===o?void 0:o.y)&&void 0!==s?s:0)+p/2;let b="",y="";return"bottom"===h?(b=l?m:`${g}px`,y=-p+"px"):"top"===h?(b=l?m:`${g}px`,y=`${c.floating.height+p}px`):"right"===h?(b=-p+"px",y=l?m:`${v}px`):"left"===h&&(b=`${c.floating.width+p}px`,y=l?m:`${v}px`),{data:{x:b,y:y}}}});function rE(e){const[t,r="center"]=e.split("-");return[t,r]}const iE=e=>{const{__scopePopper:r,children:i}=e,[n,s]=t.useState(null);return t.createElement(WP,{scope:r,anchor:n,onAnchorChange:s},i)},nE=JP,sE=YP,oE=t.forwardRef(((e,i)=>{var n;const{container:s=(null===globalThis||void 0===globalThis||null===(n=globalThis.document)||void 0===n?void 0:n.body),...o}=e;return s?r.createPortal(t.createElement(Wk.div,Ak({},o,{ref:i})),s):null}));const aE=e=>{const{present:i,children:n}=e,s=function(e){const[i,n]=t.useState(),s=t.useRef({}),o=t.useRef(e),a=t.useRef("none"),c=e?"mounted":"unmounted",[d,l]=function(e,r){return t.useReducer(((e,t)=>{const i=r[e][t];return null!=i?i:e}),e)}(c,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return t.useEffect((()=>{const e=cE(s.current);a.current="mounted"===d?e:"none"}),[d]),mT((()=>{const t=s.current,r=o.current;if(r!==e){const i=a.current,n=cE(t);if(e)l("MOUNT");else if("none"===n||"none"===(null==t?void 0:t.display))l("UNMOUNT");else{l(r&&i!==n?"ANIMATION_OUT":"UNMOUNT")}o.current=e}}),[e,l]),mT((()=>{if(i){const e=e=>{const t=cE(s.current).includes(e.animationName);e.target===i&&t&&r.flushSync((()=>l("ANIMATION_END")))},t=e=>{e.target===i&&(a.current=cE(s.current))};return i.addEventListener("animationstart",t),i.addEventListener("animationcancel",e),i.addEventListener("animationend",e),()=>{i.removeEventListener("animationstart",t),i.removeEventListener("animationcancel",e),i.removeEventListener("animationend",e)}}l("ANIMATION_END")}),[i,l]),{isPresent:["mounted","unmountSuspended"].includes(d),ref:t.useCallback((e=>{e&&(s.current=getComputedStyle(e)),n(e)}),[])}}(i),o="function"==typeof n?n({present:s.isPresent}):t.Children.only(n),a=Fk(s.ref,o.ref);return"function"==typeof n||s.isPresent?t.cloneElement(o,{ref:a}):null};function cE(e){return(null==e?void 0:e.animationName)||"none"}function dE({prop:e,defaultProp:r,onChange:i=(()=>{})}){const[n,s]=function({defaultProp:e,onChange:r}){const i=t.useState(e),[n]=i,s=t.useRef(n),o=Kk(r);return t.useEffect((()=>{s.current!==n&&(o(n),s.current=n)}),[n,s,o]),i}({defaultProp:r,onChange:i}),o=void 0!==e,a=o?e:n,c=Kk(i),d=t.useCallback((t=>{if(o){const r="function"==typeof t?t(e):t;r!==e&&c(r)}else s(t)}),[o,e,s,c]);return[a,d]}aE.displayName="Presence";var lE=new WeakMap,uE=new WeakMap,pE={},hE=0,fE=function(e){return e&&(e.host||fE(e.parentNode))},mE=function(e,t,r,i){var n=function(e,t){return t.map((function(t){if(e.contains(t))return t;var r=fE(t);return r&&e.contains(r)?r:(console.error("aria-hidden",t,"in not contained inside",e,". Doing nothing"),null)})).filter((function(e){return Boolean(e)}))}(t,Array.isArray(e)?e:[e]);pE[r]||(pE[r]=new WeakMap);var s=pE[r],o=[],a=new Set,c=new Set(n),d=function(e){e&&!a.has(e)&&(a.add(e),d(e.parentNode))};n.forEach(d);var l=function(e){e&&!c.has(e)&&Array.prototype.forEach.call(e.children,(function(e){if(a.has(e))l(e);else try{var t=e.getAttribute(i),n=null!==t&&"false"!==t,c=(lE.get(e)||0)+1,d=(s.get(e)||0)+1;lE.set(e,c),s.set(e,d),o.push(e),1===c&&n&&uE.set(e,!0),1===d&&e.setAttribute(r,"true"),n||e.setAttribute(i,"true")}catch(t){console.error("aria-hidden: cannot operate on ",e,t)}}))};return l(t),a.clear(),hE++,function(){o.forEach((function(e){var t=lE.get(e)-1,n=s.get(e)-1;lE.set(e,t),s.set(e,n),t||(uE.has(e)||e.removeAttribute(i),uE.delete(e)),n||e.removeAttribute(r)})),--hE||(lE=new WeakMap,lE=new WeakMap,uE=new WeakMap,pE={})}},gE=function(e,t,r){void 0===r&&(r="data-aria-hidden");var i=Array.from(Array.isArray(e)?e:[e]),n=t||function(e){return"undefined"==typeof document?null:(Array.isArray(e)?e[0]:e).ownerDocument.body}(e);return n?(i.push.apply(i,Array.from(n.querySelectorAll("[aria-live]"))),mE(i,n,r,"aria-hidden")):function(){return null}},vE="right-scroll-bar-position",bE="width-before-scroll-bar";function yE(e,t){return"function"==typeof e?e(t):e&&(e.current=t),e}var wE=new WeakMap;function _E(e,r){var i,n,o,a=(i=r||null,n=function(t){return e.forEach((function(e){return yE(e,t)}))},o=t.useState((function(){return{value:i,callback:n,facade:{get current(){return o.value},set current(e){var t=o.value;t!==e&&(o.value=e,o.callback(e,t))}}}}))[0],o.callback=n,o.facade);return s.useLayoutEffect((function(){var t=wE.get(a);if(t){var r=new Set(t),i=new Set(e),n=a.current;r.forEach((function(e){i.has(e)||yE(e,null)})),i.forEach((function(e){r.has(e)||yE(e,n)}))}wE.set(a,e)}),[e]),a}function SE(e){return e}var CE=function(e){var t=e.sideCar,r=aR(e,["sideCar"]);if(!t)throw new Error("Sidecar: please provide `sideCar` property to import the right car");var i=t.read();if(!i)throw new Error("Sidecar medium not found");return s.createElement(i,oR({},r))};CE.isSideCarExport=!0;var RE=function(e){void 0===e&&(e={});var t=function(e,t){void 0===t&&(t=SE);var r=[],i=!1;return{read:function(){if(i)throw new Error("Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.");return r.length?r[r.length-1]:e},useMedium:function(e){var n=t(e,i);return r.push(n),function(){r=r.filter((function(e){return e!==n}))}},assignSyncMedium:function(e){for(i=!0;r.length;){var t=r;r=[],t.forEach(e)}r={push:function(t){return e(t)},filter:function(){return r}}},assignMedium:function(e){i=!0;var t=[];if(r.length){var n=r;r=[],n.forEach(e),t=r}var s=function(){var r=t;t=[],r.forEach(e)},o=function(){return Promise.resolve().then(s)};o(),r={push:function(e){t.push(e),o()},filter:function(e){return t=t.filter(e),r}}}}}(null);return t.options=oR({async:!0,ssr:!1},e),t}(),kE=function(){},TE=s.forwardRef((function(e,t){var r=s.useRef(null),i=s.useState({onScrollCapture:kE,onWheelCapture:kE,onTouchMoveCapture:kE}),n=i[0],o=i[1],a=e.forwardProps,c=e.children,d=e.className,l=e.removeScrollBar,u=e.enabled,p=e.shards,h=e.sideCar,f=e.noIsolation,m=e.inert,g=e.allowPinchZoom,v=e.as,b=void 0===v?"div":v,y=aR(e,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noIsolation","inert","allowPinchZoom","as"]),w=h,_=_E([r,t]),S=oR(oR({},y),n);return s.createElement(s.Fragment,null,u&&s.createElement(w,{sideCar:RE,removeScrollBar:l,shards:p,noIsolation:f,inert:m,setCallbacks:o,allowPinchZoom:!!g,lockRef:r}),a?s.cloneElement(s.Children.only(c),oR(oR({},S),{ref:_})):s.createElement(b,oR({},S,{className:d,ref:_}),c))}));TE.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1},TE.classNames={fullWidth:bE,zeroRight:vE};function PE(){if(!document)return null;var e=document.createElement("style");e.type="text/css";var t=function(){if("undefined"!=typeof __webpack_nonce__)return __webpack_nonce__}();return t&&e.setAttribute("nonce",t),e}var EE=function(){var e=0,t=null;return{add:function(r){var i,n;0==e&&(t=PE())&&(n=r,(i=t).styleSheet?i.styleSheet.cssText=n:i.appendChild(document.createTextNode(n)),function(e){(document.head||document.getElementsByTagName("head")[0]).appendChild(e)}(t)),e++},remove:function(){! --e&&t&&(t.parentNode&&t.parentNode.removeChild(t),t=null)}}},OE=function(){var e,t=(e=EE(),function(t,r){s.useEffect((function(){return e.add(t),function(){e.remove()}}),[t&&r])});return function(e){var r=e.styles,i=e.dynamic;return t(r,i),null}},DE={left:0,top:0,right:0,gap:0},IE=function(e){return parseInt(e||"",10)||0},xE=function(e){if(void 0===e&&(e="margin"),"undefined"==typeof window)return DE;var t=function(e){var t=window.getComputedStyle(document.body),r=t["padding"===e?"paddingLeft":"marginLeft"],i=t["padding"===e?"paddingTop":"marginTop"],n=t["padding"===e?"paddingRight":"marginRight"];return[IE(r),IE(i),IE(n)]}(e),r=document.documentElement.clientWidth,i=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,i-r+t[2]-t[0])}},ME=OE(),LE="data-scroll-locked",jE=function(e,t,r,i){var n=e.left,s=e.top,o=e.right,a=e.gap;return void 0===r&&(r="margin"),"\n .".concat("with-scroll-bars-hidden"," {\n overflow: hidden ").concat(i,";\n padding-right: ").concat(a,"px ").concat(i,";\n }\n body[").concat(LE,"] {\n overflow: hidden ").concat(i,";\n overscroll-behavior: contain;\n ").concat([t&&"position: relative ".concat(i,";"),"margin"===r&&"\n padding-left: ".concat(n,"px;\n padding-top: ").concat(s,"px;\n padding-right: ").concat(o,"px;\n margin-left:0;\n margin-top:0;\n margin-right: ").concat(a,"px ").concat(i,";\n "),"padding"===r&&"padding-right: ".concat(a,"px ").concat(i,";")].filter(Boolean).join(""),"\n }\n \n .").concat(vE," {\n right: ").concat(a,"px ").concat(i,";\n }\n \n .").concat(bE," {\n margin-right: ").concat(a,"px ").concat(i,";\n }\n \n .").concat(vE," .").concat(vE," {\n right: 0 ").concat(i,";\n }\n \n .").concat(bE," .").concat(bE," {\n margin-right: 0 ").concat(i,";\n }\n \n body[").concat(LE,"] {\n ").concat("--removed-body-scroll-bar-size",": ").concat(a,"px;\n }\n")},AE=function(){var e=parseInt(document.body.getAttribute(LE)||"0",10);return isFinite(e)?e:0},NE=function(e){var t=e.noRelative,r=e.noImportant,i=e.gapMode,n=void 0===i?"margin":i;s.useEffect((function(){return document.body.setAttribute(LE,(AE()+1).toString()),function(){var e=AE()-1;e<=0?document.body.removeAttribute(LE):document.body.setAttribute(LE,e.toString())}}),[]);var o=s.useMemo((function(){return xE(n)}),[n]);return s.createElement(ME,{styles:jE(o,!t,n,r?"":"!important")})},BE=!1;if("undefined"!=typeof window)try{var FE=Object.defineProperty({},"passive",{get:function(){return BE=!0,!0}});window.addEventListener("test",FE,FE),window.removeEventListener("test",FE,FE)}catch(qO){BE=!1}var zE=!!BE&&{passive:!1},VE=function(e,t){var r=window.getComputedStyle(e);return"hidden"!==r[t]&&!(r.overflowY===r.overflowX&&!function(e){return"TEXTAREA"===e.tagName}(e)&&"visible"===r[t])},UE=function(e,t){var r=t;do{if("undefined"!=typeof ShadowRoot&&r instanceof ShadowRoot&&(r=r.host),$E(e,r)){var i=GE(e,r);if(i[1]>i[2])return!0}r=r.parentNode}while(r&&r!==document.body);return!1},$E=function(e,t){return"v"===e?function(e){return VE(e,"overflowY")}(t):function(e){return VE(e,"overflowX")}(t)},GE=function(e,t){return"v"===e?function(e){return[e.scrollTop,e.scrollHeight,e.clientHeight]}(t):function(e){return[e.scrollLeft,e.scrollWidth,e.clientWidth]}(t)},qE=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},HE=function(e){return[e.deltaX,e.deltaY]},WE=function(e){return e&&"current"in e?e.current:e},KE=function(e){return"\n .block-interactivity-".concat(e," {pointer-events: none;}\n .allow-interactivity-").concat(e," {pointer-events: all;}\n")},JE=0,XE=[];var QE,ZE=(QE=function(e){var t=s.useRef([]),r=s.useRef([0,0]),i=s.useRef(),n=s.useState(JE++)[0],o=s.useState((function(){return OE()}))[0],a=s.useRef(e);s.useEffect((function(){a.current=e}),[e]),s.useEffect((function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(n));var t=function(e,t,r){if(r||2===arguments.length)for(var i,n=0,s=t.length;n<s;n++)!i&&n in t||(i||(i=Array.prototype.slice.call(t,0,n)),i[n]=t[n]);return e.concat(i||Array.prototype.slice.call(t))}([e.lockRef.current],(e.shards||[]).map(WE),!0).filter(Boolean);return t.forEach((function(e){return e.classList.add("allow-interactivity-".concat(n))})),function(){document.body.classList.remove("block-interactivity-".concat(n)),t.forEach((function(e){return e.classList.remove("allow-interactivity-".concat(n))}))}}}),[e.inert,e.lockRef.current,e.shards]);var c=s.useCallback((function(e,t){if("touches"in e&&2===e.touches.length)return!a.current.allowPinchZoom;var n,s=qE(e),o=r.current,c="deltaX"in e?e.deltaX:o[0]-s[0],d="deltaY"in e?e.deltaY:o[1]-s[1],l=e.target,u=Math.abs(c)>Math.abs(d)?"h":"v";if("touches"in e&&"h"===u&&"range"===l.type)return!1;var p=UE(u,l);if(!p)return!0;if(p?n=u:(n="v"===u?"h":"v",p=UE(u,l)),!p)return!1;if(!i.current&&"changedTouches"in e&&(c||d)&&(i.current=n),!n)return!0;var h=i.current||n;return function(e,t,r,i,n){var s=function(e,t){return"h"===e&&"rtl"===t?-1:1}(e,window.getComputedStyle(t).direction),o=s*i,a=r.target,c=t.contains(a),d=!1,l=o>0,u=0,p=0;do{var h=GE(e,a),f=h[0],m=h[1]-h[2]-s*f;(f||m)&&$E(e,a)&&(u+=m,p+=f),a=a.parentNode}while(!c&&a!==document.body||c&&(t.contains(a)||t===a));return(l&&(n&&0===u||!n&&o>u)||!l&&(n&&0===p||!n&&-o>p))&&(d=!0),d}(h,t,e,"h"===h?c:d,!0)}),[]),d=s.useCallback((function(e){var r=e;if(XE.length&&XE[XE.length-1]===o){var i="deltaY"in r?HE(r):qE(r),n=t.current.filter((function(e){return e.name===r.type&&e.target===r.target&&(t=e.delta,n=i,t[0]===n[0]&&t[1]===n[1]);var t,n}))[0];if(n&&n.should)r.cancelable&&r.preventDefault();else if(!n){var s=(a.current.shards||[]).map(WE).filter(Boolean).filter((function(e){return e.contains(r.target)}));(s.length>0?c(r,s[0]):!a.current.noIsolation)&&r.cancelable&&r.preventDefault()}}}),[]),l=s.useCallback((function(e,r,i,n){var s={name:e,delta:r,target:i,should:n};t.current.push(s),setTimeout((function(){t.current=t.current.filter((function(e){return e!==s}))}),1)}),[]),u=s.useCallback((function(e){r.current=qE(e),i.current=void 0}),[]),p=s.useCallback((function(t){l(t.type,HE(t),t.target,c(t,e.lockRef.current))}),[]),h=s.useCallback((function(t){l(t.type,qE(t),t.target,c(t,e.lockRef.current))}),[]);s.useEffect((function(){return XE.push(o),e.setCallbacks({onScrollCapture:p,onWheelCapture:p,onTouchMoveCapture:h}),document.addEventListener("wheel",d,zE),document.addEventListener("touchmove",d,zE),document.addEventListener("touchstart",u,zE),function(){XE=XE.filter((function(e){return e!==o})),document.removeEventListener("wheel",d,zE),document.removeEventListener("touchmove",d,zE),document.removeEventListener("touchstart",u,zE)}}),[]);var f=e.removeScrollBar,m=e.inert;return s.createElement(s.Fragment,null,m?s.createElement(o,{styles:KE(n)}):null,f?s.createElement(NE,{gapMode:"margin"}):null)},RE.useMedium(QE),CE),YE=s.forwardRef((function(e,t){return s.createElement(TE,oR({},e,{ref:t,sideCar:ZE}))}));YE.classNames=TE.classNames;var eO=YE;const tO="Popover",[rO,iO]=zk(tO,[HP]),nO=HP(),[sO,oO]=rO(tO),aO=t.forwardRef(((e,r)=>{const{__scopePopover:i,...n}=e,s=oO("PopoverTrigger",i),o=nO(i),a=Fk(r,s.triggerRef),c=t.createElement(Wk.button,Ak({type:"button","aria-haspopup":"dialog","aria-expanded":s.open,"aria-controls":s.contentId,"data-state":gO(s.open)},n,{ref:a,onClick:Nk(e.onClick,s.onOpenToggle)}));return s.hasCustomAnchor?c:t.createElement(nE,Ak({asChild:!0},o),c)})),cO="PopoverPortal",[dO,lO]=rO(cO,{forceMount:void 0}),uO="PopoverContent",pO=t.forwardRef(((e,r)=>{const i=lO(uO,e.__scopePopover),{forceMount:n=i.forceMount,...s}=e,o=oO(uO,e.__scopePopover);return t.createElement(aE,{present:n||o.open},o.modal?t.createElement(hO,Ak({},s,{ref:r})):t.createElement(fO,Ak({},s,{ref:r})))})),hO=t.forwardRef(((e,r)=>{const i=oO(uO,e.__scopePopover),n=t.useRef(null),s=Fk(r,n),o=t.useRef(!1);return t.useEffect((()=>{const e=n.current;if(e)return gE(e)}),[]),t.createElement(eO,{as:Uk,allowPinchZoom:!0},t.createElement(mO,Ak({},e,{ref:s,trapFocus:i.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:Nk(e.onCloseAutoFocus,(e=>{var t;e.preventDefault(),o.current||null===(t=i.triggerRef.current)||void 0===t||t.focus()})),onPointerDownOutside:Nk(e.onPointerDownOutside,(e=>{const t=e.detail.originalEvent,r=0===t.button&&!0===t.ctrlKey,i=2===t.button||r;o.current=i}),{checkForDefaultPrevented:!1}),onFocusOutside:Nk(e.onFocusOutside,(e=>e.preventDefault()),{checkForDefaultPrevented:!1})})))})),fO=t.forwardRef(((e,r)=>{const i=oO(uO,e.__scopePopover),n=t.useRef(!1),s=t.useRef(!1);return t.createElement(mO,Ak({},e,{ref:r,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:t=>{var r,o;(null===(r=e.onCloseAutoFocus)||void 0===r||r.call(e,t),t.defaultPrevented)||(n.current||null===(o=i.triggerRef.current)||void 0===o||o.focus(),t.preventDefault());n.current=!1,s.current=!1},onInteractOutside:t=>{var r,o;null===(r=e.onInteractOutside)||void 0===r||r.call(e,t),t.defaultPrevented||(n.current=!0,"pointerdown"===t.detail.originalEvent.type&&(s.current=!0));const a=t.target;(null===(o=i.triggerRef.current)||void 0===o?void 0:o.contains(a))&&t.preventDefault(),"focusin"===t.detail.originalEvent.type&&s.current&&t.preventDefault()}}))})),mO=t.forwardRef(((e,r)=>{const{__scopePopover:i,trapFocus:n,onOpenAutoFocus:s,onCloseAutoFocus:o,disableOutsidePointerEvents:a,onEscapeKeyDown:c,onPointerDownOutside:d,onFocusOutside:l,onInteractOutside:u,...p}=e,h=oO(uO,i),f=nO(i);return t.useEffect((()=>{var e,t;const r=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",null!==(e=r[0])&&void 0!==e?e:nT()),document.body.insertAdjacentElement("beforeend",null!==(t=r[1])&&void 0!==t?t:nT()),iT++,()=>{1===iT&&document.querySelectorAll("[data-radix-focus-guard]").forEach((e=>e.remove())),iT--}}),[]),t.createElement(cT,{asChild:!0,loop:!0,trapped:n,onMountAutoFocus:s,onUnmountAutoFocus:o},t.createElement(eT,{asChild:!0,disableOutsidePointerEvents:a,onInteractOutside:u,onEscapeKeyDown:c,onPointerDownOutside:d,onFocusOutside:l,onDismiss:()=>h.onOpenChange(!1)},t.createElement(sE,Ak({"data-state":gO(h.open),role:"dialog",id:h.contentId},f,p,{ref:r,style:{...p.style,"--radix-popover-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-popover-content-available-width":"var(--radix-popper-available-width)","--radix-popover-content-available-height":"var(--radix-popper-available-height)","--radix-popover-trigger-width":"var(--radix-popper-anchor-width)","--radix-popover-trigger-height":"var(--radix-popper-anchor-height)"}}))))}));function gO(e){return e?"open":"closed"}const vO=e=>{const{__scopePopover:r,forceMount:i,children:n,container:s}=e,o=oO(cO,r);return t.createElement(dO,{scope:r,forceMount:i},t.createElement(aE,{present:i||o.open},t.createElement(oE,{asChild:!0,container:s},n)))},bO=pO,yO=e=>{const{__scopePopover:r,children:i,open:n,defaultOpen:s,onOpenChange:o,modal:a=!1}=e,c=nO(r),d=t.useRef(null),[l,u]=t.useState(!1),[p=!1,h]=dE({prop:n,defaultProp:s,onChange:o});return t.createElement(iE,c,t.createElement(sO,{scope:r,contentId:bT(),triggerRef:d,open:p,onOpenChange:h,onOpenToggle:t.useCallback((()=>h((e=>!e))),[h]),hasCustomAnchor:l,onCustomAnchorAdd:t.useCallback((()=>u(!0)),[]),onCustomAnchorRemove:t.useCallback((()=>u(!1)),[]),modal:a},i))},wO=aO,_O=s.forwardRef(((e,t)=>{var{style:r,align:i="center",sideOffset:n=4}=e,o=aR(e,["style","align","sideOffset"]);return s.createElement(vO,null,s.createElement(bO,Object.assign({ref:t,align:i,sideOffset:n,style:Object.assign({width:"200px",backgroundColor:"#fff",border:"1px solid #e5e5e5",borderRadius:"0.375rem",boxShadow:"0 1px 2px 0 rgb(0 0 0 / 0.05)",color:"#333",fontSize:"14px",lineHeight:"1.5",padding:"16px",zIndex:50,outline:"none"},r)},o)))}));_O.displayName=bO.displayName;const SO=s.createContext({}),CO=s.createContext({}),RO=()=>{const e=s.useContext(SO),t=s.useContext(CO);if(!t)throw new Error("useGridCell must be used within a GridCell");return Object.assign(Object.assign({},e),t)},kO=s.createContext({}),TO=e=>{const{children:t}=e,r=aR(e,["children"]),[i,n]=s.useState(!1);return s.createElement(kO.Provider,{value:{open:i,setOpen:n}},s.createElement(yO,Object.assign({},r,{open:i,onOpenChange:n}),t))},PO=s.forwardRef(((e,t)=>{var{children:r,style:i}=e,n=aR(e,["children","style"]);return s.createElement(_O,Object.assign({ref:t,style:Object.assign({display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",minWidth:"180px",maxWidth:"300px",maxHeight:"100vh",overflowY:"auto",padding:0},i)},n),r)}));PO.displayName="ParticipantMenuContent";const EO=s.forwardRef(((e,t)=>{var{children:r,style:i}=e,n=aR(e,["children","style"]);return s.createElement(wO,Object.assign({ref:t,style:Object.assign({position:"absolute",top:"10px",right:"20px",textDecoration:"none",whiteSpace:"nowrap",border:"none",cursor:"pointer"},i)},n),r)}));EO.displayName=wO.displayName;const OO=s.forwardRef(((e,t)=>{var{children:r,style:i,participantAction:n}=e,o=aR(e,["children","style","participantAction"]);const{participant:a,setOpen:c,maximizedParticipant:d,setMaximizedParticipant:l,setFloatingParticipant:u,floatingParticipant:p}=(()=>{const e=s.useContext(kO),t=RO();if(!e)throw new Error("useParticipantMenu must be used within a ParticipantMenu");return Object.assign(Object.assign({},e),t)})(),h=cR(),f=dR(dS).find((e=>e.id===a.id)),m=(null==d?void 0:d.id)===a.id,g=(null==p?void 0:p.id)===a.id;let v;switch(n){case"maximize":v=()=>{l(m?null:a),c(!1)};break;case"spotlight":v=()=>{h(f?aS({id:a.id}):oS({id:a.id})),c(!1)};break;case"float":v=()=>{u(g?null:a),c(!1)}}return s.createElement("button",Object.assign({ref:t,role:"menuitem",tabIndex:-1,onClick:null!=v?v:o.onClick,style:Object.assign({alignItems:"stretch",backgroundColor:"transparent",border:"none",cursor:"pointer",display:"flex",height:"40px",lineHeight:"40px",minWidth:"140px",padding:"0 12px",textAlign:"left",textDecoration:"none",whiteSpace:"nowrap",width:"100%"},i)},o),r)}));function DO(e){return s.createElement("svg",Object.assign({width:"100%",height:"100%",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},e),s.createElement("g",null,s.createElement("circle",{cx:"6",cy:"12",r:"2"}),s.createElement("circle",{cx:"12",cy:"12",r:"2"}),s.createElement("circle",{cx:"18",cy:"12",r:"2"})))}function IO(e){return s.createElement("svg",Object.assign({width:"100%",height:"100%",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},e),s.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"m13.875 3c0 .62132.5037 1.125 1.125 1.125h3.284l-4.0795 4.0795c-.4393.43934-.4393 1.15166 0 1.591.4393.4393 1.1517.4393 1.591 0l4.0795-4.07951v3.28401c0 .62132.5037 1.125 1.125 1.125s1.125-.50368 1.125-1.125v-6c0-.15254-.0304-.29799-.0854-.43063-.0536-.12968-.1326-.25135-.2368-.35749l-.0147-.01469c-.203-.19928-.4812-.32219-.7881-.32219h-6c-.6213 0-1.125.50368-1.125 1.125zm-9.75 12c0-.6213-.50368-1.125-1.125-1.125s-1.125.5037-1.125 1.125v6c0 .3069.12291.5851.32219.7881.00486.005.00975.0099.01469.0147.10614.1042.22781.1832.35749.2368.13264.055.27809.0854.43063.0854h6c.62132 0 1.125-.5037 1.125-1.125s-.50368-1.125-1.125-1.125h-3.28401l4.07951-4.0795c.4393-.4393.4393-1.1517 0-1.591-.43934-.4393-1.15166-.4393-1.591 0l-4.0795 4.0795z"}))}function xO(e){return s.createElement("svg",Object.assign({width:"100%",height:"100%",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},e),s.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"m15.241.146691c-.1011-.1955882-.3809-.1955879-.482 0l-1.1063 2.139639c-.0258.04991-.0665.09058-.1164.11639l-2.1396 1.10629c-.1956.10113-.1956.38085 0 .48198l2.1396 1.10629c.0499.02581.0906.06648.1164.11639l1.1063 2.13964c.1011.19559.3809.19559.482 0l1.1063-2.13964c.0258-.04991.0665-.09058.1164-.11639l2.1396-1.10629c.1956-.10113.1956-.38085 0-.48198l-2.1396-1.10629c-.0499-.02581-.0906-.06648-.1164-.11639zm-13.741 2.900259v14.67495c0 .0511.00116.1018.00345.1523-.00229.0418-.00345.0837-.00345.1258 0 .5674.21005 1.1103.59339 1.6103.24265.3472.55042.6455.90566.8773 1.61225 1.213 4.36988 2.0124 7.50095 2.0124 4.3315 0 7.9484-1.53 8.8068-3.5681.0651-.1472.1148-.3024.1455-.4658.0315-.1532.0477-.3087.0477-.4661 0-.6032-.2374-1.1788-.668-1.7045-.1377-.1975-.2995-.4017-.4877-.6127l-14.22219-13.74809c-.28845-.27884-.67396-.43471-1.07516-.43471-.85436 0-1.54695.69259-1.54695 1.54695zm19.2646 4.59631c.0988-.19101.372-.19101.4708 0l.8546 1.65303c.0253.04874.065.08846.1137.11366l1.653.85465c.1911.0988.1911.372 0 .4708l-1.653.8546c-.0487.0253-.0884.065-.1137.1137l-.8546 1.653c-.0988.1911-.372.1911-.4708 0l-.8546-1.653c-.0253-.0487-.065-.0884-.1137-.1137l-1.653-.8546c-.1911-.0988-.1911-.372 0-.4708l1.653-.85465c.0487-.0252.0884-.06492.1137-.11366zm-3.2651 10.35684c0 .0769-.1144.6851-1.5305 1.3931-1.2964.6482-3.2274 1.1069-5.4695 1.1069s-4.17308-.4587-5.46952-1.1069c-1.41607-.708-1.53047-1.3162-1.53047-1.3931 0-.077.1144-.6851 1.53047-1.3932 1.29644-.6482 3.22742-1.1068 5.46952-1.1068s4.1731.4586 5.4695 1.1068c1.4161.7081 1.5305 1.3162 1.5305 1.3932z"}))}function MO(e){return s.createElement("svg",Object.assign({width:"100%",height:"100%",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},e),s.createElement("path",{clipRule:"evenodd",fillRule:"evenodd",d:"m2.25 3v4.5c0 .41421.33579.75.75.75h4.5c.41421 0 .75-.33579.75-.75v-4.5c0-.41421-.33579-.75-.75-.75h-4.5c-.41421 0-.75.33579-.75.75zm-2.25 4.5v-4.5c0-1.65685 1.34315-3 3-3h4.5c1.65685 0 3 1.34315 3 3v4.5c0 1.65685-1.34315 3-3 3h-4.5c-1.65685 0-3-1.34315-3-3zm2.25 9v4.5c0 .4142.33579.75.75.75h4.5c.41421 0 .75-.3358.75-.75v-4.5c0-.4142-.33579-.75-.75-.75h-4.5c-.41421 0-.75.3358-.75.75zm-2.25 4.5v-4.5c0-1.6569 1.34315-3 3-3h4.5c1.65685 0 3 1.3431 3 3v4.5c0 1.6569-1.34315 3-3 3h-4.5c-1.65685 0-3-1.3431-3-3zm15.75-13.5v-4.5c0-.41421.3358-.75.75-.75h4.5c.4142 0 .75.33579.75.75v4.5c0 .41421-.3358.75-.75.75h-4.5c-.4142 0-.75-.33579-.75-.75zm-2.25-4.5v4.5c0 1.65685 1.3431 3 3 3h4.5c1.6569 0 3-1.34315 3-3v-4.5c0-1.65685-1.3431-3-3-3h-4.5c-1.6569 0-3 1.34315-3 3zm1.875 19.5c0-.6213.5037-1.125 1.125-1.125h3.284l-5.5795-5.5795c-.4393-.4393-.4393-1.1517 0-1.591s1.1517-.4393 1.591 0l5.5795 5.5795v-3.284c0-.6213.5037-1.125 1.125-1.125s1.125.5037 1.125 1.125v6c0 .308-.1238.5872-.3244.7903-.0033.0034-.0067.0068-.0101.0102-.1067.1054-.2292.1851-.3599.2391-.1326.055-.2781.0854-.4306.0854h-6c-.6213 0-1.125-.5037-1.125-1.125z"}))}function LO(e){return s.createElement("svg",Object.assign({width:"100%",height:"100%",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},e),s.createElement("path",{clipRule:"evenodd",fillRule:"evenodd",d:"m2.25 3v4.5c0 .41421.33579.75.75.75h4.5c.41421 0 .75-.33579.75-.75v-4.5c0-.41421-.33579-.75-.75-.75h-4.5c-.41421 0-.75.33579-.75.75zm-2.25 4.5v-4.5c0-1.65685 1.34315-3 3-3h4.5c1.65685 0 3 1.34315 3 3v4.5c0 1.65685-1.34315 3-3 3h-4.5c-1.65685 0-3-1.34315-3-3zm2.25 9v4.5c0 .4142.33579.75.75.75h4.5c.41421 0 .75-.3358.75-.75v-4.5c0-.4142-.33579-.75-.75-.75h-4.5c-.41421 0-.75.3358-.75.75zm-2.25 4.5v-4.5c0-1.6569 1.34315-3 3-3h4.5c1.65685 0 3 1.3431 3 3v4.5c0 1.6569-1.34315 3-3 3h-4.5c-1.65685 0-3-1.3431-3-3zm15.75-13.5v-4.5c0-.41421.3358-.75.75-.75h4.5c.4142 0 .75.33579.75.75v4.5c0 .41421-.3358.75-.75.75h-4.5c-.4142 0-.75-.33579-.75-.75zm-2.25-4.5v4.5c0 1.65685 1.3431 3 3 3h4.5c1.6569 0 3-1.34315 3-3v-4.5c0-1.65685-1.3431-3-3-3h-4.5c-1.6569 0-3 1.34315-3 3zm8.625 12c0 .6213-.5037 1.125-1.125 1.125h-3.284l5.5795 5.5795c.4393.4393.4393 1.1517 0 1.591s-1.1517.4393-1.591 0l-5.5795-5.5795v3.284c0 .6213-.5037 1.125-1.125 1.125s-1.125-.5037-1.125-1.125v-6c0-.3081.1238-.5872.3244-.7904.0034-.0034.0068-.0068.0102-.0102.1067-.1053.2292-.185.3598-.239.1326-.055.2781-.0854.4306-.0854h6c.6213 0 1.125.5037 1.125 1.125z"}))}function jO({participant:e}){const t=dR(dS).find((t=>t.id===e.id)),{isHovered:r,maximizedParticipant:i,floatingParticipant:n}=RO(),o=(null==i?void 0:i.id)===e.id,a=(null==n?void 0:n.id)===e.id;return r?s.createElement(TO,null,s.createElement(EO,{style:{display:"flex",justifyContent:"center",alignItems:"center",backgroundColor:"#fff",borderRadius:"6px",padding:"4px"}},s.createElement(DO,{height:20,width:20,transform:"rotate(90)"})),s.createElement(PO,null,e.isLocalClient?s.createElement(OO,{participantAction:"float",style:{display:"flex",alignItems:"center",gap:"10px"}},a?s.createElement(s.Fragment,null,s.createElement(LO,{height:16,width:16}),"Move to grid"):s.createElement(s.Fragment,null,s.createElement(MO,{height:16,width:16}),"Pop out")):null,s.createElement(OO,{participantAction:"maximize",style:{display:"flex",alignItems:"center",gap:"10px"}},s.createElement(IO,{height:16,width:16}),o?"Minimize":"Maximize"),s.createElement(OO,{participantAction:"spotlight",style:{display:"flex",alignItems:"center",gap:"10px"}},s.createElement(xO,{height:16,width:16}),t?"Remove spotlight":"Spotlight"))):null}OO.displayName="ParticipantMenuItem";const AO=s.forwardRef((({className:e,participant:t,children:r},i)=>{const[n,o]=s.useState(!1),a=s.useCallback((()=>{o(!0)}),[]),c=s.useCallback((()=>{o(!1)}),[]);return s.createElement(CO.Provider,{value:{participant:t,isHovered:n}},s.createElement("div",{ref:i,className:e,onMouseEnter:a,onMouseLeave:c,style:{height:"100%",width:"100%"}},r))}));AO.displayName="GridCell";const NO=s.forwardRef(((e,t)=>{var{stream:r,style:i}=e,n=aR(e,["stream","style"]);const o=s.useRef(null),{onSetClientAspectRatio:a,clientAspectRatios:c,participant:d,isConstrained:l}=RO();if(!d)return null;const u=c[d.id];s.useImperativeHandle(t,(()=>o.current));const p=s.useCallback((()=>{const e=o.current&&o.current.captureAspectRatio();e&&e!==u&&d.id&&a({aspectRatio:e,clientId:d.id})}),[c,d.id,a]),h=r||d.stream;return h?s.createElement(lR,Object.assign({ref:o,style:Object.assign(Object.assign({borderRadius:l?0:"8px"},l?{objectFit:"cover"}:{}),i),muted:d.isLocalClient},n,{stream:h,onVideoResize:p})):s.createElement(jk,{isSmallCell:!1,displayName:(null==d?void 0:d.displayName)||"Guest",withRoundedCorners:!0})}));function BO({cellView:e,enableParticipantMenu:t,render:r}){const i=null==e?void 0:e.client;if(i)return"video"===e.type?s.createElement(AO,{participant:i},i.isVideoEnabled?s.createElement(s.Fragment,null,r?r({participant:i}):s.createElement(s.Fragment,null,s.createElement(NO,null),t?s.createElement(jO,{participant:i}):null)):s.createElement(jk,{isSmallCell:!1,displayName:(null==i?void 0:i.displayName)||"Guest",withRoundedCorners:!0})):void 0}return NO.displayName="GridVideoView",e.GridCell=AO,e.GridVideoView=NO,e.ParticipantMenu=TO,e.ParticipantMenuContent=PO,e.ParticipantMenuItem=OO,e.ParticipantMenuTrigger=EO,e.VideoGrid=function({renderParticipant:e,renderFloatingParticipant:t,stageParticipantLimit:r,gridGap:i,videoGridGap:n,enableSubgrid:o,enableParticipantMenu:a,enableConstrainedGrid:c}){const d=s.useRef(null),{containerFrame:l,cellViewsFloating:u,cellViewsVideoGrid:p,cellViewsInPresentationGrid:h,cellViewsInSubgrid:f,clientAspectRatios:m,videoStage:g,setContainerBounds:v,setClientAspectRatios:b,maximizedParticipant:y,setMaximizedParticipant:w,isConstrained:_,floatingParticipant:S,setFloatingParticipant:C}=function({activeVideosSubgridTrigger:e,forceSubgrid:t,stageParticipantLimit:r=sk,gridGap:i=8,videoGridGap:n=8,enableSubgrid:o=!0,enableConstrainedGrid:a=!0}={}){const[c,d]=s.useState({width:0,height:0}),[l,u]=s.useState(!1),[p,h]=s.useState({}),[f,m]=s.useState(null),[g,v]=s.useState(null),{clientViewsInGrid:b,clientViewsInPresentationGrid:y,clientViewsInSubgrid:w,floatingClientView:_}=ck({activeVideosSubgridTrigger:e,forceSubgrid:t,stageParticipantLimit:r,enableSubgrid:o,maximizedParticipant:f,floatingParticipant:g,isConstrained:!!a&&!!l}),S=s.useMemo((()=>_?[nk({client:_,aspectRatio:p[_.id],avatarSize:0,cellPaddings:{top:0,right:0}})]:[]),[_,p]),C=s.useMemo((()=>b.map((e=>nk({client:e,aspectRatio:p[e.id],avatarSize:0,cellPaddings:{top:0,right:0}})))),[b,p]),R=s.useMemo((()=>y.map((e=>nk({client:e,aspectRatio:p[e.id],avatarSize:0,cellPaddings:{top:0,right:0}})))),[y,p]),k=s.useMemo((()=>w.map((e=>nk({client:e,aspectRatio:p[e.id],avatarSize:0,cellPaddings:{top:0,right:0},isSubgrid:!0})))),[w,p]),T=s.useMemo((()=>vR(c)),[c]);s.useEffect((()=>{a&&u(c.width<500||c.height<500)}),[c,a]);const P=s.useMemo((()=>ik({floatingVideo:S[0],frame:T,gridGap:i,isConstrained:l,roomBounds:T.bounds,videos:C,videoGridGap:n,presentationVideos:R,subgridVideos:k})),[T,S,C,R,k,i,n]);return{containerFrame:T,cellViewsFloating:S,cellViewsVideoGrid:C,cellViewsInPresentationGrid:R,cellViewsInSubgrid:k,clientAspectRatios:p,videoStage:P,setContainerBounds:d,setClientAspectRatios:h,maximizedParticipant:f,setMaximizedParticipant:m,floatingParticipant:g,setFloatingParticipant:v,isConstrained:l}}({activeVideosSubgridTrigger:12,stageParticipantLimit:r,gridGap:i,videoGridGap:n,enableSubgrid:o,enableConstrainedGrid:c}),R=s.useCallback((({aspectRatio:e,clientId:t})=>{b((r=>Object.assign(Object.assign({},r),{[t]:e})))}),[b]),k=s.useMemo((()=>BO(Object.assign({cellView:u[0],enableParticipantMenu:a},t?{render:({participant:e})=>t({participant:e})}:{}))),[u]),T=s.useMemo((()=>h.map((t=>BO(Object.assign({cellView:t,enableParticipantMenu:a},e?{render:({participant:t})=>e({participant:t})}:{}))))),[h]),P=s.useMemo((()=>p.map((t=>BO(Object.assign({cellView:t,enableParticipantMenu:a},e?{render:({participant:t})=>e({participant:t})}:{}))))),[p]),E=s.useMemo((()=>f.map((e=>BO({cellView:e,enableParticipantMenu:a})))),[f]);return s.useEffect((()=>{if(!d.current)return;const e=new ResizeObserver(vw((()=>{var e,t,r,i;v({width:null!==(t=null===(e=d.current)||void 0===e?void 0:e.clientWidth)&&void 0!==t?t:640,height:null!==(i=null===(r=d.current)||void 0===r?void 0:r.clientHeight)&&void 0!==i?i:480})}),{delay:60,edges:!1}));return e.observe(d.current),()=>{e.disconnect()}}),[]),s.createElement(SO.Provider,{value:{onSetClientAspectRatio:R,cellViewsVideoGrid:p,cellViewsInPresentationGrid:h,cellViewsInSubgrid:f,clientAspectRatios:m,maximizedParticipant:y,setMaximizedParticipant:w,floatingParticipant:S,setFloatingParticipant:C,isConstrained:_}},s.createElement("div",{ref:d,style:{width:"100%",height:"100%",position:"relative"}},s.createElement(TR,{containerFrame:l,floatingContent:k,layoutVideoStage:g,presentationGridContent:T,gridContent:P,subgridContent:E})))},e.VideoView=lR,e.WherebyProvider=function({children:e}){const t=(({preloadedState:e,injectServices:t})=>gt({devTools:bC,reducer:wC,middleware:e=>e({thunk:{extraArgument:{services:t}},serializableCheck:!1}).prepend(Ry.middleware),preloadedState:e}))({injectServices:function(){const e=KC.create({baseUrl:rR}),t=new AC({fetchDeviceCredentials:e.getCredentials.bind(e),baseUrl:rR}),r=new eR({apiClient:t});return{credentialsService:e,apiClient:t,organizationService:r,fetchOrganizationFromRoomUrl:e=>{const t=Og({host:new URL(e).host});return new tR({organizationService:r,subdomain:t.subdomain}).fetchOrganization()}}}()});return s.createElement(T,{context:iR,store:t},e)},e.useLocalMedia=function(e={audio:!0,video:!0}){const t=cR(),r=dR(hR);return s.useEffect((()=>(t(Aw(e)),()=>{t(Nw())})),[]),{state:r,actions:{setCameraDevice:s.useCallback((e=>t(ww({deviceId:e}))),[t]),setMicrophoneDevice:s.useCallback((e=>t(_w({deviceId:e}))),[t]),setSpeakerDevice:s.useCallback((e=>t(Sw({deviceId:e}))),[t]),toggleCameraEnabled:s.useCallback((e=>t(Cw({enabled:e}))),[t]),toggleMicrophoneEnabled:s.useCallback((e=>t(Rw({enabled:e}))),[t]),toggleLowDataModeEnabled:s.useCallback((e=>t(kw({enabled:e}))),[t])}}},e.useRoomConnection=function(e,t=pR){const r=cR(),i=dR(uR),n=s.useMemo((()=>{const r=new URL(e),i=new URLSearchParams(r.search),n=t.roomKey||i.get("roomKey");return{displayName:t.displayName||"Guest",localMediaOptions:t.localMedia?void 0:t.localMediaOptions,roomKey:n,roomUrl:e,userAgent:"browser-sdk:3.12.1",externalId:t.externalId||null}}),[e,t]);s.useEffect((()=>()=>{r(Ey())}),[]);const o=s.useCallback((e=>r(v_({text:e}))),[r]),a=s.useCallback((()=>r(oC())),[r]),c=s.useCallback((e=>r(HS({displayName:e}))),[r]),d=s.useCallback((e=>r(Cw({enabled:e}))),[r]),l=s.useCallback((e=>r(Rw({enabled:e}))),[r]),u=s.useCallback((e=>r(kw({enabled:e}))),[r]),p=s.useCallback((e=>r(JS({enabled:e}))),[r]),h=s.useCallback((e=>r(j_({clientIds:[e],enable:!0}))),[r]),f=s.useCallback((e=>r(A_({clientIds:[e],enable:!0}))),[r]),m=s.useCallback((e=>r(gC({participantId:e}))),[r]),g=s.useCallback((e=>r(vC({participantId:e}))),[r]),v=s.useCallback((()=>r(w_())),[r]),b=s.useCallback((()=>r(U_())),[r]),y=s.useCallback((()=>r(__())),[r]),w=s.useCallback((()=>r($_())),[r]),_=s.useCallback((()=>r(Oy(n))),[r]),S=s.useCallback((()=>r(Ey())),[r]),C=s.useCallback((e=>r(W_({locked:e}))),[r]),R=s.useCallback((e=>r(j_({clientIds:e,enable:!1}))),[r]),k=s.useCallback((e=>r(A_({clientIds:e,enable:!1}))),[r]),T=s.useCallback((e=>r(oS({id:e}))),[r]),P=s.useCallback((e=>r(aS({id:e}))),[r]),E=s.useCallback((e=>r(K_({clientId:e}))),[r]),O=s.useCallback((e=>r(J_({stayBehind:e}))),[r]),D=s.useCallback((e=>r(l_({group:e}))),[r]),I=s.useCallback((()=>r(l_({group:""}))),[r]),{events:x}=i;return{state:aR(i,["events"]),events:x,actions:{toggleLowDataMode:u,toggleRaiseHand:p,askToSpeak:h,askToTurnOnCamera:f,acceptWaitingParticipant:m,knock:a,joinRoom:_,leaveRoom:S,lockRoom:C,muteParticipants:R,turnOffParticipantCameras:k,kickParticipant:E,endMeeting:O,rejectWaitingParticipant:g,sendChatMessage:o,setDisplayName:c,startCloudRecording:v,startScreenshare:b,stopCloudRecording:y,stopScreenshare:w,toggleCamera:d,toggleMicrophone:l,spotlightParticipant:T,removeSpotlight:P,joinBreakoutGroup:D,joinBreakoutMainRoom:I}}},e}({},React,ReactDOM);
|
|
3
|
+
let zo;Mo.AwaitQueue=class{constructor(){this.pendingTasks=new Map,this.nextTaskId=0,this.stopping=!1}get size(){return this.pendingTasks.size}async push(e,t){if(t=t??e.name,No.debug(`push() [name:${t}]`),"function"!=typeof e)throw new TypeError("given task is not a function");if(t)try{Object.defineProperty(e,"name",{value:t})}catch(e){}return new Promise(((r,i)=>{const n={id:this.nextTaskId++,task:e,name:t,enqueuedAt:Date.now(),executedAt:void 0,completed:!1,resolve:e=>{if(n.completed)return;n.completed=!0,this.pendingTasks.delete(n.id),No.debug(`resolving task [name:${n.name}]`),r(e);const[t]=this.pendingTasks.values();t&&!t.executedAt&&this.execute(t)},reject:e=>{if(!n.completed&&(n.completed=!0,this.pendingTasks.delete(n.id),No.debug(`rejecting task [name:${n.name}]: %s`,String(e)),i(e),!this.stopping)){const[e]=this.pendingTasks.values();e&&!e.executedAt&&this.execute(e)}}};this.pendingTasks.set(n.id,n),1===this.pendingTasks.size&&this.execute(n)}))}stop(){No.debug("stop()"),this.stopping=!0;for(const e of this.pendingTasks.values())No.debug(`stop() | stopping task [name:${e.name}]`),e.reject(new Bo);this.stopping=!1}remove(e){No.debug(`remove() [taskIdx:${e}]`);const t=Array.from(this.pendingTasks.values())[e];t?t.reject(new Fo):No.debug(`stop() | no task with given idx [taskIdx:${e}]`)}dump(){const e=Date.now();let t=0;return Array.from(this.pendingTasks.values()).map((r=>({idx:t++,task:r.task,name:r.name,enqueuedTime:r.executedAt?r.executedAt-r.enqueuedAt:e-r.enqueuedAt,executionTime:r.executedAt?e-r.executedAt:0})))}async execute(e){if(No.debug(`execute() [name:${e.name}]`),e.executedAt)throw new Error("task already being executed");e.executedAt=Date.now();try{const t=await e.task();e.resolve(t)}catch(t){e.reject(t)}}};var Vo="function"==typeof queueMicrotask?queueMicrotask.bind("undefined"!=typeof window?window:a):e=>(zo||(zo=Promise.resolve())).then(e).catch((e=>setTimeout((()=>{throw e}),0))),Uo={};Object.defineProperty(Uo,"__esModule",{value:!0}),Uo.Producer=void 0;const $o=us,Go=Is,qo=new ss.Logger("Producer");class Ho extends $o.EnhancedEventEmitter{constructor({id:e,localId:t,rtpSender:r,track:i,rtpParameters:n,stopTracks:s,disableTrackOnPause:o,zeroRtpOnPause:a,appData:c}){super(),this._closed=!1,this._observer=new $o.EnhancedEventEmitter,qo.debug("constructor()"),this._id=e,this._localId=t,this._rtpSender=r,this._track=i,this._kind=i.kind,this._rtpParameters=n,this._paused=!!o&&!i.enabled,this._maxSpatialLayer=void 0,this._stopTracks=s,this._disableTrackOnPause=o,this._zeroRtpOnPause=a,this._appData=c??{},this.onTrackEnded=this.onTrackEnded.bind(this),this.handleTrack()}get id(){return this._id}get localId(){return this._localId}get closed(){return this._closed}get kind(){return this._kind}get rtpSender(){return this._rtpSender}get track(){return this._track}get rtpParameters(){return this._rtpParameters}get paused(){return this._paused}get maxSpatialLayer(){return this._maxSpatialLayer}get appData(){return this._appData}set appData(e){this._appData=e}get observer(){return this._observer}close(){this._closed||(qo.debug("close()"),this._closed=!0,this.destroyTrack(),this.emit("@close"),this._observer.safeEmit("close"))}transportClosed(){this._closed||(qo.debug("transportClosed()"),this._closed=!0,this.destroyTrack(),this.safeEmit("transportclose"),this._observer.safeEmit("close"))}async getStats(){if(this._closed)throw new Go.InvalidStateError("closed");return new Promise(((e,t)=>{this.safeEmit("@getstats",e,t)}))}pause(){qo.debug("pause()"),this._closed?qo.error("pause() | Producer closed"):(this._paused=!0,this._track&&this._disableTrackOnPause&&(this._track.enabled=!1),this._zeroRtpOnPause&&new Promise(((e,t)=>{this.safeEmit("@pause",e,t)})).catch((()=>{})),this._observer.safeEmit("pause"))}resume(){qo.debug("resume()"),this._closed?qo.error("resume() | Producer closed"):(this._paused=!1,this._track&&this._disableTrackOnPause&&(this._track.enabled=!0),this._zeroRtpOnPause&&new Promise(((e,t)=>{this.safeEmit("@resume",e,t)})).catch((()=>{})),this._observer.safeEmit("resume"))}async replaceTrack({track:e}){if(qo.debug("replaceTrack() [track:%o]",e),this._closed){if(e&&this._stopTracks)try{e.stop()}catch(e){}throw new Go.InvalidStateError("closed")}if(e&&"ended"===e.readyState)throw new Go.InvalidStateError("track ended");e!==this._track?(await new Promise(((t,r)=>{this.safeEmit("@replacetrack",e,t,r)})),this.destroyTrack(),this._track=e,this._track&&this._disableTrackOnPause&&(this._paused?this._paused&&(this._track.enabled=!1):this._track.enabled=!0),this.handleTrack()):qo.debug("replaceTrack() | same track, ignored")}async setMaxSpatialLayer(e){if(this._closed)throw new Go.InvalidStateError("closed");if("video"!==this._kind)throw new Go.UnsupportedError("not a video Producer");if("number"!=typeof e)throw new TypeError("invalid spatialLayer");e!==this._maxSpatialLayer&&(await new Promise(((t,r)=>{this.safeEmit("@setmaxspatiallayer",e,t,r)})).catch((()=>{})),this._maxSpatialLayer=e)}async setRtpEncodingParameters(e){if(this._closed)throw new Go.InvalidStateError("closed");if("object"!=typeof e)throw new TypeError("invalid params");await new Promise(((t,r)=>{this.safeEmit("@setrtpencodingparameters",e,t,r)}))}onTrackEnded(){qo.debug('track "ended" event'),this.safeEmit("trackended"),this._observer.safeEmit("trackended")}handleTrack(){this._track&&this._track.addEventListener("ended",this.onTrackEnded)}destroyTrack(){if(this._track)try{this._track.removeEventListener("ended",this.onTrackEnded),this._stopTracks&&this._track.stop()}catch(e){}}}Uo.Producer=Ho;var Wo={};Object.defineProperty(Wo,"__esModule",{value:!0}),Wo.Consumer=void 0;const Ko=us,Jo=Is,Xo=new ss.Logger("Consumer");class Qo extends Ko.EnhancedEventEmitter{constructor({id:e,localId:t,producerId:r,rtpReceiver:i,track:n,rtpParameters:s,appData:o}){super(),this._closed=!1,this._observer=new Ko.EnhancedEventEmitter,Xo.debug("constructor()"),this._id=e,this._localId=t,this._producerId=r,this._rtpReceiver=i,this._track=n,this._rtpParameters=s,this._paused=!n.enabled,this._appData=o??{},this.onTrackEnded=this.onTrackEnded.bind(this),this.handleTrack()}get id(){return this._id}get localId(){return this._localId}get producerId(){return this._producerId}get closed(){return this._closed}get kind(){return this._track.kind}get rtpReceiver(){return this._rtpReceiver}get track(){return this._track}get rtpParameters(){return this._rtpParameters}get paused(){return this._paused}get appData(){return this._appData}set appData(e){this._appData=e}get observer(){return this._observer}close(){this._closed||(Xo.debug("close()"),this._closed=!0,this.destroyTrack(),this.emit("@close"),this._observer.safeEmit("close"))}transportClosed(){this._closed||(Xo.debug("transportClosed()"),this._closed=!0,this.destroyTrack(),this.safeEmit("transportclose"),this._observer.safeEmit("close"))}async getStats(){if(this._closed)throw new Jo.InvalidStateError("closed");return new Promise(((e,t)=>{this.safeEmit("@getstats",e,t)}))}pause(){Xo.debug("pause()"),this._closed?Xo.error("pause() | Consumer closed"):this._paused?Xo.debug("pause() | Consumer is already paused"):(this._paused=!0,this._track.enabled=!1,this.emit("@pause"),this._observer.safeEmit("pause"))}resume(){Xo.debug("resume()"),this._closed?Xo.error("resume() | Consumer closed"):this._paused?(this._paused=!1,this._track.enabled=!0,this.emit("@resume"),this._observer.safeEmit("resume")):Xo.debug("resume() | Consumer is already resumed")}onTrackEnded(){Xo.debug('track "ended" event'),this.safeEmit("trackended"),this._observer.safeEmit("trackended")}handleTrack(){this._track.addEventListener("ended",this.onTrackEnded)}destroyTrack(){try{this._track.removeEventListener("ended",this.onTrackEnded),this._track.stop()}catch(e){}}}Wo.Consumer=Qo;var Zo={};Object.defineProperty(Zo,"__esModule",{value:!0}),Zo.DataProducer=void 0;const Yo=us,ea=Is,ta=new ss.Logger("DataProducer");class ra extends Yo.EnhancedEventEmitter{constructor({id:e,dataChannel:t,sctpStreamParameters:r,appData:i}){super(),this._closed=!1,this._observer=new Yo.EnhancedEventEmitter,ta.debug("constructor()"),this._id=e,this._dataChannel=t,this._sctpStreamParameters=r,this._appData=i??{},this.handleDataChannel()}get id(){return this._id}get closed(){return this._closed}get sctpStreamParameters(){return this._sctpStreamParameters}get readyState(){return this._dataChannel.readyState}get label(){return this._dataChannel.label}get protocol(){return this._dataChannel.protocol}get bufferedAmount(){return this._dataChannel.bufferedAmount}get bufferedAmountLowThreshold(){return this._dataChannel.bufferedAmountLowThreshold}set bufferedAmountLowThreshold(e){this._dataChannel.bufferedAmountLowThreshold=e}get appData(){return this._appData}set appData(e){this._appData=e}get observer(){return this._observer}close(){this._closed||(ta.debug("close()"),this._closed=!0,this._dataChannel.close(),this.emit("@close"),this._observer.safeEmit("close"))}transportClosed(){this._closed||(ta.debug("transportClosed()"),this._closed=!0,this._dataChannel.close(),this.safeEmit("transportclose"),this._observer.safeEmit("close"))}send(e){if(ta.debug("send()"),this._closed)throw new ea.InvalidStateError("closed");this._dataChannel.send(e)}handleDataChannel(){this._dataChannel.addEventListener("open",(()=>{this._closed||(ta.debug('DataChannel "open" event'),this.safeEmit("open"))})),this._dataChannel.addEventListener("error",(e=>{if(this._closed)return;let{error:t}=e;t||(t=new Error("unknown DataChannel error")),"sctp-failure"===t.errorDetail?ta.error("DataChannel SCTP error [sctpCauseCode:%s]: %s",t.sctpCauseCode,t.message):ta.error('DataChannel "error" event: %o',t),this.safeEmit("error",t)})),this._dataChannel.addEventListener("close",(()=>{this._closed||(ta.warn('DataChannel "close" event'),this._closed=!0,this.emit("@close"),this.safeEmit("close"),this._observer.safeEmit("close"))})),this._dataChannel.addEventListener("message",(()=>{this._closed||ta.warn('DataChannel "message" event in a DataProducer, message discarded')})),this._dataChannel.addEventListener("bufferedamountlow",(()=>{this._closed||this.safeEmit("bufferedamountlow")}))}}Zo.DataProducer=ra;var ia={};Object.defineProperty(ia,"__esModule",{value:!0}),ia.DataConsumer=void 0;const na=us,sa=new ss.Logger("DataConsumer");class oa extends na.EnhancedEventEmitter{constructor({id:e,dataProducerId:t,dataChannel:r,sctpStreamParameters:i,appData:n}){super(),this._closed=!1,this._observer=new na.EnhancedEventEmitter,sa.debug("constructor()"),this._id=e,this._dataProducerId=t,this._dataChannel=r,this._sctpStreamParameters=i,this._appData=n??{},this.handleDataChannel()}get id(){return this._id}get dataProducerId(){return this._dataProducerId}get closed(){return this._closed}get sctpStreamParameters(){return this._sctpStreamParameters}get readyState(){return this._dataChannel.readyState}get label(){return this._dataChannel.label}get protocol(){return this._dataChannel.protocol}get binaryType(){return this._dataChannel.binaryType}set binaryType(e){this._dataChannel.binaryType=e}get appData(){return this._appData}set appData(e){this._appData=e}get observer(){return this._observer}close(){this._closed||(sa.debug("close()"),this._closed=!0,this._dataChannel.close(),this.emit("@close"),this._observer.safeEmit("close"))}transportClosed(){this._closed||(sa.debug("transportClosed()"),this._closed=!0,this._dataChannel.close(),this.safeEmit("transportclose"),this._observer.safeEmit("close"))}handleDataChannel(){this._dataChannel.addEventListener("open",(()=>{this._closed||(sa.debug('DataChannel "open" event'),this.safeEmit("open"))})),this._dataChannel.addEventListener("error",(e=>{if(this._closed)return;let{error:t}=e;t||(t=new Error("unknown DataChannel error")),"sctp-failure"===t.errorDetail?sa.error("DataChannel SCTP error [sctpCauseCode:%s]: %s",t.sctpCauseCode,t.message):sa.error('DataChannel "error" event: %o',t),this.safeEmit("error",t)})),this._dataChannel.addEventListener("close",(()=>{this._closed||(sa.warn('DataChannel "close" event'),this._closed=!0,this.emit("@close"),this.safeEmit("close"),this._observer.safeEmit("close"))})),this._dataChannel.addEventListener("message",(e=>{this._closed||this.safeEmit("message",e.data)}))}}ia.DataConsumer=oa;var aa=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),ca=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),da=a&&a.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(null!=t)for(var i=e(t),n=0;n<i.length;n++)"default"!==i[n]&&aa(r,t,i[n]);return ca(r,t),r}}(),la=a&&a.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(xo,"__esModule",{value:!0}),xo.Transport=void 0;const ua=Mo,pa=la(Vo),ha=ss,fa=us,ma=Is,ga=da(Ls),va=da(Fs),ba=Uo,ya=Wo,wa=Zo,_a=ia,Sa=new ha.Logger("Transport");class Ca{constructor(e){this.consumerOptions=e,this.promise=new Promise(((e,t)=>{this.resolve=e,this.reject=t}))}}let Ra=class extends fa.EnhancedEventEmitter{constructor({direction:e,id:t,iceParameters:r,iceCandidates:i,dtlsParameters:n,sctpParameters:s,iceServers:o,iceTransportPolicy:a,additionalSettings:c,proprietaryConstraints:d,appData:l,handlerFactory:u,extendedRtpCapabilities:p,canProduceByKind:h}){super(),this._closed=!1,this._iceGatheringState="new",this._connectionState="new",this._producers=new Map,this._consumers=new Map,this._dataProducers=new Map,this._dataConsumers=new Map,this._probatorConsumerCreated=!1,this._awaitQueue=new ua.AwaitQueue,this._pendingConsumerTasks=[],this._consumerCreationInProgress=!1,this._pendingPauseConsumers=new Map,this._consumerPauseInProgress=!1,this._pendingResumeConsumers=new Map,this._consumerResumeInProgress=!1,this._pendingCloseConsumers=new Map,this._consumerCloseInProgress=!1,this._observer=new fa.EnhancedEventEmitter,Sa.debug("constructor() [id:%s, direction:%s]",t,e),this._id=t,this._direction=e,this._extendedRtpCapabilities=p,this._canProduceByKind=h,this._maxSctpMessageSize=s?s.maxMessageSize:null;const f=ga.clone(c)??{};delete f.iceServers,delete f.iceTransportPolicy,delete f.bundlePolicy,delete f.rtcpMuxPolicy,delete f.sdpSemantics,this._handler=u(),this._handler.run({direction:e,iceParameters:r,iceCandidates:i,dtlsParameters:n,sctpParameters:s,iceServers:o,iceTransportPolicy:a,additionalSettings:f,proprietaryConstraints:d,extendedRtpCapabilities:p}),this._appData=l??{},this.handleHandler()}get id(){return this._id}get closed(){return this._closed}get direction(){return this._direction}get handler(){return this._handler}get iceGatheringState(){return this._iceGatheringState}get connectionState(){return this._connectionState}get appData(){return this._appData}set appData(e){this._appData=e}get observer(){return this._observer}close(){if(!this._closed){Sa.debug("close()"),this._closed=!0,this._awaitQueue.stop(),this._handler.close(),this._connectionState="closed";for(const e of this._producers.values())e.transportClosed();this._producers.clear();for(const e of this._consumers.values())e.transportClosed();this._consumers.clear();for(const e of this._dataProducers.values())e.transportClosed();this._dataProducers.clear();for(const e of this._dataConsumers.values())e.transportClosed();this._dataConsumers.clear(),this._observer.safeEmit("close")}}async getStats(){if(this._closed)throw new ma.InvalidStateError("closed");return this._handler.getTransportStats()}async restartIce({iceParameters:e}){if(Sa.debug("restartIce()"),this._closed)throw new ma.InvalidStateError("closed");if(!e)throw new TypeError("missing iceParameters");return this._awaitQueue.push((async()=>await this._handler.restartIce(e)),"transport.restartIce()")}async updateIceServers({iceServers:e}={}){if(Sa.debug("updateIceServers()"),this._closed)throw new ma.InvalidStateError("closed");if(!Array.isArray(e))throw new TypeError("missing iceServers");return this._awaitQueue.push((async()=>this._handler.updateIceServers(e)),"transport.updateIceServers()")}async produce({track:e,encodings:t,codecOptions:r,codec:i,stopTracks:n=!0,disableTrackOnPause:s=!0,zeroRtpOnPause:o=!1,onRtpSender:a,appData:c={}}={}){if(Sa.debug("produce() [track:%o]",e),this._closed)throw new ma.InvalidStateError("closed");if(!e)throw new TypeError("missing track");if("send"!==this._direction)throw new ma.UnsupportedError("not a sending Transport");if(!this._canProduceByKind[e.kind])throw new ma.UnsupportedError(`cannot produce ${e.kind}`);if("ended"===e.readyState)throw new ma.InvalidStateError("track ended");if(0===this.listenerCount("connect")&&"new"===this._connectionState)throw new TypeError('no "connect" listener set into this transport');if(0===this.listenerCount("produce"))throw new TypeError('no "produce" listener set into this transport');if(c&&"object"!=typeof c)throw new TypeError("if given, appData must be an object");return this._awaitQueue.push((async()=>{let d;if(t&&!Array.isArray(t))throw TypeError("encodings must be an array");t&&0===t.length?d=void 0:t&&(d=t.map((e=>{const t={active:!0};return!1===e.active&&(t.active=!1),"boolean"==typeof e.dtx&&(t.dtx=e.dtx),"string"==typeof e.scalabilityMode&&(t.scalabilityMode=e.scalabilityMode),"number"==typeof e.scaleResolutionDownBy&&(t.scaleResolutionDownBy=e.scaleResolutionDownBy),"number"==typeof e.maxBitrate&&(t.maxBitrate=e.maxBitrate),"number"==typeof e.maxFramerate&&(t.maxFramerate=e.maxFramerate),"boolean"==typeof e.adaptivePtime&&(t.adaptivePtime=e.adaptivePtime),"string"==typeof e.priority&&(t.priority=e.priority),"string"==typeof e.networkPriority&&(t.networkPriority=e.networkPriority),t})));const{localId:l,rtpParameters:u,rtpSender:p}=await this._handler.send({track:e,encodings:d,codecOptions:r,codec:i,onRtpSender:a});try{va.validateRtpParameters(u);const{id:t}=await new Promise(((t,r)=>{this.safeEmit("produce",{kind:e.kind,rtpParameters:u,appData:c},t,r)})),r=new ba.Producer({id:t,localId:l,rtpSender:p,track:e,rtpParameters:u,stopTracks:n,disableTrackOnPause:s,zeroRtpOnPause:o,appData:c});return this._producers.set(r.id,r),this.handleProducer(r),this._observer.safeEmit("newproducer",r),r}catch(e){throw this._handler.stopSending(l).catch((()=>{})),e}}),"transport.produce()").catch((t=>{if(n)try{e.stop()}catch(e){}throw t}))}async consume({id:e,producerId:t,kind:r,rtpParameters:i,streamId:n,onRtpReceiver:s,appData:o={}}){if(Sa.debug("consume()"),this._closed)throw new ma.InvalidStateError("closed");if("recv"!==this._direction)throw new ma.UnsupportedError("not a receiving Transport");if("string"!=typeof e)throw new TypeError("missing id");if("string"!=typeof t)throw new TypeError("missing producerId");if("audio"!==r&&"video"!==r)throw new TypeError(`invalid kind '${r}'`);if(0===this.listenerCount("connect")&&"new"===this._connectionState)throw new TypeError('no "connect" listener set into this transport');if(o&&"object"!=typeof o)throw new TypeError("if given, appData must be an object");const a=ga.clone(i);if(!va.canReceive(a,this._extendedRtpCapabilities))throw new ma.UnsupportedError("cannot consume this Producer");const c=new Ca({id:e,producerId:t,kind:r,rtpParameters:a,streamId:n,onRtpReceiver:s,appData:o});return this._pendingConsumerTasks.push(c),(0,pa.default)((()=>{this._closed||!1===this._consumerCreationInProgress&&this.createPendingConsumers()})),c.promise}async produceData({ordered:e=!0,maxPacketLifeTime:t,maxRetransmits:r,label:i="",protocol:n="",appData:s={}}={}){if(Sa.debug("produceData()"),this._closed)throw new ma.InvalidStateError("closed");if("send"!==this._direction)throw new ma.UnsupportedError("not a sending Transport");if(!this._maxSctpMessageSize)throw new ma.UnsupportedError("SCTP not enabled by remote Transport");if(0===this.listenerCount("connect")&&"new"===this._connectionState)throw new TypeError('no "connect" listener set into this transport');if(0===this.listenerCount("producedata"))throw new TypeError('no "producedata" listener set into this transport');if(s&&"object"!=typeof s)throw new TypeError("if given, appData must be an object");return(t||r)&&(e=!1),this._awaitQueue.push((async()=>{const{dataChannel:o,sctpStreamParameters:a}=await this._handler.sendDataChannel({ordered:e,maxPacketLifeTime:t,maxRetransmits:r,label:i,protocol:n});va.validateSctpStreamParameters(a);const{id:c}=await new Promise(((e,t)=>{this.safeEmit("producedata",{sctpStreamParameters:a,label:i,protocol:n,appData:s},e,t)})),d=new wa.DataProducer({id:c,dataChannel:o,sctpStreamParameters:a,appData:s});return this._dataProducers.set(d.id,d),this.handleDataProducer(d),this._observer.safeEmit("newdataproducer",d),d}),"transport.produceData()")}async consumeData({id:e,dataProducerId:t,sctpStreamParameters:r,label:i="",protocol:n="",appData:s={}}){if(Sa.debug("consumeData()"),this._closed)throw new ma.InvalidStateError("closed");if("recv"!==this._direction)throw new ma.UnsupportedError("not a receiving Transport");if(!this._maxSctpMessageSize)throw new ma.UnsupportedError("SCTP not enabled by remote Transport");if("string"!=typeof e)throw new TypeError("missing id");if("string"!=typeof t)throw new TypeError("missing dataProducerId");if(0===this.listenerCount("connect")&&"new"===this._connectionState)throw new TypeError('no "connect" listener set into this transport');if(s&&"object"!=typeof s)throw new TypeError("if given, appData must be an object");const o=ga.clone(r);return va.validateSctpStreamParameters(o),this._awaitQueue.push((async()=>{const{dataChannel:r}=await this._handler.receiveDataChannel({sctpStreamParameters:o,label:i,protocol:n}),a=new _a.DataConsumer({id:e,dataProducerId:t,dataChannel:r,sctpStreamParameters:o,appData:s});return this._dataConsumers.set(a.id,a),this.handleDataConsumer(a),this._observer.safeEmit("newdataconsumer",a),a}),"transport.consumeData()")}async createPendingConsumers(){this._consumerCreationInProgress=!0,this._awaitQueue.push((async()=>{if(0===this._pendingConsumerTasks.length)return void Sa.debug("createPendingConsumers() | there is no Consumer to be created");const e=[...this._pendingConsumerTasks];let t;this._pendingConsumerTasks=[];const r=[];for(const t of e){const{id:e,kind:i,rtpParameters:n,streamId:s,onRtpReceiver:o}=t.consumerOptions;r.push({trackId:e,kind:i,rtpParameters:n,streamId:s,onRtpReceiver:o})}try{const i=await this._handler.receive(r);for(let r=0;r<i.length;++r){const n=e[r],s=i[r],{id:o,producerId:a,kind:c,rtpParameters:d,appData:l}=n.consumerOptions,{localId:u,rtpReceiver:p,track:h}=s,f=new ya.Consumer({id:o,localId:u,producerId:a,rtpReceiver:p,track:h,rtpParameters:d,appData:l});this._consumers.set(f.id,f),this.handleConsumer(f),this._probatorConsumerCreated||t||"video"!==c||(t=f),this._observer.safeEmit("newconsumer",f),n.resolve(f)}}catch(t){for(const r of e)r.reject(t)}if(t)try{const e=va.generateProbatorRtpParameters(t.rtpParameters);await this._handler.receive([{trackId:"probator",kind:"video",rtpParameters:e}]),Sa.debug("createPendingConsumers() | Consumer for RTP probation created"),this._probatorConsumerCreated=!0}catch(e){Sa.error("createPendingConsumers() | failed to create Consumer for RTP probation:%o",e)}}),"transport.createPendingConsumers()").then((()=>{this._consumerCreationInProgress=!1,this._pendingConsumerTasks.length>0&&this.createPendingConsumers()})).catch((()=>{}))}pausePendingConsumers(){this._consumerPauseInProgress=!0,this._awaitQueue.push((async()=>{if(0===this._pendingPauseConsumers.size)return void Sa.debug("pausePendingConsumers() | there is no Consumer to be paused");const e=Array.from(this._pendingPauseConsumers.values());this._pendingPauseConsumers.clear();try{const t=e.map((e=>e.localId));await this._handler.pauseReceiving(t)}catch(e){Sa.error("pausePendingConsumers() | failed to pause Consumers:",e)}}),"transport.pausePendingConsumers").then((()=>{this._consumerPauseInProgress=!1,this._pendingPauseConsumers.size>0&&this.pausePendingConsumers()})).catch((()=>{}))}resumePendingConsumers(){this._consumerResumeInProgress=!0,this._awaitQueue.push((async()=>{if(0===this._pendingResumeConsumers.size)return void Sa.debug("resumePendingConsumers() | there is no Consumer to be resumed");const e=Array.from(this._pendingResumeConsumers.values());this._pendingResumeConsumers.clear();try{const t=e.map((e=>e.localId));await this._handler.resumeReceiving(t)}catch(e){Sa.error("resumePendingConsumers() | failed to resume Consumers:",e)}}),"transport.resumePendingConsumers").then((()=>{this._consumerResumeInProgress=!1,this._pendingResumeConsumers.size>0&&this.resumePendingConsumers()})).catch((()=>{}))}closePendingConsumers(){this._consumerCloseInProgress=!0,this._awaitQueue.push((async()=>{if(0===this._pendingCloseConsumers.size)return void Sa.debug("closePendingConsumers() | there is no Consumer to be closed");const e=Array.from(this._pendingCloseConsumers.values());this._pendingCloseConsumers.clear();try{await this._handler.stopReceiving(e.map((e=>e.localId)))}catch(e){Sa.error("closePendingConsumers() | failed to close Consumers:",e)}}),"transport.closePendingConsumers").then((()=>{this._consumerCloseInProgress=!1,this._pendingCloseConsumers.size>0&&this.closePendingConsumers()})).catch((()=>{}))}handleHandler(){const e=this._handler;e.on("@connect",(({dtlsParameters:e},t,r)=>{this._closed?r(new ma.InvalidStateError("closed")):this.safeEmit("connect",{dtlsParameters:e},t,r)})),e.on("@icegatheringstatechange",(e=>{e!==this._iceGatheringState&&(Sa.debug("ICE gathering state changed to %s",e),this._iceGatheringState=e,this._closed||this.safeEmit("icegatheringstatechange",e))})),e.on("@connectionstatechange",(e=>{e!==this._connectionState&&(Sa.debug("connection state changed to %s",e),this._connectionState=e,this._closed||this.safeEmit("connectionstatechange",e))}))}handleProducer(e){e.on("@close",(()=>{this._producers.delete(e.id),this._closed||this._awaitQueue.push((async()=>await this._handler.stopSending(e.localId)),"producer @close event").catch((e=>Sa.warn("producer.close() failed:%o",e)))})),e.on("@pause",((t,r)=>{this._awaitQueue.push((async()=>await this._handler.pauseSending(e.localId)),"producer @pause event").then(t).catch(r)})),e.on("@resume",((t,r)=>{this._awaitQueue.push((async()=>await this._handler.resumeSending(e.localId)),"producer @resume event").then(t).catch(r)})),e.on("@replacetrack",((t,r,i)=>{this._awaitQueue.push((async()=>await this._handler.replaceTrack(e.localId,t)),"producer @replacetrack event").then(r).catch(i)})),e.on("@setmaxspatiallayer",((t,r,i)=>{this._awaitQueue.push((async()=>await this._handler.setMaxSpatialLayer(e.localId,t)),"producer @setmaxspatiallayer event").then(r).catch(i)})),e.on("@setrtpencodingparameters",((t,r,i)=>{this._awaitQueue.push((async()=>await this._handler.setRtpEncodingParameters(e.localId,t)),"producer @setrtpencodingparameters event").then(r).catch(i)})),e.on("@getstats",((t,r)=>{if(this._closed)return r(new ma.InvalidStateError("closed"));this._handler.getSenderStats(e.localId).then(t).catch(r)}))}handleConsumer(e){e.on("@close",(()=>{this._consumers.delete(e.id),this._pendingPauseConsumers.delete(e.id),this._pendingResumeConsumers.delete(e.id),this._closed||(this._pendingCloseConsumers.set(e.id,e),!1===this._consumerCloseInProgress&&this.closePendingConsumers())})),e.on("@pause",(()=>{this._pendingResumeConsumers.has(e.id)&&this._pendingResumeConsumers.delete(e.id),this._pendingPauseConsumers.set(e.id,e),(0,pa.default)((()=>{this._closed||!1===this._consumerPauseInProgress&&this.pausePendingConsumers()}))})),e.on("@resume",(()=>{this._pendingPauseConsumers.has(e.id)&&this._pendingPauseConsumers.delete(e.id),this._pendingResumeConsumers.set(e.id,e),(0,pa.default)((()=>{this._closed||!1===this._consumerResumeInProgress&&this.resumePendingConsumers()}))})),e.on("@getstats",((t,r)=>{if(this._closed)return r(new ma.InvalidStateError("closed"));this._handler.getReceiverStats(e.localId).then(t).catch(r)}))}handleDataProducer(e){e.on("@close",(()=>{this._dataProducers.delete(e.id)}))}handleDataConsumer(e){e.on("@close",(()=>{this._dataConsumers.delete(e.id)}))}};xo.Transport=Ra;var ka={},Ta={},Pa={},Oa={exports:{}},Ea=Oa.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(e){return e.encoding?"rtpmap:%d %s/%s/%s":e.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(e){return null!=e.address?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(e){return null!=e.subtype?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(e){return"extmap:%d"+(e.direction?"/%s":"%v")+(e["encrypt-uri"]?" %s":"%v")+" %s"+(e.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(e){return null!=e.sessionConfig?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(e){var t="candidate:%s %d %s %d %s %d typ %s";return t+=null!=e.raddr?" raddr %s rport %d":"%v%v",t+=null!=e.tcptype?" tcptype %s":"%v",null!=e.generation&&(t+=" generation %d"),t+=null!=e["network-id"]?" network-id %d":"%v",t+=null!=e["network-cost"]?" network-cost %d":"%v"}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(e){var t="ssrc:%d";return null!=e.attribute&&(t+=" %s",null!=e.value&&(t+=":%s")),t}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(e){return null!=e.maxMessageSize?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(e){return e.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(e){return"imageattr:%s %s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(e){return"simulcast:%s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(e){return"ts-refclk:%s"+(null!=e.clksrcExt?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(e){var t="mediaclk:";return t+=null!=e.id?"id=%s %s":"%v%s",t+=null!=e.mediaClockValue?"=%s":"",t+=null!=e.rateNumerator?" rate=%s":"",t+=null!=e.rateDenominator?"/%s":""}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};Object.keys(Ea).forEach((function(e){Ea[e].forEach((function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")}))}));var Da=Oa.exports;!function(e){var t=function(e){return String(Number(e))===e?Number(e):e},r=function(e,r,i){var n=e.name&&e.names;e.push&&!r[e.push]?r[e.push]=[]:n&&!r[e.name]&&(r[e.name]={});var s=e.push?{}:n?r[e.name]:r;!function(e,r,i,n){if(n&&!i)r[n]=t(e[1]);else for(var s=0;s<i.length;s+=1)null!=e[s+1]&&(r[i[s]]=t(e[s+1]))}(i.match(e.reg),s,e.names,e.name),e.push&&r[e.push].push(s)},i=Da,n=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},s=[],o=t;return e.split(/(\r\n|\r|\n)/).filter(n).forEach((function(e){var t=e[0],n=e.slice(2);"m"===t&&(s.push({rtp:[],fmtp:[]}),o=s[s.length-1]);for(var a=0;a<(i[t]||[]).length;a+=1){var c=i[t][a];if(c.reg.test(n))return r(c,o,n)}})),t.media=s,t};var s=function(e,r){var i=r.split(/=(.+)/,2);return 2===i.length?e[i[0]]=t(i[1]):1===i.length&&r.length>1&&(e[i[0]]=void 0),e};e.parseParams=function(e){return e.split(/;\s?/).reduce(s,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(e){return e.toString().split(" ").map(Number)},e.parseRemoteCandidates=function(e){for(var r=[],i=e.split(" ").map(t),n=0;n<i.length;n+=3)r.push({component:i[n],ip:i[n+1],port:i[n+2]});return r},e.parseImageAttributes=function(e){return e.split(" ").map((function(e){return e.substring(1,e.length-1).split(",").reduce(s,{})}))},e.parseSimulcastStreamList=function(e){return e.split(";").map((function(e){return e.split(",").map((function(e){var r,i=!1;return"~"!==e[0]?r=t(e):(r=t(e.substring(1,e.length)),i=!0),{scid:r,paused:i}}))}))}}(Pa);var Ia=Da,xa=/%[sdv%]/g,Ma=function(e){var t=1,r=arguments,i=r.length;return e.replace(xa,(function(e){if(t>=i)return e;var n=r[t];switch(t+=1,e){case"%%":return"%";case"%s":return String(n);case"%d":return Number(n);case"%v":return""}}))},ja=function(e,t,r){var i=[e+"="+(t.format instanceof Function?t.format(t.push?r:r[t.name]):t.format)];if(t.names)for(var n=0;n<t.names.length;n+=1){var s=t.names[n];t.name?i.push(r[t.name][s]):i.push(r[t.names[n]])}else i.push(r[t.name]);return Ma.apply(null,i)},La=["v","o","s","i","u","e","p","c","b","t","r","z","a"],Aa=["i","c","b","a"],Na=Pa,Ba=function(e,t){t=t||{},null==e.version&&(e.version=0),null==e.name&&(e.name=" "),e.media.forEach((function(e){null==e.payloads&&(e.payloads="")}));var r=t.outerOrder||La,i=t.innerOrder||Aa,n=[];return r.forEach((function(t){Ia[t].forEach((function(r){r.name in e&&null!=e[r.name]?n.push(ja(t,r,e)):r.push in e&&null!=e[r.push]&&e[r.push].forEach((function(e){n.push(ja(t,r,e))}))}))})),e.media.forEach((function(e){n.push(ja("m",Ia.m[0],e)),i.forEach((function(t){Ia[t].forEach((function(r){r.name in e&&null!=e[r.name]?n.push(ja(t,r,e)):r.push in e&&null!=e[r.push]&&e[r.push].forEach((function(e){n.push(ja(t,r,e))}))}))}))})),n.join("\r\n")+"\r\n"},Fa=Da;Ta.grammar=Fa,Ta.write=Ba,Ta.parse=Na.parse,Ta.parseParams=Na.parseParams,Ta.parseFmtpConfig=Na.parseFmtpConfig,Ta.parsePayloads=Na.parsePayloads,Ta.parseRemoteCandidates=Na.parseRemoteCandidates,Ta.parseImageAttributes=Na.parseImageAttributes,Ta.parseSimulcastStreamList=Na.parseSimulcastStreamList;var za={},Va=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),Ua=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),$a=a&&a.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(null!=t)for(var i=e(t),n=0;n<i.length;n++)"default"!==i[n]&&Va(r,t,i[n]);return Ua(r,t),r}}();Object.defineProperty(za,"__esModule",{value:!0});var Ga=za.extractRtpCapabilities=function({sdpObject:e}){const t=new Map,r=[];let i=!1,n=!1;for(const s of e.media){const e=s.type;switch(e){case"audio":if(i)continue;i=!0;break;case"video":if(n)continue;n=!0;break;default:continue}for(const r of s.rtp){const i={kind:e,mimeType:`${e}/${r.codec}`,preferredPayloadType:r.payload,clockRate:r.rate,channels:r.encoding,parameters:{},rtcpFeedback:[]};t.set(i.preferredPayloadType,i)}for(const e of s.fmtp||[]){const r=Ka.parseParams(e.config),i=t.get(e.payload);i&&(r?.hasOwnProperty("profile-level-id")&&(r["profile-level-id"]=String(r["profile-level-id"])),i.parameters=r)}for(const r of s.rtcpFb||[]){const i={type:r.type,parameter:r.subtype};if(i.parameter||delete i.parameter,"*"!==r.payload){const e=t.get(r.payload);if(!e)continue;e.rtcpFeedback.push(i)}else for(const r of t.values())r.kind!==e||/.+\/rtx$/i.test(r.mimeType)||r.rtcpFeedback.push(i)}for(const t of s.ext||[]){if(t["encrypt-uri"])continue;const i={kind:e,uri:t.uri,preferredId:t.value};r.push(i)}}return{codecs:Array.from(t.values()),headerExtensions:r}},qa=za.extractDtlsParameters=function({sdpObject:e}){let t,r=e.setup,i=e.fingerprint;if(!r||!i){const t=(e.media||[]).find((e=>0!==e.port));t&&(r??(r=t.setup),i??(i=t.fingerprint))}if(!r)throw new Error("no a=setup found at SDP session or media level");if(!i)throw new Error("no a=fingerprint found at SDP session or media level");switch(r){case"active":t="client";break;case"passive":t="server";break;case"actpass":t="auto"}return{role:t,fingerprints:[{algorithm:i.type,value:i.hash}]}},Ha=za.getCname=function({offerMediaObject:e}){const t=(e.ssrcs||[]).find((e=>"cname"===e.attribute));if(!t)return"";return t.value},Wa=za.applyCodecParameters=function({offerRtpParameters:e,answerMediaObject:t}){for(const r of e.codecs){const e=r.mimeType.toLowerCase();if("audio/opus"!==e)continue;if(!(t.rtp||[]).find((e=>e.payload===r.payloadType)))continue;t.fmtp=t.fmtp||[];let i=t.fmtp.find((e=>e.payload===r.payloadType));i||(i={payload:r.payloadType,config:""},t.fmtp.push(i));const n=Ka.parseParams(i.config);switch(e){case"audio/opus":{const e=r.parameters["sprop-stereo"];void 0!==e&&(n.stereo=Number(e)?1:0);break}}i.config="";for(const e of Object.keys(n))i.config&&(i.config+=";"),i.config+=`${e}=${n[e]}`}};const Ka=$a(Ta);var Ja={};Object.defineProperty(Ja,"__esModule",{value:!0}),Ja.getRtpEncodings=function({offerMediaObject:e}){const t=new Set;for(const r of e.ssrcs||[]){const e=r.id;t.add(e)}if(0===t.size)throw new Error("no a=ssrc lines found");const r=new Map;for(const i of e.ssrcGroups||[]){if("FID"!==i.semantics)continue;let[e,n]=i.ssrcs.split(/\s+/);e=Number(e),n=Number(n),t.has(e)&&(t.delete(e),t.delete(n),r.set(e,n))}for(const e of t)r.set(e,null);const i=[];for(const[e,t]of r){const r={ssrc:e};t&&(r.rtx={ssrc:t}),i.push(r)}return i},Ja.addLegacySimulcast=function({offerMediaObject:e,numStreams:t}){if(t<=1)throw new TypeError("numStreams must be greater than 1");const r=(e.ssrcs||[]).find((e=>"msid"===e.attribute));if(!r)throw new Error("a=ssrc line with msid information not found");const[i,n]=r.value.split(" "),s=Number(r.id);let o;(e.ssrcGroups||[]).some((e=>{if("FID"!==e.semantics)return!1;const t=e.ssrcs.split(/\s+/);return Number(t[0])===s&&(o=Number(t[1]),!0)}));const a=e.ssrcs.find((e=>"cname"===e.attribute));if(!a)throw new Error("a=ssrc line with cname information not found");const c=a.value,d=[],l=[];for(let e=0;e<t;++e)d.push(s+e),o&&l.push(o+e);e.ssrcGroups=[],e.ssrcs=[],e.ssrcGroups.push({semantics:"SIM",ssrcs:d.join(" ")});for(const t of d)e.ssrcs.push({id:t,attribute:"cname",value:c}),e.ssrcs.push({id:t,attribute:"msid",value:`${i} ${n}`});for(let t=0;t<l.length;++t){const r=d[t],s=l[t];e.ssrcs.push({id:s,attribute:"cname",value:c}),e.ssrcs.push({id:s,attribute:"msid",value:`${i} ${n}`}),e.ssrcGroups.push({semantics:"FID",ssrcs:`${r} ${s}`})}};var Xa={};Object.defineProperty(Xa,"__esModule",{value:!0});var Qa=Xa.addNackSuppportForOpus=function(e){for(const t of e.codecs??[])"audio/opus"!==t.mimeType.toLowerCase()&&"audio/multiopus"!==t.mimeType.toLowerCase()||t.rtcpFeedback?.some((e=>"nack"===e.type&&!e.parameter))||(t.rtcpFeedback||(t.rtcpFeedback=[]),t.rtcpFeedback.push({type:"nack"}))};var Za={};Object.defineProperty(Za,"__esModule",{value:!0});var Ya=Za.HandlerInterface=void 0;const ec=us;class tc extends ec.EnhancedEventEmitter{constructor(){super()}}Ya=Za.HandlerInterface=tc;var rc={},ic={},nc=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),sc=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),oc=a&&a.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(null!=t)for(var i=e(t),n=0;n<i.length;n++)"default"!==i[n]&&nc(r,t,i[n]);return sc(r,t),r}}();Object.defineProperty(ic,"__esModule",{value:!0}),ic.OfferMediaSection=ic.AnswerMediaSection=ic.MediaSection=void 0;const ac=oc(Ta),cc=oc(Ls);class dc{constructor({iceParameters:e,iceCandidates:t,dtlsParameters:r,planB:i=!1}){if(this._mediaObject={},this._planB=i,e&&this.setIceParameters(e),t){this._mediaObject.candidates=[];for(const e of t){const t={component:1};t.foundation=e.foundation,t.ip=e.address??e.ip,t.port=e.port,t.priority=e.priority,t.transport=e.protocol,t.type=e.type,e.tcpType&&(t.tcptype=e.tcpType),this._mediaObject.candidates.push(t)}this._mediaObject.endOfCandidates="end-of-candidates",this._mediaObject.iceOptions="renomination"}r&&this.setDtlsRole(r.role)}get mid(){return String(this._mediaObject.mid)}get closed(){return 0===this._mediaObject.port}getObject(){return this._mediaObject}setIceParameters(e){this._mediaObject.iceUfrag=e.usernameFragment,this._mediaObject.icePwd=e.password}pause(){this._mediaObject.direction="inactive"}disable(){this.pause(),delete this._mediaObject.ext,delete this._mediaObject.ssrcs,delete this._mediaObject.ssrcGroups,delete this._mediaObject.simulcast,delete this._mediaObject.simulcast_03,delete this._mediaObject.rids,delete this._mediaObject.extmapAllowMixed}close(){this.disable(),this._mediaObject.port=0}}ic.MediaSection=dc;ic.AnswerMediaSection=class extends dc{constructor({iceParameters:e,iceCandidates:t,dtlsParameters:r,sctpParameters:i,plainRtpParameters:n,planB:s=!1,offerMediaObject:o,offerRtpParameters:a,answerRtpParameters:c,codecOptions:d,extmapAllowMixed:l=!1}){switch(super({iceParameters:e,iceCandidates:t,dtlsParameters:r,planB:s}),this._mediaObject.mid=String(o.mid),this._mediaObject.type=o.type,this._mediaObject.protocol=o.protocol,n?(this._mediaObject.connection={ip:n.ip,version:n.ipVersion},this._mediaObject.port=n.port):(this._mediaObject.connection={ip:"127.0.0.1",version:4},this._mediaObject.port=7),o.type){case"audio":case"video":this._mediaObject.direction="recvonly",this._mediaObject.rtp=[],this._mediaObject.rtcpFb=[],this._mediaObject.fmtp=[];for(const e of c.codecs){const t={payload:e.payloadType,codec:lc(e),rate:e.clockRate};e.channels>1&&(t.encoding=e.channels),this._mediaObject.rtp.push(t);const r=cc.clone(e.parameters)??{};let i=cc.clone(e.rtcpFeedback)??[];if(d){const{opusStereo:t,opusFec:n,opusDtx:s,opusMaxPlaybackRate:o,opusMaxAverageBitrate:c,opusPtime:l,opusNack:u,videoGoogleStartBitrate:p,videoGoogleMaxBitrate:h,videoGoogleMinBitrate:f}=d,m=a.codecs.find((t=>t.payloadType===e.payloadType));switch(e.mimeType.toLowerCase()){case"audio/opus":case"audio/multiopus":void 0!==t&&(m.parameters["sprop-stereo"]=t?1:0,r.stereo=t?1:0),void 0!==n&&(m.parameters.useinbandfec=n?1:0,r.useinbandfec=n?1:0),void 0!==s&&(m.parameters.usedtx=s?1:0,r.usedtx=s?1:0),void 0!==o&&(r.maxplaybackrate=o),void 0!==c&&(r.maxaveragebitrate=c),void 0!==l&&(m.parameters.ptime=l,r.ptime=l),u||(m.rtcpFeedback=m.rtcpFeedback.filter((e=>"nack"!==e.type||e.parameter)),i=i.filter((e=>"nack"!==e.type||e.parameter)));break;case"video/vp8":case"video/vp9":case"video/h264":case"video/h265":void 0!==p&&(r["x-google-start-bitrate"]=p),void 0!==h&&(r["x-google-max-bitrate"]=h),void 0!==f&&(r["x-google-min-bitrate"]=f)}}const n={payload:e.payloadType,config:""};for(const e of Object.keys(r))n.config&&(n.config+=";"),n.config+=`${e}=${r[e]}`;n.config&&this._mediaObject.fmtp.push(n);for(const t of i)this._mediaObject.rtcpFb.push({payload:e.payloadType,type:t.type,subtype:t.parameter})}this._mediaObject.payloads=c.codecs.map((e=>e.payloadType)).join(" "),this._mediaObject.ext=[];for(const e of c.headerExtensions){(o.ext??[]).some((t=>t.uri===e.uri))&&this._mediaObject.ext.push({uri:e.uri,value:e.id})}if(l&&"extmap-allow-mixed"===o.extmapAllowMixed&&(this._mediaObject.extmapAllowMixed="extmap-allow-mixed"),o.simulcast){this._mediaObject.simulcast={dir1:"recv",list1:o.simulcast.list1},this._mediaObject.rids=[];for(const e of o.rids??[])"send"===e.direction&&this._mediaObject.rids.push({id:e.id,direction:"recv"})}else if(o.simulcast_03){this._mediaObject.simulcast_03={value:o.simulcast_03.value.replace(/send/g,"recv")},this._mediaObject.rids=[];for(const e of o.rids??[])"send"===e.direction&&this._mediaObject.rids.push({id:e.id,direction:"recv"})}this._mediaObject.rtcpMux="rtcp-mux",this._mediaObject.rtcpRsize="rtcp-rsize",this._planB&&"video"===this._mediaObject.type&&(this._mediaObject.xGoogleFlag="conference");break;case"application":"number"==typeof o.sctpPort?(this._mediaObject.payloads="webrtc-datachannel",this._mediaObject.sctpPort=i.port,this._mediaObject.maxMessageSize=i.maxMessageSize):o.sctpmap&&(this._mediaObject.payloads=i.port,this._mediaObject.sctpmap={app:"webrtc-datachannel",sctpmapNumber:i.port,maxMessageSize:i.maxMessageSize})}}setDtlsRole(e){switch(e){case"client":this._mediaObject.setup="active";break;case"server":this._mediaObject.setup="passive";break;case"auto":this._mediaObject.setup="actpass"}}resume(){this._mediaObject.direction="recvonly"}muxSimulcastStreams(e){if(!this._mediaObject.simulcast?.list1)return;const t={};for(const r of e)r.rid&&(t[r.rid]=r);const r=this._mediaObject.simulcast.list1,i=ac.parseSimulcastStreamList(r);for(const e of i)for(const r of e)r.paused=!t[r.scid]?.active;this._mediaObject.simulcast.list1=i.map((e=>e.map((e=>`${e.paused?"~":""}${e.scid}`)).join(","))).join(";")}};function lc(e){const t=new RegExp("^(audio|video)/(.+)","i").exec(e.mimeType);if(!t)throw new TypeError("invalid codec.mimeType");return t[2]}ic.OfferMediaSection=class extends dc{constructor({iceParameters:e,iceCandidates:t,dtlsParameters:r,sctpParameters:i,plainRtpParameters:n,planB:s=!1,mid:o,kind:a,offerRtpParameters:c,streamId:d,trackId:l,oldDataChannelSpec:u=!1}){switch(super({iceParameters:e,iceCandidates:t,dtlsParameters:r,planB:s}),this._mediaObject.mid=String(o),this._mediaObject.type=a,n?(this._mediaObject.connection={ip:n.ip,version:n.ipVersion},this._mediaObject.protocol="RTP/AVP",this._mediaObject.port=n.port):(this._mediaObject.connection={ip:"127.0.0.1",version:4},this._mediaObject.protocol=i?"UDP/DTLS/SCTP":"UDP/TLS/RTP/SAVPF",this._mediaObject.port=7),a){case"audio":case"video":{this._mediaObject.direction="sendonly",this._mediaObject.rtp=[],this._mediaObject.rtcpFb=[],this._mediaObject.fmtp=[],this._planB||(this._mediaObject.msid=`${d??"-"} ${l}`);for(const e of c.codecs){const t={payload:e.payloadType,codec:lc(e),rate:e.clockRate};e.channels>1&&(t.encoding=e.channels),this._mediaObject.rtp.push(t);const r={payload:e.payloadType,config:""};for(const t of Object.keys(e.parameters))r.config&&(r.config+=";"),r.config+=`${t}=${e.parameters[t]}`;r.config&&this._mediaObject.fmtp.push(r);for(const t of e.rtcpFeedback)this._mediaObject.rtcpFb.push({payload:e.payloadType,type:t.type,subtype:t.parameter})}this._mediaObject.payloads=c.codecs.map((e=>e.payloadType)).join(" "),this._mediaObject.ext=[];for(const e of c.headerExtensions)this._mediaObject.ext.push({uri:e.uri,value:e.id});this._mediaObject.rtcpMux="rtcp-mux",this._mediaObject.rtcpRsize="rtcp-rsize";const e=c.encodings[0],t=e.ssrc,r=e.rtx?.ssrc;this._mediaObject.ssrcs=[],this._mediaObject.ssrcGroups=[],c.rtcp.cname&&this._mediaObject.ssrcs.push({id:t,attribute:"cname",value:c.rtcp.cname}),this._planB&&this._mediaObject.ssrcs.push({id:t,attribute:"msid",value:`${d??"-"} ${l}`}),r&&(c.rtcp.cname&&this._mediaObject.ssrcs.push({id:r,attribute:"cname",value:c.rtcp.cname}),this._planB&&this._mediaObject.ssrcs.push({id:r,attribute:"msid",value:`${d??"-"} ${l}`}),this._mediaObject.ssrcGroups.push({semantics:"FID",ssrcs:`${t} ${r}`}));break}case"application":u?(this._mediaObject.payloads=i.port,this._mediaObject.sctpmap={app:"webrtc-datachannel",sctpmapNumber:i.port,maxMessageSize:i.maxMessageSize}):(this._mediaObject.payloads="webrtc-datachannel",this._mediaObject.sctpPort=i.port,this._mediaObject.maxMessageSize=i.maxMessageSize)}}setDtlsRole(e){this._mediaObject.setup="actpass"}resume(){this._mediaObject.direction="sendonly"}planBReceive({offerRtpParameters:e,streamId:t,trackId:r}){const i=e.encodings[0],n=i.ssrc,s=i.rtx?.ssrc,o=this._mediaObject.payloads.split(" ");for(const t of e.codecs){if(o.includes(String(t.payloadType)))continue;const e={payload:t.payloadType,codec:lc(t),rate:t.clockRate};t.channels>1&&(e.encoding=t.channels),this._mediaObject.rtp.push(e);const r={payload:t.payloadType,config:""};for(const e of Object.keys(t.parameters))r.config&&(r.config+=";"),r.config+=`${e}=${t.parameters[e]}`;r.config&&this._mediaObject.fmtp.push(r);for(const e of t.rtcpFeedback)this._mediaObject.rtcpFb.push({payload:t.payloadType,type:e.type,subtype:e.parameter})}this._mediaObject.payloads+=` ${e.codecs.filter((e=>!this._mediaObject.payloads.includes(e.payloadType))).map((e=>e.payloadType)).join(" ")}`,this._mediaObject.payloads=this._mediaObject.payloads.trim(),e.rtcp.cname&&this._mediaObject.ssrcs.push({id:n,attribute:"cname",value:e.rtcp.cname}),this._mediaObject.ssrcs.push({id:n,attribute:"msid",value:`${t??"-"} ${r}`}),s&&(e.rtcp.cname&&this._mediaObject.ssrcs.push({id:s,attribute:"cname",value:e.rtcp.cname}),this._mediaObject.ssrcs.push({id:s,attribute:"msid",value:`${t??"-"} ${r}`}),this._mediaObject.ssrcGroups.push({semantics:"FID",ssrcs:`${n} ${s}`}))}planBStopReceiving({offerRtpParameters:e}){const t=e.encodings[0],r=t.ssrc,i=t.rtx?.ssrc;this._mediaObject.ssrcs=this._mediaObject.ssrcs.filter((e=>e.id!==r&&e.id!==i)),i&&(this._mediaObject.ssrcGroups=this._mediaObject.ssrcGroups.filter((e=>e.ssrcs!==`${r} ${i}`)))}};var uc=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),pc=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),hc=a&&a.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(null!=t)for(var i=e(t),n=0;n<i.length;n++)"default"!==i[n]&&uc(r,t,i[n]);return pc(r,t),r}}();Object.defineProperty(rc,"__esModule",{value:!0});var fc=rc.RemoteSdp=void 0;const mc=hc(Ta),gc=ic,vc=new ss.Logger("RemoteSdp");fc=rc.RemoteSdp=class{constructor({iceParameters:e,iceCandidates:t,dtlsParameters:r,sctpParameters:i,plainRtpParameters:n,planB:s=!1}){if(this._mediaSections=[],this._midToIndex=new Map,this._iceParameters=e,this._iceCandidates=t,this._dtlsParameters=r,this._sctpParameters=i,this._plainRtpParameters=n,this._planB=s,this._sdpObject={version:0,origin:{address:"0.0.0.0",ipVer:4,netType:"IN",sessionId:1e4,sessionVersion:0,username:"mediasoup-client"},name:"-",timing:{start:0,stop:0},media:[]},e?.iceLite&&(this._sdpObject.icelite="ice-lite"),r){this._sdpObject.msidSemantic={semantic:"WMS",token:"*"};const e=this._dtlsParameters.fingerprints.length;this._sdpObject.fingerprint={type:r.fingerprints[e-1].algorithm,hash:r.fingerprints[e-1].value},this._sdpObject.groups=[{type:"BUNDLE",mids:""}]}n&&(this._sdpObject.origin.address=n.ip,this._sdpObject.origin.ipVer=n.ipVersion)}updateIceParameters(e){vc.debug("updateIceParameters() [iceParameters:%o]",e),this._iceParameters=e,this._sdpObject.icelite=e.iceLite?"ice-lite":void 0;for(const t of this._mediaSections)t.setIceParameters(e)}updateDtlsRole(e){vc.debug("updateDtlsRole() [role:%s]",e),this._dtlsParameters.role=e;for(const t of this._mediaSections)t.setDtlsRole(e)}getNextMediaSectionIdx(){for(let e=0;e<this._mediaSections.length;++e){const t=this._mediaSections[e];if(t.closed)return{idx:e,reuseMid:t.mid}}return{idx:this._mediaSections.length}}send({offerMediaObject:e,reuseMid:t,offerRtpParameters:r,answerRtpParameters:i,codecOptions:n,extmapAllowMixed:s=!1}){const o=new gc.AnswerMediaSection({iceParameters:this._iceParameters,iceCandidates:this._iceCandidates,dtlsParameters:this._dtlsParameters,plainRtpParameters:this._plainRtpParameters,planB:this._planB,offerMediaObject:e,offerRtpParameters:r,answerRtpParameters:i,codecOptions:n,extmapAllowMixed:s});t?this._replaceMediaSection(o,t):this._midToIndex.has(o.mid)?this._replaceMediaSection(o):this._addMediaSection(o)}receive({mid:e,kind:t,offerRtpParameters:r,streamId:i,trackId:n}){const s=this._midToIndex.get(e);let o;if(void 0!==s&&(o=this._mediaSections[s]),o)o.planBReceive({offerRtpParameters:r,streamId:i,trackId:n}),this._replaceMediaSection(o);else{o=new gc.OfferMediaSection({iceParameters:this._iceParameters,iceCandidates:this._iceCandidates,dtlsParameters:this._dtlsParameters,plainRtpParameters:this._plainRtpParameters,planB:this._planB,mid:e,kind:t,offerRtpParameters:r,streamId:i,trackId:n});const s=this._mediaSections.find((e=>e.closed));s?this._replaceMediaSection(o,s.mid):this._addMediaSection(o)}}pauseMediaSection(e){this._findMediaSection(e).pause()}resumeSendingMediaSection(e){this._findMediaSection(e).resume()}resumeReceivingMediaSection(e){this._findMediaSection(e).resume()}disableMediaSection(e){this._findMediaSection(e).disable()}closeMediaSection(e){const t=this._findMediaSection(e);return e===this._firstMid?(vc.debug("closeMediaSection() | cannot close first media section, disabling it instead [mid:%s]",e),this.disableMediaSection(e),!1):(t.close(),this._regenerateBundleMids(),!0)}muxMediaSectionSimulcast(e,t){const r=this._findMediaSection(e);r.muxSimulcastStreams(t),this._replaceMediaSection(r)}planBStopReceiving({mid:e,offerRtpParameters:t}){const r=this._findMediaSection(e);r.planBStopReceiving({offerRtpParameters:t}),this._replaceMediaSection(r)}sendSctpAssociation({offerMediaObject:e}){const t=new gc.AnswerMediaSection({iceParameters:this._iceParameters,iceCandidates:this._iceCandidates,dtlsParameters:this._dtlsParameters,sctpParameters:this._sctpParameters,plainRtpParameters:this._plainRtpParameters,offerMediaObject:e});this._addMediaSection(t)}receiveSctpAssociation({oldDataChannelSpec:e=!1}={}){const t=new gc.OfferMediaSection({iceParameters:this._iceParameters,iceCandidates:this._iceCandidates,dtlsParameters:this._dtlsParameters,sctpParameters:this._sctpParameters,plainRtpParameters:this._plainRtpParameters,mid:"datachannel",kind:"application",oldDataChannelSpec:e});this._addMediaSection(t)}getSdp(){return this._sdpObject.origin.sessionVersion++,mc.write(this._sdpObject)}_addMediaSection(e){this._firstMid||(this._firstMid=e.mid),this._mediaSections.push(e),this._midToIndex.set(e.mid,this._mediaSections.length-1),this._sdpObject.media.push(e.getObject()),this._regenerateBundleMids()}_replaceMediaSection(e,t){if("string"==typeof t){const r=this._midToIndex.get(t);if(void 0===r)throw new Error(`no media section found for reuseMid '${t}'`);const i=this._mediaSections[r];this._mediaSections[r]=e,this._midToIndex.delete(i.mid),this._midToIndex.set(e.mid,r),this._sdpObject.media[r]=e.getObject(),this._regenerateBundleMids()}else{const t=this._midToIndex.get(e.mid);if(void 0===t)throw new Error(`no media section found with mid '${e.mid}'`);this._mediaSections[t]=e,this._sdpObject.media[t]=e.getObject()}}_findMediaSection(e){const t=this._midToIndex.get(e);if(void 0===t)throw new Error(`no media section found with mid '${e}'`);return this._mediaSections[t]}_regenerateBundleMids(){this._dtlsParameters&&(this._sdpObject.groups[0].mids=this._mediaSections.filter((e=>!e.closed)).map((e=>e.mid)).join(" "))}};var bc={};Object.defineProperty(bc,"__esModule",{value:!0});var yc=bc.parse=function(e){const t=wc.exec(e??"");return t?{spatialLayers:Number(t[1]),temporalLayers:Number(t[2])}:{spatialLayers:1,temporalLayers:1}};const wc=new RegExp("^[LS]([1-9]\\d{0,1})T([1-9]\\d{0,1})");var _c=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),Sc=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Cc=a&&a.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(null!=t)for(var i=e(t),n=0;n<i.length;n++)"default"!==i[n]&&_c(r,t,i[n]);return Sc(r,t),r}}();Object.defineProperty(ka,"__esModule",{value:!0}),ka.Chrome111=void 0;const Rc=Cc(Ta),kc=ss,Tc=Cc(Ls),Pc=Cc(Fs),Oc=Cc(za),Ec=Cc(Ja),Dc=Cc(Xa),Ic=Is,xc=Za,Mc=rc,jc=bc,Lc=new kc.Logger("Chrome111"),Ac={OS:1024,MIS:1024};class Nc extends xc.HandlerInterface{static createFactory(){return()=>new Nc}constructor(){super(),this._closed=!1,this._mapMidTransceiver=new Map,this._sendStream=new MediaStream,this._hasDataChannelMediaSection=!1,this._nextSendSctpStreamId=0,this._transportReady=!1}get name(){return"Chrome111"}close(){if(Lc.debug("close()"),!this._closed){if(this._closed=!0,this._pc)try{this._pc.close()}catch(e){}this.emit("@close")}}async getNativeRtpCapabilities(){Lc.debug("getNativeRtpCapabilities()");const e=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"unified-plan"});try{e.addTransceiver("audio"),e.addTransceiver("video");const t=await e.createOffer();try{e.close()}catch(e){}const r=Rc.parse(t.sdp),i=Oc.extractRtpCapabilities({sdpObject:r});return Dc.addNackSuppportForOpus(i),i}catch(t){try{e.close()}catch(e){}throw t}}async getNativeSctpCapabilities(){return Lc.debug("getNativeSctpCapabilities()"),{numStreams:Ac}}run({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,extendedRtpCapabilities:d}){this.assertNotClosed(),Lc.debug("run()"),this._direction=e,this._remoteSdp=new Mc.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n}),this._sendingRtpParametersByKind={audio:Pc.getSendingRtpParameters("audio",d),video:Pc.getSendingRtpParameters("video",d)},this._sendingRemoteRtpParametersByKind={audio:Pc.getSendingRemoteRtpParameters("audio",d),video:Pc.getSendingRemoteRtpParameters("video",d)},i.role&&"auto"!==i.role&&(this._forcedLocalDtlsRole="server"===i.role?"client":"server"),this._pc=new RTCPeerConnection({iceServers:s??[],iceTransportPolicy:o??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"unified-plan",...a},c),this._pc.addEventListener("icegatheringstatechange",(()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)})),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",(()=>{this.emit("@connectionstatechange",this._pc.connectionState)})):(Lc.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",(()=>{switch(this._pc.iceConnectionState){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected");break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed")}})))}async updateIceServers(e){this.assertNotClosed(),Lc.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(this.assertNotClosed(),Lc.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});Lc.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};Lc.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};Lc.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();Lc.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",t),await this._pc.setLocalDescription(t)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:e,encodings:t,codecOptions:r,codec:i,onRtpSender:n}){if(this.assertNotClosed(),this.assertSendDirection(),Lc.debug("send() [kind:%s, track.id:%s]",e.kind,e.id),t&&t.length>1){let e=1;for(const r of t){const t=r.scalabilityMode?(0,jc.parse)(r.scalabilityMode).temporalLayers:3;t>e&&(e=t)}t.forEach(((t,r)=>{t.rid=`r${r}`,t.scalabilityMode=`L1T${e}`}))}const s=Tc.clone(this._sendingRtpParametersByKind[e.kind]);s.codecs=Pc.reduceCodecs(s.codecs,i);const o=Tc.clone(this._sendingRemoteRtpParametersByKind[e.kind]);o.codecs=Pc.reduceCodecs(o.codecs,i);const a=this._remoteSdp.getNextMediaSectionIdx(),c=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream],sendEncodings:t});n&&n(c.sender);const d=await this._pc.createOffer();let l=Rc.parse(d.sdp);this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:l}),Lc.debug("send() | calling pc.setLocalDescription() [offer:%o]",d),await this._pc.setLocalDescription(d);const u=c.mid;s.mid=u,l=Rc.parse(this._pc.localDescription.sdp);const p=l.media[a.idx];if(s.rtcp.cname=Oc.getCname({offerMediaObject:p}),t)if(1===t.length){const e=Ec.getRtpEncodings({offerMediaObject:p});Object.assign(e[0],t[0]),s.encodings=e}else s.encodings=t;else s.encodings=Ec.getRtpEncodings({offerMediaObject:p});this._remoteSdp.send({offerMediaObject:p,reuseMid:a.reuseMid,offerRtpParameters:s,answerRtpParameters:o,codecOptions:r,extmapAllowMixed:!0});const h={type:"answer",sdp:this._remoteSdp.getSdp()};return Lc.debug("send() | calling pc.setRemoteDescription() [answer:%o]",h),await this._pc.setRemoteDescription(h),this._mapMidTransceiver.set(u,c),{localId:u,rtpParameters:s,rtpSender:c.sender}}async stopSending(e){if(this.assertSendDirection(),Lc.debug("stopSending() [localId:%s]",e),this._closed)return;const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.sender.replaceTrack(null),this._pc.removeTrack(t.sender);if(this._remoteSdp.closeMediaSection(t.mid))try{t.stop()}catch(e){}const r=await this._pc.createOffer();Lc.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const i={type:"answer",sdp:this._remoteSdp.getSdp()};Lc.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),Lc.debug("pauseSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="inactive",this._remoteSdp.pauseMediaSection(e);const r=await this._pc.createOffer();Lc.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const i={type:"answer",sdp:this._remoteSdp.getSdp()};Lc.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),Lc.debug("resumeSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(this._remoteSdp.resumeSendingMediaSection(e),!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="sendonly";const r=await this._pc.createOffer();Lc.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const i={type:"answer",sdp:this._remoteSdp.getSdp()};Lc.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?Lc.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):Lc.debug("replaceTrack() [localId:%s, no track]",e);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");await r.sender.replaceTrack(t)}async setMaxSpatialLayer(e,t){this.assertNotClosed(),this.assertSendDirection(),Lc.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const i=r.sender.getParameters();i.encodings.forEach(((e,r)=>{e.active=r<=t})),await r.sender.setParameters(i),this._remoteSdp.muxMediaSectionSimulcast(e,i.encodings);const n=await this._pc.createOffer();Lc.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);const s={type:"answer",sdp:this._remoteSdp.getSdp()};Lc.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),Lc.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const i=r.sender.getParameters();i.encodings.forEach(((e,r)=>{i.encodings[r]={...e,...t}})),await r.sender.setParameters(i),this._remoteSdp.muxMediaSectionSimulcast(e,i.encodings);const n=await this._pc.createOffer();Lc.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);const s={type:"answer",sdp:this._remoteSdp.getSdp()};Lc.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async getSenderStats(e){this.assertNotClosed(),this.assertSendDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.sender.getStats()}async sendDataChannel({ordered:e,maxPacketLifeTime:t,maxRetransmits:r,label:i,protocol:n}){this.assertNotClosed(),this.assertSendDirection();const s={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmits:r,protocol:n};Lc.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(i,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%Ac.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=Rc.parse(e.sdp),r=t.media.find((e=>"application"===e.type));this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:t}),Lc.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:r});const i={type:"answer",sdp:this._remoteSdp.getSdp()};Lc.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._hasDataChannelMediaSection=!0}return{dataChannel:o,sctpStreamParameters:{streamId:s.id,ordered:s.ordered,maxPacketLifeTime:s.maxPacketLifeTime,maxRetransmits:s.maxRetransmits}}}async receive(e){this.assertNotClosed(),this.assertRecvDirection();const t=[],r=new Map;for(const t of e){const{trackId:e,kind:i,rtpParameters:n,streamId:s}=t;Lc.debug("receive() [trackId:%s, kind:%s]",e,i);const o=n.mid??String(this._mapMidTransceiver.size);r.set(e,o),this._remoteSdp.receive({mid:o,kind:i,offerRtpParameters:n,streamId:s??n.rtcp.cname,trackId:e})}const i={type:"offer",sdp:this._remoteSdp.getSdp()};Lc.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",i),await this._pc.setRemoteDescription(i);for(const t of e){const{trackId:e,onRtpReceiver:i}=t;if(i){const t=r.get(e),n=this._pc.getTransceivers().find((e=>e.mid===t));if(!n)throw new Error("transceiver not found");i(n.receiver)}}let n=await this._pc.createAnswer();const s=Rc.parse(n.sdp);for(const t of e){const{trackId:e,rtpParameters:i}=t,n=r.get(e),o=s.media.find((e=>String(e.mid)===n));Oc.applyCodecParameters({offerRtpParameters:i,answerMediaObject:o})}n={type:"answer",sdp:Rc.write(s)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:s}),Lc.debug("receive() | calling pc.setLocalDescription() [answer:%o]",n),await this._pc.setLocalDescription(n);for(const i of e){const{trackId:e}=i,n=r.get(e),s=this._pc.getTransceivers().find((e=>e.mid===n));if(!s)throw new Error("new RTCRtpTransceiver not found");this._mapMidTransceiver.set(n,s),t.push({localId:n,track:s.receiver.track,rtpReceiver:s.receiver})}return t}async stopReceiving(e){if(this.assertRecvDirection(),this._closed)return;for(const t of e){Lc.debug("stopReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(e.mid)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};Lc.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Lc.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r);for(const t of e)this._mapMidTransceiver.delete(t)}async pauseReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(const t of e){Lc.debug("pauseReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="inactive",this._remoteSdp.pauseMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};Lc.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Lc.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async resumeReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(const t of e){Lc.debug("resumeReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};Lc.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Lc.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async getReceiverStats(e){this.assertNotClosed(),this.assertRecvDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.receiver.getStats()}async receiveDataChannel({sctpStreamParameters:e,label:t,protocol:r}){this.assertNotClosed(),this.assertRecvDirection();const{streamId:i,ordered:n,maxPacketLifeTime:s,maxRetransmits:o}=e,a={negotiated:!0,id:i,ordered:n,maxPacketLifeTime:s,maxRetransmits:o,protocol:r};Lc.debug("receiveDataChannel() [options:%o]",a);const c=this._pc.createDataChannel(t,a);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();const e={type:"offer",sdp:this._remoteSdp.getSdp()};Lc.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=Rc.parse(t.sdp);await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:e})}Lc.debug("receiveDataChannel() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setLocalDescription(t),this._hasDataChannelMediaSection=!0}return{dataChannel:c}}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=Rc.parse(this._pc.localDescription.sdp));const r=Oc.extractDtlsParameters({sdpObject:t});r.role=e,this._remoteSdp.updateDtlsRole("client"===e?"server":"client"),await new Promise(((e,t)=>{this.safeEmit("@connect",{dtlsParameters:r},e,t)})),this._transportReady=!0}assertNotClosed(){if(this._closed)throw new Ic.InvalidStateError("method called in a closed handler")}assertSendDirection(){if("send"!==this._direction)throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if("recv"!==this._direction)throw new Error('method can just be called for handlers with "recv" direction')}}ka.Chrome111=Nc;var Bc={},Fc=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),zc=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Vc=a&&a.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(null!=t)for(var i=e(t),n=0;n<i.length;n++)"default"!==i[n]&&Fc(r,t,i[n]);return zc(r,t),r}}();Object.defineProperty(Bc,"__esModule",{value:!0}),Bc.Chrome74=void 0;const Uc=Vc(Ta),$c=ss,Gc=Vc(Ls),qc=Vc(Fs),Hc=Vc(za),Wc=Vc(Ja),Kc=Vc(Xa),Jc=Is,Xc=Za,Qc=rc,Zc=bc,Yc=new $c.Logger("Chrome74"),ed={OS:1024,MIS:1024};class td extends Xc.HandlerInterface{static createFactory(){return()=>new td}constructor(){super(),this._closed=!1,this._mapMidTransceiver=new Map,this._sendStream=new MediaStream,this._hasDataChannelMediaSection=!1,this._nextSendSctpStreamId=0,this._transportReady=!1}get name(){return"Chrome74"}close(){if(Yc.debug("close()"),!this._closed){if(this._closed=!0,this._pc)try{this._pc.close()}catch(e){}this.emit("@close")}}async getNativeRtpCapabilities(){Yc.debug("getNativeRtpCapabilities()");const e=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"unified-plan"});try{e.addTransceiver("audio"),e.addTransceiver("video");const t=await e.createOffer();try{e.close()}catch(e){}const r=Uc.parse(t.sdp),i=Hc.extractRtpCapabilities({sdpObject:r});return Kc.addNackSuppportForOpus(i),i}catch(t){try{e.close()}catch(e){}throw t}}async getNativeSctpCapabilities(){return Yc.debug("getNativeSctpCapabilities()"),{numStreams:ed}}run({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,extendedRtpCapabilities:d}){Yc.debug("run()"),this._direction=e,this._remoteSdp=new Qc.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n}),this._sendingRtpParametersByKind={audio:qc.getSendingRtpParameters("audio",d),video:qc.getSendingRtpParameters("video",d)},this._sendingRemoteRtpParametersByKind={audio:qc.getSendingRemoteRtpParameters("audio",d),video:qc.getSendingRemoteRtpParameters("video",d)},i.role&&"auto"!==i.role&&(this._forcedLocalDtlsRole="server"===i.role?"client":"server"),this._pc=new RTCPeerConnection({iceServers:s??[],iceTransportPolicy:o??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"unified-plan",...a},c),this._pc.addEventListener("icegatheringstatechange",(()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)})),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",(()=>{this.emit("@connectionstatechange",this._pc.connectionState)})):(Yc.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",(()=>{switch(this._pc.iceConnectionState){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected");break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed")}})))}async updateIceServers(e){this.assertNotClosed(),Yc.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(this.assertNotClosed(),Yc.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});Yc.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};Yc.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};Yc.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();Yc.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",t),await this._pc.setLocalDescription(t)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:e,encodings:t,codecOptions:r,codec:i}){this.assertNotClosed(),this.assertSendDirection(),Yc.debug("send() [kind:%s, track.id:%s]",e.kind,e.id),t&&t.length>1&&t.forEach(((e,t)=>{e.rid=`r${t}`}));const n=Gc.clone(this._sendingRtpParametersByKind[e.kind]);n.codecs=qc.reduceCodecs(n.codecs,i);const s=Gc.clone(this._sendingRemoteRtpParametersByKind[e.kind]);s.codecs=qc.reduceCodecs(s.codecs,i);const o=this._remoteSdp.getNextMediaSectionIdx(),a=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream],sendEncodings:t});let c,d=await this._pc.createOffer(),l=Uc.parse(d.sdp);this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:l});let u=!1;const p=(0,Zc.parse)((t??[{}])[0].scalabilityMode);t&&1===t.length&&p.spatialLayers>1&&"video/vp9"===n.codecs[0].mimeType.toLowerCase()&&(Yc.debug("send() | enabling legacy simulcast for VP9 SVC"),u=!0,l=Uc.parse(d.sdp),c=l.media[o.idx],Wc.addLegacySimulcast({offerMediaObject:c,numStreams:p.spatialLayers}),d={type:"offer",sdp:Uc.write(l)}),Yc.debug("send() | calling pc.setLocalDescription() [offer:%o]",d),await this._pc.setLocalDescription(d);const h=a.mid;if(n.mid=h,l=Uc.parse(this._pc.localDescription.sdp),c=l.media[o.idx],n.rtcp.cname=Hc.getCname({offerMediaObject:c}),t)if(1===t.length){let e=Wc.getRtpEncodings({offerMediaObject:c});Object.assign(e[0],t[0]),u&&(e=[e[0]]),n.encodings=e}else n.encodings=t;else n.encodings=Wc.getRtpEncodings({offerMediaObject:c});if(n.encodings.length>1&&("video/vp8"===n.codecs[0].mimeType.toLowerCase()||"video/h264"===n.codecs[0].mimeType.toLowerCase()))for(const e of n.encodings)e.scalabilityMode?e.scalabilityMode=`L1T${p.temporalLayers}`:e.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:c,reuseMid:o.reuseMid,offerRtpParameters:n,answerRtpParameters:s,codecOptions:r,extmapAllowMixed:!0});const f={type:"answer",sdp:this._remoteSdp.getSdp()};return Yc.debug("send() | calling pc.setRemoteDescription() [answer:%o]",f),await this._pc.setRemoteDescription(f),this._mapMidTransceiver.set(h,a),{localId:h,rtpParameters:n,rtpSender:a.sender}}async stopSending(e){if(this.assertSendDirection(),Yc.debug("stopSending() [localId:%s]",e),this._closed)return;const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.sender.replaceTrack(null),this._pc.removeTrack(t.sender);if(this._remoteSdp.closeMediaSection(t.mid))try{t.stop()}catch(e){}const r=await this._pc.createOffer();Yc.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const i={type:"answer",sdp:this._remoteSdp.getSdp()};Yc.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),Yc.debug("pauseSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="inactive",this._remoteSdp.pauseMediaSection(e);const r=await this._pc.createOffer();Yc.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const i={type:"answer",sdp:this._remoteSdp.getSdp()};Yc.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),Yc.debug("resumeSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(this._remoteSdp.resumeSendingMediaSection(e),!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="sendonly";const r=await this._pc.createOffer();Yc.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const i={type:"answer",sdp:this._remoteSdp.getSdp()};Yc.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?Yc.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):Yc.debug("replaceTrack() [localId:%s, no track]",e);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");await r.sender.replaceTrack(t)}async setMaxSpatialLayer(e,t){this.assertNotClosed(),this.assertSendDirection(),Yc.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const i=r.sender.getParameters();i.encodings.forEach(((e,r)=>{e.active=r<=t})),await r.sender.setParameters(i),this._remoteSdp.muxMediaSectionSimulcast(e,i.encodings);const n=await this._pc.createOffer();Yc.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);const s={type:"answer",sdp:this._remoteSdp.getSdp()};Yc.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),Yc.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const i=r.sender.getParameters();i.encodings.forEach(((e,r)=>{i.encodings[r]={...e,...t}})),await r.sender.setParameters(i),this._remoteSdp.muxMediaSectionSimulcast(e,i.encodings);const n=await this._pc.createOffer();Yc.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);const s={type:"answer",sdp:this._remoteSdp.getSdp()};Yc.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async getSenderStats(e){this.assertNotClosed(),this.assertSendDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.sender.getStats()}async sendDataChannel({ordered:e,maxPacketLifeTime:t,maxRetransmits:r,label:i,protocol:n}){this.assertNotClosed(),this.assertSendDirection();const s={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmits:r,protocol:n};Yc.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(i,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%ed.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=Uc.parse(e.sdp),r=t.media.find((e=>"application"===e.type));this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:t}),Yc.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:r});const i={type:"answer",sdp:this._remoteSdp.getSdp()};Yc.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._hasDataChannelMediaSection=!0}return{dataChannel:o,sctpStreamParameters:{streamId:s.id,ordered:s.ordered,maxPacketLifeTime:s.maxPacketLifeTime,maxRetransmits:s.maxRetransmits}}}async receive(e){this.assertNotClosed(),this.assertRecvDirection();const t=[],r=new Map;for(const t of e){const{trackId:e,kind:i,rtpParameters:n,streamId:s}=t;Yc.debug("receive() [trackId:%s, kind:%s]",e,i);const o=n.mid??String(this._mapMidTransceiver.size);r.set(e,o),this._remoteSdp.receive({mid:o,kind:i,offerRtpParameters:n,streamId:s??n.rtcp.cname,trackId:e})}const i={type:"offer",sdp:this._remoteSdp.getSdp()};Yc.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",i),await this._pc.setRemoteDescription(i);let n=await this._pc.createAnswer();const s=Uc.parse(n.sdp);for(const t of e){const{trackId:e,rtpParameters:i}=t,n=r.get(e),o=s.media.find((e=>String(e.mid)===n));Hc.applyCodecParameters({offerRtpParameters:i,answerMediaObject:o})}n={type:"answer",sdp:Uc.write(s)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:s}),Yc.debug("receive() | calling pc.setLocalDescription() [answer:%o]",n),await this._pc.setLocalDescription(n);for(const i of e){const{trackId:e}=i,n=r.get(e),s=this._pc.getTransceivers().find((e=>e.mid===n));if(!s)throw new Error("new RTCRtpTransceiver not found");this._mapMidTransceiver.set(n,s),t.push({localId:n,track:s.receiver.track,rtpReceiver:s.receiver})}return t}async stopReceiving(e){if(this.assertRecvDirection(),this._closed)return;for(const t of e){Yc.debug("stopReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(e.mid)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};Yc.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Yc.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r);for(const t of e)this._mapMidTransceiver.delete(t)}async pauseReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(const t of e){Yc.debug("pauseReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="inactive",this._remoteSdp.pauseMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};Yc.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Yc.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async resumeReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(const t of e){Yc.debug("resumeReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};Yc.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Yc.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async getReceiverStats(e){this.assertNotClosed(),this.assertRecvDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.receiver.getStats()}async receiveDataChannel({sctpStreamParameters:e,label:t,protocol:r}){this.assertNotClosed(),this.assertRecvDirection();const{streamId:i,ordered:n,maxPacketLifeTime:s,maxRetransmits:o}=e,a={negotiated:!0,id:i,ordered:n,maxPacketLifeTime:s,maxRetransmits:o,protocol:r};Yc.debug("receiveDataChannel() [options:%o]",a);const c=this._pc.createDataChannel(t,a);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();const e={type:"offer",sdp:this._remoteSdp.getSdp()};Yc.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=Uc.parse(t.sdp);await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:e})}Yc.debug("receiveDataChannel() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setLocalDescription(t),this._hasDataChannelMediaSection=!0}return{dataChannel:c}}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=Uc.parse(this._pc.localDescription.sdp));const r=Hc.extractDtlsParameters({sdpObject:t});r.role=e,this._remoteSdp.updateDtlsRole("client"===e?"server":"client"),await new Promise(((e,t)=>{this.safeEmit("@connect",{dtlsParameters:r},e,t)})),this._transportReady=!0}assertNotClosed(){if(this._closed)throw new Jc.InvalidStateError("method called in a closed handler")}assertSendDirection(){if("send"!==this._direction)throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if("recv"!==this._direction)throw new Error('method can just be called for handlers with "recv" direction')}}Bc.Chrome74=td;var rd={},id=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),nd=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),sd=a&&a.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(null!=t)for(var i=e(t),n=0;n<i.length;n++)"default"!==i[n]&&id(r,t,i[n]);return nd(r,t),r}}();Object.defineProperty(rd,"__esModule",{value:!0}),rd.Chrome70=void 0;const od=sd(Ta),ad=ss,cd=sd(Ls),dd=sd(Fs),ld=sd(za),ud=sd(Ja),pd=Za,hd=rc,fd=bc,md=new ad.Logger("Chrome70"),gd={OS:1024,MIS:1024};class vd extends pd.HandlerInterface{static createFactory(){return()=>new vd}constructor(){super(),this._mapMidTransceiver=new Map,this._sendStream=new MediaStream,this._hasDataChannelMediaSection=!1,this._nextSendSctpStreamId=0,this._transportReady=!1}get name(){return"Chrome70"}close(){if(md.debug("close()"),this._pc)try{this._pc.close()}catch(e){}this.emit("@close")}async getNativeRtpCapabilities(){md.debug("getNativeRtpCapabilities()");const e=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"unified-plan"});try{e.addTransceiver("audio"),e.addTransceiver("video");const t=await e.createOffer();try{e.close()}catch(e){}const r=od.parse(t.sdp);return ld.extractRtpCapabilities({sdpObject:r})}catch(t){try{e.close()}catch(e){}throw t}}async getNativeSctpCapabilities(){return md.debug("getNativeSctpCapabilities()"),{numStreams:gd}}run({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,extendedRtpCapabilities:d}){md.debug("run()"),this._direction=e,this._remoteSdp=new hd.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n}),this._sendingRtpParametersByKind={audio:dd.getSendingRtpParameters("audio",d),video:dd.getSendingRtpParameters("video",d)},this._sendingRemoteRtpParametersByKind={audio:dd.getSendingRemoteRtpParameters("audio",d),video:dd.getSendingRemoteRtpParameters("video",d)},i.role&&"auto"!==i.role&&(this._forcedLocalDtlsRole="server"===i.role?"client":"server"),this._pc=new RTCPeerConnection({iceServers:s??[],iceTransportPolicy:o??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"unified-plan",...a},c),this._pc.addEventListener("icegatheringstatechange",(()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)})),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",(()=>{this.emit("@connectionstatechange",this._pc.connectionState)})):this._pc.addEventListener("iceconnectionstatechange",(()=>{switch(md.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.iceConnectionState){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected");break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed")}}))}async updateIceServers(e){md.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(md.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});md.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};md.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};md.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();md.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",t),await this._pc.setLocalDescription(t)}}async getTransportStats(){return this._pc.getStats()}async send({track:e,encodings:t,codecOptions:r,codec:i}){this.assertSendDirection(),md.debug("send() [kind:%s, track.id:%s]",e.kind,e.id);const n=cd.clone(this._sendingRtpParametersByKind[e.kind]);n.codecs=dd.reduceCodecs(n.codecs,i);const s=cd.clone(this._sendingRemoteRtpParametersByKind[e.kind]);s.codecs=dd.reduceCodecs(s.codecs,i);const o=this._remoteSdp.getNextMediaSectionIdx(),a=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream]});let c,d=await this._pc.createOffer(),l=od.parse(d.sdp);this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:l}),t&&t.length>1&&(md.debug("send() | enabling legacy simulcast"),l=od.parse(d.sdp),c=l.media[o.idx],ud.addLegacySimulcast({offerMediaObject:c,numStreams:t.length}),d={type:"offer",sdp:od.write(l)});let u=!1;const p=(0,fd.parse)((t??[{}])[0].scalabilityMode);if(t&&1===t.length&&p.spatialLayers>1&&"video/vp9"===n.codecs[0].mimeType.toLowerCase()&&(md.debug("send() | enabling legacy simulcast for VP9 SVC"),u=!0,l=od.parse(d.sdp),c=l.media[o.idx],ud.addLegacySimulcast({offerMediaObject:c,numStreams:p.spatialLayers}),d={type:"offer",sdp:od.write(l)}),md.debug("send() | calling pc.setLocalDescription() [offer:%o]",d),await this._pc.setLocalDescription(d),t){md.debug("send() | applying given encodings");const e=a.sender.getParameters();for(let r=0;r<(e.encodings??[]).length;++r){const i=e.encodings[r],n=t[r];if(!n)break;e.encodings[r]=Object.assign(i,n)}await a.sender.setParameters(e)}const h=a.mid;if(n.mid=h,l=od.parse(this._pc.localDescription.sdp),c=l.media[o.idx],n.rtcp.cname=ld.getCname({offerMediaObject:c}),n.encodings=ud.getRtpEncodings({offerMediaObject:c}),t)for(let e=0;e<n.encodings.length;++e)t[e]&&Object.assign(n.encodings[e],t[e]);if(u&&(n.encodings=[n.encodings[0]]),n.encodings.length>1&&("video/vp8"===n.codecs[0].mimeType.toLowerCase()||"video/h264"===n.codecs[0].mimeType.toLowerCase()))for(const e of n.encodings)e.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:c,reuseMid:o.reuseMid,offerRtpParameters:n,answerRtpParameters:s,codecOptions:r});const f={type:"answer",sdp:this._remoteSdp.getSdp()};return md.debug("send() | calling pc.setRemoteDescription() [answer:%o]",f),await this._pc.setRemoteDescription(f),this._mapMidTransceiver.set(h,a),{localId:h,rtpParameters:n,rtpSender:a.sender}}async stopSending(e){this.assertSendDirection(),md.debug("stopSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.sender.replaceTrack(null),this._pc.removeTrack(t.sender);if(this._remoteSdp.closeMediaSection(t.mid))try{t.stop()}catch(e){}const r=await this._pc.createOffer();md.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const i={type:"answer",sdp:this._remoteSdp.getSdp()};md.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._mapMidTransceiver.delete(e)}async pauseSending(e){}async resumeSending(e){}async replaceTrack(e,t){this.assertSendDirection(),t?md.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):md.debug("replaceTrack() [localId:%s, no track]",e);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");await r.sender.replaceTrack(t)}async setMaxSpatialLayer(e,t){this.assertSendDirection(),md.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const i=r.sender.getParameters();i.encodings.forEach(((e,r)=>{e.active=r<=t})),await r.sender.setParameters(i),this._remoteSdp.muxMediaSectionSimulcast(e,i.encodings);const n=await this._pc.createOffer();md.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);const s={type:"answer",sdp:this._remoteSdp.getSdp()};md.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async setRtpEncodingParameters(e,t){this.assertSendDirection(),md.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const i=r.sender.getParameters();i.encodings.forEach(((e,r)=>{i.encodings[r]={...e,...t}})),await r.sender.setParameters(i),this._remoteSdp.muxMediaSectionSimulcast(e,i.encodings);const n=await this._pc.createOffer();md.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);const s={type:"answer",sdp:this._remoteSdp.getSdp()};md.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async getSenderStats(e){this.assertSendDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.sender.getStats()}async sendDataChannel({ordered:e,maxPacketLifeTime:t,maxRetransmits:r,label:i,protocol:n}){this.assertSendDirection();const s={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmitTime:t,maxRetransmits:r,protocol:n};md.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(i,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%gd.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=od.parse(e.sdp),r=t.media.find((e=>"application"===e.type));this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:t}),md.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:r});const i={type:"answer",sdp:this._remoteSdp.getSdp()};md.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._hasDataChannelMediaSection=!0}return{dataChannel:o,sctpStreamParameters:{streamId:s.id,ordered:s.ordered,maxPacketLifeTime:s.maxPacketLifeTime,maxRetransmits:s.maxRetransmits}}}async receive(e){this.assertRecvDirection();const t=[],r=new Map;for(const t of e){const{trackId:e,kind:i,rtpParameters:n,streamId:s}=t;md.debug("receive() [trackId:%s, kind:%s]",e,i);const o=n.mid??String(this._mapMidTransceiver.size);r.set(e,o),this._remoteSdp.receive({mid:o,kind:i,offerRtpParameters:n,streamId:s??n.rtcp.cname,trackId:e})}const i={type:"offer",sdp:this._remoteSdp.getSdp()};md.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",i),await this._pc.setRemoteDescription(i);let n=await this._pc.createAnswer();const s=od.parse(n.sdp);for(const t of e){const{trackId:e,rtpParameters:i}=t,n=r.get(e),o=s.media.find((e=>String(e.mid)===n));ld.applyCodecParameters({offerRtpParameters:i,answerMediaObject:o})}n={type:"answer",sdp:od.write(s)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:s}),md.debug("receive() | calling pc.setLocalDescription() [answer:%o]",n),await this._pc.setLocalDescription(n);for(const i of e){const{trackId:e}=i,n=r.get(e),s=this._pc.getTransceivers().find((e=>e.mid===n));if(!s)throw new Error("new RTCRtpTransceiver not found");this._mapMidTransceiver.set(n,s),t.push({localId:n,track:s.receiver.track,rtpReceiver:s.receiver})}return t}async stopReceiving(e){this.assertRecvDirection();for(const t of e){md.debug("stopReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(e.mid)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};md.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();md.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r);for(const t of e)this._mapMidTransceiver.delete(t)}async pauseReceiving(e){}async resumeReceiving(e){}async getReceiverStats(e){this.assertRecvDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.receiver.getStats()}async receiveDataChannel({sctpStreamParameters:e,label:t,protocol:r}){this.assertRecvDirection();const{streamId:i,ordered:n,maxPacketLifeTime:s,maxRetransmits:o}=e,a={negotiated:!0,id:i,ordered:n,maxPacketLifeTime:s,maxRetransmitTime:s,maxRetransmits:o,protocol:r};md.debug("receiveDataChannel() [options:%o]",a);const c=this._pc.createDataChannel(t,a);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();const e={type:"offer",sdp:this._remoteSdp.getSdp()};md.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=od.parse(t.sdp);await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:e})}md.debug("receiveDataChannel() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setLocalDescription(t),this._hasDataChannelMediaSection=!0}return{dataChannel:c}}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=od.parse(this._pc.localDescription.sdp));const r=ld.extractDtlsParameters({sdpObject:t});r.role=e,this._remoteSdp.updateDtlsRole("client"===e?"server":"client"),await new Promise(((e,t)=>{this.safeEmit("@connect",{dtlsParameters:r},e,t)})),this._transportReady=!0}assertSendDirection(){if("send"!==this._direction)throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if("recv"!==this._direction)throw new Error('method can just be called for handlers with "recv" direction')}}rd.Chrome70=vd;var bd={},yd={};Object.defineProperty(yd,"__esModule",{value:!0}),yd.getRtpEncodings=function({offerMediaObject:e,track:t}){const r=new Set;for(const i of e.ssrcs||[]){if("msid"!==i.attribute)continue;if(i.value.split(" ")[1]===t.id){const e=i.id;r.add(e)}}if(0===r.size)throw new Error(`a=ssrc line with msid information not found [track.id:${t.id}]`);const i=new Map;for(const t of e.ssrcGroups||[]){if("FID"!==t.semantics)continue;let[e,n]=t.ssrcs.split(/\s+/);e=Number(e),n=Number(n),r.has(e)&&(r.delete(e),r.delete(n),i.set(e,n))}for(const e of r)i.set(e,null);const n=[];for(const[e,t]of i){const r={ssrc:e};t&&(r.rtx={ssrc:t}),n.push(r)}return n},yd.addLegacySimulcast=function({offerMediaObject:e,track:t,numStreams:r}){if(r<=1)throw new TypeError("numStreams must be greater than 1");let i,n,s;if(!(e.ssrcs||[]).find((e=>{if("msid"!==e.attribute)return!1;return e.value.split(" ")[1]===t.id&&(i=e.id,s=e.value.split(" ")[0],!0)})))throw new Error(`a=ssrc line with msid information not found [track.id:${t.id}]`);(e.ssrcGroups||[]).some((e=>{if("FID"!==e.semantics)return!1;const t=e.ssrcs.split(/\s+/);return Number(t[0])===i&&(n=Number(t[1]),!0)}));const o=e.ssrcs.find((e=>"cname"===e.attribute&&e.id===i));if(!o)throw new Error(`a=ssrc line with cname information not found [track.id:${t.id}]`);const a=o.value,c=[],d=[];for(let e=0;e<r;++e)c.push(i+e),n&&d.push(n+e);e.ssrcGroups=e.ssrcGroups||[],e.ssrcs=e.ssrcs||[],e.ssrcGroups.push({semantics:"SIM",ssrcs:c.join(" ")});for(const r of c)e.ssrcs.push({id:r,attribute:"cname",value:a}),e.ssrcs.push({id:r,attribute:"msid",value:`${s} ${t.id}`});for(let r=0;r<d.length;++r){const i=c[r],n=d[r];e.ssrcs.push({id:n,attribute:"cname",value:a}),e.ssrcs.push({id:n,attribute:"msid",value:`${s} ${t.id}`}),e.ssrcGroups.push({semantics:"FID",ssrcs:`${i} ${n}`})}};var wd=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),_d=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Sd=a&&a.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(null!=t)for(var i=e(t),n=0;n<i.length;n++)"default"!==i[n]&&wd(r,t,i[n]);return _d(r,t),r}}();Object.defineProperty(bd,"__esModule",{value:!0}),bd.Chrome67=void 0;const Cd=Sd(Ta),Rd=ss,kd=Sd(Ls),Td=Sd(Fs),Pd=Sd(za),Od=Sd(yd),Ed=Za,Dd=rc,Id=new Rd.Logger("Chrome67"),xd={OS:1024,MIS:1024};class Md extends Ed.HandlerInterface{static createFactory(){return()=>new Md}constructor(){super(),this._sendStream=new MediaStream,this._mapSendLocalIdRtpSender=new Map,this._nextSendLocalId=0,this._mapRecvLocalIdInfo=new Map,this._hasDataChannelMediaSection=!1,this._nextSendSctpStreamId=0,this._transportReady=!1}get name(){return"Chrome67"}close(){if(Id.debug("close()"),this._pc)try{this._pc.close()}catch(e){}this.emit("@close")}async getNativeRtpCapabilities(){Id.debug("getNativeRtpCapabilities()");const e=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"plan-b"});try{const t=await e.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0});try{e.close()}catch(e){}const r=Cd.parse(t.sdp);return Pd.extractRtpCapabilities({sdpObject:r})}catch(t){try{e.close()}catch(e){}throw t}}async getNativeSctpCapabilities(){return Id.debug("getNativeSctpCapabilities()"),{numStreams:xd}}run({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,extendedRtpCapabilities:d}){Id.debug("run()"),this._direction=e,this._remoteSdp=new Dd.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n,planB:!0}),this._sendingRtpParametersByKind={audio:Td.getSendingRtpParameters("audio",d),video:Td.getSendingRtpParameters("video",d)},this._sendingRemoteRtpParametersByKind={audio:Td.getSendingRemoteRtpParameters("audio",d),video:Td.getSendingRemoteRtpParameters("video",d)},i.role&&"auto"!==i.role&&(this._forcedLocalDtlsRole="server"===i.role?"client":"server"),this._pc=new RTCPeerConnection({iceServers:s??[],iceTransportPolicy:o??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"plan-b",...a},c),this._pc.addEventListener("icegatheringstatechange",(()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)})),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",(()=>{this.emit("@connectionstatechange",this._pc.connectionState)})):this._pc.addEventListener("iceconnectionstatechange",(()=>{switch(Id.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.iceConnectionState){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected");break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed")}}))}async updateIceServers(e){Id.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(Id.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});Id.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};Id.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};Id.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();Id.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",t),await this._pc.setLocalDescription(t)}}async getTransportStats(){return this._pc.getStats()}async send({track:e,encodings:t,codecOptions:r,codec:i}){this.assertSendDirection(),Id.debug("send() [kind:%s, track.id:%s]",e.kind,e.id),i&&Id.warn("send() | codec selection is not available in %s handler",this.name),this._sendStream.addTrack(e),this._pc.addTrack(e,this._sendStream);let n,s=await this._pc.createOffer(),o=Cd.parse(s.sdp);const a=kd.clone(this._sendingRtpParametersByKind[e.kind]);a.codecs=Td.reduceCodecs(a.codecs);const c=kd.clone(this._sendingRemoteRtpParametersByKind[e.kind]);if(c.codecs=Td.reduceCodecs(c.codecs),this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:o}),"video"===e.kind&&t&&t.length>1&&(Id.debug("send() | enabling simulcast"),o=Cd.parse(s.sdp),n=o.media.find((e=>"video"===e.type)),Od.addLegacySimulcast({offerMediaObject:n,track:e,numStreams:t.length}),s={type:"offer",sdp:Cd.write(o)}),Id.debug("send() | calling pc.setLocalDescription() [offer:%o]",s),await this._pc.setLocalDescription(s),o=Cd.parse(this._pc.localDescription.sdp),n=o.media.find((t=>t.type===e.kind)),a.rtcp.cname=Pd.getCname({offerMediaObject:n}),a.encodings=Od.getRtpEncodings({offerMediaObject:n,track:e}),t)for(let e=0;e<a.encodings.length;++e)t[e]&&Object.assign(a.encodings[e],t[e]);if(a.encodings.length>1&&"video/vp8"===a.codecs[0].mimeType.toLowerCase())for(const e of a.encodings)e.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:n,offerRtpParameters:a,answerRtpParameters:c,codecOptions:r});const d={type:"answer",sdp:this._remoteSdp.getSdp()};Id.debug("send() | calling pc.setRemoteDescription() [answer:%o]",d),await this._pc.setRemoteDescription(d);const l=String(this._nextSendLocalId);this._nextSendLocalId++;const u=this._pc.getSenders().find((t=>t.track===e));return this._mapSendLocalIdRtpSender.set(l,u),{localId:l,rtpParameters:a,rtpSender:u}}async stopSending(e){this.assertSendDirection(),Id.debug("stopSending() [localId:%s]",e);const t=this._mapSendLocalIdRtpSender.get(e);if(!t)throw new Error("associated RTCRtpSender not found");this._pc.removeTrack(t),t.track&&this._sendStream.removeTrack(t.track),this._mapSendLocalIdRtpSender.delete(e);const r=await this._pc.createOffer();Id.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r);try{await this._pc.setLocalDescription(r)}catch(e){if(0===this._sendStream.getTracks().length)return void Id.warn("stopSending() | ignoring expected error due no sending tracks: %s",e.toString());throw e}if("stable"===this._pc.signalingState)return;const i={type:"answer",sdp:this._remoteSdp.getSdp()};Id.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i)}async pauseSending(e){}async resumeSending(e){}async replaceTrack(e,t){this.assertSendDirection(),t?Id.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):Id.debug("replaceTrack() [localId:%s, no track]",e);const r=this._mapSendLocalIdRtpSender.get(e);if(!r)throw new Error("associated RTCRtpSender not found");const i=r.track;await r.replaceTrack(t),i&&this._sendStream.removeTrack(i),t&&this._sendStream.addTrack(t)}async setMaxSpatialLayer(e,t){this.assertSendDirection(),Id.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);const r=this._mapSendLocalIdRtpSender.get(e);if(!r)throw new Error("associated RTCRtpSender not found");const i=r.getParameters();i.encodings.forEach(((e,r)=>{e.active=r<=t})),await r.setParameters(i)}async setRtpEncodingParameters(e,t){this.assertSendDirection(),Id.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);const r=this._mapSendLocalIdRtpSender.get(e);if(!r)throw new Error("associated RTCRtpSender not found");const i=r.getParameters();i.encodings.forEach(((e,r)=>{i.encodings[r]={...e,...t}})),await r.setParameters(i)}async getSenderStats(e){this.assertSendDirection();const t=this._mapSendLocalIdRtpSender.get(e);if(!t)throw new Error("associated RTCRtpSender not found");return t.getStats()}async sendDataChannel({ordered:e,maxPacketLifeTime:t,maxRetransmits:r,label:i,protocol:n}){this.assertSendDirection();const s={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmitTime:t,maxRetransmits:r,protocol:n};Id.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(i,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%xd.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=Cd.parse(e.sdp),r=t.media.find((e=>"application"===e.type));this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:t}),Id.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:r});const i={type:"answer",sdp:this._remoteSdp.getSdp()};Id.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._hasDataChannelMediaSection=!0}return{dataChannel:o,sctpStreamParameters:{streamId:s.id,ordered:s.ordered,maxPacketLifeTime:s.maxPacketLifeTime,maxRetransmits:s.maxRetransmits}}}async receive(e){this.assertRecvDirection();const t=[];for(const t of e){const{trackId:e,kind:r,rtpParameters:i,streamId:n}=t;Id.debug("receive() [trackId:%s, kind:%s]",e,r);const s=r;this._remoteSdp.receive({mid:s,kind:r,offerRtpParameters:i,streamId:n??i.rtcp.cname,trackId:e})}const r={type:"offer",sdp:this._remoteSdp.getSdp()};Id.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",r),await this._pc.setRemoteDescription(r);let i=await this._pc.createAnswer();const n=Cd.parse(i.sdp);for(const t of e){const{kind:e,rtpParameters:r}=t,i=e,s=n.media.find((e=>String(e.mid)===i));Pd.applyCodecParameters({offerRtpParameters:r,answerMediaObject:s})}i={type:"answer",sdp:Cd.write(n)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:n}),Id.debug("receive() | calling pc.setLocalDescription() [answer:%o]",i),await this._pc.setLocalDescription(i);for(const r of e){const{kind:e,trackId:i,rtpParameters:n}=r,s=i,o=e,a=this._pc.getReceivers().find((e=>e.track&&e.track.id===s));if(!a)throw new Error("new RTCRtpReceiver not");this._mapRecvLocalIdInfo.set(s,{mid:o,rtpParameters:n,rtpReceiver:a}),t.push({localId:s,track:a.track,rtpReceiver:a})}return t}async stopReceiving(e){this.assertRecvDirection();for(const t of e){Id.debug("stopReceiving() [localId:%s]",t);const{mid:e,rtpParameters:r}=this._mapRecvLocalIdInfo.get(t)??{};this._mapRecvLocalIdInfo.delete(t),this._remoteSdp.planBStopReceiving({mid:e,offerRtpParameters:r})}const t={type:"offer",sdp:this._remoteSdp.getSdp()};Id.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Id.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async pauseReceiving(e){}async resumeReceiving(e){}async getReceiverStats(e){this.assertRecvDirection();const{rtpReceiver:t}=this._mapRecvLocalIdInfo.get(e)??{};if(!t)throw new Error("associated RTCRtpReceiver not found");return t.getStats()}async receiveDataChannel({sctpStreamParameters:e,label:t,protocol:r}){this.assertRecvDirection();const{streamId:i,ordered:n,maxPacketLifeTime:s,maxRetransmits:o}=e,a={negotiated:!0,id:i,ordered:n,maxPacketLifeTime:s,maxRetransmitTime:s,maxRetransmits:o,protocol:r};Id.debug("receiveDataChannel() [options:%o]",a);const c=this._pc.createDataChannel(t,a);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation({oldDataChannelSpec:!0});const e={type:"offer",sdp:this._remoteSdp.getSdp()};Id.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=Cd.parse(t.sdp);await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:e})}Id.debug("receiveDataChannel() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setLocalDescription(t),this._hasDataChannelMediaSection=!0}return{dataChannel:c}}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=Cd.parse(this._pc.localDescription.sdp));const r=Pd.extractDtlsParameters({sdpObject:t});r.role=e,this._remoteSdp.updateDtlsRole("client"===e?"server":"client"),await new Promise(((e,t)=>{this.safeEmit("@connect",{dtlsParameters:r},e,t)})),this._transportReady=!0}assertSendDirection(){if("send"!==this._direction)throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if("recv"!==this._direction)throw new Error('method can just be called for handlers with "recv" direction')}}bd.Chrome67=Md;var jd={},Ld=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),Ad=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Nd=a&&a.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(null!=t)for(var i=e(t),n=0;n<i.length;n++)"default"!==i[n]&&Ld(r,t,i[n]);return Ad(r,t),r}}();Object.defineProperty(jd,"__esModule",{value:!0}),jd.Chrome55=void 0;const Bd=Nd(Ta),Fd=ss,zd=Is,Vd=Nd(Ls),Ud=Nd(Fs),$d=Nd(za),Gd=Nd(yd),qd=Za,Hd=rc,Wd=new Fd.Logger("Chrome55"),Kd={OS:1024,MIS:1024};class Jd extends qd.HandlerInterface{static createFactory(){return()=>new Jd}constructor(){super(),this._sendStream=new MediaStream,this._mapSendLocalIdTrack=new Map,this._nextSendLocalId=0,this._mapRecvLocalIdInfo=new Map,this._hasDataChannelMediaSection=!1,this._nextSendSctpStreamId=0,this._transportReady=!1}get name(){return"Chrome55"}close(){if(Wd.debug("close()"),this._pc)try{this._pc.close()}catch(e){}this.emit("@close")}async getNativeRtpCapabilities(){Wd.debug("getNativeRtpCapabilities()");const e=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"plan-b"});try{const t=await e.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0});try{e.close()}catch(e){}const r=Bd.parse(t.sdp);return $d.extractRtpCapabilities({sdpObject:r})}catch(t){try{e.close()}catch(e){}throw t}}async getNativeSctpCapabilities(){return Wd.debug("getNativeSctpCapabilities()"),{numStreams:Kd}}run({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,extendedRtpCapabilities:d}){Wd.debug("run()"),this._direction=e,this._remoteSdp=new Hd.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n,planB:!0}),this._sendingRtpParametersByKind={audio:Ud.getSendingRtpParameters("audio",d),video:Ud.getSendingRtpParameters("video",d)},this._sendingRemoteRtpParametersByKind={audio:Ud.getSendingRemoteRtpParameters("audio",d),video:Ud.getSendingRemoteRtpParameters("video",d)},i.role&&"auto"!==i.role&&(this._forcedLocalDtlsRole="server"===i.role?"client":"server"),this._pc=new RTCPeerConnection({iceServers:s??[],iceTransportPolicy:o??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"plan-b",...a},c),this._pc.addEventListener("icegatheringstatechange",(()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)})),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",(()=>{this.emit("@connectionstatechange",this._pc.connectionState)})):this._pc.addEventListener("iceconnectionstatechange",(()=>{switch(Wd.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.iceConnectionState){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected");break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed")}}))}async updateIceServers(e){Wd.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(Wd.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});Wd.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};Wd.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};Wd.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();Wd.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",t),await this._pc.setLocalDescription(t)}}async getTransportStats(){return this._pc.getStats()}async send({track:e,encodings:t,codecOptions:r,codec:i}){this.assertSendDirection(),Wd.debug("send() [kind:%s, track.id:%s]",e.kind,e.id),i&&Wd.warn("send() | codec selection is not available in %s handler",this.name),this._sendStream.addTrack(e),this._pc.addStream(this._sendStream);let n,s=await this._pc.createOffer(),o=Bd.parse(s.sdp);const a=Vd.clone(this._sendingRtpParametersByKind[e.kind]);a.codecs=Ud.reduceCodecs(a.codecs);const c=Vd.clone(this._sendingRemoteRtpParametersByKind[e.kind]);if(c.codecs=Ud.reduceCodecs(c.codecs),this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:o}),"video"===e.kind&&t&&t.length>1&&(Wd.debug("send() | enabling simulcast"),o=Bd.parse(s.sdp),n=o.media.find((e=>"video"===e.type)),Gd.addLegacySimulcast({offerMediaObject:n,track:e,numStreams:t.length}),s={type:"offer",sdp:Bd.write(o)}),Wd.debug("send() | calling pc.setLocalDescription() [offer:%o]",s),await this._pc.setLocalDescription(s),o=Bd.parse(this._pc.localDescription.sdp),n=o.media.find((t=>t.type===e.kind)),a.rtcp.cname=$d.getCname({offerMediaObject:n}),a.encodings=Gd.getRtpEncodings({offerMediaObject:n,track:e}),t)for(let e=0;e<a.encodings.length;++e)t[e]&&Object.assign(a.encodings[e],t[e]);if(a.encodings.length>1&&"video/vp8"===a.codecs[0].mimeType.toLowerCase())for(const e of a.encodings)e.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:n,offerRtpParameters:a,answerRtpParameters:c,codecOptions:r});const d={type:"answer",sdp:this._remoteSdp.getSdp()};Wd.debug("send() | calling pc.setRemoteDescription() [answer:%o]",d),await this._pc.setRemoteDescription(d);const l=String(this._nextSendLocalId);return this._nextSendLocalId++,this._mapSendLocalIdTrack.set(l,e),{localId:l,rtpParameters:a}}async stopSending(e){this.assertSendDirection(),Wd.debug("stopSending() [localId:%s]",e);const t=this._mapSendLocalIdTrack.get(e);if(!t)throw new Error("track not found");this._mapSendLocalIdTrack.delete(e),this._sendStream.removeTrack(t),this._pc.addStream(this._sendStream);const r=await this._pc.createOffer();Wd.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r);try{await this._pc.setLocalDescription(r)}catch(e){if(0===this._sendStream.getTracks().length)return void Wd.warn("stopSending() | ignoring expected error due no sending tracks: %s",e.toString());throw e}if("stable"===this._pc.signalingState)return;const i={type:"answer",sdp:this._remoteSdp.getSdp()};Wd.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i)}async pauseSending(e){}async resumeSending(e){}async replaceTrack(e,t){throw new zd.UnsupportedError("not implemented")}async setMaxSpatialLayer(e,t){throw new zd.UnsupportedError(" not implemented")}async setRtpEncodingParameters(e,t){throw new zd.UnsupportedError("not supported")}async getSenderStats(e){throw new zd.UnsupportedError("not implemented")}async sendDataChannel({ordered:e,maxPacketLifeTime:t,maxRetransmits:r,label:i,protocol:n}){this.assertSendDirection();const s={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmitTime:t,maxRetransmits:r,protocol:n};Wd.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(i,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%Kd.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=Bd.parse(e.sdp),r=t.media.find((e=>"application"===e.type));this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:t}),Wd.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:r});const i={type:"answer",sdp:this._remoteSdp.getSdp()};Wd.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._hasDataChannelMediaSection=!0}return{dataChannel:o,sctpStreamParameters:{streamId:s.id,ordered:s.ordered,maxPacketLifeTime:s.maxPacketLifeTime,maxRetransmits:s.maxRetransmits}}}async receive(e){this.assertRecvDirection();const t=[];for(const t of e){const{trackId:e,kind:r,rtpParameters:i,streamId:n}=t;Wd.debug("receive() [trackId:%s, kind:%s]",e,r);const s=r;this._remoteSdp.receive({mid:s,kind:r,offerRtpParameters:i,streamId:n??i.rtcp.cname,trackId:e})}const r={type:"offer",sdp:this._remoteSdp.getSdp()};Wd.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",r),await this._pc.setRemoteDescription(r);let i=await this._pc.createAnswer();const n=Bd.parse(i.sdp);for(const t of e){const{kind:e,rtpParameters:r}=t,i=e,s=n.media.find((e=>String(e.mid)===i));$d.applyCodecParameters({offerRtpParameters:r,answerMediaObject:s})}i={type:"answer",sdp:Bd.write(n)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:n}),Wd.debug("receive() | calling pc.setLocalDescription() [answer:%o]",i),await this._pc.setLocalDescription(i);for(const r of e){const{kind:e,trackId:i,rtpParameters:n}=r,s=e,o=i,a=r.streamId??n.rtcp.cname,c=this._pc.getRemoteStreams().find((e=>e.id===a)).getTrackById(o);if(!c)throw new Error("remote track not found");this._mapRecvLocalIdInfo.set(o,{mid:s,rtpParameters:n}),t.push({localId:o,track:c})}return t}async stopReceiving(e){this.assertRecvDirection();for(const t of e){Wd.debug("stopReceiving() [localId:%s]",t);const{mid:e,rtpParameters:r}=this._mapRecvLocalIdInfo.get(t)??{};this._mapRecvLocalIdInfo.delete(t),this._remoteSdp.planBStopReceiving({mid:e,offerRtpParameters:r})}const t={type:"offer",sdp:this._remoteSdp.getSdp()};Wd.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Wd.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async pauseReceiving(e){}async resumeReceiving(e){}async getReceiverStats(e){throw new zd.UnsupportedError("not implemented")}async receiveDataChannel({sctpStreamParameters:e,label:t,protocol:r}){this.assertRecvDirection();const{streamId:i,ordered:n,maxPacketLifeTime:s,maxRetransmits:o}=e,a={negotiated:!0,id:i,ordered:n,maxPacketLifeTime:s,maxRetransmitTime:s,maxRetransmits:o,protocol:r};Wd.debug("receiveDataChannel() [options:%o]",a);const c=this._pc.createDataChannel(t,a);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation({oldDataChannelSpec:!0});const e={type:"offer",sdp:this._remoteSdp.getSdp()};Wd.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=Bd.parse(t.sdp);await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:e})}Wd.debug("receiveDataChannel() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setLocalDescription(t),this._hasDataChannelMediaSection=!0}return{dataChannel:c}}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=Bd.parse(this._pc.localDescription.sdp));const r=$d.extractDtlsParameters({sdpObject:t});r.role=e,this._remoteSdp.updateDtlsRole("client"===e?"server":"client"),await new Promise(((e,t)=>{this.safeEmit("@connect",{dtlsParameters:r},e,t)})),this._transportReady=!0}assertSendDirection(){if("send"!==this._direction)throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if("recv"!==this._direction)throw new Error('method can just be called for handlers with "recv" direction')}}jd.Chrome55=Jd;var Xd={},Qd=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),Zd=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Yd=a&&a.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(null!=t)for(var i=e(t),n=0;n<i.length;n++)"default"!==i[n]&&Qd(r,t,i[n]);return Zd(r,t),r}}();Object.defineProperty(Xd,"__esModule",{value:!0}),Xd.Firefox120=void 0;const el=Yd(Ta),tl=ss,rl=Is,il=Yd(Ls),nl=Yd(Fs),sl=Yd(za),ol=Yd(Ja),al=Za,cl=rc,dl=bc,ll=new tl.Logger("Firefox120"),ul={OS:16,MIS:2048};class pl extends al.HandlerInterface{static createFactory(){return()=>new pl}constructor(){super(),this._closed=!1,this._mapMidTransceiver=new Map,this._sendStream=new MediaStream,this._hasDataChannelMediaSection=!1,this._nextSendSctpStreamId=0,this._transportReady=!1}get name(){return"Firefox120"}close(){if(ll.debug("close()"),!this._closed){if(this._closed=!0,this._pc)try{this._pc.close()}catch(e){}this.emit("@close")}}async getNativeRtpCapabilities(){ll.debug("getNativeRtpCapabilities()");const e=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"}),t=document.createElement("canvas");t.getContext("2d");const r=t.captureStream().getVideoTracks()[0];try{e.addTransceiver("audio",{direction:"sendrecv"}),e.addTransceiver(r,{direction:"sendrecv",sendEncodings:[{rid:"r0",maxBitrate:1e5},{rid:"r1",maxBitrate:5e5}]});const i=await e.createOffer();try{t.remove()}catch(e){}try{r.stop()}catch(e){}try{e.close()}catch(e){}const n=el.parse(i.sdp);return sl.extractRtpCapabilities({sdpObject:n})}catch(i){try{t.remove()}catch(e){}try{r.stop()}catch(e){}try{e.close()}catch(e){}throw i}}async getNativeSctpCapabilities(){return ll.debug("getNativeSctpCapabilities()"),{numStreams:ul}}run({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,extendedRtpCapabilities:d}){this.assertNotClosed(),ll.debug("run()"),this._direction=e,this._remoteSdp=new cl.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n}),this._sendingRtpParametersByKind={audio:nl.getSendingRtpParameters("audio",d),video:nl.getSendingRtpParameters("video",d)},this._sendingRemoteRtpParametersByKind={audio:nl.getSendingRemoteRtpParameters("audio",d),video:nl.getSendingRemoteRtpParameters("video",d)},this._pc=new RTCPeerConnection({iceServers:s??[],iceTransportPolicy:o??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...a},c),this._pc.addEventListener("icegatheringstatechange",(()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)})),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",(()=>{this.emit("@connectionstatechange",this._pc.connectionState)})):this._pc.addEventListener("iceconnectionstatechange",(()=>{switch(ll.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.iceConnectionState){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected");break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed")}}))}async updateIceServers(e){throw this.assertNotClosed(),new rl.UnsupportedError("not supported")}async restartIce(e){if(this.assertNotClosed(),ll.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});ll.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};ll.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};ll.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();ll.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",t),await this._pc.setLocalDescription(t)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:e,encodings:t,codecOptions:r,codec:i,onRtpSender:n}){this.assertNotClosed(),this.assertSendDirection(),ll.debug("send() [kind:%s, track.id:%s]",e.kind,e.id),t&&t.length>1&&t.forEach(((e,t)=>{e.rid=`r${t}`}));const s=il.clone(this._sendingRtpParametersByKind[e.kind]);s.codecs=nl.reduceCodecs(s.codecs,i);const o=il.clone(this._sendingRemoteRtpParametersByKind[e.kind]);o.codecs=nl.reduceCodecs(o.codecs,i);const a=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream],sendEncodings:t});n&&n(a.sender);const c=await this._pc.createOffer();let d=el.parse(c.sdp);this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:d});const l=(0,dl.parse)((t??[{}])[0].scalabilityMode);ll.debug("send() | calling pc.setLocalDescription() [offer:%o]",c),await this._pc.setLocalDescription(c);const u=a.mid;s.mid=u,d=el.parse(this._pc.localDescription.sdp);const p=d.media[d.media.length-1];if(s.rtcp.cname=sl.getCname({offerMediaObject:p}),t)if(1===t.length){const e=ol.getRtpEncodings({offerMediaObject:p});Object.assign(e[0],t[0]),s.encodings=e}else s.encodings=t;else s.encodings=ol.getRtpEncodings({offerMediaObject:p});if(s.encodings.length>1&&("video/vp8"===s.codecs[0].mimeType.toLowerCase()||"video/h264"===s.codecs[0].mimeType.toLowerCase()))for(const e of s.encodings)e.scalabilityMode?e.scalabilityMode=`L1T${l.temporalLayers}`:e.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:p,offerRtpParameters:s,answerRtpParameters:o,codecOptions:r,extmapAllowMixed:!0});const h={type:"answer",sdp:this._remoteSdp.getSdp()};return ll.debug("send() | calling pc.setRemoteDescription() [answer:%o]",h),await this._pc.setRemoteDescription(h),this._mapMidTransceiver.set(u,a),{localId:u,rtpParameters:s,rtpSender:a.sender}}async stopSending(e){if(this.assertSendDirection(),ll.debug("stopSending() [localId:%s]",e),this._closed)return;const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated transceiver not found");t.sender.replaceTrack(null),this._pc.removeTrack(t.sender),this._remoteSdp.disableMediaSection(t.mid);const r=await this._pc.createOffer();ll.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const i={type:"answer",sdp:this._remoteSdp.getSdp()};ll.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),ll.debug("pauseSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="inactive",this._remoteSdp.pauseMediaSection(e);const r=await this._pc.createOffer();ll.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const i={type:"answer",sdp:this._remoteSdp.getSdp()};ll.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),ll.debug("resumeSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="sendonly",this._remoteSdp.resumeSendingMediaSection(e);const r=await this._pc.createOffer();ll.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const i={type:"answer",sdp:this._remoteSdp.getSdp()};ll.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?ll.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):ll.debug("replaceTrack() [localId:%s, no track]",e);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");await r.sender.replaceTrack(t)}async setMaxSpatialLayer(e,t){this.assertNotClosed(),this.assertSendDirection(),ll.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated transceiver not found");const i=r.sender.getParameters();i.encodings.forEach(((e,r)=>{e.active=r<=t})),await r.sender.setParameters(i),this._remoteSdp.muxMediaSectionSimulcast(e,i.encodings);const n=await this._pc.createOffer();ll.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);const s={type:"answer",sdp:this._remoteSdp.getSdp()};ll.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),ll.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const i=r.sender.getParameters();i.encodings.forEach(((e,r)=>{i.encodings[r]={...e,...t}})),await r.sender.setParameters(i),this._remoteSdp.muxMediaSectionSimulcast(e,i.encodings);const n=await this._pc.createOffer();ll.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);const s={type:"answer",sdp:this._remoteSdp.getSdp()};ll.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async getSenderStats(e){this.assertNotClosed(),this.assertSendDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.sender.getStats()}async sendDataChannel({ordered:e,maxPacketLifeTime:t,maxRetransmits:r,label:i,protocol:n}){this.assertNotClosed(),this.assertSendDirection();const s={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmits:r,protocol:n};ll.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(i,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%ul.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=el.parse(e.sdp),r=t.media.find((e=>"application"===e.type));this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:t}),ll.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:r});const i={type:"answer",sdp:this._remoteSdp.getSdp()};ll.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._hasDataChannelMediaSection=!0}return{dataChannel:o,sctpStreamParameters:{streamId:s.id,ordered:s.ordered,maxPacketLifeTime:s.maxPacketLifeTime,maxRetransmits:s.maxRetransmits}}}async receive(e){this.assertNotClosed(),this.assertRecvDirection();const t=[],r=new Map;for(const t of e){const{trackId:e,kind:i,rtpParameters:n,streamId:s}=t;ll.debug("receive() [trackId:%s, kind:%s]",e,i);const o=n.mid??String(this._mapMidTransceiver.size);r.set(e,o),this._remoteSdp.receive({mid:o,kind:i,offerRtpParameters:n,streamId:s??n.rtcp.cname,trackId:e})}const i={type:"offer",sdp:this._remoteSdp.getSdp()};ll.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",i),await this._pc.setRemoteDescription(i);for(const t of e){const{trackId:e,onRtpReceiver:i}=t;if(i){const t=r.get(e),n=this._pc.getTransceivers().find((e=>e.mid===t));if(!n)throw new Error("transceiver not found");i(n.receiver)}}let n=await this._pc.createAnswer();const s=el.parse(n.sdp);for(const t of e){const{trackId:e,rtpParameters:i}=t,o=r.get(e),a=s.media.find((e=>String(e.mid)===o));sl.applyCodecParameters({offerRtpParameters:i,answerMediaObject:a}),n={type:"answer",sdp:el.write(s)}}this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:s}),ll.debug("receive() | calling pc.setLocalDescription() [answer:%o]",n),await this._pc.setLocalDescription(n);for(const i of e){const{trackId:e}=i,n=r.get(e),s=this._pc.getTransceivers().find((e=>e.mid===n));if(!s)throw new Error("new RTCRtpTransceiver not found");this._mapMidTransceiver.set(n,s),t.push({localId:n,track:s.receiver.track,rtpReceiver:s.receiver})}return t}async stopReceiving(e){if(this.assertRecvDirection(),this._closed)return;for(const t of e){ll.debug("stopReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(e.mid)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};ll.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();ll.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r);for(const t of e)this._mapMidTransceiver.delete(t)}async pauseReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(const t of e){ll.debug("pauseReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="inactive",this._remoteSdp.pauseMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};ll.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();ll.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async resumeReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(const t of e){ll.debug("resumeReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};ll.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();ll.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async getReceiverStats(e){this.assertRecvDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.receiver.getStats()}async receiveDataChannel({sctpStreamParameters:e,label:t,protocol:r}){this.assertNotClosed(),this.assertRecvDirection();const{streamId:i,ordered:n,maxPacketLifeTime:s,maxRetransmits:o}=e,a={negotiated:!0,id:i,ordered:n,maxPacketLifeTime:s,maxRetransmits:o,protocol:r};ll.debug("receiveDataChannel() [options:%o]",a);const c=this._pc.createDataChannel(t,a);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();const e={type:"offer",sdp:this._remoteSdp.getSdp()};ll.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=el.parse(t.sdp);await this.setupTransport({localDtlsRole:"client",localSdpObject:e})}ll.debug("receiveDataChannel() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setLocalDescription(t),this._hasDataChannelMediaSection=!0}return{dataChannel:c}}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=el.parse(this._pc.localDescription.sdp));const r=sl.extractDtlsParameters({sdpObject:t});r.role=e,this._remoteSdp.updateDtlsRole("client"===e?"server":"client"),await new Promise(((e,t)=>{this.safeEmit("@connect",{dtlsParameters:r},e,t)})),this._transportReady=!0}assertNotClosed(){if(this._closed)throw new rl.InvalidStateError("method called in a closed handler")}assertSendDirection(){if("send"!==this._direction)throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if("recv"!==this._direction)throw new Error('method can just be called for handlers with "recv" direction')}}Xd.Firefox120=pl;var hl={},fl=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),ml=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),gl=a&&a.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(null!=t)for(var i=e(t),n=0;n<i.length;n++)"default"!==i[n]&&fl(r,t,i[n]);return ml(r,t),r}}();Object.defineProperty(hl,"__esModule",{value:!0}),hl.Firefox60=void 0;const vl=gl(Ta),bl=ss,yl=Is,wl=gl(Ls),_l=gl(Fs),Sl=gl(za),Cl=gl(Ja),Rl=Za,kl=rc,Tl=bc,Pl=new bl.Logger("Firefox60"),Ol={OS:16,MIS:2048};class El extends Rl.HandlerInterface{static createFactory(){return()=>new El}constructor(){super(),this._closed=!1,this._mapMidTransceiver=new Map,this._sendStream=new MediaStream,this._hasDataChannelMediaSection=!1,this._nextSendSctpStreamId=0,this._transportReady=!1}get name(){return"Firefox60"}close(){if(Pl.debug("close()"),!this._closed){if(this._closed=!0,this._pc)try{this._pc.close()}catch(e){}this.emit("@close")}}async getNativeRtpCapabilities(){Pl.debug("getNativeRtpCapabilities()");const e=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"}),t=document.createElement("canvas");t.getContext("2d");const r=t.captureStream().getVideoTracks()[0];try{e.addTransceiver("audio",{direction:"sendrecv"});const i=e.addTransceiver(r,{direction:"sendrecv"}),n=i.sender.getParameters(),s=[{rid:"r0",maxBitrate:1e5},{rid:"r1",maxBitrate:5e5}];n.encodings=s,await i.sender.setParameters(n);const o=await e.createOffer();try{t.remove()}catch(e){}try{r.stop()}catch(e){}try{e.close()}catch(e){}const a=vl.parse(o.sdp);return Sl.extractRtpCapabilities({sdpObject:a})}catch(i){try{t.remove()}catch(e){}try{r.stop()}catch(e){}try{e.close()}catch(e){}throw i}}async getNativeSctpCapabilities(){return Pl.debug("getNativeSctpCapabilities()"),{numStreams:Ol}}run({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,extendedRtpCapabilities:d}){this.assertNotClosed(),Pl.debug("run()"),this._direction=e,this._remoteSdp=new kl.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n}),this._sendingRtpParametersByKind={audio:_l.getSendingRtpParameters("audio",d),video:_l.getSendingRtpParameters("video",d)},this._sendingRemoteRtpParametersByKind={audio:_l.getSendingRemoteRtpParameters("audio",d),video:_l.getSendingRemoteRtpParameters("video",d)},this._pc=new RTCPeerConnection({iceServers:s??[],iceTransportPolicy:o??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...a},c),this._pc.addEventListener("icegatheringstatechange",(()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)})),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",(()=>{this.emit("@connectionstatechange",this._pc.connectionState)})):this._pc.addEventListener("iceconnectionstatechange",(()=>{switch(Pl.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.iceConnectionState){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected");break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed")}}))}async updateIceServers(e){throw this.assertNotClosed(),new yl.UnsupportedError("not supported")}async restartIce(e){if(this.assertNotClosed(),Pl.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});Pl.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};Pl.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};Pl.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();Pl.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",t),await this._pc.setLocalDescription(t)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:e,encodings:t,codecOptions:r,codec:i}){this.assertNotClosed(),this.assertSendDirection(),Pl.debug("send() [kind:%s, track.id:%s]",e.kind,e.id),t&&((t=wl.clone(t)).forEach(((e,t)=>{e.rid=`r${t}`})),t.reverse());const n=wl.clone(this._sendingRtpParametersByKind[e.kind]);n.codecs=_l.reduceCodecs(n.codecs,i);const s=wl.clone(this._sendingRemoteRtpParametersByKind[e.kind]);s.codecs=_l.reduceCodecs(s.codecs,i);const o=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream]});if(t){const e=o.sender.getParameters();e.encodings=t,await o.sender.setParameters(e)}const a=await this._pc.createOffer();let c=vl.parse(a.sdp);this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:c});const d=(0,Tl.parse)((t??[{}])[0].scalabilityMode);Pl.debug("send() | calling pc.setLocalDescription() [offer:%o]",a),await this._pc.setLocalDescription(a);const l=o.mid;n.mid=l,c=vl.parse(this._pc.localDescription.sdp);const u=c.media[c.media.length-1];if(n.rtcp.cname=Sl.getCname({offerMediaObject:u}),t)if(1===t.length){const e=Cl.getRtpEncodings({offerMediaObject:u});Object.assign(e[0],t[0]),n.encodings=e}else n.encodings=t.reverse();else n.encodings=Cl.getRtpEncodings({offerMediaObject:u});if(n.encodings.length>1&&("video/vp8"===n.codecs[0].mimeType.toLowerCase()||"video/h264"===n.codecs[0].mimeType.toLowerCase()))for(const e of n.encodings)e.scalabilityMode?e.scalabilityMode=`L1T${d.temporalLayers}`:e.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:u,offerRtpParameters:n,answerRtpParameters:s,codecOptions:r,extmapAllowMixed:!0});const p={type:"answer",sdp:this._remoteSdp.getSdp()};return Pl.debug("send() | calling pc.setRemoteDescription() [answer:%o]",p),await this._pc.setRemoteDescription(p),this._mapMidTransceiver.set(l,o),{localId:l,rtpParameters:n,rtpSender:o.sender}}async stopSending(e){if(this.assertSendDirection(),Pl.debug("stopSending() [localId:%s]",e),this._closed)return;const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated transceiver not found");t.sender.replaceTrack(null),this._pc.removeTrack(t.sender),this._remoteSdp.disableMediaSection(t.mid);const r=await this._pc.createOffer();Pl.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const i={type:"answer",sdp:this._remoteSdp.getSdp()};Pl.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),Pl.debug("pauseSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="inactive",this._remoteSdp.pauseMediaSection(e);const r=await this._pc.createOffer();Pl.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const i={type:"answer",sdp:this._remoteSdp.getSdp()};Pl.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),Pl.debug("resumeSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="sendonly",this._remoteSdp.resumeSendingMediaSection(e);const r=await this._pc.createOffer();Pl.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const i={type:"answer",sdp:this._remoteSdp.getSdp()};Pl.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?Pl.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):Pl.debug("replaceTrack() [localId:%s, no track]",e);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");await r.sender.replaceTrack(t)}async setMaxSpatialLayer(e,t){this.assertNotClosed(),this.assertSendDirection(),Pl.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated transceiver not found");const i=r.sender.getParameters();t=i.encodings.length-1-t,i.encodings.forEach(((e,r)=>{e.active=r>=t})),await r.sender.setParameters(i),this._remoteSdp.muxMediaSectionSimulcast(e,i.encodings);const n=await this._pc.createOffer();Pl.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);const s={type:"answer",sdp:this._remoteSdp.getSdp()};Pl.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),Pl.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const i=r.sender.getParameters();i.encodings.forEach(((e,r)=>{i.encodings[r]={...e,...t}})),await r.sender.setParameters(i),this._remoteSdp.muxMediaSectionSimulcast(e,i.encodings);const n=await this._pc.createOffer();Pl.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);const s={type:"answer",sdp:this._remoteSdp.getSdp()};Pl.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async getSenderStats(e){this.assertNotClosed(),this.assertSendDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.sender.getStats()}async sendDataChannel({ordered:e,maxPacketLifeTime:t,maxRetransmits:r,label:i,protocol:n}){this.assertNotClosed(),this.assertSendDirection();const s={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmits:r,protocol:n};Pl.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(i,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%Ol.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=vl.parse(e.sdp),r=t.media.find((e=>"application"===e.type));this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:t}),Pl.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:r});const i={type:"answer",sdp:this._remoteSdp.getSdp()};Pl.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._hasDataChannelMediaSection=!0}return{dataChannel:o,sctpStreamParameters:{streamId:s.id,ordered:s.ordered,maxPacketLifeTime:s.maxPacketLifeTime,maxRetransmits:s.maxRetransmits}}}async receive(e){this.assertNotClosed(),this.assertRecvDirection();const t=[],r=new Map;for(const t of e){const{trackId:e,kind:i,rtpParameters:n,streamId:s}=t;Pl.debug("receive() [trackId:%s, kind:%s]",e,i);const o=n.mid??String(this._mapMidTransceiver.size);r.set(e,o),this._remoteSdp.receive({mid:o,kind:i,offerRtpParameters:n,streamId:s??n.rtcp.cname,trackId:e})}const i={type:"offer",sdp:this._remoteSdp.getSdp()};Pl.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",i),await this._pc.setRemoteDescription(i);let n=await this._pc.createAnswer();const s=vl.parse(n.sdp);for(const t of e){const{trackId:e,rtpParameters:i}=t,o=r.get(e),a=s.media.find((e=>String(e.mid)===o));Sl.applyCodecParameters({offerRtpParameters:i,answerMediaObject:a}),n={type:"answer",sdp:vl.write(s)}}this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:s}),Pl.debug("receive() | calling pc.setLocalDescription() [answer:%o]",n),await this._pc.setLocalDescription(n);for(const i of e){const{trackId:e}=i,n=r.get(e),s=this._pc.getTransceivers().find((e=>e.mid===n));if(!s)throw new Error("new RTCRtpTransceiver not found");this._mapMidTransceiver.set(n,s),t.push({localId:n,track:s.receiver.track,rtpReceiver:s.receiver})}return t}async stopReceiving(e){if(this.assertRecvDirection(),this._closed)return;for(const t of e){Pl.debug("stopReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(e.mid)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};Pl.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Pl.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r);for(const t of e)this._mapMidTransceiver.delete(t)}async pauseReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(const t of e){Pl.debug("pauseReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="inactive",this._remoteSdp.pauseMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};Pl.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Pl.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async resumeReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(const t of e){Pl.debug("resumeReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};Pl.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Pl.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async getReceiverStats(e){this.assertRecvDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.receiver.getStats()}async receiveDataChannel({sctpStreamParameters:e,label:t,protocol:r}){this.assertNotClosed(),this.assertRecvDirection();const{streamId:i,ordered:n,maxPacketLifeTime:s,maxRetransmits:o}=e,a={negotiated:!0,id:i,ordered:n,maxPacketLifeTime:s,maxRetransmits:o,protocol:r};Pl.debug("receiveDataChannel() [options:%o]",a);const c=this._pc.createDataChannel(t,a);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();const e={type:"offer",sdp:this._remoteSdp.getSdp()};Pl.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=vl.parse(t.sdp);await this.setupTransport({localDtlsRole:"client",localSdpObject:e})}Pl.debug("receiveDataChannel() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setLocalDescription(t),this._hasDataChannelMediaSection=!0}return{dataChannel:c}}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=vl.parse(this._pc.localDescription.sdp));const r=Sl.extractDtlsParameters({sdpObject:t});r.role=e,this._remoteSdp.updateDtlsRole("client"===e?"server":"client"),await new Promise(((e,t)=>{this.safeEmit("@connect",{dtlsParameters:r},e,t)})),this._transportReady=!0}assertNotClosed(){if(this._closed)throw new yl.InvalidStateError("method called in a closed handler")}assertSendDirection(){if("send"!==this._direction)throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if("recv"!==this._direction)throw new Error('method can just be called for handlers with "recv" direction')}}hl.Firefox60=El;var Dl={},Il=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),xl=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Ml=a&&a.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(null!=t)for(var i=e(t),n=0;n<i.length;n++)"default"!==i[n]&&Il(r,t,i[n]);return xl(r,t),r}}();Object.defineProperty(Dl,"__esModule",{value:!0});var jl=Dl.Safari12=void 0;const Ll=Ml(Ta),Al=ss,Nl=Ml(Ls),Bl=Ml(Fs),Fl=Ml(za),zl=Ml(Ja),Vl=Ml(Xa),Ul=Is,$l=Za,Gl=rc,ql=bc,Hl=new Al.Logger("Safari12"),Wl={OS:1024,MIS:1024};class Kl extends $l.HandlerInterface{static createFactory(){return()=>new Kl}constructor(){super(),this._closed=!1,this._mapMidTransceiver=new Map,this._sendStream=new MediaStream,this._hasDataChannelMediaSection=!1,this._nextSendSctpStreamId=0,this._transportReady=!1}get name(){return"Safari12"}close(){if(Hl.debug("close()"),!this._closed){if(this._closed=!0,this._pc)try{this._pc.close()}catch(e){}this.emit("@close")}}async getNativeRtpCapabilities(){Hl.debug("getNativeRtpCapabilities()");const e=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"});try{e.addTransceiver("audio"),e.addTransceiver("video");const t=await e.createOffer();try{e.close()}catch(e){}const r=Ll.parse(t.sdp),i=Fl.extractRtpCapabilities({sdpObject:r});return Vl.addNackSuppportForOpus(i),i}catch(t){try{e.close()}catch(e){}throw t}}async getNativeSctpCapabilities(){return Hl.debug("getNativeSctpCapabilities()"),{numStreams:Wl}}run({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,extendedRtpCapabilities:d}){this.assertNotClosed(),Hl.debug("run()"),this._direction=e,this._remoteSdp=new Gl.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n}),this._sendingRtpParametersByKind={audio:Bl.getSendingRtpParameters("audio",d),video:Bl.getSendingRtpParameters("video",d)},this._sendingRemoteRtpParametersByKind={audio:Bl.getSendingRemoteRtpParameters("audio",d),video:Bl.getSendingRemoteRtpParameters("video",d)},i.role&&"auto"!==i.role&&(this._forcedLocalDtlsRole="server"===i.role?"client":"server"),this._pc=new RTCPeerConnection({iceServers:s??[],iceTransportPolicy:o??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...a},c),this._pc.addEventListener("icegatheringstatechange",(()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)})),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",(()=>{this.emit("@connectionstatechange",this._pc.connectionState)})):this._pc.addEventListener("iceconnectionstatechange",(()=>{switch(Hl.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.iceConnectionState){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected");break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed")}}))}async updateIceServers(e){this.assertNotClosed(),Hl.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(this.assertNotClosed(),Hl.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});Hl.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};Hl.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};Hl.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();Hl.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",t),await this._pc.setLocalDescription(t)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:e,encodings:t,codecOptions:r,codec:i,onRtpSender:n}){this.assertNotClosed(),this.assertSendDirection(),Hl.debug("send() [kind:%s, track.id:%s]",e.kind,e.id);const s=Nl.clone(this._sendingRtpParametersByKind[e.kind]);s.codecs=Bl.reduceCodecs(s.codecs,i);const o=Nl.clone(this._sendingRemoteRtpParametersByKind[e.kind]);o.codecs=Bl.reduceCodecs(o.codecs,i);const a=this._remoteSdp.getNextMediaSectionIdx(),c=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream]});n&&n(c.sender);let d,l=await this._pc.createOffer(),u=Ll.parse(l.sdp);this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:u});const p=(0,ql.parse)((t??[{}])[0].scalabilityMode);t&&t.length>1&&(Hl.debug("send() | enabling legacy simulcast"),u=Ll.parse(l.sdp),d=u.media[a.idx],zl.addLegacySimulcast({offerMediaObject:d,numStreams:t.length}),l={type:"offer",sdp:Ll.write(u)}),Hl.debug("send() | calling pc.setLocalDescription() [offer:%o]",l),await this._pc.setLocalDescription(l);const h=c.mid;if(s.mid=h,u=Ll.parse(this._pc.localDescription.sdp),d=u.media[a.idx],s.rtcp.cname=Fl.getCname({offerMediaObject:d}),s.encodings=zl.getRtpEncodings({offerMediaObject:d}),t)for(let e=0;e<s.encodings.length;++e)t[e]&&Object.assign(s.encodings[e],t[e]);if(s.encodings.length>1&&("video/vp8"===s.codecs[0].mimeType.toLowerCase()||"video/h264"===s.codecs[0].mimeType.toLowerCase()))for(const e of s.encodings)e.scalabilityMode?e.scalabilityMode=`L1T${p.temporalLayers}`:e.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:d,reuseMid:a.reuseMid,offerRtpParameters:s,answerRtpParameters:o,codecOptions:r});const f={type:"answer",sdp:this._remoteSdp.getSdp()};return Hl.debug("send() | calling pc.setRemoteDescription() [answer:%o]",f),await this._pc.setRemoteDescription(f),this._mapMidTransceiver.set(h,c),{localId:h,rtpParameters:s,rtpSender:c.sender}}async stopSending(e){if(this.assertSendDirection(),this._closed)return;Hl.debug("stopSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.sender.replaceTrack(null),this._pc.removeTrack(t.sender);if(this._remoteSdp.closeMediaSection(t.mid))try{t.stop()}catch(e){}const r=await this._pc.createOffer();Hl.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const i={type:"answer",sdp:this._remoteSdp.getSdp()};Hl.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),Hl.debug("pauseSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="inactive",this._remoteSdp.pauseMediaSection(e);const r=await this._pc.createOffer();Hl.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const i={type:"answer",sdp:this._remoteSdp.getSdp()};Hl.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),Hl.debug("resumeSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="sendonly",this._remoteSdp.resumeSendingMediaSection(e);const r=await this._pc.createOffer();Hl.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const i={type:"answer",sdp:this._remoteSdp.getSdp()};Hl.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?Hl.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):Hl.debug("replaceTrack() [localId:%s, no track]",e);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");await r.sender.replaceTrack(t)}async setMaxSpatialLayer(e,t){this.assertNotClosed(),this.assertSendDirection(),Hl.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const i=r.sender.getParameters();i.encodings.forEach(((e,r)=>{e.active=r<=t})),await r.sender.setParameters(i),this._remoteSdp.muxMediaSectionSimulcast(e,i.encodings);const n=await this._pc.createOffer();Hl.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);const s={type:"answer",sdp:this._remoteSdp.getSdp()};Hl.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),Hl.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const i=r.sender.getParameters();i.encodings.forEach(((e,r)=>{i.encodings[r]={...e,...t}})),await r.sender.setParameters(i),this._remoteSdp.muxMediaSectionSimulcast(e,i.encodings);const n=await this._pc.createOffer();Hl.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);const s={type:"answer",sdp:this._remoteSdp.getSdp()};Hl.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async getSenderStats(e){this.assertNotClosed(),this.assertSendDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.sender.getStats()}async sendDataChannel({ordered:e,maxPacketLifeTime:t,maxRetransmits:r,label:i,protocol:n}){this.assertNotClosed(),this.assertSendDirection();const s={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmits:r,protocol:n};Hl.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(i,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%Wl.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=Ll.parse(e.sdp),r=t.media.find((e=>"application"===e.type));this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:t}),Hl.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:r});const i={type:"answer",sdp:this._remoteSdp.getSdp()};Hl.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._hasDataChannelMediaSection=!0}return{dataChannel:o,sctpStreamParameters:{streamId:s.id,ordered:s.ordered,maxPacketLifeTime:s.maxPacketLifeTime,maxRetransmits:s.maxRetransmits}}}async receive(e){this.assertNotClosed(),this.assertRecvDirection();const t=[],r=new Map;for(const t of e){const{trackId:e,kind:i,rtpParameters:n,streamId:s}=t;Hl.debug("receive() [trackId:%s, kind:%s]",e,i);const o=n.mid??String(this._mapMidTransceiver.size);r.set(e,o),this._remoteSdp.receive({mid:o,kind:i,offerRtpParameters:n,streamId:s??n.rtcp.cname,trackId:e})}const i={type:"offer",sdp:this._remoteSdp.getSdp()};Hl.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",i),await this._pc.setRemoteDescription(i);for(const t of e){const{trackId:e,onRtpReceiver:i}=t;if(i){const t=r.get(e),n=this._pc.getTransceivers().find((e=>e.mid===t));if(!n)throw new Error("transceiver not found");i(n.receiver)}}let n=await this._pc.createAnswer();const s=Ll.parse(n.sdp);for(const t of e){const{trackId:e,rtpParameters:i}=t,n=r.get(e),o=s.media.find((e=>String(e.mid)===n));Fl.applyCodecParameters({offerRtpParameters:i,answerMediaObject:o})}n={type:"answer",sdp:Ll.write(s)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:s}),Hl.debug("receive() | calling pc.setLocalDescription() [answer:%o]",n),await this._pc.setLocalDescription(n);for(const i of e){const{trackId:e}=i,n=r.get(e),s=this._pc.getTransceivers().find((e=>e.mid===n));if(!s)throw new Error("new RTCRtpTransceiver not found");this._mapMidTransceiver.set(n,s),t.push({localId:n,track:s.receiver.track,rtpReceiver:s.receiver})}return t}async stopReceiving(e){if(this.assertRecvDirection(),this._closed)return;for(const t of e){Hl.debug("stopReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(e.mid)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};Hl.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Hl.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r);for(const t of e)this._mapMidTransceiver.delete(t)}async pauseReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(const t of e){Hl.debug("pauseReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="inactive",this._remoteSdp.pauseMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};Hl.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Hl.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async resumeReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(const t of e){Hl.debug("resumeReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};Hl.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Hl.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async getReceiverStats(e){this.assertNotClosed(),this.assertRecvDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.receiver.getStats()}async receiveDataChannel({sctpStreamParameters:e,label:t,protocol:r}){this.assertNotClosed(),this.assertRecvDirection();const{streamId:i,ordered:n,maxPacketLifeTime:s,maxRetransmits:o}=e,a={negotiated:!0,id:i,ordered:n,maxPacketLifeTime:s,maxRetransmits:o,protocol:r};Hl.debug("receiveDataChannel() [options:%o]",a);const c=this._pc.createDataChannel(t,a);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();const e={type:"offer",sdp:this._remoteSdp.getSdp()};Hl.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=Ll.parse(t.sdp);await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:e})}Hl.debug("receiveDataChannel() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setLocalDescription(t),this._hasDataChannelMediaSection=!0}return{dataChannel:c}}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=Ll.parse(this._pc.localDescription.sdp));const r=Fl.extractDtlsParameters({sdpObject:t});r.role=e,this._remoteSdp.updateDtlsRole("client"===e?"server":"client"),await new Promise(((e,t)=>{this.safeEmit("@connect",{dtlsParameters:r},e,t)})),this._transportReady=!0}assertNotClosed(){if(this._closed)throw new Ul.InvalidStateError("method called in a closed handler")}assertSendDirection(){if("send"!==this._direction)throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if("recv"!==this._direction)throw new Error('method can just be called for handlers with "recv" direction')}}jl=Dl.Safari12=Kl;var Jl={},Xl=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),Ql=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Zl=a&&a.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(null!=t)for(var i=e(t),n=0;n<i.length;n++)"default"!==i[n]&&Xl(r,t,i[n]);return Ql(r,t),r}}();Object.defineProperty(Jl,"__esModule",{value:!0}),Jl.Safari11=void 0;const Yl=Zl(Ta),eu=ss,tu=Zl(Ls),ru=Zl(Fs),iu=Zl(za),nu=Zl(yd),su=Za,ou=rc,au=new eu.Logger("Safari11"),cu={OS:1024,MIS:1024};class du extends su.HandlerInterface{static createFactory(){return()=>new du}constructor(){super(),this._sendStream=new MediaStream,this._mapSendLocalIdRtpSender=new Map,this._nextSendLocalId=0,this._mapRecvLocalIdInfo=new Map,this._hasDataChannelMediaSection=!1,this._nextSendSctpStreamId=0,this._transportReady=!1}get name(){return"Safari11"}close(){if(au.debug("close()"),this._pc)try{this._pc.close()}catch(e){}this.emit("@close")}async getNativeRtpCapabilities(){au.debug("getNativeRtpCapabilities()");const e=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"plan-b"});try{const t=await e.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0});try{e.close()}catch(e){}const r=Yl.parse(t.sdp);return iu.extractRtpCapabilities({sdpObject:r})}catch(t){try{e.close()}catch(e){}throw t}}async getNativeSctpCapabilities(){return au.debug("getNativeSctpCapabilities()"),{numStreams:cu}}run({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,extendedRtpCapabilities:d}){au.debug("run()"),this._direction=e,this._remoteSdp=new ou.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n,planB:!0}),this._sendingRtpParametersByKind={audio:ru.getSendingRtpParameters("audio",d),video:ru.getSendingRtpParameters("video",d)},this._sendingRemoteRtpParametersByKind={audio:ru.getSendingRemoteRtpParameters("audio",d),video:ru.getSendingRemoteRtpParameters("video",d)},i.role&&"auto"!==i.role&&(this._forcedLocalDtlsRole="server"===i.role?"client":"server"),this._pc=new RTCPeerConnection({iceServers:s??[],iceTransportPolicy:o??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...a},c),this._pc.addEventListener("icegatheringstatechange",(()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)})),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",(()=>{this.emit("@connectionstatechange",this._pc.connectionState)})):this._pc.addEventListener("iceconnectionstatechange",(()=>{switch(au.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.iceConnectionState){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected");break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed")}}))}async updateIceServers(e){au.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(au.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});au.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};au.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};au.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();au.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",t),await this._pc.setLocalDescription(t)}}async getTransportStats(){return this._pc.getStats()}async send({track:e,encodings:t,codecOptions:r,codec:i}){this.assertSendDirection(),au.debug("send() [kind:%s, track.id:%s]",e.kind,e.id),i&&au.warn("send() | codec selection is not available in %s handler",this.name),this._sendStream.addTrack(e),this._pc.addTrack(e,this._sendStream);let n,s=await this._pc.createOffer(),o=Yl.parse(s.sdp);const a=tu.clone(this._sendingRtpParametersByKind[e.kind]);a.codecs=ru.reduceCodecs(a.codecs);const c=tu.clone(this._sendingRemoteRtpParametersByKind[e.kind]);if(c.codecs=ru.reduceCodecs(c.codecs),this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:o}),"video"===e.kind&&t&&t.length>1&&(au.debug("send() | enabling simulcast"),o=Yl.parse(s.sdp),n=o.media.find((e=>"video"===e.type)),nu.addLegacySimulcast({offerMediaObject:n,track:e,numStreams:t.length}),s={type:"offer",sdp:Yl.write(o)}),au.debug("send() | calling pc.setLocalDescription() [offer:%o]",s),await this._pc.setLocalDescription(s),o=Yl.parse(this._pc.localDescription.sdp),n=o.media.find((t=>t.type===e.kind)),a.rtcp.cname=iu.getCname({offerMediaObject:n}),a.encodings=nu.getRtpEncodings({offerMediaObject:n,track:e}),t)for(let e=0;e<a.encodings.length;++e)t[e]&&Object.assign(a.encodings[e],t[e]);if(a.encodings.length>1&&"video/vp8"===a.codecs[0].mimeType.toLowerCase())for(const e of a.encodings)e.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:n,offerRtpParameters:a,answerRtpParameters:c,codecOptions:r});const d={type:"answer",sdp:this._remoteSdp.getSdp()};au.debug("send() | calling pc.setRemoteDescription() [answer:%o]",d),await this._pc.setRemoteDescription(d);const l=String(this._nextSendLocalId);this._nextSendLocalId++;const u=this._pc.getSenders().find((t=>t.track===e));return this._mapSendLocalIdRtpSender.set(l,u),{localId:l,rtpParameters:a,rtpSender:u}}async stopSending(e){this.assertSendDirection();const t=this._mapSendLocalIdRtpSender.get(e);if(!t)throw new Error("associated RTCRtpSender not found");t.track&&this._sendStream.removeTrack(t.track),this._mapSendLocalIdRtpSender.delete(e);const r=await this._pc.createOffer();au.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r);try{await this._pc.setLocalDescription(r)}catch(e){if(0===this._sendStream.getTracks().length)return void au.warn("stopSending() | ignoring expected error due no sending tracks: %s",e.toString());throw e}if("stable"===this._pc.signalingState)return;const i={type:"answer",sdp:this._remoteSdp.getSdp()};au.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i)}async pauseSending(e){}async resumeSending(e){}async replaceTrack(e,t){this.assertSendDirection(),t?au.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):au.debug("replaceTrack() [localId:%s, no track]",e);const r=this._mapSendLocalIdRtpSender.get(e);if(!r)throw new Error("associated RTCRtpSender not found");const i=r.track;await r.replaceTrack(t),i&&this._sendStream.removeTrack(i),t&&this._sendStream.addTrack(t)}async setMaxSpatialLayer(e,t){this.assertSendDirection(),au.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);const r=this._mapSendLocalIdRtpSender.get(e);if(!r)throw new Error("associated RTCRtpSender not found");const i=r.getParameters();i.encodings.forEach(((e,r)=>{e.active=r<=t})),await r.setParameters(i)}async setRtpEncodingParameters(e,t){this.assertSendDirection(),au.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);const r=this._mapSendLocalIdRtpSender.get(e);if(!r)throw new Error("associated RTCRtpSender not found");const i=r.getParameters();i.encodings.forEach(((e,r)=>{i.encodings[r]={...e,...t}})),await r.setParameters(i)}async getSenderStats(e){this.assertSendDirection();const t=this._mapSendLocalIdRtpSender.get(e);if(!t)throw new Error("associated RTCRtpSender not found");return t.getStats()}async sendDataChannel({ordered:e,maxPacketLifeTime:t,maxRetransmits:r,label:i,protocol:n}){this.assertSendDirection();const s={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmits:r,protocol:n};au.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(i,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%cu.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=Yl.parse(e.sdp),r=t.media.find((e=>"application"===e.type));this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:t}),au.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:r});const i={type:"answer",sdp:this._remoteSdp.getSdp()};au.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._hasDataChannelMediaSection=!0}return{dataChannel:o,sctpStreamParameters:{streamId:s.id,ordered:s.ordered,maxPacketLifeTime:s.maxPacketLifeTime,maxRetransmits:s.maxRetransmits}}}async receive(e){this.assertRecvDirection();const t=[];for(const t of e){const{trackId:e,kind:r,rtpParameters:i,streamId:n}=t;au.debug("receive() [trackId:%s, kind:%s]",e,r);const s=r;this._remoteSdp.receive({mid:s,kind:r,offerRtpParameters:i,streamId:n??i.rtcp.cname,trackId:e})}const r={type:"offer",sdp:this._remoteSdp.getSdp()};au.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",r),await this._pc.setRemoteDescription(r);let i=await this._pc.createAnswer();const n=Yl.parse(i.sdp);for(const t of e){const{kind:e,rtpParameters:r}=t,i=e,s=n.media.find((e=>String(e.mid)===i));iu.applyCodecParameters({offerRtpParameters:r,answerMediaObject:s})}i={type:"answer",sdp:Yl.write(n)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:n}),au.debug("receive() | calling pc.setLocalDescription() [answer:%o]",i),await this._pc.setLocalDescription(i);for(const r of e){const{kind:e,trackId:i,rtpParameters:n}=r,s=e,o=i,a=this._pc.getReceivers().find((e=>e.track&&e.track.id===o));if(!a)throw new Error("new RTCRtpReceiver not");this._mapRecvLocalIdInfo.set(o,{mid:s,rtpParameters:n,rtpReceiver:a}),t.push({localId:o,track:a.track,rtpReceiver:a})}return t}async stopReceiving(e){this.assertRecvDirection();for(const t of e){au.debug("stopReceiving() [localId:%s]",t);const{mid:e,rtpParameters:r}=this._mapRecvLocalIdInfo.get(t)??{};this._mapRecvLocalIdInfo.delete(t),this._remoteSdp.planBStopReceiving({mid:e,offerRtpParameters:r})}const t={type:"offer",sdp:this._remoteSdp.getSdp()};au.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();au.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async getReceiverStats(e){this.assertRecvDirection();const{rtpReceiver:t}=this._mapRecvLocalIdInfo.get(e)??{};if(!t)throw new Error("associated RTCRtpReceiver not found");return t.getStats()}async pauseReceiving(e){}async resumeReceiving(e){}async receiveDataChannel({sctpStreamParameters:e,label:t,protocol:r}){this.assertRecvDirection();const{streamId:i,ordered:n,maxPacketLifeTime:s,maxRetransmits:o}=e,a={negotiated:!0,id:i,ordered:n,maxPacketLifeTime:s,maxRetransmits:o,protocol:r};au.debug("receiveDataChannel() [options:%o]",a);const c=this._pc.createDataChannel(t,a);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation({oldDataChannelSpec:!0});const e={type:"offer",sdp:this._remoteSdp.getSdp()};au.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=Yl.parse(t.sdp);await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:e})}au.debug("receiveDataChannel() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setLocalDescription(t),this._hasDataChannelMediaSection=!0}return{dataChannel:c}}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=Yl.parse(this._pc.localDescription.sdp));const r=iu.extractDtlsParameters({sdpObject:t});r.role=e,this._remoteSdp.updateDtlsRole("client"===e?"server":"client"),await new Promise(((e,t)=>{this.safeEmit("@connect",{dtlsParameters:r},e,t)})),this._transportReady=!0}assertSendDirection(){if("send"!==this._direction)throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if("recv"!==this._direction)throw new Error('method can just be called for handlers with "recv" direction')}}Jl.Safari11=du;var lu={},uu={},pu=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),hu=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),fu=a&&a.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(null!=t)for(var i=e(t),n=0;n<i.length;n++)"default"!==i[n]&&pu(r,t,i[n]);return hu(r,t),r}}();Object.defineProperty(uu,"__esModule",{value:!0}),uu.getCapabilities=function(){const e=RTCRtpReceiver.getCapabilities(),t=mu.clone(e);for(const e of t.codecs??[]){if(e.channels=e.numChannels,delete e.numChannels,e.mimeType=e.mimeType??`${e.kind}/${e.name}`,e.parameters){const t=e.parameters;t.apt&&(t.apt=Number(t.apt)),t["packetization-mode"]&&(t["packetization-mode"]=Number(t["packetization-mode"]))}for(const t of e.rtcpFeedback??[])t.parameter||(t.parameter="")}return t},uu.mangleRtpParameters=function(e){const t=mu.clone(e);t.mid&&(t.muxId=t.mid,delete t.mid);for(const e of t.codecs)e.channels&&(e.numChannels=e.channels,delete e.channels),e.mimeType&&!e.name&&(e.name=e.mimeType.split("/")[1]),delete e.mimeType;return t};const mu=fu(Ls);var gu=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),vu=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),bu=a&&a.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(null!=t)for(var i=e(t),n=0;n<i.length;n++)"default"!==i[n]&&gu(r,t,i[n]);return vu(r,t),r}}();Object.defineProperty(lu,"__esModule",{value:!0}),lu.Edge11=void 0;const yu=ss,wu=Is,_u=bu(Ls),Su=bu(Fs),Cu=bu(uu),Ru=Za,ku=new yu.Logger("Edge11");class Tu extends Ru.HandlerInterface{static createFactory(){return()=>new Tu}constructor(){super(),this._rtpSenders=new Map,this._rtpReceivers=new Map,this._nextSendLocalId=0,this._transportReady=!1}get name(){return"Edge11"}close(){ku.debug("close()");try{this._iceGatherer.close()}catch(e){}try{this._iceTransport.stop()}catch(e){}try{this._dtlsTransport.stop()}catch(e){}for(const e of this._rtpSenders.values())try{e.stop()}catch(e){}for(const e of this._rtpReceivers.values())try{e.stop()}catch(e){}this.emit("@close")}async getNativeRtpCapabilities(){return ku.debug("getNativeRtpCapabilities()"),Cu.getCapabilities()}async getNativeSctpCapabilities(){return ku.debug("getNativeSctpCapabilities()"),{numStreams:{OS:0,MIS:0}}}run({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,extendedRtpCapabilities:d}){ku.debug("run()"),this._sendingRtpParametersByKind={audio:Su.getSendingRtpParameters("audio",d),video:Su.getSendingRtpParameters("video",d)},this._remoteIceParameters=t,this._remoteIceCandidates=r,this._remoteDtlsParameters=i,this._cname=`CNAME-${_u.generateRandomNumber()}`,this.setIceGatherer({iceServers:s,iceTransportPolicy:o}),this.setIceTransport(),this.setDtlsTransport()}async updateIceServers(e){throw new wu.UnsupportedError("not supported")}async restartIce(e){if(ku.debug("restartIce()"),this._remoteIceParameters=e,this._transportReady){ku.debug("restartIce() | calling iceTransport.start()"),this._iceTransport.start(this._iceGatherer,e,"controlling");for(const e of this._remoteIceCandidates)this._iceTransport.addRemoteCandidate(e);this._iceTransport.addRemoteCandidate({})}}async getTransportStats(){return this._iceTransport.getStats()}async send({track:e,encodings:t,codecOptions:r,codec:i}){ku.debug("send() [kind:%s, track.id:%s]",e.kind,e.id),this._transportReady||await this.setupTransport({localDtlsRole:"server"}),ku.debug("send() | calling new RTCRtpSender()");const n=new RTCRtpSender(e,this._dtlsTransport),s=_u.clone(this._sendingRtpParametersByKind[e.kind]);s.codecs=Su.reduceCodecs(s.codecs,i);const o=s.codecs.some((e=>/.+\/rtx$/i.test(e.mimeType)));t||(t=[{}]);for(const e of t)e.ssrc=_u.generateRandomNumber(),o&&(e.rtx={ssrc:_u.generateRandomNumber()});s.encodings=t,s.rtcp={cname:this._cname,reducedSize:!0,mux:!0};const a=Cu.mangleRtpParameters(s);ku.debug("send() | calling rtpSender.send() [params:%o]",a),await n.send(a);const c=String(this._nextSendLocalId);return this._nextSendLocalId++,this._rtpSenders.set(c,n),{localId:c,rtpParameters:s,rtpSender:n}}async stopSending(e){ku.debug("stopSending() [localId:%s]",e);const t=this._rtpSenders.get(e);if(!t)throw new Error("RTCRtpSender not found");this._rtpSenders.delete(e);try{ku.debug("stopSending() | calling rtpSender.stop()"),t.stop()}catch(e){throw ku.warn("stopSending() | rtpSender.stop() failed:%o",e),e}}async pauseSending(e){}async resumeSending(e){}async replaceTrack(e,t){t?ku.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):ku.debug("replaceTrack() [localId:%s, no track]",e);const r=this._rtpSenders.get(e);if(!r)throw new Error("RTCRtpSender not found");r.setTrack(t)}async setMaxSpatialLayer(e,t){ku.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);const r=this._rtpSenders.get(e);if(!r)throw new Error("RTCRtpSender not found");const i=r.getParameters();i.encodings.forEach(((e,r)=>{e.active=r<=t})),await r.setParameters(i)}async setRtpEncodingParameters(e,t){ku.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);const r=this._rtpSenders.get(e);if(!r)throw new Error("RTCRtpSender not found");const i=r.getParameters();i.encodings.forEach(((e,r)=>{i.encodings[r]={...e,...t}})),await r.setParameters(i)}async getSenderStats(e){const t=this._rtpSenders.get(e);if(!t)throw new Error("RTCRtpSender not found");return t.getStats()}async sendDataChannel(e){throw new wu.UnsupportedError("not implemented")}async receive(e){const t=[];for(const t of e){const{trackId:e,kind:r}=t;ku.debug("receive() [trackId:%s, kind:%s]",e,r)}this._transportReady||await this.setupTransport({localDtlsRole:"server"});for(const r of e){const{trackId:e,kind:i,rtpParameters:n}=r;ku.debug("receive() | calling new RTCRtpReceiver()");const s=new RTCRtpReceiver(this._dtlsTransport,i);s.addEventListener("error",(e=>{ku.error('rtpReceiver "error" event [event:%o]',e)}));const o=Cu.mangleRtpParameters(n);ku.debug("receive() | calling rtpReceiver.receive() [params:%o]",o),await s.receive(o);const a=e;this._rtpReceivers.set(a,s),t.push({localId:a,track:s.track,rtpReceiver:s})}return t}async stopReceiving(e){for(const t of e){ku.debug("stopReceiving() [localId:%s]",t);const e=this._rtpReceivers.get(t);if(!e)throw new Error("RTCRtpReceiver not found");this._rtpReceivers.delete(t);try{ku.debug("stopReceiving() | calling rtpReceiver.stop()"),e.stop()}catch(e){ku.warn("stopReceiving() | rtpReceiver.stop() failed:%o",e)}}}async pauseReceiving(e){}async resumeReceiving(e){}async getReceiverStats(e){const t=this._rtpReceivers.get(e);if(!t)throw new Error("RTCRtpReceiver not found");return t.getStats()}async receiveDataChannel(e){throw new wu.UnsupportedError("not implemented")}setIceGatherer({iceServers:e,iceTransportPolicy:t}){const r=new RTCIceGatherer({iceServers:e??[],gatherPolicy:t??"all"});r.addEventListener("error",(e=>{ku.error('iceGatherer "error" event [event:%o]',e)}));try{r.gather()}catch(e){ku.debug("setIceGatherer() | iceGatherer.gather() failed: %s",e.toString())}this._iceGatherer=r}setIceTransport(){const e=new RTCIceTransport(this._iceGatherer);e.addEventListener("statechange",(()=>{switch(e.state){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected");break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed")}})),e.addEventListener("icestatechange",(()=>{switch(e.state){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected");break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed")}})),e.addEventListener("candidatepairchange",(e=>{ku.debug('iceTransport "candidatepairchange" event [pair:%o]',e.pair)})),this._iceTransport=e}setDtlsTransport(){const e=new RTCDtlsTransport(this._iceTransport);e.addEventListener("statechange",(()=>{ku.debug('dtlsTransport "statechange" event [state:%s]',e.state)})),e.addEventListener("dtlsstatechange",(()=>{ku.debug('dtlsTransport "dtlsstatechange" event [state:%s]',e.state),"closed"===e.state&&this.emit("@connectionstatechange","closed")})),e.addEventListener("error",(e=>{ku.error('dtlsTransport "error" event [event:%o]',e)})),this._dtlsTransport=e}async setupTransport({localDtlsRole:e}){ku.debug("setupTransport()");const t=this._dtlsTransport.getLocalParameters();t.role=e,await new Promise(((e,r)=>{this.safeEmit("@connect",{dtlsParameters:t},e,r)})),this._iceTransport.start(this._iceGatherer,this._remoteIceParameters,"controlling");for(const e of this._remoteIceCandidates)this._iceTransport.addRemoteCandidate(e);this._iceTransport.addRemoteCandidate({}),this._remoteDtlsParameters.fingerprints=this._remoteDtlsParameters.fingerprints.filter((e=>"sha-256"===e.algorithm||"sha-384"===e.algorithm||"sha-512"===e.algorithm)),this._dtlsTransport.start(this._remoteDtlsParameters),this._transportReady=!0}}lu.Edge11=Tu;var Pu={},Ou=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),Eu=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Du=a&&a.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(null!=t)for(var i=e(t),n=0;n<i.length;n++)"default"!==i[n]&&Ou(r,t,i[n]);return Eu(r,t),r}}();Object.defineProperty(Pu,"__esModule",{value:!0}),Pu.ReactNativeUnifiedPlan=void 0;const Iu=Du(Ta),xu=ss,Mu=Du(Ls),ju=Du(Fs),Lu=Du(za),Au=Du(Ja),Nu=Du(Xa),Bu=Is,Fu=Za,zu=rc,Vu=bc,Uu=new xu.Logger("ReactNativeUnifiedPlan"),$u={OS:1024,MIS:1024};class Gu extends Fu.HandlerInterface{static createFactory(){return()=>new Gu}constructor(){super(),this._closed=!1,this._mapMidTransceiver=new Map,this._sendStream=new MediaStream,this._hasDataChannelMediaSection=!1,this._nextSendSctpStreamId=0,this._transportReady=!1}get name(){return"ReactNativeUnifiedPlan"}close(){if(Uu.debug("close()"),!this._closed){if(this._closed=!0,this._sendStream.release(!1),this._pc)try{this._pc.close()}catch(e){}this.emit("@close")}}async getNativeRtpCapabilities(){Uu.debug("getNativeRtpCapabilities()");const e=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"unified-plan"});try{e.addTransceiver("audio"),e.addTransceiver("video");const t=await e.createOffer();try{e.close()}catch(e){}const r=Iu.parse(t.sdp),i=Lu.extractRtpCapabilities({sdpObject:r});return Nu.addNackSuppportForOpus(i),i}catch(t){try{e.close()}catch(e){}throw t}}async getNativeSctpCapabilities(){return Uu.debug("getNativeSctpCapabilities()"),{numStreams:$u}}run({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,extendedRtpCapabilities:d}){this.assertNotClosed(),Uu.debug("run()"),this._direction=e,this._remoteSdp=new zu.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n}),this._sendingRtpParametersByKind={audio:ju.getSendingRtpParameters("audio",d),video:ju.getSendingRtpParameters("video",d)},this._sendingRemoteRtpParametersByKind={audio:ju.getSendingRemoteRtpParameters("audio",d),video:ju.getSendingRemoteRtpParameters("video",d)},i.role&&"auto"!==i.role&&(this._forcedLocalDtlsRole="server"===i.role?"client":"server"),this._pc=new RTCPeerConnection({iceServers:s??[],iceTransportPolicy:o??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"unified-plan",...a},c),this._pc.addEventListener("icegatheringstatechange",(()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)})),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",(()=>{this.emit("@connectionstatechange",this._pc.connectionState)})):this._pc.addEventListener("iceconnectionstatechange",(()=>{switch(Uu.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.iceConnectionState){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected");break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed")}}))}async updateIceServers(e){this.assertNotClosed(),Uu.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(this.assertNotClosed(),Uu.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});Uu.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};Uu.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};Uu.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();Uu.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",t),await this._pc.setLocalDescription(t)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:e,encodings:t,codecOptions:r,codec:i,onRtpSender:n}){this.assertNotClosed(),this.assertSendDirection(),Uu.debug("send() [kind:%s, track.id:%s]",e.kind,e.id),t&&t.length>1&&t.forEach(((e,t)=>{e.rid=`r${t}`}));const s=Mu.clone(this._sendingRtpParametersByKind[e.kind]);s.codecs=ju.reduceCodecs(s.codecs,i);const o=Mu.clone(this._sendingRemoteRtpParametersByKind[e.kind]);o.codecs=ju.reduceCodecs(o.codecs,i);const a=this._remoteSdp.getNextMediaSectionIdx(),c=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream],sendEncodings:t});n&&n(c.sender);let d,l=await this._pc.createOffer(),u=Iu.parse(l.sdp);this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:u});let p=!1;const h=(0,Vu.parse)((t??[{}])[0].scalabilityMode);t&&1===t.length&&h.spatialLayers>1&&"video/vp9"===s.codecs[0].mimeType.toLowerCase()&&(Uu.debug("send() | enabling legacy simulcast for VP9 SVC"),p=!0,u=Iu.parse(l.sdp),d=u.media[a.idx],Au.addLegacySimulcast({offerMediaObject:d,numStreams:h.spatialLayers}),l={type:"offer",sdp:Iu.write(u)}),Uu.debug("send() | calling pc.setLocalDescription() [offer:%o]",l),await this._pc.setLocalDescription(l);let f=c.mid??void 0;if(f||Uu.warn("send() | missing transceiver.mid (bug in react-native-webrtc, using a workaround"),s.mid=f,u=Iu.parse(this._pc.localDescription.sdp),d=u.media[a.idx],s.rtcp.cname=Lu.getCname({offerMediaObject:d}),t)if(1===t.length){let e=Au.getRtpEncodings({offerMediaObject:d});Object.assign(e[0],t[0]),p&&(e=[e[0]]),s.encodings=e}else s.encodings=t;else s.encodings=Au.getRtpEncodings({offerMediaObject:d});if(s.encodings.length>1&&("video/vp8"===s.codecs[0].mimeType.toLowerCase()||"video/h264"===s.codecs[0].mimeType.toLowerCase()))for(const e of s.encodings)e.scalabilityMode?e.scalabilityMode=`L1T${h.temporalLayers}`:e.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:d,reuseMid:a.reuseMid,offerRtpParameters:s,answerRtpParameters:o,codecOptions:r,extmapAllowMixed:!0});const m={type:"answer",sdp:this._remoteSdp.getSdp()};return Uu.debug("send() | calling pc.setRemoteDescription() [answer:%o]",m),await this._pc.setRemoteDescription(m),f||(f=c.mid,s.mid=f),this._mapMidTransceiver.set(f,c),{localId:f,rtpParameters:s,rtpSender:c.sender}}async stopSending(e){if(this.assertSendDirection(),this._closed)return;Uu.debug("stopSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.sender.replaceTrack(null),this._pc.removeTrack(t.sender);if(this._remoteSdp.closeMediaSection(t.mid))try{t.stop()}catch(e){}const r=await this._pc.createOffer();Uu.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const i={type:"answer",sdp:this._remoteSdp.getSdp()};Uu.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),Uu.debug("pauseSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="inactive",this._remoteSdp.pauseMediaSection(e);const r=await this._pc.createOffer();Uu.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const i={type:"answer",sdp:this._remoteSdp.getSdp()};Uu.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),Uu.debug("resumeSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(this._remoteSdp.resumeSendingMediaSection(e),!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="sendonly";const r=await this._pc.createOffer();Uu.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const i={type:"answer",sdp:this._remoteSdp.getSdp()};Uu.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?Uu.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):Uu.debug("replaceTrack() [localId:%s, no track]",e);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");await r.sender.replaceTrack(t)}async setMaxSpatialLayer(e,t){this.assertNotClosed(),this.assertSendDirection(),Uu.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const i=r.sender.getParameters();i.encodings.forEach(((e,r)=>{e.active=r<=t})),await r.sender.setParameters(i),this._remoteSdp.muxMediaSectionSimulcast(e,i.encodings);const n=await this._pc.createOffer();Uu.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);const s={type:"answer",sdp:this._remoteSdp.getSdp()};Uu.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),Uu.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const i=r.sender.getParameters();i.encodings.forEach(((e,r)=>{i.encodings[r]={...e,...t}})),await r.sender.setParameters(i),this._remoteSdp.muxMediaSectionSimulcast(e,i.encodings);const n=await this._pc.createOffer();Uu.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);const s={type:"answer",sdp:this._remoteSdp.getSdp()};Uu.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async getSenderStats(e){this.assertNotClosed(),this.assertSendDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.sender.getStats()}async sendDataChannel({ordered:e,maxPacketLifeTime:t,maxRetransmits:r,label:i,protocol:n}){this.assertNotClosed(),this.assertSendDirection();const s={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmits:r,protocol:n};Uu.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(i,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%$u.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=Iu.parse(e.sdp),r=t.media.find((e=>"application"===e.type));this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:t}),Uu.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:r});const i={type:"answer",sdp:this._remoteSdp.getSdp()};Uu.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._hasDataChannelMediaSection=!0}return{dataChannel:o,sctpStreamParameters:{streamId:s.id,ordered:s.ordered,maxPacketLifeTime:s.maxPacketLifeTime,maxRetransmits:s.maxRetransmits}}}async receive(e){this.assertNotClosed(),this.assertRecvDirection();const t=[],r=new Map;for(const t of e){const{trackId:e,kind:i,rtpParameters:n,streamId:s}=t;Uu.debug("receive() [trackId:%s, kind:%s]",e,i);const o=n.mid??String(this._mapMidTransceiver.size);r.set(e,o),this._remoteSdp.receive({mid:o,kind:i,offerRtpParameters:n,streamId:s??n.rtcp.cname,trackId:e})}const i={type:"offer",sdp:this._remoteSdp.getSdp()};Uu.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",i),await this._pc.setRemoteDescription(i);for(const t of e){const{trackId:e,onRtpReceiver:i}=t;if(i){const t=r.get(e),n=this._pc.getTransceivers().find((e=>e.mid===t));if(!n)throw new Error("transceiver not found");i(n.receiver)}}let n=await this._pc.createAnswer();const s=Iu.parse(n.sdp);for(const t of e){const{trackId:e,rtpParameters:i}=t,n=r.get(e),o=s.media.find((e=>String(e.mid)===n));Lu.applyCodecParameters({offerRtpParameters:i,answerMediaObject:o})}n={type:"answer",sdp:Iu.write(s)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:s}),Uu.debug("receive() | calling pc.setLocalDescription() [answer:%o]",n),await this._pc.setLocalDescription(n);for(const i of e){const{trackId:e}=i,n=r.get(e),s=this._pc.getTransceivers().find((e=>e.mid===n));if(!s)throw new Error("new RTCRtpTransceiver not found");this._mapMidTransceiver.set(n,s),t.push({localId:n,track:s.receiver.track,rtpReceiver:s.receiver})}return t}async stopReceiving(e){if(this.assertRecvDirection(),this._closed)return;for(const t of e){Uu.debug("stopReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(e.mid)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};Uu.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Uu.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r);for(const t of e)this._mapMidTransceiver.delete(t)}async pauseReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(const t of e){Uu.debug("pauseReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="inactive",this._remoteSdp.pauseMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};Uu.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Uu.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async resumeReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(const t of e){Uu.debug("resumeReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};Uu.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Uu.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async getReceiverStats(e){this.assertNotClosed(),this.assertRecvDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.receiver.getStats()}async receiveDataChannel({sctpStreamParameters:e,label:t,protocol:r}){this.assertNotClosed(),this.assertRecvDirection();const{streamId:i,ordered:n,maxPacketLifeTime:s,maxRetransmits:o}=e,a={negotiated:!0,id:i,ordered:n,maxPacketLifeTime:s,maxRetransmits:o,protocol:r};Uu.debug("receiveDataChannel() [options:%o]",a);const c=this._pc.createDataChannel(t,a);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();const e={type:"offer",sdp:this._remoteSdp.getSdp()};Uu.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=Iu.parse(t.sdp);await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:e})}Uu.debug("receiveDataChannel() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setLocalDescription(t),this._hasDataChannelMediaSection=!0}return{dataChannel:c}}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=Iu.parse(this._pc.localDescription.sdp));const r=Lu.extractDtlsParameters({sdpObject:t});r.role=e,this._remoteSdp.updateDtlsRole("client"===e?"server":"client"),await new Promise(((e,t)=>{this.safeEmit("@connect",{dtlsParameters:r},e,t)})),this._transportReady=!0}assertNotClosed(){if(this._closed)throw new Bu.InvalidStateError("method called in a closed handler")}assertSendDirection(){if("send"!==this._direction)throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if("recv"!==this._direction)throw new Error('method can just be called for handlers with "recv" direction')}}Pu.ReactNativeUnifiedPlan=Gu;var qu={},Hu=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),Wu=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Ku=a&&a.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(null!=t)for(var i=e(t),n=0;n<i.length;n++)"default"!==i[n]&&Hu(r,t,i[n]);return Wu(r,t),r}}();Object.defineProperty(qu,"__esModule",{value:!0}),qu.ReactNative=void 0;const Ju=Ku(Ta),Xu=ss,Qu=Is,Zu=Ku(Ls),Yu=Ku(Fs),ep=Ku(za),tp=Ku(yd),rp=Za,ip=rc,np=new Xu.Logger("ReactNative"),sp={OS:1024,MIS:1024};class op extends rp.HandlerInterface{static createFactory(){return()=>new op}constructor(){super(),this._sendStream=new MediaStream,this._mapSendLocalIdTrack=new Map,this._nextSendLocalId=0,this._mapRecvLocalIdInfo=new Map,this._hasDataChannelMediaSection=!1,this._nextSendSctpStreamId=0,this._transportReady=!1}get name(){return"ReactNative"}close(){if(np.debug("close()"),this._sendStream.release(!1),this._pc)try{this._pc.close()}catch(e){}this.emit("@close")}async getNativeRtpCapabilities(){np.debug("getNativeRtpCapabilities()");const e=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"plan-b"});try{const t=await e.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0});try{e.close()}catch(e){}const r=Ju.parse(t.sdp);return ep.extractRtpCapabilities({sdpObject:r})}catch(t){try{e.close()}catch(e){}throw t}}async getNativeSctpCapabilities(){return np.debug("getNativeSctpCapabilities()"),{numStreams:sp}}run({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,extendedRtpCapabilities:d}){np.debug("run()"),this._direction=e,this._remoteSdp=new ip.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n,planB:!0}),this._sendingRtpParametersByKind={audio:Yu.getSendingRtpParameters("audio",d),video:Yu.getSendingRtpParameters("video",d)},this._sendingRemoteRtpParametersByKind={audio:Yu.getSendingRemoteRtpParameters("audio",d),video:Yu.getSendingRemoteRtpParameters("video",d)},i.role&&"auto"!==i.role&&(this._forcedLocalDtlsRole="server"===i.role?"client":"server"),this._pc=new RTCPeerConnection({iceServers:s??[],iceTransportPolicy:o??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"plan-b",...a},c),this._pc.addEventListener("icegatheringstatechange",(()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)})),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",(()=>{this.emit("@connectionstatechange",this._pc.connectionState)})):this._pc.addEventListener("iceconnectionstatechange",(()=>{switch(np.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.iceConnectionState){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected");break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed")}}))}async updateIceServers(e){np.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(np.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});np.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};np.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};np.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();np.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",t),await this._pc.setLocalDescription(t)}}async getTransportStats(){return this._pc.getStats()}async send({track:e,encodings:t,codecOptions:r,codec:i}){this.assertSendDirection(),np.debug("send() [kind:%s, track.id:%s]",e.kind,e.id),i&&np.warn("send() | codec selection is not available in %s handler",this.name),this._sendStream.addTrack(e),this._pc.addStream(this._sendStream);let n,s=await this._pc.createOffer(),o=Ju.parse(s.sdp);const a=Zu.clone(this._sendingRtpParametersByKind[e.kind]);a.codecs=Yu.reduceCodecs(a.codecs);const c=Zu.clone(this._sendingRemoteRtpParametersByKind[e.kind]);if(c.codecs=Yu.reduceCodecs(c.codecs),this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:o}),"video"===e.kind&&t&&t.length>1&&(np.debug("send() | enabling simulcast"),o=Ju.parse(s.sdp),n=o.media.find((e=>"video"===e.type)),tp.addLegacySimulcast({offerMediaObject:n,track:e,numStreams:t.length}),s={type:"offer",sdp:Ju.write(o)}),np.debug("send() | calling pc.setLocalDescription() [offer:%o]",s),await this._pc.setLocalDescription(s),o=Ju.parse(this._pc.localDescription.sdp),n=o.media.find((t=>t.type===e.kind)),a.rtcp.cname=ep.getCname({offerMediaObject:n}),a.encodings=tp.getRtpEncodings({offerMediaObject:n,track:e}),t)for(let e=0;e<a.encodings.length;++e)t[e]&&Object.assign(a.encodings[e],t[e]);if(a.encodings.length>1&&("video/vp8"===a.codecs[0].mimeType.toLowerCase()||"video/h264"===a.codecs[0].mimeType.toLowerCase()))for(const e of a.encodings)e.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:n,offerRtpParameters:a,answerRtpParameters:c,codecOptions:r});const d={type:"answer",sdp:this._remoteSdp.getSdp()};np.debug("send() | calling pc.setRemoteDescription() [answer:%o]",d),await this._pc.setRemoteDescription(d);const l=String(this._nextSendLocalId);return this._nextSendLocalId++,this._mapSendLocalIdTrack.set(l,e),{localId:l,rtpParameters:a}}async stopSending(e){this.assertSendDirection(),np.debug("stopSending() [localId:%s]",e);const t=this._mapSendLocalIdTrack.get(e);if(!t)throw new Error("track not found");this._mapSendLocalIdTrack.delete(e),this._sendStream.removeTrack(t),this._pc.addStream(this._sendStream);const r=await this._pc.createOffer();np.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r);try{await this._pc.setLocalDescription(r)}catch(e){if(0===this._sendStream.getTracks().length)return void np.warn("stopSending() | ignoring expected error due no sending tracks: %s",e.toString());throw e}if("stable"===this._pc.signalingState)return;const i={type:"answer",sdp:this._remoteSdp.getSdp()};np.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i)}async pauseSending(e){}async resumeSending(e){}async replaceTrack(e,t){throw new Qu.UnsupportedError("not implemented")}async setMaxSpatialLayer(e,t){throw new Qu.UnsupportedError("not implemented")}async setRtpEncodingParameters(e,t){throw new Qu.UnsupportedError("not implemented")}async getSenderStats(e){throw new Qu.UnsupportedError("not implemented")}async sendDataChannel({ordered:e,maxPacketLifeTime:t,maxRetransmits:r,label:i,protocol:n}){this.assertSendDirection();const s={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmitTime:t,maxRetransmits:r,protocol:n};np.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(i,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%sp.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=Ju.parse(e.sdp),r=t.media.find((e=>"application"===e.type));this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:t}),np.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:r});const i={type:"answer",sdp:this._remoteSdp.getSdp()};np.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._hasDataChannelMediaSection=!0}return{dataChannel:o,sctpStreamParameters:{streamId:s.id,ordered:s.ordered,maxPacketLifeTime:s.maxPacketLifeTime,maxRetransmits:s.maxRetransmits}}}async receive(e){this.assertRecvDirection();const t=[],r=new Map;for(const t of e){const{trackId:e,kind:i,rtpParameters:n}=t;np.debug("receive() [trackId:%s, kind:%s]",e,i);const s=i;let o=t.streamId??n.rtcp.cname;np.debug("receive() | forcing a random remote streamId to avoid well known bug in react-native-webrtc"),o+=`-hack-${Zu.generateRandomNumber()}`,r.set(e,o),this._remoteSdp.receive({mid:s,kind:i,offerRtpParameters:n,streamId:o,trackId:e})}const i={type:"offer",sdp:this._remoteSdp.getSdp()};np.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",i),await this._pc.setRemoteDescription(i);let n=await this._pc.createAnswer();const s=Ju.parse(n.sdp);for(const t of e){const{kind:e,rtpParameters:r}=t,i=e,n=s.media.find((e=>String(e.mid)===i));ep.applyCodecParameters({offerRtpParameters:r,answerMediaObject:n})}n={type:"answer",sdp:Ju.write(s)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:s}),np.debug("receive() | calling pc.setLocalDescription() [answer:%o]",n),await this._pc.setLocalDescription(n);for(const i of e){const{kind:e,trackId:n,rtpParameters:s}=i,o=n,a=e,c=r.get(n),d=this._pc.getRemoteStreams().find((e=>e.id===c)).getTrackById(o);if(!d)throw new Error("remote track not found");this._mapRecvLocalIdInfo.set(o,{mid:a,rtpParameters:s}),t.push({localId:o,track:d})}return t}async stopReceiving(e){this.assertRecvDirection();for(const t of e){np.debug("stopReceiving() [localId:%s]",t);const{mid:e,rtpParameters:r}=this._mapRecvLocalIdInfo.get(t)??{};this._mapRecvLocalIdInfo.delete(t),this._remoteSdp.planBStopReceiving({mid:e,offerRtpParameters:r})}const t={type:"offer",sdp:this._remoteSdp.getSdp()};np.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();np.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async pauseReceiving(e){}async resumeReceiving(e){}async getReceiverStats(e){throw new Qu.UnsupportedError("not implemented")}async receiveDataChannel({sctpStreamParameters:e,label:t,protocol:r}){this.assertRecvDirection();const{streamId:i,ordered:n,maxPacketLifeTime:s,maxRetransmits:o}=e,a={negotiated:!0,id:i,ordered:n,maxPacketLifeTime:s,maxRetransmitTime:s,maxRetransmits:o,protocol:r};np.debug("receiveDataChannel() [options:%o]",a);const c=this._pc.createDataChannel(t,a);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation({oldDataChannelSpec:!0});const e={type:"offer",sdp:this._remoteSdp.getSdp()};np.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=Ju.parse(t.sdp);await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:e})}np.debug("receiveDataChannel() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setLocalDescription(t),this._hasDataChannelMediaSection=!0}return{dataChannel:c}}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=Ju.parse(this._pc.localDescription.sdp));const r=ep.extractDtlsParameters({sdpObject:t});r.role=e,this._remoteSdp.updateDtlsRole("client"===e?"server":"client"),await new Promise(((e,t)=>{this.safeEmit("@connect",{dtlsParameters:r},e,t)})),this._transportReady=!0}assertSendDirection(){if("send"!==this._direction)throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if("recv"!==this._direction)throw new Error('method can just be called for handlers with "recv" direction')}}qu.ReactNative=op;var ap=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),cp=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),dp=a&&a.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(null!=t)for(var i=e(t),n=0;n<i.length;n++)"default"!==i[n]&&ap(r,t,i[n]);return cp(r,t),r}}();Object.defineProperty(rs,"__esModule",{value:!0}),rs.Device=void 0,rs.detectDevice=Dp;const lp=ns,up=ss,pp=us,hp=Is,fp=dp(Ls),mp=dp(Fs),gp=xo,vp=ka,bp=Bc,yp=rd,wp=bd,_p=jd,Sp=Xd,Cp=hl,Rp=Dl,kp=Jl,Tp=lu,Pp=Pu,Op=qu,Ep=new up.Logger("Device");function Dp(e){if(!e&&"object"==typeof navigator&&"ReactNative"===navigator.product)return Ep.debug("detectDevice() | React-Native detected"),"undefined"==typeof RTCPeerConnection?void Ep.warn("detectDevice() | unsupported react-native-webrtc without RTCPeerConnection, forgot to call registerGlobals()?"):"undefined"!=typeof RTCRtpTransceiver?(Ep.debug("detectDevice() | ReactNative UnifiedPlan handler chosen"),"ReactNativeUnifiedPlan"):(Ep.debug("detectDevice() | ReactNative PlanB handler chosen"),"ReactNative");if(e||"object"==typeof navigator&&"string"==typeof navigator.userAgent){e??(e=navigator.userAgent);const t=new lp.UAParser(e);Ep.debug("detectDevice() | browser detected [userAgent:%s, parsed:%o]",e,t.getResult());const r=t.getBrowser(),i=r.name?.toLowerCase(),n=parseInt(r.major??"0"),s=t.getEngine(),o=s.name?.toLowerCase(),a=t.getOS(),c=a.name?.toLowerCase(),d=parseFloat(a.version??"0"),l=t.getDevice(),u=l.model?.toLowerCase(),p="ios"===c||"ipad"===u,h=i&&["chrome","chromium","mobile chrome","chrome webview","chrome headless"].includes(i),f=i&&["firefox","mobile firefox","mobile focus"].includes(i),m=i&&["safari","mobile safari"].includes(i),g=i&&["edge"].includes(i);if((h||g)&&!p&&n>=111)return"Chrome111";if(h&&!p&&n>=74||g&&!p&&n>=88)return"Chrome74";if(h&&!p&&n>=70)return"Chrome70";if(h&&!p&&n>=67)return"Chrome67";if(h&&!p&&n>=55)return"Chrome55";if(f&&!p&&n>=120)return"Firefox120";if(f&&!p&&n>=60)return"Firefox60";if(f&&p&&d>=14.3)return"Safari12";if(m&&n>=12&&"undefined"!=typeof RTCRtpTransceiver&&RTCRtpTransceiver.prototype.hasOwnProperty("currentDirection"))return"Safari12";if(m&&n>=11)return"Safari11";if(g&&!p&&n>=11&&n<=18)return"Edge11";if("webkit"===o&&p&&"undefined"!=typeof RTCRtpTransceiver&&RTCRtpTransceiver.prototype.hasOwnProperty("currentDirection"))return"Safari12";if("blink"===o){const t=e.match(/(?:(?:Chrome|Chromium))[ /](\w+)/i);if(t){const e=Number(t[1]);return e>=111?"Chrome111":e>=74?"Chrome74":e>=70?"Chrome70":e>=67?"Chrome67":"Chrome55"}return"Chrome111"}Ep.warn("detectDevice() | browser not supported [name:%s, version:%s]",i,n)}else Ep.warn("detectDevice() | unknown device")}rs.Device=class{constructor({handlerName:e,handlerFactory:t}={}){if(this._loaded=!1,this._observer=new pp.EnhancedEventEmitter,Ep.debug("constructor()"),e&&t)throw new TypeError("just one of handlerName or handlerInterface can be given");if(t)this._handlerFactory=t;else{if(e)Ep.debug("constructor() | handler given: %s",e);else{if(!(e=Dp()))throw new hp.UnsupportedError("device not supported");Ep.debug("constructor() | detected handler: %s",e)}switch(e){case"Chrome111":this._handlerFactory=vp.Chrome111.createFactory();break;case"Chrome74":this._handlerFactory=bp.Chrome74.createFactory();break;case"Chrome70":this._handlerFactory=yp.Chrome70.createFactory();break;case"Chrome67":this._handlerFactory=wp.Chrome67.createFactory();break;case"Chrome55":this._handlerFactory=_p.Chrome55.createFactory();break;case"Firefox120":this._handlerFactory=Sp.Firefox120.createFactory();break;case"Firefox60":this._handlerFactory=Cp.Firefox60.createFactory();break;case"Safari12":this._handlerFactory=Rp.Safari12.createFactory();break;case"Safari11":this._handlerFactory=kp.Safari11.createFactory();break;case"Edge11":this._handlerFactory=Tp.Edge11.createFactory();break;case"ReactNativeUnifiedPlan":this._handlerFactory=Pp.ReactNativeUnifiedPlan.createFactory();break;case"ReactNative":this._handlerFactory=Op.ReactNative.createFactory();break;default:throw new TypeError(`unknown handlerName "${e}"`)}}const r=this._handlerFactory();this._handlerName=r.name,r.close(),this._extendedRtpCapabilities=void 0,this._recvRtpCapabilities=void 0,this._canProduceByKind={audio:!1,video:!1},this._sctpCapabilities=void 0}get handlerName(){return this._handlerName}get loaded(){return this._loaded}get rtpCapabilities(){if(!this._loaded)throw new hp.InvalidStateError("not loaded");return this._recvRtpCapabilities}get sctpCapabilities(){if(!this._loaded)throw new hp.InvalidStateError("not loaded");return this._sctpCapabilities}get observer(){return this._observer}async load({routerRtpCapabilities:e}){let t;Ep.debug("load() [routerRtpCapabilities:%o]",e);try{if(this._loaded)throw new hp.InvalidStateError("already loaded");const r=fp.clone(e);mp.validateRtpCapabilities(r),t=this._handlerFactory();const i=await t.getNativeRtpCapabilities();Ep.debug("load() | got native RTP capabilities:%o",i);const n=fp.clone(i);mp.validateRtpCapabilities(n),this._extendedRtpCapabilities=mp.getExtendedRtpCapabilities(n,r),Ep.debug("load() | got extended RTP capabilities:%o",this._extendedRtpCapabilities),this._canProduceByKind.audio=mp.canSend("audio",this._extendedRtpCapabilities),this._canProduceByKind.video=mp.canSend("video",this._extendedRtpCapabilities),this._recvRtpCapabilities=mp.getRecvRtpCapabilities(this._extendedRtpCapabilities),mp.validateRtpCapabilities(this._recvRtpCapabilities),Ep.debug("load() | got receiving RTP capabilities:%o",this._recvRtpCapabilities),this._sctpCapabilities=await t.getNativeSctpCapabilities(),Ep.debug("load() | got native SCTP capabilities:%o",this._sctpCapabilities),mp.validateSctpCapabilities(this._sctpCapabilities),Ep.debug("load() succeeded"),this._loaded=!0,t.close()}catch(e){throw t&&t.close(),e}}canProduce(e){if(!this._loaded)throw new hp.InvalidStateError("not loaded");if("audio"!==e&&"video"!==e)throw new TypeError(`invalid kind "${e}"`);return this._canProduceByKind[e]}createSendTransport({id:e,iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,appData:d}){return Ep.debug("createSendTransport()"),this.createTransport({direction:"send",id:e,iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,appData:d})}createRecvTransport({id:e,iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,appData:d}){return Ep.debug("createRecvTransport()"),this.createTransport({direction:"recv",id:e,iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,appData:d})}createTransport({direction:e,id:t,iceParameters:r,iceCandidates:i,dtlsParameters:n,sctpParameters:s,iceServers:o,iceTransportPolicy:a,additionalSettings:c,proprietaryConstraints:d,appData:l}){if(!this._loaded)throw new hp.InvalidStateError("not loaded");if("string"!=typeof t)throw new TypeError("missing id");if("object"!=typeof r)throw new TypeError("missing iceParameters");if(!Array.isArray(i))throw new TypeError("missing iceCandidates");if("object"!=typeof n)throw new TypeError("missing dtlsParameters");if(s&&"object"!=typeof s)throw new TypeError("wrong sctpParameters");if(l&&"object"!=typeof l)throw new TypeError("if given, appData must be an object");const u=new gp.Transport({direction:e,id:t,iceParameters:r,iceCandidates:i,dtlsParameters:n,sctpParameters:s,iceServers:o,iceTransportPolicy:a,additionalSettings:c,proprietaryConstraints:d,appData:l,handlerFactory:this._handlerFactory,extendedRtpCapabilities:this._extendedRtpCapabilities,canProduceByKind:this._canProduceByKind});return this._observer.safeEmit("newtransport",u),u}};var Ip={},xp={};Object.defineProperty(xp,"__esModule",{value:!0});var Mp={};Object.defineProperty(Mp,"__esModule",{value:!0}),function(e){var t=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),r=a&&a.__exportStar||function(e,r){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(r,i)||t(r,e,i)};Object.defineProperty(e,"__esModule",{value:!0}),r(rs,e),r(xo,e),r(Uo,e),r(Wo,e),r(Zo,e),r(ia,e),r(xp,e),r(Mp,e),r(Za,e),r(Is,e)}(Ip),function(e){var t=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),r=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),i=a&&a.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},e(t)};return function(i){if(i&&i.__esModule)return i;var n={};if(null!=i)for(var s=e(i),o=0;o<s.length;o++)"default"!==s[o]&&t(n,i,s[o]);return r(n,i),n}}(),n=a&&a.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(e,"__esModule",{value:!0}),e.debug=e.parseScalabilityMode=e.detectDevice=e.Device=e.version=e.types=void 0;const s=n(ts);e.debug=s.default;const o=rs;Object.defineProperty(e,"Device",{enumerable:!0,get:function(){return o.Device}}),Object.defineProperty(e,"detectDevice",{enumerable:!0,get:function(){return o.detectDevice}});const c=i(Ip);e.types=c,e.version="3.7.18";var d=bc;Object.defineProperty(e,"parseScalabilityMode",{enumerable:!0,get:function(){return d.parse}})}(Qn);var jp={exports:{}};!function(e,t){!function(r,i){var n="function",s="undefined",o="object",a="string",c="major",d="model",l="name",u="type",p="vendor",h="version",f="architecture",m="console",g="mobile",v="tablet",b="smarttv",y="wearable",w="embedded",_="Amazon",S="Apple",C="ASUS",R="BlackBerry",k="Browser",T="Chrome",P="Firefox",O="Google",E="Huawei",D="LG",I="Microsoft",x="Motorola",M="Opera",j="Samsung",L="Sharp",A="Sony",N="Xiaomi",B="Zebra",F="Facebook",z="Chromium OS",V="Mac OS",U=" Browser",$=function(e){for(var t={},r=0;r<e.length;r++)t[e[r].toUpperCase()]=e[r];return t},G=function(e,t){return typeof e===a&&-1!==q(t).indexOf(q(e))},q=function(e){return e.toLowerCase()},H=function(e,t){if(typeof e===a)return e=e.replace(/^\s\s*/,""),typeof t===s?e:e.substring(0,500)},W=function(e,t){for(var r,s,a,c,d,l,u=0;u<t.length&&!d;){var p=t[u],h=t[u+1];for(r=s=0;r<p.length&&!d&&p[r];)if(d=p[r++].exec(e))for(a=0;a<h.length;a++)l=d[++s],typeof(c=h[a])===o&&c.length>0?2===c.length?typeof c[1]==n?this[c[0]]=c[1].call(this,l):this[c[0]]=c[1]:3===c.length?typeof c[1]!==n||c[1].exec&&c[1].test?this[c[0]]=l?l.replace(c[1],c[2]):i:this[c[0]]=l?c[1].call(this,l,c[2]):i:4===c.length&&(this[c[0]]=l?c[3].call(this,l.replace(c[1],c[2])):i):this[c]=l||i;u+=2}},K=function(e,t){for(var r in t)if(typeof t[r]===o&&t[r].length>0){for(var n=0;n<t[r].length;n++)if(G(t[r][n],e))return"?"===r?i:r}else if(G(t[r],e))return"?"===r?i:r;return t.hasOwnProperty("*")?t["*"]:e},J={ME:"4.90","NT 3.11":"NT3.51","NT 4.0":"NT4.0",2e3:"NT 5.0",XP:["NT 5.1","NT 5.2"],Vista:"NT 6.0",7:"NT 6.1",8:"NT 6.2",8.1:"NT 6.3",10:["NT 6.4","NT 10.0"],RT:"ARM"},X={browser:[[/\b(?:crmo|crios)\/([\w\.]+)/i],[h,[l,"Chrome"]],[/edg(?:e|ios|a)?\/([\w\.]+)/i],[h,[l,"Edge"]],[/(opera mini)\/([-\w\.]+)/i,/(opera [mobiletab]{3,6})\b.+version\/([-\w\.]+)/i,/(opera)(?:.+version\/|[\/ ]+)([\w\.]+)/i],[l,h],[/opios[\/ ]+([\w\.]+)/i],[h,[l,M+" Mini"]],[/\bop(?:rg)?x\/([\w\.]+)/i],[h,[l,M+" GX"]],[/\bopr\/([\w\.]+)/i],[h,[l,M]],[/\bb[ai]*d(?:uhd|[ub]*[aekoprswx]{5,6})[\/ ]?([\w\.]+)/i],[h,[l,"Baidu"]],[/\b(?:mxbrowser|mxios|myie2)\/?([-\w\.]*)\b/i],[h,[l,"Maxthon"]],[/(kindle)\/([\w\.]+)/i,/(lunascape|maxthon|netfront|jasmine|blazer|sleipnir)[\/ ]?([\w\.]*)/i,/(avant|iemobile|slim(?:browser|boat|jet))[\/ ]?([\d\.]*)/i,/(?:ms|\()(ie) ([\w\.]+)/i,/(flock|rockmelt|midori|epiphany|silk|skyfire|ovibrowser|bolt|iron|vivaldi|iridium|phantomjs|bowser|qupzilla|falkon|rekonq|puffin|brave|whale(?!.+naver)|qqbrowserlite|duckduckgo|klar|helio|(?=comodo_)?dragon)\/([-\w\.]+)/i,/(heytap|ovi|115)browser\/([\d\.]+)/i,/(weibo)__([\d\.]+)/i],[l,h],[/quark(?:pc)?\/([-\w\.]+)/i],[h,[l,"Quark"]],[/\bddg\/([\w\.]+)/i],[h,[l,"DuckDuckGo"]],[/(?:\buc? ?browser|(?:juc.+)ucweb)[\/ ]?([\w\.]+)/i],[h,[l,"UC"+k]],[/microm.+\bqbcore\/([\w\.]+)/i,/\bqbcore\/([\w\.]+).+microm/i,/micromessenger\/([\w\.]+)/i],[h,[l,"WeChat"]],[/konqueror\/([\w\.]+)/i],[h,[l,"Konqueror"]],[/trident.+rv[: ]([\w\.]{1,9})\b.+like gecko/i],[h,[l,"IE"]],[/ya(?:search)?browser\/([\w\.]+)/i],[h,[l,"Yandex"]],[/slbrowser\/([\w\.]+)/i],[h,[l,"Smart Lenovo "+k]],[/(avast|avg)\/([\w\.]+)/i],[[l,/(.+)/,"$1 Secure "+k],h],[/\bfocus\/([\w\.]+)/i],[h,[l,P+" Focus"]],[/\bopt\/([\w\.]+)/i],[h,[l,M+" Touch"]],[/coc_coc\w+\/([\w\.]+)/i],[h,[l,"Coc Coc"]],[/dolfin\/([\w\.]+)/i],[h,[l,"Dolphin"]],[/coast\/([\w\.]+)/i],[h,[l,M+" Coast"]],[/miuibrowser\/([\w\.]+)/i],[h,[l,"MIUI"+U]],[/fxios\/([\w\.-]+)/i],[h,[l,P]],[/\bqihoobrowser\/?([\w\.]*)/i],[h,[l,"360"]],[/\b(qq)\/([\w\.]+)/i],[[l,/(.+)/,"$1Browser"],h],[/(oculus|sailfish|huawei|vivo|pico)browser\/([\w\.]+)/i],[[l,/(.+)/,"$1"+U],h],[/samsungbrowser\/([\w\.]+)/i],[h,[l,j+" Internet"]],[/metasr[\/ ]?([\d\.]+)/i],[h,[l,"Sogou Explorer"]],[/(sogou)mo\w+\/([\d\.]+)/i],[[l,"Sogou Mobile"],h],[/(electron)\/([\w\.]+) safari/i,/(tesla)(?: qtcarbrowser|\/(20\d\d\.[-\w\.]+))/i,/m?(qqbrowser|2345(?=browser|chrome|explorer))\w*[\/ ]?v?([\w\.]+)/i],[l,h],[/(lbbrowser|rekonq)/i,/\[(linkedin)app\]/i],[l],[/ome\/([\w\.]+) \w* ?(iron) saf/i,/ome\/([\w\.]+).+qihu (360)[es]e/i],[h,l],[/((?:fban\/fbios|fb_iab\/fb4a)(?!.+fbav)|;fbav\/([\w\.]+);)/i],[[l,F],h],[/(Klarna)\/([\w\.]+)/i,/(kakao(?:talk|story))[\/ ]([\w\.]+)/i,/(naver)\(.*?(\d+\.[\w\.]+).*\)/i,/safari (line)\/([\w\.]+)/i,/\b(line)\/([\w\.]+)\/iab/i,/(alipay)client\/([\w\.]+)/i,/(twitter)(?:and| f.+e\/([\w\.]+))/i,/(chromium|instagram|snapchat)[\/ ]([-\w\.]+)/i],[l,h],[/\bgsa\/([\w\.]+) .*safari\//i],[h,[l,"GSA"]],[/musical_ly(?:.+app_?version\/|_)([\w\.]+)/i],[h,[l,"TikTok"]],[/headlesschrome(?:\/([\w\.]+)| )/i],[h,[l,T+" Headless"]],[/ wv\).+(chrome)\/([\w\.]+)/i],[[l,T+" WebView"],h],[/droid.+ version\/([\w\.]+)\b.+(?:mobile safari|safari)/i],[h,[l,"Android "+k]],[/(chrome|omniweb|arora|[tizenoka]{5} ?browser)\/v?([\w\.]+)/i],[l,h],[/version\/([\w\.\,]+) .*mobile\/\w+ (safari)/i],[h,[l,"Mobile Safari"]],[/version\/([\w(\.|\,)]+) .*(mobile ?safari|safari)/i],[h,l],[/webkit.+?(mobile ?safari|safari)(\/[\w\.]+)/i],[l,[h,K,{"1.0":"/8",1.2:"/1",1.3:"/3","2.0":"/412","2.0.2":"/416","2.0.3":"/417","2.0.4":"/419","?":"/"}]],[/(webkit|khtml)\/([\w\.]+)/i],[l,h],[/(navigator|netscape\d?)\/([-\w\.]+)/i],[[l,"Netscape"],h],[/(wolvic|librewolf)\/([\w\.]+)/i],[l,h],[/mobile vr; rv:([\w\.]+)\).+firefox/i],[h,[l,P+" Reality"]],[/ekiohf.+(flow)\/([\w\.]+)/i,/(swiftfox)/i,/(icedragon|iceweasel|camino|chimera|fennec|maemo browser|minimo|conkeror)[\/ ]?([\w\.\+]+)/i,/(seamonkey|k-meleon|icecat|iceape|firebird|phoenix|palemoon|basilisk|waterfox)\/([-\w\.]+)$/i,/(firefox)\/([\w\.]+)/i,/(mozilla)\/([\w\.]+) .+rv\:.+gecko\/\d+/i,/(polaris|lynx|dillo|icab|doris|amaya|w3m|netsurf|obigo|mosaic|(?:go|ice|up)[\. ]?browser)[-\/ ]?v?([\w\.]+)/i,/(links) \(([\w\.]+)/i],[l,[h,/_/g,"."]],[/(cobalt)\/([\w\.]+)/i],[l,[h,/master.|lts./,""]]],cpu:[[/(?:(amd|x(?:(?:86|64)[-_])?|wow|win)64)[;\)]/i],[[f,"amd64"]],[/(ia32(?=;))/i],[[f,q]],[/((?:i[346]|x)86)[;\)]/i],[[f,"ia32"]],[/\b(aarch64|arm(v?8e?l?|_?64))\b/i],[[f,"arm64"]],[/\b(arm(?:v[67])?ht?n?[fl]p?)\b/i],[[f,"armhf"]],[/windows (ce|mobile); ppc;/i],[[f,"arm"]],[/((?:ppc|powerpc)(?:64)?)(?: mac|;|\))/i],[[f,/ower/,"",q]],[/(sun4\w)[;\)]/i],[[f,"sparc"]],[/((?:avr32|ia64(?=;))|68k(?=\))|\barm(?=v(?:[1-7]|[5-7]1)l?|;|eabi)|(?=atmel )avr|(?:irix|mips|sparc)(?:64)?\b|pa-risc)/i],[[f,q]]],device:[[/\b(sch-i[89]0\d|shw-m380s|sm-[ptx]\w{2,4}|gt-[pn]\d{2,4}|sgh-t8[56]9|nexus 10)/i],[d,[p,j],[u,v]],[/\b((?:s[cgp]h|gt|sm)-(?![lr])\w+|sc[g-]?[\d]+a?|galaxy nexus)/i,/samsung[- ]((?!sm-[lr])[-\w]+)/i,/sec-(sgh\w+)/i],[d,[p,j],[u,g]],[/(?:\/|\()(ip(?:hone|od)[\w, ]*)(?:\/|;)/i],[d,[p,S],[u,g]],[/\((ipad);[-\w\),; ]+apple/i,/applecoremedia\/[\w\.]+ \((ipad)/i,/\b(ipad)\d\d?,\d\d?[;\]].+ios/i],[d,[p,S],[u,v]],[/(macintosh);/i],[d,[p,S]],[/\b(sh-?[altvz]?\d\d[a-ekm]?)/i],[d,[p,L],[u,g]],[/(?:honor)([-\w ]+)[;\)]/i],[d,[p,"Honor"],[u,g]],[/\b((?:ag[rs][23]?|bah2?|sht?|btv)-a?[lw]\d{2})\b(?!.+d\/s)/i],[d,[p,E],[u,v]],[/(?:huawei)([-\w ]+)[;\)]/i,/\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][012359c][adn]?)\b(?!.+d\/s)/i],[d,[p,E],[u,g]],[/\b(poco[\w ]+|m2\d{3}j\d\d[a-z]{2})(?: bui|\))/i,/\b; (\w+) build\/hm\1/i,/\b(hm[-_ ]?note?[_ ]?(?:\d\w)?) bui/i,/\b(redmi[\-_ ]?(?:note|k)?[\w_ ]+)(?: bui|\))/i,/oid[^\)]+; (m?[12][0-389][01]\w{3,6}[c-y])( bui|; wv|\))/i,/\b(mi[-_ ]?(?:a\d|one|one[_ ]plus|note lte|max|cc)?[_ ]?(?:\d?\w?)[_ ]?(?:plus|se|lite|pro)?)(?: bui|\))/i],[[d,/_/g," "],[p,N],[u,g]],[/oid[^\)]+; (2\d{4}(283|rpbf)[cgl])( bui|\))/i,/\b(mi[-_ ]?(?:pad)(?:[\w_ ]+))(?: bui|\))/i],[[d,/_/g," "],[p,N],[u,v]],[/; (\w+) bui.+ oppo/i,/\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i],[d,[p,"OPPO"],[u,g]],[/\b(opd2\d{3}a?) bui/i],[d,[p,"OPPO"],[u,v]],[/vivo (\w+)(?: bui|\))/i,/\b(v[12]\d{3}\w?[at])(?: bui|;)/i],[d,[p,"Vivo"],[u,g]],[/\b(rmx[1-3]\d{3})(?: bui|;|\))/i],[d,[p,"Realme"],[u,g]],[/\b(milestone|droid(?:[2-4x]| (?:bionic|x2|pro|razr))?:?( 4g)?)\b[\w ]+build\//i,/\bmot(?:orola)?[- ](\w*)/i,/((?:moto[\w\(\) ]+|xt\d{3,4}|nexus 6)(?= bui|\)))/i],[d,[p,x],[u,g]],[/\b(mz60\d|xoom[2 ]{0,2}) build\//i],[d,[p,x],[u,v]],[/((?=lg)?[vl]k\-?\d{3}) bui| 3\.[-\w; ]{10}lg?-([06cv9]{3,4})/i],[d,[p,D],[u,v]],[/(lm(?:-?f100[nv]?|-[\w\.]+)(?= bui|\))|nexus [45])/i,/\blg[-e;\/ ]+((?!browser|netcast|android tv)\w+)/i,/\blg-?([\d\w]+) bui/i],[d,[p,D],[u,g]],[/(ideatab[-\w ]+)/i,/lenovo ?(s[56]000[-\w]+|tab(?:[\w ]+)|yt[-\d\w]{6}|tb[-\d\w]{6})/i],[d,[p,"Lenovo"],[u,v]],[/(?:maemo|nokia).*(n900|lumia \d+)/i,/nokia[-_ ]?([-\w\.]*)/i],[[d,/_/g," "],[p,"Nokia"],[u,g]],[/(pixel c)\b/i],[d,[p,O],[u,v]],[/droid.+; (pixel[\daxl ]{0,6})(?: bui|\))/i],[d,[p,O],[u,g]],[/droid.+; (a?\d[0-2]{2}so|[c-g]\d{4}|so[-gl]\w+|xq-a\w[4-7][12])(?= bui|\).+chrome\/(?![1-6]{0,1}\d\.))/i],[d,[p,A],[u,g]],[/sony tablet [ps]/i,/\b(?:sony)?sgp\w+(?: bui|\))/i],[[d,"Xperia Tablet"],[p,A],[u,v]],[/ (kb2005|in20[12]5|be20[12][59])\b/i,/(?:one)?(?:plus)? (a\d0\d\d)(?: b|\))/i],[d,[p,"OnePlus"],[u,g]],[/(alexa)webm/i,/(kf[a-z]{2}wi|aeo(?!bc)\w\w)( bui|\))/i,/(kf[a-z]+)( bui|\)).+silk\//i],[d,[p,_],[u,v]],[/((?:sd|kf)[0349hijorstuw]+)( bui|\)).+silk\//i],[[d,/(.+)/g,"Fire Phone $1"],[p,_],[u,g]],[/(playbook);[-\w\),; ]+(rim)/i],[d,p,[u,v]],[/\b((?:bb[a-f]|st[hv])100-\d)/i,/\(bb10; (\w+)/i],[d,[p,R],[u,g]],[/(?:\b|asus_)(transfo[prime ]{4,10} \w+|eeepc|slider \w+|nexus 7|padfone|p00[cj])/i],[d,[p,C],[u,v]],[/ (z[bes]6[027][012][km][ls]|zenfone \d\w?)\b/i],[d,[p,C],[u,g]],[/(nexus 9)/i],[d,[p,"HTC"],[u,v]],[/(htc)[-;_ ]{1,2}([\w ]+(?=\)| bui)|\w+)/i,/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,/(alcatel|geeksphone|nexian|panasonic(?!(?:;|\.))|sony(?!-bra))[-_ ]?([-\w]*)/i],[p,[d,/_/g," "],[u,g]],[/droid [\w\.]+; ((?:8[14]9[16]|9(?:0(?:48|60|8[01])|1(?:3[27]|66)|2(?:6[69]|9[56])|466))[gqswx])\w*(\)| bui)/i],[d,[p,"TCL"],[u,v]],[/(itel) ((\w+))/i],[[p,q],d,[u,K,{tablet:["p10001l","w7001"],"*":"mobile"}]],[/droid.+; ([ab][1-7]-?[0178a]\d\d?)/i],[d,[p,"Acer"],[u,v]],[/droid.+; (m[1-5] note) bui/i,/\bmz-([-\w]{2,})/i],[d,[p,"Meizu"],[u,g]],[/; ((?:power )?armor(?:[\w ]{0,8}))(?: bui|\))/i],[d,[p,"Ulefone"],[u,g]],[/; (energy ?\w+)(?: bui|\))/i,/; energizer ([\w ]+)(?: bui|\))/i],[d,[p,"Energizer"],[u,g]],[/; cat (b35);/i,/; (b15q?|s22 flip|s48c|s62 pro)(?: bui|\))/i],[d,[p,"Cat"],[u,g]],[/((?:new )?andromax[\w- ]+)(?: bui|\))/i],[d,[p,"Smartfren"],[u,g]],[/droid.+; (a(?:015|06[35]|142p?))/i],[d,[p,"Nothing"],[u,g]],[/(blackberry|benq|palm(?=\-)|sonyericsson|acer|asus|dell|meizu|motorola|polytron|infinix|tecno|micromax|advan)[-_ ]?([-\w]*)/i,/; (imo) ((?!tab)[\w ]+?)(?: bui|\))/i,/(hp) ([\w ]+\w)/i,/(asus)-?(\w+)/i,/(microsoft); (lumia[\w ]+)/i,/(lenovo)[-_ ]?([-\w]+)/i,/(jolla)/i,/(oppo) ?([\w ]+) bui/i],[p,d,[u,g]],[/(imo) (tab \w+)/i,/(kobo)\s(ereader|touch)/i,/(archos) (gamepad2?)/i,/(hp).+(touchpad(?!.+tablet)|tablet)/i,/(kindle)\/([\w\.]+)/i,/(nook)[\w ]+build\/(\w+)/i,/(dell) (strea[kpr\d ]*[\dko])/i,/(le[- ]+pan)[- ]+(\w{1,9}) bui/i,/(trinity)[- ]*(t\d{3}) bui/i,/(gigaset)[- ]+(q\w{1,9}) bui/i,/(vodafone) ([\w ]+)(?:\)| bui)/i],[p,d,[u,v]],[/(surface duo)/i],[d,[p,I],[u,v]],[/droid [\d\.]+; (fp\du?)(?: b|\))/i],[d,[p,"Fairphone"],[u,g]],[/(u304aa)/i],[d,[p,"AT&T"],[u,g]],[/\bsie-(\w*)/i],[d,[p,"Siemens"],[u,g]],[/\b(rct\w+) b/i],[d,[p,"RCA"],[u,v]],[/\b(venue[\d ]{2,7}) b/i],[d,[p,"Dell"],[u,v]],[/\b(q(?:mv|ta)\w+) b/i],[d,[p,"Verizon"],[u,v]],[/\b(?:barnes[& ]+noble |bn[rt])([\w\+ ]*) b/i],[d,[p,"Barnes & Noble"],[u,v]],[/\b(tm\d{3}\w+) b/i],[d,[p,"NuVision"],[u,v]],[/\b(k88) b/i],[d,[p,"ZTE"],[u,v]],[/\b(nx\d{3}j) b/i],[d,[p,"ZTE"],[u,g]],[/\b(gen\d{3}) b.+49h/i],[d,[p,"Swiss"],[u,g]],[/\b(zur\d{3}) b/i],[d,[p,"Swiss"],[u,v]],[/\b((zeki)?tb.*\b) b/i],[d,[p,"Zeki"],[u,v]],[/\b([yr]\d{2}) b/i,/\b(dragon[- ]+touch |dt)(\w{5}) b/i],[[p,"Dragon Touch"],d,[u,v]],[/\b(ns-?\w{0,9}) b/i],[d,[p,"Insignia"],[u,v]],[/\b((nxa|next)-?\w{0,9}) b/i],[d,[p,"NextBook"],[u,v]],[/\b(xtreme\_)?(v(1[045]|2[015]|[3469]0|7[05])) b/i],[[p,"Voice"],d,[u,g]],[/\b(lvtel\-)?(v1[12]) b/i],[[p,"LvTel"],d,[u,g]],[/\b(ph-1) /i],[d,[p,"Essential"],[u,g]],[/\b(v(100md|700na|7011|917g).*\b) b/i],[d,[p,"Envizen"],[u,v]],[/\b(trio[-\w\. ]+) b/i],[d,[p,"MachSpeed"],[u,v]],[/\btu_(1491) b/i],[d,[p,"Rotor"],[u,v]],[/(shield[\w ]+) b/i],[d,[p,"Nvidia"],[u,v]],[/(sprint) (\w+)/i],[p,d,[u,g]],[/(kin\.[onetw]{3})/i],[[d,/\./g," "],[p,I],[u,g]],[/droid.+; (cc6666?|et5[16]|mc[239][23]x?|vc8[03]x?)\)/i],[d,[p,B],[u,v]],[/droid.+; (ec30|ps20|tc[2-8]\d[kx])\)/i],[d,[p,B],[u,g]],[/smart-tv.+(samsung)/i],[p,[u,b]],[/hbbtv.+maple;(\d+)/i],[[d,/^/,"SmartTV"],[p,j],[u,b]],[/(nux; netcast.+smarttv|lg (netcast\.tv-201\d|android tv))/i],[[p,D],[u,b]],[/(apple) ?tv/i],[p,[d,S+" TV"],[u,b]],[/crkey/i],[[d,T+"cast"],[p,O],[u,b]],[/droid.+aft(\w+)( bui|\))/i],[d,[p,_],[u,b]],[/\(dtv[\);].+(aquos)/i,/(aquos-tv[\w ]+)\)/i],[d,[p,L],[u,b]],[/(bravia[\w ]+)( bui|\))/i],[d,[p,A],[u,b]],[/(mitv-\w{5}) bui/i],[d,[p,N],[u,b]],[/Hbbtv.*(technisat) (.*);/i],[p,d,[u,b]],[/\b(roku)[\dx]*[\)\/]((?:dvp-)?[\d\.]*)/i,/hbbtv\/\d+\.\d+\.\d+ +\([\w\+ ]*; *([\w\d][^;]*);([^;]*)/i],[[p,H],[d,H],[u,b]],[/\b(android tv|smart[- ]?tv|opera tv|tv; rv:)\b/i],[[u,b]],[/(ouya)/i,/(nintendo) ([wids3utch]+)/i],[p,d,[u,m]],[/droid.+; (shield) bui/i],[d,[p,"Nvidia"],[u,m]],[/(playstation [345portablevi]+)/i],[d,[p,A],[u,m]],[/\b(xbox(?: one)?(?!; xbox))[\); ]/i],[d,[p,I],[u,m]],[/\b(sm-[lr]\d\d[05][fnuw]?s?)\b/i],[d,[p,j],[u,y]],[/((pebble))app/i],[p,d,[u,y]],[/(watch)(?: ?os[,\/]|\d,\d\/)[\d\.]+/i],[d,[p,S],[u,y]],[/droid.+; (glass) \d/i],[d,[p,O],[u,y]],[/droid.+; (wt63?0{2,3})\)/i],[d,[p,B],[u,y]],[/droid.+; (glass) \d/i],[d,[p,O],[u,y]],[/(pico) (4|neo3(?: link|pro)?)/i],[p,d,[u,y]],[/; (quest( \d| pro)?)/i],[d,[p,F],[u,y]],[/(tesla)(?: qtcarbrowser|\/[-\w\.]+)/i],[p,[u,w]],[/(aeobc)\b/i],[d,[p,_],[u,w]],[/droid .+?; ([^;]+?)(?: bui|; wv\)|\) applew).+? mobile safari/i],[d,[u,g]],[/droid .+?; ([^;]+?)(?: bui|\) applew).+?(?! mobile) safari/i],[d,[u,v]],[/\b((tablet|tab)[;\/]|focus\/\d(?!.+mobile))/i],[[u,v]],[/(phone|mobile(?:[;\/]| [ \w\/\.]*safari)|pda(?=.+windows ce))/i],[[u,g]],[/(android[-\w\. ]{0,9});.+buil/i],[d,[p,"Generic"]]],engine:[[/windows.+ edge\/([\w\.]+)/i],[h,[l,"EdgeHTML"]],[/(arkweb)\/([\w\.]+)/i],[l,h],[/webkit\/537\.36.+chrome\/(?!27)([\w\.]+)/i],[h,[l,"Blink"]],[/(presto)\/([\w\.]+)/i,/(webkit|trident|netfront|netsurf|amaya|lynx|w3m|goanna|servo)\/([\w\.]+)/i,/ekioh(flow)\/([\w\.]+)/i,/(khtml|tasman|links)[\/ ]\(?([\w\.]+)/i,/(icab)[\/ ]([23]\.[\d\.]+)/i,/\b(libweb)/i],[l,h],[/rv\:([\w\.]{1,9})\b.+(gecko)/i],[h,l]],os:[[/microsoft (windows) (vista|xp)/i],[l,h],[/(windows (?:phone(?: os)?|mobile))[\/ ]?([\d\.\w ]*)/i],[l,[h,K,J]],[/windows nt 6\.2; (arm)/i,/windows[\/ ]?([ntce\d\. ]+\w)(?!.+xbox)/i,/(?:win(?=3|9|n)|win 9x )([nt\d\.]+)/i],[[h,K,J],[l,"Windows"]],[/ip[honead]{2,4}\b(?:.*os ([\w]+) like mac|; opera)/i,/(?:ios;fbsv\/|iphone.+ios[\/ ])([\d\.]+)/i,/cfnetwork\/.+darwin/i],[[h,/_/g,"."],[l,"iOS"]],[/(mac os x) ?([\w\. ]*)/i,/(macintosh|mac_powerpc\b)(?!.+haiku)/i],[[l,V],[h,/_/g,"."]],[/droid ([\w\.]+)\b.+(android[- ]x86|harmonyos)/i],[h,l],[/(android|webos|qnx|bada|rim tablet os|maemo|meego|sailfish|openharmony)[-\/ ]?([\w\.]*)/i,/(blackberry)\w*\/([\w\.]*)/i,/(tizen|kaios)[\/ ]([\w\.]+)/i,/\((series40);/i],[l,h],[/\(bb(10);/i],[h,[l,R]],[/(?:symbian ?os|symbos|s60(?=;)|series60)[-\/ ]?([\w\.]*)/i],[h,[l,"Symbian"]],[/mozilla\/[\d\.]+ \((?:mobile|tablet|tv|mobile; [\w ]+); rv:.+ gecko\/([\w\.]+)/i],[h,[l,P+" OS"]],[/web0s;.+rt(tv)/i,/\b(?:hp)?wos(?:browser)?\/([\w\.]+)/i],[h,[l,"webOS"]],[/watch(?: ?os[,\/]|\d,\d\/)([\d\.]+)/i],[h,[l,"watchOS"]],[/crkey\/([\d\.]+)/i],[h,[l,T+"cast"]],[/(cros) [\w]+(?:\)| ([\w\.]+)\b)/i],[[l,z],h],[/panasonic;(viera)/i,/(netrange)mmh/i,/(nettv)\/(\d+\.[\w\.]+)/i,/(nintendo|playstation) ([wids345portablevuch]+)/i,/(xbox); +xbox ([^\);]+)/i,/\b(joli|palm)\b ?(?:os)?\/?([\w\.]*)/i,/(mint)[\/\(\) ]?(\w*)/i,/(mageia|vectorlinux)[; ]/i,/([kxln]?ubuntu|debian|suse|opensuse|gentoo|arch(?= linux)|slackware|fedora|mandriva|centos|pclinuxos|red ?hat|zenwalk|linpus|raspbian|plan 9|minix|risc os|contiki|deepin|manjaro|elementary os|sabayon|linspire)(?: gnu\/linux)?(?: enterprise)?(?:[- ]linux)?(?:-gnu)?[-\/ ]?(?!chrom|package)([-\w\.]*)/i,/(hurd|linux) ?([\w\.]*)/i,/(gnu) ?([\w\.]*)/i,/\b([-frentopcghs]{0,5}bsd|dragonfly)[\/ ]?(?!amd|[ix346]{1,2}86)([\w\.]*)/i,/(haiku) (\w+)/i],[l,h],[/(sunos) ?([\w\.\d]*)/i],[[l,"Solaris"],h],[/((?:open)?solaris)[-\/ ]?([\w\.]*)/i,/(aix) ((\d)(?=\.|\)| )[\w\.])*/i,/\b(beos|os\/2|amigaos|morphos|openvms|fuchsia|hp-ux|serenityos)/i,/(unix) ?([\w\.]*)/i],[l,h]]},Q=function(e,t){if(typeof e===o&&(t=e,e=i),!(this instanceof Q))return new Q(e,t).getResult();var m=typeof r!==s&&r.navigator?r.navigator:i,b=e||(m&&m.userAgent?m.userAgent:""),y=m&&m.userAgentData?m.userAgentData:i,w=t?function(e,t){var r={};for(var i in e)t[i]&&t[i].length%2==0?r[i]=t[i].concat(e[i]):r[i]=e[i];return r}(X,t):X,_=m&&m.userAgent==b;return this.getBrowser=function(){var e,t={};return t[l]=i,t[h]=i,W.call(t,b,w.browser),t[c]=typeof(e=t[h])===a?e.replace(/[^\d\.]/g,"").split(".")[0]:i,_&&m&&m.brave&&typeof m.brave.isBrave==n&&(t[l]="Brave"),t},this.getCPU=function(){var e={};return e[f]=i,W.call(e,b,w.cpu),e},this.getDevice=function(){var e={};return e[p]=i,e[d]=i,e[u]=i,W.call(e,b,w.device),_&&!e[u]&&y&&y.mobile&&(e[u]=g),_&&"Macintosh"==e[d]&&m&&typeof m.standalone!==s&&m.maxTouchPoints&&m.maxTouchPoints>2&&(e[d]="iPad",e[u]=v),e},this.getEngine=function(){var e={};return e[l]=i,e[h]=i,W.call(e,b,w.engine),e},this.getOS=function(){var e={};return e[l]=i,e[h]=i,W.call(e,b,w.os),_&&!e[l]&&y&&y.platform&&"Unknown"!=y.platform&&(e[l]=y.platform.replace(/chrome os/i,z).replace(/macos/i,V)),e},this.getResult=function(){return{ua:this.getUA(),browser:this.getBrowser(),engine:this.getEngine(),os:this.getOS(),device:this.getDevice(),cpu:this.getCPU()}},this.getUA=function(){return b},this.setUA=function(e){return b=typeof e===a&&e.length>500?H(e,500):e,this},this.setUA(b),this};Q.VERSION="1.0.40",Q.BROWSER=$([l,h,c]),Q.CPU=$([f]),Q.DEVICE=$([d,p,u,m,g,b,v,y,w]),Q.ENGINE=Q.OS=$([l,h]),e.exports&&(t=e.exports=Q),t.UAParser=Q;var Z=typeof r!==s&&(r.jQuery||r.Zepto);if(Z&&!Z.ua){var Y=new Q;Z.ua=Y.getResult(),Z.ua.get=function(){return Y.getUA()},Z.ua.set=function(e){Y.setUA(e);var t=Y.getResult();for(var r in t)Z.ua[r]=t[r]}}}("object"==typeof window?window:a)}(jp,jp.exports);var Lp=jp.exports;function Ap(){}function Np(){Np.init.call(this)}function Bp(e){return void 0===e._maxListeners?Np.defaultMaxListeners:e._maxListeners}function Fp(e,t,r,i){var n,s,o,a;if("function"!=typeof r)throw new TypeError('"listener" argument must be a function');if((s=e._events)?(s.newListener&&(e.emit("newListener",t,r.listener?r.listener:r),s=e._events),o=s[t]):(s=e._events=new Ap,e._eventsCount=0),o){if("function"==typeof o?o=s[t]=i?[r,o]:[o,r]:i?o.unshift(r):o.push(r),!o.warned&&(n=Bp(e))&&n>0&&o.length>n){o.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+t+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=e,c.type=t,c.count=o.length,a=c,"function"==typeof console.warn?console.warn(a):console.log(a)}}else o=s[t]=r,++e._eventsCount;return e}function zp(e,t,r){var i=!1;function n(){e.removeListener(t,n),i||(i=!0,r.apply(e,arguments))}return n.listener=r,n}function Vp(e){var t=this._events;if(t){var r=t[e];if("function"==typeof r)return 1;if(r)return r.length}return 0}function Up(e,t){for(var r=new Array(t);t--;)r[t]=e[t];return r}Ap.prototype=Object.create(null),Np.EventEmitter=Np,Np.usingDomains=!1,Np.prototype.domain=void 0,Np.prototype._events=void 0,Np.prototype._maxListeners=void 0,Np.defaultMaxListeners=10,Np.init=function(){this.domain=null,Np.usingDomains&&undefined.active,this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new Ap,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},Np.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||isNaN(e))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=e,this},Np.prototype.getMaxListeners=function(){return Bp(this)},Np.prototype.emit=function(e){var t,r,i,n,s,o,a,c="error"===e;if(o=this._events)c=c&&null==o.error;else if(!c)return!1;if(a=this.domain,c){if(t=arguments[1],!a){if(t instanceof Error)throw t;var d=new Error('Uncaught, unspecified "error" event. ('+t+")");throw d.context=t,d}return t||(t=new Error('Uncaught, unspecified "error" event')),t.domainEmitter=this,t.domain=a,t.domainThrown=!1,a.emit("error",t),!1}if(!(r=o[e]))return!1;var l="function"==typeof r;switch(i=arguments.length){case 1:!function(e,t,r){if(t)e.call(r);else for(var i=e.length,n=Up(e,i),s=0;s<i;++s)n[s].call(r)}(r,l,this);break;case 2:!function(e,t,r,i){if(t)e.call(r,i);else for(var n=e.length,s=Up(e,n),o=0;o<n;++o)s[o].call(r,i)}(r,l,this,arguments[1]);break;case 3:!function(e,t,r,i,n){if(t)e.call(r,i,n);else for(var s=e.length,o=Up(e,s),a=0;a<s;++a)o[a].call(r,i,n)}(r,l,this,arguments[1],arguments[2]);break;case 4:!function(e,t,r,i,n,s){if(t)e.call(r,i,n,s);else for(var o=e.length,a=Up(e,o),c=0;c<o;++c)a[c].call(r,i,n,s)}(r,l,this,arguments[1],arguments[2],arguments[3]);break;default:for(n=new Array(i-1),s=1;s<i;s++)n[s-1]=arguments[s];!function(e,t,r,i){if(t)e.apply(r,i);else for(var n=e.length,s=Up(e,n),o=0;o<n;++o)s[o].apply(r,i)}(r,l,this,n)}return!0},Np.prototype.addListener=function(e,t){return Fp(this,e,t,!1)},Np.prototype.on=Np.prototype.addListener,Np.prototype.prependListener=function(e,t){return Fp(this,e,t,!0)},Np.prototype.once=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.on(e,zp(this,e,t)),this},Np.prototype.prependOnceListener=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.prependListener(e,zp(this,e,t)),this},Np.prototype.removeListener=function(e,t){var r,i,n,s,o;if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');if(!(i=this._events))return this;if(!(r=i[e]))return this;if(r===t||r.listener&&r.listener===t)0==--this._eventsCount?this._events=new Ap:(delete i[e],i.removeListener&&this.emit("removeListener",e,r.listener||t));else if("function"!=typeof r){for(n=-1,s=r.length;s-- >0;)if(r[s]===t||r[s].listener&&r[s].listener===t){o=r[s].listener,n=s;break}if(n<0)return this;if(1===r.length){if(r[0]=void 0,0==--this._eventsCount)return this._events=new Ap,this;delete i[e]}else!function(e,t){for(var r=t,i=r+1,n=e.length;i<n;r+=1,i+=1)e[r]=e[i];e.pop()}(r,n);i.removeListener&&this.emit("removeListener",e,o||t)}return this},Np.prototype.off=function(e,t){return this.removeListener(e,t)},Np.prototype.removeAllListeners=function(e){var t,r;if(!(r=this._events))return this;if(!r.removeListener)return 0===arguments.length?(this._events=new Ap,this._eventsCount=0):r[e]&&(0==--this._eventsCount?this._events=new Ap:delete r[e]),this;if(0===arguments.length){for(var i,n=Object.keys(r),s=0;s<n.length;++s)"removeListener"!==(i=n[s])&&this.removeAllListeners(i);return this.removeAllListeners("removeListener"),this._events=new Ap,this._eventsCount=0,this}if("function"==typeof(t=r[e]))this.removeListener(e,t);else if(t)do{this.removeListener(e,t[t.length-1])}while(t[0]);return this},Np.prototype.listeners=function(e){var t,r,i=this._events;return r=i&&(t=i[e])?"function"==typeof t?[t.listener||t]:function(e){for(var t=new Array(e.length),r=0;r<t.length;++r)t[r]=e[r].listener||e[r];return t}(t):[],r},Np.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):Vp.call(e,t)},Np.prototype.listenerCount=Vp,Np.prototype.eventNames=function(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]};const $p=Object.create(null);$p.open="0",$p.close="1",$p.ping="2",$p.pong="3",$p.message="4",$p.upgrade="5",$p.noop="6";const Gp=Object.create(null);Object.keys($p).forEach((e=>{Gp[$p[e]]=e}));const qp={type:"error",data:"parser error"},Hp="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),Wp="function"==typeof ArrayBuffer,Kp=e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,Jp=({type:e,data:t},r,i)=>Hp&&t instanceof Blob?r?i(t):Xp(t,i):Wp&&(t instanceof ArrayBuffer||Kp(t))?r?i(t):Xp(new Blob([t]),i):i($p[e]+(t||"")),Xp=(e,t)=>{const r=new FileReader;return r.onload=function(){const e=r.result.split(",")[1];t("b"+(e||""))},r.readAsDataURL(e)};function Qp(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let Zp;const Yp="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",eh="undefined"==typeof Uint8Array?[]:new Uint8Array(256);for(let UE=0;UE<64;UE++)eh[Yp.charCodeAt(UE)]=UE;const th="function"==typeof ArrayBuffer,rh=(e,t)=>{if("string"!=typeof e)return{type:"message",data:nh(e,t)};const r=e.charAt(0);if("b"===r)return{type:"message",data:ih(e.substring(1),t)};return Gp[r]?e.length>1?{type:Gp[r],data:e.substring(1)}:{type:Gp[r]}:qp},ih=(e,t)=>{if(th){const r=(e=>{let t,r,i,n,s,o=.75*e.length,a=e.length,c=0;"="===e[e.length-1]&&(o--,"="===e[e.length-2]&&o--);const d=new ArrayBuffer(o),l=new Uint8Array(d);for(t=0;t<a;t+=4)r=eh[e.charCodeAt(t)],i=eh[e.charCodeAt(t+1)],n=eh[e.charCodeAt(t+2)],s=eh[e.charCodeAt(t+3)],l[c++]=r<<2|i>>4,l[c++]=(15&i)<<4|n>>2,l[c++]=(3&n)<<6|63&s;return d})(e);return nh(r,t)}return{base64:!0,data:e}},nh=(e,t)=>"blob"===t?e instanceof Blob?e:new Blob([e]):e instanceof ArrayBuffer?e:e.buffer,sh=String.fromCharCode(30);function oh(){return new TransformStream({transform(e,t){!function(e,t){Hp&&e.data instanceof Blob?e.data.arrayBuffer().then(Qp).then(t):Wp&&(e.data instanceof ArrayBuffer||Kp(e.data))?t(Qp(e.data)):Jp(e,!1,(e=>{Zp||(Zp=new TextEncoder),t(Zp.encode(e))}))}(e,(r=>{const i=r.length;let n;if(i<126)n=new Uint8Array(1),new DataView(n.buffer).setUint8(0,i);else if(i<65536){n=new Uint8Array(3);const e=new DataView(n.buffer);e.setUint8(0,126),e.setUint16(1,i)}else{n=new Uint8Array(9);const e=new DataView(n.buffer);e.setUint8(0,127),e.setBigUint64(1,BigInt(i))}e.data&&"string"!=typeof e.data&&(n[0]|=128),t.enqueue(n),t.enqueue(r)}))}})}let ah;function ch(e){return e.reduce(((e,t)=>e+t.length),0)}function dh(e,t){if(e[0].length===t)return e.shift();const r=new Uint8Array(t);let i=0;for(let n=0;n<t;n++)r[n]=e[0][i++],i===e[0].length&&(e.shift(),i=0);return e.length&&i<e[0].length&&(e[0]=e[0].slice(i)),r}function lh(e){if(e)return function(e){for(var t in lh.prototype)e[t]=lh.prototype[t];return e}(e)}lh.prototype.on=lh.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this},lh.prototype.once=function(e,t){function r(){this.off(e,r),t.apply(this,arguments)}return r.fn=t,this.on(e,r),this},lh.prototype.off=lh.prototype.removeListener=lh.prototype.removeAllListeners=lh.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var r,i=this._callbacks["$"+e];if(!i)return this;if(1==arguments.length)return delete this._callbacks["$"+e],this;for(var n=0;n<i.length;n++)if((r=i[n])===t||r.fn===t){i.splice(n,1);break}return 0===i.length&&delete this._callbacks["$"+e],this},lh.prototype.emit=function(e){this._callbacks=this._callbacks||{};for(var t=new Array(arguments.length-1),r=this._callbacks["$"+e],i=1;i<arguments.length;i++)t[i-1]=arguments[i];if(r){i=0;for(var n=(r=r.slice(0)).length;i<n;++i)r[i].apply(this,t)}return this},lh.prototype.emitReserved=lh.prototype.emit,lh.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]},lh.prototype.hasListeners=function(e){return!!this.listeners(e).length};const uh="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")();function ph(e,...t){return t.reduce(((t,r)=>(e.hasOwnProperty(r)&&(t[r]=e[r]),t)),{})}const hh=uh.setTimeout,fh=uh.clearTimeout;function mh(e,t){t.useNativeTimers?(e.setTimeoutFn=hh.bind(uh),e.clearTimeoutFn=fh.bind(uh)):(e.setTimeoutFn=uh.setTimeout.bind(uh),e.clearTimeoutFn=uh.clearTimeout.bind(uh))}class gh extends Error{constructor(e,t,r){super(e),this.description=t,this.context=r,this.type="TransportError"}}class vh extends lh{constructor(e){super(),this.writable=!1,mh(this,e),this.opts=e,this.query=e.query,this.socket=e.socket}onError(e,t,r){return super.emitReserved("error",new gh(e,t,r)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return"opening"!==this.readyState&&"open"!==this.readyState||(this.doClose(),this.onClose()),this}send(e){"open"===this.readyState&&this.write(e)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){const t=rh(e,this.socket.binaryType);this.onPacket(t)}onPacket(e){super.emitReserved("packet",e)}onClose(e){this.readyState="closed",super.emitReserved("close",e)}pause(e){}createUri(e,t={}){return e+"://"+this._hostname()+this._port()+this.opts.path+this._query(t)}_hostname(){const e=this.opts.hostname;return-1===e.indexOf(":")?e:"["+e+"]"}_port(){return this.opts.port&&(this.opts.secure&&Number(443!==this.opts.port)||!this.opts.secure&&80!==Number(this.opts.port))?":"+this.opts.port:""}_query(e){const t=function(e){let t="";for(let r in e)e.hasOwnProperty(r)&&(t.length&&(t+="&"),t+=encodeURIComponent(r)+"="+encodeURIComponent(e[r]));return t}(e);return t.length?"?"+t:""}}const bh="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_".split(""),yh=64,wh={};let _h,Sh=0,Ch=0;function Rh(e){let t="";do{t=bh[e%yh]+t,e=Math.floor(e/yh)}while(e>0);return t}function kh(){const e=Rh(+new Date);return e!==_h?(Sh=0,_h=e):e+"."+Rh(Sh++)}for(;Ch<yh;Ch++)wh[bh[Ch]]=Ch;let Th=!1;try{Th="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch($E){}const Ph=Th;function Oh(e){const t=e.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!t||Ph))return new XMLHttpRequest}catch(e){}if(!t)try{return new(uh[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(e){}}function Eh(){}const Dh=null!=new Oh({xdomain:!1}).responseType;class Ih extends lh{constructor(e,t){super(),mh(this,t),this.opts=t,this.method=t.method||"GET",this.uri=e,this.data=void 0!==t.data?t.data:null,this.create()}create(){var e;const t=ph(this.opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");t.xdomain=!!this.opts.xd;const r=this.xhr=new Oh(t);try{r.open(this.method,this.uri,!0);try{if(this.opts.extraHeaders){r.setDisableHeaderCheck&&r.setDisableHeaderCheck(!0);for(let e in this.opts.extraHeaders)this.opts.extraHeaders.hasOwnProperty(e)&&r.setRequestHeader(e,this.opts.extraHeaders[e])}}catch(e){}if("POST"===this.method)try{r.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(e){}try{r.setRequestHeader("Accept","*/*")}catch(e){}null===(e=this.opts.cookieJar)||void 0===e||e.addCookies(r),"withCredentials"in r&&(r.withCredentials=this.opts.withCredentials),this.opts.requestTimeout&&(r.timeout=this.opts.requestTimeout),r.onreadystatechange=()=>{var e;3===r.readyState&&(null===(e=this.opts.cookieJar)||void 0===e||e.parseCookies(r)),4===r.readyState&&(200===r.status||1223===r.status?this.onLoad():this.setTimeoutFn((()=>{this.onError("number"==typeof r.status?r.status:0)}),0))},r.send(this.data)}catch(e){return void this.setTimeoutFn((()=>{this.onError(e)}),0)}"undefined"!=typeof document&&(this.index=Ih.requestsCount++,Ih.requests[this.index]=this)}onError(e){this.emitReserved("error",e,this.xhr),this.cleanup(!0)}cleanup(e){if(void 0!==this.xhr&&null!==this.xhr){if(this.xhr.onreadystatechange=Eh,e)try{this.xhr.abort()}catch(e){}"undefined"!=typeof document&&delete Ih.requests[this.index],this.xhr=null}}onLoad(){const e=this.xhr.responseText;null!==e&&(this.emitReserved("data",e),this.emitReserved("success"),this.cleanup())}abort(){this.cleanup()}}if(Ih.requestsCount=0,Ih.requests={},"undefined"!=typeof document)if("function"==typeof attachEvent)attachEvent("onunload",xh);else if("function"==typeof addEventListener){addEventListener("onpagehide"in uh?"pagehide":"unload",xh,!1)}function xh(){for(let e in Ih.requests)Ih.requests.hasOwnProperty(e)&&Ih.requests[e].abort()}const Mh="function"==typeof Promise&&"function"==typeof Promise.resolve?e=>Promise.resolve().then(e):(e,t)=>t(e,0),jh=uh.WebSocket||uh.MozWebSocket,Lh="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();const Ah={websocket:class extends vh{constructor(e){super(e),this.supportsBinary=!e.forceBase64}get name(){return"websocket"}doOpen(){if(!this.check())return;const e=this.uri(),t=this.opts.protocols,r=Lh?{}:ph(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(r.headers=this.opts.extraHeaders);try{this.ws=Lh?new jh(e,t,r):t?new jh(e,t):new jh(e)}catch(e){return this.emitReserved("error",e)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const r=e[t],i=t===e.length-1;Jp(r,this.supportsBinary,(e=>{try{this.ws.send(e)}catch(e){}i&&Mh((()=>{this.writable=!0,this.emitReserved("drain")}),this.setTimeoutFn)}))}}doClose(){void 0!==this.ws&&(this.ws.close(),this.ws=null)}uri(){const e=this.opts.secure?"wss":"ws",t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=kh()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}check(){return!!jh}},webtransport:class extends vh{get name(){return"webtransport"}doOpen(){"function"==typeof WebTransport&&(this.transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name]),this.transport.closed.then((()=>{this.onClose()})).catch((e=>{this.onError("webtransport error",e)})),this.transport.ready.then((()=>{this.transport.createBidirectionalStream().then((e=>{const t=function(e,t){ah||(ah=new TextDecoder);const r=[];let i=0,n=-1,s=!1;return new TransformStream({transform(o,a){for(r.push(o);;){if(0===i){if(ch(r)<1)break;const e=dh(r,1);s=128==(128&e[0]),n=127&e[0],i=n<126?3:126===n?1:2}else if(1===i){if(ch(r)<2)break;const e=dh(r,2);n=new DataView(e.buffer,e.byteOffset,e.length).getUint16(0),i=3}else if(2===i){if(ch(r)<8)break;const e=dh(r,8),t=new DataView(e.buffer,e.byteOffset,e.length),s=t.getUint32(0);if(s>Math.pow(2,21)-1){a.enqueue(qp);break}n=s*Math.pow(2,32)+t.getUint32(4),i=3}else{if(ch(r)<n)break;const e=dh(r,n);a.enqueue(rh(s?e:ah.decode(e),t)),i=0}if(0===n||n>e){a.enqueue(qp);break}}}})}(Number.MAX_SAFE_INTEGER,this.socket.binaryType),r=e.readable.pipeThrough(t).getReader(),i=oh();i.readable.pipeTo(e.writable),this.writer=i.writable.getWriter();const n=()=>{r.read().then((({done:e,value:t})=>{e||(this.onPacket(t),n())})).catch((e=>{}))};n();const s={type:"open"};this.query.sid&&(s.data=`{"sid":"${this.query.sid}"}`),this.writer.write(s).then((()=>this.onOpen()))}))})))}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const r=e[t],i=t===e.length-1;this.writer.write(r).then((()=>{i&&Mh((()=>{this.writable=!0,this.emitReserved("drain")}),this.setTimeoutFn)}))}}doClose(){var e;null===(e=this.transport)||void 0===e||e.close()}},polling:class extends vh{constructor(e){if(super(e),this.polling=!1,"undefined"!=typeof location){const t="https:"===location.protocol;let r=location.port;r||(r=t?"443":"80"),this.xd="undefined"!=typeof location&&e.hostname!==location.hostname||r!==e.port}const t=e&&e.forceBase64;this.supportsBinary=Dh&&!t,this.opts.withCredentials&&(this.cookieJar=void 0)}get name(){return"polling"}doOpen(){this.poll()}pause(e){this.readyState="pausing";const t=()=>{this.readyState="paused",e()};if(this.polling||!this.writable){let e=0;this.polling&&(e++,this.once("pollComplete",(function(){--e||t()}))),this.writable||(e++,this.once("drain",(function(){--e||t()})))}else t()}poll(){this.polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){((e,t)=>{const r=e.split(sh),i=[];for(let e=0;e<r.length;e++){const n=rh(r[e],t);if(i.push(n),"error"===n.type)break}return i})(e,this.socket.binaryType).forEach((e=>{if("opening"===this.readyState&&"open"===e.type&&this.onOpen(),"close"===e.type)return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(e)})),"closed"!==this.readyState&&(this.polling=!1,this.emitReserved("pollComplete"),"open"===this.readyState&&this.poll())}doClose(){const e=()=>{this.write([{type:"close"}])};"open"===this.readyState?e():this.once("open",e)}write(e){this.writable=!1,((e,t)=>{const r=e.length,i=new Array(r);let n=0;e.forEach(((e,s)=>{Jp(e,!1,(e=>{i[s]=e,++n===r&&t(i.join(sh))}))}))})(e,(e=>{this.doWrite(e,(()=>{this.writable=!0,this.emitReserved("drain")}))}))}uri(){const e=this.opts.secure?"https":"http",t=this.query||{};return!1!==this.opts.timestampRequests&&(t[this.opts.timestampParam]=kh()),this.supportsBinary||t.sid||(t.b64=1),this.createUri(e,t)}request(e={}){return Object.assign(e,{xd:this.xd,cookieJar:this.cookieJar},this.opts),new Ih(this.uri(),e)}doWrite(e,t){const r=this.request({method:"POST",data:e});r.on("success",t),r.on("error",((e,t)=>{this.onError("xhr post error",e,t)}))}doPoll(){const e=this.request();e.on("data",this.onData.bind(this)),e.on("error",((e,t)=>{this.onError("xhr poll error",e,t)})),this.pollXhr=e}}},Nh=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,Bh=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function Fh(e){if(e.length>2e3)throw"URI too long";const t=e,r=e.indexOf("["),i=e.indexOf("]");-1!=r&&-1!=i&&(e=e.substring(0,r)+e.substring(r,i).replace(/:/g,";")+e.substring(i,e.length));let n=Nh.exec(e||""),s={},o=14;for(;o--;)s[Bh[o]]=n[o]||"";return-1!=r&&-1!=i&&(s.source=t,s.host=s.host.substring(1,s.host.length-1).replace(/;/g,":"),s.authority=s.authority.replace("[","").replace("]","").replace(/;/g,":"),s.ipv6uri=!0),s.pathNames=function(e,t){const r=/\/{2,9}/g,i=t.replace(r,"/").split("/");"/"!=t.slice(0,1)&&0!==t.length||i.splice(0,1);"/"==t.slice(-1)&&i.splice(i.length-1,1);return i}(0,s.path),s.queryKey=function(e,t){const r={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,(function(e,t,i){t&&(r[t]=i)})),r}(0,s.query),s}let zh=class e extends lh{constructor(e,t={}){super(),this.binaryType="arraybuffer",this.writeBuffer=[],e&&"object"==typeof e&&(t=e,e=null),e?(e=Fh(e),t.hostname=e.host,t.secure="https"===e.protocol||"wss"===e.protocol,t.port=e.port,e.query&&(t.query=e.query)):t.host&&(t.hostname=Fh(t.host).host),mh(this,t),this.secure=null!=t.secure?t.secure:"undefined"!=typeof location&&"https:"===location.protocol,t.hostname&&!t.port&&(t.port=this.secure?"443":"80"),this.hostname=t.hostname||("undefined"!=typeof location?location.hostname:"localhost"),this.port=t.port||("undefined"!=typeof location&&location.port?location.port:this.secure?"443":"80"),this.transports=t.transports||["polling","websocket","webtransport"],this.writeBuffer=[],this.prevBufferLen=0,this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},t),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),"string"==typeof this.opts.query&&(this.opts.query=function(e){let t={},r=e.split("&");for(let e=0,i=r.length;e<i;e++){let i=r[e].split("=");t[decodeURIComponent(i[0])]=decodeURIComponent(i[1])}return t}(this.opts.query)),this.id=null,this.upgrades=null,this.pingInterval=null,this.pingTimeout=null,this.pingTimeoutTimer=null,"function"==typeof addEventListener&&(this.opts.closeOnBeforeunload&&(this.beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this.beforeunloadEventListener,!1)),"localhost"!==this.hostname&&(this.offlineEventListener=()=>{this.onClose("transport close",{description:"network connection lost"})},addEventListener("offline",this.offlineEventListener,!1))),this.open()}createTransport(e){const t=Object.assign({},this.opts.query);t.EIO=4,t.transport=e,this.id&&(t.sid=this.id);const r=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return new Ah[e](r)}open(){let t;if(this.opts.rememberUpgrade&&e.priorWebsocketSuccess&&-1!==this.transports.indexOf("websocket"))t="websocket";else{if(0===this.transports.length)return void this.setTimeoutFn((()=>{this.emitReserved("error","No transports available")}),0);t=this.transports[0]}this.readyState="opening";try{t=this.createTransport(t)}catch(e){return this.transports.shift(),void this.open()}t.open(),this.setTransport(t)}setTransport(e){this.transport&&this.transport.removeAllListeners(),this.transport=e,e.on("drain",this.onDrain.bind(this)).on("packet",this.onPacket.bind(this)).on("error",this.onError.bind(this)).on("close",(e=>this.onClose("transport close",e)))}probe(t){let r=this.createTransport(t),i=!1;e.priorWebsocketSuccess=!1;const n=()=>{i||(r.send([{type:"ping",data:"probe"}]),r.once("packet",(t=>{if(!i)if("pong"===t.type&&"probe"===t.data){if(this.upgrading=!0,this.emitReserved("upgrading",r),!r)return;e.priorWebsocketSuccess="websocket"===r.name,this.transport.pause((()=>{i||"closed"!==this.readyState&&(l(),this.setTransport(r),r.send([{type:"upgrade"}]),this.emitReserved("upgrade",r),r=null,this.upgrading=!1,this.flush())}))}else{const e=new Error("probe error");e.transport=r.name,this.emitReserved("upgradeError",e)}})))};function s(){i||(i=!0,l(),r.close(),r=null)}const o=e=>{const t=new Error("probe error: "+e);t.transport=r.name,s(),this.emitReserved("upgradeError",t)};function a(){o("transport closed")}function c(){o("socket closed")}function d(e){r&&e.name!==r.name&&s()}const l=()=>{r.removeListener("open",n),r.removeListener("error",o),r.removeListener("close",a),this.off("close",c),this.off("upgrading",d)};r.once("open",n),r.once("error",o),r.once("close",a),this.once("close",c),this.once("upgrading",d),-1!==this.upgrades.indexOf("webtransport")&&"webtransport"!==t?this.setTimeoutFn((()=>{i||r.open()}),200):r.open()}onOpen(){if(this.readyState="open",e.priorWebsocketSuccess="websocket"===this.transport.name,this.emitReserved("open"),this.flush(),"open"===this.readyState&&this.opts.upgrade){let e=0;const t=this.upgrades.length;for(;e<t;e++)this.probe(this.upgrades[e])}}onPacket(e){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState)switch(this.emitReserved("packet",e),this.emitReserved("heartbeat"),this.resetPingTimeout(),e.type){case"open":this.onHandshake(JSON.parse(e.data));break;case"ping":this.sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong");break;case"error":const t=new Error("server error");t.code=e.data,this.onError(t);break;case"message":this.emitReserved("data",e.data),this.emitReserved("message",e.data)}}onHandshake(e){this.emitReserved("handshake",e),this.id=e.sid,this.transport.query.sid=e.sid,this.upgrades=this.filterUpgrades(e.upgrades),this.pingInterval=e.pingInterval,this.pingTimeout=e.pingTimeout,this.maxPayload=e.maxPayload,this.onOpen(),"closed"!==this.readyState&&this.resetPingTimeout()}resetPingTimeout(){this.clearTimeoutFn(this.pingTimeoutTimer),this.pingTimeoutTimer=this.setTimeoutFn((()=>{this.onClose("ping timeout")}),this.pingInterval+this.pingTimeout),this.opts.autoUnref&&this.pingTimeoutTimer.unref()}onDrain(){this.writeBuffer.splice(0,this.prevBufferLen),this.prevBufferLen=0,0===this.writeBuffer.length?this.emitReserved("drain"):this.flush()}flush(){if("closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const e=this.getWritablePackets();this.transport.send(e),this.prevBufferLen=e.length,this.emitReserved("flush")}}getWritablePackets(){if(!(this.maxPayload&&"polling"===this.transport.name&&this.writeBuffer.length>1))return this.writeBuffer;let e=1;for(let r=0;r<this.writeBuffer.length;r++){const i=this.writeBuffer[r].data;if(i&&(e+="string"==typeof(t=i)?function(e){let t=0,r=0;for(let i=0,n=e.length;i<n;i++)t=e.charCodeAt(i),t<128?r+=1:t<2048?r+=2:t<55296||t>=57344?r+=3:(i++,r+=4);return r}(t):Math.ceil(1.33*(t.byteLength||t.size))),r>0&&e>this.maxPayload)return this.writeBuffer.slice(0,r);e+=2}var t;return this.writeBuffer}write(e,t,r){return this.sendPacket("message",e,t,r),this}send(e,t,r){return this.sendPacket("message",e,t,r),this}sendPacket(e,t,r,i){if("function"==typeof t&&(i=t,t=void 0),"function"==typeof r&&(i=r,r=null),"closing"===this.readyState||"closed"===this.readyState)return;(r=r||{}).compress=!1!==r.compress;const n={type:e,data:t,options:r};this.emitReserved("packetCreate",n),this.writeBuffer.push(n),i&&this.once("flush",i),this.flush()}close(){const e=()=>{this.onClose("forced close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),e()},r=()=>{this.once("upgrade",t),this.once("upgradeError",t)};return"opening"!==this.readyState&&"open"!==this.readyState||(this.readyState="closing",this.writeBuffer.length?this.once("drain",(()=>{this.upgrading?r():e()})):this.upgrading?r():e()),this}onError(t){e.priorWebsocketSuccess=!1,this.emitReserved("error",t),this.onClose("transport error",t)}onClose(e,t){"opening"!==this.readyState&&"open"!==this.readyState&&"closing"!==this.readyState||(this.clearTimeoutFn(this.pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),"function"==typeof removeEventListener&&(removeEventListener("beforeunload",this.beforeunloadEventListener,!1),removeEventListener("offline",this.offlineEventListener,!1)),this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this.prevBufferLen=0)}filterUpgrades(e){const t=[];let r=0;const i=e.length;for(;r<i;r++)~this.transports.indexOf(e[r])&&t.push(e[r]);return t}};zh.protocol=4;const Vh="function"==typeof ArrayBuffer,Uh=e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer,$h=Object.prototype.toString,Gh="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===$h.call(Blob),qh="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===$h.call(File);function Hh(e){return Vh&&(e instanceof ArrayBuffer||Uh(e))||Gh&&e instanceof Blob||qh&&e instanceof File}function Wh(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e)){for(let t=0,r=e.length;t<r;t++)if(Wh(e[t]))return!0;return!1}if(Hh(e))return!0;if(e.toJSON&&"function"==typeof e.toJSON&&1===arguments.length)return Wh(e.toJSON(),!0);for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t)&&Wh(e[t]))return!0;return!1}function Kh(e){const t=[],r=e.data,i=e;return i.data=Jh(r,t),i.attachments=t.length,{packet:i,buffers:t}}function Jh(e,t){if(!e)return e;if(Hh(e)){const r={_placeholder:!0,num:t.length};return t.push(e),r}if(Array.isArray(e)){const r=new Array(e.length);for(let i=0;i<e.length;i++)r[i]=Jh(e[i],t);return r}if("object"==typeof e&&!(e instanceof Date)){const r={};for(const i in e)Object.prototype.hasOwnProperty.call(e,i)&&(r[i]=Jh(e[i],t));return r}return e}function Xh(e,t){return e.data=Qh(e.data,t),delete e.attachments,e}function Qh(e,t){if(!e)return e;if(e&&!0===e._placeholder){if("number"==typeof e.num&&e.num>=0&&e.num<t.length)return t[e.num];throw new Error("illegal attachments")}if(Array.isArray(e))for(let r=0;r<e.length;r++)e[r]=Qh(e[r],t);else if("object"==typeof e)for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&(e[r]=Qh(e[r],t));return e}const Zh=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var Yh;!function(e){e[e.CONNECT=0]="CONNECT",e[e.DISCONNECT=1]="DISCONNECT",e[e.EVENT=2]="EVENT",e[e.ACK=3]="ACK",e[e.CONNECT_ERROR=4]="CONNECT_ERROR",e[e.BINARY_EVENT=5]="BINARY_EVENT",e[e.BINARY_ACK=6]="BINARY_ACK"}(Yh||(Yh={}));function ef(e){return"[object Object]"===Object.prototype.toString.call(e)}class tf extends lh{constructor(e){super(),this.reviver=e}add(e){let t;if("string"==typeof e){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");t=this.decodeString(e);const r=t.type===Yh.BINARY_EVENT;r||t.type===Yh.BINARY_ACK?(t.type=r?Yh.EVENT:Yh.ACK,this.reconstructor=new rf(t),0===t.attachments&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else{if(!Hh(e)&&!e.base64)throw new Error("Unknown type: "+e);if(!this.reconstructor)throw new Error("got binary data when not reconstructing a packet");t=this.reconstructor.takeBinaryData(e),t&&(this.reconstructor=null,super.emitReserved("decoded",t))}}decodeString(e){let t=0;const r={type:Number(e.charAt(0))};if(void 0===Yh[r.type])throw new Error("unknown packet type "+r.type);if(r.type===Yh.BINARY_EVENT||r.type===Yh.BINARY_ACK){const i=t+1;for(;"-"!==e.charAt(++t)&&t!=e.length;);const n=e.substring(i,t);if(n!=Number(n)||"-"!==e.charAt(t))throw new Error("Illegal attachments");r.attachments=Number(n)}if("/"===e.charAt(t+1)){const i=t+1;for(;++t;){if(","===e.charAt(t))break;if(t===e.length)break}r.nsp=e.substring(i,t)}else r.nsp="/";const i=e.charAt(t+1);if(""!==i&&Number(i)==i){const i=t+1;for(;++t;){const r=e.charAt(t);if(null==r||Number(r)!=r){--t;break}if(t===e.length)break}r.id=Number(e.substring(i,t+1))}if(e.charAt(++t)){const i=this.tryParse(e.substr(t));if(!tf.isPayloadValid(r.type,i))throw new Error("invalid payload");r.data=i}return r}tryParse(e){try{return JSON.parse(e,this.reviver)}catch(e){return!1}}static isPayloadValid(e,t){switch(e){case Yh.CONNECT:return ef(t);case Yh.DISCONNECT:return void 0===t;case Yh.CONNECT_ERROR:return"string"==typeof t||ef(t);case Yh.EVENT:case Yh.BINARY_EVENT:return Array.isArray(t)&&("number"==typeof t[0]||"string"==typeof t[0]&&-1===Zh.indexOf(t[0]));case Yh.ACK:case Yh.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class rf{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){const e=Xh(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}var nf=Object.freeze({__proto__:null,Decoder:tf,Encoder:class{constructor(e){this.replacer=e}encode(e){return e.type!==Yh.EVENT&&e.type!==Yh.ACK||!Wh(e)?[this.encodeAsString(e)]:this.encodeAsBinary({type:e.type===Yh.EVENT?Yh.BINARY_EVENT:Yh.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id})}encodeAsString(e){let t=""+e.type;return e.type!==Yh.BINARY_EVENT&&e.type!==Yh.BINARY_ACK||(t+=e.attachments+"-"),e.nsp&&"/"!==e.nsp&&(t+=e.nsp+","),null!=e.id&&(t+=e.id),null!=e.data&&(t+=JSON.stringify(e.data,this.replacer)),t}encodeAsBinary(e){const t=Kh(e),r=this.encodeAsString(t.packet),i=t.buffers;return i.unshift(r),i}},get PacketType(){return Yh},protocol:5});function sf(e,t,r){return e.on(t,r),function(){e.off(t,r)}}const of=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class af extends lh{constructor(e,t,r){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,r&&r.auth&&(this.auth=r.auth),this._opts=Object.assign({},r),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const e=this.io;this.subs=[sf(e,"open",this.onopen.bind(this)),sf(e,"packet",this.onpacket.bind(this)),sf(e,"error",this.onerror.bind(this)),sf(e,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected||(this.subEvents(),this.io._reconnecting||this.io.open(),"open"===this.io._readyState&&this.onopen()),this}open(){return this.connect()}send(...e){return e.unshift("message"),this.emit.apply(this,e),this}emit(e,...t){if(of.hasOwnProperty(e))throw new Error('"'+e.toString()+'" is a reserved event name');if(t.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;const r={type:Yh.EVENT,data:t,options:{}};if(r.options.compress=!1!==this.flags.compress,"function"==typeof t[t.length-1]){const e=this.ids++,i=t.pop();this._registerAckCallback(e,i),r.id=e}const i=this.io.engine&&this.io.engine.transport&&this.io.engine.transport.writable;return this.flags.volatile&&(!i||!this.connected)||(this.connected?(this.notifyOutgoingListeners(r),this.packet(r)):this.sendBuffer.push(r)),this.flags={},this}_registerAckCallback(e,t){var r;const i=null!==(r=this.flags.timeout)&&void 0!==r?r:this._opts.ackTimeout;if(void 0===i)return void(this.acks[e]=t);const n=this.io.setTimeoutFn((()=>{delete this.acks[e];for(let t=0;t<this.sendBuffer.length;t++)this.sendBuffer[t].id===e&&this.sendBuffer.splice(t,1);t.call(this,new Error("operation has timed out"))}),i);this.acks[e]=(...e)=>{this.io.clearTimeoutFn(n),t.apply(this,[null,...e])}}emitWithAck(e,...t){const r=void 0!==this.flags.timeout||void 0!==this._opts.ackTimeout;return new Promise(((i,n)=>{t.push(((e,t)=>r?e?n(e):i(t):i(e))),this.emit(e,...t)}))}_addToQueue(e){let t;"function"==typeof e[e.length-1]&&(t=e.pop());const r={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push(((e,...i)=>{if(r!==this._queue[0])return;return null!==e?r.tryCount>this._opts.retries&&(this._queue.shift(),t&&t(e)):(this._queue.shift(),t&&t(null,...i)),r.pending=!1,this._drainQueue()})),this._queue.push(r),this._drainQueue()}_drainQueue(e=!1){if(!this.connected||0===this._queue.length)return;const t=this._queue[0];t.pending&&!e||(t.pending=!0,t.tryCount++,this.flags=t.flags,this.emit.apply(this,t.args))}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){"function"==typeof this.auth?this.auth((e=>{this._sendConnectPacket(e)})):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:Yh.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved("connect_error",e)}onclose(e,t){this.connected=!1,delete this.id,this.emitReserved("disconnect",e,t)}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case Yh.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case Yh.EVENT:case Yh.BINARY_EVENT:this.onevent(e);break;case Yh.ACK:case Yh.BINARY_ACK:this.onack(e);break;case Yh.DISCONNECT:this.ondisconnect();break;case Yh.CONNECT_ERROR:this.destroy();const t=new Error(e.data.message);t.data=e.data.data,this.emitReserved("connect_error",t)}}onevent(e){const t=e.data||[];null!=e.id&&t.push(this.ack(e.id)),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){const t=this._anyListeners.slice();for(const r of t)r.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&"string"==typeof e[e.length-1]&&(this._lastOffset=e[e.length-1])}ack(e){const t=this;let r=!1;return function(...i){r||(r=!0,t.packet({type:Yh.ACK,id:e,data:i}))}}onack(e){const t=this.acks[e.id];"function"==typeof t&&(t.apply(this,e.data),delete this.acks[e.id])}onconnect(e,t){this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach((e=>this.emitEvent(e))),this.receiveBuffer=[],this.sendBuffer.forEach((e=>{this.notifyOutgoingListeners(e),this.packet(e)})),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach((e=>e())),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:Yh.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){const t=this._anyListeners;for(let r=0;r<t.length;r++)if(e===t[r])return t.splice(r,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){const t=this._anyOutgoingListeners;for(let r=0;r<t.length;r++)if(e===t[r])return t.splice(r,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const t=this._anyOutgoingListeners.slice();for(const r of t)r.apply(this,e.data)}}}function cf(e){e=e||{},this.ms=e.min||100,this.max=e.max||1e4,this.factor=e.factor||2,this.jitter=e.jitter>0&&e.jitter<=1?e.jitter:0,this.attempts=0}cf.prototype.duration=function(){var e=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),r=Math.floor(t*this.jitter*e);e=0==(1&Math.floor(10*t))?e-r:e+r}return 0|Math.min(e,this.max)},cf.prototype.reset=function(){this.attempts=0},cf.prototype.setMin=function(e){this.ms=e},cf.prototype.setMax=function(e){this.max=e},cf.prototype.setJitter=function(e){this.jitter=e};class df extends lh{constructor(e,t){var r;super(),this.nsps={},this.subs=[],e&&"object"==typeof e&&(t=e,e=void 0),(t=t||{}).path=t.path||"/socket.io",this.opts=t,mh(this,t),this.reconnection(!1!==t.reconnection),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor(null!==(r=t.randomizationFactor)&&void 0!==r?r:.5),this.backoff=new cf({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==t.timeout?2e4:t.timeout),this._readyState="closed",this.uri=e;const i=t.parser||nf;this.encoder=new i.Encoder,this.decoder=new i.Decoder,this._autoConnect=!1!==t.autoConnect,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,this):this._reconnection}reconnectionAttempts(e){return void 0===e?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return void 0===e?this._reconnectionDelay:(this._reconnectionDelay=e,null===(t=this.backoff)||void 0===t||t.setMin(e),this)}randomizationFactor(e){var t;return void 0===e?this._randomizationFactor:(this._randomizationFactor=e,null===(t=this.backoff)||void 0===t||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return void 0===e?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,null===(t=this.backoff)||void 0===t||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&0===this.backoff.attempts&&this.reconnect()}open(e){if(~this._readyState.indexOf("open"))return this;this.engine=new zh(this.uri,this.opts);const t=this.engine,r=this;this._readyState="opening",this.skipReconnect=!1;const i=sf(t,"open",(function(){r.onopen(),e&&e()})),n=t=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",t),e?e(t):this.maybeReconnectOnOpen()},s=sf(t,"error",n);if(!1!==this._timeout){const e=this._timeout,r=this.setTimeoutFn((()=>{i(),n(new Error("timeout")),t.close()}),e);this.opts.autoUnref&&r.unref(),this.subs.push((()=>{this.clearTimeoutFn(r)}))}return this.subs.push(i),this.subs.push(s),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const e=this.engine;this.subs.push(sf(e,"ping",this.onping.bind(this)),sf(e,"data",this.ondata.bind(this)),sf(e,"error",this.onerror.bind(this)),sf(e,"close",this.onclose.bind(this)),sf(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(e){this.onclose("parse error",e)}}ondecoded(e){Mh((()=>{this.emitReserved("packet",e)}),this.setTimeoutFn)}onerror(e){this.emitReserved("error",e)}socket(e,t){let r=this.nsps[e];return r?this._autoConnect&&!r.active&&r.connect():(r=new af(this,e,t),this.nsps[e]=r),r}_destroy(e){const t=Object.keys(this.nsps);for(const e of t){if(this.nsps[e].active)return}this._close()}_packet(e){const t=this.encoder.encode(e);for(let r=0;r<t.length;r++)this.engine.write(t[r],e.options)}cleanup(){this.subs.forEach((e=>e())),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close"),this.engine&&this.engine.close()}disconnect(){return this._close()}onclose(e,t){this.cleanup(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const e=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const t=this.backoff.duration();this._reconnecting=!0;const r=this.setTimeoutFn((()=>{e.skipReconnect||(this.emitReserved("reconnect_attempt",e.backoff.attempts),e.skipReconnect||e.open((t=>{t?(e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",t)):e.onreconnect()})))}),t);this.opts.autoUnref&&r.unref(),this.subs.push((()=>{this.clearTimeoutFn(r)}))}}onreconnect(){const e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}}const lf={};function uf(e,t){"object"==typeof e&&(t=e,e=void 0);const r=function(e,t="",r){let i=e;r=r||"undefined"!=typeof location&&location,null==e&&(e=r.protocol+"//"+r.host),"string"==typeof e&&("/"===e.charAt(0)&&(e="/"===e.charAt(1)?r.protocol+e:r.host+e),/^(https?|wss?):\/\//.test(e)||(e=void 0!==r?r.protocol+"//"+e:"https://"+e),i=Fh(e)),i.port||(/^(http|ws)$/.test(i.protocol)?i.port="80":/^(http|ws)s$/.test(i.protocol)&&(i.port="443")),i.path=i.path||"/";const n=-1!==i.host.indexOf(":")?"["+i.host+"]":i.host;return i.id=i.protocol+"://"+n+":"+i.port+t,i.href=i.protocol+"://"+n+(r&&r.port===i.port?"":":"+i.port),i}(e,(t=t||{}).path||"/socket.io"),i=r.source,n=r.id,s=r.path,o=lf[n]&&s in lf[n].nsps;let a;return t.forceNew||t["force new connection"]||!1===t.multiplex||o?a=new df(i,t):(lf[n]||(lf[n]=new df(i,t)),a=lf[n]),r.query&&!t.query&&(t.query=r.queryKey),a.socket(r.path,t)}Object.assign(uf,{Manager:df,Socket:af,io:uf,connect:uf});const pf=new URLSearchParams(window.location.search).has("debug");class hf{constructor(){this._isEnabled=!1,this._isEnabled=pf}isEnabled(){return this._isEnabled}enable(){this._isEnabled=!0}disable(){this._isEnabled=!1}info(...e){if(this._isEnabled)return console.info(...e)}warn(...e){if(this._isEnabled)return console.warn(...e)}error(...e){if(this._isEnabled)return console.error(...e)}withDebugLogger(e){return this._debugger=e,this}debug(...e){if(!this._isEnabled||!this._debugger)return;const t=[];e.forEach((e=>{if("function"==typeof e){const r=e();t.push(r)}else t.push(e)})),this._debugger.print(...t)}}function ff(e,t,r,i){return new(r||(r=Promise))((function(n,s){function o(e){try{c(i.next(e))}catch(e){s(e)}}function a(e){try{c(i.throw(e))}catch(e){s(e)}}function c(e){e.done?n(e.value):function(e){return e instanceof r?e:new r((function(t){t(e)}))}(e.value).then(o,a)}c((i=i.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError,pi.default;const mf={id:_i(),connectionNumber:0},gf=()=>{};let vf=gf;const bf=function(e,t=console){const r=[];let i,n,s,o,a,c,d,l,u,p,h,f,m=0,g=!1,v=0;const b={connected:!1,trace:(...e)=>{if(e.push(Date.now()),"customEvent"===e[0]&&"roomSessionId"===e[2].type){const t=c&&c[2].value.roomSessionId,r=e[2].value.roomSessionId;c=e,g&&r&&r!==t&&(null==i||i.close()),r&&(g=!0)}else"customEvent"===e[0]&&"clientId"===e[2].type?s=e:"customEvent"===e[0]&&"organizationId"===e[2].type?n=e:"customEvent"===e[0]&&"displayName"===e[2].type?o=e:"customEvent"===e[0]&&"userRole"===e[2].type?a=e:"customEvent"===e[0]&&"deviceId"===e[2].type?l=e:"customEvent"===e[0]&&"roomProduct"===e[2].type?u=e:"customEvent"===e[0]&&"roomMode"===e[2].type?p=e:"customEvent"===e[0]&&"sfuServer"===e[2].type?h=e:"customEvent"===e[0]&&"featureFlags"===e[2].type&&(f=e);(null==i?void 0:i.readyState)===WebSocket.OPEN?(m=0,i.send(JSON.stringify(e))):"getstats"===e[0]?v<20&&(v++,r.push(e)):"customEvent"===e[0]&&"insightsStats"===e[2].type||r.push(e),(null==i?void 0:i.readyState)===WebSocket.CLOSED&&d&&setTimeout((()=>{i.readyState===WebSocket.CLOSED&&d&&b.connect()}),1e3*m)},close:()=>{d=!1,null==i||i.close()},connect:()=>{d=!0,m+=1,null==i||i.close(),b.connected=!0,i=new WebSocket(e+window.location.pathname,"1.0"),i.onerror=e=>{b.connected=!1,t.warn("[RTCSTATS] WebSocket error",e)},i.onclose=e=>{b.connected=!1,t.info(`[RTCSTATS] Closed ${e.code}`),vf()},i.onopen=()=>{for(mf.connectionNumber++,i.send(JSON.stringify(["clientInfo",null,mf])),n&&i.send(JSON.stringify(n)),s&&i.send(JSON.stringify(s)),c&&i.send(JSON.stringify(c)),o&&i.send(JSON.stringify(o)),a&&i.send(JSON.stringify(a)),l&&i.send(JSON.stringify(l)),p&&i.send(JSON.stringify(p)),u&&i.send(JSON.stringify(u)),h&&i.send(JSON.stringify(h)),f&&i.send(JSON.stringify(f));r.length;)i.send(JSON.stringify(r.shift()));v=0}}};return b}("wss://rtcstats.srv.whereby.com"),yf=mi(bf.trace,1e4,[""]);vf=(null==yf?void 0:yf.resetDelta)||gf;const wf={sendEvent:(e,t)=>{bf.trace("customEvent",null,{type:e,value:t})},sendAudioMuted:e=>{wf.sendEvent("audio_muted",{muted:e})},sendVideoMuted:e=>{wf.sendEvent("video_muted",{muted:e})},server:bf};let _f=[],Sf=0;const Cf=new WeakMap,Rf=e=>{_f=_f.filter((t=>t!==e))};if(window.RTCPeerConnection){const GE=window.RTCPeerConnection;function qE(e){const t=new GE(e);_f.push(t),Cf.set(t,{index:Sf++});const r=()=>{"closed"===t.connectionState&&(Rf(t),t.removeEventListener("connectionstatechange",r))};return t.addEventListener("connectionstatechange",r),t}qE.prototype=GE.prototype,window.RTCPeerConnection=qE}const kf=e=>{var t;return null===(t=Cf.get(e))||void 0===t?void 0:t.index},Tf=new WeakMap;const Pf=()=>Promise.all(_f.map((e=>ff(void 0,void 0,void 0,(function*(){let t=Tf.get(e);t||(t={ssrcToTrackId:{}},Tf.set(e,t));try{const r=yield e.getStats();let i=null;if(r.forEach((e=>{if(!("inbound-rtp"!==e.type&&"outbound-rtp"!==e.type||e.trackIdentifier||t.ssrcToTrackId[e.ssrc])){if(e.mediaSourceId){const i=r.get(e.mediaSourceId);i&&i.trackIdentifier&&(t.ssrcToTrackId[e.ssrc]=i.trackIdentifier)}if(!t.ssrcToTrackId[e.ssrc]&&e.trackId){const i=r.get(e.trackId);i&&i.trackIdentifier&&(t.ssrcToTrackId[e.ssrc]=i.trackIdentifier)}t.ssrcToTrackId[e.ssrc]||(i||(i=[]),i.push(e.ssrc))}})),i){const r=[...e.getSenders(),...e.getReceivers()];(yield Promise.all(r.map((e=>e.getStats())))).forEach(((e,i)=>{e.forEach((e=>{"inbound-rtp"!==e.type&&"outbound-rtp"!==e.type||(t.ssrcToTrackId[e.ssrc]=r[i].track.id)}))})),i.forEach((e=>{t.ssrcToTrackId[e]||(t.ssrcToTrackId[e]="?"+e)}))}return[e,r,t]}catch(r){return wf.sendEvent("trackSsrcLookupFailed",{name:null==r?void 0:r.name,cause:null==r?void 0:r.cause,message:null==r?void 0:r.message}),[e,[],t]}}))))),Of=(e,t,r,i,n,s)=>{let o=e[i];o||(o={tracks:{},startTime:t,updated:t},e[i]=o),o.updated=t;let a=o.tracks[n];a||(a={ssrcs:{},startTime:t,updated:t},o.tracks[n]=a),a.updated=t;let c=a.ssrcs[s];return c||(c={startTime:t,updated:t,pcIndex:r},a.ssrcs[s]=c),c.updated=t,c},Ef=(e,t)=>{Object.entries(e).forEach((([r,i])=>{i.updated<t?delete e[r]:Object.entries(i.tracks).forEach((([e,r])=>{r.updated<t?delete i.tracks[e]:Object.entries(r.ssrcs).forEach((([e,i])=>{i.updated<t&&delete r.ssrcs[e]}))}))}))};function Df(e,{logger:t,interval:r},i){return ff(this,void 0,void 0,(function*(){const n=Df.bind(null,e,{interval:r,logger:t});try{const t=e.getClients(),s=t.find((e=>e.isLocalClient&&!e.isPresentation))||{id:"unknown"};let o=e.statsByView[s.id];o||(o={tracks:{},candidatePairs:{},pressure:null},e.statsByView[s.id]=o),o.pressure=e.lastPressureObserverRecord;if(Date.now()-e.lastUpdateTime<400)return i?e.statsByView:(e.subscriptions.forEach((r=>{var i;return null===(i=r.onUpdatedStats)||void 0===i?void 0:i.call(r,e.statsByView,t)})),void(e.nextTimeout=setTimeout(n,r)));if(e.lastUpdateTime=Date.now(),(yield Pf()).forEach((([i,n,a])=>{const c=kf(i);"closed"===i.connectionState&&(n=new Map,Rf(i)),a.previousSSRCs=a.currentSSRCs||{},a.currentSSRCs={},n.forEach((i=>{var d,l,u;if("candidate-pair"===i.type&&/inprogress|succeeded/.test(i.state)){const t=null===(d=a._oldReport)||void 0===d?void 0:d.get(i.id),s=t?i.timestamp-t.timestamp:r,l=c+":"+i.id;let u=o.candidatePairs[l];u||(u={startTime:e.lastUpdateTime,id:l},o.candidatePairs[l]=u),function(e,t,r,i,n){const s=t.bytesReceived-((null==r?void 0:r.bytesReceived)||0),o=t.bytesSent-((null==r?void 0:r.bytesSent)||0);e.bitrateIn=8e3*s/i,e.bitrateOut=8e3*o/i,e.state=t.state,e.roundTripTime=t.currentRoundTripTime,e.requestsSent=t.requestsSent,e.responsesReceived=t.responsesReceived,e.requestsReceived=t.requestsReceived,e.responsesSent=t.responsesSent,e.availableOutgoingBitrate=t.availableOutgoingBitrate,e.availableIncomingBitrate=t.availableIncomingBitrate;const a=n.get(t.remoteCandidateId),c=n.get(t.localCandidateId);e.usingTurn=!1,c&&/relay/i.test(c.candidateType||"")&&(e.usingTurn=!0,e.turnProtocol=c.relayProtocol),a&&c&&(e.localEp=`${c.protocol}:${c.address||c.ip}:${c.port} ${c.candidateType} (${c.networkType})`,e.remoteEp=`${a.protocol}:${a.address||a.ip}:${a.port} ${a.candidateType}`)}(u,i,t,s,n),u.lastRtcStatsTime=e.lastUpdateTime}if("inbound-rtp"===i.type||"outbound-rtp"===i.type){const o=i.mediaType||i.kind,d=i.ssrc;let p=i.trackIdentifier||a.ssrcToTrackId[d],h=null===(l=a._oldReport)||void 0===l?void 0:l.get(i.id);if(h&&h.mediaSourceId!==i.mediaSourceId){const e=n.get(i.mediaSourceId);e&&e.trackIdentifier&&(p=e.trackIdentifier,a.ssrcToTrackId[d]=p)}const f=t.find((e=>{var t;return(null===(t=e[o].track)||void 0===t?void 0:t.id)===p}))||s;if(!i.trackIdentifier&&a.ssrcToTrackId[d]&&(null===(u=f[o].track)||void 0===u?void 0:u.id)&&f[o].track.id!==a.ssrcToTrackId[d]&&(p=f[o].track.id,a.ssrcToTrackId[d]=f[o].track.id),a.currentSSRCs[d]=f.id,h){const e=n.get(i.transportId),t=a._oldReport.get(h.transportId);(t&&(null==e?void 0:e.selectedCandidatePairId)!==t.selectedCandidatePairId||i.bytesReceived<h.bytesReceived||i.bytesSent<h.bytesSent)&&(h=null)}const m=h?i.timestamp-h.timestamp:r,g=Of(e.statsByView,e.lastUpdateTime,c,f.id,p,d);!function(e,t,r,i,n){if(e.codec)return;e.kind=t.kind||t.mediaType,e.ssrc=t.ssrc,e.direction="inbound-rtp"===t.type?"in":"out";const s=t.codecId&&n.get(t.codecId);e.codec=s&&[s.mimeType,s.channels&&`${s.channels}ch`,s.clockRate,s.payloadType,t.encoderImplementation||t.decoderImplementation,s.sdpFmtpLine].filter(Boolean).join(" "),e.mid=t.mid,e.rid=t.rid}(g,i,0,0,n),function(e,t,r,i,n){const s=(t.nackCount||0)-((null==r?void 0:r.nackCount)||0);if(e.nackCount=(e.nackCount||0)+s,e.nackRate=1e3*s/i,"in"===e.direction){const n=t.packetsReceived-((null==r?void 0:r.packetsReceived)||0);e.packetCount=(e.packetCount||0)+n,e.packetRate=1e3*n/i;const s=t.packetsLost-((null==r?void 0:r.packetsLost)||0);e.packetLossCount=(e.packetLossCount||0)+s,e.packetLossRate=1e3*s/i,e.lossRatio=s/(s+n)*1e3/i;const o=t.bytesReceived-((null==r?void 0:r.bytesReceived)||0);e.byteCount=(e.byteCount||0)+o;let a=0;t.headerBytesReceived&&(a=t.headerBytesReceived-((null==r?void 0:r.headerBytesReceived)||0),e.headerByteCount=(e.headerByteCount||0)+a);const c=o+a;if(e.bitrate=8e3*c/i,e.mediaRatio=o/c,"audio"===t.kind){const i=(t.fecBytesReceived||0)-((null==r?void 0:r.fecBytesReceived)||0);e.fecRatio=i/o}const d=(t.jitterBufferDelay||0)-((null==r?void 0:r.jitterBufferDelay)||0),l=(t.jitterBufferEmittedCount||0)-((null==r?void 0:r.jitterBufferEmittedCount)||0);e.jitter=l?d/l:0}else{const s=t.packetsSent-((null==r?void 0:r.packetsSent)||0);e.packetCount=(e.packetCount||0)+s,e.packetRate=1e3*s/i;const o=t.bytesSent-((null==r?void 0:r.bytesSent)||0);e.byteCount=(e.byteCount||0)+o;let a=0;t.headerBytesSent&&(a=t.headerBytesSent-((null==r?void 0:r.headerBytesSent)||0),e.headerByteCount=(e.headerByteCount||0)+a);const c=o+a;e.bitrate=8e3*c/i,e.mediaRatio=o/c;const d=t.totalPacketSendDelay-((null==r?void 0:r.totalPacketSendDelay)||0);e.sendDelay=d/s;const l=t.retransmittedPacketsSent-((null==r?void 0:r.retransmittedPacketsSent)||0);if(e.retransRatio=l/s*1e3/i,t.remoteId){const r=n.get(t.remoteId);r&&(e.roundTripTime=r.roundTripTime||0,e.jitter=r.jitter||0,e.fractionLost=r.fractionLost||0)}}}(g,i,h,m,n),"video"===o&&function(e,t,r,i,n){e.width=t.frameWidth,e.height=t.frameHeight,e.qualityLimitationReason=t.qualityLimitationReason||"";const s=t.pliCount-((null==r?void 0:r.pliCount)||0);e.pliCount=(e.pliCount||0)+s,e.pliRate=1e3*s/i;const o=t.firCount-((null==r?void 0:r.firCount)||0);if(e.firCount=(e.firCount||0)+o,e.firRate=1e3*o/i,"in"===e.direction){const n=t.keyFramesDecoded-((null==r?void 0:r.keyFramesDecoded)||0);e.kfCount=(e.kfCount||0)+n,e.kfRate=1e3*n/i;const s=t.framesDecoded-((null==r?void 0:r.framesDecoded)||0);e.frameCount=(e.frameCount||0)+s;const o=t.qpSum-((null==r?void 0:r.qpSum)||0);e.qpf=o/s,e.fps=1e3*s/i}else{const s=t.keyFramesEncoded-((null==r?void 0:r.keyFramesEncoded)||0);e.kfCount=(e.kfCount||0)+s,e.kfRate=1e3*s/i;const o=t.framesEncoded-((null==r?void 0:r.framesEncoded)||0);e.frameCount=(e.frameCount||0)+o;const a=t.qpSum-((null==r?void 0:r.qpSum)||0);e.qpf=a/o,e.fps=1e3*o/i;const c=t.totalEncodeTime-((null==r?void 0:r.totalEncodeTime)||0);if(e.encodeTime=c/o,t.mediaSourceId){const r=n.get(t.mediaSourceId);r&&(e.sourceWidth=r.width||0,e.sourceHeight=r.height||0,e.sourceFps=r.framesPerSecond||0)}}}(g,i,h,m,n),"audio"===o&&function(e,t,r,i,n){const s=t.packetsDiscarded-((null==r?void 0:r.packetsDiscarded)||0);if(e.packetsDiscarded=(e.packetsDiscarded||0)+s,"in"===e.direction){const i=t.totalAudioEnergy-((null==r?void 0:r.totalAudioEnergy)||0),n=t.totalSamplesDuration-((null==r?void 0:r.totalSamplesDuration)||0);e.audioLevel=Math.sqrt(i/n);const s=t.totalSamplesReceived||0,o=t.concealmentEvents||0,a=s-((null==r?void 0:r.totalSamplesReceived)||0),c=t.concealedSamples||0,d=c-((null==r?void 0:r.concealedSamples)||0),l=(t.silentConcealedSamples||0)-((null==r?void 0:r.silentConcealedSamples)||0),u=(t.insertedSamplesForDeceleration||0)-((null==r?void 0:r.insertedSamplesForDeceleration)||0),p=(t.removedSamplesForAcceleration||0)-((null==r?void 0:r.removedSamplesForAcceleration)||0);e.audioSamples=s,e.audioConcealmentEvents=o,e.audioConcealedSamples=c,e.audioConcealment=d?d/a:0,e.audioSilentConcealment=l?l/a:0,e.audioAcceleration=p?p/a:0,e.audioDeceleration=u?u/a:0}}(g,i,h)}})),a._oldReport=n,Object.keys(a.previousSSRCs).filter((e=>!a.currentSSRCs[e])).forEach((t=>{const r=a.previousSSRCs[t];if(r){const i=e.statsByView[r];i&&Object.values(i.tracks).forEach((e=>{e.ssrcs[t]&&delete e.ssrcs[t]}))}}))})),Ef(e.statsByView,e.lastUpdateTime),Object.entries((null==o?void 0:o.candidatePairs)||{}).forEach((([t,r])=>{const i=r.lastRtcStatsTime===e.lastUpdateTime;r.active=i,i||(r.state="old/inactive",r.inactiveFromTime?e.lastUpdateTime-r.inactiveFromTime>4e3&&delete o.candidatePairs[t]:r.inactiveFromTime=e.lastUpdateTime)})),i)return e.statsByView;e.subscriptions.forEach((r=>{var i;return null===(i=r.onUpdatedStats)||void 0===i?void 0:i.call(r,e.statsByView,t)}))}catch(r){t.warn(r),e.numFailedStatsReports++,wf.sendEvent("collectStatsFailed",{name:null==r?void 0:r.name,cause:null==r?void 0:r.cause,message:null==r?void 0:r.message})}e.nextTimeout=setTimeout(n,r)}))}const If={};function xf(e,t=If,r=window.document){e.forEach((({hostnamePattern:e,token:i})=>{const n=`${e}-${i}`;if(!t[n]&&e.test(r.location.hostname)){const e=r.createElement("meta");e.httpEquiv="origin-trial",e.content=i,r.head.append(e),t[n]=!0}}))}const Mf={sampleRate:1,originTrials:[{hostnamePattern:/hereby\.dev/,token:"AkSNPHJw6EK08X0QU7kORnK9NABzRLAC7dqfXOwk5JwFAQG4Ey7WxLXxsnhieCgC1QHUdevE2EFICy7uBGDANwUAAABqeyJvcmlnaW4iOiJodHRwczovL2hlcmVieS5kZXY6NDQ0MyIsImZlYXR1cmUiOiJDb21wdXRlUHJlc3N1cmVfdjIiLCJleHBpcnkiOjE3MTY5NDA3OTksImlzU3ViZG9tYWluIjp0cnVlfQ=="},{hostnamePattern:/whereby\.com/,token:"Asc2wu8KpSx648i932NICteQDFcB05yl2QUUSHD7AQo8JGP2Fp6FF91TvYVJBsKGzLMH349rysPw5q9tqPC/PAUAAABqeyJvcmlnaW4iOiJodHRwczovL3doZXJlYnkuY29tOjQ0MyIsImZlYXR1cmUiOiJDb21wdXRlUHJlc3N1cmVfdjIiLCJleHBpcnkiOjE3MTY5NDA3OTksImlzU3ViZG9tYWluIjp0cnVlfQ=="}]};const jf={currentMonitor:null,getClients:()=>[],lastUpdateTime:0,statsByView:{},subscriptions:[],numFailedStatsReports:0},Lf={interval:2e3,logger:new hf},Af=()=>{var e;return null===(e=jf.currentMonitor)||void 0===e?void 0:e.getUpdatedStats()};function Nf(e,{interval:t,logger:r}){const i=Df.bind(null,e,{interval:t,logger:r});let n;try{n=function(e,{sampleRate:t,originTrials:r}=Mf,i=globalThis.window){let n;if(xf(r),"PressureObserver"in i)return n=new i.PressureObserver(e,{sampleRate:t}),n.observe("cpu",{sampleInterval:1e3*t}),{stop:()=>{n.unobserve("cpu")}}}((t=>e.lastPressureObserverRecord=t.pop()))}catch(e){r.warn("Failed to observe CPU pressure",e)}return setTimeout(i,t),{getUpdatedStats:()=>i(!0),stop:()=>{clearTimeout(e.nextTimeout),n&&n.stop()}}}var Bf;const Ff=null!==(Bf=pi.default)&&void 0!==Bf?Bf:pi,zf=new hf,Vf=Ff.browserDetails.browser,Uf=Ff.browserDetails.version;function $f(e,t){let r=e.match(/a=ssrc-group:FID (\d+) (\d+)\r\n/),i=t.match(/a=ssrc-group:FID (\d+) (\d+)\r\n/);r||(r=e.match(/a=ssrc:(\d+) cname:(.*)\r\n/g)[1].match(/a=ssrc:(\d+)/),i=t.match(/a=ssrc:(\d+) cname:(.*)\r\n/g)[1].match(/a=ssrc:(\d+)/));for(let e=1;e<r.length;e++)t=t.replace(new RegExp(i[e],"g"),r[e]);return t}function Gf(e){return"firefox"!==Vf?e:ti.splitLines(e.trim()).map((e=>e.startsWith("a=msid-semantic:")?"a=msid-semantic: WMS *":e)).join("\r\n")+"\r\n"}function qf(e){return function(e,t,r=!1,i=!1){var n,s;try{const o=Li(e);if((null===(n=null==o?void 0:o.ext)||void 0===n?void 0:n.length)&&o.ext.length>0)return e;if((null==o?void 0:o.media.length)<1)return e;const a=null==o?void 0:o.media.flatMap((e=>e.ext||[])),c=(null===(s=a.find((e=>e.uri===t)))||void 0===s?void 0:s.value)||[...new Set([0,15,...a.map((e=>e.value))])].sort(((e,t)=>e-t)).find(((e,t,r)=>e+1!==r[t+1]))+1;return o.media.forEach((e=>{var n;(r&&"audio"===e.type||i&&"video"===e.type)&&((null===(n=e.ext)||void 0===n?void 0:n.find((e=>e.uri===t)))||(Array.isArray(e.ext)?e.ext.push({value:c,uri:t}):e.ext=[{value:c,uri:t}]))})),ji(o)}catch(e){console.error("Error during addAbsCaptureTimeExtMap: ",e)}return e}(e,"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",!0,!0)}function Hf(e,t,r=console){const i=e.getSenders().find((e=>e.track&&"video"===e.track.kind));if(!i)return Promise.resolve();const n=i.getParameters();return n.encodings&&0===n.encodings.length?Promise.resolve():(n.encodings||(n.encodings=[{}]),0===t?delete n.encodings[0].maxBitrate:n.encodings[0].maxBitrate=1e3*t,i.setParameters(n).catch((e=>{r.error("setParameters err: ",e)})))}const Wf=400;var Kf;const Jf=null!==(Kf=pi.default)&&void 0!==Kf?Kf:pi,Xf=new hf;class Qf{constructor({peerConnectionId:e,bandwidth:t,maximumTurnBandwidth:r,deprioritizeH264Encoding:i}){this.peerConnectionId=e,this.relayCandidateSeen=!1,this.serverReflexiveCandidateSeen=!1,this.publicHostCandidateSeen=!1,this.ipv6HostCandidateSeen=!1,this.ipv6HostCandidateTeredoSeen=!1,this.ipv6HostCandidate6to4Seen=!1,this.mdnsHostCandidateSeen=!1,this.pc=null,this.wasEverConnected=!1,this.connectionStatus=null,this.stats={totalSent:0,totalRecv:0},this.bandwidth=t||0,this.maximumTurnBandwidth=r,this.pending=[],this.isOperationPending=!1,this.streamIds=[],this.streams=[],this.earlyIceCandidates=[],this.afterConnected=new Promise((e=>{this.registerConnected=e})),this.offerOptions={offerToReceiveAudio:!0,offerToReceiveVideo:!0},this._deprioritizeH264Encoding=i}setAndGetPeerConnection({clientId:e,constraints:t,peerConnectionConfig:r,shouldAddLocalVideo:i}){return this.peerConnectionConfig=r,this.shouldAddLocalVideo=i,this.clientId=e,this.pc=new RTCPeerConnection(r),this.signalingState=this.pc.signalingState,this.pc.addEventListener("signalingstatechange",(()=>{if(this.signalingState!==this.pc.signalingState&&(this.signalingState=this.pc.signalingState,"stable"===this.pc.signalingState)){this.isOperationPending=!1;const e=this.pending.shift();e&&e.apply()}})),this.pc}addStream(e){this.streamIds.push(e.id),this.streams.push(e),RTCPeerConnection.prototype.addTrack?(e.getAudioTracks().forEach((t=>{this.pc.addTrack(t,e)})),e.getVideoTracks().forEach((t=>{this.pc.addTrack(t,e)}))):this.pc.addStream(e)}addTrack(e,t){t||(t=this.streams[0]),null==t||t.addTrack(e),this.pc.addTrack(e,t)}removeTrack(e){this.streams[0].removeTrack(e);const t=this.pc.getSenders().find((t=>t.track===e));t&&this.pc.removeTrack(t)}removeStream(e){for(let t=0;t<this.streamIds.length;t++)this.streamIds[t]===e.id&&(this.streamIds.splice(t,1),this.streams.splice(t,1));this.pc&&(this.pc.removeTrack?e.getTracks().forEach((e=>{const t=this.pc.getSenders().find((t=>t.track===e));t&&this.pc.removeTrack(t)})):this.pc.removeStream&&this.pc.removeStream(e))}_setRemoteDescription(e){return this._deprioritizeH264Encoding&&(e.sdp=function(e){return ti.splitSections(e).map((e=>{if("video"!==ti.getKind(e))return e;const t=ti.matchPrefix(e,"a=rtpmap:").map((e=>ti.parseRtpMap(e))).filter((e=>/h264/i.test(e.name))).map((e=>""+e.payloadType));if(!t.length)return e;const r=ti.matchPrefix(e,"m=video")[0],i=/(\s\d+)+$/i.exec(r),n=i?i[0]:"",s=[...n.split(" ").filter((e=>e&&!t.includes(e))),...t].join(" "),o=r.replace(n," "+s);return e.replace(r,o)})).join("")}(e.sdp)),this.srdComplete=this.pc.setRemoteDescription(e),this.srdComplete.then((()=>{this.earlyIceCandidates.forEach((e=>this.pc.addIceCandidate(e))),this.earlyIceCandidates=[]}))}handleOffer(e){if(!this.canModifyPeerConnection())return new Promise((t=>{this.pending.push((()=>this.handleOffer(e).then(t)))}));this.isOperationPending=!0;let t=e.sdp;t=function(e){return"safari"!==Vf&&("firefox"!==Vf||Uf&&Uf>=63||60===Uf)?e:ti.splitLines(e.trim()).filter((e=>!e.startsWith("a=extmap:")||"urn:ietf:params:rtp-hdrext:sdes:mid"!==ti.parseExtmap(e).uri)).join("\r\n")+"\r\n"}(t),t=Gf(t);const r={type:e.type,sdp:t};let i;return this._setRemoteDescription(r).then((()=>this.pc.createAnswer())).then((e=>(i=e,this.pc.setLocalDescription(e)))).then((()=>Hf(this.pc,this.bandwidth))).then((()=>i))}handleAnswer(e){const t=Gf(e.sdp),r={type:e.type,sdp:t};return this._setRemoteDescription(r).then((()=>Hf(this.pc,this.bandwidth)),(e=>{Xf.warn("Could not set remote description from remote answer: ",e)}))}addIceCandidate(e){this.srdComplete?this.srdComplete.then((()=>{"closed"!==this.pc.signalingState&&("safari"===Jf.browserDetails.browser&&e&&""===e.candidate||this.pc.addIceCandidate(e).catch((t=>{Xf.warn("Failed to add ICE candidate ('%s'): %s",e?e.candidate:null,t)})))})):this.earlyIceCandidates.push(e)}canModifyPeerConnection(){return"stable"===this.pc.signalingState&&!this.isOperationPending}close(){const e=this.pc;if(e){e.oniceconnectionstatechange=null,e.onicecandidate=null,e.ontrack=null;try{e.close()}catch(e){Xf.warn("failures during close of session",e)}}}hasConnectedPeerConnection(){return this.pc&&"connected"===this.pc.connectionState}replaceTrack(e,t){const r=this.pc;if(!r)return!1;const i=r.getSenders();if(e||(e=(i.find((e=>e.track&&e.track.kind===t.kind))||{}).track),window.RTCRtpSender&&window.RTCRtpSender.prototype.replaceTrack){if(e){const r=()=>{for(let r=0;r<i.length;r++){const n=i[r].track;if((null==n?void 0:n.id)===t.id)return Promise.resolve(t);if((null==n?void 0:n.id)===e.id)return i[r].replaceTrack(t)}return null};let n=r();if(n)return n;let s=null,o=null;n=new Promise(((e,t)=>{s=e,o=t}));let a=0,c=setInterval((()=>ff(this,void 0,void 0,(function*(){const e=r();if(!e)return void(3<++a&&(clearInterval(c),c=null,o("No sender track to replace")));clearInterval(c),c=null;const t=yield e;s(t)}))),1e3);return n}const n=this.streams.find((e=>e.getTracks().find((e=>e.id===t.id))))||this.streams[0];return n?r.addTrack(t,n):Promise.reject(new Error("replaceTrack: No stream?"))}if(!this.canModifyPeerConnection())return void this.pending.push((()=>{this.replaceTrack(e,t)}));this.isOperationPending=!0;const n=r.onnegotiationneeded;return r.onnegotiationneeded=null,this.removeTrack(e),this.addTrack(t),setTimeout((()=>{r.onnegotiationneeded=n}),0),"offer"===r.localDescription.type?r.createOffer().then((e=>(e.sdp=$f(r.localDescription.sdp,e.sdp),r.setLocalDescription(e)))).then((()=>this._setRemoteDescription(r.remoteDescription))):this._setRemoteDescription(r.remoteDescription).then((()=>r.createAnswer())).then((e=>(e.sdp=$f(r.localDescription.sdp,e.sdp),r.setLocalDescription(e))))}maybeRestrictRelayBandwidth(){var e;-1!==this.maximumTurnBandwidth&&(this.pc.getStats&&(e=this.pc,e.getStats(null).then((e=>{let t,r;return e.forEach((i=>{if("transport"===i.type&&i.selectedCandidatePairId){const n=e.get(i.selectedCandidatePairId);if(!n)return;return t=e.get(n.localCandidateId).candidateType,void(r=e.get(n.remoteCandidateId).candidateType)}"candidate-pair"===i.type&&i.selected&&(t=e.get(i.localCandidateId).candidateType,r=e.get(i.remoteCandidateId).candidateType)})),"relay"===t||"relayed"===t||"relay"===r||"relayed"===r}))).then((e=>{e&&0===this.bandwidth&&this.changeBandwidth(this.maximumTurnBandwidth)})))}changeBandwidth(e){e!==this.bandwidth&&(this.canModifyPeerConnection()?(this.bandwidth=e,this.pc.localDescription&&""!==this.pc.localDescription.type&&Hf(this.pc,this.bandwidth)):this.pending.push((()=>this.changeBandwidth(e))))}setAudioOnly(e,t=[]){this.pc.getTransceivers().filter((e=>{var r,i,n,s,o,a;return"recvonly"!==(null==e?void 0:e.direction)&&"video"===(null===(i=null===(r=null==e?void 0:e.receiver)||void 0===r?void 0:r.track)||void 0===i?void 0:i.kind)&&!t.includes(null===(s=null===(n=null==e?void 0:e.receiver)||void 0===n?void 0:n.track)||void 0===s?void 0:s.id)&&!t.includes(null===(a=null===(o=null==e?void 0:e.sender)||void 0===o?void 0:o.track)||void 0===a?void 0:a.id)})).forEach((t=>{t.direction=e?"sendonly":"sendrecv"}))}}var Zf;const Yf=null!==(Zf=pi.default)&&void 0!==Zf?Zf:pi;const em="fetch_mediaserver_config",tm="start_screenshare",rm="stop_screenshare",im="audio_enabled",nm="client_left",sm="mediaserver_config",om="new_client",am="screenshare_started",cm="screenshare_stopped",dm="room_joined",lm="video_enabled",um="ice_candidate",pm="ice_endofcandidates",hm="ready_to_receive_offer",fm="sdp_answer",mm="sdp_offer",gm="pending_client_left",vm="media_quality_changed",bm="client_connection_status_changed",ym="stream_added",wm="rtc_manager_created",_m="rtc_manager_destroyed",Sm="local_stream_track_added",Cm="local_stream_track_removed",Rm="connecting",km="connection_failed",Tm="connection_successful",Pm="connection_disconnected",Om="camera",Em="screen_share";const Dm=57600,Im=2.6041666666666665,xm=921600,Mm=1.0850694444444444;const jm="[a-fA-F\\d:]",Lm=e=>e&&e.includeBoundaries?`(?:(?<=\\s|^)(?=${jm})|(?<=${jm})(?=\\s|$))`:"",Am="(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}",Nm="[a-fA-F\\d]{1,4}",Bm=`\n(?:\n(?:${Nm}:){7}(?:${Nm}|:)| // 1:2:3:4:5:6:7:: 1:2:3:4:5:6:7:8\n(?:${Nm}:){6}(?:${Am}|:${Nm}|:)| // 1:2:3:4:5:6:: 1:2:3:4:5:6::8 1:2:3:4:5:6::8 1:2:3:4:5:6::1.2.3.4\n(?:${Nm}:){5}(?::${Am}|(?::${Nm}){1,2}|:)| // 1:2:3:4:5:: 1:2:3:4:5::7:8 1:2:3:4:5::8 1:2:3:4:5::7:1.2.3.4\n(?:${Nm}:){4}(?:(?::${Nm}){0,1}:${Am}|(?::${Nm}){1,3}|:)| // 1:2:3:4:: 1:2:3:4::6:7:8 1:2:3:4::8 1:2:3:4::6:7:1.2.3.4\n(?:${Nm}:){3}(?:(?::${Nm}){0,2}:${Am}|(?::${Nm}){1,4}|:)| // 1:2:3:: 1:2:3::5:6:7:8 1:2:3::8 1:2:3::5:6:7:1.2.3.4\n(?:${Nm}:){2}(?:(?::${Nm}){0,3}:${Am}|(?::${Nm}){1,5}|:)| // 1:2:: 1:2::4:5:6:7:8 1:2::8 1:2::4:5:6:7:1.2.3.4\n(?:${Nm}:){1}(?:(?::${Nm}){0,4}:${Am}|(?::${Nm}){1,6}|:)| // 1:: 1::3:4:5:6:7:8 1::8 1::3:4:5:6:7:1.2.3.4\n(?::(?:(?::${Nm}){0,5}:${Am}|(?::${Nm}){1,7}|:)) // ::2:3:4:5:6:7:8 ::2:3:4:5:6:7:8 ::8 ::1.2.3.4\n)(?:%[0-9a-zA-Z]{1,})? // %eth0 %1\n`.replace(/\s*\/\/.*$/gm,"").replace(/\n/g,"").trim(),Fm=new RegExp(`(?:^${Am}$)|(?:^${Bm}$)`),zm=new RegExp(`^${Am}$`),Vm=new RegExp(`^${Bm}$`),Um=e=>e&&e.exact?Fm:new RegExp(`(?:${Lm(e)}${Am}${Lm(e)})|(?:${Lm(e)}${Bm}${Lm(e)})`,"g");Um.v4=e=>e&&e.exact?zm:new RegExp(`${Lm(e)}${Am}${Lm(e)}`,"g"),Um.v6=e=>e&&e.exact?Vm:new RegExp(`${Lm(e)}${Bm}${Lm(e)}`,"g");var $m="connection_blocked_by_network",Gm="ice_ipv6_seen",qm="ice_mdns_seen",Hm="ice_no_public_ip_gathered",Wm="ice_no_public_ip_gathered_3sec",Km="ice_restart",Jm="microphone_not_working",Xm="microphone_stopped_working",Qm="camera_stopped_working",Zm="new_pc",Ym="sfu_connection_open",eg="sfu_connection_closed",tg="sfu_connection_info",rg="dominant_speaker",ig="pc_sld_failure",ng="pc_on_answer_failure",sg="pc_on_offer_failure";class og extends Error{constructor(e){super(e.message),this.name="AssertionError",this.code="ERR_ASSERTION",this.actual=e.actual,this.expected=e.expected,this.operator=e.operator,Error.captureStackTrace&&Error.captureStackTrace(this,e.stackStartFn)}}function ag(e){if(e.message instanceof Error)throw e.message;throw new og(e)}function cg(...e){!function(e,t,r,i){if(!r){let n=!1;if(0===t)n=!0,i="No value argument passed to `assert.ok()`";else if(i instanceof Error)throw i;const s=new og({actual:r,expected:!0,message:i,operator:"==",stackStartFn:e});throw s.generatedMessage=n,s}}(cg,e.length,...e)}const dg={fail:e=>{ag({actual:"fail()",expected:"fail() should not be called",message:e,operator:"fail",stackStartFn:dg.fail})},ok:cg,notEqual:function e(t,r,i){if(arguments.length<2)throw new Error("'actual' and 'expected' arguments are required");t==r&&ag({actual:t,expected:r,message:i,operator:"!=",stackStartFn:e})}};dg.ok=cg;const lg=new as("Safari17"),ug={OS:1024,MIS:1024};class pg extends Ya{static createFactory(){return()=>new pg}constructor(){super(),this._closed=!1,this._mapMidTransceiver=new Map,this._sendStream=new MediaStream,this._hasDataChannelMediaSection=!1,this._nextSendSctpStreamId=0,this._transportReady=!1}get name(){return"Safari17"}close(){if(lg.debug("close()"),!this._closed){if(this._closed=!0,this._pc)try{this._pc.close()}catch(e){}this.emit("@close")}}getNativeRtpCapabilities(){return ff(this,void 0,void 0,(function*(){lg.debug("getNativeRtpCapabilities()");const e=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"});try{e.addTransceiver("audio"),e.addTransceiver("video");const t=yield e.createOffer();try{e.close()}catch(e){}const r=Li(t.sdp),i=Ga({sdpObject:r});return Qa(i),i}catch(t){try{e.close()}catch(e){}throw t}}))}getNativeSctpCapabilities(){return ff(this,void 0,void 0,(function*(){return lg.debug("getNativeSctpCapabilities()"),{numStreams:ug}}))}run({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,extendedRtpCapabilities:d}){this.assertNotClosed(),lg.debug("run()"),this._direction=e,this._remoteSdp=new fc({iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n}),this._sendingRtpParametersByKind={audio:ho("audio",d),video:ho("video",d)},this._sendingRemoteRtpParametersByKind={audio:fo("audio",d),video:fo("video",d)},i.role&&"auto"!==i.role&&(this._forcedLocalDtlsRole="server"===i.role?"client":"server"),this._pc=new RTCPeerConnection(Object.assign({iceServers:null!=s?s:[],iceTransportPolicy:null!=o?o:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"},a),c),this._pc.addEventListener("icegatheringstatechange",(()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)})),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",(()=>{this.emit("@connectionstatechange",this._pc.connectionState)})):this._pc.addEventListener("iceconnectionstatechange",(()=>{switch(lg.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.iceConnectionState){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected");break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed")}}))}updateIceServers(e){return ff(this,void 0,void 0,(function*(){this.assertNotClosed(),lg.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}))}restartIce(e){return ff(this,void 0,void 0,(function*(){if(this.assertNotClosed(),lg.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=yield this._pc.createOffer({iceRestart:!0});lg.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),yield this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};lg.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),yield this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};lg.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),yield this._pc.setRemoteDescription(e);const t=yield this._pc.createAnswer();lg.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",t),yield this._pc.setLocalDescription(t)}}))}getTransportStats(){return ff(this,void 0,void 0,(function*(){return this.assertNotClosed(),this._pc.getStats()}))}send({track:e,encodings:t,codecOptions:r,codec:i,onRtpSender:n}){var s;return ff(this,void 0,void 0,(function*(){this.assertNotClosed(),this.assertSendDirection(),lg.debug("send() [kind:%s, track.id:%s]",e.kind,e.id);const o=As(this._sendingRtpParametersByKind[e.kind]);o.codecs=mo(o.codecs,i),t&&t.length>1&&t.every((({rid:e})=>!e))&&(t=t.map(((e,t)=>(e.rid=`r${t}`,e)))),t&&(o.encodings||(o.encodings=[]),Object.assign(o.encodings,t));const a=yc((null!=t?t:[{}])[0].scalabilityMode);if(o.encodings&&o.encodings.length>1&&("video/vp8"===o.codecs[0].mimeType.toLowerCase()||"video/h264"===o.codecs[0].mimeType.toLowerCase()))for(const e of o.encodings)e.scalabilityMode?e.scalabilityMode=`L1T${a.temporalLayers}`:e.scalabilityMode="L1T3";const c=As(this._sendingRemoteRtpParametersByKind[e.kind]);c.codecs=mo(c.codecs,i);const d=this._remoteSdp.getNextMediaSectionIdx(),l=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream],sendEncodings:"video"===e.kind?t:void 0});n&&n(l.sender);const u=yield this._pc.createOffer(),p=Li(u.sdp);let h=p.media[d.idx];this._transportReady||(yield this.setupTransport({localDtlsRole:null!==(s=this._forcedLocalDtlsRole)&&void 0!==s?s:"client",localSdpObject:p})),lg.debug("send() | calling pc.setLocalDescription() [offer:%o]",u),yield this._pc.setLocalDescription(u);const f=l.mid;o.mid=f,h=p.media[d.idx],o.rtcp.cname=Ha({offerMediaObject:h}),this._remoteSdp.send({offerMediaObject:h,reuseMid:d.reuseMid,offerRtpParameters:o,answerRtpParameters:c,codecOptions:r});const m={type:"answer",sdp:this._remoteSdp.getSdp()};return lg.debug("send() | calling pc.setRemoteDescription() [answer:%o]",m),yield this._pc.setRemoteDescription(m),this._mapMidTransceiver.set(f,l),{localId:f,rtpParameters:o,rtpSender:l.sender}}))}stopSending(e){return ff(this,void 0,void 0,(function*(){if(this.assertSendDirection(),this._closed)return;lg.debug("stopSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.sender.replaceTrack(null),this._pc.removeTrack(t.sender);if(this._remoteSdp.closeMediaSection(t.mid))try{t.stop()}catch(e){}const r=yield this._pc.createOffer();lg.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r),yield this._pc.setLocalDescription(r);const i={type:"answer",sdp:this._remoteSdp.getSdp()};lg.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",i),yield this._pc.setRemoteDescription(i),this._mapMidTransceiver.delete(e)}))}pauseSending(e){return ff(this,void 0,void 0,(function*(){this.assertNotClosed(),this.assertSendDirection(),lg.debug("pauseSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="inactive",this._remoteSdp.pauseMediaSection(e);const r=yield this._pc.createOffer();lg.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),yield this._pc.setLocalDescription(r);const i={type:"answer",sdp:this._remoteSdp.getSdp()};lg.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",i),yield this._pc.setRemoteDescription(i)}))}resumeSending(e){return ff(this,void 0,void 0,(function*(){this.assertNotClosed(),this.assertSendDirection(),lg.debug("resumeSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="sendonly",this._remoteSdp.resumeSendingMediaSection(e);const r=yield this._pc.createOffer();lg.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),yield this._pc.setLocalDescription(r);const i={type:"answer",sdp:this._remoteSdp.getSdp()};lg.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",i),yield this._pc.setRemoteDescription(i)}))}replaceTrack(e,t){return ff(this,void 0,void 0,(function*(){this.assertNotClosed(),this.assertSendDirection(),t?lg.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):lg.debug("replaceTrack() [localId:%s, no track]",e);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");yield r.sender.replaceTrack(t)}))}setMaxSpatialLayer(e,t){return ff(this,void 0,void 0,(function*(){this.assertNotClosed(),this.assertSendDirection(),lg.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const i=r.sender.getParameters();i.encodings.forEach(((e,r)=>{e.active=r<=t})),yield r.sender.setParameters(i),this._remoteSdp.muxMediaSectionSimulcast(e,i.encodings);const n=yield this._pc.createOffer();lg.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",n),yield this._pc.setLocalDescription(n);const s={type:"answer",sdp:this._remoteSdp.getSdp()};lg.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",s),yield this._pc.setRemoteDescription(s)}))}setRtpEncodingParameters(e,t){return ff(this,void 0,void 0,(function*(){this.assertNotClosed(),this.assertSendDirection(),lg.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const i=r.sender.getParameters();i.encodings.forEach(((e,r)=>{i.encodings[r]=Object.assign(Object.assign({},e),t)})),yield r.sender.setParameters(i),this._remoteSdp.muxMediaSectionSimulcast(e,i.encodings);const n=yield this._pc.createOffer();lg.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",n),yield this._pc.setLocalDescription(n);const s={type:"answer",sdp:this._remoteSdp.getSdp()};lg.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",s),yield this._pc.setRemoteDescription(s)}))}getSenderStats(e){return ff(this,void 0,void 0,(function*(){this.assertNotClosed(),this.assertSendDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.sender.getStats()}))}sendDataChannel({ordered:e,maxPacketLifeTime:t,maxRetransmits:r,label:i,protocol:n}){var s;return ff(this,void 0,void 0,(function*(){this.assertNotClosed(),this.assertSendDirection();const o={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmits:r,protocol:n};lg.debug("sendDataChannel() [options:%o]",o);const a=this._pc.createDataChannel(i,o);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%ug.MIS,!this._hasDataChannelMediaSection){const e=yield this._pc.createOffer(),t=Li(e.sdp),r=t.media.find((e=>"application"===e.type));this._transportReady||(yield this.setupTransport({localDtlsRole:null!==(s=this._forcedLocalDtlsRole)&&void 0!==s?s:"client",localSdpObject:t})),lg.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),yield this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:r});const i={type:"answer",sdp:this._remoteSdp.getSdp()};lg.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",i),yield this._pc.setRemoteDescription(i),this._hasDataChannelMediaSection=!0}return{dataChannel:a,sctpStreamParameters:{streamId:o.id,ordered:o.ordered,maxPacketLifeTime:o.maxPacketLifeTime,maxRetransmits:o.maxRetransmits}}}))}receive(e){var t,r;return ff(this,void 0,void 0,(function*(){this.assertNotClosed(),this.assertRecvDirection();const i=[],n=new Map;for(const r of e){const{trackId:e,kind:i,rtpParameters:s,streamId:o}=r;lg.debug("receive() [trackId:%s, kind:%s]",e,i);const a=null!==(t=s.mid)&&void 0!==t?t:String(this._mapMidTransceiver.size);n.set(e,a),this._remoteSdp.receive({mid:a,kind:i,offerRtpParameters:s,streamId:null!=o?o:s.rtcp.cname,trackId:e})}const s={type:"offer",sdp:this._remoteSdp.getSdp()};lg.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",s),yield this._pc.setRemoteDescription(s);for(const t of e){const{trackId:e,onRtpReceiver:r}=t;if(r){const t=n.get(e),i=this._pc.getTransceivers().find((e=>e.mid===t));if(!i)throw new Error("transceiver not found");r(i.receiver)}}let o=yield this._pc.createAnswer();const a=Li(o.sdp);for(const t of e){const{trackId:e,rtpParameters:r}=t,i=n.get(e),s=a.media.find((e=>String(e.mid)===i));Wa({offerRtpParameters:r,answerMediaObject:s})}o={type:"answer",sdp:ji(a)},this._transportReady||(yield this.setupTransport({localDtlsRole:null!==(r=this._forcedLocalDtlsRole)&&void 0!==r?r:"client",localSdpObject:a})),lg.debug("receive() | calling pc.setLocalDescription() [answer:%o]",o),yield this._pc.setLocalDescription(o);for(const t of e){const{trackId:e}=t,r=n.get(e),s=this._pc.getTransceivers().find((e=>e.mid===r));if(!s)throw new Error("new RTCRtpTransceiver not found");this._mapMidTransceiver.set(r,s),i.push({localId:r,track:s.receiver.track,rtpReceiver:s.receiver})}return i}))}stopReceiving(e){return ff(this,void 0,void 0,(function*(){if(this.assertRecvDirection(),this._closed)return;for(const t of e){lg.debug("stopReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(e.mid)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};lg.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),yield this._pc.setRemoteDescription(t);const r=yield this._pc.createAnswer();lg.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",r),yield this._pc.setLocalDescription(r);for(const t of e)this._mapMidTransceiver.delete(t)}))}pauseReceiving(e){return ff(this,void 0,void 0,(function*(){this.assertNotClosed(),this.assertRecvDirection();for(const t of e){lg.debug("pauseReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="inactive",this._remoteSdp.pauseMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};lg.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),yield this._pc.setRemoteDescription(t);const r=yield this._pc.createAnswer();lg.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",r),yield this._pc.setLocalDescription(r)}))}resumeReceiving(e){return ff(this,void 0,void 0,(function*(){this.assertNotClosed(),this.assertRecvDirection();for(const t of e){lg.debug("resumeReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};lg.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),yield this._pc.setRemoteDescription(t);const r=yield this._pc.createAnswer();lg.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",r),yield this._pc.setLocalDescription(r)}))}getReceiverStats(e){return ff(this,void 0,void 0,(function*(){this.assertNotClosed(),this.assertRecvDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.receiver.getStats()}))}receiveDataChannel({sctpStreamParameters:e,label:t,protocol:r}){var i;return ff(this,void 0,void 0,(function*(){this.assertNotClosed(),this.assertRecvDirection();const{streamId:n,ordered:s,maxPacketLifeTime:o,maxRetransmits:a}=e,c={negotiated:!0,id:n,ordered:s,maxPacketLifeTime:o,maxRetransmits:a,protocol:r};lg.debug("receiveDataChannel() [options:%o]",c);const d=this._pc.createDataChannel(t,c);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();const e={type:"offer",sdp:this._remoteSdp.getSdp()};lg.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),yield this._pc.setRemoteDescription(e);const t=yield this._pc.createAnswer();if(!this._transportReady){const e=Li(t.sdp);yield this.setupTransport({localDtlsRole:null!==(i=this._forcedLocalDtlsRole)&&void 0!==i?i:"client",localSdpObject:e})}lg.debug("receiveDataChannel() | calling pc.setRemoteDescription() [answer:%o]",t),yield this._pc.setLocalDescription(t),this._hasDataChannelMediaSection=!0}return{dataChannel:d}}))}setupTransport({localDtlsRole:e,localSdpObject:t}){return ff(this,void 0,void 0,(function*(){t||(t=Li(this._pc.localDescription.sdp));const r=qa({sdpObject:t});r.role=e,this._remoteSdp.updateDtlsRole("client"===e?"server":"client"),yield new Promise(((e,t)=>{this.safeEmit("@connect",{dtlsParameters:r},e,t)})),this._transportReady=!0}))}assertNotClosed(){if(this._closed)throw new xs("method called in a closed handler")}assertSendDirection(){if("send"!==this._direction)throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if("recv"!==this._direction)throw new Error('method can just be called for handlers with "recv" direction')}}const hg={codecOptions:{opusDtx:!0,opusFec:!0},encodings:[{dtx:!0}]},fg={codecOptions:{videoGoogleStartBitrate:500},encodings:[{scaleResolutionDownBy:4,maxBitrate:15e4},{scaleResolutionDownBy:2,maxBitrate:5e5},{scaleResolutionDownBy:1,maxBitrate:1e6}]},mg={codecOptions:{videoGoogleStartBitrate:500},encodings:[{scaleResolutionDownBy:2,maxBitrate:15e4},{scaleResolutionDownBy:1,maxBitrate:5e5}]},gg={codecOptions:{videoGoogleStartBitrate:500},encodings:[{scalabilityMode:"L3T2_KEY"}]},vg={codecOptions:{videoGoogleStartBitrate:500},encodings:[{scalabilityMode:"L2T2_KEY",maxBitrate:8e5}]},bg={encodings:[{}]},yg={encodings:[{maxBitrate:6e5,maxFramerate:2}]},wg={encodings:[{scaleResolutionDownBy:2,dtx:!0,maxBitrate:5e5},{scaleResolutionDownBy:1,dtx:!0,maxBitrate:15e5}]},_g={encodings:[{dtx:!0}]},Sg=(e,t,r)=>{const{lowDataModeEnabled:i,simulcastScreenshareOn:n,lowBandwidth:s,vp9On:o}=r;return"audio"===e?hg:t?s&&!o?yg:o?_g:n?wg:bg:s?o?vg:mg:o?gg:i?mg:fg};const Cg=new hf;class Rg extends Np{constructor(e){super(),this.reconnectThresholdInMs=0,this._socket=e,this._clients={},this._signalDisconnectTime=void 0,this.rtcManager=void 0,this.metrics={roomJoinedLate:0,pendingClientCanceled:0,evaluationFailed:0,roomJoined:0},e.on("disconnect",(()=>{this._signalDisconnectTime=Date.now()})),e.on(dm,(e=>this._onRoomJoined(e))),e.on(om,(e=>this._onNewClient(e))),e.on(nm,(e=>this._onClientLeft(e))),e.on(gm,(e=>this._onPendingClientLeft(e))),e.on(im,(e=>this._onAudioEnabled(e))),e.on(lm,(e=>this._onVideoEnabled(e))),e.on(am,(e=>this._onScreenshareChanged(e,!0))),e.on(cm,(e=>this._onScreenshareChanged(e,!1)))}_onRoomJoined(e){var t,r;return ff(this,void 0,void 0,(function*(){if(this.reconnectThresholdInMs=.8*(e.disconnectTimeout||0),!(null===(t=e.room)||void 0===t?void 0:t.clients))return void this.emit(dm,e);if(!e.selfId)return void this.emit(dm,e);const i=null===(r=e.room.clients.find((t=>e.selfId===t.id)))||void 0===r?void 0:r.deviceId;if(!i)return void this.emit(dm,e);if(!this._signalDisconnectTime)return this._resetClientState(e),e.room.clients=e.room.clients.filter((e=>!(e.deviceId===i&&e.isPendingToLeave))),void this.emit(dm,e);const n=.8*e.disconnectTimeout;if(Date.now()-this._signalDisconnectTime>n)return this._resetClientState(e),this.emit(dm,e),void this.metrics.roomJoinedLate++;e.room.clients=e.room.clients.filter((e=>!(e.deviceId===i&&e.isPendingToLeave)));const s=yield Af();e.room.clients.forEach((t=>{var r;try{if(t.id===e.selfId)return;if(!this._clients[t.id])return void this._addClientToState(t);if(!(null===(r=this.rtcManager)||void 0===r?void 0:r.hasClient(t.id)))return;if(this._hasClientStateChanged({clientId:t.id,webcam:t.isVideoEnabled,mic:t.isAudioEnabled,screenShare:t.streams.length>1}))return;if(this._wasClientSendingMedia(t.id)&&!this._isClientMediaActive(s,t.id))return;t.mergeWithOldClientState=!0}catch(e){Cg.error("Failed to evaluate if we should merge client state %o",e),this.metrics.evaluationFailed++}})),e.room.clients.forEach((e=>{e.isPendingToLeave&&this._onPendingClientLeft({clientId:e.id})})),this.metrics.roomJoined++,this.emit(dm,e)}))}_onClientLeft(e){var t;const{clientId:r}=e,i=this._clients[r];i&&(clearTimeout(i.timeout),delete this._clients[r]),null===(t=this.rtcManager)||void 0===t||t.disconnect(r,null,e.eventClaim),this.emit(nm,e)}_onPendingClientLeft(e){const{clientId:t}=e,r=this._clients[t];r?r.isPendingToLeave||(r.isPendingToLeave=!0,this._wasClientSendingMedia(t)&&(r.checkActiveMediaAttempts=0,this._abortIfNotActive(e))):Cg.warn(`client ${t} not found`)}_onNewClient(e){const{client:{id:t,deviceId:r}}=e,i=this._clients[t];if(i&&i.isPendingToLeave)return clearTimeout(i.timeoutHandler),i.isPendingToLeave=!1,void this.metrics.pendingClientCanceled++;this._getPendingClientsByDeviceId(r).forEach((e=>{clearTimeout(e.timeoutHandler),e.isPendingToLeave=void 0,this.emit(nm,{clientId:e.clientId})})),this._addClientToState(e.client),this.emit(om,e)}_abortIfNotActive(e){return ff(this,void 0,void 0,(function*(){const{clientId:t}=e;let r=this._clients[t];if(!(null==r?void 0:r.isPendingToLeave))return;if(r.checkActiveMediaAttempts++,r.checkActiveMediaAttempts>3)return;(yield this._checkIsActive(t))?r.timeoutHandler=setTimeout((()=>this._abortIfNotActive(e)),500):(r=this._clients[t],(null==r?void 0:r.isPendingToLeave)&&(clearTimeout(r.timeoutHandler),delete this._clients[t],this.emit(nm,e)))}))}_checkIsActive(e){return ff(this,void 0,void 0,(function*(){const t=yield Af();return this._isClientMediaActive(t,e)}))}_isClientMediaActive(e,t){const r=null==e?void 0:e[t];let i=!1;return r&&Object.entries(r.tracks).forEach((([e,t])=>{"probator"!==e&&Object.values(t.ssrcs).forEach((e=>{(e.bitrate||0)>0&&(i=!0)}))})),i}_onAudioEnabled(e){const{clientId:t,isAudioEnabled:r}=e;this._clients[t]=Object.assign(Object.assign({},this._clients[t]||{}),{isAudioEnabled:r})}_onVideoEnabled(e){const{clientId:t,isVideoEnabled:r}=e;this._clients[t]=Object.assign(Object.assign({},this._clients[t]||{}),{isVideoEnabled:r})}_onScreenshareChanged(e,t){const{clientId:r}=e;this._clients[r]=Object.assign(Object.assign({},this._clients[r]||{}),{isScreenshareEnabled:t})}_hasClientStateChanged({clientId:e,webcam:t,mic:r,screenShare:i}){const n=this._clients[e];if(!n)throw new Error(`Client ${e} not found in ReconnectManager state`);return t!==n.isVideoEnabled||(r!==n.isAudioEnabled||i!==n.isScreenshareEnabled)}_addClientToState(e){this._clients[e.id]=Object.assign(Object.assign({},this._clients[e.id]||{}),{isAudioEnabled:e.isAudioEnabled,isVideoEnabled:e.isVideoEnabled,isScreenshareEnabled:e.streams.length>1,deviceId:e.deviceId,isPendingToLeave:e.isPendingToLeave,clientId:e.id})}_wasClientSendingMedia(e){const t=this._clients[e];if(!t)throw new Error(`Client ${e} not found in ReconnectManager state`);return t.isAudioEnabled||t.isVideoEnabled||t.isScreenshareEnabled}_getPendingClientsByDeviceId(e){return Object.values(this._clients).filter((t=>t.deviceId===e&&t.isPendingToLeave))}_resetClientState(e){this._clients={},e.room.clients.forEach((t=>{t.id!==e.selfId&&this._addClientToState(t)}))}}var kg;const Tg=null!==(kg=pi.default)&&void 0!==kg?kg:pi;class Pg{constructor(e,t,r=!1){this._wasConnectedUsingWebsocket=!1,this._reconnectManager=null,this._socket=uf(e,Object.assign({path:"/protocol/socket.io/v4",randomizationFactor:.5,reconnectionDelay:250,reconnectionDelayMax:5e3,timeout:5e3,transports:["websocket"],withCredentials:!0},t)),this._socket.io.on("reconnect",(()=>{this._socket.sendBuffer=[]})),this._socket.io.on("reconnect_attempt",(()=>{this._wasConnectedUsingWebsocket?(this._socket.io.opts.transports=["websocket"],"safari"!==Tg.browserDetails.browser&&delete this._wasConnectedUsingWebsocket):this._socket.io.opts.transports=["websocket","polling"]})),r&&(this._reconnectManager=new Rg(this._socket)),this._socket.on("connect",(()=>{"websocket"===this.getTransport()&&(this._wasConnectedUsingWebsocket=!0,this.noopKeepaliveInterval||(this.noopKeepaliveInterval=setInterval((()=>{try{this._socket.connected&&this._socket.io.engine.sendPacket("noop")}catch(e){}}),2e3)))})),this._socket.on("disconnect",(()=>{this.disconnectTimestamp=Date.now(),this.noopKeepaliveInterval&&(clearInterval(this.noopKeepaliveInterval),this.noopKeepaliveInterval=null)}))}setRtcManager(e){this._reconnectManager&&(this._reconnectManager.rtcManager=e)}connect(){this.isConnected()||this.isConnecting()||this._socket.open()}disconnect(){this._socket.disconnect()}disconnectOnConnect(){this._socket.once("connect",(()=>{this._socket.disconnect()}))}emit(e,...t){this._socket.emit.apply(this._socket,arguments)}emitIfConnected(e,t){this.isConnected()&&this.emit(e,t)}getTransport(){return this._socket&&this._socket.io&&this._socket.io.engine&&this._socket.io.engine.transport&&this._socket.io.engine.transport.name}getManager(){return this._socket.io}isConnecting(){return this._socket&&this._socket.connecting}isConnected(){return this._socket&&this._socket.connected}on(e,t){const r=[dm,nm,om];return this._reconnectManager&&r.includes(e)?this._interceptEvent(e,t):(this._socket.on(e,t),()=>{this._socket.off(e,t)})}onEngineEvent(e,t){var r;return null===(r=this._socket.io)||void 0===r||r.on(e,t),()=>{var r;null===(r=this._socket.io)||void 0===r||r.off(e,t)}}once(e,t){this._socket.once(e,t)}off(e,t){this._socket.off(e,t)}_interceptEvent(e,t){return this._reconnectManager&&this._reconnectManager.on(e,t),()=>{this._reconnectManager&&this._reconnectManager.removeListener(e,t)}}getGlitchFreeMetrics(){var e;return null===(e=this._reconnectManager)||void 0===e?void 0:e.metrics}getReconnectThreshold(){var e;return null===(e=this._reconnectManager)||void 0===e?void 0:e.reconnectThresholdInMs}}const Og=(e,t)=>{if(!t.useOnlyTURN)return;e.iceTransportPolicy="relay";const r={onlyudp:/^turn:.*transport=udp$/,onlytcp:/^turn:.*transport=tcp$/,onlytls:/^turns:.*transport=tcp$/}[t.useOnlyTURN];r&&(e.iceServers=e.iceServers.filter((e=>e.url&&e.url.match(r)||e.urls&&(e.urls=(e.urls.some?e.urls:[e.urls]).filter((e=>e.match(r))),e.urls.length>0)?e:void 0)))},Eg=(e,t)=>{if(t&&e){const r=t,i=r.indexOf(":")>0?"":":443",n=":"+r+i;return e.map((e=>{const t=Object.assign({},e);return t.url&&(t.url=t.url.replace(/:[^?]*/,n)),t.urls&&(t.urls=t.urls.map((e=>e.replace(/:[^?]*/,n)))),t}))}return e},Dg=[{pattern:/^(?:([^.]+)[.])?(server:?\d*)/,separator:"."},{pattern:/^(?:([^.]+)[.])?(localhost:?\d*)/,separator:"."},{pattern:/^(?:([^.]+)[.])?((\d+[.]){3}:?\d*)$/,separator:"."},{pattern:/^(?:([^.]+)-)?(ip-[^.]*[.](?:hereby[.]dev|rfc1918[.]disappear[.]at)(?::\d+|))$/,separator:"-"},{pattern:/^(?:([^.]+)[.])?((:?[^.]+[.]){1,}[^.]+)$/,separator:"."}];function Ig({host:e="whereby.com",protocol:t="https:"}={}){let r="",i=e,n=".";for(const{separator:t,pattern:s}of Dg){const o=s.exec(e);if(o){r=o[1]||"",i=o[2],n=t;break}}const s=r?`${r}${n}${i}`:i;return{domain:i,domainWithSeparator:`${n}${i}`,organizationDomain:s,organization:`${t}//${s}`,service:`${t}//${i}`,subdomain:r}}var xg,Mg;Ig(window&&window.location);const jg=null!==(xg=pi.default)&&void 0!==xg?xg:pi,Lg=new hf,Ag=class{constructor(e,t){this.id=""+e,this.type=t,this.isEnabled=!0,this.hasSupportForAutoSuperSize=!1,this.isAudioEnabled=!0,this.isVideoEnabled=!0,this.status=Rm,this.stream=null,this.streamId=null}setup(e){return this.stream=e,this.streamId=e.id,this.setVideoEnabled(this.isVideoEnabled&&e.getVideoTracks().length>0),this.setAudioEnabled(this.isAudioEnabled&&e.getAudioTracks().length>0),this}setStatus(e){return this.status=e,this}setVideoEnabled(e){this.isVideoEnabled=e,this.stream&&this.stream.getVideoTracks().forEach((t=>{t.enabled=e}))}setAudioEnabled(e){this.isAudioEnabled=e,this.stream&&this.stream.getAudioTracks().forEach((t=>{t.enabled=e}))}static getCameraId(){return"0"}static getTypeFromId(e){return"0"===""+e?Om:Em}}.getCameraId(),Ng=jg.browserDetails.browser,Bg=jg.browserDetails.version;"firefox"===Ng&&jg.browserShim&&"shimGetDisplayMedia"in jg.browserShim&&(null===(Mg=jg.browserShim)||void 0===Mg||Mg.shimGetDisplayMedia(window,"screen"));let Fg=!1;"chrome"===Ng&&window.document.addEventListener("beforeunload",(()=>{Fg=!0}));class zg{constructor({selfId:e,room:t,emitter:r,serverSocket:i,webrtcProvider:n,features:s}){const{name:o,session:a,iceServers:c,turnServers:d,sfuServer:l,mediaserverConfigTtlSeconds:u}=t;this._selfId=e,this._roomName=o,this._roomSessionId=a&&a.id,this.peerConnections={},this.localStreams={},this.enabledLocalStreamIds=[],this._screenshareVideoTrackIds=[],this._socketListenerDeregisterFunctions=[],this._localStreamDeregisterFunction=null,this._emitter=r,this._serverSocket=i,this._webrtcProvider=n,this._features=s||{},this._isAudioOnlyMode=!1,this.offerOptions={offerToReceiveAudio:!0,offerToReceiveVideo:!0},this._pendingActionsForConnectedPeerConnections=[],this._audioTrackOnEnded=()=>{wf.sendEvent("audio_ended",{unloading:Fg}),this._emit(Xm,{})},this._videoTrackOnEnded=()=>{wf.sendEvent("video_ended",{unloading:Fg}),this._emit(Qm,{})},this._updateAndScheduleMediaServersRefresh({sfuServer:l,iceServers:(null==c?void 0:c.iceServers)||[],turnServers:d||[],mediaserverConfigTtlSeconds:u}),this.totalSessionsCreated=0}numberOfPeerconnections(){return Object.keys(this.peerConnections).length}isInitializedWith({selfId:e,roomName:t,isSfu:r}){return this._selfId===e&&this._roomName===t&&r===!!this._sfuServer}supportsScreenShareAudio(){return!0}maybeRestrictRelayBandwidth(e){e.maybeRestrictRelayBandwidth()}addNewStream(e,t,r,i,n=[]){if(t!==this.localStreams[e]){if(this._addLocalStream(e,t),e===Ag){this._addStreamToPeerConnections(t);const e=t.getAudioTracks()[0],r=t.getVideoTracks()[0];if(e){e.effectTrack||this._monitorAudioTrack(e);const t=n.find((e=>"audio"===e.kind));t&&this._monitorAudioTrack(t)}if(r){r.effectTrack||this._monitorVideoTrack(r);const e=n.find((e=>"video"===e.kind));e&&this._monitorVideoTrack(e)}this._localStreamDeregisterFunction&&(this._localStreamDeregisterFunction(),this._localStreamDeregisterFunction=null);const i=e=>{const{enable:t,track:r}=e.detail;this._handleStopOrResumeVideo({enable:t,track:r})};return t.addEventListener("stopresumevideo",i),void(this._localStreamDeregisterFunction=()=>{t.removeEventListener("stopresumevideo",i)})}this._screenshareVideoTrackIds.push(t.getVideoTracks()[0].id),this._shareScreen(e,t)}}replaceTrack(e,t){return"audio"!==t.kind||t.effectTrack||this._monitorAudioTrack(t),"video"!==t.kind||t.effectTrack||this._monitorVideoTrack(t),this._replaceTrackToPeerConnections(e,t)}disconnectAll(){Object.keys(this.peerConnections).forEach((e=>{this.disconnect(e)})),this.peerConnections={},this._socketListenerDeregisterFunctions.forEach((e=>{e()})),this._socketListenerDeregisterFunctions=[],this._localStreamDeregisterFunction&&(this._localStreamDeregisterFunction(),this._localStreamDeregisterFunction=null)}fixChromeAudio(e){if("chrome"!==Ng)return;const t=this._getLocalCameraStream(),r=t.getAudioTracks()[0];return r&&"ended"===r.readyState?navigator.mediaDevices.getUserMedia({audio:e}).then((e=>{const i=e.getAudioTracks()[0];return i.enabled=r.enabled,t.removeTrack(r),t.addTrack(i),this.replaceTrack(r,i)})):void 0}setupSocketListeners(){this._socketListenerDeregisterFunctions=[()=>this._clearMediaServersRefresh(),this._serverSocket.on(sm,(e=>{e.error?Lg.warn("FETCH_MEDIASERVER_CONFIG failed:",e.error):this._updateAndScheduleMediaServersRefresh(e)})),this._serverSocket.on(hm,(e=>{this._connect(e.clientId)})),this._serverSocket.on(um,(e=>{const t=this._getSession(e.clientId);t?t.addIceCandidate(e.message):Lg.warn("No RTCPeerConnection on ICE_CANDIDATE",e)})),this._serverSocket.on(pm,(e=>{const t=this._getSession(e.clientId);t?t.addIceCandidate(null):Lg.warn("No RTCPeerConnection on ICE_END_OF_CANDIDATES",e)})),this._serverSocket.on(mm,(e=>{var t,r;const i=this._getSession(e.clientId);if(!i)return void Lg.warn("No RTCPeerConnection on SDP_OFFER",e);const n=this._transformIncomingSdp(e.message,i.pc);null===(r=(t=i.handleOffer(n).then((t=>{this._emitServerEvent(fm,{receiverId:e.clientId,message:this._transformOutgoingSdp(t)})}))).catch)||void 0===r||r.call(t,(e=>{this._emit(sg,e)}))})),this._serverSocket.on(fm,(e=>{var t,r;const i=this._getSession(e.clientId);if(!i)return void Lg.warn("No RTCPeerConnection on SDP_ANSWER",e);const n=this._transformIncomingSdp(e.message,i.pc);null===(r=null===(t=i.handleAnswer(n))||void 0===t?void 0:t.catch)||void 0===r||r.call(t,(e=>{this._emit(ng,e)}))})),this._serverSocket.on(dm,(({room:{sfuServer:e}})=>{if(e||!this._wasScreenSharing)return;const t=Object.keys(this.localStreams).find((e=>e!==Ag));if(!t)return;const r=this.localStreams[t];if(!r)return void Lg.warn("screenshare stream %s not found",t);const i=r.getAudioTracks().length>0;this._emitServerEvent(tm,{streamId:t,hasAudioTrack:i})}))]}sendAudioMutedStats(e){wf.sendEvent("audio_muted",{muted:e})}sendVideoMutedStats(e){wf.sendEvent("video_muted",{muted:e})}sendStatsCustomEvent(e,t){wf.sendEvent(e,t)}rtcStatsDisconnect(){wf.server.close()}rtcStatsReconnect(){wf.server.connected||wf.server.connect()}setAudioOnly(e){this._isAudioOnlyMode=e,this._forEachPeerConnection((e=>{e.hasConnectedPeerConnection()&&this._withForcedRenegotiation(e,(()=>e.setAudioOnly(this._isAudioOnlyMode,this._screenshareVideoTrackIds)))}))}setRemoteScreenshareVideoTrackIds(e=[]){const t=this._getFirstLocalNonCameraStream();this._screenshareVideoTrackIds=[...(null==t?void 0:t.track)?[t.track.id]:[],...e]}setRoomSessionId(e){this._roomSessionId=e}_setConnectionStatus(e,t,r){const i=e.connectionStatus;i!==t&&e.peerConnectionId!==this._selfId&&(i===Pm&&t===Rm||(e.connectionStatus=t,setTimeout((()=>{this._emit(bm,{streamIds:e.streamIds,clientId:r,status:t,previous:i})}),0)))}_setJitterBufferTarget(e){try{e.getReceivers().forEach((e=>{e.jitterBufferTarget=Wf,e.playoutDelayHint=.4}))}catch(e){Lg.error("Error during setting jitter buffer target:",e)}}_emitServerEvent(e,t,r){this._serverSocket.emit(e,t,r)}_emit(e,t){this._emitter.emit(e,t)}_addEnabledLocalStreamId(e){this.enabledLocalStreamIds.push(e)}_deleteEnabledLocalStreamId(e){const t=this.enabledLocalStreamIds.indexOf(e);-1!==t&&this.enabledLocalStreamIds.splice(t,1)}_getSession(e){return e in this.peerConnections?this.peerConnections[e]:null}_getOrCreateSession(e,t){let r=this.peerConnections[e];if(void 0===r){const i="safari"===Ng&&Bg&&Bg>=14&&this._features.deprioritizeH264OnSafari;this.peerConnections[e]=r=new Qf({peerConnectionId:e,bandwidth:t,maximumTurnBandwidth:this._features.unlimitedBandwidthWhenUsingRelayP2POn?-1:1280,deprioritizeH264Encoding:i}),this.totalSessionsCreated++}return r}_getLocalCameraStream(){return this.localStreams[Ag]}_getNonLocalCameraStreamIds(){return Object.keys(this.localStreams).filter((e=>e!==Ag))}_isScreensharingLocally(){return this._getNonLocalCameraStreamIds().length>0}_getFirstLocalNonCameraStream(){const e=this._getNonLocalCameraStreamIds();return 0===e.length?null:this.localStreams[e[0]]}_transformIncomingSdp(e,t){return{type:e.type,sdp:e.sdpU}}_transformOutgoingSdp(e){return{type:e.type,sdpU:e.sdp}}_createSession({clientId:e,initialBandwidth:t,isOfferer:r,peerConnectionId:i,shouldAddLocalVideo:n}){if(!i)throw new Error("peerConnectionId is missing");if(!e)throw new Error("clientId is missing");const s=this._getOrCreateSession(i,t),o={optional:[]};"chrome"===Ng&&o.optional.push({googCpuOveruseDetection:!0}),o.optional.push({rtcStatsRoomSessionId:this._roomSessionId}),o.optional.push({rtcStatsClientId:this._selfId}),o.optional.push({rtcStatsPeerId:i}),o.optional.push({rtcStatsConferenceId:this._roomName});const a={iceServers:this._features.turnServersOn?this._turnServers:this._iceServers};var c,d;a.iceServers=Eg(a.iceServers,this._features.turnServerOverrideHost),c=a,(d=this._features).addGoogleStunServers&&(c.iceServers=[{urls:"stun:stun.l.google.com:19302"},{urls:"stun:stun2.l.google.com:19302"},...c.iceServers]),d.addCloudflareStunServers&&(c.iceServers=[{urls:"stun:stun.cloudflare.com:3478"},{urls:"stun:stun.cloudflare.com:53"},...c.iceServers]),Og(a,this._features),"chrome"===Ng&&(a.sdpSemantics="unified-plan");const l=s.setAndGetPeerConnection({constraints:o,peerConnectionConfig:a,shouldAddLocalVideo:n,clientId:e});setTimeout((()=>this._emit(Zm)),0),l.ontrack=t=>{const r=t.streams[0];"default"===r.id&&0===r.getAudioTracks().length||-1===s.streamIds.indexOf(r.id)&&(s.streamIds.push(r.id),this._emit(ym,{clientId:e,stream:r}),s.connectionStatus===Tm&&setTimeout((()=>{this._emit(bm,{streamIds:s.streamIds,clientId:e,status:s.connectionStatus,previous:Rm})}),0))},l.oniceconnectionstatechange=()=>{let t;const r=s.connectionStatus;switch(l.iceConnectionState){case"checking":t=Rm;break;case"connected":case"completed":t=Tm,s.wasEverConnected||(this._pendingActionsForConnectedPeerConnections.forEach((e=>{"function"==typeof e&&e()})),this._pendingActionsForConnectedPeerConnections=[]),!s.wasEverConnected&&(l.iceConnectionState.match(/connected|completed/)||"chrome"===Ng&&l.localDescription&&"answer"===l.localDescription.type)&&(s.wasEverConnected=!0,"false"!==this._features.bandwidth&&this.maybeRestrictRelayBandwidth(s)),this._isAudioOnlyMode&&s.setAudioOnly(!0,this._screenshareVideoTrackIds),s.registerConnected();break;case"disconnected":t=Pm,setTimeout((()=>{"disconnected"===l.iceConnectionState&&this._maybeRestartIce(e,s)}),2e3);break;case"failed":t=km,r!==t&&this._maybeRestartIce(e,s),null!==s.relayCandidateSeen||s.wasEverConnected||this._emit($m);break;default:return}this._setConnectionStatus(s,t,e)},l.onconnectionstate=()=>{switch(l.connectionState){case"connected":setTimeout((()=>{(function(e){if("chrome"!==Yf.browserDetails.browser||Yf.browserDetails.browser<58||"closed"===e.signalingState)return Promise.resolve(!1);const t=e.getSenders().some((e=>e.track&&"audio"===e.track.kind)),r=e.getReceivers().some((e=>e.track&&"audio"===e.track.kind));return e.getStats(null).then((e=>{let i=!1;return e.forEach((e=>{"outbound-rtp"!==e.type||"audio"!==e.kind&&"audio"!==e.mediaType||!t?"inbound-rtp"!==e.type||"audio"!==e.kind&&"audio"!==e.mediaType||!r||0===e.bytesReceived&&(i="inbound"):0===e.bytesSent&&(i="outbound")})),i}))})(s.pc).then((t=>{!1!==t&&this._emit(Jm,{failureDirection:t,clientId:e})}))}),3e3),s.registerConnected();break;case"failed":const t=km;null!==s.relayCandidateSeen||s.wasEverConnected||this._emit($m),this._setConnectionStatus(s,t,e)}};const u=this.localStreams[Ag];return n&&u&&s.addStream(u),n&&Object.keys(this.localStreams).forEach((e=>{if(e===Ag)return;const t=this.localStreams[e];r?s.addStream(t):s.afterConnected.then((()=>{this._emitServerEvent(tm,{receiverId:s.clientId,streamId:t.id,hasAudioTrack:!!t.getAudioTracks().length}),this._withForcedRenegotiation(s,(()=>s.addStream(t)))}))})),s}_cleanup(e){const t=this._getSession(e);t?(t.close(),delete this.peerConnections[e]):Lg.warn("No RTCPeerConnection in RTCManager.disconnect()",e)}_forEachPeerConnection(e){Object.values(this.peerConnections).forEach((t=>{e(t)}))}_addStreamToPeerConnections(e){this._forEachPeerConnection((t=>{this._withForcedRenegotiation(t,(()=>t.addStream(e)))}))}_addTrackToPeerConnections(e,t){this._forEachPeerConnection((r=>{this._withForcedRenegotiation(r,(()=>r.addTrack(e,t)))}))}_replaceTrackToPeerConnections(e,t){const r=[];return this._forEachPeerConnection((i=>{if(!i.hasConnectedPeerConnection()){Lg.info("Session doesn't have a connected PeerConnection, adding pending action!");const n=this._pendingActionsForConnectedPeerConnections;if(!n)return void Lg.warn("No pending action is created to replace track, because the pending actions array is null");const s=new Promise(((r,s)=>{n.push((()=>{const n=i.replaceTrack(e,t);if(!n)return Lg.error("replaceTrack returned false!"),void s("ReplaceTrack returned false");n.then((e=>r(e))).catch((e=>s(e)))}))}));return void r.push(s)}const n=i.replaceTrack(e,t);n?r.push(n):Lg.error("replaceTrack returned false!")})),Promise.all(r)}_removeStreamFromPeerConnections(e){this._forEachPeerConnection((t=>{this._withForcedRenegotiation(t,(()=>t.removeStream(e)))}))}_removeTrackFromPeerConnections(e){this._forEachPeerConnection((t=>{this._withForcedRenegotiation(t,(()=>t.removeTrack(e)))}))}_addLocalStream(e,t){this._addEnabledLocalStreamId(e),this.localStreams[e]=t}_removeLocalStream(e){delete this.localStreams[e],this._deleteEnabledLocalStreamId(e)}_updateAndScheduleMediaServersRefresh({iceServers:e,turnServers:t,sfuServer:r,mediaserverConfigTtlSeconds:i}){this._iceServers=e,this._turnServers=t,this._sfuServer=r,this._mediaserverConfigTtlSeconds=i,this._clearMediaServersRefresh(),i&&(this._fetchMediaServersTimer=setTimeout((()=>this._emitServerEvent(em)),1e3*i))}_clearMediaServersRefresh(){this._fetchMediaServersTimer&&(clearTimeout(this._fetchMediaServersTimer),this._fetchMediaServersTimer=null)}_monitorAudioTrack(e){var t,r;(null===(t=this._audioTrackBeingMonitored)||void 0===t?void 0:t.id)!==e.id&&(null===(r=this._audioTrackBeingMonitored)||void 0===r||r.removeEventListener("ended",this._audioTrackOnEnded),e.addEventListener("ended",this._audioTrackOnEnded),this._audioTrackBeingMonitored=e)}_monitorVideoTrack(e){var t,r;(null===(t=this._videoTrackBeingMonitored)||void 0===t?void 0:t.id)!==e.id&&(null===(r=this._videoTrackBeingMonitored)||void 0===r||r.removeEventListener("ended",this._videoTrackOnEnded),e.addEventListener("ended",this._videoTrackOnEnded),this._videoTrackBeingMonitored=e)}_connect(e){let t=this._getSession(e),r=t&&t.bandwidth||0;return t?(Lg.warn("Replacing peer session",e),this._cleanup(e)):r=this._changeBandwidthForAllClients(!0),t=this._createP2pSession({clientId:e,initialBandwidth:r,shouldAddLocalVideo:!0,isOfferer:!0}),this._negotiatePeerConnection(e,t),Promise.resolve(t)}_maybeRestartIce(e,t){const r=t.pc;"disconnected"!==r.iceConnectionState&&"failed"!==r.iceConnectionState||"offer"===r.localDescription.type&&(t.wasEverConnected=!1,t.relayCandidateSeen=!1,t.serverReflexiveCandidateSeen=!1,t.publicHostCandidateSeen=!1,t.ipv6HostCandidateSeen=!1,this.ipv6HostCandidateTeredoSeen=!1,this.ipv6HostCandidate6to4Seen=!1,this.mdnsHostCandidateSeen=!1,this._emit(Km),this._negotiatePeerConnection(e,t,Object.assign({},this.offerOptions,{iceRestart:!0})))}_setCodecPreferences(e,{p2pVp9On:t,p2pAv1On:r,redOn:i}){try{const n=e.getTransceivers().filter((e=>{var t,r;return"audio"===(null===(r=null===(t=null==e?void 0:e.sender)||void 0===t?void 0:t.track)||void 0===r?void 0:r.kind)}));n.forEach((e=>{if(void 0===RTCRtpSender.getCapabilities)return;const t=RTCRtpSender.getCapabilities("audio");for(let e=0;e<t.codecs.length;e++)if(i&&"audio/red"===t.codecs[e].mimeType.toLowerCase()){t.codecs.unshift(t.codecs.splice(e,1)[0]);break}void 0!==e.setCodecPreferences&&e.setCodecPreferences(t.codecs)}));const s=e.getTransceivers().filter((e=>{var t,r;return"video"===(null===(r=null===(t=null==e?void 0:e.sender)||void 0===t?void 0:t.track)||void 0===r?void 0:r.kind)}));s.forEach((e=>{if(void 0===RTCRtpReceiver.getCapabilities)return;const i=RTCRtpReceiver.getCapabilities("video");(t||r)&&(i.codecs=function(e,t){const r=e.map((({mimeType:e})=>e)).filter(((e,t,r)=>r.indexOf(e)===t)),i=function(e,{vp9On:t,av1On:r}){return t&&e.unshift("video/vp9"),r&&e.unshift("video/av1"),e}(r,t);return e.sort(((e,t)=>{const r=i.indexOf(e.mimeType.toLowerCase()),n=i.indexOf(t.mimeType.toLowerCase());return(r>=0?r:Number.MAX_VALUE)-(n>=0?n:Number.MAX_VALUE)}))}(i.codecs,{vp9On:t,av1On:r})),void 0!==e.setCodecPreferences&&e.setCodecPreferences(i.codecs)}))}catch(e){Lg.error("Error during setting setCodecPreferences:",e)}}_negotiatePeerConnection(e,t,r){if(!t)return void Lg.warn("No RTCPeerConnection in negotiatePeerConnection()",e);const i=t.pc;if(!t.canModifyPeerConnection())return void t.pending.push((()=>{this._negotiatePeerConnection(e,t,r)}));t.isOperationPending=!0;const{p2pVp9On:n,p2pAv1On:s,redOn:o,rtpAbsCaptureTimeOn:a,cleanSdpOn:c}=this._features;(n||s||o)&&this._setCodecPreferences(i,{p2pVp9On:n,p2pAv1On:s,redOn:o}),i.createOffer(r||this.offerOptions).then((t=>{a&&(t.sdp=qf(t.sdp)),(n||o)&&"firefox"===Ng&&(t.sdp=function(e,t,r){var i,n;try{const s=Li(e);if(Array.isArray(null==s?void 0:s.media)){const e=s.media.find((e=>"audio"===e.type));if(Array.isArray(null==e?void 0:e.rtp)){const t=e.rtp;for(let n=0;n<t.length;n++)if(r&&"red"===t[n].codec){const r=null===(i=e.payloads)||void 0===i?void 0:i.split(" "),s=null==r?void 0:r.indexOf(""+t[n].payload);s&&-1!==s&&s>=0&&(null==r||r.unshift(r.splice(s,1)[0]),e.payloads=null==r?void 0:r.join(" "))}}const o=s.media.find((e=>"video"===e.type));if(Array.isArray(null==o?void 0:o.rtp)){const e=o.rtp;for(let r=0;r<e.length;r++)if(t&&"VP9"===e[r].codec){const t=null===(n=o.payloads)||void 0===n?void 0:n.split(" "),i=null==t?void 0:t.indexOf(""+e[r].payload);i&&-1!==i&&i>=0&&(null==t||t.unshift(t.splice(i,1)[0]),o.payloads=null==t?void 0:t.join(" "))}}}return ji(s)}catch(e){zf.error("setCodecPreferenceSDP error:",e)}}(t.sdp,n,o)),c&&(t.sdp=function(e){try{const t=Li(e);return t.media.forEach((e=>{const t={};e.payloads&&(e.payloads=(""+e.payloads).split(" ").filter((e=>!t[e]&&(t[e]=!0))).join(" "));const r={};e.rtp=e.rtp.filter((e=>!e.payload||t[e.payload]&&!r[e.payload]&&(r[e.payload]=!0)));const i={};e.fmtp&&(e.fmtp=e.fmtp.filter((e=>!e.payload||t[e.payload]&&!i[e.payload]&&(i[e.payload]=!0))));const n={};e.rtcpFb&&(e.rtcpFb=e.rtcpFb.filter((e=>!e.payload||t[e.payload]&&!n[e.payload+e.type+e.subtype]&&(n[e.payload+e.type+e.subtype]=!0))))})),ji(t)}catch(e){}return e}(t.sdp)),i.setLocalDescription(t).catch((e=>{throw Lg.warn("RTCPeerConnection.setLocalDescription() failed with local offer",e),this._emit(ig,e),e})).then((()=>{this._emitServerEvent(mm,{receiverId:e,message:this._transformOutgoingSdp(t)})}))})).catch((e=>{Lg.warn("RTCPeerConnection.createOffer() failed to create local offer",e)}))}_withForcedRenegotiation(e,t){const r=e.pc,i=r.onnegotationneeded;r.onnegotiationneeded=null,t(),this._negotiatePeerConnection(e.clientId,e),setTimeout((()=>r.onnegotiationneeded=i),0)}_changeBandwidthForAllClients(e){let t=this.numberOfPeerconnections();if(e&&(t+=1),0===t)return 0;t>7&&(t=7);let r=this._features.bandwidth?parseInt(this._features.bandwidth,10):{1:this._features.lowBandwidth?768:0,2:this._features.highP2PBandwidth&&!this._features.lowBandwidth?768:384,3:this._features.highP2PBandwidth&&!this._features.lowBandwidth?512:256,4:192,5:128,6:128,7:64}[t];if(void 0===r)return 0;if(this._features.adjustBitratesFromResolution){const e=this._getLocalCameraStream();if(e){const t=e&&e.getVideoTracks()[0];if(t){const{width:e,height:i,frameRate:n}=t.getSettings();if(e&&i&&n){const t=Math.round(function(e,t,r){let i=e*t;i<Dm&&(i=Dm),i>xm&&(i=xm);let n=Im;i>xm?n=Mm:i>Dm&&(n+=-17582143775720163e-22*(i-Dm));let s=e*t*n;return r<=15?s*=.7:r<=24&&(s*=.9),s}(e,i,n)/1e3);r=Math.min(t,r||t)}}}}return this._features.higherP2PBitrates&&!this._features.lowBandwidth&&(r*=1.5),this._forEachPeerConnection((e=>{e.changeBandwidth(r)})),r}_createP2pSession({clientId:e,initialBandwidth:t,shouldAddLocalVideo:r=!1,isOfferer:i=!1}){const n=this._createSession({peerConnectionId:e,clientId:e,initialBandwidth:t,shouldAddLocalVideo:r,isOfferer:i}),s=n.pc;this._features.increaseIncomingMediaBufferOn&&this._setJitterBufferTarget(s);const o=this.localStreams[Ag];return r&&o&&!o.getVideoTracks().length&&this._stoppedVideoTrack&&s.addTrack(this._stoppedVideoTrack,o),s.onicegatheringstatechange=e=>{switch(e.target.iceGatheringState){case"gathering":this.icePublicIPGatheringTimeoutID&&clearTimeout(this.icePublicIPGatheringTimeoutID),this.icePublicIPGatheringTimeoutID=setTimeout((()=>{n.publicHostCandidateSeen||n.relayCandidateSeen||n.serverReflexiveCandidateSeen||"connected"===s.iceConnectionState&&"completed"===s.iceConnectionState||this._emit(Wm)}),3e3);break;case"complete":this.icePublicIPGatheringTimeoutID&&clearTimeout(this.icePublicIPGatheringTimeoutID),this.icePublicIPGatheringTimeoutID=void 0}},s.onicecandidate=t=>{var r,i;if(t.candidate){switch(null===(r=t.candidate)||void 0===r?void 0:r.type){case"host":const e=null===(i=null==t?void 0:t.candidate)||void 0===i?void 0:i.address;try{if(Um.v4({exact:!0}).test(e)){Un(e).isPublicIp&&(n.publicHostCandidateSeen=!0)}else if(Um.v6({exact:!0}).test(e.replace(/^\[(.*)\]/,"$1"))){const t=new Ai.Address6(e.replace(/^\[(.*)\]/,"$1"));n.ipv6HostCandidateSeen=!0,"Global"===t.getScope()&&(n.publicHostCandidateSeen=!0),t.isTeredo()&&(n.ipv6HostCandidateTeredoSeen=!0),t.is6to4()&&(n.ipv6HostCandidate6to4Seen=!0)}else{const t=e.replace(/.local/,"");t&&Xn(t,4)&&(n.mdnsHostCandidateSeen=!0)}}catch(e){Lg.info("Error during parsing candidates! Error: ",{error:e})}break;case"srflx":n.serverReflexiveCandidateSeen||(n.serverReflexiveCandidateSeen=!0);break;case"relay":case"relayed":n.relayCandidateSeen||(n.relayCandidateSeen=!0)}this._emitServerEvent(um,{receiverId:e,message:t.candidate})}else this._emitServerEvent(pm,{receiverId:e}),n.publicHostCandidateSeen||n.relayCandidateSeen||n.serverReflexiveCandidateSeen||"connected"===s.iceConnectionState||"completed"===s.iceConnectionState||this._emit(Hm),n.ipv6HostCandidateSeen&&this._emit(Gm,{teredoSeen:n.ipv6HostCandidateTeredoSeen,sixtofourSeen:n.ipv6HostCandidate6to4Seen}),n.mdnsHostCandidateSeen&&this._emit(qm)},s.onnegotiationneeded=()=>{"new"!==s.iceConnectionState&&n.connectionStatus&&this._negotiatePeerConnection(e,n)},n}acceptNewStream({streamId:e,clientId:t,shouldAddLocalVideo:r}){let i=this._getSession(t);if(i&&e!==t)return i;let n=i&&i.bandwidth||0;return i?(Lg.warn("Replacing peer session",t),this._cleanup(t)):n=this._changeBandwidthForAllClients(!0),i=this._createP2pSession({clientId:t,initialBandwidth:n,shouldAddLocalVideo:!!r,isOfferer:!1}),this._emitServerEvent(hm,{receiverId:t}),i}disconnect(e){this._cleanup(e),this._changeBandwidthForAllClients(!1);0===this.numberOfPeerconnections()&&setTimeout((()=>{0===this.numberOfPeerconnections()&&this.rtcStatsDisconnect()}),6e4)}updateStreamResolution(){}stopOrResumeAudio(){}_handleStopOrResumeVideo({enable:e,track:t}){e?this._stoppedVideoTrack?(this._replaceTrackToPeerConnections(this._stoppedVideoTrack,t),delete this._stoppedVideoTrack):this._addTrackToPeerConnections(t):this._stoppedVideoTrack=t}stopOrResumeVideo(e,t){var r;if(["chrome","safari"].includes(Ng))if(!1===t){const i="ended"===(null===(r=e.getVideoTracks().find((e=>!e.enabled)))||void 0===r?void 0:r.readyState)?0:5e3;setTimeout((()=>{e.getVideoTracks().forEach((r=>{!1===r.enabled&&(r.stop(),e.removeTrack(r),this._emit(Cm,{stream:e,track:r}),this._handleStopOrResumeVideo({enable:t,track:r}))}))}),i)}else if(0===e.getVideoTracks().length){const r=this._webrtcProvider.getMediaConstraints().video;if(!r)return;navigator.mediaDevices.getUserMedia({video:r}).then((r=>{const i=r.getVideoTracks()[0];e.addTrack(i),this._monitorVideoTrack(i),this._emit(Sm,{streamId:e.id,tracks:[i],screenShare:!1}),this._handleStopOrResumeVideo({enable:t,track:i})}))}}_shareScreen(e,t){this._emitServerEvent(tm,{streamId:e,hasAudioTrack:!!t.getAudioTracks().length}),this._wasScreenSharing=!0,this._addStreamToPeerConnections(t)}removeStream(e,t,r){this._removeLocalStream(e),this._removeStreamFromPeerConnections(t),this._wasScreenSharing=!1,this._emitServerEvent(rm,{streamId:e,requestedByClientId:r})}hasClient(e){return Object.keys(this.peerConnections).includes(e)}}class Vg{static parse(e){let t;try{t=JSON.parse(e)}catch(e){return}if("object"==typeof t&&!Array.isArray(t))return t.request?Vg._handleRequest(t):t.response?Vg._handleResponse(t):t.message?Vg._handleMessage(t):void 0}static _handleRequest(e){const t={request:!0};if("string"==typeof e.method&&"number"==typeof e.id)return t.id=e.id,t.method=e.method,t.data=e.data||{},t}static _handleResponse(e){const t={response:!0};if("number"==typeof e.id)return t.id=e.id,e.ok?(t.ok=!0,t.data=e.data||{}):(t.ok=!1,t.errorCode=e.errorCode,t.errorReason=e.errorReason),t}static _handleMessage(e){const t={message:!0};if("string"==typeof e.method)return t.method=e.method,t.data=e.data||{},t}static createRequest(e,t){return{request:!0,id:Math.round(1e7*Math.random()),method:e,data:t||{}}}static createSuccessResponse(e,t){return{response:!0,id:e.id,ok:!0,data:t||{}}}static createErrorResponse(e,t,r){return{response:!0,id:e.id,errorCode:t,errorReason:r}}static createMessage(e,t){return{message:!0,method:e,data:t||{}}}}const Ug=new hf;class $g extends Np{constructor(e,t="whereby-sfu#v4"){super(),this.socket=null,this.wsUrl=e,this.protocol=t,this.sents=new Map,this._setupSocket()}_setupSocket(){this.socket=new WebSocket(this.wsUrl,this.protocol),this.socket.onopen=this._onOpen.bind(this),this.socket.onmessage=this._onMessage.bind(this),this.socket.onclose=this._onClose.bind(this),this.socket.onerror=this._onError.bind(this)}_tearDown(){null!==this.socket&&(this.socket.onopen=null,this.socket.onmessage=null,this.socket.onclose=null,this.socket.onerror=null,this.socket=null,this.sents.forEach((e=>e.close())),this.emit("close"))}close(){var e;null===(e=this.socket)||void 0===e||e.close()}_onOpen(){Ug.info("Connected"),this.emit("open")}_onMessage(e){const t=Vg.parse(e.data);Ug.info("Received message",t),(null==t?void 0:t.response)?this._handleResponse(t):(null==t?void 0:t.message)&&this.emit("message",t)}_onClose(){Ug.info("Disconnected"),this._tearDown()}_onError(e){Ug.info("Error",e)}_handleResponse(e){const t=this.sents.get(e.id);if(e.ok)t.resolve(e.data);else{const r=new Error(e.errorReason);t.reject(r)}}send(e){try{this.socket&&this.socket.send(JSON.stringify(e))}catch(e){}}message(e,t={}){const r=Vg.createMessage(e,t);this.send(r)}request(e,t={},r=1500*(15+.1*this.sents.size)){const i=Vg.createRequest(e,t);return this.send(i),new Promise(((e,t)=>{const n={id:i.id,method:i.method,resolve:t=>{this.sents.delete(i.id)&&(clearTimeout(n.timer),e(t))},reject:e=>{this.sents.delete(i.id)&&(clearTimeout(n.timer),t(e))},timer:setTimeout((()=>{this.sents.delete(i.id)&&t(new Error("request timeout"))}),r),close:()=>{clearTimeout(n.timer),t(new Error("transport closed"))}};this.sents.set(i.id,n)}))}}var Gg=Object.freeze({__proto__:null,KalmanFilter:class{constructor({R:e=.01,Q:t=2,A:r=1.1,B:i=1,C:n=1.2}={R:.01,Q:2,A:1.1,B:1,C:1.2}){this.R=e,this.Q=t,this.A=r,this.C=n,this.B=i,this.cov=NaN,this.x=NaN}filter(e,t=0){if(isNaN(this.x))this.x=1/this.C*e,this.cov=1/this.C*this.Q*(1/this.C);else{const r=this.predict(t),i=this.uncertainty(),n=i*this.C*(1/(this.C*i*this.C+this.Q));this.x=r+n*(e-this.C*r),this.cov=i-n*this.C*i}return this.x}predict(e=0){return this.A*this.x+this.B*e}uncertainty(){return this.A*this.cov*this.A+this.R}lastMeasurement(){return this.x}setMeasurementNoise(e){this.Q=e}setProcessNoise(e){this.R=e}},calculateStd:e=>{const t=e.reduce(((e,t)=>e+t),0)/e.length;return e.reduce(((e,r)=>e.concat(Math.pow(r-t,2))),[]).reduce(((e,t)=>e+t),0)/e.length},createACFCalculator:()=>{let e=-1,t=0,r=0;return i=>{const n=i.reduce(((e,t)=>e+t),0)/i.length;if(e=e<0?n:.95*e+.05*n,++r<2)return t=n,0;const s=(n-e)*(t-e);return t=n,s}},standardDeviation:e=>{const t=e.reduce(((e,t)=>e+t),0)/e.length;return{mean:t,SD:Math.sqrt(e.reduce(((e,r)=>e+Math.pow(r-t,2)),0)/e.length)}},variance:(e,t=!1)=>{const r=e.reduce(((e,t)=>e+t),0)/e.length;return e.reduce(((e,t)=>e.concat(Math.pow(t-r,2))),[]).reduce(((e,t)=>e+t),0)/(e.length-(t?0:1))}});const qg={minDecibels:-80,maxDecibels:-10,smoothingTimeConstant:.8,aggSize:1,sampleRate:10,reportRate:2,bins:32,bands:[[0,1,2,3],[4,5,6,7]],separateTrack:{autoGainControl:!1,noiseSupression:!1},binFormula:"bin",scoreFormula:"300 * bands[1].avg / Math.max(bands[1].avg + bands[0].avg, 0.01)",outFormula:"score"},Hg=new hf;const Wg=new hf,Kg=Object.freeze({ok:"ok",warning:"warning",critical:"critical"});class Jg extends Np{constructor(){super(),this._clients={},this._producers={},this._startMonitor()}close(){clearInterval(this._intervalHandle),delete this._intervalHandle,this._producers={},this._clients={}}_startMonitor(){this._intervalHandle=setInterval((()=>{Object.entries(this._producers).forEach((([e,t])=>{this._evaluateClient(e,t)}))}),600)}_evaluateClient(e,t){this._clients[e]||(this._clients[e]={audio:{currentQuality:Kg.ok,trend:[]},video:{currentQuality:Kg.ok,trend:[]}}),this._evaluateProducer(e,Object.values(t).filter((e=>"audio"===e.kind)),"audio"),this._evaluateProducer(e,Object.values(t).filter((e=>"video"===e.kind)),"video")}_evaluateProducer(e,t,r){if(0===t.length)return;const i=t.reduce(((e,t)=>e+t.score),0)/t.length,n=this._evaluateScore(i);this._updateTrend(n,this._clients[e][r])&&this.emit(vm,{clientId:e,kind:r,quality:n})}_updateTrend(e,t){return t.trend.push(e),t.trend.length>3&&t.trend.shift(),!(e===t.currentQuality||!t.trend.every((e=>e!==t.currentQuality)))&&(t.currentQuality=e,!0)}addProducer(e,t){e&&t&&"string"==typeof e&&"string"==typeof t?(this._producers[e]||(this._producers[e]={}),this._producers[e][t]={}):Wg.warn("Missing clientId or producerId")}removeProducer(e,t){delete this._producers[e][t],0===Object.keys(this._producers[e]).length&&delete this._producers[e]}addConsumer(e,t){e&&t?(this._producers[e]||(this._producers[e]={}),this._producers[e][t]={}):Wg.warn("Missing clientId or consumerId")}removeConsumer(e,t){delete this._producers[e][t],0===Object.keys(this._producers[e]).length&&delete this._producers[e]}addProducerScore(e,t,r,i){Array.isArray(i)&&0!==i.length&&!i.some((e=>!e||!e.hasOwnProperty("score")||"number"!=typeof e.score||isNaN(e.score)))?this._producers[e][t]={kind:r,score:this._calcAvgProducerScore(i.map((e=>e.score)))}:Wg.warn("Unexpected producer score format")}addConsumerScore(e,t,r,i){i&&i.hasOwnProperty("producerScores")&&Array.isArray(i.producerScores)?this._producers[e][t]={kind:r,score:this._calcAvgProducerScore(i.producerScores)}:Wg.warn("Unexpected consumer score format")}_evaluateScore(e){return e<=9&&e>7?Kg.warning:e<=7&&e>0?Kg.critical:Kg.ok}_calcAvgProducerScore(e){try{if(!Array.isArray(e)||0===e.length)return 0;let t=0,r=0;return e.forEach((e=>{e>0&&(t+=e,r++)})),0===t||0===r?0:t/r}catch(e){return Wg.error(e),0}}}function Xg(e){let t,r,i,n,s=[];const o=e=>{s=function(e){return"string"==typeof e?e.split(",").filter(Boolean).map((e=>{const[t,r]=/\|/.test(e)?e.split("|"):["",e];return{host:r,dc:t}})):e.filter((e=>e.host)).map((e=>({host:e.host,dc:e.dc||""})))}(e)};let a=!1,c=!1;const d=()=>{if(a)return void(c=!0);a=!0,c=!1;let o=s;if(t){const e=Date.now();e-3e3>(r||0)&&((!n||(i||0)>n)&&e-3e3>(i||0))||(o=[{host:t.host,dc:t.dc}])}const l={};let u=0;o.forEach((({dc:e})=>{void 0===l[e]&&(l[e]=u++)}));let p=0;const h={};let f,m=o.length,g=!1,v=!1;o.forEach((({host:i,dc:n},s)=>{if(s>0){p+=500;const e=(h[n]||0)+2e3;p=Math.max(p,e)}h[n]=p,setTimeout((()=>{var u;if(v)return;const p=new $g((null===(u=e.getUrlForHost)||void 0===u?void 0:u.call(e,i))||i);let h=!1;p.on("open",(()=>{setTimeout((()=>{var r;if(!h)if(f||v)p.close();else{f=p,v=!0;const d=[...new Set(o.slice(0,s).filter((e=>e.host!==i)).map((e=>e.host)))],u=[...new Set(o.slice(0,s).filter((e=>e.dc!==n)).map((e=>e.dc)))];t=t?Object.assign(Object.assign({},t),{host:i,dc:n,failedHosts:[...new Set([...d,...t.failedHosts])].filter((e=>e!==i&&!t.usedHosts.includes(e))),failedDCs:[...new Set([...u,...t.failedDCs])].filter((e=>e!==n&&!t.usedDCs.includes(e))),usedHosts:[...new Set([...t.usedHosts,i])],usedDCs:[...new Set([...t.usedDCs,n])],numConnections:t.numConnections+1}):{host:i,dc:n,initialHost:i,initialDC:n,initialHostIndex:s,initialDCIndex:l[n],failedHosts:d,failedDCs:u,usedHosts:[i],usedDCs:[n],numConnections:1,numUsedDCs:1,numUsedHosts:1,numFailedDCs:0,numFailedHosts:0},t.numUsedDCs=t.usedDCs.length,t.numUsedHosts=t.usedHosts.length,t.numFailedDCs=t.failedDCs.length,t.numFailedHosts=t.failedHosts.length,c=!1,a=!1,null===(r=e.onConnected)||void 0===r||r.call(e,p,t)}}),100)})),p.on("close",(()=>{var t,i;h=!0,p===f&&(f=void 0,r=Date.now(),g=!0,null===(t=e.onDisconnected)||void 0===t||t.call(e)),m--,0!==m||g||(a=!1,c?setTimeout(d,0):null===(i=e.onFailed)||void 0===i||i.call(e))}))}),p)}))};o(e.initialHostList);return{connect:d,updateHostList:o,networkIsUp:()=>{i=Math.max(Date.now(),i||0)},networkIsPossiblyDown:()=>{n=Date.now()}}}var Qg;const Zg=null!==(Qg=pi.default)&&void 0!==Qg?Qg:pi,Yg=new hf,ev=Zg.browserDetails.browser;let tv=!1;const rv=_i(),iv=_i();"chrome"===ev&&window.document.addEventListener("beforeunload",(()=>tv=!0));class nv{constructor({selfId:e,room:t,emitter:r,serverSocket:i,webrtcProvider:n,features:s,eventClaim:o}){const{session:a,iceServers:c,turnServers:d,sfuServer:l,sfuServers:u,mediaserverConfigTtlSeconds:p}=t;this._selfId=e,this._room=t,this._roomSessionId=null==a?void 0:a.id,this._emitter=r,this._serverSocket=i,this._webrtcProvider=n,this._features=s||{},this._eventClaim=o,this._vegaConnection=null,this._micAnalyser=null,this._micAnalyserDebugger=null,this._mediasoupDevice=(e=>{var t;if(e.isNodeSdk)return new Qn.Device({handlerFactory:jl.createFactory()});let r=Qn.detectDevice()||(/applecoremedia|applewebkit|safari/i.test(navigator.userAgent)?"Safari12":void 0);if("Safari12"===r&&"object"==typeof navigator&&"string"==typeof navigator.userAgent){const i=new Lp.UAParser(navigator.userAgent).getBrowser();parseInt(null!==(t=i.major)&&void 0!==t?t:"0")>=17&&e.safari17HandlerOn&&(r="Safari17")}return/iphone|ipad/i.test(navigator.userAgent)&&(r=e.safari17HandlerOn?"Safari17":"Safari12"),"Safari17"===r?new Qn.Device({handlerFactory:pg.createFactory()}):new Qn.Device({handlerName:r})})(s),this._routerRtpCapabilities=null,this._sendTransport=null,this._receiveTransport=null,this._clientStates=new Map,this._streamIdToVideoConsumerId=new Map,this._streamIdToVideoResolution=new Map,this._consumers=new Map,this._dataConsumers=new Map,this._localStreamDeregisterFunction=null,this._micTrack=null,this._webcamTrack=null,this._screenVideoTrack=null,this._screenAudioTrack=null,this._micProducer=null,this._micProducerPromise=null,this._micPaused=!1,this._micScoreProducer=null,this._micScoreProducerPromise=null,this._webcamProducer=null,this._webcamProducerPromise=null,this._webcamPaused=!1,this._screenVideoProducer=null,this._screenVideoProducerPromise=null,this._screenAudioProducer=null,this._screenAudioProducerPromise=null,this._sndTransportIceRestartPromise=null,this._rcvTransportIceRestartPromise=null,this._colocation=null,this._stopCameraTimeout=null,this._audioTrackOnEnded=()=>{wf.sendEvent("audio_ended",{unloading:tv}),this._emitToPWA(Xm,{})},this._videoTrackOnEnded=()=>{wf.sendEvent("video_ended",{unloading:tv}),this._emitToPWA(Qm,{})},this._updateAndScheduleMediaServersRefresh({sfuServer:l,sfuServers:u,iceServers:(null==c?void 0:c.iceServers)||[],turnServers:d||[],mediaserverConfigTtlSeconds:p}),this._socketListenerDeregisterFunctions=[],this._reconnect=!0,this._reconnectTimeOut=null,this._hasVegaConnection=!1,this._isConnectingOrConnected=!1,this._qualityMonitor=new Jg,this._qualityMonitor.on(vm,(e=>{this._emitToPWA(vm,e)})),this._networkIsDetectedUpBySignal=!1}_updateAndScheduleMediaServersRefresh({iceServers:e,turnServers:t,sfuServer:r,sfuServers:i,mediaserverConfigTtlSeconds:n}){var s,o,a;this._iceServers=e,this._turnServers=t,this._sfuServer=r,this._sfuServers=i,!i&&(null==r?void 0:r.fallbackServers)&&(this._sfuServers=r.fallbackServers.map((e=>({host:e.host||e.fqdn,dc:e.dc})))),this._mediaserverConfigTtlSeconds=n,null===(s=this._vegaConnectionManager)||void 0===s||s.updateHostList(this._features.sfuServersOverride||this._sfuServers||this._features.sfuServerOverrideHost||r.url);const c={iceServers:this._features.turnServersOn?this._turnServers:this._iceServers};c.iceServers=Eg(c.iceServers,this._features.turnServerOverrideHost),null===(o=this._sendTransport)||void 0===o||o.updateIceServers(c),null===(a=this._receiveTransport)||void 0===a||a.updateIceServers(c),this._clearMediaServersRefresh(),n&&(this._fetchMediaServersTimer=setTimeout((()=>this._emitToSignal(em)),1e3*n))}_clearMediaServersRefresh(){this._fetchMediaServersTimer&&(clearTimeout(this._fetchMediaServersTimer),this._fetchMediaServersTimer=null)}_onNetworkIsDetectedUpBySignal(){var e;this._networkIsDetectedUpBySignal||(this._networkIsDetectedUpBySignal=!0,null===(e=this._vegaConnectionManager)||void 0===e||e.networkIsUp())}_onNetworkIsDetectedPossiblyDownBySignal(){var e;this._networkIsDetectedUpBySignal&&(this._networkIsDetectedUpBySignal=!1,null===(e=this._vegaConnectionManager)||void 0===e||e.networkIsPossiblyDown())}setupSocketListeners(){this._socketListenerDeregisterFunctions.push((()=>this._clearMediaServersRefresh()),this._serverSocket.on(sm,(e=>{e.error?Yg.warn("FETCH_MEDIASERVER_CONFIG failed:",e.error):this._updateAndScheduleMediaServersRefresh(e)})),this._serverSocket.on(dm,(()=>{this._screenVideoTrack&&this._emitScreenshareStarted(),this._features.sfuReconnectV2On&&!this._hasVegaConnection&&this._reconnect&&this._connect()})),this._serverSocket.on("connect",(()=>this._onNetworkIsDetectedUpBySignal())),this._serverSocket.onEngineEvent("packet",(()=>this._onNetworkIsDetectedUpBySignal())),this._serverSocket.on("disconnect",(()=>this._onNetworkIsDetectedPossiblyDownBySignal()))),this._connect()}_emitScreenshareStarted(){this._emitToSignal(tm,{streamId:iv,hasAudioTrack:Boolean(this._screenAudioTrack)})}_connect(){if(this._features.sfuConnectionManagerOn)return this._connect_v2();if(this._features.sfuReconnectV2On){if(this._hasVegaConnection)return;if(!this._serverSocket.isConnected()){const e=this._serverSocket.getReconnectThreshold();if(!e)return;if(Date.now()>(this._serverSocket.disconnectTimestamp||0)+e)return}this._reconnectTimeOut&&clearTimeout(this._reconnectTimeOut)}const e=this._features.sfuServerOverrideHost||[this._sfuServer.url],t=new URLSearchParams(Object.assign({clientId:this._selfId,organizationId:this._room.organizationId,roomName:this._room.name,eventClaim:this._room.isClaimed?this._eventClaim:null,lowBw:"true"},Object.keys(this._features||{}).filter((e=>this._features[e]&&/^sfu/.test(e))).reduce(((e,t)=>Object.assign(Object.assign({},e),{[t]:this._features[t]})),{}))),r=`wss://${e}?${t.toString()}`;this._vegaConnection=new $g(r),this._hasVegaConnection=!0,this._vegaConnection.on("open",(()=>this._join())),this._vegaConnection.on("close",(()=>this._onClose())),this._vegaConnection.on("message",(e=>this._onMessage(e)))}_connect_v2(){if(this._features.sfuReconnectV2On){if(this._isConnectingOrConnected)return;if(!this._serverSocket.isConnected()){const e=this._serverSocket.getReconnectThreshold();if(!e)return;if(Date.now()>(this._serverSocket.disconnectTimestamp||0)+e)return}this._reconnectTimeOut&&clearTimeout(this._reconnectTimeOut)}if(!this._vegaConnectionManager){const e=this._features.sfuServersOverride||this._sfuServers||this._features.sfuServerOverrideHost||this._sfuServer.url;this._vegaConnectionManager=Xg({initialHostList:e,getUrlForHost:e=>{const t=new URLSearchParams(Object.assign({clientId:this._selfId,organizationId:this._room.organizationId,roomName:this._room.name,eventClaim:this._room.isClaimed?this._eventClaim:null,lowBw:"true"},Object.keys(this._features||{}).filter((e=>this._features[e]&&/^sfu/.test(e))).reduce(((e,t)=>Object.assign(Object.assign({},e),{[t]:this._features[t]})),{})));return`wss://${e}?${t.toString()}`},onConnected:(e,t)=>{this._vegaConnection=e,this._vegaConnection.on("message",(e=>this._onMessage(e))),this._emitToPWA(tg,t),this._join()},onDisconnected:()=>{this._vegaConnection=null,this._isConnectingOrConnected=!1,this._onClose()},onFailed:()=>{this._vegaConnection=null,this._isConnectingOrConnected=!1,this._onClose()}})}this._vegaConnectionManager.connect(),this._isConnectingOrConnected=!0}_onClose(){var e,t;Yg.info("_onClose()"),this._hasVegaConnection=!1,null===(e=this._sendTransport)||void 0===e||e.close(),null===(t=this._receiveTransport)||void 0===t||t.close(),this._sendTransport=null,this._receiveTransport=null,this._streamIdToVideoConsumerId.clear(),this._streamIdToVideoResolution.clear(),this._reconnect&&(this._reconnectTimeOut=setTimeout((()=>this._connect()),1e3)),this._qualityMonitor.close(),this._emitToPWA(eg)}_join(){var e,t;return ff(this,void 0,void 0,(function*(){Yg.info("join()"),this._emitToPWA(Ym);try{const{routerRtpCapabilities:r}=yield this._vegaConnection.request("getCapabilities");this._routerRtpCapabilities||(((e,t)=>{const{vp9On:r,h264On:i}=t;if(r){const{preferredPayloadType:t}=e.codecs.find((e=>"video/vp9"===e.mimeType.toLowerCase())),{preferredPayloadType:r}=e.codecs.find((e=>"video/rtx"===e.mimeType.toLowerCase()&&e.parameters.apt===t));e.codecs=e.codecs.filter((e=>"audio"===e.kind||e.preferredPayloadType===t||e.preferredPayloadType===r))}else if(i){const{preferredPayloadType:t}=e.codecs.find((e=>"video/h264"===e.mimeType.toLowerCase())),{preferredPayloadType:r}=e.codecs.find((e=>"video/rtx"===e.mimeType.toLowerCase()&&e.parameters.apt===t));e.codecs=e.codecs.filter((e=>"audio"===e.kind||e.preferredPayloadType===t||e.preferredPayloadType===r))}})(r,this._features),this._routerRtpCapabilities=r,yield null===(e=this._mediasoupDevice)||void 0===e?void 0:e.load({routerRtpCapabilities:r})),this._vegaConnection.message("setCapabilities",{rtpCapabilities:null===(t=this._mediasoupDevice)||void 0===t?void 0:t.rtpCapabilities}),this._colocation&&this._vegaConnection.message("setColocation",{colocation:this._colocation}),yield Promise.all([this._createTransport(!0),this._createTransport(!1)]);const i=[];!this._micTrack||this._micProducer||this._micProducerPromise||i.push(this._internalSendMic()),!this._webcamTrack||this._webcamProducer||this._webcamProducerPromise||i.push(this._internalSendWebcam()),!this._screenVideoTrack||this._screenVideoProducer||this._screenVideoProducerPromise||i.push(this._internalSendScreenVideo()),!this._screenAudioTrack||this._screenAudioProducer||this._screenAudioProducerPromise||i.push(this._internalSendScreenAudio()),yield Promise.all(i)}catch(e){Yg.error("_join() [error:%o]",e)}}))}_createTransport(e){var t;return ff(this,void 0,void 0,(function*(){const r=e?"createSendTransport":"createRecvTransport",i=yield this._vegaConnection.request("createTransport",{producing:e,consuming:!e,enableTcp:!0,enableUdp:!0,preferUdp:!0,sctpParameters:{enableSctp:!0,numSctpStreams:{OS:1024,MIS:1024},maxSctpMessageSize:262144,sctpSendBufferSize:262144}});i.iceServers=Eg(this._features.turnServersOn?this._turnServers:this._iceServers,this._features.turnServerOverrideHost),Og(i,this._features);const n=null===(t=this._mediasoupDevice)||void 0===t?void 0:t[r](i),s=t=>ff(this,void 0,void 0,(function*(){if(Yg.info(`Transport ConnectionStateChanged ${t}`),"disconnected"===t||"failed"===t)if(e){if(this._sndTransportIceRestartPromise)return;this._sndTransportIceRestartPromise=this._restartIce(n).finally((()=>{this._sndTransportIceRestartPromise=null}))}else{if(this._rcvTransportIceRestartPromise)return;this._rcvTransportIceRestartPromise=this._restartIce(n).finally((()=>{this._rcvTransportIceRestartPromise=null}))}}));null==n||n.on("connect",(({dtlsParameters:e},t)=>{var r;null===(r=this._vegaConnection)||void 0===r||r.message("connectTransport",{transportId:n.id,dtlsParameters:e}),t()})).on("connectionstatechange",s),null==n||n.observer.once("close",(()=>{n.removeListener("connectionstatechange",s)})),e?(null==n||n.on("produce",(({kind:e,rtpParameters:t,appData:r},i,s)=>ff(this,void 0,void 0,(function*(){var o;try{const{paused:s}=r,{id:a}=yield null===(o=this._vegaConnection)||void 0===o?void 0:o.request("produce",{transportId:n.id,kind:e,rtpParameters:t,paused:s,appData:r});i({id:a})}catch(e){s(e)}})))),null==n||n.on("producedata",(({appData:e,sctpStreamParameters:t},r,i)=>ff(this,void 0,void 0,(function*(){var s;try{const{id:i}=yield null===(s=this._vegaConnection)||void 0===s?void 0:s.request("produceData",{transportId:n.id,sctpStreamParameters:t,appData:e});r({id:i})}catch(e){i(e)}})))),this._sendTransport=n):this._receiveTransport=n}))}_restartIce(e,t=0){return ff(this,void 0,void 0,(function*(){if(!e||!("closed"in e)||!("connectionState"in e))return void Yg.info("_restartIce: No transport or property closed or connectionState!");if(e.closed)return void Yg.info("_restartIce: Transport is closed!");if("disconnected"!==e.connectionState&&"failed"!==e.connectionState)return void Yg.info("_restartIce: Connection is healthy ICE restart no loneger needed!");const{iceRestartStarted:r}=e.appData,i=Date.now();if(Number.isFinite(r)&&i-r<3500)return;if(e.appData.iceRestartStarted=i,5<=t)return void Yg.info("_restartIce: Reached restart ICE maximum retry count!");if(!this._vegaConnection)return void Yg.info("_restartIce: Connection is undefined");const{iceParameters:n}=yield this._vegaConnection.request("restartIce",{transportId:e.id});Yg.info("_restartIce: ICE restart iceParameters received from SFU: ",n);const s=yield e.restartIce({iceParameters:n}).then((()=>null)).catch((e=>e));if(s)switch(Yg.error(`_restartIce: ICE restart failed: ${s}`),s.message){case"missing transportId":case"no such transport":break;default:yield new Promise((e=>{setTimeout((()=>{e(void 0)}),Math.min(3500*Math.pow(2,t),6e4))})),yield this._restartIce(e,t+1)}else yield new Promise((e=>{setTimeout((()=>{e(void 0)}),6e4*Math.min(8,t+1))})),"failed"!==e.connectionState&&"disconnected"!==e.connectionState||(yield this._restartIce(e,t+1))}))}_internalSendMic(){return ff(this,void 0,void 0,(function*(){Yg.info("_internalSendMic()"),this._micProducerPromise=(()=>ff(this,void 0,void 0,(function*(){try{if(!this._micTrack||!this._sendTransport||this._micProducer)return void(this._micProducerPromise=null);const e=this._micPaused,t=yield this._sendTransport.produce(Object.assign(Object.assign({track:this._micTrack,disableTrackOnPause:!1,stopTracks:!1},Sg("audio",!1,Object.assign(Object.assign({},this._features),{vp9On:this._features.sfuVp9On}))),{appData:{streamId:rv,sourceClientId:this._selfId,screenShare:!1,source:"mic",paused:e}}));e?t.pause():t.resume(),this._micProducer=t,this._qualityMonitor.addProducer(this._selfId,t.id),t.observer.once("close",(()=>{var e;Yg.info('micProducer "close" event'),t.appData.localClosed&&(null===(e=this._vegaConnection)||void 0===e||e.message("closeProducers",{producerIds:[t.id]})),this._micProducer=null,this._micProducerPromise=null,this._qualityMonitor.removeProducer(this._selfId,t.id)})),this._micTrack!==this._micProducer.track&&(yield this._replaceMicTrack()),this._micPaused!==this._micProducer.paused&&this._pauseResumeMic()}catch(e){Yg.error("micProducer failed:%o",e)}finally{this._micProducerPromise=null,this._micTrack||(this._stopProducer(this._micProducer),this._micProducer=null)}})))()}))}_internalSetupMicScore(){return ff(this,void 0,void 0,(function*(){Yg.info("_internalSetupMicScore()"),this._micScoreProducerPromise=(()=>ff(this,void 0,void 0,(function*(){try{if(!this._micProducer||!this._colocation||this._micScoreProducer)return void(this._micScoreProducerPromise=null);const e=yield this._sendTransport.produceData({ordered:!1,maxPacketLifeTime:3e3,label:"micscore",appData:{producerId:this._micProducer.id,clientId:this._selfId}});this._micScoreProducer=e,e.observer.once("close",(()=>{var t;Yg.info('micScoreProducer "close" event'),e.appData.localClosed&&(null===(t=this._vegaConnection)||void 0===t||t.message("closeDataProducers",{dataProducerIds:[e.id]})),this._micScoreProducer=null,this._micScoreProducerPromise=null}))}catch(e){Yg.error("micScoreProducer failed:%o",e)}finally{this._micScoreProducerPromise=null,this._micProducer&&this._colocation||this._stopMicScoreProducer()}})))()}))}_stopMicScoreProducer(){this._stopProducer(this._micScoreProducer),this._micScoreProducer=null}_replaceMicTrack(){var e;return ff(this,void 0,void 0,(function*(){Yg.info("_replaceMicTrack()"),this._micTrack&&this._micProducer&&!this._micProducer.closed&&this._micProducer.track!==this._micTrack&&(yield this._micProducer.replaceTrack({track:this._micTrack}),null===(e=this._micAnalyser)||void 0===e||e.setTrack(this._micTrack),yield this._replaceMicTrack())}))}_pauseResumeMic(){var e,t;Yg.info("_pauseResumeMic()"),this._micProducer&&!this._micProducer.closed&&this._micPaused!==this._micProducer.paused&&(this._micPaused?(this._micProducer.pause(),null===(e=this._vegaConnection)||void 0===e||e.message("pauseProducers",{producerIds:[this._micProducer.id]})):(this._micProducer.resume(),null===(t=this._vegaConnection)||void 0===t||t.message("resumeProducers",{producerIds:[this._micProducer.id]})),this._pauseResumeMic())}_sendMic(e){return ff(this,void 0,void 0,(function*(){return Yg.info("_sendMic() [track:%o]",e),this._micTrack=e,this._micProducer?yield this._replaceMicTrack():this._micProducerPromise?void 0:this._sendTransport?yield this._internalSendMic():void 0}))}_sendMicScore(e){if(!isNaN(e)&&isFinite(e))if(this._micScoreProducer){if(this._micScoreProducer.closed)return void this._stopMicScoreProducer();try{this._micScoreProducer.send(JSON.stringify({score:e}))}catch(e){Yg.error("_sendMicScore failed [error:%o]",e)}}else!this._micScoreProducerPromise&&this._micProducer&&this._colocation&&0!==e&&this._internalSetupMicScore()}_internalSendWebcam(){var e;return ff(this,void 0,void 0,(function*(){Yg.info("_internalSendWebcam()"),!this._sendTransport||this._webcamProducer||this._webcamProducerPromise||"live"!==(null===(e=this._webcamTrack)||void 0===e?void 0:e.readyState)||(this._webcamProducerPromise=(()=>ff(this,void 0,void 0,(function*(){var e,t;try{const t=this._webcamPaused,r=yield this._sendTransport.produce(Object.assign(Object.assign({track:this._webcamTrack,disableTrackOnPause:!1,stopTracks:!1},Sg("video",!1,Object.assign(Object.assign({},this._features),{vp9On:this._features.sfuVp9On}))),{appData:{streamId:rv,sourceClientId:this._selfId,screenShare:!1,source:"webcam",paused:t}}));t?r.pause():r.resume(),this._webcamProducer=r,this._qualityMonitor.addProducer(this._selfId,r.id),r.observer.once("close",(()=>{var e;Yg.info('webcamProducer "close" event'),r.appData.localClosed&&(null===(e=this._vegaConnection)||void 0===e||e.message("closeProducers",{producerIds:[r.id]})),this._webcamProducer=null,this._webcamProducerPromise=null,this._qualityMonitor.removeProducer(this._selfId,r.id)})),this._webcamTrack&&this._webcamTrack!==(null===(e=this._webcamProducer)||void 0===e?void 0:e.track)&&(this._webcamProducerPromise=null,this._replaceWebcamTrack()),this._webcamPaused!==this._webcamProducer.paused&&this._pauseResumeWebcam()}catch(e){Yg.error("webcamProducer failed:%o",e)}finally{this._webcamProducerPromise=null,this._webcamTrack||(this._stopProducer(this._webcamProducer),this._webcamProducer=null),this._features.lowBandwidth&&this._screenVideoTrack&&(null===(t=this._webcamProducer)||void 0===t||t.setMaxSpatialLayer(0))}})))())}))}_replaceWebcamTrack(){return ff(this,void 0,void 0,(function*(){Yg.info("_replaceWebcamTrack()"),this._sendTransport&&this._webcamTrack&&!this._webcamProducerPromise&&(this._webcamProducer||!this._webcamTrack.enabled?this._webcamProducer.track!==this._webcamTrack&&(yield this._webcamProducer.replaceTrack({track:this._webcamTrack}),yield this._replaceWebcamTrack()):yield this._internalSendWebcam())}))}_pauseResumeWebcam(){var e,t;Yg.info("_pauseResumeWebcam()"),this._webcamProducer&&!this._webcamProducer.closed&&this._webcamPaused!==this._webcamProducer.paused&&(this._webcamPaused?(this._webcamProducer.pause(),null===(e=this._vegaConnection)||void 0===e||e.message("pauseProducers",{producerIds:[this._webcamProducer.id]})):(this._webcamProducer.resume(),null===(t=this._vegaConnection)||void 0===t||t.message("resumeProducers",{producerIds:[this._webcamProducer.id]})),this._pauseResumeWebcam())}_sendWebcam(e){return ff(this,void 0,void 0,(function*(){return Yg.info("_sendWebcam() [track:%o]",e),this._webcamTrack=e,this._webcamProducer?yield this._replaceWebcamTrack():this._webcamProducerPromise?void 0:this._sendTransport?yield this._internalSendWebcam():void 0}))}_internalSendScreenVideo(){return ff(this,void 0,void 0,(function*(){Yg.info("_internalSendScreenVideo()"),this._screenVideoProducerPromise=(()=>ff(this,void 0,void 0,(function*(){var e,t;try{if(!this._screenVideoTrack||!this._sendTransport||this._screenVideoProducer)return void(this._screenVideoProducerPromise=null);const t=yield this._sendTransport.produce(Object.assign(Object.assign({track:this._screenVideoTrack,disableTrackOnPause:!1,stopTracks:!1},Sg("video",!1,Object.assign(Object.assign({},this._features),{vp9On:this._features.sfuVp9On}))),{appData:{streamId:iv,sourceClientId:this._selfId,screenShare:!0,source:"screenvideo",paused:!1}}));this._screenVideoProducer=t,this._qualityMonitor.addProducer(this._selfId,t.id),t.observer.once("close",(()=>{var e;Yg.info('screenVideoProducer "close" event'),t.appData.localClosed&&(null===(e=this._vegaConnection)||void 0===e||e.message("closeProducers",{producerIds:[t.id]})),this._screenVideoProducer=null,this._screenVideoProducerPromise=null,this._qualityMonitor.removeProducer(this._selfId,t.id)})),this._screenVideoTrack!==this._screenVideoProducer.track&&(yield this._replaceScreenVideoTrack()),this._features.lowBandwidth&&(null===(e=this._webcamProducer)||void 0===e||e.setMaxSpatialLayer(0))}catch(e){Yg.error("screenVideoProducer failed:%o",e)}finally{this._screenVideoProducerPromise=null,this._screenVideoTrack||(yield this._stopProducer(this._screenVideoProducer),this._screenVideoProducer=null,this._features.lowBandwidth&&(null===(t=this._webcamProducer)||void 0===t||t.setMaxSpatialLayer(Number.MAX_VALUE)))}})))()}))}_replaceScreenVideoTrack(){return ff(this,void 0,void 0,(function*(){Yg.info("_replaceScreenVideoTrack()"),this._screenVideoTrack&&this._screenVideoProducer&&!this._screenVideoProducer.closed&&this._screenVideoProducer.track!==this._screenVideoTrack&&(yield this._screenVideoProducer.replaceTrack({track:this._screenVideoTrack}),yield this._replaceScreenVideoTrack())}))}_sendScreenVideo(e){return ff(this,void 0,void 0,(function*(){return Yg.info("_sendScreenVideo() [track:%o]",e),this._screenVideoTrack=e,this._screenVideoProducer?yield this._replaceScreenVideoTrack():this._screenVideoProducerPromise?void 0:this._sendTransport?yield this._internalSendScreenVideo():void 0}))}_internalSendScreenAudio(){return ff(this,void 0,void 0,(function*(){Yg.info("_internalSendScreenAudio()"),this._screenAudioProducerPromise=(()=>ff(this,void 0,void 0,(function*(){try{if(!this._screenAudioTrack||!this._sendTransport||this._screenAudioProducer)return void(this._screenAudioProducerPromise=null);const e=yield this._sendTransport.produce(Object.assign(Object.assign({track:this._screenAudioTrack,disableTrackOnPause:!1,stopTracks:!1},Sg("audio",!1,Object.assign(Object.assign({},this._features),{vp9On:this._features.sfuVp9On}))),{appData:{streamId:iv,sourceClientId:this._selfId,screenShare:!0,source:"screenaudio",paused:!1}}));this._screenAudioProducer=e,this._qualityMonitor.addProducer(this._selfId,e.id),e.observer.once("close",(()=>{var t;Yg.info('screenAudioProducer "close" event'),e.appData.localClosed&&(null===(t=this._vegaConnection)||void 0===t||t.message("closeProducers",{producerIds:[e.id]})),this._screenAudioProducer=null,this._screenAudioProducerPromise=null,this._qualityMonitor.removeProducer(this._selfId,e.id)})),this._screenAudioTrack!==this._screenAudioProducer.track&&(yield this._replaceScreenAudioTrack())}catch(e){Yg.error("screenAudioProducer failed:%o",e)}finally{this._screenAudioProducerPromise=null,this._screenAudioTrack||(yield this._stopProducer(this._screenAudioProducer),this._screenAudioProducer=null)}})))()}))}_replaceScreenAudioTrack(){return ff(this,void 0,void 0,(function*(){Yg.info("_replaceScreenAudioTrack()"),this._screenAudioTrack&&this._screenAudioProducer&&!this._screenAudioProducer.closed&&this._screenAudioProducer.track!==this._screenAudioTrack&&(yield this._screenAudioProducer.replaceTrack({track:this._screenAudioTrack}),yield this._replaceScreenAudioTrack())}))}_sendScreenAudio(e){return ff(this,void 0,void 0,(function*(){return Yg.info("_sendScreenAudio() [track:%o]",e),this._screenAudioTrack=e,this._screenAudioProducer?yield this._replaceScreenAudioTrack():this._screenAudioProducerPromise?void 0:this._sendTransport?yield this._internalSendScreenAudio():void 0}))}_stopProducer(e){Yg.info("_stopProducer()"),e&&!e.closed&&(e.appData.localClosed=!0,e.close())}isInitializedWith({selfId:e,roomName:t,isSfu:r}){return this._selfId===e&&this._room.name===t&&Boolean(r)}setEventClaim(e){var t;this._eventClaim=e,null===(t=this._vegaConnection)||void 0===t||t.message("eventClaim",{eventClaim:e})}setColocation(e){var t;this._colocation=e,null===(t=this._vegaConnection)||void 0===t||t.message("setColocation",{colocation:e}),e||!this._micScoreProducer||this._micScoreProducerPromise||this._stopMicScoreProducer(),this._syncMicAnalyser(),wf.sendEvent("colocation_changed",{colocation:e})}setAudioOnly(e){var t;null===(t=this._vegaConnection)||void 0===t||t.message(e?"enableAudioOnly":"disableAudioOnly")}setRemoteScreenshareVideoTrackIds(){}setRoomSessionId(e){this._roomSessionId=e}disconnect(e,t,r){var i;if(Yg.info("disconnect() [clientIdOrStreamId:%s, eventClaim:%s]",e,r),this._clientStates.has(e)){const t=this._clientStates.get(e);t.hasAcceptedWebcamStream=!1,t.hasAcceptedScreenStream=!1,this._syncIncomingStreamsWithPWA(e)}r&&(this._eventClaim=r,null===(i=this._vegaConnection)||void 0===i||i.message("eventClaim",{eventClaim:r}))}replaceTrack(e,t){"audio"===t.kind&&(t.effectTrack||this._monitorAudioTrack(t),this._micTrack=t,this._replaceMicTrack()),"video"===t.kind&&(t.effectTrack||this._monitorVideoTrack(t),this._webcamTrack=t,this._replaceWebcamTrack())}removeStream(e,t,r){var i;Yg.info("removeStream() [streamId:%s, requestedByClientId:%s]",e,r),this._emitToSignal(rm,{streamId:iv,requestedByClientId:r}),this._stopProducer(this._screenVideoProducer),this._screenVideoProducer=null,this._screenVideoTrack=null,this._stopProducer(this._screenAudioProducer),this._screenAudioProducer=null,this._screenAudioTrack=null,this._features.lowBandwidth&&(null===(i=this._webcamProducer)||void 0===i||i.setMaxSpatialLayer(Number.MAX_VALUE))}_onMicAnalyserScoreUpdated(e){var t,r;null===(r=null===(t=this._micAnalyserDebugger)||void 0===t?void 0:t.onScoreUpdated)||void 0===r||r.call(t,e),this._sendMicScore(this._micPaused?0:e.out)}addNewStream(e,t,r,i,n=[]){if("0"===e){this._micPaused=r,this._webcamPaused=i;const e=t.getVideoTracks()[0],s=t.getAudioTracks()[0];if(e){this._sendWebcam(e),e.effectTrack||this._monitorVideoTrack(e);const t=n.find((e=>"video"===e.kind));t&&this._monitorVideoTrack(t)}if(s){this._sendMic(s),this._syncMicAnalyser(),s.effectTrack||this._monitorAudioTrack(s);const e=n.find((e=>"audio"===e.kind));e&&this._monitorAudioTrack(e)}this._localStreamDeregisterFunction&&(this._localStreamDeregisterFunction(),this._localStreamDeregisterFunction=null);const o=e=>{const{enable:t,track:r}=e.detail;this._webcamPaused=!t,this._pauseResumeWebcam(),this._handleStopOrResumeVideo({enable:t,track:r})};t.addEventListener("stopresumevideo",o),this._localStreamDeregisterFunction=()=>{t.removeEventListener("stopresumevideo",o)}}else{const e=t.getVideoTracks()[0],r=t.getAudioTracks()[0];e&&this._sendScreenVideo(e),r&&this._sendScreenAudio(r),this._emitScreenshareStarted()}}_syncMicAnalyser(){if(!this._micTrack||!this._colocation||this._micAnalyser)return this._micAnalyser&&!this._colocation?(this._micAnalyser.close(),void(this._micAnalyser=null)):void 0;this._micAnalyser=function({micTrack:e,params:t,onScoreUpdated:r}){const i=new AudioContext;let n=null,s=null,o=null,a=!1;const c=e=>ff(this,void 0,void 0,(function*(){if(o&&a&&o.stop(),a=!1,e&&t.separateTrack)try{const r=yield navigator.mediaDevices.getUserMedia({audio:Object.assign({deviceId:null==o?void 0:o.getSettings().deviceId},t.separateTrack),video:!1});e=r.getAudioTracks()[0],a=!0}catch(e){Hg.warn("unable to fetch new track for colocation speaker analysis, using current",e)}if(o=e,s&&(s.disconnect(),s=null),e){const t=new MediaStream([e]);s=i.createMediaStreamSource(t),s.connect(n)}}));let d;const l=e=>{if(clearInterval(d),t=Object.assign(Object.assign({},qg),e),!n||n.fftSize!==2*t.bins){let e=null;n&&(e=o,c(null)),n=i.createAnalyser(),n.fftSize=2*t.bins,e&&c(e)}const s=new Uint8Array(n.frequencyBinCount),a=[];n.minDecibels=t.minDecibels,n.maxDecibels=t.maxDecibels,n.smoothingTimeConstant=t.smoothingTimeConstant;const l=t.initScript&&new Function("f","setTrack","lastTrack",t.initScript.join("\n")),u=t.scoreScript&&new Function("bins","g","f",t.scoreScript.join("\n")),p=t.scoreFormula&&new Function("bands",`return ${t.scoreFormula}`),h=t.outFormula&&new Function("score","avg","max","scores",`return ${t.outFormula}`),f=t.binFormula&&new Function("bin","index",`return ${t.binFormula}`);let m=0;const g=l&&l(Gg,c,o);d=setInterval((()=>{n.getByteFrequencyData(s);let e=0;if(p){const r=t.bands.map((e=>{const t=e.map((e=>f(s[e]/255,e)));return{avg:t.reduce(((e,t)=>e+t),0)/e.length,min:t.reduce(((e,t)=>Math.min(e,t/255)),Number.MAX_VALUE),max:t.reduce(((e,t)=>Math.max(e,t/255)),0)}}));e=p(r)||0}else u&&(e=u(s,g,Gg),isNaN(e)&&(e=0));if(a.push(e),a.length>t.aggSize&&a.shift(),m++,m>=t.reportRate){m=0;const t=a.reduce(((e,t)=>Math.max(e,t)),0),i=a.reduce(((e,t)=>e+t),0)/a.length,n=h(e,i,t,a);r({bins:s,score:e,max:t,avg:i,out:n})}}),1e3/t.sampleRate)};return l(t),c(e),{setParams:l,setTrack:c,close(){c(null),clearInterval(d),i.close()}}}({micTrack:this._micTrack,onScoreUpdated:this._onMicAnalyserScoreUpdated.bind(this)})}stopOrResumeAudio(e,t){Yg.info("stopOrResumeAudio() [enabled:%s]",t),this._micPaused=!t,this._pauseResumeMic()}_handleStopOrResumeVideo({enable:e,track:t}){e?this._sendWebcam(t):this._webcamProducer&&!this._webcamProducer.closed&&this._webcamProducer.track===t&&(this._stopProducer(this._webcamProducer),this._webcamProducer=null,this._webcamTrack=null)}stopOrResumeVideo(e,t){var r;if(Yg.info("stopOrResumeVideo() [enable:%s]",t),this._webcamPaused=!t,this._pauseResumeWebcam(),["chrome","safari"].includes(ev))if(t){if(0===e.getVideoTracks().length){const r=this._webrtcProvider.getMediaConstraints().video;navigator.mediaDevices.getUserMedia({video:r}).then((r=>{const i=r.getVideoTracks()[0];e.addTrack(i),this._monitorVideoTrack(i),this._emitToPWA(Sm,{streamId:e.id,tracks:[i],screenShare:!1}),this._handleStopOrResumeVideo({enable:t,track:i})}))}}else{clearTimeout(this._stopCameraTimeout);const i="ended"===(null===(r=e.getVideoTracks().find((e=>!e.enabled)))||void 0===r?void 0:r.readyState)?0:5e3;this._stopCameraTimeout=setTimeout((()=>{e.getVideoTracks().forEach((r=>{!1===r.enabled&&(r.stop(),e.removeTrack(r),this._emitToPWA(Cm,{stream:e,track:r}),this._handleStopOrResumeVideo({enable:t,track:r}))}))}),i)}}supportsScreenShareAudio(){return!0}acceptNewStream({streamId:e,clientId:t}){Yg.info("acceptNewStream()",{streamId:e,clientId:t});const r=this._getOrCreateClientState(t);e!==t?(r.hasAcceptedScreenStream=!0,r.hasEmittedScreenStream=!1):(r.hasAcceptedWebcamStream=!0,r.hasEmittedWebcamStream=!1),this._syncIncomingStreamsWithPWA(t)}updateStreamResolution(e,t,{width:r,height:i}){var n,s;Yg.info("updateStreamResolution()",{streamId:e,width:r,height:i});const o=this._streamIdToVideoConsumerId.get(e),a=this._consumers.get(o);if(!a)return void this._streamIdToVideoResolution.set(e,{width:r,height:i});const c=function(e){let t=0;return e.forEach((e=>{var r,i;e._closed||e._paused||"webcam"!==(null===(r=e._appData)||void 0===r?void 0:r.source)&&"screenvideo"!==(null===(i=e._appData)||void 0===i?void 0:i.source)||t++})),t}(this._consumers),d=function(e){var t,r,i;return/T3/.test((null===(i=null===(r=null===(t=e._rtpParameters)||void 0===t?void 0:t.encodings)||void 0===r?void 0:r[0])||void 0===i?void 0:i.scalabilityMode)||"")?3:2}(a),{spatialLayer:l,temporalLayer:u}=function({width:e,height:t},{numberOfActiveVideos:r,numberOfTemporalLayers:i,uncappedSingleRemoteVideoOn:n}){const s=Math.max(e,t);let o=s>=480?s>=960?2:1:0,a=i-1;return s<100&&(a=Math.max(i-2,0)),r>8&&0===o&&(a=Math.max(i-2,0)),r<4&&s>300&&0===o&&(o=1),n&&1===r&&(o=2,a=i-1),{spatialLayer:o,temporalLayer:a}}({width:r,height:i},{numberOfActiveVideos:c,numberOfTemporalLayers:d,uncappedSingleRemoteVideoOn:null===(n=this._features)||void 0===n?void 0:n.uncappedSingleRemoteVideoOn});a.appData.spatialLayer===l&&a.appData.temporalLayer===u||(a.appData.spatialLayer=l,a.appData.temporalLayer=u,null===(s=this._vegaConnection)||void 0===s||s.message("setConsumersPreferredLayers",{consumerIds:[o],spatialLayer:l,temporalLayer:u}))}disconnectAll(){var e,t,r,i;this._reconnect=!1,this._reconnectTimeOut&&(clearTimeout(this._reconnectTimeOut),this._reconnectTimeOut=null),this._socketListenerDeregisterFunctions.forEach((e=>{e()})),this._localStreamDeregisterFunction&&(this._localStreamDeregisterFunction(),this._localStreamDeregisterFunction=null),this._socketListenerDeregisterFunctions=[],null===(e=this._vegaConnection)||void 0===e||e.removeAllListeners(),null===(t=this._vegaConnection)||void 0===t||t.close(),null===(r=this._sendTransport)||void 0===r||r.close(),null===(i=this._receiveTransport)||void 0===i||i.close(),this._micTrack=null,this._webcamTrack=null,this._screenVideoTrack=null,this._screenAudioTrack=null,this._streamIdToVideoConsumerId.clear(),this._mediasoupDevice=null}sendAudioMutedStats(e){wf.sendEvent("audio_muted",{muted:e})}sendVideoMutedStats(e){wf.sendEvent("video_muted",{muted:e})}sendStatsCustomEvent(e,t){wf.sendEvent(e,t)}rtcStatsDisconnect(){wf.server.close()}rtcStatsReconnect(){wf.server.connected||wf.server.connect()}_monitorAudioTrack(e){var t,r;(null===(t=this._audioTrackBeingMonitored)||void 0===t?void 0:t.id)!==e.id&&(null===(r=this._audioTrackBeingMonitored)||void 0===r||r.removeEventListener("ended",this._audioTrackOnEnded),e.addEventListener("ended",this._audioTrackOnEnded),this._audioTrackBeingMonitored=e)}_monitorVideoTrack(e){var t,r;(null===(t=this._videoTrackBeingMonitored)||void 0===t?void 0:t.id)!==e.id&&(null===(r=this._videoTrackBeingMonitored)||void 0===r||r.removeEventListener("ended",this._videoTrackOnEnded),e.addEventListener("ended",this._videoTrackOnEnded),this._videoTrackBeingMonitored=e)}_onMessage(e){return ff(this,void 0,void 0,(function*(){const{method:t,data:r}=e;return Promise.resolve().then((()=>{switch(t){case"consumerReady":return this._onConsumerReady(r);case"consumerClosed":return this._onConsumerClosed(r);case"consumerPaused":return this._onConsumerPaused(r);case"consumerResumed":return this._onConsumerResumed(r);case"dataConsumerReady":return this._onDataConsumerReady(r);case"dataConsumerClosed":return this._onDataConsumerClosed(r);case"dominantSpeaker":return this._onDominantSpeaker(r);case"consumerScore":return this._onConsumerScore(r);case"producerScore":return this._onProducerScore(r);default:return void Yg.info(`unknown message method "${t}"`)}})).catch((e=>{Yg.error('"message" failed [error:%o]',e)}))}))}_onConsumerReady(e){return ff(this,void 0,void 0,(function*(){Yg.info("_onConsumerReady()",{id:e.id,producerId:e.producerId});const t=yield this._receiveTransport.consume(e);if(t.pause(),t.appData.localPaused=!0,t.appData.spatialLayer=2,this._consumers.set(t.id,t),this._qualityMonitor.addConsumer(t.appData.sourceClientId,t.id),t.observer.once("close",(()=>{this._consumers.delete(t.id),this._qualityMonitor.removeConsumer(t.appData.sourceClientId,t.id),this._consumerClosedCleanup(t)})),this._features.increaseIncomingMediaBufferOn&&t.rtpReceiver)try{t.rtpReceiver.jitterBufferTarget=Wf,t.rtpReceiver.playoutDelayHint=.4}catch(e){Yg.error("Error during setting jitter buffer target:",e)}const{sourceClientId:r,screenShare:i,streamId:n}=t.appData,s=this._getOrCreateClientState(r);i?(s.hasEmittedScreenStream=!1,s.screenShareStreamId=n):(s.hasEmittedWebcamStream=!1,s.camStreamId=n);let o=i?s.screenStream:s.webcamStream;o&&o.inboundId===n||(o=new MediaStream,o.inboundId=n,i?s.screenStream=o:s.webcamStream=o),"video"===t.kind&&this._streamIdToVideoConsumerId.set(o.id,t.id),o.addTrack(t.track),this._syncIncomingStreamsWithPWA(r);const a=this._streamIdToVideoResolution.get(o.id);a&&(this.updateStreamResolution(o.id,null,a),this._streamIdToVideoResolution.delete(o.id))}))}_onConsumerClosed({consumerId:e,reason:t}){var r;return ff(this,void 0,void 0,(function*(){Yg.info("_onConsumerClosed()",{consumerId:e,reason:t}),null===(r=this._consumers.get(e))||void 0===r||r.close()}))}_onConsumerPaused({consumerId:e}){Yg.info("_onConsumerPaused()",{consumerId:e});const t=this._consumers.get(e);t&&(t.appData.remotePaused=!0,t.pause())}_onConsumerResumed({consumerId:e}){Yg.info("_onConsumerResumed()",{consumerId:e});const t=this._consumers.get(e);t&&(t.appData.remotePaused=!1,t.appData.localPaused||t.resume())}_onConsumerScore({consumerId:e,kind:t,score:r}){Yg.info("_onConsumerScore()",{consumerId:e,kind:t,score:r});const{appData:{sourceClientId:i}}=this._consumers.get(e)||{appData:{}};i&&this._qualityMonitor.addConsumerScore(i,e,t,r)}_onProducerScore({producerId:e,kind:t,score:r}){Yg.info("_onProducerScore()",{producerId:e,kind:t,score:r}),[this._micProducer,this._webcamProducer,this._screenVideoProducer,this._screenAudioProducer].forEach((i=>{(null==i?void 0:i.id)===e&&this._qualityMonitor.addProducerScore(this._selfId,e,t,r)}))}_onDataConsumerReady(e){return ff(this,void 0,void 0,(function*(){Yg.info("_onDataConsumerReady()",{id:e.id,producerId:e.producerId});const t=yield this._receiveTransport.consumeData(e);this._dataConsumers.set(t.id,t),t.once("close",(()=>{this._dataConsumers.delete(t.id)}));const{clientId:r}=t.appData;t.on("message",(e=>{var r;if(!this._micAnalyserDebugger)return;if("string"!=typeof e)return;const{score:i}=JSON.parse(e);i&&(null===(r=this._micAnalyserDebugger)||void 0===r||r.onConsumerScore(t.appData.clientId,i))})),this._syncIncomingStreamsWithPWA(r)}))}_onDataConsumerClosed({dataConsumerId:e,reason:t}){return ff(this,void 0,void 0,(function*(){Yg.info("_onDataConsumerClosed()",{dataConsumerId:e,reason:t});const r=this._dataConsumers.get(e);null==r||r.close()}))}_onDominantSpeaker({consumerId:e}){const t=this._consumers.get(e);if(!t)return;const{sourceClientId:r}=t.appData;this._emitToPWA(rg,{clientId:r})}_consumerClosedCleanup(e){const{sourceClientId:t,screenShare:r}=e.appData,i=this._getOrCreateClientState(t),n=r?i.screenStream:i.webcamStream;n&&(n.removeTrack(e.track),0===n.getTracks().length&&(this._streamIdToVideoConsumerId.delete(n.id),this._streamIdToVideoResolution.delete(n.id),r?(i.screenStream=null,i.hasEmittedScreenStream=!1,i.screenShareStreamId=null):(i.hasEmittedWebcamStream=!1,i.camStreamId=null)))}_syncIncomingStreamsWithPWA(e){var t,r;const i=this._getOrCreateClientState(e),{webcamStream:n,screenStream:s,hasEmittedWebcamStream:o,hasEmittedScreenStream:a,hasAcceptedWebcamStream:c,hasAcceptedScreenStream:d,screenShareStreamId:l,camStreamId:u}=i,p=[],h=[];this._consumers.forEach((t=>{if(t.appData.sourceClientId!==e)return;const r=t.appData.screenShare?d:c;!t.appData.localPaused!==r&&(r?(t.appData.remotePaused||t.resume(),t.appData.localPaused=!1,h.push(t.id)):(t.pause(),t.appData.localPaused=!0,p.push(t.id)))})),p.length>0&&(null===(t=this._vegaConnection)||void 0===t||t.message("pauseConsumers",{consumerIds:p})),h.length>0&&(null===(r=this._vegaConnection)||void 0===r||r.message("resumeConsumers",{consumerIds:h})),n&&!o&&c&&(this._emitToPWA(ym,{clientId:e,stream:n,streamId:u,streamType:"webcam"}),i.hasEmittedWebcamStream=!0),s&&!a&&d&&(this._emitToPWA(ym,{clientId:e,stream:s,streamId:l,streamType:"screenshare"}),i.hasEmittedScreenStream=!0)}_getOrCreateClientState(e){let t=this._clientStates.get(e);return t||(t={hasAcceptedWebcamStream:!1,hasAcceptedScreenStream:!1,hasEmittedWebcamStream:!1,hasEmittedScreenStream:!1,webcamStream:null,screenStream:null,screenShareStreamId:null,camStreamId:null},this._clientStates.set(e,t)),t}_emitToPWA(e,t){this._emitter.emit(e,t)}_emitToSignal(e,t,r){this._serverSocket.emit(e,t,r)}shouldAcceptStreamsFromBothSides(){return!0}setMicAnalyserDebugger(e){this._micAnalyserDebugger=e}setMicAnalyserParams(e){var t;null===(t=this._micAnalyser)||void 0===t||t.setParams(e)}hasClient(e){return this._clientStates.has(e)}}class sv{constructor({emitter:e,serverSocket:t,webrtcProvider:r,features:i}){this.emitter=e,this.currentManager=null,t.on(dm,(({room:n,selfId:s,error:o,eventClaim:a})=>{if(o)return;const c={selfId:s,room:n,emitter:e,serverSocket:t,webrtcProvider:r,features:i,eventClaim:a},d=!!n.sfuServer;if(ov=d?"group":"normal",this.currentManager){if(this.currentManager.isInitializedWith({selfId:s,roomName:n.name,isSfu:d}))return void(this.currentManager.setEventClaim&&a&&this.currentManager.setEventClaim(a));this.currentManager.disconnectAll(),e.emit(_m)}let l=null;l=d?new nv(c):new zg(c),l.rtcStatsReconnect(),l.setupSocketListeners(),e.emit(wm,{rtcManager:l}),this.currentManager=l,t.setRtcManager(l)}))}stopRtcManager(){this.currentManager&&(this.currentManager.disconnectAll(),this.emitter.emit(_m))}}let ov="";const av=()=>ov,cv=new hf,dv={print:(...e)=>console.debug(e[0],...e.slice(1))};cv.withDebugLogger(dv);const lv=new class{constructor(){this.BEGIN_PACKET_LOSS_PERIOD_THRESHOLD=.04,this.END_PACKET_LOSS_PERIOD_THRESHOLD=.005,this.INTERVAL_DIFF_THRESHOLD_MS=4e3,this.STALE_MEASUREMENT_TIMEOUT_MS=1e4,this.MINIMUM_INTERVAL_MS=3e4,this.ssrcsHistory=new Map,this.staleMeasurementTimeouts=new Map}addPacketLossMeasurement(e,t,r){this.handleStaleMeasurements(e);const i=t>this.BEGIN_PACKET_LOSS_PERIOD_THRESHOLD;let n=this.ssrcsHistory.get(e);if(!n)return n={id:e,hasActivePacketLoss:i,currPeriod:i?{begin:r}:void 0,hasPeriodicPacketLoss:!1},void this.ssrcsHistory.set(e,n);n.hasActivePacketLoss?t<this.END_PACKET_LOSS_PERIOD_THRESHOLD&&(this.endPacketLossPeriod(n,r),n.prevIntervalInMs&&n.prevIntervalInMs<this.MINIMUM_INTERVAL_MS&&this.ssrcsHistory.delete(e)):i&&(n.hasActivePacketLoss=!0,n.currPeriod={begin:r})}hasPeriodicPacketLoss(e,t){const r=this.ssrcsHistory.get(e);return r&&this.prevIntervalExceeded(r,t)?(this.ssrcsHistory.delete(r.id),!1):(null==r?void 0:r.hasPeriodicPacketLoss)||!1}prevIntervalExceeded(e,t){if(e.prevPeriod&&e.prevIntervalInMs){return t>this.calculatePeriodCenterTimestamp(e.prevPeriod)+e.prevIntervalInMs+this.INTERVAL_DIFF_THRESHOLD_MS}return!1}handleStaleMeasurements(e){const t=this.staleMeasurementTimeouts.get(e);t&&clearTimeout(t),this.staleMeasurementTimeouts.set(e,setTimeout((()=>{cv.debug("handleStaleMeasurements() [measurements invalid for ssrc: %s]",e),this.ssrcsHistory.delete(e)}),this.STALE_MEASUREMENT_TIMEOUT_MS))}endPacketLossPeriod(e,t){if(cv.debug("endPacketLossPeriod() [ssrcId: %s, timestamp: %s]",e.id,t),!e.currPeriod)throw new Error("No packet loss period for "+e.id);e.prevPeriod?(e.currPeriod.end=t,this.addNewPacketLossInterval(e)):e.prevPeriod=Object.assign(Object.assign({},e.currPeriod),{end:t}),delete e.currPeriod,e.hasActivePacketLoss=!1}addNewPacketLossInterval(e){if(cv.debug("addNewPacketLossInterval() [ssrcId: %s, prevIntervalInMs: %s]",e.id,e.prevIntervalInMs),!e.currPeriod||!e.prevPeriod)throw new Error("missing period timestamps");const t=this.calculatePeriodCenterTimestamp(e.prevPeriod),r=this.calculatePeriodCenterTimestamp(e.currPeriod)-t;if(e.prevIntervalInMs){const t=Math.abs(e.prevIntervalInMs-r);e.hasPeriodicPacketLoss=t<this.INTERVAL_DIFF_THRESHOLD_MS,cv.debug("addNewPacketLossInterval() [hasPeriodicPacketLoss: %s, intervalDiffInMs: %s]",t<this.INTERVAL_DIFF_THRESHOLD_MS,t)}e.prevIntervalInMs=r,e.prevPeriod=e.currPeriod}calculatePeriodCenterTimestamp(e){if(!e.end)throw new Error("Missing period end timestamp");return e.begin+(e.end-e.begin)/2}},uv=[{id:"desync",enabled:({client:e,track:t,stats:r})=>!e.isLocalClient&&"audio"===(null==t?void 0:t.kind)&&"object"==typeof(null==r?void 0:r.tracks)&&Object.keys(r.tracks).length>1,check:({stats:e})=>{if(!e)return!1;const t={audio:0,video:0};Object.values(e.tracks).flatMap((e=>Object.values(e.ssrcs))).forEach((e=>{"audio"===e.kind&&e.jitter&&e.jitter>t.audio&&(t.audio=e.jitter),"video"===e.kind&&e.jitter&&e.jitter>t.video&&(t.video=e.jitter)}));return Math.abs(1e3*t.audio-1e3*t.video)>500}},{id:"no-track",enabled:()=>!0,check:({client:e,clients:t,kind:r,track:i})=>{if(!i&&!e.isLocalClient&&"video"===r){const e=t.find((e=>e.isLocalClient));if(e)return!e.isAudioOnlyModeEnabled}return!i}},{id:"ended-track",enabled:({track:e})=>!!e,check:({track:e})=>"ended"===(null==e?void 0:e.readyState)},{id:"no-track-stats",enabled:({hasLiveTrack:e})=>e,check:({client:e,clients:t,kind:r,ssrcs:i})=>{if(0===i.length&&!e.isLocalClient&&"video"===r){const e=t.find((e=>e.isLocalClient));if(e)return!e.isAudioOnlyModeEnabled}return 0===i.length}},{id:"dry-track",enabled:({hasLiveTrack:e,ssrcs:t})=>!(!e||!t),check:({client:e,clients:t,ssrcs:r})=>{let i=!1;if(r.forEach((e=>{i=i||((null==e?void 0:e.bitrate)||0)>0})),!i&&e.isLocalClient){const e=t.filter((e=>!e.isLocalClient));if(e.length>0)return!e.every((e=>e.isAudioOnlyModeEnabled))}return!i}},{id:"low-layer0-bitrate",enabled:({hasLiveTrack:e,ssrc0:t,kind:r,client:i})=>e&&"video"===r&&!!t&&!!(null==t?void 0:t.height)&&!i.isPresentation,check:({ssrc0:e})=>!!(null==e?void 0:e.bitrate)&&(((null==e?void 0:e.height)||0)<200&&e.bitrate<3e4)},{id:"quality-limitation-bw",enabled:({hasLiveTrack:e,stats:t,client:r,clients:i,kind:n})=>{if("normal"===av()){if(i.filter((e=>!e.isLocalClient)).some((e=>e.isAudioOnlyModeEnabled)))return!1}return e&&r.isLocalClient&&"video"===n&&!!t},check:({stats:e})=>!!e&&!!Object.values(e.tracks).find((e=>Object.values(e.ssrcs).find((e=>"bandwidth"===e.qualityLimitationReason))))},{id:"quality-limitation-cpu",enabled:({hasLiveTrack:e,stats:t,client:r,kind:i})=>e&&r.isLocalClient&&"video"===i&&!!t,check:({stats:e})=>!!e&&!!Object.values(e.tracks).find((e=>Object.values(e.ssrcs).find((e=>"cpu"===e.qualityLimitationReason))))},{id:"high-plirate",enabled:({hasLiveTrack:e,ssrc0:t})=>e&&!!t&&!!t.height,check:({ssrc0:e})=>((null==e?void 0:e.pliRate)||0)>2},{id:"extreme-plirate",enabled:({hasLiveTrack:e,ssrc0:t})=>e&&!!t&&!!t.height,check:({ssrc0:e})=>((null==e?void 0:e.pliRate)||0)>5},{id:"high-packetloss",enabled:({hasLiveTrack:e,ssrc0:t})=>e&&!!t&&"in"===t.direction,check:({ssrc0:e})=>((null==e?void 0:e.lossRatio)||0)>.02},{id:"extreme-packetloss",enabled:({hasLiveTrack:e,ssrc0:t})=>e&&!!t&&"in"===t.direction,check:({ssrc0:e})=>((null==e?void 0:e.lossRatio)||0)>.1},{id:"high-packetloss",enabled:({hasLiveTrack:e,ssrc0:t})=>e&&!!t&&"out"===t.direction,check:({ssrc0:e})=>((null==e?void 0:e.fractionLost)||0)>.02},{id:"extreme-packetloss",enabled:({hasLiveTrack:e,ssrc0:t})=>e&&!!t&&"out"===t.direction,check:({ssrc0:e})=>((null==e?void 0:e.fractionLost)||0)>.1},{id:"fps-below-20",enabled:({hasLiveTrack:e,ssrc0:t,kind:r,client:i})=>e&&!!t&&!!t.height&&"video"===r&&!i.isPresentation,check:({ssrc0:e})=>((null==e?void 0:e.height)||0)>180&&((null==e?void 0:e.fps)||0)<20},{id:"fps-below-10",enabled:({hasLiveTrack:e,ssrc0:t,kind:r,client:i})=>e&&!!t&&!!t.height&&"video"===r&&!i.isPresentation,check:({ssrc0:e})=>((null==e?void 0:e.fps)||0)<10},{id:"bad-network",enabled:({hasLiveTrack:e,ssrcs:t})=>e&&t.length>0,check:({client:e,clients:t,kind:r,ssrcs:i})=>{if(!i.some((e=>((null==e?void 0:e.bitrate)||0)>0))&&e.isLocalClient&&"video"===r){const e=t.filter((e=>!e.isLocalClient));if(e.length>0)return!e.every((e=>e.isAudioOnlyModeEnabled))}const n=i[0];return!!n&&(0===n.bitrate||(n.lossRatio||0)>.03||(n.fractionLost||0)>.03||!e.isPresentation&&"video"===r&&!!(null==n?void 0:n.bitrate)&&n.bitrate<3e4||"in"===n.direction&&!!n.pliRate&&n.pliRate>2)}},{id:"periodic-packet-loss",enabled:({client:e,hasLiveTrack:t,ssrc0:r})=>e.isLocalClient&&t&&!!(null==r?void 0:r.ssrc)&&"out"===(null==r?void 0:r.direction)&&((null==r?void 0:r.bitrate)||0)>0,check:({ssrc0:e})=>!(!e||!e.ssrc)&&(lv.addPacketLossMeasurement(e.ssrc,e.fractionLost||0,Date.now()),lv.hasPeriodicPacketLoss(e.ssrc,Date.now()))},{id:"cpu-pressure-serious",global:!0,enabled:({stats:e})=>{var t;return"cpu"===(null===(t=null==e?void 0:e.pressure)||void 0===t?void 0:t.source)},check:({stats:e})=>{var t;return"serious"===(null===(t=null==e?void 0:e.pressure)||void 0===t?void 0:t.state)}},{id:"cpu-pressure-critical",global:!0,enabled:({stats:e})=>{var t;return"cpu"===(null===(t=null==e?void 0:e.pressure)||void 0===t?void 0:t.source)},check:({stats:e})=>{var t;return"critical"===(null===(t=null==e?void 0:e.pressure)||void 0===t?void 0:t.state)}},{id:"concealed",enabled:({hasLiveTrack:e,ssrc0:t,kind:r})=>e&&!!t&&"audio"===r,check:({ssrc0:e})=>!!(null==e?void 0:e.bitrate)&&"in"===(null==e?void 0:e.direction)&&((null==e?void 0:e.audioLevel)||0)>=.001&&((null==e?void 0:e.audioConcealment)||0)>=.1},{id:"decelerated",enabled:({hasLiveTrack:e,ssrc0:t,kind:r})=>e&&!!t&&"audio"===r,check:({ssrc0:e})=>!!(null==e?void 0:e.bitrate)&&"in"===e.direction&&(e.audioLevel||0)>=.001&&((null==e?void 0:e.audioDeceleration)||0)>=.1},{id:"accelerated",enabled:({hasLiveTrack:e,ssrc0:t,kind:r})=>e&&!!t&&"audio"===r,check:({ssrc0:e})=>!!(null==e?void 0:e.bitrate)&&"in"===e.direction&&(e.audioLevel||0)>=.001&&(e.audioAcceleration||0)>=.1}];let pv=[],hv=null;const fv=[{id:"bitrate",enabled:({hasLiveTrack:e,track:t,ssrc0:r})=>e&&!!t&&!!r,value:({trackStats:e})=>Object.values((null==e?void 0:e.ssrcs)||{}).reduce(((e,t)=>e+((null==t?void 0:t.bitrate)||0)),0)},{id:"pixelrate",enabled:({hasLiveTrack:e,track:t,ssrc0:r,kind:i})=>e&&"video"===i&&!!t&&!!r&&!!r.height,value:({trackStats:e})=>Object.values((null==e?void 0:e.ssrcs)||{}).reduce(((e,t)=>e+(t.fps||0)*(t.width||0)*(t.height||0)),0)},{id:"height",enabled:({hasLiveTrack:e,track:t,trackStats:r,ssrc0:i,kind:n})=>e&&"video"===n&&!!r&&!!t&&!!i&&!!i.height,value:({trackStats:e})=>Object.values((null==e?void 0:e.ssrcs)||{}).reduce(((e,t)=>Math.max(e,t.fps>0?t.height:0)),0)},{id:"sourceHeight",enabled:({hasLiveTrack:e,track:t,ssrc0:r,kind:i})=>e&&"video"===i&&!!t&&!!r&&!!r.sourceHeight&&"out"===r.direction,value:({ssrc0:e})=>null==e?void 0:e.sourceHeight},{id:"packetloss",enabled:({hasLiveTrack:e,ssrc0:t})=>e&&!!t&&!!t.bitrate,value:({ssrc0:e})=>("in"===(null==e?void 0:e.direction)?e.lossRatio:null==e?void 0:e.fractionLost)||0},{id:"jitter",enabled:({hasLiveTrack:e,ssrc0:t})=>e&&!!t&&!!t.bitrate&&"in"===t.direction,value:({ssrc0:e})=>null==e?void 0:e.jitter},{id:"mos",enabled:({hasLiveTrack:e,ssrc0:t})=>e&&!!t&&!!t.bitrate&&"out"===t.direction,value:({ssrc0:e})=>{const t=((null==e?void 0:e.roundTripTime)||0)+2*((null==e?void 0:e.jitter)||0)+10;let r=t<160?93.2-t/40:93.2-(t-120)/10;r-=2.5*(100*((null==e?void 0:e.fractionLost)||0));return 1+.035*r+7e-6*r*(r-60)*(100-r)}},{id:"rendered",value:()=>1},{id:"active",value:({hasLiveTrack:e,track:t,ssrc0:r})=>e&&t&&r?1:0},{id:"cpu-pressure",global:!0,enabled:({stats:e})=>{var t;return"cpu"===(null===(t=null==e?void 0:e.pressure)||void 0===t?void 0:t.source)},value:({stats:e})=>{var t;return{nominal:.25,fair:.5,serious:.75,critical:1}[(null===(t=null==e?void 0:e.pressure)||void 0===t?void 0:t.state)||""]||0}},{id:"turn-usage",global:!0,enabled:({stats:e})=>!!Object.values((null==e?void 0:e.candidatePairs)||{}).length,value:({stats:e})=>Object.values((null==e?void 0:e.candidatePairs)||{}).some((e=>e.usingTurn))},{id:"turn-tls-usage",global:!0,enabled:({stats:e})=>!!Object.values((null==e?void 0:e.candidatePairs)||{}).length,value:({stats:e})=>Object.values((null==e?void 0:e.candidatePairs)||{}).some((e=>"tls"===e.turnProtocol))},{id:"concealment",enabled:({hasLiveTrack:e,ssrc0:t,kind:r})=>e&&!!t&&!!t.bitrate&&"in"===t.direction&&"audio"===r&&(t.audioLevel||0)>=.001,value:({ssrc0:e})=>null==e?void 0:e.audioConcealment},{id:"deceleration",enabled:({hasLiveTrack:e,ssrc0:t,kind:r})=>e&&!!t&&!!t.bitrate&&"in"===t.direction&&"audio"===r&&(t.audioLevel||0)>=.001,value:({ssrc0:e})=>null==e?void 0:e.audioDeceleration},{id:"acceleration",enabled:({hasLiveTrack:e,ssrc0:t,kind:r})=>e&&!!t&&!!t.bitrate&&"in"===t.direction&&"audio"===r&&(t.audioLevel||0)>=.001,value:({ssrc0:e})=>null==e?void 0:e.audioAcceleration},{id:"qpf",enabled:({hasLiveTrack:e,track:t,ssrc0:r,kind:i})=>e&&"video"===i&&!!t&&!!r&&!!r.height,value:({trackStats:e})=>Object.values((null==e?void 0:e.ssrcs)||{}).reduce(((e,t)=>e+(t.qpf||0)),0)}];let mv,gv,vv;const bv=()=>{mv={},gv={},vv={aggregated:{issues:gv,metrics:mv}}};function yv(e,t){Object.values(mv).forEach((e=>{e.curTicks=0,e.curSum=0,e.curMax=0,e.curMin=0,e.curAvg=0})),Object.values(gv).forEach((e=>{e.curTicks=0,e.curRegistered=0,e.active=!1})),t.find((e=>!e.isLocalClient))&&(t.forEach((r=>{const i=e[r.id];["video","audio","global"].forEach((e=>{var n,s;if(("global"!==e||r.isPresentation)&&!(null===(n=r[e])||void 0===n?void 0:n.enabled))return;if("global"===e&&!r.isLocalClient)return;let o=vv[r.id];o||(o={issues:{},metrics:{}},vv[r.id]=o);const a=null===(s=r[e])||void 0===s?void 0:s.track,c=!!a&&"ended"!==a.readyState,d=a&&i&&i.tracks[a.id],l=d?Object.values(d.ssrcs).sort(((e,t)=>(e.height||Number.MAX_SAFE_INTEGER)-(t.height||Number.MAX_SAFE_INTEGER))):[],u=l[0],p={client:r,clients:t,kind:e,track:a,trackStats:d,stats:i,hasLiveTrack:c,ssrc0:u,ssrcs:l,issues:o.issues,metrics:o.metrics},h="global"===e?"global":`${r.isLocalClient?"loc":"rem"}-${r.isPresentation?"pres":"cam"}-${e}`;fv.forEach((t=>{if(t.global&&"global"!==e)return;if(!t.global&&"global"===e)return;if(!t.enabled||t.enabled(p)){const e=`${h}-${t.id}`;let r=o.metrics[e];const i=t.value(p);r||(r={ticks:0,sum:0,avg:0,min:i,max:i},o.metrics[e]=r),r.ticks++,r.sum+=i,r.min=Math.min(r.min,i),r.max=Math.max(r.max,i),r.avg=r.sum/r.ticks;let n=mv[e];n||(n={ticks:0,sum:0,min:i,max:i,avg:0,curTicks:0,curMin:0,curMax:0,curAvg:0,curSum:0,totTicks:0,totMin:0,totMax:0,totAvg:0,totSum:0},mv[e]=n),n.ticks++,n.sum+=i,n.min=Math.min(n.min,i),n.max=Math.max(n.max,i),n.avg=n.sum/n.ticks,0===n.curTicks?(n.curMax=i,n.curMin=i,n.curSum=i):(n.curMax=Math.max(n.curMax,i),n.curMin=Math.min(n.curMin,i),n.curSum+=i),n.curTicks++}})),uv.forEach((t=>{if(t.global&&"global"!==e)return;if(!t.global&&"global"===e)return;const r=`${h}-${t.id}`,i=t.enabled(p);let n=o.issues[r],s=gv[r];if(i){n||(n={active:!1,ticks:0,registered:0,initial:0,periods:0,current:0,longest:0},o.issues[r]=n),n.ticks++,s||(s={active:!1,ticks:0,registered:0,initial:0,curTicks:0,curRegistered:0},gv[r]=s),s.ticks++,s.curTicks++;t.check(p)?(n.registered++,n.current++,n.active||(n.active=!0,n.periods++),n.ticks===n.initial+1&&(n.initial++,s.initial++),n.current>n.longest&&(n.longest=n.current),s.active=!0,s.registered++,s.curRegistered++):(n.active=!1,n.current=0)}else n&&(n.active=!1,n.current=0)}))}))})),Object.values(mv).forEach((e=>{e.curTicks&&(e.curAvg=e.curSum/e.curTicks,0===e.totTicks&&(e.totMin=e.curSum,e.totMax=e.curSum),e.totTicks++,e.totSum+=e.curSum,e.totMin=Math.min(e.totMin,e.curSum),e.totMax=Math.max(e.totMax,e.curSum),e.totAvg=e.totSum/e.totTicks)})),Object.values(gv).forEach((e=>{e.curTicks})),pv.forEach((r=>{var i;return null===(i=r.onUpdatedIssues)||void 0===i?void 0:i.call(r,vv,e,t)})))}function wv(e){return pv.push(e),hv||(hv=function(e,t=Lf,r=jf){return r.subscriptions.push(e),r.currentMonitor||(r.currentMonitor=Nf(r,t)),{stop(){var t;r.subscriptions=r.subscriptions.filter((t=>t!==e)),r.subscriptions.length||(null===(t=r.currentMonitor)||void 0===t||t.stop(),r.currentMonitor=null)}}}({onUpdatedStats:yv}).stop),{stop(){pv=pv.filter((t=>t!==e)),pv.length||(null==hv||hv(),hv=null,bv())}}}var _v;bv();const Sv="safari"===(null!==(_v=pi.default)&&void 0!==_v?_v:pi).browserDetails.browser,Cv=e=>e.split(/[^\d]/g).map((e=>parseInt(e,10)));function Rv({devices:e,videoId:t,audioId:r,options:i,type:n="ideal"}){const s=e.filter((e=>"audioinput"===e.kind)),o=e.filter((e=>"videoinput"===e.kind)),a=!r||!s.some((e=>e.deviceId===r)),c=!t||!o.some((e=>e.deviceId===t)),d=function({disableAEC:e,disableAGC:t,hd:r,lax:i,lowDataMode:n,preferredDeviceIds:s,resolution:o,simulcast:a,widescreen:c}){var d,l;let u=480,p=240;r&&(u=i||Sv?720:{min:360,ideal:720}),a&&(!1===r?(u=360,p=270):p=360);const h={audio:Object.assign({},s.audioId&&{deviceId:s.audioId}),video:Object.assign(Object.assign({},s.videoId?{deviceId:s.videoId}:{facingMode:"user"}),{height:n?p:u,frameRate:n&&!a?15:24})};if(i)return(null===(d=h.audio)||void 0===d?void 0:d.deviceId)||(h.audio=!0),null===(l=h.video)||void 0===l||delete l.facingMode,h;if(o){const[e,t,r]=Cv(o);e&&(h.video.width={exact:e}),t&&(h.video.height={exact:t}),r&&(h.video.frameRate={exact:r}),delete h.video.facingMode}else h.video.aspectRatio=c?16/9:4/3;return t&&(h.audio.autoGainControl=!1),e&&(h.audio.echoCancellation=!1),h}(Object.assign({preferredDeviceIds:{audioId:a?null:{[n]:r},videoId:c?null:{[n]:t}}},i));return!1!==r&&s.length||delete d.audio,!1!==t&&o.length||delete d.video,d}const kv=new hf,Tv=/mobi/i.test(navigator.userAgent);class Pv extends Error{constructor(...e){super(...e),this.name="nodevices"}}function Ov(e){return e.audio||e.video?navigator.mediaDevices.getUserMedia(e).catch((t=>{const r=`${t}, ${JSON.stringify(e,null,2)}`;throw kv.error(`getUserMedia ${r}`),t})):Promise.reject(new Pv("No provided devices"))}function Ev(e,t,r,i){var n,s,o;let a={deviceId:null};return t?(a.label=t.label,t.getSettings&&(a=Object.assign(Object.assign({},a),t.getSettings())),a.deviceId?a:(t.getCapabilities&&(a.deviceId=t.getCapabilities().deviceId),a.deviceId?a:(t.label&&r&&(a.deviceId=null===(s=r.find((r=>t.label===r.label&&r.kind===e)))||void 0===s?void 0:s.deviceId),a.deviceId||(a.deviceId=null===(o=t.getConstraints())||void 0===o?void 0:o.deviceId,a.broken=1),a))):(i&&r&&(a.deviceId=null===(n=r.find((t=>t.deviceId===i&&t.kind===e)))||void 0===n?void 0:n.deviceId),a)}function Dv(e,t){t&&"audio"!==t||e.getAudioTracks().forEach((e=>e.stop())),t&&"video"!==t||e.getVideoTracks().forEach((e=>e.stop()))}function Iv(e,{replaceStream:t,fallback:r=!0}={}){var i;return ff(this,void 0,void 0,(function*(){let n,s,o,a=null;const c=!1===e.audioId?"video":!1===e.videoId&&"audio",d=Tv||"video"!==c,l=Rv(e),u=(e,t)=>(e.details=Object.assign({constraints:l,constraint:e.constraint||(null==t?void 0:t.constraint),newConstraints:s,fallback:r,stopTracks:d},e!==n&&{error:String(n)}),e),p=t=>ff(this,void 0,void 0,(function*(){if(l.audio&&l.video){try{a=yield Ov(Rv(Object.assign(Object.assign({},e),{audioId:!1})))}catch(e){"NotFoundError"!==e.name&&u(e,t)}try{a||(a=yield Ov(Rv(Object.assign(Object.assign({},e),{videoId:!1}))))}catch(e){u(e,t)}}}));d&&t&&Dv(t,c);try{a=yield Ov(l)}catch(s){if(n=s,!r)throw u(s);if("OverconstrainedError"===s.name){o={deviceId:{videoId:null,audioId:null},width:{lax:!0},height:{lax:!0},"":{audioId:null,videoId:null,lax:!0}}[s.constraint||""]}else if("NotFoundError"===s.name)yield p(s);else if("NotAllowedError"===s.name||"NotReadableError"===s.name||"AbortError"===s.name)if(t&&!d&&(Dv(t,c),o=e),"NotAllowedError"===s.name)yield p(s);else if("NotAllowedError"!==s.name){try{a=yield Ov(Rv(Object.assign(Object.assign({},e),{options:Object.assign(Object.assign({},e.options),{lax:!0})})))}catch(e){kv.warn("Tried getting stream again with laxer constraints, but failed: "+(""+e))}const t=(""+s).toLowerCase(),r={audio:"audioId",video:"videoId"}[(null===(i=/(video|audio)/.exec(t))||void 0===i?void 0:i[0])||c||""];if(!a&&r)try{a=yield Ov(Rv(Object.assign(Object.assign({},e),{[r]:null})))}catch(e){kv.warn(`Re-tried ${r} with no constraints, but failed: ${""+e}`)}if(!a){const t=r?[r]:["videoId","audioId"];for(const r of t){try{a=yield Ov(Rv(Object.assign(Object.assign({},e),{[r]:!1})))}catch(e){kv.warn(`Re-tried without ${r}, but failed: ${""+e}`)}if(a)break}}}}if(o){const t=c?{audio:{videoId:!1},video:{audioId:!1}}[c]:{};s=Rv(Object.assign(Object.assign(Object.assign(Object.assign({},e),o),{options:Object.assign(Object.assign({},e.options),{lax:o.lax})}),t));try{a=yield Ov(s)}catch(e){throw u(e,n)}}if(!a)throw u(n);let h;return t&&(d||Dv(t,c),h=function(e,t,r){const i=[];return r&&"audio"!==r||(i.push(...e.getAudioTracks()),t.getAudioTracks().forEach((t=>{t.replacement=!0,e.addTrack(t)}))),r&&"video"!==r||(i.push(...e.getVideoTracks()),t.getVideoTracks().forEach((t=>{t.replacement=!0,e.addTrack(t)}))),i.forEach((t=>{t.replaced=!0,e.removeTrack(t)})),i}(t,a,c),a=t),{error:n&&u(n),stream:a,replacedTracks:h}}))}function xv({oldDevices:e,newDevices:t,currentAudioId:r,currentVideoId:i,currentSpeakerId:n}){const s=function(e,t){const[r,i]=[e,t].map((e=>e.filter((e=>e.kind&&e.deviceId)).reduce(((e,t)=>Object.assign(Object.assign({},e),{[t.kind]:Object.assign(Object.assign({},e[t.kind]),{[t.deviceId]:t})})),{}))),n={};return e.forEach((e=>{e.kind&&e.deviceId&&(n[e.kind]||(n[e.kind]={added:{},removed:{},changed:{}}),i[e.kind]&&i[e.kind][e.deviceId]||(n[e.kind].removed[e.deviceId]=e))})),t.forEach((e=>{e.kind&&e.deviceId&&(n[e.kind]||(n[e.kind]={added:{},removed:{},changed:{}}),r[e.kind]&&r[e.kind][e.deviceId]?r[e.kind][e.deviceId].label&&r[e.kind][e.deviceId].label!==e.label&&(n[e.kind].changed[e.deviceId]=e):n[e.kind].added[e.deviceId]=e)})),n}(e,t),o={},a={},c={};return[["audioinput",r],["videoinput",i],["audiooutput",n]].forEach((([e,r])=>{const i=s[e];if(i){if(r){if(i.removed[r]&&(a[e]={deviceId:null},"audiooutput"===e)){const r=t.find((e=>"audiooutput"===e.kind));a[e]={deviceId:null==r?void 0:r.deviceId}}i.changed[r]&&(a[e]={deviceId:r})}if(Object.keys(i.added).length>0){const[t]=Object.keys(i.added).slice(0,1),r=i.added[t];c[e]={deviceId:r.deviceId,label:r.label,kind:r.kind}}if(Object.keys(i.removed).length>0){const[t]=Object.keys(i.removed).slice(0,1);o[e]=i.removed[t]}}})),{addedDevices:c,changedDevices:a,removedDevices:o}}var Mv;!function(e){e.rtc_manager_created="rtc_manager_created",e.stream_added="stream_added"}(Mv||(Mv={}));var jv={exports:{}};jv.exports=function(e){return(e instanceof Buffer?e:Buffer.from(e.toString(),"binary")).toString("base64")};var Lv=c(jv.exports);function Av(e,t){return function(){return e.apply(t,arguments)}}const{toString:Nv}=Object.prototype,{getPrototypeOf:Bv}=Object,Fv=(e=>t=>{const r=Nv.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),zv=e=>(e=e.toLowerCase(),t=>Fv(t)===e),Vv=e=>t=>typeof t===e,{isArray:Uv}=Array,$v=Vv("undefined");const Gv=zv("ArrayBuffer");const qv=Vv("string"),Hv=Vv("function"),Wv=Vv("number"),Kv=e=>null!==e&&"object"==typeof e,Jv=e=>{if("object"!==Fv(e))return!1;const t=Bv(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||Symbol.toStringTag in e||Symbol.iterator in e)},Xv=zv("Date"),Qv=zv("File"),Zv=zv("Blob"),Yv=zv("FileList"),eb=zv("URLSearchParams");function tb(e,t,{allOwnKeys:r=!1}={}){if(null==e)return;let i,n;if("object"!=typeof e&&(e=[e]),Uv(e))for(i=0,n=e.length;i<n;i++)t.call(null,e[i],i,e);else{const n=r?Object.getOwnPropertyNames(e):Object.keys(e),s=n.length;let o;for(i=0;i<s;i++)o=n[i],t.call(null,e[o],o,e)}}function rb(e,t){t=t.toLowerCase();const r=Object.keys(e);let i,n=r.length;for(;n-- >0;)if(i=r[n],t===i.toLowerCase())return i;return null}const ib="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:global,nb=e=>!$v(e)&&e!==ib;const sb=(ob="undefined"!=typeof Uint8Array&&Bv(Uint8Array),e=>ob&&e instanceof ob);var ob;const ab=zv("HTMLFormElement"),cb=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),db=zv("RegExp"),lb=(e,t)=>{const r=Object.getOwnPropertyDescriptors(e),i={};tb(r,((r,n)=>{let s;!1!==(s=t(r,n,e))&&(i[n]=s||r)})),Object.defineProperties(e,i)},ub="abcdefghijklmnopqrstuvwxyz",pb="0123456789",hb={DIGIT:pb,ALPHA:ub,ALPHA_DIGIT:ub+ub.toUpperCase()+pb};const fb=zv("AsyncFunction");var mb={isArray:Uv,isArrayBuffer:Gv,isBuffer:function(e){return null!==e&&!$v(e)&&null!==e.constructor&&!$v(e.constructor)&&Hv(e.constructor.isBuffer)&&e.constructor.isBuffer(e)},isFormData:e=>{let t;return e&&("function"==typeof FormData&&e instanceof FormData||Hv(e.append)&&("formdata"===(t=Fv(e))||"object"===t&&Hv(e.toString)&&"[object FormData]"===e.toString()))},isArrayBufferView:function(e){let t;return t="undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&Gv(e.buffer),t},isString:qv,isNumber:Wv,isBoolean:e=>!0===e||!1===e,isObject:Kv,isPlainObject:Jv,isUndefined:$v,isDate:Xv,isFile:Qv,isBlob:Zv,isRegExp:db,isFunction:Hv,isStream:e=>Kv(e)&&Hv(e.pipe),isURLSearchParams:eb,isTypedArray:sb,isFileList:Yv,forEach:tb,merge:function e(){const{caseless:t}=nb(this)&&this||{},r={},i=(i,n)=>{const s=t&&rb(r,n)||n;Jv(r[s])&&Jv(i)?r[s]=e(r[s],i):Jv(i)?r[s]=e({},i):Uv(i)?r[s]=i.slice():r[s]=i};for(let e=0,t=arguments.length;e<t;e++)arguments[e]&&tb(arguments[e],i);return r},extend:(e,t,r,{allOwnKeys:i}={})=>(tb(t,((t,i)=>{r&&Hv(t)?e[i]=Av(t,r):e[i]=t}),{allOwnKeys:i}),e),trim:e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,""),stripBOM:e=>(65279===e.charCodeAt(0)&&(e=e.slice(1)),e),inherits:(e,t,r,i)=>{e.prototype=Object.create(t.prototype,i),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),r&&Object.assign(e.prototype,r)},toFlatObject:(e,t,r,i)=>{let n,s,o;const a={};if(t=t||{},null==e)return t;do{for(n=Object.getOwnPropertyNames(e),s=n.length;s-- >0;)o=n[s],i&&!i(o,e,t)||a[o]||(t[o]=e[o],a[o]=!0);e=!1!==r&&Bv(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},kindOf:Fv,kindOfTest:zv,endsWith:(e,t,r)=>{e=String(e),(void 0===r||r>e.length)&&(r=e.length),r-=t.length;const i=e.indexOf(t,r);return-1!==i&&i===r},toArray:e=>{if(!e)return null;if(Uv(e))return e;let t=e.length;if(!Wv(t))return null;const r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},forEachEntry:(e,t)=>{const r=(e&&e[Symbol.iterator]).call(e);let i;for(;(i=r.next())&&!i.done;){const r=i.value;t.call(e,r[0],r[1])}},matchAll:(e,t)=>{let r;const i=[];for(;null!==(r=e.exec(t));)i.push(r);return i},isHTMLForm:ab,hasOwnProperty:cb,hasOwnProp:cb,reduceDescriptors:lb,freezeMethods:e=>{lb(e,((t,r)=>{if(Hv(e)&&-1!==["arguments","caller","callee"].indexOf(r))return!1;const i=e[r];Hv(i)&&(t.enumerable=!1,"writable"in t?t.writable=!1:t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+r+"'")}))}))},toObjectSet:(e,t)=>{const r={},i=e=>{e.forEach((e=>{r[e]=!0}))};return Uv(e)?i(e):i(String(e).split(t)),r},toCamelCase:e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,(function(e,t,r){return t.toUpperCase()+r})),noop:()=>{},toFiniteNumber:(e,t)=>(e=+e,Number.isFinite(e)?e:t),findKey:rb,global:ib,isContextDefined:nb,ALPHABET:hb,generateString:(e=16,t=hb.ALPHA_DIGIT)=>{let r="";const{length:i}=t;for(;e--;)r+=t[Math.random()*i|0];return r},isSpecCompliantForm:function(e){return!!(e&&Hv(e.append)&&"FormData"===e[Symbol.toStringTag]&&e[Symbol.iterator])},toJSONObject:e=>{const t=new Array(10),r=(e,i)=>{if(Kv(e)){if(t.indexOf(e)>=0)return;if(!("toJSON"in e)){t[i]=e;const n=Uv(e)?[]:{};return tb(e,((e,t)=>{const s=r(e,i+1);!$v(s)&&(n[t]=s)})),t[i]=void 0,n}}return e};return r(e,0)},isAsyncFn:fb,isThenable:e=>e&&(Kv(e)||Hv(e))&&Hv(e.then)&&Hv(e.catch)};function gb(e,t,r,i,n){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=(new Error).stack,this.message=e,this.name="AxiosError",t&&(this.code=t),r&&(this.config=r),i&&(this.request=i),n&&(this.response=n)}mb.inherits(gb,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:mb.toJSONObject(this.config),code:this.code,status:this.response&&this.response.status?this.response.status:null}}});const vb=gb.prototype,bb={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach((e=>{bb[e]={value:e}})),Object.defineProperties(gb,bb),Object.defineProperty(vb,"isAxiosError",{value:!0}),gb.from=(e,t,r,i,n,s)=>{const o=Object.create(vb);return mb.toFlatObject(e,o,(function(e){return e!==Error.prototype}),(e=>"isAxiosError"!==e)),gb.call(o,e.message,t,r,i,n),o.cause=e,o.name=e.name,s&&Object.assign(o,s),o};function yb(e){return mb.isPlainObject(e)||mb.isArray(e)}function wb(e){return mb.endsWith(e,"[]")?e.slice(0,-2):e}function _b(e,t,r){return e?e.concat(t).map((function(e,t){return e=wb(e),!r&&t?"["+e+"]":e})).join(r?".":""):t}const Sb=mb.toFlatObject(mb,{},null,(function(e){return/^is[A-Z]/.test(e)}));function Cb(e,t,r){if(!mb.isObject(e))throw new TypeError("target must be an object");t=t||new FormData;const i=(r=mb.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,(function(e,t){return!mb.isUndefined(t[e])}))).metaTokens,n=r.visitor||d,s=r.dots,o=r.indexes,a=(r.Blob||"undefined"!=typeof Blob&&Blob)&&mb.isSpecCompliantForm(t);if(!mb.isFunction(n))throw new TypeError("visitor must be a function");function c(e){if(null===e)return"";if(mb.isDate(e))return e.toISOString();if(!a&&mb.isBlob(e))throw new gb("Blob is not supported. Use a Buffer instead.");return mb.isArrayBuffer(e)||mb.isTypedArray(e)?a&&"function"==typeof Blob?new Blob([e]):Buffer.from(e):e}function d(e,r,n){let a=e;if(e&&!n&&"object"==typeof e)if(mb.endsWith(r,"{}"))r=i?r:r.slice(0,-2),e=JSON.stringify(e);else if(mb.isArray(e)&&function(e){return mb.isArray(e)&&!e.some(yb)}(e)||(mb.isFileList(e)||mb.endsWith(r,"[]"))&&(a=mb.toArray(e)))return r=wb(r),a.forEach((function(e,i){!mb.isUndefined(e)&&null!==e&&t.append(!0===o?_b([r],i,s):null===o?r:r+"[]",c(e))})),!1;return!!yb(e)||(t.append(_b(n,r,s),c(e)),!1)}const l=[],u=Object.assign(Sb,{defaultVisitor:d,convertValue:c,isVisitable:yb});if(!mb.isObject(e))throw new TypeError("data must be an object");return function e(r,i){if(!mb.isUndefined(r)){if(-1!==l.indexOf(r))throw Error("Circular reference detected in "+i.join("."));l.push(r),mb.forEach(r,(function(r,s){!0===(!(mb.isUndefined(r)||null===r)&&n.call(t,r,mb.isString(s)?s.trim():s,i,u))&&e(r,i?i.concat(s):[s])})),l.pop()}}(e),t}function Rb(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,(function(e){return t[e]}))}function kb(e,t){this._pairs=[],e&&Cb(e,this,t)}const Tb=kb.prototype;function Pb(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function Ob(e,t,r){if(!t)return e;const i=r&&r.encode||Pb,n=r&&r.serialize;let s;if(s=n?n(t,r):mb.isURLSearchParams(t)?t.toString():new kb(t,r).toString(i),s){const t=e.indexOf("#");-1!==t&&(e=e.slice(0,t)),e+=(-1===e.indexOf("?")?"?":"&")+s}return e}Tb.append=function(e,t){this._pairs.push([e,t])},Tb.toString=function(e){const t=e?function(t){return e.call(this,t,Rb)}:Rb;return this._pairs.map((function(e){return t(e[0])+"="+t(e[1])}),"").join("&")};class Eb{constructor(){this.handlers=[]}use(e,t,r){return this.handlers.push({fulfilled:e,rejected:t,synchronous:!!r&&r.synchronous,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){mb.forEach(this.handlers,(function(t){null!==t&&e(t)}))}}var Db={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},Ib={isBrowser:!0,classes:{URLSearchParams:"undefined"!=typeof URLSearchParams?URLSearchParams:kb,FormData:"undefined"!=typeof FormData?FormData:null,Blob:"undefined"!=typeof Blob?Blob:null},protocols:["http","https","file","blob","url","data"]};const xb="undefined"!=typeof window&&"undefined"!=typeof document,Mb=(jb="undefined"!=typeof navigator&&navigator.product,xb&&["ReactNative","NativeScript","NS"].indexOf(jb)<0);var jb;const Lb="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&"function"==typeof self.importScripts;var Ab={...Object.freeze({__proto__:null,hasBrowserEnv:xb,hasStandardBrowserEnv:Mb,hasStandardBrowserWebWorkerEnv:Lb}),...Ib};function Nb(e){function t(e,r,i,n){let s=e[n++];if("__proto__"===s)return!0;const o=Number.isFinite(+s),a=n>=e.length;if(s=!s&&mb.isArray(i)?i.length:s,a)return mb.hasOwnProp(i,s)?i[s]=[i[s],r]:i[s]=r,!o;i[s]&&mb.isObject(i[s])||(i[s]=[]);return t(e,r,i[s],n)&&mb.isArray(i[s])&&(i[s]=function(e){const t={},r=Object.keys(e);let i;const n=r.length;let s;for(i=0;i<n;i++)s=r[i],t[s]=e[s];return t}(i[s])),!o}if(mb.isFormData(e)&&mb.isFunction(e.entries)){const r={};return mb.forEachEntry(e,((e,i)=>{t(function(e){return mb.matchAll(/\w+|\[(\w*)]/g,e).map((e=>"[]"===e[0]?"":e[1]||e[0]))}(e),i,r,0)})),r}return null}const Bb={transitional:Db,adapter:["xhr","http"],transformRequest:[function(e,t){const r=t.getContentType()||"",i=r.indexOf("application/json")>-1,n=mb.isObject(e);n&&mb.isHTMLForm(e)&&(e=new FormData(e));if(mb.isFormData(e))return i?JSON.stringify(Nb(e)):e;if(mb.isArrayBuffer(e)||mb.isBuffer(e)||mb.isStream(e)||mb.isFile(e)||mb.isBlob(e))return e;if(mb.isArrayBufferView(e))return e.buffer;if(mb.isURLSearchParams(e))return t.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let s;if(n){if(r.indexOf("application/x-www-form-urlencoded")>-1)return function(e,t){return Cb(e,new Ab.classes.URLSearchParams,Object.assign({visitor:function(e,t,r,i){return Ab.isNode&&mb.isBuffer(e)?(this.append(t,e.toString("base64")),!1):i.defaultVisitor.apply(this,arguments)}},t))}(e,this.formSerializer).toString();if((s=mb.isFileList(e))||r.indexOf("multipart/form-data")>-1){const t=this.env&&this.env.FormData;return Cb(s?{"files[]":e}:e,t&&new t,this.formSerializer)}}return n||i?(t.setContentType("application/json",!1),function(e,t,r){if(mb.isString(e))try{return(t||JSON.parse)(e),mb.trim(e)}catch(e){if("SyntaxError"!==e.name)throw e}return(r||JSON.stringify)(e)}(e)):e}],transformResponse:[function(e){const t=this.transitional||Bb.transitional,r=t&&t.forcedJSONParsing,i="json"===this.responseType;if(e&&mb.isString(e)&&(r&&!this.responseType||i)){const r=!(t&&t.silentJSONParsing)&&i;try{return JSON.parse(e)}catch(e){if(r){if("SyntaxError"===e.name)throw gb.from(e,gb.ERR_BAD_RESPONSE,this,null,this.response);throw e}}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:Ab.classes.FormData,Blob:Ab.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};mb.forEach(["delete","get","head","post","put","patch"],(e=>{Bb.headers[e]={}}));var Fb=Bb;const zb=mb.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]);const Vb=Symbol("internals");function Ub(e){return e&&String(e).trim().toLowerCase()}function $b(e){return!1===e||null==e?e:mb.isArray(e)?e.map($b):String(e)}function Gb(e,t,r,i,n){return mb.isFunction(i)?i.call(this,t,r):(n&&(t=r),mb.isString(t)?mb.isString(i)?-1!==t.indexOf(i):mb.isRegExp(i)?i.test(t):void 0:void 0)}class qb{constructor(e){e&&this.set(e)}set(e,t,r){const i=this;function n(e,t,r){const n=Ub(t);if(!n)throw new Error("header name must be a non-empty string");const s=mb.findKey(i,n);(!s||void 0===i[s]||!0===r||void 0===r&&!1!==i[s])&&(i[s||t]=$b(e))}const s=(e,t)=>mb.forEach(e,((e,r)=>n(e,r,t)));return mb.isPlainObject(e)||e instanceof this.constructor?s(e,t):mb.isString(e)&&(e=e.trim())&&!/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim())?s((e=>{const t={};let r,i,n;return e&&e.split("\n").forEach((function(e){n=e.indexOf(":"),r=e.substring(0,n).trim().toLowerCase(),i=e.substring(n+1).trim(),!r||t[r]&&zb[r]||("set-cookie"===r?t[r]?t[r].push(i):t[r]=[i]:t[r]=t[r]?t[r]+", "+i:i)})),t})(e),t):null!=e&&n(t,e,r),this}get(e,t){if(e=Ub(e)){const r=mb.findKey(this,e);if(r){const e=this[r];if(!t)return e;if(!0===t)return function(e){const t=Object.create(null),r=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let i;for(;i=r.exec(e);)t[i[1]]=i[2];return t}(e);if(mb.isFunction(t))return t.call(this,e,r);if(mb.isRegExp(t))return t.exec(e);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,t){if(e=Ub(e)){const r=mb.findKey(this,e);return!(!r||void 0===this[r]||t&&!Gb(0,this[r],r,t))}return!1}delete(e,t){const r=this;let i=!1;function n(e){if(e=Ub(e)){const n=mb.findKey(r,e);!n||t&&!Gb(0,r[n],n,t)||(delete r[n],i=!0)}}return mb.isArray(e)?e.forEach(n):n(e),i}clear(e){const t=Object.keys(this);let r=t.length,i=!1;for(;r--;){const n=t[r];e&&!Gb(0,this[n],n,e,!0)||(delete this[n],i=!0)}return i}normalize(e){const t=this,r={};return mb.forEach(this,((i,n)=>{const s=mb.findKey(r,n);if(s)return t[s]=$b(i),void delete t[n];const o=e?function(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,((e,t,r)=>t.toUpperCase()+r))}(n):String(n).trim();o!==n&&delete t[n],t[o]=$b(i),r[o]=!0})),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const t=Object.create(null);return mb.forEach(this,((r,i)=>{null!=r&&!1!==r&&(t[i]=e&&mb.isArray(r)?r.join(", "):r)})),t}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map((([e,t])=>e+": "+t)).join("\n")}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...t){const r=new this(e);return t.forEach((e=>r.set(e))),r}static accessor(e){const t=(this[Vb]=this[Vb]={accessors:{}}).accessors,r=this.prototype;function i(e){const i=Ub(e);t[i]||(!function(e,t){const r=mb.toCamelCase(" "+t);["get","set","has"].forEach((i=>{Object.defineProperty(e,i+r,{value:function(e,r,n){return this[i].call(this,t,e,r,n)},configurable:!0})}))}(r,e),t[i]=!0)}return mb.isArray(e)?e.forEach(i):i(e),this}}qb.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),mb.reduceDescriptors(qb.prototype,(({value:e},t)=>{let r=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(e){this[r]=e}}})),mb.freezeMethods(qb);var Hb=qb;function Wb(e,t){const r=this||Fb,i=t||r,n=Hb.from(i.headers);let s=i.data;return mb.forEach(e,(function(e){s=e.call(r,s,n.normalize(),t?t.status:void 0)})),n.normalize(),s}function Kb(e){return!(!e||!e.__CANCEL__)}function Jb(e,t,r){gb.call(this,null==e?"canceled":e,gb.ERR_CANCELED,t,r),this.name="CanceledError"}mb.inherits(Jb,gb,{__CANCEL__:!0});var Xb=Ab.hasStandardBrowserEnv?{write(e,t,r,i,n,s){const o=[e+"="+encodeURIComponent(t)];mb.isNumber(r)&&o.push("expires="+new Date(r).toGMTString()),mb.isString(i)&&o.push("path="+i),mb.isString(n)&&o.push("domain="+n),!0===s&&o.push("secure"),document.cookie=o.join("; ")},read(e){const t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read:()=>null,remove(){}};function Qb(e,t){return e&&!function(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}(t)?function(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}(e,t):t}var Zb=Ab.hasStandardBrowserEnv?function(){const e=/(msie|trident)/i.test(navigator.userAgent),t=document.createElement("a");let r;function i(r){let i=r;return e&&(t.setAttribute("href",i),i=t.href),t.setAttribute("href",i),{href:t.href,protocol:t.protocol?t.protocol.replace(/:$/,""):"",host:t.host,search:t.search?t.search.replace(/^\?/,""):"",hash:t.hash?t.hash.replace(/^#/,""):"",hostname:t.hostname,port:t.port,pathname:"/"===t.pathname.charAt(0)?t.pathname:"/"+t.pathname}}return r=i(window.location.href),function(e){const t=mb.isString(e)?i(e):e;return t.protocol===r.protocol&&t.host===r.host}}():function(){return!0};function Yb(e,t){let r=0;const i=function(e,t){e=e||10;const r=new Array(e),i=new Array(e);let n,s=0,o=0;return t=void 0!==t?t:1e3,function(a){const c=Date.now(),d=i[o];n||(n=c),r[s]=a,i[s]=c;let l=o,u=0;for(;l!==s;)u+=r[l++],l%=e;if(s=(s+1)%e,s===o&&(o=(o+1)%e),c-n<t)return;const p=d&&c-d;return p?Math.round(1e3*u/p):void 0}}(50,250);return n=>{const s=n.loaded,o=n.lengthComputable?n.total:void 0,a=s-r,c=i(a);r=s;const d={loaded:s,total:o,progress:o?s/o:void 0,bytes:a,rate:c||void 0,estimated:c&&o&&s<=o?(o-s)/c:void 0,event:n};d[t?"download":"upload"]=!0,e(d)}}var ey="undefined"!=typeof XMLHttpRequest&&function(e){return new Promise((function(t,r){let i=e.data;const n=Hb.from(e.headers).normalize();let s,o,{responseType:a,withXSRFToken:c}=e;function d(){e.cancelToken&&e.cancelToken.unsubscribe(s),e.signal&&e.signal.removeEventListener("abort",s)}if(mb.isFormData(i))if(Ab.hasStandardBrowserEnv||Ab.hasStandardBrowserWebWorkerEnv)n.setContentType(!1);else if(!1!==(o=n.getContentType())){const[e,...t]=o?o.split(";").map((e=>e.trim())).filter(Boolean):[];n.setContentType([e||"multipart/form-data",...t].join("; "))}let l=new XMLHttpRequest;if(e.auth){const t=e.auth.username||"",r=e.auth.password?unescape(encodeURIComponent(e.auth.password)):"";n.set("Authorization","Basic "+btoa(t+":"+r))}const u=Qb(e.baseURL,e.url);function p(){if(!l)return;const i=Hb.from("getAllResponseHeaders"in l&&l.getAllResponseHeaders());!function(e,t,r){const i=r.config.validateStatus;r.status&&i&&!i(r.status)?t(new gb("Request failed with status code "+r.status,[gb.ERR_BAD_REQUEST,gb.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r)):e(r)}((function(e){t(e),d()}),(function(e){r(e),d()}),{data:a&&"text"!==a&&"json"!==a?l.response:l.responseText,status:l.status,statusText:l.statusText,headers:i,config:e,request:l}),l=null}if(l.open(e.method.toUpperCase(),Ob(u,e.params,e.paramsSerializer),!0),l.timeout=e.timeout,"onloadend"in l?l.onloadend=p:l.onreadystatechange=function(){l&&4===l.readyState&&(0!==l.status||l.responseURL&&0===l.responseURL.indexOf("file:"))&&setTimeout(p)},l.onabort=function(){l&&(r(new gb("Request aborted",gb.ECONNABORTED,e,l)),l=null)},l.onerror=function(){r(new gb("Network Error",gb.ERR_NETWORK,e,l)),l=null},l.ontimeout=function(){let t=e.timeout?"timeout of "+e.timeout+"ms exceeded":"timeout exceeded";const i=e.transitional||Db;e.timeoutErrorMessage&&(t=e.timeoutErrorMessage),r(new gb(t,i.clarifyTimeoutError?gb.ETIMEDOUT:gb.ECONNABORTED,e,l)),l=null},Ab.hasStandardBrowserEnv&&(c&&mb.isFunction(c)&&(c=c(e)),c||!1!==c&&Zb(u))){const t=e.xsrfHeaderName&&e.xsrfCookieName&&Xb.read(e.xsrfCookieName);t&&n.set(e.xsrfHeaderName,t)}void 0===i&&n.setContentType(null),"setRequestHeader"in l&&mb.forEach(n.toJSON(),(function(e,t){l.setRequestHeader(t,e)})),mb.isUndefined(e.withCredentials)||(l.withCredentials=!!e.withCredentials),a&&"json"!==a&&(l.responseType=e.responseType),"function"==typeof e.onDownloadProgress&&l.addEventListener("progress",Yb(e.onDownloadProgress,!0)),"function"==typeof e.onUploadProgress&&l.upload&&l.upload.addEventListener("progress",Yb(e.onUploadProgress)),(e.cancelToken||e.signal)&&(s=t=>{l&&(r(!t||t.type?new Jb(null,e,l):t),l.abort(),l=null)},e.cancelToken&&e.cancelToken.subscribe(s),e.signal&&(e.signal.aborted?s():e.signal.addEventListener("abort",s)));const h=function(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}(u);h&&-1===Ab.protocols.indexOf(h)?r(new gb("Unsupported protocol "+h+":",gb.ERR_BAD_REQUEST,e)):l.send(i||null)}))};const ty={http:null,xhr:ey};mb.forEach(ty,((e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch(e){}Object.defineProperty(e,"adapterName",{value:t})}}));const ry=e=>`- ${e}`,iy=e=>mb.isFunction(e)||null===e||!1===e;var ny=e=>{e=mb.isArray(e)?e:[e];const{length:t}=e;let r,i;const n={};for(let s=0;s<t;s++){let t;if(r=e[s],i=r,!iy(r)&&(i=ty[(t=String(r)).toLowerCase()],void 0===i))throw new gb(`Unknown adapter '${t}'`);if(i)break;n[t||"#"+s]=i}if(!i){const e=Object.entries(n).map((([e,t])=>`adapter ${e} `+(!1===t?"is not supported by the environment":"is not available in the build")));throw new gb("There is no suitable adapter to dispatch the request "+(t?e.length>1?"since :\n"+e.map(ry).join("\n"):" "+ry(e[0]):"as no adapter specified"),"ERR_NOT_SUPPORT")}return i};function sy(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new Jb(null,e)}function oy(e){sy(e),e.headers=Hb.from(e.headers),e.data=Wb.call(e,e.transformRequest),-1!==["post","put","patch"].indexOf(e.method)&&e.headers.setContentType("application/x-www-form-urlencoded",!1);return ny(e.adapter||Fb.adapter)(e).then((function(t){return sy(e),t.data=Wb.call(e,e.transformResponse,t),t.headers=Hb.from(t.headers),t}),(function(t){return Kb(t)||(sy(e),t&&t.response&&(t.response.data=Wb.call(e,e.transformResponse,t.response),t.response.headers=Hb.from(t.response.headers))),Promise.reject(t)}))}const ay=e=>e instanceof Hb?e.toJSON():e;function cy(e,t){t=t||{};const r={};function i(e,t,r){return mb.isPlainObject(e)&&mb.isPlainObject(t)?mb.merge.call({caseless:r},e,t):mb.isPlainObject(t)?mb.merge({},t):mb.isArray(t)?t.slice():t}function n(e,t,r){return mb.isUndefined(t)?mb.isUndefined(e)?void 0:i(void 0,e,r):i(e,t,r)}function s(e,t){if(!mb.isUndefined(t))return i(void 0,t)}function o(e,t){return mb.isUndefined(t)?mb.isUndefined(e)?void 0:i(void 0,e):i(void 0,t)}function a(r,n,s){return s in t?i(r,n):s in e?i(void 0,r):void 0}const c={url:s,method:s,data:s,baseURL:o,transformRequest:o,transformResponse:o,paramsSerializer:o,timeout:o,timeoutMessage:o,withCredentials:o,withXSRFToken:o,adapter:o,responseType:o,xsrfCookieName:o,xsrfHeaderName:o,onUploadProgress:o,onDownloadProgress:o,decompress:o,maxContentLength:o,maxBodyLength:o,beforeRedirect:o,transport:o,httpAgent:o,httpsAgent:o,cancelToken:o,socketPath:o,responseEncoding:o,validateStatus:a,headers:(e,t)=>n(ay(e),ay(t),!0)};return mb.forEach(Object.keys(Object.assign({},e,t)),(function(i){const s=c[i]||n,o=s(e[i],t[i],i);mb.isUndefined(o)&&s!==a||(r[i]=o)})),r}const dy="1.6.7",ly={};["object","boolean","number","function","string","symbol"].forEach(((e,t)=>{ly[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}}));const uy={};ly.transitional=function(e,t,r){function i(e,t){return"[Axios v1.6.7] Transitional option '"+e+"'"+t+(r?". "+r:"")}return(r,n,s)=>{if(!1===e)throw new gb(i(n," has been removed"+(t?" in "+t:"")),gb.ERR_DEPRECATED);return t&&!uy[n]&&(uy[n]=!0,console.warn(i(n," has been deprecated since v"+t+" and will be removed in the near future"))),!e||e(r,n,s)}};var py={assertOptions:function(e,t,r){if("object"!=typeof e)throw new gb("options must be an object",gb.ERR_BAD_OPTION_VALUE);const i=Object.keys(e);let n=i.length;for(;n-- >0;){const s=i[n],o=t[s];if(o){const t=e[s],r=void 0===t||o(t,s,e);if(!0!==r)throw new gb("option "+s+" must be "+r,gb.ERR_BAD_OPTION_VALUE)}else if(!0!==r)throw new gb("Unknown option "+s,gb.ERR_BAD_OPTION)}},validators:ly};const hy=py.validators;class fy{constructor(e){this.defaults=e,this.interceptors={request:new Eb,response:new Eb}}async request(e,t){try{return await this._request(e,t)}catch(e){if(e instanceof Error){let t;Error.captureStackTrace?Error.captureStackTrace(t={}):t=new Error;const r=t.stack?t.stack.replace(/^.+\n/,""):"";e.stack?r&&!String(e.stack).endsWith(r.replace(/^.+\n.+\n/,""))&&(e.stack+="\n"+r):e.stack=r}throw e}}_request(e,t){"string"==typeof e?(t=t||{}).url=e:t=e||{},t=cy(this.defaults,t);const{transitional:r,paramsSerializer:i,headers:n}=t;void 0!==r&&py.assertOptions(r,{silentJSONParsing:hy.transitional(hy.boolean),forcedJSONParsing:hy.transitional(hy.boolean),clarifyTimeoutError:hy.transitional(hy.boolean)},!1),null!=i&&(mb.isFunction(i)?t.paramsSerializer={serialize:i}:py.assertOptions(i,{encode:hy.function,serialize:hy.function},!0)),t.method=(t.method||this.defaults.method||"get").toLowerCase();let s=n&&mb.merge(n.common,n[t.method]);n&&mb.forEach(["delete","get","head","post","put","patch","common"],(e=>{delete n[e]})),t.headers=Hb.concat(s,n);const o=[];let a=!0;this.interceptors.request.forEach((function(e){"function"==typeof e.runWhen&&!1===e.runWhen(t)||(a=a&&e.synchronous,o.unshift(e.fulfilled,e.rejected))}));const c=[];let d;this.interceptors.response.forEach((function(e){c.push(e.fulfilled,e.rejected)}));let l,u=0;if(!a){const e=[oy.bind(this),void 0];for(e.unshift.apply(e,o),e.push.apply(e,c),l=e.length,d=Promise.resolve(t);u<l;)d=d.then(e[u++],e[u++]);return d}l=o.length;let p=t;for(u=0;u<l;){const e=o[u++],t=o[u++];try{p=e(p)}catch(e){t.call(this,e);break}}try{d=oy.call(this,p)}catch(e){return Promise.reject(e)}for(u=0,l=c.length;u<l;)d=d.then(c[u++],c[u++]);return d}getUri(e){return Ob(Qb((e=cy(this.defaults,e)).baseURL,e.url),e.params,e.paramsSerializer)}}mb.forEach(["delete","get","head","options"],(function(e){fy.prototype[e]=function(t,r){return this.request(cy(r||{},{method:e,url:t,data:(r||{}).data}))}})),mb.forEach(["post","put","patch"],(function(e){function t(t){return function(r,i,n){return this.request(cy(n||{},{method:e,headers:t?{"Content-Type":"multipart/form-data"}:{},url:r,data:i}))}}fy.prototype[e]=t(),fy.prototype[e+"Form"]=t(!0)}));var my=fy;class gy{constructor(e){if("function"!=typeof e)throw new TypeError("executor must be a function.");let t;this.promise=new Promise((function(e){t=e}));const r=this;this.promise.then((e=>{if(!r._listeners)return;let t=r._listeners.length;for(;t-- >0;)r._listeners[t](e);r._listeners=null})),this.promise.then=e=>{let t;const i=new Promise((e=>{r.subscribe(e),t=e})).then(e);return i.cancel=function(){r.unsubscribe(t)},i},e((function(e,i,n){r.reason||(r.reason=new Jb(e,i,n),t(r.reason))}))}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){this.reason?e(this.reason):this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const t=this._listeners.indexOf(e);-1!==t&&this._listeners.splice(t,1)}static source(){let e;return{token:new gy((function(t){e=t})),cancel:e}}}var vy=gy;const by={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(by).forEach((([e,t])=>{by[t]=e}));var yy=by;const wy=function e(t){const r=new my(t),i=Av(my.prototype.request,r);return mb.extend(i,my.prototype,r,{allOwnKeys:!0}),mb.extend(i,r,null,{allOwnKeys:!0}),i.create=function(r){return e(cy(t,r))},i}(Fb);function _y(e,t){return Rt(e,t)}function Sy(e,t){return r=>(i,n,s)=>e(n())?t(r)(i,n,s):(console.warn("Not authorized to perform this action"),!1)}function Cy(e){return t=>(r,i,n)=>"connected"!==i().roomConnection.status?(console.warn("Action cannot be performed outside of a connected room"),!1):e(t)(r,i,n)}function Ry(e,t){return _y(e,((e,r)=>{const{getState:i}=r;return"connected"!==i().roomConnection.status?(console.warn("Action cannot be performed outside of a connected room"),Promise.reject("Action cannot be performed outside of a connected room")):t(e,r)}))}function ky(e,t){return r=>(i,n,s)=>"connected"!==n().roomConnection.status?(console.warn("Action cannot be performed outside of a connected room"),!1):Sy(e,t)(r)(i,n,s)}wy.Axios=my,wy.CanceledError=Jb,wy.CancelToken=vy,wy.isCancel=Kb,wy.VERSION=dy,wy.toFormData=Cb,wy.AxiosError=gb,wy.Cancel=wy.CanceledError,wy.all=function(e){return Promise.all(e)},wy.spread=function(e){return function(t){return e.apply(null,t)}},wy.isAxiosError=function(e){return mb.isObject(e)&&!0===e.isAxiosError},wy.mergeConfig=cy,wy.AxiosHeaders=Hb,wy.formToJSON=e=>Nb(mb.isHTMLForm(e)?new FormData(e):e),wy.getAdapter=ny,wy.HttpStatusCode=yy,wy.default=wy;const Ty=((e={})=>{const t=new Map,{extra:r,onError:i=ar}=e;zt(i,"onError");const n=e=>{let r=et(Array.from(t.values()),(t=>t.effect===e.effect));return r||(r=tr(e)),(e=>(e.unsubscribe=()=>t.delete(e.id),t.set(e.id,e),t=>{e.unsubscribe(),t?.cancelActive&&rr(e)}))(r)};Object.assign(n,{withTypes:()=>n});const s=e=>{const{type:r,effect:i,predicate:n}=er(e),s=et(Array.from(t.values()),(e=>("string"==typeof r?e.type===r:e.predicate===n)&&e.effect===i));return s&&(s.unsubscribe(),e.cancelActive&&rr(s)),!!s};Object.assign(s,{withTypes:()=>s});const o=async(e,s,o,a)=>{const c=new AbortController,d=Yt(n,c.signal),l=[];try{e.pending.add(c),await Promise.resolve(e.effect(s,Jt({},o,{getOriginalState:a,condition:(e,t)=>d(e,t).then(Boolean),take:d,delay:Kt(c.signal),pause:Wt(c.signal),extra:r,signal:c.signal,fork:Zt(c.signal,l),unsubscribe:e.unsubscribe,subscribe:()=>{t.set(e.id,e)},cancelActiveListeners:()=>{e.pending.forEach(((e,t,r)=>{e!==c&&(Gt(e,Nt),r.delete(e))}))},cancel:()=>{Gt(c,Nt),e.pending.delete(c)},throwIfCancelled:()=>{qt(c.signal)}})))}catch(e){e instanceof Ft||ir(i,e,{raisedBy:"effect"})}finally{await Promise.all(l),Gt(c,Bt),e.pending.delete(c)}},a=(e=>()=>{e.forEach(rr),e.clear()})(t);return{middleware:e=>r=>c=>{if(!z(c))return r(c);if(nr.match(c))return n(c.payload);if(sr.match(c))return void a();if(or.match(c))return s(c.payload);let d=e.getState();const l=()=>{if(d===Xt)throw new Error(`${Qt}: getOriginalState can only be called synchronously`);return d};let u;try{if(u=r(c),t.size>0){const r=e.getState(),n=Array.from(t.values());for(const t of n){let n=!1;try{n=t.predicate(c,r,d)}catch(e){n=!1,ir(i,e,{raisedBy:"predicate"})}n&&o(t,c,e,l)}}}finally{d=Xt}return u},startListening:n,stopListening:s,clearListeners:a}})(),Py=Ty.startListening,Oy=(e,t)=>Py({predicate:(t,r,i)=>{const n=e.map((e=>e(i))),s=e.map((e=>e(r)));return n.some(((e,t)=>e!==s[t]))},effect:(r,{dispatch:i,getState:n,extra:s})=>{const o=e.map((e=>e(n())));t({dispatch:i,getState:n,extra:s},...o)}}),Ey=Dt({name:"app",initialState:{isNodeSdk:!1,isActive:!1,isDialIn:!1,ignoreBreakoutGroups:!1,roomName:null,roomUrl:null,displayName:null,userAgent:"core:0.32.10",externalId:null},reducers:{doAppStart:(e,t)=>{const r=new URL(t.payload.roomUrl);return Object.assign(Object.assign(Object.assign({},e),t.payload),{roomName:r.pathname,initialConfig:Object.assign({},t.payload),isActive:!0})},doAppStop:e=>Object.assign(Object.assign({},e),{isActive:!1})}}),{doAppStop:Dy,doAppStart:Iy}=Ey.actions,xy=e=>e.app.isActive,My=e=>e.app.isDialIn,jy=e=>e.app.roomName,Ly=e=>e.app.displayName,Ay=e=>e.app.userAgent,Ny=e=>e.app.externalId;function By(e){return Qe(`signalConnection/event/${e}`)}const Fy={audioEnabled:By("audioEnabled"),audioEnableRequested:By("audioEnableRequested"),breakoutGroupJoined:By("breakoutGroupJoined"),breakoutMoveToGroup:By("breakoutMoveToGroup"),breakoutMoveToMain:By("breakoutMoveToMain"),breakoutSessionUpdated:By("breakoutSessionUpdated"),chatMessage:By("chatMessage"),clientLeft:By("clientLeft"),clientKicked:By("clientKicked"),clientMetadataReceived:By("clientMetadataReceived"),clientUnableToJoin:By("clientUnableToJoin"),cloudRecordingStarted:By("cloudRecordingStarted"),cloudRecordingStopped:By("cloudRecordingStopped"),disconnect:By("disconnect"),knockerLeft:By("knockerLeft"),knockHandled:By("knockHandled"),newClient:By("newClient"),roomJoined:By("roomJoined"),roomKnocked:By("roomKnocked"),roomLeft:By("roomLeft"),roomLocked:By("roomLocked"),roomSessionEnded:By("roomSessionEnded"),screenshareStarted:By("screenshareStarted"),screenshareStopped:By("screenshareStopped"),spotlightAdded:By("spotlightAdded"),spotlightRemoved:By("spotlightRemoved"),streamingStopped:By("streamingStopped"),videoEnabled:By("videoEnabled"),videoEnableRequested:By("videoEnableRequested"),liveTranscriptionStarted:By("liveTranscriptionStarted"),liveTranscriptionStopped:By("liveTranscriptionStopped")},zy={canLockRoom:["host"],canRequestAudioEnable:["host"],canRequestVideoEnable:["host"],canKickClient:["host"],canEndMeeting:["host"],canAskToSpeak:["host"],canSpotlight:["host"]},Vy=Dt({name:"authorization",initialState:{roomKey:null,roleName:"none"},reducers:{setRoomKey:(e,t)=>Object.assign(Object.assign({},e),{roomKey:t.payload})},extraReducers:e=>{e.addCase(Iy,((e,t)=>Object.assign(Object.assign({},e),{roomKey:t.payload.roomKey}))),e.addCase(Fy.roomJoined,((e,t)=>{var r,i;const n=null===(i=null===(r=t.payload)||void 0===r?void 0:r.room)||void 0===i?void 0:i.clients.find((e=>{var r;return e.id===(null===(r=t.payload)||void 0===r?void 0:r.selfId)}));return Object.assign(Object.assign({},e),{roleName:(null==n?void 0:n.role.roleName)||"none"})}))}}),{setRoomKey:Uy}=Vy.actions,$y=e=>e.authorization.roomKey,Gy=e=>e.authorization.roleName,qy=Ge(Gy,(e=>zy.canLockRoom.includes(e))),Hy=Ge(Gy,(e=>zy.canRequestAudioEnable.includes(e))),Wy=Ge(Gy,(e=>zy.canRequestVideoEnable.includes(e))),Ky=Ge(Gy,(e=>zy.canKickClient.includes(e))),Jy=Ge(Gy,(e=>zy.canEndMeeting.includes(e))),Xy=Ge(Gy,(e=>zy.canAskToSpeak.includes(e))),Qy=Ge(Gy,(e=>zy.canSpotlight.includes(e)));function Zy(e,t){var r={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(r[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(i=Object.getOwnPropertySymbols(e);n<i.length;n++)t.indexOf(i[n])<0&&Object.prototype.propertyIsEnumerable.call(e,i[n])&&(r[i[n]]=e[i[n]])}return r}function Yy(e,t,r,i){return new(r||(r=Promise))((function(n,s){function o(e){try{c(i.next(e))}catch(e){s(e)}}function a(e){try{c(i.throw(e))}catch(e){s(e)}}function c(e){e.done?n(e.value):function(e){return e instanceof r?e:new r((function(t){t(e)}))}(e.value).then(o,a)}c((i=i.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;const ew=Dt({name:"deviceCredentials",initialState:{isFetching:!1,data:null},reducers:{},extraReducers:e=>{e.addCase(tw.pending,(e=>Object.assign(Object.assign({},e),{isFetching:!0}))),e.addCase(tw.fulfilled,((e,t)=>Object.assign(Object.assign({},e),{isFetching:!1,data:t.payload}))),e.addCase(tw.rejected,(e=>Object.assign(Object.assign({},e),{isFetching:!0})))}}),tw=_y("deviceCredentials/doGetDeviceCredentials",((e,{extra:t})=>Yy(void 0,void 0,void 0,(function*(){try{return yield t.services.credentialsService.getCredentials()}catch(e){console.error(e)}})))),rw=e=>e.deviceCredentials,iw=e=>{var t,r;return null===(r=null===(t=e.deviceCredentials.data)||void 0===t?void 0:t.credentials)||void 0===r?void 0:r.uuid};Oy([Ge(xy,rw,((e,t)=>!(!e||t.isFetching||t.data)))],(({dispatch:e},t)=>{t&&e(tw())}));const nw=Dt({name:"signalConnection",initialState:{deviceIdentified:!1,isIdentifyingDevice:!1,status:"ready",socket:null},reducers:{socketConnecting:e=>Object.assign(Object.assign({},e),{status:"connecting"}),socketConnected:(e,t)=>Object.assign(Object.assign({},e),{socket:t.payload,status:"connected"}),socketDisconnected:e=>Object.assign(Object.assign({},e),{socket:null,deviceIdentified:!1,status:"disconnected"}),socketReconnecting:e=>Object.assign(Object.assign({},e),{status:"reconnecting"}),deviceIdentifying:e=>Object.assign(Object.assign({},e),{isIdentifyingDevice:!0}),deviceIdentified:e=>Object.assign(Object.assign({},e),{deviceIdentified:!0,isIdentifyingDevice:!1})},extraReducers:e=>{e.addCase(Fy.disconnect,(e=>Object.assign(Object.assign({},e),{deviceIdentified:!1,status:"disconnected"})))}}),{deviceIdentifying:sw,deviceIdentified:ow,socketConnected:aw,socketConnecting:cw,socketDisconnected:dw,socketReconnecting:lw}=nw.actions,uw=()=>(e,t)=>{if(vw(t()))return;e(cw());const r=function(){const e=new URL("wss://signal.appearin.net").origin;return new Pg(e,{autoConnect:!1})}();r.on("connect",(()=>e(aw(r)))),r.on("device_identified",(()=>e(ow()))),r.getManager().on("reconnect",(()=>e(lw()))),function(e,t){e.on("room_joined",(e=>t(Fy.roomJoined(e)))),e.on("new_client",(e=>t(Fy.newClient(e)))),e.on("client_left",(e=>t(Fy.clientLeft(e)))),e.on("client_kicked",(e=>t(Fy.clientKicked(e)))),e.on("client_unable_to_join",(e=>t(Fy.clientUnableToJoin(e)))),e.on("audio_enabled",(e=>t(Fy.audioEnabled(e)))),e.on("video_enabled",(e=>t(Fy.videoEnabled(e)))),e.on("audio_enable_requested",(e=>t(Fy.audioEnableRequested(e)))),e.on("client_metadata_received",(e=>t(Fy.clientMetadataReceived(e)))),e.on("chat_message",(e=>t(Fy.chatMessage(e)))),e.on("disconnect",(()=>t(Fy.disconnect()))),e.on("room_knocked",(e=>t(Fy.roomKnocked(e)))),e.on("room_left",(()=>t(Fy.roomLeft()))),e.on("room_locked",(e=>t(Fy.roomLocked(e)))),e.on("room_session_ended",(e=>t(Fy.roomSessionEnded(e)))),e.on("knocker_left",(e=>t(Fy.knockerLeft(e)))),e.on("knock_handled",(e=>t(Fy.knockHandled(e)))),e.on("screenshare_started",(e=>t(Fy.screenshareStarted(e)))),e.on("screenshare_stopped",(e=>t(Fy.screenshareStopped(e)))),e.on("cloud_recording_started",(e=>t(Fy.cloudRecordingStarted(e)))),e.on("cloud_recording_stopped",(()=>t(Fy.cloudRecordingStopped()))),e.on("streaming_stopped",(()=>t(Fy.streamingStopped()))),e.on("spotlight_added",(e=>t(Fy.spotlightAdded(e)))),e.on("spotlight_removed",(e=>t(Fy.spotlightRemoved(e)))),e.on("live_transcription_started",(e=>t(Fy.liveTranscriptionStarted(e)))),e.on("live_transcription_stopped",(e=>t(Fy.liveTranscriptionStopped(e)))),e.on("video_enable_requested",(e=>t(Fy.videoEnableRequested(e)))),e.on("breakout_group_joined",(e=>t(Fy.breakoutGroupJoined(e)))),e.on("breakout_session_updated",(e=>t(Fy.breakoutSessionUpdated(e)))),e.on("breakout_move_to_group",(()=>t(Fy.breakoutMoveToGroup()))),e.on("breakout_move_to_main",(()=>t(Fy.breakoutMoveToMain())))}(r,e),r.connect()},pw=({deviceCredentials:e})=>(t,r)=>{const i=r(),n=vw(i),s=mw(i);n&&(s||(n.emit("identify_device",{deviceCredentials:e}),t(sw())))},hw=()=>(e,t)=>{const r=t();if("connected"===gw(r)){const t=fw(r).socket;null==t||t.disconnect(),e(dw())}},fw=e=>e.signalConnection,mw=e=>e.signalConnection.deviceIdentified,gw=e=>e.signalConnection.status,vw=e=>e.signalConnection.socket;Oy([Ge(xy,gw,((e,t)=>!(!e||!["ready","reconnecting"].includes(t))))],(({dispatch:e},t)=>{t&&e(uw())}));const bw=Ge(rw,gw,mw,(e=>e.signalConnection.isIdentifyingDevice),((e,t,r,i)=>!(!e.data||"connected"!==t||r||i)));function yw(e,{delay:t=500,edges:r}={}){let i,n=0;return(...s)=>{n+=1,r&&1===n&&e(...s),clearTimeout(i),i=setTimeout((()=>{(!r||n>1)&&e(...s),i=void 0,n=0}),t)}}Oy([bw,rw],(({dispatch:e},t,r)=>{t&&r.data&&e(pw({deviceCredentials:r.data}))})),Py({actionCreator:Fy.roomLeft,effect:(e,{dispatch:t})=>{t(hw())}}),Py({actionCreator:Fy.clientKicked,effect:(e,{dispatch:t})=>{t(hw())}});const ww=Dt({name:"localMedia",initialState:{busyDeviceIds:[],cameraEnabled:!1,currentSpeakerDeviceId:"default",devices:[],isSettingCameraDevice:!1,isSettingMicrophoneDevice:!1,isSettingSpeakerDevice:!1,isTogglingCamera:!1,lowDataMode:!1,microphoneEnabled:!1,status:"inactive",stream:void 0,isSwitchingStream:!1},reducers:{deviceBusy:(e,t)=>e.busyDeviceIds.includes(t.payload.deviceId)?e:Object.assign(Object.assign({},e),{busyDeviceIds:[...e.busyDeviceIds,t.payload.deviceId]}),toggleCameraEnabled(e,t){var r;return Object.assign(Object.assign({},e),{cameraEnabled:null!==(r=t.payload.enabled)&&void 0!==r?r:!e.cameraEnabled})},setCurrentCameraDeviceId:(e,t)=>Object.assign(Object.assign({},e),{currentCameraDeviceId:t.payload.deviceId}),toggleMicrophoneEnabled(e,t){var r;return Object.assign(Object.assign({},e),{microphoneEnabled:null!==(r=t.payload.enabled)&&void 0!==r?r:!e.microphoneEnabled})},setCurrentMicrophoneDeviceId:(e,t)=>Object.assign(Object.assign({},e),{currentMicrophoneDeviceId:t.payload.deviceId}),setCurrentSpeakerDeviceId(e,t){var r;return Object.assign(Object.assign({},e),{currentSpeakerDeviceId:null!==(r=t.payload.deviceId)&&void 0!==r?r:"default"})},toggleLowDataModeEnabled(e,t){var r;return Object.assign(Object.assign({},e),{lowDataMode:null!==(r=t.payload.enabled)&&void 0!==r?r:!e.lowDataMode})},setDevices:(e,t)=>Object.assign(Object.assign({},e),{devices:t.payload.devices}),setLocalMediaStream:(e,t)=>Object.assign(Object.assign({},e),{stream:t.payload.stream}),setLocalMediaOptions:(e,t)=>Object.assign(Object.assign({},e),{options:t.payload.options}),localMediaStopped:e=>Object.assign(Object.assign({},e),{status:"stopped",stream:void 0}),localStreamMetadataUpdated(e,t){const{audio:r,video:i}=t.payload;return Object.assign(Object.assign({},e),{currentCameraDeviceId:i.deviceId,currentMicrophoneDeviceId:r.deviceId,busyDeviceIds:e.busyDeviceIds.filter((e=>e!==r.deviceId&&e!==i.deviceId))})}},extraReducers:e=>{e.addCase(Iy,((e,t)=>Object.assign(Object.assign({},e),{options:t.payload.localMediaOptions}))),e.addCase(Lw.pending,((e,t)=>{const{audio:r,video:i}=t.meta.arg;return Object.assign(Object.assign({},e),{isSettingCameraDevice:i,isSettingMicrophoneDevice:r})})),e.addCase(Lw.fulfilled,((e,t)=>{const{audio:r,video:i}=t.meta.arg;return Object.assign(Object.assign({},e),{isSettingCameraDevice:!i&&e.isSettingCameraDevice,isSettingMicrophoneDevice:!r&&e.isSettingMicrophoneDevice})})),e.addCase(Lw.rejected,((e,t)=>{const{audio:r,video:i}=t.meta.arg;return Object.assign(Object.assign({},e),{isSettingCameraDevice:!i&&e.isSettingCameraDevice,isSettingMicrophoneDevice:!r&&e.isSettingMicrophoneDevice,cameraDeviceError:i?t.error:e.cameraDeviceError,microphoneDeviceError:r?t.error:e.microphoneDeviceError})})),e.addCase(xw.pending,(e=>Object.assign(Object.assign({},e),{isTogglingCamera:!0}))),e.addCase(xw.fulfilled,(e=>Object.assign(Object.assign({},e),{isTogglingCamera:!1}))),e.addCase(Aw.fulfilled,((e,t)=>Object.assign(Object.assign({},e),{devices:t.payload.devices}))),e.addCase(Bw.pending,(e=>Object.assign(Object.assign({},e),{status:"starting"}))),e.addCase(Bw.fulfilled,((e,{payload:{stream:t,onDeviceChange:r}})=>{let i,n,s=!1,o=!1;const a=t.getAudioTracks()[0],c=t.getVideoTracks()[0];return a&&(n=a.getSettings().deviceId,o=a.enabled),c&&(s=c.enabled,i=c.getSettings().deviceId),Object.assign(Object.assign({},e),{stream:t,status:"started",currentCameraDeviceId:i,currentMicrophoneDeviceId:n,cameraEnabled:s,microphoneEnabled:o,onDeviceChange:r})})),e.addCase(Bw.rejected,((e,t)=>Object.assign(Object.assign({},e),{status:"error",startError:t.error}))),e.addCase(Nw.pending,(e=>Object.assign(Object.assign({},e),{isSwitchingStream:!0}))),e.addCase(Nw.fulfilled,(e=>Object.assign(Object.assign({},e),{isSwitchingStream:!1}))),e.addCase(Nw.rejected,(e=>Object.assign(Object.assign({},e),{isSwitchingStream:!1})))}}),{deviceBusy:_w,setCurrentCameraDeviceId:Sw,setCurrentMicrophoneDeviceId:Cw,setCurrentSpeakerDeviceId:Rw,toggleCameraEnabled:kw,toggleMicrophoneEnabled:Tw,toggleLowDataModeEnabled:Pw,setLocalMediaOptions:Ow,setLocalMediaStream:Ew,localMediaStopped:Dw,localStreamMetadataUpdated:Iw}=ww.actions,xw=_y("localMedia/doToggleCamera",((e,{getState:t,rejectWithValue:r})=>Yy(void 0,void 0,void 0,(function*(){const e=t(),i=Qw(e);if(!i)return;let n=i.getVideoTracks()[0];const s=Gw(e);try{if(s)if(n)n.enabled=!0;else{const t=Yw(e),r=Vw(e);yield Iv(Object.assign(Object.assign({},t),{audioId:!1,videoId:r,type:"exact"}),{replaceStream:i}),n=i.getVideoTracks()[0]}else{if(!n)return;n.enabled=!1,n.stop(),i.removeTrack(n)}i.dispatchEvent(new CustomEvent("stopresumevideo",{detail:{track:n,enable:s}}))}catch(e){return r(e)}})))),Mw=_y("localMedia/doToggleMicrophone",((e,{getState:t})=>{var r;const i=t(),n=Qw(i);if(!n)return;const s=qw(i),o=null===(r=n.getAudioTracks())||void 0===r?void 0:r[0];o&&(o.enabled=s)})),jw=()=>(e,t)=>{const r=t();if(!Qw(r))return;const i=Vw(r),n=Uw(r);e(Nw({audioId:n,videoId:i}))},Lw=_y("localMedia/reactSetDevice",(({audio:e,video:t},{getState:r,rejectWithValue:i})=>Yy(void 0,void 0,void 0,(function*(){try{const i=r(),n=Qw(i);if(!n)throw new Error("No stream");const s=!!e&&Uw(i),o=!!t&&Vw(i),a=Yw(i),{replacedTracks:c}=yield Iv(Object.assign(Object.assign({},a),{audioId:s,videoId:o,type:"exact"}),{replaceStream:n}),d=qw(i);n.getAudioTracks().forEach((e=>e.enabled=d));const l=Gw(i);return n.getVideoTracks().forEach((e=>e.enabled=l)),{replacedTracks:c}}catch(e){return i(e)}})))),Aw=_y("localMedia/doUpdateDeviceList",((e,{getState:t,dispatch:r,rejectWithValue:i})=>Yy(void 0,void 0,void 0,(function*(){var e,n,s,o;const a=t();let c=[],d=[];const l=Qw(a);try{c=yield navigator.mediaDevices.enumerateDevices(),d=Ww(a);if(!(l&&!Zw(a)&&c&&d&&d.find((e=>e.deviceId))))return{devices:c};const{changedDevices:t,addedDevices:i}=xv({oldDevices:d,newDevices:c});let u=null===(e=t.audioinput)||void 0===e?void 0:e.deviceId,p=null===(n=t.videoinput)||void 0===n?void 0:n.deviceId;return void 0===u&&(u=null===(s=i.audioinput)||void 0===s?void 0:s.deviceId),void 0===p&&(p=null===(o=i.videoinput)||void 0===o?void 0:o.deviceId),void 0===u&&void 0===p||r(Nw({audioId:u,videoId:p})),{devices:c}}catch(e){return i(e)}})))),Nw=_y("localMedia/doSwitchLocalStream",(({audioId:e,videoId:t},{dispatch:r,getState:i,rejectWithValue:n})=>Yy(void 0,void 0,void 0,(function*(){const s=i(),o=Qw(s),a=Yw(s),c=!(!t||e)||!(t||!e);if(o)try{const{replacedTracks:i}=yield Iv(Object.assign(Object.assign({},a),{audioId:void 0!==e&&e,videoId:void 0!==t&&t,type:"exact"}),{replaceStream:o}),n=e||t;return c&&n&&r(_w({deviceId:n})),{replacedTracks:i}}catch(i){console.error(i);const s=e||t;return c&&s&&r(_w({deviceId:s})),n(i)}})))),Bw=_y("localMedia/doStartLocalMedia",((e,{getState:t,dispatch:r,rejectWithValue:i})=>Yy(void 0,void 0,void 0,(function*(){const n=yw((()=>{r(Aw())}),{delay:500});if(navigator.mediaDevices&&navigator.mediaDevices.addEventListener("devicechange",n),"getTracks"in e)return Promise.resolve({stream:e,onDeviceChange:n});if(!e.audio&&!e.video)return{stream:new MediaStream,onDeviceChange:n};r(Ow({options:e}));try{yield r(Aw());const i=t(),s=Yw(i),{stream:o}=yield Iv(Object.assign(Object.assign({},s),{audioId:e.audio,videoId:e.video}));return{stream:o,onDeviceChange:n}}catch(e){return i(e)}})))),Fw=()=>(e,t)=>{const r=Qw(t()),i=Jw(t()).onDeviceChange;null==r||r.getTracks().forEach((e=>{e.stop()})),navigator.mediaDevices&&i&&navigator.mediaDevices.removeEventListener("devicechange",i),e(Dw())},zw=e=>e.localMedia.busyDeviceIds,Vw=e=>e.localMedia.currentCameraDeviceId,Uw=e=>e.localMedia.currentMicrophoneDeviceId,$w=e=>e.localMedia.currentSpeakerDeviceId,Gw=e=>e.localMedia.cameraEnabled,qw=e=>e.localMedia.microphoneEnabled,Hw=e=>e.localMedia.lowDataMode,Ww=e=>e.localMedia.devices,Kw=e=>e.localMedia.options;Ge(Kw,(e=>!!e));const Jw=e=>e.localMedia,Xw=e=>e.localMedia.status,Qw=e=>e.localMedia.stream,Zw=e=>e.localMedia.isSwitchingStream,Yw=Ge(Ww,Vw,Uw,Hw,((e,t,r,i)=>({devices:e,videoId:t,audioId:r,options:{disableAEC:!1,disableAGC:!1,hd:!0,lax:!1,lowDataMode:i,simulcast:!0,widescreen:!0}}))),e_=Ge(Xw,(e=>"starting"===e)),t_=Ge(Ww,zw,((e,t)=>e.filter((e=>"videoinput"===e.kind)).filter((e=>!t.includes(e.deviceId))))),r_=Ge(Ww,zw,((e,t)=>e.filter((e=>"audioinput"===e.kind)).filter((e=>!t.includes(e.deviceId))))),i_=Ge(Ww,(e=>e.filter((e=>"audiooutput"===e.kind))));Oy([Ge(xy,Xw,Kw,((e,t,r)=>{if(e&&["inactive","stopped"].includes(t)&&r)return r}))],(({dispatch:e},t)=>{t&&e(Bw(t))}));Oy([Ge(xy,Xw,Kw,((e,t,r)=>!e&&"inactive"!==t&&!!r))],(({dispatch:e},t)=>{t&&e(Fw())})),Py({predicate:(e,t,r)=>{const i=qw(r),n=qw(t);return"started"===Xw(r)&&i!==n},effect:(e,{dispatch:t})=>{t(Mw())}}),Py({predicate:(e,t,r)=>{const i=Hw(r),n=Hw(t);return"started"===Xw(r)&&i!==n},effect:(e,{dispatch:t})=>{t(jw())}}),Py({predicate:(e,t,r)=>{if(t.localMedia.isTogglingCamera)return!1;const i=Gw(r),n=Gw(t);return"started"===Xw(r)&&i!==n},effect:(e,{dispatch:t})=>{t(xw())}}),Py({predicate:(e,t,r)=>{const i=Vw(r),n=Vw(t);return"started"===Xw(r)&&i!==n},effect:(e,{dispatch:t})=>{t(Lw({audio:!1,video:!0}))}}),Py({predicate:(e,t,r)=>{const i=Uw(r),n=Uw(t);return"started"===Xw(r)&&i!==n},effect:(e,{dispatch:t})=>{t(Lw({audio:!0,video:!1}))}}),Py({matcher:yt(Bw.fulfilled,Aw.fulfilled,Nw.fulfilled,Nw.rejected),effect:(e,{dispatch:t,getState:r})=>{const i=r(),n=Qw(i),s=Ww(i);if(!n)return;const o=function({audioTrack:e,videoTrack:t,devices:r,stoppedVideoTrack:i,lastAudioId:n,lastVideoId:s}){const o=e=>"live"===(null==e?void 0:e.readyState)?e:null;return t=o(t)||i,e=o(e),{video:Ev("videoinput",t,r,s),audio:Ev("audioinput",e,r,n)}}({audioTrack:n.getAudioTracks()[0],videoTrack:n.getVideoTracks()[0],devices:s});t(Iw(o))}}),Py({actionCreator:Fy.audioEnableRequested,effect:({payload:e},{dispatch:t})=>{const{enable:r}=e;r||t(Tw({enabled:!1}))}}),Py({actionCreator:Fy.videoEnableRequested,effect:({payload:e},{dispatch:t})=>{const{enable:r}=e;r||t(kw({enabled:!1}))}}),Py({actionCreator:Fy.breakoutSessionUpdated,effect:({payload:e},{dispatch:t})=>{var r;!1===(null===(r=e.initiatedBy)||void 0===r?void 0:r.active)&&t(Tw({enabled:!1}))}});const n_=["recorder","streamer"],s_=e=>e.localParticipant,o_=e=>e.localParticipant.id,a_=e=>e.localParticipant.displayName,c_=e=>e.localParticipant.stickyReaction,d_=Ge(s_,Qw,((e,t)=>{const r={id:e.id,clientId:e.id,breakoutGroup:e.breakoutGroup,displayName:e.displayName,stream:t,isLocalClient:!0,isAudioEnabled:e.isAudioEnabled,isVideoEnabled:e.isVideoEnabled};return n_.includes(e.roleName)?null:r}));function l_({assignments:e,groups:t,startedAt:r,initiatedBy:i,breakoutStartedAt:n,breakoutEndedAt:s,breakoutNotification:o,breakoutTimerDuration:a,autoMoveToGroup:c,moveToGroupGracePeriod:d,autoMoveToMain:l,moveToMainGracePeriod:u,enforceAssignment:p,breakoutTimerSetting:h}={}){return{assignments:e||null,groups:t||null,startedAt:r?new Date(r):null,initiatedBy:i,breakoutStartedAt:n||null,breakoutEndedAt:s||null,breakoutNotification:o||null,breakoutTimerDuration:a||1800,autoMoveToGroup:c||!1,moveToGroupGracePeriod:d||10,autoMoveToMain:l||!1,moveToMainGracePeriod:u||30,enforceAssignment:p||!1,breakoutTimerSetting:h||!1}}const u_=Dt({name:"breakout",initialState:Object.assign(Object.assign({},l_()),{groupId:null}),reducers:{},extraReducers:e=>{e.addCase(Fy.roomJoined,((e,t)=>t.payload.breakout?Object.assign(Object.assign({},e),l_(t.payload.breakout)):e)),e.addCase(Fy.breakoutSessionUpdated,((e,t)=>Object.assign(Object.assign({},e),l_(t.payload)))),e.addCase(Fy.breakoutGroupJoined,((e,t)=>{var r;return(null===(r=t.meta)||void 0===r?void 0:r.localParticipantId)!==t.payload.clientId?e:Object.assign(Object.assign({},e),{groupId:t.payload.group})}))}}),p_=e=>(t,r)=>{const i=r(),{socket:n}=fw(i);null==n||n.emit("join_breakout_group",{group:e.group})},h_=e=>e.breakout,f_=e=>!!e.breakout.startedAt,m_=e=>e.breakout.assignments,g_=Ge(h_,(e=>e.localParticipant.breakoutGroup),((e,t)=>e.groupId||t||"")),v_=Ge(h_,g_,((e,t)=>{var r;const i=null===(r=e.groups)||void 0===r?void 0:r[t];return i?{id:t,name:i}:null}));Py({actionCreator:Fy.breakoutMoveToGroup,effect:(e,{dispatch:t,getState:r})=>{const i=r(),n=s_(i).breakoutGroupAssigned;n&&t(p_({group:n}))}}),Py({actionCreator:Fy.breakoutMoveToMain,effect:(e,{dispatch:t})=>{t(p_({group:""}))}}),Py({actionCreator:Fy.breakoutSessionUpdated,effect:({payload:e},{dispatch:t,getState:r})=>{var i;const n=r(),s=h_(n).autoMoveToMain;!1===(null===(i=e.initiatedBy)||void 0===i?void 0:i.active)&&(s||t(p_({group:""})))}});const b_=Dt({name:"chat",initialState:{chatMessages:[]},reducers:{},extraReducers(e){e.addCase(Fy.chatMessage,((e,t)=>{const r={senderId:t.payload.senderId,timestamp:t.payload.timestamp,text:t.payload.text};return Object.assign(Object.assign({},e),{chatMessages:[...e.chatMessages,r]})}))}}),y_=Cy((e=>(t,r)=>{const i=r(),n=fw(i).socket,s=g_(i);null==n||n.emit("chat_message",Object.assign(Object.assign({text:e.text},s&&{breakoutGroup:s}),e.isBroadcast&&{broadcast:!0}))})),w_=Dt({name:"cloudRecording",initialState:{isRecording:!1,error:null,startedAt:void 0},reducers:{recordingRequestStarted:e=>Object.assign(Object.assign({},e),{status:"requested"})},extraReducers:e=>{e.addCase(Fy.cloudRecordingStopped,(e=>Object.assign(Object.assign({},e),{isRecording:!1,status:void 0}))),e.addCase(Fy.cloudRecordingStarted,((e,t)=>{const{payload:r}=t;return r.error?Object.assign(Object.assign({},e),{isRecording:!1,status:"error",error:r.error}):e})),e.addCase(Fy.newClient,((e,{payload:t})=>{var r;const{client:i}=t;return"recorder"===(null===(r=i.role)||void 0===r?void 0:r.roleName)?Object.assign(Object.assign({},e),{isRecording:!0,status:"recording",startedAt:i.startedCloudRecordingAt?new Date(i.startedCloudRecordingAt).getTime():(new Date).getTime()}):e}))}}),{recordingRequestStarted:__}=w_.actions,S_=Cy((()=>(e,t)=>{const r=t(),i=fw(r).socket,n=R_(r);n&&["recording","requested"].includes(n)||(null==i||i.emit("start_recording",{recording:"cloud"}),e(__()))})),C_=Cy((()=>(e,t)=>{const r=t(),i=fw(r).socket;null==i||i.emit("stop_recording")})),R_=e=>e.cloudRecording.status,k_=e=>e.roomConnection.status;function T_(e){return Qe(`rtcConnection/event/${e}`)}const P_={rtcManagerCreated:T_("rtcManagerCreated"),rtcManagerDestroyed:T_("rtcManagerDestroyed"),streamAdded:T_("streamAdded"),clientConnectionStatusChanged:T_("clientConnectionStatusChanged")};function O_(e,t=!1){const{streams:r,role:i,breakoutGroup:n}=e,s=Zy(e,["streams","role","breakoutGroup"]);return Object.assign(Object.assign({},s),{stream:null,streams:r.map((e=>({id:e,state:t?"new_accept":"to_accept"}))),isLocalParticipant:!1,roleName:(null==i?void 0:i.roleName)||"none",presentationStream:null,breakoutGroup:n||null,newJoiner:t})}function E_(e,t){const r=e.remoteParticipants.findIndex((e=>e.id===t));return{index:r,participant:e.remoteParticipants[r]}}function D_(e,t,r){const{participant:i,index:n}=E_(e,t);return i?Object.assign(Object.assign({},e),{remoteParticipants:[...e.remoteParticipants.slice(0,n),Object.assign(Object.assign({},i),r),...e.remoteParticipants.slice(n+1)]}):(console.error(`Did not find client for update ${t}`),e)}function I_(e,t,r,i){const{participant:n}=E_(e,t);if(!n)return console.error(`No client ${t} found to update stream ${r} ${i}`),e;const s=n.streams.findIndex((e=>e.id===r)),o=[...n.streams];return o[s]=Object.assign(Object.assign({},o[s]),{state:i}),D_(e,t,{streams:o})}function x_(e,t,r){const{participant:i}=E_(e,t);return!i||i.streams.find((e=>e.id===r))?(console.warn(`No participant ${t} or stream ${r} already exists`),e):D_(e,t,{streams:[...i.streams,{id:r,state:"to_accept"}]})}const M_=Dt({name:"remoteParticipants",initialState:{remoteParticipants:[]},reducers:{streamStatusUpdated:(e,t)=>{let r=e;for(const{clientId:e,streamId:i,state:n}of t.payload)r=I_(r,e,i,n);return r},participantStreamAdded:(e,t)=>{const{clientId:r,stream:i}=t.payload;return D_(e,r,{stream:i})},participantStreamIdAdded:(e,t)=>{const{clientId:r,streamId:i}=t.payload;return x_(e,r,i)}},extraReducers:e=>{e.addCase(Fy.roomJoined,((e,t)=>{var r;if(!(null===(r=t.payload)||void 0===r?void 0:r.room))return e;const i=t.payload.selfId,{clients:n}=t.payload.room;return Object.assign(Object.assign({},e),{remoteParticipants:n.filter((e=>e.id!==i)).map((e=>O_(e)))})})),e.addCase(P_.streamAdded,((e,t)=>function(e,t){const{clientId:r,stream:i,streamType:n}=t;let{streamId:s}=t;const{participant:o}=E_(e,r);if(!o)return console.error(`Did not find client ${r} for adding stream`),e;const a=e.remoteParticipants;s||(s=i.id);const c=a.find((e=>e.id===r));if(!c)return e;const d=c.streams.find((e=>e.id===s));return c.stream&&(c.stream.id===s||c.stream.inboundId===s)||!c.stream&&"webcam"===n||!c.stream&&!n&&!d?D_(e,r,{stream:i}):D_(e,r,{presentationStream:i})}(e,t.payload))),e.addCase(Fy.newClient,((e,t)=>{const{client:r}=t.payload;return function(e,t){const{participant:r}=E_(e,t.id);return r?(console.warn(`Client already existing ${t.id}. Ignoring`),e):Object.assign(Object.assign({},e),{remoteParticipants:[...e.remoteParticipants,t]})}(e,O_(r,!0))})),e.addCase(Fy.clientLeft,((e,t)=>{const{clientId:r}=t.payload;return function(e,t){return Object.assign(Object.assign({},e),{remoteParticipants:e.remoteParticipants.filter((e=>e.id!==t))})}(e,r)})),e.addCase(Fy.audioEnabled,((e,t)=>{const{clientId:r,isAudioEnabled:i}=t.payload;return D_(e,r,{isAudioEnabled:i})})),e.addCase(Fy.videoEnabled,((e,t)=>{const{clientId:r,isVideoEnabled:i}=t.payload;return D_(e,r,{isVideoEnabled:i})})),e.addCase(Fy.clientMetadataReceived,((e,t)=>{const{error:r,payload:i}=t.payload;if(r||!i)return console.warn(r||"Client metadata error received"),e;const{clientId:n,displayName:s,stickyReaction:o}=i;return D_(e,n,{displayName:s,stickyReaction:o})})),e.addCase(Fy.breakoutGroupJoined,((e,t)=>{const{clientId:r,group:i}=t.payload;return D_(e,r,{breakoutGroup:i||null})})),e.addCase(Fy.screenshareStarted,((e,t)=>{const{clientId:r,streamId:i}=t.payload;return x_(e,r,i)})),e.addCase(Fy.screenshareStopped,((e,t)=>{const{clientId:r,streamId:i}=t.payload;return function(e,t,r){var i,n;const{participant:s}=E_(e,t);if(!s)return console.error(`No participant ${t} found to remove stream ${r}`),e;const o=s.stream&&s.stream.id,a=(null===(i=s.presentationStream)||void 0===i?void 0:i.inboundId)||(null===(n=s.presentationStream)||void 0===n?void 0:n.id),c=s.streams.findIndex((e=>e.id===r));return D_(e,t,Object.assign(Object.assign({streams:s.streams.filter(((e,t)=>t!==c))},o===r&&{stream:null}),a===r&&{presentationStream:null}))}(e,r,i)}))}}),{participantStreamAdded:j_,participantStreamIdAdded:L_,streamStatusUpdated:A_}=M_.actions,N_=ky((e=>Hy(e)),(e=>(t,r)=>{const i=r(),n=Xy(i);if(e.enable&&!n)return void console.warn("Not authorized to perform this action");const s=fw(i).socket;null==s||s.emit("request_audio_enable",e)})),B_=ky((e=>Wy(e)),(e=>(t,r)=>{const i=r(),n=fw(i).socket;null==n||n.emit("request_video_enable",e)})),F_=e=>e.remoteParticipants.remoteParticipants,z_=Ge(F_,(e=>e.filter((e=>!n_.includes(e.roleName)))));Ge(F_,(e=>e.length+1));const V_=Ge(z_,s_,((e,t)=>n_.includes(t.roleName)?e.length:e.length+1)),U_=Dt({name:"localScreenshare",initialState:{status:"inactive",stream:null,error:null},reducers:{stopScreenshare:(e,t)=>Object.assign(Object.assign({},e),{status:"inactive",stream:null})},extraReducers:e=>{e.addCase(G_.pending,(e=>Object.assign(Object.assign({},e),{status:"starting"}))),e.addCase(G_.fulfilled,((e,{payload:{stream:t}})=>Object.assign(Object.assign({},e),{status:"active",stream:t}))),e.addCase(G_.rejected,((e,{payload:t})=>Object.assign(Object.assign({},e),{error:t,status:"inactive",stream:null})))}}),{stopScreenshare:$_}=U_.actions,G_=Ry("localScreenshare/doStartScreenshare",((e,{dispatch:t,getState:r,rejectWithValue:i})=>Yy(void 0,void 0,void 0,(function*(){var e;try{const i=r(),n=H_(i);if(n)return{stream:n};const s=yield navigator.mediaDevices.getDisplayMedia(),o=()=>{t(q_())};return"oninactive"in s?s.addEventListener("inactive",o):null===(e=s.getVideoTracks()[0])||void 0===e||e.addEventListener("ended",o),{stream:s}}catch(e){return i(e)}})))),q_=Cy((()=>(e,t)=>{const r=t(),i=H_(r);i&&(i.getTracks().forEach((e=>e.stop())),e($_({stream:i})))})),H_=e=>e.localScreenshare.stream;function W_(e){return"recorder"===e.roleName}Py({actionCreator:Dw,effect:(e,{getState:t})=>{const r=t(),i=H_(r);i&&(null==i||i.getTracks().forEach((e=>{e.stop()})))}});const K_=Dt({name:"room",initialState:{isLocked:!1},reducers:{},extraReducers:e=>{e.addCase(Fy.roomJoined,((e,t)=>{const{error:r,isLocked:i}=t.payload;return r?e:Object.assign(Object.assign({},e),{isLocked:Boolean(i)})})),e.addCase(Fy.roomLocked,((e,t)=>{const{isLocked:r}=t.payload;return Object.assign(Object.assign({},e),{isLocked:Boolean(r)})}))}}),J_=Sy((e=>qy(e)),(e=>(t,r)=>{const i=r(),{socket:n}=fw(i);null==n||n.emit("set_lock",{locked:e.locked})})),X_=Sy((e=>Ky(e)),(e=>(t,r)=>{const i=r(),{socket:n}=fw(i);null==n||n.emit("kick_client",{clientId:e.clientId,reasonId:"kick"})})),Q_=Sy((e=>Jy(e)),(e=>(t,r)=>{const i=r(),n=F_(i).map((e=>e.id));if(n.length){const{socket:e}=fw(i);null==e||e.emit("kick_client",{clientIds:n,reasonId:"end-meeting"})}e.stayBehind||t(Dy())})),Z_=Ge(H_,s_,z_,((e,t,r)=>{const i=[];e&&i.push({id:e.id||"local-screenshare",participantId:"local",hasAudioTrack:e.getTracks().some((e=>"audio"===e.kind)),breakoutGroup:t.breakoutGroup,stream:e,isLocal:!0});for(const e of r)e.presentationStream&&i.push({id:e.presentationStream.id||`pres-${e.id}`,participantId:e.id,hasAudioTrack:e.presentationStream.getTracks().some((e=>"audio"===e.kind)),breakoutGroup:e.breakoutGroup,stream:e.presentationStream,isLocal:!1});return i})),Y_=Ge(H_,s_,z_,g_,m_,((e,t,r,i,n)=>{const s=[];if(e){const r=!!e.getAudioTracks().length;s.push({clientId:t.id,displayName:"Your screenshare",id:"local-screenshare",isAudioEnabled:r,isLocalClient:!0,isPresentation:!0,isVideoEnabled:!0,stream:e,breakoutGroup:i||""})}for(const e of r){if("streamer"===e.roleName||W_(e))continue;const{presentationStream:t}=e,r=Zy(e,["presentationStream"]),i=e.displayName||"Guest",o=t&&t.active,a="pres-"+e.id,c=e.stream&&e.stream.active,d=e.isVideoEnabled;s.push(Object.assign(Object.assign(Object.assign({},r),{breakoutGroupAssigned:(null==n?void 0:n[e.deviceId])||"",clientId:e.id,displayName:i,hasActivePresentation:!!o}),e.isVideoEnabled?{isVideoEnabled:d}:{})),o&&s.push(Object.assign(Object.assign(Object.assign({},r),{clientId:e.id,stream:e.presentationStream,displayName:`Screenshare (${i})`,id:a,isPresentation:!0,isVideoEnabled:!0}),c&&{isRecording:null}))}return s})),eS=Ge(d_,Y_,((e,t)=>[...e?[e]:[],...t])),tS=Ge(eS,f_,g_,((e,t,r)=>t&&r?e.filter((e=>e.isLocalClient||e.breakoutGroup===(r||"")||e.breakoutGroupAssigned&&e.breakoutGroupAssigned===r)):e)),rS=Ge(eS,f_,(e=>e.breakout.groups),((e,t,r)=>{if(!t||!r)return[];return[{clients:e.filter((e=>!e.breakoutGroup||""===e.breakoutGroup)),group:{id:"",name:""}},...Object.entries(r).map((([t,r])=>({clients:e.filter((e=>!e.isPresentation&&e.breakoutGroup===t)),group:{id:t,name:r}})))]}));function iS({isPresentation:e,stream:t}){var r,i;return e?null!==(i=null!==(r=null==t?void 0:t.outboundId)&&void 0!==r?r:null==t?void 0:t.inboundId)&&void 0!==i?i:null==t?void 0:t.id:"0"}function nS(e,t){return e.find((e=>e.clientId===t.clientId&&e.streamId===t.streamId))?e:e.concat(t)}const sS=Dt({name:"spotlights",initialState:{sorted:[]},reducers:{addSpotlight(e,t){const{clientId:r,streamId:i}=t.payload;return Object.assign(Object.assign({},e),{sorted:nS(e.sorted,{clientId:r,streamId:i})})},removeSpotlight(e,t){const{clientId:r,streamId:i}=t.payload;return Object.assign(Object.assign({},e),{sorted:e.sorted.filter((e=>!(e.clientId===r&&e.streamId===i)))})}},extraReducers:e=>{e.addCase(Fy.roomJoined,((e,t)=>{if(!t.payload.room)return e;const{spotlights:r}=t.payload.room;return Object.assign(Object.assign({},e),{sorted:r})})),e.addCase(Fy.spotlightAdded,((e,t)=>{const{clientId:r,streamId:i}=t.payload;return Object.assign(Object.assign({},e),{sorted:nS(e.sorted,{clientId:r,streamId:i})})})),e.addCase(Fy.spotlightRemoved,((e,t)=>{const{clientId:r,streamId:i}=t.payload;return Object.assign(Object.assign({},e),{sorted:e.sorted.filter((e=>!(e.clientId===r&&e.streamId===i)))})})),e.addMatcher(yt(Fy.clientKicked,Fy.clientLeft),((e,t)=>{const{clientId:r}=t.payload;return Object.assign(Object.assign({},e),{sorted:e.sorted.filter((e=>e.clientId!==r))})}))}}),{addSpotlight:oS,removeSpotlight:aS}=sS.actions,cS=Sy((e=>Qy(e)),(({id:e})=>(t,r)=>{const i=r(),n=eS(i).find((t=>t.clientId===e));if(!n)return;const{socket:s}=fw(i),o=iS(n),a={clientId:n.id,streamId:null!=o?o:"0"};null==s||s.emit("add_spotlight",a)})),dS=Sy((e=>Qy(e)),(({id:e})=>(t,r)=>{const i=r(),n=eS(i).find((t=>t.clientId===e));if(!n)return;const{socket:s}=fw(i),o=iS(n),a={clientId:n.id,streamId:null!=o?o:"0"};null==s||s.emit("remove_spotlight",a)})),lS=e=>e.spotlights.sorted;Ge(s_,lS,((e,t)=>function({spotlights:e,isPresentation:t,clientId:r,stream:i}){return!!e.find((e=>{const n=iS({isPresentation:t,stream:i});return e.clientId===r&&e.streamId===n}))}({clientId:e.id,stream:e.stream,spotlights:t})));const uS=Ge(eS,lS,((e,t)=>function(e,t){return e.reduce(((e,r)=>{const i=t.find((e=>r.clientId===e.clientId&&r.streamId===iS(e)));return i&&!e.includes(i)&&e.push(i),e}),[])}(t,e)));Py({actionCreator:G_.fulfilled,effect:({payload:e},{getState:t,dispatch:r})=>{const{stream:i}=e,n=t(),s=s_(n);s&&r(oS({clientId:s.id,streamId:i.id}))}}),Py({actionCreator:$_,effect:({payload:e},{getState:t,dispatch:r})=>{const{stream:i}=e,n=t(),s=s_(n);s&&r(aS({clientId:s.id,streamId:i.id}))}});const pS=e=>({emit:(t,r)=>{"rtc_manager_created"===t?e(PS(r)):"stream_added"===t?e(P_.streamAdded(r)):"rtc_manager_destroyed"===t?e(yS()):"client_connection_status_changed"===t&&e(P_.clientConnectionStatusChanged(r))}}),hS={dispatcherCreated:!1,error:null,isCreatingDispatcher:!1,reportedStreamResolutions:{},rtcManager:null,rtcManagerDispatcher:null,rtcManagerInitialized:!1,status:"inactive",isAcceptingStreams:!1},fS=Dt({name:"rtcConnection",initialState:hS,reducers:{isAcceptingStreams:(e,t)=>Object.assign(Object.assign({},e),{isAcceptingStreams:t.payload}),resolutionReported:(e,t)=>{const{streamId:r,width:i,height:n}=t.payload;return Object.assign(Object.assign({},e),{reportedStreamResolutions:Object.assign(Object.assign({},e.reportedStreamResolutions),{[r]:{width:i,height:n}})})},rtcDisconnected:()=>Object.assign({},hS),rtcDispatcherCreated:(e,t)=>Object.assign(Object.assign({},e),{dispatcherCreated:!0,rtcManagerDispatcher:t.payload}),rtcManagerCreated:(e,t)=>Object.assign(Object.assign({},e),{rtcManager:t.payload,status:"ready"}),rtcManagerDestroyed:e=>Object.assign(Object.assign({},e),{rtcManager:null}),rtcManagerInitialized:e=>Object.assign(Object.assign({},e),{rtcManagerInitialized:!0}),rtcClientConnectionStatusChanged:{reducer:e=>e,prepare:e=>({payload:{},meta:{localParticipantId:e.localParticipantId}})}},extraReducers:e=>{e.addCase(lw,(e=>Object.assign(Object.assign({},e),{status:"reconnecting"}))),e.addCase(Fy.roomJoined,(e=>Object.assign(Object.assign({},e),{status:"reconnecting"===e.status?"ready":e.status})))}}),{resolutionReported:mS,rtcDispatcherCreated:gS,rtcDisconnected:vS,rtcManagerCreated:bS,rtcManagerDestroyed:yS,rtcManagerInitialized:wS,isAcceptingStreams:_S,rtcClientConnectionStatusChanged:SS}=fS.actions,CS=()=>(e,t)=>{const r=t(),i=fw(r).socket,n=ES(r).rtcManagerDispatcher,s=Gw(r),o=qw(r),a=(e=>e.app.isNodeSdk)(r);if(n||!i)return;const c={getMediaConstraints:()=>({audio:o,video:s}),deferrable:e=>function({client:e,breakoutCurrentId:t}){return!(!e||(t||!e.breakoutGroup)&&(e.isAudioEnabled||e.isVideoEnabled))}({client:z_(t()).find((t=>t.id===e)),breakoutCurrentId:g_(t())||""})},d=new sv({emitter:pS(e),serverSocket:i,webrtcProvider:c,features:{isNodeSdk:a,lowDataModeEnabled:!1,sfuServerOverrideHost:void 0,turnServerOverrideHost:void 0,useOnlyTURN:void 0,vp9On:!1,h264On:!1,simulcastScreenshareOn:!1}});e(gS(d))},RS=()=>(e,t)=>{const{rtcManager:r}=ES(t());r&&r.disconnectAll(),e(vS())},kS=e=>(t,r)=>{var i;t(_S(!0));const n=r(),s=ES(n).rtcManager,o=F_(n);if(!s)throw new Error("No rtc manager");const a=f_(n),c=null===(i=s.shouldAcceptStreamsFromBothSides)||void 0===i?void 0:i.call(s),d=[];for(const{clientId:t,streamId:r,state:i}of e){if(o.find((e=>e.id===t))){if("to_accept"===i||"new_accept"===i&&c||"old_accept"===i&&!c)s.acceptNewStream({streamId:"0"===r?t:r,clientId:t,shouldAddLocalVideo:"0"===r,activeBreakout:a});else if("new_accept"===i||"old_accept"===i);else if("to_unaccept"===i)null==s||s.disconnect("0"===r?t:r,a);else if("done_accept"!==i)continue;d.push({clientId:t,streamId:r,state:i.replace(/to_|new_|old_/,"done_")})}}t(A_(d)),t(_S(!1))},TS=({streamId:e,width:t,height:r})=>(i,n)=>{const{reportedStreamResolutions:s,rtcManager:o}=ES(n()),a=Qw(n());if(!o||(null==a?void 0:a.id)===e)return;const c=s[e];c&&c.width===t&&c.height===r||o.updateStreamResolution(e,null,{width:t||1,height:r||1}),i(mS({streamId:e,width:t,height:r}))},PS=e=>t=>{const{rtcManager:r}=e;t(bS(r))},OS=()=>(e,t)=>{const r=Qw(t()),i=ES(t()).rtcManager,n=Gw(t()),s=qw(t());r&&i&&i.addNewStream("0",r,!s,!n),e(wS())},ES=e=>e.rtcConnection,DS=e=>e.rtcConnection.rtcManagerInitialized,IS=e=>e.rtcConnection.rtcManager,xS=e=>e.rtcConnection.status;Py({actionCreator:Lw.fulfilled,effect:({payload:e},{getState:t})=>{const{replacedTracks:r}=e,{rtcManager:i}=ES(t()),n=Qw(t());null==r||r.forEach((e=>{((e,t)=>{const r=null==n?void 0:n.getTracks().find((t=>t.kind===e));r&&(null==i||i.replaceTrack(t,r))})(e.kind,e)}))}}),Py({actionCreator:G_.fulfilled,effect:({payload:e},{getState:t})=>{const{stream:r}=e,{rtcManager:i}=ES(t());null==i||i.addNewStream(r.id,r,!1,!0)}}),Py({actionCreator:Dy,effect:(e,{getState:t})=>{const r=IS(t());null==r||r.rtcStatsDisconnect()}}),Py({actionCreator:$_,effect:({payload:e},{getState:t})=>{const{stream:r}=e,{rtcManager:i}=ES(t());null==i||i.removeStream(r.id,r,null)}}),Py({actionCreator:Nw.fulfilled,effect:({payload:e},{getState:t})=>{var r;const i=Qw(t()),{rtcManager:n}=ES(t());if(i&&n){const t=(e,t)=>{const r=i.getTracks().find((t=>t.kind===e));return r&&n.replaceTrack(t,r)};null===(r=null==e?void 0:e.replacedTracks)||void 0===r||r.forEach((e=>{t(e.kind,e)}))}}}),Py({actionCreator:P_.clientConnectionStatusChanged,effect:(e,{dispatch:t,getState:r})=>{const i=s_(r());t(SS({localParticipantId:i.id}))}});Oy([Ge(xS,xy,(e=>e.rtcConnection.dispatcherCreated),(e=>e.rtcConnection.isCreatingDispatcher),vw,((e,t,r,i,n)=>!(!t||"inactive"!==e||r||i||!n)))],(({dispatch:e},t)=>{t&&e(CS())}));const MS=Ge(IS,DS,Xw,((e,t,r)=>!("started"!==r||!e||t)));Oy([MS],(({dispatch:e},t)=>{t&&e(OS())}));Oy([Ge(xS,xy,((e,t)=>!t&&!["inactive","disconnected"].includes(e)))],(({dispatch:e},t)=>{t&&e(RS())}));const jS=Ge(xS,F_,g_,lS,(e=>e.app.ignoreBreakoutGroups),((e,t,r,i,n)=>{if("ready"!==e)return[];const s=[];for(const e of t){const{streams:t,id:o,newJoiner:a}=e,c=i.find((t=>t.clientId===e.id&&"0"===t.streamId));for(let i=0;i<t.length;i++){let d=t[i].id,l=t[i].state;if((null==t?void 0:t.length)>1&&"0"===t[1].id&&(0===i?(d=t[1].id,l=t[1].state):1===i&&(d=t[0].id,l=t[0].state)),!e.breakoutGroup&&!r||e.breakoutGroup===r||""===e.breakoutGroup&&c||n){if("done_accept"===l)continue;s.push({clientId:o,streamId:d,state:(a&&"0"===d?"new":"to")+"_accept"})}else{if("done_unaccept"===l)continue;s.push({clientId:o,streamId:d,state:"to_unaccept"})}}}return s}));Oy([jS,e=>e.rtcConnection.isAcceptingStreams],(({dispatch:e},t,r)=>{0<t.length&&!r&&e(kS(t))}));const LS={running:!1},AS=Dt({name:"connectionMonitor",initialState:LS,reducers:{connectionMonitorStarted:(e,t)=>Object.assign(Object.assign({},e),{running:!0,stopCallbackFunction:t.payload.stopIssueSubscription}),connectionMonitorStopped:()=>Object.assign({},LS)}}),{connectionMonitorStarted:NS,connectionMonitorStopped:BS}=AS.actions,FS=()=>(e,t)=>{var r;r=()=>{const e=t(),r=eS(e).map((e=>{var t,r;return{id:e.id,clientId:e.clientId,isLocalClient:e.isLocalClient,audio:{enabled:e.isAudioEnabled,track:null===(t=e.stream)||void 0===t?void 0:t.getAudioTracks()[0]},video:{enabled:e.isVideoEnabled,track:null===(r=e.stream)||void 0===r?void 0:r.getVideoTracks()[0]},isPresentation:e.isPresentation}}));return r},jf.getClients=r;const i=wv({onUpdatedIssues:e=>{var r;const i=t(),n=IS(i);if(!n)return;let s=0,o=0,a=0,c=0;Object.entries(e.aggregated.metrics).forEach((([e,t])=>{/loc.*packetloss/.test(e)&&(s=Math.max(s,t.curMax)),/rem.*packetloss/.test(e)&&(o=Math.max(o,t.curMax)),/loc.*bitrate/.test(e)&&(a+=t.curSum),/rem.*bitrate/.test(e)&&(c+=t.curSum)})),n.sendStatsCustomEvent("insightsStats",{ls:Math.round(1e3*s)/1e3,lr:Math.round(1e3*o)/1e3,bs:Math.round(a),br:Math.round(c),cpu:null===(r=e.aggregated.metrics["global-cpu-pressure"])||void 0===r?void 0:r.curSum,_time:Date.now()})}});e(NS({stopIssueSubscription:i.stop}))},zS=()=>(e,t)=>{const r=t(),i=US(r);i&&i(),e(BS())},VS=e=>e.connectionMonitor.running,US=e=>e.connectionMonitor.stopCallbackFunction,$S=Ge(k_,VS,((e,t)=>!t&&"connected"===e)),GS=Ge(k_,VS,((e,t)=>!(!t||!["kicked","left"].includes(e))));Oy([$S],(({dispatch:e},t)=>{t&&e(FS())})),Oy([GS],(({dispatch:e},t)=>{t&&e(zS())}));const qS=Dt({name:"localParticipant",initialState:{displayName:"",id:"",breakoutGroup:null,breakoutGroupAssigned:"",isAudioEnabled:!0,isVideoEnabled:!0,isLocalParticipant:!0,stream:void 0,isScreenSharing:!1,roleName:"none",clientClaim:void 0,stickyReaction:void 0,isDialIn:!1},reducers:{setDisplayName:(e,t)=>Object.assign(Object.assign({},e),{displayName:t.payload.displayName}),setBreakoutGroupAssigned:(e,t)=>Object.assign(Object.assign({},e),{breakoutGroupAssigned:t.payload.breakoutGroupAssigned})},extraReducers:e=>{e.addCase(Iy,((e,t)=>Object.assign(Object.assign({},e),{displayName:t.payload.displayName}))),e.addCase(JS.fulfilled,((e,t)=>Object.assign(Object.assign({},e),{isAudioEnabled:t.payload}))),e.addCase(XS.fulfilled,((e,t)=>Object.assign(Object.assign({},e),{isVideoEnabled:t.payload}))),e.addCase(QS.fulfilled,((e,t)=>Object.assign(Object.assign({},e),{stickyReaction:t.payload}))),e.addCase(Fy.roomJoined,((e,t)=>{var r,i;const n=null===(i=null===(r=t.payload)||void 0===r?void 0:r.room)||void 0===i?void 0:i.clients.find((e=>{var r;return e.id===(null===(r=t.payload)||void 0===r?void 0:r.selfId)}));return Object.assign(Object.assign({},e),{id:t.payload.selfId,roleName:(null==n?void 0:n.role.roleName)||"none",clientClaim:t.payload.clientClaim,breakoutGroup:(null==n?void 0:n.breakoutGroup)||null})})),e.addCase(Fy.breakoutGroupJoined,((e,t)=>{var r,i;return(null===(r=t.payload)||void 0===r?void 0:r.clientId)!==e.id?e:Object.assign(Object.assign({},e),{breakoutGroup:null===(i=t.payload)||void 0===i?void 0:i.group})}))}}),{setDisplayName:HS,setBreakoutGroupAssigned:WS}=qS.actions,KS=Cy((e=>(t,r)=>{const i=r(),n=fw(i).socket;null==n||n.emit("send_client_metadata",{type:"UserData",payload:{displayName:e.displayName}}),t(HS({displayName:e.displayName}))})),JS=Ry("localParticipant/doEnableAudio",((e,{dispatch:t,getState:r})=>Yy(void 0,void 0,void 0,(function*(){const i=r(),n=fw(i).socket;return null==n||n.emit("enable_audio",{enabled:e.enabled}),e.enabled&&t(QS({enabled:!1})),e.enabled})))),XS=Ry("localParticipant/doEnableVideo",((e,{getState:t})=>Yy(void 0,void 0,void 0,(function*(){const r=t(),i=fw(r).socket;return null==i||i.emit("enable_video",{enabled:e.enabled}),e.enabled})))),QS=Ry("localParticipant/doSetLocalStickyReaction",((e,{getState:t,rejectWithValue:r})=>Yy(void 0,void 0,void 0,(function*(){var i;const n=t(),s=c_(n),o=Boolean(s),a=null!==(i=e.enabled)&&void 0!==i?i:!o;if(a===o)return r(s);return a?{reaction:"✋",timestamp:(new Date).toISOString()}:null})))),ZS=Cy((()=>(e,t)=>{const r=t(),i=fw(r).socket,n={displayName:a_(r),stickyReaction:c_(r)};null==i||i.emit("send_client_metadata",{type:"UserData",payload:n})}));Py({actionCreator:kw,effect:({payload:e},{dispatch:t,getState:r})=>{const{enabled:i}=e,{isVideoEnabled:n}=s_(r());"connected"===k_(r())&&t(XS({enabled:i||!n}))}}),Py({actionCreator:Tw,effect:({payload:e},{dispatch:t,getState:r})=>{const{enabled:i}=e,{isAudioEnabled:n}=s_(r());"connected"===k_(r())&&t(JS({enabled:i||!n}))}}),Oy([a_,c_,k_],(({dispatch:e},t,r,i)=>{"connected"===i&&e(ZS())})),Oy([m_,iw,s_],(({dispatch:e},t,r,i)=>{const n=(null==t?void 0:t[r||""])||"";i.breakoutGroupAssigned!==n&&e(WS({breakoutGroupAssigned:n}))}));function YS(e){return Object.assign(Object.assign({},e),{timestamp:Date.now()})}const eC=Dt({name:"notifications",initialState:{emitter:new Np,events:[]},reducers:{addNotification:(e,t)=>Object.assign(Object.assign({},e),{events:[...e.events,Object.assign({},t.payload)]}),doClearNotifications:e=>Object.assign(Object.assign({},e),{events:[]})}});eC.actions;const tC=e=>(t,r)=>{t(eC.actions.addNotification(e));const i=r(),n=rC(i);n.emit(e.type,e),n.emit("*",e)},rC=e=>e.notifications.emitter;Py({actionCreator:Fy.chatMessage,effect:({payload:e},{dispatch:t,getState:r})=>{const i=r(),n=z_(i).find((({id:t})=>t===e.senderId));n?t(tC(YS({type:"chatMessageReceived",message:`${n.displayName} says: ${e.text}`,props:{client:n,chatMessage:{senderId:e.senderId,timestamp:e.timestamp,text:e.text}}}))):console.warn("Could not find remote client that sent chat message")}}),Py({actionCreator:Fy.audioEnableRequested,effect:({payload:e},{dispatch:t,getState:r})=>{const{enable:i,requestedByClientId:n}=e,s=r(),o=z_(s).find((({id:e})=>e===n));o?t(tC(YS({type:i?"requestAudioEnable":"requestAudioDisable",message:i?`${o.displayName} has requested for you to speak`:`${o.displayName} has muted your microphone`,props:{client:o,enable:i}}))):console.warn("Could not find remote client that requested a local audio change")}}),Py({actionCreator:Fy.videoEnableRequested,effect:({payload:e},{dispatch:t,getState:r})=>{const{enable:i,requestedByClientId:n}=e,s=r(),o=z_(s).find((({id:e})=>e===n));o?t(tC(YS({type:i?"requestVideoEnable":"requestVideoDisable",message:i?`${o.displayName} has requested for you to start video`:`${o.displayName} has stopped your video`,props:{client:o,enable:i}}))):console.warn("Could not find remote client that requested a local video change")}}),Py({actionCreator:Fy.clientMetadataReceived,effect:(e,{dispatch:t,getOriginalState:r,getState:i})=>{var n;const{error:s,payload:o}=e.payload;if(s||!o)return;const{clientId:a,stickyReaction:c}=o,d=i();if(!Xy(d))return;const l=z_(d).find((({id:e})=>e===a));if(!l)return void console.warn("Could not find remote client that provided updated metadata");const u=r(),p=z_(u).find((({id:e})=>e===a));(c||(null==p?void 0:p.stickyReaction))&&(null==c?void 0:c.timestamp)!==(null===(n=null==p?void 0:p.stickyReaction)||void 0===n?void 0:n.timestamp)&&t(tC(YS({type:c?"remoteHandRaised":"remoteHandLowered",message:`${l.displayName} ${c?"raised":"lowered"} their hand`,props:{client:l,stickyReaction:c}})))}}),Oy([gw],(({dispatch:e,getState:t},r)=>{const i=t(),n=k_(i);["left","kicked"].includes(n)||("disconnected"===r?e(tC(YS({type:"signalTrouble",message:"Network connection lost. Trying to reconnect you...",props:{}}))):"connected"===r&&e(tC(YS({type:"signalOk",message:"Network connection available",props:{}}))))})),Py({actionCreator:Fy.clientUnableToJoin,effect:(e,{dispatch:t})=>{var r;"room_full"===(null===(r=e.payload)||void 0===r?void 0:r.error)&&t(tC(YS({type:"clientUnableToJoinFullRoom",message:"Someone tried to join but the room is full and at capacity.",props:{}})))}});const iC=Dt({initialState:{data:null,isFetching:!1,error:null},name:"organization",reducers:{},extraReducers:e=>{e.addCase(nC.pending,(e=>Object.assign(Object.assign({},e),{isFetching:!0}))),e.addCase(nC.fulfilled,((e,t)=>t.payload?Object.assign(Object.assign({},e),{isFetching:!1,data:t.payload}):Object.assign(Object.assign({},e),{isFetching:!0}))),e.addCase(nC.rejected,(e=>Object.assign(Object.assign({},e),{isFetching:!1,error:!0})))}}),nC=_y("organization/doOrganizationFetch",((e,{extra:t,getState:r})=>Yy(void 0,void 0,void 0,(function*(){try{const e=r().app.roomUrl,i=yield t.services.fetchOrganizationFromRoomUrl(e||"");if(!i)throw new Error("Invalid room url");return i}catch(e){console.error(e)}})))),sC=e=>{var t;return null===(t=e.organization.data)||void 0===t?void 0:t.organizationId};Oy([Ge(xy,(e=>e.organization),rw,((e,t,r)=>!(!e||t.data||t.isFetching||t.error||r.isFetching)))],(({dispatch:e},t)=>{t&&e(nC())}));const oC=Dt({initialState:{session:null,status:"ready",error:null},name:"roomConnection",reducers:{connectionStatusChanged:(e,t)=>Object.assign(Object.assign({},e),{status:t.payload})},extraReducers:e=>{e.addCase(Fy.roomJoined,((e,t)=>{var r,i;const{error:n,isLocked:s}=t.payload;return"room_locked"===n&&s?Object.assign(Object.assign({},e),{status:"room_locked"}):n?Object.assign(Object.assign({},e),{status:"disconnected",error:n}):Object.assign(Object.assign({},e),{status:"connected",session:null!==(i=null===(r=t.payload.room)||void 0===r?void 0:r.session)&&void 0!==i?i:null})})),e.addCase(Fy.disconnect,(e=>["kicked","left"].includes(e.status)?Object.assign({},e):Object.assign(Object.assign({},e),{status:"disconnected"}))),e.addCase(Fy.newClient,((e,t)=>{var r,i;return Object.assign(Object.assign({},e),{session:null!==(i=null===(r=t.payload.room)||void 0===r?void 0:r.session)&&void 0!==i?i:null})})),e.addCase(Fy.roomSessionEnded,((e,t)=>{var r;return(null===(r=e.session)||void 0===r?void 0:r.id)!==t.payload.roomSessionId?e:Object.assign(Object.assign({},e),{session:null})})),e.addCase(Fy.clientKicked,(e=>Object.assign(Object.assign({},e),{status:"kicked"}))),e.addCase(Fy.roomLeft,(e=>Object.assign(Object.assign({},e),{status:"left"}))),e.addCase(lw,(e=>Object.assign(Object.assign({},e),{status:"reconnecting"})))}}),{connectionStatusChanged:aC}=oC.actions,cC=()=>(e,t)=>{const r=t(),i=fw(r).socket,n=jy(r),s=$y(r),o=Ly(r),a=My(r),c=Ay(r),d=Ny(r),l=sC(r);"room_locked"===k_(r)?(null==i||i.emit("knock_room",{avatarUrl:null,config:{isAudioEnabled:!0,isVideoEnabled:!0},deviceCapabilities:{canScreenshare:!0},displayName:o,isCoLocated:!1,isDialIn:a,isDevicePermissionDenied:!1,kickFromOtherRooms:!1,organizationId:l,roomKey:s,roomName:n,userAgent:c,externalId:d}),e(aC("knocking"))):console.warn("Room is not locked, knock aborted")},dC=()=>(e,t)=>{const r=t(),i=fw(r).socket,n=jy(r),s=$y(r),o=Ly(r),a=Ay(r),c=Ny(r),d=My(r),l=sC(r),u=Gw(t()),p=qw(t()),h=(e=>e.localParticipant.clientClaim)(t());null==i||i.emit("join_room",Object.assign({avatarUrl:null,config:{isAudioEnabled:p,isVideoEnabled:u},deviceCapabilities:{canScreenshare:!0},displayName:o,isCoLocated:!1,isDialIn:d,isDevicePermissionDenied:!1,kickFromOtherRooms:!1,organizationId:l,roomKey:s,roomName:n,userAgent:a,externalId:c},h&&{clientClaim:h})),e(aC("connecting"))};Oy([Ge([xy,sC,k_,mw,Xw,e=>e.roomConnection.error],((e,t,r,i,n,s)=>!(!(e&&"started"===n&&i&&t&&["ready","reconnecting","disconnected"].includes(r))||s)))],(({dispatch:e},t)=>{t&&e(dC())})),Py({actionCreator:Fy.knockHandled,effect:({payload:e},{dispatch:t,getState:r})=>{const{clientId:i,resolution:n}=e,s=r();i===o_(s)&&("accepted"===n?(t(Uy(e.metadata.roomKey)),t(dC())):"rejected"===n&&t(aC("knock_rejected")))}}),Py({actionCreator:Dy,effect:(e,{dispatch:t,getState:r})=>{const i=r();if("connected"===k_(i)){const e=fw(i).socket;null==e||e.emit("leave_room"),t(aC("leaving"))}else hw()}});const lC={audioEnabled:{actions:[JS.fulfilled],rtcEventName:"audioEnabled",getValue:e=>qw(e),getOutput:e=>({enabled:e})},videoEnabled:{actions:[XS.fulfilled],rtcEventName:"videoEnabled",getValue:e=>Gw(e),getOutput:e=>({enabled:e})},localStream:{actions:[Lw.fulfilled],rtcEventName:"localStream",getValue:e=>{var t;return null===(t=Qw(e))||void 0===t?void 0:t.getTracks().map((e=>({id:e.id,kind:e.kind,label:e.label})))},getOutput:e=>({stream:e})},localScreenshareStream:{actions:[G_.fulfilled],rtcEventName:"localScreenshareStream",getValue:e=>{var t;return null===(t=H_(e))||void 0===t?void 0:t.getTracks().map((e=>({id:e.id,kind:e.kind,label:e.label})))},getOutput:e=>({tracks:e})},localScreenshareStreamStopped:{actions:[$_],rtcEventName:"localScreenshareStream",getValue:()=>()=>null,getOutput:()=>({})},displayName:{actions:[HS],rtcEventName:"displayName",getValue:e=>Ly(e),getOutput:e=>({displayName:e})},clientId:{actions:null,rtcEventName:"clientId",getValue:e=>o_(e),getOutput:e=>({clientId:e})},deviceId:{actions:null,rtcEventName:"deviceId",getValue:e=>iw(e),getOutput:e=>({deviceId:e})},externalId:{actions:null,rtcEventName:"externalId",getValue:e=>Ny(e),getOutput:e=>({externalId:e})},organizationId:{actions:null,rtcEventName:"organizationId",getValue:e=>sC(e),getOutput:e=>({organizationId:e})},signalConnectionStatus:{actions:null,rtcEventName:"signalConnectionStatus",getValue:e=>gw(e),getOutput:e=>({status:e})},roomSessionId:{actions:[Fy.newClient,Fy.roomJoined,Fy.roomSessionEnded,Fy.clientLeft],rtcEventName:"roomSessionId",getValue:e=>(e=>{var t;return null===(t=e.roomConnection.session)||void 0===t?void 0:t.id})(e),getOutput:e=>({roomSessionId:e})},rtcConnectionStatus:{actions:null,rtcEventName:"rtcConnectionStatus",getValue:e=>xS(e),getOutput:e=>({status:e})},userRole:{actions:null,rtcEventName:"userRole",getValue:e=>Gy(e),getOutput:e=>({userRole:e})}},uC=Object.values(lC).flatMap((({actions:e})=>{var t;return null!==(t=null==e?void 0:e.map((e=>e)))&&void 0!==t?t:null})).filter((e=>null!==e)),pC=e=>"object"==typeof e?JSON.stringify(e):e,hC=Dt({initialState:{reportedValues:{}},name:"rtcAnalytics",reducers:{updateReportedValues:(e,t)=>Object.assign(Object.assign({},e),{reportedValues:Object.assign(Object.assign({},e.reportedValues),{[t.payload.rtcEventName]:t.payload.value})})}}),fC=()=>(e,t)=>{const r=t(),i=ES(r).rtcManager;i&&(i.sendStatsCustomEvent("insightsStats",{_time:Date.now(),ls:0,lr:0,bs:0,br:0,cpu:0}),Object.values(lC).forEach((({rtcEventName:t,getValue:n,getOutput:s})=>{var o;const a=n(r),c=Object.assign(Object.assign({},s(a)),{_time:Date.now()}),d=pC(a);(null===(o=r.rtcAnalytics.reportedValues)||void 0===o?void 0:o[t])!==d&&(i.sendStatsCustomEvent(t,c),e(mC({rtcEventName:t,value:a})))})))},{updateReportedValues:mC}=hC.actions;Py({matcher:yt(...uC),effect:({type:e},{getState:t,dispatch:r})=>{var i;const n=t(),s=ES(n).rtcManager;if(!s)return;const o=Object.values(lC).find((({actions:t})=>null==t?void 0:t.map((e=>e.type)).includes(e)));if(!o)return;const{getValue:a,getOutput:c,rtcEventName:d}=o,l=a(n),u=pC(l),p=Object.assign(Object.assign({},c(l)),{_time:Date.now()});(null===(i=n.rtcAnalytics.reportedValues)||void 0===i?void 0:i[d])!==u&&(s.sendStatsCustomEvent(d,p),r(mC({rtcEventName:d,value:l})))}}),Oy([DS],(({dispatch:e},t)=>{t&&e(fC())}));const gC=Dt({name:"streaming",initialState:{isStreaming:!1,error:null,startedAt:void 0},reducers:{doHandleStreamingStarted:e=>Object.assign(Object.assign({},e),{isStreaming:!0,error:null,startedAt:(new Date).getTime()}),doHandleStreamingStopped:e=>Object.assign(Object.assign({},e),{isStreaming:!1})}});gC.actions;const vC=Dt({name:"waitingParticipants",initialState:{waitingParticipants:[]},reducers:{},extraReducers:e=>{e.addCase(Fy.roomJoined,((e,{payload:t})=>{var r;return(null===(r=t.room)||void 0===r?void 0:r.knockers.length)?Object.assign(Object.assign({},e),{waitingParticipants:t.room.knockers.map((e=>({id:e.clientId,displayName:e.displayName})))}):e})),e.addCase(Fy.roomKnocked,((e,t)=>{const{clientId:r,displayName:i}=t.payload;return Object.assign(Object.assign({},e),{waitingParticipants:[...e.waitingParticipants,{id:r,displayName:i}]})})),e.addCase(Fy.knockerLeft,((e,t)=>{const{clientId:r}=t.payload;return Object.assign(Object.assign({},e),{waitingParticipants:e.waitingParticipants.filter((e=>e.id!==r))})}))}}),bC=Cy((e=>(t,r)=>{const{participantId:i}=e,n=r(),s=vw(n);null==s||s.emit("handle_knock",{action:"accept",clientId:i,response:{}})})),yC=Cy((e=>(t,r)=>{const{participantId:i}=e,n=r(),s=vw(n);null==s||s.emit("handle_knock",{action:"reject",clientId:i,response:{}})}));const wC=null===!1&&!1,_C=B({app:Ey.reducer,authorization:Vy.reducer,breakout:u_.reducer,chat:b_.reducer,cloudRecording:w_.reducer,connectionMonitor:AS.reducer,deviceCredentials:ew.reducer,localMedia:ww.reducer,localParticipant:qS.reducer,localScreenshare:U_.reducer,notifications:eC.reducer,organization:iC.reducer,remoteParticipants:M_.reducer,room:K_.reducer,roomConnection:oC.reducer,rtcAnalytics:hC.reducer,rtcConnection:fS.reducer,signalConnection:nw.reducer,spotlights:sS.reducer,streaming:gC.reducer,waitingParticipants:vC.reducer}),SC=(e,t)=>{var r;if(Iy.match(t)){const i={app:Object.assign(Object.assign({},Ey.getInitialState()),{initialConfig:null===(r=null==e?void 0:e.app)||void 0===r?void 0:r.initialConfig}),localMedia:Object.assign(Object.assign({},ww.getInitialState()),null==e?void 0:e.localMedia)};return _C(i,t)}return _C(e,t)};class CC{constructor(e={}){this.data=void 0===e.data?{}:e.data,this.headers=e.headers||{},this.status=e.status||200,this.statusText=e.statusText||"OK",this.url=e.url||null}}function RC(e,t){return dg.ok(e,`${t} is required`),e}function kC(e,t){return dg.ok("boolean"==typeof e,`${t}<boolean> is required`),e}function TC(e,t){return dg.ok("number"==typeof e,`${t}<number> is required`),e}function PC(e,t){return dg.ok("string"==typeof e,`${t}<string> is required`),e}function OC(e,t,r){const i=r||t.name[0].toLowerCase()+t.name.substring(1);return dg.ok(e instanceof t,`${i}<${t.name}> is required`),e}function EC(e,t){return dg.ok(Array.isArray(e),`${t}<array> is required`),e}function DC(e,t){if(null==e||"object"!=typeof e||Array.isArray(e))throw new Error(`${t} must be a record. ${JSON.stringify(e)}`);return e}function IC(e,t,r){PC(t,"name"),function(e,t,r,i){PC(r,"name");const n=i||`${r} must be null or of type ${t}`;dg.ok(null===e||typeof e===t,n)}(e,"string",t,r)}function xC({baseUrl:e,url:t}){return e?e+t:t}class MC{constructor({baseUrl:e}){PC(e,"baseUrl"),this._baseUrl=e}_requestAxios(e,t){const r=Object.assign({},t,{url:e,baseURL:this._baseUrl});return wy.request(r)}request(e,t){return PC(e,"url"),dg.ok("/"===e[0],'url<String> only accepts relative URLs beginning with "/".'),dg.ok(t,"options are required"),this._requestAxios(e,t).then((e=>{const{data:t,headers:r,status:i,statusText:n,config:s}=e,o=s&&s.url?xC({baseUrl:s.baseURL,url:s.url}):null;return new CC({data:t,headers:r,status:i,statusText:n,url:o})})).catch((e=>{const t=e.response;if(!t)throw new Error("Could not make the request.");const{data:r,headers:i,status:n,statusText:s,config:o}=t,a=o&&o.url?xC({baseUrl:o.baseURL,url:o.url}):null;return Promise.reject(new CC({data:r,headers:i,status:n,statusText:s,url:a}))}))}}class jC{constructor({httpClient:e}){dg.ok(e,"httpClient is required"),this._httpClient=e}static dataToFormData(e){dg.ok(e,"data is required");const t=new FormData;return Object.keys(e).forEach((r=>{const i=e[r];t.append(r,i)})),t}request(e,t={}){const r=Object.assign(t.headers||{},{"Content-Type":void 0});return this._httpClient.request(e,Object.assign(t,{headers:r,transformRequest:jC.dataToFormData}))}}let LC;LC="object"==typeof window?window.btoa||Lv:"object"==typeof global&&global.btoa||Lv;const AC=()=>Promise.resolve(null);class NC{constructor({httpClient:e,fetchDeviceCredentials:t}){this._httpClient=e,this._fetchDeviceCredentials=t}request(e,t){return this._fetchDeviceCredentials().then((r=>{const i=Object.assign({},t.headers,function(e){if(e&&e.credentials){const t=`${e.credentials.uuid}:${e.hmac}`;return{Authorization:`Basic ${LC(t)}`}}return{}}(r),{"X-Appearin-Device-Platform":"web"}),n=Object.assign({},t,{headers:i});return this._httpClient.request(e,n)}))}}class BC{constructor({baseUrl:e="https://api.appearin.net",fetchDeviceCredentials:t=AC}={}){this.authenticatedHttpClient=new NC({httpClient:new MC({baseUrl:e}),fetchDeviceCredentials:t}),this.authenticatedFormDataHttpClient=new jC({httpClient:this.authenticatedHttpClient})}request(e,t){return PC(e,"url"),dg.ok("/"===e[0],'url<String> only accepts relative URLs beginning with "/".'),dg.ok(t,"options are required"),this.authenticatedHttpClient.request(e,t)}requestMultipart(e,t){return PC(e,"url"),dg.ok("/"===e[0],'url<String> only accepts relative URLs beginning with "/".'),dg.ok(t,"options are required"),this.authenticatedFormDataHttpClient.request(e,t)}}function FC(e,t){return PC(DC(e,"data")[t],t)}const zC=(VC=FC,(e,t)=>{const r=DC(e,"data")[t];return null==r?null:VC(e,t)});var VC;function UC(e,t,r){return function(e,t){return EC(DC(e,"data")[t],t)}(e,t).map((e=>r(e)))}class $C{constructor(e,t,r=void 0){this.credentials={uuid:e},this.hmac=t,this.userId=r}toJson(){return Object.assign({credentials:this.credentials,hmac:this.hmac},this.userId&&{userId:this.userId})}static fromJson(e){return new $C(FC(function(e,t){const r=DC(e,"data")[t];return void 0===r?null:r}(e,"credentials"),"uuid"),FC(e,"hmac"),zC(e,"userId")||void 0)}}class GC{constructor({apiClient:e}){this._apiClient=e}getCredentials(){return this._apiClient.request("/devices",{method:"post"}).then((({data:e})=>$C.fromJson(e))).catch((e=>{if(e.response&&404===e.response.status)return null;throw e}))}}class qC{constructor(e,t){this._key=e,this._chromeStorage=t}loadOrDefault(e){return new Promise((t=>{this._chromeStorage.get(this._key,(r=>{t(r[this._key]||e)}))}))}save(e){return new Promise((t=>{this._chromeStorage.set({[this._key]:e},(()=>{t()}))}))}}class HC{constructor(e,t){RC(t,"localStorage"),this._key=PC(e,"key"),this._localStorage=t}loadOrDefault(e){try{const t=this._localStorage.getItem(this._key);if(t)try{return Promise.resolve(JSON.parse(t))}catch(e){}return Promise.resolve(e)}catch(t){return console.warn("Error getting access to storage. Are cookies blocked?",t),Promise.resolve(e)}}save(e){try{return this._localStorage.setItem(this._key,JSON.stringify(e)),Promise.resolve()}catch(e){return console.warn("Error getting access to storage. Are cookies blocked?",e),Promise.reject(e)}}}let WC;try{WC=self.localStorage}catch(HE){WC={getItem:()=>{},key:()=>{},setItem:()=>{},removeItem:()=>{},hasOwnProperty:()=>{},length:0}}var KC=WC;const JC="credentials_saved";class XC extends Np{constructor({deviceService:e,credentialsStore:t}){super(),this._deviceService=e,this._credentialsStore=t}static create({baseUrl:e,storeName:t="CredentialsStorage",storeType:r="localStorage"}){const i=new GC({apiClient:new BC({baseUrl:e})});let n=null;if("localStorage"===r)n=new HC(t,KC);else{if("chromeStorage"!==r)throw new Error(`Unknown store type: ${r}`);n=new qC(t,window.chrome.storage.local)}return new XC({deviceService:i,credentialsStore:n})}_fetchNewCredentialsFromApi(){const e=this._credentialsStore;return new Promise((t=>{const r=()=>{this._deviceService.getCredentials().then((r=>e.save(r?r.toJson():null).then((()=>t(r))))).catch((()=>{setTimeout(r,2e3)}))};r()}))}getCurrentCredentials(){return this._credentialsStore.loadOrDefault(null).then((e=>e?$C.fromJson(e):null))}getCredentials(){return this.credentialsPromise||(this.credentialsPromise=this.getCurrentCredentials().then((e=>e||this._fetchNewCredentialsFromApi()))),this.credentialsPromise}saveCredentials(e){return this.credentialsPromise=void 0,this._credentialsStore.save(e.toJson()).then((()=>(this.emit(JC,e),e)))}setUserId(e){return this.getCurrentCredentials().then((t=>{t||console.error("Illegal state: no credentials to set user id for.");if(null===t||t.userId!==e)return this._credentialsStore.save(Object.assign({},null==t?void 0:t.toJson(),{userId:e}))})).then((()=>{}))}}class QC{constructor({isExhausted:e,renewsAt:t,totalMinutesLimit:r,totalMinutesUsed:i}){this.isExhausted=e,this.renewsAt=t,this.totalMinutesLimit=r,this.totalMinutesUsed=i}static fromJson(e){return new QC({isExhausted:kC(e.isExhausted,"isExhausted"),renewsAt:new Date(PC(e.renewsAt,"renewsAt")),totalMinutesLimit:TC(e.totalMinutesLimit,"totalMinutesLimit"),totalMinutesUsed:TC(e.totalMinutesUsed,"totalMinutesUsed")})}}class ZC{constructor({basePlanId:e,embeddedFreeTierStatus:t,isDeactivated:r,isOnTrial:i,onTrialUntil:n,trialStatus:s}){this.basePlanId=e,this.isDeactivated=r,this.isOnTrial=i,this.onTrialUntil=n||null,this.trialStatus=s||null,this.embeddedFreeTierStatus=t||null}static fromJson(e){return new ZC({basePlanId:"string"==typeof e.basePlanId?e.basePlanId:null,isDeactivated:kC(e.isDeactivated,"isDeactivated"),isOnTrial:kC(e.isOnTrial,"isOnTrial"),onTrialUntil:"string"==typeof e.onTrialUntil?new Date(e.onTrialUntil):null,trialStatus:"string"==typeof e.trialStatus?e.trialStatus:null,embeddedFreeTierStatus:e.embeddedFreeTierStatus?QC.fromJson(e.embeddedFreeTierStatus):null})}}function YC(e){return null!=e}function eR(e={}){return{maxNumberOfInvitationsAndUsers:YC(null==e?void 0:e.maxNumberOfInvitationsAndUsers)?Number(null==e?void 0:e.maxNumberOfInvitationsAndUsers):null,maxNumberOfClaimedRooms:YC(null==e?void 0:e.maxNumberOfClaimedRooms)?Number(null==e?void 0:e.maxNumberOfClaimedRooms):null,maxRoomLimitPerOrganization:YC(null==e?void 0:e.maxRoomLimitPerOrganization)?Number(null==e?void 0:e.maxRoomLimitPerOrganization):null,trialMinutesLimit:YC(null==e?void 0:e.trialMinutesLimit)?Number(null==e?void 0:e.trialMinutesLimit):null,includedUnits:YC(null==e?void 0:e.includedUnits)?Number(null==e?void 0:e.includedUnits):null}}class tR{constructor(e){this.logoImageUrl=null,this.roomBackgroundImageUrl=null,this.roomBackgroundThumbnailUrl=null,this.roomKnockPageBackgroundImageUrl=null,this.roomKnockPageBackgroundThumbnailUrl=null,this.preferences=null,this.onboardingSurvey=null,this.type=null,OC(e,Object,"properties"),PC(e.organizationId,"organizationId"),PC(e.organizationName,"organizationName"),PC(e.subdomain,"subdomain"),OC(e.permissions,Object,"permissions"),OC(e.limits,Object,"limits"),this.organizationId=e.organizationId,this.organizationName=e.organizationName,this.subdomain=e.subdomain,this.permissions=e.permissions,this.limits=e.limits,this.account=e.account?new ZC(e.account):null,this.logoImageUrl=e.logoImageUrl,this.roomBackgroundImageUrl=e.roomBackgroundImageUrl,this.roomBackgroundThumbnailUrl=e.roomBackgroundThumbnailUrl,this.roomKnockPageBackgroundImageUrl=e.roomKnockPageBackgroundImageUrl,this.roomKnockPageBackgroundThumbnailUrl=e.roomKnockPageBackgroundThumbnailUrl,this.preferences=e.preferences,this.onboardingSurvey=e.onboardingSurvey,this.type=e.type}static fromJson(e){const t=OC(e,Object,"data"),r=(null==t?void 0:t.preferences)||{},i=(null==t?void 0:t.onboardingSurvey)||null,n=OC(t.permissions,Object,"permissions");return new tR({organizationId:PC(t.organizationId,"organizationId"),organizationName:PC(t.organizationName,"organizationName"),subdomain:PC(t.subdomain,"subdomain"),permissions:n,limits:eR(OC(t.limits,Object,"limits")),account:t.account?ZC.fromJson(t.account):null,logoImageUrl:"string"==typeof t.logoImageUrl?t.logoImageUrl:null,roomBackgroundImageUrl:"string"==typeof t.roomBackgroundImageUrl?t.roomBackgroundImageUrl:null,roomBackgroundThumbnailUrl:"string"==typeof t.roomBackgroundThumbnailUrl?t.roomBackgroundThumbnailUrl:null,roomKnockPageBackgroundImageUrl:"string"==typeof t.roomKnockPageBackgroundImageUrl?t.roomKnockPageBackgroundImageUrl:null,roomKnockPageBackgroundThumbnailUrl:"string"==typeof t.roomKnockPageBackgroundThumbnailUrl?t.roomKnockPageBackgroundThumbnailUrl:null,preferences:r,onboardingSurvey:i,type:"string"==typeof t.type?t.type:null})}}tR.GLOBAL_ORGANIZATION_ID="1";class rR{constructor({apiClient:e}){this._apiClient=e}createOrganization({organizationName:e,subdomain:t,owner:r}){const{displayName:i,consents:n}=r||{},s="email"in r?{value:r.email,verificationCode:PC(r.verificationCode,"owner.verificationCode")}:null,o="idToken"in r?r.idToken:null;if(PC(t,"subdomain"),PC(e,"organizationName"),PC(i,"owner.displayName"),dg.ok(s||o,"owner.email or owner.idToken is required"),n){EC(n,"consents");for(const{consentRevisionId:e,action:t}of n)PC(e,"consentRevisionId"),IC(t,"action")}return this._apiClient.request("/organizations",{method:"POST",data:{organizationName:e,type:"private",subdomain:t,owner:Object.assign(Object.assign(Object.assign(Object.assign({},s&&{email:s}),o&&{idToken:o}),n&&{consents:n}),{displayName:i})}}).then((({data:e})=>FC(e,"organizationId")))}getOrganizationBySubdomain(e){return PC(e,"subdomain"),this._apiClient.request(`/organization-subdomains/${encodeURIComponent(e)}/?fields=permissions,account,onboardingSurvey`,{method:"GET"}).then((({data:e})=>tR.fromJson(e))).catch((e=>{if(e instanceof CC){if(404===e.status)return null;throw new Error(e.statusText)}throw e}))}getOrganizationByOrganizationId(e){return PC(e,"organizationId"),this._apiClient.request(`/organizations/${encodeURIComponent(e)}?fields=permissions,account`,{method:"GET"}).then((({data:e})=>tR.fromJson(e))).catch((e=>{if(e instanceof CC){if(404===e.status)return null;throw new Error(e.statusText)}throw e}))}getOrganizationsByContactPoint(e){const{code:t}=e,r="email"in e?e.email:null,i="phoneNumber"in e?e.phoneNumber:null;dg.ok((r||i)&&!(r&&i),"either email or phoneNumber is required"),PC(t,"code");const n=r?{type:"email",value:r}:{type:"phoneNumber",value:i};return this._apiClient.request("/organization-queries",{method:"POST",data:{contactPoint:n,code:t}}).then((({data:e})=>UC(e,"organizations",(e=>tR.fromJson(e)))))}getOrganizationsByIdToken({idToken:e}){return PC(e,"idToken"),this._apiClient.request("/organization-queries",{method:"POST",data:{idToken:e}}).then((({data:e})=>UC(e,"organizations",(e=>tR.fromJson(Object.assign({permissions:{},limits:{}},DC(e,"organization")))))))}getOrganizationsByLoggedInUser(){return this._apiClient.request("/user/organizations",{method:"GET"}).then((({data:e})=>UC(e,"organizations",(e=>tR.fromJson(Object.assign({permissions:{},limits:{}},DC(e,"organization")))))))}getSubdomainAvailability(e){return PC(e,"subdomain"),this._apiClient.request(`/organization-subdomains/${encodeURIComponent(e)}/availability`,{method:"GET"}).then((({data:e})=>(OC(e,Object,"data"),{status:FC(e,"status")})))}updatePreferences({organizationId:e,preferences:t}){return RC(e,"organizationId"),RC(t,"preferences"),this._apiClient.request(`/organizations/${encodeURIComponent(e)}/preferences`,{method:"PATCH",data:t}).then((()=>{}))}deleteOrganization({organizationId:e}){return RC(e,"organizationId"),this._apiClient.request(`/organizations/${encodeURIComponent(e)}`,{method:"DELETE"}).then((()=>{}))}}class iR{constructor({organizationService:e,subdomain:t}){this._organizationService=e,this._subdomain=t,this._organizationPromise=null}initOrganization(){return this.fetchOrganization().then((()=>{}))}fetchOrganization(){return this._organizationPromise||(this._organizationPromise=this._organizationService.getOrganizationBySubdomain(this._subdomain)),this._organizationPromise}}const nR="https://api.whereby.dev";const sR=s.createContext(null);P(sR);const oR=function(e=v){const t=e===v?E:P(e),r=()=>t().dispatch;return Object.assign(r,{withTypes:()=>r}),r}(sR),aR=function(e=v){const t=e===v?y:b(e),r=(e,r={})=>{const{equalityFn:i=_,devModeChecks:n={}}="function"==typeof r?{equalityFn:r}:r;if(!e)throw new Error("You must pass a selector to useSelector");if("function"!=typeof e)throw new Error("You must pass a function as a selector to useSelector");if("function"!=typeof i)throw new Error("You must pass a function as an equality function to useSelector");const{store:s,subscription:o,getServerState:a,stabilityCheck:c,identityFunctionCheck:d}=t(),l=h.useRef(!0),u=h.useCallback({[e.name](t){const r=e(t);{const{identityFunctionCheck:s,stabilityCheck:o}={stabilityCheck:c,identityFunctionCheck:d,...n};if("always"===o||"once"===o&&l.current){const n=e(t);if(!i(r,n)){let i;try{throw new Error}catch(e){({stack:i}=e)}console.warn("Selector "+(e.name||"unknown")+" returned a different result when called with the same parameters. This can lead to unnecessary rerenders.\nSelectors that return a new reference (such as an object or an array) should be memoized: https://redux.js.org/usage/deriving-data-selectors#optimizing-selectors-with-memoization",{state:t,selected:r,selected2:n,stack:i})}}if(("always"===s||"once"===s&&l.current)&&r===t){let t;try{throw new Error}catch(e){({stack:t}=e)}console.warn("Selector "+(e.name||"unknown")+" returned the root state when called. This can lead to unnecessary rerenders.\nSelectors that return the entire state are almost certainly a mistake, as they will cause a rerender whenever *anything* in state changes.",{stack:t})}l.current&&(l.current=!1)}return r}}[e.name],[e,c,n.stabilityCheck]),p=w(o.addNestedSub,s.getState,a||s.getState,u,i);return h.useDebugValue(p),p};return Object.assign(r,{withTypes:()=>r}),r}(sR);var cR=function(){return cR=Object.assign||function(e){for(var t,r=1,i=arguments.length;r<i;r++)for(var n in t=arguments[r])Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e},cR.apply(this,arguments)};function dR(e,t){var r={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(r[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(i=Object.getOwnPropertySymbols(e);n<i.length;n++)t.indexOf(i[n])<0&&Object.prototype.propertyIsEnumerable.call(e,i[n])&&(r[i[n]]=e[i[n]])}return r}"function"==typeof SuppressedError&&SuppressedError;const lR=oR.withTypes(),uR=aR.withTypes(),pR=s.forwardRef(((e,t)=>{var{muted:r,mirror:i=!1,stream:n,onVideoResize:o}=e,a=dR(e,["muted","mirror","stream","onVideoResize"]);const c=lR(),d=uR($w),l=s.useRef(null),u=s.useRef(null);return s.useImperativeHandle(t,(()=>Object.assign(l.current,{captureAspectRatio:()=>{if(!l.current)return null;const e=l.current.videoHeight,t=l.current.videoWidth;return t&&e&&t+e>20?t/e:null}}))),s.useEffect((()=>{if(!l.current)return;const e=new ResizeObserver(yw((()=>{if(l.current&&(null==n?void 0:n.id)){const e=l.current.clientWidth,t=l.current.clientHeight;c(TS({streamId:n.id,width:e,height:t})),o&&o({width:e,height:t,stream:n})}}),{delay:1e3,edges:!0}));return e.observe(l.current),()=>{e.disconnect()}}),[n]),s.useEffect((()=>{l.current&&(l.current.srcObject!==n&&(l.current.srcObject=n),l.current.muted!==r&&(l.current.muted=Boolean(r)))}),[r,n,l]),s.useEffect((()=>{u.current&&!r&&n&&d&&(u.current.srcObject!==n&&(u.current.srcObject=n),u.current.setSinkId&&u.current.setSinkId(d))}),[n,u,d,r]),s.createElement(s.Fragment,null,s.createElement("video",Object.assign({ref:l,autoPlay:!0,playsInline:!0},a,{style:Object.assign({transform:i?"scaleX(-1)":"none",width:"100%",height:"100%"},a.style)})),s.createElement("audio",{ref:u,autoPlay:!0,playsInline:!0}))}));pR.displayName="VideoView";const hR=Ge((e=>e.chat.chatMessages),(e=>e.cloudRecording),v_,f_,rS,tS,s_,Qw,z_,Z_,k_,(e=>e.streaming),(e=>e.waitingParticipants.waitingParticipants),rC,uS,((e,t,r,i,n,s,o,a,c,d,l,u,p,h,f)=>({chatMessages:e,cloudRecording:t.isRecording?{status:"recording"}:void 0,breakout:{isActive:i,currentGroup:r,groupedParticipants:n,participantsInCurrentGroup:s},connectionStatus:l,events:h,liveStream:u.isStreaming?{status:"streaming",startedAt:u.startedAt}:void 0,localScreenshareStatus:o.isScreenSharing?"active":void 0,localParticipant:Object.assign(Object.assign({},o),{stream:a}),remoteParticipants:c,screenshares:d,waitingParticipants:p,spotlightedParticipants:f}))),fR={localMediaOptions:{audio:!0,video:!0}};const mR=Ge((e=>e.localMedia.cameraDeviceError),t_,Vw,Uw,$w,(e=>e.localMedia.isSettingCameraDevice),(e=>e.localMedia.isSettingMicrophoneDevice),e_,Qw,(e=>e.localMedia.microphoneDeviceError),r_,i_,(e=>e.localMedia.startError),((e,t,r,i,n,s,o,a,c,d,l,u,p)=>({cameraDeviceError:e,cameraDevices:t,currentCameraDeviceId:r,currentMicrophoneDeviceId:i,currentSpeakerDeviceId:n,isSettingCameraDevice:s,isSettingMicrophoneDevice:o,isStarting:a,localStream:c,microphoneDeviceError:d,microphoneDevices:l,speakerDevices:u,startError:p})));var gR={MIN_WINDOW_HEIGHT:320,MIN_WINDOW_WIDTH:320,DESKTOP_BREAKPOINT:1025,TABLET_BREAKPOINT:750,PHONE_BREAKPOINT:500,TOP_TOOLBAR_HEIGHT:56,BOTTOM_TOOLBAR_HEIGHT:82,SIDEBAR_WIDTH:375,VIDEO_CONTROLS_MIN_WIDTH:420,ROOM_FOOTER_MIN_WIDTH:600,FLOATING_VIDEO_CONTROLS_BOTTOM_MARGIN:20,WATERMARK_BAR_HEIGHT:32,BREAKOUT_STAGE_BACKDROP_HEADER_HEIGHT:28,BREAKOUT_STAGE_BACKDROP_FOOTER_HEIGHT:56,SUBGRID_EMPTY_STAGE_MAX_WIDTH:800,GROUPS_CELL_MARGIN:8,GROUPS_CELL_PADDING:12,GROUPS_CELL_NAV_HEIGHT:56,GROUPS_CELL_AVATAR_WRAPPER_BOTTOM_MARGIN:8,GROUPS_CELL_AVATAR_GRID_GAP:8,GROUPS_CELL_MIN_WIDTH:360,GROUPS_CELL_MAX_WIDTH:600,GROUPS_ROW_HEIGHT:72,GROUPS_ROW_GAP:1,FOLDABLE_SCREEN_STAGE_PADDING:8};function vR({top:e=0,left:t=0}={}){return{top:e,left:t}}function bR({width:e=0,height:t=0}={}){return{width:Math.max(e,0),height:Math.max(t,0)}}function yR({top:e=0,left:t=0,width:r=0,height:i=0}={}){return{bounds:bR({width:r,height:i}),origin:vR({top:e,left:t})}}function wR({top:e=0,left:t=0,bottom:r=0,right:i=0}={}){return{top:e,left:t,bottom:r,right:i}}function _R(e){return!!e&&!(e.width<=0||e.height<=0)}function SR(e,t){const{width:r,height:i}=t,n=i,s=n*e,o=Math.min(r/s,i/n);return{width:s*o,height:n*o}}const CR=({vertical:e,width:t,height:r,count:i,aspectRatio:n})=>{const s=[1,2,3].map((s=>(({width:e,height:t,rows:r,cols:i,aspectRatio:n})=>{const s=SR(n,{width:e/i,height:t/r});return Math.round(s.width*s.height)})({width:t,height:r,rows:e?Math.ceil(i/s):s,cols:e?s:Math.ceil(i/s),aspectRatio:n}))),o=Math.max(...s);return{splits:s.indexOf(o)+1,weight:o}},RR=({width:e,height:t,count:r,aspectRatio:i})=>{const n=CR({vertical:!0,width:e,height:t,count:r,aspectRatio:i}),s=CR({vertical:!1,width:e,height:t,count:r,aspectRatio:i});return n.weight>s.weight?{splits:n.splits,vertical:!0}:{splits:s.splits,vertical:!1}};function kR(e){var{aspectRatio:t,children:r,className:i,height:n,style:o,width:a,withRoundedCorners:c=!1,withShadow:d=!0}=e,l=dR(e,["aspectRatio","children","className","height","style","width","withRoundedCorners","withShadow"]);let u=a,p=n,h=0,f=0;t&&(({width:u,height:p}=SR(t,{width:a,height:n})),h=(a-u)/2,f=(n-p)/2);const m=Object.assign({width:`${Math.round(u)}px`,height:`${Math.round(p)}px`},h||f?{transform:`translate3d(${Math.round(h)}px, ${Math.round(f)}px, 0)`}:{});return s.createElement("div",{className:i,style:Object.assign({position:"absolute",top:0,left:0},o)},s.createElement("div",Object.assign({style:m},l),s.cloneElement(r,{contentWidth:u,contentHeight:p,withRoundedCorners:c,withShadow:d})))}function TR({origin:e,bounds:t}){return{top:Math.round(e.top),left:Math.round(e.left),height:Math.round(t.height),width:Math.round(t.width)}}function PR({cell:e,child:t,clientId:r,style:i={},withRoundedCorners:n=!1,withShadow:o=!1}){const a=!_R(e.bounds);return s.createElement(kR,{width:e.bounds.width,height:e.bounds.height,aspectRatio:e.aspectRatio,style:a?{width:0,height:0}:i,withRoundedCorners:n,withShadow:o,key:r},t)}function OR({containerFrame:e,debug:t=!1,featureRoundedCornersOff:r=!1,floatingContent:i,gridContent:n=[],isConstrained:o=!1,layoutOverflowBackdropFrame:a=yR(),layoutVideoStage:c,presentationGridContent:d=[],subgridContent:l=[]}){const u=!r&&!o,p=[];return n.length&&p.push(...function({content:e,isConstrained:t,stageLayout:r,withRoundedCorners:i,withShadow:n}){var o;const a=(null===(o=r.videoGrid)||void 0===o?void 0:o.cells)||[],c=e.map(((e,o)=>{var c,d;if(!r.videoGrid)return null;const l=a[o],u={top:r.videoGrid.origin.top+r.videoGrid.paddings.top+l.origin.top,left:r.videoGrid.origin.left+r.videoGrid.paddings.left+l.origin.left},p={width:Math.round(l.bounds.width),height:Math.round(l.bounds.height),transform:`translate3d(${Math.round(u.left)}px, ${Math.round(u.top)}px, 0)`},h=null===(d=null===(c=null==e?void 0:e.props)||void 0===c?void 0:c.participant)||void 0===d?void 0:d.id;return PR({cell:l,child:s.cloneElement(e,{isSmallCell:l.isSmallCell,isZoomedByDefault:!!t&&!(null==e?void 0:e.props.participant.isPresentation),canZoom:!!t,key:h||`video-${o}`}),clientId:h||`video-${o}`,withRoundedCorners:i,style:p,withShadow:n})}));return c}({content:n,isConstrained:o,stageLayout:c,withRoundedCorners:u,withShadow:!o})),d.length&&p.push(...function({content:e,isConstrained:t,stageLayout:r,withRoundedCorners:i,withShadow:n}){var o;const a=(null===(o=r.presentationGrid)||void 0===o?void 0:o.cells)||[];return e.map(((e,o)=>{var c,d;if(!r.presentationGrid)return null;const l=a[o],u={top:r.presentationGrid.origin.top+r.presentationGrid.paddings.top+l.origin.top,left:r.presentationGrid.origin.left+r.presentationGrid.paddings.left+l.origin.left},p={width:Math.round(l.bounds.width),height:Math.round(l.bounds.height),transform:`translate3d(${Math.round(u.left)}px, ${Math.round(u.top)}px, 0)`},h=null===(d=null===(c=null==e?void 0:e.props)||void 0===c?void 0:c.participant)||void 0===d?void 0:d.id;return PR({cell:l,child:s.cloneElement(e,{isSmallCell:l.isSmallCell,isZoomedByDefault:!!t&&!(null==e?void 0:e.props.participant.isPresentation),canZoom:!!t,key:h||`presentation-${o}`}),clientId:h||`presentation-${o}`,style:p,withRoundedCorners:i,withShadow:n})}))}({content:d,isConstrained:o,stageLayout:c,withRoundedCorners:u,withShadow:!o})),i&&p.push(function({content:e,containerFrame:t,stageLayout:r,withRoundedCorners:i}){var n;if(!r.floatingContent)return null;const o=r.floatingContent,a=o.origin.top,c=o.origin.left,d={width:Math.round(o.bounds.width),height:Math.round(o.bounds.height),transform:`translate3d(${Math.round(t.origin.left+c)}px, ${Math.round(t.origin.top+a)}px, 0)`,position:"fixed",top:o.bounds.height/2,left:0,zIndex:40},l=(null===(n=e.props.client)||void 0===n?void 0:n.id)||"floating";return PR({cell:o,child:s.cloneElement(e,{isSmallCell:o.isSmallCell,isZoomedByDefault:!1,canZoom:!1,key:l,isDraggable:!1}),clientId:l,style:d,withRoundedCorners:i,withShadow:!1})}({content:i,containerFrame:e,stageLayout:c,withRoundedCorners:!r})),l.length&&p.push(...function({content:e,stageLayout:t,withRoundedCorners:r,withShadow:i}){const n=t.subgrid.cells;return e.map(((e,o)=>{var a,c,d,l;const u=n[o],p={height:Math.round(u.bounds.height),width:Math.round(u.bounds.width),transform:""},h={top:t.subgrid.origin.top+u.origin.top,left:t.subgrid.origin.left+u.origin.left};p.transform=`translate3d(${Math.round(h.left)}px, ${Math.round(h.top)}px, 0)`;const f=null===(c=null===(a=null==e?void 0:e.props)||void 0===a?void 0:a.participant)||void 0===c?void 0:c.id,m=(null===(d=u.paddings)||void 0===d?void 0:d.left)||0,g=(null===(l=u.paddings)||void 0===l?void 0:l.right)||0;return PR({cell:u,child:s.cloneElement(e,{avatarSize:u.bounds.width-m-g,canZoom:!1,cellPaddings:u.paddings,isSmallCell:u.isSmallCell,isZoomedByDefault:!1,key:f||`subgrid-${o}`,style:p}),clientId:f||`subgrid-${o}`,style:p,withRoundedCorners:r,withShadow:i})}))}({content:l,stageLayout:c,withRoundedCorners:!r,withShadow:!0})),s.createElement("div",{key:"video-stage-layout",style:{width:"100%",height:"100%",position:"relative"}},_R(a.bounds)&&s.createElement("div",{style:TR(a)}),p,t&&s.createElement(s.Fragment,null))}const ER=16/9,DR=4/3,IR=({value:e,min:t,max:r})=>Math.min(Math.max(e,t),r);function xR({choices:e=[]}){const t=Math.min(...e),r=Math.max(...e);let i=null;if(t===r)i=t;else{const t=function(...e){return new Set(e).size!==e.length}(e)?(n=e).sort(((e,t)=>n.filter((t=>t===e)).length-n.filter((e=>e===t)).length)).pop():r;i=IR({value:t||r,min:DR,max:ER})}var n;return{minAr:t,maxAr:r,chosenAr:i}}function MR({width:e,height:t,cellCount:r,gridGap:i,cellAspectRatios:n=[DR],paddings:s=wR()}){if(!r)return{cellCount:r,cellHeight:0,cellWidth:0,cols:0,rows:0,extraHorizontalPadding:0,extraVerticalPadding:0,gridGap:i,paddings:s};const o=e-(s.left+s.right),a=t-(s.top+s.bottom),c=xR({choices:n});let d=c.chosenAr;const{rows:l,cols:u}=function({count:e,width:t,height:r,aspectRatio:i}){if(e<=1)return{rows:1,cols:1};const{splits:n,vertical:s}=RR({width:t,height:r,count:e,aspectRatio:i});return s?{rows:Math.ceil(e/n),cols:n}:{rows:n,cols:Math.ceil(e/n)}}({count:r,width:o,height:a,aspectRatio:d});1===l?d=IR({value:o/u/a,min:Math.min(c.chosenAr,c.maxAr),max:Math.max(c.chosenAr,c.maxAr)}):1===u&&(d=IR({value:o/(a/l),min:Math.min(c.chosenAr,c.maxAr),max:Math.max(c.chosenAr,c.maxAr)}));const{cellWidth:p,cellHeight:h,extraHorizontalPadding:f,extraVerticalPadding:m}=function({width:e,height:t,rows:r,cols:i,gridGap:n,aspectRatio:s}){const o=(e-(i-1)*n)/i,a=(t-(r-1)*n)/r,c=o/a;let d=0,l=0;return s<c?d=o-a*s:s>c&&(l=a-o/s),{cellWidth:o-d,cellHeight:a-l,extraHorizontalPadding:d*i/2,extraVerticalPadding:l*r/2}}({width:o,height:a,rows:l,cols:u,gridGap:i,aspectRatio:d});return{cellCount:r,cellHeight:h,cellWidth:p,cols:u,rows:l,extraHorizontalPadding:f,extraVerticalPadding:m,gridGap:i,paddings:s}}const jR="rows",LR="columns";function AR({layoutGrid:e,dim:t,secDim:r,index:i,count:n,gridGap:s}){const o=(t-s*(n-1))*(e.fractions?e.fractions[i]:1/n),a=e.lines[i];return[o,(r-s*(a-1))/a]}function NR({isHorizontal:e,layoutGrid:t,width:r,height:i,gridGap:n}){const s=[],o=0,a=0,c={x:0,y:0},d=t.lines.length,l=e?i:r,u=e?r:i;for(let r=0;r<d;r++){const i=AR({layoutGrid:t,dim:l,secDim:u,index:r,count:d,gridGap:n}),p={width:e?i[1]:i[0],height:e?i[0]:i[1]},h=t.lines[r];for(let t=0;t<h;t++)s.push({origin:Object.assign({},c),bounds:p}),e?c.x+=p.width+n:c.y+=p.height+n;e?(c.y+=p.height+n,c.x=o):(c.x+=p.width+n,c.y=a)}return s}function BR({layoutGrid:e,width:t,height:r,gridGap:i}){switch(e.type){case jR:return function({layoutGrid:e,width:t,height:r,gridGap:i}){return NR({isHorizontal:!0,layoutGrid:e,width:t,height:r,gridGap:i})}({layoutGrid:e,width:t,height:r,gridGap:i});case LR:return function({layoutGrid:e,width:t,height:r,gridGap:i}){return NR({isHorizontal:!1,layoutGrid:e,width:t,height:r,gridGap:i})}({layoutGrid:e,width:t,height:r,gridGap:i})}}function FR({width:e,height:t,cellCount:r,gridGap:i=0,paddings:n=wR()}){const s=e-(n.left+n.right),o=t-(n.top+n.bottom);return{cellRects:BR({layoutGrid:Math.round(s/o*10)/10<=1?{1:{type:jR,lines:[1]},2:{type:jR,lines:[1,1]},3:{type:jR,lines:[2,1]},4:{type:jR,lines:[2,2]},5:{type:jR,lines:[2,2,1]},6:{type:jR,lines:[2,2,2]},7:{type:jR,lines:[3,2,2]},8:{type:jR,lines:[2,2,2,2]},9:{type:jR,lines:[3,2,2,2]},10:{type:jR,lines:[3,3,2,2]},11:{type:jR,lines:[3,3,3,2]},12:{type:jR,lines:[3,3,3,3]},13:{type:jR,lines:[2,2,3,3,3]},14:{type:jR,lines:[2,3,3,3,3]},15:{type:jR,lines:[3,3,3,3,3]},16:{type:jR,lines:[2,2,3,3,3,3]},17:{type:jR,lines:[2,3,3,3,3,3]},18:{type:jR,lines:[3,3,3,3,3,3]},19:{type:jR,lines:[2,2,3,3,3,3,3]},20:{type:jR,lines:[2,3,3,3,3,3,3]},21:{type:jR,lines:[3,3,3,3,3,3,3]},22:{type:jR,lines:[2,2,3,3,3,3,3,3]},23:{type:jR,lines:[2,3,3,3,3,3,3,3]},24:{type:jR,lines:[3,3,3,3,3,3,3,3]}}[r]||{type:jR,lines:[3,3,3,3,3,3,3,3]}:function(e){return{1:{type:LR,lines:[1]},2:{type:LR,lines:[1,1]},3:{type:LR,lines:[2,1]},4:{type:LR,lines:[2,2]},5:{type:jR,lines:[3,2],fractions:[.45,.55]},6:{type:LR,lines:[2,2,2]},7:{type:jR,lines:[4,3],fractions:[.45,.55]},8:{type:LR,lines:[2,2,2,2]},9:{type:LR,lines:[3,2,2,2]},10:{type:LR,lines:[3,3,2,2]},11:{type:LR,lines:[3,3,3,2]},12:{type:LR,lines:[3,3,3,3]},13:{type:LR,lines:[4,3,3,3]},14:{type:LR,lines:[4,4,3,3]},15:{type:LR,lines:[3,3,3,3,3]},16:{type:LR,lines:[4,3,3,3,3]},17:{type:LR,lines:[4,4,3,3,3]},18:{type:LR,lines:[4,4,4,3,3]},19:{type:LR,lines:[4,4,4,4,3]},20:{type:LR,lines:[4,4,4,4,4]},21:{type:LR,lines:[5,4,4,4,4]},22:{type:LR,lines:[5,5,4,4,4]},23:{type:LR,lines:[5,5,5,4,4]},24:{type:LR,lines:[5,5,5,5,4]}}[e]||{type:LR,lines:[5,5,5,5,5]}}(r),width:s,height:o,gridGap:i})||[],cellCount:r,gridGap:i,extraHorizontalPadding:0,extraVerticalPadding:0,paddings:n}}function zR({containerBounds:e,isPortrait:t,cellCount:r,cellBounds:i,paddings:n=wR()}){let s=0,o=0,a=0,c=0,d=0,l=0;const u=e.width-n.left-n.right,p=e.height-n.top-n.bottom;return r&&(t?(c=Math.floor(u/i.width),a=Math.ceil(r/c),s=u,o=a*i.height,d=(u-c*i.width)/2):(a=Math.floor(p/i.height),c=Math.ceil(r/a),s=c*i.width,o=p,l=(p-a*i.height)/2)),{isPortrait:t,width:s+n.left+n.right,height:o+n.top+n.bottom,cellBounds:i,cellCount:r,rows:a,cols:c,extraHorizontalPadding:d,extraVerticalPadding:l,paddings:n}}const{BOTTOM_TOOLBAR_HEIGHT:VR,VIDEO_CONTROLS_MIN_WIDTH:UR,TABLET_BREAKPOINT:$R,SUBGRID_EMPTY_STAGE_MAX_WIDTH:GR}=gR,qR=200,HR=300,WR=200,KR=20,JR=12,XR=wR({top:4,bottom:28,left:8,right:8});function QR({hasOverflow:e,hasStage:t}){return e&&t?[80]:[80,60]}function ZR({cellCount:e}){const t=e<=6;return bR({width:t?HR-50:HR,height:t?qR-50:qR})}function YR({containerBounds:e,isPortrait:t,cellCount:r,cellSizeOptions:i,cellPaddings:n,paddings:s}){const o=function({containerBounds:e,isPortrait:t,cellCount:r,cellSizeOptions:i,cellPaddings:n,paddings:s}){let o;for(let a=0;a<i.length;a++){const c=i[a];if(o=zR({containerBounds:e,isPortrait:t,cellCount:r,cellBounds:bR({width:c+n.left+n.right,height:c+n.top+n.bottom}),paddings:s}),o.width<=e.width&&o.height<=e.height)return o}return o}({containerBounds:e,isPortrait:t,cellCount:r,cellSizeOptions:i,cellPaddings:n,paddings:s}),a=o.cellBounds.width-n.left-n.right===i[i.length-1],c=bR({width:Math.min(o.width,e.width),height:Math.min(o.height,e.height)}),d=bR({width:o.width,height:o.height});return 0===r?{bounds:c,contentBounds:d,videoCells:[]}:{bounds:c,contentBounds:d,videoCells:[...Array(r)].map(((e,t)=>{const{top:r,left:i,width:s,height:c}=function({index:e,layout:t}){const{isPortrait:r,rows:i,cols:n,cellCount:s,cellBounds:o,extraHorizontalPadding:a,extraVerticalPadding:c,paddings:d}=t,l=r?Math.floor(e/n):Math.floor(e%i),u=r?Math.floor(e%n):Math.floor(e/i),p=function({index:e,isPortrait:t,rows:r,cols:i,cellBounds:n,cellCount:s}){const o=r*i,a=o-s;if(!a)return 0;const c=o-a-1;return e<c-((t?i:r)-a)+1||e>c?0:a*(t?n.width:n.height)/2}({index:e,isPortrait:r,rows:i,cols:n,cellBounds:o,cellCount:s});return{top:d.top+c+l*o.height+(r?0:p),left:d.left+a+u*o.width+(r?p:0),width:o.width,height:o.height}}({index:t,layout:o});return{origin:vR({top:r,left:i}),bounds:bR({width:s,height:c}),paddings:n,isSmallCell:a}}))}}function ek({cellPaddings:e,cellSizeOptions:t,containerBounds:r,containerOrigin:i,gridGap:n,hasConstrainedOverflow:s,hasPresentationContent:o,hasVideoContent:a,isConstrained:c,isMaximizeMode:d,isPortrait:l,isSmallScreen:u,maxGridWidth:p,shouldOverflowSubgrid:h,subgridVideos:f}){const{width:m,height:g}=r,v=o||a,b=f.length>0;if(!b&&!v)return{isPortrait:l,videosContainer:yR(),subgrid:Object.assign(Object.assign({},yR()),{contentBounds:bR(),cells:[]}),hasOverflow:!1};if(!b)return{isPortrait:l,videosContainer:yR(Object.assign(Object.assign({},r),i)),subgrid:Object.assign(Object.assign({},yR()),{contentBounds:bR(),cells:[]}),hasOverflow:s};const y=h?KR:0;let w=null;if(v)if(h){const i=t[0];let n=d?VR:VR+e.top+(c||u?i/2:i)+e.bottom;r.height-n<qR&&(n=0),w=bR({width:r.width,height:n})}else w=bR(d?{width:r.width,height:t[0]+e.top+e.bottom}:l?{width:r.width,height:r.height/2}:{width:r.width/2,height:r.height});else w=bR({width:Math.min(GR,r.width),height:r.height});let _=0;w.width>p&&(_=(w.width-p)/2);const S=YR({containerBounds:w,isPortrait:l,cellCount:f.length,cellSizeOptions:t,cellPaddings:e,paddings:wR({top:y,left:_,right:_})}),C=bR({width:S.contentBounds.width-w.width,height:S.contentBounds.height-w.height}),R=C.width>0||C.height>0;let k,T=null;T=!v||h||R?S.contentBounds:S.bounds;let P=T;v?(P=bR(h?{width:0,height:w.height+y+n}:l?{width:0,height:S.bounds.height+n}:{width:S.bounds.width+n,height:0}),k=function({bounds:e,fromBounds:t}){return{width:Math.max(t.width-e.width,0),height:Math.max(t.height-e.height,0)}}({bounds:P,fromBounds:r})):k=bR();const O=Object.assign({},i);let E;return E=vR(v?{top:l?Math.max(i.top+g-P.height+n,0):i.top,left:l?i.left:Math.max(i.left+m-T.width,0)}:{top:i.top+Math.max(0,(g-T.height)/2),left:i.left+Math.max(0,(m-T.width)/2)}),{isPortrait:l,videosContainer:yR(Object.assign(Object.assign({},k),O)),subgrid:Object.assign(Object.assign({},yR(Object.assign(Object.assign({},T),E))),{cells:S.videoCells.map(((e,t)=>{var r,i;return Object.assign({aspectRatio:(null===(r=f[t])||void 0===r?void 0:r.aspectRatio)||1,type:"video",clientId:null===(i=f[t])||void 0===i?void 0:i.clientId},e)})),contentBounds:S.contentBounds}),hasOverflow:R||h||s,overflowNeedBounds:h?bR():C}}function tk({containerBounds:e,containerOrigin:t,gridGap:r,supersizedContentAspectRatio:i,hasPresentationContent:n,hasPresentationGrid:s,hasVideoContent:o,minGridBounds:a}){const{width:c,height:d}=e;let l=c<=d,u=bR(),p=vR(),h=o?Object.assign({},e):bR(),f=o?Object.assign({},t):vR();if(n){const n=function({bounds:e,aspectRatio:t,minGridContainerBounds:r,hasPresentationGrid:i}){const{width:n,height:s}=e;if(!(r.width>0))return{isPortrait:n<=s,supersizedContentBounds:e};const o=Math.round(n/2),a=Math.round(s/2),c=Math.max(n-r.width,0),d=Math.max(s-r.height,0);let l=c<=d,u=0,p=0;if(t){const e=SR(t,{width:c,height:s}),r=SR(t,{width:n,height:d});if(l=t<=1?r.height>e.height:r.width>e.width,l){const e=d-Math.max(r.height,a);p=Math.max(e,0)}else{const t=c-Math.max(e.width,o);u=Math.max(t,0)}}else i&&(l=c/d>=5);return{isPortrait:l,supersizedContentBounds:{width:l?n:c-u,height:l?d-p:s}}}({bounds:e,aspectRatio:i||1,minGridContainerBounds:bR({width:o?a.width+r:0,height:o?a.height+r:0}),hasPresentationGrid:s});l=n.isPortrait,u=n.supersizedContentBounds,p=Object.assign({},t),o&&(h=bR({width:l?e.width:e.width-u.width-r,height:l?e.height-u.height-r:e.height}),f=vR({top:l?t.top+u.height+r:t.top,left:l?t.left:t.left+u.width+r}))}return{isPortrait:l,presentationGrid:Object.assign({},yR(Object.assign(Object.assign({},u),p))),videoGrid:yR(Object.assign(Object.assign({},h),f))}}function rk({containerBounds:e,paddings:t=wR(),videos:r,isConstrained:i,maxGridWidth:n,gridGap:s}){const{width:o,height:a}=e,c=n?Math.min(o,n):o,d=r.length;let l=null,u=null;if(i){const e=FR({width:o,height:a,cellCount:d,gridGap:s,paddings:t}),i=d>4;u=r.map(((t,r)=>{const n=function({index:e,layout:t}){const{cellRects:r}=t,i=r[e]||yR();return{top:i.origin.y,left:i.origin.x,width:i.bounds.width,height:i.bounds.height}}({index:r,layout:e});return{clientId:t.clientId,isDraggable:t.isDraggable,origin:vR({top:n.top,left:n.left}),bounds:bR({width:n.width,height:n.height}),aspectRatio:n.width/n.height,isSmallCell:i,type:"video"}})),l=e}else{const e=r.map((e=>e.aspectRatio||1)),n=ZR({cellCount:d}),o=MR({width:c,height:a,cellCount:d,gridGap:s,cellAspectRatios:e,paddings:t});u=r.map(((e,t)=>{const r=function({index:e,layout:t}){const{cellWidth:r,cellHeight:i,rows:n,cols:s,cellCount:o,gridGap:a}=t,c=Math.floor(e/s),d=Math.floor(e%s),l=function({rows:e,cols:t,cellWidth:r,index:i,cellCount:n,gridGap:s}){const o=e*t,a=o-n;if(!a)return 0;const c=o-a-1;return i>=c-(t-a)+1&&i<=c?a*r/2+s:0}({rows:n,cols:s,cellWidth:r,index:e,cellCount:o,gridGap:a});return{top:c*i+c*a,left:d*r+d*a+l,width:r,height:i}}({index:t,layout:o}),s=o.cellWidth<n.width,a=i||s?o.cellWidth/o.cellHeight:e.aspectRatio||1;return{clientId:e.clientId,isDraggable:e.isDraggable,origin:vR({top:r.top,left:r.left}),bounds:bR({width:r.width,height:r.height}),aspectRatio:a,isSmallCell:s,type:"video"}})),l=o}return{videoCells:u,extraHorizontalPadding:o!==c?l.extraHorizontalPadding+(o-c)/2:l.extraHorizontalPadding,extraVerticalPadding:l.extraVerticalPadding,paddings:l.paddings,gridGap:s}}function ik({a:e,b:t,gridGap:r,isPortrait:i}){const n=i?e.vertical:e.horizontal,s=i?t.vertical:t.horizontal;if(n===s)return{a:0,b:0};const o=n<s?e:t,a=i?o.vertical:o.horizontal,c=(r+(n+s)+a)/2-a;return{a:o===e?c:0,b:o===t?c:0}}function nk({gridGap:e,isConstrained:t,presentationVideos:r,videos:i,videosContainerLayout:n,gridLayoutPaddings:s=wR(),presentationGridLayoutPaddings:o=wR(),maxGridWidth:a}){return{gridLayout:rk({containerBounds:n.videoGrid.bounds,gridGap:e,isConstrained:t,maxGridWidth:a,paddings:s,videos:i}),presentationGridLayout:rk({containerBounds:n.presentationGrid.bounds,gridGap:e,isConstrained:t,maxGridWidth:a,paddings:o,videos:r})}}function sk({floatingVideo:e,frame:t,gridGap:r,isConstrained:i,isMaximizeMode:n=!1,isXLMeetingSize:s=!1,paddings:o=wR(),presentationVideos:a=[],rebalanceLayout:c=!1,roomBounds:d,roomLayoutHasOverlow:l=!1,subgridCellPaddings:u=XR,subgridVideos:p=[],videoControlsHeight:h=0,videos:f=[],videoGridGap:m}){let g=s&&(!screen||screen.width<=2048);const v=!!a.length,b=a.length>1,y=v&&!b?a[0].aspectRatio:null,w=!!f.length,_=t.bounds.width-o.left-o.right;let S=t.bounds.height-o.top-o.bottom;const C=Math.max(2200,.8*_),R=i&&f.length>JR,k=S/4,T=Math.ceil((f.length-JR)/3);S=R?S+k*T:S;const P=bR({width:_,height:S}),O=vR({top:o.top,left:o.left}),E=ZR({cellCount:f.length}),D=d.width<$R||d.height<$R,I=n||g||!(v||w)||P.width<=P.height,x={cellPaddings:u,containerBounds:P,containerOrigin:O,gridGap:r,hasPresentationContent:v,hasVideoContent:w,isConstrained:i,isMaximizeMode:n,isSmallScreen:D,subgridVideos:p,maxGridWidth:C};let M=ek(Object.assign(Object.assign({},x),{cellSizeOptions:QR({hasOverflow:g,hasStage:v||w}),isPortrait:I,shouldOverflowSubgrid:g,hasConstrainedOverflow:R})),j=!1;if(!g&&l&&!M.hasOverflow){ek(Object.assign(Object.assign({},x),{containerBounds:bR({width:P.width,height:P.height-VR}),cellSizeOptions:QR({hasOverflow:g,hasStage:v||w}),isPortrait:I,shouldOverflowSubgrid:g,hasConstrainedOverflow:R})).hasOverflow&&(j=!0)}(j||M.hasOverflow&&!g)&&(g=!0,M=ek(Object.assign(Object.assign({},x),{cellSizeOptions:QR({hasOverflow:!0,hasStage:v||w}),isPortrait:!0,shouldOverflowSubgrid:g,hasConstrainedOverflow:R})));const L=tk({containerBounds:M.videosContainer.bounds,containerOrigin:M.videosContainer.origin,gridGap:r,supersizedContentAspectRatio:y||1,hasPresentationContent:v,hasPresentationGrid:b,hasVideoContent:w,minGridBounds:E});let{gridLayout:A,presentationGridLayout:N}=nk({gridGap:m||r,isConstrained:i,presentationVideos:a,videos:f,videosContainerLayout:L,maxGridWidth:C});if(M.hasOverflow&&!g){const{vPaddings:e,hPaddings:t}=function({need:e,stageLayout:t,gridLayout:r,presentationGridLayout:i,videosContainerLayout:n}){let s={presentationGrid:0,grid:0},o={presentationGrid:0,grid:0};if(t.isPortrait){const t=Math.min(r.extraVerticalPadding,i.extraVerticalPadding);s={presentationGrid:Math.min(n.isPortrait?i.extraVerticalPadding:t,e.height),grid:Math.min(n.isPortrait?r.extraVerticalPadding:t,e.height)}}else{const t=Math.min(r.extraHorizontalPadding,i.extraHorizontalPadding);o={presentationGrid:Math.min(n.isPortrait?t:i.extraHorizontalPadding,e.width),grid:Math.min(n.isPortrait?t:r.extraHorizontalPadding,e.width)}}return{vPaddings:s,hPaddings:o}}({need:M.overflowNeedBounds||bR(),stageLayout:M,gridLayout:A,presentationGridLayout:N,videosContainerLayout:L});(e.presentationGrid||e.grid||t.presentationGrid||t.grid)&&(!function({vPaddings:e,hPaddings:t,stageLayout:r,videosContainerLayout:i}){if(r.isPortrait&&(e.presentationGrid||e.grid)){const t=i.isPortrait?2*e.presentationGrid+2*e.grid:e.presentationGrid+e.grid;r.videosContainer.bounds.height-=t,r.subgrid.origin.top-=t,r.subgrid.bounds.height+=t,i.presentationGrid.bounds.height-=2*e.presentationGrid,i.videoGrid.bounds.height-=2*e.grid,i.isPortrait&&(i.videoGrid.origin.top-=e.presentationGrid)}if(!r.isPortrait&&(t.presentationGrid||t.grid)){const e=i.isPortrait?t.presentationGrid+t.grid:2*t.presentationGrid+2*t.grid;r.videosContainer.bounds.width-=e,r.subgrid.origin.left-=e,r.subgrid.bounds.width+=e,i.presentationGrid.bounds.width-=2*t.presentationGrid,i.videoGrid.bounds.width-=2*t.grid,i.isPortrait||(i.videoGrid.origin.left-=t.grid)}}({vPaddings:e,hPaddings:t,stageLayout:M,videosContainerLayout:L}),({gridLayout:A,presentationGridLayout:N}=nk({gridGap:m||r,isConstrained:i,presentationVideos:a,videos:f,videosContainerLayout:L,maxGridWidth:C})))}const B=function({roomBounds:e,containerFrame:t,floatingVideo:r,videoControlsHeight:i,margin:n=8}){if(!r)return null;const s=SR(r.aspectRatio||0,{width:WR,height:WR}),o=!(e.height-t.bounds.height-t.origin.top),a=t.bounds.width-2*(s.width+n)<UR;let c=0;o&&a?c=-1*i:o||a||(c=i);const d=vR({top:t.origin.top+(t.bounds.height-s.height-n)+c,left:t.origin.left+(t.bounds.width-s.width-n)});return{clientId:r.clientId,isDraggable:r.isDraggable,origin:d,bounds:s,aspectRatio:r.aspectRatio,isSmallCell:!0}}({roomBounds:d,containerFrame:t,floatingVideo:e||null,videoControlsHeight:h});c&&function({videosContainerLayout:e,gridLayout:t,presentationGridLayout:r,stageLayout:i,gridGap:n,shouldOverflowSubgrid:s}){const o=e.presentationGrid.bounds.width>0,a=e.videoGrid.bounds.width>0,c=i.subgrid.bounds.width>0,d={vertical:0,horizontal:0};if(o&&a){const i=ik({a:{horizontal:r.extraHorizontalPadding,vertical:r.extraVerticalPadding},b:{horizontal:t.extraHorizontalPadding,vertical:t.extraVerticalPadding},gridGap:n,isPortrait:e.isPortrait});e.isPortrait?(e.presentationGrid.origin.top+=i.a,e.videoGrid.origin.top-=i.b,d.vertical=i.b):(e.presentationGrid.origin.left+=i.a,e.videoGrid.origin.left-=i.b,d.horizontal=i.b)}if(c&&(o||a)&&!s){const s={horizontal:r.extraHorizontalPadding,vertical:r.extraVerticalPadding},c={horizontal:t.extraHorizontalPadding+d.horizontal,vertical:t.extraVerticalPadding+d.vertical};let l;const u=o&&a;l=u&&e.isPortrait&&!i.isPortrait?s.horizontal<c.horizontal?s:c:u&&!e.isPortrait&&i.isPortrait?s.vertical<c.vertical?s:c:a?c:s;const p=ik({a:l,b:{horizontal:0,vertical:0},gridGap:n,isPortrait:i.isPortrait});i.isPortrait?i.subgrid.origin.top-=p.b:i.subgrid.origin.left-=p.b}}({videosContainerLayout:L,gridLayout:A,presentationGridLayout:N,stageLayout:M,gridGap:r,shouldOverflowSubgrid:g});let F=o.top+M.videosContainer.bounds.height+M.subgrid.bounds.height+o.bottom;return(v||w)&&(F+=r),{isPortrait:M.isPortrait,hasOverflow:M.hasOverflow,videosContainer:Object.assign(Object.assign({},L),{bounds:bR({width:M.videosContainer.bounds.width,height:M.videosContainer.bounds.height}),origin:vR({top:M.videosContainer.origin.top,left:M.videosContainer.origin.left})}),bounds:bR({height:g?F:t.bounds.height,width:t.bounds.width}),gridGap:r,presentationGrid:Object.assign(Object.assign({},L.presentationGrid),{cells:N.videoCells,paddings:wR({top:N.paddings.top+N.extraVerticalPadding,bottom:N.paddings.bottom+N.extraVerticalPadding,left:N.paddings.left+N.extraHorizontalPadding,right:N.paddings.right+N.extraHorizontalPadding})}),videoGrid:Object.assign(Object.assign({},L.videoGrid),{cells:A.videoCells,paddings:wR({top:A.paddings.top+A.extraVerticalPadding,bottom:A.paddings.bottom+A.extraVerticalPadding,left:A.paddings.left+A.extraHorizontalPadding,right:A.paddings.right+A.extraHorizontalPadding})}),subgrid:M.subgrid,floatingContent:Object.assign(Object.assign(Object.assign({},B),e),{origin:(null==B?void 0:B.origin)||vR(),bounds:(null==B?void 0:B.bounds)||bR(),aspectRatio:(null==e?void 0:e.aspectRatio)||1})}}function ok({aspectRatio:e,avatarSize:t,cellPaddings:r,client:i,isDraggable:n=!0,isPlaceholder:s=!1,isSubgrid:o=!1}){return{aspectRatio:e||16/9,avatarSize:t,cellPaddings:r,client:i,clientId:(null==i?void 0:i.id)||"",isDraggable:n,isPlaceholder:s,isSubgrid:o,type:"video"}}const ak=12,ck=12,dk=24;function lk({activeVideosSubgridTrigger:e=ck,stageParticipantLimit:t=ak,forceSubgrid:r=!0,enableSubgrid:i=!0,maximizedParticipant:n,floatingParticipant:o,isConstrained:a=!1}={}){const c=uR(eS),d=uR(uS),l=uR(V_),u=s.useMemo((()=>o),[o]),p=s.useMemo((()=>u?c.filter((e=>e.id!==u.id)):c),[c,u]),h=s.useMemo((()=>!!i&&(!!r||l>t)),[r,l,t,i]),f=s.useMemo((()=>function({clientViews:e,activeVideosSubgridTrigger:t,shouldShowSubgrid:r,spotlightedParticipants:i,maximizedParticipant:n,isPhoneResolution:s}){if(!r)return[];const o=i.length>0,a=(n?e.filter((e=>e.id!==n.id)):e).filter((e=>!e.isPresentation&&!i.includes(e))),c=a.filter((e=>!e.isVideoEnabled)),d=a.filter((e=>e.isVideoEnabled)).length>t,l=a.filter((e=>!c.includes(e)&&e.isAudioEnabled)),u=a.filter((e=>!c.includes(e)&&!e.isAudioEnabled));if(c.length&&o)return[...u,...c];if(s&&a.length>dk){const e=[...l,...u],t=e.slice(0,dk);return t.length<=dk?[...e.filter((e=>!t.includes(e))),...c]:[...u,...c]}if(d&&u.length){const e=[...l,...u].slice(0,t);return e.length<=t?[...u.filter((t=>!e.includes(t))),...c]:[...u,...c]}return c}({clientViews:p,activeVideosSubgridTrigger:e,shouldShowSubgrid:h,spotlightedParticipants:d,maximizedParticipant:n,isPhoneResolution:a})),[p,h,e,d,a]),m=s.useMemo((()=>p.filter((e=>!f.includes(e)))),[p,f]),g=s.useMemo((()=>n?[n]:d),[d,n]),v=s.useMemo((()=>m.filter((e=>!g.includes(e)))),[m,g]);return{floatingClientView:u,clientViewsInGrid:v,clientViewsInPresentationGrid:g,clientViewsInSubgrid:f}}var uk={exports:{}};const pk=55296,hk=56319,fk=56320,mk=127462,gk=127487,vk=127995,bk=127999,yk=65024,wk=65039,_k=8400,Sk=8447,Ck=8205,Rk=[776,2359,2359,2367,2367,2984,3007,3021,3633,3635,3648,3657,4352,4449,4520];function kk(e){if("string"!=typeof e)throw new Error("string cannot be undefined or null");const t=[];let r=0,i=0;for(;r<e.length;)i+=Tk(r+i,e),Dk(e[r+i])&&i++,Ok(e[r+i])&&i++,Ek(e[r+i])&&i++,Ik(e[r+i])?i++:(t.push(e.substring(r,r+i)),r+=i,i=0);return t}function Tk(e,t){const r=t[e];if(!function(e){return e&&Mk(e[0].charCodeAt(0),pk,hk)}(r)||e===t.length-1)return 1;const i=r+t[e+1];let n=t.substring(e+2,e+5);return Pk(i)&&Pk(n)||function(e){return Mk(xk(e),vk,bk)}(n)?4:2}function Pk(e){return Mk(xk(e),mk,gk)}function Ok(e){return"string"==typeof e&&Mk(e.charCodeAt(0),yk,wk)}function Ek(e){return"string"==typeof e&&Mk(e.charCodeAt(0),_k,Sk)}function Dk(e){return"string"==typeof e&&-1!==Rk.indexOf(e.charCodeAt(0))}function Ik(e){return"string"==typeof e&&e.charCodeAt(0)===Ck}function xk(e){return(e.charCodeAt(0)-pk<<10)+(e.charCodeAt(1)-fk)+65536}function Mk(e,t,r){return e>=t&&e<=r}uk.exports=kk,uk.exports.substr=function(e,t,r){const i=kk(e);if(void 0===t)return e;if(t>=i.length)return"";const n=i.length-t;let s=t+(void 0===r?n:r);return s>t+n&&(s=void 0),i.slice(t,s).join("")};var jk=c(uk.exports);const Lk=({name:e})=>{const t=((e="")=>{if(e=e.trim())return e.split(/-| /).map((e=>jk(e)[0])).slice(0,3);return[]})(e),r=[0,56,48,40][t.length]||32,i=t.join("").toUpperCase();return s.createElement("svg",{viewBox:"-60 -60 120 120","aria-hidden":"true",style:{height:"100%",pointerEvents:"none",width:"100%"}},s.createElement("text",{x:0,y:0,textAnchor:"middle",dominantBaseline:"central",fontSize:r},i))};function Ak(e){var{avatarUrl:t,className:r,size:i=40,name:n,variant:o="round"}=e,a=dR(e,["avatarUrl","className","size","name","variant"]);return s.createElement("div",Object.assign({style:{height:`${i}px`,width:`${i}px`,userSelect:"none",overflow:"hidden",borderRadius:"round"===o?"50%":"4px",backgroundColor:"#f8e3c8"},className:r,title:n},a),!t&&n?s.createElement(Lk,{name:n}):s.createElement("img",{src:t||"",alt:"",style:{height:"100%",width:"100%",objectFit:"cover",maxWidth:"initial"}}))}function Nk({avatarUrl:e,displayName:t,isSmallCell:r,withRoundedCorners:i}){return s.createElement("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",position:"absolute",top:0,left:0,height:"100%",width:"100%",borderRadius:i?"8px":"0"}},s.createElement("div",{style:{height:r?60:80,width:r?60:80,pointerEvents:"none",position:"relative"}},s.createElement(Ak,{variant:"square",avatarUrl:e,name:t,size:r?60:80})))}function Bk(){return Bk=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var i in r)Object.prototype.hasOwnProperty.call(r,i)&&(e[i]=r[i])}return e},Bk.apply(this,arguments)}function Fk(e,t,{checkForDefaultPrevented:r=!0}={}){return function(i){if(null==e||e(i),!1===r||!i.defaultPrevented)return null==t?void 0:t(i)}}function zk(...e){return t=>e.forEach((e=>function(e,t){"function"==typeof e?e(t):null!=e&&(e.current=t)}(e,t)))}function Vk(...e){return t.useCallback(zk(...e),e)}function Uk(e,r=[]){let i=[];const n=()=>{const r=i.map((e=>t.createContext(e)));return function(i){const n=(null==i?void 0:i[e])||r;return t.useMemo((()=>({[`__scope${e}`]:{...i,[e]:n}})),[i,n])}};return n.scopeName=e,[function(r,n){const s=t.createContext(n),o=i.length;function a(r){const{scope:i,children:n,...a}=r,c=(null==i?void 0:i[e][o])||s,d=t.useMemo((()=>a),Object.values(a));return t.createElement(c.Provider,{value:d},n)}return i=[...i,n],a.displayName=r+"Provider",[a,function(i,a){const c=(null==a?void 0:a[e][o])||s,d=t.useContext(c);if(d)return d;if(void 0!==n)return n;throw new Error(`\`${i}\` must be used within \`${r}\``)}]},$k(n,...r)]}function $k(...e){const r=e[0];if(1===e.length)return r;const i=()=>{const i=e.map((e=>({useScope:e(),scopeName:e.scopeName})));return function(e){const n=i.reduce(((t,{useScope:r,scopeName:i})=>({...t,...r(e)[`__scope${i}`]})),{});return t.useMemo((()=>({[`__scope${r.scopeName}`]:n})),[n])}};return i.scopeName=r.scopeName,i}const Gk=t.forwardRef(((e,r)=>{const{children:i,...n}=e,s=t.Children.toArray(i),o=s.find(Wk);if(o){const e=o.props.children,i=s.map((r=>r===o?t.Children.count(e)>1?t.Children.only(null):t.isValidElement(e)?e.props.children:null:r));return t.createElement(qk,Bk({},n,{ref:r}),t.isValidElement(e)?t.cloneElement(e,void 0,i):null)}return t.createElement(qk,Bk({},n,{ref:r}),i)}));Gk.displayName="Slot";const qk=t.forwardRef(((e,r)=>{const{children:i,...n}=e;return t.isValidElement(i)?t.cloneElement(i,{...Kk(n,i.props),ref:r?zk(r,i.ref):i.ref}):t.Children.count(i)>1?t.Children.only(null):null}));qk.displayName="SlotClone";const Hk=({children:e})=>t.createElement(t.Fragment,null,e);function Wk(e){return t.isValidElement(e)&&e.type===Hk}function Kk(e,t){const r={...t};for(const i in t){const n=e[i],s=t[i];/^on[A-Z]/.test(i)?n&&s?r[i]=(...e)=>{s(...e),n(...e)}:n&&(r[i]=n):"style"===i?r[i]={...n,...s}:"className"===i&&(r[i]=[n,s].filter(Boolean).join(" "))}return{...e,...r}}const Jk=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","span","svg","ul"].reduce(((e,r)=>{const i=t.forwardRef(((e,i)=>{const{asChild:n,...s}=e,o=n?Gk:r;return t.useEffect((()=>{window[Symbol.for("radix-ui")]=!0}),[]),t.createElement(o,Bk({},s,{ref:i}))}));return i.displayName=`Primitive.${r}`,{...e,[r]:i}}),{});function Xk(e){const r=t.useRef(e);return t.useEffect((()=>{r.current=e})),t.useMemo((()=>(...e)=>{var t;return null===(t=r.current)||void 0===t?void 0:t.call(r,...e)}),[])}const Qk="dismissableLayer.update",Zk="dismissableLayer.pointerDownOutside",Yk="dismissableLayer.focusOutside";let eT;const tT=t.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),rT=t.forwardRef(((e,r)=>{var i;const{disableOutsidePointerEvents:n=!1,onEscapeKeyDown:s,onPointerDownOutside:o,onFocusOutside:a,onInteractOutside:c,onDismiss:d,...l}=e,u=t.useContext(tT),[p,h]=t.useState(null),f=null!==(i=null==p?void 0:p.ownerDocument)&&void 0!==i?i:null===globalThis||void 0===globalThis?void 0:globalThis.document,[,m]=t.useState({}),g=Vk(r,(e=>h(e))),v=Array.from(u.layers),[b]=[...u.layersWithOutsidePointerEventsDisabled].slice(-1),y=v.indexOf(b),w=p?v.indexOf(p):-1,_=u.layersWithOutsidePointerEventsDisabled.size>0,S=w>=y,C=function(e,r=(null===globalThis||void 0===globalThis?void 0:globalThis.document)){const i=Xk(e),n=t.useRef(!1),s=t.useRef((()=>{}));return t.useEffect((()=>{const e=e=>{if(e.target&&!n.current){const t={originalEvent:e};function o(){nT(Zk,i,t,{discrete:!0})}"touch"===e.pointerType?(r.removeEventListener("click",s.current),s.current=o,r.addEventListener("click",s.current,{once:!0})):o()}else r.removeEventListener("click",s.current);n.current=!1},t=window.setTimeout((()=>{r.addEventListener("pointerdown",e)}),0);return()=>{window.clearTimeout(t),r.removeEventListener("pointerdown",e),r.removeEventListener("click",s.current)}}),[r,i]),{onPointerDownCapture:()=>n.current=!0}}((e=>{const t=e.target,r=[...u.branches].some((e=>e.contains(t)));S&&!r&&(null==o||o(e),null==c||c(e),e.defaultPrevented||null==d||d())}),f),R=function(e,r=(null===globalThis||void 0===globalThis?void 0:globalThis.document)){const i=Xk(e),n=t.useRef(!1);return t.useEffect((()=>{const e=e=>{if(e.target&&!n.current){nT(Yk,i,{originalEvent:e},{discrete:!1})}};return r.addEventListener("focusin",e),()=>r.removeEventListener("focusin",e)}),[r,i]),{onFocusCapture:()=>n.current=!0,onBlurCapture:()=>n.current=!1}}((e=>{const t=e.target;[...u.branches].some((e=>e.contains(t)))||(null==a||a(e),null==c||c(e),e.defaultPrevented||null==d||d())}),f);return function(e,r=(null===globalThis||void 0===globalThis?void 0:globalThis.document)){const i=Xk(e);t.useEffect((()=>{const e=e=>{"Escape"===e.key&&i(e)};return r.addEventListener("keydown",e),()=>r.removeEventListener("keydown",e)}),[i,r])}((e=>{w===u.layers.size-1&&(null==s||s(e),!e.defaultPrevented&&d&&(e.preventDefault(),d()))}),f),t.useEffect((()=>{if(p)return n&&(0===u.layersWithOutsidePointerEventsDisabled.size&&(eT=f.body.style.pointerEvents,f.body.style.pointerEvents="none"),u.layersWithOutsidePointerEventsDisabled.add(p)),u.layers.add(p),iT(),()=>{n&&1===u.layersWithOutsidePointerEventsDisabled.size&&(f.body.style.pointerEvents=eT)}}),[p,f,n,u]),t.useEffect((()=>()=>{p&&(u.layers.delete(p),u.layersWithOutsidePointerEventsDisabled.delete(p),iT())}),[p,u]),t.useEffect((()=>{const e=()=>m({});return document.addEventListener(Qk,e),()=>document.removeEventListener(Qk,e)}),[]),t.createElement(Jk.div,Bk({},l,{ref:g,style:{pointerEvents:_?S?"auto":"none":void 0,...e.style},onFocusCapture:Fk(e.onFocusCapture,R.onFocusCapture),onBlurCapture:Fk(e.onBlurCapture,R.onBlurCapture),onPointerDownCapture:Fk(e.onPointerDownCapture,C.onPointerDownCapture)}))}));function iT(){const e=new CustomEvent(Qk);document.dispatchEvent(e)}function nT(e,t,i,{discrete:n}){const s=i.originalEvent.target,o=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:i});t&&s.addEventListener(e,t,{once:!0}),n?function(e,t){e&&r.flushSync((()=>e.dispatchEvent(t)))}(s,o):s.dispatchEvent(o)}let sT=0;function oT(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.cssText="outline: none; opacity: 0; position: fixed; pointer-events: none",e}const aT="focusScope.autoFocusOnMount",cT="focusScope.autoFocusOnUnmount",dT={bubbles:!1,cancelable:!0},lT=t.forwardRef(((e,r)=>{const{loop:i=!1,trapped:n=!1,onMountAutoFocus:s,onUnmountAutoFocus:o,...a}=e,[c,d]=t.useState(null),l=Xk(s),u=Xk(o),p=t.useRef(null),h=Vk(r,(e=>d(e))),f=t.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;t.useEffect((()=>{if(n){function e(e){if(f.paused||!c)return;const t=e.target;c.contains(t)?p.current=t:fT(p.current,{select:!0})}function t(e){if(f.paused||!c)return;const t=e.relatedTarget;null!==t&&(c.contains(t)||fT(p.current,{select:!0}))}function r(e){if(document.activeElement===document.body)for(const t of e)t.removedNodes.length>0&&fT(c)}document.addEventListener("focusin",e),document.addEventListener("focusout",t);const i=new MutationObserver(r);return c&&i.observe(c,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",e),document.removeEventListener("focusout",t),i.disconnect()}}}),[n,c,f.paused]),t.useEffect((()=>{if(c){mT.add(f);const t=document.activeElement;if(!c.contains(t)){const r=new CustomEvent(aT,dT);c.addEventListener(aT,l),c.dispatchEvent(r),r.defaultPrevented||(!function(e,{select:t=!1}={}){const r=document.activeElement;for(const i of e)if(fT(i,{select:t}),document.activeElement!==r)return}((e=uT(c),e.filter((e=>"A"!==e.tagName))),{select:!0}),document.activeElement===t&&fT(c))}return()=>{c.removeEventListener(aT,l),setTimeout((()=>{const e=new CustomEvent(cT,dT);c.addEventListener(cT,u),c.dispatchEvent(e),e.defaultPrevented||fT(null!=t?t:document.body,{select:!0}),c.removeEventListener(cT,u),mT.remove(f)}),0)}}var e}),[c,l,u,f]);const m=t.useCallback((e=>{if(!i&&!n)return;if(f.paused)return;const t="Tab"===e.key&&!e.altKey&&!e.ctrlKey&&!e.metaKey,r=document.activeElement;if(t&&r){const t=e.currentTarget,[n,s]=function(e){const t=uT(e),r=pT(t,e),i=pT(t.reverse(),e);return[r,i]}(t);n&&s?e.shiftKey||r!==s?e.shiftKey&&r===n&&(e.preventDefault(),i&&fT(s,{select:!0})):(e.preventDefault(),i&&fT(n,{select:!0})):r===t&&e.preventDefault()}}),[i,n,f.paused]);return t.createElement(Jk.div,Bk({tabIndex:-1},a,{ref:h,onKeyDown:m}))}));function uT(e){const t=[],r=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:e=>{const t="INPUT"===e.tagName&&"hidden"===e.type;return e.disabled||e.hidden||t?NodeFilter.FILTER_SKIP:e.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;r.nextNode();)t.push(r.currentNode);return t}function pT(e,t){for(const r of e)if(!hT(r,{upTo:t}))return r}function hT(e,{upTo:t}){if("hidden"===getComputedStyle(e).visibility)return!0;for(;e;){if(void 0!==t&&e===t)return!1;if("none"===getComputedStyle(e).display)return!0;e=e.parentElement}return!1}function fT(e,{select:t=!1}={}){if(e&&e.focus){const r=document.activeElement;e.focus({preventScroll:!0}),e!==r&&function(e){return e instanceof HTMLInputElement&&"select"in e}(e)&&t&&e.select()}}const mT=function(){let e=[];return{add(t){const r=e[0];t!==r&&(null==r||r.pause()),e=gT(e,t),e.unshift(t)},remove(t){var r;e=gT(e,t),null===(r=e[0])||void 0===r||r.resume()}}}();function gT(e,t){const r=[...e],i=r.indexOf(t);return-1!==i&&r.splice(i,1),r}const vT=Boolean(null===globalThis||void 0===globalThis?void 0:globalThis.document)?t.useLayoutEffect:()=>{},bT=s["useId".toString()]||(()=>{});let yT=0;function wT(e){const[t,r]=s.useState(bT());return vT((()=>{e||r((e=>null!=e?e:String(yT++)))}),[e]),e||(t?`radix-${t}`:"")}const _T=["top","right","bottom","left"],ST=Math.min,CT=Math.max,RT=Math.round,kT=Math.floor,TT=e=>({x:e,y:e}),PT={left:"right",right:"left",bottom:"top",top:"bottom"},OT={start:"end",end:"start"};function ET(e,t,r){return CT(e,ST(t,r))}function DT(e,t){return"function"==typeof e?e(t):e}function IT(e){return e.split("-")[0]}function xT(e){return e.split("-")[1]}function MT(e){return"x"===e?"y":"x"}function jT(e){return"y"===e?"height":"width"}function LT(e){return["top","bottom"].includes(IT(e))?"y":"x"}function AT(e){return MT(LT(e))}function NT(e){return e.replace(/start|end/g,(e=>OT[e]))}function BT(e){return e.replace(/left|right|bottom|top/g,(e=>PT[e]))}function FT(e){return"number"!=typeof e?function(e){return{top:0,right:0,bottom:0,left:0,...e}}(e):{top:e,right:e,bottom:e,left:e}}function zT(e){const{x:t,y:r,width:i,height:n}=e;return{width:i,height:n,top:r,left:t,right:t+i,bottom:r+n,x:t,y:r}}function VT(e,t,r){let{reference:i,floating:n}=e;const s=LT(t),o=AT(t),a=jT(o),c=IT(t),d="y"===s,l=i.x+i.width/2-n.width/2,u=i.y+i.height/2-n.height/2,p=i[a]/2-n[a]/2;let h;switch(c){case"top":h={x:l,y:i.y-n.height};break;case"bottom":h={x:l,y:i.y+i.height};break;case"right":h={x:i.x+i.width,y:u};break;case"left":h={x:i.x-n.width,y:u};break;default:h={x:i.x,y:i.y}}switch(xT(t)){case"start":h[o]-=p*(r&&d?-1:1);break;case"end":h[o]+=p*(r&&d?-1:1)}return h}async function UT(e,t){var r;void 0===t&&(t={});const{x:i,y:n,platform:s,rects:o,elements:a,strategy:c}=e,{boundary:d="clippingAncestors",rootBoundary:l="viewport",elementContext:u="floating",altBoundary:p=!1,padding:h=0}=DT(t,e),f=FT(h),m=a[p?"floating"===u?"reference":"floating":u],g=zT(await s.getClippingRect({element:null==(r=await(null==s.isElement?void 0:s.isElement(m)))||r?m:m.contextElement||await(null==s.getDocumentElement?void 0:s.getDocumentElement(a.floating)),boundary:d,rootBoundary:l,strategy:c})),v="floating"===u?{x:i,y:n,width:o.floating.width,height:o.floating.height}:o.reference,b=await(null==s.getOffsetParent?void 0:s.getOffsetParent(a.floating)),y=await(null==s.isElement?void 0:s.isElement(b))&&await(null==s.getScale?void 0:s.getScale(b))||{x:1,y:1},w=zT(s.convertOffsetParentRelativeRectToViewportRelativeRect?await s.convertOffsetParentRelativeRectToViewportRelativeRect({elements:a,rect:v,offsetParent:b,strategy:c}):v);return{top:(g.top-w.top+f.top)/y.y,bottom:(w.bottom-g.bottom+f.bottom)/y.y,left:(g.left-w.left+f.left)/y.x,right:(w.right-g.right+f.right)/y.x}}function $T(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function GT(e){return _T.some((t=>e[t]>=0))}function qT(e){return KT(e)?(e.nodeName||"").toLowerCase():"#document"}function HT(e){var t;return(null==e||null==(t=e.ownerDocument)?void 0:t.defaultView)||window}function WT(e){var t;return null==(t=(KT(e)?e.ownerDocument:e.document)||window.document)?void 0:t.documentElement}function KT(e){return e instanceof Node||e instanceof HT(e).Node}function JT(e){return e instanceof Element||e instanceof HT(e).Element}function XT(e){return e instanceof HTMLElement||e instanceof HT(e).HTMLElement}function QT(e){return"undefined"!=typeof ShadowRoot&&(e instanceof ShadowRoot||e instanceof HT(e).ShadowRoot)}function ZT(e){const{overflow:t,overflowX:r,overflowY:i,display:n}=iP(e);return/auto|scroll|overlay|hidden|clip/.test(t+i+r)&&!["inline","contents"].includes(n)}function YT(e){return["table","td","th"].includes(qT(e))}function eP(e){const t=tP(),r=iP(e);return"none"!==r.transform||"none"!==r.perspective||!!r.containerType&&"normal"!==r.containerType||!t&&!!r.backdropFilter&&"none"!==r.backdropFilter||!t&&!!r.filter&&"none"!==r.filter||["transform","perspective","filter"].some((e=>(r.willChange||"").includes(e)))||["paint","layout","strict","content"].some((e=>(r.contain||"").includes(e)))}function tP(){return!("undefined"==typeof CSS||!CSS.supports)&&CSS.supports("-webkit-backdrop-filter","none")}function rP(e){return["html","body","#document"].includes(qT(e))}function iP(e){return HT(e).getComputedStyle(e)}function nP(e){return JT(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.pageXOffset,scrollTop:e.pageYOffset}}function sP(e){if("html"===qT(e))return e;const t=e.assignedSlot||e.parentNode||QT(e)&&e.host||WT(e);return QT(t)?t.host:t}function oP(e){const t=sP(e);return rP(t)?e.ownerDocument?e.ownerDocument.body:e.body:XT(t)&&ZT(t)?t:oP(t)}function aP(e,t,r){var i;void 0===t&&(t=[]),void 0===r&&(r=!0);const n=oP(e),s=n===(null==(i=e.ownerDocument)?void 0:i.body),o=HT(n);return s?t.concat(o,o.visualViewport||[],ZT(n)?n:[],o.frameElement&&r?aP(o.frameElement):[]):t.concat(n,aP(n,[],r))}function cP(e){const t=iP(e);let r=parseFloat(t.width)||0,i=parseFloat(t.height)||0;const n=XT(e),s=n?e.offsetWidth:r,o=n?e.offsetHeight:i,a=RT(r)!==s||RT(i)!==o;return a&&(r=s,i=o),{width:r,height:i,$:a}}function dP(e){return JT(e)?e:e.contextElement}function lP(e){const t=dP(e);if(!XT(t))return TT(1);const r=t.getBoundingClientRect(),{width:i,height:n,$:s}=cP(t);let o=(s?RT(r.width):r.width)/i,a=(s?RT(r.height):r.height)/n;return o&&Number.isFinite(o)||(o=1),a&&Number.isFinite(a)||(a=1),{x:o,y:a}}const uP=TT(0);function pP(e){const t=HT(e);return tP()&&t.visualViewport?{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}:uP}function hP(e,t,r,i){void 0===t&&(t=!1),void 0===r&&(r=!1);const n=e.getBoundingClientRect(),s=dP(e);let o=TT(1);t&&(i?JT(i)&&(o=lP(i)):o=lP(e));const a=function(e,t,r){return void 0===t&&(t=!1),!(!r||t&&r!==HT(e))&&t}(s,r,i)?pP(s):TT(0);let c=(n.left+a.x)/o.x,d=(n.top+a.y)/o.y,l=n.width/o.x,u=n.height/o.y;if(s){const e=HT(s),t=i&&JT(i)?HT(i):i;let r=e,n=r.frameElement;for(;n&&i&&t!==r;){const e=lP(n),t=n.getBoundingClientRect(),i=iP(n),s=t.left+(n.clientLeft+parseFloat(i.paddingLeft))*e.x,o=t.top+(n.clientTop+parseFloat(i.paddingTop))*e.y;c*=e.x,d*=e.y,l*=e.x,u*=e.y,c+=s,d+=o,r=HT(n),n=r.frameElement}}return zT({width:l,height:u,x:c,y:d})}const fP=[":popover-open",":modal"];function mP(e){return fP.some((t=>{try{return e.matches(t)}catch(e){return!1}}))}function gP(e){return hP(WT(e)).left+nP(e).scrollLeft}function vP(e,t,r){let i;if("viewport"===t)i=function(e,t){const r=HT(e),i=WT(e),n=r.visualViewport;let s=i.clientWidth,o=i.clientHeight,a=0,c=0;if(n){s=n.width,o=n.height;const e=tP();(!e||e&&"fixed"===t)&&(a=n.offsetLeft,c=n.offsetTop)}return{width:s,height:o,x:a,y:c}}(e,r);else if("document"===t)i=function(e){const t=WT(e),r=nP(e),i=e.ownerDocument.body,n=CT(t.scrollWidth,t.clientWidth,i.scrollWidth,i.clientWidth),s=CT(t.scrollHeight,t.clientHeight,i.scrollHeight,i.clientHeight);let o=-r.scrollLeft+gP(e);const a=-r.scrollTop;return"rtl"===iP(i).direction&&(o+=CT(t.clientWidth,i.clientWidth)-n),{width:n,height:s,x:o,y:a}}(WT(e));else if(JT(t))i=function(e,t){const r=hP(e,!0,"fixed"===t),i=r.top+e.clientTop,n=r.left+e.clientLeft,s=XT(e)?lP(e):TT(1);return{width:e.clientWidth*s.x,height:e.clientHeight*s.y,x:n*s.x,y:i*s.y}}(t,r);else{const r=pP(e);i={...t,x:t.x-r.x,y:t.y-r.y}}return zT(i)}function bP(e,t){const r=sP(e);return!(r===t||!JT(r)||rP(r))&&("fixed"===iP(r).position||bP(r,t))}function yP(e,t,r){const i=XT(t),n=WT(t),s="fixed"===r,o=hP(e,!0,s,t);let a={scrollLeft:0,scrollTop:0};const c=TT(0);if(i||!i&&!s)if(("body"!==qT(t)||ZT(n))&&(a=nP(t)),i){const e=hP(t,!0,s,t);c.x=e.x+t.clientLeft,c.y=e.y+t.clientTop}else n&&(c.x=gP(n));return{x:o.left+a.scrollLeft-c.x,y:o.top+a.scrollTop-c.y,width:o.width,height:o.height}}function wP(e){return"static"===iP(e).position}function _P(e,t){return XT(e)&&"fixed"!==iP(e).position?t?t(e):e.offsetParent:null}function SP(e,t){const r=HT(e);if(mP(e))return r;if(!XT(e)){let t=sP(e);for(;t&&!rP(t);){if(JT(t)&&!wP(t))return t;t=sP(t)}return r}let i=_P(e,t);for(;i&&YT(i)&&wP(i);)i=_P(i,t);return i&&rP(i)&&wP(i)&&!eP(i)?r:i||function(e){let t=sP(e);for(;XT(t)&&!rP(t);){if(eP(t))return t;t=sP(t)}return null}(e)||r}const CP={convertOffsetParentRelativeRectToViewportRelativeRect:function(e){let{elements:t,rect:r,offsetParent:i,strategy:n}=e;const s="fixed"===n,o=WT(i),a=!!t&&mP(t.floating);if(i===o||a&&s)return r;let c={scrollLeft:0,scrollTop:0},d=TT(1);const l=TT(0),u=XT(i);if((u||!u&&!s)&&(("body"!==qT(i)||ZT(o))&&(c=nP(i)),XT(i))){const e=hP(i);d=lP(i),l.x=e.x+i.clientLeft,l.y=e.y+i.clientTop}return{width:r.width*d.x,height:r.height*d.y,x:r.x*d.x-c.scrollLeft*d.x+l.x,y:r.y*d.y-c.scrollTop*d.y+l.y}},getDocumentElement:WT,getClippingRect:function(e){let{element:t,boundary:r,rootBoundary:i,strategy:n}=e;const s="clippingAncestors"===r?mP(t)?[]:function(e,t){const r=t.get(e);if(r)return r;let i=aP(e,[],!1).filter((e=>JT(e)&&"body"!==qT(e))),n=null;const s="fixed"===iP(e).position;let o=s?sP(e):e;for(;JT(o)&&!rP(o);){const t=iP(o),r=eP(o);r||"fixed"!==t.position||(n=null),(s?!r&&!n:!r&&"static"===t.position&&n&&["absolute","fixed"].includes(n.position)||ZT(o)&&!r&&bP(e,o))?i=i.filter((e=>e!==o)):n=t,o=sP(o)}return t.set(e,i),i}(t,this._c):[].concat(r),o=[...s,i],a=o[0],c=o.reduce(((e,r)=>{const i=vP(t,r,n);return e.top=CT(i.top,e.top),e.right=ST(i.right,e.right),e.bottom=ST(i.bottom,e.bottom),e.left=CT(i.left,e.left),e}),vP(t,a,n));return{width:c.right-c.left,height:c.bottom-c.top,x:c.left,y:c.top}},getOffsetParent:SP,getElementRects:async function(e){const t=this.getOffsetParent||SP,r=this.getDimensions,i=await r(e.floating);return{reference:yP(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:i.width,height:i.height}}},getClientRects:function(e){return Array.from(e.getClientRects())},getDimensions:function(e){const{width:t,height:r}=cP(e);return{width:t,height:r}},getScale:lP,isElement:JT,isRTL:function(e){return"rtl"===iP(e).direction}};function RP(e,t,r,i){void 0===i&&(i={});const{ancestorScroll:n=!0,ancestorResize:s=!0,elementResize:o="function"==typeof ResizeObserver,layoutShift:a="function"==typeof IntersectionObserver,animationFrame:c=!1}=i,d=dP(e),l=n||s?[...d?aP(d):[],...aP(t)]:[];l.forEach((e=>{n&&e.addEventListener("scroll",r,{passive:!0}),s&&e.addEventListener("resize",r)}));const u=d&&a?function(e,t){let r,i=null;const n=WT(e);function s(){var e;clearTimeout(r),null==(e=i)||e.disconnect(),i=null}return function o(a,c){void 0===a&&(a=!1),void 0===c&&(c=1),s();const{left:d,top:l,width:u,height:p}=e.getBoundingClientRect();if(a||t(),!u||!p)return;const h={rootMargin:-kT(l)+"px "+-kT(n.clientWidth-(d+u))+"px "+-kT(n.clientHeight-(l+p))+"px "+-kT(d)+"px",threshold:CT(0,ST(1,c))||1};let f=!0;function m(e){const t=e[0].intersectionRatio;if(t!==c){if(!f)return o();t?o(!1,t):r=setTimeout((()=>{o(!1,1e-7)}),1e3)}f=!1}try{i=new IntersectionObserver(m,{...h,root:n.ownerDocument})}catch(e){i=new IntersectionObserver(m,h)}i.observe(e)}(!0),s}(d,r):null;let p,h=-1,f=null;o&&(f=new ResizeObserver((e=>{let[i]=e;i&&i.target===d&&f&&(f.unobserve(t),cancelAnimationFrame(h),h=requestAnimationFrame((()=>{var e;null==(e=f)||e.observe(t)}))),r()})),d&&!c&&f.observe(d),f.observe(t));let m=c?hP(e):null;return c&&function t(){const i=hP(e);!m||i.x===m.x&&i.y===m.y&&i.width===m.width&&i.height===m.height||r();m=i,p=requestAnimationFrame(t)}(),r(),()=>{var e;l.forEach((e=>{n&&e.removeEventListener("scroll",r),s&&e.removeEventListener("resize",r)})),null==u||u(),null==(e=f)||e.disconnect(),f=null,c&&cancelAnimationFrame(p)}}const kP=function(e){return void 0===e&&(e=0),{name:"offset",options:e,async fn(t){var r,i;const{x:n,y:s,placement:o,middlewareData:a}=t,c=await async function(e,t){const{placement:r,platform:i,elements:n}=e,s=await(null==i.isRTL?void 0:i.isRTL(n.floating)),o=IT(r),a=xT(r),c="y"===LT(r),d=["left","top"].includes(o)?-1:1,l=s&&c?-1:1,u=DT(t,e);let{mainAxis:p,crossAxis:h,alignmentAxis:f}="number"==typeof u?{mainAxis:u,crossAxis:0,alignmentAxis:null}:{mainAxis:0,crossAxis:0,alignmentAxis:null,...u};return a&&"number"==typeof f&&(h="end"===a?-1*f:f),c?{x:h*l,y:p*d}:{x:p*d,y:h*l}}(t,e);return o===(null==(r=a.offset)?void 0:r.placement)&&null!=(i=a.arrow)&&i.alignmentOffset?{}:{x:n+c.x,y:s+c.y,data:{...c,placement:o}}}}},TP=function(e){return void 0===e&&(e={}),{name:"shift",options:e,async fn(t){const{x:r,y:i,placement:n}=t,{mainAxis:s=!0,crossAxis:o=!1,limiter:a={fn:e=>{let{x:t,y:r}=e;return{x:t,y:r}}},...c}=DT(e,t),d={x:r,y:i},l=await UT(t,c),u=LT(IT(n)),p=MT(u);let h=d[p],f=d[u];if(s){const e="y"===p?"bottom":"right";h=ET(h+l["y"===p?"top":"left"],h,h-l[e])}if(o){const e="y"===u?"bottom":"right";f=ET(f+l["y"===u?"top":"left"],f,f-l[e])}const m=a.fn({...t,[p]:h,[u]:f});return{...m,data:{x:m.x-r,y:m.y-i}}}}},PP=function(e){return void 0===e&&(e={}),{name:"flip",options:e,async fn(t){var r,i;const{placement:n,middlewareData:s,rects:o,initialPlacement:a,platform:c,elements:d}=t,{mainAxis:l=!0,crossAxis:u=!0,fallbackPlacements:p,fallbackStrategy:h="bestFit",fallbackAxisSideDirection:f="none",flipAlignment:m=!0,...g}=DT(e,t);if(null!=(r=s.arrow)&&r.alignmentOffset)return{};const v=IT(n),b=IT(a)===a,y=await(null==c.isRTL?void 0:c.isRTL(d.floating)),w=p||(b||!m?[BT(a)]:function(e){const t=BT(e);return[NT(e),t,NT(t)]}(a));p||"none"===f||w.push(...function(e,t,r,i){const n=xT(e);let s=function(e,t,r){const i=["left","right"],n=["right","left"],s=["top","bottom"],o=["bottom","top"];switch(e){case"top":case"bottom":return r?t?n:i:t?i:n;case"left":case"right":return t?s:o;default:return[]}}(IT(e),"start"===r,i);return n&&(s=s.map((e=>e+"-"+n)),t&&(s=s.concat(s.map(NT)))),s}(a,m,f,y));const _=[a,...w],S=await UT(t,g),C=[];let R=(null==(i=s.flip)?void 0:i.overflows)||[];if(l&&C.push(S[v]),u){const e=function(e,t,r){void 0===r&&(r=!1);const i=xT(e),n=AT(e),s=jT(n);let o="x"===n?i===(r?"end":"start")?"right":"left":"start"===i?"bottom":"top";return t.reference[s]>t.floating[s]&&(o=BT(o)),[o,BT(o)]}(n,o,y);C.push(S[e[0]],S[e[1]])}if(R=[...R,{placement:n,overflows:C}],!C.every((e=>e<=0))){var k,T;const e=((null==(k=s.flip)?void 0:k.index)||0)+1,t=_[e];if(t)return{data:{index:e,overflows:R},reset:{placement:t}};let r=null==(T=R.filter((e=>e.overflows[0]<=0)).sort(((e,t)=>e.overflows[1]-t.overflows[1]))[0])?void 0:T.placement;if(!r)switch(h){case"bestFit":{var P;const e=null==(P=R.map((e=>[e.placement,e.overflows.filter((e=>e>0)).reduce(((e,t)=>e+t),0)])).sort(((e,t)=>e[1]-t[1]))[0])?void 0:P[0];e&&(r=e);break}case"initialPlacement":r=a}if(n!==r)return{reset:{placement:r}}}return{}}}},OP=function(e){return void 0===e&&(e={}),{name:"size",options:e,async fn(t){const{placement:r,rects:i,platform:n,elements:s}=t,{apply:o=(()=>{}),...a}=DT(e,t),c=await UT(t,a),d=IT(r),l=xT(r),u="y"===LT(r),{width:p,height:h}=i.floating;let f,m;"top"===d||"bottom"===d?(f=d,m=l===(await(null==n.isRTL?void 0:n.isRTL(s.floating))?"start":"end")?"left":"right"):(m=d,f="end"===l?"top":"bottom");const g=h-c.top-c.bottom,v=p-c.left-c.right,b=ST(h-c[f],g),y=ST(p-c[m],v),w=!t.middlewareData.shift;let _=b,S=y;if(u?S=l||w?ST(y,v):v:_=l||w?ST(b,g):g,w&&!l){const e=CT(c.left,0),t=CT(c.right,0),r=CT(c.top,0),i=CT(c.bottom,0);u?S=p-2*(0!==e||0!==t?e+t:CT(c.left,c.right)):_=h-2*(0!==r||0!==i?r+i:CT(c.top,c.bottom))}await o({...t,availableWidth:S,availableHeight:_});const C=await n.getDimensions(s.floating);return p!==C.width||h!==C.height?{reset:{rects:!0}}:{}}}},EP=function(e){return void 0===e&&(e={}),{name:"hide",options:e,async fn(t){const{rects:r}=t,{strategy:i="referenceHidden",...n}=DT(e,t);switch(i){case"referenceHidden":{const e=$T(await UT(t,{...n,elementContext:"reference"}),r.reference);return{data:{referenceHiddenOffsets:e,referenceHidden:GT(e)}}}case"escaped":{const e=$T(await UT(t,{...n,altBoundary:!0}),r.floating);return{data:{escapedOffsets:e,escaped:GT(e)}}}default:return{}}}}},DP=e=>({name:"arrow",options:e,async fn(t){const{x:r,y:i,placement:n,rects:s,platform:o,elements:a,middlewareData:c}=t,{element:d,padding:l=0}=DT(e,t)||{};if(null==d)return{};const u=FT(l),p={x:r,y:i},h=AT(n),f=jT(h),m=await o.getDimensions(d),g="y"===h,v=g?"top":"left",b=g?"bottom":"right",y=g?"clientHeight":"clientWidth",w=s.reference[f]+s.reference[h]-p[h]-s.floating[f],_=p[h]-s.reference[h],S=await(null==o.getOffsetParent?void 0:o.getOffsetParent(d));let C=S?S[y]:0;C&&await(null==o.isElement?void 0:o.isElement(S))||(C=a.floating[y]||s.floating[f]);const R=w/2-_/2,k=C/2-m[f]/2-1,T=ST(u[v],k),P=ST(u[b],k),O=T,E=C-m[f]-P,D=C/2-m[f]/2+R,I=ET(O,D,E),x=!c.arrow&&null!=xT(n)&&D!==I&&s.reference[f]/2-(D<O?T:P)-m[f]/2<0,M=x?D<O?D-O:D-E:0;return{[h]:p[h]+M,data:{[h]:I,centerOffset:D-I-M,...x&&{alignmentOffset:M}},reset:x}}}),IP=function(e){return void 0===e&&(e={}),{options:e,fn(t){const{x:r,y:i,placement:n,rects:s,middlewareData:o}=t,{offset:a=0,mainAxis:c=!0,crossAxis:d=!0}=DT(e,t),l={x:r,y:i},u=LT(n),p=MT(u);let h=l[p],f=l[u];const m=DT(a,t),g="number"==typeof m?{mainAxis:m,crossAxis:0}:{mainAxis:0,crossAxis:0,...m};if(c){const e="y"===p?"height":"width",t=s.reference[p]-s.floating[e]+g.mainAxis,r=s.reference[p]+s.reference[e]-g.mainAxis;h<t?h=t:h>r&&(h=r)}if(d){var v,b;const e="y"===p?"width":"height",t=["top","left"].includes(IT(n)),r=s.reference[u]-s.floating[e]+(t&&(null==(v=o.offset)?void 0:v[u])||0)+(t?0:g.crossAxis),i=s.reference[u]+s.reference[e]+(t?0:(null==(b=o.offset)?void 0:b[u])||0)-(t?g.crossAxis:0);f<r?f=r:f>i&&(f=i)}return{[p]:h,[u]:f}}}},xP=(e,t,r)=>{const i=new Map,n={platform:CP,...r},s={...n.platform,_c:i};return(async(e,t,r)=>{const{placement:i="bottom",strategy:n="absolute",middleware:s=[],platform:o}=r,a=s.filter(Boolean),c=await(null==o.isRTL?void 0:o.isRTL(t));let d=await o.getElementRects({reference:e,floating:t,strategy:n}),{x:l,y:u}=VT(d,i,c),p=i,h={},f=0;for(let r=0;r<a.length;r++){const{name:s,fn:m}=a[r],{x:g,y:v,data:b,reset:y}=await m({x:l,y:u,initialPlacement:i,placement:p,strategy:n,middlewareData:h,rects:d,platform:o,elements:{reference:e,floating:t}});l=null!=g?g:l,u=null!=v?v:u,h={...h,[s]:{...h[s],...b}},y&&f<=50&&(f++,"object"==typeof y&&(y.placement&&(p=y.placement),y.rects&&(d=!0===y.rects?await o.getElementRects({reference:e,floating:t,strategy:n}):y.rects),({x:l,y:u}=VT(d,p,c))),r=-1)}return{x:l,y:u,placement:p,strategy:n,middlewareData:h}})(e,t,{...n,platform:s})};var MP="undefined"!=typeof document?t.useLayoutEffect:t.useEffect;function jP(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if("function"==typeof e&&e.toString()===t.toString())return!0;let r,i,n;if(e&&t&&"object"==typeof e){if(Array.isArray(e)){if(r=e.length,r!==t.length)return!1;for(i=r;0!=i--;)if(!jP(e[i],t[i]))return!1;return!0}if(n=Object.keys(e),r=n.length,r!==Object.keys(t).length)return!1;for(i=r;0!=i--;)if(!{}.hasOwnProperty.call(t,n[i]))return!1;for(i=r;0!=i--;){const r=n[i];if(("_owner"!==r||!e.$$typeof)&&!jP(e[r],t[r]))return!1}return!0}return e!=e&&t!=t}function LP(e){if("undefined"==typeof window)return 1;return(e.ownerDocument.defaultView||window).devicePixelRatio||1}function AP(e,t){const r=LP(e);return Math.round(t*r)/r}function NP(e){const t=s.useRef(e);return MP((()=>{t.current=e})),t}const BP=e=>({name:"arrow",options:e,fn(t){const{element:r,padding:i}="function"==typeof e?e(t):e;return r&&function(e){return{}.hasOwnProperty.call(e,"current")}(r)?null!=r.current?DP({element:r.current,padding:i}).fn(t):{}:r?DP({element:r,padding:i}).fn(t):{}}}),FP=(e,t)=>({...kP(e),options:[e,t]}),zP=(e,t)=>({...TP(e),options:[e,t]}),VP=(e,t)=>({...IP(e),options:[e,t]}),UP=(e,t)=>({...PP(e),options:[e,t]}),$P=(e,t)=>({...OP(e),options:[e,t]}),GP=(e,t)=>({...EP(e),options:[e,t]}),qP=(e,t)=>({...BP(e),options:[e,t]});const HP="Popper",[WP,KP]=Uk(HP),[JP,XP]=WP(HP),QP=t.forwardRef(((e,r)=>{const{__scopePopper:i,virtualRef:n,...s}=e,o=XP("PopperAnchor",i),a=t.useRef(null),c=Vk(r,a);return t.useEffect((()=>{o.onAnchorChange((null==n?void 0:n.current)||a.current)})),n?null:t.createElement(Jk.div,Bk({},s,{ref:c}))})),ZP="PopperContent",[YP,eO]=WP(ZP),tO=t.forwardRef(((e,r)=>{var i,n,a,c,d,l,u,p;const{__scopePopper:h,side:f="bottom",sideOffset:m=0,align:g="center",alignOffset:v=0,arrowPadding:b=0,avoidCollisions:y=!0,collisionBoundary:w=[],collisionPadding:_=0,sticky:S="partial",hideWhenDetached:C=!1,updatePositionStrategy:R="optimized",onPlaced:k,...T}=e,P=XP(ZP,h),[O,E]=t.useState(null),D=Vk(r,(e=>E(e))),[I,x]=t.useState(null),M=function(e){const[r,i]=t.useState(void 0);return vT((()=>{if(e){i({width:e.offsetWidth,height:e.offsetHeight});const t=new ResizeObserver((t=>{if(!Array.isArray(t))return;if(!t.length)return;const r=t[0];let n,s;if("borderBoxSize"in r){const e=r.borderBoxSize,t=Array.isArray(e)?e[0]:e;n=t.inlineSize,s=t.blockSize}else n=e.offsetWidth,s=e.offsetHeight;i({width:n,height:s})}));return t.observe(e,{box:"border-box"}),()=>t.unobserve(e)}i(void 0)}),[e]),r}(I),j=null!==(i=null==M?void 0:M.width)&&void 0!==i?i:0,L=null!==(n=null==M?void 0:M.height)&&void 0!==n?n:0,A=f+("center"!==g?"-"+g:""),N="number"==typeof _?_:{top:0,right:0,bottom:0,left:0,..._},B=Array.isArray(w)?w:[w],F=B.length>0,z={padding:N,boundary:B.filter(rO),altBoundary:F},{refs:V,floatingStyles:U,placement:$,isPositioned:G,middlewareData:q}=function(e){void 0===e&&(e={});const{placement:t="bottom",strategy:r="absolute",middleware:i=[],platform:n,elements:{reference:a,floating:c}={},transform:d=!0,whileElementsMounted:l,open:u}=e,[p,h]=s.useState({x:0,y:0,strategy:r,placement:t,middlewareData:{},isPositioned:!1}),[f,m]=s.useState(i);jP(f,i)||m(i);const[g,v]=s.useState(null),[b,y]=s.useState(null),w=s.useCallback((e=>{e!==R.current&&(R.current=e,v(e))}),[]),_=s.useCallback((e=>{e!==k.current&&(k.current=e,y(e))}),[]),S=a||g,C=c||b,R=s.useRef(null),k=s.useRef(null),T=s.useRef(p),P=null!=l,O=NP(l),E=NP(n),D=s.useCallback((()=>{if(!R.current||!k.current)return;const e={placement:t,strategy:r,middleware:f};E.current&&(e.platform=E.current),xP(R.current,k.current,e).then((e=>{const t={...e,isPositioned:!0};I.current&&!jP(T.current,t)&&(T.current=t,o.flushSync((()=>{h(t)})))}))}),[f,t,r,E]);MP((()=>{!1===u&&T.current.isPositioned&&(T.current.isPositioned=!1,h((e=>({...e,isPositioned:!1}))))}),[u]);const I=s.useRef(!1);MP((()=>(I.current=!0,()=>{I.current=!1})),[]),MP((()=>{if(S&&(R.current=S),C&&(k.current=C),S&&C){if(O.current)return O.current(S,C,D);D()}}),[S,C,D,O,P]);const x=s.useMemo((()=>({reference:R,floating:k,setReference:w,setFloating:_})),[w,_]),M=s.useMemo((()=>({reference:S,floating:C})),[S,C]),j=s.useMemo((()=>{const e={position:r,left:0,top:0};if(!M.floating)return e;const t=AP(M.floating,p.x),i=AP(M.floating,p.y);return d?{...e,transform:"translate("+t+"px, "+i+"px)",...LP(M.floating)>=1.5&&{willChange:"transform"}}:{position:r,left:t,top:i}}),[r,d,M.floating,p.x,p.y]);return s.useMemo((()=>({...p,update:D,refs:x,elements:M,floatingStyles:j})),[p,D,x,M,j])}({strategy:"fixed",placement:A,whileElementsMounted:(...e)=>RP(...e,{animationFrame:"always"===R}),elements:{reference:P.anchor},middleware:[FP({mainAxis:m+L,alignmentAxis:v}),y&&zP({mainAxis:!0,crossAxis:!1,limiter:"partial"===S?VP():void 0,...z}),y&&UP({...z}),$P({...z,apply:({elements:e,rects:t,availableWidth:r,availableHeight:i})=>{const{width:n,height:s}=t.reference,o=e.floating.style;o.setProperty("--radix-popper-available-width",`${r}px`),o.setProperty("--radix-popper-available-height",`${i}px`),o.setProperty("--radix-popper-anchor-width",`${n}px`),o.setProperty("--radix-popper-anchor-height",`${s}px`)}}),I&&qP({element:I,padding:b}),iO({arrowWidth:j,arrowHeight:L}),C&&GP({strategy:"referenceHidden",...z})]}),[H,W]=nO($),K=Xk(k);vT((()=>{G&&(null==K||K())}),[G,K]);const J=null===(a=q.arrow)||void 0===a?void 0:a.x,X=null===(c=q.arrow)||void 0===c?void 0:c.y,Q=0!==(null===(d=q.arrow)||void 0===d?void 0:d.centerOffset),[Z,Y]=t.useState();return vT((()=>{O&&Y(window.getComputedStyle(O).zIndex)}),[O]),t.createElement("div",{ref:V.setFloating,"data-radix-popper-content-wrapper":"",style:{...U,transform:G?U.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:Z,"--radix-popper-transform-origin":[null===(l=q.transformOrigin)||void 0===l?void 0:l.x,null===(u=q.transformOrigin)||void 0===u?void 0:u.y].join(" ")},dir:e.dir},t.createElement(YP,{scope:h,placedSide:H,onArrowChange:x,arrowX:J,arrowY:X,shouldHideArrow:Q},t.createElement(Jk.div,Bk({"data-side":H,"data-align":W},T,{ref:D,style:{...T.style,animation:G?void 0:"none",opacity:null!==(p=q.hide)&&void 0!==p&&p.referenceHidden?0:void 0}}))))}));function rO(e){return null!==e}const iO=e=>({name:"transformOrigin",options:e,fn(t){var r,i,n,s,o;const{placement:a,rects:c,middlewareData:d}=t,l=0!==(null===(r=d.arrow)||void 0===r?void 0:r.centerOffset),u=l?0:e.arrowWidth,p=l?0:e.arrowHeight,[h,f]=nO(a),m={start:"0%",center:"50%",end:"100%"}[f],g=(null!==(i=null===(n=d.arrow)||void 0===n?void 0:n.x)&&void 0!==i?i:0)+u/2,v=(null!==(s=null===(o=d.arrow)||void 0===o?void 0:o.y)&&void 0!==s?s:0)+p/2;let b="",y="";return"bottom"===h?(b=l?m:`${g}px`,y=-p+"px"):"top"===h?(b=l?m:`${g}px`,y=`${c.floating.height+p}px`):"right"===h?(b=-p+"px",y=l?m:`${v}px`):"left"===h&&(b=`${c.floating.width+p}px`,y=l?m:`${v}px`),{data:{x:b,y:y}}}});function nO(e){const[t,r="center"]=e.split("-");return[t,r]}const sO=e=>{const{__scopePopper:r,children:i}=e,[n,s]=t.useState(null);return t.createElement(JP,{scope:r,anchor:n,onAnchorChange:s},i)},oO=QP,aO=tO,cO=t.forwardRef(((e,i)=>{var n;const{container:s=(null===globalThis||void 0===globalThis||null===(n=globalThis.document)||void 0===n?void 0:n.body),...o}=e;return s?r.createPortal(t.createElement(Jk.div,Bk({},o,{ref:i})),s):null}));const dO=e=>{const{present:i,children:n}=e,s=function(e){const[i,n]=t.useState(),s=t.useRef({}),o=t.useRef(e),a=t.useRef("none"),c=e?"mounted":"unmounted",[d,l]=function(e,r){return t.useReducer(((e,t)=>{const i=r[e][t];return null!=i?i:e}),e)}(c,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return t.useEffect((()=>{const e=lO(s.current);a.current="mounted"===d?e:"none"}),[d]),vT((()=>{const t=s.current,r=o.current;if(r!==e){const i=a.current,n=lO(t);if(e)l("MOUNT");else if("none"===n||"none"===(null==t?void 0:t.display))l("UNMOUNT");else{l(r&&i!==n?"ANIMATION_OUT":"UNMOUNT")}o.current=e}}),[e,l]),vT((()=>{if(i){const e=e=>{const t=lO(s.current).includes(e.animationName);e.target===i&&t&&r.flushSync((()=>l("ANIMATION_END")))},t=e=>{e.target===i&&(a.current=lO(s.current))};return i.addEventListener("animationstart",t),i.addEventListener("animationcancel",e),i.addEventListener("animationend",e),()=>{i.removeEventListener("animationstart",t),i.removeEventListener("animationcancel",e),i.removeEventListener("animationend",e)}}l("ANIMATION_END")}),[i,l]),{isPresent:["mounted","unmountSuspended"].includes(d),ref:t.useCallback((e=>{e&&(s.current=getComputedStyle(e)),n(e)}),[])}}(i),o="function"==typeof n?n({present:s.isPresent}):t.Children.only(n),a=Vk(s.ref,o.ref);return"function"==typeof n||s.isPresent?t.cloneElement(o,{ref:a}):null};function lO(e){return(null==e?void 0:e.animationName)||"none"}function uO({prop:e,defaultProp:r,onChange:i=(()=>{})}){const[n,s]=function({defaultProp:e,onChange:r}){const i=t.useState(e),[n]=i,s=t.useRef(n),o=Xk(r);return t.useEffect((()=>{s.current!==n&&(o(n),s.current=n)}),[n,s,o]),i}({defaultProp:r,onChange:i}),o=void 0!==e,a=o?e:n,c=Xk(i),d=t.useCallback((t=>{if(o){const r="function"==typeof t?t(e):t;r!==e&&c(r)}else s(t)}),[o,e,s,c]);return[a,d]}dO.displayName="Presence";var pO=new WeakMap,hO=new WeakMap,fO={},mO=0,gO=function(e){return e&&(e.host||gO(e.parentNode))},vO=function(e,t,r,i){var n=function(e,t){return t.map((function(t){if(e.contains(t))return t;var r=gO(t);return r&&e.contains(r)?r:(console.error("aria-hidden",t,"in not contained inside",e,". Doing nothing"),null)})).filter((function(e){return Boolean(e)}))}(t,Array.isArray(e)?e:[e]);fO[r]||(fO[r]=new WeakMap);var s=fO[r],o=[],a=new Set,c=new Set(n),d=function(e){e&&!a.has(e)&&(a.add(e),d(e.parentNode))};n.forEach(d);var l=function(e){e&&!c.has(e)&&Array.prototype.forEach.call(e.children,(function(e){if(a.has(e))l(e);else try{var t=e.getAttribute(i),n=null!==t&&"false"!==t,c=(pO.get(e)||0)+1,d=(s.get(e)||0)+1;pO.set(e,c),s.set(e,d),o.push(e),1===c&&n&&hO.set(e,!0),1===d&&e.setAttribute(r,"true"),n||e.setAttribute(i,"true")}catch(t){console.error("aria-hidden: cannot operate on ",e,t)}}))};return l(t),a.clear(),mO++,function(){o.forEach((function(e){var t=pO.get(e)-1,n=s.get(e)-1;pO.set(e,t),s.set(e,n),t||(hO.has(e)||e.removeAttribute(i),hO.delete(e)),n||e.removeAttribute(r)})),--mO||(pO=new WeakMap,pO=new WeakMap,hO=new WeakMap,fO={})}},bO=function(e,t,r){void 0===r&&(r="data-aria-hidden");var i=Array.from(Array.isArray(e)?e:[e]),n=t||function(e){return"undefined"==typeof document?null:(Array.isArray(e)?e[0]:e).ownerDocument.body}(e);return n?(i.push.apply(i,Array.from(n.querySelectorAll("[aria-live]"))),vO(i,n,r,"aria-hidden")):function(){return null}},yO="right-scroll-bar-position",wO="width-before-scroll-bar";function _O(e,t){return"function"==typeof e?e(t):e&&(e.current=t),e}var SO=new WeakMap;function CO(e,r){var i,n,o,a=(i=r||null,n=function(t){return e.forEach((function(e){return _O(e,t)}))},o=t.useState((function(){return{value:i,callback:n,facade:{get current(){return o.value},set current(e){var t=o.value;t!==e&&(o.value=e,o.callback(e,t))}}}}))[0],o.callback=n,o.facade);return s.useLayoutEffect((function(){var t=SO.get(a);if(t){var r=new Set(t),i=new Set(e),n=a.current;r.forEach((function(e){i.has(e)||_O(e,null)})),i.forEach((function(e){r.has(e)||_O(e,n)}))}SO.set(a,e)}),[e]),a}function RO(e){return e}var kO=function(e){var t=e.sideCar,r=dR(e,["sideCar"]);if(!t)throw new Error("Sidecar: please provide `sideCar` property to import the right car");var i=t.read();if(!i)throw new Error("Sidecar medium not found");return s.createElement(i,cR({},r))};kO.isSideCarExport=!0;var TO=function(e){void 0===e&&(e={});var t=function(e,t){void 0===t&&(t=RO);var r=[],i=!1;return{read:function(){if(i)throw new Error("Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.");return r.length?r[r.length-1]:e},useMedium:function(e){var n=t(e,i);return r.push(n),function(){r=r.filter((function(e){return e!==n}))}},assignSyncMedium:function(e){for(i=!0;r.length;){var t=r;r=[],t.forEach(e)}r={push:function(t){return e(t)},filter:function(){return r}}},assignMedium:function(e){i=!0;var t=[];if(r.length){var n=r;r=[],n.forEach(e),t=r}var s=function(){var r=t;t=[],r.forEach(e)},o=function(){return Promise.resolve().then(s)};o(),r={push:function(e){t.push(e),o()},filter:function(e){return t=t.filter(e),r}}}}}(null);return t.options=cR({async:!0,ssr:!1},e),t}(),PO=function(){},OO=s.forwardRef((function(e,t){var r=s.useRef(null),i=s.useState({onScrollCapture:PO,onWheelCapture:PO,onTouchMoveCapture:PO}),n=i[0],o=i[1],a=e.forwardProps,c=e.children,d=e.className,l=e.removeScrollBar,u=e.enabled,p=e.shards,h=e.sideCar,f=e.noIsolation,m=e.inert,g=e.allowPinchZoom,v=e.as,b=void 0===v?"div":v,y=dR(e,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noIsolation","inert","allowPinchZoom","as"]),w=h,_=CO([r,t]),S=cR(cR({},y),n);return s.createElement(s.Fragment,null,u&&s.createElement(w,{sideCar:TO,removeScrollBar:l,shards:p,noIsolation:f,inert:m,setCallbacks:o,allowPinchZoom:!!g,lockRef:r}),a?s.cloneElement(s.Children.only(c),cR(cR({},S),{ref:_})):s.createElement(b,cR({},S,{className:d,ref:_}),c))}));OO.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1},OO.classNames={fullWidth:wO,zeroRight:yO};function EO(){if(!document)return null;var e=document.createElement("style");e.type="text/css";var t=function(){if("undefined"!=typeof __webpack_nonce__)return __webpack_nonce__}();return t&&e.setAttribute("nonce",t),e}var DO=function(){var e=0,t=null;return{add:function(r){var i,n;0==e&&(t=EO())&&(n=r,(i=t).styleSheet?i.styleSheet.cssText=n:i.appendChild(document.createTextNode(n)),function(e){(document.head||document.getElementsByTagName("head")[0]).appendChild(e)}(t)),e++},remove:function(){! --e&&t&&(t.parentNode&&t.parentNode.removeChild(t),t=null)}}},IO=function(){var e,t=(e=DO(),function(t,r){s.useEffect((function(){return e.add(t),function(){e.remove()}}),[t&&r])});return function(e){var r=e.styles,i=e.dynamic;return t(r,i),null}},xO={left:0,top:0,right:0,gap:0},MO=function(e){return parseInt(e||"",10)||0},jO=function(e){if(void 0===e&&(e="margin"),"undefined"==typeof window)return xO;var t=function(e){var t=window.getComputedStyle(document.body),r=t["padding"===e?"paddingLeft":"marginLeft"],i=t["padding"===e?"paddingTop":"marginTop"],n=t["padding"===e?"paddingRight":"marginRight"];return[MO(r),MO(i),MO(n)]}(e),r=document.documentElement.clientWidth,i=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,i-r+t[2]-t[0])}},LO=IO(),AO="data-scroll-locked",NO=function(e,t,r,i){var n=e.left,s=e.top,o=e.right,a=e.gap;return void 0===r&&(r="margin"),"\n .".concat("with-scroll-bars-hidden"," {\n overflow: hidden ").concat(i,";\n padding-right: ").concat(a,"px ").concat(i,";\n }\n body[").concat(AO,"] {\n overflow: hidden ").concat(i,";\n overscroll-behavior: contain;\n ").concat([t&&"position: relative ".concat(i,";"),"margin"===r&&"\n padding-left: ".concat(n,"px;\n padding-top: ").concat(s,"px;\n padding-right: ").concat(o,"px;\n margin-left:0;\n margin-top:0;\n margin-right: ").concat(a,"px ").concat(i,";\n "),"padding"===r&&"padding-right: ".concat(a,"px ").concat(i,";")].filter(Boolean).join(""),"\n }\n \n .").concat(yO," {\n right: ").concat(a,"px ").concat(i,";\n }\n \n .").concat(wO," {\n margin-right: ").concat(a,"px ").concat(i,";\n }\n \n .").concat(yO," .").concat(yO," {\n right: 0 ").concat(i,";\n }\n \n .").concat(wO," .").concat(wO," {\n margin-right: 0 ").concat(i,";\n }\n \n body[").concat(AO,"] {\n ").concat("--removed-body-scroll-bar-size",": ").concat(a,"px;\n }\n")},BO=function(){var e=parseInt(document.body.getAttribute(AO)||"0",10);return isFinite(e)?e:0},FO=function(e){var t=e.noRelative,r=e.noImportant,i=e.gapMode,n=void 0===i?"margin":i;s.useEffect((function(){return document.body.setAttribute(AO,(BO()+1).toString()),function(){var e=BO()-1;e<=0?document.body.removeAttribute(AO):document.body.setAttribute(AO,e.toString())}}),[]);var o=s.useMemo((function(){return jO(n)}),[n]);return s.createElement(LO,{styles:NO(o,!t,n,r?"":"!important")})},zO=!1;if("undefined"!=typeof window)try{var VO=Object.defineProperty({},"passive",{get:function(){return zO=!0,!0}});window.addEventListener("test",VO,VO),window.removeEventListener("test",VO,VO)}catch(WE){zO=!1}var UO=!!zO&&{passive:!1},$O=function(e,t){var r=window.getComputedStyle(e);return"hidden"!==r[t]&&!(r.overflowY===r.overflowX&&!function(e){return"TEXTAREA"===e.tagName}(e)&&"visible"===r[t])},GO=function(e,t){var r=t;do{if("undefined"!=typeof ShadowRoot&&r instanceof ShadowRoot&&(r=r.host),qO(e,r)){var i=HO(e,r);if(i[1]>i[2])return!0}r=r.parentNode}while(r&&r!==document.body);return!1},qO=function(e,t){return"v"===e?function(e){return $O(e,"overflowY")}(t):function(e){return $O(e,"overflowX")}(t)},HO=function(e,t){return"v"===e?function(e){return[e.scrollTop,e.scrollHeight,e.clientHeight]}(t):function(e){return[e.scrollLeft,e.scrollWidth,e.clientWidth]}(t)},WO=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},KO=function(e){return[e.deltaX,e.deltaY]},JO=function(e){return e&&"current"in e?e.current:e},XO=function(e){return"\n .block-interactivity-".concat(e," {pointer-events: none;}\n .allow-interactivity-").concat(e," {pointer-events: all;}\n")},QO=0,ZO=[];var YO,eE=(YO=function(e){var t=s.useRef([]),r=s.useRef([0,0]),i=s.useRef(),n=s.useState(QO++)[0],o=s.useState((function(){return IO()}))[0],a=s.useRef(e);s.useEffect((function(){a.current=e}),[e]),s.useEffect((function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(n));var t=function(e,t,r){if(r||2===arguments.length)for(var i,n=0,s=t.length;n<s;n++)!i&&n in t||(i||(i=Array.prototype.slice.call(t,0,n)),i[n]=t[n]);return e.concat(i||Array.prototype.slice.call(t))}([e.lockRef.current],(e.shards||[]).map(JO),!0).filter(Boolean);return t.forEach((function(e){return e.classList.add("allow-interactivity-".concat(n))})),function(){document.body.classList.remove("block-interactivity-".concat(n)),t.forEach((function(e){return e.classList.remove("allow-interactivity-".concat(n))}))}}}),[e.inert,e.lockRef.current,e.shards]);var c=s.useCallback((function(e,t){if("touches"in e&&2===e.touches.length)return!a.current.allowPinchZoom;var n,s=WO(e),o=r.current,c="deltaX"in e?e.deltaX:o[0]-s[0],d="deltaY"in e?e.deltaY:o[1]-s[1],l=e.target,u=Math.abs(c)>Math.abs(d)?"h":"v";if("touches"in e&&"h"===u&&"range"===l.type)return!1;var p=GO(u,l);if(!p)return!0;if(p?n=u:(n="v"===u?"h":"v",p=GO(u,l)),!p)return!1;if(!i.current&&"changedTouches"in e&&(c||d)&&(i.current=n),!n)return!0;var h=i.current||n;return function(e,t,r,i,n){var s=function(e,t){return"h"===e&&"rtl"===t?-1:1}(e,window.getComputedStyle(t).direction),o=s*i,a=r.target,c=t.contains(a),d=!1,l=o>0,u=0,p=0;do{var h=HO(e,a),f=h[0],m=h[1]-h[2]-s*f;(f||m)&&qO(e,a)&&(u+=m,p+=f),a=a.parentNode}while(!c&&a!==document.body||c&&(t.contains(a)||t===a));return(l&&(n&&0===u||!n&&o>u)||!l&&(n&&0===p||!n&&-o>p))&&(d=!0),d}(h,t,e,"h"===h?c:d,!0)}),[]),d=s.useCallback((function(e){var r=e;if(ZO.length&&ZO[ZO.length-1]===o){var i="deltaY"in r?KO(r):WO(r),n=t.current.filter((function(e){return e.name===r.type&&e.target===r.target&&(t=e.delta,n=i,t[0]===n[0]&&t[1]===n[1]);var t,n}))[0];if(n&&n.should)r.cancelable&&r.preventDefault();else if(!n){var s=(a.current.shards||[]).map(JO).filter(Boolean).filter((function(e){return e.contains(r.target)}));(s.length>0?c(r,s[0]):!a.current.noIsolation)&&r.cancelable&&r.preventDefault()}}}),[]),l=s.useCallback((function(e,r,i,n){var s={name:e,delta:r,target:i,should:n};t.current.push(s),setTimeout((function(){t.current=t.current.filter((function(e){return e!==s}))}),1)}),[]),u=s.useCallback((function(e){r.current=WO(e),i.current=void 0}),[]),p=s.useCallback((function(t){l(t.type,KO(t),t.target,c(t,e.lockRef.current))}),[]),h=s.useCallback((function(t){l(t.type,WO(t),t.target,c(t,e.lockRef.current))}),[]);s.useEffect((function(){return ZO.push(o),e.setCallbacks({onScrollCapture:p,onWheelCapture:p,onTouchMoveCapture:h}),document.addEventListener("wheel",d,UO),document.addEventListener("touchmove",d,UO),document.addEventListener("touchstart",u,UO),function(){ZO=ZO.filter((function(e){return e!==o})),document.removeEventListener("wheel",d,UO),document.removeEventListener("touchmove",d,UO),document.removeEventListener("touchstart",u,UO)}}),[]);var f=e.removeScrollBar,m=e.inert;return s.createElement(s.Fragment,null,m?s.createElement(o,{styles:XO(n)}):null,f?s.createElement(FO,{gapMode:"margin"}):null)},TO.useMedium(YO),kO),tE=s.forwardRef((function(e,t){return s.createElement(OO,cR({},e,{ref:t,sideCar:eE}))}));tE.classNames=OO.classNames;var rE=tE;const iE="Popover",[nE,sE]=Uk(iE,[KP]),oE=KP(),[aE,cE]=nE(iE),dE=t.forwardRef(((e,r)=>{const{__scopePopover:i,...n}=e,s=cE("PopoverTrigger",i),o=oE(i),a=Vk(r,s.triggerRef),c=t.createElement(Jk.button,Bk({type:"button","aria-haspopup":"dialog","aria-expanded":s.open,"aria-controls":s.contentId,"data-state":bE(s.open)},n,{ref:a,onClick:Fk(e.onClick,s.onOpenToggle)}));return s.hasCustomAnchor?c:t.createElement(oO,Bk({asChild:!0},o),c)})),lE="PopoverPortal",[uE,pE]=nE(lE,{forceMount:void 0}),hE="PopoverContent",fE=t.forwardRef(((e,r)=>{const i=pE(hE,e.__scopePopover),{forceMount:n=i.forceMount,...s}=e,o=cE(hE,e.__scopePopover);return t.createElement(dO,{present:n||o.open},o.modal?t.createElement(mE,Bk({},s,{ref:r})):t.createElement(gE,Bk({},s,{ref:r})))})),mE=t.forwardRef(((e,r)=>{const i=cE(hE,e.__scopePopover),n=t.useRef(null),s=Vk(r,n),o=t.useRef(!1);return t.useEffect((()=>{const e=n.current;if(e)return bO(e)}),[]),t.createElement(rE,{as:Gk,allowPinchZoom:!0},t.createElement(vE,Bk({},e,{ref:s,trapFocus:i.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:Fk(e.onCloseAutoFocus,(e=>{var t;e.preventDefault(),o.current||null===(t=i.triggerRef.current)||void 0===t||t.focus()})),onPointerDownOutside:Fk(e.onPointerDownOutside,(e=>{const t=e.detail.originalEvent,r=0===t.button&&!0===t.ctrlKey,i=2===t.button||r;o.current=i}),{checkForDefaultPrevented:!1}),onFocusOutside:Fk(e.onFocusOutside,(e=>e.preventDefault()),{checkForDefaultPrevented:!1})})))})),gE=t.forwardRef(((e,r)=>{const i=cE(hE,e.__scopePopover),n=t.useRef(!1),s=t.useRef(!1);return t.createElement(vE,Bk({},e,{ref:r,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:t=>{var r,o;(null===(r=e.onCloseAutoFocus)||void 0===r||r.call(e,t),t.defaultPrevented)||(n.current||null===(o=i.triggerRef.current)||void 0===o||o.focus(),t.preventDefault());n.current=!1,s.current=!1},onInteractOutside:t=>{var r,o;null===(r=e.onInteractOutside)||void 0===r||r.call(e,t),t.defaultPrevented||(n.current=!0,"pointerdown"===t.detail.originalEvent.type&&(s.current=!0));const a=t.target;(null===(o=i.triggerRef.current)||void 0===o?void 0:o.contains(a))&&t.preventDefault(),"focusin"===t.detail.originalEvent.type&&s.current&&t.preventDefault()}}))})),vE=t.forwardRef(((e,r)=>{const{__scopePopover:i,trapFocus:n,onOpenAutoFocus:s,onCloseAutoFocus:o,disableOutsidePointerEvents:a,onEscapeKeyDown:c,onPointerDownOutside:d,onFocusOutside:l,onInteractOutside:u,...p}=e,h=cE(hE,i),f=oE(i);return t.useEffect((()=>{var e,t;const r=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",null!==(e=r[0])&&void 0!==e?e:oT()),document.body.insertAdjacentElement("beforeend",null!==(t=r[1])&&void 0!==t?t:oT()),sT++,()=>{1===sT&&document.querySelectorAll("[data-radix-focus-guard]").forEach((e=>e.remove())),sT--}}),[]),t.createElement(lT,{asChild:!0,loop:!0,trapped:n,onMountAutoFocus:s,onUnmountAutoFocus:o},t.createElement(rT,{asChild:!0,disableOutsidePointerEvents:a,onInteractOutside:u,onEscapeKeyDown:c,onPointerDownOutside:d,onFocusOutside:l,onDismiss:()=>h.onOpenChange(!1)},t.createElement(aO,Bk({"data-state":bE(h.open),role:"dialog",id:h.contentId},f,p,{ref:r,style:{...p.style,"--radix-popover-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-popover-content-available-width":"var(--radix-popper-available-width)","--radix-popover-content-available-height":"var(--radix-popper-available-height)","--radix-popover-trigger-width":"var(--radix-popper-anchor-width)","--radix-popover-trigger-height":"var(--radix-popper-anchor-height)"}}))))}));function bE(e){return e?"open":"closed"}const yE=e=>{const{__scopePopover:r,forceMount:i,children:n,container:s}=e,o=cE(lE,r);return t.createElement(uE,{scope:r,forceMount:i},t.createElement(dO,{present:i||o.open},t.createElement(cO,{asChild:!0,container:s},n)))},wE=fE,_E=e=>{const{__scopePopover:r,children:i,open:n,defaultOpen:s,onOpenChange:o,modal:a=!1}=e,c=oE(r),d=t.useRef(null),[l,u]=t.useState(!1),[p=!1,h]=uO({prop:n,defaultProp:s,onChange:o});return t.createElement(sO,c,t.createElement(aE,{scope:r,contentId:wT(),triggerRef:d,open:p,onOpenChange:h,onOpenToggle:t.useCallback((()=>h((e=>!e))),[h]),hasCustomAnchor:l,onCustomAnchorAdd:t.useCallback((()=>u(!0)),[]),onCustomAnchorRemove:t.useCallback((()=>u(!1)),[]),modal:a},i))},SE=dE,CE=s.forwardRef(((e,t)=>{var{style:r,align:i="center",sideOffset:n=4}=e,o=dR(e,["style","align","sideOffset"]);return s.createElement(yE,null,s.createElement(wE,Object.assign({ref:t,align:i,sideOffset:n,style:Object.assign({width:"200px",backgroundColor:"#fff",border:"1px solid #e5e5e5",borderRadius:"0.375rem",boxShadow:"0 1px 2px 0 rgb(0 0 0 / 0.05)",color:"#333",fontSize:"14px",lineHeight:"1.5",padding:"16px",zIndex:50,outline:"none"},r)},o)))}));CE.displayName=wE.displayName;const RE=s.createContext({}),kE=s.createContext({}),TE=()=>{const e=s.useContext(RE),t=s.useContext(kE);if(!t)throw new Error("useGridCell must be used within a GridCell");return Object.assign(Object.assign({},e),t)},PE=s.createContext({}),OE=e=>{const{children:t}=e,r=dR(e,["children"]),[i,n]=s.useState(!1);return s.createElement(PE.Provider,{value:{open:i,setOpen:n}},s.createElement(_E,Object.assign({},r,{open:i,onOpenChange:n}),t))},EE=s.forwardRef(((e,t)=>{var{children:r,style:i}=e,n=dR(e,["children","style"]);return s.createElement(CE,Object.assign({ref:t,style:Object.assign({display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",minWidth:"180px",maxWidth:"300px",maxHeight:"100vh",overflowY:"auto",padding:0},i)},n),r)}));EE.displayName="ParticipantMenuContent";const DE=s.forwardRef(((e,t)=>{var{children:r,style:i}=e,n=dR(e,["children","style"]);return s.createElement(SE,Object.assign({ref:t,style:Object.assign({position:"absolute",top:"10px",right:"20px",textDecoration:"none",whiteSpace:"nowrap",border:"none",cursor:"pointer"},i)},n),r)}));DE.displayName=SE.displayName;const IE=s.forwardRef(((e,t)=>{var{children:r,style:i,participantAction:n}=e,o=dR(e,["children","style","participantAction"]);const{participant:a,setOpen:c,maximizedParticipant:d,setMaximizedParticipant:l,setFloatingParticipant:u,floatingParticipant:p}=(()=>{const e=s.useContext(PE),t=TE();if(!e)throw new Error("useParticipantMenu must be used within a ParticipantMenu");return Object.assign(Object.assign({},e),t)})(),h=lR(),f=uR(uS).find((e=>e.id===a.id)),m=(null==d?void 0:d.id)===a.id,g=(null==p?void 0:p.id)===a.id;let v;switch(n){case"maximize":v=()=>{l(m?null:a),c(!1)};break;case"spotlight":v=()=>{h(f?dS({id:a.id}):cS({id:a.id})),c(!1)};break;case"float":v=()=>{u(g?null:a),c(!1)}}return s.createElement("button",Object.assign({ref:t,role:"menuitem",tabIndex:-1,onClick:null!=v?v:o.onClick,style:Object.assign({alignItems:"stretch",backgroundColor:"transparent",border:"none",cursor:"pointer",display:"flex",height:"40px",lineHeight:"40px",minWidth:"140px",padding:"0 12px",textAlign:"left",textDecoration:"none",whiteSpace:"nowrap",width:"100%"},i)},o),r)}));function xE(e){return s.createElement("svg",Object.assign({width:"100%",height:"100%",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},e),s.createElement("g",null,s.createElement("circle",{cx:"6",cy:"12",r:"2"}),s.createElement("circle",{cx:"12",cy:"12",r:"2"}),s.createElement("circle",{cx:"18",cy:"12",r:"2"})))}function ME(e){return s.createElement("svg",Object.assign({width:"100%",height:"100%",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},e),s.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"m13.875 3c0 .62132.5037 1.125 1.125 1.125h3.284l-4.0795 4.0795c-.4393.43934-.4393 1.15166 0 1.591.4393.4393 1.1517.4393 1.591 0l4.0795-4.07951v3.28401c0 .62132.5037 1.125 1.125 1.125s1.125-.50368 1.125-1.125v-6c0-.15254-.0304-.29799-.0854-.43063-.0536-.12968-.1326-.25135-.2368-.35749l-.0147-.01469c-.203-.19928-.4812-.32219-.7881-.32219h-6c-.6213 0-1.125.50368-1.125 1.125zm-9.75 12c0-.6213-.50368-1.125-1.125-1.125s-1.125.5037-1.125 1.125v6c0 .3069.12291.5851.32219.7881.00486.005.00975.0099.01469.0147.10614.1042.22781.1832.35749.2368.13264.055.27809.0854.43063.0854h6c.62132 0 1.125-.5037 1.125-1.125s-.50368-1.125-1.125-1.125h-3.28401l4.07951-4.0795c.4393-.4393.4393-1.1517 0-1.591-.43934-.4393-1.15166-.4393-1.591 0l-4.0795 4.0795z"}))}function jE(e){return s.createElement("svg",Object.assign({width:"100%",height:"100%",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},e),s.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"m15.241.146691c-.1011-.1955882-.3809-.1955879-.482 0l-1.1063 2.139639c-.0258.04991-.0665.09058-.1164.11639l-2.1396 1.10629c-.1956.10113-.1956.38085 0 .48198l2.1396 1.10629c.0499.02581.0906.06648.1164.11639l1.1063 2.13964c.1011.19559.3809.19559.482 0l1.1063-2.13964c.0258-.04991.0665-.09058.1164-.11639l2.1396-1.10629c.1956-.10113.1956-.38085 0-.48198l-2.1396-1.10629c-.0499-.02581-.0906-.06648-.1164-.11639zm-13.741 2.900259v14.67495c0 .0511.00116.1018.00345.1523-.00229.0418-.00345.0837-.00345.1258 0 .5674.21005 1.1103.59339 1.6103.24265.3472.55042.6455.90566.8773 1.61225 1.213 4.36988 2.0124 7.50095 2.0124 4.3315 0 7.9484-1.53 8.8068-3.5681.0651-.1472.1148-.3024.1455-.4658.0315-.1532.0477-.3087.0477-.4661 0-.6032-.2374-1.1788-.668-1.7045-.1377-.1975-.2995-.4017-.4877-.6127l-14.22219-13.74809c-.28845-.27884-.67396-.43471-1.07516-.43471-.85436 0-1.54695.69259-1.54695 1.54695zm19.2646 4.59631c.0988-.19101.372-.19101.4708 0l.8546 1.65303c.0253.04874.065.08846.1137.11366l1.653.85465c.1911.0988.1911.372 0 .4708l-1.653.8546c-.0487.0253-.0884.065-.1137.1137l-.8546 1.653c-.0988.1911-.372.1911-.4708 0l-.8546-1.653c-.0253-.0487-.065-.0884-.1137-.1137l-1.653-.8546c-.1911-.0988-.1911-.372 0-.4708l1.653-.85465c.0487-.0252.0884-.06492.1137-.11366zm-3.2651 10.35684c0 .0769-.1144.6851-1.5305 1.3931-1.2964.6482-3.2274 1.1069-5.4695 1.1069s-4.17308-.4587-5.46952-1.1069c-1.41607-.708-1.53047-1.3162-1.53047-1.3931 0-.077.1144-.6851 1.53047-1.3932 1.29644-.6482 3.22742-1.1068 5.46952-1.1068s4.1731.4586 5.4695 1.1068c1.4161.7081 1.5305 1.3162 1.5305 1.3932z"}))}function LE(e){return s.createElement("svg",Object.assign({width:"100%",height:"100%",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},e),s.createElement("path",{clipRule:"evenodd",fillRule:"evenodd",d:"m2.25 3v4.5c0 .41421.33579.75.75.75h4.5c.41421 0 .75-.33579.75-.75v-4.5c0-.41421-.33579-.75-.75-.75h-4.5c-.41421 0-.75.33579-.75.75zm-2.25 4.5v-4.5c0-1.65685 1.34315-3 3-3h4.5c1.65685 0 3 1.34315 3 3v4.5c0 1.65685-1.34315 3-3 3h-4.5c-1.65685 0-3-1.34315-3-3zm2.25 9v4.5c0 .4142.33579.75.75.75h4.5c.41421 0 .75-.3358.75-.75v-4.5c0-.4142-.33579-.75-.75-.75h-4.5c-.41421 0-.75.3358-.75.75zm-2.25 4.5v-4.5c0-1.6569 1.34315-3 3-3h4.5c1.65685 0 3 1.3431 3 3v4.5c0 1.6569-1.34315 3-3 3h-4.5c-1.65685 0-3-1.3431-3-3zm15.75-13.5v-4.5c0-.41421.3358-.75.75-.75h4.5c.4142 0 .75.33579.75.75v4.5c0 .41421-.3358.75-.75.75h-4.5c-.4142 0-.75-.33579-.75-.75zm-2.25-4.5v4.5c0 1.65685 1.3431 3 3 3h4.5c1.6569 0 3-1.34315 3-3v-4.5c0-1.65685-1.3431-3-3-3h-4.5c-1.6569 0-3 1.34315-3 3zm1.875 19.5c0-.6213.5037-1.125 1.125-1.125h3.284l-5.5795-5.5795c-.4393-.4393-.4393-1.1517 0-1.591s1.1517-.4393 1.591 0l5.5795 5.5795v-3.284c0-.6213.5037-1.125 1.125-1.125s1.125.5037 1.125 1.125v6c0 .308-.1238.5872-.3244.7903-.0033.0034-.0067.0068-.0101.0102-.1067.1054-.2292.1851-.3599.2391-.1326.055-.2781.0854-.4306.0854h-6c-.6213 0-1.125-.5037-1.125-1.125z"}))}function AE(e){return s.createElement("svg",Object.assign({width:"100%",height:"100%",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},e),s.createElement("path",{clipRule:"evenodd",fillRule:"evenodd",d:"m2.25 3v4.5c0 .41421.33579.75.75.75h4.5c.41421 0 .75-.33579.75-.75v-4.5c0-.41421-.33579-.75-.75-.75h-4.5c-.41421 0-.75.33579-.75.75zm-2.25 4.5v-4.5c0-1.65685 1.34315-3 3-3h4.5c1.65685 0 3 1.34315 3 3v4.5c0 1.65685-1.34315 3-3 3h-4.5c-1.65685 0-3-1.34315-3-3zm2.25 9v4.5c0 .4142.33579.75.75.75h4.5c.41421 0 .75-.3358.75-.75v-4.5c0-.4142-.33579-.75-.75-.75h-4.5c-.41421 0-.75.3358-.75.75zm-2.25 4.5v-4.5c0-1.6569 1.34315-3 3-3h4.5c1.65685 0 3 1.3431 3 3v4.5c0 1.6569-1.34315 3-3 3h-4.5c-1.65685 0-3-1.3431-3-3zm15.75-13.5v-4.5c0-.41421.3358-.75.75-.75h4.5c.4142 0 .75.33579.75.75v4.5c0 .41421-.3358.75-.75.75h-4.5c-.4142 0-.75-.33579-.75-.75zm-2.25-4.5v4.5c0 1.65685 1.3431 3 3 3h4.5c1.6569 0 3-1.34315 3-3v-4.5c0-1.65685-1.3431-3-3-3h-4.5c-1.6569 0-3 1.34315-3 3zm8.625 12c0 .6213-.5037 1.125-1.125 1.125h-3.284l5.5795 5.5795c.4393.4393.4393 1.1517 0 1.591s-1.1517.4393-1.591 0l-5.5795-5.5795v3.284c0 .6213-.5037 1.125-1.125 1.125s-1.125-.5037-1.125-1.125v-6c0-.3081.1238-.5872.3244-.7904.0034-.0034.0068-.0068.0102-.0102.1067-.1053.2292-.185.3598-.239.1326-.055.2781-.0854.4306-.0854h6c.6213 0 1.125.5037 1.125 1.125z"}))}function NE({participant:e}){const t=uR(uS).find((t=>t.id===e.id)),{isHovered:r,maximizedParticipant:i,floatingParticipant:n}=TE(),o=(null==i?void 0:i.id)===e.id,a=(null==n?void 0:n.id)===e.id;return r?s.createElement(OE,null,s.createElement(DE,{style:{display:"flex",justifyContent:"center",alignItems:"center",backgroundColor:"#fff",borderRadius:"6px",padding:"4px"}},s.createElement(xE,{height:20,width:20,transform:"rotate(90)"})),s.createElement(EE,null,e.isLocalClient?s.createElement(IE,{participantAction:"float",style:{display:"flex",alignItems:"center",gap:"10px"}},a?s.createElement(s.Fragment,null,s.createElement(AE,{height:16,width:16}),"Move to grid"):s.createElement(s.Fragment,null,s.createElement(LE,{height:16,width:16}),"Pop out")):null,s.createElement(IE,{participantAction:"maximize",style:{display:"flex",alignItems:"center",gap:"10px"}},s.createElement(ME,{height:16,width:16}),o?"Minimize":"Maximize"),s.createElement(IE,{participantAction:"spotlight",style:{display:"flex",alignItems:"center",gap:"10px"}},s.createElement(jE,{height:16,width:16}),t?"Remove spotlight":"Spotlight"))):null}IE.displayName="ParticipantMenuItem";const BE=s.forwardRef((({className:e,participant:t,children:r},i)=>{const[n,o]=s.useState(!1),a=s.useCallback((()=>{o(!0)}),[]),c=s.useCallback((()=>{o(!1)}),[]);return s.createElement(kE.Provider,{value:{participant:t,isHovered:n}},s.createElement("div",{ref:i,className:e,onMouseEnter:a,onMouseLeave:c,style:{height:"100%",width:"100%"}},r))}));BE.displayName="GridCell";const FE=s.forwardRef(((e,t)=>{var{stream:r,style:i}=e,n=dR(e,["stream","style"]);const o=s.useRef(null),{onSetClientAspectRatio:a,clientAspectRatios:c,participant:d,isConstrained:l}=TE();if(!d)return null;const u=c[d.id];s.useImperativeHandle(t,(()=>o.current));const p=s.useCallback((()=>{const e=o.current&&o.current.captureAspectRatio();e&&e!==u&&d.id&&a({aspectRatio:e,clientId:d.id})}),[c,d.id,a]),h=r||d.stream;return h?s.createElement(pR,Object.assign({ref:o,style:Object.assign(Object.assign({borderRadius:l?0:"8px"},l?{objectFit:"cover"}:{}),i),muted:d.isLocalClient},n,{stream:h,onVideoResize:p})):s.createElement(Nk,{isSmallCell:!1,displayName:(null==d?void 0:d.displayName)||"Guest",withRoundedCorners:!0})}));function zE({cellView:e,enableParticipantMenu:t,render:r}){const i=null==e?void 0:e.client;if(i)return"video"===e.type?s.createElement(BE,{participant:i},i.isVideoEnabled?s.createElement(s.Fragment,null,r?r({participant:i}):s.createElement(s.Fragment,null,s.createElement(FE,null),t?s.createElement(NE,{participant:i}):null)):s.createElement(Nk,{isSmallCell:!1,displayName:(null==i?void 0:i.displayName)||"Guest",withRoundedCorners:!0})):void 0}return FE.displayName="GridVideoView",e.GridCell=BE,e.GridVideoView=FE,e.ParticipantMenu=OE,e.ParticipantMenuContent=EE,e.ParticipantMenuItem=IE,e.ParticipantMenuTrigger=DE,e.VideoGrid=function({renderParticipant:e,renderFloatingParticipant:t,stageParticipantLimit:r,gridGap:i,videoGridGap:n,enableSubgrid:o,enableParticipantMenu:a,enableConstrainedGrid:c}){const d=s.useRef(null),{containerFrame:l,cellViewsFloating:u,cellViewsVideoGrid:p,cellViewsInPresentationGrid:h,cellViewsInSubgrid:f,clientAspectRatios:m,videoStage:g,setContainerBounds:v,setClientAspectRatios:b,maximizedParticipant:y,setMaximizedParticipant:w,isConstrained:_,floatingParticipant:S,setFloatingParticipant:C}=function({activeVideosSubgridTrigger:e,forceSubgrid:t,stageParticipantLimit:r=ak,gridGap:i=8,videoGridGap:n=8,enableSubgrid:o=!0,enableConstrainedGrid:a=!0}={}){const[c,d]=s.useState({width:0,height:0}),[l,u]=s.useState(!1),[p,h]=s.useState({}),[f,m]=s.useState(null),[g,v]=s.useState(null),{clientViewsInGrid:b,clientViewsInPresentationGrid:y,clientViewsInSubgrid:w,floatingClientView:_}=lk({activeVideosSubgridTrigger:e,forceSubgrid:t,stageParticipantLimit:r,enableSubgrid:o,maximizedParticipant:f,floatingParticipant:g,isConstrained:!!a&&!!l}),S=s.useMemo((()=>_?[ok({client:_,aspectRatio:p[_.id],avatarSize:0,cellPaddings:{top:0,right:0}})]:[]),[_,p]),C=s.useMemo((()=>b.map((e=>ok({client:e,aspectRatio:p[e.id],avatarSize:0,cellPaddings:{top:0,right:0}})))),[b,p]),R=s.useMemo((()=>y.map((e=>ok({client:e,aspectRatio:p[e.id],avatarSize:0,cellPaddings:{top:0,right:0}})))),[y,p]),k=s.useMemo((()=>w.map((e=>ok({client:e,aspectRatio:p[e.id],avatarSize:0,cellPaddings:{top:0,right:0},isSubgrid:!0})))),[w,p]),T=s.useMemo((()=>yR(c)),[c]);s.useEffect((()=>{a&&u(c.width<500||c.height<500)}),[c,a]);const P=s.useMemo((()=>sk({floatingVideo:S[0],frame:T,gridGap:i,isConstrained:l,roomBounds:T.bounds,videos:C,videoGridGap:n,presentationVideos:R,subgridVideos:k})),[T,S,C,R,k,i,n]);return{containerFrame:T,cellViewsFloating:S,cellViewsVideoGrid:C,cellViewsInPresentationGrid:R,cellViewsInSubgrid:k,clientAspectRatios:p,videoStage:P,setContainerBounds:d,setClientAspectRatios:h,maximizedParticipant:f,setMaximizedParticipant:m,floatingParticipant:g,setFloatingParticipant:v,isConstrained:l}}({activeVideosSubgridTrigger:12,stageParticipantLimit:r,gridGap:i,videoGridGap:n,enableSubgrid:o,enableConstrainedGrid:c}),R=s.useCallback((({aspectRatio:e,clientId:t})=>{b((r=>Object.assign(Object.assign({},r),{[t]:e})))}),[b]),k=s.useMemo((()=>zE(Object.assign({cellView:u[0],enableParticipantMenu:a},t?{render:({participant:e})=>t({participant:e})}:{}))),[u]),T=s.useMemo((()=>h.map((t=>zE(Object.assign({cellView:t,enableParticipantMenu:a},e?{render:({participant:t})=>e({participant:t})}:{}))))),[h]),P=s.useMemo((()=>p.map((t=>zE(Object.assign({cellView:t,enableParticipantMenu:a},e?{render:({participant:t})=>e({participant:t})}:{}))))),[p]),O=s.useMemo((()=>f.map((e=>zE({cellView:e,enableParticipantMenu:a})))),[f]);return s.useEffect((()=>{if(!d.current)return;const e=new ResizeObserver(yw((()=>{var e,t,r,i;v({width:null!==(t=null===(e=d.current)||void 0===e?void 0:e.clientWidth)&&void 0!==t?t:640,height:null!==(i=null===(r=d.current)||void 0===r?void 0:r.clientHeight)&&void 0!==i?i:480})}),{delay:60,edges:!1}));return e.observe(d.current),()=>{e.disconnect()}}),[]),s.createElement(RE.Provider,{value:{onSetClientAspectRatio:R,cellViewsVideoGrid:p,cellViewsInPresentationGrid:h,cellViewsInSubgrid:f,clientAspectRatios:m,maximizedParticipant:y,setMaximizedParticipant:w,floatingParticipant:S,setFloatingParticipant:C,isConstrained:_}},s.createElement("div",{ref:d,style:{width:"100%",height:"100%",position:"relative"}},s.createElement(OR,{containerFrame:l,floatingContent:k,layoutVideoStage:g,presentationGridContent:T,gridContent:P,subgridContent:O})))},e.VideoView=pR,e.WherebyProvider=function({children:e}){const t=(({preloadedState:e,injectServices:t})=>gt({devTools:wC,reducer:SC,middleware:e=>e({thunk:{extraArgument:{services:t}},serializableCheck:!1}).prepend(Ty.middleware),preloadedState:e}))({injectServices:function(){const e=XC.create({baseUrl:nR}),t=new BC({fetchDeviceCredentials:e.getCredentials.bind(e),baseUrl:nR}),r=new rR({apiClient:t});return{credentialsService:e,apiClient:t,organizationService:r,fetchOrganizationFromRoomUrl:e=>{const t=Ig({host:new URL(e).host});return new iR({organizationService:r,subdomain:t.subdomain}).fetchOrganization()}}}()});return s.createElement(T,{context:sR,store:t},e)},e.useLocalMedia=function(e={audio:!0,video:!0}){const t=lR(),r=uR(mR);return s.useEffect((()=>(t(Bw(e)),()=>{t(Fw())})),[]),{state:r,actions:{setCameraDevice:s.useCallback((e=>t(Sw({deviceId:e}))),[t]),setMicrophoneDevice:s.useCallback((e=>t(Cw({deviceId:e}))),[t]),setSpeakerDevice:s.useCallback((e=>t(Rw({deviceId:e}))),[t]),toggleCameraEnabled:s.useCallback((e=>t(kw({enabled:e}))),[t]),toggleMicrophoneEnabled:s.useCallback((e=>t(Tw({enabled:e}))),[t]),toggleLowDataModeEnabled:s.useCallback((e=>t(Pw({enabled:e}))),[t])}}},e.useRoomConnection=function(e,t=fR){const r=lR(),i=uR(hR),n=s.useMemo((()=>{const r=new URL(e),i=new URLSearchParams(r.search),n=t.roomKey||i.get("roomKey");return{displayName:t.displayName||"Guest",localMediaOptions:t.localMedia?void 0:t.localMediaOptions,roomKey:n,roomUrl:e,userAgent:"browser-sdk:3.12.3",externalId:t.externalId||null}}),[e,t]);s.useEffect((()=>()=>{r(Dy())}),[]);const o=s.useCallback((e=>r(y_({text:e}))),[r]),a=s.useCallback((()=>r(cC())),[r]),c=s.useCallback((e=>r(KS({displayName:e}))),[r]),d=s.useCallback((e=>r(kw({enabled:e}))),[r]),l=s.useCallback((e=>r(Tw({enabled:e}))),[r]),u=s.useCallback((e=>r(Pw({enabled:e}))),[r]),p=s.useCallback((e=>r(QS({enabled:e}))),[r]),h=s.useCallback((e=>r(N_({clientIds:[e],enable:!0}))),[r]),f=s.useCallback((e=>r(B_({clientIds:[e],enable:!0}))),[r]),m=s.useCallback((e=>r(bC({participantId:e}))),[r]),g=s.useCallback((e=>r(yC({participantId:e}))),[r]),v=s.useCallback((()=>r(S_())),[r]),b=s.useCallback((()=>r(G_())),[r]),y=s.useCallback((()=>r(C_())),[r]),w=s.useCallback((()=>r(q_())),[r]),_=s.useCallback((()=>r(Iy(n))),[r]),S=s.useCallback((()=>r(Dy())),[r]),C=s.useCallback((e=>r(J_({locked:e}))),[r]),R=s.useCallback((e=>r(N_({clientIds:e,enable:!1}))),[r]),k=s.useCallback((e=>r(B_({clientIds:e,enable:!1}))),[r]),T=s.useCallback((e=>r(cS({id:e}))),[r]),P=s.useCallback((e=>r(dS({id:e}))),[r]),O=s.useCallback((e=>r(X_({clientId:e}))),[r]),E=s.useCallback((e=>r(Q_({stayBehind:e}))),[r]),D=s.useCallback((e=>r(p_({group:e}))),[r]),I=s.useCallback((()=>r(p_({group:""}))),[r]),{events:x}=i;return{state:dR(i,["events"]),events:x,actions:{toggleLowDataMode:u,toggleRaiseHand:p,askToSpeak:h,askToTurnOnCamera:f,acceptWaitingParticipant:m,knock:a,joinRoom:_,leaveRoom:S,lockRoom:C,muteParticipants:R,turnOffParticipantCameras:k,kickParticipant:O,endMeeting:E,rejectWaitingParticipant:g,sendChatMessage:o,setDisplayName:c,startCloudRecording:v,startScreenshare:b,stopCloudRecording:y,stopScreenshare:w,toggleCamera:d,toggleMicrophone:l,spotlightParticipant:T,removeSpotlight:P,joinBreakoutGroup:D,joinBreakoutMainRoom:I}}},e}({},React,ReactDOM);
|