matrix-art-preview

Page to land previews on for matrix art
git clone git://archive.git.mtrnord.blog/MTRNord/matrix-art-preview.git
Log | Files | Refs

vendor-95a06cbd.js (1278875B)


      1 function RR(e,t){for(var n=0;n<t.length;n++){const r=t[n];if(typeof r!="string"&&!Array.isArray(r)){for(const i in r)if(i!=="default"&&!(i in e)){const o=Object.getOwnPropertyDescriptor(r,i);o&&Object.defineProperty(e,i,o.get?o:{enumerable:!0,get:()=>r[i]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}var $e=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Lk(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function lf(e){if(e.__esModule)return e;var t=e.default;if(typeof t=="function"){var n=function r(){if(this instanceof r){var i=[null];i.push.apply(i,arguments);var o=Function.bind.apply(t,i);return new o}return t.apply(this,arguments)};n.prototype=t.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(e).forEach(function(r){var i=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(n,r,i.get?i:{enumerable:!0,get:function(){return e[r]}})}),n}var ia={},Nk={get exports(){return ia},set exports(e){ia=e}},uf={},Oe={},xk={get exports(){return Oe},set exports(e){Oe=e}},et={};/**
      2  * @license React
      3  * react.production.min.js
      4  *
      5  * Copyright (c) Facebook, Inc. and its affiliates.
      6  *
      7  * This source code is licensed under the MIT license found in the
      8  * LICENSE file in the root directory of this source tree.
      9  */var Cu=Symbol.for("react.element"),$k=Symbol.for("react.portal"),Uk=Symbol.for("react.fragment"),Bk=Symbol.for("react.strict_mode"),Fk=Symbol.for("react.profiler"),Kk=Symbol.for("react.provider"),jk=Symbol.for("react.context"),qk=Symbol.for("react.forward_ref"),Vk=Symbol.for("react.suspense"),Wk=Symbol.for("react.memo"),Hk=Symbol.for("react.lazy"),v_=Symbol.iterator;function Gk(e){return e===null||typeof e!="object"?null:(e=v_&&e[v_]||e["@@iterator"],typeof e=="function"?e:null)}var IR={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},CR=Object.assign,OR={};function pa(e,t,n){this.props=e,this.context=t,this.refs=OR,this.updater=n||IR}pa.prototype.isReactComponent={};pa.prototype.setState=function(e,t){if(typeof e!="object"&&typeof e!="function"&&e!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,t,"setState")};pa.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function PR(){}PR.prototype=pa.prototype;function wm(e,t,n){this.props=e,this.context=t,this.refs=OR,this.updater=n||IR}var bm=wm.prototype=new PR;bm.constructor=wm;CR(bm,pa.prototype);bm.isPureReactComponent=!0;var m_=Array.isArray,kR=Object.prototype.hasOwnProperty,Tm={current:null},MR={key:!0,ref:!0,__self:!0,__source:!0};function DR(e,t,n){var r,i={},o=null,a=null;if(t!=null)for(r in t.ref!==void 0&&(a=t.ref),t.key!==void 0&&(o=""+t.key),t)kR.call(t,r)&&!MR.hasOwnProperty(r)&&(i[r]=t[r]);var c=arguments.length-2;if(c===1)i.children=n;else if(1<c){for(var f=Array(c),v=0;v<c;v++)f[v]=arguments[v+2];i.children=f}if(e&&e.defaultProps)for(r in c=e.defaultProps,c)i[r]===void 0&&(i[r]=c[r]);return{$$typeof:Cu,type:e,key:o,ref:a,props:i,_owner:Tm.current}}function zk(e,t){return{$$typeof:Cu,type:e.type,key:t,ref:e.ref,props:e.props,_owner:e._owner}}function Rm(e){return typeof e=="object"&&e!==null&&e.$$typeof===Cu}function Yk(e){var t={"=":"=0",":":"=2"};return"$"+e.replace(/[=:]/g,function(n){return t[n]})}var y_=/\/+/g;function th(e,t){return typeof e=="object"&&e!==null&&e.key!=null?Yk(""+e.key):t.toString(36)}function Gc(e,t,n,r,i){var o=typeof e;(o==="undefined"||o==="boolean")&&(e=null);var a=!1;if(e===null)a=!0;else switch(o){case"string":case"number":a=!0;break;case"object":switch(e.$$typeof){case Cu:case $k:a=!0}}if(a)return a=e,i=i(a),e=r===""?"."+th(a,0):r,m_(i)?(n="",e!=null&&(n=e.replace(y_,"$&/")+"/"),Gc(i,t,n,"",function(v){return v})):i!=null&&(Rm(i)&&(i=zk(i,n+(!i.key||a&&a.key===i.key?"":(""+i.key).replace(y_,"$&/")+"/")+e)),t.push(i)),1;if(a=0,r=r===""?".":r+":",m_(e))for(var c=0;c<e.length;c++){o=e[c];var f=r+th(o,c);a+=Gc(o,t,n,f,i)}else if(f=Gk(e),typeof f=="function")for(e=f.call(e),c=0;!(o=e.next()).done;)o=o.value,f=r+th(o,c++),a+=Gc(o,t,n,f,i);else if(o==="object")throw t=String(e),Error("Objects are not valid as a React child (found: "+(t==="[object Object]"?"object with keys {"+Object.keys(e).join(", ")+"}":t)+"). If you meant to render a collection of children, use an array instead.");return a}function nc(e,t,n){if(e==null)return e;var r=[],i=0;return Gc(e,r,"","",function(o){return t.call(n,o,i++)}),r}function Qk(e){if(e._status===-1){var t=e._result;t=t(),t.then(function(n){(e._status===0||e._status===-1)&&(e._status=1,e._result=n)},function(n){(e._status===0||e._status===-1)&&(e._status=2,e._result=n)}),e._status===-1&&(e._status=0,e._result=t)}if(e._status===1)return e._result.default;throw e._result}var dn={current:null},zc={transition:null},Jk={ReactCurrentDispatcher:dn,ReactCurrentBatchConfig:zc,ReactCurrentOwner:Tm};et.Children={map:nc,forEach:function(e,t,n){nc(e,function(){t.apply(this,arguments)},n)},count:function(e){var t=0;return nc(e,function(){t++}),t},toArray:function(e){return nc(e,function(t){return t})||[]},only:function(e){if(!Rm(e))throw Error("React.Children.only expected to receive a single React element child.");return e}};et.Component=pa;et.Fragment=Uk;et.Profiler=Fk;et.PureComponent=wm;et.StrictMode=Bk;et.Suspense=Vk;et.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=Jk;et.cloneElement=function(e,t,n){if(e==null)throw Error("React.cloneElement(...): The argument must be a React element, but you passed "+e+".");var r=CR({},e.props),i=e.key,o=e.ref,a=e._owner;if(t!=null){if(t.ref!==void 0&&(o=t.ref,a=Tm.current),t.key!==void 0&&(i=""+t.key),e.type&&e.type.defaultProps)var c=e.type.defaultProps;for(f in t)kR.call(t,f)&&!MR.hasOwnProperty(f)&&(r[f]=t[f]===void 0&&c!==void 0?c[f]:t[f])}var f=arguments.length-2;if(f===1)r.children=n;else if(1<f){c=Array(f);for(var v=0;v<f;v++)c[v]=arguments[v+2];r.children=c}return{$$typeof:Cu,type:e.type,key:i,ref:o,props:r,_owner:a}};et.createContext=function(e){return e={$$typeof:jk,_currentValue:e,_currentValue2:e,_threadCount:0,Provider:null,Consumer:null,_defaultValue:null,_globalName:null},e.Provider={$$typeof:Kk,_context:e},e.Consumer=e};et.createElement=DR;et.createFactory=function(e){var t=DR.bind(null,e);return t.type=e,t};et.createRef=function(){return{current:null}};et.forwardRef=function(e){return{$$typeof:qk,render:e}};et.isValidElement=Rm;et.lazy=function(e){return{$$typeof:Hk,_payload:{_status:-1,_result:e},_init:Qk}};et.memo=function(e,t){return{$$typeof:Wk,type:e,compare:t===void 0?null:t}};et.startTransition=function(e){var t=zc.transition;zc.transition={};try{e()}finally{zc.transition=t}};et.unstable_act=function(){throw Error("act(...) is not supported in production builds of React.")};et.useCallback=function(e,t){return dn.current.useCallback(e,t)};et.useContext=function(e){return dn.current.useContext(e)};et.useDebugValue=function(){};et.useDeferredValue=function(e){return dn.current.useDeferredValue(e)};et.useEffect=function(e,t){return dn.current.useEffect(e,t)};et.useId=function(){return dn.current.useId()};et.useImperativeHandle=function(e,t,n){return dn.current.useImperativeHandle(e,t,n)};et.useInsertionEffect=function(e,t){return dn.current.useInsertionEffect(e,t)};et.useLayoutEffect=function(e,t){return dn.current.useLayoutEffect(e,t)};et.useMemo=function(e,t){return dn.current.useMemo(e,t)};et.useReducer=function(e,t,n){return dn.current.useReducer(e,t,n)};et.useRef=function(e){return dn.current.useRef(e)};et.useState=function(e){return dn.current.useState(e)};et.useSyncExternalStore=function(e,t,n){return dn.current.useSyncExternalStore(e,t,n)};et.useTransition=function(){return dn.current.useTransition()};et.version="18.2.0";(function(e){e.exports=et})(xk);const Xk=Lk(Oe),cg=RR({__proto__:null,default:Xk},[Oe]);/**
     10  * @license React
     11  * react-jsx-runtime.production.min.js
     12  *
     13  * Copyright (c) Facebook, Inc. and its affiliates.
     14  *
     15  * This source code is licensed under the MIT license found in the
     16  * LICENSE file in the root directory of this source tree.
     17  */var Zk=Oe,eM=Symbol.for("react.element"),tM=Symbol.for("react.fragment"),nM=Object.prototype.hasOwnProperty,rM=Zk.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,iM={key:!0,ref:!0,__self:!0,__source:!0};function AR(e,t,n){var r,i={},o=null,a=null;n!==void 0&&(o=""+n),t.key!==void 0&&(o=""+t.key),t.ref!==void 0&&(a=t.ref);for(r in t)nM.call(t,r)&&!iM.hasOwnProperty(r)&&(i[r]=t[r]);if(e&&e.defaultProps)for(r in t=e.defaultProps,t)i[r]===void 0&&(i[r]=t[r]);return{$$typeof:eM,type:e,key:o,ref:a,props:i,_owner:rM.current}}uf.Fragment=tM;uf.jsx=AR;uf.jsxs=AR;(function(e){e.exports=uf})(Nk);var __={},dg={},oM={get exports(){return dg},set exports(e){dg=e}},$n={},fg={},sM={get exports(){return fg},set exports(e){fg=e}},LR={};/**
     18  * @license React
     19  * scheduler.production.min.js
     20  *
     21  * Copyright (c) Facebook, Inc. and its affiliates.
     22  *
     23  * This source code is licensed under the MIT license found in the
     24  * LICENSE file in the root directory of this source tree.
     25  */(function(e){function t(F,H){var R=F.length;F.push(H);e:for(;0<R;){var P=R-1>>>1,K=F[P];if(0<i(K,H))F[P]=H,F[R]=K,R=P;else break e}}function n(F){return F.length===0?null:F[0]}function r(F){if(F.length===0)return null;var H=F[0],R=F.pop();if(R!==H){F[0]=R;e:for(var P=0,K=F.length,U=K>>>1;P<U;){var C=2*(P+1)-1,A=F[C],T=C+1,X=F[T];if(0>i(A,R))T<K&&0>i(X,A)?(F[P]=X,F[T]=R,P=T):(F[P]=A,F[C]=R,P=C);else if(T<K&&0>i(X,R))F[P]=X,F[T]=R,P=T;else break e}}return H}function i(F,H){var R=F.sortIndex-H.sortIndex;return R!==0?R:F.id-H.id}if(typeof performance=="object"&&typeof performance.now=="function"){var o=performance;e.unstable_now=function(){return o.now()}}else{var a=Date,c=a.now();e.unstable_now=function(){return a.now()-c}}var f=[],v=[],s=1,g=null,y=3,S=!1,m=!1,p=!1,_=typeof setTimeout=="function"?setTimeout:null,u=typeof clearTimeout=="function"?clearTimeout:null,l=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function d(F){for(var H=n(v);H!==null;){if(H.callback===null)r(v);else if(H.startTime<=F)r(v),H.sortIndex=H.expirationTime,t(f,H);else break;H=n(v)}}function h(F){if(p=!1,d(F),!m)if(n(f)!==null)m=!0,z(w);else{var H=n(v);H!==null&&W(h,H.startTime-F)}}function w(F,H){m=!1,p&&(p=!1,u(k),k=-1),S=!0;var R=y;try{for(d(H),g=n(f);g!==null&&(!(g.expirationTime>H)||F&&!B());){var P=g.callback;if(typeof P=="function"){g.callback=null,y=g.priorityLevel;var K=P(g.expirationTime<=H);H=e.unstable_now(),typeof K=="function"?g.callback=K:g===n(f)&&r(f),d(H)}else r(f);g=n(f)}if(g!==null)var U=!0;else{var C=n(v);C!==null&&W(h,C.startTime-H),U=!1}return U}finally{g=null,y=R,S=!1}}var E=!1,I=null,k=-1,M=5,L=-1;function B(){return!(e.unstable_now()-L<M)}function N(){if(I!==null){var F=e.unstable_now();L=F;var H=!0;try{H=I(!0,F)}finally{H?G():(E=!1,I=null)}}else E=!1}var G;if(typeof l=="function")G=function(){l(N)};else if(typeof MessageChannel<"u"){var D=new MessageChannel,x=D.port2;D.port1.onmessage=N,G=function(){x.postMessage(null)}}else G=function(){_(N,0)};function z(F){I=F,E||(E=!0,G())}function W(F,H){k=_(function(){F(e.unstable_now())},H)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(F){F.callback=null},e.unstable_continueExecution=function(){m||S||(m=!0,z(w))},e.unstable_forceFrameRate=function(F){0>F||125<F?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):M=0<F?Math.floor(1e3/F):5},e.unstable_getCurrentPriorityLevel=function(){return y},e.unstable_getFirstCallbackNode=function(){return n(f)},e.unstable_next=function(F){switch(y){case 1:case 2:case 3:var H=3;break;default:H=y}var R=y;y=H;try{return F()}finally{y=R}},e.unstable_pauseExecution=function(){},e.unstable_requestPaint=function(){},e.unstable_runWithPriority=function(F,H){switch(F){case 1:case 2:case 3:case 4:case 5:break;default:F=3}var R=y;y=F;try{return H()}finally{y=R}},e.unstable_scheduleCallback=function(F,H,R){var P=e.unstable_now();switch(typeof R=="object"&&R!==null?(R=R.delay,R=typeof R=="number"&&0<R?P+R:P):R=P,F){case 1:var K=-1;break;case 2:K=250;break;case 5:K=1073741823;break;case 4:K=1e4;break;default:K=5e3}return K=R+K,F={id:s++,callback:H,priorityLevel:F,startTime:R,expirationTime:K,sortIndex:-1},R>P?(F.sortIndex=R,t(v,F),n(f)===null&&F===n(v)&&(p?(u(k),k=-1):p=!0,W(h,R-P))):(F.sortIndex=K,t(f,F),m||S||(m=!0,z(w))),F},e.unstable_shouldYield=B,e.unstable_wrapCallback=function(F){var H=y;return function(){var R=y;y=H;try{return F.apply(this,arguments)}finally{y=R}}}})(LR);(function(e){e.exports=LR})(sM);/**
     26  * @license React
     27  * react-dom.production.min.js
     28  *
     29  * Copyright (c) Facebook, Inc. and its affiliates.
     30  *
     31  * This source code is licensed under the MIT license found in the
     32  * LICENSE file in the root directory of this source tree.
     33  */var NR=Oe,Nn=fg;function we(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,n=1;n<arguments.length;n++)t+="&args[]="+encodeURIComponent(arguments[n]);return"Minified React error #"+e+"; visit "+t+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}var xR=new Set,eu={};function Xo(e,t){oa(e,t),oa(e+"Capture",t)}function oa(e,t){for(eu[e]=t,e=0;e<t.length;e++)xR.add(t[e])}var ii=!(typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),hg=Object.prototype.hasOwnProperty,aM=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,S_={},E_={};function lM(e){return hg.call(E_,e)?!0:hg.call(S_,e)?!1:aM.test(e)?E_[e]=!0:(S_[e]=!0,!1)}function uM(e,t,n,r){if(n!==null&&n.type===0)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return r?!1:n!==null?!n.acceptsBooleans:(e=e.toLowerCase().slice(0,5),e!=="data-"&&e!=="aria-");default:return!1}}function cM(e,t,n,r){if(t===null||typeof t>"u"||uM(e,t,n,r))return!0;if(r)return!1;if(n!==null)switch(n.type){case 3:return!t;case 4:return t===!1;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}function fn(e,t,n,r,i,o,a){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=r,this.attributeNamespace=i,this.mustUseProperty=n,this.propertyName=e,this.type=t,this.sanitizeURL=o,this.removeEmptyString=a}var Vt={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){Vt[e]=new fn(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];Vt[t]=new fn(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){Vt[e]=new fn(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){Vt[e]=new fn(e,2,!1,e,null,!1,!1)});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(e){Vt[e]=new fn(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){Vt[e]=new fn(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){Vt[e]=new fn(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){Vt[e]=new fn(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){Vt[e]=new fn(e,5,!1,e.toLowerCase(),null,!1,!1)});var Im=/[\-:]([a-z])/g;function Cm(e){return e[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(e){var t=e.replace(Im,Cm);Vt[t]=new fn(t,1,!1,e,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(e){var t=e.replace(Im,Cm);Vt[t]=new fn(t,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(e){var t=e.replace(Im,Cm);Vt[t]=new fn(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){Vt[e]=new fn(e,1,!1,e.toLowerCase(),null,!1,!1)});Vt.xlinkHref=new fn("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){Vt[e]=new fn(e,1,!1,e.toLowerCase(),null,!0,!0)});function Om(e,t,n,r){var i=Vt.hasOwnProperty(t)?Vt[t]:null;(i!==null?i.type!==0:r||!(2<t.length)||t[0]!=="o"&&t[0]!=="O"||t[1]!=="n"&&t[1]!=="N")&&(cM(t,n,i,r)&&(n=null),r||i===null?lM(t)&&(n===null?e.removeAttribute(t):e.setAttribute(t,""+n)):i.mustUseProperty?e[i.propertyName]=n===null?i.type===3?!1:"":n:(t=i.attributeName,r=i.attributeNamespace,n===null?e.removeAttribute(t):(i=i.type,n=i===3||i===4&&n===!0?"":""+n,r?e.setAttributeNS(r,t,n):e.setAttribute(t,n))))}var li=NR.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED,rc=Symbol.for("react.element"),Ls=Symbol.for("react.portal"),Ns=Symbol.for("react.fragment"),Pm=Symbol.for("react.strict_mode"),pg=Symbol.for("react.profiler"),$R=Symbol.for("react.provider"),UR=Symbol.for("react.context"),km=Symbol.for("react.forward_ref"),gg=Symbol.for("react.suspense"),vg=Symbol.for("react.suspense_list"),Mm=Symbol.for("react.memo"),Ai=Symbol.for("react.lazy"),BR=Symbol.for("react.offscreen"),w_=Symbol.iterator;function Ma(e){return e===null||typeof e!="object"?null:(e=w_&&e[w_]||e["@@iterator"],typeof e=="function"?e:null)}var St=Object.assign,nh;function kl(e){if(nh===void 0)try{throw Error()}catch(n){var t=n.stack.trim().match(/\n( *(at )?)/);nh=t&&t[1]||""}return`
     34 `+nh+e}var rh=!1;function ih(e,t){if(!e||rh)return"";rh=!0;var n=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{if(t)if(t=function(){throw Error()},Object.defineProperty(t.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(t,[])}catch(v){var r=v}Reflect.construct(e,[],t)}else{try{t.call()}catch(v){r=v}e.call(t.prototype)}else{try{throw Error()}catch(v){r=v}e()}}catch(v){if(v&&r&&typeof v.stack=="string"){for(var i=v.stack.split(`
     35 `),o=r.stack.split(`
     36 `),a=i.length-1,c=o.length-1;1<=a&&0<=c&&i[a]!==o[c];)c--;for(;1<=a&&0<=c;a--,c--)if(i[a]!==o[c]){if(a!==1||c!==1)do if(a--,c--,0>c||i[a]!==o[c]){var f=`
     37 `+i[a].replace(" at new "," at ");return e.displayName&&f.includes("<anonymous>")&&(f=f.replace("<anonymous>",e.displayName)),f}while(1<=a&&0<=c);break}}}finally{rh=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?kl(e):""}function dM(e){switch(e.tag){case 5:return kl(e.type);case 16:return kl("Lazy");case 13:return kl("Suspense");case 19:return kl("SuspenseList");case 0:case 2:case 15:return e=ih(e.type,!1),e;case 11:return e=ih(e.type.render,!1),e;case 1:return e=ih(e.type,!0),e;default:return""}}function mg(e){if(e==null)return null;if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case Ns:return"Fragment";case Ls:return"Portal";case pg:return"Profiler";case Pm:return"StrictMode";case gg:return"Suspense";case vg:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case UR:return(e.displayName||"Context")+".Consumer";case $R:return(e._context.displayName||"Context")+".Provider";case km:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case Mm:return t=e.displayName||null,t!==null?t:mg(e.type)||"Memo";case Ai:t=e._payload,e=e._init;try{return mg(e(t))}catch{}}return null}function fM(e){var t=e.type;switch(e.tag){case 24:return"Cache";case 9:return(t.displayName||"Context")+".Consumer";case 10:return(t._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=t.render,e=e.displayName||e.name||"",t.displayName||(e!==""?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return t;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return mg(t);case 8:return t===Pm?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t}return null}function to(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function FR(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function hM(e){var t=FR(e)?"checked":"value",n=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),r=""+e[t];if(!e.hasOwnProperty(t)&&typeof n<"u"&&typeof n.get=="function"&&typeof n.set=="function"){var i=n.get,o=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return i.call(this)},set:function(a){r=""+a,o.call(this,a)}}),Object.defineProperty(e,t,{enumerable:n.enumerable}),{getValue:function(){return r},setValue:function(a){r=""+a},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function ic(e){e._valueTracker||(e._valueTracker=hM(e))}function KR(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=FR(e)?e.checked?"true":"false":e.value),e=r,e!==n?(t.setValue(e),!0):!1}function pd(e){if(e=e||(typeof document<"u"?document:void 0),typeof e>"u")return null;try{return e.activeElement||e.body}catch{return e.body}}function yg(e,t){var n=t.checked;return St({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function b_(e,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=to(t.value!=null?t.value:n),e._wrapperState={initialChecked:r,initialValue:n,controlled:t.type==="checkbox"||t.type==="radio"?t.checked!=null:t.value!=null}}function jR(e,t){t=t.checked,t!=null&&Om(e,"checked",t,!1)}function _g(e,t){jR(e,t);var n=to(t.value),r=t.type;if(n!=null)r==="number"?(n===0&&e.value===""||e.value!=n)&&(e.value=""+n):e.value!==""+n&&(e.value=""+n);else if(r==="submit"||r==="reset"){e.removeAttribute("value");return}t.hasOwnProperty("value")?Sg(e,t.type,n):t.hasOwnProperty("defaultValue")&&Sg(e,t.type,to(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function T_(e,t,n){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var r=t.type;if(!(r!=="submit"&&r!=="reset"||t.value!==void 0&&t.value!==null))return;t=""+e._wrapperState.initialValue,n||t===e.value||(e.value=t),e.defaultValue=t}n=e.name,n!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,n!==""&&(e.name=n)}function Sg(e,t,n){(t!=="number"||pd(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var Ml=Array.isArray;function Ys(e,t,n,r){if(e=e.options,t){t={};for(var i=0;i<n.length;i++)t["$"+n[i]]=!0;for(n=0;n<e.length;n++)i=t.hasOwnProperty("$"+e[n].value),e[n].selected!==i&&(e[n].selected=i),i&&r&&(e[n].defaultSelected=!0)}else{for(n=""+to(n),t=null,i=0;i<e.length;i++){if(e[i].value===n){e[i].selected=!0,r&&(e[i].defaultSelected=!0);return}t!==null||e[i].disabled||(t=e[i])}t!==null&&(t.selected=!0)}}function Eg(e,t){if(t.dangerouslySetInnerHTML!=null)throw Error(we(91));return St({},t,{value:void 0,defaultValue:void 0,children:""+e._wrapperState.initialValue})}function R_(e,t){var n=t.value;if(n==null){if(n=t.children,t=t.defaultValue,n!=null){if(t!=null)throw Error(we(92));if(Ml(n)){if(1<n.length)throw Error(we(93));n=n[0]}t=n}t==null&&(t=""),n=t}e._wrapperState={initialValue:to(n)}}function qR(e,t){var n=to(t.value),r=to(t.defaultValue);n!=null&&(n=""+n,n!==e.value&&(e.value=n),t.defaultValue==null&&e.defaultValue!==n&&(e.defaultValue=n)),r!=null&&(e.defaultValue=""+r)}function I_(e){var t=e.textContent;t===e._wrapperState.initialValue&&t!==""&&t!==null&&(e.value=t)}function VR(e){switch(e){case"svg":return"http://www.w3.org/2000/svg";case"math":return"http://www.w3.org/1998/Math/MathML";default:return"http://www.w3.org/1999/xhtml"}}function wg(e,t){return e==null||e==="http://www.w3.org/1999/xhtml"?VR(t):e==="http://www.w3.org/2000/svg"&&t==="foreignObject"?"http://www.w3.org/1999/xhtml":e}var oc,WR=function(e){return typeof MSApp<"u"&&MSApp.execUnsafeLocalFunction?function(t,n,r,i){MSApp.execUnsafeLocalFunction(function(){return e(t,n,r,i)})}:e}(function(e,t){if(e.namespaceURI!=="http://www.w3.org/2000/svg"||"innerHTML"in e)e.innerHTML=t;else{for(oc=oc||document.createElement("div"),oc.innerHTML="<svg>"+t.valueOf().toString()+"</svg>",t=oc.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function tu(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var Ul={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},pM=["Webkit","ms","Moz","O"];Object.keys(Ul).forEach(function(e){pM.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),Ul[t]=Ul[e]})});function HR(e,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||Ul.hasOwnProperty(e)&&Ul[e]?(""+t).trim():t+"px"}function GR(e,t){e=e.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,i=HR(n,t[n],r);n==="float"&&(n="cssFloat"),r?e.setProperty(n,i):e[n]=i}}var gM=St({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function bg(e,t){if(t){if(gM[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(we(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(we(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(we(61))}if(t.style!=null&&typeof t.style!="object")throw Error(we(62))}}function Tg(e,t){if(e.indexOf("-")===-1)return typeof t.is=="string";switch(e){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var Rg=null;function Dm(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var Ig=null,Qs=null,Js=null;function C_(e){if(e=ku(e)){if(typeof Ig!="function")throw Error(we(280));var t=e.stateNode;t&&(t=pf(t),Ig(e.stateNode,e.type,t))}}function zR(e){Qs?Js?Js.push(e):Js=[e]:Qs=e}function YR(){if(Qs){var e=Qs,t=Js;if(Js=Qs=null,C_(e),t)for(e=0;e<t.length;e++)C_(t[e])}}function QR(e,t){return e(t)}function JR(){}var oh=!1;function XR(e,t,n){if(oh)return e(t,n);oh=!0;try{return QR(e,t,n)}finally{oh=!1,(Qs!==null||Js!==null)&&(JR(),YR())}}function nu(e,t){var n=e.stateNode;if(n===null)return null;var r=pf(n);if(r===null)return null;n=r[t];e:switch(t){case"onClick":case"onClickCapture":case"onDoubleClick":case"onDoubleClickCapture":case"onMouseDown":case"onMouseDownCapture":case"onMouseMove":case"onMouseMoveCapture":case"onMouseUp":case"onMouseUpCapture":case"onMouseEnter":(r=!r.disabled)||(e=e.type,r=!(e==="button"||e==="input"||e==="select"||e==="textarea")),e=!r;break e;default:e=!1}if(e)return null;if(n&&typeof n!="function")throw Error(we(231,t,typeof n));return n}var Cg=!1;if(ii)try{var Da={};Object.defineProperty(Da,"passive",{get:function(){Cg=!0}}),window.addEventListener("test",Da,Da),window.removeEventListener("test",Da,Da)}catch{Cg=!1}function vM(e,t,n,r,i,o,a,c,f){var v=Array.prototype.slice.call(arguments,3);try{t.apply(n,v)}catch(s){this.onError(s)}}var Bl=!1,gd=null,vd=!1,Og=null,mM={onError:function(e){Bl=!0,gd=e}};function yM(e,t,n,r,i,o,a,c,f){Bl=!1,gd=null,vM.apply(mM,arguments)}function _M(e,t,n,r,i,o,a,c,f){if(yM.apply(this,arguments),Bl){if(Bl){var v=gd;Bl=!1,gd=null}else throw Error(we(198));vd||(vd=!0,Og=v)}}function Zo(e){var t=e,n=e;if(e.alternate)for(;t.return;)t=t.return;else{e=t;do t=e,t.flags&4098&&(n=t.return),e=t.return;while(e)}return t.tag===3?n:null}function ZR(e){if(e.tag===13){var t=e.memoizedState;if(t===null&&(e=e.alternate,e!==null&&(t=e.memoizedState)),t!==null)return t.dehydrated}return null}function O_(e){if(Zo(e)!==e)throw Error(we(188))}function SM(e){var t=e.alternate;if(!t){if(t=Zo(e),t===null)throw Error(we(188));return t!==e?null:e}for(var n=e,r=t;;){var i=n.return;if(i===null)break;var o=i.alternate;if(o===null){if(r=i.return,r!==null){n=r;continue}break}if(i.child===o.child){for(o=i.child;o;){if(o===n)return O_(i),e;if(o===r)return O_(i),t;o=o.sibling}throw Error(we(188))}if(n.return!==r.return)n=i,r=o;else{for(var a=!1,c=i.child;c;){if(c===n){a=!0,n=i,r=o;break}if(c===r){a=!0,r=i,n=o;break}c=c.sibling}if(!a){for(c=o.child;c;){if(c===n){a=!0,n=o,r=i;break}if(c===r){a=!0,r=o,n=i;break}c=c.sibling}if(!a)throw Error(we(189))}}if(n.alternate!==r)throw Error(we(190))}if(n.tag!==3)throw Error(we(188));return n.stateNode.current===n?e:t}function eI(e){return e=SM(e),e!==null?tI(e):null}function tI(e){if(e.tag===5||e.tag===6)return e;for(e=e.child;e!==null;){var t=tI(e);if(t!==null)return t;e=e.sibling}return null}var nI=Nn.unstable_scheduleCallback,P_=Nn.unstable_cancelCallback,EM=Nn.unstable_shouldYield,wM=Nn.unstable_requestPaint,Tt=Nn.unstable_now,bM=Nn.unstable_getCurrentPriorityLevel,Am=Nn.unstable_ImmediatePriority,rI=Nn.unstable_UserBlockingPriority,md=Nn.unstable_NormalPriority,TM=Nn.unstable_LowPriority,iI=Nn.unstable_IdlePriority,cf=null,Br=null;function RM(e){if(Br&&typeof Br.onCommitFiberRoot=="function")try{Br.onCommitFiberRoot(cf,e,void 0,(e.current.flags&128)===128)}catch{}}var gr=Math.clz32?Math.clz32:OM,IM=Math.log,CM=Math.LN2;function OM(e){return e>>>=0,e===0?32:31-(IM(e)/CM|0)|0}var sc=64,ac=4194304;function Dl(e){switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return e&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return e&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return e}}function yd(e,t){var n=e.pendingLanes;if(n===0)return 0;var r=0,i=e.suspendedLanes,o=e.pingedLanes,a=n&268435455;if(a!==0){var c=a&~i;c!==0?r=Dl(c):(o&=a,o!==0&&(r=Dl(o)))}else a=n&~i,a!==0?r=Dl(a):o!==0&&(r=Dl(o));if(r===0)return 0;if(t!==0&&t!==r&&!(t&i)&&(i=r&-r,o=t&-t,i>=o||i===16&&(o&4194240)!==0))return t;if(r&4&&(r|=n&16),t=e.entangledLanes,t!==0)for(e=e.entanglements,t&=r;0<t;)n=31-gr(t),i=1<<n,r|=e[n],t&=~i;return r}function PM(e,t){switch(e){case 1:case 2:case 4:return t+250;case 8:case 16:case 32:case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return t+5e3;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return-1;case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function kM(e,t){for(var n=e.suspendedLanes,r=e.pingedLanes,i=e.expirationTimes,o=e.pendingLanes;0<o;){var a=31-gr(o),c=1<<a,f=i[a];f===-1?(!(c&n)||c&r)&&(i[a]=PM(c,t)):f<=t&&(e.expiredLanes|=c),o&=~c}}function Pg(e){return e=e.pendingLanes&-1073741825,e!==0?e:e&1073741824?1073741824:0}function oI(){var e=sc;return sc<<=1,!(sc&4194240)&&(sc=64),e}function sh(e){for(var t=[],n=0;31>n;n++)t.push(e);return t}function Ou(e,t,n){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-gr(t),e[t]=n}function MM(e,t){var n=e.pendingLanes&~t;e.pendingLanes=t,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=t,e.mutableReadLanes&=t,e.entangledLanes&=t,t=e.entanglements;var r=e.eventTimes;for(e=e.expirationTimes;0<n;){var i=31-gr(n),o=1<<i;t[i]=0,r[i]=-1,e[i]=-1,n&=~o}}function Lm(e,t){var n=e.entangledLanes|=t;for(e=e.entanglements;n;){var r=31-gr(n),i=1<<r;i&t|e[r]&t&&(e[r]|=t),n&=~i}}var at=0;function sI(e){return e&=-e,1<e?4<e?e&268435455?16:536870912:4:1}var aI,Nm,lI,uI,cI,kg=!1,lc=[],Vi=null,Wi=null,Hi=null,ru=new Map,iu=new Map,Ni=[],DM="mousedown mouseup touchcancel touchend touchstart auxclick dblclick pointercancel pointerdown pointerup dragend dragstart drop compositionend compositionstart keydown keypress keyup input textInput copy cut paste click change contextmenu reset submit".split(" ");function k_(e,t){switch(e){case"focusin":case"focusout":Vi=null;break;case"dragenter":case"dragleave":Wi=null;break;case"mouseover":case"mouseout":Hi=null;break;case"pointerover":case"pointerout":ru.delete(t.pointerId);break;case"gotpointercapture":case"lostpointercapture":iu.delete(t.pointerId)}}function Aa(e,t,n,r,i,o){return e===null||e.nativeEvent!==o?(e={blockedOn:t,domEventName:n,eventSystemFlags:r,nativeEvent:o,targetContainers:[i]},t!==null&&(t=ku(t),t!==null&&Nm(t)),e):(e.eventSystemFlags|=r,t=e.targetContainers,i!==null&&t.indexOf(i)===-1&&t.push(i),e)}function AM(e,t,n,r,i){switch(t){case"focusin":return Vi=Aa(Vi,e,t,n,r,i),!0;case"dragenter":return Wi=Aa(Wi,e,t,n,r,i),!0;case"mouseover":return Hi=Aa(Hi,e,t,n,r,i),!0;case"pointerover":var o=i.pointerId;return ru.set(o,Aa(ru.get(o)||null,e,t,n,r,i)),!0;case"gotpointercapture":return o=i.pointerId,iu.set(o,Aa(iu.get(o)||null,e,t,n,r,i)),!0}return!1}function dI(e){var t=Lo(e.target);if(t!==null){var n=Zo(t);if(n!==null){if(t=n.tag,t===13){if(t=ZR(n),t!==null){e.blockedOn=t,cI(e.priority,function(){lI(n)});return}}else if(t===3&&n.stateNode.current.memoizedState.isDehydrated){e.blockedOn=n.tag===3?n.stateNode.containerInfo:null;return}}}e.blockedOn=null}function Yc(e){if(e.blockedOn!==null)return!1;for(var t=e.targetContainers;0<t.length;){var n=Mg(e.domEventName,e.eventSystemFlags,t[0],e.nativeEvent);if(n===null){n=e.nativeEvent;var r=new n.constructor(n.type,n);Rg=r,n.target.dispatchEvent(r),Rg=null}else return t=ku(n),t!==null&&Nm(t),e.blockedOn=n,!1;t.shift()}return!0}function M_(e,t,n){Yc(e)&&n.delete(t)}function LM(){kg=!1,Vi!==null&&Yc(Vi)&&(Vi=null),Wi!==null&&Yc(Wi)&&(Wi=null),Hi!==null&&Yc(Hi)&&(Hi=null),ru.forEach(M_),iu.forEach(M_)}function La(e,t){e.blockedOn===t&&(e.blockedOn=null,kg||(kg=!0,Nn.unstable_scheduleCallback(Nn.unstable_NormalPriority,LM)))}function ou(e){function t(i){return La(i,e)}if(0<lc.length){La(lc[0],e);for(var n=1;n<lc.length;n++){var r=lc[n];r.blockedOn===e&&(r.blockedOn=null)}}for(Vi!==null&&La(Vi,e),Wi!==null&&La(Wi,e),Hi!==null&&La(Hi,e),ru.forEach(t),iu.forEach(t),n=0;n<Ni.length;n++)r=Ni[n],r.blockedOn===e&&(r.blockedOn=null);for(;0<Ni.length&&(n=Ni[0],n.blockedOn===null);)dI(n),n.blockedOn===null&&Ni.shift()}var Xs=li.ReactCurrentBatchConfig,_d=!0;function NM(e,t,n,r){var i=at,o=Xs.transition;Xs.transition=null;try{at=1,xm(e,t,n,r)}finally{at=i,Xs.transition=o}}function xM(e,t,n,r){var i=at,o=Xs.transition;Xs.transition=null;try{at=4,xm(e,t,n,r)}finally{at=i,Xs.transition=o}}function xm(e,t,n,r){if(_d){var i=Mg(e,t,n,r);if(i===null)vh(e,t,r,Sd,n),k_(e,r);else if(AM(i,e,t,n,r))r.stopPropagation();else if(k_(e,r),t&4&&-1<DM.indexOf(e)){for(;i!==null;){var o=ku(i);if(o!==null&&aI(o),o=Mg(e,t,n,r),o===null&&vh(e,t,r,Sd,n),o===i)break;i=o}i!==null&&r.stopPropagation()}else vh(e,t,r,null,n)}}var Sd=null;function Mg(e,t,n,r){if(Sd=null,e=Dm(r),e=Lo(e),e!==null)if(t=Zo(e),t===null)e=null;else if(n=t.tag,n===13){if(e=ZR(t),e!==null)return e;e=null}else if(n===3){if(t.stateNode.current.memoizedState.isDehydrated)return t.tag===3?t.stateNode.containerInfo:null;e=null}else t!==e&&(e=null);return Sd=e,null}function fI(e){switch(e){case"cancel":case"click":case"close":case"contextmenu":case"copy":case"cut":case"auxclick":case"dblclick":case"dragend":case"dragstart":case"drop":case"focusin":case"focusout":case"input":case"invalid":case"keydown":case"keypress":case"keyup":case"mousedown":case"mouseup":case"paste":case"pause":case"play":case"pointercancel":case"pointerdown":case"pointerup":case"ratechange":case"reset":case"resize":case"seeked":case"submit":case"touchcancel":case"touchend":case"touchstart":case"volumechange":case"change":case"selectionchange":case"textInput":case"compositionstart":case"compositionend":case"compositionupdate":case"beforeblur":case"afterblur":case"beforeinput":case"blur":case"fullscreenchange":case"focus":case"hashchange":case"popstate":case"select":case"selectstart":return 1;case"drag":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"mousemove":case"mouseout":case"mouseover":case"pointermove":case"pointerout":case"pointerover":case"scroll":case"toggle":case"touchmove":case"wheel":case"mouseenter":case"mouseleave":case"pointerenter":case"pointerleave":return 4;case"message":switch(bM()){case Am:return 1;case rI:return 4;case md:case TM:return 16;case iI:return 536870912;default:return 16}default:return 16}}var Bi=null,$m=null,Qc=null;function hI(){if(Qc)return Qc;var e,t=$m,n=t.length,r,i="value"in Bi?Bi.value:Bi.textContent,o=i.length;for(e=0;e<n&&t[e]===i[e];e++);var a=n-e;for(r=1;r<=a&&t[n-r]===i[o-r];r++);return Qc=i.slice(e,1<r?1-r:void 0)}function Jc(e){var t=e.keyCode;return"charCode"in e?(e=e.charCode,e===0&&t===13&&(e=13)):e=t,e===10&&(e=13),32<=e||e===13?e:0}function uc(){return!0}function D_(){return!1}function Un(e){function t(n,r,i,o,a){this._reactName=n,this._targetInst=i,this.type=r,this.nativeEvent=o,this.target=a,this.currentTarget=null;for(var c in e)e.hasOwnProperty(c)&&(n=e[c],this[c]=n?n(o):o[c]);return this.isDefaultPrevented=(o.defaultPrevented!=null?o.defaultPrevented:o.returnValue===!1)?uc:D_,this.isPropagationStopped=D_,this}return St(t.prototype,{preventDefault:function(){this.defaultPrevented=!0;var n=this.nativeEvent;n&&(n.preventDefault?n.preventDefault():typeof n.returnValue!="unknown"&&(n.returnValue=!1),this.isDefaultPrevented=uc)},stopPropagation:function(){var n=this.nativeEvent;n&&(n.stopPropagation?n.stopPropagation():typeof n.cancelBubble!="unknown"&&(n.cancelBubble=!0),this.isPropagationStopped=uc)},persist:function(){},isPersistent:uc}),t}var ga={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(e){return e.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},Um=Un(ga),Pu=St({},ga,{view:0,detail:0}),$M=Un(Pu),ah,lh,Na,df=St({},Pu,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:Bm,button:0,buttons:0,relatedTarget:function(e){return e.relatedTarget===void 0?e.fromElement===e.srcElement?e.toElement:e.fromElement:e.relatedTarget},movementX:function(e){return"movementX"in e?e.movementX:(e!==Na&&(Na&&e.type==="mousemove"?(ah=e.screenX-Na.screenX,lh=e.screenY-Na.screenY):lh=ah=0,Na=e),ah)},movementY:function(e){return"movementY"in e?e.movementY:lh}}),A_=Un(df),UM=St({},df,{dataTransfer:0}),BM=Un(UM),FM=St({},Pu,{relatedTarget:0}),uh=Un(FM),KM=St({},ga,{animationName:0,elapsedTime:0,pseudoElement:0}),jM=Un(KM),qM=St({},ga,{clipboardData:function(e){return"clipboardData"in e?e.clipboardData:window.clipboardData}}),VM=Un(qM),WM=St({},ga,{data:0}),L_=Un(WM),HM={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},GM={8:"Backspace",9:"Tab",12:"Clear",13:"Enter",16:"Shift",17:"Control",18:"Alt",19:"Pause",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"NumLock",145:"ScrollLock",224:"Meta"},zM={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function YM(e){var t=this.nativeEvent;return t.getModifierState?t.getModifierState(e):(e=zM[e])?!!t[e]:!1}function Bm(){return YM}var QM=St({},Pu,{key:function(e){if(e.key){var t=HM[e.key]||e.key;if(t!=="Unidentified")return t}return e.type==="keypress"?(e=Jc(e),e===13?"Enter":String.fromCharCode(e)):e.type==="keydown"||e.type==="keyup"?GM[e.keyCode]||"Unidentified":""},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:Bm,charCode:function(e){return e.type==="keypress"?Jc(e):0},keyCode:function(e){return e.type==="keydown"||e.type==="keyup"?e.keyCode:0},which:function(e){return e.type==="keypress"?Jc(e):e.type==="keydown"||e.type==="keyup"?e.keyCode:0}}),JM=Un(QM),XM=St({},df,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0}),N_=Un(XM),ZM=St({},Pu,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:Bm}),eD=Un(ZM),tD=St({},ga,{propertyName:0,elapsedTime:0,pseudoElement:0}),nD=Un(tD),rD=St({},df,{deltaX:function(e){return"deltaX"in e?e.deltaX:"wheelDeltaX"in e?-e.wheelDeltaX:0},deltaY:function(e){return"deltaY"in e?e.deltaY:"wheelDeltaY"in e?-e.wheelDeltaY:"wheelDelta"in e?-e.wheelDelta:0},deltaZ:0,deltaMode:0}),iD=Un(rD),oD=[9,13,27,32],Fm=ii&&"CompositionEvent"in window,Fl=null;ii&&"documentMode"in document&&(Fl=document.documentMode);var sD=ii&&"TextEvent"in window&&!Fl,pI=ii&&(!Fm||Fl&&8<Fl&&11>=Fl),x_=String.fromCharCode(32),$_=!1;function gI(e,t){switch(e){case"keyup":return oD.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function vI(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var xs=!1;function aD(e,t){switch(e){case"compositionend":return vI(t);case"keypress":return t.which!==32?null:($_=!0,x_);case"textInput":return e=t.data,e===x_&&$_?null:e;default:return null}}function lD(e,t){if(xs)return e==="compositionend"||!Fm&&gI(e,t)?(e=hI(),Qc=$m=Bi=null,xs=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1<t.char.length)return t.char;if(t.which)return String.fromCharCode(t.which)}return null;case"compositionend":return pI&&t.locale!=="ko"?null:t.data;default:return null}}var uD={color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0};function U_(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t==="input"?!!uD[e.type]:t==="textarea"}function mI(e,t,n,r){zR(r),t=Ed(t,"onChange"),0<t.length&&(n=new Um("onChange","change",null,n,r),e.push({event:n,listeners:t}))}var Kl=null,su=null;function cD(e){OI(e,0)}function ff(e){var t=Bs(e);if(KR(t))return e}function dD(e,t){if(e==="change")return t}var yI=!1;if(ii){var ch;if(ii){var dh="oninput"in document;if(!dh){var B_=document.createElement("div");B_.setAttribute("oninput","return;"),dh=typeof B_.oninput=="function"}ch=dh}else ch=!1;yI=ch&&(!document.documentMode||9<document.documentMode)}function F_(){Kl&&(Kl.detachEvent("onpropertychange",_I),su=Kl=null)}function _I(e){if(e.propertyName==="value"&&ff(su)){var t=[];mI(t,su,e,Dm(e)),XR(cD,t)}}function fD(e,t,n){e==="focusin"?(F_(),Kl=t,su=n,Kl.attachEvent("onpropertychange",_I)):e==="focusout"&&F_()}function hD(e){if(e==="selectionchange"||e==="keyup"||e==="keydown")return ff(su)}function pD(e,t){if(e==="click")return ff(t)}function gD(e,t){if(e==="input"||e==="change")return ff(t)}function vD(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var yr=typeof Object.is=="function"?Object.is:vD;function au(e,t){if(yr(e,t))return!0;if(typeof e!="object"||e===null||typeof t!="object"||t===null)return!1;var n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(r=0;r<n.length;r++){var i=n[r];if(!hg.call(t,i)||!yr(e[i],t[i]))return!1}return!0}function K_(e){for(;e&&e.firstChild;)e=e.firstChild;return e}function j_(e,t){var n=K_(e);e=0;for(var r;n;){if(n.nodeType===3){if(r=e+n.textContent.length,e<=t&&r>=t)return{node:n,offset:t-e};e=r}e:{for(;n;){if(n.nextSibling){n=n.nextSibling;break e}n=n.parentNode}n=void 0}n=K_(n)}}function SI(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?SI(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function EI(){for(var e=window,t=pd();t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)e=t.contentWindow;else break;t=pd(e.document)}return t}function Km(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||t==="textarea"||e.contentEditable==="true")}function mD(e){var t=EI(),n=e.focusedElem,r=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&SI(n.ownerDocument.documentElement,n)){if(r!==null&&Km(n)){if(t=r.start,e=r.end,e===void 0&&(e=t),"selectionStart"in n)n.selectionStart=t,n.selectionEnd=Math.min(e,n.value.length);else if(e=(t=n.ownerDocument||document)&&t.defaultView||window,e.getSelection){e=e.getSelection();var i=n.textContent.length,o=Math.min(r.start,i);r=r.end===void 0?o:Math.min(r.end,i),!e.extend&&o>r&&(i=r,r=o,o=i),i=j_(n,o);var a=j_(n,r);i&&a&&(e.rangeCount!==1||e.anchorNode!==i.node||e.anchorOffset!==i.offset||e.focusNode!==a.node||e.focusOffset!==a.offset)&&(t=t.createRange(),t.setStart(i.node,i.offset),e.removeAllRanges(),o>r?(e.addRange(t),e.extend(a.node,a.offset)):(t.setEnd(a.node,a.offset),e.addRange(t)))}}for(t=[],e=n;e=e.parentNode;)e.nodeType===1&&t.push({element:e,left:e.scrollLeft,top:e.scrollTop});for(typeof n.focus=="function"&&n.focus(),n=0;n<t.length;n++)e=t[n],e.element.scrollLeft=e.left,e.element.scrollTop=e.top}}var yD=ii&&"documentMode"in document&&11>=document.documentMode,$s=null,Dg=null,jl=null,Ag=!1;function q_(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;Ag||$s==null||$s!==pd(r)||(r=$s,"selectionStart"in r&&Km(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),jl&&au(jl,r)||(jl=r,r=Ed(Dg,"onSelect"),0<r.length&&(t=new Um("onSelect","select",null,t,n),e.push({event:t,listeners:r}),t.target=$s)))}function cc(e,t){var n={};return n[e.toLowerCase()]=t.toLowerCase(),n["Webkit"+e]="webkit"+t,n["Moz"+e]="moz"+t,n}var Us={animationend:cc("Animation","AnimationEnd"),animationiteration:cc("Animation","AnimationIteration"),animationstart:cc("Animation","AnimationStart"),transitionend:cc("Transition","TransitionEnd")},fh={},wI={};ii&&(wI=document.createElement("div").style,"AnimationEvent"in window||(delete Us.animationend.animation,delete Us.animationiteration.animation,delete Us.animationstart.animation),"TransitionEvent"in window||delete Us.transitionend.transition);function hf(e){if(fh[e])return fh[e];if(!Us[e])return e;var t=Us[e],n;for(n in t)if(t.hasOwnProperty(n)&&n in wI)return fh[e]=t[n];return e}var bI=hf("animationend"),TI=hf("animationiteration"),RI=hf("animationstart"),II=hf("transitionend"),CI=new Map,V_="abort auxClick cancel canPlay canPlayThrough click close contextMenu copy cut drag dragEnd dragEnter dragExit dragLeave dragOver dragStart drop durationChange emptied encrypted ended error gotPointerCapture input invalid keyDown keyPress keyUp load loadedData loadedMetadata loadStart lostPointerCapture mouseDown mouseMove mouseOut mouseOver mouseUp paste pause play playing pointerCancel pointerDown pointerMove pointerOut pointerOver pointerUp progress rateChange reset resize seeked seeking stalled submit suspend timeUpdate touchCancel touchEnd touchStart volumeChange scroll toggle touchMove waiting wheel".split(" ");function ao(e,t){CI.set(e,t),Xo(t,[e])}for(var hh=0;hh<V_.length;hh++){var ph=V_[hh],_D=ph.toLowerCase(),SD=ph[0].toUpperCase()+ph.slice(1);ao(_D,"on"+SD)}ao(bI,"onAnimationEnd");ao(TI,"onAnimationIteration");ao(RI,"onAnimationStart");ao("dblclick","onDoubleClick");ao("focusin","onFocus");ao("focusout","onBlur");ao(II,"onTransitionEnd");oa("onMouseEnter",["mouseout","mouseover"]);oa("onMouseLeave",["mouseout","mouseover"]);oa("onPointerEnter",["pointerout","pointerover"]);oa("onPointerLeave",["pointerout","pointerover"]);Xo("onChange","change click focusin focusout input keydown keyup selectionchange".split(" "));Xo("onSelect","focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(" "));Xo("onBeforeInput",["compositionend","keypress","textInput","paste"]);Xo("onCompositionEnd","compositionend focusout keydown keypress keyup mousedown".split(" "));Xo("onCompositionStart","compositionstart focusout keydown keypress keyup mousedown".split(" "));Xo("onCompositionUpdate","compositionupdate focusout keydown keypress keyup mousedown".split(" "));var Al="abort canplay canplaythrough durationchange emptied encrypted ended error loadeddata loadedmetadata loadstart pause play playing progress ratechange resize seeked seeking stalled suspend timeupdate volumechange waiting".split(" "),ED=new Set("cancel close invalid load scroll toggle".split(" ").concat(Al));function W_(e,t,n){var r=e.type||"unknown-event";e.currentTarget=n,_M(r,t,void 0,e),e.currentTarget=null}function OI(e,t){t=(t&4)!==0;for(var n=0;n<e.length;n++){var r=e[n],i=r.event;r=r.listeners;e:{var o=void 0;if(t)for(var a=r.length-1;0<=a;a--){var c=r[a],f=c.instance,v=c.currentTarget;if(c=c.listener,f!==o&&i.isPropagationStopped())break e;W_(i,c,v),o=f}else for(a=0;a<r.length;a++){if(c=r[a],f=c.instance,v=c.currentTarget,c=c.listener,f!==o&&i.isPropagationStopped())break e;W_(i,c,v),o=f}}}if(vd)throw e=Og,vd=!1,Og=null,e}function ft(e,t){var n=t[Ug];n===void 0&&(n=t[Ug]=new Set);var r=e+"__bubble";n.has(r)||(PI(t,e,2,!1),n.add(r))}function gh(e,t,n){var r=0;t&&(r|=4),PI(n,e,r,t)}var dc="_reactListening"+Math.random().toString(36).slice(2);function lu(e){if(!e[dc]){e[dc]=!0,xR.forEach(function(n){n!=="selectionchange"&&(ED.has(n)||gh(n,!1,e),gh(n,!0,e))});var t=e.nodeType===9?e:e.ownerDocument;t===null||t[dc]||(t[dc]=!0,gh("selectionchange",!1,t))}}function PI(e,t,n,r){switch(fI(t)){case 1:var i=NM;break;case 4:i=xM;break;default:i=xm}n=i.bind(null,t,n,e),i=void 0,!Cg||t!=="touchstart"&&t!=="touchmove"&&t!=="wheel"||(i=!0),r?i!==void 0?e.addEventListener(t,n,{capture:!0,passive:i}):e.addEventListener(t,n,!0):i!==void 0?e.addEventListener(t,n,{passive:i}):e.addEventListener(t,n,!1)}function vh(e,t,n,r,i){var o=r;if(!(t&1)&&!(t&2)&&r!==null)e:for(;;){if(r===null)return;var a=r.tag;if(a===3||a===4){var c=r.stateNode.containerInfo;if(c===i||c.nodeType===8&&c.parentNode===i)break;if(a===4)for(a=r.return;a!==null;){var f=a.tag;if((f===3||f===4)&&(f=a.stateNode.containerInfo,f===i||f.nodeType===8&&f.parentNode===i))return;a=a.return}for(;c!==null;){if(a=Lo(c),a===null)return;if(f=a.tag,f===5||f===6){r=o=a;continue e}c=c.parentNode}}r=r.return}XR(function(){var v=o,s=Dm(n),g=[];e:{var y=CI.get(e);if(y!==void 0){var S=Um,m=e;switch(e){case"keypress":if(Jc(n)===0)break e;case"keydown":case"keyup":S=JM;break;case"focusin":m="focus",S=uh;break;case"focusout":m="blur",S=uh;break;case"beforeblur":case"afterblur":S=uh;break;case"click":if(n.button===2)break e;case"auxclick":case"dblclick":case"mousedown":case"mousemove":case"mouseup":case"mouseout":case"mouseover":case"contextmenu":S=A_;break;case"drag":case"dragend":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"dragstart":case"drop":S=BM;break;case"touchcancel":case"touchend":case"touchmove":case"touchstart":S=eD;break;case bI:case TI:case RI:S=jM;break;case II:S=nD;break;case"scroll":S=$M;break;case"wheel":S=iD;break;case"copy":case"cut":case"paste":S=VM;break;case"gotpointercapture":case"lostpointercapture":case"pointercancel":case"pointerdown":case"pointermove":case"pointerout":case"pointerover":case"pointerup":S=N_}var p=(t&4)!==0,_=!p&&e==="scroll",u=p?y!==null?y+"Capture":null:y;p=[];for(var l=v,d;l!==null;){d=l;var h=d.stateNode;if(d.tag===5&&h!==null&&(d=h,u!==null&&(h=nu(l,u),h!=null&&p.push(uu(l,h,d)))),_)break;l=l.return}0<p.length&&(y=new S(y,m,null,n,s),g.push({event:y,listeners:p}))}}if(!(t&7)){e:{if(y=e==="mouseover"||e==="pointerover",S=e==="mouseout"||e==="pointerout",y&&n!==Rg&&(m=n.relatedTarget||n.fromElement)&&(Lo(m)||m[oi]))break e;if((S||y)&&(y=s.window===s?s:(y=s.ownerDocument)?y.defaultView||y.parentWindow:window,S?(m=n.relatedTarget||n.toElement,S=v,m=m?Lo(m):null,m!==null&&(_=Zo(m),m!==_||m.tag!==5&&m.tag!==6)&&(m=null)):(S=null,m=v),S!==m)){if(p=A_,h="onMouseLeave",u="onMouseEnter",l="mouse",(e==="pointerout"||e==="pointerover")&&(p=N_,h="onPointerLeave",u="onPointerEnter",l="pointer"),_=S==null?y:Bs(S),d=m==null?y:Bs(m),y=new p(h,l+"leave",S,n,s),y.target=_,y.relatedTarget=d,h=null,Lo(s)===v&&(p=new p(u,l+"enter",m,n,s),p.target=d,p.relatedTarget=_,h=p),_=h,S&&m)t:{for(p=S,u=m,l=0,d=p;d;d=os(d))l++;for(d=0,h=u;h;h=os(h))d++;for(;0<l-d;)p=os(p),l--;for(;0<d-l;)u=os(u),d--;for(;l--;){if(p===u||u!==null&&p===u.alternate)break t;p=os(p),u=os(u)}p=null}else p=null;S!==null&&H_(g,y,S,p,!1),m!==null&&_!==null&&H_(g,_,m,p,!0)}}e:{if(y=v?Bs(v):window,S=y.nodeName&&y.nodeName.toLowerCase(),S==="select"||S==="input"&&y.type==="file")var w=dD;else if(U_(y))if(yI)w=gD;else{w=hD;var E=fD}else(S=y.nodeName)&&S.toLowerCase()==="input"&&(y.type==="checkbox"||y.type==="radio")&&(w=pD);if(w&&(w=w(e,v))){mI(g,w,n,s);break e}E&&E(e,y,v),e==="focusout"&&(E=y._wrapperState)&&E.controlled&&y.type==="number"&&Sg(y,"number",y.value)}switch(E=v?Bs(v):window,e){case"focusin":(U_(E)||E.contentEditable==="true")&&($s=E,Dg=v,jl=null);break;case"focusout":jl=Dg=$s=null;break;case"mousedown":Ag=!0;break;case"contextmenu":case"mouseup":case"dragend":Ag=!1,q_(g,n,s);break;case"selectionchange":if(yD)break;case"keydown":case"keyup":q_(g,n,s)}var I;if(Fm)e:{switch(e){case"compositionstart":var k="onCompositionStart";break e;case"compositionend":k="onCompositionEnd";break e;case"compositionupdate":k="onCompositionUpdate";break e}k=void 0}else xs?gI(e,n)&&(k="onCompositionEnd"):e==="keydown"&&n.keyCode===229&&(k="onCompositionStart");k&&(pI&&n.locale!=="ko"&&(xs||k!=="onCompositionStart"?k==="onCompositionEnd"&&xs&&(I=hI()):(Bi=s,$m="value"in Bi?Bi.value:Bi.textContent,xs=!0)),E=Ed(v,k),0<E.length&&(k=new L_(k,e,null,n,s),g.push({event:k,listeners:E}),I?k.data=I:(I=vI(n),I!==null&&(k.data=I)))),(I=sD?aD(e,n):lD(e,n))&&(v=Ed(v,"onBeforeInput"),0<v.length&&(s=new L_("onBeforeInput","beforeinput",null,n,s),g.push({event:s,listeners:v}),s.data=I))}OI(g,t)})}function uu(e,t,n){return{instance:e,listener:t,currentTarget:n}}function Ed(e,t){for(var n=t+"Capture",r=[];e!==null;){var i=e,o=i.stateNode;i.tag===5&&o!==null&&(i=o,o=nu(e,n),o!=null&&r.unshift(uu(e,o,i)),o=nu(e,t),o!=null&&r.push(uu(e,o,i))),e=e.return}return r}function os(e){if(e===null)return null;do e=e.return;while(e&&e.tag!==5);return e||null}function H_(e,t,n,r,i){for(var o=t._reactName,a=[];n!==null&&n!==r;){var c=n,f=c.alternate,v=c.stateNode;if(f!==null&&f===r)break;c.tag===5&&v!==null&&(c=v,i?(f=nu(n,o),f!=null&&a.unshift(uu(n,f,c))):i||(f=nu(n,o),f!=null&&a.push(uu(n,f,c)))),n=n.return}a.length!==0&&e.push({event:t,listeners:a})}var wD=/\r\n?/g,bD=/\u0000|\uFFFD/g;function G_(e){return(typeof e=="string"?e:""+e).replace(wD,`
     38 `).replace(bD,"")}function fc(e,t,n){if(t=G_(t),G_(e)!==t&&n)throw Error(we(425))}function wd(){}var Lg=null,Ng=null;function xg(e,t){return e==="textarea"||e==="noscript"||typeof t.children=="string"||typeof t.children=="number"||typeof t.dangerouslySetInnerHTML=="object"&&t.dangerouslySetInnerHTML!==null&&t.dangerouslySetInnerHTML.__html!=null}var $g=typeof setTimeout=="function"?setTimeout:void 0,TD=typeof clearTimeout=="function"?clearTimeout:void 0,z_=typeof Promise=="function"?Promise:void 0,RD=typeof queueMicrotask=="function"?queueMicrotask:typeof z_<"u"?function(e){return z_.resolve(null).then(e).catch(ID)}:$g;function ID(e){setTimeout(function(){throw e})}function mh(e,t){var n=t,r=0;do{var i=n.nextSibling;if(e.removeChild(n),i&&i.nodeType===8)if(n=i.data,n==="/$"){if(r===0){e.removeChild(i),ou(t);return}r--}else n!=="$"&&n!=="$?"&&n!=="$!"||r++;n=i}while(n);ou(t)}function Gi(e){for(;e!=null;e=e.nextSibling){var t=e.nodeType;if(t===1||t===3)break;if(t===8){if(t=e.data,t==="$"||t==="$!"||t==="$?")break;if(t==="/$")return null}}return e}function Y_(e){e=e.previousSibling;for(var t=0;e;){if(e.nodeType===8){var n=e.data;if(n==="$"||n==="$!"||n==="$?"){if(t===0)return e;t--}else n==="/$"&&t++}e=e.previousSibling}return null}var va=Math.random().toString(36).slice(2),$r="__reactFiber$"+va,cu="__reactProps$"+va,oi="__reactContainer$"+va,Ug="__reactEvents$"+va,CD="__reactListeners$"+va,OD="__reactHandles$"+va;function Lo(e){var t=e[$r];if(t)return t;for(var n=e.parentNode;n;){if(t=n[oi]||n[$r]){if(n=t.alternate,t.child!==null||n!==null&&n.child!==null)for(e=Y_(e);e!==null;){if(n=e[$r])return n;e=Y_(e)}return t}e=n,n=e.parentNode}return null}function ku(e){return e=e[$r]||e[oi],!e||e.tag!==5&&e.tag!==6&&e.tag!==13&&e.tag!==3?null:e}function Bs(e){if(e.tag===5||e.tag===6)return e.stateNode;throw Error(we(33))}function pf(e){return e[cu]||null}var Bg=[],Fs=-1;function lo(e){return{current:e}}function pt(e){0>Fs||(e.current=Bg[Fs],Bg[Fs]=null,Fs--)}function dt(e,t){Fs++,Bg[Fs]=e.current,e.current=t}var no={},tn=lo(no),Tn=lo(!1),Ko=no;function sa(e,t){var n=e.type.contextTypes;if(!n)return no;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===t)return r.__reactInternalMemoizedMaskedChildContext;var i={},o;for(o in n)i[o]=t[o];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=i),i}function Rn(e){return e=e.childContextTypes,e!=null}function bd(){pt(Tn),pt(tn)}function Q_(e,t,n){if(tn.current!==no)throw Error(we(168));dt(tn,t),dt(Tn,n)}function kI(e,t,n){var r=e.stateNode;if(t=t.childContextTypes,typeof r.getChildContext!="function")return n;r=r.getChildContext();for(var i in r)if(!(i in t))throw Error(we(108,fM(e)||"Unknown",i));return St({},n,r)}function Td(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||no,Ko=tn.current,dt(tn,e),dt(Tn,Tn.current),!0}function J_(e,t,n){var r=e.stateNode;if(!r)throw Error(we(169));n?(e=kI(e,t,Ko),r.__reactInternalMemoizedMergedChildContext=e,pt(Tn),pt(tn),dt(tn,e)):pt(Tn),dt(Tn,n)}var Xr=null,gf=!1,yh=!1;function MI(e){Xr===null?Xr=[e]:Xr.push(e)}function PD(e){gf=!0,MI(e)}function uo(){if(!yh&&Xr!==null){yh=!0;var e=0,t=at;try{var n=Xr;for(at=1;e<n.length;e++){var r=n[e];do r=r(!0);while(r!==null)}Xr=null,gf=!1}catch(i){throw Xr!==null&&(Xr=Xr.slice(e+1)),nI(Am,uo),i}finally{at=t,yh=!1}}return null}var Ks=[],js=0,Rd=null,Id=0,Hn=[],Gn=0,jo=null,ei=1,ti="";function Oo(e,t){Ks[js++]=Id,Ks[js++]=Rd,Rd=e,Id=t}function DI(e,t,n){Hn[Gn++]=ei,Hn[Gn++]=ti,Hn[Gn++]=jo,jo=e;var r=ei;e=ti;var i=32-gr(r)-1;r&=~(1<<i),n+=1;var o=32-gr(t)+i;if(30<o){var a=i-i%5;o=(r&(1<<a)-1).toString(32),r>>=a,i-=a,ei=1<<32-gr(t)+i|n<<i|r,ti=o+e}else ei=1<<o|n<<i|r,ti=e}function jm(e){e.return!==null&&(Oo(e,1),DI(e,1,0))}function qm(e){for(;e===Rd;)Rd=Ks[--js],Ks[js]=null,Id=Ks[--js],Ks[js]=null;for(;e===jo;)jo=Hn[--Gn],Hn[Gn]=null,ti=Hn[--Gn],Hn[Gn]=null,ei=Hn[--Gn],Hn[Gn]=null}var Ln=null,Dn=null,vt=!1,hr=null;function AI(e,t){var n=zn(5,null,null,0);n.elementType="DELETED",n.stateNode=t,n.return=e,t=e.deletions,t===null?(e.deletions=[n],e.flags|=16):t.push(n)}function X_(e,t){switch(e.tag){case 5:var n=e.type;return t=t.nodeType!==1||n.toLowerCase()!==t.nodeName.toLowerCase()?null:t,t!==null?(e.stateNode=t,Ln=e,Dn=Gi(t.firstChild),!0):!1;case 6:return t=e.pendingProps===""||t.nodeType!==3?null:t,t!==null?(e.stateNode=t,Ln=e,Dn=null,!0):!1;case 13:return t=t.nodeType!==8?null:t,t!==null?(n=jo!==null?{id:ei,overflow:ti}:null,e.memoizedState={dehydrated:t,treeContext:n,retryLane:1073741824},n=zn(18,null,null,0),n.stateNode=t,n.return=e,e.child=n,Ln=e,Dn=null,!0):!1;default:return!1}}function Fg(e){return(e.mode&1)!==0&&(e.flags&128)===0}function Kg(e){if(vt){var t=Dn;if(t){var n=t;if(!X_(e,t)){if(Fg(e))throw Error(we(418));t=Gi(n.nextSibling);var r=Ln;t&&X_(e,t)?AI(r,n):(e.flags=e.flags&-4097|2,vt=!1,Ln=e)}}else{if(Fg(e))throw Error(we(418));e.flags=e.flags&-4097|2,vt=!1,Ln=e}}}function Z_(e){for(e=e.return;e!==null&&e.tag!==5&&e.tag!==3&&e.tag!==13;)e=e.return;Ln=e}function hc(e){if(e!==Ln)return!1;if(!vt)return Z_(e),vt=!0,!1;var t;if((t=e.tag!==3)&&!(t=e.tag!==5)&&(t=e.type,t=t!=="head"&&t!=="body"&&!xg(e.type,e.memoizedProps)),t&&(t=Dn)){if(Fg(e))throw LI(),Error(we(418));for(;t;)AI(e,t),t=Gi(t.nextSibling)}if(Z_(e),e.tag===13){if(e=e.memoizedState,e=e!==null?e.dehydrated:null,!e)throw Error(we(317));e:{for(e=e.nextSibling,t=0;e;){if(e.nodeType===8){var n=e.data;if(n==="/$"){if(t===0){Dn=Gi(e.nextSibling);break e}t--}else n!=="$"&&n!=="$!"&&n!=="$?"||t++}e=e.nextSibling}Dn=null}}else Dn=Ln?Gi(e.stateNode.nextSibling):null;return!0}function LI(){for(var e=Dn;e;)e=Gi(e.nextSibling)}function aa(){Dn=Ln=null,vt=!1}function Vm(e){hr===null?hr=[e]:hr.push(e)}var kD=li.ReactCurrentBatchConfig;function dr(e,t){if(e&&e.defaultProps){t=St({},t),e=e.defaultProps;for(var n in e)t[n]===void 0&&(t[n]=e[n]);return t}return t}var Cd=lo(null),Od=null,qs=null,Wm=null;function Hm(){Wm=qs=Od=null}function Gm(e){var t=Cd.current;pt(Cd),e._currentValue=t}function jg(e,t,n){for(;e!==null;){var r=e.alternate;if((e.childLanes&t)!==t?(e.childLanes|=t,r!==null&&(r.childLanes|=t)):r!==null&&(r.childLanes&t)!==t&&(r.childLanes|=t),e===n)break;e=e.return}}function Zs(e,t){Od=e,Wm=qs=null,e=e.dependencies,e!==null&&e.firstContext!==null&&(e.lanes&t&&(wn=!0),e.firstContext=null)}function Qn(e){var t=e._currentValue;if(Wm!==e)if(e={context:e,memoizedValue:t,next:null},qs===null){if(Od===null)throw Error(we(308));qs=e,Od.dependencies={lanes:0,firstContext:e}}else qs=qs.next=e;return t}var No=null;function zm(e){No===null?No=[e]:No.push(e)}function NI(e,t,n,r){var i=t.interleaved;return i===null?(n.next=n,zm(t)):(n.next=i.next,i.next=n),t.interleaved=n,si(e,r)}function si(e,t){e.lanes|=t;var n=e.alternate;for(n!==null&&(n.lanes|=t),n=e,e=e.return;e!==null;)e.childLanes|=t,n=e.alternate,n!==null&&(n.childLanes|=t),n=e,e=e.return;return n.tag===3?n.stateNode:null}var Li=!1;function Ym(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function xI(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,effects:e.effects})}function ni(e,t){return{eventTime:e,lane:t,tag:0,payload:null,callback:null,next:null}}function zi(e,t,n){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,it&2){var i=r.pending;return i===null?t.next=t:(t.next=i.next,i.next=t),r.pending=t,si(e,n)}return i=r.interleaved,i===null?(t.next=t,zm(r)):(t.next=i.next,i.next=t),r.interleaved=t,si(e,n)}function Xc(e,t,n){if(t=t.updateQueue,t!==null&&(t=t.shared,(n&4194240)!==0)){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,Lm(e,n)}}function eS(e,t){var n=e.updateQueue,r=e.alternate;if(r!==null&&(r=r.updateQueue,n===r)){var i=null,o=null;if(n=n.firstBaseUpdate,n!==null){do{var a={eventTime:n.eventTime,lane:n.lane,tag:n.tag,payload:n.payload,callback:n.callback,next:null};o===null?i=o=a:o=o.next=a,n=n.next}while(n!==null);o===null?i=o=t:o=o.next=t}else i=o=t;n={baseState:r.baseState,firstBaseUpdate:i,lastBaseUpdate:o,shared:r.shared,effects:r.effects},e.updateQueue=n;return}e=n.lastBaseUpdate,e===null?n.firstBaseUpdate=t:e.next=t,n.lastBaseUpdate=t}function Pd(e,t,n,r){var i=e.updateQueue;Li=!1;var o=i.firstBaseUpdate,a=i.lastBaseUpdate,c=i.shared.pending;if(c!==null){i.shared.pending=null;var f=c,v=f.next;f.next=null,a===null?o=v:a.next=v,a=f;var s=e.alternate;s!==null&&(s=s.updateQueue,c=s.lastBaseUpdate,c!==a&&(c===null?s.firstBaseUpdate=v:c.next=v,s.lastBaseUpdate=f))}if(o!==null){var g=i.baseState;a=0,s=v=f=null,c=o;do{var y=c.lane,S=c.eventTime;if((r&y)===y){s!==null&&(s=s.next={eventTime:S,lane:0,tag:c.tag,payload:c.payload,callback:c.callback,next:null});e:{var m=e,p=c;switch(y=t,S=n,p.tag){case 1:if(m=p.payload,typeof m=="function"){g=m.call(S,g,y);break e}g=m;break e;case 3:m.flags=m.flags&-65537|128;case 0:if(m=p.payload,y=typeof m=="function"?m.call(S,g,y):m,y==null)break e;g=St({},g,y);break e;case 2:Li=!0}}c.callback!==null&&c.lane!==0&&(e.flags|=64,y=i.effects,y===null?i.effects=[c]:y.push(c))}else S={eventTime:S,lane:y,tag:c.tag,payload:c.payload,callback:c.callback,next:null},s===null?(v=s=S,f=g):s=s.next=S,a|=y;if(c=c.next,c===null){if(c=i.shared.pending,c===null)break;y=c,c=y.next,y.next=null,i.lastBaseUpdate=y,i.shared.pending=null}}while(1);if(s===null&&(f=g),i.baseState=f,i.firstBaseUpdate=v,i.lastBaseUpdate=s,t=i.shared.interleaved,t!==null){i=t;do a|=i.lane,i=i.next;while(i!==t)}else o===null&&(i.shared.lanes=0);Vo|=a,e.lanes=a,e.memoizedState=g}}function tS(e,t,n){if(e=t.effects,t.effects=null,e!==null)for(t=0;t<e.length;t++){var r=e[t],i=r.callback;if(i!==null){if(r.callback=null,r=n,typeof i!="function")throw Error(we(191,i));i.call(r)}}}var $I=new NR.Component().refs;function qg(e,t,n,r){t=e.memoizedState,n=n(r,t),n=n==null?t:St({},t,n),e.memoizedState=n,e.lanes===0&&(e.updateQueue.baseState=n)}var vf={isMounted:function(e){return(e=e._reactInternals)?Zo(e)===e:!1},enqueueSetState:function(e,t,n){e=e._reactInternals;var r=cn(),i=Qi(e),o=ni(r,i);o.payload=t,n!=null&&(o.callback=n),t=zi(e,o,i),t!==null&&(vr(t,e,i,r),Xc(t,e,i))},enqueueReplaceState:function(e,t,n){e=e._reactInternals;var r=cn(),i=Qi(e),o=ni(r,i);o.tag=1,o.payload=t,n!=null&&(o.callback=n),t=zi(e,o,i),t!==null&&(vr(t,e,i,r),Xc(t,e,i))},enqueueForceUpdate:function(e,t){e=e._reactInternals;var n=cn(),r=Qi(e),i=ni(n,r);i.tag=2,t!=null&&(i.callback=t),t=zi(e,i,r),t!==null&&(vr(t,e,r,n),Xc(t,e,r))}};function nS(e,t,n,r,i,o,a){return e=e.stateNode,typeof e.shouldComponentUpdate=="function"?e.shouldComponentUpdate(r,o,a):t.prototype&&t.prototype.isPureReactComponent?!au(n,r)||!au(i,o):!0}function UI(e,t,n){var r=!1,i=no,o=t.contextType;return typeof o=="object"&&o!==null?o=Qn(o):(i=Rn(t)?Ko:tn.current,r=t.contextTypes,o=(r=r!=null)?sa(e,i):no),t=new t(n,o),e.memoizedState=t.state!==null&&t.state!==void 0?t.state:null,t.updater=vf,e.stateNode=t,t._reactInternals=e,r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=i,e.__reactInternalMemoizedMaskedChildContext=o),t}function rS(e,t,n,r){e=t.state,typeof t.componentWillReceiveProps=="function"&&t.componentWillReceiveProps(n,r),typeof t.UNSAFE_componentWillReceiveProps=="function"&&t.UNSAFE_componentWillReceiveProps(n,r),t.state!==e&&vf.enqueueReplaceState(t,t.state,null)}function Vg(e,t,n,r){var i=e.stateNode;i.props=n,i.state=e.memoizedState,i.refs=$I,Ym(e);var o=t.contextType;typeof o=="object"&&o!==null?i.context=Qn(o):(o=Rn(t)?Ko:tn.current,i.context=sa(e,o)),i.state=e.memoizedState,o=t.getDerivedStateFromProps,typeof o=="function"&&(qg(e,t,o,n),i.state=e.memoizedState),typeof t.getDerivedStateFromProps=="function"||typeof i.getSnapshotBeforeUpdate=="function"||typeof i.UNSAFE_componentWillMount!="function"&&typeof i.componentWillMount!="function"||(t=i.state,typeof i.componentWillMount=="function"&&i.componentWillMount(),typeof i.UNSAFE_componentWillMount=="function"&&i.UNSAFE_componentWillMount(),t!==i.state&&vf.enqueueReplaceState(i,i.state,null),Pd(e,n,i,r),i.state=e.memoizedState),typeof i.componentDidMount=="function"&&(e.flags|=4194308)}function xa(e,t,n){if(e=n.ref,e!==null&&typeof e!="function"&&typeof e!="object"){if(n._owner){if(n=n._owner,n){if(n.tag!==1)throw Error(we(309));var r=n.stateNode}if(!r)throw Error(we(147,e));var i=r,o=""+e;return t!==null&&t.ref!==null&&typeof t.ref=="function"&&t.ref._stringRef===o?t.ref:(t=function(a){var c=i.refs;c===$I&&(c=i.refs={}),a===null?delete c[o]:c[o]=a},t._stringRef=o,t)}if(typeof e!="string")throw Error(we(284));if(!n._owner)throw Error(we(290,e))}return e}function pc(e,t){throw e=Object.prototype.toString.call(t),Error(we(31,e==="[object Object]"?"object with keys {"+Object.keys(t).join(", ")+"}":e))}function iS(e){var t=e._init;return t(e._payload)}function BI(e){function t(u,l){if(e){var d=u.deletions;d===null?(u.deletions=[l],u.flags|=16):d.push(l)}}function n(u,l){if(!e)return null;for(;l!==null;)t(u,l),l=l.sibling;return null}function r(u,l){for(u=new Map;l!==null;)l.key!==null?u.set(l.key,l):u.set(l.index,l),l=l.sibling;return u}function i(u,l){return u=Ji(u,l),u.index=0,u.sibling=null,u}function o(u,l,d){return u.index=d,e?(d=u.alternate,d!==null?(d=d.index,d<l?(u.flags|=2,l):d):(u.flags|=2,l)):(u.flags|=1048576,l)}function a(u){return e&&u.alternate===null&&(u.flags|=2),u}function c(u,l,d,h){return l===null||l.tag!==6?(l=Rh(d,u.mode,h),l.return=u,l):(l=i(l,d),l.return=u,l)}function f(u,l,d,h){var w=d.type;return w===Ns?s(u,l,d.props.children,h,d.key):l!==null&&(l.elementType===w||typeof w=="object"&&w!==null&&w.$$typeof===Ai&&iS(w)===l.type)?(h=i(l,d.props),h.ref=xa(u,l,d),h.return=u,h):(h=id(d.type,d.key,d.props,null,u.mode,h),h.ref=xa(u,l,d),h.return=u,h)}function v(u,l,d,h){return l===null||l.tag!==4||l.stateNode.containerInfo!==d.containerInfo||l.stateNode.implementation!==d.implementation?(l=Ih(d,u.mode,h),l.return=u,l):(l=i(l,d.children||[]),l.return=u,l)}function s(u,l,d,h,w){return l===null||l.tag!==7?(l=Bo(d,u.mode,h,w),l.return=u,l):(l=i(l,d),l.return=u,l)}function g(u,l,d){if(typeof l=="string"&&l!==""||typeof l=="number")return l=Rh(""+l,u.mode,d),l.return=u,l;if(typeof l=="object"&&l!==null){switch(l.$$typeof){case rc:return d=id(l.type,l.key,l.props,null,u.mode,d),d.ref=xa(u,null,l),d.return=u,d;case Ls:return l=Ih(l,u.mode,d),l.return=u,l;case Ai:var h=l._init;return g(u,h(l._payload),d)}if(Ml(l)||Ma(l))return l=Bo(l,u.mode,d,null),l.return=u,l;pc(u,l)}return null}function y(u,l,d,h){var w=l!==null?l.key:null;if(typeof d=="string"&&d!==""||typeof d=="number")return w!==null?null:c(u,l,""+d,h);if(typeof d=="object"&&d!==null){switch(d.$$typeof){case rc:return d.key===w?f(u,l,d,h):null;case Ls:return d.key===w?v(u,l,d,h):null;case Ai:return w=d._init,y(u,l,w(d._payload),h)}if(Ml(d)||Ma(d))return w!==null?null:s(u,l,d,h,null);pc(u,d)}return null}function S(u,l,d,h,w){if(typeof h=="string"&&h!==""||typeof h=="number")return u=u.get(d)||null,c(l,u,""+h,w);if(typeof h=="object"&&h!==null){switch(h.$$typeof){case rc:return u=u.get(h.key===null?d:h.key)||null,f(l,u,h,w);case Ls:return u=u.get(h.key===null?d:h.key)||null,v(l,u,h,w);case Ai:var E=h._init;return S(u,l,d,E(h._payload),w)}if(Ml(h)||Ma(h))return u=u.get(d)||null,s(l,u,h,w,null);pc(l,h)}return null}function m(u,l,d,h){for(var w=null,E=null,I=l,k=l=0,M=null;I!==null&&k<d.length;k++){I.index>k?(M=I,I=null):M=I.sibling;var L=y(u,I,d[k],h);if(L===null){I===null&&(I=M);break}e&&I&&L.alternate===null&&t(u,I),l=o(L,l,k),E===null?w=L:E.sibling=L,E=L,I=M}if(k===d.length)return n(u,I),vt&&Oo(u,k),w;if(I===null){for(;k<d.length;k++)I=g(u,d[k],h),I!==null&&(l=o(I,l,k),E===null?w=I:E.sibling=I,E=I);return vt&&Oo(u,k),w}for(I=r(u,I);k<d.length;k++)M=S(I,u,k,d[k],h),M!==null&&(e&&M.alternate!==null&&I.delete(M.key===null?k:M.key),l=o(M,l,k),E===null?w=M:E.sibling=M,E=M);return e&&I.forEach(function(B){return t(u,B)}),vt&&Oo(u,k),w}function p(u,l,d,h){var w=Ma(d);if(typeof w!="function")throw Error(we(150));if(d=w.call(d),d==null)throw Error(we(151));for(var E=w=null,I=l,k=l=0,M=null,L=d.next();I!==null&&!L.done;k++,L=d.next()){I.index>k?(M=I,I=null):M=I.sibling;var B=y(u,I,L.value,h);if(B===null){I===null&&(I=M);break}e&&I&&B.alternate===null&&t(u,I),l=o(B,l,k),E===null?w=B:E.sibling=B,E=B,I=M}if(L.done)return n(u,I),vt&&Oo(u,k),w;if(I===null){for(;!L.done;k++,L=d.next())L=g(u,L.value,h),L!==null&&(l=o(L,l,k),E===null?w=L:E.sibling=L,E=L);return vt&&Oo(u,k),w}for(I=r(u,I);!L.done;k++,L=d.next())L=S(I,u,k,L.value,h),L!==null&&(e&&L.alternate!==null&&I.delete(L.key===null?k:L.key),l=o(L,l,k),E===null?w=L:E.sibling=L,E=L);return e&&I.forEach(function(N){return t(u,N)}),vt&&Oo(u,k),w}function _(u,l,d,h){if(typeof d=="object"&&d!==null&&d.type===Ns&&d.key===null&&(d=d.props.children),typeof d=="object"&&d!==null){switch(d.$$typeof){case rc:e:{for(var w=d.key,E=l;E!==null;){if(E.key===w){if(w=d.type,w===Ns){if(E.tag===7){n(u,E.sibling),l=i(E,d.props.children),l.return=u,u=l;break e}}else if(E.elementType===w||typeof w=="object"&&w!==null&&w.$$typeof===Ai&&iS(w)===E.type){n(u,E.sibling),l=i(E,d.props),l.ref=xa(u,E,d),l.return=u,u=l;break e}n(u,E);break}else t(u,E);E=E.sibling}d.type===Ns?(l=Bo(d.props.children,u.mode,h,d.key),l.return=u,u=l):(h=id(d.type,d.key,d.props,null,u.mode,h),h.ref=xa(u,l,d),h.return=u,u=h)}return a(u);case Ls:e:{for(E=d.key;l!==null;){if(l.key===E)if(l.tag===4&&l.stateNode.containerInfo===d.containerInfo&&l.stateNode.implementation===d.implementation){n(u,l.sibling),l=i(l,d.children||[]),l.return=u,u=l;break e}else{n(u,l);break}else t(u,l);l=l.sibling}l=Ih(d,u.mode,h),l.return=u,u=l}return a(u);case Ai:return E=d._init,_(u,l,E(d._payload),h)}if(Ml(d))return m(u,l,d,h);if(Ma(d))return p(u,l,d,h);pc(u,d)}return typeof d=="string"&&d!==""||typeof d=="number"?(d=""+d,l!==null&&l.tag===6?(n(u,l.sibling),l=i(l,d),l.return=u,u=l):(n(u,l),l=Rh(d,u.mode,h),l.return=u,u=l),a(u)):n(u,l)}return _}var la=BI(!0),FI=BI(!1),Mu={},Fr=lo(Mu),du=lo(Mu),fu=lo(Mu);function xo(e){if(e===Mu)throw Error(we(174));return e}function Qm(e,t){switch(dt(fu,t),dt(du,e),dt(Fr,Mu),e=t.nodeType,e){case 9:case 11:t=(t=t.documentElement)?t.namespaceURI:wg(null,"");break;default:e=e===8?t.parentNode:t,t=e.namespaceURI||null,e=e.tagName,t=wg(t,e)}pt(Fr),dt(Fr,t)}function ua(){pt(Fr),pt(du),pt(fu)}function KI(e){xo(fu.current);var t=xo(Fr.current),n=wg(t,e.type);t!==n&&(dt(du,e),dt(Fr,n))}function Jm(e){du.current===e&&(pt(Fr),pt(du))}var mt=lo(0);function kd(e){for(var t=e;t!==null;){if(t.tag===13){var n=t.memoizedState;if(n!==null&&(n=n.dehydrated,n===null||n.data==="$?"||n.data==="$!"))return t}else if(t.tag===19&&t.memoizedProps.revealOrder!==void 0){if(t.flags&128)return t}else if(t.child!==null){t.child.return=t,t=t.child;continue}if(t===e)break;for(;t.sibling===null;){if(t.return===null||t.return===e)return null;t=t.return}t.sibling.return=t.return,t=t.sibling}return null}var _h=[];function Xm(){for(var e=0;e<_h.length;e++)_h[e]._workInProgressVersionPrimary=null;_h.length=0}var Zc=li.ReactCurrentDispatcher,Sh=li.ReactCurrentBatchConfig,qo=0,_t=null,kt=null,Nt=null,Md=!1,ql=!1,hu=0,MD=0;function Wt(){throw Error(we(321))}function Zm(e,t){if(t===null)return!1;for(var n=0;n<t.length&&n<e.length;n++)if(!yr(e[n],t[n]))return!1;return!0}function ey(e,t,n,r,i,o){if(qo=o,_t=t,t.memoizedState=null,t.updateQueue=null,t.lanes=0,Zc.current=e===null||e.memoizedState===null?ND:xD,e=n(r,i),ql){o=0;do{if(ql=!1,hu=0,25<=o)throw Error(we(301));o+=1,Nt=kt=null,t.updateQueue=null,Zc.current=$D,e=n(r,i)}while(ql)}if(Zc.current=Dd,t=kt!==null&&kt.next!==null,qo=0,Nt=kt=_t=null,Md=!1,t)throw Error(we(300));return e}function ty(){var e=hu!==0;return hu=0,e}function xr(){var e={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return Nt===null?_t.memoizedState=Nt=e:Nt=Nt.next=e,Nt}function Jn(){if(kt===null){var e=_t.alternate;e=e!==null?e.memoizedState:null}else e=kt.next;var t=Nt===null?_t.memoizedState:Nt.next;if(t!==null)Nt=t,kt=e;else{if(e===null)throw Error(we(310));kt=e,e={memoizedState:kt.memoizedState,baseState:kt.baseState,baseQueue:kt.baseQueue,queue:kt.queue,next:null},Nt===null?_t.memoizedState=Nt=e:Nt=Nt.next=e}return Nt}function pu(e,t){return typeof t=="function"?t(e):t}function Eh(e){var t=Jn(),n=t.queue;if(n===null)throw Error(we(311));n.lastRenderedReducer=e;var r=kt,i=r.baseQueue,o=n.pending;if(o!==null){if(i!==null){var a=i.next;i.next=o.next,o.next=a}r.baseQueue=i=o,n.pending=null}if(i!==null){o=i.next,r=r.baseState;var c=a=null,f=null,v=o;do{var s=v.lane;if((qo&s)===s)f!==null&&(f=f.next={lane:0,action:v.action,hasEagerState:v.hasEagerState,eagerState:v.eagerState,next:null}),r=v.hasEagerState?v.eagerState:e(r,v.action);else{var g={lane:s,action:v.action,hasEagerState:v.hasEagerState,eagerState:v.eagerState,next:null};f===null?(c=f=g,a=r):f=f.next=g,_t.lanes|=s,Vo|=s}v=v.next}while(v!==null&&v!==o);f===null?a=r:f.next=c,yr(r,t.memoizedState)||(wn=!0),t.memoizedState=r,t.baseState=a,t.baseQueue=f,n.lastRenderedState=r}if(e=n.interleaved,e!==null){i=e;do o=i.lane,_t.lanes|=o,Vo|=o,i=i.next;while(i!==e)}else i===null&&(n.lanes=0);return[t.memoizedState,n.dispatch]}function wh(e){var t=Jn(),n=t.queue;if(n===null)throw Error(we(311));n.lastRenderedReducer=e;var r=n.dispatch,i=n.pending,o=t.memoizedState;if(i!==null){n.pending=null;var a=i=i.next;do o=e(o,a.action),a=a.next;while(a!==i);yr(o,t.memoizedState)||(wn=!0),t.memoizedState=o,t.baseQueue===null&&(t.baseState=o),n.lastRenderedState=o}return[o,r]}function jI(){}function qI(e,t){var n=_t,r=Jn(),i=t(),o=!yr(r.memoizedState,i);if(o&&(r.memoizedState=i,wn=!0),r=r.queue,ny(HI.bind(null,n,r,e),[e]),r.getSnapshot!==t||o||Nt!==null&&Nt.memoizedState.tag&1){if(n.flags|=2048,gu(9,WI.bind(null,n,r,i,t),void 0,null),xt===null)throw Error(we(349));qo&30||VI(n,t,i)}return i}function VI(e,t,n){e.flags|=16384,e={getSnapshot:t,value:n},t=_t.updateQueue,t===null?(t={lastEffect:null,stores:null},_t.updateQueue=t,t.stores=[e]):(n=t.stores,n===null?t.stores=[e]:n.push(e))}function WI(e,t,n,r){t.value=n,t.getSnapshot=r,GI(t)&&zI(e)}function HI(e,t,n){return n(function(){GI(t)&&zI(e)})}function GI(e){var t=e.getSnapshot;e=e.value;try{var n=t();return!yr(e,n)}catch{return!0}}function zI(e){var t=si(e,1);t!==null&&vr(t,e,1,-1)}function oS(e){var t=xr();return typeof e=="function"&&(e=e()),t.memoizedState=t.baseState=e,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:pu,lastRenderedState:e},t.queue=e,e=e.dispatch=LD.bind(null,_t,e),[t.memoizedState,e]}function gu(e,t,n,r){return e={tag:e,create:t,destroy:n,deps:r,next:null},t=_t.updateQueue,t===null?(t={lastEffect:null,stores:null},_t.updateQueue=t,t.lastEffect=e.next=e):(n=t.lastEffect,n===null?t.lastEffect=e.next=e:(r=n.next,n.next=e,e.next=r,t.lastEffect=e)),e}function YI(){return Jn().memoizedState}function ed(e,t,n,r){var i=xr();_t.flags|=e,i.memoizedState=gu(1|t,n,void 0,r===void 0?null:r)}function mf(e,t,n,r){var i=Jn();r=r===void 0?null:r;var o=void 0;if(kt!==null){var a=kt.memoizedState;if(o=a.destroy,r!==null&&Zm(r,a.deps)){i.memoizedState=gu(t,n,o,r);return}}_t.flags|=e,i.memoizedState=gu(1|t,n,o,r)}function sS(e,t){return ed(8390656,8,e,t)}function ny(e,t){return mf(2048,8,e,t)}function QI(e,t){return mf(4,2,e,t)}function JI(e,t){return mf(4,4,e,t)}function XI(e,t){if(typeof t=="function")return e=e(),t(e),function(){t(null)};if(t!=null)return e=e(),t.current=e,function(){t.current=null}}function ZI(e,t,n){return n=n!=null?n.concat([e]):null,mf(4,4,XI.bind(null,t,e),n)}function ry(){}function eC(e,t){var n=Jn();t=t===void 0?null:t;var r=n.memoizedState;return r!==null&&t!==null&&Zm(t,r[1])?r[0]:(n.memoizedState=[e,t],e)}function tC(e,t){var n=Jn();t=t===void 0?null:t;var r=n.memoizedState;return r!==null&&t!==null&&Zm(t,r[1])?r[0]:(e=e(),n.memoizedState=[e,t],e)}function nC(e,t,n){return qo&21?(yr(n,t)||(n=oI(),_t.lanes|=n,Vo|=n,e.baseState=!0),t):(e.baseState&&(e.baseState=!1,wn=!0),e.memoizedState=n)}function DD(e,t){var n=at;at=n!==0&&4>n?n:4,e(!0);var r=Sh.transition;Sh.transition={};try{e(!1),t()}finally{at=n,Sh.transition=r}}function rC(){return Jn().memoizedState}function AD(e,t,n){var r=Qi(e);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},iC(e))oC(t,n);else if(n=NI(e,t,n,r),n!==null){var i=cn();vr(n,e,r,i),sC(n,t,r)}}function LD(e,t,n){var r=Qi(e),i={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(iC(e))oC(t,i);else{var o=e.alternate;if(e.lanes===0&&(o===null||o.lanes===0)&&(o=t.lastRenderedReducer,o!==null))try{var a=t.lastRenderedState,c=o(a,n);if(i.hasEagerState=!0,i.eagerState=c,yr(c,a)){var f=t.interleaved;f===null?(i.next=i,zm(t)):(i.next=f.next,f.next=i),t.interleaved=i;return}}catch{}finally{}n=NI(e,t,i,r),n!==null&&(i=cn(),vr(n,e,r,i),sC(n,t,r))}}function iC(e){var t=e.alternate;return e===_t||t!==null&&t===_t}function oC(e,t){ql=Md=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function sC(e,t,n){if(n&4194240){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,Lm(e,n)}}var Dd={readContext:Qn,useCallback:Wt,useContext:Wt,useEffect:Wt,useImperativeHandle:Wt,useInsertionEffect:Wt,useLayoutEffect:Wt,useMemo:Wt,useReducer:Wt,useRef:Wt,useState:Wt,useDebugValue:Wt,useDeferredValue:Wt,useTransition:Wt,useMutableSource:Wt,useSyncExternalStore:Wt,useId:Wt,unstable_isNewReconciler:!1},ND={readContext:Qn,useCallback:function(e,t){return xr().memoizedState=[e,t===void 0?null:t],e},useContext:Qn,useEffect:sS,useImperativeHandle:function(e,t,n){return n=n!=null?n.concat([e]):null,ed(4194308,4,XI.bind(null,t,e),n)},useLayoutEffect:function(e,t){return ed(4194308,4,e,t)},useInsertionEffect:function(e,t){return ed(4,2,e,t)},useMemo:function(e,t){var n=xr();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=xr();return t=n!==void 0?n(t):t,r.memoizedState=r.baseState=t,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:t},r.queue=e,e=e.dispatch=AD.bind(null,_t,e),[r.memoizedState,e]},useRef:function(e){var t=xr();return e={current:e},t.memoizedState=e},useState:oS,useDebugValue:ry,useDeferredValue:function(e){return xr().memoizedState=e},useTransition:function(){var e=oS(!1),t=e[0];return e=DD.bind(null,e[1]),xr().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var r=_t,i=xr();if(vt){if(n===void 0)throw Error(we(407));n=n()}else{if(n=t(),xt===null)throw Error(we(349));qo&30||VI(r,t,n)}i.memoizedState=n;var o={value:n,getSnapshot:t};return i.queue=o,sS(HI.bind(null,r,o,e),[e]),r.flags|=2048,gu(9,WI.bind(null,r,o,n,t),void 0,null),n},useId:function(){var e=xr(),t=xt.identifierPrefix;if(vt){var n=ti,r=ei;n=(r&~(1<<32-gr(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=hu++,0<n&&(t+="H"+n.toString(32)),t+=":"}else n=MD++,t=":"+t+"r"+n.toString(32)+":";return e.memoizedState=t},unstable_isNewReconciler:!1},xD={readContext:Qn,useCallback:eC,useContext:Qn,useEffect:ny,useImperativeHandle:ZI,useInsertionEffect:QI,useLayoutEffect:JI,useMemo:tC,useReducer:Eh,useRef:YI,useState:function(){return Eh(pu)},useDebugValue:ry,useDeferredValue:function(e){var t=Jn();return nC(t,kt.memoizedState,e)},useTransition:function(){var e=Eh(pu)[0],t=Jn().memoizedState;return[e,t]},useMutableSource:jI,useSyncExternalStore:qI,useId:rC,unstable_isNewReconciler:!1},$D={readContext:Qn,useCallback:eC,useContext:Qn,useEffect:ny,useImperativeHandle:ZI,useInsertionEffect:QI,useLayoutEffect:JI,useMemo:tC,useReducer:wh,useRef:YI,useState:function(){return wh(pu)},useDebugValue:ry,useDeferredValue:function(e){var t=Jn();return kt===null?t.memoizedState=e:nC(t,kt.memoizedState,e)},useTransition:function(){var e=wh(pu)[0],t=Jn().memoizedState;return[e,t]},useMutableSource:jI,useSyncExternalStore:qI,useId:rC,unstable_isNewReconciler:!1};function ca(e,t){try{var n="",r=t;do n+=dM(r),r=r.return;while(r);var i=n}catch(o){i=`
     39 Error generating stack: `+o.message+`
     40 `+o.stack}return{value:e,source:t,stack:i,digest:null}}function bh(e,t,n){return{value:e,source:null,stack:n??null,digest:t??null}}function Wg(e,t){try{console.error(t.value)}catch(n){setTimeout(function(){throw n})}}var UD=typeof WeakMap=="function"?WeakMap:Map;function aC(e,t,n){n=ni(-1,n),n.tag=3,n.payload={element:null};var r=t.value;return n.callback=function(){Ld||(Ld=!0,tv=r),Wg(e,t)},n}function lC(e,t,n){n=ni(-1,n),n.tag=3;var r=e.type.getDerivedStateFromError;if(typeof r=="function"){var i=t.value;n.payload=function(){return r(i)},n.callback=function(){Wg(e,t)}}var o=e.stateNode;return o!==null&&typeof o.componentDidCatch=="function"&&(n.callback=function(){Wg(e,t),typeof r!="function"&&(Yi===null?Yi=new Set([this]):Yi.add(this));var a=t.stack;this.componentDidCatch(t.value,{componentStack:a!==null?a:""})}),n}function aS(e,t,n){var r=e.pingCache;if(r===null){r=e.pingCache=new UD;var i=new Set;r.set(t,i)}else i=r.get(t),i===void 0&&(i=new Set,r.set(t,i));i.has(n)||(i.add(n),e=XD.bind(null,e,t,n),t.then(e,e))}function lS(e){do{var t;if((t=e.tag===13)&&(t=e.memoizedState,t=t!==null?t.dehydrated!==null:!0),t)return e;e=e.return}while(e!==null);return null}function uS(e,t,n,r,i){return e.mode&1?(e.flags|=65536,e.lanes=i,e):(e===t?e.flags|=65536:(e.flags|=128,n.flags|=131072,n.flags&=-52805,n.tag===1&&(n.alternate===null?n.tag=17:(t=ni(-1,1),t.tag=2,zi(n,t,1))),n.lanes|=1),e)}var BD=li.ReactCurrentOwner,wn=!1;function ln(e,t,n,r){t.child=e===null?FI(t,null,n,r):la(t,e.child,n,r)}function cS(e,t,n,r,i){n=n.render;var o=t.ref;return Zs(t,i),r=ey(e,t,n,r,o,i),n=ty(),e!==null&&!wn?(t.updateQueue=e.updateQueue,t.flags&=-2053,e.lanes&=~i,ai(e,t,i)):(vt&&n&&jm(t),t.flags|=1,ln(e,t,r,i),t.child)}function dS(e,t,n,r,i){if(e===null){var o=n.type;return typeof o=="function"&&!dy(o)&&o.defaultProps===void 0&&n.compare===null&&n.defaultProps===void 0?(t.tag=15,t.type=o,uC(e,t,o,r,i)):(e=id(n.type,null,r,t,t.mode,i),e.ref=t.ref,e.return=t,t.child=e)}if(o=e.child,!(e.lanes&i)){var a=o.memoizedProps;if(n=n.compare,n=n!==null?n:au,n(a,r)&&e.ref===t.ref)return ai(e,t,i)}return t.flags|=1,e=Ji(o,r),e.ref=t.ref,e.return=t,t.child=e}function uC(e,t,n,r,i){if(e!==null){var o=e.memoizedProps;if(au(o,r)&&e.ref===t.ref)if(wn=!1,t.pendingProps=r=o,(e.lanes&i)!==0)e.flags&131072&&(wn=!0);else return t.lanes=e.lanes,ai(e,t,i)}return Hg(e,t,n,r,i)}function cC(e,t,n){var r=t.pendingProps,i=r.children,o=e!==null?e.memoizedState:null;if(r.mode==="hidden")if(!(t.mode&1))t.memoizedState={baseLanes:0,cachePool:null,transitions:null},dt(Ws,Mn),Mn|=n;else{if(!(n&1073741824))return e=o!==null?o.baseLanes|n:n,t.lanes=t.childLanes=1073741824,t.memoizedState={baseLanes:e,cachePool:null,transitions:null},t.updateQueue=null,dt(Ws,Mn),Mn|=e,null;t.memoizedState={baseLanes:0,cachePool:null,transitions:null},r=o!==null?o.baseLanes:n,dt(Ws,Mn),Mn|=r}else o!==null?(r=o.baseLanes|n,t.memoizedState=null):r=n,dt(Ws,Mn),Mn|=r;return ln(e,t,i,n),t.child}function dC(e,t){var n=t.ref;(e===null&&n!==null||e!==null&&e.ref!==n)&&(t.flags|=512,t.flags|=2097152)}function Hg(e,t,n,r,i){var o=Rn(n)?Ko:tn.current;return o=sa(t,o),Zs(t,i),n=ey(e,t,n,r,o,i),r=ty(),e!==null&&!wn?(t.updateQueue=e.updateQueue,t.flags&=-2053,e.lanes&=~i,ai(e,t,i)):(vt&&r&&jm(t),t.flags|=1,ln(e,t,n,i),t.child)}function fS(e,t,n,r,i){if(Rn(n)){var o=!0;Td(t)}else o=!1;if(Zs(t,i),t.stateNode===null)td(e,t),UI(t,n,r),Vg(t,n,r,i),r=!0;else if(e===null){var a=t.stateNode,c=t.memoizedProps;a.props=c;var f=a.context,v=n.contextType;typeof v=="object"&&v!==null?v=Qn(v):(v=Rn(n)?Ko:tn.current,v=sa(t,v));var s=n.getDerivedStateFromProps,g=typeof s=="function"||typeof a.getSnapshotBeforeUpdate=="function";g||typeof a.UNSAFE_componentWillReceiveProps!="function"&&typeof a.componentWillReceiveProps!="function"||(c!==r||f!==v)&&rS(t,a,r,v),Li=!1;var y=t.memoizedState;a.state=y,Pd(t,r,a,i),f=t.memoizedState,c!==r||y!==f||Tn.current||Li?(typeof s=="function"&&(qg(t,n,s,r),f=t.memoizedState),(c=Li||nS(t,n,c,r,y,f,v))?(g||typeof a.UNSAFE_componentWillMount!="function"&&typeof a.componentWillMount!="function"||(typeof a.componentWillMount=="function"&&a.componentWillMount(),typeof a.UNSAFE_componentWillMount=="function"&&a.UNSAFE_componentWillMount()),typeof a.componentDidMount=="function"&&(t.flags|=4194308)):(typeof a.componentDidMount=="function"&&(t.flags|=4194308),t.memoizedProps=r,t.memoizedState=f),a.props=r,a.state=f,a.context=v,r=c):(typeof a.componentDidMount=="function"&&(t.flags|=4194308),r=!1)}else{a=t.stateNode,xI(e,t),c=t.memoizedProps,v=t.type===t.elementType?c:dr(t.type,c),a.props=v,g=t.pendingProps,y=a.context,f=n.contextType,typeof f=="object"&&f!==null?f=Qn(f):(f=Rn(n)?Ko:tn.current,f=sa(t,f));var S=n.getDerivedStateFromProps;(s=typeof S=="function"||typeof a.getSnapshotBeforeUpdate=="function")||typeof a.UNSAFE_componentWillReceiveProps!="function"&&typeof a.componentWillReceiveProps!="function"||(c!==g||y!==f)&&rS(t,a,r,f),Li=!1,y=t.memoizedState,a.state=y,Pd(t,r,a,i);var m=t.memoizedState;c!==g||y!==m||Tn.current||Li?(typeof S=="function"&&(qg(t,n,S,r),m=t.memoizedState),(v=Li||nS(t,n,v,r,y,m,f)||!1)?(s||typeof a.UNSAFE_componentWillUpdate!="function"&&typeof a.componentWillUpdate!="function"||(typeof a.componentWillUpdate=="function"&&a.componentWillUpdate(r,m,f),typeof a.UNSAFE_componentWillUpdate=="function"&&a.UNSAFE_componentWillUpdate(r,m,f)),typeof a.componentDidUpdate=="function"&&(t.flags|=4),typeof a.getSnapshotBeforeUpdate=="function"&&(t.flags|=1024)):(typeof a.componentDidUpdate!="function"||c===e.memoizedProps&&y===e.memoizedState||(t.flags|=4),typeof a.getSnapshotBeforeUpdate!="function"||c===e.memoizedProps&&y===e.memoizedState||(t.flags|=1024),t.memoizedProps=r,t.memoizedState=m),a.props=r,a.state=m,a.context=f,r=v):(typeof a.componentDidUpdate!="function"||c===e.memoizedProps&&y===e.memoizedState||(t.flags|=4),typeof a.getSnapshotBeforeUpdate!="function"||c===e.memoizedProps&&y===e.memoizedState||(t.flags|=1024),r=!1)}return Gg(e,t,n,r,o,i)}function Gg(e,t,n,r,i,o){dC(e,t);var a=(t.flags&128)!==0;if(!r&&!a)return i&&J_(t,n,!1),ai(e,t,o);r=t.stateNode,BD.current=t;var c=a&&typeof n.getDerivedStateFromError!="function"?null:r.render();return t.flags|=1,e!==null&&a?(t.child=la(t,e.child,null,o),t.child=la(t,null,c,o)):ln(e,t,c,o),t.memoizedState=r.state,i&&J_(t,n,!0),t.child}function fC(e){var t=e.stateNode;t.pendingContext?Q_(e,t.pendingContext,t.pendingContext!==t.context):t.context&&Q_(e,t.context,!1),Qm(e,t.containerInfo)}function hS(e,t,n,r,i){return aa(),Vm(i),t.flags|=256,ln(e,t,n,r),t.child}var zg={dehydrated:null,treeContext:null,retryLane:0};function Yg(e){return{baseLanes:e,cachePool:null,transitions:null}}function hC(e,t,n){var r=t.pendingProps,i=mt.current,o=!1,a=(t.flags&128)!==0,c;if((c=a)||(c=e!==null&&e.memoizedState===null?!1:(i&2)!==0),c?(o=!0,t.flags&=-129):(e===null||e.memoizedState!==null)&&(i|=1),dt(mt,i&1),e===null)return Kg(t),e=t.memoizedState,e!==null&&(e=e.dehydrated,e!==null)?(t.mode&1?e.data==="$!"?t.lanes=8:t.lanes=1073741824:t.lanes=1,null):(a=r.children,e=r.fallback,o?(r=t.mode,o=t.child,a={mode:"hidden",children:a},!(r&1)&&o!==null?(o.childLanes=0,o.pendingProps=a):o=Sf(a,r,0,null),e=Bo(e,r,n,null),o.return=t,e.return=t,o.sibling=e,t.child=o,t.child.memoizedState=Yg(n),t.memoizedState=zg,e):iy(t,a));if(i=e.memoizedState,i!==null&&(c=i.dehydrated,c!==null))return FD(e,t,a,r,c,i,n);if(o){o=r.fallback,a=t.mode,i=e.child,c=i.sibling;var f={mode:"hidden",children:r.children};return!(a&1)&&t.child!==i?(r=t.child,r.childLanes=0,r.pendingProps=f,t.deletions=null):(r=Ji(i,f),r.subtreeFlags=i.subtreeFlags&14680064),c!==null?o=Ji(c,o):(o=Bo(o,a,n,null),o.flags|=2),o.return=t,r.return=t,r.sibling=o,t.child=r,r=o,o=t.child,a=e.child.memoizedState,a=a===null?Yg(n):{baseLanes:a.baseLanes|n,cachePool:null,transitions:a.transitions},o.memoizedState=a,o.childLanes=e.childLanes&~n,t.memoizedState=zg,r}return o=e.child,e=o.sibling,r=Ji(o,{mode:"visible",children:r.children}),!(t.mode&1)&&(r.lanes=n),r.return=t,r.sibling=null,e!==null&&(n=t.deletions,n===null?(t.deletions=[e],t.flags|=16):n.push(e)),t.child=r,t.memoizedState=null,r}function iy(e,t){return t=Sf({mode:"visible",children:t},e.mode,0,null),t.return=e,e.child=t}function gc(e,t,n,r){return r!==null&&Vm(r),la(t,e.child,null,n),e=iy(t,t.pendingProps.children),e.flags|=2,t.memoizedState=null,e}function FD(e,t,n,r,i,o,a){if(n)return t.flags&256?(t.flags&=-257,r=bh(Error(we(422))),gc(e,t,a,r)):t.memoizedState!==null?(t.child=e.child,t.flags|=128,null):(o=r.fallback,i=t.mode,r=Sf({mode:"visible",children:r.children},i,0,null),o=Bo(o,i,a,null),o.flags|=2,r.return=t,o.return=t,r.sibling=o,t.child=r,t.mode&1&&la(t,e.child,null,a),t.child.memoizedState=Yg(a),t.memoizedState=zg,o);if(!(t.mode&1))return gc(e,t,a,null);if(i.data==="$!"){if(r=i.nextSibling&&i.nextSibling.dataset,r)var c=r.dgst;return r=c,o=Error(we(419)),r=bh(o,r,void 0),gc(e,t,a,r)}if(c=(a&e.childLanes)!==0,wn||c){if(r=xt,r!==null){switch(a&-a){case 4:i=2;break;case 16:i=8;break;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:i=32;break;case 536870912:i=268435456;break;default:i=0}i=i&(r.suspendedLanes|a)?0:i,i!==0&&i!==o.retryLane&&(o.retryLane=i,si(e,i),vr(r,e,i,-1))}return cy(),r=bh(Error(we(421))),gc(e,t,a,r)}return i.data==="$?"?(t.flags|=128,t.child=e.child,t=ZD.bind(null,e),i._reactRetry=t,null):(e=o.treeContext,Dn=Gi(i.nextSibling),Ln=t,vt=!0,hr=null,e!==null&&(Hn[Gn++]=ei,Hn[Gn++]=ti,Hn[Gn++]=jo,ei=e.id,ti=e.overflow,jo=t),t=iy(t,r.children),t.flags|=4096,t)}function pS(e,t,n){e.lanes|=t;var r=e.alternate;r!==null&&(r.lanes|=t),jg(e.return,t,n)}function Th(e,t,n,r,i){var o=e.memoizedState;o===null?e.memoizedState={isBackwards:t,rendering:null,renderingStartTime:0,last:r,tail:n,tailMode:i}:(o.isBackwards=t,o.rendering=null,o.renderingStartTime=0,o.last=r,o.tail=n,o.tailMode=i)}function pC(e,t,n){var r=t.pendingProps,i=r.revealOrder,o=r.tail;if(ln(e,t,r.children,n),r=mt.current,r&2)r=r&1|2,t.flags|=128;else{if(e!==null&&e.flags&128)e:for(e=t.child;e!==null;){if(e.tag===13)e.memoizedState!==null&&pS(e,n,t);else if(e.tag===19)pS(e,n,t);else if(e.child!==null){e.child.return=e,e=e.child;continue}if(e===t)break e;for(;e.sibling===null;){if(e.return===null||e.return===t)break e;e=e.return}e.sibling.return=e.return,e=e.sibling}r&=1}if(dt(mt,r),!(t.mode&1))t.memoizedState=null;else switch(i){case"forwards":for(n=t.child,i=null;n!==null;)e=n.alternate,e!==null&&kd(e)===null&&(i=n),n=n.sibling;n=i,n===null?(i=t.child,t.child=null):(i=n.sibling,n.sibling=null),Th(t,!1,i,n,o);break;case"backwards":for(n=null,i=t.child,t.child=null;i!==null;){if(e=i.alternate,e!==null&&kd(e)===null){t.child=i;break}e=i.sibling,i.sibling=n,n=i,i=e}Th(t,!0,n,null,o);break;case"together":Th(t,!1,null,null,void 0);break;default:t.memoizedState=null}return t.child}function td(e,t){!(t.mode&1)&&e!==null&&(e.alternate=null,t.alternate=null,t.flags|=2)}function ai(e,t,n){if(e!==null&&(t.dependencies=e.dependencies),Vo|=t.lanes,!(n&t.childLanes))return null;if(e!==null&&t.child!==e.child)throw Error(we(153));if(t.child!==null){for(e=t.child,n=Ji(e,e.pendingProps),t.child=n,n.return=t;e.sibling!==null;)e=e.sibling,n=n.sibling=Ji(e,e.pendingProps),n.return=t;n.sibling=null}return t.child}function KD(e,t,n){switch(t.tag){case 3:fC(t),aa();break;case 5:KI(t);break;case 1:Rn(t.type)&&Td(t);break;case 4:Qm(t,t.stateNode.containerInfo);break;case 10:var r=t.type._context,i=t.memoizedProps.value;dt(Cd,r._currentValue),r._currentValue=i;break;case 13:if(r=t.memoizedState,r!==null)return r.dehydrated!==null?(dt(mt,mt.current&1),t.flags|=128,null):n&t.child.childLanes?hC(e,t,n):(dt(mt,mt.current&1),e=ai(e,t,n),e!==null?e.sibling:null);dt(mt,mt.current&1);break;case 19:if(r=(n&t.childLanes)!==0,e.flags&128){if(r)return pC(e,t,n);t.flags|=128}if(i=t.memoizedState,i!==null&&(i.rendering=null,i.tail=null,i.lastEffect=null),dt(mt,mt.current),r)break;return null;case 22:case 23:return t.lanes=0,cC(e,t,n)}return ai(e,t,n)}var gC,Qg,vC,mC;gC=function(e,t){for(var n=t.child;n!==null;){if(n.tag===5||n.tag===6)e.appendChild(n.stateNode);else if(n.tag!==4&&n.child!==null){n.child.return=n,n=n.child;continue}if(n===t)break;for(;n.sibling===null;){if(n.return===null||n.return===t)return;n=n.return}n.sibling.return=n.return,n=n.sibling}};Qg=function(){};vC=function(e,t,n,r){var i=e.memoizedProps;if(i!==r){e=t.stateNode,xo(Fr.current);var o=null;switch(n){case"input":i=yg(e,i),r=yg(e,r),o=[];break;case"select":i=St({},i,{value:void 0}),r=St({},r,{value:void 0}),o=[];break;case"textarea":i=Eg(e,i),r=Eg(e,r),o=[];break;default:typeof i.onClick!="function"&&typeof r.onClick=="function"&&(e.onclick=wd)}bg(n,r);var a;n=null;for(v in i)if(!r.hasOwnProperty(v)&&i.hasOwnProperty(v)&&i[v]!=null)if(v==="style"){var c=i[v];for(a in c)c.hasOwnProperty(a)&&(n||(n={}),n[a]="")}else v!=="dangerouslySetInnerHTML"&&v!=="children"&&v!=="suppressContentEditableWarning"&&v!=="suppressHydrationWarning"&&v!=="autoFocus"&&(eu.hasOwnProperty(v)?o||(o=[]):(o=o||[]).push(v,null));for(v in r){var f=r[v];if(c=i!=null?i[v]:void 0,r.hasOwnProperty(v)&&f!==c&&(f!=null||c!=null))if(v==="style")if(c){for(a in c)!c.hasOwnProperty(a)||f&&f.hasOwnProperty(a)||(n||(n={}),n[a]="");for(a in f)f.hasOwnProperty(a)&&c[a]!==f[a]&&(n||(n={}),n[a]=f[a])}else n||(o||(o=[]),o.push(v,n)),n=f;else v==="dangerouslySetInnerHTML"?(f=f?f.__html:void 0,c=c?c.__html:void 0,f!=null&&c!==f&&(o=o||[]).push(v,f)):v==="children"?typeof f!="string"&&typeof f!="number"||(o=o||[]).push(v,""+f):v!=="suppressContentEditableWarning"&&v!=="suppressHydrationWarning"&&(eu.hasOwnProperty(v)?(f!=null&&v==="onScroll"&&ft("scroll",e),o||c===f||(o=[])):(o=o||[]).push(v,f))}n&&(o=o||[]).push("style",n);var v=o;(t.updateQueue=v)&&(t.flags|=4)}};mC=function(e,t,n,r){n!==r&&(t.flags|=4)};function $a(e,t){if(!vt)switch(e.tailMode){case"hidden":t=e.tail;for(var n=null;t!==null;)t.alternate!==null&&(n=t),t=t.sibling;n===null?e.tail=null:n.sibling=null;break;case"collapsed":n=e.tail;for(var r=null;n!==null;)n.alternate!==null&&(r=n),n=n.sibling;r===null?t||e.tail===null?e.tail=null:e.tail.sibling=null:r.sibling=null}}function Ht(e){var t=e.alternate!==null&&e.alternate.child===e.child,n=0,r=0;if(t)for(var i=e.child;i!==null;)n|=i.lanes|i.childLanes,r|=i.subtreeFlags&14680064,r|=i.flags&14680064,i.return=e,i=i.sibling;else for(i=e.child;i!==null;)n|=i.lanes|i.childLanes,r|=i.subtreeFlags,r|=i.flags,i.return=e,i=i.sibling;return e.subtreeFlags|=r,e.childLanes=n,t}function jD(e,t,n){var r=t.pendingProps;switch(qm(t),t.tag){case 2:case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return Ht(t),null;case 1:return Rn(t.type)&&bd(),Ht(t),null;case 3:return r=t.stateNode,ua(),pt(Tn),pt(tn),Xm(),r.pendingContext&&(r.context=r.pendingContext,r.pendingContext=null),(e===null||e.child===null)&&(hc(t)?t.flags|=4:e===null||e.memoizedState.isDehydrated&&!(t.flags&256)||(t.flags|=1024,hr!==null&&(iv(hr),hr=null))),Qg(e,t),Ht(t),null;case 5:Jm(t);var i=xo(fu.current);if(n=t.type,e!==null&&t.stateNode!=null)vC(e,t,n,r,i),e.ref!==t.ref&&(t.flags|=512,t.flags|=2097152);else{if(!r){if(t.stateNode===null)throw Error(we(166));return Ht(t),null}if(e=xo(Fr.current),hc(t)){r=t.stateNode,n=t.type;var o=t.memoizedProps;switch(r[$r]=t,r[cu]=o,e=(t.mode&1)!==0,n){case"dialog":ft("cancel",r),ft("close",r);break;case"iframe":case"object":case"embed":ft("load",r);break;case"video":case"audio":for(i=0;i<Al.length;i++)ft(Al[i],r);break;case"source":ft("error",r);break;case"img":case"image":case"link":ft("error",r),ft("load",r);break;case"details":ft("toggle",r);break;case"input":b_(r,o),ft("invalid",r);break;case"select":r._wrapperState={wasMultiple:!!o.multiple},ft("invalid",r);break;case"textarea":R_(r,o),ft("invalid",r)}bg(n,o),i=null;for(var a in o)if(o.hasOwnProperty(a)){var c=o[a];a==="children"?typeof c=="string"?r.textContent!==c&&(o.suppressHydrationWarning!==!0&&fc(r.textContent,c,e),i=["children",c]):typeof c=="number"&&r.textContent!==""+c&&(o.suppressHydrationWarning!==!0&&fc(r.textContent,c,e),i=["children",""+c]):eu.hasOwnProperty(a)&&c!=null&&a==="onScroll"&&ft("scroll",r)}switch(n){case"input":ic(r),T_(r,o,!0);break;case"textarea":ic(r),I_(r);break;case"select":case"option":break;default:typeof o.onClick=="function"&&(r.onclick=wd)}r=i,t.updateQueue=r,r!==null&&(t.flags|=4)}else{a=i.nodeType===9?i:i.ownerDocument,e==="http://www.w3.org/1999/xhtml"&&(e=VR(n)),e==="http://www.w3.org/1999/xhtml"?n==="script"?(e=a.createElement("div"),e.innerHTML="<script><\/script>",e=e.removeChild(e.firstChild)):typeof r.is=="string"?e=a.createElement(n,{is:r.is}):(e=a.createElement(n),n==="select"&&(a=e,r.multiple?a.multiple=!0:r.size&&(a.size=r.size))):e=a.createElementNS(e,n),e[$r]=t,e[cu]=r,gC(e,t,!1,!1),t.stateNode=e;e:{switch(a=Tg(n,r),n){case"dialog":ft("cancel",e),ft("close",e),i=r;break;case"iframe":case"object":case"embed":ft("load",e),i=r;break;case"video":case"audio":for(i=0;i<Al.length;i++)ft(Al[i],e);i=r;break;case"source":ft("error",e),i=r;break;case"img":case"image":case"link":ft("error",e),ft("load",e),i=r;break;case"details":ft("toggle",e),i=r;break;case"input":b_(e,r),i=yg(e,r),ft("invalid",e);break;case"option":i=r;break;case"select":e._wrapperState={wasMultiple:!!r.multiple},i=St({},r,{value:void 0}),ft("invalid",e);break;case"textarea":R_(e,r),i=Eg(e,r),ft("invalid",e);break;default:i=r}bg(n,i),c=i;for(o in c)if(c.hasOwnProperty(o)){var f=c[o];o==="style"?GR(e,f):o==="dangerouslySetInnerHTML"?(f=f?f.__html:void 0,f!=null&&WR(e,f)):o==="children"?typeof f=="string"?(n!=="textarea"||f!=="")&&tu(e,f):typeof f=="number"&&tu(e,""+f):o!=="suppressContentEditableWarning"&&o!=="suppressHydrationWarning"&&o!=="autoFocus"&&(eu.hasOwnProperty(o)?f!=null&&o==="onScroll"&&ft("scroll",e):f!=null&&Om(e,o,f,a))}switch(n){case"input":ic(e),T_(e,r,!1);break;case"textarea":ic(e),I_(e);break;case"option":r.value!=null&&e.setAttribute("value",""+to(r.value));break;case"select":e.multiple=!!r.multiple,o=r.value,o!=null?Ys(e,!!r.multiple,o,!1):r.defaultValue!=null&&Ys(e,!!r.multiple,r.defaultValue,!0);break;default:typeof i.onClick=="function"&&(e.onclick=wd)}switch(n){case"button":case"input":case"select":case"textarea":r=!!r.autoFocus;break e;case"img":r=!0;break e;default:r=!1}}r&&(t.flags|=4)}t.ref!==null&&(t.flags|=512,t.flags|=2097152)}return Ht(t),null;case 6:if(e&&t.stateNode!=null)mC(e,t,e.memoizedProps,r);else{if(typeof r!="string"&&t.stateNode===null)throw Error(we(166));if(n=xo(fu.current),xo(Fr.current),hc(t)){if(r=t.stateNode,n=t.memoizedProps,r[$r]=t,(o=r.nodeValue!==n)&&(e=Ln,e!==null))switch(e.tag){case 3:fc(r.nodeValue,n,(e.mode&1)!==0);break;case 5:e.memoizedProps.suppressHydrationWarning!==!0&&fc(r.nodeValue,n,(e.mode&1)!==0)}o&&(t.flags|=4)}else r=(n.nodeType===9?n:n.ownerDocument).createTextNode(r),r[$r]=t,t.stateNode=r}return Ht(t),null;case 13:if(pt(mt),r=t.memoizedState,e===null||e.memoizedState!==null&&e.memoizedState.dehydrated!==null){if(vt&&Dn!==null&&t.mode&1&&!(t.flags&128))LI(),aa(),t.flags|=98560,o=!1;else if(o=hc(t),r!==null&&r.dehydrated!==null){if(e===null){if(!o)throw Error(we(318));if(o=t.memoizedState,o=o!==null?o.dehydrated:null,!o)throw Error(we(317));o[$r]=t}else aa(),!(t.flags&128)&&(t.memoizedState=null),t.flags|=4;Ht(t),o=!1}else hr!==null&&(iv(hr),hr=null),o=!0;if(!o)return t.flags&65536?t:null}return t.flags&128?(t.lanes=n,t):(r=r!==null,r!==(e!==null&&e.memoizedState!==null)&&r&&(t.child.flags|=8192,t.mode&1&&(e===null||mt.current&1?Dt===0&&(Dt=3):cy())),t.updateQueue!==null&&(t.flags|=4),Ht(t),null);case 4:return ua(),Qg(e,t),e===null&&lu(t.stateNode.containerInfo),Ht(t),null;case 10:return Gm(t.type._context),Ht(t),null;case 17:return Rn(t.type)&&bd(),Ht(t),null;case 19:if(pt(mt),o=t.memoizedState,o===null)return Ht(t),null;if(r=(t.flags&128)!==0,a=o.rendering,a===null)if(r)$a(o,!1);else{if(Dt!==0||e!==null&&e.flags&128)for(e=t.child;e!==null;){if(a=kd(e),a!==null){for(t.flags|=128,$a(o,!1),r=a.updateQueue,r!==null&&(t.updateQueue=r,t.flags|=4),t.subtreeFlags=0,r=n,n=t.child;n!==null;)o=n,e=r,o.flags&=14680066,a=o.alternate,a===null?(o.childLanes=0,o.lanes=e,o.child=null,o.subtreeFlags=0,o.memoizedProps=null,o.memoizedState=null,o.updateQueue=null,o.dependencies=null,o.stateNode=null):(o.childLanes=a.childLanes,o.lanes=a.lanes,o.child=a.child,o.subtreeFlags=0,o.deletions=null,o.memoizedProps=a.memoizedProps,o.memoizedState=a.memoizedState,o.updateQueue=a.updateQueue,o.type=a.type,e=a.dependencies,o.dependencies=e===null?null:{lanes:e.lanes,firstContext:e.firstContext}),n=n.sibling;return dt(mt,mt.current&1|2),t.child}e=e.sibling}o.tail!==null&&Tt()>da&&(t.flags|=128,r=!0,$a(o,!1),t.lanes=4194304)}else{if(!r)if(e=kd(a),e!==null){if(t.flags|=128,r=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),$a(o,!0),o.tail===null&&o.tailMode==="hidden"&&!a.alternate&&!vt)return Ht(t),null}else 2*Tt()-o.renderingStartTime>da&&n!==1073741824&&(t.flags|=128,r=!0,$a(o,!1),t.lanes=4194304);o.isBackwards?(a.sibling=t.child,t.child=a):(n=o.last,n!==null?n.sibling=a:t.child=a,o.last=a)}return o.tail!==null?(t=o.tail,o.rendering=t,o.tail=t.sibling,o.renderingStartTime=Tt(),t.sibling=null,n=mt.current,dt(mt,r?n&1|2:n&1),t):(Ht(t),null);case 22:case 23:return uy(),r=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==r&&(t.flags|=8192),r&&t.mode&1?Mn&1073741824&&(Ht(t),t.subtreeFlags&6&&(t.flags|=8192)):Ht(t),null;case 24:return null;case 25:return null}throw Error(we(156,t.tag))}function qD(e,t){switch(qm(t),t.tag){case 1:return Rn(t.type)&&bd(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return ua(),pt(Tn),pt(tn),Xm(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return Jm(t),null;case 13:if(pt(mt),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(we(340));aa()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return pt(mt),null;case 4:return ua(),null;case 10:return Gm(t.type._context),null;case 22:case 23:return uy(),null;case 24:return null;default:return null}}var vc=!1,Zt=!1,VD=typeof WeakSet=="function"?WeakSet:Set,Ke=null;function Vs(e,t){var n=e.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){wt(e,t,r)}else n.current=null}function Jg(e,t,n){try{n()}catch(r){wt(e,t,r)}}var gS=!1;function WD(e,t){if(Lg=_d,e=EI(),Km(e)){if("selectionStart"in e)var n={start:e.selectionStart,end:e.selectionEnd};else e:{n=(n=e.ownerDocument)&&n.defaultView||window;var r=n.getSelection&&n.getSelection();if(r&&r.rangeCount!==0){n=r.anchorNode;var i=r.anchorOffset,o=r.focusNode;r=r.focusOffset;try{n.nodeType,o.nodeType}catch{n=null;break e}var a=0,c=-1,f=-1,v=0,s=0,g=e,y=null;t:for(;;){for(var S;g!==n||i!==0&&g.nodeType!==3||(c=a+i),g!==o||r!==0&&g.nodeType!==3||(f=a+r),g.nodeType===3&&(a+=g.nodeValue.length),(S=g.firstChild)!==null;)y=g,g=S;for(;;){if(g===e)break t;if(y===n&&++v===i&&(c=a),y===o&&++s===r&&(f=a),(S=g.nextSibling)!==null)break;g=y,y=g.parentNode}g=S}n=c===-1||f===-1?null:{start:c,end:f}}else n=null}n=n||{start:0,end:0}}else n=null;for(Ng={focusedElem:e,selectionRange:n},_d=!1,Ke=t;Ke!==null;)if(t=Ke,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,Ke=e;else for(;Ke!==null;){t=Ke;try{var m=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(m!==null){var p=m.memoizedProps,_=m.memoizedState,u=t.stateNode,l=u.getSnapshotBeforeUpdate(t.elementType===t.type?p:dr(t.type,p),_);u.__reactInternalSnapshotBeforeUpdate=l}break;case 3:var d=t.stateNode.containerInfo;d.nodeType===1?d.textContent="":d.nodeType===9&&d.documentElement&&d.removeChild(d.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(we(163))}}catch(h){wt(t,t.return,h)}if(e=t.sibling,e!==null){e.return=t.return,Ke=e;break}Ke=t.return}return m=gS,gS=!1,m}function Vl(e,t,n){var r=t.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var i=r=r.next;do{if((i.tag&e)===e){var o=i.destroy;i.destroy=void 0,o!==void 0&&Jg(t,n,o)}i=i.next}while(i!==r)}}function yf(e,t){if(t=t.updateQueue,t=t!==null?t.lastEffect:null,t!==null){var n=t=t.next;do{if((n.tag&e)===e){var r=n.create;n.destroy=r()}n=n.next}while(n!==t)}}function Xg(e){var t=e.ref;if(t!==null){var n=e.stateNode;switch(e.tag){case 5:e=n;break;default:e=n}typeof t=="function"?t(e):t.current=e}}function yC(e){var t=e.alternate;t!==null&&(e.alternate=null,yC(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[$r],delete t[cu],delete t[Ug],delete t[CD],delete t[OD])),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}function _C(e){return e.tag===5||e.tag===3||e.tag===4}function vS(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||_C(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.flags&2||e.child===null||e.tag===4)continue e;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function Zg(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.nodeType===8?n.parentNode.insertBefore(e,t):n.insertBefore(e,t):(n.nodeType===8?(t=n.parentNode,t.insertBefore(e,n)):(t=n,t.appendChild(e)),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=wd));else if(r!==4&&(e=e.child,e!==null))for(Zg(e,t,n),e=e.sibling;e!==null;)Zg(e,t,n),e=e.sibling}function ev(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(r!==4&&(e=e.child,e!==null))for(ev(e,t,n),e=e.sibling;e!==null;)ev(e,t,n),e=e.sibling}var Ft=null,fr=!1;function pi(e,t,n){for(n=n.child;n!==null;)SC(e,t,n),n=n.sibling}function SC(e,t,n){if(Br&&typeof Br.onCommitFiberUnmount=="function")try{Br.onCommitFiberUnmount(cf,n)}catch{}switch(n.tag){case 5:Zt||Vs(n,t);case 6:var r=Ft,i=fr;Ft=null,pi(e,t,n),Ft=r,fr=i,Ft!==null&&(fr?(e=Ft,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):Ft.removeChild(n.stateNode));break;case 18:Ft!==null&&(fr?(e=Ft,n=n.stateNode,e.nodeType===8?mh(e.parentNode,n):e.nodeType===1&&mh(e,n),ou(e)):mh(Ft,n.stateNode));break;case 4:r=Ft,i=fr,Ft=n.stateNode.containerInfo,fr=!0,pi(e,t,n),Ft=r,fr=i;break;case 0:case 11:case 14:case 15:if(!Zt&&(r=n.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){i=r=r.next;do{var o=i,a=o.destroy;o=o.tag,a!==void 0&&(o&2||o&4)&&Jg(n,t,a),i=i.next}while(i!==r)}pi(e,t,n);break;case 1:if(!Zt&&(Vs(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(c){wt(n,t,c)}pi(e,t,n);break;case 21:pi(e,t,n);break;case 22:n.mode&1?(Zt=(r=Zt)||n.memoizedState!==null,pi(e,t,n),Zt=r):pi(e,t,n);break;default:pi(e,t,n)}}function mS(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var n=e.stateNode;n===null&&(n=e.stateNode=new VD),t.forEach(function(r){var i=e1.bind(null,e,r);n.has(r)||(n.add(r),r.then(i,i))})}}function sr(e,t){var n=t.deletions;if(n!==null)for(var r=0;r<n.length;r++){var i=n[r];try{var o=e,a=t,c=a;e:for(;c!==null;){switch(c.tag){case 5:Ft=c.stateNode,fr=!1;break e;case 3:Ft=c.stateNode.containerInfo,fr=!0;break e;case 4:Ft=c.stateNode.containerInfo,fr=!0;break e}c=c.return}if(Ft===null)throw Error(we(160));SC(o,a,i),Ft=null,fr=!1;var f=i.alternate;f!==null&&(f.return=null),i.return=null}catch(v){wt(i,t,v)}}if(t.subtreeFlags&12854)for(t=t.child;t!==null;)EC(t,e),t=t.sibling}function EC(e,t){var n=e.alternate,r=e.flags;switch(e.tag){case 0:case 11:case 14:case 15:if(sr(t,e),Cr(e),r&4){try{Vl(3,e,e.return),yf(3,e)}catch(p){wt(e,e.return,p)}try{Vl(5,e,e.return)}catch(p){wt(e,e.return,p)}}break;case 1:sr(t,e),Cr(e),r&512&&n!==null&&Vs(n,n.return);break;case 5:if(sr(t,e),Cr(e),r&512&&n!==null&&Vs(n,n.return),e.flags&32){var i=e.stateNode;try{tu(i,"")}catch(p){wt(e,e.return,p)}}if(r&4&&(i=e.stateNode,i!=null)){var o=e.memoizedProps,a=n!==null?n.memoizedProps:o,c=e.type,f=e.updateQueue;if(e.updateQueue=null,f!==null)try{c==="input"&&o.type==="radio"&&o.name!=null&&jR(i,o),Tg(c,a);var v=Tg(c,o);for(a=0;a<f.length;a+=2){var s=f[a],g=f[a+1];s==="style"?GR(i,g):s==="dangerouslySetInnerHTML"?WR(i,g):s==="children"?tu(i,g):Om(i,s,g,v)}switch(c){case"input":_g(i,o);break;case"textarea":qR(i,o);break;case"select":var y=i._wrapperState.wasMultiple;i._wrapperState.wasMultiple=!!o.multiple;var S=o.value;S!=null?Ys(i,!!o.multiple,S,!1):y!==!!o.multiple&&(o.defaultValue!=null?Ys(i,!!o.multiple,o.defaultValue,!0):Ys(i,!!o.multiple,o.multiple?[]:"",!1))}i[cu]=o}catch(p){wt(e,e.return,p)}}break;case 6:if(sr(t,e),Cr(e),r&4){if(e.stateNode===null)throw Error(we(162));i=e.stateNode,o=e.memoizedProps;try{i.nodeValue=o}catch(p){wt(e,e.return,p)}}break;case 3:if(sr(t,e),Cr(e),r&4&&n!==null&&n.memoizedState.isDehydrated)try{ou(t.containerInfo)}catch(p){wt(e,e.return,p)}break;case 4:sr(t,e),Cr(e);break;case 13:sr(t,e),Cr(e),i=e.child,i.flags&8192&&(o=i.memoizedState!==null,i.stateNode.isHidden=o,!o||i.alternate!==null&&i.alternate.memoizedState!==null||(ay=Tt())),r&4&&mS(e);break;case 22:if(s=n!==null&&n.memoizedState!==null,e.mode&1?(Zt=(v=Zt)||s,sr(t,e),Zt=v):sr(t,e),Cr(e),r&8192){if(v=e.memoizedState!==null,(e.stateNode.isHidden=v)&&!s&&e.mode&1)for(Ke=e,s=e.child;s!==null;){for(g=Ke=s;Ke!==null;){switch(y=Ke,S=y.child,y.tag){case 0:case 11:case 14:case 15:Vl(4,y,y.return);break;case 1:Vs(y,y.return);var m=y.stateNode;if(typeof m.componentWillUnmount=="function"){r=y,n=y.return;try{t=r,m.props=t.memoizedProps,m.state=t.memoizedState,m.componentWillUnmount()}catch(p){wt(r,n,p)}}break;case 5:Vs(y,y.return);break;case 22:if(y.memoizedState!==null){_S(g);continue}}S!==null?(S.return=y,Ke=S):_S(g)}s=s.sibling}e:for(s=null,g=e;;){if(g.tag===5){if(s===null){s=g;try{i=g.stateNode,v?(o=i.style,typeof o.setProperty=="function"?o.setProperty("display","none","important"):o.display="none"):(c=g.stateNode,f=g.memoizedProps.style,a=f!=null&&f.hasOwnProperty("display")?f.display:null,c.style.display=HR("display",a))}catch(p){wt(e,e.return,p)}}}else if(g.tag===6){if(s===null)try{g.stateNode.nodeValue=v?"":g.memoizedProps}catch(p){wt(e,e.return,p)}}else if((g.tag!==22&&g.tag!==23||g.memoizedState===null||g===e)&&g.child!==null){g.child.return=g,g=g.child;continue}if(g===e)break e;for(;g.sibling===null;){if(g.return===null||g.return===e)break e;s===g&&(s=null),g=g.return}s===g&&(s=null),g.sibling.return=g.return,g=g.sibling}}break;case 19:sr(t,e),Cr(e),r&4&&mS(e);break;case 21:break;default:sr(t,e),Cr(e)}}function Cr(e){var t=e.flags;if(t&2){try{e:{for(var n=e.return;n!==null;){if(_C(n)){var r=n;break e}n=n.return}throw Error(we(160))}switch(r.tag){case 5:var i=r.stateNode;r.flags&32&&(tu(i,""),r.flags&=-33);var o=vS(e);ev(e,o,i);break;case 3:case 4:var a=r.stateNode.containerInfo,c=vS(e);Zg(e,c,a);break;default:throw Error(we(161))}}catch(f){wt(e,e.return,f)}e.flags&=-3}t&4096&&(e.flags&=-4097)}function HD(e,t,n){Ke=e,wC(e)}function wC(e,t,n){for(var r=(e.mode&1)!==0;Ke!==null;){var i=Ke,o=i.child;if(i.tag===22&&r){var a=i.memoizedState!==null||vc;if(!a){var c=i.alternate,f=c!==null&&c.memoizedState!==null||Zt;c=vc;var v=Zt;if(vc=a,(Zt=f)&&!v)for(Ke=i;Ke!==null;)a=Ke,f=a.child,a.tag===22&&a.memoizedState!==null?SS(i):f!==null?(f.return=a,Ke=f):SS(i);for(;o!==null;)Ke=o,wC(o),o=o.sibling;Ke=i,vc=c,Zt=v}yS(e)}else i.subtreeFlags&8772&&o!==null?(o.return=i,Ke=o):yS(e)}}function yS(e){for(;Ke!==null;){var t=Ke;if(t.flags&8772){var n=t.alternate;try{if(t.flags&8772)switch(t.tag){case 0:case 11:case 15:Zt||yf(5,t);break;case 1:var r=t.stateNode;if(t.flags&4&&!Zt)if(n===null)r.componentDidMount();else{var i=t.elementType===t.type?n.memoizedProps:dr(t.type,n.memoizedProps);r.componentDidUpdate(i,n.memoizedState,r.__reactInternalSnapshotBeforeUpdate)}var o=t.updateQueue;o!==null&&tS(t,o,r);break;case 3:var a=t.updateQueue;if(a!==null){if(n=null,t.child!==null)switch(t.child.tag){case 5:n=t.child.stateNode;break;case 1:n=t.child.stateNode}tS(t,a,n)}break;case 5:var c=t.stateNode;if(n===null&&t.flags&4){n=c;var f=t.memoizedProps;switch(t.type){case"button":case"input":case"select":case"textarea":f.autoFocus&&n.focus();break;case"img":f.src&&(n.src=f.src)}}break;case 6:break;case 4:break;case 12:break;case 13:if(t.memoizedState===null){var v=t.alternate;if(v!==null){var s=v.memoizedState;if(s!==null){var g=s.dehydrated;g!==null&&ou(g)}}}break;case 19:case 17:case 21:case 22:case 23:case 25:break;default:throw Error(we(163))}Zt||t.flags&512&&Xg(t)}catch(y){wt(t,t.return,y)}}if(t===e){Ke=null;break}if(n=t.sibling,n!==null){n.return=t.return,Ke=n;break}Ke=t.return}}function _S(e){for(;Ke!==null;){var t=Ke;if(t===e){Ke=null;break}var n=t.sibling;if(n!==null){n.return=t.return,Ke=n;break}Ke=t.return}}function SS(e){for(;Ke!==null;){var t=Ke;try{switch(t.tag){case 0:case 11:case 15:var n=t.return;try{yf(4,t)}catch(f){wt(t,n,f)}break;case 1:var r=t.stateNode;if(typeof r.componentDidMount=="function"){var i=t.return;try{r.componentDidMount()}catch(f){wt(t,i,f)}}var o=t.return;try{Xg(t)}catch(f){wt(t,o,f)}break;case 5:var a=t.return;try{Xg(t)}catch(f){wt(t,a,f)}}}catch(f){wt(t,t.return,f)}if(t===e){Ke=null;break}var c=t.sibling;if(c!==null){c.return=t.return,Ke=c;break}Ke=t.return}}var GD=Math.ceil,Ad=li.ReactCurrentDispatcher,oy=li.ReactCurrentOwner,Yn=li.ReactCurrentBatchConfig,it=0,xt=null,Ct=null,qt=0,Mn=0,Ws=lo(0),Dt=0,vu=null,Vo=0,_f=0,sy=0,Wl=null,En=null,ay=0,da=1/0,Qr=null,Ld=!1,tv=null,Yi=null,mc=!1,Fi=null,Nd=0,Hl=0,nv=null,nd=-1,rd=0;function cn(){return it&6?Tt():nd!==-1?nd:nd=Tt()}function Qi(e){return e.mode&1?it&2&&qt!==0?qt&-qt:kD.transition!==null?(rd===0&&(rd=oI()),rd):(e=at,e!==0||(e=window.event,e=e===void 0?16:fI(e.type)),e):1}function vr(e,t,n,r){if(50<Hl)throw Hl=0,nv=null,Error(we(185));Ou(e,n,r),(!(it&2)||e!==xt)&&(e===xt&&(!(it&2)&&(_f|=n),Dt===4&&xi(e,qt)),In(e,r),n===1&&it===0&&!(t.mode&1)&&(da=Tt()+500,gf&&uo()))}function In(e,t){var n=e.callbackNode;kM(e,t);var r=yd(e,e===xt?qt:0);if(r===0)n!==null&&P_(n),e.callbackNode=null,e.callbackPriority=0;else if(t=r&-r,e.callbackPriority!==t){if(n!=null&&P_(n),t===1)e.tag===0?PD(ES.bind(null,e)):MI(ES.bind(null,e)),RD(function(){!(it&6)&&uo()}),n=null;else{switch(sI(r)){case 1:n=Am;break;case 4:n=rI;break;case 16:n=md;break;case 536870912:n=iI;break;default:n=md}n=kC(n,bC.bind(null,e))}e.callbackPriority=t,e.callbackNode=n}}function bC(e,t){if(nd=-1,rd=0,it&6)throw Error(we(327));var n=e.callbackNode;if(ea()&&e.callbackNode!==n)return null;var r=yd(e,e===xt?qt:0);if(r===0)return null;if(r&30||r&e.expiredLanes||t)t=xd(e,r);else{t=r;var i=it;it|=2;var o=RC();(xt!==e||qt!==t)&&(Qr=null,da=Tt()+500,Uo(e,t));do try{QD();break}catch(c){TC(e,c)}while(1);Hm(),Ad.current=o,it=i,Ct!==null?t=0:(xt=null,qt=0,t=Dt)}if(t!==0){if(t===2&&(i=Pg(e),i!==0&&(r=i,t=rv(e,i))),t===1)throw n=vu,Uo(e,0),xi(e,r),In(e,Tt()),n;if(t===6)xi(e,r);else{if(i=e.current.alternate,!(r&30)&&!zD(i)&&(t=xd(e,r),t===2&&(o=Pg(e),o!==0&&(r=o,t=rv(e,o))),t===1))throw n=vu,Uo(e,0),xi(e,r),In(e,Tt()),n;switch(e.finishedWork=i,e.finishedLanes=r,t){case 0:case 1:throw Error(we(345));case 2:Po(e,En,Qr);break;case 3:if(xi(e,r),(r&130023424)===r&&(t=ay+500-Tt(),10<t)){if(yd(e,0)!==0)break;if(i=e.suspendedLanes,(i&r)!==r){cn(),e.pingedLanes|=e.suspendedLanes&i;break}e.timeoutHandle=$g(Po.bind(null,e,En,Qr),t);break}Po(e,En,Qr);break;case 4:if(xi(e,r),(r&4194240)===r)break;for(t=e.eventTimes,i=-1;0<r;){var a=31-gr(r);o=1<<a,a=t[a],a>i&&(i=a),r&=~o}if(r=i,r=Tt()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*GD(r/1960))-r,10<r){e.timeoutHandle=$g(Po.bind(null,e,En,Qr),r);break}Po(e,En,Qr);break;case 5:Po(e,En,Qr);break;default:throw Error(we(329))}}}return In(e,Tt()),e.callbackNode===n?bC.bind(null,e):null}function rv(e,t){var n=Wl;return e.current.memoizedState.isDehydrated&&(Uo(e,t).flags|=256),e=xd(e,t),e!==2&&(t=En,En=n,t!==null&&iv(t)),e}function iv(e){En===null?En=e:En.push.apply(En,e)}function zD(e){for(var t=e;;){if(t.flags&16384){var n=t.updateQueue;if(n!==null&&(n=n.stores,n!==null))for(var r=0;r<n.length;r++){var i=n[r],o=i.getSnapshot;i=i.value;try{if(!yr(o(),i))return!1}catch{return!1}}}if(n=t.child,t.subtreeFlags&16384&&n!==null)n.return=t,t=n;else{if(t===e)break;for(;t.sibling===null;){if(t.return===null||t.return===e)return!0;t=t.return}t.sibling.return=t.return,t=t.sibling}}return!0}function xi(e,t){for(t&=~sy,t&=~_f,e.suspendedLanes|=t,e.pingedLanes&=~t,e=e.expirationTimes;0<t;){var n=31-gr(t),r=1<<n;e[n]=-1,t&=~r}}function ES(e){if(it&6)throw Error(we(327));ea();var t=yd(e,0);if(!(t&1))return In(e,Tt()),null;var n=xd(e,t);if(e.tag!==0&&n===2){var r=Pg(e);r!==0&&(t=r,n=rv(e,r))}if(n===1)throw n=vu,Uo(e,0),xi(e,t),In(e,Tt()),n;if(n===6)throw Error(we(345));return e.finishedWork=e.current.alternate,e.finishedLanes=t,Po(e,En,Qr),In(e,Tt()),null}function ly(e,t){var n=it;it|=1;try{return e(t)}finally{it=n,it===0&&(da=Tt()+500,gf&&uo())}}function Wo(e){Fi!==null&&Fi.tag===0&&!(it&6)&&ea();var t=it;it|=1;var n=Yn.transition,r=at;try{if(Yn.transition=null,at=1,e)return e()}finally{at=r,Yn.transition=n,it=t,!(it&6)&&uo()}}function uy(){Mn=Ws.current,pt(Ws)}function Uo(e,t){e.finishedWork=null,e.finishedLanes=0;var n=e.timeoutHandle;if(n!==-1&&(e.timeoutHandle=-1,TD(n)),Ct!==null)for(n=Ct.return;n!==null;){var r=n;switch(qm(r),r.tag){case 1:r=r.type.childContextTypes,r!=null&&bd();break;case 3:ua(),pt(Tn),pt(tn),Xm();break;case 5:Jm(r);break;case 4:ua();break;case 13:pt(mt);break;case 19:pt(mt);break;case 10:Gm(r.type._context);break;case 22:case 23:uy()}n=n.return}if(xt=e,Ct=e=Ji(e.current,null),qt=Mn=t,Dt=0,vu=null,sy=_f=Vo=0,En=Wl=null,No!==null){for(t=0;t<No.length;t++)if(n=No[t],r=n.interleaved,r!==null){n.interleaved=null;var i=r.next,o=n.pending;if(o!==null){var a=o.next;o.next=i,r.next=a}n.pending=r}No=null}return e}function TC(e,t){do{var n=Ct;try{if(Hm(),Zc.current=Dd,Md){for(var r=_t.memoizedState;r!==null;){var i=r.queue;i!==null&&(i.pending=null),r=r.next}Md=!1}if(qo=0,Nt=kt=_t=null,ql=!1,hu=0,oy.current=null,n===null||n.return===null){Dt=1,vu=t,Ct=null;break}e:{var o=e,a=n.return,c=n,f=t;if(t=qt,c.flags|=32768,f!==null&&typeof f=="object"&&typeof f.then=="function"){var v=f,s=c,g=s.tag;if(!(s.mode&1)&&(g===0||g===11||g===15)){var y=s.alternate;y?(s.updateQueue=y.updateQueue,s.memoizedState=y.memoizedState,s.lanes=y.lanes):(s.updateQueue=null,s.memoizedState=null)}var S=lS(a);if(S!==null){S.flags&=-257,uS(S,a,c,o,t),S.mode&1&&aS(o,v,t),t=S,f=v;var m=t.updateQueue;if(m===null){var p=new Set;p.add(f),t.updateQueue=p}else m.add(f);break e}else{if(!(t&1)){aS(o,v,t),cy();break e}f=Error(we(426))}}else if(vt&&c.mode&1){var _=lS(a);if(_!==null){!(_.flags&65536)&&(_.flags|=256),uS(_,a,c,o,t),Vm(ca(f,c));break e}}o=f=ca(f,c),Dt!==4&&(Dt=2),Wl===null?Wl=[o]:Wl.push(o),o=a;do{switch(o.tag){case 3:o.flags|=65536,t&=-t,o.lanes|=t;var u=aC(o,f,t);eS(o,u);break e;case 1:c=f;var l=o.type,d=o.stateNode;if(!(o.flags&128)&&(typeof l.getDerivedStateFromError=="function"||d!==null&&typeof d.componentDidCatch=="function"&&(Yi===null||!Yi.has(d)))){o.flags|=65536,t&=-t,o.lanes|=t;var h=lC(o,c,t);eS(o,h);break e}}o=o.return}while(o!==null)}CC(n)}catch(w){t=w,Ct===n&&n!==null&&(Ct=n=n.return);continue}break}while(1)}function RC(){var e=Ad.current;return Ad.current=Dd,e===null?Dd:e}function cy(){(Dt===0||Dt===3||Dt===2)&&(Dt=4),xt===null||!(Vo&268435455)&&!(_f&268435455)||xi(xt,qt)}function xd(e,t){var n=it;it|=2;var r=RC();(xt!==e||qt!==t)&&(Qr=null,Uo(e,t));do try{YD();break}catch(i){TC(e,i)}while(1);if(Hm(),it=n,Ad.current=r,Ct!==null)throw Error(we(261));return xt=null,qt=0,Dt}function YD(){for(;Ct!==null;)IC(Ct)}function QD(){for(;Ct!==null&&!EM();)IC(Ct)}function IC(e){var t=PC(e.alternate,e,Mn);e.memoizedProps=e.pendingProps,t===null?CC(e):Ct=t,oy.current=null}function CC(e){var t=e;do{var n=t.alternate;if(e=t.return,t.flags&32768){if(n=qD(n,t),n!==null){n.flags&=32767,Ct=n;return}if(e!==null)e.flags|=32768,e.subtreeFlags=0,e.deletions=null;else{Dt=6,Ct=null;return}}else if(n=jD(n,t,Mn),n!==null){Ct=n;return}if(t=t.sibling,t!==null){Ct=t;return}Ct=t=e}while(t!==null);Dt===0&&(Dt=5)}function Po(e,t,n){var r=at,i=Yn.transition;try{Yn.transition=null,at=1,JD(e,t,n,r)}finally{Yn.transition=i,at=r}return null}function JD(e,t,n,r){do ea();while(Fi!==null);if(it&6)throw Error(we(327));n=e.finishedWork;var i=e.finishedLanes;if(n===null)return null;if(e.finishedWork=null,e.finishedLanes=0,n===e.current)throw Error(we(177));e.callbackNode=null,e.callbackPriority=0;var o=n.lanes|n.childLanes;if(MM(e,o),e===xt&&(Ct=xt=null,qt=0),!(n.subtreeFlags&2064)&&!(n.flags&2064)||mc||(mc=!0,kC(md,function(){return ea(),null})),o=(n.flags&15990)!==0,n.subtreeFlags&15990||o){o=Yn.transition,Yn.transition=null;var a=at;at=1;var c=it;it|=4,oy.current=null,WD(e,n),EC(n,e),mD(Ng),_d=!!Lg,Ng=Lg=null,e.current=n,HD(n),wM(),it=c,at=a,Yn.transition=o}else e.current=n;if(mc&&(mc=!1,Fi=e,Nd=i),o=e.pendingLanes,o===0&&(Yi=null),RM(n.stateNode),In(e,Tt()),t!==null)for(r=e.onRecoverableError,n=0;n<t.length;n++)i=t[n],r(i.value,{componentStack:i.stack,digest:i.digest});if(Ld)throw Ld=!1,e=tv,tv=null,e;return Nd&1&&e.tag!==0&&ea(),o=e.pendingLanes,o&1?e===nv?Hl++:(Hl=0,nv=e):Hl=0,uo(),null}function ea(){if(Fi!==null){var e=sI(Nd),t=Yn.transition,n=at;try{if(Yn.transition=null,at=16>e?16:e,Fi===null)var r=!1;else{if(e=Fi,Fi=null,Nd=0,it&6)throw Error(we(331));var i=it;for(it|=4,Ke=e.current;Ke!==null;){var o=Ke,a=o.child;if(Ke.flags&16){var c=o.deletions;if(c!==null){for(var f=0;f<c.length;f++){var v=c[f];for(Ke=v;Ke!==null;){var s=Ke;switch(s.tag){case 0:case 11:case 15:Vl(8,s,o)}var g=s.child;if(g!==null)g.return=s,Ke=g;else for(;Ke!==null;){s=Ke;var y=s.sibling,S=s.return;if(yC(s),s===v){Ke=null;break}if(y!==null){y.return=S,Ke=y;break}Ke=S}}}var m=o.alternate;if(m!==null){var p=m.child;if(p!==null){m.child=null;do{var _=p.sibling;p.sibling=null,p=_}while(p!==null)}}Ke=o}}if(o.subtreeFlags&2064&&a!==null)a.return=o,Ke=a;else e:for(;Ke!==null;){if(o=Ke,o.flags&2048)switch(o.tag){case 0:case 11:case 15:Vl(9,o,o.return)}var u=o.sibling;if(u!==null){u.return=o.return,Ke=u;break e}Ke=o.return}}var l=e.current;for(Ke=l;Ke!==null;){a=Ke;var d=a.child;if(a.subtreeFlags&2064&&d!==null)d.return=a,Ke=d;else e:for(a=l;Ke!==null;){if(c=Ke,c.flags&2048)try{switch(c.tag){case 0:case 11:case 15:yf(9,c)}}catch(w){wt(c,c.return,w)}if(c===a){Ke=null;break e}var h=c.sibling;if(h!==null){h.return=c.return,Ke=h;break e}Ke=c.return}}if(it=i,uo(),Br&&typeof Br.onPostCommitFiberRoot=="function")try{Br.onPostCommitFiberRoot(cf,e)}catch{}r=!0}return r}finally{at=n,Yn.transition=t}}return!1}function wS(e,t,n){t=ca(n,t),t=aC(e,t,1),e=zi(e,t,1),t=cn(),e!==null&&(Ou(e,1,t),In(e,t))}function wt(e,t,n){if(e.tag===3)wS(e,e,n);else for(;t!==null;){if(t.tag===3){wS(t,e,n);break}else if(t.tag===1){var r=t.stateNode;if(typeof t.type.getDerivedStateFromError=="function"||typeof r.componentDidCatch=="function"&&(Yi===null||!Yi.has(r))){e=ca(n,e),e=lC(t,e,1),t=zi(t,e,1),e=cn(),t!==null&&(Ou(t,1,e),In(t,e));break}}t=t.return}}function XD(e,t,n){var r=e.pingCache;r!==null&&r.delete(t),t=cn(),e.pingedLanes|=e.suspendedLanes&n,xt===e&&(qt&n)===n&&(Dt===4||Dt===3&&(qt&130023424)===qt&&500>Tt()-ay?Uo(e,0):sy|=n),In(e,t)}function OC(e,t){t===0&&(e.mode&1?(t=ac,ac<<=1,!(ac&130023424)&&(ac=4194304)):t=1);var n=cn();e=si(e,t),e!==null&&(Ou(e,t,n),In(e,n))}function ZD(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),OC(e,n)}function e1(e,t){var n=0;switch(e.tag){case 13:var r=e.stateNode,i=e.memoizedState;i!==null&&(n=i.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(we(314))}r!==null&&r.delete(t),OC(e,n)}var PC;PC=function(e,t,n){if(e!==null)if(e.memoizedProps!==t.pendingProps||Tn.current)wn=!0;else{if(!(e.lanes&n)&&!(t.flags&128))return wn=!1,KD(e,t,n);wn=!!(e.flags&131072)}else wn=!1,vt&&t.flags&1048576&&DI(t,Id,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;td(e,t),e=t.pendingProps;var i=sa(t,tn.current);Zs(t,n),i=ey(null,t,r,e,i,n);var o=ty();return t.flags|=1,typeof i=="object"&&i!==null&&typeof i.render=="function"&&i.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,Rn(r)?(o=!0,Td(t)):o=!1,t.memoizedState=i.state!==null&&i.state!==void 0?i.state:null,Ym(t),i.updater=vf,t.stateNode=i,i._reactInternals=t,Vg(t,r,e,n),t=Gg(null,t,r,!0,o,n)):(t.tag=0,vt&&o&&jm(t),ln(null,t,i,n),t=t.child),t;case 16:r=t.elementType;e:{switch(td(e,t),e=t.pendingProps,i=r._init,r=i(r._payload),t.type=r,i=t.tag=n1(r),e=dr(r,e),i){case 0:t=Hg(null,t,r,e,n);break e;case 1:t=fS(null,t,r,e,n);break e;case 11:t=cS(null,t,r,e,n);break e;case 14:t=dS(null,t,r,dr(r.type,e),n);break e}throw Error(we(306,r,""))}return t;case 0:return r=t.type,i=t.pendingProps,i=t.elementType===r?i:dr(r,i),Hg(e,t,r,i,n);case 1:return r=t.type,i=t.pendingProps,i=t.elementType===r?i:dr(r,i),fS(e,t,r,i,n);case 3:e:{if(fC(t),e===null)throw Error(we(387));r=t.pendingProps,o=t.memoizedState,i=o.element,xI(e,t),Pd(t,r,null,n);var a=t.memoizedState;if(r=a.element,o.isDehydrated)if(o={element:r,isDehydrated:!1,cache:a.cache,pendingSuspenseBoundaries:a.pendingSuspenseBoundaries,transitions:a.transitions},t.updateQueue.baseState=o,t.memoizedState=o,t.flags&256){i=ca(Error(we(423)),t),t=hS(e,t,r,n,i);break e}else if(r!==i){i=ca(Error(we(424)),t),t=hS(e,t,r,n,i);break e}else for(Dn=Gi(t.stateNode.containerInfo.firstChild),Ln=t,vt=!0,hr=null,n=FI(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(aa(),r===i){t=ai(e,t,n);break e}ln(e,t,r,n)}t=t.child}return t;case 5:return KI(t),e===null&&Kg(t),r=t.type,i=t.pendingProps,o=e!==null?e.memoizedProps:null,a=i.children,xg(r,i)?a=null:o!==null&&xg(r,o)&&(t.flags|=32),dC(e,t),ln(e,t,a,n),t.child;case 6:return e===null&&Kg(t),null;case 13:return hC(e,t,n);case 4:return Qm(t,t.stateNode.containerInfo),r=t.pendingProps,e===null?t.child=la(t,null,r,n):ln(e,t,r,n),t.child;case 11:return r=t.type,i=t.pendingProps,i=t.elementType===r?i:dr(r,i),cS(e,t,r,i,n);case 7:return ln(e,t,t.pendingProps,n),t.child;case 8:return ln(e,t,t.pendingProps.children,n),t.child;case 12:return ln(e,t,t.pendingProps.children,n),t.child;case 10:e:{if(r=t.type._context,i=t.pendingProps,o=t.memoizedProps,a=i.value,dt(Cd,r._currentValue),r._currentValue=a,o!==null)if(yr(o.value,a)){if(o.children===i.children&&!Tn.current){t=ai(e,t,n);break e}}else for(o=t.child,o!==null&&(o.return=t);o!==null;){var c=o.dependencies;if(c!==null){a=o.child;for(var f=c.firstContext;f!==null;){if(f.context===r){if(o.tag===1){f=ni(-1,n&-n),f.tag=2;var v=o.updateQueue;if(v!==null){v=v.shared;var s=v.pending;s===null?f.next=f:(f.next=s.next,s.next=f),v.pending=f}}o.lanes|=n,f=o.alternate,f!==null&&(f.lanes|=n),jg(o.return,n,t),c.lanes|=n;break}f=f.next}}else if(o.tag===10)a=o.type===t.type?null:o.child;else if(o.tag===18){if(a=o.return,a===null)throw Error(we(341));a.lanes|=n,c=a.alternate,c!==null&&(c.lanes|=n),jg(a,n,t),a=o.sibling}else a=o.child;if(a!==null)a.return=o;else for(a=o;a!==null;){if(a===t){a=null;break}if(o=a.sibling,o!==null){o.return=a.return,a=o;break}a=a.return}o=a}ln(e,t,i.children,n),t=t.child}return t;case 9:return i=t.type,r=t.pendingProps.children,Zs(t,n),i=Qn(i),r=r(i),t.flags|=1,ln(e,t,r,n),t.child;case 14:return r=t.type,i=dr(r,t.pendingProps),i=dr(r.type,i),dS(e,t,r,i,n);case 15:return uC(e,t,t.type,t.pendingProps,n);case 17:return r=t.type,i=t.pendingProps,i=t.elementType===r?i:dr(r,i),td(e,t),t.tag=1,Rn(r)?(e=!0,Td(t)):e=!1,Zs(t,n),UI(t,r,i),Vg(t,r,i,n),Gg(null,t,r,!0,e,n);case 19:return pC(e,t,n);case 22:return cC(e,t,n)}throw Error(we(156,t.tag))};function kC(e,t){return nI(e,t)}function t1(e,t,n,r){this.tag=e,this.key=n,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=t,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function zn(e,t,n,r){return new t1(e,t,n,r)}function dy(e){return e=e.prototype,!(!e||!e.isReactComponent)}function n1(e){if(typeof e=="function")return dy(e)?1:0;if(e!=null){if(e=e.$$typeof,e===km)return 11;if(e===Mm)return 14}return 2}function Ji(e,t){var n=e.alternate;return n===null?(n=zn(e.tag,t,e.key,e.mode),n.elementType=e.elementType,n.type=e.type,n.stateNode=e.stateNode,n.alternate=e,e.alternate=n):(n.pendingProps=t,n.type=e.type,n.flags=0,n.subtreeFlags=0,n.deletions=null),n.flags=e.flags&14680064,n.childLanes=e.childLanes,n.lanes=e.lanes,n.child=e.child,n.memoizedProps=e.memoizedProps,n.memoizedState=e.memoizedState,n.updateQueue=e.updateQueue,t=e.dependencies,n.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},n.sibling=e.sibling,n.index=e.index,n.ref=e.ref,n}function id(e,t,n,r,i,o){var a=2;if(r=e,typeof e=="function")dy(e)&&(a=1);else if(typeof e=="string")a=5;else e:switch(e){case Ns:return Bo(n.children,i,o,t);case Pm:a=8,i|=8;break;case pg:return e=zn(12,n,t,i|2),e.elementType=pg,e.lanes=o,e;case gg:return e=zn(13,n,t,i),e.elementType=gg,e.lanes=o,e;case vg:return e=zn(19,n,t,i),e.elementType=vg,e.lanes=o,e;case BR:return Sf(n,i,o,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case $R:a=10;break e;case UR:a=9;break e;case km:a=11;break e;case Mm:a=14;break e;case Ai:a=16,r=null;break e}throw Error(we(130,e==null?e:typeof e,""))}return t=zn(a,n,t,i),t.elementType=e,t.type=r,t.lanes=o,t}function Bo(e,t,n,r){return e=zn(7,e,r,t),e.lanes=n,e}function Sf(e,t,n,r){return e=zn(22,e,r,t),e.elementType=BR,e.lanes=n,e.stateNode={isHidden:!1},e}function Rh(e,t,n){return e=zn(6,e,null,t),e.lanes=n,e}function Ih(e,t,n){return t=zn(4,e.children!==null?e.children:[],e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function r1(e,t,n,r,i){this.tag=t,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=sh(0),this.expirationTimes=sh(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=sh(0),this.identifierPrefix=r,this.onRecoverableError=i,this.mutableSourceEagerHydrationData=null}function fy(e,t,n,r,i,o,a,c,f){return e=new r1(e,t,n,c,f),t===1?(t=1,o===!0&&(t|=8)):t=0,o=zn(3,null,null,t),e.current=o,o.stateNode=e,o.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},Ym(o),e}function i1(e,t,n){var r=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:Ls,key:r==null?null:""+r,children:e,containerInfo:t,implementation:n}}function MC(e){if(!e)return no;e=e._reactInternals;e:{if(Zo(e)!==e||e.tag!==1)throw Error(we(170));var t=e;do{switch(t.tag){case 3:t=t.stateNode.context;break e;case 1:if(Rn(t.type)){t=t.stateNode.__reactInternalMemoizedMergedChildContext;break e}}t=t.return}while(t!==null);throw Error(we(171))}if(e.tag===1){var n=e.type;if(Rn(n))return kI(e,n,t)}return t}function DC(e,t,n,r,i,o,a,c,f){return e=fy(n,r,!0,e,i,o,a,c,f),e.context=MC(null),n=e.current,r=cn(),i=Qi(n),o=ni(r,i),o.callback=t??null,zi(n,o,i),e.current.lanes=i,Ou(e,i,r),In(e,r),e}function Ef(e,t,n,r){var i=t.current,o=cn(),a=Qi(i);return n=MC(n),t.context===null?t.context=n:t.pendingContext=n,t=ni(o,a),t.payload={element:e},r=r===void 0?null:r,r!==null&&(t.callback=r),e=zi(i,t,a),e!==null&&(vr(e,i,a,o),Xc(e,i,a)),a}function $d(e){if(e=e.current,!e.child)return null;switch(e.child.tag){case 5:return e.child.stateNode;default:return e.child.stateNode}}function bS(e,t){if(e=e.memoizedState,e!==null&&e.dehydrated!==null){var n=e.retryLane;e.retryLane=n!==0&&n<t?n:t}}function hy(e,t){bS(e,t),(e=e.alternate)&&bS(e,t)}function o1(){return null}var AC=typeof reportError=="function"?reportError:function(e){console.error(e)};function py(e){this._internalRoot=e}wf.prototype.render=py.prototype.render=function(e){var t=this._internalRoot;if(t===null)throw Error(we(409));Ef(e,t,null,null)};wf.prototype.unmount=py.prototype.unmount=function(){var e=this._internalRoot;if(e!==null){this._internalRoot=null;var t=e.containerInfo;Wo(function(){Ef(null,e,null,null)}),t[oi]=null}};function wf(e){this._internalRoot=e}wf.prototype.unstable_scheduleHydration=function(e){if(e){var t=uI();e={blockedOn:null,target:e,priority:t};for(var n=0;n<Ni.length&&t!==0&&t<Ni[n].priority;n++);Ni.splice(n,0,e),n===0&&dI(e)}};function gy(e){return!(!e||e.nodeType!==1&&e.nodeType!==9&&e.nodeType!==11)}function bf(e){return!(!e||e.nodeType!==1&&e.nodeType!==9&&e.nodeType!==11&&(e.nodeType!==8||e.nodeValue!==" react-mount-point-unstable "))}function TS(){}function s1(e,t,n,r,i){if(i){if(typeof r=="function"){var o=r;r=function(){var v=$d(a);o.call(v)}}var a=DC(t,r,e,0,null,!1,!1,"",TS);return e._reactRootContainer=a,e[oi]=a.current,lu(e.nodeType===8?e.parentNode:e),Wo(),a}for(;i=e.lastChild;)e.removeChild(i);if(typeof r=="function"){var c=r;r=function(){var v=$d(f);c.call(v)}}var f=fy(e,0,!1,null,null,!1,!1,"",TS);return e._reactRootContainer=f,e[oi]=f.current,lu(e.nodeType===8?e.parentNode:e),Wo(function(){Ef(t,f,n,r)}),f}function Tf(e,t,n,r,i){var o=n._reactRootContainer;if(o){var a=o;if(typeof i=="function"){var c=i;i=function(){var f=$d(a);c.call(f)}}Ef(t,a,e,i)}else a=s1(n,t,e,i,r);return $d(a)}aI=function(e){switch(e.tag){case 3:var t=e.stateNode;if(t.current.memoizedState.isDehydrated){var n=Dl(t.pendingLanes);n!==0&&(Lm(t,n|1),In(t,Tt()),!(it&6)&&(da=Tt()+500,uo()))}break;case 13:Wo(function(){var r=si(e,1);if(r!==null){var i=cn();vr(r,e,1,i)}}),hy(e,1)}};Nm=function(e){if(e.tag===13){var t=si(e,134217728);if(t!==null){var n=cn();vr(t,e,134217728,n)}hy(e,134217728)}};lI=function(e){if(e.tag===13){var t=Qi(e),n=si(e,t);if(n!==null){var r=cn();vr(n,e,t,r)}hy(e,t)}};uI=function(){return at};cI=function(e,t){var n=at;try{return at=e,t()}finally{at=n}};Ig=function(e,t,n){switch(t){case"input":if(_g(e,n),t=n.name,n.type==="radio"&&t!=null){for(n=e;n.parentNode;)n=n.parentNode;for(n=n.querySelectorAll("input[name="+JSON.stringify(""+t)+'][type="radio"]'),t=0;t<n.length;t++){var r=n[t];if(r!==e&&r.form===e.form){var i=pf(r);if(!i)throw Error(we(90));KR(r),_g(r,i)}}}break;case"textarea":qR(e,n);break;case"select":t=n.value,t!=null&&Ys(e,!!n.multiple,t,!1)}};QR=ly;JR=Wo;var a1={usingClientEntryPoint:!1,Events:[ku,Bs,pf,zR,YR,ly]},Ua={findFiberByHostInstance:Lo,bundleType:0,version:"18.2.0",rendererPackageName:"react-dom"},l1={bundleType:Ua.bundleType,version:Ua.version,rendererPackageName:Ua.rendererPackageName,rendererConfig:Ua.rendererConfig,overrideHookState:null,overrideHookStateDeletePath:null,overrideHookStateRenamePath:null,overrideProps:null,overridePropsDeletePath:null,overridePropsRenamePath:null,setErrorHandler:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:li.ReactCurrentDispatcher,findHostInstanceByFiber:function(e){return e=eI(e),e===null?null:e.stateNode},findFiberByHostInstance:Ua.findFiberByHostInstance||o1,findHostInstancesForRefresh:null,scheduleRefresh:null,scheduleRoot:null,setRefreshHandler:null,getCurrentFiber:null,reconcilerVersion:"18.2.0-next-9e3b772b8-20220608"};if(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"){var yc=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(!yc.isDisabled&&yc.supportsFiber)try{cf=yc.inject(l1),Br=yc}catch{}}$n.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=a1;$n.createPortal=function(e,t){var n=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!gy(t))throw Error(we(200));return i1(e,t,null,n)};$n.createRoot=function(e,t){if(!gy(e))throw Error(we(299));var n=!1,r="",i=AC;return t!=null&&(t.unstable_strictMode===!0&&(n=!0),t.identifierPrefix!==void 0&&(r=t.identifierPrefix),t.onRecoverableError!==void 0&&(i=t.onRecoverableError)),t=fy(e,1,!1,null,null,n,!1,r,i),e[oi]=t.current,lu(e.nodeType===8?e.parentNode:e),new py(t)};$n.findDOMNode=function(e){if(e==null)return null;if(e.nodeType===1)return e;var t=e._reactInternals;if(t===void 0)throw typeof e.render=="function"?Error(we(188)):(e=Object.keys(e).join(","),Error(we(268,e)));return e=eI(t),e=e===null?null:e.stateNode,e};$n.flushSync=function(e){return Wo(e)};$n.hydrate=function(e,t,n){if(!bf(t))throw Error(we(200));return Tf(null,e,t,!0,n)};$n.hydrateRoot=function(e,t,n){if(!gy(e))throw Error(we(405));var r=n!=null&&n.hydratedSources||null,i=!1,o="",a=AC;if(n!=null&&(n.unstable_strictMode===!0&&(i=!0),n.identifierPrefix!==void 0&&(o=n.identifierPrefix),n.onRecoverableError!==void 0&&(a=n.onRecoverableError)),t=DC(t,null,e,1,n??null,i,!1,o,a),e[oi]=t.current,lu(e),r)for(e=0;e<r.length;e++)n=r[e],i=n._getVersion,i=i(n._source),t.mutableSourceEagerHydrationData==null?t.mutableSourceEagerHydrationData=[n,i]:t.mutableSourceEagerHydrationData.push(n,i);return new wf(t)};$n.render=function(e,t,n){if(!bf(t))throw Error(we(200));return Tf(null,e,t,!1,n)};$n.unmountComponentAtNode=function(e){if(!bf(e))throw Error(we(40));return e._reactRootContainer?(Wo(function(){Tf(null,null,e,!1,function(){e._reactRootContainer=null,e[oi]=null})}),!0):!1};$n.unstable_batchedUpdates=ly;$n.unstable_renderSubtreeIntoContainer=function(e,t,n,r){if(!bf(n))throw Error(we(200));if(e==null||e._reactInternals===void 0)throw Error(we(38));return Tf(e,t,n,!1,r)};$n.version="18.2.0-next-9e3b772b8-20220608";(function(e){function t(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(t)}catch(n){console.error(n)}}t(),e.exports=$n})(oM);var RS=dg;__.createRoot=RS.createRoot,__.hydrateRoot=RS.hydrateRoot;/**
     41  * @remix-run/router v1.3.0
     42  *
     43  * Copyright (c) Remix Software Inc.
     44  *
     45  * This source code is licensed under the MIT license found in the
     46  * LICENSE.md file in the root directory of this source tree.
     47  *
     48  * @license MIT
     49  */function mu(){return mu=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},mu.apply(this,arguments)}var Ki;(function(e){e.Pop="POP",e.Push="PUSH",e.Replace="REPLACE"})(Ki||(Ki={}));const IS="popstate";function u1(e){e===void 0&&(e={});function t(r,i){let{pathname:o,search:a,hash:c}=r.location;return ov("",{pathname:o,search:a,hash:c},i.state&&i.state.usr||null,i.state&&i.state.key||"default")}function n(r,i){return typeof i=="string"?i:Ud(i)}return f1(t,n,null,e)}function At(e,t){if(e===!1||e===null||typeof e>"u")throw new Error(t)}function c1(e,t){if(!e){typeof console<"u"&&console.warn(t);try{throw new Error(t)}catch{}}}function d1(){return Math.random().toString(36).substr(2,8)}function CS(e,t){return{usr:e.state,key:e.key,idx:t}}function ov(e,t,n,r){return n===void 0&&(n=null),mu({pathname:typeof e=="string"?e:e.pathname,search:"",hash:""},typeof t=="string"?ma(t):t,{state:n,key:t&&t.key||r||d1()})}function Ud(e){let{pathname:t="/",search:n="",hash:r=""}=e;return n&&n!=="?"&&(t+=n.charAt(0)==="?"?n:"?"+n),r&&r!=="#"&&(t+=r.charAt(0)==="#"?r:"#"+r),t}function ma(e){let t={};if(e){let n=e.indexOf("#");n>=0&&(t.hash=e.substr(n),e=e.substr(0,n));let r=e.indexOf("?");r>=0&&(t.search=e.substr(r),e=e.substr(0,r)),e&&(t.pathname=e)}return t}function f1(e,t,n,r){r===void 0&&(r={});let{window:i=document.defaultView,v5Compat:o=!1}=r,a=i.history,c=Ki.Pop,f=null,v=s();v==null&&(v=0,a.replaceState(mu({},a.state,{idx:v}),""));function s(){return(a.state||{idx:null}).idx}function g(){let _=Ki.Pop,u=s();if(u!=null){let l=u-v;c=_,v=u,f&&f({action:c,location:p.location,delta:l})}else c1(!1,"You are trying to block a POP navigation to a location that was not created by @remix-run/router. The block will fail silently in production, but in general you should do all navigation with the router (instead of using window.history.pushState directly) to avoid this situation.")}function y(_,u){c=Ki.Push;let l=ov(p.location,_,u);n&&n(l,_),v=s()+1;let d=CS(l,v),h=p.createHref(l);try{a.pushState(d,"",h)}catch{i.location.assign(h)}o&&f&&f({action:c,location:p.location,delta:1})}function S(_,u){c=Ki.Replace;let l=ov(p.location,_,u);n&&n(l,_),v=s();let d=CS(l,v),h=p.createHref(l);a.replaceState(d,"",h),o&&f&&f({action:c,location:p.location,delta:0})}function m(_){let u=i.location.origin!=="null"?i.location.origin:i.location.href,l=typeof _=="string"?_:Ud(_);return At(u,"No window.location.(origin|href) available to create URL for href: "+l),new URL(l,u)}let p={get action(){return c},get location(){return e(i,a)},listen(_){if(f)throw new Error("A history only accepts one active listener");return i.addEventListener(IS,g),f=_,()=>{i.removeEventListener(IS,g),f=null}},createHref(_){return t(i,_)},createURL:m,encodeLocation(_){let u=m(_);return{pathname:u.pathname,search:u.search,hash:u.hash}},push:y,replace:S,go(_){return a.go(_)}};return p}var OS;(function(e){e.data="data",e.deferred="deferred",e.redirect="redirect",e.error="error"})(OS||(OS={}));function h1(e,t,n){n===void 0&&(n="/");let r=typeof t=="string"?ma(t):t,i=xC(r.pathname||"/",n);if(i==null)return null;let o=LC(e);p1(o);let a=null;for(let c=0;a==null&&c<o.length;++c)a=b1(o[c],I1(i));return a}function LC(e,t,n,r){t===void 0&&(t=[]),n===void 0&&(n=[]),r===void 0&&(r="");let i=(o,a,c)=>{let f={relativePath:c===void 0?o.path||"":c,caseSensitive:o.caseSensitive===!0,childrenIndex:a,route:o};f.relativePath.startsWith("/")&&(At(f.relativePath.startsWith(r),'Absolute route path "'+f.relativePath+'" nested under path '+('"'+r+'" is not valid. An absolute child route path ')+"must start with the combined path of all its parent routes."),f.relativePath=f.relativePath.slice(r.length));let v=Xi([r,f.relativePath]),s=n.concat(f);o.children&&o.children.length>0&&(At(o.index!==!0,"Index routes must not have child routes. Please remove "+('all child routes from route path "'+v+'".')),LC(o.children,t,s,v)),!(o.path==null&&!o.index)&&t.push({path:v,score:E1(v,o.index),routesMeta:s})};return e.forEach((o,a)=>{var c;if(o.path===""||!((c=o.path)!=null&&c.includes("?")))i(o,a);else for(let f of NC(o.path))i(o,a,f)}),t}function NC(e){let t=e.split("/");if(t.length===0)return[];let[n,...r]=t,i=n.endsWith("?"),o=n.replace(/\?$/,"");if(r.length===0)return i?[o,""]:[o];let a=NC(r.join("/")),c=[];return c.push(...a.map(f=>f===""?o:[o,f].join("/"))),i&&c.push(...a),c.map(f=>e.startsWith("/")&&f===""?"/":f)}function p1(e){e.sort((t,n)=>t.score!==n.score?n.score-t.score:w1(t.routesMeta.map(r=>r.childrenIndex),n.routesMeta.map(r=>r.childrenIndex)))}const g1=/^:\w+$/,v1=3,m1=2,y1=1,_1=10,S1=-2,PS=e=>e==="*";function E1(e,t){let n=e.split("/"),r=n.length;return n.some(PS)&&(r+=S1),t&&(r+=m1),n.filter(i=>!PS(i)).reduce((i,o)=>i+(g1.test(o)?v1:o===""?y1:_1),r)}function w1(e,t){return e.length===t.length&&e.slice(0,-1).every((r,i)=>r===t[i])?e[e.length-1]-t[t.length-1]:0}function b1(e,t){let{routesMeta:n}=e,r={},i="/",o=[];for(let a=0;a<n.length;++a){let c=n[a],f=a===n.length-1,v=i==="/"?t:t.slice(i.length)||"/",s=T1({path:c.relativePath,caseSensitive:c.caseSensitive,end:f},v);if(!s)return null;Object.assign(r,s.params);let g=c.route;o.push({params:r,pathname:Xi([i,s.pathname]),pathnameBase:k1(Xi([i,s.pathnameBase])),route:g}),s.pathnameBase!=="/"&&(i=Xi([i,s.pathnameBase]))}return o}function T1(e,t){typeof e=="string"&&(e={path:e,caseSensitive:!1,end:!0});let[n,r]=R1(e.path,e.caseSensitive,e.end),i=t.match(n);if(!i)return null;let o=i[0],a=o.replace(/(.)\/+$/,"$1"),c=i.slice(1);return{params:r.reduce((v,s,g)=>{if(s==="*"){let y=c[g]||"";a=o.slice(0,o.length-y.length).replace(/(.)\/+$/,"$1")}return v[s]=C1(c[g]||"",s),v},{}),pathname:o,pathnameBase:a,pattern:e}}function R1(e,t,n){t===void 0&&(t=!1),n===void 0&&(n=!0),vy(e==="*"||!e.endsWith("*")||e.endsWith("/*"),'Route path "'+e+'" will be treated as if it were '+('"'+e.replace(/\*$/,"/*")+'" because the `*` character must ')+"always follow a `/` in the pattern. To get rid of this warning, "+('please change the route path to "'+e.replace(/\*$/,"/*")+'".'));let r=[],i="^"+e.replace(/\/*\*?$/,"").replace(/^\/*/,"/").replace(/[\\.*+^$?{}|()[\]]/g,"\\$&").replace(/\/:(\w+)/g,(a,c)=>(r.push(c),"/([^\\/]+)"));return e.endsWith("*")?(r.push("*"),i+=e==="*"||e==="/*"?"(.*)$":"(?:\\/(.+)|\\/*)$"):n?i+="\\/*$":e!==""&&e!=="/"&&(i+="(?:(?=\\/|$))"),[new RegExp(i,t?void 0:"i"),r]}function I1(e){try{return decodeURI(e)}catch(t){return vy(!1,'The URL path "'+e+'" could not be decoded because it is is a malformed URL segment. This is probably due to a bad percent '+("encoding ("+t+").")),e}}function C1(e,t){try{return decodeURIComponent(e)}catch(n){return vy(!1,'The value for the URL param "'+t+'" will not be decoded because'+(' the string "'+e+'" is a malformed URL segment. This is probably')+(" due to a bad percent encoding ("+n+").")),e}}function xC(e,t){if(t==="/")return e;if(!e.toLowerCase().startsWith(t.toLowerCase()))return null;let n=t.endsWith("/")?t.length-1:t.length,r=e.charAt(n);return r&&r!=="/"?null:e.slice(n)||"/"}function vy(e,t){if(!e){typeof console<"u"&&console.warn(t);try{throw new Error(t)}catch{}}}function O1(e,t){t===void 0&&(t="/");let{pathname:n,search:r="",hash:i=""}=typeof e=="string"?ma(e):e;return{pathname:n?n.startsWith("/")?n:P1(n,t):t,search:M1(r),hash:D1(i)}}function P1(e,t){let n=t.replace(/\/+$/,"").split("/");return e.split("/").forEach(i=>{i===".."?n.length>1&&n.pop():i!=="."&&n.push(i)}),n.length>1?n.join("/"):"/"}function Ch(e,t,n,r){return"Cannot include a '"+e+"' character in a manually specified "+("`to."+t+"` field ["+JSON.stringify(r)+"].  Please separate it out to the ")+("`to."+n+"` field. Alternatively you may provide the full path as ")+'a string in <Link to="..."> and the router will parse it for you.'}function $C(e){return e.filter((t,n)=>n===0||t.route.path&&t.route.path.length>0)}function UC(e,t,n,r){r===void 0&&(r=!1);let i;typeof e=="string"?i=ma(e):(i=mu({},e),At(!i.pathname||!i.pathname.includes("?"),Ch("?","pathname","search",i)),At(!i.pathname||!i.pathname.includes("#"),Ch("#","pathname","hash",i)),At(!i.search||!i.search.includes("#"),Ch("#","search","hash",i)));let o=e===""||i.pathname==="",a=o?"/":i.pathname,c;if(r||a==null)c=n;else{let g=t.length-1;if(a.startsWith("..")){let y=a.split("/");for(;y[0]==="..";)y.shift(),g-=1;i.pathname=y.join("/")}c=g>=0?t[g]:"/"}let f=O1(i,c),v=a&&a!=="/"&&a.endsWith("/"),s=(o||a===".")&&n.endsWith("/");return!f.pathname.endsWith("/")&&(v||s)&&(f.pathname+="/"),f}const Xi=e=>e.join("/").replace(/\/\/+/g,"/"),k1=e=>e.replace(/\/+$/,"").replace(/^\/*/,"/"),M1=e=>!e||e==="?"?"":e.startsWith("?")?e:"?"+e,D1=e=>!e||e==="#"?"":e.startsWith("#")?e:"#"+e;class A1{constructor(t,n,r,i){i===void 0&&(i=!1),this.status=t,this.statusText=n||"",this.internal=i,r instanceof Error?(this.data=r.toString(),this.error=r):this.data=r}}function L1(e){return e instanceof A1}const N1=["post","put","patch","delete"];[...N1];/**
     50  * React Router v6.7.0
     51  *
     52  * Copyright (c) Remix Software Inc.
     53  *
     54  * This source code is licensed under the MIT license found in the
     55  * LICENSE.md file in the root directory of this source tree.
     56  *
     57  * @license MIT
     58  */function sv(){return sv=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},sv.apply(this,arguments)}function x1(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}const $1=typeof Object.is=="function"?Object.is:x1,{useState:U1,useEffect:B1,useLayoutEffect:F1,useDebugValue:K1}=cg;function j1(e,t,n){const r=t(),[{inst:i},o]=U1({inst:{value:r,getSnapshot:t}});return F1(()=>{i.value=r,i.getSnapshot=t,Oh(i)&&o({inst:i})},[e,r,t]),B1(()=>(Oh(i)&&o({inst:i}),e(()=>{Oh(i)&&o({inst:i})})),[e]),K1(r),r}function Oh(e){const t=e.getSnapshot,n=e.value;try{const r=t();return!$1(n,r)}catch{return!0}}function q1(e,t,n){return t()}const V1=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",W1=!V1,H1=W1?q1:j1;"useSyncExternalStore"in cg&&(e=>e.useSyncExternalStore)(cg);const BC=Oe.createContext(null),FC=Oe.createContext(null),Rf=Oe.createContext(null),If=Oe.createContext(null),es=Oe.createContext({outlet:null,matches:[]}),KC=Oe.createContext(null);function G1(e,t){let{relative:n}=t===void 0?{}:t;Du()||At(!1);let{basename:r,navigator:i}=Oe.useContext(Rf),{hash:o,pathname:a,search:c}=jC(e,{relative:n}),f=a;return r!=="/"&&(f=a==="/"?r:Xi([r,a])),i.createHref({pathname:f,search:c,hash:o})}function Du(){return Oe.useContext(If)!=null}function Cf(){return Du()||At(!1),Oe.useContext(If).location}function z1(){Du()||At(!1);let{basename:e,navigator:t}=Oe.useContext(Rf),{matches:n}=Oe.useContext(es),{pathname:r}=Cf(),i=JSON.stringify($C(n).map(c=>c.pathnameBase)),o=Oe.useRef(!1);return Oe.useEffect(()=>{o.current=!0}),Oe.useCallback(function(c,f){if(f===void 0&&(f={}),!o.current)return;if(typeof c=="number"){t.go(c);return}let v=UC(c,JSON.parse(i),r,f.relative==="path");e!=="/"&&(v.pathname=v.pathname==="/"?e:Xi([e,v.pathname])),(f.replace?t.replace:t.push)(v,f.state,f)},[e,t,i,r])}function dG(){let{matches:e}=Oe.useContext(es),t=e[e.length-1];return t?t.params:{}}function jC(e,t){let{relative:n}=t===void 0?{}:t,{matches:r}=Oe.useContext(es),{pathname:i}=Cf(),o=JSON.stringify($C(r).map(a=>a.pathnameBase));return Oe.useMemo(()=>UC(e,JSON.parse(o),i,n==="path"),[e,o,i,n])}function Y1(e,t){Du()||At(!1);let{navigator:n}=Oe.useContext(Rf),r=Oe.useContext(FC),{matches:i}=Oe.useContext(es),o=i[i.length-1],a=o?o.params:{};o&&o.pathname;let c=o?o.pathnameBase:"/";o&&o.route;let f=Cf(),v;if(t){var s;let p=typeof t=="string"?ma(t):t;c==="/"||(s=p.pathname)!=null&&s.startsWith(c)||At(!1),v=p}else v=f;let g=v.pathname||"/",y=c==="/"?g:g.slice(c.length)||"/",S=h1(e,{pathname:y}),m=Z1(S&&S.map(p=>Object.assign({},p,{params:Object.assign({},a,p.params),pathname:Xi([c,n.encodeLocation?n.encodeLocation(p.pathname).pathname:p.pathname]),pathnameBase:p.pathnameBase==="/"?c:Xi([c,n.encodeLocation?n.encodeLocation(p.pathnameBase).pathname:p.pathnameBase])})),i,r||void 0);return t&&m?Oe.createElement(If.Provider,{value:{location:sv({pathname:"/",search:"",hash:"",state:null,key:"default"},v),navigationType:Ki.Pop}},m):m}function Q1(){let e=rA(),t=L1(e)?e.status+" "+e.statusText:e instanceof Error?e.message:JSON.stringify(e),n=e instanceof Error?e.stack:null,r="rgba(200,200,200, 0.5)",i={padding:"0.5rem",backgroundColor:r},o={padding:"2px 4px",backgroundColor:r};return Oe.createElement(Oe.Fragment,null,Oe.createElement("h2",null,"Unhandled Thrown Error!"),Oe.createElement("h3",{style:{fontStyle:"italic"}},t),n?Oe.createElement("pre",{style:i},n):null,Oe.createElement("p",null,"💿 Hey developer 👋"),Oe.createElement("p",null,"You can provide a way better UX than this when your app throws errors by providing your own ",Oe.createElement("code",{style:o},"errorElement")," props on ",Oe.createElement("code",{style:o},"<Route>")))}class J1 extends Oe.Component{constructor(t){super(t),this.state={location:t.location,error:t.error}}static getDerivedStateFromError(t){return{error:t}}static getDerivedStateFromProps(t,n){return n.location!==t.location?{error:t.error,location:t.location}:{error:t.error||n.error,location:n.location}}componentDidCatch(t,n){console.error("React Router caught the following error during render",t,n)}render(){return this.state.error?Oe.createElement(es.Provider,{value:this.props.routeContext},Oe.createElement(KC.Provider,{value:this.state.error,children:this.props.component})):this.props.children}}function X1(e){let{routeContext:t,match:n,children:r}=e,i=Oe.useContext(BC);return i&&i.static&&i.staticContext&&n.route.errorElement&&(i.staticContext._deepestRenderedBoundaryId=n.route.id),Oe.createElement(es.Provider,{value:t},r)}function Z1(e,t,n){if(t===void 0&&(t=[]),e==null)if(n!=null&&n.errors)e=n.matches;else return null;let r=e,i=n==null?void 0:n.errors;if(i!=null){let o=r.findIndex(a=>a.route.id&&(i==null?void 0:i[a.route.id]));o>=0||At(!1),r=r.slice(0,Math.min(r.length,o+1))}return r.reduceRight((o,a,c)=>{let f=a.route.id?i==null?void 0:i[a.route.id]:null,v=n?a.route.errorElement||Oe.createElement(Q1,null):null,s=t.concat(r.slice(0,c+1)),g=()=>Oe.createElement(X1,{match:a,routeContext:{outlet:o,matches:s}},f?v:a.route.element!==void 0?a.route.element:o);return n&&(a.route.errorElement||c===0)?Oe.createElement(J1,{location:n.location,component:v,error:f,children:g(),routeContext:{outlet:null,matches:s}}):g()},null)}var kS;(function(e){e.UseBlocker="useBlocker",e.UseRevalidator="useRevalidator"})(kS||(kS={}));var Bd;(function(e){e.UseLoaderData="useLoaderData",e.UseActionData="useActionData",e.UseRouteError="useRouteError",e.UseNavigation="useNavigation",e.UseRouteLoaderData="useRouteLoaderData",e.UseMatches="useMatches",e.UseRevalidator="useRevalidator"})(Bd||(Bd={}));function eA(e){let t=Oe.useContext(FC);return t||At(!1),t}function tA(e){let t=Oe.useContext(es);return t||At(!1),t}function nA(e){let t=tA(),n=t.matches[t.matches.length-1];return n.route.id||At(!1),n.route.id}function rA(){var e;let t=Oe.useContext(KC),n=eA(Bd.UseRouteError),r=nA(Bd.UseRouteError);return t||((e=n.errors)==null?void 0:e[r])}function iA(e){At(!1)}function oA(e){let{basename:t="/",children:n=null,location:r,navigationType:i=Ki.Pop,navigator:o,static:a=!1}=e;Du()&&At(!1);let c=t.replace(/^\/*/,"/"),f=Oe.useMemo(()=>({basename:c,navigator:o,static:a}),[c,o,a]);typeof r=="string"&&(r=ma(r));let{pathname:v="/",search:s="",hash:g="",state:y=null,key:S="default"}=r,m=Oe.useMemo(()=>{let p=xC(v,c);return p==null?null:{pathname:p,search:s,hash:g,state:y,key:S}},[c,v,s,g,y,S]);return m==null?null:Oe.createElement(Rf.Provider,{value:f},Oe.createElement(If.Provider,{children:n,value:{location:m,navigationType:i}}))}function fG(e){let{children:t,location:n}=e,r=Oe.useContext(BC),i=r&&!t?r.router.routes:av(t);return Y1(i,n)}var MS;(function(e){e[e.pending=0]="pending",e[e.success=1]="success",e[e.error=2]="error"})(MS||(MS={}));new Promise(()=>{});function av(e,t){t===void 0&&(t=[]);let n=[];return Oe.Children.forEach(e,(r,i)=>{if(!Oe.isValidElement(r))return;if(r.type===Oe.Fragment){n.push.apply(n,av(r.props.children,t));return}r.type!==iA&&At(!1),!r.props.index||!r.props.children||At(!1);let o=[...t,i],a={id:r.props.id||o.join("-"),caseSensitive:r.props.caseSensitive,element:r.props.element,index:r.props.index,path:r.props.path,loader:r.props.loader,action:r.props.action,errorElement:r.props.errorElement,hasErrorBoundary:r.props.errorElement!=null,shouldRevalidate:r.props.shouldRevalidate,handle:r.props.handle};r.props.children&&(a.children=av(r.props.children,o)),n.push(a)}),n}/**
     59  * React Router DOM v6.7.0
     60  *
     61  * Copyright (c) Remix Software Inc.
     62  *
     63  * This source code is licensed under the MIT license found in the
     64  * LICENSE.md file in the root directory of this source tree.
     65  *
     66  * @license MIT
     67  */function lv(){return lv=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},lv.apply(this,arguments)}function sA(e,t){if(e==null)return{};var n={},r=Object.keys(e),i,o;for(o=0;o<r.length;o++)i=r[o],!(t.indexOf(i)>=0)&&(n[i]=e[i]);return n}function aA(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}function lA(e,t){return e.button===0&&(!t||t==="_self")&&!aA(e)}const uA=["onClick","relative","reloadDocument","replace","state","target","to","preventScrollReset"];function hG(e){let{basename:t,children:n,window:r}=e,i=Oe.useRef();i.current==null&&(i.current=u1({window:r,v5Compat:!0}));let o=i.current,[a,c]=Oe.useState({action:o.action,location:o.location});return Oe.useLayoutEffect(()=>o.listen(c),[o]),Oe.createElement(oA,{basename:t,children:n,location:a.location,navigationType:a.action,navigator:o})}const pG=Oe.forwardRef(function(t,n){let{onClick:r,relative:i,reloadDocument:o,replace:a,state:c,target:f,to:v,preventScrollReset:s}=t,g=sA(t,uA),y=G1(v,{relative:i}),S=cA(v,{replace:a,state:c,target:f,preventScrollReset:s,relative:i});function m(p){r&&r(p),p.defaultPrevented||S(p)}return Oe.createElement("a",lv({},g,{href:y,onClick:o?r:m,ref:n,target:f}))});var DS;(function(e){e.UseScrollRestoration="useScrollRestoration",e.UseSubmitImpl="useSubmitImpl",e.UseFetcher="useFetcher"})(DS||(DS={}));var AS;(function(e){e.UseFetchers="useFetchers",e.UseScrollRestoration="useScrollRestoration"})(AS||(AS={}));function cA(e,t){let{target:n,replace:r,state:i,preventScrollReset:o,relative:a}=t===void 0?{}:t,c=z1(),f=Cf(),v=jC(e,{relative:a});return Oe.useCallback(s=>{if(lA(s,n)){s.preventDefault();let g=r!==void 0?r:Ud(f)===Ud(v);c(e,{replace:g,state:i,preventScrollReset:o,relative:a})}},[f,c,v,r,i,n,e,o,a])}function mr(e){return mr=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},mr(e)}function dA(e,t){if(mr(e)!=="object"||e===null)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||"default");if(mr(r)!=="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function qC(e){var t=dA(e,"string");return mr(t)==="symbol"?t:String(t)}function Er(e,t,n){return t=qC(t),t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}const fA=Object.freeze(Object.defineProperty({__proto__:null,default:Er},Symbol.toStringTag,{value:"Module"}));function hA(e,t){if(e==null)return{};var n={},r=Object.keys(e),i,o;for(o=0;o<r.length;o++)i=r[o],!(t.indexOf(i)>=0)&&(n[i]=e[i]);return n}function pA(e,t){if(e==null)return{};var n=hA(e,t),r,i;if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);for(i=0;i<o.length;i++)r=o[i],!(t.indexOf(r)>=0)&&Object.prototype.propertyIsEnumerable.call(e,r)&&(n[r]=e[r])}return n}const gA=Object.freeze(Object.defineProperty({__proto__:null,default:pA},Symbol.toStringTag,{value:"Module"}));function vA(){if(console&&console.warn){for(var e,t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];typeof n[0]=="string"&&(n[0]="react-i18next:: ".concat(n[0])),(e=console).warn.apply(e,n)}}var LS={};function uv(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];typeof t[0]=="string"&&LS[t[0]]||(typeof t[0]=="string"&&(LS[t[0]]=new Date),vA.apply(void 0,t))}function NS(e,t,n){e.loadNamespaces(t,function(){if(e.isInitialized)n();else{var r=function i(){setTimeout(function(){e.off("initialized",i)},0),n()};e.on("initialized",r)}})}function mA(e,t){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},r=t.languages[0],i=t.options?t.options.fallbackLng:!1,o=t.languages[t.languages.length-1];if(r.toLowerCase()==="cimode")return!0;var a=function(f,v){var s=t.services.backendConnector.state["".concat(f,"|").concat(v)];return s===-1||s===2};return n.bindI18n&&n.bindI18n.indexOf("languageChanging")>-1&&t.services.backendConnector.backend&&t.isLanguageChangingTo&&!a(t.isLanguageChangingTo,e)?!1:!!(t.hasResourceBundle(r,e)||!t.services.backendConnector.backend||t.options.resources&&!t.options.partialBundledLanguages||a(r,e)&&(!i||a(o,e)))}function yA(e,t){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};if(!t.languages||!t.languages.length)return uv("i18n.languages were undefined or empty",t.languages),!0;var r=t.options.ignoreJSONStructure!==void 0;return r?t.hasLoadedNamespace(e,{precheck:function(o,a){if(n.bindI18n&&n.bindI18n.indexOf("languageChanging")>-1&&o.services.backendConnector.backend&&o.isLanguageChangingTo&&!a(o.isLanguageChangingTo,e))return!1}}):mA(e,t,n)}var _A=/&(?:amp|#38|lt|#60|gt|#62|apos|#39|quot|#34|nbsp|#160|copy|#169|reg|#174|hellip|#8230|#x2F|#47);/g,SA={"&amp;":"&","&#38;":"&","&lt;":"<","&#60;":"<","&gt;":">","&#62;":">","&apos;":"'","&#39;":"'","&quot;":'"',"&#34;":'"',"&nbsp;":" ","&#160;":" ","&copy;":"©","&#169;":"©","&reg;":"®","&#174;":"®","&hellip;":"…","&#8230;":"…","&#x2F;":"/","&#47;":"/"},EA=function(t){return SA[t]},wA=function(t){return t.replace(_A,EA)};function xS(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),n.push.apply(n,r)}return n}function $S(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?xS(Object(n),!0).forEach(function(r){Er(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):xS(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}var cv={bindI18n:"languageChanged",bindI18nStore:"",transEmptyNodeValue:"",transSupportBasicHtmlNodes:!0,transWrapTextNodes:"",transKeepBasicHtmlNodesFor:["br","strong","i","p"],useSuspense:!0,unescape:wA};function bA(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};cv=$S($S({},cv),e)}function TA(){return cv}var VC;function RA(e){VC=e}function IA(){return VC}function tr(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function US(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,qC(r.key),r)}}function nr(e,t,n){return t&&US(e.prototype,t),n&&US(e,n),Object.defineProperty(e,"prototype",{writable:!1}),e}var gG={type:"3rdParty",init:function(t){bA(t.options.react),RA(t)}},CA=Oe.createContext(),OA=function(){function e(){tr(this,e),this.usedNamespaces={}}return nr(e,[{key:"addUsedNamespaces",value:function(n){var r=this;n.forEach(function(i){r.usedNamespaces[i]||(r.usedNamespaces[i]=!0)})}},{key:"getUsedNamespaces",value:function(){return Object.keys(this.usedNamespaces)}}]),e}();function WC(e){if(Array.isArray(e))return e}function PA(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var r,i,o,a,c=[],f=!0,v=!1;try{if(o=(n=n.call(e)).next,t===0){if(Object(n)!==n)return;f=!1}else for(;!(f=(r=o.call(n)).done)&&(c.push(r.value),c.length!==t);f=!0);}catch(s){v=!0,i=s}finally{try{if(!f&&n.return!=null&&(a=n.return(),Object(a)!==a))return}finally{if(v)throw i}}return c}}function BS(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n<t;n++)r[n]=e[n];return r}function HC(e,t){if(e){if(typeof e=="string")return BS(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);if(n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set")return Array.from(e);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return BS(e,t)}}function GC(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
     68 In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function kA(e,t){return WC(e)||PA(e,t)||HC(e,t)||GC()}function FS(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),n.push.apply(n,r)}return n}function Ph(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?FS(Object(n),!0).forEach(function(r){Er(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):FS(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}var MA=function(t,n){var r=Oe.useRef();return Oe.useEffect(function(){r.current=n?r.current:t},[t,n]),r.current};function vG(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n=t.i18n,r=Oe.useContext(CA)||{},i=r.i18n,o=r.defaultNS,a=n||i||IA();if(a&&!a.reportNamespaces&&(a.reportNamespaces=new OA),!a){uv("You will need to pass in an i18next instance by using initReactI18next");var c=function(M){return Array.isArray(M)?M[M.length-1]:M},f=[c,{},!1];return f.t=c,f.i18n={},f.ready=!1,f}a.options.react&&a.options.react.wait!==void 0&&uv("It seems you are still using the old wait option, you may migrate to the new useSuspense behaviour.");var v=Ph(Ph(Ph({},TA()),a.options.react),t),s=v.useSuspense,g=v.keyPrefix,y=e||o||a.options&&a.options.defaultNS;y=typeof y=="string"?[y]:y||["translation"],a.reportNamespaces.addUsedNamespaces&&a.reportNamespaces.addUsedNamespaces(y);var S=(a.isInitialized||a.initializedStoreOnce)&&y.every(function(k){return yA(k,a,v)});function m(){return a.getFixedT(null,v.nsMode==="fallback"?y:y[0],g)}var p=Oe.useState(m),_=kA(p,2),u=_[0],l=_[1],d=y.join(),h=MA(d),w=Oe.useRef(!0);Oe.useEffect(function(){var k=v.bindI18n,M=v.bindI18nStore;w.current=!0,!S&&!s&&NS(a,y,function(){w.current&&l(m)}),S&&h&&h!==d&&w.current&&l(m);function L(){w.current&&l(m)}return k&&a&&a.on(k,L),M&&a&&a.store.on(M,L),function(){w.current=!1,k&&a&&k.split(" ").forEach(function(B){return a.off(B,L)}),M&&a&&M.split(" ").forEach(function(B){return a.store.off(B,L)})}},[a,d]);var E=Oe.useRef(!0);Oe.useEffect(function(){w.current&&!E.current&&l(m),E.current=!1},[a,g]);var I=[u,a,S];if(I.t=u,I.i18n=a,I.ready=S,S||!S&&!s)return I;throw new Promise(function(k){NS(a,y,function(){k()})})}var DA={cm:!0,mm:!0,in:!0,px:!0,pt:!0,pc:!0,em:!0,ex:!0,ch:!0,rem:!0,vw:!0,vh:!0,vmin:!0,vmax:!0,"%":!0};function AA(e){if(typeof e=="number")return{value:e,unit:"px"};var t,n=(e.match(/^[0-9.]*/)||"").toString();n.includes(".")?t=parseFloat(n):t=parseInt(n,10);var r=(e.match(/[^0-9]*$/)||"").toString();return DA[r]?{value:t,unit:r}:(console.warn("React Spinners: ".concat(e," is not a valid css value. Defaulting to ").concat(t,"px.")),{value:t,unit:"px"})}function _c(e){var t=AA(e);return"".concat(t.value).concat(t.unit)}var LA=function(e,t,n){var r="react-spinners-".concat(e,"-").concat(n);if(typeof window>"u"||!window.document)return r;var i=document.createElement("style");document.head.appendChild(i);var o=i.sheet,a=`
     69     @keyframes `.concat(r,` {
     70       `).concat(t,`
     71     }
     72   `);return o&&o.insertRule(a,0),r},Fd=globalThis&&globalThis.__assign||function(){return Fd=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++){t=arguments[n];for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i])}return e},Fd.apply(this,arguments)},NA=globalThis&&globalThis.__rest||function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,r=Object.getOwnPropertySymbols(e);i<r.length;i++)t.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(e,r[i])&&(n[r[i]]=e[r[i]]);return n},xA=LA("BounceLoader","0% {transform: scale(0)} 50% {transform: scale(1.0)} 100% {transform: scale(0)}","bounce");function mG(e){var t=e.loading,n=t===void 0?!0:t,r=e.color,i=r===void 0?"#000000":r,o=e.speedMultiplier,a=o===void 0?1:o,c=e.cssOverride,f=c===void 0?{}:c,v=e.size,s=v===void 0?60:v,g=NA(e,["loading","color","speedMultiplier","cssOverride","size"]),y=function(m){var p=m===1?"".concat(1/a,"s"):"0s";return{position:"absolute",height:_c(s),width:_c(s),backgroundColor:i,borderRadius:"100%",opacity:.6,top:0,left:0,animationFillMode:"both",animation:"".concat(xA," ").concat(2.1/a,"s ").concat(p," infinite ease-in-out")}},S=Fd({display:"inherit",position:"relative",width:_c(s),height:_c(s)},f);return n?Oe.createElement("span",Fd({style:S},g),Oe.createElement("span",{style:y(1)}),Oe.createElement("span",{style:y(2)})):null}var KS=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},Sc=function(e){return e&&e.Math==Math&&e},Ze=Sc(typeof globalThis=="object"&&globalThis)||Sc(typeof window=="object"&&window)||Sc(typeof self=="object"&&self)||Sc(typeof KS=="object"&&KS)||function(){return this}()||Function("return this")(),Of={},hn=function(e){try{return!!e()}catch{return!0}},$A=hn,wr=!$A(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7}),UA=hn,Pf=!UA(function(){var e=function(){}.bind();return typeof e!="function"||e.hasOwnProperty("prototype")}),BA=Pf,Ec=Function.prototype.call,rr=BA?Ec.bind(Ec):function(){return Ec.apply(Ec,arguments)},my={},zC={}.propertyIsEnumerable,YC=Object.getOwnPropertyDescriptor,FA=YC&&!zC.call({1:2},1);my.f=FA?function(t){var n=YC(this,t);return!!n&&n.enumerable}:zC;var kf=function(e,t){return{enumerable:!(e&1),configurable:!(e&2),writable:!(e&4),value:t}},QC=Pf,JC=Function.prototype,KA=JC.bind,dv=JC.call,jA=QC&&KA.bind(dv,dv),pn=QC?function(e){return e&&jA(e)}:function(e){return e&&function(){return dv.apply(e,arguments)}},XC=pn,qA=XC({}.toString),VA=XC("".slice),yy=function(e){return VA(qA(e),8,-1)},WA=Ze,HA=pn,GA=hn,zA=yy,kh=WA.Object,YA=HA("".split),ZC=GA(function(){return!kh("z").propertyIsEnumerable(0)})?function(e){return zA(e)=="String"?YA(e,""):kh(e)}:kh,QA=Ze,JA=QA.TypeError,eO=function(e){if(e==null)throw JA("Can't call method on "+e);return e},XA=ZC,ZA=eO,Au=function(e){return XA(ZA(e))},Ot=function(e){return typeof e=="function"},eL=Ot,ts=function(e){return typeof e=="object"?e!==null:eL(e)},Mh=Ze,tL=Ot,nL=function(e){return tL(e)?e:void 0},co=function(e,t){return arguments.length<2?nL(Mh[e]):Mh[e]&&Mh[e][t]},rL=pn,_y=rL({}.isPrototypeOf),iL=co,ns=iL("navigator","userAgent")||"",tO=Ze,Dh=ns,jS=tO.process,qS=tO.Deno,VS=jS&&jS.versions||qS&&qS.version,WS=VS&&VS.v8,pr,Kd;WS&&(pr=WS.split("."),Kd=pr[0]>0&&pr[0]<4?1:+(pr[0]+pr[1]));!Kd&&Dh&&(pr=Dh.match(/Edge\/(\d+)/),(!pr||pr[1]>=74)&&(pr=Dh.match(/Chrome\/(\d+)/),pr&&(Kd=+pr[1])));var Sy=Kd,HS=Sy,oL=hn,nO=!!Object.getOwnPropertySymbols&&!oL(function(){var e=Symbol();return!String(e)||!(Object(e)instanceof Symbol)||!Symbol.sham&&HS&&HS<41}),sL=nO,rO=sL&&!Symbol.sham&&typeof Symbol.iterator=="symbol",aL=Ze,lL=co,uL=Ot,cL=_y,dL=rO,fL=aL.Object,iO=dL?function(e){return typeof e=="symbol"}:function(e){var t=lL("Symbol");return uL(t)&&cL(t.prototype,fL(e))},hL=Ze,pL=hL.String,Mf=function(e){try{return pL(e)}catch{return"Object"}},gL=Ze,vL=Ot,mL=Mf,yL=gL.TypeError,fo=function(e){if(vL(e))return e;throw yL(mL(e)+" is not a function")},_L=fo,Ey=function(e,t){var n=e[t];return n==null?void 0:_L(n)},SL=Ze,Ah=rr,Lh=Ot,Nh=ts,EL=SL.TypeError,wL=function(e,t){var n,r;if(t==="string"&&Lh(n=e.toString)&&!Nh(r=Ah(n,e))||Lh(n=e.valueOf)&&!Nh(r=Ah(n,e))||t!=="string"&&Lh(n=e.toString)&&!Nh(r=Ah(n,e)))return r;throw EL("Can't convert object to primitive value")},wy={exports:{}},GS=Ze,bL=Object.defineProperty,by=function(e,t){try{bL(GS,e,{value:t,configurable:!0,writable:!0})}catch{GS[e]=t}return t},TL=Ze,RL=by,zS="__core-js_shared__",IL=TL[zS]||RL(zS,{}),Ty=IL,YS=Ty;(wy.exports=function(e,t){return YS[e]||(YS[e]=t!==void 0?t:{})})("versions",[]).push({version:"3.22.7",mode:"global",copyright:"© 2014-2022 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.22.7/LICENSE",source:"https://github.com/zloirock/core-js"});var CL=Ze,OL=eO,PL=CL.Object,Df=function(e){return PL(OL(e))},kL=pn,ML=Df,DL=kL({}.hasOwnProperty),jr=Object.hasOwn||function(t,n){return DL(ML(t),n)},AL=pn,LL=0,NL=Math.random(),xL=AL(1 .toString),oO=function(e){return"Symbol("+(e===void 0?"":e)+")_"+xL(++LL+NL,36)},$L=Ze,UL=wy.exports,QS=jr,BL=oO,JS=nO,sO=rO,ss=UL("wks"),Fo=$L.Symbol,XS=Fo&&Fo.for,FL=sO?Fo:Fo&&Fo.withoutSetter||BL,Cn=function(e){if(!QS(ss,e)||!(JS||typeof ss[e]=="string")){var t="Symbol."+e;JS&&QS(Fo,e)?ss[e]=Fo[e]:sO&&XS?ss[e]=XS(t):ss[e]=FL(t)}return ss[e]},KL=Ze,jL=rr,ZS=ts,eE=iO,qL=Ey,VL=wL,WL=Cn,HL=KL.TypeError,GL=WL("toPrimitive"),zL=function(e,t){if(!ZS(e)||eE(e))return e;var n=qL(e,GL),r;if(n){if(t===void 0&&(t="default"),r=jL(n,e,t),!ZS(r)||eE(r))return r;throw HL("Can't convert object to primitive value")}return t===void 0&&(t="number"),VL(e,t)},YL=zL,QL=iO,Ry=function(e){var t=YL(e,"string");return QL(t)?t:t+""},JL=Ze,tE=ts,fv=JL.document,XL=tE(fv)&&tE(fv.createElement),Af=function(e){return XL?fv.createElement(e):{}},ZL=wr,eN=hn,tN=Af,aO=!ZL&&!eN(function(){return Object.defineProperty(tN("div"),"a",{get:function(){return 7}}).a!=7}),nN=wr,rN=rr,iN=my,oN=kf,sN=Au,aN=Ry,lN=jr,uN=aO,nE=Object.getOwnPropertyDescriptor;Of.f=nN?nE:function(t,n){if(t=sN(t),n=aN(n),uN)try{return nE(t,n)}catch{}if(lN(t,n))return oN(!rN(iN.f,t,n),t[n])};var ui={},cN=wr,dN=hn,lO=cN&&dN(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42}),uO=Ze,fN=ts,hN=uO.String,pN=uO.TypeError,qr=function(e){if(fN(e))return e;throw pN(hN(e)+" is not an object")},gN=Ze,vN=wr,mN=aO,yN=lO,wc=qr,rE=Ry,_N=gN.TypeError,xh=Object.defineProperty,SN=Object.getOwnPropertyDescriptor,$h="enumerable",Uh="configurable",Bh="writable";ui.f=vN?yN?function(t,n,r){if(wc(t),n=rE(n),wc(r),typeof t=="function"&&n==="prototype"&&"value"in r&&Bh in r&&!r[Bh]){var i=SN(t,n);i&&i[Bh]&&(t[n]=r.value,r={configurable:Uh in r?r[Uh]:i[Uh],enumerable:$h in r?r[$h]:i[$h],writable:!1})}return xh(t,n,r)}:xh:function(t,n,r){if(wc(t),n=rE(n),wc(r),mN)try{return xh(t,n,r)}catch{}if("get"in r||"set"in r)throw _N("Accessors not supported");return"value"in r&&(t[n]=r.value),t};var EN=wr,wN=ui,bN=kf,Lu=EN?function(e,t,n){return wN.f(e,t,bN(1,n))}:function(e,t,n){return e[t]=n,e},cO={exports:{}},hv=wr,TN=jr,dO=Function.prototype,RN=hv&&Object.getOwnPropertyDescriptor,Iy=TN(dO,"name"),IN=Iy&&function(){}.name==="something",CN=Iy&&(!hv||hv&&RN(dO,"name").configurable),fO={EXISTS:Iy,PROPER:IN,CONFIGURABLE:CN},ON=pn,PN=Ot,pv=Ty,kN=ON(Function.toString);PN(pv.inspectSource)||(pv.inspectSource=function(e){return kN(e)});var Lf=pv.inspectSource,MN=Ze,DN=Ot,AN=Lf,iE=MN.WeakMap,LN=DN(iE)&&/native code/.test(AN(iE)),NN=wy.exports,xN=oO,oE=NN("keys"),Cy=function(e){return oE[e]||(oE[e]=xN(e))},Oy={},$N=LN,hO=Ze,Fh=pn,UN=ts,BN=Lu,Kh=jr,jh=Ty,FN=Cy,KN=Oy,sE="Object already initialized",gv=hO.TypeError,jN=hO.WeakMap,jd,yu,qd,qN=function(e){return qd(e)?yu(e):jd(e,{})},VN=function(e){return function(t){var n;if(!UN(t)||(n=yu(t)).type!==e)throw gv("Incompatible receiver, "+e+" required");return n}};if($N||jh.state){var vo=jh.state||(jh.state=new jN),WN=Fh(vo.get),aE=Fh(vo.has),HN=Fh(vo.set);jd=function(e,t){if(aE(vo,e))throw new gv(sE);return t.facade=e,HN(vo,e,t),t},yu=function(e){return WN(vo,e)||{}},qd=function(e){return aE(vo,e)}}else{var as=FN("state");KN[as]=!0,jd=function(e,t){if(Kh(e,as))throw new gv(sE);return t.facade=e,BN(e,as,t),t},yu=function(e){return Kh(e,as)?e[as]:{}},qd=function(e){return Kh(e,as)}}var Py={set:jd,get:yu,has:qd,enforce:qN,getterFor:VN},GN=hn,zN=Ot,bc=jr,pO=wr,YN=fO.CONFIGURABLE,QN=Lf,gO=Py,JN=gO.enforce,XN=gO.get,od=Object.defineProperty,ZN=pO&&!GN(function(){return od(function(){},"length",{value:8}).length!==8}),ex=String(String).split("String"),tx=cO.exports=function(e,t,n){String(t).slice(0,7)==="Symbol("&&(t="["+String(t).replace(/^Symbol\(([^)]*)\)/,"$1")+"]"),n&&n.getter&&(t="get "+t),n&&n.setter&&(t="set "+t),(!bc(e,"name")||YN&&e.name!==t)&&od(e,"name",{value:t,configurable:!0}),ZN&&n&&bc(n,"arity")&&e.length!==n.arity&&od(e,"length",{value:n.arity});try{n&&bc(n,"constructor")&&n.constructor?pO&&od(e,"prototype",{writable:!1}):e.prototype&&(e.prototype=void 0)}catch{}var r=JN(e);return bc(r,"source")||(r.source=ex.join(typeof t=="string"?t:"")),e};Function.prototype.toString=tx(function(){return zN(this)&&XN(this).source||QN(this)},"toString");var nx=Ot,rx=Lu,ix=cO.exports,ox=by,Nu=function(e,t,n,r){r||(r={});var i=r.enumerable,o=r.name!==void 0?r.name:t;return nx(n)&&ix(n,o,r),r.global?i?e[t]=n:ox(t,n):(r.unsafe?e[t]&&(i=!0):delete e[t],i?e[t]=n:rx(e,t,n)),e},vO={},sx=Math.ceil,ax=Math.floor,lx=Math.trunc||function(t){var n=+t;return(n>0?ax:sx)(n)},ux=lx,mO=function(e){var t=+e;return t!==t||t===0?0:ux(t)},cx=mO,dx=Math.max,fx=Math.min,yO=function(e,t){var n=cx(e);return n<0?dx(n+t,0):fx(n,t)},hx=mO,px=Math.min,gx=function(e){return e>0?px(hx(e),9007199254740991):0},vx=gx,Nf=function(e){return vx(e.length)},mx=Au,yx=yO,_x=Nf,lE=function(e){return function(t,n,r){var i=mx(t),o=_x(i),a=yx(r,o),c;if(e&&n!=n){for(;o>a;)if(c=i[a++],c!=c)return!0}else for(;o>a;a++)if((e||a in i)&&i[a]===n)return e||a||0;return!e&&-1}},Sx={includes:lE(!0),indexOf:lE(!1)},Ex=pn,qh=jr,wx=Au,bx=Sx.indexOf,Tx=Oy,uE=Ex([].push),_O=function(e,t){var n=wx(e),r=0,i=[],o;for(o in n)!qh(Tx,o)&&qh(n,o)&&uE(i,o);for(;t.length>r;)qh(n,o=t[r++])&&(~bx(i,o)||uE(i,o));return i},ky=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],Rx=_O,Ix=ky,Cx=Ix.concat("length","prototype");vO.f=Object.getOwnPropertyNames||function(t){return Rx(t,Cx)};var My={};My.f=Object.getOwnPropertySymbols;var Ox=co,Px=pn,kx=vO,Mx=My,Dx=qr,Ax=Px([].concat),Lx=Ox("Reflect","ownKeys")||function(t){var n=kx.f(Dx(t)),r=Mx.f;return r?Ax(n,r(t)):n},cE=jr,Nx=Lx,xx=Of,$x=ui,Ux=function(e,t,n){for(var r=Nx(t),i=$x.f,o=xx.f,a=0;a<r.length;a++){var c=r[a];!cE(e,c)&&!(n&&cE(n,c))&&i(e,c,o(t,c))}},Bx=hn,Fx=Ot,Kx=/#|\.prototype\./,xu=function(e,t){var n=qx[jx(e)];return n==Wx?!0:n==Vx?!1:Fx(t)?Bx(t):!!t},jx=xu.normalize=function(e){return String(e).replace(Kx,".").toLowerCase()},qx=xu.data={},Vx=xu.NATIVE="N",Wx=xu.POLYFILL="P",SO=xu,Vh=Ze,Hx=Of.f,Gx=Lu,zx=Nu,Yx=by,Qx=Ux,Jx=SO,ci=function(e,t){var n=e.target,r=e.global,i=e.stat,o,a,c,f,v,s;if(r?a=Vh:i?a=Vh[n]||Yx(n,{}):a=(Vh[n]||{}).prototype,a)for(c in t){if(v=t[c],e.dontCallGetSet?(s=Hx(a,c),f=s&&s.value):f=a[c],o=Jx(r?c:n+(i?".":"#")+c,e.forced),!o&&f!==void 0){if(typeof v==typeof f)continue;Qx(v,f)}(e.sham||f&&f.sham)&&Gx(v,"sham",!0),zx(a,c,v,e)}},Xx=Cn,Zx=Xx("toStringTag"),EO={};EO[Zx]="z";var e$=String(EO)==="[object z]",t$=Ze,n$=e$,r$=Ot,sd=yy,i$=Cn,o$=i$("toStringTag"),s$=t$.Object,a$=sd(function(){return arguments}())=="Arguments",l$=function(e,t){try{return e[t]}catch{}},Dy=n$?sd:function(e){var t,n,r;return e===void 0?"Undefined":e===null?"Null":typeof(n=l$(t=s$(e),o$))=="string"?n:a$?sd(t):(r=sd(t))=="Object"&&r$(t.callee)?"Arguments":r},u$=Ze,c$=Dy,d$=u$.String,f$=function(e){if(c$(e)==="Symbol")throw TypeError("Cannot convert a Symbol value to a string");return d$(e)},h$=Ry,p$=ui,g$=kf,v$=function(e,t,n){var r=h$(t);r in e?p$.f(e,r,g$(0,n)):e[r]=n},m$=Ze,dE=yO,y$=Nf,_$=v$,S$=m$.Array,E$=Math.max,w$=function(e,t,n){for(var r=y$(e),i=dE(t,r),o=dE(n===void 0?r:n,r),a=S$(E$(o-i,0)),c=0;i<o;i++,c++)_$(a,c,e[i]);return a.length=c,a},fE=w$,b$=Math.floor,vv=function(e,t){var n=e.length,r=b$(n/2);return n<8?T$(e,t):R$(e,vv(fE(e,0,r),t),vv(fE(e,r),t),t)},T$=function(e,t){for(var n=e.length,r=1,i,o;r<n;){for(o=r,i=e[r];o&&t(e[o-1],i)>0;)e[o]=e[--o];o!==r++&&(e[o]=i)}return e},R$=function(e,t,n,r){for(var i=t.length,o=n.length,a=0,c=0;a<i||c<o;)e[a+c]=a<i&&c<o?r(t[a],n[c])<=0?t[a++]:n[c++]:a<i?t[a++]:n[c++];return e},I$=vv,C$=hn,O$=function(e,t){var n=[][e];return!!n&&C$(function(){n.call(null,t||function(){return 1},1)})},P$=ns,hE=P$.match(/firefox\/(\d+)/i),k$=!!hE&&+hE[1],M$=ns,D$=/MSIE|Trident/.test(M$),A$=ns,pE=A$.match(/AppleWebKit\/(\d+)\./),L$=!!pE&&+pE[1],N$=ci,wO=pn,x$=fo,$$=Df,U$=Nf,gE=f$,Ay=hn,B$=I$,F$=O$,vE=k$,K$=D$,mE=Sy,yE=L$,ji=[],_E=wO(ji.sort),j$=wO(ji.push),q$=Ay(function(){ji.sort(void 0)}),V$=Ay(function(){ji.sort(null)}),W$=F$("sort"),bO=!Ay(function(){if(mE)return mE<70;if(!(vE&&vE>3)){if(K$)return!0;if(yE)return yE<603;var e="",t,n,r,i;for(t=65;t<76;t++){switch(n=String.fromCharCode(t),t){case 66:case 69:case 70:case 72:r=3;break;case 68:case 71:r=4;break;default:r=2}for(i=0;i<47;i++)ji.push({k:n+i,v:r})}for(ji.sort(function(o,a){return a.v-o.v}),i=0;i<ji.length;i++)n=ji[i].k.charAt(0),e.charAt(e.length-1)!==n&&(e+=n);return e!=="DGBEFHACIJK"}}),H$=q$||!V$||!W$||!bO,G$=function(e){return function(t,n){return n===void 0?-1:t===void 0?1:e!==void 0?+e(t,n)||0:gE(t)>gE(n)?1:-1}};N$({target:"Array",proto:!0,forced:H$},{sort:function(t){t!==void 0&&x$(t);var n=$$(this);if(bO)return t===void 0?_E(n):_E(n,t);var r=[],i=U$(n),o,a;for(a=0;a<i;a++)a in n&&j$(r,n[a]);for(B$(r,G$(t)),o=r.length,a=0;a<o;)n[a]=r[a++];for(;a<i;)delete n[a++];return n}});var TO={},z$=_O,Y$=ky,RO=Object.keys||function(t){return z$(t,Y$)},Q$=wr,J$=lO,X$=ui,Z$=qr,eU=Au,tU=RO;TO.f=Q$&&!J$?Object.defineProperties:function(t,n){Z$(t);for(var r=eU(n),i=tU(n),o=i.length,a=0,c;o>a;)X$.f(t,c=i[a++],r[c]);return t};var nU=co,IO=nU("document","documentElement"),rU=qr,iU=TO,SE=ky,oU=Oy,sU=IO,aU=Af,lU=Cy,EE=">",wE="<",mv="prototype",yv="script",CO=lU("IE_PROTO"),Wh=function(){},OO=function(e){return wE+yv+EE+e+wE+"/"+yv+EE},bE=function(e){e.write(OO("")),e.close();var t=e.parentWindow.Object;return e=null,t},uU=function(){var e=aU("iframe"),t="java"+yv+":",n;return e.style.display="none",sU.appendChild(e),e.src=String(t),n=e.contentWindow.document,n.open(),n.write(OO("document.F=Object")),n.close(),n.F},Tc,ad=function(){try{Tc=new ActiveXObject("htmlfile")}catch{}ad=typeof document<"u"?document.domain&&Tc?bE(Tc):uU():bE(Tc);for(var e=SE.length;e--;)delete ad[mv][SE[e]];return ad()};oU[CO]=!0;var PO=Object.create||function(t,n){var r;return t!==null?(Wh[mv]=rU(t),r=new Wh,Wh[mv]=null,r[CO]=t):r=ad(),n===void 0?r:iU.f(r,n)},cU=Cn,dU=PO,fU=ui.f,_v=cU("unscopables"),Sv=Array.prototype;Sv[_v]==null&&fU(Sv,_v,{configurable:!0,value:dU(null)});var hU=function(e){Sv[_v][e]=!0},$u={},pU=hn,gU=!pU(function(){function e(){}return e.prototype.constructor=null,Object.getPrototypeOf(new e)!==e.prototype}),vU=Ze,mU=jr,yU=Ot,_U=Df,SU=Cy,EU=gU,TE=SU("IE_PROTO"),Ev=vU.Object,wU=Ev.prototype,kO=EU?Ev.getPrototypeOf:function(e){var t=_U(e);if(mU(t,TE))return t[TE];var n=t.constructor;return yU(n)&&t instanceof n?n.prototype:t instanceof Ev?wU:null},bU=hn,TU=Ot,RE=kO,RU=Nu,IU=Cn,wv=IU("iterator"),MO=!1,Ho,Hh,Gh;[].keys&&(Gh=[].keys(),"next"in Gh?(Hh=RE(RE(Gh)),Hh!==Object.prototype&&(Ho=Hh)):MO=!0);var CU=Ho==null||bU(function(){var e={};return Ho[wv].call(e)!==e});CU&&(Ho={});TU(Ho[wv])||RU(Ho,wv,function(){return this});var DO={IteratorPrototype:Ho,BUGGY_SAFARI_ITERATORS:MO},OU=ui.f,PU=jr,kU=Cn,IE=kU("toStringTag"),Ly=function(e,t,n){e&&!n&&(e=e.prototype),e&&!PU(e,IE)&&OU(e,IE,{configurable:!0,value:t})},MU=DO.IteratorPrototype,DU=PO,AU=kf,LU=Ly,NU=$u,xU=function(){return this},$U=function(e,t,n,r){var i=t+" Iterator";return e.prototype=DU(MU,{next:AU(+!r,n)}),LU(e,i,!1),NU[i]=xU,e},AO=Ze,UU=Ot,BU=AO.String,FU=AO.TypeError,KU=function(e){if(typeof e=="object"||UU(e))return e;throw FU("Can't set "+BU(e)+" as a prototype")},jU=pn,qU=qr,VU=KU,LO=Object.setPrototypeOf||("__proto__"in{}?function(){var e=!1,t={},n;try{n=jU(Object.getOwnPropertyDescriptor(Object.prototype,"__proto__").set),n(t,[]),e=t instanceof Array}catch{}return function(i,o){return qU(i),VU(o),e?n(i,o):i.__proto__=o,i}}():void 0),WU=ci,HU=rr,NO=fO,GU=Ot,zU=$U,CE=kO,OE=LO,YU=Ly,QU=Lu,zh=Nu,JU=Cn,XU=$u,xO=DO,ZU=NO.PROPER,eB=NO.CONFIGURABLE,PE=xO.IteratorPrototype,Rc=xO.BUGGY_SAFARI_ITERATORS,Ba=JU("iterator"),kE="keys",Fa="values",ME="entries",tB=function(){return this},nB=function(e,t,n,r,i,o,a){zU(n,t,r);var c=function(u){if(u===i&&y)return y;if(!Rc&&u in s)return s[u];switch(u){case kE:return function(){return new n(this,u)};case Fa:return function(){return new n(this,u)};case ME:return function(){return new n(this,u)}}return function(){return new n(this)}},f=t+" Iterator",v=!1,s=e.prototype,g=s[Ba]||s["@@iterator"]||i&&s[i],y=!Rc&&g||c(i),S=t=="Array"&&s.entries||g,m,p,_;if(S&&(m=CE(S.call(new e)),m!==Object.prototype&&m.next&&(CE(m)!==PE&&(OE?OE(m,PE):GU(m[Ba])||zh(m,Ba,tB)),YU(m,f,!0))),ZU&&i==Fa&&g&&g.name!==Fa&&(eB?QU(s,"name",Fa):(v=!0,y=function(){return HU(g,this)})),i)if(p={values:c(Fa),keys:o?y:c(kE),entries:c(ME)},a)for(_ in p)(Rc||v||!(_ in s))&&zh(s,_,p[_]);else WU({target:t,proto:!0,forced:Rc||v},p);return s[Ba]!==y&&zh(s,Ba,y,{name:i}),XU[t]=y,p},rB=Au,Ny=hU,DE=$u,$O=Py,iB=ui.f,oB=nB,sB=wr,UO="Array Iterator",aB=$O.set,lB=$O.getterFor(UO),uB=oB(Array,"Array",function(e,t){aB(this,{type:UO,target:rB(e),index:0,kind:t})},function(){var e=lB(this),t=e.target,n=e.kind,r=e.index++;return!t||r>=t.length?(e.target=void 0,{value:void 0,done:!0}):n=="keys"?{value:r,done:!1}:n=="values"?{value:t[r],done:!1}:{value:[r,t[r]],done:!1}},"values"),AE=DE.Arguments=DE.Array;Ny("keys");Ny("values");Ny("entries");if(sB&&AE.name!=="values")try{iB(AE,"name",{value:"values"})}catch{}var cB={CSSRuleList:0,CSSStyleDeclaration:0,CSSValueList:0,ClientRectList:0,DOMRectList:0,DOMStringList:0,DOMTokenList:1,DataTransferItemList:0,FileList:0,HTMLAllCollection:0,HTMLCollection:0,HTMLFormElement:0,HTMLSelectElement:0,MediaList:0,MimeTypeArray:0,NamedNodeMap:0,NodeList:1,PaintRequestList:0,Plugin:0,PluginArray:0,SVGLengthList:0,SVGNumberList:0,SVGPathSegList:0,SVGPointList:0,SVGStringList:0,SVGTransformList:0,SourceBufferList:0,StyleSheetList:0,TextTrackCueList:0,TextTrackList:0,TouchList:0},dB=Af,Yh=dB("span").classList,LE=Yh&&Yh.constructor&&Yh.constructor.prototype,fB=LE===Object.prototype?void 0:LE,NE=Ze,BO=cB,hB=fB,Ll=uB,Qh=Lu,FO=Cn,Jh=FO("iterator"),xE=FO("toStringTag"),Xh=Ll.values,KO=function(e,t){if(e){if(e[Jh]!==Xh)try{Qh(e,Jh,Xh)}catch{e[Jh]=Xh}if(e[xE]||Qh(e,xE,t),BO[t]){for(var n in Ll)if(e[n]!==Ll[n])try{Qh(e,n,Ll[n])}catch{e[n]=Ll[n]}}}};for(var Zh in BO)KO(NE[Zh]&&NE[Zh].prototype,Zh);KO(hB,"DOMTokenList");var $E=wr,pB=pn,gB=rr,vB=hn,ep=RO,mB=My,yB=my,_B=Df,SB=ZC,ls=Object.assign,UE=Object.defineProperty,EB=pB([].concat),wB=!ls||vB(function(){if($E&&ls({b:1},ls(UE({},"a",{enumerable:!0,get:function(){UE(this,"b",{value:3,enumerable:!1})}}),{b:2})).b!==1)return!0;var e={},t={},n=Symbol(),r="abcdefghijklmnopqrst";return e[n]=7,r.split("").forEach(function(i){t[i]=i}),ls({},e)[n]!=7||ep(ls({},t)).join("")!=r})?function(t,n){for(var r=_B(t),i=arguments.length,o=1,a=mB.f,c=yB.f;i>o;)for(var f=SB(arguments[o++]),v=a?EB(ep(f),a(f)):ep(f),s=v.length,g=0,y;s>g;)y=v[g++],(!$E||gB(c,f,y))&&(r[y]=f[y]);return r}:ls,bB=ci,BE=wB;bB({target:"Object",stat:!0,arity:2,forced:Object.assign!==BE},{assign:BE});function xy(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,r=Object.getOwnPropertySymbols(e);i<r.length;i++)t.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(e,r[i])&&(n[r[i]]=e[r[i]]);return n}var TB=yy,RB=Ze,$y=TB(RB.process)=="process",IB=co,CB=ui,OB=Cn,PB=wr,FE=OB("species"),kB=function(e){var t=IB(e),n=CB.f;PB&&t&&!t[FE]&&n(t,FE,{configurable:!0,get:function(){return this}})},MB=Ze,DB=_y,AB=MB.TypeError,LB=function(e,t){if(DB(t,e))return e;throw AB("Incorrect invocation")},NB=pn,xB=hn,jO=Ot,$B=Dy,UB=co,BB=Lf,qO=function(){},FB=[],VO=UB("Reflect","construct"),Uy=/^\s*(?:class|function)\b/,KB=NB(Uy.exec),jB=!Uy.exec(qO),Ka=function(t){if(!jO(t))return!1;try{return VO(qO,FB,t),!0}catch{return!1}},WO=function(t){if(!jO(t))return!1;switch($B(t)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return jB||!!KB(Uy,BB(t))}catch{return!0}};WO.sham=!0;var qB=!VO||xB(function(){var e;return Ka(Ka.call)||!Ka(Object)||!Ka(function(){e=!0})||e})?WO:Ka,VB=Ze,WB=qB,HB=Mf,GB=VB.TypeError,zB=function(e){if(WB(e))return e;throw GB(HB(e)+" is not a constructor")},KE=qr,YB=zB,QB=Cn,JB=QB("species"),XB=function(e,t){var n=KE(e).constructor,r;return n===void 0||(r=KE(n)[JB])==null?t:YB(r)},ZB=Pf,HO=Function.prototype,jE=HO.apply,qE=HO.call,eF=typeof Reflect=="object"&&Reflect.apply||(ZB?qE.bind(jE):function(){return qE.apply(jE,arguments)}),VE=pn,tF=fo,nF=Pf,rF=VE(VE.bind),By=function(e,t){return tF(e),t===void 0?e:nF?rF(e,t):function(){return e.apply(t,arguments)}},iF=pn,oF=iF([].slice),sF=Ze,aF=sF.TypeError,lF=function(e,t){if(e<t)throw aF("Not enough arguments");return e},uF=ns,GO=/(?:ipad|iphone|ipod).*applewebkit/i.test(uF),An=Ze,cF=eF,dF=By,WE=Ot,fF=jr,hF=hn,HE=IO,pF=oF,GE=Af,gF=lF,vF=GO,mF=$y,bv=An.setImmediate,Tv=An.clearImmediate,yF=An.process,tp=An.Dispatch,_F=An.Function,zE=An.MessageChannel,SF=An.String,np=0,Gl={},YE="onreadystatechange",_u,mo,rp,ip;try{_u=An.location}catch{}var Fy=function(e){if(fF(Gl,e)){var t=Gl[e];delete Gl[e],t()}},op=function(e){return function(){Fy(e)}},QE=function(e){Fy(e.data)},JE=function(e){An.postMessage(SF(e),_u.protocol+"//"+_u.host)};(!bv||!Tv)&&(bv=function(t){gF(arguments.length,1);var n=WE(t)?t:_F(t),r=pF(arguments,1);return Gl[++np]=function(){cF(n,void 0,r)},mo(np),np},Tv=function(t){delete Gl[t]},mF?mo=function(e){yF.nextTick(op(e))}:tp&&tp.now?mo=function(e){tp.now(op(e))}:zE&&!vF?(rp=new zE,ip=rp.port2,rp.port1.onmessage=QE,mo=dF(ip.postMessage,ip)):An.addEventListener&&WE(An.postMessage)&&!An.importScripts&&_u&&_u.protocol!=="file:"&&!hF(JE)?(mo=JE,An.addEventListener("message",QE,!1)):YE in GE("script")?mo=function(e){HE.appendChild(GE("script"))[YE]=function(){HE.removeChild(this),Fy(e)}}:mo=function(e){setTimeout(op(e),0)});var zO={set:bv,clear:Tv},EF=ns,wF=Ze,bF=/ipad|iphone|ipod/i.test(EF)&&wF.Pebble!==void 0,TF=ns,RF=/web0s(?!.*chrome)/i.test(TF),Go=Ze,XE=By,IF=Of.f,sp=zO.set,CF=GO,OF=bF,PF=RF,ap=$y,ZE=Go.MutationObserver||Go.WebKitMutationObserver,ew=Go.document,tw=Go.process,Ic=Go.Promise,nw=IF(Go,"queueMicrotask"),YO=nw&&nw.value,ja,Mo,zl,Ms,lp,up,Cc,rw;YO||(ja=function(){var e,t;for(ap&&(e=tw.domain)&&e.exit();Mo;){t=Mo.fn,Mo=Mo.next;try{t()}catch(n){throw Mo?Ms():zl=void 0,n}}zl=void 0,e&&e.enter()},!CF&&!ap&&!PF&&ZE&&ew?(lp=!0,up=ew.createTextNode(""),new ZE(ja).observe(up,{characterData:!0}),Ms=function(){up.data=lp=!lp}):!OF&&Ic&&Ic.resolve?(Cc=Ic.resolve(void 0),Cc.constructor=Ic,rw=XE(Cc.then,Cc),Ms=function(){rw(ja)}):ap?Ms=function(){tw.nextTick(ja)}:(sp=XE(sp,Go),Ms=function(){sp(ja)}));var kF=YO||function(e){var t={fn:e,next:void 0};zl&&(zl.next=t),Mo||(Mo=t,Ms()),zl=t},MF=Ze,DF=function(e,t){var n=MF.console;n&&n.error&&(arguments.length==1?n.error(e):n.error(e,t))},Ky=function(e){try{return{error:!1,value:e()}}catch(t){return{error:!0,value:t}}},QO=function(){this.head=null,this.tail=null};QO.prototype={add:function(e){var t={item:e,next:null};this.head?this.tail.next=t:this.head=t,this.tail=t},get:function(){var e=this.head;if(e)return this.head=e.next,this.tail===e&&(this.tail=null),e.item}};var AF=QO,LF=Ze,xf=LF.Promise,NF=typeof window=="object"&&typeof Deno!="object",xF=Ze,Yl=xf,$F=Ot,UF=SO,BF=Lf,FF=Cn,KF=NF,iw=Sy;Yl&&Yl.prototype;var jF=FF("species"),Rv=!1,JO=$F(xF.PromiseRejectionEvent),qF=UF("Promise",function(){var e=BF(Yl),t=e!==String(Yl);if(!t&&iw===66)return!0;if(iw>=51&&/native code/.test(e))return!1;var n=new Yl(function(o){o(1)}),r=function(o){o(function(){},function(){})},i=n.constructor={};return i[jF]=r,Rv=n.then(function(){})instanceof r,Rv?!t&&KF&&!JO:!0}),Uu={CONSTRUCTOR:qF,REJECTION_EVENT:JO,SUBCLASSING:Rv},ya={},ow=fo,VF=function(e){var t,n;this.promise=new e(function(r,i){if(t!==void 0||n!==void 0)throw TypeError("Bad Promise constructor");t=r,n=i}),this.resolve=ow(t),this.reject=ow(n)};ya.f=function(e){return new VF(e)};var WF=ci,Vd=$y,ro=Ze,fa=rr,sw=Nu,aw=LO,HF=Ly,GF=kB,zF=fo,ld=Ot,YF=ts,QF=LB,JF=XB,XO=zO.set,jy=kF,XF=DF,ZF=Ky,e2=AF,ZO=Py,Wd=xf,qy=Uu,eP=ya,$f="Promise",tP=qy.CONSTRUCTOR,t2=qy.REJECTION_EVENT,n2=qy.SUBCLASSING,cp=ZO.getterFor($f),r2=ZO.set,Ds=Wd&&Wd.prototype,Do=Wd,Oc=Ds,nP=ro.TypeError,Iv=ro.document,Vy=ro.process,Cv=eP.f,i2=Cv,o2=!!(Iv&&Iv.createEvent&&ro.dispatchEvent),rP="unhandledrejection",s2="rejectionhandled",lw=0,iP=1,a2=2,Wy=1,oP=2,Pc,uw,l2,cw,sP=function(e){var t;return YF(e)&&ld(t=e.then)?t:!1},aP=function(e,t){var n=t.value,r=t.state==iP,i=r?e.ok:e.fail,o=e.resolve,a=e.reject,c=e.domain,f,v,s;try{i?(r||(t.rejection===oP&&c2(t),t.rejection=Wy),i===!0?f=n:(c&&c.enter(),f=i(n),c&&(c.exit(),s=!0)),f===e.promise?a(nP("Promise-chain cycle")):(v=sP(f))?fa(v,f,o,a):o(f)):a(n)}catch(g){c&&!s&&c.exit(),a(g)}},lP=function(e,t){e.notified||(e.notified=!0,jy(function(){for(var n=e.reactions,r;r=n.get();)aP(r,e);e.notified=!1,t&&!e.rejection&&u2(e)}))},uP=function(e,t,n){var r,i;o2?(r=Iv.createEvent("Event"),r.promise=t,r.reason=n,r.initEvent(e,!1,!0),ro.dispatchEvent(r)):r={promise:t,reason:n},!t2&&(i=ro["on"+e])?i(r):e===rP&&XF("Unhandled promise rejection",n)},u2=function(e){fa(XO,ro,function(){var t=e.facade,n=e.value,r=dw(e),i;if(r&&(i=ZF(function(){Vd?Vy.emit("unhandledRejection",n,t):uP(rP,t,n)}),e.rejection=Vd||dw(e)?oP:Wy,i.error))throw i.value})},dw=function(e){return e.rejection!==Wy&&!e.parent},c2=function(e){fa(XO,ro,function(){var t=e.facade;Vd?Vy.emit("rejectionHandled",t):uP(s2,t,e.value)})},Hs=function(e,t,n){return function(r){e(t,r,n)}},ta=function(e,t,n){e.done||(e.done=!0,n&&(e=n),e.value=t,e.state=a2,lP(e,!0))},Ov=function(e,t,n){if(!e.done){e.done=!0,n&&(e=n);try{if(e.facade===t)throw nP("Promise can't be resolved itself");var r=sP(t);r?jy(function(){var i={done:!1};try{fa(r,t,Hs(Ov,i,e),Hs(ta,i,e))}catch(o){ta(i,o,e)}}):(e.value=t,e.state=iP,lP(e,!1))}catch(i){ta({done:!1},i,e)}}};if(tP&&(Do=function(t){QF(this,Oc),zF(t),fa(Pc,this);var n=cp(this);try{t(Hs(Ov,n),Hs(ta,n))}catch(r){ta(n,r)}},Oc=Do.prototype,Pc=function(t){r2(this,{type:$f,done:!1,notified:!1,parent:!1,reactions:new e2,rejection:!1,state:lw,value:void 0})},Pc.prototype=sw(Oc,"then",function(t,n){var r=cp(this),i=Cv(JF(this,Do));return r.parent=!0,i.ok=ld(t)?t:!0,i.fail=ld(n)&&n,i.domain=Vd?Vy.domain:void 0,r.state==lw?r.reactions.add(i):jy(function(){aP(i,r)}),i.promise}),uw=function(){var e=new Pc,t=cp(e);this.promise=e,this.resolve=Hs(Ov,t),this.reject=Hs(ta,t)},eP.f=Cv=function(e){return e===Do||e===l2?new uw(e):i2(e)},ld(Wd)&&Ds!==Object.prototype)){cw=Ds.then,n2||sw(Ds,"then",function(t,n){var r=this;return new Do(function(i,o){fa(cw,r,i,o)}).then(t,n)},{unsafe:!0});try{delete Ds.constructor}catch{}aw&&aw(Ds,Oc)}WF({global:!0,constructor:!0,wrap:!0,forced:tP},{Promise:Do});HF(Do,$f,!1);GF($f);var d2=Cn,f2=$u,h2=d2("iterator"),p2=Array.prototype,g2=function(e){return e!==void 0&&(f2.Array===e||p2[h2]===e)},v2=Dy,fw=Ey,m2=$u,y2=Cn,_2=y2("iterator"),cP=function(e){if(e!=null)return fw(e,_2)||fw(e,"@@iterator")||m2[v2(e)]},S2=Ze,E2=rr,w2=fo,b2=qr,T2=Mf,R2=cP,I2=S2.TypeError,C2=function(e,t){var n=arguments.length<2?R2(e):t;if(w2(n))return b2(E2(n,e));throw I2(T2(e)+" is not iterable")},O2=rr,hw=qr,P2=Ey,k2=function(e,t,n){var r,i;hw(e);try{if(r=P2(e,"return"),!r){if(t==="throw")throw n;return n}r=O2(r,e)}catch(o){i=!0,r=o}if(t==="throw")throw n;if(i)throw r;return hw(r),n},M2=Ze,D2=By,A2=rr,L2=qr,N2=Mf,x2=g2,$2=Nf,pw=_y,U2=C2,B2=cP,gw=k2,F2=M2.TypeError,ud=function(e,t){this.stopped=e,this.result=t},vw=ud.prototype,dP=function(e,t,n){var r=n&&n.that,i=!!(n&&n.AS_ENTRIES),o=!!(n&&n.IS_ITERATOR),a=!!(n&&n.INTERRUPTED),c=D2(t,r),f,v,s,g,y,S,m,p=function(u){return f&&gw(f,"normal",u),new ud(!0,u)},_=function(u){return i?(L2(u),a?c(u[0],u[1],p):c(u[0],u[1])):a?c(u,p):c(u)};if(o)f=e;else{if(v=B2(e),!v)throw F2(N2(e)+" is not iterable");if(x2(v)){for(s=0,g=$2(e);g>s;s++)if(y=_(e[s]),y&&pw(vw,y))return y;return new ud(!1)}f=U2(e,v)}for(S=f.next;!(m=A2(S,f)).done;){try{y=_(m.value)}catch(u){gw(f,"throw",u)}if(typeof y=="object"&&y&&pw(vw,y))return y}return new ud(!1)},K2=Cn,fP=K2("iterator"),hP=!1;try{var j2=0,mw={next:function(){return{done:!!j2++}},return:function(){hP=!0}};mw[fP]=function(){return this},Array.from(mw,function(){throw 2})}catch{}var q2=function(e,t){if(!t&&!hP)return!1;var n=!1;try{var r={};r[fP]=function(){return{next:function(){return{done:n=!0}}}},e(r)}catch{}return n},V2=xf,W2=q2,H2=Uu.CONSTRUCTOR,pP=H2||!W2(function(e){V2.all(e).then(void 0,function(){})}),G2=ci,z2=rr,Y2=fo,Q2=ya,J2=Ky,X2=dP,Z2=pP;G2({target:"Promise",stat:!0,forced:Z2},{all:function(t){var n=this,r=Q2.f(n),i=r.resolve,o=r.reject,a=J2(function(){var c=Y2(n.resolve),f=[],v=0,s=1;X2(t,function(g){var y=v++,S=!1;s++,z2(c,n,g).then(function(m){S||(S=!0,f[y]=m,--s||i(f))},o)}),--s||i(f)});return a.error&&o(a.value),r.promise}});var eK=ci,tK=Uu.CONSTRUCTOR,Pv=xf,nK=co,rK=Ot,iK=Nu,yw=Pv&&Pv.prototype;eK({target:"Promise",proto:!0,forced:tK,real:!0},{catch:function(e){return this.then(void 0,e)}});if(rK(Pv)){var _w=nK("Promise").prototype.catch;yw.catch!==_w&&iK(yw,"catch",_w,{unsafe:!0})}var oK=ci,sK=rr,aK=fo,lK=ya,uK=Ky,cK=dP,dK=pP;oK({target:"Promise",stat:!0,forced:dK},{race:function(t){var n=this,r=lK.f(n),i=r.reject,o=uK(function(){var a=aK(n.resolve);cK(t,function(c){sK(a,n,c).then(r.resolve,i)})});return o.error&&i(o.value),r.promise}});var fK=ci,hK=rr,pK=ya,gK=Uu.CONSTRUCTOR;fK({target:"Promise",stat:!0,forced:gK},{reject:function(t){var n=pK.f(this);return hK(n.reject,void 0,t),n.promise}});var vK=qr,mK=ts,yK=ya,_K=function(e,t){if(vK(e),mK(t)&&t.constructor===e)return t;var n=yK.f(e),r=n.resolve;return r(t),n.promise},SK=ci,EK=co,wK=Uu.CONSTRUCTOR,bK=_K;EK("Promise");SK({target:"Promise",stat:!0,forced:wK},{resolve:function(t){return bK(this,t)}});function TK(){return!!(typeof window<"u"&&window.document&&window.document.createElement)}const gP=TK(),dp={};function RK(e="$lodash$"){dp[e]||(dp[e]=0);const t=++dp[e];return e==="$lodash$"?`${t}`:`${e}${t}`}function IK(e,t){let n;return(...r)=>(clearTimeout(n),new Promise(i=>{n=setTimeout(()=>i(e(...r)),t)}))}function CK({debounceMs:e}){const[t,n]=Oe.useState(void 0);return Oe.useEffect(()=>{if(gP){const r=()=>{n(window.innerWidth)},i=IK(r,e);return window.addEventListener("resize",i),r(),()=>window.removeEventListener("resize",i)}return()=>{}},[e]),t}const OK=e=>{var{children:t,columns:n,gap:r}=e,i=xy(e,["children","columns","gap"]);return ia.jsx("div",Object.assign({style:{display:"grid",gridTemplateColumns:`repeat(${n}, 1fr)`,columnGap:r,alignItems:"start"}},i,{children:t}))},PK=e=>{var{children:t,gap:n}=e,r=xy(e,["children","gap"]);return ia.jsx("div",Object.assign({style:{display:"grid",gridTemplateColumns:"100%",rowGap:n}},r,{children:t}))},kK=e=>e[0],MK=e=>e[e.length-1],DK=e=>e.sort((t,n)=>t.size-n.size),AK=(e,t)=>e.filter(n=>n.size<=t),LK=(e,t)=>{const n=DK(e),r=AK(n,t),{columns:i}=r.length<1?kK(n):MK(r);return Array.from({length:i},o=>[])},NK=gP?Oe.useLayoutEffect:Oe.useEffect,xK=[{size:640,columns:1},{size:768,columns:2},{size:1024,columns:3},{size:1280,columns:4}],yG=e=>{var{children:t,gap:n="10px",debounce:r=200,breakpoints:i=xK}=e,o=xy(e,["children","gap","debounce","breakpoints"]);const a=CK({debounceMs:r}),[c,f]=Oe.useState([]);return NK(()=>{const v=LK(i,a||0);Oe.Children.forEach(t,(s,g)=>{const y=RK("plock-item-");if(Oe.isValidElement(s)){const S=Oe.cloneElement(s,Object.assign(Object.assign({},s.props),{key:y}));v[g%v.length].push(S)}}),f(v)},[t,i,a]),ia.jsx(OK,Object.assign({columns:c.length,gap:n},o,{children:c.map((v,s)=>ia.jsx(PK,Object.assign({gap:n,"data-testid":"masonry-column"},{children:v}),s))}))};var $K={},vP={},_a={},Ae={},UK={get exports(){return Ae},set exports(e){Ae=e}};(function(e){function t(n){return n&&n.__esModule?n:{default:n}}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports})(UK);const Ue=lf(fA);var qa={},Hd={},BK={get exports(){return Hd},set exports(e){Hd=e}},Sw;function FK(){return Sw||(Sw=1,function(e){(function(t,n){e.exports?e.exports=n():t.log=n()})($e,function(){var t=function(){},n="undefined",r=typeof window!==n&&typeof window.navigator!==n&&/Trident\/|MSIE /.test(window.navigator.userAgent),i=["trace","debug","info","warn","error"];function o(p,_){var u=p[_];if(typeof u.bind=="function")return u.bind(p);try{return Function.prototype.bind.call(u,p)}catch{return function(){return Function.prototype.apply.apply(u,[p,arguments])}}}function a(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function c(p){return p==="debug"&&(p="log"),typeof console===n?!1:p==="trace"&&r?a:console[p]!==void 0?o(console,p):console.log!==void 0?o(console,"log"):t}function f(p,_){for(var u=0;u<i.length;u++){var l=i[u];this[l]=u<p?t:this.methodFactory(l,p,_)}this.log=this.debug}function v(p,_,u){return function(){typeof console!==n&&(f.call(this,_,u),this[p].apply(this,arguments))}}function s(p,_,u){return c(p)||v.apply(this,arguments)}function g(p,_,u){var l=this,d;_=_??"WARN";var h="loglevel";typeof p=="string"?h+=":"+p:typeof p=="symbol"&&(h=void 0);function w(M){var L=(i[M]||"silent").toUpperCase();if(!(typeof window===n||!h)){try{window.localStorage[h]=L;return}catch{}try{window.document.cookie=encodeURIComponent(h)+"="+L+";"}catch{}}}function E(){var M;if(!(typeof window===n||!h)){try{M=window.localStorage[h]}catch{}if(typeof M===n)try{var L=window.document.cookie,B=L.indexOf(encodeURIComponent(h)+"=");B!==-1&&(M=/^([^;]+)/.exec(L.slice(B))[1])}catch{}return l.levels[M]===void 0&&(M=void 0),M}}function I(){if(!(typeof window===n||!h)){try{window.localStorage.removeItem(h);return}catch{}try{window.document.cookie=encodeURIComponent(h)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}l.name=p,l.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},l.methodFactory=u||s,l.getLevel=function(){return d},l.setLevel=function(M,L){if(typeof M=="string"&&l.levels[M.toUpperCase()]!==void 0&&(M=l.levels[M.toUpperCase()]),typeof M=="number"&&M>=0&&M<=l.levels.SILENT){if(d=M,L!==!1&&w(M),f.call(l,M,p),typeof console===n&&M<l.levels.SILENT)return"No console available for logging"}else throw"log.setLevel() called with invalid level: "+M},l.setDefaultLevel=function(M){_=M,E()||l.setLevel(M,!1)},l.resetLevel=function(){l.setLevel(_,!1),I()},l.enableAll=function(M){l.setLevel(l.levels.TRACE,M)},l.disableAll=function(M){l.setLevel(l.levels.SILENT,M)};var k=E();k==null&&(k=_),l.setLevel(k,!1)}var y=new g,S={};y.getLogger=function(_){if(typeof _!="symbol"&&typeof _!="string"||_==="")throw new TypeError("You must supply a name when creating a logger.");var u=S[_];return u||(u=S[_]=new g(_,y.getLevel(),y.methodFactory)),u};var m=typeof window!==n?window.log:void 0;return y.noConflict=function(){return typeof window!==n&&window.log===y&&(window.log=m),y},y.getLoggers=function(){return S},y.default=y,y})}(BK)),Hd}var Ew;function Ge(){if(Ew)return qa;Ew=1;var e=Ae;Object.defineProperty(qa,"__esModule",{value:!0}),qa.logger=void 0;var t=e(FK());const n="matrix";t.default.methodFactory=function(a,c,f){return function(...v){return this.prefix&&v.unshift(this.prefix),a==="error"||a==="warn"||a==="trace"||a==="info"?console[a](...v):console.log(...v)}};const r=t.default.getLogger(n);qa.logger=r,r.setLevel(t.default.levels.DEBUG,!1);function i(a){a.withPrefix=function(c){const f=this.prefix||"";return o(f+c)}}i(r);function o(a){const c=t.default.getLogger(`${n}-${a}`);return c.prefix!==a&&(i(c),c.prefix=a,c.setLevel(t.default.levels.DEBUG,!1)),c}return qa}var Je={};const KK="l",jK="rn",qK={0:"O",1:"l","֭":"֖","֮":"֘","֨":"֙","֤":"֚","᪴":"ۛ","⃛":"ۛ","ؙ":"̓","ࣳ":"̓","̓":"̓","̕":"̓","ُ":"̓","ٝ":"̔","֜":"́","֝":"́","ؘ":"́","݇":"́","́":"́","॔":"́","َ":"́","̀":"̀","॓":"̀","̌":"̆","꙼":"̆","٘":"̆","ٚ":"̆","ͮ":"̆","ۨ":"̆̇","̐":"̆̇","ँ":"̆̇","ঁ":"̆̇","ઁ":"̆̇","ଁ":"̆̇","ఀ":"̆̇","ಁ":"̆̇","ഁ":"̆̇","𑒿":"̆̇","᳐":"̂","̑":"̂","ٛ":"̂","߮":"̂","꛰":"̂","֯":"̊","۟":"̊","៓":"̊","゚":"̊","ْ":"̊","ஂ":"̊","ံ":"̊","ំ":"̊","𑌀":"̊","ํ":"̊","ໍ":"̊","ͦ":"̊","ⷪ":"̊","࣫":"̈","߳":"̈","ً":"̋","ࣰ":"̋","͂":"̃","ٓ":"̃","ׄ":"̇","۬":"̇","݀":"̇","࣪":"̇","݁":"̇","͘":"̇","ֹ":"̇","ֺ":"̇","ׂ":"̇","ׁ":"̇","߭":"̇","ं":"̇","ਂ":"̇","ં":"̇","்":"̇","̷":"̸","᪷":"̨","̢":"̨","ͅ":"̨","᳒":"̄","̅":"̄","ٙ":"̄","߫":"̄","꛱":"̄","᳚":"̎","ٗ":"̒","͗":"͐","ࣿ":"͐","ࣸ":"͐","ऀ":"͒","᳭":"̖","᳜":"̩","ٖ":"̩","᳕":"̫","͇":"̳","ࣹ":"͔","ࣺ":"͕","゛":"゙","゜":"゚","̶":"̵","〬":"̉","ׅ":"̣","࣭":"̣","᳝":"̣","ִ":"̣","ٜ":"̣","़":"̣","়":"̣","਼":"̣","઼":"̣","଼":"̣","𑇊":"̣","𑓃":"̣","𐨺":"̣","࣮":"̤","᳞":"̤","༷":"̥","〭":"̥","̧":"̦","̡":"̦","̹":"̦","᳙":"̭","᳘":"̮","॒":"̱","̠":"̱","ࣱ":"ٌ","ࣨ":"ٌ","ࣥ":"ٌ",ﱞ:"ﹲّ","ࣲ":"ٍ",ﱟ:"ﹴّ",ﳲ:"ﹷّ",ﱠ:"ﹶّ",ﳳ:"ﹹّ",ﱡ:"ﹸّ","ؚ":"ِ","̗":"ِ",ﳴ:"ﹻّ",ﱢ:"ﹺّ",ﱣ:"ﹼٰ","ٟ":"ٕ","̍":"ٰ","݂":"ܼ","ਃ":"ঃ","ః":"ঃ","ಃ":"ঃ","ഃ":"ঃ","ඃ":"ঃ","း":"ঃ","𑓁":"ঃ","់":"่","່":"่","້":"้","໊":"๊","໋":"๋","꙯":"⃩","\u2028":" ","\u2029":" "," ":" "," ":" "," ":" "," ":" "," ":" "," ":" "," ":" "," ":" "," ":" "," ":" "," ":" "," ":" "," ":" "," ":" "," ":" ","ߺ":"_","﹍":"_","﹎":"_","﹏":"_","‐":"-","‑":"-","‒":"-","–":"-","﹘":"-","۔":"-","⁃":"-","˗":"-","−":"-","➖":"-","Ⲻ":"-","⨩":"-̓","⸚":"-̈","﬩":"-̇","∸":"-̇","⨪":"-̣","꓾":"-.","~":"〜","؍":",","٫":",","‚":",","¸":",","ꓹ":",","⸲":"،","٬":"،",";":";","⸵":"؛","ः":":","ઃ":":",":":":","։":":","܃":":","܄":":","᛬":":","︰":":","᠃":":","᠉":":","⁚":":","׃":":","˸":":","꞉":":","∶":":",ː:":","ꓽ":":","⩴":"::=","⧴":":→","!":"!",ǃ:"!","ⵑ":"!","‼":"!!","⁉":"!?",ʔ:"?","Ɂ":"?","ॽ":"?",Ꭾ:"?","ꛫ":"?","⁈":"?!","⁇":"??","⸮":"؟","𝅭":".","․":".","܁":".","܂":".","꘎":".","𐩐":".","٠":".","۰":".","ꓸ":".","ꓻ":".,","‥":"..","ꓺ":"..","…":"...","꛴":"꛳꛳","・":"·","・":"·","᛫":"·","·":"·","⸱":"·","𐄁":"·","•":"·","‧":"·","∙":"·","⋅":"·","ꞏ":"·",ᐧ:"·","⋯":"···","ⵈ":"···",ᑄ:"·<","⋗":"·>",ᐷ:"·>",ᑀ:"·>",ᔯ:"·4",ᑾ:"·b",ᒀ:"·ḃ",ᑺ:"·d",ᒘ:"·J",ᒶ:"·L",ᑶ:"·P",ᑗ:"·U",ᐺ:"·V",ᐼ:"·Ʌ",ᒮ:"·Γ",ᐎ:"·Δ",ᑙ:"·Ո",ᐌ:"·ᐁ",ᐐ:"·ᐄ",ᐒ:"·ᐅ",ᐔ:"·ᐆ",ᐗ:"·ᐊ",ᐙ:"·ᐋ",ᐾ:"·ᐲ",ᑂ:"·ᐴ",ᑆ:"·ᐹ",ᑛ:"·ᑏ",ᑔ:"·ᑐ",ᑝ:"·ᑐ",ᑟ:"·ᑑ",ᑡ:"·ᑕ",ᑣ:"·ᑖ",ᑴ:"·ᑫ",ᑸ:"·ᑮ",ᑼ:"·ᑰ",ᒒ:"·ᒉ",ᒔ:"·ᒋ",ᒖ:"·ᒌ",ᒚ:"·ᒎ",ᒜ:"·ᒐ",ᒞ:"·ᒑ",ᒬ:"·ᒣ",ᒰ:"·ᒦ",ᒲ:"·ᒧ",ᒴ:"·ᒨ",ᒸ:"·ᒫ",ᓉ:"·ᓀ","ᣆ":"·ᓂ","ᣈ":"·ᓃ","ᣊ":"·ᓄ","ᣌ":"·ᓅ",ᓋ:"·ᓇ",ᓍ:"·ᓈ",ᓜ:"·ᓓ",ᓞ:"·ᓕ",ᓠ:"·ᓖ",ᓢ:"·ᓗ",ᓤ:"·ᓘ",ᓦ:"·ᓚ",ᓨ:"·ᓛ",ᓶ:"·ᓭ",ᓸ:"·ᓯ",ᓺ:"·ᓰ",ᓼ:"·ᓱ",ᓾ:"·ᓲ",ᔀ:"·ᓴ",ᔂ:"·ᓵ",ᔗ:"·ᔐ",ᔙ:"·ᔑ",ᔛ:"·ᔒ",ᔝ:"·ᔓ",ᔟ:"·ᔔ",ᔡ:"·ᔕ",ᔣ:"·ᔖ",ᔱ:"·ᔨ",ᔳ:"·ᔩ",ᔵ:"·ᔪ",ᔷ:"·ᔫ",ᔹ:"·ᔭ",ᔻ:"·ᔮ","ᣎ":"·ᕃ","ᣏ":"·ᕆ","ᣐ":"·ᕇ","ᣑ":"·ᕈ","ᣒ":"·ᕉ","ᣓ":"·ᕋ",ᕎ:"·ᕌ",ᕛ:"·ᕚ",ᕨ:"·ᕧ","ᢳ":"·ᢱ","ᢶ":"·ᢴ","ᢹ":"·ᢸ","ᣂ":"·ᣀ","꠰":"।","॥":"।।","᰼":"᰻᰻","။":"၊၊","᪩":"᪨᪨","᪫":"᪪᪨","᭟":"᭞᭞","𐩗":"𐩖𐩖","𑑌":"𑑋𑑋","𑙂":"𑙁𑙁","𑱂":"𑱁𑱁","᱿":"᱾᱾","՝":"'","'":"'","‘":"'","’":"'","‛":"'","′":"'","‵":"'","՚":"'","׳":"'","`":"'","`":"'","`":"'","´":"'","΄":"'","´":"'","᾽":"'","᾿":"'","῾":"'","ʹ":"'","ʹ":"'","ˈ":"'","ˊ":"'","ˋ":"'","˴":"'",ʻ:"'",ʽ:"'",ʼ:"'",ʾ:"'","ꞌ":"'",י:"'","ߴ":"'","ߵ":"'",ᑊ:"'",ᛌ:"'","𖽑":"'","𖽒":"'","᳓":"''",'"':"''",""":"''","“":"''","”":"''","‟":"''","″":"''","‶":"''","〃":"''","״":"''","˝":"''","ʺ":"''","˶":"''",ˮ:"''",ײ:"''","‴":"'''","‷":"'''","⁗":"''''",Ɓ:"'B",Ɗ:"'D",ʼn:"'n",Ƥ:"'P",Ƭ:"'T",Ƴ:"'Y","[":"(","❨":"(","❲":"(","〔":"(","﴾":"(","⸨":"((","㈠":"(ー)","⑵":"(2)","⒇":"(2O)","⑶":"(3)","⑷":"(4)","⑸":"(5)","⑹":"(6)","⑺":"(7)","⑻":"(8)","⑼":"(9)","⒜":"(a)","🄐":"(A)","⒝":"(b)","🄑":"(B)","⒞":"(c)","🄒":"(C)","⒟":"(d)","🄓":"(D)","⒠":"(e)","🄔":"(E)","⒡":"(f)","🄕":"(F)","⒢":"(g)","🄖":"(G)","⒣":"(h)","🄗":"(H)","⒤":"(i)","⒥":"(j)","🄙":"(J)","⒦":"(k)","🄚":"(K)","⑴":"(l)","🄘":"(l)","⒧":"(l)","🄛":"(L)","⑿":"(l2)","⒀":"(l3)","⒁":"(l4)","⒂":"(l5)","⒃":"(l6)","⒄":"(l7)","⒅":"(l8)","⒆":"(l9)","⑾":"(ll)","⑽":"(lO)","🄜":"(M)","⒩":"(n)","🄝":"(N)","⒪":"(o)","🄞":"(O)","⒫":"(p)","🄟":"(P)","⒬":"(q)","🄠":"(Q)","⒭":"(r)","🄡":"(R)","⒨":"(rn)","⒮":"(s)","🄢":"(S)","🄪":"(S)","⒯":"(t)","🄣":"(T)","⒰":"(u)","🄤":"(U)","⒱":"(v)","🄥":"(V)","⒲":"(w)","🄦":"(W)","⒳":"(x)","🄧":"(X)","⒴":"(y)","🄨":"(Y)","⒵":"(z)","🄩":"(Z)","㈀":"(ᄀ)","㈎":"(가)","㈁":"(ᄂ)","㈏":"(나)","㈂":"(ᄃ)","㈐":"(다)","㈃":"(ᄅ)","㈑":"(라)","㈄":"(ᄆ)","㈒":"(마)","㈅":"(ᄇ)","㈓":"(바)","㈆":"(ᄉ)","㈔":"(사)","㈇":"(ᄋ)","㈕":"(아)","㈝":"(오전)","㈞":"(오후)","㈈":"(ᄌ)","㈖":"(자)","㈜":"(주)","㈉":"(ᄎ)","㈗":"(차)","㈊":"(ᄏ)","㈘":"(카)","㈋":"(ᄐ)","㈙":"(타)","㈌":"(ᄑ)","㈚":"(파)","㈍":"(ᄒ)","㈛":"(하)","㈦":"(七)","㈢":"(三)","🉁":"(三)","㈨":"(九)","㈡":"(二)","🉂":"(二)","㈤":"(五)","㈹":"(代)","㈽":"(企)","㉁":"(休)","㈧":"(八)","㈥":"(六)","㈸":"(労)","🉇":"(勝)","㈩":"(十)","㈿":"(協)","㈴":"(名)","㈺":"(呼)","㈣":"(四)","㈯":"(土)","㈻":"(学)","🉃":"(安)","🉅":"(打)","🉈":"(敗)","㈰":"(日)","㈪":"(月)","㈲":"(有)","㈭":"(木)","🉀":"(本)","㈱":"(株)","㈬":"(水)","㈫":"(火)","🉄":"(点)","㈵":"(特)","🉆":"(盗)","㈼":"(監)","㈳":"(社)","㈷":"(祝)","㉀":"(祭)","㉂":"(自)","㉃":"(至)","㈶":"(財)","㈾":"(資)","㈮":"(金)","]":")","❩":")","❳":")","〕":")","﴿":")","⸩":"))","❴":"{","𝄔":"{","❵":"}","〚":"⟦","〛":"⟧","⟨":"❬","〈":"❬","〈":"❬","㇛":"❬",く:"❬","𡿨":"❬","⟩":"❭","〉":"❭","〉":"❭","^":"︿","⸿":"¶","⁎":"*","٭":"*","∗":"*","𐌟":"*","᜵":"/","⁁":"/","∕":"/","⁄":"/","╱":"/","⟋":"/","⧸":"/","𝈺":"/","㇓":"/",〳:"/","Ⳇ":"/",ノ:"/",丿:"/","⼃":"/","⧶":"/̄","⫽":"//","⫻":"///","\":"\\","﹨":"\\","∖":"\\","⟍":"\\","⧵":"\\","⧹":"\\","𝈏":"\\","𝈻":"\\","㇔":"\\",丶:"\\","⼂":"\\","⳹":"\\\\","⑊":"\\\\","⟈":"\\ᑕ","ꝸ":"&","૰":"॰","𑂻":"॰","𑇇":"॰","⚬":"॰","𑇛":"꣼","៙":"๏","៕":"๚","៚":"๛","༌":"་","༎":"།།","˄":"^","ˆ":"^","꙾":"ˇ","˘":"ˇ","‾":"ˉ","﹉":"ˉ","﹊":"ˉ","﹋":"ˉ","﹌":"ˉ","¯":"ˉ"," ̄":"ˉ","▔":"ˉ",ъ:"ˉb","ꙑ":"ˉbi","͵":"ˏ","˻":"˪","꜖":"˪","꜔":"˫","。":"˳","⸰":"°","˚":"°","∘":"°","○":"°","◦":"°","⍜":"°̲","⍤":"°̈","℃":"°C","℉":"°F","௵":"௳","༛":"༚༚","༟":"༚༝","࿎":"༝༚","༞":"༝༝","Ⓒ":"©","Ⓡ":"®","Ⓟ":"℗","𝈛":"⅄","⯬":"↞","⯭":"↟","⯮":"↠","⯯":"↡","↵":"↲","⥥":"⇃⇂","⥯":"⇃ᛚ","𝛛":"∂","𝜕":"∂","𝝏":"∂","𝞉":"∂","𝟃":"∂","𞣌":"∂","𞣍":"∂̵",ð:"∂̵","⌀":"∅","𝛁":"∇","𝛻":"∇","𝜵":"∇","𝝯":"∇","𝞩":"∇","𑢨":"∇","⍢":"∇̈","⍫":"∇̴","█":"∎","■":"∎","⨿":"∐","᛭":"+","➕":"+","𐊛":"+","⨣":"+̂","⨢":"+̊","⨤":"+̃","∔":"+̇","⨥":"+̣","⨦":"+̰","⨧":"+₂","➗":"÷","‹":"<","❮":"<","˂":"<","𝈶":"<",ᐸ:"<",ᚲ:"<","⋖":"<·","Ⲵ":"<·",ᑅ:"<·","≪":"<<","⋘":"<<<","᐀":"=","⹀":"=","゠":"=","꓿":"=","≚":"=̆","≙":"=̂","≗":"=̊","≐":"=̇","≑":"=̣̇","⩮":"=⃰","⩵":"==","⩶":"===","≞":"=ͫ","›":">","❯":">","˃":">","𝈷":">",ᐳ:">","𖼿":">",ᑁ:">·","⪥":"><","≫":">>","⨠":">>","⋙":">>>","⁓":"~","˜":"~","῀":"~","∼":"~","⍨":"~̈","⸞":"~̇","⩪":"~̇","⸟":"~̣","𞣈":"∠","⋀":"∧","∯":"∮∮","∰":"∮∮∮","⸫":"∴","⸪":"∵","⸬":"∷","𑇞":"≈","♎":"≏","🝞":"≏","≣":"≡","⨃":"⊍","⨄":"⊎","𝈸":"⊏","𝈹":"⊐","⨅":"⊓","⨆":"⊔","⨂":"⊗","⍟":"⊛","🝱":"⊠","🝕":"⊡","◁":"⊲","▷":"⊳","⍣":"⋆̈","︴":"⌇","◠":"⌒","⨽":"⌙","⌥":"⌤","⧇":"⌻","◎":"⌾","⦾":"⌾","⧅":"⍂","⦰":"⍉","⏃":"⍋","⏂":"⍎","⏁":"⍕","⏆":"⍭","☸":"⎈","︵":"⏜","︶":"⏝","︷":"⏞","︸":"⏟","︹":"⏠","︺":"⏡","▱":"⏥","⏼":"⏻","︱":"│","|":"│","┃":"│","┏":"┌","┣":"├","▐":"▌","▗":"▖","▝":"▘","☐":"□","■":"▪","▸":"▶","►":"▶","⳩":"☧","🜊":"☩","🌒":"☽","🌙":"☽","⏾":"☾","🌘":"☾","⧙":"⦚","🜺":"⧟","⨾":"⨟","𐆠":"⳨","♩":"𝅘𝅥","♪":"𝅘𝅥𝅮","⓪":"🄍","↺":"🄎","˙":"ॱ","ൎ":"ॱ","-":"ー","—":"ー","―":"ー","─":"ー","━":"ー","㇐":"ー","ꟷ":"ー",ᅳ:"ー",ㅡ:"ー",一:"ー","⼀":"ー",ᆖ:"ーー","ힹ":"ーᅡ","ힺ":"ーᅥ","ힻ":"ーᅥ丨","ힼ":"ーᅩ",ᆕ:"ーᅮ",ᅴ:"ー丨",ㅢ:"ー丨",ᆗ:"ー丨ᅮ","🄏":"$⃠","₤":"£","〒":"₸","〶":"₸","᭜":"᭐","꧆":"꧐","𑓑":"১","೧":"౧","ၥ":"၁","①":"➀","⑩":"➉","⏨":"₁₀","𝟐":"2","𝟚":"2","𝟤":"2","𝟮":"2","𝟸":"2","🯲":"2","Ꝛ":"2",Ƨ:"2",Ϩ:"2","Ꙅ":"2",ᒿ:"2","ꛯ":"2","ꧏ":"٢","۲":"٢","૨":"२","𑓒":"২","೨":"౨","②":"➁",ƻ:"2̵","🄃":"2,","⒉":"2.","㏵":"22日","㍮":"22点","㏶":"23日","㍯":"23点","㏷":"24日","㍰":"24点","㏸":"25日","㏹":"26日","㏺":"27日","㏻":"28日","㏼":"29日","㏴":"2l日","㍭":"2l点","⒛":"2O.","㏳":"2O日","㍬":"2O点","෩":"෨ා","෯":"෨ී","㏡":"2日","㋁":"2月","㍚":"2点","𝈆":"3","𝟑":"3","𝟛":"3","𝟥":"3","𝟯":"3","𝟹":"3","🯳":"3","Ɜ":"3",Ȝ:"3",Ʒ:"3","Ꝫ":"3","Ⳍ":"3",З:"3",Ӡ:"3","𖼻":"3","𑣊":"3","۳":"٣","𞣉":"٣","૩":"३","③":"➂",Ҙ:"3̦","🄄":"3,","⒊":"3.","㏾":"3l日","㏽":"3O日","㏢":"3日","㋂":"3月","㍛":"3点","𝟒":"4","𝟜":"4","𝟦":"4","𝟰":"4","𝟺":"4","🯴":"4",Ꮞ:"4","𑢯":"4","۴":"٤","૪":"४","④":"➃","🄅":"4,","⒋":"4.",ᔰ:"4·","㏣":"4日","㋃":"4月","㍜":"4点","𝟓":"5","𝟝":"5","𝟧":"5","𝟱":"5","𝟻":"5","🯵":"5",Ƽ:"5","𑢻":"5","⑤":"➄","🄆":"5,","⒌":"5.","㏤":"5日","㋄":"5月","㍝":"5点","𝟔":"6","𝟞":"6","𝟨":"6","𝟲":"6","𝟼":"6","🯶":"6","Ⳓ":"6",б:"6",Ꮾ:"6","𑣕":"6","۶":"٦","𑓖":"৬","⑥":"➅","🄇":"6,","⒍":"6.","㏥":"6日","㋅":"6月","㍞":"6点","𝈒":"7","𝟕":"7","𝟟":"7","𝟩":"7","𝟳":"7","𝟽":"7","🯷":"7","𐓒":"7","𑣆":"7","⑦":"➆","🄈":"7,","⒎":"7.","㏦":"7日","㋆":"7月","㍟":"7点","ଃ":"8","৪":"8","੪":"8","𞣋":"8","𝟖":"8","𝟠":"8","𝟪":"8","𝟴":"8","𝟾":"8","🯸":"8",ȣ:"8",Ȣ:"8","𐌚":"8","૮":"८","⑧":"➇","🄉":"8,","⒏":"8.","㏧":"8日","㋇":"8月","㍠":"8点","੧":"9","୨":"9","৭":"9","൭":"9","𝟗":"9","𝟡":"9","𝟫":"9","𝟵":"9","𝟿":"9","🯹":"9","Ꝯ":"9","Ⳋ":"9","𑣌":"9","𑢬":"9","𑣖":"9","१":"٩","𑣤":"٩","۹":"٩","೯":"౯","⑨":"➈","🄊":"9,","⒐":"9.","㏨":"9日","㋈":"9月","㍡":"9点","⍺":"a",a:"a","𝐚":"a","𝑎":"a","𝒂":"a","𝒶":"a","𝓪":"a","𝔞":"a","𝕒":"a","𝖆":"a","𝖺":"a","𝗮":"a","𝘢":"a","𝙖":"a","𝚊":"a",ɑ:"a",α:"a","𝛂":"a","𝛼":"a","𝜶":"a","𝝰":"a","𝞪":"a",а:"a","ⷶ":"ͣ",A:"A","𝐀":"A","𝐴":"A","𝑨":"A","𝒜":"A","𝓐":"A","𝔄":"A","𝔸":"A","𝕬":"A","𝖠":"A","𝗔":"A","𝘈":"A","𝘼":"A","𝙰":"A",Α:"A","𝚨":"A","𝛢":"A","𝜜":"A","𝝖":"A","𝞐":"A",А:"A",Ꭺ:"A",ᗅ:"A","ꓮ":"A","𖽀":"A","𐊠":"A","⍶":"a̲",ǎ:"ă",Ǎ:"Ă",ȧ:"å",Ȧ:"Å",ẚ:"ả","℀":"a/c","℁":"a/s","ꜳ":"aa","Ꜳ":"AA",æ:"ae",ӕ:"ae",Æ:"AE",Ӕ:"AE","ꜵ":"ao","Ꜵ":"AO","🜇":"AR","ꜷ":"au","Ꜷ":"AU","ꜹ":"av","ꜻ":"av","Ꜹ":"AV","Ꜻ":"AV","ꜽ":"ay","Ꜽ":"AY","ꭺ":"ᴀ","∀":"Ɐ","𝈗":"Ɐ",ᗄ:"Ɐ","ꓯ":"Ɐ","𐐟":"Ɒ","𝐛":"b","𝑏":"b","𝒃":"b","𝒷":"b","𝓫":"b","𝔟":"b","𝕓":"b","𝖇":"b","𝖻":"b","𝗯":"b","𝘣":"b","𝙗":"b","𝚋":"b",Ƅ:"b",Ь:"b",Ꮟ:"b",ᑲ:"b",ᖯ:"b",B:"B",ℬ:"B","𝐁":"B","𝐵":"B","𝑩":"B","𝓑":"B","𝔅":"B","𝔹":"B","𝕭":"B","𝖡":"B","𝗕":"B","𝘉":"B","𝘽":"B","𝙱":"B","Ꞵ":"B",Β:"B","𝚩":"B","𝛣":"B","𝜝":"B","𝝗":"B","𝞑":"B",В:"B",Ᏼ:"B",ᗷ:"B","ꓐ":"B","𐊂":"B","𐊡":"B","𐌁":"B",ɓ:"b̔",ᑳ:"ḃ",ƃ:"b̄",Ƃ:"b̄",Б:"b̄",ƀ:"b̵",ҍ:"b̵",Ҍ:"b̵",ѣ:"b̵",Ѣ:"b̵",ᑿ:"b·",ᒁ:"ḃ·",ᒈ:"b'",Ы:"bl",в:"ʙ","ᏼ":"ʙ",c:"c","ⅽ":"c","𝐜":"c","𝑐":"c","𝒄":"c","𝒸":"c","𝓬":"c","𝔠":"c","𝕔":"c","𝖈":"c","𝖼":"c","𝗰":"c","𝘤":"c","𝙘":"c","𝚌":"c","ᴄ":"c",ϲ:"c","ⲥ":"c",с:"c","ꮯ":"c","𐐽":"c","ⷭ":"ͨ","🝌":"C","𑣲":"C","𑣩":"C",C:"C","Ⅽ":"C",ℂ:"C",ℭ:"C","𝐂":"C","𝐶":"C","𝑪":"C","𝒞":"C","𝓒":"C","𝕮":"C","𝖢":"C","𝗖":"C","𝘊":"C","𝘾":"C","𝙲":"C","Ϲ":"C","Ⲥ":"C",С:"C",Ꮯ:"C","ꓚ":"C","𐊢":"C","𐌂":"C","𐐕":"C","𐔜":"C","¢":"c̸","ȼ":"c̸","₡":"C⃫","🅮":"C⃠",ç:"c̦",ҫ:"c̦",Ç:"C̦",Ҫ:"C̦",Ƈ:"C'","℅":"c/o","℆":"c/u","🅭":"㏄	⃝","⋴":"ꞓ",ɛ:"ꞓ",ε:"ꞓ","ϵ":"ꞓ","𝛆":"ꞓ","𝛜":"ꞓ","𝜀":"ꞓ","𝜖":"ꞓ","𝜺":"ꞓ","𝝐":"ꞓ","𝝴":"ꞓ","𝞊":"ꞓ","𝞮":"ꞓ","𝟄":"ꞓ","ⲉ":"ꞓ",є:"ꞓ","ԑ":"ꞓ","ꮛ":"ꞓ","𑣎":"ꞓ","𐐩":"ꞓ","€":"Ꞓ","Ⲉ":"Ꞓ",Є:"Ꞓ","⍷":"ꞓ̲","ͽ":"ꜿ","Ͽ":"Ꜿ","ⅾ":"d","ⅆ":"d","𝐝":"d","𝑑":"d","𝒅":"d","𝒹":"d","𝓭":"d","𝔡":"d","𝕕":"d","𝖉":"d","𝖽":"d","𝗱":"d","𝘥":"d","𝙙":"d","𝚍":"d","ԁ":"d",Ꮷ:"d",ᑯ:"d","ꓒ":"d","Ⅾ":"D","ⅅ":"D","𝐃":"D","𝐷":"D","𝑫":"D","𝒟":"D","𝓓":"D","𝔇":"D","𝔻":"D","𝕯":"D","𝖣":"D","𝗗":"D","𝘋":"D","𝘿":"D","𝙳":"D",Ꭰ:"D",ᗞ:"D",ᗪ:"D","ꓓ":"D",ɗ:"d̔",ɖ:"d̨",ƌ:"d̄",đ:"d̵",Đ:"D̵",Ð:"D̵",Ɖ:"D̵","₫":"ḏ̵","ꝺ":"Ꝺ",ᑻ:"d·",ᒇ:"d'",ʤ:"dȝ",dz:"dz",ʣ:"dz",Dz:"Dz",DZ:"DZ",dž:"dž",Dž:"Dž",DŽ:"DŽ",ʥ:"dʑ","ꭰ":"ᴅ","⸹":"ẟ",δ:"ẟ","𝛅":"ẟ","𝛿":"ẟ","𝜹":"ẟ","𝝳":"ẟ","𝞭":"ẟ",ծ:"ẟ",ᕷ:"ẟ","℮":"e",e:"e",ℯ:"e","ⅇ":"e","𝐞":"e","𝑒":"e","𝒆":"e","𝓮":"e","𝔢":"e","𝕖":"e","𝖊":"e","𝖾":"e","𝗲":"e","𝘦":"e","𝙚":"e","𝚎":"e","ꬲ":"e",е:"e",ҽ:"e","ⷷ":"ͤ","⋿":"E",E:"E",ℰ:"E","𝐄":"E","𝐸":"E","𝑬":"E","𝓔":"E","𝔈":"E","𝔼":"E","𝕰":"E","𝖤":"E","𝗘":"E","𝘌":"E","𝙀":"E","𝙴":"E",Ε:"E","𝚬":"E","𝛦":"E","𝜠":"E","𝝚":"E","𝞔":"E",Е:"E","ⴹ":"E",Ꭼ:"E","ꓰ":"E","𑢦":"E","𑢮":"E","𐊆":"E",ě:"ĕ",Ě:"Ĕ","ɇ":"e̸","Ɇ":"E̸",ҿ:"ę","ꭼ":"ᴇ",ə:"ǝ",ә:"ǝ","∃":"Ǝ","ⴺ":"Ǝ","ꓱ":"Ǝ",ɚ:"ǝ˞","ᴔ":"ǝo","ꭁ":"ǝo̸","ꭂ":"ǝo̵",Ә:"Ə","𝈡":"Ɛ",ℇ:"Ɛ","Ԑ":"Ɛ",Ꮛ:"Ɛ","𖼭":"Ɛ","𐐁":"Ɛ","ᶟ":"ᵋ","ᴈ":"ɜ",з:"ɜ",ҙ:"ɜ̦","𐑂":"ɞ","ꞝ":"ʚ","𐐪":"ʚ","𝐟":"f","𝑓":"f","𝒇":"f","𝒻":"f","𝓯":"f","𝔣":"f","𝕗":"f","𝖋":"f","𝖿":"f","𝗳":"f","𝘧":"f","𝙛":"f","𝚏":"f","ꬵ":"f","ꞙ":"f",ſ:"f","ẝ":"f",ք:"f","𝈓":"F",ℱ:"F","𝐅":"F","𝐹":"F","𝑭":"F","𝓕":"F","𝔉":"F","𝔽":"F","𝕱":"F","𝖥":"F","𝗙":"F","𝘍":"F","𝙁":"F","𝙵":"F","Ꞙ":"F",Ϝ:"F","𝟊":"F",ᖴ:"F","ꓝ":"F","𑣂":"F","𑢢":"F","𐊇":"F","𐊥":"F","𐔥":"F",ƒ:"f̦",Ƒ:"F̦","ᵮ":"f̴","℻":"FAX",ff:"ff",ffi:"ffi",ffl:"ffl",fi:"fi",fl:"fl",ʩ:"fŋ",ᖵ:"Ⅎ","ꓞ":"Ⅎ","𝈰":"ꟻ",ᖷ:"ꟻ",g:"g",ℊ:"g","𝐠":"g","𝑔":"g","𝒈":"g","𝓰":"g","𝔤":"g","𝕘":"g","𝖌":"g","𝗀":"g","𝗴":"g","𝘨":"g","𝙜":"g","𝚐":"g",ɡ:"g","ᶃ":"g",ƍ:"g",ց:"g","𝐆":"G","𝐺":"G","𝑮":"G","𝒢":"G","𝓖":"G","𝔊":"G","𝔾":"G","𝕲":"G","𝖦":"G","𝗚":"G","𝘎":"G","𝙂":"G","𝙶":"G","Ԍ":"G",Ꮐ:"G",Ᏻ:"G","ꓖ":"G","ᶢ":"ᵍ",ɠ:"g̔",ǧ:"ğ",Ǧ:"Ğ",ǵ:"ģ",ǥ:"g̵",Ǥ:"G̵",Ɠ:"G'","ԍ":"ɢ","ꮐ":"ɢ","ᏻ":"ɢ",h:"h",ℎ:"h","𝐡":"h","𝒉":"h","𝒽":"h","𝓱":"h","𝔥":"h","𝕙":"h","𝖍":"h","𝗁":"h","𝗵":"h","𝘩":"h","𝙝":"h","𝚑":"h",һ:"h",հ:"h",Ꮒ:"h",H:"H",ℋ:"H",ℌ:"H",ℍ:"H","𝐇":"H","𝐻":"H","𝑯":"H","𝓗":"H","𝕳":"H","𝖧":"H","𝗛":"H","𝘏":"H","𝙃":"H","𝙷":"H",Η:"H","𝚮":"H","𝛨":"H","𝜢":"H","𝝜":"H","𝞖":"H","Ⲏ":"H",Н:"H",Ꮋ:"H",ᕼ:"H","ꓧ":"H","𐋏":"H","ᵸ":"ᴴ",ɦ:"h̔","ꚕ":"h̔",Ᏺ:"h̔","Ⱨ":"H̩",Ң:"H̩",ħ:"h̵",ℏ:"h̵",ћ:"h̵",Ħ:"H̵","Ӊ":"H̦",Ӈ:"H̦",н:"ʜ","ꮋ":"ʜ",ң:"ʜ̩","ӊ":"ʜ̦",ӈ:"ʜ̦","Ԋ":"Ƕ","ꮀ":"ⱶ","Ͱ":"Ⱶ",Ꭸ:"Ⱶ",Ꮀ:"Ⱶ","ꚱ":"Ⱶ","ꞕ":"ꜧ","˛":"i","⍳":"i",i:"i","ⅰ":"i",ℹ:"i","ⅈ":"i","𝐢":"i","𝑖":"i","𝒊":"i","𝒾":"i","𝓲":"i","𝔦":"i","𝕚":"i","𝖎":"i","𝗂":"i","𝗶":"i","𝘪":"i","𝙞":"i","𝚒":"i",ı:"i","𝚤":"i",ɪ:"i",ɩ:"i",ι:"i",ι:"i",ͺ:"i","𝛊":"i","𝜄":"i","𝜾":"i","𝝸":"i","𝞲":"i",і:"i","ꙇ":"i","ӏ":"i","ꭵ":"i",Ꭵ:"i","𑣃":"i","ⓛ":"Ⓘ","⍸":"i̲",ǐ:"ĭ",Ǐ:"Ĭ",ɨ:"i̵","ᵻ":"i̵","ᵼ":"i̵","ⅱ":"ii","ⅲ":"iii",ij:"ij","ⅳ":"iv","ⅸ":"ix",j:"j","ⅉ":"j","𝐣":"j","𝑗":"j","𝒋":"j","𝒿":"j","𝓳":"j","𝔧":"j","𝕛":"j","𝖏":"j","𝗃":"j","𝗷":"j","𝘫":"j","𝙟":"j","𝚓":"j",ϳ:"j",ј:"j",J:"J","𝐉":"J","𝐽":"J","𝑱":"J","𝒥":"J","𝓙":"J","𝔍":"J","𝕁":"J","𝕵":"J","𝖩":"J","𝗝":"J","𝘑":"J","𝙅":"J","𝙹":"J","Ʝ":"J","Ϳ":"J",Ј:"J",Ꭻ:"J",ᒍ:"J","ꓙ":"J","ɉ":"j̵","Ɉ":"J̵",ᒙ:"J·","𝚥":"ȷ",յ:"ȷ","ꭻ":"ᴊ","𝐤":"k","𝑘":"k","𝒌":"k","𝓀":"k","𝓴":"k","𝔨":"k","𝕜":"k","𝖐":"k","𝗄":"k","𝗸":"k","𝘬":"k","𝙠":"k","𝚔":"k",K:"K",K:"K","𝐊":"K","𝐾":"K","𝑲":"K","𝒦":"K","𝓚":"K","𝔎":"K","𝕂":"K","𝕶":"K","𝖪":"K","𝗞":"K","𝘒":"K","𝙆":"K","𝙺":"K",Κ:"K","𝚱":"K","𝛫":"K","𝜥":"K","𝝟":"K","𝞙":"K","Ⲕ":"K",К:"K",Ꮶ:"K",ᛕ:"K","ꓗ":"K","𐔘":"K",ƙ:"k̔","Ⱪ":"K̩",Қ:"K̩","₭":"K̵","Ꝁ":"K̵",Ҟ:"K̵",Ƙ:"K'","׀":"l","|":"l","∣":"l","⏽":"l","│":"l","١":"l","۱":"l","𐌠":"l","𞣇":"l","𝟏":"l","𝟙":"l","𝟣":"l","𝟭":"l","𝟷":"l","🯱":"l",I:KK,I:"l","Ⅰ":"l",ℐ:"l",ℑ:"l","𝐈":"l","𝐼":"l","𝑰":"l","𝓘":"l","𝕀":"l","𝕴":"l","𝖨":"l","𝗜":"l","𝘐":"l","𝙄":"l","𝙸":"l",Ɩ:"l",l:"l","ⅼ":"l",ℓ:"l","𝐥":"l","𝑙":"l","𝒍":"l","𝓁":"l","𝓵":"l","𝔩":"l","𝕝":"l","𝖑":"l","𝗅":"l","𝗹":"l","𝘭":"l","𝙡":"l","𝚕":"l",ǀ:"l",Ι:"l","𝚰":"l","𝛪":"l","𝜤":"l","𝝞":"l","𝞘":"l","Ⲓ":"l",І:"l",Ӏ:"l",ו:"l",ן:"l",ا:"l","𞸀":"l","𞺀":"l",ﺎ:"l",ﺍ:"l","ߊ":"l","ⵏ":"l",ᛁ:"l","ꓲ":"l","𖼨":"l","𐊊":"l","𐌉":"l","𝈪":"L","Ⅼ":"L",ℒ:"L","𝐋":"L","𝐿":"L","𝑳":"L","𝓛":"L","𝔏":"L","𝕃":"L","𝕷":"L","𝖫":"L","𝗟":"L","𝘓":"L","𝙇":"L","𝙻":"L","Ⳑ":"L",Ꮮ:"L",ᒪ:"L","ꓡ":"L","𖼖":"L","𑢣":"L","𑢲":"L","𐐛":"L","𐔦":"L",ﴼ:"l̋",ﴽ:"l̋",ł:"l̸",Ł:"L̸",ɭ:"l̨",Ɨ:"l̵",ƚ:"l̵",ɫ:"l̴",إ:"lٕ",ﺈ:"lٕ",ﺇ:"lٕ",ٳ:"lٕ",ŀ:"l·",Ŀ:"l·",ᒷ:"l·","🄂":"l,","⒈":"l.",ױ:"l'","⒓":"l2.","㏫":"l2日","㋋":"l2月","㍤":"l2点","⒔":"l3.","㏬":"l3日","㍥":"l3点","⒕":"l4.","㏭":"l4日","㍦":"l4点","⒖":"l5.","㏮":"l5日","㍧":"l5点","⒗":"l6.","㏯":"l6日","㍨":"l6点","⒘":"l7.","㏰":"l7日","㍩":"l7点","⒙":"l8.","㏱":"l8日","㍪":"l8点","⒚":"l9.","㏲":"l9日","㍫":"l9点",lj:"lj",IJ:"lJ",Lj:"Lj",LJ:"LJ","‖":"ll","∥":"ll","Ⅱ":"ll",ǁ:"ll",װ:"ll","𐆙":"l̵l̵","⒒":"ll.","Ⅲ":"lll","𐆘":"l̵l̵S̵","㏪":"ll日","㋊":"ll月","㍣":"ll点",Ю:"lO","⒑":"lO.","㏩":"lO日","㋉":"lO月","㍢":"lO点",ʪ:"ls","₶":"lt","Ⅳ":"lV","Ⅸ":"lX",ɮ:"lȝ",ʫ:"lz",أ:"lٴ",ﺄ:"lٴ",ﺃ:"lٴ",ٲ:"lٴ",ٵ:"lٴ",ﷳ:"lكبر",ﷲ:"lللّٰo","㏠":"l日","㋀":"l月","㍙":"l点","ⳑ":"ʟ","ꮮ":"ʟ","𐑃":"ʟ",M:"M","Ⅿ":"M",ℳ:"M","𝐌":"M","𝑀":"M","𝑴":"M","𝓜":"M","𝔐":"M","𝕄":"M","𝕸":"M","𝖬":"M","𝗠":"M","𝘔":"M","𝙈":"M","𝙼":"M",Μ:"M","𝚳":"M","𝛭":"M","𝜧":"M","𝝡":"M","𝞛":"M","Ϻ":"M","Ⲙ":"M",М:"M",Ꮇ:"M",ᗰ:"M",ᛖ:"M","ꓟ":"M","𐊰":"M","𐌑":"M","Ӎ":"M̦","🝫":"MB","ⷨ":"ᷟ","𝐧":"n","𝑛":"n","𝒏":"n","𝓃":"n","𝓷":"n","𝔫":"n","𝕟":"n","𝖓":"n","𝗇":"n","𝗻":"n","𝘯":"n","𝙣":"n","𝚗":"n",ո:"n",ռ:"n",N:"N",ℕ:"N","𝐍":"N","𝑁":"N","𝑵":"N","𝒩":"N","𝓝":"N","𝔑":"N","𝕹":"N","𝖭":"N","𝗡":"N","𝘕":"N","𝙉":"N","𝙽":"N",Ν:"N","𝚴":"N","𝛮":"N","𝜨":"N","𝝢":"N","𝞜":"N","Ⲛ":"N","ꓠ":"N","𐔓":"N","𐆎":"N̊",ɳ:"n̨",ƞ:"n̩",η:"n̩","𝛈":"n̩","𝜂":"n̩","𝜼":"n̩","𝝶":"n̩","𝞰":"n̩",Ɲ:"N̦","ᵰ":"n̴",nj:"nj",Nj:"Nj",NJ:"NJ","№":"No","ͷ":"ᴎ",и:"ᴎ","𐑍":"ᴎ",ņ:"ɲ","ం":"o","ಂ":"o","ം":"o","ං":"o","०":"o","੦":"o","૦":"o","௦":"o","౦":"o","೦":"o","൦":"o","๐":"o","໐":"o","၀":"o","٥":"o","۵":"o",o:"o",ℴ:"o","𝐨":"o","𝑜":"o","𝒐":"o","𝓸":"o","𝔬":"o","𝕠":"o","𝖔":"o","𝗈":"o","𝗼":"o","𝘰":"o","𝙤":"o","𝚘":"o","ᴏ":"o","ᴑ":"o","ꬽ":"o",ο:"o","𝛐":"o","𝜊":"o","𝝄":"o","𝝾":"o","𝞸":"o",σ:"o","𝛔":"o","𝜎":"o","𝝈":"o","𝞂":"o","𝞼":"o","ⲟ":"o",о:"o","ჿ":"o",օ:"o",ס:"o",ه:"o","𞸤":"o","𞹤":"o","𞺄":"o",ﻫ:"o",ﻬ:"o",ﻪ:"o",ﻩ:"o",ھ:"o",ﮬ:"o",ﮭ:"o",ﮫ:"o",ﮪ:"o",ہ:"o",ﮨ:"o",ﮩ:"o",ﮧ:"o",ﮦ:"o",ە:"o",ഠ:"o",ဝ:"o","𐓪":"o","𑣈":"o","𑣗":"o","𐐬":"o","߀":"O","০":"O","୦":"O","〇":"O","𑓐":"O","𑣠":"O","𝟎":"O","𝟘":"O","𝟢":"O","𝟬":"O","𝟶":"O","🯰":"O",O:"O","𝐎":"O","𝑂":"O","𝑶":"O","𝒪":"O","𝓞":"O","𝔒":"O","𝕆":"O","𝕺":"O","𝖮":"O","𝗢":"O","𝘖":"O","𝙊":"O","𝙾":"O",Ο:"O","𝚶":"O","𝛰":"O","𝜪":"O","𝝤":"O","𝞞":"O","Ⲟ":"O",О:"O",Օ:"O","ⵔ":"O",ዐ:"O",ଠ:"O","𐓂":"O","ꓳ":"O","𑢵":"O","𐊒":"O","𐊫":"O","𐐄":"O","𐔖":"O","⁰":"º","ᵒ":"º",ǒ:"ŏ",Ǒ:"Ŏ","ۿ":"ô",Ő:"Ö",ø:"o̸","ꬾ":"o̸",Ø:"O̸","ⵁ":"O̸",Ǿ:"Ó̸",ɵ:"o̵","ꝋ":"o̵",ө:"o̵",ѳ:"o̵","ꮎ":"o̵","ꮻ":"o̵","⊖":"O̵","⊝":"O̵","⍬":"O̵","𝈚":"O̵","🜔":"O̵",Ɵ:"O̵","Ꝋ":"O̵",θ:"O̵",ϑ:"O̵","𝛉":"O̵","𝛝":"O̵","𝜃":"O̵","𝜗":"O̵","𝜽":"O̵","𝝑":"O̵","𝝷":"O̵","𝞋":"O̵","𝞱":"O̵","𝟅":"O̵",Θ:"O̵","ϴ":"O̵","𝚯":"O̵","𝚹":"O̵","𝛩":"O̵","𝛳":"O̵","𝜣":"O̵","𝜭":"O̵","𝝝":"O̵","𝝧":"O̵","𝞗":"O̵","𝞡":"O̵",Ө:"O̵",Ѳ:"O̵","ⴱ":"O̵",Ꮎ:"O̵",Ꮻ:"O̵","ꭴ":"ơ",ﳙ:"oٰ","🄁":"O,","🄀":"O.",ơ:"o'",Ơ:"O'",Ꭴ:"O'","%":"º/₀","٪":"º/₀","⁒":"º/₀","‰":"º/₀₀","؉":"º/₀₀","‱":"º/₀₀₀","؊":"º/₀₀₀",œ:"oe",Œ:"OE",ɶ:"oᴇ","∞":"oo","ꝏ":"oo","ꚙ":"oo","Ꝏ":"OO","Ꚙ":"OO",ﳗ:"oج",ﱑ:"oج",ﳘ:"oم",ﱒ:"oم",ﶓ:"oمج",ﶔ:"oمم",ﱓ:"oى",ﱔ:"oى","ൟ":"oരo",တ:"oာ","㍘":"O点","ↄ":"ɔ","ᴐ":"ɔ","ͻ":"ɔ","𐑋":"ɔ","Ↄ":"Ɔ","Ͻ":"Ɔ","ꓛ":"Ɔ","𐐣":"Ɔ","ꬿ":"ɔ̸","ꭢ":"ɔe","𐐿":"ɷ","⍴":"p",p:"p","𝐩":"p","𝑝":"p","𝒑":"p","𝓅":"p","𝓹":"p","𝔭":"p","𝕡":"p","𝖕":"p","𝗉":"p","𝗽":"p","𝘱":"p","𝙥":"p","𝚙":"p",ρ:"p",ϱ:"p","𝛒":"p","𝛠":"p","𝜌":"p","𝜚":"p","𝝆":"p","𝝔":"p","𝞀":"p","𝞎":"p","𝞺":"p","𝟈":"p","ⲣ":"p",р:"p",P:"P",ℙ:"P","𝐏":"P","𝑃":"P","𝑷":"P","𝒫":"P","𝓟":"P","𝔓":"P","𝕻":"P","𝖯":"P","𝗣":"P","𝘗":"P","𝙋":"P","𝙿":"P",Ρ:"P","𝚸":"P","𝛲":"P","𝜬":"P","𝝦":"P","𝞠":"P","Ⲣ":"P",Р:"P",Ꮲ:"P",ᑭ:"P","ꓑ":"P","𐊕":"P",ƥ:"p̔","ᵽ":"p̵",ᑷ:"p·",ᒆ:"P'","ᴩ":"ᴘ","ꮲ":"ᴘ",φ:"ɸ",ϕ:"ɸ","𝛗":"ɸ","𝛟":"ɸ","𝜑":"ɸ","𝜙":"ɸ","𝝋":"ɸ","𝝓":"ɸ","𝞅":"ɸ","𝞍":"ɸ","𝞿":"ɸ","𝟇":"ɸ","ⲫ":"ɸ",ф:"ɸ","𝐪":"q","𝑞":"q","𝒒":"q","𝓆":"q","𝓺":"q","𝔮":"q","𝕢":"q","𝖖":"q","𝗊":"q","𝗾":"q","𝘲":"q","𝙦":"q","𝚚":"q","ԛ":"q",գ:"q",զ:"q",ℚ:"Q","𝐐":"Q","𝑄":"Q","𝑸":"Q","𝒬":"Q","𝓠":"Q","𝔔":"Q","𝕼":"Q","𝖰":"Q","𝗤":"Q","𝘘":"Q","𝙌":"Q","𝚀":"Q","ⵕ":"Q",ʠ:"q̔","🜀":"QE","ᶐ":"ɋ","ᴋ":"ĸ",κ:"ĸ",ϰ:"ĸ","𝛋":"ĸ","𝛞":"ĸ","𝜅":"ĸ","𝜘":"ĸ","𝜿":"ĸ","𝝒":"ĸ","𝝹":"ĸ","𝞌":"ĸ","𝞳":"ĸ","𝟆":"ĸ","ⲕ":"ĸ",к:"ĸ","ꮶ":"ĸ",қ:"ĸ̩",ҟ:"ĸ̵","𝐫":"r","𝑟":"r","𝒓":"r","𝓇":"r","𝓻":"r","𝔯":"r","𝕣":"r","𝖗":"r","𝗋":"r","𝗿":"r","𝘳":"r","𝙧":"r","𝚛":"r","ꭇ":"r","ꭈ":"r","ᴦ":"r","ⲅ":"r",г:"r","ꮁ":"r","𝈖":"R",ℛ:"R",ℜ:"R",ℝ:"R","𝐑":"R","𝑅":"R","𝑹":"R","𝓡":"R","𝕽":"R","𝖱":"R","𝗥":"R","𝘙":"R","𝙍":"R","𝚁":"R",Ʀ:"R",Ꭱ:"R",Ꮢ:"R","𐒴":"R",ᖇ:"R","ꓣ":"R","𖼵":"R",ɽ:"r̨",ɼ:"r̩","ɍ":"r̵",ғ:"r̵","ᵲ":"r̴",ґ:"r'","𑣣":"rn",m:jK,"ⅿ":"rn","𝐦":"rn","𝑚":"rn","𝒎":"rn","𝓂":"rn","𝓶":"rn","𝔪":"rn","𝕞":"rn","𝖒":"rn","𝗆":"rn","𝗺":"rn","𝘮":"rn","𝙢":"rn","𝚖":"rn","𑜀":"rn","₥":"rn̸",ɱ:"rn̦","ᵯ":"rn̴","₨":"Rs","ꭱ":"ʀ","ꮢ":"ʀ",я:"ᴙ","ᵳ":"ɾ̴","℩":"ɿ",s:"s","𝐬":"s","𝑠":"s","𝒔":"s","𝓈":"s","𝓼":"s","𝔰":"s","𝕤":"s","𝖘":"s","𝗌":"s","𝘀":"s","𝘴":"s","𝙨":"s","𝚜":"s","ꜱ":"s",ƽ:"s",ѕ:"s","ꮪ":"s","𑣁":"s","𐑈":"s",S:"S","𝐒":"S","𝑆":"S","𝑺":"S","𝒮":"S","𝓢":"S","𝔖":"S","𝕊":"S","𝕾":"S","𝖲":"S","𝗦":"S","𝘚":"S","𝙎":"S","𝚂":"S",Ѕ:"S",Տ:"S",Ꮥ:"S",Ꮪ:"S","ꓢ":"S","𖼺":"S","𐊖":"S","𐐠":"S",ʂ:"s̨","ᵴ":"s̴","ꞵ":"ß",β:"ß",ϐ:"ß","𝛃":"ß","𝛽":"ß","𝜷":"ß","𝝱":"ß","𝞫":"ß",Ᏸ:"ß","🝜":"sss",st:"st","∫":"ʃ","ꭍ":"ʃ","∑":"Ʃ","⅀":"Ʃ",Σ:"Ʃ","𝚺":"Ʃ","𝛴":"Ʃ","𝜮":"Ʃ","𝝨":"Ʃ","𝞢":"Ʃ","ⵉ":"Ʃ","∬":"ʃʃ","∭":"ʃʃʃ","⨌":"ʃʃʃʃ","𝐭":"t","𝑡":"t","𝒕":"t","𝓉":"t","𝓽":"t","𝔱":"t","𝕥":"t","𝖙":"t","𝗍":"t","𝘁":"t","𝘵":"t","𝙩":"t","𝚝":"t","⊤":"T","⟙":"T","🝨":"T",T:"T","𝐓":"T","𝑇":"T","𝑻":"T","𝒯":"T","𝓣":"T","𝔗":"T","𝕋":"T","𝕿":"T","𝖳":"T","𝗧":"T","𝘛":"T","𝙏":"T","𝚃":"T",Τ:"T","𝚻":"T","𝛵":"T","𝜯":"T","𝝩":"T","𝞣":"T","Ⲧ":"T",Т:"T",Ꭲ:"T","ꓔ":"T","𖼊":"T","𑢼":"T","𐊗":"T","𐊱":"T","𐌕":"T",ƭ:"t̔","⍡":"T̈","Ⱦ":"T̸",Ț:"Ţ",Ʈ:"T̨",Ҭ:"T̩","₮":"T⃫",ŧ:"t̵",Ŧ:"T̵","ᵵ":"t̴",Ⴀ:"Ꞇ","Ꜩ":"T3",ʨ:"tɕ","℡":"TEL","ꝷ":"tf",ʦ:"ts",ʧ:"tʃ","ꜩ":"tȝ",τ:"ᴛ","𝛕":"ᴛ","𝜏":"ᴛ","𝝉":"ᴛ","𝞃":"ᴛ","𝞽":"ᴛ",т:"ᴛ","ꭲ":"ᴛ",ҭ:"ᴛ̩",ţ:"ƫ",ț:"ƫ",Ꮏ:"ƫ","𝐮":"u","𝑢":"u","𝒖":"u","𝓊":"u","𝓾":"u","𝔲":"u","𝕦":"u","𝖚":"u","𝗎":"u","𝘂":"u","𝘶":"u","𝙪":"u","𝚞":"u","ꞟ":"u","ᴜ":"u","ꭎ":"u","ꭒ":"u",ʋ:"u",υ:"u","𝛖":"u","𝜐":"u","𝝊":"u","𝞄":"u","𝞾":"u",ս:"u","𐓶":"u","𑣘":"u","∪":"U","⋃":"U","𝐔":"U","𝑈":"U","𝑼":"U","𝒰":"U","𝓤":"U","𝔘":"U","𝕌":"U","𝖀":"U","𝖴":"U","𝗨":"U","𝘜":"U","𝙐":"U","𝚄":"U",Ս:"U",ሀ:"U","𐓎":"U",ᑌ:"U","ꓴ":"U","𖽂":"U","𑢸":"U",ǔ:"ŭ",Ǔ:"Ŭ","ᵾ":"u̵","ꮜ":"u̵","Ʉ":"U̵",Ꮜ:"U̵",ᑘ:"U·",ᑧ:"U'","ᵫ":"ue","ꭣ":"uo",ṃ:"ꭑ",պ:"ɰ",ሣ:"ɰ","℧":"Ʊ",ᘮ:"Ʊ",ᘴ:"Ʊ","ᵿ":"ʊ̵","∨":"v","⋁":"v",v:"v","ⅴ":"v","𝐯":"v","𝑣":"v","𝒗":"v","𝓋":"v","𝓿":"v","𝔳":"v","𝕧":"v","𝖛":"v","𝗏":"v","𝘃":"v","𝘷":"v","𝙫":"v","𝚟":"v","ᴠ":"v",ν:"v","𝛎":"v","𝜈":"v","𝝂":"v","𝝼":"v","𝞶":"v",ѵ:"v",ט:"v","𑜆":"v","ꮩ":"v","𑣀":"v","𝈍":"V","٧":"V","۷":"V","Ⅴ":"V","𝐕":"V","𝑉":"V","𝑽":"V","𝒱":"V","𝓥":"V","𝔙":"V","𝕍":"V","𝖁":"V","𝖵":"V","𝗩":"V","𝘝":"V","𝙑":"V","𝚅":"V",Ѵ:"V","ⴸ":"V",Ꮩ:"V",ᐯ:"V","ꛟ":"V","ꓦ":"V","𖼈":"V","𑢠":"V","𐔝":"V","𐆗":"V̵",ᐻ:"V·","🝬":"VB","ⅵ":"vi","ⅶ":"vii","ⅷ":"viii","Ⅵ":"Vl","Ⅶ":"Vll","Ⅷ":"Vlll","🜈":"Vᷤ","ᴧ":"ʌ","𐓘":"ʌ","٨":"Ʌ","۸":"Ʌ",Λ:"Ʌ","𝚲":"Ʌ","𝛬":"Ʌ","𝜦":"Ʌ","𝝠":"Ʌ","𝞚":"Ʌ",Л:"Ʌ","ⴷ":"Ʌ","𐒰":"Ʌ",ᐱ:"Ʌ","ꛎ":"Ʌ","ꓥ":"Ʌ","𖼽":"Ʌ","𐊍":"Ʌ","Ӆ":"Ʌ̦",ᐽ:"Ʌ·",ɯ:"w","𝐰":"w","𝑤":"w","𝒘":"w","𝓌":"w","𝔀":"w","𝔴":"w","𝕨":"w","𝖜":"w","𝗐":"w","𝘄":"w","𝘸":"w","𝙬":"w","𝚠":"w","ᴡ":"w",ѡ:"w","ԝ":"w",ա:"w","𑜊":"w","𑜎":"w","𑜏":"w","ꮃ":"w","𑣯":"W","𑣦":"W","𝐖":"W","𝑊":"W","𝑾":"W","𝒲":"W","𝓦":"W","𝔚":"W","𝕎":"W","𝖂":"W","𝖶":"W","𝗪":"W","𝘞":"W","𝙒":"W","𝚆":"W","Ԝ":"W",Ꮃ:"W",Ꮤ:"W","ꓪ":"W",ѽ:"w҆҇","𑓅":"ẇ","₩":"W̵","ꝡ":"w̦","ᴍ":"ʍ",м:"ʍ","ꮇ":"ʍ","ӎ":"ʍ̦","᙮":"x","×":"x","⤫":"x","⤬":"x","⨯":"x",x:"x","ⅹ":"x","𝐱":"x","𝑥":"x","𝒙":"x","𝓍":"x","𝔁":"x","𝔵":"x","𝕩":"x","𝖝":"x","𝗑":"x","𝘅":"x","𝘹":"x","𝙭":"x","𝚡":"x",х:"x",ᕁ:"x",ᕽ:"x","ⷯ":"ͯ","᙭":"X","╳":"X","𐌢":"X","𑣬":"X",X:"X","Ⅹ":"X","𝐗":"X","𝑋":"X","𝑿":"X","𝒳":"X","𝓧":"X","𝔛":"X","𝕏":"X","𝖃":"X","𝖷":"X","𝗫":"X","𝘟":"X","𝙓":"X","𝚇":"X","Ꭓ":"X",Χ:"X","𝚾":"X","𝛸":"X","𝜲":"X","𝝬":"X","𝞦":"X","Ⲭ":"X",Х:"X","ⵝ":"X",ᚷ:"X","ꓫ":"X","𐊐":"X","𐊴":"X","𐌗":"X","𐔧":"X","⨰":"ẋ",Ҳ:"X̩","𐆖":"X̵","ⅺ":"xi","ⅻ":"xii","Ⅺ":"Xl","Ⅻ":"Xll",ɣ:"y","ᶌ":"y",y:"y","𝐲":"y","𝑦":"y","𝒚":"y","𝓎":"y","𝔂":"y","𝔶":"y","𝕪":"y","𝖞":"y","𝗒":"y","𝘆":"y","𝘺":"y","𝙮":"y","𝚢":"y",ʏ:"y","ỿ":"y","ꭚ":"y",γ:"y","ℽ":"y","𝛄":"y","𝛾":"y","𝜸":"y","𝝲":"y","𝞬":"y",у:"y",ү:"y",ყ:"y","𑣜":"y",Y:"Y","𝐘":"Y","𝑌":"Y","𝒀":"Y","𝒴":"Y","𝓨":"Y","𝔜":"Y","𝕐":"Y","𝖄":"Y","𝖸":"Y","𝗬":"Y","𝘠":"Y","𝙔":"Y","𝚈":"Y",Υ:"Y",ϒ:"Y","𝚼":"Y","𝛶":"Y","𝜰":"Y","𝝪":"Y","𝞤":"Y","Ⲩ":"Y",У:"Y",Ү:"Y",Ꭹ:"Y",Ꮍ:"Y","ꓬ":"Y","𖽃":"Y","𑢤":"Y","𐊲":"Y",ƴ:"y̔","ɏ":"y̵",ұ:"y̵","¥":"Y̵","Ɏ":"Y̵",Ұ:"Y̵",ʒ:"ȝ","ꝫ":"ȝ","ⳍ":"ȝ",ӡ:"ȝ",ჳ:"ȝ","𝐳":"z","𝑧":"z","𝒛":"z","𝓏":"z","𝔃":"z","𝔷":"z","𝕫":"z","𝖟":"z","𝗓":"z","𝘇":"z","𝘻":"z","𝙯":"z","𝚣":"z","ᴢ":"z","ꮓ":"z","𑣄":"z","𐋵":"Z","𑣥":"Z",Z:"Z",ℤ:"Z",ℨ:"Z","𝐙":"Z","𝑍":"Z","𝒁":"Z","𝒵":"Z","𝓩":"Z","𝖅":"Z","𝖹":"Z","𝗭":"Z","𝘡":"Z","𝙕":"Z","𝚉":"Z",Ζ:"Z","𝚭":"Z","𝛧":"Z","𝜡":"Z","𝝛":"Z","𝞕":"Z",Ꮓ:"Z","ꓜ":"Z","𑢩":"Z",ʐ:"z̨",ƶ:"z̵",Ƶ:"Z̵",ȥ:"z̦",Ȥ:"Z̦","ᵶ":"z̴",ƿ:"þ","ϸ":"þ","Ϸ":"Þ","𐓄":"Þ","⁹":"ꝰ","ᴤ":"ƨ",ϩ:"ƨ","ꙅ":"ƨ",ь:"ƅ","ꮟ":"ƅ",ы:"ƅi","ꭾ":"ɂ",ˤ:"ˁ","ꛍ":"ʡ","⊙":"ʘ","☉":"ʘ","⨀":"ʘ","Ꙩ":"ʘ","ⵙ":"ʘ","𐓃":"ʘ","ℾ":"Γ","𝚪":"Γ","𝛤":"Γ","𝜞":"Γ","𝝘":"Γ","𝞒":"Γ","Ⲅ":"Γ",Г:"Γ",Ꮁ:"Γ",ᒥ:"Γ","𖼇":"Γ",Ғ:"Γ̵",ᒯ:"Γ·",Ґ:"Γ'","∆":"Δ","△":"Δ","🜂":"Δ","𝚫":"Δ","𝛥":"Δ","𝜟":"Δ","𝝙":"Δ","𝞓":"Δ","Ⲇ":"Δ","ⵠ":"Δ",ᐃ:"Δ","𖼚":"Δ","𐊅":"Δ","𐊣":"Δ","⍙":"Δ̲",ᐏ:"Δ·",ᐬ:"Δᐠ","𝟋":"ϝ","𝛇":"ζ","𝜁":"ζ","𝜻":"ζ","𝝵":"ζ","𝞯":"ζ","ⳤ":"ϗ","𝛌":"λ","𝜆":"λ","𝝀":"λ","𝝺":"λ","𝞴":"λ","Ⲗ":"λ","𐓛":"λ",µ:"μ","𝛍":"μ","𝜇":"μ","𝝁":"μ","𝝻":"μ","𝞵":"μ","𝛏":"ξ","𝜉":"ξ","𝝃":"ξ","𝝽":"ξ","𝞷":"ξ","𝚵":"Ξ","𝛯":"Ξ","𝜩":"Ξ","𝝣":"Ξ","𝞝":"Ξ",ϖ:"π","ℼ":"π","𝛑":"π","𝛡":"π","𝜋":"π","𝜛":"π","𝝅":"π","𝝕":"π","𝝿":"π","𝞏":"π","𝞹":"π","𝟉":"π","ᴨ":"π",п:"π","∏":"Π","ℿ":"Π","𝚷":"Π","𝛱":"Π","𝜫":"Π","𝝥":"Π","𝞟":"Π","Ⲡ":"Π",П:"Π","ꛛ":"Π","𐊭":"Ϙ","𐌒":"Ϙ",ϛ:"ς","𝛓":"ς","𝜍":"ς","𝝇":"ς","𝞁":"ς","𝞻":"ς","𝚽":"Φ","𝛷":"Φ","𝜱":"Φ","𝝫":"Φ","𝞥":"Φ","Ⲫ":"Φ",Ф:"Φ",Փ:"Φ",ቀ:"Φ","ᛰ":"Φ","𐊳":"Φ","ꭓ":"χ","ꭕ":"χ","𝛘":"χ","𝜒":"χ","𝝌":"χ","𝞆":"χ","𝟀":"χ","ⲭ":"χ","𝛙":"ψ","𝜓":"ψ","𝝍":"ψ","𝞇":"ψ","𝟁":"ψ",ѱ:"ψ","𐓹":"ψ","𝚿":"Ψ","𝛹":"Ψ","𝜳":"Ψ","𝝭":"Ψ","𝞧":"Ψ","Ⲯ":"Ψ",Ѱ:"Ψ","𐓑":"Ψ",ᛘ:"Ψ","𐊵":"Ψ","⍵":"ω","ꞷ":"ω","𝛚":"ω","𝜔":"ω","𝝎":"ω","𝞈":"ω","𝟂":"ω","ⲱ":"ω","ꙍ":"ω",Ω:"Ω","𝛀":"Ω","𝛺":"Ω","𝜴":"Ω","𝝮":"Ω","𝞨":"Ω",ᘯ:"Ω",ᘵ:"Ω","𐊶":"Ω","⍹":"ω̲",ώ:"ῴ","☰":"Ⲷ","Ⳝ":"Ϭ",җ:"ж̩",Җ:"Ж̩","𝈋":"И","Ͷ":"И","ꚡ":"И","𐐥":"И",Й:"Ѝ","Ҋ":"Ѝ̦",ѝ:"й","ҋ":"й̦","𐒼":"Ӄ","ᴫ":"л","ӆ":"л̦","ꭠ":"љ","𐓫":"ꙩ","ᷮ":"ⷬ","𐓍":"Ћ","𝈂":"Ӿ","𝈢":"Ѡ",Ꮗ:"Ѡ",ᗯ:"Ѡ",Ѽ:"Ѡ҆҇","ᣭ":"Ѡ·","Ꞷ":"Ꙍ",ӌ:"ҷ",Ӌ:"Ҷ",Ҿ:"Ҽ̨","ⲽ":"ш","Ⲽ":"Ш","Ꙑ":"Ъl","℈":"Э","🜁":"Ꙙ","𖼜":"Ꙙ","ꦒ":"ⰿ",և:"եւ",ኔ:"ձ",ﬔ:"մե",ﬕ:"մի",ﬗ:"մխ",ﬓ:"մն","∩":"Ո","⋂":"Ո","𝉅":"Ո",በ:"Ո",ᑎ:"Ո","ꓵ":"Ո",ᑚ:"Ո·",ᑨ:"Ո'",ﬖ:"վն","₽":"Ք","˓":"ՙ",ʿ:"ՙ",ℵ:"א",ﬡ:"א",אָ:"אַ",אּ:"אַ",ﭏ:"אל",ℶ:"ב",ℷ:"ג",ℸ:"ד",ﬢ:"ד",ﬣ:"ה",יּ:"יִ",ﬤ:"כ",ﬥ:"ל",ﬦ:"ם",ﬠ:"ע",ﬧ:"ר",שׂ:"שׁ",שּ:"שׁ",שּׂ:"שּׁ",ﬨ:"ת",ﺀ:"ء","۽":"ء͈",ﺂ:"آ",ﺁ:"آ",ﭑ:"ٱ",ﭐ:"ٱ","𞸁":"ب","𞸡":"ب","𞹡":"ب","𞺁":"ب","𞺡":"ب",ﺑ:"ب",ﺒ:"ب",ﺐ:"ب",ﺏ:"ب","ݑ":"بۛ","ࢶ":"بۢ","ࢡ":"بٔ",ﲠ:"بo",ﳢ:"بo",ﲜ:"بج",ﰅ:"بج",ﲝ:"بح",ﰆ:"بح",ﷂ:"بحى",ﲞ:"بخ",ﰇ:"بخ",ﳒ:"بخ",ﱋ:"بخ",ﶞ:"بخى",ﱪ:"بر",ﱫ:"بز",ﲟ:"بم",ﳡ:"بم",ﱬ:"بم",ﰈ:"بم",ﱭ:"بن",ﱮ:"بى",ﰉ:"بى",ﱯ:"بى",ﰊ:"بى",ﭔ:"ٻ",ﭕ:"ٻ",ﭓ:"ٻ",ﭒ:"ٻ",ې:"ٻ",ﯦ:"ٻ",ﯧ:"ٻ",ﯥ:"ٻ",ﯤ:"ٻ",ﭜ:"ڀ",ﭝ:"ڀ",ﭛ:"ڀ",ﭚ:"ڀ","ࢩ":"ݔ","ݧ":"ݔ","⍥":"ة",ö:"ة",ﺔ:"ة",ﺓ:"ة",ۃ:"ة","𞸕":"ت","𞸵":"ت","𞹵":"ت","𞺕":"ت","𞺵":"ت",ﺗ:"ت",ﺘ:"ت",ﺖ:"ت",ﺕ:"ت",ﲥ:"تo",ﳤ:"تo",ﲡ:"تج",ﰋ:"تج",ﵐ:"تجم",ﶠ:"تجى",ﶟ:"تجى",ﲢ:"تح",ﰌ:"تح",ﵒ:"تحج",ﵑ:"تحج",ﵓ:"تحم",ﲣ:"تخ",ﰍ:"تخ",ﵔ:"تخم",ﶢ:"تخى",ﶡ:"تخى",ﱰ:"تر",ﱱ:"تز",ﲤ:"تم",ﳣ:"تم",ﱲ:"تم",ﰎ:"تم",ﵕ:"تمج",ﵖ:"تمح",ﵗ:"تمخ",ﶤ:"تمى",ﶣ:"تمى",ﱳ:"تن",ﱴ:"تى",ﰏ:"تى",ﱵ:"تى",ﰐ:"تى",ﭠ:"ٺ",ﭡ:"ٺ",ﭟ:"ٺ",ﭞ:"ٺ",ﭤ:"ٿ",ﭥ:"ٿ",ﭣ:"ٿ",ﭢ:"ٿ","𞸂":"ج","𞸢":"ج","𞹂":"ج","𞹢":"ج","𞺂":"ج","𞺢":"ج",ﺟ:"ج",ﺠ:"ج",ﺞ:"ج",ﺝ:"ج",ﲧ:"جح",ﰕ:"جح",ﶦ:"جحى",ﶾ:"جحى",ﷻ:"جل جلlلo",ﲨ:"جم",ﰖ:"جم",ﵙ:"جمح",ﵘ:"جمح",ﶧ:"جمى",ﶥ:"جمى",ﴝ:"جى",ﴁ:"جى",ﴞ:"جى",ﴂ:"جى",ﭸ:"ڃ",ﭹ:"ڃ",ﭷ:"ڃ",ﭶ:"ڃ",ﭴ:"ڄ",ﭵ:"ڄ",ﭳ:"ڄ",ﭲ:"ڄ",ﭼ:"چ",ﭽ:"چ",ﭻ:"چ",ﭺ:"چ",ﮀ:"ڇ",ﮁ:"ڇ",ﭿ:"ڇ",ﭾ:"ڇ","𞸇":"ح","𞸧":"ح","𞹇":"ح","𞹧":"ح","𞺇":"ح","𞺧":"ح",ﺣ:"ح",ﺤ:"ح",ﺢ:"ح",ﺡ:"ح",څ:"حۛ",ځ:"حٔ","ݲ":"حٔ",ﲩ:"حج",ﰗ:"حج",ﶿ:"حجى",ﲪ:"حم",ﰘ:"حم",ﵛ:"حمى",ﵚ:"حمى",ﴛ:"حى",ﳿ:"حى",ﴜ:"حى",ﴀ:"حى","𞸗":"خ","𞸷":"خ","𞹗":"خ","𞹷":"خ","𞺗":"خ","𞺷":"خ",ﺧ:"خ",ﺨ:"خ",ﺦ:"خ",ﺥ:"خ",ﲫ:"خج",ﰙ:"خج",ﰚ:"خح",ﲬ:"خم",ﰛ:"خم",ﴟ:"خى",ﴃ:"خى",ﴠ:"خى",ﴄ:"خى","𐋡":"د","𞸃":"د","𞺃":"د","𞺣":"د",ﺪ:"د",ﺩ:"د",ڈ:"دؕ",ﮉ:"دؕ",ﮈ:"دؕ",ڎ:"دۛ",ﮇ:"دۛ",ﮆ:"دۛ","ۮ":"د̂","ࢮ":"د̤̣","𞸘":"ذ","𞺘":"ذ","𞺸":"ذ",ﺬ:"ذ",ﺫ:"ذ",ﱛ:"ذٰ",ڋ:"ڊؕ",ﮅ:"ڌ",ﮄ:"ڌ",ﮃ:"ڍ",ﮂ:"ڍ","𞸓":"ر","𞺓":"ر","𞺳":"ر",ﺮ:"ر",ﺭ:"ر",ڑ:"رؕ",ﮍ:"رؕ",ﮌ:"رؕ",ژ:"رۛ",ﮋ:"رۛ",ﮊ:"رۛ",ڒ:"ر̆","ࢹ":"ر̆̇","ۯ":"ر̂","ݬ":"رٔ",ﱜ:"رٰ",ﷶ:"رسول","﷼":"رىlل","𞸆":"ز","𞺆":"ز","𞺦":"ز",ﺰ:"ز",ﺯ:"ز","ࢲ":"ز̂","ݱ":"ڗؕ","𞸎":"س","𞸮":"س","𞹎":"س","𞹮":"س","𞺎":"س","𞺮":"س",ﺳ:"س",ﺴ:"س",ﺲ:"س",ﺱ:"س",ش:"سۛ","𞸔":"سۛ","𞸴":"سۛ","𞹔":"سۛ","𞹴":"سۛ","𞺔":"سۛ","𞺴":"سۛ",ﺷ:"سۛ",ﺸ:"سۛ",ﺶ:"سۛ",ﺵ:"سۛ","ݾ":"س̂",ﴱ:"سo",ﳨ:"سo",ﴲ:"سۛo",ﳪ:"سۛo",ﲭ:"سج",ﴴ:"سج",ﰜ:"سج",ﴭ:"سۛج",ﴷ:"سۛج",ﴥ:"سۛج",ﴉ:"سۛج",ﵝ:"سجح",ﵞ:"سجى",ﵩ:"سۛجى",ﲮ:"سح",ﴵ:"سح",ﰝ:"سح",ﴮ:"سۛح",ﴸ:"سۛح",ﴦ:"سۛح",ﴊ:"سۛح",ﵜ:"سحج",ﵨ:"سۛحم",ﵧ:"سۛحم",ﶪ:"سۛحى",ﲯ:"سخ",ﴶ:"سخ",ﰞ:"سخ",ﴯ:"سۛخ",ﴹ:"سۛخ",ﴧ:"سۛخ",ﴋ:"سۛخ",ﶨ:"سخى",ﷆ:"سخى",ﴪ:"سر",ﴎ:"سر",ﴩ:"سۛر",ﴍ:"سۛر",ﲰ:"سم",ﳧ:"سم",ﰟ:"سم",ﴰ:"سۛم",ﳩ:"سۛم",ﴨ:"سۛم",ﴌ:"سۛم",ﵡ:"سمج",ﵠ:"سمح",ﵟ:"سمح",ﵫ:"سۛمخ",ﵪ:"سۛمخ",ﵣ:"سمم",ﵢ:"سمم",ﵭ:"سۛمم",ﵬ:"سۛمم",ﴗ:"سى",ﳻ:"سى",ﴘ:"سى",ﳼ:"سى",ﴙ:"سۛى",ﳽ:"سۛى",ﴚ:"سۛى",ﳾ:"سۛى","𐋲":"ص","𞸑":"ص","𞸱":"ص","𞹑":"ص","𞹱":"ص","𞺑":"ص","𞺱":"ص",ﺻ:"ص",ﺼ:"ص",ﺺ:"ص",ﺹ:"ص",ڞ:"صۛ","ࢯ":"ص̤̣",ﲱ:"صح",ﰠ:"صح",ﵥ:"صحح",ﵤ:"صحح",ﶩ:"صحى",ﲲ:"صخ",ﴫ:"صر",ﴏ:"صر",ﷵ:"صلعم",ﷹ:"صلى",ﷰ:"صلى",ﷺ:"صلى lللo علىo وسلم",ﲳ:"صم",ﰡ:"صم",ﷅ:"صمم",ﵦ:"صمم",ﴡ:"صى",ﴅ:"صى",ﴢ:"صى",ﴆ:"صى","𞸙":"ض","𞸹":"ض","𞹙":"ض","𞹹":"ض","𞺙":"ض","𞺹":"ض",ﺿ:"ض",ﻀ:"ض",ﺾ:"ض",ﺽ:"ض",ﲴ:"ضج",ﰢ:"ضج",ﲵ:"ضح",ﰣ:"ضح",ﵮ:"ضحى",ﶫ:"ضحى",ﲶ:"ضخ",ﰤ:"ضخ",ﵰ:"ضخم",ﵯ:"ضخم",ﴬ:"ضر",ﴐ:"ضر",ﲷ:"ضم",ﰥ:"ضم",ﴣ:"ضى",ﴇ:"ضى",ﴤ:"ضى",ﴈ:"ضى","𐋨":"ط","𞸈":"ط","𞹨":"ط","𞺈":"ط","𞺨":"ط",ﻃ:"ط",ﻄ:"ط",ﻂ:"ط",ﻁ:"ط",ڟ:"طۛ",ﲸ:"طح",ﰦ:"طح",ﴳ:"طم",ﴺ:"طم",ﰧ:"طم",ﵲ:"طمح",ﵱ:"طمح",ﵳ:"طمم",ﵴ:"طمى",ﴑ:"طى",ﳵ:"طى",ﴒ:"طى",ﳶ:"طى","𞸚":"ظ","𞹺":"ظ","𞺚":"ظ","𞺺":"ظ",ﻇ:"ظ",ﻈ:"ظ",ﻆ:"ظ",ﻅ:"ظ",ﲹ:"ظم",ﴻ:"ظم",ﰨ:"ظم","؏":"ع","𞸏":"ع","𞸯":"ع","𞹏":"ع","𞹯":"ع","𞺏":"ع","𞺯":"ع",ﻋ:"ع",ﻌ:"ع",ﻊ:"ع",ﻉ:"ع",ﲺ:"عج",ﰩ:"عج",ﷄ:"عجم",ﵵ:"عجم",ﷷ:"علىo",ﲻ:"عم",ﰪ:"عم",ﵷ:"عمم",ﵶ:"عمم",ﵸ:"عمى",ﶶ:"عمى",ﴓ:"عى",ﳷ:"عى",ﴔ:"عى",ﳸ:"عى","𞸛":"غ","𞸻":"غ","𞹛":"غ","𞹻":"غ","𞺛":"غ","𞺻":"غ",ﻏ:"غ",ﻐ:"غ",ﻎ:"غ",ﻍ:"غ",ﲼ:"غج",ﰫ:"غج",ﲽ:"غم",ﰬ:"غم",ﵹ:"غمم",ﵻ:"غمى",ﵺ:"غمى",ﴕ:"غى",ﳹ:"غى",ﴖ:"غى",ﳺ:"غى","𞸐":"ف","𞸰":"ف","𞹰":"ف","𞺐":"ف","𞺰":"ف",ﻓ:"ف",ﻔ:"ف",ﻒ:"ف",ﻑ:"ف",ڧ:"ف",ﲾ:"فج",ﰭ:"فج",ﲿ:"فح",ﰮ:"فح",ﳀ:"فخ",ﰯ:"فخ",ﵽ:"فخم",ﵼ:"فخم",ﳁ:"فم",ﰰ:"فم",ﷁ:"فمى",ﱼ:"فى",ﰱ:"فى",ﱽ:"فى",ﰲ:"فى","𞸞":"ڡ","𞹾":"ڡ","ࢻ":"ڡ","ٯ":"ڡ","𞸟":"ڡ","𞹟":"ڡ","ࢼ":"ڡ",ڤ:"ڡۛ",ﭬ:"ڡۛ",ﭭ:"ڡۛ",ﭫ:"ڡۛ",ﭪ:"ڡۛ",ڨ:"ڡۛ","ࢤ":"ڢۛ",ﭰ:"ڦ",ﭱ:"ڦ",ﭯ:"ڦ",ﭮ:"ڦ","𞸒":"ق","𞸲":"ق","𞹒":"ق","𞹲":"ق","𞺒":"ق","𞺲":"ق",ﻗ:"ق",ﻘ:"ق",ﻖ:"ق",ﻕ:"ق",ﳂ:"قح",ﰳ:"قح",ﷱ:"قلى",ﳃ:"قم",ﰴ:"قم",ﶴ:"قمح",ﵾ:"قمح",ﵿ:"قمم",ﶲ:"قمى",ﱾ:"قى",ﰵ:"قى",ﱿ:"قى",ﰶ:"قى","𞸊":"ك","𞸪":"ك","𞹪":"ك",ﻛ:"ك",ﻜ:"ك",ﻚ:"ك",ﻙ:"ك",ک:"ك",ﮐ:"ك",ﮑ:"ك",ﮏ:"ك",ﮎ:"ك",ڪ:"ك",ڭ:"كۛ",ﯕ:"كۛ",ﯖ:"كۛ",ﯔ:"كۛ",ﯓ:"كۛ","ݣ":"كۛ",ﲀ:"كl",ﰷ:"كl",ﳄ:"كج",ﰸ:"كج",ﳅ:"كح",ﰹ:"كح",ﳆ:"كخ",ﰺ:"كخ",ﳇ:"كل",ﳫ:"كل",ﲁ:"كل",ﰻ:"كل",ﳈ:"كم",ﳬ:"كم",ﲂ:"كم",ﰼ:"كم",ﷃ:"كمم",ﶻ:"كمم",ﶷ:"كمى",ﲃ:"كى",ﰽ:"كى",ﲄ:"كى",ﰾ:"كى","ݢ":"ڬ",ﮔ:"گ",ﮕ:"گ",ﮓ:"گ",ﮒ:"گ","ࢰ":"گ",ڴ:"گۛ",ﮜ:"ڱ",ﮝ:"ڱ",ﮛ:"ڱ",ﮚ:"ڱ",ﮘ:"ڳ",ﮙ:"ڳ",ﮗ:"ڳ",ﮖ:"ڳ","𞸋":"ل","𞸫":"ل","𞹋":"ل","𞺋":"ل","𞺫":"ل",ﻟ:"ل",ﻠ:"ل",ﻞ:"ل",ﻝ:"ل",ڷ:"لۛ",ڵ:"ل̆",ﻼ:"لl",ﻻ:"لl",ﻺ:"لlٕ",ﻹ:"لlٕ",ﻸ:"لlٴ",ﻷ:"لlٴ",ﳍ:"لo",ﻶ:"لآ",ﻵ:"لآ",ﳉ:"لج",ﰿ:"لج",ﶃ:"لجج",ﶄ:"لجج",ﶺ:"لجم",ﶼ:"لجم",ﶬ:"لجى",ﳊ:"لح",ﱀ:"لح",ﶵ:"لحم",ﶀ:"لحم",ﶂ:"لحى",ﶁ:"لحى",ﳋ:"لخ",ﱁ:"لخ",ﶆ:"لخم",ﶅ:"لخم",ﳌ:"لم",ﳭ:"لم",ﲅ:"لم",ﱂ:"لم",ﶈ:"لمح",ﶇ:"لمح",ﶭ:"لمى",ﲆ:"لى",ﱃ:"لى",ﲇ:"لى",ﱄ:"لى","𞸌":"م","𞸬":"م","𞹬":"م","𞺌":"م","𞺬":"م",ﻣ:"م",ﻤ:"م",ﻢ:"م",ﻡ:"م","ࢧ":"مۛ","۾":"م͈",ﲈ:"مl",ﳎ:"مج",ﱅ:"مج",ﶌ:"مجح",ﶒ:"مجخ",ﶍ:"مجم",ﷀ:"مجى",ﳏ:"مح",ﱆ:"مح",ﶉ:"محج",ﶊ:"محم",ﷴ:"محمد",ﶋ:"محى",ﳐ:"مخ",ﱇ:"مخ",ﶎ:"مخج",ﶏ:"مخم",ﶹ:"مخى",ﳑ:"مم",ﲉ:"مم",ﱈ:"مم",ﶱ:"ممى",ﱉ:"مى",ﱊ:"مى","𞸍":"ن","𞸭":"ن","𞹍":"ن","𞹭":"ن","𞺍":"ن","𞺭":"ن",ﻧ:"ن",ﻨ:"ن",ﻦ:"ن",ﻥ:"ن","ݨ":"نؕ","ݩ":"ن̆",ﳖ:"نo",ﳯ:"نo",ﶸ:"نجح",ﶽ:"نجح",ﶘ:"نجم",ﶗ:"نجم",ﶙ:"نجى",ﷇ:"نجى",ﳓ:"نح",ﱌ:"نح",ﶕ:"نحم",ﶖ:"نحى",ﶳ:"نحى",ﳔ:"نخ",ﱍ:"نخ",ﲊ:"نر",ﲋ:"نز",ﳕ:"نم",ﳮ:"نم",ﲌ:"نم",ﱎ:"نم",ﶛ:"نمى",ﶚ:"نمى",ﲍ:"نن",ﲎ:"نى",ﱏ:"نى",ﲏ:"نى",ﱐ:"نى",ۂ:"ۀ",ﮥ:"ۀ",ﮤ:"ۀ","𐋤":"و","𞸅":"و","𞺅":"و","𞺥":"و",ﻮ:"و",ﻭ:"و","ࢱ":"و",ۋ:"وۛ",ﯟ:"وۛ",ﯞ:"وۛ",ۇ:"و̓",ﯘ:"و̓",ﯗ:"و̓",ۆ:"و̆",ﯚ:"و̆",ﯙ:"و̆",ۉ:"و̂",ﯣ:"و̂",ﯢ:"و̂",ۈ:"وٰ",ﯜ:"وٰ",ﯛ:"وٰ",ؤ:"وٴ",ﺆ:"وٴ",ﺅ:"وٴ",ٶ:"وٴ",ٷ:"و̓ٴ",ﯝ:"و̓ٴ",ﷸ:"وسلم",ﯡ:"ۅ",ﯠ:"ۅ","ٮ":"ى","𞸜":"ى","𞹼":"ى",ں:"ى","𞸝":"ى","𞹝":"ى",ﮟ:"ى",ﮞ:"ى","ࢽ":"ى",ﯨ:"ى",ﯩ:"ى",ﻰ:"ى",ﻯ:"ى",ي:"ى","𞸉":"ى","𞸩":"ى","𞹉":"ى","𞹩":"ى","𞺉":"ى","𞺩":"ى",ﻳ:"ى",ﻴ:"ى",ﻲ:"ى",ﻱ:"ى",ی:"ى",ﯾ:"ى",ﯿ:"ى",ﯽ:"ى",ﯼ:"ى",ے:"ى",ﮯ:"ى",ﮮ:"ى",ٹ:"ىؕ",ﭨ:"ىؕ",ﭩ:"ىؕ",ﭧ:"ىؕ",ﭦ:"ىؕ",ڻ:"ىؕ",ﮢ:"ىؕ",ﮣ:"ىؕ",ﮡ:"ىؕ",ﮠ:"ىؕ",پ:"ىۛ",ﭘ:"ىۛ",ﭙ:"ىۛ",ﭗ:"ىۛ",ﭖ:"ىۛ",ث:"ىۛ","𞸖":"ىۛ","𞸶":"ىۛ","𞹶":"ىۛ","𞺖":"ىۛ","𞺶":"ىۛ",ﺛ:"ىۛ",ﺜ:"ىۛ",ﺚ:"ىۛ",ﺙ:"ىۛ",ڽ:"ىۛ",ۑ:"ىۛ","ؿ":"ىۛ","ࢷ":"ىۛۢ","ݖ":"ى̆",ێ:"ى̆","ࢺ":"ى̆̇","ؽ":"ى̂","ࢨ":"ىٔ",ﲐ:"ىٰ",ﱝ:"ىٰ",ﳞ:"ىo",ﳱ:"ىo",ﳦ:"ىۛo",ئ:"ىٴ",ﺋ:"ىٴ",ﺌ:"ىٴ",ﺊ:"ىٴ",ﺉ:"ىٴ",ٸ:"ىٴ",ﯫ:"ىٴl",ﯪ:"ىٴl",ﲛ:"ىٴo",ﳠ:"ىٴo",ﯭ:"ىٴo",ﯬ:"ىٴo",ﯸ:"ىٴٻ",ﯷ:"ىٴٻ",ﯶ:"ىٴٻ",ﲗ:"ىٴج",ﰀ:"ىٴج",ﲘ:"ىٴح",ﰁ:"ىٴح",ﲙ:"ىٴخ",ﱤ:"ىٴر",ﱥ:"ىٴز",ﲚ:"ىٴم",ﳟ:"ىٴم",ﱦ:"ىٴم",ﰂ:"ىٴم",ﱧ:"ىٴن",ﯯ:"ىٴو",ﯮ:"ىٴو",ﯱ:"ىٴو̓",ﯰ:"ىٴو̓",ﯳ:"ىٴو̆",ﯲ:"ىٴو̆",ﯵ:"ىٴوٰ",ﯴ:"ىٴوٰ",ﯻ:"ىٴى",ﯺ:"ىٴى",ﱨ:"ىٴى",ﯹ:"ىٴى",ﰃ:"ىٴى",ﱩ:"ىٴى",ﰄ:"ىٴى",ﳚ:"ىج",ﱕ:"ىج",ﰑ:"ىۛج",ﶯ:"ىجى",ﳛ:"ىح",ﱖ:"ىح",ﶮ:"ىحى",ﳜ:"ىخ",ﱗ:"ىخ",ﲑ:"ىر",ﱶ:"ىۛر",ﲒ:"ىز",ﱷ:"ىۛز",ﳝ:"ىم",ﳰ:"ىم",ﲓ:"ىم",ﱘ:"ىم",ﲦ:"ىۛم",ﳥ:"ىۛم",ﱸ:"ىۛم",ﰒ:"ىۛم",ﶝ:"ىمم",ﶜ:"ىمم",ﶰ:"ىمى",ﲔ:"ىن",ﱹ:"ىۛن",ﲕ:"ىى",ﱙ:"ىى",ﲖ:"ىى",ﱚ:"ىى",ﱺ:"ىۛى",ﰓ:"ىۛى",ﱻ:"ىۛى",ﰔ:"ىۛى",ﮱ:"ۓ",ﮰ:"ۓ","𐊸":"ⵀ","⁞":"ⵂ","⸽":"ⵂ","⦙":"ⵂ","︙":"ⵗ","⁝":"ⵗ","⋮":"ⵗ",Մ:"ሆ",Ռ:"ቡ",Ի:"ኮ",Պ:"ጣ",आ:"अा",ऒ:"अाॆ",ओ:"अाे",औ:"अाै","ऄ":"अॆ",ऑ:"अॉ",ऍ:"एॅ",ऎ:"एॆ",ऐ:"एे",ई:"र्इ",ઽ:"ऽ","𑇜":"ꣻ","𑇋":"ऺ","ુ":"ु","ૂ":"ू","ੋ":"ॆ","੍":"्","્":"्",আ:"অা",ৠ:"ঋৃ",ৡ:"ঋৃ","𑒒":"ঘ","𑒔":"চ","𑒖":"জ","𑒘":"ঞ","𑒙":"ট","𑒛":"ড","𑒪":"ণ","𑒞":"ত","𑒟":"থ","𑒠":"দ","𑒡":"ধ","𑒢":"ন","𑒣":"প","𑒩":"ব","𑒧":"ম","𑒨":"য","𑒫":"র","𑒝":"ল","𑒭":"ষ","𑒮":"স","𑓄":"ঽ","𑒰":"া","𑒱":"ি","𑒹":"ে","𑒼":"ো","𑒾":"ৌ","𑓂":"্","𑒽":"ৗ",ਉ:"ੳੁ",ਊ:"ੳੂ",ਆ:"ਅਾ",ਐ:"ਅੈ",ਔ:"ਅੌ",ਇ:"ੲਿ",ਈ:"ੲੀ",ਏ:"ੲੇ",આ:"અા",ઑ:"અાૅ",ઓ:"અાે",ઔ:"અાૈ",ઍ:"અૅ",એ:"અે",ઐ:"અૈ",ଆ:"ଅା","௮":"அ",ர:"ஈ","ா":"ஈ","௫":"ஈு","௨":"உ",ഉ:"உ",ஊ:"உள",ഊ:"உൗ","௭":"எ","௷":"எவ",ஜ:"ஐ",ജ:"ஐ","௧":"க","௪":"ச","௬":"சு","௲":"சூ","ഺ":"டி",ണ:"ண","௺":"நீ","௴":"மீ","௰":"ய",ഴ:"ழ","ௗ":"ள","ை":"ன",ശ:"ஶ","௸":"ஷ","ി":"ி","ീ":"ி","ொ":"ெஈ","ௌ":"ெள","ோ":"ேஈ",ಅ:"అ",ಆ:"ఆ",ಇ:"ఇ",ౠ:"ఋా",ౡ:"ఌా",ಒ:"ఒ",ఔ:"ఒౌ",ಔ:"ఒౌ",ఓ:"ఒౕ",ಓ:"ఒౕ",ಜ:"జ",ಞ:"ఞ",ఢ:"డ̣",ಣ:"ణ",థ:"ధּ",భ:"బ̣",ಯ:"య",ఠ:"రּ",ಱ:"ఱ",ಲ:"ల",ష:"వ̣",హ:"వా",మ:"వు","ూ":"ుా","ౄ":"ృా",ೡ:"ಌಾ",ഈ:"ഇൗ",ഐ:"എെ",ഓ:"ഒാ",ഔ:"ഒൗ",ൡ:"ഞ","൫":"ദ്ര","൹":"നു",ഌ:"നു",ങ:"നു","൯":"ന്","ൻ":"ന്","൬":"ന്ന","൚":"ന്മ",റ:"ര","൪":"ര്","ർ":"ര്","൮":"വ്ര","൶":"ഹ്മ","ൂ":"ു","ൃ":"ു","ൈ":"െെ","෪":"ජ","෫":"ද","𑐓":"𑐴𑑂𑐒","𑐙":"𑐴𑑂𑐘","𑐤":"𑐴𑑂𑐣","𑐪":"𑐴𑑂𑐩","𑐭":"𑐴𑑂𑐬","𑐯":"𑐴𑑂𑐮","𑗘":"𑖂","𑗙":"𑖂","𑗚":"𑖃","𑗛":"𑖄","𑗜":"𑖲","𑗝":"𑖳",ฃ:"ข",ด:"ค",ต:"ค",ม:"ฆ",ຈ:"จ",ซ:"ช",ฏ:"ฎ",ท:"ฑ",ບ:"บ",ປ:"ป",ຝ:"ฝ",ພ:"พ",ຟ:"ฟ",ฦ:"ภ",ຍ:"ย","។":"ฯ",ๅ:"า",ำ:"̊า","ិ":"ิ","ី":"ี","ឹ":"ึ","ឺ":"ื","ຸ":"ุ","ູ":"ู",แ:"เเ",ໜ:"ຫນ",ໝ:"ຫມ",ຳ:"̊າ","༂":"འུྂཿ","༃":"འུྂ༔",ཪ:"ར",ༀ:"ཨོཾ","ཷ":"ྲཱྀ","ཹ":"ླཱྀ","𑲲":"𑲪","ႁ":"ဂှ",က:"ဂာ","ၰ":"ဃှ","ၦ":"ပှ",ဟ:"ပာ","ၯ":"ပာှ","ၾ":"ၽှ",ဩ:"သြ",ဪ:"သြော်","႞":"ႃ̊",ឣ:"អ","᧐":"ᦞ","᧑":"ᦱ","᪀":"ᩅ","᪐":"ᩅ","꩓":"ꨁ","꩖":"ꨣ","᭒":"ᬍ","᭓":"ᬑ","᭘":"ᬨ","ꦣ":"ꦝ",ᢖ:"ᡜ",ᡕ:"ᠵ",ῶ:"Ꮿ",ᐍ:"ᐁ·",ᐫ:"ᐁᐠ",ᐑ:"ᐄ·",ᐓ:"ᐅ·",ᐭ:"ᐅᐠ",ᐕ:"ᐆ·",ᐘ:"ᐊ·",ᐮ:"ᐊᐠ",ᐚ:"ᐋ·","ᣝ":"ᐞᣟ",ᓑ:"ᐡ",ᕀ:"ᐩ",ᐿ:"ᐲ·",ᑃ:"ᐴ·","⍩":"ᐵ",ᑇ:"ᐹ·",ᑜ:"ᑏ·","⸧":"ᑐ","⊃":"ᑐ",ᑞ:"ᑐ·",ᑩ:"ᑐ'","⟉":"ᑐ/","⫗":"ᑐᑕ",ᑠ:"ᑑ·","⸦":"ᑕ","⊂":"ᑕ",ᑢ:"ᑕ·",ᑪ:"ᑕ'",ᑤ:"ᑖ·",ᑵ:"ᑫ·",ᒅ:"ᑫ'",ᑹ:"ᑮ·",ᑽ:"ᑰ·",ᘃ:"ᒉ",ᒓ:"ᒉ·",ᒕ:"ᒋ·",ᒗ:"ᒌ·",ᒛ:"ᒎ·",ᘂ:"ᒐ",ᒝ:"ᒐ·",ᒟ:"ᒑ·",ᒭ:"ᒣ·",ᒱ:"ᒦ·",ᒳ:"ᒧ·",ᒵ:"ᒨ·",ᒹ:"ᒫ·",ᓊ:"ᓀ·","ᣇ":"ᓂ·","ᣉ":"ᓃ·","ᣋ":"ᓄ·","ᣍ":"ᓅ·",ᓌ:"ᓇ·",ᓎ:"ᓈ·",ᘄ:"ᓓ",ᓝ:"ᓓ·",ᓟ:"ᓕ·",ᓡ:"ᓖ·",ᓣ:"ᓗ·",ᓥ:"ᓘ·",ᘇ:"ᓚ",ᓧ:"ᓚ·",ᓩ:"ᓛ·",ᓷ:"ᓭ·",ᓹ:"ᓯ·",ᓻ:"ᓰ·",ᓽ:"ᓱ·",ᓿ:"ᓲ·",ᔁ:"ᓴ·",ᔃ:"ᓵ·",ᔌ:"ᔋ<",ᔎ:"ᔋb",ᔍ:"ᔋᑕ",ᔏ:"ᔋᒐ",ᔘ:"ᔐ·",ᔚ:"ᔑ·",ᔜ:"ᔒ·",ᔞ:"ᔓ·",ᔠ:"ᔔ·",ᔢ:"ᔕ·",ᔤ:"ᔖ·",ᔲ:"ᔨ·",ᔴ:"ᔩ·",ᔶ:"ᔪ·",ᔸ:"ᔫ·",ᔺ:"ᔭ·",ᔼ:"ᔮ·",ᘢ:"ᕃ","ᣠ":"ᕃ·",ᘣ:"ᕆ",ᘤ:"ᕊ",ᕏ:"ᕌ·",ᖃ:"ᕐb",ᖄ:"ᕐḃ",ᖁ:"ᕐd",ᕿ:"ᕐP",ᙯ:"ᕐᑫ",ᕾ:"ᕐᑬ",ᖀ:"ᕐᑮ",ᖂ:"ᕐᑰ",ᖅ:"ᕐᒃ",ᕜ:"ᕚ·","ᣣ":"ᕞ·","ᣤ":"ᕦ·",ᕩ:"ᕧ·","ᣥ":"ᕫ·","ᣨ":"ᖆ·",ᖑ:"ᖕJ",ᙰ:"ᖕᒉ",ᖎ:"ᖕᒊ",ᖏ:"ᖕᒋ",ᖐ:"ᖕᒌ",ᖒ:"ᖕᒎ",ᖓ:"ᖕᒐ",ᖔ:"ᖕᒑ",ᙳ:"ᖖJ",ᙱ:"ᖖᒋ",ᙲ:"ᖖᒌ",ᙴ:"ᖖᒎ",ᙵ:"ᖖᒐ",ᙶ:"ᖖᒑ","ᣪ":"ᖗ·","ᙷ":"ᖧ·","ᙸ":"ᖨ·","ᙹ":"ᖩ·","ᙺ":"ᖪ·","ᙻ":"ᖫ·","ᙼ":"ᖬ·","ᙽ":"ᖭ·","⪫":"ᗒ","⪪":"ᗕ","ꓷ":"ᗡ","ᣰ":"ᗴ·","ᣲ":"ᘛ·","ᶻ":"ᙆ","ꓭ":"ᙠ","ᶺ":"ᣔ","ᴾ":"ᣖ","ᣜ":"ᣟᐞ",ˡ:"ᣳ",ʳ:"ᣴ",ˢ:"ᣵ","ᣛ":"ᣵ","ꚰ":"ᚹ",ᛡ:"ᚼ","⍿":"ᚽ",ᛂ:"ᚽ","𝈿":"ᛋ","↑":"ᛏ","↿":"ᛐ","⥮":"ᛐ⇂","⥣":"ᛐᛚ","ⵣ":"ᛯ","↾":"ᛚ","⨡":"ᛚ","⋄":"ᛜ","◇":"ᛜ","◊":"ᛜ","♢":"ᛜ","🝔":"ᛜ","𑢷":"ᛜ","𐊔":"ᛜ","⍚":"ᛜ̲","⋈":"ᛞ","⨝":"ᛞ","𐓐":"ᛦ","↕":"ᛨ","𐳼":"𐲂","𐳺":"𐲥",ㄱ:"ᄀ",ᆨ:"ᄀ",ᄁ:"ᄀᄀ",ㄲ:"ᄀᄀ",ᆩ:"ᄀᄀ","ᇺ":"ᄀᄂ","ᅚ":"ᄀᄃ",ᇃ:"ᄀᄅ","ᇻ":"ᄀᄇ",ᆪ:"ᄀᄉ",ㄳ:"ᄀᄉ",ᇄ:"ᄀᄉᄀ","ᇼ":"ᄀᄎ","ᇽ":"ᄀᄏ","ᇾ":"ᄀᄒ",ㄴ:"ᄂ",ᆫ:"ᄂ",ᄓ:"ᄂᄀ",ᇅ:"ᄂᄀ",ᄔ:"ᄂᄂ",ㅥ:"ᄂᄂ","ᇿ":"ᄂᄂ",ᄕ:"ᄂᄃ",ㅦ:"ᄂᄃ",ᇆ:"ᄂᄃ","ퟋ":"ᄂᄅ",ᄖ:"ᄂᄇ","ᅛ":"ᄂᄉ",ᇇ:"ᄂᄉ",ㅧ:"ᄂᄉ","ᅜ":"ᄂᄌ",ᆬ:"ᄂᄌ",ㄵ:"ᄂᄌ","ퟌ":"ᄂᄎ",ᇉ:"ᄂᄐ","ᅝ":"ᄂᄒ",ᆭ:"ᄂᄒ",ㄶ:"ᄂᄒ",ᇈ:"ᄂᅀ",ㅨ:"ᄂᅀ",ㄷ:"ᄃ",ᆮ:"ᄃ",ᄗ:"ᄃᄀ",ᇊ:"ᄃᄀ",ᄄ:"ᄃᄃ",ㄸ:"ᄃᄃ","ퟍ":"ᄃᄃ","ퟎ":"ᄃᄃᄇ","ᅞ":"ᄃᄅ",ᇋ:"ᄃᄅ","ꥠ":"ᄃᄆ","ꥡ":"ᄃᄇ","ퟏ":"ᄃᄇ","ꥢ":"ᄃᄉ","ퟐ":"ᄃᄉ","ퟑ":"ᄃᄉᄀ","ꥣ":"ᄃᄌ","ퟒ":"ᄃᄌ","ퟓ":"ᄃᄎ","ퟔ":"ᄃᄐ",ㄹ:"ᄅ",ᆯ:"ᄅ","ꥤ":"ᄅᄀ",ᆰ:"ᄅᄀ",ㄺ:"ᄅᄀ","ꥥ":"ᄅᄀᄀ","ퟕ":"ᄅᄀᄀ",ᇌ:"ᄅᄀᄉ",ㅩ:"ᄅᄀᄉ","ퟖ":"ᄅᄀᄒ",ᄘ:"ᄅᄂ",ᇍ:"ᄅᄂ","ꥦ":"ᄅᄃ",ᇎ:"ᄅᄃ",ㅪ:"ᄅᄃ","ꥧ":"ᄅᄃᄃ",ᇏ:"ᄅᄃᄒ",ᄙ:"ᄅᄅ",ᇐ:"ᄅᄅ","ퟗ":"ᄅᄅᄏ","ꥨ":"ᄅᄆ",ᆱ:"ᄅᄆ",ㄻ:"ᄅᄆ",ᇑ:"ᄅᄆᄀ",ᇒ:"ᄅᄆᄉ","ퟘ":"ᄅᄆᄒ","ꥩ":"ᄅᄇ",ᆲ:"ᄅᄇ",ㄼ:"ᄅᄇ","ퟙ":"ᄅᄇᄃ","ꥪ":"ᄅᄇᄇ",ᇓ:"ᄅᄇᄉ",ㅫ:"ᄅᄇᄉ","ꥫ":"ᄅᄇᄋ",ᇕ:"ᄅᄇᄋ","ퟚ":"ᄅᄇᄑ",ᇔ:"ᄅᄇᄒ","ꥬ":"ᄅᄉ",ᆳ:"ᄅᄉ",ㄽ:"ᄅᄉ",ᇖ:"ᄅᄉᄉ",ᄛ:"ᄅᄋ","ퟝ":"ᄅᄋ","ꥭ":"ᄅᄌ","ꥮ":"ᄅᄏ",ᇘ:"ᄅᄏ",ᆴ:"ᄅᄐ",ㄾ:"ᄅᄐ",ᆵ:"ᄅᄑ",ㄿ:"ᄅᄑ",ᄚ:"ᄅᄒ",ㅀ:"ᄅᄒ",ᄻ:"ᄅᄒ",ᆶ:"ᄅᄒ","ퟲ":"ᄅᄒ",ᇗ:"ᄅᅀ",ㅬ:"ᄅᅀ","ퟛ":"ᄅᅌ",ᇙ:"ᄅᅙ",ㅭ:"ᄅᅙ","ퟜ":"ᄅᅙᄒ",ㅁ:"ᄆ",ᆷ:"ᄆ","ꥯ":"ᄆᄀ",ᇚ:"ᄆᄀ","ퟞ":"ᄆᄂ","ퟟ":"ᄆᄂᄂ","ꥰ":"ᄆᄃ",ᇛ:"ᄆᄅ","ퟠ":"ᄆᄆ",ᄜ:"ᄆᄇ",ㅮ:"ᄆᄇ",ᇜ:"ᄆᄇ","ퟡ":"ᄆᄇᄉ","ꥱ":"ᄆᄉ",ᇝ:"ᄆᄉ",ㅯ:"ᄆᄉ",ᇞ:"ᄆᄉᄉ",ᄝ:"ᄆᄋ",ㅱ:"ᄆᄋ",ᇢ:"ᄆᄋ","ퟢ":"ᄆᄌ",ᇠ:"ᄆᄎ",ᇡ:"ᄆᄒ",ᇟ:"ᄆᅀ",ㅰ:"ᄆᅀ",ㅂ:"ᄇ",ᆸ:"ᄇ",ᄞ:"ᄇᄀ",ㅲ:"ᄇᄀ",ᄟ:"ᄇᄂ",ᄠ:"ᄇᄃ",ㅳ:"ᄇᄃ","ퟣ":"ᄇᄃ",ᇣ:"ᄇᄅ","ퟤ":"ᄇᄅᄑ","ퟥ":"ᄇᄆ",ᄈ:"ᄇᄇ",ㅃ:"ᄇᄇ","ퟦ":"ᄇᄇ",ᄬ:"ᄇᄇᄋ",ㅹ:"ᄇᄇᄋ",ᄡ:"ᄇᄉ",ㅄ:"ᄇᄉ",ᆹ:"ᄇᄉ",ᄢ:"ᄇᄉᄀ",ㅴ:"ᄇᄉᄀ",ᄣ:"ᄇᄉᄃ",ㅵ:"ᄇᄉᄃ","ퟧ":"ᄇᄉᄃ",ᄤ:"ᄇᄉᄇ",ᄥ:"ᄇᄉᄉ",ᄦ:"ᄇᄉᄌ","ꥲ":"ᄇᄉᄐ",ᄫ:"ᄇᄋ",ㅸ:"ᄇᄋ",ᇦ:"ᄇᄋ",ᄧ:"ᄇᄌ",ㅶ:"ᄇᄌ","ퟨ":"ᄇᄌ",ᄨ:"ᄇᄎ","ퟩ":"ᄇᄎ","ꥳ":"ᄇᄏ",ᄩ:"ᄇᄐ",ㅷ:"ᄇᄐ",ᄪ:"ᄇᄑ",ᇤ:"ᄇᄑ","ꥴ":"ᄇᄒ",ᇥ:"ᄇᄒ",ㅅ:"ᄉ",ᆺ:"ᄉ",ᄭ:"ᄉᄀ",ㅺ:"ᄉᄀ",ᇧ:"ᄉᄀ",ᄮ:"ᄉᄂ",ㅻ:"ᄉᄂ",ᄯ:"ᄉᄃ",ㅼ:"ᄉᄃ",ᇨ:"ᄉᄃ",ᄰ:"ᄉᄅ",ᇩ:"ᄉᄅ",ᄱ:"ᄉᄆ","ퟪ":"ᄉᄆ",ᄲ:"ᄉᄇ",ㅽ:"ᄉᄇ",ᇪ:"ᄉᄇ",ᄳ:"ᄉᄇᄀ","ퟫ":"ᄉᄇᄋ",ᄊ:"ᄉᄉ",ㅆ:"ᄉᄉ",ᆻ:"ᄉᄉ","ퟬ":"ᄉᄉᄀ","ퟭ":"ᄉᄉᄃ","ꥵ":"ᄉᄉᄇ",ᄴ:"ᄉᄉᄉ",ᄵ:"ᄉᄋ",ᄶ:"ᄉᄌ",ㅾ:"ᄉᄌ","ퟯ":"ᄉᄌ",ᄷ:"ᄉᄎ","ퟰ":"ᄉᄎ",ᄸ:"ᄉᄏ",ᄹ:"ᄉᄐ","ퟱ":"ᄉᄐ",ᄺ:"ᄉᄑ","ퟮ":"ᄉᅀ",ㅇ:"ᄋ",ᆼ:"ᄋ",ᅁ:"ᄋᄀ",ᇬ:"ᄋᄀ",ᇭ:"ᄋᄀᄀ",ᅂ:"ᄋᄃ","ꥶ":"ᄋᄅ",ᅃ:"ᄋᄆ",ᅄ:"ᄋᄇ",ᅅ:"ᄋᄉ",ᇱ:"ᄋᄉ",ㆂ:"ᄋᄉ",ᅇ:"ᄋᄋ",ㆀ:"ᄋᄋ",ᇮ:"ᄋᄋ",ᅈ:"ᄋᄌ",ᅉ:"ᄋᄎ",ᇯ:"ᄋᄏ",ᅊ:"ᄋᄐ",ᅋ:"ᄋᄑ","ꥷ":"ᄋᄒ",ᅆ:"ᄋᅀ",ᇲ:"ᄋᅀ",ㆃ:"ᄋᅀ",ㅈ:"ᄌ",ᆽ:"ᄌ","ퟷ":"ᄌᄇ","ퟸ":"ᄌᄇᄇ",ᅍ:"ᄌᄋ",ᄍ:"ᄌᄌ",ㅉ:"ᄌᄌ","ퟹ":"ᄌᄌ","ꥸ":"ᄌᄌᄒ",ㅊ:"ᄎ",ᆾ:"ᄎ",ᅒ:"ᄎᄏ",ᅓ:"ᄎᄒ",ㅋ:"ᄏ",ᆿ:"ᄏ",ㅌ:"ᄐ",ᇀ:"ᄐ","ꥹ":"ᄐᄐ",ㅍ:"ᄑ",ᇁ:"ᄑ",ᅖ:"ᄑᄇ",ᇳ:"ᄑᄇ","ퟺ":"ᄑᄉ",ᅗ:"ᄑᄋ",ㆄ:"ᄑᄋ",ᇴ:"ᄑᄋ","ퟻ":"ᄑᄐ","ꥺ":"ᄑᄒ",ㅎ:"ᄒ",ᇂ:"ᄒ",ᇵ:"ᄒᄂ",ᇶ:"ᄒᄅ",ᇷ:"ᄒᄆ",ᇸ:"ᄒᄇ","ꥻ":"ᄒᄉ",ᅘ:"ᄒᄒ",ㆅ:"ᄒᄒ",ᄽ:"ᄼᄼ",ᄿ:"ᄾᄾ",ㅿ:"ᅀ",ᇫ:"ᅀ","ퟳ":"ᅀᄇ","ퟴ":"ᅀᄇᄋ",ㆁ:"ᅌ",ᇰ:"ᅌ","ퟵ":"ᅌᄆ","ퟶ":"ᅌᄒ",ᅏ:"ᅎᅎ",ᅑ:"ᅐᅐ",ㆆ:"ᅙ",ᇹ:"ᅙ","ꥼ":"ᅙᅙ",ㅤ:"ᅠ",ㅏ:"ᅡ","ᆣ":"ᅡー",ᅶ:"ᅡᅩ",ᅷ:"ᅡᅮ",ᅢ:"ᅡ丨",ㅐ:"ᅡ丨",ㅑ:"ᅣ",ᅸ:"ᅣᅩ",ᅹ:"ᅣᅭ","ᆤ":"ᅣᅮ",ᅤ:"ᅣ丨",ㅒ:"ᅣ丨",ㅓ:"ᅥ",ᅼ:"ᅥー",ᅺ:"ᅥᅩ",ᅻ:"ᅥᅮ",ᅦ:"ᅥ丨",ㅔ:"ᅥ丨",ㅕ:"ᅧ","ᆥ":"ᅧᅣ",ᅽ:"ᅧᅩ",ᅾ:"ᅧᅮ",ᅨ:"ᅧ丨",ㅖ:"ᅧ丨",ㅗ:"ᅩ",ᅪ:"ᅩᅡ",ㅘ:"ᅩᅡ",ᅫ:"ᅩᅡ丨",ㅙ:"ᅩᅡ丨","ᆦ":"ᅩᅣ","ᆧ":"ᅩᅣ丨",ᅿ:"ᅩᅥ",ᆀ:"ᅩᅥ丨","ힰ":"ᅩᅧ",ᆁ:"ᅩᅧ丨",ᆂ:"ᅩᅩ","ힱ":"ᅩᅩ丨",ᆃ:"ᅩᅮ",ᅬ:"ᅩ丨",ㅚ:"ᅩ丨",ㅛ:"ᅭ","ힲ":"ᅭᅡ","ힳ":"ᅭᅡ丨",ᆄ:"ᅭᅣ",ㆇ:"ᅭᅣ",ᆆ:"ᅭᅣ",ᆅ:"ᅭᅣ丨",ㆈ:"ᅭᅣ丨","ힴ":"ᅭᅥ",ᆇ:"ᅭᅩ",ᆈ:"ᅭ丨",ㆉ:"ᅭ丨",ㅜ:"ᅮ",ᆉ:"ᅮᅡ",ᆊ:"ᅮᅡ丨",ᅯ:"ᅮᅥ",ㅝ:"ᅮᅥ",ᆋ:"ᅮᅥー",ᅰ:"ᅮᅥ丨",ㅞ:"ᅮᅥ丨","ힵ":"ᅮᅧ",ᆌ:"ᅮᅧ丨",ᆍ:"ᅮᅮ",ᅱ:"ᅮ丨",ㅟ:"ᅮ丨","ힶ":"ᅮ丨丨",ㅠ:"ᅲ",ᆎ:"ᅲᅡ","ힷ":"ᅲᅡ丨",ᆏ:"ᅲᅥ",ᆐ:"ᅲᅥ丨",ᆑ:"ᅲᅧ",ㆊ:"ᅲᅧ",ᆒ:"ᅲᅧ丨",ㆋ:"ᅲᅧ丨","ힸ":"ᅲᅩ",ᆓ:"ᅲᅮ",ᆔ:"ᅲ丨",ㆌ:"ᅲ丨",ㆍ:"ᆞ","ퟅ":"ᆞᅡ",ᆟ:"ᆞᅥ","ퟆ":"ᆞᅥ丨",ᆠ:"ᆞᅮ",ᆢ:"ᆞᆞ",ᆡ:"ᆞ丨",ㆎ:"ᆞ丨",ヘ:"へ","⍁":"〼","⧄":"〼","꒞":"ꁊ","꒬":"ꁐ","꒜":"ꃀ","꒨":"ꄲ","꒿":"ꉙ","꒾":"ꊱ","꒔":"ꋍ","꓀":"ꎫ","꓂":"ꎵ","꒺":"ꎿ","꒰":"ꏂ","꒧":"ꑘ","⊥":"ꓕ","⟂":"ꓕ","𝈜":"ꓕ","Ʇ":"ꓕ","Ꞟ":"ꓤ","⅁":"ꓨ","⅂":"ꓶ","𝈕":"ꓶ","𝈫":"ꓶ","𖼦":"ꓶ","𐐑":"ꓶ","⅃":"𖼀","𑫦":"𑫥𑫯","𑫨":"𑫥𑫥","𑫩":"𑫥𑫥𑫯","𑫪":"𑫥𑫥𑫰","𑫧":"𑫥𑫰","𑫴":"𑫳𑫯","𑫶":"𑫳𑫳","𑫷":"𑫳𑫳𑫯","𑫸":"𑫳𑫳𑫰","𑫵":"𑫳𑫰","𑫬":"𑫫𑫯","𑫭":"𑫫𑫫","𑫮":"𑫫𑫫𑫯","⊕":"𐊨","⨁":"𐊨","🜨":"𐊨","Ꚛ":"𐊨","▽":"𐊼","𝈔":"𐊼","🜄":"𐊼","⧖":"𐋀","ꞛ":"𐐺","Ꞛ":"𐐒","𐒠":"𐒆","𐏑":"𐎂","𐏓":"𐎓","𒀸":"𐎚","☥":"𐦞","𓋹":"𐦞","〹":"卄",不:"不","丽":"丽","並":"並","⎜":"丨","⎟":"丨","⎢":"丨","⎥":"丨","⎪":"丨","⎮":"丨","㇑":"丨",ᅵ:"丨",ㅣ:"丨","⼁":"丨",ᆜ:"丨ー",ᆘ:"丨ᅡ",ᆙ:"丨ᅣ","ힽ":"丨ᅣᅩ","ힾ":"丨ᅣ丨","ힿ":"丨ᅧ","ퟀ":"丨ᅧ丨",ᆚ:"丨ᅩ","ퟁ":"丨ᅩ丨","ퟂ":"丨ᅭ",ᆛ:"丨ᅮ","ퟃ":"丨ᅲ",ᆝ:"丨ᆞ","ퟄ":"丨丨",串:"串","丸":"丸",丹:"丹","乁":"乁","㇠":"乙","⼄":"乙","㇟":"乚","⺃":"乚","㇖":"乛","⺂":"乛","⻲":"亀",亂:"亂","㇚":"亅","⼅":"亅",了:"了",ニ:"二","⼆":"二","𠄢":"𠄢","⼇":"亠",亮:"亮","⼈":"人",イ:"亻","⺅":"亻",什:"什","仌":"仌",令:"令","你":"你",倂:"併","倂":"併","侀":"侀",來:"來",例:"例","侮":"侮","侮":"侮","侻":"侻",便:"便",值:"値",倫:"倫","偺":"偺","備":"備","像":"像",僚:"僚","僧":"僧","僧":"僧","㒞":"㒞","⼉":"儿",兀:"兀","⺎":"兀","充":"充","免":"免","免":"免","兔":"兔","兤":"兤","⼊":"入","內":"內","全":"全",兩:"兩",ハ:"八","⼋":"八",六:"六","具":"具","𠔜":"𠔜","𠔥":"𠔥","冀":"冀","㒹":"㒹","⼌":"冂","再":"再","𠕋":"𠕋","冒":"冒","冕":"冕","㒻":"㒻","最":"最","⼍":"冖","冗":"冗","冤":"冤","⼎":"冫","冬":"冬","况":"况","况":"况",冷:"冷",凉:"凉",凌:"凌",凜:"凜",凞:"凞","⼏":"几","𠘺":"𠘺","凵":"凵","⼐":"凵","⼑":"刀","⺉":"刂","刃":"刃",切:"切","切":"切",列:"列",利:"利","㓟":"㓟",刺:"刺","刻":"刻","剆":"剆","割":"割","剷":"剷",劉:"劉","𠠄":"𠠄",カ:"力",力:"力","⼒":"力",劣:"劣","㔕":"㔕","劳":"劳","勇":"勇","勇":"勇","勉":"勉","勉":"勉",勒:"勒",勞:"勞","勤":"勤","勤":"勤",勵:"勵","⼓":"勹","勺":"勺","勺":"勺","包":"包","匆":"匆","𠣞":"𠣞","⼔":"匕",北:"北","北":"北","⼕":"匚","⼖":"匸",匿:"匿","⼗":"十","〸":"十","〺":"卅","卉":"卉","࿖":"卍","࿕":"卐","卑":"卑","卑":"卑","博":"博",ト:"卜","⼘":"卜","⼙":"卩","⺋":"㔾","即":"即",卵:"卵","卽":"卽","卿":"卿","卿":"卿","卿":"卿","⼚":"厂","𠨬":"𠨬","⼛":"厶",參:"參","⼜":"又","及":"及","叟":"叟","𠭣":"𠭣",ロ:"口","⼝":"口",囗:"口","⼞":"口",句:"句","叫":"叫","叱":"叱","吆":"吆",吏:"吏",吝:"吝","吸":"吸",呂:"呂","呈":"呈","周":"周","咞":"咞","咢":"咢",咽:"咽",䎛:"㖈","哶":"哶","唐":"唐","啓":"啓",啟:"啓","啕":"啕","啣":"啣","善":"善","善":"善",喇:"喇","喙":"喙","喙":"喙","喝":"喝","喝":"喝","喫":"喫","喳":"喳",嗀:"嗀","嗂":"嗂","嗢":"嗢","嘆":"嘆","嘆":"嘆","噑":"噑","噴":"噴","器":"器",囹:"囹","圖":"圖","圗":"圗","⼟":"土",士:"土","⼠":"土","型":"型","城":"城",㦳:"㘽","埴":"埴","堍":"堍","報":"報","堲":"堲","塀":"塀",塚:"塚","塚":"塚",塞:"塞",填:"塡",壿:"墫","墬":"墬","墳":"墳",壘:"壘",壟:"壟","𡓤":"𡓤","壮":"壮","売":"売","壷":"壷","⼡":"夂","夆":"夆","⼢":"夊",タ:"夕","⼣":"夕","多":"多","夢":"夢","⼤":"大","奄":"奄",奈:"奈",契:"契","奔":"奔","奢":"奢",女:"女","⼥":"女","𡚨":"𡚨","𡛪":"𡛪","姘":"姘","姬":"姬","娛":"娛","娧":"娧","婢":"婢","婦":"婦",嬀:"媯","㛮":"㛮","㛼":"㛼","媵":"媵","嬈":"嬈","嬨":"嬨","嬾":"嬾","嬾":"嬾","⼦":"子","⼧":"宀",宅:"宅","𡧈":"𡧈","寃":"寃","寘":"寘",寧:"寧",寧:"寧","寧":"寧",寮:"寮","寳":"寳","𡬘":"𡬘","⼨":"寸","寿":"寿","将":"将","⼩":"小","尢":"尢","⺐":"尢","⼪":"尢","⺏":"尣","㞁":"㞁","⼫":"尸",尿:"尿","屠":"屠",屢:"屢","層":"層",履:"履","屮":"屮","屮":"屮","⼬":"屮","𡴋":"𡴋","⼭":"山","峀":"峀","岍":"岍","𡷤":"𡷤","𡷦":"𡷦",崙:"崙","嵃":"嵃",嵐:"嵐","嵫":"嵫","嵮":"嵮","嵼":"嵼","嶲":"嶲",嶺:"嶺","⼮":"巛","巢":"巢",エ:"工","⼯":"工","⼰":"己","⺒":"巳","㠯":"㠯","巽":"巽","⼱":"巾",帲:"帡","帨":"帨","帽":"帽","幩":"幩","㡢":"㡢","𢆃":"𢆃","⼲":"干",年:"年","𢆟":"𢆟","⺓":"幺","⼳":"幺","⼴":"广",度:"度","㡼":"㡼","庰":"庰","庳":"庳","庶":"庶",廊:"廊","廊":"廊",廉:"廉","廒":"廒",廓:"廓","廙":"廙",廬:"廬","⼵":"廴","廾":"廾","⼶":"廾","𢌱":"𢌱","𢌱":"𢌱",弄:"弄","⼷":"弋","⼸":"弓","弢":"弢","弢":"弢","⼹":"彐","⺔":"彑","当":"当","㣇":"㣇","⼺":"彡","形":"形","彩":"彩","彫":"彫","⼻":"彳",律:"律","㣣":"㣣","徚":"徚",復:"復","徭":"徭","⼼":"心","⺖":"忄","⺗":"㣺","忍":"忍","志":"志",念:"念","忹":"忹",怒:"怒",怜:"怜","恵":"恵","㤜":"㤜","㤺":"㤺","悁":"悁","悔":"悔","悔":"悔","惇":"惇","惘":"惘",惡:"惡","𢛔":"𢛔","愈":"愈","慨":"慨",慄:"慄","慈":"慈","慌":"慌","慌":"慌","慎":"慎","慎":"慎","慠":"慠","慺":"慺","憎":"憎","憎":"憎","憎":"憎",憐:"憐","憤":"憤","憯":"憯","憲":"憲","𢡄":"𢡄","𢡊":"𢡊","懞":"懞","懲":"懲","懲":"懲","懲":"懲",懶:"懶","懶":"懶",戀:"戀","⼽":"戈","成":"成","戛":"戛",戮:"戮","戴":"戴","⼾":"戶",戸:"戶","⼿":"手","⺘":"扌","扝":"扝","抱":"抱",拉:"拉",拏:"拏",拓:"拓","拔":"拔","拼":"拼",拾:"拾","𢬌":"𢬌","挽":"挽","捐":"捐","捨":"捨",捻:"捻","掃":"掃",掠:"掠","掩":"掩","揄":"揄","揤":"揤","摒":"摒","𢯱":"𢯱","搜":"搜","搢":"搢","揅":"揅","摩":"摩","摷":"摷","摾":"摾","㨮":"㨮",搉:"㩁",撚:"撚","撝":"撝",擄:"擄","㩬":"㩬","⽀":"支","⽁":"攴","⺙":"攵","敏":"敏","敏":"敏","敖":"敖","敬":"敬",數:"數","𣀊":"𣀊","⽂":"文","⻫":"斉","⽃":"斗",料:"料","⽄":"斤","⽅":"方",旅:"旅","⽆":"无","⺛":"旡","既":"既","旣":"旣","⽇":"日",易:"易",曶:"㫚","㫤":"㫤","晉":"晉",晩:"晚",晴:"晴","晴":"晴","暑":"暑","暑":"暑",暈:"暈","㬈":"㬈","暜":"暜",暴:"暴",曆:"曆","㬙":"㬙","𣊸":"𣊸","⽈":"曰",更:"更","書":"書","⽉":"月","𣍟":"𣍟",肦:"朌",胐:"朏",胊:"朐",脁:"朓",胶:"㬵",朗:"朗","朗":"朗","朗":"朗",脧:"朘","望":"望","望":"望",幐:"㬺",䐠:"㬻","𣎓":"𣎓",膧:"朣","𣎜":"𣎜","⽊":"木",李:"李","杓":"杓","杖":"杖","杞":"杞","𣏃":"𣏃",柿:"杮",杻:"杻","枅":"枅",林:"林","㭉":"㭉","𣏕":"𣏕",柳:"柳","柺":"柺",栗:"栗","栟":"栟","桒":"桒","𣑭":"𣑭",梁:"梁","梅":"梅","梅":"梅","梎":"梎",梨:"梨","椔":"椔","楂":"楂","㮝":"㮝","㮝":"㮝",槩:"㮣",樧:"榝","榣":"榣","槪":"槪",樂:"樂",樂:"樂",樂:"樂",樓:"樓","𣚣":"𣚣","檨":"檨",櫓:"櫓","櫛":"櫛",欄:"欄","㰘":"㰘","⽋":"欠","次":"次","𣢧":"𣢧","歔":"歔","㱎":"㱎","⽌":"止","⻭":"歯","歲":"歲",歷:"歷","歹":"歹","⽍":"歹","⺞":"歺","殟":"殟",殮:"殮","⽎":"殳",殺:"殺","殺":"殺","殺":"殺","殻":"殻","𣪍":"𣪍","⽏":"毋","⺟":"母","𣫺":"𣫺","⽐":"比","⽑":"毛","⽒":"氏","⺠":"民","⽓":"气","⽔":"水","⺡":"氵","⺢":"氺","汎":"汎","汧":"汧",沈:"沈","沿":"沿",泌:"泌","泍":"泍",泥:"泥","𣲼":"𣲼",洛:"洛",洞:"洞","洴":"洴","派":"派",流:"流","流":"流","流":"流","洖":"洖","浩":"浩",浪:"浪","海":"海","海":"海","浸":"浸","涅":"涅","𣴞":"𣴞",淋:"淋",淚:"淚",淪:"淪","淹":"淹","渚":"渚","港":"港","湮":"湮",潙:"溈","滋":"滋","滋":"滋",溜:"溜",溺:"溺","滇":"滇",滑:"滑","滛":"滛","㴳":"㴳",漏:"漏","漢":"漢","漢":"漢",漣:"漣","𣻑":"𣻑","潮":"潮","𣽞":"𣽞","𣾎":"𣾎","濆":"濆",濫:"濫",濾:"濾","瀛":"瀛","瀞":"瀞","瀞":"瀞","瀹":"瀹","灊":"灊","㶖":"㶖","⽕":"火","⺣":"灬","灰":"灰","灷":"灷","災":"災",炙:"炙","炭":"炭",烈:"烈",烙:"烙","煮":"煮","煮":"煮","𤉣":"𤉣","煅":"煅",煉:"煉","𤋮":"𤋮","熜":"熜",燎:"燎",燐:"燐","𤎫":"𤎫",爐:"爐",爛:"爛","爨":"爨","⽖":"爪","爫":"爫","⺤":"爫","爵":"爵","爵":"爵","⽗":"父","⽘":"爻","⺦":"丬","⽙":"爿","⽚":"片","牐":"牐","⽛":"牙","𤘈":"𤘈","⽜":"牛",牢:"牢","犀":"犀","犕":"犕","⽝":"犬","⺨":"犭","犯":"犯",狀:"狀","𤜵":"𤜵",狼:"狼",猪:"猪","猪":"猪","𤠔":"𤠔",獵:"獵","獺":"獺","⽞":"玄",率:"率",率:"率","⽟":"玉","王":"王","㺬":"㺬","玥":"玥",玲:"玲","㺸":"㺸","㺸":"㺸",珞:"珞",琉:"琉",理:"理","琢":"琢","瑇":"瑇","瑜":"瑜",瑩:"瑩","瑱":"瑱","瑱":"瑱","璅":"璅",璉:"璉",璘:"璘","瓊":"瓊","⽠":"瓜","⽡":"瓦","㼛":"㼛","甆":"甆","⽢":"甘","⽣":"生","甤":"甤","⽤":"用","⽥":"田","画":"画","甾":"甾","𤰶":"𤰶",留:"留",略:"略",異:"異","異":"異","𤲒":"𤲒","⽦":"疋","⽧":"疒",痢:"痢","瘐":"瘐","瘟":"瘟","瘝":"瘝",療:"療",癩:"癩","⽨":"癶","⽩":"白","𤾡":"𤾡","𤾸":"𤾸","⽪":"皮","⽫":"皿","𥁄":"𥁄","㿼":"㿼",益:"益","益":"益","盛":"盛",盧:"盧","䀈":"䀈","⽬":"目","直":"直","直":"直","𥃲":"𥃲","𥃳":"𥃳",省:"省","䀘":"䀘","𥄙":"𥄙","眞":"眞","真":"真","真":"真","𥄳":"𥄳","着":"着","睊":"睊","睊":"睊","鿃":"䀹","䀹":"䀹","䀹":"䀹",晣:"䀿","䁆":"䁆","瞋":"瞋","𥉉":"𥉉","瞧":"瞧","⽭":"矛","⽮":"矢","⽯":"石","䂖":"䂖","𥐝":"𥐝",硏:"研","硎":"硎",硫:"硫",碌:"碌","碌":"碌","碑":"碑",磊:"磊","磌":"磌","磌":"磌",磻:"磻","䃣":"䃣",礪:"礪","⽰":"示","⺭":"礻",礼:"礼","社":"社","祈":"祈","祉":"祉","𥘦":"𥘦","祐":"祐","祖":"祖","祖":"祖","祝":"祝",神:"神",祥:"祥","視":"視","視":"視",祿:"祿","𥚚":"𥚚","禍":"禍","禎":"禎",福:"福","福":"福","𥛅":"𥛅",禮:"禮","⽱":"禸","⽲":"禾",秊:"秊","䄯":"䄯","秫":"秫",稜:"稜","穊":"穊","穀":"穀","穀":"穀","穏":"穏","⽳":"穴","突":"突","𥥼":"𥥼","窱":"窱",立:"立","⽴":"立","⻯":"竜","𥪧":"𥪧","𥪧":"𥪧","竮":"竮","⽵":"竹",笠:"笠","節":"節","節":"節","䈂":"䈂","𥮫":"𥮫","篆":"篆","䈧":"䈧","築":"築","𥲀":"𥲀","𥳐":"𥳐",簾:"簾",籠:"籠","⽶":"米","类":"类",粒:"粒",精:"精","糒":"糒",糖:"糖","糨":"糨","䊠":"䊠","糣":"糣",糧:"糧","⽷":"糸","⺯":"糹","𥾆":"𥾆","紀":"紀",紐:"紐",索:"索",累:"累",絶:"絕","絣":"絣","絛":"絛",綠:"綠",綾:"綾","緇":"緇",練:"練","練":"練","練":"練","縂":"縂","䌁":"䌁","縉":"縉",縷:"縷","繁":"繁","繅":"繅","𦇚":"𦇚","䌴":"䌴","⽸":"缶","𦈨":"𦈨","缾":"缾","𦉇":"𦉇","⽹":"网","⺫":"罒","⺲":"罒","⺱":"罓","䍙":"䍙","署":"署","𦋙":"𦋙",罹:"罹","罺":"罺",羅:"羅","𦌾":"𦌾","⽺":"羊","羕":"羕",羚:"羚",羽:"羽","⽻":"羽","翺":"翺",老:"老","⽼":"老","⺹":"耂","者":"者","者":"者","者":"者","⽽":"而","𦓚":"𦓚","⽾":"耒","𦔣":"𦔣","⽿":"耳",聆:"聆","聠":"聠","𦖨":"𦖨",聯:"聯","聰":"聰",聾:"聾","⾀":"聿","⺺":"肀","⾁":"肉",肋:"肋","肭":"肭","育":"育","䏕":"䏕","䏙":"䏙",腁:"胼","脃":"脃","脾":"脾","䐋":"䐋","朡":"朡","𦞧":"𦞧","𦞵":"𦞵",朦:"䑃",臘:"臘","⾂":"臣",臨:"臨","⾃":"自","臭":"臭","⾄":"至","⾅":"臼","舁":"舁","舁":"舁","舄":"舄","⾆":"舌","舘":"舘","⾇":"舛","⾈":"舟","䑫":"䑫","⾉":"艮",良:"良","⾊":"色","⾋":"艸","艹":"艹","艹":"艹","⺾":"艹","⺿":"艹","⻀":"艹","芋":"芋","芑":"芑","芝":"芝","花":"花","芳":"芳","芽":"芽",若:"若","若":"若","苦":"苦","𦬼":"𦬼",茶:"茶","荒":"荒","荣":"荣","茝":"茝","茣":"茣","莽":"莽","荓":"荓",菉:"菉","菊":"菊","菌":"菌","菜":"菜","菧":"菧","華":"華",菱:"菱","著":"著","著":"著","𦰶":"𦰶","莭":"莭",落:"落",葉:"葉",蔿:"蒍","𦳕":"𦳕","𦵫":"𦵫",蓮:"蓮","蓱":"蓱","蓳":"蓳",蓼:"蓼","蔖":"蔖","䔫":"䔫","蕤":"蕤","𦼬":"𦼬",藍:"藍","䕝":"䕝","𦾱":"𦾱","䕡":"䕡",藺:"藺",蘆:"蘆","䕫":"䕫",蘒:"蘒",蘭:"蘭","𧃒":"𧃒",虁:"蘷",蘿:"蘿","⾌":"虍","⻁":"虎","虐":"虐",虜:"虜","虜":"虜","虧":"虧","虩":"虩","⾍":"虫","蚩":"蚩","蚈":"蚈","蛢":"蛢","蜎":"蜎","蜨":"蜨","蝫":"蝫","蟡":"蟡","蝹":"蝹","蝹":"蝹","螆":"螆","䗗":"䗗","𧏊":"𧏊",螺:"螺","蠁":"蠁","䗹":"䗹",蠟:"蠟","⾎":"血",行:"行","⾏":"行","衠":"衠","衣":"衣","⾐":"衣","⻂":"衤",裂:"裂","𧙧":"𧙧",裏:"裏","裗":"裗","裞":"裞",裡:"裡",裸:"裸","裺":"裺","䘵":"䘵","褐":"褐","襁":"襁",襤:"襤","⾑":"襾","⻄":"西","⻃":"覀","覆":"覆",見:"見","⾒":"見","𧢮":"𧢮","⻅":"见","⾓":"角","⾔":"言","𧥦":"𧥦",詽:"訮",訞:"䚶","䚾":"䚾","䛇":"䛇","誠":"誠",說:"說",說:"說","調":"調","請":"請",諒:"諒",論:"論","諭":"諭","諭":"諭",諸:"諸","諸":"諸",諾:"諾","諾":"諾","謁":"謁","謁":"謁","謹":"謹","謹":"謹",識:"識",讀:"讀",讏:"讆","變":"變","變":"變","⻈":"讠","⾕":"谷","⾖":"豆",豈:"豈","豕":"豕","⾗":"豕",豣:"豜","⾘":"豸","𧲨":"𧲨","⾙":"貝","貫":"貫","賁":"賁",賂:"賂",賈:"賈","賓":"賓","贈":"贈","贈":"贈","贛":"贛","⻉":"贝","⾚":"赤","⾛":"走","起":"起",趆:"赿","𧻓":"𧻓","𧼯":"𧼯","⾜":"足","跋":"跋","趼":"趼",跺:"跥",路:"路","跰":"跰",躛:"躗","⾝":"身",車:"車","⾞":"車","軔":"軔",輧:"軿",輦:"輦",輪:"輪","輸":"輸","輸":"輸",輻:"輻",轢:"轢","⻋":"车","⾟":"辛","辞":"辞",辰:"辰","⾠":"辰","⾡":"辵","辶":"辶","⻌":"辶","⻍":"辶","巡":"巡",連:"連",逸:"逸","逸":"逸","遲":"遲",遼:"遼","𨗒":"𨗒","𨗭":"𨗭",邏:"邏","⾢":"邑","邔":"邔",郎:"郎",郞:"郎","郞":"郎","郱":"郱",都:"都","𨜮":"𨜮","鄑":"鄑","鄛":"鄛","⾣":"酉",酪:"酪","醙":"醙",醴:"醴","⾤":"釆",里:"里","⾥":"里",量:"量",金:"金","⾦":"金",鈴:"鈴","鈸":"鈸","鉶":"鉶","鋗":"鋗","鋘":"鋘","鉼":"鉼",錄:"錄",鍊:"鍊",鎮:"鎭","鏹":"鏹","鐕":"鐕","𨯺":"𨯺","⻐":"钅","⻑":"長","⾧":"長","⻒":"镸","⻓":"长","⾨":"門","開":"開","䦕":"䦕",閭:"閭","閷":"閷","𨵷":"𨵷","⻔":"门","⾩":"阜","⻏":"阝","⻖":"阝",阮:"阮",陋:"陋",降:"降",陵:"陵",陸:"陸","陼":"陼",隆:"隆",隣:"隣","䧦":"䧦","⾪":"隶","隷":"隷",隸:"隷",隸:"隷","⾫":"隹","雃":"雃",離:"離","難":"難","難":"難","⾬":"雨",零:"零",雷:"雷","霣":"霣","𩅅":"𩅅",露:"露",靈:"靈","⾭":"靑","⻘":"青",靖:"靖","靖":"靖","𩇟":"𩇟","⾮":"非","⾯":"面","𩈚":"𩈚","⾰":"革","䩮":"䩮","䩶":"䩶","⾱":"韋","韛":"韛","韠":"韠","⻙":"韦","⾲":"韭","𩐊":"𩐊","⾳":"音","響":"響","響":"響","⾴":"頁","䪲":"䪲","頋":"頋","頋":"頋","頋":"頋",領:"領","頩":"頩","𩒖":"𩒖","頻":"頻","頻":"頻",類:"類","⻚":"页","⾵":"風","𩖶":"𩖶","⻛":"风","⾶":"飛","⻜":"飞","⻝":"食","⾷":"食","⻟":"飠","飢":"飢",飯:"飯",飼:"飼","䬳":"䬳",館:"館","餩":"餩","⻠":"饣","⾸":"首","⾹":"香","馧":"馧","⾺":"馬","駂":"駂",駱:"駱","駾":"駾",驪:"驪","⻢":"马","⾻":"骨","䯎":"䯎","⾼":"高","⾽":"髟","𩬰":"𩬰","鬒":"鬒","鬒":"鬒","⾾":"鬥","⾿":"鬯","⿀":"鬲","⿁":"鬼","⻤":"鬼","⿂":"魚",魯:"魯","鱀":"鱀",鱗:"鱗","⻥":"鱼","⿃":"鳥","鳽":"鳽","䳎":"䳎","鵧":"鵧","䳭":"䳭","𪃎":"𪃎",鶴:"鶴","𪄅":"𪄅","䳸":"䳸",鷺:"鷺","𪈎":"𪈎",鸞:"鸞",鹃:"鹂","⿄":"鹵",鹿:"鹿","⿅":"鹿","𪊑":"𪊑",麗:"麗",麟:"麟","⿆":"麥","⻨":"麦","麻":"麻","⿇":"麻","𪎒":"𪎒","⿈":"黃","⻩":"黄","⿉":"黍",黎:"黎","䵖":"䵖","⿊":"黑",黒:"黑","墨":"墨","黹":"黹","⿋":"黹","⿌":"黽","鼅":"鼅","黾":"黾","⿍":"鼎","鼏":"鼏","⿎":"鼓","鼖":"鼖","⿏":"鼠","鼻":"鼻","⿐":"鼻","齃":"齃","⿑":"齊","⻬":"齐","⿒":"齒","𪘀":"𪘀","⻮":"齿",龍:"龍","⿓":"龍","龎":"龎","⻰":"龙",龜:"龜",龜:"龜","龜":"龜","⿔":"龜","⻳":"龟","⿕":"龠"};var fp,ww;function VK(){if(ww)return fp;ww=1;var e=qK;function t(o){return o.replace(/([.?*+^$[\]\\(){}|-])/g,"\\$1")}var n=RegExp(Object.keys(e).map(t).join("|"),"g");function r(o){return e[o]}function i(o){return o.replace(n,r)}return fp=i,fp}var Gs={},WK={get exports(){return Gs},set exports(e){Gs=e}},Gd={},HK={get exports(){return Gd},set exports(e){Gd=e}},hp={},pp,bw;function GK(){if(bw)return pp;bw=1;function e(t,n){typeof n=="boolean"&&(n={forever:n}),this._originalTimeouts=JSON.parse(JSON.stringify(t)),this._timeouts=t,this._options=n||{},this._maxRetryTime=n&&n.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}return pp=e,e.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)},e.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null},e.prototype.retry=function(t){if(this._timeout&&clearTimeout(this._timeout),!t)return!1;var n=new Date().getTime();if(t&&n-this._operationStart>=this._maxRetryTime)return this._errors.push(t),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(t);var r=this._timeouts.shift();if(r===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),r=this._cachedTimeouts.slice(-1);else return!1;var i=this;return this._timer=setTimeout(function(){i._attempts++,i._operationTimeoutCb&&(i._timeout=setTimeout(function(){i._operationTimeoutCb(i._attempts)},i._operationTimeout),i._options.unref&&i._timeout.unref()),i._fn(i._attempts)},r),this._options.unref&&this._timer.unref(),!0},e.prototype.attempt=function(t,n){this._fn=t,n&&(n.timeout&&(this._operationTimeout=n.timeout),n.cb&&(this._operationTimeoutCb=n.cb));var r=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){r._operationTimeoutCb()},r._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)},e.prototype.try=function(t){console.log("Using RetryOperation.try() is deprecated"),this.attempt(t)},e.prototype.start=function(t){console.log("Using RetryOperation.start() is deprecated"),this.attempt(t)},e.prototype.start=e.prototype.try,e.prototype.errors=function(){return this._errors},e.prototype.attempts=function(){return this._attempts},e.prototype.mainError=function(){if(this._errors.length===0)return null;for(var t={},n=null,r=0,i=0;i<this._errors.length;i++){var o=this._errors[i],a=o.message,c=(t[a]||0)+1;t[a]=c,c>=r&&(n=o,r=c)}return n},pp}var Tw;function zK(){return Tw||(Tw=1,function(e){var t=GK();e.operation=function(n){var r=e.timeouts(n);return new t(r,{forever:n&&(n.forever||n.retries===1/0),unref:n&&n.unref,maxRetryTime:n&&n.maxRetryTime})},e.timeouts=function(n){if(n instanceof Array)return[].concat(n);var r={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var i in n)r[i]=n[i];if(r.minTimeout>r.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var o=[],a=0;a<r.retries;a++)o.push(this.createTimeout(a,r));return n&&n.forever&&!o.length&&o.push(this.createTimeout(a,r)),o.sort(function(c,f){return c-f}),o},e.createTimeout=function(n,r){var i=r.randomize?Math.random()+1:1,o=Math.round(i*Math.max(r.minTimeout,1)*Math.pow(r.factor,n));return o=Math.min(o,r.maxTimeout),o},e.wrap=function(n,r,i){if(r instanceof Array&&(i=r,r=null),!i){i=[];for(var o in n)typeof n[o]=="function"&&i.push(o)}for(var a=0;a<i.length;a++){var c=i[a],f=n[c];n[c]=function(s){var g=e.operation(r),y=Array.prototype.slice.call(arguments,1),S=y.pop();y.push(function(m){g.retry(m)||(m&&(arguments[0]=g.mainError()),S.apply(this,arguments))}),g.attempt(function(){s.apply(n,y)})}.bind(n,f),n[c].options=r}}}(hp)),hp}var Rw;function YK(){return Rw||(Rw=1,function(e){e.exports=zK()}(HK)),Gd}var Iw;function mP(){if(Iw)return Gs;Iw=1;const e=YK(),t=["Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed"];class n extends Error{constructor(c){super(),c instanceof Error?(this.originalError=c,{message:c}=c):(this.originalError=new Error(c),this.originalError.stack=this.stack),this.name="AbortError",this.message=c}}const r=(a,c,f)=>{const v=f.retries-(c-1);return a.attemptNumber=c,a.retriesLeft=v,a},i=a=>t.includes(a),o=(a,c)=>new Promise((f,v)=>{c={onFailedAttempt:()=>{},retries:10,...c};const s=e.operation(c);s.attempt(async g=>{try{f(await a(g))}catch(y){if(!(y instanceof Error)){v(new TypeError(`Non-error was thrown: "${y}". You should only throw errors.`));return}if(y instanceof n)s.stop(),v(y.originalError);else if(y instanceof TypeError&&!i(y.message))s.stop(),v(y);else{r(y,g,c);try{await c.onFailedAttempt(y)}catch(S){v(S);return}s.retry(y)||v(s.mainError())}}})});return WK.exports=o,Gs.default=o,Gs.AbortError=n,Gs}var Bn={},en={},QK=Ae;Object.defineProperty(en,"__esModule",{value:!0});en.UnstableValue=en.ServerControlledNamespacedValue=en.NamespacedValue=void 0;var JK=QK(Ue);let Hy=class{constructor(t,n){if(this.stable=t,this.unstable=n,!this.unstable&&!this.stable)throw new Error("One of stable or unstable values must be supplied")}get name(){return this.stable?this.stable:this.unstable}get altName(){return this.stable?this.unstable:null}get names(){const t=[this.name],n=this.altName;return n&&t.push(n),t}matches(t){return this.name===t||this.altName===t}findIn(t){let n;return this.name&&(n=t==null?void 0:t[this.name]),!n&&this.altName&&(n=t==null?void 0:t[this.altName]),n}includedIn(t){let n=!1;return this.name&&(n=t.includes(this.name)),!n&&this.altName&&(n=t.includes(this.altName)),n}};en.NamespacedValue=Hy;class XK extends Hy{constructor(...t){super(...t),(0,JK.default)(this,"preferUnstable",!1)}setPreferUnstable(t){this.preferUnstable=t}get name(){return this.stable&&!this.preferUnstable?this.stable:this.unstable}}en.ServerControlledNamespacedValue=XK;let ZK=class extends Hy{constructor(t,n){if(super(t,n),!this.unstable)throw new Error("Unstable value must be supplied")}get name(){return this.unstable}get altName(){return this.stable}};en.UnstableValue=ZK;var Va={},Cw;function yP(){if(Cw)return Va;Cw=1,Object.defineProperty(Va,"__esModule",{value:!0}),Va.TEXT_NODE_TYPE=void 0;var e=en;const t=new e.UnstableValue("m.text","org.matrix.msc1767.text");return Va.TEXT_NODE_TYPE=t,Va}var Ow;function _P(){if(Ow)return Bn;Ow=1,Object.defineProperty(Bn,"__esModule",{value:!0}),Bn.M_TIMESTAMP=Bn.M_LOCATION=Bn.M_ASSET=Bn.LocationAssetType=void 0;var e=en;yP();let t;Bn.LocationAssetType=t,function(o){o.Self="m.self",o.Pin="m.pin"}(t||(Bn.LocationAssetType=t={}));const n=new e.UnstableValue("m.asset","org.matrix.msc3488.asset");Bn.M_ASSET=n;const r=new e.UnstableValue("m.ts","org.matrix.msc3488.ts");Bn.M_TIMESTAMP=r;const i=new e.UnstableValue("m.location","org.matrix.msc3488.location");return Bn.M_LOCATION=i,Bn}var gi={},Pw;function Sa(){if(Pw)return gi;Pw=1,Object.defineProperty(gi,"__esModule",{value:!0}),gi.ReceiptType=gi.MAIN_ROOM_TIMELINE=void 0;let e;gi.ReceiptType=e,function(n){n.Read="m.read",n.FullyRead="m.fully_read",n.ReadPrivate="m.read.private"}(e||(gi.ReceiptType=e={}));const t="main";return gi.MAIN_ROOM_TIMELINE=t,gi}var kw;function lt(){if(kw)return Je;kw=1;var e=Ae;Object.defineProperty(Je,"__esModule",{value:!0}),Je.DEFAULT_ALPHABET=void 0,Je.alphabetPad=R,Je.averageBetweenStrings=U,Je.baseToString=P,Je.checkObjectHasKeys=_,Je.chunkPromises=W,Je.compare=ne,Je.decodeParams=y,Je.deepCompare=l,Je.deepCopy=u,Je.deepSortedObjectEntries=d,Je.defer=D,Je.encodeParams=s,Je.encodeUri=S,Je.ensureNoTrailingSlash=B,Je.escapeRegExp=M,Je.globToRegexp=L,Je.internaliseString=v,Je.isFunction=p,Je.isNullOrUndefined=G,Je.isNumber=h,Je.isSupportedReceiptType=se,Je.lexicographicCompare=T,Je.mapsEqual=Q,Je.nextString=C,Je.normalize=I,Je.prevString=A,Je.promiseMapSeries=x,Je.promiseTry=z,Je.recursivelyAssign=ae,Je.removeDirectionOverrideChars=E,Je.removeElement=m,Je.removeHiddenChars=w,Je.replaceParam=g,Je.simpleRetryOperation=F,Je.sleep=N,Je.sortEventsByLatestContentTimestamp=V,Je.stringToBase=K;var t=e(Ue),n=e(VK()),r=e(mP()),i=_P(),o=Sa();function a(j,Z){var te=Object.keys(j);if(Object.getOwnPropertySymbols){var re=Object.getOwnPropertySymbols(j);Z&&(re=re.filter(function(de){return Object.getOwnPropertyDescriptor(j,de).enumerable})),te.push.apply(te,re)}return te}function c(j){for(var Z=1;Z<arguments.length;Z++){var te=arguments[Z]!=null?arguments[Z]:{};Z%2?a(Object(te),!0).forEach(function(re){(0,t.default)(j,re,te[re])}):Object.getOwnPropertyDescriptors?Object.defineProperties(j,Object.getOwnPropertyDescriptors(te)):a(Object(te)).forEach(function(re){Object.defineProperty(j,re,Object.getOwnPropertyDescriptor(te,re))})}return j}const f=new Map;function v(j){return j instanceof String&&(j=j.toString()),f.has(j)||f.set(j,j),f.get(j)}function s(j,Z){const te=Z??new URLSearchParams;for(const[re,de]of Object.entries(j))de!=null&&(Array.isArray(de)?de.forEach(ge=>{te.append(re,String(ge))}):te.append(re,String(de)));return te}function g(j,Z,te){const re=c(c({},te),{},{[Z]:te[j]});return delete re[j],re}function y(j){const Z={},te=new URLSearchParams(j);for(const re of te.keys()){const de=te.getAll(re);Z[re]=de.length===1?de[0]:de}return Z}function S(j,Z){for(const te in Z){if(!Z.hasOwnProperty(te))continue;const re=Z[te];re!=null&&(j=j.replace(te,encodeURIComponent(re)))}return j}function m(j,Z,te){let re;if(te){for(re=j.length-1;re>=0;re--)if(Z(j[re],re,j))return j.splice(re,1),!0}else for(re=0;re<j.length;re++)if(Z(j[re],re,j))return j.splice(re,1),!0;return!1}function p(j){return Object.prototype.toString.call(j)==="[object Function]"}function _(j,Z){for(const te of Z)if(!j.hasOwnProperty(te))throw new Error("Missing required key: "+te)}function u(j){return JSON.parse(JSON.stringify(j))}function l(j,Z){if(j===Z)return!0;if(typeof j!=typeof Z)return!1;if(typeof j=="number"&&isNaN(j)&&isNaN(Z))return!0;if(j===null||Z===null)return j===Z;if(!(j instanceof Object)||j.constructor!==Z.constructor||j.prototype!==Z.prototype)return!1;if(j instanceof RegExp||j instanceof Date)return j.toString()===Z.toString();if(Array.isArray(j)){if(j.length!==Z.length)return!1;for(let te=0;te<j.length;te++)if(!l(j[te],Z[te]))return!1}else{for(const te in Z)if(Z.hasOwnProperty(te)!==j.hasOwnProperty(te))return!1;for(const te in j)if(Z.hasOwnProperty(te)!==j.hasOwnProperty(te)||!l(j[te],Z[te]))return!1}return!0}function d(j){if(typeof j!="object"||j==null||Array.isArray(j))return j;const Z=[];for(const[te,re]of Object.entries(j))Z.push([te,d(re)]);return Z.sort((te,re)=>T(te[0],re[0])),Z}function h(j){return typeof j=="number"&&isFinite(j)}function w(j){return typeof j=="string"?(0,n.default)(j.normalize("NFD").replace(k,"")):""}function E(j){return typeof j=="string"?j.replace(/[\u202d-\u202e]/g,""):""}function I(j){return w(j.toLowerCase()).replace(/[\\'!"#$%&()*+,\-./:;<=>?@[\]^_`{|}~\u2000-\u206f\u2e00-\u2e7f]/g,"").toLowerCase()}const k=/[\u2000-\u200F\u202A-\u202F\u0300-\u036F\uFEFF\u061C\u2800\u2062-\u2063\s]/g;function M(j){return j.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function L(j,Z=!1){const te=[[/\\\*/g,".*"],[/\?/g,"."]];return Z||te.push([/\\\[(!|)(.*)\\]/g,(re,de,ge)=>["[",de?"^":"",ge.replace(/\\-/,"-"),"]"].join("")]),te.reduce((re,de)=>de?re.replace(de[0],de[1]):re,M(j))}function B(j){return j!=null&&j.endsWith("/")?j.slice(0,-1):j}function N(j,Z){return new Promise(te=>{setTimeout(te,j,Z)})}function G(j){return j==null}function D(){let j,Z;const te=new Promise((re,de)=>{j=re,Z=de});return{resolve:j,reject:Z,promise:te}}async function x(j,Z){for(const te of j)await Z(await te)}function z(j){return Promise.resolve(j())}async function W(j,Z){const te=[];for(let re=0;re<j.length;re+=Z)te.push(...await Promise.all(j.slice(re,re+Z).map(de=>de())));return te}function F(j){return(0,r.default)(Z=>j(Z),{forever:!0,factor:2,minTimeout:3e3,maxTimeout:15e3})}const H=(()=>{let j="";for(let Z=32;Z<=126;Z++)j+=String.fromCharCode(Z);return j})();Je.DEFAULT_ALPHABET=H;function R(j,Z,te=H){return j.padEnd(Z,te[0])}function P(j,Z=H){const te=BigInt(Z.length);if(j<=te){var re;return(re=Z[Number(j)-1])!==null&&re!==void 0?re:""}let de=j/te,ge=Number(j%te)-1;return ge<0&&(de-=BigInt(Math.abs(ge)),ge=Number(te)-1),P(de,Z)+Z[ge]}function K(j,Z=H){const te=BigInt(Z.length);let re=BigInt(0);for(let de=j.length-1,ge=BigInt(0);de>=0;de--,ge++){const fe=j.charCodeAt(de)-Z.charCodeAt(0);re+=BigInt(1+fe)*te**ge}return re}function U(j,Z,te=H){const re=Math.max(j.length,Z.length),de=K(R(j,re,te),te),ge=K(R(Z,re,te),te),fe=(de+ge)/BigInt(2);return fe===de||fe==ge?P(fe,te)+te[0]:P(fe,te)}function C(j,Z=H){return P(K(j,Z)+BigInt(1),Z)}function A(j,Z=H){return P(K(j,Z)-BigInt(1),Z)}function T(j,Z){return j<Z?-1:j>Z?1:0}const X=new Intl.Collator;function ne(j,Z){return X.compare(j,Z)}function ae(j,Z,te=!1){for(const[re,de]of Object.entries(Z)){if(j[re]instanceof Object&&de){ae(j[re],de);continue}if(de!=null||!te){j[re]=de;continue}}return j}function pe(j){var Z;return(Z=i.M_TIMESTAMP.findIn(j.getContent()))!==null&&Z!==void 0?Z:-1}function V(j,Z){return pe(Z)-pe(j)}function se(j){return[o.ReceiptType.Read,o.ReceiptType.ReadPrivate].includes(j)}function Q(j,Z,te=(re,de)=>re===de){if(j.size!==Z.size)return!1;for(const[re,de]of j){const ge=Z.get(re);if(ge===void 0||!te(de,ge))return!1}return!0}return Je}var ej=Ae;Object.defineProperty(_a,"__esModule",{value:!0});_a.MemoryCryptoStore=void 0;var an=ej(Ue),kc=Ge(),Mw=tj(lt());function SP(e){if(typeof WeakMap!="function")return null;var t=new WeakMap,n=new WeakMap;return(SP=function(r){return r?n:t})(e)}function tj(e,t){if(!t&&e&&e.__esModule)return e;if(e===null||typeof e!="object"&&typeof e!="function")return{default:e};var n=SP(t);if(n&&n.has(e))return n.get(e);var r={},i=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var o in e)if(o!=="default"&&Object.prototype.hasOwnProperty.call(e,o)){var a=i?Object.getOwnPropertyDescriptor(e,o):null;a&&(a.get||a.set)?Object.defineProperty(r,o,a):r[o]=e[o]}return r.default=e,n&&n.set(e,r),r}function Dw(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),n.push.apply(n,r)}return n}function Aw(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?Dw(Object(n),!0).forEach(function(r){(0,an.default)(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Dw(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}class nj{constructor(){(0,an.default)(this,"outgoingRoomKeyRequests",[]),(0,an.default)(this,"account",null),(0,an.default)(this,"crossSigningKeys",null),(0,an.default)(this,"privateKeys",{}),(0,an.default)(this,"sessions",{}),(0,an.default)(this,"sessionProblems",{}),(0,an.default)(this,"notifiedErrorDevices",{}),(0,an.default)(this,"inboundGroupSessions",{}),(0,an.default)(this,"inboundGroupSessionsWithheld",{}),(0,an.default)(this,"deviceData",null),(0,an.default)(this,"rooms",{}),(0,an.default)(this,"sessionsNeedingBackup",{}),(0,an.default)(this,"sharedHistoryInboundGroupSessions",{}),(0,an.default)(this,"parkedSharedHistory",new Map)}async startup(){return this}deleteAllData(){return Promise.resolve()}getOrAddOutgoingRoomKeyRequest(t){const n=t.requestBody;return Mw.promiseTry(()=>{const r=this._getOutgoingRoomKeyRequest(n);return r?(kc.logger.log(`already have key request outstanding for ${n.room_id} / ${n.session_id}: not sending another`),r):(kc.logger.log(`enqueueing key request for ${n.room_id} / `+n.session_id),this.outgoingRoomKeyRequests.push(t),t)})}getOutgoingRoomKeyRequest(t){return Promise.resolve(this._getOutgoingRoomKeyRequest(t))}_getOutgoingRoomKeyRequest(t){for(const n of this.outgoingRoomKeyRequests)if(Mw.deepCompare(n.requestBody,t))return n;return null}getOutgoingRoomKeyRequestByState(t){for(const n of this.outgoingRoomKeyRequests)for(const r of t)if(n.state===r)return Promise.resolve(n);return Promise.resolve(null)}getAllOutgoingRoomKeyRequestsByState(t){return Promise.resolve(this.outgoingRoomKeyRequests.filter(n=>n.state==t))}getOutgoingRoomKeyRequestsByTarget(t,n,r){const i=[];for(const o of this.outgoingRoomKeyRequests)for(const a of r)o.state===a&&o.recipients.some(c=>c.userId===t&&c.deviceId===n)&&i.push(o);return Promise.resolve(i)}updateOutgoingRoomKeyRequest(t,n,r){for(const i of this.outgoingRoomKeyRequests)if(i.requestId===t)return i.state!==n?(kc.logger.warn(`Cannot update room key request from ${n} as it was already updated to ${i.state}`),Promise.resolve(null)):(Object.assign(i,r),Promise.resolve(i));return Promise.resolve(null)}deleteOutgoingRoomKeyRequest(t,n){for(let r=0;r<this.outgoingRoomKeyRequests.length;r++){const i=this.outgoingRoomKeyRequests[r];if(i.requestId===t)return i.state!=n?(kc.logger.warn(`Cannot delete room key request in state ${i.state} (expected ${n})`),Promise.resolve(null)):(this.outgoingRoomKeyRequests.splice(r,1),Promise.resolve(i))}return Promise.resolve(null)}getAccount(t,n){n(this.account)}storeAccount(t,n){this.account=n}getCrossSigningKeys(t,n){n(this.crossSigningKeys)}getSecretStorePrivateKey(t,n,r){const i=this.privateKeys[r];n(i||null)}storeCrossSigningKeys(t,n){this.crossSigningKeys=n}storeSecretStorePrivateKey(t,n,r){this.privateKeys[n]=r}countEndToEndSessions(t,n){n(Object.keys(this.sessions).length)}getEndToEndSession(t,n,r,i){const o=this.sessions[t]||{};i(o[n]||null)}getEndToEndSessions(t,n,r){r(this.sessions[t]||{})}getAllEndToEndSessions(t,n){Object.entries(this.sessions).forEach(([r,i])=>{Object.entries(i).forEach(([o,a])=>{n(Aw(Aw({},a),{},{deviceKey:r,sessionId:o}))})})}storeEndToEndSession(t,n,r,i){let o=this.sessions[t];o===void 0&&(o={},this.sessions[t]=o),o[n]=r}async storeEndToEndSessionProblem(t,n,r){const i=this.sessionProblems[t]=this.sessionProblems[t]||[];i.push({type:n,fixed:r,time:Date.now()}),i.sort((o,a)=>o.time-a.time)}async getEndToEndSessionProblem(t,n){const r=this.sessionProblems[t]||[];if(!r.length)return null;const i=r[r.length-1];for(const o of r)if(o.time>n)return Object.assign({},o,{fixed:i.fixed});return i.fixed?null:i}async filterOutNotifiedErrorDevices(t){const n=this.notifiedErrorDevices,r=[];for(const i of t){const{userId:o,deviceInfo:a}=i;o in n?a.deviceId in n[o]||(r.push(i),n[o][a.deviceId]=!0):(r.push(i),n[o]={[a.deviceId]:!0})}return r}getEndToEndInboundGroupSession(t,n,r,i){const o=t+"/"+n;i(this.inboundGroupSessions[o]||null,this.inboundGroupSessionsWithheld[o]||null)}getAllEndToEndInboundGroupSessions(t,n){for(const r of Object.keys(this.inboundGroupSessions))n({senderKey:r.slice(0,43),sessionId:r.slice(44),sessionData:this.inboundGroupSessions[r]});n(null)}addEndToEndInboundGroupSession(t,n,r,i){const o=t+"/"+n;this.inboundGroupSessions[o]===void 0&&(this.inboundGroupSessions[o]=r)}storeEndToEndInboundGroupSession(t,n,r,i){this.inboundGroupSessions[t+"/"+n]=r}storeEndToEndInboundGroupSessionWithheld(t,n,r,i){const o=t+"/"+n;this.inboundGroupSessionsWithheld[o]=r}getEndToEndDeviceData(t,n){n(this.deviceData)}storeEndToEndDeviceData(t,n){this.deviceData=t}storeEndToEndRoom(t,n,r){this.rooms[t]=n}getEndToEndRooms(t,n){n(this.rooms)}getSessionsNeedingBackup(t){const n=[];for(const r in this.sessionsNeedingBackup)if(this.inboundGroupSessions[r]&&(n.push({senderKey:r.slice(0,43),sessionId:r.slice(44),sessionData:this.inboundGroupSessions[r]}),t&&r.length>=t))break;return Promise.resolve(n)}countSessionsNeedingBackup(){return Promise.resolve(Object.keys(this.sessionsNeedingBackup).length)}unmarkSessionsNeedingBackup(t){for(const n of t){const r=n.senderKey+"/"+n.sessionId;delete this.sessionsNeedingBackup[r]}return Promise.resolve()}markSessionsNeedingBackup(t){for(const n of t){const r=n.senderKey+"/"+n.sessionId;this.sessionsNeedingBackup[r]=!0}return Promise.resolve()}addSharedHistoryInboundGroupSession(t,n,r){const i=this.sharedHistoryInboundGroupSessions[t]||[];i.push([n,r]),this.sharedHistoryInboundGroupSessions[t]=i}getSharedHistoryInboundGroupSessions(t){return Promise.resolve(this.sharedHistoryInboundGroupSessions[t]||[])}addParkedSharedHistory(t,n){var r;const i=(r=this.parkedSharedHistory.get(t))!==null&&r!==void 0?r:[];i.push(n),this.parkedSharedHistory.set(t,i)}takeParkedSharedHistory(t){var n;const r=(n=this.parkedSharedHistory.get(t))!==null&&n!==void 0?n:[];return this.parkedSharedHistory.delete(t),Promise.resolve(r)}doTxn(t,n,r){return Promise.resolve(r(null))}}_a.MemoryCryptoStore=nj;var Bu={},Xn={},vi={},Ql={},rj={get exports(){return Ql},set exports(e){Ql=e}},Lw;function Uf(){if(Lw)return Ql;Lw=1;var e=typeof Reflect=="object"?Reflect:null,t=e&&typeof e.apply=="function"?e.apply:function(w,E,I){return Function.prototype.apply.call(w,E,I)},n;e&&typeof e.ownKeys=="function"?n=e.ownKeys:Object.getOwnPropertySymbols?n=function(w){return Object.getOwnPropertyNames(w).concat(Object.getOwnPropertySymbols(w))}:n=function(w){return Object.getOwnPropertyNames(w)};function r(h){console&&console.warn&&console.warn(h)}var i=Number.isNaN||function(w){return w!==w};function o(){o.init.call(this)}rj.exports=o,Ql.once=u,o.EventEmitter=o,o.prototype._events=void 0,o.prototype._eventsCount=0,o.prototype._maxListeners=void 0;var a=10;function c(h){if(typeof h!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof h)}Object.defineProperty(o,"defaultMaxListeners",{enumerable:!0,get:function(){return a},set:function(h){if(typeof h!="number"||h<0||i(h))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+h+".");a=h}}),o.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},o.prototype.setMaxListeners=function(w){if(typeof w!="number"||w<0||i(w))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+w+".");return this._maxListeners=w,this};function f(h){return h._maxListeners===void 0?o.defaultMaxListeners:h._maxListeners}o.prototype.getMaxListeners=function(){return f(this)},o.prototype.emit=function(w){for(var E=[],I=1;I<arguments.length;I++)E.push(arguments[I]);var k=w==="error",M=this._events;if(M!==void 0)k=k&&M.error===void 0;else if(!k)return!1;if(k){var L;if(E.length>0&&(L=E[0]),L instanceof Error)throw L;var B=new Error("Unhandled error."+(L?" ("+L.message+")":""));throw B.context=L,B}var N=M[w];if(N===void 0)return!1;if(typeof N=="function")t(N,this,E);else for(var G=N.length,D=m(N,G),I=0;I<G;++I)t(D[I],this,E);return!0};function v(h,w,E,I){var k,M,L;if(c(E),M=h._events,M===void 0?(M=h._events=Object.create(null),h._eventsCount=0):(M.newListener!==void 0&&(h.emit("newListener",w,E.listener?E.listener:E),M=h._events),L=M[w]),L===void 0)L=M[w]=E,++h._eventsCount;else if(typeof L=="function"?L=M[w]=I?[E,L]:[L,E]:I?L.unshift(E):L.push(E),k=f(h),k>0&&L.length>k&&!L.warned){L.warned=!0;var B=new Error("Possible EventEmitter memory leak detected. "+L.length+" "+String(w)+" listeners added. Use emitter.setMaxListeners() to increase limit");B.name="MaxListenersExceededWarning",B.emitter=h,B.type=w,B.count=L.length,r(B)}return h}o.prototype.addListener=function(w,E){return v(this,w,E,!1)},o.prototype.on=o.prototype.addListener,o.prototype.prependListener=function(w,E){return v(this,w,E,!0)};function s(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function g(h,w,E){var I={fired:!1,wrapFn:void 0,target:h,type:w,listener:E},k=s.bind(I);return k.listener=E,I.wrapFn=k,k}o.prototype.once=function(w,E){return c(E),this.on(w,g(this,w,E)),this},o.prototype.prependOnceListener=function(w,E){return c(E),this.prependListener(w,g(this,w,E)),this},o.prototype.removeListener=function(w,E){var I,k,M,L,B;if(c(E),k=this._events,k===void 0)return this;if(I=k[w],I===void 0)return this;if(I===E||I.listener===E)--this._eventsCount===0?this._events=Object.create(null):(delete k[w],k.removeListener&&this.emit("removeListener",w,I.listener||E));else if(typeof I!="function"){for(M=-1,L=I.length-1;L>=0;L--)if(I[L]===E||I[L].listener===E){B=I[L].listener,M=L;break}if(M<0)return this;M===0?I.shift():p(I,M),I.length===1&&(k[w]=I[0]),k.removeListener!==void 0&&this.emit("removeListener",w,B||E)}return this},o.prototype.off=o.prototype.removeListener,o.prototype.removeAllListeners=function(w){var E,I,k;if(I=this._events,I===void 0)return this;if(I.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):I[w]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete I[w]),this;if(arguments.length===0){var M=Object.keys(I),L;for(k=0;k<M.length;++k)L=M[k],L!=="removeListener"&&this.removeAllListeners(L);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(E=I[w],typeof E=="function")this.removeListener(w,E);else if(E!==void 0)for(k=E.length-1;k>=0;k--)this.removeListener(w,E[k]);return this};function y(h,w,E){var I=h._events;if(I===void 0)return[];var k=I[w];return k===void 0?[]:typeof k=="function"?E?[k.listener||k]:[k]:E?_(k):m(k,k.length)}o.prototype.listeners=function(w){return y(this,w,!0)},o.prototype.rawListeners=function(w){return y(this,w,!1)},o.listenerCount=function(h,w){return typeof h.listenerCount=="function"?h.listenerCount(w):S.call(h,w)},o.prototype.listenerCount=S;function S(h){var w=this._events;if(w!==void 0){var E=w[h];if(typeof E=="function")return 1;if(E!==void 0)return E.length}return 0}o.prototype.eventNames=function(){return this._eventsCount>0?n(this._events):[]};function m(h,w){for(var E=new Array(w),I=0;I<w;++I)E[I]=h[I];return E}function p(h,w){for(;w+1<h.length;w++)h[w]=h[w+1];h.pop()}function _(h){for(var w=new Array(h.length),E=0;E<w.length;++E)w[E]=h[E].listener||h[E];return w}function u(h,w){return new Promise(function(E,I){function k(L){h.removeListener(w,M),I(L)}function M(){typeof h.removeListener=="function"&&h.removeListener("error",k),E([].slice.call(arguments))}d(h,w,M,{once:!0}),w!=="error"&&l(h,k,{once:!0})})}function l(h,w,E){typeof h.on=="function"&&d(h,"error",w,E)}function d(h,w,E,I){if(typeof h.on=="function")I.once?h.once(w,E):h.on(w,E);else if(typeof h.addEventListener=="function")h.addEventListener(w,function k(M){I.once&&h.removeEventListener(w,k),E(M)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof h)}return Ql}var Nw;function Pt(){if(Nw)return vi;Nw=1,Object.defineProperty(vi,"__esModule",{value:!0}),vi.TypedEventEmitter=vi.EventEmitterEvents=void 0;var e=Uf();let t;vi.EventEmitterEvents=t,function(r){r.NewListener="newListener",r.RemoveListener="removeListener",r.Error="error"}(t||(vi.EventEmitterEvents=t={}));class n extends e.EventEmitter{addListener(i,o){return super.addListener(i,o)}emit(i,...o){return super.emit(i,...o)}eventNames(){return super.eventNames()}listenerCount(i){return super.listenerCount(i)}listeners(i){return super.listeners(i)}off(i,o){return super.off(i,o)}on(i,o){return super.on(i,o)}once(i,o){return super.once(i,o)}prependListener(i,o){return super.prependListener(i,o)}prependOnceListener(i,o){return super.prependOnceListener(i,o)}removeAllListeners(i){return super.removeAllListeners(i)}removeListener(i,o){return super.removeListener(i,o)}rawListeners(i){return super.rawListeners(i)}}return vi.TypedEventEmitter=n,vi}var ij=Ae;Object.defineProperty(Xn,"__esModule",{value:!0});Xn.UserEvent=Xn.User=void 0;var Or=ij(Ue),oj=Pt();let $i;Xn.UserEvent=$i;(function(e){e.DisplayName="User.displayName",e.AvatarUrl="User.avatarUrl",e.Presence="User.presence",e.CurrentlyActive="User.currentlyActive",e.LastPresenceTs="User.lastPresenceTs"})($i||(Xn.UserEvent=$i={}));class sj extends oj.TypedEventEmitter{constructor(t){super(),this.userId=t,(0,Or.default)(this,"modified",-1),(0,Or.default)(this,"displayName",void 0),(0,Or.default)(this,"rawDisplayName",void 0),(0,Or.default)(this,"avatarUrl",void 0),(0,Or.default)(this,"presenceStatusMsg",void 0),(0,Or.default)(this,"presence","offline"),(0,Or.default)(this,"lastActiveAgo",0),(0,Or.default)(this,"lastPresenceTs",0),(0,Or.default)(this,"currentlyActive",!1),(0,Or.default)(this,"events",{}),this.displayName=t,this.rawDisplayName=t,this.updateModifiedTime()}setPresenceEvent(t){if(t.getType()!=="m.presence")return;const n=this.events.presence===null;this.events.presence=t;const r=[];(t.getContent().presence!==this.presence||n)&&r.push($i.Presence),t.getContent().avatar_url&&t.getContent().avatar_url!==this.avatarUrl&&r.push($i.AvatarUrl),t.getContent().displayname&&t.getContent().displayname!==this.displayName&&r.push($i.DisplayName),t.getContent().currently_active!==void 0&&t.getContent().currently_active!==this.currentlyActive&&r.push($i.CurrentlyActive),this.presence=t.getContent().presence,r.push($i.LastPresenceTs),t.getContent().status_msg&&(this.presenceStatusMsg=t.getContent().status_msg),t.getContent().displayname&&(this.displayName=t.getContent().displayname),t.getContent().avatar_url&&(this.avatarUrl=t.getContent().avatar_url),this.lastActiveAgo=t.getContent().last_active_ago,this.lastPresenceTs=Date.now(),this.currentlyActive=t.getContent().currently_active,this.updateModifiedTime();for(const i of r)this.emit(i,t,this)}setDisplayName(t){const n=this.displayName;this.displayName=t,t!==n&&this.updateModifiedTime()}setRawDisplayName(t){this.rawDisplayName=t}setAvatarUrl(t){const n=this.avatarUrl;this.avatarUrl=t,t!==n&&this.updateModifiedTime()}updateModifiedTime(){this.modified=Date.now()}getLastModifiedTime(){return this.modified}getLastActiveTs(){return this.lastPresenceTs-this.lastActiveAgo}}Xn.User=sj;var mi={},Zn={},Ea={};Object.defineProperty(Ea,"__esModule",{value:!0});Ea.getHttpUriForMxc=uj;var aj=lj(lt());function EP(e){if(typeof WeakMap!="function")return null;var t=new WeakMap,n=new WeakMap;return(EP=function(r){return r?n:t})(e)}function lj(e,t){if(!t&&e&&e.__esModule)return e;if(e===null||typeof e!="object"&&typeof e!="function")return{default:e};var n=EP(t);if(n&&n.has(e))return n.get(e);var r={},i=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var o in e)if(o!=="default"&&Object.prototype.hasOwnProperty.call(e,o)){var a=i?Object.getOwnPropertyDescriptor(e,o):null;a&&(a.get||a.set)?Object.defineProperty(r,o,a):r[o]=e[o]}return r.default=e,n&&n.set(e,r),r}function uj(e,t,n,r,i,o=!1){if(typeof t!="string"||!t)return"";if(t.indexOf("mxc://")!==0)return o?t:"";let a=t.slice(6),c="/_matrix/media/r0/download/";const f={};n&&(f.width=Math.round(n).toString()),r&&(f.height=Math.round(r).toString()),i&&(f.method=i),Object.keys(f).length>0&&(c="/_matrix/media/r0/thumbnail/");const v=a.indexOf("#");let s="";v>=0&&(s=a.slice(v),a=a.slice(0,v));const g=Object.keys(f).length===0?"":"?"+aj.encodeParams(f);return e+c+a+g+s}var xe={};Object.defineProperty(xe,"__esModule",{value:!0});xe.UNSTABLE_MSC3089_TREE_SUBTYPE=xe.UNSTABLE_MSC3089_LEAF=xe.UNSTABLE_MSC3089_BRANCH=xe.UNSTABLE_MSC3088_PURPOSE=xe.UNSTABLE_MSC3088_ENABLED=xe.UNSTABLE_MSC2716_MARKER=xe.UNSTABLE_ELEMENT_FUNCTIONAL_USERS=xe.ToDeviceMessageId=xe.RoomType=xe.RoomCreateTypeField=xe.RelationType=xe.PUSHER_ENABLED=xe.PUSHER_DEVICE_ID=xe.MsgType=xe.LOCAL_NOTIFICATION_SETTINGS_PREFIX=xe.EventType=xe.EVENT_VISIBILITY_CHANGE_TYPE=void 0;var br=en;let kv;xe.EventType=kv;(function(e){e.RoomCanonicalAlias="m.room.canonical_alias",e.RoomCreate="m.room.create",e.RoomJoinRules="m.room.join_rules",e.RoomMember="m.room.member",e.RoomThirdPartyInvite="m.room.third_party_invite",e.RoomPowerLevels="m.room.power_levels",e.RoomName="m.room.name",e.RoomTopic="m.room.topic",e.RoomAvatar="m.room.avatar",e.RoomPinnedEvents="m.room.pinned_events",e.RoomEncryption="m.room.encryption",e.RoomHistoryVisibility="m.room.history_visibility",e.RoomGuestAccess="m.room.guest_access",e.RoomServerAcl="m.room.server_acl",e.RoomTombstone="m.room.tombstone",e.SpaceChild="m.space.child",e.SpaceParent="m.space.parent",e.RoomRedaction="m.room.redaction",e.RoomMessage="m.room.message",e.RoomMessageEncrypted="m.room.encrypted",e.Sticker="m.sticker",e.CallInvite="m.call.invite",e.CallCandidates="m.call.candidates",e.CallAnswer="m.call.answer",e.CallHangup="m.call.hangup",e.CallReject="m.call.reject",e.CallSelectAnswer="m.call.select_answer",e.CallNegotiate="m.call.negotiate",e.CallSDPStreamMetadataChanged="m.call.sdp_stream_metadata_changed",e.CallSDPStreamMetadataChangedPrefix="org.matrix.call.sdp_stream_metadata_changed",e.CallReplaces="m.call.replaces",e.CallAssertedIdentity="m.call.asserted_identity",e.CallAssertedIdentityPrefix="org.matrix.call.asserted_identity",e.KeyVerificationRequest="m.key.verification.request",e.KeyVerificationStart="m.key.verification.start",e.KeyVerificationCancel="m.key.verification.cancel",e.KeyVerificationMac="m.key.verification.mac",e.KeyVerificationDone="m.key.verification.done",e.KeyVerificationKey="m.key.verification.key",e.KeyVerificationAccept="m.key.verification.accept",e.KeyVerificationReady="m.key.verification.ready",e.RoomMessageFeedback="m.room.message.feedback",e.Reaction="m.reaction",e.Typing="m.typing",e.Receipt="m.receipt",e.Presence="m.presence",e.FullyRead="m.fully_read",e.Tag="m.tag",e.SpaceOrder="org.matrix.msc3230.space_order",e.PushRules="m.push_rules",e.Direct="m.direct",e.IgnoredUserList="m.ignored_user_list",e.RoomKey="m.room_key",e.RoomKeyRequest="m.room_key_request",e.ForwardedRoomKey="m.forwarded_room_key",e.Dummy="m.dummy",e.GroupCallPrefix="org.matrix.msc3401.call",e.GroupCallMemberPrefix="org.matrix.msc3401.call.member"})(kv||(xe.EventType=kv={}));let Mv;xe.RelationType=Mv;(function(e){e.Annotation="m.annotation",e.Replace="m.replace",e.Reference="m.reference",e.Thread="m.thread"})(Mv||(xe.RelationType=Mv={}));let Dv;xe.MsgType=Dv;(function(e){e.Text="m.text",e.Emote="m.emote",e.Notice="m.notice",e.Image="m.image",e.File="m.file",e.Audio="m.audio",e.Location="m.location",e.Video="m.video",e.KeyVerificationRequest="m.key.verification.request"})(Dv||(xe.MsgType=Dv={}));const cj="type";xe.RoomCreateTypeField=cj;let Av;xe.RoomType=Av;(function(e){e.Space="m.space",e.UnstableCall="org.matrix.msc3417.call",e.ElementVideo="io.element.video"})(Av||(xe.RoomType=Av={}));const dj="org.matrix.msgid";xe.ToDeviceMessageId=dj;const fj=new br.UnstableValue("m.room.purpose","org.matrix.msc3088.purpose");xe.UNSTABLE_MSC3088_PURPOSE=fj;const hj=new br.UnstableValue("m.enabled","org.matrix.msc3088.enabled");xe.UNSTABLE_MSC3088_ENABLED=hj;const pj=new br.UnstableValue("m.data_tree","org.matrix.msc3089.data_tree");xe.UNSTABLE_MSC3089_TREE_SUBTYPE=pj;const gj=new br.UnstableValue("m.leaf","org.matrix.msc3089.leaf");xe.UNSTABLE_MSC3089_LEAF=gj;const vj=new br.UnstableValue("m.branch","org.matrix.msc3089.branch");xe.UNSTABLE_MSC3089_BRANCH=vj;const mj=new br.UnstableValue("m.room.marker","org.matrix.msc2716.marker");xe.UNSTABLE_MSC2716_MARKER=mj;const yj=new br.UnstableValue("io.element.functional_members","io.element.functional_members");xe.UNSTABLE_ELEMENT_FUNCTIONAL_USERS=yj;const _j=new br.UnstableValue("m.visibility","org.matrix.msc3531.visibility");xe.EVENT_VISIBILITY_CHANGE_TYPE=_j;const Sj=new br.UnstableValue("enabled","org.matrix.msc3881.enabled");xe.PUSHER_ENABLED=Sj;const Ej=new br.UnstableValue("device_id","org.matrix.msc3881.device_id");xe.PUSHER_DEVICE_ID=Ej;const wj=new br.UnstableValue("m.local_notification_settings","org.matrix.msc3890.local_notification_settings");xe.LOCAL_NOTIFICATION_SETTINGS_PREFIX=wj;var bj=Ae;Object.defineProperty(Zn,"__esModule",{value:!0});Zn.RoomMemberEvent=Zn.RoomMember=void 0;var Fn=bj(Ue),Tj=Ea,na=Cj(lt()),Rj=Ge(),Ij=Pt(),xw=xe;function wP(e){if(typeof WeakMap!="function")return null;var t=new WeakMap,n=new WeakMap;return(wP=function(r){return r?n:t})(e)}function Cj(e,t){if(!t&&e&&e.__esModule)return e;if(e===null||typeof e!="object"&&typeof e!="function")return{default:e};var n=wP(t);if(n&&n.has(e))return n.get(e);var r={},i=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var o in e)if(o!=="default"&&Object.prototype.hasOwnProperty.call(e,o)){var a=i?Object.getOwnPropertyDescriptor(e,o):null;a&&(a.get||a.set)?Object.defineProperty(r,o,a):r[o]=e[o]}return r.default=e,n&&n.set(e,r),r}let $o;Zn.RoomMemberEvent=$o;(function(e){e.Membership="RoomMember.membership",e.Name="RoomMember.name",e.PowerLevel="RoomMember.powerLevel",e.Typing="RoomMember.typing"})($o||(Zn.RoomMemberEvent=$o={}));class Oj extends Ij.TypedEventEmitter{constructor(t,n){super(),this.roomId=t,this.userId=n,(0,Fn.default)(this,"_isOutOfBand",!1),(0,Fn.default)(this,"modified",-1),(0,Fn.default)(this,"requestedProfileInfo",!1),(0,Fn.default)(this,"typing",!1),(0,Fn.default)(this,"name",void 0),(0,Fn.default)(this,"rawDisplayName",void 0),(0,Fn.default)(this,"powerLevel",0),(0,Fn.default)(this,"powerLevelNorm",0),(0,Fn.default)(this,"user",void 0),(0,Fn.default)(this,"membership",void 0),(0,Fn.default)(this,"disambiguate",!1),(0,Fn.default)(this,"events",{}),this.name=n,this.rawDisplayName=n,this.updateModifiedTime()}markOutOfBand(){this._isOutOfBand=!0}isOutOfBand(){return this._isOutOfBand}setMembershipEvent(t,n){var r,i;const o=(r=t.getDirectionalContent().displayname)!==null&&r!==void 0?r:"";if(t.getType()!==xw.EventType.RoomMember)return;this._isOutOfBand=!1,this.events.member=t;const a=this.membership;this.membership=t.getDirectionalContent().membership,this.membership===void 0&&Rj.logger.trace(`membership event with membership undefined (forwardLooking: ${t.forwardLooking})!`,t.getContent(),"prevcontent is ",t.getPrevContent()),this.disambiguate=Mj(this.userId,o,n);const c=this.name;this.name=Dj(this.userId,o,this.disambiguate),this.rawDisplayName=na.removeDirectionOverrideChars((i=t.getDirectionalContent().displayname)!==null&&i!==void 0?i:""),(!this.rawDisplayName||!na.removeHiddenChars(this.rawDisplayName))&&(this.rawDisplayName=this.userId),a!==this.membership&&(this.updateModifiedTime(),this.emit($o.Membership,t,this,a)),c!==this.name&&(this.updateModifiedTime(),this.emit($o.Name,t,this,c))}setPowerLevelEvent(t){if(t.getType()!==xw.EventType.RoomPowerLevels||t.getStateKey()!=="")return;const n=t.getDirectionalContent();let r=n.users_default||0;const i=n.users||{};Object.values(i).forEach(c=>{r=Math.max(r,c)});const o=this.powerLevel,a=this.powerLevelNorm;i[this.userId]!==void 0&&Number.isInteger(i[this.userId])?this.powerLevel=i[this.userId]:n.users_default!==void 0?this.powerLevel=n.users_default:this.powerLevel=0,this.powerLevelNorm=0,r>0&&(this.powerLevelNorm=this.powerLevel*100/r),(o!==this.powerLevel||a!==this.powerLevelNorm)&&(this.updateModifiedTime(),this.emit($o.PowerLevel,t,this))}setTypingEvent(t){if(t.getType()!=="m.typing")return;const n=this.typing;this.typing=!1;const r=t.getContent().user_ids;Array.isArray(r)&&(r.indexOf(this.userId)!==-1&&(this.typing=!0),n!==this.typing&&(this.updateModifiedTime(),this.emit($o.Typing,t,this)))}updateModifiedTime(){this.modified=Date.now()}getLastModifiedTime(){return this.modified}isKicked(){return this.membership==="leave"&&this.events.member!==void 0&&this.events.member.getSender()!==this.events.member.getStateKey()}getDMInviter(){if(this.events.member){const t=this.events.member;let n=t.getContent(),r=t.getSender();if(n.membership==="join"&&(n=t.getPrevContent(),r=t.getUnsigned().prev_sender),n.membership==="invite"&&n.is_direct)return r}}getAvatarUrl(t,n,r,i,o=!0,a){const c=this.getMxcAvatarUrl();if(!c&&!o)return null;const f=(0,Tj.getHttpUriForMxc)(t,c,n,r,i,a);return f||null}getMxcAvatarUrl(){if(this.events.member)return this.events.member.getDirectionalContent().avatar_url;if(this.user)return this.user.avatarUrl}}Zn.RoomMember=Oj;const Pj=/@.+:.+/,kj=/[\u200E\u200F\u202A-\u202F]/;function Mj(e,t,n){return!t||t===e||!na.removeHiddenChars(t)||!n?!1:!!(Pj.test(t)||kj.test(t)||n.getUserIdsWithDisplayName(t).some(i=>i!==e))}function Dj(e,t,n){return!t||t===e?e:n?na.removeDirectionOverrideChars(t)+" ("+e+")":na.removeHiddenChars(t)?na.removeDirectionOverrideChars(t):e}var gp={},Fu={},Bf={},Ku={};Object.defineProperty(Ku,"__esModule",{value:!0});Ku.NamespacedMap=void 0;function Aj(e,t){var n=typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(!n){if(Array.isArray(e)||(n=Lj(e))||t&&e&&typeof e.length=="number"){n&&(e=n);var r=0,i=function(){};return{s:i,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(v){throw v},f:i}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
     73 In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var o=!0,a=!1,c;return{s:function(){n=n.call(e)},n:function(){var v=n.next();return o=v.done,v},e:function(v){a=!0,c=v},f:function(){try{!o&&n.return!=null&&n.return()}finally{if(a)throw c}}}}function Lj(e,t){if(e){if(typeof e=="string")return $w(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);if(n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set")return Array.from(e);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return $w(e,t)}}function $w(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n<t;n++)r[n]=e[n];return r}function Nj(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function Uw(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function xj(e,t,n){return t&&Uw(e.prototype,t),n&&Uw(e,n),Object.defineProperty(e,"prototype",{writable:!1}),e}function $j(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var Uj=function(){function e(t){if(Nj(this,e),$j(this,"internalMap",new Map),t){var n=Aj(t),r;try{for(n.s();!(r=n.n()).done;){var i=r.value;this.set(i[0],i[1])}}catch(o){n.e(o)}finally{n.f()}}}return xj(e,[{key:"get",value:function(n){return n.name&&this.internalMap.has(n.name)?this.internalMap.get(n.name):n.altName&&this.internalMap.has(n.altName)?this.internalMap.get(n.altName):null}},{key:"set",value:function(n,r){n.name&&this.internalMap.set(n.name,r),n.altName&&this.internalMap.set(n.altName,r)}},{key:"has",value:function(n){return!!this.get(n)}},{key:"delete",value:function(n){n.name&&this.internalMap.delete(n.name),n.altName&&this.internalMap.delete(n.altName)}},{key:"hasNamespaced",value:function(n){return this.internalMap.has(n)}},{key:"getNamespaced",value:function(n){return this.internalMap.get(n)}}]),e}();Ku.NamespacedMap=Uj;var di={};function Lv(e){return Lv=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Lv(e)}Object.defineProperty(di,"__esModule",{value:!0});di.InvalidEventError=void 0;function Bw(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function Bj(e,t,n){return t&&Bw(e.prototype,t),n&&Bw(e,n),Object.defineProperty(e,"prototype",{writable:!1}),e}function Fj(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function Kj(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&Su(e,t)}function jj(e){var t=bP();return function(){var r=Eu(e),i;if(t){var o=Eu(this).constructor;i=Reflect.construct(r,arguments,o)}else i=r.apply(this,arguments);return qj(this,i)}}function qj(e,t){if(t&&(Lv(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return Vj(e)}function Vj(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function Nv(e){var t=typeof Map=="function"?new Map:void 0;return Nv=function(r){if(r===null||!Wj(r))return r;if(typeof r!="function")throw new TypeError("Super expression must either be null or a function");if(typeof t<"u"){if(t.has(r))return t.get(r);t.set(r,i)}function i(){return cd(r,arguments,Eu(this).constructor)}return i.prototype=Object.create(r.prototype,{constructor:{value:i,enumerable:!1,writable:!0,configurable:!0}}),Su(i,r)},Nv(e)}function cd(e,t,n){return bP()?cd=Reflect.construct:cd=function(i,o,a){var c=[null];c.push.apply(c,o);var f=Function.bind.apply(i,c),v=new f;return a&&Su(v,a.prototype),v},cd.apply(null,arguments)}function bP(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}function Wj(e){return Function.toString.call(e).indexOf("[native code]")!==-1}function Su(e,t){return Su=Object.setPrototypeOf||function(r,i){return r.__proto__=i,r},Su(e,t)}function Eu(e){return Eu=Object.setPrototypeOf?Object.getPrototypeOf:function(n){return n.__proto__||Object.getPrototypeOf(n)},Eu(e)}var Hj=function(e){Kj(n,e);var t=jj(n);function n(r){return Fj(this,n),t.call(this,r)}return Bj(n)}(Nv(Error));di.InvalidEventError=Hj;var wa={},Vr={},ho={};Object.defineProperty(ho,"__esModule",{value:!0});ho.ExtensibleEvent=void 0;function Gj(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function Fw(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function zj(e,t,n){return t&&Fw(e.prototype,t),n&&Fw(e,n),Object.defineProperty(e,"prototype",{writable:!1}),e}var Yj=function(){function e(t){Gj(this,e),this.wireFormat=t}return zj(e,[{key:"wireContent",get:function(){return this.wireFormat.content}}]),e}();ho.ExtensibleEvent=Yj;var ju={};Object.defineProperty(ju,"__esModule",{value:!0});ju.isOptionalAString=Qj;ju.isProvided=TP;function Qj(e){return TP(e)&&typeof e=="string"}function TP(e){return e!=null}var Rt={},_r={};function xv(e){return xv=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},xv(e)}Object.defineProperty(_r,"__esModule",{value:!0});_r.UnstableValue=_r.NamespacedValue=void 0;function Jj(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&$v(e,t)}function $v(e,t){return $v=Object.setPrototypeOf||function(r,i){return r.__proto__=i,r},$v(e,t)}function Xj(e){var t=tq();return function(){var r=zd(e),i;if(t){var o=zd(this).constructor;i=Reflect.construct(r,arguments,o)}else i=r.apply(this,arguments);return Zj(this,i)}}function Zj(e,t){if(t&&(xv(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return eq(e)}function eq(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function tq(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}function zd(e){return zd=Object.setPrototypeOf?Object.getPrototypeOf:function(n){return n.__proto__||Object.getPrototypeOf(n)},zd(e)}function RP(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function Kw(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function IP(e,t,n){return t&&Kw(e.prototype,t),n&&Kw(e,n),Object.defineProperty(e,"prototype",{writable:!1}),e}var CP=function(){function e(t,n){if(RP(this,e),this.stable=t,this.unstable=n,!this.unstable&&!this.stable)throw new Error("One of stable or unstable values must be supplied")}return IP(e,[{key:"name",get:function(){return this.stable?this.stable:this.unstable}},{key:"altName",get:function(){return this.stable?this.unstable:null}},{key:"matches",value:function(n){return!!this.name&&this.name===n||!!this.altName&&this.altName===n}},{key:"findIn",value:function(n){var r;return this.name&&(r=n==null?void 0:n[this.name]),!r&&this.altName&&(r=n==null?void 0:n[this.altName]),r}},{key:"includedIn",value:function(n){var r=!1;return this.name&&(r=n.includes(this.name)),!r&&this.altName&&(r=n.includes(this.altName)),r}}]),e}();_r.NamespacedValue=CP;var nq=function(e){Jj(n,e);var t=Xj(n);function n(r,i){var o;if(RP(this,n),o=t.call(this,r,i),!o.unstable)throw new Error("Unstable value must be supplied");return o}return IP(n,[{key:"name",get:function(){return this.unstable}},{key:"altName",get:function(){return this.stable}}]),n}(CP);_r.UnstableValue=nq;Object.defineProperty(Rt,"__esModule",{value:!0});Rt.M_TEXT=Rt.M_NOTICE=Rt.M_MESSAGE=Rt.M_HTML=Rt.M_EMOTE=void 0;var qu=_r,rq=new qu.UnstableValue("m.message","org.matrix.msc1767.message");Rt.M_MESSAGE=rq;var iq=new qu.UnstableValue("m.text","org.matrix.msc1767.text");Rt.M_TEXT=iq;var oq=new qu.UnstableValue("m.html","org.matrix.msc1767.html");Rt.M_HTML=oq;var sq=new qu.UnstableValue("m.emote","org.matrix.msc1767.emote");Rt.M_EMOTE=sq;var aq=new qu.UnstableValue("m.notice","org.matrix.msc1767.notice");Rt.M_NOTICE=aq;var fi={};Object.defineProperty(fi,"__esModule",{value:!0});fi.isEventTypeSame=lq;function lq(e,t){if(typeof e=="string")return typeof t=="string"?t===e:t.matches(e);if(typeof t=="string")return e.matches(t);var n=t,r=e;return n.matches(r.name)||n.matches(r.altName)}function Uv(e){return Uv=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Uv(e)}Object.defineProperty(Vr,"__esModule",{value:!0});Vr.MessageEvent=void 0;var uq=ho,Wa=ju,vp=di,On=Rt,cq=fi;function jw(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),n.push.apply(n,r)}return n}function qw(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?jw(Object(n),!0).forEach(function(r){Di(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):jw(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function dq(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function Vw(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function fq(e,t,n){return t&&Vw(e.prototype,t),n&&Vw(e,n),Object.defineProperty(e,"prototype",{writable:!1}),e}function hq(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&Bv(e,t)}function Bv(e,t){return Bv=Object.setPrototypeOf||function(r,i){return r.__proto__=i,r},Bv(e,t)}function pq(e){var t=vq();return function(){var r=Yd(e),i;if(t){var o=Yd(this).constructor;i=Reflect.construct(r,arguments,o)}else i=r.apply(this,arguments);return gq(this,i)}}function gq(e,t){if(t&&(Uv(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return dd(e)}function dd(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function vq(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}function Yd(e){return Yd=Object.setPrototypeOf?Object.getPrototypeOf:function(n){return n.__proto__||Object.getPrototypeOf(n)},Yd(e)}function Di(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var mq=function(e){hq(n,e);var t=pq(n);function n(r){var i;dq(this,n),i=t.call(this,r),Di(dd(i),"text",void 0),Di(dd(i),"html",void 0),Di(dd(i),"renderings",void 0);var o=On.M_MESSAGE.findIn(i.wireContent),a=On.M_TEXT.findIn(i.wireContent),c=On.M_HTML.findIn(i.wireContent);if((0,Wa.isProvided)(o)){if(!Array.isArray(o))throw new vp.InvalidEventError("m.message contents must be an array");var f=o.find(function(s){return!(0,Wa.isProvided)(s.mimetype)||s.mimetype==="text/plain"}),v=o.find(function(s){return s.mimetype==="text/html"});if(!f)throw new vp.InvalidEventError("m.message is missing a plain text representation");i.text=f.body,i.html=v==null?void 0:v.body,i.renderings=o}else if((0,Wa.isOptionalAString)(a))i.text=a,i.html=c,i.renderings=[{body:a,mimetype:"text/plain"}],i.html&&i.renderings.push({body:i.html,mimetype:"text/html"});else throw new vp.InvalidEventError("Missing textual representation for event");return i}return fq(n,[{key:"isEmote",get:function(){return On.M_EMOTE.matches(this.wireFormat.type)||(0,Wa.isProvided)(On.M_EMOTE.findIn(this.wireFormat.content))}},{key:"isNotice",get:function(){return On.M_NOTICE.matches(this.wireFormat.type)||(0,Wa.isProvided)(On.M_NOTICE.findIn(this.wireFormat.content))}},{key:"isEquivalentTo",value:function(i){return(0,cq.isEventTypeSame)(i,On.M_MESSAGE)}},{key:"serializeMMessageOnly",value:function(){var i=Di({},On.M_MESSAGE.name,this.renderings);if(this.renderings.length===1){var o=this.renderings[0].mimetype;(o===void 0||o==="text/plain")&&(i=Di({},On.M_TEXT.name,this.renderings[0].body))}return i}},{key:"serialize",value:function(){var i;return{type:"m.room.message",content:qw(qw({},this.serializeMMessageOnly()),{},{body:this.text,msgtype:"m.text",format:this.html?"org.matrix.custom.html":void 0,formatted_body:(i=this.html)!==null&&i!==void 0?i:void 0})}}}],[{key:"from",value:function(i,o){var a;return new n({type:On.M_MESSAGE.name,content:(a={},Di(a,On.M_TEXT.name,i),Di(a,On.M_HTML.name,o),a)})}}]),n}(uq.ExtensibleEvent);Vr.MessageEvent=mq;var ba={};function Fv(e){return Fv=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Fv(e)}Object.defineProperty(ba,"__esModule",{value:!0});ba.NoticeEvent=void 0;var yq=Vr,Mc=Rt,_q=fi;function Ww(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Sq(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function Hw(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function Eq(e,t,n){return t&&Hw(e.prototype,t),n&&Hw(e,n),Object.defineProperty(e,"prototype",{writable:!1}),e}function Jl(){return typeof Reflect<"u"&&Reflect.get?Jl=Reflect.get:Jl=function(t,n,r){var i=wq(t,n);if(i){var o=Object.getOwnPropertyDescriptor(i,n);return o.get?o.get.call(arguments.length<3?t:r):o.value}},Jl.apply(this,arguments)}function wq(e,t){for(;!Object.prototype.hasOwnProperty.call(e,t)&&(e=zo(e),e!==null););return e}function bq(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&Kv(e,t)}function Kv(e,t){return Kv=Object.setPrototypeOf||function(r,i){return r.__proto__=i,r},Kv(e,t)}function Tq(e){var t=Cq();return function(){var r=zo(e),i;if(t){var o=zo(this).constructor;i=Reflect.construct(r,arguments,o)}else i=r.apply(this,arguments);return Rq(this,i)}}function Rq(e,t){if(t&&(Fv(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return Iq(e)}function Iq(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function Cq(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}function zo(e){return zo=Object.setPrototypeOf?Object.getPrototypeOf:function(n){return n.__proto__||Object.getPrototypeOf(n)},zo(e)}var Oq=function(e){bq(n,e);var t=Tq(n);function n(r){return Sq(this,n),t.call(this,r)}return Eq(n,[{key:"isNotice",get:function(){return!0}},{key:"isEquivalentTo",value:function(i){return(0,_q.isEventTypeSame)(i,Mc.M_NOTICE)||Jl(zo(n.prototype),"isEquivalentTo",this).call(this,i)}},{key:"serialize",value:function(){var i=Jl(zo(n.prototype),"serialize",this).call(this);return i.content.msgtype="m.notice",i}}],[{key:"from",value:function(i,o){var a;return new n({type:Mc.M_NOTICE.name,content:(a={},Ww(a,Mc.M_TEXT.name,i),Ww(a,Mc.M_HTML.name,o),a)})}}]),n}(yq.MessageEvent);ba.NoticeEvent=Oq;var Ta={};function jv(e){return jv=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},jv(e)}Object.defineProperty(Ta,"__esModule",{value:!0});Ta.EmoteEvent=void 0;var Pq=Vr,Dc=Rt,kq=fi;function Gw(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Mq(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function zw(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function Dq(e,t,n){return t&&zw(e.prototype,t),n&&zw(e,n),Object.defineProperty(e,"prototype",{writable:!1}),e}function Xl(){return typeof Reflect<"u"&&Reflect.get?Xl=Reflect.get:Xl=function(t,n,r){var i=Aq(t,n);if(i){var o=Object.getOwnPropertyDescriptor(i,n);return o.get?o.get.call(arguments.length<3?t:r):o.value}},Xl.apply(this,arguments)}function Aq(e,t){for(;!Object.prototype.hasOwnProperty.call(e,t)&&(e=Yo(e),e!==null););return e}function Lq(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&qv(e,t)}function qv(e,t){return qv=Object.setPrototypeOf||function(r,i){return r.__proto__=i,r},qv(e,t)}function Nq(e){var t=Uq();return function(){var r=Yo(e),i;if(t){var o=Yo(this).constructor;i=Reflect.construct(r,arguments,o)}else i=r.apply(this,arguments);return xq(this,i)}}function xq(e,t){if(t&&(jv(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return $q(e)}function $q(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function Uq(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}function Yo(e){return Yo=Object.setPrototypeOf?Object.getPrototypeOf:function(n){return n.__proto__||Object.getPrototypeOf(n)},Yo(e)}var Bq=function(e){Lq(n,e);var t=Nq(n);function n(r){return Mq(this,n),t.call(this,r)}return Dq(n,[{key:"isEmote",get:function(){return!0}},{key:"isEquivalentTo",value:function(i){return(0,kq.isEventTypeSame)(i,Dc.M_EMOTE)||Xl(Yo(n.prototype),"isEquivalentTo",this).call(this,i)}},{key:"serialize",value:function(){var i=Xl(Yo(n.prototype),"serialize",this).call(this);return i.content.msgtype="m.emote",i}}],[{key:"from",value:function(i,o){var a;return new n({type:Dc.M_EMOTE.name,content:(a={},Gw(a,Dc.M_TEXT.name,i),Gw(a,Dc.M_HTML.name,o),a)})}}]),n}(Pq.MessageEvent);Ta.EmoteEvent=Bq;Object.defineProperty(wa,"__esModule",{value:!0});wa.LEGACY_M_ROOM_MESSAGE=void 0;wa.parseMRoomMessage=Vq;var Yw=Vr,Fq=ba,Kq=Ta,jq=_r,yi=Rt;function Qw(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),n.push.apply(n,r)}return n}function Kn(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?Qw(Object(n),!0).forEach(function(r){ko(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Qw(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function ko(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var qq=new jq.NamespacedValue("m.room.message");wa.LEGACY_M_ROOM_MESSAGE=qq;function Vq(e){var t,n,r;if(yi.M_MESSAGE.findIn(e.content)||yi.M_TEXT.findIn(e.content))return new Yw.MessageEvent(e);var i=(t=e.content)===null||t===void 0?void 0:t.msgtype,o=(n=e.content)===null||n===void 0?void 0:n.body,a=((r=e.content)===null||r===void 0?void 0:r.format)==="org.matrix.custom.html"?e.content.formatted_body:null;if(i==="m.text"){var c;return new Yw.MessageEvent(Kn(Kn({},e),{},{content:Kn(Kn({},e.content),{},(c={},ko(c,yi.M_TEXT.name,o),ko(c,yi.M_HTML.name,a),c))}))}else if(i==="m.notice"){var f;return new Fq.NoticeEvent(Kn(Kn({},e),{},{content:Kn(Kn({},e.content),{},(f={},ko(f,yi.M_TEXT.name,o),ko(f,yi.M_HTML.name,a),f))}))}else if(i==="m.emote"){var v;return new Kq.EmoteEvent(Kn(Kn({},e),{},{content:Kn(Kn({},e.content),{},(v={},ko(v,yi.M_TEXT.name,o),ko(v,yi.M_HTML.name,a),v))}))}else return null}var Ff={};Object.defineProperty(Ff,"__esModule",{value:!0});Ff.parseMMessage=zq;var Wq=Vr,Jw=Rt,Hq=Ta,Gq=ba;function zq(e){return Jw.M_EMOTE.matches(e.type)?new Hq.EmoteEvent(e):Jw.M_NOTICE.matches(e.type)?new Gq.NoticeEvent(e):new Wq.MessageEvent(e)}var Kt={};Object.defineProperty(Kt,"__esModule",{value:!0});Kt.M_POLL_START=Kt.M_POLL_RESPONSE=Kt.M_POLL_KIND_UNDISCLOSED=Kt.M_POLL_KIND_DISCLOSED=Kt.M_POLL_END=void 0;var Vu=_r,Yq=new Vu.UnstableValue("m.poll.disclosed","org.matrix.msc3381.poll.disclosed");Kt.M_POLL_KIND_DISCLOSED=Yq;var Qq=new Vu.UnstableValue("m.poll.undisclosed","org.matrix.msc3381.poll.undisclosed");Kt.M_POLL_KIND_UNDISCLOSED=Qq;var Jq=new Vu.UnstableValue("m.poll.start","org.matrix.msc3381.poll.start");Kt.M_POLL_START=Jq;var Xq=new Vu.UnstableValue("m.poll.response","org.matrix.msc3381.poll.response");Kt.M_POLL_RESPONSE=Xq;var Zq=new Vu.UnstableValue("m.poll.end","org.matrix.msc3381.poll.end");Kt.M_POLL_END=Zq;var Kf={},Qo={};function Vv(e){return Vv=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Vv(e)}Object.defineProperty(Qo,"__esModule",{value:!0});Qo.PollStartEvent=Qo.PollAnswerSubevent=void 0;var Wr=Kt,OP=Vr,Nl=Rt,fd=di,eV=_r,tV=fi,nV=ho;function rV(e){return aV(e)||sV(e)||oV(e)||iV()}function iV(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
     74 In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function oV(e,t){if(e){if(typeof e=="string")return Wv(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);if(n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set")return Array.from(e);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return Wv(e,t)}}function sV(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function aV(e){if(Array.isArray(e))return Wv(e)}function Wv(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n<t;n++)r[n]=e[n];return r}function Xw(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),n.push.apply(n,r)}return n}function lV(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?Xw(Object(n),!0).forEach(function(r){Sn(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Xw(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function PP(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function Zw(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function kP(e,t,n){return t&&Zw(e.prototype,t),n&&Zw(e,n),Object.defineProperty(e,"prototype",{writable:!1}),e}function MP(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&Hv(e,t)}function Hv(e,t){return Hv=Object.setPrototypeOf||function(r,i){return r.__proto__=i,r},Hv(e,t)}function DP(e){var t=cV();return function(){var r=Qd(e),i;if(t){var o=Qd(this).constructor;i=Reflect.construct(r,arguments,o)}else i=r.apply(this,arguments);return uV(this,i)}}function uV(e,t){if(t&&(Vv(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return Ao(e)}function Ao(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function cV(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}function Qd(e){return Qd=Object.setPrototypeOf?Object.getPrototypeOf:function(n){return n.__proto__||Object.getPrototypeOf(n)},Qd(e)}function Sn(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var AP=function(e){MP(n,e);var t=DP(n);function n(r){var i;PP(this,n),i=t.call(this,r),Sn(Ao(i),"id",void 0);var o=r.content.id;if(!o||typeof o!="string")throw new fd.InvalidEventError("Answer ID must be a non-empty string");return i.id=o,i}return kP(n,[{key:"serialize",value:function(){return{type:"org.matrix.sdk.poll.answer",content:lV({id:this.id},this.serializeMMessageOnly())}}}],[{key:"from",value:function(i,o){return new n({type:"org.matrix.sdk.poll.answer",content:Sn({id:i},Nl.M_TEXT.name,o)})}}]),n}(OP.MessageEvent);Qo.PollAnswerSubevent=AP;var dV=function(e){MP(n,e);var t=DP(n);function n(r){var i;PP(this,n),i=t.call(this,r),Sn(Ao(i),"question",void 0),Sn(Ao(i),"kind",void 0),Sn(Ao(i),"rawKind",void 0),Sn(Ao(i),"maxSelections",void 0),Sn(Ao(i),"answers",void 0);var o=Wr.M_POLL_START.findIn(i.wireContent);if(!o.question)throw new fd.InvalidEventError("A question is required");if(i.question=new OP.MessageEvent({type:"org.matrix.sdk.poll.question",content:o.question}),i.rawKind=o.kind,Wr.M_POLL_KIND_DISCLOSED.matches(i.rawKind)?i.kind=Wr.M_POLL_KIND_DISCLOSED:i.kind=Wr.M_POLL_KIND_UNDISCLOSED,i.maxSelections=Number.isFinite(o.max_selections)&&o.max_selections>0?o.max_selections:1,!Array.isArray(o.answers))throw new fd.InvalidEventError("Poll answers must be an array");var a=o.answers.slice(0,20).map(function(c){return new AP({type:"org.matrix.sdk.poll.answer",content:c})});if(a.length<=0)throw new fd.InvalidEventError("No answers available");return i.answers=a,i}return kP(n,[{key:"isEquivalentTo",value:function(i){return(0,tV.isEventTypeSame)(i,Wr.M_POLL_START)}},{key:"serialize",value:function(){var i;return{type:Wr.M_POLL_START.name,content:(i={},Sn(i,Wr.M_POLL_START.name,{question:this.question.serialize().content,kind:this.rawKind,max_selections:this.maxSelections,answers:this.answers.map(function(o){return o.serialize().content})}),Sn(i,Nl.M_TEXT.name,"".concat(this.question.text,`
     75 `).concat(this.answers.map(function(o,a){return"".concat(a+1,". ").concat(o.text)}).join(`
     76 `))),i)}}}],[{key:"from",value:function(i,o,a){var c,f=arguments.length>3&&arguments[3]!==void 0?arguments[3]:1;return new n({type:Wr.M_POLL_START.name,content:(c={},Sn(c,Nl.M_TEXT.name,i),Sn(c,Wr.M_POLL_START.name,{question:Sn({},Nl.M_TEXT.name,i),kind:a instanceof eV.NamespacedValue?a.name:a,max_selections:f,answers:o.map(function(v){return Sn({id:fV()},Nl.M_TEXT.name,v)})}),c)})}}]),n}(nV.ExtensibleEvent);Qo.PollStartEvent=dV;var e0="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";function fV(){return rV(Array(16)).map(function(){return e0.charAt(Math.floor(Math.random()*e0.length))}).join("")}var Wu={},Ra={};Object.defineProperty(Ra,"__esModule",{value:!0});Ra.REFERENCE_RELATION=void 0;var hV=_r,pV=new hV.NamespacedValue("m.reference");Ra.REFERENCE_RELATION=pV;function Gv(e){return Gv=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Gv(e)}Object.defineProperty(Wu,"__esModule",{value:!0});Wu.PollResponseEvent=void 0;var gV=ho,us=Kt,vV=di,mp=Ra,mV=fi;function yV(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function t0(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function _V(e,t,n){return t&&t0(e.prototype,t),n&&t0(e,n),Object.defineProperty(e,"prototype",{writable:!1}),e}function SV(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&zv(e,t)}function zv(e,t){return zv=Object.setPrototypeOf||function(r,i){return r.__proto__=i,r},zv(e,t)}function EV(e){var t=bV();return function(){var r=Jd(e),i;if(t){var o=Jd(this).constructor;i=Reflect.construct(r,arguments,o)}else i=r.apply(this,arguments);return wV(this,i)}}function wV(e,t){if(t&&(Gv(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return hd(e)}function hd(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function bV(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}function Jd(e){return Jd=Object.setPrototypeOf?Object.getPrototypeOf:function(n){return n.__proto__||Object.getPrototypeOf(n)},Jd(e)}function Ha(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var TV=function(e){SV(n,e);var t=EV(n);function n(r){var i;yV(this,n),i=t.call(this,r),Ha(hd(i),"internalAnswerIds",void 0),Ha(hd(i),"internalSpoiled",void 0),Ha(hd(i),"pollEventId",void 0);var o=i.wireContent["m.relates_to"];if(!mp.REFERENCE_RELATION.matches(o==null?void 0:o.rel_type)||typeof(o==null?void 0:o.event_id)!="string")throw new vV.InvalidEventError("Relationship must be a reference to an event");return i.pollEventId=o.event_id,i.validateAgainst(null),i}return _V(n,[{key:"answerIds",get:function(){return this.internalAnswerIds}},{key:"spoiled",get:function(){return this.internalSpoiled}},{key:"validateAgainst",value:function(i){var o=us.M_POLL_RESPONSE.findIn(this.wireContent);if(!Array.isArray(o==null?void 0:o.answers)){this.internalSpoiled=!0,this.internalAnswerIds=[];return}var a=o.answers;if(a.some(function(c){return typeof c!="string"})||a.length===0){this.internalSpoiled=!0,this.internalAnswerIds=[];return}if(i){if(a.some(function(c){return!i.answers.some(function(f){return f.id===c})})){this.internalSpoiled=!0,this.internalAnswerIds=[];return}a=a.slice(0,i.maxSelections)}this.internalAnswerIds=a,this.internalSpoiled=!1}},{key:"isEquivalentTo",value:function(i){return(0,mV.isEventTypeSame)(i,us.M_POLL_RESPONSE)}},{key:"serialize",value:function(){return{type:us.M_POLL_RESPONSE.name,content:Ha({"m.relates_to":{rel_type:mp.REFERENCE_RELATION.name,event_id:this.pollEventId}},us.M_POLL_RESPONSE.name,{answers:this.spoiled?void 0:this.answerIds})}}}],[{key:"from",value:function(i,o){return new n({type:us.M_POLL_RESPONSE.name,content:Ha({"m.relates_to":{rel_type:mp.REFERENCE_RELATION.name,event_id:o}},us.M_POLL_RESPONSE.name,{answers:i})})}}]),n}(gV.ExtensibleEvent);Wu.PollResponseEvent=TV;var Hu={};function Yv(e){return Yv=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Yv(e)}Object.defineProperty(Hu,"__esModule",{value:!0});Hu.PollEndEvent=void 0;var Ga=Kt,RV=di,yp=Ra,IV=Vr,CV=Rt,OV=fi,PV=ho;function n0(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),n.push.apply(n,r)}return n}function kV(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?n0(Object(n),!0).forEach(function(r){As(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):n0(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function MV(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function r0(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function DV(e,t,n){return t&&r0(e.prototype,t),n&&r0(e,n),Object.defineProperty(e,"prototype",{writable:!1}),e}function AV(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&Qv(e,t)}function Qv(e,t){return Qv=Object.setPrototypeOf||function(r,i){return r.__proto__=i,r},Qv(e,t)}function LV(e){var t=xV();return function(){var r=Xd(e),i;if(t){var o=Xd(this).constructor;i=Reflect.construct(r,arguments,o)}else i=r.apply(this,arguments);return NV(this,i)}}function NV(e,t){if(t&&(Yv(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return Jv(e)}function Jv(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function xV(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}function Xd(e){return Xd=Object.setPrototypeOf?Object.getPrototypeOf:function(n){return n.__proto__||Object.getPrototypeOf(n)},Xd(e)}function As(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var $V=function(e){AV(n,e);var t=LV(n);function n(r){var i;MV(this,n),i=t.call(this,r),As(Jv(i),"pollEventId",void 0),As(Jv(i),"closingMessage",void 0);var o=i.wireContent["m.relates_to"];if(!yp.REFERENCE_RELATION.matches(o==null?void 0:o.rel_type)||typeof(o==null?void 0:o.event_id)!="string")throw new RV.InvalidEventError("Relationship must be a reference to an event");return i.pollEventId=o.event_id,i.closingMessage=new IV.MessageEvent(i.wireFormat),i}return DV(n,[{key:"isEquivalentTo",value:function(i){return(0,OV.isEventTypeSame)(i,Ga.M_POLL_END)}},{key:"serialize",value:function(){return{type:Ga.M_POLL_END.name,content:kV(As({"m.relates_to":{rel_type:yp.REFERENCE_RELATION.name,event_id:this.pollEventId}},Ga.M_POLL_END.name,{}),this.closingMessage.serialize().content)}}}],[{key:"from",value:function(i,o){var a;return new n({type:Ga.M_POLL_END.name,content:(a={"m.relates_to":{rel_type:yp.REFERENCE_RELATION.name,event_id:i}},As(a,Ga.M_POLL_END.name,{}),As(a,CV.M_TEXT.name,o),a)})}}]),n}(PV.ExtensibleEvent);Hu.PollEndEvent=$V;Object.defineProperty(Kf,"__esModule",{value:!0});Kf.parseMPoll=KV;var _p=Kt,UV=Qo,BV=Wu,FV=Hu;function KV(e){return _p.M_POLL_START.matches(e.type)?new UV.PollStartEvent(e):_p.M_POLL_RESPONSE.matches(e.type)?new BV.PollResponseEvent(e):_p.M_POLL_END.matches(e.type)?new FV.PollEndEvent(e):null}Object.defineProperty(Bf,"__esModule",{value:!0});Bf.ExtensibleEvents=void 0;var jV=Ku,qV=di,i0=wa,Sp=Ff,Ac=Rt,Ep=Kt,wp=Kf;function VV(e,t){var n=typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(!n){if(Array.isArray(e)||(n=WV(e))||t&&e&&typeof e.length=="number"){n&&(e=n);var r=0,i=function(){};return{s:i,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(v){throw v},f:i}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
     77 In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var o=!0,a=!1,c;return{s:function(){n=n.call(e)},n:function(){var v=n.next();return o=v.done,v},e:function(v){a=!0,c=v},f:function(){try{!o&&n.return!=null&&n.return()}finally{if(a)throw c}}}}function WV(e,t){if(e){if(typeof e=="string")return o0(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);if(n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set")return Array.from(e);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return o0(e,t)}}function o0(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n<t;n++)r[n]=e[n];return r}function HV(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function s0(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function GV(e,t,n){return t&&s0(e.prototype,t),n&&s0(e,n),Object.defineProperty(e,"prototype",{writable:!1}),e}function Xv(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var Zv=function(){function e(){HV(this,e),Xv(this,"interpreters",new jV.NamespacedMap([[i0.LEGACY_M_ROOM_MESSAGE,i0.parseMRoomMessage],[Ac.M_MESSAGE,Sp.parseMMessage],[Ac.M_EMOTE,Sp.parseMMessage],[Ac.M_NOTICE,Sp.parseMMessage],[Ep.M_POLL_START,wp.parseMPoll],[Ep.M_POLL_RESPONSE,wp.parseMPoll],[Ep.M_POLL_END,wp.parseMPoll]])),Xv(this,"_unknownInterpretOrder",[Ac.M_MESSAGE])}return GV(e,[{key:"unknownInterpretOrder",get:function(){var n;return(n=this._unknownInterpretOrder)!==null&&n!==void 0?n:[]},set:function(n){this._unknownInterpretOrder=n}},{key:"registerInterpreter",value:function(n,r){this.interpreters.set(n,r)}},{key:"parse",value:function(n){try{if(this.interpreters.hasNamespaced(n.type))return this.interpreters.getNamespaced(n.type)(n);var r=VV(this.unknownInterpretOrder),i;try{for(r.s();!(i=r.n()).done;){var o=i.value;if(this.interpreters.has(o)){var a=this.interpreters.get(o)(n);if(a)return a}}}catch(c){r.e(c)}finally{r.f()}return null}catch(c){if(c instanceof qV.InvalidEventError)return null;throw c}}}],[{key:"defaultInstance",get:function(){return e._defaultInstance}},{key:"unknownInterpretOrder",get:function(){return e.defaultInstance.unknownInterpretOrder},set:function(n){e.defaultInstance.unknownInterpretOrder=n}},{key:"registerInterpreter",value:function(n,r){e.defaultInstance.registerInterpreter(n,r)}},{key:"parse",value:function(n){return e.defaultInstance.parse(n)}}]),e}();Bf.ExtensibleEvents=Zv;Xv(Zv,"_defaultInstance",new Zv);var LP={};Object.defineProperty(LP,"__esModule",{value:!0});var Ia={};Object.defineProperty(Ia,"__esModule",{value:!0});Ia.LegacyMsgType=void 0;Ia.isEventLike=zV;var bp=Rt,ra;Ia.LegacyMsgType=ra;(function(e){e.Text="m.text",e.Notice="m.notice",e.Emote="m.emote"})(ra||(Ia.LegacyMsgType=ra={}));function zV(e,t){var n=e.content;return t===ra.Text?bp.M_MESSAGE.matches(e.type)||e.type==="m.room.message"&&(n==null?void 0:n.msgtype)==="m.text":t===ra.Emote?bp.M_EMOTE.matches(e.type)||e.type==="m.room.message"&&(n==null?void 0:n.msgtype)==="m.emote":t===ra.Notice?bp.M_NOTICE.matches(e.type)||e.type==="m.room.message"&&(n==null?void 0:n.msgtype)==="m.notice":!1}(function(e){Object.defineProperty(e,"__esModule",{value:!0});var t=Bf;Object.keys(t).forEach(function(E){E==="default"||E==="__esModule"||E in e&&e[E]===t[E]||Object.defineProperty(e,E,{enumerable:!0,get:function(){return t[E]}})});var n=LP;Object.keys(n).forEach(function(E){E==="default"||E==="__esModule"||E in e&&e[E]===n[E]||Object.defineProperty(e,E,{enumerable:!0,get:function(){return n[E]}})});var r=di;Object.keys(r).forEach(function(E){E==="default"||E==="__esModule"||E in e&&e[E]===r[E]||Object.defineProperty(e,E,{enumerable:!0,get:function(){return r[E]}})});var i=_r;Object.keys(i).forEach(function(E){E==="default"||E==="__esModule"||E in e&&e[E]===i[E]||Object.defineProperty(e,E,{enumerable:!0,get:function(){return i[E]}})});var o=Ku;Object.keys(o).forEach(function(E){E==="default"||E==="__esModule"||E in e&&e[E]===o[E]||Object.defineProperty(e,E,{enumerable:!0,get:function(){return o[E]}})});var a=ju;Object.keys(a).forEach(function(E){E==="default"||E==="__esModule"||E in e&&e[E]===a[E]||Object.defineProperty(e,E,{enumerable:!0,get:function(){return a[E]}})});var c=Ia;Object.keys(c).forEach(function(E){E==="default"||E==="__esModule"||E in e&&e[E]===c[E]||Object.defineProperty(e,E,{enumerable:!0,get:function(){return c[E]}})});var f=fi;Object.keys(f).forEach(function(E){E==="default"||E==="__esModule"||E in e&&e[E]===f[E]||Object.defineProperty(e,E,{enumerable:!0,get:function(){return f[E]}})});var v=wa;Object.keys(v).forEach(function(E){E==="default"||E==="__esModule"||E in e&&e[E]===v[E]||Object.defineProperty(e,E,{enumerable:!0,get:function(){return v[E]}})});var s=Ff;Object.keys(s).forEach(function(E){E==="default"||E==="__esModule"||E in e&&e[E]===s[E]||Object.defineProperty(e,E,{enumerable:!0,get:function(){return s[E]}})});var g=Kf;Object.keys(g).forEach(function(E){E==="default"||E==="__esModule"||E in e&&e[E]===g[E]||Object.defineProperty(e,E,{enumerable:!0,get:function(){return g[E]}})});var y=Ra;Object.keys(y).forEach(function(E){E==="default"||E==="__esModule"||E in e&&e[E]===y[E]||Object.defineProperty(e,E,{enumerable:!0,get:function(){return y[E]}})});var S=ho;Object.keys(S).forEach(function(E){E==="default"||E==="__esModule"||E in e&&e[E]===S[E]||Object.defineProperty(e,E,{enumerable:!0,get:function(){return S[E]}})});var m=Rt;Object.keys(m).forEach(function(E){E==="default"||E==="__esModule"||E in e&&e[E]===m[E]||Object.defineProperty(e,E,{enumerable:!0,get:function(){return m[E]}})});var p=Vr;Object.keys(p).forEach(function(E){E==="default"||E==="__esModule"||E in e&&e[E]===p[E]||Object.defineProperty(e,E,{enumerable:!0,get:function(){return p[E]}})});var _=Ta;Object.keys(_).forEach(function(E){E==="default"||E==="__esModule"||E in e&&e[E]===_[E]||Object.defineProperty(e,E,{enumerable:!0,get:function(){return _[E]}})});var u=ba;Object.keys(u).forEach(function(E){E==="default"||E==="__esModule"||E in e&&e[E]===u[E]||Object.defineProperty(e,E,{enumerable:!0,get:function(){return u[E]}})});var l=Kt;Object.keys(l).forEach(function(E){E==="default"||E==="__esModule"||E in e&&e[E]===l[E]||Object.defineProperty(e,E,{enumerable:!0,get:function(){return l[E]}})});var d=Qo;Object.keys(d).forEach(function(E){E==="default"||E==="__esModule"||E in e&&e[E]===d[E]||Object.defineProperty(e,E,{enumerable:!0,get:function(){return d[E]}})});var h=Wu;Object.keys(h).forEach(function(E){E==="default"||E==="__esModule"||E in e&&e[E]===h[E]||Object.defineProperty(e,E,{enumerable:!0,get:function(){return h[E]}})});var w=Hu;Object.keys(w).forEach(function(E){E==="default"||E==="__esModule"||E in e&&e[E]===w[E]||Object.defineProperty(e,E,{enumerable:!0,get:function(){return w[E]}})})})(Fu);var Et={},bt={};const YV=lf(gA);var Hr={},Gt={},_i={},Si={},a0;function Tr(){if(a0)return Si;a0=1;var e=Ae;Object.defineProperty(Si,"__esModule",{value:!0}),Si.EventTimeline=Si.Direction=void 0;var t=e(Ue),n=Ge(),r=po(),i=xe;let o;Si.Direction=o,function(c){c.Backward="b",c.Forward="f"}(o||(Si.Direction=o={}));class a{static setEventMetadata(f,v,s){var g,y,S,m;(g=f.sender)!==null&&g!==void 0&&(y=g.events)!==null&&y!==void 0&&y.member||(f.sender=v.getSentinelMember(f.getSender())),!((S=f.target)!==null&&S!==void 0&&(m=S.events)!==null&&m!==void 0&&m.member)&&f.getType()===i.EventType.RoomMember&&(f.target=v.getSentinelMember(f.getStateKey())),f.isState()&&s&&(f.forwardLooking=!1)}constructor(f){var v,s;this.eventTimelineSet=f,(0,t.default)(this,"roomId",void 0),(0,t.default)(this,"name",void 0),(0,t.default)(this,"events",[]),(0,t.default)(this,"baseIndex",0),(0,t.default)(this,"startState",void 0),(0,t.default)(this,"endState",void 0),(0,t.default)(this,"startToken",null),(0,t.default)(this,"endToken",null),(0,t.default)(this,"prevTimeline",null),(0,t.default)(this,"nextTimeline",null),(0,t.default)(this,"paginationRequests",{[o.Backward]:null,[o.Forward]:null}),this.roomId=(v=(s=f.room)===null||s===void 0?void 0:s.roomId)!==null&&v!==void 0?v:null,this.roomId&&(this.startState=new r.RoomState(this.roomId),this.endState=new r.RoomState(this.roomId)),this.paginationRequests={b:null,f:null},this.name=this.roomId+":"+new Date().toISOString()}initialiseState(f,{timelineWasEmpty:v}={}){var s,g;if(this.events.length>0)throw new Error("Cannot initialise state after events are added");(s=this.startState)===null||s===void 0||s.setStateEvents(f,{timelineWasEmpty:v}),(g=this.endState)===null||g===void 0||g.setStateEvents(f,{timelineWasEmpty:v})}forkLive(f){const v=this.getState(f),s=new a(this.eventTimelineSet);return s.startState=v==null?void 0:v.clone(),s.endState=v,this.endState=v==null?void 0:v.clone(),s}fork(f){const v=this.getState(f),s=new a(this.eventTimelineSet);return s.startState=v==null?void 0:v.clone(),s.endState=v==null?void 0:v.clone(),s}getRoomId(){return this.roomId}getFilter(){return this.eventTimelineSet.getFilter()}getTimelineSet(){return this.eventTimelineSet}getBaseIndex(){return this.baseIndex}getEvents(){return this.events}getState(f){if(f==a.BACKWARDS)return this.startState;if(f==a.FORWARDS)return this.endState;throw new Error("Invalid direction '"+f+"'")}getPaginationToken(f){return this.roomId?this.getState(f).paginationToken:f===o.Backward?this.startToken:this.endToken}setPaginationToken(f,v){this.roomId?this.getState(v).paginationToken=f:v===o.Backward?this.startToken=f:this.endToken=f}getNeighbouringTimeline(f){if(f==a.BACKWARDS)return this.prevTimeline;if(f==a.FORWARDS)return this.nextTimeline;throw new Error("Invalid direction '"+f+"'")}setNeighbouringTimeline(f,v){if(this.getNeighbouringTimeline(v))throw new Error("timeline already has a neighbouring timeline - cannot reset neighbour (direction: "+v+")");if(v==a.BACKWARDS)this.prevTimeline=f;else if(v==a.FORWARDS)this.nextTimeline=f;else throw new Error("Invalid direction '"+v+"'");this.setPaginationToken(null,v)}addEvent(f,v,s){let g=!!v,y;typeof v=="object"?{toStartOfTimeline:g,roomState:s,timelineWasEmpty:y}=v:v!==void 0&&n.logger.warn("Overload deprecated: `EventTimeline.addEvent(event, toStartOfTimeline, roomState?)` is deprecated in favor of the overload with `EventTimeline.addEvent(event, IAddEventOptions)`"),s||(s=g?this.startState:this.endState);const S=this.getTimelineSet();if(S.room&&(a.setEventMetadata(f,s,g),f.isState()&&S.room.getUnfilteredTimelineSet()===S)){var m;(m=s)===null||m===void 0||m.setStateEvents([f],{timelineWasEmpty:y}),(!f.sender||f.getType()===i.EventType.RoomMember&&!g)&&a.setEventMetadata(f,s,g)}let p;g?p=0:p=this.events.length,this.events.splice(p,0,f),g&&this.baseIndex++}removeEvent(f){for(let v=this.events.length-1;v>=0;v--){const s=this.events[v];if(s.getId()==f)return this.events.splice(v,1),v<this.baseIndex&&this.baseIndex--,s}return null}toString(){return this.name}}return Si.EventTimeline=a,(0,t.default)(a,"BACKWARDS",o.Backward),(0,t.default)(a,"FORWARDS",o.Forward),Si}var za={},Ei={},l0;function QV(){if(l0)return Ei;l0=1;var e=Ae;Object.defineProperty(Ei,"__esModule",{value:!0}),Ei.RelationsEvent=Ei.Relations=void 0;var t=e(Ue),n=nn(),r=Ge(),i=xe,o=Pt(),a=hi();let c;Ei.RelationsEvent=c,function(v){v.Add="Relations.add",v.Remove="Relations.remove",v.Redaction="Relations.redaction"}(c||(Ei.RelationsEvent=c={}));class f extends o.TypedEventEmitter{constructor(s,g,y){super(),this.relationType=s,this.eventType=g,(0,t.default)(this,"relationEventIds",new Set),(0,t.default)(this,"relations",new Set),(0,t.default)(this,"annotationsByKey",{}),(0,t.default)(this,"annotationsBySender",{}),(0,t.default)(this,"sortedAnnotationsByKey",[]),(0,t.default)(this,"targetEvent",null),(0,t.default)(this,"creationEmitted",!1),(0,t.default)(this,"client",void 0),(0,t.default)(this,"onEventStatus",(S,m)=>{if(!S.isSending()){S.removeListener(n.MatrixEventEvent.Status,this.onEventStatus);return}m===n.EventStatus.CANCELLED&&(S.removeListener(n.MatrixEventEvent.Status,this.onEventStatus),this.removeEvent(S))}),(0,t.default)(this,"onBeforeRedaction",async S=>{if(this.relations.has(S)){if(this.relations.delete(S),this.relationType===i.RelationType.Annotation)this.removeAnnotationFromAggregation(S);else if(this.relationType===i.RelationType.Replace&&this.targetEvent&&!this.targetEvent.isState()){const m=await this.getLastReplacement();this.targetEvent.makeReplaced(m)}S.removeListener(n.MatrixEventEvent.BeforeRedaction,this.onBeforeRedaction),this.emit(c.Redaction,S)}}),this.client=y instanceof a.Room?y.client:y}async addEvent(s){if(this.relationEventIds.has(s.getId()))return;const g=s.getRelation();if(!g){r.logger.error("Event must have relation info");return}const y=g.rel_type,S=s.getType();if(this.relationType!==y||this.eventType!==S){r.logger.error("Event relation info doesn't match this container");return}if(s.isSending()&&s.on(n.MatrixEventEvent.Status,this.onEventStatus),this.relations.add(s),this.relationEventIds.add(s.getId()),this.relationType===i.RelationType.Annotation)this.addAnnotationToAggregation(s);else if(this.relationType===i.RelationType.Replace&&this.targetEvent&&!this.targetEvent.isState()){const m=await this.getLastReplacement();this.targetEvent.makeReplaced(m)}s.on(n.MatrixEventEvent.BeforeRedaction,this.onBeforeRedaction),this.emit(c.Add,s),this.maybeEmitCreated()}async removeEvent(s){if(!this.relations.has(s))return;const g=s.getRelation();if(!g){r.logger.error("Event must have relation info");return}const y=g.rel_type,S=s.getType();if(this.relationType!==y||this.eventType!==S){r.logger.error("Event relation info doesn't match this container");return}if(this.relations.delete(s),this.relationType===i.RelationType.Annotation)this.removeAnnotationFromAggregation(s);else if(this.relationType===i.RelationType.Replace&&this.targetEvent&&!this.targetEvent.isState()){const m=await this.getLastReplacement();this.targetEvent.makeReplaced(m)}this.emit(c.Remove,s)}getRelations(){return[...this.relations]}addAnnotationToAggregation(s){var g;const{key:y}=(g=s.getRelation())!==null&&g!==void 0?g:{};if(!y)return;let S=this.annotationsByKey[y];S||(S=this.annotationsByKey[y]=new Set,this.sortedAnnotationsByKey.push([y,S])),S.add(s),this.sortedAnnotationsByKey.sort((_,u)=>{const l=_[1];return u[1].size-l.size});const m=s.getSender();let p=this.annotationsBySender[m];p||(p=this.annotationsBySender[m]=new Set),p.add(s)}removeAnnotationFromAggregation(s){var g;const{key:y}=(g=s.getRelation())!==null&&g!==void 0?g:{};if(!y)return;const S=this.annotationsByKey[y];S&&(S.delete(s),this.sortedAnnotationsByKey.sort((_,u)=>{const l=_[1];return u[1].size-l.size}));const m=s.getSender(),p=this.annotationsBySender[m];p&&p.delete(s)}getSortedAnnotationsByKey(){return this.relationType!==i.RelationType.Annotation?null:this.sortedAnnotationsByKey}getAnnotationsBySender(){return this.relationType!==i.RelationType.Annotation?null:this.annotationsBySender}async getLastReplacement(){if(this.relationType!==i.RelationType.Replace||!this.targetEvent)return null;const s=this.targetEvent.getServerAggregatedRelation(i.RelationType.Replace),g=s==null?void 0:s.origin_server_ts,y=this.getRelations().reduce((S,m)=>m.getSender()!==this.targetEvent.getSender()||g&&g>m.getTs()||S&&S.getTs()>m.getTs()?S:m,null);return y!=null&&y.shouldAttemptDecryption()&&this.client.isCryptoEnabled()?await y.attemptDecryption(this.client.crypto):y!=null&&y.isBeingDecrypted()&&await y.getDecryptionPromise(),y}async setTargetEvent(s){if(!this.targetEvent){if(this.targetEvent=s,this.relationType===i.RelationType.Replace&&!this.targetEvent.isState()){const g=await this.getLastReplacement();g&&this.targetEvent.makeReplaced(g)}this.maybeEmitCreated()}}maybeEmitCreated(){this.creationEmitted||!this.targetEvent||!this.relations.size||(this.creationEmitted=!0,this.targetEvent.emit(n.MatrixEventEvent.RelationsCreated,this.relationType,this.eventType))}}return Ei.Relations=f,Ei}var u0;function NP(){if(u0)return za;u0=1;var e=Ae;Object.defineProperty(za,"__esModule",{value:!0}),za.RelationsContainer=void 0;var t=e(Ue),n=QV(),r=nn();class i{constructor(a,c){this.client=a,this.room=c,(0,t.default)(this,"relations",new Map)}getChildEventsForEvent(a,c,f){var v,s;return(v=this.relations.get(a))===null||v===void 0||(s=v.get(c))===null||s===void 0?void 0:s.get(f)}getAllChildEventsForEvent(a){var c;const f=(c=this.relations.get(a))!==null&&c!==void 0?c:new Map,v=[];for(const s of f.values())for(const g of s.values())v.push(...g.getRelations());return v}aggregateParentEvent(a){const c=this.relations.get(a.getId());if(c)for(const f of c.values())for(const v of f.values())v.setTargetEvent(a)}aggregateChildEvent(a,c){if(a.isRedacted()||a.status===r.EventStatus.CANCELLED)return;const f=a.getRelation();if(!f)return;const v=()=>{if(a.isDecryptionFailure()){a.once(r.MatrixEventEvent.Decrypted,v);return}this.aggregateChildEvent(a,c)};if(a.isBeingDecrypted()||a.shouldAttemptDecryption()){a.once(r.MatrixEventEvent.Decrypted,v);return}const{event_id:s,rel_type:g}=f,y=a.getType();let S=this.relations.get(s);S||(S=new Map,this.relations.set(s,S));let m=S.get(g);m||(m=new Map,S.set(g,m));let p=m.get(y);if(!p){var _,u,l;p=new n.Relations(g,y,this.client),m.set(y,p);const d=(_=this.room)!==null&&_!==void 0?_:c==null?void 0:c.room,h=(u=(l=c==null?void 0:c.findEventById(s))!==null&&l!==void 0?l:d==null?void 0:d.findEventById(s))!==null&&u!==void 0?u:d==null?void 0:d.getPendingEvent(s);h&&p.setTargetEvent(h)}p.addEvent(a)}}return za.RelationsContainer=i,za}var c0;function Gy(){if(c0)return _i;c0=1;var e=Ae;Object.defineProperty(_i,"__esModule",{value:!0}),_i.EventTimelineSet=_i.DuplicateStrategy=void 0;var t=e(Ue),n=Tr(),r=Ge(),i=hi(),o=Pt(),a=NP();let c;c=r.logger.log.bind(r.logger);let f;_i.DuplicateStrategy=f,function(s){s.Ignore="ignore",s.Replace="replace"}(f||(_i.DuplicateStrategy=f={}));class v extends o.TypedEventEmitter{constructor(g,y={},S,m,p=null){var _,u,l;super(),this.room=g,this.thread=m,this.threadListType=p,(0,t.default)(this,"relations",void 0),(0,t.default)(this,"timelineSupport",void 0),(0,t.default)(this,"displayPendingEvents",void 0),(0,t.default)(this,"liveTimeline",void 0),(0,t.default)(this,"timelines",void 0),(0,t.default)(this,"_eventIdToTimeline",new Map),(0,t.default)(this,"filter",void 0),this.timelineSupport=Boolean(y.timelineSupport),this.liveTimeline=new n.EventTimeline(this),this.displayPendingEvents=y.pendingEvents!==!1,this.timelines=[this.liveTimeline],this._eventIdToTimeline=new Map,this.filter=y.filter,this.relations=(_=(u=this.room)===null||u===void 0?void 0:u.relations)!==null&&_!==void 0?_:new a.RelationsContainer((l=g==null?void 0:g.client)!==null&&l!==void 0?l:S)}getTimelines(){return this.timelines}getFilter(){return this.filter}setFilter(g){this.filter=g}getPendingEvents(){return!this.room||!this.displayPendingEvents?[]:this.room.getPendingEvents()}getLiveTimeline(){return this.liveTimeline}setLiveTimeline(g){this.liveTimeline=g}eventIdToTimeline(g){return this._eventIdToTimeline.get(g)}replaceEventId(g,y){const S=this._eventIdToTimeline.get(g);S&&(this._eventIdToTimeline.delete(g),this._eventIdToTimeline.set(y,S))}resetLiveTimeline(g,y){const S=!this.timelineSupport||!y,m=this.liveTimeline,p=S?m.forkLive(n.EventTimeline.FORWARDS):m.fork(n.EventTimeline.FORWARDS);S?(this.timelines=[p],this._eventIdToTimeline=new Map):this.timelines.push(p),y&&m.setPaginationToken(y,n.EventTimeline.FORWARDS),p.setPaginationToken(g??null,n.EventTimeline.BACKWARDS),this.liveTimeline=p,this.emit(i.RoomEvent.TimelineReset,this.room,this,S)}getTimelineForEvent(g){if(g==null)return null;const y=this._eventIdToTimeline.get(g);return y===void 0?null:y}findEventById(g){const y=this.getTimelineForEvent(g);if(y)return y.getEvents().find(function(S){return S.getId()==g})}addTimeline(){if(!this.timelineSupport)throw new Error("timeline support is disabled. Set the 'timelineSupport' parameter to true when creating MatrixClient to enable it.");const g=new n.EventTimeline(this);return this.timelines.push(g),g}addEventsToTimeline(g,y,S,m){if(!S)throw new Error("'timeline' not specified for EventTimelineSet.addEventsToTimeline");if(!y&&S==this.liveTimeline)throw new Error("EventTimelineSet.addEventsToTimeline cannot be used for adding events to the live timeline - use Room.addLiveEvents instead");if(this.filter&&(g=this.filter.filterRoomTimeline(g),!g.length))return;const p=y?n.EventTimeline.BACKWARDS:n.EventTimeline.FORWARDS,_=y?n.EventTimeline.FORWARDS:n.EventTimeline.BACKWARDS;let u=!1,l=!1;for(const d of g){const h=d.getId(),w=this._eventIdToTimeline.get(h);if(!w){this.addEventToTimeline(d,S,{toStartOfTimeline:y}),l=!0,u=!0;continue}if(l=!1,w==S){c("Event "+h+" already in timeline "+S);continue}const E=S.getNeighbouringTimeline(p);if(E){w==E?c("Event "+h+" in neighbouring timeline - switching to "+w):c("Event "+h+" already in a different timeline "+w),S=w;continue}r.logger.info("Already have timeline for "+h+" - joining timeline "+S+" to "+w);const I=w===this.liveTimeline,k=S===this.liveTimeline,M=p===n.EventTimeline.BACKWARDS&&I,L=p===n.EventTimeline.FORWARDS&&k;if(M||L){M&&r.logger.warn("Refusing to set a preceding existingTimeLine on our timeline as the existingTimeLine is live ("+w+")"),L&&r.logger.warn("Refusing to set our preceding timeline on a existingTimeLine as our timeline is live ("+S+")");continue}S.setNeighbouringTimeline(w,p),w.setNeighbouringTimeline(S,_),S=w,u=!0}if(l||!u){if(p===n.EventTimeline.FORWARDS&&S===this.liveTimeline){r.logger.warn({lastEventWasNew:l,didUpdate:u}),r.logger.warn(`Refusing to set forwards pagination token of live timeline ${S} to ${m}`);return}S.setPaginationToken(m??null,p)}}addLiveEvent(g,y,S=!1,m){let p=y||f.Ignore,_;if(typeof y=="object"?{duplicateStrategy:p=f.Ignore,fromCache:S=!1,roomState:m,timelineWasEmpty:_}=y:y!==void 0&&r.logger.warn("Overload deprecated: `EventTimelineSet.addLiveEvent(event, duplicateStrategy?, fromCache?, roomState?)` is deprecated in favor of the overload with `EventTimelineSet.addLiveEvent(event, IAddLiveEventOptions)`"),this.filter&&!this.filter.filterRoomTimeline([g]).length)return;const u=this._eventIdToTimeline.get(g.getId());if(u){if(p===f.Replace){c("EventTimelineSet.addLiveEvent: replacing duplicate event "+g.getId());const l=u.getEvents();for(let d=0;d<l.length;d++)if(l[d].getId()===g.getId()){m||(m=u.getState(n.EventTimeline.FORWARDS)),n.EventTimeline.setEventMetadata(g,m,!1),l[d]=g;break}}else c("EventTimelineSet.addLiveEvent: ignoring duplicate event "+g.getId());return}this.addEventToTimeline(g,this.liveTimeline,{toStartOfTimeline:!1,fromCache:S,roomState:m,timelineWasEmpty:_})}addEventToTimeline(g,y,S,m=!1,p){let _=!!S,u;if(typeof S=="object"?{toStartOfTimeline:_,fromCache:m=!1,roomState:p,timelineWasEmpty:u}=S:S!==void 0&&r.logger.warn("Overload deprecated: `EventTimelineSet.addEventToTimeline(event, timeline, toStartOfTimeline, fromCache?, roomState?)` is deprecated in favor of the overload with `EventTimelineSet.addEventToTimeline(event, timeline, IAddEventToTimelineOptions)`"),y.getTimelineSet()!==this){var l;throw new Error(`EventTimelineSet.addEventToTimeline: Timeline=${y.toString()} does not belong " +
     78                 "in timelineSet(threadId=${(l=this.thread)===null||l===void 0?void 0:l.id})`)}if(this.room&&!this.canContain(g)){var d;let E=`event=${g.getId()}`;g.threadRootId&&(E+=`(belongs to thread=${g.threadRootId})`),r.logger.warn(`EventTimelineSet.addEventToTimeline: Ignoring ${E} that does not belong in timeline=${y.toString()} timelineSet(threadId=${(d=this.thread)===null||d===void 0?void 0:d.id})`);return}const h=g.getId();y.addEvent(g,{toStartOfTimeline:_,roomState:p,timelineWasEmpty:u}),this._eventIdToTimeline.set(h,y),this.relations.aggregateParentEvent(g),this.relations.aggregateChildEvent(g,this);const w={timeline:y,liveEvent:!_&&y==this.liveTimeline&&!m};this.emit(i.RoomEvent.Timeline,g,this.room,Boolean(_),!1,w)}handleRemoteEcho(g,y,S){const m=this._eventIdToTimeline.get(y);m?(this._eventIdToTimeline.delete(y),this._eventIdToTimeline.set(S,m)):(!this.filter||this.filter.filterRoomTimeline([g]).length)&&this.addEventToTimeline(g,this.liveTimeline,{toStartOfTimeline:!1})}removeEvent(g){const y=this._eventIdToTimeline.get(g);if(!y)return null;const S=y.removeEvent(g);if(S){this._eventIdToTimeline.delete(g);const m={timeline:y};this.emit(i.RoomEvent.Timeline,S,this.room,void 0,!0,m)}return S}compareEventOrdering(g,y){if(g==y)return 0;const S=this._eventIdToTimeline.get(g),m=this._eventIdToTimeline.get(y);if(S===void 0||m===void 0)return null;if(S===m){let _,u;const l=S.getEvents();for(let d=0;d<l.length&&(_===void 0||u===void 0);d++){const h=l[d].getId();h==g&&(_=d),h==y&&(u=d)}return _-u}let p=S;for(;p;){if(p===m)return-1;p=p.getNeighbouringTimeline(n.EventTimeline.FORWARDS)}for(p=S;p;){if(p===m)return 1;p=p.getNeighbouringTimeline(n.EventTimeline.BACKWARDS)}return null}canContain(g){if(!this.room)throw new Error("Cannot call `EventTimelineSet::canContain without a `room` set. Set the room when creating the EventTimelineSet to call this method.");const{threadId:y,shouldLiveInRoom:S}=this.room.eventShouldLiveIn(g);return this.thread?this.thread.id===y:S}}return _i.EventTimelineSet=v,_i}var cs={},d0;function xP(){if(d0)return cs;d0=1,Object.defineProperty(cs,"__esModule",{value:!0}),cs.EventStatus=void 0;let e;return cs.EventStatus=e,function(t){t.NOT_SENT="not_sent",t.ENCRYPTING="encrypting",t.SENDING="sending",t.QUEUED="queued",t.SENT="sent",t.CANCELLED="cancelled"}(e||(cs.EventStatus=e={})),cs}var Gu={};Object.defineProperty(Gu,"__esModule",{value:!0});Gu.RoomSummary=void 0;class JV{constructor(t,n){this.roomId=t}}Gu.RoomSummary=JV;var yo={},f0;function rs(){if(f0)return yo;f0=1;var e=Ae;Object.defineProperty(yo,"__esModule",{value:!0}),yo.TypedReEmitter=yo.ReEmitter=void 0;var t=e(Ue);let n=class{constructor(o){this.target=o,(0,t.default)(this,"reEmitters",new Map)}reEmit(o,a){let c=this.reEmitters.get(o);c||(c=new Map,this.reEmitters.set(o,c));for(const f of a){const v=(...s)=>{f==="error"&&this.target.listenerCount("error")===0||this.target.emit(f,...s,o)};o.on(f,v),c.set(f,v)}}stopReEmitting(o,a){const c=this.reEmitters.get(o);if(c){for(const f of a)o.off(f,c.get(f)),c.delete(f);c.size===0&&this.reEmitters.delete(o)}}};yo.ReEmitter=n;class r extends n{constructor(o){super(o)}reEmit(o,a){super.reEmit(o,a)}stopReEmitting(o,a){super.stopReEmitting(o,a)}}return yo.TypedReEmitter=r,yo}var Ya={},Qa={},h0;function jf(){if(h0)return Qa;h0=1,Object.defineProperty(Qa,"__esModule",{value:!0}),Qa.UNREAD_THREAD_NOTIFICATIONS=void 0;var e=en;const t=new e.ServerControlledNamespacedValue("unread_thread_notifications","org.matrix.msc3773.unread_thread_notifications");return Qa.UNREAD_THREAD_NOTIFICATIONS=t,Qa}var Ja={},p0;function XV(){if(p0)return Ja;p0=1,Object.defineProperty(Ja,"__esModule",{value:!0}),Ja.FilterComponent=void 0;var e=zf();function t(r,i){if(i.endsWith("*")){const o=i.slice(0,-1);return r.slice(0,o.length)===o}else return r===i}class n{constructor(i,o){this.filterJson=i,this.userId=o}check(i){var o,a;const c=((o=i.getUnsigned())===null||o===void 0?void 0:o["m.relations"])||{},f=Object.keys(c),v=[];return this.userId&&c!==null&&c!==void 0&&(a=c[e.THREAD_RELATION_TYPE.name])!==null&&a!==void 0&&a.current_user_participated&&v.push(this.userId),this.checkFields(i.getRoomId(),i.getSender(),i.getType(),i.getContent()?i.getContent().url!==void 0:!1,f,v)}toJSON(){return{types:this.filterJson.types||null,not_types:this.filterJson.not_types||[],rooms:this.filterJson.rooms||null,not_rooms:this.filterJson.not_rooms||[],senders:this.filterJson.senders||null,not_senders:this.filterJson.not_senders||[],contains_url:this.filterJson.contains_url||null,[e.FILTER_RELATED_BY_SENDERS.name]:this.filterJson[e.FILTER_RELATED_BY_SENDERS.name]||[],[e.FILTER_RELATED_BY_REL_TYPES.name]:this.filterJson[e.FILTER_RELATED_BY_REL_TYPES.name]||[]}}checkFields(i,o,a,c,f,v){const s={rooms:function(m){return i===m},senders:function(m){return o===m},types:function(m){return t(a,m)}};for(const m in s){const p=s[m],_="not_"+m,u=this.filterJson[_];if(u!=null&&u.some(p))return!1;const l=this.filterJson[m];if(l&&!l.some(p))return!1}const g=this.filterJson.contains_url;if(g!==void 0&&g!==c)return!1;const y=this.filterJson[e.FILTER_RELATED_BY_REL_TYPES.name];if(y!==void 0&&!this.arrayMatchesFilter(y,f))return!1;const S=this.filterJson[e.FILTER_RELATED_BY_SENDERS.name];return!(S!==void 0&&!this.arrayMatchesFilter(S,v))}arrayMatchesFilter(i,o){return o.length>0&&i.every(a=>o.includes(a))}filter(i){return i.filter(this.check,this)}limit(){return this.filterJson.limit!==void 0?this.filterJson.limit:10}}return Ja.FilterComponent=n,Ja}var g0;function qf(){if(g0)return Ya;g0=1;var e=Ae;Object.defineProperty(Ya,"__esModule",{value:!0}),Ya.Filter=void 0;var t=e(Ue),n=jf(),r=XV();function i(f,v){var s=Object.keys(f);if(Object.getOwnPropertySymbols){var g=Object.getOwnPropertySymbols(f);v&&(g=g.filter(function(y){return Object.getOwnPropertyDescriptor(f,y).enumerable})),s.push.apply(s,g)}return s}function o(f){for(var v=1;v<arguments.length;v++){var s=arguments[v]!=null?arguments[v]:{};v%2?i(Object(s),!0).forEach(function(g){(0,t.default)(f,g,s[g])}):Object.getOwnPropertyDescriptors?Object.defineProperties(f,Object.getOwnPropertyDescriptors(s)):i(Object(s)).forEach(function(g){Object.defineProperty(f,g,Object.getOwnPropertyDescriptor(s,g))})}return f}function a(f,v,s){const g=v.split(".");let y=f;for(let S=0;S<g.length-1;S++)y[g[S]]||(y[g[S]]={}),y=y[g[S]];y[g[g.length-1]]=s}class c{static fromJson(v,s,g){const y=new c(v,s);return y.setDefinition(g),y}constructor(v,s){this.userId=v,this.filterId=s,(0,t.default)(this,"definition",{}),(0,t.default)(this,"roomFilter",void 0),(0,t.default)(this,"roomTimelineFilter",void 0)}getFilterId(){return this.filterId}getDefinition(){return this.definition}setDefinition(v){this.definition=v;const s=v.room,g={};s&&(s.rooms&&(g.rooms=s.rooms),s.rooms&&(g.not_rooms=s.not_rooms)),this.roomFilter=new r.FilterComponent(g,this.userId),this.roomTimelineFilter=new r.FilterComponent((s==null?void 0:s.timeline)||{},this.userId)}getRoomTimelineFilterComponent(){return this.roomTimelineFilter}filterRoomTimeline(v){return this.roomFilter&&(v=this.roomFilter.filter(v)),this.roomTimelineFilter&&(v=this.roomTimelineFilter.filter(v)),v}setTimelineLimit(v){a(this.definition,"room.timeline.limit",v)}setUnreadThreadNotifications(v){var s,g,y;this.definition=o(o({},this.definition),{},{room:o(o({},(s=this.definition)===null||s===void 0?void 0:s.room),{},{timeline:o(o({},(g=this.definition)===null||g===void 0||(y=g.room)===null||y===void 0?void 0:y.timeline),{},{[n.UNREAD_THREAD_NOTIFICATIONS.name]:v})})})}setLazyLoadMembers(v){a(this.definition,"room.state.lazy_load_members",v)}setIncludeLeaveRooms(v){a(this.definition,"room.include_leave",v)}}return Ya.Filter=c,(0,t.default)(c,"LAZY_LOADING_MESSAGES_FILTER",{lazy_load_members:!0}),Ya}var bn={},ut={},Xa={},v0;function ZV(){if(v0)return Xa;v0=1,Object.defineProperty(Xa,"__esModule",{value:!0}),Xa.M_TOPIC=void 0;var e=en;const t=new e.UnstableValue("m.topic","org.matrix.msc3765.topic");return Xa.M_TOPIC=t,Xa}var eW=Ae;Object.defineProperty(ut,"__esModule",{value:!0});ut.makeBeaconInfoContent=ut.makeBeaconContent=ut.getTextForLocationEvent=void 0;ut.makeEmoteMessage=lW;ut.makeHtmlEmote=oW;ut.makeHtmlMessage=rW;ut.makeHtmlNotice=iW;ut.makeLocationContent=void 0;ut.makeNotice=aW;ut.makeTextMessage=sW;ut.parseTopicContent=ut.parseLocationEvent=ut.parseBeaconInfoContent=ut.parseBeaconContent=ut.makeTopicContent=void 0;var tW=eW(Ue),zy=Fu,is=xe,$P=yP(),Mt=_P(),UP=ZV();function m0(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),n.push.apply(n,r)}return n}function nW(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?m0(Object(n),!0).forEach(function(r){(0,tW.default)(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):m0(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function rW(e,t){return{msgtype:is.MsgType.Text,format:"org.matrix.custom.html",body:e,formatted_body:t}}function iW(e,t){return{msgtype:is.MsgType.Notice,format:"org.matrix.custom.html",body:e,formatted_body:t}}function oW(e,t){return{msgtype:is.MsgType.Emote,format:"org.matrix.custom.html",body:e,formatted_body:t}}function sW(e){return{msgtype:is.MsgType.Text,body:e}}function aW(e){return{msgtype:is.MsgType.Notice,body:e}}function lW(e){return{msgtype:is.MsgType.Emote,body:e}}const BP=(e,t,n,r)=>{const i=`at ${new Date(n).toISOString()}`,o=t===Mt.LocationAssetType.Self?"User":void 0,a=r?`"${r}"`:void 0;return[o,"Location",a,e,i].filter(Boolean).join(" ")};ut.getTextForLocationEvent=BP;const FP=(e,t,n,r,i)=>{const o=e??BP(t,i||Mt.LocationAssetType.Self,n,r),a=n?{[Mt.M_TIMESTAMP.name]:n}:{};return nW({msgtype:is.MsgType.Location,body:o,geo_uri:t,[Mt.M_LOCATION.name]:{description:r,uri:t},[Mt.M_ASSET.name]:{type:i||Mt.LocationAssetType.Self},[$P.TEXT_NODE_TYPE.name]:o},a)};ut.makeLocationContent=FP;const uW=e=>{var t,n;const r=Mt.M_LOCATION.findIn(e),i=Mt.M_ASSET.findIn(e),o=Mt.M_TIMESTAMP.findIn(e),a=$P.TEXT_NODE_TYPE.findIn(e),c=(t=r==null?void 0:r.uri)!==null&&t!==void 0?t:e==null?void 0:e.geo_uri,f=r==null?void 0:r.description,v=(n=i==null?void 0:i.type)!==null&&n!==void 0?n:Mt.LocationAssetType.Self,s=a??e.body;return FP(s,c,o??void 0,f,v)};ut.parseLocationEvent=uW;const cW=(e,t)=>{const n=[{body:e,mimetype:"text/plain"}];return(0,zy.isProvided)(t)&&n.push({body:t,mimetype:"text/html"}),{topic:e,[UP.M_TOPIC.name]:n}};ut.makeTopicContent=cW;const dW=e=>{var t,n,r;const i=UP.M_TOPIC.findIn(e),o=(t=i==null||(n=i.find(c=>!(0,zy.isProvided)(c.mimetype)||c.mimetype==="text/plain"))===null||n===void 0?void 0:n.body)!==null&&t!==void 0?t:e.topic,a=i==null||(r=i.find(c=>c.mimetype==="text/html"))===null||r===void 0?void 0:r.body;return{text:o,html:a}};ut.parseTopicContent=dW;const fW=(e,t,n,r,i)=>({description:n,timeout:e,live:t,[Mt.M_TIMESTAMP.name]:i||Date.now(),[Mt.M_ASSET.name]:{type:r??Mt.LocationAssetType.Self}});ut.makeBeaconInfoContent=fW;const hW=e=>{var t;const{description:n,timeout:r,live:i}=e,o=(t=Mt.M_TIMESTAMP.findIn(e))!==null&&t!==void 0?t:void 0,a=Mt.M_ASSET.findIn(e);return{description:n,timeout:r,live:i,assetType:a==null?void 0:a.type,timestamp:o}};ut.parseBeaconInfoContent=hW;const pW=(e,t,n,r)=>({[Mt.M_LOCATION.name]:{description:r,uri:e},[Mt.M_TIMESTAMP.name]:t,"m.relates_to":{rel_type:zy.REFERENCE_RELATION.name,event_id:n}});ut.makeBeaconContent=pW;const gW=e=>{var t;const n=Mt.M_LOCATION.findIn(e),r=(t=Mt.M_TIMESTAMP.findIn(e))!==null&&t!==void 0?t:void 0;return{description:n==null?void 0:n.description,uri:n==null?void 0:n.uri,timestamp:r}};ut.parseBeaconContent=gW;var vW=Ae;Object.defineProperty(bn,"__esModule",{value:!0});bn.isTimestampInDuration=bn.getBeaconInfoIdentifier=bn.BeaconEvent=bn.Beacon=void 0;var ds=vW(Ue),Tp=ut,mW=lt(),yW=Pt();let Ui;bn.BeaconEvent=Ui;(function(e){e.New="Beacon.new",e.Update="Beacon.update",e.LivenessChange="Beacon.LivenessChange",e.Destroy="Beacon.Destroy",e.LocationUpdate="Beacon.LocationUpdate"})(Ui||(bn.BeaconEvent=Ui={}));const em=(e,t,n)=>n>=e&&e+t>=n;bn.isTimestampInDuration=em;const tm=e=>`${e.getRoomId()}_${e.getStateKey()}`;bn.getBeaconInfoIdentifier=tm;class _W extends yW.TypedEventEmitter{constructor(t){super(),this.rootEvent=t,(0,ds.default)(this,"roomId",void 0),(0,ds.default)(this,"_beaconInfo",void 0),(0,ds.default)(this,"_isLive",void 0),(0,ds.default)(this,"livenessWatchTimeout",void 0),(0,ds.default)(this,"_latestLocationEvent",void 0),(0,ds.default)(this,"clearLatestLocation",()=>{this._latestLocationEvent=void 0,this.emit(Ui.LocationUpdate,this.latestLocationState)}),this.setBeaconInfo(this.rootEvent),this.roomId=this.rootEvent.getRoomId()}get isLive(){return!!this._isLive}get identifier(){return tm(this.rootEvent)}get beaconInfoId(){return this.rootEvent.getId()}get beaconInfoOwner(){return this.rootEvent.getStateKey()}get beaconInfoEventType(){return this.rootEvent.getType()}get beaconInfo(){return this._beaconInfo}get latestLocationState(){return this._latestLocationEvent&&(0,Tp.parseBeaconContent)(this._latestLocationEvent.getContent())}get latestLocationEvent(){return this._latestLocationEvent}update(t){if(tm(t)!==this.identifier)throw new Error("Invalid updating event");t.getTs()<this.rootEvent.getTs()||(this.rootEvent=t,this.setBeaconInfo(this.rootEvent),this.emit(Ui.Update,t,this),this.clearLatestLocation())}destroy(){this.livenessWatchTimeout&&clearTimeout(this.livenessWatchTimeout),this._isLive=!1,this.emit(Ui.Destroy,this.identifier)}monitorLiveness(){if(this.livenessWatchTimeout&&clearTimeout(this.livenessWatchTimeout),this.checkLiveness(),!!this.beaconInfo)if(this.isLive){const t=this.beaconInfo.timestamp+this.beaconInfo.timeout-Date.now();t>1&&(this.livenessWatchTimeout=setTimeout(()=>{this.monitorLiveness()},t))}else this.beaconInfo.timestamp>Date.now()&&(this.livenessWatchTimeout=setTimeout(()=>{this.monitorLiveness()},this.beaconInfo.timestamp-Date.now()))}addLocations(t){var n;if(!this.isLive)return;const i=(n=t.filter(o=>{const a=o.getContent(),c=(0,Tp.parseBeaconContent)(a);if(!c.uri||!c.timestamp)return!1;const{timestamp:f}=c;return this._beaconInfo.timestamp&&em(this._beaconInfo.timestamp,this._beaconInfo.timeout,f)&&(!this.latestLocationState||f>this.latestLocationState.timestamp)}).sort(mW.sortEventsByLatestContentTimestamp))===null||n===void 0?void 0:n[0];i&&(this._latestLocationEvent=i,this.emit(Ui.LocationUpdate,this.latestLocationState))}setBeaconInfo(t){this._beaconInfo=(0,Tp.parseBeaconInfoContent)(t.getContent()),this.checkLiveness()}checkLiveness(){var t,n;const r=this.isLive;if(!this.beaconInfo)return;const i=this.beaconInfo.timestamp>Date.now()?this.beaconInfo.timestamp-36e4:this.beaconInfo.timestamp;this._isLive=!!((t=this._beaconInfo)!==null&&t!==void 0&&t.live)&&!!i&&em(i,(n=this._beaconInfo)===null||n===void 0?void 0:n.timeout,Date.now()),r!==this.isLive&&this.emit(Ui.LivenessChange,this.isLive,this)}}bn.Beacon=_W;var fs={},y0;function KP(){if(y0)return fs;y0=1;var e=Ae;Object.defineProperty(fs,"__esModule",{value:!0}),fs.ReadReceipt=void 0,fs.synthesizeReceipt=v;var t=e(Ue),n=Sa(),r=Pt(),i=f(lt()),o=nn(),a=xe;function c(S){if(typeof WeakMap!="function")return null;var m=new WeakMap,p=new WeakMap;return(c=function(_){return _?p:m})(S)}function f(S,m){if(!m&&S&&S.__esModule)return S;if(S===null||typeof S!="object"&&typeof S!="function")return{default:S};var p=c(m);if(p&&p.has(S))return p.get(S);var _={},u=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var l in S)if(l!=="default"&&Object.prototype.hasOwnProperty.call(S,l)){var d=u?Object.getOwnPropertyDescriptor(S,l):null;d&&(d.get||d.set)?Object.defineProperty(_,l,d):_[l]=S[l]}return _.default=S,p&&p.set(S,_),_}function v(S,m,p){var _;return new o.MatrixEvent({content:{[m.getId()]:{[p]:{[S]:{ts:m.getTs(),thread_id:(_=m.threadRootId)!==null&&_!==void 0?_:n.MAIN_ROOM_TIMELINE}}}},type:a.EventType.Receipt,room_id:m.getRoomId()})}const s=0,g=1;class y extends r.TypedEventEmitter{constructor(...m){super(...m),(0,t.default)(this,"receipts",{}),(0,t.default)(this,"receiptCacheByEventId",{}),(0,t.default)(this,"timeline",void 0)}getReadReceiptForUserId(m,p=!1,_=n.ReceiptType.Read){var u,l;const[d,h]=(u=(l=this.receipts[_])===null||l===void 0?void 0:l[m])!==null&&u!==void 0?u:[];return p?d:h??d}getEventReadUpTo(m,p=!1){var _,u,l,d,h;const w=this.getUnfilteredTimelineSet(),E=this.getReadReceiptForUserId(m,p,n.ReceiptType.Read),I=this.getReadReceiptForUserId(m,p,n.ReceiptType.ReadPrivate);let k;if(E!=null&&E.eventId&&I!==null&&I!==void 0&&I.eventId&&(k=w.compareEventOrdering(E==null?void 0:E.eventId,I==null?void 0:I.eventId)),!k&&E!==null&&E!==void 0&&(_=E.data)!==null&&_!==void 0&&_.ts&&I!==null&&I!==void 0&&(u=I.data)!==null&&u!==void 0&&u.ts){var M,L;k=(E==null||(M=E.data)===null||M===void 0?void 0:M.ts)-(I==null||(L=I.data)===null||L===void 0?void 0:L.ts)}return k?(h=k<0?I==null?void 0:I.eventId:E==null?void 0:E.eventId)!==null&&h!==void 0?h:null:(l=(d=I==null?void 0:I.eventId)!==null&&d!==void 0?d:E==null?void 0:E.eventId)!==null&&l!==void 0?l:null}addReceiptToStructure(m,p,_,u,l){var d,h;this.receipts[p]||(this.receipts[p]={}),this.receipts[p][_]||(this.receipts[p][_]=[null,null]);const w=this.receipts[p][_];let E=w[s];if(l){var I;E=(I=w[g])!==null&&I!==void 0?I:w[s]}if(E){const x=this.getUnfilteredTimelineSet().compareEventOrdering(E.eventId,m);if(x!==null&&x>=0)return}const k={eventId:m,data:u},M=l?w[s]:k,L=l?k:w[g];let B=null;M&&L&&(B=this.getUnfilteredTimelineSet().compareEventOrdering(M.eventId,L.eventId));const N=B===null||B<0,G=(d=w[g])!==null&&d!==void 0?d:w[s];l&&N?w[g]=k:l||(w[s]=k,N||(w[g]=null));const D=(h=w[g])!==null&&h!==void 0?h:w[s];if(G!==D){if(G&&this.receiptCacheByEventId[G.eventId]){const x=G.eventId;this.receiptCacheByEventId[x]=this.receiptCacheByEventId[x].filter(z=>z.type!==p||z.userId!==_),this.receiptCacheByEventId[x].length<1&&delete this.receiptCacheByEventId[x]}this.receiptCacheByEventId[m]||(this.receiptCacheByEventId[m]=[]),this.receiptCacheByEventId[m].push({userId:_,type:p,data:u})}}getReceiptsForEvent(m){return this.receiptCacheByEventId[m.getId()]||[]}addLocalEchoReceipt(m,p,_){this.addReceipt(v(m,p,_),!0)}getUsersReadUpTo(m){return this.getReceiptsForEvent(m).filter(function(p){return i.isSupportedReceiptType(p.type)}).map(function(p){return p.userId})}hasUserReadEvent(m,p){var _;const u=this.getEventReadUpTo(m,!1);if(u===p||(_=this.timeline)!==null&&_!==void 0&&_.length&&this.timeline[this.timeline.length-1].getSender()&&this.timeline[this.timeline.length-1].getSender()===m)return!0;for(let d=((l=this.timeline)===null||l===void 0?void 0:l.length)-1;d>=0;--d){var l;const h=this.timeline[d];if(h.getId()===p)return!1;if(h.getId()===u)return!0}return!1}}return fs.ReadReceipt=y,fs}var Pr={},_0;function Yy(){if(_0)return Pr;_0=1,Object.defineProperty(Pr,"__esModule",{value:!0}),Pr.ServerSupport=Pr.Feature=void 0,Pr.buildFeatureSupportMap=r;let e;Pr.ServerSupport=e,function(i){i[i.Stable=0]="Stable",i[i.Unstable=1]="Unstable",i[i.Unsupported=2]="Unsupported"}(e||(Pr.ServerSupport=e={}));let t;Pr.Feature=t,function(i){i.Thread="Thread",i.ThreadUnreadNotifications="ThreadUnreadNotifications",i.LoginTokenRequest="LoginTokenRequest"}(t||(Pr.Feature=t={}));const n={[t.Thread]:{unstablePrefixes:["org.matrix.msc3440"],matrixVersion:"v1.3"},[t.ThreadUnreadNotifications]:{unstablePrefixes:["org.matrix.msc3771","org.matrix.msc3773"],matrixVersion:"v1.4"},[t.LoginTokenRequest]:{unstablePrefixes:["org.matrix.msc3882"]}};async function r(i){const o=new Map;for(const[s,g]of Object.entries(n)){var a,c,f,v;const y=(a=(c=i.versions)===null||c===void 0?void 0:c.includes(g.matrixVersion||""))!==null&&a!==void 0?a:!1,S=(f=(v=g.unstablePrefixes)===null||v===void 0?void 0:v.every(m=>{var p;return((p=i.unstable_features)===null||p===void 0?void 0:p[m])===!0}))!==null&&f!==void 0?f:!1;y?o.set(s,e.Stable):S?o.set(s,e.Unstable):o.set(s,e.Unsupported)}return o}return Pr}var S0;function hi(){if(S0)return Gt;S0=1;var e=Ae;Object.defineProperty(Gt,"__esModule",{value:!0}),Gt.RoomNameType=Gt.RoomEvent=Gt.Room=Gt.NotificationCountType=Gt.KNOWN_SAFE_ROOM_VERSION=void 0;var t=e(Ue),n=Gy(),r=Tr(),i=Ea,o=I(lt()),a=nn(),c=xP(),f=Zn,v=Gu,s=Ge(),g=rs(),y=xe,S=or(),m=qf(),p=po(),_=bn,u=zf(),l=Sa(),d=NP(),h=KP(),w=Yy();function E(H){if(typeof WeakMap!="function")return null;var R=new WeakMap,P=new WeakMap;return(E=function(K){return K?P:R})(H)}function I(H,R){if(!R&&H&&H.__esModule)return H;if(H===null||typeof H!="object"&&typeof H!="function")return{default:H};var P=E(R);if(P&&P.has(H))return P.get(H);var K={},U=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var C in H)if(C!=="default"&&Object.prototype.hasOwnProperty.call(H,C)){var A=U?Object.getOwnPropertyDescriptor(H,C):null;A&&(A.get||A.set)?Object.defineProperty(K,C,A):K[C]=H[C]}return K.default=H,P&&P.set(H,K),K}function k(H,R){var P=Object.keys(H);if(Object.getOwnPropertySymbols){var K=Object.getOwnPropertySymbols(H);R&&(K=K.filter(function(U){return Object.getOwnPropertyDescriptor(H,U).enumerable})),P.push.apply(P,K)}return P}function M(H){for(var R=1;R<arguments.length;R++){var P=arguments[R]!=null?arguments[R]:{};R%2?k(Object(P),!0).forEach(function(K){(0,t.default)(H,K,P[K])}):Object.getOwnPropertyDescriptors?Object.defineProperties(H,Object.getOwnPropertyDescriptors(P)):k(Object(P)).forEach(function(K){Object.defineProperty(H,K,Object.getOwnPropertyDescriptor(P,K))})}return H}const L="9";Gt.KNOWN_SAFE_ROOM_VERSION=L;const B=["1","2","3","4","5","6","7","8","9"],N=30;let G;Gt.NotificationCountType=G,function(H){H.Highlight="highlight",H.Total="total"}(G||(Gt.NotificationCountType=G={}));let D;Gt.RoomEvent=D,function(H){H.MyMembership="Room.myMembership",H.Tags="Room.tags",H.AccountData="Room.accountData",H.Receipt="Room.receipt",H.Name="Room.name",H.Redaction="Room.redaction",H.RedactionCancelled="Room.redactionCancelled",H.LocalEchoUpdated="Room.localEchoUpdated",H.Timeline="Room.timeline",H.TimelineReset="Room.timelineReset",H.TimelineRefresh="Room.TimelineRefresh",H.OldStateUpdated="Room.OldStateUpdated",H.CurrentStateUpdated="Room.CurrentStateUpdated",H.HistoryImportedWithinTimeline="Room.historyImportedWithinTimeline",H.UnreadNotifications="Room.UnreadNotifications"}(D||(Gt.RoomEvent=D={}));class x extends h.ReadReceipt{constructor(R,P,K,U={}){super(),this.roomId=R,this.client=P,this.myUserId=K,this.opts=U,(0,t.default)(this,"reEmitter",void 0),(0,t.default)(this,"txnToEvent",{}),(0,t.default)(this,"notificationCounts",{}),(0,t.default)(this,"threadNotifications",new Map),(0,t.default)(this,"cachedThreadReadReceipts",new Map),(0,t.default)(this,"timelineSets",void 0),(0,t.default)(this,"threadsTimelineSets",[]),(0,t.default)(this,"filteredTimelineSets",{}),(0,t.default)(this,"timelineNeedsRefresh",!1),(0,t.default)(this,"pendingEventList",void 0),(0,t.default)(this,"blacklistUnverifiedDevices",void 0),(0,t.default)(this,"selfMembership",void 0),(0,t.default)(this,"summaryHeroes",null),(0,t.default)(this,"getTypeWarning",!1),(0,t.default)(this,"getVersionWarning",!1),(0,t.default)(this,"membersPromise",void 0),(0,t.default)(this,"name",void 0),(0,t.default)(this,"normalizedName",void 0),(0,t.default)(this,"tags",{}),(0,t.default)(this,"accountData",{}),(0,t.default)(this,"summary",null),(0,t.default)(this,"timeline",void 0),(0,t.default)(this,"oldState",void 0),(0,t.default)(this,"currentState",void 0),(0,t.default)(this,"relations",new d.RelationsContainer(this.client,this)),(0,t.default)(this,"threads",new Map),(0,t.default)(this,"lastThread",void 0),(0,t.default)(this,"visibilityEvents",new Map),(0,t.default)(this,"threadTimelineSetsPromise",null),(0,t.default)(this,"threadsReady",!1),(0,t.default)(this,"updateThreadRootEvents",(C,A,T)=>{if(C.length){var X;if(this.updateThreadRootEvent((X=this.threadsTimelineSets)===null||X===void 0?void 0:X[0],C,A,T),C.hasCurrentUserParticipated){var ne;this.updateThreadRootEvent((ne=this.threadsTimelineSets)===null||ne===void 0?void 0:ne[1],C,A,T)}}}),(0,t.default)(this,"updateThreadRootEvent",(C,A,T,X)=>{C&&A.rootEvent&&(X&&C.removeEvent(A.id),u.Thread.hasServerSideSupport?C.addLiveEvent(A.rootEvent,{duplicateStrategy:n.DuplicateStrategy.Replace,fromCache:!1,roomState:this.currentState}):C.addEventToTimeline(A.rootEvent,C.getLiveTimeline(),{toStartOfTimeline:T}))}),(0,t.default)(this,"applyRedaction",C=>{if(C.isRedaction()){const A=C.event.redacts,T=A?this.findEventById(A):void 0;if(T){if(T.makeRedacted(C),T.isState()){const X=this.currentState.getStateEvents(T.getType(),T.getStateKey());(X==null?void 0:X.getId())===T.getId()&&this.currentState.setStateEvents([T])}this.emit(D.Redaction,C,this),this.visibilityEvents.delete(A),T.isVisibilityEvent()&&this.redactVisibilityChangeEvent(C)}}}),this.setMaxListeners(100),this.reEmitter=new g.TypedReEmitter(this),U.pendingEventOrdering=U.pendingEventOrdering||S.PendingEventOrdering.Chronological,this.name=R,this.normalizedName=R,this.timelineSets=[new n.EventTimelineSet(this,U)],this.reEmitter.reEmit(this.getUnfilteredTimelineSet(),[D.Timeline,D.TimelineReset]),this.fixUpLegacyTimelineFields(),this.opts.pendingEventOrdering===S.PendingEventOrdering.Detached&&(this.pendingEventList=[],this.client.store.getPendingEvents(this.roomId).then(C=>{const A=this.client.getEventMapper({toDevice:!1,decrypt:!1});C.forEach(async T=>{const X=A(T);X.getType()===y.EventType.RoomMessageEncrypted&&this.client.isCryptoEnabled()&&await X.attemptDecryption(this.client.crypto),X.setStatus(c.EventStatus.NOT_SENT),this.addPendingEvent(X,X.getTxnId())})})),this.opts.lazyLoadMembers?this.membersPromise=void 0:this.membersPromise=Promise.resolve(!1)}async createThreadsTimelineSets(){var R;if(this.threadTimelineSetsPromise)return this.threadTimelineSetsPromise;if((R=this.client)!==null&&R!==void 0&&R.supportsExperimentalThreads())try{this.threadTimelineSetsPromise=Promise.all([this.createThreadTimelineSet(),this.createThreadTimelineSet(u.ThreadFilterType.My)]);const P=await this.threadTimelineSetsPromise;return this.threadsTimelineSets.push(...P),P}catch{return this.threadTimelineSetsPromise=null,null}return null}async decryptCriticalEvents(){if(!this.client.isCryptoEnabled())return;const R=this.getEventReadUpTo(this.client.getUserId(),!0),P=this.getLiveTimeline().getEvents(),K=P.findIndex(C=>C.event.event_id===R),U=P.slice(K).filter(C=>C.shouldAttemptDecryption()).reverse().map(C=>C.attemptDecryption(this.client.crypto,{isRetry:!0}));await Promise.allSettled(U)}async decryptAllEvents(){if(!this.client.isCryptoEnabled())return;const R=this.getUnfilteredTimelineSet().getLiveTimeline().getEvents().filter(P=>P.shouldAttemptDecryption()).reverse().map(P=>P.attemptDecryption(this.client.crypto,{isRetry:!0}));await Promise.allSettled(R)}getCreator(){var R;const P=this.currentState.getStateEvents(y.EventType.RoomCreate,"");return(R=P==null?void 0:P.getContent().creator)!==null&&R!==void 0?R:null}getVersion(){var R;const P=this.currentState.getStateEvents(y.EventType.RoomCreate,"");return P?(R=P.getContent().room_version)!==null&&R!==void 0?R:"1":(this.getVersionWarning||(s.logger.warn("[getVersion] Room "+this.roomId+" does not have an m.room.create event"),this.getVersionWarning=!0),"1")}shouldUpgradeToVersion(){return B.includes(this.getVersion())?null:L}async getRecommendedVersion(){let P=(await this.client.getCapabilities())["m.room_versions"];if(!P){P={default:L,available:{}};for(const U of B)P.available[U]=S.RoomVersionStability.Stable}let K=this.checkVersionAgainstCapability(P);if(K.urgent&&K.needsUpgrade)if(s.logger.warn("Refreshing room version capability because the server looks to be supporting a newer room version we don't know about."),P=(await this.client.getCapabilities(!0))["m.room_versions"],P)K=this.checkVersionAgainstCapability(P);else return s.logger.warn("No room version capability - assuming upgrade required."),K;return K}checkVersionAgainstCapability(R){const P=this.getVersion();s.logger.log(`[${this.roomId}] Current version: ${P}`),s.logger.log(`[${this.roomId}] Version capability: `,R);const K={version:P,needsUpgrade:!1,urgent:!1};return P===R.default||Object.keys(R.available).filter(C=>R.available[C]==="stable").includes(P)||(K.version=R.default,K.needsUpgrade=!0,K.urgent=!!this.getVersion().match(/^[0-9]+[0-9.]*$/g),K.urgent?s.logger.warn(`URGENT upgrade required on ${this.roomId}`):s.logger.warn(`Non-urgent upgrade required on ${this.roomId}`)),K}userMayUpgradeRoom(R){return this.currentState.maySendStateEvent(y.EventType.RoomTombstone,R)}getPendingEvents(){if(!this.pendingEventList)throw new Error("Cannot call getPendingEvents with pendingEventOrdering == "+this.opts.pendingEventOrdering);return this.pendingEventList}removePendingEvent(R){if(!this.pendingEventList)throw new Error("Cannot call removePendingEvent with pendingEventOrdering == "+this.opts.pendingEventOrdering);const P=o.removeElement(this.pendingEventList,function(K){return K.getId()==R},!1);return this.savePendingEvents(),P}hasPendingEvent(R){var P,K;return(P=(K=this.pendingEventList)===null||K===void 0?void 0:K.some(U=>U.getId()===R))!==null&&P!==void 0?P:!1}getPendingEvent(R){var P,K;return(P=(K=this.pendingEventList)===null||K===void 0?void 0:K.find(U=>U.getId()===R))!==null&&P!==void 0?P:null}getLiveTimeline(){return this.getUnfilteredTimelineSet().getLiveTimeline()}getLastActiveTimestamp(){const P=this.getLiveTimeline().getEvents();return P.length?P[P.length-1].getTs():Number.MIN_SAFE_INTEGER}getMyMembership(){var R;return(R=this.selfMembership)!==null&&R!==void 0?R:"leave"}getDMInviter(){const R=this.getMember(this.myUserId);if(R)return R.getDMInviter();if(this.selfMembership==="invite"&&this.getInvitedAndJoinedMemberCount()===2){var P;return(P=this.summaryHeroes)===null||P===void 0?void 0:P[0]}}guessDMUserId(){const R=this.getMember(this.myUserId);if(R){const U=R.getDMInviter();if(U)return U}if(Array.isArray(this.summaryHeroes)&&this.summaryHeroes.length)return this.summaryHeroes[0];const K=this.currentState.getMembers().find(U=>U.userId!==this.myUserId);return K?K.userId:this.myUserId}getAvatarFallbackMember(){if(this.getInvitedAndJoinedMemberCount()>2)return;const P=Array.isArray(this.summaryHeroes)&&this.summaryHeroes.length;if(P){const U=this.summaryHeroes.map(C=>this.getMember(C)).find(C=>!!C);if(U)return U}const K=this.currentState.getMembers();if(K.length<=2){const U=K.find(C=>C.userId!==this.myUserId);if(U)return U}if(P){const U=this.summaryHeroes.map(C=>this.client.getUser(C)).find(C=>!!C);if(U){const C=new f.RoomMember(this.roomId,U.userId);return C.user=U,C}}}updateMyMembership(R){const P=this.selfMembership;this.selfMembership=R,P!==R&&(R==="leave"&&this.cleanupAfterLeaving(),this.emit(D.MyMembership,this,R,P))}async loadMembersFromServer(){const R=this.client.store.getSyncToken();return(await this.client.members(this.roomId,void 0,"leave",R??void 0)).chunk}async loadMembers(){let R=!1,P=await this.client.store.getOutOfBandMembers(this.roomId);return(P===null||this.client.isCryptoEnabled()&&this.client.isRoomEncrypted(this.roomId))&&(R=!0,P=await this.loadMembersFromServer(),s.logger.log(`LL: got ${P.length} members from server for room ${this.roomId}`)),{memberEvents:P.map(this.client.getEventMapper()),fromServer:R}}loadMembersIfNeeded(){if(this.membersPromise)return this.membersPromise;this.currentState.markOutOfBandMembersStarted();const R=this.loadMembers().then(P=>(this.currentState.setOutOfBandMembers(P.memberEvents),this.client.isCryptoEnabled()&&this.client.isRoomEncrypted(this.roomId)&&this.client.crypto.trackRoomDevices(this.roomId),P.fromServer)).catch(P=>{throw this.membersPromise=void 0,this.currentState.markOutOfBandMembersFailed(),P});return R.then(P=>{if(P){const K=this.currentState.getMembers().filter(C=>C.isOutOfBand()).map(C=>{var A;return(A=C.events.member)===null||A===void 0?void 0:A.event});return s.logger.log(`LL: telling store to write ${K.length} members for room ${this.roomId}`),this.client.store.setOutOfBandMembers(this.roomId,K).catch(C=>{s.logger.log("LL: storing OOB room members failed, oh well",C)})}}).catch(P=>{s.logger.error(P)}),this.membersPromise=R,this.membersPromise}async clearLoadedMembersIfNeeded(){this.opts.lazyLoadMembers&&this.membersPromise&&(await this.loadMembersIfNeeded(),await this.client.store.clearOutOfBandMembers(this.roomId),this.currentState.clearOutOfBandMembers(),this.membersPromise=void 0)}cleanupAfterLeaving(){this.clearLoadedMembersIfNeeded().catch(R=>{s.logger.error(`error after clearing loaded members from room ${this.roomId} after leaving`),s.logger.log(R)})}async refreshLiveTimeline(){const R=this.getLiveTimeline(),P=R.getPaginationToken(r.EventTimeline.FORWARDS),K=R.getPaginationToken(r.EventTimeline.BACKWARDS),U=R.getEvents(),C=U[U.length-1];s.logger.log(`[refreshLiveTimeline for ${this.roomId}] at mostRecentEventInTimeline=${C&&C.getId()} liveTimelineBefore=${R.toString()} forwardPaginationToken=${P} backwardPaginationToken=${K}`);const A=this.getUnfilteredTimelineSet();let T;C?(this.resetLiveTimeline(null,null),this.emit(D.TimelineRefresh,this,A),T=await this.client.getEventTimeline(A,C.getId())):T=await this.client.getLatestTimeline(A);const X=A.getLiveTimeline();!X||X.getPaginationToken(r.Direction.Forward)===null&&X.getPaginationToken(r.Direction.Backward)===null&&X.getEvents().length===0?(s.logger.log(`[refreshLiveTimeline for ${this.roomId}] using our new live timeline`),T.setPaginationToken(P,r.EventTimeline.FORWARDS),A.setLiveTimeline(T),this.fixUpLegacyTimelineFields()):s.logger.log(`[refreshLiveTimeline for ${this.roomId}] \`/sync\` or some other request beat us to creating a new live timeline after we reset it. We'll use that instead since any events in the scrollback from this timeline will include the history.`),this.setTimelineNeedsRefresh(!1),this.emit(D.TimelineRefresh,this,A)}resetLiveTimeline(R,P){for(const K of this.timelineSets)K.resetLiveTimeline(R??void 0,P??void 0);this.fixUpLegacyTimelineFields()}fixUpLegacyTimelineFields(){const R=this.oldState,P=this.currentState;this.timeline=this.getLiveTimeline().getEvents(),this.oldState=this.getLiveTimeline().getState(r.EventTimeline.BACKWARDS),this.currentState=this.getLiveTimeline().getState(r.EventTimeline.FORWARDS),R!==this.oldState&&this.emit(D.OldStateUpdated,this,R,this.oldState),P!==this.currentState&&(this.emit(D.CurrentStateUpdated,this,P,this.currentState),this.reEmitter.stopReEmitting(P,[p.RoomStateEvent.Events,p.RoomStateEvent.Members,p.RoomStateEvent.NewMember,p.RoomStateEvent.Update,p.RoomStateEvent.Marker,_.BeaconEvent.New,_.BeaconEvent.Update,_.BeaconEvent.Destroy,_.BeaconEvent.LivenessChange]),this.reEmitter.reEmit(this.currentState,[p.RoomStateEvent.Events,p.RoomStateEvent.Members,p.RoomStateEvent.NewMember,p.RoomStateEvent.Update,p.RoomStateEvent.Marker,_.BeaconEvent.New,_.BeaconEvent.Update,_.BeaconEvent.Destroy,_.BeaconEvent.LivenessChange]))}async hasUnverifiedDevices(){if(!this.client.isRoomEncrypted(this.roomId))return!1;const R=await this.getEncryptionTargetMembers();for(const P of R)if(this.client.getStoredDevicesForUser(P.userId).some(U=>U.isUnverified()))return!0;return!1}getTimelineSets(){return this.timelineSets}getUnfilteredTimelineSet(){return this.timelineSets[0]}getTimelineForEvent(R){const P=this.findEventById(R),K=this.findThreadForEvent(P);return K?K.timelineSet.getLiveTimeline():this.getUnfilteredTimelineSet().getTimelineForEvent(R)}addTimeline(){return this.getUnfilteredTimelineSet().addTimeline()}setTimelineNeedsRefresh(R){this.timelineNeedsRefresh=R}getTimelineNeedsRefresh(){return this.timelineNeedsRefresh}findEventById(R){let P=this.getUnfilteredTimelineSet().findEventById(R);if(!P){const K=this.getThreads();for(let U=0;U<K.length;U++)if(P=K[U].findEventById(R),P)return P}return P}getUnreadNotificationCount(R=G.Total){let P=this.getRoomUnreadNotificationCount(R);if(this.client.canSupport.get(w.Feature.ThreadUnreadNotifications)!==w.ServerSupport.Unsupported)for(const U of this.threadNotifications.values()){var K;P+=(K=U[R])!==null&&K!==void 0?K:0}return P}getUnreadCountForEventContext(R=G.Total,P){var K;return(K=!!P.threadRootId&&!P.isThreadRoot?this.getThreadUnreadNotificationCount(P.threadRootId,R):this.getRoomUnreadNotificationCount(R))!==null&&K!==void 0?K:0}getRoomUnreadNotificationCount(R=G.Total){var P;return(P=this.notificationCounts[R])!==null&&P!==void 0?P:0}getThreadUnreadNotificationCount(R,P=G.Total){var K,U;return(K=(U=this.threadNotifications.get(R))===null||U===void 0?void 0:U[P])!==null&&K!==void 0?K:0}hasThreadUnreadNotification(){for(const K of this.threadNotifications.values()){var R,P;if(((R=K.highlight)!==null&&R!==void 0?R:0)>0||((P=K.total)!==null&&P!==void 0?P:0)>0)return!0}return!1}setThreadUnreadNotificationCount(R,P,K){var U,C;const A=M({highlight:(U=this.threadNotifications.get(R))===null||U===void 0?void 0:U.highlight,total:(C=this.threadNotifications.get(R))===null||C===void 0?void 0:C.total},{[P]:K});this.threadNotifications.set(R,A),this.emit(D.UnreadNotifications,A,R)}get threadsAggregateNotificationType(){let R=null;for(const U of this.threadNotifications.values()){var P,K;if(((P=U.highlight)!==null&&P!==void 0?P:0)>0)return G.Highlight;((K=U.total)!==null&&K!==void 0?K:0)>0&&!R&&(R=G.Total)}return R}resetThreadUnreadNotificationCount(R){if(R)for(const[P]of this.threadNotifications)R.includes(P)||this.threadNotifications.delete(P);else this.threadNotifications.clear();this.emit(D.UnreadNotifications)}setUnreadNotificationCount(R,P){this.notificationCounts[R]=P,this.emit(D.UnreadNotifications,this.notificationCounts)}setSummary(R){const P=R["m.heroes"],K=R["m.joined_member_count"],U=R["m.invited_member_count"];Number.isInteger(K)&&this.currentState.setJoinedMemberCount(K),Number.isInteger(U)&&this.currentState.setInvitedMemberCount(U),Array.isArray(P)&&(this.summaryHeroes=P.filter(C=>C!==this.myUserId))}setBlacklistUnverifiedDevices(R){this.blacklistUnverifiedDevices=R}getBlacklistUnverifiedDevices(){return this.blacklistUnverifiedDevices===void 0?null:this.blacklistUnverifiedDevices}getAvatarUrl(R,P,K,U,C=!0){const A=this.currentState.getStateEvents(y.EventType.RoomAvatar,"");if(!A&&!C)return null;const T=A?A.getContent().url:null;return T?(0,i.getHttpUriForMxc)(R,T,P,K,U):null}getMxcAvatarUrl(){var R,P;return((R=this.currentState.getStateEvents(y.EventType.RoomAvatar,""))===null||R===void 0||(P=R.getContent())===null||P===void 0?void 0:P.url)||null}getCanonicalAlias(){const R=this.currentState.getStateEvents(y.EventType.RoomCanonicalAlias,"");return R&&R.getContent().alias||null}getAltAliases(){const R=this.currentState.getStateEvents(y.EventType.RoomCanonicalAlias,"");return R?R.getContent().alt_aliases||[]:[]}addEventsToTimeline(R,P,K,U){K.getTimelineSet().addEventsToTimeline(R,P,K,U)}getThread(R){var P;return(P=this.threads.get(R))!==null&&P!==void 0?P:null}getThreads(){return Array.from(this.threads.values())}getMember(R){return this.currentState.getMember(R)}getMembers(){return this.currentState.getMembers()}getJoinedMembers(){return this.getMembersWithMembership("join")}getJoinedMemberCount(){return this.currentState.getJoinedMemberCount()}getInvitedMemberCount(){return this.currentState.getInvitedMemberCount()}getInvitedAndJoinedMemberCount(){return this.getInvitedMemberCount()+this.getJoinedMemberCount()}getMembersWithMembership(R){return this.currentState.getMembers().filter(function(P){return P.membership===R})}async getEncryptionTargetMembers(){await this.loadMembersIfNeeded();let R=this.getMembersWithMembership("join");return this.shouldEncryptForInvitedMembers()&&(R=R.concat(this.getMembersWithMembership("invite"))),R}shouldEncryptForInvitedMembers(){var R;const P=this.currentState.getStateEvents(y.EventType.RoomHistoryVisibility,"");return(P==null||(R=P.getContent())===null||R===void 0?void 0:R.history_visibility)!=="joined"}getDefaultRoomName(R){return this.calculateRoomName(R,!0)}hasMembershipState(R,P){const K=this.getMember(R);return K?K.membership===P:!1}getOrCreateFilteredTimelineSet(R,{prepopulateTimeline:P=!0,useSyncEvents:K=!0,pendingEvents:U=!0}={}){if(this.filteredTimelineSets[R.filterId])return this.filteredTimelineSets[R.filterId];const C=Object.assign({filter:R,pendingEvents:U},this.opts),A=new n.EventTimelineSet(this,C);this.reEmitter.reEmit(A,[D.Timeline,D.TimelineReset]),K&&(this.filteredTimelineSets[R.filterId]=A,this.timelineSets.push(A));const T=this.getLiveTimeline();if(P){T.getEvents().forEach(function(ne){A.addLiveEvent(ne)});let X=T;for(;X.getNeighbouringTimeline(r.EventTimeline.BACKWARDS);)X=X.getNeighbouringTimeline(r.EventTimeline.BACKWARDS);A.getLiveTimeline().setPaginationToken(X.getPaginationToken(r.EventTimeline.BACKWARDS),r.EventTimeline.BACKWARDS)}else if(K){const X=T.getPaginationToken(r.Direction.Forward);A.getLiveTimeline().setPaginationToken(X,r.Direction.Backward)}return A}async getThreadListFilter(R=u.ThreadFilterType.All){const P=this.client.getUserId(),K=new m.Filter(P),U={room:{timeline:{[u.FILTER_RELATED_BY_REL_TYPES.name]:[u.THREAD_RELATION_TYPE.name]}}};R===u.ThreadFilterType.My&&(U.room.timeline[u.FILTER_RELATED_BY_SENDERS.name]=[P]),K.setDefinition(U);const C=await this.client.getOrCreateFilter(`THREAD_PANEL_${this.roomId}_${R}`,K);return K.filterId=C,K}async createThreadTimelineSet(R){let P;if(u.Thread.hasServerSideListSupport)P=new n.EventTimelineSet(this,M(M({},this.opts),{},{pendingEvents:!1}),void 0,void 0,R??u.ThreadFilterType.All),this.reEmitter.reEmit(P,[D.Timeline,D.TimelineReset]);else if(u.Thread.hasServerSideSupport){const K=await this.getThreadListFilter(R);P=this.getOrCreateFilteredTimelineSet(K,{prepopulateTimeline:!1,useSyncEvents:!1,pendingEvents:!1})}else P=new n.EventTimelineSet(this,{pendingEvents:!1}),Array.from(this.threads).forEach(([,K])=>{if(K.length===0)return;const U=K.timeline.some(C=>C.getSender()===this.client.getUserId());(R!==u.ThreadFilterType.My||U)&&P.getLiveTimeline().addEvent(K.rootEvent,{toStartOfTimeline:!1})});return P}processThreadRoots(R,P){for(const K of R)r.EventTimeline.setEventMetadata(K,this.currentState,P),this.getThread(K.getId())||this.createThread(K.getId(),K,[],P)}async fetchRoomThreads(){if(!(this.threadsReady||!this.client.supportsExperimentalThreads())){if(u.Thread.hasServerSideListSupport)await Promise.all([this.fetchRoomThreadList(u.ThreadFilterType.All),this.fetchRoomThreadList(u.ThreadFilterType.My)]);else{const K=await this.getThreadListFilter(),{chunk:U}=await this.client.createMessagesRequest(this.roomId,"",Number.MAX_SAFE_INTEGER,r.Direction.Backward,K);if(!U.length)return;const C=U.map(this.client.getEventMapper()).sort((X,ne)=>{const ae=X.getServerAggregatedRelation(u.THREAD_RELATION_TYPE.name),pe=ne.getServerAggregatedRelation(u.THREAD_RELATION_TYPE.name);return ae.latest_event.origin_server_ts-pe.latest_event.origin_server_ts});let A;const T=this.getLiveTimeline().getState(r.EventTimeline.FORWARDS);for(const X of C){var R;const ne={duplicateStrategy:n.DuplicateStrategy.Ignore,fromCache:!1,roomState:T};(R=this.threadsTimelineSets[0])===null||R===void 0||R.addLiveEvent(X,ne);const ae=X.getServerAggregatedRelation(u.THREAD_RELATION_TYPE.name);if(ae!=null&&ae.current_user_participated){var P;(P=this.threadsTimelineSets[1])===null||P===void 0||P.addLiveEvent(X,ne),A=X}}this.processThreadRoots(C,!0),this.client.decryptEventIfNeeded(C[C.length-1]),A&&this.client.decryptEventIfNeeded(A)}this.on(u.ThreadEvent.NewReply,this.onThreadNewReply),this.on(u.ThreadEvent.Delete,this.onThreadDelete),this.threadsReady=!0}}async fetchRoomThreadList(R){const P=R===u.ThreadFilterType.My?this.threadsTimelineSets[1]:this.threadsTimelineSets[0],{chunk:K,end:U}=await this.client.createThreadListMessagesRequest(this.roomId,null,void 0,r.Direction.Backward,P.threadListType,P.getFilter());if(P.getLiveTimeline().setPaginationToken(U??null,r.Direction.Backward),!K.length)return;const C=K.map(this.client.getEventMapper());this.processThreadRoots(C,!0);const A=this.getLiveTimeline().getState(r.EventTimeline.FORWARDS);for(const T of C)P.addLiveEvent(T,{duplicateStrategy:n.DuplicateStrategy.Replace,fromCache:!1,roomState:A})}onThreadNewReply(R){this.updateThreadRootEvents(R,!1,!0)}onThreadDelete(R){var P;this.threads.delete(R.id);const K=this.getTimelineForEvent(R.id),U=K==null||(P=K.getEvents())===null||P===void 0?void 0:P.find(C=>C.getId()===R.id);U?R.clearEventMetadata(U):s.logger.debug("onThreadDelete: Could not find root event in room timeline");for(const C of this.threadsTimelineSets)C.removeEvent(R.id)}removeFilteredTimelineSet(R){const P=this.filteredTimelineSets[R.filterId];delete this.filteredTimelineSets[R.filterId];const K=this.timelineSets.indexOf(P);K>-1&&this.timelineSets.splice(K,1)}eventShouldLiveIn(R,P,K){var U,C;if(!((U=this.client)!==null&&U!==void 0&&U.supportsExperimentalThreads()))return{shouldLiveInRoom:!0,shouldLiveInThread:!1};if(R.isThreadRoot||K!=null&&K.has(R.getId()))return{shouldLiveInRoom:!0,shouldLiveInThread:!0,threadId:R.getId()};if(R.isRelation(u.THREAD_RELATION_TYPE.name))return{shouldLiveInRoom:!1,shouldLiveInThread:!0,threadId:R.threadRootId};const A=R.getAssociatedId(),T=(C=this.findEventById(A))!==null&&C!==void 0?C:P==null?void 0:P.find(X=>X.getId()===A);return T&&(R.isRelation()||R.isRedaction())?this.eventShouldLiveIn(T,P,K):K!=null&&K.has(R.relationEventId)?{shouldLiveInRoom:!0,shouldLiveInThread:!0,threadId:R.relationEventId}:{shouldLiveInRoom:!0,shouldLiveInThread:!1}}findThreadForEvent(R){if(!R)return null;const{threadId:P}=this.eventShouldLiveIn(R);return P?this.getThread(P):null}addThreadedEvents(R,P,K=!1){let U=this.getThread(R);if(!U){var C;const A=(C=this.findEventById(R))!==null&&C!==void 0?C:P.find(T=>T.getId()===R);U=this.createThread(R,A,P,K)}U.addEvents(P,K)}processThreadedEvents(R,P){R.forEach(this.applyRedaction);const K={};for(const C of R){var U;const{threadId:A,shouldLiveInThread:T}=this.eventShouldLiveIn(C);T&&!K[A]&&(K[A]=[]),(U=K[A])===null||U===void 0||U.push(C)}Object.entries(K).map(([C,A])=>this.addThreadedEvents(C,A,P))}createThread(R,P,K=[],U){var C,A,T;if(this.threads.has(R))return this.threads.get(R);if(P){const ae=this.relations.getAllChildEventsForEvent(P.getId());ae!=null&&ae.length&&(K=K.concat(ae.filter(pe=>!pe.isRelation(y.RelationType.Replace))))}const X=new u.Thread(R,P,{room:this,client:this.client,pendingEventOrdering:this.opts.pendingEventOrdering,receipts:(C=this.cachedThreadReadReceipts.get(R))!==null&&C!==void 0?C:[]});this.cachedThreadReadReceipts.delete(R),X.addEvents(K,!1),this.threads.set(X.id,X),this.reEmitter.reEmit(X,[u.ThreadEvent.Delete,u.ThreadEvent.Update,u.ThreadEvent.NewReply,D.Timeline,D.TimelineReset]);const ne=((A=this.lastThread)===null||A===void 0?void 0:A.rootEvent)&&(P==null?void 0:P.localTimestamp)&&((T=this.lastThread.rootEvent)===null||T===void 0?void 0:T.localTimestamp)<(P==null?void 0:P.localTimestamp);return(!this.lastThread||ne)&&(this.lastThread=X),this.threadsReady&&this.updateThreadRootEvents(X,U,!1),this.emit(u.ThreadEvent.New,X,U),X}processLiveEvent(R){if(this.applyRedaction(R),R.isVisibilityEvent()&&this.applyNewVisibilityEvent(R),this.applyPendingVisibilityEvents(R),!R.getUnsigned().transaction_id&&R.getSender()===this.myUserId){for(const K in this.txnToEvent)if(this.txnToEvent[K].getId()===R.getId()){s.logger.debug("processLiveEvent: found sent event without txn ID: ",K,R.getId());const C=R.getUnsigned();C.transaction_id=K,R.setUnsigned(C);break}}}addLiveEvent(R,P){const{duplicateStrategy:K,timelineWasEmpty:U,fromCache:C}=P;for(const A of this.timelineSets)A.addLiveEvent(R,{duplicateStrategy:K,fromCache:C,timelineWasEmpty:U});R.sender&&R.getType()!==y.EventType.RoomRedaction&&this.addReceipt((0,h.synthesizeReceipt)(R.sender.userId,R,l.ReceiptType.Read),!0)}addPendingEvent(R,P){if(R.status!==c.EventStatus.SENDING&&R.status!==c.EventStatus.NOT_SENT)throw new Error("addPendingEvent called on an event with status "+R.status);if(this.txnToEvent[P])throw new Error("addPendingEvent called on an event with known txnId "+P);if(r.EventTimeline.setEventMetadata(R,this.getLiveTimeline().getState(r.EventTimeline.FORWARDS),!1),this.txnToEvent[P]=R,this.pendingEventList){if(this.pendingEventList.some(K=>K.status===c.EventStatus.NOT_SENT)&&(s.logger.warn("Setting event as NOT_SENT due to messages in the same state"),R.setStatus(c.EventStatus.NOT_SENT)),this.pendingEventList.push(R),this.savePendingEvents(),R.isRelation()&&this.aggregateNonLiveRelation(R),R.isRedaction()){const K=R.event.redacts;let U=this.pendingEventList.find(C=>C.getId()===K);!U&&K&&(U=this.findEventById(K)),U&&(U.markLocallyRedacted(R),this.emit(D.Redaction,R,this))}}else for(const K of this.timelineSets)K.getFilter()?K.getFilter().filterRoomTimeline([R]).length&&K.addEventToTimeline(R,K.getLiveTimeline(),{toStartOfTimeline:!1}):K.addEventToTimeline(R,K.getLiveTimeline(),{toStartOfTimeline:!1});this.emit(D.LocalEchoUpdated,R,this)}savePendingEvents(){if(this.pendingEventList){const R=this.pendingEventList.map(P=>M(M({},P.event),{},{txn_id:P.getTxnId()})).filter(P=>{const K=P.type===y.EventType.RoomMessageEncrypted,U=this.client.isRoomEncrypted(this.roomId);return K||!U});this.client.store.setPendingEvents(this.roomId,R)}}aggregateNonLiveRelation(R){this.relations.aggregateChildEvent(R)}getEventForTxnId(R){return this.txnToEvent[R]}handleRemoteEcho(R,P){const K=P.getId(),U=R.getId(),C=P.status;s.logger.debug(`Got remote echo for event ${K} -> ${U} old status ${C}`),delete this.txnToEvent[R.getUnsigned().transaction_id],this.pendingEventList&&this.removePendingEvent(K),P.handleRemoteEcho(R.event);const{shouldLiveInRoom:A,threadId:T}=this.eventShouldLiveIn(R),X=T?this.getThread(T):null;if(X==null||X.timelineSet.handleRemoteEcho(P,K,U),A)for(const ne of this.timelineSets)ne.handleRemoteEcho(P,K,U);this.emit(D.LocalEchoUpdated,P,this,K,C)}updatePendingEvent(R,P,K){if(s.logger.log(`setting pendingEvent status to ${P} in ${R.getRoomId()} event ID ${R.getId()} -> ${K}`),P==c.EventStatus.SENT&&!K)throw new Error("updatePendingEvent called with status=SENT, but no new event id");if(P==c.EventStatus.SENT&&this.getTimelineForEvent(K)){const X=this.findEventById(K);if(!(X==null?void 0:X.getUnsigned().transaction_id)&&X){const ae=X.getUnsigned();ae.transaction_id=R.getTxnId(),X.setUnsigned(ae),this.removeEvent(X.getId()),this.handleRemoteEcho(X,R)}return}const U=R.status,C=R.getId();if(!U)throw new Error("updatePendingEventStatus called on an event which is not a local echo.");const A=z[U];if(!(A!=null&&A.includes(P)))throw new Error(`Invalid EventStatus transition ${U}->${P}`);if(R.setStatus(P),P==c.EventStatus.SENT){R.replaceLocalEventId(K);const{shouldLiveInRoom:T,threadId:X}=this.eventShouldLiveIn(R),ne=X?this.getThread(X):void 0;if(ne==null||ne.timelineSet.replaceEventId(C,K),T)for(const ae of this.timelineSets)ae.replaceEventId(C,K)}else if(P==c.EventStatus.CANCELLED){if(this.pendingEventList){const T=this.getPendingEvent(C);this.removePendingEvent(C),T!=null&&T.isRedaction()&&this.revertRedactionLocalEcho(T)}this.removeEvent(C)}this.savePendingEvents(),this.emit(D.LocalEchoUpdated,R,this,C,U)}revertRedactionLocalEcho(R){const P=R.event.redacts;if(!P)return;const K=this.getUnfilteredTimelineSet().findEventById(P);K&&(K.unmarkLocallyRedacted(),this.emit(D.RedactionCancelled,R,this),K.isRelation()&&this.aggregateNonLiveRelation(K))}addLiveEvents(R,P,K=!1){let U=P,C=!1;if(typeof P=="object"?{duplicateStrategy:U,fromCache:K=!1,timelineWasEmpty:C}=P:P!==void 0&&s.logger.warn("Overload deprecated: `Room.addLiveEvents(events, duplicateStrategy?, fromCache?)` is deprecated in favor of the overload with `Room.addLiveEvents(events, IAddLiveEventOptions)`"),U&&["replace","ignore"].indexOf(U)===-1)throw new Error("duplicateStrategy MUST be either 'replace' or 'ignore'");for(let ae=0;ae<this.timelineSets.length;ae++){const pe=this.timelineSets[ae].getLiveTimeline();if(pe.getPaginationToken(r.EventTimeline.FORWARDS))throw new Error("live timeline "+ae+" is no longer live - it has a pagination token ("+pe.getPaginationToken(r.EventTimeline.FORWARDS)+")");if(pe.getNeighbouringTimeline(r.EventTimeline.FORWARDS))throw new Error(`live timeline ${ae} is no longer live - it has a neighbouring timeline`)}const A=this.findThreadRoots(R),T={},X={duplicateStrategy:U,fromCache:K,timelineWasEmpty:C};for(const ae of R){var ne;if(this.processLiveEvent(ae),ae.getUnsigned().transaction_id){const Q=this.txnToEvent[ae.getUnsigned().transaction_id];if(Q){this.handleRemoteEcho(ae,Q);continue}}const{shouldLiveInRoom:pe,shouldLiveInThread:V,threadId:se}=this.eventShouldLiveIn(ae,R,A);V&&!T[se??""]&&(T[se??""]=[]),(ne=T[se??""])===null||ne===void 0||ne.push(ae),pe&&this.addLiveEvent(ae,X)}Object.entries(T).forEach(([ae,pe])=>{this.addThreadedEvents(ae,pe,!1)})}partitionThreadedEvents(R){if(this.client.supportsExperimentalThreads()){const U=this.findThreadRoots(R);return R.reduce((C,A)=>{const{shouldLiveInRoom:T,shouldLiveInThread:X,threadId:ne}=this.eventShouldLiveIn(A,R,U);return T&&C[0].push(A),X&&(A.setThreadId(ne??""),C[1].push(A)),C},[[],[]])}else return[R,[]]}findThreadRoots(R){const P=new Set;for(const U of R)if(U.isRelation(u.THREAD_RELATION_TYPE.name)){var K;P.add((K=U.relationEventId)!==null&&K!==void 0?K:"")}return P}addReceipt(R,P=!1){const K=R.getContent();Object.keys(K).forEach(U=>{Object.keys(K[U]).forEach(C=>{Object.keys(K[U][C]).forEach(A=>{var T;const X=K[U][C][A],ae=!X.thread_id||X.thread_id===l.MAIN_ROOM_TIMELINE?this:this.threads.get((T=X.thread_id)!==null&&T!==void 0?T:"");if(ae)ae.addReceiptToStructure(U,C,A,X,P);else{var pe;this.cachedThreadReadReceipts.set(X.thread_id,[...(pe=this.cachedThreadReadReceipts.get(X.thread_id))!==null&&pe!==void 0?pe:[],{event:R,synthetic:P}])}})})}),this.emit(D.Receipt,R,this)}addEphemeralEvents(R){for(const P of R)P.getType()===y.EventType.Typing?this.currentState.setTypingEvent(P):P.getType()===y.EventType.Receipt&&this.addReceipt(P)}removeEvents(R){for(const P of R)this.removeEvent(P)}removeEvent(R){let P=!1;for(const K of this.timelineSets){const U=K.removeEvent(R);U&&(U.isRedaction()&&this.revertRedactionLocalEcho(U),P=!0)}return P}recalculate(){const R=this.currentState.getStateEvents(y.EventType.RoomMember,this.myUserId);if(R){const K=R.getContent().membership;this.updateMyMembership(K),K==="invite"&&(R.getUnsigned().invite_room_state||[]).forEach(C=>{this.currentState.getStateEvents(C.type,C.state_key)||this.currentState.setStateEvents([new a.MatrixEvent({type:C.type,state_key:C.state_key,content:C.content,event_id:"$fake"+Date.now(),room_id:this.roomId,user_id:this.myUserId})])})}const P=this.name;this.name=this.calculateRoomName(this.myUserId),this.normalizedName=(0,o.normalize)(this.name),this.summary=new v.RoomSummary(this.roomId,{title:this.name}),P!==this.name&&this.emit(D.Name,this)}addTags(R){this.tags=R.getContent().tags||{},this.emit(D.Tags,R,this)}addAccountData(R){for(const P of R){P.getType()==="m.tag"&&this.addTags(P);const K=this.accountData[P.getType()];this.accountData[P.getType()]=P,this.emit(D.AccountData,P,this,K)}}getAccountData(R){return this.accountData[R]}maySendMessage(){return this.getMyMembership()==="join"&&(this.client.isRoomEncrypted(this.roomId)?this.currentState.maySendEvent(y.EventType.RoomMessageEncrypted,this.myUserId):this.currentState.maySendEvent(y.EventType.RoomMessage,this.myUserId))}canInvite(R){let P=this.getMyMembership()==="join";const K=this.currentState.getStateEvents(y.EventType.RoomPowerLevels,""),U=K&&K.getContent(),C=this.getMember(R);return U&&C&&U.invite>C.powerLevel&&(P=!1),P}getJoinRule(){return this.currentState.getJoinRule()}getHistoryVisibility(){return this.currentState.getHistoryVisibility()}getGuestAccess(){return this.currentState.getGuestAccess()}getType(){const R=this.currentState.getStateEvents(y.EventType.RoomCreate,"");if(!R){this.getTypeWarning||(s.logger.warn("[getType] Room "+this.roomId+" does not have an m.room.create event"),this.getTypeWarning=!0);return}return R.getContent()[y.RoomCreateTypeField]}isSpaceRoom(){return this.getType()===y.RoomType.Space}isCallRoom(){return this.getType()===y.RoomType.UnstableCall}isElementVideoRoom(){return this.getType()===y.RoomType.ElementVideo}roomNameGenerator(R){if(this.client.roomNameGenerator){const P=this.client.roomNameGenerator(this.roomId,R);if(P!==null)return P}switch(R.type){case W.Actual:return R.name;case W.Generated:switch(R.subtype){case"Inviting":return`Inviting ${F(R.names,R.count)}`;default:return F(R.names,R.count)}case W.EmptyRoom:return R.oldName?`Empty room (was ${R.oldName})`:"Empty room"}}calculateRoomName(R,P=!1){if(!P){const se=this.currentState.getStateEvents(y.EventType.RoomName,"");if(se!=null&&se.getContent().name)return this.roomNameGenerator({type:W.Actual,name:se.getContent().name})}const K=this.getCanonicalAlias();if(K)return this.roomNameGenerator({type:W.Actual,name:K});const U=this.currentState.getJoinedMemberCount(),C=this.currentState.getInvitedMemberCount();let A=U+C-1,T=[];const X=this.currentState.getStateEvents(y.UNSTABLE_ELEMENT_FUNCTIONAL_USERS.name,"");Array.isArray(X==null?void 0:X.getContent().service_members)&&(T=X.getContent().service_members);let ne=[];if(this.summaryHeroes)this.summaryHeroes.forEach(se=>{if(T.includes(se)){A--;return}const Q=this.getMember(se);ne.push(Q?Q.name:se)});else{let se=this.currentState.getMembers().filter(Q=>Q.userId!==R&&(Q.membership==="invite"||Q.membership==="join"));se=se.filter(({userId:Q})=>T.includes(Q)?(A--,!1):!0),se.sort((Q,j)=>o.compare(Q.userId,j.userId)),se=se.slice(0,5),ne=se.map(Q=>Q.name)}if(A)return this.roomNameGenerator({type:W.Generated,names:ne,count:A});if(this.getMyMembership()=="join"){const se=this.currentState.getStateEvents(y.EventType.RoomThirdPartyInvite);if(se!=null&&se.length){const Q=se.map(j=>j.getContent().display_name);return this.roomNameGenerator({type:W.Generated,subtype:"Inviting",names:Q,count:Q.length+1})}}let pe=ne;pe.length||(pe=this.currentState.getMembers().filter(se=>se.userId!==R&&se.membership!=="invite"&&se.membership!=="join").map(se=>se.name));let V;return pe.length&&(V=this.roomNameGenerator({type:W.Generated,names:pe,count:pe.length+1})),this.roomNameGenerator({type:W.EmptyRoom,oldName:V})}applyNewVisibilityEvent(R){const P=R.asVisibilityChange();if(!P)return;const K=R.getSender();if(!K||!(y.EVENT_VISIBILITY_CHANGE_TYPE.name&&this.currentState.maySendStateEvent(y.EVENT_VISIBILITY_CHANGE_TYPE.name,K)||y.EVENT_VISIBILITY_CHANGE_TYPE.altName&&this.currentState.maySendStateEvent(y.EVENT_VISIBILITY_CHANGE_TYPE.altName,K)))return;const C=this.visibilityEvents.get(P.eventId);if(C){let T=C.length-1;const X=Math.max(0,C.length-N);for(;T>=X&&!(C[T].getTs()<R.getTs());--T);T===-1?C.unshift(R):C.splice(T+1,0,R)}else this.visibilityEvents.set(P.eventId,[R]);const A=this.findEventById(P.eventId);A&&A.applyVisibilityEvent(P)}redactVisibilityChangeEvent(R){if(!R.isVisibilityEvent)throw new Error("expected a visibility change event");const P=R.getRelation(),K=P==null?void 0:P.event_id,U=this.visibilityEvents.get(K);if(!U)return;const C=U.findIndex(A=>A.getId()===R.getId());if(C!==-1&&(U.splice(C,1),C===U.length)){const A=this.findEventById(K);if(!A)return;if(C===0)this.visibilityEvents.delete(K),A.applyVisibilityEvent();else{const X=U[U.length-1].asVisibilityChange();if(!X)throw new Error("at this stage, visibility changes should be well-formed");A.applyVisibilityEvent(X)}}}applyPendingVisibilityEvents(R){const P=this.visibilityEvents.get(R.getId());if(!P||P.length==0)return;const K=P[P.length-1],U=K.asVisibilityChange();U&&(U.visible,!(K.getTs()<R.getTs())&&R.applyVisibilityEvent(U))}}Gt.Room=x;const z={[c.EventStatus.ENCRYPTING]:[c.EventStatus.SENDING,c.EventStatus.NOT_SENT,c.EventStatus.CANCELLED],[c.EventStatus.SENDING]:[c.EventStatus.ENCRYPTING,c.EventStatus.QUEUED,c.EventStatus.NOT_SENT,c.EventStatus.SENT],[c.EventStatus.QUEUED]:[c.EventStatus.SENDING,c.EventStatus.CANCELLED],[c.EventStatus.SENT]:[],[c.EventStatus.NOT_SENT]:[c.EventStatus.SENDING,c.EventStatus.QUEUED,c.EventStatus.CANCELLED],[c.EventStatus.CANCELLED]:[]};let W;Gt.RoomNameType=W,function(H){H[H.EmptyRoom=0]="EmptyRoom",H[H.Generated=1]="Generated",H[H.Actual=2]="Actual"}(W||(Gt.RoomNameType=W={}));function F(H,R){const P=R-1;return H.length?H.length===1&&P<=1?H[0]:H.length===2&&P<=2?`${H[0]} and ${H[1]}`:P>1?`${H[0]} and ${P} others`:`${H[0]} and 1 other`:"Empty room"}return Gt}var Za={},ht={};Object.defineProperty(ht,"__esModule",{value:!0});ht.TweakName=ht.RuleId=ht.PushRuleKind=ht.PushRuleActionName=ht.DMMemberCountCondition=ht.ConditionOperator=ht.ConditionKind=void 0;ht.isDmMemberCountCondition=EW;let nm;ht.PushRuleActionName=nm;(function(e){e.DontNotify="dont_notify",e.Notify="notify",e.Coalesce="coalesce"})(nm||(ht.PushRuleActionName=nm={}));let rm;ht.TweakName=rm;(function(e){e.Highlight="highlight",e.Sound="sound"})(rm||(ht.TweakName=rm={}));let im;ht.ConditionOperator=im;(function(e){e.ExactEquals="==",e.LessThan="<",e.GreaterThan=">",e.GreaterThanOrEqual=">=",e.LessThanOrEqual="<="})(im||(ht.ConditionOperator=im={}));const SW="2";ht.DMMemberCountCondition=SW;function EW(e){return e==="==2"||e==="2"}let om;ht.ConditionKind=om;(function(e){e.EventMatch="event_match",e.ContainsDisplayName="contains_display_name",e.RoomMemberCount="room_member_count",e.SenderNotificationPermission="sender_notification_permission",e.CallStarted="call_started",e.CallStartedPrefix="org.matrix.msc3914.call_started"})(om||(ht.ConditionKind=om={}));let sm;ht.PushRuleKind=sm;(function(e){e.Override="override",e.ContentSpecific="content",e.RoomSpecific="room",e.SenderSpecific="sender",e.Underride="underride"})(sm||(ht.PushRuleKind=sm={}));let am;ht.RuleId=am;(function(e){e.Master=".m.rule.master",e.ContainsDisplayName=".m.rule.contains_display_name",e.ContainsUserName=".m.rule.contains_user_name",e.AtRoomNotification=".m.rule.roomnotif",e.DM=".m.rule.room_one_to_one",e.EncryptedDM=".m.rule.encrypted_room_one_to_one",e.Message=".m.rule.message",e.EncryptedMessage=".m.rule.encrypted",e.InviteToSelf=".m.rule.invite_for_me",e.MemberEvent=".m.rule.member_event",e.IncomingCall=".m.rule.call",e.SuppressNotices=".m.rule.suppress_notices",e.Tombstone=".m.rule.tombstone"})(am||(ht.RuleId=am={}));var E0;function Qy(){if(E0)return Za;E0=1;var e=Ae;Object.defineProperty(Za,"__esModule",{value:!0}),Za.PushProcessor=void 0;var t=e(Ue),n=lt(),r=Ge(),i=ht,o=xe;function a(y,S){var m=Object.keys(y);if(Object.getOwnPropertySymbols){var p=Object.getOwnPropertySymbols(y);S&&(p=p.filter(function(_){return Object.getOwnPropertyDescriptor(y,_).enumerable})),m.push.apply(m,p)}return m}function c(y){for(var S=1;S<arguments.length;S++){var m=arguments[S]!=null?arguments[S]:{};S%2?a(Object(m),!0).forEach(function(p){(0,t.default)(y,p,m[p])}):Object.getOwnPropertyDescriptors?Object.defineProperties(y,Object.getOwnPropertyDescriptors(m)):a(Object(m)).forEach(function(p){Object.defineProperty(y,p,Object.getOwnPropertyDescriptor(m,p))})}return y}const f=[i.PushRuleKind.Override,i.PushRuleKind.ContentSpecific,i.PushRuleKind.RoomSpecific,i.PushRuleKind.SenderSpecific,i.PushRuleKind.Underride],v=[{rule_id:".m.rule.reaction",default:!0,enabled:!0,conditions:[{kind:i.ConditionKind.EventMatch,key:"type",pattern:"m.reaction"}],actions:[i.PushRuleActionName.DontNotify]},{rule_id:".org.matrix.msc3786.rule.room.server_acl",default:!0,enabled:!0,conditions:[{kind:i.ConditionKind.EventMatch,key:"type",pattern:o.EventType.RoomServerAcl},{kind:i.ConditionKind.EventMatch,key:"state_key",pattern:""}],actions:[]}],s=[{rule_id:".org.matrix.msc3914.rule.room.call",default:!0,enabled:!0,conditions:[{kind:i.ConditionKind.EventMatch,key:"type",pattern:"org.matrix.msc3401.call"},{kind:i.ConditionKind.CallStarted}],actions:[i.PushRuleActionName.Notify,{set_tweak:i.TweakName.Sound,value:"default"}]}];class g{constructor(S){this.client=S}static actionListToActionsObject(S){const m={notify:!1,tweaks:{}};for(const p of S)p===i.PushRuleActionName.Notify?m.notify=!0:typeof p=="object"&&(p.value===void 0&&(p.value=!0),m.tweaks[p.set_tweak]=p.value);return m}static rewriteDefaultRules(S){var m;let p=JSON.parse(JSON.stringify(S));p||(p={}),p.global||(p.global={}),p.global.override||(p.global.override=[]),p.global.override||(p.global.underride=[]);const _=p.global.override;for(const l of v){const d=_.find(h=>h.rule_id===l.rule_id);if(d)d.default=l.default,d.conditions=l.conditions,d.actions=l.actions;else{const h=l.rule_id;r.logger.warn(`Adding default global override for ${h}`),_.push(l)}}const u=(m=p.global.underride)!==null&&m!==void 0?m:[];for(const l of s){const d=u.find(h=>h.rule_id===l.rule_id);if(d)d.default=l.default,d.conditions=l.conditions,d.actions=l.actions;else{const h=l.rule_id;r.logger.warn(`Adding default global underride for ${h}`),u.push(l)}}return p}matchingRuleFromKindSet(S,m){for(const p of f){const _=m[p];if(_)for(const u of _){if(!u.enabled)continue;const l=this.templateRuleToRaw(p,u);if(l&&this.ruleMatchesEvent(l,S))return c(c({},u),{},{kind:p})}}return null}templateRuleToRaw(S,m){const p={rule_id:m.rule_id,actions:m.actions,conditions:[]};switch(S){case i.PushRuleKind.Underride:case i.PushRuleKind.Override:p.conditions=m.conditions;break;case i.PushRuleKind.RoomSpecific:if(!m.rule_id)return null;p.conditions.push({kind:i.ConditionKind.EventMatch,key:"room_id",value:m.rule_id});break;case i.PushRuleKind.SenderSpecific:if(!m.rule_id)return null;p.conditions.push({kind:i.ConditionKind.EventMatch,key:"user_id",value:m.rule_id});break;case i.PushRuleKind.ContentSpecific:if(!m.pattern)return null;p.conditions.push({kind:i.ConditionKind.EventMatch,key:"content.body",pattern:m.pattern});break}return p}eventFulfillsCondition(S,m){switch(S.kind){case i.ConditionKind.EventMatch:return this.eventFulfillsEventMatchCondition(S,m);case i.ConditionKind.ContainsDisplayName:return this.eventFulfillsDisplayNameCondition(S,m);case i.ConditionKind.RoomMemberCount:return this.eventFulfillsRoomMemberCountCondition(S,m);case i.ConditionKind.SenderNotificationPermission:return this.eventFulfillsSenderNotifPermCondition(S,m);case i.ConditionKind.CallStarted:case i.ConditionKind.CallStartedPrefix:return this.eventFulfillsCallStartedCondition(S,m)}return!1}eventFulfillsSenderNotifPermCondition(S,m){const p=S.key;if(!p)return!1;const _=this.client.getRoom(m.getRoomId());return _!=null&&_.currentState?_.currentState.mayTriggerNotifOfType(p,m.getSender()):!1}eventFulfillsRoomMemberCountCondition(S,m){if(!S.is)return!1;const p=this.client.getRoom(m.getRoomId());if(!p||!p.currentState||!p.currentState.members)return!1;const _=p.currentState.getJoinedMemberCount(),u=S.is.match(/^([=<>]*)(\d*)$/);if(!u)return!1;const l=u[1],d=parseInt(u[2]);if(isNaN(d))return!1;switch(l){case"":case"==":return _==d;case"<":return _<d;case">":return _>d;case"<=":return _<=d;case">=":return _>=d;default:return!1}}eventFulfillsDisplayNameCondition(S,m){var p;let _=m.getContent();if(m.isEncrypted()&&m.getClearContent()&&(_=m.getClearContent()),!_||!_.body||typeof _.body!="string")return!1;const u=this.client.getRoom(m.getRoomId()),l=u==null||(p=u.currentState)===null||p===void 0?void 0:p.getMember(this.client.credentials.userId);if(!l)return!1;const d=l.name,h=new RegExp("(^|\\W)"+(0,n.escapeRegExp)(d)+"(\\W|$)","i");return _.body.search(h)>-1}eventFulfillsEventMatchCondition(S,m){if(!S.key)return!1;const p=this.valueForDottedKey(S.key,m);if(typeof p!="string")return!1;if(S.value)return S.value===p;if(typeof S.pattern!="string")return!1;const _=S.key==="content.body"?this.createCachedRegex("(^|\\W)",S.pattern,"(\\W|$)"):this.createCachedRegex("^",S.pattern,"$");return!!p.match(_)}eventFulfillsCallStartedCondition(S,m){return["m.ring","m.prompt"].includes(m.getContent()["m.intent"])&&!("m.terminated"in m.getContent())&&(m.getPrevContent()["m.terminated"]!==m.getContent()["m.terminated"]||(0,n.deepCompare)(m.getPrevContent(),{}))}createCachedRegex(S,m,p){return g.cachedGlobToRegex[m]||(g.cachedGlobToRegex[m]=new RegExp(S+(0,n.globToRegexp)(m)+p,"i")),g.cachedGlobToRegex[m]}valueForDottedKey(S,m){const p=S.split(".");let _;const u=p[0];for(u==="content"?(_=m.getContent(),p.shift()):u==="type"?(_=m.getType(),p.shift()):_=m.event;p.length>0;){const l=p.shift();if((0,n.isNullOrUndefined)(_[l]))return null;_=_[l]}return _}matchingRuleForEventWithRulesets(S,m){return!m||S.getSender()===this.client.credentials.userId?null:this.matchingRuleFromKindSet(S,m.global)}pushActionsForEventAndRulesets(S,m){const p=this.matchingRuleForEventWithRulesets(S,m);if(!p)return{};const _=g.actionListToActionsObject(p.actions);return _.tweaks.highlight===void 0&&(_.tweaks.highlight=p.kind==i.PushRuleKind.ContentSpecific),_}ruleMatchesEvent(S,m){var p;return!((p=S.conditions)!==null&&p!==void 0&&p.some(_=>!this.eventFulfillsCondition(_,m)))}actionsForEvent(S){return this.pushActionsForEventAndRulesets(S,this.client.pushRules)}getPushRuleById(S){for(const p of["global"]){var m;if(((m=this.client.pushRules)===null||m===void 0?void 0:m[p])!==void 0){for(const _ of f)if(this.client.pushRules[p][_]!==void 0){for(const u of this.client.pushRules[p][_])if(u.rule_id===S)return u}}}return null}}return Za.PushProcessor=g,(0,t.default)(g,"cachedGlobToRegex",{}),Za}var jt={},wW=Ae;Object.defineProperty(jt,"__esModule",{value:!0});jt.KeySignatureUploadError=jt.InvalidStoreState=jt.InvalidStoreError=jt.InvalidCryptoStoreState=jt.InvalidCryptoStoreError=void 0;var jP=wW(Ue);let Zd;jt.InvalidStoreState=Zd;(function(e){e[e.ToggledLazyLoading=0]="ToggledLazyLoading"})(Zd||(jt.InvalidStoreState=Zd={}));class qP extends Error{constructor(t,n){const r=`Store is invalid because ${t}, please stop the client, delete all data and start the client again`;super(r),this.reason=t,this.value=n,this.name="InvalidStoreError"}}jt.InvalidStoreError=qP;(0,jP.default)(qP,"TOGGLED_LAZY_LOADING",Zd.ToggledLazyLoading);let ef;jt.InvalidCryptoStoreState=ef;(function(e){e.TooNew="TOO_NEW"})(ef||(jt.InvalidCryptoStoreState=ef={}));class VP extends Error{constructor(t){const n=`Crypto store is invalid because ${t}, please stop the client, delete all data and start the client again`;super(n),this.reason=t,this.name="InvalidCryptoStoreError"}}jt.InvalidCryptoStoreError=VP;(0,jP.default)(VP,"TOO_NEW",ef.TooNew);class bW extends Error{constructor(t,n){super(t),this.value=n}}jt.KeySignatureUploadError=bW;var Rr={},el={},hs={},w0;function WP(){if(w0)return hs;w0=1,Object.defineProperty(hs,"__esModule",{value:!0}),hs.Method=void 0;let e;return hs.Method=e,function(t){t.Get="GET",t.Put="PUT",t.Post="POST",t.Delete="DELETE"}(e||(hs.Method=e={})),hs}var Gr={},b0;function Jy(){if(b0)return Gr;b0=1;var e=Ae;Object.defineProperty(Gr,"__esModule",{value:!0}),Gr.MatrixError=Gr.HTTPError=Gr.ConnectionError=void 0;var t=e(Ue);class n extends Error{constructor(a,c){super(a),this.httpStatus=c}}Gr.HTTPError=n;class r extends n{constructor(a={},c,f,v){let s=a.error||"Unknown message";c&&(s=`[${c}] ${s}`),f&&(s=`${s} (${f})`),super(`MatrixError: ${s}`,c),this.httpStatus=c,this.url=f,this.event=v,(0,t.default)(this,"errcode",void 0),(0,t.default)(this,"data",void 0),this.errcode=a.errcode,this.name=a.errcode||"Unknown error code",this.data=a}}Gr.MatrixError=r;class i extends Error{constructor(a,c){super(a+(c?`: ${c.message}`:""))}get name(){return"ConnectionError"}}return Gr.ConnectionError=i,Gr}var ps={},T0;function HP(){if(T0)return ps;T0=1,Object.defineProperty(ps,"__esModule",{value:!0}),ps.HttpApiEvent=void 0;let e;return ps.HttpApiEvent=e,function(t){t.SessionLoggedOut="Session.logged_out",t.NoConsent="no_consent"}(e||(ps.HttpApiEvent=e={})),ps}var _o={},Lc={};/*!
     79  * content-type
     80  * Copyright(c) 2015 Douglas Christopher Wilson
     81  * MIT Licensed
     82  */var R0;function TW(){if(R0)return Lc;R0=1;var e=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,t=/^[\u000b\u0020-\u007e\u0080-\u00ff]+$/,n=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,r=/\\([\u000b\u0020-\u00ff])/g,i=/([\\"])/g,o=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;Lc.format=a,Lc.parse=c;function a(g){if(!g||typeof g!="object")throw new TypeError("argument obj is required");var y=g.parameters,S=g.type;if(!S||!o.test(S))throw new TypeError("invalid type");var m=S;if(y&&typeof y=="object")for(var p,_=Object.keys(y).sort(),u=0;u<_.length;u++){if(p=_[u],!n.test(p))throw new TypeError("invalid parameter name");m+="; "+p+"="+v(y[p])}return m}function c(g){if(!g)throw new TypeError("argument string is required");var y=typeof g=="object"?f(g):g;if(typeof y!="string")throw new TypeError("argument string is required to be a string");var S=y.indexOf(";"),m=S!==-1?y.substr(0,S).trim():y.trim();if(!o.test(m))throw new TypeError("invalid media type");var p=new s(m.toLowerCase());if(S!==-1){var _,u,l;for(e.lastIndex=S;u=e.exec(y);){if(u.index!==S)throw new TypeError("invalid parameter format");S+=u[0].length,_=u[1].toLowerCase(),l=u[2],l[0]==='"'&&(l=l.substr(1,l.length-2).replace(r,"$1")),p.parameters[_]=l}if(S!==y.length)throw new TypeError("invalid parameter format")}return p}function f(g){var y;if(typeof g.getHeader=="function"?y=g.getHeader("content-type"):typeof g.headers=="object"&&(y=g.headers&&g.headers["content-type"]),typeof y!="string")throw new TypeError("content-type header is missing from object");return y}function v(g){var y=String(g);if(n.test(y))return y;if(y.length>0&&!t.test(y))throw new TypeError("invalid parameter value");return'"'+y.replace(i,"\\$1")+'"'}function s(g){this.parameters=Object.create(null),this.type=g}return Lc}var I0;function GP(){if(I0)return _o;I0=1,Object.defineProperty(_o,"__esModule",{value:!0}),_o.anySignal=o,_o.parseErrorResponse=a,_o.retryNetworkOperation=v,_o.timeoutSignal=i;var e=TW(),t=Ge(),n=lt(),r=Jy();function i(s){const g=new AbortController;return setTimeout(()=>{g.abort()},s),g.signal}function o(s){const g=new AbortController;function y(){for(const m of s)m.removeEventListener("abort",S)}function S(){g.abort(),y()}for(const m of s){if(m.aborted){S();break}m.addEventListener("abort",S)}return{signal:g.signal,cleanup:y}}function a(s,g){var y,S;let m;try{m=f(s)}catch(p){return p}return((y=m)===null||y===void 0?void 0:y.type)==="application/json"&&g?new r.MatrixError(JSON.parse(g),s.status,c(s)?s.responseURL:s.url):((S=m)===null||S===void 0?void 0:S.type)==="text/plain"?new r.HTTPError(`Server returned ${s.status} error: ${g}`,s.status):new r.HTTPError(`Server returned ${s.status} error`,s.status)}function c(s){return"getResponseHeader"in s}function f(s){let g;if(c(s)?g=s.getResponseHeader("Content-Type"):g=s.headers.get("Content-Type"),!g)return null;try{return(0,e.parse)(g)}catch(y){throw new Error(`Error parsing Content-Type '${g}': ${y}`)}}async function v(s,g){let y=0,S=null;for(;y<s;)try{if(y>0){const m=1e3*Math.pow(2,y);t.logger.log(`network operation failed ${y} times, retrying in ${m}ms...`),await(0,n.sleep)(m)}return await g()}catch(m){if(m instanceof r.ConnectionError)y+=1,S=m;else throw m}throw S}return _o}var C0;function RW(){if(C0)return el;C0=1;var e=Ae;Object.defineProperty(el,"__esModule",{value:!0}),el.FetchHttpApi=void 0;var t=e(Ue),n=f(lt()),r=WP(),i=Jy(),o=HP(),a=GP();function c(s){if(typeof WeakMap!="function")return null;var g=new WeakMap,y=new WeakMap;return(c=function(S){return S?y:g})(s)}function f(s,g){if(!g&&s&&s.__esModule)return s;if(s===null||typeof s!="object"&&typeof s!="function")return{default:s};var y=c(g);if(y&&y.has(s))return y.get(s);var S={},m=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var p in s)if(p!=="default"&&Object.prototype.hasOwnProperty.call(s,p)){var _=m?Object.getOwnPropertyDescriptor(s,p):null;_&&(_.get||_.set)?Object.defineProperty(S,p,_):S[p]=s[p]}return S.default=s,y&&y.set(s,S),S}class v{constructor(g,y){var S;this.eventEmitter=g,this.opts=y,(0,t.default)(this,"abortController",new AbortController),n.checkObjectHasKeys(y,["baseUrl","prefix"]),y.onlyData=!!y.onlyData,y.useAuthorizationHeader=(S=y.useAuthorizationHeader)!==null&&S!==void 0?S:!0}abort(){this.abortController.abort(),this.abortController=new AbortController}fetch(g,y){return this.opts.fetchFn?this.opts.fetchFn(g,y):$e.fetch(g,y)}setIdBaseUrl(g){this.opts.idBaseUrl=g}idServerRequest(g,y,S,m,p){if(!this.opts.idBaseUrl)throw new Error("No identity server base URL set");let _,u;g===r.Method.Get?_=S:u=S;const l=this.getUrl(y,_,m,this.opts.idBaseUrl),d={json:!0,headers:{}};return p&&(d.headers.Authorization=`Bearer ${p}`),this.requestOtherUrl(g,l,u,d)}authedRequest(g,y,S,m,p={}){S||(S={}),this.opts.accessToken&&(this.opts.useAuthorizationHeader?(p.headers||(p.headers={}),p.headers.Authorization||(p.headers.Authorization="Bearer "+this.opts.accessToken),S.access_token&&delete S.access_token):S.access_token||(S.access_token=this.opts.accessToken));const _=this.request(g,y,S,m,p);return _.catch(u=>{u.errcode=="M_UNKNOWN_TOKEN"&&!(p!=null&&p.inhibitLogoutEmit)?this.eventEmitter.emit(o.HttpApiEvent.SessionLoggedOut,u):u.errcode=="M_CONSENT_NOT_GIVEN"&&this.eventEmitter.emit(o.HttpApiEvent.NoConsent,u.message,u.data.consent_uri)}),_}request(g,y,S,m,p){const _=this.getUrl(y,S,p==null?void 0:p.prefix,p==null?void 0:p.baseUrl);return this.requestOtherUrl(g,_,m,p)}async requestOtherUrl(g,y,S,m={}){var p,_,u,l;const d=Object.assign({},m.headers||{}),h=(p=m.json)!==null&&p!==void 0?p:!0,w=h&&(S==null||(_=S.constructor)===null||_===void 0?void 0:_.name)===Object.name;h&&(w&&!d["Content-Type"]&&(d["Content-Type"]="application/json"),d.Accept||(d.Accept="application/json"));const E=(u=m.localTimeoutMs)!==null&&u!==void 0?u:this.opts.localTimeoutMs,I=(l=m.keepAlive)!==null&&l!==void 0?l:!1,k=[this.abortController.signal];E!==void 0&&k.push((0,a.timeoutSignal)(E)),m.abortSignal&&k.push(m.abortSignal);let M;w?M=JSON.stringify(S):M=S;const{signal:L,cleanup:B}=(0,a.anySignal)(k);let N;try{N=await this.fetch(y,{signal:L,method:g,body:M,headers:d,mode:"cors",redirect:"follow",referrer:"",referrerPolicy:"no-referrer",cache:"no-cache",credentials:"omit",keepalive:I})}catch(G){throw G.name==="AbortError"?G:new i.ConnectionError("fetch failed",G)}finally{B()}if(!N.ok)throw(0,a.parseErrorResponse)(N,await N.text());return this.opts.onlyData?h?N.json():N.text():N}getUrl(g,y,S,m){const p=new URL((m??this.opts.baseUrl)+(S??this.opts.prefix)+g);return y&&n.encodeParams(y,p.searchParams),p}}return el.FetchHttpApi=v,el}var jn={},O0;function IW(){if(O0)return jn;O0=1,Object.defineProperty(jn,"__esModule",{value:!0}),jn.MediaPrefix=jn.IdentityPrefix=jn.ClientPrefix=void 0;let e;jn.ClientPrefix=e,function(r){r.R0="/_matrix/client/r0",r.V1="/_matrix/client/v1",r.V3="/_matrix/client/v3",r.Unstable="/_matrix/client/unstable"}(e||(jn.ClientPrefix=e={}));let t;jn.IdentityPrefix=t,function(r){r.V1="/_matrix/identity/api/v1",r.V2="/_matrix/identity/v2"}(t||(jn.IdentityPrefix=t={}));let n;return jn.MediaPrefix=n,function(r){r.R0="/_matrix/media/r0"}(n||(jn.MediaPrefix=n={})),jn}var tl={},P0;function CW(){if(P0)return tl;P0=1,Object.defineProperty(tl,"__esModule",{value:!0}),tl.clearTimeout=c,tl.setTimeout=a;var e=Ge();const t=1e3;let n=0,r;const i=[],o=function(...g){};function a(g,y,...S){y=y||0,y<0&&(y=0);const m=Date.now()+y,p=n++,_={runAt:m,func:g,params:S,key:p},u=s(i,function(l){return l.runAt-m});return i.splice(u,0,_),f(),p}function c(g){if(i.length===0)return;let y;for(y=0;y<i.length;y++)if(i[y].key==g){i.splice(y,1);break}y===0&&f()}function f(){r&&$e.clearTimeout(r);const g=i[0];if(!g)return;const y=Date.now(),S=Math.min(g.runAt-y,t);r=$e.setTimeout(v,S)}function v(){const g=Date.now(),y=[];for(;;){const S=i[0];if(!S||S.runAt>g)break;const m=i.shift();o("runCallbacks: popping",m.key),y.push(m)}f();for(const S of y)try{S.func.apply($e,S.params)}catch(m){e.logger.error("Uncaught exception in callback function",m)}}function s(g,y){let S=0,m=g.length;for(;S<m;){const p=S+m>>1;y(g[p])>0?m=p:S=p+1}return S}return tl}(function(e){var t=Ae;Object.defineProperty(e,"__esModule",{value:!0});var n={MatrixHttpApi:!0};e.MatrixHttpApi=void 0;var r=t(Ue),i=RW(),o=IW();Object.keys(o).forEach(function(p){p==="default"||p==="__esModule"||Object.prototype.hasOwnProperty.call(n,p)||p in e&&e[p]===o[p]||Object.defineProperty(e,p,{enumerable:!0,get:function(){return o[p]}})});var a=S(lt()),c=S(CW()),f=WP();Object.keys(f).forEach(function(p){p==="default"||p==="__esModule"||Object.prototype.hasOwnProperty.call(n,p)||p in e&&e[p]===f[p]||Object.defineProperty(e,p,{enumerable:!0,get:function(){return f[p]}})});var v=Jy();Object.keys(v).forEach(function(p){p==="default"||p==="__esModule"||Object.prototype.hasOwnProperty.call(n,p)||p in e&&e[p]===v[p]||Object.defineProperty(e,p,{enumerable:!0,get:function(){return v[p]}})});var s=GP();Object.keys(s).forEach(function(p){p==="default"||p==="__esModule"||Object.prototype.hasOwnProperty.call(n,p)||p in e&&e[p]===s[p]||Object.defineProperty(e,p,{enumerable:!0,get:function(){return s[p]}})});var g=HP();Object.keys(g).forEach(function(p){p==="default"||p==="__esModule"||Object.prototype.hasOwnProperty.call(n,p)||p in e&&e[p]===g[p]||Object.defineProperty(e,p,{enumerable:!0,get:function(){return g[p]}})});function y(p){if(typeof WeakMap!="function")return null;var _=new WeakMap,u=new WeakMap;return(y=function(l){return l?u:_})(p)}function S(p,_){if(!_&&p&&p.__esModule)return p;if(p===null||typeof p!="object"&&typeof p!="function")return{default:p};var u=y(_);if(u&&u.has(p))return u.get(p);var l={},d=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var h in p)if(h!=="default"&&Object.prototype.hasOwnProperty.call(p,h)){var w=d?Object.getOwnPropertyDescriptor(p,h):null;w&&(w.get||w.set)?Object.defineProperty(l,h,w):l[h]=p[h]}return l.default=p,u&&u.set(p,l),l}class m extends i.FetchHttpApi{constructor(..._){super(..._),(0,r.default)(this,"uploads",[])}uploadContent(_,u={}){var l,d,h,w,E;const I=(l=u.includeFilename)!==null&&l!==void 0?l:!0,k=(d=u.abortController)!==null&&d!==void 0?d:new AbortController,M=(h=(w=u.type)!==null&&w!==void 0?w:_.type)!==null&&h!==void 0?h:"application/octet-stream",L=(E=u.name)!==null&&E!==void 0?E:_.name,B={loaded:0,total:0,abortController:k},N=a.defer();if($e.XMLHttpRequest){const G=new $e.XMLHttpRequest,D=function(){G.abort(),N.reject(new Error("Timeout"))};let x=c.setTimeout(D,3e4);G.onreadystatechange=function(){switch(G.readyState){case $e.XMLHttpRequest.DONE:c.clearTimeout(x);try{if(G.status===0)throw new DOMException(G.statusText,"AbortError");if(!G.responseText)throw new Error("No response body.");G.status>=400?N.reject((0,s.parseErrorResponse)(G,G.responseText)):N.resolve(JSON.parse(G.responseText))}catch(W){if(W.name==="AbortError"){N.reject(W);return}N.reject(new v.ConnectionError("request failed",W))}break}},G.upload.onprogress=W=>{var F;c.clearTimeout(x),B.loaded=W.loaded,B.total=W.total,x=c.setTimeout(D,3e4),(F=u.progressHandler)===null||F===void 0||F.call(u,{loaded:W.loaded,total:W.total})};const z=this.getUrl("/upload",void 0,o.MediaPrefix.R0);I&&L&&z.searchParams.set("filename",encodeURIComponent(L)),!this.opts.useAuthorizationHeader&&this.opts.accessToken&&z.searchParams.set("access_token",encodeURIComponent(this.opts.accessToken)),G.open(f.Method.Post,z.href),this.opts.useAuthorizationHeader&&this.opts.accessToken&&G.setRequestHeader("Authorization","Bearer "+this.opts.accessToken),G.setRequestHeader("Content-Type",M),G.send(_),k.signal.addEventListener("abort",()=>{G.abort()})}else{const G={};I&&L&&(G.filename=L);const D={"Content-Type":M};this.authedRequest(f.Method.Post,"/upload",G,_,{prefix:o.MediaPrefix.R0,headers:D,abortSignal:k.signal}).then(x=>this.opts.onlyData?x:x.json()).then(N.resolve,N.reject)}return B.promise=N.promise.finally(()=>{a.removeElement(this.uploads,G=>G===B)}),k.signal.addEventListener("abort",()=>{a.removeElement(this.uploads,G=>G===B),N.reject(new DOMException("Aborted","AbortError"))}),this.uploads.push(B),B.promise}cancelUpload(_){const u=this.uploads.find(l=>l.promise===_);return u?(u.abortController.abort(),!0):!1}getCurrentUploads(){return this.uploads}getContentUri(){return{base:this.opts.baseUrl,path:o.MediaPrefix.R0+"/upload",params:{access_token:this.opts.accessToken}}}}e.MatrixHttpApi=m})(Rr);var k0;function Vf(){if(k0)return Hr;k0=1;var e=Ae;Object.defineProperty(Hr,"__esModule",{value:!0}),Hr.SyncState=Hr.SyncApi=void 0,Hr._createAndReEmitRoom=G;var t=e(Ue),n=Xn,r=hi(),i=d(lt()),o=qf(),a=Tr(),c=Qy(),f=Ge(),v=jt,s=or(),g=Rr,y=xe,S=po(),m=Zn,p=bn,_=jf(),u=Yy();function l(D){if(typeof WeakMap!="function")return null;var x=new WeakMap,z=new WeakMap;return(l=function(W){return W?z:x})(D)}function d(D,x){if(!x&&D&&D.__esModule)return D;if(D===null||typeof D!="object"&&typeof D!="function")return{default:D};var z=l(x);if(z&&z.has(D))return z.get(D);var W={},F=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var H in D)if(H!=="default"&&Object.prototype.hasOwnProperty.call(D,H)){var R=F?Object.getOwnPropertyDescriptor(D,H):null;R&&(R.get||R.set)?Object.defineProperty(W,H,R):W[H]=D[H]}return W.default=D,z&&z.set(D,W),W}const h=80*1e3,w=3;let E;Hr.SyncState=E,function(D){D.Error="ERROR",D.Prepared="PREPARED",D.Stopped="STOPPED",D.Syncing="SYNCING",D.Catchup="CATCHUP",D.Reconnecting="RECONNECTING"}(E||(Hr.SyncState=E={}));const I=["org.matrix.msc2716v3"];function k(D,x){return`FILTER_SYNC_${D}`+(x?"_"+x:"")}function M(...D){f.logger.log(...D)}var L;(function(D){D.Offline="offline",D.Online="online",D.Unavailable="unavailable"})(L||(L={}));class B{constructor(x,z={}){var W;this.client=x,this.opts=z,(0,t.default)(this,"_peekRoom",null),(0,t.default)(this,"currentSyncRequest",void 0),(0,t.default)(this,"abortController",void 0),(0,t.default)(this,"syncState",null),(0,t.default)(this,"syncStateData",void 0),(0,t.default)(this,"catchingUp",!1),(0,t.default)(this,"running",!1),(0,t.default)(this,"keepAliveTimer",void 0),(0,t.default)(this,"connectionReturnedDefer",void 0),(0,t.default)(this,"notifEvents",[]),(0,t.default)(this,"failedSyncCount",0),(0,t.default)(this,"storeIsInvalid",!1),(0,t.default)(this,"getPushRules",async()=>{try{M("Getting push rules...");const F=await this.client.getPushRules();M("Got push rules"),this.client.pushRules=F}catch(F){return f.logger.error("Getting push rules failed",F),this.shouldAbortSync(F)?void 0:(M("Waiting for saved sync before retrying push rules..."),await this.recoverFromSyncStartupError(this.savedSyncPromise,F),this.getPushRules())}}),(0,t.default)(this,"buildDefaultFilter",()=>{const F=new o.Filter(this.client.credentials.userId);return this.client.canSupport.get(u.Feature.ThreadUnreadNotifications)!==u.ServerSupport.Unsupported&&F.setUnreadThreadNotifications(!0),F}),(0,t.default)(this,"checkLazyLoadStatus",async()=>{if(M("Checking lazy load status..."),this.opts.lazyLoadMembers&&this.client.isGuest()&&(this.opts.lazyLoadMembers=!1),this.opts.lazyLoadMembers&&(M("Checking server lazy load support..."),await this.client.doesServerSupportLazyLoading()?(M("Enabling lazy load on sync filter..."),this.opts.filter||(this.opts.filter=this.buildDefaultFilter()),this.opts.filter.setLazyLoadMembers(!0)):(M("LL: lazy loading requested but not supported by server, so disabling"),this.opts.lazyLoadMembers=!1)),M("Checking whether lazy loading has changed in store..."),await this.wasLazyLoadingToggled(this.opts.lazyLoadMembers)){this.storeIsInvalid=!0;const R=new v.InvalidStoreError(v.InvalidStoreState.ToggledLazyLoading,!!this.opts.lazyLoadMembers);this.updateSyncState(E.Error,{error:R}),f.logger.warn("InvalidStoreError: store is not usable: stopping sync.");return}if(this.opts.lazyLoadMembers){var H;(H=this.opts.crypto)===null||H===void 0||H.enableLazyLoading()}try{M("Storing client options..."),await this.client.storeClientOptions(),M("Stored client options")}catch(R){throw f.logger.error("Storing client options failed",R),R}}),(0,t.default)(this,"getFilter",async()=>{M("Getting filter...");let F;this.opts.filter?F=this.opts.filter:F=this.buildDefaultFilter();let H;try{H=await this.client.getOrCreateFilter(k(this.client.credentials.userId),F)}catch(R){return f.logger.error("Getting filter failed",R),this.shouldAbortSync(R)?{}:(M("Waiting for saved sync before retrying filter..."),await this.recoverFromSyncStartupError(this.savedSyncPromise,R),this.getFilter())}return{filter:F,filterId:H}}),(0,t.default)(this,"savedSyncPromise",void 0),(0,t.default)(this,"onOnline",()=>{M("Browser thinks we are back online"),this.startKeepAlives(0)}),this.opts.initialSyncLimit=(W=this.opts.initialSyncLimit)!==null&&W!==void 0?W:8,this.opts.resolveInvitesToProfiles=this.opts.resolveInvitesToProfiles||!1,this.opts.pollTimeout=this.opts.pollTimeout||30*1e3,this.opts.pendingEventOrdering=this.opts.pendingEventOrdering||s.PendingEventOrdering.Chronological,this.opts.experimentalThreadSupport=this.opts.experimentalThreadSupport===!0,z.canResetEntireTimeline||(z.canResetEntireTimeline=F=>!1),x.getNotifTimelineSet()&&x.reEmitter.reEmit(x.getNotifTimelineSet(),[r.RoomEvent.Timeline,r.RoomEvent.TimelineReset])}createRoom(x){const z=G(this.client,x,this.opts);return z.on(S.RoomStateEvent.Marker,(W,F)=>{this.onMarkerStateEvent(z,W,F)}),z}onMarkerStateEvent(x,z,{timelineWasEmpty:W}={}){if(W){f.logger.debug(`MarkerState: Ignoring markerEventId=${z.getId()} in roomId=${x.roomId} because the timeline was empty before the marker arrived which means there is nothing to refresh.`);return}I.includes(x.getVersion())||z.getSender()===x.getCreator()?(f.logger.debug(`MarkerState: Timeline needs to be refreshed because a new markerEventId=${z.getId()} was sent in roomId=${x.roomId}`),x.setTimelineNeedsRefresh(!0),x.emit(r.RoomEvent.HistoryImportedWithinTimeline,z,x)):f.logger.debug(`MarkerState: Ignoring markerEventId=${z.getId()} in roomId=${x.roomId} because MSC2716 is not supported in the room version or for any room version, the marker wasn't sent by the room creator.`)}async syncLeftRooms(){var x;const z=this.client,W=new o.Filter(this.client.credentials.userId);W.setTimelineLimit(1),W.setIncludeLeaveRooms(!0);const F=this.opts.pollTimeout+h,R={timeout:0,filter:await z.getOrCreateFilter(k(z.credentials.userId,"LEFT_ROOMS"),W)},P=await z.http.authedRequest(g.Method.Get,"/sync",R,void 0,{localTimeoutMs:F});let K=[];return(x=P.rooms)!==null&&x!==void 0&&x.leave&&(K=this.mapSyncResponseToRoomArray(P.rooms.leave)),(await Promise.all(K.map(async C=>{const A=C.room;if(!C.isBrandNewRoom)return;C.timeline=C.timeline||{prev_batch:null,events:[]};const T=this.mapSyncEventsFormat(C.timeline,A),X=this.mapSyncEventsFormat(C.state,A);return A.getLiveTimeline().setPaginationToken(C.timeline.prev_batch,a.EventTimeline.BACKWARDS),await this.injectRoomEvents(A,X,T),A.recalculate(),z.store.storeRoom(A),z.emit(s.ClientEvent.Room,A),this.processEventsForNotifs(A,T),A}))).filter(Boolean)}peek(x){var z;if(((z=this._peekRoom)===null||z===void 0?void 0:z.roomId)===x)return Promise.resolve(this._peekRoom);const W=this.client;return this._peekRoom=this.createRoom(x),this.client.roomInitialSync(x,20).then(F=>{F.messages=F.messages||{chunk:[]},F.messages.chunk=F.messages.chunk||[],F.state=F.state||[];const H=i.deepCopy(F.state).map(W.getEventMapper()),R=F.state.map(W.getEventMapper()),P=F.messages.chunk.map(W.getEventMapper());return Array.isArray(F.presence)&&F.presence.map(W.getEventMapper()).forEach(function(K){let U=W.store.getUser(K.getContent().user_id);U?U.setPresenceEvent(K):(U=N(W,K.getContent().user_id),U.setPresenceEvent(K),W.store.storeUser(U)),W.emit(s.ClientEvent.Event,K)}),F.messages.start&&(this._peekRoom.oldState.paginationToken=F.messages.start),this._peekRoom.oldState.setStateEvents(H),this._peekRoom.currentState.setStateEvents(R),this.resolveInvites(this._peekRoom),this._peekRoom.recalculate(),this._peekRoom.addEventsToTimeline(P.reverse(),!0,this._peekRoom.getLiveTimeline(),F.messages.start),W.store.storeRoom(this._peekRoom),W.emit(s.ClientEvent.Room,this._peekRoom),this.peekPoll(this._peekRoom),this._peekRoom})}stopPeeking(){this._peekRoom=null}peekPoll(x,z){var W;if(this._peekRoom!==x){M("Stopped peeking in room %s",x.roomId);return}this.client.http.authedRequest(g.Method.Get,"/events",{room_id:x.roomId,timeout:String(30*1e3),from:z},void 0,{localTimeoutMs:50*1e3,abortSignal:(W=this.abortController)===null||W===void 0?void 0:W.signal}).then(F=>{if(this._peekRoom!==x){M("Stopped peeking in room %s",x.roomId);return}F.chunk.filter(function(R){return R.type==="m.presence"}).map(this.client.getEventMapper()).forEach(R=>{let P=this.client.store.getUser(R.getContent().user_id);P?P.setPresenceEvent(R):(P=N(this.client,R.getContent().user_id),P.setPresenceEvent(R),this.client.store.storeUser(P)),this.client.emit(s.ClientEvent.Event,R)});const H=F.chunk.filter(function(R){return R.room_id===x.roomId&&R.event_id}).map(this.client.getEventMapper());x.addLiveEvents(H),this.peekPoll(x,F.end)},F=>{f.logger.error("[%s] Peek poll failed: %s",x.roomId,F),setTimeout(()=>{this.peekPoll(x,z)},30*1e3)})}getSyncState(){return this.syncState}getSyncStateData(){var x;return(x=this.syncStateData)!==null&&x!==void 0?x:null}async recoverFromSyncStartupError(x,z){await x;const W=this.startKeepAlives();this.updateSyncState(E.Error,{error:z}),await W}async wasLazyLoadingToggled(x=!1){let z=!1;if(!await this.client.store.isNewlyCreated()){const F=await this.client.store.getClientOptions();return F&&(z=!!F.lazyLoadMembers),z!==x}return!1}shouldAbortSync(x){return x.errcode==="M_UNKNOWN_TOKEN"?(f.logger.warn("Token no longer valid - assuming logout"),this.stop(),this.updateSyncState(E.Error,{error:x}),!0):!1}async sync(){var x,z;if(this.running=!0,this.abortController=new AbortController,(x=$e.window)===null||x===void 0||(z=x.addEventListener)===null||z===void 0||z.call(x,"online",this.onOnline,!1),this.client.isGuest())return this.doSync({});M("Getting saved sync token...");const W=this.client.store.getSavedSyncToken().then(R=>(M("Got saved sync token"),R));this.savedSyncPromise=this.client.store.getSavedSync().then(R=>{if(M(`Got reply from saved sync, exists? ${!!R}`),R)return this.syncFromCache(R)}).catch(R=>{f.logger.error("Getting saved sync failed",R)}),await this.getPushRules(),await this.checkLazyLoadStatus();const{filterId:F,filter:H}=await this.getFilter();if(H){if(this.client.resetNotifTimelineSet(),!this.currentSyncRequest){let R=F;const P=await W;if(P)M("Sending first sync request...");else{M("Sending initial sync request...");const K=this.buildDefaultFilter();K.setDefinition(H.getDefinition()),K.setTimelineLimit(this.opts.initialSyncLimit),R=JSON.stringify(K.getDefinition())}this.currentSyncRequest=this.doSyncRequest({filter:R},P)}return M("Waiting for saved sync before starting sync processing..."),await this.savedSyncPromise,this.doSync({filter:F})}}stop(){var x,z,W;M("SyncApi.stop"),(x=$e.window)===null||x===void 0||(z=x.removeEventListener)===null||z===void 0||z.call(x,"online",this.onOnline,!1),this.running=!1,(W=this.abortController)===null||W===void 0||W.abort(),this.keepAliveTimer&&(clearTimeout(this.keepAliveTimer),this.keepAliveTimer=void 0)}retryImmediately(){return this.connectionReturnedDefer?(this.startKeepAlives(0),!0):!1}async syncFromCache(x){M("sync(): not doing HTTP hit, instead returning stored /sync data");const z=x.nextBatch;this.client.store.setSyncToken(z);const W={nextSyncToken:z,catchingUp:!1,fromCache:!0},F={next_batch:z,rooms:x.roomsData,account_data:{events:x.accountData}};try{await this.processSyncResponse(W,F)}catch(H){f.logger.error("Error processing cached sync",H)}this.storeIsInvalid||this.updateSyncState(E.Prepared,W)}async doSync(x){for(;this.running;){const z=this.client.store.getSyncToken();let W;try{this.currentSyncRequest||(this.currentSyncRequest=this.doSyncRequest(x,z)),W=await this.currentSyncRequest}catch(H){if(await this.onSyncError(H))return;continue}finally{this.currentSyncRequest=void 0}this.client.store.setSyncToken(W.next_batch),this.failedSyncCount=0,await this.client.store.setSyncData(W);const F={oldSyncToken:z??void 0,nextSyncToken:W.next_batch,catchingUp:this.catchingUp};this.opts.crypto&&await this.opts.crypto.onSyncWillProcess(F);try{await this.processSyncResponse(F,W)}catch(H){f.logger.error("Caught /sync error",H),this.client.emit(s.ClientEvent.SyncUnexpectedError,H)}F.catchingUp=this.catchingUp,x.hasSyncedBefore||(this.updateSyncState(E.Prepared,F),x.hasSyncedBefore=!0),this.opts.crypto&&await this.opts.crypto.onSyncCompleted(F),this.updateSyncState(E.Syncing,F),this.client.store.wantsSave()&&(this.opts.crypto&&await this.opts.crypto.saveDeviceList(0),this.client.store.save())}this.running||(M("Sync no longer running: exiting."),this.connectionReturnedDefer&&(this.connectionReturnedDefer.reject(),this.connectionReturnedDefer=void 0),this.updateSyncState(E.Stopped))}doSyncRequest(x,z){var W;const F=this.getSyncParams(x,z);return this.client.http.authedRequest(g.Method.Get,"/sync",F,void 0,{localTimeoutMs:F.timeout+h,abortSignal:(W=this.abortController)===null||W===void 0?void 0:W.signal})}getSyncParams(x,z){let W=this.opts.pollTimeout;(this.getSyncState()!==E.Syncing||this.catchingUp)&&(this.catchingUp=!0,W=0);let F=x.filter;this.client.isGuest()&&!F&&(F=this.getGuestFilter());const H={filter:F,timeout:W};return this.opts.disablePresence&&(H.set_presence=L.Offline),z?H.since=z:H._cacheBuster=Date.now(),[E.Reconnecting,E.Error].includes(this.getSyncState())&&(H.timeout=0),H}async onSyncError(x){if(!this.running)return M("Sync no longer running: exiting"),this.connectionReturnedDefer&&(this.connectionReturnedDefer.reject(),this.connectionReturnedDefer=void 0),this.updateSyncState(E.Stopped),!0;if(f.logger.error("/sync error %s",x),this.shouldAbortSync(x))return!0;this.failedSyncCount++,f.logger.log("Number of consecutive failed sync requests:",this.failedSyncCount),M("Starting keep-alive");const z=this.startKeepAlives();return this.currentSyncRequest=void 0,this.updateSyncState(this.failedSyncCount>=w?E.Error:E.Reconnecting,{error:x}),await z&&this.getSyncState()===E.Error&&this.updateSyncState(E.Catchup,{catchingUp:!0}),!1}async processSyncResponse(x,z){var W,F,H;const R=this.client;if(Array.isArray((W=z.presence)===null||W===void 0?void 0:W.events)&&z.presence.events.map(R.getEventMapper()).forEach(function(C){let A=R.store.getUser(C.getSender());A?A.setPresenceEvent(C):(A=N(R,C.getSender()),A.setPresenceEvent(C),R.store.storeUser(A)),R.emit(s.ClientEvent.Event,C)}),Array.isArray((F=z.account_data)===null||F===void 0?void 0:F.events)){const C=z.account_data.events.map(R.getEventMapper()),A=C.reduce((T,X)=>(T[X.getType()]=R.store.getAccountData(X.getType()),T),{});R.store.storeAccountDataEvents(C),C.forEach(function(T){if(T.getType()===y.EventType.PushRules){const ne=T.getContent();R.pushRules=c.PushProcessor.rewriteDefaultRules(ne)}const X=A[T.getType()];return R.emit(s.ClientEvent.AccountData,T,X),T})}if(Array.isArray((H=z.to_device)===null||H===void 0?void 0:H.events)&&z.to_device.events.length>0){const C=[];z.to_device.events.filter(A=>{var T;return A.type===y.EventType.RoomMessageEncrypted&&!["m.olm.v1.curve25519-aes-sha2"].includes((T=A.content)===null||T===void 0?void 0:T.algorithm)?(f.logger.log("Ignoring invalid encrypted to-device event from "+A.sender),!1):!0}).map(R.getEventMapper({toDevice:!0})).map(A=>{if(A.getType()==="m.key.verification.cancel"){const T=A.getContent().transaction_id;T&&C.push(T)}return A}).forEach(function(A){const T=A.getContent();if(A.getType()=="m.room.message"&&T.msgtype=="m.bad.encrypted"){f.logger.log("Ignoring undecryptable to-device event from "+A.getSender());return}if(A.getType()==="m.key.verification.start"||A.getType()==="m.key.verification.request"){const X=T.transaction_id;C.includes(X)&&A.flagCancelled()}R.emit(s.ClientEvent.ToDeviceEvent,A)})}else this.catchingUp=!1;let P=[],K=[],U=[];if(z.rooms&&(z.rooms.invite&&(P=this.mapSyncResponseToRoomArray(z.rooms.invite)),z.rooms.join&&(K=this.mapSyncResponseToRoomArray(z.rooms.join)),z.rooms.leave&&(U=this.mapSyncResponseToRoomArray(z.rooms.leave))),this.notifEvents=[],await i.promiseMapSeries(P,async C=>{var A;const T=C.room,X=this.mapSyncEventsFormat(C.invite_state,T);await this.injectRoomEvents(T,X);const ne=(A=T.currentState.getStateEvents(y.EventType.RoomMember,R.getUserId()))===null||A===void 0?void 0:A.getSender();if(R.isCryptoEnabled()){const ae=await R.crypto.cryptoStore.takeParkedSharedHistory(T.roomId);for(const pe of ae)pe.senderId===ne&&await R.crypto.olmDevice.addInboundGroupSession(T.roomId,pe.senderKey,pe.forwardingCurve25519KeyChain,pe.sessionId,pe.sessionKey,pe.keysClaimed,!0,{sharedHistory:!0,untrusted:!0})}C.isBrandNewRoom?(T.recalculate(),R.store.storeRoom(T),R.emit(s.ClientEvent.Room,T)):T.recalculate(),X.forEach(function(ae){R.emit(s.ClientEvent.Event,ae)})}),await i.promiseMapSeries(K,async C=>{var A;const T=C.room,X=this.mapSyncEventsFormat(C.state,T),ne=this.mapSyncEventsFormat(C.timeline,T,!1),ae=this.mapSyncEventsFormat(C.ephemeral),pe=this.mapSyncEventsFormat(C.account_data),V=R.isRoomEncrypted(T.roomId);if(C.unread_notifications){var se;if(T.setUnreadNotificationCount(r.NotificationCountType.Total,(se=C.unread_notifications.notification_count)!==null&&se!==void 0?se:0),!V||T.getUnreadNotificationCount(r.NotificationCountType.Highlight)<=0){var Q;T.setUnreadNotificationCount(r.NotificationCountType.Highlight,(Q=C.unread_notifications.highlight_count)!==null&&Q!==void 0?Q:0)}}const j=(A=C[_.UNREAD_THREAD_NOTIFICATIONS.name])!==null&&A!==void 0?A:C[_.UNREAD_THREAD_NOTIFICATIONS.altName];if(j){T.resetThreadUnreadNotificationCount(Object.keys(j));for(const[ge,fe]of Object.entries(j)){var Z;T.setThreadUnreadNotificationCount(ge,r.NotificationCountType.Total,(Z=fe.notification_count)!==null&&Z!==void 0?Z:0);const he=T.getThreadUnreadNotificationCount(ge,r.NotificationCountType.Highlight)<=0;if(!V||V&&he){var te;T.setThreadUnreadNotificationCount(ge,r.NotificationCountType.Highlight,(te=fe.highlight_count)!==null&&te!==void 0?te:0)}}}else T.resetThreadUnreadNotificationCount();if(C.timeline=C.timeline||{},C.isBrandNewRoom)C.timeline.prev_batch!==null&&T.getLiveTimeline().setPaginationToken(C.timeline.prev_batch,a.EventTimeline.BACKWARDS);else if(C.timeline.limited){let ge=!0;for(let fe=ne.length-1;fe>=0;fe--){const he=ne[fe].getId();if(T.getTimelineForEvent(he)){M(`Already have event ${he} in limited sync - not resetting`),ge=!1,ne.splice(0,fe);break}}if(ge){var re;T.resetLiveTimeline(C.timeline.prev_batch,this.opts.canResetEntireTimeline(T.roomId)?null:(re=x.oldSyncToken)!==null&&re!==void 0?re:null),R.resetNotifTimelineSet()}}if(this.opts.crypto)for(const ge of X.concat(ne))ge.isState()&&ge.getType()===y.EventType.RoomEncryption&&ge.getStateKey()===""&&await this.opts.crypto.onCryptoEvent(T,ge);try{await this.injectRoomEvents(T,X,ne,x.fromCache)}catch(ge){f.logger.error(`Failed to process events on room ${T.roomId}:`,ge)}C.summary&&T.setSummary(C.summary),T.addEphemeralEvents(ae),T.addAccountData(pe),T.recalculate(),C.isBrandNewRoom&&(R.store.storeRoom(T),R.emit(s.ClientEvent.Room,T)),this.processEventsForNotifs(T,ne);const de=ge=>R.emit(s.ClientEvent.Event,ge);X.forEach(de),ne.forEach(de),ae.forEach(de),pe.forEach(de),T.decryptCriticalEvents()}),await i.promiseMapSeries(U,async C=>{const A=C.room,T=this.mapSyncEventsFormat(C.state,A),X=this.mapSyncEventsFormat(C.timeline,A),ne=this.mapSyncEventsFormat(C.account_data);await this.injectRoomEvents(A,T,X),A.addAccountData(ne),A.recalculate(),C.isBrandNewRoom&&(R.store.storeRoom(A),R.emit(s.ClientEvent.Room,A)),this.processEventsForNotifs(A,X),T.forEach(function(ae){R.emit(s.ClientEvent.Event,ae)}),X.forEach(function(ae){R.emit(s.ClientEvent.Event,ae)}),ne.forEach(function(ae){R.emit(s.ClientEvent.Event,ae)})}),x.oldSyncToken&&this.notifEvents.length&&(this.notifEvents.sort(function(C,A){return C.getTs()-A.getTs()}),this.notifEvents.forEach(function(C){var A;(A=R.getNotifTimelineSet())===null||A===void 0||A.addLiveEvent(C)})),z.device_lists&&this.opts.crypto&&await this.opts.crypto.handleDeviceListChanges(x,z.device_lists),this.opts.crypto&&z.device_one_time_keys_count){const C=z.device_one_time_keys_count.signed_curve25519||0;this.opts.crypto.updateOneTimeKeyCount(C)}if(this.opts.crypto&&(z.device_unused_fallback_key_types||z["org.matrix.msc2732.device_unused_fallback_key_types"])){const C=z.device_unused_fallback_key_types||z["org.matrix.msc2732.device_unused_fallback_key_types"];this.opts.crypto.setNeedsNewFallback(Array.isArray(C)&&!C.includes("signed_curve25519"))}}startKeepAlives(x){return x===void 0&&(x=2e3+Math.floor(Math.random()*5e3)),this.keepAliveTimer!==null&&clearTimeout(this.keepAliveTimer),x>0?this.keepAliveTimer=setTimeout(this.pokeKeepAlive.bind(this),x):this.pokeKeepAlive(),this.connectionReturnedDefer||(this.connectionReturnedDefer=i.defer()),this.connectionReturnedDefer.promise}pokeKeepAlive(x=!1){var z;const W=()=>{clearTimeout(this.keepAliveTimer),this.connectionReturnedDefer&&(this.connectionReturnedDefer.resolve(x),this.connectionReturnedDefer=void 0)};this.client.http.request(g.Method.Get,"/_matrix/client/versions",void 0,void 0,{prefix:"",localTimeoutMs:15*1e3,abortSignal:(z=this.abortController)===null||z===void 0?void 0:z.signal}).then(()=>{W()},F=>{F.httpStatus==400||F.httpStatus==404?this.keepAliveTimer=setTimeout(W,2e3):(x=!0,this.keepAliveTimer=setTimeout(this.pokeKeepAlive.bind(this,x),5e3+Math.floor(Math.random()*5e3)),this.updateSyncState(E.Error,{error:F}))})}mapSyncResponseToRoomArray(x){const z=this.client;return Object.keys(x).map(W=>{const F=x[W];let H=z.store.getRoom(W),R=!1;return H||(H=this.createRoom(W),R=!0),F.room=H,F.isBrandNewRoom=R,F})}mapSyncEventsFormat(x,z,W=!0){if(!x||!Array.isArray(x.events))return[];const F=this.client.getEventMapper({decrypt:W});return x.events.map(function(H){return z&&(H.room_id=z.roomId),F(H)})}resolveInvites(x){if(!x||!this.opts.resolveInvitesToProfiles)return;const z=this.client;x.getMembersWithMembership("invite").forEach(function(W){if(W.requestedProfileInfo)return;W.requestedProfileInfo=!0;const F=z.getUser(W.userId);let H;F?H=Promise.resolve({avatar_url:F.avatarUrl,displayname:F.displayName}):H=z.getProfileInfo(W.userId),H.then(function(R){const P=W.events.member;(P==null?void 0:P.getContent().membership)==="invite"&&(P.getContent().avatar_url=R.avatar_url,P.getContent().displayname=R.displayname,W.setMembershipEvent(P,x.currentState))},function(R){})})}async injectRoomEvents(x,z,W,F=!1){const H=x.getLiveTimeline(),R=H.getEvents().length==0;if(R){for(const P of z)this.client.getPushActionsForEvent(P);H.initialiseState(z,{timelineWasEmpty:R})}this.resolveInvites(x),x.recalculate(),R||(x.oldState.setStateEvents(z||[]),x.currentState.setStateEvents(z||[])),x.addLiveEvents(W||[],{fromCache:F,timelineWasEmpty:R}),this.client.processBeaconEvents(x,W)}processEventsForNotifs(x,z){if(this.client.getNotifTimelineSet())for(const F of z){var W;const H=this.client.getPushActionsForEvent(F);H!=null&&H.notify&&(W=H.tweaks)!==null&&W!==void 0&&W.highlight&&this.notifEvents.push(F)}}getGuestFilter(){return"{}"}updateSyncState(x,z){const W=this.syncState;this.syncState=x,this.syncStateData=z,this.client.emit(s.ClientEvent.Sync,this.syncState,W,z)}}Hr.SyncApi=B;function N(D,x){const z=new n.User(x);return D.reEmitter.reEmit(z,[n.UserEvent.AvatarUrl,n.UserEvent.DisplayName,n.UserEvent.Presence,n.UserEvent.CurrentlyActive,n.UserEvent.LastPresenceTs]),z}function G(D,x,z){const{timelineSupport:W}=D,F=new r.Room(x,D,D.getUserId(),{lazyLoadMembers:z.lazyLoadMembers,pendingEventOrdering:z.pendingEventOrdering,timelineSupport:W});return D.reEmitter.reEmit(F,[r.RoomEvent.Name,r.RoomEvent.Redaction,r.RoomEvent.RedactionCancelled,r.RoomEvent.Receipt,r.RoomEvent.Tags,r.RoomEvent.LocalEchoUpdated,r.RoomEvent.AccountData,r.RoomEvent.MyMembership,r.RoomEvent.Timeline,r.RoomEvent.TimelineReset,S.RoomStateEvent.Events,S.RoomStateEvent.Members,S.RoomStateEvent.NewMember,S.RoomStateEvent.Update,p.BeaconEvent.New,p.BeaconEvent.Update,p.BeaconEvent.Destroy,p.BeaconEvent.LivenessChange]),F.on(S.RoomStateEvent.NewMember,(H,R,P)=>{var K;P.user=(K=D.getUser(P.userId))!==null&&K!==void 0?K:void 0,D.reEmitter.reEmit(P,[m.RoomMemberEvent.Name,m.RoomMemberEvent.Typing,m.RoomMemberEvent.PowerLevel,m.RoomMemberEvent.Membership])}),F}return Hr}var nl={},M0;function OW(){if(M0)return nl;M0=1;var e=Ae;Object.defineProperty(nl,"__esModule",{value:!0}),nl.StubStore=void 0;var t=e(Ue);class n{constructor(){(0,t.default)(this,"accountData",{}),(0,t.default)(this,"fromToken",null)}isNewlyCreated(){return Promise.resolve(!0)}getSyncToken(){return this.fromToken}setSyncToken(i){this.fromToken=i}storeRoom(i){}getRoom(i){return null}getRooms(){return[]}removeRoom(i){}getRoomSummaries(){return[]}storeUser(i){}getUser(i){return null}getUsers(){return[]}scrollback(i,o){return[]}storeEvents(i,o,a,c){}storeFilter(i){}getFilter(i,o){return null}getFilterIdByName(i){return null}setFilterIdByName(i,o){}storeAccountDataEvents(i){}getAccountData(i){}setSyncData(i){return Promise.resolve()}wantsSave(){return!1}save(){}startup(){return Promise.resolve()}getSavedSync(){return Promise.resolve(null)}getSavedSyncToken(){return Promise.resolve(null)}deleteAllData(){return Promise.resolve()}getOutOfBandMembers(){return Promise.resolve(null)}setOutOfBandMembers(i,o){return Promise.resolve()}clearOutOfBandMembers(){return Promise.resolve()}getClientOptions(){return Promise.resolve(void 0)}storeClientOptions(i){return Promise.resolve()}async getPendingEvents(i){return[]}setPendingEvents(i,o){return Promise.resolve()}async saveToDeviceBatches(i){return Promise.resolve()}getOldestToDeviceBatch(){return Promise.resolve(null)}async removeToDeviceBatch(i){return Promise.resolve()}}return nl.StubStore=n,nl}var ot={},D0=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto<"u"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto),PW=new Uint8Array(16);function zP(){if(!D0)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return D0(PW)}var YP=[];for(var Nc=0;Nc<256;++Nc)YP[Nc]=(Nc+256).toString(16).substr(1);function Xy(e,t){var n=t||0,r=YP;return[r[e[n++]],r[e[n++]],r[e[n++]],r[e[n++]],"-",r[e[n++]],r[e[n++]],"-",r[e[n++]],r[e[n++]],"-",r[e[n++]],r[e[n++]],"-",r[e[n++]],r[e[n++]],r[e[n++]],r[e[n++]],r[e[n++]],r[e[n++]]].join("")}var A0,Rp,Ip=0,Cp=0;function kW(e,t,n){var r=t&&n||0,i=t||[];e=e||{};var o=e.node||A0,a=e.clockseq!==void 0?e.clockseq:Rp;if(o==null||a==null){var c=e.random||(e.rng||zP)();o==null&&(o=A0=[c[0]|1,c[1],c[2],c[3],c[4],c[5]]),a==null&&(a=Rp=(c[6]<<8|c[7])&16383)}var f=e.msecs!==void 0?e.msecs:new Date().getTime(),v=e.nsecs!==void 0?e.nsecs:Cp+1,s=f-Ip+(v-Cp)/1e4;if(s<0&&e.clockseq===void 0&&(a=a+1&16383),(s<0||f>Ip)&&e.nsecs===void 0&&(v=0),v>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");Ip=f,Cp=v,Rp=a,f+=122192928e5;var g=((f&268435455)*1e4+v)%4294967296;i[r++]=g>>>24&255,i[r++]=g>>>16&255,i[r++]=g>>>8&255,i[r++]=g&255;var y=f/4294967296*1e4&268435455;i[r++]=y>>>8&255,i[r++]=y&255,i[r++]=y>>>24&15|16,i[r++]=y>>>16&255,i[r++]=a>>>8|128,i[r++]=a&255;for(var S=0;S<6;++S)i[r+S]=o[S];return t||Xy(i)}function MW(e){var t=[];return e.replace(/[a-fA-F0-9]{2}/g,function(n){t.push(parseInt(n,16))}),t}function DW(e){e=unescape(encodeURIComponent(e));for(var t=new Array(e.length),n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}var AW="6ba7b810-9dad-11d1-80b4-00c04fd430c8",LW="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function QP(e,t,n){var r=function(o,a,c,f){var v=c&&f||0;if(typeof o=="string"&&(o=DW(o)),typeof a=="string"&&(a=MW(a)),!Array.isArray(o))throw TypeError("value must be an array of bytes");if(!Array.isArray(a)||a.length!==16)throw TypeError("namespace must be uuid string or an Array of 16 byte values");var s=n(a.concat(o));if(s[6]=s[6]&15|t,s[8]=s[8]&63|128,c)for(var g=0;g<16;++g)c[v+g]=s[g];return c||Xy(s)};try{r.name=e}catch{}return r.DNS=AW,r.URL=LW,r}function NW(e){if(typeof e=="string"){var t=unescape(encodeURIComponent(e));e=new Array(t.length);for(var n=0;n<t.length;n++)e[n]=t.charCodeAt(n)}return xW($W(UW(e),e.length*8))}function xW(e){var t,n,r=[],i=e.length*32,o="0123456789abcdef",a;for(t=0;t<i;t+=8)n=e[t>>5]>>>t%32&255,a=parseInt(o.charAt(n>>>4&15)+o.charAt(n&15),16),r.push(a);return r}function $W(e,t){e[t>>5]|=128<<t%32,e[(t+64>>>9<<4)+14]=t;var n,r,i,o,a,c=1732584193,f=-271733879,v=-1732584194,s=271733878;for(n=0;n<e.length;n+=16)r=c,i=f,o=v,a=s,c=zt(c,f,v,s,e[n],7,-680876936),s=zt(s,c,f,v,e[n+1],12,-389564586),v=zt(v,s,c,f,e[n+2],17,606105819),f=zt(f,v,s,c,e[n+3],22,-1044525330),c=zt(c,f,v,s,e[n+4],7,-176418897),s=zt(s,c,f,v,e[n+5],12,1200080426),v=zt(v,s,c,f,e[n+6],17,-1473231341),f=zt(f,v,s,c,e[n+7],22,-45705983),c=zt(c,f,v,s,e[n+8],7,1770035416),s=zt(s,c,f,v,e[n+9],12,-1958414417),v=zt(v,s,c,f,e[n+10],17,-42063),f=zt(f,v,s,c,e[n+11],22,-1990404162),c=zt(c,f,v,s,e[n+12],7,1804603682),s=zt(s,c,f,v,e[n+13],12,-40341101),v=zt(v,s,c,f,e[n+14],17,-1502002290),f=zt(f,v,s,c,e[n+15],22,1236535329),c=Yt(c,f,v,s,e[n+1],5,-165796510),s=Yt(s,c,f,v,e[n+6],9,-1069501632),v=Yt(v,s,c,f,e[n+11],14,643717713),f=Yt(f,v,s,c,e[n],20,-373897302),c=Yt(c,f,v,s,e[n+5],5,-701558691),s=Yt(s,c,f,v,e[n+10],9,38016083),v=Yt(v,s,c,f,e[n+15],14,-660478335),f=Yt(f,v,s,c,e[n+4],20,-405537848),c=Yt(c,f,v,s,e[n+9],5,568446438),s=Yt(s,c,f,v,e[n+14],9,-1019803690),v=Yt(v,s,c,f,e[n+3],14,-187363961),f=Yt(f,v,s,c,e[n+8],20,1163531501),c=Yt(c,f,v,s,e[n+13],5,-1444681467),s=Yt(s,c,f,v,e[n+2],9,-51403784),v=Yt(v,s,c,f,e[n+7],14,1735328473),f=Yt(f,v,s,c,e[n+12],20,-1926607734),c=Qt(c,f,v,s,e[n+5],4,-378558),s=Qt(s,c,f,v,e[n+8],11,-2022574463),v=Qt(v,s,c,f,e[n+11],16,1839030562),f=Qt(f,v,s,c,e[n+14],23,-35309556),c=Qt(c,f,v,s,e[n+1],4,-1530992060),s=Qt(s,c,f,v,e[n+4],11,1272893353),v=Qt(v,s,c,f,e[n+7],16,-155497632),f=Qt(f,v,s,c,e[n+10],23,-1094730640),c=Qt(c,f,v,s,e[n+13],4,681279174),s=Qt(s,c,f,v,e[n],11,-358537222),v=Qt(v,s,c,f,e[n+3],16,-722521979),f=Qt(f,v,s,c,e[n+6],23,76029189),c=Qt(c,f,v,s,e[n+9],4,-640364487),s=Qt(s,c,f,v,e[n+12],11,-421815835),v=Qt(v,s,c,f,e[n+15],16,530742520),f=Qt(f,v,s,c,e[n+2],23,-995338651),c=Jt(c,f,v,s,e[n],6,-198630844),s=Jt(s,c,f,v,e[n+7],10,1126891415),v=Jt(v,s,c,f,e[n+14],15,-1416354905),f=Jt(f,v,s,c,e[n+5],21,-57434055),c=Jt(c,f,v,s,e[n+12],6,1700485571),s=Jt(s,c,f,v,e[n+3],10,-1894986606),v=Jt(v,s,c,f,e[n+10],15,-1051523),f=Jt(f,v,s,c,e[n+1],21,-2054922799),c=Jt(c,f,v,s,e[n+8],6,1873313359),s=Jt(s,c,f,v,e[n+15],10,-30611744),v=Jt(v,s,c,f,e[n+6],15,-1560198380),f=Jt(f,v,s,c,e[n+13],21,1309151649),c=Jt(c,f,v,s,e[n+4],6,-145523070),s=Jt(s,c,f,v,e[n+11],10,-1120210379),v=Jt(v,s,c,f,e[n+2],15,718787259),f=Jt(f,v,s,c,e[n+9],21,-343485551),c=qi(c,r),f=qi(f,i),v=qi(v,o),s=qi(s,a);return[c,f,v,s]}function UW(e){var t,n=[];for(n[(e.length>>2)-1]=void 0,t=0;t<n.length;t+=1)n[t]=0;var r=e.length*8;for(t=0;t<r;t+=8)n[t>>5]|=(e[t/8]&255)<<t%32;return n}function qi(e,t){var n=(e&65535)+(t&65535),r=(e>>16)+(t>>16)+(n>>16);return r<<16|n&65535}function BW(e,t){return e<<t|e>>>32-t}function Wf(e,t,n,r,i,o){return qi(BW(qi(qi(t,e),qi(r,o)),i),n)}function zt(e,t,n,r,i,o,a){return Wf(t&n|~t&r,e,t,i,o,a)}function Yt(e,t,n,r,i,o,a){return Wf(t&r|n&~r,e,t,i,o,a)}function Qt(e,t,n,r,i,o,a){return Wf(t^n^r,e,t,i,o,a)}function Jt(e,t,n,r,i,o,a){return Wf(n^(t|~r),e,t,i,o,a)}var FW=QP("v3",48,NW);const KW=FW;function jW(e,t,n){var r=t&&n||0;typeof e=="string"&&(t=e==="binary"?new Array(16):null,e=null),e=e||{};var i=e.random||(e.rng||zP)();if(i[6]=i[6]&15|64,i[8]=i[8]&63|128,t)for(var o=0;o<16;++o)t[r+o]=i[o];return t||Xy(i)}function qW(e,t,n,r){switch(e){case 0:return t&n^~t&r;case 1:return t^n^r;case 2:return t&n^t&r^n&r;case 3:return t^n^r}}function Op(e,t){return e<<t|e>>>32-t}function VW(e){var t=[1518500249,1859775393,2400959708,3395469782],n=[1732584193,4023233417,2562383102,271733878,3285377520];if(typeof e=="string"){var r=unescape(encodeURIComponent(e));e=new Array(r.length);for(var i=0;i<r.length;i++)e[i]=r.charCodeAt(i)}e.push(128);for(var o=e.length/4+2,a=Math.ceil(o/16),c=new Array(a),i=0;i<a;i++){c[i]=new Array(16);for(var f=0;f<16;f++)c[i][f]=e[i*64+f*4]<<24|e[i*64+f*4+1]<<16|e[i*64+f*4+2]<<8|e[i*64+f*4+3]}c[a-1][14]=(e.length-1)*8/Math.pow(2,32),c[a-1][14]=Math.floor(c[a-1][14]),c[a-1][15]=(e.length-1)*8&4294967295;for(var i=0;i<a;i++){for(var v=new Array(80),s=0;s<16;s++)v[s]=c[i][s];for(var s=16;s<80;s++)v[s]=Op(v[s-3]^v[s-8]^v[s-14]^v[s-16],1);for(var g=n[0],y=n[1],S=n[2],m=n[3],p=n[4],s=0;s<80;s++){var _=Math.floor(s/20),u=Op(g,5)+qW(_,y,S,m)+p+t[_]+v[s]>>>0;p=m,m=S,S=Op(y,30)>>>0,y=g,g=u}n[0]=n[0]+g>>>0,n[1]=n[1]+y>>>0,n[2]=n[2]+S>>>0,n[3]=n[3]+m>>>0,n[4]=n[4]+p>>>0}return[n[0]>>24&255,n[0]>>16&255,n[0]>>8&255,n[0]&255,n[1]>>24&255,n[1]>>16&255,n[1]>>8&255,n[1]&255,n[2]>>24&255,n[2]>>16&255,n[2]>>8&255,n[2]&255,n[3]>>24&255,n[3]>>16&255,n[3]>>8&255,n[3]&255,n[4]>>24&255,n[4]>>16&255,n[4]>>8&255,n[4]&255]}var WW=QP("v5",80,VW);const HW=WW,GW=Object.freeze(Object.defineProperty({__proto__:null,v1:kW,v3:KW,v4:jW,v5:HW},Symbol.toStringTag,{value:"Module"})),zu=lf(GW);var kr={},Pp={},tf={},zW={get exports(){return tf},set exports(e){tf=e}},L0;function JP(){if(L0)return tf;L0=1;var e=zW.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(t){return t.encoding?"rtpmap:%d %s/%s/%s":t.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(t){return t.address!=null?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(t){return t.subtype!=null?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(t){return"extmap:%d"+(t.direction?"/%s":"%v")+(t["encrypt-uri"]?" %s":"%v")+" %s"+(t.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(t){return t.sessionConfig!=null?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(t){var n="candidate:%s %d %s %d %s %d typ %s";return n+=t.raddr!=null?" raddr %s rport %d":"%v%v",n+=t.tcptype!=null?" tcptype %s":"%v",t.generation!=null&&(n+=" generation %d"),n+=t["network-id"]!=null?" network-id %d":"%v",n+=t["network-cost"]!=null?" network-cost %d":"%v",n}},{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(t){var n="ssrc:%d";return t.attribute!=null&&(n+=" %s",t.value!=null&&(n+=":%s")),n}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(t){return t.maxMessageSize!=null?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(t){return t.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(t){return"imageattr:%s %s %s"+(t.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(t){return"simulcast:%s %s"+(t.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(t){return"ts-refclk:%s"+(t.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(t){var n="mediaclk:";return n+=t.id!=null?"id=%s %s":"%v%s",n+=t.mediaClockValue!=null?"=%s":"",n+=t.rateNumerator!=null?" rate=%s":"",n+=t.rateDenominator!=null?"/%s":"",n}},{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"]}]};return Object.keys(e).forEach(function(t){var n=e[t];n.forEach(function(r){r.reg||(r.reg=/(.*)/),r.format||(r.format="%s")})}),tf}var N0;function YW(){return N0||(N0=1,function(e){var t=function(c){return String(Number(c))===c?Number(c):c},n=function(c,f,v,s){if(s&&!v)f[s]=t(c[1]);else for(var g=0;g<v.length;g+=1)c[g+1]!=null&&(f[v[g]]=t(c[g+1]))},r=function(c,f,v){var s=c.name&&c.names;c.push&&!f[c.push]?f[c.push]=[]:s&&!f[c.name]&&(f[c.name]={});var g=c.push?{}:s?f[c.name]:f;n(v.match(c.reg),g,c.names,c.name),c.push&&f[c.push].push(g)},i=JP(),o=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(c){var f={},v=[],s=f;return c.split(/(\r\n|\r|\n)/).filter(o).forEach(function(g){var y=g[0],S=g.slice(2);y==="m"&&(v.push({rtp:[],fmtp:[]}),s=v[v.length-1]);for(var m=0;m<(i[y]||[]).length;m+=1){var p=i[y][m];if(p.reg.test(S))return r(p,s,S)}}),f.media=v,f};var a=function(c,f){var v=f.split(/=(.+)/,2);return v.length===2?c[v[0]]=t(v[1]):v.length===1&&f.length>1&&(c[v[0]]=void 0),c};e.parseParams=function(c){return c.split(/;\s?/).reduce(a,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(c){return c.toString().split(" ").map(Number)},e.parseRemoteCandidates=function(c){for(var f=[],v=c.split(" ").map(t),s=0;s<v.length;s+=3)f.push({component:v[s],ip:v[s+1],port:v[s+2]});return f},e.parseImageAttributes=function(c){return c.split(" ").map(function(f){return f.substring(1,f.length-1).split(",").reduce(a,{})})},e.parseSimulcastStreamList=function(c){return c.split(";").map(function(f){return f.split(",").map(function(v){var s,g=!1;return v[0]!=="~"?s=t(v):(s=t(v.substring(1,v.length)),g=!0),{scid:s,paused:g}})})}}(Pp)),Pp}var kp,x0;function QW(){if(x0)return kp;x0=1;var e=JP(),t=/%[sdv%]/g,n=function(a){var c=1,f=arguments,v=f.length;return a.replace(t,function(s){if(c>=v)return s;var g=f[c];switch(c+=1,s){case"%%":return"%";case"%s":return String(g);case"%d":return Number(g);case"%v":return""}})},r=function(a,c,f){var v=c.format instanceof Function?c.format(c.push?f:f[c.name]):c.format,s=[a+"="+v];if(c.names)for(var g=0;g<c.names.length;g+=1){var y=c.names[g];c.name?s.push(f[c.name][y]):s.push(f[c.names[g]])}else s.push(f[c.name]);return n.apply(null,s)},i=["v","o","s","i","u","e","p","c","b","t","r","z","a"],o=["i","c","b","a"];return kp=function(a,c){c=c||{},a.version==null&&(a.version=0),a.name==null&&(a.name=" "),a.media.forEach(function(g){g.payloads==null&&(g.payloads="")});var f=c.outerOrder||i,v=c.innerOrder||o,s=[];return f.forEach(function(g){e[g].forEach(function(y){y.name in a&&a[y.name]!=null?s.push(r(g,y,a)):y.push in a&&a[y.push]!=null&&a[y.push].forEach(function(S){s.push(r(g,y,S))})})}),a.media.forEach(function(g){s.push(r("m",e.m[0],g)),v.forEach(function(y){e[y].forEach(function(S){S.name in g&&g[S.name]!=null?s.push(r(y,S,g)):S.push in g&&g[S.push]!=null&&g[S.push].forEach(function(m){s.push(r(y,S,m))})})})}),s.join(`\r
     83 `)+`\r
     84 `},kp}var $0;function JW(){if($0)return kr;$0=1;var e=YW(),t=QW();return kr.write=t,kr.parse=e.parse,kr.parseParams=e.parseParams,kr.parseFmtpConfig=e.parseFmtpConfig,kr.parsePayloads=e.parsePayloads,kr.parseRemoteCandidates=e.parseRemoteCandidates,kr.parseImageAttributes=e.parseImageAttributes,kr.parseSimulcastStreamList=e.parseSimulcastStreamList,kr}var gs={},U0;function Yu(){if(U0)return gs;U0=1,Object.defineProperty(gs,"__esModule",{value:!0}),gs.randomLowercaseString=i,gs.randomString=r,gs.randomUppercaseString=o;const e="abcdefghijklmnopqrstuvwxyz",t="ABCDEFGHIJKLMNOPQRSTUVWXYZ",n="0123456789";function r(c){return a(c,t+e+n)}function i(c){return a(c,e)}function o(c){return a(c,t)}function a(c,f){let v="";for(let s=0;s<c;++s)v+=f.charAt(Math.floor(Math.random()*f.length));return v}return gs}var wi={},B0;function Zy(){if(B0)return wi;B0=1,Object.defineProperty(wi,"__esModule",{value:!0}),wi.SDPStreamMetadataPurpose=wi.SDPStreamMetadataKey=void 0;const e="org.matrix.msc3077.sdp_stream_metadata";wi.SDPStreamMetadataKey=e;let t;return wi.SDPStreamMetadataPurpose=t,function(n){n.Usermedia="m.usermedia",n.Screenshare="m.screenshare"}(t||(wi.SDPStreamMetadataPurpose=t={})),wi}var Mr={},So={},F0;function XW(){if(F0)return So;F0=1,Object.defineProperty(So,"__esModule",{value:!0}),So.releaseContext=So.acquireContext=void 0;let e=null,t=0;const n=()=>(e===null&&(e=new AudioContext),t++,e);So.acquireContext=n;const r=()=>{if(t--,t===0){var i;(i=e)===null||i===void 0||i.close(),e=null}};return So.releaseContext=r,So}var K0;function XP(){if(K0)return Mr;K0=1;var e=Ae;Object.defineProperty(Mr,"__esModule",{value:!0}),Mr.SPEAKING_THRESHOLD=Mr.CallFeedEvent=Mr.CallFeed=void 0;var t=e(Ue),n=Zy(),r=XW(),i=Ge(),o=Pt(),a=Ju();const c=200,f=-60;Mr.SPEAKING_THRESHOLD=f;const v=8;let s;Mr.CallFeedEvent=s,function(y){y.NewStream="new_stream",y.MuteStateChanged="mute_state_changed",y.LocalVolumeChanged="local_volume_changed",y.VolumeChanged="volume_changed",y.ConnectedChanged="connected_changed",y.Speaking="speaking",y.Disposed="disposed"}(s||(Mr.CallFeedEvent=s={}));class g extends o.TypedEventEmitter{constructor(S){super(),(0,t.default)(this,"stream",void 0),(0,t.default)(this,"sdpMetadataStreamId",void 0),(0,t.default)(this,"userId",void 0),(0,t.default)(this,"deviceId",void 0),(0,t.default)(this,"purpose",void 0),(0,t.default)(this,"speakingVolumeSamples",void 0),(0,t.default)(this,"client",void 0),(0,t.default)(this,"call",void 0),(0,t.default)(this,"roomId",void 0),(0,t.default)(this,"audioMuted",void 0),(0,t.default)(this,"videoMuted",void 0),(0,t.default)(this,"localVolume",1),(0,t.default)(this,"measuringVolumeActivity",!1),(0,t.default)(this,"audioContext",void 0),(0,t.default)(this,"analyser",void 0),(0,t.default)(this,"frequencyBinCount",void 0),(0,t.default)(this,"speakingThreshold",f),(0,t.default)(this,"speaking",!1),(0,t.default)(this,"volumeLooperTimeout",void 0),(0,t.default)(this,"_disposed",!1),(0,t.default)(this,"_connected",!1),(0,t.default)(this,"onAddTrack",()=>{this.emit(s.NewStream,this.stream)}),(0,t.default)(this,"onCallState",m=>{m===a.CallState.Connected?this.connected=!0:m===a.CallState.Connecting&&(this.connected=!1)}),(0,t.default)(this,"volumeLooper",()=>{if(!this.analyser||!this.measuringVolumeActivity)return;this.analyser.getFloatFrequencyData(this.frequencyBinCount);let m=-1/0;for(const _ of this.frequencyBinCount)_>m&&(m=_);this.speakingVolumeSamples.shift(),this.speakingVolumeSamples.push(m),this.emit(s.VolumeChanged,m);let p=!1;for(const _ of this.speakingVolumeSamples)if(_>this.speakingThreshold){p=!0;break}this.speaking!==p&&(this.speaking=p,this.emit(s.Speaking,this.speaking)),this.volumeLooperTimeout=setTimeout(this.volumeLooper,c)}),this.client=S.client,this.call=S.call,this.roomId=S.roomId,this.userId=S.userId,this.deviceId=S.deviceId,this.purpose=S.purpose,this.audioMuted=S.audioMuted,this.videoMuted=S.videoMuted,this.speakingVolumeSamples=new Array(v).fill(-1/0),this.sdpMetadataStreamId=S.stream.id,this.updateStream(null,S.stream),this.stream=S.stream,this.hasAudioTrack&&this.initVolumeMeasuring(),S.call&&(S.call.addListener(a.CallEvent.State,this.onCallState),this.onCallState(S.call.state))}get connected(){return this.isLocal()||this._connected}set connected(S){this._connected=S,this.emit(s.ConnectedChanged,this.connected)}get hasAudioTrack(){return this.stream.getAudioTracks().length>0}updateStream(S,m){m!==S&&(S&&(S.removeEventListener("addtrack",this.onAddTrack),this.measureVolumeActivity(!1)),this.stream=m,m.addEventListener("addtrack",this.onAddTrack),this.hasAudioTrack?this.initVolumeMeasuring():this.measureVolumeActivity(!1),this.emit(s.NewStream,this.stream))}initVolumeMeasuring(){if(!this.hasAudioTrack)return;this.audioContext||(this.audioContext=(0,r.acquireContext)()),this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=512,this.analyser.smoothingTimeConstant=.1,this.audioContext.createMediaStreamSource(this.stream).connect(this.analyser),this.frequencyBinCount=new Float32Array(this.analyser.frequencyBinCount)}getMember(){var S;const m=this.client.getRoom(this.roomId);return(S=m==null?void 0:m.getMember(this.userId))!==null&&S!==void 0?S:null}isLocal(){return this.userId===this.client.getUserId()&&(this.deviceId===void 0||this.deviceId===this.client.getDeviceId())}isAudioMuted(){return this.stream.getAudioTracks().length===0||this.audioMuted}isVideoMuted(){return this.stream.getVideoTracks().length===0||this.videoMuted}isSpeaking(){return this.speaking}setNewStream(S){this.updateStream(this.stream,S)}setAudioVideoMuted(S,m){S!==null&&(this.audioMuted!==S&&this.speakingVolumeSamples.fill(-1/0),this.audioMuted=S),m!==null&&(this.videoMuted=m),this.emit(s.MuteStateChanged,this.audioMuted,this.videoMuted)}measureVolumeActivity(S){if(S){if(!this.analyser||!this.frequencyBinCount||!this.hasAudioTrack)return;this.measuringVolumeActivity=!0,this.volumeLooper()}else this.measuringVolumeActivity=!1,this.speakingVolumeSamples.fill(-1/0),this.emit(s.VolumeChanged,-1/0)}setSpeakingThreshold(S){this.speakingThreshold=S}clone(){const S=this.client.getMediaHandler(),m=this.stream.clone();return i.logger.log(`callFeed cloning stream ${this.stream.id} newStream ${m.id}`),this.purpose===n.SDPStreamMetadataPurpose.Usermedia?S.userMediaStreams.push(m):S.screensharingStreams.push(m),new g({client:this.client,roomId:this.roomId,userId:this.userId,deviceId:this.deviceId,stream:m,purpose:this.purpose,audioMuted:this.audioMuted,videoMuted:this.videoMuted})}dispose(){var S,m;clearTimeout(this.volumeLooperTimeout),(S=this.stream)===null||S===void 0||S.removeEventListener("addtrack",this.onAddTrack),(m=this.call)===null||m===void 0||m.removeListener(a.CallEvent.State,this.onCallState),this.audioContext&&(this.audioContext=void 0,this.analyser=void 0,(0,r.releaseContext)()),this._disposed=!0,this.emit(s.Disposed)}get disposed(){return this._disposed}set disposed(S){this._disposed=S}getLocalVolume(){return this.localVolume}setLocalVolume(S){this.localVolume=S,this.emit(s.LocalVolumeChanged,S)}}return Mr.CallFeed=g,Mr}var rl={},j0;function Qu(){if(j0)return rl;j0=1;var e=Ae;Object.defineProperty(rl,"__esModule",{value:!0}),rl.DeviceInfo=void 0;var t=e(Ue),n;(function(i){i[i.Blocked=-1]="Blocked",i[i.Unverified=0]="Unverified",i[i.Verified=1]="Verified"})(n||(n={}));class r{static fromStorage(o,a){const c=new r(a);for(const f in o)o.hasOwnProperty(f)&&(c[f]=o[f]);return c}constructor(o){this.deviceId=o,(0,t.default)(this,"algorithms",[]),(0,t.default)(this,"keys",{}),(0,t.default)(this,"verified",n.Unverified),(0,t.default)(this,"known",!1),(0,t.default)(this,"unsigned",{}),(0,t.default)(this,"signatures",{})}toStorage(){return{algorithms:this.algorithms,keys:this.keys,verified:this.verified,known:this.known,unsigned:this.unsigned,signatures:this.signatures}}getFingerprint(){return this.keys["ed25519:"+this.deviceId]}getIdentityKey(){return this.keys["curve25519:"+this.deviceId]}getDisplayName(){return this.unsigned.device_display_name||null}isBlocked(){return this.verified==n.Blocked}isVerified(){return this.verified==n.Verified}isUnverified(){return this.verified==n.Unverified}isKnown(){return this.known===!0}}return rl.DeviceInfo=r,(0,t.default)(r,"DeviceVerification",{VERIFIED:n.Verified,UNVERIFIED:n.Unverified,BLOCKED:n.Blocked}),rl}var st={},bi={},q0;function ZP(){if(q0)return bi;q0=1;var e=Ae;Object.defineProperty(bi,"__esModule",{value:!0}),bi.CallEventHandlerEvent=bi.CallEventHandler=void 0;var t=e(Ue),n=Ge(),r=Ju(),i=xe,o=or(),a=Ca(),c=hi();const f=3e3;let v;bi.CallEventHandlerEvent=v,function(g){g.Incoming="Call.incoming"}(v||(bi.CallEventHandlerEvent=v={}));class s{constructor(y){(0,t.default)(this,"calls",void 0),(0,t.default)(this,"callEventBuffer",void 0),(0,t.default)(this,"nextSeqByCall",new Map),(0,t.default)(this,"toDeviceEventBuffers",new Map),(0,t.default)(this,"client",void 0),(0,t.default)(this,"candidateEventsByCall",void 0),(0,t.default)(this,"eventBufferPromiseChain",void 0),(0,t.default)(this,"onSync",()=>{const S=this.callEventBuffer;this.callEventBuffer=[],this.eventBufferPromiseChain?this.eventBufferPromiseChain=this.eventBufferPromiseChain.then(()=>this.evaluateEventBuffer(S)):this.eventBufferPromiseChain=this.evaluateEventBuffer(S)}),(0,t.default)(this,"onRoomTimeline",S=>{this.callEventBuffer.push(S)}),(0,t.default)(this,"onToDeviceEvent",S=>{const m=S.getContent();if(!m.call_id){this.callEventBuffer.push(S);return}if(this.nextSeqByCall.has(m.call_id)||this.nextSeqByCall.set(m.call_id,0),m.seq===void 0){this.callEventBuffer.push(S);return}const p=this.nextSeqByCall.get(m.call_id)||0;if(m.seq!==p){this.toDeviceEventBuffers.has(m.call_id)||this.toDeviceEventBuffers.set(m.call_id,[]);const _=this.toDeviceEventBuffers.get(m.call_id),u=_.findIndex(l=>l.getContent().seq>m.seq);u===-1?_.push(S):_.splice(u,0,S)}else{const _=m.call_id;this.callEventBuffer.push(S),this.nextSeqByCall.set(_,m.seq+1);const u=this.toDeviceEventBuffers.get(_);let l=u&&u.shift();for(;l&&l.getContent().seq===this.nextSeqByCall.get(_);)this.callEventBuffer.push(l),this.nextSeqByCall.set(_,l.getContent().seq+1),l=u.shift()}}),this.client=y,this.calls=new Map,this.callEventBuffer=[],this.candidateEventsByCall=new Map}start(){this.client.on(o.ClientEvent.Sync,this.onSync),this.client.on(c.RoomEvent.Timeline,this.onRoomTimeline),this.client.on(o.ClientEvent.ToDeviceEvent,this.onToDeviceEvent)}stop(){this.client.removeListener(o.ClientEvent.Sync,this.onSync),this.client.removeListener(c.RoomEvent.Timeline,this.onRoomTimeline),this.client.removeListener(o.ClientEvent.ToDeviceEvent,this.onToDeviceEvent)}async evaluateEventBuffer(y){await Promise.all(y.map(p=>this.client.decryptEventIfNeeded(p)));const S=y.filter(p=>{const _=p.getType();return _.startsWith("m.call.")||_.startsWith("org.matrix.call.")}),m=new Set;for(const p of S){const _=p.getType();(_===i.EventType.CallAnswer||_===i.EventType.CallHangup)&&m.add(p.getContent().call_id)}for(const p of S){const _=p.getType(),u=p.getContent().call_id;if(!(_===i.EventType.CallInvite&&m.has(u)))try{await this.handleCallEvent(p)}catch(l){n.logger.error("Caught exception handling call event",l)}}}async handleCallEvent(y){var S,m;this.client.emit(o.ClientEvent.ReceivedVoipEvent,y);const p=y.getContent(),_=y.getRoomId()||((S=this.client.groupCallEventHandler.getGroupCallById(p.conf_id))===null||S===void 0||(m=S.room)===null||m===void 0?void 0:m.roomId),u=p.conf_id,l=y.getType(),d=y.getSender();let h=p.call_id?this.calls.get(p.call_id):void 0,w,E;if(u){if(E=this.client.groupCallEventHandler.getGroupCallById(u),!E){n.logger.warn(`Cannot find a group call ${u} for event ${l}. Ignoring event.`);return}if(w=p.device_id,!w){n.logger.warn(`Cannot find a device id for ${d}. Ignoring event.`),E.emit(a.GroupCallEvent.Error,new a.GroupCallUnknownDeviceError(d));return}if(p.dest_session_id!==this.client.getSessionId()){n.logger.warn("Call event does not match current session id, ignoring.");return}}const I=d===this.client.credentials.userId&&(w===void 0||w===this.client.getDeviceId());if(_){if(l===i.EventType.CallInvite){var k,M;if(I||y.getLocalAge()>p.lifetime-f||h&&h.state===r.CallState.Ended||(h&&n.logger.log(`WARN: Already have a MatrixCall with id ${p.call_id} but got an invite. Clobbering.`),p.invitee&&p.invitee!==this.client.getUserId()))return;const G=((k=this.client.getTurnServersExpiry())!==null&&k!==void 0?k:0)-Date.now();if(n.logger.info("Current turn creds expire in "+G+" ms"),h=(M=(0,r.createNewMatrixCall)(this.client,_,{forceTURN:this.client.forceTURN,opponentDeviceId:w,groupCallId:u,opponentSessionId:p.sender_session_id}))!==null&&M!==void 0?M:void 0,!h){n.logger.log("Incoming call ID "+p.call_id+" but this client doesn't support WebRTC");return}h.callId=p.call_id;try{await h.initWithInvite(y)}catch(x){if(x instanceof r.CallError)if(x.code===a.GroupCallErrorCode.UnknownDevice){var L;(L=E)===null||L===void 0||L.emit(a.GroupCallEvent.Error,x)}else n.logger.error(x)}if(this.calls.set(h.callId,h),this.candidateEventsByCall.get(h.callId))for(const x of this.candidateEventsByCall.get(h.callId))h.onRemoteIceCandidatesReceived(x);let D;for(const x of this.calls.values()){var B;const z=[r.CallState.WaitLocalMedia,r.CallState.CreateOffer,r.CallState.InviteSent].includes(x.state);if(h.roomId===x.roomId&&x.direction===r.CallDirection.Outbound&&((B=h.getOpponentMember())===null||B===void 0?void 0:B.userId)===x.invitee&&z){D=x;break}}D?D.callId>h.callId?(n.logger.log("Glare detected: answering incoming call "+h.callId+" and canceling outgoing call "+D.callId),D.replacedBy(h)):(n.logger.log("Glare detected: rejecting incoming call "+h.callId+" and keeping outgoing call "+D.callId),h.hangup(r.CallErrorCode.Replaced,!0)):this.client.emit(v.Incoming,h);return}else if(l===i.EventType.CallCandidates){if(I)return;h?h.onRemoteIceCandidatesReceived(y):(this.candidateEventsByCall.has(p.call_id)||this.candidateEventsByCall.set(p.call_id,[]),this.candidateEventsByCall.get(p.call_id).push(y));return}else if([i.EventType.CallHangup,i.EventType.CallReject].includes(l)){if(h)h.state!==r.CallState.Ended&&(l===i.EventType.CallHangup?h.onHangupReceived(p):h.onRejectReceived(p),h.state===r.CallState.Ended&&this.calls.delete(p.call_id));else{var N;h=(N=(0,r.createNewMatrixCall)(this.client,_,{opponentDeviceId:w,opponentSessionId:p.sender_session_id}))!==null&&N!==void 0?N:void 0,h&&(h.callId=p.call_id,h.initWithHangup(y),this.calls.set(p.call_id,h))}return}if(!h||!h.hasPeerConnection){n.logger.info(`Discarding possible call event ${y.getId()} as we don't have a call/peerConn`,l);return}if(y.getContent().party_id!==h.ourPartyId)switch(l){case i.EventType.CallAnswer:I?h.state===r.CallState.Ringing&&h.onAnsweredElsewhere(p):h.onAnswerReceived(y);break;case i.EventType.CallSelectAnswer:h.onSelectAnswerReceived(y);break;case i.EventType.CallNegotiate:h.onNegotiateReceived(y);break;case i.EventType.CallAssertedIdentity:case i.EventType.CallAssertedIdentityPrefix:h.onAssertedIdentityReceived(y);break;case i.EventType.CallSDPStreamMetadataChanged:case i.EventType.CallSDPStreamMetadataChangedPrefix:h.onSDPStreamMetadataChangedReceived(y);break}}}}return bi.CallEventHandler=s,bi}var Ti={},V0;function ek(){if(V0)return Ti;V0=1;var e=Ae;Object.defineProperty(Ti,"__esModule",{value:!0}),Ti.GroupCallEventHandlerEvent=Ti.GroupCallEventHandler=void 0;var t=e(Ue),n=or(),r=Ca(),i=po(),o=Ge(),a=xe,c=Vf();let f;Ti.GroupCallEventHandlerEvent=f,function(s){s.Incoming="GroupCall.incoming",s.Outgoing="GroupCall.outgoing",s.Ended="GroupCall.ended",s.Participants="GroupCall.participants"}(f||(Ti.GroupCallEventHandlerEvent=f={}));class v{constructor(g){this.client=g,(0,t.default)(this,"groupCalls",new Map),(0,t.default)(this,"roomDeferreds",new Map),(0,t.default)(this,"onRoomsChanged",y=>{this.createGroupCallForRoom(y)}),(0,t.default)(this,"onRoomStateChanged",(y,S)=>{if(y.getType()===a.EventType.GroupCallPrefix){const p=y.getStateKey(),_=y.getContent(),u=this.groupCalls.get(S.roomId);!u&&!_["m.terminated"]?this.createGroupCallFromRoomStateEvent(y):u&&u.groupCallId===p?_["m.terminated"]?u.terminate(!1):_["m.type"]!==u.type&&o.logger.warn(`The group call type changed for room: ${S.roomId}. Changing the group call type is currently unsupported.`):u&&u.groupCallId!==p&&o.logger.warn(`Multiple group calls detected for room: ${S.roomId}. Multiple group calls are currently unsupported.`)}})}async start(){this.client.getSyncState()!==c.SyncState.Syncing&&(o.logger.debug("Waiting for client to start syncing..."),await new Promise(y=>{const S=()=>{if(this.client.getSyncState()===c.SyncState.Syncing)return this.client.off(n.ClientEvent.Sync,S),y()};this.client.on(n.ClientEvent.Sync,S)}));const g=this.client.getRooms();for(const y of g)this.createGroupCallForRoom(y);this.client.on(n.ClientEvent.Room,this.onRoomsChanged),this.client.on(i.RoomStateEvent.Events,this.onRoomStateChanged)}stop(){this.client.removeListener(i.RoomStateEvent.Events,this.onRoomStateChanged)}getRoomDeferred(g){let y=this.roomDeferreds.get(g);if(y===void 0){let S;y={prom:new Promise(m=>{S=m})},y.resolve=S,this.roomDeferreds.set(g,y)}return y}waitUntilRoomReadyForGroupCalls(g){return this.getRoomDeferred(g).prom}getGroupCallById(g){return[...this.groupCalls.values()].find(y=>y.groupCallId===g)}createGroupCallForRoom(g){const y=g.currentState.getStateEvents(a.EventType.GroupCallPrefix),S=y.sort((m,p)=>p.getTs()-m.getTs());for(const m of S)if(!m.getContent()["m.terminated"]){o.logger.debug(`Choosing group call ${m.getStateKey()} with TS ${m.getTs()} for room ${g.roomId} from ${y.length} possible calls.`),this.createGroupCallFromRoomStateEvent(m);break}o.logger.info("Group call event handler processed room",g.roomId),this.getRoomDeferred(g.roomId).resolve()}createGroupCallFromRoomStateEvent(g){const y=g.getRoomId(),S=g.getContent(),m=this.client.getRoom(y);if(!m){o.logger.warn(`Couldn't find room ${y} for GroupCall`);return}const p=g.getStateKey(),_=S["m.type"];if(!Object.values(r.GroupCallType).includes(_)){o.logger.warn(`Received invalid group call type ${_} for room ${y}.`);return}const u=S["m.intent"];if(!Object.values(r.GroupCallIntent).includes(u)){o.logger.warn(`Received invalid group call intent ${_} for room ${y}.`);return}const l=Boolean(S["io.element.ptt"]);let d;if(S!=null&&S.dataChannelsEnabled&&S!==null&&S!==void 0&&S.dataChannelOptions){const{ordered:w,maxPacketLifeTime:E,maxRetransmits:I,protocol:k}=S.dataChannelOptions;d={ordered:w,maxPacketLifeTime:E,maxRetransmits:I,protocol:k}}const h=new r.GroupCall(this.client,m,_,l,u,p,S==null?void 0:S.dataChannelsEnabled,d);return this.groupCalls.set(m.roomId,h),this.client.emit(f.Incoming,h),h}}return Ti.GroupCallEventHandler=v,Ti}var W0;function Ca(){if(W0)return st;W0=1;var e=Ae;Object.defineProperty(st,"__esModule",{value:!0}),st.OtherUserSpeakingError=st.GroupCallUnknownDeviceError=st.GroupCallType=st.GroupCallTerminationReason=st.GroupCallState=st.GroupCallIntent=st.GroupCallEvent=st.GroupCallErrorCode=st.GroupCallError=st.GroupCall=void 0;var t=e(Ue),n=Pt(),r=XP(),i=Ju(),o=po(),a=Ge(),c=rs(),f=Zy(),v=xe,s=ZP(),g=ek(),y=lt();function S(B,N){var G=Object.keys(B);if(Object.getOwnPropertySymbols){var D=Object.getOwnPropertySymbols(B);N&&(D=D.filter(function(x){return Object.getOwnPropertyDescriptor(B,x).enumerable})),G.push.apply(G,D)}return G}function m(B){for(var N=1;N<arguments.length;N++){var G=arguments[N]!=null?arguments[N]:{};N%2?S(Object(G),!0).forEach(function(D){(0,t.default)(B,D,G[D])}):Object.getOwnPropertyDescriptors?Object.defineProperties(B,Object.getOwnPropertyDescriptors(G)):S(Object(G)).forEach(function(D){Object.defineProperty(B,D,Object.getOwnPropertyDescriptor(G,D))})}return B}let p;st.GroupCallIntent=p,function(B){B.Ring="m.ring",B.Prompt="m.prompt",B.Room="m.room"}(p||(st.GroupCallIntent=p={}));let _;st.GroupCallType=_,function(B){B.Video="m.video",B.Voice="m.voice"}(_||(st.GroupCallType=_={}));let u;st.GroupCallTerminationReason=u,function(B){B.CallEnded="call_ended"}(u||(st.GroupCallTerminationReason=u={}));let l;st.GroupCallEvent=l,function(B){B.GroupCallStateChanged="group_call_state_changed",B.ActiveSpeakerChanged="active_speaker_changed",B.CallsChanged="calls_changed",B.UserMediaFeedsChanged="user_media_feeds_changed",B.ScreenshareFeedsChanged="screenshare_feeds_changed",B.LocalScreenshareStateChanged="local_screenshare_state_changed",B.LocalMuteStateChanged="local_mute_state_changed",B.ParticipantsChanged="participants_changed",B.Error="error"}(l||(st.GroupCallEvent=l={}));let d;st.GroupCallErrorCode=d,function(B){B.NoUserMedia="no_user_media",B.UnknownDevice="unknown_device",B.PlaceCallFailed="place_call_failed"}(d||(st.GroupCallErrorCode=d={}));class h extends Error{constructor(N,G,D){D?(super(G+": "+D),(0,t.default)(this,"code",void 0)):(super(G),(0,t.default)(this,"code",void 0)),this.code=N}}st.GroupCallError=h;class w extends h{constructor(N){super(d.UnknownDevice,"No device found for "+N),this.userId=N}}st.GroupCallUnknownDeviceError=w;class E extends Error{constructor(){super("Cannot unmute: another user is speaking")}}st.OtherUserSpeakingError=E;let I;st.GroupCallState=I,function(B){B.LocalCallFeedUninitialized="local_call_feed_uninitialized",B.InitializingLocalCallFeed="initializing_local_call_feed",B.LocalCallFeedInitialized="local_call_feed_initialized",B.Entered="entered",B.Ended="ended"}(I||(st.GroupCallState=I={}));const k=1e3*60*60;function M(B){var N;return((N=B.getOpponentMember())===null||N===void 0?void 0:N.userId)||B.invitee||null}class L extends n.TypedEventEmitter{constructor(N,G,D,x,z,W,F,H){var R,P;super(),this.client=N,this.room=G,this.type=D,this.isPtt=x,this.intent=z,this.dataChannelsEnabled=F,this.dataChannelOptions=H,(0,t.default)(this,"activeSpeakerInterval",1e3),(0,t.default)(this,"retryCallInterval",5e3),(0,t.default)(this,"participantTimeout",1e3*15),(0,t.default)(this,"pttMaxTransmitTime",1e3*20),(0,t.default)(this,"activeSpeaker",void 0),(0,t.default)(this,"localCallFeed",void 0),(0,t.default)(this,"localScreenshareFeed",void 0),(0,t.default)(this,"localDesktopCapturerSourceId",void 0),(0,t.default)(this,"userMediaFeeds",[]),(0,t.default)(this,"screenshareFeeds",[]),(0,t.default)(this,"groupCallId",void 0),(0,t.default)(this,"calls",new Map),(0,t.default)(this,"callHandlers",new Map),(0,t.default)(this,"activeSpeakerLoopInterval",void 0),(0,t.default)(this,"retryCallLoopInterval",void 0),(0,t.default)(this,"retryCallCounts",new Map),(0,t.default)(this,"reEmitter",void 0),(0,t.default)(this,"transmitTimer",null),(0,t.default)(this,"participantsExpirationTimer",null),(0,t.default)(this,"resendMemberStateTimer",null),(0,t.default)(this,"initWithAudioMuted",!1),(0,t.default)(this,"initWithVideoMuted",!1),(0,t.default)(this,"_state",I.LocalCallFeedUninitialized),(0,t.default)(this,"_participants",new Map),(0,t.default)(this,"_creationTs",null),(0,t.default)(this,"_enteredViaAnotherSession",!1),(0,t.default)(this,"onIncomingCall",K=>{var U;if(K.roomId!==this.room.roomId)return;if(K.state!==i.CallState.Ringing){a.logger.warn("Incoming call no longer in ringing state. Ignoring.");return}if(!K.groupCallId||K.groupCallId!==this.groupCallId){a.logger.log(`Incoming call with groupCallId ${K.groupCallId} ignored because it doesn't match the current group call`),K.reject();return}const C=K.getOpponentMember();if(C===void 0){a.logger.warn("Incoming call with no member. Ignoring.");return}const A=(U=this.calls.get(C))!==null&&U!==void 0?U:new Map,T=A.get(K.getOpponentDeviceId());(T==null?void 0:T.callId)!==K.callId&&(a.logger.log(`GroupCall: incoming call from ${C.userId} with ID ${K.callId}`),T&&this.disposeCall(T,i.CallErrorCode.Replaced),this.initCall(K),K.answerWithCallFeeds(this.getLocalFeeds().map(X=>X.clone())),A.set(K.getOpponentDeviceId(),K),this.calls.set(C,A),this.emit(l.CallsChanged,this.calls))}),(0,t.default)(this,"onRetryCallLoop",()=>{let K=!1;for(const[A,T]of this.participants){const X=this.calls.get(A);let ne=this.retryCallCounts.get(A);for(const[ae,pe]of T){var U,C;const V=X==null?void 0:X.get(ae),se=(U=(C=ne)===null||C===void 0?void 0:C.get(ae))!==null&&U!==void 0?U:0;(V==null?void 0:V.getOpponentSessionId())!==pe.sessionId&&this.wantsOutgoingCall(A.userId,ae)&&se<3&&(ne===void 0&&(ne=new Map,this.retryCallCounts.set(A,ne)),ne.set(ae,se+1),K=!0)}}K&&this.placeOutgoingCalls()}),(0,t.default)(this,"onCallFeedsChanged",K=>{const U=M(K),C=K.getOpponentDeviceId();if(!U)throw new Error("Cannot change call feeds without user id");const A=this.getUserMediaFeed(U,C),T=K.remoteUsermediaFeed;T!==A&&(!A&&T?this.addUserMediaFeed(T):A&&T?this.replaceUserMediaFeed(A,T):A&&!T&&this.removeUserMediaFeed(A));const ne=this.getScreenshareFeed(U,C),ae=K.remoteScreensharingFeed;ae!==ne&&(!ne&&ae?this.addScreenshareFeed(ae):ne&&ae?this.replaceScreenshareFeed(ne,ae):ne&&!ae&&this.removeScreenshareFeed(ne))}),(0,t.default)(this,"onCallStateChanged",(K,U,C)=>{const A=this.localCallFeed.isAudioMuted();K.localUsermediaStream&&K.isMicrophoneMuted()!==A&&K.setMicrophoneMuted(A);const T=this.localCallFeed.isVideoMuted();if(K.localUsermediaStream&&K.isLocalVideoMuted()!==T&&K.setLocalVideoMuted(T),U===i.CallState.Connected){const X=K.getOpponentMember(),ne=this.retryCallCounts.get(X);ne==null||ne.delete(K.getOpponentDeviceId()),(ne==null?void 0:ne.size)===0&&this.retryCallCounts.delete(X)}}),(0,t.default)(this,"onCallHangup",K=>{var U;if(K.hangupReason===i.CallErrorCode.Replaced)return;const C=(U=K.getOpponentMember())!==null&&U!==void 0?U:this.room.getMember(K.invitee),A=this.calls.get(C);(A==null?void 0:A.get(K.getOpponentDeviceId()))===K&&(this.disposeCall(K,K.hangupReason),A.delete(K.getOpponentDeviceId()),A.size===0&&this.calls.delete(C),this.emit(l.CallsChanged,this.calls))}),(0,t.default)(this,"onCallReplaced",(K,U)=>{const C=K.getOpponentMember();let A=this.calls.get(C);A===void 0&&(A=new Map,this.calls.set(C,A)),this.disposeCall(K,i.CallErrorCode.Replaced),this.initCall(U),A.set(K.getOpponentDeviceId(),U),this.emit(l.CallsChanged,this.calls)}),(0,t.default)(this,"onActiveSpeakerLoop",()=>{let K,U;for(const C of this.userMediaFeeds){if(C.isLocal()&&this.userMediaFeeds.length>1)continue;const T=C.speakingVolumeSamples.reduce((X,ne)=>X+Math.max(ne,r.SPEAKING_THRESHOLD))/C.speakingVolumeSamples.length;(!K||T>K)&&(K=T,U=C)}U&&this.activeSpeaker!==U&&K&&K>r.SPEAKING_THRESHOLD&&(this.activeSpeaker=U,this.emit(l.ActiveSpeakerChanged,this.activeSpeaker))}),(0,t.default)(this,"onRoomState",()=>this.updateParticipants()),(0,t.default)(this,"onParticipantsChanged",()=>{this.state===I.Entered&&this.placeOutgoingCalls()}),(0,t.default)(this,"onStateChanged",(K,U)=>{(K===I.Entered||U===I.Entered||K===I.Ended)&&(this.updateParticipants(),this.updateMemberState().catch(C=>a.logger.error("Failed to update member state devices",C)))}),(0,t.default)(this,"onLocalFeedsChanged",()=>{this.state===I.Entered&&this.updateMemberState().catch(K=>a.logger.error("Failed to update member state feeds",K))}),this.reEmitter=new c.ReEmitter(this),this.groupCallId=W??(0,i.genCallID)(),this.creationTs=(R=(P=G.currentState.getStateEvents(v.EventType.GroupCallPrefix,this.groupCallId))===null||P===void 0?void 0:P.getTs())!==null&&R!==void 0?R:null,this.updateParticipants(),G.on(o.RoomStateEvent.Update,this.onRoomState),this.on(l.ParticipantsChanged,this.onParticipantsChanged),this.on(l.GroupCallStateChanged,this.onStateChanged),this.on(l.LocalScreenshareStateChanged,this.onLocalFeedsChanged)}async create(){this.creationTs=Date.now(),this.client.groupCallEventHandler.groupCalls.set(this.room.roomId,this),this.client.emit(g.GroupCallEventHandlerEvent.Outgoing,this);const N={"m.intent":this.intent,"m.type":this.type,"io.element.ptt":this.isPtt,dataChannelsEnabled:this.dataChannelsEnabled,dataChannelOptions:this.dataChannelsEnabled?this.dataChannelOptions:void 0};return await this.client.sendStateEvent(this.room.roomId,v.EventType.GroupCallPrefix,N,this.groupCallId),this}get state(){return this._state}set state(N){const G=this._state;N!==G&&(this._state=N,this.emit(l.GroupCallStateChanged,N,G))}get participants(){return this._participants}set participants(N){const G=this._participants,D=(z,W)=>z.sessionId===W.sessionId&&z.screensharing===W.screensharing,x=(z,W)=>(0,y.mapsEqual)(z,W,D);(0,y.mapsEqual)(N,G,x)||(this._participants=N,this.emit(l.ParticipantsChanged,N))}get creationTs(){return this._creationTs}set creationTs(N){this._creationTs=N}get enteredViaAnotherSession(){return this._enteredViaAnotherSession}set enteredViaAnotherSession(N){this._enteredViaAnotherSession=N,this.updateParticipants()}forEachCall(N){for(const G of this.calls.values())for(const D of G.values())N(D)}getLocalFeeds(){const N=[];return this.localCallFeed&&N.push(this.localCallFeed),this.localScreenshareFeed&&N.push(this.localScreenshareFeed),N}hasLocalParticipant(){var N,G;return(N=(G=this.participants.get(this.room.getMember(this.client.getUserId())))===null||G===void 0?void 0:G.has(this.client.getDeviceId()))!==null&&N!==void 0?N:!1}async initLocalCallFeed(){if(a.logger.log(`groupCall ${this.groupCallId} initLocalCallFeed`),this.state!==I.LocalCallFeedUninitialized)throw new Error(`Cannot initialize local call feed in the "${this.state}" state.`);this.state=I.InitializingLocalCallFeed;let N,G=!1;const D=z=>{z===I.LocalCallFeedUninitialized&&(G=!0)};this.on(l.GroupCallStateChanged,D);try{N=await this.client.getMediaHandler().getUserMediaStream(!0,this.type===_.Video)}catch(z){throw this.state=I.LocalCallFeedUninitialized,z}finally{this.off(l.GroupCallStateChanged,D)}if(G)throw new Error("Group call disposed");const x=new r.CallFeed({client:this.client,roomId:this.room.roomId,userId:this.client.getUserId(),deviceId:this.client.getDeviceId(),stream:N,purpose:f.SDPStreamMetadataPurpose.Usermedia,audioMuted:this.initWithAudioMuted||N.getAudioTracks().length===0||this.isPtt,videoMuted:this.initWithVideoMuted||N.getVideoTracks().length===0});return(0,i.setTracksEnabled)(N.getAudioTracks(),!x.isAudioMuted()),(0,i.setTracksEnabled)(N.getVideoTracks(),!x.isVideoMuted()),this.localCallFeed=x,this.addUserMediaFeed(x),this.state=I.LocalCallFeedInitialized,x}async updateLocalUsermediaStream(N){if(this.localCallFeed){const G=this.localCallFeed.stream;this.localCallFeed.setNewStream(N);const D=this.localCallFeed.isAudioMuted(),x=this.localCallFeed.isVideoMuted();a.logger.log(`groupCall ${this.groupCallId} updateLocalUsermediaStream oldStream ${G.id} newStream ${N.id} micShouldBeMuted ${D} vidShouldBeMuted ${x}`),(0,i.setTracksEnabled)(N.getAudioTracks(),!D),(0,i.setTracksEnabled)(N.getVideoTracks(),!x),this.client.getMediaHandler().stopUserMediaStream(G)}}async enter(){if(this.state===I.LocalCallFeedUninitialized)await this.initLocalCallFeed();else if(this.state!==I.LocalCallFeedInitialized)throw new Error(`Cannot enter call in the "${this.state}" state`);a.logger.log(`Entered group call ${this.groupCallId}`),this.state=I.Entered,this.client.on(s.CallEventHandlerEvent.Incoming,this.onIncomingCall);for(const N of this.client.callEventHandler.calls.values())this.onIncomingCall(N);this.retryCallLoopInterval=setInterval(this.onRetryCallLoop,this.retryCallInterval),this.activeSpeaker=void 0,this.onActiveSpeakerLoop(),this.activeSpeakerLoopInterval=setInterval(this.onActiveSpeakerLoop,this.activeSpeakerInterval)}dispose(){this.localCallFeed&&(this.removeUserMediaFeed(this.localCallFeed),this.localCallFeed=void 0),this.localScreenshareFeed&&(this.client.getMediaHandler().stopScreensharingStream(this.localScreenshareFeed.stream),this.removeScreenshareFeed(this.localScreenshareFeed),this.localScreenshareFeed=void 0,this.localDesktopCapturerSourceId=void 0),this.client.getMediaHandler().stopAllStreams(),this.transmitTimer!==null&&(clearTimeout(this.transmitTimer),this.transmitTimer=null),this.retryCallLoopInterval!==void 0&&(clearInterval(this.retryCallLoopInterval),this.retryCallLoopInterval=void 0),this.state===I.Entered&&(this.forEachCall(N=>this.disposeCall(N,i.CallErrorCode.UserHangup)),this.calls.clear(),this.activeSpeaker=void 0,clearInterval(this.activeSpeakerLoopInterval),this.retryCallCounts.clear(),clearInterval(this.retryCallLoopInterval),this.client.removeListener(s.CallEventHandlerEvent.Incoming,this.onIncomingCall))}leave(){this.dispose(),this.state=I.LocalCallFeedUninitialized}async terminate(N=!0){if(this.dispose(),this.room.off(o.RoomStateEvent.Update,this.onRoomState),this.client.groupCallEventHandler.groupCalls.delete(this.room.roomId),this.client.emit(g.GroupCallEventHandlerEvent.Ended,this),this.state=I.Ended,N){const G=this.room.currentState.getStateEvents(v.EventType.GroupCallPrefix,this.groupCallId);await this.client.sendStateEvent(this.room.roomId,v.EventType.GroupCallPrefix,m(m({},G.getContent()),{},{"m.terminated":u.CallEnded}),this.groupCallId)}}isLocalVideoMuted(){return this.localCallFeed?this.localCallFeed.isVideoMuted():!0}isMicrophoneMuted(){return this.localCallFeed?this.localCallFeed.isAudioMuted():!0}async setMicrophoneMuted(N){if(!N&&!await this.client.getMediaHandler().hasAudioDevice())return!1;const G=!N&&this.isPtt;this.isPtt&&(!N&&this.isMicrophoneMuted()?this.transmitTimer=setTimeout(()=>{this.setMicrophoneMuted(!0)},this.pttMaxTransmitTime):N&&!this.isMicrophoneMuted()&&(this.transmitTimer!==null&&clearTimeout(this.transmitTimer),this.transmitTimer=null)),this.forEachCall(x=>{var z;return(z=x.localUsermediaFeed)===null||z===void 0?void 0:z.setAudioVideoMuted(N,null)});const D=async()=>{const x=[];this.forEachCall(z=>x.push(z.sendMetadataUpdate())),await Promise.all(x).catch(z=>a.logger.info("Failed to send some metadata updates",z))};return G&&await D(),this.localCallFeed?(a.logger.log(`groupCall ${this.groupCallId} setMicrophoneMuted stream ${this.localCallFeed.stream.id} muted ${N}`),this.localCallFeed.setAudioVideoMuted(N,null),(0,i.setTracksEnabled)(this.localCallFeed.stream.getAudioTracks(),!N)):(a.logger.log(`groupCall ${this.groupCallId} setMicrophoneMuted no stream muted ${N}`),this.initWithAudioMuted=N),this.forEachCall(x=>(0,i.setTracksEnabled)(x.localUsermediaFeed.stream.getAudioTracks(),!N)),this.emit(l.LocalMuteStateChanged,N,this.isLocalVideoMuted()),G||await D(),!0}async setLocalVideoMuted(N){if(!N&&!await this.client.getMediaHandler().hasVideoDevice())return!1;this.localCallFeed?(a.logger.log(`groupCall ${this.groupCallId} setLocalVideoMuted stream ${this.localCallFeed.stream.id} muted ${N}`),this.localCallFeed.setAudioVideoMuted(null,N),(0,i.setTracksEnabled)(this.localCallFeed.stream.getVideoTracks(),!N)):(a.logger.log(`groupCall ${this.groupCallId} setLocalVideoMuted no stream muted ${N}`),this.initWithVideoMuted=N);const G=[];return this.forEachCall(D=>G.push(D.setLocalVideoMuted(N))),await Promise.all(G),this.emit(l.LocalMuteStateChanged,this.isMicrophoneMuted(),N),!0}async setScreensharingEnabled(N,G={}){if(N===this.isScreensharing())return N;if(N)try{a.logger.log("Asking for screensharing permissions...");const D=await this.client.getMediaHandler().getScreensharingStream(G);for(const x of D.getTracks()){const z=()=>{this.setScreensharingEnabled(!1),x.removeEventListener("ended",z)};x.addEventListener("ended",z)}return a.logger.log("Screensharing permissions granted. Setting screensharing enabled on all calls"),this.localDesktopCapturerSourceId=G.desktopCapturerSourceId,this.localScreenshareFeed=new r.CallFeed({client:this.client,roomId:this.room.roomId,userId:this.client.getUserId(),deviceId:this.client.getDeviceId(),stream:D,purpose:f.SDPStreamMetadataPurpose.Screenshare,audioMuted:!1,videoMuted:!1}),this.addScreenshareFeed(this.localScreenshareFeed),this.emit(l.LocalScreenshareStateChanged,!0,this.localScreenshareFeed,this.localDesktopCapturerSourceId),this.forEachCall(x=>x.pushLocalFeed(this.localScreenshareFeed.clone())),!0}catch(D){if(G.throwOnFail)throw D;return a.logger.error("Enabling screensharing error",D),this.emit(l.Error,new h(d.NoUserMedia,"Failed to get screen-sharing stream: ",D)),!1}else return this.forEachCall(D=>{D.localScreensharingFeed&&D.removeLocalFeed(D.localScreensharingFeed)}),this.client.getMediaHandler().stopScreensharingStream(this.localScreenshareFeed.stream),this.removeScreenshareFeed(this.localScreenshareFeed),this.localScreenshareFeed=void 0,this.localDesktopCapturerSourceId=void 0,this.emit(l.LocalScreenshareStateChanged,!1,void 0,void 0),!1}isScreensharing(){return!!this.localScreenshareFeed}wantsOutgoingCall(N,G){const D=this.client.getUserId(),x=this.client.getDeviceId();return N>=D&&(N!==D||G>x)}placeOutgoingCalls(){let N=!1;for(const[D,x]of this.participants){var G;const z=(G=this.calls.get(D))!==null&&G!==void 0?G:new Map;for(const[W,F]of x){const H=z.get(W);if((H==null?void 0:H.getOpponentSessionId())!==F.sessionId&&this.wantsOutgoingCall(D.userId,W)){N=!0,H!==void 0&&(a.logger.debug(`Replacing call ${H.callId} to ${D.userId} ${W}`),this.disposeCall(H,i.CallErrorCode.NewSession));const R=(0,i.createNewMatrixCall)(this.client,this.room.roomId,{invitee:D.userId,opponentDeviceId:W,opponentSessionId:F.sessionId,groupCallId:this.groupCallId});R===null?(a.logger.error(`Failed to create call with ${D.userId} ${W}`),z.delete(W)):(this.initCall(R),z.set(W,R),a.logger.debug(`Placing call to ${D.userId} ${W} (session ${F.sessionId})`),R.placeCallWithCallFeeds(this.getLocalFeeds().map(P=>P.clone()),F.screensharing).then(()=>{this.dataChannelsEnabled&&R.createDataChannel("datachannel",this.dataChannelOptions)}).catch(P=>{a.logger.warn(`Failed to place call to ${D.userId}`,P),P instanceof i.CallError&&P.code===d.UnknownDevice?this.emit(l.Error,P):this.emit(l.Error,new h(d.PlaceCallFailed,`Failed to place call to ${D.userId}`)),this.disposeCall(R,i.CallErrorCode.SignallingFailed),z.get(W)===R&&z.delete(W)}))}}z.size>0?this.calls.set(D,z):this.calls.delete(D)}N&&this.emit(l.CallsChanged,this.calls)}getMemberStateEvents(N){return N===void 0?this.room.currentState.getStateEvents(v.EventType.GroupCallMemberPrefix):this.room.currentState.getStateEvents(v.EventType.GroupCallMemberPrefix,N)}initCall(N){const G=M(N);if(!G)throw new Error("Cannot init call without user id");const D=()=>this.onCallFeedsChanged(N),x=(H,R)=>this.onCallStateChanged(N,H,R),z=this.onCallHangup,W=H=>this.onCallReplaced(N,H);let F=this.callHandlers.get(G);F===void 0&&(F=new Map,this.callHandlers.set(G,F)),F.set(N.getOpponentDeviceId(),{onCallFeedsChanged:D,onCallStateChanged:x,onCallHangup:z,onCallReplaced:W}),N.on(i.CallEvent.FeedsChanged,D),N.on(i.CallEvent.State,x),N.on(i.CallEvent.Hangup,z),N.on(i.CallEvent.Replaced,W),N.isPtt=this.isPtt,this.reEmitter.reEmit(N,Object.values(i.CallEvent)),D()}disposeCall(N,G){const D=M(N),x=N.getOpponentDeviceId();if(!D)throw new Error("Cannot dispose call without user id");const z=this.callHandlers.get(D),{onCallFeedsChanged:W,onCallStateChanged:F,onCallHangup:H,onCallReplaced:R}=z.get(x);if(N.removeListener(i.CallEvent.FeedsChanged,W),N.removeListener(i.CallEvent.State,F),N.removeListener(i.CallEvent.Hangup,H),N.removeListener(i.CallEvent.Replaced,R),z.delete(D),z.size===0&&this.callHandlers.delete(D),N.hangupReason===i.CallErrorCode.Replaced)return;N.state!==i.CallState.Ended&&N.hangup(G,!1);const P=this.getUserMediaFeed(D,x);P&&this.removeUserMediaFeed(P);const K=this.getScreenshareFeed(D,x);K&&this.removeScreenshareFeed(K)}getUserMediaFeed(N,G){return this.userMediaFeeds.find(D=>D.userId===N&&D.deviceId===G)}addUserMediaFeed(N){this.userMediaFeeds.push(N),N.measureVolumeActivity(!0),this.emit(l.UserMediaFeedsChanged,this.userMediaFeeds)}replaceUserMediaFeed(N,G){const D=this.userMediaFeeds.findIndex(x=>x.userId===N.userId&&x.deviceId===N.deviceId);if(D===-1)throw new Error("Couldn't find user media feed to replace");this.userMediaFeeds.splice(D,1,G),N.dispose(),G.measureVolumeActivity(!0),this.emit(l.UserMediaFeedsChanged,this.userMediaFeeds)}removeUserMediaFeed(N){const G=this.userMediaFeeds.findIndex(D=>D.userId===N.userId&&D.deviceId===N.deviceId);if(G===-1)throw new Error("Couldn't find user media feed to remove");this.userMediaFeeds.splice(G,1),N.dispose(),this.emit(l.UserMediaFeedsChanged,this.userMediaFeeds),this.activeSpeaker===N&&(this.activeSpeaker=this.userMediaFeeds[0],this.emit(l.ActiveSpeakerChanged,this.activeSpeaker))}getScreenshareFeed(N,G){return this.screenshareFeeds.find(D=>D.userId===N&&D.deviceId===G)}addScreenshareFeed(N){this.screenshareFeeds.push(N),this.emit(l.ScreenshareFeedsChanged,this.screenshareFeeds)}replaceScreenshareFeed(N,G){const D=this.screenshareFeeds.findIndex(x=>x.userId===N.userId&&x.deviceId===N.deviceId);if(D===-1)throw new Error("Couldn't find screenshare feed to replace");this.screenshareFeeds.splice(D,1,G),N.dispose(),this.emit(l.ScreenshareFeedsChanged,this.screenshareFeeds)}removeScreenshareFeed(N){const G=this.screenshareFeeds.findIndex(D=>D.userId===N.userId&&D.deviceId===N.deviceId);if(G===-1)throw new Error("Couldn't find screenshare feed to remove");this.screenshareFeeds.splice(G,1),N.dispose(),this.emit(l.ScreenshareFeedsChanged,this.screenshareFeeds)}updateParticipants(){if(this.participantsExpirationTimer!==null&&(clearTimeout(this.participantsExpirationTimer),this.participantsExpirationTimer=null),this.state===I.Ended){this.participants=new Map;return}const N=new Map,G=Date.now(),D=this.state===I.Entered||this.enteredViaAnotherSession;let x=1/0;for(const z of this.getMemberStateEvents()){const W=this.room.getMember(z.getStateKey()),F=z.getContent(),R=(Array.isArray(F["m.calls"])?F["m.calls"]:[]).find(U=>U["m.call_id"]===this.groupCallId);let K=(Array.isArray(R==null?void 0:R["m.devices"])?R["m.devices"]:[]).filter(U=>typeof U.device_id=="string"&&typeof U.session_id=="string"&&typeof U.expires_ts=="number"&&U.expires_ts>G&&Array.isArray(U.feeds));if(!D&&(W==null?void 0:W.userId)===this.client.getUserId()&&(K=K.filter(U=>U.device_id!==this.client.getDeviceId())),K.length>0&&(W==null?void 0:W.membership)==="join"){const U=new Map;N.set(W,U);for(const C of K)U.set(C.device_id,{sessionId:C.session_id,screensharing:C.feeds.some(A=>A.purpose===f.SDPStreamMetadataPurpose.Screenshare)}),C.expires_ts<x&&(x=C.expires_ts)}}if(D){const z=this.room.getMember(this.client.getUserId());let W=N.get(z);W===void 0&&(W=new Map,N.set(z,W)),W.has(this.client.getDeviceId())||W.set(this.client.getDeviceId(),{sessionId:this.client.getSessionId(),screensharing:this.getLocalFeeds().some(F=>F.purpose===f.SDPStreamMetadataPurpose.Screenshare)})}this.participants=N,x<1/0&&(this.participantsExpirationTimer=setTimeout(()=>this.updateParticipants(),x-G))}async updateDevices(N,G=!1){var D;const x=Date.now(),z=this.client.getUserId(),W=this.getMemberStateEvents(z),F=(D=W==null?void 0:W.getContent())!==null&&D!==void 0?D:{},H=Array.isArray(F["m.calls"])?F["m.calls"]:[];let R=null;const P=[];for(const X of H)X["m.call_id"]===this.groupCallId?R=X:P.push(X);R===null&&(R={});const U=(Array.isArray(R["m.devices"])?R["m.devices"]:[]).filter(X=>typeof X.device_id=="string"&&typeof X.session_id=="string"&&typeof X.expires_ts=="number"&&X.expires_ts>x&&Array.isArray(X.feeds)),C=N(U);if(C===null)return;const A=[...P];C.length>0&&A.push(m(m({},R),{},{"m.call_id":this.groupCallId,"m.devices":C}));const T={"m.calls":A};await this.client.sendStateEvent(this.room.roomId,v.EventType.GroupCallMemberPrefix,T,z,{keepAlive:G})}async addDeviceToMemberState(){await this.updateDevices(N=>[...N.filter(G=>G.device_id!==this.client.getDeviceId()),{device_id:this.client.getDeviceId(),session_id:this.client.getSessionId(),expires_ts:Date.now()+k,feeds:this.getLocalFeeds().map(G=>({purpose:G.purpose}))}])}async updateMemberState(){this.resendMemberStateTimer!==null&&(clearInterval(this.resendMemberStateTimer),this.resendMemberStateTimer=null),this.state===I.Entered?(await this.addDeviceToMemberState(),this.resendMemberStateTimer=setInterval(async()=>{a.logger.log("Resending call member state");try{await this.addDeviceToMemberState()}catch(N){a.logger.error("Failed to resend call member state",N)}},k*3/4)):await this.updateDevices(N=>N.filter(G=>G.device_id!==this.client.getDeviceId()),!0)}async cleanMemberState(){const{devices:N}=await this.client.getDevices(),G=new Map(N.map(D=>[D.device_id,D]));await this.updateDevices(D=>{const x=D.filter(z=>{const W=G.get(z.device_id);return(W==null?void 0:W.last_seen_ts)!==void 0&&!(z.device_id===this.client.getDeviceId()&&this.state!==I.Entered&&!this.enteredViaAnotherSession)});return x.length===D.length?null:x})}}return st.GroupCall=L,st}var H0;function Ju(){if(H0)return ot;H0=1;var e=Ae;Object.defineProperty(ot,"__esModule",{value:!0}),ot.MatrixCall=ot.CallType=ot.CallState=ot.CallParty=ot.CallEvent=ot.CallErrorCode=ot.CallError=ot.CallDirection=void 0,ot.createNewMatrixCall=K,ot.genCallID=z,ot.setTracksEnabled=R,ot.supportsMatrixCall=P;var t=e(Ue),n=zu,r=JW(),i=Ge(),o=p(lt()),a=xe,c=Yu(),f=Zy(),v=XP(),s=Pt(),g=Qu(),y=Ca(),S=Rr;function m(U){if(typeof WeakMap!="function")return null;var C=new WeakMap,A=new WeakMap;return(m=function(T){return T?A:C})(U)}function p(U,C){if(!C&&U&&U.__esModule)return U;if(U===null||typeof U!="object"&&typeof U!="function")return{default:U};var A=m(C);if(A&&A.has(U))return A.get(U);var T={},X=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var ne in U)if(ne!=="default"&&Object.prototype.hasOwnProperty.call(U,ne)){var ae=X?Object.getOwnPropertyDescriptor(U,ne):null;ae&&(ae.get||ae.set)?Object.defineProperty(T,ne,ae):T[ne]=U[ne]}return T.default=U,A&&A.set(U,T),T}function _(U,C){var A=Object.keys(U);if(Object.getOwnPropertySymbols){var T=Object.getOwnPropertySymbols(U);C&&(T=T.filter(function(X){return Object.getOwnPropertyDescriptor(U,X).enumerable})),A.push.apply(A,T)}return A}function u(U){for(var C=1;C<arguments.length;C++){var A=arguments[C]!=null?arguments[C]:{};C%2?_(Object(A),!0).forEach(function(T){(0,t.default)(U,T,A[T])}):Object.getOwnPropertyDescriptors?Object.defineProperties(U,Object.getOwnPropertyDescriptors(A)):_(Object(A)).forEach(function(T){Object.defineProperty(U,T,Object.getOwnPropertyDescriptor(A,T))})}return U}var l;(function(U){U.AUDIO="audio",U.VIDEO="video"})(l||(l={}));var d;(function(U){U.OPUS="opus"})(d||(d={}));let h;ot.CallState=h,function(U){U.Fledgling="fledgling",U.InviteSent="invite_sent",U.WaitLocalMedia="wait_local_media",U.CreateOffer="create_offer",U.CreateAnswer="create_answer",U.Connecting="connecting",U.Connected="connected",U.Ringing="ringing",U.Ended="ended"}(h||(ot.CallState=h={}));let w;ot.CallType=w,function(U){U.Voice="voice",U.Video="video"}(w||(ot.CallType=w={}));let E;ot.CallDirection=E,function(U){U.Inbound="inbound",U.Outbound="outbound"}(E||(ot.CallDirection=E={}));let I;ot.CallParty=I,function(U){U.Local="local",U.Remote="remote"}(I||(ot.CallParty=I={}));let k;ot.CallEvent=k,function(U){U.Hangup="hangup",U.State="state",U.Error="error",U.Replaced="replaced",U.LocalHoldUnhold="local_hold_unhold",U.RemoteHoldUnhold="remote_hold_unhold",U.HoldUnhold="hold_unhold",U.FeedsChanged="feeds_changed",U.AssertedIdentityChanged="asserted_identity_changed",U.LengthChanged="length_changed",U.DataChannel="datachannel",U.SendVoipEvent="send_voip_event"}(k||(ot.CallEvent=k={}));let M;ot.CallErrorCode=M,function(U){U.UserHangup="user_hangup",U.LocalOfferFailed="local_offer_failed",U.NoUserMedia="no_user_media",U.UnknownDevices="unknown_devices",U.SendInvite="send_invite",U.CreateAnswer="create_answer",U.CreateOffer="create_offer",U.SendAnswer="send_answer",U.SetRemoteDescription="set_remote_description",U.SetLocalDescription="set_local_description",U.AnsweredElsewhere="answered_elsewhere",U.IceFailed="ice_failed",U.InviteTimeout="invite_timeout",U.Replaced="replaced",U.SignallingFailed="signalling_timeout",U.UserBusy="user_busy",U.Transfered="transferred",U.NewSession="new_session"}(M||(ot.CallErrorCode=M={}));const L="1",B="stun:turn.matrix.org",N=60*1e3,G=1e3,D=30*1e3;class x extends Error{constructor(C,A,T){super(A+": "+T),(0,t.default)(this,"code",void 0),this.code=C}}ot.CallError=x;function z(){return Date.now().toString()+(0,c.randomString)(16)}function W(U){return[{mediaType:"audio",codec:"opus",enableDtx:!0,maxAverageBitrate:U?12e3:void 0}]}function F(U,C){return U+":"+C}class H extends s.TypedEventEmitter{constructor(C){var A;if(super(),(0,t.default)(this,"roomId",void 0),(0,t.default)(this,"callId",void 0),(0,t.default)(this,"invitee",void 0),(0,t.default)(this,"hangupParty",void 0),(0,t.default)(this,"hangupReason",void 0),(0,t.default)(this,"direction",void 0),(0,t.default)(this,"ourPartyId",void 0),(0,t.default)(this,"peerConn",void 0),(0,t.default)(this,"toDeviceSeq",0),(0,t.default)(this,"isPtt",!1),(0,t.default)(this,"_state",h.Fledgling),(0,t.default)(this,"client",void 0),(0,t.default)(this,"forceTURN",void 0),(0,t.default)(this,"turnServers",void 0),(0,t.default)(this,"candidateSendQueue",[]),(0,t.default)(this,"candidateSendTries",0),(0,t.default)(this,"candidatesEnded",!1),(0,t.default)(this,"feeds",[]),(0,t.default)(this,"transceivers",new Map),(0,t.default)(this,"inviteOrAnswerSent",!1),(0,t.default)(this,"waitForLocalAVStream",!1),(0,t.default)(this,"successor",void 0),(0,t.default)(this,"opponentMember",void 0),(0,t.default)(this,"opponentVersion",void 0),(0,t.default)(this,"opponentPartyId",void 0),(0,t.default)(this,"opponentCaps",void 0),(0,t.default)(this,"iceDisconnectedTimeout",void 0),(0,t.default)(this,"inviteTimeout",void 0),(0,t.default)(this,"removeTrackListeners",new Map),(0,t.default)(this,"remoteOnHold",!1),(0,t.default)(this,"callStatsAtEnd",void 0),(0,t.default)(this,"makingOffer",!1),(0,t.default)(this,"ignoreOffer",!1),(0,t.default)(this,"responsePromiseChain",void 0),(0,t.default)(this,"remoteCandidateBuffer",new Map),(0,t.default)(this,"remoteAssertedIdentity",void 0),(0,t.default)(this,"remoteSDPStreamMetadata",void 0),(0,t.default)(this,"callLengthInterval",void 0),(0,t.default)(this,"callStartTime",void 0),(0,t.default)(this,"opponentDeviceId",void 0),(0,t.default)(this,"opponentDeviceInfo",void 0),(0,t.default)(this,"opponentSessionId",void 0),(0,t.default)(this,"groupCallId",void 0),(0,t.default)(this,"gotLocalIceCandidate",T=>{if(T.candidate){if(this.candidatesEnded){i.logger.warn("Got candidate after candidates have ended - ignoring!");return}if(i.logger.debug("Call "+this.callId+" got local ICE "+T.candidate.sdpMid+" candidate: "+T.candidate.candidate),this.callHasEnded())return;T.candidate.candidate===""?this.queueCandidate(null):this.queueCandidate(T.candidate)}}),(0,t.default)(this,"onIceGatheringStateChange",T=>{var X;i.logger.debug(`Call ${this.callId} ice gathering state changed to  ${this.peerConn.iceGatheringState}`),((X=this.peerConn)===null||X===void 0?void 0:X.iceGatheringState)==="complete"&&this.queueCandidate(null)}),(0,t.default)(this,"getLocalOfferFailed",T=>{i.logger.error(`Call ${this.callId} Failed to get local offer`,T),this.emit(k.Error,new x(M.LocalOfferFailed,"Failed to get local offer!",T)),this.terminate(I.Local,M.LocalOfferFailed,!1)}),(0,t.default)(this,"getUserMediaFailed",T=>{if(this.successor){this.successor.getUserMediaFailed(T);return}i.logger.warn(`Failed to get user media - ending call ${this.callId}`,T),this.emit(k.Error,new x(M.NoUserMedia,"Couldn't start capturing media! Is your microphone set up and does this app have permission?",T)),this.terminate(I.Local,M.NoUserMedia,!1)}),(0,t.default)(this,"onIceConnectionStateChanged",()=>{var T,X,ne,ae,pe;if(!this.callHasEnded()){if(i.logger.debug("Call ID "+this.callId+": ICE connection state changed to: "+((T=this.peerConn)===null||T===void 0?void 0:T.iceConnectionState)),["connected","completed"].includes((X=(ne=this.peerConn)===null||ne===void 0?void 0:ne.iceConnectionState)!==null&&X!==void 0?X:""))clearTimeout(this.iceDisconnectedTimeout),this.state=h.Connected,!this.callLengthInterval&&!this.callStartTime&&(this.callStartTime=Date.now(),this.callLengthInterval=setInterval(()=>{this.emit(k.LengthChanged,Math.round((Date.now()-this.callStartTime)/1e3))},G));else if(((ae=this.peerConn)===null||ae===void 0?void 0:ae.iceConnectionState)=="failed"){var V;(V=this.peerConn)!==null&&V!==void 0&&V.restartIce?(this.candidatesEnded=!1,this.peerConn.restartIce()):(i.logger.info(`Hanging up call ${this.callId} (ICE failed and no ICE restart method)`),this.hangup(M.IceFailed,!1))}else((pe=this.peerConn)===null||pe===void 0?void 0:pe.iceConnectionState)=="disconnected"&&(this.iceDisconnectedTimeout=setTimeout(()=>{i.logger.info(`Hanging up call ${this.callId} (ICE disconnected for too long)`),this.hangup(M.IceFailed,!1)},D),this.state=h.Connecting);if(this.isPtt&&["failed","disconnected"].includes(this.peerConn.iceConnectionState))for(const se of this.getRemoteFeeds())se.setAudioVideoMuted(!0,!0)}}),(0,t.default)(this,"onSignallingStateChanged",()=>{var T;i.logger.debug(`call ${this.callId}: Signalling state changed to: ${(T=this.peerConn)===null||T===void 0?void 0:T.signalingState}`)}),(0,t.default)(this,"onTrack",T=>{if(T.streams.length===0){i.logger.warn(`Call ${this.callId} Streamless ${T.track.kind} found: ignoring.`);return}const X=T.streams[0];if(this.pushRemoteFeed(X),!this.removeTrackListeners.has(X)){const ne=()=>{X.getTracks().length===0&&(i.logger.info(`Call ${this.callId} removing track streamId: ${X.id}`),this.deleteFeedByStream(X),X.removeEventListener("removetrack",ne),this.removeTrackListeners.delete(X))};X.addEventListener("removetrack",ne),this.removeTrackListeners.set(X,ne)}}),(0,t.default)(this,"onDataChannel",T=>{this.emit(k.DataChannel,T.channel)}),(0,t.default)(this,"onNegotiationNeeded",async()=>{if(i.logger.info(`Call ${this.callId} Negotiation is needed!`),this.state!==h.CreateOffer&&this.opponentVersion===0){i.logger.info(`Call ${this.callId} Opponent does not support renegotiation: ignoring negotiationneeded event`);return}this.queueGotLocalOffer()}),(0,t.default)(this,"onHangupReceived",T=>{i.logger.debug("Hangup received for call ID "+this.callId),this.partyIdMatches(T)||this.state===h.Ringing?this.terminate(I.Remote,T.reason||M.UserHangup,!0):i.logger.info(`Call ${this.callId} Ignoring message from party ID ${T.party_id}: our partner is ${this.opponentPartyId}`)}),(0,t.default)(this,"onRejectReceived",T=>{i.logger.debug("Reject received for call ID "+this.callId),[h.InviteSent,h.Ringing].includes(this.state)||this.state===h.Fledgling&&this.direction===E.Inbound?this.terminate(I.Remote,T.reason||M.UserHangup,!0):i.logger.debug(`Call ${this.callId} is in state: ${this.state}: ignoring reject`)}),(0,t.default)(this,"onAnsweredElsewhere",T=>{i.logger.debug("Call "+this.callId+" answered elsewhere"),this.terminate(I.Remote,M.AnsweredElsewhere,!0)}),this.roomId=C.roomId,this.invitee=C.invitee,this.client=C.client,!this.client.deviceId)throw new Error("Client must have a device ID to start calls");this.forceTURN=(A=C.forceTURN)!==null&&A!==void 0?A:!1,this.ourPartyId=this.client.deviceId,this.opponentDeviceId=C.opponentDeviceId,this.opponentSessionId=C.opponentSessionId,this.groupCallId=C.groupCallId,this.turnServers=C.turnServers||[],this.turnServers.length===0&&this.client.isFallbackICEServerAllowed()&&this.turnServers.push({urls:[B]});for(const T of this.turnServers)o.checkObjectHasKeys(T,["urls"]);this.callId=z()}async placeVoiceCall(){await this.placeCall(!0,!1)}async placeVideoCall(){await this.placeCall(!0,!0)}createDataChannel(C,A){const T=this.peerConn.createDataChannel(C,A);return this.emit(k.DataChannel,T),T}getOpponentMember(){return this.opponentMember}getOpponentDeviceId(){return this.opponentDeviceId}getOpponentSessionId(){return this.opponentSessionId}opponentCanBeTransferred(){return Boolean(this.opponentCaps&&this.opponentCaps["m.call.transferee"])}opponentSupportsDTMF(){return Boolean(this.opponentCaps&&this.opponentCaps["m.call.dtmf"])}getRemoteAssertedIdentity(){return this.remoteAssertedIdentity}get state(){return this._state}set state(C){const A=this._state;this._state=C,this.emit(k.State,C,A)}get type(){return this.hasLocalUserMediaVideoTrack||this.hasRemoteUserMediaVideoTrack?w.Video:w.Voice}get hasLocalUserMediaVideoTrack(){var C;return!!((C=this.localUsermediaStream)!==null&&C!==void 0&&C.getVideoTracks().length)}get hasRemoteUserMediaVideoTrack(){return this.getRemoteFeeds().some(C=>{var A;return C.purpose===f.SDPStreamMetadataPurpose.Usermedia&&((A=C.stream)===null||A===void 0?void 0:A.getVideoTracks().length)})}get hasLocalUserMediaAudioTrack(){var C;return!!((C=this.localUsermediaStream)!==null&&C!==void 0&&C.getAudioTracks().length)}get hasRemoteUserMediaAudioTrack(){return this.getRemoteFeeds().some(C=>{var A;return C.purpose===f.SDPStreamMetadataPurpose.Usermedia&&!!((A=C.stream)!==null&&A!==void 0&&A.getAudioTracks().length)})}get localUsermediaFeed(){return this.getLocalFeeds().find(C=>C.purpose===f.SDPStreamMetadataPurpose.Usermedia)}get localScreensharingFeed(){return this.getLocalFeeds().find(C=>C.purpose===f.SDPStreamMetadataPurpose.Screenshare)}get localUsermediaStream(){var C;return(C=this.localUsermediaFeed)===null||C===void 0?void 0:C.stream}get localScreensharingStream(){var C;return(C=this.localScreensharingFeed)===null||C===void 0?void 0:C.stream}get remoteUsermediaFeed(){return this.getRemoteFeeds().find(C=>C.purpose===f.SDPStreamMetadataPurpose.Usermedia)}get remoteScreensharingFeed(){return this.getRemoteFeeds().find(C=>C.purpose===f.SDPStreamMetadataPurpose.Screenshare)}get remoteUsermediaStream(){var C;return(C=this.remoteUsermediaFeed)===null||C===void 0?void 0:C.stream}get remoteScreensharingStream(){var C;return(C=this.remoteScreensharingFeed)===null||C===void 0?void 0:C.stream}getFeedByStreamId(C){return this.getFeeds().find(A=>A.stream.id===C)}getFeeds(){return this.feeds}getLocalFeeds(){return this.feeds.filter(C=>C.isLocal())}getRemoteFeeds(){return this.feeds.filter(C=>!C.isLocal())}async initOpponentCrypto(){var C;if(!this.opponentDeviceId||!this.client.getUseE2eForGroupCall())return;if(!this.client.isCryptoEnabled()){this.opponentDeviceInfo=new g.DeviceInfo(this.opponentDeviceId);return}if(!this.client.crypto)throw new Error("Crypto is not initialised.");const A=this.invitee||((C=this.getOpponentMember())===null||C===void 0?void 0:C.userId);if(!A)throw new Error("Couldn't find opponent user ID to init crypto");const T=await this.client.crypto.deviceList.downloadKeys([A],!1);if(this.opponentDeviceInfo=T[A][this.opponentDeviceId],this.opponentDeviceInfo===void 0)throw new y.GroupCallUnknownDeviceError(A)}getLocalSDPStreamMetadata(C=!1){const A={};for(const T of this.getLocalFeeds())C&&(T.sdpMetadataStreamId=T.stream.id),A[T.sdpMetadataStreamId]={purpose:T.purpose,audio_muted:T.isAudioMuted(),video_muted:T.isVideoMuted()};return A}noIncomingFeeds(){return!this.feeds.some(C=>!C.isLocal())}pushRemoteFeed(C){if(!this.opponentSupportsSDPStreamMetadata()){this.pushRemoteFeedWithoutMetadata(C);return}const A=this.getOpponentMember().userId,T=this.remoteSDPStreamMetadata[C.id].purpose,X=this.remoteSDPStreamMetadata[C.id].audio_muted,ne=this.remoteSDPStreamMetadata[C.id].video_muted;if(!T){i.logger.warn(`Call ${this.callId} Ignoring stream with id ${C.id} because we didn't get any metadata about it`);return}if(this.getFeedByStreamId(C.id)){i.logger.warn(`Ignoring stream with id ${C.id} because we already have a feed for it`);return}this.feeds.push(new v.CallFeed({client:this.client,call:this,roomId:this.roomId,userId:A,deviceId:this.getOpponentDeviceId(),stream:C,purpose:T,audioMuted:X,videoMuted:ne})),this.emit(k.FeedsChanged,this.feeds),i.logger.info(`Call ${this.callId} pushed remote stream (id="${C.id}", active="${C.active}", purpose=${T})`)}pushRemoteFeedWithoutMetadata(C){var A;const T=this.getOpponentMember().userId,X=f.SDPStreamMetadataPurpose.Usermedia,ne=(A=this.feeds.find(ae=>!ae.isLocal()))===null||A===void 0?void 0:A.stream;if(ne&&C.id!==ne.id){i.logger.warn(`Call ${this.callId} Ignoring new stream ID ${C.id}: we already have stream ID ${ne.id}`);return}if(this.getFeedByStreamId(C.id)){i.logger.warn(`Ignoring stream with id ${C.id} because we already have a feed for it`);return}this.feeds.push(new v.CallFeed({client:this.client,call:this,roomId:this.roomId,audioMuted:!1,videoMuted:!1,userId:T,deviceId:this.getOpponentDeviceId(),stream:C,purpose:X})),this.emit(k.FeedsChanged,this.feeds),i.logger.info(`Call ${this.callId} pushed remote stream (id="${C.id}", active="${C.active}")`)}pushNewLocalFeed(C,A,T=!0){const X=this.client.getUserId();if(R(C.getAudioTracks(),!0),R(C.getVideoTracks(),!0),this.getFeedByStreamId(C.id)){i.logger.warn(`Ignoring stream with id ${C.id} because we already have a feed for it`);return}this.pushLocalFeed(new v.CallFeed({client:this.client,roomId:this.roomId,audioMuted:!1,videoMuted:!1,userId:X,deviceId:this.getOpponentDeviceId(),stream:C,purpose:A}),T)}pushLocalFeed(C,A=!0){if(this.feeds.some(T=>C.stream.id===T.stream.id)){i.logger.info(`Ignoring duplicate local stream ${C.stream.id} in call ${this.callId}`);return}if(this.feeds.push(C),A)for(const T of C.stream.getTracks()){i.logger.info(`Call ${this.callId} Adding track (id="${T.id}", kind="${T.kind}", streamId="${C.stream.id}", streamPurpose="${C.purpose}", enabled=${T.enabled}) to peer connection`);const X=F(C.purpose,T.kind);if(this.transceivers.has(X)){const ne=this.transceivers.get(X);ne.sender.setStreams&&ne.sender.setStreams(C.stream),ne.sender.replaceTrack(T),ne.direction=ne.direction==="inactive"?"sendonly":"sendrecv"}else{const ne=this.peerConn.addTrack(T,C.stream),ae=this.peerConn.getTransceivers().find(pe=>pe.sender===ne);ae?this.transceivers.set(X,ae):i.logger.warn("Didn't find a matching transceiver after adding track!")}}i.logger.info(`Call ${this.callId} Pushed local stream (id="${C.stream.id}", active="${C.stream.active}", purpose="${C.purpose}")`),this.emit(k.FeedsChanged,this.feeds)}removeLocalFeed(C){const A=F(C.purpose,"audio"),T=F(C.purpose,"video");for(const X of[A,T])if(this.transceivers.has(X)){const ne=this.transceivers.get(X);ne.sender&&this.peerConn.removeTrack(ne.sender)}C.purpose===f.SDPStreamMetadataPurpose.Screenshare&&this.client.getMediaHandler().stopScreensharingStream(C.stream),this.deleteFeed(C)}deleteAllFeeds(){for(const C of this.feeds)(!C.isLocal()||!this.groupCallId)&&C.dispose();this.feeds=[],this.emit(k.FeedsChanged,this.feeds)}deleteFeedByStream(C){const A=this.getFeedByStreamId(C.id);if(!A){i.logger.warn(`Call ${this.callId} Didn't find the feed with stream id ${C.id} to delete`);return}this.deleteFeed(A)}deleteFeed(C){C.dispose(),this.feeds.splice(this.feeds.indexOf(C),1),this.emit(k.FeedsChanged,this.feeds)}async getCurrentCallStats(){return this.callHasEnded()?this.callStatsAtEnd:this.collectCallStats()}async collectCallStats(){if(!this.peerConn)return;const C=await this.peerConn.getStats(),A=[];return C.forEach(T=>{A.push(T)}),A}async initWithInvite(C){var A;const T=C.getContent();this.direction=E.Inbound,await this.client.checkTurnServers()||i.logger.warn(`Call ${this.callId} Failed to get TURN credentials! Proceeding with call anyway...`);const ne=T[f.SDPStreamMetadataKey];ne?this.updateRemoteSDPStreamMetadata(ne):i.logger.debug(`Call ${this.callId} did not get any SDPStreamMetadata! Can not send/receive multiple streams`),this.peerConn=this.createPeerConnection(),this.chooseOpponent(C),await this.initOpponentCrypto();try{await this.peerConn.setRemoteDescription(T.offer),await this.addBufferedIceCandidates()}catch(pe){i.logger.debug(`Call ${this.callId} failed to set remote description`,pe),this.terminate(I.Local,M.SetRemoteDescription,!1);return}const ae=(A=this.feeds.find(pe=>!pe.isLocal()))===null||A===void 0?void 0:A.stream;if(!ae||ae.getTracks().length===0){i.logger.error(`Call ${this.callId} no remote stream or no tracks after setting remote description!`),this.terminate(I.Local,M.SetRemoteDescription,!1);return}if(this.state=h.Ringing,C.getLocalAge()){const pe=setTimeout(()=>{this.state==h.Ringing&&(i.logger.debug(`Call ${this.callId} invite has expired. Hanging up.`),this.hangupParty=I.Remote,this.state=h.Ended,this.stopAllMedia(),this.peerConn.signalingState!="closed"&&this.peerConn.close(),this.emit(k.Hangup,this))},T.lifetime-C.getLocalAge()),V=se=>{se!==h.Ringing&&(clearTimeout(pe),this.off(k.State,V))};this.on(k.State,V)}}initWithHangup(C){this.state=h.Ended}shouldAnswerWithMediaType(C,A,T){return C&&!A?(i.logger.warn(`Call ${this.callId} Unable to answer with ${T} because the other side isn't sending it either.`),!1):!o.isNullOrUndefined(C)&&C!==A&&!this.opponentSupportsSDPStreamMetadata()?(i.logger.warn(`Call ${this.callId} Unable to answer with ${T}=${C} because the other side doesn't support it. Answering with ${T}=${A}.`),A):C??A}async answer(C,A){if(!this.inviteOrAnswerSent){if(C===!1&&A===!1)throw new Error("You CANNOT answer a call without media");if(!this.localUsermediaStream&&!this.waitForLocalAVStream){const X=this.state,ne=this.shouldAnswerWithMediaType(C,this.hasRemoteUserMediaAudioTrack,"audio"),ae=this.shouldAnswerWithMediaType(A,this.hasRemoteUserMediaVideoTrack,"video");this.state=h.WaitLocalMedia,this.waitForLocalAVStream=!0;try{var T;const pe=await this.client.getMediaHandler().getUserMediaStream(ne,ae);this.waitForLocalAVStream=!1;const se=[new v.CallFeed({client:this.client,roomId:this.roomId,userId:this.client.getUserId(),deviceId:(T=this.client.getDeviceId())!==null&&T!==void 0?T:void 0,stream:pe,purpose:f.SDPStreamMetadataPurpose.Usermedia,audioMuted:!1,videoMuted:!1})];this.localScreensharingFeed&&se.push(this.localScreensharingFeed),this.answerWithCallFeeds(se)}catch(pe){if(ae)i.logger.warn(`Call ${this.callId} Failed to getUserMedia(), trying to getUserMedia() without video`),this.state=X,this.waitForLocalAVStream=!1,await this.answer(ne,!1);else{this.getUserMediaFailed(pe);return}}}else this.waitForLocalAVStream&&(this.state=h.WaitLocalMedia)}}answerWithCallFeeds(C){this.inviteOrAnswerSent||this.queueGotCallFeedsForAnswer(C)}replacedBy(C){i.logger.debug(`Call ${this.callId} replaced by ${C.callId}`),this.state===h.WaitLocalMedia?(i.logger.debug(`Call ${this.callId} telling new call ${C.callId} to wait for local media`),C.waitForLocalAVStream=!0):[h.CreateOffer,h.InviteSent].includes(this.state)&&(C.direction===E.Outbound?C.queueGotCallFeedsForAnswer([]):(i.logger.debug(`Call ${this.callId} handing local stream to new call ${C.callId}`),C.queueGotCallFeedsForAnswer(this.getLocalFeeds().map(A=>A.clone())))),this.successor=C,this.emit(k.Replaced,C),this.hangup(M.Replaced,!0)}hangup(C,A){if(this.callHasEnded()||(i.logger.debug(`Ending call ${this.callId} with reason ${C}`),this.terminate(I.Local,C,!A),[h.Fledgling,h.WaitLocalMedia].includes(this.state)))return;const T={};(this.opponentVersion&&this.opponentVersion!==0||C!==M.UserHangup)&&(T.reason=C),this.sendVoipEvent(a.EventType.CallHangup,T)}reject(){if(this.state!==h.Ringing)throw Error("Call must be in 'ringing' state to reject!");if(this.opponentVersion===0){i.logger.info(`Call ${this.callId} Opponent version is less than 1 (${this.opponentVersion}): sending hangup instead of reject`),this.hangup(M.UserHangup,!0);return}i.logger.debug("Rejecting call: "+this.callId),this.terminate(I.Local,M.UserHangup,!0),this.sendVoipEvent(a.EventType.CallReject,{})}async upgradeCall(C,A){if(!(!C&&!A)&&this.opponentSupportsSDPStreamMetadata())try{i.logger.debug(`Upgrading call ${this.callId}: audio?=${C} video?=${A}`);const T=C||this.hasLocalUserMediaAudioTrack,X=A||this.hasLocalUserMediaVideoTrack,ne=await this.client.getMediaHandler().getUserMediaStream(T,X,!1);await this.updateLocalUsermediaStream(ne,C,A)}catch(T){i.logger.error(`Call ${this.callId} Failed to upgrade the call`,T),this.emit(k.Error,new x(M.NoUserMedia,"Failed to get camera access: ",T))}}opponentSupportsSDPStreamMetadata(){return Boolean(this.remoteSDPStreamMetadata)}isScreensharing(){return Boolean(this.localScreensharingStream)}async setScreensharingEnabled(C,A){if(C&&this.isScreensharing())return i.logger.warn(`Call ${this.callId} There is already a screensharing stream - there is nothing to do!`),!0;if(!C&&!this.isScreensharing())return i.logger.warn(`Call ${this.callId} There already isn't a screensharing stream - there is nothing to do!`),!1;if(!this.opponentSupportsSDPStreamMetadata())return this.setScreensharingEnabledWithoutMetadataSupport(C,A);if(i.logger.debug(`Call ${this.callId} set screensharing enabled? ${C}`),C)try{const T=await this.client.getMediaHandler().getScreensharingStream(A);return T?(this.pushNewLocalFeed(T,f.SDPStreamMetadataPurpose.Screenshare),!0):!1}catch(T){return i.logger.error(`Call ${this.callId} Failed to get screen-sharing stream:`,T),!1}else{const T=this.transceivers.get(F(f.SDPStreamMetadataPurpose.Screenshare,"audio")),X=this.transceivers.get(F(f.SDPStreamMetadataPurpose.Screenshare,"video"));for(const ne of[T,X])ne&&ne.sender&&this.peerConn.removeTrack(ne.sender);return this.client.getMediaHandler().stopScreensharingStream(this.localScreensharingStream),this.deleteFeedByStream(this.localScreensharingStream),!1}}async setScreensharingEnabledWithoutMetadataSupport(C,A){if(i.logger.debug(`Call ${this.callId} Set screensharing enabled? ${C} using replaceTrack()`),C)try{var T;const ae=await this.client.getMediaHandler().getScreensharingStream(A);if(!ae)return!1;const pe=ae.getTracks().find(se=>se.kind==="video"),V=(T=this.transceivers.get(F(f.SDPStreamMetadataPurpose.Usermedia,"video")))===null||T===void 0?void 0:T.sender;return V==null||V.replaceTrack(pe??null),this.pushNewLocalFeed(ae,f.SDPStreamMetadataPurpose.Screenshare,!1),!0}catch(ae){return i.logger.error(`Call ${this.callId} Failed to get screen-sharing stream:`,ae),!1}else{var X,ne;const ae=(X=this.localUsermediaStream)===null||X===void 0?void 0:X.getTracks().find(V=>V.kind==="video"),pe=(ne=this.transceivers.get(F(f.SDPStreamMetadataPurpose.Usermedia,"video")))===null||ne===void 0?void 0:ne.sender;return pe==null||pe.replaceTrack(ae??null),this.client.getMediaHandler().stopScreensharingStream(this.localScreensharingStream),this.deleteFeedByStream(this.localScreensharingStream),!1}}async updateLocalUsermediaStream(C,A=!1,T=!1){const X=this.localUsermediaFeed,ne=A||!X.isAudioMuted()&&!this.remoteOnHold,ae=T||!X.isVideoMuted()&&!this.remoteOnHold;i.logger.log(`call ${this.callId} updateLocalUsermediaStream stream ${C.id} audioEnabled ${ne} videoEnabled ${ae}`),R(C.getAudioTracks(),ne),R(C.getVideoTracks(),ae);for(const V of this.localUsermediaStream.getTracks())this.localUsermediaStream.removeTrack(V),V.stop();for(const V of C.getTracks())this.localUsermediaStream.addTrack(V);for(const V of C.getTracks()){var pe;const se=F(f.SDPStreamMetadataPurpose.Usermedia,V.kind),Q=(pe=this.transceivers.get(se))===null||pe===void 0?void 0:pe.sender;let j=!1;if(Q)try{i.logger.info(`Call ${this.callId} Replacing track (id="${V.id}", kind="${V.kind}", streamId="${C.id}", streamPurpose="${X.purpose}") to peer connection`),await Q.replaceTrack(V),j=!0}catch(Z){i.logger.warn("replaceTrack failed: adding new transceiver instead",Z)}if(!j){i.logger.info(`Call ${this.callId} Adding track (id="${V.id}", kind="${V.kind}", streamId="${C.id}", streamPurpose="${X.purpose}") to peer connection`);const Z=this.peerConn.addTrack(V,this.localUsermediaStream),te=this.peerConn.getTransceivers().find(re=>re.sender===Z);te?this.transceivers.set(se,te):i.logger.warn("Couldn't find matching transceiver for newly added track!")}}}async setLocalVideoMuted(C){var A;return i.logger.log(`call ${this.callId} setLocalVideoMuted ${C}`),await this.client.getMediaHandler().hasVideoDevice()?!this.hasLocalUserMediaVideoTrack&&!C?(await this.upgradeCall(!1,!0),this.isLocalVideoMuted()):((A=this.localUsermediaFeed)===null||A===void 0||A.setAudioVideoMuted(null,C),this.updateMuteStatus(),await this.sendMetadataUpdate(),this.isLocalVideoMuted()):this.isLocalVideoMuted()}isLocalVideoMuted(){var C,A;return(C=(A=this.localUsermediaFeed)===null||A===void 0?void 0:A.isVideoMuted())!==null&&C!==void 0?C:!1}async setMicrophoneMuted(C){var A;return i.logger.log(`call ${this.callId} setMicrophoneMuted ${C}`),await this.client.getMediaHandler().hasAudioDevice()?!this.hasLocalUserMediaAudioTrack&&!C?(await this.upgradeCall(!0,!1),this.isMicrophoneMuted()):((A=this.localUsermediaFeed)===null||A===void 0||A.setAudioVideoMuted(C,null),this.updateMuteStatus(),await this.sendMetadataUpdate(),this.isMicrophoneMuted()):this.isMicrophoneMuted()}isMicrophoneMuted(){var C,A;return(C=(A=this.localUsermediaFeed)===null||A===void 0?void 0:A.isAudioMuted())!==null&&C!==void 0?C:!1}isRemoteOnHold(){return this.remoteOnHold}setRemoteOnHold(C){if(this.isRemoteOnHold()!==C){this.remoteOnHold=C;for(const A of this.peerConn.getTransceivers())A.direction=C?"sendonly":"sendrecv";this.updateMuteStatus(),this.sendMetadataUpdate(),this.emit(k.RemoteHoldUnhold,this.remoteOnHold)}}isLocalOnHold(){if(this.state!==h.Connected)return!1;let C=!0;for(const A of this.peerConn.getTransceivers())["inactive","recvonly"].includes(A.currentDirection)||(C=!1);return C}sendDtmfDigit(C){for(const T of this.peerConn.getSenders()){var A;if(((A=T.track)===null||A===void 0?void 0:A.kind)==="audio"&&T.dtmf){T.dtmf.insertDTMF(C);return}}throw new Error("Unable to find a track to send DTMF on")}updateMuteStatus(){const C=this.isMicrophoneMuted()||this.remoteOnHold,A=this.isLocalVideoMuted()||this.remoteOnHold;i.logger.log(`call ${this.callId} updateMuteStatus stream ${this.localUsermediaStream.id} micShouldBeMuted ${C} vidShouldBeMuted ${A}`),R(this.localUsermediaStream.getAudioTracks(),!C),R(this.localUsermediaStream.getVideoTracks(),!A)}async sendMetadataUpdate(){await this.sendVoipEvent(a.EventType.CallSDPStreamMetadataChangedPrefix,{[f.SDPStreamMetadataKey]:this.getLocalSDPStreamMetadata()})}gotCallFeedsForInvite(C,A=!1){if(this.successor){this.successor.queueGotCallFeedsForAnswer(C);return}if(this.callHasEnded()){this.stopAllMedia();return}for(const T of C)this.pushLocalFeed(T);A&&this.peerConn.addTransceiver("video",{direction:"recvonly"}),this.state=h.CreateOffer,i.logger.debug(`Call ${this.callId} gotUserMediaForInvite`)}async sendAnswer(){const C={answer:{sdp:this.peerConn.localDescription.sdp,type:this.peerConn.localDescription.type},[f.SDPStreamMetadataKey]:this.getLocalSDPStreamMetadata(!0)};C.capabilities={"m.call.transferee":this.client.supportsCallTransfer,"m.call.dtmf":!1};const A=this.discardDuplicateCandidates();i.logger.info(`Call ${this.callId} Discarding ${A} candidates that will be sent in answer`);try{await this.sendVoipEvent(a.EventType.CallAnswer,C),this.inviteOrAnswerSent=!0}catch(T){this.state=h.Ringing,T instanceof S.MatrixError&&T.event&&this.client.cancelPendingEvent(T.event);let X=M.SendAnswer,ne="Failed to send answer";throw T.name=="UnknownDeviceError"&&(X=M.UnknownDevices,ne="Unknown devices present in the room"),this.emit(k.Error,new x(X,ne,T)),T}this.sendCandidateQueue()}queueGotCallFeedsForAnswer(C){this.responsePromiseChain?this.responsePromiseChain=this.responsePromiseChain.then(()=>this.gotCallFeedsForAnswer(C)):this.responsePromiseChain=this.gotCallFeedsForAnswer(C)}mungeSdp(C,A){const T=(0,r.parse)(C.sdp);T.media.forEach(X=>{const ne=new Map,ae=new Map;for(const pe of X.rtp)ne.set(pe.payload,pe.codec),ae.set(pe.codec,pe.payload);for(const pe of A){if(pe.mediaType!==X.type)continue;if(!ae.has(pe.codec)){i.logger.info(`Ignoring SDP modifications for ${pe.codec} as it's not present.`);continue}const V=[];pe.enableDtx!==void 0&&V.push(`usedtx=${pe.enableDtx?"1":"0"}`),pe.maxAverageBitrate!==void 0&&V.push(`maxaveragebitrate=${pe.maxAverageBitrate}`);let se=!1;for(const Q of X.fmtp)ne.get(Q.payload)===pe.codec&&(se=!0,Q.config+=";"+V.join(";"));se||X.fmtp.push({payload:ae.get(pe.codec),config:V.join(";")})}}),C.sdp=(0,r.write)(T)}async createOffer(){const C=await this.peerConn.createOffer();return this.mungeSdp(C,W(this.isPtt)),C}async createAnswer(){const C=await this.peerConn.createAnswer();return this.mungeSdp(C,W(this.isPtt)),C}async gotCallFeedsForAnswer(C){if(this.callHasEnded())return;this.waitForLocalAVStream=!1;for(const T of C)this.pushLocalFeed(T);this.state=h.CreateAnswer;let A;try{this.getRidOfRTXCodecs(),A=await this.createAnswer()}catch(T){i.logger.debug(`Call ${this.callId} Failed to create answer: `,T),this.terminate(I.Local,M.CreateAnswer,!0);return}try{if(await this.peerConn.setLocalDescription(A),this.callHasEnded()||(this.state=h.Connecting,await new Promise(T=>{setTimeout(T,200)}),this.callHasEnded()))return;this.sendAnswer()}catch(T){i.logger.debug(`Call ${this.callId} Error setting local description!`,T),this.terminate(I.Local,M.SetLocalDescription,!0);return}}async onRemoteIceCandidatesReceived(C){if(this.callHasEnded())return;const A=C.getContent(),T=A.candidates;if(!T){i.logger.info(`Call ${this.callId} Ignoring candidates event with no candidates!`);return}const X=A.version===0?null:A.party_id||null;if(this.opponentPartyId===void 0){if(X){i.logger.info(`Call ${this.callId} Buffering ${T.length} candidates until we pick an opponent`);const ne=this.remoteCandidateBuffer.get(X)||[];ne.push(...T),this.remoteCandidateBuffer.set(X,ne)}return}if(!this.partyIdMatches(A)){i.logger.info(`Call ${this.callId} Ignoring candidates from party ID ${A.party_id}: we have chosen party ID ${this.opponentPartyId}`);return}await this.addIceCandidates(T)}async onAnswerReceived(C){const A=C.getContent();if(i.logger.debug(`Got answer for call ID ${this.callId} from party ID ${A.party_id}`),this.callHasEnded()){i.logger.debug(`Ignoring answer because call ID ${this.callId} has ended`);return}if(this.opponentPartyId!==void 0){i.logger.info(`Call ${this.callId} Ignoring answer from party ID ${A.party_id}: we already have an answer/reject from ${this.opponentPartyId}`);return}this.chooseOpponent(C),await this.addBufferedIceCandidates(),this.state=h.Connecting;const T=A[f.SDPStreamMetadataKey];T?this.updateRemoteSDPStreamMetadata(T):i.logger.warn(`Call ${this.callId} Did not get any SDPStreamMetadata! Can not send/receive multiple streams`);try{await this.peerConn.setRemoteDescription(A.answer)}catch(X){i.logger.debug(`Call ${this.callId} Failed to set remote description`,X),this.terminate(I.Local,M.SetRemoteDescription,!1);return}if(this.opponentPartyId!==null)try{await this.sendVoipEvent(a.EventType.CallSelectAnswer,{selected_party_id:this.opponentPartyId})}catch(X){i.logger.warn(`Call ${this.callId} Failed to send select_answer event`,X)}}async onSelectAnswerReceived(C){if(this.direction!==E.Inbound){i.logger.warn(`Call ${this.callId} Got select_answer for an outbound call: ignoring`);return}const A=C.getContent().selected_party_id;if(A==null){i.logger.warn(`Call ${this.callId} Got nonsensical select_answer with null/undefined selected_party_id: ignoring`);return}A!==this.ourPartyId&&(i.logger.info(`Call ${this.callId} Got select_answer for party ID ${A}: we are party ID ${this.ourPartyId}.`),await this.terminate(I.Remote,M.AnsweredElsewhere,!0))}async onNegotiateReceived(C){const A=C.getContent(),T=A.description;if(!T||!T.sdp||!T.type){i.logger.info(`Call ${this.callId} Ignoring invalid m.call.negotiate event`);return}const X=this.direction===E.Inbound,ne=T.type==="offer"&&(this.makingOffer||this.peerConn.signalingState!=="stable");if(this.ignoreOffer=!X&&ne,this.ignoreOffer){i.logger.info(`Call ${this.callId} Ignoring colliding negotiate event because we're impolite`);return}const ae=this.isLocalOnHold(),pe=A[f.SDPStreamMetadataKey];pe?this.updateRemoteSDPStreamMetadata(pe):i.logger.warn(`Call ${this.callId} Received negotiation event without SDPStreamMetadata!`);try{if(await this.peerConn.setRemoteDescription(T),T.type==="offer"){var V;let Q;try{this.getRidOfRTXCodecs(),Q=await this.createAnswer()}catch(j){i.logger.debug(`Call ${this.callId} Failed to create answer: `,j),this.terminate(I.Local,M.CreateAnswer,!0);return}await this.peerConn.setLocalDescription(Q),this.sendVoipEvent(a.EventType.CallNegotiate,{description:(V=this.peerConn.localDescription)===null||V===void 0?void 0:V.toJSON(),[f.SDPStreamMetadataKey]:this.getLocalSDPStreamMetadata(!0)})}}catch(Q){i.logger.warn(`Call ${this.callId} Failed to complete negotiation`,Q)}const se=this.isLocalOnHold();ae!==se&&(this.emit(k.LocalHoldUnhold,se),this.emit(k.HoldUnhold,se))}updateRemoteSDPStreamMetadata(C){this.remoteSDPStreamMetadata=o.recursivelyAssign(this.remoteSDPStreamMetadata||{},C,!0);for(const T of this.getRemoteFeeds()){var A;const X=T.stream.id,ne=this.remoteSDPStreamMetadata[X];T.setAudioVideoMuted(ne==null?void 0:ne.audio_muted,ne==null?void 0:ne.video_muted),T.purpose=(A=this.remoteSDPStreamMetadata[X])===null||A===void 0?void 0:A.purpose}}onSDPStreamMetadataChangedReceived(C){const T=C.getContent()[f.SDPStreamMetadataKey];this.updateRemoteSDPStreamMetadata(T)}async onAssertedIdentityReceived(C){const A=C.getContent();A.asserted_identity&&(this.remoteAssertedIdentity={id:A.asserted_identity.id,displayName:A.asserted_identity.display_name},this.emit(k.AssertedIdentityChanged))}callHasEnded(){return this.state===h.Ended}queueGotLocalOffer(){this.responsePromiseChain?this.responsePromiseChain=this.responsePromiseChain.then(()=>this.wrappedGotLocalOffer()):this.responsePromiseChain=this.wrappedGotLocalOffer()}async wrappedGotLocalOffer(){this.makingOffer=!0;try{await this.gotLocalOffer()}catch(C){this.getLocalOfferFailed(C);return}finally{this.makingOffer=!1}}async gotLocalOffer(){if(i.logger.debug(`Call ${this.callId} Setting local description`),this.callHasEnded()){i.logger.debug("Ignoring newly created offer on call ID "+this.callId+" because the call has ended");return}let C;try{this.getRidOfRTXCodecs(),C=await this.createOffer()}catch(pe){i.logger.debug(`Call ${this.callId} Failed to create offer: `,pe),this.terminate(I.Local,M.CreateOffer,!0);return}try{await this.peerConn.setLocalDescription(C)}catch(pe){i.logger.debug(`Call ${this.callId} Error setting local description!`,pe),this.terminate(I.Local,M.SetLocalDescription,!0);return}if(this.peerConn.iceGatheringState==="gathering"&&await new Promise(pe=>{setTimeout(pe,200)}),this.callHasEnded())return;const A=this.state===h.CreateOffer?a.EventType.CallInvite:a.EventType.CallNegotiate,T={lifetime:N};if(A===a.EventType.CallInvite&&this.invitee&&(T.invitee=this.invitee),this.state===h.CreateOffer){var X;T.offer=(X=this.peerConn.localDescription)===null||X===void 0?void 0:X.toJSON()}else{var ne;T.description=(ne=this.peerConn.localDescription)===null||ne===void 0?void 0:ne.toJSON()}T.capabilities={"m.call.transferee":this.client.supportsCallTransfer,"m.call.dtmf":!1},T[f.SDPStreamMetadataKey]=this.getLocalSDPStreamMetadata(!0);const ae=this.discardDuplicateCandidates();i.logger.info(`Call ${this.callId} Discarding ${ae} candidates that will be sent in offer`);try{await this.sendVoipEvent(A,T)}catch(pe){i.logger.error(`Call ${this.callId} Failed to send invite`,pe),pe instanceof S.MatrixError&&pe.event&&this.client.cancelPendingEvent(pe.event);let V=M.SignallingFailed,se="Signalling failed";this.state===h.CreateOffer&&(V=M.SendInvite,se="Failed to send invite"),pe.name=="UnknownDeviceError"&&(V=M.UnknownDevices,se="Unknown devices present in the room"),this.emit(k.Error,new x(V,se,pe)),this.terminate(I.Local,V,!1);return}this.sendCandidateQueue(),this.state===h.CreateOffer&&(this.inviteOrAnswerSent=!0,this.state=h.InviteSent,this.inviteTimeout=setTimeout(()=>{this.inviteTimeout=void 0,this.state===h.InviteSent&&this.hangup(M.InviteTimeout,!1)},N))}getRidOfRTXCodecs(){if(!RTCRtpReceiver.getCapabilities||!RTCRtpSender.getCapabilities)return;const C=RTCRtpReceiver.getCapabilities("video").codecs,T=[...RTCRtpSender.getCapabilities("video").codecs,...C];for(const ne of T)if(ne.mimeType==="video/rtx"){const ae=T.indexOf(ne);T.splice(ae,1)}const X=this.transceivers.get(F(f.SDPStreamMetadataPurpose.Screenshare,"video"));X&&X.setCodecPreferences(T)}async sendVoipEvent(C,A){const T=Object.assign({},A,{version:L,call_id:this.callId,party_id:this.ourPartyId,conf_id:this.groupCallId});if(this.opponentDeviceId){var X;const ae=this.toDeviceSeq++,pe=u(u({},T),{},{device_id:this.client.deviceId,sender_session_id:this.client.getSessionId(),dest_session_id:this.opponentSessionId,seq:ae,[a.ToDeviceMessageId]:(0,n.v4)()});this.emit(k.SendVoipEvent,{type:"toDevice",eventType:C,userId:this.invitee||((X=this.getOpponentMember())===null||X===void 0?void 0:X.userId),opponentDeviceId:this.opponentDeviceId,content:pe});const V=this.invitee||this.getOpponentMember().userId;this.client.getUseE2eForGroupCall()?await this.client.encryptAndSendToDevices([{userId:V,deviceInfo:this.opponentDeviceInfo}],{type:C,content:pe}):await this.client.sendToDevice(C,{[V]:{[this.opponentDeviceId]:pe}})}else{var ne;this.emit(k.SendVoipEvent,{type:"sendEvent",eventType:C,roomId:this.roomId,content:T,userId:this.invitee||((ne=this.getOpponentMember())===null||ne===void 0?void 0:ne.userId)}),await this.client.sendEvent(this.roomId,C,T)}}queueCandidate(C){if(C?this.candidateSendQueue.push(C):this.candidatesEnded=!0,this.state===h.Ringing||!this.inviteOrAnswerSent)return;const A=this.direction===E.Inbound?500:2e3;this.candidateSendTries===0&&setTimeout(()=>{this.sendCandidateQueue()},A)}discardDuplicateCandidates(){let C=0;const A=[];for(let T=0;T<this.candidateSendQueue.length;T++){const X=this.candidateSendQueue[T];X.candidate===""?A.push(X):C++}return this.candidateSendQueue=A,C}async transfer(C){const A=await this.client.getProfileInfo(C),T=z(),X={replacement_id:z(),target_user:{id:C,display_name:A.displayname,avatar_url:A.avatar_url},create_call:T};await this.sendVoipEvent(a.EventType.CallReplaces,X),await this.terminate(I.Local,M.Transfered,!0)}async transferToCall(C){var A,T;const X=(A=C.getOpponentMember())===null||A===void 0?void 0:A.userId,ne=X?await this.client.getProfileInfo(X):void 0,ae=(T=this.getOpponentMember())===null||T===void 0?void 0:T.userId,pe=ae?await this.client.getProfileInfo(ae):void 0,V=z(),se={replacement_id:z(),target_user:{id:ae,display_name:pe==null?void 0:pe.displayname,avatar_url:pe==null?void 0:pe.avatar_url},await_call:V};await C.sendVoipEvent(a.EventType.CallReplaces,se);const Q={replacement_id:z(),target_user:{id:X,display_name:ne==null?void 0:ne.displayname,avatar_url:ne==null?void 0:ne.avatar_url},create_call:V};await this.sendVoipEvent(a.EventType.CallReplaces,Q),await this.terminate(I.Local,M.Transfered,!0),await C.terminate(I.Local,M.Transfered,!0)}async terminate(C,A,T){if(!this.callHasEnded()){this.hangupParty=C,this.hangupReason=A,this.state=h.Ended,this.inviteTimeout&&(clearTimeout(this.inviteTimeout),this.inviteTimeout=void 0),this.callLengthInterval&&(clearInterval(this.callLengthInterval),this.callLengthInterval=void 0);for(const[X,ne]of this.removeTrackListeners)X.removeEventListener("removetrack",ne);this.removeTrackListeners.clear(),this.callStatsAtEnd=await this.collectCallStats(),this.stopAllMedia(),this.deleteAllFeeds(),this.peerConn&&this.peerConn.signalingState!=="closed"&&this.peerConn.close(),T&&this.emit(k.Hangup,this),this.client.callEventHandler.calls.delete(this.callId)}}stopAllMedia(){i.logger.debug(this.groupCallId?`Call ${this.callId} stopping all media except local feeds`:`Call ${this.callId} stopping all media`);for(const C of this.feeds)if(C.isLocal()&&C.purpose===f.SDPStreamMetadataPurpose.Usermedia&&!this.groupCallId)this.client.getMediaHandler().stopUserMediaStream(C.stream);else if(C.isLocal()&&C.purpose===f.SDPStreamMetadataPurpose.Screenshare&&!this.groupCallId)this.client.getMediaHandler().stopScreensharingStream(C.stream);else if(!C.isLocal()||!this.groupCallId){i.logger.debug("Stopping remote stream",C.stream.id);for(const A of C.stream.getTracks())A.stop()}}checkForErrorListener(){if(this.listeners(s.EventEmitterEvents.Error).length===0)throw new Error("You MUST attach an error listener using call.on('error', function() {})")}async sendCandidateQueue(){if(this.candidateSendQueue.length===0||this.callHasEnded())return;const C=this.candidateSendQueue;this.candidateSendQueue=[],++this.candidateSendTries;const A={candidates:C.map(T=>T.toJSON())};this.candidatesEnded&&A.candidates.push({candidate:""}),i.logger.debug(`Call ${this.callId} attempting to send ${C.length} candidates`);try{await this.sendVoipEvent(a.EventType.CallCandidates,A),this.candidateSendTries=0,this.sendCandidateQueue()}catch(T){if(T instanceof S.MatrixError&&T.event&&this.client.cancelPendingEvent(T.event),this.candidateSendQueue.push(...C),this.candidateSendTries>5){i.logger.debug(`Call ${this.callId} failed to send candidates on attempt ${this.candidateSendTries}. Giving up on this call.`,T);const ne=M.SignallingFailed,ae="Signalling failed";this.emit(k.Error,new x(ne,ae,T)),this.hangup(ne,!1);return}const X=500*Math.pow(2,this.candidateSendTries);++this.candidateSendTries,i.logger.debug(`Call ${this.callId} failed to send candidates. Retrying in ${X}ms`,T),setTimeout(()=>{this.sendCandidateQueue()},X)}}async placeCall(C,A){if(!C)throw new Error("You CANNOT start a call without audio");this.state=h.WaitLocalMedia;try{var T;const X=await this.client.getMediaHandler().getUserMediaStream(C,A);R(X.getAudioTracks(),!0),R(X.getVideoTracks(),!0);const ne=new v.CallFeed({client:this.client,roomId:this.roomId,userId:this.client.getUserId(),deviceId:(T=this.client.getDeviceId())!==null&&T!==void 0?T:void 0,stream:X,purpose:f.SDPStreamMetadataPurpose.Usermedia,audioMuted:!1,videoMuted:!1});await this.placeCallWithCallFeeds([ne])}catch(X){this.getUserMediaFailed(X);return}}async placeCallWithCallFeeds(C,A=!1){this.checkForErrorListener(),this.direction=E.Outbound,await this.initOpponentCrypto(),this.client.callEventHandler.calls.set(this.callId,this),await this.client.checkTurnServers()||i.logger.warn(`Call ${this.callId} Failed to get TURN credentials! Proceeding with call anyway...`),this.peerConn=this.createPeerConnection(),this.gotCallFeedsForInvite(C,A)}createPeerConnection(){const C=new window.RTCPeerConnection({iceTransportPolicy:this.forceTURN?"relay":void 0,iceServers:this.turnServers,iceCandidatePoolSize:this.client.iceCandidatePoolSize,bundlePolicy:"max-bundle"});return C.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChanged),C.addEventListener("signalingstatechange",this.onSignallingStateChanged),C.addEventListener("icecandidate",this.gotLocalIceCandidate),C.addEventListener("icegatheringstatechange",this.onIceGatheringStateChange),C.addEventListener("track",this.onTrack),C.addEventListener("negotiationneeded",this.onNegotiationNeeded),C.addEventListener("datachannel",this.onDataChannel),C}partyIdMatches(C){return(C.version===0?null:C.party_id||null)===this.opponentPartyId}chooseOpponent(C){var A;const T=C.getContent();i.logger.debug(`Call ${this.callId} choosing opponent party ID ${T.party_id}`),this.opponentVersion=T.version,this.opponentVersion===0?this.opponentPartyId=null:this.opponentPartyId=T.party_id||null,this.opponentCaps=T.capabilities||{},this.opponentMember=(A=this.client.getRoom(this.roomId).getMember(C.getSender()))!==null&&A!==void 0?A:void 0}async addBufferedIceCandidates(){const C=this.remoteCandidateBuffer.get(this.opponentPartyId);C&&(i.logger.info(`Call ${this.callId} Adding ${C.length} buffered candidates for opponent ${this.opponentPartyId}`),await this.addIceCandidates(C)),this.remoteCandidateBuffer.clear()}async addIceCandidates(C){for(const A of C){(A.sdpMid===null||A.sdpMid===void 0)&&(A.sdpMLineIndex===null||A.sdpMLineIndex===void 0)?i.logger.debug(`Call ${this.callId} got remote ICE end-of-candidates`):i.logger.debug(`Call ${this.callId} got remote ICE ${A.sdpMid} candidate: ${A.candidate}`);try{await this.peerConn.addIceCandidate(A)}catch(T){this.ignoreOffer||i.logger.info(`Call ${this.callId} failed to add remote ICE candidate`,T)}}}get hasPeerConnection(){return Boolean(this.peerConn)}}ot.MatrixCall=H;function R(U,C){for(const A of U)A.enabled=C}function P(){if(typeof window>"u"||typeof document>"u")return!1;try{if(!Boolean(window.RTCPeerConnection||window.RTCSessionDescription||window.RTCIceCandidate||navigator.mediaDevices))return i.logger.error("WebRTC is not supported in this browser / environment"),!1}catch(U){return i.logger.error("Exception thrown when trying to access WebRTC",U),!1}return!0}function K(U,C,A){if(!P())return null;const T=A?A.forceTURN:!1,X={client:U,roomId:C,invitee:A==null?void 0:A.invitee,turnServers:U.getTurnServers(),forceTURN:U.forceTURN||T,opponentDeviceId:A==null?void 0:A.opponentDeviceId,opponentSessionId:A==null?void 0:A.opponentSessionId,groupCallId:A==null?void 0:A.groupCallId},ne=new H(X);return U.reEmitter.reEmit(ne,Object.values(k)),ne}return ot}var io={},ZW=Ae;Object.defineProperty(io,"__esModule",{value:!0});io.AutoDiscoveryAction=io.AutoDiscovery=void 0;var gn=ZW(Ue),Dr=Ge(),G0=Rr;let un;io.AutoDiscoveryAction=un;(function(e){e.SUCCESS="SUCCESS",e.IGNORE="IGNORE",e.PROMPT="PROMPT",e.FAIL_PROMPT="FAIL_PROMPT",e.FAIL_ERROR="FAIL_ERROR"})(un||(io.AutoDiscoveryAction=un={}));var er;(function(e){e.Invalid="Invalid homeserver discovery response",e.GenericFailure="Failed to get autodiscovery configuration from server",e.InvalidHsBaseUrl="Invalid base_url for m.homeserver",e.InvalidHomeserver="Homeserver URL does not appear to be a valid Matrix homeserver",e.InvalidIsBaseUrl="Invalid base_url for m.identity_server",e.InvalidIdentityServer="Identity server URL does not appear to be a valid identity server",e.InvalidIs="Invalid identity server discovery response",e.MissingWellknown="No .well-known JSON file found",e.InvalidJson="Invalid JSON"})(er||(er={}));class Qe{static async fromDiscoveryConfig(t){var n;const r={"m.homeserver":{state:Qe.FAIL_ERROR,error:Qe.ERROR_INVALID,base_url:null},"m.identity_server":{state:Qe.PROMPT,error:null,base_url:null}};if(!t||!t["m.homeserver"])return Dr.logger.error("No m.homeserver key in config"),r["m.homeserver"].state=Qe.FAIL_PROMPT,r["m.homeserver"].error=Qe.ERROR_INVALID,Promise.resolve(r);if(!t["m.homeserver"].base_url)return Dr.logger.error("No m.homeserver base_url in config"),r["m.homeserver"].state=Qe.FAIL_PROMPT,r["m.homeserver"].error=Qe.ERROR_INVALID_HS_BASE_URL,Promise.resolve(r);const i=this.sanitizeWellKnownUrl(t["m.homeserver"].base_url);if(!i)return Dr.logger.error("Invalid base_url for m.homeserver"),r["m.homeserver"].error=Qe.ERROR_INVALID_HS_BASE_URL,Promise.resolve(r);const o=await this.fetchWellKnownObject(`${i}/_matrix/client/versions`);if(!o||!((n=o.raw)!==null&&n!==void 0&&n.versions))return Dr.logger.error("Invalid /versions response"),r["m.homeserver"].error=Qe.ERROR_INVALID_HOMESERVER,r["m.homeserver"].base_url=i,Promise.resolve(r);r["m.homeserver"]={state:Qe.SUCCESS,error:null,base_url:i};let a="";if(t["m.identity_server"]){const c={"m.homeserver":r["m.homeserver"],"m.identity_server":{state:Qe.FAIL_PROMPT,error:Qe.ERROR_INVALID_IS,base_url:null}};if(a=this.sanitizeWellKnownUrl(t["m.identity_server"].base_url),!a)return Dr.logger.error("Invalid base_url for m.identity_server"),c["m.identity_server"].error=Qe.ERROR_INVALID_IS_BASE_URL,Promise.resolve(c);const f=await this.fetchWellKnownObject(`${a}/_matrix/identity/api/v1`);if(!(f!=null&&f.raw)||f.action!==un.SUCCESS)return Dr.logger.error("Invalid /api/v1 response"),c["m.identity_server"].error=Qe.ERROR_INVALID_IDENTITY_SERVER,c["m.identity_server"].base_url=a,Promise.resolve(c)}return a&&a.toString().length>0&&(r["m.identity_server"]={state:Qe.SUCCESS,error:null,base_url:a}),Object.keys(t).forEach(c=>{if(c==="m.homeserver"||c==="m.identity_server"){const f=["error","state","base_url"];for(const v of Object.keys(t[c]))f.includes(v)||(r[c][v]=t[c][v])}else r[c]=t[c]}),Promise.resolve(r)}static async findClientConfig(t){if(!t||typeof t!="string"||t.length===0)throw new Error("'domain' must be a string of non-zero length");const n={"m.homeserver":{state:Qe.FAIL_ERROR,error:Qe.ERROR_INVALID,base_url:null},"m.identity_server":{state:Qe.PROMPT,error:null,base_url:null}},r=await this.fetchWellKnownObject(`https://${t}/.well-known/matrix/client`);return!r||r.action!==un.SUCCESS?(Dr.logger.error("No response or error when parsing .well-known"),r.reason&&Dr.logger.error(r.reason),r.action===un.IGNORE?n["m.homeserver"]={state:Qe.PROMPT,error:null,base_url:null}:(n["m.homeserver"].state=Qe.FAIL_PROMPT,n["m.homeserver"].error=Qe.ERROR_INVALID),Promise.resolve(n)):Qe.fromDiscoveryConfig(r.raw)}static async getRawClientConfig(t){if(!t||typeof t!="string"||t.length===0)throw new Error("'domain' must be a string of non-zero length");const n=await this.fetchWellKnownObject(`https://${t}/.well-known/matrix/client`);return n?n.raw||{}:{}}static sanitizeWellKnownUrl(t){if(!t)return!1;try{var n;let r;try{r=new URL(t)}catch(c){Dr.logger.error("Could not parse url",c)}if(!((n=r)!==null&&n!==void 0&&n.hostname)||r.protocol!=="http:"&&r.protocol!=="https:")return!1;const i=r.port?`:${r.port}`:"",o=r.pathname?r.pathname:"";let a=`${r.protocol}//${r.hostname}${i}${o}`;return a.endsWith("/")&&(a=a.substring(0,a.length-1)),a}catch(r){return Dr.logger.error(r),!1}}static fetch(t,n){return this.fetchFn?this.fetchFn(t,n):$e.fetch(t,n)}static setFetchFn(t){Qe.fetchFn=t}static async fetchWellKnownObject(t){let n;try{if(n=await Qe.fetch(t,{method:G0.Method.Get,signal:(0,G0.timeoutSignal)(5e3)}),n.status===404)return{raw:{},action:un.IGNORE,reason:Qe.ERROR_MISSING_WELLKNOWN};if(!n.ok)return{raw:{},action:un.FAIL_PROMPT,reason:"General failure"}}catch(r){const i=r;let o="";return typeof i=="object"&&(o=i==null?void 0:i.message),{error:i,raw:{},action:un.FAIL_PROMPT,reason:o||"General failure"}}try{return{raw:await n.json(),action:un.SUCCESS}}catch(r){const i=r;return{error:i,raw:{},action:un.FAIL_PROMPT,reason:(i==null?void 0:i.name)==="SyntaxError"?Qe.ERROR_INVALID_JSON:Qe.ERROR_INVALID}}}}io.AutoDiscovery=Qe;(0,gn.default)(Qe,"ERROR_INVALID",er.Invalid);(0,gn.default)(Qe,"ERROR_GENERIC_FAILURE",er.GenericFailure);(0,gn.default)(Qe,"ERROR_INVALID_HS_BASE_URL",er.InvalidHsBaseUrl);(0,gn.default)(Qe,"ERROR_INVALID_HOMESERVER",er.InvalidHomeserver);(0,gn.default)(Qe,"ERROR_INVALID_IS_BASE_URL",er.InvalidIsBaseUrl);(0,gn.default)(Qe,"ERROR_INVALID_IDENTITY_SERVER",er.InvalidIdentityServer);(0,gn.default)(Qe,"ERROR_INVALID_IS",er.InvalidIs);(0,gn.default)(Qe,"ERROR_MISSING_WELLKNOWN",er.MissingWellknown);(0,gn.default)(Qe,"ERROR_INVALID_JSON",er.InvalidJson);(0,gn.default)(Qe,"ALL_ERRORS",Object.keys(er));(0,gn.default)(Qe,"FAIL_ERROR",un.FAIL_ERROR);(0,gn.default)(Qe,"FAIL_PROMPT",un.FAIL_PROMPT);(0,gn.default)(Qe,"PROMPT",un.PROMPT);(0,gn.default)(Qe,"SUCCESS",un.SUCCESS);(0,gn.default)(Qe,"fetchFn",void 0);var ct={},Mp,z0;function Hf(){if(z0)return Mp;z0=1;for(var e=/[\\\"\x00-\x1F]/g,t={},n=0;n<32;++n)t[String.fromCharCode(n)]="\\U"+("0000"+n.toString(16)).slice(-4).toUpperCase();t["\b"]="\\b",t["	"]="\\t",t[`
     85 `]="\\n",t["\f"]="\\f",t["\r"]="\\r",t['"']='\\"',t["\\"]="\\\\";function r(c){return e.lastIndex=0,c.replace(e,function(f){return t[f]})}function i(c){switch(typeof c){case"string":return'"'+r(c)+'"';case"number":return isFinite(c)?c:"null";case"boolean":return c;case"object":return c===null?"null":Array.isArray(c)?o(c):a(c);default:throw new Error("Cannot stringify: "+typeof c)}}function o(c){for(var f="[",v="",s=0;s<c.length;++s)v+=f,f=",",v+=i(c[s]);return f!=","?"[]":v+"]"}function a(c){var f="{",v="",s=Object.keys(c);s.sort();for(var g=0;g<s.length;++g){var y=s[g];v+=f+'"'+r(y)+'":',f=",",v+=i(c[y])}return f!=","?"{}":v+"}"}return Mp={stringify:i},Mp}var tk=Ae;Object.defineProperty(ct,"__esModule",{value:!0});ct.OLM_ALGORITHM=ct.MEGOLM_BACKUP_ALGORITHM=o3=ct.MEGOLM_ALGORITHM=void 0;ct.decodeBase64=g3;ct.encodeBase64=rk;ct.encodeUnpaddedBase64=p3;ct.encryptMessageForDevice=a3;ct.ensureOlmSessionsForDevices=u3;ct.getExistingOlmSessions=l3;ct.isOlmEncrypted=h3;ct.pkSign=d3;ct.pkVerify=f3;ct.verifySignature=nk;var e3=tk(Ue),e_=tk(Hf()),Zi=Ge(),t3=xe;function Y0(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),n.push.apply(n,r)}return n}function n3(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?Y0(Object(n),!0).forEach(function(r){(0,e3.default)(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Y0(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}var wu;(function(e){e.Olm="m.olm.v1.curve25519-aes-sha2",e.Megolm="m.megolm.v1.aes-sha2",e.MegolmBackup="m.megolm_backup.v1.curve25519-aes-sha2"})(wu||(wu={}));const r3=wu.Olm;ct.OLM_ALGORITHM=r3;const i3=wu.Megolm;var o3=ct.MEGOLM_ALGORITHM=i3;const s3=wu.MegolmBackup;ct.MEGOLM_BACKUP_ALGORITHM=s3;async function a3(e,t,n,r,i,o,a){const c=o.getIdentityKey(),f=await r.getSessionIdForDevice(c);if(f===null){Zi.logger.log(`[olmlib.encryptMessageForDevice] Unable to find Olm session for device ${i}:${o.deviceId}`);return}Zi.logger.log(`[olmlib.encryptMessageForDevice] Using Olm session ${f} for device ${i}:${o.deviceId}`);const v=n3({sender:t,sender_device:n,keys:{ed25519:r.deviceEd25519Key},recipient:i,recipient_keys:{ed25519:o.getFingerprint()}},a);e[c]=await r.encryptMessage(c,f,JSON.stringify(v))}async function l3(e,t,n){const r={},i={},o=[];for(const[a,c]of Object.entries(n))for(const f of c){const v=f.deviceId,s=f.getIdentityKey();o.push((async()=>{const g=await e.getSessionIdForDevice(s,!0);g===null?(r[a]=r[a]||[],r[a].push(f)):(i[a]=i[a]||{},i[a][v]={device:f,sessionId:g})})())}return await Promise.all(o),[r,i]}async function u3(e,t,n,r=!1,i,o,a=Zi.logger){const c=[],f={},v={};for(const[,p]of Object.entries(n))for(const _ of p){const u=_.getIdentityKey();u!==e.deviceCurve25519Key&&(e.sessionsInProgress[u]||(e.sessionsInProgress[u]=new Promise(l=>{v[u]=d=>{delete e.sessionsInProgress[u],l(d)}})))}for(const[p,_]of Object.entries(n)){f[p]={};for(const u of _){const l=u.deviceId,d=u.getIdentityKey();if(d===e.deviceCurve25519Key){a.info("Attempted to start session with ourself! Ignoring"),f[p][l]={device:u,sessionId:null};continue}const h=`for ${d} (${p}:${l})`,w=await e.getSessionIdForDevice(d,!!v[d],a);w!==null&&v[d]&&v[d](),(w===null||r)&&(r?a.info(`Forcing new Olm session ${h}`):a.info(`Making new Olm session ${h}`),c.push([p,l])),f[p][l]={device:u,sessionId:w}}}if(c.length===0)return f;const s="signed_curve25519";let g,y=`one-time keys for ${c.length} devices`;try{a.debug(`Claiming ${y}`),g=await t.claimOneTimeKeys(c,s,i),a.debug(`Claimed ${y}`)}catch(p){for(const _ of Object.values(v))_();throw a.log(`Failed to claim ${y}`,p,c),p}o&&"failures"in g&&o.push(...Object.keys(g.failures));const S=g.one_time_keys||{},m=[];for(const[p,_]of Object.entries(n)){const u=S[p]||{};for(const l of _){const d=l.deviceId,h=l.getIdentityKey();if(h===e.deviceCurve25519Key||f[p][d].sessionId&&!r)continue;const w=u[d]||{};let E=null;for(const I in w)I.indexOf(s+":")===0&&(E=w[I]);if(!E){a.warn(`No one-time keys (alg=${s}) for device ${p}:${d}`),v[h]&&v[h]();continue}m.push(c3(e,E,p,l).then(I=>{v[h]&&v[h](I??void 0),f[p][d].sessionId=I},I=>{throw v[h]&&v[h](),I}))}}return y=`Olm sessions for ${m.length} devices`,a.debug(`Starting ${y}`),await Promise.all(m),a.debug(`Started ${y}`),f}async function c3(e,t,n,r){const i=r.deviceId;try{await nk(e,t,n,i,r.getFingerprint())}catch(a){return Zi.logger.error("Unable to verify signature on one-time key for device "+n+":"+i+":",a),null}let o;try{o=await e.createOutboundSession(r.getIdentityKey(),t.key)}catch(a){return Zi.logger.error("Error starting olm session with device "+n+":"+i+": "+a),null}return Zi.logger.log("Started new olm sessionid "+o+" for device "+n+":"+i),o}async function nk(e,t,n,r,i){const o="ed25519:"+r,f=((t.signatures||{})[n]||{})[o];if(!f)throw Error("No signature");const v=Object.assign({},t);"unsigned"in v&&delete v.unsigned,delete v.signatures;const s=e_.default.stringify(v);e.verifySignature(i,s,f)}function d3(e,t,n,r){let i=!1;if(t instanceof Uint8Array){const c=new $e.Olm.PkSigning;r=c.init_with_seed(t),t=c,i=!0}const o=e.signatures||{};delete e.signatures;const a=e.unsigned;e.unsigned&&delete e.unsigned;try{const c=o[n]||{};return o[n]=c,c["ed25519:"+r]=t.sign(e_.default.stringify(e))}finally{e.signatures=o,a&&(e.unsigned=a),i&&t.free()}}function f3(e,t,n){const r="ed25519:"+t;if(!(e.signatures&&e.signatures[n]&&e.signatures[n][r]))throw new Error("No signature");const i=e.signatures[n][r],o=new $e.Olm.Utility,a=e.signatures;delete e.signatures;const c=e.unsigned;e.unsigned&&delete e.unsigned;try{o.ed25519_verify(t,e_.default.stringify(e),i)}finally{e.signatures=a,c&&(e.unsigned=c),o.free()}}function h3(e){return e.getSenderKey()?e.getWireType()!==t3.EventType.RoomMessageEncrypted||!["m.olm.v1.curve25519-aes-sha2"].includes(e.getWireContent().algorithm)?(Zi.logger.error("Event was not encrypted using an appropriate algorithm"),!1):!0:(Zi.logger.error("Event has no sender key (not encrypted?)"),!1)}function rk(e){return Buffer.from(e).toString("base64")}function p3(e){return rk(e).replace(/=+$/g,"")}function g3(e){return Buffer.from(e,"base64")}var il={},ir={},ol={},Q0;function v3(){if(Q0)return ol;Q0=1,Object.defineProperty(ol,"__esModule",{value:!0}),ol.LocalStorageCryptoStore=void 0;var e=Ge(),t=_a;const n="crypto.",r=n+"account",i=n+"cross_signing_keys",o=n+"notified_error_devices",a=n+"device_data",c=n+"inboundgroupsessions/",f=n+"inboundgroupsessions.withheld/",v=n+"rooms/",s=n+"sessionsneedingbackup";function g(d){return n+"sessions/"+d}function y(d){return n+"session.problems/"+d}function S(d,h){return c+d+"/"+h}function m(d,h){return f+d+"/"+h}function p(d){return v+d}class _ extends t.MemoryCryptoStore{static exists(h){const w=h.length;for(let I=0;I<w;I++){var E;if((E=h.key(I))!==null&&E!==void 0&&E.startsWith(n))return!0}return!1}constructor(h){super(),this.store=h}countEndToEndSessions(h,w){let E=0;for(let k=0;k<this.store.length;++k){var I;(I=this.store.key(k))!==null&&I!==void 0&&I.startsWith(g(""))&&++E}w(E)}_getEndToEndSessions(h){const w=u(this.store,g(h)),E={};for(const[I,k]of Object.entries(w||{}))typeof k=="string"?E[I]={session:k}:E[I]=k;return E}getEndToEndSession(h,w,E,I){const k=this._getEndToEndSessions(h);I(k[w]||{})}getEndToEndSessions(h,w,E){E(this._getEndToEndSessions(h)||{})}getAllEndToEndSessions(h,w){for(let I=0;I<this.store.length;++I){var E;if((E=this.store.key(I))!==null&&E!==void 0&&E.startsWith(g(""))){const k=this.store.key(I).split("/")[1];for(const M of Object.values(this._getEndToEndSessions(k)))w(M)}}}storeEndToEndSession(h,w,E,I){const k=this._getEndToEndSessions(h)||{};k[w]=E,l(this.store,g(h),k)}async storeEndToEndSessionProblem(h,w,E){const I=y(h),k=u(this.store,I)||[];k.push({type:w,fixed:E,time:Date.now()}),k.sort((M,L)=>M.time-L.time),l(this.store,I,k)}async getEndToEndSessionProblem(h,w){const E=y(h),I=u(this.store,E)||[];if(!I.length)return null;const k=I[I.length-1];for(const M of I)if(M.time>w)return Object.assign({},M,{fixed:k.fixed});return k.fixed?null:k}async filterOutNotifiedErrorDevices(h){const w=u(this.store,o)||{},E=[];for(const I of h){const{userId:k,deviceInfo:M}=I;k in w?M.deviceId in w[k]||(E.push(I),w[k][M.deviceId]=!0):(E.push(I),w[k]={[M.deviceId]:!0})}return l(this.store,o,w),E}getEndToEndInboundGroupSession(h,w,E,I){I(u(this.store,S(h,w)),u(this.store,m(h,w)))}getAllEndToEndInboundGroupSessions(h,w){for(let E=0;E<this.store.length;++E){const I=this.store.key(E);I!=null&&I.startsWith(c)&&w({senderKey:I.slice(c.length,c.length+43),sessionId:I.slice(c.length+44),sessionData:u(this.store,I)})}w(null)}addEndToEndInboundGroupSession(h,w,E,I){u(this.store,S(h,w))||this.storeEndToEndInboundGroupSession(h,w,E,I)}storeEndToEndInboundGroupSession(h,w,E,I){l(this.store,S(h,w),E)}storeEndToEndInboundGroupSessionWithheld(h,w,E,I){l(this.store,m(h,w),E)}getEndToEndDeviceData(h,w){w(u(this.store,a))}storeEndToEndDeviceData(h,w){l(this.store,a,h)}storeEndToEndRoom(h,w,E){l(this.store,p(h),w)}getEndToEndRooms(h,w){const E={},I=p("");for(let k=0;k<this.store.length;++k){const M=this.store.key(k);if(M!=null&&M.startsWith(I)){const L=M.slice(I.length);E[L]=u(this.store,M)}}w(E)}getSessionsNeedingBackup(h){const w=u(this.store,s)||{},E=[];for(const I in w)if(Object.prototype.hasOwnProperty.call(w,I)){const k=I.slice(0,43),M=I.slice(44);if(this.getEndToEndInboundGroupSession(k,M,null,L=>{E.push({senderKey:k,sessionId:M,sessionData:L})}),h&&E.length>=h)break}return Promise.resolve(E)}countSessionsNeedingBackup(){const h=u(this.store,s)||{};return Promise.resolve(Object.keys(h).length)}unmarkSessionsNeedingBackup(h){const w=u(this.store,s)||{};for(const E of h)delete w[E.senderKey+"/"+E.sessionId];return l(this.store,s,w),Promise.resolve()}markSessionsNeedingBackup(h){const w=u(this.store,s)||{};for(const E of h)w[E.senderKey+"/"+E.sessionId]=!0;return l(this.store,s,w),Promise.resolve()}deleteAllData(){return this.store.removeItem(r),Promise.resolve()}getAccount(h,w){const E=u(this.store,r);w(E)}storeAccount(h,w){l(this.store,r,w)}getCrossSigningKeys(h,w){const E=u(this.store,i);w(E)}getSecretStorePrivateKey(h,w,E){const I=u(this.store,n+`ssss_cache.${E}`);w(I)}storeCrossSigningKeys(h,w){l(this.store,i,w)}storeSecretStorePrivateKey(h,w,E){l(this.store,n+`ssss_cache.${w}`,E)}doTxn(h,w,E){return Promise.resolve(E(null))}}ol.LocalStorageCryptoStore=_;function u(d,h){try{return JSON.parse(d.getItem(h))}catch(w){e.logger.log("Error: Failed to get key %s: %s",h,w.message),e.logger.log(w.stack)}return null}function l(d,h,w){d.setItem(h,JSON.stringify(w))}return ol}var Ri={},J0;function m3(){if(J0)return Ri;J0=1;var e=Ae;Object.defineProperty(Ri,"__esModule",{value:!0}),Ri.VERSION=Ri.Backend=void 0,Ri.upgradeDatabase=v;var t=e(Ue),n=Ge(),r=o(lt());function i(S){if(typeof WeakMap!="function")return null;var m=new WeakMap,p=new WeakMap;return(i=function(_){return _?p:m})(S)}function o(S,m){if(!m&&S&&S.__esModule)return S;if(S===null||typeof S!="object"&&typeof S!="function")return{default:S};var p=i(m);if(p&&p.has(S))return p.get(S);var _={},u=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var l in S)if(l!=="default"&&Object.prototype.hasOwnProperty.call(S,l)){var d=u?Object.getOwnPropertyDescriptor(S,l):null;d&&(d.get||d.set)?Object.defineProperty(_,l,d):_[l]=S[l]}return _.default=S,p&&p.set(S,_),_}class a{constructor(m){this.db=m,(0,t.default)(this,"nextTxnId",0),m.onversionchange=()=>{n.logger.log(`versionchange for indexeddb ${this.db.name}: closing`),m.close()}}async startup(){return this}async deleteAllData(){throw Error("This is not implemented, call IDBFactory::deleteDatabase(dbName) instead.")}getOrAddOutgoingRoomKeyRequest(m){const p=m.requestBody;return new Promise((_,u)=>{const l=this.db.transaction("outgoingRoomKeyRequests","readwrite");l.onerror=u,this._getOutgoingRoomKeyRequest(l,p,d=>{if(d){n.logger.log(`already have key request outstanding for ${p.room_id} / ${p.session_id}: not sending another`),_(d);return}n.logger.log(`enqueueing key request for ${p.room_id} / `+p.session_id),l.oncomplete=()=>{_(m)},l.objectStore("outgoingRoomKeyRequests").add(m)})})}getOutgoingRoomKeyRequest(m){return new Promise((p,_)=>{const u=this.db.transaction("outgoingRoomKeyRequests","readonly");u.onerror=_,this._getOutgoingRoomKeyRequest(u,m,l=>{p(l)})})}_getOutgoingRoomKeyRequest(m,p,_){const d=m.objectStore("outgoingRoomKeyRequests").index("session").openCursor([p.room_id,p.session_id]);d.onsuccess=()=>{const h=d.result;if(!h){_(null);return}const w=h.value;if(r.deepCompare(w.requestBody,p)){_(w);return}h.continue()}}getOutgoingRoomKeyRequestByState(m){if(m.length===0)return Promise.resolve(null);let p=0,_;function u(){const E=this.result;if(E){_=E.value;return}if(p++,p>=m.length)return;const I=m[p],k=this.source.openCursor(I);k.onsuccess=u}const l=this.db.transaction("outgoingRoomKeyRequests","readonly"),d=l.objectStore("outgoingRoomKeyRequests"),h=m[p],w=d.index("state").openCursor(h);return w.onsuccess=u,y(l).then(()=>_)}getAllOutgoingRoomKeyRequestsByState(m){return new Promise((p,_)=>{const h=this.db.transaction("outgoingRoomKeyRequests","readonly").objectStore("outgoingRoomKeyRequests").index("state").getAll(m);h.onsuccess=()=>p(h.result),h.onerror=()=>_(h.error)})}getOutgoingRoomKeyRequestsByTarget(m,p,_){let u=0;const l=[];function d(){const k=this.result;if(k){const M=k.value;M.recipients.some(L=>L.userId===m&&L.deviceId===p)&&l.push(M),k.continue()}else{if(u++,u>=_.length)return;const M=_[u],L=this.source.openCursor(M);L.onsuccess=d}}const h=this.db.transaction("outgoingRoomKeyRequests","readonly"),w=h.objectStore("outgoingRoomKeyRequests"),E=_[u],I=w.index("state").openCursor(E);return I.onsuccess=d,y(h).then(()=>l)}updateOutgoingRoomKeyRequest(m,p,_){let u=null;function l(){const w=this.result;if(!w)return;const E=w.value;if(E.state!=p){n.logger.warn(`Cannot update room key request from ${p} as it was already updated to ${E.state}`);return}Object.assign(E,_),w.update(E),u=E}const d=this.db.transaction("outgoingRoomKeyRequests","readwrite"),h=d.objectStore("outgoingRoomKeyRequests").openCursor(m);return h.onsuccess=l,y(d).then(()=>u)}deleteOutgoingRoomKeyRequest(m,p){const _=this.db.transaction("outgoingRoomKeyRequests","readwrite"),u=_.objectStore("outgoingRoomKeyRequests").openCursor(m);return u.onsuccess=()=>{const l=u.result;if(!l)return;const d=l.value;if(d.state!=p){n.logger.warn(`Cannot delete room key request in state ${d.state} (expected ${p})`);return}l.delete()},y(_)}getAccount(m,p){const u=m.objectStore("account").get("-");u.onsuccess=function(){try{p(u.result||null)}catch(l){g(m,l)}}}storeAccount(m,p){m.objectStore("account").put(p,"-")}getCrossSigningKeys(m,p){const u=m.objectStore("account").get("crossSigningKeys");u.onsuccess=function(){try{p(u.result||null)}catch(l){g(m,l)}}}getSecretStorePrivateKey(m,p,_){const l=m.objectStore("account").get(`ssss_cache:${_}`);l.onsuccess=function(){try{p(l.result||null)}catch(d){g(m,d)}}}storeCrossSigningKeys(m,p){m.objectStore("account").put(p,"crossSigningKeys")}storeSecretStorePrivateKey(m,p,_){m.objectStore("account").put(_,`ssss_cache:${p}`)}countEndToEndSessions(m,p){const u=m.objectStore("sessions").count();u.onsuccess=function(){try{p(u.result)}catch(l){g(m,l)}}}getEndToEndSessions(m,p,_){const d=p.objectStore("sessions").index("deviceKey").openCursor(m),h={};d.onsuccess=function(){const w=d.result;if(w)h[w.value.sessionId]={session:w.value.session,lastReceivedMessageTs:w.value.lastReceivedMessageTs},w.continue();else try{_(h)}catch(E){g(p,E)}}}getEndToEndSession(m,p,_,u){const d=_.objectStore("sessions").get([m,p]);d.onsuccess=function(){try{d.result?u({session:d.result.session,lastReceivedMessageTs:d.result.lastReceivedMessageTs}):u(null)}catch(h){g(_,h)}}}getAllEndToEndSessions(m,p){const u=m.objectStore("sessions").openCursor();u.onsuccess=function(){try{const l=u.result;l?(p(l.value),l.continue()):p(null)}catch(l){g(m,l)}}}storeEndToEndSession(m,p,_,u){u.objectStore("sessions").put({deviceKey:m,sessionId:p,session:_.session,lastReceivedMessageTs:_.lastReceivedMessageTs})}async storeEndToEndSessionProblem(m,p,_){const u=this.db.transaction("session_problems","readwrite");u.objectStore("session_problems").put({deviceKey:m,type:p,fixed:_,time:Date.now()}),await y(u)}async getEndToEndSessionProblem(m,p){let _=null;const u=this.db.transaction("session_problems","readwrite"),h=u.objectStore("session_problems").index("deviceKey").getAll(m);return h.onsuccess=()=>{const w=h.result;if(!w.length){_=null;return}w.sort((I,k)=>I.time-k.time);const E=w[w.length-1];for(const I of w)if(I.time>p){_=Object.assign({},I,{fixed:E.fixed});return}E.fixed?_=null:_=E},await y(u),_}async filterOutNotifiedErrorDevices(m){const _=this.db.transaction("notified_error_devices","readwrite").objectStore("notified_error_devices"),u=[];return await Promise.all(m.map(l=>new Promise(d=>{const{userId:h,deviceInfo:w}=l,E=_.get([h,w.deviceId]);E.onsuccess=function(){E.result||(_.put({userId:h,deviceId:w.deviceId}),u.push(l)),d()}}))),u}getEndToEndInboundGroupSession(m,p,_,u){let l=!1,d=!1;const w=_.objectStore("inbound_group_sessions").get([m,p]);w.onsuccess=function(){try{w.result?l=w.result.session:l=null,d!==!1&&u(l,d)}catch(k){g(_,k)}};const I=_.objectStore("inbound_group_sessions_withheld").get([m,p]);I.onsuccess=function(){try{I.result?d=I.result.session:d=null,l!==!1&&u(l,d)}catch(k){g(_,k)}}}getAllEndToEndInboundGroupSessions(m,p){const u=m.objectStore("inbound_group_sessions").openCursor();u.onsuccess=function(){const l=u.result;if(l){try{p({senderKey:l.value.senderCurve25519Key,sessionId:l.value.sessionId,sessionData:l.value.session})}catch(d){g(m,d)}l.continue()}else try{p(null)}catch(d){g(m,d)}}}addEndToEndInboundGroupSession(m,p,_,u){const d=u.objectStore("inbound_group_sessions").add({senderCurve25519Key:m,sessionId:p,session:_});d.onerror=h=>{var w;((w=d.error)===null||w===void 0?void 0:w.name)==="ConstraintError"?(h.stopPropagation(),h.preventDefault(),n.logger.log("Ignoring duplicate inbound group session: "+m+" / "+p)):g(u,new Error("Failed to add inbound group session: "+d.error))}}storeEndToEndInboundGroupSession(m,p,_,u){u.objectStore("inbound_group_sessions").put({senderCurve25519Key:m,sessionId:p,session:_})}storeEndToEndInboundGroupSessionWithheld(m,p,_,u){u.objectStore("inbound_group_sessions_withheld").put({senderCurve25519Key:m,sessionId:p,session:_})}getEndToEndDeviceData(m,p){const u=m.objectStore("device_data").get("-");u.onsuccess=function(){try{p(u.result||null)}catch(l){g(m,l)}}}storeEndToEndDeviceData(m,p){p.objectStore("device_data").put(m,"-")}storeEndToEndRoom(m,p,_){_.objectStore("rooms").put(p,m)}getEndToEndRooms(m,p){const _={},l=m.objectStore("rooms").openCursor();l.onsuccess=function(){const d=l.result;if(d)_[d.key]=d.value,d.continue();else try{p(_)}catch(h){g(m,h)}}}getSessionsNeedingBackup(m){return new Promise((p,_)=>{const u=[],l=this.db.transaction(["sessions_needing_backup","inbound_group_sessions"],"readonly");l.onerror=_,l.oncomplete=function(){p(u)};const d=l.objectStore("sessions_needing_backup"),h=l.objectStore("inbound_group_sessions"),w=d.openCursor();w.onsuccess=function(){const E=w.result;if(E){const I=h.get(E.key);I.onsuccess=function(){u.push({senderKey:I.result.senderCurve25519Key,sessionId:I.result.sessionId,sessionData:I.result.session})},(!m||u.length<m)&&E.continue()}}})}countSessionsNeedingBackup(m){m||(m=this.db.transaction("sessions_needing_backup","readonly"));const p=m.objectStore("sessions_needing_backup");return new Promise((_,u)=>{const l=p.count();l.onerror=u,l.onsuccess=()=>_(l.result)})}async unmarkSessionsNeedingBackup(m,p){p||(p=this.db.transaction("sessions_needing_backup","readwrite"));const _=p.objectStore("sessions_needing_backup");await Promise.all(m.map(u=>new Promise((l,d)=>{const h=_.delete([u.senderKey,u.sessionId]);h.onsuccess=l,h.onerror=d})))}async markSessionsNeedingBackup(m,p){p||(p=this.db.transaction("sessions_needing_backup","readwrite"));const _=p.objectStore("sessions_needing_backup");await Promise.all(m.map(u=>new Promise((l,d)=>{const h=_.put({senderCurve25519Key:u.senderKey,sessionId:u.sessionId});h.onsuccess=l,h.onerror=d})))}addSharedHistoryInboundGroupSession(m,p,_,u){u||(u=this.db.transaction("shared_history_inbound_group_sessions","readwrite"));const l=u.objectStore("shared_history_inbound_group_sessions"),d=l.get([m]);d.onsuccess=()=>{const{sessions:h}=d.result||{sessions:[]};h.push([p,_]),l.put({roomId:m,sessions:h})}}getSharedHistoryInboundGroupSessions(m,p){p||(p=this.db.transaction("shared_history_inbound_group_sessions","readonly"));const u=p.objectStore("shared_history_inbound_group_sessions").get([m]);return new Promise((l,d)=>{u.onsuccess=()=>{const{sessions:h}=u.result||{sessions:[]};l(h)},u.onerror=d})}addParkedSharedHistory(m,p,_){_||(_=this.db.transaction("parked_shared_history","readwrite"));const u=_.objectStore("parked_shared_history"),l=u.get([m]);l.onsuccess=()=>{const{parked:d}=l.result||{parked:[]};d.push(p),u.put({roomId:m,parked:d})}}takeParkedSharedHistory(m,p){p||(p=this.db.transaction("parked_shared_history","readwrite"));const _=p.objectStore("parked_shared_history").openCursor(m);return new Promise((u,l)=>{_.onsuccess=()=>{const d=_.result;if(!d){u([]);return}const h=d.value;d.delete(),u(h)},_.onerror=l})}doTxn(m,p,_,u=n.logger){const l=this.db.transaction(p,m),d=y(l),h=_(l);return d.then(()=>h)}}Ri.Backend=a;const c=[S=>{s(S)},S=>{S.createObjectStore("account")},S=>{S.createObjectStore("sessions",{keyPath:["deviceKey","sessionId"]}).createIndex("deviceKey","deviceKey")},S=>{S.createObjectStore("inbound_group_sessions",{keyPath:["senderCurve25519Key","sessionId"]})},S=>{S.createObjectStore("device_data")},S=>{S.createObjectStore("rooms")},S=>{S.createObjectStore("sessions_needing_backup",{keyPath:["senderCurve25519Key","sessionId"]})},S=>{S.createObjectStore("inbound_group_sessions_withheld",{keyPath:["senderCurve25519Key","sessionId"]})},S=>{S.createObjectStore("session_problems",{keyPath:["deviceKey","time"]}).createIndex("deviceKey","deviceKey"),S.createObjectStore("notified_error_devices",{keyPath:["userId","deviceId"]})},S=>{S.createObjectStore("shared_history_inbound_group_sessions",{keyPath:["roomId"]})},S=>{S.createObjectStore("parked_shared_history",{keyPath:["roomId"]})}],f=c.length;Ri.VERSION=f;function v(S,m){n.logger.log(`Upgrading IndexedDBCryptoStore from version ${m} to ${f}`),c.forEach((p,_)=>{m<=_&&p(S)})}function s(S){const m=S.createObjectStore("outgoingRoomKeyRequests",{keyPath:"requestId"});m.createIndex("session",["requestBody.room_id","requestBody.session_id"]),m.createIndex("state","state")}function g(S,m){S._mx_abortexception=m;try{S.abort()}catch{}}function y(S){return new Promise((m,p)=>{S.oncomplete=()=>{S._mx_abortexception!==void 0&&p(S._mx_abortexception),m(null)},S.onerror=_=>{S._mx_abortexception!==void 0?p(S._mx_abortexception):(n.logger.log("Error performing indexeddb txn",_),p(S.error))},S.onabort=_=>{S._mx_abortexception!==void 0?p(S._mx_abortexception):(n.logger.log("Error performing indexeddb txn",_),p(S.error))}})}return Ri}var xc={},X0;function ik(){if(X0)return xc;X0=1,Object.defineProperty(xc,"__esModule",{value:!0}),xc.exists=e;function e(t,n){return new Promise((r,i)=>{let o=!0;const a=t.open(n);a.onupgradeneeded=()=>{o=!1},a.onblocked=()=>i(a.error),a.onsuccess=()=>{a.result.close(),o||t.deleteDatabase(n),r(o)},a.onerror=()=>i(a.error)})}return xc}var y3=Ae;Object.defineProperty(ir,"__esModule",{value:!0});ir.IndexedDBCryptoStore=void 0;var Sr=y3(Ue),qn=Ge(),_3=v3(),S3=_a,Dp=sk(m3()),Z0=jt,E3=sk(ik());function ok(e){if(typeof WeakMap!="function")return null;var t=new WeakMap,n=new WeakMap;return(ok=function(r){return r?n:t})(e)}function sk(e,t){if(!t&&e&&e.__esModule)return e;if(e===null||typeof e!="object"&&typeof e!="function")return{default:e};var n=ok(t);if(n&&n.has(e))return n.get(e);var r={},i=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var o in e)if(o!=="default"&&Object.prototype.hasOwnProperty.call(e,o)){var a=i?Object.getOwnPropertyDescriptor(e,o):null;a&&(a.get||a.set)?Object.defineProperty(r,o,a):r[o]=e[o]}return r.default=e,n&&n.set(e,r),r}class xn{static exists(t,n){return E3.exists(t,n)}constructor(t,n){this.indexedDB=t,this.dbName=n,(0,Sr.default)(this,"backendPromise",void 0),(0,Sr.default)(this,"backend",void 0)}startup(){return this.backendPromise?this.backendPromise:(this.backendPromise=new Promise((t,n)=>{if(!this.indexedDB){n(new Error("no indexeddb support available"));return}qn.logger.log(`connecting to indexeddb ${this.dbName}`);const r=this.indexedDB.open(this.dbName,Dp.VERSION);r.onupgradeneeded=i=>{const o=r.result,a=i.oldVersion;Dp.upgradeDatabase(o,a)},r.onblocked=()=>{qn.logger.log("can't yet open IndexedDBCryptoStore because it is open elsewhere")},r.onerror=i=>{qn.logger.log("Error connecting to indexeddb",i),n(r.error)},r.onsuccess=()=>{const i=r.result;qn.logger.log(`connected to indexeddb ${this.dbName}`),t(new Dp.Backend(i))}}).then(t=>t.doTxn("readonly",[xn.STORE_INBOUND_GROUP_SESSIONS,xn.STORE_INBOUND_GROUP_SESSIONS_WITHHELD],n=>{t.getEndToEndInboundGroupSession("","",n,()=>{})}).then(()=>t)).catch(t=>{if(t.name==="VersionError")throw qn.logger.warn("Crypto DB is too new for us to use!",t),new Z0.InvalidCryptoStoreError(Z0.InvalidCryptoStoreState.TooNew);qn.logger.warn(`unable to connect to indexeddb ${this.dbName}: falling back to localStorage store: ${t}`);try{return new _3.LocalStorageCryptoStore($e.localStorage)}catch(n){return qn.logger.warn(`unable to open localStorage: falling back to in-memory store: ${n}`),new S3.MemoryCryptoStore}}).then(t=>(this.backend=t,t)),this.backendPromise)}deleteAllData(){return new Promise((t,n)=>{if(!this.indexedDB){n(new Error("no indexeddb support available"));return}qn.logger.log(`Removing indexeddb instance: ${this.dbName}`);const r=this.indexedDB.deleteDatabase(this.dbName);r.onblocked=()=>{qn.logger.log("can't yet delete IndexedDBCryptoStore because it is open elsewhere")},r.onerror=i=>{qn.logger.log("Error deleting data from indexeddb",i),n(r.error)},r.onsuccess=()=>{qn.logger.log(`Removed indexeddb instance: ${this.dbName}`),t()}}).catch(t=>{qn.logger.warn(`unable to delete IndexedDBCryptoStore: ${t}`)})}getOrAddOutgoingRoomKeyRequest(t){return this.backend.getOrAddOutgoingRoomKeyRequest(t)}getOutgoingRoomKeyRequest(t){return this.backend.getOutgoingRoomKeyRequest(t)}getOutgoingRoomKeyRequestByState(t){return this.backend.getOutgoingRoomKeyRequestByState(t)}getAllOutgoingRoomKeyRequestsByState(t){return this.backend.getAllOutgoingRoomKeyRequestsByState(t)}getOutgoingRoomKeyRequestsByTarget(t,n,r){return this.backend.getOutgoingRoomKeyRequestsByTarget(t,n,r)}updateOutgoingRoomKeyRequest(t,n,r){return this.backend.updateOutgoingRoomKeyRequest(t,n,r)}deleteOutgoingRoomKeyRequest(t,n){return this.backend.deleteOutgoingRoomKeyRequest(t,n)}getAccount(t,n){this.backend.getAccount(t,n)}storeAccount(t,n){this.backend.storeAccount(t,n)}getCrossSigningKeys(t,n){this.backend.getCrossSigningKeys(t,n)}getSecretStorePrivateKey(t,n,r){this.backend.getSecretStorePrivateKey(t,n,r)}storeCrossSigningKeys(t,n){this.backend.storeCrossSigningKeys(t,n)}storeSecretStorePrivateKey(t,n,r){this.backend.storeSecretStorePrivateKey(t,n,r)}countEndToEndSessions(t,n){this.backend.countEndToEndSessions(t,n)}getEndToEndSession(t,n,r,i){this.backend.getEndToEndSession(t,n,r,i)}getEndToEndSessions(t,n,r){this.backend.getEndToEndSessions(t,n,r)}getAllEndToEndSessions(t,n){this.backend.getAllEndToEndSessions(t,n)}storeEndToEndSession(t,n,r,i){this.backend.storeEndToEndSession(t,n,r,i)}storeEndToEndSessionProblem(t,n,r){return this.backend.storeEndToEndSessionProblem(t,n,r)}getEndToEndSessionProblem(t,n){return this.backend.getEndToEndSessionProblem(t,n)}filterOutNotifiedErrorDevices(t){return this.backend.filterOutNotifiedErrorDevices(t)}getEndToEndInboundGroupSession(t,n,r,i){this.backend.getEndToEndInboundGroupSession(t,n,r,i)}getAllEndToEndInboundGroupSessions(t,n){this.backend.getAllEndToEndInboundGroupSessions(t,n)}addEndToEndInboundGroupSession(t,n,r,i){this.backend.addEndToEndInboundGroupSession(t,n,r,i)}storeEndToEndInboundGroupSession(t,n,r,i){this.backend.storeEndToEndInboundGroupSession(t,n,r,i)}storeEndToEndInboundGroupSessionWithheld(t,n,r,i){this.backend.storeEndToEndInboundGroupSessionWithheld(t,n,r,i)}storeEndToEndDeviceData(t,n){this.backend.storeEndToEndDeviceData(t,n)}getEndToEndDeviceData(t,n){this.backend.getEndToEndDeviceData(t,n)}storeEndToEndRoom(t,n,r){this.backend.storeEndToEndRoom(t,n,r)}getEndToEndRooms(t,n){this.backend.getEndToEndRooms(t,n)}getSessionsNeedingBackup(t){return this.backend.getSessionsNeedingBackup(t)}countSessionsNeedingBackup(t){return this.backend.countSessionsNeedingBackup(t)}unmarkSessionsNeedingBackup(t,n){return this.backend.unmarkSessionsNeedingBackup(t,n)}markSessionsNeedingBackup(t,n){return this.backend.markSessionsNeedingBackup(t,n)}addSharedHistoryInboundGroupSession(t,n,r,i){this.backend.addSharedHistoryInboundGroupSession(t,n,r,i)}getSharedHistoryInboundGroupSessions(t,n){return this.backend.getSharedHistoryInboundGroupSessions(t,n)}addParkedSharedHistory(t,n,r){this.backend.addParkedSharedHistory(t,n,r)}takeParkedSharedHistory(t,n){return this.backend.takeParkedSharedHistory(t,n)}doTxn(t,n,r,i){return this.backend.doTxn(t,n,r,i)}}ir.IndexedDBCryptoStore=xn;(0,Sr.default)(xn,"STORE_ACCOUNT","account");(0,Sr.default)(xn,"STORE_SESSIONS","sessions");(0,Sr.default)(xn,"STORE_INBOUND_GROUP_SESSIONS","inbound_group_sessions");(0,Sr.default)(xn,"STORE_INBOUND_GROUP_SESSIONS_WITHHELD","inbound_group_sessions_withheld");(0,Sr.default)(xn,"STORE_SHARED_HISTORY_INBOUND_GROUP_SESSIONS","shared_history_inbound_group_sessions");(0,Sr.default)(xn,"STORE_PARKED_SHARED_HISTORY","parked_shared_history");(0,Sr.default)(xn,"STORE_DEVICE_DATA","device_data");(0,Sr.default)(xn,"STORE_ROOMS","rooms");(0,Sr.default)(xn,"STORE_BACKUP","sessions_needing_backup");var eb;function w3(){if(eb)return il;eb=1;var e=Ae;Object.defineProperty(il,"__esModule",{value:!0}),il.RoomList=void 0;var t=e(Ue),n=ir;let r=class{constructor(o){this.cryptoStore=o,(0,t.default)(this,"roomEncryption",{})}async init(){await this.cryptoStore.doTxn("readwrite",[n.IndexedDBCryptoStore.STORE_ROOMS],o=>{this.cryptoStore.getEndToEndRooms(o,a=>{this.roomEncryption=a})})}getRoomEncryption(o){return this.roomEncryption[o]||null}isRoomEncrypted(o){return Boolean(this.getRoomEncryption(o))}async setRoomEncryption(o,a){this.roomEncryption[o]=a,await this.cryptoStore.doTxn("readwrite",[n.IndexedDBCryptoStore.STORE_ROOMS],c=>{this.cryptoStore.storeEndToEndRoom(o,a,c)})}};return il.RoomList=r,il}var Oa={};Object.defineProperty(Oa,"__esModule",{value:!0});Oa.SERVICE_TYPES=void 0;let lm;Oa.SERVICE_TYPES=lm;(function(e){e.IS="SERVICE_TYPE_IS",e.IM="SERVICE_TYPE_IM"})(lm||(Oa.SERVICE_TYPES=lm={}));var mn={},zr={},Ap={},tb={},Xt={},nb;function t_(){if(nb)return Xt;nb=1;var e=Ae;Object.defineProperty(Xt,"__esModule",{value:!0}),Xt.UnknownDeviceError=Xt.EncryptionAlgorithm=Xt.ENCRYPTION_CLASSES=Xt.DecryptionError=Xt.DecryptionAlgorithm=Xt.DECRYPTION_CLASSES=void 0,Xt.registerAlgorithm=v;var t=e(Ue);const n=new Map;Xt.ENCRYPTION_CLASSES=n;const r=new Map;Xt.DECRYPTION_CLASSES=r;class i{constructor(g){(0,t.default)(this,"userId",void 0),(0,t.default)(this,"deviceId",void 0),(0,t.default)(this,"crypto",void 0),(0,t.default)(this,"olmDevice",void 0),(0,t.default)(this,"baseApis",void 0),(0,t.default)(this,"roomId",void 0),this.userId=g.userId,this.deviceId=g.deviceId,this.crypto=g.crypto,this.olmDevice=g.olmDevice,this.baseApis=g.baseApis,this.roomId=g.roomId}prepareToEncrypt(g){}onRoomMembership(g,y,S){}}Xt.EncryptionAlgorithm=i;class o{constructor(g){(0,t.default)(this,"userId",void 0),(0,t.default)(this,"crypto",void 0),(0,t.default)(this,"olmDevice",void 0),(0,t.default)(this,"baseApis",void 0),(0,t.default)(this,"roomId",void 0),this.userId=g.userId,this.crypto=g.crypto,this.olmDevice=g.olmDevice,this.baseApis=g.baseApis,this.roomId=g.roomId}async onRoomKeyEvent(g){}async importRoomKey(g,y){}hasKeysForKeyRequest(g){return Promise.resolve(!1)}shareKeysWithDevice(g){throw new Error("shareKeysWithDevice not supported for this DecryptionAlgorithm")}async retryDecryptionFromSender(g){return!1}}Xt.DecryptionAlgorithm=o;class a extends Error{constructor(g,y,S){super(y),this.code=g,(0,t.default)(this,"detailedString",void 0),this.code=g,this.name="DecryptionError",this.detailedString=c(this,S)}}Xt.DecryptionError=a;function c(s,g){let y=s.name+"[msg: "+s.message;return g&&(y+=", "+Object.keys(g).map(S=>S+": "+g[S]).join(", ")),y+="]",y}class f extends Error{constructor(g,y,S){super(g),this.devices=y,this.event=S,this.name="UnknownDeviceError",this.devices=y}}Xt.UnknownDeviceError=f;function v(s,g,y){n.set(s,g),r.set(s,y)}return Xt}var rb;function b3(){if(rb)return tb;rb=1;var e=Ae,t=e(Ue),n=Ge(),r=c(ct),i=Qu(),o=t_();function a(g){if(typeof WeakMap!="function")return null;var y=new WeakMap,S=new WeakMap;return(a=function(m){return m?S:y})(g)}function c(g,y){if(!y&&g&&g.__esModule)return g;if(g===null||typeof g!="object"&&typeof g!="function")return{default:g};var S=a(y);if(S&&S.has(g))return S.get(g);var m={},p=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var _ in g)if(_!=="default"&&Object.prototype.hasOwnProperty.call(g,_)){var u=p?Object.getOwnPropertyDescriptor(g,_):null;u&&(u.get||u.set)?Object.defineProperty(m,_,u):m[_]=g[_]}return m.default=g,S&&S.set(g,m),m}const f=i.DeviceInfo.DeviceVerification;class v extends o.EncryptionAlgorithm{constructor(...y){super(...y),(0,t.default)(this,"sessionPrepared",!1),(0,t.default)(this,"prepPromise",null)}ensureSession(y){return this.prepPromise?this.prepPromise:this.sessionPrepared?Promise.resolve():(this.prepPromise=this.crypto.downloadKeys(y).then(()=>this.crypto.ensureOlmSessionsForUsers(y)).then(()=>{this.sessionPrepared=!0}).finally(()=>{this.prepPromise=null}),this.prepPromise)}async encryptMessage(y,S,m){const _=(await y.getEncryptionTargetMembers()).map(function(h){return h.userId});await this.ensureSession(_);const u={room_id:y.roomId,type:S,content:m},l={algorithm:r.OLM_ALGORITHM,sender_key:this.olmDevice.deviceCurve25519Key,ciphertext:{}},d=[];for(const h of _){const w=this.crypto.getStoredDevicesForUser(h)||[];for(const E of w)E.getIdentityKey()!=this.olmDevice.deviceCurve25519Key&&E.verified!=f.BLOCKED&&d.push(r.encryptMessageForDevice(l.ciphertext,this.userId,this.deviceId,this.olmDevice,h,E,u))}return Promise.all(d).then(()=>l)}}class s extends o.DecryptionAlgorithm{async decryptEvent(y){const S=y.getWireContent(),m=S.sender_key,p=S.ciphertext;if(!p)throw new o.DecryptionError("OLM_MISSING_CIPHERTEXT","Missing ciphertext");if(!(this.olmDevice.deviceCurve25519Key in p))throw new o.DecryptionError("OLM_NOT_INCLUDED_IN_RECIPIENTS","Not included in recipients");const _=p[this.olmDevice.deviceCurve25519Key];let u;try{u=await this.decryptMessage(m,_)}catch(w){throw new o.DecryptionError("OLM_BAD_ENCRYPTED_MESSAGE","Bad Encrypted Message",{sender:m,err:w})}const l=JSON.parse(u);if(l.recipient!=this.userId)throw new o.DecryptionError("OLM_BAD_RECIPIENT","Message was intented for "+l.recipient);if(l.recipient_keys.ed25519!=this.olmDevice.deviceEd25519Key)throw new o.DecryptionError("OLM_BAD_RECIPIENT_KEY","Message not intended for this device",{intended:l.recipient_keys.ed25519,our_key:this.olmDevice.deviceEd25519Key});await this.crypto.deviceList.downloadKeys([y.getSender()],!1);const d=this.crypto.deviceList.getUserByIdentityKey(r.OLM_ALGORITHM,m);if(d!==y.getSender()&&d!=null)throw new o.DecryptionError("OLM_BAD_SENDER","Message claimed to be from "+y.getSender(),{real_sender:d});if(l.sender!=y.getSender())throw new o.DecryptionError("OLM_FORWARDED_MESSAGE","Message forwarded from "+l.sender,{reported_sender:y.getSender()});if(l.room_id!==y.getRoomId())throw new o.DecryptionError("OLM_BAD_ROOM","Message intended for room "+l.room_id,{reported_room:y.getRoomId()||"ROOM_ID_UNDEFINED"});const h=l.keys||{};return{clearEvent:l,senderCurve25519Key:m,claimedEd25519Key:h.ed25519||null}}decryptMessage(y,S){if(S.type!==0)return this.reallyDecryptMessage(y,S);{const m=this.olmDevice.olmPrekeyPromise.then(()=>this.reallyDecryptMessage(y,S));return this.olmDevice.olmPrekeyPromise=m.catch(()=>{}),m}}async reallyDecryptMessage(y,S){const m=await this.olmDevice.getSessionIdsForDevice(y),p={};for(const u of m)try{const l=await this.olmDevice.decryptMessage(y,u,S.type,S.body);return n.logger.log("Decrypted Olm message from "+y+" with session "+u),l}catch(l){if(await this.olmDevice.matchesSession(y,u,S.type,S.body))throw new Error("Error decrypting prekey message with existing session id "+u+": "+l.message);p[u]=l.message}if(S.type!==0)throw m.length===0?new Error("No existing sessions"):new Error("Error decrypting non-prekey message with existing sessions: "+JSON.stringify(p));let _;try{_=await this.olmDevice.createInboundSession(y,S.type,S.body)}catch(u){throw p["(new)"]=u.message,new Error("Error decrypting prekey message: "+JSON.stringify(p))}return n.logger.log("created new inbound Olm session ID "+_.session_id+" with "+y),_.payload}}return(0,o.registerAlgorithm)(r.OLM_ALGORITHM,v,s),tb}var Ii={},Ci={},ib;function ak(){if(ib)return Ci;ib=1;var e=Ae;Object.defineProperty(Ci,"__esModule",{value:!0}),Ci.RoomKeyRequestState=Ci.OutgoingRoomKeyRequestManager=void 0;var t=e(Ue),n=zu,r=Ge(),i=xe;function o(y,S){var m=Object.keys(y);if(Object.getOwnPropertySymbols){var p=Object.getOwnPropertySymbols(y);S&&(p=p.filter(function(_){return Object.getOwnPropertyDescriptor(y,_).enumerable})),m.push.apply(m,p)}return m}function a(y){for(var S=1;S<arguments.length;S++){var m=arguments[S]!=null?arguments[S]:{};S%2?o(Object(m),!0).forEach(function(p){(0,t.default)(y,p,m[p])}):Object.getOwnPropertyDescriptors?Object.defineProperties(y,Object.getOwnPropertyDescriptors(m)):o(Object(m)).forEach(function(p){Object.defineProperty(y,p,Object.getOwnPropertyDescriptor(m,p))})}return y}const c=500;let f;Ci.RoomKeyRequestState=f,function(y){y[y.Unsent=0]="Unsent",y[y.Sent=1]="Sent",y[y.CancellationPending=2]="CancellationPending",y[y.CancellationPendingAndWillResend=3]="CancellationPendingAndWillResend"}(f||(Ci.RoomKeyRequestState=f={}));let v=class{constructor(S,m,p){this.baseApis=S,this.deviceId=m,this.cryptoStore=p,(0,t.default)(this,"sendOutgoingRoomKeyRequestsTimer",void 0),(0,t.default)(this,"sendOutgoingRoomKeyRequestsRunning",!1),(0,t.default)(this,"clientRunning",!0)}stop(){r.logger.log("stopping OutgoingRoomKeyRequestManager"),this.clientRunning=!1}sendQueuedRequests(){this.startTimer()}async queueRoomKeyRequest(S,m,p=!1){const _=await this.cryptoStore.getOutgoingRoomKeyRequest(S);if(!_)await this.cryptoStore.getOrAddOutgoingRoomKeyRequest({requestBody:S,recipients:m,requestId:this.baseApis.makeTxnId(),state:f.Unsent});else switch(_.state){case f.CancellationPendingAndWillResend:case f.Unsent:return;case f.CancellationPending:{const u=p?f.CancellationPendingAndWillResend:f.Sent;await this.cryptoStore.updateOutgoingRoomKeyRequest(_.requestId,f.CancellationPending,{state:u,cancellationTxnId:this.baseApis.makeTxnId()});break}case f.Sent:{if(p){const u=f.CancellationPendingAndWillResend,l=await this.cryptoStore.updateOutgoingRoomKeyRequest(_.requestId,f.Sent,{state:u,cancellationTxnId:this.baseApis.makeTxnId(),requestTxnId:this.baseApis.makeTxnId()});if(!l)return this.queueRoomKeyRequest(S,m,p);try{await this.sendOutgoingRoomKeyRequestCancellation(l,!0)}catch(d){r.logger.error("Error sending room key request cancellation; will retry later.",d)}}break}default:throw new Error("unhandled state: "+_.state)}}cancelRoomKeyRequest(S){return this.cryptoStore.getOutgoingRoomKeyRequest(S).then(m=>{if(m)switch(m.state){case f.CancellationPending:case f.CancellationPendingAndWillResend:return;case f.Unsent:return r.logger.log("deleting unnecessary room key request for "+s(S)),this.cryptoStore.deleteOutgoingRoomKeyRequest(m.requestId,f.Unsent);case f.Sent:return this.cryptoStore.updateOutgoingRoomKeyRequest(m.requestId,f.Sent,{state:f.CancellationPending,cancellationTxnId:this.baseApis.makeTxnId()}).then(p=>{if(!p){r.logger.log("Tried to cancel room key request for "+s(S)+" but it was already cancelled in another tab");return}this.sendOutgoingRoomKeyRequestCancellation(p).catch(_=>{r.logger.error("Error sending room key request cancellation; will retry later.",_),this.startTimer()})});default:throw new Error("unhandled state: "+m.state)}})}getOutgoingSentRoomKeyRequest(S,m){return this.cryptoStore.getOutgoingRoomKeyRequestsByTarget(S,m,[f.Sent])}async cancelAndResendAllOutgoingRequests(){const S=await this.cryptoStore.getAllOutgoingRoomKeyRequestsByState(f.Sent);return Promise.all(S.map(({requestBody:m,recipients:p})=>this.queueRoomKeyRequest(m,p,!0)))}startTimer(){if(this.sendOutgoingRoomKeyRequestsTimer)return;const S=()=>{if(this.sendOutgoingRoomKeyRequestsRunning)throw new Error("RoomKeyRequestSend already in progress!");this.sendOutgoingRoomKeyRequestsRunning=!0,this.sendOutgoingRoomKeyRequests().finally(()=>{this.sendOutgoingRoomKeyRequestsRunning=!1}).catch(m=>{r.logger.warn(`error in OutgoingRoomKeyRequestManager: ${m}`)})};this.sendOutgoingRoomKeyRequestsTimer=setTimeout(S,c)}async sendOutgoingRoomKeyRequests(){if(!this.clientRunning){this.sendOutgoingRoomKeyRequestsTimer=void 0;return}const S=await this.cryptoStore.getOutgoingRoomKeyRequestByState([f.CancellationPending,f.CancellationPendingAndWillResend,f.Unsent]);if(!S){this.sendOutgoingRoomKeyRequestsTimer=void 0;return}try{switch(S.state){case f.Unsent:await this.sendOutgoingRoomKeyRequest(S);break;case f.CancellationPending:await this.sendOutgoingRoomKeyRequestCancellation(S);break;case f.CancellationPendingAndWillResend:await this.sendOutgoingRoomKeyRequestCancellation(S,!0);break}return this.sendOutgoingRoomKeyRequests()}catch(m){r.logger.error("Error sending room key request; will retry later.",m),this.sendOutgoingRoomKeyRequestsTimer=void 0}}sendOutgoingRoomKeyRequest(S){r.logger.log(`Requesting keys for ${s(S.requestBody)} from ${g(S.recipients)}(id ${S.requestId})`);const m={action:"request",requesting_device_id:this.deviceId,request_id:S.requestId,body:S.requestBody};return this.sendMessageToDevices(m,S.recipients,S.requestTxnId||S.requestId).then(()=>this.cryptoStore.updateOutgoingRoomKeyRequest(S.requestId,f.Unsent,{state:f.Sent}))}sendOutgoingRoomKeyRequestCancellation(S,m=!1){r.logger.log(`Sending cancellation for key request for ${s(S.requestBody)} to ${g(S.recipients)} (cancellation id ${S.cancellationTxnId})`);const p={action:"request_cancellation",requesting_device_id:this.deviceId,request_id:S.requestId};return this.sendMessageToDevices(p,S.recipients,S.cancellationTxnId).then(()=>m?this.cryptoStore.updateOutgoingRoomKeyRequest(S.requestId,f.CancellationPendingAndWillResend,{state:f.Unsent}):this.cryptoStore.deleteOutgoingRoomKeyRequest(S.requestId,f.CancellationPending))}sendMessageToDevices(S,m,p){const _={};for(const u of m)_[u.userId]||(_[u.userId]={}),_[u.userId][u.deviceId]=a(a({},S),{},{[i.ToDeviceMessageId]:(0,n.v4)()});return this.baseApis.sendToDevice(i.EventType.RoomKeyRequest,_,p)}};Ci.OutgoingRoomKeyRequestManager=v;function s(y){return y.room_id+" / "+y.session_id}function g(y){return`[${y.map(S=>`${S.userId}:${S.deviceId}`).join(",")}]`}return Ci}var ob;function lk(){if(ob)return Ii;ob=1;var e=Ae;Object.defineProperty(Ii,"__esModule",{value:!0}),Ii.MegolmEncryption=Ii.MegolmDecryption=void 0,Ii.isRoomSharedHistory=S;var t=e(Ue),n=zu,r=Ge(),i=s(ct),o=t_(),a=ck(),c=xe,f=ak();function v(l){if(typeof WeakMap!="function")return null;var d=new WeakMap,h=new WeakMap;return(v=function(w){return w?h:d})(l)}function s(l,d){if(!d&&l&&l.__esModule)return l;if(l===null||typeof l!="object"&&typeof l!="function")return{default:l};var h=v(d);if(h&&h.has(l))return h.get(l);var w={},E=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var I in l)if(I!=="default"&&Object.prototype.hasOwnProperty.call(l,I)){var k=E?Object.getOwnPropertyDescriptor(l,I):null;k&&(k.get||k.set)?Object.defineProperty(w,I,k):w[I]=l[I]}return w.default=l,h&&h.set(l,w),w}function g(l,d){var h=Object.keys(l);if(Object.getOwnPropertySymbols){var w=Object.getOwnPropertySymbols(l);d&&(w=w.filter(function(E){return Object.getOwnPropertyDescriptor(l,E).enumerable})),h.push.apply(h,w)}return h}function y(l){for(var d=1;d<arguments.length;d++){var h=arguments[d]!=null?arguments[d]:{};d%2?g(Object(h),!0).forEach(function(w){(0,t.default)(l,w,h[w])}):Object.getOwnPropertyDescriptors?Object.defineProperties(l,Object.getOwnPropertyDescriptors(h)):g(Object(h)).forEach(function(w){Object.defineProperty(l,w,Object.getOwnPropertyDescriptor(h,w))})}return l}function S(l){var d,h;const w=l==null||(d=l.currentState)===null||d===void 0?void 0:d.getStateEvents("m.room.history_visibility",""),E=w==null||(h=w.getContent())===null||h===void 0?void 0:h.history_visibility;return["world_readable","shared"].includes(E)}class m{constructor(d,h=!1){this.sessionId=d,this.sharedHistory=h,(0,t.default)(this,"useCount",0),(0,t.default)(this,"creationTime",void 0),(0,t.default)(this,"sharedWithDevices",{}),(0,t.default)(this,"blockedDevicesNotified",{}),this.creationTime=new Date().getTime()}needsRotation(d,h){const w=new Date().getTime()-this.creationTime;return this.useCount>=d||w>=h?(r.logger.log("Rotating megolm session after "+this.useCount+" messages, "+w+"ms"),!0):!1}markSharedWithDevice(d,h,w,E){this.sharedWithDevices[d]||(this.sharedWithDevices[d]={}),this.sharedWithDevices[d][h]={deviceKey:w,messageIndex:E}}markNotifiedBlockedDevice(d,h){this.blockedDevicesNotified[d]||(this.blockedDevicesNotified[d]={}),this.blockedDevicesNotified[d][h]=!0}sharedWithTooManyDevices(d){for(const h in this.sharedWithDevices)if(this.sharedWithDevices.hasOwnProperty(h)){if(!d.hasOwnProperty(h))return r.logger.log("Starting new megolm session because we shared with "+h),!0;for(const w in this.sharedWithDevices[h])if(this.sharedWithDevices[h].hasOwnProperty(w)&&!d[h].hasOwnProperty(w))return r.logger.log("Starting new megolm session because we shared with "+h+":"+w),!0}return!1}}class p extends o.EncryptionAlgorithm{constructor(d){var h,w,E,I;super(d),(0,t.default)(this,"setupPromise",Promise.resolve(null)),(0,t.default)(this,"outboundSessions",{}),(0,t.default)(this,"sessionRotationPeriodMsgs",void 0),(0,t.default)(this,"sessionRotationPeriodMs",void 0),(0,t.default)(this,"encryptionPreparation",void 0),(0,t.default)(this,"roomId",void 0),this.roomId=d.roomId,this.sessionRotationPeriodMsgs=(h=(w=d.config)===null||w===void 0?void 0:w.rotation_period_msgs)!==null&&h!==void 0?h:100,this.sessionRotationPeriodMs=(E=(I=d.config)===null||I===void 0?void 0:I.rotation_period_ms)!==null&&E!==void 0?E:7*24*3600*1e3}async ensureOutboundSession(d,h,w,E=!1){const I=async M=>{const L=S(d),B=await this.prepareSession(h,L,M);return await this.shareSession(h,L,E,w,B),B},k=this.setupPromise.then(I);return this.setupPromise=k.catch(M=>(r.logger.error(`Failed to setup outbound session in ${this.roomId}`,M),null)),k}async prepareSession(d,h,w){var E,I;return w&&h!==w.sharedHistory&&(w=null),(E=w)!==null&&E!==void 0&&E.needsRotation(this.sessionRotationPeriodMsgs,this.sessionRotationPeriodMs)&&(r.logger.log("Starting new megolm session because we need to rotate."),w=null),(I=w)!==null&&I!==void 0&&I.sharedWithTooManyDevices(d)&&(w=null),w||(r.logger.log(`Starting new megolm session for room ${this.roomId}`),w=await this.prepareNewSession(h),r.logger.log(`Started new megolm session ${w.sessionId} for room ${this.roomId}`),this.outboundSessions[w.sessionId]=w),w}async shareSession(d,h,w,E,I){const k={};for(const[G,D]of Object.entries(d))for(const[x,z]of Object.entries(D))z.getIdentityKey()!=this.olmDevice.deviceCurve25519Key&&(!I.sharedWithDevices[G]||I.sharedWithDevices[G][x]===void 0)&&(k[G]=k[G]||[],k[G].push(z));const M=this.olmDevice.getOutboundGroupSessionKey(I.sessionId),L={type:"m.room_key",content:{algorithm:i.MEGOLM_ALGORITHM,room_id:this.roomId,session_id:I.sessionId,session_key:M.key,chain_index:M.chain_index,"org.matrix.msc3061.shared_history":h}},[B,N]=await i.getExistingOlmSessions(this.olmDevice,this.baseApis,k);await Promise.all([(async()=>{r.logger.debug(`Sharing keys with existing Olm sessions in ${this.roomId}`,N),await this.shareKeyWithOlmSessions(I,M,L,N),r.logger.debug(`Shared keys with existing Olm sessions in ${this.roomId}`)})(),(async()=>{r.logger.debug(`Sharing keys (start phase 1) with new Olm sessions in ${this.roomId}`,B);const G=[],D=Date.now(),x=[];await this.shareKeyWithDevices(I,M,L,B,G,w?1e4:2e3,x),r.logger.debug(`Shared keys (end phase 1) with new Olm sessions in ${this.roomId}`),!w&&Date.now()-D<1e4?(async()=>{const z={},W=new Set;for(const H of x)W.add(H);const F=[];for(const{userId:H,deviceInfo:R}of G){const P=H.slice(H.indexOf(":")+1);W.has(P)?(z[H]=z[H]||[],z[H].push(R)):F.push({userId:H,deviceInfo:R})}r.logger.debug(`Sharing keys (start phase 2) with new Olm sessions in ${this.roomId}`),await this.shareKeyWithDevices(I,M,L,z,F,3e4),r.logger.debug(`Shared keys (end phase 2) with new Olm sessions in ${this.roomId}`),await this.notifyFailedOlmDevices(I,M,F)})():await this.notifyFailedOlmDevices(I,M,G),r.logger.debug(`Shared keys (all phases done) with new Olm sessions in ${this.roomId}`)})(),(async()=>{r.logger.debug(`There are ${Object.entries(E).length} blocked devices in ${this.roomId}`,Object.entries(E)),r.logger.debug(`Notifying newly blocked devices in ${this.roomId}`);const G={};let D=0;for(const[x,z]of Object.entries(E))for(const[W,F]of Object.entries(z))(!I.blockedDevicesNotified[x]||I.blockedDevicesNotified[x][W]===void 0)&&(G[x]=G[x]||{},G[x][W]={device:F},D++);await this.notifyBlockedDevices(I,G),r.logger.debug(`Notified ${D} newly blocked devices in ${this.roomId}`,G)})()])}async prepareNewSession(d){const h=this.olmDevice.createOutboundGroupSession(),w=this.olmDevice.getOutboundGroupSessionKey(h);return await this.olmDevice.addInboundGroupSession(this.roomId,this.olmDevice.deviceCurve25519Key,[],h,w.key,{ed25519:this.olmDevice.deviceEd25519Key},!1,{sharedHistory:d}),this.crypto.backupManager.backupGroupSession(this.olmDevice.deviceCurve25519Key,h),new m(h,d)}getDevicesWithoutSessions(d,h,w=[]){for(const[E,I]of Object.entries(h)){const k=d[E];for(const M of I){const L=M.deviceId;if(!k[L].sessionId){w.push({userId:E,deviceInfo:M}),delete k[L];continue}}}return w}splitDevices(d){let w=[];const E=[w];for(const[I,k]of Object.entries(d)){for(const M of Object.values(k))w.push({userId:I,deviceInfo:M.device});w.length>20&&(w=[],E.push(w))}return w.length===0&&E.pop(),E}encryptAndSendKeysToDevices(d,h,w,E){return this.crypto.encryptAndSendToDevices(w,E).then(()=>{for(const I of w)d.markSharedWithDevice(I.userId,I.deviceInfo.deviceId,I.deviceInfo.getIdentityKey(),h)}).catch(I=>{throw r.logger.error("failed to encryptAndSendToDevices",I),I})}async sendBlockedNotificationsToDevices(d,h,w){const E={};for(const I of h){const k=I.userId,M=I.deviceInfo,B=M.deviceInfo.deviceId,N=y(y({},w),{},{code:M.code,reason:M.reason,[c.ToDeviceMessageId]:(0,n.v4)()});N.code==="m.no_olm"&&(delete N.room_id,delete N.session_id),E[k]||(E[k]={}),E[k][B]=N}await this.baseApis.sendToDevice("m.room_key.withheld",E);for(const I of Object.keys(E))for(const k of Object.keys(E[I]))d.markNotifiedBlockedDevice(I,k)}async reshareKeyWithDevice(d,h,w,E){const I=this.outboundSessions[h];if(!I){r.logger.debug(`megolm session ${d}|${h} not found: not re-sharing keys`);return}if(I.sharedWithDevices[w]===void 0){r.logger.debug(`megolm session ${d}|${h} never shared with user ${w}`);return}const k=I.sharedWithDevices[w][E.deviceId];if(k===void 0){r.logger.debug(`megolm session ${d}|${h} never shared with device ${w}:${E.deviceId}`);return}if(k.deviceKey!==E.getIdentityKey()){r.logger.warn(`Megolm session ${d}|${h} has been shared with device ${E.deviceId} but with identity key ${k.deviceKey}. Key is now ${E.getIdentityKey()}!`);return}const M=await this.olmDevice.getInboundGroupSessionKey(this.roomId,d,h,k.messageIndex);if(!M){r.logger.warn(`No inbound session key found for megolm session ${d}|${h}: not re-sharing keys`);return}await i.ensureOlmSessionsForDevices(this.olmDevice,this.baseApis,{[w]:[E]});const L={type:"m.forwarded_room_key",content:{algorithm:i.MEGOLM_ALGORITHM,room_id:this.roomId,session_id:h,session_key:M.key,chain_index:M.chain_index,sender_key:d,sender_claimed_ed25519_key:M.sender_claimed_ed25519_key,forwarding_curve25519_key_chain:M.forwarding_curve25519_key_chain,"org.matrix.msc3061.shared_history":M.shared_history||!1}},B={algorithm:i.OLM_ALGORITHM,sender_key:this.olmDevice.deviceCurve25519Key,ciphertext:{},[c.ToDeviceMessageId]:(0,n.v4)()};await i.encryptMessageForDevice(B.ciphertext,this.userId,this.deviceId,this.olmDevice,w,E,L),await this.baseApis.sendToDevice("m.room.encrypted",{[w]:{[E.deviceId]:B}}),r.logger.debug(`Re-shared key for megolm session ${d}|${h} with ${w}:${E.deviceId}`)}async shareKeyWithDevices(d,h,w,E,I,k,M){var L;r.logger.debug(`Ensuring Olm sessions for devices in ${this.roomId}`);const B=await i.ensureOlmSessionsForDevices(this.olmDevice,this.baseApis,E,!1,k,M,(L=r.logger.withPrefix)===null||L===void 0?void 0:L.call(r.logger,`[${this.roomId}]`));r.logger.debug(`Ensured Olm sessions for devices in ${this.roomId}`),this.getDevicesWithoutSessions(B,E,I),r.logger.debug(`Sharing keys with newly created Olm sessions in ${this.roomId}`),await this.shareKeyWithOlmSessions(d,h,w,B),r.logger.debug(`Shared keys with newly created Olm sessions in ${this.roomId}`)}async shareKeyWithOlmSessions(d,h,w,E){const I=this.splitDevices(E);for(let k=0;k<I.length;k++){const M=`megolm keys for ${d.sessionId} in ${this.roomId} (slice ${k+1}/${I.length})`;try{r.logger.debug(`Sharing ${M}`,I[k].map(L=>`${L.userId}/${L.deviceInfo.deviceId}`)),await this.encryptAndSendKeysToDevices(d,h.chain_index,I[k],w),r.logger.debug(`Shared ${M}`)}catch(L){throw r.logger.error(`Failed to share ${M}`),L}}}async notifyFailedOlmDevices(d,h,w){r.logger.debug(`Notifying ${w.length} devices we failed to create Olm sessions in ${this.roomId}`);for(const{userId:k,deviceInfo:M}of w){const L=M.deviceId;d.markSharedWithDevice(k,L,M.getIdentityKey(),h.chain_index)}const E=await this.olmDevice.filterOutNotifiedErrorDevices(w);r.logger.debug(`Need to notify ${E.length} failed devices which haven't been notified before in ${this.roomId}`);const I={};for(const{userId:k,deviceInfo:M}of E)I[k]=I[k]||{},I[k][M.deviceId]={device:{code:"m.no_olm",reason:a.WITHHELD_MESSAGES["m.no_olm"],deviceInfo:M}};await this.notifyBlockedDevices(d,I),r.logger.debug(`Notified ${E.length} devices we failed to create Olm sessions in ${this.roomId}`)}async notifyBlockedDevices(d,h){const w={room_id:this.roomId,session_id:d.sessionId,algorithm:i.MEGOLM_ALGORITHM,sender_key:this.olmDevice.deviceCurve25519Key},E=this.splitDevices(h);for(let I=0;I<E.length;I++)try{await this.sendBlockedNotificationsToDevices(d,E[I],w),r.logger.log(`Completed blacklist notification for ${d.sessionId} in ${this.roomId} (slice ${I+1}/${E.length})`)}catch(k){throw r.logger.log(`blacklist notification for ${d.sessionId} in ${this.roomId} (slice ${I+1}/${E.length}) failed`),k}}prepareToEncrypt(d){if(this.encryptionPreparation!=null){const h=Date.now()-this.encryptionPreparation.startTime;r.logger.debug(`Already started preparing to encrypt for ${this.roomId} ${h} ms ago, skipping`);return}r.logger.debug(`Preparing to encrypt events for ${this.roomId}`),this.encryptionPreparation={startTime:Date.now(),promise:(async()=>{try{r.logger.debug(`Getting devices in ${this.roomId}`);const[h,w]=await this.getDevicesInRoom(d);this.crypto.globalErrorOnUnknownDevices&&this.removeUnknownDevices(h),r.logger.debug(`Ensuring outbound session in ${this.roomId}`),await this.ensureOutboundSession(d,h,w,!0),r.logger.debug(`Ready to encrypt events for ${this.roomId}`)}catch(h){r.logger.error(`Failed to prepare to encrypt events for ${this.roomId}`,h)}finally{delete this.encryptionPreparation}})()}}async encryptMessage(d,h,w){if(r.logger.log(`Starting to encrypt event for ${this.roomId}`),this.encryptionPreparation!=null)try{await this.encryptionPreparation.promise}catch{}const E=this.isVerificationEvent(h,w),[I,k]=await this.getDevicesInRoom(d,E);this.crypto.globalErrorOnUnknownDevices&&this.checkForUnknownDevices(I);const M=await this.ensureOutboundSession(d,I,k),L={room_id:this.roomId,type:h,content:w},B=this.olmDevice.encryptGroupMessage(M.sessionId,JSON.stringify(L)),N={algorithm:i.MEGOLM_ALGORITHM,sender_key:this.olmDevice.deviceCurve25519Key,ciphertext:B,session_id:M.sessionId,device_id:this.deviceId};return M.useCount++,N}isVerificationEvent(d,h){switch(d){case c.EventType.KeyVerificationCancel:case c.EventType.KeyVerificationDone:case c.EventType.KeyVerificationMac:case c.EventType.KeyVerificationStart:case c.EventType.KeyVerificationKey:case c.EventType.KeyVerificationReady:case c.EventType.KeyVerificationAccept:return!0;case c.EventType.RoomMessage:return h.msgtype===c.MsgType.KeyVerificationRequest;default:return!1}}forceDiscardSession(){this.setupPromise=this.setupPromise.then(()=>null)}checkForUnknownDevices(d){const h={};if(Object.keys(d).forEach(w=>{Object.keys(d[w]).forEach(E=>{const I=d[w][E];I.isUnverified()&&!I.isKnown()&&(h[w]||(h[w]={}),h[w][E]=I)})}),Object.keys(h).length)throw new o.UnknownDeviceError("This room contains unknown devices which have not been verified. We strongly recommend you verify them before continuing.",h)}removeUnknownDevices(d){for(const[h,w]of Object.entries(d)){for(const[E,I]of Object.entries(w))I.isUnverified()&&!I.isKnown()&&delete w[E];Object.keys(w).length===0&&delete d[h]}}async getDevicesInRoom(d,h=!1){const E=(await d.getEncryptionTargetMembers()).map(function(B){return B.userId});let I=this.crypto.globalBlacklistUnverifiedDevices;const k=d.getBlacklistUnverifiedDevices();typeof k=="boolean"&&(I=k);const M=await this.crypto.downloadKeys(E,!1),L={};for(const B in M){if(!M.hasOwnProperty(B))continue;const N=M[B];for(const G in N){if(!N.hasOwnProperty(G))continue;const D=this.crypto.checkDeviceTrust(B,G);if(N[G].isBlocked()||!D.isVerified()&&I&&!h){L[B]||(L[B]={});const x=N[G].isBlocked();L[B][G]={code:x?"m.blacklisted":"m.unverified",reason:a.WITHHELD_MESSAGES[x?"m.blacklisted":"m.unverified"],deviceInfo:N[G]},delete N[G]}}}return[M,L]}}Ii.MegolmEncryption=p;class _ extends o.DecryptionAlgorithm{constructor(d){super(d),(0,t.default)(this,"pendingEvents",new Map),(0,t.default)(this,"olmlib",i),(0,t.default)(this,"roomId",void 0),this.roomId=d.roomId}async decryptEvent(d){const h=d.getWireContent();if(!h.sender_key||!h.session_id||!h.ciphertext)throw new o.DecryptionError("MEGOLM_MISSING_FIELDS","Missing fields in input");this.addEventToPendingList(d);let w;try{w=await this.olmDevice.decryptGroupMessage(d.getRoomId(),h.sender_key,h.session_id,h.ciphertext,d.getId(),d.getTs())}catch(I){if(I.name==="DecryptionError")throw I;let k="OLM_DECRYPT_GROUP_MESSAGE_ERROR";throw(I==null?void 0:I.message)==="OLM.UNKNOWN_MESSAGE_INDEX"&&(this.requestKeysForEvent(d),k="OLM_UNKNOWN_MESSAGE_INDEX"),new o.DecryptionError(k,I?I.toString():"Unknown Error: Error is undefined",{session:h.sender_key+"|"+h.session_id})}if(w===null){this.crypto.backupManager.queryKeyBackupRateLimited(d.getRoomId(),h.session_id).catch(()=>{}),this.requestKeysForEvent(d);const I=await this.olmDevice.sessionMayHaveProblems(h.sender_key,d.getTs()-12e4);if(I){r.logger.info(`When handling UISI from ${d.getSender()} (sender key ${h.sender_key}): recent session problem with that sender: ${I}`);let k=u[I.type]||u.unknown;throw I.fixed&&(k+=" Trying to create a new secure channel and re-requesting the keys."),new o.DecryptionError("MEGOLM_UNKNOWN_INBOUND_SESSION_ID",k,{session:h.sender_key+"|"+h.session_id})}throw new o.DecryptionError("MEGOLM_UNKNOWN_INBOUND_SESSION_ID","The sender's device has not sent us the keys for this message.",{session:h.sender_key+"|"+h.session_id})}w.untrusted||this.removeEventFromPendingList(d);const E=JSON.parse(w.result);if(E.room_id!==d.getRoomId())throw new o.DecryptionError("MEGOLM_BAD_ROOM","Message intended for room "+E.room_id);return{clearEvent:E,senderCurve25519Key:w.senderKey,claimedEd25519Key:w.keysClaimed.ed25519,forwardingCurve25519KeyChain:w.forwardingCurve25519KeyChain,untrusted:w.untrusted}}requestKeysForEvent(d){const h=d.getWireContent(),w=d.getKeyRequestRecipients(this.userId);this.crypto.requestRoomKey({room_id:d.getRoomId(),algorithm:h.algorithm,sender_key:h.sender_key,session_id:h.session_id},w)}addEventToPendingList(d){var h;const w=d.getWireContent(),E=w.sender_key,I=w.session_id;this.pendingEvents.has(E)||this.pendingEvents.set(E,new Map);const k=this.pendingEvents.get(E);k.has(I)||k.set(I,new Set),(h=k.get(I))===null||h===void 0||h.add(d)}removeEventFromPendingList(d){const h=d.getWireContent(),w=h.sender_key,E=h.session_id,I=this.pendingEvents.get(w),k=I==null?void 0:I.get(E);k&&(k.delete(d),k.size===0&&I.delete(E),I.size===0&&this.pendingEvents.delete(w))}async onRoomKeyEvent(d){const h=d.getContent();let w=d.getSenderKey(),E=[],I=!1,k;const M={};if(!h.room_id||!h.session_key||!h.session_id||!h.algorithm){r.logger.error("key event is missing fields");return}if(!i.isOlmEncrypted(d)){r.logger.error("key event not properly encrypted");return}if(h["org.matrix.msc3061.shared_history"]&&(M.sharedHistory=!0),d.getType()=="m.forwarded_room_key"){var L,B,N,G;const D=this.crypto.deviceList.getDeviceByIdentityKey(i.OLM_ALGORITHM,w);if(this.baseApis.crypto.deviceList.getUserByIdentityKey(i.OLM_ALGORITHM,w)!==d.getSender()){r.logger.error("sending device does not belong to the user it claims to be from");return}const W=(D?await this.crypto.cryptoStore.getOutgoingRoomKeyRequestsByTarget(d.getSender(),D.deviceId,[f.RoomKeyRequestState.Sent]):[]).some(A=>A.requestBody.room_id===h.room_id&&A.requestBody.session_id===h.session_id),F=this.baseApis.getRoom(h.room_id),H=F==null||(L=F.getMember(this.userId))===null||L===void 0?void 0:L.events.member,R=(H==null?void 0:H.getSender())===d.getSender()||(H==null||(B=H.getUnsigned())===null||B===void 0?void 0:B.prev_sender)===d.getSender()&&(H==null||(N=H.getPrevContent())===null||N===void 0?void 0:N.membership)==="invite",P=d.getSender()===this.baseApis.getUserId();if(!W&&!P){if(!M.sharedHistory){r.logger.log("forwarded key not shared history - ignoring");return}if(F&&!R){r.logger.log("forwarded key not from inviter or from us - ignoring");return}}if(I=!0,E=Array.isArray(h.forwarding_curve25519_key_chain)?h.forwarding_curve25519_key_chain:[],E=E.slice(),E.push(w),!h.sender_key){r.logger.error("forwarded_room_key event is missing sender_key field");return}const K=h.sender_claimed_ed25519_key;if(!K){r.logger.error("forwarded_room_key_event is missing sender_claimed_ed25519_key field");return}if(k={ed25519:K},!F){const A={senderId:d.getSender(),senderKey:h.sender_key,sessionId:h.session_id,sessionKey:h.session_key,keysClaimed:k,forwardingCurve25519KeyChain:E};await this.crypto.cryptoStore.doTxn("readwrite",["parked_shared_history"],T=>this.crypto.cryptoStore.addParkedSharedHistory(h.room_id,A,T),r.logger.withPrefix("[addParkedSharedHistory]"));return}const U=(G=this.crypto.deviceList.getDeviceByIdentityKey(i.OLM_ALGORITHM,w))!==null&&G!==void 0?G:void 0,C=this.crypto.checkDeviceInfoTrust(d.getSender(),U);if(P&&!C.isVerified())return;M.untrusted=!0,w=h.sender_key}else k=d.getKeysClaimed();h["org.matrix.msc3061.shared_history"]&&(M.sharedHistory=!0);try{await this.olmDevice.addInboundGroupSession(h.room_id,w,E,h.session_id,h.session_key,k,I,M),await this.retryDecryption(w,h.session_id,!M.untrusted)&&this.crypto.cancelRoomKeyRequest({algorithm:h.algorithm,room_id:h.room_id,session_id:h.session_id,sender_key:w}),await this.crypto.backupManager.backupGroupSession(w,h.session_id)}catch(D){r.logger.error(`Error handling m.room_key_event: ${D}`)}}async onRoomKeyWithheldEvent(d){const h=d.getContent(),w=h.sender_key;if(h.code==="m.no_olm"){const E=d.getSender();if(r.logger.warn(`${E}:${w} was unable to establish an olm session with us`),await this.olmDevice.getSessionIdForDevice(w)){r.logger.debug("New session already created.  Not creating a new one."),await this.olmDevice.recordSessionProblem(w,"no_olm",!0),this.retryDecryptionFromSender(w);return}let I=this.crypto.deviceList.getDeviceByIdentityKey(h.algorithm,w);if(!I&&(await this.crypto.downloadKeys([E],!1),I=this.crypto.deviceList.getDeviceByIdentityKey(h.algorithm,w),!I)){r.logger.info("Couldn't find device for identity key "+w+": not establishing session"),await this.olmDevice.recordSessionProblem(w,"no_olm",!1),this.retryDecryptionFromSender(w);return}await i.ensureOlmSessionsForDevices(this.olmDevice,this.baseApis,{[E]:[I]},!1);const k={algorithm:i.OLM_ALGORITHM,sender_key:this.olmDevice.deviceCurve25519Key,ciphertext:{},[c.ToDeviceMessageId]:(0,n.v4)()};await i.encryptMessageForDevice(k.ciphertext,this.userId,void 0,this.olmDevice,E,I,{type:"m.dummy"}),await this.olmDevice.recordSessionProblem(w,"no_olm",!0),this.retryDecryptionFromSender(w),await this.baseApis.sendToDevice("m.room.encrypted",{[E]:{[I.deviceId]:k}})}else await this.olmDevice.addInboundGroupSessionWithheld(h.room_id,w,h.session_id,h.code,h.reason)}hasKeysForKeyRequest(d){const h=d.requestBody;return this.olmDevice.hasInboundSessionKeys(h.room_id,h.sender_key,h.session_id)}shareKeysWithDevice(d){const h=d.userId,w=d.deviceId,E=this.crypto.getStoredDevice(h,w),I=d.requestBody;this.olmlib.ensureOlmSessionsForDevices(this.olmDevice,this.baseApis,{[h]:[E]}).then(k=>k[h][w].sessionId?(r.logger.log("sharing keys for session "+I.sender_key+"|"+I.session_id+" with device "+h+":"+w),this.buildKeyForwardingMessage(I.room_id,I.sender_key,I.session_id)):null).then(k=>{const M={algorithm:i.OLM_ALGORITHM,sender_key:this.olmDevice.deviceCurve25519Key,ciphertext:{},[c.ToDeviceMessageId]:(0,n.v4)()};return this.olmlib.encryptMessageForDevice(M.ciphertext,this.userId,void 0,this.olmDevice,h,E,k).then(()=>{const L={[h]:{[w]:M}};return this.baseApis.sendToDevice("m.room.encrypted",L)})})}async buildKeyForwardingMessage(d,h,w){const E=await this.olmDevice.getInboundGroupSessionKey(d,h,w);return{type:"m.forwarded_room_key",content:{algorithm:i.MEGOLM_ALGORITHM,room_id:d,sender_key:h,sender_claimed_ed25519_key:E.sender_claimed_ed25519_key,session_id:w,session_key:E.key,chain_index:E.chain_index,forwarding_curve25519_key_chain:E.forwarding_curve25519_key_chain,"org.matrix.msc3061.shared_history":E.shared_history||!1}}}importRoomKey(d,{untrusted:h,source:w}={}){const E={};return(h||d.untrusted)&&(E.untrusted=!0),d["org.matrix.msc3061.shared_history"]&&(E.sharedHistory=!0),this.olmDevice.addInboundGroupSession(d.room_id,d.sender_key,d.forwarding_curve25519_key_chain,d.session_id,d.session_key,d.sender_claimed_keys,!0,E).then(()=>{w!=="backup"&&this.crypto.backupManager.backupGroupSession(d.sender_key,d.session_id).catch(I=>{r.logger.log("Failed to back up megolm session",I)}),this.retryDecryption(d.sender_key,d.session_id,!E.untrusted)})}async retryDecryption(d,h,w){var E;const I=this.pendingEvents.get(d);if(!I)return!0;const k=I.get(h);return k?(r.logger.debug("Retrying decryption on events",[...k]),await Promise.all([...k].map(async M=>{try{await M.attemptDecryption(this.crypto,{isRetry:!0,forceRedecryptIfUntrusted:w})}catch{}})),!((E=this.pendingEvents.get(d))!==null&&E!==void 0&&E.has(h))):!0}async retryDecryptionFromSender(d){const h=this.pendingEvents.get(d);return h?(this.pendingEvents.delete(d),await Promise.all([...h].map(async([w,E])=>{await Promise.all([...E].map(async I=>{try{await I.attemptDecryption(this.crypto)}catch{}}))})),!this.pendingEvents.has(d)):!0}async sendSharedHistoryInboundSessions(d){await i.ensureOlmSessionsForDevices(this.olmDevice,this.baseApis,d);const h=await this.olmDevice.getSharedHistoryInboundGroupSessions(this.roomId);r.logger.log(`Sharing history in ${this.roomId} with users ${Object.keys(d)}`,h.map(([w,E])=>`${w}|${E}`));for(const[w,E]of h){const I=await this.buildKeyForwardingMessage(this.roomId,w,E),k=[],M={};for(const[L,B]of Object.entries(d)){M[L]={};for(const N of B){const G={algorithm:i.OLM_ALGORITHM,sender_key:this.olmDevice.deviceCurve25519Key,ciphertext:{},[c.ToDeviceMessageId]:(0,n.v4)()};M[L][N.deviceId]=G,k.push(i.encryptMessageForDevice(G.ciphertext,this.userId,void 0,this.olmDevice,L,N,I))}}await Promise.all(k);for(const L of Object.keys(M)){for(const B of Object.keys(M[L]))Object.keys(M[L][B].ciphertext).length===0&&(r.logger.log("No ciphertext for device "+L+":"+B+": pruning"),delete M[L][B]);Object.keys(M[L]).length===0&&(r.logger.log("Pruned all devices for user "+L),delete M[L])}if(Object.keys(M).length===0){r.logger.log("No users left to send to: aborting");return}await this.baseApis.sendToDevice("m.room.encrypted",M)}}}Ii.MegolmDecryption=_;const u={no_olm:"The sender was unable to establish a secure channel.",unknown:"The secure channel with the sender was corrupted."};return(0,o.registerAlgorithm)(i.MEGOLM_ALGORITHM,p,_),Ii}var sb;function uk(){return sb||(sb=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),b3(),lk();var t=t_();Object.keys(t).forEach(function(n){n==="default"||n==="__esModule"||n in e&&e[n]===t[n]||Object.defineProperty(e,n,{enumerable:!0,get:function(){return t[n]}})})}(Ap)),Ap}var ab;function ck(){if(ab)return zr;ab=1;var e=Ae;Object.defineProperty(zr,"__esModule",{value:!0}),zr.WITHHELD_MESSAGES=zr.PayloadTooLargeError=zr.OlmDevice=void 0;var t=e(Ue),n=Ge(),r=ir,i=a(uk());function o(S){if(typeof WeakMap!="function")return null;var m=new WeakMap,p=new WeakMap;return(o=function(_){return _?p:m})(S)}function a(S,m){if(!m&&S&&S.__esModule)return S;if(S===null||typeof S!="object"&&typeof S!="function")return{default:S};var p=o(m);if(p&&p.has(S))return p.get(S);var _={},u=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var l in S)if(l!=="default"&&Object.prototype.hasOwnProperty.call(S,l)){var d=u?Object.getOwnPropertyDescriptor(S,l):null;d&&(d.get||d.set)?Object.defineProperty(_,l,d):_[l]=S[l]}return _.default=S,p&&p.set(S,_),_}const c=65536*3/4;class f extends Error{constructor(...m){super(...m),(0,t.default)(this,"data",{errcode:"M_TOO_LARGE",error:"Payload too large for encrypted message"})}}zr.PayloadTooLargeError=f;function v(S){if(S===void 0)throw new Error("payloadString undefined");if(S.length>c)throw new f(`Message too long (${S.length} bytes). The maximum for an encrypted message is ${c} bytes.`)}let s=class{constructor(m){this.cryptoStore=m,(0,t.default)(this,"pickleKey","DEFAULT_KEY"),(0,t.default)(this,"deviceCurve25519Key",null),(0,t.default)(this,"deviceEd25519Key",null),(0,t.default)(this,"maxOneTimeKeys",null),(0,t.default)(this,"outboundGroupSessionStore",{}),(0,t.default)(this,"inboundGroupSessionMessageIndexes",{}),(0,t.default)(this,"sessionsInProgress",{}),(0,t.default)(this,"olmPrekeyPromise",Promise.resolve())}static getOlmVersion(){return $e.Olm.get_library_version()}async init({pickleKey:m,fromExportedDevice:p}={}){let _;const u=new $e.Olm.Account;try{p?(m&&n.logger.warn("ignoring opts.pickleKey because opts.fromExportedDevice is present."),this.pickleKey=p.pickleKey,await this.initialiseFromExportedDevice(p,u)):(m&&(this.pickleKey=m),await this.initialiseAccount(u)),_=JSON.parse(u.identity_keys()),this.maxOneTimeKeys=u.max_number_of_one_time_keys()}finally{u.free()}this.deviceCurve25519Key=_.curve25519,this.deviceEd25519Key=_.ed25519}async initialiseFromExportedDevice(m,p){await this.cryptoStore.doTxn("readwrite",[r.IndexedDBCryptoStore.STORE_ACCOUNT,r.IndexedDBCryptoStore.STORE_SESSIONS],_=>{this.cryptoStore.storeAccount(_,m.pickledAccount),m.sessions.forEach(u=>{const{deviceKey:l,sessionId:d}=u,h={session:u.session,lastReceivedMessageTs:u.lastReceivedMessageTs};this.cryptoStore.storeEndToEndSession(l,d,h,_)})}),p.unpickle(this.pickleKey,m.pickledAccount)}async initialiseAccount(m){await this.cryptoStore.doTxn("readwrite",[r.IndexedDBCryptoStore.STORE_ACCOUNT],p=>{this.cryptoStore.getAccount(p,_=>{_!==null?m.unpickle(this.pickleKey,_):(m.create(),_=m.pickle(this.pickleKey),this.cryptoStore.storeAccount(p,_))})})}getAccount(m,p){this.cryptoStore.getAccount(m,_=>{const u=new $e.Olm.Account;try{u.unpickle(this.pickleKey,_),p(u)}finally{u.free()}})}storeAccount(m,p){this.cryptoStore.storeAccount(m,p.pickle(this.pickleKey))}async export(){const m={pickleKey:this.pickleKey};return await this.cryptoStore.doTxn("readonly",[r.IndexedDBCryptoStore.STORE_ACCOUNT,r.IndexedDBCryptoStore.STORE_SESSIONS],p=>{this.cryptoStore.getAccount(p,_=>{m.pickledAccount=_}),m.sessions=[],this.cryptoStore.getAllEndToEndSessions(p,_=>{m.sessions.push(_)})}),m}getSession(m,p,_,u){this.cryptoStore.getEndToEndSession(m,p,_,l=>{this.unpickleSession(l,u)})}unpickleSession(m,p){const _=new $e.Olm.Session;try{_.unpickle(this.pickleKey,m.session);const u=Object.assign({},m,{session:_});p(u)}finally{_.free()}}saveSession(m,p,_){const u=p.session.session_id(),l=Object.assign(p,{session:p.session.pickle(this.pickleKey)});this.cryptoStore.storeEndToEndSession(m,u,l,_)}getUtility(m){const p=new $e.Olm.Utility;try{return m(p)}finally{p.free()}}async sign(m){let p;return await this.cryptoStore.doTxn("readonly",[r.IndexedDBCryptoStore.STORE_ACCOUNT],_=>{this.getAccount(_,u=>{p=u.sign(m)})}),p}async getOneTimeKeys(){let m;return await this.cryptoStore.doTxn("readonly",[r.IndexedDBCryptoStore.STORE_ACCOUNT],p=>{this.getAccount(p,_=>{m=JSON.parse(_.one_time_keys())})}),m}maxNumberOfOneTimeKeys(){var m;return(m=this.maxOneTimeKeys)!==null&&m!==void 0?m:-1}async markKeysAsPublished(){await this.cryptoStore.doTxn("readwrite",[r.IndexedDBCryptoStore.STORE_ACCOUNT],m=>{this.getAccount(m,p=>{p.mark_keys_as_published(),this.storeAccount(m,p)})})}generateOneTimeKeys(m){return this.cryptoStore.doTxn("readwrite",[r.IndexedDBCryptoStore.STORE_ACCOUNT],p=>{this.getAccount(p,_=>{_.generate_one_time_keys(m),this.storeAccount(p,_)})})}async generateFallbackKey(){await this.cryptoStore.doTxn("readwrite",[r.IndexedDBCryptoStore.STORE_ACCOUNT],m=>{this.getAccount(m,p=>{p.generate_fallback_key(),this.storeAccount(m,p)})})}async getFallbackKey(){let m;return await this.cryptoStore.doTxn("readonly",[r.IndexedDBCryptoStore.STORE_ACCOUNT],p=>{this.getAccount(p,_=>{m=JSON.parse(_.unpublished_fallback_key())})}),m}async forgetOldFallbackKey(){await this.cryptoStore.doTxn("readwrite",[r.IndexedDBCryptoStore.STORE_ACCOUNT],m=>{this.getAccount(m,p=>{p.forget_old_fallback_key(),this.storeAccount(m,p)})})}async createOutboundSession(m,p){let _;return await this.cryptoStore.doTxn("readwrite",[r.IndexedDBCryptoStore.STORE_ACCOUNT,r.IndexedDBCryptoStore.STORE_SESSIONS],u=>{this.getAccount(u,l=>{const d=new $e.Olm.Session;try{d.create_outbound(l,m,p),_=d.session_id(),this.storeAccount(u,l);const h={session:d,lastReceivedMessageTs:Date.now()};this.saveSession(m,h,u)}finally{d.free()}})},n.logger.withPrefix("[createOutboundSession]")),_}async createInboundSession(m,p,_){if(p!==0)throw new Error("Need messageType == 0 to create inbound session");let u;return await this.cryptoStore.doTxn("readwrite",[r.IndexedDBCryptoStore.STORE_ACCOUNT,r.IndexedDBCryptoStore.STORE_SESSIONS],l=>{this.getAccount(l,d=>{const h=new $e.Olm.Session;try{h.create_inbound_from(d,m,_),d.remove_one_time_keys(h),this.storeAccount(l,d);const w=h.decrypt(p,_),E={session:h,lastReceivedMessageTs:Date.now()};this.saveSession(m,E,l),u={payload:w,session_id:h.session_id()}}finally{h.free()}})},n.logger.withPrefix("[createInboundSession]")),u}async getSessionIdsForDevice(m){const p=n.logger.withPrefix("[getSessionIdsForDevice]");if(m in this.sessionsInProgress){p.debug(`Waiting for Olm session for ${m} to be created`);try{await this.sessionsInProgress[m]}catch{}}let _;return await this.cryptoStore.doTxn("readonly",[r.IndexedDBCryptoStore.STORE_SESSIONS],u=>{this.cryptoStore.getEndToEndSessions(m,u,l=>{_=Object.keys(l)})},p),_}async getSessionIdForDevice(m,p=!1,_){const u=await this.getSessionInfoForDevice(m,p,_);if(u.length===0)return null;let l=0;for(let d=1;d<u.length;d++){const h=u[d],w=h.lastReceivedMessageTs===void 0?0:h.lastReceivedMessageTs,E=u[l],I=E.lastReceivedMessageTs===void 0?0:E.lastReceivedMessageTs;(w>I||w===I&&h.sessionId<E.sessionId)&&(l=d)}return u[l].sessionId}async getSessionInfoForDevice(m,p=!1,_=n.logger){if(_=_.withPrefix("[getSessionInfoForDevice]"),m in this.sessionsInProgress&&!p){_.debug(`Waiting for Olm session for ${m} to be created`);try{await this.sessionsInProgress[m]}catch{}}const u=[];return await this.cryptoStore.doTxn("readonly",[r.IndexedDBCryptoStore.STORE_SESSIONS],l=>{this.cryptoStore.getEndToEndSessions(m,l,d=>{const h=Object.keys(d).sort();for(const w of h)this.unpickleSession(d[w],E=>{u.push({lastReceivedMessageTs:E.lastReceivedMessageTs,hasReceivedMessage:E.session.has_received_message(),sessionId:w})})})},_),u}async encryptMessage(m,p,_){v(_);let u;return await this.cryptoStore.doTxn("readwrite",[r.IndexedDBCryptoStore.STORE_SESSIONS],l=>{this.getSession(m,p,l,d=>{const h=d.session.describe();n.logger.log("encryptMessage: Olm Session ID "+p+" to "+m+": "+h),u=d.session.encrypt(_),this.saveSession(m,d,l)})},n.logger.withPrefix("[encryptMessage]")),u}async decryptMessage(m,p,_,u){let l;return await this.cryptoStore.doTxn("readwrite",[r.IndexedDBCryptoStore.STORE_SESSIONS],d=>{this.getSession(m,p,d,h=>{const w=h.session.describe();n.logger.log("decryptMessage: Olm Session ID "+p+" from "+m+": "+w),l=h.session.decrypt(_,u),h.lastReceivedMessageTs=Date.now(),this.saveSession(m,h,d)})},n.logger.withPrefix("[decryptMessage]")),l}async matchesSession(m,p,_,u){if(_!==0)return!1;let l;return await this.cryptoStore.doTxn("readonly",[r.IndexedDBCryptoStore.STORE_SESSIONS],d=>{this.getSession(m,p,d,h=>{l=h.session.matches_inbound(u)})},n.logger.withPrefix("[matchesSession]")),l}async recordSessionProblem(m,p,_){n.logger.info(`Recording problem on olm session with ${m} of type ${p}. Recreating: ${_}`),await this.cryptoStore.storeEndToEndSessionProblem(m,p,_)}sessionMayHaveProblems(m,p){return this.cryptoStore.getEndToEndSessionProblem(m,p)}filterOutNotifiedErrorDevices(m){return this.cryptoStore.filterOutNotifiedErrorDevices(m)}saveOutboundGroupSession(m){this.outboundGroupSessionStore[m.session_id()]=m.pickle(this.pickleKey)}getOutboundGroupSession(m,p){const _=this.outboundGroupSessionStore[m];if(_===void 0)throw new Error("Unknown outbound group session "+m);const u=new $e.Olm.OutboundGroupSession;try{return u.unpickle(this.pickleKey,_),p(u)}finally{u.free()}}createOutboundGroupSession(){const m=new $e.Olm.OutboundGroupSession;try{return m.create(),this.saveOutboundGroupSession(m),m.session_id()}finally{m.free()}}encryptGroupMessage(m,p){return n.logger.log(`encrypting msg with megolm session ${m}`),v(p),this.getOutboundGroupSession(m,_=>{const u=_.encrypt(p);return this.saveOutboundGroupSession(_),u})}getOutboundGroupSessionKey(m){return this.getOutboundGroupSession(m,function(p){return{chain_index:p.message_index(),key:p.session_key()}})}unpickleInboundGroupSession(m,p){const _=new $e.Olm.InboundGroupSession;try{return _.unpickle(this.pickleKey,m.session),p(_)}finally{_.free()}}getInboundGroupSession(m,p,_,u,l){this.cryptoStore.getEndToEndInboundGroupSession(p,_,u,(d,h)=>{if(d===null){l(null,null,h);return}if(m!==null&&m!==d.room_id)throw new Error("Mismatched room_id for inbound group session (expected "+d.room_id+", was "+m+")");this.unpickleInboundGroupSession(d,w=>{l(w,d,h)})})}async addInboundGroupSession(m,p,_,u,l,d,h,w={}){await this.cryptoStore.doTxn("readwrite",[r.IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS,r.IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS_WITHHELD,r.IndexedDBCryptoStore.STORE_SHARED_HISTORY_INBOUND_GROUP_SESSIONS],E=>{this.getInboundGroupSession(m,p,u,E,(I,k)=>{const M=new $e.Olm.InboundGroupSession;try{if(h?M.import_session(l):M.create(l),u!=M.session_id())throw new Error("Mismatched group session ID from senderKey: "+p);if(I&&(n.logger.log(`Update for megolm session ${p}|${u}`),I.first_known_index()<=M.first_known_index())){if(!k.untrusted||w.untrusted){n.logger.log(`Keeping existing megolm session ${p}|${u}`);return}if(I.first_known_index()<M.first_known_index()){I.export_session(M.first_known_index())===M.export_session(M.first_known_index())?(n.logger.info(`Upgrading trust of existing megolm session ${p}|${u} based on newly-received trusted session`),k.untrusted=!1,this.cryptoStore.storeEndToEndInboundGroupSession(p,u,k,E)):n.logger.warn(`Newly-received megolm session ${p}|$sessionId} does not match existing session! Keeping existing session`);return}}n.logger.info(`Storing megolm session ${p}|${u} with first index `+M.first_known_index());const L=Object.assign({},w,{room_id:m,session:M.pickle(this.pickleKey),keysClaimed:d,forwardingCurve25519KeyChain:_});this.cryptoStore.storeEndToEndInboundGroupSession(p,u,L,E),!I&&w.sharedHistory&&this.cryptoStore.addSharedHistoryInboundGroupSession(m,p,u,E)}finally{M.free()}})},n.logger.withPrefix("[addInboundGroupSession]"))}async addInboundGroupSessionWithheld(m,p,_,u,l){await this.cryptoStore.doTxn("readwrite",[r.IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS_WITHHELD],d=>{this.cryptoStore.storeEndToEndInboundGroupSessionWithheld(p,_,{room_id:m,code:u,reason:l},d)})}async decryptGroupMessage(m,p,_,u,l,d){let h=null,w;if(await this.cryptoStore.doTxn("readwrite",[r.IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS,r.IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS_WITHHELD],E=>{this.getInboundGroupSession(m,p,_,E,(I,k,M)=>{if(I===null||k===null){M&&(w=new i.DecryptionError("MEGOLM_UNKNOWN_INBOUND_SESSION_ID",y(M),{session:p+"|"+_})),h=null;return}let L;try{L=I.decrypt(u)}catch(N){(N==null?void 0:N.message)==="OLM.UNKNOWN_MESSAGE_INDEX"&&M?w=new i.DecryptionError("MEGOLM_UNKNOWN_INBOUND_SESSION_ID",y(M),{session:p+"|"+_}):w=N;return}let B=L.plaintext;if(B===void 0)B=L;else{const N=p+"|"+_+"|"+L.message_index;if(N in this.inboundGroupSessionMessageIndexes){const G=this.inboundGroupSessionMessageIndexes[N];if(G.id!==l||G.timestamp!==d){w=new Error("Duplicate message index, possible replay attack: "+N);return}}this.inboundGroupSessionMessageIndexes[N]={id:l,timestamp:d}}k.session=I.pickle(this.pickleKey),this.cryptoStore.storeEndToEndInboundGroupSession(p,_,k,E),h={result:B,keysClaimed:k.keysClaimed||{},senderKey:p,forwardingCurve25519KeyChain:k.forwardingCurve25519KeyChain||[],untrusted:!!k.untrusted}})},n.logger.withPrefix("[decryptGroupMessage]")),w)throw w;return h}async hasInboundSessionKeys(m,p,_){let u;return await this.cryptoStore.doTxn("readonly",[r.IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS,r.IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS_WITHHELD],l=>{this.cryptoStore.getEndToEndInboundGroupSession(p,_,l,d=>{if(d===null){u=!1;return}m!==d.room_id?(n.logger.warn(`requested keys for inbound group session ${p}|${_}, with incorrect room_id (expected ${d.room_id}, was ${m})`),u=!1):u=!0})},n.logger.withPrefix("[hasInboundSessionKeys]")),u}async getInboundGroupSessionKey(m,p,_,u){let l=null;return await this.cryptoStore.doTxn("readonly",[r.IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS,r.IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS_WITHHELD],d=>{this.getInboundGroupSession(m,p,_,d,(h,w)=>{if(h===null||w===null){l=null;return}u===void 0&&(u=h.first_known_index());const E=h.export_session(u),k=(w.keysClaimed||{}).ed25519||null,M=w.forwardingCurve25519KeyChain||[],L="untrusted"in w?w.untrusted:M.length>0;l={chain_index:u,key:E,forwarding_curve25519_key_chain:M,sender_claimed_ed25519_key:k,shared_history:w.sharedHistory||!1,untrusted:L}})},n.logger.withPrefix("[getInboundGroupSessionKey]")),l}exportInboundGroupSession(m,p,_){return this.unpickleInboundGroupSession(_,u=>{const l=u.first_known_index();return{sender_key:m,sender_claimed_keys:_.keysClaimed,room_id:_.room_id,session_id:p,session_key:u.export_session(l),forwarding_curve25519_key_chain:_.forwardingCurve25519KeyChain||[],first_known_index:u.first_known_index(),"org.matrix.msc3061.shared_history":_.sharedHistory||!1}})}async getSharedHistoryInboundGroupSessions(m){let p;return await this.cryptoStore.doTxn("readonly",[r.IndexedDBCryptoStore.STORE_SHARED_HISTORY_INBOUND_GROUP_SESSIONS],_=>{p=this.cryptoStore.getSharedHistoryInboundGroupSessions(m,_)},n.logger.withPrefix("[getSharedHistoryInboundGroupSessionsForRoom]")),p}verifySignature(m,p,_){this.getUtility(function(u){u.ed25519_verify(m,p,_)})}};zr.OlmDevice=s;const g={"m.unverified":"The sender has disabled encrypting to unverified devices.","m.blacklisted":"The sender has blocked you.","m.unauthorised":"You are not authorised to read the message.","m.no_olm":"Unable to establish a secure channel."};zr.WITHHELD_MESSAGES=g;function y(S){return S.code&&S.code in g?g[S.code]:S.reason?S.reason:"decryption key withheld"}return zr}var Oi={},yn={},vs={},$t={};const T3={},R3=Object.freeze(Object.defineProperty({__proto__:null,default:T3},Symbol.toStringTag,{value:"Module"})),zs=lf(R3);var lb;function n_(){if(lb)return $t;lb=1,Object.defineProperty($t,"__esModule",{value:!0}),$t.crypto=$t.TextEncoder=void 0,$t.setCrypto=y,$t.setTextEncoder=S,$t.subtleCrypto=void 0;var e=Ge(),t,n,r,i,o,a,c;let f=(t=$e.window)===null||t===void 0?void 0:t.crypto;$t.crypto=f;let v=(n=(r=$e.window)===null||r===void 0||(i=r.crypto)===null||i===void 0?void 0:i.subtle)!==null&&n!==void 0?n:(o=$e.window)===null||o===void 0||(a=o.crypto)===null||a===void 0?void 0:a.webkitSubtle;$t.subtleCrypto=v;let s=(c=$e.window)===null||c===void 0?void 0:c.TextEncoder;if($t.TextEncoder=s,!f)try{$t.crypto=f=zs.webcrypto}catch(m){e.logger.error("Failed to load webcrypto",m)}if(!v){var g;$t.subtleCrypto=v=(g=f)===null||g===void 0?void 0:g.subtle}if(!s)try{$t.TextEncoder=s=zs.TextEncoder}catch(m){e.logger.error("Failed to load TextEncoder util",m)}function y(m){var p;$t.crypto=f=m,$t.subtleCrypto=v=(p=m.subtle)!==null&&p!==void 0?p:m.webkitSubtle}function S(m){$t.TextEncoder=s=m}return $t}var ub;function Xu(){if(ub)return vs;ub=1,Object.defineProperty(vs,"__esModule",{value:!0}),vs.calculateKeyCheck=c,vs.decryptAES=i,vs.encryptAES=r;var e=ct,t=n_();const n=new Uint8Array(8);async function r(f,v,s,g){let y;g?y=(0,e.decodeBase64)(g):(y=new Uint8Array(16),t.crypto.getRandomValues(y),y[8]&=127);const[S,m]=await o(v,s),p=new t.TextEncoder().encode(f),_=await t.subtleCrypto.encrypt({name:"AES-CTR",counter:y,length:64},S,p),u=await t.subtleCrypto.sign({name:"HMAC"},m,_);return{iv:(0,e.encodeBase64)(y),ciphertext:(0,e.encodeBase64)(_),mac:(0,e.encodeBase64)(u)}}async function i(f,v,s){const[g,y]=await o(v,s),S=(0,e.decodeBase64)(f.ciphertext);if(!await t.subtleCrypto.verify({name:"HMAC"},y,(0,e.decodeBase64)(f.mac),S))throw new Error(`Error decrypting secret ${s}: bad MAC`);const m=await t.subtleCrypto.decrypt({name:"AES-CTR",counter:(0,e.decodeBase64)(f.iv),length:64},g,S);return new TextDecoder().decode(new Uint8Array(m))}async function o(f,v){const s=await t.subtleCrypto.importKey("raw",f,{name:"HKDF"},!1,["deriveBits"]),g=await t.subtleCrypto.deriveBits({name:"HKDF",salt:n,info:new t.TextEncoder().encode(v),hash:"SHA-256"},s,512),y=g.slice(0,32),S=g.slice(32),m=t.subtleCrypto.importKey("raw",y,{name:"AES-CTR"},!1,["encrypt","decrypt"]),p=t.subtleCrypto.importKey("raw",S,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign","verify"]);return Promise.all([m,p])}const a="\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";function c(f,v){return r(a,f,"",v)}return vs}var cb;function Gf(){if(cb)return yn;cb=1;var e=Ae;Object.defineProperty(yn,"__esModule",{value:!0}),yn.UserTrustLevel=yn.DeviceTrustLevel=yn.CrossSigningLevel=yn.CrossSigningInfo=void 0,yn.createCryptoStoreCacheCallbacks=S,yn.requestKeysDuringVerification=m;var t=e(Ue),n=ct,r=Ge(),i=ir,o=Xu();const a=1e3*60;function c(p){return Object.values(p.keys)[0]}class f{constructor(_,u={},l={}){this.userId=_,this.callbacks=u,this.cacheCallbacks=l,(0,t.default)(this,"keys",{}),(0,t.default)(this,"firstUse",!0),(0,t.default)(this,"crossSigningVerifiedBefore",!1)}static fromStorage(_,u){const l=new f(u);for(const d in _)_.hasOwnProperty(d)&&(l[d]=_[d]);return l}toStorage(){return{keys:this.keys,firstUse:this.firstUse,crossSigningVerifiedBefore:this.crossSigningVerifiedBefore}}async getCrossSigningKey(_,u){const l=["master","self_signing","user_signing"].indexOf(_)>=0;if(!this.callbacks.getCrossSigningKey)throw new Error("No getCrossSigningKey callback supplied");u===void 0&&(u=this.getId(_));function d(I){if(!I)return;const k=new $e.Olm.PkSigning,M=k.init_with_seed(I);if(M===u)return[M,k];k.free()}let h=null;this.cacheCallbacks.getCrossSigningKeyCache&&l&&(h=await this.cacheCallbacks.getCrossSigningKeyCache(_,u));const w=d(h);if(w)return w;h=await this.callbacks.getCrossSigningKey(_,u);const E=d(h);if(E)return this.cacheCallbacks.storeCrossSigningKeyCache&&l&&await this.cacheCallbacks.storeCrossSigningKeyCache(_,h),E;throw h?new Error("Key type "+_+" from getCrossSigningKey callback did not match"):new Error("getCrossSigningKey callback for "+_+" returned falsey")}async isStoredInSecretStorage(_){const u=await _.isStored("m.cross_signing.master")||{};function l(d){for(const h of Object.keys(u))d[h]||delete u[h]}for(const d of["self_signing","user_signing"])l(await _.isStored(`m.cross_signing.${d}`)||{});return Object.keys(u).length?u:null}static async storeInSecretStorage(_,u){for(const[l,d]of _){const h=(0,n.encodeBase64)(d);await u.store(`m.cross_signing.${l}`,h)}}static async getFromSecretStorage(_,u){const l=await u.get(`m.cross_signing.${_}`);return l?(0,n.decodeBase64)(l):null}async isStoredInKeyCache(_){const u=this.cacheCallbacks;if(!u)return!1;const l=_?[_]:["master","self_signing","user_signing"];for(const h of l){var d;if(!await((d=u.getCrossSigningKeyCache)===null||d===void 0?void 0:d.call(u,h)))return!1}return!0}async getCrossSigningKeysFromCache(){const _=new Map,u=this.cacheCallbacks;if(!u)return _;for(const d of["master","self_signing","user_signing"]){var l;const h=await((l=u.getCrossSigningKeyCache)===null||l===void 0?void 0:l.call(u,d));h&&_.set(d,h)}return _}getId(_="master"){if(!this.keys[_])return null;const u=this.keys[_];return c(u)}async resetKeys(_){if(!this.callbacks.saveCrossSigningKeys)throw new Error("No saveCrossSigningKeys callback supplied");if(_===void 0||_&s.MASTER||!this.keys.master)_=s.MASTER|s.USER_SIGNING|s.SELF_SIGNING;else if(_===0)return;const u={},l={};let d,h;try{if(_&s.MASTER?(d=new $e.Olm.PkSigning,u.master=d.generate_seed(),h=d.init_with_seed(u.master),l.master={user_id:this.userId,usage:["master"],keys:{["ed25519:"+h]:h}}):[h,d]=await this.getCrossSigningKey("master"),_&s.SELF_SIGNING){const w=new $e.Olm.PkSigning;try{u.self_signing=w.generate_seed();const E=w.init_with_seed(u.self_signing);l.self_signing={user_id:this.userId,usage:["self_signing"],keys:{["ed25519:"+E]:E}},(0,n.pkSign)(l.self_signing,d,this.userId,h)}finally{w.free()}}if(_&s.USER_SIGNING){const w=new $e.Olm.PkSigning;try{u.user_signing=w.generate_seed();const E=w.init_with_seed(u.user_signing);l.user_signing={user_id:this.userId,usage:["user_signing"],keys:{["ed25519:"+E]:E}},(0,n.pkSign)(l.user_signing,d,this.userId,h)}finally{w.free()}}Object.assign(this.keys,l),this.callbacks.saveCrossSigningKeys(u)}finally{d&&d.free()}}clearKeys(){this.keys={}}setKeys(_){const u={};if(_.master){if(_.master.user_id!==this.userId){const d="Mismatched user ID "+_.master.user_id+" in master key from "+this.userId;throw r.logger.error(d),new Error(d)}this.keys.master?c(_.master)!==this.getId()&&(this.firstUse=!1):this.firstUse=!0,u.master=_.master}else if(this.keys.master)u.master=this.keys.master;else throw new Error("Tried to set cross-signing keys without a master key");const l=c(u.master);if(_.user_signing){if(_.user_signing.user_id!==this.userId){const d="Mismatched user ID "+_.master.user_id+" in user_signing key from "+this.userId;throw r.logger.error(d),new Error(d)}try{(0,n.pkVerify)(_.user_signing,l,this.userId)}catch(d){throw r.logger.error("invalid signature on user-signing key"),d}}if(_.self_signing){if(_.self_signing.user_id!==this.userId){const d="Mismatched user ID "+_.master.user_id+" in self_signing key from "+this.userId;throw r.logger.error(d),new Error(d)}try{(0,n.pkVerify)(_.self_signing,l,this.userId)}catch(d){throw r.logger.error("invalid signature on self-signing key"),d}}_.master&&(this.keys.master=_.master,delete this.keys.self_signing,delete this.keys.user_signing),_.self_signing&&(this.keys.self_signing=_.self_signing),_.user_signing&&(this.keys.user_signing=_.user_signing)}updateCrossSigningVerifiedBefore(_){!this.crossSigningVerifiedBefore&&_&&(this.crossSigningVerifiedBefore=!0)}async signObject(_,u){if(!this.keys[u])throw new Error("Attempted to sign with "+u+" key but no such key present");const[l,d]=await this.getCrossSigningKey(u);try{return(0,n.pkSign)(_,d,this.userId,l),_}finally{d.free()}}async signUser(_){if(!this.keys.user_signing){r.logger.info("No user signing key: not signing user");return}return this.signObject(_.keys.master,"user_signing")}async signDevice(_,u){if(_!==this.userId)throw new Error(`Trying to sign ${_}'s device; can only sign our own device`);if(!this.keys.self_signing){r.logger.info("No self signing key: not signing device");return}return this.signObject({algorithms:u.algorithms,keys:u.keys,device_id:u.deviceId,user_id:_},"self_signing")}checkUserTrust(_){if(this.userId===_.userId&&this.getId()&&this.getId()===_.getId()&&this.getId("self_signing")&&this.getId("self_signing")===_.getId("self_signing"))return new g(!0,!0,this.firstUse);if(!this.keys.user_signing)return new g(!1,!1,_.firstUse);let u;const l=_.keys.master,d=this.getId("user_signing");try{(0,n.pkVerify)(l,d,this.userId),u=!0}catch{u=!1}return new g(u,_.crossSigningVerifiedBefore,_.firstUse)}checkDeviceTrust(_,u,l,d){const h=this.checkUserTrust(_),w=_.keys.self_signing;if(!w)return new y(!1,!1,l,d);const E=v(u,_.userId);try{return(0,n.pkVerify)(w,_.getId(),_.userId),(0,n.pkVerify)(E,c(w),_.userId),y.fromUserTrustLevel(h,l,d)}catch{return new y(!1,!1,l,d)}}getCacheCallbacks(){return this.cacheCallbacks}}yn.CrossSigningInfo=f;function v(p,_){return{algorithms:p.algorithms,keys:p.keys,device_id:p.deviceId,user_id:_,signatures:p.signatures}}let s;yn.CrossSigningLevel=s,function(p){p[p.MASTER=4]="MASTER",p[p.USER_SIGNING=2]="USER_SIGNING",p[p.SELF_SIGNING=1]="SELF_SIGNING"}(s||(yn.CrossSigningLevel=s={}));class g{constructor(_,u,l){this.crossSigningVerified=_,this.crossSigningVerifiedBefore=u,this.tofu=l}isVerified(){return this.isCrossSigningVerified()}isCrossSigningVerified(){return this.crossSigningVerified}wasCrossSigningVerified(){return this.crossSigningVerifiedBefore}isTofu(){return this.tofu}}yn.UserTrustLevel=g;class y{constructor(_,u,l,d){this.crossSigningVerified=_,this.tofu=u,this.localVerified=l,this.trustCrossSignedDevices=d}static fromUserTrustLevel(_,u,l){return new y(_.isCrossSigningVerified(),_.isTofu(),u,l)}isVerified(){return Boolean(this.isLocallyVerified()||this.trustCrossSignedDevices&&this.isCrossSigningVerified())}isCrossSigningVerified(){return this.crossSigningVerified}isLocallyVerified(){return this.localVerified}isTofu(){return this.tofu}}yn.DeviceTrustLevel=y;function S(p,_){return{getCrossSigningKeyCache:async function(u,l){const d=await new Promise(h=>p.doTxn("readonly",[i.IndexedDBCryptoStore.STORE_ACCOUNT],w=>{p.getSecretStorePrivateKey(w,h,u)}));if(d&&d.ciphertext){const h=Buffer.from(_.pickleKey),w=await(0,o.decryptAES)(d,h,u);return(0,n.decodeBase64)(w)}else return d},storeCrossSigningKeyCache:async function(u,l){if(!(l instanceof Uint8Array))throw new Error(`storeCrossSigningKeyCache expects Uint8Array, got ${l}`);const d=Buffer.from(_.pickleKey),h=await(0,o.encryptAES)((0,n.encodeBase64)(l),d,u);return p.doTxn("readwrite",[i.IndexedDBCryptoStore.STORE_ACCOUNT],w=>{p.storeSecretStorePrivateKey(w,u,h)})}}}async function m(p,_,u){if(p.getUserId()===_)return r.logger.log("Cross-signing: Self-verification done; requesting keys"),new Promise((l,d)=>{const h=p,w=h.crypto.crossSigningInfo,E=new f(w.userId,{getCrossSigningKey:async M=>{r.logger.debug("Cross-signing: requesting secret",M,u);const{promise:L}=h.requestSecret(`m.cross_signing.${M}`,[u]),B=await L,N=(0,n.decodeBase64)(B);return Uint8Array.from(N)}},w.getCacheCallbacks());E.keys=w.keys;const I=new Promise(M=>{setTimeout(M,a,new Error("Timeout"))}),k=(async()=>{if(!await h.crypto.getSessionBackupPrivateKey()){r.logger.info("No cached backup key found. Requesting...");const B=await h.requestSecret("m.megolm_backup.v1",[u]).promise;r.logger.info("Got key backup key, decoding...");const N=(0,n.decodeBase64)(B);r.logger.info("Decoded backup key, storing..."),await h.crypto.storeSessionBackupPrivateKey(Uint8Array.from(N)),r.logger.info("Backup key stored. Starting backup restore...");const G=await h.getKeyBackupVersion();h.restoreKeyBackupWithCache(void 0,void 0,G).then(()=>{r.logger.info("Backup restored.")})}})();return Promise.race([Promise.all([E.getCrossSigningKey("master"),E.getCrossSigningKey("self_signing"),E.getCrossSigningKey("user_signing"),k]),I]).then(l,d)}).catch(l=>{r.logger.warn("Cross-signing: failure while requesting keys:",l)})}return yn}var db;function I3(){if(db)return Oi;db=1;var e=Ae;Object.defineProperty(Oi,"__esModule",{value:!0}),Oi.TrackingStatus=Oi.DeviceList=void 0;var t=e(Ue),n=Ge(),r=Qu(),i=Gf(),o=g(ct),a=ir,c=lt(),f=Pt(),v=a_();function s(u){if(typeof WeakMap!="function")return null;var l=new WeakMap,d=new WeakMap;return(s=function(h){return h?d:l})(u)}function g(u,l){if(!l&&u&&u.__esModule)return u;if(u===null||typeof u!="object"&&typeof u!="function")return{default:u};var d=s(l);if(d&&d.has(u))return d.get(u);var h={},w=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var E in u)if(E!=="default"&&Object.prototype.hasOwnProperty.call(u,E)){var I=w?Object.getOwnPropertyDescriptor(u,E):null;I&&(I.get||I.set)?Object.defineProperty(h,E,I):h[E]=u[E]}return h.default=u,d&&d.set(u,h),h}let y;Oi.TrackingStatus=y,function(u){u[u.NotTracked=0]="NotTracked",u[u.PendingDownload=1]="PendingDownload",u[u.DownloadInProgress=2]="DownloadInProgress",u[u.UpToDate=3]="UpToDate"}(y||(Oi.TrackingStatus=y={}));let S=class extends f.TypedEventEmitter{constructor(l,d,h,w=250){super(),this.cryptoStore=d,this.keyDownloadChunkSize=w,(0,t.default)(this,"devices",{}),(0,t.default)(this,"crossSigningInfo",{}),(0,t.default)(this,"userByIdentityKey",{}),(0,t.default)(this,"deviceTrackingStatus",{}),(0,t.default)(this,"syncToken",null),(0,t.default)(this,"keyDownloadsInProgressByUser",new Map),(0,t.default)(this,"dirty",!1),(0,t.default)(this,"savePromise",null),(0,t.default)(this,"resolveSavePromise",null),(0,t.default)(this,"savePromiseTime",null),(0,t.default)(this,"saveTimer",null),(0,t.default)(this,"hasFetched",null),(0,t.default)(this,"serialiser",void 0),this.serialiser=new m(l,h,this)}async load(){await this.cryptoStore.doTxn("readonly",[a.IndexedDBCryptoStore.STORE_DEVICE_DATA],l=>{this.cryptoStore.getEndToEndDeviceData(l,d=>{var h;this.hasFetched=Boolean(d&&d.devices),this.devices=d?d.devices:{},this.crossSigningInfo=d?d.crossSigningInfo||{}:{},this.deviceTrackingStatus=d?d.trackingStatus:{},this.syncToken=(h=d==null?void 0:d.syncToken)!==null&&h!==void 0?h:null,this.userByIdentityKey={};for(const w of Object.keys(this.devices)){const E=this.devices[w];for(const I of Object.keys(E)){const k=E[I].keys["curve25519:"+I];k!==void 0&&(this.userByIdentityKey[k]=w)}}})});for(const l of Object.keys(this.deviceTrackingStatus))this.deviceTrackingStatus[l]==y.DownloadInProgress&&(this.deviceTrackingStatus[l]=y.PendingDownload)}stop(){this.saveTimer!==null&&clearTimeout(this.saveTimer)}async saveIfDirty(l=500){if(!this.dirty)return Promise.resolve(!1);const d=Date.now()+l;this.savePromiseTime&&d<this.savePromiseTime&&(clearTimeout(this.saveTimer),this.saveTimer=null,this.savePromiseTime=null);let h=this.savePromise;if(h===null&&(h=new Promise(w=>{this.resolveSavePromise=w}),this.savePromise=h),this.saveTimer===null){const w=this.resolveSavePromise;this.savePromiseTime=d,this.saveTimer=setTimeout(()=>{n.logger.log("Saving device tracking data",this.syncToken),this.savePromiseTime=null,this.saveTimer=null,this.savePromise=null,this.resolveSavePromise=null,this.cryptoStore.doTxn("readwrite",[a.IndexedDBCryptoStore.STORE_DEVICE_DATA],E=>{var I;this.cryptoStore.storeEndToEndDeviceData({devices:this.devices,crossSigningInfo:this.crossSigningInfo,trackingStatus:this.deviceTrackingStatus,syncToken:(I=this.syncToken)!==null&&I!==void 0?I:void 0},E)}).then(()=>{this.dirty=!1,w==null||w(!0)},E=>{n.logger.error("Failed to save device tracking data",this.syncToken),n.logger.error(E)})},l)}return h}getSyncToken(){return this.syncToken}setSyncToken(l){this.syncToken=l}downloadKeys(l,d){const h=[],w=[];if(l.forEach(E=>{const I=this.deviceTrackingStatus[E];this.keyDownloadsInProgressByUser.has(E)?(n.logger.log(`downloadKeys: already have a download in progress for ${E}: awaiting its result`),w.push(this.keyDownloadsInProgressByUser.get(E))):(d||I!=y.UpToDate)&&h.push(E)}),h.length!=0){n.logger.log("downloadKeys: downloading for",h);const E=this.doKeyDownload(h);w.push(E)}return w.length===0&&n.logger.log("downloadKeys: already have all necessary keys"),Promise.all(w).then(()=>this.getDevicesFromStore(l))}getDevicesFromStore(l){const d={};return l.forEach(h=>{d[h]={},(this.getStoredDevicesForUser(h)||[]).forEach(function(E){d[h][E.deviceId]=E})}),d}getKnownUserIds(){return Object.keys(this.devices)}getStoredDevicesForUser(l){const d=this.devices[l];if(!d)return null;const h=[];for(const w in d)d.hasOwnProperty(w)&&h.push(r.DeviceInfo.fromStorage(d[w],w));return h}getRawStoredDevicesForUser(l){return this.devices[l]}getStoredCrossSigningForUser(l){return this.crossSigningInfo[l]?i.CrossSigningInfo.fromStorage(this.crossSigningInfo[l],l):null}storeCrossSigningForUser(l,d){this.crossSigningInfo[l]=d,this.dirty=!0}getStoredDevice(l,d){const h=this.devices[l];if(h!=null&&h[d])return r.DeviceInfo.fromStorage(h[d],d)}getUserByIdentityKey(l,d){return l!==o.OLM_ALGORITHM&&l!==o.MEGOLM_ALGORITHM?null:this.userByIdentityKey[d]}getDeviceByIdentityKey(l,d){const h=this.getUserByIdentityKey(l,d);if(!h)return null;const w=this.devices[h];if(!w)return null;for(const E in w){if(!w.hasOwnProperty(E))continue;const I=w[E];for(const k in I.keys){if(!I.keys.hasOwnProperty(k)||k.indexOf("curve25519:")!==0)continue;if(I.keys[k]==d)return r.DeviceInfo.fromStorage(I,E)}}return null}storeDevicesForUser(l,d){this.setRawStoredDevicesForUser(l,d),this.dirty=!0}startTrackingDeviceList(l){if(typeof l!="string")throw new Error("userId must be a string; was "+l);this.deviceTrackingStatus[l]||(n.logger.log("Now tracking device list for "+l),this.deviceTrackingStatus[l]=y.PendingDownload,this.dirty=!0)}stopTrackingDeviceList(l){this.deviceTrackingStatus[l]&&(n.logger.log("No longer tracking device list for "+l),this.deviceTrackingStatus[l]=y.NotTracked,this.dirty=!0)}stopTrackingAllDeviceLists(){for(const l of Object.keys(this.deviceTrackingStatus))this.deviceTrackingStatus[l]=y.NotTracked;this.dirty=!0}invalidateUserDeviceList(l){this.deviceTrackingStatus[l]&&(n.logger.log("Marking device list outdated for",l),this.deviceTrackingStatus[l]=y.PendingDownload,this.dirty=!0)}refreshOutdatedDeviceLists(){this.saveIfDirty();const l=[];for(const d of Object.keys(this.deviceTrackingStatus))this.deviceTrackingStatus[d]==y.PendingDownload&&l.push(d);return this.doKeyDownload(l)}setRawStoredDevicesForUser(l,d){if(this.devices[l]!==void 0)for(const[h,w]of Object.entries(this.devices[l])){const E=w.keys["curve25519:"+h];delete this.userByIdentityKey[E]}this.devices[l]=d;for(const[h,w]of Object.entries(d)){const E=w.keys["curve25519:"+h];this.userByIdentityKey[E]=l}}setRawStoredCrossSigningForUser(l,d){this.crossSigningInfo[l]=d}doKeyDownload(l){if(l.length===0)return Promise.resolve();const d=this.serialiser.updateDevicesForUsers(l,this.syncToken).then(()=>{h(!0)},w=>{throw n.logger.error("Error downloading keys for "+l+":",w),h(!1),w});l.forEach(w=>{this.keyDownloadsInProgressByUser.set(w,d),this.deviceTrackingStatus[w]==y.PendingDownload&&(this.deviceTrackingStatus[w]=y.DownloadInProgress)});const h=w=>{this.emit(v.CryptoEvent.WillUpdateDevices,l,!this.hasFetched),l.forEach(E=>{if(this.dirty=!0,this.keyDownloadsInProgressByUser.get(E)!==d){n.logger.log("Another update in the queue for",E,"- not marking up-to-date");return}this.keyDownloadsInProgressByUser.delete(E),this.deviceTrackingStatus[E]==y.DownloadInProgress&&(w?(this.deviceTrackingStatus[E]=y.UpToDate,n.logger.log("Device list for",E,"now up to date")):this.deviceTrackingStatus[E]=y.PendingDownload)}),this.saveIfDirty(),this.emit(v.CryptoEvent.DevicesUpdated,l,!this.hasFetched),this.hasFetched=!0};return d}};Oi.DeviceList=S;class m{constructor(l,d,h){this.baseApis=l,this.olmDevice=d,this.deviceList=h,(0,t.default)(this,"downloadInProgress",!1),(0,t.default)(this,"keyDownloadsQueuedByUser",{}),(0,t.default)(this,"queuedQueryDeferred",void 0),(0,t.default)(this,"syncToken",void 0)}updateDevicesForUsers(l,d){return l.forEach(h=>{this.keyDownloadsQueuedByUser[h]=!0}),this.queuedQueryDeferred||(this.queuedQueryDeferred=(0,c.defer)()),this.syncToken=d,this.downloadInProgress?(n.logger.log("Queued key download for",l),this.queuedQueryDeferred.promise):this.doQueuedQueries()}doQueuedQueries(){if(this.downloadInProgress)throw new Error("DeviceListUpdateSerialiser.doQueuedQueries called with request active");const l=Object.keys(this.keyDownloadsQueuedByUser);this.keyDownloadsQueuedByUser={};const d=this.queuedQueryDeferred;this.queuedQueryDeferred=void 0,n.logger.log("Starting key download for",l),this.downloadInProgress=!0;const h={};this.syncToken&&(h.token=this.syncToken);const w=[];for(let E=0;E<l.length;E+=this.deviceList.keyDownloadChunkSize){const I=l.slice(E,E+this.deviceList.keyDownloadChunkSize);w.push(()=>this.baseApis.downloadKeysForUsers(I,h))}return(0,c.chunkPromises)(w,3).then(async E=>{const I=Object.assign({},...E.map(B=>B.device_keys||{})),k=Object.assign({},...E.map(B=>B.master_keys||{})),M=Object.assign({},...E.map(B=>B.self_signing_keys||{})),L=Object.assign({},...E.map(B=>B.user_signing_keys||{}));for(const B of l){await(0,c.sleep)(5);try{await this.processQueryResponseForUser(B,I[B],{master:k==null?void 0:k[B],self_signing:M==null?void 0:M[B],user_signing:L==null?void 0:L[B]})}catch(N){n.logger.error(`Error processing keys for ${B}:`,N)}}}).then(()=>{n.logger.log("Completed key download for "+l),this.downloadInProgress=!1,d==null||d.resolve(),this.queuedQueryDeferred&&this.doQueuedQueries()},E=>{n.logger.warn("Error downloading keys for "+l+":",E),this.downloadInProgress=!1,d==null||d.reject(E)}),d.promise}async processQueryResponseForUser(l,d,h){n.logger.log("got device keys for "+l+":",d),n.logger.log("got cross-signing keys for "+l+":",h);{const w={},E=this.deviceList.getRawStoredDevicesForUser(l);E&&Object.keys(E).forEach(k=>{const M=r.DeviceInfo.fromStorage(E[k],k);w[k]=M}),await p(this.olmDevice,l,w,d||{},this.baseApis.getUserId(),this.baseApis.deviceId);const I={};Object.keys(w).forEach(k=>{I[k]=w[k].toStorage()}),this.deviceList.setRawStoredDevicesForUser(l,I)}if(h&&(h.master||h.self_signing||h.user_signing)){const w=this.deviceList.getStoredCrossSigningForUser(l)||new i.CrossSigningInfo(l);w.setKeys(h),this.deviceList.setRawStoredCrossSigningForUser(l,w.toStorage()),this.deviceList.emit(v.CryptoEvent.UserCrossSigningUpdated,l)}}}async function p(u,l,d,h,w,E){let I=!1;for(const k in d)if(d.hasOwnProperty(k)&&!(k in h)){if(l===w&&k===E){n.logger.warn(`Local device ${k} missing from sync, skipping removal`);continue}n.logger.log("Device "+l+":"+k+" has been removed"),delete d[k],I=!0}for(const k in h){if(!h.hasOwnProperty(k))continue;const M=h[k];if(M.user_id!==l){n.logger.warn("Mismatched user_id "+M.user_id+" in keys from "+l+":"+k);continue}if(M.device_id!==k){n.logger.warn("Mismatched device_id "+M.device_id+" in keys from "+l+":"+k);continue}await _(u,d,M)&&(I=!0)}return I}async function _(u,l,d){if(!d.keys)return!1;const h=d.device_id,w=d.user_id,E="ed25519:"+h,I=d.keys[E];if(!I)return n.logger.warn("Device "+w+":"+h+" has no ed25519 key"),!1;const k=d.unsigned||{},M=d.signatures||{};try{await o.verifySignature(u,d,w,h,I)}catch(B){return n.logger.warn("Unable to verify signature on device "+w+":"+h+":"+B),!1}let L;if(h in l){if(L=l[h],L.getFingerprint()!=I)return n.logger.warn("Ed25519 key for device "+w+":"+h+" has changed"),!1}else l[h]=L=new r.DeviceInfo(h);return L.keys=d.keys||{},L.algorithms=d.algorithms||[],L.unsigned=k,L.signatures=M,!0}return Oi}var Eo={},fb;function C3(){if(fb)return Eo;fb=1;var e=Ae;Object.defineProperty(Eo,"__esModule",{value:!0}),Eo.EncryptionSetupOperation=Eo.EncryptionSetupBuilder=void 0;var t=e(Ue),n=Ge(),r=nn(),i=Gf(),o=ir,a=Rr,c=or(),f=Pt();class v{constructor(p,_){(0,t.default)(this,"accountDataClientAdapter",void 0),(0,t.default)(this,"crossSigningCallbacks",void 0),(0,t.default)(this,"ssssCryptoCallbacks",void 0),(0,t.default)(this,"crossSigningKeys",void 0),(0,t.default)(this,"keySignatures",void 0),(0,t.default)(this,"keyBackupInfo",void 0),(0,t.default)(this,"sessionBackupPrivateKey",void 0),this.accountDataClientAdapter=new g(p),this.crossSigningCallbacks=new y,this.ssssCryptoCallbacks=new S(_)}addCrossSigningKeys(p,_){this.crossSigningKeys={authUpload:p,keys:_}}addSessionBackup(p){this.keyBackupInfo=p}addSessionBackupPrivateKeyToCache(p){this.sessionBackupPrivateKey=p}addKeySignature(p,_,u){this.keySignatures||(this.keySignatures={});const l=this.keySignatures[p]||{};this.keySignatures[p]=l,l[_]=u}async setAccountData(p,_){await this.accountDataClientAdapter.setAccountData(p,_)}buildOperation(){const p=this.accountDataClientAdapter.values;return new s(p,this.crossSigningKeys,this.keyBackupInfo,this.keySignatures)}async persist(p){if(this.crossSigningKeys){const u=(0,i.createCryptoStoreCacheCallbacks)(p.cryptoStore,p.olmDevice);for(const l of["master","self_signing","user_signing"]){var _;n.logger.log(`Cache ${l} cross-signing private key locally`);const d=this.crossSigningCallbacks.privateKeys.get(l);await((_=u.storeCrossSigningKeyCache)===null||_===void 0?void 0:_.call(u,l,d))}await p.cryptoStore.doTxn("readwrite",[o.IndexedDBCryptoStore.STORE_ACCOUNT],l=>{p.cryptoStore.storeCrossSigningKeys(l,this.crossSigningKeys.keys)})}this.sessionBackupPrivateKey&&await p.storeSessionBackupPrivateKey(this.sessionBackupPrivateKey)}}Eo.EncryptionSetupBuilder=v;class s{constructor(p,_,u,l){this.accountData=p,this.crossSigningKeys=_,this.keyBackupInfo=u,this.keySignatures=l}async apply(p){const _=p.baseApis;if(this.crossSigningKeys){var u,l;const d={};for(const[h,w]of Object.entries(this.crossSigningKeys.keys))d[h+"_key"]=w;await((u=(l=this.crossSigningKeys).authUpload)===null||u===void 0?void 0:u.call(l,h=>_.uploadDeviceSigningKeys(h,d))),p.crossSigningInfo.setKeys(this.crossSigningKeys.keys)}if(this.accountData)for(const[d,h]of this.accountData)await _.setAccountData(d,h);this.keySignatures&&await _.uploadKeySignatures(this.keySignatures),this.keyBackupInfo&&(this.keyBackupInfo.version?await _.http.authedRequest(a.Method.Put,"/room_keys/version/"+this.keyBackupInfo.version,void 0,{algorithm:this.keyBackupInfo.algorithm,auth_data:this.keyBackupInfo.auth_data},{prefix:a.ClientPrefix.V3}):await _.http.authedRequest(a.Method.Post,"/room_keys/version",void 0,this.keyBackupInfo,{prefix:a.ClientPrefix.V3}))}}Eo.EncryptionSetupOperation=s;class g extends f.TypedEventEmitter{constructor(p){super(),this.existingValues=p,(0,t.default)(this,"values",new Map)}getAccountDataFromServer(p){return Promise.resolve(this.getAccountData(p))}getAccountData(p){const _=this.values.get(p);if(_)return _;const u=this.existingValues[p];return u?u.getContent():null}setAccountData(p,_){const u=this.values.get(p);return this.values.set(p,_),Promise.resolve().then(()=>{const l=new r.MatrixEvent({type:p,content:_});return this.emit(c.ClientEvent.AccountData,l,u),{}})}}class y{constructor(){(0,t.default)(this,"privateKeys",new Map)}getCrossSigningKeyCache(p,_){return this.getCrossSigningKey(p,_)}storeCrossSigningKeyCache(p,_){return this.privateKeys.set(p,_),Promise.resolve()}getCrossSigningKey(p,_){var u;return Promise.resolve((u=this.privateKeys.get(p))!==null&&u!==void 0?u:null)}saveCrossSigningKeys(p){for(const[_,u]of Object.entries(p))this.privateKeys.set(_,u)}}class S{constructor(p){this.delegateCryptoCallbacks=p,(0,t.default)(this,"privateKeys",new Map)}async getSecretStorageKey({keys:p},_){var u;for(const l of Object.keys(p)){const d=this.privateKeys.get(l);if(d)return[l,d]}if(this!==null&&this!==void 0&&(u=this.delegateCryptoCallbacks)!==null&&u!==void 0&&u.getSecretStorageKey){const l=await this.delegateCryptoCallbacks.getSecretStorageKey({keys:p},_);if(l){const[d,h]=l;this.privateKeys.set(d,h)}return l}return null}addPrivateKey(p,_,u){var l,d;this.privateKeys.set(p,u),(l=this.delegateCryptoCallbacks)===null||l===void 0||(d=l.cacheSecretStorageKey)===null||d===void 0||d.call(l,p,_,u)}}return Eo}var wo={},hb;function O3(){if(hb)return wo;hb=1;var e=Ae;Object.defineProperty(wo,"__esModule",{value:!0}),wo.SecretStorage=wo.SECRET_STORAGE_ALGORITHM_V1_AES=void 0;var t=e(Ue),n=zu,r=Ge(),i=g(ct),o=Yu(),a=Xu(),c=or(),f=lt(),v=xe;function s(m){if(typeof WeakMap!="function")return null;var p=new WeakMap,_=new WeakMap;return(s=function(u){return u?_:p})(m)}function g(m,p){if(!p&&m&&m.__esModule)return m;if(m===null||typeof m!="object"&&typeof m!="function")return{default:m};var _=s(p);if(_&&_.has(m))return _.get(m);var u={},l=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var d in m)if(d!=="default"&&Object.prototype.hasOwnProperty.call(m,d)){var h=l?Object.getOwnPropertyDescriptor(m,d):null;h&&(h.get||h.set)?Object.defineProperty(u,d,h):u[d]=m[d]}return u.default=m,_&&_.set(m,u),u}const y="m.secret_storage.v1.aes-hmac-sha2";wo.SECRET_STORAGE_ALGORITHM_V1_AES=y;let S=class{constructor(p,_,u){this.accountDataAdapter=p,this.cryptoCallbacks=_,this.baseApis=u,(0,t.default)(this,"requests",new Map)}async getDefaultKeyId(){const p=await this.accountDataAdapter.getAccountDataFromServer("m.secret_storage.default_key");return p?p.key:null}setDefaultKeyId(p){return new Promise((_,u)=>{const l=d=>{d.getType()==="m.secret_storage.default_key"&&d.getContent().key===p&&(this.accountDataAdapter.removeListener(c.ClientEvent.AccountData,l),_())};this.accountDataAdapter.on(c.ClientEvent.AccountData,l),this.accountDataAdapter.setAccountData("m.secret_storage.default_key",{key:p}).catch(d=>{this.accountDataAdapter.removeListener(c.ClientEvent.AccountData,l),u(d)})})}async addKey(p,_={},u){const l={algorithm:p};if(_.name&&(l.name=_.name),p===y){if(_.passphrase&&(l.passphrase=_.passphrase),_.key){const{iv:d,mac:h}=await(0,a.calculateKeyCheck)(_.key);l.iv=d,l.mac=h}}else throw new Error(`Unknown key algorithm ${p}`);if(!u)do u=(0,o.randomString)(32);while(await this.accountDataAdapter.getAccountDataFromServer(`m.secret_storage.key.${u}`));return await this.accountDataAdapter.setAccountData(`m.secret_storage.key.${u}`,l),{keyId:u,keyInfo:l}}async getKey(p){if(p||(p=await this.getDefaultKeyId()),!p)return null;const _=await this.accountDataAdapter.getAccountDataFromServer("m.secret_storage.key."+p);return _?[p,_]:null}async hasKey(p){return Boolean(await this.getKey(p))}async checkKey(p,_){if(_.algorithm===y)if(_.mac){const{mac:u}=await(0,a.calculateKeyCheck)(p,_.iv);return _.mac.replace(/=+$/g,"")===u.replace(/=+$/g,"")}else return!0;else throw new Error("Unknown algorithm")}async store(p,_,u){const l={};if(!u){const d=await this.getDefaultKeyId();if(!d)throw new Error("No keys specified and no default key present");u=[d]}if(u.length===0)throw new Error("Zero keys given to encrypt with!");for(const d of u){const h=await this.accountDataAdapter.getAccountDataFromServer("m.secret_storage.key."+d);if(!h)throw new Error("Unknown key: "+d);if(h.algorithm===y){const w={[d]:h},[,E]=await this.getSecretStorageKey(w,p);l[d]=await E.encrypt(_)}else r.logger.warn("unknown algorithm for secret storage key "+d+": "+h.algorithm)}await this.accountDataAdapter.setAccountData(p,{encrypted:l})}async get(p){const _=await this.accountDataAdapter.getAccountDataFromServer(p);if(!_)return;if(!_.encrypted)throw new Error("Content is not encrypted!");const u={};for(const w of Object.keys(_.encrypted)){const E=await this.accountDataAdapter.getAccountDataFromServer("m.secret_storage.key."+w),I=_.encrypted[w];E.algorithm===y&&I.iv&&I.ciphertext&&I.mac&&(u[w]=E)}if(Object.keys(u).length===0)throw new Error(`Could not decrypt ${p} because none of the keys it is encrypted with are for a supported algorithm`);const[l,d]=await this.getSecretStorageKey(u,p),h=_.encrypted[l];return d.decrypt(h)}async isStored(p){const _=await this.accountDataAdapter.getAccountDataFromServer(p);if(!(_!=null&&_.encrypted))return null;const u={};for(const l of Object.keys(_.encrypted)){const d=await this.accountDataAdapter.getAccountDataFromServer("m.secret_storage.key."+l);if(!d)continue;const h=_.encrypted[l];d.algorithm===y&&h.iv&&h.ciphertext&&h.mac&&(u[l]=d)}return Object.keys(u).length?u:null}request(p,_){const u=this.baseApis.makeTxnId(),l=(0,f.defer)();this.requests.set(u,{name:p,devices:_,deferred:l});const d=E=>{const I={action:"request_cancellation",requesting_device_id:this.baseApis.deviceId,request_id:u},k={};for(const M of _)k[M]=I;this.baseApis.sendToDevice("m.secret.request",{[this.baseApis.getUserId()]:k}),l.reject(new Error(E||"Cancelled"))},h={name:p,action:"request",requesting_device_id:this.baseApis.deviceId,request_id:u,[v.ToDeviceMessageId]:(0,n.v4)()},w={};for(const E of _)w[E]=h;return r.logger.info(`Request secret ${p} from ${_}, id ${u}`),this.baseApis.sendToDevice("m.secret.request",{[this.baseApis.getUserId()]:w}),{requestId:u,promise:l.promise,cancel:d}}async onRequestReceived(p){const _=p.getSender(),u=p.getContent();if(_!==this.baseApis.getUserId()||!(u.name&&u.action&&u.requesting_device_id&&u.request_id))return;const l=u.requesting_device_id;if(u.action!=="request_cancellation"){if(u.action==="request"){if(l===this.baseApis.deviceId||(r.logger.info("received request for secret ("+_+", "+l+", "+u.request_id+")"),!this.cryptoCallbacks.onSecretRequested))return;const d=await this.cryptoCallbacks.onSecretRequested(_,l,u.request_id,u.name,this.baseApis.checkDeviceTrust(_,l));if(d){r.logger.info(`Preparing ${u.name} secret for ${l}`);const h={type:"m.secret.send",content:{request_id:u.request_id,secret:d}},w={algorithm:i.OLM_ALGORITHM,sender_key:this.baseApis.crypto.olmDevice.deviceCurve25519Key,ciphertext:{},[v.ToDeviceMessageId]:(0,n.v4)()};await i.ensureOlmSessionsForDevices(this.baseApis.crypto.olmDevice,this.baseApis,{[_]:[this.baseApis.getStoredDevice(_,l)]}),await i.encryptMessageForDevice(w.ciphertext,this.baseApis.getUserId(),this.baseApis.deviceId,this.baseApis.crypto.olmDevice,_,this.baseApis.getStoredDevice(_,l),h);const E={[_]:{[l]:w}};r.logger.info(`Sending ${u.name} secret for ${l}`),this.baseApis.sendToDevice("m.room.encrypted",E)}else r.logger.info(`Request denied for ${u.name} secret for ${l}`)}}}onSecretReceived(p){if(p.getSender()!==this.baseApis.getUserId())return;if(!i.isOlmEncrypted(p)){r.logger.error("secret event not properly encrypted");return}const _=p.getContent();if(this.baseApis.crypto.deviceList.getUserByIdentityKey(i.OLM_ALGORITHM,p.getSenderKey()||"")!==p.getSender()){r.logger.error("sending device does not belong to the user it claims to be from");return}r.logger.log("got secret share for request",_.request_id);const l=this.requests.get(_.request_id);if(l){const d=this.baseApis.crypto.deviceList.getDeviceByIdentityKey(i.OLM_ALGORITHM,p.getSenderKey());if(!d){r.logger.log("secret share from unknown device with key",p.getSenderKey());return}if(!l.devices.includes(d.deviceId)){r.logger.log("unsolicited secret share from device",d.deviceId);return}if(!this.baseApis.crypto.checkDeviceInfoTrust(p.getSender(),d).isVerified()){r.logger.log("secret share from unverified device");return}r.logger.log(`Successfully received secret ${l.name} from ${d.deviceId}`),l.deferred.resolve(_.secret)}}async getSecretStorageKey(p,_){if(!this.cryptoCallbacks.getSecretStorageKey)throw new Error("No getSecretStorageKey callback supplied");const u=await this.cryptoCallbacks.getSecretStorageKey({keys:p},_);if(!u)throw new Error("getSecretStorageKey callback returned falsey");if(u.length<2)throw new Error("getSecretStorageKey callback returned invalid data");const[l,d]=u;if(!p[l])throw new Error("App returned unknown key from getSecretStorageKey!");if(p[l].algorithm===y)return[l,{encrypt:function(w){return(0,a.encryptAES)(w,d,_)},decrypt:function(w){return(0,a.decryptAES)(w,d,_)}}];throw new Error("Unknown key type: "+p[l].algorithm)}};return wo.SecretStorage=S,wo}var _n={},Ar={},Lt={},pb;function Zu(){if(pb)return Lt;pb=1,Object.defineProperty(Lt,"__esModule",{value:!0}),Lt.errorFactory=r,Lt.errorFromEvent=s,Lt.newUserCancelledError=Lt.newUnknownMethodError=Lt.newUnexpectedMessageError=Lt.newTimeoutError=Lt.newKeyMismatchError=Lt.newInvalidMessageError=void 0,Lt.newVerificationError=n;var e=nn(),t=xe;function n(g,y,S){const m=Object.assign({},{code:g,reason:y},S);return new e.MatrixEvent({type:t.EventType.KeyVerificationCancel,content:m})}function r(g,y){return function(S){return n(g,y,S)}}const i=r("m.user","Cancelled by user");Lt.newUserCancelledError=i;const o=r("m.timeout","Timed out");Lt.newTimeoutError=o;const a=r("m.unknown_method","Unknown method");Lt.newUnknownMethodError=a;const c=r("m.unexpected_message","Unexpected message");Lt.newUnexpectedMessageError=c;const f=r("m.key_mismatch","Key mismatch");Lt.newKeyMismatchError=f;const v=r("m.invalid_message","Invalid message");Lt.newInvalidMessageError=v;function s(g){const y=g.getContent();if(y){const{code:S,reason:m}=y;return{code:S,reason:m}}else return{code:"Unknown error",reason:"m.unknown"}}return Lt}var gb;function r_(){if(gb)return Ar;gb=1;var e=Ae;Object.defineProperty(Ar,"__esModule",{value:!0}),Ar.VerificationEvent=Ar.VerificationBase=Ar.SwitchStartEventError=void 0;var t=e(Ue),n=nn(),r=xe,i=Ge(),o=Qu(),a=Zu(),c=Gf(),f=Pt();const v=new Error("Verification timed out");class s extends Error{constructor(m){super(),this.startEvent=m}}Ar.SwitchStartEventError=s;let g;Ar.VerificationEvent=g,function(S){S.Cancel="cancel"}(g||(Ar.VerificationEvent=g={}));class y extends f.TypedEventEmitter{constructor(m,p,_,u,l,d){super(),this.channel=m,this.baseApis=p,this.userId=_,this.deviceId=u,this.startEvent=l,this.request=d,(0,t.default)(this,"cancelled",!1),(0,t.default)(this,"_done",!1),(0,t.default)(this,"promise",null),(0,t.default)(this,"transactionTimeoutTimer",null),(0,t.default)(this,"expectedEvent",void 0),(0,t.default)(this,"resolve",void 0),(0,t.default)(this,"reject",void 0),(0,t.default)(this,"resolveEvent",void 0),(0,t.default)(this,"rejectEvent",void 0),(0,t.default)(this,"started",void 0),(0,t.default)(this,"doVerification",void 0)}get initiatedByMe(){if(!this.startEvent)return!0;const m=this.startEvent.getSender(),p=this.startEvent.getContent();return m===this.baseApis.getUserId()&&p.from_device===this.baseApis.getDeviceId()}get hasBeenCancelled(){return this.cancelled}resetTimer(){i.logger.info("Refreshing/starting the verification transaction timeout timer"),this.transactionTimeoutTimer!==null&&clearTimeout(this.transactionTimeoutTimer),this.transactionTimeoutTimer=setTimeout(()=>{!this._done&&!this.cancelled&&(i.logger.info("Triggering verification timeout"),this.cancel(v))},10*60*1e3)}endTimer(){this.transactionTimeoutTimer!==null&&(clearTimeout(this.transactionTimeoutTimer),this.transactionTimeoutTimer=null)}send(m,p){return this.channel.send(m,p)}waitForEvent(m){if(this._done)return Promise.reject(new Error("Verification is already done"));const p=this.request.getEventFromOtherParty(m);return p?Promise.resolve(p):(this.expectedEvent=m,new Promise((_,u)=>{this.resolveEvent=_,this.rejectEvent=u}))}canSwitchStartEvent(m){return!1}switchStartEvent(m){if(this.canSwitchStartEvent(m))if(i.logger.log("Verification Base: switching verification start event",{restartingFlow:!!this.rejectEvent}),this.rejectEvent){const p=this.rejectEvent;this.rejectEvent=void 0,p(new s(m))}else this.startEvent=m}handleEvent(m){if(!this._done){if(m.getType()===this.expectedEvent){if(this.expectedEvent!==r.EventType.KeyVerificationDone){var p;this.expectedEvent=void 0,this.rejectEvent=void 0,this.resetTimer(),(p=this.resolveEvent)===null||p===void 0||p.call(this,m)}}else if(m.getType()===r.EventType.KeyVerificationCancel){const _=this.reject;if(this.reject=void 0,_){const u=m.getContent(),{reason:l,code:d}=u;_(new Error(`Other side cancelled verification because ${l} (${d})`))}}else if(this.expectedEvent){const _=new Error("Unexpected message: expecting "+this.expectedEvent+" but got "+m.getType());if(this.expectedEvent=void 0,this.rejectEvent){const u=this.rejectEvent;this.rejectEvent=void 0,u(_)}this.cancel(_)}}}async done(){if(this.endTimer(),!this._done){var m;return this.request.onVerifierFinished(),(m=this.resolve)===null||m===void 0||m.call(this),(0,c.requestKeysDuringVerification)(this.baseApis,this.userId,this.deviceId)}}cancel(m){if(this.endTimer(),!this._done){if(this.cancelled=!0,this.request.onVerifierCancelled(),this.userId&&this.deviceId)if(m===v){const p=(0,a.newTimeoutError)();this.send(p.getType(),p.getContent())}else if(m instanceof n.MatrixEvent){if(m.getSender()!==this.userId){const _=m.getContent();m.getType()===r.EventType.KeyVerificationCancel?(_.code=_.code||"m.unknown",_.reason=_.reason||_.body||"Unknown reason",this.send(r.EventType.KeyVerificationCancel,_)):this.send(r.EventType.KeyVerificationCancel,{code:"m.unknown",reason:_.body||"Unknown reason"})}}else this.send(r.EventType.KeyVerificationCancel,{code:"m.unknown",reason:m.toString()});this.promise!==null?this.reject&&this.reject(m):this.promise=Promise.reject(m),this.emit(g.Cancel,m)}}verify(){return this.promise?this.promise:(this.promise=new Promise((m,p)=>{this.resolve=(..._)=>{this._done=!0,this.endTimer(),m(..._)},this.reject=_=>{this._done=!0,this.endTimer(),p(_)}}),this.doVerification&&!this.started&&(this.started=!0,this.resetTimer(),new Promise((m,p)=>{var _;((_=this.baseApis.crypto.deviceList.getStoredCrossSigningForUser(this.userId))===null||_===void 0?void 0:_.getId())===this.deviceId&&p(new Error("Device ID is the same as the cross-signing ID")),m()}).then(()=>this.doVerification()).then(this.done.bind(this),this.cancel.bind(this))),this.promise)}async verifyKeys(m,p,_){const u=[];for(const[l,d]of Object.entries(p)){const h=l.split(":",2)[1],w=this.baseApis.getStoredDevice(m,h);if(w)_(l,w,d),u.push([h,l,w.keys[l]]);else{const E=this.baseApis.crypto.deviceList.getStoredCrossSigningForUser(m);E&&E.getId()===h?(_(l,o.DeviceInfo.fromStorage({keys:{[l]:h}},h),d),u.push([h,l,h])):i.logger.warn(`verification: Could not find device ${h} to verify`)}}if(!u.length)throw new Error("No devices could be verified");i.logger.info("Verification completed! Marking devices verified: ",u);for(const[l,d,h]of u)await this.baseApis.crypto.setDeviceVerification(m,l,!0,null,null,{[d]:h});m==this.baseApis.credentials.userId&&await this.baseApis.checkKeyBackup()}get events(){}}return Ar.VerificationBase=y,Ar}var vb;function dk(){if(vb)return _n;vb=1;var e=Ae;Object.defineProperty(_n,"__esModule",{value:!0}),_n.SHOW_QR_CODE_METHOD=_n.SCAN_QR_CODE_METHOD=_n.ReciprocateQRCode=_n.QrCodeEvent=_n.QRCodeData=void 0;var t=e(Ue),n=r_(),r=Zu(),i=ct,o=Ge();const a="m.qr_code.show.v1";_n.SHOW_QR_CODE_METHOD=a;const c="m.qr_code.scan.v1";_n.SCAN_QR_CODE_METHOD=c;let f;_n.QrCodeEvent=f,function(m){m.ShowReciprocateQr="show_reciprocate_qr"}(f||(_n.QrCodeEvent=f={}));class v extends n.VerificationBase{constructor(...p){super(...p),(0,t.default)(this,"reciprocateQREvent",void 0),(0,t.default)(this,"doVerification",async()=>{if(!this.startEvent)throw new Error("It is not currently possible to start verificationwith this method yet.");const{qrCodeData:_}=this.request;if(this.startEvent.getContent().secret!==(_==null?void 0:_.encodedSharedSecret))throw(0,r.newKeyMismatchError)();await new Promise((l,d)=>{this.reciprocateQREvent={confirm:l,cancel:()=>d((0,r.newUserCancelledError)())},this.emit(f.ShowReciprocateQr,this.reciprocateQREvent)});const u={};switch(_==null?void 0:_.mode){case y.VerifyOtherUser:{const l=_.otherUserMasterKey;u[`ed25519:${l}`]=l;break}case y.VerifySelfTrusted:{const l=this.request.targetDevice.deviceId;u[`ed25519:${l}`]=_.otherDeviceKey;break}case y.VerifySelfUntrusted:{const l=_.myMasterKey;u[`ed25519:${l}`]=l;break}}await this.verifyKeys(this.userId,u,(l,d,h)=>{const w=u[l];if(!w)throw(0,r.newKeyMismatchError)();if(h!==w)throw o.logger.error("key ID from key info does not match"),(0,r.newKeyMismatchError)();for(const E in d.keys){if(!E.startsWith("ed25519"))continue;const I=u[E];if(!I)throw(0,r.newKeyMismatchError)();if(d.keys[E]!==I)throw o.logger.error("master key does not match"),(0,r.newKeyMismatchError)()}})})}static factory(p,_,u,l,d,h){return new v(p,_,u,l,d,h)}static get NAME(){return"m.reciprocate.v1"}}_n.ReciprocateQRCode=v;const s=2,g="MATRIX";var y;(function(m){m[m.VerifyOtherUser=0]="VerifyOtherUser",m[m.VerifySelfTrusted=1]="VerifySelfTrusted",m[m.VerifySelfUntrusted=2]="VerifySelfUntrusted"})(y||(y={}));class S{constructor(p,_,u,l,d,h){this.mode=p,this.sharedSecret=_,this.otherUserMasterKey=u,this.otherDeviceKey=l,this.myMasterKey=d,this.buffer=h}static async create(p,_){const u=S.generateSharedSecret(),l=S.determineMode(p,_);let d=null,h=null,w=null;if(l===y.VerifyOtherUser)d=_.getStoredCrossSigningForUser(p.otherUserId).getId("master");else if(l===y.VerifySelfTrusted)h=await S.getOtherDeviceKey(p,_);else if(l===y.VerifySelfUntrusted){const k=_.getUserId();w=_.getStoredCrossSigningForUser(k).getId("master")}const E=S.generateQrData(p,_,l,u,d,h,w),I=S.generateBuffer(E);return new S(l,u,d,h,w,I)}get encodedSharedSecret(){return this.sharedSecret}getBuffer(){return this.buffer}static generateSharedSecret(){const p=new Uint8Array(11);return $e.crypto.getRandomValues(p),(0,i.encodeUnpaddedBase64)(p)}static async getOtherDeviceKey(p,_){const u=_.getUserId(),l=p.targetDevice,d=l.deviceId?_.getStoredDevice(u,l.deviceId):void 0;if(!d)throw new Error("could not find device "+(l==null?void 0:l.deviceId));return d.getFingerprint()}static determineMode(p,_){const u=_.getUserId(),l=p.otherUserId;let d=y.VerifyOtherUser;return u===l&&(_.checkUserTrust(u).isCrossSigningVerified()?d=y.VerifySelfTrusted:d=y.VerifySelfUntrusted),d}static generateQrData(p,_,u,l,d,h,w){const E=_.getUserId(),I=p.channel.transactionId,k={prefix:g,version:s,mode:u,transactionId:I,firstKeyB64:"",secondKeyB64:"",secretB64:l},M=_.getStoredCrossSigningForUser(E);return u===y.VerifyOtherUser?(k.firstKeyB64=M.getId("master"),k.secondKeyB64=d):u===y.VerifySelfTrusted?(k.firstKeyB64=M.getId("master"),k.secondKeyB64=h):u===y.VerifySelfUntrusted&&(k.firstKeyB64=_.getDeviceEd25519Key(),k.secondKeyB64=w),k}static generateBuffer(p){let _=Buffer.alloc(0);const u=w=>{const E=Buffer.from([w]);_=Buffer.concat([_,E])},l=w=>{const E=Buffer.alloc(2);E.writeInt16BE(w,0),_=Buffer.concat([_,E])},d=(w,E,I=!0)=>{const k=Buffer.from(w,E);I&&l(k.byteLength),_=Buffer.concat([_,k])},h=w=>{const E=(0,i.decodeBase64)(w),I=Buffer.from(E);_=Buffer.concat([_,I])};return d(p.prefix,"ascii",!1),u(p.version),u(p.mode),d(p.transactionId,"utf-8"),h(p.firstKeyB64),h(p.secondKeyB64),h(p.secretB64),_}}return _n.QRCodeData=S,_n}var Pi={},$c={},mb;function P3(){if(mb)return $c;mb=1,Object.defineProperty($c,"__esModule",{value:!0}),$c.generateDecimalSas=e;function e(t){return[(t[0]<<5|t[1]>>3)+1e3,((t[1]&7)<<10|t[2]<<2|t[3]>>6)+1e3,((t[3]&63)<<7|t[4]>>1)+1e3]}return $c}var yb;function k3(){if(yb)return Pi;yb=1;var e=Ae;Object.defineProperty(Pi,"__esModule",{value:!0}),Pi.SasEvent=Pi.SAS=void 0;var t=e(Ue),n=e(Hf()),r=r_(),i=Zu(),o=Ge(),a=P3(),c=xe;const f=c.EventType.KeyVerificationStart,v=[c.EventType.KeyVerificationAccept,c.EventType.KeyVerificationKey,c.EventType.KeyVerificationMac];let s;const g=(0,i.errorFactory)("m.mismatched_sas","Mismatched short authentication string"),y=(0,i.errorFactory)("m.mismatched_commitment","Mismatched commitment"),S=[["🐶","dog"],["🐱","cat"],["🦁","lion"],["🐎","horse"],["🦄","unicorn"],["🐷","pig"],["🐘","elephant"],["🐰","rabbit"],["🐼","panda"],["🐓","rooster"],["🐧","penguin"],["🐢","turtle"],["🐟","fish"],["🐙","octopus"],["🦋","butterfly"],["🌷","flower"],["🌳","tree"],["🌵","cactus"],["🍄","mushroom"],["🌏","globe"],["🌙","moon"],["☁️","cloud"],["🔥","fire"],["🍌","banana"],["🍎","apple"],["🍓","strawberry"],["🌽","corn"],["🍕","pizza"],["🎂","cake"],["❤️","heart"],["🙂","smiley"],["🤖","robot"],["🎩","hat"],["👓","glasses"],["🔧","spanner"],["🎅","santa"],["👍","thumbs up"],["☂️","umbrella"],["⌛","hourglass"],["⏰","clock"],["🎁","gift"],["💡","light bulb"],["📕","book"],["✏️","pencil"],["📎","paperclip"],["✂️","scissors"],["🔒","lock"],["🔑","key"],["🔨","hammer"],["☎️","telephone"],["🏁","flag"],["🚂","train"],["🚲","bicycle"],["✈️","aeroplane"],["🚀","rocket"],["🏆","trophy"],["⚽","ball"],["🎸","guitar"],["🎺","trumpet"],["🔔","bell"],["⚓️","anchor"],["🎧","headphones"],["📁","folder"],["📌","pin"]];function m(x){return[x[0]>>2,(x[0]&3)<<4|x[1]>>4,(x[1]&15)<<2|x[2]>>6,x[2]&63,x[3]>>2,(x[3]&3)<<4|x[4]>>4,(x[4]&15)<<2|x[5]>>6].map(W=>S[W])}const p={decimal:a.generateDecimalSas,emoji:m};function _(x,z){const W={};for(const F of z)F in p&&(W[F]=p[F](Array.from(x)));return W}const u={"hkdf-hmac-sha256":"calculate_mac","org.matrix.msc3783.hkdf-hmac-sha256":"calculate_mac_fixed_base64","hmac-sha256":"calculate_mac_long_kdf"};function l(x,z){return function(W,F){const H=x[u[z]](W,F);return o.logger.log("SAS calculateMAC:",z,[W,F],H),H}}const d={"curve25519-hkdf-sha256":function(x,z,W){const F=`${x.baseApis.getUserId()}|${x.baseApis.deviceId}|${x.ourSASPubKey}|`,H=`${x.userId}|${x.deviceId}|${x.theirSASPubKey}|`,R="MATRIX_KEY_VERIFICATION_SAS|"+(x.initiatedByMe?F+H:H+F)+x.channel.transactionId;return z.generate_bytes(R,W)},curve25519:function(x,z,W){const F=`${x.baseApis.getUserId()}${x.baseApis.deviceId}`,H=`${x.userId}${x.deviceId}`,R="MATRIX_KEY_VERIFICATION_SAS"+(x.initiatedByMe?F+H:H+F)+x.channel.transactionId;return z.generate_bytes(R,W)}},h=["curve25519-hkdf-sha256","curve25519"],w=["sha256"],E=["org.matrix.msc3783.hkdf-hmac-sha256","hkdf-hmac-sha256","hmac-sha256"],I=Object.keys(p),k=new Set(h),M=new Set(w),L=new Set(E),B=new Set(I);function N(x,z){return Array.isArray(x)?x.filter(W=>z.has(W)):[]}let G;Pi.SasEvent=G,function(x){x.ShowSas="show_sas"}(G||(Pi.SasEvent=G={}));let D=class extends r.VerificationBase{constructor(...z){super(...z),(0,t.default)(this,"waitingForAccept",void 0),(0,t.default)(this,"ourSASPubKey",void 0),(0,t.default)(this,"theirSASPubKey",void 0),(0,t.default)(this,"sasEvent",void 0),(0,t.default)(this,"doVerification",async()=>{await $e.Olm.init(),s=s||new $e.Olm.Utility,await this.baseApis.downloadKeys([this.userId]);let W=!1;do try{return this.initiatedByMe?await this.doSendVerification():await this.doRespondVerification()}catch(F){if(F instanceof r.SwitchStartEventError)this.startEvent=F.startEvent,W=!0;else throw F}while(W)})}static get NAME(){return"m.sas.v1"}get events(){return v}canSwitchStartEvent(z){if(z.getType()!==f)return!1;const W=z.getContent();return(W==null?void 0:W.method)===D.NAME&&!!this.waitingForAccept}async sendStart(){const z=this.channel.completeContent(f,{method:D.NAME,from_device:this.baseApis.deviceId,key_agreement_protocols:h,hashes:w,message_authentication_codes:E,short_authentication_string:I});return await this.channel.sendCompleted(f,z),z}async verifyAndCheckMAC(z,W,F,H){const R=d[z](this,F,6),P=new Promise((C,A)=>{this.sasEvent={sas:_(R,W),confirm:async()=>{try{await this.sendMAC(F,H),C()}catch(T){A(T)}},cancel:()=>A((0,i.newUserCancelledError)()),mismatch:()=>A(g())},this.emit(G.ShowSas,this.sasEvent)}),[K]=await Promise.all([this.waitForEvent(c.EventType.KeyVerificationMac).then(C=>(this.expectedEvent=c.EventType.KeyVerificationDone,C)),P]),U=K.getContent();await this.checkMAC(F,U,H)}async doSendVerification(){this.waitingForAccept=!0;let z;if(this.startEvent?z=this.channel.completedContentFromEvent(this.startEvent):z=await this.sendStart(),!this.initiatedByMe)throw new r.SwitchStartEventError(this.startEvent);let W;try{W=await this.waitForEvent(c.EventType.KeyVerificationAccept)}finally{this.waitingForAccept=!1}let F=W.getContent();const H=N(F.short_authentication_string,B);if(!(k.has(F.key_agreement_protocol)&&M.has(F.hash)&&L.has(F.message_authentication_code)&&H.length))throw(0,i.newUnknownMethodError)();if(typeof F.commitment!="string")throw(0,i.newInvalidMessageError)();const R=F.key_agreement_protocol,P=F.message_authentication_code,K=F.commitment,U=new $e.Olm.SAS;try{this.ourSASPubKey=U.get_pubkey(),await this.send(c.EventType.KeyVerificationKey,{key:this.ourSASPubKey}),W=await this.waitForEvent(c.EventType.KeyVerificationKey),F=W.getContent();const C=F.key+n.default.stringify(z);if(s.sha256(C)!==K)throw y();this.theirSASPubKey=F.key,U.set_their_key(F.key),await this.verifyAndCheckMAC(R,H,U,P)}finally{U.free()}}async doRespondVerification(){let z=this.channel.completedContentFromEvent(this.startEvent);const W=N(h,new Set(z.key_agreement_protocols))[0],F=N(w,new Set(z.hashes))[0],H=N(E,new Set(z.message_authentication_codes))[0],R=N(z.short_authentication_string,B);if(!(W!==void 0&&F!==void 0&&H!==void 0&&R.length))throw(0,i.newUnknownMethodError)();const P=new $e.Olm.SAS;try{const K=P.get_pubkey()+n.default.stringify(z);await this.send(c.EventType.KeyVerificationAccept,{key_agreement_protocol:W,hash:F,message_authentication_code:H,short_authentication_string:R,commitment:s.sha256(K)}),z=(await this.waitForEvent(c.EventType.KeyVerificationKey)).getContent(),this.theirSASPubKey=z.key,P.set_their_key(z.key),this.ourSASPubKey=P.get_pubkey(),await this.send(c.EventType.KeyVerificationKey,{key:this.ourSASPubKey}),await this.verifyAndCheckMAC(W,R,P,H)}finally{P.free()}}sendMAC(z,W){const F={},H=[],R="MATRIX_KEY_VERIFICATION_MAC"+this.baseApis.getUserId()+this.baseApis.deviceId+this.userId+this.deviceId+this.channel.transactionId,P=`ed25519:${this.baseApis.deviceId}`;F[P]=l(z,W)(this.baseApis.getDeviceEd25519Key(),R+P),H.push(P);const K=this.baseApis.getCrossSigningId();if(K){const C=`ed25519:${K}`;F[C]=l(z,W)(K,R+C),H.push(C)}const U=l(z,W)(H.sort().join(","),R+"KEY_IDS");return this.send(c.EventType.KeyVerificationMac,{mac:F,keys:U})}async checkMAC(z,W,F){const H="MATRIX_KEY_VERIFICATION_MAC"+this.userId+this.deviceId+this.baseApis.getUserId()+this.baseApis.deviceId+this.channel.transactionId;if(W.keys!==l(z,F)(Object.keys(W.mac).sort().join(","),H+"KEY_IDS"))throw(0,i.newKeyMismatchError)();await this.verifyKeys(this.userId,W.mac,(R,P,K)=>{if(K!==l(z,F)(P.keys[R],H+R))throw(0,i.newKeyMismatchError)()})}};return Pi.SAS=D,Pi}var ms={},_b;function i_(){if(_b)return ms;_b=1,Object.defineProperty(ms,"__esModule",{value:!0}),ms.deriveKey=a,ms.keyFromAuthData=i,ms.keyFromPassphrase=o;var e=Yu(),t=n_();const n=5e5,r=256;function i(c,f){if(!$e.Olm)throw new Error("Olm is not available");if(!c.private_key_salt||!c.private_key_iterations)throw new Error("Salt and/or iterations not found: this backup cannot be restored with a passphrase");return a(f,c.private_key_salt,c.private_key_iterations,c.private_key_bits||r)}async function o(c){if(!$e.Olm)throw new Error("Olm is not available");const f=(0,e.randomString)(32);return{key:await a(c,f,n,r),salt:f,iterations:n}}async function a(c,f,v,s=r){if(!t.subtleCrypto||!t.TextEncoder)throw new Error("Password-based backup is not available on this platform");const g=await t.subtleCrypto.importKey("raw",new t.TextEncoder().encode(c),{name:"PBKDF2"},!1,["deriveBits"]),y=await t.subtleCrypto.deriveBits({name:"PBKDF2",salt:new t.TextEncoder().encode(f),iterations:v,hash:"SHA-512"},g,s);return new Uint8Array(y)}return ms}var sl={},Lp,Sb;function M3(){if(Sb)return Lp;Sb=1;function e(t){if(t.length>=255)throw new TypeError("Alphabet too long");for(var n=new Uint8Array(256),r=0;r<n.length;r++)n[r]=255;for(var i=0;i<t.length;i++){var o=t.charAt(i),a=o.charCodeAt(0);if(n[a]!==255)throw new TypeError(o+" is ambiguous");n[a]=i}var c=t.length,f=t.charAt(0),v=Math.log(c)/Math.log(256),s=Math.log(256)/Math.log(c);function g(m){if(m instanceof Uint8Array||(ArrayBuffer.isView(m)?m=new Uint8Array(m.buffer,m.byteOffset,m.byteLength):Array.isArray(m)&&(m=Uint8Array.from(m))),!(m instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(m.length===0)return"";for(var p=0,_=0,u=0,l=m.length;u!==l&&m[u]===0;)u++,p++;for(var d=(l-u)*s+1>>>0,h=new Uint8Array(d);u!==l;){for(var w=m[u],E=0,I=d-1;(w!==0||E<_)&&I!==-1;I--,E++)w+=256*h[I]>>>0,h[I]=w%c>>>0,w=w/c>>>0;if(w!==0)throw new Error("Non-zero carry");_=E,u++}for(var k=d-_;k!==d&&h[k]===0;)k++;for(var M=f.repeat(p);k<d;++k)M+=t.charAt(h[k]);return M}function y(m){if(typeof m!="string")throw new TypeError("Expected String");if(m.length===0)return new Uint8Array;for(var p=0,_=0,u=0;m[p]===f;)_++,p++;for(var l=(m.length-p)*v+1>>>0,d=new Uint8Array(l);m[p];){var h=n[m.charCodeAt(p)];if(h===255)return;for(var w=0,E=l-1;(h!==0||w<u)&&E!==-1;E--,w++)h+=c*d[E]>>>0,d[E]=h%256>>>0,h=h/256>>>0;if(h!==0)throw new Error("Non-zero carry");u=w,p++}for(var I=l-u;I!==l&&d[I]===0;)I++;for(var k=new Uint8Array(_+(l-I)),M=_;I!==l;)k[M++]=d[I++];return k}function S(m){var p=y(m);if(p)return p;throw new Error("Non-base"+c+" character")}return{encode:g,decodeUnsafe:y,decode:S}}return Lp=e,Lp}var Np,Eb;function D3(){return Eb||(Eb=1,Np=M3()("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")),Np}var wb;function o_(){if(wb)return sl;wb=1,Object.defineProperty(sl,"__esModule",{value:!0}),sl.decodeRecoveryKey=o,sl.encodeRecoveryKey=i;var e=n(D3());function t(a){if(typeof WeakMap!="function")return null;var c=new WeakMap,f=new WeakMap;return(t=function(v){return v?f:c})(a)}function n(a,c){if(!c&&a&&a.__esModule)return a;if(a===null||typeof a!="object"&&typeof a!="function")return{default:a};var f=t(c);if(f&&f.has(a))return f.get(a);var v={},s=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var g in a)if(g!=="default"&&Object.prototype.hasOwnProperty.call(a,g)){var y=s?Object.getOwnPropertyDescriptor(a,g):null;y&&(y.get||y.set)?Object.defineProperty(v,g,y):v[g]=a[g]}return v.default=a,f&&f.set(a,v),v}const r=[139,1];function i(a){var c;const f=Buffer.alloc(r.length+a.length+1);f.set(r,0),f.set(a,r.length);let v=0;for(let g=0;g<f.length-1;++g)v^=f[g];return f[f.length-1]=v,(c=e.encode(f).match(/.{1,4}/g))===null||c===void 0?void 0:c.join(" ")}function o(a){const c=e.decode(a.replace(/ /g,""));let f=0;for(const v of c)f^=v;if(f!==0)throw new Error("Incorrect parity");for(let v=0;v<r.length;++v)if(c[v]!==r[v])throw new Error("Incorrect prefix");if(c.length!==r.length+$e.Olm.PRIVATE_KEY_LENGTH+1)throw new Error("Incorrect length");return Uint8Array.from(c.slice(r.length,r.length+$e.Olm.PRIVATE_KEY_LENGTH))}return sl}var nt={},bb;function s_(){if(bb)return nt;bb=1;var e=Ae;Object.defineProperty(nt,"__esModule",{value:!0}),nt.VerificationRequestEvent=nt.VerificationRequest=nt.START_TYPE=nt.REQUEST_TYPE=nt.READY_TYPE=nt.Phase=nt.PHASE_UNSENT=nt.PHASE_STARTED=nt.PHASE_REQUESTED=nt.PHASE_READY=nt.PHASE_DONE=nt.PHASE_CANCELLED=nt.EVENT_PREFIX=nt.DONE_TYPE=nt.CANCEL_TYPE=void 0;var t=e(Ue),n=Ge(),r=Zu(),i=dk(),o=xe,a=Pt();const c=10*60*1e3,f=2*60*1e3,v=3*1e3,s="m.key.verification.";nt.EVENT_PREFIX=s;const g=s+"request";nt.REQUEST_TYPE=g;const y=s+"start";nt.START_TYPE=y;const S=s+"cancel";nt.CANCEL_TYPE=S;const m=s+"done";nt.DONE_TYPE=m;const p=s+"ready";nt.READY_TYPE=p;let _;nt.Phase=_,function(M){M[M.Unsent=1]="Unsent",M[M.Requested=2]="Requested",M[M.Ready=3]="Ready",M[M.Started=4]="Started",M[M.Cancelled=5]="Cancelled",M[M.Done=6]="Done"}(_||(nt.Phase=_={}));const u=_.Unsent;nt.PHASE_UNSENT=u;const l=_.Requested;nt.PHASE_REQUESTED=l;const d=_.Ready;nt.PHASE_READY=d;const h=_.Started;nt.PHASE_STARTED=h;const w=_.Cancelled;nt.PHASE_CANCELLED=w;const E=_.Done;nt.PHASE_DONE=E;let I;nt.VerificationRequestEvent=I,function(M){M.Change="change"}(I||(nt.VerificationRequestEvent=I={}));let k=class extends a.TypedEventEmitter{constructor(L,B,N){super(),this.channel=L,this.verificationMethods=B,this.client=N,(0,t.default)(this,"eventsByUs",new Map),(0,t.default)(this,"eventsByThem",new Map),(0,t.default)(this,"_observeOnly",!1),(0,t.default)(this,"timeoutTimer",null),(0,t.default)(this,"_accepting",!1),(0,t.default)(this,"_declining",!1),(0,t.default)(this,"verifierHasFinished",!1),(0,t.default)(this,"_cancelled",!1),(0,t.default)(this,"_chosenMethod",null),(0,t.default)(this,"_qrCodeData",null),(0,t.default)(this,"requestReceivedAt",null),(0,t.default)(this,"commonMethods",[]),(0,t.default)(this,"_phase",void 0),(0,t.default)(this,"_cancellingUserId",void 0),(0,t.default)(this,"_verifier",void 0),(0,t.default)(this,"cancelOnTimeout",async()=>{try{this.initiatedByMe?await this.cancel({reason:"Other party didn't accept in time",code:"m.timeout"}):await this.cancel({reason:"User didn't accept in time",code:"m.timeout"})}catch(G){n.logger.error("Error while cancelling verification request",G)}}),this.channel.request=this,this.setPhase(u,!1)}static validateEvent(L,B,N){const G=B.getContent();return!L||!L.startsWith(s)?!1:G?(L===g||L===p)&&!Array.isArray(G.methods)?(n.logger.log("VerificationRequest: validateEvent: fail because methods"),!1):(L===g||L===p||L===y)&&(typeof G.from_device!="string"||G.from_device.length===0)?(n.logger.log("VerificationRequest: validateEvent: fail because from_device"),!1):!0:(n.logger.log("VerificationRequest: validateEvent: no content"),!1)}get invalid(){return this.phase===u}get requested(){return this.phase===l}get cancelled(){return this.phase===w}get ready(){return this.phase===d}get started(){return this.phase===h}get done(){return this.phase===E}get methods(){return this.commonMethods}get chosenMethod(){return this._chosenMethod}calculateEventTimeout(L){let B=this.channel.getTimestamp(L)+c;if(this.requestReceivedAt&&!this.initiatedByMe&&this.phase<=l){const N=this.requestReceivedAt+f;B=Math.min(B,N)}return Math.max(0,B-Date.now())}get timeout(){const L=this.getEventByEither(g);return L?this.calculateEventTimeout(L):0}get requestEvent(){return this.getEventByEither(g)}get phase(){return this._phase}get verifier(){return this._verifier}get canAccept(){return this.phase<d&&!this._accepting&&!this._declining}get accepting(){return this._accepting}get declining(){return this._declining}get pending(){return!this.observeOnly&&this._phase!==E&&this._phase!==w}get qrCodeData(){return this._qrCodeData}otherPartySupportsMethod(L,B=!1){if(!B&&!this.ready&&!this.started)return!1;const N=this.eventsByThem.get(g)||this.eventsByThem.get(p);if(!N){if(this.started&&this.initiatedByMe){const x=this.eventsByUs.get(y),z=x&&x.getContent(),W=z&&z.method;return L==W}return!1}const G=N.getContent();if(!G)return!1;const{methods:D}=G;return Array.isArray(D)?D.includes(L):!1}get initiatedByMe(){const L=this.eventsByUs.size+this.eventsByThem.size===0;if(this._phase===u&&L)return!0;const B=this.eventsByUs.has(g),N=this.eventsByThem.has(g);if(B&&!N)return!0;if(!B&&N)return!1;const G=this.eventsByUs.has(y),D=this.eventsByThem.has(y);return!!(G&&!D)}get requestingUserId(){return this.initiatedByMe?this.client.getUserId():this.otherUserId}get receivingUserId(){return this.initiatedByMe?this.otherUserId:this.client.getUserId()}get otherUserId(){return this.channel.userId}get isSelfVerification(){return this.client.getUserId()===this.otherUserId}get cancellingUserId(){const L=this.eventsByUs.get(S),B=this.eventsByThem.get(S);if(L&&(!B||L.getId()<B.getId()))return L.getSender();if(B)return B.getSender()}get cancellationCode(){const L=this.getEventByEither(S);return L?L.getContent().code:null}get observeOnly(){return this._observeOnly}get targetDevice(){const L=this.eventsByThem.get(g)||this.eventsByThem.get(p)||this.eventsByThem.get(y),B=L==null?void 0:L.getContent(),N=B==null?void 0:B.from_device;return{userId:this.otherUserId,deviceId:N}}beginKeyVerification(L,B=null){if(!this.observeOnly&&!this._verifier&&(this.phase===l||this.phase===d||this.phase===u&&this.channel.canCreateRequest(y))){if(this.commonMethods.length&&!this.commonMethods.includes(L)||(this._verifier=this.createVerifier(L,null,B),!this._verifier))throw(0,r.newUnknownMethodError)();this._chosenMethod=L}return this._verifier}async sendRequest(){if(!this.observeOnly&&this._phase===u){const L=[...this.verificationMethods.keys()];await this.channel.send(g,{methods:L})}}async cancel({reason:L="User declined",code:B="m.user"}={}){if(!this.observeOnly&&this._phase!==w){if(this._declining=!0,this.emit(I.Change),this._verifier)return this._verifier.cancel((0,r.errorFactory)(B,L)());this._cancellingUserId=this.client.getUserId(),await this.channel.send(S,{code:B,reason:L})}}async accept(){if(!this.observeOnly&&this.phase===l&&!this.initiatedByMe){const L=[...this.verificationMethods.keys()];this._accepting=!0,this.emit(I.Change),await this.channel.send(p,{methods:L})}}waitFor(L){return new Promise((B,N)=>{const G=()=>{let D=!1;return L(this)?(B(this),D=!0):this.cancelled&&(N(new Error("cancelled")),D=!0),D&&this.off(I.Change,G),D};G()||this.on(I.Change,G)})}setPhase(L,B=!0){this._phase=L,B&&this.emit(I.Change)}getEventByEither(L){return this.eventsByThem.get(L)||this.eventsByUs.get(L)}getEventBy(L,B=!1){return B?this.eventsByThem.get(L):this.eventsByUs.get(L)}calculatePhaseTransitions(){const L=[{phase:u}],B=()=>L[L.length-1].phase,N=this.eventsByThem.has(g),G=this.getEventBy(g,N);G&&L.push({phase:l,event:G});const D=G&&this.getEventBy(p,!N);D&&B()===l&&L.push({phase:d,event:D});let x;if(D||!G){const F=this.eventsByThem.get(y),H=this.eventsByUs.get(y);F&&H?x=F.getSender()<H.getSender()?F:H:x=F||H}else x=this.getEventBy(y,!N);if(x){const F=B()===l&&(G==null?void 0:G.getSender())!==x.getSender(),H=B()===u&&this.channel.canCreateRequest(y);(F||B()===d||H)&&L.push({phase:h,event:x})}const z=this.eventsByUs.get(m);(this.verifierHasFinished||z&&B()===h)&&L.push({phase:E});const W=this.getEventByEither(S);return(this._cancelled||W)&&B()!==E&&L.push({phase:w,event:W}),L}transitionToPhase(L){const{phase:B,event:N}=L;if((B===l||B===d)&&!this.wasSentByOwnDevice(N)){const G=N.getContent();this.commonMethods=G.methods.filter(D=>this.verificationMethods.has(D))}if(this.observeOnly||(B===l||B===h||B===d)&&this.channel.receiveStartFromOtherDevices&&this.wasSentByOwnUser(N)&&!this.wasSentByOwnDevice(N)&&(this._observeOnly=!0),B===h){const{method:G}=N.getContent();!this._verifier&&!this.observeOnly&&(this._verifier=this.createVerifier(G,N),this._verifier?this._chosenMethod=G:this.cancel({code:"m.unknown_method",reason:`Unknown method: ${G}`}))}}applyPhaseTransitions(){const L=this.calculatePhaseTransitions(),B=L.findIndex(G=>G.phase===this.phase),N=L.slice(B+1);for(const G of N)this.transitionToPhase(G);return N}isWinningStartRace(L){if(L.getType()!==y)return!1;const B=this._verifier.startEvent;let N;if(this.isSelfVerification)if(B){const D=B.getContent();N=D&&D.from_device}else N=this.client.getDeviceId();else B?N=B.getSender():N=this.client.getUserId();let G;if(this.isSelfVerification){const D=L.getContent();G=D&&D.from_device}else G=L.getSender();return G<N}hasEventId(L){for(const B of this.eventsByUs.values())if(B.getId()===L)return!0;for(const B of this.eventsByThem.values())if(B.getId()===L)return!0;return!1}async handleEvent(L,B,N,G,D){if(this.done||this.cancelled)return;const x=this._observeOnly;if(this.adjustObserveOnly(B,N),!this.observeOnly&&!G&&await this.cancelOnError(L,B)||(D?this.eventsByUs.has(L):this.eventsByThem.has(L)))return;const W=this.phase;this.addEvent(L,B,D);const F=this.applyPhaseTransitions();try{if(this._verifier&&!this.observeOnly){const R=this.isWinningStartRace(B);if(this._verifier.canSwitchStartEvent(B)&&R)this._verifier.switchStartEvent(B);else if(!G){var H;(L===S||(H=this._verifier.events)!==null&&H!==void 0&&H.includes(L))&&this._verifier.handleEvent(B)}}if(F.length){N&&F.some(K=>K.phase===d)&&this.otherPartySupportsMethod(i.SCAN_QR_CODE_METHOD,!0)&&(this._qrCodeData=await i.QRCodeData.create(this,this.client));const R=F[F.length-1],{phase:P}=R;this.setupTimeout(P),this.setPhase(P)}else this._observeOnly!==x&&this.emit(I.Change)}finally{n.logger.log(`Verification request ${this.channel.transactionId}: ${L} event with id:${B.getId()}, content:${JSON.stringify(B.getContent())} deviceId:${this.channel.deviceId}, sender:${B.getSender()}, isSentByUs:${D}, isLiveEvent:${N}, isRemoteEcho:${G}, phase:${W}=>${this.phase}, observeOnly:${x}=>${this._observeOnly}`)}}setupTimeout(L){!this.timeoutTimer&&!this.observeOnly&&L===l&&(this.timeoutTimer=setTimeout(this.cancelOnTimeout,this.timeout)),this.timeoutTimer&&(L===h||L===d||L===E||L===w)&&(clearTimeout(this.timeoutTimer),this.timeoutTimer=null)}async cancelOnError(L,B){if(L===y){const D=B.getContent().method;if(!this.verificationMethods.has(D))return await this.cancel((0,r.errorFromEvent)((0,r.newUnknownMethodError)())),!0}const N=L===g&&this.phase!==u,G=L===p&&this.phase!==l&&this.phase!==h;if(this.phase!==u&&(N||G)){n.logger.warn(`Cancelling, unexpected ${L} verification event from ${B.getSender()}`);const D=`Unexpected ${L} event in phase ${this.phase}`;return await this.cancel((0,r.errorFromEvent)((0,r.newUnexpectedMessageError)({reason:D}))),!0}return!1}adjustObserveOnly(L,B=!1){B||(this._observeOnly=!0),this.calculateEventTimeout(L)<v&&(this._observeOnly=!0)}addEvent(L,B,N=!1){if(N?this.eventsByUs.set(L,B):this.eventsByThem.set(L,B),L===g){for(const[G,D]of this.eventsByThem.entries())D.getSender()!==this.otherUserId&&this.eventsByThem.delete(G);this.requestReceivedAt=Date.now()}}createVerifier(L,B=null,N=null){N||(N=this.targetDevice);const{userId:G,deviceId:D}=N,x=this.verificationMethods.get(L);if(!x){n.logger.warn("could not find verifier constructor for method",L);return}return new x(this.channel,this.client,G,D,B,this)}wasSentByOwnUser(L){return(L==null?void 0:L.getSender())===this.client.getUserId()}wasSentByOwnDevice(L){if(!this.wasSentByOwnUser(L))return!1;const B=L.getContent();return!(!B||B.from_device!==this.client.getDeviceId())}onVerifierCancelled(){this._cancelled=!0;const L=this.applyPhaseTransitions();L.length&&this.setPhase(L[L.length-1].phase)}onVerifierFinished(){this.channel.send(o.EventType.KeyVerificationDone,{}),this.verifierHasFinished=!0;const L=this.applyPhaseTransitions();L.length&&this.setPhase(L[L.length-1].phase)}getEventFromOtherParty(L){return this.eventsByThem.get(L)}};return nt.VerificationRequest=k,nt}var bo={},Tb;function A3(){if(Tb)return bo;Tb=1;var e=Ae;Object.defineProperty(bo,"__esModule",{value:!0}),bo.InRoomRequests=bo.InRoomChannel=void 0;var t=e(Ue),n=s_(),r=Ge(),i=xe;const o=i.EventType.RoomMessage,a="m.reference",c="m.relates_to";let f=class{constructor(g,y,S){this.client=g,this.roomId=y,this.userId=S,(0,t.default)(this,"requestEventId",void 0)}get receiveStartFromOtherDevices(){return!0}get transactionId(){return this.requestEventId}static getOtherPartyUserId(g,y){if(f.getEventType(g)!==n.REQUEST_TYPE)return;const m=y.getUserId(),p=g.getSender(),u=g.getContent().to;if(p===m)return u;if(u===m)return p}getTimestamp(g){return g.getTs()}static canCreateRequest(g){return g===n.REQUEST_TYPE}canCreateRequest(g){return f.canCreateRequest(g)}static getTransactionId(g){if(f.getEventType(g)===n.REQUEST_TYPE)return g.getId();{const y=g.getRelation();if((y==null?void 0:y.rel_type)===a)return y.event_id}}static validateEvent(g,y){const S=f.getTransactionId(g);if(typeof S!="string"||S.length===0)return!1;const m=f.getEventType(g),p=g.getContent();if(m===n.REQUEST_TYPE){if(!p||typeof p.to!="string"||!p.to.length)return r.logger.log("InRoomChannel: validateEvent: no valid to "+(p&&p.to)),!1;if(!f.getOtherPartyUserId(g,y))return r.logger.log(`InRoomChannel: validateEvent: not directed to or sent by me: ${g.getSender()}, ${p&&p.to}`),!1}return n.VerificationRequest.validateEvent(m,g,y)}static getEventType(g){const y=g.getType();if(y===o){const S=g.getContent();if(S){const{msgtype:m}=S;if(m===n.REQUEST_TYPE)return n.REQUEST_TYPE}}return y&&y!==n.REQUEST_TYPE?y:""}async handleEvent(g,y,S=!1){if(y.hasEventId(g.getId()))return;const m=f.getEventType(g);if(g.getRoomId()!==this.roomId)return;if(!this.userId){const d=f.getOtherPartyUserId(g,this.client);d&&(this.userId=d)}const p=this.client.getUserId(),_=g.getSender();if(this.userId&&_!==p&&_!==this.userId){r.logger.log(`InRoomChannel: ignoring verification event from non-participating sender ${_}`);return}this.requestEventId||(this.requestEventId=f.getTransactionId(g));const u=!!g.getUnsigned().transaction_id,l=g.getSender()===this.client.getUserId();return y.handleEvent(m,g,S,u,l)}completedContentFromEvent(g){const y=Object.assign({},g.getContent());return y[c]=g.getRelation(),y}completeContent(g,y){return y=Object.assign({},y),(g===n.REQUEST_TYPE||g===n.READY_TYPE||g===n.START_TYPE)&&(y.from_device=this.client.getDeviceId()),g===n.REQUEST_TYPE?y={body:this.client.getUserId()+" is requesting to verify your key, but your client does not support in-chat key verification.  You will need to use legacy key verification to verify keys.",msgtype:n.REQUEST_TYPE,to:this.userId,from_device:y.from_device,methods:y.methods}:y[c]={rel_type:a,event_id:this.transactionId},y}send(g,y){const S=this.completeContent(g,y);return this.sendCompleted(g,S)}async sendCompleted(g,y){let S=g;g===n.REQUEST_TYPE&&(S=o);const m=await this.client.sendEvent(this.roomId,S,y);g===n.REQUEST_TYPE&&(this.requestEventId=m.event_id)}};bo.InRoomChannel=f;class v{constructor(){(0,t.default)(this,"requestsByRoomId",new Map)}getRequest(g){const y=g.getRoomId(),S=f.getTransactionId(g);return this.getRequestByTxnId(y,S)}getRequestByChannel(g){return this.getRequestByTxnId(g.roomId,g.transactionId)}getRequestByTxnId(g,y){const S=this.requestsByRoomId.get(g);if(S)return S.get(y)}setRequest(g,y){this.doSetRequest(g.getRoomId(),f.getTransactionId(g),y)}setRequestByChannel(g,y){this.doSetRequest(g.roomId,g.transactionId,y)}doSetRequest(g,y,S){let m=this.requestsByRoomId.get(g);m||(m=new Map,this.requestsByRoomId.set(g,m)),m.set(y,S)}removeRequest(g){const y=g.getRoomId(),S=this.requestsByRoomId.get(y);S&&(S.delete(f.getTransactionId(g)),S.size===0&&this.requestsByRoomId.delete(y))}findRequestInProgress(g){const y=this.requestsByRoomId.get(g);if(y){for(const S of y.values())if(S.pending)return S}}}return bo.InRoomRequests=v,bo}var To={},Rb;function L3(){if(Rb)return To;Rb=1;var e=Ae;Object.defineProperty(To,"__esModule",{value:!0}),To.ToDeviceRequests=To.ToDeviceChannel=void 0;var t=e(Ue),n=Yu(),r=Ge(),i=s_(),o=Zu(),a=nn();let c=class{constructor(s,g,y,S,m){this.client=s,this.userId=g,this.devices=y,this.transactionId=S,this.deviceId=m,(0,t.default)(this,"request",void 0)}isToDevices(s){if(s.length===this.devices.length){for(const g of s)if(!this.devices.includes(g))return!1;return!0}else return!1}static getEventType(s){return s.getType()}static getTransactionId(s){const g=s.getContent();return g&&g.transaction_id}static canCreateRequest(s){return s===i.REQUEST_TYPE||s===i.START_TYPE}canCreateRequest(s){return c.canCreateRequest(s)}static validateEvent(s,g){if(s.isCancelled())return r.logger.warn("Ignoring flagged verification request from "+s.getSender()),!1;const y=s.getContent();if(!y)return r.logger.warn("ToDeviceChannel.validateEvent: invalid: no content"),!1;if(!y.transaction_id)return r.logger.warn("ToDeviceChannel.validateEvent: invalid: no transaction_id"),!1;const S=s.getType();if(S===i.REQUEST_TYPE){if(!Number.isFinite(y.timestamp))return r.logger.warn("ToDeviceChannel.validateEvent: invalid: no timestamp"),!1;if(s.getSender()===g.getUserId()&&y.from_device==g.getDeviceId())return r.logger.warn("ToDeviceChannel.validateEvent: invalid: from own device"),!1}return i.VerificationRequest.validateEvent(S,s,g)}getTimestamp(s){const g=s.getContent();return g&&g.timestamp}async handleEvent(s,g,y=!1){const S=s.getType(),m=s.getContent();if(S===i.REQUEST_TYPE||S===i.READY_TYPE||S===i.START_TYPE){this.transactionId||(this.transactionId=m.transaction_id);const l=m.from_device;if(!this.deviceId&&this.devices.includes(l)&&(this.deviceId=l),!this.deviceId||this.deviceId!==l){const d=this.completeContent(i.CANCEL_TYPE,(0,o.errorFromEvent)((0,o.newUnexpectedMessageError)()));return this.sendToDevices(i.CANCEL_TYPE,d,[l])}}const p=g.phase===i.PHASE_STARTED||g.phase===i.PHASE_READY;await g.handleEvent(s.getType(),s,y,!1,!1);const _=g.phase===i.PHASE_STARTED||g.phase===i.PHASE_READY;if((S===i.START_TYPE||S===i.READY_TYPE)&&!p&&_&&this.deviceId){const l=this.devices.filter(d=>d!==this.deviceId&&d!==this.client.getDeviceId());if(l.length){const d=this.completeContent(i.CANCEL_TYPE,{code:"m.accepted",reason:"Verification request accepted by another device"});await this.sendToDevices(i.CANCEL_TYPE,d,l)}}}completedContentFromEvent(s){return s.getContent()}completeContent(s,g){return g=Object.assign({},g),this.transactionId&&(g.transaction_id=this.transactionId),(s===i.REQUEST_TYPE||s===i.READY_TYPE||s===i.START_TYPE)&&(g.from_device=this.client.getDeviceId()),s===i.REQUEST_TYPE&&(g.timestamp=Date.now()),g}send(s,g={}){(s===i.REQUEST_TYPE||s===i.START_TYPE)&&!this.transactionId&&(this.transactionId=c.makeTransactionId());const y=this.completeContent(s,g);return this.sendCompleted(s,y)}async sendCompleted(s,g){let y;s===i.REQUEST_TYPE||s===i.CANCEL_TYPE&&!this.deviceId?y=await this.sendToDevices(s,g,this.devices):y=await this.sendToDevices(s,g,[this.deviceId]);const S=new a.MatrixEvent({sender:this.client.getUserId(),content:g,type:s});return await this.request.handleEvent(s,S,!0,!0,!0),y}async sendToDevices(s,g,y){if(y.length){const S={};for(const m of y)S[m]=g;await this.client.sendToDevice(s,{[this.userId]:S})}}static makeTransactionId(){return(0,n.randomString)(32)}};To.ToDeviceChannel=c;class f{constructor(){(0,t.default)(this,"requestsByUserId",new Map)}getRequest(s){return this.getRequestBySenderAndTxnId(s.getSender(),c.getTransactionId(s))}getRequestByChannel(s){return this.getRequestBySenderAndTxnId(s.userId,s.transactionId)}getRequestBySenderAndTxnId(s,g){const y=this.requestsByUserId.get(s);if(y)return y.get(g)}setRequest(s,g){this.setRequestBySenderAndTxnId(s.getSender(),c.getTransactionId(s),g)}setRequestByChannel(s,g){this.setRequestBySenderAndTxnId(s.userId,s.transactionId,g)}setRequestBySenderAndTxnId(s,g,y){let S=this.requestsByUserId.get(s);S||(S=new Map,this.requestsByUserId.set(s,S)),S.set(g,y)}removeRequest(s){const g=s.getSender(),y=this.requestsByUserId.get(g);y&&(y.delete(c.getTransactionId(s)),y.size===0&&this.requestsByUserId.delete(g))}findRequestInProgress(s,g){const y=this.requestsByUserId.get(s);if(y){for(const S of y.values())if(S.pending&&S.channel.isToDevices(g))return S}}getRequestsInProgress(s){const g=this.requestsByUserId.get(s);return g?Array.from(g.values()).filter(y=>y.pending):[]}}return To.ToDeviceRequests=f,To}var al={},Ib;function N3(){if(Ib)return al;Ib=1;var e=Ae;Object.defineProperty(al,"__esModule",{value:!0}),al.IllegalMethod=void 0;var t=e(Ue),n=r_();let r=class extends n.VerificationBase{constructor(...o){super(...o),(0,t.default)(this,"doVerification",async()=>{throw new Error("Verification is not possible with this method")})}static factory(o,a,c,f,v,s){return new r(o,a,c,f,v,s)}static get NAME(){return"org.matrix.illegal_method"}};return al.IllegalMethod=r,al}var Ro={},Cb;function fk(){if(Cb)return Ro;Cb=1;var e=Ae;Object.defineProperty(Ro,"__esModule",{value:!0}),Ro.DehydrationManager=Ro.DEHYDRATION_ALGORITHM=void 0;var t=e(Ue),n=e(Hf()),r=ct,i=ir,o=Xu(),a=Ge(),c=Rr;const f="org.matrix.msc2697.v1.olm.libolm_pickle";Ro.DEHYDRATION_ALGORITHM=f;const v=7*24*60*60*1e3;class s{constructor(y){this.crypto=y,(0,t.default)(this,"inProgress",!1),(0,t.default)(this,"timeoutId",void 0),(0,t.default)(this,"key",void 0),(0,t.default)(this,"keyInfo",void 0),(0,t.default)(this,"deviceDisplayName",void 0),this.getDehydrationKeyFromCache()}getDehydrationKeyFromCache(){return this.crypto.cryptoStore.doTxn("readonly",[i.IndexedDBCryptoStore.STORE_ACCOUNT],y=>{this.crypto.cryptoStore.getSecretStorePrivateKey(y,async S=>{if(S){const{key:m,keyInfo:p,deviceDisplayName:_,time:u}=S,l=Buffer.from(this.crypto.olmDevice.pickleKey),d=await(0,o.decryptAES)(m,l,f);this.key=(0,r.decodeBase64)(d),this.keyInfo=p,this.deviceDisplayName=_;const h=Date.now(),w=Math.max(1,u+v-h);this.timeoutId=$e.setTimeout(this.dehydrateDevice.bind(this),w)}},"dehydration")})}async setKeyAndQueueDehydration(y,S={},m){await this.setKey(y,S,m)||this.dehydrateDevice()}async setKey(y,S={},m){if(!y){this.timeoutId&&($e.clearTimeout(this.timeoutId),this.timeoutId=void 0),await this.crypto.cryptoStore.doTxn("readwrite",[i.IndexedDBCryptoStore.STORE_ACCOUNT],_=>{this.crypto.cryptoStore.storeSecretStorePrivateKey(_,"dehydration",null)}),this.key=void 0,this.keyInfo=void 0;return}let p=!!this.key&&y.length==this.key.length;for(let _=0;p&&_<y.length;_++)y[_]!=this.key[_]&&(p=!1);return p||(this.key=y,this.keyInfo=S,this.deviceDisplayName=m),p}async dehydrateDevice(){if(this.inProgress){a.logger.log("Dehydration already in progress -- not starting new dehydration");return}this.inProgress=!0,this.timeoutId&&($e.clearTimeout(this.timeoutId),this.timeoutId=void 0);try{const y=Buffer.from(this.crypto.olmDevice.pickleKey),S=await(0,o.encryptAES)((0,r.encodeBase64)(this.key),y,f);await this.crypto.cryptoStore.doTxn("readwrite",[i.IndexedDBCryptoStore.STORE_ACCOUNT],B=>{this.crypto.cryptoStore.storeSecretStorePrivateKey(B,"dehydration",{keyInfo:this.keyInfo,key:S,deviceDisplayName:this.deviceDisplayName,time:Date.now()})}),a.logger.log("Attempting to dehydrate device"),a.logger.log("Creating account");const m=new $e.Olm.Account;m.create();const p=JSON.parse(m.identity_keys()),_=m.max_number_of_one_time_keys();m.generate_one_time_keys(_/2),m.generate_fallback_key();const u=JSON.parse(m.one_time_keys()),l=JSON.parse(m.fallback_key());m.mark_keys_as_published();const d=m.pickle(new Uint8Array(this.key)),h={algorithm:f,account:d};this.keyInfo.passphrase&&(h.passphrase=this.keyInfo.passphrase),a.logger.log("Uploading account to server");const E=(await this.crypto.baseApis.http.authedRequest(c.Method.Put,"/dehydrated_device",void 0,{device_data:h,initial_device_display_name:this.deviceDisplayName},{prefix:"/_matrix/client/unstable/org.matrix.msc2697.v2"})).device_id;a.logger.log("Preparing device keys",E);const I={algorithms:this.crypto.supportedAlgorithms,device_id:E,user_id:this.crypto.userId,keys:{[`ed25519:${E}`]:p.ed25519,[`curve25519:${E}`]:p.curve25519}},k=m.sign(n.default.stringify(I));I.signatures={[this.crypto.userId]:{[`ed25519:${E}`]:k}},this.crypto.crossSigningInfo.getId("self_signing")&&await this.crypto.crossSigningInfo.signObject(I,"self_signing"),a.logger.log("Preparing one-time keys");const M={};for(const[B,N]of Object.entries(u.curve25519)){const G={key:N},D=m.sign(n.default.stringify(G));G.signatures={[this.crypto.userId]:{[`ed25519:${E}`]:D}},M[`signed_curve25519:${B}`]=G}a.logger.log("Preparing fallback keys");const L={};for(const[B,N]of Object.entries(l.curve25519)){const G={key:N,fallback:!0},D=m.sign(n.default.stringify(G));G.signatures={[this.crypto.userId]:{[`ed25519:${E}`]:D}},L[`signed_curve25519:${B}`]=G}return a.logger.log("Uploading keys to server"),await this.crypto.baseApis.http.authedRequest(c.Method.Post,"/keys/upload/"+encodeURI(E),void 0,{device_keys:I,one_time_keys:M,"org.matrix.msc2732.fallback_keys":L}),a.logger.log("Done dehydrating"),this.timeoutId=$e.setTimeout(this.dehydrateDevice.bind(this),v),E}finally{this.inProgress=!1}}stop(){this.timeoutId&&($e.clearTimeout(this.timeoutId),this.timeoutId=void 0)}}return Ro.DehydrationManager=s,Ro}var Pn={},Ob;function hk(){if(Ob)return Pn;Ob=1;var e=Ae;Object.defineProperty(Pn,"__esModule",{value:!0}),Pn.algorithmsByName=Pn.DefaultAlgorithm=Pn.Curve25519=Pn.BackupManager=Pn.Aes256=void 0;var t=e(Ue),n=or(),r=Ge(),i=ct,o=i_(),a=lt(),c=ir,f=o_(),v=Xu(),s=en,g=a_(),y=n_(),S=Rr;const m=200,p=5e3;class _{constructor(k,M){this.baseApis=k,this.getKey=M,(0,t.default)(this,"algorithm",void 0),(0,t.default)(this,"backupInfo",void 0),(0,t.default)(this,"checkedForBackup",void 0),(0,t.default)(this,"sendingBackups",void 0),(0,t.default)(this,"sessionLastCheckAttemptedTime",{}),this.checkedForBackup=!1,this.sendingBackups=!1}get version(){return this.backupInfo&&this.backupInfo.version}static checkBackupVersion(k){const M=w[k.algorithm];if(!M)throw new Error("Unknown backup algorithm: "+k.algorithm);if(typeof k.auth_data!="object")throw new Error("Invalid backup data returned");return M.checkBackupVersion(k)}static makeAlgorithm(k,M){const L=w[k.algorithm];if(!L)throw new Error("Unknown backup algorithm");return L.init(k.auth_data,M)}async enableKeyBackup(k){this.backupInfo=k,this.algorithm&&this.algorithm.free(),this.algorithm=await _.makeAlgorithm(k,this.getKey),this.baseApis.emit(g.CryptoEvent.KeyBackupStatus,!0),this.scheduleKeyBackupSend()}disableKeyBackup(){this.algorithm&&this.algorithm.free(),this.algorithm=void 0,this.backupInfo=void 0,this.baseApis.emit(g.CryptoEvent.KeyBackupStatus,!1)}getKeyBackupEnabled(){return this.checkedForBackup?Boolean(this.algorithm):null}async prepareKeyBackupVersion(k,M){const L=M?w[M]:E;if(!L)throw new Error("Unknown backup algorithm");const[B,N]=await L.prepare(k),G=(0,f.encodeRecoveryKey)(B);return{algorithm:L.algorithmName,auth_data:N,recovery_key:G,privateKey:B}}async createKeyBackupVersion(k){this.algorithm=await _.makeAlgorithm(k,this.getKey)}async checkAndStart(){if(r.logger.log("Checking key backup status..."),this.baseApis.isGuest())return r.logger.log("Skipping key backup check since user is guest"),this.checkedForBackup=!0,null;let k;try{var M;k=(M=await this.baseApis.getKeyBackupVersion())!==null&&M!==void 0?M:void 0}catch(B){return r.logger.log("Error checking for active key backup",B),B.httpStatus===404&&(this.checkedForBackup=!0),null}this.checkedForBackup=!0;const L=await this.isKeyBackupTrusted(k);return L.usable&&!this.backupInfo?(r.logger.log(`Found usable key backup v${k.version}: enabling key backups`),await this.enableKeyBackup(k)):!L.usable&&this.backupInfo?(r.logger.log("No usable key backup: disabling key backup"),this.disableKeyBackup()):!L.usable&&!this.backupInfo?r.logger.log("No usable key backup: not enabling key backup"):L.usable&&this.backupInfo&&(k.version!==this.backupInfo.version?(r.logger.log(`On backup version ${this.backupInfo.version} but found version ${k.version}: switching.`),this.disableKeyBackup(),await this.enableKeyBackup(k),await this.scheduleAllGroupSessionsForBackup()):r.logger.log(`Backup version ${k.version} still current`)),{backupInfo:k,trustInfo:L}}async checkKeyBackup(){return this.checkedForBackup=!1,this.checkAndStart()}async queryKeyBackupRateLimited(k,M){if(!this.backupInfo)return;const L=new Date().getTime();(!this.sessionLastCheckAttemptedTime[M]||L-this.sessionLastCheckAttemptedTime[M]>p)&&(this.sessionLastCheckAttemptedTime[M]=L,await this.baseApis.restoreKeyBackupWithCache(k,M,this.backupInfo,{}))}async isKeyBackupTrusted(k){const M={usable:!1,trusted_locally:!1,sigs:[]};if(!k||!k.algorithm||!k.auth_data||!k.auth_data.signatures)return r.logger.info("Key backup is absent or missing required data"),M;const L=this.baseApis.getUserId(),B=await this.baseApis.crypto.getSessionBackupPrivateKey();if(B){let D=null;try{D=await _.makeAlgorithm(k,async()=>B),await D.keyMatches(B)&&(r.logger.info("Backup is trusted locally"),M.trusted_locally=!0)}catch{}finally{var N;(N=D)===null||N===void 0||N.free()}}const G=k.auth_data.signatures[L]||{};for(const D of Object.keys(G)){const x=D.split(":");if(x[0]!=="ed25519"){r.logger.log("Ignoring unknown signature type: "+x[0]);continue}const z={deviceId:x[1]},W=this.baseApis.crypto.crossSigningInfo.getId();if(W===z.deviceId){z.crossSigningId=!0;try{await(0,i.verifySignature)(this.baseApis.crypto.olmDevice,k.auth_data,L,z.deviceId,W),z.valid=!0}catch(H){r.logger.warn("Bad signature from cross signing key "+W,H),z.valid=!1}M.sigs.push(z);continue}const F=this.baseApis.crypto.deviceList.getStoredDevice(L,z.deviceId);if(F){z.device=F,z.deviceTrust=this.baseApis.checkDeviceTrust(L,z.deviceId);try{await(0,i.verifySignature)(this.baseApis.crypto.olmDevice,k.auth_data,L,F.deviceId,F.getFingerprint()),z.valid=!0}catch(H){r.logger.info("Bad signature from key ID "+D+" userID "+this.baseApis.getUserId()+" device ID "+F.deviceId+" fingerprint: "+F.getFingerprint(),k.auth_data,H),z.valid=!1}}else z.valid=null,r.logger.info("Ignoring signature from unknown key "+D);M.sigs.push(z)}return M.usable=M.sigs.some(D=>{var x;return D.valid&&(D.device&&((x=D.deviceTrust)===null||x===void 0?void 0:x.isVerified())||D.crossSigningId)}),M}async scheduleKeyBackupSend(k=1e4){if(!this.sendingBackups){this.sendingBackups=!0;try{const M=Math.random()*k;await(0,a.sleep)(M);let L=0;for(;;){if(!this.algorithm)return;try{if(await this.backupPendingKeys(m)===0)return;L=0}catch(B){if(L++,r.logger.log("Key backup request failed",B),B.data&&(B.data.errcode=="M_NOT_FOUND"||B.data.errcode=="M_WRONG_ROOM_KEYS_VERSION"))throw await this.checkKeyBackup(),this.baseApis.crypto.emit(g.CryptoEvent.KeyBackupFailed,B.data.errcode),B}L&&await(0,a.sleep)(1e3*Math.pow(2,Math.min(L-1,4)))}}finally{this.sendingBackups=!1}}}async backupPendingKeys(k){const M=await this.baseApis.crypto.cryptoStore.getSessionsNeedingBackup(k);if(!M.length)return 0;let L=await this.baseApis.crypto.cryptoStore.countSessionsNeedingBackup();this.baseApis.crypto.emit(g.CryptoEvent.KeyBackupSessionsRemaining,L);const B={};for(const G of M){var N;const D=G.sessionData.room_id;B[D]===void 0&&(B[D]={sessions:{}});const x=this.baseApis.crypto.olmDevice.exportInboundGroupSession(G.senderKey,G.sessionId,G.sessionData);x.algorithm=i.MEGOLM_ALGORITHM;const z=(x.forwarding_curve25519_key_chain||[]).length,W=this.baseApis.crypto.deviceList.getUserByIdentityKey(i.MEGOLM_ALGORITHM,G.senderKey),F=(N=this.baseApis.crypto.deviceList.getDeviceByIdentityKey(i.MEGOLM_ALGORITHM,G.senderKey))!==null&&N!==void 0?N:void 0,H=this.baseApis.crypto.checkDeviceInfoTrust(W,F).isVerified();B[D].sessions[G.sessionId]={first_message_index:x.first_known_index,forwarded_count:z,is_verified:H,session_data:await this.algorithm.encryptSession(x)}}return await this.baseApis.sendKeyBackup(void 0,void 0,this.backupInfo.version,{rooms:B}),await this.baseApis.crypto.cryptoStore.unmarkSessionsNeedingBackup(M),L=await this.baseApis.crypto.cryptoStore.countSessionsNeedingBackup(),this.baseApis.crypto.emit(g.CryptoEvent.KeyBackupSessionsRemaining,L),M.length}async backupGroupSession(k,M){await this.baseApis.crypto.cryptoStore.markSessionsNeedingBackup([{senderKey:k,sessionId:M}]),this.backupInfo&&this.scheduleKeyBackupSend()}async scheduleAllGroupSessionsForBackup(){await this.flagAllGroupSessionsForBackup(),this.scheduleKeyBackupSend(0)}async flagAllGroupSessionsForBackup(){await this.baseApis.crypto.cryptoStore.doTxn("readwrite",[c.IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS,c.IndexedDBCryptoStore.STORE_BACKUP],M=>{this.baseApis.crypto.cryptoStore.getAllEndToEndInboundGroupSessions(M,L=>{L!==null&&this.baseApis.crypto.cryptoStore.markSessionsNeedingBackup([L],M)})});const k=await this.baseApis.crypto.cryptoStore.countSessionsNeedingBackup();return this.baseApis.emit(g.CryptoEvent.KeyBackupSessionsRemaining,k),k}countSessionsNeedingBackup(){return this.baseApis.crypto.cryptoStore.countSessionsNeedingBackup()}}Pn.BackupManager=_;class u{constructor(k,M,L){this.authData=k,this.publicKey=M,this.getKey=L}static async init(k,M){if(!k||!("public_key"in k))throw new Error("auth_data missing required information");const L=new $e.Olm.PkEncryption;return L.set_recipient_key(k.public_key),new u(k,L,M)}static async prepare(k){const M=new $e.Olm.PkDecryption;try{const L={};if(!k)L.public_key=M.generate_key();else if(k instanceof Uint8Array)L.public_key=M.init_with_private_key(k);else{const N=await(0,o.keyFromPassphrase)(k);L.private_key_salt=N.salt,L.private_key_iterations=N.iterations,L.public_key=M.init_with_private_key(N.key)}return new $e.Olm.PkEncryption().set_recipient_key(L.public_key),[M.get_private_key(),L]}finally{M.free()}}static checkBackupVersion(k){if(!("public_key"in k.auth_data))throw new Error("Invalid backup data returned")}get untrusted(){return!0}async encryptSession(k){const M=Object.assign({},k);return delete M.session_id,delete M.room_id,delete M.first_known_index,this.publicKey.encrypt(JSON.stringify(M))}async decryptSessions(k){const M=await this.getKey(),L=new $e.Olm.PkDecryption;try{if(L.init_with_private_key(M)!==this.authData.public_key)throw new S.MatrixError({errcode:n.MatrixClient.RESTORE_BACKUP_ERROR_BAD_KEY});const N=[];for(const[G,D]of Object.entries(k))try{const x=JSON.parse(L.decrypt(D.session_data.ephemeral,D.session_data.mac,D.session_data.ciphertext));x.session_id=G,N.push(x)}catch(x){r.logger.log("Failed to decrypt megolm session from backup",x,D)}return N}finally{L.free()}}async keyMatches(k){const M=new $e.Olm.PkDecryption;let L;try{L=M.init_with_private_key(k)}finally{M.free()}return L===this.authData.public_key}free(){this.publicKey.free()}}Pn.Curve25519=u,(0,t.default)(u,"algorithmName","m.megolm_backup.v1.curve25519-aes-sha2");function l(I){const k=new Uint8Array(I);return y.crypto.getRandomValues(k),k}const d=new s.UnstableValue("m.megolm_backup.v1.aes-hmac-sha2","org.matrix.msc3270.v1.aes-hmac-sha2");class h{constructor(k,M){this.authData=k,this.key=M}static async init(k,M){if(!k)throw new Error("auth_data missing");const L=await M();if(k.mac){const{mac:B}=await(0,v.calculateKeyCheck)(L,k.iv);if(k.mac.replace(/=+$/g,"")!==B.replace(/=+/g,""))throw new Error("Key does not match")}return new h(k,L)}static async prepare(k){let M;const L={};if(!k)M=l(32);else if(k instanceof Uint8Array)M=new Uint8Array(k);else{const G=await(0,o.keyFromPassphrase)(k);L.private_key_salt=G.salt,L.private_key_iterations=G.iterations,M=G.key}const{iv:B,mac:N}=await(0,v.calculateKeyCheck)(M);return L.iv=B,L.mac=N,[M,L]}static checkBackupVersion(k){if(!("iv"in k.auth_data&&"mac"in k.auth_data))throw new Error("Invalid backup data returned")}get untrusted(){return!1}encryptSession(k){const M=Object.assign({},k);return delete M.session_id,delete M.room_id,delete M.first_known_index,(0,v.encryptAES)(JSON.stringify(M),this.key,k.session_id)}async decryptSessions(k){const M=[];for(const[L,B]of Object.entries(k))try{const N=JSON.parse(await(0,v.decryptAES)(B.session_data,this.key,L));N.session_id=L,M.push(N)}catch(N){r.logger.log("Failed to decrypt megolm session from backup",N,B)}return M}async keyMatches(k){if(this.authData.mac){const{mac:M}=await(0,v.calculateKeyCheck)(k,this.authData.iv);return this.authData.mac.replace(/=+$/g,"")===M.replace(/=+/g,"")}else return!0}free(){this.key.fill(0)}}Pn.Aes256=h,(0,t.default)(h,"algorithmName",d.name);const w={[u.algorithmName]:u,[h.algorithmName]:h};Pn.algorithmsByName=w;const E=u;return Pn.DefaultAlgorithm=E,Pn}var Pb;function a_(){if(Pb)return mn;Pb=1;var e=Ae;Object.defineProperty(mn,"__esModule",{value:!0}),mn.IncomingRoomKeyRequest=mn.CryptoEvent=mn.Crypto=void 0,mn.fixBackupKey=ae,mn.isCryptoAvailable=A,mn.verificationMethods=void 0;var t=e(Ue),n=e(Hf()),r=zu,i=xe,o=rs(),a=Ge(),c=ck(),f=H(ct),v=I3(),s=Qu(),g=H(uk()),y=Gf(),S=C3(),m=O3(),p=ak(),_=ir,u=dk(),l=k3(),d=i_(),h=o_(),w=s_(),E=A3(),I=L3(),k=N3(),M=jt,L=Xu(),B=fk(),N=hk(),G=hi(),D=Zn,x=nn(),z=or(),W=Pt();function F(se){if(typeof WeakMap!="function")return null;var Q=new WeakMap,j=new WeakMap;return(F=function(Z){return Z?j:Q})(se)}function H(se,Q){if(!Q&&se&&se.__esModule)return se;if(se===null||typeof se!="object"&&typeof se!="function")return{default:se};var j=F(Q);if(j&&j.has(se))return j.get(se);var Z={},te=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var re in se)if(re!=="default"&&Object.prototype.hasOwnProperty.call(se,re)){var de=te?Object.getOwnPropertyDescriptor(se,re):null;de&&(de.get||de.set)?Object.defineProperty(Z,re,de):Z[re]=se[re]}return Z.default=se,j&&j.set(se,Z),Z}function R(se,Q){var j=Object.keys(se);if(Object.getOwnPropertySymbols){var Z=Object.getOwnPropertySymbols(se);Q&&(Z=Z.filter(function(te){return Object.getOwnPropertyDescriptor(se,te).enumerable})),j.push.apply(j,Z)}return j}function P(se){for(var Q=1;Q<arguments.length;Q++){var j=arguments[Q]!=null?arguments[Q]:{};Q%2?R(Object(j),!0).forEach(function(Z){(0,t.default)(se,Z,j[Z])}):Object.getOwnPropertyDescriptors?Object.defineProperties(se,Object.getOwnPropertyDescriptors(j)):R(Object(j)).forEach(function(Z){Object.defineProperty(se,Z,Object.getOwnPropertyDescriptor(j,Z))})}return se}const K=s.DeviceInfo.DeviceVerification,U={[u.ReciprocateQRCode.NAME]:u.ReciprocateQRCode,[l.SAS.NAME]:l.SAS,[u.SHOW_QR_CODE_METHOD]:k.IllegalMethod,[u.SCAN_QR_CODE_METHOD]:k.IllegalMethod},C={RECIPROCATE_QR_CODE:u.ReciprocateQRCode.NAME,SAS:l.SAS.NAME};mn.verificationMethods=C;function A(){return Boolean($e.Olm)}const T=60*60*1e3;let X;mn.CryptoEvent=X,function(se){se.DeviceVerificationChanged="deviceVerificationChanged",se.UserTrustStatusChanged="userTrustStatusChanged",se.UserCrossSigningUpdated="userCrossSigningUpdated",se.RoomKeyRequest="crypto.roomKeyRequest",se.RoomKeyRequestCancellation="crypto.roomKeyRequestCancellation",se.KeyBackupStatus="crypto.keyBackupStatus",se.KeyBackupFailed="crypto.keyBackupFailed",se.KeyBackupSessionsRemaining="crypto.keyBackupSessionsRemaining",se.KeySignatureUploadFailure="crypto.keySignatureUploadFailure",se.VerificationRequest="crypto.verification.request",se.Warning="crypto.warning",se.WillUpdateDevices="crypto.willUpdateDevices",se.DevicesUpdated="crypto.devicesUpdated",se.KeysChanged="crossSigning.keysChanged"}(X||(mn.CryptoEvent=X={}));class ne extends W.TypedEventEmitter{static getOlmVersion(){return c.OlmDevice.getOlmVersion()}constructor(Q,j,Z,te,re,de,ge){if(super(),this.baseApis=Q,this.userId=j,this.deviceId=Z,this.clientStore=te,this.cryptoStore=re,this.roomList=de,(0,t.default)(this,"backupManager",void 0),(0,t.default)(this,"crossSigningInfo",void 0),(0,t.default)(this,"olmDevice",void 0),(0,t.default)(this,"deviceList",void 0),(0,t.default)(this,"dehydrationManager",void 0),(0,t.default)(this,"secretStorage",void 0),(0,t.default)(this,"reEmitter",void 0),(0,t.default)(this,"verificationMethods",void 0),(0,t.default)(this,"supportedAlgorithms",void 0),(0,t.default)(this,"outgoingRoomKeyRequestManager",void 0),(0,t.default)(this,"toDeviceVerificationRequests",void 0),(0,t.default)(this,"inRoomVerificationRequests",void 0),(0,t.default)(this,"trustCrossSignedDevices",!0),(0,t.default)(this,"lastOneTimeKeyCheck",null),(0,t.default)(this,"oneTimeKeyCheckInProgress",!1),(0,t.default)(this,"roomEncryptors",new Map),(0,t.default)(this,"roomDecryptors",new Map),(0,t.default)(this,"deviceKeys",{}),(0,t.default)(this,"globalBlacklistUnverifiedDevices",!1),(0,t.default)(this,"globalErrorOnUnknownDevices",!0),(0,t.default)(this,"receivedRoomKeyRequests",[]),(0,t.default)(this,"receivedRoomKeyRequestCancellations",[]),(0,t.default)(this,"processingRoomKeyRequests",!1),(0,t.default)(this,"lazyLoadMembers",!1),(0,t.default)(this,"roomDeviceTrackingState",{}),(0,t.default)(this,"lastNewSessionForced",{}),(0,t.default)(this,"sendKeyRequestsImmediately",!1),(0,t.default)(this,"oneTimeKeyCount",void 0),(0,t.default)(this,"needsNewFallback",void 0),(0,t.default)(this,"fallbackCleanup",void 0),(0,t.default)(this,"onDeviceListUserCrossSigningUpdated",async ye=>{if(ye===this.userId){const ce=this.deviceList.getStoredCrossSigningForUser(ye),le=ce?ce.getId():null,Se=this.crossSigningInfo.getId();Se&&le&&!(Se!==le)?await this.checkOwnCrossSigningTrust():(this.storeTrustedSelfKeys(null),this.emit(X.KeysChanged,{}),this.emit(X.UserTrustStatusChanged,this.userId,this.checkUserTrust(ye)))}else{await this.checkDeviceVerifications(ye);const ce=this.deviceList.getStoredCrossSigningForUser(ye);ce&&(ce.updateCrossSigningVerifiedBefore(this.checkUserTrust(ye).isCrossSigningVerified()),this.deviceList.setRawStoredCrossSigningForUser(ye,ce.toStorage())),this.emit(X.UserTrustStatusChanged,ye,this.checkUserTrust(ye))}}),(0,t.default)(this,"onMembership",(ye,ce,le)=>{try{this.onRoomMembership(ye,ce,le)}catch(Se){a.logger.error("Error handling membership change:",Se)}}),(0,t.default)(this,"onToDeviceEvent",ye=>{try{a.logger.log(`received to-device ${ye.getType()} from: ${ye.getSender()} id: ${ye.getContent()[i.ToDeviceMessageId]}`),ye.getType()=="m.room_key"||ye.getType()=="m.forwarded_room_key"?this.onRoomKeyEvent(ye):ye.getType()=="m.room_key_request"?this.onRoomKeyRequestEvent(ye):ye.getType()==="m.secret.request"?this.secretStorage.onRequestReceived(ye):ye.getType()==="m.secret.send"?this.secretStorage.onSecretReceived(ye):ye.getType()==="m.room_key.withheld"?this.onRoomKeyWithheldEvent(ye):ye.getContent().transaction_id?this.onKeyVerificationMessage(ye):ye.getContent().msgtype==="m.bad.encrypted"?this.onToDeviceBadEncrypted(ye):(ye.isBeingDecrypted()||ye.shouldAttemptDecryption())&&(ye.isBeingDecrypted()||ye.attemptDecryption(this),ye.once(x.MatrixEventEvent.Decrypted,ce=>{this.onToDeviceEvent(ce)}))}catch(ce){a.logger.error("Error handling toDeviceEvent:",ce)}}),(0,t.default)(this,"onTimelineEvent",(ye,ce,le,Se,{liveEvent:Te=!0}={})=>{if(!E.InRoomChannel.validateEvent(ye,this.baseApis))return;const De=je=>{const Le=new E.InRoomChannel(this.baseApis,je.getRoomId());return new w.VerificationRequest(Le,this.verificationMethods,this.baseApis)};this.handleVerificationEvent(ye,this.inRoomVerificationRequests,De,Te)}),this.reEmitter=new o.TypedReEmitter(this),ge){this.verificationMethods=new Map;for(const ye of ge)typeof ye=="string"?U[ye]&&this.verificationMethods.set(ye,U[ye]):ye.NAME?this.verificationMethods.set(ye.NAME,ye):a.logger.warn(`Excluding unknown verification method ${ye}`)}else this.verificationMethods=new Map(Object.entries(U));this.backupManager=new N.BackupManager(Q,async()=>{const ye=await this.getSessionBackupPrivateKey();if(ye)return ye;const ce=await this.getSecret("m.megolm_backup.v1");if(ce){const le=ae(ce);if(le){const Se=await this.getSecretStorageKey();await this.storeSecret("m.megolm_backup.v1",le,[Se[0]])}return f.decodeBase64(le||ce)}if(this.baseApis.cryptoCallbacks&&this.baseApis.cryptoCallbacks.getBackupKey)return this.baseApis.cryptoCallbacks.getBackupKey();throw new Error("Unable to get private key")}),this.olmDevice=new c.OlmDevice(re),this.deviceList=new v.DeviceList(Q,re,this.olmDevice),this.deviceList.on(X.UserCrossSigningUpdated,this.onDeviceListUserCrossSigningUpdated),this.reEmitter.reEmit(this.deviceList,[X.DevicesUpdated,X.WillUpdateDevices]),this.supportedAlgorithms=Array.from(g.DECRYPTION_CLASSES.keys()),this.outgoingRoomKeyRequestManager=new p.OutgoingRoomKeyRequestManager(Q,this.deviceId,this.cryptoStore),this.toDeviceVerificationRequests=new I.ToDeviceRequests,this.inRoomVerificationRequests=new E.InRoomRequests;const fe=this.baseApis.cryptoCallbacks||{},he=(0,y.createCryptoStoreCacheCallbacks)(re,this.olmDevice);this.crossSigningInfo=new y.CrossSigningInfo(j,fe,he),this.secretStorage=new m.SecretStorage(Q,fe,Q),this.dehydrationManager=new B.DehydrationManager(this),!fe.getCrossSigningKey&&fe.getSecretStorageKey&&(fe.getCrossSigningKey=async ye=>y.CrossSigningInfo.getFromSecretStorage(ye,this.secretStorage))}async init({exportedOlmDevice:Q,pickleKey:j}={}){a.logger.log("Crypto: initialising Olm..."),await $e.Olm.init(),a.logger.log(Q?"Crypto: initialising Olm device from exported device...":"Crypto: initialising Olm device..."),await this.olmDevice.init({fromExportedDevice:Q,pickleKey:j}),a.logger.log("Crypto: loading device list..."),await this.deviceList.load(),this.deviceKeys["ed25519:"+this.deviceId]=this.olmDevice.deviceEd25519Key,this.deviceKeys["curve25519:"+this.deviceId]=this.olmDevice.deviceCurve25519Key,a.logger.log("Crypto: fetching own devices...");let Z=this.deviceList.getRawStoredDevicesForUser(this.userId);if(Z||(Z={}),!Z[this.deviceId]){a.logger.log("Crypto: adding this device to the store...");const te={keys:this.deviceKeys,algorithms:this.supportedAlgorithms,verified:K.VERIFIED,known:!0};Z[this.deviceId]=te,this.deviceList.storeDevicesForUser(this.userId,Z),this.deviceList.saveIfDirty()}await this.cryptoStore.doTxn("readonly",[_.IndexedDBCryptoStore.STORE_ACCOUNT],te=>{this.cryptoStore.getCrossSigningKeys(te,re=>{re&&Object.keys(re).length!==0&&(a.logger.log("Loaded cross-signing public keys from crypto store"),this.crossSigningInfo.setKeys(re))})}),this.deviceList.startTrackingDeviceList(this.userId),a.logger.log("Crypto: checking for key backup..."),this.backupManager.checkAndStart()}getCryptoTrustCrossSignedDevices(){return this.trustCrossSignedDevices}setCryptoTrustCrossSignedDevices(Q){this.trustCrossSignedDevices=Q;for(const j of this.deviceList.getKnownUserIds()){const Z=this.deviceList.getRawStoredDevicesForUser(j);for(const te of Object.keys(Z)){const re=this.checkDeviceTrust(j,te);if(!re.isLocallyVerified()&&re.isCrossSigningVerified()){const de=this.deviceList.getStoredDevice(j,te);this.emit(X.DeviceVerificationChanged,j,te,de)}}}}async createRecoveryKeyFromPassphrase(Q){const j=new $e.Olm.PkDecryption;try{const Z={};if(Q){const de=await(0,d.keyFromPassphrase)(Q);Z.passphrase={algorithm:"m.pbkdf2",iterations:de.iterations,salt:de.salt},Z.pubkey=j.init_with_private_key(de.key)}else Z.pubkey=j.generate_key();const te=j.get_private_key(),re=(0,h.encodeRecoveryKey)(te);return{keyInfo:Z,encodedPrivateKey:re,privateKey:te}}finally{j==null||j.free()}}async userHasCrossSigningKeys(){return await this.downloadKeys([this.userId]),this.deviceList.getStoredCrossSigningForUser(this.userId)!==null}async isCrossSigningReady(){const Q=this.crossSigningInfo.getId(),j=await this.crossSigningInfo.isStoredInKeyCache()||await this.crossSigningInfo.isStoredInSecretStorage(this.secretStorage);return!!(Q&&j)}async isSecretStorageReady(){const Q=await this.secretStorage.hasKey(),j=await this.crossSigningInfo.isStoredInSecretStorage(this.secretStorage),Z=!this.backupManager.getKeyBackupEnabled()||await this.baseApis.isKeyBackupKeyStored();return!!(Q&&j&&Z)}async bootstrapCrossSigning({authUploadDeviceSigningKeys:Q,setupNewCrossSigning:j}={}){a.logger.log("Bootstrapping cross-signing");const Z=this.baseApis.cryptoCallbacks,te=new S.EncryptionSetupBuilder(this.baseApis.store.accountData,Z),re=new y.CrossSigningInfo(this.userId,te.crossSigningCallbacks,te.crossSigningCallbacks),de=async()=>{re.resetKeys(),await this.signObject(re.keys.master),te.addCrossSigningKeys(Q,re.keys);const Se=this.deviceList.getStoredDevice(this.userId,this.deviceId),Te=await re.signDevice(this.userId,Se);te.addKeySignature(this.userId,this.deviceId,Te),this.backupManager.backupInfo&&(await re.signObject(this.backupManager.backupInfo.auth_data,"master"),te.addSessionBackup(this.backupManager.backupInfo))},ge=this.crossSigningInfo.getId(),fe=await this.crossSigningInfo.isStoredInKeyCache(),he=await this.crossSigningInfo.isStoredInSecretStorage(this.secretStorage),ye=fe||he;a.logger.log({setupNewCrossSigning:j,publicKeysOnDevice:ge,privateKeysInCache:fe,privateKeysInStorage:he,privateKeysExistSomewhere:ye}),!ye||j?(a.logger.log("Cross-signing private keys not found locally or in secret storage, creating new keys"),await de()):ge&&fe?a.logger.log("Cross-signing public keys trusted and private keys found locally"):he&&(a.logger.log("Cross-signing private keys not found locally, but they are available in secret storage, reading storage and caching locally"),await this.checkOwnCrossSigningTrust({allowPrivateKeyRequests:!0}));const ce=te.crossSigningCallbacks.privateKeys;if(ce.size&&!this.baseApis.cryptoCallbacks.saveCrossSigningKeys){const Se=new m.SecretStorage(te.accountDataClientAdapter,te.ssssCryptoCallbacks,void 0);await Se.hasKey()&&(a.logger.log("Storing new cross-signing private keys in secret storage"),await y.CrossSigningInfo.storeInSecretStorage(ce,Se))}await te.buildOperation().apply(this),await te.persist(this),a.logger.log("Cross-signing ready")}async bootstrapSecretStorage({createSecretStorageKey:Q=async()=>({}),keyBackupInfo:j,setupNewKeyBackup:Z,setupNewSecretStorage:te,getKeyBackupPassphrase:re}={}){a.logger.log("Bootstrapping Secure Secret Storage");const de=this.baseApis.cryptoCallbacks,ge=new S.EncryptionSetupBuilder(this.baseApis.store.accountData,de),fe=new m.SecretStorage(ge.accountDataClientAdapter,ge.ssssCryptoCallbacks,void 0);let he=null;const ye=async(Be,Ne)=>{Ne&&(Be.key=Ne);const{keyId:We,keyInfo:Re}=await fe.addKey(m.SECRET_STORAGE_ALGORITHM_V1_AES,Be);return Ne&&ge.ssssCryptoCallbacks.addPrivateKey(We,Re,Ne),await fe.setDefaultKeyId(We),We},ce=async(Be,Ne)=>{if(!Ne.mac){var We,Re;const b=await((We=(Re=this.baseApis.cryptoCallbacks).getSecretStorageKey)===null||We===void 0?void 0:We.call(Re,{keys:{[Be]:Ne}},""));if(b){const O=b[1];ge.ssssCryptoCallbacks.addPrivateKey(Be,Ne,O);const{iv:$,mac:Y}=await(0,L.calculateKeyCheck)(O);Ne.iv=$,Ne.mac=Y,await ge.setAccountData(`m.secret_storage.key.${Be}`,Ne)}}},le=async Be=>{if(this.crossSigningInfo.getId()&&await this.crossSigningInfo.isStoredInKeyCache("master"))try{a.logger.log("Adding cross-signing signature to key backup"),await this.crossSigningInfo.signObject(Be,"master")}catch(Ne){a.logger.error("Signing key backup with cross-signing keys failed",Ne)}else a.logger.warn("Cross-signing keys not available, skipping signature on key backup")},Se=await this.getSecretStorageKey(),[Te,De]=Se||[null,null],je=!te&&De&&De.algorithm===m.SECRET_STORAGE_ALGORITHM_V1_AES;if(a.logger.log({keyBackupInfo:j,setupNewKeyBackup:Z,setupNewSecretStorage:te,storageExists:je,oldKeyInfo:De}),!je&&!j){a.logger.log("Secret storage does not exist, creating new storage key");const{keyInfo:Be={},privateKey:Ne}=await Q();he=await ye(Be,Ne)}else if(!je&&j){a.logger.log("Secret storage does not exist, using key backup key");const Be=await this.getSessionBackupPrivateKey()||await(re==null?void 0:re()),Ne={};j.auth_data.private_key_salt&&j.auth_data.private_key_iterations&&(Ne.passphrase={algorithm:"m.pbkdf2",iterations:j.auth_data.private_key_iterations,salt:j.auth_data.private_key_salt,bits:256}),he=await ye(Ne,Be),await fe.store("m.megolm_backup.v1",f.encodeBase64(Be),[he]),await le(j.auth_data),ge.addSessionBackup(j)}else a.logger.log("Secret storage exists"),De&&De.algorithm===m.SECRET_STORAGE_ALGORITHM_V1_AES&&await ce(Te,De);if(!this.baseApis.cryptoCallbacks.saveCrossSigningKeys&&await this.isCrossSigningReady()&&(he||!await this.crossSigningInfo.isStoredInSecretStorage(fe))){a.logger.log("Copying cross-signing private keys from cache to secret storage");const Be=await this.crossSigningInfo.getCrossSigningKeysFromCache();await y.CrossSigningInfo.storeInSecretStorage(Be,fe)}if(Z&&!j){a.logger.log("Creating new message key backup version");const Be=await this.baseApis.prepareKeyBackupVersion(null,{secureSecretStorage:!1}),Ne=(0,h.decodeRecoveryKey)(Be.recovery_key);await fe.store("m.megolm_backup.v1",f.encodeBase64(Ne));const We={algorithm:Be.algorithm,auth_data:Be.auth_data};await le(We.auth_data),await this.signObject(We.auth_data),ge.addSessionBackup(We)}const Le=await fe.get("m.megolm_backup.v1");if(Le){a.logger.info("Got session backup key from secret storage: caching");const Be=ae(Le);if(Be){const We=he||Te;await fe.store("m.megolm_backup.v1",Be,We?[We]:null)}const Ne=new Uint8Array(f.decodeBase64(Be||Le));ge.addSessionBackupPrivateKeyToCache(Ne)}else if(this.backupManager.getKeyBackupEnabled()){const Be=await this.getSessionBackupPrivateKey()||await(re==null?void 0:re());if(!Be){a.logger.error("Key backup is enabled but couldn't get key backup key!");return}a.logger.info("Got session backup key from cache/user that wasn't in SSSS: saving to SSSS"),await fe.store("m.megolm_backup.v1",f.encodeBase64(Be))}await ge.buildOperation().apply(this),await ge.persist(this),a.logger.log("Secure Secret Storage ready")}addSecretStorageKey(Q,j,Z){return this.secretStorage.addKey(Q,j,Z)}hasSecretStorageKey(Q){return this.secretStorage.hasKey(Q)}getSecretStorageKey(Q){return this.secretStorage.getKey(Q)}storeSecret(Q,j,Z){return this.secretStorage.store(Q,j,Z)}getSecret(Q){return this.secretStorage.get(Q)}isSecretStored(Q){return this.secretStorage.isStored(Q)}requestSecret(Q,j){return j||(j=Object.keys(this.deviceList.getRawStoredDevicesForUser(this.userId))),this.secretStorage.request(Q,j)}getDefaultSecretStorageKeyId(){return this.secretStorage.getDefaultKeyId()}setDefaultSecretStorageKeyId(Q){return this.secretStorage.setDefaultKeyId(Q)}checkSecretStorageKey(Q,j){return this.secretStorage.checkKey(Q,j)}checkSecretStoragePrivateKey(Q,j){let Z=null;try{return Z=new $e.Olm.PkDecryption,Z.init_with_private_key(Q)===j}finally{var te;(te=Z)===null||te===void 0||te.free()}}async getSessionBackupPrivateKey(){let Q=await new Promise(j=>{this.cryptoStore.doTxn("readonly",[_.IndexedDBCryptoStore.STORE_ACCOUNT],Z=>{this.cryptoStore.getSecretStorePrivateKey(Z,j,"m.megolm_backup.v1")})});if(Q&&typeof Q=="string"&&(Q=new Uint8Array(f.decodeBase64(ae(Q)||Q)),await this.storeSessionBackupPrivateKey(Q)),Q&&Q.ciphertext){const j=Buffer.from(this.olmDevice.pickleKey),Z=await(0,L.decryptAES)(Q,j,"m.megolm_backup.v1");Q=f.decodeBase64(Z)}return Q}async storeSessionBackupPrivateKey(Q){if(!(Q instanceof Uint8Array))throw new Error(`storeSessionBackupPrivateKey expects Uint8Array, got ${Q}`);const j=Buffer.from(this.olmDevice.pickleKey),Z=await(0,L.encryptAES)(f.encodeBase64(Q),j,"m.megolm_backup.v1");return this.cryptoStore.doTxn("readwrite",[_.IndexedDBCryptoStore.STORE_ACCOUNT],te=>{this.cryptoStore.storeSecretStorePrivateKey(te,"m.megolm_backup.v1",Z)})}checkCrossSigningPrivateKey(Q,j){let Z=null;try{return Z=new $e.Olm.PkSigning,Z.init_with_seed(Q)===j}finally{var te;(te=Z)===null||te===void 0||te.free()}}async afterCrossSigningLocalKeyChange(){a.logger.info("Starting cross-signing key change post-processing");const Q=this.deviceList.getStoredDevice(this.userId,this.deviceId),j=await this.crossSigningInfo.signDevice(this.userId,Q);a.logger.info(`Starting background key sig upload for ${this.deviceId}`);const Z=({shouldEmit:re=!1})=>this.baseApis.uploadKeySignatures({[this.userId]:{[this.deviceId]:j}}).then(de=>{const{failures:ge}=de||{};if(Object.keys(ge||[]).length>0)throw re&&this.baseApis.emit(X.KeySignatureUploadFailure,ge,"afterCrossSigningLocalKeyChange",Z),new M.KeySignatureUploadError("Key upload failed",{failures:ge});a.logger.info(`Finished background key sig upload for ${this.deviceId}`)}).catch(de=>{a.logger.error(`Error during background key sig upload for ${this.deviceId}`,de)});Z({shouldEmit:!0});const te=this.baseApis.cryptoCallbacks.shouldUpgradeDeviceVerifications;if(te){a.logger.info("Starting device verification upgrade");const re={};for(const[de,ge]of Object.entries(this.deviceList.crossSigningInfo)){const fe=await this.checkForDeviceVerificationUpgrade(de,y.CrossSigningInfo.fromStorage(ge,de));fe&&(re[de]=fe)}if(Object.keys(re).length>0){a.logger.info(`Found ${Object.keys(re).length} verif users to upgrade`);try{const de=await te({users:re});if(de)for(const ge of de)ge in re&&await this.baseApis.setDeviceVerified(ge,re[ge].crossSigningInfo.getId())}catch(de){a.logger.log("shouldUpgradeDeviceVerifications threw an error: not upgrading",de)}}a.logger.info("Finished device verification upgrade")}a.logger.info("Finished cross-signing key change post-processing")}async checkForDeviceVerificationUpgrade(Q,j){const Z=this.crossSigningInfo.checkUserTrust(j);if(j.firstUse&&!Z.isVerified()){const te=this.deviceList.getRawStoredDevicesForUser(Q),re=await this.checkForValidDeviceSignature(Q,j.keys.master,te);if(re.length)return{devices:re.map(de=>s.DeviceInfo.fromStorage(te[de],de)),crossSigningInfo:j}}}async checkForValidDeviceSignature(Q,j,Z){const te=[];if(Z&&j.signatures&&j.signatures[Q])for(const re of Object.keys(j.signatures[Q])){const[,de]=re.split(":",2);if(de in Z&&Z[de].verified===K.VERIFIED)try{await f.verifySignature(this.olmDevice,j,Q,de,Z[de].keys[re]),te.push(de)}catch{}}return te}getCrossSigningId(Q){return this.crossSigningInfo.getId(Q)}getStoredCrossSigningForUser(Q){return this.deviceList.getStoredCrossSigningForUser(Q)}checkUserTrust(Q){const j=this.deviceList.getStoredCrossSigningForUser(Q);return j?this.crossSigningInfo.checkUserTrust(j):new y.UserTrustLevel(!1,!1,!1)}checkDeviceTrust(Q,j){const Z=this.deviceList.getStoredDevice(Q,j);return this.checkDeviceInfoTrust(Q,Z)}checkDeviceInfoTrust(Q,j){const Z=!!(j!=null&&j.isVerified()),te=this.deviceList.getStoredCrossSigningForUser(Q);if(j&&te){const re=this.trustCrossSignedDevices||Q===this.userId;return this.crossSigningInfo.checkDeviceTrust(te,j,Z,re)}else return new y.DeviceTrustLevel(!1,!1,Z,!1)}checkIfOwnDeviceCrossSigned(Q){var j;const Z=this.deviceList.getStoredDevice(this.userId,Q);if(!Z)return!1;const te=this.deviceList.getStoredCrossSigningForUser(this.userId);return(j=te==null?void 0:te.checkDeviceTrust(te,Z,!1,!0).isCrossSigningVerified())!==null&&j!==void 0?j:!1}async checkOwnCrossSigningTrust({allowPrivateKeyRequests:Q=!1}={}){const j=this.userId;await this.downloadKeys([this.userId]);const Z=await this.crossSigningInfo.getCrossSigningKeysFromCache(),te=this.deviceList.getStoredCrossSigningForUser(j);if(!te){a.logger.error("Got cross-signing update event for user "+j+" but no new cross-signing information found!");return}const re=te.getId(),de=this.crossSigningInfo.getId()!==re,ge=te.getId()&&!Z.has("master");if(de&&a.logger.info("Got new master public key",re),Q&&(de||ge)){a.logger.info("Attempting to retrieve cross-signing master private key");let Be=null;try{Be=(await this.crossSigningInfo.getCrossSigningKey("master",re))[1],a.logger.info("Got cross-signing master private key")}finally{var fe;(fe=Be)===null||fe===void 0||fe.free()}}const he=this.crossSigningInfo.getId("self_signing"),ye=this.crossSigningInfo.getId("user_signing");this.storeTrustedSelfKeys(te.keys);const ce=he!==te.getId("self_signing"),le=ye!==te.getId("user_signing"),Se=te.getId("self_signing")&&!Z.has("self_signing"),Te=te.getId("user_signing")&&!Z.has("user_signing"),De={};if(ce&&a.logger.info("Got new self-signing key",te.getId("self_signing")),Q&&(ce||Se)){a.logger.info("Attempting to retrieve cross-signing self-signing private key");let Be=null;try{Be=(await this.crossSigningInfo.getCrossSigningKey("self_signing",te.getId("self_signing")))[1],a.logger.info("Got cross-signing self-signing private key")}finally{var je;(je=Be)===null||je===void 0||je.free()}const Ne=this.deviceList.getStoredDevice(this.userId,this.deviceId),We=await this.crossSigningInfo.signDevice(this.userId,Ne);De[this.deviceId]=We}if(le&&a.logger.info("Got new user-signing key",te.getId("user_signing")),Q&&(le||Te)){a.logger.info("Attempting to retrieve cross-signing user-signing private key");let Be=null;try{Be=(await this.crossSigningInfo.getCrossSigningKey("user_signing",te.getId("user_signing")))[1],a.logger.info("Got cross-signing user-signing private key")}finally{var Le;(Le=Be)===null||Le===void 0||Le.free()}}if(de){const Be=this.crossSigningInfo.keys.master;await this.signObject(Be);const Ne=Be.signatures[this.userId]["ed25519:"+this.deviceId];De[this.crossSigningInfo.getId()]=Object.assign({},Be,{signatures:{[this.userId]:{["ed25519:"+this.deviceId]:Ne}}})}const Ve=Object.keys(De);if(Ve.length){const Be=({shouldEmit:Ne=!1})=>(a.logger.info(`Starting background key sig upload for ${Ve}`),this.baseApis.uploadKeySignatures({[this.userId]:De}).then(We=>{const{failures:Re}=We||{};if(a.logger.info(`Finished background key sig upload for ${Ve}`),Object.keys(Re||[]).length>0)throw Ne&&this.baseApis.emit(X.KeySignatureUploadFailure,Re,"checkOwnCrossSigningTrust",Be),new M.KeySignatureUploadError("Key upload failed",{failures:Re})}).catch(We=>{a.logger.error(`Error during background key sig upload for ${Ve}`,We)}));Be({shouldEmit:!0})}this.emit(X.UserTrustStatusChanged,j,this.checkUserTrust(j)),de&&(this.emit(X.KeysChanged,{}),await this.afterCrossSigningLocalKeyChange()),await this.backupManager.checkKeyBackup()}async storeTrustedSelfKeys(Q){Q?this.crossSigningInfo.setKeys(Q):this.crossSigningInfo.clearKeys(),await this.cryptoStore.doTxn("readwrite",[_.IndexedDBCryptoStore.STORE_ACCOUNT],j=>{this.cryptoStore.storeCrossSigningKeys(j,this.crossSigningInfo.keys)})}async checkDeviceVerifications(Q){const j=this.baseApis.cryptoCallbacks.shouldUpgradeDeviceVerifications;if(j){if(a.logger.info(`Starting device verification upgrade for ${Q}`),this.crossSigningInfo.keys.user_signing){const Z=this.deviceList.getStoredCrossSigningForUser(Q);if(Z){const te=await this.checkForDeviceVerificationUpgrade(Q,Z);te&&(await j({users:{[Q]:te}})).includes(Q)&&await this.baseApis.setDeviceVerified(Q,Z.getId())}}a.logger.info(`Finished device verification upgrade for ${Q}`)}}enableLazyLoading(){this.lazyLoadMembers=!0}registerEventHandlers(Q){Q.on(D.RoomMemberEvent.Membership,this.onMembership),Q.on(z.ClientEvent.ToDeviceEvent,this.onToDeviceEvent),Q.on(G.RoomEvent.Timeline,this.onTimelineEvent),Q.on(x.MatrixEventEvent.Decrypted,this.onTimelineEvent)}start(){a.logger.warn("MatrixClient.crypto.start() is deprecated")}stop(){this.outgoingRoomKeyRequestManager.stop(),this.deviceList.stop(),this.dehydrationManager.stop()}getDeviceEd25519Key(){return this.olmDevice.deviceEd25519Key}getDeviceCurve25519Key(){return this.olmDevice.deviceCurve25519Key}setGlobalBlacklistUnverifiedDevices(Q){this.globalBlacklistUnverifiedDevices=Q}getGlobalBlacklistUnverifiedDevices(){return this.globalBlacklistUnverifiedDevices}uploadDeviceKeys(){const Q={algorithms:this.supportedAlgorithms,device_id:this.deviceId,keys:this.deviceKeys,user_id:this.userId};return this.signObject(Q).then(()=>this.baseApis.uploadKeysRequest({device_keys:Q}))}updateOneTimeKeyCount(Q){if(isFinite(Q))this.oneTimeKeyCount=Q;else throw new TypeError("Parameter for updateOneTimeKeyCount has to be a number")}setNeedsNewFallback(Q){this.needsNewFallback=Q}getNeedsNewFallback(){return!!this.needsNewFallback}maybeUploadOneTimeKeys(){if(this.oneTimeKeyCheckInProgress)return;const Z=Date.now();if(this.lastOneTimeKeyCheck!==null&&Z-this.lastOneTimeKeyCheck<6e4)return;this.lastOneTimeKeyCheck=Z;const te=this.olmDevice.maxNumberOfOneTimeKeys(),re=Math.floor(te/2),de=async ge=>{for(;re>ge||this.getNeedsNewFallback();){if(re>ge){a.logger.info("generating oneTimeKeys");const he=Math.min(re-ge,5);await this.olmDevice.generateOneTimeKeys(he)}if(this.getNeedsNewFallback()){const he=await this.olmDevice.getFallbackKey();(!he.curve25519||Object.keys(he.curve25519).length==0)&&(a.logger.info("generating fallback key"),this.fallbackCleanup&&(clearTimeout(this.fallbackCleanup),delete this.fallbackCleanup),await this.olmDevice.generateFallbackKey())}a.logger.info("calling uploadOneTimeKeys");const fe=await this.uploadOneTimeKeys();if(fe.one_time_key_counts&&fe.one_time_key_counts.signed_curve25519)ge=fe.one_time_key_counts.signed_curve25519;else throw new Error("response for uploading keys does not contain one_time_key_counts.signed_curve25519")}};this.oneTimeKeyCheckInProgress=!0,Promise.resolve().then(()=>this.oneTimeKeyCount!==void 0?Promise.resolve(this.oneTimeKeyCount):this.baseApis.uploadKeysRequest({}).then(ge=>ge.one_time_key_counts.signed_curve25519||0)).then(ge=>de(ge)).catch(ge=>{a.logger.error("Error uploading one-time keys",ge.stack||ge)}).finally(()=>{this.oneTimeKeyCount=void 0,this.oneTimeKeyCheckInProgress=!1})}async uploadOneTimeKeys(){const Q=[];let j;if(this.getNeedsNewFallback()){j={};const ge=await this.olmDevice.getFallbackKey();for(const[fe,he]of Object.entries(ge.curve25519)){const ye={key:he,fallback:!0};j["signed_curve25519:"+fe]=ye,Q.push(this.signObject(ye))}this.setNeedsNewFallback(!1)}const Z=await this.olmDevice.getOneTimeKeys(),te={};for(const ge in Z.curve25519)if(Z.curve25519.hasOwnProperty(ge)){const fe={key:Z.curve25519[ge]};te["signed_curve25519:"+ge]=fe,Q.push(this.signObject(fe))}await Promise.all(Q);const re={one_time_keys:te};j&&(re["org.matrix.msc2732.fallback_keys"]=j,re.fallback_keys=j);const de=await this.baseApis.uploadKeysRequest(re);return j&&(this.fallbackCleanup=setTimeout(()=>{delete this.fallbackCleanup,this.olmDevice.forgetOldFallbackKey()},60*60*1e3)),await this.olmDevice.markKeysAsPublished(),de}downloadKeys(Q,j){return this.deviceList.downloadKeys(Q,!!j)}getStoredDevicesForUser(Q){return this.deviceList.getStoredDevicesForUser(Q)}getStoredDevice(Q,j){return this.deviceList.getStoredDevice(Q,j)}saveDeviceList(Q){return this.deviceList.saveIfDirty(Q)}async setDeviceVerification(Q,j,Z=null,te=null,re=null,de){const ge=this.deviceList.getStoredCrossSigningForUser(Q);if(ge&&ge.getId()===j){if(te!==null||re!==null)throw new Error("Cannot set blocked or known for a cross-signing key");if(!Z)throw new Error("Cannot set a cross-signing key as unverified");const Se=de?Object.values(de)[0]:null;if(de&&(Object.values(de).length!==1||Se!==ge.getId()))throw new Error(`Key did not match expected value: expected ${ge.getId()}, got ${Se}`);if(!this.crossSigningInfo.getId()&&Q===this.crossSigningInfo.userId&&(this.storeTrustedSelfKeys(ge.keys),this.emit(X.UserTrustStatusChanged,this.userId,this.checkUserTrust(Q))),Q!==this.userId){a.logger.info("Master key "+ge.getId()+" for "+Q+" marked verified. Signing...");const Te=await this.crossSigningInfo.signUser(ge);if(Te){const De=async({shouldEmit:je=!1})=>{a.logger.info("Uploading signature for "+Q+"...");const Le=await this.baseApis.uploadKeySignatures({[Q]:{[j]:Te}}),{failures:Ve}=Le||{};if(Object.keys(Ve||[]).length>0)throw je&&this.baseApis.emit(X.KeySignatureUploadFailure,Ve,"setDeviceVerification",De),new M.KeySignatureUploadError("Key upload failed",{failures:Ve})};await De({shouldEmit:!0})}return Te}else return ge}const fe=this.deviceList.getRawStoredDevicesForUser(Q);if(!fe||!fe[j])throw new Error("Unknown device "+Q+":"+j);const he=fe[j];let ye=he.verified;if(Z){if(de){for(const[Se,Te]of Object.entries(de))if(he.keys[Se]!==Te)throw new Error(`Key did not match expected value: expected ${Te}, got ${he.keys[Se]}`)}ye=K.VERIFIED}else Z!==null&&ye==K.VERIFIED&&(ye=K.UNVERIFIED);te?ye=K.BLOCKED:te!==null&&ye==K.BLOCKED&&(ye=K.UNVERIFIED);let ce=he.known;if(re!==null&&(ce=re),(he.verified!==ye||he.known!==ce)&&(he.verified=ye,he.known=ce,this.deviceList.storeDevicesForUser(Q,fe),this.deviceList.saveIfDirty()),Z&&Q===this.userId){a.logger.info("Own device "+j+" marked verified: signing");let Se;if(this.checkDeviceTrust(Q,j).isCrossSigningVerified()?a.logger.log(`Own device ${j} already cross-signing verified`):Se=await this.crossSigningInfo.signDevice(Q,s.DeviceInfo.fromStorage(he,j)),Se){const De=async({shouldEmit:je=!1})=>{a.logger.info("Uploading signature for "+j);const Le=await this.baseApis.uploadKeySignatures({[Q]:{[j]:Se}}),{failures:Ve}=Le||{};if(Object.keys(Ve||[]).length>0)throw je&&this.baseApis.emit(X.KeySignatureUploadFailure,Ve,"setDeviceVerification",De),new M.KeySignatureUploadError("Key upload failed",{failures:Ve})};await De({shouldEmit:!0})}this.cancelAndResendAllOutgoingKeyRequests()}const le=s.DeviceInfo.fromStorage(he,j);return this.emit(X.DeviceVerificationChanged,Q,j,le),le}findVerificationRequestDMInProgress(Q){return this.inRoomVerificationRequests.findRequestInProgress(Q)}getVerificationRequestsToDeviceInProgress(Q){return this.toDeviceVerificationRequests.getRequestsInProgress(Q)}requestVerificationDM(Q,j){const Z=this.inRoomVerificationRequests.findRequestInProgress(j);if(Z)return Promise.resolve(Z);const te=new E.InRoomChannel(this.baseApis,j,Q);return this.requestVerificationWithChannel(Q,te,this.inRoomVerificationRequests)}requestVerification(Q,j){j||(j=Object.keys(this.deviceList.getRawStoredDevicesForUser(Q)));const Z=this.toDeviceVerificationRequests.findRequestInProgress(Q,j);if(Z)return Promise.resolve(Z);const te=new I.ToDeviceChannel(this.baseApis,Q,j,I.ToDeviceChannel.makeTransactionId());return this.requestVerificationWithChannel(Q,te,this.toDeviceVerificationRequests)}async requestVerificationWithChannel(Q,j,Z){let te=new w.VerificationRequest(j,this.verificationMethods,this.baseApis);j.transactionId&&Z.setRequestByChannel(j,te),await te.sendRequest();const re=Z.getRequestByChannel(j);return re?te=re:(a.logger.log(`Crypto: adding new request to requestsByTxnId with id ${j.transactionId} ${j.roomId}`),Z.setRequestByChannel(j,te)),te}beginKeyVerification(Q,j,Z,te=null){let re;if(te){if(re=this.toDeviceVerificationRequests.getRequestBySenderAndTxnId(j,te),!re)throw new Error(`No request found for user ${j} with transactionId ${te}`)}else{te=I.ToDeviceChannel.makeTransactionId();const de=new I.ToDeviceChannel(this.baseApis,j,[Z],te,Z);re=new w.VerificationRequest(de,this.verificationMethods,this.baseApis),this.toDeviceVerificationRequests.setRequestBySenderAndTxnId(j,te,re)}return re.beginKeyVerification(Q,{userId:j,deviceId:Z})}async legacyDeviceVerification(Q,j,Z){const te=I.ToDeviceChannel.makeTransactionId(),re=new I.ToDeviceChannel(this.baseApis,Q,[j],te,j),de=new w.VerificationRequest(re,this.verificationMethods,this.baseApis);this.toDeviceVerificationRequests.setRequestBySenderAndTxnId(Q,te,de);const ge=de.beginKeyVerification(Z,{userId:Q,deviceId:j});return await Promise.race([ge.verify(),de.waitFor(fe=>fe.started)]),de}async getOlmSessionsForUser(Q){const j=this.getStoredDevicesForUser(Q)||[],Z={};for(const te of j){const re=te.getIdentityKey(),de=await this.olmDevice.getSessionInfoForDevice(re);Z[te.deviceId]={deviceIdKey:re,sessions:de}}return Z}getEventSenderDeviceInfo(Q){const j=Q.getSenderKey(),Z=Q.getWireContent().algorithm;if(!j||!Z||Q.isKeySourceUntrusted())return null;const te=this.deviceList.getDeviceByIdentityKey(Z,j);if(te===null)return null;const re=Q.getClaimedEd25519Key();return re?re!==te.getFingerprint()?(a.logger.warn("Event "+Q.getId()+" claims ed25519 key "+re+" but sender device has key "+te.getFingerprint()),null):te:(a.logger.warn("Event "+Q.getId()+" claims no ed25519 key: cannot verify sending device"),null)}getEventEncryptionInfo(Q){var j,Z;const te={};if(te.senderKey=(j=Q.getSenderKey())!==null&&j!==void 0?j:void 0,te.algorithm=Q.getWireContent().algorithm,!te.senderKey||!te.algorithm)return te.encrypted=!1,te;te.encrypted=!0,Q.isKeySourceUntrusted()?te.authenticated=!1:te.authenticated=!0,te.sender=(Z=this.deviceList.getDeviceByIdentityKey(te.algorithm,te.senderKey))!==null&&Z!==void 0?Z:void 0;const re=Q.getClaimedEd25519Key();return re||(a.logger.warn("Event "+Q.getId()+" claims no ed25519 key: cannot verify sending device"),te.mismatchedSender=!0),te.sender&&re!==te.sender.getFingerprint()&&(a.logger.warn("Event "+Q.getId()+" claims ed25519 key "+re+"but sender device has key "+te.sender.getFingerprint()),te.mismatchedSender=!0),te}forceDiscardSession(Q){const j=this.roomEncryptors.get(Q);if(j===void 0)throw new Error("Room not encrypted");if(j.forceDiscardSession===void 0)throw new Error("Room encryption algorithm doesn't support session discarding");j.forceDiscardSession()}async setRoomEncryption(Q,j,Z){const te=this.clientStore.getRoom(Q);if(!te)throw new Error(`Unable to enable encryption tracking devices in unknown room ${Q}`);await this.setRoomEncryptionImpl(te,j),!this.lazyLoadMembers&&!Z&&this.deviceList.refreshOutdatedDeviceLists()}async setRoomEncryptionImpl(Q,j){const Z=Q.roomId;if(!j.algorithm){a.logger.log("Ignoring setRoomEncryption with no algorithm");return}const te=this.roomList.getRoomEncryption(Z);if(te&&JSON.stringify(te)!=JSON.stringify(j)){a.logger.error("Ignoring m.room.encryption event which requests a change of config in "+Z);return}if(this.roomEncryptors.get(Z))return;let de=null;te||(de=this.roomList.setRoomEncryption(Z,j));const ge=g.ENCRYPTION_CLASSES.get(j.algorithm);if(!ge)throw new Error("Unable to encrypt with "+j.algorithm);const fe=new ge({userId:this.userId,deviceId:this.deviceId,crypto:this,olmDevice:this.olmDevice,baseApis:this.baseApis,roomId:Z,config:j});this.roomEncryptors.set(Z,fe),de&&await de,this.lazyLoadMembers?a.logger.log("Enabling encryption in "+Z):(a.logger.log("Enabling encryption in "+Z+"; starting to track device lists for all users therein"),await this.trackRoomDevicesImpl(Q))}trackRoomDevices(Q){const j=this.clientStore.getRoom(Q);if(!j)throw new Error(`Unable to start tracking devices in unknown room ${Q}`);return this.trackRoomDevicesImpl(j)}trackRoomDevicesImpl(Q){const j=Q.roomId,Z=async()=>{if(!this.roomEncryptors.has(j))return;a.logger.log(`Starting to track devices for room ${j} ...`),(await Q.getEncryptionTargetMembers()).forEach(de=>{this.deviceList.startTrackingDeviceList(de.userId)})};let te=this.roomDeviceTrackingState[j];return te||(te=Z(),this.roomDeviceTrackingState[j]=te.catch(re=>{throw delete this.roomDeviceTrackingState[j],re})),te}ensureOlmSessionsForUsers(Q,j){const Z={};for(const te of Q){Z[te]=[];const re=this.getStoredDevicesForUser(te)||[];for(const de of re)de.getIdentityKey()!=this.olmDevice.deviceCurve25519Key&&de.verified!=K.BLOCKED&&Z[te].push(de)}return f.ensureOlmSessionsForDevices(this.olmDevice,this.baseApis,Z,j)}async exportRoomKeys(){const Q=[];return await this.cryptoStore.doTxn("readonly",[_.IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS],j=>{this.cryptoStore.getAllEndToEndInboundGroupSessions(j,Z=>{if(Z===null)return;const te=this.olmDevice.exportInboundGroupSession(Z.senderKey,Z.sessionId,Z.sessionData);delete te.first_known_index,te.algorithm=f.MEGOLM_ALGORITHM,Q.push(te)})}),Q}importRoomKeys(Q,j={}){let Z=0,te=0;const re=Q.length;function de(){var ge;(ge=j.progressCallback)===null||ge===void 0||ge.call(j,{stage:"load_keys",successes:Z,failures:te,total:re})}return Promise.all(Q.map(ge=>!ge.room_id||!ge.algorithm?(a.logger.warn("ignoring room key entry with missing fields",ge),te++,j.progressCallback&&de(),null):this.getRoomDecryptor(ge.room_id,ge.algorithm).importRoomKey(ge,j).finally(()=>{Z++,j.progressCallback&&de()}))).then()}countSessionsNeedingBackup(){return this.backupManager.countSessionsNeedingBackup()}prepareToEncrypt(Q){const j=this.roomEncryptors.get(Q.roomId);j&&j.prepareToEncrypt(Q)}async encryptEvent(Q,j){if(!j)throw new Error("Cannot send encrypted messages in unknown rooms");const Z=Q.getRoomId(),te=this.roomEncryptors.get(Z);if(!te)throw new Error("Room "+Z+" was previously configured to use encryption, but is no longer. Perhaps the homeserver is hiding the configuration event.");await this.trackRoomDevicesImpl(j);let re=Q.getContent();const de=re["m.relates_to"];de&&(re=Object.assign({},re),delete re["m.relates_to"]);const ge=re["io.element.performance_metrics"];ge&&(re=Object.assign({},re),delete re["io.element.performance_metrics"]);const fe=await te.encryptMessage(j,Q.getType(),re);de&&(fe["m.relates_to"]=de),ge&&(fe["io.element.performance_metrics"]=ge),Q.makeEncrypted("m.room.encrypted",fe,this.olmDevice.deviceCurve25519Key,this.olmDevice.deviceEd25519Key)}async decryptEvent(Q){if(Q.isRedacted()){const j=new x.MatrixEvent(P({room_id:Q.getRoomId()},Q.getUnsigned().redacted_because)),Z=await this.decryptEvent(j);return{clearEvent:{room_id:Q.getRoomId(),type:"m.room.message",content:{},unsigned:{redacted_because:Z.clearEvent}}}}else{const j=Q.getWireContent();return this.getRoomDecryptor(Q.getRoomId(),j.algorithm).decryptEvent(Q)}}async handleDeviceListChanges(Q,j){Q.oldSyncToken&&await this.evalDeviceListChanges(j)}requestRoomKey(Q,j,Z=!1){return this.outgoingRoomKeyRequestManager.queueRoomKeyRequest(Q,j,Z).then(()=>{this.sendKeyRequestsImmediately&&this.outgoingRoomKeyRequestManager.sendQueuedRequests()}).catch(te=>{a.logger.error("Error requesting key for event",te)})}cancelRoomKeyRequest(Q){this.outgoingRoomKeyRequestManager.cancelRoomKeyRequest(Q).catch(j=>{a.logger.warn("Error clearing pending room key requests",j)})}async cancelAndResendAllOutgoingKeyRequests(){await this.outgoingRoomKeyRequestManager.cancelAndResendAllOutgoingRequests()}async onCryptoEvent(Q,j){const Z=j.getContent();await this.setRoomEncryptionImpl(Q,Z)}async onSyncWillProcess(Q){Q.oldSyncToken||(a.logger.log("Initial sync performed - resetting device tracking state"),this.deviceList.stopTrackingAllDeviceLists(),this.deviceList.startTrackingDeviceList(this.userId),this.roomDeviceTrackingState={}),this.sendKeyRequestsImmediately=!1}async onSyncCompleted(Q){var j;this.deviceList.setSyncToken((j=Q.nextSyncToken)!==null&&j!==void 0?j:null),this.deviceList.saveIfDirty(),this.deviceList.startTrackingDeviceList(this.userId),this.deviceList.refreshOutdatedDeviceLists(),Q.catchingUp||(this.maybeUploadOneTimeKeys(),this.processReceivedRoomKeyRequests(),this.outgoingRoomKeyRequestManager.sendQueuedRequests(),this.sendKeyRequestsImmediately=!0)}async evalDeviceListChanges(Q){if(Array.isArray(Q==null?void 0:Q.changed)&&Q.changed.forEach(j=>{this.deviceList.invalidateUserDeviceList(j)}),Array.isArray(Q==null?void 0:Q.left)&&Q.left.length){const j=new Set(await this.getTrackedE2eUsers());Q.left.forEach(Z=>{j.has(Z)||this.deviceList.stopTrackingDeviceList(Z)})}}async getTrackedE2eUsers(){const Q=[];for(const j of this.getTrackedE2eRooms()){const Z=await j.getEncryptionTargetMembers();for(const te of Z)Q.push(te.userId)}return Q}getTrackedE2eRooms(){return this.clientStore.getRooms().filter(Q=>{if(!this.roomEncryptors.get(Q.roomId)||!this.roomDeviceTrackingState[Q.roomId])return!1;const Z=Q.getMyMembership();return Z==="join"||Z==="invite"})}async encryptAndSendToDevices(Q,j){const Z={eventType:i.EventType.RoomMessageEncrypted,batch:[]};try{await Promise.all(Q.map(async({userId:te,deviceInfo:re})=>{const de=re.deviceId,ge={algorithm:f.OLM_ALGORITHM,sender_key:this.olmDevice.deviceCurve25519Key,ciphertext:{},[i.ToDeviceMessageId]:(0,r.v4)()};Z.batch.push({userId:te,deviceId:de,payload:ge}),await f.ensureOlmSessionsForDevices(this.olmDevice,this.baseApis,{[te]:[re]}),await f.encryptMessageForDevice(ge.ciphertext,this.userId,this.deviceId,this.olmDevice,te,re,j)})),Z.batch=Z.batch.filter(te=>Object.keys(te.payload.ciphertext).length>0?!0:(a.logger.log(`No ciphertext for device ${te.userId}:${te.deviceId}: pruning`),!1));try{await this.baseApis.queueToDevice(Z)}catch(te){throw a.logger.error("sendToDevice failed",te),te}}catch(te){throw a.logger.error("encryptAndSendToDevices promises failed",te),te}}onRoomKeyEvent(Q){const j=Q.getContent();if(!j.room_id||!j.algorithm){a.logger.error("key event is missing fields");return}this.backupManager.checkedForBackup||this.backupManager.checkAndStart(),this.getRoomDecryptor(j.room_id,j.algorithm).onRoomKeyEvent(Q)}onRoomKeyWithheldEvent(Q){const j=Q.getContent();if(j.code!=="m.no_olm"&&(!j.room_id||!j.session_id)||!j.algorithm||!j.sender_key){a.logger.error("key withheld event is missing fields");return}a.logger.info(`Got room key withheld event from ${Q.getSender()} for ${j.algorithm} session ${j.sender_key}|${j.session_id} in room ${j.room_id} with code ${j.code} (${j.reason})`);const Z=this.getRoomDecryptor(j.room_id,j.algorithm);if(Z.onRoomKeyWithheldEvent&&Z.onRoomKeyWithheldEvent(Q),!j.room_id){const te=this.getRoomDecryptors(j.algorithm);for(const re of te)re.retryDecryptionFromSender(j.sender_key)}}onKeyVerificationMessage(Q){if(!I.ToDeviceChannel.validateEvent(Q,this.baseApis))return;const j=Z=>{if(!I.ToDeviceChannel.canCreateRequest(I.ToDeviceChannel.getEventType(Z)))return;const te=Z.getContent(),re=te&&te.from_device;if(!re)return;const de=Z.getSender(),ge=new I.ToDeviceChannel(this.baseApis,de,[re]);return new w.VerificationRequest(ge,this.verificationMethods,this.baseApis)};this.handleVerificationEvent(Q,this.toDeviceVerificationRequests,j)}async handleVerificationEvent(Q,j,Z,te=!0){if(Q.isSending()&&Q.status!=x.EventStatus.SENT){let fe,he;try{await new Promise((ye,ce)=>{fe=ye,he=()=>{Q.status==x.EventStatus.CANCELLED&&ce(new Error("Event status set to CANCELLED."))},Q.once(x.MatrixEventEvent.LocalEventIdReplaced,fe),Q.on(x.MatrixEventEvent.Status,he)})}catch(ye){a.logger.error("error while waiting for the verification event to be sent: ",ye);return}finally{Q.removeListener(x.MatrixEventEvent.LocalEventIdReplaced,fe),Q.removeListener(x.MatrixEventEvent.Status,he)}}let re=j.getRequest(Q),de=!1;if(!re){if(re=Z(Q),!re){a.logger.log(`Crypto: could not find VerificationRequest for ${Q.getType()}, and could not create one, so ignoring.`);return}de=!0,j.setRequest(Q,re)}Q.setVerificationRequest(re);try{await re.channel.handleEvent(Q,re,te)}catch(fe){a.logger.error("error while handling verification event",fe)}de&&!re.initiatedByMe&&!re.invalid&&!re.observeOnly&&this.baseApis.emit(X.VerificationRequest,re)}async onToDeviceBadEncrypted(Q){const j=Q.getWireContent(),Z=Q.getSender(),te=j.algorithm,re=j.sender_key,de=()=>{const le=this.getRoomDecryptors(f.MEGOLM_ALGORITHM);for(const Se of le)Se.retryDecryptionFromSender(re)};if(Z===void 0||re===void 0||re===void 0)return;this.lastNewSessionForced[Z]=this.lastNewSessionForced[Z]||{};const ge=this.lastNewSessionForced[Z][re]||0;if(ge+T>Date.now()){a.logger.debug("New session already forced with device "+Z+":"+re+" at "+ge+": not forcing another"),await this.olmDevice.recordSessionProblem(re,"wedged",!0),de();return}let fe=this.deviceList.getDeviceByIdentityKey(te,re);if(!fe&&(await this.downloadKeys([Z],!1),fe=this.deviceList.getDeviceByIdentityKey(te,re),!fe)){a.logger.info("Couldn't find device for identity key "+re+": not re-establishing session"),await this.olmDevice.recordSessionProblem(re,"wedged",!1),de();return}const he={};he[Z]=[fe],await f.ensureOlmSessionsForDevices(this.olmDevice,this.baseApis,he,!0),this.lastNewSessionForced[Z][re]=Date.now();const ye={algorithm:f.OLM_ALGORITHM,sender_key:this.olmDevice.deviceCurve25519Key,ciphertext:{},[i.ToDeviceMessageId]:(0,r.v4)()};await f.encryptMessageForDevice(ye.ciphertext,this.userId,this.deviceId,this.olmDevice,Z,fe,{type:"m.dummy"}),await this.olmDevice.recordSessionProblem(re,"wedged",!0),de(),await this.baseApis.sendToDevice("m.room.encrypted",{[Z]:{[fe.deviceId]:ye}});const ce=await this.outgoingRoomKeyRequestManager.getOutgoingSentRoomKeyRequest(Z,fe.deviceId);for(const le of ce)this.requestRoomKey(le.requestBody,le.recipients,!0)}onRoomMembership(Q,j,Z){const te=j.roomId,re=this.roomEncryptors.get(te);if(re){if(te in this.roomDeviceTrackingState){var de;j.membership=="join"?(a.logger.log("Join event for "+j.userId+" in "+te),this.deviceList.startTrackingDeviceList(j.userId)):j.membership=="invite"&&(de=this.clientStore.getRoom(te))!==null&&de!==void 0&&de.shouldEncryptForInvitedMembers()&&(a.logger.log("Invite event for "+j.userId+" in "+te),this.deviceList.startTrackingDeviceList(j.userId))}re.onRoomMembership(Q,j,Z)}}onRoomKeyRequestEvent(Q){const j=Q.getContent();if(j.action==="request"){const Z=new pe(Q);this.receivedRoomKeyRequests.push(Z)}else if(j.action==="request_cancellation"){const Z=new V(Q);this.receivedRoomKeyRequestCancellations.push(Z)}}async processReceivedRoomKeyRequests(){if(!this.processingRoomKeyRequests){this.processingRoomKeyRequests=!0;try{const Q=this.receivedRoomKeyRequests;this.receivedRoomKeyRequests=[];const j=this.receivedRoomKeyRequestCancellations;this.receivedRoomKeyRequestCancellations=[],await Promise.all(Q.map(Z=>this.processReceivedRoomKeyRequest(Z))),await Promise.all(j.map(Z=>this.processReceivedRoomKeyRequestCancellation(Z)))}catch(Q){a.logger.error(`Error processing room key requsts: ${Q}`)}finally{this.processingRoomKeyRequests=!1}}}async processReceivedRoomKeyRequest(Q){const j=Q.userId,Z=Q.deviceId,te=Q.requestBody,re=te.room_id,de=te.algorithm;if(a.logger.log(`m.room_key_request from ${j}:${Z} for ${re} / ${te.session_id} (id ${Q.requestId})`),j!==this.userId){if(!this.roomEncryptors.get(re)){a.logger.debug(`room key request for unencrypted room ${re}`);return}const fe=this.roomEncryptors.get(re),he=this.deviceList.getStoredDevice(j,Z);if(!he){a.logger.debug(`Ignoring keyshare for unknown device ${j}:${Z}`);return}try{await fe.reshareKeyWithDevice(te.sender_key,te.session_id,j,he)}catch(ye){a.logger.warn("Failed to re-share keys for session "+te.session_id+" with device "+j+":"+he.deviceId,ye)}return}if(Z===this.deviceId){a.logger.log("Ignoring room key request from ourselves");return}if(!this.roomDecryptors.has(re)){a.logger.log(`room key request for unencrypted room ${re}`);return}const ge=this.roomDecryptors.get(re).get(de);if(!ge){a.logger.log(`room key request for unknown alg ${de} in room ${re}`);return}if(!await ge.hasKeysForKeyRequest(Q)){a.logger.log(`room key request for unknown session ${re} / `+te.session_id);return}if(Q.share=()=>{ge.shareKeysWithDevice(Q)},this.checkDeviceTrust(j,Z).isVerified()){a.logger.log("device is already verified: sharing keys"),Q.share();return}this.emit(X.RoomKeyRequest,Q)}async processReceivedRoomKeyRequestCancellation(Q){a.logger.log(`m.room_key_request cancellation for ${Q.userId}:${Q.deviceId} (id ${Q.requestId})`),this.emit(X.RoomKeyRequestCancellation,Q)}getRoomDecryptor(Q,j){let Z,te;if(Q&&(Z=this.roomDecryptors.get(Q),Z||(Z=new Map,this.roomDecryptors.set(Q,Z)),te=Z.get(j),te))return te;const re=g.DECRYPTION_CLASSES.get(j);if(!re)throw new g.DecryptionError("UNKNOWN_ENCRYPTION_ALGORITHM",'Unknown encryption algorithm "'+j+'".');return te=new re({userId:this.userId,crypto:this,olmDevice:this.olmDevice,baseApis:this.baseApis,roomId:Q??void 0}),Z&&Z.set(j,te),te}getRoomDecryptors(Q){const j=[];for(const Z of this.roomDecryptors.values())Z.has(Q)&&j.push(Z.get(Q));return j}async signObject(Q){const j=Q.signatures||{},Z=Q.unsigned;delete Q.signatures,delete Q.unsigned,j[this.userId]=j[this.userId]||{},j[this.userId]["ed25519:"+this.deviceId]=await this.olmDevice.sign(n.default.stringify(Q)),Q.signatures=j,Z!==void 0&&(Q.unsigned=Z)}}mn.Crypto=ne;function ae(se){if(typeof se!="string"||se.indexOf(",")<0)return null;const Q=Uint8Array.from(se.split(","),j=>parseInt(j));return f.encodeBase64(Q)}class pe{constructor(Q){(0,t.default)(this,"userId",void 0),(0,t.default)(this,"deviceId",void 0),(0,t.default)(this,"requestId",void 0),(0,t.default)(this,"requestBody",void 0),(0,t.default)(this,"share",void 0);const j=Q.getContent();this.userId=Q.getSender(),this.deviceId=j.requesting_device_id,this.requestId=j.request_id,this.requestBody=j.body||{},this.share=()=>{throw new Error("don't know how to share keys for this request yet")}}}mn.IncomingRoomKeyRequest=pe;class V{constructor(Q){(0,t.default)(this,"userId",void 0),(0,t.default)(this,"deviceId",void 0),(0,t.default)(this,"requestId",void 0);const j=Q.getContent();this.userId=Q.getSender(),this.deviceId=j.requesting_device_id,this.requestId=j.request_id}}return mn}var ll={},ul={},kb;function x3(){if(kb)return ul;kb=1;var e=Ae;Object.defineProperty(ul,"__esModule",{value:!0}),ul.EventContext=void 0;var t=e(Ue),n=Tr();class r{constructor(o){this.ourEvent=o,(0,t.default)(this,"timeline",void 0),(0,t.default)(this,"ourEventIndex",0),(0,t.default)(this,"paginateTokens",{[n.Direction.Backward]:null,[n.Direction.Forward]:null}),this.timeline=[o]}getEvent(){return this.timeline[this.ourEventIndex]}getTimeline(){return this.timeline}getOurEventIndex(){return this.ourEventIndex}getPaginateToken(o=!1){return this.paginateTokens[o?n.Direction.Backward:n.Direction.Forward]}setPaginateToken(o,a=!1){this.paginateTokens[a?n.Direction.Backward:n.Direction.Forward]=o??null}addEvents(o,a=!1){a?(this.timeline=o.concat(this.timeline),this.ourEventIndex+=o.length):this.timeline=this.timeline.concat(o)}}return ul.EventContext=r,ul}var Mb;function $3(){if(Mb)return ll;Mb=1,Object.defineProperty(ll,"__esModule",{value:!0}),ll.SearchResult=void 0;var e=x3();class t{static fromJson(r,i){const o=r.context||{};let a=(o.events_before||[]).map(i),c=(o.events_after||[]).map(i);const f=new e.EventContext(i(r.result)),v=f.ourEvent.threadRootId;return a=a.filter(s=>s.threadRootId===v),c=c.filter(s=>s.threadRootId===v),f.setPaginateToken(o.start,!0),f.addEvents(a,!0),f.addEvents(c,!1),f.setPaginateToken(o.end,!1),new t(r.rank,f)}constructor(r,i){this.rank=r,this.context=i}}return ll.SearchResult=t,ll}var ys={},Db;function U3(){if(Db)return ys;Db=1,Object.defineProperty(ys,"__esModule",{value:!0}),ys.CrossSigningKey=void 0;let e;return ys.CrossSigningKey=e,function(t){t.Master="master",t.SelfSigning="self_signing",t.UserSigning="user_signing"}(e||(ys.CrossSigningKey=e={})),ys}var yt={};Object.defineProperty(yt,"__esModule",{value:!0});yt.Visibility=yt.RestrictedAllowType=yt.Preset=yt.JoinRule=yt.HistoryVisibility=yt.GuestAccess=void 0;let um;yt.Visibility=um;(function(e){e.Public="public",e.Private="private"})(um||(yt.Visibility=um={}));let cm;yt.Preset=cm;(function(e){e.PrivateChat="private_chat",e.TrustedPrivateChat="trusted_private_chat",e.PublicChat="public_chat"})(cm||(yt.Preset=cm={}));let dm;yt.JoinRule=dm;(function(e){e.Public="public",e.Invite="invite",e.Private="private",e.Knock="knock",e.Restricted="restricted"})(dm||(yt.JoinRule=dm={}));let fm;yt.RestrictedAllowType=fm;(function(e){e.RoomMembership="m.room_membership"})(fm||(yt.RestrictedAllowType=fm={}));let hm;yt.GuestAccess=hm;(function(e){e.CanJoin="can_join",e.Forbidden="forbidden"})(hm||(yt.GuestAccess=hm={}));let pm;yt.HistoryVisibility=pm;(function(e){e.Invited="invited",e.Joined="joined",e.Shared="shared",e.WorldReadable="world_readable"})(pm||(yt.HistoryVisibility=pm={}));var Uc={},Ab;function B3(){if(Ab)return Uc;Ab=1;var e=Ae;Object.defineProperty(Uc,"__esModule",{value:!0}),Uc.eventMapperFor=o;var t=e(Ue),n=nn();function r(a,c){var f=Object.keys(a);if(Object.getOwnPropertySymbols){var v=Object.getOwnPropertySymbols(a);c&&(v=v.filter(function(s){return Object.getOwnPropertyDescriptor(a,s).enumerable})),f.push.apply(f,v)}return f}function i(a){for(var c=1;c<arguments.length;c++){var f=arguments[c]!=null?arguments[c]:{};c%2?r(Object(f),!0).forEach(function(v){(0,t.default)(a,v,f[v])}):Object.getOwnPropertyDescriptors?Object.defineProperties(a,Object.getOwnPropertyDescriptors(f)):r(Object(f)).forEach(function(v){Object.defineProperty(a,v,Object.getOwnPropertyDescriptor(f,v))})}return a}function o(a,c){let f=Boolean(c.preventReEmit);const v=c.decrypt!==!1;function s(g){c.toDevice&&delete g.room_id;const y=a.getRoom(g.room_id);let S;y&&g.state_key===void 0&&(S=y.findEventById(g.event_id)),!S||S.status?S=new n.MatrixEvent(g):(S.setUnsigned(i(i({},S.getUnsigned()),g.unsigned)),f=!0);const m=y==null?void 0:y.findThreadForEvent(S);return m&&S.setThread(m),S.isEncrypted()&&(f||a.reEmitter.reEmit(S,[n.MatrixEventEvent.Decrypted]),v&&a.decryptEventIfNeeded(S)),f||(a.reEmitter.reEmit(S,[n.MatrixEventEvent.Replaced,n.MatrixEventEvent.VisibilityChange]),y==null||y.reEmitter.reEmit(S,[n.MatrixEventEvent.BeforeRedaction])),S}return s}return Uc}var Lr={},cl={},Lb;function F3(){if(Lb)return cl;Lb=1;var e=Ae;Object.defineProperty(cl,"__esModule",{value:!0}),cl.MSC3089Branch=void 0;var t=e(Ue),n=xe,r=Tr();function i(c,f){var v=Object.keys(c);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(c);f&&(s=s.filter(function(g){return Object.getOwnPropertyDescriptor(c,g).enumerable})),v.push.apply(v,s)}return v}function o(c){for(var f=1;f<arguments.length;f++){var v=arguments[f]!=null?arguments[f]:{};f%2?i(Object(v),!0).forEach(function(s){(0,t.default)(c,s,v[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(c,Object.getOwnPropertyDescriptors(v)):i(Object(v)).forEach(function(s){Object.defineProperty(c,s,Object.getOwnPropertyDescriptor(v,s))})}return c}let a=class{constructor(f,v,s){this.client=f,this.indexEvent=v,this.directory=s}get id(){const f=this.indexEvent.getStateKey();if(!f)throw new Error("State key not found for branch");return f}get isActive(){return this.indexEvent.getContent().active===!0}get version(){var f;return(f=this.indexEvent.getContent().version)!==null&&f!==void 0?f:1}get roomId(){return this.indexEvent.getRoomId()}async delete(){await this.client.sendStateEvent(this.roomId,n.UNSTABLE_MSC3089_BRANCH.name,{},this.id),await this.client.redactEvent(this.roomId,this.id);const f=(await this.getVersionHistory())[1];f&&await f.delete()}getName(){return this.indexEvent.getContent().name||"Unnamed File"}async setName(f){await this.client.sendStateEvent(this.roomId,n.UNSTABLE_MSC3089_BRANCH.name,o(o({},this.indexEvent.getContent()),{},{name:f}),this.id)}isLocked(){return this.indexEvent.getContent().locked||!1}async setLocked(f){await this.client.sendStateEvent(this.roomId,n.UNSTABLE_MSC3089_BRANCH.name,o(o({},this.indexEvent.getContent()),{},{locked:f}),this.id)}async getFileInfo(){const v=(await this.getFileEvent()).getOriginalContent().file,s=this.client.mxcUrlToHttp(v.url);if(!s)throw new Error(`No HTTP URL available for ${v.url}`);return{info:v,httpUrl:s}}async getFileEvent(){const f=this.client.getRoom(this.roomId);if(!f)throw new Error("Unknown room");let v=f.getUnfilteredTimelineSet().findEventById(this.id);for(;!v&&f.getLiveTimeline().getState(r.EventTimeline.BACKWARDS).paginationToken;)await this.client.scrollback(f,100),v=f.getUnfilteredTimelineSet().findEventById(this.id);if(!v)throw new Error("Failed to find event");return await this.client.decryptEventIfNeeded(v,{emit:!0,isRetry:!0}),v}async createNewVersion(f,v,s,g){const y=await this.directory.createFile(f,v,s,o(o({},g??{}),{},{"m.new_content":!0,"m.relates_to":{rel_type:n.RelationType.Replace,event_id:this.id}}));return await this.client.sendStateEvent(this.roomId,n.UNSTABLE_MSC3089_BRANCH.name,{active:!0,name:f,version:this.version+1},y.event_id),await this.client.sendStateEvent(this.roomId,n.UNSTABLE_MSC3089_BRANCH.name,o(o({},this.indexEvent.getContent()),{},{active:!1}),this.id),y}async getVersionHistory(){const f=[];f.push(this);const v=this.client.getRoom(this.roomId);if(!v)throw new Error("Invalid or unknown room");const s=[...v.getLiveTimeline().getEvents()].reverse();let g,y=await this.getFileEvent();do if(g=s.find(S=>S.replacingEventId()===y.getId()),g){const S=this.directory.getFile(g.getId());if(S)f.push(S),y=g;else break}while(g);return f}};return cl.MSC3089Branch=a,cl}var Nb;function pk(){if(Nb)return Lr;Nb=1;var e=Ae;Object.defineProperty(Lr,"__esModule",{value:!0}),Lr.TreePermissions=Lr.MSC3089TreeSpace=Lr.DEFAULT_TREE_POWER_LEVELS_TEMPLATE=void 0;var t=e(Ue),n=e(mP()),r=xe,i=Ge(),o=lt(),a=F3(),c=lk();function f(S,m){var p=Object.keys(S);if(Object.getOwnPropertySymbols){var _=Object.getOwnPropertySymbols(S);m&&(_=_.filter(function(u){return Object.getOwnPropertyDescriptor(S,u).enumerable})),p.push.apply(p,_)}return p}function v(S){for(var m=1;m<arguments.length;m++){var p=arguments[m]!=null?arguments[m]:{};m%2?f(Object(p),!0).forEach(function(_){(0,t.default)(S,_,p[_])}):Object.getOwnPropertyDescriptors?Object.defineProperties(S,Object.getOwnPropertyDescriptors(p)):f(Object(p)).forEach(function(_){Object.defineProperty(S,_,Object.getOwnPropertyDescriptor(p,_))})}return S}const s={invite:100,kick:100,ban:100,redact:50,state_default:50,events_default:50,users_default:0,events:{[r.EventType.RoomPowerLevels]:100,[r.EventType.RoomHistoryVisibility]:100,[r.EventType.RoomTombstone]:100,[r.EventType.RoomEncryption]:100,[r.EventType.RoomName]:50,[r.EventType.RoomMessage]:50,[r.EventType.RoomMessageEncrypted]:50,[r.EventType.Sticker]:50},users:{}};Lr.DEFAULT_TREE_POWER_LEVELS_TEMPLATE=s;let g;Lr.TreePermissions=g,function(S){S.Viewer="viewer",S.Editor="editor",S.Owner="owner"}(g||(Lr.TreePermissions=g={}));let y=class{constructor(m,p){if(this.client=m,this.roomId=p,(0,t.default)(this,"room",void 0),this.room=this.client.getRoom(this.roomId),!this.room)throw new Error("Unknown room")}get id(){return this.roomId}get isTopLevel(){const m=this.room.currentState.getStateEvents(r.EventType.SpaceParent);return m!=null&&m.length?m.every(p=>{var _;return!((_=p.getContent())!==null&&_!==void 0&&_.via)}):!0}async setName(m){await this.client.sendStateEvent(this.roomId,r.EventType.RoomName,{name:m},"")}async invite(m,p=!0,_=!0){const u=[this.retryInvite(m)];return p&&u.push(...this.getDirectories().map(l=>l.invite(m,p,_))),Promise.all(u).then(()=>{_&&(0,c.isRoomSharedHistory)(this.room)&&this.client.sendSharedHistoryKeys(this.roomId,[m])})}retryInvite(m){return(0,o.simpleRetryOperation)(async()=>{await this.client.invite(this.roomId,m).catch(p=>{throw(p==null?void 0:p.errcode)==="M_FORBIDDEN"?new n.default.AbortError(p):p})})}async setPermissions(m,p){var _;const u=this.room.currentState.getStateEvents(r.EventType.RoomPowerLevels,"");if(Array.isArray(u))throw new Error("Unexpected return type for power levels");const l=(u==null?void 0:u.getContent())||{},d=l.users_default||0,h=l.events_default||50,w=((_=l.events)===null||_===void 0?void 0:_[r.EventType.RoomPowerLevels])||100,E=l.users||{};switch(p){case g.Viewer:E[m]=d;break;case g.Editor:E[m]=h;break;case g.Owner:E[m]=w;break;default:throw new Error("Invalid role: "+p)}l.users=E,await this.client.sendStateEvent(this.roomId,r.EventType.RoomPowerLevels,l,"")}getPermissions(m){var p,_;const u=this.room.currentState.getStateEvents(r.EventType.RoomPowerLevels,"");if(Array.isArray(u))throw new Error("Unexpected return type for power levels");const l=(u==null?void 0:u.getContent())||{},d=l.users_default||0,h=l.events_default||50,w=((p=l.events)===null||p===void 0?void 0:p[r.EventType.RoomPowerLevels])||100,E=((_=l.users)===null||_===void 0?void 0:_[m])||d;return E>=w?g.Owner:E>=h?g.Editor:g.Viewer}async createDirectory(m){const p=await this.client.unstableCreateFileTree(m);return await this.client.sendStateEvent(this.roomId,r.EventType.SpaceChild,{via:[this.client.getDomain()]},p.roomId),await this.client.sendStateEvent(p.roomId,r.EventType.SpaceParent,{via:[this.client.getDomain()]},this.roomId),p}getDirectories(){const m=[],p=this.room.currentState.getStateEvents(r.EventType.SpaceChild);for(const _ of p)try{const u=_.getStateKey();if(u){const l=this.client.unstableGetFileTreeSpace(u);l&&m.push(l)}}catch(u){i.logger.warn("Unable to create tree space instance for listing. Are we joined?",u)}return m}getDirectory(m){return this.getDirectories().find(p=>p.roomId===m)}async delete(){const m=this.getDirectories();for(const u of m)await u.delete();const p=["invite","knock","join"],_=this.room.currentState.getStateEvents(r.EventType.RoomMember);for(const u of _)if(u.getStateKey()!==this.client.getUserId()&&p.includes(u.getContent().membership)){const d=u.getStateKey();if(!d)throw new Error("State key not found for branch");await this.client.kick(this.roomId,d,"Room deleted")}await this.client.leave(this.roomId)}getOrderedChildren(m){const p=m.map(_=>({roomId:_.getStateKey(),order:_.getContent().order})).filter(_=>_.roomId);return p.sort((_,u)=>{if(_.order&&!u.order)return-1;if(!_.order&&u.order)return 1;if(!_.order&&!u.order){var l,d,h,w;const E=this.client.getRoom(_.roomId),I=this.client.getRoom(u.roomId);if(!E||!I)return(0,o.lexicographicCompare)(_.roomId,u.roomId);const k=(l=(d=E.currentState.getStateEvents(r.EventType.RoomCreate,""))===null||d===void 0?void 0:d.getTs())!==null&&l!==void 0?l:0,M=(h=(w=I.currentState.getStateEvents(r.EventType.RoomCreate,""))===null||w===void 0?void 0:w.getTs())!==null&&h!==void 0?h:0;return k===M?(0,o.lexicographicCompare)(_.roomId,u.roomId):k-M}else return(0,o.lexicographicCompare)(_.order,u.order)}),p}getParentRoom(){const p=this.room.currentState.getStateEvents(r.EventType.SpaceParent)[0];if(!p)throw new Error("Expected to have a parent in a non-top level space");const _=p.getStateKey();if(!_)throw new Error("No state key found for parent");const u=this.client.getRoom(_);if(!u)throw new Error("Unable to locate room for parent");return u}getOrder(){if(this.isTopLevel)return-1;const p=this.getParentRoom().currentState.getStateEvents(r.EventType.SpaceChild);return this.getOrderedChildren(p).findIndex(u=>u.roomId===this.roomId)}async setOrder(m){var p;if(this.isTopLevel)throw new Error("Cannot set order of top level spaces currently");const _=this.getParentRoom(),u=_.currentState.getStateEvents(r.EventType.SpaceChild),l=this.getOrderedChildren(u);m=Math.max(Math.min(m,l.length-1),0);const h=this.getOrder()<m;h&&m===l.length-1?m--:!h&&m===0&&m++;const w=l[h?m:m-1],E=l[h?m+1:m];let I=o.DEFAULT_ALPHABET[0],k=!1;if(!w)E!=null&&E.order&&(I=(0,o.prevString)(E.order));else if(m===l.length-1)E!=null&&E.order&&(I=(0,o.nextString)(E.order));else{const N=w==null?void 0:w.order,G=E==null?void 0:E.order;N&&G?N===G?I=(0,o.nextString)(N):I=(0,o.averageBetweenStrings)(N,G):N?I=(0,o.nextString)(N):G?I=(0,o.prevString)(G):k=!0}if(k){let N;for(let G=0;G<=m;G++){const D=l[G];if(G===0&&(N=D.order),D.order)N=D.order;else{var M;N=N?(0,o.nextString)(N):o.DEFAULT_ALPHABET[0];const x=_.currentState.getStateEvents(r.EventType.SpaceChild,D.roomId),z=(M=x==null?void 0:x.getContent())!==null&&M!==void 0?M:{via:[this.client.getDomain()]};await this.client.sendStateEvent(_.roomId,r.EventType.SpaceChild,v(v({},z),{},{order:N}),D.roomId)}}N&&(I=(0,o.nextString)(N))}const L=_.currentState.getStateEvents(r.EventType.SpaceChild,this.roomId),B=(p=L==null?void 0:L.getContent())!==null&&p!==void 0?p:{via:[this.client.getDomain()]};await this.client.sendStateEvent(_.roomId,r.EventType.SpaceChild,v(v({},B),{},{order:I}),this.roomId)}async createFile(m,p,_,u){var l;const{content_uri:d}=await this.client.uploadContent(p,{includeFilename:!1});_.url=d;const h={msgtype:r.MsgType.File,body:m,url:d,file:_};u=(l=u)!==null&&l!==void 0?l:{},u["m.new_content"]&&(u["m.new_content"]=h);const w=await this.client.sendMessage(this.roomId,v(v(v({},u),h),{},{[r.UNSTABLE_MSC3089_LEAF.name]:{}}));return await this.client.sendStateEvent(this.roomId,r.UNSTABLE_MSC3089_BRANCH.name,{active:!0,name:m},w.event_id),w}getFile(m){const p=this.room.currentState.getStateEvents(r.UNSTABLE_MSC3089_BRANCH.name,m);return p?new a.MSC3089Branch(this.client,p,this):null}listFiles(){return this.listAllFiles().filter(m=>m.isActive)}listAllFiles(){var m;return((m=this.room.currentState.getStateEvents(r.UNSTABLE_MSC3089_BRANCH.name))!==null&&m!==void 0?m:[]).map(_=>new a.MSC3089Branch(this.client,_,this))}};return Lr.MSC3089TreeSpace=y,Lr}var Pa={};Object.defineProperty(Pa,"__esModule",{value:!0});Pa.SearchOrderBy=void 0;var xb;(function(e){e.RoomId="room_id",e.Sender="sender"})(xb||(xb={}));let gm;Pa.SearchOrderBy=gm;(function(e){e.Recent="recent",e.Rank="rank"})(gm||(Pa.SearchOrderBy=gm={}));var ki={},$b;function K3(){if($b)return ki;$b=1;var e=Ae;Object.defineProperty(ki,"__esModule",{value:!0}),ki.MediaHandlerEvent=ki.MediaHandler=void 0;var t=e(Ue),n=Pt(),r=Ca(),i=Ge();let o;ki.MediaHandlerEvent=o,function(c){c.LocalStreamsChanged="local_streams_changed"}(o||(ki.MediaHandlerEvent=o={}));class a extends n.TypedEventEmitter{constructor(f){super(),this.client=f,(0,t.default)(this,"audioInput",void 0),(0,t.default)(this,"audioSettings",void 0),(0,t.default)(this,"videoInput",void 0),(0,t.default)(this,"localUserMediaStream",void 0),(0,t.default)(this,"userMediaStreams",[]),(0,t.default)(this,"screensharingStreams",[])}restoreMediaSettings(f,v){this.audioInput=f,this.videoInput=v}async setAudioInput(f){i.logger.info("Setting audio input to",f),this.audioInput!==f&&(this.audioInput=f,await this.updateLocalUsermediaStreams())}async setAudioSettings(f){i.logger.info("Setting audio settings to",f),this.audioSettings=Object.assign({},f),await this.updateLocalUsermediaStreams()}async setVideoInput(f){i.logger.info("Setting video input to",f),this.videoInput!==f&&(this.videoInput=f,await this.updateLocalUsermediaStreams())}async setMediaInputs(f,v){i.logger.log(`mediaHandler setMediaInputs audioInput: ${f} videoInput: ${v}`),this.audioInput=f,this.videoInput=v,await this.updateLocalUsermediaStreams()}async updateLocalUsermediaStreams(){if(this.userMediaStreams.length===0)return;const f=new Map;for(const v of this.client.callEventHandler.calls.values())f.set(v.callId,{audio:v.hasLocalUserMediaAudioTrack,video:v.hasLocalUserMediaVideoTrack});for(const v of this.userMediaStreams){i.logger.log(`mediaHandler stopping all tracks for stream ${v.id}`);for(const s of v.getTracks())s.stop()}this.userMediaStreams=[],this.localUserMediaStream=void 0;for(const v of this.client.callEventHandler.calls.values()){if(v.callHasEnded()||!f.has(v.callId))continue;const{audio:s,video:g}=f.get(v.callId);i.logger.log(`mediaHandler updateLocalUsermediaStreams getUserMediaStream call ${v.callId}`);const y=await this.getUserMediaStream(s,g);v.callHasEnded()||await v.updateLocalUsermediaStream(y)}for(const v of this.client.groupCallEventHandler.groupCalls.values()){if(!v.localCallFeed)continue;i.logger.log(`mediaHandler updateLocalUsermediaStreams getUserMediaStream groupCall ${v.groupCallId}`);const s=await this.getUserMediaStream(!0,v.type===r.GroupCallType.Video);v.state!==r.GroupCallState.Ended&&await v.updateLocalUsermediaStream(s)}this.emit(o.LocalStreamsChanged)}async hasAudioDevice(){return(await navigator.mediaDevices.enumerateDevices()).filter(v=>v.kind==="audioinput").length>0}async hasVideoDevice(){return(await navigator.mediaDevices.enumerateDevices()).filter(v=>v.kind==="videoinput").length>0}async getUserMediaStream(f,v,s=!0){const g=f&&await this.hasAudioDevice(),y=v&&await this.hasVideoDevice();let S,m=!0;if(this.localUserMediaStream){if(g){var p,_;(this.localUserMediaStream.getAudioTracks().length===0||((p=this.localUserMediaStream.getAudioTracks()[0])===null||p===void 0||(_=p.getSettings())===null||_===void 0?void 0:_.deviceId)!==this.audioInput)&&(m=!1)}if(y){var u,l;(this.localUserMediaStream.getVideoTracks().length===0||((u=this.localUserMediaStream.getVideoTracks()[0])===null||u===void 0||(l=u.getSettings())===null||l===void 0?void 0:l.deviceId)!==this.videoInput)&&(m=!1)}}else m=!1;if(m){var d;if(S=this.localUserMediaStream.clone(),i.logger.log(`mediaHandler clone userMediaStream ${(d=this.localUserMediaStream)===null||d===void 0?void 0:d.id} new stream ${S.id} shouldRequestAudio ${g} shouldRequestVideo ${y}`),!g)for(const h of S.getAudioTracks())S.removeTrack(h);if(!y)for(const h of S.getVideoTracks())S.removeTrack(h)}else{const h=this.getUserMediaContraints(g,y);S=await navigator.mediaDevices.getUserMedia(h),i.logger.log(`mediaHandler getUserMediaStream streamId ${S.id} shouldRequestAudio ${g} shouldRequestVideo ${y}`,h);for(const w of S.getTracks()){const E=w.getSettings();w.kind==="audio"?this.audioInput=E.deviceId:w.kind==="video"&&(this.videoInput=E.deviceId)}s&&(this.localUserMediaStream=S)}return s&&this.userMediaStreams.push(S),this.emit(o.LocalStreamsChanged),S}stopUserMediaStream(f){i.logger.log(`mediaHandler stopUserMediaStream stopping stream ${f.id}`);for(const s of f.getTracks())s.stop();const v=this.userMediaStreams.indexOf(f);v!==-1&&(i.logger.debug("Splicing usermedia stream out stream array",f.id),this.userMediaStreams.splice(v,1)),this.emit(o.LocalStreamsChanged),this.localUserMediaStream===f&&(this.localUserMediaStream=void 0)}async getScreensharingStream(f={},v=!0){let s;if(this.screensharingStreams.length===0){const g=this.getScreenshareContraints(f);f.desktopCapturerSourceId?(i.logger.debug("Getting screensharing stream using getUserMedia()",f),s=await navigator.mediaDevices.getUserMedia(g)):(i.logger.debug("Getting screensharing stream using getDisplayMedia()",f),s=await navigator.mediaDevices.getDisplayMedia(g))}else{const g=this.screensharingStreams[this.screensharingStreams.length-1];i.logger.log("Cloning screensharing stream",g.id),s=g.clone()}return v&&this.screensharingStreams.push(s),this.emit(o.LocalStreamsChanged),s}stopScreensharingStream(f){i.logger.debug("Stopping screensharing stream",f.id);for(const s of f.getTracks())s.stop();const v=this.screensharingStreams.indexOf(f);v!==-1&&(i.logger.debug("Splicing screensharing stream out stream array",f.id),this.screensharingStreams.splice(v,1)),this.emit(o.LocalStreamsChanged)}stopAllStreams(){for(const f of this.userMediaStreams){i.logger.log(`mediaHandler stopAllStreams stopping stream ${f.id}`);for(const v of f.getTracks())v.stop()}for(const f of this.screensharingStreams)for(const v of f.getTracks())v.stop();this.userMediaStreams=[],this.screensharingStreams=[],this.localUserMediaStream=void 0,this.emit(o.LocalStreamsChanged)}getUserMediaContraints(f,v){const s=!!navigator.webkitGetUserMedia;return{audio:f?{deviceId:this.audioInput?{ideal:this.audioInput}:void 0,autoGainControl:this.audioSettings?{ideal:this.audioSettings.autoGainControl}:void 0,echoCancellation:this.audioSettings?{ideal:this.audioSettings.echoCancellation}:void 0,noiseSuppression:this.audioSettings?{ideal:this.audioSettings.noiseSuppression}:void 0}:!1,video:v?{deviceId:this.videoInput?{ideal:this.videoInput}:void 0,width:s?{exact:640}:{ideal:640},height:s?{exact:360}:{ideal:360}}:!1}}getScreenshareContraints(f){const{desktopCapturerSourceId:v,audio:s}=f;return v?(i.logger.debug("Using desktop capturer source",v),{audio:s??!1,video:{mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:v}}}):(i.logger.debug("Not using desktop capturer source"),{audio:s??!1,video:!0})}}return ki.MediaHandler=a,ki}var dl={},It={},Ub;function j3(){if(Ub)return It;Ub=1;var e=Ae;Object.defineProperty(It,"__esModule",{value:!0}),It.SlidingSyncState=It.SlidingSyncEvent=It.SlidingSync=It.MSC3575_WILDCARD=It.MSC3575_STATE_KEY_ME=It.MSC3575_STATE_KEY_LAZY=It.ExtensionState=void 0;var t=e(Ue),n=Ge(),r=Pt(),i=lt();function o(u,l){var d=Object.keys(u);if(Object.getOwnPropertySymbols){var h=Object.getOwnPropertySymbols(u);l&&(h=h.filter(function(w){return Object.getOwnPropertyDescriptor(u,w).enumerable})),d.push.apply(d,h)}return d}function a(u){for(var l=1;l<arguments.length;l++){var d=arguments[l]!=null?arguments[l]:{};l%2?o(Object(d),!0).forEach(function(h){(0,t.default)(u,h,d[h])}):Object.getOwnPropertyDescriptors?Object.defineProperties(u,Object.getOwnPropertyDescriptors(d)):o(Object(d)).forEach(function(h){Object.defineProperty(u,h,Object.getOwnPropertyDescriptor(d,h))})}return u}const c=10*1e3,f="*";It.MSC3575_WILDCARD=f;const v="$ME";It.MSC3575_STATE_KEY_ME=v;const s="$LAZY";It.MSC3575_STATE_KEY_LAZY=s;let g;It.SlidingSyncState=g,function(u){u.RequestFinished="FINISHED",u.Complete="COMPLETE"}(g||(It.SlidingSyncState=g={}));class y{constructor(l){(0,t.default)(this,"list",void 0),(0,t.default)(this,"isModified",void 0),(0,t.default)(this,"roomIndexToRoomId",{}),(0,t.default)(this,"joinedCount",0),this.replaceList(l)}setModified(l){this.isModified=l}updateListRange(l){this.list.ranges=JSON.parse(JSON.stringify(l))}replaceList(l){l.filters=l.filters||{},l.ranges=l.ranges||[],this.list=JSON.parse(JSON.stringify(l)),this.isModified=!0,this.roomIndexToRoomId={},this.joinedCount=0}getList(l){let d={ranges:JSON.parse(JSON.stringify(this.list.ranges))};return(this.isModified||l)&&(d=JSON.parse(JSON.stringify(this.list))),d}isIndexInRange(l){for(const d of this.list.ranges)if(d[0]<=l&&l<=d[1])return!0;return!1}}let S;It.ExtensionState=S,function(u){u.PreProcess="ExtState.PreProcess",u.PostProcess="ExtState.PostProcess"}(S||(It.ExtensionState=S={}));let m;It.SlidingSyncEvent=m,function(u){u.RoomData="SlidingSync.RoomData",u.Lifecycle="SlidingSync.Lifecycle",u.List="SlidingSync.List"}(m||(It.SlidingSyncEvent=m={}));class p extends r.TypedEventEmitter{constructor(l,d,h,w,E){super(),this.proxyBaseUrl=l,this.roomSubscriptionInfo=h,this.client=w,this.timeoutMS=E,(0,t.default)(this,"lists",void 0),(0,t.default)(this,"listModifiedCount",0),(0,t.default)(this,"terminated",!1),(0,t.default)(this,"needsResend",!1),(0,t.default)(this,"txnId",null),(0,t.default)(this,"txnIdDefers",[]),(0,t.default)(this,"extensions",{}),(0,t.default)(this,"desiredRoomSubscriptions",new Set),(0,t.default)(this,"confirmedRoomSubscriptions",new Set),(0,t.default)(this,"customSubscriptions",new Map),(0,t.default)(this,"roomIdToCustomSubscription",new Map),(0,t.default)(this,"pendingReq",void 0),(0,t.default)(this,"abortController",void 0),this.lists=d.map(I=>new y(I))}addCustomSubscription(l,d){this.customSubscriptions.set(l,d)}useCustomSubscription(l,d){this.roomIdToCustomSubscription.set(l,d),this.confirmedRoomSubscriptions.delete(l)}listLength(){return this.lists.length}getListData(l){return this.lists[l]?{joinedCount:this.lists[l].joinedCount,roomIndexToRoomId:Object.assign({},this.lists[l].roomIndexToRoomId)}:null}getList(l){return this.lists[l]?this.lists[l].getList(!0):null}setListRanges(l,d){return this.lists[l].updateListRange(d),this.resend()}setList(l,d){return this.lists[l]?this.lists[l].replaceList(d):this.lists[l]=new y(d),this.listModifiedCount+=1,this.resend()}getRoomSubscriptions(){return new Set(Array.from(this.desiredRoomSubscriptions))}modifyRoomSubscriptions(l){return this.desiredRoomSubscriptions=l,this.resend()}modifyRoomSubscriptionInfo(l){return this.roomSubscriptionInfo=l,this.confirmedRoomSubscriptions=new Set,this.resend()}registerExtension(l){if(this.extensions[l.name()])throw new Error(`registerExtension: ${l.name()} already exists as an extension`);this.extensions[l.name()]=l}getExtensionRequest(l){const d={};return Object.keys(this.extensions).forEach(h=>{d[h]=this.extensions[h].onRequest(l)}),d}onPreExtensionsResponse(l){Object.keys(l).forEach(d=>{this.extensions[d].when()==S.PreProcess&&this.extensions[d].onResponse(l[d])})}onPostExtensionsResponse(l){Object.keys(l).forEach(d=>{this.extensions[d].when()==S.PostProcess&&this.extensions[d].onResponse(l[d])})}invokeRoomDataListeners(l,d){d.required_state||(d.required_state=[]),d.timeline||(d.timeline=[]),this.emit(m.RoomData,l,d)}invokeLifecycleListeners(l,d,h){this.emit(m.Lifecycle,l,d,h)}shiftRight(l,d,h){for(let w=d;w>h;w--)this.lists[l].isIndexInRange(w)&&(this.lists[l].roomIndexToRoomId[w]=this.lists[l].roomIndexToRoomId[w-1])}shiftLeft(l,d,h){for(let w=h;w<d;w++)this.lists[l].isIndexInRange(w)&&(this.lists[l].roomIndexToRoomId[w]=this.lists[l].roomIndexToRoomId[w+1])}removeEntry(l,d){let h=-1;for(const w in this.lists[l].roomIndexToRoomId)Number(w)>h&&(h=Number(w));h<0||d>h||(this.shiftLeft(l,h,d),delete this.lists[l].roomIndexToRoomId[h])}addEntry(l,d){let h=-1;for(const w in this.lists[l].roomIndexToRoomId)Number(w)>h&&(h=Number(w));h<0||d>h||this.shiftRight(l,h+1,d)}processListOps(l,d){let h=-1;l.ops.forEach(w=>{switch(w.op){case"DELETE":{n.logger.debug("DELETE",d,w.index,";"),delete this.lists[d].roomIndexToRoomId[w.index],h!==-1&&this.removeEntry(d,h),h=w.index;break}case"INSERT":{n.logger.debug("INSERT",d,w.index,w.room_id,";"),this.lists[d].roomIndexToRoomId[w.index]&&(h<0?this.addEntry(d,w.index):h>w.index?this.shiftRight(d,h,w.index):h<w.index&&this.shiftLeft(d,w.index,h)),h=-1,this.lists[d].roomIndexToRoomId[w.index]=w.room_id;break}case"INVALIDATE":{const E=w.range[0];for(let I=E;I<=w.range[1];I++)delete this.lists[d].roomIndexToRoomId[I];n.logger.debug("INVALIDATE",d,w.range[0],w.range[1],";");break}case"SYNC":{const E=w.range[0];for(let I=E;I<=w.range[1];I++){const k=w.room_ids[I-E];if(!k)break;this.lists[d].roomIndexToRoomId[I]=k}n.logger.debug("SYNC",d,w.range[0],w.range[1],(w.room_ids||[]).join(" "),";");break}}}),h!==-1&&this.removeEntry(d,h)}resend(){var l;if(this.needsResend&&this.txnIdDefers.length>0)return this.txnIdDefers[this.txnIdDefers.length-1].promise;this.needsResend=!0,this.txnId=this.client.makeTxnId();const d=(0,i.defer)();return this.txnIdDefers.push(a(a({},d),{},{txnId:this.txnId})),(l=this.abortController)===null||l===void 0||l.abort(),this.abortController=new AbortController,d.promise}resolveTransactionDefers(l){if(!l)return;let d=-1;for(let h=0;h<this.txnIdDefers.length;h++)if(this.txnIdDefers[h].txnId===l){d=h;break}if(d===-1){n.logger.warn(`resolveTransactionDefers: seen ${l} but it isn't a pending txn, ignoring.`);return}for(let h=0;h<d;h++)this.txnIdDefers[h].reject(this.txnIdDefers[h].txnId);this.txnIdDefers[d].resolve(l),this.txnIdDefers=this.txnIdDefers.slice(d+1)}stop(){var l;this.terminated=!0,(l=this.abortController)===null||l===void 0||l.abort(),this.removeAllListeners(m.Lifecycle),this.removeAllListeners(m.List),this.removeAllListeners(m.RoomData)}resetup(){var l;n.logger.warn("SlidingSync: resetting connection info"),this.txnIdDefers.forEach(d=>{d.reject(d.txnId)}),this.txnIdDefers=[],this.lists.forEach(d=>{d.setModified(!0)}),this.confirmedRoomSubscriptions=new Set,this.needsResend=!0,(l=this.abortController)===null||l===void 0||l.abort(),this.abortController=new AbortController}async start(){this.abortController=new AbortController;let l;for(;!this.terminated;){this.needsResend=!1;let d=!1,h;try{const E=this.listModifiedCount,I={lists:this.lists.map(L=>L.getList(!1)),pos:l,timeout:this.timeoutMS,clientTimeout:this.timeoutMS+c,extensions:this.getExtensionRequest(l===void 0)},k=_(this.desiredRoomSubscriptions,this.confirmedRoomSubscriptions),M=_(this.confirmedRoomSubscriptions,this.desiredRoomSubscriptions);if(M.size>0&&(I.unsubscribe_rooms=Array.from(M)),k.size>0){I.room_subscriptions={};for(const L of k){const B=this.roomIdToCustomSubscription.get(L);let N=this.roomSubscriptionInfo;B&&this.customSubscriptions.has(B)&&(N=this.customSubscriptions.get(B)),I.room_subscriptions[L]=N}}this.txnId&&(I.txn_id=this.txnId,this.txnId=null),this.pendingReq=this.client.slidingSync(I,this.proxyBaseUrl,this.abortController.signal),h=await this.pendingReq,l=h.pos;for(const L of k)this.confirmedRoomSubscriptions.add(L);for(const L of M)this.confirmedRoomSubscriptions.delete(L);E!==this.listModifiedCount&&(n.logger.debug("list modified during await call, not updating list"),d=!0),this.lists.forEach(L=>{L.setModified(!1)}),h.lists=h.lists||[],h.rooms=h.rooms||{},h.extensions=h.extensions||{},h.lists.forEach((L,B)=>{this.lists[B].joinedCount=L.count}),this.invokeLifecycleListeners(g.RequestFinished,h)}catch(E){if(E.httpStatus){if(this.invokeLifecycleListeners(g.RequestFinished,null,E),E.httpStatus===400){this.resetup(),l=void 0,await(0,i.sleep)(50);continue}}else if(this.needsResend||E.name==="AbortError")continue;n.logger.error(E),await(0,i.sleep)(5e3)}if(!h)continue;this.onPreExtensionsResponse(h.extensions),Object.keys(h.rooms).forEach(E=>{this.invokeRoomDataListeners(E,h.rooms[E])});const w=new Set;d||h.lists.forEach((E,I)=>{E.ops=E.ops||[],E.ops.length>0&&w.add(I),this.processListOps(E,I)}),this.invokeLifecycleListeners(g.Complete,h),this.onPostExtensionsResponse(h.extensions),w.forEach(E=>{this.emit(m.List,E,this.lists[E].joinedCount,Object.assign({},this.lists[E].roomIndexToRoomId))}),this.resolveTransactionDefers(h.txn_id)}}}It.SlidingSync=p;const _=(u,l)=>{const d=new Set(u);for(const h of l)d.delete(h);return d};return It}var Bb;function gk(){if(Bb)return dl;Bb=1;var e=Ae;Object.defineProperty(dl,"__esModule",{value:!0}),dl.SlidingSyncSdk=void 0;var t=e(Ue),n=hi(),r=Ge(),i=p(lt()),o=Tr(),a=or(),c=Vf(),f=Rr,v=j3(),s=xe,g=Qy(),y=po(),S=Zn;function m(L){if(typeof WeakMap!="function")return null;var B=new WeakMap,N=new WeakMap;return(m=function(G){return G?N:B})(L)}function p(L,B){if(!B&&L&&L.__esModule)return L;if(L===null||typeof L!="object"&&typeof L!="function")return{default:L};var N=m(B);if(N&&N.has(L))return N.get(L);var G={},D=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var x in L)if(x!=="default"&&Object.prototype.hasOwnProperty.call(L,x)){var z=D?Object.getOwnPropertyDescriptor(L,x):null;z&&(z.get||z.set)?Object.defineProperty(G,x,z):G[x]=L[x]}return G.default=L,N&&N.set(L,G),G}const _=3;class u{constructor(B){this.crypto=B}name(){return"e2ee"}when(){return v.ExtensionState.PreProcess}onRequest(B){if(B)return{enabled:!0}}async onResponse(B){if(B.device_lists&&await this.crypto.handleDeviceListChanges({oldSyncToken:"yep"},B.device_lists),B.device_one_time_keys_count){const N=B.device_one_time_keys_count.signed_curve25519||0;this.crypto.updateOneTimeKeyCount(N)}if(B.device_unused_fallback_key_types||B["org.matrix.msc2732.device_unused_fallback_key_types"]){const N=B.device_unused_fallback_key_types||B["org.matrix.msc2732.device_unused_fallback_key_types"];this.crypto.setNeedsNewFallback(Array.isArray(N)&&!N.includes("signed_curve25519"))}}}class l{constructor(B){this.client=B,(0,t.default)(this,"nextBatch",null)}name(){return"to_device"}when(){return v.ExtensionState.PreProcess}onRequest(B){const N={since:this.nextBatch!==null?this.nextBatch:void 0};return B&&(N.limit=100,N.enabled=!0),N}async onResponse(B){var N;const G=[];(N=B.events)===null||N===void 0||N.map(this.client.getEventMapper()).map(D=>{if(D.getType()==="m.key.verification.cancel"){const x=D.getContent().transaction_id;x&&G.push(x)}return D}).forEach(D=>{const x=D.getContent();if(D.getType()=="m.room.message"&&x.msgtype=="m.bad.encrypted"){r.logger.log("Ignoring undecryptable to-device event from "+D.getSender());return}if(D.getType()==="m.key.verification.start"||D.getType()==="m.key.verification.request"){const z=x.transaction_id;G.includes(z)&&D.flagCancelled()}this.client.emit(a.ClientEvent.ToDeviceEvent,D)}),this.nextBatch=B.next_batch}}class d{constructor(B){this.client=B}name(){return"account_data"}when(){return v.ExtensionState.PostProcess}onRequest(B){if(B)return{enabled:!0}}onResponse(B){B.global&&B.global.length>0&&this.processGlobalAccountData(B.global);for(const N in B.rooms){const G=k(this.client,N,B.rooms[N]),D=this.client.getRoom(N);if(!D){r.logger.warn("got account data for room but room doesn't exist on client:",N);continue}D.addAccountData(G),G.forEach(x=>{this.client.emit(a.ClientEvent.Event,x)})}}processGlobalAccountData(B){const N=k(this.client,void 0,B),G=N.reduce((D,x)=>(D[x.getType()]=this.client.store.getAccountData(x.getType()),D),{});this.client.store.storeAccountDataEvents(N),N.forEach(D=>{if(D.getType()===s.EventType.PushRules){const z=D.getContent();this.client.pushRules=g.PushProcessor.rewriteDefaultRules(z)}const x=G[D.getType()];return this.client.emit(a.ClientEvent.AccountData,D,x),D})}}class h{constructor(B){this.client=B}name(){return"typing"}when(){return v.ExtensionState.PostProcess}onRequest(B){if(B)return{enabled:!0}}onResponse(B){if(B!=null&&B.rooms)for(const N in B.rooms)M(this.client,N,[B.rooms[N]])}}class w{constructor(B){this.client=B}name(){return"receipts"}when(){return v.ExtensionState.PostProcess}onRequest(B){if(B)return{enabled:!0}}onResponse(B){if(B!=null&&B.rooms)for(const N in B.rooms)M(this.client,N,[B.rooms[N]])}}class E{constructor(B,N,G={}){var D;this.slidingSync=B,this.client=N,this.opts=G,(0,t.default)(this,"syncState",null),(0,t.default)(this,"syncStateData",void 0),(0,t.default)(this,"lastPos",null),(0,t.default)(this,"failCount",0),(0,t.default)(this,"notifEvents",[]),this.opts.initialSyncLimit=(D=this.opts.initialSyncLimit)!==null&&D!==void 0?D:8,this.opts.resolveInvitesToProfiles=this.opts.resolveInvitesToProfiles||!1,this.opts.pollTimeout=this.opts.pollTimeout||30*1e3,this.opts.pendingEventOrdering=this.opts.pendingEventOrdering||a.PendingEventOrdering.Chronological,this.opts.experimentalThreadSupport=this.opts.experimentalThreadSupport===!0,G.canResetEntireTimeline||(G.canResetEntireTimeline=z=>!1),N.getNotifTimelineSet()&&N.reEmitter.reEmit(N.getNotifTimelineSet(),[n.RoomEvent.Timeline,n.RoomEvent.TimelineReset]),this.slidingSync.on(v.SlidingSyncEvent.Lifecycle,this.onLifecycle.bind(this)),this.slidingSync.on(v.SlidingSyncEvent.RoomData,this.onRoomData.bind(this));const x=[new l(this.client),new d(this.client),new h(this.client),new w(this.client)];this.opts.crypto&&x.push(new u(this.opts.crypto)),x.forEach(z=>{this.slidingSync.registerExtension(z)})}onRoomData(B,N){let G=this.client.store.getRoom(B);if(!G){if(!N.initial){r.logger.debug("initial flag not set but no stored room exists for room ",B,N);return}G=(0,c._createAndReEmitRoom)(this.client,B,this.opts)}this.processRoomData(this.client,G,N)}onLifecycle(B,N,G){switch(G&&r.logger.debug("onLifecycle",B,G),B){case v.SlidingSyncState.Complete:if(this.purgeNotifications(),!N)break;this.lastPos||this.updateSyncState(c.SyncState.Prepared,{oldSyncToken:void 0,nextSyncToken:N.pos,catchingUp:!1,fromCache:!1}),this.updateSyncState(c.SyncState.Syncing,{oldSyncToken:this.lastPos,nextSyncToken:N.pos,catchingUp:!1,fromCache:!1}),this.lastPos=N.pos;break;case v.SlidingSyncState.RequestFinished:if(G){if(this.failCount+=1,this.updateSyncState(this.failCount>_?c.SyncState.Error:c.SyncState.Reconnecting,{error:new f.MatrixError(G)}),this.shouldAbortSync(new f.MatrixError(G)))return}else this.failCount=0;break}}async syncLeftRooms(){return[]}async peek(B){return null}stopPeeking(){}getSyncState(){return this.syncState}getSyncStateData(){var B;return(B=this.syncStateData)!==null&&B!==void 0?B:null}createRoom(B){const{timelineSupport:N}=this.client,G=new n.Room(B,this.client,this.client.getUserId(),{lazyLoadMembers:this.opts.lazyLoadMembers,pendingEventOrdering:this.opts.pendingEventOrdering,timelineSupport:N});return this.client.reEmitter.reEmit(G,[n.RoomEvent.Name,n.RoomEvent.Redaction,n.RoomEvent.RedactionCancelled,n.RoomEvent.Receipt,n.RoomEvent.Tags,n.RoomEvent.LocalEchoUpdated,n.RoomEvent.AccountData,n.RoomEvent.MyMembership,n.RoomEvent.Timeline,n.RoomEvent.TimelineReset]),this.registerStateListeners(G),G}registerStateListeners(B){this.client.reEmitter.reEmit(B.currentState,[y.RoomStateEvent.Events,y.RoomStateEvent.Members,y.RoomStateEvent.NewMember,y.RoomStateEvent.Update]),B.currentState.on(y.RoomStateEvent.NewMember,(N,G,D)=>{var x;D.user=(x=this.client.getUser(D.userId))!==null&&x!==void 0?x:void 0,this.client.reEmitter.reEmit(D,[S.RoomMemberEvent.Name,S.RoomMemberEvent.Typing,S.RoomMemberEvent.PowerLevel,S.RoomMemberEvent.Membership])})}shouldAbortSync(B){return B.errcode==="M_UNKNOWN_TOKEN"?(r.logger.warn("Token no longer valid - assuming logout"),this.stop(),this.updateSyncState(c.SyncState.Error,{error:B}),!0):!1}async processRoomData(B,N,G){G=I(B,N.roomId,G);const D=k(this.client,N.roomId,G.required_state);let x=k(this.client,N.roomId,G.timeline,!1);const z=[];if(G.initial){const R=new Set;N.getLiveTimeline().getEvents().forEach(C=>{R.add(C.getId())});const P=[],K=[];let U=!1;for(let C=x.length-1;C>=0;C--){const A=x[C];if(R.has(A.getId())){U=!0;continue}U?P.push(A):K.unshift(A)}x=K,P.length>0&&N.addEventsToTimeline(P,!0,N.getLiveTimeline(),G.prev_batch)}const W=this.client.isRoomEncrypted(N.roomId);if(G.notification_count!=null&&N.setUnreadNotificationCount(n.NotificationCountType.Total,G.notification_count),G.highlight_count!=null&&(!W||W&&N.getUnreadNotificationCount(n.NotificationCountType.Highlight)<=0)&&N.setUnreadNotificationCount(n.NotificationCountType.Highlight,G.highlight_count),Number.isInteger(G.invited_count)&&N.currentState.setInvitedMemberCount(G.invited_count),Number.isInteger(G.joined_count)&&N.currentState.setJoinedMemberCount(G.joined_count),G.invite_state){const R=k(this.client,N.roomId,G.invite_state);this.injectRoomEvents(N,R),G.initial&&(N.recalculate(),this.client.store.storeRoom(N),this.client.emit(a.ClientEvent.Room,N)),R.forEach(P=>{this.client.emit(a.ClientEvent.Event,P)}),N.updateMyMembership("invite");return}if(G.initial){var F;N.getLiveTimeline().setPaginationToken((F=G.prev_batch)!==null&&F!==void 0?F:null,o.EventTimeline.BACKWARDS)}this.injectRoomEvents(N,D,x,G.num_live),N.addEphemeralEvents(z),N.updateMyMembership("join"),N.recalculate(),G.initial&&(B.store.storeRoom(N),B.emit(a.ClientEvent.Room,N)),this.addNotifications(x);const H=async R=>{B.emit(a.ClientEvent.Event,R),R.isState()&&R.getType()==s.EventType.RoomEncryption&&this.opts.crypto&&await this.opts.crypto.onCryptoEvent(N,R)};await i.promiseMapSeries(D,H),await i.promiseMapSeries(x,H),z.forEach(function(R){B.emit(a.ClientEvent.Event,R)}),N.decryptCriticalEvents()}injectRoomEvents(B,N,G,D){G=G||[],N=N||[],D=D||0;const x=B.getLiveTimeline(),z=x.getEvents().length==0;if(z){for(const F of N)this.client.getPushActionsForEvent(F);x.initialiseState(N)}z||(B.oldState.setStateEvents(N),B.currentState.setStateEvents(N));let W=[];D>0&&(W=G.slice(-1*D),G=G.slice(0,-1*W.length)),B.addLiveEvents(G,{fromCache:!0}),W.length>0&&B.addLiveEvents(W,{fromCache:!1}),B.recalculate(),this.resolveInvites(B)}resolveInvites(B){if(!B||!this.opts.resolveInvitesToProfiles)return;const N=this.client;B.getMembersWithMembership("invite").forEach(function(G){if(G.requestedProfileInfo)return;G.requestedProfileInfo=!0;const D=N.getUser(G.userId);let x;D?x=Promise.resolve({avatar_url:D.avatarUrl,displayname:D.displayName}):x=N.getProfileInfo(G.userId),x.then(function(z){const W=G.events.member;W.getContent().membership==="invite"&&(W.getContent().avatar_url=z.avatar_url,W.getContent().displayname=z.displayname,G.setMembershipEvent(W,B.currentState))},function(z){})})}retryImmediately(){return!0}async sync(){for(r.logger.debug("Sliding sync init loop");!this.client.isGuest();)try{r.logger.debug("Getting push rules...");const B=await this.client.getPushRules();r.logger.debug("Got push rules"),this.client.pushRules=B;break}catch(B){if(r.logger.error("Getting push rules failed",B),this.shouldAbortSync(B))return}await this.slidingSync.start()}stop(){r.logger.debug("SyncApi.stop"),this.slidingSync.stop()}updateSyncState(B,N){const G=this.syncState;this.syncState=B,this.syncStateData=N,this.client.emit(a.ClientEvent.Sync,this.syncState,G,N)}addNotifications(B){if(this.client.getNotifTimelineSet())for(const N of B){const G=this.client.getPushActionsForEvent(N);G&&G.notify&&G.tweaks&&G.tweaks.highlight&&this.notifEvents.push(N)}}purgeNotifications(){this.notifEvents.sort(function(B,N){return B.getTs()-N.getTs()}),this.notifEvents.forEach(B=>{var N;(N=this.client.getNotifTimelineSet())===null||N===void 0||N.addLiveEvent(B)}),this.notifEvents=[]}}dl.SlidingSyncSdk=E;function I(L,B,N){if(!N.name)return N;for(const G of N.required_state)if(G.type===s.EventType.RoomName&&G.state_key==="")return G.content={name:N.name},N;return N.required_state.push({event_id:"$fake-sliding-sync-name-event-"+B,state_key:"",type:s.EventType.RoomName,content:{name:N.name},sender:L.getUserId(),origin_server_ts:new Date().getTime()}),N}function k(L,B,N,G=!0){const D=L.getEventMapper({decrypt:G});return N.map(function(x){return x.room_id=B,D(x)})}function M(L,B,N){const G=k(L,B,N),D=L.getRoom(B);if(!D){r.logger.warn("got ephemeral events for room but room doesn't exist on client:",B);return}D.addEphemeralEvents(G),G.forEach(x=>{L.emit(a.ClientEvent.Event,x)})}return dl}var Io={},Fb;function vk(){if(Fb)return Io;Fb=1,Object.defineProperty(Io,"__esModule",{value:!0}),Io.M_BEACON_INFO=Io.M_BEACON=void 0;var e=en;const t=new e.UnstableValue("m.beacon_info","org.matrix.msc3672.beacon_info");Io.M_BEACON_INFO=t;const n=new e.UnstableValue("m.beacon","org.matrix.msc3672.beacon");return Io.M_BEACON=n,Io}var fl={},ec={},q3=Ae;Object.defineProperty(ec,"__esModule",{value:!0});ec.MatrixScheduler=void 0;var Bc=q3(Ue),Kb=H3(lt());Ge();var V3=xe,W3=Rr;function mk(e){if(typeof WeakMap!="function")return null;var t=new WeakMap,n=new WeakMap;return(mk=function(r){return r?n:t})(e)}function H3(e,t){if(!t&&e&&e.__esModule)return e;if(e===null||typeof e!="object"&&typeof e!="function")return{default:e};var n=mk(t);if(n&&n.has(e))return n.get(e);var r={},i=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var o in e)if(o!=="default"&&Object.prototype.hasOwnProperty.call(e,o)){var a=i?Object.getOwnPropertyDescriptor(e,o):null;a&&(a.get||a.set)?Object.defineProperty(r,o,a):r[o]=e[o]}return r.default=e,n&&n.set(e,r),r}class nf{static RETRY_BACKOFF_RATELIMIT(t,n,r){if(r.httpStatus===400||r.httpStatus===403||r.httpStatus===401||r instanceof W3.ConnectionError||r.name==="M_TOO_LARGE")return-1;if(r.name==="M_LIMIT_EXCEEDED"){const i=r.data.retry_after_ms;if(i>0)return i}return n>4?-1:1e3*Math.pow(2,n)}static QUEUE_MESSAGES(t){return t.getType()===V3.EventType.RoomMessage||t.hasAssociation()?"message":null}constructor(t=nf.RETRY_BACKOFF_RATELIMIT,n=nf.QUEUE_MESSAGES){this.retryAlgorithm=t,this.queueAlgorithm=n,(0,Bc.default)(this,"queues",{}),(0,Bc.default)(this,"activeQueues",[]),(0,Bc.default)(this,"procFn",null),(0,Bc.default)(this,"processQueue",r=>{const i=this.peekNextEvent(r);if(!i){const o=this.activeQueues.indexOf(r);o>=0&&this.activeQueues.splice(o,1);return}hl("Queue '%s' has %s pending events",r,this.queues[r].length),Promise.resolve().then(()=>this.procFn(i.event)).then(o=>{this.removeNextEvent(r),hl("Queue '%s' sent event %s",r,i.event.getId()),i.defer.resolve(o),this.processQueue(r)},o=>{i.attempts+=1;const a=this.retryAlgorithm(i.event,i.attempts,o);hl("retry(%s) err=%s event_id=%s waitTime=%s",i.attempts,o,i.event.getId(),a),a===-1?(hl("Queue '%s' giving up on event %s",r,i.event.getId()),this.removeNextEvent(r),i.defer.reject(o),this.processQueue(r)):setTimeout(this.processQueue,a,r)})})}getQueueForEvent(t){const n=this.queueAlgorithm(t);return!n||!this.queues[n]?null:this.queues[n].map(function(r){return r.event})}removeEventFromQueue(t){const n=this.queueAlgorithm(t);if(!n||!this.queues[n])return!1;let r=!1;return Kb.removeElement(this.queues[n],i=>i.event.getId()===t.getId()?(r=!0,!0):!1),r}setProcessFunction(t){this.procFn=t,this.startProcessingQueues()}queueEvent(t){const n=this.queueAlgorithm(t);if(!n)return null;this.queues[n]||(this.queues[n]=[]);const r=Kb.defer();return this.queues[n].push({event:t,defer:r,attempts:0}),hl("Queue algorithm dumped event %s into queue '%s'",t.getId(),n),this.startProcessingQueues(),r.promise}startProcessingQueues(){this.procFn&&Object.keys(this.queues).filter(t=>this.activeQueues.indexOf(t)===-1&&this.queues[t].length>0).forEach(t=>{this.activeQueues.push(t),this.processQueue(t)})}peekNextEvent(t){const n=this.queues[t];if(Array.isArray(n))return n[0]}removeNextEvent(t){const n=this.queues[t];if(Array.isArray(n))return n.shift()}}ec.MatrixScheduler=nf;function hl(...e){}var jb;function G3(){if(jb)return fl;jb=1;var e=Ae;Object.defineProperty(fl,"__esModule",{value:!0}),fl.ToDeviceMessageQueue=void 0;var t=e(Ue),n=xe,r=Ge(),i=ec;const o=20;let a=class{constructor(f){this.client=f,(0,t.default)(this,"sending",!1),(0,t.default)(this,"running",!0),(0,t.default)(this,"retryTimeout",null),(0,t.default)(this,"retryAttempts",0),(0,t.default)(this,"sendQueue",async()=>{if(this.retryTimeout!==null&&clearTimeout(this.retryTimeout),this.retryTimeout=null,this.sending||!this.running)return;r.logger.debug("Attempting to send queued to-device messages"),this.sending=!0;let v;try{for(;this.running&&(v=await this.client.store.getOldestToDeviceBatch(),v!==null);)await this.sendBatch(v),await this.client.store.removeToDeviceBatch(v.id),this.retryAttempts=0;if(!this.running)return;r.logger.debug("All queued to-device messages sent")}catch(s){++this.retryAttempts;const g=i.MatrixScheduler.RETRY_BACKOFF_RATELIMIT(null,this.retryAttempts,s);if(g===-1){Math.floor(s.httpStatus/100)===4?(r.logger.error("Fatal error when sending to-device message - dropping to-device batch!",s),await this.client.store.removeToDeviceBatch(v.id)):r.logger.info("Automatic retry limit reached for to-device messages.");return}r.logger.info(`Failed to send batch of to-device messages. Will retry in ${g}ms`,s),this.retryTimeout=setTimeout(this.sendQueue,g)}finally{this.sending=!1}})}start(){this.running=!0,this.sendQueue()}stop(){this.running=!1,this.retryTimeout!==null&&clearTimeout(this.retryTimeout),this.retryTimeout=null}async queueBatch(f){const v=[];for(let s=0;s<f.batch.length;s+=o){const g={eventType:f.eventType,batch:f.batch.slice(s,s+o),txnId:this.client.makeTxnId()};v.push(g);const y=g.batch.map(S=>`${S.userId}/${S.deviceId} (msgid ${S.payload[n.ToDeviceMessageId]})`);r.logger.info(`Enqueuing batch of to-device messages. type=${f.eventType} txnid=${g.txnId}`,y)}await this.client.store.saveToDeviceBatches(v),this.sendQueue()}async sendBatch(f){const v={};for(const s of f.batch)v[s.userId]||(v[s.userId]={}),v[s.userId][s.deviceId]=s.payload;r.logger.info(`Sending batch of ${f.batch.length} to-device messages with ID ${f.id} and txnId ${f.txnId}`),await this.client.sendToDevice(f.eventType,v,f.txnId)}};return fl.ToDeviceMessageQueue=a,fl}var Vn={},qb;function z3(){if(qb)return Vn;qb=1,Object.defineProperty(Vn,"__esModule",{value:!0}),Vn.PolicyScope=Vn.POLICIES_ACCOUNT_EVENT_TYPE=Vn.IgnoredInvites=Vn.IGNORE_INVITES_ACCOUNT_EVENT_KEY=void 0;var e=Fu,t=Tr(),n=yt,r=lt();const i=new e.UnstableValue("m.policies","org.matrix.msc3847.policies");Vn.POLICIES_ACCOUNT_EVENT_TYPE=i;const o=new e.UnstableValue("m.ignore.invites","org.matrix.msc3847.ignore.invites");Vn.IGNORE_INVITES_ACCOUNT_EVENT_KEY=o;var a;(function(v){v.Ban="m.ban"})(a||(a={}));let c;Vn.PolicyScope=c,function(v){v.User="m.policy.user",v.Room="m.policy.room",v.Server="m.policy.server"}(c||(Vn.PolicyScope=c={}));class f{constructor(s){this.client=s}async addRule(s,g,y){const S=await this.getOrCreateTargetRoom();return(await this.client.sendStateEvent(S.roomId,s,{entity:g,reason:y,recommendation:a.Ban})).event_id}async removeRule(s){await this.client.redactEvent(s.getRoomId(),s.getId())}async addSource(s){await this.client.joinRoom(s);const g=(await this.getOrCreateSourceRooms()).map(y=>y.roomId);return g.includes(s)?!1:(g.push(s),await this.withIgnoreInvitesPolicies(y=>{y.sources=g}),!0)}async getRuleForInvite({sender:s,roomId:g}){const y=await this.getOrCreateSourceRooms(),S=s.split(":")[1],m=g.split(":")[1];for(const p of y){const _=p.getUnfilteredTimelineSet().getLiveTimeline().getState(t.EventTimeline.FORWARDS);for(const{scope:u,entities:l}of[{scope:c.Room,entities:[g]},{scope:c.User,entities:[s]},{scope:c.Server,entities:[S,m]}]){const d=_.getStateEvents(u);for(const h of d){const w=h.getContent();if((w==null?void 0:w.recommendation)!=a.Ban)continue;const E=w==null?void 0:w.entity;if(!E)continue;let I;try{I=new RegExp((0,r.globToRegexp)(E,!1))}catch{continue}for(const k of l)if(k&&I.test(k))return h}}}return null}async getOrCreateTargetRoom(){let g=this.getIgnoreInvitesPolicies().target;if(typeof g!="string"&&(g=null),g){const y=this.client.getRoom(g);if(y)return y;g=null}return g=(await this.client.createRoom({name:"Individual Policy Room",preset:n.Preset.PrivateChat})).room_id,await this.withIgnoreInvitesPolicies(y=>{y.target=g}),this.client.getRoom(g)}async getOrCreateSourceRooms(){let g=this.getIgnoreInvitesPolicies().sources,y=!1;Array.isArray(g)||(y=!0,g=[]);let S=g.filter(m=>typeof m=="string").map(m=>this.client.getRoom(m)).filter(m=>!!m);if(S.length!=g.length&&(y=!0),S.length==0){const m=await this.getOrCreateTargetRoom();y=!0,S=[m]}return y&&await this.withIgnoreInvitesPolicies(m=>{m.sources=g}),S}getIgnoreInvitesPolicies(){return this.getPoliciesAndIgnoreInvitesPolicies().ignoreInvitesPolicies}async withIgnoreInvitesPolicies(s){const{policies:g,ignoreInvitesPolicies:y}=this.getPoliciesAndIgnoreInvitesPolicies();s(y),g[o.name]=y,await this.client.setAccountData(i.name,g)}getPoliciesAndIgnoreInvitesPolicies(){let s={};for(const m of[i.name,i.altName]){var g;if(!m)continue;const p=(g=this.client.getAccountData(m))===null||g===void 0?void 0:g.getContent();if(p){s=p;break}}let y={},S=!1;for(const m of[o.name,o.altName]){if(!m)continue;const p=s[m];if(p&&typeof p=="object"){y=p,S=!0;break}}return S||(s[o.name]=y),{policies:s,ignoreInvitesPolicies:y}}}return Vn.IgnoredInvites=f,Vn}var Vb;function or(){if(Vb)return bt;Vb=1;var e=Ae;Object.defineProperty(bt,"__esModule",{value:!0}),bt.UNSTABLE_MSC3852_LAST_SEEN_UA=bt.RoomVersionStability=bt.PendingEventOrdering=bt.MatrixClient=bt.M_AUTHENTICATION=bt.ClientEvent=bt.CRYPTO_ENABLED=void 0,bt.fixNotificationCountOnDecryption=We;var t=e(YV),n=e(Ue),r=Fu,i=Vf(),o=nn(),a=OW(),c=Ju(),f=qf(),v=ZP(),s=re(lt()),g=Tr(),y=Qy(),S=io,m=re(ct),p=rs(),_=w3(),u=Ge(),l=Oa,d=Rr,h=a_(),w=o_(),E=i_(),I=Xn,k=Ea,M=$3(),L=fk(),B=U3(),N=re(ut),G=hi(),D=xe,x=yt,z=B3(),W=Yu(),F=hk(),H=pk(),R=Pa,P=ht,K=Ca(),U=K3(),C=ek(),A=Pt(),T=Sa(),X=gk(),ne=zf(),ae=vk(),pe=en,V=G3(),se=z3(),Q=jf(),j=Yy();const Z=["server","limit","since"];function te(Re){if(typeof WeakMap!="function")return null;var b=new WeakMap,O=new WeakMap;return(te=function($){return $?O:b})(Re)}function re(Re,b){if(!b&&Re&&Re.__esModule)return Re;if(Re===null||typeof Re!="object"&&typeof Re!="function")return{default:Re};var O=te(b);if(O&&O.has(Re))return O.get(Re);var $={},Y=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var ee in Re)if(ee!=="default"&&Object.prototype.hasOwnProperty.call(Re,ee)){var ie=Y?Object.getOwnPropertyDescriptor(Re,ee):null;ie&&(ie.get||ie.set)?Object.defineProperty($,ee,ie):$[ee]=Re[ee]}return $.default=Re,O&&O.set(Re,$),$}function de(Re,b){var O=Object.keys(Re);if(Object.getOwnPropertySymbols){var $=Object.getOwnPropertySymbols(Re);b&&($=$.filter(function(Y){return Object.getOwnPropertyDescriptor(Re,Y).enumerable})),O.push.apply(O,$)}return O}function ge(Re){for(var b=1;b<arguments.length;b++){var O=arguments[b]!=null?arguments[b]:{};b%2?de(Object(O),!0).forEach(function($){(0,n.default)(Re,$,O[$])}):Object.getOwnPropertyDescriptors?Object.defineProperties(Re,Object.getOwnPropertyDescriptors(O)):de(Object(O)).forEach(function($){Object.defineProperty(Re,$,Object.getOwnPropertyDescriptor(O,$))})}return Re}const fe=3e3,he=(0,h.isCryptoAvailable)();bt.CRYPTO_ENABLED=he;const ye=216e5,ce=10*60*1e3,le=new pe.UnstableValue("last_seen_user_agent","org.matrix.msc3852.last_seen_user_agent");bt.UNSTABLE_MSC3852_LAST_SEEN_UA=le;let Se;bt.PendingEventOrdering=Se,function(Re){Re.Chronological="chronological",Re.Detached="detached"}(Se||(bt.PendingEventOrdering=Se={}));let Te;bt.RoomVersionStability=Te,function(Re){Re.Stable="stable",Re.Unstable="unstable"}(Te||(bt.RoomVersionStability=Te={}));var De;(function(Re){Re.MasterKey="master_key",Re.SelfSigningKey="self_signing_key",Re.UserSigningKey="user_signing_key"})(De||(De={}));const je=new pe.UnstableValue("m.authentication","org.matrix.msc2965.authentication");bt.M_AUTHENTICATION=je;const Le="$";let Ve;bt.ClientEvent=Ve,function(Re){Re.Sync="sync",Re.Event="event",Re.ToDeviceEvent="toDeviceEvent",Re.AccountData="accountData",Re.Room="Room",Re.DeleteRoom="deleteRoom",Re.SyncUnexpectedError="sync.unexpectedError",Re.ClientWellKnown="WellKnown.client",Re.ReceivedVoipEvent="received_voip_event",Re.TurnServers="turnServers",Re.TurnServersError="turnServers.error"}(Ve||(bt.ClientEvent=Ve={}));const Be=new pe.UnstableValue("action","org.matrix.msc3824.action");class Ne extends A.TypedEventEmitter{constructor(b){var O;super(),(0,n.default)(this,"reEmitter",new p.TypedReEmitter(this)),(0,n.default)(this,"olmVersion",null),(0,n.default)(this,"usingExternalCrypto",!1),(0,n.default)(this,"store",void 0),(0,n.default)(this,"deviceId",void 0),(0,n.default)(this,"credentials",void 0),(0,n.default)(this,"pickleKey",void 0),(0,n.default)(this,"scheduler",void 0),(0,n.default)(this,"clientRunning",!1),(0,n.default)(this,"timelineSupport",!1),(0,n.default)(this,"urlPreviewCache",{}),(0,n.default)(this,"identityServer",void 0),(0,n.default)(this,"http",void 0),(0,n.default)(this,"crypto",void 0),(0,n.default)(this,"cryptoBackend",void 0),(0,n.default)(this,"cryptoCallbacks",void 0),(0,n.default)(this,"callEventHandler",void 0),(0,n.default)(this,"groupCallEventHandler",void 0),(0,n.default)(this,"supportsCallTransfer",!1),(0,n.default)(this,"forceTURN",!1),(0,n.default)(this,"iceCandidatePoolSize",0),(0,n.default)(this,"idBaseUrl",void 0),(0,n.default)(this,"baseUrl",void 0),(0,n.default)(this,"canSupportVoip",!1),(0,n.default)(this,"peekSync",null),(0,n.default)(this,"isGuestAccount",!1),(0,n.default)(this,"ongoingScrollbacks",{}),(0,n.default)(this,"notifTimelineSet",null),(0,n.default)(this,"cryptoStore",void 0),(0,n.default)(this,"verificationMethods",void 0),(0,n.default)(this,"fallbackICEServerAllowed",!1),(0,n.default)(this,"roomList",void 0),(0,n.default)(this,"syncApi",void 0),(0,n.default)(this,"roomNameGenerator",void 0),(0,n.default)(this,"pushRules",void 0),(0,n.default)(this,"syncLeftRoomsPromise",void 0),(0,n.default)(this,"syncedLeftRooms",!1),(0,n.default)(this,"clientOpts",void 0),(0,n.default)(this,"clientWellKnownIntervalID",void 0),(0,n.default)(this,"canResetTimelineCallback",void 0),(0,n.default)(this,"canSupport",new Map),(0,n.default)(this,"pushProcessor",new y.PushProcessor(this)),(0,n.default)(this,"serverVersionsPromise",void 0),(0,n.default)(this,"cachedCapabilities",void 0),(0,n.default)(this,"clientWellKnown",void 0),(0,n.default)(this,"clientWellKnownPromise",void 0),(0,n.default)(this,"turnServers",[]),(0,n.default)(this,"turnServersExpiry",0),(0,n.default)(this,"checkTurnServersIntervalID",void 0),(0,n.default)(this,"exportedOlmDeviceToImport",void 0),(0,n.default)(this,"txnCtr",0),(0,n.default)(this,"mediaHandler",new U.MediaHandler(this)),(0,n.default)(this,"sessionId",void 0),(0,n.default)(this,"pendingEventEncryption",new Map),(0,n.default)(this,"useE2eForGroupCall",!0),(0,n.default)(this,"toDeviceMessageQueue",void 0),(0,n.default)(this,"ignoredInvites",void 0),(0,n.default)(this,"startCallEventHandler",()=>{this.isInitialSyncComplete()&&(this.callEventHandler.start(),this.groupCallEventHandler.start(),this.off(Ve.Sync,this.startCallEventHandler))}),b.baseUrl=s.ensureNoTrailingSlash(b.baseUrl),b.idBaseUrl=s.ensureNoTrailingSlash(b.idBaseUrl),this.baseUrl=b.baseUrl,this.idBaseUrl=b.idBaseUrl,this.identityServer=b.identityServer,this.usingExternalCrypto=(O=b.usingExternalCrypto)!==null&&O!==void 0?O:!1,this.store=b.store||new a.StubStore,this.deviceId=b.deviceId||null,this.sessionId=(0,W.randomString)(10);const $=b.userId||null;this.credentials={userId:$},this.http=new d.MatrixHttpApi(this,{fetchFn:b.fetchFn,baseUrl:b.baseUrl,idBaseUrl:b.idBaseUrl,accessToken:b.accessToken,prefix:d.ClientPrefix.R0,onlyData:!0,extraParams:b.queryParams,localTimeoutMs:b.localTimeoutMs,useAuthorizationHeader:b.useAuthorizationHeader}),b.deviceToImport?this.deviceId?u.logger.warn("not importing device because device ID is provided to constructor independently of exported data"):this.credentials.userId?u.logger.warn("not importing device because user ID is provided to constructor independently of exported data"):b.deviceToImport.deviceId?(this.deviceId=b.deviceToImport.deviceId,this.credentials.userId=b.deviceToImport.userId,this.exportedOlmDeviceToImport=b.deviceToImport.olmDevice):u.logger.warn("not importing device because no device ID in exported data"):b.pickleKey&&(this.pickleKey=b.pickleKey),this.scheduler=b.scheduler,this.scheduler&&this.scheduler.setProcessFunction(async Y=>{const ee=this.getRoom(Y.getRoomId());Y.status!==o.EventStatus.SENDING&&this.updatePendingEventStatus(ee,Y,o.EventStatus.SENDING);const ie=await this.sendEventHttpRequest(Y);return ee&&ee.updatePendingEvent(Y,o.EventStatus.SENT,ie.event_id),ie}),(0,c.supportsMatrixCall)()&&(this.callEventHandler=new v.CallEventHandler(this),this.groupCallEventHandler=new C.GroupCallEventHandler(this),this.canSupportVoip=!0,this.on(Ve.Sync,this.startCallEventHandler)),this.timelineSupport=Boolean(b.timelineSupport),this.cryptoStore=b.cryptoStore,this.verificationMethods=b.verificationMethods,this.cryptoCallbacks=b.cryptoCallbacks||{},this.forceTURN=b.forceTURN||!1,this.iceCandidatePoolSize=b.iceCandidatePoolSize===void 0?0:b.iceCandidatePoolSize,this.supportsCallTransfer=b.supportsCallTransfer||!1,this.fallbackICEServerAllowed=b.fallbackICEServerAllowed||!1,b.useE2eForGroupCall!==void 0&&(this.useE2eForGroupCall=b.useE2eForGroupCall),this.roomList=new _.RoomList(this.cryptoStore),this.roomNameGenerator=b.roomNameGenerator,this.toDeviceMessageQueue=new V.ToDeviceMessageQueue(this),this.on(o.MatrixEventEvent.Decrypted,Y=>{We(this,Y)}),this.on(G.RoomEvent.Receipt,(Y,ee)=>{if(ee&&this.isRoomEncrypted(ee.roomId)){const ue=Y.getContent();if(!(Object.keys(ue).filter(Fe=>{for(const[Pe,Ee]of Object.entries(ue[Fe]))if(s.isSupportedReceiptType(Pe)&&Ee&&Object.keys(Ee).includes(this.getUserId()))return!0;return!1}).length>0))return;const _e=20,be=ee.getLiveTimeline().getEvents();let Ce=0;for(let Fe=be.length-1;Fe>=0;Fe--){var ie;if(Fe===be.length-_e)return;const Pe=be[Fe];if(ee.hasUserReadEvent(this.getUserId(),Pe.getId()))break;const Ee=this.getPushActionsForEvent(Pe);Ce+=Ee!=null&&(ie=Ee.tweaks)!==null&&ie!==void 0&&ie.highlight?1:0}ee.setUnreadNotificationCount(G.NotificationCountType.Highlight,Ce)}}),this.ignoredInvites=new se.IgnoredInvites(this)}async startClient(b){if(this.clientRunning)return;this.clientRunning=!0,typeof b=="number"&&(b={initialSyncLimit:b});const O=this.getUserId();O&&this.store.storeUser(new I.User(O)),this.canSupportVoip&&(this.checkTurnServersIntervalID=setInterval(()=>{this.checkTurnServers()},ce),this.checkTurnServers()),this.syncApi&&(u.logger.error("Still have sync object whilst not running: stopping old one"),this.syncApi.stop());try{await this.getVersions();const{threads:$,list:Y,fwdPagination:ee}=await this.doesServerSupportThread();ne.Thread.setServerSideSupport($),ne.Thread.setServerSideListSupport(Y),ne.Thread.setServerSideFwdPaginationSupport(ee)}catch($){u.logger.error("Can't fetch server versions, continuing to initialise sync, this will be retried later",$)}this.clientOpts=Object.assign({},b),this.clientOpts.crypto=this.crypto,this.clientOpts.canResetEntireTimeline=$=>this.canResetTimelineCallback?this.canResetTimelineCallback($):!1,this.clientOpts.slidingSync?this.syncApi=new X.SlidingSyncSdk(this.clientOpts.slidingSync,this,this.clientOpts):this.syncApi=new i.SyncApi(this,this.clientOpts),this.syncApi.sync(),this.clientOpts.clientWellKnownPollPeriod!==void 0&&(this.clientWellKnownIntervalID=setInterval(()=>{this.fetchClientWellKnown()},1e3*this.clientOpts.clientWellKnownPollPeriod),this.fetchClientWellKnown()),this.toDeviceMessageQueue.start()}stopClient(){var b,O,$,Y,ee;(b=this.cryptoBackend)===null||b===void 0||b.stop(),this.clientRunning&&(u.logger.log("stopping MatrixClient"),this.clientRunning=!1,(O=this.syncApi)===null||O===void 0||O.stop(),this.syncApi=void 0,($=this.peekSync)===null||$===void 0||$.stopPeeking(),(Y=this.callEventHandler)===null||Y===void 0||Y.stop(),(ee=this.groupCallEventHandler)===null||ee===void 0||ee.stop(),this.callEventHandler=void 0,this.groupCallEventHandler=void 0,$e.clearInterval(this.checkTurnServersIntervalID),this.checkTurnServersIntervalID=void 0,this.clientWellKnownIntervalID!==void 0&&$e.clearInterval(this.clientWellKnownIntervalID),this.toDeviceMessageQueue.stop())}async rehydrateDevice(){if(this.crypto)throw new Error("Cannot rehydrate device after crypto is initialized");if(!this.cryptoCallbacks.getDehydrationKey)return;const b=await this.getDehydratedDevice();if(!b)return;if(!b.device_data||!b.device_id){u.logger.info("no dehydrated device found");return}const O=new $e.Olm.Account;try{const $=b.device_data;if($.algorithm!==L.DEHYDRATION_ALGORITHM){u.logger.warn("Wrong algorithm for dehydrated device");return}u.logger.log("unpickling dehydrated device");const Y=await this.cryptoCallbacks.getDehydrationKey($,ie=>{O.unpickle(new Uint8Array(ie),$.account)});if(O.unpickle(Y,$.account),u.logger.log("unpickled device"),(await this.http.authedRequest(d.Method.Post,"/dehydrated_device/claim",void 0,{device_id:b.device_id},{prefix:"/_matrix/client/unstable/org.matrix.msc2697.v2"})).success){this.deviceId=b.device_id,u.logger.info("using dehydrated device");const ie=this.pickleKey||"DEFAULT_KEY";return this.exportedOlmDeviceToImport={pickledAccount:O.pickle(ie),sessions:[],pickleKey:ie},O.free(),this.deviceId}else{O.free(),u.logger.info("not using dehydrated device");return}}catch($){O.free(),u.logger.warn("could not unpickle",$)}}async getDehydratedDevice(){try{return await this.http.authedRequest(d.Method.Get,"/dehydrated_device",void 0,void 0,{prefix:"/_matrix/client/unstable/org.matrix.msc2697.v2"})}catch(b){u.logger.info("could not get dehydrated device",b);return}}async setDehydrationKey(b,O,$){if(!this.crypto){u.logger.warn("not dehydrating device if crypto is not enabled");return}return this.crypto.dehydrationManager.setKeyAndQueueDehydration(b,O,$)}async createDehydratedDevice(b,O,$){if(!this.crypto){u.logger.warn("not dehydrating device if crypto is not enabled");return}return await this.crypto.dehydrationManager.setKey(b,O,$),this.crypto.dehydrationManager.dehydrateDevice()}async exportDevice(){if(!this.crypto){u.logger.warn("not exporting device if crypto is not enabled");return}return{userId:this.credentials.userId,deviceId:this.deviceId,olmDevice:await this.crypto.olmDevice.export()}}clearStores(){if(this.clientRunning)throw new Error("Cannot clear stores while client is running");const b=[];return b.push(this.store.deleteAllData()),this.cryptoStore&&b.push(this.cryptoStore.deleteAllData()),Promise.all(b).then()}getUserId(){return this.credentials&&this.credentials.userId?this.credentials.userId:null}getDomain(){return this.credentials&&this.credentials.userId?this.credentials.userId.replace(/^.*?:/,""):null}getUserIdLocalpart(){return this.credentials&&this.credentials.userId?this.credentials.userId.split(":")[0].substring(1):null}getDeviceId(){return this.deviceId}getSessionId(){return this.sessionId}supportsVoip(){return this.canSupportVoip}getMediaHandler(){return this.mediaHandler}setForceTURN(b){this.forceTURN=b}setSupportsCallTransfer(b){this.supportsCallTransfer=b}getUseE2eForGroupCall(){return this.useE2eForGroupCall}createCall(b){return(0,c.createNewMatrixCall)(this,b)}async createGroupCall(b,O,$,Y,ee,ie){if(this.getGroupCallForRoom(b))throw new Error(`${b} already has an existing group call`);const ue=this.getRoom(b);if(!ue)throw new Error(`Cannot find room ${b}`);return new K.GroupCall(this,ue,O,$,Y,void 0,ee,ie).create()}waitUntilRoomReadyForGroupCalls(b){return this.groupCallEventHandler.waitUntilRoomReadyForGroupCalls(b)}getGroupCallForRoom(b){return this.groupCallEventHandler.groupCalls.get(b)||null}getSyncState(){var b,O;return(b=(O=this.syncApi)===null||O===void 0?void 0:O.getSyncState())!==null&&b!==void 0?b:null}getSyncStateData(){return this.syncApi?this.syncApi.getSyncStateData():null}isInitialSyncComplete(){const b=this.getSyncState();return b?b===i.SyncState.Prepared||b===i.SyncState.Syncing:!1}isGuest(){return this.isGuestAccount}setGuest(b){this.isGuestAccount=b}getScheduler(){return this.scheduler}retryImmediately(){var b,O;return this.toDeviceMessageQueue.sendQueue(),(b=(O=this.syncApi)===null||O===void 0?void 0:O.retryImmediately())!==null&&b!==void 0?b:!1}getNotifTimelineSet(){return this.notifTimelineSet}setNotifTimelineSet(b){this.notifTimelineSet=b}getCapabilities(b=!1){const O=new Date().getTime();return this.cachedCapabilities&&!b&&O<this.cachedCapabilities.expiration?(u.logger.log("Returning cached capabilities"),Promise.resolve(this.cachedCapabilities.capabilities)):this.http.authedRequest(d.Method.Get,"/capabilities").catch($=>(u.logger.error($),{})).then(($={})=>{const Y=$.capabilities||{},ee=Object.keys(Y).length?ye:6e4+Math.random()*5e3;return this.cachedCapabilities={capabilities:Y,expiration:O+ee},u.logger.log("Caching capabilities: ",Y),Y})}async initCrypto(){if(!(0,h.isCryptoAvailable)())throw new Error("End-to-end encryption not supported in this js-sdk build: did you remember to load the olm library?");if(this.cryptoBackend){u.logger.warn("Attempt to re-initialise e2e encryption on MatrixClient");return}if(!this.cryptoStore)throw new Error("Cannot enable encryption: no cryptoStore provided");u.logger.log("Crypto: Starting up crypto store..."),await this.cryptoStore.startup(),u.logger.log("Crypto: initialising roomlist..."),await this.roomList.init();const b=this.getUserId();if(b===null)throw new Error("Cannot enable encryption on MatrixClient with unknown userId: ensure userId is passed in createClient().");if(this.deviceId===null)throw new Error("Cannot enable encryption on MatrixClient with unknown deviceId: ensure deviceId is passed in createClient().");const O=new h.Crypto(this,b,this.deviceId,this.store,this.cryptoStore,this.roomList,this.verificationMethods);this.reEmitter.reEmit(O,[h.CryptoEvent.KeyBackupFailed,h.CryptoEvent.KeyBackupSessionsRemaining,h.CryptoEvent.RoomKeyRequest,h.CryptoEvent.RoomKeyRequestCancellation,h.CryptoEvent.Warning,h.CryptoEvent.DevicesUpdated,h.CryptoEvent.WillUpdateDevices,h.CryptoEvent.DeviceVerificationChanged,h.CryptoEvent.UserTrustStatusChanged,h.CryptoEvent.KeysChanged]),u.logger.log("Crypto: initialising crypto object..."),await O.init({exportedOlmDevice:this.exportedOlmDeviceToImport,pickleKey:this.pickleKey}),delete this.exportedOlmDeviceToImport,this.olmVersion=h.Crypto.getOlmVersion(),O.registerEventHandlers(this),this.cryptoBackend=this.crypto=O,this.crypto.uploadDeviceKeys().catch($=>{u.logger.error("Error uploading device keys",$)})}isCryptoEnabled(){return!!this.cryptoBackend}getDeviceEd25519Key(){var b,O;return(b=(O=this.crypto)===null||O===void 0?void 0:O.getDeviceEd25519Key())!==null&&b!==void 0?b:null}getDeviceCurve25519Key(){var b,O;return(b=(O=this.crypto)===null||O===void 0?void 0:O.getDeviceCurve25519Key())!==null&&b!==void 0?b:null}async uploadKeys(){u.logger.warn("MatrixClient.uploadKeys is deprecated")}downloadKeys(b,O){return this.crypto?this.crypto.downloadKeys(b,O):Promise.reject(new Error("End-to-end encryption disabled"))}getStoredDevicesForUser(b){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.getStoredDevicesForUser(b)||[]}getStoredDevice(b,O){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.getStoredDevice(b,O)||null}setDeviceVerified(b,O,$=!0){const Y=this.setDeviceVerification(b,O,$,null,null);return b==this.credentials.userId&&this.checkKeyBackup(),Y}setDeviceBlocked(b,O,$=!0){return this.setDeviceVerification(b,O,null,$,null)}setDeviceKnown(b,O,$=!0){return this.setDeviceVerification(b,O,null,null,$)}async setDeviceVerification(b,O,$,Y,ee){if(!this.crypto)throw new Error("End-to-end encryption disabled");await this.crypto.setDeviceVerification(b,O,$,Y,ee)}requestVerificationDM(b,O){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.requestVerificationDM(b,O)}findVerificationRequestDMInProgress(b){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.findVerificationRequestDMInProgress(b)}getVerificationRequestsToDeviceInProgress(b){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.getVerificationRequestsToDeviceInProgress(b)}requestVerification(b,O){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.requestVerification(b,O)}beginKeyVerification(b,O,$){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.beginKeyVerification(b,O,$)}checkSecretStorageKey(b,O){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.checkSecretStorageKey(b,O)}setGlobalBlacklistUnverifiedDevices(b){if(!this.cryptoBackend)throw new Error("End-to-end encryption disabled");return this.cryptoBackend.globalBlacklistUnverifiedDevices=b,b}getGlobalBlacklistUnverifiedDevices(){if(!this.cryptoBackend)throw new Error("End-to-end encryption disabled");return this.cryptoBackend.globalBlacklistUnverifiedDevices}setGlobalErrorOnUnknownDevices(b){if(!this.cryptoBackend)throw new Error("End-to-end encryption disabled");this.cryptoBackend.globalErrorOnUnknownDevices=b}getGlobalErrorOnUnknownDevices(){if(!this.cryptoBackend)throw new Error("End-to-end encryption disabled");return this.cryptoBackend.globalErrorOnUnknownDevices}getCrossSigningId(b=B.CrossSigningKey.Master){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.getCrossSigningId(b)}getStoredCrossSigningForUser(b){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.getStoredCrossSigningForUser(b)}checkUserTrust(b){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.checkUserTrust(b)}checkDeviceTrust(b,O){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.checkDeviceTrust(b,O)}checkIfOwnDeviceCrossSigned(b){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.checkIfOwnDeviceCrossSigned(b)}checkOwnCrossSigningTrust(b){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.checkOwnCrossSigningTrust(b)}checkCrossSigningPrivateKey(b,O){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.checkCrossSigningPrivateKey(b,O)}legacyDeviceVerification(b,O,$){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.legacyDeviceVerification(b,O,$)}prepareToEncrypt(b){if(!this.crypto)throw new Error("End-to-end encryption disabled");this.crypto.prepareToEncrypt(b)}userHasCrossSigningKeys(){if(!this.cryptoBackend)throw new Error("End-to-end encryption disabled");return this.cryptoBackend.userHasCrossSigningKeys()}isCrossSigningReady(){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.isCrossSigningReady()}bootstrapCrossSigning(b){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.bootstrapCrossSigning(b)}getCryptoTrustCrossSignedDevices(){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.getCryptoTrustCrossSignedDevices()}setCryptoTrustCrossSignedDevices(b){if(!this.crypto)throw new Error("End-to-end encryption disabled");this.crypto.setCryptoTrustCrossSignedDevices(b)}countSessionsNeedingBackup(){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.countSessionsNeedingBackup()}getEventEncryptionInfo(b){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.getEventEncryptionInfo(b)}createRecoveryKeyFromPassphrase(b){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.createRecoveryKeyFromPassphrase(b)}isSecretStorageReady(){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.isSecretStorageReady()}bootstrapSecretStorage(b){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.bootstrapSecretStorage(b)}addSecretStorageKey(b,O,$){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.addSecretStorageKey(b,O,$)}hasSecretStorageKey(b){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.hasSecretStorageKey(b)}storeSecret(b,O,$){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.storeSecret(b,O,$)}getSecret(b){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.getSecret(b)}isSecretStored(b){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.isSecretStored(b)}requestSecret(b,O){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.requestSecret(b,O)}getDefaultSecretStorageKeyId(){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.getDefaultSecretStorageKeyId()}setDefaultSecretStorageKeyId(b){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.setDefaultSecretStorageKeyId(b)}checkSecretStoragePrivateKey(b,O){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.checkSecretStoragePrivateKey(b,O)}async getEventSenderDeviceInfo(b){return this.crypto?this.crypto.getEventSenderDeviceInfo(b):null}async isEventSenderVerified(b){const O=await this.getEventSenderDeviceInfo(b);return O?O.isVerified():!1}getOutgoingRoomKeyRequest(b){if(!this.crypto)throw new Error("End-to-End encryption disabled");const O=b.getWireContent(),$={session_id:O.session_id,sender_key:O.sender_key,algorithm:O.algorithm,room_id:b.getRoomId()};return!$.session_id||!$.sender_key||!$.algorithm||!$.room_id?Promise.resolve(null):this.crypto.cryptoStore.getOutgoingRoomKeyRequest($)}cancelAndResendEventRoomKeyRequest(b){if(!this.crypto)throw new Error("End-to-End encryption disabled");return b.cancelAndResendKeyRequest(this.crypto,this.getUserId())}setRoomEncryption(b,O){if(!this.crypto)throw new Error("End-to-End encryption disabled");return this.crypto.setRoomEncryption(b,O)}isRoomEncrypted(b){const O=this.getRoom(b);return O?O.currentState.getStateEvents(D.EventType.RoomEncryption,"")?!0:this.roomList.isRoomEncrypted(b):!1}encryptAndSendToDevices(b,O){if(!this.crypto)throw new Error("End-to-End encryption disabled");return this.crypto.encryptAndSendToDevices(b,O)}forceDiscardSession(b){if(!this.crypto)throw new Error("End-to-End encryption disabled");this.crypto.forceDiscardSession(b)}exportRoomKeys(){return this.crypto?this.crypto.exportRoomKeys():Promise.reject(new Error("End-to-end encryption disabled"))}importRoomKeys(b,O){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.importRoomKeys(b,O)}checkKeyBackup(){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.backupManager.checkKeyBackup()}async getKeyBackupVersion(){let b;try{b=await this.http.authedRequest(d.Method.Get,"/room_keys/version",void 0,void 0,{prefix:d.ClientPrefix.V3})}catch(O){if(O.errcode==="M_NOT_FOUND")return null;throw O}return F.BackupManager.checkBackupVersion(b),b}isKeyBackupTrusted(b){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.backupManager.isKeyBackupTrusted(b)}getKeyBackupEnabled(){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.backupManager.getKeyBackupEnabled()}enableKeyBackup(b){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.backupManager.enableKeyBackup(b)}disableKeyBackup(){if(!this.crypto)throw new Error("End-to-end encryption disabled");this.crypto.backupManager.disableKeyBackup()}async prepareKeyBackupVersion(b,O={secureSecretStorage:!1}){if(!this.crypto)throw new Error("End-to-end encryption disabled");const{algorithm:$,auth_data:Y,recovery_key:ee,privateKey:ie}=await this.crypto.backupManager.prepareKeyBackupVersion(b);return O.secureSecretStorage&&(await this.storeSecret("m.megolm_backup.v1",(0,m.encodeBase64)(ie)),u.logger.info("Key backup private key stored in secret storage")),{algorithm:$,auth_data:Y,recovery_key:ee}}isKeyBackupKeyStored(){return Promise.resolve(this.isSecretStored("m.megolm_backup.v1"))}async createKeyBackupVersion(b){if(!this.crypto)throw new Error("End-to-end encryption disabled");await this.crypto.backupManager.createKeyBackupVersion(b);const O={algorithm:b.algorithm,auth_data:b.auth_data};await this.crypto.signObject(O.auth_data),this.cryptoCallbacks.getCrossSigningKey&&this.crypto.crossSigningInfo.getId()&&await this.crypto.crossSigningInfo.signObject(O.auth_data,"master");const $=await this.http.authedRequest(d.Method.Post,"/room_keys/version",void 0,O,{prefix:d.ClientPrefix.V3});return await this.checkKeyBackup(),this.getKeyBackupEnabled()||u.logger.error("Key backup not usable even though we just created it"),$}async deleteKeyBackupVersion(b){if(!this.crypto)throw new Error("End-to-end encryption disabled");this.crypto.backupManager.version&&this.crypto.backupManager.disableKeyBackup();const O=s.encodeUri("/room_keys/version/$version",{$version:b});await this.http.authedRequest(d.Method.Delete,O,void 0,void 0,{prefix:d.ClientPrefix.V3})}makeKeyBackupPath(b,O,$){let Y;return O!==void 0?Y=s.encodeUri("/room_keys/keys/$roomId/$sessionId",{$roomId:b,$sessionId:O}):b!==void 0?Y=s.encodeUri("/room_keys/keys/$roomId",{$roomId:b}):Y="/room_keys/keys",{path:Y,queryData:$===void 0?void 0:{version:$}}}async sendKeyBackup(b,O,$,Y){if(!this.crypto)throw new Error("End-to-end encryption disabled");const ee=this.makeKeyBackupPath(b,O,$);await this.http.authedRequest(d.Method.Put,ee.path,ee.queryData,Y,{prefix:d.ClientPrefix.V3})}async scheduleAllGroupSessionsForBackup(){if(!this.crypto)throw new Error("End-to-end encryption disabled");await this.crypto.backupManager.scheduleAllGroupSessionsForBackup()}flagAllGroupSessionsForBackup(){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.backupManager.flagAllGroupSessionsForBackup()}isValidRecoveryKey(b){try{return(0,w.decodeRecoveryKey)(b),!0}catch{return!1}}keyBackupKeyFromPassword(b,O){return(0,E.keyFromAuthData)(O.auth_data,b)}keyBackupKeyFromRecoveryKey(b){return(0,w.decodeRecoveryKey)(b)}async restoreKeyBackupWithPassword(b,O,$,Y,ee){const ie=await(0,E.keyFromAuthData)(Y.auth_data,b);return this.restoreKeyBackup(ie,O,$,Y,ee)}async restoreKeyBackupWithSecretStorage(b,O,$,Y){if(!this.crypto)throw new Error("End-to-end encryption disabled");const ee=await this.getSecret("m.megolm_backup.v1"),ie=(0,h.fixBackupKey)(ee);if(ie){const ve=await this.crypto.getSecretStorageKey();await this.storeSecret("m.megolm_backup.v1",ie,[ve[0]])}const ue=(0,m.decodeBase64)(ie||ee);return this.restoreKeyBackup(ue,O,$,b,Y)}restoreKeyBackupWithRecoveryKey(b,O,$,Y,ee){const ie=(0,w.decodeRecoveryKey)(b);return this.restoreKeyBackup(ie,O,$,Y,ee)}async restoreKeyBackupWithCache(b,O,$,Y){if(!this.crypto)throw new Error("End-to-end encryption disabled");const ee=await this.crypto.getSessionBackupPrivateKey();if(!ee)throw new Error("Couldn't get key");return this.restoreKeyBackup(ee,b,O,$,Y)}async restoreKeyBackup(b,O,$,Y,ee){const ie=ee==null?void 0:ee.cacheCompleteCallback,ue=ee==null?void 0:ee.progressCallback;if(!this.crypto)throw new Error("End-to-end encryption disabled");let ve=0,_e=[];const be=this.makeKeyBackupPath(O,$,Y.version),Ce=await F.BackupManager.makeAlgorithm(Y,async()=>b),Fe=Ce.untrusted;try{if(!await Ce.keyMatches(b))return Promise.reject(new d.MatrixError({errcode:Ne.RESTORE_BACKUP_ERROR_BAD_KEY}));this.crypto.storeSessionBackupPrivateKey(b).catch(Ee=>{u.logger.warn("Error caching session backup key:",Ee)}).then(ie),ue&&ue({stage:"fetch"});const Pe=await this.http.authedRequest(d.Method.Get,be.path,be.queryData,void 0,{prefix:d.ClientPrefix.V3});if(Pe.rooms){const Ee=Pe.rooms;for(const[qe,ke]of Object.entries(Ee)){if(!ke.sessions)continue;ve+=Object.keys(ke.sessions).length;const Me=await Ce.decryptSessions(ke.sessions);for(const tt of Me)tt.room_id=qe,_e.push(tt)}}else if(Pe.sessions){const Ee=Pe.sessions;ve=Object.keys(Ee).length,_e=await Ce.decryptSessions(Ee);for(const qe of _e)qe.room_id=O}else{ve=1;try{const[Ee]=await Ce.decryptSessions({[$]:Pe});Ee.room_id=O,Ee.session_id=$,_e.push(Ee)}catch(Ee){u.logger.log("Failed to decrypt megolm session from backup",Ee)}}}finally{Ce.free()}return await this.importRoomKeys(_e,{progressCallback:ue,untrusted:Fe,source:"backup"}),await this.checkKeyBackup(),{total:ve,imported:_e.length}}async deleteKeysFromBackup(b,O,$){if(!this.crypto)throw new Error("End-to-end encryption disabled");const Y=this.makeKeyBackupPath(b,O,$);await this.http.authedRequest(d.Method.Delete,Y.path,Y.queryData,void 0,{prefix:d.ClientPrefix.V3})}async sendSharedHistoryKeys(b,O){if(!this.crypto)throw new Error("End-to-end encryption disabled");const $=this.roomList.getRoomEncryption(b);if(!$){u.logger.error("Unknown room.  Not sharing decryption keys");return}const Y=await this.crypto.downloadKeys(O),ee={};for(const[ue,ve]of Object.entries(Y))ee[ue]=Object.values(ve);const ie=this.crypto.getRoomDecryptor(b,$.algorithm);ie.sendSharedHistoryInboundSessions?await ie.sendSharedHistoryInboundSessions(ee):u.logger.warn("Algorithm does not support sharing previous keys",$.algorithm)}getMediaConfig(){return this.http.authedRequest(d.Method.Get,"/config",void 0,void 0,{prefix:d.MediaPrefix.R0})}getRoom(b){return b?this.store.getRoom(b):null}getRooms(){return this.store.getRooms()}getVisibleRooms(){const b=this.store.getRooms(),O=new Set;for(const $ of b){const Y=$.currentState.getStateEvents(D.EventType.RoomCreate,"");if(Y){const ee=Y.getContent().predecessor;ee&&ee.room_id&&O.add(ee.room_id)}}return b.filter($=>!($.currentState.getStateEvents(D.EventType.RoomTombstone,"")&&O.has($.roomId)))}getUser(b){return this.store.getUser(b)}getUsers(){return this.store.getUsers()}setAccountData(b,O){const $=s.encodeUri("/user/$userId/account_data/$type",{$userId:this.credentials.userId,$type:b});return(0,d.retryNetworkOperation)(5,()=>this.http.authedRequest(d.Method.Put,$,void 0,O))}getAccountData(b){return this.store.getAccountData(b)}async getAccountDataFromServer(b){if(this.isInitialSyncComplete()){const Y=this.store.getAccountData(b);return Y?Y.getContent():null}const O=s.encodeUri("/user/$userId/account_data/$type",{$userId:this.credentials.userId,$type:b});try{return await this.http.authedRequest(d.Method.Get,O)}catch(Y){var $;if((($=Y.data)===null||$===void 0?void 0:$.errcode)==="M_NOT_FOUND")return null;throw Y}}getIgnoredUsers(){const b=this.getAccountData("m.ignored_user_list");return!b||!b.getContent()||!b.getContent().ignored_users?[]:Object.keys(b.getContent().ignored_users)}setIgnoredUsers(b){const O={ignored_users:{}};return b.forEach($=>{O.ignored_users[$]={}}),this.setAccountData("m.ignored_user_list",O)}isUserIgnored(b){return this.getIgnoredUsers().includes(b)}async joinRoom(b,O={}){O.syncRoom===void 0&&(O.syncRoom=!0);const $=this.getRoom(b);if($!=null&&$.hasMembershipState(this.credentials.userId,"join"))return Promise.resolve($);let Y=Promise.resolve();if(O.inviteSignUrl){const ie=new URL(O.inviteSignUrl);ie.searchParams.set("mxid",this.credentials.userId),Y=this.http.requestOtherUrl(d.Method.Post,ie)}const ee={};O.viaServers&&(ee.server_name=O.viaServers);try{const ie={},ue=await Y;ue&&(ie.third_party_signed=ue);const ve=s.encodeUri("/join/$roomid",{$roomid:b}),be=(await this.http.authedRequest(d.Method.Post,ve,ee,ie)).room_id,Fe=new i.SyncApi(this,this.clientOpts).createRoom(be);return O.syncRoom,Fe}catch(ie){throw ie}}resendEvent(b,O){return this.toDeviceMessageQueue.sendQueue(),this.updatePendingEventStatus(O,b,o.EventStatus.SENDING),this.encryptAndSendEvent(O,b)}cancelPendingEvent(b){if(![o.EventStatus.QUEUED,o.EventStatus.NOT_SENT,o.EventStatus.ENCRYPTING].includes(b.status))throw new Error("cannot cancel an event with status "+b.status);b.status===o.EventStatus.ENCRYPTING?this.pendingEventEncryption.delete(b.getId()):this.scheduler&&b.status===o.EventStatus.QUEUED&&this.scheduler.removeEventFromQueue(b);const O=this.getRoom(b.getRoomId());this.updatePendingEventStatus(O,b,o.EventStatus.CANCELLED)}setRoomName(b,O){return this.sendStateEvent(b,D.EventType.RoomName,{name:O})}setRoomTopic(b,O,$){const Y=N.makeTopicContent(O,$);return this.sendStateEvent(b,D.EventType.RoomTopic,Y)}getRoomTags(b){const O=s.encodeUri("/user/$userId/rooms/$roomId/tags",{$userId:this.credentials.userId,$roomId:b});return this.http.authedRequest(d.Method.Get,O)}setRoomTag(b,O,$){const Y=s.encodeUri("/user/$userId/rooms/$roomId/tags/$tag",{$userId:this.credentials.userId,$roomId:b,$tag:O});return this.http.authedRequest(d.Method.Put,Y,void 0,$)}deleteRoomTag(b,O){const $=s.encodeUri("/user/$userId/rooms/$roomId/tags/$tag",{$userId:this.credentials.userId,$roomId:b,$tag:O});return this.http.authedRequest(d.Method.Delete,$)}setRoomAccountData(b,O,$){const Y=s.encodeUri("/user/$userId/rooms/$roomId/account_data/$type",{$userId:this.credentials.userId,$roomId:b,$type:O});return this.http.authedRequest(d.Method.Put,Y,void 0,$)}setPowerLevel(b,O,$,Y){let ee={users:{}};if(Y.getType()===D.EventType.RoomPowerLevels&&(ee=s.deepCopy(Y.getContent())),Array.isArray(O))for(const ue of O)ee.users[ue]=$;else ee.users[O]=$;const ie=s.encodeUri("/rooms/$roomId/state/m.room.power_levels",{$roomId:b});return this.http.authedRequest(d.Method.Put,ie,void 0,ee)}async unstable_createLiveBeacon(b,O){return this.unstable_setLiveBeacon(b,O)}async unstable_setLiveBeacon(b,O){return this.sendStateEvent(b,ae.M_BEACON_INFO.name,O,this.getUserId())}sendEvent(b,O,$,Y,ee){var ie;let ue,ve,_e,be;if(!(O!=null&&O.startsWith(Le))&&O!==null?(be=Y,_e=$,ve=O,ue=null):(be=ee,_e=Y,ve=$,ue=O),ue&&!((ie=_e["m.relates_to"])!==null&&ie!==void 0&&ie.rel_type)){var Ce,Fe;const qe=!!((Ce=_e["m.relates_to"])!==null&&Ce!==void 0&&Ce["m.in_reply_to"]);_e["m.relates_to"]=ge(ge({},_e["m.relates_to"]),{},{rel_type:ne.THREAD_RELATION_TYPE.name,event_id:ue,is_falling_back:!qe});const ke=(Fe=this.getRoom(b))===null||Fe===void 0?void 0:Fe.getThread(ue);if(ke&&!qe){var Pe,Ee;_e["m.relates_to"]["m.in_reply_to"]={event_id:(Pe=(Ee=ke.lastReply(Me=>Me.isRelation(ne.THREAD_RELATION_TYPE.name)&&!Me.status))===null||Ee===void 0?void 0:Ee.getId())!==null&&Pe!==void 0?Pe:ue}}}return this.sendCompleteEvent(b,ue,{type:ve,content:_e},be)}sendCompleteEvent(b,O,$,Y){Y||(Y=this.makeTxnId());const ee=new o.MatrixEvent(Object.assign($,{event_id:"~"+b+":"+Y,user_id:this.credentials.userId,sender:this.credentials.userId,room_id:b,origin_server_ts:new Date().getTime()})),ie=this.getRoom(b),ue=O?ie==null?void 0:ie.getThread(O):void 0;ue&&ee.setThread(ue),this.reEmitter.reEmit(ee,[o.MatrixEventEvent.Replaced,o.MatrixEventEvent.VisibilityChange]),ie==null||ie.reEmitter.reEmit(ee,[o.MatrixEventEvent.BeforeRedaction]);const ve=ee.getAssociatedId();if(ve!=null&&ve.startsWith("~")){const be=ie==null?void 0:ie.getPendingEvents().find(Ce=>Ce.getId()===ve);be==null||be.once(o.MatrixEventEvent.LocalEventIdReplaced,()=>{ee.updateAssociatedId(be.getId())})}const _e=ee.getType();return u.logger.log(`sendEvent of type ${_e} in ${b} with txnId ${Y}`),ee.setTxnId(Y),ee.setStatus(o.EventStatus.SENDING),ie==null||ie.addPendingEvent(ee,Y),ee.status===o.EventStatus.NOT_SENT?Promise.reject(new Error("Event blocked by other events not yet sent")):this.encryptAndSendEvent(ie,ee)}encryptAndSendEvent(b,O){let $=!1;return Promise.resolve().then(()=>{const Y=this.encryptEventIfNeeded(O,b??void 0);return Y?(this.pendingEventEncryption.set(O.getId(),Y),this.updatePendingEventStatus(b,O,o.EventStatus.ENCRYPTING),Y.then(()=>{if(!this.pendingEventEncryption.has(O.getId())){$=!0;return}this.updatePendingEventStatus(b,O,o.EventStatus.SENDING)})):null}).then(()=>{if($)return{};let Y=null;return this.scheduler&&(Y=this.scheduler.queueEvent(O),Y&&this.scheduler.getQueueForEvent(O).length>1&&this.updatePendingEventStatus(b,O,o.EventStatus.QUEUED)),Y||(Y=this.sendEventHttpRequest(O),b&&(Y=Y.then(ee=>(b.updatePendingEvent(O,o.EventStatus.SENT,ee.event_id),ee)))),Y}).catch(Y=>{u.logger.error("Error sending event",Y.stack||Y);try{O.error=Y,this.updatePendingEventStatus(b,O,o.EventStatus.NOT_SENT)}catch(ee){u.logger.error("Exception in error handler!",ee.stack||Y)}throw Y instanceof d.MatrixError&&(Y.event=O),Y})}encryptEventIfNeeded(b,O){if(b.isEncrypted()||b.isRedaction()||!this.isRoomEncrypted(b.getRoomId())||!this.crypto&&this.usingExternalCrypto||b.getType()===D.EventType.Reaction)return null;if(!this.crypto)throw new Error("This room is configured to use encryption, but your client does not support encryption.");return this.crypto.encryptEvent(b,O)}getEncryptedIfNeededEventType(b,O){return O===D.EventType.Reaction?O:this.isRoomEncrypted(b)?D.EventType.RoomMessageEncrypted:O}updatePendingEventStatus(b,O,$){b?b.updatePendingEvent(O,$):O.setStatus($)}sendEventHttpRequest(b){let O=b.getTxnId();O||(O=this.makeTxnId(),b.setTxnId(O));const $={$roomId:b.getRoomId(),$eventType:b.getWireType(),$stateKey:b.getStateKey(),$txnId:O};let Y;if(b.isState()){let ee="/rooms/$roomId/state/$eventType";b.getStateKey()&&b.getStateKey().length>0&&(ee="/rooms/$roomId/state/$eventType/$stateKey"),Y=s.encodeUri(ee,$)}else if(b.isRedaction()){const ee="/rooms/$roomId/redact/$redactsEventId/$txnId";Y=s.encodeUri(ee,ge({$redactsEventId:b.event.redacts},$))}else Y=s.encodeUri("/rooms/$roomId/send/$eventType/$txnId",$);return this.http.authedRequest(d.Method.Put,Y,void 0,b.getWireContent()).then(ee=>(u.logger.log(`Event sent to ${b.getRoomId()} with event id ${ee.event_id}`),ee))}redactEvent(b,O,$,Y,ee){var ie,ue;(ie=$)!==null&&ie!==void 0&&ie.startsWith(Le)||(ee=Y,Y=$,$=O,O=null);const ve=(ue=ee)===null||ue===void 0?void 0:ue.reason;return this.sendCompleteEvent(b,O,{type:D.EventType.RoomRedaction,content:{reason:ve},redacts:$},Y)}sendMessage(b,O,$,Y){typeof O!="string"&&O!==null&&(Y=$,$=O,O=null);let ee=D.EventType.RoomMessage,ie=$;const ue=(_e={},be=!0)=>{let Ce;if(_e.msgtype===D.MsgType.Text?Ce=r.MessageEvent.from(_e.body,_e.formatted_body).serialize():_e.msgtype===D.MsgType.Emote?Ce=r.EmoteEvent.from(_e.body,_e.formatted_body).serialize():_e.msgtype===D.MsgType.Notice&&(Ce=r.NoticeEvent.from(_e.body,_e.formatted_body).serialize()),Ce&&_e["m.new_content"]&&be){const Fe=ue(_e["m.new_content"],!1);Fe&&(Ce.content["m.new_content"]=Fe.content)}if(Ce)for(const[Fe,Pe]of Object.entries(_e))Ce.content.hasOwnProperty(Fe)||(Ce.content[Fe]=Pe);return Ce},ve=ue(ie);return ve&&(ee=ve.type,ie=ve.content),this.sendEvent(b,O,ee,ie,Y)}sendTextMessage(b,O,$,Y){var ee;!((ee=O)!==null&&ee!==void 0&&ee.startsWith(Le))&&O!==null&&(Y=$,$=O,O=null);const ie=N.makeTextMessage($);return this.sendMessage(b,O,ie,Y)}sendNotice(b,O,$,Y){var ee;!((ee=O)!==null&&ee!==void 0&&ee.startsWith(Le))&&O!==null&&(Y=$,$=O,O=null);const ie=N.makeNotice($);return this.sendMessage(b,O,ie,Y)}sendEmoteMessage(b,O,$,Y){var ee;!((ee=O)!==null&&ee!==void 0&&ee.startsWith(Le))&&O!==null&&(Y=$,$=O,O=null);const ie=N.makeEmoteMessage($);return this.sendMessage(b,O,ie,Y)}sendImageMessage(b,O,$,Y,ee="Image"){var ie;!((ie=O)!==null&&ie!==void 0&&ie.startsWith(Le))&&O!==null&&(ee=Y||"Image",Y=$,$=O,O=null);const ue={msgtype:D.MsgType.Image,url:$,info:Y,body:ee};return this.sendMessage(b,O,ue)}sendStickerMessage(b,O,$,Y,ee="Sticker"){var ie;!((ie=O)!==null&&ie!==void 0&&ie.startsWith(Le))&&O!==null&&(ee=Y||"Sticker",Y=$,$=O,O=null);const ue={url:$,info:Y,body:ee};return this.sendEvent(b,O,D.EventType.Sticker,ue)}sendHtmlMessage(b,O,$,Y){var ee;!((ee=O)!==null&&ee!==void 0&&ee.startsWith(Le))&&O!==null&&(Y=$,$=O,O=null);const ie=N.makeHtmlMessage($,Y);return this.sendMessage(b,O,ie)}sendHtmlNotice(b,O,$,Y){var ee;!((ee=O)!==null&&ee!==void 0&&ee.startsWith(Le))&&O!==null&&(Y=$,$=O,O=null);const ie=N.makeHtmlNotice($,Y);return this.sendMessage(b,O,ie)}sendHtmlEmote(b,O,$,Y){var ee;!((ee=O)!==null&&ee!==void 0&&ee.startsWith(Le))&&O!==null&&(Y=$,$=O,O=null);const ie=N.makeHtmlEmote($,Y);return this.sendMessage(b,O,ie)}async sendReceipt(b,O,$,Y=!1){if(this.isGuest())return Promise.resolve({});const ee=s.encodeUri("/rooms/$roomId/receipt/$receiptType/$eventId",{$roomId:b.getRoomId(),$receiptType:O,$eventId:b.getId()});if(this.canSupport.get(j.Feature.ThreadUnreadNotifications)!==j.ServerSupport.Unsupported&&!Y){const _e=!!b.threadRootId;$=ge(ge({},$),{},{thread_id:_e?b.threadRootId:T.MAIN_ROOM_TIMELINE})}const ue=this.http.authedRequest(d.Method.Post,ee,void 0,$||{}),ve=this.getRoom(b.getRoomId());return ve&&this.credentials.userId&&ve.addLocalEchoReceipt(this.credentials.userId,b,O),ue}async sendReadReceipt(b,O=T.ReceiptType.Read,$=!1){if(!b)return;const Y=b.getId(),ee=this.getRoom(b.getRoomId());if(ee!=null&&ee.hasPendingEvent(Y))throw new Error(`Cannot set read receipt to a pending event (${Y})`);return this.sendReceipt(b,O,{},$)}async setRoomReadMarkers(b,O,$,Y){const ee=this.getRoom(b);if(ee&&ee.hasPendingEvent(O))throw new Error(`Cannot set read marker to a pending event (${O})`);let ie;if($){if(ie=$.getId(),ee!=null&&ee.hasPendingEvent(ie))throw new Error(`Cannot set read receipt to a pending event (${ie})`);ee==null||ee.addLocalEchoReceipt(this.credentials.userId,$,T.ReceiptType.Read)}let ue;if(Y){if(ue=Y.getId(),ee!=null&&ee.hasPendingEvent(ue))throw new Error(`Cannot set read receipt to a pending event (${ue})`);ee==null||ee.addLocalEchoReceipt(this.credentials.userId,Y,T.ReceiptType.ReadPrivate)}return await this.setRoomReadMarkersHttpRequest(b,O,ie,ue)}getUrlPreview(b,O){O=Math.floor(O/6e4)*6e4;const $=new URL(b);$.hash="",b=$.toString();const Y=O+"_"+b,ee=this.urlPreviewCache[Y];if(ee)return ee;const ie=this.http.authedRequest(d.Method.Get,"/preview_url",{url:b,ts:O.toString()},void 0,{prefix:d.MediaPrefix.R0});return this.urlPreviewCache[Y]=ie,ie}sendTyping(b,O,$){if(this.isGuest())return Promise.resolve({});const Y=s.encodeUri("/rooms/$roomId/typing/$userId",{$roomId:b,$userId:this.getUserId()}),ee={typing:O};return O&&(ee.timeout=$||2e4),this.http.authedRequest(d.Method.Put,Y,void 0,ee)}getRoomUpgradeHistory(b,O=!1){let $=this.getRoom(b);if(!$)return[];const Y=[$];let ee=$.currentState.getStateEvents(D.EventType.RoomCreate,"");for(;ee;){const ue=ee.getContent().predecessor;if(ue&&ue.room_id){const ve=this.getRoom(ue.room_id);if(!ve)break;if(O){const _e=ve.currentState.getStateEvents(D.EventType.RoomTombstone,"");if(!_e||_e.getContent().replacement_room!==ve.roomId)break}Y.splice(0,0,ve),ee=ve.currentState.getStateEvents(D.EventType.RoomCreate,"")}else break}let ie=$.currentState.getStateEvents(D.EventType.RoomTombstone,"");for(;ie;){const ue=this.getRoom(ie.getContent().replacement_room);if(!ue||ue.roomId===$.roomId||O&&(ee=ue.currentState.getStateEvents(D.EventType.RoomCreate,""),!ee||!ee.getContent().predecessor||ee.getContent().predecessor.room_id!==$.roomId))break;if(Y.push(ue),new Set(Y.map(_e=>_e.roomId)).size<Y.length)return Y.slice(0,Y.length-1);$=ue,ie=$.currentState.getStateEvents(D.EventType.RoomTombstone,"")}return Y}invite(b,O,$){return this.membershipChange(b,O,"invite",$)}inviteByEmail(b,O){return this.inviteByThreePid(b,"email",O)}async inviteByThreePid(b,O,$){var Y;const ee=s.encodeUri("/rooms/$roomId/invite",{$roomId:b}),ie=this.getIdentityServerUrl(!0);if(!ie)return Promise.reject(new d.MatrixError({error:"No supplied identity server URL",errcode:"ORG.MATRIX.JSSDK_MISSING_PARAM"}));const ue={id_server:ie,medium:O,address:$};if((Y=this.identityServer)!==null&&Y!==void 0&&Y.getAccessToken&&await this.doesServerAcceptIdentityAccessToken()){const ve=await this.identityServer.getAccessToken();ve&&(ue.id_access_token=ve)}return this.http.authedRequest(d.Method.Post,ee,void 0,ue)}leave(b){return this.membershipChange(b,void 0,"leave")}leaveRoomChain(b,O=!0){const $=this.getRoomUpgradeHistory(b);let Y=$;if(!O){Y=[];for(const ve of $)if(Y.push(ve),ve.roomId===b)break}const ee={},ie=[],ue=ve=>this.leave(ve).then(()=>{delete ee[ve]}).catch(_e=>{ee[ve]=_e});for(const ve of Y)ie.push(ue(ve.roomId));return Promise.all(ie).then(()=>ee)}ban(b,O,$){return this.membershipChange(b,O,"ban",$)}forget(b,O=!0){const $=this.membershipChange(b,void 0,"forget");return O?$.then(Y=>(this.store.removeRoom(b),this.emit(Ve.DeleteRoom,b),Y)):$}unban(b,O){const $=s.encodeUri("/rooms/$roomId/unban",{$roomId:b}),Y={user_id:O};return this.http.authedRequest(d.Method.Post,$,void 0,Y)}kick(b,O,$){const Y=s.encodeUri("/rooms/$roomId/kick",{$roomId:b}),ee={user_id:O,reason:$};return this.http.authedRequest(d.Method.Post,Y,void 0,ee)}membershipChange(b,O,$,Y){const ee=s.encodeUri("/rooms/$room_id/$membership",{$room_id:b,$membership:$});return this.http.authedRequest(d.Method.Post,ee,void 0,{user_id:O,reason:Y})}getPushActionsForEvent(b,O=!1){return(!b.getPushActions()||O)&&b.setPushActions(this.pushProcessor.actionsForEvent(b)),b.getPushActions()}setProfileInfo(b,O){const $=s.encodeUri("/profile/$userId/$info",{$userId:this.credentials.userId,$info:b});return this.http.authedRequest(d.Method.Put,$,void 0,O)}async setDisplayName(b){const O=await this.setProfileInfo("displayname",{displayname:b}),$=this.getUser(this.getUserId());return $&&($.displayName=b,$.emit(I.UserEvent.DisplayName,$.events.presence,$)),O}async setAvatarUrl(b){const O=await this.setProfileInfo("avatar_url",{avatar_url:b}),$=this.getUser(this.getUserId());return $&&($.avatarUrl=b,$.emit(I.UserEvent.AvatarUrl,$.events.presence,$)),O}mxcUrlToHttp(b,O,$,Y,ee){return(0,k.getHttpUriForMxc)(this.baseUrl,b,O,$,Y,ee)}async setPresence(b){const O=s.encodeUri("/presence/$userId/status",{$userId:this.credentials.userId});if(["offline","online","unavailable"].indexOf(b.presence)===-1)throw new Error("Bad presence value: "+b.presence);await this.http.authedRequest(d.Method.Put,O,void 0,b)}getPresence(b){const O=s.encodeUri("/presence/$userId/status",{$userId:b});return this.http.authedRequest(d.Method.Get,O)}scrollback(b,O=30){let $=0,Y=this.ongoingScrollbacks[b.roomId]||{};if(Y.promise)return Y.promise;if(Y.errorTs){const ue=Date.now()-Y.errorTs;$=Math.max(fe-ue,0)}if(b.oldState.paginationToken===null)return Promise.resolve(b);const ee=this.store.scrollback(b,O).length;if(ee===O)return Promise.resolve(b);O=O-ee;const ie=new Promise((ue,ve)=>{(0,s.sleep)($).then(()=>this.createMessagesRequest(b.roomId,b.oldState.paginationToken,O,g.Direction.Backward)).then(_e=>{var be,Ce;const Fe=_e.chunk.map(this.getEventMapper());if(_e.state){const qe=_e.state.map(this.getEventMapper());b.currentState.setUnknownStateEvents(qe)}const[Pe,Ee]=b.partitionThreadedEvents(Fe);this.processBeaconEvents(b,Pe),b.addEventsToTimeline(Pe,!0,b.getLiveTimeline()),this.processThreadEvents(b,Ee,!0),b.oldState.paginationToken=(be=_e.end)!==null&&be!==void 0?be:null,_e.chunk.length===0&&(b.oldState.paginationToken=null),this.store.storeEvents(b,Fe,(Ce=_e.end)!==null&&Ce!==void 0?Ce:null,!0),delete this.ongoingScrollbacks[b.roomId],ue(b)}).catch(_e=>{this.ongoingScrollbacks[b.roomId]={errorTs:Date.now()},ve(_e)})});return Y={promise:ie},this.ongoingScrollbacks[b.roomId]=Y,ie}getEventMapper(b){return(0,z.eventMapperFor)(this,b||{})}async getEventTimeline(b,O){var $,Y,ee,ie;if(!this.timelineSupport)throw new Error("timeline support is disabled. Set the 'timelineSupport' parameter to true when creating MatrixClient to enable it.");if(!(b!=null&&b.room))throw new Error("getEventTimeline only supports room timelines");if(b.getTimelineForEvent(O))return b.getTimelineForEvent(O);if(b.thread&&this.supportsExperimentalThreads())return this.getThreadTimeline(b,O);const ue=s.encodeUri("/rooms/$roomId/context/$eventId",{$roomId:b.room.roomId,$eventId:O});let ve;($=this.clientOpts)!==null&&$!==void 0&&$.lazyLoadMembers&&(ve={filter:JSON.stringify(f.Filter.LAZY_LOADING_MESSAGES_FILTER)});const _e=await this.http.authedRequest(d.Method.Get,ue,ve);if(!_e.event)throw new Error("'event' not in '/context' result - homeserver too old?");if(b.getTimelineForEvent(O))return b.getTimelineForEvent(O);const be=this.getEventMapper(),Ce=be(_e.event);if(Ce.isRelation(ne.THREAD_RELATION_TYPE.name)){u.logger.warn("Tried loading a regular timeline at the position of a thread event");return}const Fe=[..._e.events_after.reverse().map(be),Ce,..._e.events_before.map(be)];let Pe=b.getTimelineForEvent(Fe[0].getId());Pe?Pe.getState(g.EventTimeline.BACKWARDS).setUnknownStateEvents(_e.state.map(be)):(Pe=b.addTimeline(),Pe.initialiseState(_e.state.map(be)),Pe.getState(g.EventTimeline.FORWARDS).paginationToken=_e.end);const[Ee,qe]=b.room.partitionThreadedEvents(Fe);return b.addEventsToTimeline(Ee,!0,Pe,_e.start),this.processThreadEvents(b.room,qe,!0),this.processBeaconEvents(b.room,Ee),(Y=(ee=b.getTimelineForEvent(O))!==null&&ee!==void 0?ee:(ie=b.room.findThreadForEvent(Ce))===null||ie===void 0?void 0:ie.liveTimeline)!==null&&Y!==void 0?Y:Pe}async getThreadTimeline(b,O){var $;if(!this.supportsExperimentalThreads())throw new Error("could not get thread timeline: no client support");if(!b.room)throw new Error("could not get thread timeline: not a room timeline");if(!b.thread)throw new Error("could not get thread timeline: not a thread timeline");const Y=s.encodeUri("/rooms/$roomId/context/$eventId",{$roomId:b.room.roomId,$eventId:O}),ee={limit:"0"};($=this.clientOpts)!==null&&$!==void 0&&$.lazyLoadMembers&&(ee.filter=JSON.stringify(f.Filter.LAZY_LOADING_MESSAGES_FILTER));const ie=await this.http.authedRequest(d.Method.Get,Y,ee),ue=this.getEventMapper(),ve=ue(ie.event);if(b.canContain(ve)&&ne.Thread.hasServerSideSupport)if(ne.Thread.hasServerSideFwdPaginationSupport){var _e,be,Ce;if(!b.thread)throw new Error("could not get thread timeline: not a thread timeline");const ke=b.thread,Me=await this.fetchRelations(b.room.roomId,ke.id,ne.THREAD_RELATION_TYPE.name,null,{dir:g.Direction.Backward,from:ie.start}),tt=await this.fetchRelations(b.room.roomId,ke.id,ne.THREAD_RELATION_TYPE.name,null,{dir:g.Direction.Forward,from:ie.end}),Ye=[...tt.chunk.reverse().map(ue),ve,...Me.chunk.map(ue)];for(const ze of Ye){var Fe;await((Fe=b.thread)===null||Fe===void 0?void 0:Fe.processEvent(ze))}let Xe=b.getTimelineForEvent(ve.getId());if(Xe?Xe.getState(g.EventTimeline.BACKWARDS).setUnknownStateEvents(ie.state.map(ue)):(Xe=b.addTimeline(),Xe.initialiseState(ie.state.map(ue))),b.addEventsToTimeline(Ye,!0,Xe,tt.next_batch),!Me.next_batch){const ze=await this.fetchRoomEvent(b.room.roomId,ke.id);b.addEventsToTimeline([ue(ze)],!0,Xe,null)}return Xe.setPaginationToken((_e=Me.next_batch)!==null&&_e!==void 0?_e:null,g.Direction.Backward),Xe.setPaginationToken((be=tt.next_batch)!==null&&be!==void 0?be:null,g.Direction.Forward),this.processBeaconEvents(b.room,Ye),(Ce=b.getTimelineForEvent(O))!==null&&Ce!==void 0?Ce:Xe}else{var Pe;const ke=b.thread,Me=await this.fetchRelations(b.room.roomId,ke.id,ne.THREAD_RELATION_TYPE.name,null,{dir:g.Direction.Backward,from:ie.start}),tt=[];let Ye=ie.end;for(;Ye;){var Ee;const gt=await this.fetchRelations(b.room.roomId,ke.id,ne.THREAD_RELATION_TYPE.name,null,{dir:g.Direction.Forward,from:Ye});Ye=(Ee=gt.next_batch)!==null&&Ee!==void 0?Ee:null,tt.push(...gt.chunk)}const Xe=[...tt.reverse().map(ue),ve,...Me.chunk.map(ue)];for(const gt of Xe){var qe;await((qe=b.thread)===null||qe===void 0?void 0:qe.processEvent(gt))}const ze=b.getLiveTimeline();if(ze.getState(g.EventTimeline.BACKWARDS).setUnknownStateEvents(ie.state.map(ue)),b.addEventsToTimeline(Xe,!0,ze,null),!Me.next_batch){const gt=await this.fetchRoomEvent(b.room.roomId,ke.id);b.addEventsToTimeline([ue(gt)],!0,ze,null)}return ze.setPaginationToken((Pe=Me.next_batch)!==null&&Pe!==void 0?Pe:null,g.Direction.Backward),ze.setPaginationToken(null,g.Direction.Forward),this.processBeaconEvents(b.room,Xe),ze}}async getLatestTimeline(b){if(!this.timelineSupport)throw new Error("timeline support is disabled. Set the 'timelineSupport' parameter to true when creating MatrixClient to enable it.");if(!b.room)throw new Error("getLatestTimeline only supports room timelines");let O;if(b.threadListType!==null){var $;O=($=(await this.createThreadListMessagesRequest(b.room.roomId,null,1,g.Direction.Backward,b.threadListType,b.getFilter())).chunk)===null||$===void 0?void 0:$[0]}else if(b.thread&&ne.Thread.hasServerSideSupport){var Y;O=(Y=(await this.fetchRelations(b.room.roomId,b.thread.id,ne.THREAD_RELATION_TYPE.name,null,{dir:g.Direction.Backward,limit:1})).chunk)===null||Y===void 0?void 0:Y[0]}else{var ee,ie;const ue=s.encodeUri("/rooms/$roomId/messages",{$roomId:b.room.roomId}),ve={dir:"b"};(ee=this.clientOpts)!==null&&ee!==void 0&&ee.lazyLoadMembers&&(ve.filter=JSON.stringify(f.Filter.LAZY_LOADING_MESSAGES_FILTER)),O=(ie=(await this.http.authedRequest(d.Method.Get,ue,ve)).chunk)===null||ie===void 0?void 0:ie[0]}if(!O)throw new Error("No message returned when trying to construct getLatestTimeline");return this.getEventTimeline(b,O.event_id)}createMessagesRequest(b,O,$=30,Y,ee){var ie;const ue=s.encodeUri("/rooms/$roomId/messages",{$roomId:b}),ve={limit:$.toString(),dir:Y};O&&(ve.from=O);let _e=null;if((ie=this.clientOpts)!==null&&ie!==void 0&&ie.lazyLoadMembers&&(_e=Object.assign({},f.Filter.LAZY_LOADING_MESSAGES_FILTER)),ee){var be;_e=_e||{},Object.assign(_e,(be=ee.getRoomTimelineFilterComponent())===null||be===void 0?void 0:be.toJSON())}return _e&&(ve.filter=JSON.stringify(_e)),this.http.authedRequest(d.Method.Get,ue,ve)}createThreadListMessagesRequest(b,O,$=30,Y=g.Direction.Backward,ee=ne.ThreadFilterType.All,ie){var ue;const ve=s.encodeUri("/rooms/$roomId/threads",{$roomId:b}),_e={limit:$.toString(),dir:Y,include:(0,ne.threadFilterTypeToFilter)(ee)};O&&(_e.from=O);let be={};if((ue=this.clientOpts)!==null&&ue!==void 0&&ue.lazyLoadMembers&&(be=ge({},f.Filter.LAZY_LOADING_MESSAGES_FILTER)),ie){var Ce;be=ge(ge({},be),(Ce=ie.getRoomTimelineFilterComponent())===null||Ce===void 0?void 0:Ce.toJSON())}Object.keys(be).length&&(_e.filter=JSON.stringify(be));const Fe={prefix:ne.Thread.hasServerSideListSupport===ne.FeatureSupport.Stable?"/_matrix/client/v1":"/_matrix/client/unstable/org.matrix.msc3856"};return this.http.authedRequest(d.Method.Get,ve,_e,void 0,Fe).then(Pe=>{var Ee;return ge(ge({},Pe),{},{chunk:(Ee=Pe.chunk)===null||Ee===void 0?void 0:Ee.reverse(),start:Pe.prev_batch,end:Pe.next_batch})})}paginateEventTimeline(b,O){const $=b.getTimelineSet()===this.notifTimelineSet,Y=this.getRoom(b.getRoomId()),ee=b.getTimelineSet().threadListType,ie=b.getTimelineSet().thread;O=O||{};const ue=O.backwards||!1;if($&&!ue)throw new Error("paginateNotifTimeline can only paginate backwards");const ve=ue?g.EventTimeline.BACKWARDS:g.EventTimeline.FORWARDS,_e=b.getPaginationToken(ve),be=b.paginationRequests[ve];if(be)return be;let Ce,Fe,Pe;if($){var Ee;Ce="/notifications",Fe={limit:((Ee=O.limit)!==null&&Ee!==void 0?Ee:30).toString(),only:"highlight"},_e&&_e!=="end"&&(Fe.from=_e),Pe=this.http.authedRequest(d.Method.Get,Ce,Fe).then(async Me=>{const tt=Me.next_token,Ye=[];for(let ze=0;ze<Me.notifications.length;ze++){const gt=Me.notifications[ze],rn=this.getEventMapper()(gt.event);rn.setPushActions(y.PushProcessor.actionListToActionsObject(gt.actions)),rn.event.room_id=gt.room_id,Ye[ze]=rn}const Xe=b.getTimelineSet();return Xe.addEventsToTimeline(Ye,ue,b,tt),this.processBeaconEvents(Xe.room,Ye),ue&&!Me.next_token&&b.setPaginationToken(null,ve),Boolean(Me.next_token)}).finally(()=>{b.paginationRequests[ve]=null}),b.paginationRequests[ve]=Pe}else if(ee!==null){if(!Y)throw new Error("Unknown room "+b.getRoomId());if(!ne.Thread.hasServerSideFwdPaginationSupport&&ve===g.Direction.Forward)throw new Error("Cannot paginate threads forwards without server-side support for MSC 3715");Pe=this.createThreadListMessagesRequest(b.getRoomId(),_e,O.limit,ve,ee,b.getFilter()).then(Me=>{if(Me.state){const ze=b.getState(ve),gt=Me.state.map(this.getEventMapper());ze.setUnknownStateEvents(gt)}const tt=Me.end,Ye=Me.chunk.map(this.getEventMapper());return b.getTimelineSet().addEventsToTimeline(Ye,ue,b,tt),this.processBeaconEvents(Y,Ye),this.processThreadRoots(Y,Ye,ue),ue&&Me.end==Me.start&&b.setPaginationToken(null,ve),Me.end!==Me.start}).finally(()=>{b.paginationRequests[ve]=null}),b.paginationRequests[ve]=Pe}else if(ie){var qe,ke;const Me=this.getRoom((qe=b.getRoomId())!==null&&qe!==void 0?qe:void 0);if(!Me)throw new Error("Unknown room "+b.getRoomId());Pe=this.fetchRelations((ke=b.getRoomId())!==null&&ke!==void 0?ke:"",ie.id,ne.THREAD_RELATION_TYPE.name,null,{dir:ve,limit:O.limit,from:_e??void 0}).then(async tt=>{const Ye=this.getEventMapper(),Xe=tt.chunk.map(Ye);for(const q of Xe.slice().reverse()){await(ie==null?void 0:ie.processEvent(q));const J=q.getSender();(!ue||(ie==null?void 0:ie.getEventReadUpTo(J))===null)&&Me.addLocalEchoReceipt(J,q,T.ReceiptType.Read)}const ze=tt.next_batch,gt=b.getTimelineSet();if(gt.addEventsToTimeline(Xe,ue,b,ze??null),!ze&&ue){var rn;const q=await this.fetchRoomEvent((rn=b.getRoomId())!==null&&rn!==void 0?rn:"",ie.id);gt.addEventsToTimeline([Ye(q)],!0,b,null)}return this.processBeaconEvents(gt.room,Xe),ue&&!ze&&b.setPaginationToken(null,ve),Boolean(ze)}).finally(()=>{b.paginationRequests[ve]=null}),b.paginationRequests[ve]=Pe}else{if(!Y)throw new Error("Unknown room "+b.getRoomId());Pe=this.createMessagesRequest(b.getRoomId(),_e,O.limit,ve,b.getFilter()).then(Me=>{if(Me.state){const rn=b.getState(ve),q=Me.state.map(this.getEventMapper());rn.setUnknownStateEvents(q)}const tt=Me.end,Ye=Me.chunk.map(this.getEventMapper()),Xe=b.getTimelineSet(),[ze]=Y.partitionThreadedEvents(Ye);Xe.addEventsToTimeline(ze,ue,b,tt),this.processBeaconEvents(Y,ze),this.processThreadRoots(Y,ze.filter(rn=>rn.getServerAggregatedRelation(ne.THREAD_RELATION_TYPE.name)),!1);const gt=Me.end===void 0||Me.end===Me.start;return ue&&gt&&b.setPaginationToken(null,ve),!gt}).finally(()=>{b.paginationRequests[ve]=null}),b.paginationRequests[ve]=Pe}return Pe}resetNotifTimelineSet(){this.notifTimelineSet&&this.notifTimelineSet.resetLiveTimeline("end")}peekInRoom(b){var O;return(O=this.peekSync)===null||O===void 0||O.stopPeeking(),this.peekSync=new i.SyncApi(this,this.clientOpts),this.peekSync.peek(b)}stopPeeking(){this.peekSync&&(this.peekSync.stopPeeking(),this.peekSync=null)}setGuestAccess(b,O){const $=this.sendStateEvent(b,D.EventType.RoomGuestAccess,{guest_access:O.allowJoin?"can_join":"forbidden"},"");let Y=Promise.resolve(void 0);return O.allowRead&&(Y=this.sendStateEvent(b,D.EventType.RoomHistoryVisibility,{history_visibility:"world_readable"},"")),Promise.all([Y,$]).then()}requestRegisterEmailToken(b,O,$,Y){return this.requestTokenFromEndpoint("/register/email/requestToken",{email:b,client_secret:O,send_attempt:$,next_link:Y})}requestRegisterMsisdnToken(b,O,$,Y,ee){return this.requestTokenFromEndpoint("/register/msisdn/requestToken",{country:b,phone_number:O,client_secret:$,send_attempt:Y,next_link:ee})}requestAdd3pidEmailToken(b,O,$,Y){return this.requestTokenFromEndpoint("/account/3pid/email/requestToken",{email:b,client_secret:O,send_attempt:$,next_link:Y})}requestAdd3pidMsisdnToken(b,O,$,Y,ee){return this.requestTokenFromEndpoint("/account/3pid/msisdn/requestToken",{country:b,phone_number:O,client_secret:$,send_attempt:Y,next_link:ee})}requestPasswordEmailToken(b,O,$,Y){return this.requestTokenFromEndpoint("/account/password/email/requestToken",{email:b,client_secret:O,send_attempt:$,next_link:Y})}requestPasswordMsisdnToken(b,O,$,Y,ee){return this.requestTokenFromEndpoint("/account/password/msisdn/requestToken",{country:b,phone_number:O,client_secret:$,send_attempt:Y,next_link:ee})}async requestTokenFromEndpoint(b,O){const $=Object.assign({},O);if(!await this.doesServerSupportSeparateAddAndBind()&&this.idBaseUrl){var Y;const ee=new URL(this.idBaseUrl);if($.id_server=ee.host,(Y=this.identityServer)!==null&&Y!==void 0&&Y.getAccessToken&&await this.doesServerAcceptIdentityAccessToken()){const ie=await this.identityServer.getAccessToken();ie&&($.id_access_token=ie)}}return this.http.request(d.Method.Post,b,void 0,$)}getRoomPushRule(b,O){if(this.pushRules){var $,Y;return($=this.pushRules[b])===null||$===void 0||(Y=$.room)===null||Y===void 0?void 0:Y.find(ee=>ee.rule_id===O)}else throw new Error("SyncApi.sync() must be done before accessing to push rules.")}setRoomMutePushRule(b,O,$){let Y,ee=!1;const ie=this.getRoomPushRule(b,O);if(ie!=null&&ie.actions.includes(P.PushRuleActionName.DontNotify)&&(ee=!0),!$)ee&&(Y=this.deletePushRule(b,P.PushRuleKind.RoomSpecific,ie.rule_id));else if(!ie)Y=this.addPushRule(b,P.PushRuleKind.RoomSpecific,O,{actions:[P.PushRuleActionName.DontNotify]});else if(!ee){const ue=s.defer();this.deletePushRule(b,P.PushRuleKind.RoomSpecific,ie.rule_id).then(()=>{this.addPushRule(b,P.PushRuleKind.RoomSpecific,O,{actions:[P.PushRuleActionName.DontNotify]}).then(()=>{ue.resolve()}).catch(ve=>{ue.reject(ve)})}).catch(ve=>{ue.reject(ve)}),Y=ue.promise}if(Y)return new Promise((ue,ve)=>{Y.then(()=>{this.getPushRules().then(_e=>{this.pushRules=_e,ue()}).catch(_e=>{ve(_e)})}).catch(_e=>{this.getPushRules().then(be=>{this.pushRules=be,ve(_e)}).catch(be=>{ve(_e)})})})}searchMessageText(b){const O={search_term:b.query};return"keys"in b&&(O.keys=b.keys),this.search({body:{search_categories:{room_events:O}}})}searchRoomEvents(b){const O={search_categories:{room_events:{search_term:b.term,filter:b.filter,order_by:R.SearchOrderBy.Recent,event_context:{before_limit:1,after_limit:1,include_profile:!0}}}},$={_query:O,results:[],highlights:[]};return this.search({body:O}).then(Y=>this.processRoomEventsSearch($,Y))}backPaginateRoomEventsSearch(b){if(!b.next_batch)return Promise.reject(new Error("Cannot backpaginate event search any further"));if(b.pendingRequest)return b.pendingRequest;const O={body:b._query,next_batch:b.next_batch},$=this.search(O,b.abortSignal).then(Y=>this.processRoomEventsSearch(b,Y)).finally(()=>{b.pendingRequest=void 0});return b.pendingRequest=$,$}processRoomEventsSearch(b,O){var $,Y;const ee=O.search_categories.room_events;b.count=ee.count,b.next_batch=ee.next_batch;const ie=new Set(ee.highlights);b.highlights.forEach(_e=>{ie.add(_e)}),b.highlights=Array.from(ie);const ue=this.getEventMapper(),ve=($=(Y=ee.results)===null||Y===void 0?void 0:Y.length)!==null&&$!==void 0?$:0;for(let _e=0;_e<ve;_e++){const be=M.SearchResult.fromJson(ee.results[_e],ue),Ce=this.getRoom(be.context.getEvent().getRoomId());if(Ce)for(const Fe of be.context.getTimeline()){const Pe=Ce.getMember(Fe.getSender());!Fe.sender&&Pe&&(Fe.sender=Pe)}b.results.push(be)}return b}syncLeftRooms(){if(this.syncedLeftRooms)return Promise.resolve([]);if(this.syncLeftRoomsPromise)return this.syncLeftRoomsPromise;const b=new i.SyncApi(this,this.clientOpts);return this.syncLeftRoomsPromise=b.syncLeftRooms(),this.syncLeftRoomsPromise.then(()=>{u.logger.log("Marking success of sync left room request"),this.syncedLeftRooms=!0}).finally(()=>{this.syncLeftRoomsPromise=void 0}),this.syncLeftRoomsPromise}createFilter(b){const O=s.encodeUri("/user/$userId/filter",{$userId:this.credentials.userId});return this.http.authedRequest(d.Method.Post,O,void 0,b).then($=>{const Y=f.Filter.fromJson(this.credentials.userId,$.filter_id,b);return this.store.storeFilter(Y),Y})}getFilter(b,O,$){if($){const ee=this.store.getFilter(b,O);if(ee)return Promise.resolve(ee)}const Y=s.encodeUri("/user/$userId/filter/$filterId",{$userId:b,$filterId:O});return this.http.authedRequest(d.Method.Get,Y).then(ee=>{const ie=f.Filter.fromJson(b,O,ee);return this.store.storeFilter(ie),ie})}async getOrCreateFilter(b,O){const $=this.store.getFilterIdByName(b);let Y;if($){try{const ie=await this.getFilter(this.credentials.userId,$,!0);if(ie){const ue=ie.getDefinition(),ve=O.getDefinition();s.deepCompare(ue,ve)&&(Y=$)}}catch(ie){if(ie.errcode!=="M_UNKNOWN"&&ie.errcode!=="M_NOT_FOUND")throw ie}Y||this.store.setFilterIdByName(b,void 0)}if(Y)return Y;const ee=await this.createFilter(O.getDefinition());return this.store.setFilterIdByName(b,ee.filterId),ee.filterId}getOpenIdToken(){const b=s.encodeUri("/user/$userId/openid/request_token",{$userId:this.credentials.userId});return this.http.authedRequest(d.Method.Post,b,void 0,{})}turnServer(){return this.http.authedRequest(d.Method.Get,"/voip/turnServer")}getTurnServers(){return this.turnServers||[]}getTurnServersExpiry(){return this.turnServersExpiry}get pollingTurnServers(){return this.checkTurnServersIntervalID!==void 0}async checkTurnServers(){if(!this.canSupportVoip)return;let b=!1;const O=this.turnServersExpiry-Date.now();if(O>ce)u.logger.debug("TURN creds are valid for another "+O+" ms: not fetching new ones."),b=!0;else{u.logger.debug("Fetching new TURN credentials");try{const $=await this.turnServer();if($.uris){u.logger.log("Got TURN URIs: "+$.uris+" refresh in "+$.ttl+" secs");const Y={urls:$.uris,username:$.username,credential:$.password};this.turnServers=[Y],this.turnServersExpiry=Date.now()+$.ttl*1e3,b=!0,this.emit(Ve.TurnServers,this.turnServers)}}catch($){u.logger.error("Failed to get TURN URIs",$),$.httpStatus===403?(u.logger.info("TURN access unavailable for this account: stopping credentials checks"),this.checkTurnServersIntervalID!==null&&$e.clearInterval(this.checkTurnServersIntervalID),this.checkTurnServersIntervalID=void 0,this.emit(Ve.TurnServersError,$,!0)):this.emit(Ve.TurnServersError,$,!1)}}return b}setFallbackICEServerAllowed(b){this.fallbackICEServerAllowed=b}isFallbackICEServerAllowed(){return this.fallbackICEServerAllowed}isSynapseAdministrator(){const b=s.encodeUri("/_synapse/admin/v1/users/$userId/admin",{$userId:this.getUserId()});return this.http.authedRequest(d.Method.Get,b,void 0,void 0,{prefix:""}).then(O=>O.admin)}whoisSynapseUser(b){const O=s.encodeUri("/_synapse/admin/v1/whois/$userId",{$userId:b});return this.http.authedRequest(d.Method.Get,O,void 0,void 0,{prefix:""})}deactivateSynapseUser(b){const O=s.encodeUri("/_synapse/admin/v1/deactivate/$userId",{$userId:b});return this.http.authedRequest(d.Method.Post,O,void 0,void 0,{prefix:""})}async fetchClientWellKnown(){var b;this.clientWellKnownPromise=S.AutoDiscovery.getRawClientConfig((b=this.getDomain())!==null&&b!==void 0?b:void 0),this.clientWellKnown=await this.clientWellKnownPromise,this.emit(Ve.ClientWellKnown,this.clientWellKnown)}getClientWellKnown(){return this.clientWellKnown}waitForClientWellKnown(){if(!this.clientRunning)throw new Error("Client is not running");return this.clientWellKnownPromise}storeClientOptions(){const b=["boolean","string","number"],O=Object.entries(this.clientOpts).filter(([$,Y])=>b.includes(typeof Y)).reduce(($,[Y,ee])=>($[Y]=ee,$),{});return this.store.storeClientOptions(O)}async _unstable_getSharedRooms(b){const O=await this.doesServerSupportUnstableFeature("uk.half-shot.msc2666"),$=await this.doesServerSupportUnstableFeature("uk.half-shot.msc2666.mutual_rooms");if(!O&&!$)throw Error("Server does not support mutual_rooms API");const Y=s.encodeUri(`/uk.half-shot.msc2666/user/${$?"mutual_rooms":"shared_rooms"}/$userId`,{$userId:b});return(await this.http.authedRequest(d.Method.Get,Y,void 0,void 0,{prefix:d.ClientPrefix.Unstable})).joined}async getVersions(){if(this.serverVersionsPromise)return this.serverVersionsPromise;this.serverVersionsPromise=this.http.request(d.Method.Get,"/_matrix/client/versions",void 0,void 0,{prefix:""}).catch($=>{throw this.serverVersionsPromise=void 0,$});const b=await this.serverVersionsPromise;this.canSupport=await(0,j.buildFeatureSupportMap)(b);const O=this.canSupport.get(j.Feature.ThreadUnreadNotifications);return Q.UNREAD_THREAD_NOTIFICATIONS.setPreferUnstable(O===j.ServerSupport.Unstable),this.serverVersionsPromise}async isVersionSupported(b){const{versions:O}=await this.getVersions();return O&&O.includes(b)}async doesServerSupportLazyLoading(){const b=await this.getVersions();if(!b)return!1;const O=b.versions,$=b.unstable_features;return O&&O.includes("r0.5.0")||$&&$["m.lazy_load_members"]}async doesServerRequireIdServerParam(){const b=await this.getVersions();if(!b)return!0;const O=b.versions;if(O&&O.includes("r0.6.0"))return!1;const $=b.unstable_features;return!$||$["m.require_identity_server"]===void 0?!0:$["m.require_identity_server"]}async doesServerAcceptIdentityAccessToken(){const b=await this.getVersions();if(!b)return!1;const O=b.versions,$=b.unstable_features;return O&&O.includes("r0.6.0")||$&&$["m.id_access_token"]}async doesServerSupportSeparateAddAndBind(){const b=await this.getVersions();if(!b)return!1;const O=b.versions,$=b.unstable_features;return(O==null?void 0:O.includes("r0.6.0"))||($==null?void 0:$["m.separate_add_and_bind"])}async doesServerSupportUnstableFeature(b){const O=await this.getVersions();if(!O)return!1;const $=O.unstable_features;return $&&!!$[b]}async doesServerForceEncryptionForPreset(b){const O=await this.getVersions();if(!O)return!1;const $=O.unstable_features,Y=b.includes("_chat")?b.substring(0,b.indexOf("_chat")):b;return $&&!!$[`io.element.e2ee_forced.${Y}`]}async doesServerSupportThread(){if(await this.isVersionSupported("v1.4"))return{threads:ne.FeatureSupport.Stable,list:ne.FeatureSupport.Stable,fwdPagination:ne.FeatureSupport.Stable};try{const[b,O,$,Y,ee,ie]=await Promise.all([this.doesServerSupportUnstableFeature("org.matrix.msc3440"),this.doesServerSupportUnstableFeature("org.matrix.msc3440.stable"),this.doesServerSupportUnstableFeature("org.matrix.msc3856"),this.doesServerSupportUnstableFeature("org.matrix.msc3856.stable"),this.doesServerSupportUnstableFeature("org.matrix.msc3715"),this.doesServerSupportUnstableFeature("org.matrix.msc3715.stable")]);return{threads:(0,ne.determineFeatureSupport)(O,b),list:(0,ne.determineFeatureSupport)(Y,$),fwdPagination:(0,ne.determineFeatureSupport)(ie,ee)}}catch{return{threads:ne.FeatureSupport.None,list:ne.FeatureSupport.None,fwdPagination:ne.FeatureSupport.None}}}doesServerSupportLogoutDevices(){return this.isVersionSupported("r0.6.1")}hasLazyLoadMembersEnabled(){var b;return!!((b=this.clientOpts)!==null&&b!==void 0&&b.lazyLoadMembers)}setCanResetTimelineCallback(b){this.canResetTimelineCallback=b}getCanResetTimelineCallback(){return this.canResetTimelineCallback}async relations(b,O,$,Y,ee={dir:g.Direction.Backward}){var ie,ue;const ve=Y?this.getEncryptedIfNeededEventType(b,Y):null,[_e,be]=await Promise.all([this.fetchRoomEvent(b,O),this.fetchRelations(b,O,$,ve,ee)]),Ce=this.getEventMapper(),Fe=_e?Ce(_e):void 0;let Pe=be.chunk.map(Ce);if(ve===D.EventType.RoomMessageEncrypted){const Ee=Fe?Pe.concat(Fe):Pe;await Promise.all(Ee.map(qe=>this.decryptEventIfNeeded(qe))),Y!==null&&(Pe=Pe.filter(qe=>qe.getType()===Y))}return Fe&&$===D.RelationType.Replace&&(Pe=Pe.filter(Ee=>Ee.getSender()===Fe.getSender())),{originalEvent:Fe??null,events:Pe,nextBatch:(ie=be.next_batch)!==null&&ie!==void 0?ie:null,prevBatch:(ue=be.prev_batch)!==null&&ue!==void 0?ue:null}}getCrossSigningCacheCallbacks(){var b;return(b=this.crypto)===null||b===void 0?void 0:b.crossSigningInfo.getCacheCallbacks()}generateClientSecret(){return(0,W.randomString)(32)}decryptEventIfNeeded(b,O){return b.shouldAttemptDecryption()&&this.isCryptoEnabled()&&b.attemptDecryption(this.cryptoBackend,O),b.isBeingDecrypted()?b.getDecryptionPromise():Promise.resolve()}termsUrlForService(b,O){switch(b){case l.SERVICE_TYPES.IS:return this.http.getUrl("/terms",void 0,d.IdentityPrefix.V2,O);case l.SERVICE_TYPES.IM:return this.http.getUrl("/terms",void 0,"/_matrix/integrations/v1",O);default:throw new Error("Unsupported service type")}}getHomeserverUrl(){return this.baseUrl}getIdentityServerUrl(b=!1){var O,$;return b&&((O=this.idBaseUrl)!==null&&O!==void 0&&O.startsWith("http://")||($=this.idBaseUrl)!==null&&$!==void 0&&$.startsWith("https://"))?this.idBaseUrl.split("://")[1]:this.idBaseUrl}setIdentityServerUrl(b){this.idBaseUrl=s.ensureNoTrailingSlash(b),this.http.setIdBaseUrl(this.idBaseUrl)}getAccessToken(){return this.http.opts.accessToken||null}setAccessToken(b){this.http.opts.accessToken=b}isLoggedIn(){return this.http.opts.accessToken!==void 0}makeTxnId(){return"m"+new Date().getTime()+"."+this.txnCtr++}isUsernameAvailable(b){return this.http.authedRequest(d.Method.Get,"/register/available",{username:b}).then(O=>O.available).catch(O=>O.errcode==="M_USER_IN_USE"?!1:Promise.reject(O))}register(b,O,$,Y,ee,ie,ue){ee===!0?ee={email:!0}:(ee==null||ee===!1)&&(ee={}),$&&(Y.session=$);const ve={auth:Y,refresh_token:!0};return b!=null&&(ve.username=b),O!=null&&(ve.password=O),ee.email&&(ve.bind_email=!0),ee.msisdn&&(ve.bind_msisdn=!0),ie!=null&&(ve.guest_access_token=ie),ue!=null&&(ve.inhibit_login=ue),O!=null&&(ve.x_show_msisdn=!0),this.registerRequest(ve)}registerGuest({body:b}={}){return this.registerRequest(b||{},"guest")}registerRequest(b,O){const $={};return O&&($.kind=O),this.http.request(d.Method.Post,"/register",$,b)}refreshToken(b){return this.http.authedRequest(d.Method.Post,"/refresh",void 0,{refresh_token:b},{prefix:d.ClientPrefix.V1,inhibitLogoutEmit:!0})}loginFlows(){return this.http.request(d.Method.Get,"/login")}login(b,O){const $={type:b};return Object.assign($,O),this.http.authedRequest(d.Method.Post,"/login",void 0,$).then(Y=>(Y.access_token&&Y.user_id&&(this.http.opts.accessToken=Y.access_token,this.credentials={userId:Y.user_id}),Y))}loginWithPassword(b,O){return this.login("m.login.password",{user:b,password:O})}loginWithSAML2(b){return this.login("m.login.saml2",{relay_state:b})}getCasLoginUrl(b){return this.getSsoLoginUrl(b,"cas")}getSsoLoginUrl(b,O="sso",$,Y){let ee="/login/"+O+"/redirect";$&&(ee+="/"+$);const ie={redirectUrl:b,[Be.unstable]:Y};return this.http.getUrl(ee,ie,d.ClientPrefix.R0).href}loginWithToken(b){return this.login("m.login.token",{token:b})}async logout(b=!1){var O,$;if((O=this.crypto)!==null&&O!==void 0&&($=O.backupManager)!==null&&$!==void 0&&$.getKeyBackupEnabled())try{for(;await this.crypto.backupManager.backupPendingKeys(200)>0;);}catch(Y){u.logger.error("Key backup request failed when logging out. Some keys may be missing from backup",Y)}return b&&(this.stopClient(),this.http.abort()),this.http.authedRequest(d.Method.Post,"/logout")}deactivateAccount(b,O){const $={};return b&&($.auth=b),O!==void 0&&($.erase=O),this.http.authedRequest(d.Method.Post,"/account/deactivate",void 0,$)}requestLoginToken(b){const O={auth:b};return this.http.authedRequest(d.Method.Post,"/org.matrix.msc3882/login/token",void 0,O,{prefix:d.ClientPrefix.Unstable})}getFallbackAuthUrl(b,O){const $=s.encodeUri("/auth/$loginType/fallback/web",{$loginType:b});return this.http.getUrl($,{session:O},d.ClientPrefix.R0).href}async createRoom(b){var O;const $=(b.invite_3pid||[]).filter(Y=>!Y.id_access_token);if($.length>0&&(O=this.identityServer)!==null&&O!==void 0&&O.getAccessToken&&await this.doesServerAcceptIdentityAccessToken()){const Y=await this.identityServer.getAccessToken();if(Y)for(const ee of $)ee.id_access_token=Y}return this.http.authedRequest(d.Method.Post,"/createRoom",void 0,b)}fetchRelations(b,O,$,Y,ee={dir:g.Direction.Backward}){let ie=ee;ne.Thread.hasServerSideFwdPaginationSupport===ne.FeatureSupport.Experimental&&(ie=(0,s.replaceParam)("dir","org.matrix.msc3715.dir",ie));const ue=s.encodeParams(ie);let ve="/rooms/$roomId/relations/$eventId";$!==null?(ve+="/$relationType",Y!==null&&(ve+="/$eventType")):Y!==null&&(u.logger.warn(`eventType: ${Y} ignored when fetching
     86             relations as relationType is null`),Y=null);const _e=s.encodeUri(ve+"?"+ue,{$roomId:b,$eventId:O,$relationType:$,$eventType:Y});return this.http.authedRequest(d.Method.Get,_e,void 0,void 0,{prefix:d.ClientPrefix.V1})}roomState(b){const O=s.encodeUri("/rooms/$roomId/state",{$roomId:b});return this.http.authedRequest(d.Method.Get,O)}fetchRoomEvent(b,O){const $=s.encodeUri("/rooms/$roomId/event/$eventId",{$roomId:b,$eventId:O});return this.http.authedRequest(d.Method.Get,$)}members(b,O,$,Y){const ee={};O&&(ee.membership=O),$&&(ee.not_membership=$),Y&&(ee.at=Y);const ie=s.encodeParams(ee),ue=s.encodeUri("/rooms/$roomId/members?"+ie,{$roomId:b});return this.http.authedRequest(d.Method.Get,ue)}upgradeRoom(b,O){const $=s.encodeUri("/rooms/$roomId/upgrade",{$roomId:b});return this.http.authedRequest(d.Method.Post,$,void 0,{new_version:O})}getStateEvent(b,O,$){const Y={$roomId:b,$eventType:O,$stateKey:$};let ee=s.encodeUri("/rooms/$roomId/state/$eventType",Y);return $!==void 0&&(ee=s.encodeUri(ee+"/$stateKey",Y)),this.http.authedRequest(d.Method.Get,ee)}sendStateEvent(b,O,$,Y="",ee={}){const ie={$roomId:b,$eventType:O,$stateKey:Y};let ue=s.encodeUri("/rooms/$roomId/state/$eventType",ie);return Y!==void 0&&(ue=s.encodeUri(ue+"/$stateKey",ie)),this.http.authedRequest(d.Method.Put,ue,void 0,$,ee)}roomInitialSync(b,O){var $;const Y=s.encodeUri("/rooms/$roomId/initialSync",{$roomId:b});return this.http.authedRequest(d.Method.Get,Y,{limit:($=O==null?void 0:O.toString())!==null&&$!==void 0?$:"30"})}async setRoomReadMarkersHttpRequest(b,O,$,Y){const ee=s.encodeUri("/rooms/$roomId/read_markers",{$roomId:b}),ie={[T.ReceiptType.FullyRead]:O,[T.ReceiptType.Read]:$};return(await this.doesServerSupportUnstableFeature("org.matrix.msc2285.stable")||await this.isVersionSupported("v1.4"))&&(ie[T.ReceiptType.ReadPrivate]=Y),this.http.authedRequest(d.Method.Post,ee,void 0,ie)}getJoinedRooms(){const b=s.encodeUri("/joined_rooms",{});return this.http.authedRequest(d.Method.Get,b)}getJoinedRoomMembers(b){const O=s.encodeUri("/rooms/$roomId/joined_members",{$roomId:b});return this.http.authedRequest(d.Method.Get,O)}publicRooms(b={}){let{server:O,limit:$,since:Y}=b,ee=(0,t.default)(b,Z);const ie={server:O,limit:$,since:Y};return Object.keys(ee).length===0?this.http.authedRequest(d.Method.Get,"/publicRooms",ie):this.http.authedRequest(d.Method.Post,"/publicRooms",ie,ee)}createAlias(b,O){const $=s.encodeUri("/directory/room/$alias",{$alias:b}),Y={room_id:O};return this.http.authedRequest(d.Method.Put,$,void 0,Y)}deleteAlias(b){const O=s.encodeUri("/directory/room/$alias",{$alias:b});return this.http.authedRequest(d.Method.Delete,O)}getLocalAliases(b){const O=s.encodeUri("/rooms/$roomId/aliases",{$roomId:b}),$=d.ClientPrefix.V3;return this.http.authedRequest(d.Method.Get,O,void 0,void 0,{prefix:$})}getRoomIdForAlias(b){const O=s.encodeUri("/directory/room/$alias",{$alias:b});return this.http.authedRequest(d.Method.Get,O)}resolveRoomAlias(b){const O=s.encodeUri("/directory/room/$alias",{$alias:b});return this.http.request(d.Method.Get,O)}getRoomDirectoryVisibility(b){const O=s.encodeUri("/directory/list/room/$roomId",{$roomId:b});return this.http.authedRequest(d.Method.Get,O)}setRoomDirectoryVisibility(b,O){const $=s.encodeUri("/directory/list/room/$roomId",{$roomId:b});return this.http.authedRequest(d.Method.Put,$,void 0,{visibility:O})}setRoomDirectoryVisibilityAppService(b,O,$){const Y=s.encodeUri("/directory/list/appservice/$networkId/$roomId",{$networkId:b,$roomId:O});return this.http.authedRequest(d.Method.Put,Y,void 0,{visibility:$})}searchUserDirectory({term:b,limit:O}){const $={search_term:b};return O!==void 0&&($.limit=O),this.http.authedRequest(d.Method.Post,"/user_directory/search",void 0,$)}uploadContent(b,O){return this.http.uploadContent(b,O)}cancelUpload(b){return this.http.cancelUpload(b)}getCurrentUploads(){return this.http.getCurrentUploads()}getProfileInfo(b,O){const $=O?s.encodeUri("/profile/$userId/$info",{$userId:b,$info:O}):s.encodeUri("/profile/$userId",{$userId:b});return this.http.authedRequest(d.Method.Get,$)}getThreePids(){return this.http.authedRequest(d.Method.Get,"/account/3pid")}addThreePid(b,O){const $="/account/3pid",Y={threePidCreds:b,bind:O};return this.http.authedRequest(d.Method.Post,$,void 0,Y)}async addThreePidOnly(b){const O="/account/3pid/add",$=await this.isVersionSupported("r0.6.0")?d.ClientPrefix.R0:d.ClientPrefix.Unstable;return this.http.authedRequest(d.Method.Post,O,void 0,b,{prefix:$})}async bindThreePid(b){const O="/account/3pid/bind",$=await this.isVersionSupported("r0.6.0")?d.ClientPrefix.R0:d.ClientPrefix.Unstable;return this.http.authedRequest(d.Method.Post,O,void 0,b,{prefix:$})}async unbindThreePid(b,O){const $="/account/3pid/unbind",Y={medium:b,address:O,id_server:this.getIdentityServerUrl(!0)},ee=await this.isVersionSupported("r0.6.0")?d.ClientPrefix.R0:d.ClientPrefix.Unstable;return this.http.authedRequest(d.Method.Post,$,void 0,Y,{prefix:ee})}deleteThreePid(b,O){const $="/account/3pid/delete";return this.http.authedRequest(d.Method.Post,$,void 0,{medium:b,address:O})}setPassword(b,O,$){const Y="/account/password",ee={auth:b,new_password:O,logout_devices:$};return this.http.authedRequest(d.Method.Post,Y,void 0,ee)}getDevices(){return this.http.authedRequest(d.Method.Get,"/devices")}getDevice(b){const O=s.encodeUri("/devices/$device_id",{$device_id:b});return this.http.authedRequest(d.Method.Get,O)}setDeviceDetails(b,O){const $=s.encodeUri("/devices/$device_id",{$device_id:b});return this.http.authedRequest(d.Method.Put,$,void 0,O)}deleteDevice(b,O){const $=s.encodeUri("/devices/$device_id",{$device_id:b}),Y={};return O&&(Y.auth=O),this.http.authedRequest(d.Method.Delete,$,void 0,Y)}deleteMultipleDevices(b,O){const $={devices:b};O&&($.auth=O);const Y="/delete_devices";return this.http.authedRequest(d.Method.Post,Y,void 0,$)}async getPushers(){const b=await this.http.authedRequest(d.Method.Get,"/pushers");return await this.doesServerSupportUnstableFeature("org.matrix.msc3881")||(b.pushers=b.pushers.map(O=>(O.hasOwnProperty(D.PUSHER_ENABLED.name)||(O[D.PUSHER_ENABLED.name]=!0),O))),b}setPusher(b){const O="/pushers/set";return this.http.authedRequest(d.Method.Post,O,void 0,b)}setLocalNotificationSettings(b,O){const $=`${D.LOCAL_NOTIFICATION_SETTINGS_PREFIX.name}.${b}`;return this.setAccountData($,O)}getPushRules(){return this.http.authedRequest(d.Method.Get,"/pushrules/").then(b=>y.PushProcessor.rewriteDefaultRules(b))}addPushRule(b,O,$,Y){const ee=s.encodeUri("/pushrules/"+b+"/$kind/$ruleId",{$kind:O,$ruleId:$});return this.http.authedRequest(d.Method.Put,ee,void 0,Y)}deletePushRule(b,O,$){const Y=s.encodeUri("/pushrules/"+b+"/$kind/$ruleId",{$kind:O,$ruleId:$});return this.http.authedRequest(d.Method.Delete,Y)}setPushRuleEnabled(b,O,$,Y){const ee=s.encodeUri("/pushrules/"+b+"/$kind/$ruleId/enabled",{$kind:O,$ruleId:$});return this.http.authedRequest(d.Method.Put,ee,void 0,{enabled:Y})}setPushRuleActions(b,O,$,Y){const ee=s.encodeUri("/pushrules/"+b+"/$kind/$ruleId/actions",{$kind:O,$ruleId:$});return this.http.authedRequest(d.Method.Put,ee,void 0,{actions:Y})}search({body:b,next_batch:O},$){const Y={};return O&&(Y.next_batch=O),this.http.authedRequest(d.Method.Post,"/search",Y,b,{abortSignal:$})}uploadKeysRequest(b,O){return this.http.authedRequest(d.Method.Post,"/keys/upload",void 0,b)}uploadKeySignatures(b){return this.http.authedRequest(d.Method.Post,"/keys/signatures/upload",void 0,b,{prefix:d.ClientPrefix.V3})}downloadKeysForUsers(b,{token:O}={}){const $={device_keys:{}};return O!==void 0&&($.token=O),b.forEach(Y=>{$.device_keys[Y]=[]}),this.http.authedRequest(d.Method.Post,"/keys/query",void 0,$)}claimOneTimeKeys(b,O="signed_curve25519",$){const Y={};O===void 0&&(O="signed_curve25519");for(const[ue,ve]of b){const _e=Y[ue]||{};Y[ue]=_e,_e[ve]=O}const ee={one_time_keys:Y};$&&(ee.timeout=$);const ie="/keys/claim";return this.http.authedRequest(d.Method.Post,ie,void 0,ee)}getKeyChanges(b,O){const $={from:b,to:O};return this.http.authedRequest(d.Method.Get,"/keys/changes",$)}uploadDeviceSigningKeys(b,O){const $=Object.assign({},O);return b&&Object.assign($,{auth:b}),this.http.authedRequest(d.Method.Post,"/keys/device_signing/upload",void 0,$,{prefix:d.ClientPrefix.Unstable})}registerWithIdentityServer(b){if(!this.idBaseUrl)throw new Error("No identity server base URL set");const O=this.http.getUrl("/account/register",void 0,d.IdentityPrefix.V2,this.idBaseUrl);return this.http.requestOtherUrl(d.Method.Post,O,b)}requestEmailToken(b,O,$,Y,ee){const ie={client_secret:O,email:b,send_attempt:$==null?void 0:$.toString(),next_link:Y};return this.http.idServerRequest(d.Method.Post,"/validate/email/requestToken",ie,d.IdentityPrefix.V2,ee)}requestMsisdnToken(b,O,$,Y,ee,ie){const ue={client_secret:$,country:b,phone_number:O,send_attempt:Y==null?void 0:Y.toString(),next_link:ee};return this.http.idServerRequest(d.Method.Post,"/validate/msisdn/requestToken",ue,d.IdentityPrefix.V2,ie)}submitMsisdnToken(b,O,$,Y){const ee={sid:b,client_secret:O,token:$};return this.http.idServerRequest(d.Method.Post,"/validate/msisdn/submitToken",ee,d.IdentityPrefix.V2,Y)}submitMsisdnTokenOtherUrl(b,O,$,Y){const ee={sid:O,client_secret:$,token:Y};return this.http.requestOtherUrl(d.Method.Post,b,ee)}getIdentityHashDetails(b){return this.http.idServerRequest(d.Method.Get,"/hash_details",void 0,d.IdentityPrefix.V2,b)}async identityHashedLookup(b,O){const $={},Y=await this.getIdentityHashDetails(O);if(!Y||!Y.lookup_pepper||!Y.algorithms)throw new Error("Unsupported identity server: bad response");$.pepper=Y.lookup_pepper;const ee={};if(Y.algorithms.includes("sha256")){const ve=new $e.Olm.Utility;$.addresses=b.map(_e=>{const be=_e[0].toLowerCase(),Ce=_e[1].toLowerCase(),Fe=ve.sha256(`${be} ${Ce} ${$.pepper}`).replace(/\+/g,"-").replace(/\//g,"_");return ee[Fe]=_e[0],Fe}),$.algorithm="sha256"}else if(Y.algorithms.includes("none"))$.addresses=b.map(ve=>{const _e=ve[0].toLowerCase(),be=ve[1].toLowerCase(),Ce=`${_e} ${be}`;return ee[Ce]=ve[0],Ce}),$.algorithm="none";else throw new Error("Unsupported identity server: unknown hash algorithm");const ie=await this.http.idServerRequest(d.Method.Post,"/lookup",$,d.IdentityPrefix.V2,O);if(!(ie!=null&&ie.mappings))return[];const ue=[];for(const ve of Object.keys(ie.mappings)){const _e=ie.mappings[ve],be=ee[ve];if(!be)throw new Error("Identity server returned more results than expected");ue.push({address:be,mxid:_e})}return ue}async lookupThreePid(b,O,$){const ee=(await this.identityHashedLookup([[O,b]],$)).find(ue=>ue.address===O);return ee?{address:O,medium:b,mxid:ee.mxid}:{}}async bulkLookupThreePids(b,O){const $=await this.identityHashedLookup(b.map(ee=>[ee[1],ee[0]]),O),Y=[];for(const ee of $){const ie=b.find(ue=>ue[1]===ee.address);if(!ie)throw new Error("Identity sever returned unexpected results");Y.push([ie[0],ee.address,ee.mxid])}return{threepids:Y}}getIdentityAccount(b){return this.http.idServerRequest(d.Method.Get,"/account",void 0,d.IdentityPrefix.V2,b)}sendToDevice(b,O,$){const Y=s.encodeUri("/sendToDevice/$eventType/$txnId",{$eventType:b,$txnId:$||this.makeTxnId()}),ee={messages:O},ie=Object.keys(O).reduce((ue,ve)=>(ue[ve]=Object.keys(O[ve]),ue),{});return u.logger.log(`PUT ${Y}`,ie),this.http.authedRequest(d.Method.Put,Y,void 0,ee)}queueToDevice(b){return this.toDeviceMessageQueue.queueBatch(b)}getThirdpartyProtocols(){return this.http.authedRequest(d.Method.Get,"/thirdparty/protocols").then(b=>{if(!b||typeof b!="object")throw new Error(`/thirdparty/protocols did not return an object: ${b}`);return b})}getThirdpartyLocation(b,O){const $=s.encodeUri("/thirdparty/location/$protocol",{$protocol:b});return this.http.authedRequest(d.Method.Get,$,O)}getThirdpartyUser(b,O){const $=s.encodeUri("/thirdparty/user/$protocol",{$protocol:b});return this.http.authedRequest(d.Method.Get,$,O)}getTerms(b,O){const $=this.termsUrlForService(b,O);return this.http.requestOtherUrl(d.Method.Get,$)}agreeToTerms(b,O,$,Y){const ee=this.termsUrlForService(b,O),ie={Authorization:"Bearer "+$};return this.http.requestOtherUrl(d.Method.Post,ee,{user_accepts:Y},{headers:ie})}reportEvent(b,O,$,Y){const ee=s.encodeUri("/rooms/$roomId/report/$eventId",{$roomId:b,$eventId:O});return this.http.authedRequest(d.Method.Post,ee,void 0,{score:$,reason:Y})}getRoomHierarchy(b,O,$,Y=!1,ee){const ie=s.encodeUri("/rooms/$roomId/hierarchy",{$roomId:b}),ue={suggested_only:String(Y),max_depth:$==null?void 0:$.toString(),from:ee,limit:O==null?void 0:O.toString()};return this.http.authedRequest(d.Method.Get,ie,ue,void 0,{prefix:d.ClientPrefix.V1}).catch(ve=>{if(ve.errcode==="M_UNRECOGNIZED")return this.http.authedRequest(d.Method.Get,ie,ue,void 0,{prefix:"/_matrix/client/unstable/org.matrix.msc2946"});throw ve})}async unstableCreateFileTree(b){const{room_id:O}=await this.createRoom({name:b,preset:x.Preset.PrivateChat,power_level_content_override:ge(ge({},H.DEFAULT_TREE_POWER_LEVELS_TEMPLATE),{},{users:{[this.getUserId()]:100}}),creation_content:{[D.RoomCreateTypeField]:D.RoomType.Space},initial_state:[{type:D.UNSTABLE_MSC3088_PURPOSE.name,state_key:D.UNSTABLE_MSC3089_TREE_SUBTYPE.name,content:{[D.UNSTABLE_MSC3088_ENABLED.name]:!0}},{type:D.EventType.RoomEncryption,state_key:"",content:{algorithm:m.MEGOLM_ALGORITHM}}]});return new H.MSC3089TreeSpace(this,O)}unstableGetFileTreeSpace(b){var O,$;const Y=this.getRoom(b);if((Y==null?void 0:Y.getMyMembership())!=="join")return null;const ee=Y.currentState.getStateEvents(D.EventType.RoomCreate,""),ie=Y.currentState.getStateEvents(D.UNSTABLE_MSC3088_PURPOSE.name,D.UNSTABLE_MSC3089_TREE_SUBTYPE.name);if(!ee)throw new Error("Expected single room create event");return!(ie!=null&&(O=ie.getContent())!==null&&O!==void 0&&O[D.UNSTABLE_MSC3088_ENABLED.name])||(($=ee.getContent())===null||$===void 0?void 0:$[D.RoomCreateTypeField])!==D.RoomType.Space?null:new H.MSC3089TreeSpace(this,b)}slidingSync(b,O,$){const Y={};b.pos&&(Y.pos=b.pos,delete b.pos),b.timeout&&(Y.timeout=b.timeout,delete b.timeout);const ee=b.clientTimeout;return delete b.clientTimeout,this.http.authedRequest(d.Method.Post,"/sync",Y,b,{prefix:"/_matrix/client/unstable/org.matrix.msc3575",baseUrl:O,localTimeoutMs:ee,abortSignal:$})}supportsExperimentalThreads(){var b;return((b=this.clientOpts)===null||b===void 0?void 0:b.experimentalThreadSupport)||!1}async getRoomSummary(b,O){const $=s.encodeUri("/rooms/$roomid/summary",{$roomid:b});return this.http.authedRequest(d.Method.Get,$,{via:O},void 0,{prefix:"/_matrix/client/unstable/im.nheko.summary"})}processThreadEvents(b,O,$){b.processThreadedEvents(O,$)}processThreadRoots(b,O,$){b.processThreadRoots(O,$)}processBeaconEvents(b,O){O!=null&&O.length&&b&&b.currentState.processBeaconEvents(O,this)}async whoami(){return this.http.authedRequest(d.Method.Get,"/account/whoami")}timestampToEvent(b,O,$){const Y=s.encodeUri("/rooms/$roomId/timestamp_to_event",{$roomId:b});return this.http.authedRequest(d.Method.Get,Y,{ts:O.toString(),dir:$},void 0,{prefix:"/_matrix/client/unstable/org.matrix.msc3030"})}}bt.MatrixClient=Ne,(0,n.default)(Ne,"RESTORE_BACKUP_ERROR_BAD_KEY","RESTORE_BACKUP_ERROR_BAD_KEY");function We(Re,b){var O,$;const Y=b.getPushActions(),ee=Re.getPushActionsForEvent(b,!0),ie=Re.getRoom(b.getRoomId());if(!ie||!Re.getUserId())return;const ue=!!b.threadRootId&&!b.isThreadRoot,ve=ie.getUnreadCountForEventContext(G.NotificationCountType.Highlight,b),_e=!!(Y!=null&&(O=Y.tweaks)!==null&&O!==void 0&&O.highlight),be=!!(ee!=null&&($=ee.tweaks)!==null&&$!==void 0&&$.highlight);if(_e!==be||ve>0){let Fe;if(ue){const Pe=ie.getThread(b.threadRootId);Fe=Pe?Pe.hasUserReadEvent(Re.getUserId(),b.getId()):!0}else Fe=ie.hasUserReadEvent(Re.getUserId(),b.getId());if(!Fe){var Ce;let Pe=ve;be&&!_e&&Pe++,!be&&_e&&Pe--,ue?ie.setThreadUnreadNotificationCount(b.threadRootId,G.NotificationCountType.Highlight,Pe):ie.setUnreadNotificationCount(G.NotificationCountType.Highlight,Pe),((Ce=ue?ie.getThreadUnreadNotificationCount(b.threadRootId,G.NotificationCountType.Total):ie.getRoomUnreadNotificationCount(G.NotificationCountType.Total))!==null&&Ce!==void 0?Ce:0)<Pe&&(ue?ie.setThreadUnreadNotificationCount(b.threadRootId,G.NotificationCountType.Total,Pe):ie.setUnreadNotificationCount(G.NotificationCountType.Total,Pe))}}}return bt}var Wb;function zf(){if(Wb)return Et;Wb=1;var e=Ae;Object.defineProperty(Et,"__esModule",{value:!0}),Et.ThreadFilterType=Et.ThreadEvent=Et.Thread=Et.THREAD_RELATION_TYPE=Et.FeatureSupport=Et.FILTER_RELATED_BY_SENDERS=Et.FILTER_RELATED_BY_REL_TYPES=void 0,Et.determineFeatureSupport=u,Et.threadFilterTypeToFilter=I;var t=e(Ue),n=or(),r=rs(),i=xe,o=nn(),a=Tr(),c=Gy(),f=hi(),v=en,s=Ge(),g=KP(),y=Sa();function S(k,M){var L=Object.keys(k);if(Object.getOwnPropertySymbols){var B=Object.getOwnPropertySymbols(k);M&&(B=B.filter(function(N){return Object.getOwnPropertyDescriptor(k,N).enumerable})),L.push.apply(L,B)}return L}function m(k){for(var M=1;M<arguments.length;M++){var L=arguments[M]!=null?arguments[M]:{};M%2?S(Object(L),!0).forEach(function(B){(0,t.default)(k,B,L[B])}):Object.getOwnPropertyDescriptors?Object.defineProperties(k,Object.getOwnPropertyDescriptors(L)):S(Object(L)).forEach(function(B){Object.defineProperty(k,B,Object.getOwnPropertyDescriptor(L,B))})}return k}let p;Et.ThreadEvent=p,function(k){k.New="Thread.new",k.Update="Thread.update",k.NewReply="Thread.newReply",k.ViewThread="Thread.viewThread",k.Delete="Thread.delete"}(p||(Et.ThreadEvent=p={}));let _;Et.FeatureSupport=_,function(k){k[k.None=0]="None",k[k.Experimental=1]="Experimental",k[k.Stable=2]="Stable"}(_||(Et.FeatureSupport=_={}));function u(k,M){return k?_.Stable:M?_.Experimental:_.None}class l extends g.ReadReceipt{constructor(M,L,B){var N;if(super(),this.id=M,this.rootEvent=L,(0,t.default)(this,"timelineSet",void 0),(0,t.default)(this,"timeline",[]),(0,t.default)(this,"_currentUserParticipated",!1),(0,t.default)(this,"reEmitter",void 0),(0,t.default)(this,"lastEvent",void 0),(0,t.default)(this,"replyCount",0),(0,t.default)(this,"lastPendingEvent",void 0),(0,t.default)(this,"pendingReplyCount",0),(0,t.default)(this,"room",void 0),(0,t.default)(this,"client",void 0),(0,t.default)(this,"pendingEventOrdering",void 0),(0,t.default)(this,"initialEventsFetched",!l.hasServerSideSupport),(0,t.default)(this,"onBeforeRedaction",(G,D)=>{G!=null&&G.isRelation(w.name)&&this.room.eventShouldLiveIn(G).threadId===this.id&&G.getId()!==this.id&&!D.status&&(this.replyCount--,this.updatePendingReplyCount(),this.emit(p.Update,this))}),(0,t.default)(this,"onRedaction",async G=>{if(G.threadRootId===this.id)if(this.replyCount<=0){for(const D of this.timeline)this.clearEventMetadata(D);this.lastEvent=this.rootEvent,this._currentUserParticipated=!1,this.emit(p.Delete,this)}else await this.updateThreadMetadata()}),(0,t.default)(this,"onTimelineEvent",(G,D,x)=>{x||D.addLocalEchoReceipt(G.getSender(),G,y.ReceiptType.Read),this.onEcho(G,x??!1)}),(0,t.default)(this,"onLocalEcho",G=>{this.onEcho(G,!1)}),(0,t.default)(this,"onEcho",async(G,D)=>{G.threadRootId===this.id&&this.lastEvent!==G&&(await this.updateThreadMetadata(),G.isRelation(w.name)&&(D||this.emit(p.NewReply,this,G)))}),!(B!=null&&B.room))throw new Error("element-web#22141: A thread requires a room in order to function");this.room=B.room,this.client=B.client,this.pendingEventOrdering=(N=B.pendingEventOrdering)!==null&&N!==void 0?N:n.PendingEventOrdering.Chronological,this.timelineSet=new c.EventTimelineSet(this.room,{timelineSupport:!0,pendingEvents:!0},this.client,this),this.reEmitter=new r.TypedReEmitter(this),this.reEmitter.reEmit(this.timelineSet,[f.RoomEvent.Timeline,f.RoomEvent.TimelineReset]),this.room.on(o.MatrixEventEvent.BeforeRedaction,this.onBeforeRedaction),this.room.on(f.RoomEvent.Redaction,this.onRedaction),this.room.on(f.RoomEvent.LocalEchoUpdated,this.onLocalEcho),this.timelineSet.on(f.RoomEvent.Timeline,this.onTimelineEvent),this.processReceipts(B.receipts),this.updateThreadMetadata(),this.setEventMetadata(this.rootEvent)}async fetchRootEvent(){this.rootEvent=this.room.findEventById(this.id);try{const M=await this.client.fetchRoomEvent(this.roomId,this.id),L=this.client.getEventMapper();this.rootEvent=L(M)}catch(M){s.logger.error("Failed to fetch thread root to construct thread with",M)}await this.processEvent(this.rootEvent)}static setServerSideSupport(M){l.hasServerSideSupport=M,M!==_.Stable&&(d.setPreferUnstable(!0),h.setPreferUnstable(!0),w.setPreferUnstable(!0))}static setServerSideListSupport(M){l.hasServerSideListSupport=M}static setServerSideFwdPaginationSupport(M){l.hasServerSideFwdPaginationSupport=M}get roomState(){return this.room.getLiveTimeline().getState(a.EventTimeline.FORWARDS)}addEventToTimeline(M,L){this.findEventById(M.getId())||(this.timelineSet.addEventToTimeline(M,this.liveTimeline,{toStartOfTimeline:L,fromCache:!1,roomState:this.roomState}),this.timeline=this.events)}addEvents(M,L){M.forEach(B=>this.addEvent(B,L,!1)),this.updateThreadMetadata()}async addEvent(M,L,B=!0){this.setEventMetadata(M);const N=this.lastReply(),G=!N||M.localTimestamp>N.localTimestamp;if(!l.hasServerSideSupport)this.addEventToTimeline(M,L),this.client.decryptEventIfNeeded(M,{});else if(!L&&this.initialEventsFetched&&G)this.addEventToTimeline(M,!1),this.fetchEditsWhereNeeded(M);else if(M.isRelation(i.RelationType.Annotation)||M.isRelation(i.RelationType.Replace)){var D,x;(D=this.timelineSet.relations)===null||D===void 0||D.aggregateParentEvent(M),(x=this.timelineSet.relations)===null||x===void 0||x.aggregateChildEvent(M,this.timelineSet);return}(!l.hasServerSideSupport||!this.rootEvent)&&M.isRelation(w.name)&&this.replyCount++,B&&(this.emit(p.NewReply,this,M),this.updateThreadMetadata())}async processEvent(M){M&&(this.setEventMetadata(M),await this.fetchEditsWhereNeeded(M)),this.timeline=this.events}processReceipts(M=[]){for(const{event:L,synthetic:B}of M){const N=L.getContent();Object.keys(N).forEach(G=>{Object.keys(N[G]).forEach(D=>{Object.keys(N[G][D]).forEach(x=>{const z=N[G][D][x];this.addReceiptToStructure(G,D,x,z,B)})})})}}getRootEventBundledRelationship(M=this.rootEvent){return M==null?void 0:M.getServerAggregatedRelation(w.name)}async processRootEvent(){const M=this.getRootEventBundledRelationship();if(l.hasServerSideSupport&&M){this.replyCount=M.count,this._currentUserParticipated=!!M.current_user_participated;const L=this.client.getEventMapper();this.lastEvent=L(m(m({},M.latest_event),{},{room_id:this.roomId})),this.updatePendingReplyCount(),await this.processEvent(this.lastEvent)}}updatePendingReplyCount(){const L=(this.pendingEventOrdering===n.PendingEventOrdering.Detached?this.room.getPendingEvents():this.events).filter(B=>{var N;return B.threadRootId===this.id&&B.isRelation(w.name)&&B.status!==null&&B.getId()!==((N=this.lastEvent)===null||N===void 0?void 0:N.getId())});this.lastPendingEvent=L.length?L[L.length-1]:void 0,this.pendingReplyCount=L.length}async updateThreadMetadata(){if(this.updatePendingReplyCount(),l.hasServerSideSupport&&(this.initialEventsFetched||await this.processRootEvent(),await this.fetchRootEvent()),await this.processRootEvent(),!this.initialEventsFetched){this.initialEventsFetched=!0;try{this.replyCount===0&&this.rootEvent?(this.timelineSet.addEventsToTimeline([this.rootEvent],!0,this.liveTimeline,null),this.liveTimeline.setPaginationToken(null,a.Direction.Backward)):await this.client.paginateEventTimeline(this.liveTimeline,{backwards:!0,limit:Math.max(1,this.length)}),this.emit(f.RoomEvent.TimelineReset,this.room,this.timelineSet,!0)}catch(M){s.logger.error("Failed to load start of newly created thread: ",M),this.initialEventsFetched=!1}}this.emit(p.Update,this)}async fetchEditsWhereNeeded(...M){return Promise.all(M.filter(L=>L.isEncrypted()).map(L=>{if(!L.isRelation())return this.client.relations(this.roomId,L.getId(),i.RelationType.Replace,L.getType(),{limit:1}).then(B=>{B.events.length&&L.makeReplaced(B.events[0])}).catch(B=>{s.logger.error("Failed to load edits for encrypted thread event",B)})}))}setEventMetadata(M){M&&(a.EventTimeline.setEventMetadata(M,this.roomState,!1),M.setThread(this))}clearEventMetadata(M){if(M){var L,B,N;M.setThread(void 0),(L=M.event)===null||L===void 0||(B=L.unsigned)===null||B===void 0||(N=B["m.relations"])===null||N===void 0||delete N[w.name]}}findEventById(M){return this.timelineSet.findEventById(M)}lastReply(M=()=>!0){for(let L=this.timeline.length-1;L>=0;L--){const B=this.timeline[L];if(M(B))return B}return null}get roomId(){return this.room.roomId}get length(){return this.replyCount+this.pendingReplyCount}get replyToEvent(){var M,L;return(M=(L=this.lastPendingEvent)!==null&&L!==void 0?L:this.lastEvent)!==null&&M!==void 0?M:this.lastReply()}get events(){return this.liveTimeline.getEvents()}has(M){return this.timelineSet.findEventById(M)instanceof o.MatrixEvent}get hasCurrentUserParticipated(){return this._currentUserParticipated}get liveTimeline(){return this.timelineSet.getLiveTimeline()}getUnfilteredTimelineSet(){return this.timelineSet}addReceipt(M,L){throw new Error("Unsupported function on the thread model")}hasUserReadEvent(M,L){if(M===this.client.getUserId()){const B=this.getReadReceiptForUserId(M,!1,y.ReceiptType.Read),N=this.getReadReceiptForUserId(M,!1,y.ReceiptType.ReadPrivate),G=this.room.getThreadUnreadNotificationCount(this.id,f.NotificationCountType.Total)>0;if(!B&&!N&&!G)return!0}return super.hasUserReadEvent(M,L)}}Et.Thread=l,(0,t.default)(l,"hasServerSideSupport",_.None),(0,t.default)(l,"hasServerSideListSupport",_.None),(0,t.default)(l,"hasServerSideFwdPaginationSupport",_.None);const d=new v.ServerControlledNamespacedValue("related_by_senders","io.element.relation_senders");Et.FILTER_RELATED_BY_SENDERS=d;const h=new v.ServerControlledNamespacedValue("related_by_rel_types","io.element.relation_types");Et.FILTER_RELATED_BY_REL_TYPES=h;const w=new v.ServerControlledNamespacedValue("m.thread","io.element.thread");Et.THREAD_RELATION_TYPE=w;let E;Et.ThreadFilterType=E,function(k){k[k.My=0]="My",k[k.All=1]="All"}(E||(Et.ThreadFilterType=E={}));function I(k){switch(k){case E.My:return"participated";default:return"all"}}return Et}var Hb;function nn(){return Hb||(Hb=1,function(e){var t=Ae;Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"EventStatus",{enumerable:!0,get:function(){return s.EventStatus}}),e.MatrixEventEvent=e.MatrixEvent=void 0;var n=t(Ue),r=Fu,i=Ge(),o=xe,a=lt(),c=zf(),f=rs(),v=Pt(),s=xP();const g=Object.freeze({visible:!0});let y;e.MatrixEventEvent=y,function(_){_.Decrypted="Event.decrypted",_.BeforeRedaction="Event.beforeRedaction",_.VisibilityChange="Event.visibilityChange",_.LocalEventIdReplaced="Event.localEventIdReplaced",_.Status="Event.status",_.Replaced="Event.replaced",_.RelationsCreated="Event.relationsCreated"}(y||(e.MatrixEventEvent=y={}));class S extends v.TypedEventEmitter{constructor(u={}){var l;super(),this.event=u,(0,n.default)(this,"pushActions",null),(0,n.default)(this,"_replacingEvent",null),(0,n.default)(this,"_localRedactionEvent",null),(0,n.default)(this,"_isCancelled",!1),(0,n.default)(this,"clearEvent",void 0),(0,n.default)(this,"visibility",g),(0,n.default)(this,"_hasCachedExtEv",!1),(0,n.default)(this,"_cachedExtEv",void 0),(0,n.default)(this,"senderCurve25519Key",null),(0,n.default)(this,"claimedEd25519Key",null),(0,n.default)(this,"forwardingCurve25519KeyChain",[]),(0,n.default)(this,"untrusted",null),(0,n.default)(this,"decryptionPromise",null),(0,n.default)(this,"retryDecryption",!1),(0,n.default)(this,"txnId",void 0),(0,n.default)(this,"thread",void 0),(0,n.default)(this,"threadId",void 0),(0,n.default)(this,"localTimestamp",void 0),(0,n.default)(this,"sender",null),(0,n.default)(this,"target",null),(0,n.default)(this,"status",null),(0,n.default)(this,"error",null),(0,n.default)(this,"forwardLooking",!0),(0,n.default)(this,"verificationRequest",void 0),(0,n.default)(this,"reEmitter",void 0),["state_key","type","sender","room_id","membership"].forEach(d=>{typeof u[d]=="string"&&(u[d]=(0,a.internaliseString)(u[d]))}),["membership","avatar_url","displayname"].forEach(d=>{var h;typeof((h=u.content)===null||h===void 0?void 0:h[d])=="string"&&(u.content[d]=(0,a.internaliseString)(u.content[d]))}),["rel_type"].forEach(d=>{var h,w;typeof((h=u.content)===null||h===void 0||(w=h["m.relates_to"])===null||w===void 0?void 0:w[d])=="string"&&(u.content["m.relates_to"][d]=(0,a.internaliseString)(u.content["m.relates_to"][d]))}),this.txnId=u.txn_id,this.localTimestamp=Date.now()-((l=this.getAge())!==null&&l!==void 0?l:0),this.reEmitter=new f.TypedReEmitter(this)}get unstableExtensibleEvent(){return this._hasCachedExtEv||(this._cachedExtEv=r.ExtensibleEvents.parse(this.getEffectiveEvent())),this._cachedExtEv}invalidateExtensibleEvent(){this._hasCachedExtEv=!1}getEffectiveEvent(){const u=Object.assign({},this.getContent());if(this.getWireType()===o.EventType.RoomMessageEncrypted)for(const[l,d]of Object.entries(this.getWireContent()))["algorithm","ciphertext","device_id","sender_key","session_id"].includes(l)||u[l]===void 0&&(u[l]=d);return Object.assign({},this.event,this.clearEvent,{content:u})}getId(){return this.event.event_id}getSender(){return this.event.sender||this.event.user_id}getType(){return this.clearEvent?this.clearEvent.type:this.event.type}getWireType(){return this.event.type}getRoomId(){return this.event.room_id}getTs(){return this.event.origin_server_ts}getDate(){return this.event.origin_server_ts?new Date(this.event.origin_server_ts):null}getDetails(){let u=`id=${this.getId()} type=${this.getWireType()} sender=${this.getSender()}`;const l=this.getRoomId();l&&(u+=` room=${l}`);const d=this.getDate();return d&&(u+=` ts=${d.toISOString()}`),u}getOriginalContent(){return this._localRedactionEvent?{}:this.clearEvent?this.clearEvent.content||{}:this.event.content||{}}getContent(){return this._localRedactionEvent?{}:this._replacingEvent?this._replacingEvent.getContent()["m.new_content"]||{}:this.getOriginalContent()}getWireContent(){return this.event.content||{}}get threadRootId(){var u;const l=(u=this.getWireContent())===null||u===void 0?void 0:u["m.relates_to"];if((l==null?void 0:l.rel_type)===c.THREAD_RELATION_TYPE.name)return l.event_id;var d;return((d=this.getThread())===null||d===void 0?void 0:d.id)||this.threadId}get isThreadRoot(){var u;return!!this.getServerAggregatedRelation(c.THREAD_RELATION_TYPE.name)||((u=this.getThread())===null||u===void 0?void 0:u.id)===this.getId()}get replyEventId(){var u;const l=this.getContent()["m.relates_to"]||this.getWireContent()["m.relates_to"];return l==null||(u=l["m.in_reply_to"])===null||u===void 0?void 0:u.event_id}get relationEventId(){var u,l;return(u=this.getWireContent())===null||u===void 0||(l=u["m.relates_to"])===null||l===void 0?void 0:l.event_id}getPrevContent(){return this.getUnsigned().prev_content||this.event.prev_content||{}}getDirectionalContent(){return this.forwardLooking?this.getContent():this.getPrevContent()}getAge(){return this.getUnsigned().age||this.event.age}getLocalAge(){return Date.now()-this.localTimestamp}getStateKey(){return this.event.state_key}isState(){return this.event.state_key!==void 0}makeEncrypted(u,l,d,h){this.clearEvent={type:this.event.type,content:this.event.content},this.event.type=u,this.event.content=l,this.senderCurve25519Key=d,this.claimedEd25519Key=h}isBeingDecrypted(){return this.decryptionPromise!=null}getDecryptionPromise(){return this.decryptionPromise}isDecryptionFailure(){var u,l;return((u=this.clearEvent)===null||u===void 0||(l=u.content)===null||l===void 0?void 0:l.msgtype)==="m.bad.encrypted"}shouldAttemptDecryption(){return!(this.isRedacted()||this.isBeingDecrypted()||this.clearEvent||!this.isEncrypted())}async attemptDecryption(u,l={}){if(!this.isEncrypted())throw new Error("Attempt to decrypt event which isn't encrypted");const d=this.clearEvent&&!this.isDecryptionFailure(),h=l.forceRedecryptIfUntrusted&&this.isKeySourceUntrusted();if(d&&!h)throw new Error("Attempt to decrypt event which has already been decrypted");return this.decryptionPromise?(i.logger.log(`Event ${this.getId()} already being decrypted; queueing a retry`),this.retryDecryption=!0,this.decryptionPromise):(this.decryptionPromise=this.decryptionLoop(u,l),this.decryptionPromise)}cancelAndResendKeyRequest(u,l){const d=this.getWireContent();return u.requestRoomKey({algorithm:d.algorithm,room_id:this.getRoomId(),session_id:d.session_id,sender_key:d.sender_key},this.getKeyRequestRecipients(l),!0)}getKeyRequestRecipients(u){const l=this.getWireContent(),d=[{userId:u,deviceId:"*"}],h=this.getSender();return h!==u&&d.push({userId:h,deviceId:l.device_id}),d}async decryptionLoop(u,l={}){for(await Promise.resolve();;){this.retryDecryption=!1;let d,h;try{u?(d=await u.decryptEvent(this),l.isRetry===!0&&i.logger.info(`Decrypted event on retry (${this.getDetails()})`)):d=this.badEncryptedMessage("Encryption not enabled")}catch(w){if(w.name!=="DecryptionError"){const E=l.isRetry?"re":"";i.logger.error(`Error ${E}decrypting event (${this.getDetails()})`,w),this.decryptionPromise=null,this.retryDecryption=!1;return}if(h=w,this.retryDecryption){i.logger.log(`Error decrypting event (${this.getDetails()}), but retrying: `+w.detailedString);continue}i.logger.warn(`Error decrypting event (${this.getDetails()}): `+w.detailedString),d=this.badEncryptedMessage(w.message)}this.decryptionPromise=null,this.retryDecryption=!1,this.setClearData(d),this.setPushActions(null),l.emit!==!1&&this.emit(y.Decrypted,this,h);return}}badEncryptedMessage(u){return{clearEvent:{type:o.EventType.RoomMessage,content:{msgtype:"m.bad.encrypted",body:"** Unable to decrypt: "+u+" **"}}}}setClearData(u){var l,d;this.clearEvent=u.clearEvent,this.senderCurve25519Key=(l=u.senderCurve25519Key)!==null&&l!==void 0?l:null,this.claimedEd25519Key=(d=u.claimedEd25519Key)!==null&&d!==void 0?d:null,this.forwardingCurve25519KeyChain=u.forwardingCurve25519KeyChain||[],this.untrusted=u.untrusted||!1,this.invalidateExtensibleEvent()}getClearContent(){return this.clearEvent?this.clearEvent.content:null}isEncrypted(){return!this.isState()&&this.event.type===o.EventType.RoomMessageEncrypted}getSenderKey(){return this.senderCurve25519Key}getKeysClaimed(){return this.claimedEd25519Key?{ed25519:this.claimedEd25519Key}:{}}getClaimedEd25519Key(){return this.claimedEd25519Key}getForwardingCurve25519KeyChain(){return this.forwardingCurve25519KeyChain}isKeySourceUntrusted(){return!!this.untrusted}getUnsigned(){return this.event.unsigned||{}}setUnsigned(u){this.event.unsigned=u}unmarkLocallyRedacted(){const u=this._localRedactionEvent;return this._localRedactionEvent=null,this.event.unsigned&&(this.event.unsigned.redacted_because=void 0),!!u}markLocallyRedacted(u){this._localRedactionEvent||(this.emit(y.BeforeRedaction,this,u),this._localRedactionEvent=u,this.event.unsigned||(this.event.unsigned={}),this.event.unsigned.redacted_because=u.event)}applyVisibilityEvent(u){var l,d;const h=(l=u==null?void 0:u.visible)!==null&&l!==void 0?l:!0,w=(d=u==null?void 0:u.reason)!==null&&d!==void 0?d:null;let E=!1;(this.visibility.visible!==h||!this.visibility.visible&&this.visibility.reason!==w)&&(E=!0),E&&(h?this.visibility=g:this.visibility=Object.freeze({visible:!1,reason:w}),this.emit(y.VisibilityChange,this,h))}messageVisibility(){return this.visibility}makeRedacted(u){if(!u.event)throw new Error("invalid redactionEvent in makeRedacted");this._localRedactionEvent=null,this.emit(y.BeforeRedaction,this,u),this._replacingEvent=null,this.event.unsigned||(this.event.unsigned={}),this.event.unsigned.redacted_because=u.event;for(const h in this.event)this.event.hasOwnProperty(h)&&!m.has(h)&&delete this.event[h];this.isEncrypted()&&(this.clearEvent=void 0);const l=this.getType()in p?p[this.getType()]:{},d=this.getContent();for(const h in d)d.hasOwnProperty(h)&&!l[h]&&delete d[h];this.invalidateExtensibleEvent()}isRedacted(){return Boolean(this.getUnsigned().redacted_because)}isRedaction(){return this.getType()===o.EventType.RoomRedaction}asVisibilityChange(){if(!o.EVENT_VISIBILITY_CHANGE_TYPE.matches(this.getType()))return null;const u=this.getRelation();if(!u||u.rel_type!="m.reference")return null;const l=u.event_id;if(!l)return null;const d=this.getWireContent(),h=!!d.visible,w=d.reason;return w&&typeof w!="string"?null:{visible:h,reason:w,eventId:l}}isVisibilityEvent(){return o.EVENT_VISIBILITY_CHANGE_TYPE.matches(this.getType())}getRedactionEvent(){var u,l;if(!this.isRedacted())return null;if((u=this.clearEvent)!==null&&u!==void 0&&u.unsigned){var d,h;return(d=(h=this.clearEvent)===null||h===void 0?void 0:h.unsigned.redacted_because)!==null&&d!==void 0?d:null}else return(l=this.event.unsigned)!==null&&l!==void 0&&l.redacted_because?this.event.unsigned.redacted_because:{}}getPushActions(){return this.pushActions}setPushActions(u){this.pushActions=u}handleRemoteEcho(u){const l=this.getUnsigned(),d=this.getId();this.event=u,l.redacted_because&&(this.event.unsigned||(this.event.unsigned={}),this.event.unsigned.redacted_because=l.redacted_because),this.setStatus(null),this.getId()!==d&&this.emit(y.LocalEventIdReplaced,this),this.localTimestamp=Date.now()-this.getAge()}isSending(){return!!this.status}setStatus(u){this.status=u,this.emit(y.Status,this,u)}replaceLocalEventId(u){this.event.event_id=u,this.emit(y.LocalEventIdReplaced,this)}isRelation(u){var l;const d=(l=this.getWireContent())===null||l===void 0?void 0:l["m.relates_to"];return this.isState()&&(d==null?void 0:d.rel_type)===o.RelationType.Replace?!1:!!(d!=null&&d.rel_type&&d.event_id&&(!u||d.rel_type===u))}getRelation(){var u;return this.isRelation()&&(u=this.getWireContent()["m.relates_to"])!==null&&u!==void 0?u:null}makeReplaced(u){this.isRedacted()&&u||this.isState()||this._replacingEvent!==u&&(this._replacingEvent=u??null,this.emit(y.Replaced,this),this.invalidateExtensibleEvent())}getAssociatedStatus(){return this._replacingEvent?this._replacingEvent.status:this._localRedactionEvent?this._localRedactionEvent.status:this.status}getServerAggregatedRelation(u){var l;return(l=this.getUnsigned()["m.relations"])===null||l===void 0?void 0:l[u]}replacingEventId(){const u=this.getServerAggregatedRelation(o.RelationType.Replace);if(u)return u.event_id;if(this._replacingEvent)return this._replacingEvent.getId()}replacingEvent(){return this._replacingEvent}replacingEventDate(){const u=this.getServerAggregatedRelation(o.RelationType.Replace);if(u){const d=u.origin_server_ts;if(Number.isFinite(d))return new Date(d)}else if(this._replacingEvent){var l;return(l=this._replacingEvent.getDate())!==null&&l!==void 0?l:void 0}}localRedactionEvent(){return this._localRedactionEvent}getAssociatedId(){const u=this.getRelation();if(this.replyEventId)return this.replyEventId;if(u)return u.event_id;if(this.isRedaction())return this.event.redacts}hasAssocation(){return!!this.getAssociatedId()}hasAssociation(){return!!this.getAssociatedId()}updateAssociatedId(u){const l=this.getRelation();l?l.event_id=u:this.isRedaction()&&(this.event.redacts=u)}flagCancelled(u=!0){this._isCancelled=u}isCancelled(){return this._isCancelled}toSnapshot(){const u=new S(JSON.parse(JSON.stringify(this.event)));for(const[l,d]of Object.entries(this))l!=="event"&&(u[l]=d);return u}isEquivalentTo(u){if(!u)return!1;if(u===this)return!0;const l=(0,a.deepSortedObjectEntries)(this.event),d=(0,a.deepSortedObjectEntries)(u.event);return JSON.stringify(l)===JSON.stringify(d)}toJSON(){const u=this.getEffectiveEvent();return this.isEncrypted()?{decrypted:u,encrypted:this.event}:u}setVerificationRequest(u){this.verificationRequest=u}setTxnId(u){this.txnId=u}getTxnId(){return this.txnId}setThread(u){this.thread&&this.reEmitter.stopReEmitting(this.thread,[c.ThreadEvent.Update]),this.thread=u,this.setThreadId(u==null?void 0:u.id),u&&this.reEmitter.reEmit(u,[c.ThreadEvent.Update])}getThread(){return this.thread}setThreadId(u){this.threadId=u}}e.MatrixEvent=S;const m=new Set(["event_id","type","room_id","user_id","sender","state_key","prev_state","content","unsigned","origin_server_ts"]),p={[o.EventType.RoomMember]:{membership:1},[o.EventType.RoomCreate]:{creator:1},[o.EventType.RoomJoinRules]:{join_rule:1},[o.EventType.RoomPowerLevels]:{ban:1,events:1,events_default:1,kick:1,redact:1,state_default:1,users:1,users_default:1}}}(gp)),gp}var Gb;function po(){if(Gb)return mi;Gb=1;var e=Ae;Object.defineProperty(mi,"__esModule",{value:!0}),mi.RoomStateEvent=mi.RoomState=void 0;var t=e(Ue),n=Zn,r=Ge(),i=S(lt()),o=xe,a=nn(),c=yt,f=Pt(),v=bn,s=rs(),g=vk();function y(d){if(typeof WeakMap!="function")return null;var h=new WeakMap,w=new WeakMap;return(y=function(E){return E?w:h})(d)}function S(d,h){if(!h&&d&&d.__esModule)return d;if(d===null||typeof d!="object"&&typeof d!="function")return{default:d};var w=y(h);if(w&&w.has(d))return w.get(d);var E={},I=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var k in d)if(k!=="default"&&Object.prototype.hasOwnProperty.call(d,k)){var M=I?Object.getOwnPropertyDescriptor(d,k):null;M&&(M.get||M.set)?Object.defineProperty(E,k,M):E[k]=d[k]}return E.default=d,w&&w.set(d,E),E}function m(d,h){var w=Object.keys(d);if(Object.getOwnPropertySymbols){var E=Object.getOwnPropertySymbols(d);h&&(E=E.filter(function(I){return Object.getOwnPropertyDescriptor(d,I).enumerable})),w.push.apply(w,E)}return w}function p(d){for(var h=1;h<arguments.length;h++){var w=arguments[h]!=null?arguments[h]:{};h%2?m(Object(w),!0).forEach(function(E){(0,t.default)(d,E,w[E])}):Object.getOwnPropertyDescriptors?Object.defineProperties(d,Object.getOwnPropertyDescriptors(w)):m(Object(w)).forEach(function(E){Object.defineProperty(d,E,Object.getOwnPropertyDescriptor(w,E))})}return d}var _;(function(d){d[d.NotStarted=0]="NotStarted",d[d.InProgress=1]="InProgress",d[d.Finished=2]="Finished"})(_||(_={}));let u;mi.RoomStateEvent=u,function(d){d.Events="RoomState.events",d.Members="RoomState.members",d.NewMember="RoomState.newMember",d.Update="RoomState.update",d.BeaconLiveness="RoomState.BeaconLiveness",d.Marker="RoomState.Marker"}(u||(mi.RoomStateEvent=u={}));class l extends f.TypedEventEmitter{constructor(h,w={status:_.NotStarted}){super(),this.roomId=h,this.oobMemberFlags=w,(0,t.default)(this,"reEmitter",new s.TypedReEmitter(this)),(0,t.default)(this,"sentinels",{}),(0,t.default)(this,"displayNameToUserIds",new Map),(0,t.default)(this,"userIdsToDisplayNames",{}),(0,t.default)(this,"tokenToInvite",{}),(0,t.default)(this,"joinedMemberCount",null),(0,t.default)(this,"summaryJoinedMemberCount",null),(0,t.default)(this,"invitedMemberCount",null),(0,t.default)(this,"summaryInvitedMemberCount",null),(0,t.default)(this,"modified",-1),(0,t.default)(this,"members",{}),(0,t.default)(this,"events",new Map),(0,t.default)(this,"paginationToken",null),(0,t.default)(this,"beacons",new Map),(0,t.default)(this,"_liveBeaconIds",[]),this.updateModifiedTime()}getJoinedMemberCount(){return this.summaryJoinedMemberCount!==null?this.summaryJoinedMemberCount:(this.joinedMemberCount===null&&(this.joinedMemberCount=this.getMembers().reduce((h,w)=>w.membership==="join"?h+1:h,0)),this.joinedMemberCount)}setJoinedMemberCount(h){this.summaryJoinedMemberCount=h}getInvitedMemberCount(){return this.summaryInvitedMemberCount!==null?this.summaryInvitedMemberCount:(this.invitedMemberCount===null&&(this.invitedMemberCount=this.getMembers().reduce((h,w)=>w.membership==="invite"?h+1:h,0)),this.invitedMemberCount)}setInvitedMemberCount(h){this.summaryInvitedMemberCount=h}getMembers(){return Object.values(this.members)}getMembersExcept(h){return this.getMembers().filter(w=>!h.includes(w.userId))}getMember(h){return this.members[h]||null}getSentinelMember(h){if(!h)return null;let w=this.sentinels[h];if(w===void 0){w=new n.RoomMember(this.roomId,h);const E=this.members[h];E!=null&&E.events.member&&w.setMembershipEvent(E.events.member,this),this.sentinels[h]=w}return w}getStateEvents(h,w){if(!this.events.has(h))return w===void 0?[]:null;if(w===void 0)return Array.from(this.events.get(h).values());const E=this.events.get(h).get(w);return E||null}get hasLiveBeacons(){var h;return!!((h=this.liveBeaconIds)!==null&&h!==void 0&&h.length)}get liveBeaconIds(){return this._liveBeaconIds}clone(){const h=new l(this.roomId,this.oobMemberFlags),w=this.oobMemberFlags.status;return this.oobMemberFlags.status=_.NotStarted,Array.from(this.events.values()).forEach(E=>{h.setStateEvents(Array.from(E.values()))}),this.oobMemberFlags.status=w,this.summaryInvitedMemberCount!==null&&h.setInvitedMemberCount(this.getInvitedMemberCount()),this.summaryJoinedMemberCount!==null&&h.setJoinedMemberCount(this.getJoinedMemberCount()),this.oobMemberFlags.status==_.Finished&&this.getMembers().forEach(E=>{if(E.isOutOfBand()){var I;(I=h.getMember(E.userId))===null||I===void 0||I.markOutOfBand()}}),h}setUnknownStateEvents(h){const w=h.filter(E=>!this.events.has(E.getType())||!this.events.get(E.getType()).has(E.getStateKey()));this.setStateEvents(w)}setStateEvents(h,w){this.updateModifiedTime(),h.forEach(E=>{if(E.getRoomId()!==this.roomId||!E.isState())return;g.M_BEACON_INFO.matches(E.getType())&&this.setBeacon(E);const I=this.getStateEventMatching(E);if(this.setStateEvent(E),E.getType()===o.EventType.RoomMember){var k;this.updateDisplayNameCache(E.getStateKey(),(k=E.getContent().displayname)!==null&&k!==void 0?k:""),this.updateThirdPartyTokenCache(E)}this.emit(u.Events,E,this,I)}),this.onBeaconLivenessChange(),h.forEach(E=>{if(!(E.getRoomId()!==this.roomId||!E.isState()))if(E.getType()===o.EventType.RoomMember){const I=E.getStateKey();(E.getContent().membership==="leave"||E.getContent().membership==="ban")&&(E.getContent().avatar_url=E.getContent().avatar_url||E.getPrevContent().avatar_url,E.getContent().displayname=E.getContent().displayname||E.getPrevContent().displayname);const k=this.getOrCreateMember(I,E);k.setMembershipEvent(E,this),this.updateMember(k),this.emit(u.Members,E,this,k)}else if(E.getType()===o.EventType.RoomPowerLevels){if(E.getStateKey()!=="")return;Object.values(this.members).forEach(k=>{const M=k.getLastModifiedTime();k.setPowerLevelEvent(E),M!==k.getLastModifiedTime()&&this.emit(u.Members,E,this,k)}),this.sentinels={}}else o.UNSTABLE_MSC2716_MARKER.matches(E.getType())&&this.emit(u.Marker,E,w)}),this.emit(u.Update,this)}processBeaconEvents(h,w){if(!h.length||!this.beacons.size)return;const E=[...this.beacons.values()].reduce((k,M)=>p(p({},k),{},{[M.beaconInfoId]:M}),{}),I=(k,M)=>{if(!g.M_BEACON.matches(M.getType()))return;const L=E[k];L&&L.addLocations([M])};h.forEach(k=>{var M;const L=(M=k.getRelation())===null||M===void 0?void 0:M.event_id;!L||!E[L]||(w.decryptEventIfNeeded(k),k.isBeingDecrypted()||k.isDecryptionFailure()?k.once(a.MatrixEventEvent.Decrypted,async()=>{I(L,k)}):I(L,k))})}getOrCreateMember(h,w){let E=this.members[h];return E||(E=new n.RoomMember(this.roomId,h),this.members[h]=E,this.emit(u.NewMember,w,this,E)),E}setStateEvent(h){this.events.has(h.getType())||this.events.set(h.getType(),new Map),this.events.get(h.getType()).set(h.getStateKey(),h)}setBeacon(h){const w=(0,v.getBeaconInfoIdentifier)(h);if(this.beacons.has(w)){const k=this.beacons.get(w);if(h.isRedacted()){var E;k.beaconInfoId===((E=h.getRedactionEvent())===null||E===void 0?void 0:E.redacts)&&(k.destroy(),this.beacons.delete(w));return}return k.update(h)}if(h.isRedacted())return;const I=new v.Beacon(h);this.reEmitter.reEmit(I,[v.BeaconEvent.New,v.BeaconEvent.Update,v.BeaconEvent.Destroy,v.BeaconEvent.LivenessChange]),this.emit(v.BeaconEvent.New,h,I),I.on(v.BeaconEvent.LivenessChange,this.onBeaconLivenessChange.bind(this)),I.on(v.BeaconEvent.Destroy,this.onBeaconLivenessChange.bind(this)),this.beacons.set(I.identifier,I)}onBeaconLivenessChange(){this._liveBeaconIds=Array.from(this.beacons.values()).filter(h=>h.isLive).map(h=>h.identifier),this.emit(u.BeaconLiveness,this,this.hasLiveBeacons)}getStateEventMatching(h){var w,E;return(w=(E=this.events.get(h.getType()))===null||E===void 0?void 0:E.get(h.getStateKey()))!==null&&w!==void 0?w:null}updateMember(h){const w=this.getStateEvents(o.EventType.RoomPowerLevels,"");w&&h.setPowerLevelEvent(w),delete this.sentinels[h.userId],this.members[h.userId]=h,this.joinedMemberCount=null,this.invitedMemberCount=null}needsOutOfBandMembers(){return this.oobMemberFlags.status===_.NotStarted}markOutOfBandMembersStarted(){this.oobMemberFlags.status===_.NotStarted&&(this.oobMemberFlags.status=_.InProgress)}markOutOfBandMembersFailed(){this.oobMemberFlags.status===_.InProgress&&(this.oobMemberFlags.status=_.NotStarted)}clearOutOfBandMembers(){let h=0;Object.keys(this.members).forEach(w=>{this.members[w].isOutOfBand()&&(++h,delete this.members[w])}),r.logger.log(`LL: RoomState removed ${h} members...`),this.oobMemberFlags.status=_.NotStarted}setOutOfBandMembers(h){r.logger.log(`LL: RoomState about to set ${h.length} OOB members ...`),this.oobMemberFlags.status===_.InProgress&&(r.logger.log("LL: RoomState put in finished state ..."),this.oobMemberFlags.status=_.Finished,h.forEach(w=>this.setOutOfBandMember(w)),this.emit(u.Update,this))}setOutOfBandMember(h){if(h.getType()!==o.EventType.RoomMember)return;const w=h.getStateKey(),E=this.getMember(w);if(E&&!E.isOutOfBand())return;const I=this.getOrCreateMember(w,h);I.setMembershipEvent(h,this),I.markOutOfBand(),this.updateDisplayNameCache(I.userId,I.name),this.setStateEvent(h),this.updateMember(I),this.emit(u.Members,h,this,I)}setTypingEvent(h){Object.values(this.members).forEach(function(w){w.setTypingEvent(h)})}getInviteForThreePidToken(h){return this.tokenToInvite[h]||null}updateModifiedTime(){this.modified=Date.now()}getLastModifiedTime(){return this.modified}getUserIdsWithDisplayName(h){var w;return(w=this.displayNameToUserIds.get(i.removeHiddenChars(h)))!==null&&w!==void 0?w:[]}maySendRedactionForEvent(h,w){const E=this.getMember(w);if(!E||E.membership==="leave"||h.status||h.isRedacted())return!1;const I=this.maySendEvent(o.EventType.RoomRedaction,w);return h.getSender()===w?I:this.hasSufficientPowerLevelFor("redact",E.powerLevel)}hasSufficientPowerLevelFor(h,w){const E=this.getStateEvents(o.EventType.RoomPowerLevels,"");let I={};E&&(I=E.getContent());let k=50;return i.isNumber(I[h])&&(k=I[h]),w>=k}maySendMessage(h){return this.maySendEventOfType(o.EventType.RoomMessage,h,!1)}maySendEvent(h,w){return this.maySendEventOfType(h,w,!1)}mayClientSendStateEvent(h,w){return w.isGuest()||!w.credentials.userId?!1:this.maySendStateEvent(h,w.credentials.userId)}maySendStateEvent(h,w){return this.maySendEventOfType(h,w,!0)}maySendEventOfType(h,w,E){const I=this.getStateEvents(o.EventType.RoomPowerLevels,"");let k,M={},L=0,B=0,N=0;if(I){k=I.getContent(),M=k.events||{},Number.isSafeInteger(k.state_default)?L=k.state_default:L=50;const D=k.users&&k.users[w];Number.isSafeInteger(D)?N=D:Number.isSafeInteger(k.users_default)&&(N=k.users_default),Number.isSafeInteger(k.events_default)&&(B=k.events_default)}let G=E?L:B;return Number.isSafeInteger(M[h])&&(G=M[h]),N>=G}mayTriggerNotifOfType(h,w){const E=this.getMember(w);if(!E)return!1;const I=this.getStateEvents(o.EventType.RoomPowerLevels,"");let k=50;return I&&I.getContent()&&I.getContent().notifications&&i.isNumber(I.getContent().notifications[h])&&(k=I.getContent().notifications[h]),E.powerLevel>=k}getJoinRule(){var h;const w=this.getStateEvents(o.EventType.RoomJoinRules,"");return((h=w==null?void 0:w.getContent())!==null&&h!==void 0?h:{}).join_rule||c.JoinRule.Invite}getHistoryVisibility(){var h;const w=this.getStateEvents(o.EventType.RoomHistoryVisibility,"");return((h=w==null?void 0:w.getContent())!==null&&h!==void 0?h:{}).history_visibility||c.HistoryVisibility.Shared}getGuestAccess(){var h;const w=this.getStateEvents(o.EventType.RoomGuestAccess,"");return((h=w==null?void 0:w.getContent())!==null&&h!==void 0?h:{}).guest_access||c.GuestAccess.Forbidden}updateThirdPartyTokenCache(h){if(!h.getContent().third_party_invite)return;const w=(h.getContent().third_party_invite.signed||{}).token;!w||!this.getStateEvents(o.EventType.RoomThirdPartyInvite,w)||(this.tokenToInvite[w]=h)}updateDisplayNameCache(h,w){const E=this.userIdsToDisplayNames[h];if(delete this.userIdsToDisplayNames[h],E){const M=i.removeHiddenChars(E),L=this.displayNameToUserIds.get(M);if(L){const B=L.filter(N=>N!==h);this.displayNameToUserIds.set(M,B)}}this.userIdsToDisplayNames[h]=w;const I=w&&i.removeHiddenChars(w);if(I){var k;const M=(k=this.displayNameToUserIds.get(I))!==null&&k!==void 0?k:[];M.push(h),this.displayNameToUserIds.set(I,M)}}}return mi.RoomState=l,mi}var Y3=Ae;Object.defineProperty(Bu,"__esModule",{value:!0});Bu.MemoryStore=void 0;var Wn=Y3(Ue),Q3=Xn,zb=po();function Yb(e){return typeof e=="string"&&!!e&&e!=="undefined"&&e!=="null"||typeof e=="number"}class J3{constructor(t={}){(0,Wn.default)(this,"rooms",{}),(0,Wn.default)(this,"users",{}),(0,Wn.default)(this,"syncToken",null),(0,Wn.default)(this,"filters",{}),(0,Wn.default)(this,"accountData",{}),(0,Wn.default)(this,"localStorage",void 0),(0,Wn.default)(this,"oobMembers",{}),(0,Wn.default)(this,"pendingEvents",{}),(0,Wn.default)(this,"clientOptions",void 0),(0,Wn.default)(this,"pendingToDeviceBatches",[]),(0,Wn.default)(this,"nextToDeviceBatchId",0),(0,Wn.default)(this,"onRoomMember",(n,r,i)=>{if(i.membership==="invite")return;const o=this.users[i.userId]||new Q3.User(i.userId);i.name&&(o.setDisplayName(i.name),i.events.member&&o.setRawDisplayName(i.events.member.getDirectionalContent().displayname)),i.events.member&&i.events.member.getContent().avatar_url&&o.setAvatarUrl(i.events.member.getContent().avatar_url),this.users[o.userId]=o}),this.localStorage=t.localStorage}getSyncToken(){return this.syncToken}isNewlyCreated(){return Promise.resolve(!0)}setSyncToken(t){this.syncToken=t}storeRoom(t){this.rooms[t.roomId]=t,t.currentState.on(zb.RoomStateEvent.Members,this.onRoomMember),t.currentState.getMembers().forEach(n=>{this.onRoomMember(null,t.currentState,n)})}getRoom(t){return this.rooms[t]||null}getRooms(){return Object.values(this.rooms)}removeRoom(t){this.rooms[t]&&this.rooms[t].currentState.removeListener(zb.RoomStateEvent.Members,this.onRoomMember),delete this.rooms[t]}getRoomSummaries(){return Object.values(this.rooms).map(function(t){return t.summary})}storeUser(t){this.users[t.userId]=t}getUser(t){return this.users[t]||null}getUsers(){return Object.values(this.users)}scrollback(t,n){return[]}storeEvents(t,n,r,i){}storeFilter(t){!(t!=null&&t.userId)||!(t!=null&&t.filterId)||(this.filters[t.userId]||(this.filters[t.userId]={}),this.filters[t.userId][t.filterId]=t)}getFilter(t,n){return!this.filters[t]||!this.filters[t][n]?null:this.filters[t][n]}getFilterIdByName(t){if(!this.localStorage)return null;const n="mxjssdk_memory_filter_"+t;try{const r=this.localStorage.getItem(n);if(Yb(r))return r}catch{}return null}setFilterIdByName(t,n){if(!this.localStorage)return;const r="mxjssdk_memory_filter_"+t;try{Yb(n)?this.localStorage.setItem(r,n):this.localStorage.removeItem(r)}catch{}}storeAccountDataEvents(t){t.forEach(n=>{this.accountData[n.getType()]=n})}getAccountData(t){return this.accountData[t]}setSyncData(t){return Promise.resolve()}wantsSave(){return!1}save(t){}startup(){return Promise.resolve()}getSavedSync(){return Promise.resolve(null)}getSavedSyncToken(){return Promise.resolve(null)}deleteAllData(){return this.rooms={},this.users={},this.syncToken=null,this.filters={},this.accountData={},Promise.resolve()}getOutOfBandMembers(t){return Promise.resolve(this.oobMembers[t]||null)}setOutOfBandMembers(t,n){return this.oobMembers[t]=n,Promise.resolve()}clearOutOfBandMembers(t){return this.oobMembers={},Promise.resolve()}getClientOptions(){return Promise.resolve(this.clientOptions)}storeClientOptions(t){return this.clientOptions=Object.assign({},t),Promise.resolve()}async getPendingEvents(t){var n;return(n=this.pendingEvents[t])!==null&&n!==void 0?n:[]}async setPendingEvents(t,n){this.pendingEvents[t]=n}saveToDeviceBatches(t){for(const n of t)this.pendingToDeviceBatches.push({id:this.nextToDeviceBatchId++,eventType:n.eventType,txnId:n.txnId,batch:n.batch});return Promise.resolve()}async getOldestToDeviceBatch(){return this.pendingToDeviceBatches.length===0?null:this.pendingToDeviceBatches[0]}removeToDeviceBatch(t){return this.pendingToDeviceBatches=this.pendingToDeviceBatches.filter(n=>n.id!==t),Promise.resolve()}}Bu.MemoryStore=J3;var Yf={},xp={},pl={},Co={},Qb;function l_(){if(Qb)return Co;Qb=1,Object.defineProperty(Co,"__esModule",{value:!0}),Co.WidgetApiDirection=void 0,Co.invertedDirection=t;var e;Co.WidgetApiDirection=e,function(n){n.ToWidget="toWidget",n.FromWidget="fromWidget"}(e||(Co.WidgetApiDirection=e={}));function t(n){if(n===e.ToWidget)return e.FromWidget;if(n===e.FromWidget)return e.ToWidget;throw new Error("Invalid direction")}return Co}var ar={},Jb;function u_(){if(Jb)return ar;Jb=1,Object.defineProperty(ar,"__esModule",{value:!0}),ar.UnstableApiVersion=ar.MatrixApiVersion=ar.CurrentApiVersions=void 0;var e;ar.MatrixApiVersion=e,function(r){r.Prerelease1="0.0.1",r.Prerelease2="0.0.2"}(e||(ar.MatrixApiVersion=e={}));var t;ar.UnstableApiVersion=t,function(r){r.MSC2762="org.matrix.msc2762",r.MSC2871="org.matrix.msc2871",r.MSC2931="org.matrix.msc2931",r.MSC2974="org.matrix.msc2974",r.MSC2876="org.matrix.msc2876",r.MSC3819="org.matrix.msc3819",r.MSC3846="town.robin.msc3846",r.MSC3869="org.matrix.msc3869"}(t||(ar.UnstableApiVersion=t={}));var n=[e.Prerelease1,e.Prerelease2,t.MSC2762,t.MSC2871,t.MSC2931,t.MSC2974,t.MSC2876,t.MSC3819,t.MSC3846,t.MSC3869];return ar.CurrentApiVersions=n,ar}var gl={},Xb;function c_(){if(Xb)return gl;Xb=1;function e(u){return e=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(l){return typeof l}:function(l){return l&&typeof Symbol=="function"&&l.constructor===Symbol&&l!==Symbol.prototype?"symbol":typeof l},e(u)}Object.defineProperty(gl,"__esModule",{value:!0}),gl.PostmessageTransport=void 0;var t=Uf(),n=Qf();function r(u,l){var d=Object.keys(u);if(Object.getOwnPropertySymbols){var h=Object.getOwnPropertySymbols(u);l&&(h=h.filter(function(w){return Object.getOwnPropertyDescriptor(u,w).enumerable})),d.push.apply(d,h)}return d}function i(u){for(var l=1;l<arguments.length;l++){var d=arguments[l]!=null?arguments[l]:{};l%2?r(Object(d),!0).forEach(function(h){p(u,h,d[h])}):Object.getOwnPropertyDescriptors?Object.defineProperties(u,Object.getOwnPropertyDescriptors(d)):r(Object(d)).forEach(function(h){Object.defineProperty(u,h,Object.getOwnPropertyDescriptor(d,h))})}return u}function o(u,l){if(!(u instanceof l))throw new TypeError("Cannot call a class as a function")}function a(u,l){for(var d=0;d<l.length;d++){var h=l[d];h.enumerable=h.enumerable||!1,h.configurable=!0,"value"in h&&(h.writable=!0),Object.defineProperty(u,h.key,h)}}function c(u,l,d){return l&&a(u.prototype,l),d&&a(u,d),Object.defineProperty(u,"prototype",{writable:!1}),u}function f(u,l){if(typeof l!="function"&&l!==null)throw new TypeError("Super expression must either be null or a function");u.prototype=Object.create(l&&l.prototype,{constructor:{value:u,writable:!0,configurable:!0}}),Object.defineProperty(u,"prototype",{writable:!1}),l&&v(u,l)}function v(u,l){return v=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(h,w){return h.__proto__=w,h},v(u,l)}function s(u){var l=S();return function(){var h=m(u),w;if(l){var E=m(this).constructor;w=Reflect.construct(h,arguments,E)}else w=h.apply(this,arguments);return g(this,w)}}function g(u,l){if(l&&(e(l)==="object"||typeof l=="function"))return l;if(l!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return y(u)}function y(u){if(u===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return u}function S(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}function m(u){return m=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(d){return d.__proto__||Object.getPrototypeOf(d)},m(u)}function p(u,l,d){return l in u?Object.defineProperty(u,l,{value:d,enumerable:!0,configurable:!0,writable:!0}):u[l]=d,u}var _=function(u){f(d,u);var l=s(d);function d(h,w,E,I){var k;return o(this,d),k=l.call(this),k.sendDirection=h,k.initialWidgetId=w,k.transportWindow=E,k.inboundWindow=I,p(y(k),"strictOriginCheck",void 0),p(y(k),"targetOrigin",void 0),p(y(k),"timeoutSeconds",10),p(y(k),"_ready",!1),p(y(k),"_widgetId",null),p(y(k),"outboundRequests",new Map),p(y(k),"stopController",new AbortController),k._widgetId=w,k}return c(d,[{key:"ready",get:function(){return this._ready}},{key:"widgetId",get:function(){return this._widgetId||null}},{key:"nextRequestId",get:function(){for(var w="widgetapi-".concat(Date.now()),E=0,I=w;this.outboundRequests.has(I);)I="".concat(w,"-").concat(E++);return this.outboundRequests.set(I,null),I}},{key:"sendInternal",value:function(w){var E=this.targetOrigin||"*";console.log("[PostmessageTransport] Sending object to ".concat(E,": "),w),this.transportWindow.postMessage(w,E)}},{key:"reply",value:function(w,E){return this.sendInternal(i(i({},w),{},{response:E}))}},{key:"send",value:function(w,E){return this.sendComplete(w,E).then(function(I){return I.response})}},{key:"sendComplete",value:function(w,E){var I=this;if(!this.ready||!this.widgetId)return Promise.reject(new Error("Not ready or unknown widget ID"));var k={api:this.sendDirection,widgetId:this.widgetId,requestId:this.nextRequestId,action:w,data:E};return w===n.WidgetApiToWidgetAction.UpdateVisibility&&(k.visible=E.visible),new Promise(function(M,L){var B=function(W){x(),M(W)},N=function(W){x(),L(W)},G=setTimeout(function(){return N(new Error("Request timed out"))},(I.timeoutSeconds||1)*1e3),D=function(){return N(new Error("Transport stopped"))};I.stopController.signal.addEventListener("abort",D);var x=function(){I.outboundRequests.delete(k.requestId),clearTimeout(G),I.stopController.signal.removeEventListener("abort",D)};I.outboundRequests.set(k.requestId,{request:k,resolve:B,reject:N}),I.sendInternal(k)})}},{key:"start",value:function(){var w=this;this.inboundWindow.addEventListener("message",function(E){w.handleMessage(E)}),this._ready=!0}},{key:"stop",value:function(){this._ready=!1,this.stopController.abort()}},{key:"handleMessage",value:function(w){if(!this.stopController.signal.aborted&&w.data&&!(this.strictOriginCheck&&w.origin!==window.origin)){var E=w.data;if(!(!E.action||!E.requestId||!E.widgetId))if(E.response){if(E.api!==this.sendDirection)return;this.handleResponse(E)}else{var I=E;if(I.api!==(0,n.invertedDirection)(this.sendDirection))return;this.handleRequest(I)}}}},{key:"handleRequest",value:function(w){if(this.widgetId){if(this.widgetId!==w.widgetId)return}else this._widgetId=w.widgetId;this.emit("message",new CustomEvent("message",{detail:w}))}},{key:"handleResponse",value:function(w){if(w.widgetId===this.widgetId){var E=this.outboundRequests.get(w.requestId);if(E)if((0,n.isErrorResponse)(w.response)){var I=w.response;E.reject(new Error(I.error.message))}else E.resolve(w)}}}]),d}(t.EventEmitter);return gl.PostmessageTransport=_,gl}var Yr={},Zb;function d_(){if(Zb)return Yr;Zb=1,Object.defineProperty(Yr,"__esModule",{value:!0}),Yr.WidgetApiToWidgetAction=Yr.WidgetApiFromWidgetAction=void 0;var e;Yr.WidgetApiToWidgetAction=e,function(n){n.SupportedApiVersions="supported_api_versions",n.Capabilities="capabilities",n.NotifyCapabilities="notify_capabilities",n.TakeScreenshot="screenshot",n.UpdateVisibility="visibility",n.OpenIDCredentials="openid_credentials",n.WidgetConfig="widget_config",n.CloseModalWidget="close_modal",n.ButtonClicked="button_clicked",n.SendEvent="send_event",n.SendToDevice="send_to_device",n.UpdateTurnServers="update_turn_servers"}(e||(Yr.WidgetApiToWidgetAction=e={}));var t;return Yr.WidgetApiFromWidgetAction=t,function(n){n.SupportedApiVersions="supported_api_versions",n.ContentLoaded="content_loaded",n.SendSticker="m.sticker",n.UpdateAlwaysOnScreen="set_always_on_screen",n.GetOpenIDCredentials="get_openid",n.CloseModalWidget="close_modal",n.OpenModalWidget="open_modal",n.SetModalButtonEnabled="set_button_enabled",n.SendEvent="send_event",n.SendToDevice="send_to_device",n.WatchTurnServers="watch_turn_servers",n.UnwatchTurnServers="unwatch_turn_servers",n.MSC2876ReadEvents="org.matrix.msc2876.read_events",n.MSC2931Navigate="org.matrix.msc2931.navigate",n.MSC2974RenegotiateCapabilities="org.matrix.msc2974.request_capabilities",n.MSC3869ReadRelations="org.matrix.msc3869.read_relations"}(t||(Yr.WidgetApiFromWidgetAction=t={})),Yr}var _s={},eT;function f_(){if(eT)return _s;eT=1,Object.defineProperty(_s,"__esModule",{value:!0}),_s.OpenIDRequestState=void 0;var e;return _s.OpenIDRequestState=e,function(t){t.Allowed="allowed",t.Blocked="blocked",t.PendingUserConfirmation="request"}(e||(_s.OpenIDRequestState=e={})),_s}var Ss={},tT;function yk(){if(tT)return Ss;tT=1,Object.defineProperty(Ss,"__esModule",{value:!0}),Ss.MatrixWidgetType=void 0;var e;return Ss.MatrixWidgetType=e,function(t){t.Custom="m.custom",t.JitsiMeet="m.jitsi",t.Stickerpicker="m.stickerpicker"}(e||(Ss.MatrixWidgetType=e={})),Ss}var Es={},nT;function _k(){if(nT)return Es;nT=1,Object.defineProperty(Es,"__esModule",{value:!0}),Es.BuiltInModalButtonID=void 0;var e;return Es.BuiltInModalButtonID=e,function(t){t.Close="m.close"}(e||(Es.BuiltInModalButtonID=e={})),Es}var lr={},rT;function h_(){if(rT)return lr;rT=1,Object.defineProperty(lr,"__esModule",{value:!0}),lr.WidgetEventCapability=lr.EventKind=lr.EventDirection=void 0;function e(v,s){var g=typeof Symbol<"u"&&v[Symbol.iterator]||v["@@iterator"];if(!g){if(Array.isArray(v)||(g=t(v))||s&&v&&typeof v.length=="number"){g&&(v=g);var y=0,S=function(){};return{s:S,n:function(){return y>=v.length?{done:!0}:{done:!1,value:v[y++]}},e:function(l){throw l},f:S}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
     87 In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var m=!0,p=!1,_;return{s:function(){g=g.call(v)},n:function(){var l=g.next();return m=l.done,l},e:function(l){p=!0,_=l},f:function(){try{!m&&g.return!=null&&g.return()}finally{if(p)throw _}}}}function t(v,s){if(v){if(typeof v=="string")return n(v,s);var g=Object.prototype.toString.call(v).slice(8,-1);if(g==="Object"&&v.constructor&&(g=v.constructor.name),g==="Map"||g==="Set")return Array.from(v);if(g==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(g))return n(v,s)}}function n(v,s){(s==null||s>v.length)&&(s=v.length);for(var g=0,y=new Array(s);g<s;g++)y[g]=v[g];return y}function r(v,s){if(!(v instanceof s))throw new TypeError("Cannot call a class as a function")}function i(v,s){for(var g=0;g<s.length;g++){var y=s[g];y.enumerable=y.enumerable||!1,y.configurable=!0,"value"in y&&(y.writable=!0),Object.defineProperty(v,y.key,y)}}function o(v,s,g){return s&&i(v.prototype,s),g&&i(v,g),Object.defineProperty(v,"prototype",{writable:!1}),v}var a;lr.EventKind=a,function(v){v.Event="event",v.State="state_event",v.ToDevice="to_device"}(a||(lr.EventKind=a={}));var c;lr.EventDirection=c,function(v){v.Send="send",v.Receive="receive"}(c||(lr.EventDirection=c={}));var f=function(){function v(s,g,y,S,m){r(this,v),this.direction=s,this.eventType=g,this.kind=y,this.keyStr=S,this.raw=m}return o(v,[{key:"matchesAsStateEvent",value:function(g,y,S){return this.kind!==a.State||this.direction!==g||this.eventType!==y?!1:this.keyStr===null||this.keyStr===S}},{key:"matchesAsToDeviceEvent",value:function(g,y){return!(this.kind!==a.ToDevice||this.direction!==g||this.eventType!==y)}},{key:"matchesAsRoomEvent",value:function(g,y){var S=arguments.length>2&&arguments[2]!==void 0?arguments[2]:null;if(this.kind!==a.Event||this.direction!==g||this.eventType!==y)return!1;if(this.eventType==="m.room.message"){if(this.keyStr===null||this.keyStr===S)return!0}else return!0;return!1}}],[{key:"forStateEvent",value:function(g,y,S){y=y.replace(/#/g,"\\#"),S=S!=null?"#".concat(S):"";var m="org.matrix.msc2762.".concat(g,".state_event:").concat(y).concat(S);return v.findEventCapabilities([m])[0]}},{key:"forToDeviceEvent",value:function(g,y){var S="org.matrix.msc3819.".concat(g,".to_device:").concat(y);return v.findEventCapabilities([S])[0]}},{key:"forRoomEvent",value:function(g,y){var S="org.matrix.msc2762.".concat(g,".event:").concat(y);return v.findEventCapabilities([S])[0]}},{key:"forRoomMessageEvent",value:function(g,y){y=y??"";var S="org.matrix.msc2762.".concat(g,".event:m.room.message#").concat(y);return v.findEventCapabilities([S])[0]}},{key:"findEventCapabilities",value:function(g){var y=[],S=e(g),m;try{for(S.s();!(m=S.n()).done;){var p=m.value,_=null,u=void 0,l=null;if(p.startsWith("org.matrix.msc2762.send.event:")?(_=c.Send,l=a.Event,u=p.substring(30)):p.startsWith("org.matrix.msc2762.send.state_event:")?(_=c.Send,l=a.State,u=p.substring(36)):p.startsWith("org.matrix.msc3819.send.to_device:")?(_=c.Send,l=a.ToDevice,u=p.substring(34)):p.startsWith("org.matrix.msc2762.receive.event:")?(_=c.Receive,l=a.Event,u=p.substring(33)):p.startsWith("org.matrix.msc2762.receive.state_event:")?(_=c.Receive,l=a.State,u=p.substring(39)):p.startsWith("org.matrix.msc3819.receive.to_device:")&&(_=c.Receive,l=a.ToDevice,u=p.substring(37)),!(_===null||l===null)){var d=u.startsWith("m.room.message#")||l===a.State,h=null;if(u.includes("#")&&d){var w=u.split("#"),E=w.findIndex(function(I){return!I.endsWith("\\")});u=w.slice(0,E+1).map(function(I){return I.endsWith("\\")?I.substring(0,I.length-1):I}).join("#"),h=w.slice(E+1).join("#")}y.push(new v(_,u,l,h,p))}}}catch(I){S.e(I)}finally{S.f()}return y}}]),v}();return lr.WidgetEventCapability=f,lr}var ws={},iT;function p_(){if(iT)return ws;iT=1,Object.defineProperty(ws,"__esModule",{value:!0}),ws.Symbols=void 0;var e;return ws.Symbols=e,function(t){t.AnyRoom="*"}(e||(ws.Symbols=e={})),ws}var oT;function X3(){if(oT)return pl;oT=1;function e(D){return e=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(x){return typeof x}:function(x){return x&&typeof Symbol=="function"&&x.constructor===Symbol&&x!==Symbol.prototype?"symbol":typeof x},e(D)}Object.defineProperty(pl,"__esModule",{value:!0}),pl.WidgetApi=void 0;var t=Uf(),n=l_(),r=u_(),i=c_(),o=d_(),a=f_(),c=yk(),f=_k(),v=h_(),s=p_();function g(){/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */g=function(){return D};var D={},x=Object.prototype,z=x.hasOwnProperty,W=typeof Symbol=="function"?Symbol:{},F=W.iterator||"@@iterator",H=W.asyncIterator||"@@asyncIterator",R=W.toStringTag||"@@toStringTag";function P(fe,he,ye){return Object.defineProperty(fe,he,{value:ye,enumerable:!0,configurable:!0,writable:!0}),fe[he]}try{P({},"")}catch{P=function(ye,ce,le){return ye[ce]=le}}function K(fe,he,ye,ce){var le=he&&he.prototype instanceof A?he:A,Se=Object.create(le.prototype),Te=new re(ce||[]);return Se._invoke=function(De,je,Le){var Ve="suspendedStart";return function(Be,Ne){if(Ve==="executing")throw new Error("Generator is already running");if(Ve==="completed"){if(Be==="throw")throw Ne;return ge()}for(Le.method=Be,Le.arg=Ne;;){var We=Le.delegate;if(We){var Re=j(We,Le);if(Re){if(Re===C)continue;return Re}}if(Le.method==="next")Le.sent=Le._sent=Le.arg;else if(Le.method==="throw"){if(Ve==="suspendedStart")throw Ve="completed",Le.arg;Le.dispatchException(Le.arg)}else Le.method==="return"&&Le.abrupt("return",Le.arg);Ve="executing";var b=U(De,je,Le);if(b.type==="normal"){if(Ve=Le.done?"completed":"suspendedYield",b.arg===C)continue;return{value:b.arg,done:Le.done}}b.type==="throw"&&(Ve="completed",Le.method="throw",Le.arg=b.arg)}}}(fe,ye,Te),Se}function U(fe,he,ye){try{return{type:"normal",arg:fe.call(he,ye)}}catch(ce){return{type:"throw",arg:ce}}}D.wrap=K;var C={};function A(){}function T(){}function X(){}var ne={};P(ne,F,function(){return this});var ae=Object.getPrototypeOf,pe=ae&&ae(ae(de([])));pe&&pe!==x&&z.call(pe,F)&&(ne=pe);var V=X.prototype=A.prototype=Object.create(ne);function se(fe){["next","throw","return"].forEach(function(he){P(fe,he,function(ye){return this._invoke(he,ye)})})}function Q(fe,he){function ye(le,Se,Te,De){var je=U(fe[le],fe,Se);if(je.type!=="throw"){var Le=je.arg,Ve=Le.value;return Ve&&e(Ve)=="object"&&z.call(Ve,"__await")?he.resolve(Ve.__await).then(function(Be){ye("next",Be,Te,De)},function(Be){ye("throw",Be,Te,De)}):he.resolve(Ve).then(function(Be){Le.value=Be,Te(Le)},function(Be){return ye("throw",Be,Te,De)})}De(je.arg)}var ce;this._invoke=function(le,Se){function Te(){return new he(function(De,je){ye(le,Se,De,je)})}return ce=ce?ce.then(Te,Te):Te()}}function j(fe,he){var ye=fe.iterator[he.method];if(ye===void 0){if(he.delegate=null,he.method==="throw"){if(fe.iterator.return&&(he.method="return",he.arg=void 0,j(fe,he),he.method==="throw"))return C;he.method="throw",he.arg=new TypeError("The iterator does not provide a 'throw' method")}return C}var ce=U(ye,fe.iterator,he.arg);if(ce.type==="throw")return he.method="throw",he.arg=ce.arg,he.delegate=null,C;var le=ce.arg;return le?le.done?(he[fe.resultName]=le.value,he.next=fe.nextLoc,he.method!=="return"&&(he.method="next",he.arg=void 0),he.delegate=null,C):le:(he.method="throw",he.arg=new TypeError("iterator result is not an object"),he.delegate=null,C)}function Z(fe){var he={tryLoc:fe[0]};1 in fe&&(he.catchLoc=fe[1]),2 in fe&&(he.finallyLoc=fe[2],he.afterLoc=fe[3]),this.tryEntries.push(he)}function te(fe){var he=fe.completion||{};he.type="normal",delete he.arg,fe.completion=he}function re(fe){this.tryEntries=[{tryLoc:"root"}],fe.forEach(Z,this),this.reset(!0)}function de(fe){if(fe){var he=fe[F];if(he)return he.call(fe);if(typeof fe.next=="function")return fe;if(!isNaN(fe.length)){var ye=-1,ce=function le(){for(;++ye<fe.length;)if(z.call(fe,ye))return le.value=fe[ye],le.done=!1,le;return le.value=void 0,le.done=!0,le};return ce.next=ce}}return{next:ge}}function ge(){return{value:void 0,done:!0}}return T.prototype=X,P(V,"constructor",X),P(X,"constructor",T),T.displayName=P(X,R,"GeneratorFunction"),D.isGeneratorFunction=function(fe){var he=typeof fe=="function"&&fe.constructor;return!!he&&(he===T||(he.displayName||he.name)==="GeneratorFunction")},D.mark=function(fe){return Object.setPrototypeOf?Object.setPrototypeOf(fe,X):(fe.__proto__=X,P(fe,R,"GeneratorFunction")),fe.prototype=Object.create(V),fe},D.awrap=function(fe){return{__await:fe}},se(Q.prototype),P(Q.prototype,H,function(){return this}),D.AsyncIterator=Q,D.async=function(fe,he,ye,ce,le){le===void 0&&(le=Promise);var Se=new Q(K(fe,he,ye,ce),le);return D.isGeneratorFunction(he)?Se:Se.next().then(function(Te){return Te.done?Te.value:Se.next()})},se(V),P(V,R,"Generator"),P(V,F,function(){return this}),P(V,"toString",function(){return"[object Generator]"}),D.keys=function(fe){var he=[];for(var ye in fe)he.push(ye);return he.reverse(),function ce(){for(;he.length;){var le=he.pop();if(le in fe)return ce.value=le,ce.done=!1,ce}return ce.done=!0,ce}},D.values=de,re.prototype={constructor:re,reset:function(he){if(this.prev=0,this.next=0,this.sent=this._sent=void 0,this.done=!1,this.delegate=null,this.method="next",this.arg=void 0,this.tryEntries.forEach(te),!he)for(var ye in this)ye.charAt(0)==="t"&&z.call(this,ye)&&!isNaN(+ye.slice(1))&&(this[ye]=void 0)},stop:function(){this.done=!0;var he=this.tryEntries[0].completion;if(he.type==="throw")throw he.arg;return this.rval},dispatchException:function(he){if(this.done)throw he;var ye=this;function ce(Le,Ve){return Te.type="throw",Te.arg=he,ye.next=Le,Ve&&(ye.method="next",ye.arg=void 0),!!Ve}for(var le=this.tryEntries.length-1;le>=0;--le){var Se=this.tryEntries[le],Te=Se.completion;if(Se.tryLoc==="root")return ce("end");if(Se.tryLoc<=this.prev){var De=z.call(Se,"catchLoc"),je=z.call(Se,"finallyLoc");if(De&&je){if(this.prev<Se.catchLoc)return ce(Se.catchLoc,!0);if(this.prev<Se.finallyLoc)return ce(Se.finallyLoc)}else if(De){if(this.prev<Se.catchLoc)return ce(Se.catchLoc,!0)}else{if(!je)throw new Error("try statement without catch or finally");if(this.prev<Se.finallyLoc)return ce(Se.finallyLoc)}}}},abrupt:function(he,ye){for(var ce=this.tryEntries.length-1;ce>=0;--ce){var le=this.tryEntries[ce];if(le.tryLoc<=this.prev&&z.call(le,"finallyLoc")&&this.prev<le.finallyLoc){var Se=le;break}}Se&&(he==="break"||he==="continue")&&Se.tryLoc<=ye&&ye<=Se.finallyLoc&&(Se=null);var Te=Se?Se.completion:{};return Te.type=he,Te.arg=ye,Se?(this.method="next",this.next=Se.finallyLoc,C):this.complete(Te)},complete:function(he,ye){if(he.type==="throw")throw he.arg;return he.type==="break"||he.type==="continue"?this.next=he.arg:he.type==="return"?(this.rval=this.arg=he.arg,this.method="return",this.next="end"):he.type==="normal"&&ye&&(this.next=ye),C},finish:function(he){for(var ye=this.tryEntries.length-1;ye>=0;--ye){var ce=this.tryEntries[ye];if(ce.finallyLoc===he)return this.complete(ce.completion,ce.afterLoc),te(ce),C}},catch:function(he){for(var ye=this.tryEntries.length-1;ye>=0;--ye){var ce=this.tryEntries[ye];if(ce.tryLoc===he){var le=ce.completion;if(le.type==="throw"){var Se=le.arg;te(ce)}return Se}}throw new Error("illegal catch attempt")},delegateYield:function(he,ye,ce){return this.delegate={iterator:de(he),resultName:ye,nextLoc:ce},this.method==="next"&&(this.arg=void 0),C}},D}function y(D,x,z,W,F,H,R){try{var P=D[H](R),K=P.value}catch(U){z(U);return}P.done?x(K):Promise.resolve(K).then(W,F)}function S(D){return function(){var x=this,z=arguments;return new Promise(function(W,F){var H=D.apply(x,z);function R(K){y(H,W,F,R,P,"next",K)}function P(K){y(H,W,F,R,P,"throw",K)}R(void 0)})}}function m(D,x){if(!(D instanceof x))throw new TypeError("Cannot call a class as a function")}function p(D,x){for(var z=0;z<x.length;z++){var W=x[z];W.enumerable=W.enumerable||!1,W.configurable=!0,"value"in W&&(W.writable=!0),Object.defineProperty(D,W.key,W)}}function _(D,x,z){return x&&p(D.prototype,x),z&&p(D,z),Object.defineProperty(D,"prototype",{writable:!1}),D}function u(D,x){if(typeof x!="function"&&x!==null)throw new TypeError("Super expression must either be null or a function");D.prototype=Object.create(x&&x.prototype,{constructor:{value:D,writable:!0,configurable:!0}}),Object.defineProperty(D,"prototype",{writable:!1}),x&&l(D,x)}function l(D,x){return l=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(W,F){return W.__proto__=F,W},l(D,x)}function d(D){var x=E();return function(){var W=I(D),F;if(x){var H=I(this).constructor;F=Reflect.construct(W,arguments,H)}else F=W.apply(this,arguments);return h(this,F)}}function h(D,x){if(x&&(e(x)==="object"||typeof x=="function"))return x;if(x!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return w(D)}function w(D){if(D===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return D}function E(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}function I(D){return I=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(z){return z.__proto__||Object.getPrototypeOf(z)},I(D)}function k(D,x,z){return x in D?Object.defineProperty(D,x,{value:z,enumerable:!0,configurable:!0,writable:!0}):D[x]=z,D}function M(D){return new N(D)}function L(D){return function(){return new B(D.apply(this,arguments))}}function B(D){var x,z;function W(R,P){return new Promise(function(K,U){var C={key:R,arg:P,resolve:K,reject:U,next:null};z?z=z.next=C:(x=z=C,F(R,P))})}function F(R,P){try{var K=D[R](P),U=K.value,C=U instanceof N;Promise.resolve(C?U.wrapped:U).then(function(A){if(C){F(R==="return"?"return":"next",A);return}H(K.done?"return":"normal",A)},function(A){F("throw",A)})}catch(A){H("throw",A)}}function H(R,P){switch(R){case"return":x.resolve({value:P,done:!0});break;case"throw":x.reject(P);break;default:x.resolve({value:P,done:!1});break}x=x.next,x?F(x.key,x.arg):z=null}this._invoke=W,typeof D.return!="function"&&(this.return=void 0)}B.prototype[typeof Symbol=="function"&&Symbol.asyncIterator||"@@asyncIterator"]=function(){return this},B.prototype.next=function(D){return this._invoke("next",D)},B.prototype.throw=function(D){return this._invoke("throw",D)},B.prototype.return=function(D){return this._invoke("return",D)};function N(D){this.wrapped=D}var G=function(D){u(z,D);var x=d(z);function z(){var W,F=arguments.length>0&&arguments[0]!==void 0?arguments[0]:null,H=arguments.length>1&&arguments[1]!==void 0?arguments[1]:null;if(m(this,z),W=x.call(this),W.clientOrigin=H,k(w(W),"transport",void 0),k(w(W),"capabilitiesFinished",!1),k(w(W),"supportsMSC2974Renegotiate",!1),k(w(W),"requestedCapabilities",[]),k(w(W),"approvedCapabilities",void 0),k(w(W),"cachedClientVersions",void 0),k(w(W),"turnServerWatchers",0),!window.parent)throw new Error("No parent window. This widget doesn't appear to be embedded properly.");return W.transport=new i.PostmessageTransport(n.WidgetApiDirection.FromWidget,F,window.parent,window),W.transport.targetOrigin=H,W.transport.on("message",W.handleMessage.bind(w(W))),W}return _(z,[{key:"hasCapability",value:function(F){return Array.isArray(this.approvedCapabilities)?this.approvedCapabilities.includes(F):this.requestedCapabilities.includes(F)}},{key:"requestCapability",value:function(F){if(this.capabilitiesFinished&&!this.supportsMSC2974Renegotiate)throw new Error("Capabilities have already been negotiated");this.requestedCapabilities.push(F)}},{key:"requestCapabilities",value:function(F){var H=this;F.forEach(function(R){return H.requestCapability(R)})}},{key:"requestCapabilityForRoomTimeline",value:function(F){this.requestCapability("org.matrix.msc2762.timeline:".concat(F))}},{key:"requestCapabilityToSendState",value:function(F,H){this.requestCapability(v.WidgetEventCapability.forStateEvent(v.EventDirection.Send,F,H).raw)}},{key:"requestCapabilityToReceiveState",value:function(F,H){this.requestCapability(v.WidgetEventCapability.forStateEvent(v.EventDirection.Receive,F,H).raw)}},{key:"requestCapabilityToSendToDevice",value:function(F){this.requestCapability(v.WidgetEventCapability.forToDeviceEvent(v.EventDirection.Send,F).raw)}},{key:"requestCapabilityToReceiveToDevice",value:function(F){this.requestCapability(v.WidgetEventCapability.forToDeviceEvent(v.EventDirection.Receive,F).raw)}},{key:"requestCapabilityToSendEvent",value:function(F){this.requestCapability(v.WidgetEventCapability.forRoomEvent(v.EventDirection.Send,F).raw)}},{key:"requestCapabilityToReceiveEvent",value:function(F){this.requestCapability(v.WidgetEventCapability.forRoomEvent(v.EventDirection.Receive,F).raw)}},{key:"requestCapabilityToSendMessage",value:function(F){this.requestCapability(v.WidgetEventCapability.forRoomMessageEvent(v.EventDirection.Send,F).raw)}},{key:"requestCapabilityToReceiveMessage",value:function(F){this.requestCapability(v.WidgetEventCapability.forRoomMessageEvent(v.EventDirection.Receive,F).raw)}},{key:"requestOpenIDConnectToken",value:function(){var F=this;return new Promise(function(H,R){F.transport.sendComplete(o.WidgetApiFromWidgetAction.GetOpenIDCredentials,{}).then(function(P){var K=P.response;if(K.state===a.OpenIDRequestState.Allowed)H(K);else if(K.state===a.OpenIDRequestState.Blocked)R(new Error("User declined to verify their identity"));else if(K.state===a.OpenIDRequestState.PendingUserConfirmation){var U=function C(A){A.preventDefault();var T=A.detail;T.data.original_request_id===P.requestId&&(T.data.state===a.OpenIDRequestState.Allowed?(H(T.data),F.transport.reply(T,{})):T.data.state===a.OpenIDRequestState.Blocked?(R(new Error("User declined to verify their identity")),F.transport.reply(T,{})):(R(new Error("Invalid state on reply: "+K.state)),F.transport.reply(T,{error:{message:"Invalid state"}})),F.off("action:".concat(o.WidgetApiToWidgetAction.OpenIDCredentials),C))};F.on("action:".concat(o.WidgetApiToWidgetAction.OpenIDCredentials),U)}else R(new Error("Invalid state: "+K.state))}).catch(R)})}},{key:"updateRequestedCapabilities",value:function(){return this.transport.send(o.WidgetApiFromWidgetAction.MSC2974RenegotiateCapabilities,{capabilities:this.requestedCapabilities}).then()}},{key:"sendContentLoaded",value:function(){return this.transport.send(o.WidgetApiFromWidgetAction.ContentLoaded,{}).then()}},{key:"sendSticker",value:function(F){return this.transport.send(o.WidgetApiFromWidgetAction.SendSticker,F).then()}},{key:"setAlwaysOnScreen",value:function(F){return this.transport.send(o.WidgetApiFromWidgetAction.UpdateAlwaysOnScreen,{value:F}).then(function(H){return H.success})}},{key:"openModalWidget",value:function(F,H){var R=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[],P=arguments.length>3&&arguments[3]!==void 0?arguments[3]:{},K=arguments.length>4&&arguments[4]!==void 0?arguments[4]:c.MatrixWidgetType.Custom;return this.transport.send(o.WidgetApiFromWidgetAction.OpenModalWidget,{type:K,url:F,name:H,buttons:R,data:P}).then()}},{key:"closeModalWidget",value:function(){var F=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return this.transport.send(o.WidgetApiFromWidgetAction.CloseModalWidget,F).then()}},{key:"sendRoomEvent",value:function(F,H,R){return this.transport.send(o.WidgetApiFromWidgetAction.SendEvent,{type:F,content:H,room_id:R})}},{key:"sendStateEvent",value:function(F,H,R,P){return this.transport.send(o.WidgetApiFromWidgetAction.SendEvent,{type:F,content:R,state_key:H,room_id:P})}},{key:"sendToDevice",value:function(F,H,R){return this.transport.send(o.WidgetApiFromWidgetAction.SendToDevice,{type:F,encrypted:H,messages:R})}},{key:"readRoomEvents",value:function(F,H,R,P){var K={type:F,msgtype:R};return H!==void 0&&(K.limit=H),P&&(P.includes(s.Symbols.AnyRoom)?K.room_ids=s.Symbols.AnyRoom:K.room_ids=P),this.transport.send(o.WidgetApiFromWidgetAction.MSC2876ReadEvents,K).then(function(U){return U.events})}},{key:"readEventRelations",value:function(){var W=S(g().mark(function H(R,P,K,U,C,A,T,X){var ne,ae;return g().wrap(function(V){for(;;)switch(V.prev=V.next){case 0:return V.next=2,this.getClientVersions();case 2:if(ne=V.sent,ne.includes(r.UnstableApiVersion.MSC3869)){V.next=5;break}throw new Error("The read_relations action is not supported by the client.");case 5:return ae={event_id:R,rel_type:K,event_type:U,room_id:P,to:T,from:A,limit:C,direction:X},V.abrupt("return",this.transport.send(o.WidgetApiFromWidgetAction.MSC3869ReadRelations,ae));case 7:case"end":return V.stop()}},H,this)}));function F(H,R,P,K,U,C,A,T){return W.apply(this,arguments)}return F}()},{key:"readStateEvents",value:function(F,H,R,P){var K={type:F,state_key:R===void 0?!0:R};return H!==void 0&&(K.limit=H),P&&(P.includes(s.Symbols.AnyRoom)?K.room_ids=s.Symbols.AnyRoom:K.room_ids=P),this.transport.send(o.WidgetApiFromWidgetAction.MSC2876ReadEvents,K).then(function(U){return U.events})}},{key:"setModalButtonEnabled",value:function(F,H){if(F===f.BuiltInModalButtonID.Close)throw new Error("The close button cannot be disabled");return this.transport.send(o.WidgetApiFromWidgetAction.SetModalButtonEnabled,{button:F,enabled:H}).then()}},{key:"navigateTo",value:function(F){if(!F||!F.startsWith("https://matrix.to/#"))throw new Error("Invalid matrix.to URI");return this.transport.send(o.WidgetApiFromWidgetAction.MSC2931Navigate,{uri:F}).then()}},{key:"getTurnServers",value:function(){var F=this;return L(g().mark(function H(){var R,P;return g().wrap(function(U){for(;;)switch(U.prev=U.next){case 0:if(P=function(){var C=S(g().mark(function A(T){return g().wrap(function(ne){for(;;)switch(ne.prev=ne.next){case 0:return T.preventDefault(),R(T.detail.data),ne.next=4,F.transport.reply(T.detail,{});case 4:case"end":return ne.stop()}},A)}));return function(T){return C.apply(this,arguments)}}(),F.on("action:".concat(o.WidgetApiToWidgetAction.UpdateTurnServers),P),F.turnServerWatchers!==0){U.next=12;break}return U.prev=3,U.next=6,M(F.transport.send(o.WidgetApiFromWidgetAction.WatchTurnServers,{}));case 6:U.next=12;break;case 8:throw U.prev=8,U.t0=U.catch(3),F.off("action:".concat(o.WidgetApiToWidgetAction.UpdateTurnServers),P),U.t0;case 12:F.turnServerWatchers++,U.prev=13;case 14:return U.next=17,M(new Promise(function(C){return R=C}));case 17:return U.next=19,U.sent;case 19:U.next=14;break;case 21:if(U.prev=21,F.off("action:".concat(o.WidgetApiToWidgetAction.UpdateTurnServers),P),F.turnServerWatchers--,F.turnServerWatchers!==0){U.next=27;break}return U.next=27,M(F.transport.send(o.WidgetApiFromWidgetAction.UnwatchTurnServers,{}));case 27:return U.finish(21);case 28:case"end":return U.stop()}},H,null,[[3,8],[13,,21,28]])}))()}},{key:"start",value:function(){var F=this;this.transport.start(),this.getClientVersions().then(function(H){H.includes(r.UnstableApiVersion.MSC2974)&&(F.supportsMSC2974Renegotiate=!0)})}},{key:"handleMessage",value:function(F){var H=new CustomEvent("action:".concat(F.detail.action),{detail:F.detail,cancelable:!0});if(this.emit("action:".concat(F.detail.action),H),!H.defaultPrevented)switch(F.detail.action){case o.WidgetApiToWidgetAction.SupportedApiVersions:return this.replyVersions(F.detail);case o.WidgetApiToWidgetAction.Capabilities:return this.handleCapabilities(F.detail);case o.WidgetApiToWidgetAction.UpdateVisibility:return this.transport.reply(F.detail,{});case o.WidgetApiToWidgetAction.NotifyCapabilities:return this.transport.reply(F.detail,{});default:return this.transport.reply(F.detail,{error:{message:"Unknown or unsupported action: "+F.detail.action}})}}},{key:"replyVersions",value:function(F){this.transport.reply(F,{supported_versions:r.CurrentApiVersions})}},{key:"getClientVersions",value:function(){var F=this;return Array.isArray(this.cachedClientVersions)?Promise.resolve(this.cachedClientVersions):this.transport.send(o.WidgetApiFromWidgetAction.SupportedApiVersions,{}).then(function(H){return F.cachedClientVersions=H.supported_versions,H.supported_versions}).catch(function(H){return console.warn("non-fatal error getting supported client versions: ",H),[]})}},{key:"handleCapabilities",value:function(F){var H=this;return this.capabilitiesFinished?this.transport.reply(F,{error:{message:"Capability negotiation already completed"}}):this.getClientVersions().then(function(R){return R.includes(r.UnstableApiVersion.MSC2871)?H.once("action:".concat(o.WidgetApiToWidgetAction.NotifyCapabilities),function(P){H.approvedCapabilities=P.detail.data.approved,H.emit("ready")}):H.emit("ready"),H.capabilitiesFinished=!0,H.transport.reply(F,{capabilities:H.requestedCapabilities})})}}]),z}(t.EventEmitter);return pl.WidgetApi=G,pl}var vl={},kn={},sT;function Sk(){if(sT)return kn;sT=1,Object.defineProperty(kn,"__esModule",{value:!0}),kn.VideoConferenceCapabilities=kn.StickerpickerCapabilities=kn.MatrixCapabilities=void 0,kn.getTimelineRoomIDFromCapability=o,kn.isTimelineCapability=r,kn.isTimelineCapabilityFor=i;var e;kn.MatrixCapabilities=e,function(a){a.Screenshots="m.capability.screenshot",a.StickerSending="m.sticker",a.AlwaysOnScreen="m.always_on_screen",a.RequiresClient="io.element.requires_client",a.MSC2931Navigate="org.matrix.msc2931.navigate",a.MSC3846TurnServers="town.robin.msc3846.turn_servers"}(e||(kn.MatrixCapabilities=e={}));var t=[e.StickerSending];kn.StickerpickerCapabilities=t;var n=[e.AlwaysOnScreen];kn.VideoConferenceCapabilities=n;function r(a){return a==null?void 0:a.startsWith("org.matrix.msc2762.timeline:")}function i(a,c){return a==="org.matrix.msc2762.timeline:".concat(c)}function o(a){return a.substring(a.indexOf(":")+1)}return kn}var ml={},aT;function Ek(){if(aT)return ml;aT=1,Object.defineProperty(ml,"__esModule",{value:!0}),ml.SimpleObservable=void 0;function e(f,v){var s=typeof Symbol<"u"&&f[Symbol.iterator]||f["@@iterator"];if(!s){if(Array.isArray(f)||(s=t(f))||v&&f&&typeof f.length=="number"){s&&(f=s);var g=0,y=function(){};return{s:y,n:function(){return g>=f.length?{done:!0}:{done:!1,value:f[g++]}},e:function(u){throw u},f:y}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
     88 In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var S=!0,m=!1,p;return{s:function(){s=s.call(f)},n:function(){var u=s.next();return S=u.done,u},e:function(u){m=!0,p=u},f:function(){try{!S&&s.return!=null&&s.return()}finally{if(m)throw p}}}}function t(f,v){if(f){if(typeof f=="string")return n(f,v);var s=Object.prototype.toString.call(f).slice(8,-1);if(s==="Object"&&f.constructor&&(s=f.constructor.name),s==="Map"||s==="Set")return Array.from(f);if(s==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(s))return n(f,v)}}function n(f,v){(v==null||v>f.length)&&(v=f.length);for(var s=0,g=new Array(v);s<v;s++)g[s]=f[s];return g}function r(f,v){if(!(f instanceof v))throw new TypeError("Cannot call a class as a function")}function i(f,v){for(var s=0;s<v.length;s++){var g=v[s];g.enumerable=g.enumerable||!1,g.configurable=!0,"value"in g&&(g.writable=!0),Object.defineProperty(f,g.key,g)}}function o(f,v,s){return v&&i(f.prototype,v),s&&i(f,s),Object.defineProperty(f,"prototype",{writable:!1}),f}function a(f,v,s){return v in f?Object.defineProperty(f,v,{value:s,enumerable:!0,configurable:!0,writable:!0}):f[v]=s,f}var c=function(){function f(v){r(this,f),a(this,"listeners",[]),v&&this.listeners.push(v)}return o(f,[{key:"onUpdate",value:function(s){this.listeners.push(s)}},{key:"update",value:function(s){var g=e(this.listeners),y;try{for(g.s();!(y=g.n()).done;){var S=y.value;S(s)}}catch(m){g.e(m)}finally{g.f()}}},{key:"close",value:function(){this.listeners=[]}}]),f}();return ml.SimpleObservable=c,ml}var lT;function Z3(){if(lT)return vl;lT=1;function e(W){return e=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(F){return typeof F}:function(F){return F&&typeof Symbol=="function"&&F.constructor===Symbol&&F!==Symbol.prototype?"symbol":typeof F},e(W)}Object.defineProperty(vl,"__esModule",{value:!0}),vl.ClientWidgetApi=void 0;var t=Uf(),n=c_(),r=l_(),i=d_(),o=Sk(),a=u_(),c=h_(),f=f_(),v=Ek(),s=p_();function g(){/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */g=function(){return W};var W={},F=Object.prototype,H=F.hasOwnProperty,R=typeof Symbol=="function"?Symbol:{},P=R.iterator||"@@iterator",K=R.asyncIterator||"@@asyncIterator",U=R.toStringTag||"@@toStringTag";function C(ce,le,Se){return Object.defineProperty(ce,le,{value:Se,enumerable:!0,configurable:!0,writable:!0}),ce[le]}try{C({},"")}catch{C=function(Se,Te,De){return Se[Te]=De}}function A(ce,le,Se,Te){var De=le&&le.prototype instanceof ne?le:ne,je=Object.create(De.prototype),Le=new fe(Te||[]);return je._invoke=function(Ve,Be,Ne){var We="suspendedStart";return function(Re,b){if(We==="executing")throw new Error("Generator is already running");if(We==="completed"){if(Re==="throw")throw b;return ye()}for(Ne.method=Re,Ne.arg=b;;){var O=Ne.delegate;if(O){var $=re(O,Ne);if($){if($===X)continue;return $}}if(Ne.method==="next")Ne.sent=Ne._sent=Ne.arg;else if(Ne.method==="throw"){if(We==="suspendedStart")throw We="completed",Ne.arg;Ne.dispatchException(Ne.arg)}else Ne.method==="return"&&Ne.abrupt("return",Ne.arg);We="executing";var Y=T(Ve,Be,Ne);if(Y.type==="normal"){if(We=Ne.done?"completed":"suspendedYield",Y.arg===X)continue;return{value:Y.arg,done:Ne.done}}Y.type==="throw"&&(We="completed",Ne.method="throw",Ne.arg=Y.arg)}}}(ce,Se,Le),je}function T(ce,le,Se){try{return{type:"normal",arg:ce.call(le,Se)}}catch(Te){return{type:"throw",arg:Te}}}W.wrap=A;var X={};function ne(){}function ae(){}function pe(){}var V={};C(V,P,function(){return this});var se=Object.getPrototypeOf,Q=se&&se(se(he([])));Q&&Q!==F&&H.call(Q,P)&&(V=Q);var j=pe.prototype=ne.prototype=Object.create(V);function Z(ce){["next","throw","return"].forEach(function(le){C(ce,le,function(Se){return this._invoke(le,Se)})})}function te(ce,le){function Se(De,je,Le,Ve){var Be=T(ce[De],ce,je);if(Be.type!=="throw"){var Ne=Be.arg,We=Ne.value;return We&&e(We)=="object"&&H.call(We,"__await")?le.resolve(We.__await).then(function(Re){Se("next",Re,Le,Ve)},function(Re){Se("throw",Re,Le,Ve)}):le.resolve(We).then(function(Re){Ne.value=Re,Le(Ne)},function(Re){return Se("throw",Re,Le,Ve)})}Ve(Be.arg)}var Te;this._invoke=function(De,je){function Le(){return new le(function(Ve,Be){Se(De,je,Ve,Be)})}return Te=Te?Te.then(Le,Le):Le()}}function re(ce,le){var Se=ce.iterator[le.method];if(Se===void 0){if(le.delegate=null,le.method==="throw"){if(ce.iterator.return&&(le.method="return",le.arg=void 0,re(ce,le),le.method==="throw"))return X;le.method="throw",le.arg=new TypeError("The iterator does not provide a 'throw' method")}return X}var Te=T(Se,ce.iterator,le.arg);if(Te.type==="throw")return le.method="throw",le.arg=Te.arg,le.delegate=null,X;var De=Te.arg;return De?De.done?(le[ce.resultName]=De.value,le.next=ce.nextLoc,le.method!=="return"&&(le.method="next",le.arg=void 0),le.delegate=null,X):De:(le.method="throw",le.arg=new TypeError("iterator result is not an object"),le.delegate=null,X)}function de(ce){var le={tryLoc:ce[0]};1 in ce&&(le.catchLoc=ce[1]),2 in ce&&(le.finallyLoc=ce[2],le.afterLoc=ce[3]),this.tryEntries.push(le)}function ge(ce){var le=ce.completion||{};le.type="normal",delete le.arg,ce.completion=le}function fe(ce){this.tryEntries=[{tryLoc:"root"}],ce.forEach(de,this),this.reset(!0)}function he(ce){if(ce){var le=ce[P];if(le)return le.call(ce);if(typeof ce.next=="function")return ce;if(!isNaN(ce.length)){var Se=-1,Te=function De(){for(;++Se<ce.length;)if(H.call(ce,Se))return De.value=ce[Se],De.done=!1,De;return De.value=void 0,De.done=!0,De};return Te.next=Te}}return{next:ye}}function ye(){return{value:void 0,done:!0}}return ae.prototype=pe,C(j,"constructor",pe),C(pe,"constructor",ae),ae.displayName=C(pe,U,"GeneratorFunction"),W.isGeneratorFunction=function(ce){var le=typeof ce=="function"&&ce.constructor;return!!le&&(le===ae||(le.displayName||le.name)==="GeneratorFunction")},W.mark=function(ce){return Object.setPrototypeOf?Object.setPrototypeOf(ce,pe):(ce.__proto__=pe,C(ce,U,"GeneratorFunction")),ce.prototype=Object.create(j),ce},W.awrap=function(ce){return{__await:ce}},Z(te.prototype),C(te.prototype,K,function(){return this}),W.AsyncIterator=te,W.async=function(ce,le,Se,Te,De){De===void 0&&(De=Promise);var je=new te(A(ce,le,Se,Te),De);return W.isGeneratorFunction(le)?je:je.next().then(function(Le){return Le.done?Le.value:je.next()})},Z(j),C(j,U,"Generator"),C(j,P,function(){return this}),C(j,"toString",function(){return"[object Generator]"}),W.keys=function(ce){var le=[];for(var Se in ce)le.push(Se);return le.reverse(),function Te(){for(;le.length;){var De=le.pop();if(De in ce)return Te.value=De,Te.done=!1,Te}return Te.done=!0,Te}},W.values=he,fe.prototype={constructor:fe,reset:function(le){if(this.prev=0,this.next=0,this.sent=this._sent=void 0,this.done=!1,this.delegate=null,this.method="next",this.arg=void 0,this.tryEntries.forEach(ge),!le)for(var Se in this)Se.charAt(0)==="t"&&H.call(this,Se)&&!isNaN(+Se.slice(1))&&(this[Se]=void 0)},stop:function(){this.done=!0;var le=this.tryEntries[0].completion;if(le.type==="throw")throw le.arg;return this.rval},dispatchException:function(le){if(this.done)throw le;var Se=this;function Te(Ne,We){return Le.type="throw",Le.arg=le,Se.next=Ne,We&&(Se.method="next",Se.arg=void 0),!!We}for(var De=this.tryEntries.length-1;De>=0;--De){var je=this.tryEntries[De],Le=je.completion;if(je.tryLoc==="root")return Te("end");if(je.tryLoc<=this.prev){var Ve=H.call(je,"catchLoc"),Be=H.call(je,"finallyLoc");if(Ve&&Be){if(this.prev<je.catchLoc)return Te(je.catchLoc,!0);if(this.prev<je.finallyLoc)return Te(je.finallyLoc)}else if(Ve){if(this.prev<je.catchLoc)return Te(je.catchLoc,!0)}else{if(!Be)throw new Error("try statement without catch or finally");if(this.prev<je.finallyLoc)return Te(je.finallyLoc)}}}},abrupt:function(le,Se){for(var Te=this.tryEntries.length-1;Te>=0;--Te){var De=this.tryEntries[Te];if(De.tryLoc<=this.prev&&H.call(De,"finallyLoc")&&this.prev<De.finallyLoc){var je=De;break}}je&&(le==="break"||le==="continue")&&je.tryLoc<=Se&&Se<=je.finallyLoc&&(je=null);var Le=je?je.completion:{};return Le.type=le,Le.arg=Se,je?(this.method="next",this.next=je.finallyLoc,X):this.complete(Le)},complete:function(le,Se){if(le.type==="throw")throw le.arg;return le.type==="break"||le.type==="continue"?this.next=le.arg:le.type==="return"?(this.rval=this.arg=le.arg,this.method="return",this.next="end"):le.type==="normal"&&Se&&(this.next=Se),X},finish:function(le){for(var Se=this.tryEntries.length-1;Se>=0;--Se){var Te=this.tryEntries[Se];if(Te.finallyLoc===le)return this.complete(Te.completion,Te.afterLoc),ge(Te),X}},catch:function(le){for(var Se=this.tryEntries.length-1;Se>=0;--Se){var Te=this.tryEntries[Se];if(Te.tryLoc===le){var De=Te.completion;if(De.type==="throw"){var je=De.arg;ge(Te)}return je}}throw new Error("illegal catch attempt")},delegateYield:function(le,Se,Te){return this.delegate={iterator:he(le),resultName:Se,nextLoc:Te},this.method==="next"&&(this.arg=void 0),X}},W}function y(W,F,H,R,P,K,U){try{var C=W[K](U),A=C.value}catch(T){H(T);return}C.done?F(A):Promise.resolve(A).then(R,P)}function S(W){return function(){var F=this,H=arguments;return new Promise(function(R,P){var K=W.apply(F,H);function U(A){y(K,R,P,U,C,"next",A)}function C(A){y(K,R,P,U,C,"throw",A)}U(void 0)})}}function m(W,F){var H=typeof Symbol<"u"&&W[Symbol.iterator]||W["@@iterator"];if(!H){if(Array.isArray(W)||(H=p(W))||F&&W&&typeof W.length=="number"){H&&(W=H);var R=0,P=function(){};return{s:P,n:function(){return R>=W.length?{done:!0}:{done:!1,value:W[R++]}},e:function(T){throw T},f:P}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
     89 In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var K=!0,U=!1,C;return{s:function(){H=H.call(W)},n:function(){var T=H.next();return K=T.done,T},e:function(T){U=!0,C=T},f:function(){try{!K&&H.return!=null&&H.return()}finally{if(U)throw C}}}}function p(W,F){if(W){if(typeof W=="string")return _(W,F);var H=Object.prototype.toString.call(W).slice(8,-1);if(H==="Object"&&W.constructor&&(H=W.constructor.name),H==="Map"||H==="Set")return Array.from(W);if(H==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(H))return _(W,F)}}function _(W,F){(F==null||F>W.length)&&(F=W.length);for(var H=0,R=new Array(F);H<F;H++)R[H]=W[H];return R}function u(W,F){var H=Object.keys(W);if(Object.getOwnPropertySymbols){var R=Object.getOwnPropertySymbols(W);F&&(R=R.filter(function(P){return Object.getOwnPropertyDescriptor(W,P).enumerable})),H.push.apply(H,R)}return H}function l(W){for(var F=1;F<arguments.length;F++){var H=arguments[F]!=null?arguments[F]:{};F%2?u(Object(H),!0).forEach(function(R){G(W,R,H[R])}):Object.getOwnPropertyDescriptors?Object.defineProperties(W,Object.getOwnPropertyDescriptors(H)):u(Object(H)).forEach(function(R){Object.defineProperty(W,R,Object.getOwnPropertyDescriptor(H,R))})}return W}function d(W,F){if(!(W instanceof F))throw new TypeError("Cannot call a class as a function")}function h(W,F){for(var H=0;H<F.length;H++){var R=F[H];R.enumerable=R.enumerable||!1,R.configurable=!0,"value"in R&&(R.writable=!0),Object.defineProperty(W,R.key,R)}}function w(W,F,H){return F&&h(W.prototype,F),H&&h(W,H),Object.defineProperty(W,"prototype",{writable:!1}),W}function E(W,F){if(typeof F!="function"&&F!==null)throw new TypeError("Super expression must either be null or a function");W.prototype=Object.create(F&&F.prototype,{constructor:{value:W,writable:!0,configurable:!0}}),Object.defineProperty(W,"prototype",{writable:!1}),F&&I(W,F)}function I(W,F){return I=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(R,P){return R.__proto__=P,R},I(W,F)}function k(W){var F=B();return function(){var R=N(W),P;if(F){var K=N(this).constructor;P=Reflect.construct(R,arguments,K)}else P=R.apply(this,arguments);return M(this,P)}}function M(W,F){if(F&&(e(F)==="object"||typeof F=="function"))return F;if(F!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return L(W)}function L(W){if(W===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return W}function B(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}function N(W){return N=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(H){return H.__proto__||Object.getPrototypeOf(H)},N(W)}function G(W,F,H){return F in W?Object.defineProperty(W,F,{value:H,enumerable:!0,configurable:!0,writable:!0}):W[F]=H,W}function D(W){var F,H,R,P=2;for(typeof Symbol<"u"&&(H=Symbol.asyncIterator,R=Symbol.iterator);P--;){if(H&&(F=W[H])!=null)return F.call(W);if(R&&(F=W[R])!=null)return new x(F.call(W));H="@@asyncIterator",R="@@iterator"}throw new TypeError("Object is not async iterable")}function x(W){function F(H){if(Object(H)!==H)return Promise.reject(new TypeError(H+" is not an object."));var R=H.done;return Promise.resolve(H.value).then(function(P){return{value:P,done:R}})}return x=function(R){this.s=R,this.n=R.next},x.prototype={s:null,n:null,next:function(){return F(this.n.apply(this.s,arguments))},return:function(R){var P=this.s.return;return P===void 0?Promise.resolve({value:R,done:!0}):F(P.apply(this.s,arguments))},throw:function(R){var P=this.s.return;return P===void 0?Promise.reject(R):F(P.apply(this.s,arguments))}},new x(W)}var z=function(W){E(H,W);var F=k(H);function H(R,P,K){var U;if(d(this,H),U=F.call(this),U.widget=R,U.iframe=P,U.driver=K,G(L(U),"transport",void 0),G(L(U),"contentLoadedActionSent",!1),G(L(U),"allowedCapabilities",new Set),G(L(U),"allowedEvents",[]),G(L(U),"isStopped",!1),G(L(U),"turnServers",null),!(P!=null&&P.contentWindow))throw new Error("No iframe supplied");if(!R)throw new Error("Invalid widget");if(!K)throw new Error("Invalid driver");return U.transport=new n.PostmessageTransport(r.WidgetApiDirection.ToWidget,R.id,P.contentWindow,window),U.transport.targetOrigin=R.origin,U.transport.on("message",U.handleMessage.bind(L(U))),P.addEventListener("load",U.onIframeLoad.bind(L(U))),U.transport.start(),U}return w(H,[{key:"hasCapability",value:function(P){return this.allowedCapabilities.has(P)}},{key:"canUseRoomTimeline",value:function(P){return this.hasCapability("org.matrix.msc2762.timeline:".concat(s.Symbols.AnyRoom))||this.hasCapability("org.matrix.msc2762.timeline:".concat(P))}},{key:"canSendRoomEvent",value:function(P){var K=arguments.length>1&&arguments[1]!==void 0?arguments[1]:null;return this.allowedEvents.some(function(U){return U.matchesAsRoomEvent(c.EventDirection.Send,P,K)})}},{key:"canSendStateEvent",value:function(P,K){return this.allowedEvents.some(function(U){return U.matchesAsStateEvent(c.EventDirection.Send,P,K)})}},{key:"canSendToDeviceEvent",value:function(P){return this.allowedEvents.some(function(K){return K.matchesAsToDeviceEvent(c.EventDirection.Send,P)})}},{key:"canReceiveRoomEvent",value:function(P){var K=arguments.length>1&&arguments[1]!==void 0?arguments[1]:null;return this.allowedEvents.some(function(U){return U.matchesAsRoomEvent(c.EventDirection.Receive,P,K)})}},{key:"canReceiveStateEvent",value:function(P,K){return this.allowedEvents.some(function(U){return U.matchesAsStateEvent(c.EventDirection.Receive,P,K)})}},{key:"canReceiveToDeviceEvent",value:function(P){return this.allowedEvents.some(function(K){return K.matchesAsToDeviceEvent(c.EventDirection.Receive,P)})}},{key:"stop",value:function(){this.isStopped=!0,this.transport.stop()}},{key:"beginCapabilities",value:function(){var P=this;this.emit("preparing");var K;this.transport.send(i.WidgetApiToWidgetAction.Capabilities,{}).then(function(U){return K=U.capabilities,P.driver.validateCapabilities(new Set(U.capabilities))}).then(function(U){console.log("Widget ".concat(P.widget.id," is allowed capabilities:"),Array.from(U)),P.allowedCapabilities=U,P.allowedEvents=c.WidgetEventCapability.findEventCapabilities(U),P.notifyCapabilities(K),P.emit("ready")})}},{key:"notifyCapabilities",value:function(P){var K=this;this.transport.send(i.WidgetApiToWidgetAction.NotifyCapabilities,{requested:P,approved:Array.from(this.allowedCapabilities)}).catch(function(U){console.warn("non-fatal error notifying widget of approved capabilities:",U)}).then(function(){K.emit("capabilitiesNotified")})}},{key:"onIframeLoad",value:function(P){this.widget.waitForIframeLoad?this.beginCapabilities():this.contentLoadedActionSent=!1}},{key:"handleContentLoadedAction",value:function(P){if(this.contentLoadedActionSent)throw new Error("Improper sequence: ContentLoaded Action can only be send once after the widget loaded and should only be used if waitForIframeLoad is false (default=true)");this.widget.waitForIframeLoad?this.transport.reply(P,{error:{message:"Improper sequence: not expecting ContentLoaded event if waitForIframLoad is true (default=true)"}}):(this.transport.reply(P,{}),this.beginCapabilities()),this.contentLoadedActionSent=!0}},{key:"replyVersions",value:function(P){this.transport.reply(P,{supported_versions:a.CurrentApiVersions})}},{key:"handleCapabilitiesRenegotiate",value:function(P){var K,U=this;this.transport.reply(P,{});var C=((K=P.data)===null||K===void 0?void 0:K.capabilities)||[],A=new Set(C.filter(function(T){return!U.hasCapability(T)}));if(A.size===0)return this.notifyCapabilities([]);this.driver.validateCapabilities(A).then(function(T){T.forEach(function(ne){return U.allowedCapabilities.add(ne)});var X=c.WidgetEventCapability.findEventCapabilities(T);return X.forEach(function(ne){return U.allowedEvents.push(ne)}),U.notifyCapabilities(Array.from(A))})}},{key:"handleNavigate",value:function(P){var K,U,C=this;if(!this.hasCapability(o.MatrixCapabilities.MSC2931Navigate))return this.transport.reply(P,{error:{message:"Missing capability"}});if(!((K=P.data)!==null&&K!==void 0&&K.uri)||!((U=P.data)!==null&&U!==void 0&&U.uri.toString().startsWith("https://matrix.to/#")))return this.transport.reply(P,{error:{message:"Invalid matrix.to URI"}});var A=function(X){return console.error("[ClientWidgetApi] Failed to handle navigation: ",X),C.transport.reply(P,{error:{message:"Error handling navigation"}})};try{this.driver.navigate(P.data.uri.toString()).catch(function(T){return A(T)}).then(function(){return C.transport.reply(P,{})})}catch(T){return A(T)}}},{key:"handleOIDC",value:function(P){var K=this,U=1,C=function(ne,ae){return ae=ae||{},U>1?K.transport.send(i.WidgetApiToWidgetAction.OpenIDCredentials,l({state:ne,original_request_id:P.requestId},ae)):K.transport.reply(P,l({state:ne},ae))},A=function(ne){return console.error("[ClientWidgetApi] Failed to handle OIDC: ",ne),U>1?C(f.OpenIDRequestState.Blocked):K.transport.reply(P,{error:{message:ne}})},T=new v.SimpleObservable(function(X){if(X.state===f.OpenIDRequestState.PendingUserConfirmation&&U>1)return T.close(),A("client provided out-of-phase response to OIDC flow");if(X.state===f.OpenIDRequestState.PendingUserConfirmation){C(X.state),U++;return}return X.state===f.OpenIDRequestState.Allowed&&!X.token?A("client provided invalid OIDC token for an allowed request"):(X.state===f.OpenIDRequestState.Blocked&&(X.token=null),T.close(),C(X.state,X.token))});this.driver.askOpenID(T)}},{key:"handleReadEvents",value:function(P){var K=this;if(!P.data.type)return this.transport.reply(P,{error:{message:"Invalid request - missing event type"}});if(P.data.limit!==void 0&&(!P.data.limit||P.data.limit<0))return this.transport.reply(P,{error:{message:"Invalid request - limit out of range"}});var U=null;if(P.data.room_ids){U=P.data.room_ids,Array.isArray(U)||(U=[U]);var C=m(U),A;try{for(C.s();!(A=C.n()).done;){var T=A.value;if(!this.canUseRoomTimeline(T))return this.transport.reply(P,{error:{message:"Unable to access room timeline: ".concat(T)}})}}catch(pe){C.e(pe)}finally{C.f()}}var X=P.data.limit||0,ne=Promise.resolve([]);if(P.data.state_key!==void 0){var ae=P.data.state_key===!0?void 0:P.data.state_key.toString();if(!this.canReceiveStateEvent(P.data.type,ae))return this.transport.reply(P,{error:{message:"Cannot read state events of this type"}});ne=this.driver.readStateEvents(P.data.type,ae,X,U)}else{if(!this.canReceiveRoomEvent(P.data.type,P.data.msgtype))return this.transport.reply(P,{error:{message:"Cannot read room events of this type"}});ne=this.driver.readRoomEvents(P.data.type,P.data.msgtype,X,U)}return ne.then(function(pe){return K.transport.reply(P,{events:pe})})}},{key:"handleSendEvent",value:function(P){var K=this;if(!P.data.type)return this.transport.reply(P,{error:{message:"Invalid request - missing event type"}});if(P.data.room_id&&!this.canUseRoomTimeline(P.data.room_id))return this.transport.reply(P,{error:{message:"Unable to access room timeline: ".concat(P.data.room_id)}});var U=P.data.state_key!==null&&P.data.state_key!==void 0,C;if(U){if(!this.canSendStateEvent(P.data.type,P.data.state_key))return this.transport.reply(P,{error:{message:"Cannot send state events of this type"}});C=this.driver.sendEvent(P.data.type,P.data.content||{},P.data.state_key,P.data.room_id)}else{var A=P.data.content||{},T=A.msgtype;if(!this.canSendRoomEvent(P.data.type,T))return this.transport.reply(P,{error:{message:"Cannot send room events of this type"}});C=this.driver.sendEvent(P.data.type,A,null,P.data.room_id)}C.then(function(X){return K.transport.reply(P,{room_id:X.roomId,event_id:X.eventId})}).catch(function(X){return console.error("error sending event: ",X),K.transport.reply(P,{error:{message:"Error sending event"}})})}},{key:"handleSendToDevice",value:function(){var R=S(g().mark(function K(U){return g().wrap(function(A){for(;;)switch(A.prev=A.next){case 0:if(U.data.type){A.next=5;break}return A.next=3,this.transport.reply(U,{error:{message:"Invalid request - missing event type"}});case 3:A.next=32;break;case 5:if(U.data.messages){A.next=10;break}return A.next=8,this.transport.reply(U,{error:{message:"Invalid request - missing event contents"}});case 8:A.next=32;break;case 10:if(typeof U.data.encrypted=="boolean"){A.next=15;break}return A.next=13,this.transport.reply(U,{error:{message:"Invalid request - missing encryption flag"}});case 13:A.next=32;break;case 15:if(this.canSendToDeviceEvent(U.data.type)){A.next=20;break}return A.next=18,this.transport.reply(U,{error:{message:"Cannot send to-device events of this type"}});case 18:A.next=32;break;case 20:return A.prev=20,A.next=23,this.driver.sendToDevice(U.data.type,U.data.encrypted,U.data.messages);case 23:return A.next=25,this.transport.reply(U,{});case 25:A.next=32;break;case 27:return A.prev=27,A.t0=A.catch(20),console.error("error sending to-device event",A.t0),A.next=32,this.transport.reply(U,{error:{message:"Error sending event"}});case 32:case"end":return A.stop()}},K,this,[[20,27]])}));function P(K){return R.apply(this,arguments)}return P}()},{key:"pollTurnServers",value:function(){var R=S(g().mark(function K(U,C){var A,T,X,ne,ae,pe;return g().wrap(function(se){for(;;)switch(se.prev=se.next){case 0:return se.prev=0,se.next=3,this.transport.send(i.WidgetApiToWidgetAction.UpdateTurnServers,C);case 3:A=!1,T=!1,se.prev=5,ne=D(U);case 7:return se.next=9,ne.next();case 9:if(!(A=!(ae=se.sent).done)){se.next=16;break}return pe=ae.value,se.next=13,this.transport.send(i.WidgetApiToWidgetAction.UpdateTurnServers,pe);case 13:A=!1,se.next=7;break;case 16:se.next=22;break;case 18:se.prev=18,se.t0=se.catch(5),T=!0,X=se.t0;case 22:if(se.prev=22,se.prev=23,!(A&&ne.return!=null)){se.next=27;break}return se.next=27,ne.return();case 27:if(se.prev=27,!T){se.next=30;break}throw X;case 30:return se.finish(27);case 31:return se.finish(22);case 32:se.next=37;break;case 34:se.prev=34,se.t1=se.catch(0),console.error("error polling for TURN servers",se.t1);case 37:case"end":return se.stop()}},K,this,[[0,34],[5,18,22,32],[23,,27,31]])}));function P(K,U){return R.apply(this,arguments)}return P}()},{key:"handleWatchTurnServers",value:function(){var R=S(g().mark(function K(U){var C,A,T,X;return g().wrap(function(ae){for(;;)switch(ae.prev=ae.next){case 0:if(this.hasCapability(o.MatrixCapabilities.MSC3846TurnServers)){ae.next=5;break}return ae.next=3,this.transport.reply(U,{error:{message:"Missing capability"}});case 3:ae.next=30;break;case 5:if(!this.turnServers){ae.next=10;break}return ae.next=8,this.transport.reply(U,{});case 8:ae.next=30;break;case 10:return ae.prev=10,C=this.driver.getTurnServers(),ae.next=14,C.next();case 14:if(A=ae.sent,T=A.done,X=A.value,!T){ae.next=19;break}throw new Error("Client refuses to provide any TURN servers");case 19:return ae.next=21,this.transport.reply(U,{});case 21:this.pollTurnServers(C,X),this.turnServers=C,ae.next=30;break;case 25:return ae.prev=25,ae.t0=ae.catch(10),console.error("error getting first TURN server results",ae.t0),ae.next=30,this.transport.reply(U,{error:{message:"TURN servers not available"}});case 30:case"end":return ae.stop()}},K,this,[[10,25]])}));function P(K){return R.apply(this,arguments)}return P}()},{key:"handleUnwatchTurnServers",value:function(){var R=S(g().mark(function K(U){return g().wrap(function(A){for(;;)switch(A.prev=A.next){case 0:if(this.hasCapability(o.MatrixCapabilities.MSC3846TurnServers)){A.next=5;break}return A.next=3,this.transport.reply(U,{error:{message:"Missing capability"}});case 3:A.next=15;break;case 5:if(this.turnServers){A.next=10;break}return A.next=8,this.transport.reply(U,{});case 8:A.next=15;break;case 10:return A.next=12,this.turnServers.return(void 0);case 12:return this.turnServers=null,A.next=15,this.transport.reply(U,{});case 15:case"end":return A.stop()}},K,this)}));function P(K){return R.apply(this,arguments)}return P}()},{key:"handleReadRelations",value:function(){var R=S(g().mark(function K(U){var C=this,A,T;return g().wrap(function(ne){for(;;)switch(ne.prev=ne.next){case 0:if(U.data.event_id){ne.next=2;break}return ne.abrupt("return",this.transport.reply(U,{error:{message:"Invalid request - missing event ID"}}));case 2:if(!(U.data.limit!==void 0&&U.data.limit<0)){ne.next=4;break}return ne.abrupt("return",this.transport.reply(U,{error:{message:"Invalid request - limit out of range"}}));case 4:if(!(U.data.room_id!==void 0&&!this.canUseRoomTimeline(U.data.room_id))){ne.next=6;break}return ne.abrupt("return",this.transport.reply(U,{error:{message:"Unable to access room timeline: ".concat(U.data.room_id)}}));case 6:return ne.prev=6,ne.next=9,this.driver.readEventRelations(U.data.event_id,U.data.room_id,U.data.rel_type,U.data.event_type,U.data.from,U.data.to,U.data.limit,U.data.direction);case 9:if(A=ne.sent,!A.originalEvent){ne.next=18;break}if(A.originalEvent.state_key===void 0){ne.next=16;break}if(this.canReceiveStateEvent(A.originalEvent.type,A.originalEvent.state_key)){ne.next=14;break}return ne.abrupt("return",this.transport.reply(U,{error:{message:"Cannot read state events of this type"}}));case 14:ne.next=18;break;case 16:if(this.canReceiveRoomEvent(A.originalEvent.type,A.originalEvent.content.msgtype)){ne.next=18;break}return ne.abrupt("return",this.transport.reply(U,{error:{message:"Cannot read room events of this type"}}));case 18:return T=A.chunk.filter(function(ae){return ae.state_key!==void 0?C.canReceiveStateEvent(ae.type,ae.state_key):C.canReceiveRoomEvent(ae.type,ae.content.msgtype)}),ne.abrupt("return",this.transport.reply(U,{original_event:A.originalEvent,chunk:T,prev_batch:A.prevBatch,next_batch:A.nextBatch}));case 22:return ne.prev=22,ne.t0=ne.catch(6),console.error("error getting the relations",ne.t0),ne.next=27,this.transport.reply(U,{error:{message:"Unexpected error while reading relations"}});case 27:case"end":return ne.stop()}},K,this,[[6,22]])}));function P(K){return R.apply(this,arguments)}return P}()},{key:"handleMessage",value:function(P){if(!this.isStopped){var K=new CustomEvent("action:".concat(P.detail.action),{detail:P.detail,cancelable:!0});if(this.emit("action:".concat(P.detail.action),K),!K.defaultPrevented)switch(P.detail.action){case i.WidgetApiFromWidgetAction.ContentLoaded:return this.handleContentLoadedAction(P.detail);case i.WidgetApiFromWidgetAction.SupportedApiVersions:return this.replyVersions(P.detail);case i.WidgetApiFromWidgetAction.SendEvent:return this.handleSendEvent(P.detail);case i.WidgetApiFromWidgetAction.SendToDevice:return this.handleSendToDevice(P.detail);case i.WidgetApiFromWidgetAction.GetOpenIDCredentials:return this.handleOIDC(P.detail);case i.WidgetApiFromWidgetAction.MSC2931Navigate:return this.handleNavigate(P.detail);case i.WidgetApiFromWidgetAction.MSC2974RenegotiateCapabilities:return this.handleCapabilitiesRenegotiate(P.detail);case i.WidgetApiFromWidgetAction.MSC2876ReadEvents:return this.handleReadEvents(P.detail);case i.WidgetApiFromWidgetAction.WatchTurnServers:return this.handleWatchTurnServers(P.detail);case i.WidgetApiFromWidgetAction.UnwatchTurnServers:return this.handleUnwatchTurnServers(P.detail);case i.WidgetApiFromWidgetAction.MSC3869ReadRelations:return this.handleReadRelations(P.detail);default:return this.transport.reply(P.detail,{error:{message:"Unknown or unsupported action: "+P.detail.action}})}}}},{key:"takeScreenshot",value:function(){return this.transport.send(i.WidgetApiToWidgetAction.TakeScreenshot,{})}},{key:"updateVisibility",value:function(P){return this.transport.send(i.WidgetApiToWidgetAction.UpdateVisibility,{visible:P})}},{key:"sendWidgetConfig",value:function(P){return this.transport.send(i.WidgetApiToWidgetAction.WidgetConfig,P).then()}},{key:"notifyModalWidgetButtonClicked",value:function(P){return this.transport.send(i.WidgetApiToWidgetAction.ButtonClicked,{id:P}).then()}},{key:"notifyModalWidgetClose",value:function(P){return this.transport.send(i.WidgetApiToWidgetAction.CloseModalWidget,P).then()}},{key:"feedEvent",value:function(){var R=S(g().mark(function K(U,C){var A;return g().wrap(function(X){for(;;)switch(X.prev=X.next){case 0:if(!(U.room_id!==C&&!this.canUseRoomTimeline(U.room_id))){X.next=2;break}return X.abrupt("return");case 2:if(!(U.state_key!==void 0&&U.state_key!==null)){X.next=7;break}if(this.canReceiveStateEvent(U.type,U.state_key)){X.next=5;break}return X.abrupt("return");case 5:X.next=9;break;case 7:if(this.canReceiveRoomEvent(U.type,(A=U.content)===null||A===void 0?void 0:A.msgtype)){X.next=9;break}return X.abrupt("return");case 9:return X.next=11,this.transport.send(i.WidgetApiToWidgetAction.SendEvent,U);case 11:case"end":return X.stop()}},K,this)}));function P(K,U){return R.apply(this,arguments)}return P}()},{key:"feedToDevice",value:function(){var R=S(g().mark(function K(U,C){return g().wrap(function(T){for(;;)switch(T.prev=T.next){case 0:if(!this.canReceiveToDeviceEvent(U.type)){T.next=3;break}return T.next=3,this.transport.send(i.WidgetApiToWidgetAction.SendToDevice,l(l({},U),{},{encrypted:C}));case 3:case"end":return T.stop()}},K,this)}));function P(K,U){return R.apply(this,arguments)}return P}()}]),H}(t.EventEmitter);return vl.ClientWidgetApi=z,vl}var $p={},uT;function e5(){return uT||(uT=1,Object.defineProperty($p,"__esModule",{value:!0})),$p}var Up={},cT;function t5(){return cT||(cT=1,Object.defineProperty(Up,"__esModule",{value:!0})),Up}var Bp={},dT;function n5(){return dT||(dT=1,Object.defineProperty(Bp,"__esModule",{value:!0})),Bp}var Fp={},fT;function r5(){return fT||(fT=1,Object.defineProperty(Fp,"__esModule",{value:!0})),Fp}var Kp={},hT;function i5(){return hT||(hT=1,Object.defineProperty(Kp,"__esModule",{value:!0})),Kp}var Fc={},pT;function o5(){if(pT)return Fc;pT=1,Object.defineProperty(Fc,"__esModule",{value:!0}),Fc.isErrorResponse=e;function e(t){if("error"in t){var n=t;return!!n.error.message}return!1}return Fc}var jp={},gT;function s5(){return gT||(gT=1,Object.defineProperty(jp,"__esModule",{value:!0})),jp}var qp={},vT;function a5(){return vT||(vT=1,Object.defineProperty(qp,"__esModule",{value:!0})),qp}var Vp={},mT;function l5(){return mT||(mT=1,Object.defineProperty(Vp,"__esModule",{value:!0})),Vp}var Wp={},yT;function u5(){return yT||(yT=1,Object.defineProperty(Wp,"__esModule",{value:!0})),Wp}var Hp={},_T;function c5(){return _T||(_T=1,Object.defineProperty(Hp,"__esModule",{value:!0})),Hp}var Gp={},ST;function d5(){return ST||(ST=1,Object.defineProperty(Gp,"__esModule",{value:!0})),Gp}var zp={},ET;function f5(){return ET||(ET=1,Object.defineProperty(zp,"__esModule",{value:!0})),zp}var Yp={},wT;function h5(){return wT||(wT=1,Object.defineProperty(Yp,"__esModule",{value:!0})),Yp}var Qp={},bT;function p5(){return bT||(bT=1,Object.defineProperty(Qp,"__esModule",{value:!0})),Qp}var Jp={},TT;function g5(){return TT||(TT=1,Object.defineProperty(Jp,"__esModule",{value:!0})),Jp}var bs={},RT;function v5(){if(RT)return bs;RT=1,Object.defineProperty(bs,"__esModule",{value:!0}),bs.WidgetKind=void 0;var e;return bs.WidgetKind=e,function(t){t.Room="room",t.Account="account",t.Modal="modal"}(e||(bs.WidgetKind=e={})),bs}var Ts={},IT;function m5(){if(IT)return Ts;IT=1,Object.defineProperty(Ts,"__esModule",{value:!0}),Ts.ModalButtonKind=void 0;var e;return Ts.ModalButtonKind=e,function(t){t.Primary="m.primary",t.Secondary="m.secondary",t.Warning="m.warning",t.Danger="m.danger",t.Link="m.link"}(e||(Ts.ModalButtonKind=e={})),Ts}var Xp={},CT;function y5(){return CT||(CT=1,Object.defineProperty(Xp,"__esModule",{value:!0})),Xp}var Zp={},OT;function _5(){return OT||(OT=1,Object.defineProperty(Zp,"__esModule",{value:!0})),Zp}var eg={},PT;function S5(){return PT||(PT=1,Object.defineProperty(eg,"__esModule",{value:!0})),eg}var tg={},kT;function E5(){return kT||(kT=1,Object.defineProperty(tg,"__esModule",{value:!0})),tg}var ng={},MT;function w5(){return MT||(MT=1,Object.defineProperty(ng,"__esModule",{value:!0})),ng}var rg={},DT;function b5(){return DT||(DT=1,Object.defineProperty(rg,"__esModule",{value:!0})),rg}var ig={},AT;function T5(){return AT||(AT=1,Object.defineProperty(ig,"__esModule",{value:!0})),ig}var og={},LT;function R5(){return LT||(LT=1,Object.defineProperty(og,"__esModule",{value:!0})),og}var sg={},NT;function I5(){return NT||(NT=1,Object.defineProperty(sg,"__esModule",{value:!0})),sg}var Kc={},xT;function wk(){if(xT)return Kc;xT=1,Object.defineProperty(Kc,"__esModule",{value:!0}),Kc.isValidUrl=e;function e(t){if(!t)return!1;try{var n=new URL(t);return!(n.protocol!=="http"&&n.protocol!=="https")}catch(r){if(r instanceof TypeError)return!1;throw r}}return Kc}var jc={},$T;function bk(){if($T)return jc;$T=1,Object.defineProperty(jc,"__esModule",{value:!0}),jc.assertPresent=e;function e(t,n){if(!t[n])throw new Error("".concat(n," is required"))}return jc}var yl={},UT;function Tk(){if(UT)return yl;UT=1,Object.defineProperty(yl,"__esModule",{value:!0}),yl.Widget=void 0;var e=bk(),t=Qf();function n(a,c){if(!(a instanceof c))throw new TypeError("Cannot call a class as a function")}function r(a,c){for(var f=0;f<c.length;f++){var v=c[f];v.enumerable=v.enumerable||!1,v.configurable=!0,"value"in v&&(v.writable=!0),Object.defineProperty(a,v.key,v)}}function i(a,c,f){return c&&r(a.prototype,c),f&&r(a,f),Object.defineProperty(a,"prototype",{writable:!1}),a}var o=function(){function a(c){if(n(this,a),this.definition=c,!this.definition)throw new Error("Definition is required");(0,e.assertPresent)(c,"id"),(0,e.assertPresent)(c,"creatorUserId"),(0,e.assertPresent)(c,"type"),(0,e.assertPresent)(c,"url")}return i(a,[{key:"creatorUserId",get:function(){return this.definition.creatorUserId}},{key:"type",get:function(){return this.definition.type}},{key:"id",get:function(){return this.definition.id}},{key:"name",get:function(){return this.definition.name||null}},{key:"title",get:function(){return this.rawData.title||null}},{key:"templateUrl",get:function(){return this.definition.url}},{key:"origin",get:function(){return new URL(this.templateUrl).origin}},{key:"waitForIframeLoad",get:function(){return this.definition.waitForIframeLoad===!1?!1:(this.definition.waitForIframeLoad===!0,!0)}},{key:"rawData",get:function(){return this.definition.data||{}}},{key:"getCompleteUrl",value:function(f){return(0,t.runTemplate)(this.templateUrl,this.definition,f)}}]),a}();return yl.Widget=o,yl}var _l={},BT;function C5(){if(BT)return _l;BT=1,Object.defineProperty(_l,"__esModule",{value:!0}),_l.WidgetParser=void 0;var e=Tk(),t=wk();function n(v,s){var g=typeof Symbol<"u"&&v[Symbol.iterator]||v["@@iterator"];if(!g){if(Array.isArray(v)||(g=r(v))||s&&v&&typeof v.length=="number"){g&&(v=g);var y=0,S=function(){};return{s:S,n:function(){return y>=v.length?{done:!0}:{done:!1,value:v[y++]}},e:function(l){throw l},f:S}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
     90 In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var m=!0,p=!1,_;return{s:function(){g=g.call(v)},n:function(){var l=g.next();return m=l.done,l},e:function(l){p=!0,_=l},f:function(){try{!m&&g.return!=null&&g.return()}finally{if(p)throw _}}}}function r(v,s){if(v){if(typeof v=="string")return i(v,s);var g=Object.prototype.toString.call(v).slice(8,-1);if(g==="Object"&&v.constructor&&(g=v.constructor.name),g==="Map"||g==="Set")return Array.from(v);if(g==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(g))return i(v,s)}}function i(v,s){(s==null||s>v.length)&&(s=v.length);for(var g=0,y=new Array(s);g<s;g++)y[g]=v[g];return y}function o(v,s){if(!(v instanceof s))throw new TypeError("Cannot call a class as a function")}function a(v,s){for(var g=0;g<s.length;g++){var y=s[g];y.enumerable=y.enumerable||!1,y.configurable=!0,"value"in y&&(y.writable=!0),Object.defineProperty(v,y.key,y)}}function c(v,s,g){return s&&a(v.prototype,s),g&&a(v,g),Object.defineProperty(v,"prototype",{writable:!1}),v}var f=function(){function v(){o(this,v)}return c(v,null,[{key:"parseAccountData",value:function(g){if(!g)return[];for(var y=[],S=0,m=Object.keys(g);S<m.length;S++){var p=m[S],_=g[p];if(_&&!(_.type!=="m.widget"&&_.type!=="im.vector.modular.widgets")&&_.sender){var u=_.state_key||_.id;if(u===p){var l={content:_.content,sender:_.sender,type:"m.widget",state_key:p,event_id:"$example",room_id:"!example",origin_server_ts:1},d=v.parseRoomWidget(l);d&&y.push(d)}}}return y}},{key:"parseWidgetsFromRoomState",value:function(g){if(!g)return[];var y=[],S=n(g),m;try{for(S.s();!(m=S.n()).done;){var p=m.value,_=v.parseRoomWidget(p);_&&y.push(_)}}catch(u){S.e(u)}finally{S.f()}return y}},{key:"parseRoomWidget",value:function(g){if(!g||g.type!=="m.widget"&&g.type!=="im.vector.modular.widgets")return null;var y=g.content||{},S={id:g.state_key,creatorUserId:y.creatorUserId||g.sender,name:y.name,type:y.type,url:y.url,waitForIframeLoad:y.waitForIframeLoad,data:y.data};return v.processEstimatedWidget(S)}},{key:"processEstimatedWidget",value:function(g){return!g.id||!g.creatorUserId||!g.type||!(0,t.isValidUrl)(g.url)?null:new e.Widget(g)}}]),v}();return _l.WidgetParser=f,_l}var Sl={},FT;function O5(){if(FT)return Sl;FT=1,Object.defineProperty(Sl,"__esModule",{value:!0}),Sl.runTemplate=e,Sl.toString=t;function e(n,r,i){for(var o=Object.assign({},r.data,{matrix_room_id:i.widgetRoomId||"",matrix_user_id:i.currentUserId,matrix_display_name:i.userDisplayName||i.currentUserId,matrix_avatar_url:i.userHttpAvatarUrl||"",matrix_widget_id:r.id,"org.matrix.msc2873.client_id":i.clientId||"","org.matrix.msc2873.client_theme":i.clientTheme||"","org.matrix.msc2873.client_language":i.clientLanguage||""}),a=n,c=0,f=Object.keys(o);c<f.length;c++){var v=f[c],s="$".concat(v).replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),g=new RegExp(s,"g");a=a.replace(g,encodeURIComponent(t(o[v])))}return a}function t(n){return n==null?"".concat(n):n.toString()}return Sl}var El={},KT;function P5(){if(KT)return El;KT=1,Object.defineProperty(El,"__esModule",{value:!0}),El.WidgetDriver=void 0;var e=Qf();function t(o,a){if(!(o instanceof a))throw new TypeError("Cannot call a class as a function")}function n(o,a){for(var c=0;c<a.length;c++){var f=a[c];f.enumerable=f.enumerable||!1,f.configurable=!0,"value"in f&&(f.writable=!0),Object.defineProperty(o,f.key,f)}}function r(o,a,c){return a&&n(o.prototype,a),c&&n(o,c),Object.defineProperty(o,"prototype",{writable:!1}),o}var i=function(){function o(){t(this,o)}return r(o,[{key:"validateCapabilities",value:function(c){return Promise.resolve(new Set)}},{key:"sendEvent",value:function(c,f){return Promise.reject(new Error("Failed to override function"))}},{key:"sendToDevice",value:function(c,f,v){return Promise.reject(new Error("Failed to override function"))}},{key:"readRoomEvents",value:function(c,f,v){return Promise.resolve([])}},{key:"readStateEvents",value:function(c,f,v){return Promise.resolve([])}},{key:"readEventRelations",value:function(c,f,v,s,g,y,S,m){return Promise.resolve({chunk:[]})}},{key:"askOpenID",value:function(c){c.update({state:e.OpenIDRequestState.Blocked})}},{key:"navigate",value:function(c){throw new Error("Navigation is not implemented")}},{key:"getTurnServers",value:function(){throw new Error("TURN server support is not implemented")}}]),o}();return El.WidgetDriver=i,El}var jT;function Qf(){return jT||(jT=1,function(e){Object.defineProperty(e,"__esModule",{value:!0});var t=X3();Object.keys(t).forEach(function(V){V==="default"||V==="__esModule"||V in e&&e[V]===t[V]||Object.defineProperty(e,V,{enumerable:!0,get:function(){return t[V]}})});var n=Z3();Object.keys(n).forEach(function(V){V==="default"||V==="__esModule"||V in e&&e[V]===n[V]||Object.defineProperty(e,V,{enumerable:!0,get:function(){return n[V]}})});var r=p_();Object.keys(r).forEach(function(V){V==="default"||V==="__esModule"||V in e&&e[V]===r[V]||Object.defineProperty(e,V,{enumerable:!0,get:function(){return r[V]}})});var i=e5();Object.keys(i).forEach(function(V){V==="default"||V==="__esModule"||V in e&&e[V]===i[V]||Object.defineProperty(e,V,{enumerable:!0,get:function(){return i[V]}})});var o=c_();Object.keys(o).forEach(function(V){V==="default"||V==="__esModule"||V in e&&e[V]===o[V]||Object.defineProperty(e,V,{enumerable:!0,get:function(){return o[V]}})});var a=t5();Object.keys(a).forEach(function(V){V==="default"||V==="__esModule"||V in e&&e[V]===a[V]||Object.defineProperty(e,V,{enumerable:!0,get:function(){return a[V]}})});var c=n5();Object.keys(c).forEach(function(V){V==="default"||V==="__esModule"||V in e&&e[V]===c[V]||Object.defineProperty(e,V,{enumerable:!0,get:function(){return c[V]}})});var f=r5();Object.keys(f).forEach(function(V){V==="default"||V==="__esModule"||V in e&&e[V]===f[V]||Object.defineProperty(e,V,{enumerable:!0,get:function(){return f[V]}})});var v=i5();Object.keys(v).forEach(function(V){V==="default"||V==="__esModule"||V in e&&e[V]===v[V]||Object.defineProperty(e,V,{enumerable:!0,get:function(){return v[V]}})});var s=yk();Object.keys(s).forEach(function(V){V==="default"||V==="__esModule"||V in e&&e[V]===s[V]||Object.defineProperty(e,V,{enumerable:!0,get:function(){return s[V]}})});var g=o5();Object.keys(g).forEach(function(V){V==="default"||V==="__esModule"||V in e&&e[V]===g[V]||Object.defineProperty(e,V,{enumerable:!0,get:function(){return g[V]}})});var y=s5();Object.keys(y).forEach(function(V){V==="default"||V==="__esModule"||V in e&&e[V]===y[V]||Object.defineProperty(e,V,{enumerable:!0,get:function(){return y[V]}})});var S=a5();Object.keys(S).forEach(function(V){V==="default"||V==="__esModule"||V in e&&e[V]===S[V]||Object.defineProperty(e,V,{enumerable:!0,get:function(){return S[V]}})});var m=d_();Object.keys(m).forEach(function(V){V==="default"||V==="__esModule"||V in e&&e[V]===m[V]||Object.defineProperty(e,V,{enumerable:!0,get:function(){return m[V]}})});var p=l_();Object.keys(p).forEach(function(V){V==="default"||V==="__esModule"||V in e&&e[V]===p[V]||Object.defineProperty(e,V,{enumerable:!0,get:function(){return p[V]}})});var _=u_();Object.keys(_).forEach(function(V){V==="default"||V==="__esModule"||V in e&&e[V]===_[V]||Object.defineProperty(e,V,{enumerable:!0,get:function(){return _[V]}})});var u=Sk();Object.keys(u).forEach(function(V){V==="default"||V==="__esModule"||V in e&&e[V]===u[V]||Object.defineProperty(e,V,{enumerable:!0,get:function(){return u[V]}})});var l=l5();Object.keys(l).forEach(function(V){V==="default"||V==="__esModule"||V in e&&e[V]===l[V]||Object.defineProperty(e,V,{enumerable:!0,get:function(){return l[V]}})});var d=u5();Object.keys(d).forEach(function(V){V==="default"||V==="__esModule"||V in e&&e[V]===d[V]||Object.defineProperty(e,V,{enumerable:!0,get:function(){return d[V]}})});var h=c5();Object.keys(h).forEach(function(V){V==="default"||V==="__esModule"||V in e&&e[V]===h[V]||Object.defineProperty(e,V,{enumerable:!0,get:function(){return h[V]}})});var w=d5();Object.keys(w).forEach(function(V){V==="default"||V==="__esModule"||V in e&&e[V]===w[V]||Object.defineProperty(e,V,{enumerable:!0,get:function(){return w[V]}})});var E=f5();Object.keys(E).forEach(function(V){V==="default"||V==="__esModule"||V in e&&e[V]===E[V]||Object.defineProperty(e,V,{enumerable:!0,get:function(){return E[V]}})});var I=h5();Object.keys(I).forEach(function(V){V==="default"||V==="__esModule"||V in e&&e[V]===I[V]||Object.defineProperty(e,V,{enumerable:!0,get:function(){return I[V]}})});var k=p5();Object.keys(k).forEach(function(V){V==="default"||V==="__esModule"||V in e&&e[V]===k[V]||Object.defineProperty(e,V,{enumerable:!0,get:function(){return k[V]}})});var M=f_();Object.keys(M).forEach(function(V){V==="default"||V==="__esModule"||V in e&&e[V]===M[V]||Object.defineProperty(e,V,{enumerable:!0,get:function(){return M[V]}})});var L=g5();Object.keys(L).forEach(function(V){V==="default"||V==="__esModule"||V in e&&e[V]===L[V]||Object.defineProperty(e,V,{enumerable:!0,get:function(){return L[V]}})});var B=v5();Object.keys(B).forEach(function(V){V==="default"||V==="__esModule"||V in e&&e[V]===B[V]||Object.defineProperty(e,V,{enumerable:!0,get:function(){return B[V]}})});var N=m5();Object.keys(N).forEach(function(V){V==="default"||V==="__esModule"||V in e&&e[V]===N[V]||Object.defineProperty(e,V,{enumerable:!0,get:function(){return N[V]}})});var G=_k();Object.keys(G).forEach(function(V){V==="default"||V==="__esModule"||V in e&&e[V]===G[V]||Object.defineProperty(e,V,{enumerable:!0,get:function(){return G[V]}})});var D=y5();Object.keys(D).forEach(function(V){V==="default"||V==="__esModule"||V in e&&e[V]===D[V]||Object.defineProperty(e,V,{enumerable:!0,get:function(){return D[V]}})});var x=_5();Object.keys(x).forEach(function(V){V==="default"||V==="__esModule"||V in e&&e[V]===x[V]||Object.defineProperty(e,V,{enumerable:!0,get:function(){return x[V]}})});var z=S5();Object.keys(z).forEach(function(V){V==="default"||V==="__esModule"||V in e&&e[V]===z[V]||Object.defineProperty(e,V,{enumerable:!0,get:function(){return z[V]}})});var W=E5();Object.keys(W).forEach(function(V){V==="default"||V==="__esModule"||V in e&&e[V]===W[V]||Object.defineProperty(e,V,{enumerable:!0,get:function(){return W[V]}})});var F=w5();Object.keys(F).forEach(function(V){V==="default"||V==="__esModule"||V in e&&e[V]===F[V]||Object.defineProperty(e,V,{enumerable:!0,get:function(){return F[V]}})});var H=b5();Object.keys(H).forEach(function(V){V==="default"||V==="__esModule"||V in e&&e[V]===H[V]||Object.defineProperty(e,V,{enumerable:!0,get:function(){return H[V]}})});var R=T5();Object.keys(R).forEach(function(V){V==="default"||V==="__esModule"||V in e&&e[V]===R[V]||Object.defineProperty(e,V,{enumerable:!0,get:function(){return R[V]}})});var P=R5();Object.keys(P).forEach(function(V){V==="default"||V==="__esModule"||V in e&&e[V]===P[V]||Object.defineProperty(e,V,{enumerable:!0,get:function(){return P[V]}})});var K=I5();Object.keys(K).forEach(function(V){V==="default"||V==="__esModule"||V in e&&e[V]===K[V]||Object.defineProperty(e,V,{enumerable:!0,get:function(){return K[V]}})});var U=h_();Object.keys(U).forEach(function(V){V==="default"||V==="__esModule"||V in e&&e[V]===U[V]||Object.defineProperty(e,V,{enumerable:!0,get:function(){return U[V]}})});var C=wk();Object.keys(C).forEach(function(V){V==="default"||V==="__esModule"||V in e&&e[V]===C[V]||Object.defineProperty(e,V,{enumerable:!0,get:function(){return C[V]}})});var A=bk();Object.keys(A).forEach(function(V){V==="default"||V==="__esModule"||V in e&&e[V]===A[V]||Object.defineProperty(e,V,{enumerable:!0,get:function(){return A[V]}})});var T=Tk();Object.keys(T).forEach(function(V){V==="default"||V==="__esModule"||V in e&&e[V]===T[V]||Object.defineProperty(e,V,{enumerable:!0,get:function(){return T[V]}})});var X=C5();Object.keys(X).forEach(function(V){V==="default"||V==="__esModule"||V in e&&e[V]===X[V]||Object.defineProperty(e,V,{enumerable:!0,get:function(){return X[V]}})});var ne=O5();Object.keys(ne).forEach(function(V){V==="default"||V==="__esModule"||V in e&&e[V]===ne[V]||Object.defineProperty(e,V,{enumerable:!0,get:function(){return ne[V]}})});var ae=Ek();Object.keys(ae).forEach(function(V){V==="default"||V==="__esModule"||V in e&&e[V]===ae[V]||Object.defineProperty(e,V,{enumerable:!0,get:function(){return ae[V]}})});var pe=P5();Object.keys(pe).forEach(function(V){V==="default"||V==="__esModule"||V in e&&e[V]===pe[V]||Object.defineProperty(e,V,{enumerable:!0,get:function(){return pe[V]}})})}(xp)),xp}var k5=Ae;Object.defineProperty(Yf,"__esModule",{value:!0});Yf.RoomWidgetClient=void 0;var Rs=k5(Ue),wl=Qf(),bl=nn(),M5=xe,Is=Ge(),Cs=or(),qc=Vf(),D5=gk(),A5=Xn;class L5 extends Cs.MatrixClient{constructor(t,n,r,i){var o,a,c,f,v,s,g,y,S,m;super(i),this.widgetApi=t,this.capabilities=n,this.roomId=r,(0,Rs.default)(this,"room",void 0),(0,Rs.default)(this,"widgetApiReady",new Promise(p=>this.widgetApi.once("ready",p))),(0,Rs.default)(this,"lifecycle",void 0),(0,Rs.default)(this,"syncState",null),(0,Rs.default)(this,"onEvent",async p=>{if(p.preventDefault(),p.detail.data.room_id===this.roomId){const _=new bl.MatrixEvent(p.detail.data);await this.syncApi.injectRoomEvents(this.room,[],[_]),this.emit(Cs.ClientEvent.Event,_),this.setSyncState(qc.SyncState.Syncing),Is.logger.info(`Received event ${_.getId()} ${_.getType()} ${_.getStateKey()}`)}else{const{event_id:_,room_id:u}=p.detail.data;Is.logger.info(`Received event ${_} for a different room ${u}; discarding`)}await this.ack(p)}),(0,Rs.default)(this,"onToDevice",async p=>{p.preventDefault();const _=new bl.MatrixEvent({type:p.detail.data.type,sender:p.detail.data.sender,content:p.detail.data.content});p.detail.data.encrypted&&_.makeEncrypted(M5.EventType.RoomMessageEncrypted,{},"",""),this.emit(Cs.ClientEvent.ToDeviceEvent,_),this.setSyncState(qc.SyncState.Syncing),await this.ack(p)}),((o=n.sendEvent)!==null&&o!==void 0&&o.length||(a=n.receiveEvent)!==null&&a!==void 0&&a.length||n.sendMessage===!0||Array.isArray(n.sendMessage)&&n.sendMessage.length||n.receiveMessage===!0||Array.isArray(n.receiveMessage)&&n.receiveMessage.length||(c=n.sendState)!==null&&c!==void 0&&c.length||(f=n.receiveState)!==null&&f!==void 0&&f.length)&&t.requestCapabilityForRoomTimeline(r),(v=n.sendEvent)===null||v===void 0||v.forEach(p=>t.requestCapabilityToSendEvent(p)),(s=n.receiveEvent)===null||s===void 0||s.forEach(p=>t.requestCapabilityToReceiveEvent(p)),n.sendMessage===!0?t.requestCapabilityToSendMessage():Array.isArray(n.sendMessage)&&n.sendMessage.forEach(p=>t.requestCapabilityToSendMessage(p)),n.receiveMessage===!0?t.requestCapabilityToReceiveMessage():Array.isArray(n.receiveMessage)&&n.receiveMessage.forEach(p=>t.requestCapabilityToReceiveMessage(p)),(g=n.sendState)===null||g===void 0||g.forEach(({eventType:p,stateKey:_})=>t.requestCapabilityToSendState(p,_)),(y=n.receiveState)===null||y===void 0||y.forEach(({eventType:p,stateKey:_})=>t.requestCapabilityToReceiveState(p,_)),(S=n.sendToDevice)===null||S===void 0||S.forEach(p=>t.requestCapabilityToSendToDevice(p)),(m=n.receiveToDevice)===null||m===void 0||m.forEach(p=>t.requestCapabilityToReceiveToDevice(p)),n.turnServers&&t.requestCapability(wl.MatrixCapabilities.MSC3846TurnServers),t.on(`action:${wl.WidgetApiToWidgetAction.SendEvent}`,this.onEvent),t.on(`action:${wl.WidgetApiToWidgetAction.SendToDevice}`,this.onToDevice),t.start()}async startClient(t={}){var n,r;this.lifecycle=new AbortController;const i=this.getUserId();i&&this.store.storeUser(new A5.User(i)),t.slidingSync?this.syncApi=new D5.SlidingSyncSdk(t.slidingSync,this,t):this.syncApi=new qc.SyncApi(this,t),this.room=this.syncApi.createRoom(this.roomId),this.store.storeRoom(this.room),await this.widgetApiReady,await Promise.all((n=(r=this.capabilities.receiveState)===null||r===void 0?void 0:r.map(async({eventType:o,stateKey:a})=>{const f=(await this.widgetApi.readStateEvents(o,void 0,a,[this.roomId])).map(v=>new bl.MatrixEvent(v));await this.syncApi.injectRoomEvents(this.room,[],f),f.forEach(v=>{this.emit(Cs.ClientEvent.Event,v),Is.logger.info(`Backfilled event ${v.getId()} ${v.getType()} ${v.getStateKey()}`)})}))!==null&&n!==void 0?n:[]),this.setSyncState(qc.SyncState.Syncing),Is.logger.info("Finished backfilling events"),this.capabilities.turnServers&&this.watchTurnServers()}stopClient(){this.widgetApi.off(`action:${wl.WidgetApiToWidgetAction.SendEvent}`,this.onEvent),this.widgetApi.off(`action:${wl.WidgetApiToWidgetAction.SendToDevice}`,this.onToDevice),super.stopClient(),this.lifecycle.abort()}async joinRoom(t){if(t===this.roomId)return this.room;throw new Error(`Unknown room: ${t}`)}async encryptAndSendEvent(t,n){let r;try{r=await this.widgetApi.sendRoomEvent(n.getType(),n.getContent(),t.roomId)}catch(i){throw this.updatePendingEventStatus(t,n,bl.EventStatus.NOT_SENT),i}return t.updatePendingEvent(n,bl.EventStatus.SENT,r.event_id),{event_id:r.event_id}}async sendStateEvent(t,n,r,i=""){return await this.widgetApi.sendStateEvent(n,i,r,t)}async sendToDevice(t,n){return await this.widgetApi.sendToDevice(t,!1,n),{}}async queueToDevice({eventType:t,batch:n}){const r={};for(const{userId:i,deviceId:o,payload:a}of n)r[i]||(r[i]={}),r[i][o]=a;await this.widgetApi.sendToDevice(t,!1,r)}async encryptAndSendToDevices(t,n){const r={};for(const{userId:i,deviceInfo:{deviceId:o}}of t)r[i]||(r[i]={}),r[i][o]=n;await this.widgetApi.sendToDevice(n.type,!0,r)}async checkTurnServers(){return this.turnServers.length>0}getSyncState(){return this.syncState}setSyncState(t){const n=this.syncState;this.syncState=t,this.emit(Cs.ClientEvent.Sync,t,n)}async ack(t){await this.widgetApi.transport.reply(t.detail,{})}async watchTurnServers(){const t=this.widgetApi.getTurnServers(),n=()=>{t.return(void 0)};this.lifecycle.signal.addEventListener("abort",n);try{for await(const r of t)this.turnServers=[{urls:r.uris,username:r.username,credential:r.password}],this.emit(Cs.ClientEvent.TurnServers,this.turnServers),Is.logger.log(`Received TURN server: ${r.uris}`)}catch(r){Is.logger.warn("Error watching TURN servers",r)}finally{this.lifecycle.signal.removeEventListener("abort",n)}}}Yf.RoomWidgetClient=L5;var oo={},N5=Ae;Object.defineProperty(oo,"__esModule",{value:!0});oo.SyncAccumulator=oo.Category=void 0;var xl=N5(Ue),x5=Ge(),qT=lt(),VT=xe,$5=Sa(),WT=jf();function HT(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),n.push.apply(n,r)}return n}function Vc(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?HT(Object(n),!0).forEach(function(r){(0,xl.default)(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):HT(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}let Zr;oo.Category=Zr;(function(e){e.Invite="invite",e.Leave="leave",e.Join="join"})(Zr||(oo.Category=Zr={}));function U5(e){return"_localTs"in e&&e._localTs!==void 0}class B5{constructor(t={}){this.opts=t,(0,xl.default)(this,"accountData",{}),(0,xl.default)(this,"inviteRooms",{}),(0,xl.default)(this,"joinRooms",{}),(0,xl.default)(this,"nextBatch",null),this.opts.maxTimelineEntries=this.opts.maxTimelineEntries||50}accumulate(t,n=!1){this.accumulateRooms(t,n),this.accumulateAccountData(t),this.nextBatch=t.next_batch}accumulateAccountData(t){!t.account_data||!t.account_data.events||t.account_data.events.forEach(n=>{this.accountData[n.type]=n})}accumulateRooms(t,n=!1){t.rooms&&(t.rooms.invite&&Object.keys(t.rooms.invite).forEach(r=>{this.accumulateRoom(r,Zr.Invite,t.rooms.invite[r],n)}),t.rooms.join&&Object.keys(t.rooms.join).forEach(r=>{this.accumulateRoom(r,Zr.Join,t.rooms.join[r],n)}),t.rooms.leave&&Object.keys(t.rooms.leave).forEach(r=>{this.accumulateRoom(r,Zr.Leave,t.rooms.leave[r],n)}))}accumulateRoom(t,n,r,i=!1){switch(n){case Zr.Invite:this.accumulateInviteState(t,r);break;case Zr.Join:this.inviteRooms[t]&&delete this.inviteRooms[t],this.accumulateJoinState(t,r,i);break;case Zr.Leave:this.inviteRooms[t]?delete this.inviteRooms[t]:delete this.joinRooms[t];break;default:x5.logger.error("Unknown cateogory: ",n)}}accumulateInviteState(t,n){if(!n.invite_state||!n.invite_state.events)return;if(!this.inviteRooms[t]){this.inviteRooms[t]={invite_state:n.invite_state};return}const r=this.inviteRooms[t];n.invite_state.events.forEach(i=>{let o=!1;for(let a=0;a<r.invite_state.events.length;a++){const c=r.invite_state.events[a];c.type===i.type&&c.state_key==i.state_key&&(r.invite_state.events[a]=i,o=!0)}o||r.invite_state.events.push(i)})}accumulateJoinState(t,n,r=!1){var i,o,a,c,f,v,s,g;this.joinRooms[t]||(this.joinRooms[t]={_currentState:Object.create(null),_timeline:[],_accountData:Object.create(null),_unreadNotifications:{},_unreadThreadNotifications:{},_summary:{},_readReceipts:{},_threadReadReceipts:{}});const y=this.joinRooms[t];if(n.account_data&&n.account_data.events&&n.account_data.events.forEach(S=>{y._accountData[S.type]=S}),n.unread_notifications&&(y._unreadNotifications=n.unread_notifications),y._unreadThreadNotifications=(i=(o=n[WT.UNREAD_THREAD_NOTIFICATIONS.stable])!==null&&o!==void 0?o:n[WT.UNREAD_THREAD_NOTIFICATIONS.unstable])!==null&&i!==void 0?i:void 0,n.summary){const S="m.heroes",m="m.invited_member_count",p="m.joined_member_count",_=y._summary,u=n.summary;_[S]=u[S]||_[S],_[p]=u[p]||_[p],_[m]=u[m]||_[m]}if((a=n.ephemeral)===null||a===void 0||(c=a.events)===null||c===void 0||c.forEach(S=>{S.type!==VT.EventType.Receipt||!S.content||Object.keys(S.content).forEach(m=>{Object.entries(S.content[m]).forEach(([p,_])=>{if((0,qT.isSupportedReceiptType)(p))for(const l of Object.keys(_)){const d=S.content[m][p][l],h={data:S.content[m][p][l],type:p,eventId:m};if(!d.thread_id||d.thread_id===$5.MAIN_ROOM_TIMELINE)y._readReceipts[l]=h;else{var u;y._threadReadReceipts=Vc(Vc({},y._threadReadReceipts),{},{[d.thread_id]:Vc(Vc({},(u=y._threadReadReceipts[d.thread_id])!==null&&u!==void 0?u:{}),{},{[l]:h})})}}})})}),n.timeline&&n.timeline.limited&&(y._timeline=[]),(f=n.state)===null||f===void 0||(v=f.events)===null||v===void 0||v.forEach(S=>{ag(y._currentState,S)}),(s=n.timeline)===null||s===void 0||(g=s.events)===null||g===void 0||g.forEach((S,m)=>{var p;ag(y._currentState,S);let _;if(r)_=S;else{_=Object.assign({},S),_.unsigned!==void 0&&(_.unsigned=Object.assign({},_.unsigned));const u=S.unsigned?S.unsigned.age:S.age;u!==void 0&&(_._localTs=Date.now()-u)}y._timeline.push({event:_,token:m===0&&(p=n.timeline.prev_batch)!==null&&p!==void 0?p:null})}),y._timeline.length>this.opts.maxTimelineEntries){const S=y._timeline.length-this.opts.maxTimelineEntries;for(let m=S;m<y._timeline.length;m++)if(y._timeline[m].token){y._timeline=y._timeline.slice(m,y._timeline.length);break}}}getJSON(t=!1){const n={join:{},invite:{},leave:{}};Object.keys(this.inviteRooms).forEach(i=>{n.invite[i]=this.inviteRooms[i]}),Object.keys(this.joinRooms).forEach(i=>{const o=this.joinRooms[i],a={ephemeral:{events:[]},account_data:{events:[]},state:{events:[]},timeline:{events:[],prev_batch:null},unread_notifications:o._unreadNotifications,unread_thread_notifications:o._unreadThreadNotifications,summary:o._summary};Object.keys(o._accountData).forEach(v=>{a.account_data.events.push(o._accountData[v])});const c={type:VT.EventType.Receipt,room_id:i,content:{}};for(const[v,s]of Object.entries(o._readReceipts))c.content[s.eventId]||(c.content[s.eventId]={}),c.content[s.eventId][s.type]||(c.content[s.eventId][s.type]={}),c.content[s.eventId][s.type][v]=s.data;for(const v of Object.values(o._threadReadReceipts))for(const[s,g]of Object.entries(v))c.content[g.eventId]||(c.content[g.eventId]={}),c.content[g.eventId][g.type]||(c.content[g.eventId][g.type]={}),c.content[g.eventId][g.type][s]=g.data;Object.keys(c.content).length>0&&a.ephemeral.events.push(c),o._timeline.forEach(v=>{if(!a.timeline.prev_batch){if(!v.token)return;a.timeline.prev_batch=v.token}let s;!t&&U5(v.event)?(s=Object.assign({},v.event),s.unsigned!==void 0&&(s.unsigned=Object.assign({},s.unsigned)),delete s._localTs,s.unsigned=s.unsigned||{},s.unsigned.age=Date.now()-v.event._localTs):s=v.event,a.timeline.events.push(s)});const f=Object.create(null);for(let v=a.timeline.events.length-1;v>=0;v--){const s=a.timeline.events[v];if(s.state_key===null||s.state_key===void 0)continue;const g=(0,qT.deepCopy)(s);g.unsigned&&(g.unsigned.prev_content&&(g.content=g.unsigned.prev_content),g.unsigned.prev_sender&&(g.sender=g.unsigned.prev_sender)),ag(f,g)}Object.keys(o._currentState).forEach(v=>{Object.keys(o._currentState[v]).forEach(s=>{let g=o._currentState[v][s];f[v]&&f[v][s]&&(g=f[v][s]),a.state.events.push(g)})}),n.join[i]=a});const r=[];return Object.keys(this.accountData).forEach(i=>{r.push(this.accountData[i])}),{nextBatch:this.nextBatch,roomsData:n,accountData:r}}getNextBatchToken(){return this.nextBatch}}oo.SyncAccumulator=B5;function ag(e,t){t.state_key===null||t.state_key===void 0||!t.type||(e[t.type]||(e[t.type]=Object.create(null)),e[t.type][t.state_key]=t)}var ha={},F5=Ae;Object.defineProperty(ha,"__esModule",{value:!0});ha.TimelineWindow=ha.TimelineIndex=void 0;var $l=F5(Ue),Jr=Tr();Ge();const GT=function(){},K5=5;class j5{constructor(t,n,r={}){this.client=t,this.timelineSet=n,(0,$l.default)(this,"windowLimit",void 0),(0,$l.default)(this,"start",void 0),(0,$l.default)(this,"end",void 0),(0,$l.default)(this,"eventCount",0),this.windowLimit=r.windowLimit||1e3}load(t,n=20){const r=i=>{if(!i)throw new Error("No timeline given to initFields");let o;const a=i.getEvents();if(!t)o=a.length;else if(o=a.findIndex(v=>v.getId()===t),o<0)throw new Error("getEventTimeline result didn't include requested event");const c=Math.min(a.length,o+Math.ceil(n/2)),f=Math.max(0,c-n);this.start=new vm(i,f-i.getBaseIndex()),this.end=new vm(i,c-i.getBaseIndex()),this.eventCount=c-f};return this.timelineSet.getTimelineForEvent(t)?(r(this.timelineSet.getTimelineForEvent(t)),Promise.resolve()):t?this.client.getEventTimeline(this.timelineSet,t).then(r):(r(this.timelineSet.getLiveTimeline()),Promise.resolve())}getTimelineIndex(t){if(t==Jr.EventTimeline.BACKWARDS){var n;return(n=this.start)!==null&&n!==void 0?n:null}else if(t==Jr.EventTimeline.FORWARDS){var r;return(r=this.end)!==null&&r!==void 0?r:null}else throw new Error("Invalid direction '"+t+"'")}extend(t,n){const r=this.getTimelineIndex(t);if(!r)return!1;const i=t==Jr.EventTimeline.BACKWARDS?r.retreat(n):r.advance(n);if(i){this.eventCount+=i,GT("TimelineWindow: increased cap by "+i+" (now "+this.eventCount+")");const o=this.eventCount-this.windowLimit;return o>0&&this.unpaginate(o,t!=Jr.EventTimeline.BACKWARDS),!0}return!1}canPaginate(t){const n=this.getTimelineIndex(t);if(!n)return!1;if(t==Jr.EventTimeline.BACKWARDS){if(n.index>n.minIndex())return!0}else if(n.index<n.maxIndex())return!0;const r=n.timeline.getNeighbouringTimeline(t),i=n.timeline.getPaginationToken(t);return Boolean(r)||Boolean(i)}async paginate(t,n,r=!0,i=K5){const o=this.getTimelineIndex(t);if(!o)return!1;if(o.pendingPaginate)return o.pendingPaginate;if(this.extend(t,n))return!0;if(!r||i===0||!o.timeline.getPaginationToken(t))return!1;const c=this.client.paginateEventTimeline(o.timeline,{backwards:t==Jr.EventTimeline.BACKWARDS,limit:n}).finally(function(){o.pendingPaginate=void 0}).then(f=>f?this.paginate(t,n,!0,i-1):this.paginate(t,n,!1,0));return o.pendingPaginate=c,c}unpaginate(t,n){const r=n?this.start:this.end;if(!r)throw new Error(`Attempting to unpaginate startOfTimeline=${n} but don't have this direction`);if(t>this.eventCount||t<0)throw new Error(`Attemting to unpaginate ${t} events, but only have ${this.eventCount} in the timeline`);for(;t>0;){const i=n?r.advance(t):r.retreat(t);if(i<=0)throw new Error("Unable to unpaginate any further, but still have "+this.eventCount+" events");t-=i,this.eventCount-=i,GT("TimelineWindow.unpaginate: dropped "+i+" (now "+this.eventCount+")")}}getEvents(){if(!this.start)return[];const t=[];let n=this.start.timeline;for(;;){var r,i;const o=n.getEvents();let a=0,c=o.length;n===this.start.timeline&&(a=this.start.index+n.getBaseIndex()),n===((r=this.end)===null||r===void 0?void 0:r.timeline)&&(c=this.end.index+n.getBaseIndex());for(let f=a;f<c;f++)t.push(o[f]);if(n===((i=this.end)===null||i===void 0?void 0:i.timeline))break;n=n.getNeighbouringTimeline(Jr.EventTimeline.FORWARDS)}return t}}ha.TimelineWindow=j5;class vm{constructor(t,n){this.timeline=t,this.index=n,(0,$l.default)(this,"pendingPaginate",void 0)}minIndex(){return this.timeline.getBaseIndex()*-1}maxIndex(){return this.timeline.getEvents().length-this.timeline.getBaseIndex()}advance(t){if(!t)return 0;let n;if(t<0){if(n=Math.max(t,this.minIndex()-this.index),n<0)return this.index+=n,n}else if(n=Math.min(t,this.maxIndex()-this.index),n>0)return this.index+=n,n;const r=this.timeline.getNeighbouringTimeline(t<0?Jr.EventTimeline.BACKWARDS:Jr.EventTimeline.FORWARDS);return r?(this.timeline=r,t<0?this.index=this.maxIndex():this.index=this.minIndex(),this.advance(t)):0}retreat(t){return this.advance(t*-1)*-1}}ha.TimelineIndex=vm;var Jo={},q5=Ae;Object.defineProperty(Jo,"__esModule",{value:!0});Jo.InteractiveAuth=Jo.AuthType=void 0;var Bt=q5(Ue),Os=Ge(),V5=lt();const Tl="m.login.email.identity",zT="m.login.msisdn";let bu;Jo.AuthType=bu;(function(e){e.Password="m.login.password",e.Recaptcha="m.login.recaptcha",e.Terms="m.login.terms",e.Email="m.login.email.identity",e.Msisdn="m.login.msisdn",e.Sso="m.login.sso",e.SsoUnstable="org.matrix.login.sso",e.Dummy="m.login.dummy",e.RegistrationToken="m.login.registration_token",e.UnstableRegistrationToken="org.matrix.msc3231.login.registration_token"})(bu||(Jo.AuthType=bu={}));class W5 extends Error{constructor(t,n,r){super(t),this.required_stages=n,this.flows=r,(0,Bt.default)(this,"name","NoAuthFlowFoundError")}}class H5{constructor(t){(0,Bt.default)(this,"matrixClient",void 0),(0,Bt.default)(this,"inputs",void 0),(0,Bt.default)(this,"clientSecret",void 0),(0,Bt.default)(this,"requestCallback",void 0),(0,Bt.default)(this,"busyChangedCallback",void 0),(0,Bt.default)(this,"stateUpdatedCallback",void 0),(0,Bt.default)(this,"requestEmailTokenCallback",void 0),(0,Bt.default)(this,"data",void 0),(0,Bt.default)(this,"emailSid",void 0),(0,Bt.default)(this,"requestingEmailToken",!1),(0,Bt.default)(this,"attemptAuthDeferred",null),(0,Bt.default)(this,"chosenFlow",null),(0,Bt.default)(this,"currentStage",null),(0,Bt.default)(this,"emailAttempt",1),(0,Bt.default)(this,"submitPromise",null),(0,Bt.default)(this,"requestEmailToken",async()=>{if(this.requestingEmailToken)Os.logger.warn("Could not request email token: Already requesting");else{Os.logger.trace("Requesting email token. Attempt: "+this.emailAttempt),this.requestingEmailToken=!0;try{const n=await this.requestEmailTokenCallback(this.inputs.emailAddress,this.clientSecret,this.emailAttempt++,this.data.session);this.emailSid=n.sid,Os.logger.trace("Email token request succeeded")}finally{this.requestingEmailToken=!1}}}),this.matrixClient=t.matrixClient,this.data=t.authData||{},this.requestCallback=t.doRequest,this.busyChangedCallback=t.busyChanged,this.stateUpdatedCallback=t.stateUpdated||t.startAuthStage,this.requestEmailTokenCallback=t.requestEmailToken,this.inputs=t.inputs||{},t.sessionId&&(this.data.session=t.sessionId),this.clientSecret=t.clientSecret||this.matrixClient.generateClientSecret(),this.emailSid=t.emailSid}attemptAuth(){var t;this.attemptAuthDeferred=(0,V5.defer)();const n=this.attemptAuthDeferred.promise;if((t=this.data)!==null&&t!==void 0&&t.flows)this.startNextAuthStage();else{var r;(r=this.busyChangedCallback)===null||r===void 0||r.call(this,!0);const i=this.data.session?{session:this.data.session}:null;this.doRequest(i).finally(()=>{var o;(o=this.busyChangedCallback)===null||o===void 0||o.call(this,!1)})}return n}async poll(){if(!this.data.session||!this.attemptAuthDeferred||this.submitPromise)return;let t={};if(this.currentStage==Tl&&this.emailSid){const n={sid:this.emailSid,client_secret:this.clientSecret};if(await this.matrixClient.doesServerRequireIdServerParam()){const r=new URL(this.matrixClient.getIdentityServerUrl());n.id_server=r.host}t={type:Tl,threepid_creds:n,threepidCreds:n}}this.submitAuthDict(t,!0)}getSessionId(){var t;return(t=this.data)===null||t===void 0?void 0:t.session}getClientSecret(){return this.clientSecret}getStageParams(t){var n;return(n=this.data.params)===null||n===void 0?void 0:n[t]}getChosenFlow(){return this.chosenFlow}async submitAuthDict(t,n=!1){if(!this.attemptAuthDeferred)throw new Error("submitAuthDict() called before attemptAuth()");if(!n){var r;(r=this.busyChangedCallback)===null||r===void 0||r.call(this,!0)}for(;this.submitPromise;)try{await this.submitPromise}catch{}let i;this.data.session?(i={session:this.data.session},Object.assign(i,t)):i=t;try{this.submitPromise=this.doRequest(i,n),await this.submitPromise}finally{if(this.submitPromise=null,!n){var o;(o=this.busyChangedCallback)===null||o===void 0||o.call(this,!1)}}}getEmailSid(){return this.emailSid}setEmailSid(t){this.emailSid=t}async doRequest(t,n=!1){try{const c=await this.requestCallback(t,n);this.attemptAuthDeferred.resolve(c),this.attemptAuthDeferred=null}catch(c){var r,i,o;const f=(r=(i=c.data)===null||i===void 0?void 0:i.flows)!==null&&r!==void 0?r:null,v=this.data.flows||Boolean(f);if(c.httpStatus!==401||!c.data||!v)if(n)Os.logger.log("Background poll request failed doing UI auth: ignoring",c);else{var a;(a=this.attemptAuthDeferred)===null||a===void 0||a.reject(c)}c.data||(c.data={}),!c.data.flows&&!c.data.completed&&!c.data.session&&(c.data.flows=this.data.flows,c.data.completed=this.data.completed,c.data.session=this.data.session),this.data=c.data;try{this.startNextAuthStage()}catch(s){this.attemptAuthDeferred.reject(s),this.attemptAuthDeferred=null;return}if(!this.emailSid&&(o=this.chosenFlow)!==null&&o!==void 0&&o.stages.includes(bu.Email))try{await this.requestEmailToken()}catch(s){this.attemptAuthDeferred.reject(s),this.attemptAuthDeferred=null}}}startNextAuthStage(){var t,n;const r=this.chooseStage();if(!r)throw new Error("No incomplete flows from the server");if(this.currentStage=r,r===bu.Dummy){this.submitAuthDict({type:"m.login.dummy"});return}if((t=this.data)!==null&&t!==void 0&&t.errcode||(n=this.data)!==null&&n!==void 0&&n.error){var i,o;this.stateUpdatedCallback(r,{errcode:((i=this.data)===null||i===void 0?void 0:i.errcode)||"",error:((o=this.data)===null||o===void 0?void 0:o.error)||""});return}this.stateUpdatedCallback(r,r===Tl?{emailSid:this.emailSid}:{})}chooseStage(){this.chosenFlow===null&&(this.chosenFlow=this.chooseFlow()),Os.logger.log("Active flow => %s",JSON.stringify(this.chosenFlow));const t=this.firstUncompletedStage(this.chosenFlow);return Os.logger.log("Next stage: %s",t),t}chooseFlow(){const t=this.data.flows||[],n=Boolean(this.inputs.emailAddress)||Boolean(this.emailSid),r=Boolean(this.inputs.phoneCountry)&&Boolean(this.inputs.phoneNumber);for(const o of t){let a=!1,c=!1;for(const f of o.stages)f===Tl?a=!0:f==zT&&(c=!0);if(a==n&&c==r)return o}const i=[];throw n&&i.push(Tl),r&&i.push(zT),new W5("No appropriate authentication flow found",i,t)}firstUncompletedStage(t){const n=this.data.completed||[];return t.stages.find(r=>!n.includes(r))}}Jo.InteractiveAuth=H5;var Jf={},Rl={},YT;function G5(){if(YT)return Rl;YT=1;var e=Ae;Object.defineProperty(Rl,"__esModule",{value:!0}),Rl.LocalIndexedDBStoreBackend=void 0;var t=e(Ue),n=oo,r=c(lt()),i=c(ik()),o=Ge();function a(_){if(typeof WeakMap!="function")return null;var u=new WeakMap,l=new WeakMap;return(a=function(d){return d?l:u})(_)}function c(_,u){if(!u&&_&&_.__esModule)return _;if(_===null||typeof _!="object"&&typeof _!="function")return{default:_};var l=a(u);if(l&&l.has(_))return l.get(_);var d={},h=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var w in _)if(w!=="default"&&Object.prototype.hasOwnProperty.call(_,w)){var E=h?Object.getOwnPropertyDescriptor(_,w):null;E&&(E.get||E.set)?Object.defineProperty(d,w,E):d[w]=_[w]}return d.default=_,l&&l.set(_,d),d}const f=[_=>{_.createObjectStore("users",{keyPath:["userId"]}),_.createObjectStore("accountData",{keyPath:["type"]}),_.createObjectStore("sync",{keyPath:["clobber"]})},_=>{_.createObjectStore("oob_membership_events",{keyPath:["room_id","state_key"]}).createIndex("room","room_id")},_=>{_.createObjectStore("client_options",{keyPath:["clobber"]})},_=>{_.createObjectStore("to_device_queue",{autoIncrement:!0})}],v=f.length;function s(_,u,l){const d=_.openCursor(u);return new Promise((h,w)=>{const E=[];d.onerror=()=>{w(new Error("Query failed: "+d.error))},d.onsuccess=()=>{const I=d.result;if(!I){h(E);return}E.push(l(I)),I.continue()}})}function g(_){return new Promise((u,l)=>{_.oncomplete=function(d){u(d)},_.onerror=function(){l(_.error)}})}function y(_){return new Promise((u,l)=>{_.onsuccess=function(d){u(d)},_.onerror=function(){l(_.error)}})}function S(_){return new Promise((u,l)=>{_.onsuccess=()=>u(_),_.onerror=d=>l(d)})}function m(_){return y(_).then(u=>_.result)}class p{static exists(u,l){return l="matrix-js-sdk:"+(l||"default"),i.exists(u,l)}constructor(u,l="default"){this.indexedDB=u,(0,t.default)(this,"dbName",void 0),(0,t.default)(this,"syncAccumulator",void 0),(0,t.default)(this,"db",void 0),(0,t.default)(this,"disconnected",!0),(0,t.default)(this,"_isNewlyCreated",!1),(0,t.default)(this,"isPersisting",!1),(0,t.default)(this,"pendingUserPresenceData",[]),this.dbName="matrix-js-sdk:"+l,this.syncAccumulator=new n.SyncAccumulator}connect(){if(!this.disconnected)return o.logger.log("LocalIndexedDBStoreBackend.connect: already connected or connecting"),Promise.resolve();this.disconnected=!1,o.logger.log("LocalIndexedDBStoreBackend.connect: connecting...");const u=this.indexedDB.open(this.dbName,v);return u.onupgradeneeded=l=>{const d=u.result,h=l.oldVersion;o.logger.log(`LocalIndexedDBStoreBackend.connect: upgrading from ${h}`),h<1&&(this._isNewlyCreated=!0),f.forEach((w,E)=>{h<=E&&w(d)})},u.onblocked=()=>{o.logger.log("can't yet open LocalIndexedDBStoreBackend because it is open elsewhere")},o.logger.log("LocalIndexedDBStoreBackend.connect: awaiting connection..."),y(u).then(async()=>{o.logger.log("LocalIndexedDBStoreBackend.connect: connected"),this.db=u.result,this.db.onversionchange=()=>{var l;(l=this.db)===null||l===void 0||l.close()},await this.init()})}isNewlyCreated(){return Promise.resolve(this._isNewlyCreated)}init(){return Promise.all([this.loadAccountData(),this.loadSyncData()]).then(([u,l])=>{o.logger.log("LocalIndexedDBStoreBackend: loaded initial data"),this.syncAccumulator.accumulate({next_batch:l.nextBatch,rooms:l.roomsData,account_data:{events:u}},!0)})}getOutOfBandMembers(u){return new Promise((l,d)=>{const E=this.db.transaction(["oob_membership_events"],"readonly").objectStore("oob_membership_events").index("room"),I=IDBKeyRange.only(u),k=E.openCursor(I),M=[];let L=!1;k.onsuccess=()=>{const B=k.result;if(!B)return!M.length&&!L?l(null):l(M);const N=B.value;N.oob_written?L=!0:M.push(N),B.continue()},k.onerror=B=>{d(B)}}).then(l=>(o.logger.log(`LL: got ${l==null?void 0:l.length} membershipEvents from storage for room ${u} ...`),l))}async setOutOfBandMembers(u,l){o.logger.log(`LL: backend about to store ${l.length} members for ${u}`);const d=this.db.transaction(["oob_membership_events"],"readwrite"),h=d.objectStore("oob_membership_events");l.forEach(E=>{h.put(E)});const w={room_id:u,oob_written:!0,state_key:0};h.put(w),await g(d),o.logger.log(`LL: backend done storing for ${u}!`)}async clearOutOfBandMembers(u){const h=this.db.transaction(["oob_membership_events"],"readonly").objectStore("oob_membership_events").index("room"),w=IDBKeyRange.only(u),E=m(h.openKeyCursor(w,"next")).then(G=>(G==null?void 0:G.primaryKey)[1]),I=m(h.openKeyCursor(w,"prev")).then(G=>(G==null?void 0:G.primaryKey)[1]),[k,M]=await Promise.all([E,I]),B=this.db.transaction(["oob_membership_events"],"readwrite").objectStore("oob_membership_events"),N=IDBKeyRange.bound([u,k],[u,M]);o.logger.log(`LL: Deleting all users + marker in storage for room ${u}, with key range:`,[u,k],[u,M]),await S(B.delete(N))}clearDatabase(){return new Promise(u=>{o.logger.log(`Removing indexeddb instance: ${this.dbName}`);const l=this.indexedDB.deleteDatabase(this.dbName);l.onblocked=()=>{o.logger.log(`can't yet delete indexeddb ${this.dbName} because it is open elsewhere`)},l.onerror=()=>{o.logger.warn(`unable to delete js-sdk store indexeddb: ${l.error}`),u()},l.onsuccess=()=>{o.logger.log(`Removed indexeddb instance: ${this.dbName}`),u()}})}getSavedSync(u=!0){const l=this.syncAccumulator.getJSON();return l.nextBatch?u?Promise.resolve(r.deepCopy(l)):Promise.resolve(l):Promise.resolve(null)}getNextBatchToken(){return Promise.resolve(this.syncAccumulator.getNextBatchToken())}setSyncData(u){return Promise.resolve().then(()=>{this.syncAccumulator.accumulate(u)})}async syncToDatabase(u){if(this.isPersisting){o.logger.warn("Skipping syncToDatabase() as persist already in flight"),this.pendingUserPresenceData.push(...u);return}else u.unshift(...this.pendingUserPresenceData),this.isPersisting=!0;try{const l=this.syncAccumulator.getJSON(!0);await Promise.all([this.persistUserPresenceEvents(u),this.persistAccountData(l.accountData),this.persistSyncData(l.nextBatch,l.roomsData)])}finally{this.isPersisting=!1}}persistSyncData(u,l){return o.logger.log("Persisting sync data up to",u),r.promiseTry(()=>{const d=this.db.transaction(["sync"],"readwrite");return d.objectStore("sync").put({clobber:"-",nextBatch:u,roomsData:l}),g(d).then(()=>{o.logger.log("Persisted sync data up to",u)})})}persistAccountData(u){return r.promiseTry(()=>{const l=this.db.transaction(["accountData"],"readwrite"),d=l.objectStore("accountData");for(const h of u)d.put(h);return g(l).then()})}persistUserPresenceEvents(u){return r.promiseTry(()=>{const l=this.db.transaction(["users"],"readwrite"),d=l.objectStore("users");for(const h of u)d.put({userId:h[0],event:h[1]});return g(l).then()})}getUserPresenceEvents(){return r.promiseTry(()=>{const l=this.db.transaction(["users"],"readonly").objectStore("users");return s(l,void 0,d=>[d.value.userId,d.value.event])})}loadAccountData(){return o.logger.log("LocalIndexedDBStoreBackend: loading account data..."),r.promiseTry(()=>{const l=this.db.transaction(["accountData"],"readonly").objectStore("accountData");return s(l,void 0,d=>d.value).then(d=>(o.logger.log("LocalIndexedDBStoreBackend: loaded account data"),d))})}loadSyncData(){return o.logger.log("LocalIndexedDBStoreBackend: loading sync data..."),r.promiseTry(()=>{const l=this.db.transaction(["sync"],"readonly").objectStore("sync");return s(l,void 0,d=>d.value).then(d=>(o.logger.log("LocalIndexedDBStoreBackend: loaded sync data"),d.length>1&&o.logger.warn("loadSyncData: More than 1 sync row found."),d.length>0?d[0]:{}))})}getClientOptions(){return Promise.resolve().then(()=>{const l=this.db.transaction(["client_options"],"readonly").objectStore("client_options");return s(l,void 0,d=>{var h;return(h=d.value)===null||h===void 0?void 0:h.options}).then(d=>d[0])})}async storeClientOptions(u){const l=this.db.transaction(["client_options"],"readwrite");l.objectStore("client_options").put({clobber:"-",options:u}),await g(l)}async saveToDeviceBatches(u){const l=this.db.transaction(["to_device_queue"],"readwrite"),d=l.objectStore("to_device_queue");for(const h of u)d.add(h);await g(l)}async getOldestToDeviceBatch(){const l=this.db.transaction(["to_device_queue"],"readonly").objectStore("to_device_queue"),d=await m(l.openCursor());if(!d)return null;const h=d.value;return{id:d.key,txnId:h.txnId,eventType:h.eventType,batch:h.batch}}async removeToDeviceBatch(u){const l=this.db.transaction(["to_device_queue"],"readwrite");l.objectStore("to_device_queue").delete(u),await g(l)}}return Rl.LocalIndexedDBStoreBackend=p,Rl}var Il={},QT;function z5(){if(QT)return Il;QT=1;var e=Ae;Object.defineProperty(Il,"__esModule",{value:!0}),Il.RemoteIndexedDBStoreBackend=void 0;var t=e(Ue),n=Ge(),r=lt();class i{constructor(a,c){this.workerFactory=a,this.dbName=c,(0,t.default)(this,"worker",void 0),(0,t.default)(this,"nextSeq",0),(0,t.default)(this,"inFlight",{}),(0,t.default)(this,"startPromise",void 0),(0,t.default)(this,"onWorkerMessage",f=>{const v=f.data;if(v.command=="cmd_success"||v.command=="cmd_fail"){if(v.seq===void 0){n.logger.error("Got reply from worker with no seq");return}const s=this.inFlight[v.seq];if(s===void 0){n.logger.error("Got reply for unknown seq "+v.seq);return}if(delete this.inFlight[v.seq],v.command=="cmd_success")s.resolve(v.result);else{const g=new Error(v.error.message);g.name=v.error.name,s.reject(g)}}else n.logger.warn("Unrecognised message from worker: ",v)})}connect(){return this.ensureStarted().then(()=>this.doCmd("connect"))}clearDatabase(){return this.ensureStarted().then(()=>this.doCmd("clearDatabase"))}isNewlyCreated(){return this.doCmd("isNewlyCreated")}getSavedSync(){return this.doCmd("getSavedSync")}getNextBatchToken(){return this.doCmd("getNextBatchToken")}setSyncData(a){return this.doCmd("setSyncData",[a])}syncToDatabase(a){return this.doCmd("syncToDatabase",[a])}getOutOfBandMembers(a){return this.doCmd("getOutOfBandMembers",[a])}setOutOfBandMembers(a,c){return this.doCmd("setOutOfBandMembers",[a,c])}clearOutOfBandMembers(a){return this.doCmd("clearOutOfBandMembers",[a])}getClientOptions(){return this.doCmd("getClientOptions")}storeClientOptions(a){return this.doCmd("storeClientOptions",[a])}getUserPresenceEvents(){return this.doCmd("getUserPresenceEvents")}async saveToDeviceBatches(a){return this.doCmd("saveToDeviceBatches",[a])}async getOldestToDeviceBatch(){return this.doCmd("getOldestToDeviceBatch")}async removeToDeviceBatch(a){return this.doCmd("removeToDeviceBatch",[a])}ensureStarted(){return this.startPromise||(this.worker=this.workerFactory(),this.worker.onmessage=this.onWorkerMessage,this.startPromise=this.doCmd("setupWorker",[this.dbName]).then(()=>{n.logger.log("IndexedDB worker is ready")})),this.startPromise}doCmd(a,c){return Promise.resolve().then(()=>{var f;const v=this.nextSeq++,s=(0,r.defer)();return this.inFlight[v]=s,(f=this.worker)===null||f===void 0||f.postMessage({command:a,seq:v,args:c}),s.promise})}}return Il.RemoteIndexedDBStoreBackend=i,Il}var Y5=Ae;Object.defineProperty(Jf,"__esModule",{value:!0});Jf.IndexedDBStore=void 0;var Ut=Y5(Ue),Q5=Bu,JT=G5(),J5=z5(),X5=Xn,Z5=nn(),ur=Ge(),eH=Pt();const tH=1e3*60*5;class nH extends Q5.MemoryStore{static exists(t,n){return JT.LocalIndexedDBStoreBackend.exists(t,n)}constructor(t){if(super(t),(0,Ut.default)(this,"backend",void 0),(0,Ut.default)(this,"startedUp",!1),(0,Ut.default)(this,"syncTs",0),(0,Ut.default)(this,"userModifiedMap",{}),(0,Ut.default)(this,"emitter",new eH.TypedEventEmitter),(0,Ut.default)(this,"on",this.emitter.on.bind(this.emitter)),(0,Ut.default)(this,"getSavedSync",this.degradable(()=>this.backend.getSavedSync(),"getSavedSync")),(0,Ut.default)(this,"isNewlyCreated",this.degradable(()=>this.backend.isNewlyCreated(),"isNewlyCreated")),(0,Ut.default)(this,"getSavedSyncToken",this.degradable(()=>this.backend.getNextBatchToken(),"getSavedSyncToken")),(0,Ut.default)(this,"deleteAllData",this.degradable(()=>(super.deleteAllData(),this.backend.clearDatabase().then(()=>{ur.logger.log("Deleted indexeddb data.")},n=>{throw ur.logger.error(`Failed to delete indexeddb data: ${n}`),n})))),(0,Ut.default)(this,"reallySave",this.degradable(()=>{this.syncTs=Date.now();const n=[];for(const r of this.getUsers())this.userModifiedMap[r.userId]!==r.getLastModifiedTime()&&r.events.presence&&(n.push([r.userId,r.events.presence.event]),this.userModifiedMap[r.userId]=r.getLastModifiedTime());return this.backend.syncToDatabase(n)})),(0,Ut.default)(this,"setSyncData",this.degradable(n=>this.backend.setSyncData(n),"setSyncData")),(0,Ut.default)(this,"getOutOfBandMembers",this.degradable(n=>this.backend.getOutOfBandMembers(n),"getOutOfBandMembers")),(0,Ut.default)(this,"setOutOfBandMembers",this.degradable((n,r)=>(super.setOutOfBandMembers(n,r),this.backend.setOutOfBandMembers(n,r)),"setOutOfBandMembers")),(0,Ut.default)(this,"clearOutOfBandMembers",this.degradable(n=>(super.clearOutOfBandMembers(n),this.backend.clearOutOfBandMembers(n)),"clearOutOfBandMembers")),(0,Ut.default)(this,"getClientOptions",this.degradable(()=>this.backend.getClientOptions(),"getClientOptions")),(0,Ut.default)(this,"storeClientOptions",this.degradable(n=>(super.storeClientOptions(n),this.backend.storeClientOptions(n)),"storeClientOptions")),!t.indexedDB)throw new Error("Missing required option: indexedDB");t.workerFactory?this.backend=new J5.RemoteIndexedDBStoreBackend(t.workerFactory,t.dbName):this.backend=new JT.LocalIndexedDBStoreBackend(t.indexedDB,t.dbName)}startup(){return this.startedUp?(ur.logger.log("IndexedDBStore.startup: already started"),Promise.resolve()):(ur.logger.log("IndexedDBStore.startup: connecting to backend"),this.backend.connect().then(()=>(ur.logger.log("IndexedDBStore.startup: loading presence events"),this.backend.getUserPresenceEvents())).then(t=>{ur.logger.log("IndexedDBStore.startup: processing presence events"),t.forEach(([n,r])=>{const i=new X5.User(n);r&&i.setPresenceEvent(new Z5.MatrixEvent(r)),this.userModifiedMap[i.userId]=i.getLastModifiedTime(),this.storeUser(i)})}))}wantsSave(){return Date.now()-this.syncTs>tH}save(t=!1){return t||this.wantsSave()?this.reallySave():Promise.resolve()}degradable(t,n){const r=n?super[n]:null;return async(...i)=>{try{return await t.call(this,...i)}catch(o){ur.logger.error("IndexedDBStore failure, degrading to MemoryStore",o),this.emitter.emit("degraded",o);try{ur.logger.log("IndexedDBStore trying to delete degraded data"),await this.backend.clearDatabase(),ur.logger.log("IndexedDBStore delete after degrading succeeded")}catch(a){ur.logger.warn("IndexedDBStore delete after degrading failed",a)}if(r)return r.call(this,...i)}}}async getPendingEvents(t){if(!this.localStorage)return super.getPendingEvents(t);const n=this.localStorage.getItem(lg(t));if(n)try{return JSON.parse(n)}catch(r){ur.logger.error("Could not parse persisted pending events",r)}return[]}async setPendingEvents(t,n){if(!this.localStorage)return super.setPendingEvents(t,n);n.length>0?this.localStorage.setItem(lg(t),JSON.stringify(n)):this.localStorage.removeItem(lg(t))}saveToDeviceBatches(t){return this.backend.saveToDeviceBatches(t)}getOldestToDeviceBatch(){return this.backend.getOldestToDeviceBatch()}removeToDeviceBatch(t){return this.backend.removeToDeviceBatch(t)}}Jf.IndexedDBStore=nH;function lg(e){return`mx_pending_events_${e}`}var Rk={};Object.defineProperty(Rk,"__esModule",{value:!0});(function(e){Object.defineProperty(e,"__esModule",{value:!0});var t={setCryptoStoreFactory:!0,createClient:!0,createRoomWidgetClient:!0,ContentHelpers:!0,createNewMatrixCall:!0,GroupCallEvent:!0,GroupCallIntent:!0,GroupCallState:!0,GroupCallType:!0};e.ContentHelpers=void 0,Object.defineProperty(e,"GroupCallEvent",{enumerable:!0,get:function(){return F.GroupCallEvent}}),Object.defineProperty(e,"GroupCallIntent",{enumerable:!0,get:function(){return F.GroupCallIntent}}),Object.defineProperty(e,"GroupCallState",{enumerable:!0,get:function(){return F.GroupCallState}}),Object.defineProperty(e,"GroupCallType",{enumerable:!0,get:function(){return F.GroupCallType}}),e.createClient=C,Object.defineProperty(e,"createNewMatrixCall",{enumerable:!0,get:function(){return W.createNewMatrixCall}}),e.createRoomWidgetClient=A,e.setCryptoStoreFactory=K;var n=_a;Object.keys(n).forEach(function(T){T==="default"||T==="__esModule"||Object.prototype.hasOwnProperty.call(t,T)||T in e&&e[T]===n[T]||Object.defineProperty(e,T,{enumerable:!0,get:function(){return n[T]}})});var r=Bu;Object.keys(r).forEach(function(T){T==="default"||T==="__esModule"||Object.prototype.hasOwnProperty.call(t,T)||T in e&&e[T]===r[T]||Object.defineProperty(e,T,{enumerable:!0,get:function(){return r[T]}})});var i=ec;Object.keys(i).forEach(function(T){T==="default"||T==="__esModule"||Object.prototype.hasOwnProperty.call(t,T)||T in e&&e[T]===i[T]||Object.defineProperty(e,T,{enumerable:!0,get:function(){return i[T]}})});var o=or();Object.keys(o).forEach(function(T){T==="default"||T==="__esModule"||Object.prototype.hasOwnProperty.call(t,T)||T in e&&e[T]===o[T]||Object.defineProperty(e,T,{enumerable:!0,get:function(){return o[T]}})});var a=Yf;Object.keys(a).forEach(function(T){T==="default"||T==="__esModule"||Object.prototype.hasOwnProperty.call(t,T)||T in e&&e[T]===a[T]||Object.defineProperty(e,T,{enumerable:!0,get:function(){return a[T]}})});var c=Rr;Object.keys(c).forEach(function(T){T==="default"||T==="__esModule"||Object.prototype.hasOwnProperty.call(t,T)||T in e&&e[T]===c[T]||Object.defineProperty(e,T,{enumerable:!0,get:function(){return c[T]}})});var f=io;Object.keys(f).forEach(function(T){T==="default"||T==="__esModule"||Object.prototype.hasOwnProperty.call(t,T)||T in e&&e[T]===f[T]||Object.defineProperty(e,T,{enumerable:!0,get:function(){return f[T]}})});var v=oo;Object.keys(v).forEach(function(T){T==="default"||T==="__esModule"||Object.prototype.hasOwnProperty.call(t,T)||T in e&&e[T]===v[T]||Object.defineProperty(e,T,{enumerable:!0,get:function(){return v[T]}})});var s=jt;Object.keys(s).forEach(function(T){T==="default"||T==="__esModule"||Object.prototype.hasOwnProperty.call(t,T)||T in e&&e[T]===s[T]||Object.defineProperty(e,T,{enumerable:!0,get:function(){return s[T]}})});var g=bn;Object.keys(g).forEach(function(T){T==="default"||T==="__esModule"||Object.prototype.hasOwnProperty.call(t,T)||T in e&&e[T]===g[T]||Object.defineProperty(e,T,{enumerable:!0,get:function(){return g[T]}})});var y=nn();Object.keys(y).forEach(function(T){T==="default"||T==="__esModule"||Object.prototype.hasOwnProperty.call(t,T)||T in e&&e[T]===y[T]||Object.defineProperty(e,T,{enumerable:!0,get:function(){return y[T]}})});var S=hi();Object.keys(S).forEach(function(T){T==="default"||T==="__esModule"||Object.prototype.hasOwnProperty.call(t,T)||T in e&&e[T]===S[T]||Object.defineProperty(e,T,{enumerable:!0,get:function(){return S[T]}})});var m=Tr();Object.keys(m).forEach(function(T){T==="default"||T==="__esModule"||Object.prototype.hasOwnProperty.call(t,T)||T in e&&e[T]===m[T]||Object.defineProperty(e,T,{enumerable:!0,get:function(){return m[T]}})});var p=Gy();Object.keys(p).forEach(function(T){T==="default"||T==="__esModule"||Object.prototype.hasOwnProperty.call(t,T)||T in e&&e[T]===p[T]||Object.defineProperty(e,T,{enumerable:!0,get:function(){return p[T]}})});var _=Zn;Object.keys(_).forEach(function(T){T==="default"||T==="__esModule"||Object.prototype.hasOwnProperty.call(t,T)||T in e&&e[T]===_[T]||Object.defineProperty(e,T,{enumerable:!0,get:function(){return _[T]}})});var u=po();Object.keys(u).forEach(function(T){T==="default"||T==="__esModule"||Object.prototype.hasOwnProperty.call(t,T)||T in e&&e[T]===u[T]||Object.defineProperty(e,T,{enumerable:!0,get:function(){return u[T]}})});var l=Xn;Object.keys(l).forEach(function(T){T==="default"||T==="__esModule"||Object.prototype.hasOwnProperty.call(t,T)||T in e&&e[T]===l[T]||Object.defineProperty(e,T,{enumerable:!0,get:function(){return l[T]}})});var d=qf();Object.keys(d).forEach(function(T){T==="default"||T==="__esModule"||Object.prototype.hasOwnProperty.call(t,T)||T in e&&e[T]===d[T]||Object.defineProperty(e,T,{enumerable:!0,get:function(){return d[T]}})});var h=ha;Object.keys(h).forEach(function(T){T==="default"||T==="__esModule"||Object.prototype.hasOwnProperty.call(t,T)||T in e&&e[T]===h[T]||Object.defineProperty(e,T,{enumerable:!0,get:function(){return h[T]}})});var w=Jo;Object.keys(w).forEach(function(T){T==="default"||T==="__esModule"||Object.prototype.hasOwnProperty.call(t,T)||T in e&&e[T]===w[T]||Object.defineProperty(e,T,{enumerable:!0,get:function(){return w[T]}})});var E=Oa;Object.keys(E).forEach(function(T){T==="default"||T==="__esModule"||Object.prototype.hasOwnProperty.call(t,T)||T in e&&e[T]===E[T]||Object.defineProperty(e,T,{enumerable:!0,get:function(){return E[T]}})});var I=Jf;Object.keys(I).forEach(function(T){T==="default"||T==="__esModule"||Object.prototype.hasOwnProperty.call(t,T)||T in e&&e[T]===I[T]||Object.defineProperty(e,T,{enumerable:!0,get:function(){return I[T]}})});var k=ir;Object.keys(k).forEach(function(T){T==="default"||T==="__esModule"||Object.prototype.hasOwnProperty.call(t,T)||T in e&&e[T]===k[T]||Object.defineProperty(e,T,{enumerable:!0,get:function(){return k[T]}})});var M=Ea;Object.keys(M).forEach(function(T){T==="default"||T==="__esModule"||Object.prototype.hasOwnProperty.call(t,T)||T in e&&e[T]===M[T]||Object.defineProperty(e,T,{enumerable:!0,get:function(){return M[T]}})});var L=xe;Object.keys(L).forEach(function(T){T==="default"||T==="__esModule"||Object.prototype.hasOwnProperty.call(t,T)||T in e&&e[T]===L[T]||Object.defineProperty(e,T,{enumerable:!0,get:function(){return L[T]}})});var B=ht;Object.keys(B).forEach(function(T){T==="default"||T==="__esModule"||Object.prototype.hasOwnProperty.call(t,T)||T in e&&e[T]===B[T]||Object.defineProperty(e,T,{enumerable:!0,get:function(){return B[T]}})});var N=yt;Object.keys(N).forEach(function(T){T==="default"||T==="__esModule"||Object.prototype.hasOwnProperty.call(t,T)||T in e&&e[T]===N[T]||Object.defineProperty(e,T,{enumerable:!0,get:function(){return N[T]}})});var G=Rk;Object.keys(G).forEach(function(T){T==="default"||T==="__esModule"||Object.prototype.hasOwnProperty.call(t,T)||T in e&&e[T]===G[T]||Object.defineProperty(e,T,{enumerable:!0,get:function(){return G[T]}})});var D=Pa;Object.keys(D).forEach(function(T){T==="default"||T==="__esModule"||Object.prototype.hasOwnProperty.call(t,T)||T in e&&e[T]===D[T]||Object.defineProperty(e,T,{enumerable:!0,get:function(){return D[T]}})});var x=Gu;Object.keys(x).forEach(function(T){T==="default"||T==="__esModule"||Object.prototype.hasOwnProperty.call(t,T)||T in e&&e[T]===x[T]||Object.defineProperty(e,T,{enumerable:!0,get:function(){return x[T]}})});var z=R(ut);e.ContentHelpers=z;var W=Ju(),F=Ca();function H(T){if(typeof WeakMap!="function")return null;var X=new WeakMap,ne=new WeakMap;return(H=function(ae){return ae?ne:X})(T)}function R(T,X){if(!X&&T&&T.__esModule)return T;if(T===null||typeof T!="object"&&typeof T!="function")return{default:T};var ne=H(X);if(ne&&ne.has(T))return ne.get(T);var ae={},pe=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var V in T)if(V!=="default"&&Object.prototype.hasOwnProperty.call(T,V)){var se=pe?Object.getOwnPropertyDescriptor(T,V):null;se&&(se.get||se.set)?Object.defineProperty(ae,V,se):ae[V]=T[V]}return ae.default=T,ne&&ne.set(T,ae),ae}let P=()=>new n.MemoryCryptoStore;function K(T){P=T}function U(T){var X,ne,ae;return T.store=(X=T.store)!==null&&X!==void 0?X:new r.MemoryStore({localStorage:$e.localStorage}),T.scheduler=(ne=T.scheduler)!==null&&ne!==void 0?ne:new i.MatrixScheduler,T.cryptoStore=(ae=T.cryptoStore)!==null&&ae!==void 0?ae:P(),T}function C(T){return new o.MatrixClient(U(T))}function A(T,X,ne,ae){return new a.RoomWidgetClient(T,X,ne,U(ae))}})(vP);(function(e){Object.defineProperty(e,"__esModule",{value:!0});var t={};e.default=void 0;var n=i(vP);Object.keys(n).forEach(function(c){c==="default"||c==="__esModule"||Object.prototype.hasOwnProperty.call(t,c)||c in e&&e[c]===n[c]||Object.defineProperty(e,c,{enumerable:!0,get:function(){return n[c]}})});function r(c){if(typeof WeakMap!="function")return null;var f=new WeakMap,v=new WeakMap;return(r=function(s){return s?v:f})(c)}function i(c,f){if(!f&&c&&c.__esModule)return c;if(c===null||typeof c!="object"&&typeof c!="function")return{default:c};var v=r(f);if(v&&v.has(c))return v.get(c);var s={},g=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var y in c)if(y!=="default"&&Object.prototype.hasOwnProperty.call(c,y)){var S=g?Object.getOwnPropertyDescriptor(c,y):null;S&&(S.get||S.set)?Object.defineProperty(s,y,S):s[y]=c[y]}return s.default=c,v&&v.set(c,s),s}if($e.__js_sdk_entrypoint)throw new Error("Multiple matrix-js-sdk entrypoints detected!");$e.__js_sdk_entrypoint=!0;let o;try{o=$e.indexedDB}catch{}o&&n.setCryptoStoreFactory(()=>new n.IndexedDBCryptoStore(o,"matrix-js-sdk:crypto"));var a=n;e.default=a,$e.matrixcs=n})($K);var NG=pk();const xG="/pr-301/assets/olm-82e831ad.wasm",$G="/pr-301/assets/olm_legacy-086c8bde.js";var mm={},rH={get exports(){return mm},set exports(e){mm=e}};(function(e,t){// @license magnet:?xt=urn:btih:8e4f440f4c65981c5bf93c76d35135ba5064d8b7&dn=apache-2.0.txt Apache-2.0
     91 var n=function(){var r={},i,o,a=(()=>{var f=typeof document<"u"&&document.currentScript?document.currentScript.src:void 0;return typeof __filename<"u"&&(f=f||__filename),function(v){v=v||{};var s;s||(s=typeof v<"u"?v:{});var g,y;s.ready=new Promise(function(q,J){g=q,y=J});var S;if(typeof window<"u")S=function(q){window.crypto.getRandomValues(q)};else if(e.exports){var m=zs;S=function(q){var J=m.randomBytes(q.length);q.set(J)},process=$e.process}else throw Error("Cannot find global to attach library to");if(typeof OLM_OPTIONS<"u")for(var p in OLM_OPTIONS)OLM_OPTIONS.hasOwnProperty(p)&&(s[p]=OLM_OPTIONS[p]);s.onRuntimeInitialized=function(){Fe=s._olm_error(),r.PRIVATE_KEY_LENGTH=s._olm_pk_private_key_length(),i&&i()},s.onAbort=function(q){o&&o(q)};var _=Object.assign({},s),u=typeof window=="object",l=typeof importScripts=="function",d=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",h="",w,E,I,k,M,L;d?(h=l?zs.dirname(h)+"/":__dirname+"/",L=()=>{M||(k=zs,M=zs)},w=function(q,J){return L(),q=M.normalize(q),k.readFileSync(q,J?void 0:"utf8")},I=q=>(q=w(q,!0),q.buffer||(q=new Uint8Array(q)),q),E=(q,J,oe)=>{L(),q=M.normalize(q),k.readFile(q,function(me,Ie){me?oe(me):J(Ie.buffer)})},1<process.argv.length&&process.argv[1].replace(/\\/g,"/"),process.argv.slice(2),process.on("uncaughtException",function(q){throw q}),process.on("unhandledRejection",function(q){throw q}),s.inspect=function(){return"[Emscripten Module object]"}):(u||l)&&(l?h=self.location.href:typeof document<"u"&&document.currentScript&&(h=document.currentScript.src),f&&(h=f),h.indexOf("blob:")!==0?h=h.substr(0,h.replace(/[?#].*/,"").lastIndexOf("/")+1):h="",w=q=>{var J=new XMLHttpRequest;return J.open("GET",q,!1),J.send(null),J.responseText},l&&(I=q=>{var J=new XMLHttpRequest;return J.open("GET",q,!1),J.responseType="arraybuffer",J.send(null),new Uint8Array(J.response)}),E=(q,J,oe)=>{var me=new XMLHttpRequest;me.open("GET",q,!0),me.responseType="arraybuffer",me.onload=()=>{me.status==200||me.status==0&&me.response?J(me.response):oe()},me.onerror=oe,me.send(null)}),s.print||console.log.bind(console);var B=s.printErr||console.warn.bind(console);Object.assign(s,_),_=null;var N;s.wasmBinary&&(N=s.wasmBinary),s.noExitRuntime,typeof WebAssembly!="object"&&j("no native wasm support detected");var G,D=!1,x=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0;function z(q,J){if(q){var oe=P,me=q+J;for(J=q;oe[J]&&!(J>=me);)++J;if(16<J-q&&oe.buffer&&x)q=x.decode(oe.subarray(q,J));else{for(me="";q<J;){var Ie=oe[q++];if(Ie&128){var He=oe[q++]&63;if((Ie&224)==192)me+=String.fromCharCode((Ie&31)<<6|He);else{var rt=oe[q++]&63;Ie=(Ie&240)==224?(Ie&15)<<12|He<<6|rt:(Ie&7)<<18|He<<12|rt<<6|oe[q++]&63,65536>Ie?me+=String.fromCharCode(Ie):(Ie-=65536,me+=String.fromCharCode(55296|Ie>>10,56320|Ie&1023))}}else me+=String.fromCharCode(Ie)}q=me}}else q="";return q}function W(q,J,oe,me){if(!(0<me))return 0;var Ie=oe;me=oe+me-1;for(var He=0;He<q.length;++He){var rt=q.charCodeAt(He);if(55296<=rt&&57343>=rt){var on=q.charCodeAt(++He);rt=65536+((rt&1023)<<10)|on&1023}if(127>=rt){if(oe>=me)break;J[oe++]=rt}else{if(2047>=rt){if(oe+1>=me)break;J[oe++]=192|rt>>6}else{if(65535>=rt){if(oe+2>=me)break;J[oe++]=224|rt>>12}else{if(oe+3>=me)break;J[oe++]=240|rt>>18,J[oe++]=128|rt>>12&63}J[oe++]=128|rt>>6&63}J[oe++]=128|rt&63}}return J[oe]=0,oe-Ie}function F(q){for(var J=0,oe=0;oe<q.length;++oe){var me=q.charCodeAt(oe);127>=me?J++:2047>=me?J+=2:55296<=me&&57343>=me?(J+=4,++oe):J+=3}return J}var H,R,P,K,U,C,A,T;function X(){var q=G.buffer;H=q,s.HEAP8=R=new Int8Array(q),s.HEAP16=K=new Int16Array(q),s.HEAP32=U=new Int32Array(q),s.HEAPU8=P=new Uint8Array(q),s.HEAPU16=new Uint16Array(q),s.HEAPU32=C=new Uint32Array(q),s.HEAPF32=A=new Float32Array(q),s.HEAPF64=T=new Float64Array(q)}var ne=[],ae=[],pe=[];function V(){var q=s.preRun.shift();ne.unshift(q)}var se=0,Q=null;function j(q){throw s.onAbort&&s.onAbort(q),q="Aborted("+q+")",B(q),D=!0,q=new WebAssembly.RuntimeError(q+". Build with -sASSERTIONS for more info."),y(q),q}function Z(){return te.startsWith("data:application/octet-stream;base64,")}var te;if(te="olm.wasm",!Z()){var re=te;te=s.locateFile?s.locateFile(re,h):h+re}function de(){var q=te;try{if(q==te&&N)return new Uint8Array(N);if(I)return I(q);throw"both async and sync fetching of the wasm failed"}catch(J){j(J)}}function ge(){if(!N&&(u||l)){if(typeof fetch=="function"&&!te.startsWith("file://"))return fetch(te,{credentials:"same-origin"}).then(function(q){if(!q.ok)throw"failed to load wasm binary file at '"+te+"'";return q.arrayBuffer()}).catch(function(){return de()});if(E)return new Promise(function(q,J){E(te,function(oe){q(new Uint8Array(oe))},J)})}return Promise.resolve().then(function(){return de()})}var fe;function he(q){for(;0<q.length;)q.shift()(s)}function ye(q,J="i8"){switch(J.endsWith("*")&&(J="*"),J){case"i1":return R[q>>0];case"i8":return R[q>>0];case"i16":return K[q>>1];case"i32":return U[q>>2];case"i64":return U[q>>2];case"float":return A[q>>2];case"double":return T[q>>3];case"*":return C[q>>2];default:j("invalid type for getValue: "+J)}return null}function ce(q){var J="i8";switch(J.endsWith("*")&&(J="*"),J){case"i1":R[q>>0]=0;break;case"i8":R[q>>0]=0;break;case"i16":K[q>>1]=0;break;case"i32":U[q>>2]=0;break;case"i64":fe=[0,0],U[q>>2]=fe[0],U[q+4>>2]=fe[1];break;case"float":A[q>>2]=0;break;case"double":T[q>>3]=0;break;case"*":C[q>>2]=0;break;default:j("invalid type for setValue: "+J)}}function le(q,J,oe){for(var me=0;me<q.length;++me)R[J++>>0]=q.charCodeAt(me);oe||(R[J>>0]=0)}function Se(q,J,oe){return oe=Array(0<oe?oe:F(q)+1),q=W(q,oe,0,oe.length),J&&(oe.length=q),oe}var Te={b:function(q,J,oe){P.copyWithin(q,J,J+oe)},a:function(q){var J=P.length;if(q>>>=0,2147483648<q)return!1;for(var oe=1;4>=oe;oe*=2){var me=J*(1+.2/oe);me=Math.min(me,q+100663296);var Ie=Math;me=Math.max(q,me),Ie=Ie.min.call(Ie,2147483648,me+(65536-me%65536)%65536);e:{try{G.grow(Ie-H.byteLength+65535>>>16),X();var He=1;break e}catch{}He=void 0}if(He)return!0}return!1}};(function(){function q(Ie){s.asm=Ie.exports,G=s.asm.c,X(),ae.unshift(s.asm.d),se--,s.monitorRunDependencies&&s.monitorRunDependencies(se),se==0&&Q&&(Ie=Q,Q=null,Ie())}function J(Ie){q(Ie.instance)}function oe(Ie){return ge().then(function(He){return WebAssembly.instantiate(He,me)}).then(function(He){return He}).then(Ie,function(He){B("failed to asynchronously prepare wasm: "+He),j(He)})}var me={a:Te};if(se++,s.monitorRunDependencies&&s.monitorRunDependencies(se),s.instantiateWasm)try{return s.instantiateWasm(me,q)}catch(Ie){return B("Module.instantiateWasm callback failed with error: "+Ie),!1}return function(){return N||typeof WebAssembly.instantiateStreaming!="function"||Z()||te.startsWith("file://")||d||typeof fetch!="function"?oe(J):fetch(te,{credentials:"same-origin"}).then(function(Ie){return WebAssembly.instantiateStreaming(Ie,me).then(J,function(He){return B("wasm streaming compile failed: "+He),B("falling back to ArrayBuffer instantiation"),oe(J)})})}().catch(y),{}})(),s.___wasm_call_ctors=function(){return(s.___wasm_call_ctors=s.asm.d).apply(null,arguments)},s._olm_get_library_version=function(){return(s._olm_get_library_version=s.asm.f).apply(null,arguments)},s._olm_error=function(){return(s._olm_error=s.asm.g).apply(null,arguments)},s._olm_account_last_error=function(){return(s._olm_account_last_error=s.asm.h).apply(null,arguments)},s.__olm_error_to_string=function(){return(s.__olm_error_to_string=s.asm.i).apply(null,arguments)},s._olm_account_last_error_code=function(){return(s._olm_account_last_error_code=s.asm.j).apply(null,arguments)},s._olm_session_last_error=function(){return(s._olm_session_last_error=s.asm.k).apply(null,arguments)},s._olm_session_last_error_code=function(){return(s._olm_session_last_error_code=s.asm.l).apply(null,arguments)},s._olm_utility_last_error=function(){return(s._olm_utility_last_error=s.asm.m).apply(null,arguments)},s._olm_utility_last_error_code=function(){return(s._olm_utility_last_error_code=s.asm.n).apply(null,arguments)},s._olm_account_size=function(){return(s._olm_account_size=s.asm.o).apply(null,arguments)},s._olm_session_size=function(){return(s._olm_session_size=s.asm.p).apply(null,arguments)},s._olm_utility_size=function(){return(s._olm_utility_size=s.asm.q).apply(null,arguments)},s._olm_account=function(){return(s._olm_account=s.asm.r).apply(null,arguments)},s._olm_session=function(){return(s._olm_session=s.asm.s).apply(null,arguments)},s._olm_utility=function(){return(s._olm_utility=s.asm.t).apply(null,arguments)},s._olm_clear_account=function(){return(s._olm_clear_account=s.asm.u).apply(null,arguments)},s._olm_clear_session=function(){return(s._olm_clear_session=s.asm.v).apply(null,arguments)},s._olm_clear_utility=function(){return(s._olm_clear_utility=s.asm.w).apply(null,arguments)},s._olm_pickle_account_length=function(){return(s._olm_pickle_account_length=s.asm.x).apply(null,arguments)},s._olm_pickle_session_length=function(){return(s._olm_pickle_session_length=s.asm.y).apply(null,arguments)},s._olm_pickle_account=function(){return(s._olm_pickle_account=s.asm.z).apply(null,arguments)},s._olm_pickle_session=function(){return(s._olm_pickle_session=s.asm.A).apply(null,arguments)},s._olm_unpickle_account=function(){return(s._olm_unpickle_account=s.asm.B).apply(null,arguments)},s._olm_unpickle_session=function(){return(s._olm_unpickle_session=s.asm.C).apply(null,arguments)},s._olm_create_account_random_length=function(){return(s._olm_create_account_random_length=s.asm.D).apply(null,arguments)},s._olm_create_account=function(){return(s._olm_create_account=s.asm.E).apply(null,arguments)},s._olm_account_identity_keys_length=function(){return(s._olm_account_identity_keys_length=s.asm.F).apply(null,arguments)},s._olm_account_identity_keys=function(){return(s._olm_account_identity_keys=s.asm.G).apply(null,arguments)},s._olm_account_signature_length=function(){return(s._olm_account_signature_length=s.asm.H).apply(null,arguments)},s._olm_account_sign=function(){return(s._olm_account_sign=s.asm.I).apply(null,arguments)},s._olm_account_one_time_keys_length=function(){return(s._olm_account_one_time_keys_length=s.asm.J).apply(null,arguments)},s._olm_account_one_time_keys=function(){return(s._olm_account_one_time_keys=s.asm.K).apply(null,arguments)},s._olm_account_mark_keys_as_published=function(){return(s._olm_account_mark_keys_as_published=s.asm.L).apply(null,arguments)},s._olm_account_max_number_of_one_time_keys=function(){return(s._olm_account_max_number_of_one_time_keys=s.asm.M).apply(null,arguments)},s._olm_account_generate_one_time_keys_random_length=function(){return(s._olm_account_generate_one_time_keys_random_length=s.asm.N).apply(null,arguments)},s._olm_account_generate_one_time_keys=function(){return(s._olm_account_generate_one_time_keys=s.asm.O).apply(null,arguments)},s._olm_account_generate_fallback_key_random_length=function(){return(s._olm_account_generate_fallback_key_random_length=s.asm.P).apply(null,arguments)},s._olm_account_generate_fallback_key=function(){return(s._olm_account_generate_fallback_key=s.asm.Q).apply(null,arguments)},s._olm_account_fallback_key_length=function(){return(s._olm_account_fallback_key_length=s.asm.R).apply(null,arguments)},s._olm_account_fallback_key=function(){return(s._olm_account_fallback_key=s.asm.S).apply(null,arguments)},s._olm_account_unpublished_fallback_key_length=function(){return(s._olm_account_unpublished_fallback_key_length=s.asm.T).apply(null,arguments)},s._olm_account_unpublished_fallback_key=function(){return(s._olm_account_unpublished_fallback_key=s.asm.U).apply(null,arguments)},s._olm_account_forget_old_fallback_key=function(){return(s._olm_account_forget_old_fallback_key=s.asm.V).apply(null,arguments)},s._olm_create_outbound_session_random_length=function(){return(s._olm_create_outbound_session_random_length=s.asm.W).apply(null,arguments)},s._olm_create_outbound_session=function(){return(s._olm_create_outbound_session=s.asm.X).apply(null,arguments)},s._olm_create_inbound_session=function(){return(s._olm_create_inbound_session=s.asm.Y).apply(null,arguments)},s._olm_create_inbound_session_from=function(){return(s._olm_create_inbound_session_from=s.asm.Z).apply(null,arguments)},s._olm_session_id_length=function(){return(s._olm_session_id_length=s.asm._).apply(null,arguments)},s._olm_session_id=function(){return(s._olm_session_id=s.asm.$).apply(null,arguments)},s._olm_session_has_received_message=function(){return(s._olm_session_has_received_message=s.asm.aa).apply(null,arguments)},s._olm_session_describe=function(){return(s._olm_session_describe=s.asm.ba).apply(null,arguments)},s._olm_matches_inbound_session=function(){return(s._olm_matches_inbound_session=s.asm.ca).apply(null,arguments)},s._olm_matches_inbound_session_from=function(){return(s._olm_matches_inbound_session_from=s.asm.da).apply(null,arguments)},s._olm_remove_one_time_keys=function(){return(s._olm_remove_one_time_keys=s.asm.ea).apply(null,arguments)},s._olm_encrypt_message_type=function(){return(s._olm_encrypt_message_type=s.asm.fa).apply(null,arguments)},s._olm_encrypt_random_length=function(){return(s._olm_encrypt_random_length=s.asm.ga).apply(null,arguments)},s._olm_encrypt_message_length=function(){return(s._olm_encrypt_message_length=s.asm.ha).apply(null,arguments)},s._olm_encrypt=function(){return(s._olm_encrypt=s.asm.ia).apply(null,arguments)},s._olm_decrypt_max_plaintext_length=function(){return(s._olm_decrypt_max_plaintext_length=s.asm.ja).apply(null,arguments)},s._olm_decrypt=function(){return(s._olm_decrypt=s.asm.ka).apply(null,arguments)},s._olm_sha256_length=function(){return(s._olm_sha256_length=s.asm.la).apply(null,arguments)},s._olm_sha256=function(){return(s._olm_sha256=s.asm.ma).apply(null,arguments)},s._olm_ed25519_verify=function(){return(s._olm_ed25519_verify=s.asm.na).apply(null,arguments)},s._olm_pk_encryption_last_error=function(){return(s._olm_pk_encryption_last_error=s.asm.oa).apply(null,arguments)},s._olm_pk_encryption_last_error_code=function(){return(s._olm_pk_encryption_last_error_code=s.asm.pa).apply(null,arguments)},s._olm_pk_encryption_size=function(){return(s._olm_pk_encryption_size=s.asm.qa).apply(null,arguments)},s._olm_pk_encryption=function(){return(s._olm_pk_encryption=s.asm.ra).apply(null,arguments)},s._olm_clear_pk_encryption=function(){return(s._olm_clear_pk_encryption=s.asm.sa).apply(null,arguments)},s._olm_pk_encryption_set_recipient_key=function(){return(s._olm_pk_encryption_set_recipient_key=s.asm.ta).apply(null,arguments)},s._olm_pk_key_length=function(){return(s._olm_pk_key_length=s.asm.ua).apply(null,arguments)},s._olm_pk_ciphertext_length=function(){return(s._olm_pk_ciphertext_length=s.asm.va).apply(null,arguments)},s._olm_pk_mac_length=function(){return(s._olm_pk_mac_length=s.asm.wa).apply(null,arguments)},s._olm_pk_encrypt_random_length=function(){return(s._olm_pk_encrypt_random_length=s.asm.xa).apply(null,arguments)},s._olm_pk_encrypt=function(){return(s._olm_pk_encrypt=s.asm.ya).apply(null,arguments)},s._olm_pk_decryption_last_error=function(){return(s._olm_pk_decryption_last_error=s.asm.za).apply(null,arguments)},s._olm_pk_decryption_last_error_code=function(){return(s._olm_pk_decryption_last_error_code=s.asm.Aa).apply(null,arguments)},s._olm_pk_decryption_size=function(){return(s._olm_pk_decryption_size=s.asm.Ba).apply(null,arguments)},s._olm_pk_decryption=function(){return(s._olm_pk_decryption=s.asm.Ca).apply(null,arguments)},s._olm_clear_pk_decryption=function(){return(s._olm_clear_pk_decryption=s.asm.Da).apply(null,arguments)},s._olm_pk_private_key_length=function(){return(s._olm_pk_private_key_length=s.asm.Ea).apply(null,arguments)},s._olm_pk_generate_key_random_length=function(){return(s._olm_pk_generate_key_random_length=s.asm.Fa).apply(null,arguments)},s._olm_pk_key_from_private=function(){return(s._olm_pk_key_from_private=s.asm.Ga).apply(null,arguments)},s._olm_pk_generate_key=function(){return(s._olm_pk_generate_key=s.asm.Ha).apply(null,arguments)},s._olm_pickle_pk_decryption_length=function(){return(s._olm_pickle_pk_decryption_length=s.asm.Ia).apply(null,arguments)},s._olm_pickle_pk_decryption=function(){return(s._olm_pickle_pk_decryption=s.asm.Ja).apply(null,arguments)},s._olm_unpickle_pk_decryption=function(){return(s._olm_unpickle_pk_decryption=s.asm.Ka).apply(null,arguments)},s._olm_pk_max_plaintext_length=function(){return(s._olm_pk_max_plaintext_length=s.asm.La).apply(null,arguments)},s._olm_pk_decrypt=function(){return(s._olm_pk_decrypt=s.asm.Ma).apply(null,arguments)},s._olm_pk_get_private_key=function(){return(s._olm_pk_get_private_key=s.asm.Na).apply(null,arguments)},s._olm_pk_signing_size=function(){return(s._olm_pk_signing_size=s.asm.Oa).apply(null,arguments)},s._olm_pk_signing=function(){return(s._olm_pk_signing=s.asm.Pa).apply(null,arguments)},s._olm_pk_signing_last_error=function(){return(s._olm_pk_signing_last_error=s.asm.Qa).apply(null,arguments)},s._olm_pk_signing_last_error_code=function(){return(s._olm_pk_signing_last_error_code=s.asm.Ra).apply(null,arguments)},s._olm_clear_pk_signing=function(){return(s._olm_clear_pk_signing=s.asm.Sa).apply(null,arguments)},s._olm_pk_signing_seed_length=function(){return(s._olm_pk_signing_seed_length=s.asm.Ta).apply(null,arguments)},s._olm_pk_signing_public_key_length=function(){return(s._olm_pk_signing_public_key_length=s.asm.Ua).apply(null,arguments)},s._olm_pk_signing_key_from_seed=function(){return(s._olm_pk_signing_key_from_seed=s.asm.Va).apply(null,arguments)},s._olm_pk_signature_length=function(){return(s._olm_pk_signature_length=s.asm.Wa).apply(null,arguments)},s._olm_pk_sign=function(){return(s._olm_pk_sign=s.asm.Xa).apply(null,arguments)},s._olm_inbound_group_session_size=function(){return(s._olm_inbound_group_session_size=s.asm.Ya).apply(null,arguments)},s._olm_inbound_group_session=function(){return(s._olm_inbound_group_session=s.asm.Za).apply(null,arguments)},s._olm_clear_inbound_group_session=function(){return(s._olm_clear_inbound_group_session=s.asm._a).apply(null,arguments)},s._olm_inbound_group_session_last_error=function(){return(s._olm_inbound_group_session_last_error=s.asm.$a).apply(null,arguments)},s._olm_inbound_group_session_last_error_code=function(){return(s._olm_inbound_group_session_last_error_code=s.asm.ab).apply(null,arguments)},s._olm_init_inbound_group_session=function(){return(s._olm_init_inbound_group_session=s.asm.bb).apply(null,arguments)},s._olm_import_inbound_group_session=function(){return(s._olm_import_inbound_group_session=s.asm.cb).apply(null,arguments)},s._olm_pickle_inbound_group_session_length=function(){return(s._olm_pickle_inbound_group_session_length=s.asm.db).apply(null,arguments)},s._olm_pickle_inbound_group_session=function(){return(s._olm_pickle_inbound_group_session=s.asm.eb).apply(null,arguments)},s._olm_unpickle_inbound_group_session=function(){return(s._olm_unpickle_inbound_group_session=s.asm.fb).apply(null,arguments)},s._olm_group_decrypt_max_plaintext_length=function(){return(s._olm_group_decrypt_max_plaintext_length=s.asm.gb).apply(null,arguments)},s._olm_group_decrypt=function(){return(s._olm_group_decrypt=s.asm.hb).apply(null,arguments)},s._olm_inbound_group_session_id_length=function(){return(s._olm_inbound_group_session_id_length=s.asm.ib).apply(null,arguments)},s._olm_inbound_group_session_id=function(){return(s._olm_inbound_group_session_id=s.asm.jb).apply(null,arguments)},s._olm_inbound_group_session_first_known_index=function(){return(s._olm_inbound_group_session_first_known_index=s.asm.kb).apply(null,arguments)},s._olm_inbound_group_session_is_verified=function(){return(s._olm_inbound_group_session_is_verified=s.asm.lb).apply(null,arguments)},s._olm_export_inbound_group_session_length=function(){return(s._olm_export_inbound_group_session_length=s.asm.mb).apply(null,arguments)},s._olm_export_inbound_group_session=function(){return(s._olm_export_inbound_group_session=s.asm.nb).apply(null,arguments)},s._olm_outbound_group_session_size=function(){return(s._olm_outbound_group_session_size=s.asm.ob).apply(null,arguments)},s._olm_outbound_group_session=function(){return(s._olm_outbound_group_session=s.asm.pb).apply(null,arguments)},s._olm_clear_outbound_group_session=function(){return(s._olm_clear_outbound_group_session=s.asm.qb).apply(null,arguments)},s._olm_outbound_group_session_last_error=function(){return(s._olm_outbound_group_session_last_error=s.asm.rb).apply(null,arguments)},s._olm_outbound_group_session_last_error_code=function(){return(s._olm_outbound_group_session_last_error_code=s.asm.sb).apply(null,arguments)},s._olm_pickle_outbound_group_session_length=function(){return(s._olm_pickle_outbound_group_session_length=s.asm.tb).apply(null,arguments)},s._olm_pickle_outbound_group_session=function(){return(s._olm_pickle_outbound_group_session=s.asm.ub).apply(null,arguments)},s._olm_unpickle_outbound_group_session=function(){return(s._olm_unpickle_outbound_group_session=s.asm.vb).apply(null,arguments)},s._olm_init_outbound_group_session_random_length=function(){return(s._olm_init_outbound_group_session_random_length=s.asm.wb).apply(null,arguments)},s._olm_init_outbound_group_session=function(){return(s._olm_init_outbound_group_session=s.asm.xb).apply(null,arguments)},s._olm_group_encrypt_message_length=function(){return(s._olm_group_encrypt_message_length=s.asm.yb).apply(null,arguments)},s._olm_group_encrypt=function(){return(s._olm_group_encrypt=s.asm.zb).apply(null,arguments)},s._olm_outbound_group_session_id_length=function(){return(s._olm_outbound_group_session_id_length=s.asm.Ab).apply(null,arguments)},s._olm_outbound_group_session_id=function(){return(s._olm_outbound_group_session_id=s.asm.Bb).apply(null,arguments)},s._olm_outbound_group_session_message_index=function(){return(s._olm_outbound_group_session_message_index=s.asm.Cb).apply(null,arguments)},s._olm_outbound_group_session_key_length=function(){return(s._olm_outbound_group_session_key_length=s.asm.Db).apply(null,arguments)},s._olm_outbound_group_session_key=function(){return(s._olm_outbound_group_session_key=s.asm.Eb).apply(null,arguments)},s._olm_sas_last_error=function(){return(s._olm_sas_last_error=s.asm.Fb).apply(null,arguments)},s._olm_sas_last_error_code=function(){return(s._olm_sas_last_error_code=s.asm.Gb).apply(null,arguments)},s._olm_sas_size=function(){return(s._olm_sas_size=s.asm.Hb).apply(null,arguments)},s._olm_sas=function(){return(s._olm_sas=s.asm.Ib).apply(null,arguments)},s._olm_clear_sas=function(){return(s._olm_clear_sas=s.asm.Jb).apply(null,arguments)},s._olm_create_sas_random_length=function(){return(s._olm_create_sas_random_length=s.asm.Kb).apply(null,arguments)},s._olm_create_sas=function(){return(s._olm_create_sas=s.asm.Lb).apply(null,arguments)},s._olm_sas_pubkey_length=function(){return(s._olm_sas_pubkey_length=s.asm.Mb).apply(null,arguments)},s._olm_sas_get_pubkey=function(){return(s._olm_sas_get_pubkey=s.asm.Nb).apply(null,arguments)},s._olm_sas_set_their_key=function(){return(s._olm_sas_set_their_key=s.asm.Ob).apply(null,arguments)},s._olm_sas_is_their_key_set=function(){return(s._olm_sas_is_their_key_set=s.asm.Pb).apply(null,arguments)},s._olm_sas_generate_bytes=function(){return(s._olm_sas_generate_bytes=s.asm.Qb).apply(null,arguments)},s._olm_sas_mac_length=function(){return(s._olm_sas_mac_length=s.asm.Rb).apply(null,arguments)},s._olm_sas_calculate_mac_fixed_base64=function(){return(s._olm_sas_calculate_mac_fixed_base64=s.asm.Sb).apply(null,arguments)},s._olm_sas_calculate_mac=function(){return(s._olm_sas_calculate_mac=s.asm.Tb).apply(null,arguments)},s._olm_sas_calculate_mac_long_kdf=function(){return(s._olm_sas_calculate_mac_long_kdf=s.asm.Ub).apply(null,arguments)},s._malloc=function(){return(s._malloc=s.asm.Vb).apply(null,arguments)},s._free=function(){return(s._free=s.asm.Wb).apply(null,arguments)};var De=s.stackSave=function(){return(De=s.stackSave=s.asm.Xb).apply(null,arguments)},je=s.stackRestore=function(){return(je=s.stackRestore=s.asm.Yb).apply(null,arguments)},Le=s.stackAlloc=function(){return(Le=s.stackAlloc=s.asm.Zb).apply(null,arguments)};s.intArrayFromString=Se,s.writeAsciiToMemory=le,s.ALLOC_STACK=1;var Ve;Q=function q(){Ve||Be(),Ve||(Q=q)};function Be(){function q(){if(!Ve&&(Ve=!0,s.calledRun=!0,!D)){if(he(ae),g(s),s.onRuntimeInitialized&&s.onRuntimeInitialized(),s.postRun)for(typeof s.postRun=="function"&&(s.postRun=[s.postRun]);s.postRun.length;){var J=s.postRun.shift();pe.unshift(J)}he(pe)}}if(!(0<se)){if(s.preRun)for(typeof s.preRun=="function"&&(s.preRun=[s.preRun]);s.preRun.length;)V();he(ne),0<se||(s.setStatus?(s.setStatus("Running..."),setTimeout(function(){setTimeout(function(){s.setStatus("")},1),q()},1)):q())}}if(s.preInit)for(typeof s.preInit=="function"&&(s.preInit=[s.preInit]);0<s.preInit.length;)s.preInit.pop()();Be();function Ne(){var q=s._olm_outbound_group_session_size();this.ac=be(q),this.$b=s._olm_outbound_group_session(this.ac)}function We(q){return function(){var J=q.apply(this,arguments);if(J===Fe)throw J=z(s._olm_outbound_group_session_last_error(arguments[0])),Error("OLM."+J);return J}}Ne.prototype.free=function(){s._olm_clear_outbound_group_session(this.$b),Ce(this.$b)},Ne.prototype.pickle=ke(function(q){q=qe(q);var J=We(s._olm_pickle_outbound_group_session_length)(this.$b),oe=Ee(q),me=Ee(J+1);try{We(s._olm_pickle_outbound_group_session)(this.$b,oe,q.length,me,J)}finally{for(Me(oe,q.length),oe=0;oe<q.length;oe++)q[oe]=0}return z(me,J)}),Ne.prototype.unpickle=ke(function(q,J){q=qe(q);var oe=Ee(q);J=qe(J);var me=Ee(J);try{We(s._olm_unpickle_outbound_group_session)(this.$b,oe,q.length,me,J.length)}finally{for(Me(oe,q.length),oe=0;oe<q.length;oe++)q[oe]=0}}),Ne.prototype.create=ke(function(){var q=We(s._olm_init_outbound_group_session_random_length)(this.$b),J=Pe(q,S);try{We(s._olm_init_outbound_group_session)(this.$b,J,q)}finally{Me(J,q)}}),Ne.prototype.encrypt=function(q){try{var J=F(q),oe=We(s._olm_group_encrypt_message_length)(this.$b,J),me=be(J+1);W(q,P,me,J+1);var Ie=be(oe+1);return We(s._olm_group_encrypt)(this.$b,me,J,Ie,oe),ce(Ie+oe),z(Ie,oe)}finally{me!==void 0&&(Me(me,J+1),Ce(me)),Ie!==void 0&&Ce(Ie)}},Ne.prototype.session_id=ke(function(){var q=We(s._olm_outbound_group_session_id_length)(this.$b),J=Ee(q+1);return We(s._olm_outbound_group_session_id)(this.$b,J,q),z(J,q)}),Ne.prototype.session_key=ke(function(){var q=We(s._olm_outbound_group_session_key_length)(this.$b),J=Ee(q+1);We(s._olm_outbound_group_session_key)(this.$b,J,q);var oe=z(J,q);return Me(J,q),oe}),Ne.prototype.message_index=function(){return We(s._olm_outbound_group_session_message_index)(this.$b)},r.OutboundGroupSession=Ne;function Re(){var q=s._olm_inbound_group_session_size();this.ac=be(q),this.$b=s._olm_inbound_group_session(this.ac)}function b(q){return function(){var J=q.apply(this,arguments);if(J===Fe)throw J=z(s._olm_inbound_group_session_last_error(arguments[0])),Error("OLM."+J);return J}}Re.prototype.free=function(){s._olm_clear_inbound_group_session(this.$b),Ce(this.$b)},Re.prototype.pickle=ke(function(q){q=qe(q);var J=b(s._olm_pickle_inbound_group_session_length)(this.$b),oe=Ee(q),me=Ee(J+1);try{b(s._olm_pickle_inbound_group_session)(this.$b,oe,q.length,me,J)}finally{for(Me(oe,q.length),oe=0;oe<q.length;oe++)q[oe]=0}return z(me,J)}),Re.prototype.unpickle=ke(function(q,J){q=qe(q);var oe=Ee(q);J=qe(J);var me=Ee(J);try{b(s._olm_unpickle_inbound_group_session)(this.$b,oe,q.length,me,J.length)}finally{for(Me(oe,q.length),oe=0;oe<q.length;oe++)q[oe]=0}}),Re.prototype.create=ke(function(q){q=qe(q);var J=Ee(q);try{b(s._olm_init_inbound_group_session)(this.$b,J,q.length)}finally{for(Me(J,q.length),J=0;J<q.length;J++)q[J]=0}}),Re.prototype.import_session=ke(function(q){q=qe(q);var J=Ee(q);try{b(s._olm_import_inbound_group_session)(this.$b,J,q.length)}finally{for(Me(J,q.length),J=0;J<q.length;J++)q[J]=0}}),Re.prototype.decrypt=ke(function(q){try{var J=be(q.length);le(q,J,!0);var oe=b(s._olm_group_decrypt_max_plaintext_length)(this.$b,J,q.length);le(q,J,!0);var me=be(oe+1),Ie=Ee(4),He=b(s._olm_group_decrypt)(this.$b,J,q.length,me,oe,Ie);return ce(me+He),{plaintext:z(me,He),message_index:ye(Ie,"i32")}}finally{J!==void 0&&Ce(J),me!==void 0&&(Me(me,He),Ce(me))}}),Re.prototype.session_id=ke(function(){var q=b(s._olm_inbound_group_session_id_length)(this.$b),J=Ee(q+1);return b(s._olm_inbound_group_session_id)(this.$b,J,q),z(J,q)}),Re.prototype.first_known_index=ke(function(){return b(s._olm_inbound_group_session_first_known_index)(this.$b)}),Re.prototype.export_session=ke(function(q){var J=b(s._olm_export_inbound_group_session_length)(this.$b),oe=Ee(J+1);return We(s._olm_export_inbound_group_session)(this.$b,oe,J,q),q=z(oe,J),Me(oe,J),q}),r.InboundGroupSession=Re;function O(){var q=s._olm_pk_encryption_size();this.ac=be(q),this.$b=s._olm_pk_encryption(this.ac)}function $(q){return function(){var J=q.apply(this,arguments);if(J===Fe)throw J=z(s._olm_pk_encryption_last_error(arguments[0])),Error("OLM."+J);return J}}O.prototype.free=function(){s._olm_clear_pk_encryption(this.$b),Ce(this.$b)},O.prototype.set_recipient_key=ke(function(q){q=qe(q);var J=Ee(q);$(s._olm_pk_encryption_set_recipient_key)(this.$b,J,q.length)}),O.prototype.encrypt=ke(function(q){try{var J=F(q),oe=be(J+1);W(q,P,oe,J+1);var me=$(s._olm_pk_encrypt_random_length)(),Ie=Pe(me,S),He=$(s._olm_pk_ciphertext_length)(this.$b,J),rt=be(He+1),on=$(s._olm_pk_mac_length)(this.$b),ka=Ee(on+1);ce(ka+on);var go=$(s._olm_pk_key_length)(),Ir=Ee(go+1);return ce(Ir+go),$(s._olm_pk_encrypt)(this.$b,oe,J,rt,He,ka,on,Ir,go,Ie,me),ce(rt+He),{ciphertext:z(rt,He),mac:z(ka,on),ephemeral:z(Ir,go)}}finally{Ie!==void 0&&Me(Ie,me),oe!==void 0&&(Me(oe,J+1),Ce(oe)),rt!==void 0&&Ce(rt)}});function Y(){var q=s._olm_pk_decryption_size();this.ac=be(q),this.$b=s._olm_pk_decryption(this.ac)}function ee(q){return function(){var J=q.apply(this,arguments);if(J===Fe)throw J=z(s._olm_pk_decryption_last_error(arguments[0])),Error("OLM."+J);return J}}Y.prototype.free=function(){s._olm_clear_pk_decryption(this.$b),Ce(this.$b)},Y.prototype.init_with_private_key=ke(function(q){var J=Ee(q.length);s.HEAPU8.set(q,J);var oe=ee(s._olm_pk_key_length)(),me=Ee(oe+1);try{ee(s._olm_pk_key_from_private)(this.$b,me,oe,J,q.length)}finally{Me(J,q.length)}return z(me,oe)}),Y.prototype.generate_key=ke(function(){var q=ee(s._olm_pk_private_key_length)(),J=Pe(q,S),oe=ee(s._olm_pk_key_length)(),me=Ee(oe+1);try{ee(s._olm_pk_key_from_private)(this.$b,me,oe,J,q)}finally{Me(J,q)}return z(me,oe)}),Y.prototype.get_private_key=ke(function(){var q=$(s._olm_pk_private_key_length)(),J=Ee(q);ee(s._olm_pk_get_private_key)(this.$b,J,q);var oe=new Uint8Array(new Uint8Array(s.HEAPU8.buffer,J,q));return Me(J,q),oe}),Y.prototype.pickle=ke(function(q){q=qe(q);var J=ee(s._olm_pickle_pk_decryption_length)(this.$b),oe=Ee(q),me=Ee(J+1);try{ee(s._olm_pickle_pk_decryption)(this.$b,oe,q.length,me,J)}finally{for(Me(oe,q.length),oe=0;oe<q.length;oe++)q[oe]=0}return z(me,J)}),Y.prototype.unpickle=ke(function(q,J){q=qe(q);var oe=Ee(q),me=qe(J),Ie=Ee(me);J=ee(s._olm_pk_key_length)();var He=Ee(J+1);try{ee(s._olm_unpickle_pk_decryption)(this.$b,oe,q.length,Ie,me.length,He,J)}finally{for(Me(oe,q.length),oe=0;oe<q.length;oe++)q[oe]=0}return z(He,J)}),Y.prototype.decrypt=ke(function(q,J,oe){try{var me=F(oe),Ie=be(me+1);W(oe,P,Ie,me+1);var He=qe(q),rt=Ee(He),on=qe(J),ka=Ee(on),go=ee(s._olm_pk_max_plaintext_length)(this.$b,me),Ir=be(go+1),eh=ee(s._olm_pk_decrypt)(this.$b,rt,He.length,ka,on.length,Ie,me,Ir,go);return ce(Ir+eh),z(Ir,eh)}finally{Ir!==void 0&&(Me(Ir,eh+1),Ce(Ir)),Ie!==void 0&&Ce(Ie)}});function ie(){var q=s._olm_pk_signing_size();this.ac=be(q),this.$b=s._olm_pk_signing(this.ac)}function ue(q){return function(){var J=q.apply(this,arguments);if(J===Fe)throw J=z(s._olm_pk_signing_last_error(arguments[0])),Error("OLM."+J);return J}}ie.prototype.free=function(){s._olm_clear_pk_signing(this.$b),Ce(this.$b)},ie.prototype.init_with_seed=ke(function(q){var J=Ee(q.length);s.HEAPU8.set(q,J);var oe=ue(s._olm_pk_signing_public_key_length)(),me=Ee(oe+1);try{ue(s._olm_pk_signing_key_from_seed)(this.$b,me,oe,J,q.length)}finally{Me(J,q.length)}return z(me,oe)}),ie.prototype.generate_seed=ke(function(){var q=ue(s._olm_pk_signing_seed_length)(),J=Pe(q,S),oe=new Uint8Array(new Uint8Array(s.HEAPU8.buffer,J,q));return Me(J,q),oe}),ie.prototype.sign=ke(function(q){try{var J=F(q),oe=be(J+1);W(q,P,oe,J+1);var me=ue(s._olm_pk_signature_length)(),Ie=Ee(me+1);return ue(s._olm_pk_sign)(this.$b,oe,J,Ie,me),z(Ie,me)}finally{oe!==void 0&&(Me(oe,J+1),Ce(oe))}});function ve(){var q=s._olm_sas_size(),J=s._olm_create_sas_random_length(),oe=Pe(J,S);this.ac=be(q),this.$b=s._olm_sas(this.ac),s._olm_create_sas(this.$b,oe,J),Me(oe,J)}function _e(q){return function(){var J=q.apply(this,arguments);if(J===Fe)throw J=z(s._olm_sas_last_error(arguments[0])),Error("OLM."+J);return J}}ve.prototype.free=function(){s._olm_clear_sas(this.$b),Ce(this.$b)},ve.prototype.get_pubkey=ke(function(){var q=_e(s._olm_sas_pubkey_length)(this.$b),J=Ee(q+1);return _e(s._olm_sas_get_pubkey)(this.$b,J,q),z(J,q)}),ve.prototype.set_their_key=ke(function(q){q=qe(q);var J=Ee(q);_e(s._olm_sas_set_their_key)(this.$b,J,q.length)}),ve.prototype.is_their_key_set=ke(function(){return!!_e(s._olm_sas_is_their_key_set)(this.$b)}),ve.prototype.generate_bytes=ke(function(q,J){q=qe(q);var oe=Ee(q),me=Ee(J);return _e(s._olm_sas_generate_bytes)(this.$b,oe,q.length,me,J),new Uint8Array(new Uint8Array(s.HEAPU8.buffer,me,J))}),ve.prototype.calculate_mac=ke(function(q,J){q=qe(q);var oe=Ee(q);J=qe(J);var me=Ee(J),Ie=_e(s._olm_sas_mac_length)(this.$b),He=Ee(Ie+1);return _e(s._olm_sas_calculate_mac)(this.$b,oe,q.length,me,J.length,He,Ie),z(He,Ie)}),ve.prototype.calculate_mac_fixed_base64=ke(function(q,J){q=qe(q);var oe=Ee(q);J=qe(J);var me=Ee(J),Ie=_e(s._olm_sas_mac_length)(this.$b),He=Ee(Ie+1);return _e(s._olm_sas_calculate_mac_fixed_base64)(this.$b,oe,q.length,me,J.length,He,Ie),z(He,Ie)}),ve.prototype.calculate_mac_long_kdf=ke(function(q,J){q=qe(q);var oe=Ee(q);J=qe(J);var me=Ee(J),Ie=_e(s._olm_sas_mac_length)(this.$b),He=Ee(Ie+1);return _e(s._olm_sas_calculate_mac_long_kdf)(this.$b,oe,q.length,me,J.length,He,Ie),z(He,Ie)});var be=s._malloc,Ce=s._free,Fe;function Pe(q,J){var oe=Le(q);return J(new Uint8Array(s.HEAPU8.buffer,oe,q)),oe}function Ee(q){return typeof q=="number"?Pe(q,function(J){J.fill(0)}):Pe(q.length,function(J){J.set(q)})}function qe(q){return q instanceof Uint8Array?q:Se(q,!0)}function ke(q){return function(){var J=De();try{return q.apply(this,arguments)}finally{je(J)}}}function Me(q,J){for(;0<J--;)s.HEAP8[q++]=0}function tt(){var q=s._olm_account_size();this.ac=be(q),this.$b=s._olm_account(this.ac)}function Ye(q){return function(){var J=q.apply(this,arguments);if(J===Fe)throw J=z(s._olm_account_last_error(arguments[0])),Error("OLM."+J);return J}}tt.prototype.free=function(){s._olm_clear_account(this.$b),Ce(this.$b)},tt.prototype.create=ke(function(){var q=Ye(s._olm_create_account_random_length)(this.$b),J=Pe(q,S);try{Ye(s._olm_create_account)(this.$b,J,q)}finally{Me(J,q)}}),tt.prototype.identity_keys=ke(function(){var q=Ye(s._olm_account_identity_keys_length)(this.$b),J=Ee(q+1);return Ye(s._olm_account_identity_keys)(this.$b,J,q),z(J,q)}),tt.prototype.sign=ke(function(q){var J=Ye(s._olm_account_signature_length)(this.$b);q=qe(q);var oe=Ee(q),me=Ee(J+1);try{Ye(s._olm_account_sign)(this.$b,oe,q.length,me,J)}finally{for(Me(oe,q.length),oe=0;oe<q.length;oe++)q[oe]=0}return z(me,J)}),tt.prototype.one_time_keys=ke(function(){var q=Ye(s._olm_account_one_time_keys_length)(this.$b),J=Ee(q+1);return Ye(s._olm_account_one_time_keys)(this.$b,J,q),z(J,q)}),tt.prototype.mark_keys_as_published=ke(function(){Ye(s._olm_account_mark_keys_as_published)(this.$b)}),tt.prototype.max_number_of_one_time_keys=ke(function(){return Ye(s._olm_account_max_number_of_one_time_keys)(this.$b)}),tt.prototype.generate_one_time_keys=ke(function(q){var J=Ye(s._olm_account_generate_one_time_keys_random_length)(this.$b,q),oe=Pe(J,S);try{Ye(s._olm_account_generate_one_time_keys)(this.$b,q,oe,J)}finally{Me(oe,J)}}),tt.prototype.remove_one_time_keys=ke(function(q){Ye(s._olm_remove_one_time_keys)(this.$b,q.$b)}),tt.prototype.generate_fallback_key=ke(function(){var q=Ye(s._olm_account_generate_fallback_key_random_length)(this.$b),J=Pe(q,S);try{Ye(s._olm_account_generate_fallback_key)(this.$b,J,q)}finally{Me(J,q)}}),tt.prototype.fallback_key=ke(function(){var q=Ye(s._olm_account_fallback_key_length)(this.$b),J=Ee(q+1);return Ye(s._olm_account_fallback_key)(this.$b,J,q),z(J,q)}),tt.prototype.unpublished_fallback_key=ke(function(){var q=Ye(s._olm_account_unpublished_fallback_key_length)(this.$b),J=Ee(q+1);return Ye(s._olm_account_unpublished_fallback_key)(this.$b,J,q),z(J,q)}),tt.prototype.forget_old_fallback_key=ke(function(){Ye(s._olm_account_forget_old_fallback_key)(this.$b)}),tt.prototype.pickle=ke(function(q){q=qe(q);var J=Ye(s._olm_pickle_account_length)(this.$b),oe=Ee(q),me=Ee(J+1);try{Ye(s._olm_pickle_account)(this.$b,oe,q.length,me,J)}finally{for(Me(oe,q.length),oe=0;oe<q.length;oe++)q[oe]=0}return z(me,J)}),tt.prototype.unpickle=ke(function(q,J){q=qe(q);var oe=Ee(q);J=qe(J);var me=Ee(J);try{Ye(s._olm_unpickle_account)(this.$b,oe,q.length,me,J.length)}finally{for(Me(oe,q.length),oe=0;oe<q.length;oe++)q[oe]=0}});function Xe(){var q=s._olm_session_size();this.ac=be(q),this.$b=s._olm_session(this.ac)}function ze(q){return function(){var J=q.apply(this,arguments);if(J===Fe)throw J=z(s._olm_session_last_error(arguments[0])),Error("OLM."+J);return J}}Xe.prototype.free=function(){s._olm_clear_session(this.$b),Ce(this.$b)},Xe.prototype.pickle=ke(function(q){q=qe(q);var J=ze(s._olm_pickle_session_length)(this.$b),oe=Ee(q),me=Ee(J+1);try{ze(s._olm_pickle_session)(this.$b,oe,q.length,me,J)}finally{for(Me(oe,q.length),oe=0;oe<q.length;oe++)q[oe]=0}return z(me,J)}),Xe.prototype.unpickle=ke(function(q,J){q=qe(q);var oe=Ee(q);J=qe(J);var me=Ee(J);try{ze(s._olm_unpickle_session)(this.$b,oe,q.length,me,J.length)}finally{for(Me(oe,q.length),oe=0;oe<q.length;oe++)q[oe]=0}}),Xe.prototype.create_outbound=ke(function(q,J,oe){var me=ze(s._olm_create_outbound_session_random_length)(this.$b),Ie=Pe(me,S);J=qe(J),oe=qe(oe);var He=Ee(J),rt=Ee(oe);try{ze(s._olm_create_outbound_session)(this.$b,q.$b,He,J.length,rt,oe.length,Ie,me)}finally{Me(Ie,me)}}),Xe.prototype.create_inbound=ke(function(q,J){J=qe(J);var oe=Ee(J);try{ze(s._olm_create_inbound_session)(this.$b,q.$b,oe,J.length)}finally{for(Me(oe,J.length),q=0;q<J.length;q++)J[q]=0}}),Xe.prototype.create_inbound_from=ke(function(q,J,oe){J=qe(J);var me=Ee(J);oe=qe(oe);var Ie=Ee(oe);try{ze(s._olm_create_inbound_session_from)(this.$b,q.$b,me,J.length,Ie,oe.length)}finally{for(Me(Ie,oe.length),q=0;q<oe.length;q++)oe[q]=0}}),Xe.prototype.session_id=ke(function(){var q=ze(s._olm_session_id_length)(this.$b),J=Ee(q+1);return ze(s._olm_session_id)(this.$b,J,q),z(J,q)}),Xe.prototype.has_received_message=function(){return!!ze(s._olm_session_has_received_message)(this.$b)},Xe.prototype.matches_inbound=ke(function(q){q=qe(q);var J=Ee(q);return!!ze(s._olm_matches_inbound_session)(this.$b,J,q.length)}),Xe.prototype.matches_inbound_from=ke(function(q,J){q=qe(q);var oe=Ee(q);J=qe(J);var me=Ee(J);return!!ze(s._olm_matches_inbound_session_from)(this.$b,oe,q.length,me,J.length)}),Xe.prototype.encrypt=ke(function(q){try{var J=ze(s._olm_encrypt_random_length)(this.$b),oe=ze(s._olm_encrypt_message_type)(this.$b),me=F(q),Ie=ze(s._olm_encrypt_message_length)(this.$b,me),He=Pe(J,S),rt=be(me+1);W(q,P,rt,me+1);var on=be(Ie+1);return ze(s._olm_encrypt)(this.$b,rt,me,He,J,on,Ie),ce(on+Ie),{type:oe,body:z(on,Ie)}}finally{He!==void 0&&Me(He,J),rt!==void 0&&(Me(rt,me+1),Ce(rt)),on!==void 0&&Ce(on)}}),Xe.prototype.decrypt=ke(function(q,J){try{var oe=be(J.length);le(J,oe,!0);var me=ze(s._olm_decrypt_max_plaintext_length)(this.$b,q,oe,J.length);le(J,oe,!0);var Ie=be(me+1),He=ze(s._olm_decrypt)(this.$b,q,oe,J.length,Ie,me);return ce(Ie+He),z(Ie,He)}finally{oe!==void 0&&Ce(oe),Ie!==void 0&&(Me(Ie,me),Ce(Ie))}}),Xe.prototype.describe=ke(function(){try{var q=be(256);return ze(s._olm_session_describe)(this.$b,q,256),z(q)}finally{q!==void 0&&Ce(q)}});function gt(){var q=s._olm_utility_size();this.ac=be(q),this.$b=s._olm_utility(this.ac)}function rn(q){return function(){var J=q.apply(this,arguments);if(J===Fe)throw J=z(s._olm_utility_last_error(arguments[0])),Error("OLM."+J);return J}}return gt.prototype.free=function(){s._olm_clear_utility(this.$b),Ce(this.$b)},gt.prototype.sha256=ke(function(q){var J=rn(s._olm_sha256_length)(this.$b);q=qe(q);var oe=Ee(q),me=Ee(J+1);try{rn(s._olm_sha256)(this.$b,oe,q.length,me,J)}finally{for(Me(oe,q.length),oe=0;oe<q.length;oe++)q[oe]=0}return z(me,J)}),gt.prototype.ed25519_verify=ke(function(q,J,oe){q=qe(q);var me=Ee(q);J=qe(J);var Ie=Ee(J);oe=qe(oe);var He=Ee(oe);try{rn(s._olm_ed25519_verify)(this.$b,me,q.length,Ie,J.length,He,oe.length)}finally{for(Me(Ie,J.length),q=0;q<J.length;q++)J[q]=0}}),r.Account=tt,r.Session=Xe,r.Utility=gt,r.PkEncryption=O,r.PkDecryption=Y,r.PkSigning=ie,r.SAS=ve,r.get_library_version=ke(function(){var q=Ee(3);return s._olm_get_library_version(q,q+1,q+2),[ye(q,"i8"),ye(q+1,"i8"),ye(q+2,"i8")]}),v.ready}})();e.exports=a;var c;return r.init=function(f){return c||(f&&(OLM_OPTIONS=f),c=new Promise(function(v,s){i=function(){v()},o=function(g){s(g)},a()}),c)},r}();typeof window<"u"&&(window.Olm=n),e.exports=n;// @license-end
     92 })(rH);const UG=mm;function eo(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function ym(e,t){return ym=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(r,i){return r.__proto__=i,r},ym(e,t)}function Xf(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&ym(e,t)}function tc(e,t){if(t&&(mr(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return eo(e)}function Kr(e){return Kr=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(n){return n.__proto__||Object.getPrototypeOf(n)},Kr(e)}function iH(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function oH(e){return WC(e)||iH(e)||HC(e)||GC()}function XT(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),n.push.apply(n,r)}return n}function ZT(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?XT(Object(n),!0).forEach(function(r){Er(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):XT(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}var sH={type:"logger",log:function(t){this.output("log",t)},warn:function(t){this.output("warn",t)},error:function(t){this.output("error",t)},output:function(t,n){console&&console[t]&&console[t].apply(console,n)}},aH=function(){function e(t){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};tr(this,e),this.init(t,n)}return nr(e,[{key:"init",value:function(n){var r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};this.prefix=r.prefix||"i18next:",this.logger=n||sH,this.options=r,this.debug=r.debug}},{key:"setDebug",value:function(n){this.debug=n}},{key:"log",value:function(){for(var n=arguments.length,r=new Array(n),i=0;i<n;i++)r[i]=arguments[i];return this.forward(r,"log","",!0)}},{key:"warn",value:function(){for(var n=arguments.length,r=new Array(n),i=0;i<n;i++)r[i]=arguments[i];return this.forward(r,"warn","",!0)}},{key:"error",value:function(){for(var n=arguments.length,r=new Array(n),i=0;i<n;i++)r[i]=arguments[i];return this.forward(r,"error","")}},{key:"deprecate",value:function(){for(var n=arguments.length,r=new Array(n),i=0;i<n;i++)r[i]=arguments[i];return this.forward(r,"warn","WARNING DEPRECATED: ",!0)}},{key:"forward",value:function(n,r,i,o){return o&&!this.debug?null:(typeof n[0]=="string"&&(n[0]="".concat(i).concat(this.prefix," ").concat(n[0])),this.logger[r](n))}},{key:"create",value:function(n){return new e(this.logger,ZT(ZT({},{prefix:"".concat(this.prefix,":").concat(n,":")}),this.options))}},{key:"clone",value:function(n){return n=n||this.options,n.prefix=n.prefix||this.prefix,new e(this.logger,n)}}]),e}(),Ur=new aH,so=function(){function e(){tr(this,e),this.observers={}}return nr(e,[{key:"on",value:function(n,r){var i=this;return n.split(" ").forEach(function(o){i.observers[o]=i.observers[o]||[],i.observers[o].push(r)}),this}},{key:"off",value:function(n,r){if(this.observers[n]){if(!r){delete this.observers[n];return}this.observers[n]=this.observers[n].filter(function(i){return i!==r})}}},{key:"emit",value:function(n){for(var r=arguments.length,i=new Array(r>1?r-1:0),o=1;o<r;o++)i[o-1]=arguments[o];if(this.observers[n]){var a=[].concat(this.observers[n]);a.forEach(function(f){f.apply(void 0,i)})}if(this.observers["*"]){var c=[].concat(this.observers["*"]);c.forEach(function(f){f.apply(f,[n].concat(i))})}}}]),e}();function Cl(){var e,t,n=new Promise(function(r,i){e=r,t=i});return n.resolve=e,n.reject=t,n}function eR(e){return e==null?"":""+e}function lH(e,t,n){e.forEach(function(r){t[r]&&(n[r]=t[r])})}function g_(e,t,n){function r(c){return c&&c.indexOf("###")>-1?c.replace(/###/g,"."):c}function i(){return!e||typeof e=="string"}for(var o=typeof t!="string"?[].concat(t):t.split(".");o.length>1;){if(i())return{};var a=r(o.shift());!e[a]&&n&&(e[a]=new n),Object.prototype.hasOwnProperty.call(e,a)?e=e[a]:e={}}return i()?{}:{obj:e,k:r(o.shift())}}function tR(e,t,n){var r=g_(e,t,Object),i=r.obj,o=r.k;i[o]=n}function uH(e,t,n,r){var i=g_(e,t,Object),o=i.obj,a=i.k;o[a]=o[a]||[],r&&(o[a]=o[a].concat(n)),r||o[a].push(n)}function rf(e,t){var n=g_(e,t),r=n.obj,i=n.k;if(r)return r[i]}function nR(e,t,n){var r=rf(e,n);return r!==void 0?r:rf(t,n)}function Ik(e,t,n){for(var r in t)r!=="__proto__"&&r!=="constructor"&&(r in e?typeof e[r]=="string"||e[r]instanceof String||typeof t[r]=="string"||t[r]instanceof String?n&&(e[r]=t[r]):Ik(e[r],t[r],n):e[r]=t[r]);return e}function Ps(e){return e.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&")}var cH={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#x2F;"};function dH(e){return typeof e=="string"?e.replace(/[&<>"'\/]/g,function(t){return cH[t]}):e}var Zf=typeof window<"u"&&window.navigator&&typeof window.navigator.userAgentData>"u"&&window.navigator.userAgent&&window.navigator.userAgent.indexOf("MSIE")>-1,fH=[" ",",","?","!",";"];function hH(e,t,n){t=t||"",n=n||"";var r=fH.filter(function(c){return t.indexOf(c)<0&&n.indexOf(c)<0});if(r.length===0)return!0;var i=new RegExp("(".concat(r.map(function(c){return c==="?"?"\\?":c}).join("|"),")")),o=!i.test(e);if(!o){var a=e.indexOf(n);a>0&&!i.test(e.substring(0,a))&&(o=!0)}return o}function rR(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),n.push.apply(n,r)}return n}function Wc(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?rR(Object(n),!0).forEach(function(r){Er(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):rR(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function pH(e){var t=gH();return function(){var r=Kr(e),i;if(t){var o=Kr(this).constructor;i=Reflect.construct(r,arguments,o)}else i=r.apply(this,arguments);return tc(this,i)}}function gH(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}function Ck(e,t){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:".";if(e){if(e[t])return e[t];for(var r=t.split(n),i=e,o=0;o<r.length;++o){if(!i||typeof i[r[o]]=="string"&&o+1<r.length)return;if(i[r[o]]===void 0){for(var a=2,c=r.slice(o,o+a).join(n),f=i[c];f===void 0&&r.length>o+a;)a++,c=r.slice(o,o+a).join(n),f=i[c];if(f===void 0)return;if(f===null)return null;if(t.endsWith(c)){if(typeof f=="string")return f;if(c&&typeof f[c]=="string")return f[c]}var v=r.slice(o+a).join(n);return v?Ck(f,v,n):void 0}i=i[r[o]]}return i}}var vH=function(e){Xf(n,e);var t=pH(n);function n(r){var i,o=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{ns:["translation"],defaultNS:"translation"};return tr(this,n),i=t.call(this),Zf&&so.call(eo(i)),i.data=r||{},i.options=o,i.options.keySeparator===void 0&&(i.options.keySeparator="."),i.options.ignoreJSONStructure===void 0&&(i.options.ignoreJSONStructure=!0),i}return nr(n,[{key:"addNamespaces",value:function(i){this.options.ns.indexOf(i)<0&&this.options.ns.push(i)}},{key:"removeNamespaces",value:function(i){var o=this.options.ns.indexOf(i);o>-1&&this.options.ns.splice(o,1)}},{key:"getResource",value:function(i,o,a){var c=arguments.length>3&&arguments[3]!==void 0?arguments[3]:{},f=c.keySeparator!==void 0?c.keySeparator:this.options.keySeparator,v=c.ignoreJSONStructure!==void 0?c.ignoreJSONStructure:this.options.ignoreJSONStructure,s=[i,o];a&&typeof a!="string"&&(s=s.concat(a)),a&&typeof a=="string"&&(s=s.concat(f?a.split(f):a)),i.indexOf(".")>-1&&(s=i.split("."));var g=rf(this.data,s);return g||!v||typeof a!="string"?g:Ck(this.data&&this.data[i]&&this.data[i][o],a,f)}},{key:"addResource",value:function(i,o,a,c){var f=arguments.length>4&&arguments[4]!==void 0?arguments[4]:{silent:!1},v=this.options.keySeparator;v===void 0&&(v=".");var s=[i,o];a&&(s=s.concat(v?a.split(v):a)),i.indexOf(".")>-1&&(s=i.split("."),c=o,o=s[1]),this.addNamespaces(o),tR(this.data,s,c),f.silent||this.emit("added",i,o,a,c)}},{key:"addResources",value:function(i,o,a){var c=arguments.length>3&&arguments[3]!==void 0?arguments[3]:{silent:!1};for(var f in a)(typeof a[f]=="string"||Object.prototype.toString.apply(a[f])==="[object Array]")&&this.addResource(i,o,f,a[f],{silent:!0});c.silent||this.emit("added",i,o,a)}},{key:"addResourceBundle",value:function(i,o,a,c,f){var v=arguments.length>5&&arguments[5]!==void 0?arguments[5]:{silent:!1},s=[i,o];i.indexOf(".")>-1&&(s=i.split("."),c=a,a=o,o=s[1]),this.addNamespaces(o);var g=rf(this.data,s)||{};c?Ik(g,a,f):g=Wc(Wc({},g),a),tR(this.data,s,g),v.silent||this.emit("added",i,o,a)}},{key:"removeResourceBundle",value:function(i,o){this.hasResourceBundle(i,o)&&delete this.data[i][o],this.removeNamespaces(o),this.emit("removed",i,o)}},{key:"hasResourceBundle",value:function(i,o){return this.getResource(i,o)!==void 0}},{key:"getResourceBundle",value:function(i,o){return o||(o=this.options.defaultNS),this.options.compatibilityAPI==="v1"?Wc(Wc({},{}),this.getResource(i,o)):this.getResource(i,o)}},{key:"getDataByLanguage",value:function(i){return this.data[i]}},{key:"hasLanguageSomeTranslations",value:function(i){var o=this.getDataByLanguage(i),a=o&&Object.keys(o)||[];return!!a.find(function(c){return o[c]&&Object.keys(o[c]).length>0})}},{key:"toJSON",value:function(){return this.data}}]),n}(so),Ok={processors:{},addPostProcessor:function(t){this.processors[t.name]=t},handle:function(t,n,r,i,o){var a=this;return t.forEach(function(c){a.processors[c]&&(n=a.processors[c].process(n,r,i,o))}),n}};function iR(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),n.push.apply(n,r)}return n}function sn(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?iR(Object(n),!0).forEach(function(r){Er(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):iR(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function mH(e){var t=yH();return function(){var r=Kr(e),i;if(t){var o=Kr(this).constructor;i=Reflect.construct(r,arguments,o)}else i=r.apply(this,arguments);return tc(this,i)}}function yH(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}var oR={},sR=function(e){Xf(n,e);var t=mH(n);function n(r){var i,o=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return tr(this,n),i=t.call(this),Zf&&so.call(eo(i)),lH(["resourceStore","languageUtils","pluralResolver","interpolator","backendConnector","i18nFormat","utils"],r,eo(i)),i.options=o,i.options.keySeparator===void 0&&(i.options.keySeparator="."),i.logger=Ur.create("translator"),i}return nr(n,[{key:"changeLanguage",value:function(i){i&&(this.language=i)}},{key:"exists",value:function(i){var o=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{interpolation:{}};if(i==null)return!1;var a=this.resolve(i,o);return a&&a.res!==void 0}},{key:"extractFromKey",value:function(i,o){var a=o.nsSeparator!==void 0?o.nsSeparator:this.options.nsSeparator;a===void 0&&(a=":");var c=o.keySeparator!==void 0?o.keySeparator:this.options.keySeparator,f=o.ns||this.options.defaultNS||[],v=a&&i.indexOf(a)>-1,s=!this.options.userDefinedKeySeparator&&!o.keySeparator&&!this.options.userDefinedNsSeparator&&!o.nsSeparator&&!hH(i,a,c);if(v&&!s){var g=i.match(this.interpolator.nestingRegexp);if(g&&g.length>0)return{key:i,namespaces:f};var y=i.split(a);(a!==c||a===c&&this.options.ns.indexOf(y[0])>-1)&&(f=y.shift()),i=y.join(c)}return typeof f=="string"&&(f=[f]),{key:i,namespaces:f}}},{key:"translate",value:function(i,o,a){var c=this;if(mr(o)!=="object"&&this.options.overloadTranslationOptionHandler&&(o=this.options.overloadTranslationOptionHandler(arguments)),o||(o={}),i==null)return"";Array.isArray(i)||(i=[String(i)]);var f=o.returnDetails!==void 0?o.returnDetails:this.options.returnDetails,v=o.keySeparator!==void 0?o.keySeparator:this.options.keySeparator,s=this.extractFromKey(i[i.length-1],o),g=s.key,y=s.namespaces,S=y[y.length-1],m=o.lng||this.language,p=o.appendNamespaceToCIMode||this.options.appendNamespaceToCIMode;if(m&&m.toLowerCase()==="cimode"){if(p){var _=o.nsSeparator||this.options.nsSeparator;return f?(u.res="".concat(S).concat(_).concat(g),u):"".concat(S).concat(_).concat(g)}return f?(u.res=g,u):g}var u=this.resolve(i,o),l=u&&u.res,d=u&&u.usedKey||g,h=u&&u.exactUsedKey||g,w=Object.prototype.toString.apply(l),E=["[object Number]","[object Function]","[object RegExp]"],I=o.joinArrays!==void 0?o.joinArrays:this.options.joinArrays,k=!this.i18nFormat||this.i18nFormat.handleAsObject,M=typeof l!="string"&&typeof l!="boolean"&&typeof l!="number";if(k&&l&&M&&E.indexOf(w)<0&&!(typeof I=="string"&&w==="[object Array]")){if(!o.returnObjects&&!this.options.returnObjects){this.options.returnedObjectHandler||this.logger.warn("accessing an object - but returnObjects options is not enabled!");var L=this.options.returnedObjectHandler?this.options.returnedObjectHandler(d,l,sn(sn({},o),{},{ns:y})):"key '".concat(g," (").concat(this.language,")' returned an object instead of string.");return f?(u.res=L,u):L}if(v){var B=w==="[object Array]",N=B?[]:{},G=B?h:d;for(var D in l)if(Object.prototype.hasOwnProperty.call(l,D)){var x="".concat(G).concat(v).concat(D);N[D]=this.translate(x,sn(sn({},o),{joinArrays:!1,ns:y})),N[D]===x&&(N[D]=l[D])}l=N}}else if(k&&typeof I=="string"&&w==="[object Array]")l=l.join(I),l&&(l=this.extendTranslation(l,i,o,a));else{var z=!1,W=!1,F=o.count!==void 0&&typeof o.count!="string",H=n.hasDefaultValue(o),R=F?this.pluralResolver.getSuffix(m,o.count,o):"",P=o["defaultValue".concat(R)]||o.defaultValue;!this.isValidLookup(l)&&H&&(z=!0,l=P),this.isValidLookup(l)||(W=!0,l=g);var K=o.missingKeyNoValueFallbackToKey||this.options.missingKeyNoValueFallbackToKey,U=K&&W?void 0:l,C=H&&P!==l&&this.options.updateMissing;if(W||z||C){if(this.logger.log(C?"updateKey":"missingKey",m,S,g,C?P:l),v){var A=this.resolve(g,sn(sn({},o),{},{keySeparator:!1}));A&&A.res&&this.logger.warn("Seems the loaded translations were in flat JSON format instead of nested. Either set keySeparator: false on init or make sure your translations are published in nested format.")}var T=[],X=this.languageUtils.getFallbackCodes(this.options.fallbackLng,o.lng||this.language);if(this.options.saveMissingTo==="fallback"&&X&&X[0])for(var ne=0;ne<X.length;ne++)T.push(X[ne]);else this.options.saveMissingTo==="all"?T=this.languageUtils.toResolveHierarchy(o.lng||this.language):T.push(o.lng||this.language);var ae=function(V,se,Q){var j=H&&Q!==l?Q:U;c.options.missingKeyHandler?c.options.missingKeyHandler(V,S,se,j,C,o):c.backendConnector&&c.backendConnector.saveMissing&&c.backendConnector.saveMissing(V,S,se,j,C,o),c.emit("missingKey",V,S,se,l)};this.options.saveMissing&&(this.options.saveMissingPlurals&&F?T.forEach(function(pe){c.pluralResolver.getSuffixes(pe,o).forEach(function(V){ae([pe],g+V,o["defaultValue".concat(V)]||P)})}):ae(T,g,P))}l=this.extendTranslation(l,i,o,u,a),W&&l===g&&this.options.appendNamespaceToMissingKey&&(l="".concat(S,":").concat(g)),(W||z)&&this.options.parseMissingKeyHandler&&(this.options.compatibilityAPI!=="v1"?l=this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey?"".concat(S,":").concat(g):g,z?l:void 0):l=this.options.parseMissingKeyHandler(l))}return f?(u.res=l,u):l}},{key:"extendTranslation",value:function(i,o,a,c,f){var v=this;if(this.i18nFormat&&this.i18nFormat.parse)i=this.i18nFormat.parse(i,sn(sn({},this.options.interpolation.defaultVariables),a),c.usedLng,c.usedNS,c.usedKey,{resolved:c});else if(!a.skipInterpolation){a.interpolation&&this.interpolator.init(sn(sn({},a),{interpolation:sn(sn({},this.options.interpolation),a.interpolation)}));var s=typeof i=="string"&&(a&&a.interpolation&&a.interpolation.skipOnVariables!==void 0?a.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables),g;if(s){var y=i.match(this.interpolator.nestingRegexp);g=y&&y.length}var S=a.replace&&typeof a.replace!="string"?a.replace:a;if(this.options.interpolation.defaultVariables&&(S=sn(sn({},this.options.interpolation.defaultVariables),S)),i=this.interpolator.interpolate(i,S,a.lng||this.language,a),s){var m=i.match(this.interpolator.nestingRegexp),p=m&&m.length;g<p&&(a.nest=!1)}a.nest!==!1&&(i=this.interpolator.nest(i,function(){for(var l=arguments.length,d=new Array(l),h=0;h<l;h++)d[h]=arguments[h];return f&&f[0]===d[0]&&!a.context?(v.logger.warn("It seems you are nesting recursively key: ".concat(d[0]," in key: ").concat(o[0])),null):v.translate.apply(v,d.concat([o]))},a)),a.interpolation&&this.interpolator.reset()}var _=a.postProcess||this.options.postProcess,u=typeof _=="string"?[_]:_;return i!=null&&u&&u.length&&a.applyPostProcessor!==!1&&(i=Ok.handle(u,i,o,this.options&&this.options.postProcessPassResolved?sn({i18nResolved:c},a):a,this)),i}},{key:"resolve",value:function(i){var o=this,a=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},c,f,v,s,g;return typeof i=="string"&&(i=[i]),i.forEach(function(y){if(!o.isValidLookup(c)){var S=o.extractFromKey(y,a),m=S.key;f=m;var p=S.namespaces;o.options.fallbackNS&&(p=p.concat(o.options.fallbackNS));var _=a.count!==void 0&&typeof a.count!="string",u=_&&!a.ordinal&&a.count===0&&o.pluralResolver.shouldUseIntlApi(),l=a.context!==void 0&&(typeof a.context=="string"||typeof a.context=="number")&&a.context!=="",d=a.lngs?a.lngs:o.languageUtils.toResolveHierarchy(a.lng||o.language,a.fallbackLng);p.forEach(function(h){o.isValidLookup(c)||(g=h,!oR["".concat(d[0],"-").concat(h)]&&o.utils&&o.utils.hasLoadedNamespace&&!o.utils.hasLoadedNamespace(g)&&(oR["".concat(d[0],"-").concat(h)]=!0,o.logger.warn('key "'.concat(f,'" for languages "').concat(d.join(", "),`" won't get resolved as namespace "`).concat(g,'" was not yet loaded'),"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!")),d.forEach(function(w){if(!o.isValidLookup(c)){s=w;var E=[m];if(o.i18nFormat&&o.i18nFormat.addLookupKeys)o.i18nFormat.addLookupKeys(E,m,w,h,a);else{var I;_&&(I=o.pluralResolver.getSuffix(w,a.count,a));var k="".concat(o.options.pluralSeparator,"zero");if(_&&(E.push(m+I),u&&E.push(m+k)),l){var M="".concat(m).concat(o.options.contextSeparator).concat(a.context);E.push(M),_&&(E.push(M+I),u&&E.push(M+k))}}for(var L;L=E.pop();)o.isValidLookup(c)||(v=L,c=o.getResource(w,h,L,a))}}))})}}),{res:c,usedKey:f,exactUsedKey:v,usedLng:s,usedNS:g}}},{key:"isValidLookup",value:function(i){return i!==void 0&&!(!this.options.returnNull&&i===null)&&!(!this.options.returnEmptyString&&i==="")}},{key:"getResource",value:function(i,o,a){var c=arguments.length>3&&arguments[3]!==void 0?arguments[3]:{};return this.i18nFormat&&this.i18nFormat.getResource?this.i18nFormat.getResource(i,o,a,c):this.resourceStore.getResource(i,o,a,c)}}],[{key:"hasDefaultValue",value:function(i){var o="defaultValue";for(var a in i)if(Object.prototype.hasOwnProperty.call(i,a)&&o===a.substring(0,o.length)&&i[a]!==void 0)return!0;return!1}}]),n}(so);function ug(e){return e.charAt(0).toUpperCase()+e.slice(1)}var aR=function(){function e(t){tr(this,e),this.options=t,this.supportedLngs=this.options.supportedLngs||!1,this.logger=Ur.create("languageUtils")}return nr(e,[{key:"getScriptPartFromCode",value:function(n){if(!n||n.indexOf("-")<0)return null;var r=n.split("-");return r.length===2||(r.pop(),r[r.length-1].toLowerCase()==="x")?null:this.formatLanguageCode(r.join("-"))}},{key:"getLanguagePartFromCode",value:function(n){if(!n||n.indexOf("-")<0)return n;var r=n.split("-");return this.formatLanguageCode(r[0])}},{key:"formatLanguageCode",value:function(n){if(typeof n=="string"&&n.indexOf("-")>-1){var r=["hans","hant","latn","cyrl","cans","mong","arab"],i=n.split("-");return this.options.lowerCaseLng?i=i.map(function(o){return o.toLowerCase()}):i.length===2?(i[0]=i[0].toLowerCase(),i[1]=i[1].toUpperCase(),r.indexOf(i[1].toLowerCase())>-1&&(i[1]=ug(i[1].toLowerCase()))):i.length===3&&(i[0]=i[0].toLowerCase(),i[1].length===2&&(i[1]=i[1].toUpperCase()),i[0]!=="sgn"&&i[2].length===2&&(i[2]=i[2].toUpperCase()),r.indexOf(i[1].toLowerCase())>-1&&(i[1]=ug(i[1].toLowerCase())),r.indexOf(i[2].toLowerCase())>-1&&(i[2]=ug(i[2].toLowerCase()))),i.join("-")}return this.options.cleanCode||this.options.lowerCaseLng?n.toLowerCase():n}},{key:"isSupportedCode",value:function(n){return(this.options.load==="languageOnly"||this.options.nonExplicitSupportedLngs)&&(n=this.getLanguagePartFromCode(n)),!this.supportedLngs||!this.supportedLngs.length||this.supportedLngs.indexOf(n)>-1}},{key:"getBestMatchFromCodes",value:function(n){var r=this;if(!n)return null;var i;return n.forEach(function(o){if(!i){var a=r.formatLanguageCode(o);(!r.options.supportedLngs||r.isSupportedCode(a))&&(i=a)}}),!i&&this.options.supportedLngs&&n.forEach(function(o){if(!i){var a=r.getLanguagePartFromCode(o);if(r.isSupportedCode(a))return i=a;i=r.options.supportedLngs.find(function(c){if(c.indexOf(a)===0)return c})}}),i||(i=this.getFallbackCodes(this.options.fallbackLng)[0]),i}},{key:"getFallbackCodes",value:function(n,r){if(!n)return[];if(typeof n=="function"&&(n=n(r)),typeof n=="string"&&(n=[n]),Object.prototype.toString.apply(n)==="[object Array]")return n;if(!r)return n.default||[];var i=n[r];return i||(i=n[this.getScriptPartFromCode(r)]),i||(i=n[this.formatLanguageCode(r)]),i||(i=n[this.getLanguagePartFromCode(r)]),i||(i=n.default),i||[]}},{key:"toResolveHierarchy",value:function(n,r){var i=this,o=this.getFallbackCodes(r||this.options.fallbackLng||[],n),a=[],c=function(v){v&&(i.isSupportedCode(v)?a.push(v):i.logger.warn("rejecting language code not found in supportedLngs: ".concat(v)))};return typeof n=="string"&&n.indexOf("-")>-1?(this.options.load!=="languageOnly"&&c(this.formatLanguageCode(n)),this.options.load!=="languageOnly"&&this.options.load!=="currentOnly"&&c(this.getScriptPartFromCode(n)),this.options.load!=="currentOnly"&&c(this.getLanguagePartFromCode(n))):typeof n=="string"&&c(this.formatLanguageCode(n)),o.forEach(function(f){a.indexOf(f)<0&&c(i.formatLanguageCode(f))}),a}}]),e}(),_H=[{lngs:["ach","ak","am","arn","br","fil","gun","ln","mfe","mg","mi","oc","pt","pt-BR","tg","tl","ti","tr","uz","wa"],nr:[1,2],fc:1},{lngs:["af","an","ast","az","bg","bn","ca","da","de","dev","el","en","eo","es","et","eu","fi","fo","fur","fy","gl","gu","ha","hi","hu","hy","ia","it","kk","kn","ku","lb","mai","ml","mn","mr","nah","nap","nb","ne","nl","nn","no","nso","pa","pap","pms","ps","pt-PT","rm","sco","se","si","so","son","sq","sv","sw","ta","te","tk","ur","yo"],nr:[1,2],fc:2},{lngs:["ay","bo","cgg","fa","ht","id","ja","jbo","ka","km","ko","ky","lo","ms","sah","su","th","tt","ug","vi","wo","zh"],nr:[1],fc:3},{lngs:["be","bs","cnr","dz","hr","ru","sr","uk"],nr:[1,2,5],fc:4},{lngs:["ar"],nr:[0,1,2,3,11,100],fc:5},{lngs:["cs","sk"],nr:[1,2,5],fc:6},{lngs:["csb","pl"],nr:[1,2,5],fc:7},{lngs:["cy"],nr:[1,2,3,8],fc:8},{lngs:["fr"],nr:[1,2],fc:9},{lngs:["ga"],nr:[1,2,3,7,11],fc:10},{lngs:["gd"],nr:[1,2,3,20],fc:11},{lngs:["is"],nr:[1,2],fc:12},{lngs:["jv"],nr:[0,1],fc:13},{lngs:["kw"],nr:[1,2,3,4],fc:14},{lngs:["lt"],nr:[1,2,10],fc:15},{lngs:["lv"],nr:[1,2,0],fc:16},{lngs:["mk"],nr:[1,2],fc:17},{lngs:["mnk"],nr:[0,1,2],fc:18},{lngs:["mt"],nr:[1,2,11,20],fc:19},{lngs:["or"],nr:[2,1],fc:2},{lngs:["ro"],nr:[1,2,20],fc:20},{lngs:["sl"],nr:[5,1,2,3],fc:21},{lngs:["he","iw"],nr:[1,2,20,21],fc:22}],SH={1:function(t){return Number(t>1)},2:function(t){return Number(t!=1)},3:function(t){return 0},4:function(t){return Number(t%10==1&&t%100!=11?0:t%10>=2&&t%10<=4&&(t%100<10||t%100>=20)?1:2)},5:function(t){return Number(t==0?0:t==1?1:t==2?2:t%100>=3&&t%100<=10?3:t%100>=11?4:5)},6:function(t){return Number(t==1?0:t>=2&&t<=4?1:2)},7:function(t){return Number(t==1?0:t%10>=2&&t%10<=4&&(t%100<10||t%100>=20)?1:2)},8:function(t){return Number(t==1?0:t==2?1:t!=8&&t!=11?2:3)},9:function(t){return Number(t>=2)},10:function(t){return Number(t==1?0:t==2?1:t<7?2:t<11?3:4)},11:function(t){return Number(t==1||t==11?0:t==2||t==12?1:t>2&&t<20?2:3)},12:function(t){return Number(t%10!=1||t%100==11)},13:function(t){return Number(t!==0)},14:function(t){return Number(t==1?0:t==2?1:t==3?2:3)},15:function(t){return Number(t%10==1&&t%100!=11?0:t%10>=2&&(t%100<10||t%100>=20)?1:2)},16:function(t){return Number(t%10==1&&t%100!=11?0:t!==0?1:2)},17:function(t){return Number(t==1||t%10==1&&t%100!=11?0:1)},18:function(t){return Number(t==0?0:t==1?1:2)},19:function(t){return Number(t==1?0:t==0||t%100>1&&t%100<11?1:t%100>10&&t%100<20?2:3)},20:function(t){return Number(t==1?0:t==0||t%100>0&&t%100<20?1:2)},21:function(t){return Number(t%100==1?1:t%100==2?2:t%100==3||t%100==4?3:0)},22:function(t){return Number(t==1?0:t==2?1:(t<0||t>10)&&t%10==0?2:3)}},EH=["v1","v2","v3"],lR={zero:0,one:1,two:2,few:3,many:4,other:5};function wH(){var e={};return _H.forEach(function(t){t.lngs.forEach(function(n){e[n]={numbers:t.nr,plurals:SH[t.fc]}})}),e}var bH=function(){function e(t){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};tr(this,e),this.languageUtils=t,this.options=n,this.logger=Ur.create("pluralResolver"),(!this.options.compatibilityJSON||this.options.compatibilityJSON==="v4")&&(typeof Intl>"u"||!Intl.PluralRules)&&(this.options.compatibilityJSON="v3",this.logger.error("Your environment seems not to be Intl API compatible, use an Intl.PluralRules polyfill. Will fallback to the compatibilityJSON v3 format handling.")),this.rules=wH()}return nr(e,[{key:"addRule",value:function(n,r){this.rules[n]=r}},{key:"getRule",value:function(n){var r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(this.shouldUseIntlApi())try{return new Intl.PluralRules(n,{type:r.ordinal?"ordinal":"cardinal"})}catch{return}return this.rules[n]||this.rules[this.languageUtils.getLanguagePartFromCode(n)]}},{key:"needsPlural",value:function(n){var r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},i=this.getRule(n,r);return this.shouldUseIntlApi()?i&&i.resolvedOptions().pluralCategories.length>1:i&&i.numbers.length>1}},{key:"getPluralFormsOfKey",value:function(n,r){var i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return this.getSuffixes(n,i).map(function(o){return"".concat(r).concat(o)})}},{key:"getSuffixes",value:function(n){var r=this,i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},o=this.getRule(n,i);return o?this.shouldUseIntlApi()?o.resolvedOptions().pluralCategories.sort(function(a,c){return lR[a]-lR[c]}).map(function(a){return"".concat(r.options.prepend).concat(a)}):o.numbers.map(function(a){return r.getSuffix(n,a,i)}):[]}},{key:"getSuffix",value:function(n,r){var i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},o=this.getRule(n,i);return o?this.shouldUseIntlApi()?"".concat(this.options.prepend).concat(o.select(r)):this.getSuffixRetroCompatible(o,r):(this.logger.warn("no plural rule found for: ".concat(n)),"")}},{key:"getSuffixRetroCompatible",value:function(n,r){var i=this,o=n.noAbs?n.plurals(r):n.plurals(Math.abs(r)),a=n.numbers[o];this.options.simplifyPluralSuffix&&n.numbers.length===2&&n.numbers[0]===1&&(a===2?a="plural":a===1&&(a=""));var c=function(){return i.options.prepend&&a.toString()?i.options.prepend+a.toString():a.toString()};return this.options.compatibilityJSON==="v1"?a===1?"":typeof a=="number"?"_plural_".concat(a.toString()):c():this.options.compatibilityJSON==="v2"||this.options.simplifyPluralSuffix&&n.numbers.length===2&&n.numbers[0]===1?c():this.options.prepend&&o.toString()?this.options.prepend+o.toString():o.toString()}},{key:"shouldUseIntlApi",value:function(){return!EH.includes(this.options.compatibilityJSON)}}]),e}();function uR(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),n.push.apply(n,r)}return n}function cr(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?uR(Object(n),!0).forEach(function(r){Er(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):uR(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}var TH=function(){function e(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};tr(this,e),this.logger=Ur.create("interpolator"),this.options=t,this.format=t.interpolation&&t.interpolation.format||function(n){return n},this.init(t)}return nr(e,[{key:"init",value:function(){var n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};n.interpolation||(n.interpolation={escapeValue:!0});var r=n.interpolation;this.escape=r.escape!==void 0?r.escape:dH,this.escapeValue=r.escapeValue!==void 0?r.escapeValue:!0,this.useRawValueToEscape=r.useRawValueToEscape!==void 0?r.useRawValueToEscape:!1,this.prefix=r.prefix?Ps(r.prefix):r.prefixEscaped||"{{",this.suffix=r.suffix?Ps(r.suffix):r.suffixEscaped||"}}",this.formatSeparator=r.formatSeparator?r.formatSeparator:r.formatSeparator||",",this.unescapePrefix=r.unescapeSuffix?"":r.unescapePrefix||"-",this.unescapeSuffix=this.unescapePrefix?"":r.unescapeSuffix||"",this.nestingPrefix=r.nestingPrefix?Ps(r.nestingPrefix):r.nestingPrefixEscaped||Ps("$t("),this.nestingSuffix=r.nestingSuffix?Ps(r.nestingSuffix):r.nestingSuffixEscaped||Ps(")"),this.nestingOptionsSeparator=r.nestingOptionsSeparator?r.nestingOptionsSeparator:r.nestingOptionsSeparator||",",this.maxReplaces=r.maxReplaces?r.maxReplaces:1e3,this.alwaysFormat=r.alwaysFormat!==void 0?r.alwaysFormat:!1,this.resetRegExp()}},{key:"reset",value:function(){this.options&&this.init(this.options)}},{key:"resetRegExp",value:function(){var n="".concat(this.prefix,"(.+?)").concat(this.suffix);this.regexp=new RegExp(n,"g");var r="".concat(this.prefix).concat(this.unescapePrefix,"(.+?)").concat(this.unescapeSuffix).concat(this.suffix);this.regexpUnescape=new RegExp(r,"g");var i="".concat(this.nestingPrefix,"(.+?)").concat(this.nestingSuffix);this.nestingRegexp=new RegExp(i,"g")}},{key:"interpolate",value:function(n,r,i,o){var a=this,c,f,v,s=this.options&&this.options.interpolation&&this.options.interpolation.defaultVariables||{};function g(_){return _.replace(/\$/g,"$$$$")}var y=function(u){if(u.indexOf(a.formatSeparator)<0){var l=nR(r,s,u);return a.alwaysFormat?a.format(l,void 0,i,cr(cr(cr({},o),r),{},{interpolationkey:u})):l}var d=u.split(a.formatSeparator),h=d.shift().trim(),w=d.join(a.formatSeparator).trim();return a.format(nR(r,s,h),w,i,cr(cr(cr({},o),r),{},{interpolationkey:h}))};this.resetRegExp();var S=o&&o.missingInterpolationHandler||this.options.missingInterpolationHandler,m=o&&o.interpolation&&o.interpolation.skipOnVariables!==void 0?o.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables,p=[{regex:this.regexpUnescape,safeValue:function(u){return g(u)}},{regex:this.regexp,safeValue:function(u){return a.escapeValue?g(a.escape(u)):g(u)}}];return p.forEach(function(_){for(v=0;c=_.regex.exec(n);){var u=c[1].trim();if(f=y(u),f===void 0)if(typeof S=="function"){var l=S(n,c,o);f=typeof l=="string"?l:""}else if(o&&o.hasOwnProperty(u))f="";else if(m){f=c[0];continue}else a.logger.warn("missed to pass in variable ".concat(u," for interpolating ").concat(n)),f="";else typeof f!="string"&&!a.useRawValueToEscape&&(f=eR(f));var d=_.safeValue(f);if(n=n.replace(c[0],d),m?(_.regex.lastIndex+=f.length,_.regex.lastIndex-=c[0].length):_.regex.lastIndex=0,v++,v>=a.maxReplaces)break}}),n}},{key:"nest",value:function(n,r){var i=this,o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},a,c,f;function v(S,m){var p=this.nestingOptionsSeparator;if(S.indexOf(p)<0)return S;var _=S.split(new RegExp("".concat(p,"[ ]*{"))),u="{".concat(_[1]);S=_[0],u=this.interpolate(u,f);var l=u.match(/'/g),d=u.match(/"/g);(l&&l.length%2===0&&!d||d.length%2!==0)&&(u=u.replace(/'/g,'"'));try{f=JSON.parse(u),m&&(f=cr(cr({},m),f))}catch(h){return this.logger.warn("failed parsing options string in nesting for key ".concat(S),h),"".concat(S).concat(p).concat(u)}return delete f.defaultValue,S}for(;a=this.nestingRegexp.exec(n);){var s=[];f=cr({},o),f=f.replace&&typeof f.replace!="string"?f.replace:f,f.applyPostProcessor=!1,delete f.defaultValue;var g=!1;if(a[0].indexOf(this.formatSeparator)!==-1&&!/{.*}/.test(a[1])){var y=a[1].split(this.formatSeparator).map(function(S){return S.trim()});a[1]=y.shift(),s=y,g=!0}if(c=r(v.call(this,a[1].trim(),f),f),c&&a[0]===n&&typeof c!="string")return c;typeof c!="string"&&(c=eR(c)),c||(this.logger.warn("missed to resolve ".concat(a[1]," for nesting ").concat(n)),c=""),g&&(c=s.reduce(function(S,m){return i.format(S,m,o.lng,cr(cr({},o),{},{interpolationkey:a[1].trim()}))},c.trim())),n=n.replace(a[0],c),this.regexp.lastIndex=0}return n}}]),e}();function cR(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),n.push.apply(n,r)}return n}function Mi(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?cR(Object(n),!0).forEach(function(r){Er(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):cR(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function RH(e){var t=e.toLowerCase().trim(),n={};if(e.indexOf("(")>-1){var r=e.split("(");t=r[0].toLowerCase().trim();var i=r[1].substring(0,r[1].length-1);if(t==="currency"&&i.indexOf(":")<0)n.currency||(n.currency=i.trim());else if(t==="relativetime"&&i.indexOf(":")<0)n.range||(n.range=i.trim());else{var o=i.split(";");o.forEach(function(a){if(a){var c=a.split(":"),f=oH(c),v=f[0],s=f.slice(1),g=s.join(":").trim().replace(/^'+|'+$/g,"");n[v.trim()]||(n[v.trim()]=g),g==="false"&&(n[v.trim()]=!1),g==="true"&&(n[v.trim()]=!0),isNaN(g)||(n[v.trim()]=parseInt(g,10))}})}}return{formatName:t,formatOptions:n}}function ks(e){var t={};return function(r,i,o){var a=i+JSON.stringify(o),c=t[a];return c||(c=e(i,o),t[a]=c),c(r)}}var IH=function(){function e(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};tr(this,e),this.logger=Ur.create("formatter"),this.options=t,this.formats={number:ks(function(n,r){var i=new Intl.NumberFormat(n,r);return function(o){return i.format(o)}}),currency:ks(function(n,r){var i=new Intl.NumberFormat(n,Mi(Mi({},r),{},{style:"currency"}));return function(o){return i.format(o)}}),datetime:ks(function(n,r){var i=new Intl.DateTimeFormat(n,Mi({},r));return function(o){return i.format(o)}}),relativetime:ks(function(n,r){var i=new Intl.RelativeTimeFormat(n,Mi({},r));return function(o){return i.format(o,r.range||"day")}}),list:ks(function(n,r){var i=new Intl.ListFormat(n,Mi({},r));return function(o){return i.format(o)}})},this.init(t)}return nr(e,[{key:"init",value:function(n){var r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{interpolation:{}},i=r.interpolation;this.formatSeparator=i.formatSeparator?i.formatSeparator:i.formatSeparator||","}},{key:"add",value:function(n,r){this.formats[n.toLowerCase().trim()]=r}},{key:"addCached",value:function(n,r){this.formats[n.toLowerCase().trim()]=ks(r)}},{key:"format",value:function(n,r,i,o){var a=this,c=r.split(this.formatSeparator),f=c.reduce(function(v,s){var g=RH(s),y=g.formatName,S=g.formatOptions;if(a.formats[y]){var m=v;try{var p=o&&o.formatParams&&o.formatParams[o.interpolationkey]||{},_=p.locale||p.lng||o.locale||o.lng||i;m=a.formats[y](v,_,Mi(Mi(Mi({},S),o),p))}catch(u){a.logger.warn(u)}return m}else a.logger.warn("there was no format function for ".concat(y));return v},n);return f}}]),e}();function dR(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),n.push.apply(n,r)}return n}function fR(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?dR(Object(n),!0).forEach(function(r){Er(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):dR(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function CH(e){var t=OH();return function(){var r=Kr(e),i;if(t){var o=Kr(this).constructor;i=Reflect.construct(r,arguments,o)}else i=r.apply(this,arguments);return tc(this,i)}}function OH(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}function PH(e,t){e.pending[t]!==void 0&&(delete e.pending[t],e.pendingCount--)}var kH=function(e){Xf(n,e);var t=CH(n);function n(r,i,o){var a,c=arguments.length>3&&arguments[3]!==void 0?arguments[3]:{};return tr(this,n),a=t.call(this),Zf&&so.call(eo(a)),a.backend=r,a.store=i,a.services=o,a.languageUtils=o.languageUtils,a.options=c,a.logger=Ur.create("backendConnector"),a.waitingReads=[],a.maxParallelReads=c.maxParallelReads||10,a.readingCalls=0,a.maxRetries=c.maxRetries>=0?c.maxRetries:5,a.retryTimeout=c.retryTimeout>=1?c.retryTimeout:350,a.state={},a.queue=[],a.backend&&a.backend.init&&a.backend.init(o,c.backend,c),a}return nr(n,[{key:"queueLoad",value:function(i,o,a,c){var f=this,v={},s={},g={},y={};return i.forEach(function(S){var m=!0;o.forEach(function(p){var _="".concat(S,"|").concat(p);!a.reload&&f.store.hasResourceBundle(S,p)?f.state[_]=2:f.state[_]<0||(f.state[_]===1?s[_]===void 0&&(s[_]=!0):(f.state[_]=1,m=!1,s[_]===void 0&&(s[_]=!0),v[_]===void 0&&(v[_]=!0),y[p]===void 0&&(y[p]=!0)))}),m||(g[S]=!0)}),(Object.keys(v).length||Object.keys(s).length)&&this.queue.push({pending:s,pendingCount:Object.keys(s).length,loaded:{},errors:[],callback:c}),{toLoad:Object.keys(v),pending:Object.keys(s),toLoadLanguages:Object.keys(g),toLoadNamespaces:Object.keys(y)}}},{key:"loaded",value:function(i,o,a){var c=i.split("|"),f=c[0],v=c[1];o&&this.emit("failedLoading",f,v,o),a&&this.store.addResourceBundle(f,v,a),this.state[i]=o?-1:2;var s={};this.queue.forEach(function(g){uH(g.loaded,[f],v),PH(g,i),o&&g.errors.push(o),g.pendingCount===0&&!g.done&&(Object.keys(g.loaded).forEach(function(y){s[y]||(s[y]={});var S=g.loaded[y];S.length&&S.forEach(function(m){s[y][m]===void 0&&(s[y][m]=!0)})}),g.done=!0,g.errors.length?g.callback(g.errors):g.callback())}),this.emit("loaded",s),this.queue=this.queue.filter(function(g){return!g.done})}},{key:"read",value:function(i,o,a){var c=this,f=arguments.length>3&&arguments[3]!==void 0?arguments[3]:0,v=arguments.length>4&&arguments[4]!==void 0?arguments[4]:this.retryTimeout,s=arguments.length>5?arguments[5]:void 0;if(!i.length)return s(null,{});if(this.readingCalls>=this.maxParallelReads){this.waitingReads.push({lng:i,ns:o,fcName:a,tried:f,wait:v,callback:s});return}this.readingCalls++;var g=function(p,_){if(c.readingCalls--,c.waitingReads.length>0){var u=c.waitingReads.shift();c.read(u.lng,u.ns,u.fcName,u.tried,u.wait,u.callback)}if(p&&_&&f<c.maxRetries){setTimeout(function(){c.read.call(c,i,o,a,f+1,v*2,s)},v);return}s(p,_)},y=this.backend[a].bind(this.backend);if(y.length===2){try{var S=y(i,o);S&&typeof S.then=="function"?S.then(function(m){return g(null,m)}).catch(g):g(null,S)}catch(m){g(m)}return}return y(i,o,g)}},{key:"prepareLoading",value:function(i,o){var a=this,c=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},f=arguments.length>3?arguments[3]:void 0;if(!this.backend)return this.logger.warn("No backend was added via i18next.use. Will not load resources."),f&&f();typeof i=="string"&&(i=this.languageUtils.toResolveHierarchy(i)),typeof o=="string"&&(o=[o]);var v=this.queueLoad(i,o,c,f);if(!v.toLoad.length)return v.pending.length||f(),null;v.toLoad.forEach(function(s){a.loadOne(s)})}},{key:"load",value:function(i,o,a){this.prepareLoading(i,o,{},a)}},{key:"reload",value:function(i,o,a){this.prepareLoading(i,o,{reload:!0},a)}},{key:"loadOne",value:function(i){var o=this,a=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"",c=i.split("|"),f=c[0],v=c[1];this.read(f,v,"read",void 0,void 0,function(s,g){s&&o.logger.warn("".concat(a,"loading namespace ").concat(v," for language ").concat(f," failed"),s),!s&&g&&o.logger.log("".concat(a,"loaded namespace ").concat(v," for language ").concat(f),g),o.loaded(i,s,g)})}},{key:"saveMissing",value:function(i,o,a,c,f){var v=arguments.length>5&&arguments[5]!==void 0?arguments[5]:{},s=arguments.length>6&&arguments[6]!==void 0?arguments[6]:function(){};if(this.services.utils&&this.services.utils.hasLoadedNamespace&&!this.services.utils.hasLoadedNamespace(o)){this.logger.warn('did not save key "'.concat(a,'" as the namespace "').concat(o,'" was not yet loaded'),"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!");return}if(!(a==null||a==="")){if(this.backend&&this.backend.create){var g=fR(fR({},v),{},{isUpdate:f}),y=this.backend.create.bind(this.backend);if(y.length<6)try{var S;y.length===5?S=y(i,o,a,c,g):S=y(i,o,a,c),S&&typeof S.then=="function"?S.then(function(m){return s(null,m)}).catch(s):s(null,S)}catch(m){s(m)}else y(i,o,a,c,s,g)}!i||!i[0]||this.store.addResource(i[0],o,a,c)}}}]),n}(so);function hR(){return{debug:!1,initImmediate:!0,ns:["translation"],defaultNS:["translation"],fallbackLng:["dev"],fallbackNS:!1,supportedLngs:!1,nonExplicitSupportedLngs:!1,load:"all",preload:!1,simplifyPluralSuffix:!0,keySeparator:".",nsSeparator:":",pluralSeparator:"_",contextSeparator:"_",partialBundledLanguages:!1,saveMissing:!1,updateMissing:!1,saveMissingTo:"fallback",saveMissingPlurals:!0,missingKeyHandler:!1,missingInterpolationHandler:!1,postProcess:!1,postProcessPassResolved:!1,returnNull:!0,returnEmptyString:!0,returnObjects:!1,joinArrays:!1,returnedObjectHandler:!1,parseMissingKeyHandler:!1,appendNamespaceToMissingKey:!1,appendNamespaceToCIMode:!1,overloadTranslationOptionHandler:function(t){var n={};if(mr(t[1])==="object"&&(n=t[1]),typeof t[1]=="string"&&(n.defaultValue=t[1]),typeof t[2]=="string"&&(n.tDescription=t[2]),mr(t[2])==="object"||mr(t[3])==="object"){var r=t[3]||t[2];Object.keys(r).forEach(function(i){n[i]=r[i]})}return n},interpolation:{escapeValue:!0,format:function(t,n,r,i){return t},prefix:"{{",suffix:"}}",formatSeparator:",",unescapePrefix:"-",nestingPrefix:"$t(",nestingSuffix:")",nestingOptionsSeparator:",",maxReplaces:1e3,skipOnVariables:!0}}}function pR(e){return typeof e.ns=="string"&&(e.ns=[e.ns]),typeof e.fallbackLng=="string"&&(e.fallbackLng=[e.fallbackLng]),typeof e.fallbackNS=="string"&&(e.fallbackNS=[e.fallbackNS]),e.supportedLngs&&e.supportedLngs.indexOf("cimode")<0&&(e.supportedLngs=e.supportedLngs.concat(["cimode"])),e}function gR(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),n.push.apply(n,r)}return n}function Nr(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?gR(Object(n),!0).forEach(function(r){Er(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):gR(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function MH(e){var t=DH();return function(){var r=Kr(e),i;if(t){var o=Kr(this).constructor;i=Reflect.construct(r,arguments,o)}else i=r.apply(this,arguments);return tc(this,i)}}function DH(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}function Hc(){}function AH(e){var t=Object.getOwnPropertyNames(Object.getPrototypeOf(e));t.forEach(function(n){typeof e[n]=="function"&&(e[n]=e[n].bind(e))})}var of=function(e){Xf(n,e);var t=MH(n);function n(){var r,i=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},o=arguments.length>1?arguments[1]:void 0;if(tr(this,n),r=t.call(this),Zf&&so.call(eo(r)),r.options=pR(i),r.services={},r.logger=Ur,r.modules={external:[]},AH(eo(r)),o&&!r.isInitialized&&!i.isClone){if(!r.options.initImmediate)return r.init(i,o),tc(r,eo(r));setTimeout(function(){r.init(i,o)},0)}return r}return nr(n,[{key:"init",value:function(){var i=this,o=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},a=arguments.length>1?arguments[1]:void 0;typeof o=="function"&&(a=o,o={}),!o.defaultNS&&o.defaultNS!==!1&&o.ns&&(typeof o.ns=="string"?o.defaultNS=o.ns:o.ns.indexOf("translation")<0&&(o.defaultNS=o.ns[0]));var c=hR();this.options=Nr(Nr(Nr({},c),this.options),pR(o)),this.options.compatibilityAPI!=="v1"&&(this.options.interpolation=Nr(Nr({},c.interpolation),this.options.interpolation)),o.keySeparator!==void 0&&(this.options.userDefinedKeySeparator=o.keySeparator),o.nsSeparator!==void 0&&(this.options.userDefinedNsSeparator=o.nsSeparator);function f(u){return u?typeof u=="function"?new u:u:null}if(!this.options.isClone){this.modules.logger?Ur.init(f(this.modules.logger),this.options):Ur.init(null,this.options);var v;this.modules.formatter?v=this.modules.formatter:typeof Intl<"u"&&(v=IH);var s=new aR(this.options);this.store=new vH(this.options.resources,this.options);var g=this.services;g.logger=Ur,g.resourceStore=this.store,g.languageUtils=s,g.pluralResolver=new bH(s,{prepend:this.options.pluralSeparator,compatibilityJSON:this.options.compatibilityJSON,simplifyPluralSuffix:this.options.simplifyPluralSuffix}),v&&(!this.options.interpolation.format||this.options.interpolation.format===c.interpolation.format)&&(g.formatter=f(v),g.formatter.init(g,this.options),this.options.interpolation.format=g.formatter.format.bind(g.formatter)),g.interpolator=new TH(this.options),g.utils={hasLoadedNamespace:this.hasLoadedNamespace.bind(this)},g.backendConnector=new kH(f(this.modules.backend),g.resourceStore,g,this.options),g.backendConnector.on("*",function(u){for(var l=arguments.length,d=new Array(l>1?l-1:0),h=1;h<l;h++)d[h-1]=arguments[h];i.emit.apply(i,[u].concat(d))}),this.modules.languageDetector&&(g.languageDetector=f(this.modules.languageDetector),g.languageDetector.init&&g.languageDetector.init(g,this.options.detection,this.options)),this.modules.i18nFormat&&(g.i18nFormat=f(this.modules.i18nFormat),g.i18nFormat.init&&g.i18nFormat.init(this)),this.translator=new sR(this.services,this.options),this.translator.on("*",function(u){for(var l=arguments.length,d=new Array(l>1?l-1:0),h=1;h<l;h++)d[h-1]=arguments[h];i.emit.apply(i,[u].concat(d))}),this.modules.external.forEach(function(u){u.init&&u.init(i)})}if(this.format=this.options.interpolation.format,a||(a=Hc),this.options.fallbackLng&&!this.services.languageDetector&&!this.options.lng){var y=this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);y.length>0&&y[0]!=="dev"&&(this.options.lng=y[0])}!this.services.languageDetector&&!this.options.lng&&this.logger.warn("init: no languageDetector is used and no lng is defined");var S=["getResource","hasResourceBundle","getResourceBundle","getDataByLanguage"];S.forEach(function(u){i[u]=function(){var l;return(l=i.store)[u].apply(l,arguments)}});var m=["addResource","addResources","addResourceBundle","removeResourceBundle"];m.forEach(function(u){i[u]=function(){var l;return(l=i.store)[u].apply(l,arguments),i}});var p=Cl(),_=function(){var l=function(h,w){i.isInitialized&&!i.initializedStoreOnce&&i.logger.warn("init: i18next is already initialized. You should call init just once!"),i.isInitialized=!0,i.options.isClone||i.logger.log("initialized",i.options),i.emit("initialized",i.options),p.resolve(w),a(h,w)};if(i.languages&&i.options.compatibilityAPI!=="v1"&&!i.isInitialized)return l(null,i.t.bind(i));i.changeLanguage(i.options.lng,l)};return this.options.resources||!this.options.initImmediate?_():setTimeout(_,0),p}},{key:"loadResources",value:function(i){var o=this,a=arguments.length>1&&arguments[1]!==void 0?arguments[1]:Hc,c=a,f=typeof i=="string"?i:this.language;if(typeof i=="function"&&(c=i),!this.options.resources||this.options.partialBundledLanguages){if(f&&f.toLowerCase()==="cimode")return c();var v=[],s=function(S){if(S){var m=o.services.languageUtils.toResolveHierarchy(S);m.forEach(function(p){v.indexOf(p)<0&&v.push(p)})}};if(f)s(f);else{var g=this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);g.forEach(function(y){return s(y)})}this.options.preload&&this.options.preload.forEach(function(y){return s(y)}),this.services.backendConnector.load(v,this.options.ns,function(y){!y&&!o.resolvedLanguage&&o.language&&o.setResolvedLanguage(o.language),c(y)})}else c(null)}},{key:"reloadResources",value:function(i,o,a){var c=Cl();return i||(i=this.languages),o||(o=this.options.ns),a||(a=Hc),this.services.backendConnector.reload(i,o,function(f){c.resolve(),a(f)}),c}},{key:"use",value:function(i){if(!i)throw new Error("You are passing an undefined module! Please check the object you are passing to i18next.use()");if(!i.type)throw new Error("You are passing a wrong module! Please check the object you are passing to i18next.use()");return i.type==="backend"&&(this.modules.backend=i),(i.type==="logger"||i.log&&i.warn&&i.error)&&(this.modules.logger=i),i.type==="languageDetector"&&(this.modules.languageDetector=i),i.type==="i18nFormat"&&(this.modules.i18nFormat=i),i.type==="postProcessor"&&Ok.addPostProcessor(i),i.type==="formatter"&&(this.modules.formatter=i),i.type==="3rdParty"&&this.modules.external.push(i),this}},{key:"setResolvedLanguage",value:function(i){if(!(!i||!this.languages)&&!(["cimode","dev"].indexOf(i)>-1))for(var o=0;o<this.languages.length;o++){var a=this.languages[o];if(!(["cimode","dev"].indexOf(a)>-1)&&this.store.hasLanguageSomeTranslations(a)){this.resolvedLanguage=a;break}}}},{key:"changeLanguage",value:function(i,o){var a=this;this.isLanguageChangingTo=i;var c=Cl();this.emit("languageChanging",i);var f=function(y){a.language=y,a.languages=a.services.languageUtils.toResolveHierarchy(y),a.resolvedLanguage=void 0,a.setResolvedLanguage(y)},v=function(y,S){S?(f(S),a.translator.changeLanguage(S),a.isLanguageChangingTo=void 0,a.emit("languageChanged",S),a.logger.log("languageChanged",S)):a.isLanguageChangingTo=void 0,c.resolve(function(){return a.t.apply(a,arguments)}),o&&o(y,function(){return a.t.apply(a,arguments)})},s=function(y){!i&&!y&&a.services.languageDetector&&(y=[]);var S=typeof y=="string"?y:a.services.languageUtils.getBestMatchFromCodes(y);S&&(a.language||f(S),a.translator.language||a.translator.changeLanguage(S),a.services.languageDetector&&a.services.languageDetector.cacheUserLanguage&&a.services.languageDetector.cacheUserLanguage(S)),a.loadResources(S,function(m){v(m,S)})};return!i&&this.services.languageDetector&&!this.services.languageDetector.async?s(this.services.languageDetector.detect()):!i&&this.services.languageDetector&&this.services.languageDetector.async?this.services.languageDetector.detect.length===0?this.services.languageDetector.detect().then(s):this.services.languageDetector.detect(s):s(i),c}},{key:"getFixedT",value:function(i,o,a){var c=this,f=function v(s,g){var y;if(mr(g)!=="object"){for(var S=arguments.length,m=new Array(S>2?S-2:0),p=2;p<S;p++)m[p-2]=arguments[p];y=c.options.overloadTranslationOptionHandler([s,g].concat(m))}else y=Nr({},g);y.lng=y.lng||v.lng,y.lngs=y.lngs||v.lngs,y.ns=y.ns||v.ns,y.keyPrefix=y.keyPrefix||a||v.keyPrefix;var _=c.options.keySeparator||".",u;return y.keyPrefix&&Array.isArray(s)?u=s.map(function(l){return"".concat(y.keyPrefix).concat(_).concat(l)}):u=y.keyPrefix?"".concat(y.keyPrefix).concat(_).concat(s):s,c.t(u,y)};return typeof i=="string"?f.lng=i:f.lngs=i,f.ns=o,f.keyPrefix=a,f}},{key:"t",value:function(){var i;return this.translator&&(i=this.translator).translate.apply(i,arguments)}},{key:"exists",value:function(){var i;return this.translator&&(i=this.translator).exists.apply(i,arguments)}},{key:"setDefaultNamespace",value:function(i){this.options.defaultNS=i}},{key:"hasLoadedNamespace",value:function(i){var o=this,a=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(!this.isInitialized)return this.logger.warn("hasLoadedNamespace: i18next was not initialized",this.languages),!1;if(!this.languages||!this.languages.length)return this.logger.warn("hasLoadedNamespace: i18n.languages were undefined or empty",this.languages),!1;var c=this.resolvedLanguage||this.languages[0],f=this.options?this.options.fallbackLng:!1,v=this.languages[this.languages.length-1];if(c.toLowerCase()==="cimode")return!0;var s=function(S,m){var p=o.services.backendConnector.state["".concat(S,"|").concat(m)];return p===-1||p===2};if(a.precheck){var g=a.precheck(this,s);if(g!==void 0)return g}return!!(this.hasResourceBundle(c,i)||!this.services.backendConnector.backend||this.options.resources&&!this.options.partialBundledLanguages||s(c,i)&&(!f||s(v,i)))}},{key:"loadNamespaces",value:function(i,o){var a=this,c=Cl();return this.options.ns?(typeof i=="string"&&(i=[i]),i.forEach(function(f){a.options.ns.indexOf(f)<0&&a.options.ns.push(f)}),this.loadResources(function(f){c.resolve(),o&&o(f)}),c):(o&&o(),Promise.resolve())}},{key:"loadLanguages",value:function(i,o){var a=Cl();typeof i=="string"&&(i=[i]);var c=this.options.preload||[],f=i.filter(function(v){return c.indexOf(v)<0});return f.length?(this.options.preload=c.concat(f),this.loadResources(function(v){a.resolve(),o&&o(v)}),a):(o&&o(),Promise.resolve())}},{key:"dir",value:function(i){if(i||(i=this.resolvedLanguage||(this.languages&&this.languages.length>0?this.languages[0]:this.language)),!i)return"rtl";var o=["ar","shu","sqr","ssh","xaa","yhd","yud","aao","abh","abv","acm","acq","acw","acx","acy","adf","ads","aeb","aec","afb","ajp","apc","apd","arb","arq","ars","ary","arz","auz","avl","ayh","ayl","ayn","ayp","bbz","pga","he","iw","ps","pbt","pbu","pst","prp","prd","ug","ur","ydd","yds","yih","ji","yi","hbo","men","xmn","fa","jpr","peo","pes","prs","dv","sam","ckb"],a=this.services&&this.services.languageUtils||new aR(hR());return o.indexOf(a.getLanguagePartFromCode(i))>-1||i.toLowerCase().indexOf("-arab")>1?"rtl":"ltr"}},{key:"cloneInstance",value:function(){var i=this,o=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},a=arguments.length>1&&arguments[1]!==void 0?arguments[1]:Hc,c=Nr(Nr(Nr({},this.options),o),{isClone:!0}),f=new n(c);(o.debug!==void 0||o.prefix!==void 0)&&(f.logger=f.logger.clone(o));var v=["store","services","language"];return v.forEach(function(s){f[s]=i[s]}),f.services=Nr({},this.services),f.services.utils={hasLoadedNamespace:f.hasLoadedNamespace.bind(f)},f.translator=new sR(f.services,f.options),f.translator.on("*",function(s){for(var g=arguments.length,y=new Array(g>1?g-1:0),S=1;S<g;S++)y[S-1]=arguments[S];f.emit.apply(f,[s].concat(y))}),f.init(c,a),f.translator.options=f.options,f.translator.backendConnector.services.utils={hasLoadedNamespace:f.hasLoadedNamespace.bind(f)},f}},{key:"toJSON",value:function(){return{options:this.options,store:this.store,language:this.language,languages:this.languages,resolvedLanguage:this.resolvedLanguage}}}]),n}(so);Er(of,"createInstance",function(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},t=arguments.length>1?arguments[1]:void 0;return new of(e,t)});var vn=of.createInstance();vn.createInstance=of.createInstance;vn.createInstance;vn.dir;vn.init;vn.loadResources;vn.reloadResources;vn.use;vn.changeLanguage;vn.getFixedT;vn.t;vn.exists;vn.setDefaultNamespace;vn.hasLoadedNamespace;vn.loadNamespaces;vn.loadLanguages;function _m(e){return _m=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},_m(e)}var Pk=[],LH=Pk.forEach,NH=Pk.slice;function Sm(e){return LH.call(NH.call(arguments,1),function(t){if(t)for(var n in t)e[n]===void 0&&(e[n]=t[n])}),e}function kk(){return typeof XMLHttpRequest=="function"||(typeof XMLHttpRequest>"u"?"undefined":_m(XMLHttpRequest))==="object"}function xH(e){return!!e&&typeof e.then=="function"}function $H(e){return xH(e)?e:Promise.resolve(e)}function UH(e){throw new Error('Could not dynamically require "'+e+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var Tu={},BH={get exports(){return Tu},set exports(e){Tu=e}},Zl={},FH={get exports(){return Zl},set exports(e){Zl=e}},vR;function KH(){return vR||(vR=1,function(e,t){var n=typeof self<"u"?self:$e,r=function(){function o(){this.fetch=!1,this.DOMException=n.DOMException}return o.prototype=n,new o}();(function(o){(function(a){var c={searchParams:"URLSearchParams"in o,iterable:"Symbol"in o&&"iterator"in Symbol,blob:"FileReader"in o&&"Blob"in o&&function(){try{return new Blob,!0}catch{return!1}}(),formData:"FormData"in o,arrayBuffer:"ArrayBuffer"in o};function f(D){return D&&DataView.prototype.isPrototypeOf(D)}if(c.arrayBuffer)var v=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],s=ArrayBuffer.isView||function(D){return D&&v.indexOf(Object.prototype.toString.call(D))>-1};function g(D){if(typeof D!="string"&&(D=String(D)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(D))throw new TypeError("Invalid character in header field name");return D.toLowerCase()}function y(D){return typeof D!="string"&&(D=String(D)),D}function S(D){var x={next:function(){var z=D.shift();return{done:z===void 0,value:z}}};return c.iterable&&(x[Symbol.iterator]=function(){return x}),x}function m(D){this.map={},D instanceof m?D.forEach(function(x,z){this.append(z,x)},this):Array.isArray(D)?D.forEach(function(x){this.append(x[0],x[1])},this):D&&Object.getOwnPropertyNames(D).forEach(function(x){this.append(x,D[x])},this)}m.prototype.append=function(D,x){D=g(D),x=y(x);var z=this.map[D];this.map[D]=z?z+", "+x:x},m.prototype.delete=function(D){delete this.map[g(D)]},m.prototype.get=function(D){return D=g(D),this.has(D)?this.map[D]:null},m.prototype.has=function(D){return this.map.hasOwnProperty(g(D))},m.prototype.set=function(D,x){this.map[g(D)]=y(x)},m.prototype.forEach=function(D,x){for(var z in this.map)this.map.hasOwnProperty(z)&&D.call(x,this.map[z],z,this)},m.prototype.keys=function(){var D=[];return this.forEach(function(x,z){D.push(z)}),S(D)},m.prototype.values=function(){var D=[];return this.forEach(function(x){D.push(x)}),S(D)},m.prototype.entries=function(){var D=[];return this.forEach(function(x,z){D.push([z,x])}),S(D)},c.iterable&&(m.prototype[Symbol.iterator]=m.prototype.entries);function p(D){if(D.bodyUsed)return Promise.reject(new TypeError("Already read"));D.bodyUsed=!0}function _(D){return new Promise(function(x,z){D.onload=function(){x(D.result)},D.onerror=function(){z(D.error)}})}function u(D){var x=new FileReader,z=_(x);return x.readAsArrayBuffer(D),z}function l(D){var x=new FileReader,z=_(x);return x.readAsText(D),z}function d(D){for(var x=new Uint8Array(D),z=new Array(x.length),W=0;W<x.length;W++)z[W]=String.fromCharCode(x[W]);return z.join("")}function h(D){if(D.slice)return D.slice(0);var x=new Uint8Array(D.byteLength);return x.set(new Uint8Array(D)),x.buffer}function w(){return this.bodyUsed=!1,this._initBody=function(D){this._bodyInit=D,D?typeof D=="string"?this._bodyText=D:c.blob&&Blob.prototype.isPrototypeOf(D)?this._bodyBlob=D:c.formData&&FormData.prototype.isPrototypeOf(D)?this._bodyFormData=D:c.searchParams&&URLSearchParams.prototype.isPrototypeOf(D)?this._bodyText=D.toString():c.arrayBuffer&&c.blob&&f(D)?(this._bodyArrayBuffer=h(D.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):c.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(D)||s(D))?this._bodyArrayBuffer=h(D):this._bodyText=D=Object.prototype.toString.call(D):this._bodyText="",this.headers.get("content-type")||(typeof D=="string"?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):c.searchParams&&URLSearchParams.prototype.isPrototypeOf(D)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},c.blob&&(this.blob=function(){var D=p(this);if(D)return D;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){return this._bodyArrayBuffer?p(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(u)}),this.text=function(){var D=p(this);if(D)return D;if(this._bodyBlob)return l(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(d(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},c.formData&&(this.formData=function(){return this.text().then(M)}),this.json=function(){return this.text().then(JSON.parse)},this}var E=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];function I(D){var x=D.toUpperCase();return E.indexOf(x)>-1?x:D}function k(D,x){x=x||{};var z=x.body;if(D instanceof k){if(D.bodyUsed)throw new TypeError("Already read");this.url=D.url,this.credentials=D.credentials,x.headers||(this.headers=new m(D.headers)),this.method=D.method,this.mode=D.mode,this.signal=D.signal,!z&&D._bodyInit!=null&&(z=D._bodyInit,D.bodyUsed=!0)}else this.url=String(D);if(this.credentials=x.credentials||this.credentials||"same-origin",(x.headers||!this.headers)&&(this.headers=new m(x.headers)),this.method=I(x.method||this.method||"GET"),this.mode=x.mode||this.mode||null,this.signal=x.signal||this.signal,this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&z)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(z)}k.prototype.clone=function(){return new k(this,{body:this._bodyInit})};function M(D){var x=new FormData;return D.trim().split("&").forEach(function(z){if(z){var W=z.split("="),F=W.shift().replace(/\+/g," "),H=W.join("=").replace(/\+/g," ");x.append(decodeURIComponent(F),decodeURIComponent(H))}}),x}function L(D){var x=new m,z=D.replace(/\r?\n[\t ]+/g," ");return z.split(/\r?\n/).forEach(function(W){var F=W.split(":"),H=F.shift().trim();if(H){var R=F.join(":").trim();x.append(H,R)}}),x}w.call(k.prototype);function B(D,x){x||(x={}),this.type="default",this.status=x.status===void 0?200:x.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in x?x.statusText:"OK",this.headers=new m(x.headers),this.url=x.url||"",this._initBody(D)}w.call(B.prototype),B.prototype.clone=function(){return new B(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new m(this.headers),url:this.url})},B.error=function(){var D=new B(null,{status:0,statusText:""});return D.type="error",D};var N=[301,302,303,307,308];B.redirect=function(D,x){if(N.indexOf(x)===-1)throw new RangeError("Invalid status code");return new B(null,{status:x,headers:{location:D}})},a.DOMException=o.DOMException;try{new a.DOMException}catch{a.DOMException=function(x,z){this.message=x,this.name=z;var W=Error(x);this.stack=W.stack},a.DOMException.prototype=Object.create(Error.prototype),a.DOMException.prototype.constructor=a.DOMException}function G(D,x){return new Promise(function(z,W){var F=new k(D,x);if(F.signal&&F.signal.aborted)return W(new a.DOMException("Aborted","AbortError"));var H=new XMLHttpRequest;function R(){H.abort()}H.onload=function(){var P={status:H.status,statusText:H.statusText,headers:L(H.getAllResponseHeaders()||"")};P.url="responseURL"in H?H.responseURL:P.headers.get("X-Request-URL");var K="response"in H?H.response:H.responseText;z(new B(K,P))},H.onerror=function(){W(new TypeError("Network request failed"))},H.ontimeout=function(){W(new TypeError("Network request failed"))},H.onabort=function(){W(new a.DOMException("Aborted","AbortError"))},H.open(F.method,F.url,!0),F.credentials==="include"?H.withCredentials=!0:F.credentials==="omit"&&(H.withCredentials=!1),"responseType"in H&&c.blob&&(H.responseType="blob"),F.headers.forEach(function(P,K){H.setRequestHeader(K,P)}),F.signal&&(F.signal.addEventListener("abort",R),H.onreadystatechange=function(){H.readyState===4&&F.signal.removeEventListener("abort",R)}),H.send(typeof F._bodyInit>"u"?null:F._bodyInit)})}return G.polyfill=!0,o.fetch||(o.fetch=G,o.Headers=m,o.Request=k,o.Response=B),a.Headers=m,a.Request=k,a.Response=B,a.fetch=G,Object.defineProperty(a,"__esModule",{value:!0}),a})({})})(r),r.fetch.ponyfill=!0,delete r.fetch.polyfill;var i=r;t=i.fetch,t.default=i.fetch,t.fetch=i.fetch,t.Headers=i.Headers,t.Request=i.Request,t.Response=i.Response,e.exports=t}(FH,Zl)),Zl}(function(e,t){var n;if(typeof fetch=="function"&&(typeof $e<"u"&&$e.fetch?n=$e.fetch:typeof window<"u"&&window.fetch?n=window.fetch:n=fetch),typeof UH<"u"&&(typeof window>"u"||typeof window.document>"u")){var r=n||KH();r.default&&(r=r.default),t.default=r,e.exports=t.default}})(BH,Tu);const Mk=Tu,mR=RR({__proto__:null,default:Mk},[Tu]);function sf(e){return sf=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},sf(e)}var ri;typeof fetch=="function"&&(typeof global<"u"&&global.fetch?ri=global.fetch:typeof window<"u"&&window.fetch?ri=window.fetch:ri=fetch);var Ru;kk()&&(typeof global<"u"&&global.XMLHttpRequest?Ru=global.XMLHttpRequest:typeof window<"u"&&window.XMLHttpRequest&&(Ru=window.XMLHttpRequest));var af;typeof ActiveXObject=="function"&&(typeof global<"u"&&global.ActiveXObject?af=global.ActiveXObject:typeof window<"u"&&window.ActiveXObject&&(af=window.ActiveXObject));!ri&&mR&&!Ru&&!af&&(ri=Mk||mR);typeof ri!="function"&&(ri=void 0);var Em=function(t,n){if(n&&sf(n)==="object"){var r="";for(var i in n)r+="&"+encodeURIComponent(i)+"="+encodeURIComponent(n[i]);if(!r)return t;t=t+(t.indexOf("?")!==-1?"&":"?")+r.slice(1)}return t},yR=function(t,n,r){ri(t,n).then(function(i){if(!i.ok)return r(i.statusText||"Error",{status:i.status});i.text().then(function(o){r(null,{status:i.status,data:o})}).catch(r)}).catch(r)},_R=!1,jH=function(t,n,r,i){t.queryStringParams&&(n=Em(n,t.queryStringParams));var o=Sm({},typeof t.customHeaders=="function"?t.customHeaders():t.customHeaders);r&&(o["Content-Type"]="application/json");var a=typeof t.requestOptions=="function"?t.requestOptions(r):t.requestOptions,c=Sm({method:r?"POST":"GET",body:r?t.stringify(r):void 0,headers:o},_R?{}:a);try{yR(n,c,i)}catch(f){if(!a||Object.keys(a).length===0||!f.message||f.message.indexOf("not implemented")<0)return i(f);try{Object.keys(a).forEach(function(v){delete c[v]}),yR(n,c,i),_R=!0}catch(v){i(v)}}},qH=function(t,n,r,i){r&&sf(r)==="object"&&(r=Em("",r).slice(1)),t.queryStringParams&&(n=Em(n,t.queryStringParams));try{var o;Ru?o=new Ru:o=new af("MSXML2.XMLHTTP.3.0"),o.open(r?"POST":"GET",n,1),t.crossDomain||o.setRequestHeader("X-Requested-With","XMLHttpRequest"),o.withCredentials=!!t.withCredentials,r&&o.setRequestHeader("Content-Type","application/x-www-form-urlencoded"),o.overrideMimeType&&o.overrideMimeType("application/json");var a=t.customHeaders;if(a=typeof a=="function"?a():a,a)for(var c in a)o.setRequestHeader(c,a[c]);o.onreadystatechange=function(){o.readyState>3&&i(o.status>=400?o.statusText:null,{status:o.status,data:o.responseText})},o.send(r)}catch(f){console&&console.log(f)}},VH=function(t,n,r,i){if(typeof r=="function"&&(i=r,r=void 0),i=i||function(){},ri&&n.indexOf("file:")!==0)return jH(t,n,r,i);if(kk()||typeof ActiveXObject=="function")return qH(t,n,r,i);i(new Error("No fetch and no xhr implementation found!"))};function Iu(e){return Iu=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Iu(e)}function WH(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function SR(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,Dk(r.key),r)}}function HH(e,t,n){return t&&SR(e.prototype,t),n&&SR(e,n),Object.defineProperty(e,"prototype",{writable:!1}),e}function GH(e,t,n){return t=Dk(t),t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Dk(e){var t=zH(e,"string");return Iu(t)==="symbol"?t:String(t)}function zH(e,t){if(Iu(e)!=="object"||e===null)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||"default");if(Iu(r)!=="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var YH=function(){return{loadPath:"/locales/{{lng}}/{{ns}}.json",addPath:"/locales/add/{{lng}}/{{ns}}",allowMultiLoading:!1,parse:function(n){return JSON.parse(n)},stringify:JSON.stringify,parsePayload:function(n,r,i){return GH({},r,i||"")},request:VH,reloadInterval:typeof window<"u"?!1:60*60*1e3,customHeaders:{},queryStringParams:{},crossDomain:!1,withCredentials:!1,overrideMimeType:!1,requestOptions:{mode:"cors",credentials:"same-origin",cache:"default"}}},QH=function(){function e(t){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};WH(this,e),this.services=t,this.options=n,this.allOptions=r,this.type="backend",this.init(t,n,r)}return HH(e,[{key:"init",value:function(n){var r=this,i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};this.services=n,this.options=Sm(i,this.options||{},YH()),this.allOptions=o,this.services&&this.options.reloadInterval&&setInterval(function(){return r.reload()},this.options.reloadInterval)}},{key:"readMulti",value:function(n,r,i){this._readAny(n,n,r,r,i)}},{key:"read",value:function(n,r,i){this._readAny([n],n,[r],r,i)}},{key:"_readAny",value:function(n,r,i,o,a){var c=this,f=this.options.loadPath;typeof this.options.loadPath=="function"&&(f=this.options.loadPath(n,i)),f=$H(f),f.then(function(v){if(!v)return a(null,{});var s=c.services.interpolator.interpolate(v,{lng:n.join("+"),ns:i.join("+")});c.loadUrl(s,a,r,o)})}},{key:"loadUrl",value:function(n,r,i,o){var a=this;this.options.request(this.options,n,void 0,function(c,f){if(f&&(f.status>=500&&f.status<600||!f.status))return r("failed loading "+n+"; status code: "+f.status,!0);if(f&&f.status>=400&&f.status<500)return r("failed loading "+n+"; status code: "+f.status,!1);if(!f&&c&&c.message&&c.message.indexOf("Failed to fetch")>-1)return r("failed loading "+n+": "+c.message,!0);if(c)return r(c,!1);var v,s;try{typeof f.data=="string"?v=a.options.parse(f.data,i,o):v=f.data}catch{s="failed parsing "+n+" to json"}if(s)return r(s,!1);r(null,v)})}},{key:"create",value:function(n,r,i,o,a){var c=this;if(this.options.addPath){typeof n=="string"&&(n=[n]);var f=this.options.parsePayload(r,i,o),v=0,s=[],g=[];n.forEach(function(y){var S=c.options.addPath;typeof c.options.addPath=="function"&&(S=c.options.addPath(y,r));var m=c.services.interpolator.interpolate(S,{lng:y,ns:r});c.options.request(c.options,m,f,function(p,_){v+=1,s.push(p),g.push(_),v===n.length&&typeof a=="function"&&a(s,g)})})}}},{key:"reload",value:function(){var n=this,r=this.services,i=r.backendConnector,o=r.languageUtils,a=r.logger,c=i.language;if(!(c&&c.toLowerCase()==="cimode")){var f=[],v=function(g){var y=o.toResolveHierarchy(g);y.forEach(function(S){f.indexOf(S)<0&&f.push(S)})};v(c),this.allOptions.preload&&this.allOptions.preload.forEach(function(s){return v(s)}),f.forEach(function(s){n.allOptions.ns.forEach(function(g){i.read(s,g,"read",null,null,function(y,S){y&&a.warn("loading namespace ".concat(g," for language ").concat(s," failed"),y),!y&&S&&a.log("loaded namespace ".concat(g," for language ").concat(s),S),i.loaded("".concat(s,"|").concat(g),y,S)})})})}}}]),e}();QH.type="backend";var Ak=[],JH=Ak.forEach,XH=Ak.slice;function ZH(e){return JH.call(XH.call(arguments,1),function(t){if(t)for(var n in t)e[n]===void 0&&(e[n]=t[n])}),e}var ER=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/,eG=function(t,n,r){var i=r||{};i.path=i.path||"/";var o=encodeURIComponent(n),a="".concat(t,"=").concat(o);if(i.maxAge>0){var c=i.maxAge-0;if(Number.isNaN(c))throw new Error("maxAge should be a Number");a+="; Max-Age=".concat(Math.floor(c))}if(i.domain){if(!ER.test(i.domain))throw new TypeError("option domain is invalid");a+="; Domain=".concat(i.domain)}if(i.path){if(!ER.test(i.path))throw new TypeError("option path is invalid");a+="; Path=".concat(i.path)}if(i.expires){if(typeof i.expires.toUTCString!="function")throw new TypeError("option expires is invalid");a+="; Expires=".concat(i.expires.toUTCString())}if(i.httpOnly&&(a+="; HttpOnly"),i.secure&&(a+="; Secure"),i.sameSite){var f=typeof i.sameSite=="string"?i.sameSite.toLowerCase():i.sameSite;switch(f){case!0:a+="; SameSite=Strict";break;case"lax":a+="; SameSite=Lax";break;case"strict":a+="; SameSite=Strict";break;case"none":a+="; SameSite=None";break;default:throw new TypeError("option sameSite is invalid")}}return a},wR={create:function(t,n,r,i){var o=arguments.length>4&&arguments[4]!==void 0?arguments[4]:{path:"/",sameSite:"strict"};r&&(o.expires=new Date,o.expires.setTime(o.expires.getTime()+r*60*1e3)),i&&(o.domain=i),document.cookie=eG(t,encodeURIComponent(n),o)},read:function(t){for(var n="".concat(t,"="),r=document.cookie.split(";"),i=0;i<r.length;i++){for(var o=r[i];o.charAt(0)===" ";)o=o.substring(1,o.length);if(o.indexOf(n)===0)return o.substring(n.length,o.length)}return null},remove:function(t){this.create(t,"",-1)}},tG={name:"cookie",lookup:function(t){var n;if(t.lookupCookie&&typeof document<"u"){var r=wR.read(t.lookupCookie);r&&(n=r)}return n},cacheUserLanguage:function(t,n){n.lookupCookie&&typeof document<"u"&&wR.create(n.lookupCookie,t,n.cookieMinutes,n.cookieDomain,n.cookieOptions)}},nG={name:"querystring",lookup:function(t){var n;if(typeof window<"u"){var r=window.location.search;!window.location.search&&window.location.hash&&window.location.hash.indexOf("?")>-1&&(r=window.location.hash.substring(window.location.hash.indexOf("?")));for(var i=r.substring(1),o=i.split("&"),a=0;a<o.length;a++){var c=o[a].indexOf("=");if(c>0){var f=o[a].substring(0,c);f===t.lookupQuerystring&&(n=o[a].substring(c+1))}}}return n}},Ol=null,bR=function(){if(Ol!==null)return Ol;try{Ol=window!=="undefined"&&window.localStorage!==null;var t="i18next.translate.boo";window.localStorage.setItem(t,"foo"),window.localStorage.removeItem(t)}catch{Ol=!1}return Ol},rG={name:"localStorage",lookup:function(t){var n;if(t.lookupLocalStorage&&bR()){var r=window.localStorage.getItem(t.lookupLocalStorage);r&&(n=r)}return n},cacheUserLanguage:function(t,n){n.lookupLocalStorage&&bR()&&window.localStorage.setItem(n.lookupLocalStorage,t)}},Pl=null,TR=function(){if(Pl!==null)return Pl;try{Pl=window!=="undefined"&&window.sessionStorage!==null;var t="i18next.translate.boo";window.sessionStorage.setItem(t,"foo"),window.sessionStorage.removeItem(t)}catch{Pl=!1}return Pl},iG={name:"sessionStorage",lookup:function(t){var n;if(t.lookupSessionStorage&&TR()){var r=window.sessionStorage.getItem(t.lookupSessionStorage);r&&(n=r)}return n},cacheUserLanguage:function(t,n){n.lookupSessionStorage&&TR()&&window.sessionStorage.setItem(n.lookupSessionStorage,t)}},oG={name:"navigator",lookup:function(t){var n=[];if(typeof navigator<"u"){if(navigator.languages)for(var r=0;r<navigator.languages.length;r++)n.push(navigator.languages[r]);navigator.userLanguage&&n.push(navigator.userLanguage),navigator.language&&n.push(navigator.language)}return n.length>0?n:void 0}},sG={name:"htmlTag",lookup:function(t){var n,r=t.htmlTag||(typeof document<"u"?document.documentElement:null);return r&&typeof r.getAttribute=="function"&&(n=r.getAttribute("lang")),n}},aG={name:"path",lookup:function(t){var n;if(typeof window<"u"){var r=window.location.pathname.match(/\/([a-zA-Z-]*)/g);if(r instanceof Array)if(typeof t.lookupFromPathIndex=="number"){if(typeof r[t.lookupFromPathIndex]!="string")return;n=r[t.lookupFromPathIndex].replace("/","")}else n=r[0].replace("/","")}return n}},lG={name:"subdomain",lookup:function(t){var n=typeof t.lookupFromSubdomainIndex=="number"?t.lookupFromSubdomainIndex+1:1,r=typeof window<"u"&&window.location&&window.location.hostname&&window.location.hostname.match(/^(\w{2,5})\.(([a-z0-9-]{1,63}\.[a-z]{2,6})|localhost)/i);if(r)return r[n]}};function uG(){return{order:["querystring","cookie","localStorage","sessionStorage","navigator","htmlTag"],lookupQuerystring:"lng",lookupCookie:"i18next",lookupLocalStorage:"i18nextLng",lookupSessionStorage:"i18nextLng",caches:["localStorage"],excludeCacheFor:["cimode"]}}var cG=function(){function e(t){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};tr(this,e),this.type="languageDetector",this.detectors={},this.init(t,n)}return nr(e,[{key:"init",value:function(n){var r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};this.services=n,this.options=ZH(r,this.options||{},uG()),this.options.lookupFromUrlIndex&&(this.options.lookupFromPathIndex=this.options.lookupFromUrlIndex),this.i18nOptions=i,this.addDetector(tG),this.addDetector(nG),this.addDetector(rG),this.addDetector(iG),this.addDetector(oG),this.addDetector(sG),this.addDetector(aG),this.addDetector(lG)}},{key:"addDetector",value:function(n){this.detectors[n.name]=n}},{key:"detect",value:function(n){var r=this;n||(n=this.options.order);var i=[];return n.forEach(function(o){if(r.detectors[o]){var a=r.detectors[o].lookup(r.options);a&&typeof a=="string"&&(a=[a]),a&&(i=i.concat(a))}}),this.services.languageUtils.getBestMatchFromCodes?i:i.length>0?i[0]:null}},{key:"cacheUserLanguage",value:function(n,r){var i=this;r||(r=this.options.caches),r&&(this.options.excludeCacheFor&&this.options.excludeCacheFor.indexOf(n)>-1||r.forEach(function(o){i.detectors[o]&&i.detectors[o].cacheUserLanguage(n,i.options)}))}}]),e}();cG.type="languageDetector";export{mG as B,pG as L,NG as M,UG as O,yG as P,fG as R,o3 as a,$K as b,iA as c,$G as d,QH as e,cG as f,gG as g,__ as h,vn as i,ia as j,Xk as k,Fu as l,hG as m,z1 as n,xG as o,dG as p,Oe as r,vG as u};
     93 //# sourceMappingURL=vendor-95a06cbd.js.map